@ljcl/storybook-addon-cssprops
Version:
Interact with css custom properties dynamically in the Storybook UI
63 lines (62 loc) • 2.51 kB
JavaScript
import { useState, useCallback, useEffect } from "react";
import { useWindowEvent } from "./useWindowEvent";
function serializeJSON(value) {
try {
return JSON.stringify(value);
}
catch (error) {
throw new Error("[storybook-addon-cssprops]: Failed to serialize the value");
}
}
function deserializeJSON(value) {
try {
return JSON.parse(value);
}
catch (_a) {
return value;
}
}
export function useLocalStorage(_a) {
var _b;
var key = _a.key, defaultValue = _a.defaultValue, _c = _a.getInitialValueInEffect, getInitialValueInEffect = _c === void 0 ? false : _c, _d = _a.deserialize, deserialize = _d === void 0 ? deserializeJSON : _d, _e = _a.serialize, serialize = _e === void 0 ? serializeJSON : _e;
var _f = useState(typeof window !== "undefined" &&
"localStorage" in window &&
!getInitialValueInEffect
? deserialize((_b = window.localStorage.getItem(key)) !== null && _b !== void 0 ? _b : undefined)
: (defaultValue !== null && defaultValue !== void 0 ? defaultValue : "")), value = _f[0], setValue = _f[1];
var setLocalStorageValue = useCallback(function (val) {
if (val instanceof Function) {
setValue(function (current) {
var result = val(current);
window.localStorage.setItem(key, serialize(result));
return result;
});
}
else {
window.localStorage.setItem(key, serialize(val));
setValue(val);
}
}, [key, serialize]);
useWindowEvent("storage", function (event) {
var _a;
if (event.storageArea === window.localStorage && event.key === key) {
setValue(deserialize((_a = event.newValue) !== null && _a !== void 0 ? _a : undefined));
}
});
useEffect(function () {
if (defaultValue !== undefined && value === undefined) {
setLocalStorageValue(defaultValue);
}
}, [defaultValue, value, setLocalStorageValue]);
useEffect(function () {
var _a;
if (getInitialValueInEffect) {
setValue(deserialize((_a = window.localStorage.getItem(key)) !== null && _a !== void 0 ? _a : undefined) ||
(defaultValue !== null && defaultValue !== void 0 ? defaultValue : ""));
}
}, [defaultValue, deserialize, getInitialValueInEffect, key]);
return [
value === undefined ? defaultValue : value,
setLocalStorageValue,
];
}