@wordpress/interactivity-router 2.24.0 → 2.26.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +22 -0
  3. package/build/assets/dynamic-importmap/fetch.js +60 -0
  4. package/build/assets/dynamic-importmap/fetch.js.map +1 -0
  5. package/build/assets/dynamic-importmap/index.js +91 -0
  6. package/build/assets/dynamic-importmap/index.js.map +1 -0
  7. package/build/assets/dynamic-importmap/loader.js +286 -0
  8. package/build/assets/dynamic-importmap/loader.js.map +1 -0
  9. package/build/assets/dynamic-importmap/resolver.js +220 -0
  10. package/build/assets/dynamic-importmap/resolver.js.map +1 -0
  11. package/build/assets/script-modules.js +64 -0
  12. package/build/assets/script-modules.js.map +1 -0
  13. package/build/assets/scs.js +62 -0
  14. package/build/assets/scs.js.map +1 -0
  15. package/build/assets/styles.js +246 -0
  16. package/build/assets/styles.js.map +1 -0
  17. package/build/full-page.js +43 -0
  18. package/build/full-page.js.map +1 -0
  19. package/build/index.js +141 -112
  20. package/build/index.js.map +1 -1
  21. package/build-module/assets/dynamic-importmap/fetch.js +54 -0
  22. package/build-module/assets/dynamic-importmap/fetch.js.map +1 -0
  23. package/build-module/assets/dynamic-importmap/index.js +72 -0
  24. package/build-module/assets/dynamic-importmap/index.js.map +1 -0
  25. package/build-module/assets/dynamic-importmap/loader.js +279 -0
  26. package/build-module/assets/dynamic-importmap/loader.js.map +1 -0
  27. package/build-module/assets/dynamic-importmap/resolver.js +213 -0
  28. package/build-module/assets/dynamic-importmap/resolver.js.map +1 -0
  29. package/build-module/assets/script-modules.js +55 -0
  30. package/build-module/assets/script-modules.js.map +1 -0
  31. package/build-module/assets/scs.js +56 -0
  32. package/build-module/assets/scs.js.map +1 -0
  33. package/build-module/assets/styles.js +235 -0
  34. package/build-module/assets/styles.js.map +1 -0
  35. package/build-module/full-page.js +39 -0
  36. package/build-module/full-page.js.map +1 -0
  37. package/build-module/index.js +138 -107
  38. package/build-module/index.js.map +1 -1
  39. package/build-types/assets/dynamic-importmap/fetch.d.ts +30 -0
  40. package/build-types/assets/dynamic-importmap/fetch.d.ts.map +1 -0
  41. package/build-types/assets/dynamic-importmap/index.d.ts +42 -0
  42. package/build-types/assets/dynamic-importmap/index.d.ts.map +1 -0
  43. package/build-types/assets/dynamic-importmap/loader.d.ts +68 -0
  44. package/build-types/assets/dynamic-importmap/loader.d.ts.map +1 -0
  45. package/build-types/assets/dynamic-importmap/resolver.d.ts +35 -0
  46. package/build-types/assets/dynamic-importmap/resolver.d.ts.map +1 -0
  47. package/build-types/assets/script-modules.d.ts +26 -0
  48. package/build-types/assets/script-modules.d.ts.map +1 -0
  49. package/build-types/assets/scs.d.ts +24 -0
  50. package/build-types/assets/scs.d.ts.map +1 -0
  51. package/build-types/assets/styles.d.ts +69 -0
  52. package/build-types/assets/styles.d.ts.map +1 -0
  53. package/build-types/full-page.d.ts +3 -0
  54. package/build-types/full-page.d.ts.map +1 -0
  55. package/build-types/index.d.ts +4 -5
  56. package/build-types/index.d.ts.map +1 -1
  57. package/package.json +9 -5
  58. package/src/assets/dynamic-importmap/fetch.ts +58 -0
  59. package/src/assets/dynamic-importmap/index.ts +87 -0
  60. package/src/assets/dynamic-importmap/loader.ts +366 -0
  61. package/src/assets/dynamic-importmap/resolver.ts +292 -0
  62. package/src/assets/script-modules.ts +69 -0
  63. package/src/assets/scs.ts +61 -0
  64. package/src/assets/styles.ts +272 -0
  65. package/src/assets/test/scs.test.ts +367 -0
  66. package/src/assets/test/styles.test.ts +758 -0
  67. package/src/full-page.ts +53 -0
  68. package/src/index.ts +160 -135
  69. package/tsconfig.full-page.json +12 -0
  70. package/tsconfig.full-page.tsbuildinfo +1 -0
  71. package/tsconfig.json +9 -4
  72. package/tsconfig.main.json +21 -0
  73. package/tsconfig.main.tsbuildinfo +1 -0
  74. package/build/head.js +0 -113
  75. package/build/head.js.map +0 -1
  76. package/build-module/head.js +0 -103
  77. package/build-module/head.js.map +0 -1
  78. package/build-types/head.d.ts +0 -24
  79. package/build-types/head.d.ts.map +0 -1
  80. package/src/head.ts +0 -126
  81. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Internal dependencies
