@tarve/svelte 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/render.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { Code, Column, Markdown, memo, Row, Scroll, Text, TitleBar, View } from "@tarve/core";
1
+ import { Code, Column, Markdown, memo, Row, Scroll, Text, TitleBar, tw, View } from "@tarve/core";
2
2
  import { jsx, type Child, type VNode } from "@tarve/core/jsx-runtime";
3
- import { elementStyle, isComponentClass } from "./css";
4
- import { camelCase, COMMENT_NODE, documentInstance, ELEMENT_NODE, scheduleIntersections, TDataTransfer, TEvent, TEXT_NODE, type TCharacterData, type TElement, type THTMLMediaElement, type TNode } from "./dom";
3
+ import { elementStyle, isComponentClass, usesPreflight } from "./css";
4
+ import { camelCase, COMMENT_NODE, documentInstance, ELEMENT_NODE, elementToClient, layout, scheduleIntersections, TDataTransfer, TEvent, TEXT_NODE, windowInstance, type TCharacterData, type TElement, type THTMLMediaElement, type TNode } from "./dom";
5
5
  import { generatedContent, type GeneratedContent } from "./css";
6
6
  import { applyValue, editableModel, fireInput } from "./editable";
7
7
 
@@ -19,8 +19,10 @@ const TEXT_CONTAINERS = new Set(["p", "span", "h1", "h2", "h3", "h4", "h5", "h6"
19
19
  /** Intrinsics the reconciler expands; any other tag (section, header, nav…) is a block `div`. */
20
20
  const KNOWN = new Set(["div", "audio", "p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "img", "form", "audio", "canvas", "input", "textarea", "button", "a", "svg", "label", "select", "progress", "hr",
21
21
  "pre", "blockquote", "meter", "fieldset", "legend", "ul", "ol", "li", "dl", "dt", "dd", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "details", "summary", ...INLINE]);
22
- const BOOLEAN = new Set(["disabled", "checked", "selected", "required", "readonly", "multiple", "hidden", "open", "autofocus", "draggable", "drag-region", "focusable"]);
22
+ const BOOLEAN = new Set(["disabled", "checked", "selected", "required", "readonly", "multiple", "hidden", "open", "autofocus", "draggable", "drag-region", "focusable", "follow-tail"]);
23
23
  const SKIPPED = new Set(["class", "style", "role", "xmlns"]);
24
+ /** Elements the pointer is over (per native's reports): kept across rebuilds of their handlers. */
25
+ const pointerInside = new WeakSet<TElement>();
24
26
  const HOVER = ["mouseenter", "mouseleave", "mouseover", "mouseout", "pointerenter", "pointerleave", "pointerover", "pointerout"];
25
27
  const SCOPE_CLASS = /^svelte-[a-z0-9]+$/;
26
28
 
@@ -110,10 +112,16 @@ function props(element: TElement, tag: string): Record<string, any> {
110
112
  }
111
113
  const classes = (element._attributes.get("class") ?? "").split(/\s+/).filter(Boolean);
112
114
  const style = elementStyle(element, classes);
113
- if (style) out.style = style;
115
+ // CSS: `display: flex` lays out in a row unless flex-direction says otherwise, whatever the element.
116
+ if (style) out.style = inheritValues(element, style);
117
+ if (out.style && "inline" in out.style) out.style = inlineLevel(element, out.style);
114
118
  // Classes the component's own CSS selects are not Tailwind utilities (`.filter`, `.container`).
115
119
  const plain = classes.filter(name => !SCOPE_CLASS.test(name) && !isComponentClass(name));
116
120
  if (plain.length) out.class = plain.join(" ");
121
+ // Tailwind's preflight: headings and paragraphs inherit their font and lose their margins.
122
+ if (PREFLIGHT_TEXT.has(tag) && usesPreflight()) out.userAgentStyles = false;
123
+ // CSS: `display: flex` lays out in a row unless flex-direction says otherwise, whatever the element.
124
+ if (displayOf(out) === "flex" && out.style?.direction === undefined && !/(^|\s)flex-(row|col)/.test(out.class ?? "")) out.style = { ...out.style, direction: "row" };
117
125
  if (out.hidden) { out.style = { ...out.style, display: "none" }; delete out.hidden; }
118
126
  return out;
119
127
  }
@@ -184,8 +192,9 @@ function addEvents(element: TElement, tag: string, out: Record<string, any>): vo
184
192
  if (element._resizeObservers?.size || element._measured) out.onSize = () => {};
185
193
  if (element.hasAttribute("draggable") || wanted.has("drop") || wanted.has("dragover") || wanted.has("dragenter")) addDragAndDrop(element, wanted, out);
186
194
  if (wanted.has("scroll") || element._scrollTracked) {
187
- out.onScroll = (offset: number) => {
188
- element.scrollTop = offset;
195
+ out.onScroll = (offset: number, max: number) => {
196
+ element._scrollTop = offset;
197
+ element._scrollMaxY = max;
189
198
  scheduleIntersections();
190
199
  if (wanted.has("scroll")) fire(element, "scroll", { bubbles: false });
191
200
  };
@@ -203,14 +212,30 @@ function addEvents(element: TElement, tag: string, out: Record<string, any>): vo
203
212
  if (detail === 2) fireAll(element, ["dblclick"], wanted, init);
204
213
  };
205
214
  }
206
- if (wanted.has("mousemove") || wanted.has("pointermove")) {
215
+ const moves = wanted.has("mousemove") || wanted.has("pointermove");
216
+ const hovers = HOVER.some(type => wanted.has(type));
217
+ if (moves || hovers) {
218
+ // Native reports the pointer over every element under it that asks (`pointerMove` with the point
219
+ // inside its box, `pointerLeave` when it goes), as the DOM sends enter/leave to each element
220
+ // on the path. Its `hover` names only the topmost interactive node: a plain div under a
221
+ // full-window button (a player's click-to-pause layer) would never see the pointer leave.
222
+ if (moves) { element._measure(); out.onSize ??= () => {}; }
207
223
  out.onPointerMove = (point: { x: number; y: number }) => {
208
- setPointerPosition(point.x, point.y);
224
+ if (!pointerInside.has(element)) {
225
+ pointerInside.add(element);
226
+ if (hovers) fireAll(element, ["pointerover", "pointerenter", "mouseover", "mouseenter"], wanted);
227
+ }
228
+ if (!moves) return;
229
+ // The point is inside this element's box; clientX/clientY are the viewport's.
230
+ const client = elementToClient(element, point.x, point.y);
231
+ if (!client) return;
232
+ setPointerPosition(client.x, client.y);
209
233
  fireAll(element, ["pointermove", "mousemove"], wanted, pointer.position);
210
234
  };
211
- }
212
- if (HOVER.some(type => wanted.has(type))) {
213
- out.onHover = (entered: boolean) => fireAll(element, entered ? ["pointerover", "pointerenter", "mouseover", "mouseenter"] : ["pointerout", "pointerleave", "mouseout", "mouseleave"], wanted);
235
+ out.onPointerLeave = () => {
236
+ if (!pointerInside.delete(element)) return;
237
+ if (hovers) fireAll(element, ["pointerout", "pointerleave", "mouseout", "mouseleave"], wanted);
238
+ };
214
239
  }
215
240
  if (wanted.has("contextmenu")) out.onContextMenu = (point: { x: number; y: number }) => fire(element, "contextmenu", { clientX: point.x, clientY: point.y, pageX: point.x, pageY: point.y, button: 2 });
216
241
  if (tag === "form") out.onSubmit = () => fire(element, "submit");
@@ -260,7 +285,7 @@ function elementChild(node: TElement): VNode {
260
285
  return vnode;
261
286
  }
262
287
 
263
- function children(element: TElement, tag: string): Child {
288
+ function children(element: TElement, tag: string, display?: unknown): Child {
264
289
  const out: Child[] = [];
265
290
  if (TEXT_CONTAINERS.has(tag)) {
266
291
  for (let child = element._first; child; child = child._next) out.push(plain(child));
@@ -270,23 +295,43 @@ function children(element: TElement, tag: string): Child {
270
295
  for (let child = element._first; child; child = child._next) {
271
296
  if (child.nodeType !== ELEMENT_NODE) continue;
272
297
  elements = true;
273
- if (!INLINE.has((child as TElement).localName)) { inlineOnly = false; break; }
298
+ // A phrasing element holding a block (`<span><svg/></span>`) lays out as a block, not inside a text run.
299
+ if (!isInlineContent(child as TElement)) { inlineOnly = false; break; }
274
300
  }
275
- // Text and phrasing elements side by side flow as one paragraph, as in a CSS block.
276
- if (elements && inlineOnly) {
301
+ // Text and phrasing elements side by side flow as one paragraph, as in a CSS block. In a
302
+ // flex or grid container each one is an item of its own (CSS blockifies them).
303
+ if (elements && inlineOnly && display !== "flex" && display !== "grid") {
277
304
  for (let child = element._first; child; child = child._next) out.push(plain(child));
278
305
  return jsx("span", { children: out });
279
306
  }
307
+ const orders: number[] = [];
280
308
  for (let child = element._first; child; child = child._next) {
281
- if (child.nodeType === ELEMENT_NODE) out.push(elementChild(child as TElement));
282
- else if (child.nodeType === TEXT_NODE && !isBlank(child)) out.push((child as TCharacterData).data);
309
+ if (child.nodeType === ELEMENT_NODE) {
310
+ out.push(elementChild(child as TElement));
311
+ orders.push(Number((child as TElement)._renderCache?.props.style?.order ?? 0) || 0);
312
+ } else if (child.nodeType === TEXT_NODE && !isBlank(child)) { out.push((child as TCharacterData).data); orders.push(0); }
313
+ }
314
+ // CSS `order`: a flex or grid container lays its items out by it (stable for equal values).
315
+ if ((display === "flex" || display === "grid") && orders.some(order => order !== 0)) {
316
+ return out.map((item, index) => ({ item, order: orders[index]!, index })).sort((a, b) => a.order - b.order || a.index - b.index).map(entry => entry.item);
283
317
  }
284
318
  return out.length ? out : undefined;
285
319
  }
286
320
 
321
+ /**
322
+ * A phrasing element that flows inside a run of text: not one the CSS makes a box of its own
323
+ * (`inline-block`, `inline-flex`, `block`, `flex`…) and holding only phrasing content.
324
+ */
325
+ function isInlineContent(element: TElement): boolean {
326
+ if (!INLINE.has(element.localName)) return false;
327
+ const style = (element._renderCache?.props.style ?? elementStyle(element, (element.getAttribute("class") ?? "").split(/\s+/).filter(Boolean))) as Record<string, unknown> | undefined;
328
+ if (style && (style.inline === "block" || style.display !== undefined && style.display !== "inline")) return false;
329
+ return !hasNonPhrasingChild(element);
330
+ }
331
+
287
332
  function hasNonPhrasingChild(element: TElement): boolean {
288
333
  for (let child = element._first; child; child = child._next) {
289
- if (child.nodeType === ELEMENT_NODE && (!INLINE.has((child as TElement).localName) || hasNonPhrasingChild(child as TElement))) return true;
334
+ if (child.nodeType === ELEMENT_NODE && !isInlineContent(child as TElement)) return true;
290
335
  }
291
336
  return false;
292
337
  }
@@ -296,7 +341,7 @@ function hasNonPhrasingChild(element: TElement): boolean {
296
341
  * wrapping row of text runs and elements, as inline formatting lays it out. A
297
342
  * label passes its clicks to its control, as in HTML.
298
343
  */
299
- function mixedFlow(element: TElement, tag: string, out: Record<string, any>): VNode {
344
+ function mixedFlow(element: TElement, tag: string, out: Record<string, any>, blockify = false): VNode {
300
345
  const items: Child[] = [];
301
346
  let run: Child[] = [];
302
347
  const flush = () => { if (run.length) items.push(jsx("span", { children: run })); run = []; };
@@ -304,12 +349,22 @@ function mixedFlow(element: TElement, tag: string, out: Record<string, any>): VN
304
349
  if (child.nodeType === TEXT_NODE) { if (!isBlank(child)) run.push((child as TCharacterData).data); continue; }
305
350
  if (child.nodeType !== ELEMENT_NODE) continue;
306
351
  const item = child as TElement;
307
- if (INLINE.has(item.localName) && !hasNonPhrasingChild(item)) { run.push(build(item)); continue; }
352
+ if (!blockify && isInlineContent(item)) { run.push(build(item)); continue; }
308
353
  flush();
309
354
  items.push(elementChild(item));
310
355
  }
311
356
  flush();
312
- const style = { direction: "row", wrap: true, align: "center", gap: 4, ...out.style };
357
+ // A line of mixed content wraps; a flex container's items stay on one line unless it says `wrap`.
358
+ const flex = displayOf(out) === "flex";
359
+ // Defaults the element's CSS and Tailwind classes have not set (a class loses to a style key).
360
+ const classes = out.class ?? "";
361
+ const style = {
362
+ ...(/(^|\s)flex-(row|col)/.test(classes) ? {} : { direction: "row" }),
363
+ ...(/(^|\s)flex-(wrap|nowrap)/.test(classes) ? {} : { wrap: !flex }),
364
+ ...(out.style?.align !== undefined || /(^|\s)items-/.test(classes) ? {} : { alignItems: flex ? "stretch" : "center" }),
365
+ ...(/(^|\s)(gap|space-x)-/.test(classes) ? {} : { gap: flex ? 0 : 4 }),
366
+ ...out.style,
367
+ };
313
368
  const props: Record<string, any> = { ...out, style, children: items };
314
369
  if (tag === "label") {
315
370
  const target = labelTarget(element);
@@ -331,7 +386,10 @@ function labelTarget(label: TElement): TElement | null {
331
386
 
332
387
  /** `::before` / `::after` content around an element's children. */
333
388
  function withGenerated(content: Child, generated: { before?: GeneratedContent; after?: GeneratedContent }, inline: boolean): Child {
334
- const box = (part: GeneratedContent) => part.text || inline ? jsx("span", { style: part.style, children: part.text }) : jsx("div", { style: part.style });
389
+ const box = (part: GeneratedContent) => {
390
+ const { inline: _inline, ...style } = part.style;
391
+ return part.text || inline ? jsx("span", { style, children: part.text }) : jsx("div", { style });
392
+ };
335
393
  const items: Child[] = [];
336
394
  if (generated.before) items.push(box(generated.before));
337
395
  if (Array.isArray(content)) items.push(...content); else if (content != null) items.push(content);
@@ -361,6 +419,19 @@ function titleBar(element: TElement, out: Record<string, any>): VNode {
361
419
  });
362
420
  }
363
421
 
422
+ /**
423
+ * `<surface>`: a box another renderer presents into (libmpv, a game engine). Its `surface`
424
+ * events (`ready`, `resize`, `destroyed`) carry the native event as `detail`; children draw on top.
425
+ */
426
+ function surface(element: TElement, out: Record<string, any>): VNode {
427
+ return jsx("surface", {
428
+ ...out,
429
+ ...(element.hasAttribute("native") ? { native: element.getAttribute("native") !== "false" } : {}),
430
+ onSurface: (event: object) => fire(element, "surface", { bubbles: false, detail: event }),
431
+ children: children(element, "div"),
432
+ });
433
+ }
434
+
364
435
  function hasElementOrText(element: TElement): boolean {
365
436
  for (let child = element._first; child; child = child._next) if (child.nodeType === ELEMENT_NODE || (child.nodeType === TEXT_NODE && !isBlank(child))) return true;
366
437
  return false;
@@ -391,6 +462,7 @@ export function build(element: TElement): VNode {
391
462
  element._renderCache = cache = { version: element._attrVersion, props: base };
392
463
  }
393
464
  const out: Record<string, any> = { ...cache.props };
465
+ boxDefaults(element, tag, out);
394
466
  if (element.isContentEditable) return editable(element, out);
395
467
  if (tag === "audio") {
396
468
  const media = element as THTMLMediaElement;
@@ -432,29 +504,240 @@ export function build(element: TElement): VNode {
432
504
  return jsx("select", { ...out, children: options });
433
505
  }
434
506
  if (tag === "button") {
507
+ // A button made a flex or grid container lays out like any other one: items stretch across
508
+ // and pack at the start (`align-items`/`justify-content: normal`), not centred as a plain button.
509
+ const display = displayOf(out);
510
+ if (display === "flex" || display === "grid") {
511
+ const classes = out.class ?? "";
512
+ out.style = { ...(/(^|\s)items-/.test(classes) ? {} : { alignItems: "stretch" }), ...(/(^|\s)justify-/.test(classes) ? {} : { justifyContent: "flex-start" }), ...out.style };
513
+ }
514
+ // A button the page paints keeps its paint when hovered or pressed unless its CSS says otherwise:
515
+ // the theme's state colours belong to the unstyled button.
516
+ const painted = out.style && (out.style.background !== undefined || out.style.backgroundColor !== undefined || out.style.backgroundImage !== undefined)
517
+ || /(^|\s)bg-/.test(out.class ?? "");
518
+ if (painted) out.style = { hover: {}, active: {}, disabled: {}, ...out.style };
519
+ // Tailwind's preflight: a button takes its parent's font and colour (`font: inherit; color: inherit`)
520
+ // and has no fill of its own. Utility classes still set their own.
521
+ if (usesPreflight()) {
522
+ const classes = out.class ?? "";
523
+ const inherited: Record<string, unknown> = {};
524
+ const take = (key: string, skip: RegExp) => { if (out.style?.[key] === undefined && !skip.test(classes)) { const value = inheritedValue(element, key); if (value !== undefined) inherited[key] = value; } };
525
+ take("fontSize", /(^|\s)text-(xs|sm|base|lg|[0-9]*xl|\[\d)/);
526
+ take("fontWeight", /(^|\s)font-(thin|extralight|light|normal|medium|semibold|bold|extrabold|black|\[)/);
527
+ take("lineHeight", /(^|\s)leading-/);
528
+ take("foreground", /(^|\s)text-(?!xs|sm|base|lg|[0-9]*xl|\[\d|left|right|center|justify)/);
529
+ if (!painted) inherited.background = "transparent";
530
+ out.style = { ...inherited, ...out.style };
531
+ }
532
+ // A button the CSS lays out or pads is as tall as its content, not the fixed height of an unstyled one.
533
+ if ((display === "flex" || display === "grid" || out.style?.padding !== undefined || /(^|\s)p[xytrbl]?-/.test(out.class ?? "")) && out.style?.height === undefined && !/(^|\s)(h|size)-/.test(out.class ?? "")) out.style = { ...out.style, height: "auto" };
534
+ // An icon beside the label (`<button><svg/> Play</button>`) keeps its elements; plain text stays one label.
535
+ if (element.querySelector("*")) {
536
+ out.children = children(element, tag);
537
+ const generated = generatedContent(element);
538
+ if (generated) out.children = withGenerated(out.children, generated, false);
539
+ return jsx("button", out);
540
+ }
435
541
  settle(element);
436
542
  out.children = textOf(element);
437
543
  return jsx("button", out);
438
544
  }
439
545
  if (tag === "svg" || element.namespaceURI.endsWith("svg")) {
440
- out.children = element.childNodes.filter(node => node.nodeType === ELEMENT_NODE).map(node => build(node as TElement));
546
+ // An HTML <svg> starts from SVG's initial values (filled black, no stroke), not the stroked
547
+ // line-icon defaults of Tarve's <Svg>: icon sets fill their paths with currentColor.
548
+ if (tag === "svg") for (const [key, value] of Object.entries({ fill: "black", stroke: "none", strokeWidth: 1, strokeLinecap: "butt", strokeLinejoin: "miter" })) out[key] ??= value;
549
+ // `currentColor` is the colour the svg inherits, as in CSS, not the theme's foreground.
550
+ if (tag === "svg" && out.color === undefined && out.style?.color === undefined && out.style?.foreground === undefined
551
+ && !/(^|\s)text-(?!\[?\d|xs|sm|base|lg|xl|[2-9]xl|left|right|center|justify|start|end|wrap|nowrap|clip|ellipsis)/.test(out.class ?? "")) out.color = "currentColor";
552
+ // Icon sets size an icon to the text (`width="1.2em"`): an em is the font size it inherits.
553
+ for (const side of ["width", "height"] as const) {
554
+ const em = typeof out[side] === "string" ? /^(\d*\.?\d+)em$/.exec(out[side].trim()) : null;
555
+ if (em) out[side] = Number(em[1]) * inheritedFontSize(element);
556
+ // `width="24"` (and `24px`) is a length in user units: a number, as the native box wants.
557
+ const px = typeof out[side] === "string" ? /^(\d*\.?\d+)(px)?$/.exec(out[side].trim()) : null;
558
+ if (px) out[side] = Number(px[1]);
559
+ }
560
+ const shapes = element.childNodes.filter(node => node.nodeType === ELEMENT_NODE).map(node => {
561
+ const shape = build(node as TElement);
562
+ // A shape's own attributes draw it; box styles from CSS rules (`* { … }`) and classes do not apply.
563
+ const { style: _style, class: _class, ...attributes } = shape.props as Record<string, unknown>;
564
+ return { ...shape, props: attributes };
565
+ });
566
+ // Leaves (`<path/>`, `<circle/>`) take no children, not even an empty list.
567
+ if (shapes.length) out.children = shapes;
568
+ else delete out.children;
441
569
  return jsx(tag, out);
442
570
  }
443
571
  if (tag === "titlebar") return titleBar(element, out);
572
+ if (tag === "surface") return surface(element, out);
444
573
  if (TEXT_CONTAINERS.has(tag) && hasNonPhrasingChild(element)) return mixedFlow(element, tag, out);
445
- out.children = children(element, tag);
574
+ // A flex or grid text element (`<h2 class="flex"><span class="accent"></span>Title</h2>`) lays
575
+ // its children out as items, each element a box of its own and each text run an anonymous item.
576
+ if (TEXT_CONTAINERS.has(tag) && (displayOf(out) === "flex" || displayOf(out) === "grid") && element.querySelector("*")) return mixedFlow(element, tag, out, true);
577
+ // A block holding only text that clamps or ellipsizes it (`text-overflow`, `line-clamp`) is that text:
578
+ // the text node takes the box style, so its lines are the ones the box cuts.
579
+ if (!TEXT_CONTAINERS.has(tag) && (out.style?.textOverflow !== undefined || out.style?.lineClamp !== undefined) && !element.querySelector("*") && element.textContent?.trim()) {
580
+ settle(element);
581
+ return jsx("span", { ...out, style: { ...out.style, display: undefined }, children: textOf(element) });
582
+ }
583
+ out.children = children(element, tag, displayOf(out));
446
584
  const generated = generatedContent(element);
447
585
  if (generated) out.children = withGenerated(out.children, generated, TEXT_CONTAINERS.has(tag));
586
+ backgroundImage(out);
448
587
  const native = NATIVE[tag];
449
588
  if (native) return native(out);
589
+ if (FLEX_TEXT.has(tag) && (out.style?.display === "flex" || out.style?.display === "grid")) return flexText(out);
450
590
  return jsx(KNOWN.has(tag) ? tag : "div", out);
451
591
  }
452
592
 
593
+ /**
594
+ * The display an element renders with: its CSS, else its Tailwind classes (`flex`, `inline-grid`,
595
+ * `hidden`…; the unprefixed ones, which hold at every width).
596
+ */
597
+ function displayOf(props: { style?: Record<string, any>; class?: string }): string | undefined {
598
+ if (props.style?.display !== undefined) return props.style.display;
599
+ let display: string | undefined;
600
+ for (const name of (props.class ?? "").split(/\s+/)) {
601
+ if (name === "flex" || name === "inline-flex") display = "flex";
602
+ else if (name === "grid" || name === "inline-grid") display = "grid";
603
+ else if (name === "block" || name === "inline-block") display = "block";
604
+ else if (name === "hidden") display = "none";
605
+ }
606
+ return display;
607
+ }
608
+
609
+ const PREFLIGHT_TEXT = new Set(["p", "h1", "h2", "h3", "h4", "h5", "h6"]);
610
+
611
+ const BLOCK_TAGS = new Set(["div", "section", "main", "header", "footer", "article", "aside", "nav", "form", "fieldset", "ul", "ol", "li", "figure", "blockquote", "dl", "dd"]);
612
+
613
+ function hasInlineLevelChild(element: TElement): boolean {
614
+ for (let child = element._first; child; child = child._next) {
615
+ if (child.nodeType !== ELEMENT_NODE) continue;
616
+ const item = child as TElement;
617
+ const style = (item._renderCache?.props.style ?? elementStyle(item, (item.getAttribute("class") ?? "").split(/\s+/).filter(Boolean))) as Record<string, unknown> | undefined;
618
+ if (style?.inline !== undefined || /(^|\s)inline-(flex|block|grid)(\s|$)/.test(item.getAttribute("class") ?? "")) return true;
619
+ if (INLINE.has(item.localName) && !style?.display) return true;
620
+ }
621
+ return false;
622
+ }
623
+
624
+ const CONTROL_TAGS = new Set(["button", "input", "select", "textarea", "img", "svg", "progress", "meter", "video", "audio", "canvas", "surface", "titlebar"]);
625
+
626
+ /**
627
+ * CSS defaults Tarve's layout does not share: `box-sizing: content-box` (unless the page resets it,
628
+ * as Tailwind's preflight does), and a block's children never shrink to fit it (only a flex
629
+ * container's items do).
630
+ */
631
+ function boxDefaults(element: TElement, tag: string, out: Record<string, any>): void {
632
+ const style = out.style as Record<string, unknown> | undefined;
633
+ if (!CONTROL_TAGS.has(tag) && style && style.boxSizing === undefined && !usesPreflight()
634
+ && (style.padding !== undefined || style.borderWidth !== undefined)) out.style = { ...style, boxSizing: "content-box" };
635
+ // A CSS block lays out as one (Taffy's block layout): vertical margins collapse, `margin: auto`
636
+ // centres, children stack at full width. One holding inline-level boxes (`inline-block` badges)
637
+ // stays a flex column, where those can shrink to their content.
638
+ // (`space-y-*` and `gap` are spacing Tarve gives flex columns; a block would drop them.)
639
+ if (BLOCK_TAGS.has(tag) && displayOf(out) === undefined && !hasInlineLevelChild(element)
640
+ && out.style?.gap === undefined && out.style?.rowGap === undefined && !/(^|\s)(space-y-|gap-)/.test(out.class ?? "")) out.style = { ...out.style, display: "block" };
641
+ const parent = element.parentElement;
642
+ const parentProps = parent?._renderCache?.props;
643
+ const parentDisplay = parentProps ? displayOf(parentProps) : undefined;
644
+ if (parent && parentDisplay !== "flex" && parentDisplay !== "grid" && out.style?.shrink === undefined && out.style?.flex === undefined && out.style?.position !== "absolute"
645
+ // Clamped by max-height, the item already is no taller than CSS makes it.
646
+ && out.style?.maxHeight === undefined
647
+ && !/(^|\s)(shrink|flex-)/.test(out.class ?? "")) out.style = { ...out.style, shrink: 0 };
648
+ }
649
+
650
+ /** Text elements that can be made flex containers of their own text (`<span class="badge">1</span>`). */
651
+ const FLEX_TEXT = new Set(["span", "p", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "em", "b", "i", "small", "dt", "dd"]);
652
+ const TEXT_STYLE = new Set(["fontSize", "fontWeight", "fontStyle", "fontFamily", "color", "foreground", "letterSpacing", "wordSpacing", "lineHeight",
653
+ "textTransform", "textAlign", "textDecoration", "textShadow", "whiteSpace", "textOverflow", "lineClamp", "fontVariantNumeric", "fontFeatureSettings"]);
654
+
655
+ /**
656
+ * A text element with `display: flex` (or grid) is a box laying out its text as an item, which
657
+ * `justify-content`/`align-items` place (a centred number in a round badge). The box keeps the
658
+ * element's box style; the text inside takes its text style.
659
+ */
660
+ function flexText(out: Record<string, any>): VNode {
661
+ const box: Record<string, unknown> = {}, text: Record<string, unknown> = {};
662
+ for (const [key, value] of Object.entries(out.style as Record<string, unknown>)) (TEXT_STYLE.has(key) ? text : box)[key] = value;
663
+ // The box's hover colours its text: the text follows the box as a hover group.
664
+ const hover = box.hover as Record<string, unknown> | undefined;
665
+ if (hover && Object.keys(hover).some(key => TEXT_STYLE.has(key))) {
666
+ box.hover = Object.fromEntries(Object.entries(hover).filter(([key]) => !TEXT_STYLE.has(key)));
667
+ text.groupHover = Object.fromEntries(Object.entries(hover).filter(([key]) => TEXT_STYLE.has(key)));
668
+ box.group = true;
669
+ }
670
+ return jsx("div", { ...out, style: box, children: jsx("span", { style: text, children: out.children }) });
671
+ }
672
+
673
+ /**
674
+ * CSS `background-image: url(…)` (with `background-size`): an image drawn under the
675
+ * element's children, filling its box like `cover` (default), `contain` or `100% 100%`.
676
+ * Gradients in `background-image` are the element's background.
677
+ */
678
+ function backgroundImage(out: Record<string, any>): void {
679
+ const style = out.style as Record<string, any> | undefined;
680
+ if (!style || (style.backgroundImage === undefined && style.backgroundSize === undefined && style.backgroundPosition === undefined && style.backgroundRepeat === undefined)) return;
681
+ const { backgroundImage: image, backgroundSize: size, backgroundPosition: _position, backgroundRepeat: _repeat, ...rest } = style;
682
+ out.style = rest;
683
+ if (typeof image !== "string" || image.trim() === "none") return;
684
+ const layers = image.split(/,(?![^(]*\))/).map(layer => layer.trim());
685
+ const url = layers.map(layer => /^url\(\s*(['"]?)(.*?)\1\s*\)$/.exec(layer)?.[2]).find(Boolean);
686
+ const gradient = layers.find(layer => /gradient\(/.test(layer));
687
+ if (gradient && rest.background === undefined) rest.background = gradient;
688
+ if (!url) return;
689
+ const fit = size === "contain" ? "contain" : /^100%(\s+100%)?$/.test(String(size ?? "")) ? "fill" : "cover";
690
+ if (rest.position === undefined || rest.position === "static") rest.position = "relative";
691
+ const layer = jsx("img", {
692
+ src: url, fit, "aria-hidden": "true",
693
+ style: { position: "absolute", top: 0, right: 0, bottom: 0, left: 0, width: "100%", height: "100%", pointerEvents: "none", ...(rest.radius !== undefined ? { radius: rest.radius } : {}) },
694
+ });
695
+ out.children = [layer, ...(Array.isArray(out.children) ? out.children : out.children == null ? [] : [out.children])];
696
+ }
697
+
453
698
  const ElementView = memo(
454
699
  ({ element }: { element: TElement; version: number }) => build(element),
455
700
  (previous, next) => previous.element === next.element && previous.version === next.version,
456
701
  );
457
702
 
703
+ /**
704
+ * The page's canvas colour, as a browser paints it: `<html>`'s background, else `<body>`'s.
705
+ * Undefined when the CSS sets neither (the window keeps its own).
706
+ */
707
+ export function canvasBackground(): unknown {
708
+ for (const element of [documentInstance.documentElement, documentInstance.body]) {
709
+ const style = elementStyle(element, (element.getAttribute("class") ?? "").split(/\s+/).filter(Boolean)) as Record<string, unknown> | undefined;
710
+ const background = style?.background ?? style?.backgroundColor;
711
+ if (background !== undefined) return background;
712
+ }
713
+ return undefined;
714
+ }
715
+
716
+ /** Text properties a page inherits from `<html>` and `<body>`. */
717
+ const CANVAS_TEXT = ["fontFamily", "fontSize", "fontWeight", "fontStyle", "lineHeight", "letterSpacing", "color", "foreground", "textAlign", "textTransform"] as const;
718
+
719
+ /**
720
+ * What `<html>` and `<body>` pass down to the page, as in a browser: their text properties
721
+ * (`font-family`, `line-height`, `color`…; body's over html's). The mount target holds the
722
+ * page, so the body itself never renders; its inherited values start the page's.
723
+ */
724
+ export function canvasText(): Record<string, unknown> {
725
+ const out: Record<string, unknown> = {};
726
+ for (const element of [documentInstance.documentElement, documentInstance.body]) {
727
+ const style = elementStyle(element, (element.getAttribute("class") ?? "").split(/\s+/).filter(Boolean)) as Record<string, unknown> | undefined;
728
+ if (!style) continue;
729
+ for (const key of CANVAS_TEXT) if (style[key] !== undefined) out[key === "color" ? "foreground" : key] = style[key];
730
+ }
731
+ return out;
732
+ }
733
+
734
+ /** The native id of the box standing for the viewport: the mount target's, so layout reads reach it. */
735
+ export function viewportId(target: TElement): string {
736
+ const id = nativeIdOf(target);
737
+ if (elementsById.get(id)?.deref() !== target) elementsById.set(id, new WeakRef(target));
738
+ return id;
739
+ }
740
+
458
741
  /** The children of the mount target, as the Window's content. */
459
742
  export function rootChildren(target: TElement): Child {
460
743
  target._pending = false;
@@ -465,3 +748,82 @@ export function rootChildren(target: TElement): Child {
465
748
  }
466
749
  return out;
467
750
  }
751
+
752
+ /**
753
+ * An ancestor's style for inheritance lookups: its rendered props when built, else its CSS, computed
754
+ * once per render. Each descendant asks its whole parent chain (font, colour, `inherit`), and before
755
+ * an ancestor has finished building, recomputing its rules for every descendant made a first render
756
+ * of a large page take over a second.
757
+ */
758
+ const ancestorStyles = new WeakMap<TElement, { epoch: string; version: number; style: Record<string, unknown> | undefined }>();
759
+ /** One render's key: the DOM epoch it renders and the viewport (`vw`, `@media`) it styles for. */
760
+ const renderKey = () => `${layout.rendered}:${windowInstance.innerWidth}x${windowInstance.innerHeight}`;
761
+ function styleOf(element: TElement): Record<string, unknown> | undefined {
762
+ const built = element._renderCache?.props.style as Record<string, unknown> | undefined;
763
+ if (built) return built;
764
+ const cached = ancestorStyles.get(element);
765
+ const epoch = renderKey();
766
+ if (cached && cached.epoch === epoch && cached.version === element._attrVersion) return cached.style;
767
+ const style = elementStyle(element, (element.getAttribute("class") ?? "").split(/\s+/).filter(Boolean)) as Record<string, unknown> | undefined;
768
+ ancestorStyles.set(element, { epoch, version: element._attrVersion, style });
769
+ return style;
770
+ }
771
+
772
+ /** An inherited text property of `element`'s parent chain (CSS inheritance), else the page's own (`body`). */
773
+ function inheritedValue(element: TElement, key: string): unknown {
774
+ for (let current = element.parentElement; current; current = current.parentElement) {
775
+ const classes = current.getAttribute("class") ?? "";
776
+ const own = styleOf(current);
777
+ // Utility classes count too (`<div class="text-white">`); the element's CSS wins over them.
778
+ let utilities: Record<string, unknown> | undefined;
779
+ try { utilities = classes && usesPreflight() ? tw(classes) as Record<string, unknown> : undefined; } catch { utilities = undefined; }
780
+ const style = { ...utilities, ...own };
781
+ const value = key === "foreground" ? style.foreground ?? style.color : style[key];
782
+ if (value !== undefined) return value;
783
+ }
784
+ // The page's own values, once per render (every element without an ancestor value asks).
785
+ if (canvasCache?.epoch !== renderKey()) canvasCache = { epoch: renderKey(), text: canvasText() };
786
+ return canvasCache.text[key];
787
+ }
788
+ let canvasCache: { epoch: string; text: Record<string, unknown> } | undefined;
789
+
790
+ /** CSS `inherit`: the parent's value of the same property (`border-radius: inherit`). */
791
+ function inheritValues(element: TElement, style: Record<string, unknown>): Record<string, unknown> {
792
+ let out = style;
793
+ for (const [key, value] of Object.entries(style)) {
794
+ if (value !== "inherit") continue;
795
+ if (out === style) out = { ...style };
796
+ const parent = element.parentElement;
797
+ const parentStyle = parent ? styleOf(parent) : undefined;
798
+ const inherited = parentStyle?.[key];
799
+ if (inherited === undefined || inherited === "inherit") delete out[key]; else out[key] = inherited;
800
+ }
801
+ return out;
802
+ }
803
+
804
+ /** The font size `element` inherits (CSS `em`): its own or its nearest ancestor's, else 16 px. */
805
+ function inheritedFontSize(element: TElement): number {
806
+ for (let current: TElement | null = element; current; current = current.parentElement) {
807
+ const style = current === element ? (current._renderCache?.props.style ?? elementStyle(current, (current.getAttribute("class") ?? "").split(/\s+/).filter(Boolean))) as Record<string, unknown> | undefined : styleOf(current);
808
+ if (typeof style?.fontSize === "number") return style.fontSize;
809
+ }
810
+ return 16;
811
+ }
812
+
813
+ /**
814
+ * An inline-level box (`inline-block`, `inline-flex`) in a block shrinks to its content and sits
815
+ * where the line puts it (`text-align`); a flex or grid parent makes it an item like any other.
816
+ */
817
+ function inlineLevel(element: TElement, style: Record<string, unknown>): Record<string, unknown> {
818
+ const { inline, ...rest } = style;
819
+ if (!inline || rest.alignSelf !== undefined || rest.position === "absolute") return rest;
820
+ const parent = element.parentElement;
821
+ // A line of text and phrasing elements already sizes each to its content.
822
+ if (!parent || TEXT_CONTAINERS.has(parent.localName)) return rest;
823
+ const parentProps = parent._renderCache?.props ?? { style: elementStyle(parent, (parent.getAttribute("class") ?? "").split(/\s+/).filter(Boolean)), class: parent.getAttribute("class") ?? "" };
824
+ const parentStyle = parentProps.style as Record<string, unknown> | undefined;
825
+ const parentDisplay = displayOf(parentProps);
826
+ if (parentDisplay === "flex" || parentDisplay === "grid") return rest;
827
+ const align = parentStyle?.textAlign;
828
+ return { ...rest, alignSelf: align === "center" ? "center" : align === "right" || align === "end" ? "end" : "start" };
829
+ }
package/src/selectors.ts CHANGED
@@ -36,12 +36,21 @@ export interface Compound {
36
36
  export type Combinator = " " | ">" | "+" | "~";
37
37
 
38
38
  /** Compounds left to right, with the combinator before each but the first. */
39
+ /**
40
+ * Pseudo-elements a rule can style: generated content (`::before`/`::after`), an input's
41
+ * `::placeholder` and the scrollbar parts (`::-webkit-scrollbar`, `-thumb`, `-track`).
42
+ */
43
+ export type PseudoElement = "before" | "after" | "placeholder" | "-webkit-scrollbar" | "-webkit-scrollbar-thumb" | "-webkit-scrollbar-track"
44
+ | "-webkit-slider-thumb" | "-moz-range-thumb" | "-webkit-slider-runnable-track" | "-moz-range-track" | "-moz-range-progress";
45
+ const PSEUDO_ELEMENTS = new Set<string>(["before", "after", "placeholder", "-webkit-scrollbar", "-webkit-scrollbar-thumb", "-webkit-scrollbar-track",
46
+ "-webkit-slider-thumb", "-moz-range-thumb", "-webkit-slider-runnable-track", "-moz-range-track", "-moz-range-progress"]);
47
+
39
48
  export interface Selector {
40
49
  compounds: Compound[];
41
50
  combinators: Combinator[];
42
51
  specificity: number;
43
52
  /** `::before` / `::after` on the last compound: the rule styles generated content. */
44
- pseudoElement?: "before" | "after";
53
+ pseudoElement?: PseudoElement;
45
54
  }
46
55
 
47
56
  const STATES: Record<string, "hover" | "focus" | "focusVisible" | "active" | "focusWithin"> = {
@@ -79,7 +88,13 @@ function splitTopLevel(text: string, separator: string): string[] {
79
88
  return out.map(part => part.trim()).filter(Boolean);
80
89
  }
81
90
 
82
- const IDENT = /^-?[_a-zA-Z\u00a0-\uffff][-_a-zA-Z0-9\u00a0-\uffff]*|^\*/;
91
+ // Identifiers may escape any character (`.md\:flex`, `.w-1\/2`, Tailwind's class names).
92
+ const IDENT = /^(?:-?(?:[_a-zA-Z\u00a0-\uffff]|\\[0-9a-fA-F]{1,6}\s?|\\[^\n0-9a-fA-F])(?:[-_a-zA-Z0-9\u00a0-\uffff]|\\[0-9a-fA-F]{1,6}\s?|\\[^\n0-9a-fA-F])*|\*)/;
93
+
94
+ /** An identifier as written, its escapes resolved (`md\:flex` is the class "md:flex"). */
95
+ function unescape(ident: string): string {
96
+ return ident.replace(/\\([0-9a-fA-F]{1,6})\s?|\\(.)/g, (_, hex: string | undefined, char: string | undefined) => hex ? String.fromCodePoint(parseInt(hex, 16)) : char!);
97
+ }
83
98
 
84
99
  function parseSelector(text: string): Selector {
85
100
  const compounds: Compound[] = [];
@@ -107,7 +122,7 @@ function parseSelector(text: string): Selector {
107
122
  if (char === "#" || char === ".") {
108
123
  const ident = IDENT.exec(rest.slice(1));
109
124
  if (!ident) throw new SyntaxError(`Invalid selector "${text}"`);
110
- if (char === "#") { current.id = ident[0]; specificity += 100; } else { current.classes.push(ident[0]); specificity += 10; }
125
+ if (char === "#") { current.id = unescape(ident[0]); specificity += 100; } else { current.classes.push(unescape(ident[0])); specificity += 10; }
111
126
  rest = rest.slice(1 + ident[0].length);
112
127
  } else if (char === "[") {
113
128
  const match = /^\[\s*([^\s~|^$*=\]]+)\s*(?:([~|^$*]?=)\s*(?:"([^"]*)"|'([^']*)'|([^\s\]]+))\s*(i)?\s*)?\]/.exec(rest);
@@ -129,8 +144,8 @@ function parseSelector(text: string): Selector {
129
144
  rest = rest.slice(end + 1);
130
145
  }
131
146
  if (element || name === "before" || name === "after") {
132
- if (name !== "before" && name !== "after") throw new SyntaxError(`Pseudo-element ::${name} is not supported`);
133
- pseudoElement = name;
147
+ if (!PSEUDO_ELEMENTS.has(name)) throw new SyntaxError(`Pseudo-element ::${name} is not supported`);
148
+ pseudoElement = name as PseudoElement;
134
149
  specificity += 1;
135
150
  started = true;
136
151
  continue;
@@ -302,6 +317,17 @@ export function ruleState(selector: Selector): "hover" | "focus" | "focusVisible
302
317
  return undefined;
303
318
  }
304
319
 
320
+ /**
321
+ * The interaction state an ancestor compound requires (`.card:hover .title` → "hover"), with
322
+ * the index of that compound; undefined when only the last compound (or none) has one.
323
+ */
324
+ export function ancestorState(selector: Selector): { state: "hover" | "focus" | "focusVisible" | "active" | "focusWithin"; index: number } | undefined {
325
+ for (let index = selector.compounds.length - 2; index >= 0; index--) {
326
+ for (const pseudo of selector.compounds[index]!.pseudos) if (pseudo.kind === "state") return { state: pseudo.state, index };
327
+ }
328
+ return undefined;
329
+ }
330
+
305
331
  /** Whether a selector reads an element's descendants or later siblings (`:has()`). */
306
332
  export function usesHas(selector: Selector): boolean {
307
333
  return selector.compounds.some(compound => compound.pseudos.some(pseudo => pseudo.kind === "has"