@prunellejs/spa 0.9.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/llms.txt +5 -2
- package/package.json +2 -2
- package/src/client.ts +81 -60
- package/src/navigation.ts +108 -0
package/llms.txt
CHANGED
|
@@ -5,7 +5,10 @@
|
|
|
5
5
|
## Imports
|
|
6
6
|
|
|
7
7
|
- `@prunellejs/spa`: `spa(options?: SpaOptions)` (returns a `PrunellePlugin` for `prunelle.config.ts`; `skipPaths?: readonly string[]` lists path prefixes that always perform full browser navigation).
|
|
8
|
-
- `@prunellejs/spa/client`:
|
|
8
|
+
- `@prunellejs/spa/client`:
|
|
9
|
+
- `navigate(url: string, push?: boolean)`: programmatic SPA navigation (pushes history by default; aborts any in-flight navigation).
|
|
10
|
+
- `prefetch(url: string, region?: string)`: populates the shared 8-entry / 15s prefetch cache; respects `Save-Data`.
|
|
11
|
+
- `useNavigation(): NavigationState` (`{ url: ReadonlySignal<string>, pathname: ReadonlySignal<string>, navigating: ReadonlySignal<boolean> }`): reactive navigation state shared across islands on the page (tree-shaken out of pages that never call it; calling it promotes the component to an island automatically). Type `NavigationState` is also exported.
|
|
9
12
|
|
|
10
13
|
## Default: MPA plus core `<Region>`
|
|
11
14
|
|
|
@@ -13,7 +16,7 @@ Most apps want plain multi-page loads (with the browser's cross-document view tr
|
|
|
13
16
|
|
|
14
17
|
## Full-Page SPA Navigation (`spa()`)
|
|
15
18
|
|
|
16
|
-
- Intercepts same-origin `<a>` clicks, diffs `<head>` stylesheets (zero-FOUC, in the order the next page serves them, every attribute kept) and meta/title/lang/dir, preserves `[data-persist]` islands, iframes, and focused inputs alive via `Element.moveBefore` across navigations, focuses the element the URL's `#hash` names, else `<main>`/`<h1>` (unless focus is inside a persisted form field), announces the new title in a polite live region, and dispatches `pru:navigate
|
|
19
|
+
- Intercepts same-origin `<a>` clicks, diffs `<head>` stylesheets (zero-FOUC, in the order the next page serves them, every attribute kept) and meta/title/tab icons (`icon`, `apple-touch-icon`, `mask-icon`)/lang/dir, preserves `[data-persist]` islands, iframes, and focused inputs alive via `Element.moveBefore` across navigations, focuses the element the URL's `#hash` names, else `<main>`/`<h1>` (unless focus is inside a persisted form field), announces the new title in a polite live region, re-seeds shared module state for the new document, and dispatches `pru:navigate` (with `{ url }` detail) and `pru:navigating` (`boolean` detail on navigation start/end).
|
|
17
20
|
- Preserves `<script data-pru-build="...">` across navigations and verifies same-origin before dynamically importing head module scripts from the next page (e.g. core's `<Region>` client when navigating from a plain page to a `<Region>` page), so stale-build detection stays active.
|
|
18
21
|
- Ships `pru-island,pru-slot,pru-s{display:contents}` as an inline CSP-hashed `<style>` in `<head>` (0 extra stylesheet network requests) so navigating from an island-less page to an island or `<Suspense>` page stays CSP-safe.
|
|
19
22
|
- Sets `history.scrollRestoration = 'manual'` and restores the saved window and `data-pru-keep-scroll` offsets once on back/forward, between two hashes of one page too. Runs the swap in a view transition unless the user prefers reduced motion or `navigation: { viewTransitions: false }` is set.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/spa",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Opt-in SPA navigation with persistent islands plugin for Prunelle",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -24,6 +24,6 @@
|
|
|
24
24
|
"directory": "packages/plugin-spa"
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
|
-
"prunelle": "^0.
|
|
27
|
+
"prunelle": "^0.10.0"
|
|
28
28
|
}
|
|
29
29
|
}
|
package/src/client.ts
CHANGED
|
@@ -11,6 +11,16 @@ import { countView, fetchKeyOf, getCachedHtml, HTML_ACCEPT, inflightPrefetch, is
|
|
|
11
11
|
import { announce, ANNOUNCER_ID, entryScroll, readScrolls, replaceKeeping, restoreScroll, saveScroll, swapInTransition, syncElementAttrs, trackScroll, trustedHtml, writeScrolls } from 'prunelle/internal/swap'
|
|
12
12
|
|
|
13
13
|
export { prefetch }
|
|
14
|
+
export { useNavigation } from './navigation'
|
|
15
|
+
export type { NavigationState } from './navigation'
|
|
16
|
+
|
|
17
|
+
const INIT_KEY = Symbol.for('pru.spa.init')
|
|
18
|
+
const NAVIGATING_KEY = Symbol.for('pru.navigating')
|
|
19
|
+
const emit = (name: string, detail: unknown) => window.dispatchEvent(new CustomEvent(name, { detail }))
|
|
20
|
+
const setNavigating = (busy: boolean) => {
|
|
21
|
+
;(window as unknown as Record<symbol, boolean | undefined>)[NAVIGATING_KEY] = busy
|
|
22
|
+
emit('pru:navigating', busy)
|
|
23
|
+
}
|
|
14
24
|
|
|
15
25
|
let activeController: AbortController | undefined
|
|
16
26
|
let currentDocKey = typeof location !== 'undefined' ? `${location.pathname}${location.search}` : ''
|
|
@@ -91,7 +101,7 @@ function isEligibleLink(link: HTMLAnchorElement): URL | undefined {
|
|
|
91
101
|
return url
|
|
92
102
|
}
|
|
93
103
|
|
|
94
|
-
const SYNC_HEAD_SELECTOR = 'meta[name="description"],meta[name="robots"],meta[property^="og:"],meta[name^="twitter:"],link[rel="canonical"],link[rel="alternate"][hreflang],script[type="application/ld+json"]'
|
|
104
|
+
const SYNC_HEAD_SELECTOR = 'meta[name="description"],meta[name="robots"],meta[property^="og:"],meta[name^="twitter:"],link[rel="canonical"],link[rel="alternate"][hreflang],link[rel="icon"],link[rel="apple-touch-icon"],link[rel="mask-icon"],script[type="application/ld+json"]'
|
|
95
105
|
|
|
96
106
|
function resolveSuspenseTemplates(doc: Document): void {
|
|
97
107
|
for (const tpl of doc.querySelectorAll<HTMLTemplateElement>('template[data-ks]')) {
|
|
@@ -324,10 +334,13 @@ async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ h
|
|
|
324
334
|
}
|
|
325
335
|
|
|
326
336
|
export async function navigate(url: string, push = true, restore?: EntryScroll, targetDocId?: number): Promise<void> {
|
|
337
|
+
const wasBusy = activeController !== undefined
|
|
327
338
|
// Abort any in-flight navigation so rapid clicks always win immediately
|
|
328
339
|
activeController?.abort()
|
|
329
340
|
const controller = new AbortController()
|
|
330
341
|
activeController = controller
|
|
342
|
+
if (!wasBusy)
|
|
343
|
+
setNavigating(true)
|
|
331
344
|
const root = document.documentElement
|
|
332
345
|
const busy = setTimeout(() => root.setAttribute('data-pru-navigating', ''), 150)
|
|
333
346
|
|
|
@@ -423,7 +436,8 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
|
|
|
423
436
|
focusPrimaryLandmark(anchor)
|
|
424
437
|
announce(document.title)
|
|
425
438
|
|
|
426
|
-
|
|
439
|
+
;(globalThis as unknown as Record<symbol, ((root?: ParentNode) => void) | undefined>)[Symbol.for('pru.reseed')]?.(document)
|
|
440
|
+
emit('pru:navigate', { url: nextFullUrl })
|
|
427
441
|
}
|
|
428
442
|
|
|
429
443
|
countView(view, nextParsed)
|
|
@@ -440,70 +454,77 @@ export async function navigate(url: string, push = true, restore?: EntryScroll,
|
|
|
440
454
|
if (activeController === controller) {
|
|
441
455
|
activeController = undefined
|
|
442
456
|
root.removeAttribute('data-pru-navigating')
|
|
457
|
+
setNavigating(false)
|
|
443
458
|
}
|
|
444
459
|
}
|
|
445
460
|
}
|
|
446
461
|
|
|
447
462
|
if (typeof document !== 'undefined') {
|
|
448
|
-
document
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
463
|
+
const doc = document as Document & Record<symbol, boolean | undefined>
|
|
464
|
+
if (!doc[INIT_KEY]) {
|
|
465
|
+
doc[INIT_KEY] = true
|
|
466
|
+
document.addEventListener('click', (event) => {
|
|
467
|
+
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
|
|
468
|
+
return
|
|
469
|
+
const target = event.target as Element | null
|
|
470
|
+
const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
|
|
471
|
+
if (!link)
|
|
472
|
+
return
|
|
473
|
+
const url = isEligibleLink(link)
|
|
474
|
+
if (url === undefined)
|
|
475
|
+
return
|
|
476
|
+
if (url.pathname === location.pathname && url.search === location.search && (url.hash || link.getAttribute('href') === '#')) {
|
|
477
|
+
saveScroll()
|
|
478
|
+
return
|
|
479
|
+
}
|
|
462
480
|
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
481
|
+
event.preventDefault()
|
|
482
|
+
void navigate(url.href, true)
|
|
483
|
+
})
|
|
484
|
+
|
|
485
|
+
const onIntent = (event: Event) => {
|
|
486
|
+
const target = event.target as Element | null
|
|
487
|
+
const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
|
|
488
|
+
// A region link prefetches its region alone, in core's region client.
|
|
489
|
+
if (!link || link.hasAttribute('data-no-prefetch') || link.hasAttribute('data-pru-target'))
|
|
490
|
+
return
|
|
491
|
+
// Prefetch is strictly opt-in via [data-pru-prefetch] so side-effecting links like /logout are never prefetched
|
|
492
|
+
if (link.closest('[data-pru-prefetch]') === null)
|
|
493
|
+
return
|
|
494
|
+
const url = isEligibleLink(link)
|
|
495
|
+
if (url === undefined)
|
|
496
|
+
return
|
|
497
|
+
if (url.pathname === location.pathname && url.search === location.search)
|
|
498
|
+
return
|
|
499
|
+
void prefetch(url.href)
|
|
500
|
+
}
|
|
466
501
|
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
502
|
+
listenIntent(onIntent)
|
|
503
|
+
|
|
504
|
+
// A region swap moves the address too, so a later #hash entry of that address is no new page.
|
|
505
|
+
window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
|
|
506
|
+
window.addEventListener('popstate', (event) => {
|
|
507
|
+
const nextDocKey = `${location.pathname}${location.search}`
|
|
508
|
+
const st = event.state as { __pruIdx?: number, __pruDoc?: number } | null
|
|
509
|
+
if (nextDocKey === currentDocKey) {
|
|
510
|
+
// The newest entry wins: a slower page still in flight must not land under this address.
|
|
511
|
+
activeController?.abort()
|
|
512
|
+
// Between two hashes of one page the browser's own restoring is off, so the entry's saved scroll goes back here.
|
|
513
|
+
const saved = entryScroll(st)
|
|
514
|
+
if (saved !== undefined)
|
|
515
|
+
restoreScroll(saved)
|
|
516
|
+
else
|
|
517
|
+
scrollToHash(location.hash)
|
|
518
|
+
return
|
|
519
|
+
}
|
|
520
|
+
// Only same-document region swaps belong to core's region client; cross-document entries (even with __pruIdx) belong to spa().
|
|
521
|
+
if (isSameDocRegionState(st))
|
|
522
|
+
return
|
|
523
|
+
const targetDocId = typeof st?.__pruDoc === 'number' ? st.__pruDoc : undefined
|
|
524
|
+
void navigate(location.href, false, entryScroll(st), targetDocId)
|
|
525
|
+
})
|
|
526
|
+
// The browser's own restoring would fight the one the swap does, once the new page is in.
|
|
527
|
+
history.scrollRestoration = 'manual'
|
|
528
|
+
trackScroll()
|
|
482
529
|
}
|
|
483
|
-
|
|
484
|
-
listenIntent(onIntent)
|
|
485
|
-
|
|
486
|
-
// A region swap moves the address too, so a later #hash entry of that address is no new page.
|
|
487
|
-
window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
|
|
488
|
-
window.addEventListener('popstate', (event) => {
|
|
489
|
-
const nextDocKey = `${location.pathname}${location.search}`
|
|
490
|
-
const st = event.state as { __pruIdx?: number, __pruDoc?: number } | null
|
|
491
|
-
if (nextDocKey === currentDocKey) {
|
|
492
|
-
// Between two hashes of one page the browser's own restoring is off, so the entry's saved scroll goes back here.
|
|
493
|
-
const saved = entryScroll(st)
|
|
494
|
-
if (saved !== undefined)
|
|
495
|
-
restoreScroll(saved)
|
|
496
|
-
else
|
|
497
|
-
scrollToHash(location.hash)
|
|
498
|
-
return
|
|
499
|
-
}
|
|
500
|
-
// Only same-document region swaps belong to core's region client; cross-document entries (even with __pruIdx) belong to spa().
|
|
501
|
-
if (isSameDocRegionState(st))
|
|
502
|
-
return
|
|
503
|
-
const targetDocId = typeof st?.__pruDoc === 'number' ? st.__pruDoc : undefined
|
|
504
|
-
void navigate(location.href, false, entryScroll(st), targetDocId)
|
|
505
|
-
})
|
|
506
|
-
// The browser's own restoring would fight the one the swap does, once the new page is in.
|
|
507
|
-
history.scrollRestoration = 'manual'
|
|
508
|
-
trackScroll()
|
|
509
530
|
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// Reactive navigation state for @prunellejs/spa (tree-shakable, zero top-level side effects).
|
|
2
|
+
|
|
3
|
+
import type { ReadonlySignal, Signal } from 'prunelle'
|
|
4
|
+
import { batch, getOwner, onCleanup, signal } from 'prunelle'
|
|
5
|
+
|
|
6
|
+
export interface NavigationState {
|
|
7
|
+
readonly url: ReadonlySignal<string>
|
|
8
|
+
readonly pathname: ReadonlySignal<string>
|
|
9
|
+
readonly navigating: ReadonlySignal<boolean>
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface SharedNav {
|
|
13
|
+
url: Signal<string>
|
|
14
|
+
pathname: Signal<string>
|
|
15
|
+
navigating: Signal<boolean>
|
|
16
|
+
refs: number
|
|
17
|
+
syncUrl: (ev?: Event) => void
|
|
18
|
+
onNavigating: (ev: Event) => void
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
type NavWindow = Window & Record<symbol, SharedNav | boolean | undefined>
|
|
22
|
+
|
|
23
|
+
function navKey(): symbol {
|
|
24
|
+
return Symbol.for('pru.spa.nav')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function navigatingKey(): symbol {
|
|
28
|
+
return Symbol.for('pru.navigating')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function createSharedNav(win: NavWindow): SharedNav {
|
|
32
|
+
const url = signal(win.location.href)
|
|
33
|
+
const pathname = signal(win.location.pathname)
|
|
34
|
+
const rawBusy = win[navigatingKey()]
|
|
35
|
+
const navigating = signal(
|
|
36
|
+
typeof rawBusy === 'boolean'
|
|
37
|
+
? rawBusy
|
|
38
|
+
: (typeof document !== 'undefined' && document.documentElement.hasAttribute('data-pru-navigating')),
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
const syncUrl = (ev?: Event) => {
|
|
42
|
+
const detailUrl = (ev as CustomEvent<{ url?: string }> | undefined)?.detail?.url
|
|
43
|
+
let nextHref: string
|
|
44
|
+
let nextPathname: string
|
|
45
|
+
if (typeof detailUrl === 'string') {
|
|
46
|
+
const parsed = new URL(detailUrl, win.location.href)
|
|
47
|
+
nextHref = parsed.href
|
|
48
|
+
nextPathname = parsed.pathname
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
nextHref = win.location.href
|
|
52
|
+
nextPathname = win.location.pathname
|
|
53
|
+
}
|
|
54
|
+
batch(() => {
|
|
55
|
+
url.value = nextHref
|
|
56
|
+
pathname.value = nextPathname
|
|
57
|
+
})
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const onNavigating = (ev: Event) => {
|
|
61
|
+
navigating.value = Boolean((ev as CustomEvent<boolean>).detail)
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
win.addEventListener('pru:navigate', syncUrl)
|
|
65
|
+
win.addEventListener('pru:region', syncUrl)
|
|
66
|
+
win.addEventListener('popstate', syncUrl)
|
|
67
|
+
win.addEventListener('hashchange', syncUrl)
|
|
68
|
+
win.addEventListener('pru:navigating', onNavigating)
|
|
69
|
+
|
|
70
|
+
const shared: SharedNav = { url, pathname, navigating, refs: 0, syncUrl, onNavigating }
|
|
71
|
+
win[navKey()] = shared
|
|
72
|
+
return shared
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function teardownSharedNav(win: NavWindow, shared: SharedNav): void {
|
|
76
|
+
win.removeEventListener('pru:navigate', shared.syncUrl)
|
|
77
|
+
win.removeEventListener('pru:region', shared.syncUrl)
|
|
78
|
+
win.removeEventListener('popstate', shared.syncUrl)
|
|
79
|
+
win.removeEventListener('hashchange', shared.syncUrl)
|
|
80
|
+
win.removeEventListener('pru:navigating', shared.onNavigating)
|
|
81
|
+
const key = navKey()
|
|
82
|
+
if (win[key] === shared)
|
|
83
|
+
delete win[key]
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function useNavigation(): NavigationState {
|
|
87
|
+
if (typeof window === 'undefined' || typeof location === 'undefined') {
|
|
88
|
+
return {
|
|
89
|
+
url: signal(''),
|
|
90
|
+
pathname: signal(''),
|
|
91
|
+
navigating: signal(false),
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const win = window as unknown as NavWindow
|
|
95
|
+
const shared = (win[navKey()] as SharedNav | undefined) ?? createSharedNav(win)
|
|
96
|
+
shared.refs++
|
|
97
|
+
if (getOwner() !== undefined) {
|
|
98
|
+
onCleanup(() => {
|
|
99
|
+
if (--shared.refs === 0)
|
|
100
|
+
teardownSharedNav(win, shared)
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
url: shared.url,
|
|
105
|
+
pathname: shared.pathname,
|
|
106
|
+
navigating: shared.navigating,
|
|
107
|
+
}
|
|
108
|
+
}
|