@prunellejs/spa 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/llms.txt +70 -0
- package/package.json +29 -4
- package/src/announcer.ts +30 -0
- package/src/check.ts +31 -0
- package/src/client.ts +417 -0
- package/src/index.ts +31 -0
- package/src/prefetch.ts +105 -0
- package/src/regions.ts +426 -0
- package/src/swap.ts +75 -0
- package/README.md +0 -3
package/llms.txt
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
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):
|
|
14
|
+
|
|
15
|
+
- `<a href="/items?p=2" data-pru-target="results">`: sends `x-pru-region: results` (or `outer/inner` for nested regions), swaps inner HTML, updates `document.title` from `x-pru-title`, pushes history, manages focus & `aria-label` announcement, sets `aria-busy="true"` after 150 ms.
|
|
16
|
+
- `data-pru-append` on a targeted `<a>`: appends response HTML, removes clicked link (Load more), replaces history entry.
|
|
17
|
+
- `<form method="get" data-pru-target="results">`: swaps on submit; add `data-pru-live` to also swap while typing (200 ms debounce, one history entry per typing burst).
|
|
18
|
+
- `data-pru-sync="q tag"` on a link or input/select: keeps query params or field values outside the region in sync after every swap.
|
|
19
|
+
- `[data-pru-prefetch]` ancestor: prefetches targeted links on hover/focus (`data-no-prefetch` opts a link out).
|
|
20
|
+
- `<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.
|
|
21
|
+
- Empty fields are dropped from the URL of a GET form.
|
|
22
|
+
- Swaps run in `document.startViewTransition` where supported, and not under `prefers-reduced-motion: reduce`. `append`, `refreshRegion()` and live typing swap without one.
|
|
23
|
+
- 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`.
|
|
24
|
+
- After a swap, links whose `href` matches the new URL get `aria-current="page"`, others lose it.
|
|
25
|
+
- 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.
|
|
26
|
+
- The regions client loads only on routes whose tree renders a `<Region>`: every other page ships none of it (plugin field `regionClientEntry`).
|
|
27
|
+
- Dispatches `window` event `pru:region` with `{ detail: { name, url } }`. `prunelle check` verifies every `data-pru-target` matches a `<Region>` in `src/`.
|
|
28
|
+
- `data-pru-keep-scroll="<key>"` on any element: its scroll offset survives region swaps and `spa()` swaps, and is kept per history entry.
|
|
29
|
+
|
|
30
|
+
## Default: MPA plus `regions()`
|
|
31
|
+
|
|
32
|
+
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]`).
|
|
33
|
+
|
|
34
|
+
## Full-Page SPA Navigation (`spa()`)
|
|
35
|
+
|
|
36
|
+
- Intercepts same-origin `<a>` clicks, diffs `<head>` stylesheets (zero-FOUC, in the order the next page serves them, every attribute kept) and meta/title/lang, preserves `[data-persist]` islands alive across navigations, focuses `<main>`/`<h1>`, and dispatches `pru:navigate`.
|
|
37
|
+
- Sets `history.scrollRestoration = 'manual'` and restores the saved window and `data-pru-keep-scroll` offsets once on back/forward. Runs the swap in a view transition unless the user prefers reduced motion. Loads the regions client of a page it swaps to.
|
|
38
|
+
- Attributes: `data-no-spa` opts a link out; `[data-pru-prefetch]` enables hover/focus prefetch; `[data-persist]` preserves an island DOM subtree.
|
|
39
|
+
|
|
40
|
+
## Snippets
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// prunelle.config.ts
|
|
44
|
+
import { defineConfig } from 'prunelle/config'
|
|
45
|
+
import { regions, spa } from '@prunellejs/spa'
|
|
46
|
+
|
|
47
|
+
export default defineConfig({
|
|
48
|
+
plugins: [regions(), spa()],
|
|
49
|
+
})
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
```tsx
|
|
53
|
+
// src/routes/search.tsx
|
|
54
|
+
import { Region } from 'prunelle'
|
|
55
|
+
import type { PageProps } from 'prunelle'
|
|
56
|
+
|
|
57
|
+
export default function Search({ url }: PageProps) {
|
|
58
|
+
const q = url.searchParams.get('q') ?? ''
|
|
59
|
+
return (
|
|
60
|
+
<>
|
|
61
|
+
<form method="get" data-pru-target="results" data-pru-live>
|
|
62
|
+
<input name="q" value={q} data-pru-sync />
|
|
63
|
+
</form>
|
|
64
|
+
<Region name="results" aria-label="Search results">
|
|
65
|
+
<p>Results for {q}</p>
|
|
66
|
+
</Region>
|
|
67
|
+
</>
|
|
68
|
+
)
|
|
69
|
+
}
|
|
70
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/spa",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.5.1",
|
|
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.5.1"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/announcer.ts
ADDED
|
@@ -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,417 @@
|
|
|
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 = /(?:^|\/)auth\/(?:oauth(?:\/|$)|verify-email(?:\/|$)|magic-link\/verify(?:\/|$))/
|
|
26
|
+
|
|
27
|
+
// Inline <style> blocks present on initial document load already have their SHA-256 hashes in this document's CSP.
|
|
28
|
+
const initialInlineStyles = new Set<string>(
|
|
29
|
+
typeof document !== 'undefined'
|
|
30
|
+
? [...document.querySelectorAll('style')].map(s => s.textContent ?? '').filter(Boolean)
|
|
31
|
+
: [],
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
function hasStrictStyleCsp(csp: string | null | undefined): boolean {
|
|
35
|
+
if (!csp)
|
|
36
|
+
return false
|
|
37
|
+
const directives = new Map<string, string>()
|
|
38
|
+
for (const part of csp.split(';')) {
|
|
39
|
+
const trimmed = part.trim()
|
|
40
|
+
if (!trimmed)
|
|
41
|
+
continue
|
|
42
|
+
const space = trimmed.search(/\s/)
|
|
43
|
+
const name = (space === -1 ? trimmed : trimmed.slice(0, space)).toLowerCase()
|
|
44
|
+
const value = space === -1 ? '' : trimmed.slice(space + 1)
|
|
45
|
+
if (!directives.has(name))
|
|
46
|
+
directives.set(name, value)
|
|
47
|
+
}
|
|
48
|
+
const effective = directives.get('style-src-elem') ?? directives.get('style-src') ?? directives.get('default-src')
|
|
49
|
+
return effective !== undefined && !effective.includes("'unsafe-inline'")
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function hasBlockedInlineStyle(nextDoc: Document, csp: string | null | undefined): boolean {
|
|
53
|
+
if (!hasStrictStyleCsp(csp))
|
|
54
|
+
return false
|
|
55
|
+
for (const style of nextDoc.querySelectorAll('style')) {
|
|
56
|
+
const txt = style.textContent ?? ''
|
|
57
|
+
if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt) && !initialInlineStyles.has(txt))
|
|
58
|
+
return true
|
|
59
|
+
}
|
|
60
|
+
return false
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function isEligibleLink(link: HTMLAnchorElement): URL | undefined {
|
|
64
|
+
if (link.target || link.hasAttribute('download') || link.hasAttribute('data-no-spa'))
|
|
65
|
+
return undefined
|
|
66
|
+
const url = new URL(link.href, location.href)
|
|
67
|
+
if (url.origin !== location.origin)
|
|
68
|
+
return undefined
|
|
69
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:')
|
|
70
|
+
return undefined
|
|
71
|
+
if (SKIP_SPA_PATH_RE.test(url.pathname))
|
|
72
|
+
return undefined
|
|
73
|
+
return url
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
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"]'
|
|
77
|
+
|
|
78
|
+
function resolveSuspenseTemplates(doc: Document): void {
|
|
79
|
+
for (const tpl of doc.querySelectorAll<HTMLTemplateElement>('template[data-ks]')) {
|
|
80
|
+
const id = tpl.dataset.ks
|
|
81
|
+
if (!id)
|
|
82
|
+
continue
|
|
83
|
+
const slot = doc.getElementById(`k-s-${id}`)
|
|
84
|
+
if (slot !== null) {
|
|
85
|
+
slot.replaceWith(tpl.content)
|
|
86
|
+
tpl.remove()
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function focusPrimaryLandmark(): void {
|
|
92
|
+
const target = document.querySelector<HTMLElement>('main') ?? document.querySelector<HTMLElement>('h1')
|
|
93
|
+
if (target === null)
|
|
94
|
+
return
|
|
95
|
+
if (!target.hasAttribute('tabindex'))
|
|
96
|
+
target.setAttribute('tabindex', '-1')
|
|
97
|
+
try {
|
|
98
|
+
target.focus({ preventScroll: true })
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
target.focus()
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => void, abort: () => void }> {
|
|
106
|
+
const currentLinks = [...document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')]
|
|
107
|
+
const currentByHref = new Map<string, HTMLLinkElement>()
|
|
108
|
+
for (const el of currentLinks)
|
|
109
|
+
currentByHref.set(el.getAttribute('href') ?? '', el)
|
|
110
|
+
|
|
111
|
+
const nextHrefs = new Set<string>()
|
|
112
|
+
// Every link this call puts in the head: the added ones and the copies of kept ones that had to move.
|
|
113
|
+
const added: HTMLLinkElement[] = []
|
|
114
|
+
const moved: HTMLLinkElement[] = []
|
|
115
|
+
const waitLoads: Promise<void>[] = []
|
|
116
|
+
const track = (link: HTMLLinkElement): void => {
|
|
117
|
+
waitLoads.push(new Promise<void>((resolve) => {
|
|
118
|
+
link.addEventListener('load', () => resolve(), { once: true })
|
|
119
|
+
link.addEventListener('error', () => resolve(), { once: true })
|
|
120
|
+
}))
|
|
121
|
+
added.push(link)
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// 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.
|
|
125
|
+
const order: HTMLLinkElement[] = []
|
|
126
|
+
for (const nextEl of nextDoc.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')) {
|
|
127
|
+
const href = nextEl.getAttribute('href') ?? ''
|
|
128
|
+
if (!href)
|
|
129
|
+
continue
|
|
130
|
+
nextHrefs.add(href)
|
|
131
|
+
order.push(currentByHref.get(href) ?? document.importNode(nextEl, true))
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// 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.
|
|
135
|
+
let last: HTMLLinkElement | undefined
|
|
136
|
+
for (const [at, link] of order.entries()) {
|
|
137
|
+
let el = link
|
|
138
|
+
const fresh = !el.isConnected
|
|
139
|
+
if (last === undefined) {
|
|
140
|
+
const firstKept = order.find(other => other.isConnected)
|
|
141
|
+
if (fresh && firstKept !== undefined)
|
|
142
|
+
firstKept.before(el)
|
|
143
|
+
else if (fresh)
|
|
144
|
+
document.head.append(el)
|
|
145
|
+
}
|
|
146
|
+
else if (fresh || !(last.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING)) {
|
|
147
|
+
if (!fresh) {
|
|
148
|
+
moved.push(el)
|
|
149
|
+
el = el.cloneNode() as HTMLLinkElement
|
|
150
|
+
order[at] = el
|
|
151
|
+
}
|
|
152
|
+
last.after(el)
|
|
153
|
+
}
|
|
154
|
+
if (!currentLinks.includes(el))
|
|
155
|
+
track(el)
|
|
156
|
+
last = el
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
if (waitLoads.length > 0)
|
|
160
|
+
await Promise.race([Promise.all(waitLoads), new Promise<void>(r => setTimeout(r, 1500))])
|
|
161
|
+
|
|
162
|
+
return {
|
|
163
|
+
abort() {
|
|
164
|
+
for (const el of added)
|
|
165
|
+
el.remove()
|
|
166
|
+
},
|
|
167
|
+
commit() {
|
|
168
|
+
for (const [href, el] of currentByHref) {
|
|
169
|
+
if (!nextHrefs.has(href))
|
|
170
|
+
el.remove()
|
|
171
|
+
}
|
|
172
|
+
for (const el of moved)
|
|
173
|
+
el.remove()
|
|
174
|
+
// Sync non-builtin <head> <style> tags (skipping pru-island/pru-s styles already covered by pru-island.css).
|
|
175
|
+
const nextHeadStyles = new Set<string>()
|
|
176
|
+
for (const nextStyle of nextDoc.head.querySelectorAll('style')) {
|
|
177
|
+
const txt = nextStyle.textContent ?? ''
|
|
178
|
+
if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt))
|
|
179
|
+
nextHeadStyles.add(txt)
|
|
180
|
+
}
|
|
181
|
+
const existingStyles = new Set<string>()
|
|
182
|
+
for (const curStyle of document.head.querySelectorAll('style')) {
|
|
183
|
+
const txt = curStyle.textContent ?? ''
|
|
184
|
+
if (!PRUNELLE_BUILTIN_STYLES.has(txt) && !nextHeadStyles.has(txt))
|
|
185
|
+
curStyle.remove()
|
|
186
|
+
else if (txt)
|
|
187
|
+
existingStyles.add(txt)
|
|
188
|
+
}
|
|
189
|
+
for (const nextStyle of nextDoc.head.querySelectorAll('style')) {
|
|
190
|
+
const txt = nextStyle.textContent ?? ''
|
|
191
|
+
if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt) && !existingStyles.has(txt)) {
|
|
192
|
+
document.head.appendChild(document.importNode(nextStyle, true))
|
|
193
|
+
existingStyles.add(txt)
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
// Sync <html lang>, <html dir>, <title>, and head metadata tags
|
|
197
|
+
const nextLang = nextDoc.documentElement.getAttribute('lang')
|
|
198
|
+
if (nextLang)
|
|
199
|
+
document.documentElement.setAttribute('lang', nextLang)
|
|
200
|
+
const nextDir = nextDoc.documentElement.getAttribute('dir')
|
|
201
|
+
if (nextDir)
|
|
202
|
+
document.documentElement.setAttribute('dir', nextDir)
|
|
203
|
+
else
|
|
204
|
+
document.documentElement.removeAttribute('dir')
|
|
205
|
+
document.title = nextDoc.title
|
|
206
|
+
|
|
207
|
+
for (const oldMeta of document.head.querySelectorAll(SYNC_HEAD_SELECTOR))
|
|
208
|
+
oldMeta.remove()
|
|
209
|
+
for (const nextMeta of nextDoc.head.querySelectorAll(SYNC_HEAD_SELECTOR))
|
|
210
|
+
document.head.appendChild(document.importNode(nextMeta, true))
|
|
211
|
+
},
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ html: string, url: string, csp: string | null | undefined } | undefined> {
|
|
216
|
+
const cached = getCachedHtml(fetchKey)
|
|
217
|
+
if (cached !== undefined) {
|
|
218
|
+
prefetchCache.delete(fetchKey)
|
|
219
|
+
return { html: cached.html, url: cached.url, csp: cached.csp }
|
|
220
|
+
}
|
|
221
|
+
const pending = inflightPrefetch.get(fetchKey)
|
|
222
|
+
const prefetched = pending !== undefined ? await pending : undefined
|
|
223
|
+
if (signal.aborted)
|
|
224
|
+
return undefined
|
|
225
|
+
if (prefetched !== undefined) {
|
|
226
|
+
prefetchCache.delete(fetchKey)
|
|
227
|
+
return { html: prefetched.html, url: prefetched.url, csp: prefetched.csp }
|
|
228
|
+
}
|
|
229
|
+
const res = await fetch(fetchKey, {
|
|
230
|
+
headers: { 'x-pru-spa': '1' },
|
|
231
|
+
signal,
|
|
232
|
+
})
|
|
233
|
+
if (signal.aborted)
|
|
234
|
+
return undefined
|
|
235
|
+
if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html'))
|
|
236
|
+
return undefined
|
|
237
|
+
return { html: await res.text(), url: res.url || fetchKey, csp: res.headers.get('content-security-policy') }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export async function navigate(url: string, push = true, restore?: EntryScroll, targetDocId?: number): Promise<void> {
|
|
241
|
+
// Abort any in-flight navigation so rapid clicks always win immediately
|
|
242
|
+
activeController?.abort()
|
|
243
|
+
const controller = new AbortController()
|
|
244
|
+
activeController = controller
|
|
245
|
+
|
|
246
|
+
const targetUrl = new URL(url, location.href)
|
|
247
|
+
const hash = targetUrl.hash
|
|
248
|
+
const fetchKey = fetchKeyOf(targetUrl)
|
|
249
|
+
|
|
250
|
+
try {
|
|
251
|
+
const fetched = await fetchPageHtml(fetchKey, controller.signal)
|
|
252
|
+
if (controller.signal.aborted)
|
|
253
|
+
return
|
|
254
|
+
if (fetched === undefined) {
|
|
255
|
+
location.assign(url)
|
|
256
|
+
return
|
|
257
|
+
}
|
|
258
|
+
const { html, url: finalUrl, csp } = fetched
|
|
259
|
+
|
|
260
|
+
const nextDoc = new DOMParser().parseFromString(html, 'text/html')
|
|
261
|
+
resolveSuspenseTemplates(nextDoc)
|
|
262
|
+
|
|
263
|
+
const nextFullUrl = hash && !finalUrl.includes('#') ? `${finalUrl}${hash}` : finalUrl
|
|
264
|
+
if (hasBlockedInlineStyle(nextDoc, csp)) {
|
|
265
|
+
if (push)
|
|
266
|
+
location.assign(nextFullUrl)
|
|
267
|
+
else
|
|
268
|
+
location.reload()
|
|
269
|
+
return
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const headPrep = await prepareHeadStyles(nextDoc)
|
|
273
|
+
if (controller.signal.aborted) {
|
|
274
|
+
headPrep.abort()
|
|
275
|
+
return
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const nextParsed = new URL(nextFullUrl, location.href)
|
|
279
|
+
|
|
280
|
+
const applySwap = () => {
|
|
281
|
+
if (push)
|
|
282
|
+
saveScroll()
|
|
283
|
+
// Elements that keep their scroll by key keep it into the next page.
|
|
284
|
+
const kept = readScrolls(false)
|
|
285
|
+
|
|
286
|
+
const existingAnnouncer = document.getElementById(ANNOUNCER_ID)
|
|
287
|
+
|
|
288
|
+
// Preserve live [data-persist] elements (e.g. persistent audio player or counter island) across navigations
|
|
289
|
+
const persisted = new Map<string, Element>()
|
|
290
|
+
for (const el of document.querySelectorAll('[data-persist]')) {
|
|
291
|
+
const key = el.getAttribute('data-persist')
|
|
292
|
+
if (key)
|
|
293
|
+
persisted.set(key, el)
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
headPrep.commit()
|
|
297
|
+
|
|
298
|
+
for (const incoming of nextDoc.querySelectorAll('[data-persist]')) {
|
|
299
|
+
const key = incoming.getAttribute('data-persist')
|
|
300
|
+
const existing = key ? persisted.get(key) : undefined
|
|
301
|
+
if (existing !== undefined)
|
|
302
|
+
incoming.replaceWith(existing)
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (existingAnnouncer !== null)
|
|
306
|
+
nextDoc.body.appendChild(existingAnnouncer)
|
|
307
|
+
|
|
308
|
+
document.body.replaceWith(nextDoc.body)
|
|
309
|
+
if (push) {
|
|
310
|
+
const newDocId = nextDocId()
|
|
311
|
+
setDocId(newDocId)
|
|
312
|
+
history.pushState({ __pruDoc: newDocId }, '', nextFullUrl)
|
|
313
|
+
}
|
|
314
|
+
else {
|
|
315
|
+
setDocId(targetDocId ?? nextDocId())
|
|
316
|
+
}
|
|
317
|
+
currentDocKey = `${nextParsed.pathname}${nextParsed.search}`
|
|
318
|
+
writeScrolls(kept)
|
|
319
|
+
// A page module the next page loads that this one did not (regions' client) runs now: scripts of a parsed page never do.
|
|
320
|
+
for (const script of nextDoc.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]'))
|
|
321
|
+
void import(new URL(script.getAttribute('src') ?? '', location.href).href)
|
|
322
|
+
|
|
323
|
+
if (restore !== undefined) {
|
|
324
|
+
restoreScroll(restore)
|
|
325
|
+
}
|
|
326
|
+
else if (hash.length > 1) {
|
|
327
|
+
let anchorId = hash.slice(1)
|
|
328
|
+
try {
|
|
329
|
+
anchorId = decodeURIComponent(anchorId)
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
// Malformed percent-encoding in hash: use the raw fragment id.
|
|
333
|
+
}
|
|
334
|
+
const anchor = document.getElementById(anchorId)
|
|
335
|
+
if (anchor !== null)
|
|
336
|
+
anchor.scrollIntoView()
|
|
337
|
+
else
|
|
338
|
+
window.scrollTo(0, 0)
|
|
339
|
+
}
|
|
340
|
+
else {
|
|
341
|
+
window.scrollTo(0, 0)
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
focusPrimaryLandmark()
|
|
345
|
+
announce(document.title)
|
|
346
|
+
|
|
347
|
+
window.dispatchEvent(new CustomEvent('pru:navigate', { detail: { url: nextFullUrl } }))
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
await swapInTransition(applySwap)
|
|
351
|
+
}
|
|
352
|
+
catch (err) {
|
|
353
|
+
if (controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError'))
|
|
354
|
+
return
|
|
355
|
+
location.assign(url)
|
|
356
|
+
}
|
|
357
|
+
finally {
|
|
358
|
+
if (activeController === controller)
|
|
359
|
+
activeController = undefined
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
if (typeof document !== 'undefined') {
|
|
364
|
+
document.addEventListener('click', (event) => {
|
|
365
|
+
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
|
|
366
|
+
return
|
|
367
|
+
const target = event.target as Element | null
|
|
368
|
+
const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
|
|
369
|
+
if (!link)
|
|
370
|
+
return
|
|
371
|
+
const url = isEligibleLink(link)
|
|
372
|
+
if (url === undefined)
|
|
373
|
+
return
|
|
374
|
+
if (url.pathname === location.pathname && url.search === location.search && url.hash)
|
|
375
|
+
return
|
|
376
|
+
|
|
377
|
+
event.preventDefault()
|
|
378
|
+
void navigate(url.href, true)
|
|
379
|
+
})
|
|
380
|
+
|
|
381
|
+
const onIntent = (event: Event) => {
|
|
382
|
+
const target = event.target as Element | null
|
|
383
|
+
const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
|
|
384
|
+
// A region link prefetches its region alone, in regions().
|
|
385
|
+
if (!link || link.hasAttribute('data-no-prefetch') || link.hasAttribute('data-pru-target'))
|
|
386
|
+
return
|
|
387
|
+
// Prefetch is strictly opt-in via [data-pru-prefetch] so side-effecting links like /logout are never prefetched
|
|
388
|
+
if (link.closest('[data-pru-prefetch]') === null)
|
|
389
|
+
return
|
|
390
|
+
const url = isEligibleLink(link)
|
|
391
|
+
if (url === undefined)
|
|
392
|
+
return
|
|
393
|
+
if (url.pathname === location.pathname && url.search === location.search)
|
|
394
|
+
return
|
|
395
|
+
void prefetch(url.href)
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
document.addEventListener('pointerover', onIntent, { passive: true })
|
|
399
|
+
document.addEventListener('focusin', onIntent, { passive: true })
|
|
400
|
+
|
|
401
|
+
// A region swap moves the address too, so a later #hash entry of that address is no new page.
|
|
402
|
+
window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
|
|
403
|
+
window.addEventListener('popstate', (event) => {
|
|
404
|
+
const nextDocKey = `${location.pathname}${location.search}`
|
|
405
|
+
if (nextDocKey === currentDocKey)
|
|
406
|
+
return
|
|
407
|
+
const st = event.state as { __pruIdx?: number, __pruDoc?: number } | null
|
|
408
|
+
// Only same-document region swaps belong to regions(); cross-document entries (even with __pruIdx) belong to spa().
|
|
409
|
+
if (isSameDocRegionState(st))
|
|
410
|
+
return
|
|
411
|
+
const targetDocId = typeof st?.__pruDoc === 'number' ? st.__pruDoc : undefined
|
|
412
|
+
void navigate(location.href, false, entryScroll(st), targetDocId)
|
|
413
|
+
})
|
|
414
|
+
// The browser's own restoring would fight the one the swap does, once the new page is in.
|
|
415
|
+
history.scrollRestoration = 'manual'
|
|
416
|
+
trackScroll()
|
|
417
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
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 { checkRegionTargets } from './check'
|
|
7
|
+
|
|
8
|
+
// Shipped as a same-origin stylesheet so navigating from an island-less page to an island/Suspense page
|
|
9
|
+
// never needs to inject an unhashed inline <style> tag blocked by the initial page's strict CSP.
|
|
10
|
+
const SPA_ISLAND_CSS = 'pru-island,pru-slot,pru-s{display:contents}'
|
|
11
|
+
|
|
12
|
+
function emitIslandStylesheet(ctx: BuildPluginContext): void {
|
|
13
|
+
ctx.addStyle(ctx.emitAsset('pru-island.css', SPA_ISLAND_CSS))
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function spa(): PrunellePlugin {
|
|
17
|
+
return definePlugin({
|
|
18
|
+
name: '@prunellejs/spa',
|
|
19
|
+
clientEntry: resolve(import.meta.dir, 'client.ts'),
|
|
20
|
+
build: emitIslandStylesheet,
|
|
21
|
+
})
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function regions(): PrunellePlugin {
|
|
25
|
+
return definePlugin({
|
|
26
|
+
name: '@prunellejs/spa/regions',
|
|
27
|
+
regionClientEntry: resolve(import.meta.dir, 'regions.ts'),
|
|
28
|
+
build: emitIslandStylesheet,
|
|
29
|
+
check: checkRegionTargets,
|
|
30
|
+
})
|
|
31
|
+
}
|
package/src/prefetch.ts
ADDED
|
@@ -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