@prunellejs/spa 0.1.1 → 0.7.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # @prunellejs/spa Reference
2
2
 
3
- > Opt-in in-place navigation: `regions()` swaps individual `<Region>` fragments from the server, and `spa()` swaps whole pages with `[data-persist]` islands (`0 B` when uninstalled).
3
+ > Opt-in in-place navigation: `regions()` swaps individual `<Region>` fragments from the server, and `spa()` swaps whole pages with `[data-persist]` islands (`0 B` when uninstalled; `spa()` adds 3.8 KB gzip to every page, `regions()` 4.0 KB gzip to the pages rendering a `<Region>`).
4
4
 
5
5
  ## Imports
6
6
 
@@ -10,11 +10,13 @@
10
10
 
11
11
  ## Partial Swaps (`regions()`)
12
12
 
13
- Pair `regions()` in `prunelle.config.ts` with `<Region name="pane" as="section" ...attrs>` from `prunelle` (server-only):
13
+ Pair `regions()` in `prunelle.config.ts` with `<Region name="pane" as="section" ...attrs>` from `prunelle` (server-only like `Head`), which renders `<section data-pru-region="pane">` (a `<div>` without `as`). Its children are read only when the page or the requested region needs them.
14
14
 
15
- - `<a href="/items?p=2" data-pru-target="results">`: sends `x-pru-region: results` (or `outer/inner` for nested regions), swaps inner HTML, updates `document.title` from `x-pru-title`, pushes history, manages focus & `aria-label` announcement, sets `aria-busy="true"` after 150 ms.
15
+ - `<a href="/items?p=2" data-pru-target="results">`: sends `x-pru-region: results`, and the server answers with the region's inner HTML alone (no layouts, no document; `ctx.region` tells `load()` which region was asked for; `vary: x-pru-region`). The client swaps it in, updates `document.title` from `x-pru-title` (the page's `<Head><title>` with the title template), pushes history (back/forward re-fetch and restore the title), moves focus to the region, announces its `aria-label`, and sets `aria-busy="true"` after 150 ms, cleared on swap or failure.
16
+ - Without JS, or when the fetch fails or the response lacks the region, the link or form loads the whole page.
16
17
  - `data-pru-append` on a targeted `<a>`: appends response HTML, removes clicked link (Load more), replaces history entry.
17
- - `<form method="get" data-pru-target="results">`: swaps on submit; add `data-pru-live` to also swap while typing (200 ms debounce, one history entry per typing burst).
18
+ - `<form method="get" data-pru-target="results">`: swaps on submit; add `data-pru-live` to also swap while typing (200 ms debounce, one history entry per typing burst, which a 1 s pause ends).
19
+ - Nested regions each take their own name. Asking for the inner one renders it alone (header `x-pru-region: results/sets`, outermost first, computed by the client); asking for the outer one renders it with a fresh inner; an outer swap drops in-flight fetches of the regions inside it.
18
20
  - `data-pru-sync="q tag"` on a link or input/select: keeps query params or field values outside the region in sync after every swap.
19
21
  - `[data-pru-prefetch]` ancestor: prefetches targeted links on hover/focus (`data-no-prefetch` opts a link out).
20
22
  - `<form method="post" data-pru-target="results">`: posts through `fetch`, follows the redirect and swaps the region from the final page; without JS it posts normally. `data-pru-live` is refused on it.
