@prunellejs/spa 0.7.7 → 0.9.0

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/llms.txt CHANGED
@@ -1,83 +1,35 @@
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; `spa()` adds 4.1 KB gzip to every page, `regions()` 4.6 KB gzip to the pages rendering a `<Region>`).
3
+ > Opt-in full-page SPA navigation (`spa()`) with `Element.moveBefore`-preserved `[data-persist]` islands and elements (`0 B` when uninstalled; adds the SPA client entry to every page when enabled). Partial `<Region>` swaps are built into core `prunelle` (no plugin required; `refreshRegion` is exported from `prunelle`).
4
4
 
5
5
  ## Imports
6
6
 
7
- - `@prunellejs/spa`: `spa()`, `regions()` (both return `PrunellePlugin` for `prunelle.config.ts`).
8
- - `@prunellejs/spa/regions`: `refreshRegion(name: string): Promise<void>` (redraws `<Region name>` from the current URL without touching history or focus; skips prefetch cache; rejects if region is missing or fetch fails).
7
+ - `@prunellejs/spa`: `spa(options?: SpaOptions)` (returns a `PrunellePlugin` for `prunelle.config.ts`; `skipPaths?: readonly string[]` lists path prefixes that always perform full browser navigation).
9
8
  - `@prunellejs/spa/client`: `prefetch(url: string, region?: string)` (populates the shared 8-entry / 15s prefetch cache; respects `Save-Data`).
10
9
 
