@prunellejs/spa 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/regions.ts DELETED
@@ -1,496 +0,0 @@
1
- // @prunellejs/spa regions() client: a link or GET form with data-pru-target swaps one <Region> of the page, fetched alone.
2
- // - a[data-pru-target] replaces the region; with data-pru-append the response is added to it and the clicked link goes (Load more)
3
- // - form[data-pru-target] swaps on submit; with data-pru-live also while typing: one history entry per typing burst
4
- // - [data-pru-sync="a b"] copies those query params of the current URL into links and fields outside the region
5
- // - form[method=post][data-pru-target] posts through fetch, follows the redirect and swaps the region with the page it lands on
6
- // - history push and back/forward re-fetch the region the entry changed; aria-busy while a fetch is slow
7
- // - [data-persist="<key>"] inside the region survives the swap in the place of the new element of that key: a field keeps focus, caret and value, an iframe its document
8
- // - a swap runs in a view transition (not under reduced motion), keeps the scroll of [data-pru-keep-scroll] elements, resets the region's own, and moves aria-current to the links that match the new URL
9
- // - a link to a #hash already on the page scrolls to it without a fetch; after a swap the page scrolls to the URL's hash
10
- // - prefetch on hover and focus inside [data-pru-prefetch], through the cache spa() shares
11
-
12
- import type { PrefetchEntry } from './prefetch'
13
- import type { EntryScroll } from './swap'
14
- import { announce } from './announcer'
15
- import { countView, fetchKeyOf, getCachedHtml, getDocId, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, prefetch, prefetchCache } from './prefetch'
16
- import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
17
-
18
- const BUSY_DELAY = 150
19
- const LIVE_DEBOUNCE = 200
20
- const BURST_PAUSE = 1000
21
-
22
- interface RegionState { __pruIdx: number, __pruDoc?: number | undefined, __pruRegion?: string | undefined }
23
-
24
- function safeGetAttribute(el: Element, name: string): string | null {
25
- return Element.prototype.getAttribute.call(el, name)
26
- }
27
-
28
- interface Swap {
29
- url: URL
30
- region: string
31
- append?: boolean
32
- /** `burst`: pushed by the first change of a typing burst, replaced by the rest. */
33
- history: 'push' | 'replace' | 'burst' | 'none'
34
- /** Moves focus into the region (a link did it), not for a form the user is typing in. */
35
- focus?: boolean
36
- trigger?: Element
37
- /** Skips the prefetch cache: the region is redrawn because the server's state changed. */
38
- fresh?: boolean
39
- /** A form posted to `url`: the swap shows the page its redirect lands on. */
40
- post?: { form: HTMLFormElement, body: FormData }
41
- /** Where the post's redirect ended, once it did. */
42
- landed?: string
43
- /** The scroll a back or forward entry had, put back after the swap. */
44
- restore?: EntryScroll
45
- }
46
-
47
- function stateOf(state: unknown): RegionState | undefined {
48
- return typeof state === 'object' && state !== null && typeof (state as RegionState).__pruIdx === 'number' ? state as RegionState : undefined
49
- }
50
-
51
- const controllers = new Map<string, AbortController>()
52
- let idx = stateOf(typeof history === 'undefined' ? undefined : history.state)?.__pruIdx ?? 0
53
- let lastRegion = stateOf(typeof history === 'undefined' ? undefined : history.state)?.__pruRegion
54
- // The page and query the document shows: an entry that differs from it only in its hash needs no fetch.
55
- let shown = typeof location === 'undefined' ? '' : location.pathname + location.search
56
- // The pages Load more added to the document since its last swap, beside the one it shows: their #hash links scroll too.
57
- const appended = new Set<string>()
58
- let burstOpen = false
59
- let burstTimer: ReturnType<typeof setTimeout> | undefined
60
- let liveTimer: ReturnType<typeof setTimeout> | undefined
61
-
62
- function findRegion(name: string): HTMLElement | null {
63
- return document.querySelector<HTMLElement>(`[data-pru-region="${name.replace(/["\\]/g, '\\$&')}"]`)
64
- }
65
-
66
- // A region's path from the outermost one around it: `results/sets` for `sets` inside `results`. The server renders through the outer ones.
67
- function pathOf(region: HTMLElement): string {
68
- const names: string[] = []
69
- for (let el: Element | null = region; el !== null; el = el.parentElement?.closest('[data-pru-region]') ?? null)
70
- names.unshift(el.getAttribute('data-pru-region')!)
71
- return names.join('/')
72
- }
73
-
74
- async function load(swap: Swap, region: string, signal: AbortSignal): Promise<PrefetchEntry | undefined> {
75
- const { url, post } = swap
76
- const key = fetchKeyOf(url, region)
77
- const ready = swap.fresh === true || post !== undefined ? undefined : getCachedHtml(key) ?? await inflightPrefetch.get(key)
78
- if (ready !== undefined) {
79
- prefetchCache.delete(key)
80
- return ready
81
- }
82
- const res = await fetch(fetchKeyOf(url), { headers: { 'x-pru-region': region, 'accept': HTML_ACCEPT }, signal, ...(post === undefined ? {} : { method: 'POST', body: post.body }) })
83
- if (post !== undefined)
84
- swap.landed = res.url
85
- if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
86
- void res.body?.cancel()
87
- return undefined
88
- }
89
- return { html: await res.text(), url: res.url || fetchKeyOf(url), ts: Date.now(), region: res.headers.get('x-pru-region'), title: res.headers.get('x-pru-title') }
90
- }
91
-
92
- // The region's inner HTML and the page title: the answer itself when the server sent the region alone, else the region cut out of a full page (a prerendered page, a proxy that dropped the header).
93
- function contentOf(entry: PrefetchEntry, path: string): { content: DocumentFragment, title: string | undefined } | undefined {
94
- const template = document.createElement('template')
95
- if (entry.region === path) {
96
- template.innerHTML = entry.html
97
- // The title is HTML text, percent-encoded in the header: a textarea unescapes it.
98
- const unescape = document.createElement('textarea')
99
- unescape.innerHTML = entry.title === null ? '' : decodeURIComponent(entry.title)
100
- return { content: template.content, title: entry.title === null ? undefined : unescape.value }
101
- }
102
- const page = new DOMParser().parseFromString(entry.html, 'text/html')
103
- const found = page.querySelector(`[data-pru-region="${path.split('/').at(-1)!.replace(/["\\]/g, '\\$&')}"]`)
104
- if (found === null)
105
- return undefined
106
- template.innerHTML = found.innerHTML
107
- return { content: template.content, title: page.title === '' ? undefined : page.title }
108
- }
109
-
110
- function record(url: URL, name: string, mode: 'push' | 'replace' | 'burst'): void {
111
- clearTimeout(burstTimer)
112
- // A replace inside the region the entry was made for keeps that region, so back and forward restore the whole of it.
113
- const before = stateOf(history.state)?.__pruRegion
114
- const around = mode === 'replace' && before !== undefined && before !== name && findRegion(before)?.contains(findRegion(name)) === true ? before : name
115
- let push = mode === 'push' || (mode === 'burst' && !burstOpen)
116
- if (mode === 'burst') {
117
- burstOpen = true
118
- burstTimer = setTimeout(() => { burstOpen = false }, BURST_PAUSE)
119
- }
120
- else {
121
- burstOpen = false
122
- }
123
- const next = `${url.pathname}${url.search}${url.hash}`
124
- if (next === `${location.pathname}${location.search}${location.hash}`)
125
- push = false
126
- const prev = (typeof history.state === 'object' && history.state !== null ? history.state : {}) as Record<string, unknown>
127
- const docId = getDocId()
128
- if (push) {
129
- // The entry left behind is stamped first, so back and forward can tell it from a page of another document.
130
- history.replaceState({ ...prev, __pruDoc: docId, __pruIdx: idx }, '')
131
- idx++
132
- history.pushState({ __pruDoc: docId, __pruIdx: idx, __pruRegion: around }, '', next)
133
- }
134
- else {
135
- history.replaceState({ ...prev, __pruDoc: docId, __pruIdx: idx, __pruRegion: around }, '', next)
136
- }
137
- lastRegion = around
138
- shown = url.pathname + url.search
139
- }
140
-
141
- function focusNode(el: Element | null | undefined): void {
142
- if (el === null || el === undefined)
143
- return
144
- if (!el.hasAttribute('tabindex'))
145
- el.setAttribute('tabindex', '-1')
146
- ;(el as HTMLElement).focus({ preventScroll: true })
147
- }
148
-
149
- // Links and fields the app marked data-pru-sync follow the URL the swap just set.
150
- function syncParams(): void {
151
- const params = new URL(location.href).searchParams
152
- for (const el of document.querySelectorAll<HTMLElement>('[data-pru-sync]')) {
153
- if (el instanceof HTMLAnchorElement) {
154
- const url = new URL(el.href, location.href)
155
- if (url.origin !== location.origin)
156
- continue
157
- for (const name of (el.getAttribute('data-pru-sync') ?? '').split(/\s+/).filter(Boolean)) {
158
- url.searchParams.delete(name)
159
- for (const value of params.getAll(name))
160
- url.searchParams.append(name, value)
161
- }
162
- el.setAttribute('href', `${url.pathname}${url.search}${url.hash}`)
163
- }
164
- else if ((el instanceof HTMLInputElement || el instanceof HTMLSelectElement || el instanceof HTMLTextAreaElement) && el !== document.activeElement) {
165
- el.value = params.get(el.name) ?? ''
166
- }
167
- }
168
- }
169
-
170
- // The links that point at the page the swap landed on say so; the ones that did and no longer do stop.
171
- function syncCurrent(): void {
172
- for (const link of document.querySelectorAll<HTMLAnchorElement>('a[href]')) {
173
- if (link.origin === location.origin && link.hash === '' && link.pathname + link.search === location.pathname + location.search)
174
- link.setAttribute('aria-current', 'page')
175
- else if (link.getAttribute('aria-current') === 'page')
176
- link.removeAttribute('aria-current')
177
- }
178
- }
179
-
180
- const PERSIST = '[data-persist]'
181
-
182
- // The outermost [data-persist] elements under `root` by key (a nested one moves with its own), and a key found on two of them.
183
- function persistedIn(root: ParentNode & Node): { byKey: Map<string, Element>, twice: string | undefined } {
184
- const byKey = new Map<string, Element>()
185
- let twice: string | undefined
186
- for (const el of root.querySelectorAll(PERSIST)) {
187
- const outer = el.parentElement?.closest(PERSIST)
188
- const key = el.getAttribute('data-persist')
189
- if (key === null || key === '' || (outer !== null && outer !== undefined && root.contains(outer)))
190
- continue
191
- if (byKey.has(key))
192
- twice ??= key
193
- byKey.set(key, el)
194
- }
195
- return { byKey, twice }
196
- }
197
-
198
- type Movable = ParentNode & { moveBefore?: (node: Node, child: Node | null) => void }
199
-
200
- // Swaps `content` in, each live [data-persist] element taking the place of the new one of its key. moveBefore keeps a field's focus and an iframe's document; where it is missing, a re-inserted field gets its focus and selection back.
201
- function replaceKeeping(region: HTMLElement, content: DocumentFragment): void {
202
- const incoming = persistedIn(content).byKey
203
- const live = persistedIn(region).byKey
204
- const old = [...region.childNodes]
205
- region.append(content)
206
- const focused = document.activeElement
207
- const field = focused instanceof HTMLInputElement || focused instanceof HTMLTextAreaElement ? focused : undefined
208
- const selection = field?.selectionStart == null ? undefined : [field.selectionStart, field.selectionEnd ?? field.selectionStart, field.selectionDirection ?? 'none'] as const
209
- let refocus = false
210
- for (const [key, el] of live) {
211
- const slot = incoming.get(key)
212
- const parent = slot?.parentNode as Movable | null | undefined
213
- if (slot === undefined || parent === null || parent === undefined)
214
- continue
215
- if (typeof parent.moveBefore === 'function') {
216
- parent.moveBefore(el, slot)
217
- }
218
- else {
219
- refocus ||= focused !== null && el.contains(focused)
220
- parent.insertBefore(el, slot)
221
- }
222
- slot.remove()
223
- }
224
- for (const node of old)
225
- node.remove()
226
- if (refocus && focused instanceof HTMLElement && document.activeElement !== focused) {
227
- focused.focus({ preventScroll: true })
228
- if (field !== undefined && selection !== undefined)
229
- field.setSelectionRange(...selection)
230
- }
231
- }
232
-
233
- function elementOfHash(hash: string): HTMLElement | null {
234
- const raw = hash.slice(1)
235
- let id: string
236
- try {
237
- id = decodeURIComponent(raw)
238
- }
239
- catch {
240
- id = raw
241
- }
242
- return id === '' ? null : document.getElementById(id)
243
- }
244
-
245
- async function apply(region: HTMLElement, found: { content: DocumentFragment, title: string | undefined }, swap: Swap, finalUrl: URL): Promise<void> {
246
- const { content, title } = found
247
- // A typing burst and an append stay put: a transition freezes the page, and the field being typed in with it.
248
- const animate = !swap.append && swap.history !== 'burst' && swap.fresh !== true
249
- await swapInTransition(() => {
250
- if (swap.append)
251
- appended.add(shown)
252
- else
253
- appended.clear()
254
- if (swap.history !== 'none') {
255
- saveScroll()
256
- record(finalUrl, swap.region, swap.history)
257
- }
258
- const kept = readScrolls(false)
259
- const first = content.firstElementChild
260
- if (swap.append) {
261
- if (swap.trigger !== undefined && region.contains(swap.trigger))
262
- swap.trigger.remove()
263
- region.append(content)
264
- }
265
- else {
266
- // A fetch for a region about to be replaced must not land in the new one.
267
- for (const inner of region.querySelectorAll('[data-pru-region]'))
268
- controllers.get(inner.getAttribute('data-pru-region')!)?.abort()
269
- replaceKeeping(region, content)
270
- writeScrolls(kept)
271
- if (swap.history !== 'none' && !region.hasAttribute('data-pru-keep-scroll'))
272
- region.scrollTop = 0
273
- }
274
- if (title !== undefined)
275
- document.title = title
276
- syncParams()
277
- syncCurrent()
278
- if (swap.restore !== undefined)
279
- restoreScroll(swap.restore)
280
- else if (!swap.append && swap.history !== 'none')
281
- elementOfHash(finalUrl.hash)?.scrollIntoView()
282
- if (swap.focus === true)
283
- focusNode(swap.append ? first : region)
284
- const label = region.getAttribute('aria-label')
285
- if (label !== null)
286
- announce(label)
287
- window.dispatchEvent(new CustomEvent('pru:region', { detail: { name: swap.region, url: location.href } }))
288
- }, animate)
289
- }
290
-
291
- // Resolves false when the region could not be swapped: no such region, a failed fetch, or an answer without it.
292
- async function swapRegion(swap: Swap): Promise<boolean> {
293
- const name = swap.region
294
- if (findRegion(name) === null)
295
- return false
296
- controllers.get(name)?.abort()
297
- const controller = new AbortController()
298
- controllers.set(name, controller)
299
- const path = pathOf(findRegion(name)!)
300
- const busy = setTimeout(() => findRegion(name)?.setAttribute('aria-busy', 'true'), BUSY_DELAY)
301
- try {
302
- const entry = await load(swap, path, controller.signal)
303
- if (controller.signal.aborted)
304
- return true
305
- const content = entry === undefined ? undefined : contentOf(entry, path)
306
- const region = findRegion(name)
307
- if (entry === undefined || content === undefined || region === null)
308
- return false
309
- const finalUrl = entry.url ? new URL(entry.url, location.href) : swap.url
310
- if (finalUrl.origin !== location.origin)
311
- return false
312
- if (swap.url.hash && !finalUrl.hash)
313
- finalUrl.hash = swap.url.hash
314
- const twice = swap.append === true ? undefined : persistedIn(content.content).twice
315
- if (twice !== undefined) {
316
- console.error(`prunelle: data-persist="${twice}" is on two elements of the region "${name}" that ${finalUrl.pathname}${finalUrl.search} answers: give each its own key. The page loads whole instead.`)
317
- return false
318
- }
319
- countView(entry.view, finalUrl)
320
- await apply(region, content, swap, finalUrl)
321
- return true
322
- }
323
- catch (err) {
324
- return controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError')
325
- }
326
- finally {
327
- clearTimeout(busy)
328
- if (controllers.get(name) === controller) {
329
- controllers.delete(name)
330
- findRegion(name)?.removeAttribute('aria-busy')
331
- }
332
- }
333
- }
334
-
335
- // A swap a link, a form or history asked for: what cannot be swapped loads the whole page. A form already posted loads the page its redirect reached, never posts twice; one whose post never got an answer posts the plain way.
336
- async function navigate(swap: Swap): Promise<void> {
337
- if (await swapRegion(swap))
338
- return
339
- if (swap.post === undefined)
340
- location.assign(swap.url.href)
341
- else if (swap.landed)
342
- location.assign(swap.landed)
343
- else
344
- swap.post.form.submit()
345
- }
346
-
347
- /** Redraws region `name` from the server at the current address, with no history entry and focus left where it is; rejects when the page has no such region, the fetch fails or the answer lacks it. */
348
- export async function refreshRegion(name: string): Promise<void> {
349
- if (!await swapRegion({ url: new URL(location.href), region: name, history: 'none', fresh: true }))
350
- throw new Error(`prunelle: region "${name}" could not be redrawn from ${location.href}: render a <Region name="${name}"> on this page, and check the server answers it.`)
351
- }
352
-
353
- function formMethod(form: HTMLFormElement, submitter?: HTMLElement | null): string {
354
- const rawMethod = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formmethod') : null)
355
- ?? safeGetAttribute(form, 'method')
356
- ?? 'get'
357
- return rawMethod.toLowerCase()
358
- }
359
-
360
- function formAction(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
361
- // Read raw attributes via Element.prototype.getAttribute so <input name="action"> cannot DOM-clobber form.action.
362
- const rawAction = (submitter !== null && submitter !== undefined ? safeGetAttribute(submitter, 'formaction') : null)
363
- ?? safeGetAttribute(form, 'action')
364
- ?? ''
365
- return new URL(rawAction, location.href)
366
- }
367
-
368
- /** The live form on the page that an element is, or belongs to by `form="<id>"` or as a descendant. */
369
- function liveForm(el: Element | null): HTMLFormElement | null {
370
- const form = el?.isConnected ? (el as HTMLInputElement).form ?? el.closest?.('form') : null
371
- return form?.matches('[data-pru-live][data-pru-target]') ? form : null
372
- }
373
-
374
- function formUrl(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
375
- const url = formAction(form, submitter)
376
- // A field left empty stays out of the address, so it names only the filters in use; a button with an empty value clears its name, as a server reading the last value sees natively.
377
- const cleared = (submitter as HTMLButtonElement | null | undefined)?.value === '' ? submitter!.getAttribute('name') : null
378
- const params = new URLSearchParams()
379
- for (const [key, value] of new FormData(form, submitter ?? undefined)) {
380
- if (typeof value === 'string' && value !== '' && key !== cleared)
381
- params.append(key, value)
382
- }
383
- url.search = params.toString()
384
- return url
385
- }
386
-
387
- function missingRegion(name: string, element: string): boolean {
388
- if (findRegion(name) !== null)
389
- return false
390
- console.error(`prunelle: ${element} targets the region "${name}", and this page has no <Region name="${name}">: add it, or fix the name. The link loads the whole page instead.`)
391
- return true
392
- }
393
-
394
- function linkOf(event: Event): HTMLAnchorElement | null {
395
- return (event.target as Element | null)?.closest?.<HTMLAnchorElement>('a[href][data-pru-target]') ?? null
396
- }
397
-
398
- if (typeof document !== 'undefined') {
399
- document.addEventListener('click', (event) => {
400
- if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
401
- return
402
- const link = linkOf(event)
403
- if (link === null || link.target !== '' || link.hasAttribute('download'))
404
- return
405
- const url = new URL(link.href, location.href)
406
- const name = link.getAttribute('data-pru-target')!
407
- const append = link.hasAttribute('data-pru-append')
408
- if (url.origin !== location.origin || missingRegion(name, `<a href="${link.getAttribute('href')}">`))
409
- return
410
- event.preventDefault()
411
- // A hash already on the page is a scroll when the document holds the page the link names, with the address keeping its page.
412
- const page = url.pathname + url.search
413
- if (!append && (page === shown || appended.has(page)) && elementOfHash(url.hash) !== null) {
414
- location.hash = url.hash
415
- return
416
- }
417
- void navigate({ url, region: name, append, history: append ? 'replace' : 'push', focus: true, trigger: link })
418
- }, true)
419
-
420
- document.addEventListener('submit', (event) => {
421
- const form = event.target as HTMLFormElement
422
- if (!(form instanceof HTMLFormElement))
423
- return
424
- const submitter = (event as SubmitEvent).submitter
425
- const name = safeGetAttribute(form, 'data-pru-target')
426
- const method = formMethod(form, submitter)
427
- if (event.defaultPrevented || name === null || (method !== 'get' && method !== 'post') || missingRegion(name, '<form>'))
428
- return
429
- event.preventDefault()
430
- clearTimeout(liveTimer)
431
- if (method === 'get')
432
- void navigate({ url: formUrl(form, submitter), region: name, history: 'push' })
433
- else
434
- void navigate({ url: formAction(form, submitter), region: name, history: 'push', post: { form, body: new FormData(form, submitter ?? undefined) } })
435
- }, true)
436
-
437
- document.addEventListener('input', (event) => {
438
- const field = event.target as Element | null
439
- const typed = liveForm(field)
440
- if (typed === null || formMethod(typed) !== 'get')
441
- return
442
- clearTimeout(liveTimer)
443
- liveTimer = setTimeout(() => {
444
- // A swap that landed since the key may have replaced the form: send the one on the page now, or nothing.
445
- const form = liveForm(typed) ?? liveForm(field) ?? liveForm(typed.id === '' ? null : document.getElementById(typed.id))
446
- const name = form && safeGetAttribute(form, 'data-pru-target')!
447
- if (name && !missingRegion(name, '<form>'))
448
- void navigate({ url: formUrl(form!), region: name, history: 'burst' })
449
- }, LIVE_DEBOUNCE)
450
- })
451
-
452
- const onIntent = (event: Event) => {
453
- const link = linkOf(event)
454
- if (link === null || link.hasAttribute('data-no-prefetch') || link.closest('[data-pru-prefetch]') === null)
455
- return
456
- const url = new URL(link.href, location.href)
457
- if (url.origin === location.origin && `${url.pathname}${url.search}` !== `${location.pathname}${location.search}`) {
458
- const region = findRegion(link.getAttribute('data-pru-target')!)
459
- if (region !== null)
460
- void prefetch(url.href, pathOf(region))
461
- }
462
- }
463
- listenIntent(onIntent)
464
-
465
- // Keep region state aligned when spa() swaps to another document (including popstate back to a document with prior region entries).
466
- window.addEventListener('pru:navigate', () => {
467
- shown = location.pathname + location.search
468
- appended.clear()
469
- const st = stateOf(history.state)
470
- idx = st?.__pruIdx ?? 0
471
- lastRegion = st?.__pruRegion
472
- burstOpen = false
473
- })
474
- window.addEventListener('popstate', (event) => {
475
- if (!isSameDocRegionState(event.state))
476
- return
477
- const state = stateOf(event.state)
478
- const sameDocument = location.pathname + location.search === shown
479
- shown = location.pathname + location.search
480
- if (state === undefined)
481
- return
482
- const name = state.__pruIdx < idx ? lastRegion : state.__pruRegion
483
- idx = state.__pruIdx
484
- lastRegion = state.__pruRegion
485
- burstOpen = false
486
- const restore = entryScroll(event.state)
487
- if (name === undefined || sameDocument) {
488
- // With spa() the browser leaves the scroll to the page, a swap or not.
489
- if (restore !== undefined && history.scrollRestoration === 'manual')
490
- restoreScroll(restore)
491
- return
492
- }
493
- void navigate({ url: new URL(location.href), region: name, history: 'none', ...(restore === undefined ? {} : { restore }) })
494
- })
495
- trackScroll()
496
- }
package/src/swap.ts DELETED
@@ -1,119 +0,0 @@
1
- // What a region swap and a whole-page swap share: the view transition they run in, and the scroll they keep per history entry and across the swap.
2
- // An element with `data-pru-keep-scroll="<key>"` keeps its offset by key; a `<Region>` that scrolls itself is remembered per entry as `region:<name>`.
3
-
4
- import { getDocId } from './prefetch'
5
-
6
- export interface EntryScroll { y: number, k: Record<string, number> }
7
-
8
- const SCROLLERS = '[data-pru-keep-scroll],[data-pru-region]'
9
-
10
- const keyOf = (el: Element): string => el.getAttribute('data-pru-keep-scroll') ?? `region:${el.getAttribute('data-pru-region')}`
11
-
12
- /** The offsets of the elements that keep theirs; `regions` adds the scrolled `<Region>`s, which a swap resets and a history entry restores. */
13
- export function readScrolls(regions: boolean): Record<string, number> {
14
- const out: Record<string, number> = {}
15
- for (const el of document.querySelectorAll(SCROLLERS)) {
16
- if (el.hasAttribute('data-pru-keep-scroll') || (regions && el.scrollTop > 0))
17
- out[keyOf(el)] = el.scrollTop
18
- }
19
- return out
20
- }
21
-
22
- export function writeScrolls(offsets: Record<string, number>): void {
23
- for (const el of document.querySelectorAll(SCROLLERS)) {
24
- const top = offsets[keyOf(el)]
25
- if (top !== undefined)
26
- el.scrollTop = top
27
- }
28
- }
29
-
30
- export function entryScroll(state: unknown): EntryScroll | undefined {
31
- const saved = typeof state === 'object' && state !== null ? (state as { __pruScroll?: EntryScroll }).__pruScroll : undefined
32
- return typeof saved?.y === 'number' ? saved : undefined
33
- }
34
-
35
- export function restoreScroll(saved: EntryScroll): void {
36
- writeScrolls(saved.k)
37
- window.scrollTo(0, saved.y)
38
- }
39
-
40
- /** Writes the page's scroll into the current history entry, so back and forward can return to it. */
41
- export function saveScroll(): void {
42
- try {
43
- const prev = typeof history.state === 'object' && history.state !== null ? history.state as Record<string, unknown> : {}
44
- history.replaceState({ ...prev, __pruDoc: getDocId(), __pruScroll: { y: window.scrollY, k: readScrolls(true) } satisfies EntryScroll }, '')
45
- }
46
- catch {
47
- // Restricted history API environments (e.g. sandboxed iframes) refuse state updates: the entry keeps no scroll.
48
- return
49
- }
50
- }
51
-
52
- let tracking = false
53
-
54
- /** Keeps the current entry's scroll up to date once the page stops scrolling, as a swap by back or forward has no earlier moment to read it. */
55
- export function trackScroll(): void {
56
- if (tracking)
57
- return
58
- tracking = true
59
- let timer: ReturnType<typeof setTimeout> | undefined
60
- document.addEventListener('scroll', () => {
61
- clearTimeout(timer)
62
- timer = setTimeout(saveScroll, 150)
63
- }, { capture: true, passive: true })
64
- }
65
-
66
- interface Transition { updateCallbackDone: Promise<void>, ready: Promise<void>, finished: Promise<void>, skipTransition: () => void }
67
- type Transitions = Document & { startViewTransition?: (update: () => void) => Transition }
68
-
69
- let running: Transition | undefined
70
- let listening = false
71
-
72
- // While a view transition runs, Chrome hit-tests every click to <html>: the click skips the transition and goes to what is under the pointer once it ends.
73
- function retargetClick(event: MouseEvent): void {
74
- const transition = running
75
- if (transition === undefined || event.target !== document.documentElement || event.detail === 0 || event.button !== 0)
76
- return
77
- event.preventDefault()
78
- event.stopImmediatePropagation()
79
- const { clientX, clientY } = event
80
- // A skipped transition rejects `ready`, which nothing else waits on.
81
- transition.ready.catch(() => undefined)
82
- transition.skipTransition()
83
- const resend = (): void => {
84
- const under = document.elementFromPoint(clientX, clientY)
85
- if (under instanceof HTMLElement && under !== document.documentElement)
86
- under.click()
87
- }
88
- void transition.finished.then(resend, resend)
89
- }
90
-
91
- // `navigation: { viewTransitions: false }` leaves the `@view-transition` rule out of every page: swaps follow what the page says.
92
- function pageAnimates(): boolean {
93
- for (const style of document.head.querySelectorAll('style')) {
94
- if (style.textContent?.includes('@view-transition'))
95
- return true
96
- }
97
- return false
98
- }
99
-
100
- /** Runs the DOM `update` inside a view transition where the browser has them, the app keeps them and the user allows motion; resolves once it ran. */
101
- export async function swapInTransition(update: () => void, animate = true): Promise<void> {
102
- const doc = document as Transitions
103
- if (!animate || typeof doc.startViewTransition !== 'function' || matchMedia('(prefers-reduced-motion: reduce)').matches || !pageAnimates()) {
104
- update()
105
- return
106
- }
107
- if (!listening) {
108
- listening = true
109
- document.addEventListener('click', retargetClick, true)
110
- }
111
- const transition = doc.startViewTransition(update)
112
- running = transition
113
- const done = (): void => {
114
- if (running === transition)
115
- running = undefined
116
- }
117
- void transition.finished.then(done, done)
118
- await transition.updateCallbackDone
119
- }