@prunellejs/spa 0.0.0-stage → 0.7.2
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/LICENSE +21 -0
- package/llms.txt +82 -0
- package/package.json +29 -4
- package/src/announcer.ts +36 -0
- package/src/check.ts +31 -0
- package/src/client.ts +467 -0
- package/src/index.ts +44 -0
- package/src/prefetch.ts +130 -0
- package/src/regions.ts +425 -0
- package/src/swap.ts +75 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Kaynooo
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/llms.txt
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# @prunellejs/spa Reference
|
|
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>`).
|
|
4
|
+
|
|
5
|
+
## Imports
|
|
6
|
+
|
|
7
|
+
- `@prunellejs/spa`: `spa()`, `regions()` (both return `PrunellePlugin` for `prunelle.config.ts`).
|
|
8
|
+
- `@prunellejs/spa/regions`: `refreshRegion(name: string): Promise<void>` (redraws `<Region name>` from the current URL without touching history or focus; skips prefetch cache; rejects if region is missing or fetch fails).
|
|
9
|
+
- `@prunellejs/spa/client`: `prefetch(url: string, region?: string)` (populates the shared 8-entry / 15s prefetch cache; respects `Save-Data`).
|
|
10
|
+
|
|
11
|
+
## Partial Swaps (`regions()`)
|
|
12
|
+
|
|
13
|
+
Pair `regions()` in `prunelle.config.ts` with `<Region name="pane" as="section" ...attrs>` from `prunelle` (server-only like `Head`), which renders `<section data-pru-region="pane">` (a `<div>` without `as`). Its children are read only when the page or the requested region needs them.
|
|
14
|
+
|
|
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
|
+
- Without JS, or when the fetch fails or the response lacks the region, the link or form loads the whole page.
|
|
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).
|
|
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
|
+
- `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
|
+
- `[data-pru-prefetch]` ancestor: prefetches targeted links on hover/focus (`data-no-prefetch` opts a link out).
|
|
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
|
+
- 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.
|
|
25
|
+
- 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
|
+
- After a swap, links whose `href` matches the new URL get `aria-current="page"`, others lose it.
|
|
27
|
+
- 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.
|
|
28
|
+
- The regions client loads only on routes whose tree renders a `<Region>`: every other page ships none of it (plugin field `regionClientEntry`).
|
|
29
|
+
- Dispatches `window` event `pru:region` with `{ detail: { name, url } }`. `prunelle check` verifies every `data-pru-target` matches a `<Region>` in `src/`.
|
|
30
|
+
- `data-pru-keep-scroll="<key>"` on any element: its scroll offset survives region swaps and `spa()` swaps, and is kept per history entry.
|
|
31
|
+
- `await refreshRegion(name)` (from `@prunellejs/spa/regions`) redraws a region of the current address from script, after a background `fetch` to an action for instance: no history entry, focus left alone, prefetch cache skipped, `pru:region` fired.
|
|
32
|
+
|
|
33
|
+
## Mistakes
|
|
34
|
+
|
|
35
|
+
- Compile errors: `<Region>` without `name`, `data-pru-target` on anything but `<a>`/`<form>`, `data-pru-live` on a non-GET form, `data-pru-append`/`data-pru-live` without `data-pru-target`, a region inside a region of the same name.
|
|
36
|
+
- `prunelle check`: a `data-pru-target` naming no `<Region>` in `src/`.
|
|
37
|
+
- Runtime throws: two regions of one name on a page, a requested region the route does not render.
|
|
38
|
+
|
|
39
|
+
## Default: MPA plus `regions()`
|
|
40
|
+
|
|
41
|
+
Most apps want plain page loads (with the browser's cross-document view transitions) and `regions()` for the fragments that change in place. Add `spa()` only when islands must stay alive across pages (`[data-persist]`).
|
|
42
|
+
|
|
43
|
+
## Full-Page SPA Navigation (`spa()`)
|
|
44
|
+
|
|
45
|
+
- 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, preserves `[data-persist]` islands alive across navigations, focuses the element the URL's `#hash` names, else `<main>`/`<h1>`, announces the new title in a polite live region, and dispatches `pru:navigate`.
|
|
46
|
+
- 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. Loads the regions client of a page it swaps to.
|
|
47
|
+
- A link whose last path segment has an extension other than `.html` (`/files/report.pdf`) is left to the browser, and a response that is not HTML has its body cancelled before the full page load. Navigation and prefetch requests send `Accept: text/html`, and prefetch requests (page and region) also send `Purpose: prefetch`.
|
|
48
|
+
- A prefetch response carrying `x-pru-view: <path>` (`@prunellejs/analytics` sends it) keeps that path on its cache entry. A navigation or region swap rendered from that entry posts the page path and query to it with `navigator.sendBeacon`, before the history entry is pushed, so the page is counted although no request was made. A response without the header posts nothing.
|
|
49
|
+
- A navigation running over 150 ms sets `data-pru-navigating` on `<html>` until it ends (style a busy state with it). It starts loading the next page's island chunks while it waits for the stylesheets. Hover prefetch waits for the pointer to rest 80 ms on a link, focus prefetches at once, and at most 3 prefetches run at once.
|
|
50
|
+
- Attributes: `data-no-spa` opts a link out; `[data-pru-prefetch]` enables hover/focus prefetch; `[data-persist]` preserves an island DOM subtree.
|
|
51
|
+
|
|
52
|
+
## Snippets
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
// prunelle.config.ts
|
|
56
|
+
import { defineConfig } from 'prunelle/config'
|
|
57
|
+
import { regions, spa } from '@prunellejs/spa'
|
|
58
|
+
|
|
59
|
+
export default defineConfig({
|
|
60
|
+
plugins: [regions(), spa()],
|
|
61
|
+
})
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```tsx
|
|
65
|
+
// src/routes/search.tsx
|
|
66
|
+
import { Region } from 'prunelle'
|
|
67
|
+
import type { PageProps } from 'prunelle'
|
|
68
|
+
|
|
69
|
+
export default function Search({ url }: PageProps) {
|
|
70
|
+
const q = url.searchParams.get('q') ?? ''
|
|
71
|
+
return (
|
|
72
|
+
<>
|
|
73
|
+
<form method="get" data-pru-target="results" data-pru-live>
|
|
74
|
+
<input name="q" value={q} data-pru-sync />
|
|
75
|
+
</form>
|
|
76
|
+
<Region name="results" aria-label="Search results">
|
|
77
|
+
<p>Results for {q}</p>
|
|
78
|
+
</Region>
|
|
79
|
+
</>
|
|
80
|
+
)
|
|
81
|
+
}
|
|
82
|
+
```
|
package/package.json
CHANGED
|
@@ -1,6 +1,31 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@prunellejs/spa",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.7.2",
|
|
4
|
+
"description": "Opt-in SPA navigation with persistent islands plugin for Prunelle",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"sideEffects": [
|
|
8
|
+
"./src/client.ts",
|
|
9
|
+
"./src/regions.ts"
|
|
10
|
+
],
|
|
11
|
+
"files": [
|
|
12
|
+
"src",
|
|
13
|
+
"llms.txt"
|
|
14
|
+
],
|
|
15
|
+
"exports": {
|
|
16
|
+
".": "./src/index.ts",
|
|
17
|
+
"./client": "./src/client.ts",
|
|
18
|
+
"./regions": "./src/regions.ts"
|
|
19
|
+
},
|
|
20
|
+
"engines": {
|
|
21
|
+
"bun": ">=1.4.0"
|
|
22
|
+
},
|
|
23
|
+
"repository": {
|
|
24
|
+
"type": "git",
|
|
25
|
+
"url": "https://github.com/Kayno0o/prunelle",
|
|
26
|
+
"directory": "packages/plugin-spa"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"prunelle": "^0.7.2"
|
|
30
|
+
}
|
|
31
|
+
}
|
package/src/announcer.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
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/client.ts
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
// @prunellejs/spa client bootstrap:
|
|
2
|
+
// - Intercepts internal <a> clicks with AbortController cancellation (no dropped rapid clicks)
|
|
3
|
+
// - Diffs <head> stylesheets (zero-FOUC load-before-remove), <html lang>, <title>, meta/canonical tags
|
|
4
|
+
// - Preserves [data-persist] islands alive across View Transitions swaps
|
|
5
|
+
// - Restores scroll position on popstate, scrolls to #hash targets, manages focus & polite live announcements
|
|
6
|
+
// - Opt-in prefetch via [data-pru-prefetch] (bounded 8-entry / 15s TTL cache, respects Save-Data)
|
|
7
|
+
|
|
8
|
+
import type { EntryScroll } from './swap'
|
|
9
|
+
import { ANNOUNCER_ID, announce } from './announcer'
|
|
10
|
+
import { countView, fetchKeyOf, getCachedHtml, HTML_ACCEPT, inflightPrefetch, isSameDocRegionState, listenIntent, nextDocId, prefetch, prefetchCache, setDocId } from './prefetch'
|
|
11
|
+
import { entryScroll, readScrolls, restoreScroll, saveScroll, swapInTransition, trackScroll, writeScrolls } from './swap'
|
|
12
|
+
|
|
13
|
+
export { prefetch }
|
|
14
|
+
|
|
15
|
+
let activeController: AbortController | undefined
|
|
16
|
+
let currentDocKey = typeof location !== 'undefined' ? `${location.pathname}${location.search}` : ''
|
|
17
|
+
|
|
18
|
+
// Framework inline styles shipped in pru-island.css so SPA navigation never injects unhashed <style> tags.
|
|
19
|
+
const PRUNELLE_BUILTIN_STYLES = new Set([
|
|
20
|
+
'pru-island,pru-slot{display:contents}',
|
|
21
|
+
'pru-s{display:contents}',
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
// One-time token and OAuth redirect endpoints must hit the server once via normal navigation, never via SPA fetch.
|
|
25
|
+
const SKIP_SPA_PATH_RE = /(?:^|\/)(?:oauth(?:\/|$)|verify-email(?:\/|$)|magic-link\/verify(?:\/|$))/
|
|
26
|
+
|
|
27
|
+
// A last path segment with an extension other than .html names a file the browser fetches itself: a second request through spa would run the endpoint twice.
|
|
28
|
+
const FILE_PATH_RE = /\/[^/]*\.(?!html$)[^/.]+$/i
|
|
29
|
+
|
|
30
|
+
function isSkippedPath(pathname: string): boolean {
|
|
31
|
+
if (SKIP_SPA_PATH_RE.test(pathname) || FILE_PATH_RE.test(pathname))
|
|
32
|
+
return true
|
|
33
|
+
const raw = document.querySelector('meta[name="pru-spa-skip"]')?.getAttribute('content')
|
|
34
|
+
if (!raw)
|
|
35
|
+
return false
|
|
36
|
+
for (const entry of raw.split(',')) {
|
|
37
|
+
const prefix = entry.trim()
|
|
38
|
+
if (prefix && (pathname === prefix || pathname.startsWith(`${prefix}/`)))
|
|
39
|
+
return true
|
|
40
|
+
}
|
|
41
|
+
return false
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Inline <style> blocks present on initial document load already have their SHA-256 hashes in this document's CSP.
|
|
45
|
+
const initialInlineStyles = new Set<string>(
|
|
46
|
+
typeof document !== 'undefined'
|
|
47
|
+
? [...document.querySelectorAll('style')].map(s => s.textContent ?? '').filter(Boolean)
|
|
48
|
+
: [],
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
function hasStrictStyleCsp(csp: string | null | undefined): boolean {
|
|
52
|
+
if (!csp)
|
|
53
|
+
return false
|
|
54
|
+
const directives = new Map<string, string>()
|
|
55
|
+
for (const part of csp.split(';')) {
|
|
56
|
+
const trimmed = part.trim()
|
|
57
|
+
if (!trimmed)
|
|
58
|
+
continue
|
|
59
|
+
const space = trimmed.search(/\s/)
|
|
60
|
+
const name = (space === -1 ? trimmed : trimmed.slice(0, space)).toLowerCase()
|
|
61
|
+
const value = space === -1 ? '' : trimmed.slice(space + 1)
|
|
62
|
+
if (!directives.has(name))
|
|
63
|
+
directives.set(name, value)
|
|
64
|
+
}
|
|
65
|
+
const effective = directives.get('style-src-elem') ?? directives.get('style-src') ?? directives.get('default-src')
|
|
66
|
+
return effective !== undefined && !effective.includes("'unsafe-inline'")
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function hasBlockedInlineStyle(nextDoc: Document, csp: string | null | undefined): boolean {
|
|
70
|
+
if (!hasStrictStyleCsp(csp))
|
|
71
|
+
return false
|
|
72
|
+
for (const style of nextDoc.querySelectorAll('style')) {
|
|
73
|
+
const txt = style.textContent ?? ''
|
|
74
|
+
if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt) && !initialInlineStyles.has(txt))
|
|
75
|
+
return true
|
|
76
|
+
}
|
|
77
|
+
return false
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isEligibleLink(link: HTMLAnchorElement): URL | undefined {
|
|
81
|
+
if (link.target || link.hasAttribute('download') || link.closest('[data-no-spa]') !== null)
|
|
82
|
+
return undefined
|
|
83
|
+
const url = new URL(link.href, location.href)
|
|
84
|
+
if (url.origin !== location.origin)
|
|
85
|
+
return undefined
|
|
86
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:')
|
|
87
|
+
return undefined
|
|
88
|
+
if (isSkippedPath(url.pathname))
|
|
89
|
+
return undefined
|
|
90
|
+
return url
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
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"]'
|
|
94
|
+
|
|
95
|
+
function resolveSuspenseTemplates(doc: Document): void {
|
|
96
|
+
for (const tpl of doc.querySelectorAll<HTMLTemplateElement>('template[data-ks]')) {
|
|
97
|
+
const id = tpl.dataset.ks
|
|
98
|
+
if (!id)
|
|
99
|
+
continue
|
|
100
|
+
const slot = doc.getElementById(`k-s-${id}`)
|
|
101
|
+
if (slot !== null) {
|
|
102
|
+
slot.replaceWith(tpl.content)
|
|
103
|
+
tpl.remove()
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Focus goes where a full page load would start it: the section a hash names, else the main landmark.
|
|
109
|
+
function focusPrimaryLandmark(anchor: HTMLElement | null): void {
|
|
110
|
+
const target = anchor ?? document.querySelector<HTMLElement>('main') ?? document.querySelector<HTMLElement>('h1')
|
|
111
|
+
if (target === null)
|
|
112
|
+
return
|
|
113
|
+
if (!target.hasAttribute('tabindex'))
|
|
114
|
+
target.setAttribute('tabindex', '-1')
|
|
115
|
+
try {
|
|
116
|
+
target.focus({ preventScroll: true })
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
target.focus()
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async function prepareHeadStyles(nextDoc: Document): Promise<{ commit: () => void, abort: () => void }> {
|
|
124
|
+
const currentLinks = [...document.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')]
|
|
125
|
+
const currentByHref = new Map<string, HTMLLinkElement>()
|
|
126
|
+
for (const el of currentLinks)
|
|
127
|
+
currentByHref.set(el.getAttribute('href') ?? '', el)
|
|
128
|
+
|
|
129
|
+
const nextHrefs = new Set<string>()
|
|
130
|
+
// Every link this call puts in the head: the added ones and the copies of kept ones that had to move.
|
|
131
|
+
const added: HTMLLinkElement[] = []
|
|
132
|
+
const moved: HTMLLinkElement[] = []
|
|
133
|
+
const waitLoads: Promise<void>[] = []
|
|
134
|
+
const track = (link: HTMLLinkElement): void => {
|
|
135
|
+
waitLoads.push(new Promise<void>((resolve) => {
|
|
136
|
+
link.addEventListener('load', () => resolve(), { once: true })
|
|
137
|
+
link.addEventListener('error', () => resolve(), { once: true })
|
|
138
|
+
}))
|
|
139
|
+
added.push(link)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// The next page's stylesheets in the order it serves them, each as the link that stands for it here: the kept one, or a copy of the served one with every attribute it came with.
|
|
143
|
+
const order: HTMLLinkElement[] = []
|
|
144
|
+
for (const nextEl of nextDoc.head.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]')) {
|
|
145
|
+
const href = nextEl.getAttribute('href') ?? ''
|
|
146
|
+
if (!href)
|
|
147
|
+
continue
|
|
148
|
+
nextHrefs.add(href)
|
|
149
|
+
order.push(currentByHref.get(href) ?? document.importNode(nextEl, true))
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Layer order and cascade follow the order the next page serves, kept links included. A kept link taken out and put back would leave the page unstyled until it loaded again: a copy takes the place, and the original goes once the copy loaded.
|
|
153
|
+
let last: HTMLLinkElement | undefined
|
|
154
|
+
for (const [at, link] of order.entries()) {
|
|
155
|
+
let el = link
|
|
156
|
+
const fresh = !el.isConnected
|
|
157
|
+
if (last === undefined) {
|
|
158
|
+
const firstKept = order.find(other => other.isConnected)
|
|
159
|
+
if (fresh && firstKept !== undefined)
|
|
160
|
+
firstKept.before(el)
|
|
161
|
+
else if (fresh)
|
|
162
|
+
document.head.append(el)
|
|
163
|
+
}
|
|
164
|
+
else if (fresh || !(last.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING)) {
|
|
165
|
+
if (!fresh) {
|
|
166
|
+
moved.push(el)
|
|
167
|
+
el = el.cloneNode() as HTMLLinkElement
|
|
168
|
+
order[at] = el
|
|
169
|
+
}
|
|
170
|
+
last.after(el)
|
|
171
|
+
}
|
|
172
|
+
if (!currentLinks.includes(el))
|
|
173
|
+
track(el)
|
|
174
|
+
last = el
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (waitLoads.length > 0)
|
|
178
|
+
await Promise.race([Promise.all(waitLoads), new Promise<void>(r => setTimeout(r, 1500))])
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
abort() {
|
|
182
|
+
for (const el of added)
|
|
183
|
+
el.remove()
|
|
184
|
+
},
|
|
185
|
+
commit() {
|
|
186
|
+
for (const [href, el] of currentByHref) {
|
|
187
|
+
if (!nextHrefs.has(href))
|
|
188
|
+
el.remove()
|
|
189
|
+
}
|
|
190
|
+
for (const el of moved)
|
|
191
|
+
el.remove()
|
|
192
|
+
// Sync non-builtin <head> <style> tags (skipping pru-island/pru-s styles already covered by pru-island.css).
|
|
193
|
+
const nextHeadStyles = new Set<string>()
|
|
194
|
+
for (const nextStyle of nextDoc.head.querySelectorAll('style')) {
|
|
195
|
+
const txt = nextStyle.textContent ?? ''
|
|
196
|
+
if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt))
|
|
197
|
+
nextHeadStyles.add(txt)
|
|
198
|
+
}
|
|
199
|
+
const existingStyles = new Set<string>()
|
|
200
|
+
for (const curStyle of document.head.querySelectorAll('style')) {
|
|
201
|
+
const txt = curStyle.textContent ?? ''
|
|
202
|
+
if (!PRUNELLE_BUILTIN_STYLES.has(txt) && !nextHeadStyles.has(txt))
|
|
203
|
+
curStyle.remove()
|
|
204
|
+
else if (txt)
|
|
205
|
+
existingStyles.add(txt)
|
|
206
|
+
}
|
|
207
|
+
for (const nextStyle of nextDoc.head.querySelectorAll('style')) {
|
|
208
|
+
const txt = nextStyle.textContent ?? ''
|
|
209
|
+
if (txt && !PRUNELLE_BUILTIN_STYLES.has(txt) && !existingStyles.has(txt)) {
|
|
210
|
+
document.head.appendChild(document.importNode(nextStyle, true))
|
|
211
|
+
existingStyles.add(txt)
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
// Sync <html lang>, <html dir>, <title>, and head metadata tags
|
|
215
|
+
const nextLang = nextDoc.documentElement.getAttribute('lang')
|
|
216
|
+
if (nextLang)
|
|
217
|
+
document.documentElement.setAttribute('lang', nextLang)
|
|
218
|
+
const nextDir = nextDoc.documentElement.getAttribute('dir')
|
|
219
|
+
if (nextDir)
|
|
220
|
+
document.documentElement.setAttribute('dir', nextDir)
|
|
221
|
+
else
|
|
222
|
+
document.documentElement.removeAttribute('dir')
|
|
223
|
+
document.title = nextDoc.title
|
|
224
|
+
|
|
225
|
+
for (const oldMeta of document.head.querySelectorAll(SYNC_HEAD_SELECTOR))
|
|
226
|
+
oldMeta.remove()
|
|
227
|
+
for (const nextMeta of nextDoc.head.querySelectorAll(SYNC_HEAD_SELECTOR))
|
|
228
|
+
document.head.appendChild(document.importNode(nextMeta, true))
|
|
229
|
+
},
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
async function fetchPageHtml(fetchKey: string, signal: AbortSignal): Promise<{ html: string, url: string, csp: string | null | undefined, view?: string | null | undefined } | undefined> {
|
|
234
|
+
const cached = getCachedHtml(fetchKey)
|
|
235
|
+
if (cached !== undefined) {
|
|
236
|
+
prefetchCache.delete(fetchKey)
|
|
237
|
+
return { html: cached.html, url: cached.url, csp: cached.csp, view: cached.view }
|
|
238
|
+
}
|
|
239
|
+
const pending = inflightPrefetch.get(fetchKey)
|
|
240
|
+
const prefetched = pending !== undefined ? await pending : undefined
|
|
241
|
+
if (signal.aborted)
|
|
242
|
+
return undefined
|
|
243
|
+
if (prefetched !== undefined) {
|
|
244
|
+
prefetchCache.delete(fetchKey)
|
|
245
|
+
return { html: prefetched.html, url: prefetched.url, csp: prefetched.csp, view: prefetched.view }
|
|
246
|
+
}
|
|
247
|
+
const res = await fetch(fetchKey, {
|
|
248
|
+
headers: { 'x-pru-spa': '1', accept: HTML_ACCEPT },
|
|
249
|
+
signal,
|
|
250
|
+
})
|
|
251
|
+
if (signal.aborted)
|
|
252
|
+
return undefined
|
|
253
|
+
if (!res.ok || !(res.headers.get('content-type') ?? '').includes('text/html')) {
|
|
254
|
+
void res.body?.cancel()
|
|
255
|
+
return undefined
|
|
256
|
+
}
|
|
257
|
+
return { html: await res.text(), url: res.url || fetchKey, csp: res.headers.get('content-security-policy') }
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export async function navigate(url: string, push = true, restore?: EntryScroll, targetDocId?: number): Promise<void> {
|
|
261
|
+
// Abort any in-flight navigation so rapid clicks always win immediately
|
|
262
|
+
activeController?.abort()
|
|
263
|
+
const controller = new AbortController()
|
|
264
|
+
activeController = controller
|
|
265
|
+
const root = document.documentElement
|
|
266
|
+
const busy = setTimeout(() => root.setAttribute('data-pru-navigating', ''), 150)
|
|
267
|
+
|
|
268
|
+
const targetUrl = new URL(url, location.href)
|
|
269
|
+
const hash = targetUrl.hash
|
|
270
|
+
const fetchKey = fetchKeyOf(targetUrl)
|
|
271
|
+
|
|
272
|
+
try {
|
|
273
|
+
const fetched = await fetchPageHtml(fetchKey, controller.signal)
|
|
274
|
+
if (controller.signal.aborted)
|
|
275
|
+
return
|
|
276
|
+
if (fetched === undefined) {
|
|
277
|
+
location.assign(url)
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
const { html, url: finalUrl, csp, view } = fetched
|
|
281
|
+
|
|
282
|
+
const nextFullUrl = hash && !finalUrl.includes('#') ? `${finalUrl}${hash}` : finalUrl
|
|
283
|
+
const nextParsed = new URL(nextFullUrl, location.href)
|
|
284
|
+
// A server redirect may land on a foreign origin: fall back to a full navigation before touching the DOM or history.
|
|
285
|
+
if (nextParsed.origin !== location.origin) {
|
|
286
|
+
location.assign(nextFullUrl)
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const nextDoc = new DOMParser().parseFromString(html, 'text/html')
|
|
291
|
+
resolveSuspenseTemplates(nextDoc)
|
|
292
|
+
|
|
293
|
+
if (hasBlockedInlineStyle(nextDoc, csp)) {
|
|
294
|
+
if (push)
|
|
295
|
+
location.assign(nextFullUrl)
|
|
296
|
+
else
|
|
297
|
+
location.reload()
|
|
298
|
+
return
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// The next page's island chunks start loading now, alongside its stylesheets, not a round trip after the swap.
|
|
302
|
+
const preloaded = new Set([...document.head.querySelectorAll('link[rel=modulepreload]')].map(l => l.getAttribute('href')))
|
|
303
|
+
for (const link of nextDoc.head.querySelectorAll('link[rel=modulepreload]')) {
|
|
304
|
+
if (!preloaded.has(link.getAttribute('href')))
|
|
305
|
+
document.head.append(document.importNode(link, true))
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const headPrep = await prepareHeadStyles(nextDoc)
|
|
309
|
+
if (controller.signal.aborted) {
|
|
310
|
+
headPrep.abort()
|
|
311
|
+
return
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const applySwap = () => {
|
|
315
|
+
if (push)
|
|
316
|
+
saveScroll()
|
|
317
|
+
// Elements that keep their scroll by key keep it into the next page.
|
|
318
|
+
const kept = readScrolls(false)
|
|
319
|
+
|
|
320
|
+
const existingAnnouncer = document.getElementById(ANNOUNCER_ID)
|
|
321
|
+
|
|
322
|
+
// Preserve live [data-persist] elements (e.g. persistent audio player or counter island) across navigations
|
|
323
|
+
const persisted = new Map<string, Element>()
|
|
324
|
+
for (const el of document.querySelectorAll('[data-persist]')) {
|
|
325
|
+
const key = el.getAttribute('data-persist')
|
|
326
|
+
if (key)
|
|
327
|
+
persisted.set(key, el)
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
headPrep.commit()
|
|
331
|
+
|
|
332
|
+
for (const incoming of nextDoc.querySelectorAll('[data-persist]')) {
|
|
333
|
+
const key = incoming.getAttribute('data-persist')
|
|
334
|
+
const existing = key ? persisted.get(key) : undefined
|
|
335
|
+
if (existing !== undefined)
|
|
336
|
+
incoming.replaceWith(existing)
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
if (existingAnnouncer !== null)
|
|
340
|
+
nextDoc.body.appendChild(existingAnnouncer)
|
|
341
|
+
|
|
342
|
+
document.body.replaceWith(nextDoc.body)
|
|
343
|
+
if (push) {
|
|
344
|
+
const newDocId = nextDocId()
|
|
345
|
+
setDocId(newDocId)
|
|
346
|
+
history.pushState({ __pruDoc: newDocId }, '', nextFullUrl)
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
setDocId(targetDocId ?? nextDocId())
|
|
350
|
+
}
|
|
351
|
+
currentDocKey = `${nextParsed.pathname}${nextParsed.search}`
|
|
352
|
+
writeScrolls(kept)
|
|
353
|
+
// A page module the next page loads that this one did not (regions' client) runs now: scripts of a parsed page never do.
|
|
354
|
+
for (const script of nextDoc.head.querySelectorAll<HTMLScriptElement>('script[type="module"][src]'))
|
|
355
|
+
void import(new URL(script.getAttribute('src') ?? '', location.href).href)
|
|
356
|
+
const fb = nextDoc.querySelector<HTMLScriptElement>('script[data-kui-fallback]')?.dataset.kuiFallback
|
|
357
|
+
if (fb && !('command' in HTMLButtonElement.prototype && 'closedBy' in HTMLDialogElement.prototype && typeof CSS !== 'undefined' && CSS.supports?.('position-area:block-end'))) {
|
|
358
|
+
const fbUrl = new URL(fb, location.href)
|
|
359
|
+
if (fbUrl.origin === location.origin)
|
|
360
|
+
void import(fbUrl.href)
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
let anchor: HTMLElement | null = null
|
|
364
|
+
if (restore !== undefined) {
|
|
365
|
+
restoreScroll(restore)
|
|
366
|
+
}
|
|
367
|
+
else if (hash.length > 1) {
|
|
368
|
+
let anchorId = hash.slice(1)
|
|
369
|
+
try {
|
|
370
|
+
anchorId = decodeURIComponent(anchorId)
|
|
371
|
+
}
|
|
372
|
+
catch {
|
|
373
|
+
// Malformed percent-encoding in hash: use the raw fragment id.
|
|
374
|
+
}
|
|
375
|
+
anchor = document.getElementById(anchorId)
|
|
376
|
+
if (anchor !== null)
|
|
377
|
+
anchor.scrollIntoView()
|
|
378
|
+
else
|
|
379
|
+
window.scrollTo(0, 0)
|
|
380
|
+
}
|
|
381
|
+
else {
|
|
382
|
+
window.scrollTo(0, 0)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
focusPrimaryLandmark(anchor)
|
|
386
|
+
announce(document.title)
|
|
387
|
+
|
|
388
|
+
window.dispatchEvent(new CustomEvent('pru:navigate', { detail: { url: nextFullUrl } }))
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
countView(view, nextParsed)
|
|
392
|
+
await swapInTransition(applySwap)
|
|
393
|
+
}
|
|
394
|
+
catch (err) {
|
|
395
|
+
if (controller.signal.aborted || (err instanceof DOMException && err.name === 'AbortError'))
|
|
396
|
+
return
|
|
397
|
+
location.assign(url)
|
|
398
|
+
}
|
|
399
|
+
finally {
|
|
400
|
+
clearTimeout(busy)
|
|
401
|
+
// A newer navigation that superseded this one owns the marker.
|
|
402
|
+
if (activeController === controller) {
|
|
403
|
+
activeController = undefined
|
|
404
|
+
root.removeAttribute('data-pru-navigating')
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
if (typeof document !== 'undefined') {
|
|
410
|
+
document.addEventListener('click', (event) => {
|
|
411
|
+
if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
|
|
412
|
+
return
|
|
413
|
+
const target = event.target as Element | null
|
|
414
|
+
const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
|
|
415
|
+
if (!link)
|
|
416
|
+
return
|
|
417
|
+
const url = isEligibleLink(link)
|
|
418
|
+
if (url === undefined)
|
|
419
|
+
return
|
|
420
|
+
if (url.pathname === location.pathname && url.search === location.search && url.hash)
|
|
421
|
+
return
|
|
422
|
+
|
|
423
|
+
event.preventDefault()
|
|
424
|
+
void navigate(url.href, true)
|
|
425
|
+
})
|
|
426
|
+
|
|
427
|
+
const onIntent = (event: Event) => {
|
|
428
|
+
const target = event.target as Element | null
|
|
429
|
+
const link = target?.closest?.('a[href]') as HTMLAnchorElement | null
|
|
430
|
+
// A region link prefetches its region alone, in regions().
|
|
431
|
+
if (!link || link.hasAttribute('data-no-prefetch') || link.hasAttribute('data-pru-target'))
|
|
432
|
+
return
|
|
433
|
+
// Prefetch is strictly opt-in via [data-pru-prefetch] so side-effecting links like /logout are never prefetched
|
|
434
|
+
if (link.closest('[data-pru-prefetch]') === null)
|
|
435
|
+
return
|
|
436
|
+
const url = isEligibleLink(link)
|
|
437
|
+
if (url === undefined)
|
|
438
|
+
return
|
|
439
|
+
if (url.pathname === location.pathname && url.search === location.search)
|
|
440
|
+
return
|
|
441
|
+
void prefetch(url.href)
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
listenIntent(onIntent)
|
|
445
|
+
|
|
446
|
+
// A region swap moves the address too, so a later #hash entry of that address is no new page.
|
|
447
|
+
window.addEventListener('pru:region', () => { currentDocKey = `${location.pathname}${location.search}` })
|
|
448
|
+
window.addEventListener('popstate', (event) => {
|
|
449
|
+
const nextDocKey = `${location.pathname}${location.search}`
|
|
450
|
+
const st = event.state as { __pruIdx?: number, __pruDoc?: number } | null
|
|
451
|
+
if (nextDocKey === currentDocKey) {
|
|
452
|
+
// Between two hashes of one page the browser's own restoring is off, so the entry's saved scroll goes back here.
|
|
453
|
+
const saved = entryScroll(st)
|
|
454
|
+
if (saved !== undefined)
|
|
455
|
+
restoreScroll(saved)
|
|
456
|
+
return
|
|
457
|
+
}
|
|
458
|
+
// Only same-document region swaps belong to regions(); cross-document entries (even with __pruIdx) belong to spa().
|
|
459
|
+
if (isSameDocRegionState(st))
|
|
460
|
+
return
|
|
461
|
+
const targetDocId = typeof st?.__pruDoc === 'number' ? st.__pruDoc : undefined
|
|
462
|
+
void navigate(location.href, false, entryScroll(st), targetDocId)
|
|
463
|
+
})
|
|
464
|
+
// The browser's own restoring would fight the one the swap does, once the new page is in.
|
|
465
|
+
history.scrollRestoration = 'manual'
|
|
466
|
+
trackScroll()
|
|
467
|
+
}
|