@wordpress/interactivity-router 1.6.0 → 1.8.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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,10 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 1.8.0 (2024-05-16)
6
+
7
+ ## 1.7.0 (2024-05-02)
8
+
5
9
  ## 1.6.0 (2024-04-19)
6
10
 
7
11
  ## 1.5.0 (2024-04-03)
package/build/head.js ADDED
@@ -0,0 +1,102 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.updateHead = exports.fetchHeadAssets = void 0;
7
+ /**
8
+ * Helper to update only the necessary tags in the head.
9
+ *
10
+ * @async
11
+ * @param {Array} newHead The head elements of the new page.
12
+ */
13
+ const updateHead = async newHead => {
14
+ // Helper to get the tag id store in the cache.
15
+ const getTagId = tag => tag.id || tag.outerHTML;
16
+
17
+ // Map incoming head tags by their content.
18
+ const newHeadMap = new Map();
19
+ for (const child of newHead) {
20
+ newHeadMap.set(getTagId(child), child);
21
+ }
22
+ const toRemove = [];
23
+
24
+ // Detect nodes that should be added or removed.
25
+ for (const child of document.head.children) {
26
+ const id = getTagId(child);
27
+ // Always remove styles and links as they might change.
28
+ if (child.nodeName === 'LINK' || child.nodeName === 'STYLE') {
29
+ toRemove.push(child);
30
+ } else if (newHeadMap.has(id)) {
31
+ newHeadMap.delete(id);
32
+ } else if (child.nodeName !== 'SCRIPT' && child.nodeName !== 'META') {
33
+ toRemove.push(child);
34
+ }
35
+ }
36
+
37
+ // Prepare new assets.
38
+ const toAppend = [...newHeadMap.values()];
39
+
40
+ // Apply the changes.
41
+ toRemove.forEach(n => n.remove());
42
+ document.head.append(...toAppend);
43
+ };
44
+
45
+ /**
46
+ * Fetches and processes head assets (stylesheets and scripts) from a specified document.
47
+ *
48
+ * @async
49
+ * @param {Document} doc The document from which to fetch head assets. It should support standard DOM querying methods.
50
+ * @param {Map} headElements A map of head elements to modify tracking the URLs of already processed assets to avoid duplicates.
51
+ *
52
+ * @return {Promise<HTMLElement[]>} Returns an array of HTML elements representing the head assets.
53
+ */
54
+ exports.updateHead = updateHead;
55
+ const fetchHeadAssets = async (doc, headElements) => {
56
+ const headTags = [];
57
+ const assets = [{
58
+ tagName: 'style',
59
+ selector: 'link[rel=stylesheet]',
60
+ attribute: 'href'
61
+ }, {
62
+ tagName: 'script',
63
+ selector: 'script[src]',
64
+ attribute: 'src'
65
+ }];
66
+ for (const asset of assets) {
67
+ const {
68
+ tagName,
69
+ selector,
70
+ attribute
71
+ } = asset;
72
+ const tags = doc.querySelectorAll(selector);
73
+
74
+ // Use Promise.all to wait for fetch to complete
75
+ await Promise.all(Array.from(tags).map(async tag => {
76
+ const attributeValue = tag.getAttribute(attribute);
77
+ if (!headElements.has(attributeValue)) {
78
+ try {
79
+ const response = await fetch(attributeValue);
80
+ const text = await response.text();
81
+ headElements.set(attributeValue, {
82
+ tag,
83
+ text
84
+ });
85
+ } catch (e) {
86
+ // eslint-disable-next-line no-console
87
+ console.error(e);
88
+ }
89
+ }
90
+ const headElement = headElements.get(attributeValue);
91
+ const element = doc.createElement(tagName);
92
+ element.innerText = headElement.text;
93
+ for (const attr of headElement.tag.attributes) {
94
+ element.setAttribute(attr.name, attr.value);
95
+ }
96
+ headTags.push(element);
97
+ }));
98
+ }
99
+ return [doc.querySelector('title'), ...doc.querySelectorAll('style'), ...headTags];
100
+ };
101
+ exports.fetchHeadAssets = fetchHeadAssets;
102
+ //# sourceMappingURL=head.js.map
@@ -0,0 +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","exports","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.js"],"sourcesContent":["/**\n * Helper to update only the necessary tags in the head.\n *\n * @async\n * @param {Array} newHead The head elements of the new page.\n */\nexport const updateHead = async ( newHead ) => {\n\t// Helper to get the tag id store in the cache.\n\tconst getTagId = ( tag ) => tag.id || tag.outerHTML;\n\n\t// Map incoming head tags by their content.\n\tconst newHeadMap = new Map();\n\tfor ( const child of newHead ) {\n\t\tnewHeadMap.set( getTagId( child ), child );\n\t}\n\n\tconst toRemove = [];\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 {Document} doc The document from which to fetch head assets. It should support standard DOM querying methods.\n * @param {Map} headElements A map of head elements to modify tracking the URLs of already processed assets to avoid duplicates.\n *\n * @return {Promise<HTMLElement[]>} Returns an array of HTML elements representing the head assets.\n */\nexport const fetchHeadAssets = async ( doc, headElements ) => {\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( 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;AACO,MAAMA,UAAU,GAAG,MAAQC,OAAO,IAAM;EAC9C;EACA,MAAMC,QAAQ,GAAKC,GAAG,IAAMA,GAAG,CAACC,EAAE,IAAID,GAAG,CAACE,SAAS;;EAEnD;EACA,MAAMC,UAAU,GAAG,IAAIC,GAAG,CAAC,CAAC;EAC5B,KAAM,MAAMC,KAAK,IAAIP,OAAO,EAAG;IAC9BK,UAAU,CAACG,GAAG,CAAEP,QAAQ,CAAEM,KAAM,CAAC,EAAEA,KAAM,CAAC;EAC3C;EAEA,MAAME,QAAQ,GAAG,EAAE;;EAEnB;EACA,KAAM,MAAMF,KAAK,IAAIG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AAQ,CACX;AACF,CAAC;AAACJ,OAAA,CAAAC,eAAA,GAAAA,eAAA","ignoreList":[]}
package/build/index.js CHANGED
@@ -5,10 +5,14 @@ Object.defineProperty(exports, "__esModule", {
5
5
  });
6
6
  exports.state = exports.actions = void 0;
7
7
  var _interactivity = require("@wordpress/interactivity");
8
+ var _head = require("./head");
9
+ var _getConfig$navigation;
8
10
  /**
9
11
  * WordPress dependencies
10
12
  */
11
-
13
+ /**
14
+ * Internal dependencies
15
+ */
12
16
  const {
13
17
  directivePrefix,
14
18
  getRegionRootFragment,
@@ -20,8 +24,12 @@ const {
20
24
  batch
21
25
  } = (0, _interactivity.privateApis)('I acknowledge that using private APIs means my theme or plugin will inevitably break in the next version of WordPress.');
22
26
 
23
- // The cache of visited and prefetched pages.
27
+ // Check if the navigation mode is full page or region based.
28
+ const navigationMode = (_getConfig$navigation = (0, _interactivity.getConfig)('core/router').navigationMode) !== null && _getConfig$navigation !== void 0 ? _getConfig$navigation : 'regionBased';
29
+
30
+ // The cache of visited and prefetched pages, stylesheets and scripts.
24
31
  const pages = new Map();
32
+ const headElements = new Map();
25
33
 
26
34
  // Helper to remove domain and hash from the URL. We are only interesting in
27
35
  // caching the path and the query.
@@ -37,7 +45,9 @@ const fetchPage = async (url, {
37
45
  try {
38
46
  if (!html) {
39
47
  const res = await window.fetch(url);
40
- if (res.status !== 200) return false;
48
+ if (res.status !== 200) {
49
+ return false;
50
+ }
41
51
  html = await res.text();
42
52
  }
43
53
  const dom = new window.DOMParser().parseFromString(html, 'text/html');
@@ -49,19 +59,29 @@ const fetchPage = async (url, {
49
59
 
50
60
  // Return an object with VDOM trees of those HTML regions marked with a
51
61
  // `router-region` directive.
52
- const regionsToVdom = (dom, {
62
+ const regionsToVdom = async (dom, {
53
63
  vdom
54
64
  } = {}) => {
55
65
  const regions = {};
56
- const attrName = `data-${directivePrefix}-router-region`;
57
- dom.querySelectorAll(`[${attrName}]`).forEach(region => {
58
- const id = region.getAttribute(attrName);
59
- regions[id] = vdom?.has(region) ? vdom.get(region) : toVdom(region);
60
- });
66
+ let head;
67
+ if (process.env.IS_GUTENBERG_PLUGIN) {
68
+ if (navigationMode === 'fullPage') {
69
+ head = await (0, _head.fetchHeadAssets)(dom, headElements);
70
+ regions.body = vdom ? vdom.get(document.body) : toVdom(dom.body);
71
+ }
72
+ }
73
+ if (navigationMode === 'regionBased') {
74
+ const attrName = `data-${directivePrefix}-router-region`;
75
+ dom.querySelectorAll(`[${attrName}]`).forEach(region => {
76
+ const id = region.getAttribute(attrName);
77
+ regions[id] = vdom?.has(region) ? vdom.get(region) : toVdom(region);
78
+ });
79
+ }
61
80
  const title = dom.querySelector('title')?.innerText;
62
81
  const initialData = parseInitialData(dom);
63
82
  return {
64
83
  regions,
84
+ head,
65
85
  title,
66
86
  initialData
67
87
  };
@@ -70,13 +90,23 @@ const regionsToVdom = (dom, {
70
90
  // Render all interactive regions contained in the given page.
71
91
  const renderRegions = page => {
72
92
  batch(() => {
73
- populateInitialData(page.initialData);
74
- const attrName = `data-${directivePrefix}-router-region`;
75
- document.querySelectorAll(`[${attrName}]`).forEach(region => {
76
- const id = region.getAttribute(attrName);
77
- const fragment = getRegionRootFragment(region);
78
- render(page.regions[id], fragment);
79
- });
93
+ if (process.env.IS_GUTENBERG_PLUGIN) {
94
+ if (navigationMode === 'fullPage') {
95
+ // Once this code is tested and more mature, the head should be updated for region based navigation as well.
96
+ (0, _head.updateHead)(page.head);
97
+ const fragment = getRegionRootFragment(document.body);
98
+ render(page.regions.body, fragment);
99
+ }
100
+ }
101
+ if (navigationMode === 'regionBased') {
102
+ populateInitialData(page.initialData);
103
+ const attrName = `data-${directivePrefix}-router-region`;
104
+ document.querySelectorAll(`[${attrName}]`).forEach(region => {
105
+ const id = region.getAttribute(attrName);
106
+ const fragment = getRegionRootFragment(region);
107
+ render(page.regions[id], fragment);
108
+ });
109
+ }
80
110
  if (page.title) {
81
111
  document.title = page.title;
82
112
  }
@@ -112,11 +142,38 @@ window.addEventListener('popstate', async () => {
112
142
  }
113
143
  });
114
144
 
115
- // Cache the initial page using the intially parsed vDOM.
145
+ // Initialize the router and cache the initial page using the initial vDOM.
146
+ // Once this code is tested and more mature, the head should be updated for region based navigation as well.
147
+ if (process.env.IS_GUTENBERG_PLUGIN) {
148
+ if (navigationMode === 'fullPage') {
149
+ // Cache the scripts. Has to be called before fetching the assets.
150
+ [].map.call(document.querySelectorAll('script[src]'), script => {
151
+ headElements.set(script.getAttribute('src'), {
152
+ tag: script,
153
+ text: script.textContent
154
+ });
155
+ });
156
+ await (0, _head.fetchHeadAssets)(document, headElements);
157
+ }
158
+ }
116
159
  pages.set(getPagePath(window.location), Promise.resolve(regionsToVdom(document, {
117
160
  vdom: initialVdom
118
161
  })));
119
162
 
163
+ // Check if the link is valid for client-side navigation.
164
+ const isValidLink = ref => ref && ref instanceof window.HTMLAnchorElement && ref.href && (!ref.target || ref.target === '_self') && ref.origin === window.location.origin && !ref.pathname.startsWith('/wp-admin') && !ref.pathname.startsWith('/wp-login.php') && !ref.getAttribute('href').startsWith('#') && !new URL(ref.href).searchParams.has('_wpnonce');
165
+
166
+ // Check if the event is valid for client-side navigation.
167
+ const isValidEvent = event => event && event.button === 0 &&
168
+ // Left clicks only.
169
+ !event.metaKey &&
170
+ // Open in new tab (Mac).
171
+ !event.ctrlKey &&
172
+ // Open in new tab (Windows).
173
+ !event.altKey &&
174
+ // Download.
175
+ !event.shiftKey && !event.defaultPrevented;
176
+
120
177
  // Variable to store the current navigation.
121
178
  let navigatingTo = '';
122
179
  const {
@@ -175,7 +232,9 @@ const {
175
232
 
176
233
  // Don't update the navigation status immediately, wait 400 ms.
177
234
  const loadingTimeout = setTimeout(() => {
178
- if (navigatingTo !== href) return;
235
+ if (navigatingTo !== href) {
236
+ return;
237
+ }
179
238
  if (loadingAnimation) {
180
239
  navigation.hasStarted = true;
181
240
  navigation.hasFinished = false;
@@ -192,9 +251,11 @@ const {
192
251
  // Once the page is fetched, the destination URL could have changed
193
252
  // (e.g., by clicking another link in the meantime). If so, bail
194
253
  // out, and let the newer execution to update the HTML.
195
- if (navigatingTo !== href) return;
254
+ if (navigatingTo !== href) {
255
+ return;
256
+ }
196
257
  if (page && !page.initialData?.config?.['core/router']?.clientNavigationDisabled) {
197
- renderRegions(page);
258
+ yield renderRegions(page);
198
259
  window.history[options.replace ? 'replaceState' : 'pushState']({}, '', href);
199
260
 
200
261
  // Update the URL in the state.
@@ -212,6 +273,14 @@ const {
212
273
  // package: https://github.com/WordPress/gutenberg/blob/c395242b8e6ee20f8b06c199e4fc2920d7018af1/packages/a11y/src/filter-message.js#L20-L26
213
274
  navigation.message = navigation.texts.loaded + (navigation.message === navigation.texts.loaded ? '\u00A0' : '');
214
275
  }
276
+
277
+ // Scroll to the anchor if exits in the link.
278
+ const {
279
+ hash
280
+ } = new URL(href, window.location);
281
+ if (hash) {
282
+ document.querySelector(hash)?.scrollIntoView();
283
+ }
215
284
  } else {
216
285
  yield forcePageReload(href);
217
286
  }
@@ -225,14 +294,15 @@ const {
225
294
  * @param {string} url The page URL.
226
295
  * @param {Object} [options] Options object.
227
296
  * @param {boolean} [options.force] Force fetching the URL again.
228
- * @param {string} [options.html] HTML string to be used instead of
229
- * fetching the requested URL.
297
+ * @param {string} [options.html] HTML string to be used instead of fetching the requested URL.
230
298
  */
231
299
  prefetch(url, options = {}) {
232
300
  const {
233
301
  clientNavigationDisabled
234
302
  } = (0, _interactivity.getConfig)();
235
- if (clientNavigationDisabled) return;
303
+ if (clientNavigationDisabled) {
304
+ return;
305
+ }
236
306
  const pagePath = getPagePath(url);
237
307
  if (options.force || !pages.has(pagePath)) {
238
308
  pages.set(pagePath, fetchPage(pagePath, options));
@@ -240,6 +310,29 @@ const {
240
310
  }
241
311
  }
242
312
  });
313
+
314
+ // Add click and prefetch to all links.
243
315
  exports.actions = actions;
244
316
  exports.state = state;
317
+ if (process.env.IS_GUTENBERG_PLUGIN) {
318
+ if (navigationMode === 'fullPage') {
319
+ // Navigate on click.
320
+ document.addEventListener('click', function (event) {
321
+ const ref = event.target.closest('a');
322
+ if (isValidLink(ref) && isValidEvent(event)) {
323
+ event.preventDefault();
324
+ actions.navigate(ref.href);
325
+ }
326
+ }, true);
327
+ // Prefetch on hover.
328
+ document.addEventListener('mouseenter', function (event) {
329
+ if (event.target?.nodeName === 'A') {
330
+ const ref = event.target.closest('a');
331
+ if (isValidLink(ref) && isValidEvent(event)) {
332
+ actions.prefetch(ref.href);
333
+ }
334
+ }
335
+ }, true);
336
+ }
337
+ }
245
338
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"names":["_interactivity","require","directivePrefix","getRegionRootFragment","initialVdom","toVdom","render","parseInitialData","populateInitialData","batch","privateApis","pages","Map","getPagePath","url","u","URL","window","location","pathname","search","fetchPage","html","res","fetch","status","text","dom","DOMParser","parseFromString","regionsToVdom","e","vdom","regions","attrName","querySelectorAll","forEach","region","id","getAttribute","has","get","title","querySelector","innerText","initialData","renderRegions","page","document","fragment","forcePageReload","href","assign","Promise","addEventListener","pagePath","state","reload","set","resolve","navigatingTo","actions","store","navigation","hasStarted","hasFinished","texts","navigate","options","clientNavigationDisabled","getConfig","loadingAnimation","screenReaderAnnouncement","timeout","prefetch","timeoutPromise","setTimeout","loadingTimeout","message","loading","race","clearTimeout","config","history","replace","loaded","force","exports"],"sources":["@wordpress/interactivity-router/src/index.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { store, privateApis, getConfig } from '@wordpress/interactivity';\n\nconst {\n\tdirectivePrefix,\n\tgetRegionRootFragment,\n\tinitialVdom,\n\ttoVdom,\n\trender,\n\tparseInitialData,\n\tpopulateInitialData,\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\n// The cache of visited and prefetched pages.\nconst pages = new Map();\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 ) => {\n\tconst u = new URL( url, window.location );\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, { html } ) => {\n\ttry {\n\t\tif ( ! html ) {\n\t\t\tconst res = await window.fetch( url );\n\t\t\tif ( res.status !== 200 ) return false;\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 = ( dom, { vdom } = {} ) => {\n\tconst regions = {};\n\tconst attrName = `data-${ directivePrefix }-router-region`;\n\tdom.querySelectorAll( `[${ attrName }]` ).forEach( ( region ) => {\n\t\tconst id = region.getAttribute( attrName );\n\t\tregions[ id ] = vdom?.has( region )\n\t\t\t? vdom.get( region )\n\t\t\t: toVdom( region );\n\t} );\n\tconst title = dom.querySelector( 'title' )?.innerText;\n\tconst initialData = parseInitialData( dom );\n\treturn { regions, title, initialData };\n};\n\n// Render all interactive regions contained in the given page.\nconst renderRegions = ( page ) => {\n\tbatch( () => {\n\t\tpopulateInitialData( page.initialData );\n\t\tconst attrName = `data-${ directivePrefix }-router-region`;\n\t\tdocument.querySelectorAll( `[${ attrName }]` ).forEach( ( region ) => {\n\t\t\tconst id = region.getAttribute( attrName );\n\t\t\tconst fragment = getRegionRootFragment( region );\n\t\t\trender( page.regions[ id ], fragment );\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 {string} href The page href.\n * @return {Promise} Promise that never resolves.\n */\nconst forcePageReload = ( href ) => {\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 ); // 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// Cache the initial page using the intially parsed vDOM.\npages.set(\n\tgetPagePath( window.location ),\n\tPromise.resolve( regionsToVdom( document, { vdom: initialVdom } ) )\n);\n\n// Variable to store the current navigation.\nlet navigatingTo = '';\n\nexport const { state, actions } = 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\ttexts: {},\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 {string} href The page href.\n\t\t * @param {Object} [options] Options object.\n\t\t * @param {boolean} [options.force] If true, it forces re-fetching the URL.\n\t\t * @param {string} [options.html] HTML string to be used instead of fetching the requested URL.\n\t\t * @param {boolean} [options.replace] If true, it replaces the current entry in the browser session history.\n\t\t * @param {number} [options.timeout] Time until the navigation is aborted, in milliseconds. Default is 10000.\n\t\t * @param {boolean} [options.loadingAnimation] Whether an animation should be shown while navigating. Default to `true`.\n\t\t * @param {boolean} [options.screenReaderAnnouncement] Whether a message for screen readers should be announced while navigating. Default to `true`.\n\t\t *\n\t\t * @return {Promise} Promise that resolves once the navigation is completed or aborted.\n\t\t */\n\t\t*navigate( href, options = {} ) {\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( ( 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 ) return;\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\tnavigation.message = navigation.texts.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 ) return;\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\trenderRegions( 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\t// Announce that the page has been loaded. If the message is the\n\t\t\t\t\t// same, we use a no-break space similar to the @wordpress/a11y\n\t\t\t\t\t// package: https://github.com/WordPress/gutenberg/blob/c395242b8e6ee20f8b06c199e4fc2920d7018af1/packages/a11y/src/filter-message.js#L20-L26\n\t\t\t\t\tnavigation.message =\n\t\t\t\t\t\tnavigation.texts.loaded +\n\t\t\t\t\t\t( navigation.message === navigation.texts.loaded\n\t\t\t\t\t\t\t? '\\u00A0'\n\t\t\t\t\t\t\t: '' );\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 {string} url The page URL.\n\t\t * @param {Object} [options] Options object.\n\t\t * @param {boolean} [options.force] Force fetching the URL again.\n\t\t * @param {string} [options.html] HTML string to be used instead of\n\t\t * fetching the requested URL.\n\t\t */\n\t\tprefetch( url, options = {} ) {\n\t\t\tconst { clientNavigationDisabled } = getConfig();\n\t\t\tif ( clientNavigationDisabled ) return;\n\n\t\t\tconst pagePath = getPagePath( url );\n\t\t\tif ( options.force || ! pages.has( pagePath ) ) {\n\t\t\t\tpages.set( pagePath, fetchPage( pagePath, options ) );\n\t\t\t}\n\t\t},\n\t},\n} );\n"],"mappings":";;;;;;AAGA,IAAAA,cAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA,MAAM;EACLC,eAAe;EACfC,qBAAqB;EACrBC,WAAW;EACXC,MAAM;EACNC,MAAM;EACNC,gBAAgB;EAChBC,mBAAmB;EACnBC;AACD,CAAC,GAAG,IAAAC,0BAAW,EACd,wHACD,CAAC;;AAED;AACA,MAAMC,KAAK,GAAG,IAAIC,GAAG,CAAC,CAAC;;AAEv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AAG;UACvBR,UAAU,CAACC,UAAU,GAAG,KAAK;UAC7BD,UAAU,CAACE,WAAW,GAAG,IAAI;QAC9B;QAEA,IAAKO,wBAAwB,EAAG;UAC/B;UACA;UACA;UACAT,UAAU,CAACe,OAAO,GACjBf,UAAU,CAACG,KAAK,CAACmB,MAAM,IACrBtB,UAAU,CAACe,OAAO,KAAKf,UAAU,CAACG,KAAK,CAACmB,MAAM,GAC7C,QAAQ,GACR,EAAE,CAAE;QACT;MACD,CAAC,MAAM;QACN,MAAMnC,eAAe,CAAEC,IAAK,CAAC;MAC9B;IACD,CAAC;IAED;AACF;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;IACEuB,QAAQA,CAAE5D,GAAG,EAAEsD,OAAO,GAAG,CAAC,CAAC,EAAG;MAC7B,MAAM;QAAEC;MAAyB,CAAC,GAAG,IAAAC,wBAAS,EAAC,CAAC;MAChD,IAAKD,wBAAwB,EAAG;MAEhC,MAAMd,QAAQ,GAAG1C,WAAW,CAAEC,GAAI,CAAC;MACnC,IAAKsD,OAAO,CAACkB,KAAK,IAAI,CAAE3E,KAAK,CAAC6B,GAAG,CAAEe,QAAS,CAAC,EAAG;QAC/C5C,KAAK,CAAC+C,GAAG,CAAEH,QAAQ,EAAElC,SAAS,CAAEkC,QAAQ,EAAEa,OAAQ,CAAE,CAAC;MACtD;IACD;EACD;AACD,CAAE,CAAC;AAACmB,OAAA,CAAA1B,OAAA,GAAAA,OAAA;AAAA0B,OAAA,CAAA/B,KAAA,GAAAA,KAAA","ignoreList":[]}
1
+ {"version":3,"names":["_interactivity","require","_head","_getConfig$navigation","directivePrefix","getRegionRootFragment","initialVdom","toVdom","render","parseInitialData","populateInitialData","batch","privateApis","navigationMode","getConfig","pages","Map","headElements","getPagePath","url","u","URL","window","location","pathname","search","fetchPage","html","res","fetch","status","text","dom","DOMParser","parseFromString","regionsToVdom","e","vdom","regions","head","process","env","IS_GUTENBERG_PLUGIN","fetchHeadAssets","body","get","document","attrName","querySelectorAll","forEach","region","id","getAttribute","has","title","querySelector","innerText","initialData","renderRegions","page","updateHead","fragment","forcePageReload","href","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","actions","store","navigation","hasStarted","hasFinished","texts","navigate","options","clientNavigationDisabled","loadingAnimation","screenReaderAnnouncement","timeout","prefetch","timeoutPromise","setTimeout","loadingTimeout","message","loading","race","clearTimeout","config","history","replace","loaded","hash","scrollIntoView","force","exports","closest","preventDefault","nodeName"],"sources":["@wordpress/interactivity-router/src/index.js"],"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\tparseInitialData,\n\tpopulateInitialData,\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\n// Check if the navigation mode is full page or region based.\nconst navigationMode =\n\tgetConfig( 'core/router' ).navigationMode ?? 'regionBased';\n\n// The cache of visited and prefetched pages, stylesheets and scripts.\nconst pages = new Map();\nconst headElements = new Map();\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 ) => {\n\tconst u = new URL( url, window.location );\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, { html } ) => {\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 = async ( dom, { vdom } = {} ) => {\n\tconst regions = {};\n\tlet head;\n\tif ( process.env.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 = parseInitialData( dom );\n\treturn { regions, head, title, initialData };\n};\n\n// Render all interactive regions contained in the given page.\nconst renderRegions = ( page ) => {\n\tbatch( () => {\n\t\tif ( process.env.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\tpopulateInitialData( 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 {string} href The page href.\n * @return {Promise} Promise that never resolves.\n */\nconst forcePageReload = ( href ) => {\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 ); // 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 region based navigation as well.\nif ( process.env.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 ),\n\tPromise.resolve( regionsToVdom( document, { vdom: initialVdom } ) )\n);\n\n// Check if the link is valid for client-side navigation.\nconst isValidLink = ( ref ) =>\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 ) =>\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\nexport const { state, actions } = 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\ttexts: {},\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 {string} href The page href.\n\t\t * @param {Object} [options] Options object.\n\t\t * @param {boolean} [options.force] If true, it forces re-fetching the URL.\n\t\t * @param {string} [options.html] HTML string to be used instead of fetching the requested URL.\n\t\t * @param {boolean} [options.replace] If true, it replaces the current entry in the browser session history.\n\t\t * @param {number} [options.timeout] Time until the navigation is aborted, in milliseconds. Default is 10000.\n\t\t * @param {boolean} [options.loadingAnimation] Whether an animation should be shown while navigating. Default to `true`.\n\t\t * @param {boolean} [options.screenReaderAnnouncement] Whether a message for screen readers should be announced while navigating. Default to `true`.\n\t\t *\n\t\t * @return {Promise} Promise that resolves once the navigation is completed or aborted.\n\t\t */\n\t\t*navigate( href, options = {} ) {\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( ( 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\tnavigation.message = navigation.texts.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\t// Announce that the page has been loaded. If the message is the\n\t\t\t\t\t// same, we use a no-break space similar to the @wordpress/a11y\n\t\t\t\t\t// package: https://github.com/WordPress/gutenberg/blob/c395242b8e6ee20f8b06c199e4fc2920d7018af1/packages/a11y/src/filter-message.js#L20-L26\n\t\t\t\t\tnavigation.message =\n\t\t\t\t\t\tnavigation.texts.loaded +\n\t\t\t\t\t\t( navigation.message === navigation.texts.loaded\n\t\t\t\t\t\t\t? '\\u00A0'\n\t\t\t\t\t\t\t: '' );\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 );\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 {string} url The page URL.\n\t\t * @param {Object} [options] Options object.\n\t\t * @param {boolean} [options.force] Force fetching the URL again.\n\t\t * @param {string} [options.html] HTML string to be used instead of fetching the requested URL.\n\t\t */\n\t\tprefetch( url, options = {} ) {\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( pagePath, fetchPage( pagePath, options ) );\n\t\t\t}\n\t\t},\n\t},\n} );\n\n// Add click and prefetch to all links.\nif ( process.env.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.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?.nodeName === 'A' ) {\n\t\t\t\t\tconst ref = event.target.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":";;;;;;AAGA,IAAAA,cAAA,GAAAC,OAAA;AAKA,IAAAC,KAAA,GAAAD,OAAA;AAAqD,IAAAE,qBAAA;AARrD;AACA;AACA;AAGA;AACA;AACA;AAGA,MAAM;EACLC,eAAe;EACfC,qBAAqB;EACrBC,WAAW;EACXC,MAAM;EACNC,MAAM;EACNC,gBAAgB;EAChBC,mBAAmB;EACnBC;AACD,CAAC,GAAG,IAAAC,0BAAW,EACd,wHACD,CAAC;;AAED;AACA,MAAMC,cAAc,IAAAV,qBAAA,GACnB,IAAAW,wBAAS,EAAE,aAAc,CAAC,CAACD,cAAc,cAAAV,qBAAA,cAAAA,qBAAA,GAAI,aAAa;;AAE3D;AACA,MAAMY,KAAK,GAAG,IAAIC,GAAG,CAAC,CAAC;AACvB,MAAMC,YAAY,GAAG,IAAID,GAAG,CAAC,CAAC;;AAE9B;AACA;AACA,MAAME,WAAW,GAAKC,GAAG,IAAM;EAC9B,MAAMC,CAAC,GAAG,IAAIC,GAAG,CAAEF,GAAG,EAAEG,MAAM,CAACC,QAAS,CAAC;EACzC,OAAOH,CAAC,CAACI,QAAQ,GAAGJ,CAAC,CAACK,MAAM;AAC7B,CAAC;;AAED;AACA,MAAMC,SAAS,GAAG,M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CAACL,MAAM,CAACyC,OAAO,CAAE,GAAI,CAAC;QACvC,IAAK5C,WAAW,CAAEC,GAAI,CAAC,IAAIM,YAAY,CAAEC,KAAM,CAAC,EAAG;UAClDQ,OAAO,CAACY,QAAQ,CAAE3B,GAAG,CAACf,IAAK,CAAC;QAC7B;MACD;IACD,CAAC,EACD,IACD,CAAC;EACF;AACD","ignoreList":[]}
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Helper to update only the necessary tags in the head.
3
+ *
4
+ * @async
5
+ * @param {Array} newHead The head elements of the new page.
6
+ */
7
+ export const updateHead = async newHead => {
8
+ // Helper to get the tag id store in the cache.
9
+ const getTagId = tag => tag.id || tag.outerHTML;
10
+
11
+ // Map incoming head tags by their content.
12
+ const newHeadMap = new Map();
13
+ for (const child of newHead) {
14
+ newHeadMap.set(getTagId(child), child);
15
+ }
16
+ const toRemove = [];
17
+
18
+ // Detect nodes that should be added or removed.
19
+ for (const child of document.head.children) {
20
+ const id = getTagId(child);
21
+ // Always remove styles and links as they might change.
22
+ if (child.nodeName === 'LINK' || child.nodeName === 'STYLE') {
23
+ toRemove.push(child);
24
+ } else if (newHeadMap.has(id)) {
25
+ newHeadMap.delete(id);
26
+ } else if (child.nodeName !== 'SCRIPT' && child.nodeName !== 'META') {
27
+ toRemove.push(child);
28
+ }
29
+ }
30
+
31
+ // Prepare new assets.
32
+ const toAppend = [...newHeadMap.values()];
33
+
34
+ // Apply the changes.
35
+ toRemove.forEach(n => n.remove());
36
+ document.head.append(...toAppend);
37
+ };
38
+
39
+ /**
40
+ * Fetches and processes head assets (stylesheets and scripts) from a specified document.
41
+ *
42
+ * @async
43
+ * @param {Document} doc The document from which to fetch head assets. It should support standard DOM querying methods.
44
+ * @param {Map} headElements A map of head elements to modify tracking the URLs of already processed assets to avoid duplicates.
45
+ *
46
+ * @return {Promise<HTMLElement[]>} Returns an array of HTML elements representing the head assets.
47
+ */
48
+ export const fetchHeadAssets = async (doc, headElements) => {
49
+ const headTags = [];
50
+ const assets = [{
51
+ tagName: 'style',
52
+ selector: 'link[rel=stylesheet]',
53
+ attribute: 'href'
54
+ }, {
55
+ tagName: 'script',
56
+ selector: 'script[src]',
57
+ attribute: 'src'
58
+ }];
59
+ for (const asset of assets) {
60
+ const {
61
+ tagName,
62
+ selector,
63
+ attribute
64
+ } = asset;
65
+ const tags = doc.querySelectorAll(selector);
66
+
67
+ // Use Promise.all to wait for fetch to complete
68
+ await Promise.all(Array.from(tags).map(async tag => {
69
+ const attributeValue = tag.getAttribute(attribute);
70
+ if (!headElements.has(attributeValue)) {
71
+ try {
72
+ const response = await fetch(attributeValue);
73
+ const text = await response.text();
74
+ headElements.set(attributeValue, {
75
+ tag,
76
+ text
77
+ });
78
+ } catch (e) {
79
+ // eslint-disable-next-line no-console
80
+ console.error(e);
81
+ }
82
+ }
83
+ const headElement = headElements.get(attributeValue);
84
+ const element = doc.createElement(tagName);
85
+ element.innerText = headElement.text;
86
+ for (const attr of headElement.tag.attributes) {
87
+ element.setAttribute(attr.name, attr.value);
88
+ }
89
+ headTags.push(element);
90
+ }));
91
+ }
92
+ return [doc.querySelector('title'), ...doc.querySelectorAll('style'), ...headTags];
93
+ };
94
+ //# sourceMappingURL=head.js.map
@@ -0,0 +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.js"],"sourcesContent":["/**\n * Helper to update only the necessary tags in the head.\n *\n * @async\n * @param {Array} newHead The head elements of the new page.\n */\nexport const updateHead = async ( newHead ) => {\n\t// Helper to get the tag id store in the cache.\n\tconst getTagId = ( tag ) => tag.id || tag.outerHTML;\n\n\t// Map incoming head tags by their content.\n\tconst newHeadMap = new Map();\n\tfor ( const child of newHead ) {\n\t\tnewHeadMap.set( getTagId( child ), child );\n\t}\n\n\tconst toRemove = [];\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 {Document} doc The document from which to fetch head assets. It should support standard DOM querying methods.\n * @param {Map} headElements A map of head elements to modify tracking the URLs of already processed assets to avoid duplicates.\n *\n * @return {Promise<HTMLElement[]>} Returns an array of HTML elements representing the head assets.\n */\nexport const fetchHeadAssets = async ( doc, headElements ) => {\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( 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,OAAO,IAAM;EAC9C;EACA,MAAMC,QAAQ,GAAKC,GAAG,IAAMA,GAAG,CAACC,EAAE,IAAID,GAAG,CAACE,SAAS;;EAEnD;EACA,MAAMC,UAAU,GAAG,IAAIC,GAAG,CAAC,CAAC;EAC5B,KAAM,MAAMC,KAAK,IAAIP,OAAO,EAAG;IAC9BK,UAAU,CAACG,GAAG,CAAEP,QAAQ,CAAEM,KAAM,CAAC,EAAEA,KAAM,CAAC;EAC3C;EAEA,MAAME,QAAQ,GAAG,EAAE;;EAEnB;EACA,KAAM,MAAMF,KAAK,IAAIG,QAAQ,CAACC,IAAI,CAACC,QAAQ,EAAG;IAC7C,MAAMT,EAAE,GAAGF,QAAQ,CAAEM,KAAM,CAAC;IAC5B;IACA,IAAKA,KAAK,CAACM,QAAQ,KAAK,MAAM,IAAIN,KAAK,CAACM,QAAQ,KAAK,OAAO,EAAG;MAC9DJ,QAAQ,CAACK,IAAI,CAAEP,KAAM,CAAC;I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