jq79 0.7.10 → 0.7.12

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.
@@ -41,6 +41,7 @@ export type Effect = {
41
41
  adopted: Map<Set<Effect>, Unsubscribe> | null;
42
42
  read: Set<Set<Effect>> | null;
43
43
  };
44
+ export declare const $batch: <T>(fn: () => T) => T;
44
45
  export declare const ALSO_WAKEN_BY: unique symbol;
45
46
  export declare const OWNER: unique symbol;
46
47
  export declare const $reactive: <T extends Record<string, any>>(data: T) => ReactiveDeepData<T>;
@@ -12,4 +12,9 @@ export declare const parsePropsPattern: (pattern: string | undefined) => PropDec
12
12
  export declare const parseFactoryProps: (src: string) => PropDecl[] | null;
13
13
  export declare const transformFactoryScript: (src: string) => string | null;
14
14
  export declare const freeIdentifiers: (expr: string) => string[] | null;
15
+ export type Preload = {
16
+ spec: string;
17
+ kind: "component" | "page" | "fetch";
18
+ };
19
+ export declare const preloadSpecifiers: (src: string) => Preload[];
15
20
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jq79",
3
- "version": "0.7.10",
3
+ "version": "0.7.12",
4
4
  "description": "Mini reactive component library: single-file .html components, Svelte-style setup scripts, fine-grained proxy reactivity. No compiler, no bundler, no dependencies — works from any static host.",
