@pairdraw/dom-css 0.21.0 → 0.22.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.
Files changed (38) hide show
  1. package/dist/chunks/behaviours/states/layers.js +100 -15
  2. package/dist/chunks/behaviours/states/layers.js.map +1 -1
  3. package/dist/chunks/browser.js +373 -37
  4. package/dist/chunks/browser.js.map +1 -1
  5. package/dist/chunks/import/html.js +66 -11
  6. package/dist/chunks/import/html.js.map +1 -1
  7. package/dist/chunks/import/jsx/source/ast.js +207 -0
  8. package/dist/chunks/import/jsx/source/ast.js.map +1 -0
  9. package/dist/chunks/import/jsx/source/candidates.js +74 -0
  10. package/dist/chunks/import/jsx/source/candidates.js.map +1 -0
  11. package/dist/chunks/import/jsx/source/evaluate.js +213 -0
  12. package/dist/chunks/import/jsx/source/evaluate.js.map +1 -0
  13. package/dist/chunks/import/jsx/source/index.js +448 -0
  14. package/dist/chunks/import/jsx/source/index.js.map +1 -0
  15. package/dist/export.d.ts +16 -3
  16. package/dist/export.js +2 -2
  17. package/dist/index.d.ts +66 -1
  18. package/dist/index.js +5 -2
  19. package/dist/styling.d.ts +9 -2
  20. package/package.json +5 -3
  21. package/src/cssom/browser.ts +63 -0
  22. package/src/export/css.ts +28 -1
  23. package/src/export/index.ts +3 -0
  24. package/src/export/projection.ts +97 -13
  25. package/src/import/flow.ts +127 -6
  26. package/src/import/jsx/source/ast.ts +267 -0
  27. package/src/import/jsx/source/candidates.ts +72 -0
  28. package/src/import/jsx/source/evaluate.ts +300 -0
  29. package/src/import/jsx/source/index.ts +36 -0
  30. package/src/import/jsx/source/render.ts +543 -0
  31. package/src/import/jsx/source/report.ts +49 -0
  32. package/src/import/scene-graph.ts +19 -7
  33. package/src/index.ts +10 -0
  34. package/src/runtime/browser/runtime.ts +13 -5
  35. package/src/runtime/browser/sandbox.ts +176 -27
  36. package/src/runtime/css/scan.ts +45 -0
  37. package/src/runtime/css/url.ts +92 -0
  38. package/src/runtime/headless/styles.ts +71 -15
@@ -1,6 +1,6 @@
1
1
  import { serializeHTML } from "./behaviours/states/tailwind.js";
2
2
  import { isEqual } from "es-toolkit/predicate";
3
- import { isValid, toUint8Array } from "js-base64";
3
+ import { decode, isValid, toUint8Array } from "js-base64";
4
4
  import { TRANSPARENT } from "@pairdraw/scene-graph/constants";
5
5
  import { computeImageHash, imageSize } from "@pairdraw/scene-graph/images";
6
6
  import { autoLayoutSizingFields, fillSizingFields, layoutSizing, textAutoResizeFor } from "@pairdraw/scene-graph/layout";
