@ecopages/browser-router 0.2.0-beta.2 → 0.2.0-beta.21

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 +8 -2
  2. package/package.json +7 -7
  3. package/src/client/document-element-sync.d.ts +0 -7
  4. package/src/client/document-element-sync.js +0 -3
  5. package/src/client/dom/body-morpher.d.ts +24 -0
  6. package/src/client/dom/body-morpher.js +103 -0
  7. package/src/client/dom/dom-swapper.d.ts +30 -0
  8. package/src/client/dom/dom-swapper.js +51 -0
  9. package/src/client/dom/head-updater.d.ts +42 -0
  10. package/src/client/dom/head-updater.js +173 -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 +20 -0
  15. package/src/client/dom/stylesheet-preloader.d.ts +10 -0
  16. package/src/client/dom/stylesheet-preloader.js +38 -0
  17. package/src/client/eco-router.d.ts +1 -33
  18. package/src/client/eco-router.js +61 -211
  19. package/src/client/index.d.ts +3 -0
  20. package/src/client/index.js +13 -0
  21. package/src/client/navigation-commit.d.ts +21 -0
  22. package/src/client/navigation-commit.js +114 -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 +29 -47
  27. package/src/client/services/view-transition-manager.js +1 -1
  28. package/src/client/types.d.ts +6 -0
  29. package/src/index.d.ts +3 -5
  30. package/src/index.js +7 -7
  31. package/src/client/services/dom-swapper.d.ts +0 -168
  32. package/src/client/services/dom-swapper.js +0 -529
  33. package/src/client/services/index.d.ts +0 -8
  34. package/src/client/services/index.js +0 -10
  35. package/src/client/services/scroll-manager.d.ts +0 -19
  36. package/src/client/services/scroll-manager.js +0 -36
  37. package/src/client/view-transition-utils.d.ts +0 -14
  38. package/src/client/view-transition-utils.js +0 -60
  39. package/src/types.d.ts +0 -15
  40. package/src/types.js +0 -5
@@ -13,32 +13,14 @@ 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
18
  private viewTransitionManager;
21
19
  private prefetchManager;
20
+ private readonly navigationCommit;
22
21
  constructor(options?: EcoRouterOptions);
23
- private getLinkFromEvent;
24
- private canInterceptLink;
25
22
  private getRecoveredPointerHref;
26
- private getRecoveredHoverHref;
27
23
  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
24
  /**
43
25
  * Starts the router and begins intercepting navigation.
44
26
  *
@@ -76,18 +58,12 @@ export declare class EcoRouter {
76
58
  * Shadow DOM boundaries (Web Components).
77
59
  */
78
60
  private handlePointerDown;
79
- private handleHoverIntent;
80
61
  private handleClick;
81
62
  /**
82
63
  * Handles browser back/forward navigation.
83
64
  * Triggered by the History API's popstate event.
84
65
  */
85
66
  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
67
  private cancelNavigationTransaction;
92
68
  private beginNavigationTransaction;
93
69
  /**
@@ -109,13 +85,6 @@ export declare class EcoRouter {
109
85
  * @param direction - Navigation direction ('forward', 'back', or 'replace')
110
86
  */
111
87
  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
88
  }
120
89
  /**
121
90
  * Creates and starts a router instance.
@@ -129,4 +98,3 @@ export declare class EcoRouter {
129
98
  * @returns A started EcoRouter instance
130
99
  */
131
100
  export declare function createRouter(options?: EcoRouterOptions): EcoRouter;
132
- export type { EcoRouterOptions, EcoNavigationEvent, EcoBeforeSwapEvent, EcoAfterSwapEvent } from './types';
@@ -1,23 +1,27 @@
1
1
  import { getEcoNavigationRuntime } from "@ecopages/core/router/navigation-coordinator";
2
2
  import {
3
3
  getAnchorFromNavigationEvent,
4
+ isStaticAssetHref,
4
5
  recoverPendingNavigationHref
5
6
  } from "@ecopages/core/router/link-intent";
