@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
@@ -1,461 +1,355 @@
1
- import { getEcoNavigationRuntime } from "@ecopages/core/router/navigation-coordinator";
2
- import {
3
- getAnchorFromNavigationEvent,
4
- recoverPendingNavigationHref
5
- } from "@ecopages/core/router/link-intent";
6
- import { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS } from "./types.js";
7
- import { syncDocumentElementAttributes } from "./document-element-sync.js";
8
- import { DomSwapper, ScrollManager, ViewTransitionManager, PrefetchManager } from "./services/index.js";
9
- class EcoRouter {
10
- options;
11
- unregisterNavigationRuntime = null;
12
- started = false;
13
- pendingNavigations = 0;
14
- pendingPointerNavigation = null;
15
- queuedNavigationHref = null;
16
- domSwapper;
17
- scrollManager;
18
- viewTransitionManager;
19
- prefetchManager = null;
20
- constructor(options = {}) {
21
- this.options = {
22
- ...DEFAULT_OPTIONS,
23
- ...options,
24
- documentElementAttributesToSync: [
25
- ...options.documentElementAttributesToSync ?? DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC
26
- ]
27
- };
28
- this.domSwapper = new DomSwapper(this.options.persistAttribute);
29
- this.scrollManager = new ScrollManager(this.options.scrollBehavior, this.options.smoothScroll);
30
- this.viewTransitionManager = new ViewTransitionManager(this.options.viewTransitions);
31
- if (this.options.prefetch !== false) {
32
- this.prefetchManager = new PrefetchManager({
33
- ...this.options.prefetch,
34
- linkSelector: this.options.linkSelector
35
- });
36
- }
37
- this.handleClick = this.handleClick.bind(this);
38
- this.handlePointerDown = this.handlePointerDown.bind(this);
39
- this.handlePopState = this.handlePopState.bind(this);
40
- }
41
- getLinkFromEvent(event) {
42
- return getAnchorFromNavigationEvent(event, this.options.linkSelector);
43
- }
44
- canInterceptLink(event, link) {
45
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return null;
46
- if (event.button !== 0) return null;
47
- const target = link.getAttribute("target");
48
- if (target && target !== "_self") return null;
49
- if (link.hasAttribute(this.options.reloadAttribute)) return null;
50
- if (link.hasAttribute("download")) return null;
51
- const href = link.getAttribute("href");
52
- if (!href) return null;
53
- if (href.startsWith("#")) return null;
54
- if (href.startsWith("javascript:")) return null;
55
- const url = new URL(href, window.location.origin);
56
- if (!this.isSameOrigin(url)) return null;
57
- if (url.hash && url.pathname === window.location.pathname && url.search === window.location.search) {
58
- return null;
59
- }
60
- return href;
61
- }
62
- getRecoveredPointerHref() {
63
- const href = recoverPendingNavigationHref(
64
- this.pendingPointerNavigation,
65
- this.pendingNavigations > 0,
66
- performance.now()
67
- );
68
- if (!href) {
69
- this.pendingPointerNavigation = null;
70
- }
71
- return href;
72
- }
73
- isAnotherNavigationRuntimeActive() {
74
- const ownerState = getEcoNavigationRuntime(window).getOwnerState();
75
- return ownerState.owner !== "none" && ownerState.owner !== "browser-router" && ownerState.canHandleSpaNavigation;
76
- }
77
- getDocumentOwner(doc) {
78
- return getEcoNavigationRuntime(window).resolveDocumentOwner(doc, "browser-router");
79
- }
80
- adoptDocumentOwner(doc) {
81
- getEcoNavigationRuntime(window).adoptDocumentOwner(doc, "browser-router");
82
- }
83
- syncDocumentElementAttributes(newDocument) {
84
- syncDocumentElementAttributes(document, newDocument, this.options.documentElementAttributesToSync);
85
- }
86
- reloadDocument(url) {
87
- window.location.assign(url.href);
88
- }
89
- /**
90
- * Commits a fully fetched document into the live page.
91
- *
92
- * When browser-router accepts a handoff from another runtime, it delays source
93
- * runtime cleanup until the incoming document has been prepared and is ready to
94
- * commit. That ordering avoids the blank-page window we previously hit when a
95
- * delegated navigation went stale after the source runtime had already torn
96
- * itself down.
97
- */
98
- async commitDocumentNavigation(url, direction, newDocument, options = {}) {
99
- const previousUrl = new URL(window.location.href);
100
- const navigationRuntime = getEcoNavigationRuntime(window);
101
- const isStaleNavigation = options.isStaleNavigation ?? (() => false);
102
- const currentDocumentOwner = navigationRuntime.resolveDocumentOwner(document, "browser-router");
103
- const newDocumentOwner = navigationRuntime.resolveDocumentOwner(newDocument, "browser-router");
104
- const activeOwner = navigationRuntime.getOwnerState().owner;
105
- const shouldCleanupCurrentOwner = currentDocumentOwner !== newDocumentOwner && currentDocumentOwner !== "browser-router" && activeOwner === currentDocumentOwner;
106
- let shouldReload = false;
107
- const beforeSwapEvent = {
108
- url,
109
- direction,
110
- newDocument,
111
- reload: () => {
112
- shouldReload = true;
113
- }
114
- };
115
- document.dispatchEvent(new CustomEvent("eco:before-swap", { detail: beforeSwapEvent }));
116
- if (isStaleNavigation()) return;
117
- if (shouldReload) {
118
- if (shouldCleanupCurrentOwner) {
119
- await navigationRuntime.cleanupOwner(currentDocumentOwner);
120
- }
121
- if (isStaleNavigation()) return;
122
- this.reloadDocument(url);
123
- return;
124
- }
125
- const useViewTransitions = this.options.viewTransitions;
126
- await this.domSwapper.preloadStylesheets(newDocument);
127
- if (isStaleNavigation()) return;
128
- if (shouldCleanupCurrentOwner) {
129
- await navigationRuntime.cleanupOwner(currentDocumentOwner);
130
- }
131
- if (isStaleNavigation()) return;
132
- const commitSwap = () => {
133
- if (isStaleNavigation()) return;
134
- if (this.options.updateHistory && direction === "forward") {
135
- window.history.pushState({}, "", url.href);
136
- } else if (direction === "replace") {
137
- window.history.replaceState({}, "", url.href);
138
- }
139
- this.syncDocumentElementAttributes(newDocument);
140
- this.domSwapper.morphHead(newDocument);
141
- if (useViewTransitions && !this.domSwapper.shouldReplaceBodyForRerunScripts()) {
142
- this.domSwapper.morphBody(newDocument);
143
- } else {
144
- this.domSwapper.replaceBody(newDocument);
145
- }
146
- this.domSwapper.flushRerunScripts();
147
- this.scrollManager.handleScroll(url, previousUrl);
148
- };
149
- if (useViewTransitions) {
150
- await this.viewTransitionManager.transition(commitSwap);
151
- } else {
152
- commitSwap();
1
+ /**
2
+ * Client-side router for Ecopages with morphdom-based DOM diffing.
3
+ * @module eco-router
4
+ */
5
+ import { getEcoNavigationRuntime } from '@ecopages/core/router/navigation-coordinator';
6
+ import { getAnchorFromNavigationEvent, isStaticAssetHref, recoverPendingNavigationHref, } from '@ecopages/core/router/link-intent';
7
+ import { getNavigableHrefFromClick } from '@ecopages/core/router/link-navigation-policy';
8
+ import { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS } from './types.js';
9
+ import { DomSwapper } from './dom/dom-swapper.js';
10
+ import { PrefetchManager } from './services/prefetch-manager.js';
11
+ import { ViewTransitionManager } from './services/view-transition-manager.js';
12
+ import { NavigationCommit } from './navigation-commit.js';
13
+ import { fetchNavigationPage } from './navigation-fetch.js';
14
+ /**
15
+ * Intercepts same-origin link clicks and performs client-side navigation
16
+ * using morphdom for efficient DOM diffing. Supports View Transitions API.
17
+ */
18
+ export class EcoRouter {
19
+ options;
20
+ unregisterNavigationRuntime = null;
21
+ started = false;
22
+ pendingNavigations = 0;
23
+ pendingPointerNavigation = null;
24
+ queuedNavigationHref = null;
25
+ domSwapper;
26
+ viewTransitionManager;
27
+ prefetchManager = null;
28
+ navigationCommit;
29
+ constructor(options = {}) {
30
+ this.options = {
31
+ ...DEFAULT_OPTIONS,
32
+ ...options,
33
+ documentElementAttributesToSync: [
34
+ ...(options.documentElementAttributesToSync ?? DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC),
35
+ ],
36
+ };
37
+ this.domSwapper = new DomSwapper(this.options.persistAttribute);
38
+ this.viewTransitionManager = new ViewTransitionManager(this.options.viewTransitions);
39
+ if (this.options.prefetch !== false) {
40
+ this.prefetchManager = new PrefetchManager({
41
+ ...this.options.prefetch,
42
+ linkSelector: this.options.linkSelector,
43
+ });
44
+ }
45
+ this.handleClick = this.handleClick.bind(this);
46
+ this.handlePointerDown = this.handlePointerDown.bind(this);
47
+ this.handlePopState = this.handlePopState.bind(this);
48
+ this.navigationCommit = new NavigationCommit(this.domSwapper, this.viewTransitionManager, this.prefetchManager, this.options);
153
49
  }
154
- if (isStaleNavigation()) return;
155
- navigationRuntime.adoptDocumentOwner(newDocument, "browser-router");
156
- const afterSwapEvent = {
157
- url,
158
- direction
159
- };
160
- document.dispatchEvent(new CustomEvent("eco:after-swap", { detail: afterSwapEvent }));
161
- this.prefetchManager?.observeNewLinks();
162
- if (options.html) {
163
- this.prefetchManager?.cacheVisitedPage(url.href, options.html);
50
+ getRecoveredPointerHref() {
51
+ const href = recoverPendingNavigationHref(this.pendingPointerNavigation, this.pendingNavigations > 0, performance.now());
52
+ if (!href) {
53
+ this.pendingPointerNavigation = null;
54
+ }
55
+ return href;
164
56
  }
165
- requestAnimationFrame(() => {
166
- if (isStaleNavigation()) return;
167
- document.dispatchEvent(
168
- new CustomEvent("eco:page-load", {
169
- detail: { url, direction }
170
- })
171
- );
172
- });
173
- }
174
- /**
175
- * Starts the router and begins intercepting navigation.
176
- *
177
- * Attaches click handlers for links and popstate handlers for browser
178
- * back/forward buttons. Also starts the prefetch manager if configured.
179
- */
180
- start() {
181
- if (this.started) {
182
- return;
57
+ isAnotherNavigationRuntimeActive() {
58
+ const ownerState = getEcoNavigationRuntime(window).getOwnerState();
59
+ return (ownerState.owner !== 'none' && ownerState.owner !== 'browser-router' && ownerState.canHandleSpaNavigation);
183
60
  }
184
- const navigationRuntime = getEcoNavigationRuntime(window);
185
- navigationRuntime.cancelCurrentNavigationTransaction();
186
- this.pendingNavigations = 0;
187
- this.queuedNavigationHref = null;
188
- this.pendingPointerNavigation = null;
189
- document.addEventListener("pointerdown", this.handlePointerDown, true);
190
- document.addEventListener("click", this.handleClick, true);
191
- window.addEventListener("popstate", this.handlePopState);
192
- this.prefetchManager?.start();
193
- this.unregisterNavigationRuntime?.();
194
- this.unregisterNavigationRuntime = navigationRuntime.register({
195
- owner: "browser-router",
196
- navigate: async (request) => {
197
- await this.performNavigation(
198
- new URL(request.href, window.location.origin),
199
- request.direction ?? "forward"
200
- );
201
- return true;
202
- },
203
- handoffNavigation: async (request) => {
204
- const { isStaleNavigation, complete } = this.beginNavigationTransaction();
205
- if (isStaleNavigation()) return true;
206
- try {
207
- await this.commitDocumentNavigation(
208
- new URL(request.finalHref ?? request.href, window.location.origin),
209
- request.direction ?? "forward",
210
- request.document,
211
- { html: request.html, isStaleNavigation }
212
- );
213
- } finally {
214
- complete();
61
+ /**
62
+ * Starts the router and begins intercepting navigation.
63
+ *
64
+ * Attaches click handlers for links and popstate handlers for browser
65
+ * back/forward buttons. Also starts the prefetch manager if configured.
66
+ */
67
+ start() {
68
+ if (this.started) {
69
+ return;
215
70
  }
216
- return true;
217
- },
218
- reloadCurrentPage: async (request) => {
219
- if (this.pendingNavigations > 0) return;
220
- const currentUrl = window.location.pathname + window.location.search;
221
- if (request?.clearCache) {
222
- this.prefetchManager?.invalidate(currentUrl);
71
+ const navigationRuntime = getEcoNavigationRuntime(window);
72
+ navigationRuntime.cancelCurrentNavigationTransaction();
73
+ this.pendingNavigations = 0;
74
+ this.queuedNavigationHref = null;
75
+ this.pendingPointerNavigation = null;
76
+ document.addEventListener('pointerdown', this.handlePointerDown, true);
77
+ document.addEventListener('click', this.handleClick, true);
78
+ window.addEventListener('popstate', this.handlePopState);
79
+ this.prefetchManager?.start();
80
+ this.unregisterNavigationRuntime?.();
81
+ this.unregisterNavigationRuntime = navigationRuntime.register({
82
+ owner: 'browser-router',
83
+ navigate: async (request) => {
84
+ await this.performNavigation(new URL(request.href, window.location.origin), request.direction ?? 'forward');
85
+ return true;
86
+ },
87
+ handoffNavigation: async (request) => {
88
+ const { isStaleNavigation, complete } = this.beginNavigationTransaction();
89
+ if (isStaleNavigation())
90
+ return true;
91
+ try {
92
+ await this.navigationCommit.commit(new URL(request.finalHref ?? request.href, window.location.origin), request.direction ?? 'forward', request.document, { html: request.html, isStaleNavigation });
93
+ }
94
+ finally {
95
+ complete();
96
+ }
97
+ return true;
98
+ },
99
+ reloadCurrentPage: async (request) => {
100
+ if (this.pendingNavigations > 0) {
101
+ return false;
102
+ }
103
+ const currentUrl = window.location.pathname + window.location.search;
104
+ if (request?.clearCache) {
105
+ this.prefetchManager?.invalidate(currentUrl);
106
+ }
107
+ return await this.performNavigation(new URL(currentUrl, window.location.origin), 'replace', {
108
+ bypassPrefetchCache: !!request?.clearCache,
109
+ allowFullDocumentFallback: false,
110
+ });
111
+ },
112
+ cleanupBeforeHandoff: async () => {
113
+ this.cancelNavigationTransaction();
114
+ },
115
+ });
116
+ getEcoNavigationRuntime(window).adoptDocumentOwner(document, 'browser-router');
117
+ // Cache the initial page for instant back-navigation
118
+ const initialHtml = document.documentElement.outerHTML;
119
+ this.prefetchManager?.cacheVisitedPage(window.location.href, initialHtml);
120
+ this.started = true;
121
+ }
122
+ /**
123
+ * Stops the router and cleans up all event listeners.
124
+ * After calling this, navigation will fall back to full page reloads.
125
+ */
126
+ stop() {
127
+ if (!this.started) {
128
+ return;
223
129
  }
224
- await this.performNavigation(new URL(currentUrl, window.location.origin), "replace");
225
- },
226
- cleanupBeforeHandoff: async () => {
227
130
  this.cancelNavigationTransaction();
228
- }
229
- });
230
- this.adoptDocumentOwner(document);
231
- const initialHtml = document.documentElement.outerHTML;
232
- this.prefetchManager?.cacheVisitedPage(window.location.href, initialHtml);
233
- this.started = true;
234
- }
235
- /**
236
- * Stops the router and cleans up all event listeners.
237
- * After calling this, navigation will fall back to full page reloads.
238
- */
239
- stop() {
240
- if (!this.started) {
241
- return;
131
+ document.removeEventListener('pointerdown', this.handlePointerDown, true);
132
+ document.removeEventListener('click', this.handleClick, true);
133
+ window.removeEventListener('popstate', this.handlePopState);
134
+ this.prefetchManager?.stop();
135
+ this.unregisterNavigationRuntime?.();
136
+ this.unregisterNavigationRuntime = null;
137
+ this.started = false;
138
+ this.pendingPointerNavigation = null;
139
+ this.queuedNavigationHref = null;
140
+ const win = window;
141
+ if (win[ACTIVE_ROUTER_KEY] === this) {
142
+ delete win[ACTIVE_ROUTER_KEY];
143
+ }
242
144
  }
243
- this.cancelNavigationTransaction();
244
- document.removeEventListener("pointerdown", this.handlePointerDown, true);
245
- document.removeEventListener("click", this.handleClick, true);
246
- window.removeEventListener("popstate", this.handlePopState);
247
- this.prefetchManager?.stop();
248
- this.unregisterNavigationRuntime?.();
249
- this.unregisterNavigationRuntime = null;
250
- this.started = false;
251
- this.pendingPointerNavigation = null;
252
- this.queuedNavigationHref = null;
253
- const win = window;
254
- if (win[ACTIVE_ROUTER_KEY] === this) {
255
- delete win[ACTIVE_ROUTER_KEY];
145
+ /**
146
+ * Programmatic navigation.
147
+ * Falls back to full page reload for cross-origin URLs.
148
+ * @param href - The URL to navigate to
149
+ * @param options - Navigation options
150
+ * @param options.replace - If true, replaces the current history entry instead of pushing
151
+ */
152
+ async navigate(href, options = {}) {
153
+ const url = new URL(href, window.location.origin);
154
+ if (url.origin !== window.location.origin) {
155
+ window.location.href = href;
156
+ return;
157
+ }
158
+ if (isStaticAssetHref(href)) {
159
+ window.location.assign(url.href);
160
+ return;
161
+ }
162
+ await this.performNavigation(url, options.replace ? 'replace' : 'forward');
256
163
  }
257
- }
258
- /**
259
- * Programmatic navigation.
260
- * Falls back to full page reload for cross-origin URLs.
261
- * @param href - The URL to navigate to
262
- * @param options - Navigation options
263
- * @param options.replace - If true, replaces the current history entry instead of pushing
264
- */
265
- async navigate(href, options = {}) {
266
- const url = new URL(href, window.location.origin);
267
- if (!this.isSameOrigin(url)) {
268
- window.location.href = href;
269
- return;
164
+ /**
165
+ * Manually prefetch a URL.
166
+ * @param href - The URL to prefetch
167
+ */
168
+ async prefetch(href) {
169
+ if (!this.prefetchManager) {
170
+ console.warn('[ecopages] Prefetching is disabled. Enable it in router options.');
171
+ return;
172
+ }
173
+ return this.prefetchManager.prefetch(href);
270
174
  }
271
- await this.performNavigation(url, options.replace ? "replace" : "forward");
272
- }
273
- /**
274
- * Manually prefetch a URL.
275
- * @param href - The URL to prefetch
276
- */
277
- async prefetch(href) {
278
- if (!this.prefetchManager) {
279
- console.warn("[ecopages] Prefetching is disabled. Enable it in router options.");
280
- return;
175
+ /**
176
+ * Intercepts link clicks for client-side navigation.
177
+ *
178
+ * Filters out clicks with modifier keys (opens new tab), non-left clicks,
179
+ * external links, download links, and links with the reload attribute.
180
+ *
181
+ * Uses `event.composedPath()` to correctly detect clicks on anchors inside
182
+ * Shadow DOM boundaries (Web Components).
183
+ */
184
+ handlePointerDown(event) {
185
+ const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
186
+ if (!link) {
187
+ this.pendingPointerNavigation = null;
188
+ return;
189
+ }
190
+ const href = getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute });
191
+ this.pendingPointerNavigation = href
192
+ ? {
193
+ href,
194
+ timestamp: performance.now(),
195
+ }
196
+ : null;
197
+ if (href && this.pendingNavigations > 0) {
198
+ this.queuedNavigationHref = href;
199
+ }
281
200
  }
282
- return this.prefetchManager.prefetch(href);
283
- }
284
- /**
285
- * Intercepts link clicks for client-side navigation.
286
- *
287
- * Filters out clicks with modifier keys (opens new tab), non-left clicks,
288
- * external links, download links, and links with the reload attribute.
289
- *
290
- * Uses `event.composedPath()` to correctly detect clicks on anchors inside
291
- * Shadow DOM boundaries (Web Components).
292
- */
293
- handlePointerDown(event) {
294
- const link = this.getLinkFromEvent(event);
295
- if (!link) {
296
- this.pendingPointerNavigation = null;
297
- return;
201
+ handleClick(event) {
202
+ const navigationRuntime = getEcoNavigationRuntime(window);
203
+ const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
204
+ const href = link
205
+ ? getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute })
206
+ : this.getRecoveredPointerHref();
207
+ this.pendingPointerNavigation = null;
208
+ if (!href)
209
+ return;
210
+ this.queuedNavigationHref = null;
211
+ if (this.isAnotherNavigationRuntimeActive()) {
212
+ event.preventDefault();
213
+ event.stopImmediatePropagation();
214
+ void navigationRuntime.requestNavigation({
215
+ href,
216
+ direction: 'forward',
217
+ source: 'browser-router',
218
+ });
219
+ return;
220
+ }
221
+ const url = new URL(href, window.location.origin);
222
+ event.preventDefault();
223
+ if (this.pendingNavigations > 0) {
224
+ this.queuedNavigationHref = href;
225
+ this.cancelNavigationTransaction();
226
+ return;
227
+ }
228
+ this.performNavigation(url, 'forward');
298
229
  }
299
- const href = this.canInterceptLink(event, link);
300
- this.pendingPointerNavigation = href ? {
301
- href,
302
- timestamp: performance.now()
303
- } : null;
304
- if (href && this.pendingNavigations > 0) {
305
- this.queuedNavigationHref = href;
230
+ /**
231
+ * Handles browser back/forward navigation.
232
+ * Triggered by the History API's popstate event.
233
+ */
234
+ handlePopState(_event) {
235
+ if (this.isAnotherNavigationRuntimeActive())
236
+ return;
237
+ const url = new URL(window.location.href);
238
+ this.performNavigation(url, 'back');
306
239
  }
307
- }
308
- handleClick(event) {
309
- const navigationRuntime = getEcoNavigationRuntime(window);
310
- const link = this.getLinkFromEvent(event);
311
- const href = link ? this.canInterceptLink(event, link) : this.getRecoveredPointerHref();
312
- this.pendingPointerNavigation = null;
313
- if (!href) return;
314
- this.queuedNavigationHref = null;
315
- if (this.isAnotherNavigationRuntimeActive()) {
316
- event.preventDefault();
317
- event.stopImmediatePropagation();
318
- void navigationRuntime.requestNavigation({
319
- href,
320
- direction: "forward",
321
- source: "browser-router"
322
- });
323
- return;
240
+ cancelNavigationTransaction() {
241
+ getEcoNavigationRuntime(window).cancelCurrentNavigationTransaction();
324
242
  }
325
- const url = new URL(href, window.location.origin);
326
- event.preventDefault();
327
- if (this.pendingNavigations > 0) {
328
- this.queuedNavigationHref = href;
329
- this.cancelNavigationTransaction();
330
- return;
243
+ beginNavigationTransaction() {
244
+ const transaction = getEcoNavigationRuntime(window).beginNavigationTransaction();
245
+ return {
246
+ isStaleNavigation: () => !transaction.isCurrent(),
247
+ signal: transaction.signal,
248
+ complete: () => transaction.complete(),
249
+ };
331
250
  }
332
- this.performNavigation(url, "forward");
333
- }
334
- /**
335
- * Handles browser back/forward navigation.
336
- * Triggered by the History API's popstate event.
337
- */
338
- handlePopState(_event) {
339
- if (this.isAnotherNavigationRuntimeActive()) return;
340
- const url = new URL(window.location.href);
341
- this.performNavigation(url, "back");
342
- }
343
- /**
344
- * Checks if a URL shares the same origin as the current page.
345
- * Cross-origin navigation always falls back to full page reload.
346
- */
347
- isSameOrigin(url) {
348
- return url.origin === window.location.origin;
349
- }
350
- cancelNavigationTransaction() {
351
- getEcoNavigationRuntime(window).cancelCurrentNavigationTransaction();
352
- }
353
- beginNavigationTransaction() {
354
- const transaction = getEcoNavigationRuntime(window).beginNavigationTransaction();
355
- return {
356
- isStaleNavigation: () => !transaction.isCurrent(),
357
- signal: transaction.signal,
358
- complete: () => transaction.complete()
359
- };
360
- }
361
- /**
362
- * Executes the core navigation flow.
363
- *
364
- * Orchestrates fetching, DOM swapping, and lifecycle events:
365
- *
366
- * 1. **Fetch** - Retrieves HTML (from cache or network)
367
- * 2. **eco:before-swap** - Allows listeners to force a full reload
368
- * 3. **History update** - Updates URL before DOM swap so Web Components
369
- * see the correct URL in their `connectedCallback`
370
- * 4. **Stylesheet preload** - Prevents FOUC by loading styles first
371
- * 5. **DOM swap** - Morphs head/body, optionally with View Transition
372
- * 6. **Lifecycle events** - Dispatches `eco:after-swap` and `eco:page-load`
373
- *
374
- * Falls back to full page reload on network errors.
375
- *
376
- * @param url - The target URL to navigate to
377
- * @param direction - Navigation direction ('forward', 'back', or 'replace')
378
- */
379
- async performNavigation(url, direction) {
380
- this.pendingNavigations++;
381
- const { isStaleNavigation, signal, complete } = this.beginNavigationTransaction();
382
- let queuedNavigationHref = null;
383
- try {
384
- const html = await this.fetchPage(url, signal);
385
- if (isStaleNavigation()) return;
386
- const newDocument = this.domSwapper.parseHTML(html, url);
387
- if (isStaleNavigation()) return;
388
- await this.commitDocumentNavigation(url, direction, newDocument, {
389
- html,
390
- isStaleNavigation
391
- });
392
- } catch (error) {
393
- if (isStaleNavigation()) return;
394
- if (error instanceof Error && error.name === "AbortError") {
395
- return;
396
- }
397
- console.error("[ecopages] Navigation failed:", error);
398
- window.location.href = url.href;
399
- } finally {
400
- complete();
401
- this.pendingNavigations--;
402
- const navigationRuntime = getEcoNavigationRuntime(window);
403
- if (!navigationRuntime.hasPendingNavigationTransaction()) {
404
- queuedNavigationHref = this.queuedNavigationHref;
405
- this.queuedNavigationHref = null;
406
- }
407
- if (queuedNavigationHref && queuedNavigationHref !== window.location.pathname + window.location.search) {
408
- const ownerState = navigationRuntime.getOwnerState();
409
- if (ownerState.owner !== "none" && ownerState.owner !== "browser-router" && ownerState.canHandleSpaNavigation) {
410
- void navigationRuntime.requestNavigation({
411
- href: queuedNavigationHref,
412
- direction: "forward",
413
- source: "browser-router"
414
- });
415
- } else {
416
- void this.performNavigation(new URL(queuedNavigationHref, window.location.origin), "forward");
251
+ /**
252
+ * Executes the core navigation flow.
253
+ *
254
+ * Orchestrates fetching, DOM swapping, and lifecycle events:
255
+ *
256
+ * 1. **Fetch** - Retrieves HTML (from cache or network)
257
+ * 2. **eco:before-swap** - Allows listeners to force a full reload
258
+ * 3. **History update** - Updates URL before DOM swap so Web Components
259
+ * see the correct URL in their `connectedCallback`
260
+ * 4. **Stylesheet preload** - Prevents FOUC by loading styles first
261
+ * 5. **DOM swap** - Morphs head/body, optionally with View Transition
262
+ * 6. **Lifecycle events** - Dispatches `eco:after-swap` and `eco:page-load`
263
+ *
264
+ * Falls back to full page reload on network errors.
265
+ *
266
+ * @param url - The target URL to navigate to
267
+ * @param direction - Navigation direction ('forward', 'back', or 'replace')
268
+ */
269
+ async performNavigation(url, direction, options = {}) {
270
+ const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
271
+ this.pendingNavigations++;
272
+ const { isStaleNavigation, signal, complete } = this.beginNavigationTransaction();
273
+ let queuedNavigationHref = null;
274
+ let committed = false;
275
+ try {
276
+ const html = await fetchNavigationPage(url, signal, {
277
+ bypassCache: options.bypassPrefetchCache,
278
+ getCachedHtml: this.prefetchManager ? (href) => this.prefetchManager.getCachedHtml(href) : undefined,
279
+ });
280
+ if (isStaleNavigation()) {
281
+ return false;
282
+ }
283
+ const newDocument = this.domSwapper.parseHTML(html, url);
284
+ if (isStaleNavigation()) {
285
+ return false;
286
+ }
287
+ committed = await this.navigationCommit.commit(url, direction, newDocument, {
288
+ html,
289
+ isStaleNavigation,
290
+ allowFullDocumentFallback,
291
+ });
292
+ return committed;
293
+ }
294
+ catch (error) {
295
+ if (isStaleNavigation()) {
296
+ return false;
297
+ }
298
+ if (error instanceof Error && error.name === 'AbortError') {
299
+ return false;
300
+ }
301
+ console.error('[ecopages] Navigation failed:', error);
302
+ if (allowFullDocumentFallback) {
303
+ window.location.href = url.href;
304
+ }
305
+ return false;
306
+ }
307
+ finally {
308
+ complete();
309
+ this.pendingNavigations--;
310
+ const navigationRuntime = getEcoNavigationRuntime(window);
311
+ if (!navigationRuntime.hasPendingNavigationTransaction()) {
312
+ queuedNavigationHref = this.queuedNavigationHref;
313
+ this.queuedNavigationHref = null;
314
+ }
315
+ if (queuedNavigationHref && queuedNavigationHref !== window.location.pathname + window.location.search) {
316
+ const ownerState = navigationRuntime.getOwnerState();
317
+ if (ownerState.owner !== 'none' &&
318
+ ownerState.owner !== 'browser-router' &&
319
+ ownerState.canHandleSpaNavigation) {
320
+ void navigationRuntime.requestNavigation({
321
+ href: queuedNavigationHref,
322
+ direction: 'forward',
323
+ source: 'browser-router',
324
+ });
325
+ }
326
+ else {
327
+ void this.performNavigation(new URL(queuedNavigationHref, window.location.origin), 'forward');
328
+ }
329
+ }
417
330
  }
418
- }
419
- }
420
- }
421
- /**
422
- * Fetches the HTML content of a page.
423
- * @param url - The URL to fetch
424
- * @param signal - AbortSignal for cancelling the request
425
- * @throws Error if the response is not ok
426
- */
427
- async fetchPage(url, signal) {
428
- if (this.prefetchManager) {
429
- const cachedHtml = this.prefetchManager.getCachedHtml(url.href);
430
- if (cachedHtml) {
431
- return cachedHtml;
432
- }
433
- }
434
- const response = await fetch(url.href, {
435
- signal,
436
- headers: {
437
- Accept: "text/html"
438
- }
439
- });
440
- if (!response.ok) {
441
- throw new Error(`Failed to fetch page: ${response.status}`);
442
331
  }
443
- return response.text();
444
- }
445
332
  }
446
- const ACTIVE_ROUTER_KEY = "__ecopages_browser_router__";
447
- function createRouter(options) {
448
- const win = window;
449
- const existingRouter = win[ACTIVE_ROUTER_KEY];
450
- if (existingRouter) {
451
- return existingRouter;
452
- }
453
- const router = new EcoRouter(options);
454
- win[ACTIVE_ROUTER_KEY] = router;
455
- router.start();
456
- return router;
333
+ const ACTIVE_ROUTER_KEY = '__ecopages_browser_router__';
334
+ /**
335
+ * Creates and starts a router instance.
336
+ *
337
+ * Stops the previously active router (if any) before creating a new one so
338
+ * click listeners and coordinator registrations from earlier instances are
339
+ * cleaned up on re-execution (e.g. when the layout script is re-run via
340
+ * `data-eco-rerun` after a browser-router page commit).
341
+ *
342
+ * @param options - Configuration options for the router
343
+ * @returns A started EcoRouter instance
344
+ */
345
+ export function createRouter(options) {
346
+ const win = window;
347
+ const existingRouter = win[ACTIVE_ROUTER_KEY];
348
+ if (existingRouter) {
349
+ return existingRouter;
350
+ }
351
+ const router = new EcoRouter(options);
352
+ win[ACTIVE_ROUTER_KEY] = router;
353
+ router.start();
354
+ return router;
457
355
  }
458
- export {
459
- EcoRouter,
460
- createRouter
461
- };