5
5
  "keywords": [
6
6
  "reactive",
package/src/jq79.ts CHANGED
@@ -1,9 +1,9 @@
1
1
 
2
2
  import { $, $$, $create, sanitizeHTML, allowedHosts } from "./dom"
3
3
  import type { AllowUrl, QueryAll, QueryOne } from "./dom"
4
- import { $reactive, $toRaw, $computed, untracked, createEffectScope, ALSO_WAKEN_BY, OWNER } from "./reactive"
4
+ import { $reactive, $toRaw, $computed, $batch, untracked, createEffectScope, ALSO_WAKEN_BY, OWNER } from "./reactive"
5
5
  import type { ReactiveDeepData, EffectScope } from "./reactive"
6
- import { transformSetupScript, transformFactoryScript, parsePropsPattern, parseFactoryProps, type PropDecl } from "./transform"
6
+ import { transformSetupScript, transformFactoryScript, parsePropsPattern, parseFactoryProps, preloadSpecifiers, type PropDecl } from "./transform"
7
7
  import {
8
8
  COMPONENT_NAME_RE, COMPONENT_TAG_ATTR, CONTROL_ATTRS, EACH_PATTERN, EXPR_PARAMS, PRECOMPILED_PARAM, PRECOMPILED_QUEUE,
9
9
  componentTagName, functionText,
@@ -14,7 +14,7 @@ import {
14
14
 
15
15
  export { $, $$, $create } from "./dom"
16
16
  export type { QueryOne, QueryAll } from "./dom"
17
- export { $reactive, $toRaw, $computed } from "./reactive"
17
+ export { $reactive, $toRaw, $computed, $batch } from "./reactive"
18
18
  export type { Computed } from "./reactive"
19
19
 
20
20
  // the package version, substituted at build time (tsup/vitest `define`, read
@@ -1135,6 +1135,9 @@ const renderNestedComponent = (key: string, node: TemplateNode, scope: Record<st
1135
1135
  // marks a spread: the whole object's properties, not one binding
1136
1136
  const sources: Array<{ name?: string; expr: string }> = []
1137
1137
  let hasSpread = false
1138
+ // directives written on the tag whose names a prop could have (see
1139
+ // warnDirectiveProps) - allocated only when there is one
1140
+ let directiveNamed: string[] | undefined
1138
1141
  Object.entries(node.attrs).forEach(([attr, value]) => {
1139
1142
  // the parent's scope stamp is stamped on every template element, this tag
1140
1143
  // included - it's not a prop, and the child renders under its own scope
@@ -1147,7 +1150,10 @@ const renderNestedComponent = (key: string, node: TemplateNode, scope: Record<st
1147
1150
  sources.push({ expr: value })
1148
1151
  return
1149
1152
  }
1150
- if (isControlAttr(attr)) return
1153
+ if (isControlAttr(attr)) {
1154
+ if (DIRECTIVE_PROP_NAMES.has(attr)) (directiveNamed ??= []).push(attr.slice(1))
1155
+ return
1156
+ }
1151
1157
  if (attr.startsWith("@")) {
1152
1158
  events.push([attr, value])
1153
1159
  } else if (attr === ":model" || attr.startsWith(":model.")) {
@@ -1318,6 +1324,7 @@ const renderNestedComponent = (key: string, node: TemplateNode, scope: Record<st
1318
1324
  // on the next update
1319
1325
  const declared = declaredPropSet(instance.scripts)
1320
1326
  warnUndeclared(node, key, Object.keys(props), declared)
1327
+ if (directiveNamed) warnDirectiveProps(node, key, directiveNamed, declared)
1321
1328
  const seed = pickDeclared(untracked(resolveProps), declared)
1322
1329
  // mounting into a fragment attaches no shadow root of its own: a
1323
1330
  // shadow-rendered child keeps its <style> elements inline, next to the DOM
@@ -2374,6 +2381,8 @@ type EachPlan = {
2374
2381
  // can a row render anything into an effect scope of its own? Only then does
2375
2382
  // a keyed row need the OWNER mark that lets its re-run reach them
2376
2383
  nestsScopes: boolean
2384
+ // `:window="rowHeight"`: render only the rows in view (see openWindow)
2385
+ windowExpr: string | undefined
2377
2386
  }
2378
2387
 
2379
2388
  const eachPlans = new WeakMap<TemplateNode, EachPlan | null>()
@@ -2404,7 +2413,7 @@ const eachPlanOf = (node: TemplateNode): EachPlan | null => {
2404
2413
  const keyProp = keyExpr !== undefined && !keyIsItem && KEY_MEMBER.test(keyExpr) && keyExpr.startsWith(`${itemName}.`)
2405
2414
  ? keyExpr.slice(itemName.length + 1)
2406
2415
  : undefined
2407
- const { [":each"]: _each, [":key"]: _key, ...itemAttrs } = node.attrs
2416
+ const { [":each"]: _each, [":key"]: _key, [":window"]: windowExpr, ...itemAttrs } = node.attrs
2408
2417
  const itemNode: TemplateNode = { ...node, attrs: itemAttrs }
2409
2418
 
2410
2419
  // An entry that changed position needs its position-only bindings re-run -
@@ -2421,16 +2430,187 @@ const eachPlanOf = (node: TemplateNode): EachPlan | null => {
2421
2430
 
2422
2431
  const namesComponent = /^[A-Z]/.test(itemName) || (atName !== undefined && /^[A-Z]/.test(atName))
2423
2432
  const nestsScopes = keyExpr !== undefined && rendersScopes(itemNode)
2424
- const plan: EachPlan = { itemName, atName, listExpr, keyExpr, keyIsItem, keyProp, itemNode, readsPosition, namesComponent, nestsScopes }
2433
+ const plan: EachPlan = { itemName, atName, listExpr, keyExpr, keyIsItem, keyProp, itemNode, readsPosition, namesComponent, nestsScopes, windowExpr }
2425
2434
  eachPlans.set(node, plan)
2426
2435
  return plan
2427
2436
  }
2428
2437
 
2438
+ // :window - a :each that renders only the rows in its scroll container's
2439
+ // viewport, plus OVERSCAN on either side, between two spacers whose heights
2440
+ // stand in for the rows that are not there. Rows are a fixed height (the
2441
+ // attribute's value, in pixels), which is what makes index <-> offset plain
2442
+ // arithmetic and $scrollTo exact. See RECORD/2026-11-12.a-windowed-each.md
2443
+ //
2444
+ // The window lives in a private store the list effect reads, so a scroll is an
2445
+ // ordinary wake of that effect - the same keyed diff, over list[start..end)
2446
+ const OVERSCAN = 8
2447
+ const SCROLLABLE_RE = /^(auto|scroll|overlay)$/
2448
+
2449
+ // the nearest ancestor that scrolls vertically, or null for the page. Crosses
2450
+ // a shadow root to its host, which is where a mountShadow'd list scrolls
2451
+ const scrollParentOf = (from: Node | null): HTMLElement | null => {
2452
+ for (let node = from; node; node = node instanceof ShadowRoot ? node.host : node.parentNode) {
2453
+ if (!(node instanceof HTMLElement) || node === document.body || node === document.documentElement) continue
2454
+ if (SCROLLABLE_RE.test(getComputedStyle(node).overflowY)) return node
2455
+ }
2456
+ return null
2457
+ }
2458
+
2459
+ type ListWindow = {
2460
+ top: Element
2461
+ bottom: Element
2462
+ // the slice of a list this long to render, spacers sized to match
2463
+ range: (length: number) => [number, number]
2464
+ // the pass is done: connect to the scroll container once the list is in the
2465
+ // document (it is not, on the pass that builds it)
2466
+ settled: () => void
2467
+ }
2468
+
2469
+ type ScrollToOptions79 = { block?: "nearest" | "start" | "center" | "end" }
2470
+
2471
+ const openWindow = (
2472
+ itemNode: TemplateNode,
2473
+ windowExpr: string,
2474
+ scope: Record<string, any>,
2475
+ fx: EffectScope,
2476
+ entries: () => EachEntry[]
2477
+ ): ListWindow => {
2478
+ // the spacers are the rows' own tag, so they are valid wherever rows are (a
2479
+ // <tr> in a <tbody>, an <li> in a <ul>); a component row gets a <div>
2480
+ const spacer = () => {
2481
+ const el = itemNode.component !== undefined || itemNode.tag.includes("-") ? document.createElement("div") : createFor(itemNode)
2482
+ el.setAttribute("aria-hidden", "true")
2483
+ el.setAttribute("style", "height: 0px; margin: 0; padding: 0; border: 0; list-style: none; visibility: hidden")
2484
+ return el
2485
+ }
2486
+ const top = spacer()
2487
+ const bottom = spacer()
2488
+ // count -1: not measured yet - a screenful of the window's height is assumed
2489
+ const view = $reactive({ start: 0, count: -1 })
2490
+ let rowHeight = 0
2491
+ let length = 0
2492
+ let scroller: HTMLElement | null = null
2493
+ let connected = false
2494
+ let frame = 0
2495
+ let observer: ResizeObserver | null = null
2496
+ let holder: Element | null = null
2497
+
2498
+ const rowsFor = (viewport: number) => Math.ceil(viewport / rowHeight) + 1 + 2 * OVERSCAN
2499
+ const setWindow = (start: number, count: number) => {
2500
+ start = Math.max(0, Math.min(start, Math.max(0, length - count)))
2501
+ if (view.start !== start || view.count !== count) $batch(() => { view.start = start; view.count = count })
2502
+ }
2503
+
2504
+ // where the rows begin and the viewport is, in the container's content
2505
+ // coordinates (the page's, when the page scrolls)
2506
+ const metrics = () => {
2507
+ const at = top.getBoundingClientRect().top
2508
+ if (scroller) {
2509
+ const box = scroller.getBoundingClientRect()
2510
+ const scrollTop = scroller.scrollTop
2511
+ return { listTop: at - box.top - scroller.clientTop + scrollTop, scrollTop, height: scroller.clientHeight || window.innerHeight }
2512
+ }
2513
+ return { listTop: at + window.scrollY, scrollTop: window.scrollY, height: window.innerHeight }
2514
+ }
2515
+
2516
+ const measure = () => {
2517
+ frame = 0
2518
+ if (!(rowHeight > 0) || !top.isConnected) return
2519
+ const { listTop, scrollTop, height } = metrics()
2520
+ setWindow(Math.floor((scrollTop - listTop) / rowHeight) - OVERSCAN, rowsFor(height))
2521
+ }
2522
+ const schedule = () => {
2523
+ if (frame) return
2524
+ frame = typeof requestAnimationFrame === "function" ? requestAnimationFrame(measure) : (setTimeout(measure, 16) as any)
2525
+ }
2526
+
2527
+ // scrolls the container so row `index` is in view and renders it before
2528
+ // returning - an aria-activedescendant has to point at a row that exists
2529
+ const scrollTo = (index: number, { block = "nearest" }: ScrollToOptions79 = {}): Node | null => {
2530
+ connect()
2531
+ if (rowHeight > 0 && top.isConnected) {
2532
+ const { listTop, scrollTop, height } = metrics()
2533
+ const rowTop = listTop + index * rowHeight
2534
+ const rowBottom = rowTop + rowHeight
2535
+ let next = scrollTop
2536
+ if (block === "start") next = rowTop
2537
+ else if (block === "end") next = rowBottom - height
2538
+ else if (block === "center") next = rowTop - (height - rowHeight) / 2
2539
+ else if (rowTop < scrollTop) next = rowTop
2540
+ else if (rowBottom > scrollTop + height) next = rowBottom - height
2541
+ if (next !== scrollTop) {
2542
+ if (scroller) scroller.scrollTop = next
2543
+ else window.scrollTo(window.scrollX, next)
2544
+ }
2545
+ measure()
2546
+ }
2547
+ // whatever layout said (or could not say, before there is one), the row
2548
+ // is in the window when this returns
2549
+ const count = view.count > 0 ? view.count : rowsFor(window.innerHeight || 800)
2550
+ if (index < view.start || index >= view.start + count) setWindow(index - OVERSCAN, count)
2551
+ const entry = entries().find(row => row.scope.$index === index)
2552
+ return entry ? entry.range.first : null
2553
+ }
2554
+
2555
+ const connect = () => {
2556
+ if (connected || !top.isConnected) return
2557
+ connected = true
2558
+ holder = top.parentElement
2559
+ scroller = scrollParentOf(top.parentNode)
2560
+ ;(scroller ?? window).addEventListener("scroll", schedule, { passive: true })
2561
+ window.addEventListener("resize", schedule)
2562
+ if (scroller && typeof ResizeObserver === "function") {
2563
+ observer = new ResizeObserver(schedule)
2564
+ observer.observe(scroller)
2565
+ }
2566
+ if (holder) Object.defineProperty(holder, "$scrollTo", { value: scrollTo, configurable: true, writable: true })
2567
+ measure()
2568
+ }
2569
+
2570
+ fx.onDispose(() => {
2571
+ if (frame) (typeof cancelAnimationFrame === "function" ? cancelAnimationFrame : clearTimeout)(frame)
2572
+ if (!connected) return
2573
+ ;(scroller ?? window).removeEventListener("scroll", schedule)
2574
+ window.removeEventListener("resize", schedule)
2575
+ observer?.disconnect()
2576
+ if (holder && (holder as any).$scrollTo === scrollTo) delete (holder as any).$scrollTo
2577
+ })
2578
+
2579
+ let queued = false
2580
+ return {
2581
+ top,
2582
+ bottom,
2583
+ range: listLength => {
2584
+ length = listLength
2585
+ const height = Number(evalExpr(windowExpr, scope))
2586
+ rowHeight = height > 0 ? height : 0
2587
+ if (!rowHeight) {
2588
+ ;(top as HTMLElement).style.height = (bottom as HTMLElement).style.height = "0px"
2589
+ return [0, listLength]
2590
+ }
2591
+ const count = view.count > 0 ? view.count : rowsFor(window.innerHeight || 800)
2592
+ const start = Math.max(0, Math.min(view.start, listLength - count))
2593
+ const end = Math.min(listLength, start + count)
2594
+ ;(top as HTMLElement).style.height = `${start * rowHeight}px`
2595
+ ;(bottom as HTMLElement).style.height = `${(listLength - end) * rowHeight}px`
2596
+ return [start, end]
2597
+ },
2598
+ settled: () => {
2599
+ if (connected || queued) return
2600
+ queued = true
2601
+ queueMicrotask(() => {
2602
+ queued = false
2603
+ connect()
2604
+ })
2605
+ },
2606
+ }
2607
+ }
2608
+
2429
2609
  const renderEach = (node: TemplateNode, scope: Record<string, any>, fx: EffectScope, shadow: boolean): Node => {
2430
2610
  const plan = eachPlanOf(node)
2431
2611
  if (!plan) return document.createComment(`invalid :each expression "${node.attrs[":each"]}"`)
2432
2612
 
2433
- const { itemName, atName, listExpr, keyExpr, keyIsItem, keyProp, itemNode, readsPosition, namesComponent, nestsScopes } = plan
2613
+ const { itemName, atName, listExpr, keyExpr, keyIsItem, keyProp, itemNode, readsPosition, namesComponent, nestsScopes, windowExpr } = plan
2434
2614
 
2435
2615
  // `:key="row.id"`, or the loop variable itself, is what a key almost always
2436
2616
  // is - and reading one needs neither a scope to resolve names against nor a
@@ -2445,6 +2625,8 @@ const renderEach = (node: TemplateNode, scope: Record<string, any>, fx: EffectSc
2445
2625
  const anchor = document.createComment("each")
2446
2626
  const wrapper = document.createDocumentFragment()
2447
2627
  wrapper.appendChild(anchor)
2628
+ const win = windowExpr === undefined ? null : openWindow(itemNode, windowExpr, scope, fx, () => entries)
2629
+ if (win) wrapper.append(win.top, win.bottom)
2448
2630
 
2449
2631
  // :if on the same element is not per-item filtering, and rendering
2450
2632
  // everything in silence reads like a broken filter - say it out loud
@@ -2472,6 +2654,9 @@ const renderEach = (node: TemplateNode, scope: Record<string, any>, fx: EffectSc
2472
2654
  const array = Array.isArray(list)
2473
2655
  const keys: string[] | null = array ? null : isPlainObject(list) ? Object.keys(list) : []
2474
2656
  const length = array ? list.length : keys!.length
2657
+ // a windowed list walks only the rows in view; the spacers stand in for
2658
+ // the rest, so `index` stays the row's real position
2659
+ const [from, to] = win ? win.range(length) : [0, length]
2475
2660
  // buckets rather than a key->entry map: duplicate keys (a user error, but
2476
2661
  // one that must degrade instead of corrupt) consume entries in order of
2477
2662
  // appearance, so no entry is ever matched twice - matching one twice is
@@ -2504,7 +2689,7 @@ const renderEach = (node: TemplateNode, scope: Record<string, any>, fx: EffectSc
2504
2689
  // scope of its own, below
2505
2690
  let scratch: Record<string, any> | undefined
2506
2691
 
2507
- for (let index = 0; index < length; index++) {
2692
+ for (let index = from; index < to; index++) {
2508
2693
  const at = array ? index : keys![index]
2509
2694
  const item = array ? list[index] : list[at]
2510
2695
 
@@ -2607,7 +2792,7 @@ const renderEach = (node: TemplateNode, scope: Record<string, any>, fx: EffectSc
2607
2792
  removeRuns(contiguousRuns(entries, entry => entry.dead === true))
2608
2793
  }
2609
2794
 
2610
- let prevNode: Node = anchor
2795
+ let prevNode: Node = win ? win.top : anchor
2611
2796
  // rows already in order relative to each other stay where they are; the
2612
2797
  // rest are placed after the row that precedes them in the new order,
2613
2798
  // which is where the pass has just left `prevNode`
@@ -2631,6 +2816,7 @@ const renderEach = (node: TemplateNode, scope: Record<string, any>, fx: EffectSc
2631
2816
  } finally {
2632
2817
  closeRenderPass(pass)
2633
2818
  }
2819
+ win?.settled()
2634
2820
  })
2635
2821
  // the rows live inside whatever holds this list, as a :if branch does (see
2636
2822
  // renderConditional): torn down with it, not left subscribed to the store
@@ -3029,27 +3215,81 @@ const stampScope = (nodes: (TemplateNode | string)[], scope: string) => {
3029
3215
 
3030
3216
  // the scope attribute goes on the selector's last compound - the element the
3031
3217
  // rule actually targets - but *before* a pseudo-element, which must stay last
3032
- // (".a::before" scopes to ".a[data-jq79='x']::before", not "::before[...]")
3033
- const scopeSelector = (selectorText: string, scope: string): string =>
3034
- selectorText
3035
- .split(",")
3036
- .map(part => {
3037
- const selector = part.trim()
3038
- const pseudoAt = selector.indexOf("::")
3039
- const target = pseudoAt === -1 ? selector : selector.slice(0, pseudoAt)
3040
- const pseudoElement = pseudoAt === -1 ? "" : selector.slice(pseudoAt)
3041
- return `${target}[${SCOPE_ATTR}="${scope}"]${pseudoElement}`
3042
- })
3043
- .join(", ")
3044
-
3045
- // CSSStyleRule is scoped in place; CSSGroupingRule (@media, @supports,
3046
- // @container) is recursed into; everything else - notably @keyframes, whose
3047
- // "selectors" are percentages - is left alone
3048
- const scopeRules = (rules: CSSRuleList, scope: string) => {
3049
- Array.from(rules).forEach(rule => {
3050
- if (rule instanceof CSSStyleRule) rule.selectorText = scopeSelector(rule.selectorText, scope)
3051
- else if (rule instanceof CSSGroupingRule) scopeRules(rule.cssRules, scope)
3218
+ // (".a::before" scopes to ".a[data-jq79='x']::before", not "::before[...]").
3219
+ // This reads the author's text, not an engine's serialisation, so the CSS2
3220
+ // single-colon pseudo-elements are recognised by name: nothing has rewritten
3221
+ // ":before" to "::before" for us (see scopeCss)
3222
+ const LEGACY_PSEUDO_ELEMENT_RE = /^:(before|after|first-line|first-letter)(?![\w-])/i
3223
+
3224
+ // walks `text` at nesting depth 0 - outside (), [], strings and escapes -
3225
+ // calling `at(i)` on each such index; `at` returning true stops the walk
3226
+ const atTopLevel = (text: string, at: (i: number) => boolean | void) => {
3227
+ let depth = 0
3228
+ for (let i = 0; i < text.length; i++) {
3229
+ const char = text[i]
3230
+ if (char === "\\") i++
3231
+ else if (char === '"' || char === "'") {
3232
+ i++
3233
+ while (i < text.length && text[i] !== char) i += text[i] === "\\" ? 2 : 1
3234
+ } else if (char === "(" || char === "[") depth++
3235
+ else if (char === ")" || char === "]") depth--
3236
+ else if (depth === 0 && at(i)) return
3237
+ }
3238
+ }
3239
+
3240
+ const scopeSelector = (selector: string, scope: string): string => {
3241
+ let pseudoAt = selector.length
3242
+ atTopLevel(selector, i => {
3243
+ if (selector[i] !== ":") return false
3244
+ if (selector[i + 1] !== ":" && !LEGACY_PSEUDO_ELEMENT_RE.test(selector.slice(i))) return false
3245
+ pseudoAt = i
3246
+ return true
3247
+ })
3248
+ return `${selector.slice(0, pseudoAt)}[${SCOPE_ATTR}="${scope}"]${selector.slice(pseudoAt)}`
3249
+ }
3250
+
3251
+ // a selector list is split on its top-level commas only: `.a:is(.b, .c)` is
3252
+ // one selector. A comment in a selector is removed - CSS reads it as nothing,
3253
+ // so `.a/**/.b` is `.a.b` - since the attribute must never land inside one
3254
+ const scopeSelectorList = (prelude: string, scope: string): string => {
3255
+ const text = stripCssComments(prelude)
3256
+ const lead = text.match(/^\s*/)![0]
3257
+ const trail = text.match(/\s*$/)![0]
3258
+ const body = text.slice(lead.length, text.length - trail.length)
3259
+ if (!body) return prelude
3260
+ const parts: string[] = []
3261
+ let from = 0
3262
+ atTopLevel(body, i => {
3263
+ if (body[i] === ",") {
3264
+ parts.push(body.slice(from, i))
3265
+ from = i + 1
3266
+ }
3052
3267
  })
3268
+ parts.push(body.slice(from))
3269
+ return lead + parts.map(part => part.trim() && scopeSelector(part.trim(), scope)).join(", ") + trail
3270
+ }
3271
+
3272
+ const stripCssComments = (text: string): string => {
3273
+ let out = ""
3274
+ for (let i = 0; i < text.length; ) {
3275
+ const char = text[i]
3276
+ if (char === "/" && text[i + 1] === "*") {
3277
+ const end = text.indexOf("*/", i + 2)
3278
+ i = end === -1 ? text.length : end + 2
3279
+ } else if (char === '"' || char === "'") {
3280
+ let j = i + 1
3281
+ while (j < text.length && text[j] !== char) j += text[j] === "\\" ? 2 : 1
3282
+ out += text.slice(i, j + 1)
3283
+ i = j + 1
3284
+ } else if (char === "\\") {
3285
+ out += text.slice(i, i + 2)
3286
+ i += 2
3287
+ } else {
3288
+ out += char
3289
+ i++
3290
+ }
3291
+ }
3292
+ return out
3053
3293
  }
3054
3294
 
3055
3295
  // A component's name in a selector - `Circle { color: red }` - names the box
@@ -3146,18 +3386,66 @@ const renameComponentSelectors = (css: string): string => {
3146
3386
  return out
3147
3387
  }
3148
3388
 
3149
- // the CSS parser is the browser's own (no dependency, no hand-rolled parser).
3150
- // Note browsers *silently drop* rules whose selector they can't parse, which
3151
- // is what Vue's :deep()/::v-deep/>>> escape hatches are - unsupported here,
3152
- // and warned about rather than left to vanish
3389
+ // Scoping rewrites selectors and nothing else, on the SOURCE. It used to parse
3390
+ // the block into a CSSStyleSheet and write it back from rule.cssText, which
3391
+ // round-trips every declaration through the engine's serialiser - and Chromium
3392
+ // serialises `border: var(--w) solid red; border-bottom-width: 0` as a row of
3393
+ // empty longhands (`border-top-style: ;` …), so the border vanished once
3394
+ // scoped. See RECORD/2026-11-12.scope-the-source-not-the-cssom.md
3395
+ //
3396
+ // The scan tracks strings, comments and nesting the way renameComponentSelectors
3397
+ // does. In rule position (top level, or inside @media and the other at-rules
3398
+ // that hold rules) a prelude that is not an at-rule is a selector list and gets
3399
+ // scoped; a declaration block is copied whole, nested blocks included - CSS
3400
+ // nesting is relative to the parent, which is already scoped. @keyframes holds
3401
+ // frames, not rules, so it is copied whole too.
3402
+ //
3403
+ // Vue's :deep()/::v-deep/>>> escape hatches are not CSS: the browser drops a
3404
+ // rule it can't parse when the block is injected, so they are warned about
3405
+ // rather than left to vanish
3153
3406
  const scopeCss = (css: string, scope: string): string => {
3154
3407
  if (/:deep\(|::v-deep|>>>/.test(css)) {
3155
3408
  console.warn("jq79: :deep()/::v-deep/>>> are not supported in <style scoped>; the rule will be dropped by the browser")
3156
3409
  }
3157
- const sheet = new CSSStyleSheet()
3158
- sheet.replaceSync(css)
3159
- scopeRules(sheet.cssRules, scope)
3160
- return Array.from(sheet.cssRules).map(rule => rule.cssText).join("\n")
3410
+ let out = ""
3411
+ let prelude = "" // rule position: the text since the last delimiter
3412
+ const stack: boolean[] = [] // true = the block holds rules, not declarations
3413
+ const holdsRules = () => stack.length === 0 || stack[stack.length - 1]
3414
+
3415
+ for (let i = 0; i < css.length; ) {
3416
+ const char = css[i]
3417
+ let token = char
3418
+ if (char === "/" && css[i + 1] === "*") {
3419
+ const end = css.indexOf("*/", i + 2)
3420
+ token = css.slice(i, end === -1 ? css.length : end + 2)
3421
+ } else if (char === '"' || char === "'") {
3422
+ let j = i + 1
3423
+ while (j < css.length && css[j] !== char) j += css[j] === "\\" ? 2 : 1
3424
+ token = css.slice(i, j + 1)
3425
+ } else if (char === "\\") {
3426
+ token = css.slice(i, i + 2)
3427
+ }
3428
+ i += token.length
3429
+
3430
+ if (!holdsRules()) {
3431
+ out += token
3432
+ if (token === "{") stack.push(false)
3433
+ else if (token === "}") stack.pop()
3434
+ } else if (token === "{") {
3435
+ const bare = stripCssComments(prelude)
3436
+ const atRule = AT_RULE_RE.test(bare)
3437
+ out += (atRule ? prelude : scopeSelectorList(prelude, scope)) + "{"
3438
+ stack.push(atRule && NESTED_AT_RULE_RE.test(bare))
3439
+ prelude = ""
3440
+ } else if (token === "}" || token === ";") {
3441
+ out += prelude + token
3442
+ prelude = ""
3443
+ if (token === "}") stack.pop()
3444
+ } else {
3445
+ prelude += token
3446
+ }
3447
+ }
3448
+ return out + prelude
3161
3449
  }
3162
3450
 
3163
3451
  // converts a string of HTML into an AST representation of the component:
@@ -3332,8 +3620,10 @@ const componentPartsFrom = (elements: Element[], hashSource: string): ComponentP
3332
3620
  // loads .html URLs as components, delegating anything else to native import().
3333
3621
  // Goes to fetchComponent rather than Component79.fetch because an import wants
3334
3622
  // the component, not the chainable handle the public entry point returns
3623
+ const HTML_URL_RE = /\.html?([?#]|$)/
3624
+
3335
3625
  const importResource = (url: string): Promise<any> =>
3336
- /\.html?([?#]|$)/.test(url) ? fetchComponent(url) : import(url)
3626
+ HTML_URL_RE.test(url) ? fetchComponent(url) : import(url)
3337
3627
 
3338
3628
  // a relative specifier means "next to the file that wrote it", so it is
3339
3629
  // resolved against the component's own URL before importResource sees it -
@@ -3682,6 +3972,26 @@ const warnUndeclared = (node: TemplateNode, name: string, written: string[], dec
3682
3972
  })
3683
3973
  }
3684
3974
 
3975
+ // `:checked` on a component tag is the directive, not a prop: the prop
3976
+ // collection skips every control attribute, so a child that declares
3977
+ // `checked` gets nothing and says nothing. Said here, once per usage site, for
3978
+ // the case where the author can only have meant the prop - the child declares
3979
+ // one of that name. See RECORD/2026-11-12.a-prop-named-like-a-directive.md
3980
+ const DIRECTIVE_PROP_NAMES = new Set([":value", ":checked", ":selected", ":text", ":html", ":class"])
3981
+ const directivePropsWarned = new WeakSet<TemplateNode>()
3982
+
3983
+ const warnDirectiveProps = (node: TemplateNode, name: string, written: string[], declared: Set<string> | null) => {
3984
+ if (declared === null || directivePropsWarned.has(node)) return
3985
+ const clashing = written.filter(prop => declared.has(prop))
3986
+ if (!clashing.length) return
3987
+ directivePropsWarned.add(node)
3988
+ clashing.forEach(prop => console.warn(
3989
+ `jq79: :${prop} on <${name}> is a directive, not a prop - <${name}> never receives its "${prop}". ` +
3990
+ `Rename the prop (${clashing.map(p => `:${p}`).join(", ")} are reserved on a component tag), ` +
3991
+ `or use :model for a value that goes both ways`
3992
+ ))
3993
+ }
3994
+
3685
3995
  // the sibling components this one resolves by name, or null when there are
3686
3996
  // none left to resolve. They go on the store's *prototype* rather than in it:
3687
3997
  // the component-key scan walks the chain, so <Row> resolves; they stay out of
@@ -3995,6 +4305,74 @@ const fetchComponent = async (rawUrl: string): Promise<Component79> => {
3995
4305
  return new Component79(text, { filename: url })
3996
4306
  }
3997
4307
 
4308
+ // ---------------------------------------------------------------------------
4309
+ // preloading (RECORD/2026-11-05.a-preload-scanner.md)
4310
+ //
4311
+ // Before a definition's scripts first run, every download their top level is
4312
+ // sure to ask for starts at once - so `await import("./a.html")` on one line
4313
+ // and `await import("./b.html")` on the next are one round trip, not two, and
4314
+ // still run in that order. Each specifier resolves as its call would, and
4315
+ // lands where that call will look: a component in the cache, a module in the
4316
+ // browser's module map (modulepreload fetches and parses, never evaluates)
4317
+ // ---------------------------------------------------------------------------
4318
+
4319
+ // the script blocks already preloaded: one scan per definition, however many
4320
+ // instances render it
4321
+ const preloadedScripts = new WeakSet<TagBlock>()
4322
+ const preloadedModules = new Set<string>()
4323
+
4324
+ const preloadModule = (url: string) => {
4325
+ if (preloadedModules.has(url)) return
4326
+ preloadedModules.add(url)
4327
+ const link = document.createElement("link")
4328
+ link.rel = "modulepreload"
4329
+ const nonce = pageNonce()
4330
+ if (nonce) link.setAttribute("nonce", nonce)
4331
+ link.href = url
4332
+ document.head.append(link)
4333
+ }
4334
+
4335
+ // a script block's body, quote-aware in its attributes, for a file that is
4336
+ // text and not yet a component: what a preloaded child is when it arrives
4337
+ const SCRIPT_BODY_RE = /<script\b(?:"[^"]*"|'[^']*'|[^>"'])*>([\s\S]*?)<\/script\s*>/gi
4338
+ // the files whose scripts were read for preloads as they arrived: each once,
4339
+ // so two components importing each other end there
4340
+ const preloadedFiles = new Set<string>()
4341
+
4342
+ // one script's preloads, resolved as its calls will be. A component it
4343
+ // preloads is read in turn when it arrives - its imports start before it
4344
+ // renders, and so on down - against its own URL, and with no modules map:
4345
+ // a fetched component has none
4346
+ const preloadSource = (source: string, filename: string | undefined, modules: Record<string, any> | undefined) => {
4347
+ for (const { spec, kind } of preloadSpecifiers(source)) {
4348
+ // the bundle already holds it
4349
+ if (kind === "component" && modules && spec in modules) continue
4350
+ // fetch() goes to the cache as written; the imports resolve first, as
4351
+ // importResource is handed them
4352
+ const url = resolveBare(kind === "fetch" ? spec : resolveSpecifier(spec, kind === "component" ? filename : undefined))
4353
+ if (kind === "fetch" || HTML_URL_RE.test(url)) {
4354
+ // with the cache off there is nowhere to keep it, and the real request
4355
+ // would download it again. A failure is the real request's to report
4356
+ if (componentCache) componentSource(url).then(text => preloadFile(text, url), () => {})
4357
+ } else if (RESOLVABLE_SPECIFIER_RE.test(url)) preloadModule(url)
4358
+ }
4359
+ }
4360
+
4361
+ const preloadFile = (text: string, url: string) => {
4362
+ const key = cacheKey(url)
4363
+ if (preloadedFiles.has(key)) return
4364
+ preloadedFiles.add(key)
4365
+ for (const [, body] of text.matchAll(SCRIPT_BODY_RE)) preloadSource(body, url, undefined)
4366
+ }
4367
+
4368
+ const preloadScripts = (scripts: TagBlock[], filename: string | undefined, modules: Record<string, any> | undefined) => {
4369
+ for (const script of scripts) {
4370
+ if (preloadedScripts.has(script)) continue
4371
+ preloadedScripts.add(script)
4372
+ preloadSource(script.content, filename, modules)
4373
+ }
4374
+ }
4375
+
3998
4376
  // ---------------------------------------------------------------------------
3999
4377
  // safe eval's worker
4000
4378
  //
@@ -4339,13 +4717,14 @@ export class Component79 {
4339
4717
  //
4340
4718
  // Returns the setting as it stands after the call
4341
4719
  static cache(enabled?: boolean): boolean {
4342
- if (enabled === false) componentCache = null
4720
+ if (enabled === false) { componentCache = null; preloadedFiles.clear() }
4343
4721
  else if (enabled === true) componentCache ??= new Map()
4344
4722
  return !!componentCache
4345
4723
  }
4346
4724
 
4347
4725
  static clearCache(): void {
4348
4726
  componentCache?.clear()
4727
+ preloadedFiles.clear()
4349
4728
  }
4350
4729
 
4351
4730
  static fetch(url: string): PendingComponent79 {
@@ -4614,6 +4993,7 @@ export class Component79 {
4614
4993
  const gates: Promise<void>[] = []
4615
4994
  let allSync = true
4616
4995
 
4996
+ preloadScripts(this.scripts, this.filename, this.modules)
4617
4997
  this.scripts.forEach((script, index) => {
4618
4998
  let resolveGate!: () => void
4619
4999
  gates.push(new Promise<void>(resolve => { resolveGate = resolve }))
@@ -5127,7 +5507,7 @@ let settleQueued = false
5127
5507
  // declaration) shadows them. Their names, in this order, are also
5128
5508
  // SETUP_HELPER_NAMES (source.ts) - what precompile compiles scripts with, so
5129
5509
  // the two change together
5130
- const SETUP_HELPERS: Record<string, any> = { $, $$, $create, $reactive, $toRaw, Component79, C79: Component79 }
5510
+ const SETUP_HELPERS: Record<string, any> = { $, $$, $create, $reactive, $toRaw, $batch, Component79, C79: Component79 }
5131
5511
 
5132
5512
  // the hot-reload handshake. jq79/dev serves a classic script that sets the flag
5133
5513
  // below; classic scripts run before deferred module ones, so the flag is always
package/src/precompile.ts CHANGED
@@ -81,6 +81,7 @@ const collectExpressions = (nodes: (TemplateNode | string)[], known: string[], a
81
81
  const match = attrs[":each"].match(EACH_PATTERN)
82
82
  if (match) add(match[3])
83
83
  if (":key" in attrs) add(attrs[":key"])
84
+ if (":window" in attrs) add(attrs[":window"])
84
85
  }
85
86
  if (":with" in attrs) add(attrs[":with"])
86
87
  // bindSlotProps: a :slot binder's defaults, on a component tag or its <template>