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