11
- ## Partial Swaps (`regions()`)
10
+ ## Default: MPA plus core `<Region>`
12
11
 
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
-
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.
17
- - `data-pru-append` on a targeted `<a>`: appends response HTML, removes clicked link (Load more), replaces history entry.
18
- - `<form method="get" data-pru-target="results">`: swaps on submit, leaving empty fields out of the address (a submit button with an empty value clears its name, so `<button name="f" value="">` turns off a hidden `f`); add `data-pru-live` to also swap while typing (200 ms debounce, one history entry per typing burst, which a 1 s pause ends). Fields tied by `form="<id>"` count, and when a swap replaces the form mid-burst the form then on the page is sent.
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.
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.
21
- - `[data-pru-prefetch]` ancestor: prefetches targeted links on hover/focus (`data-no-prefetch` opts a link out).
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.
23
- - Empty fields are dropped from the URL of a GET form.
24
- - Swaps run in `document.startViewTransition` where supported, and not under `prefers-reduced-motion: reduce` nor with `navigation: { viewTransitions: false }` in `prunelle.config.ts` (it turns off `spa()`'s too). `append`, `refreshRegion()` and live typing swap without one. While a transition runs, Chrome sends every click to `<html>`: a click landing there during a swap skips the rest of the transition and is sent to the element under the pointer, so a link clicked right after a swap is not lost. Turn transitions off when a list is clicked through page after page and the fade only gets in the way.
25
- - `data-persist="<key>"` inside a swapped region, as with `spa()`: the live element takes the place of the new HTML's element of that key, so a search field keeps focus, caret, selection and what was typed during the fetch, and one region can cover a whole filtered view, field included. An `<iframe>` keeps its document where `Element.moveBefore` exists (elsewhere it reloads, and a focused field gets its focus and selection back); key it by what it shows (`data-persist={'frame-' + page}`) so it reloads only when that changes. A live element whose key the answer lacks goes; a key on two elements of one answer logs `prunelle: data-persist="<key>" is on two elements ...` and loads the whole page. Append swaps keep nothing.
26
- - Each history entry remembers the window's scroll and the scrolled regions' scroll, and back/forward restores both. A pushed swap leaves the window's scroll alone and resets the region's own scroll, unless the region carries `data-pru-keep-scroll`.
27
- - After a swap, links whose `href` matches the new URL get `aria-current="page"`, others lose it.
28
- - A `#hash` link to an element already on the page scrolls to it with no fetch when its page and query are the ones the page shows, or one Load more appended; another query fetches; after a swap the page scrolls to the URL's hash.
29
- - The regions client loads only on routes whose tree renders a `<Region>`: every other page ships none of it (plugin field `regionClientEntry`).
30
- - Dispatches `window` event `pru:region` with `{ detail: { name, url } }`. `prunelle check` verifies every `data-pru-target` matches a `<Region>` in `src/`.
31
- - `data-pru-keep-scroll="<key>"` on any element: its scroll offset survives region swaps and `spa()` swaps, and is kept per history entry.
32
- - `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.
33
-
34
- ## Mistakes
35
-
36
- - 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.
37
- - `prunelle check`: a `data-pru-target` naming no `<Region>` in `src/`.
38
- - Runtime throws: two regions of one name on a page, a requested region the route does not render.
39
-
40
- ## Default: MPA plus `regions()`
41
-
42
- Most apps want plain page loads (with the browser's cross-document view transitions) and `regions()` for the fragments that change in place. Add `spa()` only when islands must stay alive across pages (`[data-persist]`).
12
+ Most apps want plain multi-page loads (with the browser's cross-document view transitions) and core `<Region>` from `prunelle` for fragments that swap in place (ships its client only on routes rendering `<Region>`, with `refreshRegion()` exported from `prunelle`). Add `spa()` only when `[data-persist]` islands, media, or iframes must stay mounted across route changes.
43
13
 
44
14
  ## Full-Page SPA Navigation (`spa()`)
45
15
 
46
- - 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`.
47
- - 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.
48
- - 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`.
49
- - 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.
16
+ - 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/dir, preserves `[data-persist]` islands, iframes, and focused inputs alive via `Element.moveBefore` across navigations, focuses the element the URL's `#hash` names, else `<main>`/`<h1>` (unless focus is inside a persisted form field), announces the new title in a polite live region, and dispatches `pru:navigate`.
17
+ - Preserves `<script data-pru-build="...">` across navigations and verifies same-origin before dynamically importing head module scripts from the next page (e.g. core's `<Region>` client when navigating from a plain page to a `<Region>` page), so stale-build detection stays active.
18
+ - Ships `pru-island,pru-slot,pru-s{display:contents}` as an inline CSP-hashed `<style>` in `<head>` (0 extra stylesheet network requests) so navigating from an island-less page to an island or `<Suspense>` page stays CSP-safe.
19
+ - 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 or `navigation: { viewTransitions: false }` is set.
20
+ - 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 also send `Purpose: prefetch`.
21
+ - A prefetch response carrying `x-pru-view: <path>` (`@prunellejs/analytics` sends it) keeps that path on its cache entry. A navigation 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.
50
22
  - 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.
51
- - Attributes: `data-no-spa` opts a link out; `[data-pru-prefetch]` enables hover/focus prefetch; `[data-persist]` preserves an island DOM subtree.
23
+ - Attributes: `data-no-spa` opts a link out; `[data-pru-prefetch]` enables hover/focus prefetch; `[data-persist]` preserves an island or stateful DOM subtree.
52
24
 
53
- ## Snippets
25
+ ## Snippet
54
26
 
55
27
  ```ts
56
28
  // prunelle.config.ts
57
29
  import { defineConfig } from 'prunelle/config'
58
- import { regions, spa } from '@prunellejs/spa'
30
+ import { spa } from '@prunellejs/spa'
59
31
 
60
32
  export default defineConfig({
61
- plugins: [regions(), spa()],
33
+ plugins: [spa()],
62
34
  })
63
35
  ```
64
-
65
- ```tsx
66
- // src/routes/search.tsx
67
- import { Region } from 'prunelle'
68
- import type { PageProps } from 'prunelle'
69
-
70
- export default function Search({ url }: PageProps) {
71
- const q = url.searchParams.get('q') ?? ''
72
- return (
73
- <>
74
- <form method="get" data-pru-target="results" data-pru-live>
75
- <input name="q" value={q} data-pru-sync />
76
- </form>
77
- <Region name="results" aria-label="Search results">
78
- <p>Results for {q}</p>
79
- </Region>
80
- </>
81
- )
82
- }
83
- ```
package/package.json CHANGED
@@ -1,12 +1,11 @@
1
1
  {
2
2
  "name": "@prunellejs/spa",
3
- "version": "0.7.7",
3
+ "version": "0.9.0",
4
4
  "description": "Opt-in SPA navigation with persistent islands plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "sideEffects": [
8
- "./src/client.ts",
9
- "./src/regions.ts"
8
+ "./src/client.ts"
10
9
  ],
11
10
  "files": [
12
11
  "src",
@@ -14,8 +13,7 @@
14
13
  ],
15
14
  "exports": {
16
15
  ".": "./src/index.ts",
17
- "./client": "./src/client.ts",
18
- "./regions": "./src/regions.ts"
16
+ "./client": "./src/client.ts"
19
17
  },
20
18
  "engines": {
21
19
  "bun": ">=1.4.0"
@@ -26,6 +24,6 @@
26
24
  "directory": "packages/plugin-spa"
27
25
  },
28
26
  "peerDependencies": {
29
- "prunelle": "^0.7.7"
27
+ "prunelle": "^0.9.0"
30
28
  }
31
29
  }
package/src/client.ts CHANGED
@@ -1,24 +1,25 @@
1
1
  // @prunellejs/spa client bootstrap:
2
2
  // - Intercepts internal <a> clicks with AbortController cancellation (no dropped rapid clicks)
3
3
  // - Diffs <head> stylesheets (zero-FOUC load-before-remove), <html lang>, <title>, meta/canonical tags
4
- // - Preserves [data-persist] islands alive across View Transitions swaps
4
+ // - Preserves [data-persist] islands and stateful elements alive via Element.moveBefore across View Transitions swaps
5
+ // - Preserves <script data-pru-build> across navigations and verifies same-origin before importing page module scripts
5
6
  // - Restores scroll position on popstate, scrolls to #hash targets, manages focus & polite live announcements
6
7
  // - Opt-in prefetch via [data-pru-prefetch] (bounded 8-entry / 15s TTL cache, respects Save-Data)
7
8
 
8
- import type { EntryScroll } from './swap'
9
- import { ANNOUNCER_ID, announce } from './announcer'
10
- import { countView, fetchKeyOf, getCachedHtml, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, nextDocId, prefetch, prefetchCache, setDocId } from './prefetch'
11
- import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
9
+ import type { EntryScroll } from 'prunelle/internal/swap'
10
+ import { countView, fetchKeyOf, getCachedHtml, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, nextDocId, prefetch, prefetchCache, setDocId } from 'prunelle/internal/prefetch'
11
+ import { announce, ANNOUNCER_ID, entryScroll, readScrolls, replaceKeeping, restoreScroll, saveScroll, swapInTransition, syncElementAttrs, trackScroll, trustedHtml, writeScrolls } from 'prunelle/internal/swap'
12
12
 
13
13
  export { prefetch }
14
14
 
15
15
  let activeController: AbortController | undefined
16
16
  let currentDocKey = typeof location !== 'undefined' ? `${location.pathname}${location.search}` : ''
17
17
 
18
- // Framework inline styles shipped in pru-island.css so SPA navigation never injects unhashed <style> tags.
18
+ // Framework inline styles shipped in <head> so SPA navigation never injects unhashed <style> tags.
19
19
  const PRUNELLE_BUILTIN_STYLES = new Set([
20
20
  'pru-island,pru-slot{display:contents}',
21
21
  'pru-s{display:contents}',
22
+ 'pru-island,pru-slot,pru-s{display:contents}',
22
23
  ])
23
24
 
24
25
  // One-time token and OAuth redirect endpoints must hit the server once via normal navigation, never via SPA fetch.
@@ -107,12 +108,13 @@ function resolveSuspenseTemplates(doc: Document): void {
107
108
 
108
109
  function scrollToHash(hash: string): HTMLElement | null {
109
110
  if (hash.length > 1) {
110
- let id = hash.slice(1)
111
+ const raw = hash.slice(1)
112
+ let id: string
111
113
  try {
112
- id = decodeURIComponent(id)
114
+ id = decodeURIComponent(raw)
113
115
  }
114
116
  catch {
115
- // Malformed percent-encoding in hash: use the raw fragment id.
117
+ id = raw
116
118
  }
117
119
  const anchor = document.getElementById(id)
118
120
  if (anchor !== null) {
@@ -139,6 +141,51 @@ function focusPrimaryLandmark(anchor: HTMLElement | null): void {
139
141
  }
140
142
  }
141
143
 
144
+ function isFocusedPersistedField(): boolean {
145
+ const active = document.activeElement
146
+ if (active === null || active === document.body || active.closest('[data-persist]') === null)
147
+ return false
148
+ return active instanceof HTMLInputElement
149
+ || active instanceof HTMLTextAreaElement
150
+ || active instanceof HTMLSelectElement
151
+ || (active as HTMLElement).isContentEditable === true
152
+ }
153
+
154
+ /** Imports new same-origin head module scripts (e.g. core's region client) and preserves `data-pru-build` / `data-pru-runtime` across navigations. */
155
+ function syncHeadModuleScripts(nextDoc: Document): void {
156
+ const existingSrcs = new Set<string>()
157
+ let hostScript: HTMLScriptElement | null = null
158
+ for (const cur of document.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]')) {
159
+ hostScript ??= cur
160
+ const raw = cur.getAttribute('src')
161
+ if (raw)
162
+ existingSrcs.add(new URL(raw, location.href).href)
163
+ }
164
+ for (const script of nextDoc.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]')) {
165
+ const rawSrc = script.getAttribute('src')
166
+ if (!rawSrc)
167
+ continue
168
+ const scriptUrl = new URL(rawSrc, location.href)
169
+ if (scriptUrl.origin !== location.origin)
170
+ continue
171
+ const buildId = script.getAttribute('data-pru-build')
172
+ const runtimeSrc = script.getAttribute('data-pru-runtime')
173
+ if (buildId !== null && document.head.querySelector('script[data-pru-build]') === null) {
174
+ // Stamp on an existing module script (or a non-executable JSON script tag) so strict CSP + Trusted Types never block setting `script.src`.
175
+ const target = hostScript ?? document.head.appendChild(Object.assign(document.createElement('script'), { type: 'application/json' }))
176
+ target.setAttribute('data-pru-build', buildId)
177
+ if (runtimeSrc !== null && !target.hasAttribute('data-pru-runtime'))
178
+ target.setAttribute('data-pru-runtime', runtimeSrc)
179
+ }
180
+ if (!existingSrcs.has(scriptUrl.href)) {
181
+ existingSrcs.add(scriptUrl.href)
182
+ void import(scriptUrl.href).catch((err) => {
183
+ console.error('[prunelle] failed to load module script:', scriptUrl.href, err)
184
+ })
185
+ }
186
+ }
187
+ }
188
+
142
189
  async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => void, abort: () => void }> {
143
190
  const currentLinks = [...document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')]
144
191
  const currentByHref = new Map<string, HTMLLinkElement>()
@@ -208,7 +255,7 @@ async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => voi
208
255
  }
209
256
  for (const el of moved)
210
257
  el.remove()
211
- // Sync non-builtin <head> <style> tags (skipping pru-island/pru-s styles already covered by pru-island.css).
258
+ // Sync non-builtin <head> <style> tags (skipping pru-island/pru-s styles already covered in <head>).
212
259
  const nextHeadStyles = new Set<string>()
213
260
  for (const nextStyle of nextDoc.head.querySelectorAll('style')) {
214
261
  const txt = nextStyle.textContent ?? ''
@@ -306,7 +353,7 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
306
353
  return
307
354
  }
308
355
 
309
- const nextDoc = new DOMParser().parseFromString(html, 'text/html')
356
+ const nextDoc = new DOMParser().parseFromString(trustedHtml(html), 'text/html')
310
357
  resolveSuspenseTemplates(nextDoc)
311
358
 
312
359
  if (hasBlockedInlineStyle(nextDoc, csp)) {
@@ -338,27 +385,16 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
338
385
 
339
386
  const existingAnnouncer = document.getElementById(ANNOUNCER_ID)
340
387
 
341
- // Preserve live [data-persist] elements (e.g. persistent audio player or counter island) across navigations
342
- const persisted = new Map<string, Element>()
343
- for (const el of document.querySelectorAll('[data-persist]')) {
344
- const key = el.getAttribute('data-persist')
345
- if (key)
346
- persisted.set(key, el)
347
- }
348
-
349
388
  headPrep.commit()
350
389
 
351
- for (const incoming of nextDoc.querySelectorAll('[data-persist]')) {
352
- const key = incoming.getAttribute('data-persist')
353
- const existing = key ? persisted.get(key) : undefined
354
- if (existing !== undefined)
355
- incoming.replaceWith(existing)
356
- }
357
-
390
+ // Swap body children in place via shared moveBefore helper so persisted islands, iframes, and focused inputs stay alive.
391
+ const nextContent = document.createDocumentFragment()
392
+ nextContent.append(...nextDoc.body.childNodes)
393
+ syncElementAttrs(document.body, nextDoc.body)
394
+ replaceKeeping(document.body, nextContent, existingAnnouncer !== null ? new Set([existingAnnouncer]) : undefined)
358
395
  if (existingAnnouncer !== null)
359
- nextDoc.body.appendChild(existingAnnouncer)
396
+ document.body.append(existingAnnouncer)
360
397
 
361
- document.body.replaceWith(nextDoc.body)
362
398
  if (push) {
363
399
  const newDocId = nextDocId()
364
400
  setDocId(newDocId)
@@ -369,10 +405,8 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
369
405
  }
370
406
  currentDocKey = `${nextParsed.pathname}${nextParsed.search}`
371
407
  writeScrolls(kept)
372
- // A page module the next page loads that this one did not (regions' client) runs now: scripts of a parsed page never do.
373
- for (const script of nextDoc.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]'))
374
- void import(new URL(script.getAttribute('src') ?? '', location.href).href)
375
- const fb = nextDoc.querySelector<HTMLScriptElement>('script[data-kui-fallback]')?.dataset.kuiFallback
408
+ syncHeadModuleScripts(nextDoc)
409
+ const fb = nextDoc.querySelector<HTMLScriptElement>('script[data-pru-fallback]')?.dataset.pruFallback
376
410
  if (fb && !('command' in HTMLButtonElement.prototype && 'closedBy' in HTMLDialogElement.prototype && typeof CSS !== 'undefined' && CSS.supports?.('position-area:block-end'))) {
377
411
  const fbUrl = new URL(fb, location.href)
378
412
  if (fbUrl.origin === location.origin)
@@ -385,7 +419,8 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
385
419
  else
386
420
  anchor = scrollToHash(hash)
387
421
 
388
- focusPrimaryLandmark(anchor)
422
+ if (anchor !== null || !isFocusedPersistedField())
423
+ focusPrimaryLandmark(anchor)
389
424
  announce(document.title)
390
425
 
391
426
  window.dispatchEvent(new CustomEvent('pru:navigate', { detail: { url: nextFullUrl } }))
@@ -432,7 +467,7 @@ if (typeof document !== 'undefined') {
432
467
  const onIntent = (event: Event) => {
433
468
  const target = event.target as Element | null
434
469
  const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
435
- // A region link prefetches its region alone, in regions().
470
+ // A region link prefetches its region alone, in core's region client.
436
471
  if (!link || link.hasAttribute('data-no-prefetch') || link.hasAttribute('data-pru-target'))
437
472
  return
438
473
  // Prefetch is strictly opt-in via [data-pru-prefetch] so side-effecting links like /logout are never prefetched
@@ -462,7 +497,7 @@ if (typeof document !== 'undefined') {
462
497
  scrollToHash(location.hash)
463
498
  return
464
499
  }
465
- // Only same-document region swaps belong to regions(); cross-document entries (even with __pruIdx) belong to spa().
500
+ // Only same-document region swaps belong to core's region client; cross-document entries (even with __pruIdx) belong to spa().
466
501
  if (isSameDocRegionState(st))
467
502
  return
468
503
  const targetDocId = typeof st?.__pruDoc === 'number' ? st.__pruDoc : undefined
package/src/index.ts CHANGED
@@ -1,23 +1,17 @@
1
- // @prunellejs/spa — opt-in in-place navigation: `spa()` swaps whole pages and keeps persistent islands (4.1 KB gzip), `regions()` swaps one <Region> of a page (4.6 KB gzip, on the pages with a <Region>). 0 B when uninstalled.
1
+ // @prunellejs/spa — opt-in full-page SPA navigation with persistent `[data-persist]` islands. 0 B when uninstalled.
2
2
 
3
- import type { BuildPluginContext, PrunellePlugin } from 'prunelle/config'
3
+ import type { PrunellePlugin } from 'prunelle/config'
4
4
  import { resolve } from 'node:path'
5
5
  import { definePlugin } from 'prunelle/config'
6
6
  import { escAttr } from 'prunelle/server'
7
- import { checkRegionTargets } from './check'
8
7
 
9
8
  export interface SpaOptions {
10
9
  /** Path prefixes that must always perform a full browser navigation instead of an SPA swap (e.g. custom auth base paths). */
11
10
  skipPaths?: readonly string[] | undefined
12
11
  }
13
12
 
14
- // Shipped as a same-origin stylesheet so navigating from an island-less page to an island/Suspense page
15
- // never needs to inject an unhashed inline <style> tag blocked by the initial page's strict CSP.
16
- const SPA_ISLAND_CSS = 'pru-island,pru-slot,pru-s{display:contents}'
17
-
18
- function emitIslandStylesheet(ctx: BuildPluginContext): void {
19
- ctx.addStyle(ctx.emitAsset('pru-island.css', SPA_ISLAND_CSS))
20
- }
13
+ // Inline style hashed automatically by core's `headTagStyleHashes`: navigating from an island-less page to an island or `<Suspense>` page needs 0 extra stylesheet network requests and never injects an unhashed `<style>`.
14
+ const SPA_ISLAND_STYLE_TAG = '<style>pru-island,pru-slot,pru-s{display:contents}</style>'
21
15
 
22
16
  export function spa(options?: SpaOptions): PrunellePlugin {
23
17
  const skipPaths = options?.skipPaths
@@ -27,18 +21,9 @@ export function spa(options?: SpaOptions): PrunellePlugin {
27
21
  name: '@prunellejs/spa',
28
22
  clientEntry: resolve(import.meta.dir, 'client.ts'),
29
23
  build(ctx) {
30
- emitIslandStylesheet(ctx)
24
+ ctx.addHead(SPA_ISLAND_STYLE_TAG)
31
25
  if (skipPaths && skipPaths.length > 0)
32
26
  ctx.addHead(`<meta name="pru-spa-skip" content="${escAttr(skipPaths.join(','))}">`)
33
27
  },
34
28
  })
35
29
  }
36
-
37
- export function regions(): PrunellePlugin {
38
- return definePlugin({
39
- name: '@prunellejs/spa/regions',
40
- regionClientEntry: resolve(import.meta.dir, 'regions.ts'),
41
- build: emitIslandStylesheet,
42
- check: checkRegionTargets,
43
- })
44
- }
package/src/announcer.ts DELETED
@@ -1,36 +0,0 @@
1
- // The polite live region a swap announces itself in, shared by `spa()` and `regions()`.
2
-
3
- export const ANNOUNCER_ID = '__pru-spa-announcer'
4
-
5
- function applySrOnlyStyle(el: HTMLElement): void {
6
- const s = el.style
7
- s.position = 'absolute'
8
- s.width = '1px'
9
- s.height = '1px'
10
- s.padding = '0'
11
- s.margin = '-1px'
12
- s.overflow = 'hidden'
13
- s.clip = 'rect(0,0,0,0)'
14
- s.whiteSpace = 'nowrap'
15
- s.border = '0'
16
- }
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.
21
- export function announce(text: string): void {
22
- let region = document.getElementById(ANNOUNCER_ID)
23
- if (region === null) {
24
- region = document.createElement('div')
25
- region.id = ANNOUNCER_ID
26
- region.setAttribute('role', 'status')
27
- region.setAttribute('aria-live', 'polite')
28
- region.setAttribute('aria-atomic', 'true')
29
- applySrOnlyStyle(region)
30
- document.body.appendChild(region)
31
- }
32
- region.textContent = ''
33
- requestAnimationFrame(() => {
34
- region.textContent = text
35
- })
36
- }
package/src/check.ts DELETED
@@ -1,31 +0,0 @@
1
- // `prunelle check` for regions(): a data-pru-target written as a string that names no <Region> in the app's src/.
2
-
3
- import type { CheckPluginContext } from 'prunelle/config'
4
- import { join, relative } from 'node:path'
5
-
6
- const TARGET_RE = /data-pru-target=["']([^"'{}]+)["']/g
7
- const REGION_RE = /<Region\b[^>]*?\bname=(?:["']([^"'{}]+)["']|\{)/g
8
-
9
- export async function checkRegionTargets(ctx: CheckPluginContext): Promise<void> {
10
- const targets: { file: string, name: string }[] = []
11
- const regions = new Set<string>()
12
- let computedName = false
13
- for await (const path of new Bun.Glob('src/**/*.{ts,tsx}').scan({ cwd: ctx.root })) {
14
- const file = join(ctx.root, path)
15
- const text = await Bun.file(file).text()
16
- for (const match of text.matchAll(TARGET_RE))
17
- targets.push({ file: relative(ctx.root, file), name: match[1]! })
18
- for (const match of text.matchAll(REGION_RE)) {
19
- if (match[1] === undefined)
20
- computedName = true
21
- else
22
- regions.add(match[1])
23
- }
24
- }
25
- if (computedName)
26
- return
27
- for (const { file, name } of targets) {
28
- if (!regions.has(name))
29
- ctx.error(`[regions] ${file}: data-pru-target="${name}" names no <Region name="${name}"> in src/: add the region, or fix the name`)
30
- }
31
- }
package/src/prefetch.ts DELETED
@@ -1,130 +0,0 @@
1
- // The fetch cache `spa()` and `regions()` share: a link inside [data-pru-prefetch] is fetched on hover or focus, and the swap that follows takes the answer from here.
2
-
3
- export interface PrefetchEntry {
4
- html: string
5
- url: string
6
- ts: number
7
- /** The `x-pru-region` the server answered with: the region's HTML alone, not a whole page. */
8
- region: string | null
9
- /** The percent-encoded `x-pru-title` of a region answer: the title the page has at this URL. */
10
- title: string | null
11
- /** Response Content-Security-Policy header, used by spa() to detect blocked destination <style> tags. */
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
15
- }
16
-
17
- export const HTML_ACCEPT = 'text/html'
18
- const PREFETCH_TTL = 15_000
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
23
- export const prefetchCache = new Map<string, PrefetchEntry>()
24
- export const inflightPrefetch = new Map<string, Promise<PrefetchEntry | undefined>>()
25
-
26
- // Document generation counter shared by spa() and regions() so popstate separates same-doc region swaps from cross-doc page navigations.
27
- function initialDocId(): number {
28
- const st = typeof history === 'undefined' ? undefined : history.state as { __pruDoc?: unknown } | null
29
- return typeof st?.__pruDoc === 'number' ? st.__pruDoc : 0
30
- }
31
-
32
- let currentDocId = initialDocId()
33
- let maxDocId = currentDocId
34
-
35
- export function getDocId(): number {
36
- return currentDocId
37
- }
38
-
39
- export function setDocId(id: number): void {
40
- currentDocId = id
41
- if (id > maxDocId)
42
- maxDocId = id
43
- }
44
-
45
- export function nextDocId(): number {
46
- return ++maxDocId
47
- }
48
-
49
- export function isSameDocRegionState(state: unknown): boolean {
50
- if (typeof state !== 'object' || state === null)
51
- return false
52
- const s = state as { __pruIdx?: unknown, __pruDoc?: unknown }
53
- return typeof s.__pruIdx === 'number' && (s.__pruDoc === undefined || s.__pruDoc === currentDocId)
54
- }
55
-
56
- /** The cache key of a page, or of one region of it, given by its path from the outermost region (`results/sets`). */
57
- export function fetchKeyOf(url: URL, region?: string): string {
58
- const key = `${url.origin}${url.pathname}${url.search}`
59
- return region === undefined ? key : `${region} ${key}`
60
- }
61
-
62
- export function getCachedHtml(href: string): PrefetchEntry | undefined {
63
- const hit = prefetchCache.get(href)
64
- if (hit === undefined)
65
- return undefined
66
- if (Date.now() - hit.ts > PREFETCH_TTL) {
67
- prefetchCache.delete(href)
68
- return undefined
69
- }
70
- return hit
71
- }
72
-
73
- function putCachedHtml(href: string, entry: PrefetchEntry): void {
74
- prefetchCache.delete(href)
75
- prefetchCache.set(href, entry)
76
- if (prefetchCache.size > PREFETCH_MAX) {
77
- const oldest = prefetchCache.keys().next()
78
- if (!oldest.done)
79
- prefetchCache.delete(oldest.value)
80
- }
81
- }
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
-
89
- export async function prefetch(url: string, region?: string): Promise<void> {
90
- const clean = new URL(url, location.href)
91
- clean.hash = ''
92
- const key = fetchKeyOf(clean, region)
93
- if (getCachedHtml(key) !== undefined || inflightPrefetch.has(key) || inflightPrefetch.size >= PREFETCH_PARALLEL)
94
- return
95
- const conn = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection
96
- if (conn?.saveData)
97
- return
98
-
99
- const task = (async (): Promise<PrefetchEntry | undefined> => {
100
- try {
101
- const res = await fetch(clean.href, { headers: { ...(region === undefined ? { 'x-pru-spa': '1' } : { 'x-pru-region': region }), 'accept': HTML_ACCEPT, 'purpose': 'prefetch' } })
102
- if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
103
- void res.body?.cancel()
104
- return undefined
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') }
107
- putCachedHtml(key, entry)
108
- return entry
109
- }
110
- catch {
111
- return undefined
112
- }
113
- finally {
114
- inflightPrefetch.delete(key)
115
- }
116
- })()
117
- inflightPrefetch.set(key, task)
118
- await task
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 DELETED
@@ -1,496 +0,0 @@
1
- // @prunellejs/spa regions() client: a link or GET form with data-pru-target swaps one <Region> of the page, fetched alone.
2
- // - a[data-pru-target] replaces the region; with data-pru-append the response is added to it and the clicked link goes (Load more)
3
- // - form[data-pru-target] swaps on submit; with data-pru-live also while typing: one history entry per typing burst
4
- // - [data-pru-sync="a b"] copies those query params of the current URL into links and fields outside the region
5
- // - form[method=post][data-pru-target] posts through fetch, follows the redirect and swaps the region with the page it lands on
6
- // - history push and back/forward re-fetch the region the entry changed; aria-busy while a fetch is slow
7
- // - [data-persist="<key>"] inside the region survives the swap in the place of the new element of that key: a field keeps focus, caret and value, an iframe its document
8
- // - a swap runs in a view transition (not under reduced motion), keeps the scroll of [data-pru-keep-scroll] elements, resets the region's own, and moves aria-current to the links that match the new URL
9
- // - a link to a #hash already on the page scrolls to it without a fetch; after a swap the page scrolls to the URL's hash
10
- // - prefetch on hover and focus inside [data-pru-prefetch], through the cache spa() shares
11
-
12
- import type { PrefetchEntry } from './prefetch'
13
- import type { EntryScroll } from './swap'
14
- import { announce } from './announcer'
15
- import { countView, fetchKeyOf, getCachedHtml, getDocId, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, prefetch, prefetchCache } from './prefetch'
16
- import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
17
-
18
- const BUSY_DELAY = 150
19
- const LIVE_DEBOUNCE = 200
20
- const BURST_PAUSE = 1000
21
-
22
- interface RegionState { __pruIdx: number, __pruDoc?: number | undefined, __pruRegion?: string | undefined }
23
-
24
- function safeGetAttribute(el: Element, name: string): string | null {
25
- return Element.prototype.getAttribute.call(el, name)
26
- }
27
-
28
- interface Swap {
29
- url: URL
30
- region: string
31
- append?: boolean
32
- /** `burst`: pushed by the first change of a typing burst, replaced by the rest. */
33
- history: 'push' | 'replace' | 'burst' | 'none'
34
- /** Moves focus into the region (a link did it), not for a form the user is typing in. */
35
- focus?: boolean
36
- trigger?: Element
37
- /** Skips the prefetch cache: the region is redrawn because the server's state changed. */
38
- fresh?: boolean
39
- /** A form posted to `url`: the swap shows the page its redirect lands on. */
40
- post?: { form: HTMLFormElement, body: FormData }
41
- /** Where the post's redirect ended, once it did. */
42
- landed?: string
43
- /** The scroll a back or forward entry had, put back after the swap. */
44
- restore?: EntryScroll
45
- }
46
-
47
- function stateOf(state: unknown): RegionState | undefined {
48
- return typeof state === 'object' && state !== null && typeof (state as RegionState).__pruIdx === 'number' ? state as RegionState : undefined
49
- }
50
-
51
- const controllers = new Map<string, AbortController>()
52
- let idx = stateOf(typeof history === 'undefined' ? undefined : history.state)?.__pruIdx ?? 0
53
- let lastRegion = stateOf(typeof history === 'undefined' ? undefined : history.state)?.__pruRegion
54
- // The page and query the document shows: an entry that differs from it only in its hash needs no fetch.
55
- let shown = typeof location === 'undefined' ? '' : location.pathname + location.search
56
- // The pages Load more added to the document since its last swap, beside the one it shows: their #hash links scroll too.
57
- const appended = new Set<string>()
58
- let burstOpen = false
59
- let burstTimer: ReturnType<typeof setTimeout> | undefined
60
- let liveTimer: ReturnType<typeof setTimeout> | undefined
61
-
62
- function findRegion(name: string): HTMLElement | null {
63
- return document.querySelector<HTMLElement>(`[data-pru-region="${name.replace(/["\\]/g, '\\$&')}"]`)
64
- }
65
-
66
- // A region's path from the outermost one around it: `results/sets` for `sets` inside `results`. The server renders through the outer ones.
67
- function pathOf(region: HTMLElement): string {
68
- const names: string[] = []
69
- for (let el: Element | null = region; el !== null; el = el.parentElement?.closest('[data-pru-region]') ?? null)
70
- names.unshift(el.getAttribute('data-pru-region')!)
71
- return names.join('/')
72
- }
73
-
74
- async function load(swap: Swap, region: string, signal: AbortSignal): Promise<PrefetchEntry | undefined> {
75
- const { url, post } = swap
76
- const key = fetchKeyOf(url, region)
77
- const ready = swap.fresh === true || post !== undefined ? undefined : getCachedHtml(key) ?? await inflightPrefetch.get(key)
78
- if (ready !== undefined) {
79
- prefetchCache.delete(key)
80
- return ready
81
- }
82
- const res = await fetch(fetchKeyOf(url), { headers: { 'x-pru-region': region, 'accept': HTML_ACCEPT }, signal, ...(post === undefined ? {} : { method: 'POST', body: post.body }) })
83
- if (post !== undefined)
84
- swap.landed = res.url
85
- if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
86
- void res.body?.cancel()
87
- return undefined
88
- }
89
- return { html: await res.text(), url: res.url || fetchKeyOf(url), ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title') }
90
- }
91
-
92
- // The region's inner HTML and the page title: the answer itself when the server sent the region alone, else the region cut out of a full page (a prerendered page, a proxy that dropped the header).
93
- function contentOf(entry: PrefetchEntry, path: string): { content: DocumentFragment, title: string | undefined } | undefined {
94
- const template = document.createElement('template')
95
- if (entry.region === path) {
96
- template.innerHTML = entry.html
97
- // The title is HTML text, percent-encoded in the header: a textarea unescapes it.
98
- const unescape = document.createElement('textarea')
99
- unescape.innerHTML = entry.title === null ? '' : decodeURIComponent(entry.title)
100
- return { content: template.content, title: entry.title === null ? undefined : unescape.value }
101
- }
102
- const page = new DOMParser().parseFromString(entry.html, 'text/html')
103
- const found = page.querySelector(`[data-pru-region="${path.split('/').at(-1)!.replace(/["\\]/g, '\\$&')}"]`)
104
- if (found === null)
105
- return undefined
106
- template.innerHTML = found.innerHTML
107
- return { content: template.content, title: page.title === '' ? undefined : page.title }
108
- }
109
-
110
- function record(url: URL, name: string, mode: 'push' | 'replace' | 'burst'): void {
111
- clearTimeout(burstTimer)
112
- // A replace inside the region the entry was made for keeps that region, so back and forward restore the whole of it.
113
- const before = stateOf(history.state)?.__pruRegion
114
- const around = mode === 'replace' && before !== undefined && before !== name && findRegion(before)?.contains(findRegion(name)) === true ? before : name
115
- let push = mode === 'push' || (mode === 'burst' && !burstOpen)
116
- if (mode === 'burst') {
117
- burstOpen = true
118
- burstTimer = setTimeout(() => { burstOpen = false }, BURST_PAUSE)
119
- }
120
- else {
121
- burstOpen = false
122
- }
123
- const next = `${url.pathname}${url.search}${url.hash}`
124
- if (next === `${location.pathname}${location.search}${location.hash}`)
125
- push = false
126
- const prev = (typeof history.state === 'object' && history.state !== null ? history.state : {}) as Record<string, unknown>
127
- const docId = getDocId()
128
- if (push) {
129
- // The entry left behind is stamped first, so back and forward can tell it from a page of another document.
130
- history.replaceState({ ...prev, __pruDoc: docId, __pruIdx: idx }, '')
131
- idx++
132
- history.pushState({ __pruDoc: docId, __pruIdx: idx, __pruRegion: around }, '', next)
133
- }
134
- else {
135
- history.replaceState({ ...prev, __pruDoc: docId, __pruIdx: idx, __pruRegion: around }, '', next)
136
- }
137
- lastRegion = around
138
- shown = url.pathname + url.search
139
- }
140
-
141
- function focusNode(el: Element | null | undefined): void {
142
- if (el === null || el === undefined)
143
- return
144
- if (!el.hasAttribute('tabindex'))
145
- el.setAttribute('tabindex', '-1')
146
- ;(el as HTMLElement).focus({ preventScroll: true })
147
- }
148
-
149
- // Links and fields the app marked data-pru-sync follow the URL the swap just set.
150
- function syncParams(): void {
151
- const params = new URL(location.href).searchParams
152
- for (const el of document.querySelectorAll<HTMLElement>('[data-pru-sync]')) {
153
- if (el instanceof HTMLAnchorElement) {
154
- const url = new URL(el.href, location.href)
155
- if (url.origin !== location.origin)
156
- continue
157
- for (const name of (el.getAttribute('data-pru-sync') ?? '').split(/\s+/).filter(Boolean)) {
158
- url.searchParams.delete(name)
159
- for (const value of params.getAll(name))
160
- url.searchParams.append(name, value)
161
- }
162
- el.setAttribute('href', `${url.pathname}${url.search}${url.hash}`)
163
- }
164
- else if ((el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement) && el !== document.activeElement) {
165
- el.value = params.get(el.name) ?? ''
166
- }
167
- }
168
- }
169
-
170
- // The links that point at the page the swap landed on say so; the ones that did and no longer do stop.
171
- function syncCurrent(): void {
172
- for (const link of document.querySelectorAll<HTMLAnchorElement>('a[href]')) {
173
- if (link.origin === location.origin && link.hash === '' && link.pathname + link.search === location.pathname + location.search)
174
- link.setAttribute('aria-current', 'page')
175
- else if (link.getAttribute('aria-current') === 'page')
176
- link.removeAttribute('aria-current')
177
- }
178
- }
179
-
180
- const PERSIST = '[data-persist]'
181
-
182
- // The outermost [data-persist] elements under `root` by key (a nested one moves with its own), and a key found on two of them.
183
- function persistedIn(root: ParentNode & Node): { byKey: Map<string, Element>, twice: string | undefined } {
184
- const byKey = new Map<string, Element>()
185
- let twice: string | undefined
186
- for (const el of root.querySelectorAll(PERSIST)) {
187
- const outer = el.parentElement?.closest(PERSIST)
188
- const key = el.getAttribute('data-persist')
189
- if (key === null || key === '' || (outer !== null && outer !== undefined && root.contains(outer)))
190
- continue
191
- if (byKey.has(key))
192
- twice ??= key
193
- byKey.set(key, el)
194
- }
195
- return { byKey, twice }
196
- }
197
-
198
- type Movable = ParentNode & { moveBefore?: (node: Node, child: Node | null) => void }
199
-
200
- // Swaps `content` in, each live [data-persist] element taking the place of the new one of its key. moveBefore keeps a field's focus and an iframe's document; where it is missing, a re-inserted field gets its focus and selection back.
201
- function replaceKeeping(region: HTMLElement, content: DocumentFragment): void {
202
- const incoming = persistedIn(content).byKey
203
- const live = persistedIn(region).byKey
204
- const old = [...region.childNodes]
205
- region.append(content)
206
- const focused = document.activeElement
207
- const field = focused instanceof HTMLInputElement || focused instanceof HTMLTextAreaElement ? focused : undefined
208
- const selection = field?.selectionStart == null ? undefined : [field.selectionStart, field.selectionEnd ?? field.selectionStart, field.selectionDirection ?? 'none'] as const
209
- let refocus = false
210
- for (const [key, el] of live) {
211
- const slot = incoming.get(key)
212
- const parent = slot?.parentNode as Movable | null | undefined
213
- if (slot === undefined || parent === null || parent === undefined)
214
- continue
215
- if (typeof parent.moveBefore === 'function') {
216
- parent.moveBefore(el, slot)
217
- }
218
- else {
219
- refocus ||= focused !== null && el.contains(focused)
220
- parent.insertBefore(el, slot)
221
- }
222
- slot.remove()
223
- }
224
- for (const node of old)
225
- node.remove()
226
- if (refocus && focused instanceof HTMLElement && document.activeElement !== focused) {
227
- focused.focus({ preventScroll: true })
228
- if (field !== undefined && selection !== undefined)
229
- field.setSelectionRange(...selection)
230
- }
231
- }
232
-
233
- function elementOfHash(hash: string): HTMLElement | null {
234
- const raw = hash.slice(1)
235
- let id: string
236
- try {
237
- id = decodeURIComponent(raw)
238
- }
239
- catch {
240
- id = raw
241
- }
242
- return id === '' ? null : document.getElementById(id)
243
- }
244
-
245
- async function apply(region: HTMLElement, found: { content: DocumentFragment, title: string | undefined }, swap: Swap, finalUrl: URL): Promise<void> {
246
- const { content, title } = found
247
- // A typing burst and an append stay put: a transition freezes the page, and the field being typed in with it.
248
- const animate = !swap.append && swap.history !== 'burst' && swap.fresh !== true
249
- await swapInTransition(() => {
250
- if (swap.append)
251
- appended.add(shown)
252
- else
253
- appended.clear()
254
- if (swap.history !== 'none') {
255
- saveScroll()
256
- record(finalUrl, swap.region, swap.history)
257
- }
258
- const kept = readScrolls(false)
259
- const first = content.firstElementChild
260
- if (swap.append) {
261
- if (swap.trigger !== undefined && region.contains(swap.trigger))
262
- swap.trigger.remove()
263
- region.append(content)
264
- }
265
- else {
266
- // A fetch for a region about to be replaced must not land in the new one.
267
- for (const inner of region.querySelectorAll('[data-pru-region]'))
268
- controllers.get(inner.getAttribute('data-pru-region')!)?.abort()
269
- replaceKeeping(region, content)
270
- writeScrolls(kept)
271
- if (swap.history !== 'none' && !region.hasAttribute('data-pru-keep-scroll'))
272
- region.scrollTop = 0
273
- }
274
- if (title !== undefined)
275
- document.title = title
276
- syncParams()
277
- syncCurrent()
278
- if (swap.restore !== undefined)
279
- restoreScroll(swap.restore)
280
- else if (!swap.append && swap.history !== 'none')
281
- elementOfHash(finalUrl.hash)?.scrollIntoView()
282
- if (swap.focus === true)
283
- focusNode(swap.append ? first : region)
284
- const label = region.getAttribute('aria-label')
285
- if (label !== null)
286
- announce(label)
287
- window.dispatchEvent(new CustomEvent('pru:region', { detail: { name: swap.region, url: location.href } }))
288
- }, animate)
289
- }
290
-
291
- // Resolves false when the region could not be swapped: no such region, a failed fetch, or an answer without it.
292
- async function swapRegion(swap: Swap): Promise<boolean> {
293
- const name = swap.region
294
- if (findRegion(name) === null)
295
- return false
296
- controllers.get(name)?.abort()
297
- const controller = new AbortController()
298
- controllers.set(name, controller)
299
- const path = pathOf(findRegion(name)!)
300
- const busy = setTimeout(() => findRegion(name)?.setAttribute('aria-busy', 'true'), BUSY_DELAY)
301
- try {
302
- const entry = await load(swap, path, controller.signal)
303
- if (controller.signal.aborted)
304
- return true
305
- const content = entry === undefined ? undefined : contentOf(entry, path)
306
- const region = findRegion(name)
307
- if (entry === undefined || content === undefined || region === null)
308
- return false
309
- const finalUrl = entry.url ? new URL(entry.url, location.href) : swap.url
310
- if (finalUrl.origin !== location.origin)
311
- return false
312
- if (swap.url.hash && !finalUrl.hash)
313
- finalUrl.hash = swap.url.hash
314
- const twice = swap.append === true ? undefined : persistedIn(content.content).twice
315
- if (twice !== undefined) {
316
- console.error(`prunelle: data-persist="${twice}" is on two elements of the region "${name}" that ${finalUrl.pathname}${finalUrl.search} answers: give each its own key. The page loads whole instead.`)
317
- return false
318
- }
319
- countView(entry.view, finalUrl)
320
- await apply(region, content, swap, finalUrl)
321
- return true
322
- }
323
- catch (err) {
324
- return controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError')
325
- }
326
- finally {
327
- clearTimeout(busy)
328
- if (controllers.get(name) === controller) {
329
- controllers.delete(name)
330
- findRegion(name)?.removeAttribute('aria-busy')
331
- }
332
- }
333
- }
334
-
335
- // A swap a link, a form or history asked for: what cannot be swapped loads the whole page. A form already posted loads the page its redirect reached, never posts twice; one whose post never got an answer posts the plain way.
336
- async function navigate(swap: Swap): Promise<void> {
337
- if (await swapRegion(swap))
338
- return
339
- if (swap.post === undefined)
340
- location.assign(swap.url.href)
341
- else if (swap.landed)
342
- location.assign(swap.landed)
343
- else
344
- swap.post.form.submit()
345
- }
346
-
347
- /** Redraws region `name` from the server at the current address, with no history entry and focus left where it is; rejects when the page has no such region, the fetch fails or the answer lacks it. */
348
- export async function refreshRegion(name: string): Promise<void> {
349
- if (!await swapRegion({ url: new URL(location.href), region: name, history: 'none', fresh: true }))
350
- throw new Error(`prunelle: region "${name}" could not be redrawn from ${location.href}: render a <Region name="${name}"> on this page, and check the server answers it.`)
351
- }
352
-
353
- function formMethod(form: HTMLFormElement, submitter?: HTMLElement | null): string {
354
- const rawMethod = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formmethod') : null)
355
- ?? safeGetAttribute(form, 'method')
356
- ?? 'get'
357
- return rawMethod.toLowerCase()
358
- }
359
-
360
- function formAction(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
361
- // Read raw attributes via Element.prototype.getAttribute so <input name="action"> cannot DOM-clobber form.action.
362
- const rawAction = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formaction') : null)
363
- ?? safeGetAttribute(form, 'action')
364
- ?? ''
365
- return new URL(rawAction, location.href)
366
- }
367
-
368
- /** The live form on the page that an element is, or belongs to by `form="<id>"` or as a descendant. */
369
- function liveForm(el: Element | null): HTMLFormElement | null {
370
- const form = el?.isConnected ? (el as HTMLInputElement).form ?? el.closest?.('form') : null
371
- return form?.matches('[data-pru-live][data-pru-target]') ? form : null
372
- }
373
-
374
- function formUrl(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
375
- const url = formAction(form, submitter)
376
- // A field left empty stays out of the address, so it names only the filters in use; a button with an empty value clears its name, as a server reading the last value sees natively.
377
- const cleared = (submitter as HTMLButtonElement | null | undefined)?.value === '' ? submitter!.getAttribute('name') : null
378
- const params = new URLSearchParams()
379
- for (const [key, value] of new FormData(form, submitter ?? undefined)) {
380
- if (typeof value === 'string' && value !== '' && key !== cleared)
381
- params.append(key, value)
382
- }
383
- url.search = params.toString()
384
- return url
385
- }
386
-
387
- function missingRegion(name: string, element: string): boolean {
388
- if (findRegion(name) !== null)
389
- return false
390
- console.error(`prunelle: ${element} targets the region "${name}", and this page has no <Region name="${name}">: add it, or fix the name. The link loads the whole page instead.`)
391
- return true
392
- }
393
-
394
- function linkOf(event: Event): HTMLAnchorElement | null {
395
- return (event.target as Element | null)?.closest?.<HTMLAnchorElement>('a[href][data-pru-target]') ?? null
396
- }
397
-
398
- if (typeof document !== 'undefined') {
399
- document.addEventListener('click', (event) => {
400
- if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
401
- return
402
- const link = linkOf(event)
403
- if (link === null || link.target !== '' || link.hasAttribute('download'))
404
- return
405
- const url = new URL(link.href, location.href)
406
- const name = link.getAttribute('data-pru-target')!
407
- const append = link.hasAttribute('data-pru-append')
408
- if (url.origin !== location.origin || missingRegion(name, `<a href="${link.getAttribute('href')}">`))
409
- return
410
- event.preventDefault()
411
- // A hash already on the page is a scroll when the document holds the page the link names, with the address keeping its page.
412
- const page = url.pathname + url.search
413
- if (!append && (page === shown || appended.has(page)) && elementOfHash(url.hash) !== null) {
414
- location.hash = url.hash
415
- return
416
- }
417
- void navigate({ url, region: name, append, history: append ? 'replace' : 'push', focus: true, trigger: link })
418
- }, true)
419
-
420
- document.addEventListener('submit', (event) => {
421
- const form = event.target as HTMLFormElement
422
- if (!(form instanceof HTMLFormElement))
423
- return
424
- const submitter = (event as SubmitEvent).submitter
425
- const name = safeGetAttribute(form, 'data-pru-target')
426
- const method = formMethod(form, submitter)
427
- if (event.defaultPrevented || name === null || (method !== 'get' && method !== 'post') || missingRegion(name, '<form>'))
428
- return
429
- event.preventDefault()
430
- clearTimeout(liveTimer)
431
- if (method === 'get')
432
- void navigate({ url: formUrl(form, submitter), region: name, history: 'push' })
433
- else
434
- void navigate({ url: formAction(form, submitter), region: name, history: 'push', post: { form, body: new FormData(form, submitter ?? undefined) } })
435
- }, true)
436
-
437
- document.addEventListener('input', (event) => {
438
- const field = event.target as Element | null
439
- const typed = liveForm(field)
440
- if (typed === null || formMethod(typed) !== 'get')
441
- return
442
- clearTimeout(liveTimer)
443
- liveTimer = setTimeout(() => {
444
- // A swap that landed since the key may have replaced the form: send the one on the page now, or nothing.
445
- const form = liveForm(typed) ?? liveForm(field) ?? liveForm(typed.id === '' ? null : document.getElementById(typed.id))
446
- const name = form && safeGetAttribute(form, 'data-pru-target')!
447
- if (name && !missingRegion(name, '<form>'))
448
- void navigate({ url: formUrl(form!), region: name, history: 'burst' })
449
- }, LIVE_DEBOUNCE)
450
- })
451
-
452
- const onIntent = (event: Event) => {
453
- const link = linkOf(event)
454
- if (link === null || link.hasAttribute('data-no-prefetch') || link.closest('[data-pru-prefetch]') === null)
455
- return
456
- const url = new URL(link.href, location.href)
457
- if (url.origin === location.origin && `${url.pathname}${url.search}` !== `${location.pathname}${location.search}`) {
458
- const region = findRegion(link.getAttribute('data-pru-target')!)
459
- if (region !== null)
460
- void prefetch(url.href, pathOf(region))
461
- }
462
- }
463
- listenIntent(onIntent)
464
-
465
- // Keep region state aligned when spa() swaps to another document (including popstate back to a document with prior region entries).
466
- window.addEventListener('pru:navigate', () => {
467
- shown = location.pathname + location.search
468
- appended.clear()
469
- const st = stateOf(history.state)
470
- idx = st?.__pruIdx ?? 0
471
- lastRegion = st?.__pruRegion
472
- burstOpen = false
473
- })
474
- window.addEventListener('popstate', (event) => {
475
- if (!isSameDocRegionState(event.state))
476
- return
477
- const state = stateOf(event.state)
478
- const sameDocument = location.pathname + location.search === shown
479
- shown = location.pathname + location.search
480
- if (state === undefined)
481
- return
482
- const name = state.__pruIdx < idx ? lastRegion : state.__pruRegion
483
- idx = state.__pruIdx
484
- lastRegion = state.__pruRegion
485
- burstOpen = false
486
- const restore = entryScroll(event.state)
487
- if (name === undefined || sameDocument) {
488
- // With spa() the browser leaves the scroll to the page, a swap or not.
489
- if (restore !== undefined && history.scrollRestoration === 'manual')
490
- restoreScroll(restore)
491
- return
492
- }
493
- void navigate({ url: new URL(location.href), region: name, history: 'none', ...(restore === undefined ? {} : { restore }) })
494
- })
495
- trackScroll()
496
- }
package/src/swap.ts DELETED
@@ -1,119 +0,0 @@
1
- // What a region swap and a whole-page swap share: the view transition they run in, and the scroll they keep per history entry and across the swap.
2
- // An element with `data-pru-keep-scroll="<key>"` keeps its offset by key; a `<Region>` that scrolls itself is remembered per entry as `region:<name>`.
3
-
4
- import { getDocId } from './prefetch'
5
-
6
- export interface EntryScroll { y: number, k: Record<string, number> }
7
-
8
- const SCROLLERS = '[data-pru-keep-scroll],[data-pru-region]'
9
-
10
- const keyOf = (el: Element): string => el.getAttribute('data-pru-keep-scroll') ?? `region:${el.getAttribute('data-pru-region')}`
11
-
12
- /** The offsets of the elements that keep theirs; `regions` adds the scrolled `<Region>`s, which a swap resets and a history entry restores. */
13
- export function readScrolls(regions: boolean): Record<string, number> {
14
- const out: Record<string, number> = {}
15
- for (const el of document.querySelectorAll(SCROLLERS)) {
16
- if (el.hasAttribute('data-pru-keep-scroll') || (regions && el.scrollTop > 0))
17
- out[keyOf(el)] = el.scrollTop
18
- }
19
- return out
20
- }
21
-
22
- export function writeScrolls(offsets: Record<string, number>): void {
23
- for (const el of document.querySelectorAll(SCROLLERS)) {
24
- const top = offsets[keyOf(el)]
25
- if (top !== undefined)
26
- el.scrollTop = top
27
- }
28
- }
29
-
30
- export function entryScroll(state: unknown): EntryScroll | undefined {
31
- const saved = typeof state === 'object' && state !== null ? (state as { __pruScroll?: EntryScroll }).__pruScroll : undefined
32
- return typeof saved?.y === 'number' ? saved : undefined
33
- }
34
-
35
- export function restoreScroll(saved: EntryScroll): void {
36
- writeScrolls(saved.k)
37
- window.scrollTo(0, saved.y)
38
- }
39
-
40
- /** Writes the page's scroll into the current history entry, so back and forward can return to it. */
41
- export function saveScroll(): void {
42
- try {
43
- const prev = typeof history.state === 'object' && history.state !== null ? history.state as Record<string, unknown> : {}
44
- history.replaceState({ ...prev, __pruDoc: getDocId(), __pruScroll: { y: window.scrollY, k: readScrolls(true) } satisfies EntryScroll }, '')
45
- }
46
- catch {
47
- // Restricted history API environments (e.g. sandboxed iframes) refuse state updates: the entry keeps no scroll.
48
- return
49
- }
50
- }
51
-
52
- let tracking = false
53
-
54
- /** Keeps the current entry's scroll up to date once the page stops scrolling, as a swap by back or forward has no earlier moment to read it. */
55
- export function trackScroll(): void {
56
- if (tracking)
57
- return
58
- tracking = true
59
- let timer: ReturnType<typeof setTimeout> | undefined
60
- document.addEventListener('scroll', () => {
61
- clearTimeout(timer)
62
- timer = setTimeout(saveScroll, 150)
63
- }, { capture: true, passive: true })
64
- }
65
-
66
- interface Transition { updateCallbackDone: Promise<void>, ready: Promise<void>, finished: Promise<void>, skipTransition: () => void }
67
- type Transitions = Document & { startViewTransition?: (update: () => void) => Transition }
68
-
69
- let running: Transition | undefined
70
- let listening = false
71
-
72
- // While a view transition runs, Chrome hit-tests every click to <html>: the click skips the transition and goes to what is under the pointer once it ends.
73
- function retargetClick(event: MouseEvent): void {
74
- const transition = running
75
- if (transition === undefined || event.target !== document.documentElement || event.detail === 0 || event.button !== 0)
76
- return
77
- event.preventDefault()
78
- event.stopImmediatePropagation()
79
- const { clientX, clientY } = event
80
- // A skipped transition rejects `ready`, which nothing else waits on.
81
- transition.ready.catch(() => undefined)
82
- transition.skipTransition()
83
- const resend = (): void => {
84
- const under = document.elementFromPoint(clientX, clientY)
85
- if (under instanceof HTMLElement && under !== document.documentElement)
86
- under.click()
87
- }
88
- void transition.finished.then(resend, resend)
89
- }
90
-
91
- // `navigation: { viewTransitions: false }` leaves the `@view-transition` rule out of every page: swaps follow what the page says.
92
- function pageAnimates(): boolean {
93
- for (const style of document.head.querySelectorAll('style')) {
94
- if (style.textContent?.includes('@view-transition'))
95
- return true
96
- }
97
- return false
98
- }
99
-
100
- /** Runs the DOM `update` inside a view transition where the browser has them, the app keeps them and the user allows motion; resolves once it ran. */
101
- export async function swapInTransition(update: () => void, animate = true): Promise<void> {
102
- const doc = document as Transitions
103
- if (!animate || typeof doc.startViewTransition !== 'function' || matchMedia('(prefers-reduced-motion: reduce)').matches || !pageAnimates()) {
104
- update()
105
- return
106
- }
107
- if (!listening) {
108
- listening = true
109
- document.addEventListener('click', retargetClick, true)
110
- }
111
- const transition = doc.startViewTransition(update)
112
- running = transition
113
- const done = (): void => {
114
- if (running === transition)
115
- running = undefined
116
- }
117
- void transition.finished.then(done, done)
118
- await transition.updateCallbackDone
119
- }