Debian Codegraph @

src/modules/Hooks.ts

raw
1 import type { DelegateEvent } from 'delegate-it';
2
3 import type Swup from '../Swup.js';
4 import { isPromise, runAsPromise } from '../utils.js';
5 import { Visit } from './Visit.js';
6 import type { FetchOptions, PageData } from './fetchPage.js';
7
8 export interface HookDefinitions {
9 'animation:out:start': undefined;
10 'animation:out:await': { skip: boolean };
11 'animation:out:end': undefined;
12 'animation:in:start': undefined;
13 'animation:in:await': { skip: boolean };
14 'animation:in:end': undefined;
15 'animation:skip': undefined;
16 'cache:clear': undefined;
17 'cache:set': { page: PageData };
18 'content:replace': { page: PageData };
19 'content:scroll': undefined;
20 'enable': undefined;
21 'disable': undefined;
22 'fetch:request': { url: string; options: FetchOptions };
23 'fetch:error': { url: string; status: number; response: Response };
24 'fetch:timeout': { url: string };
25 'history:popstate': { event: PopStateEvent };
26 'link:click': { el: HTMLAnchorElement; event: DelegateEvent<MouseEvent> };
27 'link:self': undefined;
28 'link:anchor': { hash: string };
29 'link:newtab': { href: string };
30 'page:load': { page?: PageData; cache?: boolean; options: FetchOptions };
31 'page:view': { url: string; title: string };
32 'scroll:top': { options: ScrollIntoViewOptions };
33 'scroll:anchor': { hash: string; options: ScrollIntoViewOptions };
34 'visit:start': undefined;
35 'visit:transition': undefined;
36 'visit:abort': undefined;
37 'visit:end': undefined;
38 }
39
40 export interface HookReturnValues {
41 'content:scroll': Promise<boolean> | boolean;
42 'fetch:request': Promise<Response>;
43 'page:load': Promise<PageData>;
44 'scroll:top': boolean;
45 'scroll:anchor': boolean;
46 }
47
48 export type HookArguments<T extends HookName> = HookDefinitions[T];
49
50 export type HookName = keyof HookDefinitions;
51
52 export type HookNameWithModifier = `${HookName}.${HookModifier}`;
53
54 type HookModifier = 'once' | 'before' | 'replace';
55
56 /** A generic hook handler. */
57 export type HookHandler<T extends HookName> = (
58 /** Context about the current visit. */
59 visit: Visit,
60 /** Local arguments passed into the handler. */
61 args: HookArguments<T>
62 ) => Promise<unknown> | unknown;
63
64 /** A default hook handler with an expected return type. */
65 export type HookDefaultHandler<T extends HookName> = (
66 /** Context about the current visit. */
67 visit: Visit,
68 /** Local arguments passed into the handler. */
69 args: HookArguments<T>,
70 /** Default handler to be executed. Available if replacing an internal hook handler. */
71 defaultHandler?: HookDefaultHandler<T>
72 ) => T extends keyof HookReturnValues ? HookReturnValues[T] : Promise<unknown> | unknown;
73
74 export type Handlers = {
75 [K in HookName]: HookHandler<K>[];
76 };
77
78 export type HookInitOptions = {
79 [K in HookName as K | `${K}.${HookModifier}`]: HookHandler<K>;
80 } & {
81 [K in HookName as K | `${K}.${HookModifier}.${HookModifier}`]: HookHandler<K>;
82 };
83
84 /** Unregister a previously registered hook handler. */
85 export type HookUnregister = () => void;
86
87 /** Define when and how a hook handler is executed. */
88 export type HookOptions = {
89 /** Execute the hook once, then remove the handler */
90 once?: boolean;
91 /** Execute the hook before the internal default handler */
92 before?: boolean;
93 /** Set a priority for when to execute this hook. Lower numbers execute first. Default: `0` */
94 priority?: number;
95 /** Replace the internal default handler with this hook handler */
96 replace?: boolean;
97 };
98
99 export type HookRegistration<
100 T extends HookName,
101 H extends HookHandler<T> | HookDefaultHandler<T> = HookHandler<T>
102 > = {
103 id: number;
104 hook: T;
105 handler: H;
106 defaultHandler?: HookDefaultHandler<T>;
107 } & HookOptions;
108
109 type HookEventDetail = {
110 hook: HookName;
111 args: unknown;
112 visit: Visit;
113 };
114
115 export type HookEvent = CustomEvent<HookEventDetail>;
116
117 type HookLedger<T extends HookName> = Map<HookHandler<T>, HookRegistration<T>>;
118
119 interface HookRegistry extends Map<HookName, HookLedger<HookName>> {
120 get<K extends HookName>(key: K): HookLedger<K> | undefined;
121 set<K extends HookName>(key: K, value: HookLedger<K>): this;
122 }
123
124 /**
125 * Hook registry.
126 *
127 * Create, trigger and handle hooks.
128 *
129 */
130 export class Hooks {
131 /** Swup instance this registry belongs to */
132 protected swup: Swup;
133
134 /** Map of all registered hook handlers. */
135 protected registry: HookRegistry = new Map();
136
137 // Can we deduplicate this somehow? Or make it error when not in sync with HookDefinitions?
138 // https://stackoverflow.com/questions/53387838/how-to-ensure-an-arrays-values-the-keys-of-a-typescript-interface/53395649
139 protected readonly hooks: HookName[] = [
140 'animation:out:start',
141 'animation:out:await',
142 'animation:out:end',
143 'animation:in:start',
144 'animation:in:await',
145 'animation:in:end',
146 'animation:skip',
147 'cache:clear',
148 'cache:set',
149 'content:replace',
150 'content:scroll',
151 'enable',
152 'disable',
153 'fetch:request',
154 'fetch:error',
155 'fetch:timeout',
156 'history:popstate',
157 'link:click',
158 'link:self',
159 'link:anchor',
160 'link:newtab',
161 'page:load',
162 'page:view',
163 'scroll:top',
164 'scroll:anchor',
165 'visit:start',
166 'visit:transition',
167 'visit:abort',
168 'visit:end'
169 ];
170
171 constructor(swup: Swup) {
172 this.swup = swup;
173 this.init();
174 }
175
176 /**
177 * Create ledgers for all core hooks.
178 */
179 protected init() {
180 this.hooks.forEach((hook) => this.create(hook));
181 }
182
183 /**
184 * Create a new hook type.
185 */
186 create(hook: string) {
187 if (!this.registry.has(hook as HookName)) {
188 this.registry.set(hook as HookName, new Map());
189 }
190 }
191
192 /**
193 * Check if a hook type exists.
194 */
195 exists(hook: HookName): boolean {
196 return this.registry.has(hook);
197 }
198
199 /**
200 * Get the ledger with all registrations for a hook.
201 */
202 protected get<T extends HookName>(hook: T): HookLedger<T> | undefined {
203 const ledger = this.registry.get(hook);
204 if (ledger) {
205 return ledger;
206 }
207 console.error(`Unknown hook '${hook}'`);
208 }
209
210 /**
211 * Remove all handlers of all hooks.
212 */
213 clear() {
214 this.registry.forEach((ledger) => ledger.clear());
215 }
216
217 /**
218 * Register a new hook handler.
219 * @param hook Name of the hook to listen for
220 * @param handler The handler function to execute
221 * @param options Object to specify how and when the handler is executed
222 * Available options:
223 * - `once`: Only execute the handler once
224 * - `before`: Execute the handler before the default handler
225 * - `priority`: Specify the order in which the handlers are executed
226 * - `replace`: Replace the default handler with this handler
227 * @returns A function to unregister the handler
228 */
229
230 // Overload: replacing default handler
231 on<T extends HookName, O extends HookOptions>(hook: T, handler: HookDefaultHandler<T>, options: O & { replace: true }): HookUnregister; // prettier-ignore
232 // Overload: passed in handler options
233 on<T extends HookName, O extends HookOptions>(hook: T, handler: HookHandler<T>, options: O): HookUnregister; // prettier-ignore
234 // Overload: no handler options
235 on<T extends HookName>(hook: T, handler: HookHandler<T>): HookUnregister; // prettier-ignore
236 // Implementation
237 on<T extends HookName, O extends HookOptions>(
238 hook: T,
239 handler: O['replace'] extends true ? HookDefaultHandler<T> : HookHandler<T>,
240 options: Partial<O> = {}
241 ): HookUnregister {
242 const ledger = this.get(hook);
243 if (!ledger) {
244 console.warn(`Hook '${hook}' not found.`);
245 return () => {};
246 }
247
248 const id = ledger.size + 1;
249 const registration: HookRegistration<T> = { ...options, id, hook, handler };
250 ledger.set(handler, registration);
251
252 return () => this.off(hook, handler);
253 }
254
255 /**
256 * Register a new hook handler to run before the default handler.
257 * Shortcut for `hooks.on(hook, handler, { before: true })`.
258 * @param hook Name of the hook to listen for
259 * @param handler The handler function to execute
260 * @param options Any other event options (see `hooks.on()` for details)
261 * @returns A function to unregister the handler
262 * @see on
263 */
264 // Overload: passed in handler options
265 before<T extends HookName>(hook: T, handler: HookHandler<T>, options: HookOptions): HookUnregister; // prettier-ignore
266 // Overload: no handler options
267 before<T extends HookName>(hook: T, handler: HookHandler<T>): HookUnregister;
268 // Implementation
269 before<T extends HookName>(
270 hook: T,
271 handler: HookHandler<T>,
272 options: HookOptions = {}
273 ): HookUnregister {
274 return this.on(hook, handler, { ...options, before: true });
275 }
276
277 /**
278 * Register a new hook handler to replace the default handler.
279 * Shortcut for `hooks.on(hook, handler, { replace: true })`.
280 * @param hook Name of the hook to listen for
281 * @param handler The handler function to execute instead of the default handler
282 * @param options Any other event options (see `hooks.on()` for details)
283 * @returns A function to unregister the handler
284 * @see on
285 */
286 // Overload: passed in handler options
287 replace<T extends HookName>(hook: T, handler: HookDefaultHandler<T>, options: HookOptions): HookUnregister; // prettier-ignore
288 // Overload: no handler options
289 replace<T extends HookName>(hook: T, handler: HookDefaultHandler<T>): HookUnregister; // prettier-ignore
290 // Implementation
291 replace<T extends HookName>(
292 hook: T,
293 handler: HookDefaultHandler<T>,
294 options: HookOptions = {}
295 ): HookUnregister {
296 return this.on(hook, handler, { ...options, replace: true });
297 }
298
299 /**
300 * Register a new hook handler to run once.
301 * Shortcut for `hooks.on(hook, handler, { once: true })`.
302 * @param hook Name of the hook to listen for
303 * @param handler The handler function to execute
304 * @param options Any other event options (see `hooks.on()` for details)
305 * @see on
306 */
307 // Overload: passed in handler options
308 once<T extends HookName>(hook: T, handler: HookHandler<T>, options: HookOptions): HookUnregister; // prettier-ignore
309 // Overload: no handler options
310 once<T extends HookName>(hook: T, handler: HookHandler<T>): HookUnregister;
311 // Implementation
312 once<T extends HookName>(
313 hook: T,
314 handler: HookHandler<T>,
315 options: HookOptions = {}
316 ): HookUnregister {
317 return this.on(hook, handler, { ...options, once: true });
318 }
319
320 /**
321 * Unregister a hook handler.
322 * @param hook Name of the hook the handler is registered for
323 * @param handler The handler function that was registered.
324 * If omitted, all handlers for the hook will be removed.
325 */
326 // Overload: unregister a specific handler
327 off<T extends HookName>(hook: T, handler: HookHandler<T> | HookDefaultHandler<T>): void;
328 // Overload: unregister all handlers
329 off<T extends HookName>(hook: T): void;
330 // Implementation
331 off<T extends HookName>(hook: T, handler?: HookHandler<T> | HookDefaultHandler<T>): void {
332 const ledger = this.get(hook);
333 if (ledger && handler) {
334 const deleted = ledger.delete(handler);
335 if (!deleted) {
336 console.warn(`Handler for hook '${hook}' not found.`);
337 }
338 } else if (ledger) {
339 ledger.clear();
340 }
341 }
342
343 /**
344 * Trigger a hook asynchronously, executing its default handler and all registered handlers.
345 * Will execute all handlers in order and `await` any `Promise`s they return.
346 * @param hook Name of the hook to trigger
347 * @param visit The visit object this hook belongs to
348 * @param args Arguments to pass to the handler
349 * @param defaultHandler A default implementation of this hook to execute
350 * @returns The resolved return value of the executed default handler
351 */
352 // Overload: default order of arguments
353 async call<T extends HookName>(hook: T, visit: Visit | undefined, args: HookArguments<T>, defaultHandler?: HookDefaultHandler<T>): Promise<Awaited<ReturnType<HookDefaultHandler<T>>>>; // prettier-ignore
354 // Overload: legacy order of arguments, with visit missing
355 async call<T extends HookName>(hook: T, args: HookArguments<T>, defaultHandler?: HookDefaultHandler<T>): Promise<Awaited<ReturnType<HookDefaultHandler<T>>>>; // prettier-ignore
356 // Implementation
357 async call<T extends HookName>(
358 hook: T,
359 arg1: Visit | HookArguments<T>,
360 arg2: HookArguments<T> | HookDefaultHandler<T>,
361 arg3?: HookDefaultHandler<T>
362 ): Promise<Awaited<ReturnType<HookDefaultHandler<T>>>> {
363 const [visit, args, defaultHandler] = this.parseCallArgs(hook, arg1, arg2, arg3);
364
365 const { before, handler, after } = this.getHandlers(hook, defaultHandler);
366 await this.run(before, visit, args);
367 const [result] = await this.run(handler, visit, args, true);
368 await this.run(after, visit, args);
369 this.dispatchDomEvent(hook, visit, args);
370 return result;
371 }
372
373 /**
374 * Trigger a hook synchronously, executing its default handler and all registered handlers.
375 * Will execute all handlers in order, but will **not** `await` any `Promise`s they return.
376 * @param hook Name of the hook to trigger
377 * @param visit The visit object this hook belongs to
378 * @param args Arguments to pass to the handler
379 * @param defaultHandler A default implementation of this hook to execute
380 * @returns The (possibly unresolved) return value of the executed default handler
381 */
382 // Overload: default order of arguments
383 callSync<T extends HookName>(hook: T, visit: Visit | undefined, args: HookArguments<T>, defaultHandler?: HookDefaultHandler<T>): ReturnType<HookDefaultHandler<T>>; // prettier-ignore
384 // Overload: legacy order of arguments, with visit missing
385 callSync<T extends HookName>(hook: T, args: HookArguments<T>, defaultHandler?: HookDefaultHandler<T>): ReturnType<HookDefaultHandler<T>>; // prettier-ignore
386 // Implementation
387 callSync<T extends HookName>(
388 hook: T,
389 arg1: Visit | HookArguments<T>,
390 arg2: HookArguments<T> | HookDefaultHandler<T>,
391 arg3?: HookDefaultHandler<T>
392 ): ReturnType<HookDefaultHandler<T>> {
393 const [visit, args, defaultHandler] = this.parseCallArgs(hook, arg1, arg2, arg3);
394 const { before, handler, after } = this.getHandlers(hook, defaultHandler);
395 this.runSync(before, visit, args);
396 const [result] = this.runSync(handler, visit, args, true);
397 this.runSync(after, visit, args);
398 this.dispatchDomEvent(hook, visit, args);
399 return result;
400 }
401
402 /**
403 * Parse the call arguments for call() and callSync() to allow legacy argument order.
404 */
405 protected parseCallArgs<T extends HookName>(
406 hook: T,
407 arg1: Visit | HookArguments<T> | undefined,
408 arg2: HookArguments<T> | HookDefaultHandler<T>,
409 arg3?: HookDefaultHandler<T>
410 ): [Visit | undefined, HookArguments<T>, HookDefaultHandler<T> | undefined] {
411 const isLegacyOrder =
412 !(arg1 instanceof Visit) && (typeof arg1 === 'object' || typeof arg2 === 'function');
413 if (isLegacyOrder) {
414 // Legacy positioning: arguments in second or handler passed in third place
415 return [undefined, arg1 as HookArguments<T>, arg2 as HookDefaultHandler<T>];
416 } else {
417 // Default positioning: visit passed in as first argument
418 return [arg1, arg2 as HookArguments<T>, arg3];
419 }
420 }
421
422 /**
423 * Execute the handlers for a hook, in order, as `Promise`s that will be `await`ed.
424 * @param registrations The registrations (handler + options) to execute
425 * @param args Arguments to pass to the handler
426 */
427
428 // Overload: running HookDefaultHandler: expect HookDefaultHandler return type
429 protected async run<T extends HookName>(registrations: HookRegistration<T, HookDefaultHandler<T>>[], visit: Visit | undefined, args: HookArguments<T>, rethrow: true): Promise<Awaited<ReturnType<HookDefaultHandler<T>>>[]>; // prettier-ignore
430 // Overload: running user handler: expect no specific type
431 protected async run<T extends HookName>(registrations: HookRegistration<T>[], visit: Visit | undefined, args: HookArguments<T>): Promise<unknown[]>; // prettier-ignore
432 // Implementation
433 protected async run<T extends HookName, R extends HookRegistration<T>[]>(
434 registrations: R,
435 visit: Visit | undefined = this.swup.visit,
436 args: HookArguments<T>,
437 rethrow: boolean = false
438 ): Promise<Awaited<ReturnType<HookDefaultHandler<T>>> | unknown[]> {
439 const results = [];
440 for (const { hook, handler, defaultHandler, once } of registrations) {
441 if (visit?.done) continue;
442 if (once) this.off(hook, handler);
443 try {
444 const result = await runAsPromise(handler, [visit, args, defaultHandler]);
445 results.push(result);
446 } catch (error) {
447 if (rethrow) {
448 throw error;
449 } else {
450 console.error(`Error in hook '${hook}':`, error);
451 }
452 }
453 }
454 return results;
455 }
456
457 /**
458 * Execute the handlers for a hook, in order, without `await`ing any returned `Promise`s.
459 * @param registrations The registrations (handler + options) to execute
460 * @param args Arguments to pass to the handler
461 */
462
463 // Overload: running HookDefaultHandler: expect HookDefaultHandler return type
464 protected runSync<T extends HookName>(registrations: HookRegistration<T, HookDefaultHandler<T>>[], visit: Visit | undefined, args: HookArguments<T>, rethrow: true): ReturnType<HookDefaultHandler<T>>[]; // prettier-ignore
465 // Overload: running user handler: expect no specific type
466 protected runSync<T extends HookName>(registrations: HookRegistration<T>[], visit: Visit | undefined, args: HookArguments<T>): unknown[]; // prettier-ignore
467 // Implementation
468 protected runSync<T extends HookName, R extends HookRegistration<T>[]>(
469 registrations: R,
470 visit: Visit | undefined = this.swup.visit,
471 args: HookArguments<T>,
472 rethrow: boolean = false
473 ): (ReturnType<HookDefaultHandler<T>> | unknown)[] {
474 const results = [];
475 for (const { hook, handler, defaultHandler, once } of registrations) {
476 if (visit?.done) continue;
477 if (once) this.off(hook, handler);
478 try {
479 const result = (handler as HookDefaultHandler<T>)(visit, args, defaultHandler);
480 results.push(result);
481 if (isPromise(result)) {
482 console.warn(
483 `Swup will not await Promises in handler for synchronous hook '${hook}'.`
484 );
485 }
486 } catch (error) {
487 if (rethrow) {
488 throw error;
489 } else {
490 console.error(`Error in hook '${hook}':`, error);
491 }
492 }
493 }
494 return results;
495 }
496
497 /**
498 * Get all registered handlers for a hook, sorted by priority and registration order.
499 * @param hook Name of the hook
500 * @param defaultHandler The optional default handler of this hook
501 * @returns An object with the handlers sorted into `before` and `after` arrays,
502 * as well as a flag indicating if the original handler was replaced
503 */
504 protected getHandlers<T extends HookName>(hook: T, defaultHandler?: HookDefaultHandler<T>) {
505 const ledger = this.get(hook);
506 if (!ledger) {
507 return { found: false, before: [], handler: [], after: [], replaced: false };
508 }
509
510 const registrations = Array.from(ledger.values());
511
512 // Let TypeScript know that replaced handlers are default handlers by filtering to true
513 const def = (T: HookRegistration<T>): T is HookRegistration<T, HookDefaultHandler<T>> => true; // prettier-ignore
514 const sort = this.sortRegistrations;
515
516 // Filter into before, after, and replace handlers
517 const before = registrations.filter(({ before, replace }) => before && !replace).sort(sort);
518 const replace = registrations.filter(({ replace }) => replace).filter(def).sort(sort); // prettier-ignore
519 const after = registrations.filter(({ before, replace }) => !before && !replace).sort(sort);
520 const replaced = replace.length > 0;
521
522 // Define main handler registration
523 // Created as HookRegistration[] array to allow passing it into hooks.run() directly
524 let handler: HookRegistration<T, HookDefaultHandler<T>>[] = [];
525 if (defaultHandler) {
526 handler = [{ id: 0, hook, handler: defaultHandler }];
527 if (replaced) {
528 const index = replace.length - 1;
529 const { handler: replacingHandler, once } = replace[index];
530 const createDefaultHandler = (index: number): HookDefaultHandler<T> | undefined => {
531 const next = replace[index - 1];
532 if (next) {
533 return (visit, args) =>
534 next.handler(visit, args, createDefaultHandler(index - 1));
535 } else {
536 return defaultHandler;
537 }
538 };
539 const nestedDefaultHandler = createDefaultHandler(index);
540 handler = [{ id: 0, hook, once, handler: replacingHandler, defaultHandler: nestedDefaultHandler }]; // prettier-ignore
541 }
542 }
543
544 return { found: true, before, handler, after, replaced };
545 }
546
547 /**
548 * Sort two hook registrations by priority and registration order.
549 * @param a The registration object to compare
550 * @param b The other registration object to compare with
551 * @returns The sort direction
552 */
553 protected sortRegistrations<T extends HookName>(
554 a: HookRegistration<T>,
555 b: HookRegistration<T>
556 ): number {
557 const priority = (a.priority ?? 0) - (b.priority ?? 0);
558 const id = a.id - b.id;
559 return priority || id || 0;
560 }
561
562 /**
563 * Dispatch a custom event on the `document` for a hook. Prefixed with `swup:`
564 * @param hook Name of the hook.
565 */
566 protected dispatchDomEvent<T extends HookName>(
567 hook: T,
568 visit: Visit | undefined,
569 args?: HookArguments<T>
570 ): void {
571 if (visit?.done) return;
572
573 const detail: HookEventDetail = { hook, args, visit: visit || this.swup.visit };
574 document.dispatchEvent(
575 new CustomEvent<HookEventDetail>(`swup:any`, { detail, bubbles: true })
576 );
577 document.dispatchEvent(
578 new CustomEvent<HookEventDetail>(`swup:${hook}`, { detail, bubbles: true })
579 );
580 }
581
582 /**
583 * Parse a hook name into the name and any modifiers.
584 * @param hook Name of the hook.
585 */
586 parseName(hook: HookName | HookNameWithModifier): [HookName, Partial<HookOptions>] {
587 const [name, ...modifiers] = hook.split('.');
588 const options = modifiers.reduce((acc, mod) => ({ ...acc, [mod]: true }), {});
589 return [name as HookName, options];
590 }
591 }