3
+ */
4
+ import {
5
+ initialImportMap,
6
+ importPreloadedModule,
7
+ preloadWithMap,
8
+ type ModuleLoad,
9
+ } from './dynamic-importmap';
10
+
11
+ /**
12
+ * IDs of modules that should be resolved by the browser rather than
13
+ * processed internally.
14
+ */
15
+ const resolvedScriptModules = new Set< string >();
16
+
17
+ /**
18
+ * Marks the specified module as natively resolved.
19
+ * @param url Script module URL.
20
+ */
21
+ export const markScriptModuleAsResolved = ( url: string ) => {
22
+ resolvedScriptModules.add( url );
23
+ };
24
+
25
+ /**
26
+ * Resolves and fetches modules present in the passed document, using the
27
+ * document's import map to resolve them.
28
+ *
29
+ * @param doc Document containing the modules to preload.
30
+ * @return Array of promises that resolve to a `ScriptModuleLoad` instance.
31
+ */
32
+ export const preloadScriptModules = ( doc: Document ) => {
33
+ // Extract the import map from the document.
34
+ const importMapElement = doc.querySelector< HTMLScriptElement >(
35
+ 'script#wp-importmap[type=importmap]'
36
+ );
37
+ const importMap = importMapElement
38
+ ? JSON.parse( importMapElement.text )
39
+ : { imports: {}, scopes: {} };
40
+
41
+ // Remove imports also in the initial page's import map.
42
+ // Those should be handled natively.
43
+ for ( const key in initialImportMap.imports ) {
44
+ delete importMap.imports[ key ];
45
+ }
46
+
47
+ // Get the URL of all modules contained in the document.
48
+ const moduleUrls = [
49
+ ...doc.querySelectorAll< HTMLScriptElement >(
50
+ 'script[type=module][src]'
51
+ ),
52
+ ].map( ( s ) => s.src );
53
+
54
+ // Resolve and fetch those not resolved natively.
55
+ return moduleUrls
56
+ .filter( ( url ) => ! resolvedScriptModules.has( url ) )
57
+ .map( ( url ) => preloadWithMap( url, importMap ) );
58
+ };
59
+
60
+ /**
61
+ * Imports modules respresented by the passed `ScriptModuleLoad` instances.
62
+ *
63
+ * @param modules Array of `MoudleLoad` instances.
64
+ * @return Promise that resolves once all modules are imported.
65
+ */
66
+ export const importScriptModules = ( modules: ScriptModuleLoad[] ) =>
67
+ Promise.all( modules.map( ( m ) => importPreloadedModule( m ) ) );
68
+
69
+ export type ScriptModuleLoad = ModuleLoad;
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Calculates the Shortest Common Supersequence (SCS) of two sequences.
3
+ *
4
+ * A supersequence is a sequence that contains both input sequences as subsequences.
5
+ * The shortest common supersequence is the shortest possible such sequence.
6
+ *
7
+ * This implementation uses dynamic programming with a time complexity of O(mn)
8
+ * and space complexity of O(mn), where m and n are the lengths of sequences X and Y.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const seq1 = [1, 3, 5];
13
+ * const seq2 = [2, 3, 4];
14
+ * const scs = shortestCommonSupersequence(seq1, seq2); // [1, 2, 3, 4, 5]
15
+ * ```
16
+ *
17
+ * @param X The first sequence.
18
+ * @param Y The second sequence.
19
+ * @param isEqual Optional equality function to compare elements.
20
+ * Defaults to strict equality (===).
21
+ * @return The shortest common supersequence of X and Y.
22
+ */
23
+ export function shortestCommonSupersequence< E = unknown >(
24
+ X: E[],
25
+ Y: E[],
26
+ isEqual = ( a: E, b: E ) => a === b
27
+ ) {
28
+ const m = X.length;
29
+ const n = Y.length;
30
+
31
+ // Create a 2D dp table where dp[i][j] is the SCS for X[0..i-1] and Y[0..j-1].
32
+ const dp: E[][][] = Array.from( { length: m + 1 }, () =>
33
+ Array( n + 1 ).fill( null )
34
+ );
35
+
36
+ // Base cases: one of the sequences is empty.
37
+ for ( let i = 0; i <= m; i++ ) {
38
+ dp[ i ][ 0 ] = X.slice( 0, i );
39
+ }
40
+ for ( let j = 0; j <= n; j++ ) {
41
+ dp[ 0 ][ j ] = Y.slice( 0, j );
42
+ }
43
+
44
+ // Fill in the dp table.
45
+ for ( let i = 1; i <= m; i++ ) {
46
+ for ( let j = 1; j <= n; j++ ) {
47
+ if ( isEqual( X[ i - 1 ], Y[ j - 1 ] ) ) {
48
+ // When X[i-1] equals Y[j-1], use the reference from X.
49
+ dp[ i ][ j ] = dp[ i - 1 ][ j - 1 ].concat( X[ i - 1 ] );
50
+ } else {
51
+ // Choose the shorter option between appending X[i-1] or Y[j-1].
52
+ const option1 = dp[ i - 1 ][ j ].concat( X[ i - 1 ] );
53
+ const option2 = dp[ i ][ j - 1 ].concat( Y[ j - 1 ] );
54
+ dp[ i ][ j ] =
55
+ option1.length <= option2.length ? option1 : option2;
56
+ }
57
+ }
58
+ }
59
+
60
+ return dp[ m ][ n ];
61
+ }
@@ -0,0 +1,272 @@
1
+ /**
2
+ * Internal dependencies
3
+ */
4
+ import { shortestCommonSupersequence } from './scs';
5
+
6
+ export type StyleElement = HTMLLinkElement | HTMLStyleElement;
7
+
8
+ /**
9
+ * Compares the passed style or link elements to check if they can be
10
+ * considered equal.
11
+ *
12
+ * @param a `<style>` or `<link>` element.
13
+ * @param b `<style>` or `<link>` element.
14
+ * @return Whether they are considered equal.
15
+ */
16
+ const areNodesEqual = ( a: StyleElement, b: StyleElement ): boolean =>
17
+ a.isEqualNode( b );
18
+
19
+ /**
20
+ * Normalizes the passed style or link element, reverting the changes
21
+ * made by {@link prepareStylePromise|`prepareStylePromise`} to the
22
+ * `data-original-media` and `media`.
23
+ *
24
+ * @example
25
+ * The following elements should be normalized to the same element:
26
+ * ```html
27
+ * <link rel="stylesheet" src="./assets/styles.css">
28
+ * <link rel="stylesheet" src="./assets/styles.css" media="all">
29
+ * <link rel="stylesheet" src="./assets/styles.css" media="preload">
30
+ * <link rel="stylesheet" src="./assets/styles.css" media="preload" data-original-media="all">
31
+ * ```
32
+ *
33
+ * @param element `<style>` or `<link>` element.
34
+ * @return Normalized node.
35
+ */
36
+ export const normalizeMedia = ( element: StyleElement ): StyleElement => {
37
+ element = element.cloneNode( true ) as StyleElement;
38
+ const media = element.media;
39
+ const { originalMedia } = element.dataset;
40
+
41
+ if ( media === 'preload' ) {
42
+ element.media = originalMedia || 'all';
43
+ element.removeAttribute( 'data-original-media' );
44
+ } else if ( ! element.media ) {
45
+ element.media = 'all';
46
+ }
47
+ return element;
48
+ };
49
+
50
+ /**
51
+ * Adds the minimum style elements from Y around those in X using a
52
+ * shortest common supersequence algorithm, returning a list of
53
+ * promises for all the elements in Y.
54
+ *
55
+ * If X is empty, it appends all elements in Y to the passed parent
56
+ * element or to `document.head` instead.
57
+ *
58
+ * The returned promises resolve once the corresponding style element
59
+ * is loaded and ready. Those elements that are also in X return a
60
+ * cached promise.
61
+ *
62
+ * The algorithm ensures that the final style elements present in the
63
+ * document (or the passed `parent` element) are in the correct order
64
+ * and they are included in either X or Y.
65
+ *
66
+ * @param X Base list of style elements.
67
+ * @param Y List of style elements.
68
+ * @param parent Optional parent element to append to the new style elements.
69
+ * @return List of promises that resolve once the elements in Y are ready.
70
+ */
71
+ export function updateStylesWithSCS(
72
+ X: StyleElement[],
73
+ Y: StyleElement[],
74
+ parent: Element = window.document.head
75
+ ) {
76
+ if ( X.length === 0 ) {
77
+ return Y.map( ( element ) => {
78
+ const promise = prepareStylePromise( element );
79
+ parent.appendChild( element );
80
+ return promise;
81
+ } );
82
+ }
83
+
84
+ // Create normalized arrays for comparison.
85
+ const xNormalized = X.map( normalizeMedia );
86
+ const yNormalized = Y.map( normalizeMedia );
87
+
88
+ // The `scs` array contains normalized elements.
89
+ const scs = shortestCommonSupersequence(
90
+ xNormalized,
91
+ yNormalized,
92
+ areNodesEqual
93
+ );
94
+ const xLength = X.length;
95
+ const yLength = Y.length;
96
+ const promises = [];
97
+ let last = X[ xLength - 1 ];
98
+ let xIndex = 0;
99
+ let yIndex = 0;
100
+
101
+ for ( const scsElement of scs ) {
102
+ // Actual elements that will end up in the DOM.
103
+ const xElement = X[ xIndex ];
104
+ const yElement = Y[ yIndex ];
105
+ // Normalized elements for comparison.
106
+ const xNormEl = xNormalized[ xIndex ];
107
+ const yNormEl = yNormalized[ yIndex ];
108
+ if ( xIndex < xLength && areNodesEqual( xNormEl, scsElement ) ) {
109
+ if ( yIndex < yLength && areNodesEqual( yNormEl, scsElement ) ) {
110
+ promises.push( prepareStylePromise( xElement ) );
111
+ yIndex++;
112
+ }
113
+ xIndex++;
114
+ } else {
115
+ promises.push( prepareStylePromise( yElement ) );
116
+ if ( xIndex < xLength ) {
117
+ xElement.before( yElement );
118
+ } else {
119
+ last.after( yElement );
120
+ last = yElement;
121
+ }
122
+ yIndex++;
123
+ }
124
+ }
125
+
126
+ return promises;
127
+ }
128
+
129
+ /**
130
+ * Cache of promises per style elements.
131
+ *
132
+ * Each style element has their own associated `Promise` that resolves
133
+ * once the element has been loaded and is ready.
134
+ */
135
+ const stylePromiseCache = new WeakMap<
136
+ StyleElement,
137
+ Promise< StyleElement >
138
+ >();
139
+
140
+ /**
141
+ * Prepares and returns the corresponding `Promise` for the passed style
142
+ * element.
143
+ *
144
+ * It returns the cached promise if it exists. Otherwise, constructs
145
+ * a `Promise` that resolves once the element has finished loading.
146
+ *
147
+ * For those elements that are not in the DOM yet, this function
148
+ * injects a `media="preload"` attribute to the passed element so the
149
+ * style is loaded without applying any styles to the document.
150
+ *
151
+ * @param element Style element.
152
+ * @return The associated `Promise` to the passed element.
153
+ */
154
+ const prepareStylePromise = (
155
+ element: StyleElement
156
+ ): Promise< StyleElement > => {
157
+ if ( stylePromiseCache.has( element ) ) {
158
+ return stylePromiseCache.get( element );
159
+ }
160
+
161
+ // When the element exists in the main document and its media attribute
162
+ // is not "preload", that means the element comes from the initial page.
163
+ // The `media` attribute doesn't need to be handled in this case.
164
+ if ( window.document.contains( element ) && element.media !== 'preload' ) {
165
+ const promise = Promise.resolve( element );
166
+ stylePromiseCache.set( element, promise );
167
+ return promise;
168
+ }
169
+
170
+ if ( element.hasAttribute( 'media' ) && element.media !== 'all' ) {
171
+ element.dataset.originalMedia = element.media;
172
+ }
173
+
174
+ element.media = 'preload';
175
+
176
+ if ( element instanceof HTMLStyleElement ) {
177
+ const promise = Promise.resolve( element );
178
+ stylePromiseCache.set( element, promise );
179
+ return promise;
180
+ }
181
+
182
+ const promise = new Promise< HTMLLinkElement >( ( resolve, reject ) => {
183
+ element.addEventListener( 'load', () => resolve( element ) );
184
+ element.addEventListener( 'error', ( event ) => {
185
+ const { href } = event.target as HTMLLinkElement;
186
+ reject(
187
+ Error(
188
+ `The style sheet with the following URL failed to load: ${ href }`
189
+ )
190
+ );
191
+ } );
192
+ } );
193
+
194
+ stylePromiseCache.set( element, promise );
195
+ return promise;
196
+ };
197
+
198
+ /**
199
+ * Cache of style promise lists per URL.
200
+ *
201
+ * It contains the list of style elements associated to the page with the
202
+ * passed URL. The original order is preserved to respect the CSS cascade.
203
+ *
204
+ * Each included promise resolves when the associated style element is ready.
205
+ */
206
+ const styleSheetCache = new Map< string, Promise< StyleElement >[] >();
207
+
208
+ /**
209
+ * Prepares all style elements contained in the passed document.
210
+ *
211
+ * This function calls {@link updateStylesWithSCS|`updateStylesWithSCS`}
212
+ * to insert only the minimum amount of style elements into the DOM, so
213
+ * those present in the passed document end up in the DOM while the order
214
+ * is respected.
215
+ *
216
+ * New appended style elements contain a `media=preload` attribute to
217
+ * make them effectively disabled until they are applied with the
218
+ * {@link applyStyles|`applyStyles`} function.
219
+ *
220
+ * @param doc Document instance.
221
+ * @param url URL for the passed document.
222
+ * @return A list of promises for each style element in the passed document.
223
+ */
224
+ export const preloadStyles = (
225
+ doc: Document,
226
+ url: string
227
+ ): Promise< StyleElement >[] => {
228
+ if ( ! styleSheetCache.has( url ) ) {
229
+ const currentStyleElements = Array.from(
230
+ window.document.querySelectorAll< StyleElement >(
231
+ 'style,link[rel=stylesheet]'
232
+ )
233
+ );
234
+ const newStyleElements = Array.from(
235
+ doc.querySelectorAll< StyleElement >( 'style,link[rel=stylesheet]' )
236
+ );
237
+
238
+ // Set styles in order.
239
+ const stylePromises = updateStylesWithSCS(
240
+ currentStyleElements,
241
+ newStyleElements
242
+ );
243
+
244
+ styleSheetCache.set( url, stylePromises );
245
+ }
246
+ return styleSheetCache.get( url );
247
+ };
248
+
249
+ /**
250
+ * Traverses all style elements in the DOM, enabling only those included
251
+ * in the passed list and disabling the others.
252
+ *
253
+ * If the style element has the `data-original-media` attribute, the
254
+ * original `media` value is restored.
255
+ *
256
+ * @param styles List of style elements to apply.
257
+ */
258
+ export const applyStyles = ( styles: StyleElement[] ) => {
259
+ window.document
260
+ .querySelectorAll( 'style,link[rel=stylesheet]' )
261
+ .forEach( ( el: HTMLLinkElement | HTMLStyleElement ) => {
262
+ if ( el.sheet ) {
263
+ if ( styles.includes( el ) ) {
264
+ const { originalMedia = 'all' } = el.dataset;
265
+ el.sheet.media.mediaText = originalMedia;
266
+ el.sheet.disabled = false;
267
+ } else {
268
+ el.sheet.disabled = true;
269
+ }
270
+ }
271
+ } );
272
+ };