Public
Edited
May 31, 2023
Importers
Insert cell
Insert cell
import { localStorage } from "@mbostock/safe-local-storage"
Insert cell
DEFAULTS_APPLIED = Symbol('Whether defaults have been applied to an input in a form');
Insert cell
fromState = (keyName, inputMap, defaults = {}) => {
let storageDefaults;
Object.entries(inputMap).forEach(([key, input]) => {
if (!input[DEFAULTS_APPLIED]) {
if (!storageDefaults) {
storageDefaults = JSON.parse(localStorage.getItem(keyName) || "{}");
}
const defaultValue = storageDefaults[key] || defaults[key];
if (defaultValue) {
input.value = defaultValue;
}
input[DEFAULTS_APPLIED] = true;
}
});
return inputMap;
}
Insert cell
formWithLocalStorage = (keyName, inputMap, defaults = {}, options = {}) => {
fromState(keyName, inputMap, defaults);

const { mode = 'oninput', ...formOptions } = options;
const form = Inputs.form(inputMap, formOptions);

form[mode] = function () {
const result = {};
for (const [key, elt] of Object.entries(inputMap)) {
result[key] = elt.value;
}
localStorage.setItem(keyName, JSON.stringify(result));
};
return form;
}
Insert cell
Insert cell
inputs = ({
testField: Inputs.textarea({ rows: 10, label: 'System Prompt' }),
})
Insert cell
viewof form = formWithLocalStorage('test-local-storage', inputs, { testField: 'This is the in-doc default' }, { mode: 'onchange' })
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more