|
| 1 | +/* === Types === */ |
| 2 | +/* === Internal === */ |
| 3 | +// hold the currently active effect |
| 4 | +let active; |
| 5 | +/* === Exported functions === */ |
| 6 | +/** |
| 7 | + * Check if a given variable is a function |
| 8 | + * |
| 9 | + * @param {unknown} fn - variable to check if it is a function |
| 10 | + * @returns {boolean} true if supplied parameter is a function |
| 11 | + */ |
| 12 | +const isFunction = (fn) => typeof fn === 'function'; |
| 13 | +/** |
| 14 | + * Check if a given variable is a reactive state |
| 15 | + * |
| 16 | + * @param {unknown} value - variable to check if it is a reactive state |
| 17 | + * @returns {boolean} true if supplied parameter is a reactive state |
| 18 | + */ |
| 19 | +const isState = (value) => isFunction(value) && isFunction(value.set); |
| 20 | +/** |
| 21 | + * Define a reactive state |
| 22 | + * |
| 23 | + * @since 0.1.0 |
| 24 | + * @param {unknown} value - initial value of the state; may be a function for derived state |
| 25 | + * @returns {UIState} getter function for the current value with a `set` method to update the value |
| 26 | + */ |
| 27 | +const cause = (value) => { |
| 28 | + const state = () => { |
| 29 | + active && state.effects.add(active); |
| 30 | + return value; |
| 31 | + }; |
| 32 | + state.effects = new Set(); // set of listeners |
| 33 | + state.set = (updater) => { |
| 34 | + const old = value; |
| 35 | + value = isFunction(updater) && !isState(updater) |
| 36 | + ? updater(old) |
| 37 | + : updater; |
| 38 | + if (!Object.is(value, old)) { |
| 39 | + for (const effect of state.effects) |
| 40 | + effect(); |
| 41 | + } |
| 42 | + }; |
| 43 | + return state; |
| 44 | +}; |
| 45 | +/** |
| 46 | + * Create a derived state from an existing state |
| 47 | + * |
| 48 | + * @since 0.1.0 |
| 49 | + * @param {() => unknown} fn - existing state to derive from |
| 50 | + * @returns {() => unknown} derived state |
| 51 | + */ |
| 52 | +const derive = (fn) => fn; |
| 53 | +/** |
| 54 | + * Define what happens when a reactive state changes |
| 55 | + * |
| 56 | + * @since 0.1.0 |
| 57 | + * @param {UIEffectCallback} fn - callback function to be executed when a state changes |
| 58 | + */ |
| 59 | +const effect = (fn) => { |
| 60 | + const targets = new Map(); |
| 61 | + const next = () => { |
| 62 | + const prev = active; |
| 63 | + active = next; |
| 64 | + const cleanup = fn((element, domFn) => { |
| 65 | + !targets.has(element) && targets.set(element, new Set()); |
| 66 | + targets.get(element).add(domFn); |
| 67 | + }); |
| 68 | + active = prev; |
| 69 | + queueMicrotask(() => { |
| 70 | + for (const domFns of targets.values()) { |
| 71 | + for (const domFn of domFns) |
| 72 | + domFn(); |
| 73 | + } |
| 74 | + isFunction(cleanup) && cleanup(); |
| 75 | + }); |
| 76 | + }; |
| 77 | + next.targets = targets; |
| 78 | + next(); |
| 79 | +}; |
| 80 | + |
| 81 | +export { cause, derive, effect, isFunction, isState }; |
0 commit comments