@prunellejs/spa 0.8.0 → 0.10.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,38 @@
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).
9
- - `@prunellejs/spa/client`: `prefetch(url: string, region?: string)` (populates the shared 8-entry / 15s prefetch cache; respects `Save-Data`).
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).
8
+ - `@prunellejs/spa/client`:
9
+ - `navigate(url: string, push?: boolean)`: programmatic SPA navigation (pushes history by default; aborts any in-flight navigation).
10
+ - `prefetch(url: string, region?: string)`: populates the shared 8-entry / 15s prefetch cache; respects `Save-Data`.
11
+ - `useNavigation(): NavigationState` (`{ url: ReadonlySignal<string>, pathname: ReadonlySignal<string>, navigating: ReadonlySignal<boolean> }`): reactive navigation state shared across islands on the page (tree-shaken out of pages that never call it; calling it promotes the component to an island automatically). Type `NavigationState` is also exported.
10
12
 
11
- ## Partial Swaps (`regions()`)
13
+ ## Default: MPA plus core `<Region>`
12
14
 
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]`).
15
+ 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
16
 
44
17
  ## Full-Page SPA Navigation (`spa()`)
45
18
 
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.
19
+ - Intercepts same-origin `<a>` clicks, diffs `<head>` stylesheets (zero-FOUC, in the order the next page serves them, every attribute kept) and meta/title/tab icons (`icon`, `apple-touch-icon`, `mask-icon`)/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, re-seeds shared module state for the new document, and dispatches `pru:navigate` (with `{ url }` detail) and `pru:navigating` (`boolean` detail on navigation start/end).
20
+ - 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.
21
+ - 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.
22
+ - 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.
23
+ - 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`.
24
+ - 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
25
  - 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.
26
+ - 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
27
 
53
- ## Snippets
28
+ ## Snippet
54
29
 
55
30
  ```ts
56
31
  // prunelle.config.ts
57
32
  import { defineConfig } from 'prunelle/config'
58
- import { regions, spa } from '@prunellejs/spa'
33
+ import { spa } from '@prunellejs/spa'
59
34
 
60
35
  export default defineConfig({
61
- plugins: [regions(), spa()],
36
+ plugins: [spa()],
62
37
  })
63
38
  ```
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.8.0",
3
+ "version": "0.10.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.8.0"
27
+ "prunelle": "^0.10.0"
30
28
  }
31
29
  }
package/src/client.ts CHANGED
@@ -1,24 +1,35 @@
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
+ export { useNavigation } from './navigation'
15
+ export type { NavigationState } from './navigation'
16
+
17
+ const INIT_KEY = Symbol.for('pru.spa.init')
18
+ const NAVIGATING_KEY = Symbol.for('pru.navigating')
19
+ const emit = (name: string, detail: unknown) => window.dispatchEvent(new CustomEvent(name, { detail }))
20
+ const setNavigating = (busy: boolean) => {
21
+ ;(window as unknown as Record<symbol, boolean | undefined>)[NAVIGATING_KEY] = busy
22
+ emit('pru:navigating', busy)
23
+ }
14
24
 
15
25
  let activeController: AbortController | undefined
16
26
  let currentDocKey = typeof location !== 'undefined' ? `${location.pathname}${location.search}` : ''
17
27
 
18
- // Framework inline styles shipped in pru-island.css so SPA navigation never injects unhashed <style> tags.
28
+ // Framework inline styles shipped in <head> so SPA navigation never injects unhashed <style> tags.
19
29
  const PRUNELLE_BUILTIN_STYLES = new Set([
20
30
  'pru-island,pru-slot{display:contents}',
21
31
  'pru-s{display:contents}',
32
+ 'pru-island,pru-slot,pru-s{display:contents}',
22
33
  ])
23
34
 
24
35
  // One-time token and OAuth redirect endpoints must hit the server once via normal navigation, never via SPA fetch.
@@ -90,7 +101,7 @@ function isEligibleLink(link: HTMLAnchorElement): URL | undefined {
90
101
  return url
91
102
  }
92
103
 
93
- const SYNC_HEAD_SELECTOR = 'meta[name="description"],meta[name="robots"],meta[property^="og:"],meta[name^="twitter:"],link[rel="canonical"],link[rel="alternate"][hreflang],script[type="application/ld+json"]'
104
+ const SYNC_HEAD_SELECTOR = 'meta[name="description"],meta[name="robots"],meta[property^="og:"],meta[name^="twitter:"],link[rel="canonical"],link[rel="alternate"][hreflang],link[rel="icon"],link[rel="apple-touch-icon"],link[rel="mask-icon"],script[type="application/ld+json"]'
94
105
 
