Skip to content

Commit

Permalink
Save settings in localStorage
Browse files Browse the repository at this point in the history
  • Loading branch information
lydell committed Aug 4, 2023
1 parent cf662ca commit e9d84b0
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,10 @@ <h1>

<fieldset>
<div class="radio-group">
<label><input type="radio" name="indent" checked /> spaces</label>
<label
><input type="radio" name="indent" id="spaces" checked />
spaces</label
>
<label><input type="radio" name="indent" id="tabs" /> tabs</label>
</div>
<label
Expand Down Expand Up @@ -169,6 +172,19 @@ <h1>
<script type="module">
import stringify from "./index.js";

const localStorageKey = "settings";

try {
const settings = JSON.parse(localStorage.getItem(localStorageKey));
if (settings.tabs) {
tabs.checked = true;
} else {
spaces.checked = true;
}
indent.value = settings.indent;
maxLength.value = settings.maxLength;
} catch {}

const update = () => {
try {
output.value = stringify(JSON.parse(input.value), {
Expand All @@ -179,9 +195,31 @@ <h1>
} catch (error) {
output.value = error.message;
}
try {
localStorage.setItem(
localStorageKey,
JSON.stringify({
tabs: tabs.checked,
indent: indent.valueAsNumber,
maxLength: maxLength.valueAsNumber,
})
);
} catch {}
};

const normalize = () => {
if (!Number.isFinite(indent.valueAsNumber)) {
indent.value = 2;
}
if (!Number.isFinite(maxLength.valueAsNumber)) {
maxLength.value = 80;
}
update();
};

form.oninput = update;
indent.onblur = normalize;
maxLength.onblur = normalize;

output.onfocus = () => {
// The timeout is needed in Safari.
Expand Down Expand Up @@ -240,7 +278,7 @@ <h1>
};

input.value = JSON.stringify(example, null, 2);
update();
normalize();
</script>
</body>
</html>

0 comments on commit e9d84b0

Please sign in to comment.