generated from shgysk8zer0/npm-template
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate.js
667 lines (598 loc) · 23.2 KB
/
state.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
const stateRegistry = new Map();
const channel = new BroadcastChannel('aegis:state_sync');
const sender = crypto.randomUUID();
const proxySymbol = Symbol('proxy');
const updateSymbol = Symbol('aegis:state:update');
let isChannelOpen = true;
export const EVENT_TARGET = new EventTarget();
export const stateKey = 'aegisStateKey';
export const stateAttr = 'aegisStateAttr';
export const stateStyle = 'aegisStateStyle';
export const stateProperty = 'aegisStateProperty';
export const stateKeyAttribute = 'data-aegis-state-key';
export const stateAttrAttribute = 'data-aegis-state-attr';
export const statePropertyAttr = 'data-aegis-state-property';
export const stateStyleAttribute = 'data-aegis-state-style';
export const changeEvent = 'change';
export const beforeChangeEvent = 'beforechange';
const _getState = (key, fallback = null) => history.state?.[key] ?? fallback;
function $$(selector, base = document.documentElement) {
const results = base.querySelectorAll(selector);
return base.matches(selector) ? [base, ...results] : Array.from(results);
}
async function _updateElement({ state = history.state ?? {} } = {}) {
const key = this.dataset.aegisStateKey;
const val = state?.[key];
await scheduler?.yield();
if (typeof this.dataset[stateAttr] === 'string') {
const attr = this.dataset[stateAttr];
const oldVal = this.getAttribute(attr);
if (typeof oldVal === 'string' && oldVal.startsWith('blob:')) {
URL.revokeObjectURL(oldVal);
}
if (typeof val === 'boolean') {
this.toggleAttribute(attr, val);
} else if (val === null || val === undefined) {
this.removeAttribute(attr);
} else if (val instanceof Blob) {
this.setAttribute(attr, URL.createObjectURL(val));
} else {
this.setAttribute(attr, val);
}
} else if (typeof this.dataset[stateProperty] === 'string' && this.dataset[stateProperty] !== 'innerHTML') {
this[this.dataset[stateProperty]] = val;
} else if (typeof this.dataset[stateStyle] === 'string') {
if (typeof val === 'undefined' || val === null || val === false) {
this.style.removeProperty(this.dataset[stateStyle]);
} else {
this.style.setProperty(this.dataset[stateStyle], val);
}
} else if (this instanceof HTMLInputElement || this instanceof HTMLSelectElement || this instanceof HTMLTextAreaElement) {
this.value = val;
} else {
this.textContent = val;
}
}
const domObserver = new MutationObserver(mutations => {
mutations.forEach(record => {
switch(record.type) {
case 'childList':
record.addedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
$$(`[${stateKeyAttribute}]`, node.target).forEach(el => {
el[updateSymbol] = _updateElement.bind(el);
observeStateChanges(el[updateSymbol], el.dataset[stateKey]);
});
}
});
record.removedNodes.forEach(node => {
if (node.nodeType === Node.ELEMENT_NODE) {
$$(`[${stateKeyAttribute}]`, node.target).forEach(el => {
unobserveStateChanges(el[updateSymbol]);
delete el[updateSymbol];
});
}
});
break;
case 'attributes':
if (typeof record.oldValue === 'string') {
unobserveStateChanges(record.target[updateSymbol]);
delete record.target[updateSymbol];
} else if (typeof record.target.dataset[stateKey] === 'string') {
record.target[updateSymbol] = _updateElement.bind(record.target);
observeStateChanges(record.target[updateSymbol], record.target.dataset[stateKey]);
}
break;
}
});
});
function _getStateMessage(type, recipient, data = {}) {
return {
sender, type, state: getStateObj(), msgId: crypto.randomUUID(),
recipient, location: location.href, timestamp: Date.now(), ...data
};
}
function _updateState(state = getStateObj(), url = location.href) {
const diff = diffState(state);
if (diff.length !== 0) {
history.replaceState(state, '', url);
notifyStateChange(diff);
return true;
} else {
return false;
}
}
/**
* Closes the broadcast channel if it's currently open. This will stop syncing between browsing contexts (tabs/windows/iframes)
*/
export function closeChannel() {
if (isChannelOpen) {
channel.close();
isChannelOpen = false;
}
}
/**
* Calculates the difference between two state objects.
*
* @param {object} newState - The new state object.
* @param {object} [oldState] - The old state object. Defaults to the current state object.
* @returns {string[]} - An array of keys representing the added, removed, or changed properties.
*/
export function diffState(newState, oldState = getStateObj()) {
if (oldState !== newState) {
const oldKeys = Object.keys(oldState);
const newKeys = Object.keys(newState);
const addedKeys = newKeys.filter(key => ! oldKeys.includes(key));
const removedKeys = oldKeys.filter(key => ! newKeys.includes(key));
const changedKeys = oldKeys.filter(key => key in newState && key in oldState && newState[key] !== oldState[key]);
return Object.freeze([...addedKeys, ...changedKeys, ...removedKeys]);
} else {
return [];
}
}
/**
* Notifies registered state change callbacks about changes in the state object.
*
* @param {string[]} diff - An array of keys representing the added, removed, or changed properties.
* @returns {Promise<object[]>} - A promise that resolves to an array of settlement objects, one for each callback invocation.
*/
export async function notifyStateChange(diff) {
if (Array.isArray(diff) && diff.length !== 0) {
const currState = getStateObj();
const state = Object.fromEntries(diff.map(key => [key, currState[key]]));
await Promise.allSettled(Array.from(
stateRegistry.entries(),
([callback, observedStates]) => {
if (observedStates.length === 0 || observedStates.some(state => diff.includes(state))) {
callback({ diff, state });
}
}
));
}
}
/**
* Registers a callback function to be notified of state changes.
*
* @param {Function} target - The callback function to register.
* @param {string[]} observedStates - An array of state keys to observe.
* @returns {boolean} - True if the callback was successfully registered, false otherwise.
*/
export function observeStateChanges(target, ...observedStates) {
if (target instanceof Function && ! stateRegistry.has(target)) {
stateRegistry.set(target, observedStates);
return true;
} else {
return false;
}
};
/**
* Gets a state value associated with a given key, providing a proxy object for reactive access and modification.
*
* @param {string} key - The key of the state value to retrieve.
* @param {*} [fallback=null] - The fallback value to return if the state value is undefined or null.
* @returns {ProxyHandler} - A proxy object representing the state value.
*/
export function getState(key, fallback = null) {
return new Proxy({
toString() {
return _getState(key, fallback)?.toString() ?? '';
},
valueOf() {
const val = _getState(key, fallback);
return val?.valueOf instanceof Function ? val.valueOf() : val;
},
toJSON() {
return _getState(key, fallback);
},
[Symbol.toPrimitive](hint) {
const val = _getState(key, fallback);
if (typeof val === hint) {
return val;
} else if (hint === 'default' && typeof val !== 'object') {
return val;
} else if (val?.[Symbol.toPrimitive] instanceof Function) {
return val?.[Symbol.toPrimitive] instanceof Function ? val[Symbol.toPrimitive](hint) : val;
} else if (hint !== 'number' && val?.toString instanceof Function) {
return val.toString();
} else if (hint === 'number') {
return parseFloat(val);
} else {
return val;
}
},
[proxySymbol]: true,
[Symbol.toStringTag]: 'StateValue',
[Symbol.iterator]() {
return _getState(key, fallback)?.[Symbol.iterator]();
},
}, {
defineProperty(target, prop, attributes) {
const val = _getState(key, fallback);
if (Reflect.defineProperty(val, prop, attributes)) {
setState(key, val);
return val;
} else {
return false;
}
},
deleteProperty(target, prop) {
return Reflect.deleteProperty(_getState(key, fallback), prop);
},
get(target, prop) {
const val = _getState(key, fallback);
if (prop in target) {
return target[prop];
} else if (typeof val === 'object') {
const result = Reflect.get(val, prop, val);
return result instanceof Function ? result.bind(val) : result;
} else {
return val[prop];
}
},
getOwnPropertyDescriptor(target, prop) {
return Reflect.getOwnPropertyDescriptor(_getState(key, fallback), prop);
},
getPrototypeOf() {
const val = _getState(key, fallback);
return typeof val === 'object' ? Reflect.getPrototypeOf(val) : Object.getPrototypeOf(val);
},
has(target, prop) {
return Reflect.has(_getState(key, fallback), prop);
},
isExtensible() {
return Reflect.isExtensible(_getState(key, fallback));
},
ownKeys() {
return Reflect.ownKeys(_getState(key, fallback));
},
preventExtensions() {
return Reflect.preventExtensions(_getState(key, fallback));
},
set(target, prop, newValue) {
const val = _getState(key, fallback);
if (Reflect.set(val, prop, newValue, val)) {
setState(key, val);
return true;
} else {
return false;
}
}
});
}
/**
* Unregisters a callback function from being notified of state changes.
*
* @param {Function} target - The callback function to unregister.
* @returns {boolean} - True if the callback was successfully unregistered, false otherwise.
*/
export const unobserveStateChanges = target => stateRegistry.delete(target);
/**
* Gets the current state object from the history.
*
* @returns {object} - A frozen copy of the current state object.
*/
export const getStateObj = () => Object.freeze(history.state === null ? {} : structuredClone(history.state));
/**
* Checks if a state key exists in the current state object.
*
* @param {string} key - The key to check for.
* @returns {boolean} - True if the key exists, false otherwise.
*/
export const hasState = key => key in getStateObj();
/**
* Sets a state value.
*
* @param {string} key - The property name to set.
* @param {*} newValue - The new value for the property, or a function to call to update
* @throws {TypeError} If state is not a string or has a length of 0
*/
export function setState(key, newValue) {
const state = getStateObj();
if (typeof key !== 'string' || key.length === 0) {
throw new TypeError('Invalid key.');
} else if (typeof newValue === 'function') {
updateState(key, newValue);
} else if (state[key] !== newValue) {
const detail = { key, oldValue: state[key], newValue };
const event = new CustomEvent(beforeChangeEvent, { cancelable: true, detail });
EVENT_TARGET.dispatchEvent(event);
if (! event.defaultPrevented) {
replaceState({ ...getStateObj(), [key]: newValue?.[proxySymbol] ? newValue.valueOf() : newValue }, location.href);
EVENT_TARGET.dispatchEvent(new CustomEvent(changeEvent, { detail }));
}
}
};
/**
* Updates a state value asynchronously.
*
* @param {string} key - The key of the state value to update.
* @param {Function} cb - The callback function to update the value.
* @returns {Promise<*>} - A promise that resolves to the updated state value.
*/
export const updateState = async (key, cb) => await Promise.try(() => cb(_getState(key), key)).then(val => {
setState(key, val);
return val;
});
/**
* Manages a state value, providing a getter and setter functions.
*
* @param {string} key - The key of the state value.
* @param {*} [initialValue=null] - The initial value for the state value.
* @returns {[ProxyHandler, Function]} - An array containing the getter and setter functions. The first function returns a proxy object representing the state value, and the second function is used to update the value.
*/
export function manageState(key, initialValue = null) {
return [getState(key, initialValue), newVal => setState(key, newVal)];
};
/**
* Deletes a state value.
*
* @param {string} key - The key of the state value to delete.
*/
export function deleteState(key) {
const state = { ...getStateObj() };
delete state[key];
replaceState(state, location.href);
};
/**
* Saves the current state object to local storage.
*
* @param {string} [key="aegis:state"] - The key to use for storing the state in local storage.
*/
export const saveState = (key = 'aegis:state') => localStorage.setItem(key, JSON.stringify(getStateObj()));
/**
* Restores the state object from local storage.
*
* @param {string} [key="aegis:state"] - The key used for storing the state in local storage.
*/
export const restoreState = (key = 'aegis:state') => _updateState(JSON.parse(localStorage.getItem(key)), location.href);
/**
* Clears the current state object.
*/
export const clearState = () => replaceState({}, location.href);
/**
* Replaces the current state object with the given state and updates the URL.
*
* @param {Object} state - The new state object.
* @param {string} url - The new URL.
* @returns {boolean} - True if the state was successfully replaced, false otherwise.
*/
export function replaceState(state = getStateObj(), url = location.href) {
if (_updateState(state, url)) {
if (isChannelOpen) {
channel.postMessage(_getStateMessage('update'));
}
}
}
/**
* Watches for state updates broadcasted through the channel and applies them to the local state.
*
* @param {object} [options] - Optional options.
* @param {AbortSignal} [options.signal] - An AbortSignal to cancel the watcher.
*/
export function watchState({ signal } = {}) {
channel.addEventListener('message', event => {
if (
event.isTrusted
&& typeof event.data.msgId === 'string'
&& typeof event.data.sender === 'string'
&& event.data.sender !== sender
&& typeof event.data.state === 'object'
&& (typeof event.data.recipient !== 'string' || event.data.recipient === sender)
) {
const currentState = getStateObj();
const diff = diffState(event.data.state, currentState);
if (diff.length !== 0) {
switch(event.data.type) {
case 'update':
_updateState({ ...currentState, ...event.data.state }, location.href);
break;
case 'sync':
if (isChannelOpen) {
channel.postMessage(_getStateMessage('update', event.data.sender));
}
break;
case 'clear':
_updateState({}, location.href);
break;
default:
reportError(new Error(`Unhandled broadcast channel message type: ${event.data.type}`));
}
}
}
}, { signal });
channel.postMessage(_getStateMessage('sync'));
if (signal instanceof AbortSignal && signal.aborted) {
closeChannel();
} else if (signal instanceof AbortSignal) {
signal.addEventListener('abort', closeChannel, { once: true });
}
};
/**
* Watches for DOM mutations (added/removed nodes and attribute changes) for elements matching `[data-aegis-state-key]`.
* Matching elements register a callback to be updated on state changes
*
* @param {Element|ShadowRoot|string} [target=document.documentElement] Root element to observe from
* @param {object} options
* @param {AbortSignal} [options.signal] Optional signal to disconnect the observer on abort
* @param {Element} [options.base=document.documentElement] Base element to query from when `target` is a selector
* @throws {TypeError} If the `target` is not an Element, ShadowRoot, or a valid CSS selector.
* @throws {Error} If the provided `signal` is aborted.
*/
export function observeDOMState(target = document.documentElement, { signal, base = document.documentElement } = {}) {
if (signal instanceof AbortSignal && signal.aborted) {
throw signal.reason;
} else if (typeof target === 'string') {
observeDOMState(base.querySelector(target), { signal });
} else if (! (target instanceof Element || target instanceof ShadowRoot)) {
throw new TypeError('Target must be an element, selector, or shadow root.');
} else {
domObserver.observe(target, {
childList: true,
subtree: true,
attributeFilter: [stateKeyAttribute],
attributeOldValue: true,
});
$$(`[${stateKeyAttribute}]`, target).forEach(el => {
el[updateSymbol] = _updateElement.bind(el);
observeStateChanges(el[updateSymbol], el.dataset[stateKey]);
el[updateSymbol]({ state: history.state });
});
if (signal instanceof AbortSignal) {
signal.addEventListener('abort', () => domObserver.disconnect(), { once: true });
}
}
}
/**
* Binds a DOM element to a specific state key to be updated on state changes
*
* @param {Element|string} target Target element or a selector
* @param {string} key Name/key to observe
* @param {object} options
* @param {string} [options.attr] Optional attribute to bind state to
* @param {string} [options.style] Optional style property to bind state to
* @param {Element} [options.base=document.body] Base to query from when `target` is a selector
*/
export function bindState(target, key, { attr, style, base = document.body } = {}) {
if (typeof target === 'string') {
bindState(base.querySelector(target), key, { attr, style });
} else if (! (target instanceof Element)) {
throw new TypeError('Target must be an element or selector.');
} else if (typeof stateKey !== 'string' || stateKey.length === 0) {
throw new TypeError('State key must be a non-empty string.');
} else if (target instanceof HTMLElement) {
target.dataset[stateKey] = key;
if (typeof attr === 'string') {
target.dataset[stateAttr] = attr;
} else if (typeof style === 'string') {
target.dataset[stateStyle] = style;
}
requestAnimationFrame(() => _updateElement.call(target, { state: history.state ?? {}}));
} else if (target instanceof Element) {
target.setAttribute(stateKeyAttribute, key);
if (typeof attr === 'string') {
target.setAttribute(stateAttrAttribute, attr);
} else if (typeof style === 'string') {
target.setAttribute(stateStyleAttribute, style);
}
requestAnimationFrame(() => _updateElement.call(target, { state: history.state ?? {}}));
}
}
/**
* Creates and registers a callback on for given element (`target`) for state changes specified by `key`
*
* @param {Element|string} target Element or selector
* @param {string} key Name/value for key in state obejct
* @param {Function} handler The callback to register on for state changes
* @param {object} options
* @param {Element} [options.base=document.body] Base to query from when `target` is a selector
* @param {AbortSignal} [options.signal] Optional signal to unregister callback when aborted
* @returns {Function} The resulting callback, bound to the target Element
*/
export function createStateHandler(target, key, handler, { base = document.documentElement, signal } = {}) {
if (signal instanceof AbortSignal && signal.aborted) {
throw signal.reason;
} else if (typeof target === 'string') {
return createStateHandler(base.querySelector(target), key, handler, {});
} else if (! (target instanceof Element)) {
throw new TypeError('Target must be an element or selector.');
} else if (typeof key !== 'string' || key.length === 0) {
throw new TypeError('State key must be a non-empty string.');
} else if (! (handler instanceof Function)) {
throw new TypeError('Callback must be a function.');
} else {
const callback = (function({ state = {} } = {}) {
return handler.call(this, state[key], this);
}).bind(target);
observeStateChanges(callback, key);
if (signal instanceof AbortSignal) {
signal.addEventListener('abort', () => unobserveStateChanges(callback), { once: true });
}
return callback;
}
}
/**
* A change or input handler for inputs, updating state to new values
*
* @param {Event} event A change or input event
* @throws {TypeError} If the event target is not an HTMLElement
*/
export function changeHandler({ target, currentTarget, type }) {
if (! (target instanceof HTMLElement)) {
throw new TypeError(`Event ${type} target must be an HTMLElement.`);
} else if (target.isContentEditable && typeof target.dataset.name === 'string' && target.dataset.name.length !== 0) {
setState(target.dataset.name, target.textContent);
} else if (typeof target.name !== 'string' || target.name.length === 0) {
// Remove event listener if event target is the element the listener was set on
if (target.isSameNode(currentTarget)) {
target.removeEventListener(type, changeHandler);
}
} else if (target instanceof HTMLSelectElement) {
setState(target.name, target.multiple ? Array.from(target.selectedOptions, opt => opt.value) : target.value);
} else if (target instanceof HTMLInputElement) {
switch(target.type) {
case 'checkbox': {
const checkboxes = Array.from(target.form?.elements ?? [target])
.filter(input => input.name === target.name && input.type === 'checkbox');
if (checkboxes.length === 1) {
setState(target.name, target.value === 'on' ? target.checked : target.value);
} else {
setState(target.name, Array.from(checkboxes).filter(item => item.checked).map(item => item.value));
}
}
break;
case 'radio':
setState(
target.name,
Array.from(target.form?.elements ?? [target])
.filter(input => input.name === target.name && input.checked)
.find(input => input.value)?.value
);
break;
case 'number':
case 'range':
setState(target.name, target.valueAsNumber);
break;
case 'date':
setState(target.name, target.valueAsDate?.toISOString()?.split('T')?.at(0));
break;
case 'file':
setState(target.name, target.multiple ? Array.from(target.files) : target.files.item(0));
break;
case 'datetime-local':
setState(target.name, target.valueAsDate);
break;
default:
setState(target.name, target.value);
}
} else if (target instanceof HTMLTextAreaElement) {
setState(target.name, target.value);
} else if (target.constructor.formAssociated) {
setState(target.name, target.value);
} else {
throw new TypeError(`Event ${type} target is not a valid form element.`);
}
}
/**
* Adds an event listener for a `change` event on state.
*
* @param {Function} callback - The callback function to handle the `change` event.
* @param {object} [options] - Optional configuration object to customize the listener behavior.
* @param {AbortSignal} [options.signal] - An optional `AbortSignal` object that allows you to cancel the event listener (useful for cleanup).
* @param {boolean} [options.once=false] - If `true`, the listener will be invoked at most once and then removed after the first invocation.
* @param {boolean} [options.passive=false] - If `true`, the listener will never call `preventDefault()`, improving performance for some types of events (e.g., scrolling).
*/
export function onStateChange(callback, { signal, once = false, passive = false } = {}) {
EVENT_TARGET.addEventListener(changeEvent, callback, { signal, once, passive });
}
/**
* Adds an event listener for a cancelable `beforechange` event on state
*
* @param {Function} callback - The callback function to handle the `beforechange` event.
* @param {object} [options] - Optional configuration object to customize the listener behavior.
* @param {AbortSignal} [options.signal] - An optional `AbortSignal` object that allows you to cancel the event listener (useful for cleanup).
* @param {boolean} [options.once=false] - If `true`, the listener will be invoked at most once and then removed after the first invocation.
* @param {boolean} [options.passive=false] - If `true`, the listener will never call `preventDefault()`, improving performance for some types of events (e.g., scrolling).
*/
export function onBeforeStateChange(callback, { signal, once = false, passive = false } = {}) {
EVENT_TARGET.addEventListener(beforeChangeEvent, callback, { signal, once, passive });
}