@@ -26,6 +28,13 @@ Pair `regions()` in `prunelle.config.ts` with `<Region name="pane" as="section"
26
28
  - The regions client loads only on routes whose tree renders a `<Region>`: every other page ships none of it (plugin field `regionClientEntry`).
27
29
  - Dispatches `window` event `pru:region` with `{ detail: { name, url } }`. `prunelle check` verifies every `data-pru-target` matches a `<Region>` in `src/`.
28
30
  - `data-pru-keep-scroll="<key>"` on any element: its scroll offset survives region swaps and `spa()` swaps, and is kept per history entry.
31
+ - `await refreshRegion(name)` (from `@prunellejs/spa/regions`) redraws a region of the current address from script, after a background `fetch` to an action for instance: no history entry, focus left alone, prefetch cache skipped, `pru:region` fired.
32
+
33
+ ## Mistakes
34
+
35
+ - Compile errors: `<Region>` without `name`, `data-pru-target` on anything but `<a>`/`<form>`, `data-pru-live` on a non-GET form, `data-pru-append`/`data-pru-live` without `data-pru-target`, a region inside a region of the same name.
36
+ - `prunelle check`: a `data-pru-target` naming no `<Region>` in `src/`.
37
+ - Runtime throws: two regions of one name on a page, a requested region the route does not render.
29
38
 
30
39
  ## Default: MPA plus `regions()`
31
40
 
@@ -33,8 +42,11 @@ Most apps want plain page loads (with the browser's cross-document view transiti
33
42
 
34
43
  ## Full-Page SPA Navigation (`spa()`)
35
44
 
36
- - Intercepts same-origin `<a>` clicks, diffs `<head>` stylesheets (zero-FOUC, in the order the next page serves them, every attribute kept) and meta/title/lang, preserves `[data-persist]` islands alive across navigations, focuses `<main>`/`<h1>`, and dispatches `pru:navigate`.
37
- - Sets `history.scrollRestoration = 'manual'` and restores the saved window and `data-pru-keep-scroll` offsets once on back/forward. Runs the swap in a view transition unless the user prefers reduced motion. Loads the regions client of a page it swaps to.
45
+ - Intercepts same-origin `<a>` clicks, diffs `<head>` stylesheets (zero-FOUC, in the order the next page serves them, every attribute kept) and meta/title/lang, preserves `[data-persist]` islands alive across navigations, focuses the element the URL's `#hash` names, else `<main>`/`<h1>`, announces the new title in a polite live region, and dispatches `pru:navigate`.
46
+ - Sets `history.scrollRestoration = 'manual'` and restores the saved window and `data-pru-keep-scroll` offsets once on back/forward, between two hashes of one page too. Runs the swap in a view transition unless the user prefers reduced motion. Loads the regions client of a page it swaps to.
47
+ - A link whose last path segment has an extension other than `.html` (`/files/report.pdf`) is left to the browser, and a response that is not HTML has its body cancelled before the full page load. Navigation and prefetch requests send `Accept: text/html`, and prefetch requests (page and region) also send `Purpose: prefetch`.
48
+ - A prefetch response carrying `x-pru-view: <path>` (`@prunellejs/analytics` sends it) keeps that path on its cache entry. A navigation or region swap rendered from that entry posts the page path and query to it with `navigator.sendBeacon`, before the history entry is pushed, so the page is counted although no request was made. A response without the header posts nothing.
49
+ - A navigation running over 150 ms sets `data-pru-navigating` on `<html>` until it ends (style a busy state with it). It starts loading the next page's island chunks while it waits for the stylesheets. Hover prefetch waits for the pointer to rest 80 ms on a link, focus prefetches at once, and at most 3 prefetches run at once.
38
50
  - Attributes: `data-no-spa` opts a link out; `[data-pru-prefetch]` enables hover/focus prefetch; `[data-persist]` preserves an island DOM subtree.
39
51
 
40
52
  ## Snippets
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/spa",
3
- "version": "0.1.1",
3
+ "version": "0.7.2",
4
4
  "description": "Opt-in SPA navigation with persistent islands plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,6 +26,6 @@
26
26
  "directory": "packages/plugin-spa"
27
27
  },
28
28
  "peerDependencies": {
29
- "prunelle": "^0.1.1"
29
+ "prunelle": "^0.7.2"
30
30
  }
31
31
  }
package/src/announcer.ts CHANGED
@@ -15,6 +15,9 @@ function applySrOnlyStyle(el: HTMLElement): void {
15
15
  s.border = '0'
16
16
  }
17
17
 
