@prunellejs/spa 0.7.3 → 0.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms.txt CHANGED
@@ -1,6 +1,6 @@
1
1
  # @prunellejs/spa Reference
2
2
 
3
- > Opt-in in-place navigation: `regions()` swaps individual `<Region>` fragments from the server, and `spa()` swaps whole pages with `[data-persist]` islands (`0 B` when uninstalled; `spa()` adds 3.8 KB gzip to every page, `regions()` 4.0 KB gzip to the pages rendering a `<Region>`).
3
+ > Opt-in in-place navigation: `regions()` swaps individual `<Region>` fragments from the server, and `spa()` swaps whole pages with `[data-persist]` islands (`0 B` when uninstalled; `spa()` adds 4.1 KB gzip to every page, `regions()` 4.6 KB gzip to the pages rendering a `<Region>`).
4
4
 
5
5
  ## Imports
6
6
 
@@ -15,13 +15,14 @@ Pair `regions()` in `prunelle.config.ts` with `<Region name="pane" as="section"
15
15
  - `<a href="/items?p=2" data-pru-target="results">`: sends `x-pru-region: results`, and the server answers with the region's inner HTML alone (no layouts, no document; `ctx.region` tells `load()` which region was asked for; `vary: x-pru-region`). The client swaps it in, updates `document.title` from `x-pru-title` (the page's `<Head><title>` with the title template), pushes history (back/forward re-fetch and restore the title), moves focus to the region, announces its `aria-label`, and sets `aria-busy="true"` after 150 ms, cleared on swap or failure.
16
16
  - Without JS, or when the fetch fails or the response lacks the region, the link or form loads the whole page.
17
17
  - `data-pru-append` on a targeted `<a>`: appends response HTML, removes clicked link (Load more), replaces history entry.
18
- - `<form method="get" data-pru-target="results">`: swaps on submit; add `data-pru-live` to also swap while typing (200 ms debounce, one history entry per typing burst, which a 1 s pause ends).
18
+ - `<form method="get" data-pru-target="results">`: swaps on submit; add `data-pru-live` to also swap while typing (200 ms debounce, one history entry per typing burst, which a 1 s pause ends). Fields tied by `form="<id>"` count, and when a swap replaces the form mid-burst the form then on the page is sent.
19
19
  - Nested regions each take their own name. Asking for the inner one renders it alone (header `x-pru-region: results/sets`, outermost first, computed by the client); asking for the outer one renders it with a fresh inner; an outer swap drops in-flight fetches of the regions inside it.
20
20
  - `data-pru-sync="q tag"` on a link or input/select: keeps query params or field values outside the region in sync after every swap.
21
21
  - `[data-pru-prefetch]` ancestor: prefetches targeted links on hover/focus (`data-no-prefetch` opts a link out).
22
22
  - `<form method="post" data-pru-target="results">`: posts through `fetch`, follows the redirect and swaps the region from the final page; without JS it posts normally. `data-pru-live` is refused on it.
23
23
  - Empty fields are dropped from the URL of a GET form.
24
- - Swaps run in `document.startViewTransition` where supported, and not under `prefers-reduced-motion: reduce`. `append`, `refreshRegion()` and live typing swap without one.
24
+ - Swaps run in `document.startViewTransition` where supported, and not under `prefers-reduced-motion: reduce` nor with `navigation: { viewTransitions: false }` in `prunelle.config.ts` (it turns off `spa()`'s too). `append`, `refreshRegion()` and live typing swap without one. While a transition runs, Chrome sends every click to `<html>`: a click landing there during a swap skips the rest of the transition and is sent to the element under the pointer, so a link clicked right after a swap is not lost. Turn transitions off when a list is clicked through page after page and the fade only gets in the way.
25
+ - `data-persist="<key>"` inside a swapped region, as with `spa()`: the live element takes the place of the new HTML's element of that key, so a search field keeps focus, caret, selection and what was typed during the fetch, and one region can cover a whole filtered view, field included. An `<iframe>` keeps its document where `Element.moveBefore` exists (elsewhere it reloads, and a focused field gets its focus and selection back); key it by what it shows (`data-persist={'frame-' + page}`) so it reloads only when that changes. A live element whose key the answer lacks goes; a key on two elements of one answer logs `prunelle: data-persist="<key>" is on two elements ...` and loads the whole page. Append swaps keep nothing.
25
26
  - Each history entry remembers the window's scroll and the scrolled regions' scroll, and back/forward restores both. A pushed swap leaves the window's scroll alone and resets the region's own scroll, unless the region carries `data-pru-keep-scroll`.
26
27
  - After a swap, links whose `href` matches the new URL get `aria-current="page"`, others lose it.
27
28
  - A `#hash` link to an element already on the page scrolls to it with no fetch when its page and query are the ones the page shows, or one Load more appended; another query fetches; after a swap the page scrolls to the URL's hash.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/spa",
