@ecopages/browser-router 0.2.0-beta.9 → 0.2.0-rc.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.
Files changed (43) hide show
  1. package/README.md +12 -4
  2. package/package.json +6 -6
  3. package/src/client/document-element-sync.d.ts +0 -7
  4. package/src/client/document-element-sync.js +28 -18
  5. package/src/client/dom/body-morpher.d.ts +24 -0
  6. package/src/client/dom/body-morpher.js +143 -0
  7. package/src/client/dom/dom-swapper.d.ts +30 -0
  8. package/src/client/dom/dom-swapper.js +52 -0
  9. package/src/client/dom/head-updater.d.ts +42 -0
  10. package/src/client/dom/head-updater.js +194 -0
  11. package/src/client/dom/html-parser.d.ts +4 -0
  12. package/src/client/dom/html-parser.js +8 -0
  13. package/src/client/dom/stylesheet-discovery.d.ts +12 -0
  14. package/src/client/dom/stylesheet-discovery.js +24 -0
  15. package/src/client/dom/stylesheet-preloader.d.ts +10 -0
  16. package/src/client/dom/stylesheet-preloader.js +44 -0
  17. package/src/client/eco-router.d.ts +2 -31
  18. package/src/client/eco-router.js +337 -443
  19. package/src/client/index.d.ts +3 -0
  20. package/src/client/index.js +3 -0
  21. package/src/client/navigation-commit.d.ts +22 -0
  22. package/src/client/navigation-commit.js +104 -0
  23. package/src/client/navigation-fetch.d.ts +8 -0
  24. package/src/client/navigation-fetch.js +24 -0
  25. package/src/client/services/prefetch-manager.d.ts +2 -14
  26. package/src/client/services/prefetch-manager.js +378 -370
  27. package/src/client/services/view-transition-manager.d.ts +6 -2
  28. package/src/client/services/view-transition-manager.js +76 -52
  29. package/src/client/types.d.ts +6 -13
  30. package/src/client/types.js +19 -20
  31. package/src/index.d.ts +3 -5
  32. package/src/index.js +8 -18
  33. package/src/client/services/dom-swapper.d.ts +0 -168
  34. package/src/client/services/dom-swapper.js +0 -529
  35. package/src/client/services/index.d.ts +0 -8
  36. package/src/client/services/index.js +0 -10
  37. package/src/client/services/scroll-manager.d.ts +0 -19
  38. package/src/client/services/scroll-manager.js +0 -36
  39. package/src/client/view-transition-utils.d.ts +0 -14
  40. package/src/client/view-transition-utils.js +0 -60
  41. package/src/styles.css +0 -218
  42. package/src/types.d.ts +0 -15
  43. package/src/types.js +0 -5
@@ -2,13 +2,17 @@
2
2
  * Manages View Transition API integration
3
3
  * @module
4
4
  */
5
+ export type ViewTransitionNavigationOptions = {
6
+ /** Incoming document for the navigation (used to detect named transitions on the next page). */
7
+ incomingDocument?: Document;
8
+ };
5
9
  /**
6
10
  * Service for handling View Transition API during page transitions.
7
11
  * Falls back to direct execution if the API is not supported.
8
12
  */