18
+
19
+ // A screen reader speaks a live region's change only once the region is in the page, and only when its text differs:
20
+ // the region is emptied now and filled on the next frame, so a new region, a moved one and a repeated title are all heard.
18
21
  export function announce(text: string): void {
19
22
  let region = document.getElementById(ANNOUNCER_ID)
20
23
  if (region === null) {
@@ -26,5 +29,8 @@ export function announce(text: string): void {
26
29
  applySrOnlyStyle(region)
27
30
  document.body.appendChild(region)
28
31
  }
29
- region.textContent = text
32
+ region.textContent = ''
33
+ requestAnimationFrame(() => {
34
+ region.textContent = text
35
+ })
30
36
  }
package/src/client.ts CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  import type { EntryScroll } from './swap'
9
9
  import { ANNOUNCER_ID, announce } from './announcer'
10
- import { fetchKeyOf, getCachedHtml, inflightPrefetch, isSameDocRegionState, nextDocId, prefetch, prefetchCache, setDocId } from './prefetch'
10
+ import { countView, fetchKeyOf, getCachedHtml, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, nextDocId, prefetch, prefetchCache, setDocId } from './prefetch'
11
11
  import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
12
12
 
13
13
  export { prefetch }
@@ -22,7 +22,24 @@ const PRUNELLE_BUILTIN_STYLES = new Set([
22
22
  ])
23
23
 
24
24
  // One-time token and OAuth redirect endpoints must hit the server once via normal navigation, never via SPA fetch.
25
- const SKIP_SPA_PATH_RE = /(?:^|\/)auth\/(?:oauth(?:\/|$)|verify-email(?:\/|$)|magic-link\/verify(?:\/|$))/
25
+ const SKIP_SPA_PATH_RE = /(?:^|\/)(?:oauth(?:\/|$)|verify-email(?:\/|$)|magic-link\/verify(?:\/|$))/
26
+
27
+ // A last path segment with an extension other than .html names a file the browser fetches itself: a second request through spa would run the endpoint twice.
28
+ const FILE_PATH_RE = /\/[^/]*\.(?!html$)[^/.]+$/i
29
+
30
+ function isSkippedPath(pathname: string): boolean {
31
+ if (SKIP_SPA_PATH_RE.test(pathname) || FILE_PATH_RE.test(pathname))
32
+ return true
33
+ const raw = document.querySelector('meta[name="pru-spa-skip"]')?.getAttribute('content')
34
+ if (!raw)
35
+ return false
36
+ for (const entry of raw.split(',')) {
37
+ const prefix = entry.trim()
38
+ if (prefix && (pathname === prefix || pathname.startsWith(`${prefix}/`)))
39
+ return true
40
+ }
41
+ return false
42
+ }
26
43
 
27
44
  // Inline <style> blocks present on initial document load already have their SHA-256 hashes in this document's CSP.
28
45
  const initialInlineStyles = new Set<string>(
@@ -61,14 +78,14 @@ function hasBlockedInlineStyle(nextDoc: Document, csp: string | null | undefined
61
78
  }
62
79
 
63
80
  function isEligibleLink(link: HTMLAnchorElement): URL | undefined {
64
- if (link.target || link.hasAttribute('download') || link.hasAttribute('data-no-spa'))
81
+ if (link.target || link.hasAttribute('download') || link.closest('[data-no-spa]') !== null)
65
82
  return undefined
66
83
  const url = new URL(link.href, location.href)
67
84
  if (url.origin !== location.origin)
68
85
  return undefined
69
86
  if (url.protocol !== 'http:' && url.protocol !== 'https:')
70
87
  return undefined
71
- if (SKIP_SPA_PATH_RE.test(url.pathname))
88
+ if (isSkippedPath(url.pathname))
72
89
  return undefined
73
90
  return url
74
91
  }
@@ -88,8 +105,9 @@ function resolveSuspenseTemplates(doc: Document): void {
88
105
  }
89
106
  }
90
107
 
91
- function focusPrimaryLandmark(): void {
92
- const target = document.querySelector<HTMLElement>('main') ?? document.querySelector<HTMLElement>('h1')
108
+ // Focus goes where a full page load would start it: the section a hash names, else the main landmark.
109
+ function focusPrimaryLandmark(anchor: HTMLElement | null): void {
110
+ const target = anchor ?? document.querySelector<HTMLElement>('main') ?? document.querySelector<HTMLElement>('h1')
93
111
  if (target === null)
94
112
  return
95
113
  if (!target.hasAttribute('tabindex'))
@@ -212,11 +230,11 @@ async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => voi
212
230
  }
213
231
  }
214
232
 
215
- async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ html: string, url: string, csp: string | null | undefined } | undefined> {
233
+ async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ html: string, url: string, csp: string | null | undefined, view?: string | null | undefined } | undefined> {
216
234
  const cached = getCachedHtml(fetchKey)
217
235
  if (cached !== undefined) {
218
236
  prefetchCache.delete(fetchKey)
219
- return { html: cached.html, url: cached.url, csp: cached.csp }
237
+ return { html: cached.html, url: cached.url, csp: cached.csp, view: cached.view }
220
238
  }
221
239
  const pending = inflightPrefetch.get(fetchKey)
222
240
  const prefetched = pending !== undefined ? await pending : undefined
@@ -224,16 +242,18 @@ async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ h
224
242
  return undefined
225
243
  if (prefetched !== undefined) {
226
244
  prefetchCache.delete(fetchKey)
227
- return { html: prefetched.html, url: prefetched.url, csp: prefetched.csp }
245
+ return { html: prefetched.html, url: prefetched.url, csp: prefetched.csp, view: prefetched.view }
228
246
  }
229
247
  const res = await fetch(fetchKey, {
230
- headers: { 'x-pru-spa': '1' },
248
+ headers: { 'x-pru-spa': '1', accept: HTML_ACCEPT },
231
249
  signal,
232
250
  })
233
251
  if (signal.aborted)
234
252
  return undefined
235
- if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html'))
253
+ if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
254
+ void res.body?.cancel()
236
255
  return undefined
256
+ }
237
257
  return { html: await res.text(), url: res.url || fetchKey, csp: res.headers.get('content-security-policy') }
