@krate/runtime 0.5.0-rc.6 → 0.5.0-rc.8

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.
package/dist/router.js CHANGED
@@ -14,6 +14,12 @@ import { siteConfig } from './site-config.js';
14
14
  * removed before loading a new page and re-appended.
15
15
  */
16
16
  const RUNTIME_CHUNK_RE = /\/chunks\/runtime\.[^/]+\.js$/;
17
+ /**
18
+ * Scripts that stay loaded across navigations: the runtime and the shared
19
+ * component chunks (chunks/c/), which only register the hydration code page
20
+ * scripts call. Each runs once per document.
21
+ */
22
+ const PERSISTENT_SCRIPT_RE = /\/chunks\/(?:runtime\.[^/]+|c\/[^/]+)\.js$/;
17
23
  function runtimeConfig() {
18
24
  return siteConfig();
19
25
  }
@@ -62,7 +68,7 @@ function resolveSrc(src, baseUrl) {
62
68
  * not stall waiting on the chunk after the HTML swap.
63
69
  */
64
70
  export function pageAssetURLs(html, baseUrl, loaded) {
65
- const doc = new DOMParser().parseFromString(html, 'text/html');
71
+ const doc = typeof html === 'string' ? new DOMParser().parseFromString(html, 'text/html') : html;
66
72
  const out = [];
67
73
  const seen = new Set();
68
74
  const consider = (src) => {
@@ -88,6 +94,45 @@ export function pageAssetURLs(html, baseUrl, loaded) {
88
94
  }
89
95
  // Router state (module scope, survives reinitRouter).
90
96
  let initialized = false;
97
+ // Island bundles carry their own copy of this module, which is never
98
+ // initialized: the page's router registers itself here, and an uninitialized
99
+ // copy hands navigations to it instead of loading a new document.
100
+ const LIVE_ROUTER = Symbol.for('krate.router');
101
+ function liveRouter() {
102
+ if (initialized)
103
+ return null;
104
+ const g = globalThis;
105
+ let r = g[LIVE_ROUTER];
106
+ // The page runtime is loaded but its router has not started yet (a page
107
+ // with islands only, before the runtime starts it): start it here. The
108
+ // check compares krateRouter, not initRouter, so an island's copy does not
109
+ // keep its own (unused) router start code.
110
+ if (!r && typeof document !== 'undefined' && otherRuntime() && typeof g.initRouter === 'function') {
111
+ try {
112
+ g.initRouter();
113
+ }
114
+ catch (err) {
115
+ console.error(err);
116
+ }
117
+ r = g[LIVE_ROUTER];
118
+ }
119
+ return r && r !== krateRouter ? r : null;
120
+ }
121
+ /**
122
+ * The page runtime's navigate when this is an island's copy of the router
123
+ * and the page has no registered router (an older runtime): it still owns
124
+ * the history, so a navigation goes through it before falling back to a
125
+ * full load.
126
+ */
127
+ function pageNavigate() {
128
+ const nav = globalThis.navigate;
129
+ return otherRuntime() && typeof nav === 'function' ? nav : null;
130
+ }
131
+ /** True in a copy of this module other than the one the page runtime exposes. */
132
+ function otherRuntime() {
133
+ const pageRouter = globalThis.krateRouter;
134
+ return !!pageRouter && pageRouter !== krateRouter;
135
+ }
91
136
  let navSeq = 0;
92
137
  let pendingAbort;
93
138
  let keySeq = 0;
@@ -108,13 +153,27 @@ const SCROLL_HISTORY_MAX = 50;
108
153
  const prefetchedAssets = new Set();
109
154
  const PREFETCHED_ASSETS_MAX = 128;
110
155
  const errorPageCache = new Map();
156
+ /**
157
+ * Documents of visited history entries, keyed by history entry key (LRU), so
158
+ * back/forward renders without a request. Cleared by invalidatePrefetchCache().
159
+ */
160
+ const historyDocs = new Map();
161
+ const HISTORY_CACHE_MAX = 10;
162
+ /** Bumped by invalidatePrefetchCache(): a document fetched before it is stale. */
163
+ let cacheGen = 0;
164
+ /** History key of the hard-loaded first entry, until its document is stored. */
165
+ let initialKey = '';
111
166
  let prefetchTimers = new Map();
112
167
  let prefetchObserver = null;
113
168
  let loadingOverlay = [];
169
+ let loadingTimer;
114
170
  /** Output prefix of intercepting-route fragments (see the compiler's parallel.go). */
115
171
  const INTERCEPT_PREFIX = '_krate/i';
116
- const TRANSITION_MS = 150;
117
172
  const PREFETCH_DELAY = 200;
173
+ /** How long a navigation must be pending before the loading.tsx UI shows. */
174
+ const LOADING_DELAY_MS = 100;
175
+ /** Attribute set on <html> while a navigation is loading. */
176
+ const NAVIGATING_ATTR = 'data-krate-navigating';
118
177
  function now() {
119
178
  return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();
120
179
  }
@@ -171,6 +230,9 @@ function snapshot() {
171
230
  }
172
231
  /** Current router state (pathname without base path, search, hash, status). */
173
232
  export function getNavigationState() {
233
+ const live = liveRouter();
234
+ if (live)
235
+ return live.getState();
174
236
  if (typeof location === 'undefined') {
175
237
  return { url: '', pathname: '/', search: '', hash: '', status: 'idle' };
176
238
  }
@@ -193,6 +255,14 @@ function setStatus(next) {
193
255
  if (status === next)
194
256
  return;
195
257
  status = next;
258
+ // Apps style the pending state with html[data-krate-navigating]; the old
259
+ // page stays visible and interactive until the new one is ready.
260
+ try {
261
+ document.documentElement.toggleAttribute(NAVIGATING_ATTR, next === 'loading');
262
+ }
263
+ catch {
264
+ /* ignore */
265
+ }
196
266
  emit();
197
267
  }
198
268
  /**
@@ -202,6 +272,9 @@ function setStatus(next) {
202
272
  * with getNavigationState().
203
273
  */
204
274
  export function subscribeNavigation(fn) {
275
+ const live = liveRouter();
276
+ if (live)
277
+ return live.subscribe(fn);
205
278
  listeners.add(fn);
206
279
  return () => {
207
280
  listeners.delete(fn);
@@ -273,14 +346,64 @@ function cacheTake(key) {
273
346
  export function invalidatePrefetchCache(url) {
274
347
  // A prefetch still in flight started before the data changed: forgetting it
275
348
  // keeps its (stale) response out of the cache.
349
+ cacheGen++;
276
350
  if (url === undefined) {
277
351
  prefetchCache.clear();
278
352
  prefetchInflight.clear();
353
+ historyDocs.clear();
279
354
  return;
280
355
  }
281
356
  const key = cacheKey(url);
282
357
  prefetchCache.delete(key);
283
358
  prefetchInflight.delete(key);
359
+ historyDocs.forEach((doc, k) => {
360
+ if (cacheKey(doc.url) === key)
361
+ historyDocs.delete(k);
362
+ });
363
+ }
364
+ function historyPut(key, doc) {
365
+ if (!key)
366
+ return;
367
+ historyDocs.delete(key);
368
+ while (historyDocs.size >= HISTORY_CACHE_MAX) {
369
+ const oldest = historyDocs.keys().next().value;
370
+ if (oldest === undefined)
371
+ break;
372
+ historyDocs.delete(oldest);
373
+ }
374
+ historyDocs.set(key, doc);
375
+ }
376
+ /**
377
+ * The hard-loaded first entry has no document string: fetch it in idle time
378
+ * once the user left it, so going back to it is instant too. A response the
379
+ * server marked no-store is not kept.
380
+ */
381
+ function storeInitialDocument(key, url) {
382
+ if (savingData())
383
+ return;
384
+ const gen = cacheGen;
385
+ idle(() => {
386
+ if (historyDocs.has(key) || gen !== cacheGen)
387
+ return;
388
+ fetch(cacheKey(url), { headers: { Accept: 'text/html' }, credentials: 'same-origin' })
389
+ .then(async (res) => {
390
+ if (!res.ok || /no-store/i.test(res.headers.get('cache-control') || ''))
391
+ return;
392
+ const finalUrl = res.url || cacheKey(url);
393
+ if (pathOf(finalUrl) !== pathOf(url))
394
+ return;
395
+ const ct = res.headers.get('content-type') || '';
396
+ const html = await res.text();
397
+ if (!(isHTMLType(ct) || (ct === '' && looksLikeHTML(html))))
398
+ return;
399
+ if (gen !== cacheGen || historyDocs.has(key) || !initialized)
400
+ return;
401
+ historyPut(key, { html, url, status: res.status });
402
+ })
403
+ .catch(() => {
404
+ /* back falls back to a normal fetch */
405
+ });
406
+ });
284
407
  }
285
408
  function isHTMLType(ct) {
286
409
  return /text\/html|application\/xhtml\+xml/i.test(ct);
@@ -288,16 +411,50 @@ function isHTMLType(ct) {
288
411
  function looksLikeHTML(body) {
289
412
  return /^\s*(<!doctype html|<html|<head|<body)/i.test(body);
290
413
  }
291
- function prefetchAsset(url) {
414
+ function prefetchAsset(url, as = 'script') {
292
415
  if (prefetchedAssets.has(url) || prefetchedAssets.size >= PREFETCHED_ASSETS_MAX)
293
416
  return;
294
417
  prefetchedAssets.add(url);
295
418
  const link = document.createElement('link');
296
419
  link.rel = 'prefetch';
297
- link.as = 'script';
420
+ link.as = as;
298
421
  link.href = url;
299
422
  document.head.appendChild(link);
300
423
  }
424
+ /** Stylesheets of a prefetched document that this document does not have. */
425
+ function newStylesheetURLs(doc, baseUrl) {
426
+ const have = new Set();
427
+ document.querySelectorAll('link[rel="stylesheet"]').forEach((l) => have.add(l.href));
428
+ const out = [];
429
+ doc.querySelectorAll('link[rel="stylesheet"][href]').forEach((l) => {
430
+ try {
431
+ const abs = new URL(l.getAttribute('href'), baseUrl).href;
432
+ if (!have.has(abs) && !out.includes(abs))
433
+ out.push(abs);
434
+ }
435
+ catch {
436
+ /* ignore */
437
+ }
438
+ });
439
+ return out;
440
+ }
441
+ /**
442
+ * The scripts this document already has: its script tags, and every resource
443
+ * it fetched, which includes the island modules an earlier client-side
444
+ * navigation imported and that the current head no longer lists.
445
+ */
446
+ function loadedAssetURLs() {
447
+ const loaded = new Set();
448
+ document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
449
+ try {
450
+ for (const e of performance.getEntriesByType('resource'))
451
+ loaded.add(e.name);
452
+ }
453
+ catch {
454
+ // No resource timing: the script tags are all we know.
455
+ }
456
+ return loaded;
457
+ }
301
458
  function prefetchPage(url) {
302
459
  const key = cacheKey(url);
303
460
  const cached = prefetchCache.get(key);
@@ -322,9 +479,12 @@ function prefetchPage(url) {
322
479
  if (prefetchInflight.get(key) !== p)
323
480
  return;
324
481
  cachePut(key, { html, url: finalUrl, status: res.status, at: now() });
325
- const loaded = new Set();
326
- document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
327
- for (const asset of pageAssetURLs(html, finalUrl, loaded))
482
+ // Warm the route's stylesheets and scripts too, so the navigation does
483
+ // not wait on them before the swap.
484
+ const doc = new DOMParser().parseFromString(html, 'text/html');
485
+ for (const sheet of newStylesheetURLs(doc, finalUrl))
486
+ prefetchAsset(sheet, 'style');
487
+ for (const asset of pageAssetURLs(doc, finalUrl, loadedAssetURLs()))
328
488
  prefetchAsset(asset);
329
489
  })
330
490
  .catch(() => {
@@ -364,6 +524,24 @@ function shouldPrefetch(a) {
364
524
  const v = a.getAttribute('data-prefetch');
365
525
  return a.hasAttribute('data-prefetch') && v !== 'false' && v !== '0';
366
526
  }
527
+ /** Most links per page that viewport prefetch will fetch. */
528
+ const VIEWPORT_PREFETCH_MAX = 5;
529
+ let viewportPrefetched = 0;
530
+ /** Whether the connection asks for no speculative traffic (Save-Data, 2g). */
531
+ function savingData() {
532
+ const c = navigator.connection;
533
+ if (!c)
534
+ return false;
535
+ return c.saveData === true || c.effectiveType === 'slow-2g' || c.effectiveType === '2g';
536
+ }
537
+ // Viewport prefetch is opt-in: prefetch="viewport" on the link, or the site-wide
538
+ // `prefetch: "viewport"` default. Everything else prefetches on intent only.
539
+ function wantsViewportPrefetch(a) {
540
+ if (!shouldPrefetch(a))
541
+ return false;
542
+ const v = a.getAttribute('data-prefetch');
543
+ return v === 'viewport' || (runtimeConfig().prefetch === 'viewport' && v !== 'intent');
544
+ }
367
545
  // Above-the-fold/viewport prefetch is deferred to idle time so it never
368
546
  // competes with first paint; hover/focus keeps the 200ms intent debounce.
369
547
  function idle(fn) {
@@ -373,19 +551,27 @@ function idle(fn) {
373
551
  else
374
552
  setTimeout(fn, 50);
375
553
  }
376
- function prefetchHoverHandler(e) {
554
+ /** The prefetchable link an event targets and its absolute URL. */
555
+ function prefetchTarget(e) {
377
556
  const t = e.target;
378
557
  if (!t || typeof t.closest !== 'function')
379
- return;
558
+ return null;
380
559
  const a = t.closest('a[data-prefetch]');
381
- if (!a || !shouldPrefetch(a) || !isLocalLink(a))
382
- return;
560
+ if (!a || !shouldPrefetch(a) || !isLocalLink(a) || savingData())
561
+ return null;
383
562
  const href = a.getAttribute('href');
384
563
  if (!href)
385
- return;
564
+ return null;
386
565
  const url = new URL(href, location.href).href;
387
566
  if (pathOf(url) === renderedPath)
567
+ return null;
568
+ return { a, url };
569
+ }
570
+ function prefetchHoverHandler(e) {
571
+ const hit = prefetchTarget(e);
572
+ if (!hit)
388
573
  return;
574
+ const { a, url } = hit;
389
575
  const existing = prefetchTimers.get(a);
390
576
  if (existing)
391
577
  clearTimeout(existing);
@@ -395,17 +581,36 @@ function prefetchHoverHandler(e) {
395
581
  }, PREFETCH_DELAY);
396
582
  prefetchTimers.set(a, timer);
397
583
  }
584
+ // A press (touch, or a pointer about to click) is a stronger signal than a
585
+ // hover: prefetch right away, so the click finds the document in flight.
586
+ function prefetchPressHandler(e) {
587
+ if (typeof e.button === 'number' && e.button !== 0)
588
+ return;
589
+ const hit = prefetchTarget(e);
590
+ if (!hit)
591
+ return;
592
+ const existing = prefetchTimers.get(hit.a);
593
+ if (existing) {
594
+ clearTimeout(existing);
595
+ prefetchTimers.delete(hit.a);
596
+ }
597
+ void prefetchPage(hit.url);
598
+ }
599
+ const PRESS_EVENTS = ['touchstart', typeof PointerEvent === 'function' ? 'pointerdown' : 'mousedown'];
398
600
  function observePrefetchLinks() {
399
- if (!prefetchObserver)
601
+ viewportPrefetched = 0;
602
+ if (!prefetchObserver || savingData())
400
603
  return;
401
604
  document.querySelectorAll('a[data-prefetch]').forEach((a) => {
402
- if (shouldPrefetch(a))
605
+ if (wantsViewportPrefetch(a))
403
606
  prefetchObserver.observe(a);
404
607
  });
405
608
  }
406
609
  function setupPrefetch() {
407
610
  document.addEventListener('mouseover', prefetchHoverHandler);
408
611
  document.addEventListener('focusin', prefetchHoverHandler);
612
+ for (const name of PRESS_EVENTS)
613
+ document.addEventListener(name, prefetchPressHandler, { passive: true });
409
614
  if (typeof IntersectionObserver !== 'undefined') {
410
615
  prefetchObserver = new IntersectionObserver((entries) => {
411
616
  for (const entry of entries) {
@@ -413,10 +618,12 @@ function setupPrefetch() {
413
618
  continue;
414
619
  const a = entry.target;
415
620
  const href = a.getAttribute('href');
416
- if (href && isLocalLink(a) && shouldPrefetch(a)) {
621
+ if (href && isLocalLink(a) && wantsViewportPrefetch(a) && viewportPrefetched < VIEWPORT_PREFETCH_MAX && !savingData()) {
417
622
  const url = new URL(href, location.href).href;
418
- if (pathOf(url) !== renderedPath)
623
+ if (pathOf(url) !== renderedPath) {
624
+ viewportPrefetched++;
419
625
  idle(() => void prefetchPage(url));
626
+ }
420
627
  }
421
628
  prefetchObserver.unobserve(entry.target);
422
629
  }
@@ -437,6 +644,8 @@ function setupSpeculationRules() {
437
644
  // is used instead of emitting a blocked script.
438
645
  if (document.querySelector('meta[http-equiv="Content-Security-Policy" i]'))
439
646
  return;
647
+ if (savingData())
648
+ return;
440
649
  try {
441
650
  const script = document.createElement('script');
442
651
  script.type = 'speculationrules';
@@ -494,33 +703,34 @@ function supportsViewTransitions() {
494
703
  function appRoot(doc) {
495
704
  return (doc.getElementById('root') || doc.body);
496
705
  }
497
- // While a fetch is in flight: overlay the loading.tsx template (if the page
498
- // has one) and, without View Transitions, fade the content out.
706
+ // While a fetch is in flight the old page stays as it is (visible and
707
+ // interactive). A navigation still pending after LOADING_DELAY_MS overlays the
708
+ // loading.tsx template, if the page has one, so a fast response never flashes it.
499
709
  function beginTransition() {
500
- const tpl = document.querySelector('template[data-krate-loading]');
501
- if (tpl && tpl.content && loadingOverlay.length === 0) {
710
+ if (loadingTimer !== undefined)
711
+ clearTimeout(loadingTimer);
712
+ loadingTimer = setTimeout(() => {
713
+ loadingTimer = undefined;
714
+ const tpl = document.querySelector('template[data-krate-loading]');
715
+ if (status !== 'loading' || !tpl || !tpl.content || loadingOverlay.length > 0)
716
+ return;
502
717
  // Non-destructive loading UI: overlay the template without wiping the
503
718
  // live DOM, so the swap still sees the old tree.
504
719
  const frag = tpl.content.cloneNode(true);
505
720
  loadingOverlay = Array.from(frag.childNodes);
506
721
  document.body.appendChild(frag);
507
- }
508
- // Reduced motion: no fade at all (the overlay above is static).
509
- if (!supportsViewTransitions() && !prefersReducedMotion()) {
510
- const el = appRoot(document);
511
- el.style.transition = `opacity ${TRANSITION_MS}ms ease`;
512
- el.style.opacity = '0';
513
- }
722
+ }, LOADING_DELAY_MS);
514
723
  }
515
724
  function endTransition() {
725
+ if (loadingTimer !== undefined) {
726
+ clearTimeout(loadingTimer);
727
+ loadingTimer = undefined;
728
+ }
516
729
  for (const n of loadingOverlay) {
517
730
  if (n.parentNode)
518
731
  n.parentNode.removeChild(n);
519
732
  }
520
733
  loadingOverlay = [];
521
- const el = appRoot(document);
522
- if (el.style.opacity === '0')
523
- el.style.opacity = '';
524
734
  }
525
735
  /**
526
736
  * Apply `data-view-transition="name"` to `view-transition-name` (and
@@ -540,8 +750,30 @@ function applyViewTransitionNames(root) {
540
750
  });
541
751
  }
542
752
  // Document reconciliation
543
- /** How long a navigation waits for new stylesheets before swapping anyway. */
544
- const STYLESHEET_TIMEOUT_MS = 3000;
753
+ /** How long a navigation waits for new stylesheets and scripts before swapping anyway. */
754
+ const ASSET_TIMEOUT_MS = 3000;
755
+ /** Resolves once link has loaded or failed (listen before inserting it). */
756
+ function linkSettled(link) {
757
+ return new Promise((resolve) => {
758
+ const done = () => {
759
+ link.removeEventListener('load', done);
760
+ link.removeEventListener('error', done);
761
+ resolve();
762
+ };
763
+ link.addEventListener('load', done);
764
+ link.addEventListener('error', done);
765
+ });
766
+ }
767
+ /** Resolves once every promise settled, or after ASSET_TIMEOUT_MS. */
768
+ function settledOrTimeout(pending) {
769
+ if (pending.length === 0)
770
+ return Promise.resolve();
771
+ let timer;
772
+ const timeout = new Promise((resolve) => {
773
+ timer = setTimeout(resolve, ASSET_TIMEOUT_MS);
774
+ });
775
+ return Promise.race([Promise.all(pending).then(() => undefined), timeout]).then(() => clearTimeout(timer));
776
+ }
545
777
  /**
546
778
  * Diff stylesheet <link>s by absolute URL (base-path and format safe). New
547
779
  * links are inserted at the position they have in the incoming document (before
@@ -580,15 +812,7 @@ function prepareStylesheets(doc, baseUrl) {
580
812
  link.rel = 'stylesheet';
581
813
  link.href = abs;
582
814
  // Listen before insertion so a synchronous settle is not missed.
583
- pending.push(new Promise((resolve) => {
584
- const done = () => {
585
- link.removeEventListener('load', done);
586
- link.removeEventListener('error', done);
587
- resolve();
588
- };
589
- link.addEventListener('load', done);
590
- link.addEventListener('error', done);
591
- }));
815
+ pending.push(linkSettled(link));
592
816
  added.push({ link, media: link.getAttribute('media') });
593
817
  link.media = 'not all';
594
818
  if (prev) {
@@ -605,16 +829,8 @@ function prepareStylesheets(doc, baseUrl) {
605
829
  }
606
830
  prev = el;
607
831
  });
608
- let ready = Promise.resolve();
609
- if (pending.length > 0) {
610
- let timer;
611
- const timeout = new Promise((resolve) => {
612
- timer = setTimeout(resolve, STYLESHEET_TIMEOUT_MS);
613
- });
614
- ready = Promise.race([Promise.all(pending).then(() => undefined), timeout]).then(() => clearTimeout(timer));
615
- }
616
832
  return {
617
- ready,
833
+ ready: settledOrTimeout(pending),
618
834
  commit() {
619
835
  for (const { link, media } of added) {
620
836
  if (media === null)
@@ -687,15 +903,66 @@ function scriptsToLoad(doc, baseUrl) {
687
903
  });
688
904
  return out;
689
905
  }
906
+ /**
907
+ * Preloads the incoming page's scripts (and its own modulepreload links) before
908
+ * the swap, so they run from cache right after it instead of leaving the new
909
+ * page un-hydrated while they download. The links request each script the way
910
+ * loadScript does (no crossorigin attribute: a module script fetches in cors
911
+ * mode with same-origin credentials, as modulepreload does; a classic one in
912
+ * no-cors mode, as preload as=script does), so the browser reuses the response.
913
+ */
914
+ function preloadScripts(doc, baseUrl, scripts) {
915
+ const loaded = loadedAssetURLs();
916
+ const links = [];
917
+ const pending = [];
918
+ const add = (href, module, crossOrigin) => {
919
+ if (loaded.has(href))
920
+ return;
921
+ loaded.add(href);
922
+ const link = document.createElement('link');
923
+ if (module)
924
+ link.rel = 'modulepreload';
925
+ else {
926
+ link.rel = 'preload';
927
+ link.as = 'script';
928
+ }
929
+ if (crossOrigin !== null)
930
+ link.setAttribute('crossorigin', crossOrigin);
931
+ link.href = href;
932
+ pending.push(linkSettled(link));
933
+ links.push(link);
934
+ document.head.appendChild(link);
935
+ };
936
+ for (const s of scripts)
937
+ add(s.src, s.module, null);
938
+ doc.querySelectorAll('link[rel="modulepreload"][href]').forEach((l) => {
939
+ try {
940
+ add(resolveSrc(l.getAttribute('href'), baseUrl), true, l.getAttribute('crossorigin'));
941
+ }
942
+ catch {
943
+ /* ignore */
944
+ }
945
+ });
946
+ return {
947
+ ready: settledOrTimeout(pending),
948
+ remove() {
949
+ links.forEach((l) => l.remove());
950
+ },
951
+ };
952
+ }
690
953
  function loadScript(script) {
691
954
  return new Promise((resolve) => {
692
955
  const s = document.createElement('script');
693
956
  s.src = script.src;
694
957
  if (script.module)
695
958
  s.type = 'module';
959
+ // Classic scripts run in document order, as on a full load: a shared
960
+ // component chunk must register before the page script that calls it.
961
+ else
962
+ s.async = false;
696
963
  // Only page scripts are disposable across navigations; the shared runtime
697
- // chunk stays in place.
698
- if (!RUNTIME_CHUNK_RE.test(script.src))
964
+ // and component chunks stay in place.
965
+ if (!PERSISTENT_SCRIPT_RE.test(script.src))
699
966
  s.setAttribute('data-krate-spa', '');
700
967
  s.onload = () => resolve(true);
701
968
  s.onerror = () => resolve(false);
@@ -758,6 +1025,71 @@ function applyScroll(url, req) {
758
1025
  window.scrollTo(0, 0);
759
1026
  }
760
1027
  let focusedRoot = null;
1028
+ // Attributes that tell a focused control apart from its siblings, in addition
1029
+ // to its tag, when it has no id.
1030
+ const FOCUS_SIG_ATTRS = ['name', 'type', 'role', 'aria-label', 'placeholder', 'data-testid', 'data-slot', 'href'];
1031
+ function focusSignature(el) {
1032
+ let s = el.tagName;
1033
+ for (const a of FOCUS_SIG_ATTRS) {
1034
+ const v = el.getAttribute(a);
1035
+ if (v !== null)
1036
+ s += '\u0000' + a + '=' + v;
1037
+ }
1038
+ return s;
1039
+ }
1040
+ function sameSignature(root, sig, tag) {
1041
+ return Array.from(root.getElementsByTagName(tag)).filter((e) => focusSignature(e) === sig);
1042
+ }
1043
+ /** Whether the swap of plan replaces el (it sits in the swapped region or a swapped slot). */
1044
+ function replacedBySwap(el, root, plan) {
1045
+ if (!root.contains(el))
1046
+ return false;
1047
+ if (!plan.region)
1048
+ return true;
1049
+ const within = (pair) => !!(pair[0].compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) &&
1050
+ !!(pair[1].compareDocumentPosition(el) & Node.DOCUMENT_POSITION_PRECEDING);
1051
+ return within(plan.region.live) || plan.slots.some((sl) => within(sl.live));
1052
+ }
1053
+ function captureFocus(root, plan) {
1054
+ const el = document.activeElement;
1055
+ if (!el || el === document.body || el === root || !replacedBySwap(el, root, plan))
1056
+ return null;
1057
+ const sig = focusSignature(el);
1058
+ const field = el;
1059
+ let start = null;
1060
+ let end = null;
1061
+ try {
1062
+ start = typeof field.selectionStart === 'number' ? field.selectionStart : null;
1063
+ end = typeof field.selectionEnd === 'number' ? field.selectionEnd : null;
1064
+ }
1065
+ catch {
1066
+ /* input types without a selection */
1067
+ }
1068
+ return { id: el.id, sig, index: sameSignature(root, sig, el.tagName).indexOf(el), start, end };
1069
+ }
1070
+ function hasFocusWithin(root) {
1071
+ const a = document.activeElement;
1072
+ return !!a && a !== document.body && a !== root && root.contains(a);
1073
+ }
1074
+ function restoreFocus(root, mark) {
1075
+ const tag = mark.sig.split('\u0000')[0];
1076
+ let el = mark.id ? document.getElementById(mark.id) : null;
1077
+ if (!el || !root.contains(el))
1078
+ el = sameSignature(root, mark.sig, tag)[mark.index] ?? null;
1079
+ if (!el || typeof el.focus !== 'function')
1080
+ return;
1081
+ try {
1082
+ el.focus({ preventScroll: true });
1083
+ const field = el;
1084
+ if (mark.start !== null && mark.end !== null && document.activeElement === el && typeof field.setSelectionRange === 'function') {
1085
+ const n = field.value.length;
1086
+ field.setSelectionRange(Math.min(mark.start, n), Math.min(mark.end, n));
1087
+ }
1088
+ }
1089
+ catch {
1090
+ /* ignore */
1091
+ }
1092
+ }
761
1093
  /** Move focus to the content root after navigation (a11y). */
762
1094
  function focusContent() {
763
1095
  const active = document.activeElement;
@@ -843,8 +1175,18 @@ function fetchErrorPage(path) {
843
1175
  })
844
1176
  .catch(() => null);
845
1177
  }
1178
+ /** The stored document of the history entry a back/forward step restores. */
1179
+ function historyHit(req) {
1180
+ if (req.kind !== 'pop' || !req.restoreKey || req.bypassCache)
1181
+ return undefined;
1182
+ const doc = historyDocs.get(req.restoreKey);
1183
+ return doc && pathOf(doc.url) === pathOf(req.url) ? doc : undefined;
1184
+ }
846
1185
  async function loadDocument(req, signal) {
847
1186
  const key = cacheKey(req.url);
1187
+ const stored = historyHit(req);
1188
+ if (stored)
1189
+ return { ok: true, doc: { html: stored.html, url: req.url, status: stored.status } };
848
1190
  if (!req.bypassCache) {
849
1191
  const inflight = prefetchInflight.get(key);
850
1192
  if (inflight)
@@ -860,6 +1202,10 @@ async function loadDocument(req, signal) {
860
1202
  return { ok: true, doc: { html: hit.html, url: target, status: hit.status } };
861
1203
  }
862
1204
  }
1205
+ // Only a document that has to come from the network can show the loading
1206
+ // UI: a prefetched one (even one still in flight, awaited above) or a stored
1207
+ // history entry is nearly there.
1208
+ beginTransition();
863
1209
  let res;
864
1210
  try {
865
1211
  res = await fetch(key, {
@@ -939,9 +1285,6 @@ async function runNavigation(req) {
939
1285
  const ctrl = new AbortController();
940
1286
  pendingAbort = ctrl;
941
1287
  setStatus('loading');
942
- const hasCached = !req.bypassCache && prefetchCache.has(cacheKey(req.url));
943
- if (!hasCached)
944
- beginTransition();
945
1288
  let result;
946
1289
  try {
947
1290
  result = await loadDocument(req, ctrl.signal);
@@ -966,20 +1309,41 @@ async function commitDocument(loaded, req, seq) {
966
1309
  const url = loaded.url;
967
1310
  const newRoot = appRoot(doc);
968
1311
  const oldRoot = appRoot(document);
969
- // Save the position of the entry we are leaving (pop saves in the handler).
970
- if (req.kind === 'push')
971
- saveScroll(currentKey);
972
- const newChain = readRouteChain(doc);
973
- const plan = planSwap(currentChain, newChain, location.href, url, doc);
974
1312
  // Load the incoming stylesheets before swapping so the new page (and kept
975
- // layouts whose rules live in the per-page sheet) never renders unstyled.
1313
+ // layouts whose rules live in the per-page sheet) never renders unstyled,
1314
+ // and its scripts so it hydrates as soon as it appears.
976
1315
  const sheets = prepareStylesheets(doc, url);
977
- await sheets.ready;
1316
+ const preload = preloadScripts(doc, url, scriptsToLoad(doc, url));
1317
+ await Promise.all([sheets.ready, preload.ready]);
978
1318
  if (seq !== navSeq) {
979
1319
  sheets.abort();
1320
+ preload.remove();
980
1321
  return;
981
1322
  }
1323
+ // Save the position of the entry we are leaving (pop saves in the handler).
1324
+ // The old page stayed scrollable while the new one loaded.
1325
+ const leaving = currentKey;
1326
+ const leavingUrl = location.href;
1327
+ if (req.kind === 'push')
1328
+ saveScroll(currentKey);
1329
+ const newChain = readRouteChain(doc);
1330
+ const plan = planSwap(currentChain, newChain, location.href, url, doc);
1331
+ // A navigation that stays on the page (a query change, router.refresh())
1332
+ // keeps the page's islands mounted and their DOM in place; a control
1333
+ // focused in one of them keeps the focus. When the swap replaces the focused
1334
+ // element, focus moves to the same element in the new DOM.
1335
+ // Compared with the document on screen: on back/forward the location
1336
+ // already shows the target URL.
1337
+ const samePage = pathOf(url).split('?')[0] === docPath.split('?')[0];
1338
+ let focusMark = null;
1339
+ let focused = null;
1340
+ let islandJobs = [];
982
1341
  const mutate = () => {
1342
+ if (samePage)
1343
+ focusMark = captureFocus(oldRoot, plan);
1344
+ const active = document.activeElement;
1345
+ focused = active && active !== document.body && oldRoot.contains(active) ? active : null;
1346
+ const sel = focused ? selectionOf(focused) : null;
983
1347
  const title = doc.querySelector('title');
984
1348
  if (title)
985
1349
  document.title = title.textContent || '';
@@ -988,36 +1352,55 @@ async function commitDocument(loaded, req, seq) {
988
1352
  g.krateDisposeExcept(plan.keep);
989
1353
  else if (typeof g.disposeAll === 'function')
990
1354
  g.disposeAll();
1355
+ // Islands in the new markup that are mounted already stay mounted; a
1356
+ // navigation to another page keeps only those with the same props.
1357
+ const opts = { sameProps: !samePage };
1358
+ // Imported into one fragment, so the nodes keep their siblings (an
1359
+ // island's open and close comments find each other).
1360
+ const imported = (nodes) => {
1361
+ const f = document.createDocumentFragment();
1362
+ for (const n of nodes)
1363
+ f.appendChild(document.importNode(n, true));
1364
+ return Array.from(f.childNodes);
1365
+ };
991
1366
  if (plan.region) {
992
1367
  // Only the deepest boundary that differs is replaced; the kept layouts'
993
1368
  // DOM (and its state, focus and scroll containers) stays in place.
994
1369
  const { live, next } = plan.region;
995
- clearBetween(live[0], live[1]);
996
- const nodes = between(next[0], next[1]).map((n) => document.importNode(n, true));
997
- for (const n of nodes)
998
- live[1].parentNode.insertBefore(n, live[1]);
1370
+ islandJobs = swapNodes(live[0].parentNode, live[0], live[1], imported(between(next[0], next[1])), opts);
999
1371
  for (const sl of plan.slots) {
1000
- clearBetween(sl.live[0], sl.live[1]);
1001
- for (const n of between(sl.next[0], sl.next[1]))
1002
- sl.live[1].parentNode.insertBefore(document.importNode(n, true), sl.live[1]);
1372
+ islandJobs.push(...swapNodes(sl.live[0].parentNode, sl.live[0], sl.live[1], imported(between(sl.next[0], sl.next[1])), opts));
1003
1373
  }
1004
1374
  syncLoadingTemplate(oldRoot, newRoot);
1005
1375
  }
1006
1376
  else {
1007
- const nodes = Array.from(newRoot.childNodes).map((n) => document.importNode(n, true));
1008
- oldRoot.replaceChildren(...nodes);
1377
+ islandJobs = swapNodes(oldRoot, null, null, imported(Array.from(newRoot.childNodes)), opts);
1009
1378
  }
1010
1379
  currentChain = plan.chain;
1011
1380
  // Detached slot content of earlier intercepts belonged to the old page.
1381
+ interceptSnapshots.forEach((snap) => unmountIslands(snap.nodes));
1012
1382
  interceptSnapshots.clear();
1013
1383
  sheets.commit();
1014
1384
  reconcileHeadMeta(doc);
1015
1385
  reconcileDocAttrs(doc);
1016
1386
  applyViewTransitionNames(document);
1387
+ if (focused && focused.isConnected) {
1388
+ // The focused element was kept: it keeps the focus (and its selection)
1389
+ // even when it had to move.
1390
+ if (document.activeElement !== focused)
1391
+ refocus(focused, sel);
1392
+ focusMark = null;
1393
+ }
1394
+ else if (focusMark)
1395
+ restoreFocus(oldRoot, focusMark);
1017
1396
  };
1018
- await runMutation(mutate);
1019
- if (seq !== navSeq)
1397
+ // A View Transition cross-fades a change of page; a refresh or a query
1398
+ // change on the same page (a search box, a revalidation) swaps in place.
1399
+ await runMutation(mutate, req.kind !== 'refresh' && !samePage);
1400
+ if (seq !== navSeq) {
1401
+ preload.remove();
1020
1402
  return;
1403
+ }
1021
1404
  endTransition();
1022
1405
  // History: the DOM now shows the new route, so the URL follows it before
1023
1406
  // any page script runs.
@@ -1027,6 +1410,7 @@ async function commitDocument(loaded, req, seq) {
1027
1410
  }
1028
1411
  else if (req.kind === 'replace') {
1029
1412
  scrollPositions.delete(currentKey);
1413
+ historyDocs.delete(currentKey);
1030
1414
  currentKey = newKey();
1031
1415
  history.replaceState(historyEntry(currentKey, req.state), '', url);
1032
1416
  }
@@ -1037,6 +1421,15 @@ async function commitDocument(loaded, req, seq) {
1037
1421
  else if (req.restoreKey) {
1038
1422
  currentKey = req.restoreKey;
1039
1423
  }
1424
+ if (loaded.status >= 200 && loaded.status < 300)
1425
+ historyPut(currentKey, { html: loaded.html, url: location.href, status: loaded.status });
1426
+ if (req.kind === 'push' && leaving && leaving === initialKey) {
1427
+ initialKey = '';
1428
+ storeInitialDocument(leaving, leavingUrl);
1429
+ }
1430
+ else if (req.kind === 'replace' && leaving === initialKey) {
1431
+ initialKey = '';
1432
+ }
1040
1433
  renderedPath = pathOf(location.href);
1041
1434
  docPath = renderedPath;
1042
1435
  syncParams(doc);
@@ -1058,6 +1451,7 @@ async function commitDocument(loaded, req, seq) {
1058
1451
  keepScopes(plan.skip);
1059
1452
  const results = await Promise.all(srcs.map(loadScript));
1060
1453
  keepScopes([]);
1454
+ preload.remove();
1061
1455
  if (seq !== navSeq)
1062
1456
  return;
1063
1457
  if (results.some((ok) => !ok)) {
@@ -1069,14 +1463,76 @@ async function commitDocument(loaded, req, seq) {
1069
1463
  }
1070
1464
  refreshPageBindings();
1071
1465
  dispatch('krate:navigate-end', { url: location.href, status: loaded.status });
1466
+ // An island that rendered its element anew while mounting took the focus
1467
+ // with it; look the element up again once the islands mounted.
1468
+ const mark = focusMark;
1469
+ if (mark && !hasFocusWithin(oldRoot)) {
1470
+ await islandsSettled(islandJobs);
1471
+ if (seq === navSeq && !hasFocusWithin(oldRoot))
1472
+ restoreFocus(oldRoot, mark);
1473
+ }
1474
+ }
1475
+ /** The island-preserving swap (island-swap.ts), which the island loader chunk installs on pages with islands. */
1476
+ function islandSwap() {
1477
+ const s = globalThis.__krateIslandSwap;
1478
+ return s && typeof s.swap === 'function' && typeof s.unmount === 'function' ? s : null;
1479
+ }
1480
+ /**
1481
+ * Replaces the children of parent between start and end (all of them when
1482
+ * both are null) with nodes, keeping the page's mounted islands when the page
1483
+ * has any.
1484
+ */
1485
+ function swapNodes(parent, start, end, nodes, opts) {
1486
+ const s = islandSwap();
1487
+ if (s)
1488
+ return s.swap(parent, start, end, nodes, opts);
1489
+ if (start && end) {
1490
+ clearBetween(start, end);
1491
+ for (const n of nodes)
1492
+ parent.insertBefore(n, end);
1493
+ }
1494
+ else
1495
+ parent.replaceChildren(...nodes);
1496
+ return [];
1497
+ }
1498
+ function unmountIslands(nodes) {
1499
+ const s = islandSwap();
1500
+ if (s)
1501
+ s.unmount(nodes);
1502
+ }
1503
+ /** Waits (at most a few seconds) for the islands the island loader is mounting and for island updates. */
1504
+ function islandsSettled(jobs) {
1505
+ const ready = globalThis.__krateIslandsReady;
1506
+ const all = Promise.all([...jobs, ready && typeof ready.then === 'function' ? ready : null]);
1507
+ return Promise.race([all, new Promise((r) => setTimeout(r, 3000))]);
1508
+ }
1509
+ function selectionOf(el) {
1510
+ const field = el;
1511
+ try {
1512
+ return typeof field.selectionStart === 'number' && typeof field.selectionEnd === 'number' ? [field.selectionStart, field.selectionEnd] : null;
1513
+ }
1514
+ catch {
1515
+ return null;
1516
+ }
1517
+ }
1518
+ function refocus(el, sel) {
1519
+ try {
1520
+ el.focus({ preventScroll: true });
1521
+ if (sel && document.activeElement === el && typeof el.setSelectionRange === 'function') {
1522
+ el.setSelectionRange(sel[0], sel[1]);
1523
+ }
1524
+ }
1525
+ catch {
1526
+ /* ignore */
1527
+ }
1072
1528
  }
1073
1529
  /**
1074
1530
  * Runs the DOM mutation, inside a View Transition when supported. Resolves
1075
1531
  * once the mutation has been applied (the transition's update callback has
1076
1532
  * run), so callers can touch the new DOM, history and focus afterwards.
1077
1533
  */
1078
- function runMutation(mutate) {
1079
- if (!supportsViewTransitions()) {
1534
+ function runMutation(mutate, animate = true) {
1535
+ if (!animate || !supportsViewTransitions()) {
1080
1536
  mutate();
1081
1537
  return Promise.resolve();
1082
1538
  }
@@ -1151,6 +1607,7 @@ function between(start, end) {
1151
1607
  }
1152
1608
  function clearBetween(start, end) {
1153
1609
  const dispose = globalThis.disposeNode;
1610
+ unmountIslands(between(start, end));
1154
1611
  for (const n of between(start, end)) {
1155
1612
  n.parentNode.removeChild(n);
1156
1613
  if (typeof dispose === 'function')
@@ -1567,8 +2024,11 @@ function hashNavigate(url, req) {
1567
2024
  history.replaceState(historyEntry(currentKey || newKey(), req.state), '', url);
1568
2025
  }
1569
2026
  else {
2027
+ const prev = historyDocs.get(currentKey);
1570
2028
  currentKey = newKey();
1571
2029
  history.pushState(historyEntry(currentKey, req.state), '', url);
2030
+ if (prev)
2031
+ historyPut(currentKey, { ...prev, url });
1572
2032
  }
1573
2033
  }
1574
2034
  const hash = new URL(url).hash;
@@ -1730,12 +2190,15 @@ function refreshPageBindings() {
1730
2190
  // Mark the page scripts as disposable so they're removed and re-executed
1731
2191
  // against the fresh DOM on the next navigation.
1732
2192
  document.querySelectorAll('script[src]').forEach((s) => {
1733
- if (!RUNTIME_CHUNK_RE.test(s.src))
2193
+ if (!PERSISTENT_SCRIPT_RE.test(s.src))
1734
2194
  s.setAttribute('data-krate-spa', '');
1735
2195
  });
1736
2196
  }
1737
2197
  // Public API
1738
2198
  function refresh() {
2199
+ const live = liveRouter();
2200
+ if (live)
2201
+ return live.refresh();
1739
2202
  if (!initialized || typeof location === 'undefined') {
1740
2203
  if (typeof location !== 'undefined')
1741
2204
  location.reload();
@@ -1752,7 +2215,13 @@ function refresh() {
1752
2215
  }
1753
2216
  function push(url, opts = {}) {
1754
2217
  if (!initialized) {
1755
- if (typeof location !== 'undefined')
2218
+ const live = liveRouter();
2219
+ if (live)
2220
+ return live.push(url, opts);
2221
+ const nav = pageNavigate();
2222
+ if (nav)
2223
+ nav(url, { ...opts, replace: false });
2224
+ else if (typeof location !== 'undefined')
1756
2225
  location.assign(withBase(url));
1757
2226
  return Promise.resolve();
1758
2227
  }
@@ -1760,7 +2229,13 @@ function push(url, opts = {}) {
1760
2229
  }
1761
2230
  function replace(url, opts = {}) {
1762
2231
  if (!initialized) {
1763
- if (typeof location !== 'undefined')
2232
+ const live = liveRouter();
2233
+ if (live)
2234
+ return live.replace(url, opts);
2235
+ const nav = pageNavigate();
2236
+ if (nav)
2237
+ nav(url, { ...opts, replace: true });
2238
+ else if (typeof location !== 'undefined')
1764
2239
  location.replace(withBase(url));
1765
2240
  return Promise.resolve();
1766
2241
  }
@@ -1789,6 +2264,9 @@ export const krateRouter = {
1789
2264
  },
1790
2265
  refresh,
1791
2266
  prefetch(url) {
2267
+ const live = liveRouter();
2268
+ if (live)
2269
+ return live.prefetch(url);
1792
2270
  if (!initialized || typeof location === 'undefined')
1793
2271
  return Promise.resolve();
1794
2272
  let u;
@@ -1812,7 +2290,7 @@ export const krateRouter = {
1812
2290
  * client-side, true when a full navigation was triggered.
1813
2291
  */
1814
2292
  export function navigate(url, opts = {}) {
1815
- if (initialized) {
2293
+ if (initialized || liveRouter()) {
1816
2294
  void (opts.replace ? replace(url, opts) : push(url, opts));
1817
2295
  return false;
1818
2296
  }
@@ -1832,6 +2310,7 @@ export function initRouter() {
1832
2310
  return;
1833
2311
  }
1834
2312
  initialized = true;
2313
+ globalThis[LIVE_ROUTER] = krateRouter;
1835
2314
  // The first document ran its own boot scripts.
1836
2315
  document.querySelectorAll('script[data-krate-boot]').forEach((s) => bootRan.add(s.textContent || ''));
1837
2316
  renderedPath = pathOf(location.href);
@@ -1839,6 +2318,7 @@ export function initRouter() {
1839
2318
  docAttrSnap = docAttrsOf(document);
1840
2319
  docPath = renderedPath;
1841
2320
  currentKey = entryKey(history.state) || newKey();
2321
+ initialKey = currentKey;
1842
2322
  if (entryKey(history.state) === undefined) {
1843
2323
  try {
1844
2324
  history.replaceState(historyEntry(currentKey, history.state), '', location.href);
@@ -1875,6 +2355,8 @@ export function destroyRouter() {
1875
2355
  if (!initialized)
1876
2356
  return;
1877
2357
  initialized = false;
2358
+ if (globalThis[LIVE_ROUTER] === krateRouter)
2359
+ delete globalThis[LIVE_ROUTER];
1878
2360
  document.removeEventListener('click', clickHandler);
1879
2361
  document.removeEventListener('submit', submitHandler);
1880
2362
  window.removeEventListener('popstate', popstateHandler);
@@ -1883,6 +2365,8 @@ export function destroyRouter() {
1883
2365
  window.removeEventListener('pageshow', pageshowHandler);
1884
2366
  document.removeEventListener('mouseover', prefetchHoverHandler);
1885
2367
  document.removeEventListener('focusin', prefetchHoverHandler);
2368
+ for (const name of PRESS_EVENTS)
2369
+ document.removeEventListener(name, prefetchPressHandler);
1886
2370
  for (const timer of prefetchTimers.values())
1887
2371
  clearTimeout(timer);
1888
2372
  prefetchTimers = new Map();
@@ -1896,12 +2380,16 @@ export function destroyRouter() {
1896
2380
  navSeq++;
1897
2381
  prefetchCache.clear();
1898
2382
  prefetchInflight.clear();
2383
+ historyDocs.clear();
2384
+ initialKey = '';
2385
+ cacheGen++;
1899
2386
  scrollPositions.clear();
1900
2387
  errorPageCache.clear();
1901
2388
  bootRan.clear();
1902
2389
  listeners.clear();
1903
2390
  status = 'idle';
1904
- loadingOverlay = [];
2391
+ document.documentElement.removeAttribute(NAVIGATING_ATTR);
2392
+ endTransition();
1905
2393
  currentChain = [];
1906
2394
  interceptSnapshots.clear();
1907
2395
  docPath = '';