-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
Copy pathindex.js
160 lines (146 loc) · 4.99 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
/**
* WordPress dependencies
*/
import {
render,
directivePrefix,
toVdom,
getRegionRootFragment,
store,
} from '@wordpress/interactivity';
// The cache of visited and prefetched pages.
const pages = new Map();
// Helper to remove domain and hash from the URL. We are only interesting in
// caching the path and the query.
const cleanUrl = ( url ) => {
const u = new URL( url, window.location );
return u.pathname + u.search;
};
// Fetch a new page and convert it to a static virtual DOM.
const fetchPage = async ( url, { html } ) => {
try {
if ( ! html ) {
const res = await window.fetch( url );
if ( res.status !== 200 ) return false;
html = await res.text();
}
const dom = new window.DOMParser().parseFromString( html, 'text/html' );
return regionsToVdom( dom );
} catch ( e ) {
return false;
}
};
// Return an object with VDOM trees of those HTML regions marked with a
// `router-region` directive.
const regionsToVdom = ( dom ) => {
const regions = {};
const attrName = `data-${ directivePrefix }-router-region`;
dom.querySelectorAll( `[${ attrName }]` ).forEach( ( region ) => {
const id = region.getAttribute( attrName );
regions[ id ] = toVdom( region );
} );
const title = dom.querySelector( 'title' )?.innerText;
return { regions, title };
};
// Render all interactive regions contained in the given page.
const renderRegions = ( page ) => {
const attrName = `data-${ directivePrefix }-router-region`;
document.querySelectorAll( `[${ attrName }]` ).forEach( ( region ) => {
const id = region.getAttribute( attrName );
const fragment = getRegionRootFragment( region );
render( page.regions[ id ], fragment );
} );
if ( page.title ) {
document.title = page.title;
}
};
// Variable to store the current navigation.
let navigatingTo = '';
// Listen to the back and forward buttons and restore the page if it's in the
// cache.
window.addEventListener( 'popstate', async () => {
const url = cleanUrl( window.location ); // Remove hash.
const page = pages.has( url ) && ( await pages.get( url ) );
if ( page ) {
renderRegions( page );
} else {
window.location.reload();
}
} );
// Cache the current regions.
pages.set(
cleanUrl( window.location ),
Promise.resolve( regionsToVdom( document ) )
);
export const { state, actions } = store( 'core/router', {
actions: {
/**
* Navigates to the specified page.
*
* This function normalizes the passed href, fetchs the page HTML if
* needed, and updates any interactive regions whose contents have
* changed. It also creates a new entry in the browser session history.
*
* @param {string} href The page href.
* @param {Object} [options] Options object.
* @param {boolean} [options.force] If true, it forces re-fetching the
* URL.
* @param {string} [options.html] HTML string to be used instead of
* fetching the requested URL.
* @param {boolean} [options.replace] If true, it replaces the current
* entry in the browser session
* history.
* @param {number} [options.timeout] Time until the navigation is
* aborted, in milliseconds. Default
* is 10000.
*
* @return {Promise} Promise that resolves once the navigation is
* completed or aborted.
*/
*navigate( href, options = {} ) {
const url = cleanUrl( href );
navigatingTo = href;
actions.prefetch( url, options );
// Create a promise that resolves when the specified timeout ends.
// The timeout value is 10 seconds by default.
const timeoutPromise = new Promise( ( resolve ) =>
setTimeout( resolve, options.timeout ?? 10000 )
);
const page = yield Promise.race( [
pages.get( url ),
timeoutPromise,
] );
// Once the page is fetched, the destination URL could have changed
// (e.g., by clicking another link in the meantime). If so, bail
// out, and let the newer execution to update the HTML.
if ( navigatingTo !== href ) return;
if ( page ) {
renderRegions( page );
window.history[
options.replace ? 'replaceState' : 'pushState'
]( {}, '', href );
} else {
window.location.assign( href );
yield new Promise( () => {} );
}
},
/**
* Prefetchs the page with the passed URL.
*
* The function normalizes the URL and stores internally the fetch
* promise, to avoid triggering a second fetch for an ongoing request.
*
* @param {string} url The page URL.
* @param {Object} [options] Options object.
* @param {boolean} [options.force] Force fetching the URL again.
* @param {string} [options.html] HTML string to be used instead of
* fetching the requested URL.
*/
prefetch( url, options = {} ) {
url = cleanUrl( url );
if ( options.force || ! pages.has( url ) ) {
pages.set( url, fetchPage( url, options ) );
}
},
},
} );