@prunellejs/spa 0.0.0-stage → 0.6.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 ADDED
@@ -0,0 +1,79 @@
1
+ # @prunellejs/spa Reference
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).
4
+
5
+ ## Imports
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`).
10
+
11
+ ## Partial Swaps (`regions()`)
12
+
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; add `data-pru-live` to also swap while typing (200 ms debounce, one history entry per typing burst, which a 1 s pause ends).
19
+ - Nested regions each take their own name. Asking for the inner one renders it alone (header `x-pru-region: results/sets`, outermost first, computed by the client); asking for the outer one renders it with a fresh inner; an outer swap drops in-flight fetches of the regions inside it.
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`. `append`, `refreshRegion()` and live typing swap without one.
25
+ - 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`.
26
+ - After a swap, links whose `href` matches the new URL get `aria-current="page"`, others lose it.
27
+ - 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.
28
+ - The regions client loads only on routes whose tree renders a `<Region>`: every other page ships none of it (plugin field `regionClientEntry`).
29
+ - Dispatches `window` event `pru:region` with `{ detail: { name, url } }`. `prunelle check` verifies every `data-pru-target` matches a `<Region>` in `src/`.
30
+ - `data-pru-keep-scroll="<key>"` on any element: its scroll offset survives region swaps and `spa()` swaps, and is kept per history entry.
31
+ - `await refreshRegion(name)` (from `@prunellejs/spa/regions`) redraws a region of the current address from script, after a background `fetch` to an action for instance: no history entry, focus left alone, prefetch cache skipped, `pru:region` fired.
32
+
33
+ ## Mistakes
34
+
35
+ - Compile errors: `<Region>` without `name`, `data-pru-target` on anything but `<a>`/`<form>`, `data-pru-live` on a non-GET form, `data-pru-append`/`data-pru-live` without `data-pru-target`, a region inside a region of the same name.
36
+ - `prunelle check`: a `data-pru-target` naming no `<Region>` in `src/`.
37
+ - Runtime throws: two regions of one name on a page, a requested region the route does not render.
38
+
39
+ ## Default: MPA plus `regions()`
40
+
41
+ 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]`).
42
+
43
+ ## Full-Page SPA Navigation (`spa()`)
44
+
45
+ - Intercepts same-origin `<a>` clicks, diffs `<head>` stylesheets (zero-FOUC, in the order the next page serves them, every attribute kept) and meta/title/lang, preserves `[data-persist]` islands alive across navigations, focuses `<main>`/`<h1>`, and dispatches `pru:navigate`.
46
+ - Sets `history.scrollRestoration = 'manual'` and restores the saved window and `data-pru-keep-scroll` offsets once on back/forward. Runs the swap in a view transition unless the user prefers reduced motion. Loads the regions client of a page it swaps to.
47
+ - Attributes: `data-no-spa` opts a link out; `[data-pru-prefetch]` enables hover/focus prefetch; `[data-persist]` preserves an island DOM subtree.
48
+
49
+ ## Snippets
50
+
51
+ ```ts
52
+ // prunelle.config.ts
53
+ import { defineConfig } from 'prunelle/config'
54
+ import { regions, spa } from '@prunellejs/spa'
55
+
56
+ export default defineConfig({
57
+ plugins: [regions(), spa()],
58
+ })
59
+ ```
60
+
61
+ ```tsx
62
+ // src/routes/search.tsx
63
+ import { Region } from 'prunelle'
64
+ import type { PageProps } from 'prunelle'
65
+
66
+ export default function Search({ url }: PageProps) {
67
+ const q = url.searchParams.get('q') ?? ''
68
+ return (
69
+ <>
70
+ <form method="get" data-pru-target="results" data-pru-live>
71
+ <input name="q" value={q} data-pru-sync />
72
+ </form>
73
+ <Region name="results" aria-label="Search results">
74
+ <p>Results for {q}</p>
75
+ </Region>
76
+ </>
77
+ )
78
+ }
79
+ ```
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
2
  "name": "@prunellejs/spa",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.6.0",
