@ecopages/browser-router 0.2.0-beta.9 → 0.2.0-rc.1

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