9
13
  export declare class ViewTransitionManager {
10
14
  private enabled;
11
- constructor(enabled: boolean);
15
+ constructor(enabled?: boolean);
12
16
  /**
13
17
  * Check if the View Transition API is supported
14
18
  */
@@ -25,5 +29,5 @@ export declare class ViewTransitionManager {
25
29
  * @param callback - The DOM update callback to execute
26
30
  * @returns Promise that resolves when the DOM update has committed
27
31
  */
28
- transition(callback: () => void | Promise<void>): Promise<void>;
32
+ transition(callback: () => void | Promise<void>, options?: ViewTransitionNavigationOptions): Promise<void>;
29
33
  }
@@ -1,54 +1,78 @@
1
- import { applyViewTransitionNames, clearViewTransitionNames } from "../view-transition-utils.js";
2
- class ViewTransitionManager {
3
- enabled;
4
- constructor(enabled) {
5
- this.enabled = enabled;
6
- }
7
- /**
8
- * Check if the View Transition API is supported
9
- */
10
- isSupported() {
11
- return "startViewTransition" in document;
12
- }
13
- /**
14
- * Execute a callback with view transition if available and enabled.
15
- * Falls back to direct execution if not supported.
16
- *
17
- * Navigation correctness depends on the DOM update callback completing, not on
18
- * the browser finishing the visual transition animation. Awaiting
19
- * `finished` here can leave router transactions artificially in-flight and
20
- * block later navigations during rapid repeated clicks, so the router waits
21
- * for `updateCallbackDone` and lets the animation finish in the background.
22
- * @param callback - The DOM update callback to execute
23
- * @returns Promise that resolves when the DOM update has committed
24
- */
25
- async transition(callback) {
26
- if (!this.enabled || !this.isSupported()) {
27
- await callback();
28
- return;
1
+ /**
2
+ * Manages View Transition API integration
3
+ * @module
4
+ */
5
+ import { applyViewTransitionNames, clearViewTransitionNames, ensureRootViewTransitionStyles, navigationHasNamedViewTransitions, } from '@ecopages/core/client/view-transitions';
6
+ /**
7
+ * Service for handling View Transition API during page transitions.
8
+ * Falls back to direct execution if the API is not supported.
9
+ */
10
+ export class ViewTransitionManager {
11
+ enabled;
12
+ constructor(enabled = true) {
13
+ this.enabled = enabled;
14
+ if (this.enabled) {
15
+ ensureRootViewTransitionStyles();
16
+ }
17
+ }
18
+ /**
19
+ * Check if the View Transition API is supported
20
+ */
21
+ isSupported() {
22
+ return 'startViewTransition' in document;
23
+ }
24
+ /**
25
+ * Execute a callback with view transition if available and enabled.
26
+ * Falls back to direct execution if not supported.
27
+ *
28
+ * Navigation correctness depends on the DOM update callback completing, not on
29
+ * the browser finishing the visual transition animation. Awaiting
30
+ * `finished` here can leave router transactions artificially in-flight and
31
+ * block later navigations during rapid repeated clicks, so the router waits
32
+ * for `updateCallbackDone` and lets the animation finish in the background.
33
+ * @param callback - The DOM update callback to execute
34
+ * @returns Promise that resolves when the DOM update has committed
35
+ */
36
+ async transition(callback, options = {}) {
37
+ const incoming = options.incomingDocument;
38
+ const useNamedTransition = this.enabled && this.isSupported() && navigationHasNamedViewTransitions(document, incoming ?? document);
39
+ if (!useNamedTransition) {
40
+ await callback();
41
+ return;
42
+ }
43
+ /**
44
+ * Apply view transition names to current elements before starting the transition.
45
+ * This ensures the "old" state is captured correctly.
46
+ */
47
+ applyViewTransitionNames();
48
+ const transition = document.startViewTransition(async () => {
49
+ await callback();
50
+ /**
51
+ * Apply names to the NEW elements after DOM swap and hydration.
52
+ * This ensures the "new" state is captured correctly.
53
+ */
54
+ applyViewTransitionNames();
55
+ });
56
+ void transition.ready.catch((error) => {
57
+ if (error instanceof Error && error.name === 'AbortError') {
58
+ return;
59
+ }
60
+ console.error('[ecopages] View transition failed to start:', error);
61
+ });
62
+ void transition.finished
63
+ .catch((error) => {
64
+ if (error instanceof Error && error.name === 'AbortError') {
65
+ return;
66
+ }
67
+ console.error('[ecopages] View transition lifecycle failed:', error);
68
+ })
69
+ .finally(() => {
70
+ /**
71
+ * Cleanup view transition names and dynamic styles after the browser's
72
+ * animation lifecycle completes.
73
+ */
74
+ clearViewTransitionNames();
75
+ });
76
+ await transition.updateCallbackDone;
29
77
  }
30
- applyViewTransitionNames();
31
- const transition = document.startViewTransition(async () => {
32
- await callback();
33
- applyViewTransitionNames();
34
- });
35
- void transition.ready.catch((error) => {
36
- if (error instanceof Error && error.name === "AbortError") {
37
- return;
38
- }
39
- console.error("[ecopages] View transition failed to start:", error);
40
- });
41
- void transition.finished.catch((error) => {
42
- if (error instanceof Error && error.name === "AbortError") {
43
- return;
44
- }
45
- console.error("[ecopages] View transition lifecycle failed:", error);
46
- }).finally(() => {
47
- clearViewTransitionNames();
48
- });
49
- await transition.updateCallbackDone;
50
- }
51
78
  }
52
- export {
53
- ViewTransitionManager
54
- };
@@ -59,6 +59,12 @@ export interface EcoRouterOptions {
59
59
  /**
60
60
  * Whether to use the View Transition API for animations.
61
61
  * Falls back to instant swap if not supported.
62
+ *
63
+ * @remarks
64
+ * When enabled, injects `html { view-transition-name: none }` so the UA root
65
+ * group does not flash lighter on dark UIs. `startViewTransition` runs only when
66
+ * the current or incoming page has `data-view-transition` elements. Use
67
+ * `viewTransitions: false` to disable entirely.
62
68
  * @default true
63
69
  */
64
70
  viewTransitions?: boolean;
@@ -77,19 +83,6 @@ export interface EcoRouterOptions {
77
83
  export type BrowserRouterNavigateOptions = {
78
84
  direction?: 'forward' | 'back' | 'replace';
79
85
  };
80
- /** Events emitted during the navigation lifecycle */
81
- export interface EcoNavigationEvent {
82
- url: URL;
83
- direction: 'forward' | 'back' | 'replace';
84
- }
85
- /** Event fired before the DOM swap occurs */
86
- export interface EcoBeforeSwapEvent extends EcoNavigationEvent {
87
- newDocument: Document;
88
- reload: () => void;
89
- }
90
- /** Event fired after the DOM swap completes */
91
- export interface EcoAfterSwapEvent extends EcoNavigationEvent {
92
- }
93
86
  /** Default document-level `<html>` attributes synchronized during navigation swaps. */
94
87
  export declare const DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC: string[];
95
88
  /** Default configuration options */
@@ -1,23 +1,22 @@
1
- import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from "@ecopages/core/router/navigation-coordinator";
1
+ import { ECO_DOCUMENT_OWNER_ATTRIBUTE } from '@ecopages/core/router/navigation-coordinator';
2
+ /** Default prefetch configuration */
2
3
  const DEFAULT_PREFETCH_CONFIG = {
3
- strategy: "intent",
4
- delay: 65,
5
- noPrefetchAttribute: "data-eco-no-prefetch",
6
- respectDataSaver: true
4
+ strategy: 'intent',
5
+ delay: 65,
6
+ noPrefetchAttribute: 'data-eco-no-prefetch',
7
+ respectDataSaver: true,
7
8
  };
8
- const DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC = ["lang", "dir", ECO_DOCUMENT_OWNER_ATTRIBUTE];
9
- const DEFAULT_OPTIONS = {
10
- linkSelector: "a[href]",
11
- documentElementAttributesToSync: DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
12
- persistAttribute: "data-eco-persist",
13
- reloadAttribute: "data-eco-reload",
14
- updateHistory: true,
15
- scrollBehavior: "top",
16
- viewTransitions: true,
17
- smoothScroll: false,
18
- prefetch: DEFAULT_PREFETCH_CONFIG
19
- };
20
- export {
21
- DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
22
- DEFAULT_OPTIONS
9
+ /** Default document-level `<html>` attributes synchronized during navigation swaps. */
10
+ export const DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC = ['lang', 'dir', ECO_DOCUMENT_OWNER_ATTRIBUTE];
11
+ /** Default configuration options */
12
+ export const DEFAULT_OPTIONS = {
13
+ linkSelector: 'a[href]',
14
+ documentElementAttributesToSync: DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
15
+ persistAttribute: 'data-eco-persist',
16
+ reloadAttribute: 'data-eco-reload',
17
+ updateHistory: true,
18
+ scrollBehavior: 'top',
19
+ viewTransitions: true,
20
+ smoothScroll: false,
21
+ prefetch: DEFAULT_PREFETCH_CONFIG,
23
22
  };
package/src/index.d.ts CHANGED
@@ -3,8 +3,6 @@
3
3
  * Client-side navigation and view transitions for Ecopages
4
4
  * @module
5
5
  */
6
- export type { EcoRouterOptions, EcoNavigationEvent, EcoBeforeSwapEvent, EcoAfterSwapEvent, EcoRouterEventMap, } from './types.js';
7
- export { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS } from './types.js';
8
- export { defaultDocumentElementAttributesToSync, syncDocumentElementAttributes, } from './client/document-element-sync.js';
9
- export { EcoRouter, createRouter } from './client/eco-router.js';
10
- export { DomSwapper, ScrollManager, ViewTransitionManager } from './client/services/index.js';
6
+ export { createRouter, DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS, EcoRouter, syncDocumentElementAttributes, type BrowserRouterNavigateOptions, type EcoRouterOptions, } from './client/index.js';
7
+ export { DomSwapper } from './client/dom/dom-swapper.js';
8
+ export { ViewTransitionManager } from './client/services/view-transition-manager.js';
package/src/index.js CHANGED
@@ -1,18 +1,8 @@
1
- import { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS } from "./types.js";
2
- import {
3
- defaultDocumentElementAttributesToSync,
4
- syncDocumentElementAttributes
5
- } from "./client/document-element-sync.js";
6
- import { EcoRouter, createRouter } from "./client/eco-router.js";
7
- import { DomSwapper, ScrollManager, ViewTransitionManager } from "./client/services/index.js";
8
- export {
9
- DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
10
- DEFAULT_OPTIONS,
11
- DomSwapper,
12
- EcoRouter,
13
- ScrollManager,
14
- ViewTransitionManager,
15
- createRouter,
16
- defaultDocumentElementAttributesToSync,
17
- syncDocumentElementAttributes
18
- };
1
+ /**
2
+ * @ecopages/browser-router
3
+ * Client-side navigation and view transitions for Ecopages
4
+ * @module
5
+ */
6
+ export { createRouter, DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS, EcoRouter, syncDocumentElementAttributes, } from './client/index.js';
7
+ export { DomSwapper } from './client/dom/dom-swapper.js';
8
+ export { ViewTransitionManager } from './client/services/view-transition-manager.js';
@@ -1,168 +0,0 @@
1
- /**
2
- * DOM morphing service for client-side navigation.
3
- * Uses Idiomorph for body morphing and Turbo-style surgical updates for head.
4
- * @module dom-swapper
5
- */
6
- /**
7
- * Handles DOM manipulation during client-side page transitions.
8
- *
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 declare class DomSwapper {
14
- private persistAttribute;
15
- private pendingHeadScripts;
16
- private pendingRerunScripts;
17
- private rerunNonce;
18
- constructor(persistAttribute: string);
19
- /**
20
- * Parses HTML string into a Document, injecting a temporary base tag for URL resolution.
21
- */
22
- parseHTML(html: string, url?: URL): Document;
23
- /**
24
- * Preloads new stylesheets from target document to prevent FOUC.
25
- *
26
- * Discovers stylesheet links in the target document that aren't present in the
27
- * current document, creates corresponding link elements, and waits for all to
28
- * load before resolving. This follows Turbo's approach of waiting for stylesheets
29
- * before any DOM updates.
30
- */
31
- preloadStylesheets(newDocument: Document): Promise<void>;
32
- /**
33
- * Updates document head using Turbo-style surgical updates.
34
- *
35
- * This approach avoids morphing the head element entirely, which prevents
36
- * browser repaints that cause FOUC. Instead, it:
37
- * - Updates the document title
38
- * - Merges meta tags (adds new, updates changed)
39
- * - Leaves stylesheets untouched (they're preloaded separately)
40
- * - Handles script re-execution for marked scripts
41
- * - Injects new scripts from the incoming page that are absent from the current head
42
- */
43
- morphHead(newDocument: Document): void;
44
- /**
45
- * Replays queued `data-eco-rerun` scripts after the body swap completes.
46
- *
47
- * Scripts are intentionally flushed after the new body is in place so DOM-
48
- * dependent bootstraps bind against the incoming page rather than the page
49
- * being replaced.
50
- */
51
- flushRerunScripts(): void;
52
- /**
53
- * Returns whether pending rerun scripts require a full body replacement
54
- * instead of morphing, so DOM-dependent bootstraps bind against fresh markup.
55
- */
56
- shouldReplaceBodyForRerunScripts(): boolean;
57
- /**
58
- * Detects custom elements without shadow DOM (light-DOM custom elements).
59
- * These need full replacement rather than morphing, because morphdom would
60
- * strip JS-generated content from their light DOM children.
61
- */
62
- private isLightDomCustomElement;
63
- /**
64
- * Queues a custom element for deferred replacement instead of replacing it
65
- * inline during the morphdom walk.
66
- *
67
- * Replacing elements during morphdom traversal mutates the live DOM tree,
68
- * which can cause morphdom to skip siblings or process stale nodes.
69
- * Deferring the replacement until after morphdom finishes avoids this.
70
- *
71
- * @returns Always `false` to tell morphdom to skip updating this element.
72
- */
73
- private replaceCustomElement;
74
- private materializeCustomElement;
75
- /**
76
- * Replaces all deferred custom elements after morphdom has finished traversing.
77
- *
78
- * Each element is recreated via `document.createElement` so the browser fires
79
- * the full custom element lifecycle (`disconnectedCallback` on the old instance,
80
- * `connectedCallback` on the new one). Elements that were already removed during
81
- * the morph pass are skipped via the `isConnected` guard.
82
- */
83
- private flushDeferredCustomElementReplacements;
84
- /**
85
- * Morphs document body using morphdom.
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
- morphBody(newDocument: Document): void;
91
- /**
92
- * Replaces body content in a single operation.
93
- * Preserves persisted elements by moving them to the new body.
94
- * Use when View Transitions are disabled.
95
- */
96
- replaceBody(newDocument: Document): void;
97
- /**
98
- * Collects all `data-eco-rerun` scripts from the incoming document.
99
- *
100
- * These scripts are re-executed after each navigation so their side-effects
101
- * (event listeners, DOM bootstraps) bind against the new page content.
102
- */
103
- private collectRerunScripts;
104
- /**
105
- * Removes head scripts that are no longer present in the incoming document.
106
- *
107
- * Persisted scripts and executable inline scripts with stable identifiers
108
- * are kept to avoid breaking long-lived runtime state.
109
- */
110
- private removeStaleHeadScripts;
111
- /**
112
- * Determines whether an inline head script should survive navigation.
113
- *
114
- * Only identified (`data-eco-script-id` or `id`), executable inline scripts
115
- * are persisted. External scripts and rerun scripts are never persisted here
116
- * because they have their own lifecycle management.
117
- */
118
- private shouldPersistExecutableInlineHeadScript;
119
- /**
120
- * Returns whether a script is non-executable (e.g. `type="application/json"`).
121
- *
122
- * Non-executable scripts are data carriers (JSON-LD, page data) that can be
123
- * safely replaced without side-effects, unlike executable scripts that would
124
- * re-run their bootstrap logic.
125
- */
126
- private isNonExecutableHeadScript;
127
- /**
128
- * Compares two head scripts for structural equality (key, content, attributes).
129
- *
130
- * Used to skip replacing non-executable data scripts when their content
131
- * has not changed between navigations.
132
- */
133
- private areHeadScriptsEquivalent;
134
- /**
135
- * Derives a stable identity key for a head script.
136
- *
137
- * Priority: `data-eco-script-id` / `id` > `src` > trimmed inline content.
138
- * Returns `null` for empty anonymous inline scripts that cannot be tracked.
139
- */
140
- private getHeadScriptKey;
141
- /**
142
- * Finds an existing head script that matches the given script's identity key.
143
- */
144
- private findExistingHeadScript;
145
- /**
146
- * Finds an existing rerun script in the given root by `data-eco-script-id` or
147
- * by matching `src` and `textContent`.
148
- */
149
- private findExistingRerunScript;
150
- /**
151
- * Returns whether a rerun script is an external ES module (`type="module"` with `src`).
152
- *
153
- * Module scripts are cached by URL, so re-execution requires cache-busting
154
- * via a query parameter nonce.
155
- */
156
- private isExternalModuleRerunScript;
157
- private getRegisteredRerunScript;
158
- /**
159
- * Appends a nonce query parameter to a script URL to bust the browser's
160
- * module cache and force re-execution on navigation.
161
- */
162
- private createRerunScriptUrl;
163
- /**
164
- * Manually attaches declarative shadow DOM templates.
165
- * Browsers only process `<template shadowrootmode>` during initial parse.
166
- */
167
- private processDeclarativeShadowDOM;
168
- }