95
106
  function resolveSuspenseTemplates(doc: Document): void {
96
107
  for (const tpl of doc.querySelectorAll<HTMLTemplateElement>('template[data-ks]')) {
@@ -107,12 +118,13 @@ function resolveSuspenseTemplates(doc: Document): void {
107
118
 
108
119
  function scrollToHash(hash: string): HTMLElement | null {
109
120
  if (hash.length > 1) {
110
- let id = hash.slice(1)
121
+ const raw = hash.slice(1)
122
+ let id: string
111
123
  try {
112
- id = decodeURIComponent(id)
124
+ id = decodeURIComponent(raw)
113
125
  }
114
126
  catch {
115
- // Malformed percent-encoding in hash: use the raw fragment id.
127
+ id = raw
116
128
  }
117
129
  const anchor = document.getElementById(id)
118
130
  if (anchor !== null) {
@@ -139,6 +151,51 @@ function focusPrimaryLandmark(anchor: HTMLElement | null): void {
139
151
  }
140
152
  }
141
153
 
154
+ function isFocusedPersistedField(): boolean {
155
+ const active = document.activeElement
156
+ if (active === null || active === document.body || active.closest('[data-persist]') === null)
157
+ return false
158
+ return active instanceof HTMLInputElement
159
+ || active instanceof HTMLTextAreaElement
160
+ || active instanceof HTMLSelectElement
161
+ || (active as HTMLElement).isContentEditable === true
162
+ }
163
+
164
+ /** Imports new same-origin head module scripts (e.g. core's region client) and preserves `data-pru-build` / `data-pru-runtime` across navigations. */
165
+ function syncHeadModuleScripts(nextDoc: Document): void {
166
+ const existingSrcs = new Set<string>()
167
+ let hostScript: HTMLScriptElement | null = null
168
+ for (const cur of document.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]')) {
169
+ hostScript ??= cur
170
+ const raw = cur.getAttribute('src')
171
+ if (raw)
172
+ existingSrcs.add(new URL(raw, location.href).href)
173
+ }
174
+ for (const script of nextDoc.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]')) {
175
+ const rawSrc = script.getAttribute('src')
176
+ if (!rawSrc)
177
+ continue
178
+ const scriptUrl = new URL(rawSrc, location.href)
179
+ if (scriptUrl.origin !== location.origin)
180
+ continue
181
+ const buildId = script.getAttribute('data-pru-build')
182
+ const runtimeSrc = script.getAttribute('data-pru-runtime')
183
+ if (buildId !== null && document.head.querySelector('script[data-pru-build]') === null) {
184
+ // Stamp on an existing module script (or a non-executable JSON script tag) so strict CSP + Trusted Types never block setting `script.src`.
185
+ const target = hostScript ?? document.head.appendChild(Object.assign(document.createElement('script'), { type: 'application/json' }))
186
+ target.setAttribute('data-pru-build', buildId)
187
+ if (runtimeSrc !== null && !target.hasAttribute('data-pru-runtime'))
188
+ target.setAttribute('data-pru-runtime', runtimeSrc)
189
+ }
190
+ if (!existingSrcs.has(scriptUrl.href)) {
191
+ existingSrcs.add(scriptUrl.href)
192
+ void import(scriptUrl.href).catch((err) => {
193
+ console.error('[prunelle] failed to load module script:', scriptUrl.href, err)
194
+ })
195
+ }
196
+ }
197
+ }
198
+
142
199
  async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => void, abort: () => void }> {
143
200
  const currentLinks = [...document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')]
144
201
  const currentByHref = new Map<string, HTMLLinkElement>()
@@ -208,7 +265,7 @@ async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => voi
208
265
  }
209
266
  for (const el of moved)
210
267
  el.remove()
211
- // Sync non-builtin <head> <style> tags (skipping pru-island/pru-s styles already covered by pru-island.css).
268
+ // Sync non-builtin <head> <style> tags (skipping pru-island/pru-s styles already covered in <head>).
212
269
  const nextHeadStyles = new Set<string>()
213
270
  for (const nextStyle of nextDoc.head.querySelectorAll('style')) {
214
271
  const txt = nextStyle.textContent ?? ''
@@ -277,10 +334,13 @@ async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ h
277
334
  }
278
335
 
279
336
  export async function navigate(url: string, push = true, restore?: EntryScroll, targetDocId?: number): Promise<void> {
337
+ const wasBusy = activeController !== undefined
280
338
  // Abort any in-flight navigation so rapid clicks always win immediately
281
339
  activeController?.abort()
282
340
  const controller = new AbortController()
283
341
  activeController = controller
342
+ if (!wasBusy)
343
+ setNavigating(true)
284
344
  const root = document.documentElement
285
345
  const busy = setTimeout(() => root.setAttribute('data-pru-navigating', ''), 150)
286
346
 
@@ -306,7 +366,7 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
306
366
  return
307
367
  }
308
368
 
309
- const nextDoc = new DOMParser().parseFromString(html, 'text/html')
369
+ const nextDoc = new DOMParser().parseFromString(trustedHtml(html), 'text/html')
310
370
  resolveSuspenseTemplates(nextDoc)
311
371
 
312
372
  if (hasBlockedInlineStyle(nextDoc, csp)) {
@@ -338,27 +398,16 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
338
398
 
339
399
  const existingAnnouncer = document.getElementById(ANNOUNCER_ID)
340
400
 
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
401
  headPrep.commit()
350
402
 
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
-
403
+ // Swap body children in place via shared moveBefore helper so persisted islands, iframes, and focused inputs stay alive.
404
+ const nextContent = document.createDocumentFragment()
405
+ nextContent.append(...nextDoc.body.childNodes)
406
+ syncElementAttrs(document.body, nextDoc.body)
407
+ replaceKeeping(document.body, nextContent, existingAnnouncer !== null ? new Set([existingAnnouncer]) : undefined)
358
408
  if (existingAnnouncer !== null)
359
- nextDoc.body.appendChild(existingAnnouncer)
409
+ document.body.append(existingAnnouncer)
360
410
 
361
- document.body.replaceWith(nextDoc.body)
362
411
  if (push) {
363
412
  const newDocId = nextDocId()
364
413
  setDocId(newDocId)
@@ -369,10 +418,8 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
369
418
  }
370
419
  currentDocKey = `${nextParsed.pathname}${nextParsed.search}`
371
420
  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
421
+ syncHeadModuleScripts(nextDoc)
422
+ const fb = nextDoc.querySelector<HTMLScriptElement>('script[data-pru-fallback]')?.dataset.pruFallback
376
423
  if (fb && !('command' in HTMLButtonElement.prototype && 'closedBy' in HTMLDialogElement.prototype && typeof CSS !== 'undefined' && CSS.supports?.('position-area:block-end'))) {
377
424
  const fbUrl = new URL(fb, location.href)
378
425
  if (fbUrl.origin === location.origin)
@@ -385,10 +432,12 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
385
432
  else
386
433
  anchor = scrollToHash(hash)
387
434
 
388
- focusPrimaryLandmark(anchor)
435
+ if (anchor !== null || !isFocusedPersistedField())
436
+ focusPrimaryLandmark(anchor)
389
437
  announce(document.title)
390
438
 
391
- window.dispatchEvent(new CustomEvent('pru:navigate', { detail: { url: nextFullUrl } }))
439
+ ;(globalThis as unknown as Record<symbol, ((root?: ParentNode) => void) | undefined>)[Symbol.for('pru.reseed')]?.(document)
440
+ emit('pru:navigate', { url: nextFullUrl })
392
441
  }
393
442
 
394
443
  countView(view, nextParsed)
@@ -405,70 +454,77 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
405
454
  if (activeController === controller) {
406
455
  activeController = undefined
407
456
  root.removeAttribute('data-pru-navigating')
457
+ setNavigating(false)
408
458
  }
409
459
  }
410
460
  }
411
461
 
412
462
  if (typeof document !== 'undefined') {
413
- document.addEventListener('click', (event) => {
414
- if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
415
- return
416
- const target = event.target as Element | null
417
- const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
418
- if (!link)
419
- return
420
- const url = isEligibleLink(link)
421
- if (url === undefined)
422
- return
423
- if (url.pathname === location.pathname && url.search === location.search && url.hash) {
424
- saveScroll()
425
- return
426
- }
463
+ const doc = document as Document & Record<symbol, boolean | undefined>
464
+ if (!doc[INIT_KEY]) {
465
+ doc[INIT_KEY] = true
466
+ document.addEventListener('click', (event) => {
467
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
468
+ return
469
+ const target = event.target as Element | null
470
+ const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
471
+ if (!link)
472
+ return
473
+ const url = isEligibleLink(link)
474
+ if (url === undefined)
475
+ return
476
+ if (url.pathname === location.pathname && url.search === location.search && (url.hash || link.getAttribute('href') === '#')) {
477
+ saveScroll()
478
+ return
479
+ }
427
480
 
428
- event.preventDefault()
429
- void navigate(url.href, true)
430
- })
481
+ event.preventDefault()
482
+ void navigate(url.href, true)
483
+ })
484
+
485
+ const onIntent = (event: Event) => {
486
+ const target = event.target as Element | null
487
+ const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
488
+ // A region link prefetches its region alone, in core's region client.
489
+ if (!link || link.hasAttribute('data-no-prefetch') || link.hasAttribute('data-pru-target'))
490
+ return
491
+ // Prefetch is strictly opt-in via [data-pru-prefetch] so side-effecting links like /logout are never prefetched
492
+ if (link.closest('[data-pru-prefetch]') === null)
493
+ return
494
+ const url = isEligibleLink(link)
495
+ if (url === undefined)
496
+ return
497
+ if (url.pathname === location.pathname && url.search === location.search)
498
+ return
499
+ void prefetch(url.href)
500
+ }
431
501
 
432
- const onIntent = (event: Event) => {
433
- const target = event.target as Element | null
434
- const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
435
- // A region link prefetches its region alone, in regions().
436
- if (!link || link.hasAttribute('data-no-prefetch') || link.hasAttribute('data-pru-target'))
437
- return
438
- // Prefetch is strictly opt-in via [data-pru-prefetch] so side-effecting links like /logout are never prefetched
439
- if (link.closest('[data-pru-prefetch]') === null)
440
- return
441
- const url = isEligibleLink(link)
442
- if (url === undefined)
443
- return
444
- if (url.pathname === location.pathname && url.search === location.search)
445
- return
446
- void prefetch(url.href)
502
+ listenIntent(onIntent)
503
+
504
+ // A region swap moves the address too, so a later #hash entry of that address is no new page.
505
+ window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
506
+ window.addEventListener('popstate', (event) => {
507
+ const nextDocKey = `${location.pathname}${location.search}`
508
+ const st = event.state as { __pruIdx?: number, __pruDoc?: number } | null
509
+ if (nextDocKey === currentDocKey) {
510
+ // The newest entry wins: a slower page still in flight must not land under this address.
511
+ activeController?.abort()
512
+ // Between two hashes of one page the browser's own restoring is off, so the entry's saved scroll goes back here.
513
+ const saved = entryScroll(st)
514
+ if (saved !== undefined)
515
+ restoreScroll(saved)
516
+ else
517
+ scrollToHash(location.hash)
518
+ return
519
+ }
520
+ // Only same-document region swaps belong to core's region client; cross-document entries (even with __pruIdx) belong to spa().
521
+ if (isSameDocRegionState(st))
522
+ return
523
+ const targetDocId = typeof st?.__pruDoc === 'number' ? st.__pruDoc : undefined
524
+ void navigate(location.href, false, entryScroll(st), targetDocId)
525
+ })
526
+ // The browser's own restoring would fight the one the swap does, once the new page is in.
527
+ history.scrollRestoration = 'manual'
528
+ trackScroll()
447
529
  }
448
-
449
- listenIntent(onIntent)
450
-
451
- // A region swap moves the address too, so a later #hash entry of that address is no new page.
452
- window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
453
- window.addEventListener('popstate', (event) => {
454
- const nextDocKey = `${location.pathname}${location.search}`
455
- const st = event.state as { __pruIdx?: number, __pruDoc?: number } | null
456
- if (nextDocKey === currentDocKey) {
457
- // Between two hashes of one page the browser's own restoring is off, so the entry's saved scroll goes back here.
458
- const saved = entryScroll(st)
459
- if (saved !== undefined)
460
- restoreScroll(saved)
461
- else
462
- scrollToHash(location.hash)
463
- return
464
- }
465
- // Only same-document region swaps belong to regions(); cross-document entries (even with __pruIdx) belong to spa().
466
- if (isSameDocRegionState(st))
467
- return
468
- const targetDocId = typeof st?.__pruDoc === 'number' ? st.__pruDoc : undefined
469
- void navigate(location.href, false, entryScroll(st), targetDocId)
470
- })
471
- // The browser's own restoring would fight the one the swap does, once the new page is in.
472
- history.scrollRestoration = 'manual'
473
- trackScroll()
474
530
  }
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
- }