238
258
  }
239
259
 
@@ -242,6 +262,8 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
242
262
  activeController?.abort()
243
263
  const controller = new AbortController()
244
264
  activeController = controller
265
+ const root = document.documentElement
266
+ const busy = setTimeout(() => root.setAttribute('data-pru-navigating', ''), 150)
245
267
 
246
268
  const targetUrl = new URL(url, location.href)
247
269
  const hash = targetUrl.hash
@@ -255,12 +277,19 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
255
277
  location.assign(url)
256
278
  return
257
279
  }
258
- const { html, url: finalUrl, csp } = fetched
280
+ const { html, url: finalUrl, csp, view } = fetched
281
+
282
+ const nextFullUrl = hash && !finalUrl.includes('#') ? `${finalUrl}${hash}` : finalUrl
283
+ const nextParsed = new URL(nextFullUrl, location.href)
284
+ // A server redirect may land on a foreign origin: fall back to a full navigation before touching the DOM or history.
285
+ if (nextParsed.origin !== location.origin) {
286
+ location.assign(nextFullUrl)
287
+ return
288
+ }
259
289
 
260
290
  const nextDoc = new DOMParser().parseFromString(html, 'text/html')
261
291
  resolveSuspenseTemplates(nextDoc)
262
292
 
263
- const nextFullUrl = hash && !finalUrl.includes('#') ? `${finalUrl}${hash}` : finalUrl
264
293
  if (hasBlockedInlineStyle(nextDoc, csp)) {
265
294
  if (push)
266
295
  location.assign(nextFullUrl)
@@ -269,14 +298,19 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
269
298
  return
270
299
  }
271
300
 
301
+ // The next page's island chunks start loading now, alongside its stylesheets, not a round trip after the swap.
302
+ const preloaded = new Set([...document.head.querySelectorAll('link[rel=modulepreload]')].map(l => l.getAttribute('href')))
303
+ for (const link of nextDoc.head.querySelectorAll('link[rel=modulepreload]')) {
304
+ if (!preloaded.has(link.getAttribute('href')))
305
+ document.head.append(document.importNode(link, true))
306
+ }
307
+
272
308
  const headPrep = await prepareHeadStyles(nextDoc)
273
309
  if (controller.signal.aborted) {
274
310
  headPrep.abort()
275
311
  return
276
312
  }
277
313
 
