@krate/runtime 0.5.0-rc.7 → 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.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * these warms the route's JS in addition to its HTML, so an SPA navigation does
5
5
  * not stall waiting on the chunk after the HTML swap.
6
6
  */
7
- export declare function pageAssetURLs(html: string, baseUrl: string, loaded: Set<string>): string[];
7
+ export declare function pageAssetURLs(html: string | Document, baseUrl: string, loaded: Set<string>): string[];
8
8
  export interface NavigateOptions {
9
9
  /** Replace the current history entry instead of pushing a new one. */
10
10
  replace?: boolean;
package/dist/router.js CHANGED
@@ -68,7 +68,7 @@ function resolveSrc(src, baseUrl) {
68
68
  * not stall waiting on the chunk after the HTML swap.
69
69
  */
70
70
  export function pageAssetURLs(html, baseUrl, loaded) {
71
- const doc = new DOMParser().parseFromString(html, 'text/html');
71
+ const doc = typeof html === 'string' ? new DOMParser().parseFromString(html, 'text/html') : html;
72
72
  const out = [];
73
73
  const seen = new Set();
74
74
  const consider = (src) => {
@@ -153,13 +153,27 @@ const SCROLL_HISTORY_MAX = 50;
153
153
  const prefetchedAssets = new Set();
154
154
  const PREFETCHED_ASSETS_MAX = 128;
155
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 = '';
156
166
  let prefetchTimers = new Map();
157
167
  let prefetchObserver = null;
158
168
  let loadingOverlay = [];
169
+ let loadingTimer;
159
170
  /** Output prefix of intercepting-route fragments (see the compiler's parallel.go). */
160
171
  const INTERCEPT_PREFIX = '_krate/i';
161
- const TRANSITION_MS = 150;
162
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';
163
177
  function now() {
164
178
  return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();
165
179
  }
@@ -241,6 +255,14 @@ function setStatus(next) {
241
255
  if (status === next)
242
256
  return;
243
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
+ }
244
266
  emit();
245
267
  }
246
268
  /**
@@ -324,14 +346,64 @@ function cacheTake(key) {
324
346
  export function invalidatePrefetchCache(url) {
325
347
  // A prefetch still in flight started before the data changed: forgetting it
326
348
  // keeps its (stale) response out of the cache.
349
+ cacheGen++;
327
350
  if (url === undefined) {
328
351
  prefetchCache.clear();
329
352
  prefetchInflight.clear();
353
+ historyDocs.clear();
330
354
  return;
331
355
  }
332
356
  const key = cacheKey(url);
333
357
  prefetchCache.delete(key);
334
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
+ });
335
407
  }
336
408
  function isHTMLType(ct) {
337
409
  return /text\/html|application\/xhtml\+xml/i.test(ct);
@@ -339,16 +411,33 @@ function isHTMLType(ct) {
339
411
  function looksLikeHTML(body) {
340
412
  return /^\s*(<!doctype html|<html|<head|<body)/i.test(body);
341
413
  }
342
- function prefetchAsset(url) {
414
+ function prefetchAsset(url, as = 'script') {
343
415
  if (prefetchedAssets.has(url) || prefetchedAssets.size >= PREFETCHED_ASSETS_MAX)
344
416
  return;
345
417
  prefetchedAssets.add(url);
346
418
  const link = document.createElement('link');
347
419
  link.rel = 'prefetch';
348
- link.as = 'script';
420
+ link.as = as;
349
421
  link.href = url;
350
422
  document.head.appendChild(link);
351
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
+ }
352
441
  /**
353
442
  * The scripts this document already has: its script tags, and every resource
354
443
  * it fetched, which includes the island modules an earlier client-side
@@ -390,7 +479,12 @@ function prefetchPage(url) {
390
479
  if (prefetchInflight.get(key) !== p)
391
480
  return;
392
481
  cachePut(key, { html, url: finalUrl, status: res.status, at: now() });
393
- for (const asset of pageAssetURLs(html, finalUrl, loadedAssetURLs()))
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()))
394
488
  prefetchAsset(asset);
395
489
  })
396
490
  .catch(() => {
@@ -457,19 +551,27 @@ function idle(fn) {
457
551
  else
458
552
  setTimeout(fn, 50);
459
553
  }
460
- function prefetchHoverHandler(e) {
554
+ /** The prefetchable link an event targets and its absolute URL. */
555
+ function prefetchTarget(e) {
461
556
  const t = e.target;
462
557
  if (!t || typeof t.closest !== 'function')
463
- return;
558
+ return null;
464
559
  const a = t.closest('a[data-prefetch]');
465
560
  if (!a || !shouldPrefetch(a) || !isLocalLink(a) || savingData())
466
- return;
561
+ return null;
467
562
  const href = a.getAttribute('href');
468
563
  if (!href)
469
- return;
564
+ return null;
470
565
  const url = new URL(href, location.href).href;
471
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)
472
573
  return;
574
+ const { a, url } = hit;
473
575
  const existing = prefetchTimers.get(a);
474
576
  if (existing)
475
577
  clearTimeout(existing);
@@ -479,6 +581,22 @@ function prefetchHoverHandler(e) {
479
581
  }, PREFETCH_DELAY);
480
582
  prefetchTimers.set(a, timer);
481
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'];
482
600
  function observePrefetchLinks() {
483
601
  viewportPrefetched = 0;
484
602
  if (!prefetchObserver || savingData())
@@ -491,6 +609,8 @@ function observePrefetchLinks() {
491
609
  function setupPrefetch() {
492
610
  document.addEventListener('mouseover', prefetchHoverHandler);
493
611
  document.addEventListener('focusin', prefetchHoverHandler);
612
+ for (const name of PRESS_EVENTS)
613
+ document.addEventListener(name, prefetchPressHandler, { passive: true });
494
614
  if (typeof IntersectionObserver !== 'undefined') {
495
615
  prefetchObserver = new IntersectionObserver((entries) => {
496
616
  for (const entry of entries) {
@@ -583,33 +703,34 @@ function supportsViewTransitions() {
583
703
  function appRoot(doc) {
584
704
  return (doc.getElementById('root') || doc.body);
585
705
  }
586
- // While a fetch is in flight: overlay the loading.tsx template (if the page
587
- // 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.
588
709
  function beginTransition() {
589
- const tpl = document.querySelector('template[data-krate-loading]');
590
- 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;
591
717
  // Non-destructive loading UI: overlay the template without wiping the
592
718
  // live DOM, so the swap still sees the old tree.
593
719
  const frag = tpl.content.cloneNode(true);
594
720
  loadingOverlay = Array.from(frag.childNodes);
595
721
  document.body.appendChild(frag);
596
- }
597
- // Reduced motion: no fade at all (the overlay above is static).
598
- if (!supportsViewTransitions() && !prefersReducedMotion()) {
599
- const el = appRoot(document);
600
- el.style.transition = `opacity ${TRANSITION_MS}ms ease`;
601
- el.style.opacity = '0';
602
- }
722
+ }, LOADING_DELAY_MS);
603
723
  }
604
724
  function endTransition() {
725
+ if (loadingTimer !== undefined) {
726
+ clearTimeout(loadingTimer);
727
+ loadingTimer = undefined;
728
+ }
605
729
  for (const n of loadingOverlay) {
606
730
  if (n.parentNode)
607
731
  n.parentNode.removeChild(n);
608
732
  }
609
733
  loadingOverlay = [];
610
- const el = appRoot(document);
611
- if (el.style.opacity === '0')
612
- el.style.opacity = '';
613
734
  }
614
735
  /**
615
736
  * Apply `data-view-transition="name"` to `view-transition-name` (and
@@ -629,8 +750,30 @@ function applyViewTransitionNames(root) {
629
750
  });
630
751
  }
631
752
  // Document reconciliation
632
- /** How long a navigation waits for new stylesheets before swapping anyway. */
633
- 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
+ }
634
777
  /**
635
778
  * Diff stylesheet <link>s by absolute URL (base-path and format safe). New
636
779
  * links are inserted at the position they have in the incoming document (before
@@ -669,15 +812,7 @@ function prepareStylesheets(doc, baseUrl) {
669
812
  link.rel = 'stylesheet';
670
813
  link.href = abs;
671
814
  // Listen before insertion so a synchronous settle is not missed.
672
- pending.push(new Promise((resolve) => {
673
- const done = () => {
674
- link.removeEventListener('load', done);
675
- link.removeEventListener('error', done);
676
- resolve();
677
- };
678
- link.addEventListener('load', done);
679
- link.addEventListener('error', done);
680
- }));
815
+ pending.push(linkSettled(link));
681
816
  added.push({ link, media: link.getAttribute('media') });
682
817
  link.media = 'not all';
683
818
  if (prev) {
@@ -694,16 +829,8 @@ function prepareStylesheets(doc, baseUrl) {
694
829
  }
695
830
  prev = el;
696
831
  });
697
- let ready = Promise.resolve();
698
- if (pending.length > 0) {
699
- let timer;
700
- const timeout = new Promise((resolve) => {
701
- timer = setTimeout(resolve, STYLESHEET_TIMEOUT_MS);
702
- });
703
- ready = Promise.race([Promise.all(pending).then(() => undefined), timeout]).then(() => clearTimeout(timer));
704
- }
705
832
  return {
706
- ready,
833
+ ready: settledOrTimeout(pending),
707
834
  commit() {
708
835
  for (const { link, media } of added) {
709
836
  if (media === null)
@@ -776,6 +903,53 @@ function scriptsToLoad(doc, baseUrl) {
776
903
  });
777
904
  return out;
778
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
+ }
779
953
  function loadScript(script) {
780
954
  return new Promise((resolve) => {
781
955
  const s = document.createElement('script');
@@ -1001,8 +1175,18 @@ function fetchErrorPage(path) {
1001
1175
  })
1002
1176
  .catch(() => null);
1003
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
+ }
1004
1185
  async function loadDocument(req, signal) {
1005
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 } };
1006
1190
  if (!req.bypassCache) {
1007
1191
  const inflight = prefetchInflight.get(key);
1008
1192
  if (inflight)
@@ -1018,6 +1202,10 @@ async function loadDocument(req, signal) {
1018
1202
  return { ok: true, doc: { html: hit.html, url: target, status: hit.status } };
1019
1203
  }
1020
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();
1021
1209
  let res;
1022
1210
  try {
1023
1211
  res = await fetch(key, {
@@ -1097,9 +1285,6 @@ async function runNavigation(req) {
1097
1285
  const ctrl = new AbortController();
1098
1286
  pendingAbort = ctrl;
1099
1287
  setStatus('loading');
1100
- const hasCached = !req.bypassCache && prefetchCache.has(cacheKey(req.url));
1101
- if (!hasCached)
1102
- beginTransition();
1103
1288
  let result;
1104
1289
  try {
1105
1290
  result = await loadDocument(req, ctrl.signal);
@@ -1124,24 +1309,32 @@ async function commitDocument(loaded, req, seq) {
1124
1309
  const url = loaded.url;
1125
1310
  const newRoot = appRoot(doc);
1126
1311
  const oldRoot = appRoot(document);
1127
- // Save the position of the entry we are leaving (pop saves in the handler).
1128
- if (req.kind === 'push')
1129
- saveScroll(currentKey);
1130
- const newChain = readRouteChain(doc);
1131
- const plan = planSwap(currentChain, newChain, location.href, url, doc);
1132
1312
  // Load the incoming stylesheets before swapping so the new page (and kept
1133
- // 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.
1134
1315
  const sheets = prepareStylesheets(doc, url);
1135
- await sheets.ready;
1316
+ const preload = preloadScripts(doc, url, scriptsToLoad(doc, url));
1317
+ await Promise.all([sheets.ready, preload.ready]);
1136
1318
  if (seq !== navSeq) {
1137
1319
  sheets.abort();
1320
+ preload.remove();
1138
1321
  return;
1139
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);
1140
1331
  // A navigation that stays on the page (a query change, router.refresh())
1141
1332
  // keeps the page's islands mounted and their DOM in place; a control
1142
1333
  // focused in one of them keeps the focus. When the swap replaces the focused
1143
1334
  // element, focus moves to the same element in the new DOM.
1144
- const samePage = normPath(new URL(url, location.href).pathname) === normPath(location.pathname);
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];
1145
1338
  let focusMark = null;
1146
1339
  let focused = null;
1147
1340
  let islandJobs = [];
@@ -1201,9 +1394,13 @@ async function commitDocument(loaded, req, seq) {
1201
1394
  else if (focusMark)
1202
1395
  restoreFocus(oldRoot, focusMark);
1203
1396
  };
1204
- await runMutation(mutate);
1205
- 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();
1206
1402
  return;
1403
+ }
1207
1404
  endTransition();
1208
1405
  // History: the DOM now shows the new route, so the URL follows it before
1209
1406
  // any page script runs.
@@ -1213,6 +1410,7 @@ async function commitDocument(loaded, req, seq) {
1213
1410
  }
1214
1411
  else if (req.kind === 'replace') {
1215
1412
  scrollPositions.delete(currentKey);
1413
+ historyDocs.delete(currentKey);
1216
1414
  currentKey = newKey();
1217
1415
  history.replaceState(historyEntry(currentKey, req.state), '', url);
1218
1416
  }
@@ -1223,6 +1421,15 @@ async function commitDocument(loaded, req, seq) {
1223
1421
  else if (req.restoreKey) {
1224
1422
  currentKey = req.restoreKey;
1225
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
+ }
1226
1433
  renderedPath = pathOf(location.href);
1227
1434
  docPath = renderedPath;
1228
1435
  syncParams(doc);
@@ -1244,6 +1451,7 @@ async function commitDocument(loaded, req, seq) {
1244
1451
  keepScopes(plan.skip);
1245
1452
  const results = await Promise.all(srcs.map(loadScript));
1246
1453
  keepScopes([]);
1454
+ preload.remove();
1247
1455
  if (seq !== navSeq)
1248
1456
  return;
1249
1457
  if (results.some((ok) => !ok)) {
@@ -1323,8 +1531,8 @@ function refocus(el, sel) {
1323
1531
  * once the mutation has been applied (the transition's update callback has
1324
1532
  * run), so callers can touch the new DOM, history and focus afterwards.
1325
1533
  */
1326
- function runMutation(mutate) {
1327
- if (!supportsViewTransitions()) {
1534
+ function runMutation(mutate, animate = true) {
1535
+ if (!animate || !supportsViewTransitions()) {
1328
1536
  mutate();
1329
1537
  return Promise.resolve();
1330
1538
  }
@@ -1816,8 +2024,11 @@ function hashNavigate(url, req) {
1816
2024
  history.replaceState(historyEntry(currentKey || newKey(), req.state), '', url);
1817
2025
  }
1818
2026
  else {
2027
+ const prev = historyDocs.get(currentKey);
1819
2028
  currentKey = newKey();
1820
2029
  history.pushState(historyEntry(currentKey, req.state), '', url);
2030
+ if (prev)
2031
+ historyPut(currentKey, { ...prev, url });
1821
2032
  }
1822
2033
  }
1823
2034
  const hash = new URL(url).hash;
@@ -2107,6 +2318,7 @@ export function initRouter() {
2107
2318
  docAttrSnap = docAttrsOf(document);
2108
2319
  docPath = renderedPath;
2109
2320
  currentKey = entryKey(history.state) || newKey();
2321
+ initialKey = currentKey;
2110
2322
  if (entryKey(history.state) === undefined) {
2111
2323
  try {
2112
2324
  history.replaceState(historyEntry(currentKey, history.state), '', location.href);
@@ -2153,6 +2365,8 @@ export function destroyRouter() {
2153
2365
  window.removeEventListener('pageshow', pageshowHandler);
2154
2366
  document.removeEventListener('mouseover', prefetchHoverHandler);
2155
2367
  document.removeEventListener('focusin', prefetchHoverHandler);
2368
+ for (const name of PRESS_EVENTS)
2369
+ document.removeEventListener(name, prefetchPressHandler);
2156
2370
  for (const timer of prefetchTimers.values())
2157
2371
  clearTimeout(timer);
2158
2372
  prefetchTimers = new Map();
@@ -2166,12 +2380,16 @@ export function destroyRouter() {
2166
2380
  navSeq++;
2167
2381
  prefetchCache.clear();
2168
2382
  prefetchInflight.clear();
2383
+ historyDocs.clear();
2384
+ initialKey = '';
2385
+ cacheGen++;
2169
2386
  scrollPositions.clear();
2170
2387
  errorPageCache.clear();
2171
2388
  bootRan.clear();
2172
2389
  listeners.clear();
2173
2390
  status = 'idle';
2174
- loadingOverlay = [];
2391
+ document.documentElement.removeAttribute(NAVIGATING_ATTR);
2392
+ endTransition();
2175
2393
  currentChain = [];
2176
2394
  interceptSnapshots.clear();
2177
2395
  docPath = '';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.5.0-rc.7",
3
+ "version": "0.5.0-rc.8",
4
4
  "description": "Client-side runtime for Krate - signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",