@wordpress/interactivity-router 2.8.5 → 2.10.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.
@@ -1,3 +1,8 @@
1
+ /**
2
+ * The cache of prefetched stylesheets and scripts.
3
+ */
4
+ export const headElements = new Map();
5
+
1
6
  /**
2
7
  * Helper to update only the necessary tags in the head.
3
8
  *
@@ -27,6 +32,11 @@ export const updateHead = async newHead => {
27
32
  toRemove.push(child);
28
33
  }
29
34
  }
35
+ await Promise.all([...headElements.entries()].filter(([, {
36
+ tag
37
+ }]) => tag.nodeName === 'SCRIPT').map(async ([url]) => {
38
+ await import(/* webpackIgnore: true */url);
39
+ }));
30
40
 
31
41
  // Prepare new assets.
32
42
  const toAppend = [...newHeadMap.values()];
@@ -40,57 +50,54 @@ export const updateHead = async newHead => {
40
50
  * Fetches and processes head assets (stylesheets and scripts) from a specified document.
41
51
  *
42
52
  * @async
43
- * @param doc The document from which to fetch head assets. It should support standard DOM querying methods.
44
- * @param headElements A map of head elements to modify tracking the URLs of already processed assets to avoid duplicates.
45
- * @param headElements.tag
46
- * @param headElements.text
53
+ * @param doc The document from which to fetch head assets. It should support standard DOM querying methods.
47
54
  *
48
55
  * @return Returns an array of HTML elements representing the head assets.
49
56
  */
50
- export const fetchHeadAssets = async (doc, headElements) => {
57
+ export const fetchHeadAssets = async doc => {
51
58
  const headTags = [];
52
- const assets = [{
53
- tagName: 'style',
54
- selector: 'link[rel=stylesheet]',
55
- attribute: 'href'
56
- }, {
57
- tagName: 'script',
58
- selector: 'script[src]',
59
- attribute: 'src'
60
- }];
61
- for (const asset of assets) {
62
- const {
63
- tagName,
64
- selector,
65
- attribute
66
- } = asset;
67
- const tags = doc.querySelectorAll(selector);
68
59
 
69
- // Use Promise.all to wait for fetch to complete
70
- await Promise.all(Array.from(tags).map(async tag => {
71
- const attributeValue = tag.getAttribute(attribute);
72
- if (!headElements.has(attributeValue)) {
73
- try {
74
- const response = await fetch(attributeValue);
75
- const text = await response.text();
76
- headElements.set(attributeValue, {
77
- tag,
78
- text
79
- });
80
- } catch (e) {
81
- // eslint-disable-next-line no-console
82
- console.error(e);
83
- }
84
- }
85
- const headElement = headElements.get(attributeValue);
86
- const element = doc.createElement(tagName);
87
- element.innerText = headElement.text;
88
- for (const attr of headElement.tag.attributes) {
89
- element.setAttribute(attr.name, attr.value);
60
+ // We only want to fetch module scripts because regular scripts (without
61
+ // `async` or `defer` attributes) can depend on the execution of other scripts.
62
+ // Scripts found in the head are blocking and must be executed in order.
63
+ const scripts = doc.querySelectorAll('script[type="module"][src]');
64
+ scripts.forEach(script => {
65
+ const src = script.getAttribute('src');
66
+ if (!headElements.has(src)) {
67
+ // add the <link> elements to prefetch the module scripts
68
+ const link = doc.createElement('link');
69
+ link.rel = 'modulepreload';
70
+ link.href = src;
71
+ document.head.append(link);
72
+ headElements.set(src, {
73
+ tag: script
74
+ });
75
+ }
76
+ });
77
+ const stylesheets = doc.querySelectorAll('link[rel=stylesheet]');
78
+ await Promise.all(Array.from(stylesheets).map(async tag => {
79
+ const href = tag.getAttribute('href');
80
+ if (!href) {
81
+ return;
82
+ }
83
+ if (!headElements.has(href)) {
84
+ try {
85
+ const response = await fetch(href);
86
+ const text = await response.text();
87
+ headElements.set(href, {
88
+ tag,
89
+ text
90
+ });
91
+ } catch (e) {
92
+ // eslint-disable-next-line no-console
93
+ console.error(e);
90
94
  }
91
- headTags.push(element);
92
- }));
93
- }
95
+ }
96
+ const headElement = headElements.get(href);
97
+ const styleElement = doc.createElement('style');
98
+ styleElement.textContent = headElement.text;
99
+ headTags.push(styleElement);
100
+ }));
94
101
  return [doc.querySelector('title'), ...doc.querySelectorAll('style'), ...headTags];
95
102
  };
96
103
  //# sourceMappingURL=head.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["updateHead","newHead","getTagId","tag","id","outerHTML","newHeadMap","Map","child","set","toRemove","document","head","children","nodeName","push","has","delete","toAppend","values","forEach","n","remove","append","fetchHeadAssets","doc","headElements","headTags","assets","tagName","selector","attribute","asset","tags","querySelectorAll","Promise","all","Array","from","map","attributeValue","getAttribute","response","fetch","text","e","console","error","headElement","get","element","createElement","innerText","attr","attributes","setAttribute","name","value","querySelector"],"sources":["@wordpress/interactivity-router/src/head.ts"],"sourcesContent":["/**\n * Helper to update only the necessary tags in the head.\n *\n * @async\n * @param newHead The head elements of the new page.\n */\nexport const updateHead = async ( newHead: HTMLHeadElement[] ) => {\n\t// Helper to get the tag id store in the cache.\n\tconst getTagId = ( tag: Element ) => tag.id || tag.outerHTML;\n\n\t// Map incoming head tags by their content.\n\tconst newHeadMap = new Map< string, Element >();\n\tfor ( const child of newHead ) {\n\t\tnewHeadMap.set( getTagId( child ), child );\n\t}\n\n\tconst toRemove: Element[] = [];\n\n\t// Detect nodes that should be added or removed.\n\tfor ( const child of document.head.children ) {\n\t\tconst id = getTagId( child );\n\t\t// Always remove styles and links as they might change.\n\t\tif ( child.nodeName === 'LINK' || child.nodeName === 'STYLE' ) {\n\t\t\ttoRemove.push( child );\n\t\t} else if ( newHeadMap.has( id ) ) {\n\t\t\tnewHeadMap.delete( id );\n\t\t} else if ( child.nodeName !== 'SCRIPT' && child.nodeName !== 'META' ) {\n\t\t\ttoRemove.push( child );\n\t\t}\n\t}\n\n\t// Prepare new assets.\n\tconst toAppend = [ ...newHeadMap.values() ];\n\n\t// Apply the changes.\n\ttoRemove.forEach( ( n ) => n.remove() );\n\tdocument.head.append( ...toAppend );\n};\n\n/**\n * Fetches and processes head assets (stylesheets and scripts) from a specified document.\n *\n * @async\n * @param doc The document from which to fetch head assets. It should support standard DOM querying methods.\n * @param headElements A map of head elements to modify tracking the URLs of already processed assets to avoid duplicates.\n * @param headElements.tag\n * @param headElements.text\n *\n * @return Returns an array of HTML elements representing the head assets.\n */\nexport const fetchHeadAssets = async (\n\tdoc: Document,\n\theadElements: Map< string, { tag: HTMLElement; text: string } >\n): Promise< HTMLElement[] > => {\n\tconst headTags = [];\n\tconst assets = [\n\t\t{\n\t\t\ttagName: 'style',\n\t\t\tselector: 'link[rel=stylesheet]',\n\t\t\tattribute: 'href',\n\t\t},\n\t\t{ tagName: 'script', selector: 'script[src]', attribute: 'src' },\n\t];\n\tfor ( const asset of assets ) {\n\t\tconst { tagName, selector, attribute } = asset;\n\t\tconst tags = doc.querySelectorAll<\n\t\t\tHTMLScriptElement | HTMLStyleElement\n\t\t>( selector );\n\n\t\t// Use Promise.all to wait for fetch to complete\n\t\tawait Promise.all(\n\t\t\tArray.from( tags ).map( async ( tag ) => {\n\t\t\t\tconst attributeValue = tag.getAttribute( attribute );\n\t\t\t\tif ( ! headElements.has( attributeValue ) ) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst response = await fetch( attributeValue );\n\t\t\t\t\t\tconst text = await response.text();\n\t\t\t\t\t\theadElements.set( attributeValue, {\n\t\t\t\t\t\t\ttag,\n\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t} );\n\t\t\t\t\t} catch ( e ) {\n\t\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\t\tconsole.error( e );\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst headElement = headElements.get( attributeValue );\n\t\t\t\tconst element = doc.createElement( tagName );\n\t\t\t\telement.innerText = headElement.text;\n\t\t\t\tfor ( const attr of headElement.tag.attributes ) {\n\t\t\t\t\telement.setAttribute( attr.name, attr.value );\n\t\t\t\t}\n\t\t\t\theadTags.push( element );\n\t\t\t} )\n\t\t);\n\t}\n\n\treturn [\n\t\tdoc.querySelector( 'title' ),\n\t\t...doc.querySelectorAll( 'style' ),\n\t\t...headTags,\n\t];\n};\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMA,UAAU,GAAG,MAAQC,OAA0B,IAAM;EACjE;EACA,MAAMC,QAAQ,GAAKC,GAAY,IAAMA,GAAG,CAACC,EAAE,IAAID,GAAG,CAACE,SAAS;;EAE5D;EACA,MAAMC,UAAU,GAAG,IAA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A9B,QAAQ,CAACZ,IAAI,CAAEmC,OAAQ,CAAC;IACzB,CAAE,CACH,CAAC;EACF;EAEA,OAAO,CACNzB,GAAG,CAACiC,aAAa,CAAE,OAAQ,CAAC,EAC5B,GAAGjC,GAAG,CAACS,gBAAgB,CAAE,OAAQ,CAAC,EAClC,GAAGP,QAAQ,CACX;AACF,CAAC","ignoreList":[]}
1
+ {"version":3,"names":["headElements","Map","updateHead","newHead","getTagId","tag","id","outerHTML","newHeadMap","child","set","toRemove","document","head","children","nodeName","push","has","delete","Promise","all","entries","filter","map","url","toAppend","values","forEach","n","remove","append","fetchHeadAssets","doc","headTags","scripts","querySelectorAll","script","src","getAttribute","link","createElement","rel","href","stylesheets","Array","from","response","fetch","text","e","console","error","headElement","get","styleElement","textContent","querySelector"],"sources":["@wordpress/interactivity-router/src/head.ts"],"sourcesContent":["/**\n * The cache of prefetched stylesheets and scripts.\n */\nexport const headElements = new Map<\n\tstring,\n\t{ tag: HTMLElement; text?: string }\n>();\n\n/**\n * Helper to update only the necessary tags in the head.\n *\n * @async\n * @param newHead The head elements of the new page.\n */\nexport const updateHead = async ( newHead: HTMLHeadElement[] ) => {\n\t// Helper to get the tag id store in the cache.\n\tconst getTagId = ( tag: Element ) => tag.id || tag.outerHTML;\n\n\t// Map incoming head tags by their content.\n\tconst newHeadMap = new Map< string, Element >();\n\tfor ( const child of newHead ) {\n\t\tnewHeadMap.set( getTagId( child ), child );\n\t}\n\n\tconst toRemove: Element[] = [];\n\n\t// Detect nodes that should be added or removed.\n\tfor ( const child of document.head.children ) {\n\t\tconst id = getTagId( child );\n\t\t// Always remove styles and links as they might change.\n\t\tif ( child.nodeName === 'LINK' || child.nodeName === 'STYLE' ) {\n\t\t\ttoRemove.push( child );\n\t\t} else if ( newHeadMap.has( id ) ) {\n\t\t\tnewHeadMap.delete( id );\n\t\t} else if ( child.nodeName !== 'SCRIPT' && child.nodeName !== 'META' ) {\n\t\t\ttoRemove.push( child );\n\t\t}\n\t}\n\n\tawait Promise.all(\n\t\t[ ...headElements.entries() ]\n\t\t\t.filter( ( [ , { tag } ] ) => tag.nodeName === 'SCRIPT' )\n\t\t\t.map( async ( [ url ] ) => {\n\t\t\t\tawait import( /* webpackIgnore: true */ url );\n\t\t\t} )\n\t);\n\n\t// Prepare new assets.\n\tconst toAppend = [ ...newHeadMap.values() ];\n\n\t// Apply the changes.\n\ttoRemove.forEach( ( n ) => n.remove() );\n\tdocument.head.append( ...toAppend );\n};\n\n/**\n * Fetches and processes head assets (stylesheets and scripts) from a specified document.\n *\n * @async\n * @param doc The document from which to fetch head assets. It should support standard DOM querying methods.\n *\n * @return Returns an array of HTML elements representing the head assets.\n */\nexport const fetchHeadAssets = async (\n\tdoc: Document\n): Promise< HTMLElement[] > => {\n\tconst headTags = [];\n\n\t// We only want to fetch module scripts because regular scripts (without\n\t// `async` or `defer` attributes) can depend on the execution of other scripts.\n\t// Scripts found in the head are blocking and must be executed in order.\n\tconst scripts = doc.querySelectorAll< HTMLScriptElement >(\n\t\t'script[type=\"module\"][src]'\n\t);\n\n\tscripts.forEach( ( script ) => {\n\t\tconst src = script.getAttribute( 'src' );\n\t\tif ( ! headElements.has( src ) ) {\n\t\t\t// add the <link> elements to prefetch the module scripts\n\t\t\tconst link = doc.createElement( 'link' );\n\t\t\tlink.rel = 'modulepreload';\n\t\t\tlink.href = src;\n\t\t\tdocument.head.append( link );\n\t\t\theadElements.set( src, { tag: script } );\n\t\t}\n\t} );\n\n\tconst stylesheets = doc.querySelectorAll< HTMLLinkElement >(\n\t\t'link[rel=stylesheet]'\n\t);\n\n\tawait Promise.all(\n\t\tArray.from( stylesheets ).map( async ( tag ) => {\n\t\t\tconst href = tag.getAttribute( 'href' );\n\t\t\tif ( ! href ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif ( ! headElements.has( href ) ) {\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await fetch( href );\n\t\t\t\t\tconst text = await response.text();\n\t\t\t\t\theadElements.set( href, {\n\t\t\t\t\t\ttag,\n\t\t\t\t\t\ttext,\n\t\t\t\t\t} );\n\t\t\t\t} catch ( e ) {\n\t\t\t\t\t// eslint-disable-next-line no-console\n\t\t\t\t\tconsole.error( e );\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst headElement = headElements.get( href );\n\t\t\tconst styleElement = doc.createElement( 'style' );\n\t\t\tstyleElement.textContent = headElement.text;\n\n\t\t\theadTags.push( styleElement );\n\t\t} )\n\t);\n\n\treturn [\n\t\tdoc.querySelector( 'title' ),\n\t\t...doc.querySelectorAll( 'style' ),\n\t\t...headTags,\n\t];\n};\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAO,MAAMA,YAAY,GAAG,IAAIC,GAAG,CAGjC,CAAC;;AAEH;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMC,UAAU,GAAG,MAAQC,OAA0B,IAAM;EACjE;EACA,MAAMC,QAAQ,GAAKC,GAAY,IAAMA,GAAG,CAACC,EAAE,IAAID,GAAG,CAACE,SAAS;;EAE5D;EACA,MAAMC,UAAU,GAAG,IAAIP,GAAG,CAAoB,CAAC;EAC/C,KAAM,MAAMQ,KAAK,IAAIN,OAAO,EAAG;IAC9BK,UAAU,CAACE,GAAG,CAAEN,QAAQ,CAAEK,KAAM,CAAC,EAAEA,KAAM,CAAC;EAC3C;EAEA,MAAME,QAAmB,GAAG,EAAE;;EAE9B;EACA,KAAM,MAAMF,KAAK,IAAIG,QAAQ,CAACC,IAAI,CAACC,QAAQ,EAAG;IAC7C,MAAMR,EAAE,GAAGF,QAAQ,CAAEK,KAAM,CAAC;IAC5B;IACA,IAAKA,KAAK,CAACM,QAAQ,KAAK,MAAM,IAAIN,KAAK,CAACM,QAAQ,KAAK,OAAO,EAAG;MAC9DJ,QAAQ,CAACK,IAAI,CAAEP,KAAM,CAAC;IACvB,CAAC,MAAM,IAAKD,UAAU,CAACS,GAAG,CAAEX,EAAG,CAAC,EAAG;MAClCE,UAAU,CAACU,MAAM,CAAEZ,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,OAAQ,CAAC,EAClC,GAAGF,QAAQ,CACX;AACF,CAAC","ignoreList":[]}
@@ -7,7 +7,7 @@ import { store, privateApis, getConfig } from '@wordpress/interactivity';
7
7
  /**
8
8
  * Internal dependencies
9
9
  */
10
- import { fetchHeadAssets, updateHead } from './head';
10
+ import { fetchHeadAssets, updateHead, headElements } from './head';
11
11
  const {
12
12
  directivePrefix,
13
13
  getRegionRootFragment,
@@ -23,7 +23,6 @@ const navigationMode = (_getConfig$navigation = getConfig('core/router').navigat
23
23
 
24
24
  // The cache of visited and prefetched pages, stylesheets and scripts.
25
25
  const pages = new Map();
26
- const headElements = new Map();
27
26
 
28
27
  // Helper to remove domain and hash from the URL. We are only interesting in
29
28
  // caching the path and the query.
@@ -62,7 +61,7 @@ const regionsToVdom = async (dom, {
62
61
  let head;
63
62
  if (globalThis.IS_GUTENBERG_PLUGIN) {
64
63
  if (navigationMode === 'fullPage') {
65
- head = await fetchHeadAssets(dom, headElements);
64
+ head = await fetchHeadAssets(dom);
66
65
  regions.body = vdom ? vdom.get(document.body) : toVdom(dom.body);
67
66
  }
68
67
  }
@@ -84,29 +83,32 @@ const regionsToVdom = async (dom, {
84
83
  };
85
84
 
86
85
  // Render all interactive regions contained in the given page.
87
- const renderRegions = page => {
88
- batch(() => {
89
- if (globalThis.IS_GUTENBERG_PLUGIN) {
90
- if (navigationMode === 'fullPage') {
91
- // Once this code is tested and more mature, the head should be updated for region based navigation as well.
92
- updateHead(page.head);
93
- const fragment = getRegionRootFragment(document.body);
86
+ const renderRegions = async page => {
87
+ if (globalThis.IS_GUTENBERG_PLUGIN) {
88
+ if (navigationMode === 'fullPage') {
89
+ // Once this code is tested and more mature, the head should be updated for region based navigation as well.
90
+ await updateHead(page.head);
91
+ const fragment = getRegionRootFragment(document.body);
92
+ batch(() => {
93
+ populateServerData(page.initialData);
94
94
  render(page.regions.body, fragment);
95
- }
95
+ });
96
96
  }
97
- if (navigationMode === 'regionBased') {
97
+ }
98
+ if (navigationMode === 'regionBased') {
99
+ const attrName = `data-${directivePrefix}-router-region`;
100
+ batch(() => {
98
101
  populateServerData(page.initialData);
99
- const attrName = `data-${directivePrefix}-router-region`;
100
102
  document.querySelectorAll(`[${attrName}]`).forEach(region => {
101
103
  const id = region.getAttribute(attrName);
102
104
  const fragment = getRegionRootFragment(region);
103
105
  render(page.regions[id], fragment);
104
106
  });
105
- }
106
- if (page.title) {
107
- document.title = page.title;
108
- }
109
- });
107
+ });
108
+ }
109
+ if (page.title) {
110
+ document.title = page.title;
111
+ }
110
112
  };
111
113
 
112
114
  /**
@@ -130,7 +132,7 @@ window.addEventListener('popstate', async () => {
130
132
  const pagePath = getPagePath(window.location.href); // Remove hash.
131
133
  const page = pages.has(pagePath) && (await pages.get(pagePath));
132
134
  if (page) {
133
- renderRegions(page);
135
+ await renderRegions(page);
134
136
  // Update the URL in the state.
135
137
  state.url = window.location.href;
136
138
  } else {
@@ -144,13 +146,12 @@ window.addEventListener('popstate', async () => {
144
146
  if (globalThis.IS_GUTENBERG_PLUGIN) {
145
147
  if (navigationMode === 'fullPage') {
146
148
  // Cache the scripts. Has to be called before fetching the assets.
147
- [].map.call(document.querySelectorAll('script[src]'), script => {
149
+ [].map.call(document.querySelectorAll('script[type="module"][src]'), script => {
148
150
  headElements.set(script.getAttribute('src'), {
149
- tag: script,
150
- text: script.textContent
151
+ tag: script
151
152
  });
152
153
  });
153
- await fetchHeadAssets(document, headElements);
154
+ await fetchHeadAssets(document);
154
155
  }
155
156
  }
156
157
  pages.set(getPagePath(window.location.href), Promise.resolve(regionsToVdom(document, {
@@ -1 +1 @@
1
- {"version":3,"names":["store","privateApis","getConfig","fetchHeadAssets","updateHead","directivePrefix","getRegionRootFragment","initialVdom","toVdom","render","parseServerData","populateServerData","batch","navigationMode","_getConfig$navigation","pages","Map","headElements","getPagePath","url","u","URL","window","location","href","pathname","search","fetchPage","html","res","fetch","status","text","dom","DOMParser","parseFromString","regionsToVdom","e","vdom","regions","body","undefined","head","globalThis","IS_GUTENBERG_PLUGIN","get","document","attrName","querySelectorAll","forEach","region","id","getAttribute","has","title","querySelector","innerText","initialData","renderRegions","page","fragment","forcePageReload","assign","Promise","addEventListener","pagePath","state","reload","map","call","script","set","tag","textContent","resolve","isValidLink","ref","HTMLAnchorElement","target","origin","startsWith","searchParams","isValidEvent","event","button","metaKey","ctrlKey","altKey","shiftKey","defaultPrevented","navigatingTo","hasLoadedNavigationTextsData","navigationTexts","loading","loaded","actions","navigation","hasStarted","hasFinished","navigate","options","clientNavigationDisabled","loadingAnimation","screenReaderAnnouncement","timeout","prefetch","timeoutPromise","setTimeout","loadingTimeout","a11ySpeak","race","clearTimeout","config","history","replace","hash","scrollIntoView","force","messageKey","content","getElementById","parsed","JSON","parse","i18n","texts","message","then","speak","closest","preventDefault","nodeName"],"sources":["@wordpress/interactivity-router/src/index.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { store, privateApis, getConfig } from '@wordpress/interactivity';\n\n/**\n * Internal dependencies\n */\nimport { fetchHeadAssets, updateHead } from './head';\n\nconst {\n\tdirectivePrefix,\n\tgetRegionRootFragment,\n\tinitialVdom,\n\ttoVdom,\n\trender,\n\tparseServerData,\n\tpopulateServerData,\n\tbatch,\n} = privateApis(\n\t'I acknowledge that using private APIs means my theme or plugin will inevitably break in the next version of WordPress.'\n);\n\ninterface NavigateOptions {\n\tforce?: boolean;\n\thtml?: string;\n\treplace?: boolean;\n\ttimeout?: number;\n\tloadingAnimation?: boolean;\n\tscreenReaderAnnouncement?: boolean;\n}\n\ninterface PrefetchOptions {\n\tforce?: boolean;\n\thtml?: string;\n}\n\ninterface VdomParams {\n\tvdom?: typeof initialVdom;\n}\n\ninterface Page {\n\tregions: Record< string, any >;\n\thead: HTMLHeadElement[];\n\ttitle: string;\n\tinitialData: any;\n}\n\ntype RegionsToVdom = ( dom: Document, params?: VdomParams ) => Promise< Page >;\n\n// Check if the navigation mode is full page or region based.\nconst navigationMode: 'regionBased' | 'fullPage' =\n\tgetConfig( 'core/router' ).navigationMode ?? 'regionBased';\n\n// The cache of visited and prefetched pages, stylesheets and scripts.\nconst pages = new Map< string, Promise< Page | false > >();\nconst headElements = new Map< string, { tag: HTMLElement; text: string } >();\n\n// Helper to remove domain and hash from the URL. We are only interesting in\n// caching the path and the query.\nconst getPagePath = ( url: string ) => {\n\tconst u = new URL( url, window.location.href );\n\treturn u.pathname + u.search;\n};\n\n// Fetch a new page and convert it to a static virtual DOM.\nconst fetchPage = async ( url: string, { html }: { html: string } ) => {\n\ttry {\n\t\tif ( ! html ) {\n\t\t\tconst res = await window.fetch( url );\n\t\t\tif ( res.status !== 200 ) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\thtml = await res.text();\n\t\t}\n\t\tconst dom = new window.DOMParser().parseFromString( html, 'text/html' );\n\t\treturn regionsToVdom( dom );\n\t} catch ( e ) {\n\t\treturn false;\n\t}\n};\n\n// Return an object with VDOM trees of those HTML regions marked with a\n// `router-region` directive.\nconst regionsToVdom: RegionsToVdom = async ( dom, { vdom } = {} ) => {\n\tconst regions = { body: undefined };\n\tlet head: HTMLElement[];\n\tif ( globalThis.IS_GUTENBERG_PLUGIN ) {\n\t\tif ( navigationMode === 'fullPage' ) {\n\t\t\thead = await fetchHeadAssets( dom, headElements );\n\t\t\tregions.body = vdom\n\t\t\t\t? vdom.get( document.body )\n\t\t\t\t: toVdom( dom.body );\n\t\t}\n\t}\n\tif ( navigationMode === 'regionBased' ) {\n\t\tconst attrName = `data-${ directivePrefix }-router-region`;\n\t\tdom.querySelectorAll( `[${ attrName }]` ).forEach( ( region ) => {\n\t\t\tconst id = region.getAttribute( attrName );\n\t\t\tregions[ id ] = vdom?.has( region )\n\t\t\t\t? vdom.get( region )\n\t\t\t\t: toVdom( region );\n\t\t} );\n\t}\n\tconst title = dom.querySelector( 'title' )?.innerText;\n\tconst initialData = parseServerData( dom );\n\treturn { regions, head, title, initialData };\n};\n\n// Render all interactive regions contained in the given page.\nconst renderRegions = ( page: Page ) => {\n\tbatch( () => {\n\t\tif ( globalThis.IS_GUTENBERG_PLUGIN ) {\n\t\t\tif ( navigationMode === 'fullPage' ) {\n\t\t\t\t// Once this code is tested and more mature, the head should be updated for region based navigation as well.\n\t\t\t\tupdateHead( page.head );\n\t\t\t\tconst fragment = getRegionRootFragment( document.body );\n\t\t\t\trender( page.regions.body, fragment );\n\t\t\t}\n\t\t}\n\t\tif ( navigationMode === 'regionBased' ) {\n\t\t\tpopulateServerData( page.initialData );\n\t\t\tconst attrName = `data-${ directivePrefix }-router-region`;\n\t\t\tdocument\n\t\t\t\t.querySelectorAll( `[${ attrName }]` )\n\t\t\t\t.forEach( ( region ) => {\n\t\t\t\t\tconst id = region.getAttribute( attrName );\n\t\t\t\t\tconst fragment = getRegionRootFragment( region );\n\t\t\t\t\trender( page.regions[ id ], fragment );\n\t\t\t\t} );\n\t\t}\n\t\tif ( page.title ) {\n\t\t\tdocument.title = page.title;\n\t\t}\n\t} );\n};\n\n/**\n * Load the given page forcing a full page reload.\n *\n * The function returns a promise that won't resolve, useful to prevent any\n * potential feedback indicating that the navigation has finished while the new\n * page is being loaded.\n *\n * @param href The page href.\n * @return Promise that never resolves.\n */\nconst forcePageReload = ( href: string ) => {\n\twindow.location.assign( href );\n\treturn new Promise( () => {} );\n};\n\n// Listen to the back and forward buttons and restore the page if it's in the\n// cache.\nwindow.addEventListener( 'popstate', async () => {\n\tconst pagePath = getPagePath( window.location.href ); // Remove hash.\n\tconst page = pages.has( pagePath ) && ( await pages.get( pagePath ) );\n\tif ( page ) {\n\t\trenderRegions( page );\n\t\t// Update the URL in the state.\n\t\tstate.url = window.location.href;\n\t} else {\n\t\twindow.location.reload();\n\t}\n} );\n\n// Initialize the router and cache the initial page using the initial vDOM.\n// Once this code is tested and more mature, the head should be updated for\n// region based navigation as well.\nif ( globalThis.IS_GUTENBERG_PLUGIN ) {\n\tif ( navigationMode === 'fullPage' ) {\n\t\t// Cache the scripts. Has to be called before fetching the assets.\n\t\t[].map.call( document.querySelectorAll( 'script[src]' ), ( script ) => {\n\t\t\theadElements.set( script.getAttribute( 'src' ), {\n\t\t\t\ttag: script,\n\t\t\t\ttext: script.textContent,\n\t\t\t} );\n\t\t} );\n\t\tawait fetchHeadAssets( document, headElements );\n\t}\n}\npages.set(\n\tgetPagePath( window.location.href ),\n\tPromise.resolve( regionsToVdom( document, { vdom: initialVdom } ) )\n);\n\n// Check if the link is valid for client-side navigation.\nconst isValidLink = ( ref: HTMLAnchorElement ) =>\n\tref &&\n\tref instanceof window.HTMLAnchorElement &&\n\tref.href &&\n\t( ! ref.target || ref.target === '_self' ) &&\n\tref.origin === window.location.origin &&\n\t! ref.pathname.startsWith( '/wp-admin' ) &&\n\t! ref.pathname.startsWith( '/wp-login.php' ) &&\n\t! ref.getAttribute( 'href' ).startsWith( '#' ) &&\n\t! new URL( ref.href ).searchParams.has( '_wpnonce' );\n\n// Check if the event is valid for client-side navigation.\nconst isValidEvent = ( event: MouseEvent ) =>\n\tevent &&\n\tevent.button === 0 && // Left clicks only.\n\t! event.metaKey && // Open in new tab (Mac).\n\t! event.ctrlKey && // Open in new tab (Windows).\n\t! event.altKey && // Download.\n\t! event.shiftKey &&\n\t! event.defaultPrevented;\n\n// Variable to store the current navigation.\nlet navigatingTo = '';\n\nlet hasLoadedNavigationTextsData = false;\nconst navigationTexts = {\n\tloading: 'Loading page, please wait.',\n\tloaded: 'Page Loaded.',\n};\n\ninterface Store {\n\tstate: {\n\t\turl: string;\n\t\tnavigation: {\n\t\t\thasStarted: boolean;\n\t\t\thasFinished: boolean;\n\t\t};\n\t};\n\tactions: {\n\t\tnavigate: ( href: string, options?: NavigateOptions ) => void;\n\t\tprefetch: ( url: string, options?: PrefetchOptions ) => void;\n\t};\n}\n\nexport const { state, actions } = store< Store >( 'core/router', {\n\tstate: {\n\t\turl: window.location.href,\n\t\tnavigation: {\n\t\t\thasStarted: false,\n\t\t\thasFinished: false,\n\t\t},\n\t},\n\tactions: {\n\t\t/**\n\t\t * Navigates to the specified page.\n\t\t *\n\t\t * This function normalizes the passed href, fetchs the page HTML if\n\t\t * needed, and updates any interactive regions whose contents have\n\t\t * changed. It also creates a new entry in the browser session history.\n\t\t *\n\t\t * @param href The page href.\n\t\t * @param [options] Options object.\n\t\t * @param [options.force] If true, it forces re-fetching the URL.\n\t\t * @param [options.html] HTML string to be used instead of fetching the requested URL.\n\t\t * @param [options.replace] If true, it replaces the current entry in the browser session history.\n\t\t * @param [options.timeout] Time until the navigation is aborted, in milliseconds. Default is 10000.\n\t\t * @param [options.loadingAnimation] Whether an animation should be shown while navigating. Default to `true`.\n\t\t * @param [options.screenReaderAnnouncement] Whether a message for screen readers should be announced while navigating. Default to `true`.\n\t\t *\n\t\t * @return Promise that resolves once the navigation is completed or aborted.\n\t\t */\n\t\t*navigate( href: string, options: NavigateOptions = {} ) {\n\t\t\tconst { clientNavigationDisabled } = getConfig();\n\t\t\tif ( clientNavigationDisabled ) {\n\t\t\t\tyield forcePageReload( href );\n\t\t\t}\n\n\t\t\tconst pagePath = getPagePath( href );\n\t\t\tconst { navigation } = state;\n\t\t\tconst {\n\t\t\t\tloadingAnimation = true,\n\t\t\t\tscreenReaderAnnouncement = true,\n\t\t\t\ttimeout = 10000,\n\t\t\t} = options;\n\n\t\t\tnavigatingTo = href;\n\t\t\tactions.prefetch( pagePath, options );\n\n\t\t\t// Create a promise that resolves when the specified timeout ends.\n\t\t\t// The timeout value is 10 seconds by default.\n\t\t\tconst timeoutPromise = new Promise< void >( ( resolve ) =>\n\t\t\t\tsetTimeout( resolve, timeout )\n\t\t\t);\n\n\t\t\t// Don't update the navigation status immediately, wait 400 ms.\n\t\t\tconst loadingTimeout = setTimeout( () => {\n\t\t\t\tif ( navigatingTo !== href ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif ( loadingAnimation ) {\n\t\t\t\t\tnavigation.hasStarted = true;\n\t\t\t\t\tnavigation.hasFinished = false;\n\t\t\t\t}\n\t\t\t\tif ( screenReaderAnnouncement ) {\n\t\t\t\t\ta11ySpeak( 'loading' );\n\t\t\t\t}\n\t\t\t}, 400 );\n\n\t\t\tconst page = yield Promise.race( [\n\t\t\t\tpages.get( pagePath ),\n\t\t\t\ttimeoutPromise,\n\t\t\t] );\n\n\t\t\t// Dismiss loading message if it hasn't been added yet.\n\t\t\tclearTimeout( loadingTimeout );\n\n\t\t\t// Once the page is fetched, the destination URL could have changed\n\t\t\t// (e.g., by clicking another link in the meantime). If so, bail\n\t\t\t// out, and let the newer execution to update the HTML.\n\t\t\tif ( navigatingTo !== href ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tpage &&\n\t\t\t\t! page.initialData?.config?.[ 'core/router' ]\n\t\t\t\t\t?.clientNavigationDisabled\n\t\t\t) {\n\t\t\t\tyield renderRegions( page );\n\t\t\t\twindow.history[\n\t\t\t\t\toptions.replace ? 'replaceState' : 'pushState'\n\t\t\t\t]( {}, '', href );\n\n\t\t\t\t// Update the URL in the state.\n\t\t\t\tstate.url = href;\n\n\t\t\t\t// Update the navigation status once the the new page rendering\n\t\t\t\t// has been completed.\n\t\t\t\tif ( loadingAnimation ) {\n\t\t\t\t\tnavigation.hasStarted = false;\n\t\t\t\t\tnavigation.hasFinished = true;\n\t\t\t\t}\n\n\t\t\t\tif ( screenReaderAnnouncement ) {\n\t\t\t\t\ta11ySpeak( 'loaded' );\n\t\t\t\t}\n\n\t\t\t\t// Scroll to the anchor if exits in the link.\n\t\t\t\tconst { hash } = new URL( href, window.location.href );\n\t\t\t\tif ( hash ) {\n\t\t\t\t\tdocument.querySelector( hash )?.scrollIntoView();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield forcePageReload( href );\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Prefetchs the page with the passed URL.\n\t\t *\n\t\t * The function normalizes the URL and stores internally the fetch\n\t\t * promise, to avoid triggering a second fetch for an ongoing request.\n\t\t *\n\t\t * @param url The page URL.\n\t\t * @param [options] Options object.\n\t\t * @param [options.force] Force fetching the URL again.\n\t\t * @param [options.html] HTML string to be used instead of fetching the requested URL.\n\t\t */\n\t\tprefetch( url: string, options: PrefetchOptions = {} ) {\n\t\t\tconst { clientNavigationDisabled } = getConfig();\n\t\t\tif ( clientNavigationDisabled ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst pagePath = getPagePath( url );\n\t\t\tif ( options.force || ! pages.has( pagePath ) ) {\n\t\t\t\tpages.set(\n\t\t\t\t\tpagePath,\n\t\t\t\t\tfetchPage( pagePath, { html: options.html } )\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t},\n} );\n\n/**\n * Announces a message to screen readers.\n *\n * This is a wrapper around the `@wordpress/a11y` package's `speak` function. It handles importing\n * the package on demand and should be used instead of calling `ally.speak` direacly.\n *\n * @param messageKey The message to be announced by assistive technologies.\n */\nfunction a11ySpeak( messageKey: keyof typeof navigationTexts ) {\n\tif ( ! hasLoadedNavigationTextsData ) {\n\t\thasLoadedNavigationTextsData = true;\n\t\tconst content = document.getElementById(\n\t\t\t'wp-script-module-data-@wordpress/interactivity-router'\n\t\t)?.textContent;\n\t\tif ( content ) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse( content );\n\t\t\t\tif ( typeof parsed?.i18n?.loading === 'string' ) {\n\t\t\t\t\tnavigationTexts.loading = parsed.i18n.loading;\n\t\t\t\t}\n\t\t\t\tif ( typeof parsed?.i18n?.loaded === 'string' ) {\n\t\t\t\t\tnavigationTexts.loaded = parsed.i18n.loaded;\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t} else {\n\t\t\t// Fallback to localized strings from Interactivity API state.\n\t\t\t// @todo This block is for Core < 6.7.0. Remove when support is dropped.\n\n\t\t\t// @ts-expect-error\n\t\t\tif ( state.navigation.texts?.loading ) {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnavigationTexts.loading = state.navigation.texts.loading;\n\t\t\t}\n\t\t\t// @ts-expect-error\n\t\t\tif ( state.navigation.texts?.loaded ) {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnavigationTexts.loaded = state.navigation.texts.loaded;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst message = navigationTexts[ messageKey ];\n\n\timport( '@wordpress/a11y' ).then(\n\t\t( { speak } ) => speak( message ),\n\t\t// Ignore failures to load the a11y module.\n\t\t() => {}\n\t);\n}\n\n// Add click and prefetch to all links.\nif ( globalThis.IS_GUTENBERG_PLUGIN ) {\n\tif ( navigationMode === 'fullPage' ) {\n\t\t// Navigate on click.\n\t\tdocument.addEventListener(\n\t\t\t'click',\n\t\t\tfunction ( event ) {\n\t\t\t\tconst ref = ( event.target as Element ).closest( 'a' );\n\t\t\t\tif ( isValidLink( ref ) && isValidEvent( event ) ) {\n\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\tactions.navigate( ref.href );\n\t\t\t\t}\n\t\t\t},\n\t\t\ttrue\n\t\t);\n\t\t// Prefetch on hover.\n\t\tdocument.addEventListener(\n\t\t\t'mouseenter',\n\t\t\tfunction ( event ) {\n\t\t\t\tif ( ( event.target as Element )?.nodeName === 'A' ) {\n\t\t\t\t\tconst ref = ( event.target as Element ).closest( 'a' );\n\t\t\t\t\tif ( isValidLink( ref ) && isValidEvent( event ) ) {\n\t\t\t\t\t\tactions.prefetch( ref.href );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\ttrue\n\t\t);\n\t}\n}\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,KAAK,EAAEC,WAAW,EAAEC,SAAS,QAAQ,0BAA0B;;AAExE;AACA;AACA;AACA,SAASC,eAAe,EAAEC,UAAU,QAAQ,QAAQ;AAEpD,MAAM;EACLC,eAAe;EACfC,qBAAqB;EACrBC,WAAW;EACXC,MAAM;EACNC,MAAM;EACNC,eAAe;EACfC,kBAAkB;EAClBC;AACD,CAAC,GAAGX,WAAW,CACd,wHACD,CAAC;AA6BD;AACA,MAAMY,cAA0C,IAAAC,qBAAA,GAC/CZ,SAAS,CAAE,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tBnC,OAAO,CAACI,QAAQ,CAAEvB,GAAG,CAACpD,IAAK,CAAC;MAC7B;IACD,CAAC,EACD,IACD,CAAC;IACD;IACAsB,QAAQ,CAACkB,gBAAgB,CACxB,YAAY,EACZ,UAAWmB,KAAK,EAAG;MAClB,IAAOA,KAAK,CAACL,MAAM,EAAeqD,QAAQ,KAAK,GAAG,EAAG;QACpD,MAAMvD,GAAG,GAAKO,KAAK,CAACL,MAAM,CAAcmD,OAAO,CAAE,GAAI,CAAC;QACtD,IAAKtD,WAAW,CAAEC,GAAI,CAAC,IAAIM,YAAY,CAAEC,KAAM,CAAC,EAAG;UAClDY,OAAO,CAACU,QAAQ,CAAE7B,GAAG,CAACpD,IAAK,CAAC;QAC7B;MACD;IACD,CAAC,EACD,IACD,CAAC;EACF;AACD","ignoreList":[]}
1
+ {"version":3,"names":["store","privateApis","getConfig","fetchHeadAssets","updateHead","headElements","directivePrefix","getRegionRootFragment","initialVdom","toVdom","render","parseServerData","populateServerData","batch","navigationMode","_getConfig$navigation","pages","Map","getPagePath","url","u","URL","window","location","href","pathname","search","fetchPage","html","res","fetch","status","text","dom","DOMParser","parseFromString","regionsToVdom","e","vdom","regions","body","undefined","head","globalThis","IS_GUTENBERG_PLUGIN","get","document","attrName","querySelectorAll","forEach","region","id","getAttribute","has","title","querySelector","innerText","initialData","renderRegions","page","fragment","forcePageReload","assign","Promise","addEventListener","pagePath","state","reload","map","call","script","set","tag","resolve","isValidLink","ref","HTMLAnchorElement","target","origin","startsWith","searchParams","isValidEvent","event","button","metaKey","ctrlKey","altKey","shiftKey","defaultPrevented","navigatingTo","hasLoadedNavigationTextsData","navigationTexts","loading","loaded","actions","navigation","hasStarted","hasFinished","navigate","options","clientNavigationDisabled","loadingAnimation","screenReaderAnnouncement","timeout","prefetch","timeoutPromise","setTimeout","loadingTimeout","a11ySpeak","race","clearTimeout","config","history","replace","hash","scrollIntoView","force","messageKey","content","getElementById","textContent","parsed","JSON","parse","i18n","texts","message","then","speak","closest","preventDefault","nodeName"],"sources":["@wordpress/interactivity-router/src/index.ts"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { store, privateApis, getConfig } from '@wordpress/interactivity';\n\n/**\n * Internal dependencies\n */\nimport { fetchHeadAssets, updateHead, headElements } from './head';\n\nconst {\n\tdirectivePrefix,\n\tgetRegionRootFragment,\n\tinitialVdom,\n\ttoVdom,\n\trender,\n\tparseServerData,\n\tpopulateServerData,\n\tbatch,\n} = privateApis(\n\t'I acknowledge that using private APIs means my theme or plugin will inevitably break in the next version of WordPress.'\n);\n\ninterface NavigateOptions {\n\tforce?: boolean;\n\thtml?: string;\n\treplace?: boolean;\n\ttimeout?: number;\n\tloadingAnimation?: boolean;\n\tscreenReaderAnnouncement?: boolean;\n}\n\ninterface PrefetchOptions {\n\tforce?: boolean;\n\thtml?: string;\n}\n\ninterface VdomParams {\n\tvdom?: typeof initialVdom;\n}\n\ninterface Page {\n\tregions: Record< string, any >;\n\thead: HTMLHeadElement[];\n\ttitle: string;\n\tinitialData: any;\n}\n\ntype RegionsToVdom = ( dom: Document, params?: VdomParams ) => Promise< Page >;\n\n// Check if the navigation mode is full page or region based.\nconst navigationMode: 'regionBased' | 'fullPage' =\n\tgetConfig( 'core/router' ).navigationMode ?? 'regionBased';\n\n// The cache of visited and prefetched pages, stylesheets and scripts.\nconst pages = new Map< string, Promise< Page | false > >();\n\n// Helper to remove domain and hash from the URL. We are only interesting in\n// caching the path and the query.\nconst getPagePath = ( url: string ) => {\n\tconst u = new URL( url, window.location.href );\n\treturn u.pathname + u.search;\n};\n\n// Fetch a new page and convert it to a static virtual DOM.\nconst fetchPage = async ( url: string, { html }: { html: string } ) => {\n\ttry {\n\t\tif ( ! html ) {\n\t\t\tconst res = await window.fetch( url );\n\t\t\tif ( res.status !== 200 ) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\thtml = await res.text();\n\t\t}\n\t\tconst dom = new window.DOMParser().parseFromString( html, 'text/html' );\n\t\treturn regionsToVdom( dom );\n\t} catch ( e ) {\n\t\treturn false;\n\t}\n};\n\n// Return an object with VDOM trees of those HTML regions marked with a\n// `router-region` directive.\nconst regionsToVdom: RegionsToVdom = async ( dom, { vdom } = {} ) => {\n\tconst regions = { body: undefined };\n\tlet head: HTMLElement[];\n\tif ( globalThis.IS_GUTENBERG_PLUGIN ) {\n\t\tif ( navigationMode === 'fullPage' ) {\n\t\t\thead = await fetchHeadAssets( dom );\n\t\t\tregions.body = vdom\n\t\t\t\t? vdom.get( document.body )\n\t\t\t\t: toVdom( dom.body );\n\t\t}\n\t}\n\tif ( navigationMode === 'regionBased' ) {\n\t\tconst attrName = `data-${ directivePrefix }-router-region`;\n\t\tdom.querySelectorAll( `[${ attrName }]` ).forEach( ( region ) => {\n\t\t\tconst id = region.getAttribute( attrName );\n\t\t\tregions[ id ] = vdom?.has( region )\n\t\t\t\t? vdom.get( region )\n\t\t\t\t: toVdom( region );\n\t\t} );\n\t}\n\tconst title = dom.querySelector( 'title' )?.innerText;\n\tconst initialData = parseServerData( dom );\n\treturn { regions, head, title, initialData };\n};\n\n// Render all interactive regions contained in the given page.\nconst renderRegions = async ( page: Page ) => {\n\tif ( globalThis.IS_GUTENBERG_PLUGIN ) {\n\t\tif ( navigationMode === 'fullPage' ) {\n\t\t\t// Once this code is tested and more mature, the head should be updated for region based navigation as well.\n\t\t\tawait updateHead( page.head );\n\t\t\tconst fragment = getRegionRootFragment( document.body );\n\t\t\tbatch( () => {\n\t\t\t\tpopulateServerData( page.initialData );\n\t\t\t\trender( page.regions.body, fragment );\n\t\t\t} );\n\t\t}\n\t}\n\tif ( navigationMode === 'regionBased' ) {\n\t\tconst attrName = `data-${ directivePrefix }-router-region`;\n\t\tbatch( () => {\n\t\t\tpopulateServerData( page.initialData );\n\t\t\tdocument\n\t\t\t\t.querySelectorAll( `[${ attrName }]` )\n\t\t\t\t.forEach( ( region ) => {\n\t\t\t\t\tconst id = region.getAttribute( attrName );\n\t\t\t\t\tconst fragment = getRegionRootFragment( region );\n\t\t\t\t\trender( page.regions[ id ], fragment );\n\t\t\t\t} );\n\t\t} );\n\t}\n\tif ( page.title ) {\n\t\tdocument.title = page.title;\n\t}\n};\n\n/**\n * Load the given page forcing a full page reload.\n *\n * The function returns a promise that won't resolve, useful to prevent any\n * potential feedback indicating that the navigation has finished while the new\n * page is being loaded.\n *\n * @param href The page href.\n * @return Promise that never resolves.\n */\nconst forcePageReload = ( href: string ) => {\n\twindow.location.assign( href );\n\treturn new Promise( () => {} );\n};\n\n// Listen to the back and forward buttons and restore the page if it's in the\n// cache.\nwindow.addEventListener( 'popstate', async () => {\n\tconst pagePath = getPagePath( window.location.href ); // Remove hash.\n\tconst page = pages.has( pagePath ) && ( await pages.get( pagePath ) );\n\tif ( page ) {\n\t\tawait renderRegions( page );\n\t\t// Update the URL in the state.\n\t\tstate.url = window.location.href;\n\t} else {\n\t\twindow.location.reload();\n\t}\n} );\n\n// Initialize the router and cache the initial page using the initial vDOM.\n// Once this code is tested and more mature, the head should be updated for\n// region based navigation as well.\nif ( globalThis.IS_GUTENBERG_PLUGIN ) {\n\tif ( navigationMode === 'fullPage' ) {\n\t\t// Cache the scripts. Has to be called before fetching the assets.\n\t\t[].map.call(\n\t\t\tdocument.querySelectorAll( 'script[type=\"module\"][src]' ),\n\t\t\t( script ) => {\n\t\t\t\theadElements.set( script.getAttribute( 'src' ), {\n\t\t\t\t\ttag: script,\n\t\t\t\t} );\n\t\t\t}\n\t\t);\n\t\tawait fetchHeadAssets( document );\n\t}\n}\npages.set(\n\tgetPagePath( window.location.href ),\n\tPromise.resolve( regionsToVdom( document, { vdom: initialVdom } ) )\n);\n\n// Check if the link is valid for client-side navigation.\nconst isValidLink = ( ref: HTMLAnchorElement ) =>\n\tref &&\n\tref instanceof window.HTMLAnchorElement &&\n\tref.href &&\n\t( ! ref.target || ref.target === '_self' ) &&\n\tref.origin === window.location.origin &&\n\t! ref.pathname.startsWith( '/wp-admin' ) &&\n\t! ref.pathname.startsWith( '/wp-login.php' ) &&\n\t! ref.getAttribute( 'href' ).startsWith( '#' ) &&\n\t! new URL( ref.href ).searchParams.has( '_wpnonce' );\n\n// Check if the event is valid for client-side navigation.\nconst isValidEvent = ( event: MouseEvent ) =>\n\tevent &&\n\tevent.button === 0 && // Left clicks only.\n\t! event.metaKey && // Open in new tab (Mac).\n\t! event.ctrlKey && // Open in new tab (Windows).\n\t! event.altKey && // Download.\n\t! event.shiftKey &&\n\t! event.defaultPrevented;\n\n// Variable to store the current navigation.\nlet navigatingTo = '';\n\nlet hasLoadedNavigationTextsData = false;\nconst navigationTexts = {\n\tloading: 'Loading page, please wait.',\n\tloaded: 'Page Loaded.',\n};\n\ninterface Store {\n\tstate: {\n\t\turl: string;\n\t\tnavigation: {\n\t\t\thasStarted: boolean;\n\t\t\thasFinished: boolean;\n\t\t};\n\t};\n\tactions: {\n\t\tnavigate: ( href: string, options?: NavigateOptions ) => void;\n\t\tprefetch: ( url: string, options?: PrefetchOptions ) => void;\n\t};\n}\n\nexport const { state, actions } = store< Store >( 'core/router', {\n\tstate: {\n\t\turl: window.location.href,\n\t\tnavigation: {\n\t\t\thasStarted: false,\n\t\t\thasFinished: false,\n\t\t},\n\t},\n\tactions: {\n\t\t/**\n\t\t * Navigates to the specified page.\n\t\t *\n\t\t * This function normalizes the passed href, fetchs the page HTML if\n\t\t * needed, and updates any interactive regions whose contents have\n\t\t * changed. It also creates a new entry in the browser session history.\n\t\t *\n\t\t * @param href The page href.\n\t\t * @param [options] Options object.\n\t\t * @param [options.force] If true, it forces re-fetching the URL.\n\t\t * @param [options.html] HTML string to be used instead of fetching the requested URL.\n\t\t * @param [options.replace] If true, it replaces the current entry in the browser session history.\n\t\t * @param [options.timeout] Time until the navigation is aborted, in milliseconds. Default is 10000.\n\t\t * @param [options.loadingAnimation] Whether an animation should be shown while navigating. Default to `true`.\n\t\t * @param [options.screenReaderAnnouncement] Whether a message for screen readers should be announced while navigating. Default to `true`.\n\t\t *\n\t\t * @return Promise that resolves once the navigation is completed or aborted.\n\t\t */\n\t\t*navigate( href: string, options: NavigateOptions = {} ) {\n\t\t\tconst { clientNavigationDisabled } = getConfig();\n\t\t\tif ( clientNavigationDisabled ) {\n\t\t\t\tyield forcePageReload( href );\n\t\t\t}\n\n\t\t\tconst pagePath = getPagePath( href );\n\t\t\tconst { navigation } = state;\n\t\t\tconst {\n\t\t\t\tloadingAnimation = true,\n\t\t\t\tscreenReaderAnnouncement = true,\n\t\t\t\ttimeout = 10000,\n\t\t\t} = options;\n\n\t\t\tnavigatingTo = href;\n\t\t\tactions.prefetch( pagePath, options );\n\n\t\t\t// Create a promise that resolves when the specified timeout ends.\n\t\t\t// The timeout value is 10 seconds by default.\n\t\t\tconst timeoutPromise = new Promise< void >( ( resolve ) =>\n\t\t\t\tsetTimeout( resolve, timeout )\n\t\t\t);\n\n\t\t\t// Don't update the navigation status immediately, wait 400 ms.\n\t\t\tconst loadingTimeout = setTimeout( () => {\n\t\t\t\tif ( navigatingTo !== href ) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tif ( loadingAnimation ) {\n\t\t\t\t\tnavigation.hasStarted = true;\n\t\t\t\t\tnavigation.hasFinished = false;\n\t\t\t\t}\n\t\t\t\tif ( screenReaderAnnouncement ) {\n\t\t\t\t\ta11ySpeak( 'loading' );\n\t\t\t\t}\n\t\t\t}, 400 );\n\n\t\t\tconst page = yield Promise.race( [\n\t\t\t\tpages.get( pagePath ),\n\t\t\t\ttimeoutPromise,\n\t\t\t] );\n\n\t\t\t// Dismiss loading message if it hasn't been added yet.\n\t\t\tclearTimeout( loadingTimeout );\n\n\t\t\t// Once the page is fetched, the destination URL could have changed\n\t\t\t// (e.g., by clicking another link in the meantime). If so, bail\n\t\t\t// out, and let the newer execution to update the HTML.\n\t\t\tif ( navigatingTo !== href ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tif (\n\t\t\t\tpage &&\n\t\t\t\t! page.initialData?.config?.[ 'core/router' ]\n\t\t\t\t\t?.clientNavigationDisabled\n\t\t\t) {\n\t\t\t\tyield renderRegions( page );\n\t\t\t\twindow.history[\n\t\t\t\t\toptions.replace ? 'replaceState' : 'pushState'\n\t\t\t\t]( {}, '', href );\n\n\t\t\t\t// Update the URL in the state.\n\t\t\t\tstate.url = href;\n\n\t\t\t\t// Update the navigation status once the the new page rendering\n\t\t\t\t// has been completed.\n\t\t\t\tif ( loadingAnimation ) {\n\t\t\t\t\tnavigation.hasStarted = false;\n\t\t\t\t\tnavigation.hasFinished = true;\n\t\t\t\t}\n\n\t\t\t\tif ( screenReaderAnnouncement ) {\n\t\t\t\t\ta11ySpeak( 'loaded' );\n\t\t\t\t}\n\n\t\t\t\t// Scroll to the anchor if exits in the link.\n\t\t\t\tconst { hash } = new URL( href, window.location.href );\n\t\t\t\tif ( hash ) {\n\t\t\t\t\tdocument.querySelector( hash )?.scrollIntoView();\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield forcePageReload( href );\n\t\t\t}\n\t\t},\n\n\t\t/**\n\t\t * Prefetchs the page with the passed URL.\n\t\t *\n\t\t * The function normalizes the URL and stores internally the fetch\n\t\t * promise, to avoid triggering a second fetch for an ongoing request.\n\t\t *\n\t\t * @param url The page URL.\n\t\t * @param [options] Options object.\n\t\t * @param [options.force] Force fetching the URL again.\n\t\t * @param [options.html] HTML string to be used instead of fetching the requested URL.\n\t\t */\n\t\tprefetch( url: string, options: PrefetchOptions = {} ) {\n\t\t\tconst { clientNavigationDisabled } = getConfig();\n\t\t\tif ( clientNavigationDisabled ) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst pagePath = getPagePath( url );\n\t\t\tif ( options.force || ! pages.has( pagePath ) ) {\n\t\t\t\tpages.set(\n\t\t\t\t\tpagePath,\n\t\t\t\t\tfetchPage( pagePath, { html: options.html } )\n\t\t\t\t);\n\t\t\t}\n\t\t},\n\t},\n} );\n\n/**\n * Announces a message to screen readers.\n *\n * This is a wrapper around the `@wordpress/a11y` package's `speak` function. It handles importing\n * the package on demand and should be used instead of calling `ally.speak` direacly.\n *\n * @param messageKey The message to be announced by assistive technologies.\n */\nfunction a11ySpeak( messageKey: keyof typeof navigationTexts ) {\n\tif ( ! hasLoadedNavigationTextsData ) {\n\t\thasLoadedNavigationTextsData = true;\n\t\tconst content = document.getElementById(\n\t\t\t'wp-script-module-data-@wordpress/interactivity-router'\n\t\t)?.textContent;\n\t\tif ( content ) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse( content );\n\t\t\t\tif ( typeof parsed?.i18n?.loading === 'string' ) {\n\t\t\t\t\tnavigationTexts.loading = parsed.i18n.loading;\n\t\t\t\t}\n\t\t\t\tif ( typeof parsed?.i18n?.loaded === 'string' ) {\n\t\t\t\t\tnavigationTexts.loaded = parsed.i18n.loaded;\n\t\t\t\t}\n\t\t\t} catch {}\n\t\t} else {\n\t\t\t// Fallback to localized strings from Interactivity API state.\n\t\t\t// @todo This block is for Core < 6.7.0. Remove when support is dropped.\n\n\t\t\t// @ts-expect-error\n\t\t\tif ( state.navigation.texts?.loading ) {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnavigationTexts.loading = state.navigation.texts.loading;\n\t\t\t}\n\t\t\t// @ts-expect-error\n\t\t\tif ( state.navigation.texts?.loaded ) {\n\t\t\t\t// @ts-expect-error\n\t\t\t\tnavigationTexts.loaded = state.navigation.texts.loaded;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst message = navigationTexts[ messageKey ];\n\n\timport( '@wordpress/a11y' ).then(\n\t\t( { speak } ) => speak( message ),\n\t\t// Ignore failures to load the a11y module.\n\t\t() => {}\n\t);\n}\n\n// Add click and prefetch to all links.\nif ( globalThis.IS_GUTENBERG_PLUGIN ) {\n\tif ( navigationMode === 'fullPage' ) {\n\t\t// Navigate on click.\n\t\tdocument.addEventListener(\n\t\t\t'click',\n\t\t\tfunction ( event ) {\n\t\t\t\tconst ref = ( event.target as Element ).closest( 'a' );\n\t\t\t\tif ( isValidLink( ref ) && isValidEvent( event ) ) {\n\t\t\t\t\tevent.preventDefault();\n\t\t\t\t\tactions.navigate( ref.href );\n\t\t\t\t}\n\t\t\t},\n\t\t\ttrue\n\t\t);\n\t\t// Prefetch on hover.\n\t\tdocument.addEventListener(\n\t\t\t'mouseenter',\n\t\t\tfunction ( event ) {\n\t\t\t\tif ( ( event.target as Element )?.nodeName === 'A' ) {\n\t\t\t\t\tconst ref = ( event.target as Element ).closest( 'a' );\n\t\t\t\t\tif ( isValidLink( ref ) && isValidEvent( event ) ) {\n\t\t\t\t\t\tactions.prefetch( ref.href );\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t\ttrue\n\t\t);\n\t}\n}\n"],"mappings":";AAAA;AACA;AACA;AACA,SAASA,KAAK,EAAEC,WAAW,EAAEC,SAAS,QAAQ,0BAA0B;;AAExE;AACA;AACA;AACA,SAASC,eAAe,EAAEC,UAAU,EAAEC,YAAY,QAAQ,QAAQ;AAElE,MAAM;EACLC,eAAe;EACfC,qBAAqB;EACrBC,WAAW;EACXC,MAAM;EACNC,MAAM;EACNC,eAAe;EACfC,kBAAkB;EAClBC;AACD,CAAC,GAAGZ,WAAW,CACd,wHACD,CAAC;AA6BD;AACA,MAAMa,cAA0C,IAAAC,qBAAA,GAC/Cb,SAAS,CAAE,aAAc,CAAC,CAACY,cAAc,cAAAC,qBAAA,cAAAA,qBAAA,GAAI,aAAa;;AAE3D;AACA,MAAMC,KAAK,GAAG,IAAIC,GAAG,CAAoC,CAAC;;AAE1D;AACA;AACA,MAAMC,WAAW,GAAKC,GAAW,IAAM;EACtC,MAAMC,CAAC,GAAG,IAAIC,GAAG,CAAEF,GAAG,EAAEG,MAAM,CAACC,QAAQ,CAACC,IAAK,CAAC;EAC9C,OAAOJ,CAAC,CAACK,QAAQ,GAAGL,CAAC,CAACM,MAAM;AAC7B,CAAC;;AAED;AACA,MAAMC,SAAS,GAAG,MAAAA,CAAQR,GAAW,EAAE;EAAES;AAAuB,CAAC,KAAM;EACtE,IAAI;IACH,IAA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CAAC,EACD,IACD,CAAC;EACF;AACD","ignoreList":[]}
@@ -1,3 +1,10 @@
1
+ /**
2
+ * The cache of prefetched stylesheets and scripts.
3
+ */
4
+ export declare const headElements: Map<string, {
5
+ tag: HTMLElement;
6
+ text?: string;
7
+ }>;
1
8
  /**
2
9
  * Helper to update only the necessary tags in the head.
3
10
  *
@@ -9,15 +16,9 @@ export declare const updateHead: (newHead: HTMLHeadElement[]) => Promise<void>;
9
16
  * Fetches and processes head assets (stylesheets and scripts) from a specified document.
10
17
  *
11
18
  * @async
12
- * @param doc The document from which to fetch head assets. It should support standard DOM querying methods.
13
- * @param headElements A map of head elements to modify tracking the URLs of already processed assets to avoid duplicates.
14
- * @param headElements.tag
15
- * @param headElements.text
19
+ * @param doc The document from which to fetch head assets. It should support standard DOM querying methods.
16
20
  *
17
21
  * @return Returns an array of HTML elements representing the head assets.
18
22
  */
19
- export declare const fetchHeadAssets: (doc: Document, headElements: Map<string, {
20
- tag: HTMLElement;
21
- text: string;
22
- }>) => Promise<HTMLElement[]>;
23
+ export declare const fetchHeadAssets: (doc: Document) => Promise<HTMLElement[]>;
23
24
  //# sourceMappingURL=head.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"head.d.ts","sourceRoot":"","sources":["../src/head.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,eAAO,MAAM,UAAU,YAAoB,eAAe,EAAE,kBA+B3D,CAAC;AAEF;;;;;;;;;;GAUG;AACH,eAAO,MAAM,eAAe,QACtB,QAAQ,gBACC,GAAG,CAAE,MAAM,EAAE;IAAE,GAAG,EAAE,WAAW,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAE,KAC7D,OAAO,CAAE,WAAW,EAAE,CAkDxB,CAAC"}
1
+ {"version":3,"file":"head.d.ts","sourceRoot":"","sources":["../src/head.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,YAAY;SAEjB,WAAW;WAAS,MAAM;EAC/B,CAAC;AAEJ;;;;;GAKG;AACH,eAAO,MAAM,UAAU,YAAoB,eAAe,EAAE,kBAuC3D,CAAC;AAEF;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,QACtB,QAAQ,KACX,OAAO,CAAE,WAAW,EAAE,CA4DxB,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAuBA,UAAU,eAAe;IACxB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,wBAAwB,CAAC,EAAE,OAAO,CAAC;CACnC;AAED,UAAU,eAAe;IACxB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAoMD,eAAO,MAAQ,KAAK;SAZb,MAAM;gBACC;QACX,UAAU,EAAE,OAAO,CAAC;QACpB,WAAW,EAAE,OAAO,CAAC;KACrB;GAQmB,OAAO;cALjB,CAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,KAAM,IAAI;cACnD,CAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,KAAM,IAAI;CAgJ3D,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAuBA,UAAU,eAAe;IACxB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B,wBAAwB,CAAC,EAAE,OAAO,CAAC;CACnC;AAED,UAAU,eAAe;IACxB,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAwMD,eAAO,MAAQ,KAAK;SAZb,MAAM;;oBAEE,OAAO;qBACN,OAAO;;GASD,OAAO;cALjB,CAAE,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,KAAM,IAAI;cACnD,CAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe,KAAM,IAAI;CAgJ3D,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wordpress/interactivity-router",
3
- "version": "2.8.5",
3
+ "version": "2.10.0",
4
4
  "description": "Package that exposes state and actions from the `core/router` store, part of the Interactivity API.",
5
5
  "author": "The WordPress Contributors",
6
6
  "license": "GPL-2.0-or-later",
@@ -28,11 +28,11 @@
28
28
  "types": "build-types",
29
29
  "wpScriptModuleExports": "./build-module/index.js",
30
30
  "dependencies": {
31
- "@wordpress/a11y": "^4.8.2",
32
- "@wordpress/interactivity": "^6.8.4"
31
+ "@wordpress/a11y": "^4.10.0",
32
+ "@wordpress/interactivity": "^6.10.0"
33
33
  },
34
34
  "publishConfig": {
35
35
  "access": "public"
36
36
  },
37
- "gitHead": "b7af02f8431034ee19cdc33dd105d21705823eed"
37
+ "gitHead": "ab34a7ac935fd1478eac63b596242d83270897ee"
38
38
  }
package/src/head.ts CHANGED
@@ -1,3 +1,11 @@
1
+ /**
2
+ * The cache of prefetched stylesheets and scripts.
3
+ */
4
+ export const headElements = new Map<
5
+ string,
6
+ { tag: HTMLElement; text?: string }
7
+ >();
8
+
1
9
  /**
2
10
  * Helper to update only the necessary tags in the head.
3
11
  *
@@ -29,6 +37,14 @@ export const updateHead = async ( newHead: HTMLHeadElement[] ) => {
29
37
  }
30
38
  }
31
39
 
40
+ await Promise.all(
41
+ [ ...headElements.entries() ]
42
+ .filter( ( [ , { tag } ] ) => tag.nodeName === 'SCRIPT' )
43
+ .map( async ( [ url ] ) => {
44
+ await import( /* webpackIgnore: true */ url );
45
+ } )
46
+ );
47
+
32
48
  // Prepare new assets.
33
49
  const toAppend = [ ...newHeadMap.values() ];
34
50
 
@@ -41,60 +57,66 @@ export const updateHead = async ( newHead: HTMLHeadElement[] ) => {
41
57
  * Fetches and processes head assets (stylesheets and scripts) from a specified document.
42
58
  *
43
59
  * @async
44
- * @param doc The document from which to fetch head assets. It should support standard DOM querying methods.
45
- * @param headElements A map of head elements to modify tracking the URLs of already processed assets to avoid duplicates.
46
- * @param headElements.tag
47
- * @param headElements.text
60
+ * @param doc The document from which to fetch head assets. It should support standard DOM querying methods.
48
61
  *
49
62
  * @return Returns an array of HTML elements representing the head assets.
50
63
  */
51
64
  export const fetchHeadAssets = async (
52
- doc: Document,
53
- headElements: Map< string, { tag: HTMLElement; text: string } >
65
+ doc: Document
54
66
  ): Promise< HTMLElement[] > => {
55
67
  const headTags = [];
56
- const assets = [
57
- {
58
- tagName: 'style',
59
- selector: 'link[rel=stylesheet]',
60
- attribute: 'href',
61
- },
62
- { tagName: 'script', selector: 'script[src]', attribute: 'src' },
63
- ];
64
- for ( const asset of assets ) {
65
- const { tagName, selector, attribute } = asset;
66
- const tags = doc.querySelectorAll<
67
- HTMLScriptElement | HTMLStyleElement
68
- >( selector );
69
-
70
- // Use Promise.all to wait for fetch to complete
71
- await Promise.all(
72
- Array.from( tags ).map( async ( tag ) => {
73
- const attributeValue = tag.getAttribute( attribute );
74
- if ( ! headElements.has( attributeValue ) ) {
75
- try {
76
- const response = await fetch( attributeValue );
77
- const text = await response.text();
78
- headElements.set( attributeValue, {
79
- tag,
80
- text,
81
- } );
82
- } catch ( e ) {
83
- // eslint-disable-next-line no-console
84
- console.error( e );
85
- }
86
- }
87
68
 
88
- const headElement = headElements.get( attributeValue );
89
- const element = doc.createElement( tagName );
90
- element.innerText = headElement.text;
91
- for ( const attr of headElement.tag.attributes ) {
92
- element.setAttribute( attr.name, attr.value );
69
+ // We only want to fetch module scripts because regular scripts (without
70
+ // `async` or `defer` attributes) can depend on the execution of other scripts.
71
+ // Scripts found in the head are blocking and must be executed in order.
72
+ const scripts = doc.querySelectorAll< HTMLScriptElement >(
73
+ 'script[type="module"][src]'
74
+ );
75
+
76
+ scripts.forEach( ( script ) => {
77
+ const src = script.getAttribute( 'src' );
78
+ if ( ! headElements.has( src ) ) {
79
+ // add the <link> elements to prefetch the module scripts
80
+ const link = doc.createElement( 'link' );
81
+ link.rel = 'modulepreload';
82
+ link.href = src;
83
+ document.head.append( link );
84
+ headElements.set( src, { tag: script } );
85
+ }
86
+ } );
87
+
88
+ const stylesheets = doc.querySelectorAll< HTMLLinkElement >(
89
+ 'link[rel=stylesheet]'
90
+ );
91
+
92
+ await Promise.all(
93
+ Array.from( stylesheets ).map( async ( tag ) => {
94
+ const href = tag.getAttribute( 'href' );
95
+ if ( ! href ) {
96
+ return;
97
+ }
98
+
99
+ if ( ! headElements.has( href ) ) {
100
+ try {
101
+ const response = await fetch( href );
102
+ const text = await response.text();
103
+ headElements.set( href, {
104
+ tag,
105
+ text,
106
+ } );
107
+ } catch ( e ) {
108
+ // eslint-disable-next-line no-console
109
+ console.error( e );
93
110
  }
94
- headTags.push( element );
95
- } )
96
- );
97
- }
111
+ }
112
+
113
+ const headElement = headElements.get( href );
114
+ const styleElement = doc.createElement( 'style' );
115
+ styleElement.textContent = headElement.text;
116
+
117
+ headTags.push( styleElement );
118
+ } )
119
+ );
98
120
 
99
121
  return [
100
122
  doc.querySelector( 'title' ),