@ecopages/browser-router 0.2.0-beta.30 → 0.2.0-beta.32

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ecopages/browser-router",
3
- "version": "0.2.0-beta.30",
3
+ "version": "0.2.0-beta.32",
4
4
  "description": "Client-side router for Ecopages with view transitions support",
5
5
  "keywords": [
6
6
  "ecopages",
@@ -35,7 +35,7 @@
35
35
  "morphdom": "^2.7.8"
36
36
  },
37
37
  "peerDependencies": {
38
- "@ecopages/core": "0.2.0-beta.30"
38
+ "@ecopages/core": "0.2.0-beta.32"
39
39
  },
40
40
  "types": "./src/index.d.ts"
41
41
  }
@@ -1,17 +1,30 @@
1
- function syncDocumentElementAttributes(currentDocument, newDocument, attributes) {
2
- const currentHtml = currentDocument.documentElement;
3
- const nextHtml = newDocument.documentElement;
4
- for (const attributeName of attributes) {
5
- const nextValue = nextHtml.getAttribute(attributeName);
6
- if (nextValue === null) {
7
- currentHtml.removeAttribute(attributeName);
8
- continue;
1
+ /**
2
+ * Helpers for synchronizing selected root `<html>` attributes during client-side navigation.
3
+ * @module
4
+ */
5
+ /**
6
+ * Synchronizes a selected set of root `<html>` attributes from an incoming document
7
+ * onto the current live document.
8
+ *
9
+ * Attributes listed here are treated as document-owned metadata. Attributes not
10
+ * listed remain untouched on the live document so client-managed state can survive
11
+ * across navigation swaps.
12
+ *
13
+ * @param currentDocument - The live document being updated
14
+ * @param newDocument - The parsed incoming document for the next page
15
+ * @param attributes - Root `<html>` attributes to synchronize
16
+ */
17
+ export function syncDocumentElementAttributes(currentDocument, newDocument, attributes) {
18
+ const currentHtml = currentDocument.documentElement;
19
+ const nextHtml = newDocument.documentElement;
20
+ for (const attributeName of attributes) {
21
+ const nextValue = nextHtml.getAttribute(attributeName);
22
+ if (nextValue === null) {
23
+ currentHtml.removeAttribute(attributeName);
24
+ continue;
25
+ }
26
+ if (currentHtml.getAttribute(attributeName) !== nextValue) {
27
+ currentHtml.setAttribute(attributeName, nextValue);
28
+ }
9
29
  }
10
- if (currentHtml.getAttribute(attributeName) !== nextValue) {
11
- currentHtml.setAttribute(attributeName, nextValue);
12
- }
13
- }
14
30
  }
15
- export {
16
- syncDocumentElementAttributes
17
- };
@@ -1,103 +1,143 @@
1
- import morphdom from "morphdom";
2
- const DEFAULT_PERSIST_ATTR = "data-eco-persist";
1
+ import morphdom from 'morphdom';
2
+ const DEFAULT_PERSIST_ATTR = 'data-eco-persist';
3
3
  function isPersisted(element, persistAttribute) {
4
- return element.hasAttribute(persistAttribute) || element.hasAttribute(DEFAULT_PERSIST_ATTR);
4
+ return element.hasAttribute(persistAttribute) || element.hasAttribute(DEFAULT_PERSIST_ATTR);
5
5
  }
6
6
  function isHydratedCustomElement(element) {
7
- return element.localName.includes("-") && element.shadowRoot !== null;
7
+ return element.localName.includes('-') && element.shadowRoot !== null;
8
8
  }
9
+ /**
10
+ * Returns the only body-morph keys that browser-router should trust.
11
+ *
12
+ * @remarks
13
+ * morphdom defaults to treating every `id` attribute as a structural key.
14
+ * That is fragile for content-heavy pages where repeated heading ids or other
15
+ * invalid-but-common markup can appear. Browser-router only needs stable keys
16
+ * for explicitly persisted nodes, so all other elements fall back to normal
17
+ * tree-order diffing.
18
+ */
9
19
  function getBodyMorphKey(element, persistAttribute) {
10
- if (!(element instanceof Element)) {
11
- return void 0;
12
- }
13
- return element.getAttribute(persistAttribute) || element.getAttribute(DEFAULT_PERSIST_ATTR) || void 0;
20
+ if (!(element instanceof Element)) {
21
+ return undefined;
22
+ }
23
+ return element.getAttribute(persistAttribute) || element.getAttribute(DEFAULT_PERSIST_ATTR) || undefined;
14
24
  }
15
25
  function isLightDomCustomElement(element) {
16
- return element.localName.includes("-") && element.shadowRoot === null;
26
+ return element.localName.includes('-') && element.shadowRoot === null;
17
27
  }
28
+ /**
29
+ * @returns Always `false` to tell morphdom to skip updating this element.
30
+ *
31
+ * @remarks
32
+ * Replacing elements during morphdom traversal mutates the live DOM tree,
33
+ * which can cause morphdom to skip siblings or process stale nodes.
34
+ * Deferring the replacement until after morphdom finishes avoids this.
35
+ */
18
36
  function replaceCustomElement(fromEl, toEl, deferred) {
19
- deferred.push({ from: fromEl, to: toEl.cloneNode(true) });
20
- return false;
37
+ deferred.push({ from: fromEl, to: toEl.cloneNode(true) });
38
+ return false;
21
39
  }
22
40
  function materializeCustomElement(element) {
23
- const materializedElement = document.createElement(element.localName);
24
- for (const attr of element.attributes) {
25
- materializedElement.setAttribute(attr.name, attr.value);
26
- }
27
- materializedElement.innerHTML = element.innerHTML;
28
- return materializedElement;
41
+ const materializedElement = document.createElement(element.localName);
42
+ for (const attr of element.attributes) {
43
+ materializedElement.setAttribute(attr.name, attr.value);
44
+ }
45
+ materializedElement.innerHTML = element.innerHTML;
46
+ return materializedElement;
29
47
  }
48
+ /**
49
+ * @remarks
50
+ * Each element is recreated via `document.createElement` so the browser fires
51
+ * the full custom element lifecycle (`disconnectedCallback` on the old instance,
52
+ * `connectedCallback` on the new one). Elements that were already removed during
53
+ * the morph pass are skipped via the `isConnected` guard.
54
+ */
30
55
  function flushDeferredCustomElementReplacements(deferred) {
31
- for (const { from, to } of deferred) {
32
- if (!from.isConnected) continue;
33
- const newEl = materializeCustomElement(to);
34
- from.replaceWith(newEl);
35
- }
36
- }
37
- function processDeclarativeShadowDOM(root) {
38
- const templates = root.querySelectorAll("template[shadowrootmode], template[shadowroot]");
39
- for (const template of templates) {
40
- const mode = template.getAttribute("shadowrootmode") || template.getAttribute("shadowroot");
41
- const parent = template.parentElement;
42
- if (parent && !parent.shadowRoot) {
43
- const shadowRoot = parent.attachShadow({ mode });
44
- shadowRoot.appendChild(template.content);
45
- template.remove();
46
- processDeclarativeShadowDOM(shadowRoot);
56
+ for (const { from, to } of deferred) {
57
+ if (!from.isConnected)
58
+ continue;
59
+ const newEl = materializeCustomElement(to);
60
+ from.replaceWith(newEl);
47
61
  }
48
- }
49
62
  }
50
- function morphBody(newDocument, persistAttribute) {
51
- const deferredReplacements = [];
52
- morphdom(document.body, newDocument.body, {
53
- getNodeKey: (node) => getBodyMorphKey(node, persistAttribute),
54
- onBeforeNodeAdded: (node) => {
55
- if (node instanceof Element && isLightDomCustomElement(node)) {
56
- return materializeCustomElement(node);
57
- }
58
- return node;
59
- },
60
- onBeforeElUpdated: (fromEl, toEl) => {
61
- if (isPersisted(fromEl, persistAttribute)) {
62
- return false;
63
- }
64
- if (isHydratedCustomElement(fromEl)) {
65
- return replaceCustomElement(fromEl, toEl, deferredReplacements);
66
- }
67
- if (isLightDomCustomElement(fromEl)) {
68
- return replaceCustomElement(fromEl, toEl, deferredReplacements);
69
- }
70
- if (fromEl.isEqualNode(toEl)) {
71
- return false;
72
- }
73
- return true;
63
+ /**
64
+ * Manually attaches declarative shadow DOM templates.
65
+ *
66
+ * @remarks
67
+ * Browsers only process `<template shadowrootmode>` during initial parse.
68
+ */
69
+ export function processDeclarativeShadowDOM(root) {
70
+ const templates = root.querySelectorAll('template[shadowrootmode], template[shadowroot]');
71
+ for (const template of templates) {
72
+ const mode = (template.getAttribute('shadowrootmode') || template.getAttribute('shadowroot'));
73
+ const parent = template.parentElement;
74
+ if (parent && !parent.shadowRoot) {
75
+ const shadowRoot = parent.attachShadow({ mode });
76
+ shadowRoot.appendChild(template.content);
77
+ template.remove();
78
+ processDeclarativeShadowDOM(shadowRoot);
79
+ }
74
80
  }
75
- });
76
- flushDeferredCustomElementReplacements(deferredReplacements);
77
- processDeclarativeShadowDOM(document.body);
78
81
  }
79
- function replaceBody(newDocument, persistAttribute) {
80
- const persistedElements = document.body.querySelectorAll(`[${persistAttribute}], [${DEFAULT_PERSIST_ATTR}]`);
81
- const persistedMap = /* @__PURE__ */ new Map();
82
- for (const el of persistedElements) {
83
- const key = el.getAttribute(persistAttribute) || el.getAttribute(DEFAULT_PERSIST_ATTR);
84
- if (key) {
85
- persistedMap.set(key, el);
82
+ /**
83
+ * Morphs document body using morphdom.
84
+ *
85
+ * @remarks
86
+ * Preserves persisted elements and hydrated custom elements.
87
+ * Light-DOM custom elements are fully replaced to trigger proper
88
+ * disconnectedCallback → connectedCallback lifecycle.
89
+ */
90
+ export function morphBody(newDocument, persistAttribute) {
91
+ const deferredReplacements = [];
92
+ morphdom(document.body, newDocument.body, {
93
+ getNodeKey: (node) => getBodyMorphKey(node, persistAttribute),
94
+ onBeforeNodeAdded: (node) => {
95
+ if (node instanceof Element && isLightDomCustomElement(node)) {
96
+ return materializeCustomElement(node);
97
+ }
98
+ return node;
99
+ },
100
+ onBeforeElUpdated: (fromEl, toEl) => {
101
+ if (isPersisted(fromEl, persistAttribute)) {
102
+ return false;
103
+ }
104
+ if (isHydratedCustomElement(fromEl)) {
105
+ return replaceCustomElement(fromEl, toEl, deferredReplacements);
106
+ }
107
+ if (isLightDomCustomElement(fromEl)) {
108
+ return replaceCustomElement(fromEl, toEl, deferredReplacements);
109
+ }
110
+ if (fromEl.isEqualNode(toEl)) {
111
+ return false;
112
+ }
113
+ return true;
114
+ },
115
+ });
116
+ flushDeferredCustomElementReplacements(deferredReplacements);
117
+ processDeclarativeShadowDOM(document.body);
118
+ }
119
+ /**
120
+ * Replaces body content in a single operation.
121
+ *
122
+ * @remarks
123
+ * Preserves persisted elements by moving them to the new body.
124
+ * Use when View Transitions are disabled.
125
+ */
126
+ export function replaceBody(newDocument, persistAttribute) {
127
+ const persistedElements = document.body.querySelectorAll(`[${persistAttribute}], [${DEFAULT_PERSIST_ATTR}]`);
128
+ const persistedMap = new Map();
129
+ for (const el of persistedElements) {
130
+ const key = el.getAttribute(persistAttribute) || el.getAttribute(DEFAULT_PERSIST_ATTR);
131
+ if (key) {
132
+ persistedMap.set(key, el);
133
+ }
86
134
  }
87
- }
88
- for (const [key, oldEl] of persistedMap) {
89
- const placeholder = newDocument.body.querySelector(
90
- `[${persistAttribute}="${key}"], [${DEFAULT_PERSIST_ATTR}="${key}"]`
91
- );
92
- if (placeholder) {
93
- placeholder.replaceWith(oldEl);
135
+ for (const [key, oldEl] of persistedMap) {
136
+ const placeholder = newDocument.body.querySelector(`[${persistAttribute}="${key}"], [${DEFAULT_PERSIST_ATTR}="${key}"]`);
137
+ if (placeholder) {
138
+ placeholder.replaceWith(oldEl);
139
+ }
94
140
  }
95
- }
96
- document.body.replaceChildren(...Array.from(newDocument.body.childNodes));
97
- processDeclarativeShadowDOM(document.body);
141
+ document.body.replaceChildren(...Array.from(newDocument.body.childNodes));
142
+ processDeclarativeShadowDOM(document.body);
98
143
  }
99
- export {
100
- morphBody,
101
- processDeclarativeShadowDOM,
102
- replaceBody
103
- };
@@ -1,51 +1,52 @@
1
- import { morphBody, replaceBody } from "./body-morpher.js";
2
- import {
3
- flushHeadScripts,
4
- flushRerunScripts as flushPendingRerunScripts,
5
- morphHead
6
- } from "./head-updater.js";
7
- import { parseHTML } from "./html-parser.js";
8
- import { preloadStylesheets } from "./stylesheet-preloader.js";
9
- class DomSwapper {
10
- persistAttribute;
11
- pendingHeadScripts = [];
12
- pendingRerunScripts = [];
13
- constructor(persistAttribute) {
14
- this.persistAttribute = persistAttribute;
15
- }
16
- parseHTML(html, url) {
17
- return parseHTML(html, url);
18
- }
19
- async preloadStylesheets(newDocument) {
20
- return preloadStylesheets(newDocument);
21
- }
22
- morphHead(newDocument) {
23
- const result = morphHead(newDocument, this.persistAttribute);
24
- this.pendingHeadScripts = result.pendingHeadScripts;
25
- this.pendingRerunScripts = result.pendingRerunScripts;
26
- return { bodyStrategy: result.bodyStrategy };
27
- }
28
- /**
29
- * Replays queued scripts after the body swap completes.
30
- *
31
- * @remarks
32
- * Scripts are intentionally flushed after the new body is in place so DOM-
33
- * dependent bootstraps bind against the incoming page rather than the page
34
- * being replaced.
35
- */
36
- flushRerunScripts() {
37
- flushHeadScripts(this.pendingHeadScripts);
38
- this.pendingHeadScripts = [];
39
- flushPendingRerunScripts(this.pendingRerunScripts);
40
- this.pendingRerunScripts = [];
41
- }
42
- morphBody(newDocument) {
43
- morphBody(newDocument, this.persistAttribute);
44
- }
45
- replaceBody(newDocument) {
46
- replaceBody(newDocument, this.persistAttribute);
47
- }
1
+ import { morphBody, replaceBody } from './body-morpher.js';
2
+ import { flushHeadScripts, flushRerunScripts as flushPendingRerunScripts, morphHead, } from './head-updater.js';
3
+ import { parseHTML } from './html-parser.js';
4
+ import { preloadStylesheets } from './stylesheet-preloader.js';
5
+ /**
6
+ * Handles DOM manipulation during client-side page transitions.
7
+ *
8
+ * @remarks
9
+ * Uses a hybrid approach inspired by Turbo:
10
+ * - Surgical head updates (no morphing) to prevent FOUC
11
+ * - Idiomorph for efficient body diffing
12
+ */
13
+ export class DomSwapper {
14
+ persistAttribute;
15
+ pendingHeadScripts = [];
16
+ pendingRerunScripts = [];
17
+ constructor(persistAttribute) {
18
+ this.persistAttribute = persistAttribute;
19
+ }
20
+ parseHTML(html, url) {
21
+ return parseHTML(html, url);
22
+ }
23
+ async preloadStylesheets(newDocument) {
24
+ return preloadStylesheets(newDocument);
25
+ }
26
+ morphHead(newDocument) {
27
+ const result = morphHead(newDocument, this.persistAttribute);
28
+ this.pendingHeadScripts = result.pendingHeadScripts;
29
+ this.pendingRerunScripts = result.pendingRerunScripts;
30
+ return { bodyStrategy: result.bodyStrategy };
31
+ }
32
+ /**
33
+ * Replays queued scripts after the body swap completes.
34
+ *
35
+ * @remarks
36
+ * Scripts are intentionally flushed after the new body is in place so DOM-
37
+ * dependent bootstraps bind against the incoming page rather than the page
38
+ * being replaced.
39
+ */
40
+ flushRerunScripts() {
41
+ flushHeadScripts(this.pendingHeadScripts);
42
+ this.pendingHeadScripts = [];
43
+ flushPendingRerunScripts(this.pendingRerunScripts);
44
+ this.pendingRerunScripts = [];
45
+ }
46
+ morphBody(newDocument) {
47
+ morphBody(newDocument, this.persistAttribute);
48
+ }
49
+ replaceBody(newDocument) {
50
+ replaceBody(newDocument, this.persistAttribute);
51
+ }
48
52
  }
49
- export {
50
- DomSwapper
51
- };