@prunellejs/spa 0.7.4 → 0.7.5

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
 
@@ -21,7 +21,8 @@ Pair `regions()` in `prunelle.config.ts` with `<Region name="pane" as="section"
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.4",
3
+ "version": "0.7.5",
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.4"
29
+ "prunelle": "^0.7.5"
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/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
@@ -176,6 +177,59 @@ function syncCurrent(): void {
176
177
  }
177
178
  }
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
+
179
233
  function elementOfHash(hash: string): HTMLElement | null {
180
234
  const raw = hash.slice(1)
181
235
  let id: string
@@ -212,7 +266,7 @@ async function apply(region: HTMLElement, found: { content: DocumentFragment, ti
212
266
  // A fetch for a region about to be replaced must not land in the new one.
213
267
  for (const inner of region.querySelectorAll('[data-pru-region]'))
214
268
  controllers.get(inner.getAttribute('data-pru-region')!)?.abort()
215
- region.replaceChildren(content)
269
+ replaceKeeping(region, content)
216
270
  writeScrolls(kept)
217
271
  if (swap.history !== 'none' && !region.hasAttribute('data-pru-keep-scroll'))
218
272
  region.scrollTop = 0
@@ -257,6 +311,11 @@ async function swapRegion(swap: Swap): Promise<boolean> {
257
311
  return false
258
312
  if (swap.url.hash && !finalUrl.hash)
259
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
+ }
260
319
  countView(entry.view, finalUrl)
261
320
  await apply(region, content, swap, finalUrl)
262
321
  return true
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
  }