@krate/runtime 0.5.0-rc.1 → 0.5.0-rc.11

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 (214) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +470 -77
  22. package/dist/dom.js +18 -3
  23. package/dist/effects.js +2 -2
  24. package/dist/flight-props.d.ts +7 -0
  25. package/dist/flight-props.js +105 -0
  26. package/dist/handler-html.js +4 -4
  27. package/dist/handler-routing.d.ts +2 -23
  28. package/dist/handler-routing.js +9 -190
  29. package/dist/handler-segments.d.ts +6 -0
  30. package/dist/handler-segments.js +18 -4
  31. package/dist/head-tags.d.ts +9 -0
  32. package/dist/head-tags.js +93 -6
  33. package/dist/highlight-bind.js +1 -1
  34. package/dist/highlight.d.ts +3 -2
  35. package/dist/highlight.js +17 -12
  36. package/dist/hints.d.ts +25 -2
  37. package/dist/hints.js +147 -74
  38. package/dist/index.d.ts +2 -0
  39. package/dist/index.js +3 -0
  40. package/dist/island-swap.d.ts +47 -0
  41. package/dist/island-swap.js +635 -0
  42. package/dist/jsx-dev-runtime.d.ts +1 -1
  43. package/dist/jsx-types.d.ts +99 -3
  44. package/dist/krate-core.js +1 -1
  45. package/dist/krate-dev.js +385 -66
  46. package/dist/krate-f-actions.js +1 -1
  47. package/dist/krate-f-classes.js +1 -1
  48. package/dist/krate-f-highlight.js +1 -1
  49. package/dist/krate-f-list.js +1 -1
  50. package/dist/krate-f-navigation.js +1 -1
  51. package/dist/krate-f-router-lite.js +1 -1
  52. package/dist/krate-f-router.js +1 -1
  53. package/dist/krate-features.json +454 -0
  54. package/dist/krate-hydrate-lite.js +5 -5
  55. package/dist/krate-hydrate.js +5 -5
  56. package/dist/krate-island-swap.js +1 -0
  57. package/dist/krate-runtime.js +5 -5
  58. package/dist/list.d.ts +14 -4
  59. package/dist/list.js +4 -5
  60. package/dist/metadata.js +5 -2
  61. package/dist/navigation-react.d.ts +13 -0
  62. package/dist/navigation-react.js +86 -0
  63. package/dist/navigation.d.ts +19 -0
  64. package/dist/navigation.js +35 -0
  65. package/dist/node-server.js +3 -3
  66. package/dist/og.js +1 -1
  67. package/dist/platform.d.ts +52 -0
  68. package/dist/platform.js +57 -0
  69. package/dist/react-compat.d.ts +39 -0
  70. package/dist/react-compat.js +359 -0
  71. package/dist/react-server.d.ts +63 -0
  72. package/dist/react-server.js +125 -0
  73. package/dist/region-wire.d.ts +10 -0
  74. package/dist/region-wire.js +154 -0
  75. package/dist/request-context.js +1 -1
  76. package/dist/request-extras.d.ts +4 -0
  77. package/dist/request-extras.js +51 -0
  78. package/dist/resp.js +1 -1
  79. package/dist/route-source.d.ts +39 -0
  80. package/dist/route-source.js +532 -0
  81. package/dist/router-lite.js +3 -9
  82. package/dist/router.d.ts +1 -1
  83. package/dist/router.js +628 -98
  84. package/dist/server-handler.d.ts +69 -1
  85. package/dist/server-handler.js +515 -96
  86. package/dist/server-renderer.js +16 -7
  87. package/dist/server.d.ts +73 -16
  88. package/dist/server.js +619 -102
  89. package/dist/sha256.js +9 -9
  90. package/dist/signal.js +0 -6
  91. package/dist/site-config.d.ts +15 -0
  92. package/dist/site-config.js +28 -0
  93. package/dist/slot.d.ts +12 -0
  94. package/dist/slot.js +23 -0
  95. package/dist/ssr-core.d.ts +2 -0
  96. package/dist/ssr-core.js +12 -4
  97. package/dist/testing.d.ts +62 -0
  98. package/dist/testing.js +90 -0
  99. package/dist/use-id.js +1 -1
  100. package/package.json +28 -3
  101. package/dist/action-context.test.d.ts +0 -1
  102. package/dist/action-context.test.js +0 -72
  103. package/dist/actions.test.d.ts +0 -1
  104. package/dist/actions.test.js +0 -477
  105. package/dist/cache-adapter.test.d.ts +0 -1
  106. package/dist/cache-adapter.test.js +0 -244
  107. package/dist/cache.test.d.ts +0 -1
  108. package/dist/cache.test.js +0 -233
  109. package/dist/class-component.test.d.ts +0 -1
  110. package/dist/class-component.test.js +0 -462
  111. package/dist/class-helpers.test.d.ts +0 -1
  112. package/dist/class-helpers.test.js +0 -169
  113. package/dist/context.test.d.ts +0 -1
  114. package/dist/context.test.js +0 -57
  115. package/dist/derived.test.d.ts +0 -1
  116. package/dist/derived.test.js +0 -140
  117. package/dist/dev-overlay.test.d.ts +0 -1
  118. package/dist/dev-overlay.test.js +0 -165
  119. package/dist/discrete.test.d.ts +0 -1
  120. package/dist/discrete.test.js +0 -100
  121. package/dist/dom.test.d.ts +0 -1
  122. package/dist/dom.test.js +0 -39
  123. package/dist/effect-errors.test.d.ts +0 -1
  124. package/dist/effect-errors.test.js +0 -199
  125. package/dist/effects.test.d.ts +0 -1
  126. package/dist/effects.test.js +0 -485
  127. package/dist/events.test.d.ts +0 -1
  128. package/dist/events.test.js +0 -447
  129. package/dist/handler-html.test.d.ts +0 -1
  130. package/dist/handler-html.test.js +0 -256
  131. package/dist/handler-routing.test.d.ts +0 -1
  132. package/dist/handler-routing.test.js +0 -99
  133. package/dist/handler-segments.test.d.ts +0 -1
  134. package/dist/handler-segments.test.js +0 -217
  135. package/dist/head-tags.test.d.ts +0 -1
  136. package/dist/head-tags.test.js +0 -131
  137. package/dist/highlight-bind.test.d.ts +0 -1
  138. package/dist/highlight-bind.test.js +0 -124
  139. package/dist/highlight.test.d.ts +0 -1
  140. package/dist/highlight.test.js +0 -56
  141. package/dist/lanes.test.d.ts +0 -1
  142. package/dist/lanes.test.js +0 -59
  143. package/dist/list.test.d.ts +0 -1
  144. package/dist/list.test.js +0 -435
  145. package/dist/metadata.test.d.ts +0 -1
  146. package/dist/metadata.test.js +0 -167
  147. package/dist/navigation.test.d.ts +0 -1
  148. package/dist/navigation.test.js +0 -130
  149. package/dist/node-server.test.d.ts +0 -1
  150. package/dist/node-server.test.js +0 -492
  151. package/dist/optimistic-lanes.test.d.ts +0 -1
  152. package/dist/optimistic-lanes.test.js +0 -45
  153. package/dist/patterns.test.d.ts +0 -1
  154. package/dist/patterns.test.js +0 -125
  155. package/dist/portal.test.d.ts +0 -1
  156. package/dist/portal.test.js +0 -99
  157. package/dist/react-effects.test.d.ts +0 -1
  158. package/dist/react-effects.test.js +0 -133
  159. package/dist/react-suspense.test.d.ts +0 -1
  160. package/dist/react-suspense.test.js +0 -194
  161. package/dist/react.test.d.ts +0 -1
  162. package/dist/react.test.js +0 -60
  163. package/dist/react19.test.d.ts +0 -1
  164. package/dist/react19.test.js +0 -176
  165. package/dist/reactivity-core.test.d.ts +0 -1
  166. package/dist/reactivity-core.test.js +0 -152
  167. package/dist/reconcile.test.d.ts +0 -1
  168. package/dist/reconcile.test.js +0 -110
  169. package/dist/refs.test.d.ts +0 -1
  170. package/dist/refs.test.js +0 -257
  171. package/dist/router-layout.test.d.ts +0 -1
  172. package/dist/router-layout.test.js +0 -249
  173. package/dist/router-nav.test.d.ts +0 -1
  174. package/dist/router-nav.test.js +0 -559
  175. package/dist/router-slots.test.d.ts +0 -1
  176. package/dist/router-slots.test.js +0 -144
  177. package/dist/router-speculation.test.d.ts +0 -1
  178. package/dist/router-speculation.test.js +0 -25
  179. package/dist/router-styles.test.d.ts +0 -1
  180. package/dist/router-styles.test.js +0 -98
  181. package/dist/router.test.d.ts +0 -1
  182. package/dist/router.test.js +0 -36
  183. package/dist/server-async.test.d.ts +0 -1
  184. package/dist/server-async.test.js +0 -216
  185. package/dist/server-handler.test.d.ts +0 -1
  186. package/dist/server-handler.test.js +0 -535
  187. package/dist/server-highlight.test.d.ts +0 -1
  188. package/dist/server-highlight.test.js +0 -32
  189. package/dist/server-renderer.test.d.ts +0 -1
  190. package/dist/server-renderer.test.js +0 -266
  191. package/dist/server.test.d.ts +0 -1
  192. package/dist/server.test.js +0 -88
  193. package/dist/sha256.test.d.ts +0 -1
  194. package/dist/sha256.test.js +0 -13
  195. package/dist/signal-lanes.test.d.ts +0 -1
  196. package/dist/signal-lanes.test.js +0 -32
  197. package/dist/signal.test.d.ts +0 -1
  198. package/dist/signal.test.js +0 -68
  199. package/dist/slots.test.d.ts +0 -1
  200. package/dist/slots.test.js +0 -187
  201. package/dist/snapshots.test.d.ts +0 -1
  202. package/dist/snapshots.test.js +0 -208
  203. package/dist/ssr-core-behavior.test.d.ts +0 -1
  204. package/dist/ssr-core-behavior.test.js +0 -620
  205. package/dist/ssr-core.test.d.ts +0 -1
  206. package/dist/ssr-core.test.js +0 -324
  207. package/dist/static-memory.test.d.ts +0 -1
  208. package/dist/static-memory.test.js +0 -26
  209. package/dist/storage.test.d.ts +0 -1
  210. package/dist/storage.test.js +0 -46
  211. package/dist/suspense-actions.test.d.ts +0 -1
  212. package/dist/suspense-actions.test.js +0 -72
  213. package/dist/suspense.test.d.ts +0 -1
  214. package/dist/suspense.test.js +0 -556
