@ecopages/browser-router 0.6.1 → 0.7.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/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
- 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.
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/browser-router",
3
- "version": "0.6.1",
3
+ "version": "0.7.0",
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.6.1"
44
+ "@ecopages/core": "0.7.0"
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
  *
@@ -23,5 +48,14 @@ export declare function processDeclarativeShadowDOM(root: Element | Document | S
23
48
  * components must handle rebinding.
24
49
  * Light-DOM custom elements are fully replaced to trigger their
25
50
  * disconnectedCallback → connectedCallback lifecycle.
51
+ *
52
+ * On a reload of the current URL, an element whose server markup is the same in the previous and the incoming
53
+ * document is kept with its state, its runtime attributes and its children, including custom elements and their
54
+ * shadow roots. A changed element is handled as on navigation, except that a plain element whose own server
55
+ * attributes did not change keeps its live attributes while its children are morphed. Rerun scripts do not
56
+ * refresh elements on a reload: a replaced ancestor would drop the unchanged elements inside it, so a rerun
57
+ * script must register handlers idempotently on every element a reload does not replace, which is all but changed custom elements.
58
+ * Elements are paired in tree order, as morphdom pairs them, so inserting or removing an earlier sibling with
59
+ * the same markup moves state to its neighbour.
26
60
  */
27
- export declare function morphBody(newDocument: Document, persistAttribute: string): void;
61
+ 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,10 +148,11 @@ 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) {
151
+ function deferElementReplacement(fromEl, toEl, server, deferred) {
62
152
  deferred.push({
63
153
  from: fromEl,
64
154
  to: toEl.cloneNode(true),
155
+ server,
65
156
  isCustomElement: fromEl.localName.includes('-'),
66
157
  });
67
158
  return false;
@@ -79,11 +170,13 @@ function materializeCustomElement(element) {
79
170
  * Custom elements are recreated via `document.createElement` so the browser fires
80
171
  * their full lifecycle. Elements already removed during the morph pass are skipped.
81
172
  */
82
- function flushDeferredReplacements(deferred) {
83
- for (const { from, to, isCustomElement } of deferred) {
173
+ function flushDeferredReplacements(deferred, serverMarkup) {
174
+ for (const { from, to, server, isCustomElement } of deferred) {
84
175
  if (!from.isConnected)
85
176
  continue;
86
177
  const newEl = isCustomElement ? materializeCustomElement(to) : to.cloneNode(true);
178
+ if (serverMarkup && server)
179
+ recordServerSubtree(serverMarkup, newEl, server);
87
180
  from.replaceWith(newEl);
88
181
  }
89
182
  }
@@ -124,43 +217,67 @@ export function processDeclarativeShadowDOM(root) {
124
217
  * components must handle rebinding.
125
218
  * Light-DOM custom elements are fully replaced to trigger their
126
219
  * disconnectedCallback → connectedCallback lifecycle.
220
+ *
221
+ * On a reload of the current URL, an element whose server markup is the same in the previous and the incoming
222
+ * document is kept with its state, its runtime attributes and its children, including custom elements and their
223
+ * shadow roots. A changed element is handled as on navigation, except that a plain element whose own server
224
+ * attributes did not change keeps its live attributes while its children are morphed. Rerun scripts do not
225
+ * refresh elements on a reload: a replaced ancestor would drop the unchanged elements inside it, so a rerun
226
+ * script must register handlers idempotently on every element a reload does not replace, which is all but changed custom elements.
227
+ * Elements are paired in tree order, as morphdom pairs them, so inserting or removing an earlier sibling with
228
+ * the same markup moves state to its neighbour.
127
229
  */
128
- export function morphBody(newDocument, persistAttribute) {
230
+ export function morphBody(newDocument, persistAttribute, { serverMarkup, reload = false } = {}) {
129
231
  const deferredReplacements = [];
130
- const refreshUnpersistedElements = newDocument.querySelector('script[data-eco-rerun]') !== null;
232
+ const refreshUnpersistedElements = !reload && newDocument.querySelector('script[data-eco-rerun]') !== null;
131
233
  const retainedRerunContext = refreshUnpersistedElements
132
234
  ? findPersistedRerunContext(document.body, persistAttribute)
133
235
  : new Set();
236
+ const incomingServerMarkup = new Map();
237
+ if (serverMarkup) {
238
+ const serverBody = newDocument.body.cloneNode(true);
239
+ incomingServerMarkup.set(newDocument.body, serverBody);
240
+ const incoming = newDocument.body.querySelectorAll('*');
241
+ const server = serverBody.querySelectorAll('*');
242
+ for (let index = 0; index < incoming.length; index++) {
243
+ incomingServerMarkup.set(incoming[index], server[index]);
244
+ }
245
+ }
134
246
  morphdom(document.body, newDocument.body, {
135
247
  getNodeKey: (node) => getBodyMorphKey(node, persistAttribute),
136
248
  onBeforeNodeAdded: (node) => {
137
- if (node instanceof Element && isLightDomCustomElement(node)) {
138
- return materializeCustomElement(node);
139
- }
140
- return node;
249
+ const added = node instanceof Element && isLightDomCustomElement(node) ? materializeCustomElement(node) : node;
250
+ const server = node instanceof Element ? incomingServerMarkup.get(node) : undefined;
251
+ if (serverMarkup && server && added instanceof Element)
252
+ recordServerSubtree(serverMarkup, added, server);
253
+ return added;
141
254
  },
142
255
  onBeforeElUpdated: (fromEl, toEl) => {
143
256
  if (isPersisted(fromEl, persistAttribute)) {
144
257
  return false;
145
258
  }
259
+ const incomingServer = incomingServerMarkup.get(toEl);
260
+ const previousServer = serverMarkup?.get(fromEl);
261
+ if (reload && isUnchangedServerMarkup(previousServer, incomingServer)) {
262
+ return false;
263
+ }
146
264
  if (refreshUnpersistedElements) {
147
265
  if (fromEl === document.body || retainedRerunContext.has(fromEl)) {
148
- return true;
266
+ return updateElement(fromEl, toEl, previousServer, incomingServer, serverMarkup, reload);
149
267
  }
150
- return deferElementReplacement(fromEl, toEl, deferredReplacements);
151
- }
152
- if (isHydratedCustomElement(fromEl)) {
153
- return deferElementReplacement(fromEl, toEl, deferredReplacements);
268
+ return deferElementReplacement(fromEl, toEl, incomingServer, deferredReplacements);
154
269
  }
155
- if (isLightDomCustomElement(fromEl)) {
156
- return deferElementReplacement(fromEl, toEl, deferredReplacements);
270
+ if (isHydratedCustomElement(fromEl) || isLightDomCustomElement(fromEl)) {
271
+ return deferElementReplacement(fromEl, toEl, incomingServer, deferredReplacements);
157
272
  }
158
273
  if (fromEl.isEqualNode(toEl)) {
274
+ if (serverMarkup && incomingServer)
275
+ recordServerSubtree(serverMarkup, fromEl, incomingServer);
159
276
  return false;
160
277
  }
161
- return true;
278
+ return updateElement(fromEl, toEl, previousServer, incomingServer, serverMarkup, reload);
162
279
  },
163
280
  });
164
- flushDeferredReplacements(deferredReplacements);
281
+ flushDeferredReplacements(deferredReplacements, serverMarkup);
165
282
  processDeclarativeShadowDOM(document.body);
166
283
  }
@@ -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) {
@@ -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');