7
+ import { getNavigableHrefFromClick } from "@ecopages/core/router/link-navigation-policy";
6
8
  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
+ 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";
9
14
  class EcoRouter {
10
15
  options;
11
16
  unregisterNavigationRuntime = null;
12
17
  started = false;
13
18
  pendingNavigations = 0;
14
19
  pendingPointerNavigation = null;
15
- pendingHoverNavigation = null;
16
20
  queuedNavigationHref = null;
17
21
  domSwapper;
18
- scrollManager;
19
22
  viewTransitionManager;
20
23
  prefetchManager = null;
24
+ navigationCommit;
21
25
  constructor(options = {}) {
22
26
  this.options = {
23
27
  ...DEFAULT_OPTIONS,
@@ -27,7 +31,6 @@ class EcoRouter {
27
31
  ]
28
32
  };
29
33
  this.domSwapper = new DomSwapper(this.options.persistAttribute);
30
- this.scrollManager = new ScrollManager(this.options.scrollBehavior, this.options.smoothScroll);
31
34
  this.viewTransitionManager = new ViewTransitionManager(this.options.viewTransitions);
32
35
  if (this.options.prefetch !== false) {
33
36
  this.prefetchManager = new PrefetchManager({
@@ -36,30 +39,14 @@ class EcoRouter {
36
39
  });
37
40
  }
38
41
  this.handleClick = this.handleClick.bind(this);
39
- this.handleHoverIntent = this.handleHoverIntent.bind(this);
40
42
  this.handlePointerDown = this.handlePointerDown.bind(this);
41
43
  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;
44
+ this.navigationCommit = new NavigationCommit(
45
+ this.domSwapper,
46
+ this.viewTransitionManager,
47
+ this.prefetchManager,
48
+ this.options
49
+ );
63
50
  }
64
51
  getRecoveredPointerHref() {
65
52
  const href = recoverPendingNavigationHref(
@@ -72,118 +59,10 @@ class EcoRouter {
72
59
  }
73
60
  return href;
74
61
  }
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
62
  isAnotherNavigationRuntimeActive() {
87
63
  const ownerState = getEcoNavigationRuntime(window).getOwnerState();
88
64
  return ownerState.owner !== "none" && ownerState.owner !== "browser-router" && ownerState.canHandleSpaNavigation;
89
65
  }
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();
166
- }
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);
177
- }
178
- requestAnimationFrame(() => {
179
- if (isStaleNavigation()) return;
180
- document.dispatchEvent(
181
- new CustomEvent("eco:page-load", {
182
- detail: { url, direction }
183
- })
184
- );
185
- });
186
- }
187
66
  /**
188
67
  * Starts the router and begins intercepting navigation.
189
68
  *
@@ -195,10 +74,10 @@ class EcoRouter {
195
74
  return;
196
75
  }
197
76
  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);
77
+ navigationRuntime.cancelCurrentNavigationTransaction();
78
+ this.pendingNavigations = 0;
79
+ this.queuedNavigationHref = null;
80
+ this.pendingPointerNavigation = null;
202
81
  document.addEventListener("pointerdown", this.handlePointerDown, true);
203
82
  document.addEventListener("click", this.handleClick, true);
204
83
  window.addEventListener("popstate", this.handlePopState);
@@ -217,7 +96,7 @@ class EcoRouter {
217
96
  const { isStaleNavigation, complete } = this.beginNavigationTransaction();
218
97
  if (isStaleNavigation()) return true;
219
98
  try {
220
- await this.commitDocumentNavigation(
99
+ await this.navigationCommit.commit(
221
100
  new URL(request.finalHref ?? request.href, window.location.origin),
222
101
  request.direction ?? "forward",
223
102
  request.document,
@@ -229,18 +108,23 @@ class EcoRouter {
229
108
  return true;
230
109
  },
231
110
  reloadCurrentPage: async (request) => {
232
- if (this.pendingNavigations > 0) return;
111
+ if (this.pendingNavigations > 0) {
112
+ return false;
113
+ }
233
114
  const currentUrl = window.location.pathname + window.location.search;
234
115
  if (request?.clearCache) {
235
116
  this.prefetchManager?.invalidate(currentUrl);
236
117
  }
237
- await this.performNavigation(new URL(currentUrl, window.location.origin), "replace");
118
+ return await this.performNavigation(new URL(currentUrl, window.location.origin), "replace", {
119
+ bypassPrefetchCache: !!request?.clearCache,
120
+ allowFullDocumentFallback: false
121
+ });
238
122
  },
239
123
  cleanupBeforeHandoff: async () => {
240
124
  this.cancelNavigationTransaction();
241
125
  }
242
126
  });
243
- this.adoptDocumentOwner(document);
127
+ getEcoNavigationRuntime(window).adoptDocumentOwner(document, "browser-router");
244
128
  const initialHtml = document.documentElement.outerHTML;
245
129
  this.prefetchManager?.cacheVisitedPage(window.location.href, initialHtml);
246
130
  this.started = true;
@@ -254,10 +138,6 @@ class EcoRouter {
254
138
  return;
255
139
  }
256
140
  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
141
  document.removeEventListener("pointerdown", this.handlePointerDown, true);
262
142
  document.removeEventListener("click", this.handleClick, true);
263
143
  window.removeEventListener("popstate", this.handlePopState);
@@ -265,7 +145,6 @@ class EcoRouter {
265
145
  this.unregisterNavigationRuntime?.();
266
146
  this.unregisterNavigationRuntime = null;
267
147
  this.started = false;
268
- this.pendingHoverNavigation = null;
269
148
  this.pendingPointerNavigation = null;
270
149
  this.queuedNavigationHref = null;
271
150
  const win = window;
@@ -282,10 +161,14 @@ class EcoRouter {
282
161
  */