package/dist/router.js CHANGED
@@ -5,6 +5,8 @@
5
5
  // place. All router state lives at module scope so `reinitRouter()` (called
6
6
  // by every page's hydration script) only refreshes per-page bindings and never
7
7
  // loses the prefetch cache, saved scroll positions or the in-flight navigation.
8
+ import { basePath, withBase } from './base-path.js';
9
+ import { siteConfig } from './site-config.js';
8
10
  /**
9
11
  * The shared runtime chunk is loaded once and must persist across SPA
10
12
  * navigations. Page-specific hydration scripts, in contrast, must be
@@ -12,15 +14,14 @@
12
14
  * removed before loading a new page and re-appended.
13
15
  */
14
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$/;
15
23
  function runtimeConfig() {
16
- return globalThis.__KRATE_CFG__ || {};
17
- }
18
- /** Normalizes the configured base path to "" or "/prefix" (no trailing slash). */
19
- function basePath() {
20
- const bp = runtimeConfig().basePath || '';
21
- if (!bp || bp === '/')
22
- return '';
23
- return '/' + bp.replace(/^\/+|\/+$/g, '');
24
+ return siteConfig();
24
25
  }
25
26
  /** Strips the base path from a pathname so route comparisons are consistent. */
26
27
  function stripBase(pathname) {
@@ -67,7 +68,7 @@ function resolveSrc(src, baseUrl) {
67
68
  * not stall waiting on the chunk after the HTML swap.
68
69
  */
69
70
  export function pageAssetURLs(html, baseUrl, loaded) {
70
- const doc = new DOMParser().parseFromString(html, 'text/html');
71
+ const doc = typeof html === 'string' ? new DOMParser().parseFromString(html, 'text/html') : html;
71
72
  const out = [];
72
73
  const seen = new Set();
73
74
  const consider = (src) => {
@@ -93,6 +94,45 @@ export function pageAssetURLs(html, baseUrl, loaded) {
93
94
  }
94
95
  // Router state (module scope, survives reinitRouter).
95
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
+ }
96
136
  let navSeq = 0;
97
137
  let pendingAbort;
98
138
  let keySeq = 0;
@@ -113,13 +153,27 @@ const SCROLL_HISTORY_MAX = 50;
113
153
  const prefetchedAssets = new Set();
114
154
  const PREFETCHED_ASSETS_MAX = 128;
115
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 = '';
116
166
  let prefetchTimers = new Map();
117
167
  let prefetchObserver = null;
118
168
  let loadingOverlay = [];
169
+ let loadingTimer;
119
170
  /** Output prefix of intercepting-route fragments (see the compiler's parallel.go). */
120
171
  const INTERCEPT_PREFIX = '_krate/i';
121
- const TRANSITION_MS = 150;
122
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';
123
177
  function now() {
124
178
  return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now();
125
179
  }
@@ -176,6 +230,9 @@ function snapshot() {
176
230
  }
177
231
  /** Current router state (pathname without base path, search, hash, status). */
178
232
  export function getNavigationState() {
233
+ const live = liveRouter();
234
+ if (live)
235
+ return live.getState();
179
236
  if (typeof location === 'undefined') {
180
237
  return { url: '', pathname: '/', search: '', hash: '', status: 'idle' };
181
238
  }
@@ -198,6 +255,14 @@ function setStatus(next) {
198
255
  if (status === next)
199
256
  return;
200
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
+ }
201
266
  emit();
202
267
  }
203
268
  /**
@@ -207,6 +272,9 @@ function setStatus(next) {
207
272
  * with getNavigationState().
208
273
  */
209
274
  export function subscribeNavigation(fn) {
275
+ const live = liveRouter();
276
+ if (live)
277
+ return live.subscribe(fn);
210
278
  listeners.add(fn);
211
279
  return () => {
212
280
  listeners.delete(fn);
@@ -278,14 +346,64 @@ function cacheTake(key) {
278
346
  export function invalidatePrefetchCache(url) {
279
347
  // A prefetch still in flight started before the data changed: forgetting it
280
348
  // keeps its (stale) response out of the cache.
349
+ cacheGen++;
281
350
  if (url === undefined) {
282
351
  prefetchCache.clear();
283
352
  prefetchInflight.clear();
353
+ historyDocs.clear();
284
354
  return;
285
355
  }
286
356
  const key = cacheKey(url);
287
357
  prefetchCache.delete(key);
288
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
+ });
289
407
  }
290
408
  function isHTMLType(ct) {
291
409
  return /text\/html|application\/xhtml\+xml/i.test(ct);
@@ -293,16 +411,50 @@ function isHTMLType(ct) {
293
411
  function looksLikeHTML(body) {
294
412
  return /^\s*(<!doctype html|<html|<head|<body)/i.test(body);
295
413
  }
296
- function prefetchAsset(url) {
414
+ function prefetchAsset(url, as = 'script') {
297
415
  if (prefetchedAssets.has(url) || prefetchedAssets.size >= PREFETCHED_ASSETS_MAX)
298
416
  return;
299
417
  prefetchedAssets.add(url);
300
418
  const link = document.createElement('link');
301
419
  link.rel = 'prefetch';
302
- link.as = 'script';
420
+ link.as = as;
303
421
  link.href = url;
304
422
  document.head.appendChild(link);
305
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
+ }
306
458
  function prefetchPage(url) {
307
459
  const key = cacheKey(url);
308
460
  const cached = prefetchCache.get(key);
@@ -327,9 +479,12 @@ function prefetchPage(url) {
327
479
  if (prefetchInflight.get(key) !== p)
328
480
  return;
329
481
  cachePut(key, { html, url: finalUrl, status: res.status, at: now() });
330
- const loaded = new Set();
331
- document.querySelectorAll('script[src]').forEach((s) => loaded.add(s.src));
332
- 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()))
333
488
  prefetchAsset(asset);
334
489
  })
335
490
  .catch(() => {
@@ -369,6 +524,24 @@ function shouldPrefetch(a) {
369
524
  const v = a.getAttribute('data-prefetch');
370
525
  return a.hasAttribute('data-prefetch') && v !== 'false' && v !== '0';
371
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
+ }
372
545
  // Above-the-fold/viewport prefetch is deferred to idle time so it never
373
546
  // competes with first paint; hover/focus keeps the 200ms intent debounce.
374
547
  function idle(fn) {
@@ -378,19 +551,27 @@ function idle(fn) {
378
551
  else
379
552
  setTimeout(fn, 50);
380
553
  }
381
- function prefetchHoverHandler(e) {
554
+ /** The prefetchable link an event targets and its absolute URL. */
555
+ function prefetchTarget(e) {
382
556
  const t = e.target;
383
557
  if (!t || typeof t.closest !== 'function')
384
- return;
558
+ return null;
385
559
  const a = t.closest('a[data-prefetch]');
386
- if (!a || !shouldPrefetch(a) || !isLocalLink(a))
387
- return;
560
+ if (!a || !shouldPrefetch(a) || !isLocalLink(a) || savingData())
561
+ return null;
388
562
  const href = a.getAttribute('href');
389
563
  if (!href)
390
- return;
564
+ return null;
391
565
  const url = new URL(href, location.href).href;
392
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)
393
573
  return;
574
+ const { a, url } = hit;
394
575
  const existing = prefetchTimers.get(a);
395
576
  if (existing)
396
577
  clearTimeout(existing);
@@ -400,17 +581,36 @@ function prefetchHoverHandler(e) {
400
581
  }, PREFETCH_DELAY);
401
582
  prefetchTimers.set(a, timer);
402
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'];
403
600
  function observePrefetchLinks() {
404
- if (!prefetchObserver)
601
+ viewportPrefetched = 0;
602
+ if (!prefetchObserver || savingData())
405
603
  return;
406
604
  document.querySelectorAll('a[data-prefetch]').forEach((a) => {
407
- if (shouldPrefetch(a))
605
+ if (wantsViewportPrefetch(a))
408
606
  prefetchObserver.observe(a);
409
607
  });
410
608
  }
411
609
  function setupPrefetch() {
412
610
  document.addEventListener('mouseover', prefetchHoverHandler);
413
611
  document.addEventListener('focusin', prefetchHoverHandler);
612
+ for (const name of PRESS_EVENTS)
613
+ document.addEventListener(name, prefetchPressHandler, { passive: true });
414
614
  if (typeof IntersectionObserver !== 'undefined') {
415
615
  prefetchObserver = new IntersectionObserver((entries) => {
416
616
  for (const entry of entries) {
@@ -418,10 +618,12 @@ function setupPrefetch() {
418
618
  continue;
419
619
  const a = entry.target;
420
620
  const href = a.getAttribute('href');
421
- if (href && isLocalLink(a) && shouldPrefetch(a)) {
621
+ if (href && isLocalLink(a) && wantsViewportPrefetch(a) && viewportPrefetched < VIEWPORT_PREFETCH_MAX && !savingData()) {
422
622
  const url = new URL(href, location.href).href;
423
- if (pathOf(url) !== renderedPath)
623
+ if (pathOf(url) !== renderedPath) {
624
+ viewportPrefetched++;
424
625
  idle(() => void prefetchPage(url));
626
+ }
425
627
  }
426
628
  prefetchObserver.unobserve(entry.target);
427
629
  }
@@ -442,23 +644,35 @@ function setupSpeculationRules() {
442
644
  // is used instead of emitting a blocked script.
443
645
  if (document.querySelector('meta[http-equiv="Content-Security-Policy" i]'))
444
646
  return;
647
+ if (savingData())
648
+ return;
445
649
  try {
446
650
  const script = document.createElement('script');
447
651
  script.type = 'speculationrules';
652
+ const bp = basePath();
448
653
  script.textContent = JSON.stringify({
449
654
  prefetch: [
450
655
  {
451
656
  where: {
452
657
  and: [
453
- { href_matches: '/*' },
454
- { not: { href_matches: '/__krate/*' } },
455
- { not: { href_matches: '/api/*' } },
658
+ { href_matches: bp + '/*' },
659
+ { not: { href_matches: bp + '/__krate/*' } },
660
+ { not: { href_matches: bp + '/api/*' } },
456
661
  ],
457
662
  },
458
663
  eagerness: 'moderate',
459
664
  },
460
665
  ],
461
666
  });
667
+ // A CSP sent as a header cannot be read from here: when it blocks the
668
+ // inline script, drop it and leave prefetching to the JS path.
669
+ const onViolation = (e) => {
670
+ if (e && e.blockedURI === 'inline' && String(e.effectiveDirective || e.violatedDirective || '').startsWith('script-src')) {
671
+ script.remove();
672
+ document.removeEventListener('securitypolicyviolation', onViolation);
673
+ }
674
+ };
675
+ document.addEventListener('securitypolicyviolation', onViolation);
462
676
  document.head.appendChild(script);
463
677
  }
464
678
  catch {
@@ -489,33 +703,34 @@ function supportsViewTransitions() {
489
703
  function appRoot(doc) {
490
704
  return (doc.getElementById('root') || doc.body);
491
705
  }
492
- // While a fetch is in flight: overlay the loading.tsx template (if the page
493
- // 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.
494
709
  function beginTransition() {
495
- const tpl = document.querySelector('template[data-krate-loading]');
496
- 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;
497
717
  // Non-destructive loading UI: overlay the template without wiping the
498
718
  // live DOM, so the swap still sees the old tree.
499
719
  const frag = tpl.content.cloneNode(true);
500
720
  loadingOverlay = Array.from(frag.childNodes);
501
721
  document.body.appendChild(frag);
502
- }
503
- // Reduced motion: no fade at all (the overlay above is static).
504
- if (!supportsViewTransitions() && !prefersReducedMotion()) {
505
- const el = appRoot(document);
506
- el.style.transition = `opacity ${TRANSITION_MS}ms ease`;
507
- el.style.opacity = '0';
508
- }
722
+ }, LOADING_DELAY_MS);
509
723
  }
510
724
  function endTransition() {
725
+ if (loadingTimer !== undefined) {
726
+ clearTimeout(loadingTimer);
727
+ loadingTimer = undefined;
728
+ }
511
729
  for (const n of loadingOverlay) {
512
730
  if (n.parentNode)
513
731
  n.parentNode.removeChild(n);
514
732
  }
515
733
  loadingOverlay = [];
516
- const el = appRoot(document);
517
- if (el.style.opacity === '0')
518
- el.style.opacity = '';
519
734
  }
520
735
  /**
521
736
  * Apply `data-view-transition="name"` to `view-transition-name` (and
@@ -535,8 +750,30 @@ function applyViewTransitionNames(root) {
535
750
  });
536
751
  }
537
752
  // Document reconciliation
538
- /** How long a navigation waits for new stylesheets before swapping anyway. */
539
- 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(() => { }), timeout]).then(() => clearTimeout(timer));
776
+ }
540
777
  /**
541
778
  * Diff stylesheet <link>s by absolute URL (base-path and format safe). New
542
779
  * links are inserted at the position they have in the incoming document (before
@@ -575,15 +812,7 @@ function prepareStylesheets(doc, baseUrl) {
575
812
  link.rel = 'stylesheet';
576
813
  link.href = abs;
577
814
  // Listen before insertion so a synchronous settle is not missed.
578
- pending.push(new Promise((resolve) => {
579
- const done = () => {
580
- link.removeEventListener('load', done);
581
- link.removeEventListener('error', done);
582
- resolve();
583
- };
584
- link.addEventListener('load', done);
585
- link.addEventListener('error', done);
586
- }));
815
+ pending.push(linkSettled(link));
587
816
  added.push({ link, media: link.getAttribute('media') });
588
817
  link.media = 'not all';
589
818
  if (prev) {
@@ -600,16 +829,8 @@ function prepareStylesheets(doc, baseUrl) {
600
829
  }
601
830
  prev = el;
602
831
  });
603
- let ready = Promise.resolve();
604
- if (pending.length > 0) {
605
- let timer;
606
- const timeout = new Promise((resolve) => {
607
- timer = setTimeout(resolve, STYLESHEET_TIMEOUT_MS);
608
- });
609
- ready = Promise.race([Promise.all(pending).then(() => undefined), timeout]).then(() => clearTimeout(timer));
610
- }
611
832
  return {
612
- ready,
833
+ ready: settledOrTimeout(pending),
613
834
  commit() {
614
835
  for (const { link, media } of added) {
615
836
  if (media === null)
@@ -632,6 +853,36 @@ function reconcileHeadMeta(doc) {
632
853
  document.head.appendChild(document.importNode(el, true));
633
854
  });
634
855
  }
856
+ let docAttrSnap = null;
857
+ function attrsOf(el) {
858
+ const out = {};
859
+ if (el)
860
+ for (const a of Array.from(el.attributes))
861
+ out[a.name] = a.value;
862
+ return out;
863
+ }
864
+ function docAttrsOf(d) {
865
+ return { html: attrsOf(d.documentElement), body: attrsOf(d.body) };
866
+ }
867
+ function reconcileDocAttrs(doc) {
868
+ const prev = docAttrSnap ?? docAttrsOf(document);
869
+ const next = docAttrsOf(doc);
870
+ const apply = (target, before, after) => {
871
+ if (!target)
872
+ return;
873
+ for (const name of new Set([...Object.keys(before), ...Object.keys(after)])) {
874
+ if (before[name] === after[name])
875
+ continue;
876
+ if (after[name] === undefined)
877
+ target.removeAttribute(name);
878
+ else
879
+ target.setAttribute(name, after[name]);
880
+ }
881
+ };
882
+ apply(document.documentElement, prev.html, next.html);
883
+ apply(document.body, prev.body, next.body);
884
+ docAttrSnap = next;
885
+ }
635
886
  function scriptsToLoad(doc, baseUrl) {
636
887
  const keep = new Set();
637
888
  document.querySelectorAll('script[src]:not([data-krate-spa])').forEach((s) => keep.add(s.src));
@@ -652,15 +903,66 @@ function scriptsToLoad(doc, baseUrl) {
652
903
  });
653
904
  return out;
654
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
+ }
655
953
  function loadScript(script) {
656
954
  return new Promise((resolve) => {
657
955
  const s = document.createElement('script');
658
956
  s.src = script.src;
659
957
  if (script.module)
660
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;
661
963
  // Only page scripts are disposable across navigations; the shared runtime
662
- // chunk stays in place.
663
- if (!RUNTIME_CHUNK_RE.test(script.src))
964
+ // and component chunks stay in place.
965
+ if (!PERSISTENT_SCRIPT_RE.test(script.src))
664
966
  s.setAttribute('data-krate-spa', '');
665
967
  s.onload = () => resolve(true);
666
968
  s.onerror = () => resolve(false);
@@ -723,6 +1025,71 @@ function applyScroll(url, req) {
723
1025
  window.scrollTo(0, 0);
724
1026
  }
725
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
+ }
726
1093
  /** Move focus to the content root after navigation (a11y). */
727
1094
  function focusContent() {
728
1095
  const active = document.activeElement;
@@ -808,8 +1175,18 @@ function fetchErrorPage(path) {
808
1175
  })
809
1176
  .catch(() => null);
810
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
+ }
811
1185
  async function loadDocument(req, signal) {
812
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 } };
813
1190
  if (!req.bypassCache) {
814
1191
  const inflight = prefetchInflight.get(key);
815
1192
  if (inflight)
@@ -825,6 +1202,10 @@ async function loadDocument(req, signal) {
825
1202
  return { ok: true, doc: { html: hit.html, url: target, status: hit.status } };
826
1203
  }
827
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();
828
1209
  let res;
829
1210
  try {
830
1211
  res = await fetch(key, {
@@ -904,9 +1285,6 @@ async function runNavigation(req) {
904
1285
  const ctrl = new AbortController();
905
1286
  pendingAbort = ctrl;
906
1287
  setStatus('loading');
907
- const hasCached = !req.bypassCache && prefetchCache.has(cacheKey(req.url));
908
- if (!hasCached)
909
- beginTransition();
910
1288
  let result;
911
1289
  try {
912
1290
  result = await loadDocument(req, ctrl.signal);
@@ -931,20 +1309,41 @@ async function commitDocument(loaded, req, seq) {
931
1309
  const url = loaded.url;
932
1310
  const newRoot = appRoot(doc);
933
1311
  const oldRoot = appRoot(document);
934
- // Save the position of the entry we are leaving (pop saves in the handler).
935
- if (req.kind === 'push')
936
- saveScroll(currentKey);
937
- const newChain = readRouteChain(doc);
938
- const plan = planSwap(currentChain, newChain, location.href, url, doc);
939
1312
  // Load the incoming stylesheets before swapping so the new page (and kept
940
- // 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.
941
1315
  const sheets = prepareStylesheets(doc, url);
942
- await sheets.ready;
1316
+ const preload = preloadScripts(doc, url, scriptsToLoad(doc, url));
1317
+ await Promise.all([sheets.ready, preload.ready]);
943
1318
  if (seq !== navSeq) {
944
1319
  sheets.abort();
1320
+ preload.remove();
945
1321
  return;
946
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 = [];
947
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;
948
1347
  const title = doc.querySelector('title');
949
1348
  if (title)
950
1349
  document.title = title.textContent || '';
@@ -953,35 +1352,55 @@ async function commitDocument(loaded, req, seq) {
953
1352
  g.krateDisposeExcept(plan.keep);
954
1353
  else if (typeof g.disposeAll === 'function')
955
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
+ };
956
1366
  if (plan.region) {
957
1367
  // Only the deepest boundary that differs is replaced; the kept layouts'
958
1368
  // DOM (and its state, focus and scroll containers) stays in place.
959
1369
  const { live, next } = plan.region;
960
- clearBetween(live[0], live[1]);
961
- const nodes = between(next[0], next[1]).map((n) => document.importNode(n, true));
962
- for (const n of nodes)
963
- live[1].parentNode.insertBefore(n, live[1]);
1370
+ islandJobs = swapNodes(live[0].parentNode, live[0], live[1], imported(between(next[0], next[1])), opts);
964
1371
  for (const sl of plan.slots) {
965
- clearBetween(sl.live[0], sl.live[1]);
966
- for (const n of between(sl.next[0], sl.next[1]))
967
- 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));
968
1373
  }
969
1374
  syncLoadingTemplate(oldRoot, newRoot);
970
1375
  }
971
1376
  else {
972
- const nodes = Array.from(newRoot.childNodes).map((n) => document.importNode(n, true));
973
- oldRoot.replaceChildren(...nodes);
1377
+ islandJobs = swapNodes(oldRoot, null, null, imported(Array.from(newRoot.childNodes)), opts);
974
1378
  }
975
1379
  currentChain = plan.chain;
976
1380
  // Detached slot content of earlier intercepts belonged to the old page.
1381
+ interceptSnapshots.forEach((snap) => unmountIslands(snap.nodes));
977
1382
  interceptSnapshots.clear();
978
1383
  sheets.commit();
979
1384
  reconcileHeadMeta(doc);
1385
+ reconcileDocAttrs(doc);
980
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);
981
1396
  };
982
- await runMutation(mutate);
983
- 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();
984
1402
  return;
1403
+ }
985
1404
  endTransition();
986
1405
  // History: the DOM now shows the new route, so the URL follows it before
987
1406
  // any page script runs.
@@ -991,6 +1410,7 @@ async function commitDocument(loaded, req, seq) {
991
1410
  }
992
1411
  else if (req.kind === 'replace') {
993
1412
  scrollPositions.delete(currentKey);
1413
+ historyDocs.delete(currentKey);
994
1414
  currentKey = newKey();
995
1415
  history.replaceState(historyEntry(currentKey, req.state), '', url);
996
1416
  }
@@ -1001,6 +1421,15 @@ async function commitDocument(loaded, req, seq) {
1001
1421
  else if (req.restoreKey) {
1002
1422
  currentKey = req.restoreKey;
1003
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
+ }
1004
1433
  renderedPath = pathOf(location.href);
1005
1434
  docPath = renderedPath;
1006
1435
  syncParams(doc);
@@ -1022,6 +1451,7 @@ async function commitDocument(loaded, req, seq) {
1022
1451
  keepScopes(plan.skip);
1023
1452
  const results = await Promise.all(srcs.map(loadScript));
1024
1453
  keepScopes([]);
1454
+ preload.remove();
1025
1455
  if (seq !== navSeq)
1026
1456
  return;
1027
1457
  if (results.some((ok) => !ok)) {
@@ -1033,14 +1463,76 @@ async function commitDocument(loaded, req, seq) {
1033
1463
  }
1034
1464
  refreshPageBindings();
1035
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
+ }
1036
1528
  }
1037
1529
  /**
1038
1530
  * Runs the DOM mutation, inside a View Transition when supported. Resolves
1039
1531
  * once the mutation has been applied (the transition's update callback has
1040
1532
  * run), so callers can touch the new DOM, history and focus afterwards.
1041
1533
  */
1042
- function runMutation(mutate) {
1043
- if (!supportsViewTransitions()) {
1534
+ function runMutation(mutate, animate = true) {
1535
+ if (!animate || !supportsViewTransitions()) {
1044
1536
  mutate();
1045
1537
  return Promise.resolve();
1046
1538
  }
@@ -1055,6 +1547,11 @@ function runMutation(mutate) {
1055
1547
  const vt = document.startViewTransition(once);
1056
1548
  if (vt && vt.finished && typeof vt.finished.catch === 'function')
1057
1549
  vt.finished.catch(() => { });
1550
+ // A newer navigation skips this transition; ready then rejects with
1551
+ // "Transition was skipped", which would otherwise surface as an unhandled
1552
+ // rejection on the page.
1553
+ if (vt && vt.ready && typeof vt.ready.catch === 'function')
1554
+ vt.ready.catch(() => { });
1058
1555
  const done = vt && vt.updateCallbackDone;
1059
1556
  if (done && typeof done.then === 'function') {
1060
1557
  return done.then(() => once(), () => once());
@@ -1110,6 +1607,7 @@ function between(start, end) {
1110
1607
  }
1111
1608
  function clearBetween(start, end) {
1112
1609
  const dispose = globalThis.disposeNode;
1610
+ unmountIslands(between(start, end));
1113
1611
  for (const n of between(start, end)) {
1114
1612
  n.parentNode.removeChild(n);
1115
1613
  if (typeof dispose === 'function')
@@ -1526,8 +2024,11 @@ function hashNavigate(url, req) {
1526
2024
  history.replaceState(historyEntry(currentKey || newKey(), req.state), '', url);
1527
2025
  }
1528
2026
  else {
2027
+ const prev = historyDocs.get(currentKey);
1529
2028
  currentKey = newKey();
1530
2029
  history.pushState(historyEntry(currentKey, req.state), '', url);
2030
+ if (prev)
2031
+ historyPut(currentKey, { ...prev, url });
1531
2032
  }
1532
2033
  }
1533
2034
  const hash = new URL(url).hash;
@@ -1689,12 +2190,15 @@ function refreshPageBindings() {
1689
2190
  // Mark the page scripts as disposable so they're removed and re-executed
1690
2191
  // against the fresh DOM on the next navigation.
1691
2192
  document.querySelectorAll('script[src]').forEach((s) => {
1692
- if (!RUNTIME_CHUNK_RE.test(s.src))
2193
+ if (!PERSISTENT_SCRIPT_RE.test(s.src))
1693
2194
  s.setAttribute('data-krate-spa', '');
1694
2195
  });
1695
2196
  }
1696
2197
  // Public API
1697
2198
  function refresh() {
2199
+ const live = liveRouter();
2200
+ if (live)
2201
+ return live.refresh();
1698
2202
  if (!initialized || typeof location === 'undefined') {
1699
2203
  if (typeof location !== 'undefined')
1700
2204
  location.reload();
@@ -1711,19 +2215,31 @@ function refresh() {
1711
2215
  }
1712
2216
  function push(url, opts = {}) {
1713
2217
  if (!initialized) {
1714
- if (typeof location !== 'undefined')
1715
- location.assign(url);
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')
2225
+ location.assign(withBase(url));
1716
2226
  return Promise.resolve();
1717
2227
  }
1718
- return start({ url, kind: 'push', scroll: opts.scroll !== false, state: opts.state });
2228
+ return start({ url: withBase(url), kind: 'push', scroll: opts.scroll !== false, state: opts.state });
1719
2229
  }
1720
2230
  function replace(url, opts = {}) {
1721
2231
  if (!initialized) {
1722
- if (typeof location !== 'undefined')
1723
- location.replace(url);
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')
2239
+ location.replace(withBase(url));
1724
2240
  return Promise.resolve();
1725
2241
  }
1726
- return start({ url, kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
2242
+ return start({ url: withBase(url), kind: 'replace', scroll: opts.scroll !== false, state: opts.state });
1727
2243
  }
1728
2244
  /**
1729
2245
  * The router API. Every navigation method resolves once the new route's DOM
@@ -1748,11 +2264,14 @@ export const krateRouter = {
1748
2264
  },
1749
2265
  refresh,
1750
2266
  prefetch(url) {
2267
+ const live = liveRouter();
2268
+ if (live)
2269
+ return live.prefetch(url);
1751
2270
  if (!initialized || typeof location === 'undefined')
1752
2271
  return Promise.resolve();
1753
2272
  let u;
1754
2273
  try {
1755
- u = new URL(url, location.href);
2274
+ u = new URL(withBase(url), location.href);
1756
2275
  }
1757
2276
  catch {
1758
2277
  return Promise.resolve();
@@ -1771,15 +2290,15 @@ export const krateRouter = {
1771
2290
  * client-side, true when a full navigation was triggered.
1772
2291
  */
1773
2292
  export function navigate(url, opts = {}) {
1774
- if (initialized) {
2293
+ if (initialized || liveRouter()) {
1775
2294
  void (opts.replace ? replace(url, opts) : push(url, opts));
1776
2295
  return false;
1777
2296
  }
1778
2297
  if (typeof location !== 'undefined') {
1779
2298
  if (opts.replace)
1780
- location.replace(url);
2299
+ location.replace(withBase(url));
1781
2300
  else
1782
- location.assign(url);
2301
+ location.assign(withBase(url));
1783
2302
  }
1784
2303
  return true;
1785
2304
  }
@@ -1791,12 +2310,15 @@ export function initRouter() {
1791
2310
  return;
1792
2311
  }
1793
2312
  initialized = true;
2313
+ globalThis[LIVE_ROUTER] = krateRouter;
1794
2314
  // The first document ran its own boot scripts.
1795
2315
  document.querySelectorAll('script[data-krate-boot]').forEach((s) => bootRan.add(s.textContent || ''));
1796
2316
  renderedPath = pathOf(location.href);
1797
2317
  currentChain = readRouteChain(document);
2318
+ docAttrSnap = docAttrsOf(document);
1798
2319
  docPath = renderedPath;
1799
2320
  currentKey = entryKey(history.state) || newKey();
2321
+ initialKey = currentKey;
1800
2322
  if (entryKey(history.state) === undefined) {
1801
2323
  try {
1802
2324
  history.replaceState(historyEntry(currentKey, history.state), '', location.href);
@@ -1833,6 +2355,8 @@ export function destroyRouter() {
1833
2355
  if (!initialized)
1834
2356
  return;
1835
2357
  initialized = false;
2358
+ if (globalThis[LIVE_ROUTER] === krateRouter)
2359
+ delete globalThis[LIVE_ROUTER];
1836
2360
  document.removeEventListener('click', clickHandler);
1837
2361
  document.removeEventListener('submit', submitHandler);
1838
2362
  window.removeEventListener('popstate', popstateHandler);
@@ -1841,6 +2365,8 @@ export function destroyRouter() {
1841
2365
  window.removeEventListener('pageshow', pageshowHandler);
1842
2366
  document.removeEventListener('mouseover', prefetchHoverHandler);
1843
2367
  document.removeEventListener('focusin', prefetchHoverHandler);
2368
+ for (const name of PRESS_EVENTS)
2369
+ document.removeEventListener(name, prefetchPressHandler);
1844
2370
  for (const timer of prefetchTimers.values())
1845
2371
  clearTimeout(timer);
1846
2372
  prefetchTimers = new Map();
@@ -1854,12 +2380,16 @@ export function destroyRouter() {
1854
2380
  navSeq++;
1855
2381
  prefetchCache.clear();
1856
2382
  prefetchInflight.clear();
2383
+ historyDocs.clear();
2384
+ initialKey = '';
2385
+ cacheGen++;
1857
2386
  scrollPositions.clear();
1858
2387
  errorPageCache.clear();
1859
2388
  bootRan.clear();
1860
2389
  listeners.clear();
1861
2390
  status = 'idle';
1862
- loadingOverlay = [];
2391
+ document.documentElement.removeAttribute(NAVIGATING_ATTR);
2392
+ endTransition();
1863
2393
  currentChain = [];
1864
2394
  interceptSnapshots.clear();
1865
2395
  docPath = '';