@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/llms.txt +18 -63
- package/package.json +4 -6
- package/src/client.ts +149 -93
- package/src/index.ts +5 -20
- package/src/navigation.ts +108 -0
- package/src/announcer.ts +0 -36
- package/src/check.ts +0 -31
- package/src/prefetch.ts +0 -130
- package/src/regions.ts +0 -496
- package/src/swap.ts +0 -119
|
@@ -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
|
+
}
|
package/src/announcer.ts
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
// The polite live region a swap announces itself in, shared by `spa()` and `regions()`.
|
|
2
|
-
|
|
3
|
-
export const ANNOUNCER_ID = '__pru-spa-announcer'
|
|
4
|
-
|
|
5
|
-
function applySrOnlyStyle(el: HTMLElement): void {
|
|
6
|
-
const s = el.style
|
|
7
|
-
s.position = 'absolute'
|
|
8
|
-
s.width = '1px'
|
|
9
|
-
s.height = '1px'
|
|
10
|
-
s.padding = '0'
|
|
11
|
-
s.margin = '-1px'
|
|
12
|
-
s.overflow = 'hidden'
|
|
13
|
-
s.clip = 'rect(0,0,0,0)'
|
|
14
|
-
s.whiteSpace = 'nowrap'
|
|
15
|
-
s.border = '0'
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
// A screen reader speaks a live region's change only once the region is in the page, and only when its text differs:
|
|
20
|
-
// the region is emptied now and filled on the next frame, so a new region, a moved one and a repeated title are all heard.
|
|
21
|
-
export function announce(text: string): void {
|
|
22
|
-
let region = document.getElementById(ANNOUNCER_ID)
|
|
23
|
-
if (region === null) {
|
|
24
|
-
region = document.createElement('div')
|
|
25
|
-
region.id = ANNOUNCER_ID
|
|
26
|
-
region.setAttribute('role', 'status')
|
|
27
|
-
region.setAttribute('aria-live', 'polite')
|
|
28
|
-
region.setAttribute('aria-atomic', 'true')
|
|
29
|
-
applySrOnlyStyle(region)
|
|
30
|
-
document.body.appendChild(region)
|
|
31
|
-
}
|
|
32
|
-
region.textContent = ''
|
|
33
|
-
requestAnimationFrame(() => {
|
|
34
|
-
region.textContent = text
|
|
35
|
-
})
|
|
36
|
-
}
|
package/src/check.ts
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
// `prunelle check` for regions(): a data-pru-target written as a string that names no <Region> in the app's src/.
|
|
2
|
-
|
|
3
|
-
import type { CheckPluginContext } from 'prunelle/config'
|
|
4
|
-
import { join, relative } from 'node:path'
|
|
5
|
-
|
|
6
|
-
const TARGET_RE = /data-pru-target=["']([^"'{}]+)["']/g
|
|
7
|
-
const REGION_RE = /<Region\b[^>]*?\bname=(?:["']([^"'{}]+)["']|\{)/g
|
|
8
|
-
|
|
9
|
-
export async function checkRegionTargets(ctx: CheckPluginContext): Promise<void> {
|
|
10
|
-
const targets: { file: string, name: string }[] = []
|
|
11
|
-
const regions = new Set<string>()
|
|
12
|
-
let computedName = false
|
|
13
|
-
for await (const path of new Bun.Glob('src/**/*.{ts,tsx}').scan({ cwd: ctx.root })) {
|
|
14
|
-
const file = join(ctx.root, path)
|
|
15
|
-
const text = await Bun.file(file).text()
|
|
16
|
-
for (const match of text.matchAll(TARGET_RE))
|
|
17
|
-
targets.push({ file: relative(ctx.root, file), name: match[1]! })
|
|
18
|
-
for (const match of text.matchAll(REGION_RE)) {
|
|
19
|
-
if (match[1] === undefined)
|
|
20
|
-
computedName = true
|
|
21
|
-
else
|
|
22
|
-
regions.add(match[1])
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
if (computedName)
|
|
26
|
-
return
|
|
27
|
-
for (const { file, name } of targets) {
|
|
28
|
-
if (!regions.has(name))
|
|
29
|
-
ctx.error(`[regions] ${file}: data-pru-target="${name}" names no <Region name="${name}"> in src/: add the region, or fix the name`)
|
|
30
|
-
}
|
|
31
|
-
}
|
package/src/prefetch.ts
DELETED
|
@@ -1,130 +0,0 @@
|
|
|
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' } : { 'x-pru-region': region }), 'accept': HTML_ACCEPT, '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
|
-
}
|