@pairdraw/dom-css 0.19.2 → 0.21.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.
@@ -1,22 +1,87 @@
1
1
  import { serializeHTML } from "./behaviours/states/tailwind.js";
2
2
  import { isEqual } from "es-toolkit/predicate";
3
3
  import { isValid, toUint8Array } from "js-base64";
4
- import { DEFAULT_FONT_FAMILY, TRANSPARENT } from "@pairdraw/scene-graph/constants";
5
- import { computeImageHash } from "@pairdraw/scene-graph/images";
4
+ import { TRANSPARENT } from "@pairdraw/scene-graph/constants";
5
+ import { computeImageHash, imageSize } from "@pairdraw/scene-graph/images";
6
6
  import { autoLayoutSizingFields, fillSizingFields, layoutSizing, textAutoResizeFor } from "@pairdraw/scene-graph/layout";
7
7
  import { countBy } from "es-toolkit/array";
8
8
  import { blurRadiusForSigma } from "@pairdraw/scene-graph/geometry";
9
9
  import { pick } from "es-toolkit";
10
- import { parseCSSAlignItems, parseCSSAlignSelf, parseCSSBackgroundImages, parseCSSColor, parseCSSFlexDirection, parseCSSFontFamilies, parseCSSFontFamily, parseCSSJustifyContent, parseCSSLetterSpacing, parseCSSLineHeight, parseCSSNumber, parseCSSShadows } from "@pairdraw/scene-graph/css";
10
+ import { GENERIC_FONT_FAMILIES_BY_CLASS, genericFontFamilyClass, parseCSSAlignItems, parseCSSAlignSelf, parseCSSBackgroundImages, parseCSSColor, parseCSSFlexDirection, parseCSSFontFamilies, parseCSSFontFamily, parseCSSJustifyContent, parseCSSLetterSpacing, parseCSSLineHeight, parseCSSNumber, parseCSSShadows, splitCSSValue } from "@pairdraw/scene-graph/css";
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
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.
24
+ */
25
+ /** Elements that hold a document or code of their own, which the sandbox shows as a plain box. */
26
+ const CODE_TAGS = /* @__PURE__ */ new Set(["script", "style"]);
27
+ /** Elements that load another document; their fallback content stays, the element does not. */
28
+ const EMBEDDED_TAGS = /* @__PURE__ */ new Set([
29
+ "applet",
30
+ "embed",
31
+ "frame",
32
+ "frameset",
33
+ "iframe",
34
+ "object"
35
+ ]);
36
+ /**
37
+ * `value` without the characters a browser ignores inside a URL scheme: controls and space, so
38
+ * `java\tscript:` runs as `javascript:`.
39
+ */
40
+ function withoutSchemeNoise(value) {
41
+ let plain = "";
42
+ for (const char of value) if (char.charCodeAt(0) > 32) plain += char;
43
+ return plain;
44
+ }
45
+ /** A URL a browser runs as script or reads as a document of its own. */
46
+ const EXECUTABLE_URL = /^(?:javascript|vbscript|data:text\/html)/i;
47
+ /** Whether the browser would run this attribute: an event handler or an executable URL. */
48
+ function executableAttribute(name, value) {
49
+ const attribute = name.toLowerCase();
50
+ if (attribute.startsWith("on") || attribute === "srcdoc") return true;
51
+ return EXECUTABLE_URL.test(withoutSchemeNoise(value));
52
+ }
53
+ function sandboxedNode(node) {
54
+ if (node.type === "text") return node;
55
+ const tagName = node.tagName.toLowerCase();
56
+ const attrs = Object.fromEntries(Object.entries(node.attrs).filter(([name, value]) => !executableAttribute(name, value)));
57
+ return {
58
+ ...node,
59
+ tagName: CODE_TAGS.has(tagName) || EMBEDDED_TAGS.has(tagName) ? "div" : node.tagName,
60
+ attrs,
61
+ children: CODE_TAGS.has(tagName) ? [] : node.children.map(sandboxedNode)
62
+ };
63
+ }
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) {
71
+ return {
72
+ ...document,
73
+ children: document.children.map(sandboxedNode)
74
+ };
75
+ }
76
+ //#endregion
14
77
  //#region src/runtime/browser/runtime.ts
