svelte-ux
Version:
- Increment version in `package.json` and commit as `Version bump to x.y.z` - `npm run publish`
49 lines (48 loc) • 2.15 kB
JavaScript
import { writable } from 'svelte/store';
import { isFunction } from 'lodash-es';
import { decode, encode } from '../utils/json';
import { expireObject } from '../utils/object';
import { browser } from '../utils/env';
function localStore(key, initialValue, options) {
var _a;
let value = initialValue;
let previousExpiry = null;
if ((options === null || options === void 0 ? void 0 : options.override) != null) {
value = options === null || options === void 0 ? void 0 : options.override;
}
else {
const storedValue = browser ? localStorage.getItem(key) : null;
if (storedValue !== null) {
const decodedValue = decode(storedValue);
if (options === null || options === void 0 ? void 0 : options.expiry) {
// TODO: if object returned, merge with initialValue (sub-properties)?
value = (_a = expireObject(decodedValue.value, decodedValue.expiry)) !== null && _a !== void 0 ? _a : initialValue;
previousExpiry = decodedValue.expiry;
}
else {
value = decodedValue;
}
}
}
const store = writable(value);
if (browser) {
store.subscribe((val) => {
if (options === null || options === void 0 ? void 0 : options.expiry) {
// Remove all expired expiry
const prunedPreviousExpiry = previousExpiry
? expireObject(previousExpiry, previousExpiry)
: previousExpiry;
const expiry = isFunction(options === null || options === void 0 ? void 0 : options.expiry)
? options === null || options === void 0 ? void 0 : options.expiry(prunedPreviousExpiry) // Update expiry on write
: options === null || options === void 0 ? void 0 : options.expiry;
previousExpiry = expiry;
localStorage.setItem(key, encode({ value: val, expiry }));
}
else {
localStorage.setItem(key, encode(val));
}
});
}
return store;
}
export default localStore;