diff --git a/CHANGELOG.md b/CHANGELOG.md index d9a8c8d..7c3080c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -121,6 +121,19 @@ What changes for apps: - **`calyx --bundle` compiles again** inside the bundle, with the binary it bundles. +### Navigation in SvelteKit apps is faster + +After every navigation SvelteKit walks the page for its links, to set up +preloading, and for `[autofocus]`. The DOM layer now resolves a link's +`href` once per attribute and page, builds a selector's test once instead +of matching it from scratch on every element, and makes a `URL`'s +`searchParams` only when it is asked for. SvelteKit's look at each link +went from 16.3 to 7.3 µs; in the Tracker the turn that renders the Board +is 5.5 ms shorter and Issues' 3.2 (`compare/results/nav-cost.md`). + +- `searchParams` on the DOM layer's `URL` is no longer an own property of + each URL, as in browsers and Node: `Object.keys(url)` no longer lists it. + ## 0.2.0-alpha.0 (25 Nov 2026) ### Breaking: SvelteKit is the only router diff --git a/CLAUDE.md b/CLAUDE.md index 3e360e8..4ed3730 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -534,6 +534,10 @@ at the size when a change adds crates or features. AppKit: it cannot show a problem in how macOS delivers events. `key ` (`key Escape`) and `type ` press keys; those start one step later, at the document, because winit cannot build a key event. +- Timing a step headless, put `drive`'s `gc:` before it: a cycle + collection, so that none lands in one run and not the next (a Board visit + varies from 78 to 117 ms without it). Time with `Date.now()` in an + `eval:`: `performance.now()` stands still headless. - `drive`'s `time:` moves virtual time and returns at once, so a `fetch` over the network is still on its way. `real:SECONDS` lets real time pass while the host's answers come in: `drive real:4 text:SEL`. diff --git a/HANDOVER.md b/HANDOVER.md index 0f1fd5a..52f3f80 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -7,6 +7,50 @@ standing rules and `README.md` the architecture; this file is the work. what was published before the rename, and under which names, is in `CHANGELOG.md`. +## Navigation costs (27 Nov 2026, branch `nav-cost`) + +After every navigation SvelteKit walks the whole page twice: `a`, to set +up link preloading (each link's `href`, a `new URL` of it, five +`getAttribute`s on every ancestor), and `[autofocus]`. Three changes in +the DOM layer, each its own commit: + +- A link's `href` is resolved once per attribute value and page address + (`resolve_href` in `dom.js`): 4.9 to 0.47 µs a link. +- A selector's test is built once (`test_for` in `dom.js`): one tag, one + attribute that must be there, one id or one class gets a test of its + own, any other compound is matched directly. `querySelectorAll('a')` on + the Board went from 1,775 to 800 µs, `[autofocus]` from 2,475 to 750. +- `url.js`: `searchParams` is made on first use, and the raw query and the + no-authority flag are private fields: `new URL` from 4.27 to 0.87 µs. + `searchParams` is no longer an own property, as in Node. + +SvelteKit's loop went from 16.3 to 7.28 µs a link. In a window (session +`nav-1`, `compare/results/nav-cost.md`) the Board's render turn is 5.5 ms +shorter and Issues' 3.2. Insights' mark is 7.6 ms later with the same +render turn: the click's `requestAnimationFrame` waits for the next vsync, +and where the click lands in a 13 ms frame moves the mark. `drive` has a +`gc:` step for timing headless: without it, a Board visit varied from 78 to +117 ms, with it from 80 to 87. + +Found on the way, and not changed: + +- **A first visit pays for growth.** The Board's first visit costs ~50 ms + over a repeat, on the old main too, spread evenly over its 300 cards. + Making and dropping 20,000 of the renderer's nodes beforehand takes all of + it away; plain objects, `Map`s or `WeakRef`s alone take 4-16 ms of it. + Not `cn()`, Svelte's templates, Bits UI, the data, QuickJS's collector or + its warm-up. Which part of the growth costs is the next job; startup's + first screen probably pays the same. +- The split build's first visits trail a single bundle by 1-1.5 ms, and + not on the Board: no turn waits for a route's stylesheet, and the chunk + is read in the turn that renders it. +- With the growth taken out of both, the Board's first visit is ~14 ms + behind the old main, ~9 of it the two walks before these changes; ~5 ms + is not accounted for. +- The ancestor walk (4.1 µs a link) is SvelteKit's own calls. +- The parsed-selector cache and the new test cache are unbounded: an app + that builds selectors with ids in them grows both. + ## Modules load as QuickJS bytecode (26 Nov 2026, branch `bytecode`) `calyx --compile ` compiles every module of the app folder with the @@ -87,13 +131,9 @@ Left for later, each its own job: and **the server build** (the backend thread), which the adapter refuses today. 2. **The host's size on Linux**, under the 30 MB budget. -3. **SvelteKit's link scan.** After every navigation SvelteKit looks at - each `` on the page (its URL, its `data-sveltekit-*` options up the - ancestors) to set up preloading: about 32 µs a link in the DOM layer, - 10 ms on the Board's 316. Main never paid it, because its `` was a - stand-in with no children. `href`, attribute reads and `closest` are - where it can come down (`preload-fix.md`). Without it the Board is still - 4.7 ms behind main on a repeat visit: not looked into. +3. ~~**SvelteKit's link scan**~~: done, branch `nav-cost` (above): 16.3 to + 7.3 µs a link. The 4.7 ms the Board was still behind main without it + was the `[autofocus]` walk. 4. ~~**Blitz hit testing clipped to `overflow: hidden`**~~: done, blitz-dom patch 14, for every box that clips its overflow (a scroll box too: the counter's buttons stopped taking clicks once its list was scrolled). diff --git a/README.md b/README.md index aa7246f..12c9847 100644 --- a/README.md +++ b/README.md @@ -1038,6 +1038,10 @@ What the time is spent on, from sampling: renderer's glyph atlas is now on (a patch to the vendored `anyrender_vello_hybrid`), which cut the time spent painting by half. A page with an endless animation, such as a `Skeleton`, still never idles. +- **Navigation.** After every navigation SvelteKit looks at each link on + the page, to set up preloading, and walks the page for `[autofocus]`: on + the Tracker's Board, 316 links of 3,500 elements, that is about 4 ms in the + DOM layer (7.3 µs a link and two walks of under 1 ms). - **Start-up.** Modules load as bytecode, compiled when the app is built: the Tracker's page starts 19-20 ms sooner than when QuickJS parsed and compiled its 36 modules at every launch (`compare/results/bytecode.md`). diff --git a/compare/results/make_nav_report.py b/compare/results/make_nav_report.py new file mode 100644 index 0000000..a2456b9 --- /dev/null +++ b/compare/results/make_nav_report.py @@ -0,0 +1,203 @@ +"""Navigation after the DOM layer's three fixes, against main, at 1,000 issues. + + python3 compare/results/make_nav_report.py [session] > compare/results/nav-cost.md + +One interleaved session (default nav-1), Stage Manager off, warm-up and aborted runs left out: + main Sepal on main at 51d4598 build blitzb + branch Sepal on nav-cost at 6fec75a: the href cache, selector tests build blitzc + built once, url.js's lazy searchParams +Both bench builds were bundled by the same dist-profile host, built at +6fec75a (the branch changes no Rust the host runs): the two apps differ in +one chunk, the entry, which carries the DOM layer and url.js. Each cell is +the median of the runs, with the range under it. +""" +import json +import re +import statistics as st +import sys +from pathlib import Path + +RESULTS = Path(__file__).parent +SESSION = sys.argv[1] if len(sys.argv) > 1 else 'nav-1' +COLS = [('main', 'blitzb'), ('branch', 'blitzc')] +HELP = ('WebKit', 'com.apple.WebKit') +MB = 1024 * 1024 + +RUNS = [json.loads(line) for line in (RESULTS / 'raw' / SESSION / 'runs.jsonl').open()] + + +def runs(build, n): + return [r for r in RUNS if r['status'] == 'ok' and not r.get('warmup') and r['build'] == build and r['scenario'] == n] + + +def median(vals): + vals = [v for v in vals if v is not None] + return st.median(vals) if vals else None + + +def cell(vals, d): + vals = [v for v in vals if v is not None] + if not vals: + return 'n/a' + f = lambda v: f'{v:,.{d}f}' + lo, hi = min(vals), max(vals) + return f'{f(st.median(vals))}
{f(lo)}–{f(hi)}' if len(vals) > 1 and lo != hi else f(st.median(vals)) + + +def table(title, scenarios, rows): + print(f'### {title}\n') + print('| | ' + ' | '.join(c for c, _ in COLS) + ' | branch − main |') + print('|---|' + '---:|' * (len(COLS) + 1)) + for label, fn, d in rows: + vals = [[fn(r) for n in scenarios for r in runs(b, n)] for _, b in COLS] + a, b = median(vals[0]), median(vals[1]) + gap = f'{b - a:+,.{d}f}' if a is not None and b is not None else 'n/a' + print(f'| {label} | ' + ' | '.join(cell(v, d) for v in vals) + f' | {gap} |') + counts = ', '.join(f'{c}: {sum(len(runs(b, n)) for n in scenarios)}' for c, b in COLS) + print(f'\nRuns: {counts}.\n') + + +def step(label, key): + def get(r): + s = next((s for s in r['steps'] if s['label'] == label), None) + return s.get(key) if s else None + return get + + +def mark(name): + return lambda r: (r.get('startup') or {}).get(name, {}).get('ms_from_exec') + + +def startup(key): + return lambda r: (r.get('startup') or {}).get(key) + + +def first_input(r): + return ((r.get('startup') or {}).get('first_input') or {}).get('ms_from_exec') + + +def frame_after_mounted(r): + return ((r.get('startup') or {}).get('first_frame_after_mounted') or {}).get('ms_from_exec') + + +def page_started(r): + """The host's own count: index.html parsed, its scripts run, settled.""" + for line in (RESULTS / r['log']).read_text().splitlines(): + m = re.search(r'the page started in ([\d.]+)ms', line) + if m: + return float(m.group(1)) + return None + + +def turn(mark_name): + """The navigation's turn in the window trace: the `poll took` line after its MARK.""" + def get(r): + lines = (RESULTS / r['log']).read_text().splitlines() + i = next((k for k, l in enumerate(lines) if f'MARK {mark_name}' in l), None) + if i is None: + return None + m = next((re.search(r'poll took ([\d.]+)ms', l) for l in lines[i:] if 'poll took' in l), None) + return float(m.group(1)) if m else None + return get + + +def presented(r): + d = r.get('trace_damage') + return d['full'] + d['partial'] if d else None + + +ram = lambda fp: sum(p['footprint'] for p in fp['processes'] if p['name'] not in HELP) / MB if fp else None +cpu = lambda r: r['usage']['cpu_ns'] / 1e6 +gpu = lambda r: r['gpu_ns'] / 1e6 if 'gpu_ns' in r else None +wake = lambda r: r['usage'].get('interrupt_wkups') + +print(__doc__.split('\n\n')[0].strip('"'), '\n') +print(f'Session `{SESSION}`, interleaved, 1 warm-up and 3 runs per build and scenario, Stage Manager off, ' + 'no screen recording. M4 Pro, macOS 27.0.1, 5K display at 75 Hz. Times are from the input.\n') + +table('Idle, 20 s (scenario 3)', [3], [ + ('CPU time, ms', cpu, 1), + ('GPU time, ms', gpu, 2), + ('frames presented', presented, 0), + ('interrupt wake-ups', wake, 0), + ('RAM 5 s after load, MB', lambda r: ram(r.get('footprint_mounted5')), 1), + ('RAM at the end, MB', lambda r: ram(r.get('footprint')), 1), +]) +table('Open an issue (scenario 5)', [5], [ + ('click row → mark, ms', step('click row', 'ms_to_mark'), 1), + ('click row → frame, ms', step('click row', 'ms_to_frame'), 1), + ('Escape → mark, ms', step('Escape', 'ms_to_mark'), 1), + ('Escape → frame, ms', step('Escape', 'ms_to_frame'), 1), +]) +SCREENS = ('board', 'insights', 'settings', 'issues') +table('Switch screens (scenario 10)', [10], [ + *[(f'{to} → mark, ms', step(f'click nav-{to}', 'ms_to_mark'), 1) for to in SCREENS], + *[(f'{to} → frame, ms', step(f'click nav-{to}', 'ms_to_frame'), 1) for to in SCREENS], + *[(f'{to}: the turn that renders it, ms', turn(f'nav:/{to}'), 1) for to in SCREENS], +]) + + +print('''### Notes + +- **The render turns are the cleaner number.** The Board's is 5.5 ms + shorter and Issues' 3.2; Settings and Insights are within 1 ms. The + marks and frames add the wait before that turn: SvelteKit follows a + link from a `requestAnimationFrame` callback, which waits for the next + vsync, and while the nav item's hover transition draws, frames are + coming every 13 ms. Where the click lands in that cycle moves a mark by + up to a frame. Insights shows it: the same render turn on both builds, + and its mark 7.6 ms later on the branch. Headless, where there are no + frames, its first visit is 1 ms quicker. +- **Idle** is the same: no frames, 34 and 32 wake-ups in 20 s. + +### Where SvelteKit's link scan went + +After every navigation SvelteKit takes `querySelectorAll('a')` and, for +each link, its `href`, a `new URL` of it, and five `getAttribute`s on every +ancestor up to ``, to set up preloading. Timed piece by piece on the +Board (316 links, 8.9 ancestors each, 3,529 elements), headless, µs a link: + +| | before | after | +|---|---:|---:| +| `a.href` | 4.9 | 0.47 | +| `new URL(a.href, document.baseURI)` | 4.27 | 0.87 | +| the ancestor walk (`getAttribute` and `parentNode`) | 4.35 | 4.11 | +| the loop, whole | 16.3 | 7.28 | +| `querySelectorAll('a')`, per call | 1,775 | 800 | +| `querySelector('[autofocus]')`, per call | 2,475 | 750 | + +One commit for each, with a cycle collection before each timed step +(`drive`'s `gc:`): the Board's repeat visit went from 76 to 73 ms with the +`href` cache, to 70 with the selector tests, and to 69 with url.js. The +ancestor walk is SvelteKit's own five calls a level, which no change on +this side makes fewer. + +The 4.7 ms the Board trailed the old main by (`preload-fix.md`, without the +scan) was `[autofocus]`, the other walk of the whole page: with both +walks taken out, the Board's repeat visit was 72 ms, the old main's +(`bae68bb`) 72 ms. + +### First visits + +A screen's first visit is not slower in the split build for any reason of +its own: headless, the split build trails a single bundle by 1-1.5 ms on +Insights, Settings and opening an issue (the route's chunk read and Vite's +preload helper adding a `modulepreload` link), and not at all on the +Board. The route's chunk is read in the turn that renders it, no turn waits +for a stylesheet, and the turns are the same: the click's frame, then the +timer that navigates and renders. + +The Board's first visit costs ~50 ms over a repeat (136 against 76 ms +here), on the old main too. It is spread evenly over the 300 cards it +draws (210-320 µs a card, against 130-145), and it is neither `cn()` (0.55 +ms), nor Svelte's templates (a custom renderer gets new nodes every time), +nor Bits UI, the app's data, QuickJS's collector or its warm-up. Making and +dropping 20,000 of the renderer's nodes before the first visit takes all of +it away: the process makes nodes in numbers it has not before. Which part +of that growth costs, JavaScript's or the allocator's, is the next job. + +| headless, ms | first visit | repeat | first, 20,000 nodes made first | repeat, same | +|---|---:|---:|---:|---:| +| before | 134-136 | 76-77 | 76-78 | 70-72 | +| after | 132-136 | 72-73 | 73 | 67-68 | +''') diff --git a/compare/results/nav-cost.md b/compare/results/nav-cost.md new file mode 100644 index 0000000..2c681d9 --- /dev/null +++ b/compare/results/nav-cost.md @@ -0,0 +1,111 @@ +Navigation after the DOM layer's three fixes, against main, at 1,000 issues. + +Session `nav-1`, interleaved, 1 warm-up and 3 runs per build and scenario, Stage Manager off, no screen recording. M4 Pro, macOS 27.0.1, 5K display at 75 Hz. Times are from the input. + +### Idle, 20 s (scenario 3) + +| | main | branch | branch − main | +|---|---:|---:|---:| +| CPU time, ms | 6.5
6.3–7.0 | 6.8
6.3–8.3 | +0.3 | +| GPU time, ms | 0.00 | 0.00 | +0.00 | +| frames presented | 0 | 0 | +0 | +| interrupt wake-ups | 34
33–35 | 32
31–35 | -2 | +| RAM 5 s after load, MB | 105.1
102.3–105.2 | 105.4
102.8–105.8 | +0.3 | +| RAM at the end, MB | 96.9
96.1–97.1 | 97.2
96.6–97.6 | +0.3 | + +Runs: main: 3, branch: 3. + +### Open an issue (scenario 5) + +| | main | branch | branch − main | +|---|---:|---:|---:| +| click row → mark, ms | 22.5
22.4–22.9 | 24.6
24.1–28.3 | +2.1 | +| click row → frame, ms | 44.0
38.1–45.1 | 36.9
36.1–40.6 | -7.1 | +| Escape → mark, ms | 30.3
27.4–30.4 | 24.7
18.0–29.9 | -5.6 | +| Escape → frame, ms | 44.5
43.1–44.5 | 43.4
36.6–44.6 | -1.1 | + +Runs: main: 3, branch: 3. + +### Switch screens (scenario 10) + +| | main | branch | branch − main | +|---|---:|---:|---:| +| board → mark, ms | 109.3
108.0–112.4 | 98.5
97.0–112.1 | -10.8 | +| insights → mark, ms | 51.3
51.0–54.9 | 58.8
58.3–61.9 | +7.6 | +| settings → mark, ms | 40.2
39.5–47.3 | 41.2
38.2–44.3 | +1.1 | +| issues → mark, ms | 61.5
53.5–62.6 | 51.0
50.5–59.8 | -10.4 | +| board → frame, ms | 143.0
140.1–147.0 | 133.7
128.1–141.7 | -9.3 | +| insights → frame, ms | 65.5
64.8–69.0 | 76.2
72.2–77.3 | +10.7 | +| settings → frame, ms | 48.8
48.7–54.7 | 49.7
46.8–51.7 | +0.9 | +| issues → frame, ms | 77.8
68.9–86.7 | 66.2
65.7–75.2 | -11.6 | +| board: the turn that renders it, ms | 109.2
107.8–109.2 | 103.7
102.7–105.7 | -5.5 | +| insights: the turn that renders it, ms | 39.6
39.0–42.0 | 40.5
38.2–40.9 | +0.9 | +| settings: the turn that renders it, ms | 23.8
23.5–25.9 | 23.3
22.7–25.1 | -0.5 | +| issues: the turn that renders it, ms | 44.4
44.2–46.1 | 41.2
40.7–42.1 | -3.2 | + +Runs: main: 3, branch: 3. + +### Notes + +- **The render turns are the cleaner number.** The Board's is 5.5 ms + shorter and Issues' 3.2; Settings and Insights are within 1 ms. The + marks and frames add the wait before that turn: SvelteKit follows a + link from a `requestAnimationFrame` callback, which waits for the next + vsync, and while the nav item's hover transition draws, frames are + coming every 13 ms. Where the click lands in that cycle moves a mark by + up to a frame. Insights shows it: the same render turn on both builds, + and its mark 7.6 ms later on the branch. Headless, where there are no + frames, its first visit is 1 ms quicker. +- **Idle** is the same: no frames, 34 and 32 wake-ups in 20 s. + +### Where SvelteKit's link scan went + +After every navigation SvelteKit takes `querySelectorAll('a')` and, for +each link, its `href`, a `new URL` of it, and five `getAttribute`s on every +ancestor up to ``, to set up preloading. Timed piece by piece on the +Board (316 links, 8.9 ancestors each, 3,529 elements), headless, µs a link: + +| | before | after | +|---|---:|---:| +| `a.href` | 4.9 | 0.47 | +| `new URL(a.href, document.baseURI)` | 4.27 | 0.87 | +| the ancestor walk (`getAttribute` and `parentNode`) | 4.35 | 4.11 | +| the loop, whole | 16.3 | 7.28 | +| `querySelectorAll('a')`, per call | 1,775 | 800 | +| `querySelector('[autofocus]')`, per call | 2,475 | 750 | + +One commit for each, with a cycle collection before each timed step +(`drive`'s `gc:`): the Board's repeat visit went from 76 to 73 ms with the +`href` cache, to 70 with the selector tests, and to 69 with url.js. The +ancestor walk is SvelteKit's own five calls a level, which no change on +this side makes fewer. + +The 4.7 ms the Board trailed the old main by (`preload-fix.md`, without the +scan) was `[autofocus]`, the other walk of the whole page: with both +walks taken out, the Board's repeat visit was 72 ms, the old main's +(`bae68bb`) 72 ms. + +### First visits + +A screen's first visit is not slower in the split build for any reason of +its own: headless, the split build trails a single bundle by 1-1.5 ms on +Insights, Settings and opening an issue (the route's chunk read and Vite's +preload helper adding a `modulepreload` link), and not at all on the +Board. The route's chunk is read in the turn that renders it, no turn waits +for a stylesheet, and the turns are the same: the click's frame, then the +timer that navigates and renders. + +The Board's first visit costs ~50 ms over a repeat (136 against 76 ms +here), on the old main too. It is spread evenly over the 300 cards it +draws (210-320 µs a card, against 130-145), and it is neither `cn()` (0.55 +ms), nor Svelte's templates (a custom renderer gets new nodes every time), +nor Bits UI, the app's data, QuickJS's collector or its warm-up. Making and +dropping 20,000 of the renderer's nodes before the first visit takes all of +it away: the process makes nodes in numbers it has not before. Which part +of that growth costs, JavaScript's or the allocator's, is the next job. + +| headless, ms | first visit | repeat | first, 20,000 nodes made first | repeat, same | +|---|---:|---:|---:|---:| +| before | 134-136 | 76-77 | 76-78 | 70-72 | +| after | 132-136 | 72-73 | 73 | 67-68 | + diff --git a/crates/host/examples/drive.rs b/crates/host/examples/drive.rs index 0945daa..1317cd9 100644 --- a/crates/host/examples/drive.rs +++ b/crates/host/examples/drive.rs @@ -11,7 +11,9 @@ //! answers arrive: for `fetch` and other host calls that wait on the network //! or the disk), `text:SELECTOR`, `count:SELECTOR`, //! `rect:SELECTOR`, `attr:SELECTOR@NAME`, `eval:JAVASCRIPT`, `files:` (how -//! many files the app has read from its folder), `hud:on`/`hud:off` +//! many files the app has read from its folder), `gc:` (a cycle collection, +//! with the `DROP`s it queues applied: before a step that is timed, so that +//! no collection lands in one run and not in the next), `hud:on`/`hud:off` //! (the performance overlay), `shot:FILE.png` //! (CPU renderer), `gpushot:FILE.png` (the window's renderer; needs a GPU). //! @@ -72,6 +74,11 @@ fn main() { println!(" type {rest}") } "eval" => println!(" eval: {:?}", doc.js().eval_string(rest)), + "gc" => { + doc.js().collect_garbage(); + doc.settle(); + println!(" gc") + } "hud" => { doc.set_hud(rest == "on"); println!(" hud {rest}") diff --git a/packages/sepal/src/dom.js b/packages/sepal/src/dom.js index ad2cfa0..873f60b 100644 --- a/packages/sepal/src/dom.js +++ b/packages/sepal/src/dom.js @@ -144,8 +144,42 @@ function matches_complex(node, complex, index = complex.compounds.length - 1) { return false; } +/** + * The test for a selector, built once. Walks of the page call it on every + * element: SvelteKit looks for `a` and `[autofocus]` after every navigation, + * 3,500 elements on the Tracker's Board, and going through the general + * matcher for each cost 1.8 and 2.4 ms. One tag, one attribute that must be + * there, one id or one class gets a test of its own; any other compound + * without combinators is matched directly; the rest as a list. + * @type {Map boolean>} + */ +const tests = new Map(); + +/** @param {string} selector */ +function test_for(selector) { + let test = tests.get(selector); + if (test !== undefined) return test; + const list = parse_selector(selector); + const one = list.length === 1 && list[0].compounds.length === 1 ? list[0].compounds[0] : null; + if (one === null) { + test = (node) => list.some((complex) => matches_complex(node, complex)); + } else { + const parts = (one.tag !== null ? 1 : 0) + (one.id !== null ? 1 : 0) + one.classes.length + one.attrs.length + one.nots.length + one.pseudos.length; + const { tag, id } = one; + const [name] = one.classes; + const attr = one.attrs[0]; + if (parts === 1 && tag !== null) test = (node) => node.type === 'element' && (node.name === tag || node.name.toLowerCase() === tag); + else if (parts === 1 && id !== null) test = (node) => node.type === 'element' && node.attrs !== null && node.attrs.get('id') === id; + else if (parts === 1 && name !== undefined) test = (node) => node.type === 'element' && node.attrs !== null && (node.attrs.get('class') ?? '').split(/\s+/).includes(name); + else if (parts === 1 && attr !== undefined && attr.op === null) test = (node) => node.type === 'element' && node.attrs !== null && node.attrs.has(attr.name); + else test = (node) => matches_compound(node, one); + } + tests.set(selector, test); + return test; +} + /** @param {any} node @param {string} selector */ -const matches = (node, selector) => parse_selector(selector).some((complex) => matches_complex(node, complex)); +const matches = (node, selector) => test_for(selector)(node); /** Every element below `scope`, in document order. @param {any} scope @param {(node: any) => boolean | void} visit returns true to stop */ function walk(scope, visit) { @@ -213,8 +247,9 @@ function query_all(scope, selector) { if (candidates !== null) return [...candidates].sort((a, b) => (precedes(a, b) ? -1 : 1)); /** @type {any[]} */ const found = []; + const test = test_for(selector); walk(scope, (node) => { - if (matches(node, selector)) found.push(node); + if (test(node)) found.push(node); }); return found; } @@ -228,8 +263,9 @@ function query(scope, selector) { return first; } let found = null; + const test = test_for(selector); walk(scope, (node) => { - if (!matches(node, selector)) return false; + if (!test(node)) return false; found = node; return true; }); @@ -748,7 +784,7 @@ define(proto, { get() { const written = this.attrs?.get('href'); if (written === undefined) return ''; - return URL.parse(written, address.href)?.href ?? written; + return resolve_href(written, address.href); }, /** @this {any} @param {any} value */ set(value) { @@ -971,6 +1007,30 @@ function is_focusable(node) { return /^(button|input|select|textarea|summary)$/i.test(node.name) || (/^(a|area)$/i.test(node.name) && node.attrs?.has('href')); } +/** + * Where a link's `href` attribute leads from a page, by both. SvelteKit reads + * every link's `href` after each navigation, to set up preloading, and + * resolving one builds a whole `URL`: 316 of them were 1.8 ms of a Board + * visit in the Tracker. Keyed by the page's address as well, which a + * relative attribute depends on. + * ponytail: dropped whole at 4,096 entries, as url.js's parses are. + * @type {Map} + */ +const resolved_hrefs = new Map(); + +/** @param {string} written @param {string} base */ +function resolve_href(written, base) { + // The base's length first, so that no attribute can make two pairs one key. + const key = `${base.length}:${base}${written}`; + let href = resolved_hrefs.get(key); + if (href === undefined) { + href = URL.parse(written, base)?.href ?? written; + if (resolved_hrefs.size >= 4096) resolved_hrefs.clear(); + resolved_hrefs.set(key, href); + } + return href; +} + /** A DOM class that elements with one of these tag names count as. @param {((node: any) => boolean)} test */ const node_class = (test) => { const stand_in = function () { diff --git a/packages/sepal/src/url.js b/packages/sepal/src/url.js index b1cf61b..982493c 100644 --- a/packages/sepal/src/url.js +++ b/packages/sepal/src/url.js @@ -87,10 +87,10 @@ function parse(input, base) { return { protocol, username: '', password: '', hostname: '', port: '', pathname: opaque[2], search: clean(opaque[3], QUERY_UNSAFE), hash: clean(opaque[4], HASH_UNSAFE), opaque: true }; } if (base === undefined) return null; - if (no_authority.has(base)) { + if (no_authority(base)) { // Nothing resolves against such a URL except a hash. if (!input.startsWith('#')) return null; - return { protocol: base.protocol, username: '', password: '', hostname: '', port: '', pathname: base.pathname, search: raw.get(base)?.search ?? '', hash: clean(input, HASH_UNSAFE), opaque: true }; + return { protocol: base.protocol, username: '', password: '', hostname: '', port: '', pathname: base.pathname, search: raw_search(base), hash: clean(input, HASH_UNSAFE), opaque: true }; } // Relative to the base: `//host/path`, `/path`, `path`, `?query`, `#hash`, or nothing. if (input.startsWith('//')) return parse(base.protocol + input, undefined); @@ -102,7 +102,7 @@ function parse(input, base) { return { ...parts, pathname: base.pathname, - search: search === undefined ? raw.get(base)?.search ?? base.search : clean(search, QUERY_UNSAFE), + search: search === undefined ? raw_search(base) : clean(search, QUERY_UNSAFE), hash: clean(hash, HASH_UNSAFE) }; } @@ -139,7 +139,7 @@ const parsed = new Map(); /** @param {string} input @param {string | URL | undefined} base */ function parse_cached(input, base) { - const base_key = base === undefined ? '' : base instanceof URL ? (no_authority.has(base) ? 'o' : 'u') + base.href : 's' + String(base); + const base_key = base === undefined ? '' : base instanceof URL ? (no_authority(base) ? 'o' : 'u') + base.href : 's' + String(base); // The base's length first, so that no input can make two pairs one key. const key = `${base_key.length}:${base_key}${input}`; let parts = parsed.get(key); @@ -152,6 +152,11 @@ function parse_cached(input, base) { return parts; } +/** The query of a URL as written, lone `?` included, for resolving against it. Set by the class. @type {(url: URL) => string} */ +let raw_search; +/** Whether a URL is of the `scheme:path` kind. Set by the class. @type {(url: URL) => boolean} */ +let no_authority; + export class URL { /** @param {string | URL} input @param {string | URL} [base] */ constructor(input, base) { @@ -165,20 +170,39 @@ export class URL { this.pathname = parts.pathname; this.#search = parts.search; this.#hash = parts.hash; - raw.set(this, { search: parts.search }); - if (parts.opaque) no_authority.add(this); - this.searchParams = new URLSearchParams(this.#search); - link.set(this.searchParams, (/** @type {string} */ query) => this.#set_search(query === '' ? '' : '?' + query)); + this.#opaque = parts.opaque === true; } - // With their `?` and `#`, which may be all there is. + // With their `?` and `#`, which may be all there is: what a URL resolved + // against this one keeps, lone `?` included. #search = ''; #hash = ''; + /** A `scheme:path` URL, with no host to print or to resolve against. */ + #opaque = false; + /** + * Made when it is first asked for. Routers and Vite's preload helper + * make URLs for their parts, many a navigation (SvelteKit: one per link + * on the page), and a `URLSearchParams` each was a third of that. + * @type {URLSearchParams | null} + */ + #params = null; + + static { + raw_search = (url) => url.#search; + no_authority = (url) => url.#opaque; + } + + get searchParams() { + if (this.#params === null) { + this.#params = new URLSearchParams(this.#search); + link.set(this.#params, (/** @type {string} */ query) => this.#set_search(query === '' ? '' : '?' + query)); + } + return this.#params; + } /** @param {string} search */ #set_search(search) { this.#search = search; - raw.set(this, { search }); } get search() { @@ -187,7 +211,7 @@ export class URL { set search(value) { value = String(value); this.#set_search(value === '' ? '' : clean(value.startsWith('?') ? value : '?' + value, QUERY_UNSAFE)); - reset.get(this.searchParams)?.(this.#search); + if (this.#params !== null) reset.get(this.#params)?.(this.#search); } get hash() { return this.#hash === '#' ? '' : this.#hash; @@ -206,7 +230,7 @@ export class URL { return SPECIAL.test(this.protocol) ? `${this.protocol}//${this.host}` : 'null'; } get href() { - if (no_authority.has(this)) return `${this.protocol}${this.pathname}${this.#search}${this.#hash}`; + if (this.#opaque) return `${this.protocol}${this.pathname}${this.#search}${this.#hash}`; const user = this.username === '' ? '' : this.username + (this.password === '' ? '' : ':' + this.password) + '@'; return `${this.protocol}//${user}${this.host}${this.pathname}${this.#search}${this.#hash}`; } @@ -214,8 +238,7 @@ export class URL { const parts = parse(String(value), undefined); if (parts === null) throw new TypeError(`Invalid URL: ${String(value)}`); const { search, hash, opaque, ...rest } = parts; - if (opaque) no_authority.add(this); - else no_authority.delete(this); + this.#opaque = opaque === true; Object.assign(this, rest); this.search = search; this.#hash = hash; @@ -246,11 +269,6 @@ export class URL { } } -/** URLs of the `scheme:path` kind, which have no host to print or to resolve against. @type {WeakSet} */ -const no_authority = new WeakSet(); - -/** The query of a URL as written, lone `?` included, for resolving against it. @type {WeakMap} */ -const raw = new WeakMap(); /** How a `searchParams` tells its URL that it changed, and the other way round. */ /** @type {WeakMap void>} */ diff --git a/packages/sepal/test/dom.test.js b/packages/sepal/test/dom.test.js index 8318d23..7a54364 100644 --- a/packages/sepal/test/dom.test.js +++ b/packages/sepal/test/dom.test.js @@ -25,6 +25,18 @@ assert.equal(run('document.body instanceof HTMLElement && !(document.body instan assert.equal(run(`document.querySelector('#count').tagName`), 'BUTTON'); assert.equal(run(`document.querySelectorAll('main > div [data-slot=button]').length`), 8); assert.equal(run(`document.getElementById('count').closest('main') === document.querySelector('main')`), true); +// A selector of one tag, attribute, id or class has a test of its own, which a +// walk of the page calls on every element. Each answers what the general +// matcher does, which `:not(:not(…))` goes through. +for (const selector of ['div', 'DIV', '[data-slot]', '#count', '.flex', 'button[data-slot]', 'main div']) { + const fast = run(`[...document.querySelectorAll(${JSON.stringify(selector)})].map((node) => node.node_id).join()`); + const general = selector.includes(' ') ? fast : run(`[...document.querySelectorAll(${JSON.stringify(`:not(:not(${selector}))`)})].map((node) => node.node_id).join()`); + assert.ok(fast.length > 0, `${selector} finds something`); + assert.equal(fast, general, selector); +} +assert.equal(run(`document.querySelector('[data-none]')`), null); +assert.equal(run(`document.body.matches('body') && !document.body.matches('[id]') && document.getElementById('count').matches('#count')`), true); + // A selector that ends in a tag tries only the elements of that tag. The // answers are the walk's (`*` always walks): document order, below the scope, // nothing detached or removed. @@ -221,6 +233,15 @@ assert.throws(() => run(`history.pushState(null, '', 'http://elsewhere.test/')`) // A link's `href` is where it leads from here, whatever was written in the attribute. run(`const link = document.createElement('a'); link.id = 'link'; link.setAttribute('href', '../up?q#h'); document.body.appendChild(link);`); assert.equal(run(`document.getElementById('link').href + ' ' + document.getElementById('link').getAttribute('href')`), 'http://app.localhost/up?q#h ../up?q#h'); +// Asked again, it answers from what is written now and from where the page is +// now: a changed attribute, or a navigation, gives a fresh answer. +run(`document.getElementById('link').setAttribute('href', 'next')`); +assert.equal(run(`document.getElementById('link').href`), 'http://app.localhost/next'); +run(`history.pushState(null, '', '/deep/page')`); +assert.equal(run(`document.getElementById('link').href`), 'http://app.localhost/deep/next'); +run(`history.back()`); +host.advance(1); +assert.equal(run(`location.pathname + ' ' + document.getElementById('link').href`), '/one http://app.localhost/next'); run(`document.getElementById('link').remove(); sessionStorage.setItem('k', 'v'); sessionStorage.other = 1`); assert.equal(run(`[sessionStorage.getItem('k'), sessionStorage.k, sessionStorage.getItem('other'), sessionStorage.length, sessionStorage.getItem('none')].join()`), 'v,v,1,2,'); assert.equal(run(`new TextDecoder().decode(new TextEncoder().encode('héllo'))`), 'héllo'); diff --git a/packages/sepal/test/url.test.js b/packages/sepal/test/url.test.js index 5364fc9..2331b94 100644 --- a/packages/sepal/test/url.test.js +++ b/packages/sepal/test/url.test.js @@ -88,5 +88,19 @@ for (const [Class, Params] of [[URL, URLSearchParams], [Ours, OurParams]]) { assert.equal(new Params([['k', 'v']]).get('k'), 'v'); assert.equal(Class.canParse('nope'), false); assert.equal(Class.canParse('/x', 'http://localhost'), true); + + // Ours makes `searchParams` when it is first asked for: whatever came + // before, it has to start from the query as it is then. + const later = new Class('http://localhost/?a=1'); + later.search = '?b=2'; + assert.equal(later.searchParams.get('b'), '2'); + const moved = new Class('http://localhost/'); + moved.href = 'http://localhost/x?c=3#h'; + assert.deepEqual([...moved.searchParams], [['c', '3']]); + moved.search = ''; + assert.equal(moved.searchParams.size, 0); + moved.searchParams.append('d', '4'); + assert.equal(moved.search, '?d=4'); + assert.ok(!Object.keys(moved).includes('searchParams'), 'searchParams is not an own property, as in Node'); } console.log(`url: ok (${compared} URLs compared with Node's)`);