15
78
  const DEFAULT_COMPUTED_PROPERTIES = [
16
79
  "align-items",
17
80
  "aspect-ratio",
18
81
  "background-color",
82
+ "background-clip",
19
83
  "background-image",
84
+ "background-origin",
20
85
  "border-bottom-color",
21
86
  "border-bottom-style",
22
87
  "border-bottom-left-radius",
@@ -56,6 +121,7 @@ const DEFAULT_COMPUTED_PROPERTIES = [
56
121
  "max-height",
57
122
  "max-width",
58
123
  "min-height",
124
+ "isolation",
59
125
  "min-width",
60
126
  "object-fit",
61
127
  "opacity",
@@ -73,7 +139,8 @@ const DEFAULT_COMPUTED_PROPERTIES = [
73
139
  "text-transform",
74
140
  "top",
75
141
  "white-space",
76
- "width"
142
+ "width",
143
+ "z-index"
77
144
  ];
78
145
  function resolveBrowserDocument$1(documentOverride) {
79
146
  if (documentOverride) return documentOverride;
@@ -183,7 +250,7 @@ async function computeStylesInShadowRoot(browserDocument, designDocument, cssTex
183
250
  style.textContent = cssText;
184
251
  shadow.append(style);
185
252
  const content = browserDocument.createElement("div");
186
- content.innerHTML = serializeHTML(designDocument);
253
+ content.innerHTML = serializeHTML(sandboxedDesignDocument(designDocument));
187
254
  shadow.append(content);
188
255
  browserDocument.body.append(host);
189
256
  try {
@@ -208,7 +275,7 @@ async function computeStylesInIframe(browserDocument, designDocument, cssText, o
208
275
  style.textContent = cssText;
209
276
  iframeDocument.head.append(style);
210
277
  const content = iframeDocument.createElement("div");
211
- content.innerHTML = serializeHTML(designDocument);
278
+ content.innerHTML = serializeHTML(sandboxedDesignDocument(designDocument));
212
279
  iframeDocument.body.append(content);
213
280
  await requestFrame(browserDocument);
214
281
  return copyComputedStyles(designDocument, content, options);
@@ -465,36 +532,394 @@ function mergeCSSText(...parts) {
465
532
  return text.length > 0 ? text.join("\n") : void 0;
466
533
  }
467
534
  //#endregion
468
- //#region src/import/fonts.ts
469
- /** CSS generic families, by the concrete face class they stand for. */
470
- const GENERIC_FAMILIES = {
471
- "sans-serif": "sans-serif",
472
- "ui-sans-serif": "sans-serif",
473
- "system-ui": "sans-serif",
474
- "-apple-system": "sans-serif",
475
- blinkmacsystemfont: "sans-serif",
476
- serif: "serif",
477
- "ui-serif": "serif",
478
- monospace: "monospace",
479
- "ui-monospace": "monospace"
480
- };
481
- /** Known system faces of each class, best first. The app bundles Inter for sans-serif. */
482
- const DEFAULT_FAMILIES = {
483
- "sans-serif": [DEFAULT_FONT_FAMILY],
484
- serif: [
485
- "Georgia",
486
- "Times New Roman",
487
- "Times"
488
- ],
489
- monospace: [
490
- "Menlo",
491
- "SF Mono",
492
- "Consolas",
493
- "Courier New"
494
- ]
535
+ //#region src/import/background-pictures.ts
536
+ const REPEAT_KEYWORDS = /* @__PURE__ */ new Set([
537
+ "repeat",
538
+ "no-repeat",
539
+ "repeat-x",
540
+ "repeat-y",
541
+ "space",
542
+ "round"
543
+ ]);
544
+ const BOX_KEYWORDS = /* @__PURE__ */ new Set([
545
+ "border-box",
546
+ "padding-box",
547
+ "content-box"
548
+ ]);
549
+ const ATTACHMENT_KEYWORDS = /* @__PURE__ */ new Set([
550
+ "scroll",
551
+ "fixed",
552
+ "local"
553
+ ]);
554
+ const GRADIENT_PREFIXES = [
555
+ "linear-gradient(",
556
+ "radial-gradient(",
557
+ "conic-gradient(",
558
+ "repeating-linear-gradient(",
559
+ "repeating-radial-gradient(",
560
+ "repeating-conic-gradient("
561
+ ];
562
+ /** Splits a CSS value list at its top-level commas, keeping functions whole. */
563
+ function splitLayers(value) {
564
+ const layers = [];
565
+ let depth = 0;
566
+ let start = 0;
567
+ for (let index = 0; index < value.length; index++) {
568
+ const character = value[index];
569
+ if (character === "(") depth++;
570
+ else if (character === ")") depth = Math.max(0, depth - 1);
571
+ else if (character === "," && depth === 0) {
572
+ layers.push(value.slice(start, index).trim());
573
+ start = index + 1;
574
+ }
575
+ }
576
+ const last = value.slice(start).trim();
577
+ if (last) layers.push(last);
578
+ return layers;
579
+ }
580
+ /** The value a property list gives layer `index`, repeating its last entry as CSS does. */
581
+ function at(list, index) {
582
+ return list[Math.min(index, list.length - 1)];
583
+ }
584
+ /** Splits a value into its `url(...)` and gradient functions and the words around them. */
585
+ function splitBackgroundFunctions(value) {
586
+ let image = "";
587
+ let depth = 0;
588
+ let start = -1;
589
+ let end = -1;
590
+ for (let index = 0; index < value.length; index++) {
591
+ const character = value[index];
592
+ if (character === "(") {
593
+ if (depth === 0) start = index;
594
+ depth++;
595
+ } else if (character === ")") {
596
+ depth--;
597
+ if (depth === 0) end = index;
598
+ } else if (depth === 0 && character === " ") continue;
599
+ if (depth === 0 && end !== -1) {
600
+ const name = value.slice(0, start).trim().split(/[\s,]/).pop() ?? "";
601
+ const candidate = `${name}${value.slice(start, end + 1)}`;
602
+ if (name === "url" || GRADIENT_PREFIXES.some((prefix) => candidate.startsWith(prefix))) {
603
+ image = candidate;
604
+ const before = value.slice(0, start).trim().split(/\s+/);
605
+ const after = value.slice(end + 1).trim();
606
+ return {
607
+ image,
608
+ rest: [...before.slice(0, -1), after].join(" ").trim()
609
+ };
610
+ }
611
+ start = -1;
612
+ end = -1;
613
+ }
614
+ }
615
+ return {
616
+ image,
617
+ rest: value
618
+ };
619
+ }
620
+ function parseShorthand(layer) {
621
+ const { image, rest } = splitBackgroundFunctions(layer);
622
+ const [positionPart = "", sizePart = ""] = rest.split("/");
623
+ const words = splitCSSValue(positionPart.toLowerCase());
624
+ const sizes = splitCSSValue(sizePart.toLowerCase());
625
+ const result = {
626
+ image,
627
+ size: "auto",
628
+ position: "0% 0%",
629
+ repeat: "repeat",
630
+ origin: "padding-box",
631
+ clip: "border-box"
632
+ };
633
+ const places = [];
634
+ let sawOrigin = false;
635
+ let sawClip = false;
636
+ for (const word of words) if (REPEAT_KEYWORDS.has(word)) result.repeat = word;
637
+ else if (BOX_KEYWORDS.has(word)) {
638
+ if (!sawOrigin) {
639
+ result.origin = word;
640
+ sawOrigin = true;
641
+ } else {
642
+ result.clip = word;
643
+ sawClip = true;
644
+ }
645
+ } else if (ATTACHMENT_KEYWORDS.has(word)) continue;
646
+ else if (/^[\d.+-]/.test(word) || [
647
+ "left",
648
+ "right",
649
+ "center",
650
+ "top",
651
+ "bottom"
652
+ ].includes(word)) places.push(word);
653
+ const sizing = sizes.filter((word) => !REPEAT_KEYWORDS.has(word) && !BOX_KEYWORDS.has(word));
654
+ if (sizing.length > 0) result.size = sizing.slice(0, 2).join(" ");
655
+ for (const word of sizes) if (REPEAT_KEYWORDS.has(word)) result.repeat = word;
656
+ else if (BOX_KEYWORDS.has(word)) {
657
+ if (!sawOrigin) {
658
+ result.origin = word;
659
+ sawOrigin = true;
660
+ } else {
661
+ result.clip = word;
662
+ sawClip = true;
663
+ }
664
+ }
665
+ if (!sawClip && sawOrigin) result.clip = result.origin;
666
+ if (places.length === 1) result.position = places[0];
667
+ else if (places.length >= 2) result.position = places.slice(-2).join(" ");
668
+ return result;
669
+ }
670
+ /** The background layers of an element, top layer first, from the shorthand or the longhands. */
671
+ function backgroundLayers(style, width = 1, height = 1) {
672
+ const shorthand = splitLayers(pickStyle(style, "background") ?? "");
673
+ if (shorthand.length > 0) return shorthand.map((layer) => parseShorthand(layer));
674
+ const parsed = parseCSSBackgroundImages(pickStyle(style, "background-image"), width, height);
675
+ const sizes = splitLayers(pickStyle(style, "background-size") ?? "");
676
+ const positions = splitLayers(pickStyle(style, "background-position") ?? "");
677
+ const repeats = splitLayers(pickStyle(style, "background-repeat") ?? "");
678
+ const origins = splitLayers(pickStyle(style, "background-origin") ?? "");
679
+ const clips = splitLayers(pickStyle(style, "background-clip") ?? "");
680
+ return parsed.map((layer, index) => ({
681
+ image: layer.kind === "image" ? `url(${layer.url})` : "",
682
+ gradient: layer.kind === "gradient" ? layer.fill : void 0,
683
+ size: at(sizes, index) ?? "auto",
684
+ position: at(positions, index) ?? "0% 0%",
685
+ repeat: at(repeats, index) ?? "repeat",
686
+ origin: at(origins, index) ?? "padding-box",
687
+ clip: at(clips, index) ?? "border-box"
688
+ }));
689
+ }
690
+ /** A length or percentage of `total`, as one value of `background-size` or `-position` gives. */
691
+ function lengthOf(value, total) {
692
+ if (!value) return null;
693
+ const trimmed = value.trim();
694
+ const percent = /^(-?[\d.]+)%$/.exec(trimmed);
695
+ if (percent) {
696
+ const share = Number.parseFloat(percent[1]);
697
+ return Number.isFinite(share) ? total * share / 100 : null;
698
+ }
699
+ const pixels = /^(-?[\d.]+)(?:px)?$/.exec(trimmed);
700
+ if (!pixels) return null;
701
+ const number = Number.parseFloat(pixels[1]);
702
+ return Number.isFinite(number) ? number : null;
703
+ }
704
+ /** The size `background-size` draws a picture of `natural` size at in `box`. */
705
+ function pictureSize(size, box, natural) {
706
+ const sizing = size.trim().toLowerCase();
707
+ if (sizing === "cover" || sizing === "contain") {
708
+ const scale = (sizing === "cover" ? Math.max : Math.min)(box.width / natural.width, box.height / natural.height);
709
+ return {
710
+ width: natural.width * scale,
711
+ height: natural.height * scale
712
+ };
713
+ }
714
+ const [across, down = "auto"] = splitCSSValue(sizing);
715
+ const width = across === "auto" ? null : lengthOf(across, box.width);
716
+ const height = down === "auto" ? null : lengthOf(down, box.height);
717
+ if (width === null && height === null) return natural;
718
+ if (width === null && height !== null) return {
719
+ width: height * natural.width / natural.height,
720
+ height
721
+ };
722
+ if (width !== null && height === null) return {
723
+ width,
724
+ height: width * natural.height / natural.width
725
+ };
726
+ return {
727
+ width: width ?? natural.width,
728
+ height: height ?? natural.height
729
+ };
730
+ }
731
+ const POSITION_KEYWORDS = {
732
+ left: "0%",
733
+ top: "0%",
734
+ center: "50%",
735
+ right: "100%",
736
+ bottom: "100%"
495
737
  };
738
+ /** Where `background-position` puts a picture of `size` in `box`: a percentage of the room left. */
739
+ function pictureOffset(position, box, size) {
740
+ const [across = "50%", down = "50%"] = splitCSSValue(position.trim().toLowerCase()).map((value) => POSITION_KEYWORDS[value] ?? value);
741
+ const along = (value, room, total) => {
742
+ if (value.endsWith("%")) {
743
+ const number = Number.parseFloat(value);
744
+ return Number.isFinite(number) ? room * number / 100 : room / 2;
745
+ }
746
+ return lengthOf(value, total) ?? room / 2;
747
+ };
748
+ return {
749
+ x: along(across, box.width - size.width, box.width),
750
+ y: along(down, box.height - size.height, box.height)
751
+ };
752
+ }
753
+ function cropTransform(area, picture) {
754
+ return {
755
+ m00: area.width / picture.width,
756
+ m01: 0,
757
+ m02: (area.x - picture.x) / picture.width,
758
+ m10: 0,
759
+ m11: area.height / picture.height,
760
+ m12: (area.y - picture.y) / picture.height
761
+ };
762
+ }
763
+ function cropFill(imageHash, imageTransform) {
764
+ return {
765
+ type: "IMAGE",
766
+ imageHash,
767
+ imageScaleMode: "CROP",
768
+ imageTransform,
769
+ color: TRANSPARENT,
770
+ opacity: 1,
771
+ visible: true
772
+ };
773
+ }
774
+ function borderWidth(style, side) {
775
+ const parsed = lengthOf(pickStyle(style, `border-${side}-width`) ?? pickStyle(style, "border-width"), 0);
776
+ return parsed === null || parsed < 0 ? 0 : parsed;
777
+ }
778
+ function paddingWidth(style, side) {
779
+ const parsed = lengthOf(pickStyle(style, `padding-${side}`), 0);
780
+ return parsed === null || parsed < 0 ? 0 : parsed;
781
+ }
782
+ function boxInsets(box, style) {
783
+ const border = {
784
+ top: borderWidth(style, "top"),
785
+ right: borderWidth(style, "right"),
786
+ bottom: borderWidth(style, "bottom"),
787
+ left: borderWidth(style, "left")
788
+ };
789
+ if (box === "padding-box") return border;
790
+ if (box !== "content-box") return {
791
+ top: 0,
792
+ right: 0,
793
+ bottom: 0,
794
+ left: 0
795
+ };
796
+ return {
797
+ top: border.top + paddingWidth(style, "top"),
798
+ right: border.right + paddingWidth(style, "right"),
799
+ bottom: border.bottom + paddingWidth(style, "bottom"),
800
+ left: border.left + paddingWidth(style, "left")
801
+ };
802
+ }
803
+ function insetArea(node, insets) {
804
+ return {
805
+ x: insets.left,
806
+ y: insets.top,
807
+ width: Math.max(0, node.width - insets.left - insets.right),
808
+ height: Math.max(0, node.height - insets.top - insets.bottom)
809
+ };
810
+ }
811
+ /** Adds a layer's picture to the stack, at the area it shows when it covers part of its box. */
812
+ function placePicture(graph, node, style, layer, stack) {
813
+ const images = parseCSSBackgroundImages(layer.image, node.width, node.height);
814
+ for (const image of images) {
815
+ if (image.kind === "gradient") {
816
+ stack.push({
817
+ fill: image.fill,
818
+ picture: false
819
+ });
820
+ continue;
821
+ }
822
+ const bytes = bytesFromDataURL$1(image.url);
823
+ if (!bytes) continue;
824
+ const natural = imageSize(bytes);
825
+ if (!natural || natural.width <= 0 || natural.height <= 0) continue;
826
+ const imageHash = computeImageHash(bytes);
827
+ graph.images.set(imageHash, bytes);
828
+ const origin = insetArea(node, boxInsets(layer.origin, style));
829
+ const size = pictureSize(layer.size, origin, natural);
830
+ if (size.width <= 0 || size.height <= 0) continue;
831
+ const clip = insetArea(node, boxInsets(layer.clip, style));
832
+ if (layer.repeat !== "no-repeat" && layer.repeat !== "space" && layer.repeat !== "round" && (layer.size.trim() === "auto" || layer.size.trim() === "auto auto")) {
833
+ stack.push({
834
+ fill: {
835
+ type: "IMAGE",
836
+ imageHash,
837
+ imageScaleMode: "TILE",
838
+ color: TRANSPARENT,
839
+ opacity: 1,
840
+ visible: true
841
+ },
842
+ picture: true
843
+ });
844
+ continue;
845
+ }
846
+ const offset = pictureOffset(layer.position, origin, size);
847
+ const picture = {
848
+ x: origin.x + offset.x,
849
+ y: origin.y + offset.y,
850
+ ...size
851
+ };
852
+ const left = Math.max(clip.x, picture.x);
853
+ const top = Math.max(clip.y, picture.y);
854
+ const right = Math.min(clip.x + clip.width, picture.x + picture.width);
855
+ const bottom = Math.min(clip.y + clip.height, picture.y + picture.height);
856
+ if (right <= left || bottom <= top) continue;
857
+ const area = {
858
+ x: left,
859
+ y: top,
860
+ width: right - left,
861
+ height: bottom - top
862
+ };
863
+ const fill = cropFill(imageHash, cropTransform(area, picture));
864
+ if (area.x <= .5 && area.y <= .5 && area.width >= node.width - 1 && area.height >= node.height - 1) stack.push({
865
+ fill,
866
+ picture: true
867
+ });
868
+ else stack.push({
869
+ area,
870
+ fill,
871
+ picture: true
872
+ });
873
+ }
874
+ }
875
+ /**
876
+ * Reads an element's background layers: the color, gradients, tiles and pictures placed where
877
+ * `background-size`, `-position`, `-repeat`, `-origin`, and `-clip` put them, bottom layer first.
878
+ * Every layer stays a fill while all of them cover the box; as soon as one covers part of it, the
879
+ * whole stack becomes layers of their own, so CSS paint order survives across the two kinds.
880
+ */
881
+ function backgroundPaint(graph, style, node) {
882
+ const color = fillFromColor(style);
883
+ const layers = backgroundLayers(style, node.width, node.height).reverse();
884
+ const stack = [];
885
+ for (const layer of layers) {
886
+ if (layer.gradient) {
887
+ stack.push({
888
+ fill: layer.gradient,
889
+ picture: false
890
+ });
891
+ continue;
892
+ }
893
+ placePicture(graph, node, style, layer, stack);
894
+ }
895
+ if (stack.every((layer) => layer.area === void 0)) {
896
+ const fills = stack.map((layer) => layer.fill);
897
+ return {
898
+ fills: color ? [color, ...fills] : fills,
899
+ layers: []
900
+ };
901
+ }
902
+ return {
903
+ fills: color ? [color] : [],
904
+ layers: stack
905
+ };
906
+ }
907
+ function fillFromColor(style) {
908
+ return colorToFillFromCSS(pickStyle(style, "background-color"))[0] ?? null;
909
+ }
910
+ function bytesFromDataURL$1(value) {
911
+ const match = value ? /^data:[^,]*;base64,([\s\S]*)$/.exec(value.trim()) : null;
912
+ if (!match) return null;
913
+ try {
914
+ return toUint8Array(match[1]);
915
+ } catch {
916
+ return null;
917
+ }
918
+ }
919
+ //#endregion
920
+ //#region src/import/fonts.ts
496
921
  function defaultFamily(kind, options) {
497
- const candidates = DEFAULT_FAMILIES[kind];
922
+ const candidates = GENERIC_FONT_FAMILIES_BY_CLASS[kind];
498
923
  return (options.isAvailable ? candidates.find((family) => options.isAvailable?.(family)) : null) ?? candidates[0];
499
924
  }
500
925
  /**
@@ -504,14 +929,89 @@ function defaultFamily(kind, options) {
504
929
  */
505
930
  function resolveFontFamilyStack(value, options = {}) {
506
931
  for (const family of parseCSSFontFamilies(value)) {
507
- const generic = GENERIC_FAMILIES[family.trim().toLowerCase()];
508
- if (generic) return defaultFamily(generic, options);
932
+ const kind = genericFontFamilyClass(family);
933
+ if (kind) return defaultFamily(kind, options);
509
934
  if (options.isAvailable && !options.isAvailable(family)) continue;
510
935
  return family;
511
936
  }
512
937
  return null;
513
938
  }
514
939
  //#endregion
940
+ //#region src/import/stacking.ts
941
+ function isPositioned(style) {
942
+ const position = pickStyle(style, "position")?.trim();
943
+ return position !== void 0 && position !== "static";
944
+ }
945
+ function zIndexOf(style) {
946
+ if (!isPositioned(style)) return null;
947
+ const value = pickStyle(style, "z-index")?.trim();
948
+ if (!value || value === "auto") return null;
949
+ const z = Number.parseInt(value, 10);
950
+ return Number.isInteger(z) ? z : null;
951
+ }
952
+ /** Whether a box starts a stacking context of its own, as CSS decides it for the common cases. */
953
+ function formsStackingContext(style) {
954
+ const value = (property) => pickStyle(style, property)?.trim();
955
+ const position = value("position");
956
+ const opacity = Number.parseFloat(value("opacity") ?? "1");
957
+ return zIndexOf(style) !== null || position === "fixed" || position === "sticky" || opacity < 1 || (value("transform") ?? "none") !== "none" || (value("filter") ?? "none") !== "none" || value("isolation") === "isolate" || (value("mix-blend-mode") ?? "normal") !== "normal";
958
+ }
959
+ /**
960
+ * Puts a container's children in the order CSS paints them: negative layers first, lowest
961
+ * first, then the boxes in the flow as they were, then positioned ones, lowest first and in tree
962
+ * order at the same level. A container that is not a stacking context paints its negative layers
963
+ * under its own background, which a layer's fills cannot go under, so its fills move to a layer
964
+ * of their own above those children.
965
+ */
966
+ function applyStacking(graph, parent, style, parts) {
967
+ if (parts.length === 0) return;
968
+ const children = [];
969
+ let flowAfter = false;
970
+ for (const { layer, style: childStyle } of parts) {
971
+ const movable = layer.layoutPositioning === "ABSOLUTE" || parent.layoutMode === "NONE";
972
+ if (!isPositioned(childStyle) || !movable) {
973
+ if (children.some((child) => child.z === 0)) flowAfter = true;
974
+ continue;
975
+ }
976
+ children.push({
977
+ id: layer.id,
978
+ z: zIndexOf(childStyle) ?? 0
979
+ });
980
+ }
981
+ if (!flowAfter && children.every((child) => child.z === 0)) return;
982
+ const below = children.filter((child) => child.z < 0).toSorted((a, b) => a.z - b.z);
983
+ const above = children.filter((child) => child.z >= 0).toSorted((a, b) => a.z - b.z);
984
+ const moved = new Set(children.map((child) => child.id));
985
+ const order = [
986
+ ...below.map((child) => child.id),
987
+ ...parent.childIds.filter((id) => !moved.has(id)),
988
+ ...above.map((child) => child.id)
989
+ ];
990
+ for (const [index, id] of order.entries()) graph.insertChildAt(id, parent.id, index);
991
+ if (below.length > 0 && !formsStackingContext(style)) liftBackground(graph, parent, below.length);
992
+ }
993
+ /** Moves a container's fills into a layer of its own at `index`, its size and corners. */
994
+ function liftBackground(graph, parent, index) {
995
+ if (!parent.fills.some((fill) => fill.visible)) return;
996
+ const background = graph.createNode("RECTANGLE", parent.id, {
997
+ name: "background",
998
+ x: 0,
999
+ y: 0,
1000
+ width: parent.width,
1001
+ height: parent.height,
1002
+ fills: parent.fills,
1003
+ cornerRadius: parent.cornerRadius,
1004
+ topLeftRadius: parent.topLeftRadius,
1005
+ topRightRadius: parent.topRightRadius,
1006
+ bottomRightRadius: parent.bottomRightRadius,
1007
+ bottomLeftRadius: parent.bottomLeftRadius,
1008
+ independentCorners: parent.independentCorners,
1009
+ layoutPositioning: parent.layoutMode === "NONE" ? "AUTO" : "ABSOLUTE"
1010
+ });
1011
+ graph.insertChildAt(background.id, parent.id, index);
1012
+ graph.updateNode(parent.id, { fills: [] });
1013
+ }
1014
+ //#endregion
515
1015
  //#region src/import/text.ts
516
1016
  /**
517
1017
  * What characters take from the elements around them: the properties CSS inherits, and the
@@ -857,9 +1357,12 @@ const IMAGE_SOURCE_URL_KEY = "image-source-url";
857
1357
  * by half its blur length, which the canvas draws from the radius that gives that sigma.
858
1358
  */
859
1359
  function cssShadows(value) {
860
- return parseCSSShadows(value).map((effect) => effect.type === "SHADER" ? effect : {
861
- ...effect,
862
- radius: blurRadiusForSigma(effect.radius / 2)
1360
+ return parseCSSShadows(value).map((effect) => {
1361
+ if (effect.type !== "DROP_SHADOW" && effect.type !== "INNER_SHADOW") return effect;
1362
+ return {
1363
+ ...effect,
1364
+ radius: blurRadiusForSigma(effect.radius / 2)
1365
+ };
863
1366
  });
864
1367
  }
865
1368
  /**
@@ -914,36 +1417,32 @@ function firstCSSNumber(style, ...properties) {
914
1417
  }
915
1418
  return null;
916
1419
  }
917
- function fillsFromStyle(style, property) {
918
- return colorToFillFromCSS(pickStyle(style, property));
919
- }
920
1420
  /**
921
- * The `background-image` layers as fills, bottom-first as Pairdraw paints them: CSS paints the
922
- * first layer on top, so the list reverses. A `url()` layer becomes an image fill when its
923
- * bytes are inline; a remote address is skipped, as an unfetchable background paints nothing.
1421
+ * Puts one background layer behind the children, at the area a picture shows or over the whole
1422
+ * box. Layers are added bottom-first, so each new one paints above the last.
924
1423
  */
925
- function backgroundFills(graph, node, style) {
926
- const layers = parseCSSBackgroundImages(pickStyle(style, "background-image"), node.width, node.height);
927
- const fills = [];
928
- for (const layer of layers) {
929
- if (layer.kind === "gradient") {
930
- fills.push(layer.fill);
931
- continue;
932
- }
933
- const bytes = bytesFromDataURL(layer.url);
934
- if (!bytes) continue;
935
- const imageHash = computeImageHash(bytes);
936
- graph.images.set(imageHash, bytes);
937
- fills.push({
938
- type: "IMAGE",
939
- imageHash,
940
- imageScaleMode: "FILL",
941
- color: { ...TRANSPARENT },
942
- opacity: 1,
943
- visible: true
944
- });
945
- }
946
- return fills.reverse();
1424
+ function addBackgroundLayer(graph, parent, layer) {
1425
+ const corners = layer.area === void 0 ? {
1426
+ cornerRadius: parent.cornerRadius,
1427
+ topLeftRadius: parent.topLeftRadius,
1428
+ topRightRadius: parent.topRightRadius,
1429
+ bottomRightRadius: parent.bottomRightRadius,
1430
+ bottomLeftRadius: parent.bottomLeftRadius,
1431
+ independentCorners: parent.independentCorners
1432
+ } : {};
1433
+ const background = graph.createNode("RECTANGLE", parent.id, {
1434
+ name: layer.picture ? "background image" : "background",
1435
+ ...layer.area ?? {
1436
+ x: 0,
1437
+ y: 0,
1438
+ width: parent.width,
1439
+ height: parent.height
1440
+ },
1441
+ fills: [layer.fill],
1442
+ ...corners,
1443
+ layoutPositioning: parent.layoutMode === "NONE" ? "AUTO" : "ABSOLUTE"
1444
+ });
1445
+ graph.insertChildAt(background.id, parent.id, parent.childIds.length);
947
1446
  }
948
1447
  function aspectRatioFromCSS(value) {
949
1448
  if (!value || value === "auto") return null;
@@ -1105,11 +1604,11 @@ function applyImageFill(graph, node, element, style) {
1105
1604
  const source = element.attrs.src;
1106
1605
  const bytes = bytesFromDataURL(source);
1107
1606
  if (!bytes) {
1108
- if (source) node.pluginData.push({
1607
+ if (source) node.pluginData = [...node.pluginData, {
1109
1608
  pluginId: DOM_CSS_PLUGIN_ID,
1110
1609
  key: IMAGE_SOURCE_URL_KEY,
1111
1610
  value: source
1112
- });
1611
+ }];
1113
1612
  return;
1114
1613
  }
1115
1614
  const imageHash = computeImageHash(bytes);
@@ -1128,9 +1627,9 @@ function applyElementStyle(graph, node, element, style) {
1128
1627
  applyBoxSizing(node, style);
1129
1628
  applyPositioning(node, style);
1130
1629
  applyPadding(node, style);
1131
- const fills = fillsFromStyle(style, "background-color");
1132
- const background = backgroundFills(graph, node, style);
1133
- if (fills.length > 0 || background.length > 0) node.fills = [...fills, ...background];
1630
+ const background = backgroundPaint(graph, style, node);
1631
+ if (background.fills.length > 0) node.fills = background.fills;
1632
+ for (const layer of background.layers) addBackgroundLayer(graph, node, layer);
1134
1633
  applyImageFill(graph, node, element, style);
1135
1634
  const strokes = colorToStrokeFromCSS(firstStrokeColor(style), strokeWeightFromStyle(style)?.toString());
1136
1635
  if (strokes.length > 0) {
@@ -1321,6 +1820,19 @@ function containerFlow(element, display) {
1321
1820
  lines
1322
1821
  };
1323
1822
  }
1823
+ /** Builds a container's children and orders them the way CSS paints them. */
1824
+ function paintChildren(graph, node, element, style, flow) {
1825
+ const children = flow === "flex" ? element.children.toSorted(byFlexOrder) : element.children;
1826
+ const painted = [];
1827
+ for (const child of children) {
1828
+ const layer = createDesignNode(graph, node.id, child, flow, inheritedTextStyle(element, style));
1829
+ if (layer) painted.push({
1830
+ layer,
1831
+ style: child.type === "element" ? mergedStyle(child) : {}
1832
+ });
1833
+ }
1834
+ applyStacking(graph, node, style, painted);
1835
+ }
1324
1836
  function createElementNode(graph, parentId, element, parentFlow) {
1325
1837
  const style = mergedStyle(element);
1326
1838
  const display = elementDisplay(element, style);
@@ -1349,8 +1861,7 @@ function createElementNode(graph, parentId, element, parentFlow) {
1349
1861
  createRichTextNode(graph, node.id, element, textStyle, textDisplay, flow ?? "none");
1350
1862
  return node;
1351
1863
  }
1352
- const children = flow === "flex" ? element.children.toSorted(byFlexOrder) : element.children;
1353
- for (const child of children) createDesignNode(graph, node.id, child, flow ?? "none", inheritedTextStyle(element, style));
1864
+ paintChildren(graph, node, element, style, flow ?? "none");
1354
1865
  return node;
1355
1866
  }
1356
1867
  function flexOrder(node) {