@ecopages/browser-router 0.2.1 → 0.3.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 +25 -8
- package/package.json +11 -8
- package/src/client/document-element-sync.d.ts +0 -7
- package/src/client/document-element-sync.js +28 -18
- package/src/client/dom/body-morpher.d.ts +27 -0
- package/src/client/dom/body-morpher.js +166 -0
- package/src/client/dom/dom-swapper.d.ts +7 -0
- package/src/client/dom/dom-swapper.js +15 -0
- package/src/client/dom/stylesheet-discovery.d.ts +12 -0
- package/src/client/dom/stylesheet-discovery.js +24 -0
- package/src/client/eco-router-perform-navigation.d.ts +13 -0
- package/src/client/eco-router-perform-navigation.js +24 -0
- package/src/client/eco-router.d.ts +2 -35
- package/src/client/eco-router.js +329 -479
- package/src/client/index.d.ts +3 -0
- package/src/client/index.js +3 -0
- package/src/client/navigation-commit-reload.d.ts +21 -0
- package/src/client/navigation-commit-reload.js +16 -0
- package/src/client/navigation-commit.d.ts +19 -0
- package/src/client/navigation-commit.js +83 -0
- package/src/client/services/prefetch-manager.d.ts +10 -18
- package/src/client/services/prefetch-manager.js +353 -360
- package/src/client/types.d.ts +16 -13
- package/src/client/types.js +21 -20
- package/src/index.d.ts +2 -5
- package/src/index.js +7 -18
- package/CHANGELOG.md +0 -25
- package/src/client/services/dom-swapper.d.ts +0 -166
- package/src/client/services/dom-swapper.js +0 -497
- package/src/client/services/index.d.ts +0 -8
- package/src/client/services/index.js +0 -10
- package/src/client/services/scroll-manager.d.ts +0 -19
- package/src/client/services/scroll-manager.js +0 -36
- package/src/client/services/view-transition-manager.d.ts +0 -29
- package/src/client/services/view-transition-manager.js +0 -54
- package/src/client/view-transition-utils.d.ts +0 -14
- package/src/client/view-transition-utils.js +0 -60
- package/src/styles.css +0 -218
- package/src/types.d.ts +0 -15
- package/src/types.js +0 -5
package/README.md
CHANGED
|
@@ -10,6 +10,8 @@ Client-side navigation and view transitions for Ecopages. It intercepts same-ori
|
|
|
10
10
|
- **View Transitions**: Optional integration with the View Transition API.
|
|
11
11
|
- **Lifecycle events**: Hook into navigation with `eco:before-swap`, `eco:after-swap`, `eco:page-load`.
|
|
12
12
|
|
|
13
|
+
The core navigation pipeline shares document fetching, parsing, prefetch cache, head reconciliation, stylesheet staging, script activation, named view transitions, and lifecycle events with `@ecopages/react-router`. Browser-router always morphs the incoming body, preserving persisted elements across navigation regardless of view-transition settings or rerun scripts. View transitions only wrap the morph; scroll restoration uses the shared post-swap hook.
|
|
14
|
+
|
|
13
15
|
## Compatibility
|
|
14
16
|
|
|
15
17
|
This package is designed for MPA-style rendering where the server returns full HTML pages (e.g., KitaJS, Lit, vanilla JS, or component-level React islands).
|
|
@@ -24,7 +26,7 @@ This package is designed for MPA-style rendering where the server returns full H
|
|
|
24
26
|
## Installation
|
|
25
27
|
|
|
26
28
|
```bash
|
|
27
|
-
|
|
29
|
+
bun add @ecopages/browser-router
|
|
28
30
|
```
|
|
29
31
|
|
|
30
32
|
## Usage
|
|
@@ -53,6 +55,8 @@ const router = createRouter({
|
|
|
53
55
|
});
|
|
54
56
|
```
|
|
55
57
|
|
|
58
|
+
By default, when view transitions are enabled, the router opts the document out of the UA root group (no lighter flash on dark themes) and only calls `startViewTransition` when a page uses `data-view-transition` shared-element morphs. Set `viewTransitions: false` to disable.
|
|
59
|
+
|
|
56
60
|
By default, browser-router only syncs root `<html>` metadata it owns. Client-managed attributes and classes such as theme state are preserved unless you explicitly include them in `documentElementAttributesToSync`.
|
|
57
61
|
|
|
58
62
|
For advanced cases, browser-router also exports low-level document sync tooling without changing the router instance API:
|
|
@@ -60,7 +64,7 @@ For advanced cases, browser-router also exports low-level document sync tooling
|
|
|
60
64
|
```ts
|
|
61
65
|
import {
|
|
62
66
|
createRouter,
|
|
63
|
-
|
|
67
|
+
DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
|
|
64
68
|
syncDocumentElementAttributes,
|
|
65
69
|
} from '@ecopages/browser-router';
|
|
66
70
|
|
|
@@ -68,7 +72,7 @@ const router = createRouter();
|
|
|
68
72
|
|
|
69
73
|
document.addEventListener('eco:before-swap', (event) => {
|
|
70
74
|
syncDocumentElementAttributes(document, event.detail.newDocument, [
|
|
71
|
-
...
|
|
75
|
+
...DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
|
|
72
76
|
'data-theme',
|
|
73
77
|
]);
|
|
74
78
|
});
|
|
@@ -76,6 +80,12 @@ document.addEventListener('eco:before-swap', (event) => {
|
|
|
76
80
|
|
|
77
81
|
Loading the router script is the opt-in point for browser-router-managed navigation on that page shell. Pages without the router script continue to use normal document navigation.
|
|
78
82
|
|
|
83
|
+
## Router singleton
|
|
84
|
+
|
|
85
|
+
`createRouter()` returns a single active router per browser tab. The first call creates, starts, and stores the instance on `window.__ecopages_browser_router__`. Later calls return that same instance and ignore new options.
|
|
86
|
+
|
|
87
|
+
Call `router.stop()` before replacing the router script in long-lived sessions (for example after `data-eco-rerun` layout reloads) if you need a fresh instance with different options.
|
|
88
|
+
|
|
79
89
|
## Configuration
|
|
80
90
|
|
|
81
91
|
| Option | Type | Default | Description |
|
|
@@ -86,21 +96,28 @@ Loading the router script is the opt-in point for browser-router-managed navigat
|
|
|
86
96
|
| `reloadAttribute` | `string` | `'data-eco-reload'` | Attribute to force full page reload |
|
|
87
97
|
| `updateHistory` | `boolean` | `true` | Whether to update browser history |
|
|
88
98
|
| `scrollBehavior` | `'top' \| 'preserve' \| 'auto'` | `'top'` | Scroll behavior after navigation |
|
|
89
|
-
| `viewTransitions` | `boolean` | `
|
|
99
|
+
| `viewTransitions` | `boolean` | `true` | View Transition API; disables UA root crossfade by default. `false` disables. |
|
|
90
100
|
| `smoothScroll` | `boolean` | `false` | Use smooth scrolling during navigation |
|
|
101
|
+
| `reloadDocument` | `(href: string) => void` | `(href) => window.location.assign(href)` | Loads a URL as a full document when the router hands a navigation back to the browser |
|
|
91
102
|
|
|
92
103
|
## Persistence
|
|
93
104
|
|
|
94
|
-
Mark elements to preserve across navigations.
|
|
105
|
+
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.
|
|
106
|
+
|
|
107
|
+
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.
|
|
95
108
|
|
|
96
109
|
```html
|
|
97
110
|
<!-- This counter keeps its internal state across all navigations -->
|
|
98
111
|
<radiant-counter data-eco-persist="counter"></radiant-counter>
|
|
99
112
|
```
|
|
100
113
|
|
|
114
|
+
## Scripts on navigation
|
|
115
|
+
|
|
116
|
+
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.
|
|
117
|
+
|
|
101
118
|
## Script Re-execution
|
|
102
119
|
|
|
103
|
-
To force a script to re-execute on every navigation (e.g., analytics), add `data-eco-rerun`:
|
|
120
|
+
To force a head script to re-execute on every navigation (e.g., analytics), add `data-eco-rerun`:
|
|
104
121
|
|
|
105
122
|
```html
|
|
106
123
|
<script data-eco-rerun="true">
|
|
@@ -109,7 +126,7 @@ To force a script to re-execute on every navigation (e.g., analytics), add `data
|
|
|
109
126
|
```
|
|
110
127
|
|
|
111
128
|
> [!NOTE]
|
|
112
|
-
> `data-eco-script-id` is optional. Use it when you want an explicit stable identity for a rerun script.
|
|
129
|
+
> `data-eco-script-id` is optional. Use it when you want an explicit stable identity for a rerun script. Without it, an HTML `id` takes precedence; otherwise the router matches by original `src` or inline content. When matching by a relative `src`, the identity stays the same across different `<base>` URLs, while an external module reruns from the incoming page's resolved URL.
|
|
113
130
|
|
|
114
131
|
## Force Full Reload
|
|
115
132
|
|
|
@@ -121,7 +138,7 @@ Use `data-eco-reload` on an anchor tag to bypass the router and force a full pag
|
|
|
121
138
|
|
|
122
139
|
## Events
|
|
123
140
|
|
|
124
|
-
Listen to navigation lifecycle events on the `document
|
|
141
|
+
Listen to navigation lifecycle events on the `document`. Event detail types live in `@ecopages/core/client`.
|
|
125
142
|
|
|
126
143
|
```ts
|
|
127
144
|
document.addEventListener('eco:before-swap', (e) => {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ecopages/browser-router",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Client-side router for Ecopages with view transitions support",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ecopages",
|
|
@@ -18,24 +18,27 @@
|
|
|
18
18
|
"default": "./src/index.js"
|
|
19
19
|
},
|
|
20
20
|
"./client": {
|
|
21
|
-
"types": "./src/client/
|
|
22
|
-
"default": "./src/client/
|
|
21
|
+
"types": "./src/client/index.d.ts",
|
|
22
|
+
"default": "./src/client/index.js"
|
|
23
23
|
},
|
|
24
24
|
"./client.ts": {
|
|
25
|
-
"types": "./src/client/
|
|
26
|
-
"default": "./src/client/
|
|
25
|
+
"types": "./src/client/index.d.ts",
|
|
26
|
+
"default": "./src/client/index.js"
|
|
27
27
|
}
|
|
28
28
|
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
},
|
|
29
32
|
"repository": {
|
|
30
33
|
"type": "git",
|
|
31
|
-
"url": "https://github.com/ecopages/ecopages.git",
|
|
34
|
+
"url": "git+https://github.com/ecopages/ecopages.git",
|
|
32
35
|
"directory": "packages/browser-router"
|
|
33
36
|
},
|
|
34
37
|
"dependencies": {
|
|
35
38
|
"morphdom": "^2.7.8"
|
|
36
39
|
},
|
|
37
40
|
"peerDependencies": {
|
|
38
|
-
"@ecopages/core": "0.
|
|
41
|
+
"@ecopages/core": "0.3.0"
|
|
39
42
|
},
|
|
40
43
|
"types": "./src/index.d.ts"
|
|
41
|
-
}
|
|
44
|
+
}
|
|
@@ -2,13 +2,6 @@
|
|
|
2
2
|
* Helpers for synchronizing selected root `<html>` attributes during client-side navigation.
|
|
3
3
|
* @module
|
|
4
4
|
*/
|
|
5
|
-
/**
|
|
6
|
-
* Default root `<html>` attributes that browser-router treats as document-owned.
|
|
7
|
-
*
|
|
8
|
-
* These attributes are synchronized from the incoming document during navigation.
|
|
9
|
-
* Other root attributes are preserved unless explicitly included.
|
|
10
|
-
*/
|
|
11
|
-
export declare const defaultDocumentElementAttributesToSync: string[];
|
|
12
5
|
/**
|
|
13
6
|
* Synchronizes a selected set of root `<html>` attributes from an incoming document
|
|
14
7
|
* onto the current live document.
|
|
@@ -1,20 +1,30 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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
|
+
}
|
|
11
29
|
}
|
|
12
|
-
if (currentHtml.getAttribute(attributeName) !== nextValue) {
|
|
13
|
-
currentHtml.setAttribute(attributeName, nextValue);
|
|
14
|
-
}
|
|
15
|
-
}
|
|
16
30
|
}
|
|
17
|
-
export {
|
|
18
|
-
defaultDocumentElementAttributesToSync,
|
|
19
|
-
syncDocumentElementAttributes
|
|
20
|
-
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Manually attaches declarative shadow DOM templates.
|
|
3
|
+
*
|
|
4
|
+
* @remarks
|
|
5
|
+
* Browsers only process `<template shadowrootmode>` during initial parse.
|
|
6
|
+
*/
|
|
7
|
+
export declare function processDeclarativeShadowDOM(root: Element | Document | ShadowRoot): void;
|
|
8
|
+
/**
|
|
9
|
+
* Morphs document body using morphdom.
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* Preserves persisted elements and hydrated custom elements when their ancestor
|
|
13
|
+
* structure remains compatible. Rerun scripts refresh matching non-persisted
|
|
14
|
+
* elements so freshly activated handlers do not accumulate on nodes retained by
|
|
15
|
+
* morphdom.
|
|
16
|
+
*
|
|
17
|
+
* @remarks
|
|
18
|
+
* Persisted nodes and their ancestors remain in place while other matching
|
|
19
|
+
* elements are refreshed, so rerun scripts that add handlers to retained nodes
|
|
20
|
+
* must register them idempotently. Descendants of custom elements on that path
|
|
21
|
+
* also remain the same nodes when their markup stays structurally compatible;
|
|
22
|
+
* changed child markup can replace nodes without reconnecting the host, so
|
|
23
|
+
* components must handle rebinding.
|
|
24
|
+
* Light-DOM custom elements are fully replaced to trigger their
|
|
25
|
+
* disconnectedCallback → connectedCallback lifecycle.
|
|
26
|
+
*/
|
|
27
|
+
export declare function morphBody(newDocument: Document, persistAttribute: string): void;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import morphdom from 'morphdom';
|
|
2
|
+
import { ECO_PERSIST_ATTRIBUTE } from '@ecopages/core/client';
|
|
3
|
+
function isPersisted(element, persistAttribute) {
|
|
4
|
+
return element.hasAttribute(persistAttribute) || element.hasAttribute(ECO_PERSIST_ATTRIBUTE);
|
|
5
|
+
}
|
|
6
|
+
function isHydratedCustomElement(element) {
|
|
7
|
+
return element.localName.includes('-') && element.shadowRoot !== null;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Finds the persisted path and custom-element descendants retained during rerun refreshes.
|
|
11
|
+
*
|
|
12
|
+
* @remarks
|
|
13
|
+
* Custom elements may bind listeners to their children in `connectedCallback`. Their descendants
|
|
14
|
+
* must remain the same nodes when a persisted element keeps the custom-element host connected.
|
|
15
|
+
*/
|
|
16
|
+
function findPersistedRerunContext(root, persistAttribute) {
|
|
17
|
+
const retainedElements = new Set();
|
|
18
|
+
for (const element of root.querySelectorAll('*')) {
|
|
19
|
+
if (!isPersisted(element, persistAttribute))
|
|
20
|
+
continue;
|
|
21
|
+
let parent = element.parentElement;
|
|
22
|
+
while (parent && parent !== root) {
|
|
23
|
+
retainedElements.add(parent);
|
|
24
|
+
if (parent.localName.includes('-')) {
|
|
25
|
+
for (const descendant of parent.querySelectorAll('*')) {
|
|
26
|
+
retainedElements.add(descendant);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
parent = parent.parentElement;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return retainedElements;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Returns the only body-morph keys that browser-router should trust.
|
|
36
|
+
*
|
|
37
|
+
* @remarks
|
|
38
|
+
* morphdom defaults to treating every `id` attribute as a structural key.
|
|
39
|
+
* That is fragile for content-heavy pages where repeated heading ids or other
|
|
40
|
+
* invalid-but-common markup can appear. Browser-router only needs stable keys
|
|
41
|
+
* for explicitly persisted nodes, so all other elements fall back to normal
|
|
42
|
+
* tree-order diffing.
|
|
43
|
+
*/
|
|
44
|
+
function getBodyMorphKey(element, persistAttribute) {
|
|
45
|
+
if (!(element instanceof Element)) {
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
return element.getAttribute(persistAttribute) || element.getAttribute(ECO_PERSIST_ATTRIBUTE) || undefined;
|
|
49
|
+
}
|
|
50
|
+
function isLightDomCustomElement(element) {
|
|
51
|
+
return element.localName.includes('-') && element.shadowRoot === null;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* @returns Always `false` to tell morphdom to skip updating this element.
|
|
55
|
+
*
|
|
56
|
+
* @remarks
|
|
57
|
+
* Replacing elements during morphdom traversal mutates the live DOM tree,
|
|
58
|
+
* which can cause morphdom to skip siblings or process stale nodes.
|
|
59
|
+
* Deferring the replacement until after morphdom finishes avoids this.
|
|
60
|
+
*/
|
|
61
|
+
function deferElementReplacement(fromEl, toEl, deferred) {
|
|
62
|
+
deferred.push({
|
|
63
|
+
from: fromEl,
|
|
64
|
+
to: toEl.cloneNode(true),
|
|
65
|
+
isCustomElement: fromEl.localName.includes('-'),
|
|
66
|
+
});
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
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
|
+
/**
|
|
78
|
+
* @remarks
|
|
79
|
+
* Custom elements are recreated via `document.createElement` so the browser fires
|
|
80
|
+
* their full lifecycle. Elements already removed during the morph pass are skipped.
|
|
81
|
+
*/
|
|
82
|
+
function flushDeferredReplacements(deferred) {
|
|
83
|
+
for (const { from, to, isCustomElement } of deferred) {
|
|
84
|
+
if (!from.isConnected)
|
|
85
|
+
continue;
|
|
86
|
+
const newEl = isCustomElement ? materializeCustomElement(to) : to.cloneNode(true);
|
|
87
|
+
from.replaceWith(newEl);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Manually attaches declarative shadow DOM templates.
|
|
92
|
+
*
|
|
93
|
+
* @remarks
|
|
94
|
+
* Browsers only process `<template shadowrootmode>` during initial parse.
|
|
95
|
+
*/
|
|
96
|
+
export function processDeclarativeShadowDOM(root) {
|
|
97
|
+
const templates = root.querySelectorAll('template[shadowrootmode], template[shadowroot]');
|
|
98
|
+
for (const template of templates) {
|
|
99
|
+
const mode = (template.getAttribute('shadowrootmode') || template.getAttribute('shadowroot'));
|
|
100
|
+
const parent = template.parentElement;
|
|
101
|
+
if (parent && !parent.shadowRoot) {
|
|
102
|
+
const shadowRoot = parent.attachShadow({ mode });
|
|
103
|
+
shadowRoot.appendChild(template.content);
|
|
104
|
+
template.remove();
|
|
105
|
+
processDeclarativeShadowDOM(shadowRoot);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Morphs document body using morphdom.
|
|
111
|
+
*
|
|
112
|
+
* @remarks
|
|
113
|
+
* Preserves persisted elements and hydrated custom elements when their ancestor
|
|
114
|
+
* structure remains compatible. Rerun scripts refresh matching non-persisted
|
|
115
|
+
* elements so freshly activated handlers do not accumulate on nodes retained by
|
|
116
|
+
* morphdom.
|
|
117
|
+
*
|
|
118
|
+
* @remarks
|
|
119
|
+
* Persisted nodes and their ancestors remain in place while other matching
|
|
120
|
+
* elements are refreshed, so rerun scripts that add handlers to retained nodes
|
|
121
|
+
* must register them idempotently. Descendants of custom elements on that path
|
|
122
|
+
* also remain the same nodes when their markup stays structurally compatible;
|
|
123
|
+
* changed child markup can replace nodes without reconnecting the host, so
|
|
124
|
+
* components must handle rebinding.
|
|
125
|
+
* Light-DOM custom elements are fully replaced to trigger their
|
|
126
|
+
* disconnectedCallback → connectedCallback lifecycle.
|
|
127
|
+
*/
|
|
128
|
+
export function morphBody(newDocument, persistAttribute) {
|
|
129
|
+
const deferredReplacements = [];
|
|
130
|
+
const refreshUnpersistedElements = newDocument.querySelector('script[data-eco-rerun]') !== null;
|
|
131
|
+
const retainedRerunContext = refreshUnpersistedElements
|
|
132
|
+
? findPersistedRerunContext(document.body, persistAttribute)
|
|
133
|
+
: new Set();
|
|
134
|
+
morphdom(document.body, newDocument.body, {
|
|
135
|
+
getNodeKey: (node) => getBodyMorphKey(node, persistAttribute),
|
|
136
|
+
onBeforeNodeAdded: (node) => {
|
|
137
|
+
if (node instanceof Element && isLightDomCustomElement(node)) {
|
|
138
|
+
return materializeCustomElement(node);
|
|
139
|
+
}
|
|
140
|
+
return node;
|
|
141
|
+
},
|
|
142
|
+
onBeforeElUpdated: (fromEl, toEl) => {
|
|
143
|
+
if (isPersisted(fromEl, persistAttribute)) {
|
|
144
|
+
return false;
|
|
145
|
+
}
|
|
146
|
+
if (refreshUnpersistedElements) {
|
|
147
|
+
if (fromEl === document.body || retainedRerunContext.has(fromEl)) {
|
|
148
|
+
return true;
|
|
149
|
+
}
|
|
150
|
+
return deferElementReplacement(fromEl, toEl, deferredReplacements);
|
|
151
|
+
}
|
|
152
|
+
if (isHydratedCustomElement(fromEl)) {
|
|
153
|
+
return deferElementReplacement(fromEl, toEl, deferredReplacements);
|
|
154
|
+
}
|
|
155
|
+
if (isLightDomCustomElement(fromEl)) {
|
|
156
|
+
return deferElementReplacement(fromEl, toEl, deferredReplacements);
|
|
157
|
+
}
|
|
158
|
+
if (fromEl.isEqualNode(toEl)) {
|
|
159
|
+
return false;
|
|
160
|
+
}
|
|
161
|
+
return true;
|
|
162
|
+
},
|
|
163
|
+
});
|
|
164
|
+
flushDeferredReplacements(deferredReplacements);
|
|
165
|
+
processDeclarativeShadowDOM(document.body);
|
|
166
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/** Applies browser-router's DOM body swap. Core owns document navigation work. */
|
|
2
|
+
export declare class DomSwapper {
|
|
3
|
+
private persistAttribute;
|
|
4
|
+
constructor(persistAttribute: string);
|
|
5
|
+
parseHTML(html: string, url?: URL): Document;
|
|
6
|
+
morphBody(newDocument: Document): void;
|
|
7
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { parseNavigationDocument } from '@ecopages/core/client';
|
|
2
|
+
import { morphBody } from './body-morpher.js';
|
|
3
|
+
/** Applies browser-router's DOM body swap. Core owns document navigation work. */
|
|
4
|
+
export class DomSwapper {
|
|
5
|
+
persistAttribute;
|
|
6
|
+
constructor(persistAttribute) {
|
|
7
|
+
this.persistAttribute = persistAttribute;
|
|
8
|
+
}
|
|
9
|
+
parseHTML(html, url) {
|
|
10
|
+
return parseNavigationDocument(html, url ?? new URL(window.location.href));
|
|
11
|
+
}
|
|
12
|
+
morphBody(newDocument) {
|
|
13
|
+
morphBody(newDocument, this.persistAttribute);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared stylesheet href discovery for navigation prefetch and commit.
|
|
3
|
+
* @module
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Returns resolved stylesheet hrefs currently in the document head.
|
|
7
|
+
*/
|
|
8
|
+
export declare function getCurrentStylesheetHrefs(): Set<string>;
|
|
9
|
+
/**
|
|
10
|
+
* Returns stylesheet links present in `source` but not in `existingHrefs`.
|
|
11
|
+
*/
|
|
12
|
+
export declare function discoverNewStylesheetLinks(source: Document, existingHrefs?: Set<string>): HTMLLinkElement[];
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared stylesheet href discovery for navigation prefetch and commit.
|
|
3
|
+
* @module
|
|
4
|
+
*/
|
|
5
|
+
/**
|
|
6
|
+
* Returns resolved stylesheet hrefs currently in the document head.
|
|
7
|
+
*/
|
|
8
|
+
export function getCurrentStylesheetHrefs() {
|
|
9
|
+
return new Set(Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).map((link) => link.href));
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Returns stylesheet links present in `source` but not in `existingHrefs`.
|
|
13
|
+
*/
|
|
14
|
+
export function discoverNewStylesheetLinks(source, existingHrefs = getCurrentStylesheetHrefs()) {
|
|
15
|
+
const discovered = [];
|
|
16
|
+
for (const link of source.head.querySelectorAll('link[rel="stylesheet"]')) {
|
|
17
|
+
if (existingHrefs.has(link.href)) {
|
|
18
|
+
continue;
|
|
19
|
+
}
|
|
20
|
+
existingHrefs.add(link.href);
|
|
21
|
+
discovered.push(link);
|
|
22
|
+
}
|
|
23
|
+
return discovered;
|
|
24
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { EcoNavigationEvent } from '@ecopages/core/client';
|
|
2
|
+
import type { NavigationCommit } from './navigation-commit.js';
|
|
3
|
+
export type PerformNavigationAttemptInput = {
|
|
4
|
+
url: URL;
|
|
5
|
+
direction: EcoNavigationEvent['direction'];
|
|
6
|
+
bypassPrefetchCache?: boolean;
|
|
7
|
+
allowFullDocumentFallback?: boolean;
|
|
8
|
+
navigationCommit: NavigationCommit;
|
|
9
|
+
isStaleNavigation: () => boolean;
|
|
10
|
+
signal: AbortSignal;
|
|
11
|
+
};
|
|
12
|
+
export declare function runPerformNavigationAttempt(input: PerformNavigationAttemptInput): Promise<boolean>;
|
|
13
|
+
export declare function shouldIgnorePerformNavigationError(error: unknown, isStaleNavigation: () => boolean): boolean;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { fetchNavigationPage } from '@ecopages/core/client';
|
|
2
|
+
export async function runPerformNavigationAttempt(input) {
|
|
3
|
+
const page = await fetchNavigationPage(input.url, {
|
|
4
|
+
signal: input.signal,
|
|
5
|
+
bypassCache: input.bypassPrefetchCache,
|
|
6
|
+
});
|
|
7
|
+
if (!page) {
|
|
8
|
+
throw new Error('Navigation response was not a successful HTML page');
|
|
9
|
+
}
|
|
10
|
+
if (input.isStaleNavigation()) {
|
|
11
|
+
return false;
|
|
12
|
+
}
|
|
13
|
+
return await input.navigationCommit.commit(page.finalUrl, input.direction, page.document, {
|
|
14
|
+
html: page.html,
|
|
15
|
+
isStaleNavigation: input.isStaleNavigation,
|
|
16
|
+
allowFullDocumentFallback: input.allowFullDocumentFallback ?? true,
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export function shouldIgnorePerformNavigationError(error, isStaleNavigation) {
|
|
20
|
+
if (isStaleNavigation()) {
|
|
21
|
+
return true;
|
|
22
|
+
}
|
|
23
|
+
return error instanceof Error && error.name === 'AbortError';
|
|
24
|
+
}
|
|
@@ -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 type
|
|
5
|
+
import { type EcoRouterOptions } from './types.js';
|
|
6
6
|
/**
|
|
7
7
|
* Intercepts same-origin link clicks and performs client-side navigation
|
|
8
8
|
* using morphdom for efficient DOM diffing. Supports View Transitions API.
|
|
@@ -13,32 +13,13 @@ export declare class EcoRouter {
|
|
|
13
13
|
private started;
|
|
14
14
|
private pendingNavigations;
|
|
15
15
|
private pendingPointerNavigation;
|
|
16
|
-
private pendingHoverNavigation;
|
|
17
16
|
private queuedNavigationHref;
|
|
18
17
|
private domSwapper;
|
|
19
|
-
private scrollManager;
|
|
20
|
-
private viewTransitionManager;
|
|
21
18
|
private prefetchManager;
|
|
19
|
+
private readonly navigationCommit;
|
|
22
20
|
constructor(options?: EcoRouterOptions);
|
|
23
|
-
private getLinkFromEvent;
|
|
24
|
-
private canInterceptLink;
|
|
25
21
|
private getRecoveredPointerHref;
|
|
26
|
-
private getRecoveredHoverHref;
|
|
27
22
|
private isAnotherNavigationRuntimeActive;
|
|
28
|
-
private getDocumentOwner;
|
|
29
|
-
private adoptDocumentOwner;
|
|
30
|
-
private syncDocumentElementAttributes;
|
|
31
|
-
private reloadDocument;
|
|
32
|
-
/**
|
|
33
|
-
* Commits a fully fetched document into the live page.
|
|
34
|
-
*
|
|
35
|
-
* When browser-router accepts a handoff from another runtime, it delays source
|
|
36
|
-
* runtime cleanup until the incoming document has been prepared and is ready to
|
|
37
|
-
* commit. That ordering avoids the blank-page window we previously hit when a
|
|
38
|
-
* delegated navigation went stale after the source runtime had already torn
|
|
39
|
-
* itself down.
|
|
40
|
-
*/
|
|
41
|
-
private commitDocumentNavigation;
|
|
42
23
|
/**
|
|
43
24
|
* Starts the router and begins intercepting navigation.
|
|
44
25
|
*
|
|
@@ -76,18 +57,12 @@ export declare class EcoRouter {
|
|
|
76
57
|
* Shadow DOM boundaries (Web Components).
|
|
77
58
|
*/
|
|
78
59
|
private handlePointerDown;
|
|
79
|
-
private handleHoverIntent;
|
|
80
60
|
private handleClick;
|
|
81
61
|
/**
|
|
82
62
|
* Handles browser back/forward navigation.
|
|
83
63
|
* Triggered by the History API's popstate event.
|
|
84
64
|
*/
|
|
85
65
|
private handlePopState;
|
|
86
|
-
/**
|
|
87
|
-
* Checks if a URL shares the same origin as the current page.
|
|
88
|
-
* Cross-origin navigation always falls back to full page reload.
|
|
89
|
-
*/
|
|
90
|
-
private isSameOrigin;
|
|
91
66
|
private cancelNavigationTransaction;
|
|
92
67
|
private beginNavigationTransaction;
|
|
93
68
|
/**
|
|
@@ -109,13 +84,6 @@ export declare class EcoRouter {
|
|
|
109
84
|
* @param direction - Navigation direction ('forward', 'back', or 'replace')
|
|
110
85
|
*/
|
|
111
86
|
private performNavigation;
|
|
112
|
-
/**
|
|
113
|
-
* Fetches the HTML content of a page.
|
|
114
|
-
* @param url - The URL to fetch
|
|
115
|
-
* @param signal - AbortSignal for cancelling the request
|
|
116
|
-
* @throws Error if the response is not ok
|
|
117
|
-
*/
|
|
118
|
-
private fetchPage;
|
|
119
87
|
}
|
|
120
88
|
/**
|
|
121
89
|
* Creates and starts a router instance.
|
|
@@ -129,4 +97,3 @@ export declare class EcoRouter {
|
|
|
129
97
|
* @returns A started EcoRouter instance
|
|
130
98
|
*/
|
|
131
99
|
export declare function createRouter(options?: EcoRouterOptions): EcoRouter;
|
|
132
|
-
export type { EcoRouterOptions, EcoNavigationEvent, EcoBeforeSwapEvent, EcoAfterSwapEvent } from './types';
|