@ecopages/browser-router 0.6.1 → 0.7.1
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/README.md +21 -1
- package/package.json +5 -2
- package/src/client/dom/body-morpher.d.ts +40 -3
- package/src/client/dom/body-morpher.js +141 -35
- package/src/client/eco-router-perform-navigation.d.ts +2 -0
- package/src/client/eco-router-perform-navigation.js +2 -0
- package/src/client/eco-router.js +10 -4
- package/src/client/navigation-commit.d.ts +13 -0
- package/src/client/navigation-commit.js +22 -2
package/README.md
CHANGED
|
@@ -106,13 +106,22 @@ Call `router.stop()` before replacing the router script in long-lived sessions (
|
|
|
106
106
|
|
|
107
107
|
Mark elements with the same persistence key on each page to preserve them across navigations. When the incoming page keeps the element under a compatible ancestor structure, it stays connected and is never recreated; morphdom skips it entirely. This holds when view transitions are disabled and when the incoming page has `data-eco-rerun` scripts. Changing the element's ancestor tags can require replacing its containing path, so keep that structure stable when connection continuity matters.
|
|
108
108
|
|
|
109
|
-
|
|
109
|
+
On navigation to another URL, when an incoming page has a `data-eco-rerun` script, browser-router refreshes matching non-persisted elements before running it, except for the body, persisted elements, their ancestor path, and descendants of custom elements on that path. Those custom-element descendants stay in place because the connected host may have attached handlers to them. Keep handler-bound child markup structurally compatible across pages, or have the component rebind when its child markup changes; replacing a child does not reconnect the host. Event handlers installed on refreshed elements attach to new nodes instead of stacking on nodes retained by the morph. A rerun script that installs handlers on any retained node must make that registration idempotent, because those nodes remain attached across navigations.
|
|
110
110
|
|
|
111
111
|
```html
|
|
112
112
|
<!-- This counter keeps its internal state across all navigations -->
|
|
113
113
|
<radiant-counter data-eco-persist="counter"></radiant-counter>
|
|
114
114
|
```
|
|
115
115
|
|
|
116
|
+
## Reloading the current page
|
|
117
|
+
|
|
118
|
+
`reloadCurrentPage()` on the navigation runtime, which development HMR calls when a server-rendered template such as a page, layout, include or view is saved, and when a module update reloads the active page (`clearCache: false`), fetches the current URL again and compares each body element's server markup in the previous document with its markup in the new one, rather than with the live element. An element whose server markup did not change stays as it is, with its state, children, shadow root and runtime attributes; a changed custom element is replaced, and a changed plain element is morphed, keeping its live attributes when its own server attributes did not change. Rerun scripts do not refresh elements on a reload, so a `data-eco-rerun` script must register handlers idempotently on every element a reload does not replace, which is all but changed custom elements. Navigation to another URL morphs as described above. The router records server markup only after development HMR calls `enableReloadStatePreservation()` on the navigation runtime, so production navigations copy nothing.
|
|
119
|
+
|
|
120
|
+
Known limits:
|
|
121
|
+
|
|
122
|
+
- The first save after a full page load compares against the body as the router found it when recording started, so a component that rendered or changed its attributes on the client before then is replaced once.
|
|
123
|
+
- State follows tree position, so identical sibling hosts can swap state when an earlier sibling is inserted or removed.
|
|
124
|
+
|
|
116
125
|
## Scripts on navigation
|
|
117
126
|
|
|
118
127
|
After the swap, a head script runs only if the previous page's head did not have it, and body scripts run on every navigation, as in Turbo: the body is new content even when the previous page had the same script. That covers inline scripts and external classic scripts; an external module script runs only once per URL in a tab, because the browser evaluates each module URL once. A classic script's top-level `const`, `let` and `class` declarations live in the page's global scope, so when a classic body script runs again they are declared twice and throw `SyntaxError: Identifier '…' has already been declared`. Write such a script without them (use `var` or functions, or wrap the code in a block or an IIFE), or make it a module script, which runs once per URL, and listen for `eco:page-load` for code that must run on each visit. A script inside an element marked `data-eco-persist` is kept as it was and does not run again. Scripts run in one sequence: new head scripts, then `data-eco-rerun` scripts, then body scripts, each group in document order. Each waits until earlier blocking scripts (external classic scripts without `async`, `defer`, or `nomodule`) have loaded, as during page parsing, so an inline script that uses a library the page loads runs after it. External `defer` and module scripts keep that insertion order too; only scripts the page marks `async` run as soon as they load. If the next navigation swaps the page while a script is still loading, the rest of the previous sequence does not run.
|
|
@@ -157,6 +166,17 @@ document.addEventListener('eco:page-load', (e) => {
|
|
|
157
166
|
});
|
|
158
167
|
```
|
|
159
168
|
|
|
169
|
+
`e.detail.newDocument` is the parsed incoming document and a listener may change it. Custom elements the router inserts or replaces are the nodes of that document themselves, so properties you set on them, and their nested nodes, are still there when the browser upgrades and connects them:
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
document.addEventListener('eco:before-swap', (e) => {
|
|
173
|
+
const host = e.detail.newDocument.querySelector('my-host');
|
|
174
|
+
if (host) host.engine = engine;
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Elements the router keeps in place, such as persisted elements, ignore properties set on their incoming counterpart. A property set before an element upgrades shadows a class accessor of the same name and is reset by a class field of that name: the component should read the own value, delete it and assign it through the accessor in its constructor.
|
|
179
|
+
|
|
160
180
|
## Programmatic Navigation
|
|
161
181
|
|
|
162
182
|
Use the router instance to navigate programmatically:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecopages/browser-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Client-side router for Ecopages with view transitions support",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ecopages",
|
|
@@ -11,6 +11,9 @@
|
|
|
11
11
|
"view-transitions"
|
|
12
12
|
],
|
|
13
13
|
"license": "MIT",
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": "^24.22.0 || >=26.0.0"
|
|
16
|
+
},
|
|
14
17
|
"type": "module",
|
|
15
18
|
"exports": {
|
|
16
19
|
".": {
|
|
@@ -38,7 +41,7 @@
|
|
|
38
41
|
"morphdom": "^2.7.8"
|
|
39
42
|
},
|
|
40
43
|
"peerDependencies": {
|
|
41
|
-
"@ecopages/core": "0.
|
|
44
|
+
"@ecopages/core": "0.7.1"
|
|
42
45
|
},
|
|
43
46
|
"types": "./src/index.d.ts"
|
|
44
47
|
}
|
|
@@ -1,3 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps each live body element to a detached copy of the server markup it was rendered from.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* A same-URL reload compares this markup with the incoming markup instead of comparing the live element, which
|
|
6
|
+
* always differs once a component or script has touched it.
|
|
7
|
+
*/
|
|
8
|
+
export type ServerMarkup = WeakMap<Element, Element>;
|
|
9
|
+
/**
|
|
10
|
+
* Records the current body as the server markup of the document the router starts on.
|
|
11
|
+
*
|
|
12
|
+
* @remarks
|
|
13
|
+
* The router cannot read the initial HTML response, so it copies the body as it finds it at start. An element a
|
|
14
|
+
* script changed before then counts as changed on the first same-URL reload and is replaced, as on navigation.
|
|
15
|
+
*/
|
|
16
|
+
export declare function recordInitialServerMarkup(serverMarkup: ServerMarkup): void;
|
|
17
|
+
export type MorphBodyOptions = {
|
|
18
|
+
/** Live-to-server element map that the morph reads on a reload and updates for the next one. */
|
|
19
|
+
serverMarkup?: ServerMarkup;
|
|
20
|
+
/**
|
|
21
|
+
* Set for a reload of the current URL: elements whose server markup did not change are kept as they are.
|
|
22
|
+
* Needs `serverMarkup`, which holds the previous markup.
|
|
23
|
+
*/
|
|
24
|
+
reload?: boolean;
|
|
25
|
+
};
|
|
1
26
|
/**
|
|
2
27
|
* Manually attaches declarative shadow DOM templates.
|
|
3
28
|
*
|
|
@@ -21,7 +46,19 @@ export declare function processDeclarativeShadowDOM(root: Element | Document | S
|
|
|
21
46
|
* also remain the same nodes when their markup stays structurally compatible;
|
|
22
47
|
* changed child markup can replace nodes without reconnecting the host, so
|
|
23
48
|
* components must handle rebinding.
|
|
24
|
-
* Light-DOM custom elements are
|
|
25
|
-
* disconnectedCallback → connectedCallback lifecycle.
|
|
49
|
+
* Light-DOM and hydrated custom elements are replaced by the incoming element itself, which triggers the
|
|
50
|
+
* disconnectedCallback → connectedCallback lifecycle. Elements the morph adds or replaces are the parsed
|
|
51
|
+
* nodes, so properties set on them in `eco:before-swap`, and the identity of their descendants, are preserved.
|
|
52
|
+
* Elements the morph keeps in place (persisted, retained, or plain elements it morphs) ignore properties set
|
|
53
|
+
* on their incoming counterpart.
|
|
54
|
+
*
|
|
55
|
+
* On a reload of the current URL, an element whose server markup is the same in the previous and the incoming
|
|
56
|
+
* document is kept with its state, its runtime attributes and its children, including custom elements and their
|
|
57
|
+
* shadow roots. A changed element is handled as on navigation, except that a plain element whose own server
|
|
58
|
+
* attributes did not change keeps its live attributes while its children are morphed. Rerun scripts do not
|
|
59
|
+
* refresh elements on a reload: a replaced ancestor would drop the unchanged elements inside it, so a rerun
|
|
60
|
+
* script must register handlers idempotently on every element a reload does not replace, which is all but changed custom elements.
|
|
61
|
+
* Elements are paired in tree order, as morphdom pairs them, so inserting or removing an earlier sibling with
|
|
62
|
+
* the same markup moves state to its neighbour.
|
|
26
63
|
*/
|
|
27
|
-
export declare function morphBody(newDocument: Document, persistAttribute: string): void;
|
|
64
|
+
export declare function morphBody(newDocument: Document, persistAttribute: string, { serverMarkup, reload }?: MorphBodyOptions): void;
|
|
@@ -47,6 +47,96 @@ function getBodyMorphKey(element, persistAttribute) {
|
|
|
47
47
|
}
|
|
48
48
|
return element.getAttribute(persistAttribute) || element.getAttribute(ECO_PERSIST_ATTRIBUTE) || undefined;
|
|
49
49
|
}
|
|
50
|
+
/**
|
|
51
|
+
* Pairs the elements of two subtrees with the same structure, such as an element and its clone.
|
|
52
|
+
*/
|
|
53
|
+
function recordServerSubtree(serverMarkup, live, server) {
|
|
54
|
+
serverMarkup.set(live, server);
|
|
55
|
+
const liveDescendants = live.querySelectorAll('*');
|
|
56
|
+
const serverDescendants = server.querySelectorAll('*');
|
|
57
|
+
for (let index = 0; index < liveDescendants.length; index++) {
|
|
58
|
+
serverMarkup.set(liveDescendants[index], serverDescendants[index]);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Copies a live element as markup, writing each open shadow root back as a declarative `<template>` and
|
|
63
|
+
* recording the copy of every element in `serverMarkup`.
|
|
64
|
+
*/
|
|
65
|
+
function copyLiveMarkup(element, serverMarkup) {
|
|
66
|
+
const copy = element.cloneNode(false);
|
|
67
|
+
serverMarkup.set(element, copy);
|
|
68
|
+
if (element.shadowRoot) {
|
|
69
|
+
const template = document.createElement('template');
|
|
70
|
+
template.setAttribute('shadowrootmode', element.shadowRoot.mode);
|
|
71
|
+
if (element.shadowRoot.delegatesFocus)
|
|
72
|
+
template.setAttribute('shadowrootdelegatesfocus', '');
|
|
73
|
+
if (element.shadowRoot.clonable)
|
|
74
|
+
template.setAttribute('shadowrootclonable', '');
|
|
75
|
+
if (element.shadowRoot.serializable)
|
|
76
|
+
template.setAttribute('shadowrootserializable', '');
|
|
77
|
+
for (const child of element.shadowRoot.childNodes) {
|
|
78
|
+
template.content.append(copyLiveNode(child, serverMarkup));
|
|
79
|
+
}
|
|
80
|
+
copy.append(template);
|
|
81
|
+
}
|
|
82
|
+
for (const child of element.childNodes) {
|
|
83
|
+
copy.append(copyLiveNode(child, serverMarkup));
|
|
84
|
+
}
|
|
85
|
+
return copy;
|
|
86
|
+
}
|
|
87
|
+
function copyLiveNode(node, serverMarkup) {
|
|
88
|
+
return node instanceof Element ? copyLiveMarkup(node, serverMarkup) : node.cloneNode(false);
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Records the current body as the server markup of the document the router starts on.
|
|
92
|
+
*
|
|
93
|
+
* @remarks
|
|
94
|
+
* The router cannot read the initial HTML response, so it copies the body as it finds it at start. An element a
|
|
95
|
+
* script changed before then counts as changed on the first same-URL reload and is replaced, as on navigation.
|
|
96
|
+
*/
|
|
97
|
+
export function recordInitialServerMarkup(serverMarkup) {
|
|
98
|
+
copyLiveMarkup(document.body, serverMarkup);
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* @remarks
|
|
102
|
+
* Compares serialized markup because `isEqualNode` ignores the contents of a `<template>`, which hold a
|
|
103
|
+
* declarative shadow root.
|
|
104
|
+
*/
|
|
105
|
+
function isUnchangedServerMarkup(previous, incoming) {
|
|
106
|
+
return previous !== undefined && incoming !== undefined && previous.outerHTML === incoming.outerHTML;
|
|
107
|
+
}
|
|
108
|
+
function hasSameAttributes(left, right) {
|
|
109
|
+
if (left.attributes.length !== right.attributes.length)
|
|
110
|
+
return false;
|
|
111
|
+
for (const attr of left.attributes) {
|
|
112
|
+
if (right.getAttribute(attr.name) !== attr.value)
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
return true;
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Gives the incoming element the live element's attributes, so the morph keeps attributes a script added.
|
|
119
|
+
*/
|
|
120
|
+
function adoptLiveAttributes(fromEl, toEl) {
|
|
121
|
+
for (const attr of Array.from(toEl.attributes)) {
|
|
122
|
+
if (!fromEl.hasAttribute(attr.name))
|
|
123
|
+
toEl.removeAttribute(attr.name);
|
|
124
|
+
}
|
|
125
|
+
for (const attr of fromEl.attributes) {
|
|
126
|
+
toEl.setAttribute(attr.name, attr.value);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* @returns Always `true`, to let morphdom update the element and visit its children.
|
|
131
|
+
*/
|
|
132
|
+
function updateElement(fromEl, toEl, previousServer, incomingServer, serverMarkup, reload) {
|
|
133
|
+
if (reload && previousServer && incomingServer && hasSameAttributes(previousServer, incomingServer)) {
|
|
134
|
+
adoptLiveAttributes(fromEl, toEl);
|
|
135
|
+
}
|
|
136
|
+
if (serverMarkup && incomingServer)
|
|
137
|
+
serverMarkup.set(fromEl, incomingServer);
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
50
140
|
function isLightDomCustomElement(element) {
|
|
51
141
|
return element.localName.includes('-') && element.shadowRoot === null;
|
|
52
142
|
}
|
|
@@ -58,33 +148,23 @@ function isLightDomCustomElement(element) {
|
|
|
58
148
|
* which can cause morphdom to skip siblings or process stale nodes.
|
|
59
149
|
* Deferring the replacement until after morphdom finishes avoids this.
|
|
60
150
|
*/
|
|
61
|
-
function deferElementReplacement(fromEl, toEl, deferred) {
|
|
62
|
-
deferred.push({
|
|
63
|
-
from: fromEl,
|
|
64
|
-
to: toEl.cloneNode(true),
|
|
65
|
-
isCustomElement: fromEl.localName.includes('-'),
|
|
66
|
-
});
|
|
151
|
+
function deferElementReplacement(fromEl, toEl, server, deferred) {
|
|
152
|
+
deferred.push({ from: fromEl, to: toEl, server });
|
|
67
153
|
return false;
|
|
68
154
|
}
|
|
69
|
-
function materializeCustomElement(element) {
|
|
70
|
-
const materializedElement = document.createElement(element.localName);
|
|
71
|
-
for (const attr of element.attributes) {
|
|
72
|
-
materializedElement.setAttribute(attr.name, attr.value);
|
|
73
|
-
}
|
|
74
|
-
materializedElement.innerHTML = element.innerHTML;
|
|
75
|
-
return materializedElement;
|
|
76
|
-
}
|
|
77
155
|
/**
|
|
78
156
|
* @remarks
|
|
79
|
-
*
|
|
157
|
+
* The incoming element itself replaces the live one, so properties set on it and the identity of its descendants
|
|
158
|
+
* survive. The browser disconnects the live element and upgrades and connects the incoming one, which fires
|
|
80
159
|
* their full lifecycle. Elements already removed during the morph pass are skipped.
|
|
81
160
|
*/
|
|
82
|
-
function flushDeferredReplacements(deferred) {
|
|
83
|
-
for (const { from, to,
|
|
161
|
+
function flushDeferredReplacements(deferred, serverMarkup) {
|
|
162
|
+
for (const { from, to, server } of deferred) {
|
|
84
163
|
if (!from.isConnected)
|
|
85
164
|
continue;
|
|
86
|
-
|
|
87
|
-
|
|
165
|
+
if (serverMarkup && server)
|
|
166
|
+
recordServerSubtree(serverMarkup, to, server);
|
|
167
|
+
from.replaceWith(to);
|
|
88
168
|
}
|
|
89
169
|
}
|
|
90
170
|
/**
|
|
@@ -122,45 +202,71 @@ export function processDeclarativeShadowDOM(root) {
|
|
|
122
202
|
* also remain the same nodes when their markup stays structurally compatible;
|
|
123
203
|
* changed child markup can replace nodes without reconnecting the host, so
|
|
124
204
|
* components must handle rebinding.
|
|
125
|
-
* Light-DOM custom elements are
|
|
126
|
-
* disconnectedCallback → connectedCallback lifecycle.
|
|
205
|
+
* Light-DOM and hydrated custom elements are replaced by the incoming element itself, which triggers the
|
|
206
|
+
* disconnectedCallback → connectedCallback lifecycle. Elements the morph adds or replaces are the parsed
|
|
207
|
+
* nodes, so properties set on them in `eco:before-swap`, and the identity of their descendants, are preserved.
|
|
208
|
+
* Elements the morph keeps in place (persisted, retained, or plain elements it morphs) ignore properties set
|
|
209
|
+
* on their incoming counterpart.
|
|
210
|
+
*
|
|
211
|
+
* On a reload of the current URL, an element whose server markup is the same in the previous and the incoming
|
|
212
|
+
* document is kept with its state, its runtime attributes and its children, including custom elements and their
|
|
213
|
+
* shadow roots. A changed element is handled as on navigation, except that a plain element whose own server
|
|
214
|
+
* attributes did not change keeps its live attributes while its children are morphed. Rerun scripts do not
|
|
215
|
+
* refresh elements on a reload: a replaced ancestor would drop the unchanged elements inside it, so a rerun
|
|
216
|
+
* script must register handlers idempotently on every element a reload does not replace, which is all but changed custom elements.
|
|
217
|
+
* Elements are paired in tree order, as morphdom pairs them, so inserting or removing an earlier sibling with
|
|
218
|
+
* the same markup moves state to its neighbour.
|
|
127
219
|
*/
|
|
128
|
-
export function morphBody(newDocument, persistAttribute) {
|
|
220
|
+
export function morphBody(newDocument, persistAttribute, { serverMarkup, reload = false } = {}) {
|
|
129
221
|
const deferredReplacements = [];
|
|
130
|
-
const refreshUnpersistedElements = newDocument.querySelector('script[data-eco-rerun]') !== null;
|
|
222
|
+
const refreshUnpersistedElements = !reload && newDocument.querySelector('script[data-eco-rerun]') !== null;
|
|
131
223
|
const retainedRerunContext = refreshUnpersistedElements
|
|
132
224
|
? findPersistedRerunContext(document.body, persistAttribute)
|
|
133
225
|
: new Set();
|
|
226
|
+
const incomingServerMarkup = new Map();
|
|
227
|
+
if (serverMarkup) {
|
|
228
|
+
const serverBody = newDocument.body.cloneNode(true);
|
|
229
|
+
incomingServerMarkup.set(newDocument.body, serverBody);
|
|
230
|
+
const incoming = newDocument.body.querySelectorAll('*');
|
|
231
|
+
const server = serverBody.querySelectorAll('*');
|
|
232
|
+
for (let index = 0; index < incoming.length; index++) {
|
|
233
|
+
incomingServerMarkup.set(incoming[index], server[index]);
|
|
234
|
+
}
|
|
235
|
+
}
|
|
134
236
|
morphdom(document.body, newDocument.body, {
|
|
135
237
|
getNodeKey: (node) => getBodyMorphKey(node, persistAttribute),
|
|
136
238
|
onBeforeNodeAdded: (node) => {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
239
|
+
const server = node instanceof Element ? incomingServerMarkup.get(node) : undefined;
|
|
240
|
+
if (serverMarkup && server && node instanceof Element)
|
|
241
|
+
recordServerSubtree(serverMarkup, node, server);
|
|
140
242
|
return node;
|
|
141
243
|
},
|
|
142
244
|
onBeforeElUpdated: (fromEl, toEl) => {
|
|
143
245
|
if (isPersisted(fromEl, persistAttribute)) {
|
|
144
246
|
return false;
|
|
145
247
|
}
|
|
248
|
+
const incomingServer = incomingServerMarkup.get(toEl);
|
|
249
|
+
const previousServer = serverMarkup?.get(fromEl);
|
|
250
|
+
if (reload && isUnchangedServerMarkup(previousServer, incomingServer)) {
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
146
253
|
if (refreshUnpersistedElements) {
|
|
147
254
|
if (fromEl === document.body || retainedRerunContext.has(fromEl)) {
|
|
148
|
-
return
|
|
255
|
+
return updateElement(fromEl, toEl, previousServer, incomingServer, serverMarkup, reload);
|
|
149
256
|
}
|
|
150
|
-
return deferElementReplacement(fromEl, toEl, deferredReplacements);
|
|
151
|
-
}
|
|
152
|
-
if (isHydratedCustomElement(fromEl)) {
|
|
153
|
-
return deferElementReplacement(fromEl, toEl, deferredReplacements);
|
|
257
|
+
return deferElementReplacement(fromEl, toEl, incomingServer, deferredReplacements);
|
|
154
258
|
}
|
|
155
|
-
if (isLightDomCustomElement(fromEl)) {
|
|
156
|
-
return deferElementReplacement(fromEl, toEl, deferredReplacements);
|
|
259
|
+
if (isHydratedCustomElement(fromEl) || isLightDomCustomElement(fromEl)) {
|
|
260
|
+
return deferElementReplacement(fromEl, toEl, incomingServer, deferredReplacements);
|
|
157
261
|
}
|
|
158
262
|
if (fromEl.isEqualNode(toEl)) {
|
|
263
|
+
if (serverMarkup && incomingServer)
|
|
264
|
+
recordServerSubtree(serverMarkup, fromEl, incomingServer);
|
|
159
265
|
return false;
|
|
160
266
|
}
|
|
161
|
-
return
|
|
267
|
+
return updateElement(fromEl, toEl, previousServer, incomingServer, serverMarkup, reload);
|
|
162
268
|
},
|
|
163
269
|
});
|
|
164
|
-
flushDeferredReplacements(deferredReplacements);
|
|
270
|
+
flushDeferredReplacements(deferredReplacements, serverMarkup);
|
|
165
271
|
processDeclarativeShadowDOM(document.body);
|
|
166
272
|
}
|
|
@@ -5,8 +5,10 @@ export type PerformNavigationAttemptInput = {
|
|
|
5
5
|
direction: EcoNavigationEvent['direction'];
|
|
6
6
|
bypassPrefetchCache?: boolean;
|
|
7
7
|
allowFullDocumentFallback?: boolean;
|
|
8
|
+
reload?: boolean;
|
|
8
9
|
navigationCommit: NavigationCommit;
|
|
9
10
|
isStaleNavigation: () => boolean;
|
|
11
|
+
isSupersededNavigation: () => boolean;
|
|
10
12
|
signal: AbortSignal;
|
|
11
13
|
};
|
|
12
14
|
/**
|
|
@@ -20,7 +20,9 @@ export async function runPerformNavigationAttempt(input) {
|
|
|
20
20
|
return await input.navigationCommit.commit(page.finalUrl, input.direction, page.document, {
|
|
21
21
|
html: page.html,
|
|
22
22
|
isStaleNavigation: input.isStaleNavigation,
|
|
23
|
+
isSupersededNavigation: input.isSupersededNavigation,
|
|
23
24
|
allowFullDocumentFallback: input.allowFullDocumentFallback ?? true,
|
|
25
|
+
reload: input.reload,
|
|
24
26
|
});
|
|
25
27
|
}
|
|
26
28
|
export function shouldIgnorePerformNavigationError(error, isStaleNavigation) {
|
package/src/client/eco-router.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Client-side router for Ecopages with morphdom-based DOM diffing.
|
|
3
3
|
* @module eco-router
|
|
4
4
|
*/
|
|
5
|
-
import { getEcoNavigationRuntime } from '@ecopages/core/client';
|
|
5
|
+
import { getEcoNavigationRuntime, schedulePageLoad } from '@ecopages/core/client';
|
|
6
6
|
import { getAnchorFromNavigationEvent, isStaticAssetHref, recoverPendingNavigationHref, } from '@ecopages/core/client';
|
|
7
7
|
import { getNavigableHrefFromClick } from '@ecopages/core/client';
|
|
8
8
|
import { decideQueuedNavigationReplay } from '@ecopages/core/client';
|
|
@@ -81,11 +81,11 @@ export class EcoRouter {
|
|
|
81
81
|
return true;
|
|
82
82
|
},
|
|
83
83
|
handoffNavigation: async (request) => {
|
|
84
|
-
const { isStaleNavigation, complete } = this.beginNavigationTransaction();
|
|
84
|
+
const { isStaleNavigation, isSupersededNavigation, complete } = this.beginNavigationTransaction();
|
|
85
85
|
if (isStaleNavigation())
|
|
86
86
|
return true;
|
|
87
87
|
try {
|
|
88
|
-
await this.navigationCommit.commit(new URL(request.finalHref ?? request.href, window.location.origin), request.direction ?? 'forward', request.document, { html: request.html, isStaleNavigation });
|
|
88
|
+
await this.navigationCommit.commit(new URL(request.finalHref ?? request.href, window.location.origin), request.direction ?? 'forward', request.document, { html: request.html, isStaleNavigation, isSupersededNavigation });
|
|
89
89
|
}
|
|
90
90
|
finally {
|
|
91
91
|
complete();
|
|
@@ -103,17 +103,20 @@ export class EcoRouter {
|
|
|
103
103
|
return await this.performNavigation(new URL(currentUrl, window.location.origin), 'replace', {
|
|
104
104
|
bypassPrefetchCache: !!request?.clearCache,
|
|
105
105
|
allowFullDocumentFallback: false,
|
|
106
|
+
reload: true,
|
|
106
107
|
});
|
|
107
108
|
},
|
|
108
109
|
cleanupBeforeHandoff: async () => {
|
|
109
110
|
this.cancelNavigationTransaction();
|
|
110
111
|
},
|
|
112
|
+
enableReloadStatePreservation: () => this.navigationCommit.trackServerMarkup(),
|
|
111
113
|
});
|
|
112
114
|
getEcoNavigationRuntime(window).adoptDocumentOwner(document, 'browser-router');
|
|
113
115
|
// Cache the initial page for instant back-navigation
|
|
114
116
|
const initialHtml = document.documentElement.outerHTML;
|
|
115
117
|
this.prefetchManager?.cacheVisitedPage(window.location.href, initialHtml);
|
|
116
118
|
this.started = true;
|
|
119
|
+
schedulePageLoad(document, { url: new URL(window.location.href), direction: 'replace' }, { isSuperseded: () => !this.started });
|
|
117
120
|
}
|
|
118
121
|
/**
|
|
119
122
|
* Stops the router and cleans up all event listeners.
|
|
@@ -240,6 +243,7 @@ export class EcoRouter {
|
|
|
240
243
|
const transaction = getEcoNavigationRuntime(window).beginNavigationTransaction();
|
|
241
244
|
return {
|
|
242
245
|
isStaleNavigation: () => !transaction.isCurrent(),
|
|
246
|
+
isSupersededNavigation: () => transaction.isSuperseded(),
|
|
243
247
|
signal: transaction.signal,
|
|
244
248
|
complete: () => transaction.complete(),
|
|
245
249
|
};
|
|
@@ -265,7 +269,7 @@ export class EcoRouter {
|
|
|
265
269
|
async performNavigation(url, direction, options = {}) {
|
|
266
270
|
const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
|
|
267
271
|
this.pendingNavigations++;
|
|
268
|
-
const { isStaleNavigation, signal, complete } = this.beginNavigationTransaction();
|
|
272
|
+
const { isStaleNavigation, isSupersededNavigation, signal, complete } = this.beginNavigationTransaction();
|
|
269
273
|
let queuedNavigationHref = null;
|
|
270
274
|
let committed = false;
|
|
271
275
|
try {
|
|
@@ -274,8 +278,10 @@ export class EcoRouter {
|
|
|
274
278
|
direction,
|
|
275
279
|
bypassPrefetchCache: options.bypassPrefetchCache || !this.prefetchManager,
|
|
276
280
|
allowFullDocumentFallback,
|
|
281
|
+
reload: options.reload,
|
|
277
282
|
navigationCommit: this.navigationCommit,
|
|
278
283
|
isStaleNavigation,
|
|
284
|
+
isSupersededNavigation,
|
|
279
285
|
signal,
|
|
280
286
|
});
|
|
281
287
|
return committed;
|
|
@@ -4,7 +4,10 @@ import type { EcoRouterOptions } from './types.js';
|
|
|
4
4
|
export type NavigationCommitOptions = {
|
|
5
5
|
html?: string;
|
|
6
6
|
isStaleNavigation?: () => boolean;
|
|
7
|
+
isSupersededNavigation?: () => boolean;
|
|
7
8
|
allowFullDocumentFallback?: boolean;
|
|
9
|
+
/** Set when the router reloads the current page; ignored when the response ends on another URL. */
|
|
10
|
+
reload?: boolean;
|
|
8
11
|
};
|
|
9
12
|
/**
|
|
10
13
|
* Commits a fetched document into the live page and dispatches navigation lifecycle events.
|
|
@@ -12,6 +15,16 @@ export type NavigationCommitOptions = {
|
|
|
12
15
|
export declare class NavigationCommit {
|
|
13
16
|
private readonly prefetchManager;
|
|
14
17
|
private readonly options;
|
|
18
|
+
private serverMarkup;
|
|
15
19
|
constructor(prefetchManager: PrefetchManager | null, options: Required<EcoRouterOptions>);
|
|
20
|
+
/**
|
|
21
|
+
* Starts tracking the server markup of each body element, so a reload of the current URL keeps the elements
|
|
22
|
+
* whose markup did not change.
|
|
23
|
+
*
|
|
24
|
+
* @remarks
|
|
25
|
+
* Off until development HMR asks for it, so production navigations do no copying. The current body is the
|
|
26
|
+
* first baseline.
|
|
27
|
+
*/
|
|
28
|
+
trackServerMarkup(): void;
|
|
16
29
|
commit(url: URL, direction: EcoNavigationEvent['direction'], newDocument: Document, options?: NavigationCommitOptions): Promise<boolean>;
|
|
17
30
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { getEcoNavigationRuntime } from '@ecopages/core/client';
|
|
2
2
|
import { commitNavigationPage } from '@ecopages/core/client';
|
|
3
3
|
import { manageWindowScroll } from '@ecopages/core/client';
|
|
4
|
-
import { morphBody } from './dom/body-morpher.js';
|
|
4
|
+
import { morphBody, recordInitialServerMarkup } from './dom/body-morpher.js';
|
|
5
5
|
import { resolveNavigationReloadDecision } from './navigation-commit-reload.js';
|
|
6
6
|
import { syncDocumentElementAttributes } from './document-element-sync.js';
|
|
7
7
|
function resolveCommitOwnerContext(navigationRuntime, newDocument) {
|
|
@@ -13,19 +13,38 @@ function resolveCommitOwnerContext(navigationRuntime, newDocument) {
|
|
|
13
13
|
activeOwner === currentDocumentOwner;
|
|
14
14
|
return { currentDocumentOwner, shouldCleanupCurrentOwner };
|
|
15
15
|
}
|
|
16
|
+
function isSameDocumentUrl(left, right) {
|
|
17
|
+
return left.origin === right.origin && left.pathname === right.pathname && left.search === right.search;
|
|
18
|
+
}
|
|
16
19
|
/**
|
|
17
20
|
* Commits a fetched document into the live page and dispatches navigation lifecycle events.
|
|
18
21
|
*/
|
|
19
22
|
export class NavigationCommit {
|
|
20
23
|
prefetchManager;
|
|
21
24
|
options;
|
|
25
|
+
serverMarkup;
|
|
22
26
|
constructor(prefetchManager, options) {
|
|
23
27
|
this.prefetchManager = prefetchManager;
|
|
24
28
|
this.options = options;
|
|
25
29
|
}
|
|
30
|
+
/**
|
|
31
|
+
* Starts tracking the server markup of each body element, so a reload of the current URL keeps the elements
|
|
32
|
+
* whose markup did not change.
|
|
33
|
+
*
|
|
34
|
+
* @remarks
|
|
35
|
+
* Off until development HMR asks for it, so production navigations do no copying. The current body is the
|
|
36
|
+
* first baseline.
|
|
37
|
+
*/
|
|
38
|
+
trackServerMarkup() {
|
|
39
|
+
if (this.serverMarkup)
|
|
40
|
+
return;
|
|
41
|
+
this.serverMarkup = new WeakMap();
|
|
42
|
+
recordInitialServerMarkup(this.serverMarkup);
|
|
43
|
+
}
|
|
26
44
|
async commit(url, direction, newDocument, options = {}) {
|
|
27
45
|
const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
|
|
28
46
|
const previousUrl = new URL(window.location.href);
|
|
47
|
+
const reload = options.reload === true && isSameDocumentUrl(url, previousUrl);
|
|
29
48
|
const navigationRuntime = getEcoNavigationRuntime(window);
|
|
30
49
|
const isStaleNavigation = options.isStaleNavigation ?? (() => false);
|
|
31
50
|
const { currentDocumentOwner, shouldCleanupCurrentOwner } = resolveCommitOwnerContext(navigationRuntime, newDocument);
|
|
@@ -34,6 +53,7 @@ export class NavigationCommit {
|
|
|
34
53
|
direction,
|
|
35
54
|
newDocument,
|
|
36
55
|
isStale: isStaleNavigation,
|
|
56
|
+
isSuperseded: options.isSupersededNavigation,
|
|
37
57
|
viewTransitionsEnabled: this.options.viewTransitions,
|
|
38
58
|
persistAttribute: this.options.persistAttribute,
|
|
39
59
|
onReloadRequested: async () => {
|
|
@@ -62,7 +82,7 @@ export class NavigationCommit {
|
|
|
62
82
|
},
|
|
63
83
|
swap: () => {
|
|
64
84
|
syncDocumentElementAttributes(document, newDocument, this.options.documentElementAttributesToSync);
|
|
65
|
-
morphBody(newDocument, this.options.persistAttribute);
|
|
85
|
+
morphBody(newDocument, this.options.persistAttribute, { serverMarkup: this.serverMarkup, reload });
|
|
66
86
|
},
|
|
67
87
|
onSwapped: () => {
|
|
68
88
|
navigationRuntime.adoptDocumentOwner(newDocument, 'browser-router');
|