@prunellejs/spa 0.0.0-stage → 0.7.2

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/src/index.ts ADDED
@@ -0,0 +1,44 @@
1
+ // @prunellejs/spa — opt-in in-place navigation: `spa()` swaps whole pages and keeps persistent islands (3.8 KB gzip), `regions()` swaps one <Region> of a page (4.0 KB gzip, on the pages with a <Region>). 0 B when uninstalled.
2
+
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,130 @@
1
+ // The fetch cache `spa()` and `regions()` share: a link inside [data-pru-prefetch] is fetched on hover or focus, and the swap that follows takes the answer from here.
2
+
3
+ export interface PrefetchEntry {
4
+ html: string
5
+ url: string
6
+ ts: number
7
+ /** The `x-pru-region` the server answered with: the region's HTML alone, not a whole page. */
8
+ region: string | null
9
+ /** The percent-encoded `x-pru-title` of a region answer: the title the page has at this URL. */
10
+ title: string | null
11
+ /** Response Content-Security-Policy header, used by spa() to detect blocked destination <style> tags. */
12
+ csp?: string | null | undefined
13
+ /** The `x-pru-view` the server answered a prefetch with: where to post the page when the visitor opens it, since a cache hit makes no request for the server to count. */
14
+ view?: string | null | undefined
15
+ }
16
+
17
+ export const HTML_ACCEPT = 'text/html'
18
+ const PREFETCH_TTL = 15_000
19
+ const PREFETCH_MAX = 8
20
+ // A prefetch past this many in flight is dropped: the click fetches the page as usual.
21
+ const PREFETCH_PARALLEL = 3
22
+ const HOVER_INTENT = 80
23
+ export const prefetchCache = new Map<string, PrefetchEntry>()
24
+ export const inflightPrefetch = new Map<string, Promise<PrefetchEntry | undefined>>()
25
+
26
+ // Document generation counter shared by spa() and regions() so popstate separates same-doc region swaps from cross-doc page navigations.
27
+ function initialDocId(): number {
28
+ const st = typeof history === 'undefined' ? undefined : history.state as { __pruDoc?: unknown } | null
29
+ return typeof st?.__pruDoc === 'number' ? st.__pruDoc : 0
30
+ }
31
+
32
+ let currentDocId = initialDocId()
33
+ let maxDocId = currentDocId
34
+
35
+ export function getDocId(): number {
36
+ return currentDocId
37
+ }
38
+
39
+ export function setDocId(id: number): void {
40
+ currentDocId = id
41
+ if (id > maxDocId)
42
+ maxDocId = id
43
+ }
44
+
45
+ export function nextDocId(): number {
46
+ return ++maxDocId
47
+ }
48
+
49
+ export function isSameDocRegionState(state: unknown): boolean {
50
+ if (typeof state !== 'object' || state === null)
51
+ return false
52
+ const s = state as { __pruIdx?: unknown, __pruDoc?: unknown }
53
+ return typeof s.__pruIdx === 'number' && (s.__pruDoc === undefined || s.__pruDoc === currentDocId)
54
+ }
55
+
56
+ /** The cache key of a page, or of one region of it, given by its path from the outermost region (`results/sets`). */
57
+ export function fetchKeyOf(url: URL, region?: string): string {
58
+ const key = `${url.origin}${url.pathname}${url.search}`
59
+ return region === undefined ? key : `${region} ${key}`
60
+ }
61
+
62
+ export function getCachedHtml(href: string): PrefetchEntry | undefined {
63
+ const hit = prefetchCache.get(href)
64
+ if (hit === undefined)
65
+ return undefined
66
+ if (Date.now() - hit.ts > PREFETCH_TTL) {
67
+ prefetchCache.delete(href)
68
+ return undefined
69
+ }
70
+ return hit
71
+ }
72
+
73
+ function putCachedHtml(href: string, entry: PrefetchEntry): void {
74
+ prefetchCache.delete(href)
75
+ prefetchCache.set(href, entry)
76
+ if (prefetchCache.size > PREFETCH_MAX) {
77
+ const oldest = prefetchCache.keys().next()
78
+ if (!oldest.done)
79
+ prefetchCache.delete(oldest.value)
80
+ }
81
+ }
82
+
83
+ /** Tells the server a page was opened from the cache, when it asked to be told. */
84
+ export function countView(view: string | null | undefined, url: URL): void {
85
+ if (view)
86
+ navigator.sendBeacon(view, `${url.pathname}${url.search}`)
87
+ }
88
+
89
+ export async function prefetch(url: string, region?: string): Promise<void> {
90
+ const clean = new URL(url, location.href)
91
+ clean.hash = ''
92
+ const key = fetchKeyOf(clean, region)
93
+ if (getCachedHtml(key) !== undefined || inflightPrefetch.has(key) || inflightPrefetch.size >= PREFETCH_PARALLEL)
94
+ return
95
+ const conn = (navigator as Navigator & { connection?: { saveData?: boolean } }).connection
96
+ if (conn?.saveData)
97
+ return
98
+
99
+ const task = (async (): Promise<PrefetchEntry | undefined> => {
100
+ try {
101
+ const res = await fetch(clean.href, { headers: region === undefined ? { 'x-pru-spa': '1', 'accept': HTML_ACCEPT, 'purpose': 'prefetch' } : { 'x-pru-region': region, 'purpose': 'prefetch' } })
102
+ if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
103
+ void res.body?.cancel()
104
+ return undefined
105
+ }
106
+ const entry: PrefetchEntry = { html: await res.text(), url: res.url || clean.href, ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title'), csp: res.headers.get('content-security-policy'), view: res.headers.get('x-pru-view') }
107
+ putCachedHtml(key, entry)
108
+ return entry
109
+ }
110
+ catch {
111
+ return undefined
112
+ }
113
+ finally {
114
+ inflightPrefetch.delete(key)
115
+ }
116
+ })()
117
+ inflightPrefetch.set(key, task)
118
+ await task
119
+ }
120
+
121
+ /** Runs `run` on keyboard focus at once, and on a pointer that rests 80 ms over a target, not on one sweeping across. */
122
+ export function listenIntent(run: (event: Event) => void): void {
123
+ let timer: ReturnType<typeof setTimeout> | undefined
124
+ document.addEventListener('pointerover', (event) => {
125
+ clearTimeout(timer)
126
+ timer = setTimeout(run, HOVER_INTENT, event)
127
+ }, { passive: true })
128
+ document.addEventListener('pointerout', () => clearTimeout(timer), { passive: true })
129
+ document.addEventListener('focusin', run, { passive: true })
130
+ }
package/src/regions.ts ADDED
@@ -0,0 +1,425 @@
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 { countView, fetchKeyOf, getCachedHtml, getDocId, inflightPrefetch, isSameDocRegionState, listenIntent, 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
+ countView(entry.view, finalUrl)
259
+ await apply(region, content, swap, finalUrl)
260
+ return true
261
+ }
262
+ catch (err) {
263
+ return controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError')
264
+ }
265
+ finally {
266
+ clearTimeout(busy)
267
+ if (controllers.get(name) === controller) {
268
+ controllers.delete(name)
269
+ findRegion(name)?.removeAttribute('aria-busy')
270
+ }
271
+ }
272
+ }
273
+
274
+ // 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.
275
+ async function navigate(swap: Swap): Promise<void> {
276
+ if (await swapRegion(swap))
277
+ return
278
+ if (swap.post === undefined)
279
+ location.assign(swap.url.href)
280
+ else if (swap.landed)
281
+ location.assign(swap.landed)
282
+ else
283
+ swap.post.form.submit()
284
+ }
285
+
286
+ /** 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. */
287
+ export async function refreshRegion(name: string): Promise<void> {
288
+ if (!await swapRegion({ url: new URL(location.href), region: name, history: 'none', fresh: true }))
289
+ 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.`)
290
+ }
291
+
292
+ function formMethod(form: HTMLFormElement, submitter?: HTMLElement | null): string {
293
+ const rawMethod = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formmethod') : null)
294
+ ?? safeGetAttribute(form, 'method')
295
+ ?? 'get'
296
+ return rawMethod.toLowerCase()
297
+ }
298
+
299
+ function formAction(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
300
+ // Read raw attributes via Element.prototype.getAttribute so <input name="action"> cannot DOM-clobber form.action.
301
+ const rawAction = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formaction') : null)
302
+ ?? safeGetAttribute(form, 'action')
303
+ ?? ''
304
+ return new URL(rawAction, location.href)
305
+ }
306
+
307
+ function formUrl(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
308
+ const url = formAction(form, submitter)
309
+ // A field left empty stays out of the address, so it names only the filters in use.
310
+ const params = new URLSearchParams()
311
+ for (const [key, value] of new FormData(form, submitter ?? undefined)) {
312
+ if (typeof value === 'string' && value !== '')
313
+ params.append(key, value)
314
+ }
315
+ url.search = params.toString()
316
+ return url
317
+ }
318
+
319
+ function missingRegion(name: string, element: string): boolean {
320
+ if (findRegion(name) !== null)
321
+ return false
322
+ 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.`)
323
+ return true
324
+ }
325
+
326
+ function linkOf(event: Event): HTMLAnchorElement | null {
327
+ return (event.target as Element | null)?.closest?.<HTMLAnchorElement>('a[href][data-pru-target]') ?? null
328
+ }
329
+
330
+ if (typeof document !== 'undefined') {
331
+ document.addEventListener('click', (event) => {
332
+ if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
333
+ return
334
+ const link = linkOf(event)
335
+ if (link === null || link.target !== '' || link.hasAttribute('download'))
336
+ return
337
+ const url = new URL(link.href, location.href)
338
+ const name = link.getAttribute('data-pru-target')!
339
+ const append = link.hasAttribute('data-pru-append')
340
+ if (url.origin !== location.origin || missingRegion(name, `<a href="${link.getAttribute('href')}">`))
341
+ return
342
+ event.preventDefault()
343
+ // A hash already on the page is a scroll when the document holds the page the link names, with the address keeping its page.
344
+ const page = url.pathname + url.search
345
+ if (!append && (page === shown || appended.has(page)) && elementOfHash(url.hash) !== null) {
346
+ location.hash = url.hash
347
+ return
348
+ }
349
+ void navigate({ url, region: name, append, history: append ? 'replace' : 'push', focus: true, trigger: link })
350
+ }, true)
351
+
352
+ document.addEventListener('submit', (event) => {
353
+ const form = event.target as HTMLFormElement
354
+ if (!(form instanceof HTMLFormElement))
355
+ return
356
+ const submitter = (event as SubmitEvent).submitter
357
+ const name = safeGetAttribute(form, 'data-pru-target')
358
+ const method = formMethod(form, submitter)
359
+ if (event.defaultPrevented || name === null || (method !== 'get' && method !== 'post') || missingRegion(name, '<form>'))
360
+ return
361
+ event.preventDefault()
362
+ clearTimeout(liveTimer)
363
+ if (method === 'get')
364
+ void navigate({ url: formUrl(form, submitter), region: name, history: 'push' })
365
+ else
366
+ void navigate({ url: formAction(form, submitter), region: name, history: 'push', post: { form, body: new FormData(form, submitter ?? undefined) } })
367
+ }, true)
368
+
369
+ document.addEventListener('input', (event) => {
370
+ const form = (event.target as Element | null)?.closest?.<HTMLFormElement>('form[data-pru-live][data-pru-target]')
371
+ if (form === null || form === undefined || formMethod(form) !== 'get')
372
+ return
373
+ clearTimeout(liveTimer)
374
+ liveTimer = setTimeout(() => {
375
+ const name = safeGetAttribute(form, 'data-pru-target')!
376
+ if (!missingRegion(name, '<form>'))
377
+ void navigate({ url: formUrl(form), region: name, history: 'burst' })
378
+ }, LIVE_DEBOUNCE)
379
+ })
380
+
381
+ const onIntent = (event: Event) => {
382
+ const link = linkOf(event)
383
+ if (link === null || link.hasAttribute('data-no-prefetch') || link.closest('[data-pru-prefetch]') === null)
384
+ return
385
+ const url = new URL(link.href, location.href)
386
+ if (url.origin === location.origin && `${url.pathname}${url.search}` !== `${location.pathname}${location.search}`) {
387
+ const region = findRegion(link.getAttribute('data-pru-target')!)
388
+ if (region !== null)
389
+ void prefetch(url.href, pathOf(region))
390
+ }
391
+ }
392
+ listenIntent(onIntent)
393
+
394
+ // Keep region state aligned when spa() swaps to another document (including popstate back to a document with prior region entries).
395
+ window.addEventListener('pru:navigate', () => {
396
+ shown = location.pathname + location.search
397
+ appended.clear()
398
+ const st = stateOf(history.state)
399
+ idx = st?.__pruIdx ?? 0
400
+ lastRegion = st?.__pruRegion
401
+ burstOpen = false
402
+ })
403
+ window.addEventListener('popstate', (event) => {
404
+ if (!isSameDocRegionState(event.state))
405
+ return
406
+ const state = stateOf(event.state)
407
+ const sameDocument = location.pathname + location.search === shown
408
+ shown = location.pathname + location.search
409
+ if (state === undefined)
410
+ return
411
+ const name = state.__pruIdx < idx ? lastRegion : state.__pruRegion
412
+ idx = state.__pruIdx
413
+ lastRegion = state.__pruRegion
414
+ burstOpen = false
415
+ const restore = entryScroll(event.state)
416
+ if (name === undefined || sameDocument) {
417
+ // With spa() the browser leaves the scroll to the page, a swap or not.
418
+ if (restore !== undefined && history.scrollRestoration === 'manual')
419
+ restoreScroll(restore)
420
+ return
421
+ }
422
+ void navigate({ url: new URL(location.href), region: name, history: 'none', ...(restore === undefined ? {} : { restore }) })
423
+ })
424
+ trackScroll()
425
+ }
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.