@aegisjsproject/callback-registry 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,509 @@
1
+ let _isRegistrationOpen = true;
2
+
3
+ const $$ = (selector, base = document) => base.querySelectorAll(selector);
4
+
5
+ const $ = (selector, base = document) => base.querySelector(selector);
6
+
7
+ const FUNCS = {
8
+ debug: {
9
+ log: 'aegis:debug:log',
10
+ info: 'aegis:debug:info',
11
+ warn: 'aegis:debug:warn',
12
+ error: 'aegis:debug:error',
13
+ },
14
+ navigate: {
15
+ back: 'aegis:navigate:back',
16
+ forward: 'aegis:navigate:forward',
17
+ reload: 'aegis:navigate:reload',
18
+ link: 'aegis:navigate:go',
19
+ popup: 'aegis:navigate:popup',
20
+ },
21
+ ui: {
22
+ print: 'aegis:ui:print',
23
+ remove: 'aegis:ui:remove',
24
+ hide: 'aegis:ui:hide',
25
+ unhide: 'aegis:ui:unhide',
26
+ showModal: 'aegis:ui:showModal',
27
+ closeModal: 'aegis:ui:closeModal',
28
+ showPopover: 'aegis:ui:showPopover',
29
+ hidePopover: 'aegis:ui:hidePopover',
30
+ togglePopover: 'aegis:ui:togglePopover',
31
+ enable: 'aegis:ui:enable',
32
+ disable: 'aegis:ui:disable',
33
+ scrollTo: 'aegis:ui:scrollTo',
34
+ prevent: 'aegis:ui:prevent',
35
+ },
36
+ };
37
+
38
+ const registry = new Map([
39
+ [FUNCS.debug.log, console.log],
40
+ [FUNCS.debug.warn, console.warn],
41
+ [FUNCS.debug.error, console.error],
42
+ [FUNCS.debug.info, console.info],
43
+ [FUNCS.navigate.back, history.back],
44
+ [FUNCS.navigate.forward, history.forward],
45
+ [FUNCS.navigate.reload, () => history.go(0)],
46
+ [FUNCS.navigate.link, event => {
47
+ if (event.isTrusted) {
48
+ event.preventDefault();
49
+ location.href = event.currentTarget.dataset.url;
50
+ }
51
+ }],
52
+ [FUNCS.navigate.popup, event => {
53
+ if (event.isTrusted) {
54
+ event.preventDefault();
55
+ globalThis.open(event.currentTarget.dataset.url);
56
+ }
57
+ }],
58
+ [FUNCS.ui.hide, ({ currentTarget }) => {
59
+ $$(currentTarget.dataset.hideSelector).forEach(el => el.hidden = true);
60
+ }],
61
+ [FUNCS.ui.unhide, ({ currentTarget }) => {
62
+ $$(currentTarget.dataset.unhideSelector).forEach(el => el.hidden = false);
63
+ }],
64
+ [FUNCS.ui.disable, ({ currentTarget }) => {
65
+ $$(currentTarget.dataset.disableSelector).forEach(el => el.disabled = true);
66
+ }],
67
+ [FUNCS.ui.enable, ({ currentTarget }) => {
68
+ $$(currentTarget.dataset.enableSelector).forEach(el => el.disabled = false);
69
+ }],
70
+ [FUNCS.ui.remove, ({ currentTarget }) => {
71
+ $$(currentTarget.dataset.removeSelector).forEach(el => el.remove());
72
+ }],
73
+ [FUNCS.ui.scrollTo, ({ currentTarget }) => {
74
+ const target = $(currentTarget.dataset.scrollToSelector);
75
+
76
+ if (target instanceof Element) {
77
+ target.scrollIntoView({
78
+ behavior: matchMedia('(prefers-reduced-motion: reduce)').matches
79
+ ? 'instant'
80
+ : 'smooth',
81
+ });
82
+ }
83
+ }],
84
+ [FUNCS.ui.showModal, ({ currentTarget }) => {
85
+ const target = $(currentTarget.dataset.showModalSelector);
86
+
87
+ if (target instanceof HTMLDialogElement) {
88
+ target.showModal();
89
+ }
90
+ }],
91
+ [FUNCS.ui.closeModal, ({ currentTarget }) => {
92
+ const target = $(currentTarget.dataset.closeModalSelector);
93
+
94
+ if (target instanceof HTMLDialogElement) {
95
+ target.close();
96
+ }
97
+ }],
98
+ [FUNCS.ui.showPopover, ({ currentTarget }) => {
99
+ const target = $(currentTarget.dataset.showPopoverSelector);
100
+
101
+ if (target instanceof HTMLElement) {
102
+ target.showPopover();
103
+ }
104
+ }],
105
+ [FUNCS.ui.hidePopover, ({ currentTarget }) => {
106
+ const target = $(currentTarget.dataset.hidePopoverSelector);
107
+
108
+ if (target instanceof HTMLElement) {
109
+ target.hidePopover();
110
+ }
111
+ }],
112
+ [FUNCS.ui.togglePopover, ({ currentTarget }) => {
113
+ const target = $(currentTarget.dataset.togglePopoverSelector);
114
+
115
+ if (target instanceof HTMLElement) {
116
+ target.togglePopover();
117
+ }
118
+ }],
119
+ [FUNCS.ui.print, () => globalThis.print()],
120
+ [FUNCS.ui.prevent, event => event.preventDefault()],
121
+ ]);
122
+
123
+ /**
124
+ * Check if callback registry is open
125
+ *
126
+ * @returns {boolean} Whether or not callback registry is open
127
+ */
128
+ const isRegistrationOpen = () => _isRegistrationOpen;
129
+
130
+ /**
131
+ * Close callback registry
132
+ *
133
+ * @returns {boolean} Whether or not the callback was succesfully removed
134
+ */
135
+ const closeRegistration = () => _isRegistrationOpen = false;
136
+
137
+ /**
138
+ * Get an array of registered callbacks
139
+ *
140
+ * @returns {Array} A frozen array listing keys to all registered callbacks
141
+ */
142
+ const listCallbacks = () => Object.freeze(Array.from(registry.keys()));
143
+
144
+ /**
145
+ * Check if a callback is registered
146
+ *
147
+ * @param {string} name The name/key to check for in callback registry
148
+ * @returns {boolean} Whether or not a callback is registered
149
+ */
150
+ const hasCallback = name => registry.has(name);
151
+
152
+ /**
153
+ * Get a callback from the registry by name/key
154
+ *
155
+ * @param {string} name The name/key of the callback to get
156
+ * @returns {Function|undefined} The corresponding function registered under that name/key
157
+ */
158
+ const getCallback = name => registry.get(name);
159
+
160
+ /**
161
+ * Remove a callback from the registry
162
+ *
163
+ * @param {string} name The name/key of the callback to get
164
+ * @returns {boolean} Whether or not the callback was successfully unregisterd
165
+ */
166
+ const unregisterCallback = name => _isRegistrationOpen && registry.delete(name);
167
+
168
+ /**
169
+ * Remove all callbacks from the registry
170
+ *
171
+ * @returns {undefined}
172
+ */
173
+ const clearRegistry = () => registry.clear();
174
+
175
+ /**
176
+ * Create a registered callback with a randomly generated name
177
+ *
178
+ * @param {Function} callback Callback function to register
179
+ * @returns {string} The automatically generated key/name of the registered callback
180
+ */
181
+ const createCallback = (callback) => registerCallback('aegis:callback:' + crypto.randomUUID(), callback);
182
+
183
+ /**
184
+ * Call a callback fromt the registry by name/key
185
+ *
186
+ * @param {string} name The name/key of the registered function
187
+ * @param {...any} args Any arguments to pass along to the function
188
+ * @returns {any} Whatever the return value of the function is
189
+ * @throws {Error} Throws if callback is not found or any error resulting from calling the function
190
+ */
191
+ function callCallback(name, ...args) {
192
+ if (registry.has(name)) {
193
+ return registry.get(name).apply(this || globalThis, args);
194
+ } else {
195
+ throw new Error(`No ${name} function registered.`);
196
+ }
197
+ }
198
+
199
+ /**
200
+ * Register a named callback in registry
201
+ *
202
+ * @param {string} name The name/key to register the callback under
203
+ * @param {Function} callback The callback value to register
204
+ * @returns {string} The registered name/key
205
+ */
206
+ function registerCallback(name, callback) {
207
+ if (typeof name !== 'string' || name.length === 0) {
208
+ throw new TypeError('Callback name must be a string.');
209
+ } if (! (callback instanceof Function)) {
210
+ throw new TypeError('Callback must be a function.');
211
+ } else if (! _isRegistrationOpen) {
212
+ throw new TypeError('Cannot register new callbacks because registry is closed.');
213
+ } else if (registry.has(name)) {
214
+ throw new Error(`Handler "${name}" is already registered.`);
215
+ } else {
216
+ registry.set(name, callback);
217
+ return name;
218
+ }
219
+ }
220
+
221
+ /**
222
+ * Get the host/root node of a given thing.
223
+ *
224
+ * @param {Event|Document|Element|ShadowRoot} target Source thing to search for host of
225
+ * @returns {Document|Element|null} The host/root node, or null
226
+ */
227
+ function getHost(target) {
228
+ if (target instanceof Event) {
229
+ return getHost(target.currentTarget);
230
+ } else if (target instanceof Document) {
231
+ return target;
232
+ } else if (target instanceof Element) {
233
+ return getHost(target.getRootNode());
234
+ } else if (target instanceof ShadowRoot) {
235
+ return target.host;
236
+ } else {
237
+ return null;
238
+ }
239
+ }
240
+
241
+ const EVENT_PREFIX = 'data-aegis-event-on-';
242
+ const EVENT_PREFIX_LENGTH = EVENT_PREFIX.length;
243
+ const DATA_PREFIX = 'aegisEventOn';
244
+ const DATA_PREFIX_LENGTH = DATA_PREFIX.length;
245
+
246
+ const once = 'data-aegis-event-once',
247
+ passive = 'data-aegis-event-passive',
248
+ capture = 'data-aegis-event-capture';
249
+
250
+ const eventAttrs = [
251
+ EVENT_PREFIX + 'abort',
252
+ EVENT_PREFIX + 'blur',
253
+ EVENT_PREFIX + 'focus',
254
+ EVENT_PREFIX + 'cancel',
255
+ EVENT_PREFIX + 'auxclick',
256
+ EVENT_PREFIX + 'beforeinput',
257
+ EVENT_PREFIX + 'beforetoggle',
258
+ EVENT_PREFIX + 'canplay',
259
+ EVENT_PREFIX + 'canplaythrough',
260
+ EVENT_PREFIX + 'change',
261
+ EVENT_PREFIX + 'click',
262
+ EVENT_PREFIX + 'close',
263
+ EVENT_PREFIX + 'contextmenu',
264
+ EVENT_PREFIX + 'copy',
265
+ EVENT_PREFIX + 'cuechange',
266
+ EVENT_PREFIX + 'cut',
267
+ EVENT_PREFIX + 'dblclick',
268
+ EVENT_PREFIX + 'drag',
269
+ EVENT_PREFIX + 'dragend',
270
+ EVENT_PREFIX + 'dragenter',
271
+ EVENT_PREFIX + 'dragexit',
272
+ EVENT_PREFIX + 'dragleave',
273
+ EVENT_PREFIX + 'dragover',
274
+ EVENT_PREFIX + 'dragstart',
275
+ EVENT_PREFIX + 'drop',
276
+ EVENT_PREFIX + 'durationchange',
277
+ EVENT_PREFIX + 'emptied',
278
+ EVENT_PREFIX + 'ended',
279
+ EVENT_PREFIX + 'formdata',
280
+ EVENT_PREFIX + 'input',
281
+ EVENT_PREFIX + 'invalid',
282
+ EVENT_PREFIX + 'keydown',
283
+ EVENT_PREFIX + 'keypress',
284
+ EVENT_PREFIX + 'keyup',
285
+ EVENT_PREFIX + 'load',
286
+ EVENT_PREFIX + 'loadeddata',
287
+ EVENT_PREFIX + 'loadedmetadata',
288
+ EVENT_PREFIX + 'loadstart',
289
+ EVENT_PREFIX + 'mousedown',
290
+ EVENT_PREFIX + 'mouseenter',
291
+ EVENT_PREFIX + 'mouseleave',
292
+ EVENT_PREFIX + 'mousemove',
293
+ EVENT_PREFIX + 'mouseout',
294
+ EVENT_PREFIX + 'mouseover',
295
+ EVENT_PREFIX + 'mouseup',
296
+ EVENT_PREFIX + 'wheel',
297
+ EVENT_PREFIX + 'paste',
298
+ EVENT_PREFIX + 'pause',
299
+ EVENT_PREFIX + 'play',
300
+ EVENT_PREFIX + 'playing',
301
+ EVENT_PREFIX + 'progress',
302
+ EVENT_PREFIX + 'ratechange',
303
+ EVENT_PREFIX + 'reset',
304
+ EVENT_PREFIX + 'resize',
305
+ EVENT_PREFIX + 'scroll',
306
+ EVENT_PREFIX + 'scrollend',
307
+ EVENT_PREFIX + 'securitypolicyviolation',
308
+ EVENT_PREFIX + 'seeked',
309
+ EVENT_PREFIX + 'seeking',
310
+ EVENT_PREFIX + 'select',
311
+ EVENT_PREFIX + 'slotchange',
312
+ EVENT_PREFIX + 'stalled',
313
+ EVENT_PREFIX + 'submit',
314
+ EVENT_PREFIX + 'suspend',
315
+ EVENT_PREFIX + 'timeupdate',
316
+ EVENT_PREFIX + 'volumechange',
317
+ EVENT_PREFIX + 'waiting',
318
+ EVENT_PREFIX + 'selectstart',
319
+ EVENT_PREFIX + 'selectionchange',
320
+ EVENT_PREFIX + 'toggle',
321
+ EVENT_PREFIX + 'pointercancel',
322
+ EVENT_PREFIX + 'pointerdown',
323
+ EVENT_PREFIX + 'pointerup',
324
+ EVENT_PREFIX + 'pointermove',
325
+ EVENT_PREFIX + 'pointerout',
326
+ EVENT_PREFIX + 'pointerover',
327
+ EVENT_PREFIX + 'pointerenter',
328
+ EVENT_PREFIX + 'pointerleave',
329
+ EVENT_PREFIX + 'gotpointercapture',
330
+ EVENT_PREFIX + 'lostpointercapture',
331
+ EVENT_PREFIX + 'mozfullscreenchange',
332
+ EVENT_PREFIX + 'mozfullscreenerror',
333
+ EVENT_PREFIX + 'animationcancel',
334
+ EVENT_PREFIX + 'animationend',
335
+ EVENT_PREFIX + 'animationiteration',
336
+ EVENT_PREFIX + 'animationstart',
337
+ EVENT_PREFIX + 'transitioncancel',
338
+ EVENT_PREFIX + 'transitionend',
339
+ EVENT_PREFIX + 'transitionrun',
340
+ EVENT_PREFIX + 'transitionstart',
341
+ EVENT_PREFIX + 'webkitanimationend',
342
+ EVENT_PREFIX + 'webkitanimationiteration',
343
+ EVENT_PREFIX + 'webkitanimationstart',
344
+ EVENT_PREFIX + 'webkittransitionend',
345
+ EVENT_PREFIX + 'error',
346
+ ];
347
+
348
+ let selector = eventAttrs.map(attr => `[${CSS.escape(attr)}]`).join(', ');
349
+
350
+ const attrToProp = attr => `on${attr[EVENT_PREFIX_LENGTH].toUpperCase()}${attr.substring(EVENT_PREFIX_LENGTH + 1)}`;
351
+
352
+ const attrEntriesMap = attr => [attrToProp(attr), attr];
353
+
354
+ const isEventDataAttr = ([name]) => name.startsWith(DATA_PREFIX);
355
+
356
+ const DATA_EVENTS = Object.fromEntries([...eventAttrs].map(attrEntriesMap));
357
+
358
+ function _addListeners(el, { signal, attrFilter = EVENTS } = {}) {
359
+ const dataset = el.dataset;
360
+
361
+ for (const [attr, val] of Object.entries(dataset).filter(isEventDataAttr)) {
362
+ try {
363
+ const event = 'on' + attr.substring(DATA_PREFIX_LENGTH);
364
+
365
+ if (attrFilter.hasOwnProperty(event) && hasCallback(val)) {
366
+ el.addEventListener(event.substring(2).toLowerCase(), getCallback(val), {
367
+ passive: dataset.hasOwnProperty('aegisEventPassive'),
368
+ capture: dataset.hasOwnProperty('aegisEventCapture'),
369
+ once: dataset.hasOwnProperty('aegisEventOnce'),
370
+ signal,
371
+ });
372
+ }
373
+ } catch(err) {
374
+ console.error(err);
375
+ }
376
+ }
377
+ }
378
+
379
+ const observer = new MutationObserver(records => {
380
+ records.forEach(record => {
381
+ switch(record.type) {
382
+ case 'childList':
383
+ [...record.addedNodes]
384
+ .filter(node => node.nodeType === Node.ELEMENT_NODE)
385
+ .forEach(node => attachListeners(node));
386
+ break;
387
+
388
+ case 'attributes':
389
+ if (typeof record.oldValue === 'string' && hasCallback(record.oldValue)) {
390
+ record.target.removeEventListener(
391
+ record.attributeName.substring(EVENT_PREFIX_LENGTH),
392
+ getCallback(record.oldValue), {
393
+ once: record.target.hasAttribute(once),
394
+ capture: record.target.hasAttribute(capture),
395
+ passive: record.target.hasAttribute(passive),
396
+ }
397
+ );
398
+ }
399
+
400
+ if (
401
+ record.target.hasAttribute(record.attributeName)
402
+ && hasCallback(record.target.getAttribute(record.attributeName))
403
+ ) {
404
+ record.target.addEventListener(
405
+ record.attributeName.substring(EVENT_PREFIX_LENGTH),
406
+ getCallback(record.target.getAttribute(record.attributeName)), {
407
+ once: record.target.hasAttribute(once),
408
+ capture: record.target.hasAttribute(capture),
409
+ passive: record.target.hasAttribute(passive),
410
+ }
411
+ );
412
+ }
413
+ break;
414
+ }
415
+ });
416
+ });
417
+
418
+ const EVENTS = { ...DATA_EVENTS, once, passive, capture };
419
+
420
+ /**
421
+ * Register an attribute to observe for adding/removing event listeners
422
+ *
423
+ * @param {string} attr Name of the attribute to observe
424
+ * @param {object} options
425
+ * @param {boolean} [options.addListeners=false] Whether or not to automatically add listeners
426
+ * @param {Document|Element} [options.base=document.body] Root node to observe
427
+ * @param {AbortSignal} [options.signal] An abort signal to remove any listeners when aborted
428
+ * @returns {string} The resulting `data-*` attribute name
429
+ */
430
+ function registerEventAttribute(attr, {
431
+ addListeners = false,
432
+ base = document.body,
433
+ signal,
434
+ } = {}) {
435
+ const fullAttr = EVENT_PREFIX + attr.toLowerCase();
436
+
437
+ if (! eventAttrs.includes(fullAttr)) {
438
+ const sel = `[${CSS.escape(fullAttr)}]`;
439
+ const prop = attrToProp(fullAttr);
440
+ eventAttrs.push(fullAttr);
441
+ EVENTS[prop] = fullAttr;
442
+ selector += `, ${sel}`;
443
+
444
+ if (addListeners) {
445
+ requestAnimationFrame(() => {
446
+ const config = { attrFilter: { [prop]: sel }, signal };
447
+ [base, ...base.querySelectorAll(sel)].forEach(el => _addListeners(el, config));
448
+ });
449
+ }
450
+ }
451
+
452
+ return fullAttr;
453
+ }
454
+
455
+ /**
456
+ * Add listeners to an element and its children, matching a generated query based on registered attributes
457
+ *
458
+ * @param {Element|Document} target Root node to add listeners from
459
+ * @param {object} options
460
+ * @param {AbortSignal} [options.signal] Optional signal to remove event listeners
461
+ * @returns {Element|Document} Returns the passed target node
462
+ */
463
+ function attachListeners(target, { signal } = {}) {
464
+ const nodes = target instanceof Element && target.matches(selector)
465
+ ? [target, ...target.querySelectorAll(selector)]
466
+ : target.querySelectorAll(selector);
467
+
468
+ nodes.forEach(el => _addListeners(el, { signal }));
469
+
470
+ return target;
471
+ }
472
+ /**
473
+ * Add a node to the `MutationObserver` to observe attributes and add/remove event listeners
474
+ *
475
+ * @param {Document|Element} root Element to observe attributes on
476
+ */
477
+ function observeEvents(root = document) {
478
+ attachListeners(root);
479
+ observer.observe(root, {
480
+ subtree: true,
481
+ childList:true,
482
+ attributes: true,
483
+ attributeOldValue: true,
484
+ attributeFilter: eventAttrs,
485
+ });
486
+ }
487
+
488
+ /**
489
+ * Disconnects the `MutationObserver`, disabling observing of all attribute changes
490
+ *
491
+ * @returns {void}
492
+ */
493
+ const disconnectEventsObserver = () => observer.disconnect();
494
+
495
+ /**
496
+ * Register a global error handler callback
497
+ *
498
+ * @param {Function} callback Callback to register as a global error handler
499
+ * @param {EventInit} config Typical event listener config object
500
+ */
501
+ function setGlobalErrorHandler(callback, { capture, once, passive, signal } = {}) {
502
+ if (callback instanceof Function) {
503
+ globalThis.addEventListener('error', callback, { capture, once, passive, signal });
504
+ } else {
505
+ throw new TypeError('Callback is not a function.');
506
+ }
507
+ }
508
+
509
+ export { EVENTS, FUNCS, attachListeners, callCallback, clearRegistry, closeRegistration, createCallback, disconnectEventsObserver, getCallback, getHost, hasCallback, isRegistrationOpen, listCallbacks, observeEvents, registerCallback, registerEventAttribute, setGlobalErrorHandler, unregisterCallback };