278
- const nextParsed = new URL(nextFullUrl, location.href)
279
-
280
314
  const applySwap = () => {
281
315
  if (push)
282
316
  saveScroll()
@@ -319,7 +353,14 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
319
353
  // A page module the next page loads that this one did not (regions' client) runs now: scripts of a parsed page never do.
320
354
  for (const script of nextDoc.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]'))
321
355
  void import(new URL(script.getAttribute('src') ?? '', location.href).href)
356
+ const fb = nextDoc.querySelector<HTMLScriptElement>('script[data-kui-fallback]')?.dataset.kuiFallback
357
+ if (fb && !('command' in HTMLButtonElement.prototype && 'closedBy' in HTMLDialogElement.prototype && typeof CSS !== 'undefined' && CSS.supports?.('position-area:block-end'))) {
358
+ const fbUrl = new URL(fb, location.href)
359
+ if (fbUrl.origin === location.origin)
360
+ void import(fbUrl.href)
361
+ }
322
362
 
363
+ let anchor: HTMLElement | null = null
323
364
  if (restore !== undefined) {
324
365
  restoreScroll(restore)
325
366
  }
@@ -331,7 +372,7 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
331
372
  catch {
332
373
  // Malformed percent-encoding in hash: use the raw fragment id.
333
374
  }
334
- const anchor = document.getElementById(anchorId)
375
+ anchor = document.getElementById(anchorId)
335
376
  if (anchor !== null)
336
377
  anchor.scrollIntoView()
337
378
  else
@@ -341,12 +382,13 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
341
382
  window.scrollTo(0, 0)
342
383
  }
343
384
 
344
- focusPrimaryLandmark()
385
+ focusPrimaryLandmark(anchor)
345
386
  announce(document.title)
346
387
 
347
388
  window.dispatchEvent(new CustomEvent('pru:navigate', { detail: { url: nextFullUrl } }))
348
389
  }
349
390
 
391
+ countView(view, nextParsed)
350
392
  await swapInTransition(applySwap)
351
393
  }
352
394
  catch (err) {
@@ -355,8 +397,12 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
355
397
  location.assign(url)
356
398
  }
357
399
  finally {
358
- if (activeController === controller)
400
+ clearTimeout(busy)
401
+ // A newer navigation that superseded this one owns the marker.
402
+ if (activeController === controller) {
359
403
  activeController = undefined
404
+ root.removeAttribute('data-pru-navigating')
405
+ }
360
406
  }
361
407
  }
362
408
 
@@ -395,16 +441,20 @@ if (typeof document !== 'undefined') {
395
441
  void prefetch(url.href)
396
442
  }
397
443
 
398
- document.addEventListener('pointerover', onIntent, { passive: true })
399
- document.addEventListener('focusin', onIntent, { passive: true })
444
+ listenIntent(onIntent)
400
445
 
401
446
  // A region swap moves the address too, so a later #hash entry of that address is no new page.
402
447
  window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
