@chasemoskal/magical
Version:
web toolkit for lit apps
41 lines • 1.5 kB
JavaScript
export const setupUseObjectForElement = ({ addSetup, rerender, getRenderCount, incrementStateCount, }) => {
const stateMap = new Map();
return {
setup: initializer => {
if (getRenderCount() === 0)
addSetup(initializer);
},
state: initial => {
const count = incrementStateCount();
const alreadySet = stateMap.has(count);
let currentValue;
let previousValue;
if (alreadySet)
[currentValue, previousValue] = stateMap.get(count) ?? [];
else
stateMap.set(count, [
currentValue =
(typeof initial === "function")
? initial()
: initial,
undefined,
]);
const setter = valueOrFunction => {
const previousValue = getter();
const newValue = (typeof valueOrFunction === "function")
? valueOrFunction(previousValue)
: valueOrFunction;
stateMap.set(count, [newValue, previousValue]);
rerender();
};
const getter = () => (stateMap.get(count) ?? [])[0];
return [
currentValue,
setter,
getter,
previousValue,
];
},
};
};
//# sourceMappingURL=setup-use-object-for-element.js.map