@wordpress/interactivity-router 2.25.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 (74) hide show
  1. package/CHANGELOG.md +17 -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 +140 -38
  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 +142 -38
  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 +165 -45
  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/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,292 @@
1
+ /**
2
+ * This code is derived from the following projects:
3
+ *
4
+ * 1. dynamic-importmap (https://github.com/keller-mark/dynamic-importmap)
5
+ * 2. es-module-shims (https://github.com/guybedford/es-module-shims)
6
+ *
7
+ * The original implementation was created by Guy Bedford in es-module-shims,
8
+ * then adapted by Mark Keller in dynamic-importmap, and further modified
9
+ * for use in this project.
10
+ *
11
+ * Both projects are licensed under the MIT license.
12
+ *
13
+ * MIT License: https://opensource.org/licenses/MIT
14
+ */
15
+
16
+ const backslashRegEx = /\\/g;
17
+
18
+ function isURL( url: string ) {
19
+ if ( url.indexOf( ':' ) === -1 ) {
20
+ return false;
21
+ }
22
+ try {
23
+ new URL( url );
24
+ return true;
25
+ } catch ( _ ) {
26
+ return false;
27
+ }
28
+ }
29
+
30
+ function resolveIfNotPlainOrUrl( relUrl, parentUrl ) {
31
+ const hIdx = parentUrl.indexOf( '#' ),
32
+ qIdx = parentUrl.indexOf( '?' );
33
+ if ( hIdx + qIdx > -2 ) {
34
+ parentUrl = parentUrl.slice(
35
+ 0,
36
+ // eslint-disable-next-line no-nested-ternary
37
+ hIdx === -1 ? qIdx : qIdx === -1 || qIdx > hIdx ? hIdx : qIdx
38
+ );
39
+ }
40
+ if ( relUrl.indexOf( '\\' ) !== -1 ) {
41
+ relUrl = relUrl.replace( backslashRegEx, '/' );
42
+ }
43
+ // protocol-relative
44
+ if ( relUrl[ 0 ] === '/' && relUrl[ 1 ] === '/' ) {
45
+ return parentUrl.slice( 0, parentUrl.indexOf( ':' ) + 1 ) + relUrl;
46
+ }
47
+ // relative-url
48
+ else if (
49
+ ( relUrl[ 0 ] === '.' &&
50
+ ( relUrl[ 1 ] === '/' ||
51
+ ( relUrl[ 1 ] === '.' &&
52
+ ( relUrl[ 2 ] === '/' ||
53
+ ( relUrl.length === 2 && ( relUrl += '/' ) ) ) ) ||
54
+ ( relUrl.length === 1 && ( relUrl += '/' ) ) ) ) ||
55
+ relUrl[ 0 ] === '/'
56
+ ) {
57
+ const parentProtocol = parentUrl.slice(
58
+ 0,
59
+ parentUrl.indexOf( ':' ) + 1
60
+ );
61
+ // Disabled, but these cases will give inconsistent results for deep backtracking
62
+ //if (parentUrl[parentProtocol.length] !== '/')
63
+ // throw new Error('Cannot resolve');
64
+ // read pathname from parent URL
65
+ // pathname taken to be part after leading "/"
66
+ let pathname;
67
+ if ( parentUrl[ parentProtocol.length + 1 ] === '/' ) {
68
+ // resolving to a :// so we need to read out the auth and host
69
+ if ( parentProtocol !== 'file:' ) {
70
+ pathname = parentUrl.slice( parentProtocol.length + 2 );
71
+ pathname = pathname.slice( pathname.indexOf( '/' ) + 1 );
72
+ } else {
73
+ pathname = parentUrl.slice( 8 );
74
+ }
75
+ } else {
76
+ // resolving to :/ so pathname is the /... part
77
+ pathname = parentUrl.slice(
78
+ parentProtocol.length +
79
+ ( parentUrl[ parentProtocol.length ] === '/' )
80
+ );
81
+ }
82
+
83
+ if ( relUrl[ 0 ] === '/' ) {
84
+ return (
85
+ parentUrl.slice( 0, parentUrl.length - pathname.length - 1 ) +
86
+ relUrl
87
+ );
88
+ }
89
+
90
+ // join together and split for removal of .. and . segments
91
+ // looping the string instead of anything fancy for perf reasons
92
+ // '../../../../../z' resolved to 'x/y' is just 'z'
93
+ const segmented =
94
+ pathname.slice( 0, pathname.lastIndexOf( '/' ) + 1 ) + relUrl;
95
+
96
+ const output = [];
97
+ let segmentIndex = -1;
98
+ for ( let i = 0; i < segmented.length; i++ ) {
99
+ // busy reading a segment - only terminate on '/'
100
+ if ( segmentIndex !== -1 ) {
101
+ if ( segmented[ i ] === '/' ) {
102
+ output.push( segmented.slice( segmentIndex, i + 1 ) );
103
+ segmentIndex = -1;
104
+ }
105
+ continue;
106
+ }
107
+ // new segment - check if it is relative
108
+ else if ( segmented[ i ] === '.' ) {
109
+ // ../ segment
110
+ if (
111
+ segmented[ i + 1 ] === '.' &&
112
+ ( segmented[ i + 2 ] === '/' || i + 2 === segmented.length )
113
+ ) {
114
+ output.pop();
115
+ i += 2;
116
+ continue;
117
+ }
118
+ // ./ segment
119
+ else if (
120
+ segmented[ i + 1 ] === '/' ||
121
+ i + 1 === segmented.length
122
+ ) {
123
+ i += 1;
124
+ continue;
125
+ }
126
+ }
127
+ // it is the start of a new segment
128
+ while ( segmented[ i ] === '/' ) {
129
+ i++;
130
+ }
131
+ segmentIndex = i;
132
+ }
133
+ // finish reading out the last segment
134
+ if ( segmentIndex !== -1 ) {
135
+ output.push( segmented.slice( segmentIndex ) );
136
+ }
137
+ return (
138
+ parentUrl.slice( 0, parentUrl.length - pathname.length ) +
139
+ output.join( '' )
140
+ );
141
+ }
142
+ }
143
+
144
+ function resolveUrl( relUrl, parentUrl ) {
145
+ return (
146
+ resolveIfNotPlainOrUrl( relUrl, parentUrl ) ||
147
+ ( isURL( relUrl )
148
+ ? relUrl
149
+ : resolveIfNotPlainOrUrl( './' + relUrl, parentUrl ) )
150
+ );
151
+ }
152
+
153
+ function getMatch( path, matchObj ) {
154
+ if ( matchObj[ path ] ) {
155
+ return path;
156
+ }
157
+ let sepIndex = path.length;
158
+ do {
159
+ const segment = path.slice( 0, sepIndex + 1 );
160
+ if ( segment in matchObj ) {
161
+ return segment;
162
+ }
163
+ } while ( ( sepIndex = path.lastIndexOf( '/', sepIndex - 1 ) ) !== -1 );
164
+ }
165
+
166
+ function applyPackages( id, packages ) {
167
+ const pkgName = getMatch( id, packages );
168
+ if ( pkgName ) {
169
+ const pkg = packages[ pkgName ];
170
+ if ( pkg === null ) {
171
+ return;
172
+ }
173
+ return pkg + id.slice( pkgName.length );
174
+ }
175
+ }
176
+
177
+ function resolveImportMap( importMap, resolvedOrPlain, parentUrl ) {
178
+ let scopeUrl = parentUrl && getMatch( parentUrl, importMap.scopes );
179
+ while ( scopeUrl ) {
180
+ const packageResolution = applyPackages(
181
+ resolvedOrPlain,
182
+ importMap.scopes[ scopeUrl ]
183
+ );
184
+ if ( packageResolution ) {
185
+ return packageResolution;
186
+ }
187
+ scopeUrl = getMatch(
188
+ scopeUrl.slice( 0, scopeUrl.lastIndexOf( '/' ) ),
189
+ importMap.scopes
190
+ );
191
+ }
192
+ return (
193
+ applyPackages( resolvedOrPlain, importMap.imports ) ||
194
+ ( resolvedOrPlain.indexOf( ':' ) !== -1 && resolvedOrPlain )
195
+ );
196
+ }
197
+
198
+ function resolveAndComposePackages(
199
+ packages,
200
+ outPackages,
201
+ baseUrl,
202
+ parentMap
203
+ ) {
204
+ for ( const p in packages ) {
205
+ const resolvedLhs = resolveIfNotPlainOrUrl( p, baseUrl ) || p;
206
+ const target = packages[ p ];
207
+ if ( typeof target !== 'string' ) {
208
+ continue;
209
+ }
210
+ const mapped = resolveImportMap(
211
+ parentMap,
212
+ resolveIfNotPlainOrUrl( target, baseUrl ) || target,
213
+ baseUrl
214
+ );
215
+ if ( mapped ) {
216
+ outPackages[ resolvedLhs ] = mapped;
217
+ continue;
218
+ }
219
+ // console.warn(
220
+ // `Mapping "${ p }" -> "${ packages[ p ] }" does not resolve`
221
+ // );
222
+ }
223
+ }
224
+
225
+ function resolveAndComposeImportMap( json, baseUrl, parentMap ) {
226
+ const outMap = {
227
+ imports: Object.assign( {}, parentMap.imports ),
228
+ scopes: Object.assign( {}, parentMap.scopes ),
229
+ };
230
+
231
+ if ( json.imports ) {
232
+ resolveAndComposePackages(
233
+ json.imports,
234
+ outMap.imports,
235
+ baseUrl,
236
+ parentMap
237
+ );
238
+ }
239
+
240
+ if ( json.scopes ) {
241
+ for ( const s in json.scopes ) {
242
+ const resolvedScope = resolveUrl( s, baseUrl );
243
+ resolveAndComposePackages(
244
+ json.scopes[ s ],
245
+ outMap.scopes[ resolvedScope ] ||
246
+ ( outMap.scopes[ resolvedScope ] = {} ),
247
+ baseUrl,
248
+ parentMap
249
+ );
250
+ }
251
+ }
252
+
253
+ return outMap;
254
+ }
255
+
256
+ let importMap = { imports: {}, scopes: {} };
257
+
258
+ // TODO: check if this baseURI should change per document, and so
259
+ // it need to be passed as a parameter to methods like `resolve`.
260
+ const baseUrl = document.baseURI;
261
+ const pageBaseUrl = baseUrl;
262
+
263
+ /**
264
+ * Extends the internal dynamic import map with the passed one.
265
+ *
266
+ * @param importMapIn Import map.
267
+ * @param importMapIn.imports Imports declaration.
268
+ * @param importMapIn.scopes Scopes declaration.
269
+ */
270
+ export function addImportMap( importMapIn: {
271
+ imports?: Record< string, string >;
272
+ scopes?: Record< string, any >;
273
+ } ) {
274
+ importMap = resolveAndComposeImportMap(
275
+ importMapIn,
276
+ pageBaseUrl,
277
+ importMap
278
+ );
279
+ }
280
+
281
+ /**
282
+ * Resolves the URL of the passed module ID against the current internal
283
+ * dynamic import map.
284
+ *
285
+ * @param id Module ID.
286
+ * @param parentUrl Parent URL, in case the module ID is relative.
287
+ * @return Resolved module URL.
288
+ */
289
+ export function resolve( id: string, parentUrl: string ): string {
290
+ const urlResolved = resolveIfNotPlainOrUrl( id, parentUrl );
291
+ return resolveImportMap( importMap, urlResolved || id, parentUrl ) || id;
292
+ }
@@ -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
+ };