@tarve/svelte 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/src/css.ts +581 -28
- package/src/dom-animation.ts +30 -4
- package/src/dom.ts +136 -10
- package/src/events.ts +18 -6
- package/src/index.ts +18 -8
- package/src/plugin.ts +32 -7
- package/src/render.ts +388 -25
- package/src/selectors.ts +31 -5
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
|
-
|
|
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
|
}
|
|
@@ -165,6 +173,7 @@ function addMedia(element: THTMLMediaElement, out: Record<string, any>): void {
|
|
|
165
173
|
out.onPlay = (info: object) => element._media("play", info);
|
|
166
174
|
out.onPause = (info: object) => element._media("pause", info);
|
|
167
175
|
out.onTimeUpdate = (info: object) => element._media("timeupdate", info);
|
|
176
|
+
out.onSeeking = (info: object) => element._media("seeking", info);
|
|
168
177
|
out.onSeeked = (info: object) => element._media("seeked", info);
|
|
169
178
|
out.onEnded = (info: object) => element._media("ended", info);
|
|
170
179
|
out.onWaiting = (info: object) => element._media("waiting", info);
|
|
@@ -183,8 +192,9 @@ function addEvents(element: TElement, tag: string, out: Record<string, any>): vo
|
|
|
183
192
|
if (element._resizeObservers?.size || element._measured) out.onSize = () => {};
|
|
184
193
|
if (element.hasAttribute("draggable") || wanted.has("drop") || wanted.has("dragover") || wanted.has("dragenter")) addDragAndDrop(element, wanted, out);
|
|
185
194
|
if (wanted.has("scroll") || element._scrollTracked) {
|
|
186
|
-
out.onScroll = (offset: number) => {
|
|
187
|
-
element.
|
|
195
|
+
out.onScroll = (offset: number, max: number) => {
|
|
196
|
+
element._scrollTop = offset;
|
|
197
|
+
element._scrollMaxY = max;
|
|
188
198
|
scheduleIntersections();
|
|
189
199
|
if (wanted.has("scroll")) fire(element, "scroll", { bubbles: false });
|
|
190
200
|
};
|
|
@@ -202,14 +212,30 @@ function addEvents(element: TElement, tag: string, out: Record<string, any>): vo
|
|
|
202
212
|
if (detail === 2) fireAll(element, ["dblclick"], wanted, init);
|
|
203
213
|
};
|
|
204
214
|
}
|
|
205
|
-
|
|
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 ??= () => {}; }
|
|
206
223
|
out.onPointerMove = (point: { x: number; y: number }) => {
|
|
207
|
-
|
|
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);
|
|
208
233
|
fireAll(element, ["pointermove", "mousemove"], wanted, pointer.position);
|
|
209
234
|
};
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
235
|
+
out.onPointerLeave = () => {
|
|
236
|
+
if (!pointerInside.delete(element)) return;
|
|
237
|
+
if (hovers) fireAll(element, ["pointerout", "pointerleave", "mouseout", "mouseleave"], wanted);
|
|
238
|
+
};
|
|
213
239
|
}
|
|
214
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 });
|
|
215
241
|
if (tag === "form") out.onSubmit = () => fire(element, "submit");
|
|
@@ -259,7 +285,7 @@ function elementChild(node: TElement): VNode {
|
|
|
259
285
|
return vnode;
|
|
260
286
|
}
|
|
261
287
|
|
|
262
|
-
function children(element: TElement, tag: string): Child {
|
|
288
|
+
function children(element: TElement, tag: string, display?: unknown): Child {
|
|
263
289
|
const out: Child[] = [];
|
|
264
290
|
if (TEXT_CONTAINERS.has(tag)) {
|
|
265
291
|
for (let child = element._first; child; child = child._next) out.push(plain(child));
|
|
@@ -269,23 +295,43 @@ function children(element: TElement, tag: string): Child {
|
|
|
269
295
|
for (let child = element._first; child; child = child._next) {
|
|
270
296
|
if (child.nodeType !== ELEMENT_NODE) continue;
|
|
271
297
|
elements = true;
|
|
272
|
-
|
|
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; }
|
|
273
300
|
}
|
|
274
|
-
// Text and phrasing elements side by side flow as one paragraph, as in a CSS block.
|
|
275
|
-
|
|
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") {
|
|
276
304
|
for (let child = element._first; child; child = child._next) out.push(plain(child));
|
|
277
305
|
return jsx("span", { children: out });
|
|
278
306
|
}
|
|
307
|
+
const orders: number[] = [];
|
|
279
308
|
for (let child = element._first; child; child = child._next) {
|
|
280
|
-
if (child.nodeType === ELEMENT_NODE)
|
|
281
|
-
|
|
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);
|
|
282
317
|
}
|
|
283
318
|
return out.length ? out : undefined;
|
|
284
319
|
}
|
|
285
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
|
+
|
|
286
332
|
function hasNonPhrasingChild(element: TElement): boolean {
|
|
287
333
|
for (let child = element._first; child; child = child._next) {
|
|
288
|
-
if (child.nodeType === ELEMENT_NODE &&
|
|
334
|
+
if (child.nodeType === ELEMENT_NODE && !isInlineContent(child as TElement)) return true;
|
|
289
335
|
}
|
|
290
336
|
return false;
|
|
291
337
|
}
|
|
@@ -295,7 +341,7 @@ function hasNonPhrasingChild(element: TElement): boolean {
|
|
|
295
341
|
* wrapping row of text runs and elements, as inline formatting lays it out. A
|
|
296
342
|
* label passes its clicks to its control, as in HTML.
|
|
297
343
|
*/
|
|
298
|
-
function mixedFlow(element: TElement, tag: string, out: Record<string, any
|
|
344
|
+
function mixedFlow(element: TElement, tag: string, out: Record<string, any>, blockify = false): VNode {
|
|
299
345
|
const items: Child[] = [];
|
|
300
346
|
let run: Child[] = [];
|
|
301
347
|
const flush = () => { if (run.length) items.push(jsx("span", { children: run })); run = []; };
|
|
@@ -303,12 +349,22 @@ function mixedFlow(element: TElement, tag: string, out: Record<string, any>): VN
|
|
|
303
349
|
if (child.nodeType === TEXT_NODE) { if (!isBlank(child)) run.push((child as TCharacterData).data); continue; }
|
|
304
350
|
if (child.nodeType !== ELEMENT_NODE) continue;
|
|
305
351
|
const item = child as TElement;
|
|
306
|
-
if (
|
|
352
|
+
if (!blockify && isInlineContent(item)) { run.push(build(item)); continue; }
|
|
307
353
|
flush();
|
|
308
354
|
items.push(elementChild(item));
|
|
309
355
|
}
|
|
310
356
|
flush();
|
|
311
|
-
|
|
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
|
+
};
|
|
312
368
|
const props: Record<string, any> = { ...out, style, children: items };
|
|
313
369
|
if (tag === "label") {
|
|
314
370
|
const target = labelTarget(element);
|
|
@@ -330,7 +386,10 @@ function labelTarget(label: TElement): TElement | null {
|
|
|
330
386
|
|
|
331
387
|
/** `::before` / `::after` content around an element's children. */
|
|
332
388
|
function withGenerated(content: Child, generated: { before?: GeneratedContent; after?: GeneratedContent }, inline: boolean): Child {
|
|
333
|
-
const box = (part: GeneratedContent) =>
|
|
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
|
+
};
|
|
334
393
|
const items: Child[] = [];
|
|
335
394
|
if (generated.before) items.push(box(generated.before));
|
|
336
395
|
if (Array.isArray(content)) items.push(...content); else if (content != null) items.push(content);
|
|
@@ -360,6 +419,19 @@ function titleBar(element: TElement, out: Record<string, any>): VNode {
|
|
|
360
419
|
});
|
|
361
420
|
}
|
|
362
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
|
+
|
|
363
435
|
function hasElementOrText(element: TElement): boolean {
|
|
364
436
|
for (let child = element._first; child; child = child._next) if (child.nodeType === ELEMENT_NODE || (child.nodeType === TEXT_NODE && !isBlank(child))) return true;
|
|
365
437
|
return false;
|
|
@@ -390,6 +462,7 @@ export function build(element: TElement): VNode {
|
|
|
390
462
|
element._renderCache = cache = { version: element._attrVersion, props: base };
|
|
391
463
|
}
|
|
392
464
|
const out: Record<string, any> = { ...cache.props };
|
|
465
|
+
boxDefaults(element, tag, out);
|
|
393
466
|
if (element.isContentEditable) return editable(element, out);
|
|
394
467
|
if (tag === "audio") {
|
|
395
468
|
const media = element as THTMLMediaElement;
|
|
@@ -431,29 +504,240 @@ export function build(element: TElement): VNode {
|
|
|
431
504
|
return jsx("select", { ...out, children: options });
|
|
432
505
|
}
|
|
433
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
|
+
}
|
|
434
541
|
settle(element);
|
|
435
542
|
out.children = textOf(element);
|
|
436
543
|
return jsx("button", out);
|
|
437
544
|
}
|
|
438
545
|
if (tag === "svg" || element.namespaceURI.endsWith("svg")) {
|
|
439
|
-
|
|
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;
|
|
440
569
|
return jsx(tag, out);
|
|
441
570
|
}
|
|
442
571
|
if (tag === "titlebar") return titleBar(element, out);
|
|
572
|
+
if (tag === "surface") return surface(element, out);
|
|
443
573
|
if (TEXT_CONTAINERS.has(tag) && hasNonPhrasingChild(element)) return mixedFlow(element, tag, out);
|
|
444
|
-
|
|
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));
|
|
445
584
|
const generated = generatedContent(element);
|
|
446
585
|
if (generated) out.children = withGenerated(out.children, generated, TEXT_CONTAINERS.has(tag));
|
|
586
|
+
backgroundImage(out);
|
|
447
587
|
const native = NATIVE[tag];
|
|
448
588
|
if (native) return native(out);
|
|
589
|
+
if (FLEX_TEXT.has(tag) && (out.style?.display === "flex" || out.style?.display === "grid")) return flexText(out);
|
|
449
590
|
return jsx(KNOWN.has(tag) ? tag : "div", out);
|
|
450
591
|
}
|
|
451
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
|
+
|
|
452
698
|
const ElementView = memo(
|
|
453
699
|
({ element }: { element: TElement; version: number }) => build(element),
|
|
454
700
|
(previous, next) => previous.element === next.element && previous.version === next.version,
|
|
455
701
|
);
|
|
456
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
|
+
|
|
457
741
|
/** The children of the mount target, as the Window's content. */
|
|
458
742
|
export function rootChildren(target: TElement): Child {
|
|
459
743
|
target._pending = false;
|
|
@@ -464,3 +748,82 @@ export function rootChildren(target: TElement): Child {
|
|
|
464
748
|
}
|
|
465
749
|
return out;
|
|
466
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?:
|
|
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
|
-
|
|
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
|
|
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"
|