@@ -11,18 +11,120 @@ import { GENERIC_FONT_FAMILIES_BY_CLASS, genericFontFamilyClass, parseCSSAlignIt
11
11
  import { SceneGraph } from "@pairdraw/scene-graph";
12
12
  import { normalizeEffects } from "@pairdraw/scene-graph/effects";
13
13
  import { textLayerName } from "@pairdraw/scene-graph/node-defaults";
14
- //#region src/runtime/browser/sandbox.ts
14
+ //#region src/runtime/css/scan.ts
15
15
  /**
16
- * What a styling sandbox inserts, with nothing the browser would execute: imported markup reaches
17
- * the frame as a design document, and an attribute such as `onerror` on an image runs there just as
18
- * it would on a page. A sandboxed iframe has no `allow-scripts`, so a script that got in is blocked
19
- * and reported; the shadow root is the app's own document, where it would really run.
20
- *
21
- * This is the executable-markup half of the sandbox copy. The network half, which rewrites fetchable
22
- * addresses so a sandbox never loads a remote resource, walks the same tree: when both are present
23
- * they are one pass over the nodes, and no pass may keep a `srcdoc`, which this one always drops.
16
+ * Visits each character outside quotes with its parenthesis depth after the character, so a
17
+ * caller can find a matching parenthesis or split at a top-level separator. An escaped character
18
+ * inside a quote is skipped, as CSS reads it.
24
19
  */
25
- /** Elements that hold a document or code of their own, which the sandbox shows as a plain box. */
20
+ function scanCSS(text, from, visit) {
21
+ let quote = "";
22
+ let depth = 0;
23
+ for (let index = from; index < text.length; index++) {
24
+ const character = text[index];
25
+ if (quote) {
26
+ if (character === "\\") index += 1;
27
+ else if (character === quote) quote = "";
28
+ continue;
29
+ }
30
+ if (character === "\"" || character === "'") {
31
+ quote = character;
32
+ continue;
33
+ }
34
+ if (character === "(") {
35
+ depth += 1;
36
+ continue;
37
+ }
38
+ if (character === ")") depth -= 1;
39
+ if (visit(character, index, depth)) return {
40
+ stop: index,
41
+ quote: quote !== "",
42
+ depth
43
+ };
44
+ }
45
+ return {
46
+ stop: -1,
47
+ quote: quote !== "",
48
+ depth
49
+ };
50
+ }
51
+ /** The index of the `)` closing a function whose arguments start at `from`, or -1 when unclosed. */
52
+ function closingParen(css, from) {
53
+ return scanCSS(css, from, (_character, _index, depth) => depth < 0).stop;
54
+ }
55
+ //#endregion
56
+ //#region src/runtime/css/url.ts
57
+ /**
58
+ * CSS spellings that a plain text match misses: `\72` is `r`, and a comment splits `url` in two.
59
+ * The styling sandbox decides on the decoded text, so an escaped or commented spelling cannot
60
+ * make it load a resource.
61
+ */
62
+ const CSS_ESCAPE = /\\([0-9a-f]{1,6})\s?/gi;
63
+ const CSS_COMMENT = /\/\*[\s\S]*?\*\//g;
64
+ /** A stylesheet value with its comments removed and its escapes decoded, as CSS parses it. */
65
+ function decodedCSS(text) {
66
+ return text.replace(CSS_COMMENT, "").replace(CSS_ESCAPE, (_, hex) => {
67
+ const code = Number.parseInt(hex, 16);
68
+ return code > 0 && code <= 1114111 ? String.fromCodePoint(code) : "";
69
+ });
70
+ }
71
+ /** Whether a declaration or rule loads a picture, in any spelling CSS allows. */
72
+ function mentionsURL(text) {
73
+ return /url\s*\(/i.test(decodedCSS(text));
74
+ }
75
+ /** Whether text can load anything: `url()`, `image-set()`, or a stylesheet import. */
76
+ function mentionsResource(text) {
77
+ return /url\s*\(|image-set\s*\(|@import/i.test(decodedCSS(text));
78
+ }
79
+ /** A resource that loads nothing over the network: an inline value or a document fragment. */
80
+ const LOCAL_RESOURCE = /^(?:data:|#|about:blank$)/i;
81
+ function isLocalResource(value) {
82
+ return LOCAL_RESOURCE.test(value.trim());
83
+ }
84
+ /** Every resource the text names is local, so keeping it cannot fetch anything. */
85
+ function resourcesAreLocal(text) {
86
+ const decoded = decodedCSS(text);
87
+ if (/@import/i.test(decoded)) return false;
88
+ for (const match of decoded.matchAll(/url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/gi)) if (!isLocalResource(match[1] || match[2] || match[3] || "")) return false;
89
+ for (const match of decoded.matchAll(/image-set\s*\(([^)]*)\)/gi)) for (const candidate of match[1].matchAll(/"([^"]*)"|'([^']*)'/g)) if (!isLocalResource(candidate[1] || candidate[2] || "")) return false;
90
+ return true;
91
+ }
92
+ /**
93
+ * A declaration list split on semicolons outside quotes and parentheses; null when a quote or
94
+ * parenthesis is unclosed, so a malformed style fails closed instead of being cut into fragments.
95
+ */
96
+ function splitDeclarations$1(text) {
97
+ const parts = [];
98
+ let start = 0;
99
+ const scan = scanCSS(text, 0, (character, index, depth) => {
100
+ if (character !== ";" || depth !== 0) return;
101
+ parts.push(text.slice(start, index));
102
+ start = index + 1;
103
+ });
104
+ if (scan.quote || scan.depth !== 0) return null;
105
+ parts.push(text.slice(start));
106
+ return parts;
107
+ }
108
+ /** A declaration list with every part that can load a resource dropped. */
109
+ function withoutResourceDeclarations(text) {
110
+ const parts = splitDeclarations$1(decodedCSS(text).replace(/@import[^;{}]*;?/gi, ""));
111
+ if (!parts) return "";
112
+ return parts.map((part) => part.trim()).filter((part) => part.length > 0 && (!mentionsResource(part) || resourcesAreLocal(part))).join("; ");
113
+ }
114
+ /**
115
+ * A pasted stylesheet with its resource-loading declarations and imports removed, keeping the
116
+ * rules that only style. A block the flat scan cannot take apart is dropped whole.
117
+ */
118
+ function withoutResourceRules(cssText) {
119
+ const cleaned = decodedCSS(cssText).replace(/@import[^;{}]*;?/gi, "").replace(/([^{}]*)\{([^{}]*)\}/g, (_, selector, body) => {
120
+ const declarations = withoutResourceDeclarations(body);
121
+ return declarations.length > 0 ? `${selector.trim()} { ${declarations} }` : "";
122
+ });
123
+ return resourcesAreLocal(cleaned) ? cleaned : "";
124
+ }
125
+ //#endregion
126
+ //#region src/runtime/browser/sandbox.ts
127
+ /** Elements that hold a document or code of their own; a script is emptied, a style is cleaned. */
26
128
  const CODE_TAGS = /* @__PURE__ */ new Set(["script", "style"]);
27
129
  /** Elements that load another document; their fallback content stays, the element does not. */
28
130
  const EMBEDDED_TAGS = /* @__PURE__ */ new Set([
@@ -50,27 +152,122 @@ function executableAttribute(name, value) {
50
152
  if (attribute.startsWith("on") || attribute === "srcdoc") return true;
51
153
  return EXECUTABLE_URL.test(withoutSchemeNoise(value));
52
154
  }
53
- function sandboxedNode(node) {
155
+ /** `url(...)` in a style attribute, an inline style value, or a stylesheet rule. */
156
+ const URL_FUNCTION = /url\(\s*(?:"([^"]*)"|'([^']*)'|([^)]*))\s*\)/gi;
157
+ /** A stylesheet loaded from elsewhere; the sanitizer drops it too, but not from JSX or CSS text. */
158
+ const CSS_IMPORT = /@import[^;]*;?/gi;
159
+ /** Attributes naming a resource the sandbox would load as soon as the element is live. */
160
+ const URL_ATTRIBUTES = {
161
+ src: true,
162
+ srcset: true,
163
+ imagesrcset: true,
164
+ poster: true,
165
+ background: true,
166
+ srcdoc: true,
167
+ data: true,
168
+ action: true,
169
+ formaction: true,
170
+ cite: true,
171
+ ping: true,
172
+ manifest: true,
173
+ longdesc: true,
174
+ profile: true,
175
+ usemap: true
176
+ };
177
+ /** Elements whose `href` addresses another document; everywhere else `href` may stay a link. */
178
+ const LINK_ELEMENTS = {
179
+ a: true,
180
+ area: true
181
+ };
182
+ /** The replacement for an address the sandbox must not fetch: a valid, local, empty resource. */
183
+ const INERT_URL = "url(\"data:,\")";
184
+ /** Every candidate address in a comma-separated `srcset` is local, so none of them is fetched. */
185
+ function isLocalSrcset(value) {
186
+ return value.split(",").every((candidate) => {
187
+ const address = candidate.trim().split(/\s+/)[0];
188
+ return !address || isLocalResource(address);
189
+ });
190
+ }
191
+ /** A quoted image candidate, as `image-set("…" 1x)` takes instead of a `url()`. */
192
+ const QUOTED_CANDIDATE = /"([^"]*)"|'([^']*)'/g;
193
+ /** `image-set(...)` and its WebKit spelling, whose arguments may hold quoted image sources. */
194
+ const IMAGE_SET_OPEN = /(?:-webkit-)?image-set\s*\(/gi;
195
+ /** A quoted value that is local, or the inert one; an image-set candidate without `url()`. */
196
+ function localCandidate(token, double, single) {
197
+ return isLocalResource(double || single || "") ? token : "\"data:,\"";
198
+ }
199
+ /** Every quoted source inside each `image-set(...)`, rewritten when it is not local. */
200
+ function withLocalImageSets(css) {
201
+ let result = "";
202
+ let last = 0;
203
+ for (const match of css.matchAll(IMAGE_SET_OPEN)) {
204
+ const start = match.index + match[0].length;
205
+ const end = closingParen(css, start);
206
+ if (end === -1) break;
207
+ result += css.slice(last, start) + css.slice(start, end).replace(QUOTED_CANDIDATE, localCandidate);
208
+ last = end;
209
+ }
210
+ return result + css.slice(last);
211
+ }
212
+ /** Style text and stylesheets with every fetchable resource replaced, so a pasted rule loads none. */
213
+ function withLocalResources(value) {
214
+ return withLocalImageSets(value.replace(URL_FUNCTION, (match, double, single, bare) => {
215
+ return isLocalResource(double || single || bare) ? match : INERT_URL;
216
+ }));
217
+ }
218
+ /** A pasted stylesheet, without its imports and with only local resources it may load. */
219
+ function sandboxCSS(cssText) {
220
+ return withLocalResources(decodedCSS(cssText).replace(CSS_IMPORT, ""));
221
+ }
222
+ function sandboxStyle(style) {
223
+ return style && Object.fromEntries(Object.entries(style).filter(([, value]) => !mentionsResource(value) || resourcesAreLocal(value)));
224
+ }
225
+ function sandboxAttribute(element, name, value) {
226
+ const lower = name.toLowerCase();
227
+ if (lower === "style") return withoutResourceDeclarations(value);
228
+ if (lower === "srcset" || lower === "imagesrcset") return isLocalSrcset(value) ? value : "";
229
+ if (lower === "href" || lower === "xlink:href") return LINK_ELEMENTS[element.tagName.toLowerCase()] || isLocalResource(value) ? value : "";
230
+ if (URL_ATTRIBUTES[lower]) return isLocalResource(value) ? value : "";
231
+ if (mentionsResource(value)) return resourcesAreLocal(value) ? value : "";
232
+ return value;
233
+ }
234
+ function sandboxChildren(element) {
235
+ const tagName = element.tagName.toLowerCase();
236
+ if (tagName === "style") return element.children.filter((child) => child.type === "text").map((child) => ({
237
+ ...child,
238
+ text: withoutResourceRules(child.text)
239
+ }));
240
+ if (CODE_TAGS.has(tagName)) return [];
241
+ return element.children.map(sandboxNode);
242
+ }
243
+ function sandboxNode(node) {
54
244
  if (node.type === "text") return node;
55
245
  const tagName = node.tagName.toLowerCase();
56
- const attrs = Object.fromEntries(Object.entries(node.attrs).filter(([name, value]) => !executableAttribute(name, value)));
246
+ const attrs = Object.fromEntries(Object.entries(node.attrs).filter(([name, value]) => !executableAttribute(name, value)).map(([name, value]) => [name, sandboxAttribute(node, name, value)]));
57
247
  return {
58
248
  ...node,
59
- tagName: CODE_TAGS.has(tagName) || EMBEDDED_TAGS.has(tagName) ? "div" : node.tagName,
249
+ tagName: CODE_TAGS.has(tagName) && tagName !== "style" || EMBEDDED_TAGS.has(tagName) ? "div" : node.tagName,
60
250
  attrs,
61
- children: CODE_TAGS.has(tagName) ? [] : node.children.map(sandboxedNode)
251
+ inlineStyle: sandboxStyle(node.inlineStyle),
252
+ children: sandboxChildren(node),
253
+ ...node.shader?.frame && !isLocalResource(node.shader.frame) ? { shader: {
254
+ ...node.shader,
255
+ frame: void 0
256
+ } } : {}
62
257
  };
63
258
  }
64
- /**
65
- * `document` as the styling sandbox inserts it: the same layers, with every executable attribute,
66
- * embedded document, and code element replaced by something inert. A replaced element keeps the
67
- * attributes that decide its box where the browser draws one; a layer's own styles still come from
68
- * the captured stylesheet, so reading computed styles answers the same question.
69
- */
70
- function sandboxedDesignDocument(document) {
259
+ /** The design document as the styling sandbox may see it: same tree, no fetchable address. */
260
+ function sandboxDocument(document) {
71
261
  return {
72
262
  ...document,
73
- children: document.children.map(sandboxedNode)
263
+ children: document.children.map(sandboxNode)
264
+ };
265
+ }
266
+ /** Exactly what a styling sandbox inserts: the markup it assigns, and the CSS it applies. */
267
+ function sandboxContent(document, cssText) {
268
+ return {
269
+ html: serializeHTML(sandboxDocument(document)),
270
+ css: sandboxCSS(cssText)
74
271
  };
75
272
  }
76
273
  //#endregion
@@ -113,6 +310,10 @@ const DEFAULT_COMPUTED_PROPERTIES = [
113
310
  "font-style",
114
311
  "font-weight",
115
312
  "gap",
313
+ "grid-column",
314
+ "grid-row",
315
+ "grid-template-columns",
316
+ "grid-template-rows",
116
317
  "height",
117
318
  "justify-content",
118
319
  "letter-spacing",
@@ -245,12 +446,13 @@ function applySandboxHostStyle(element) {
245
446
  async function computeStylesInShadowRoot(browserDocument, designDocument, cssText, options) {
246
447
  const host = browserDocument.createElement("div");
247
448
  applySandboxHostStyle(host);
449
+ const sandbox = sandboxContent(designDocument, cssText);
248
450
  const shadow = host.attachShadow({ mode: "open" });
249
451
  const style = browserDocument.createElement("style");
250
- style.textContent = cssText;
452
+ style.textContent = sandbox.css;
251
453
  shadow.append(style);
252
454
  const content = browserDocument.createElement("div");
253
- content.innerHTML = serializeHTML(sandboxedDesignDocument(designDocument));
455
+ content.innerHTML = sandbox.html;
254
456
  shadow.append(content);
255
457
  browserDocument.body.append(host);
256
458
  try {
@@ -271,11 +473,12 @@ async function computeStylesInIframe(browserDocument, designDocument, cssText, o
271
473
  iframeDocument.open();
272
474
  iframeDocument.write(`<!doctype html><html><head></head><body></body></html>`);
273
475
  iframeDocument.close();
476
+ const sandbox = sandboxContent(designDocument, cssText);
274
477
  const style = iframeDocument.createElement("style");
275
- style.textContent = cssText;
478
+ style.textContent = sandbox.css;
276
479
  iframeDocument.head.append(style);
277
480
  const content = iframeDocument.createElement("div");
278
- content.innerHTML = serializeHTML(sandboxedDesignDocument(designDocument));
481
+ content.innerHTML = sandbox.html;
279
482
  iframeDocument.body.append(content);
280
483
  await requestFrame(browserDocument);
281
484
  return copyComputedStyles(designDocument, content, options);
@@ -410,12 +613,126 @@ function elementDisplay(element, style) {
410
613
  */
411
614
  function flowOf(display) {
412
615
  if (display === "flex" || display === "inline-flex") return "flex";
616
+ if (display === "grid" || display === "inline-grid") return "grid";
413
617
  return display === "inline" ? "inline" : "block";
414
618
  }
619
+ /** The most tracks a `repeat()` may expand to, so one value cannot grow a document. */
620
+ const MAX_GRID_TRACKS = 24;
621
+ /** One column or row track of a grid, as CSS sizes it. */
622
+ function gridTrack(token) {
623
+ const value = token.trim().toLowerCase();
624
+ if (value === "auto" || value === "min-content" || value === "max-content") return {
625
+ sizing: "AUTO",
626
+ value: 0
627
+ };
628
+ if (value.startsWith("fit-content(")) return {
629
+ sizing: "AUTO",
630
+ value: 0
631
+ };
632
+ if (value.startsWith("minmax(")) {
633
+ const bounds = value.slice(7, -1).split(",");
634
+ return gridTrack(bounds.at(1) ?? bounds.at(0) ?? "");
635
+ }
636
+ const fraction = /^([\d.]+)fr$/.exec(value);
637
+ if (fraction) return {
638
+ sizing: "FR",
639
+ value: Number(fraction[1])
640
+ };
641
+ const length = /^(-?[\d.]+)(px|rem|em)$/.exec(value);
642
+ if (length) return {
643
+ sizing: "FIXED",
644
+ value: Number(length[1])
645
+ };
646
+ if (/^-?[\d.]+$/.test(value)) return {
647
+ sizing: "FIXED",
648
+ value: Number(value)
649
+ };
650
+ return null;
651
+ }
652
+ /**
653
+ * The tracks a `grid-template-columns` or `grid-template-rows` value names. `undefined` when the
654
+ * value has a track this document cannot place, as `auto-fit` needs a width known at layout time
655
+ * and a percentage track a container size; the caller then keeps the content in block flow.
656
+ */
657
+ function gridTracks(value) {
658
+ const trimmed = value?.trim();
659
+ if (!trimmed || trimmed === "none" || trimmed === "subgrid") return void 0;
660
+ const tracks = [];
661
+ for (const token of splitCSSValue(trimmed)) {
662
+ const repeat = /^repeat\(\s*([^,]+),\s*(.+)\)$/i.exec(token);
663
+ if (repeat) {
664
+ const count = Number(repeat[1]);
665
+ if (!Number.isInteger(count) || count < 1 || count > MAX_GRID_TRACKS) return void 0;
666
+ const inner = gridTracks(repeat[2]);
667
+ if (!inner || inner.length === 0) return void 0;
668
+ for (let index = 0; index < count; index++) tracks.push(...inner);
669
+ continue;
670
+ }
671
+ const track = gridTrack(token);
672
+ if (!track) return void 0;
673
+ tracks.push(track);
674
+ }
675
+ return tracks.length > 0 && tracks.length <= MAX_GRID_TRACKS ? tracks : void 0;
676
+ }
677
+ /** The lines `grid-column` or `grid-row` names: a start line and a span, or a bare span. */
678
+ function gridLines(value) {
679
+ const trimmed = value?.trim().toLowerCase();
680
+ if (!trimmed) return null;
681
+ const span = /^span\s+(\d+)$/.exec(trimmed);
682
+ if (span) return {
683
+ start: 0,
684
+ span: Number(span[1])
685
+ };
686
+ const lines = /^(\d+)\s*\/\s*(?:span\s+)?(\d+)$/.exec(trimmed);
687
+ if (lines) {
688
+ const start = Number(lines[1]);
689
+ const end = Number(lines[2]);
690
+ return {
691
+ start,
692
+ span: Math.max(1, end - start)
693
+ };
694
+ }
695
+ return null;
696
+ }
415
697
  /** Whether the element sits in a line rather than on its own row, so it hugs its content. */
416
698
  function isInlineLevel(display) {
417
699
  return display.startsWith("inline");
418
700
  }
701
+ /** Where a grid places a child, from `grid-column` and `grid-row`. */
702
+ function applyGridPlacement(node, style) {
703
+ const column = gridLines(pickStyle(style, "grid-column") ?? gridColumnShorthand(style));
704
+ const row = gridLines(pickStyle(style, "grid-row") ?? gridRowShorthand(style));
705
+ if (!column && !row) return;
706
+ node.gridPosition = {
707
+ column: column?.start ?? 0,
708
+ row: row?.start ?? 0,
709
+ columnSpan: Math.max(1, column?.span ?? 1),
710
+ rowSpan: Math.max(1, row?.span ?? 1)
711
+ };
712
+ }
713
+ /** `grid-area: 2 / 1 / 4 / 3`, as a start line and a span on each axis. */
714
+ function gridColumnShorthand(style) {
715
+ const heading = gridAreaLines(style);
716
+ if (!heading) return void 0;
717
+ return `${heading.startColumn} / ${heading.endColumn}`;
718
+ }
719
+ function gridRowShorthand(style) {
720
+ const heading = gridAreaLines(style);
721
+ if (!heading) return void 0;
722
+ return `${heading.startRow} / ${heading.endRow}`;
723
+ }
724
+ function gridAreaLines(style) {
725
+ const parts = pickStyle(style, "grid-area")?.trim().split(/\s*\/\s*/);
726
+ if (!parts || parts.length < 2) return null;
727
+ const startRow = parts.at(0) ?? "";
728
+ const startColumn = parts.at(1) ?? "";
729
+ return {
730
+ startRow,
731
+ startColumn,
732
+ endRow: parts.at(2) ?? startRow,
733
+ endColumn: parts.at(3) ?? startColumn
734
+ };
735
+ }
419
736
  function textAlignAxis(element, style) {
420
737
  const align = pickStyle(style, "text-align")?.trim().toLowerCase();
421
738
  if (align === "center") return "CENTER";
@@ -432,7 +749,17 @@ function applyContainerLayout(node, element, style, flow) {
432
749
  node.layoutWrap = pickStyle(style, "flex-wrap") === "wrap" ? "WRAP" : "NO_WRAP";
433
750
  return;
434
751
  }
435
- if (flow === "block") {
752
+ if (flow === "grid") {
753
+ const columns = gridTracks(pickStyle(style, "grid-template-columns"));
754
+ if (columns) {
755
+ node.layoutMode = "GRID";
756
+ node.gridTemplateColumns = columns;
757
+ const rows = gridTracks(pickStyle(style, "grid-template-rows"));
758
+ if (rows) node.gridTemplateRows = rows;
759
+ return;
760
+ }
761
+ }
762
+ if (flow === "grid" || flow === "block") {
436
763
  node.layoutMode = "VERTICAL";
437
764
  if (CENTERED_TAGS.has(element.tagName.toLowerCase())) {
438
765
  node.primaryAxisAlign = "CENTER";
@@ -511,9 +838,10 @@ function applyFlowSizing(graph, node, style, display, parentFlow) {
511
838
  fixedWidth: parseCSSNumber(pickStyle(style, "width")) !== null,
512
839
  fixedHeight: parseCSSNumber(pickStyle(style, "height")) !== null
513
840
  };
514
- if (node.layoutMode !== "NONE" && node.layoutMode !== "GRID") {
841
+ if (node.layoutMode !== "NONE") {
515
842
  const own = (fixed) => fixed ? "FIXED" : "HUG";
516
- Object.assign(node, autoLayoutSizingFields(node.layoutMode, own(size.fixedWidth), own(size.fixedHeight)));
843
+ const direction = node.layoutMode === "GRID" ? "HORIZONTAL" : node.layoutMode;
844
+ Object.assign(node, autoLayoutSizingFields(direction, own(size.fixedWidth), own(size.fixedHeight)));
517
845
  }
518
846
  if (node.type === "TEXT" && staysOnItsLines(style)) {
519
847
  applyTextSizing(graph, node, {
@@ -1528,10 +1856,15 @@ function applyCornerRadii(node, style) {
1528
1856
  node.bottomLeftRadius
1529
1857
  ].some((radius) => radius !== fallback);
1530
1858
  }
1531
- function applyFlexGap(node, style) {
1859
+ function applyAutoLayoutGap(node, style) {
1532
1860
  const gap = firstCSSNumber(style, "gap");
1533
1861
  const rowGap = firstCSSNumber(style, "row-gap");
1534
1862
  const columnGap = firstCSSNumber(style, "column-gap");
1863
+ if (node.layoutMode === "GRID") {
1864
+ node.gridColumnGap = columnGap ?? gap ?? 0;
1865
+ node.gridRowGap = rowGap ?? gap ?? 0;
1866
+ return;
1867
+ }
1535
1868
  const isHorizontal = node.layoutMode === "HORIZONTAL";
1536
1869
  const isWrapped = node.layoutWrap === "WRAP";
1537
1870
  node.itemSpacing = (isHorizontal ? columnGap : rowGap) ?? gap ?? 0;
@@ -1601,7 +1934,8 @@ function bytesFromDataURL(value) {
1601
1934
  }
1602
1935
  function applyImageFill(graph, node, element, style) {
1603
1936
  if (element.tagName.toLowerCase() !== "img") return;
1604
- const source = element.attrs.src;
1937
+ const kept = element.attrs["data-image-source-b64"];
1938
+ const source = element.attrs.src || (kept && isValid(kept) ? decode(kept) : void 0);
1605
1939
  const bytes = bytesFromDataURL(source);
1606
1940
  if (!bytes) {
1607
1941
  if (source) node.pluginData = [...node.pluginData, {
@@ -1627,6 +1961,7 @@ function applyElementStyle(graph, node, element, style) {
1627
1961
  applyBoxSizing(node, style);
1628
1962
  applyPositioning(node, style);
1629
1963
  applyPadding(node, style);
1964
+ applyGridPlacement(node, style);
1630
1965
  const background = backgroundPaint(graph, style, node);
1631
1966
  if (background.fills.length > 0) node.fills = background.fills;
1632
1967
  for (const layer of background.layers) addBackgroundLayer(graph, node, layer);
@@ -1811,8 +2146,9 @@ function holdsInlineBoxes(element) {
1811
2146
  }
1812
2147
  /** The flow a box lays its children out in, and whether they are one text instead. */
1813
2148
  function containerFlow(element, display) {
1814
- const own = hasContent(element) || flowOf(display) === "flex" ? flowOf(display) : null;
1815
- const richText = own !== "flex" && holdsRichText(element);
2149
+ const flowKind = flowOf(display);
2150
+ const own = hasContent(element) || flowKind === "flex" || flowKind === "grid" ? flowKind : null;
2151
+ const richText = own !== "flex" && own !== "grid" && holdsRichText(element);
1816
2152
  const lines = own === "block" && !richText && holdsInlineBoxes(element);
1817
2153
  return {
1818
2154
  flow: lines ? "inline" : own,
@@ -1822,7 +2158,7 @@ function containerFlow(element, display) {
1822
2158
  }
1823
2159
  /** Builds a container's children and orders them the way CSS paints them. */
1824
2160
  function paintChildren(graph, node, element, style, flow) {
1825
- const children = flow === "flex" ? element.children.toSorted(byFlexOrder) : element.children;
2161
+ const children = flow === "flex" || flow === "grid" ? element.children.toSorted(byFlexOrder) : element.children;
1826
2162
  const painted = [];
1827
2163
  for (const child of children) {
1828
2164
  const layer = createDesignNode(graph, node.id, child, flow, inheritedTextStyle(element, style));
@@ -1851,7 +2187,7 @@ function createElementNode(graph, parentId, element, parentFlow) {
1851
2187
  const { flow, richText, lines } = containerFlow(element, display);
1852
2188
  if (flow) {
1853
2189
  applyContainerLayout(node, element, style, flow);
1854
- if (flow === "flex") applyFlexGap(node, style);
2190
+ if (flow === "flex" || flow === "grid") applyAutoLayoutGap(node, style);
1855
2191
  if (lines) node.layoutWrap = "WRAP";
1856
2192
  }
1857
2193
  applyFlowSizing(graph, node, style, display, parentFlow);
@@ -2105,6 +2441,6 @@ async function browserTailwindJSXToSceneGraph(input, candidates, options = {}) {
2105
2441
  return designDocumentToSceneGraph(await browserTailwindJSXToDesignDocument(input, candidates, options), options);
2106
2442
  }
2107
2443
  //#endregion
2108
- export { Fragment, INLINE_TAGS, browserHTMLToDesignDocument, browserHTMLToSceneGraph, browserJSXToDesignDocument, browserJSXToSceneGraph, browserTailwindHTMLToDesignDocument, browserTailwindHTMLToSceneGraph, browserTailwindJSXToDesignDocument, browserTailwindJSXToSceneGraph, createBrowserCSSRuntime, designDocumentToSceneGraph, jsx, jsxToDesignDocumentCore, jsxs, mergeCSSText, resolveFontFamilyStack };
2444
+ export { Fragment, INLINE_TAGS, browserHTMLToDesignDocument, browserHTMLToSceneGraph, browserJSXToDesignDocument, browserJSXToSceneGraph, browserTailwindHTMLToDesignDocument, browserTailwindHTMLToSceneGraph, browserTailwindJSXToDesignDocument, browserTailwindJSXToSceneGraph, createBrowserCSSRuntime, decodedCSS, designDocumentToSceneGraph, jsx, jsxToDesignDocumentCore, jsxs, mentionsResource, mentionsURL, mergeCSSText, resolveFontFamilyStack, withoutResourceRules };
2109
2445
 
2110
2446
  //# sourceMappingURL=browser.js.map