4
+ "description": "Opt-in SPA navigation with persistent islands plugin for Prunelle",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "sideEffects": [
8
+ "./src/client.ts",
9
+ "./src/regions.ts"
10
+ ],
11
+ "files": [
12
+ "src",
13
+ "llms.txt"
14
+ ],
15
+ "exports": {
16
+ ".": "./src/index.ts",
17
+ "./client": "./src/client.ts",
18
+ "./regions": "./src/regions.ts"
19
+ },
20
+ "engines": {
21
+ "bun": ">=1.4.0"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://github.com/Kayno0o/prunelle",
26
+ "directory": "packages/plugin-spa"
27
+ },
28
+ "peerDependencies": {
29
+ "prunelle": "^0.6.0"
30
+ }
31
+ }
@@ -0,0 +1,30 @@
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
+ export function announce(text: string): void {
19
+ let region = document.getElementById(ANNOUNCER_ID)
20
+ if (region === null) {
21
+ region = document.createElement('div')
22
+ region.id = ANNOUNCER_ID
23
+ region.setAttribute('role', 'status')
24
+ region.setAttribute('aria-live', 'polite')
25
+ region.setAttribute('aria-atomic', 'true')
26
+ applySrOnlyStyle(region)
27
+ document.body.appendChild(region)
28
+ }
29
+ region.textContent = text
30
+ }
package/src/check.ts ADDED
@@ -0,0 +1,31 @@
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/client.ts ADDED
@@ -0,0 +1,442 @@
1
+ // @prunellejs/spa client bootstrap:
2
+ // - Intercepts internal <a> clicks with AbortController cancellation (no dropped rapid clicks)
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
5
+ // - Restores scroll position on popstate, scrolls to #hash targets, manages focus & polite live announcements
6
+ // - Opt-in prefetch via [data-pru-prefetch] (bounded 8-entry / 15s TTL cache, respects Save-Data)
7
+
8
+ import type { EntryScroll } from './swap'
9
+ import { ANNOUNCER_ID, announce } from './announcer'
10
+ import { fetchKeyOf, getCachedHtml, inflightPrefetch, isSameDocRegionState, nextDocId, prefetch, prefetchCache, setDocId } from './prefetch'
11
+ import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
12
+
13
+ export { prefetch }
14
+
15
+ let activeController: AbortController | undefined
16
+ let currentDocKey = typeof location !== 'undefined' ? `${location.pathname}${location.search}` : ''
17
+
18
+ // Framework inline styles shipped in pru-island.css so SPA navigation never injects unhashed <style> tags.
19
+ const PRUNELLE_BUILTIN_STYLES = new Set([
20
+ 'pru-island,pru-slot{display:contents}',
21
+ 'pru-s{display:contents}',
22
+ ])
23
+
24
+ // One-time token and OAuth redirect endpoints must hit the server once via normal navigation, never via SPA fetch.
25
+ const SKIP_SPA_PATH_RE = /(?:^|\/)(?:oauth(?:\/|$)|verify-email(?:\/|$)|magic-link\/verify(?:\/|$))/
26
+
27
+ function isSkippedPath(pathname: string): boolean {
28
+ if (SKIP_SPA_PATH_RE.test(pathname))
29
+ return true
30
+ const raw = document.querySelector('meta[name="pru-spa-skip"]')?.getAttribute('content')
31
+ if (!raw)
32
+ return false
33
+ for (const entry of raw.split(',')) {
34
+ const prefix = entry.trim()
35
+ if (prefix && (pathname === prefix || pathname.startsWith(`${prefix}/`)))
36
+ return true
37
+ }
38
+ return false
39
+ }
40
+
41
+ // Inline <style> blocks present on initial document load already have their SHA-256 hashes in this document's CSP.
42
+ const initialInlineStyles = new Set<string>(
43
+ typeof document !== 'undefined'
44
+ ? [...document.querySelectorAll('style')].map(s => s.textContent ?? '').filter(Boolean)
45
+ : [],
46
+ )
47
+
48
+ function hasStrictStyleCsp(csp: string | null | undefined): boolean {
49
+ if (!csp)
50
+ return false
51
+ const directives = new Map<string, string>()
52
+ for (const part of csp.split(';')) {
53
+ const trimmed = part.trim()
54
+ if (!trimmed)
55
+ continue
56
+ const space = trimmed.search(/\s/)
57
+ const name = (space === -1 ? trimmed : trimmed.slice(0, space)).toLowerCase()
58
+ const value = space === -1 ? '' : trimmed.slice(space + 1)
59
+ if (!directives.has(name))
60
+ directives.set(name, value)
61
+ }
62
+ const effective = directives.get('style-src-elem') ?? directives.get('style-src') ?? directives.get('default-src')
63
+ return effective !== undefined && !effective.includes("'unsafe-inline'")
64
+ }
65
+
66
+ function hasBlockedInlineStyle(nextDoc: Document, csp: string | null | undefined): boolean {
67
+ if (!hasStrictStyleCsp(csp))
68
+ return false
69
+ for (const style of nextDoc.querySelectorAll('style')) {
70
+ const txt = style.textContent ?? ''
71
+ if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt) && !initialInlineStyles.has(txt))
72
+ return true
73
+ }
74
+ return false
75
+ }
76
+
77
+ function isEligibleLink(link: HTMLAnchorElement): URL | undefined {
78
+ if (link.target || link.hasAttribute('download') || link.closest('[data-no-spa]') !== null)
79
+ return undefined
80
+ const url = new URL(link.href, location.href)
81
+ if (url.origin !== location.origin)
82
+ return undefined
83
+ if (url.protocol !== 'http:' && url.protocol !== 'https:')
84
+ return undefined
85
+ if (isSkippedPath(url.pathname))
86
+ return undefined
87
+ return url
88
+ }
89
+
90
+ 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"]'
91
+
92
+ function resolveSuspenseTemplates(doc: Document): void {
93
+ for (const tpl of doc.querySelectorAll<HTMLTemplateElement>('template[data-ks]')) {
94
+ const id = tpl.dataset.ks
95
+ if (!id)
96
+ continue
97
+ const slot = doc.getElementById(`k-s-${id}`)
98
+ if (slot !== null) {
99
+ slot.replaceWith(tpl.content)
100
+ tpl.remove()
101
+ }
102
+ }
103
+ }
104
+
105
+ function focusPrimaryLandmark(): void {
106
+ const target = document.querySelector<HTMLElement>('main') ?? document.querySelector<HTMLElement>('h1')
107
+ if (target === null)
108
+ return
109
+ if (!target.hasAttribute('tabindex'))
110
+ target.setAttribute('tabindex', '-1')
111
+ try {
112
+ target.focus({ preventScroll: true })
113
+ }
114
+ catch {
115
+ target.focus()
116
+ }
117
+ }
118
+
119
+ async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => void, abort: () => void }> {
120
+ const currentLinks = [...document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')]
121
+ const currentByHref = new Map<string, HTMLLinkElement>()
122
+ for (const el of currentLinks)
123
+ currentByHref.set(el.getAttribute('href') ?? '', el)
124
+
125
+ const nextHrefs = new Set<string>()
126
+ // Every link this call puts in the head: the added ones and the copies of kept ones that had to move.
127
+ const added: HTMLLinkElement[] = []
128
+ const moved: HTMLLinkElement[] = []
129
+ const waitLoads: Promise<void>[] = []
130
+ const track = (link: HTMLLinkElement): void => {
131
+ waitLoads.push(new Promise<void>((resolve) => {
132
+ link.addEventListener('load', () => resolve(), { once: true })
133
+ link.addEventListener('error', () => resolve(), { once: true })
134
+ }))
135
+ added.push(link)
136
+ }
137
+
138
+ // The next page's stylesheets in the order it serves them, each as the link that stands for it here: the kept one, or a copy of the served one with every attribute it came with.
139
+ const order: HTMLLinkElement[] = []
140
+ for (const nextEl of nextDoc.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')) {
141
+ const href = nextEl.getAttribute('href') ?? ''
142
+ if (!href)
143
+ continue
144
+ nextHrefs.add(href)
145
+ order.push(currentByHref.get(href) ?? document.importNode(nextEl, true))
146
+ }
147
+
148
+ // Layer order and cascade follow the order the next page serves, kept links included. A kept link taken out and put back would leave the page unstyled until it loaded again: a copy takes the place, and the original goes once the copy loaded.
149
+ let last: HTMLLinkElement | undefined
150
+ for (const [at, link] of order.entries()) {
151
+ let el = link
152
+ const fresh = !el.isConnected
153
+ if (last === undefined) {
154
+ const firstKept = order.find(other => other.isConnected)
155
+ if (fresh && firstKept !== undefined)
156
+ firstKept.before(el)
157
+ else if (fresh)
158
+ document.head.append(el)
159
+ }
160
+ else if (fresh || !(last.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING)) {
161
+ if (!fresh) {
162
+ moved.push(el)
163
+ el = el.cloneNode() as HTMLLinkElement
164
+ order[at] = el
165
+ }
166
+ last.after(el)
167
+ }
168
+ if (!currentLinks.includes(el))
169
+ track(el)
170
+ last = el
171
+ }
172
+
173
+ if (waitLoads.length > 0)
174
+ await Promise.race([Promise.all(waitLoads), new Promise<void>(r => setTimeout(r, 1500))])
175
+
176
+ return {
177
+ abort() {
178
+ for (const el of added)
179
+ el.remove()
180
+ },
181
+ commit() {
182
+ for (const [href, el] of currentByHref) {
183
+ if (!nextHrefs.has(href))
184
+ el.remove()
185
+ }
186
+ for (const el of moved)
187
+ el.remove()
188
+ // Sync non-builtin <head> <style> tags (skipping pru-island/pru-s styles already covered by pru-island.css).
189
+ const nextHeadStyles = new Set<string>()
190
+ for (const nextStyle of nextDoc.head.querySelectorAll('style')) {
191
+ const txt = nextStyle.textContent ?? ''
192
+ if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt))
193
+ nextHeadStyles.add(txt)
194
+ }
195
+ const existingStyles = new Set<string>()
196
+ for (const curStyle of document.head.querySelectorAll('style')) {
197
+ const txt = curStyle.textContent ?? ''
198
+ if (!PRUNELLE_BUILTIN_STYLES.has(txt) && !nextHeadStyles.has(txt))
199
+ curStyle.remove()
200
+ else if (txt)
201
+ existingStyles.add(txt)
202
+ }
203
+ for (const nextStyle of nextDoc.head.querySelectorAll('style')) {
204
+ const txt = nextStyle.textContent ?? ''
205
+ if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt) && !existingStyles.has(txt)) {
206
+ document.head.appendChild(document.importNode(nextStyle, true))
207
+ existingStyles.add(txt)
208
+ }
209
+ }
210
+ // Sync <html lang>, <html dir>, <title>, and head metadata tags
211
+ const nextLang = nextDoc.documentElement.getAttribute('lang')
212
+ if (nextLang)
213
+ document.documentElement.setAttribute('lang', nextLang)
214
+ const nextDir = nextDoc.documentElement.getAttribute('dir')
215
+ if (nextDir)
216
+ document.documentElement.setAttribute('dir', nextDir)
217
+ else
218
+ document.documentElement.removeAttribute('dir')
219
+ document.title = nextDoc.title
220
+
221
+ for (const oldMeta of document.head.querySelectorAll(SYNC_HEAD_SELECTOR))
222
+ oldMeta.remove()
223
+ for (const nextMeta of nextDoc.head.querySelectorAll(SYNC_HEAD_SELECTOR))
224
+ document.head.appendChild(document.importNode(nextMeta, true))
225
+ },
226
+ }
227
+ }
228
+
229
+ async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ html: string, url: string, csp: string | null | undefined } | undefined> {
230
+ const cached = getCachedHtml(fetchKey)
231
+ if (cached !== undefined) {
232
+ prefetchCache.delete(fetchKey)
233
+ return { html: cached.html, url: cached.url, csp: cached.csp }
234
+ }
235
+ const pending = inflightPrefetch.get(fetchKey)
236
+ const prefetched = pending !== undefined ? await pending : undefined
237
+ if (signal.aborted)
238
+ return undefined
239
+ if (prefetched !== undefined) {
240
+ prefetchCache.delete(fetchKey)
241
+ return { html: prefetched.html, url: prefetched.url, csp: prefetched.csp }
242
+ }
243
+ const res = await fetch(fetchKey, {
244
+ headers: { 'x-pru-spa': '1' },
245
+ signal,
246
+ })
247
+ if (signal.aborted)
248
+ return undefined
249
+ if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html'))
250
+ return undefined
251
+ return { html: await res.text(), url: res.url || fetchKey, csp: res.headers.get('content-security-policy') }
252
+ }
253
+
254
+ export async function navigate(url: string, push = true, restore?: EntryScroll, targetDocId?: number): Promise<void> {
255
+ // Abort any in-flight navigation so rapid clicks always win immediately
256
+ activeController?.abort()
257
+ const controller = new AbortController()
258
+ activeController = controller
259
+
260
+ const targetUrl = new URL(url, location.href)
261
+ const hash = targetUrl.hash
262
+ const fetchKey = fetchKeyOf(targetUrl)
263
+
264
+ try {
265
+ const fetched = await fetchPageHtml(fetchKey, controller.signal)
266
+ if (controller.signal.aborted)
267
+ return
268
+ if (fetched === undefined) {
269
+ location.assign(url)
270
+ return
271
+ }
272
+ const { html, url: finalUrl, csp } = fetched
273
+
274
+ const nextFullUrl = hash && !finalUrl.includes('#') ? `${finalUrl}${hash}` : finalUrl
275
+ const nextParsed = new URL(nextFullUrl, location.href)
276
+ // A server redirect may land on a foreign origin: fall back to a full navigation before touching the DOM or history.
277
+ if (nextParsed.origin !== location.origin) {
278
+ location.assign(nextFullUrl)
279
+ return
280
+ }
281
+
282
+ const nextDoc = new DOMParser().parseFromString(html, 'text/html')
283
+ resolveSuspenseTemplates(nextDoc)
284
+
285
+ if (hasBlockedInlineStyle(nextDoc, csp)) {
286
+ if (push)
287
+ location.assign(nextFullUrl)
288
+ else
289
+ location.reload()
290
+ return
291
+ }
292
+
293
+ const headPrep = await prepareHeadStyles(nextDoc)
294
+ if (controller.signal.aborted) {
295
+ headPrep.abort()
296
+ return
297
+ }
298
+
299
+ const applySwap = () => {
300
+ if (push)
301
+ saveScroll()
302
+ // Elements that keep their scroll by key keep it into the next page.
303
+ const kept = readScrolls(false)
304
+
305
+ const existingAnnouncer = document.getElementById(ANNOUNCER_ID)
306
+
307
+ // Preserve live [data-persist] elements (e.g. persistent audio player or counter island) across navigations
308
+ const persisted = new Map<string, Element>()
309
+ for (const el of document.querySelectorAll('[data-persist]')) {
310
+ const key = el.getAttribute('data-persist')
311
+ if (key)
312
+ persisted.set(key, el)
313
+ }
314
+
315
+ headPrep.commit()
316
+
317
+ for (const incoming of nextDoc.querySelectorAll('[data-persist]')) {
318
+ const key = incoming.getAttribute('data-persist')
319
+ const existing = key ? persisted.get(key) : undefined
320
+ if (existing !== undefined)
321
+ incoming.replaceWith(existing)
322
+ }
323
+
324
+ if (existingAnnouncer !== null)
325
+ nextDoc.body.appendChild(existingAnnouncer)
326
+
327
+ document.body.replaceWith(nextDoc.body)
328
+ if (push) {
329
+ const newDocId = nextDocId()
330
+ setDocId(newDocId)
331
+ history.pushState({ __pruDoc: newDocId }, '', nextFullUrl)
332
+ }
333
+ else {
334
+ setDocId(targetDocId ?? nextDocId())
335
+ }
336
+ currentDocKey = `${nextParsed.pathname}${nextParsed.search}`
337
+ writeScrolls(kept)
338
+ // A page module the next page loads that this one did not (regions' client) runs now: scripts of a parsed page never do.
339
+ for (const script of nextDoc.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]'))
340
+ void import(new URL(script.getAttribute('src') ?? '', location.href).href)
341
+ const fb = nextDoc.querySelector<HTMLScriptElement>('script[data-kui-fallback]')?.dataset.kuiFallback
342
+ if (fb && !('command' in HTMLButtonElement.prototype && 'closedBy' in HTMLDialogElement.prototype && typeof CSS !== 'undefined' && CSS.supports?.('position-area:block-end'))) {
343
+ const fbUrl = new URL(fb, location.href)
344
+ if (fbUrl.origin === location.origin)
345
+ void import(fbUrl.href)
346
+ }
347
+
348
+ if (restore !== undefined) {
349
+ restoreScroll(restore)
350
+ }
351
+ else if (hash.length > 1) {
352
+ let anchorId = hash.slice(1)
353
+ try {
354
+ anchorId = decodeURIComponent(anchorId)
355
+ }
356
+ catch {
357
+ // Malformed percent-encoding in hash: use the raw fragment id.
358
+ }
359
+ const anchor = document.getElementById(anchorId)
360
+ if (anchor !== null)
361
+ anchor.scrollIntoView()
362
+ else
363
+ window.scrollTo(0, 0)
364
+ }
365
+ else {
366
+ window.scrollTo(0, 0)
367
+ }
368
+
369
+ focusPrimaryLandmark()
370
+ announce(document.title)
371
+
372
+ window.dispatchEvent(new CustomEvent('pru:navigate', { detail: { url: nextFullUrl } }))
373
+ }
374
+
375
+ await swapInTransition(applySwap)
376
+ }
377
+ catch (err) {
378
+ if (controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError'))
379
+ return
380
+ location.assign(url)
381
+ }
382
+ finally {
383
+ if (activeController === controller)
384
+ activeController = undefined
385
+ }
386
+ }
387
+
388
+ if (typeof document !== 'undefined') {
389
+ document.addEventListener('click', (event) => {
390
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
391
+ return
392
+ const target = event.target as Element | null
393
+ const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
394
+ if (!link)
395
+ return
396
+ const url = isEligibleLink(link)
397
+ if (url === undefined)
398
+ return
399
+ if (url.pathname === location.pathname && url.search === location.search && url.hash)
400
+ return
401
+
402
+ event.preventDefault()
403
+ void navigate(url.href, true)
404
+ })
405
+
406
+ const onIntent = (event: Event) => {
407
+ const target = event.target as Element | null
408
+ const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
409
+ // A region link prefetches its region alone, in regions().
410
+ if (!link || link.hasAttribute('data-no-prefetch') || link.hasAttribute('data-pru-target'))
411
+ return
412
+ // Prefetch is strictly opt-in via [data-pru-prefetch] so side-effecting links like /logout are never prefetched
413
+ if (link.closest('[data-pru-prefetch]') === null)
414
+ return
415
+ const url = isEligibleLink(link)
416
+ if (url === undefined)
417
+ return
418
+ if (url.pathname === location.pathname && url.search === location.search)
419
+ return
420
+ void prefetch(url.href)
421
+ }
422
+
423
+ document.addEventListener('pointerover', onIntent, { passive: true })
424
+ document.addEventListener('focusin', onIntent, { passive: true })
425
+
426
+ // A region swap moves the address too, so a later #hash entry of that address is no new page.
427
+ window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
428
+ window.addEventListener('popstate', (event) => {
429
+ const nextDocKey = `${location.pathname}${location.search}`
430
+ if (nextDocKey === currentDocKey)
431
+ return
432
+ const st = event.state as { __pruIdx?: number, __pruDoc?: number } | null
433
+ // Only same-document region swaps belong to regions(); cross-document entries (even with __pruIdx) belong to spa().
434
+ if (isSameDocRegionState(st))
435
+ return
436
+ const targetDocId = typeof st?.__pruDoc === 'number' ? st.__pruDoc : undefined
437
+ void navigate(location.href, false, entryScroll(st), targetDocId)
438
+ })
439
+ // The browser's own restoring would fight the one the swap does, once the new page is in.
440
+ history.scrollRestoration = 'manual'
441
+ trackScroll()
442
+ }
package/src/index.ts ADDED
@@ -0,0 +1,44 @@
1
+ // @prunellejs/spa — opt-in in-place navigation: `spa()` swaps whole pages and keeps persistent islands (~700 B gzip), `regions()` swaps one <Region> of a page. 0 B when uninstalled.
2
+
3
+ import type { BuildPluginContext, PrunellePlugin } from 'prunelle/config'
4
+ import { resolve } from 'node:path'
5
+ import { definePlugin } from 'prunelle/config'
6
+ import { escAttr } from 'prunelle/server'
7
+ import { checkRegionTargets } from './check'
8
+
9
+ export interface SpaOptions {
10
+ /** Path prefixes that must always perform a full browser navigation instead of an SPA swap (e.g. custom auth base paths). */
11
+ skipPaths?: readonly string[] | undefined
12
+ }
13
+
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
+ }
21
+
22
+ export function spa(options?: SpaOptions): PrunellePlugin {
23
+ const skipPaths = options?.skipPaths
24
+ ?.map(p => p.trim().replace(/\/+$/, ''))
25
+ .filter(p => p.length > 0)
26
+ return definePlugin({
27
+ name: '@prunellejs/spa',
28
+ clientEntry: resolve(import.meta.dir, 'client.ts'),
29
+ build(ctx) {
30
+ emitIslandStylesheet(ctx)
31
+ if (skipPaths && skipPaths.length > 0)
32
+ ctx.addHead(`<meta name="pru-spa-skip" content="${escAttr(skipPaths.join(','))}">`)
33
+ },
34
+ })
35
+ }
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
+ }
@@ -0,0 +1,105 @@
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
+ }
14
+
15
+ const PREFETCH_TTL = 15_000
16
+ const PREFETCH_MAX = 8
17
+ export const prefetchCache = new Map<string, PrefetchEntry>()
18
+ export const inflightPrefetch = new Map<string, Promise<PrefetchEntry | undefined>>()
19
+
20
+ // Document generation counter shared by spa() and regions() so popstate separates same-doc region swaps from cross-doc page navigations.
21
+ function initialDocId(): number {
22
+ const st = typeof history === 'undefined' ? undefined : history.state as { __pruDoc?: unknown } | null
23
+ return typeof st?.__pruDoc === 'number' ? st.__pruDoc : 0
24
+ }
25
+
26
+ let currentDocId = initialDocId()
27
+ let maxDocId = currentDocId
28
+
29
+ export function getDocId(): number {
30
+ return currentDocId
31
+ }
32
+
33
+ export function setDocId(id: number): void {
34
+ currentDocId = id
35
+ if (id > maxDocId)
36
+ maxDocId = id
37
+ }
38
+
39
+ export function nextDocId(): number {
40
+ return ++maxDocId
41
+ }
42
+
43
+ export function isSameDocRegionState(state: unknown): boolean {
44
+ if (typeof state !== 'object' || state === null)
45
+ return false
46
+ const s = state as { __pruIdx?: unknown, __pruDoc?: unknown }
47
+ return typeof s.__pruIdx === 'number' && (s.__pruDoc === undefined || s.__pruDoc === currentDocId)
48
+ }
49
+
50
+ /** The cache key of a page, or of one region of it, given by its path from the outermost region (`results/sets`). */
51
+ export function fetchKeyOf(url: URL, region?: string): string {
52
+ const key = `${url.origin}${url.pathname}${url.search}`
53
+ return region === undefined ? key : `${region} ${key}`
54
+ }
55
+
56
+ export function getCachedHtml(href: string): PrefetchEntry | undefined {
57
+ const hit = prefetchCache.get(href)
58
+ if (hit === undefined)
59
+ return undefined
60
+ if (Date.now() - hit.ts > PREFETCH_TTL) {
61
+ prefetchCache.delete(href)
62
+ return undefined
63
+ }
64
+ return hit
65
+ }
66
+
67
+ function putCachedHtml(href: string, entry: PrefetchEntry): void {
68
+ prefetchCache.delete(href)
69
+ prefetchCache.set(href, entry)
70
+ if (prefetchCache.size > PREFETCH_MAX) {
71
+ const oldest = prefetchCache.keys().next()
72
+ if (!oldest.done)
73
+ prefetchCache.delete(oldest.value)
74
+ }
75
+ }
76
+
77
+ export async function prefetch(url: string, region?: string): Promise<void> {
78
+ const clean = new URL(url, location.href)
79
+ clean.hash = ''
80
+ const key = fetchKeyOf(clean, region)
81
+ if (getCachedHtml(key) !== undefined || inflightPrefetch.has(key))
82
+ return
83
+ const conn = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection
84
+ if (conn?.saveData)
85
+ return
86
+
87
+ const task = (async (): Promise<PrefetchEntry | undefined> => {
88
+ try {
89
+ const res = await fetch(clean.href, { headers: region === undefined ? { 'x-pru-spa': '1' } : { 'x-pru-region': region } })
90
+ if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html'))
91
+ return undefined
92
+ const entry: PrefetchEntry = { html: await res.text(), url: res.url || clean.href, ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), csp: res.headers.get('content-security-policy') }
93
+ putCachedHtml(key, entry)
94
+ return entry
95
+ }
96
+ catch {
97
+ return undefined
98
+ }
99
+ finally {
100
+ inflightPrefetch.delete(key)
101
+ }
102
+ })()
103
+ inflightPrefetch.set(key, task)
104
+ await task
105
+ }
package/src/regions.ts ADDED
@@ -0,0 +1,426 @@
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
+ // - 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
8
+ // - 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
9
+ // - prefetch on hover and focus inside [data-pru-prefetch], through the cache spa() shares
10
+
11
+ import type { PrefetchEntry } from './prefetch'
12
+ import type { EntryScroll } from './swap'
13
+ import { announce } from './announcer'
14
+ import { fetchKeyOf, getCachedHtml, getDocId, inflightPrefetch, isSameDocRegionState, prefetch, prefetchCache } from './prefetch'
15
+ import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
16
+
17
+ const BUSY_DELAY = 150
18
+ const LIVE_DEBOUNCE = 200
19
+ const BURST_PAUSE = 1000
20
+
21
+ interface RegionState { __pruIdx: number, __pruDoc?: number | undefined, __pruRegion?: string | undefined }
22
+
23
+ function safeGetAttribute(el: Element, name: string): string | null {
24
+ return Element.prototype.getAttribute.call(el, name)
25
+ }
26
+
27
+ interface Swap {
28
+ url: URL
29
+ region: string
30
+ append?: boolean
31
+ /** `burst`: pushed by the first change of a typing burst, replaced by the rest. */
32
+ history: 'push' | 'replace' | 'burst' | 'none'
33
+ /** Moves focus into the region (a link did it), not for a form the user is typing in. */
34
+ focus?: boolean
35
+ trigger?: Element
36
+ /** Skips the prefetch cache: the region is redrawn because the server's state changed. */
37
+ fresh?: boolean
38
+ /** A form posted to `url`: the swap shows the page its redirect lands on. */
39
+ post?: { form: HTMLFormElement, body: FormData }
40
+ /** Where the post's redirect ended, once it did. */
41
+ landed?: string
42
+ /** The scroll a back or forward entry had, put back after the swap. */
43
+ restore?: EntryScroll
44
+ }
45
+
46
+ function stateOf(state: unknown): RegionState | undefined {
47
+ return typeof state === 'object' && state !== null && typeof (state as RegionState).__pruIdx === 'number' ? state as RegionState : undefined
48
+ }
49
+
50
+ const controllers = new Map<string, AbortController>()
51
+ let idx = stateOf(typeof history === 'undefined' ? undefined : history.state)?.__pruIdx ?? 0
52
+ let lastRegion = stateOf(typeof history === 'undefined' ? undefined : history.state)?.__pruRegion
53
+ // The page and query the document shows: an entry that differs from it only in its hash needs no fetch.
54
+ let shown = typeof location === 'undefined' ? '' : location.pathname + location.search
55
+ // The pages Load more added to the document since its last swap, beside the one it shows: their #hash links scroll too.
56
+ const appended = new Set<string>()
57
+ let burstOpen = false
58
+ let burstTimer: ReturnType<typeof setTimeout> | undefined
59
+ let liveTimer: ReturnType<typeof setTimeout> | undefined
60
+
61
+ function findRegion(name: string): HTMLElement | null {
62
+ return document.querySelector<HTMLElement>(`[data-pru-region="${name.replace(/["\\]/g, '\\$&')}"]`)
63
+ }
64
+
65
+ // A region's path from the outermost one around it: `results/sets` for `sets` inside `results`. The server renders through the outer ones.
66
+ function pathOf(region: HTMLElement): string {
67
+ const names: string[] = []
68
+ for (let el: Element | null = region; el !== null; el = el.parentElement?.closest('[data-pru-region]') ?? null)
69
+ names.unshift(el.getAttribute('data-pru-region')!)
70
+ return names.join('/')
71
+ }
72
+
73
+ async function load(swap: Swap, region: string, signal: AbortSignal): Promise<PrefetchEntry | undefined> {
74
+ const { url, post } = swap
75
+ const key = fetchKeyOf(url, region)
76
+ const ready = swap.fresh === true || post !== undefined ? undefined : getCachedHtml(key) ?? await inflightPrefetch.get(key)
77
+ if (ready !== undefined) {
78
+ prefetchCache.delete(key)
79
+ return ready
80
+ }
81
+ const res = await fetch(fetchKeyOf(url), { headers: { 'x-pru-region': region }, signal, ...(post === undefined ? {} : { method: 'POST', body: post.body }) })
82
+ if (post !== undefined)
83
+ swap.landed = res.url
84
+ if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html'))
85
+ return undefined
86
+ 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') }
87
+ }
88
+
89
+ // 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).
90
+ function contentOf(entry: PrefetchEntry, path: string): { content: DocumentFragment, title: string | undefined } | undefined {
91
+ const template = document.createElement('template')
92
+ if (entry.region === path) {
93
+ template.innerHTML = entry.html
94
+ // The title is HTML text, percent-encoded in the header: a textarea unescapes it.
95
+ const unescape = document.createElement('textarea')
96
+ unescape.innerHTML = entry.title === null ? '' : decodeURIComponent(entry.title)
97
+ return { content: template.content, title: entry.title === null ? undefined : unescape.value }
98
+ }
99
+ const page = new DOMParser().parseFromString(entry.html, 'text/html')
100
+ const found = page.querySelector(`[data-pru-region="${path.split('/').at(-1)!.replace(/["\\]/g, '\\$&')}"]`)
101
+ if (found === null)
102
+ return undefined
103
+ template.innerHTML = found.innerHTML
104
+ return { content: template.content, title: page.title === '' ? undefined : page.title }
105
+ }
106
+
107
+ function record(url: URL, name: string, mode: 'push' | 'replace' | 'burst'): void {
108
+ clearTimeout(burstTimer)
109
+ // A replace inside the region the entry was made for keeps that region, so back and forward restore the whole of it.
110
+ const before = stateOf(history.state)?.__pruRegion
111
+ const around = mode === 'replace' && before !== undefined && before !== name && findRegion(before)?.contains(findRegion(name)) === true ? before : name
112
+ let push = mode === 'push' || (mode === 'burst' && !burstOpen)
113
+ if (mode === 'burst') {
114
+ burstOpen = true
115
+ burstTimer = setTimeout(() => { burstOpen = false }, BURST_PAUSE)
116
+ }
117
+ else {
118
+ burstOpen = false
119
+ }
120
+ const next = `${url.pathname}${url.search}${url.hash}`
121
+ if (next === `${location.pathname}${location.search}${location.hash}`)
122
+ push = false
123
+ const prev = (typeof history.state === 'object' && history.state !== null ? history.state : {}) as Record<string, unknown>
124
+ const docId = getDocId()
125
+ if (push) {
126
+ // The entry left behind is stamped first, so back and forward can tell it from a page of another document.
127
+ history.replaceState({ ...prev, __pruDoc: docId, __pruIdx: idx }, '')
128
+ idx++
129
+ history.pushState({ __pruDoc: docId, __pruIdx: idx, __pruRegion: around }, '', next)
130
+ }
131
+ else {
132
+ history.replaceState({ ...prev, __pruDoc: docId, __pruIdx: idx, __pruRegion: around }, '', next)
133
+ }
134
+ lastRegion = around
135
+ shown = url.pathname + url.search
136
+ }
137
+
138
+ function focusNode(el: Element | null | undefined): void {
139
+ if (el === null || el === undefined)
140
+ return
141
+ if (!el.hasAttribute('tabindex'))
142
+ el.setAttribute('tabindex', '-1')
143
+ ;(el as HTMLElement).focus({ preventScroll: true })
144
+ }
145
+
146
+ // Links and fields the app marked data-pru-sync follow the URL the swap just set.
147
+ function syncParams(): void {
148
+ const params = new URL(location.href).searchParams
149
+ for (const el of document.querySelectorAll<HTMLElement>('[data-pru-sync]')) {
150
+ if (el instanceof HTMLAnchorElement) {
151
+ const url = new URL(el.href, location.href)
152
+ if (url.origin !== location.origin)
153
+ continue
154
+ for (const name of (el.getAttribute('data-pru-sync') ?? '').split(/\s+/).filter(Boolean)) {
155
+ url.searchParams.delete(name)
156
+ for (const value of params.getAll(name))
157
+ url.searchParams.append(name, value)
158
+ }
159
+ el.setAttribute('href', `${url.pathname}${url.search}${url.hash}`)
160
+ }
161
+ else if ((el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement) && el !== document.activeElement) {
162
+ el.value = params.get(el.name) ?? ''
163
+ }
164
+ }
165
+ }
166
+
167
+ // The links that point at the page the swap landed on say so; the ones that did and no longer do stop.
168
+ function syncCurrent(): void {
169
+ for (const link of document.querySelectorAll<HTMLAnchorElement>('a[href]')) {
170
+ if (link.origin === location.origin && link.hash === '' && link.pathname + link.search === location.pathname + location.search)
171
+ link.setAttribute('aria-current', 'page')
172
+ else if (link.getAttribute('aria-current') === 'page')
173
+ link.removeAttribute('aria-current')
174
+ }
175
+ }
176
+
177
+ function elementOfHash(hash: string): HTMLElement | null {
178
+ const raw = hash.slice(1)
179
+ let id: string
180
+ try {
181
+ id = decodeURIComponent(raw)
182
+ }
183
+ catch {
184
+ id = raw
185
+ }
186
+ return id === '' ? null : document.getElementById(id)
187
+ }
188
+
189
+ async function apply(region: HTMLElement, found: { content: DocumentFragment, title: string | undefined }, swap: Swap, finalUrl: URL): Promise<void> {
190
+ const { content, title } = found
191
+ // A typing burst and an append stay put: a transition freezes the page, and the field being typed in with it.
192
+ const animate = !swap.append && swap.history !== 'burst' && swap.fresh !== true
193
+ await swapInTransition(() => {
194
+ if (swap.append)
195
+ appended.add(shown)
196
+ else
197
+ appended.clear()
198
+ if (swap.history !== 'none') {
199
+ saveScroll()
200
+ record(finalUrl, swap.region, swap.history)
201
+ }
202
+ const kept = readScrolls(false)
203
+ const first = content.firstElementChild
204
+ if (swap.append) {
205
+ if (swap.trigger !== undefined && region.contains(swap.trigger))
206
+ swap.trigger.remove()
207
+ region.append(content)
208
+ }
209
+ else {
210
+ // A fetch for a region about to be replaced must not land in the new one.
211
+ for (const inner of region.querySelectorAll('[data-pru-region]'))
212
+ controllers.get(inner.getAttribute('data-pru-region')!)?.abort()
213
+ region.replaceChildren(content)
214
+ writeScrolls(kept)
215
+ if (swap.history !== 'none' && !region.hasAttribute('data-pru-keep-scroll'))
216
+ region.scrollTop = 0
217
+ }
218
+ if (title !== undefined)
219
+ document.title = title
220
+ syncParams()
221
+ syncCurrent()
222
+ if (swap.restore !== undefined)
223
+ restoreScroll(swap.restore)
224
+ else if (!swap.append && swap.history !== 'none')
225
+ elementOfHash(finalUrl.hash)?.scrollIntoView()
226
+ if (swap.focus === true)
227
+ focusNode(swap.append ? first : region)
228
+ const label = region.getAttribute('aria-label')
229
+ if (label !== null)
230
+ announce(label)
231
+ window.dispatchEvent(new CustomEvent('pru:region', { detail: { name: swap.region, url: location.href } }))
232
+ }, animate)
233
+ }
234
+
235
+ // Resolves false when the region could not be swapped: no such region, a failed fetch, or an answer without it.
236
+ async function swapRegion(swap: Swap): Promise<boolean> {
237
+ const name = swap.region
238
+ if (findRegion(name) === null)
239
+ return false
240
+ controllers.get(name)?.abort()
241
+ const controller = new AbortController()
242
+ controllers.set(name, controller)
243
+ const path = pathOf(findRegion(name)!)
244
+ const busy = setTimeout(() => findRegion(name)?.setAttribute('aria-busy', 'true'), BUSY_DELAY)
245
+ try {
246
+ const entry = await load(swap, path, controller.signal)
247
+ if (controller.signal.aborted)
248
+ return true
249
+ const content = entry === undefined ? undefined : contentOf(entry, path)
250
+ const region = findRegion(name)
251
+ if (entry === undefined || content === undefined || region === null)
252
+ return false
253
+ const finalUrl = entry.url ? new URL(entry.url, location.href) : swap.url
254
+ if (finalUrl.origin !== location.origin)
255
+ return false
256
+ if (swap.url.hash && !finalUrl.hash)
257
+ finalUrl.hash = swap.url.hash
258
+ await apply(region, content, swap, finalUrl)
259
+ return true
260
+ }
261
+ catch (err) {
262
+ return controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError')
263
+ }
264
+ finally {
265
+ clearTimeout(busy)
266
+ if (controllers.get(name) === controller) {
267
+ controllers.delete(name)
268
+ findRegion(name)?.removeAttribute('aria-busy')
269
+ }
270
+ }
271
+ }
272
+
273
+ // 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.
274
+ async function navigate(swap: Swap): Promise<void> {
275
+ if (await swapRegion(swap))
276
+ return
277
+ if (swap.post === undefined)
278
+ location.assign(swap.url.href)
279
+ else if (swap.landed)
280
+ location.assign(swap.landed)
281
+ else
282
+ swap.post.form.submit()
283
+ }
284
+
285
+ /** 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. */
286
+ export async function refreshRegion(name: string): Promise<void> {
287
+ if (!await swapRegion({ url: new URL(location.href), region: name, history: 'none', fresh: true }))
288
+ 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.`)
289
+ }
290
+
291
+ function formMethod(form: HTMLFormElement, submitter?: HTMLElement | null): string {
292
+ const rawMethod = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formmethod') : null)
293
+ ?? safeGetAttribute(form, 'method')
294
+ ?? 'get'
295
+ return rawMethod.toLowerCase()
296
+ }
297
+
298
+ function formAction(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
299
+ // Read raw attributes via Element.prototype.getAttribute so <input name="action"> cannot DOM-clobber form.action.
300
+ const rawAction = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formaction') : null)
301
+ ?? safeGetAttribute(form, 'action')
302
+ ?? ''
303
+ return new URL(rawAction, location.href)
304
+ }
305
+
306
+ function formUrl(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
307
+ const url = formAction(form, submitter)
308
+ // A field left empty stays out of the address, so it names only the filters in use.
309
+ const params = new URLSearchParams()
310
+ for (const [key, value] of new FormData(form, submitter ?? undefined)) {
311
+ if (typeof value === 'string' && value !== '')
312
+ params.append(key, value)
313
+ }
314
+ url.search = params.toString()
315
+ return url
316
+ }
317
+
318
+ function missingRegion(name: string, element: string): boolean {
319
+ if (findRegion(name) !== null)
320
+ return false
321
+ 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.`)
322
+ return true
323
+ }
324
+
325
+ function linkOf(event: Event): HTMLAnchorElement | null {
326
+ return (event.target as Element | null)?.closest?.<HTMLAnchorElement>('a[href][data-pru-target]') ?? null
327
+ }
328
+
329
+ if (typeof document !== 'undefined') {
330
+ document.addEventListener('click', (event) => {
331
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
332
+ return
333
+ const link = linkOf(event)
334
+ if (link === null || link.target !== '' || link.hasAttribute('download'))
335
+ return
336
+ const url = new URL(link.href, location.href)
337
+ const name = link.getAttribute('data-pru-target')!
338
+ const append = link.hasAttribute('data-pru-append')
339
+ if (url.origin !== location.origin || missingRegion(name, `<a href="${link.getAttribute('href')}">`))
340
+ return
341
+ event.preventDefault()
342
+ // A hash already on the page is a scroll when the document holds the page the link names, with the address keeping its page.
343
+ const page = url.pathname + url.search
344
+ if (!append && (page === shown || appended.has(page)) && elementOfHash(url.hash) !== null) {
345
+ location.hash = url.hash
346
+ return
347
+ }
348
+ void navigate({ url, region: name, append, history: append ? 'replace' : 'push', focus: true, trigger: link })
349
+ }, true)
350
+
351
+ document.addEventListener('submit', (event) => {
352
+ const form = event.target as HTMLFormElement
353
+ if (!(form instanceof HTMLFormElement))
354
+ return
355
+ const submitter = (event as SubmitEvent).submitter
356
+ const name = safeGetAttribute(form, 'data-pru-target')
357
+ const method = formMethod(form, submitter)
358
+ if (event.defaultPrevented || name === null || (method !== 'get' && method !== 'post') || missingRegion(name, '<form>'))
359
+ return
360
+ event.preventDefault()
361
+ clearTimeout(liveTimer)
362
+ if (method === 'get')
363
+ void navigate({ url: formUrl(form, submitter), region: name, history: 'push' })
364
+ else
365
+ void navigate({ url: formAction(form, submitter), region: name, history: 'push', post: { form, body: new FormData(form, submitter ?? undefined) } })
366
+ }, true)
367
+
368
+ document.addEventListener('input', (event) => {
369
+ const form = (event.target as Element | null)?.closest?.<HTMLFormElement>('form[data-pru-live][data-pru-target]')
370
+ if (form === null || form === undefined || formMethod(form) !== 'get')
371
+ return
372
+ clearTimeout(liveTimer)
373
+ liveTimer = setTimeout(() => {
374
+ const name = safeGetAttribute(form, 'data-pru-target')!
375
+ if (!missingRegion(name, '<form>'))
376
+ void navigate({ url: formUrl(form), region: name, history: 'burst' })
377
+ }, LIVE_DEBOUNCE)
378
+ })
379
+
380
+ const onIntent = (event: Event) => {
381
+ const link = linkOf(event)
382
+ if (link === null || link.hasAttribute('data-no-prefetch') || link.closest('[data-pru-prefetch]') === null)
383
+ return
384
+ const url = new URL(link.href, location.href)
385
+ if (url.origin === location.origin && `${url.pathname}${url.search}` !== `${location.pathname}${location.search}`)
386
+ {
387
+ const region = findRegion(link.getAttribute('data-pru-target')!)
388
+ if (region !== null)
389
+ void prefetch(url.href, pathOf(region))
390
+ }
391
+ }
392
+ document.addEventListener('pointerover', onIntent, { passive: true })
393
+ document.addEventListener('focusin', onIntent, { passive: true })
394
+
395
+ // Keep region state aligned when spa() swaps to another document (including popstate back to a document with prior region entries).
396
+ window.addEventListener('pru:navigate', () => {
397
+ shown = location.pathname + location.search
398
+ appended.clear()
399
+ const st = stateOf(history.state)
400
+ idx = st?.__pruIdx ?? 0
401
+ lastRegion = st?.__pruRegion
402
+ burstOpen = false
403
+ })
404
+ window.addEventListener('popstate', (event) => {
405
+ if (!isSameDocRegionState(event.state))
406
+ return
407
+ const state = stateOf(event.state)
408
+ const sameDocument = location.pathname + location.search === shown
409
+ shown = location.pathname + location.search
410
+ if (state === undefined)
411
+ return
412
+ const name = state.__pruIdx < idx ? lastRegion : state.__pruRegion
413
+ idx = state.__pruIdx
414
+ lastRegion = state.__pruRegion
415
+ burstOpen = false
416
+ const restore = entryScroll(event.state)
417
+ if (name === undefined || sameDocument) {
418
+ // With spa() the browser leaves the scroll to the page, a swap or not.
419
+ if (restore !== undefined && history.scrollRestoration === 'manual')
420
+ restoreScroll(restore)
421
+ return
422
+ }
423
+ void navigate({ url: new URL(location.href), region: name, history: 'none', ...(restore === undefined ? {} : { restore }) })
424
+ })
425
+ trackScroll()
426
+ }
package/src/swap.ts ADDED
@@ -0,0 +1,75 @@
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
+ type Transitions = Document & { startViewTransition?: (update: () => void) => { updateCallbackDone: Promise<void> } }
67
+
68
+ /** Runs the DOM `update` inside a view transition where the browser has them and the user allows motion; resolves once it ran. */
69
+ export async function swapInTransition(update: () => void, animate = true): Promise<void> {
70
+ const doc = document as Transitions
71
+ if (animate && typeof doc.startViewTransition === 'function' && !matchMedia('(prefers-reduced-motion: reduce)').matches)
72
+ await doc.startViewTransition(update).updateCallbackDone
73
+ else
74
+ update()
75
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.