Store user preferences in and retrieve them from the browser localStorage.
preferences.js is currently loaded in the global scope using <script> tags.
This allows for easy local development without a web server. Modern web browsers
typically disallow module loading behavior in documents loaded from the
filesystem. Module-loading behavior is being pondered.
<script src="<preferences.js location>"></script>
<script>
const preferences = getOrCreatePreferences({
storageKey: storageKey,
schema: schema
});
</script>preferences.js uses destructuring syntax for configuration. Three key-value pairs are accepted:
storageKey: stringthe key to use when accessing localStorage.schema: objecta key-value pair where the key is the preference name, and the value is the JavaScript data type of the preference as would be returned bytypeof. Currently"boolean","number", and"string"are supported.createOnError: booleanwhether or not to create an empty JSON string record if a JSON-unserializable value is returned from localStorage for the provided storage key.
const preferences = getOrCreatePreferences({
storageKey: "storageKey",
schema: {
booleanPreference: "boolean",
numberPreference: "number",
stringPreference: "string",
},
createOnError: true
})Assuming that preferences has already been instantiated using a schema that
defines a preference named booleanPreference:
preferences.booleanPreference = true;Assuming that preferences has already been instantiated using a schema that
defines a preference named booleanPreference, and that booleanPreference has
been previously set to true:
// Logs `true`
console.log(preferences.booleanPreference);Remote databases aren't always necessary, and even when they're necessary, all of the data isn't always needed. Mostly this is just a fun excuse to work with localStorage.
preferences.js can currently be used for per-user settings by specifying unique storage keys per user, or even unique preference keys per user. However, this makes it possible for user preferences to be read by anybody with access to the browser. Ideally there is some way to conveniently encrypt user settings.
preferences.js should offer a feature to automatically generate a form that can be used to manage preferences based on the provided schema.
Currently, createOnError doesn't do anything other than check if the
localStorage value for a given storageKey is JSON serializable before
manipulating it. This could lead to errors or other undesirable outcomes. If
there is pre-existing data for the provided storageKey in an array format,
preferences.js may misbehave. If there is pre-existing data in a format
preferences.js behaves with, the user may malform that existing data.
Ideally, preferences.js should check the data for a desired key-value pair before manipulating existing data, or perform some other sanity-check to determine that existing data is safe to manipualte.