283
162
  async navigate(href, options = {}) {
284
163
  const url = new URL(href, window.location.origin);
285
- if (!this.isSameOrigin(url)) {
164
+ if (url.origin !== window.location.origin) {
286
165
  window.location.href = href;
287
166
  return;
288
167
  }
168
+ if (isStaticAssetHref(href)) {
169
+ window.location.assign(url.href);
170
+ return;
171
+ }
289
172
  await this.performNavigation(url, options.replace ? "replace" : "forward");
290
173
  }
291
174
  /**
@@ -309,12 +192,12 @@ class EcoRouter {
309
192
  * Shadow DOM boundaries (Web Components).
310
193
  */
311
194
  handlePointerDown(event) {
312
- const link = this.getLinkFromEvent(event);
195
+ const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
313
196
  if (!link) {
314
197
  this.pendingPointerNavigation = null;
315
198
  return;
316
199
  }
317
- const href = this.canInterceptLink(event, link);
200
+ const href = getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute });
318
201
  this.pendingPointerNavigation = href ? {
319
202
  href,
320
203
  timestamp: performance.now()
@@ -323,29 +206,11 @@ class EcoRouter {
323
206
  this.queuedNavigationHref = href;
324
207
  }
325
208
  }
326
- handleHoverIntent(event) {
327
- const link = this.getLinkFromEvent(event);
328
- if (!link) {
329
- return;
330
- }
331
- const href = this.canInterceptLink(event, link);
332
- if (!href) {
333
- return;
334
- }
335
- this.pendingHoverNavigation = {
336
- href,
337
- timestamp: performance.now()
338
- };
339
- if (this.pendingNavigations > 0) {
340
- this.queuedNavigationHref = href;
341
- }
342
- }
343
209
  handleClick(event) {
344
210
  const navigationRuntime = getEcoNavigationRuntime(window);
345
- const link = this.getLinkFromEvent(event);
346
- const href = link ? this.canInterceptLink(event, link) : this.getRecoveredPointerHref() ?? this.getRecoveredHoverHref();
211
+ const link = getAnchorFromNavigationEvent(event, this.options.linkSelector);
212
+ const href = link ? getNavigableHrefFromClick(event, link, { reloadAttribute: this.options.reloadAttribute }) : this.getRecoveredPointerHref();
347
213
  this.pendingPointerNavigation = null;
348
- this.pendingHoverNavigation = null;
349
214
  if (!href) return;
350
215
  this.queuedNavigationHref = null;
351
216
  if (this.isAnotherNavigationRuntimeActive()) {
@@ -376,13 +241,6 @@ class EcoRouter {
376
241
  const url = new URL(window.location.href);
377
242
  this.performNavigation(url, "back");
378
243
  }
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
244
  cancelNavigationTransaction() {
387
245
  getEcoNavigationRuntime(window).cancelCurrentNavigationTransaction();
388
246
  }
@@ -412,26 +270,42 @@ class EcoRouter {
412
270
  * @param url - The target URL to navigate to
413
271
  * @param direction - Navigation direction ('forward', 'back', or 'replace')
414
272
  */
415
- async performNavigation(url, direction) {
273
+ async performNavigation(url, direction, options = {}) {
274
+ const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
416
275
  this.pendingNavigations++;
417
276
  const { isStaleNavigation, signal, complete } = this.beginNavigationTransaction();
418
277
  let queuedNavigationHref = null;
278
+ let committed = false;
419
279
  try {
420
- const html = await this.fetchPage(url, signal);
421
- if (isStaleNavigation()) return;
280
+ const html = await fetchNavigationPage(url, signal, {
281
+ bypassCache: options.bypassPrefetchCache,
282
+ getCachedHtml: this.prefetchManager ? (href) => this.prefetchManager.getCachedHtml(href) : void 0
283
+ });
284
+ if (isStaleNavigation()) {
285
+ return false;
286
+ }
422
287
  const newDocument = this.domSwapper.parseHTML(html, url);
423
- if (isStaleNavigation()) return;
424
- await this.commitDocumentNavigation(url, direction, newDocument, {
288
+ if (isStaleNavigation()) {
289
+ return false;
290
+ }
291
+ committed = await this.navigationCommit.commit(url, direction, newDocument, {
425
292
  html,
426
- isStaleNavigation
293
+ isStaleNavigation,
294
+ allowFullDocumentFallback
427
295
  });
296
+ return committed;
428
297
  } catch (error) {
429
- if (isStaleNavigation()) return;
298
+ if (isStaleNavigation()) {
299
+ return false;
300
+ }
430
301
  if (error instanceof Error && error.name === "AbortError") {
431
- return;
302
+ return false;
432
303
  }
433
304
  console.error("[ecopages] Navigation failed:", error);
434
- window.location.href = url.href;
305
+ if (allowFullDocumentFallback) {
306
+ window.location.href = url.href;
307
+ }
308
+ return false;
435
309
  } finally {
436
310
  complete();
437
311
  this.pendingNavigations--;
@@ -454,30 +328,6 @@ class EcoRouter {
454
328
  }
455
329
  }
456
330
  }
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
- }
479
- return response.text();
480
- }
481
331
  }
482
332
  const ACTIVE_ROUTER_KEY = "__ecopages_browser_router__";
483
333
  function createRouter(options) {
@@ -0,0 +1,3 @@
1
+ export { EcoRouter, createRouter } from './eco-router.js';
2
+ export { syncDocumentElementAttributes } from './document-element-sync.js';
3
+ export { DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC, DEFAULT_OPTIONS, type BrowserRouterNavigateOptions, type EcoAfterSwapEvent, type EcoBeforeSwapEvent, type EcoNavigationEvent, type EcoRouterEventMap, type EcoRouterOptions, } from './types.js';
@@ -0,0 +1,13 @@
1
+ import { EcoRouter, createRouter } from "./eco-router.js";
2
+ import { syncDocumentElementAttributes } from "./document-element-sync.js";
3
+ import {
4
+ DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
5
+ DEFAULT_OPTIONS
6
+ } from "./types.js";
7
+ export {
8
+ DEFAULT_DOCUMENT_ELEMENT_ATTRIBUTES_TO_SYNC,
9
+ DEFAULT_OPTIONS,
10
+ EcoRouter,
11
+ createRouter,
12
+ syncDocumentElementAttributes
13
+ };
@@ -0,0 +1,21 @@
1
+ import type { DomSwapper } from './dom/dom-swapper.js';
2
+ import type { PrefetchManager } from './services/prefetch-manager.js';
3
+ import type { ViewTransitionManager } from './services/view-transition-manager.js';
4
+ import type { EcoNavigationEvent, EcoRouterOptions } from './types.js';
5
+ export type NavigationCommitOptions = {
6
+ html?: string;
7
+ isStaleNavigation?: () => boolean;
8
+ allowFullDocumentFallback?: boolean;
9
+ };
10
+ /**
11
+ * Commits a fetched document into the live page and dispatches navigation lifecycle events.
12
+ */
13
+ export declare class NavigationCommit {
14
+ private readonly domSwapper;
15
+ private readonly viewTransitionManager;
16
+ private readonly prefetchManager;
17
+ private readonly options;
18
+ constructor(domSwapper: DomSwapper, viewTransitionManager: ViewTransitionManager, prefetchManager: PrefetchManager | null, options: Required<EcoRouterOptions>);
19
+ commit(url: URL, direction: EcoNavigationEvent['direction'], newDocument: Document, options?: NavigationCommitOptions): Promise<boolean>;
20
+ private reloadDocument;
21
+ }
@@ -0,0 +1,114 @@
1
+ import { getEcoNavigationRuntime } from "@ecopages/core/router/navigation-coordinator";
2
+ import { manageWindowScroll } from "@ecopages/core/client/scroll";
3
+ import { syncDocumentElementAttributes } from "./document-element-sync.js";
4
+ class NavigationCommit {
5
+ domSwapper;
6
+ viewTransitionManager;
7
+ prefetchManager;
8
+ options;
9
+ constructor(domSwapper, viewTransitionManager, prefetchManager, options) {
10
+ this.domSwapper = domSwapper;
11
+ this.viewTransitionManager = viewTransitionManager;
12
+ this.prefetchManager = prefetchManager;
13
+ this.options = options;
14
+ }
15
+ async commit(url, direction, newDocument, options = {}) {
16
+ const allowFullDocumentFallback = options.allowFullDocumentFallback ?? true;
17
+ const previousUrl = new URL(window.location.href);
18
+ const navigationRuntime = getEcoNavigationRuntime(window);
19
+ const isStaleNavigation = options.isStaleNavigation ?? (() => false);
20
+ const currentDocumentOwner = navigationRuntime.resolveDocumentOwner(document, "browser-router");
21
+ const newDocumentOwner = navigationRuntime.resolveDocumentOwner(newDocument, "browser-router");
22
+ const activeOwner = navigationRuntime.getOwnerState().owner;
23
+ const shouldCleanupCurrentOwner = currentDocumentOwner !== newDocumentOwner && currentDocumentOwner !== "browser-router" && activeOwner === currentDocumentOwner;
24
+ let shouldReload = false;
25
+ const beforeSwapEvent = {
26
+ url,
27
+ direction,
28
+ newDocument,
29
+ reload: () => {
30
+ shouldReload = true;
31
+ }
32
+ };
33
+ document.dispatchEvent(new CustomEvent("eco:before-swap", { detail: beforeSwapEvent }));
34
+ if (isStaleNavigation()) {
35
+ return false;
36
+ }
37
+ if (shouldReload) {
38
+ if (shouldCleanupCurrentOwner) {
39
+ await navigationRuntime.cleanupOwner(currentDocumentOwner);
40
+ }
41
+ if (isStaleNavigation()) {
42
+ return false;
43
+ }
44
+ if (allowFullDocumentFallback) {
45
+ this.reloadDocument(url.href);
46
+ }
47
+ return false;
48
+ }
49
+ const useViewTransitions = this.options.viewTransitions;
50
+ await this.domSwapper.preloadStylesheets(newDocument);
51
+ if (isStaleNavigation()) {
52
+ return false;
53
+ }
54
+ if (shouldCleanupCurrentOwner) {
55
+ await navigationRuntime.cleanupOwner(currentDocumentOwner);
56
+ }
57
+ if (isStaleNavigation()) {
58
+ return false;
59
+ }
60
+ const commitSwap = () => {
61
+ if (isStaleNavigation()) return;
62
+ if (this.options.updateHistory && direction === "forward") {
63
+ window.history.pushState({}, "", url.href);
64
+ } else if (direction === "replace") {
65
+ window.history.replaceState({}, "", url.href);
66
+ }
67
+ syncDocumentElementAttributes(document, newDocument, this.options.documentElementAttributesToSync);
68
+ const { bodyStrategy } = this.domSwapper.morphHead(newDocument);
69
+ if (useViewTransitions && bodyStrategy === "morph") {
70
+ this.domSwapper.morphBody(newDocument);
71
+ } else {
72
+ this.domSwapper.replaceBody(newDocument);
73
+ }
74
+ this.domSwapper.flushRerunScripts();
75
+ manageWindowScroll(url, previousUrl, {
76
+ scrollBehavior: this.options.scrollBehavior,
77
+ smoothScroll: this.options.smoothScroll
78
+ });
79
+ };
80
+ if (useViewTransitions) {
81
+ await this.viewTransitionManager.transition(commitSwap);
82
+ } else {
83
+ commitSwap();
84
+ }
85
+ if (isStaleNavigation()) {
86
+ return false;
87
+ }
88
+ navigationRuntime.adoptDocumentOwner(newDocument, "browser-router");
89
+ const afterSwapEvent = {
90
+ url,
91
+ direction
92
+ };
93
+ document.dispatchEvent(new CustomEvent("eco:after-swap", { detail: afterSwapEvent }));
94
+ this.prefetchManager?.observeLinks();
95
+ if (options.html) {
96
+ this.prefetchManager?.cacheVisitedPage(url.href, options.html);
97
+ }
98
+ requestAnimationFrame(() => {
99
+ if (isStaleNavigation()) return;
100
+ document.dispatchEvent(
101
+ new CustomEvent("eco:page-load", {
102
+ detail: { url, direction }
103
+ })
104
+ );
105
+ });
106
+ return true;
107
+ }
108
+ reloadDocument(href) {
109
+ window.location.assign(href);
110
+ }
111
+ }
112
+ export {
113
+ NavigationCommit
114
+ };
@@ -0,0 +1,8 @@
1
+ export type FetchNavigationPageOptions = {
2
+ bypassCache?: boolean;
3
+ getCachedHtml?: (href: string) => string | null | undefined;
4
+ };
5
+ /**
6
+ * Fetches HTML for a client-side navigation request.
7
+ */
8
+ export declare function fetchNavigationPage(url: URL, signal: AbortSignal, options?: FetchNavigationPageOptions): Promise<string>;
@@ -0,0 +1,24 @@
1
+ import { assertHtmlPageResponse } from "@ecopages/core/router/link-navigation-policy";
2
+ async function fetchNavigationPage(url, signal, options = {}) {
3
+ if (!options.bypassCache && options.getCachedHtml) {
4
+ const cachedHtml = options.getCachedHtml(url.href);
5
+ if (cachedHtml) {
6
+ return cachedHtml;
7
+ }
8
+ }
9
+ const response = await fetch(url.href, {
10
+ signal,
11
+ cache: "no-store",
12
+ headers: {
13
+ Accept: "text/html"
14
+ }
15
+ });
16
+ if (!response.ok) {
17
+ throw new Error(`Failed to fetch page: ${response.status}`);
18
+ }
19
+ await assertHtmlPageResponse(response);
20
+ return response.text();
21
+ }
22
+ export {
23
+ fetchNavigationPage
24
+ };