403
448
  window.addEventListener('popstate', (event) => {
404
449
  const nextDocKey = `${location.pathname}${location.search}`
405
- if (nextDocKey === currentDocKey)
406
- return
407
450
  const st = event.state as { __pruIdx?: number, __pruDoc?: number } | null
451
+ if (nextDocKey === currentDocKey) {
452
+ // Between two hashes of one page the browser's own restoring is off, so the entry's saved scroll goes back here.
453
+ const saved = entryScroll(st)
454
+ if (saved !== undefined)
455
+ restoreScroll(saved)
456
+ return
457
+ }
408
458
  // Only same-document region swaps belong to regions(); cross-document entries (even with __pruIdx) belong to spa().
409
459
  if (isSameDocRegionState(st))
410
460
  return
package/src/index.ts CHANGED
@@ -1,10 +1,16 @@
1
- // @prunellejs/spa — opt-in in-place navigation: `spa()` swaps whole pages and keeps persistent islands (~700 B gzip), `regions()` swaps one <Region> of a page. 0 B when uninstalled.
1
+ // @prunellejs/spa — opt-in in-place navigation: `spa()` swaps whole pages and keeps persistent islands (3.8 KB gzip), `regions()` swaps one <Region> of a page (4.0 KB gzip, on the pages with a <Region>). 0 B when uninstalled.
2
2
 
3
3
  import type { BuildPluginContext, PrunellePlugin } from 'prunelle/config'
4
4
  import { resolve } from 'node:path'
5
5
  import { definePlugin } from 'prunelle/config'
6
+ import { escAttr } from 'prunelle/server'
6
7
  import { checkRegionTargets } from './check'
7
8
 
9
+ export interface SpaOptions {
10
+ /** Path prefixes that must always perform a full browser navigation instead of an SPA swap (e.g. custom auth base paths). */
11
+ skipPaths?: readonly string[] | undefined
12
+ }
13
+
8
14
  // Shipped as a same-origin stylesheet so navigating from an island-less page to an island/Suspense page
9
15
  // never needs to inject an unhashed inline <style> tag blocked by the initial page's strict CSP.
10
16
  const SPA_ISLAND_CSS = 'pru-island,pru-slot,pru-s{display:contents}'
@@ -13,11 +19,18 @@ function emitIslandStylesheet(ctx: BuildPluginContext): void {
13
19
  ctx.addStyle(ctx.emitAsset('pru-island.css', SPA_ISLAND_CSS))
14
20
  }
15
21
 
16
- export function spa(): PrunellePlugin {
22
+ export function spa(options?: SpaOptions): PrunellePlugin {
23
+ const skipPaths = options?.skipPaths
24
+ ?.map(p => p.trim().replace(/\/+$/, ''))
25
+ .filter(p => p.length > 0)
17
26
  return definePlugin({
18
27
  name: '@prunellejs/spa',
19
28
  clientEntry: resolve(import.meta.dir, 'client.ts'),
20
- build: emitIslandStylesheet,
29
+ build(ctx) {
30
+ emitIslandStylesheet(ctx)
31
+ if (skipPaths && skipPaths.length > 0)
32
+ ctx.addHead(`<meta name="pru-spa-skip" content="${escAttr(skipPaths.join(','))}">`)
33
+ },
21
34
  })
22
35
  }
23
36
 
package/src/prefetch.ts CHANGED
@@ -10,10 +10,16 @@ export interface PrefetchEntry {
10
10
  title: string | null
11
11
  /** Response Content-Security-Policy header, used by spa() to detect blocked destination <style> tags. */
12
12
  csp?: string | null | undefined
13
+ /** The `x-pru-view` the server answered a prefetch with: where to post the page when the visitor opens it, since a cache hit makes no request for the server to count. */
14
+ view?: string | null | undefined
13
15
  }
14
16
 
17
+ export const HTML_ACCEPT = 'text/html'
15
18
  const PREFETCH_TTL = 15_000
16
19
  const PREFETCH_MAX = 8
20
+ // A prefetch past this many in flight is dropped: the click fetches the page as usual.
21
+ const PREFETCH_PARALLEL = 3
22
+ const HOVER_INTENT = 80
17
23
  export const prefetchCache = new Map<string, PrefetchEntry>()
18
24
  export const inflightPrefetch = new Map<string, Promise<PrefetchEntry | undefined>>()
19
25
 
@@ -74,11 +80,17 @@ function putCachedHtml(href: string, entry: PrefetchEntry): void {
74
80
  }
75
81
  }
76
82
 
83
+ /** Tells the server a page was opened from the cache, when it asked to be told. */
84
+ export function countView(view: string | null | undefined, url: URL): void {
85
+ if (view)
86
+ navigator.sendBeacon(view, `${url.pathname}${url.search}`)
87
+ }
88
+
77
89
  export async function prefetch(url: string, region?: string): Promise<void> {
78
90
  const clean = new URL(url, location.href)
79
91
  clean.hash = ''
80
92
  const key = fetchKeyOf(clean, region)
81
- if (getCachedHtml(key) !== undefined || inflightPrefetch.has(key))
93
+ if (getCachedHtml(key) !== undefined || inflightPrefetch.has(key) || inflightPrefetch.size >= PREFETCH_PARALLEL)
82
94
  return
83
95
  const conn = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection
84
96
  if (conn?.saveData)
@@ -86,10 +98,12 @@ export async function prefetch(url: string, region?: string): Promise<void> {
86
98
 
87
99
  const task = (async (): Promise<PrefetchEntry | undefined> => {
88
100
  try {
89
- const res = await fetch(clean.href, { headers: region === undefined ? { 'x-pru-spa': '1' } : { 'x-pru-region': region } })
90
- if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html'))
101
+ const res = await fetch(clean.href, { headers: region === undefined ? { 'x-pru-spa': '1', 'accept': HTML_ACCEPT, 'purpose': 'prefetch' } : { 'x-pru-region': region, 'purpose': 'prefetch' } })
102
+ if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
103
+ void res.body?.cancel()
91
104
  return undefined
92
- const entry: PrefetchEntry = { html: await res.text(), url: res.url || clean.href, ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), csp: res.headers.get('content-security-policy') }
105
+ }
106
+ const entry: PrefetchEntry = { html: await res.text(), url: res.url || clean.href, ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), csp: res.headers.get('content-security-policy'), view: res.headers.get('x-pru-view') }
93
107
  putCachedHtml(key, entry)
94
108
  return entry
95
109
  }
@@ -103,3 +117,14 @@ export async function prefetch(url: string, region?: string): Promise<void> {
103
117
  inflightPrefetch.set(key, task)
104
118
  await task
105
119
  }
120
+
121
+ /** Runs `run` on keyboard focus at once, and on a pointer that rests 80 ms over a target, not on one sweeping across. */
122
+ export function listenIntent(run: (event: Event) => void): void {
123
+ let timer: ReturnType<typeof setTimeout> | undefined
124
+ document.addEventListener('pointerover', (event) => {
125
+ clearTimeout(timer)
126
+ timer = setTimeout(run, HOVER_INTENT, event)
127
+ }, { passive: true })
128
+ document.addEventListener('pointerout', () => clearTimeout(timer), { passive: true })
129
+ document.addEventListener('focusin', run, { passive: true })
130
+ }
package/src/regions.ts CHANGED
@@ -11,7 +11,7 @@
11
11
  import type { PrefetchEntry } from './prefetch'
12
12
  import type { EntryScroll } from './swap'
13
13
  import { announce } from './announcer'
14
- import { fetchKeyOf, getCachedHtml, getDocId, inflightPrefetch, isSameDocRegionState, prefetch, prefetchCache } from './prefetch'
14
+ import { countView, fetchKeyOf, getCachedHtml, getDocId, inflightPrefetch, isSameDocRegionState, listenIntent, prefetch, prefetchCache } from './prefetch'
15
15
  import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
16
16
 
17
17
  const BUSY_DELAY = 150
@@ -255,6 +255,7 @@ async function swapRegion(swap: Swap): Promise<boolean> {
255
255
  return false
256
256
  if (swap.url.hash && !finalUrl.hash)
257
257
  finalUrl.hash = swap.url.hash
258
+ countView(entry.view, finalUrl)
258
259
  await apply(region, content, swap, finalUrl)
259
260
  return true
260
261
  }
@@ -382,15 +383,13 @@ if (typeof document !== 'undefined') {
382
383
  if (link === null || link.hasAttribute('data-no-prefetch') || link.closest('[data-pru-prefetch]') === null)
383
384
  return
384
385
  const url = new URL(link.href, location.href)
385
- if (url.origin === location.origin && `${url.pathname}${url.search}` !== `${location.pathname}${location.search}`)
386
- {
386
+ if (url.origin === location.origin && `${url.pathname}${url.search}` !== `${location.pathname}${location.search}`) {
387
387
  const region = findRegion(link.getAttribute('data-pru-target')!)
388
388
  if (region !== null)
389
389
  void prefetch(url.href, pathOf(region))
390
390
  }
391
391
  }
392
- document.addEventListener('pointerover', onIntent, { passive: true })
393
- document.addEventListener('focusin', onIntent, { passive: true })
392
+ listenIntent(onIntent)
394
393
 
395
394
  // Keep region state aligned when spa() swaps to another document (including popstate back to a document with prior region entries).
396
395
  window.addEventListener('pru:navigate', () => {