3
- "version": "0.7.3",
3
+ "version": "0.7.6",
4
4
  "description": "Opt-in SPA navigation with persistent islands plugin for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -26,6 +26,6 @@
26
26
  "directory": "packages/plugin-spa"
27
27
  },
28
28
  "peerDependencies": {
29
- "prunelle": "^0.7.3"
29
+ "prunelle": "^0.7.6"
30
30
  }
31
31
  }
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
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.
1
+ // @prunellejs/spa — opt-in in-place navigation: `spa()` swaps whole pages and keeps persistent islands (4.1 KB gzip), `regions()` swaps one <Region> of a page (4.6 KB gzip, on the pages with a <Region>). 0 B when uninstalled.
2
2
 
3
3
  import type { BuildPluginContext, PrunellePlugin } from 'prunelle/config'
4
4
  import { resolve } from 'node:path'
package/src/prefetch.ts CHANGED
@@ -98,7 +98,7 @@ export async function prefetch(url: string, region?: string): Promise<void> {
98
98
 
99
99
  const task = (async (): Promise<PrefetchEntry | undefined> => {
100
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' } })
101
+ const res = await fetch(clean.href, { headers: { ...(region === undefined ? { 'x-pru-spa': '1' } : { 'x-pru-region': region }), 'accept': HTML_ACCEPT, 'purpose': 'prefetch' } })
102
102
  if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
103
103
  void res.body?.cancel()
104
104
  return undefined
package/src/regions.ts CHANGED
@@ -4,6 +4,7 @@
4
4
  // - [data-pru-sync="a b"] copies those query params of the current URL into links and fields outside the region
5
5
  // - form[method=post][data-pru-target] posts through fetch, follows the redirect and swaps the region with the page it lands on
6
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
7
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
8
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
9
10
  // - prefetch on hover and focus inside [data-pru-prefetch], through the cache spa() shares
@@ -11,7 +12,7 @@
11
12
  import type { PrefetchEntry } from './prefetch'
12
13
  import type { EntryScroll } from './swap'
13
14
  import { announce } from './announcer'
14
- import { countView, fetchKeyOf, getCachedHtml, getDocId, inflightPrefetch, isSameDocRegionState, listenIntent, prefetch, prefetchCache } from './prefetch'
15
+ import { countView, fetchKeyOf, getCachedHtml, getDocId, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, prefetch, prefetchCache } from './prefetch'
15
16
  import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
16
17
 
17
18
  const BUSY_DELAY = 150
@@ -78,11 +79,13 @@ async function load(swap: Swap, region: string, signal: AbortSignal): Promise<Pr
78
79
  prefetchCache.delete(key)
79
80
  return ready
80
81
  }
81
- const res = await fetch(fetchKeyOf(url), { headers: { 'x-pru-region': region }, signal, ...(post === undefined ? {} : { method: 'POST', body: post.body }) })
82
+ const res = await fetch(fetchKeyOf(url), { headers: { 'x-pru-region': region, 'accept': HTML_ACCEPT }, signal, ...(post === undefined ? {} : { method: 'POST', body: post.body }) })
82
83
  if (post !== undefined)
83
84
  swap.landed = res.url
84
- if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html'))
85
+ if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
86
+ void res.body?.cancel()
85
87
  return undefined
88
+ }
86
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') }
87
90
  }
