@prunellejs/spa 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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
 
@@ -42,8 +42,11 @@ Most apps want plain page loads (with the browser's cross-document view transiti
42
42
 
43
43
  ## Full-Page SPA Navigation (`spa()`)
44
44
 
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 `<main>`/`<h1>`, and dispatches `pru:navigate`.
46
- - 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.
47
50
  - Attributes: `data-no-spa` opts a link out; `[data-pru-prefetch]` enables hover/focus prefetch; `[data-persist]` preserves an island DOM subtree.
48
51
 
49
52
  ## Snippets
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/spa",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
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.6.0"
29
+ "prunelle": "^0.7.1"
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 }
@@ -24,8 +24,11 @@ const PRUNELLE_BUILTIN_STYLES = new Set([
24
24
  // One-time token and OAuth redirect endpoints must hit the server once via normal navigation, never via SPA fetch.
25
25
  const SKIP_SPA_PATH_RE = /(?:^|\/)(?:oauth(?:\/|$)|verify-email(?:\/|$)|magic-link\/verify(?:\/|$))/
26
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
+
27
30
  function isSkippedPath(pathname: string): boolean {
28
- if (SKIP_SPA_PATH_RE.test(pathname))
31
+ if (SKIP_SPA_PATH_RE.test(pathname) || FILE_PATH_RE.test(pathname))
29
32
  return true
30
33
  const raw = document.querySelector('meta[name="pru-spa-skip"]')?.getAttribute('content')
31
34
  if (!raw)
@@ -102,8 +105,9 @@ function resolveSuspenseTemplates(doc: Document): void {
102
105
  }
103
106
  }
104
107
 
105
- function focusPrimaryLandmark(): void {
106
- 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')
107
111
  if (target === null)
108
112
  return
109
113
  if (!target.hasAttribute('tabindex'))
@@ -226,11 +230,11 @@ async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => voi
226
230
  }
227
231
  }
228
232
 
229
- 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> {
230
234
  const cached = getCachedHtml(fetchKey)
231
235
  if (cached !== undefined) {
232
236
  prefetchCache.delete(fetchKey)
233
- return { html: cached.html, url: cached.url, csp: cached.csp }
237
+ return { html: cached.html, url: cached.url, csp: cached.csp, view: cached.view }
234
238
  }
235
239
  const pending = inflightPrefetch.get(fetchKey)
236
240
  const prefetched = pending !== undefined ? await pending : undefined
@@ -238,16 +242,18 @@ async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ h
238
242
  return undefined
239
243
  if (prefetched !== undefined) {
240
244
  prefetchCache.delete(fetchKey)
241
- return { html: prefetched.html, url: prefetched.url, csp: prefetched.csp }
245
+ return { html: prefetched.html, url: prefetched.url, csp: prefetched.csp, view: prefetched.view }
242
246
  }
243
247
  const res = await fetch(fetchKey, {
244
- headers: { 'x-pru-spa': '1' },
248
+ headers: { 'x-pru-spa': '1', accept: HTML_ACCEPT },
245
249
  signal,
246
250
  })
247
251
  if (signal.aborted)
248
252
  return undefined
249
- 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()
250
255
  return undefined
256
+ }
251
257
  return { html: await res.text(), url: res.url || fetchKey, csp: res.headers.get('content-security-policy') }
252
258
  }
253
259
 
@@ -256,6 +262,8 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
256
262
  activeController?.abort()
257
263
  const controller = new AbortController()
258
264
  activeController = controller
265
+ const root = document.documentElement
266
+ const busy = setTimeout(() => root.setAttribute('data-pru-navigating', ''), 150)
259
267
 
260
268
  const targetUrl = new URL(url, location.href)
261
269
  const hash = targetUrl.hash
@@ -269,7 +277,7 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
269
277
  location.assign(url)
270
278
  return
271
279
  }
272
- const { html, url: finalUrl, csp } = fetched
280
+ const { html, url: finalUrl, csp, view } = fetched
273
281
 
274
282
  const nextFullUrl = hash && !finalUrl.includes('#') ? `${finalUrl}${hash}` : finalUrl
275
283
  const nextParsed = new URL(nextFullUrl, location.href)
@@ -290,6 +298,13 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
290
298
  return
291
299
  }
292
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
+
293
308
  const headPrep = await prepareHeadStyles(nextDoc)
294
309
  if (controller.signal.aborted) {
295
310
  headPrep.abort()
@@ -345,6 +360,7 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
345
360
  void import(fbUrl.href)
346
361
  }
347
362
 
363
+ let anchor: HTMLElement | null = null
348
364
  if (restore !== undefined) {
349
365
  restoreScroll(restore)
350
366
  }
@@ -356,7 +372,7 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
356
372
  catch {
357
373
  // Malformed percent-encoding in hash: use the raw fragment id.
358
374
  }
359
- const anchor = document.getElementById(anchorId)
375
+ anchor = document.getElementById(anchorId)
360
376
  if (anchor !== null)
361
377
  anchor.scrollIntoView()
362
378
  else
@@ -366,12 +382,13 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
366
382
  window.scrollTo(0, 0)
367
383
  }
368
384
 
369
- focusPrimaryLandmark()
385
+ focusPrimaryLandmark(anchor)
370
386
  announce(document.title)
371
387
 
372
388
  window.dispatchEvent(new CustomEvent('pru:navigate', { detail: { url: nextFullUrl } }))
373
389
  }
374
390
 
391
+ countView(view, nextParsed)
375
392
  await swapInTransition(applySwap)
376
393
  }
377
394
  catch (err) {
@@ -380,8 +397,12 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
380
397
  location.assign(url)
381
398
  }
382
399
  finally {
383
- if (activeController === controller)
400
+ clearTimeout(busy)
401
+ // A newer navigation that superseded this one owns the marker.
402
+ if (activeController === controller) {
384
403
  activeController = undefined
404
+ root.removeAttribute('data-pru-navigating')
405
+ }
385
406
  }
386
407
  }
387
408
 
@@ -420,16 +441,20 @@ if (typeof document !== 'undefined') {
420
441
  void prefetch(url.href)
421
442
  }
422
443
 
423
- document.addEventListener('pointerover', onIntent, { passive: true })
424
- document.addEventListener('focusin', onIntent, { passive: true })
444
+ listenIntent(onIntent)
425
445
 
426
446
  // A region swap moves the address too, so a later #hash entry of that address is no new page.
427
447
  window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
428
448
  window.addEventListener('popstate', (event) => {
429
449
  const nextDocKey = `${location.pathname}${location.search}`
430
- if (nextDocKey === currentDocKey)
431
- return
432
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
+ }
433
458
  // Only same-document region swaps belong to regions(); cross-document entries (even with __pruIdx) belong to spa().
434
459
  if (isSameDocRegionState(st))
435
460
  return
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
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'
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', () => {