@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 +0,0 @@
1
- import morphdom from "morphdom";
2
- const DEFAULT_PERSIST_ATTR = "data-eco-persist";
3
- const RERUN_SRC_ATTR = "data-eco-rerun-src";
4
- function isPersisted(element, persistAttribute) {
5
- return element.hasAttribute(persistAttribute) || element.hasAttribute(DEFAULT_PERSIST_ATTR);
6
- }
7
- function isHydratedCustomElement(element) {
8
- return element.localName.includes("-") && element.shadowRoot !== null;
9
- }
10
- class DomSwapper {
11
- persistAttribute;
12
- pendingHeadScripts = [];
13
- pendingRerunScripts = [];
14
- rerunNonce = 0;
15
- constructor(persistAttribute) {
16
- this.persistAttribute = persistAttribute;
17
- }
18
- /**
19
- * Parses HTML string into a Document, injecting a temporary base tag for URL resolution.
20
- */
21
- parseHTML(html, url) {
22
- const parser = new DOMParser();
23
- const htmlToParse = url ? `<base href="${url.href}" data-eco-injected>${html}` : html;
24
- return parser.parseFromString(htmlToParse, "text/html");
25
- }
26
- /**
27
- * Preloads new stylesheets from target document to prevent FOUC.
28
- *
29
- * Discovers stylesheet links in the target document that aren't present in the
30
- * current document, creates corresponding link elements, and waits for all to
31
- * load before resolving. This follows Turbo's approach of waiting for stylesheets
32
- * before any DOM updates.
33
- */
34
- async preloadStylesheets(newDocument) {
35
- const existingHrefs = new Set(
36
- Array.from(document.head.querySelectorAll('link[rel="stylesheet"]')).map((l) => l.href)
37
- );
38
- const newStylesheetLinks = Array.from(
39
- newDocument.head.querySelectorAll('link[rel="stylesheet"]')
40
- ).filter((link) => !existingHrefs.has(link.href));
41
- if (newStylesheetLinks.length === 0) {
42
- return;
43
- }
44
- const TIMEOUT = 5e3;
45
- const loadPromises = newStylesheetLinks.map((link) => {
46
- return new Promise((resolve) => {
47
- const newLink = document.createElement("link");
48
- newLink.rel = "stylesheet";
49
- newLink.media = link.media || "all";
50
- const timeoutId = setTimeout(() => {
51
- cleanup();
52
- resolve();
53
- }, TIMEOUT);
54
- const cleanup = () => {
55
- clearTimeout(timeoutId);
56
- newLink.onload = null;
57
- newLink.onerror = null;
58
- };
59
- newLink.onload = () => {
60
- cleanup();
61
- resolve();
62
- };
63
- newLink.onerror = () => {
64
- cleanup();
65
- resolve();
66
- };
67
- newLink.href = link.href;
68
- document.head.appendChild(newLink);
69
- });
70
- });
71
- await Promise.all(loadPromises);
72
- }
73
- /**
74
- * Updates document head using Turbo-style surgical updates.
75
- *
76
- * This approach avoids morphing the head element entirely, which prevents
77
- * browser repaints that cause FOUC. Instead, it:
78
- * - Updates the document title
79
- * - Merges meta tags (adds new, updates changed)
80
- * - Leaves stylesheets untouched (they're preloaded separately)
81
- * - Handles script re-execution for marked scripts
82
- * - Injects new scripts from the incoming page that are absent from the current head
83
- */
84
- morphHead(newDocument) {
85
- this.pendingHeadScripts = [];
86
- this.pendingRerunScripts = this.collectRerunScripts(newDocument);
87
- this.removeStaleHeadScripts(newDocument);
88
- const newTitle = newDocument.head.querySelector("title");
89
- if (newTitle && document.title !== newTitle.textContent) {
90
- document.title = newTitle.textContent || "";
91
- }
92
- const newMetas = newDocument.head.querySelectorAll("meta[name], meta[property]");
93
- for (const newMeta of newMetas) {
94
- const name = newMeta.getAttribute("name");
95
- const property = newMeta.getAttribute("property");
96
- const content = newMeta.getAttribute("content");
97
- const selector = name ? `meta[name="${name}"]` : `meta[property="${property}"]`;
98
- const existingMeta = document.head.querySelector(selector);
99
- if (existingMeta) {
100
- if (existingMeta.getAttribute("content") !== content) {
101
- existingMeta.setAttribute("content", content || "");
102
- }
103
- } else {
104
- document.head.appendChild(newMeta.cloneNode(true));
105
- }
106
- }
107
- const existingScriptSrcs = new Set(
108
- Array.from(document.head.querySelectorAll("script[src]")).map((s) => s.getAttribute("src"))
109
- );
110
- const existingInlineContents = new Set(
111
- Array.from(document.head.querySelectorAll("script:not([src])")).map((s) => (s.textContent ?? "").trim())
112
- );
113
- const allNewHeadScripts = newDocument.head.querySelectorAll("script");
114
- for (const script of allNewHeadScripts) {
115
- if (script.hasAttribute("data-eco-rerun")) continue;
116
- const src = script.getAttribute("src");
117
- const scriptId = script.getAttribute("data-eco-script-id") || script.getAttribute("id");
118
- const existingScript = this.findExistingHeadScript(script);
119
- if (scriptId && existingScript) {
120
- if (!this.isNonExecutableHeadScript(script)) {
121
- continue;
122
- }
123
- if (this.areHeadScriptsEquivalent(script, existingScript)) {
124
- continue;
125
- }
126
- this.pendingHeadScripts.push({
127
- attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
128
- textContent: script.textContent ?? "",
129
- src,
130
- scriptId,
131
- replaceExisting: true
132
- });
133
- continue;
134
- }
135
- if (src) {
136
- if (existingScriptSrcs.has(src)) continue;
137
- this.pendingHeadScripts.push({
138
- attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
139
- textContent: script.textContent ?? "",
140
- src,
141
- scriptId,
142
- replaceExisting: false
143
- });
144
- existingScriptSrcs.add(src);
145
- } else {
146
- const content = (script.textContent ?? "").trim();
147
- if (!content || existingInlineContents.has(content)) continue;
148
- this.pendingHeadScripts.push({
149
- attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
150
- textContent: script.textContent ?? "",
151
- src: null,
152
- scriptId,
153
- replaceExisting: false
154
- });
155
- existingInlineContents.add(content);
156
- }
157
- }
158
- }
159
- /**
160
- * Replays queued `data-eco-rerun` scripts after the body swap completes.
161
- *
162
- * Scripts are intentionally flushed after the new body is in place so DOM-
163
- * dependent bootstraps bind against the incoming page rather than the page
164
- * being replaced.
165
- */
166
- flushRerunScripts() {
167
- for (const script of this.pendingHeadScripts) {
168
- const replacement = document.createElement("script");
169
- for (const [name, value] of script.attributes) {
170
- replacement.setAttribute(name, value);
171
- }
172
- replacement.textContent = script.textContent;
173
- const existingScript = this.findExistingHeadScript(script);
174
- if (script.replaceExisting && existingScript) {
175
- existingScript.replaceWith(replacement);
176
- continue;
177
- }
178
- document.head.appendChild(replacement);
179
- }
180
- this.pendingHeadScripts = [];
181
- for (const script of this.pendingRerunScripts) {
182
- const targetParent = script.parent === "body" ? document.body : document.head;
183
- const replacement = document.createElement("script");
184
- const shouldBustModuleSrc = this.isExternalModuleRerunScript(script);
185
- for (const [name, value] of script.attributes) {
186
- if (name === "data-eco-rerun") {
187
- continue;
188
- }
189
- if (name === "src" && shouldBustModuleSrc) {
190
- replacement.setAttribute(RERUN_SRC_ATTR, value);
191
- replacement.setAttribute("src", this.createRerunScriptUrl(value));
192
- continue;
193
- }
194
- replacement.setAttribute(name, value);
195
- }
196
- replacement.textContent = script.textContent;
197
- const existingScript = this.findExistingRerunScript(targetParent, script);
198
- if (existingScript) {
199
- existingScript.replaceWith(replacement);
200
- continue;
201
- }
202
- targetParent.appendChild(replacement);
203
- }
204
- this.pendingRerunScripts = [];
205
- }
206
- /**
207
- * Returns whether pending rerun scripts require a full body replacement
208
- * instead of morphing, so DOM-dependent bootstraps bind against fresh markup.
209
- */
210
- shouldReplaceBodyForRerunScripts() {
211
- return this.pendingRerunScripts.length > 0;
212
- }
213
- /**
214
- * Detects custom elements without shadow DOM (light-DOM custom elements).
215
- * These need full replacement rather than morphing, because morphdom would
216
- * strip JS-generated content from their light DOM children.
217
- */
218
- isLightDomCustomElement(element) {
219
- return element.localName.includes("-") && element.shadowRoot === null;
220
- }
221
- /**
222
- * Queues a custom element for deferred replacement instead of replacing it
223
- * inline during the morphdom walk.
224
- *
225
- * Replacing elements during morphdom traversal mutates the live DOM tree,
226
- * which can cause morphdom to skip siblings or process stale nodes.
227
- * Deferring the replacement until after morphdom finishes avoids this.
228
- *
229
- * @returns Always `false` to tell morphdom to skip updating this element.
230
- */
231
- replaceCustomElement(fromEl, toEl, deferred) {
232
- deferred.push({ from: fromEl, to: toEl });
233
- return false;
234
- }
235
- /**
236
- * Replaces all deferred custom elements after morphdom has finished traversing.
237
- *
238
- * Each element is recreated via `document.createElement` so the browser fires
239
- * the full custom element lifecycle (`disconnectedCallback` on the old instance,
240
- * `connectedCallback` on the new one). Elements that were already removed during
241
- * the morph pass are skipped via the `isConnected` guard.
242
- */
243
- flushDeferredCustomElementReplacements(deferred) {
244
- for (const { from, to } of deferred) {
245
- if (!from.isConnected) continue;
246
- const newEl = document.createElement(to.tagName);
247
- for (const attr of to.attributes) {
248
- newEl.setAttribute(attr.name, attr.value);
249
- }
250
- newEl.innerHTML = to.innerHTML;
251
- from.replaceWith(newEl);
252
- }
253
- }
254
- /**
255
- * Morphs document body using morphdom.
256
- * Preserves persisted elements and hydrated custom elements.
257
- * Light-DOM custom elements are fully replaced to trigger proper
258
- * disconnectedCallback → connectedCallback lifecycle.
259
- */
260
- morphBody(newDocument) {
261
- const persistAttr = this.persistAttribute;
262
- const deferredReplacements = [];
263
- morphdom(document.body, newDocument.body, {
264
- onBeforeElUpdated: (fromEl, toEl) => {
265
- if (isPersisted(fromEl, persistAttr)) {
266
- return false;
267
- }
268
- if (isHydratedCustomElement(fromEl)) {
269
- return this.replaceCustomElement(fromEl, toEl, deferredReplacements);
270
- }
271
- if (this.isLightDomCustomElement(fromEl)) {
272
- return this.replaceCustomElement(fromEl, toEl, deferredReplacements);
273
- }
274
- if (fromEl.isEqualNode(toEl)) {
275
- return false;
276
- }
277
- return true;
278
- }
279
- });
280
- this.flushDeferredCustomElementReplacements(deferredReplacements);
281
- this.processDeclarativeShadowDOM(document.body);
282
- }
283
- /**
284
- * Replaces body content in a single operation.
285
- * Preserves persisted elements by moving them to the new body.
286
- * Use when View Transitions are disabled.
287
- */
288
- replaceBody(newDocument) {
289
- const persistAttr = this.persistAttribute;
290
- const persistedElements = document.body.querySelectorAll(`[${persistAttr}], [${DEFAULT_PERSIST_ATTR}]`);
291
- const persistedMap = /* @__PURE__ */ new Map();
292
- for (const el of persistedElements) {
293
- const key = el.getAttribute(persistAttr) || el.getAttribute(DEFAULT_PERSIST_ATTR);
294
- if (key) {
295
- persistedMap.set(key, el);
296
- }
297
- }
298
- for (const [key, oldEl] of persistedMap) {
299
- const placeholder = newDocument.body.querySelector(
300
- `[${persistAttr}="${key}"], [${DEFAULT_PERSIST_ATTR}="${key}"]`
301
- );
302
- if (placeholder) {
303
- placeholder.replaceWith(oldEl);
304
- }
305
- }
306
- document.body.replaceChildren(...Array.from(newDocument.body.childNodes));
307
- this.processDeclarativeShadowDOM(document.body);
308
- }
309
- /**
310
- * Collects all `data-eco-rerun` scripts from the incoming document.
311
- *
312
- * These scripts are re-executed after each navigation so their side-effects
313
- * (event listeners, DOM bootstraps) bind against the new page content.
314
- */
315
- collectRerunScripts(newDocument) {
316
- return Array.from(newDocument.querySelectorAll("script[data-eco-rerun]")).map((script) => ({
317
- parent: script.closest("body") ? "body" : "head",
318
- attributes: Array.from(script.attributes).map((attr) => [attr.name, attr.value]),
319
- textContent: script.textContent ?? "",
320
- src: script.getAttribute("src"),
321
- scriptId: script.getAttribute("data-eco-script-id")
322
- }));
323
- }
324
- /**
325
- * Removes head scripts that are no longer present in the incoming document.
326
- *
327
- * Persisted scripts and executable inline scripts with stable identifiers
328
- * are kept to avoid breaking long-lived runtime state.
329
- */
330
- removeStaleHeadScripts(newDocument) {
331
- const nextScriptKeys = new Set(
332
- Array.from(newDocument.head.querySelectorAll("script")).map((script) => this.getHeadScriptKey(script)).filter((key) => key !== null)
333
- );
334
- for (const script of Array.from(document.head.querySelectorAll("script"))) {
335
- const key = this.getHeadScriptKey(script);
336
- if (!key || nextScriptKeys.has(key)) {
337
- continue;
338
- }
339
- if (isPersisted(script, this.persistAttribute)) {
340
- continue;
341
- }
342
- if (this.shouldPersistExecutableInlineHeadScript(script)) {
343
- continue;
344
- }
345
- script.remove();
346
- }
347
- }
348
- /**
349
- * Determines whether an inline head script should survive navigation.
350
- *
351
- * Only identified (`data-eco-script-id` or `id`), executable inline scripts
352
- * are persisted. External scripts and rerun scripts are never persisted here
353
- * because they have their own lifecycle management.
354
- */
355
- shouldPersistExecutableInlineHeadScript(script) {
356
- const scriptId = script.getAttribute("data-eco-script-id") || script.getAttribute("id");
357
- if (!scriptId) {
358
- return false;
359
- }
360
- if (script.hasAttribute("data-eco-rerun")) {
361
- return false;
362
- }
363
- if (script.getAttribute(RERUN_SRC_ATTR) || script.getAttribute("src")) {
364
- return false;
365
- }
366
- return !this.isNonExecutableHeadScript(script);
367
- }
368
- /**
369
- * Returns whether a script is non-executable (e.g. `type="application/json"`).
370
- *
371
- * Non-executable scripts are data carriers (JSON-LD, page data) that can be
372
- * safely replaced without side-effects, unlike executable scripts that would
373
- * re-run their bootstrap logic.
374
- */
375
- isNonExecutableHeadScript(script) {
376
- const type = (script.getAttribute("type") ?? "").trim().toLowerCase();
377
- if (!type) {
378
- return false;
379
- }
380
- return ![
381
- "application/javascript",
382
- "application/ecmascript",
383
- "module",
384
- "text/ecmascript",
385
- "text/javascript"
386
- ].includes(type);
387
- }
388
- /**
389
- * Compares two head scripts for structural equality (key, content, attributes).
390
- *
391
- * Used to skip replacing non-executable data scripts when their content
392
- * has not changed between navigations.
393
- */
394
- areHeadScriptsEquivalent(nextScript, currentScript) {
395
- if (this.getHeadScriptKey(nextScript) !== this.getHeadScriptKey(currentScript)) {
396
- return false;
397
- }
398
- if ((nextScript.textContent ?? "") !== (currentScript.textContent ?? "")) {
399
- return false;
400
- }
401
- const nextAttributes = Array.from(nextScript.attributes).map((attribute) => [attribute.name, attribute.value]);
402
- const currentAttributes = Array.from(currentScript.attributes).map((attribute) => [
403
- attribute.name,
404
- attribute.value
405
- ]);
406
- if (nextAttributes.length !== currentAttributes.length) {
407
- return false;
408
- }
409
- return nextAttributes.every(
410
- ([name, value], index) => currentAttributes[index]?.[0] === name && currentAttributes[index]?.[1] === value
411
- );
412
- }
413
- /**
414
- * Derives a stable identity key for a head script.
415
- *
416
- * Priority: `data-eco-script-id` / `id` > `src` > trimmed inline content.
417
- * Returns `null` for empty anonymous inline scripts that cannot be tracked.
418
- */
419
- getHeadScriptKey(script) {
420
- const scriptId = script instanceof HTMLScriptElement ? script.getAttribute("data-eco-script-id") || script.getAttribute("id") : script.scriptId;
421
- if (scriptId) {
422
- return `id:${scriptId}`;
423
- }
424
- const src = script instanceof HTMLScriptElement ? script.getAttribute(RERUN_SRC_ATTR) || script.getAttribute("src") : script.src;
425
- if (src) {
426
- return `src:${src}`;
427
- }
428
- const textContent = (script.textContent ?? "").trim();
429
- return textContent ? `inline:${textContent}` : null;
430
- }
431
- /**
432
- * Finds an existing head script that matches the given script's identity key.
433
- */
434
- findExistingHeadScript(script) {
435
- const scriptKey = this.getHeadScriptKey(script);
436
- if (!scriptKey) {
437
- return null;
438
- }
439
- return Array.from(document.head.querySelectorAll("script")).find(
440
- (candidate) => this.getHeadScriptKey(candidate) === scriptKey
441
- ) ?? null;
442
- }
443
- /**
444
- * Finds an existing rerun script in the given root by `data-eco-script-id` or
445
- * by matching `src` and `textContent`.
446
- */
447
- findExistingRerunScript(root, script) {
448
- const scripts = Array.from(root.querySelectorAll("script"));
449
- if (script.scriptId) {
450
- return scripts.find((candidate) => candidate.getAttribute("data-eco-script-id") === script.scriptId) ?? null;
451
- }
452
- return scripts.find(
453
- (candidate) => (candidate.getAttribute(RERUN_SRC_ATTR) ?? candidate.getAttribute("src")) === script.src && (candidate.textContent ?? "") === script.textContent
454
- ) ?? null;
455
- }
456
- /**
457
- * Returns whether a rerun script is an external ES module (`type="module"` with `src`).
458
- *
459
- * Module scripts are cached by URL, so re-execution requires cache-busting
460
- * via a query parameter nonce.
461
- */
462
- isExternalModuleRerunScript(script) {
463
- if (!script.src) {
464
- return false;
465
- }
466
- return script.attributes.some(([name, value]) => name === "type" && value === "module");
467
- }
468
- /**
469
- * Appends a nonce query parameter to a script URL to bust the browser's
470
- * module cache and force re-execution on navigation.
471
- */
472
- createRerunScriptUrl(src) {
473
- const url = new URL(src, document.baseURI);
474
- url.searchParams.set("__eco_rerun", String(++this.rerunNonce));
475
- return url.toString();
476
- }
477
- /**
478
- * Manually attaches declarative shadow DOM templates.
479
- * Browsers only process `<template shadowrootmode>` during initial parse.
480
- */
481
- processDeclarativeShadowDOM(root) {
482
- const templates = root.querySelectorAll("template[shadowrootmode], template[shadowroot]");
483
- for (const template of templates) {
484
- const mode = template.getAttribute("shadowrootmode") || template.getAttribute("shadowroot");
485
- const parent = template.parentElement;
486
- if (parent && !parent.shadowRoot) {
487
- const shadowRoot = parent.attachShadow({ mode });
488
- shadowRoot.appendChild(template.content);
489
- template.remove();
490
- this.processDeclarativeShadowDOM(shadowRoot);
491
- }
492
- }
493
- }
494
- }
495
- export {
496
- DomSwapper
497
- };
@@ -1,8 +0,0 @@
1
- /**
2
- * Services for the EcoPages transitions package
3
- * @module
4
- */
5
- export { DomSwapper } from './dom-swapper.js';
6
- export { ScrollManager } from './scroll-manager.js';
7
- export { ViewTransitionManager } from './view-transition-manager.js';
8
- export { PrefetchManager } from './prefetch-manager.js';
@@ -1,10 +0,0 @@
1
- import { DomSwapper } from "./dom-swapper.js";
2
- import { ScrollManager } from "./scroll-manager.js";
3
- import { ViewTransitionManager } from "./view-transition-manager.js";
4
- import { PrefetchManager } from "./prefetch-manager.js";
5
- export {
6
- DomSwapper,
7
- PrefetchManager,
8
- ScrollManager,
9
- ViewTransitionManager
10
- };
@@ -1,19 +0,0 @@
1
- /**
2
- * Manages scroll position during navigations
3
- * @module
4
- */
5
- import type { EcoRouterOptions } from '../types';
6
- /**
7
- * Service for handling scroll position during page transitions.
8
- * Handles window scroll behavior and hash navigation.
9
- */
10
- export declare class ScrollManager {
11
- private scrollBehavior;
12
- private smoothScroll;
13
- constructor(scrollBehavior: Required<EcoRouterOptions>['scrollBehavior'], smoothScroll: boolean);
14
- /**
15
- * Handle window scroll position based on scrollBehavior option.
16
- * Hash links always scroll to target regardless of option.
17
- */
18
- handleScroll(newUrl: URL, previousUrl: URL): void;
19
- }
@@ -1,36 +0,0 @@
1
- class ScrollManager {
2
- scrollBehavior;
3
- smoothScroll;
4
- constructor(scrollBehavior, smoothScroll) {
5
- this.scrollBehavior = scrollBehavior;
6
- this.smoothScroll = smoothScroll;
7
- }
8
- /**
9
- * Handle window scroll position based on scrollBehavior option.
10
- * Hash links always scroll to target regardless of option.
11
- */
12
- handleScroll(newUrl, previousUrl) {
13
- if (newUrl.hash) {
14
- const target = document.querySelector(newUrl.hash);
15
- target?.scrollIntoView({ behavior: this.smoothScroll ? "smooth" : "instant" });
16
- return;
17
- }
18
- const behavior = this.smoothScroll ? "smooth" : "instant";
19
- switch (this.scrollBehavior) {
20
- case "preserve":
21
- break;
22
- case "auto":
23
- if (newUrl.pathname !== previousUrl.pathname) {
24
- window.scrollTo({ top: 0, left: 0, behavior });
25
- }
26
- break;
27
- case "top":
28
- default:
29
- window.scrollTo({ top: 0, left: 0, behavior });
30
- break;
31
- }
32
- }
33
- }
34
- export {
35
- ScrollManager
36
- };
@@ -1,29 +0,0 @@
1
- /**
2
- * Manages View Transition API integration
3
- * @module
4
- */
5
- /**
6
- * Service for handling View Transition API during page transitions.
7
- * Falls back to direct execution if the API is not supported.
8
- */
9
- export declare class ViewTransitionManager {
10
- private enabled;
11
- constructor(enabled: boolean);
12
- /**
13
- * Check if the View Transition API is supported
14
- */
15
- isSupported(): boolean;
16
- /**
17
- * Execute a callback with view transition if available and enabled.
18
- * Falls back to direct execution if not supported.
19
- *
20
- * Navigation correctness depends on the DOM update callback completing, not on
21
- * the browser finishing the visual transition animation. Awaiting
22
- * `finished` here can leave router transactions artificially in-flight and
23
- * block later navigations during rapid repeated clicks, so the router waits
24
- * for `updateCallbackDone` and lets the animation finish in the background.
25
- * @param callback - The DOM update callback to execute
26
- * @returns Promise that resolves when the DOM update has committed
27
- */
28
- transition(callback: () => void | Promise<void>): Promise<void>;
29
- }
@@ -1,54 +0,0 @@
1
- import { applyViewTransitionNames, clearViewTransitionNames } from "../view-transition-utils.js";
2
- class ViewTransitionManager {
3
- enabled;
4
- constructor(enabled) {
5
- this.enabled = enabled;
6
- }
7
- /**
8
- * Check if the View Transition API is supported
9
- */
10
- isSupported() {
11
- return "startViewTransition" in document;
12
- }
13
- /**
14
- * Execute a callback with view transition if available and enabled.
15
- * Falls back to direct execution if not supported.
16
- *
17
- * Navigation correctness depends on the DOM update callback completing, not on
18
- * the browser finishing the visual transition animation. Awaiting
19
- * `finished` here can leave router transactions artificially in-flight and
20
- * block later navigations during rapid repeated clicks, so the router waits
21
- * for `updateCallbackDone` and lets the animation finish in the background.
22
- * @param callback - The DOM update callback to execute
23
- * @returns Promise that resolves when the DOM update has committed
24
- */
25
- async transition(callback) {
26
- if (!this.enabled || !this.isSupported()) {
27
- await callback();
28
- return;
29
- }
30
- applyViewTransitionNames();
31
- const transition = document.startViewTransition(async () => {
32
- await callback();
33
- applyViewTransitionNames();
34
- });
35
- void transition.ready.catch((error) => {
36
- if (error instanceof Error && error.name === "AbortError") {
37
- return;
38
- }
39
- console.error("[ecopages] View transition failed to start:", error);
40
- });
41
- void transition.finished.catch((error) => {
42
- if (error instanceof Error && error.name === "AbortError") {
43
- return;
44
- }
45
- console.error("[ecopages] View transition lifecycle failed:", error);
46
- }).finally(() => {
47
- clearViewTransitionNames();
48
- });
49
- await transition.updateCallbackDone;
50
- }
51
- }
52
- export {
53
- ViewTransitionManager
54
- };
@@ -1,14 +0,0 @@
1
- /**
2
- * View transition utilities for applying transition names from data attributes.
3
- * @module
4
- */
5
- /**
6
- * Applies view-transition-name CSS property to elements with data-view-transition attribute.
7
- * By default, it also injects styles to prevent "ghosting" (sets animation: none) for clean morphing,
8
- * unless data-view-transition-animate="fade" is present.
9
- */
10
- export declare function applyViewTransitionNames(): void;
11
- /**
12
- * Clears view-transition-name CSS property from all elements.
13
- */
14
- export declare function clearViewTransitionNames(): void;