88
91
 
@@ -174,6 +177,59 @@ function syncCurrent(): void {
174
177
  }
175
178
  }
176
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
+
177
233
  function elementOfHash(hash: string): HTMLElement | null {
178
234
  const raw = hash.slice(1)
179
235
  let id: string
@@ -210,7 +266,7 @@ async function apply(region: HTMLElement, found: { content: DocumentFragment, ti
210
266
  // A fetch for a region about to be replaced must not land in the new one.
211
267
  for (const inner of region.querySelectorAll('[data-pru-region]'))
212
268
  controllers.get(inner.getAttribute('data-pru-region')!)?.abort()
213
- region.replaceChildren(content)
269
+ replaceKeeping(region, content)
214
270
  writeScrolls(kept)
215
271
  if (swap.history !== 'none' && !region.hasAttribute('data-pru-keep-scroll'))
216
272
  region.scrollTop = 0
@@ -255,6 +311,11 @@ async function swapRegion(swap: Swap): Promise<boolean> {
255
311
  return false
256
312
  if (swap.url.hash && !finalUrl.hash)
257
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
+ }
258
319
  countView(entry.view, finalUrl)
259
320
  await apply(region, content, swap, finalUrl)
260
321
  return true
@@ -304,6 +365,12 @@ function formAction(form: HTMLFormElement, submitter?: HTMLElement | null): URL
304
365
  return new URL(rawAction, location.href)
305
366
  }
306
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
+
307
374
  function formUrl(form: HTMLFormElement, submitter?: HTMLElement | null): URL {
308
375
  const url = formAction(form, submitter)
309
376
  // A field left empty stays out of the address, so it names only the filters in use.
@@ -367,14 +434,17 @@ if (typeof document !== 'undefined') {
367
434
  }, true)
368
435
 
369
436
  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')
437
+ const field = event.target as Element | null
438
+ const typed = liveForm(field)
439
+ if (typed === null || formMethod(typed) !== 'get')
372
440
  return
373
441
  clearTimeout(liveTimer)
374
442
  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' })
443
+ // A swap that landed since the key may have replaced the form: send the one on the page now, or nothing.
444
+ const form = liveForm(typed) ?? liveForm(field) ?? liveForm(typed.id === '' ? null : document.getElementById(typed.id))
445
+ const name = form && safeGetAttribute(form, 'data-pru-target')!
446
+ if (name && !missingRegion(name, '<form>'))
447
+ void navigate({ url: formUrl(form!), region: name, history: 'burst' })
378
448
  }, LIVE_DEBOUNCE)
379
449
  })
380
450
 
package/src/swap.ts CHANGED
@@ -63,13 +63,57 @@ export function trackScroll(): void {
63
63
  }, { capture: true, passive: true })
64
64
  }
65
65
 
66
- type Transitions = Document & { startViewTransition?: (update: () => void) => { updateCallbackDone: Promise<void> } }
66
+ interface Transition { updateCallbackDone: Promise<void>, ready: Promise<void>, finished: Promise<void>, skipTransition: () => void }
67
+ type Transitions = Document & { startViewTransition?: (update: () => void) => Transition }
67
68
 
68
- /** Runs the DOM `update` inside a view transition where the browser has them and the user allows motion; resolves once it ran. */
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. */
69
101
  export async function swapInTransition(update: () => void, animate = true): Promise<void> {
70
102
  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
103
+ if (!animate || typeof doc.startViewTransition !== 'function' || matchMedia('(prefers-reduced-motion: reduce)').matches || !pageAnimates()) {
74
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
75
119
  }