diagram-contracts 0.1.3 → 0.1.4

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/dist/cli.mjs CHANGED
@@ -740,1034 +740,417 @@ var ELEMENT_CATALOG = {
740
740
 
741
741
  // src/ir/index.ts
742
742
  import { z } from "zod";
743
- var IrNodeSchema = z.lazy(
744
- () => z.object({
745
- kind: z.string(),
746
- id: z.string().optional(),
747
- props: z.record(z.string(), z.unknown()),
748
- children: z.array(IrNodeSchema).optional()
749
- })
750
- );
751
- function buildValidPropsSet(kind) {
752
- const element = ELEMENT_CATALOG[kind];
753
- if (!element) return /* @__PURE__ */ new Set();
754
- const props = new Set(element.properties);
755
- if (element.children.kind === "text") {
756
- props.add("text");
757
- }
758
- return props;
759
- }
760
- function validateNode(node, path) {
761
- if (!(node.kind in ELEMENT_CATALOG)) {
762
- throw new Error(`Invalid element kind '${node.kind}' at ${path}`);
763
- }
764
- const validProps = buildValidPropsSet(node.kind);
765
- const unknownProps = Object.keys(node.props).filter((k) => !validProps.has(k));
766
- if (unknownProps.length > 0) {
767
- throw new Error(
768
- `Unknown properties for '${node.kind}' at ${path}: ${unknownProps.join(", ")}`
769
- );
770
- }
771
- if (node.children) {
772
- for (let i = 0; i < node.children.length; i++) {
773
- validateNode(node.children[i], `${path}.children[${i}]`);
774
- }
775
- }
743
+
744
+ // src/graph/rule-engine.ts
745
+ import { load } from "js-yaml";
746
+
747
+ // src/graph/graph-helpers.ts
748
+ function num(v) {
749
+ return v ?? 0;
776
750
  }
777
- function parseIr(json) {
778
- const parsed = IrNodeSchema.parse(json);
779
- validateNode(parsed, "root");
780
- return parsed;
751
+ function childrenOf(node) {
752
+ return node.children ?? [];
781
753
  }
782
-
783
- // src/parser/tokenizer.ts
784
- var SHAPE_PATTERNS = [
785
- { shape: "capsule", open: "([", close: "])" },
786
- { shape: "cylinder", open: "[(", close: ")]" },
787
- { shape: "circle", open: "((", close: "))" },
788
- { shape: "hexagon", open: "[[", close: "]]" },
789
- { shape: "roundedRect", open: "[", close: "]" },
790
- { shape: "diamond", open: "{", close: "}" },
791
- { shape: "rect", open: "(", close: ")" }
792
- ];
793
- var SHAPE_ALIASES = {
794
- stadium: "capsule",
795
- pill: "capsule",
796
- rounded: "roundedRect",
797
- db: "cylinder",
798
- database: "cylinder",
799
- cyl: "cylinder",
800
- decision: "diamond",
801
- hex: "hexagon",
802
- tri: "triangle"
803
- };
804
- function parseNodeShape(rest) {
805
- let shapeOverride;
806
- let cursor = 0;
807
- if (rest.startsWith("@")) {
808
- const atMatch = rest.match(/^@(\w+)/);
809
- if (!atMatch) return null;
810
- shapeOverride = SHAPE_ALIASES[atMatch[1]] ?? atMatch[1];
811
- cursor = atMatch[0].length;
812
- }
813
- const remaining = rest.slice(cursor);
814
- for (const { shape, open, close } of SHAPE_PATTERNS) {
815
- if (!remaining.startsWith(open)) continue;
816
- const contentStart = open.length;
817
- const closeIdx = remaining.indexOf(close, contentStart);
818
- if (closeIdx === -1) continue;
819
- const afterClose = remaining.slice(closeIdx + close.length);
820
- if (afterClose.length > 0 && /^[a-zA-Z0-9_-]/.test(afterClose)) continue;
821
- let label = remaining.slice(contentStart, closeIdx);
822
- if (label.startsWith('"') && label.endsWith('"')) {
823
- label = label.slice(1, -1);
824
- }
825
- return {
826
- label,
827
- shape: shapeOverride ?? shape,
828
- shapeOverride,
829
- consumed: cursor + closeIdx + close.length
830
- };
831
- }
832
- return null;
754
+ function slotId(nodeId, kind) {
755
+ return `${nodeId}.${kind}`;
833
756
  }
834
- function matchEdgeOp(s) {
835
- const trimmed = s.trimStart();
836
- for (const op of ["==>", "-.->", "-->", "---", "~~~"]) {
837
- if (!trimmed.startsWith(op)) continue;
838
- let after = trimmed.slice(op.length);
839
- let label;
840
- if (op !== "~~~" && after.startsWith("|")) {
841
- const pipeEnd = after.indexOf("|", 1);
842
- if (pipeEnd !== -1) {
843
- label = after.slice(1, pipeEnd).trim();
844
- after = after.slice(pipeEnd + 1);
845
- }
846
- }
847
- return { op, label, rest: after };
757
+ function ensureSlot(graph, nodeId, kind, value) {
758
+ const id = slotId(nodeId, kind);
759
+ let slot = graph.slots.get(id);
760
+ if (!slot) {
761
+ slot = { id, value, nodeId, slotKind: kind };
762
+ graph.slots.set(id, slot);
763
+ } else if (value !== void 0 && slot.value === void 0) {
764
+ slot.value = value;
848
765
  }
849
- return null;
766
+ return slot;
850
767
  }
851
- function parseNodeRef(s) {
852
- const trimmed = s.trimStart();
853
- const idMatch = trimmed.match(/^([a-zA-Z_][a-zA-Z0-9_-]*)/);
854
- if (!idMatch) return null;
855
- const nodeId = idMatch[1];
856
- let after = trimmed.slice(idMatch[0].length);
857
- const shapeParsed = parseNodeShape(after);
858
- let def;
859
- if (shapeParsed) {
860
- after = after.slice(shapeParsed.consumed);
861
- def = { label: shapeParsed.label, shape: shapeParsed.shape, shapeOverride: shapeParsed.shapeOverride };
768
+ function addCandidate(graph, targetSlotId, value, source, priority, operationId) {
769
+ const candidate = { targetSlotId, value, source, priority, operationId };
770
+ graph.candidates.push(candidate);
771
+ let bySlot = graph.candidatesBySlot.get(targetSlotId);
772
+ if (!bySlot) {
773
+ bySlot = [];
774
+ graph.candidatesBySlot.set(targetSlotId, bySlot);
862
775
  }
863
- if (after.startsWith(":::")) {
864
- const classMatch = after.slice(3).match(/^([a-zA-Z_][a-zA-Z0-9_-]*)/);
865
- if (classMatch) {
866
- if (def) {
867
- def.variant = classMatch[1];
868
- } else {
869
- def = { label: nodeId, shape: "roundedRect", variant: classMatch[1] };
870
- }
871
- after = after.slice(3 + classMatch[0].length);
776
+ bySlot.push(candidate);
777
+ if (operationId) {
778
+ let byOp = graph.candidatesByOperation.get(operationId);
779
+ if (!byOp) {
780
+ byOp = [];
781
+ graph.candidatesByOperation.set(operationId, byOp);
872
782
  }
783
+ byOp.push(candidate);
873
784
  }
874
- return { nodeId, def, rest: after };
785
+ return candidate;
875
786
  }
876
- function tokenizeLine(line, lineNum) {
877
- const trimmed = line.trim();
878
- if (trimmed === "") return null;
879
- if (trimmed.startsWith("%%")) {
880
- return { type: "comment", raw: line, line: lineNum };
881
- }
882
- const dirMatch = trimmed.match(/^(?:flowchart|graph)\s+(TD|TB|LR)$/i);
883
- if (dirMatch) {
884
- const dirRaw = dirMatch[1].toUpperCase();
885
- const dir = dirRaw === "TB" ? "TD" : dirRaw;
886
- if (dir !== "TD" && dir !== "LR") {
887
- return null;
888
- }
889
- return { type: "direction", raw: line, line: lineNum, dir };
787
+ function addOperation(graph, id, op, inputs, outputs, compute) {
788
+ const operation = { id, op, inputs, outputs, compute };
789
+ graph.operations.set(id, operation);
790
+ for (const inputSlotId of inputs) {
791
+ graph.dependencies.push({ fromSlotId: inputSlotId, toOperationId: id });
890
792
  }
891
- const subMatch = trimmed.match(/^subgraph\s+(\S+)(?:\s+\[([^\]]*)\])?\s*$/);
892
- if (subMatch) {
893
- return {
894
- type: "subgraphStart",
895
- raw: line,
896
- line: lineNum,
897
- subgraphId: subMatch[1],
898
- label: subMatch[2] ?? void 0
899
- };
793
+ return operation;
794
+ }
795
+ function addResolver(graph, targetSlotId, policy) {
796
+ if (!graph.resolvers.has(targetSlotId)) {
797
+ graph.resolvers.set(targetSlotId, { slotId: targetSlotId, policy });
900
798
  }
901
- if (trimmed === "end") {
902
- return { type: "subgraphEnd", raw: line, line: lineNum };
799
+ }
800
+ function getNumericProp(node, prop, fallback) {
801
+ const val = node.props[prop];
802
+ if (typeof val === "number") return val;
803
+ if (typeof val === "string") {
804
+ const n = parseFloat(val);
805
+ if (!isNaN(n)) return n;
903
806
  }
904
- const localDirMatch = trimmed.match(/^direction\s+(TD|TB|LR)$/i);
905
- if (localDirMatch) {
906
- const dirRaw = localDirMatch[1].toUpperCase();
907
- const dir = dirRaw === "TB" ? "TD" : dirRaw;
908
- return { type: "localDirection", raw: line, line: lineNum, dir };
807
+ return fallback;
808
+ }
809
+ function getStringProp(node, prop, defaultValue) {
810
+ const val = node.props[prop];
811
+ return typeof val === "string" ? val : defaultValue;
812
+ }
813
+ function getSizeProp(node, prop) {
814
+ const val = node.props[prop];
815
+ if (typeof val === "number") return val;
816
+ if (val === "wrap") return "wrap";
817
+ if (val === "fill") return "fill";
818
+ if (typeof val === "string") {
819
+ const n = parseFloat(val);
820
+ if (!isNaN(n)) return n;
909
821
  }
910
- const classDefMatch = trimmed.match(/^classDef\s+(\S+)\s+(.+)$/);
911
- if (classDefMatch) {
912
- return {
913
- type: "classDef",
914
- raw: line,
915
- line: lineNum,
916
- className: classDefMatch[1],
917
- styles: classDefMatch[2]
918
- };
822
+ return "wrap";
823
+ }
824
+ function isConstraintKind(kind) {
825
+ return kind === "alignConstraint" || kind === "equalizeWidth" || kind === "equalizeHeight" || kind === "minGap" || kind === "keepInsideConstraint" || kind === "orderConstraint";
826
+ }
827
+ function registerSizeSlots(node, graph, parentId) {
828
+ const id = node.id;
829
+ const widthIntent = getSizeProp(node, "width");
830
+ const heightIntent = getSizeProp(node, "height");
831
+ ensureSlot(graph, id, "resolvedWidth");
832
+ ensureSlot(graph, id, "resolvedHeight");
833
+ ensureSlot(graph, id, "localX");
834
+ ensureSlot(graph, id, "localY");
835
+ if (typeof widthIntent === "number") {
836
+ ensureSlot(graph, id, "contentWidth", widthIntent);
837
+ addCandidate(graph, slotId(id, "contentWidth"), widthIntent, `${node.kind}(${id}).explicit`, "required");
838
+ addCandidate(graph, slotId(id, "resolvedWidth"), widthIntent, `${node.kind}(${id}).explicit`, "normal");
839
+ } else if (widthIntent === "fill" && parentId) {
840
+ ensureSlot(graph, parentId, "availableWidth");
919
841
  }
920
- if (trimmed.startsWith("@")) {
921
- return parseDirective(trimmed, line, lineNum);
842
+ if (typeof heightIntent === "number") {
843
+ ensureSlot(graph, id, "contentHeight", heightIntent);
844
+ addCandidate(graph, slotId(id, "contentHeight"), heightIntent, `${node.kind}(${id}).explicit`, "required");
845
+ addCandidate(graph, slotId(id, "resolvedHeight"), heightIntent, `${node.kind}(${id}).explicit`, "normal");
846
+ } else if (heightIntent === "fill" && parentId) {
847
+ ensureSlot(graph, parentId, "availableHeight");
922
848
  }
923
- return parseEdgeOrNodeLine(trimmed, line, lineNum);
924
849
  }
925
- var SAME_SIZE_DEFAULT_STRATEGY = "max";
926
- function parseDirective(trimmed, raw, lineNum) {
927
- const sameWidthMatch = trimmed.match(/^@same-width(?:\s+(\w+))?:\s*(.+)$/);
928
- if (sameWidthMatch) {
929
- const strategy = sameWidthMatch[1] ?? SAME_SIZE_DEFAULT_STRATEGY;
930
- const targets = sameWidthMatch[2].split(",").map((t) => t.trim()).filter(Boolean);
931
- return {
932
- type: "directive",
933
- raw,
934
- line: lineNum,
935
- directiveType: "same-width",
936
- strategy,
937
- targets
938
- };
939
- }
940
- const sameHeightMatch = trimmed.match(/^@same-height(?:\s+(\w+))?:\s*(.+)$/);
941
- if (sameHeightMatch) {
942
- const strategy = sameHeightMatch[1] ?? SAME_SIZE_DEFAULT_STRATEGY;
943
- const targets = sameHeightMatch[2].split(",").map((t) => t.trim()).filter(Boolean);
944
- return {
945
- type: "directive",
946
- raw,
947
- line: lineNum,
948
- directiveType: "same-height",
949
- strategy,
950
- targets
951
- };
952
- }
953
- const gapMatch = trimmed.match(/^@gap\s+min=(\d+):\s*(.+)$/);
954
- if (gapMatch) {
955
- const min = parseInt(gapMatch[1], 10);
956
- const targets = gapMatch[2].split(",").map((t) => t.trim()).filter(Boolean);
957
- return {
958
- type: "directive",
959
- raw,
960
- line: lineNum,
961
- directiveType: "gap",
962
- min,
963
- targets
964
- };
850
+
851
+ // src/graph/east-asian-width.ts
852
+ var WIDE_RANGES = [
853
+ [4352, 4447],
854
+ // Hangul Jamo (leading consonants)
855
+ [8986, 8987],
856
+ // ⌚ ⌛ watch, hourglass
857
+ [9001, 9002],
858
+ // 〈 〉 angle brackets (EAW Wide)
859
+ [9193, 9196],
860
+ // ⏩–⏬ media controls
861
+ [9200, 9200],
862
+ // ⏰ alarm clock
863
+ [9203, 9203],
864
+ // ⏳ hourglass with sand
865
+ [9725, 9726],
866
+ // ◽ ◾ medium small squares
867
+ [9748, 9749],
868
+ // ☔ ☕ umbrella, hot beverage
869
+ [9800, 9811],
870
+ // ♈–♓ zodiac signs
871
+ [9855, 9855],
872
+ // ♿ wheelchair symbol
873
+ [9875, 9875],
874
+ // ⚓ anchor
875
+ [9889, 9889],
876
+ // ⚡ high voltage
877
+ [9898, 9899],
878
+ // ⚪ ⚫ circles
879
+ [9917, 9918],
880
+ // ⚽ ⚾ soccer, baseball
881
+ [9924, 9925],
882
+ // ⛄ ⛅ snowman, sun behind cloud
883
+ [9934, 9934],
884
+ // ⛎ Ophiuchus
885
+ [9940, 9940],
886
+ // ⛔ no entry
887
+ [9962, 9962],
888
+ // ⛪ church
889
+ [9970, 9971],
890
+ // ⛲ ⛳ fountain, flag in hole
891
+ [9973, 9973],
892
+ // ⛵ sailboat
893
+ [9978, 9978],
894
+ // ⛺ tent
895
+ [9981, 9981],
896
+ // ⛽ fuel pump
897
+ [9989, 9989],
898
+ // ✅ check mark button
899
+ [9994, 9995],
900
+ // ✊ ✋ fists
901
+ [10024, 10024],
902
+ // ✨ sparkles
903
+ [10060, 10060],
904
+ // ❌ cross mark
905
+ [10062, 10062],
906
+ // ❎ cross mark button
907
+ [10067, 10069],
908
+ // ❓❔❕ question/exclamation marks
909
+ [10071, 10071],
910
+ // ❗ exclamation mark
911
+ [10133, 10135],
912
+ // ➕➖➗ math signs
913
+ [10160, 10160],
914
+ // ➰ curly loop
915
+ [10175, 10175],
916
+ // ➿ double curly loop
917
+ [11035, 11036],
918
+ // ⬛ ⬜ large squares
919
+ [11088, 11088],
920
+ // ⭐ star
921
+ [11093, 11093],
922
+ // ⭕ heavy large circle
923
+ [11904, 12350],
924
+ // CJK Radicals, Kangxi Radicals, CJK Symbols & Punctuation (incl. U+3000 ideographic space)
925
+ [12353, 13311],
926
+ // Hiragana, Katakana, Bopomofo, Hangul Compat Jamo, Kanbun, CJK Compatibility
927
+ [13312, 19903],
928
+ // CJK Unified Ideographs Extension A
929
+ [19968, 40959],
930
+ // CJK Unified Ideographs
931
+ [40960, 42191],
932
+ // Yi Syllables, Yi Radicals
933
+ [43360, 43391],
934
+ // Hangul Jamo Extended-A
935
+ [44032, 55203],
936
+ // Hangul Syllables
937
+ [63744, 64255],
938
+ // CJK Compatibility Ideographs
939
+ [65040, 65049],
940
+ // Vertical Forms
941
+ [65072, 65106],
942
+ // CJK Compatibility Forms
943
+ [65108, 65126],
944
+ // Small Form Variants
945
+ [65128, 65131],
946
+ // Small Form Variants (fullwidth-ish signs)
947
+ [65281, 65376],
948
+ // Fullwidth Forms (! … ⦆)
949
+ [65504, 65510],
950
+ // Fullwidth signs (¢ £ ¬  ̄ ¦ ¥ ₩)
951
+ [94176, 101759],
952
+ // Tangut, Khitan Small Script, Tangut Supplement (EAW Wide)
953
+ [110576, 111355],
954
+ // Kana Extended-B, Kana Supplement, Kana Extended-A, Small Kana Extension, Nushu
955
+ [126980, 126980],
956
+ // 🀄 mahjong red dragon
957
+ [127183, 127183],
958
+ // 🃏 playing card joker
959
+ [127374, 127374],
960
+ // 🆎 AB blood type button
961
+ [127377, 127386],
962
+ // 🆑–🆚 squared Latin abbreviations
963
+ [127488, 127589],
964
+ // Enclosed Ideographic Supplement (🈁 🈯 squared kana/CJK)
965
+ [127744, 128591],
966
+ // Misc Symbols & Pictographs, Emoticons (emoji, EAW Wide)
967
+ [128640, 128767],
968
+ // Transport and Map Symbols (🚀 …)
969
+ [128992, 129008],
970
+ // Geometric Shapes Extended (colored circles/squares)
971
+ [129280, 129535],
972
+ // Supplemental Symbols & Pictographs (emoji, EAW Wide)
973
+ [129648, 129791],
974
+ // Symbols & Pictographs Extended-A (🩰 🪐 …)
975
+ [131072, 196605],
976
+ // CJK Unified Ideographs Extensions B–F
977
+ [196608, 262141]
978
+ // CJK Unified Ideographs Extension G+
979
+ ];
980
+ function isEastAsianWide(codePoint) {
981
+ let lo = 0;
982
+ let hi = WIDE_RANGES.length - 1;
983
+ while (lo <= hi) {
984
+ const mid = lo + hi >> 1;
985
+ const [start, end] = WIDE_RANGES[mid];
986
+ if (codePoint < start) {
987
+ hi = mid - 1;
988
+ } else if (codePoint > end) {
989
+ lo = mid + 1;
990
+ } else {
991
+ return true;
992
+ }
965
993
  }
966
- const moverMatch = trimmed.match(/^@mover\s+(\S+):\s*(.+)$/);
967
- if (moverMatch) {
968
- const moverId = moverMatch[1];
969
- const targets = moverMatch[2].split(",").map((t) => t.trim()).filter(Boolean);
970
- return {
971
- type: "directive",
972
- raw,
973
- line: lineNum,
974
- directiveType: "mover",
975
- moverId,
976
- targets
977
- };
994
+ return false;
995
+ }
996
+ function approxCharEm(codePoint) {
997
+ return isEastAsianWide(codePoint) ? 1 : 0.6;
998
+ }
999
+
1000
+ // src/graph/ops.ts
1001
+ function approxTextWidth(text, fontSize) {
1002
+ let width = 0;
1003
+ for (const ch of text) {
1004
+ width += approxCharEm(ch.codePointAt(0)) * fontSize;
978
1005
  }
979
- return null;
1006
+ return width;
980
1007
  }
981
- function parseEdgeOrNodeLine(trimmed, raw, lineNum) {
982
- const firstRef = parseNodeRef(trimmed);
983
- if (!firstRef) return null;
984
- let cursor = trimmed.length - firstRef.rest.length;
985
- let remaining = firstRef.rest;
986
- const edgeMatch = matchEdgeOp(remaining);
987
- if (!edgeMatch) {
988
- if (!firstRef.def) {
989
- return null;
1008
+ var SIMPLE_FONT_METRICS = {
1009
+ CAP_HEIGHT: 0.7,
1010
+ ASCENT: 0.9,
1011
+ DESCENT: 0.25,
1012
+ LINE_HEIGHT: 1.4
1013
+ };
1014
+ var SimpleTextMeasurer = class {
1015
+ measure(text, fontSize, maxWidth) {
1016
+ const lineHeight = SIMPLE_FONT_METRICS.LINE_HEIGHT * fontSize;
1017
+ if (!text) {
1018
+ return { width: 0, height: lineHeight, lines: [""] };
990
1019
  }
1020
+ const measureFn = (t) => approxTextWidth(t, fontSize);
1021
+ const lines = wrapLines(text, maxWidth, measureFn);
1022
+ const width = Math.max(...lines.map(measureFn));
1023
+ const height = lines.length * lineHeight;
1024
+ return { width, height, lines };
1025
+ }
1026
+ metrics(fontSize) {
991
1027
  return {
992
- type: "nodeDef",
993
- raw,
994
- line: lineNum,
995
- nodeId: firstRef.nodeId,
996
- label: firstRef.def.label,
997
- shape: firstRef.def.shape,
998
- variant: firstRef.def.variant,
999
- shapeOverride: firstRef.def.shapeOverride
1028
+ ascent: SIMPLE_FONT_METRICS.ASCENT * fontSize,
1029
+ descent: SIMPLE_FONT_METRICS.DESCENT * fontSize,
1030
+ capHeight: SIMPLE_FONT_METRICS.CAP_HEIGHT * fontSize,
1031
+ lineHeight: SIMPLE_FONT_METRICS.LINE_HEIGHT * fontSize
1000
1032
  };
1001
1033
  }
1002
- if (edgeMatch.op === "~~~") {
1003
- return parseInvisibleEdgeChain(trimmed, firstRef, raw, lineNum);
1034
+ };
1035
+ var BROWSER_COMPENSATION = 1.1;
1036
+ function measureGlyphWidth(font, text, fontSize) {
1037
+ const scale = fontSize / font.unitsPerEm;
1038
+ let width = 0;
1039
+ for (const ch of text) {
1040
+ const glyph = font.charToGlyph(ch);
1041
+ const missing = glyph.index === 0 || glyph.advanceWidth == null;
1042
+ if (missing) {
1043
+ width += approxCharEm(ch.codePointAt(0)) * fontSize;
1044
+ } else {
1045
+ width += glyph.advanceWidth * scale;
1046
+ }
1004
1047
  }
1005
- return parseVisibleEdgeChain(trimmed, firstRef, raw, lineNum);
1048
+ return width * BROWSER_COMPENSATION;
1006
1049
  }
1007
- function parseInvisibleEdgeChain(input, firstRef, raw, lineNum) {
1008
- const segments = [];
1009
- let currentId = firstRef.nodeId;
1010
- let remaining = firstRef.rest;
1011
- while (true) {
1012
- const edgeMatch = matchEdgeOp(remaining);
1013
- if (!edgeMatch || edgeMatch.op !== "~~~") break;
1014
- remaining = edgeMatch.rest;
1015
- const nextRef = parseNodeRef(remaining);
1016
- if (!nextRef) break;
1017
- segments.push({ fromId: currentId, toId: nextRef.nodeId });
1018
- currentId = nextRef.nodeId;
1019
- remaining = nextRef.rest;
1050
+ var OpenTypeTextMeasurer = class _OpenTypeTextMeasurer {
1051
+ fonts = /* @__PURE__ */ new Map();
1052
+ // Line-box factor shared with the SimpleTextMeasurer SSoT so a single-line
1053
+ // text box's measured height matches the line box regardless of measurer.
1054
+ lineHeightFactor = SIMPLE_FONT_METRICS.LINE_HEIGHT;
1055
+ addFont(key, font) {
1056
+ this.fonts.set(key, font);
1020
1057
  }
1021
- return { type: "invisibleEdge", raw, line: lineNum, segments };
1022
- }
1023
- function parseVisibleEdgeChain(input, firstRef, raw, lineNum) {
1024
- const segments = [];
1025
- let currentId = firstRef.nodeId;
1026
- let currentDef = firstRef.def;
1027
- let remaining = firstRef.rest;
1028
- while (true) {
1029
- const edgeMatch = matchEdgeOp(remaining);
1030
- if (!edgeMatch || edgeMatch.op === "~~~") break;
1031
- remaining = edgeMatch.rest;
1032
- let colonLabel;
1033
- const nextRef = parseNodeRef(remaining);
1034
- if (!nextRef) break;
1035
- remaining = nextRef.rest;
1036
- const colonMatch = remaining.match(/^\s*:\s*(.+?)$/);
1037
- if (colonMatch) {
1038
- colonLabel = colonMatch[1].trim();
1039
- remaining = "";
1058
+ /** Canonical CSS font-weight key for "normal" — the default when none given. */
1059
+ static DEFAULT_WEIGHT = "400";
1060
+ static WEIGHT_ALIASES = {
1061
+ normal: "400",
1062
+ bold: "700",
1063
+ lighter: "300",
1064
+ bolder: "700"
1065
+ };
1066
+ getFont(fontWeight) {
1067
+ const raw = fontWeight != null ? String(fontWeight) : _OpenTypeTextMeasurer.DEFAULT_WEIGHT;
1068
+ const w = _OpenTypeTextMeasurer.WEIGHT_ALIASES[raw] ?? raw;
1069
+ return this.fonts.get(w) ?? this.fonts.get(_OpenTypeTextMeasurer.DEFAULT_WEIGHT) ?? this.fonts.values().next().value;
1070
+ }
1071
+ measure(text, fontSize, maxWidth, fontWeight) {
1072
+ const lineHeight = this.lineHeightFactor * fontSize;
1073
+ if (!text) {
1074
+ return { width: 0, height: lineHeight, lines: [""] };
1040
1075
  }
1041
- const seg = {
1042
- fromId: currentId,
1043
- toId: nextRef.nodeId,
1044
- edgeType: edgeMatch.op,
1045
- edgeLabel: edgeMatch.label ?? colonLabel
1046
- };
1047
- if (currentDef) {
1048
- seg.fromDef = currentDef;
1076
+ const font = this.getFont(fontWeight);
1077
+ if (!font) {
1078
+ return new SimpleTextMeasurer().measure(text, fontSize, maxWidth);
1049
1079
  }
1050
- if (nextRef.def) {
1051
- seg.toDef = nextRef.def;
1080
+ const measureFn = (t) => measureGlyphWidth(font, t, fontSize);
1081
+ const lines = wrapLines(text, maxWidth, measureFn);
1082
+ const width = Math.max(...lines.map(measureFn));
1083
+ const height = lines.length * lineHeight;
1084
+ return { width, height, lines };
1085
+ }
1086
+ /**
1087
+ * Real vertical metrics for the weight's font, in px at `fontSize`.
1088
+ *
1089
+ * capHeight comes from the OS/2 `sCapHeight` field when present; otherwise it
1090
+ * is measured from the "H" glyph's bounding box (top-of-cap in font units).
1091
+ * If neither is available the loaded font is degenerate, so we defer to the
1092
+ * documented {@link SIMPLE_FONT_METRICS} ratio rather than inventing a value.
1093
+ * ascent/descent use the OS/2 typographic values, falling back to the
1094
+ * hhea ascender/descender, then to the Simple ratios.
1095
+ */
1096
+ metrics(fontSize, fontWeight) {
1097
+ const font = this.getFont(fontWeight);
1098
+ if (!font) {
1099
+ return new SimpleTextMeasurer().metrics(fontSize);
1052
1100
  }
1053
- segments.push(seg);
1054
- currentId = nextRef.nodeId;
1055
- currentDef = nextRef.def;
1101
+ const scale = fontSize / font.unitsPerEm;
1102
+ const simple = new SimpleTextMeasurer().metrics(fontSize);
1103
+ const capUnits = capHeightFontUnits(font);
1104
+ const ascentUnits = ascentFontUnits(font);
1105
+ const descentUnits = descentFontUnits(font);
1106
+ return {
1107
+ capHeight: capUnits !== void 0 ? capUnits * scale : simple.capHeight,
1108
+ ascent: ascentUnits !== void 0 ? ascentUnits * scale : simple.ascent,
1109
+ descent: descentUnits !== void 0 ? descentUnits * scale : simple.descent,
1110
+ lineHeight: this.lineHeightFactor * fontSize
1111
+ };
1056
1112
  }
1057
- return { type: "edge", raw, line: lineNum, segments };
1113
+ };
1114
+ function capHeightFontUnits(font) {
1115
+ const os2Cap = font.tables?.os2?.sCapHeight;
1116
+ if (os2Cap != null && os2Cap > 0) return os2Cap;
1117
+ const h = font.charToGlyph("H");
1118
+ const bbox = h.getBoundingBox?.();
1119
+ if (bbox && Number.isFinite(bbox.y2) && bbox.y2 > 0) return bbox.y2;
1120
+ if (h.yMax != null && h.yMax > 0) return h.yMax;
1121
+ return void 0;
1058
1122
  }
1059
- function tokenize(source) {
1060
- const lines = source.split("\n");
1061
- const tokens = [];
1062
- for (let i = 0; i < lines.length; i++) {
1063
- const token = tokenizeLine(lines[i], i + 1);
1064
- if (token) {
1065
- tokens.push(token);
1123
+ function ascentFontUnits(font) {
1124
+ const typo = font.tables?.os2?.sTypoAscender;
1125
+ if (typo != null && typo > 0) return typo;
1126
+ if (font.ascender != null && font.ascender > 0) return font.ascender;
1127
+ return void 0;
1128
+ }
1129
+ function descentFontUnits(font) {
1130
+ const typo = font.tables?.os2?.sTypoDescender;
1131
+ if (typo != null) return Math.abs(typo);
1132
+ if (font.descender != null) return Math.abs(font.descender);
1133
+ return void 0;
1134
+ }
1135
+ function wrapLines(text, maxWidth, measureFn) {
1136
+ const words = text.split(/\s+/);
1137
+ const lines = [];
1138
+ if (maxWidth !== void 0 && maxWidth > 0) {
1139
+ let currentLine = "";
1140
+ for (const word of words) {
1141
+ const candidate = currentLine ? `${currentLine} ${word}` : word;
1142
+ if (measureFn(candidate) > maxWidth && currentLine) {
1143
+ lines.push(currentLine);
1144
+ currentLine = word;
1145
+ } else {
1146
+ currentLine = candidate;
1147
+ }
1066
1148
  }
1149
+ if (currentLine) lines.push(currentLine);
1150
+ } else {
1151
+ lines.push(text);
1067
1152
  }
1068
- return tokens;
1069
- }
1070
-
1071
- // src/parser/parser.ts
1072
- function parseDrawText(source) {
1073
- const diagnostics = [];
1074
- const tokens = tokenize(source);
1075
- let rootDirection = "TD";
1076
- const nodeMap = /* @__PURE__ */ new Map();
1077
- const connectors = [];
1078
- const constraints = [];
1079
- const classDefMap = /* @__PURE__ */ new Map();
1080
- const scopeStack = [];
1081
- const groups = [];
1082
- const rootNodeIds = [];
1083
- function currentDirection() {
1084
- for (let i = scopeStack.length - 1; i >= 0; i--) {
1085
- if (scopeStack[i].direction) return scopeStack[i].direction;
1086
- }
1087
- return rootDirection;
1088
- }
1089
- function registerNode(id, label, shape, variant) {
1090
- if (!nodeMap.has(id)) {
1091
- nodeMap.set(id, { id, label, shape, variant });
1092
- }
1093
- if (scopeStack.length > 0) {
1094
- const top = scopeStack[scopeStack.length - 1];
1095
- if (!top.nodeIds.includes(id)) top.nodeIds.push(id);
1096
- } else {
1097
- if (!rootNodeIds.includes(id)) rootNodeIds.push(id);
1098
- }
1099
- }
1100
- function ensureNode(id) {
1101
- if (nodeMap.has(id)) return;
1102
- nodeMap.set(id, { id, label: id, shape: "roundedRect" });
1103
- if (scopeStack.length > 0) {
1104
- const top = scopeStack[scopeStack.length - 1];
1105
- if (!top.nodeIds.includes(id)) top.nodeIds.push(id);
1106
- } else {
1107
- if (!rootNodeIds.includes(id)) rootNodeIds.push(id);
1108
- }
1109
- }
1110
- for (const token of tokens) {
1111
- switch (token.type) {
1112
- case "comment":
1113
- break;
1114
- case "direction":
1115
- rootDirection = token.dir;
1116
- break;
1117
- case "nodeDef": {
1118
- const t = token;
1119
- registerNode(t.nodeId, t.label, t.shape, t.variant);
1120
- break;
1121
- }
1122
- case "edge": {
1123
- const t = token;
1124
- for (const seg of t.segments) {
1125
- processEdgeSegment(seg);
1126
- }
1127
- break;
1128
- }
1129
- case "invisibleEdge": {
1130
- const t = token;
1131
- for (const seg of t.segments) {
1132
- ensureNode(seg.fromId);
1133
- ensureNode(seg.toId);
1134
- }
1135
- const dir = currentDirection();
1136
- const allIds = /* @__PURE__ */ new Set();
1137
- for (const seg of t.segments) {
1138
- allIds.add(seg.fromId);
1139
- allIds.add(seg.toId);
1140
- }
1141
- constraints.push(buildAlignConstraint([...allIds], dir));
1142
- break;
1143
- }
1144
- case "subgraphStart": {
1145
- const t = token;
1146
- scopeStack.push({
1147
- id: t.subgraphId,
1148
- label: t.label,
1149
- nodeIds: []
1150
- });
1151
- break;
1152
- }
1153
- case "subgraphEnd": {
1154
- if (scopeStack.length === 0) {
1155
- diagnostics.push({
1156
- level: "warning",
1157
- message: "Unexpected 'end' without matching subgraph",
1158
- path: `line:${token.line}`
1159
- });
1160
- break;
1161
- }
1162
- const frame = scopeStack.pop();
1163
- groups.push({ frame, children: [...frame.nodeIds] });
1164
- if (scopeStack.length > 0) {
1165
- const parent = scopeStack[scopeStack.length - 1];
1166
- if (!parent.nodeIds.includes(frame.id)) parent.nodeIds.push(frame.id);
1167
- } else {
1168
- if (!rootNodeIds.includes(frame.id)) rootNodeIds.push(frame.id);
1169
- }
1170
- break;
1171
- }
1172
- case "localDirection": {
1173
- const t = token;
1174
- if (scopeStack.length > 0) {
1175
- scopeStack[scopeStack.length - 1].direction = t.dir;
1176
- } else {
1177
- rootDirection = t.dir;
1178
- }
1179
- break;
1180
- }
1181
- case "classDef": {
1182
- const t = token;
1183
- classDefMap.set(t.className, t.styles);
1184
- break;
1185
- }
1186
- case "directive": {
1187
- const t = token;
1188
- processDirective(t);
1189
- break;
1190
- }
1191
- }
1192
- }
1193
- function processEdgeSegment(seg) {
1194
- if (seg.fromDef) {
1195
- registerNode(seg.fromId, seg.fromDef.label, seg.fromDef.shape, seg.fromDef.variant);
1196
- } else {
1197
- ensureNode(seg.fromId);
1198
- }
1199
- if (seg.toDef) {
1200
- registerNode(seg.toId, seg.toDef.label, seg.toDef.shape, seg.toDef.variant);
1201
- } else {
1202
- ensureNode(seg.toId);
1203
- }
1204
- const connectorProps = {
1205
- from: seg.fromId,
1206
- to: seg.toId
1207
- };
1208
- switch (seg.edgeType) {
1209
- case "-->":
1210
- connectorProps.endArrow = "arrow";
1211
- break;
1212
- case "---":
1213
- connectorProps.startArrow = "none";
1214
- connectorProps.endArrow = "none";
1215
- break;
1216
- case "-.->":
1217
- connectorProps.strokeStyle = "dashed";
1218
- connectorProps.endArrow = "arrow";
1219
- break;
1220
- case "==>":
1221
- connectorProps.strokeWidth = 3;
1222
- connectorProps.endArrow = "arrow";
1223
- break;
1224
- }
1225
- const children = [];
1226
- if (seg.edgeLabel) {
1227
- children.push({
1228
- kind: "label",
1229
- props: { text: seg.edgeLabel }
1230
- });
1231
- }
1232
- const connector = {
1233
- kind: "connector",
1234
- props: connectorProps
1235
- };
1236
- if (children.length > 0) {
1237
- connector.children = children;
1238
- }
1239
- connectors.push(connector);
1240
- }
1241
- function processDirective(t) {
1242
- switch (t.directiveType) {
1243
- case "same-width": {
1244
- const props = { targets: t.targets };
1245
- if (t.strategy) props.strategy = t.strategy;
1246
- constraints.push({ kind: "equalizeWidth", props });
1247
- break;
1248
- }
1249
- case "same-height": {
1250
- const props = { targets: t.targets };
1251
- if (t.strategy) props.strategy = t.strategy;
1252
- constraints.push({ kind: "equalizeHeight", props });
1253
- break;
1254
- }
1255
- case "gap": {
1256
- const props = {
1257
- targets: t.targets,
1258
- gap: t.min
1259
- };
1260
- constraints.push({ kind: "minGap", props });
1261
- break;
1262
- }
1263
- case "mover": {
1264
- const props = {
1265
- targets: t.targets,
1266
- mover: t.moverId
1267
- };
1268
- constraints.push({ kind: "alignConstraint", props });
1269
- break;
1270
- }
1271
- }
1272
- }
1273
- const stackKind = rootDirection === "LR" ? "hstack" : "vstack";
1274
- const groupNodes = /* @__PURE__ */ new Map();
1275
- for (const g of groups) {
1276
- const dir = g.frame.direction ?? rootDirection;
1277
- const innerKind = dir === "LR" ? "hstack" : "vstack";
1278
- const groupChildren = [];
1279
- const innerStack = {
1280
- kind: innerKind,
1281
- props: { gap: 60, align: "center" },
1282
- children: []
1283
- };
1284
- for (const childId of g.children) {
1285
- const childGroup = groupNodes.get(childId);
1286
- if (childGroup) {
1287
- innerStack.children.push(childGroup);
1288
- } else {
1289
- const node = nodeMap.get(childId);
1290
- if (node) {
1291
- innerStack.children.push(buildBox(node));
1292
- }
1293
- }
1294
- }
1295
- groupChildren.push(innerStack);
1296
- const groupNode = {
1297
- kind: "group",
1298
- id: g.frame.id,
1299
- props: {},
1300
- children: groupChildren
1301
- };
1302
- if (g.frame.label) {
1303
- groupNode.props.label = g.frame.label;
1304
- }
1305
- groupNodes.set(g.frame.id, groupNode);
1306
- }
1307
- const rootChildren = [];
1308
- for (const id of rootNodeIds) {
1309
- const groupNode = groupNodes.get(id);
1310
- if (groupNode) {
1311
- rootChildren.push(groupNode);
1312
- } else {
1313
- const node = nodeMap.get(id);
1314
- if (node) {
1315
- rootChildren.push(buildBox(node));
1316
- }
1317
- }
1318
- }
1319
- const rootStack = {
1320
- kind: stackKind,
1321
- props: { gap: 60, align: "center" },
1322
- children: rootChildren
1323
- };
1324
- const documentChildren = [rootStack, ...connectors, ...constraints];
1325
- const document = {
1326
- kind: "document",
1327
- props: { padding: 20 },
1328
- children: documentChildren
1329
- };
1330
- return { ir: document, diagnostics };
1331
- }
1332
- function buildBox(node) {
1333
- const props = { shape: node.shape };
1334
- if (node.variant) {
1335
- props.variant = node.variant;
1336
- }
1337
- return {
1338
- kind: "box",
1339
- id: node.id,
1340
- props,
1341
- children: [
1342
- { kind: "text", props: { text: node.label } }
1343
- ]
1344
- };
1345
- }
1346
- function buildAlignConstraint(targets, direction) {
1347
- const axis = direction === "TD" ? "vertical" : "horizontal";
1348
- return {
1349
- kind: "alignConstraint",
1350
- props: {
1351
- targets,
1352
- axis,
1353
- align: "center"
1354
- }
1355
- };
1356
- }
1357
-
1358
- // src/compiler/compiler.ts
1359
- import ts from "typescript";
1360
-
1361
- // src/graph/rule-engine.ts
1362
- import { load } from "js-yaml";
1363
-
1364
- // src/graph/graph-helpers.ts
1365
- function num(v) {
1366
- return v ?? 0;
1367
- }
1368
- function childrenOf(node) {
1369
- return node.children ?? [];
1370
- }
1371
- function slotId(nodeId, kind) {
1372
- return `${nodeId}.${kind}`;
1373
- }
1374
- function ensureSlot(graph, nodeId, kind, value) {
1375
- const id = slotId(nodeId, kind);
1376
- let slot = graph.slots.get(id);
1377
- if (!slot) {
1378
- slot = { id, value, nodeId, slotKind: kind };
1379
- graph.slots.set(id, slot);
1380
- } else if (value !== void 0 && slot.value === void 0) {
1381
- slot.value = value;
1382
- }
1383
- return slot;
1384
- }
1385
- function addCandidate(graph, targetSlotId, value, source, priority, operationId) {
1386
- const candidate = { targetSlotId, value, source, priority, operationId };
1387
- graph.candidates.push(candidate);
1388
- let bySlot = graph.candidatesBySlot.get(targetSlotId);
1389
- if (!bySlot) {
1390
- bySlot = [];
1391
- graph.candidatesBySlot.set(targetSlotId, bySlot);
1392
- }
1393
- bySlot.push(candidate);
1394
- if (operationId) {
1395
- let byOp = graph.candidatesByOperation.get(operationId);
1396
- if (!byOp) {
1397
- byOp = [];
1398
- graph.candidatesByOperation.set(operationId, byOp);
1399
- }
1400
- byOp.push(candidate);
1401
- }
1402
- return candidate;
1403
- }
1404
- function addOperation(graph, id, op, inputs, outputs, compute) {
1405
- const operation = { id, op, inputs, outputs, compute };
1406
- graph.operations.set(id, operation);
1407
- for (const inputSlotId of inputs) {
1408
- graph.dependencies.push({ fromSlotId: inputSlotId, toOperationId: id });
1409
- }
1410
- return operation;
1411
- }
1412
- function addResolver(graph, targetSlotId, policy) {
1413
- if (!graph.resolvers.has(targetSlotId)) {
1414
- graph.resolvers.set(targetSlotId, { slotId: targetSlotId, policy });
1415
- }
1416
- }
1417
- function getNumericProp(node, prop, fallback) {
1418
- const val = node.props[prop];
1419
- if (typeof val === "number") return val;
1420
- if (typeof val === "string") {
1421
- const n = parseFloat(val);
1422
- if (!isNaN(n)) return n;
1423
- }
1424
- return fallback;
1425
- }
1426
- function getStringProp(node, prop, defaultValue) {
1427
- const val = node.props[prop];
1428
- return typeof val === "string" ? val : defaultValue;
1429
- }
1430
- function getSizeProp(node, prop) {
1431
- const val = node.props[prop];
1432
- if (typeof val === "number") return val;
1433
- if (val === "wrap") return "wrap";
1434
- if (val === "fill") return "fill";
1435
- if (typeof val === "string") {
1436
- const n = parseFloat(val);
1437
- if (!isNaN(n)) return n;
1438
- }
1439
- return "wrap";
1440
- }
1441
- function isConstraintKind(kind) {
1442
- return kind === "alignConstraint" || kind === "equalizeWidth" || kind === "equalizeHeight" || kind === "minGap" || kind === "keepInsideConstraint" || kind === "orderConstraint";
1443
- }
1444
- function registerSizeSlots(node, graph, parentId) {
1445
- const id = node.id;
1446
- const widthIntent = getSizeProp(node, "width");
1447
- const heightIntent = getSizeProp(node, "height");
1448
- ensureSlot(graph, id, "resolvedWidth");
1449
- ensureSlot(graph, id, "resolvedHeight");
1450
- ensureSlot(graph, id, "localX");
1451
- ensureSlot(graph, id, "localY");
1452
- if (typeof widthIntent === "number") {
1453
- ensureSlot(graph, id, "contentWidth", widthIntent);
1454
- addCandidate(graph, slotId(id, "contentWidth"), widthIntent, `${node.kind}(${id}).explicit`, "required");
1455
- addCandidate(graph, slotId(id, "resolvedWidth"), widthIntent, `${node.kind}(${id}).explicit`, "normal");
1456
- } else if (widthIntent === "fill" && parentId) {
1457
- ensureSlot(graph, parentId, "availableWidth");
1458
- }
1459
- if (typeof heightIntent === "number") {
1460
- ensureSlot(graph, id, "contentHeight", heightIntent);
1461
- addCandidate(graph, slotId(id, "contentHeight"), heightIntent, `${node.kind}(${id}).explicit`, "required");
1462
- addCandidate(graph, slotId(id, "resolvedHeight"), heightIntent, `${node.kind}(${id}).explicit`, "normal");
1463
- } else if (heightIntent === "fill" && parentId) {
1464
- ensureSlot(graph, parentId, "availableHeight");
1465
- }
1466
- }
1467
-
1468
- // src/graph/east-asian-width.ts
1469
- var WIDE_RANGES = [
1470
- [4352, 4447],
1471
- // Hangul Jamo (leading consonants)
1472
- [8986, 8987],
1473
- // ⌚ ⌛ watch, hourglass
1474
- [9001, 9002],
1475
- // 〈 〉 angle brackets (EAW Wide)
1476
- [9193, 9196],
1477
- // ⏩–⏬ media controls
1478
- [9200, 9200],
1479
- // ⏰ alarm clock
1480
- [9203, 9203],
1481
- // ⏳ hourglass with sand
1482
- [9725, 9726],
1483
- // ◽ ◾ medium small squares
1484
- [9748, 9749],
1485
- // ☔ ☕ umbrella, hot beverage
1486
- [9800, 9811],
1487
- // ♈–♓ zodiac signs
1488
- [9855, 9855],
1489
- // ♿ wheelchair symbol
1490
- [9875, 9875],
1491
- // ⚓ anchor
1492
- [9889, 9889],
1493
- // ⚡ high voltage
1494
- [9898, 9899],
1495
- // ⚪ ⚫ circles
1496
- [9917, 9918],
1497
- // ⚽ ⚾ soccer, baseball
1498
- [9924, 9925],
1499
- // ⛄ ⛅ snowman, sun behind cloud
1500
- [9934, 9934],
1501
- // ⛎ Ophiuchus
1502
- [9940, 9940],
1503
- // ⛔ no entry
1504
- [9962, 9962],
1505
- // ⛪ church
1506
- [9970, 9971],
1507
- // ⛲ ⛳ fountain, flag in hole
1508
- [9973, 9973],
1509
- // ⛵ sailboat
1510
- [9978, 9978],
1511
- // ⛺ tent
1512
- [9981, 9981],
1513
- // ⛽ fuel pump
1514
- [9989, 9989],
1515
- // ✅ check mark button
1516
- [9994, 9995],
1517
- // ✊ ✋ fists
1518
- [10024, 10024],
1519
- // ✨ sparkles
1520
- [10060, 10060],
1521
- // ❌ cross mark
1522
- [10062, 10062],
1523
- // ❎ cross mark button
1524
- [10067, 10069],
1525
- // ❓❔❕ question/exclamation marks
1526
- [10071, 10071],
1527
- // ❗ exclamation mark
1528
- [10133, 10135],
1529
- // ➕➖➗ math signs
1530
- [10160, 10160],
1531
- // ➰ curly loop
1532
- [10175, 10175],
1533
- // ➿ double curly loop
1534
- [11035, 11036],
1535
- // ⬛ ⬜ large squares
1536
- [11088, 11088],
1537
- // ⭐ star
1538
- [11093, 11093],
1539
- // ⭕ heavy large circle
1540
- [11904, 12350],
1541
- // CJK Radicals, Kangxi Radicals, CJK Symbols & Punctuation (incl. U+3000 ideographic space)
1542
- [12353, 13311],
1543
- // Hiragana, Katakana, Bopomofo, Hangul Compat Jamo, Kanbun, CJK Compatibility
1544
- [13312, 19903],
1545
- // CJK Unified Ideographs Extension A
1546
- [19968, 40959],
1547
- // CJK Unified Ideographs
1548
- [40960, 42191],
1549
- // Yi Syllables, Yi Radicals
1550
- [43360, 43391],
1551
- // Hangul Jamo Extended-A
1552
- [44032, 55203],
1553
- // Hangul Syllables
1554
- [63744, 64255],
1555
- // CJK Compatibility Ideographs
1556
- [65040, 65049],
1557
- // Vertical Forms
1558
- [65072, 65106],
1559
- // CJK Compatibility Forms
1560
- [65108, 65126],
1561
- // Small Form Variants
1562
- [65128, 65131],
1563
- // Small Form Variants (fullwidth-ish signs)
1564
- [65281, 65376],
1565
- // Fullwidth Forms (! … ⦆)
1566
- [65504, 65510],
1567
- // Fullwidth signs (¢ £ ¬  ̄ ¦ ¥ ₩)
1568
- [94176, 101759],
1569
- // Tangut, Khitan Small Script, Tangut Supplement (EAW Wide)
1570
- [110576, 111355],
1571
- // Kana Extended-B, Kana Supplement, Kana Extended-A, Small Kana Extension, Nushu
1572
- [126980, 126980],
1573
- // 🀄 mahjong red dragon
1574
- [127183, 127183],
1575
- // 🃏 playing card joker
1576
- [127374, 127374],
1577
- // 🆎 AB blood type button
1578
- [127377, 127386],
1579
- // 🆑–🆚 squared Latin abbreviations
1580
- [127488, 127589],
1581
- // Enclosed Ideographic Supplement (🈁 🈯 squared kana/CJK)
1582
- [127744, 128591],
1583
- // Misc Symbols & Pictographs, Emoticons (emoji, EAW Wide)
1584
- [128640, 128767],
1585
- // Transport and Map Symbols (🚀 …)
1586
- [128992, 129008],
1587
- // Geometric Shapes Extended (colored circles/squares)
1588
- [129280, 129535],
1589
- // Supplemental Symbols & Pictographs (emoji, EAW Wide)
1590
- [129648, 129791],
1591
- // Symbols & Pictographs Extended-A (🩰 🪐 …)
1592
- [131072, 196605],
1593
- // CJK Unified Ideographs Extensions B–F
1594
- [196608, 262141]
1595
- // CJK Unified Ideographs Extension G+
1596
- ];
1597
- function isEastAsianWide(codePoint) {
1598
- let lo = 0;
1599
- let hi = WIDE_RANGES.length - 1;
1600
- while (lo <= hi) {
1601
- const mid = lo + hi >> 1;
1602
- const [start, end] = WIDE_RANGES[mid];
1603
- if (codePoint < start) {
1604
- hi = mid - 1;
1605
- } else if (codePoint > end) {
1606
- lo = mid + 1;
1607
- } else {
1608
- return true;
1609
- }
1610
- }
1611
- return false;
1612
- }
1613
- function approxCharEm(codePoint) {
1614
- return isEastAsianWide(codePoint) ? 1 : 0.6;
1615
- }
1616
-
1617
- // src/graph/ops.ts
1618
- function approxTextWidth(text, fontSize) {
1619
- let width = 0;
1620
- for (const ch of text) {
1621
- width += approxCharEm(ch.codePointAt(0)) * fontSize;
1622
- }
1623
- return width;
1624
- }
1625
- var SIMPLE_FONT_METRICS = {
1626
- CAP_HEIGHT: 0.7,
1627
- ASCENT: 0.9,
1628
- DESCENT: 0.25,
1629
- LINE_HEIGHT: 1.4
1630
- };
1631
- var SimpleTextMeasurer = class {
1632
- measure(text, fontSize, maxWidth) {
1633
- const lineHeight = SIMPLE_FONT_METRICS.LINE_HEIGHT * fontSize;
1634
- if (!text) {
1635
- return { width: 0, height: lineHeight, lines: [""] };
1636
- }
1637
- const measureFn = (t) => approxTextWidth(t, fontSize);
1638
- const lines = wrapLines(text, maxWidth, measureFn);
1639
- const width = Math.max(...lines.map(measureFn));
1640
- const height = lines.length * lineHeight;
1641
- return { width, height, lines };
1642
- }
1643
- metrics(fontSize) {
1644
- return {
1645
- ascent: SIMPLE_FONT_METRICS.ASCENT * fontSize,
1646
- descent: SIMPLE_FONT_METRICS.DESCENT * fontSize,
1647
- capHeight: SIMPLE_FONT_METRICS.CAP_HEIGHT * fontSize,
1648
- lineHeight: SIMPLE_FONT_METRICS.LINE_HEIGHT * fontSize
1649
- };
1650
- }
1651
- };
1652
- var BROWSER_COMPENSATION = 1.1;
1653
- function measureGlyphWidth(font, text, fontSize) {
1654
- const scale = fontSize / font.unitsPerEm;
1655
- let width = 0;
1656
- for (const ch of text) {
1657
- const glyph = font.charToGlyph(ch);
1658
- const missing = glyph.index === 0 || glyph.advanceWidth == null;
1659
- if (missing) {
1660
- width += approxCharEm(ch.codePointAt(0)) * fontSize;
1661
- } else {
1662
- width += glyph.advanceWidth * scale;
1663
- }
1664
- }
1665
- return width * BROWSER_COMPENSATION;
1666
- }
1667
- var OpenTypeTextMeasurer = class _OpenTypeTextMeasurer {
1668
- fonts = /* @__PURE__ */ new Map();
1669
- // Line-box factor shared with the SimpleTextMeasurer SSoT so a single-line
1670
- // text box's measured height matches the line box regardless of measurer.
1671
- lineHeightFactor = SIMPLE_FONT_METRICS.LINE_HEIGHT;
1672
- addFont(key, font) {
1673
- this.fonts.set(key, font);
1674
- }
1675
- /** Canonical CSS font-weight key for "normal" — the default when none given. */
1676
- static DEFAULT_WEIGHT = "400";
1677
- static WEIGHT_ALIASES = {
1678
- normal: "400",
1679
- bold: "700",
1680
- lighter: "300",
1681
- bolder: "700"
1682
- };
1683
- getFont(fontWeight) {
1684
- const raw = fontWeight != null ? String(fontWeight) : _OpenTypeTextMeasurer.DEFAULT_WEIGHT;
1685
- const w = _OpenTypeTextMeasurer.WEIGHT_ALIASES[raw] ?? raw;
1686
- return this.fonts.get(w) ?? this.fonts.get(_OpenTypeTextMeasurer.DEFAULT_WEIGHT) ?? this.fonts.values().next().value;
1687
- }
1688
- measure(text, fontSize, maxWidth, fontWeight) {
1689
- const lineHeight = this.lineHeightFactor * fontSize;
1690
- if (!text) {
1691
- return { width: 0, height: lineHeight, lines: [""] };
1692
- }
1693
- const font = this.getFont(fontWeight);
1694
- if (!font) {
1695
- return new SimpleTextMeasurer().measure(text, fontSize, maxWidth);
1696
- }
1697
- const measureFn = (t) => measureGlyphWidth(font, t, fontSize);
1698
- const lines = wrapLines(text, maxWidth, measureFn);
1699
- const width = Math.max(...lines.map(measureFn));
1700
- const height = lines.length * lineHeight;
1701
- return { width, height, lines };
1702
- }
1703
- /**
1704
- * Real vertical metrics for the weight's font, in px at `fontSize`.
1705
- *
1706
- * capHeight comes from the OS/2 `sCapHeight` field when present; otherwise it
1707
- * is measured from the "H" glyph's bounding box (top-of-cap in font units).
1708
- * If neither is available the loaded font is degenerate, so we defer to the
1709
- * documented {@link SIMPLE_FONT_METRICS} ratio rather than inventing a value.
1710
- * ascent/descent use the OS/2 typographic values, falling back to the
1711
- * hhea ascender/descender, then to the Simple ratios.
1712
- */
1713
- metrics(fontSize, fontWeight) {
1714
- const font = this.getFont(fontWeight);
1715
- if (!font) {
1716
- return new SimpleTextMeasurer().metrics(fontSize);
1717
- }
1718
- const scale = fontSize / font.unitsPerEm;
1719
- const simple = new SimpleTextMeasurer().metrics(fontSize);
1720
- const capUnits = capHeightFontUnits(font);
1721
- const ascentUnits = ascentFontUnits(font);
1722
- const descentUnits = descentFontUnits(font);
1723
- return {
1724
- capHeight: capUnits !== void 0 ? capUnits * scale : simple.capHeight,
1725
- ascent: ascentUnits !== void 0 ? ascentUnits * scale : simple.ascent,
1726
- descent: descentUnits !== void 0 ? descentUnits * scale : simple.descent,
1727
- lineHeight: this.lineHeightFactor * fontSize
1728
- };
1729
- }
1730
- };
1731
- function capHeightFontUnits(font) {
1732
- const os2Cap = font.tables?.os2?.sCapHeight;
1733
- if (os2Cap != null && os2Cap > 0) return os2Cap;
1734
- const h = font.charToGlyph("H");
1735
- const bbox = h.getBoundingBox?.();
1736
- if (bbox && Number.isFinite(bbox.y2) && bbox.y2 > 0) return bbox.y2;
1737
- if (h.yMax != null && h.yMax > 0) return h.yMax;
1738
- return void 0;
1739
- }
1740
- function ascentFontUnits(font) {
1741
- const typo = font.tables?.os2?.sTypoAscender;
1742
- if (typo != null && typo > 0) return typo;
1743
- if (font.ascender != null && font.ascender > 0) return font.ascender;
1744
- return void 0;
1745
- }
1746
- function descentFontUnits(font) {
1747
- const typo = font.tables?.os2?.sTypoDescender;
1748
- if (typo != null) return Math.abs(typo);
1749
- if (font.descender != null) return Math.abs(font.descender);
1750
- return void 0;
1751
- }
1752
- function wrapLines(text, maxWidth, measureFn) {
1753
- const words = text.split(/\s+/);
1754
- const lines = [];
1755
- if (maxWidth !== void 0 && maxWidth > 0) {
1756
- let currentLine = "";
1757
- for (const word of words) {
1758
- const candidate = currentLine ? `${currentLine} ${word}` : word;
1759
- if (measureFn(candidate) > maxWidth && currentLine) {
1760
- lines.push(currentLine);
1761
- currentLine = word;
1762
- } else {
1763
- currentLine = candidate;
1764
- }
1765
- }
1766
- if (currentLine) lines.push(currentLine);
1767
- } else {
1768
- lines.push(text);
1769
- }
1770
- return lines;
1153
+ return lines;
1771
1154
  }
1772
1155
 
1773
1156
  // src/graph/rule-engine.ts
@@ -2160,1315 +1543,2028 @@ function numericParamDefault(rule, paramName) {
2160
1543
  `Rule Catalog error: layout rule '${rule.type}' param '${paramName}' has no numeric default (got ${JSON.stringify(raw)}); every numeric layout param must declare its default: in layout-rules.yaml`
2161
1544
  );
2162
1545
  }
2163
- return raw;
1546
+ return raw;
1547
+ }
1548
+ function stringParamDefault(rule, paramName) {
1549
+ const raw = rule.params?.[paramName]?.default;
1550
+ if (typeof raw !== "string") {
1551
+ throw new Error(
1552
+ `Rule Catalog error: layout rule '${rule.type}' param '${paramName}' has no string default (got ${JSON.stringify(raw)}); declare its default: in layout-rules.yaml`
1553
+ );
1554
+ }
1555
+ return raw;
1556
+ }
1557
+ var CONSTRAINT_DEFAULTS = {
1558
+ /** world_align: horizontal aligns the vertical (Y) coordinate. */
1559
+ alignAxis: "horizontal",
1560
+ /** world_align alignment mode. */
1561
+ alignMode: "start",
1562
+ /** enforce_order / enforce_min_gap operate top-to-bottom by default. */
1563
+ orderAxis: "vertical",
1564
+ /** equalize aggregation strategy when the catalog declares none. */
1565
+ equalizeStrategy: "max"
1566
+ };
1567
+ var UNIVERSAL_PROPS = /* @__PURE__ */ new Set(["id", "geometry"]);
1568
+ function deriveAllowedPropsMap(layoutRulesInput, constraintRulesInput) {
1569
+ const layout2 = layoutRulesInput;
1570
+ const constraints = constraintRulesInput;
1571
+ const map = /* @__PURE__ */ new Map();
1572
+ const stylePropsSection = layout2.style_props;
1573
+ const commonStyles = stylePropsSection?._common ?? [];
1574
+ for (const [ruleKey, rule] of Object.entries(layout2)) {
1575
+ if (ruleKey === "style_props") continue;
1576
+ const paramNames = rule.params ? Object.entries(rule.params).map(([key, p]) => p.from ?? key) : [];
1577
+ const kindStyleProps = stylePropsSection?.[ruleKey] ?? [];
1578
+ if (rule.applies_to) {
1579
+ for (const subKind of Object.keys(rule.applies_to)) {
1580
+ const set = /* @__PURE__ */ new Set([...UNIVERSAL_PROPS, ...paramNames, ...kindStyleProps, ...commonStyles]);
1581
+ const subStyleProps = stylePropsSection?.[subKind] ?? [];
1582
+ for (const p of subStyleProps) set.add(p);
1583
+ map.set(subKind, set);
1584
+ }
1585
+ } else {
1586
+ const inheritsFrom = rule.inherits ? map.get(rule.inherits) : void 0;
1587
+ const set = /* @__PURE__ */ new Set([
1588
+ ...UNIVERSAL_PROPS,
1589
+ ...paramNames,
1590
+ ...kindStyleProps,
1591
+ ...commonStyles,
1592
+ ...inheritsFrom ?? []
1593
+ /* fallback-ok: rule with no `inherits` (or unresolved base) contributes no inherited props */
1594
+ ]);
1595
+ map.set(ruleKey, set);
1596
+ }
1597
+ }
1598
+ for (const [constraintKind, rule] of Object.entries(constraints)) {
1599
+ const props = new Set(UNIVERSAL_PROPS);
1600
+ props.add("targets");
1601
+ if (rule.axis_mapping || rule.axis_to_slot || rule.axis_to_position_slot) props.add("axis");
1602
+ if (rule.priority_from) props.add(rule.priority_from);
1603
+ if (rule.strategy_from) props.add(rule.strategy_from);
1604
+ if (rule.min_gap_from) props.add(rule.min_gap_from);
1605
+ if (rule.reference || rule.movers) props.add("anchor");
1606
+ const moverPropName = rule.movers?.split("??")[0]?.trim();
1607
+ if (moverPropName && /^[A-Za-z_][A-Za-z0-9_]*$/.test(moverPropName)) {
1608
+ props.add(moverPropName);
1609
+ }
1610
+ if (rule.operation === "world_align") props.add("align");
1611
+ map.set(constraintKind, props);
1612
+ }
1613
+ return map;
1614
+ }
1615
+ function buildAllowedPropsMap() {
1616
+ return deriveAllowedPropsMap(layoutRules, constraintRules);
1617
+ }
1618
+ var _allowedPropsMap;
1619
+ function getAllowedProps(kind) {
1620
+ if (!_allowedPropsMap) _allowedPropsMap = buildAllowedPropsMap();
1621
+ return _allowedPropsMap.get(kind);
1622
+ }
1623
+ function buildCatalogKindSet() {
1624
+ const kinds = /* @__PURE__ */ new Set();
1625
+ for (const [ruleKey, rule] of Object.entries(layoutRules)) {
1626
+ if (ruleKey === "style_props") continue;
1627
+ if (rule.applies_to) {
1628
+ for (const subKind of Object.keys(rule.applies_to)) kinds.add(subKind);
1629
+ continue;
1630
+ }
1631
+ kinds.add(ruleKey);
1632
+ if (rule.grid) {
1633
+ kinds.add(rule.grid.row_kind);
1634
+ kinds.add(rule.grid.cell_kind);
1635
+ }
1636
+ }
1637
+ for (const constraintKind of Object.keys(constraintRules)) {
1638
+ kinds.add(constraintKind);
1639
+ }
1640
+ return kinds;
1641
+ }
1642
+ var _catalogKinds;
1643
+ function hasCatalogRule(kind) {
1644
+ if (!_catalogKinds) _catalogKinds = buildCatalogKindSet();
1645
+ return _catalogKinds.has(kind);
1646
+ }
1647
+ function unsupportedKindMessage(kind) {
1648
+ return `Element kind '${kind}' has no layout rules in the Rule Catalog and is not yet supported`;
1649
+ }
1650
+ var MAIN_AXIS_KINDS = {
1651
+ vstack: "localY",
1652
+ hstack: "localX",
1653
+ row: "localX"
1654
+ };
1655
+ function baseMainSlot(mainSlot) {
1656
+ return mainSlot === "localY" ? "baseLocalY" : "baseLocalX";
1657
+ }
1658
+ function getEffectiveSizeIntent(node, prop) {
1659
+ if (node.props[prop] === void 0) {
1660
+ const rule = layoutRules[node.kind];
1661
+ if (rule?.size_from_axis) {
1662
+ const axis = getStringProp(node, "axis", stringParamDefault(rule, "axis"));
1663
+ const spec = rule.size_from_axis[axis]?.[prop];
1664
+ if (spec === "fill") return "fill";
1665
+ if (typeof spec === "number") return spec;
1666
+ }
1667
+ }
1668
+ return getSizeProp(node, prop);
1669
+ }
1670
+ function sizeResolvableIndependently(nodeId, axis, graph) {
1671
+ const node = graph.irNodeMap.get(nodeId);
1672
+ if (!node) return false;
1673
+ const prop = axis === "horizontal" ? "width" : "height";
1674
+ const intent = getEffectiveSizeIntent(node, prop);
1675
+ if (typeof intent === "number") return true;
1676
+ if (intent === "fill") {
1677
+ const parentId = graph.parentMap.get(nodeId);
1678
+ if (!parentId) return false;
1679
+ return parentAvailableConcrete(parentId, axis, graph);
1680
+ }
1681
+ return false;
1682
+ }
1683
+ function parentAvailableConcrete(parentId, axis, graph) {
1684
+ const parentKind = graph.nodeKindMap.get(parentId);
1685
+ if (!parentKind) return false;
1686
+ if (parentKind === "document") return true;
1687
+ const isContainer = parentKind === "box" || parentKind === "group" || parentKind === "overlay" || parentKind === "cell";
1688
+ const isStack = parentKind in MAIN_AXIS_KINDS;
1689
+ if (isContainer || isStack) {
1690
+ return sizeResolvableIndependently(parentId, axis, graph);
1691
+ }
1692
+ return false;
1693
+ }
1694
+ function classifyMainAxisFill(graph, dim, parentId) {
1695
+ const parentKind = graph.nodeKindMap.get(parentId);
1696
+ const parentAxisConfig = parentKind ? STACK_RULE.applies_to?.[parentKind] : void 0;
1697
+ if (!parentAxisConfig || parentAxisConfig.main_size !== dim) return "cross";
1698
+ const axis = dim === "resolvedWidth" ? "horizontal" : "vertical";
1699
+ return sizeResolvableIndependently(parentId, axis, graph) ? "distributed" : "circular";
1700
+ }
1701
+ function suffixShiftSlotId(stackId, index) {
1702
+ return slotId(stackId, `suffixShift.${index}`);
1703
+ }
1704
+ function stackMainAxisContext(targetId, localSlot, graph) {
1705
+ const parentId = graph.parentMap.get(targetId);
1706
+ if (!parentId) return null;
1707
+ const parentKind = graph.nodeKindMap.get(parentId);
1708
+ if (!parentKind) return null;
1709
+ const mainAxis = MAIN_AXIS_KINDS[parentKind];
1710
+ if (!mainAxis || mainAxis !== localSlot) return null;
1711
+ const order = graph.childrenOrderMap.get(parentId);
1712
+ if (!order) return null;
1713
+ const index = order.indexOf(targetId);
1714
+ if (index < 0) return null;
1715
+ return { stackId: parentId, index };
1716
+ }
1717
+ function pickReferenceTarget(targets, localSlot, graph, anchorProp, moverProp) {
1718
+ if (anchorProp) {
1719
+ return {
1720
+ reference: anchorProp,
1721
+ movers: targets.filter((t) => t !== anchorProp)
1722
+ };
1723
+ }
1724
+ if (moverProp) {
1725
+ const reference2 = targets.find((t) => t !== moverProp) ?? targets[0];
1726
+ return { reference: reference2, movers: [moverProp] };
1727
+ }
1728
+ const scored = targets.map((t) => ({ id: t, score: computeFreedomScore(t, localSlot, graph) }));
1729
+ const allMainAxis = scored.every((s) => s.score === 0);
1730
+ if (allMainAxis) {
1731
+ const stackParents = new Set(
1732
+ targets.map((t) => graph.parentMap.get(t)).filter((p) => p !== void 0)
1733
+ );
1734
+ if (stackParents.size === 1) {
1735
+ const stackId = [...stackParents][0];
1736
+ const order = graph.childrenOrderMap.get(stackId);
1737
+ if (order) {
1738
+ let maxIdx = -1;
1739
+ let reference2 = targets[0];
1740
+ for (const t of targets) {
1741
+ const idx = order.indexOf(t);
1742
+ if (idx > maxIdx) {
1743
+ maxIdx = idx;
1744
+ reference2 = t;
1745
+ }
1746
+ }
1747
+ return { reference: reference2, movers: targets.filter((t) => t !== reference2) };
1748
+ }
1749
+ }
1750
+ }
1751
+ scored.sort((a, b) => a.score - b.score);
1752
+ const reference = scored[0].id;
1753
+ return { reference, movers: scored.slice(1).map((s) => s.id) };
2164
1754
  }
2165
- function stringParamDefault(rule, paramName) {
2166
- const raw = rule.params?.[paramName]?.default;
2167
- if (typeof raw !== "string") {
2168
- throw new Error(
2169
- `Rule Catalog error: layout rule '${rule.type}' param '${paramName}' has no string default (got ${JSON.stringify(raw)}); declare its default: in layout-rules.yaml`
2170
- );
1755
+ function computeFreedomScore(targetId, localSlot, graph) {
1756
+ const parentId = graph.parentMap.get(targetId);
1757
+ if (!parentId) return 4;
1758
+ const parentKind = graph.nodeKindMap.get(parentId);
1759
+ if (!parentKind) return 4;
1760
+ if (parentKind === "document") return 4;
1761
+ if (parentKind === "absolute") return 3;
1762
+ const mainAxis = MAIN_AXIS_KINDS[parentKind];
1763
+ if (mainAxis) {
1764
+ return mainAxis === localSlot ? 0 : 2;
2171
1765
  }
2172
- return raw;
1766
+ if (parentKind === "table" || parentKind === "cell" || parentKind === "grid") return 0;
1767
+ if (parentKind === "overlay") return 1;
1768
+ return 2;
2173
1769
  }
2174
- var CONSTRAINT_DEFAULTS = {
2175
- /** world_align: horizontal aligns the vertical (Y) coordinate. */
2176
- alignAxis: "horizontal",
2177
- /** world_align alignment mode. */
2178
- alignMode: "start",
2179
- /** enforce_order / enforce_min_gap operate top-to-bottom by default. */
2180
- orderAxis: "vertical",
2181
- /** equalize aggregation strategy when the catalog declares none. */
2182
- equalizeStrategy: "max"
2183
- };
2184
- var UNIVERSAL_PROPS = /* @__PURE__ */ new Set(["id", "geometry"]);
2185
- function deriveAllowedPropsMap(layoutRulesInput, constraintRulesInput) {
2186
- const layout2 = layoutRulesInput;
2187
- const constraints = constraintRulesInput;
2188
- const map = /* @__PURE__ */ new Map();
2189
- const stylePropsSection = layout2.style_props;
2190
- const commonStyles = stylePropsSection?._common ?? [];
2191
- for (const [ruleKey, rule] of Object.entries(layout2)) {
2192
- if (ruleKey === "style_props") continue;
2193
- const paramNames = rule.params ? Object.entries(rule.params).map(([key, p]) => p.from ?? key) : [];
2194
- const kindStyleProps = stylePropsSection?.[ruleKey] ?? [];
2195
- if (rule.applies_to) {
2196
- for (const subKind of Object.keys(rule.applies_to)) {
2197
- const set = /* @__PURE__ */ new Set([...UNIVERSAL_PROPS, ...paramNames, ...kindStyleProps, ...commonStyles]);
2198
- const subStyleProps = stylePropsSection?.[subKind] ?? [];
2199
- for (const p of subStyleProps) set.add(p);
2200
- map.set(subKind, set);
1770
+ function describeFreedomContext(targetId, localSlot, graph) {
1771
+ const parentId = graph.parentMap.get(targetId);
1772
+ if (!parentId) return "root child";
1773
+ const parentKind = graph.nodeKindMap.get(parentId) ?? "unknown";
1774
+ const mainAxis = MAIN_AXIS_KINDS[parentKind];
1775
+ if (mainAxis && mainAxis === localSlot) {
1776
+ return `main-axis child of ${parentKind}(${parentId})`;
1777
+ }
1778
+ if (mainAxis && mainAxis !== localSlot) {
1779
+ return `cross-axis child of ${parentKind}(${parentId})`;
1780
+ }
1781
+ return `child of ${parentKind}(${parentId})`;
1782
+ }
1783
+ function collectPathLocalSlots(fromId, toAncestorId, localSlotKind, graph) {
1784
+ const slots = [];
1785
+ let current = fromId;
1786
+ while (current !== toAncestorId) {
1787
+ ensureSlot(graph, current, localSlotKind);
1788
+ slots.push(slotId(current, localSlotKind));
1789
+ const parent = graph.parentMap.get(current);
1790
+ if (!parent) break;
1791
+ current = parent;
1792
+ }
1793
+ return slots;
1794
+ }
1795
+ function applyWorldAlign(rule, node, graph) {
1796
+ const targets = node.props.targets;
1797
+ if (!targets || targets.length < 2) return;
1798
+ const axis = getStringProp(node, "axis", CONSTRAINT_DEFAULTS.alignAxis);
1799
+ const alignMode = getStringProp(node, "align", CONSTRAINT_DEFAULTS.alignMode);
1800
+ const strength = node.props.strength ?? rule.default_priority;
1801
+ const mapping = rule.axis_mapping;
1802
+ if (!mapping) return;
1803
+ const axisMap = mapping[axis];
1804
+ if (!axisMap) return;
1805
+ const { world_slot: worldSlot, local_slot: localSlot, size_slot: sizeSlot } = axisMap;
1806
+ let reference;
1807
+ let movers;
1808
+ const anchorProp = node.props.anchor;
1809
+ const moverProp = node.props.mover;
1810
+ if (anchorProp) {
1811
+ if (!targets.includes(anchorProp)) {
1812
+ graph.diagnostics.push({
1813
+ level: "error",
1814
+ message: `AlignConstraint(${node.id}): anchor="${anchorProp}" is not in targets [${targets.join(", ")}].`,
1815
+ path: node.id ?? ""
1816
+ /* fallback-ok: diagnostic path label; constraint nodes without an explicit id fall back to an empty path */
1817
+ });
1818
+ return;
1819
+ }
1820
+ }
1821
+ ({ reference, movers } = pickReferenceTarget(targets, localSlot, graph, anchorProp, moverProp));
1822
+ if (moverProp) {
1823
+ const score = computeFreedomScore(moverProp, localSlot, graph);
1824
+ if (score <= 0) {
1825
+ graph.diagnostics.push({
1826
+ level: "warning",
1827
+ message: `AlignConstraint(${node.id}): mover="${moverProp}" is ${describeFreedomContext(moverProp, localSlot, graph)}. Aligning may break sibling layout.`,
1828
+ path: node.id ?? ""
1829
+ /* fallback-ok: diagnostic path label; constraint nodes without an explicit id fall back to an empty path */
1830
+ });
1831
+ }
1832
+ } else if (!anchorProp) {
1833
+ const scored = targets.map((t) => ({ id: t, score: computeFreedomScore(t, localSlot, graph) }));
1834
+ const allLow = scored.every((s) => s.score <= 0);
1835
+ const allMainAxis = scored.every((s) => s.score === 0);
1836
+ const sameStackAllMain = allMainAxis && new Set(targets.map((t) => graph.parentMap.get(t))).size === 1;
1837
+ if (allLow && !sameStackAllMain) {
1838
+ graph.diagnostics.push({
1839
+ level: "warning",
1840
+ message: `AlignConstraint(${node.id}): all targets have low freedom on ${localSlot}. Alignment may break sibling layout. ` + targets.map((t) => `${t} is ${describeFreedomContext(t, localSlot, graph)}`).join("; ") + ".",
1841
+ path: node.id ?? ""
1842
+ /* fallback-ok: diagnostic path label; constraint nodes without an explicit id fall back to an empty path */
1843
+ });
1844
+ }
1845
+ }
1846
+ const alignRefs = node.props.alignRefs ?? {};
1847
+ const refMeasure = alignRefs[reference] ?? reference;
1848
+ ensureSlot(graph, refMeasure, worldSlot);
1849
+ if (alignMode !== "start") {
1850
+ ensureSlot(graph, refMeasure, sizeSlot);
1851
+ }
1852
+ for (const moverId of movers) {
1853
+ const moverParentId = graph.parentMap.get(moverId);
1854
+ if (!moverParentId) continue;
1855
+ const moverMeasure = alignRefs[moverId] ?? moverId;
1856
+ const stackCtx = stackMainAxisContext(moverId, localSlot, graph);
1857
+ const refStackCtx = stackMainAxisContext(reference, localSlot, graph);
1858
+ const hasMoverPath = moverMeasure !== moverId;
1859
+ const useSuffixShift = stackCtx !== null && !hasMoverPath && (refStackCtx === null || refStackCtx.stackId === stackCtx.stackId || anchorProp !== void 0);
1860
+ if (useSuffixShift && stackCtx) {
1861
+ applySuffixShiftAlign(
1862
+ graph,
1863
+ node,
1864
+ moverId,
1865
+ stackCtx.stackId,
1866
+ stackCtx.index,
1867
+ refMeasure,
1868
+ moverMeasure,
1869
+ alignMode,
1870
+ strength,
1871
+ worldSlot,
1872
+ baseMainSlot(localSlot),
1873
+ sizeSlot,
1874
+ localSlot
1875
+ );
1876
+ continue;
1877
+ }
1878
+ ensureSlot(graph, moverParentId, worldSlot);
1879
+ ensureSlot(graph, moverId, localSlot);
1880
+ const opId = `op.${node.kind}.${node.id}.${moverId}.${localSlot}`;
1881
+ const outputSlotId = slotId(moverId, localSlot);
1882
+ const inputSlots = [
1883
+ slotId(refMeasure, worldSlot),
1884
+ slotId(moverParentId, worldSlot)
1885
+ ];
1886
+ const localSlotKind = localSlot;
1887
+ if (alignMode === "center" || alignMode === "end") {
1888
+ ensureSlot(graph, refMeasure, sizeSlot);
1889
+ inputSlots.push(slotId(refMeasure, sizeSlot));
1890
+ if (moverMeasure === moverId) {
1891
+ ensureSlot(graph, moverId, sizeSlot);
1892
+ inputSlots.push(slotId(moverId, sizeSlot));
1893
+ } else {
1894
+ const pathLocalYSlots = collectPathLocalSlots(
1895
+ moverMeasure,
1896
+ moverId,
1897
+ localSlotKind,
1898
+ graph
1899
+ );
1900
+ ensureSlot(graph, moverMeasure, sizeSlot);
1901
+ for (const s of pathLocalYSlots) inputSlots.push(s);
1902
+ inputSlots.push(slotId(moverMeasure, sizeSlot));
1903
+ }
1904
+ }
1905
+ addCandidate(graph, outputSlotId, void 0, `${node.kind}(${node.id})`, strength, opId);
1906
+ addOperation(graph, opId, "alignDelta", inputSlots, [outputSlotId], (inputs) => {
1907
+ const refWorld = num(inputs[0]);
1908
+ const moverParentWorld = num(inputs[1]);
1909
+ if (alignMode === "center") {
1910
+ const refSize = num(inputs[2]);
1911
+ const refCenter = refWorld + refSize / 2;
1912
+ if (!hasMoverPath) {
1913
+ const moverSize = num(inputs[3]);
1914
+ return [refCenter - moverParentWorld - moverSize / 2];
1915
+ }
1916
+ const pathSlots = inputs.slice(3, -1);
1917
+ const moverMeasureSize = num(inputs[inputs.length - 1]);
1918
+ const internalOffset = pathSlots.reduce((sum, v) => sum + num(v), 0) + moverMeasureSize / 2;
1919
+ return [refCenter - moverParentWorld - internalOffset];
1920
+ }
1921
+ if (alignMode === "end") {
1922
+ const refSize = num(inputs[2]);
1923
+ const refEnd = refWorld + refSize;
1924
+ if (!hasMoverPath) {
1925
+ const moverSize = num(inputs[3]);
1926
+ return [refEnd - moverParentWorld - moverSize];
1927
+ }
1928
+ const pathSlots = inputs.slice(3, -1);
1929
+ const moverMeasureSize = num(inputs[inputs.length - 1]);
1930
+ const internalOffset = pathSlots.reduce((sum, v) => sum + num(v), 0) + moverMeasureSize;
1931
+ return [refEnd - moverParentWorld - internalOffset];
2201
1932
  }
1933
+ return [refWorld - moverParentWorld];
1934
+ });
1935
+ }
1936
+ }
1937
+ function applySuffixShiftAlign(graph, node, moverId, stackId, index, refMeasure, moverMeasure, alignMode, strength, worldSlot, baseMainSlotKind, sizeSlot, _localSlot) {
1938
+ const ssSlotId = suffixShiftSlotId(stackId, index);
1939
+ ensureSlot(graph, stackId, `suffixShift.${index}`);
1940
+ addResolver(graph, ssSlotId, "max");
1941
+ ensureSlot(graph, refMeasure, worldSlot);
1942
+ ensureSlot(graph, stackId, worldSlot);
1943
+ ensureSlot(graph, moverId, baseMainSlotKind);
1944
+ const opId = `op.${node.kind}.${node.id}.${moverId}.suffixShift`;
1945
+ addCandidate(graph, ssSlotId, void 0, `${node.kind}(${node.id}).suffix`, strength, opId);
1946
+ const inputSlots = [
1947
+ slotId(refMeasure, worldSlot),
1948
+ slotId(stackId, worldSlot),
1949
+ slotId(moverId, baseMainSlotKind)
1950
+ ];
1951
+ if (alignMode === "center" || alignMode === "end") {
1952
+ ensureSlot(graph, refMeasure, sizeSlot);
1953
+ inputSlots.push(slotId(refMeasure, sizeSlot));
1954
+ ensureSlot(graph, moverMeasure, sizeSlot);
1955
+ inputSlots.push(slotId(moverMeasure, sizeSlot));
1956
+ }
1957
+ addOperation(graph, opId, "suffixShiftDelta", inputSlots, [ssSlotId], (inputs) => {
1958
+ const refWorld = num(inputs[0]);
1959
+ const stackWorld = num(inputs[1]);
1960
+ const baseLocal = num(inputs[2]);
1961
+ let delta;
1962
+ if (alignMode === "center") {
1963
+ const refSize = num(inputs[3]);
1964
+ const moverSize = num(inputs[4]);
1965
+ delta = refWorld + refSize / 2 - stackWorld - baseLocal - moverSize / 2;
1966
+ } else if (alignMode === "end") {
1967
+ const refSize = num(inputs[3]);
1968
+ const moverSize = num(inputs[4]);
1969
+ delta = refWorld + refSize - stackWorld - baseLocal - moverSize;
2202
1970
  } else {
2203
- const inheritsFrom = rule.inherits ? map.get(rule.inherits) : void 0;
2204
- const set = /* @__PURE__ */ new Set([
2205
- ...UNIVERSAL_PROPS,
2206
- ...paramNames,
2207
- ...kindStyleProps,
2208
- ...commonStyles,
2209
- ...inheritsFrom ?? []
2210
- /* fallback-ok: rule with no `inherits` (or unresolved base) contributes no inherited props */
2211
- ]);
2212
- map.set(ruleKey, set);
1971
+ delta = refWorld - stackWorld - baseLocal;
2213
1972
  }
1973
+ return [Math.max(0, delta)];
1974
+ });
1975
+ }
1976
+ function applyEqualize(rule, node, graph) {
1977
+ const targets = node.props.targets;
1978
+ if (!targets || targets.length < 2) return;
1979
+ const strength = node.props.strength ?? rule.default_priority;
1980
+ const strategy = getStringProp(node, "strategy", rule.default_strategy ?? CONSTRAINT_DEFAULTS.equalizeStrategy);
1981
+ const outputSlotName = rule.slot;
1982
+ const inputSlotName = rule.content_slot;
1983
+ if (!outputSlotName || !inputSlotName) return;
1984
+ const constraintId = node.id;
1985
+ const aggSlotId = `${constraintId}._agg`;
1986
+ ensureSlot(graph, constraintId, "_agg");
1987
+ const gatherOpId = `op.${node.kind}.${constraintId}.gather`;
1988
+ const gatherInputs = [];
1989
+ for (const targetId of targets) {
1990
+ ensureSlot(graph, targetId, inputSlotName);
1991
+ gatherInputs.push(slotId(targetId, inputSlotName));
2214
1992
  }
2215
- for (const [constraintKind, rule] of Object.entries(constraints)) {
2216
- const props = new Set(UNIVERSAL_PROPS);
2217
- props.add("targets");
2218
- if (rule.axis_mapping || rule.axis_to_slot || rule.axis_to_position_slot) props.add("axis");
2219
- if (rule.priority_from) props.add(rule.priority_from);
2220
- if (rule.strategy_from) props.add(rule.strategy_from);
2221
- if (rule.min_gap_from) props.add(rule.min_gap_from);
2222
- if (rule.reference || rule.movers) props.add("anchor");
2223
- const moverPropName = rule.movers?.split("??")[0]?.trim();
2224
- if (moverPropName && /^[A-Za-z_][A-Za-z0-9_]*$/.test(moverPropName)) {
2225
- props.add(moverPropName);
1993
+ addCandidate(graph, aggSlotId, void 0, `${node.kind}(${constraintId}).agg`, "required", gatherOpId);
1994
+ addOperation(graph, gatherOpId, strategy, gatherInputs, [aggSlotId], (inputs) => {
1995
+ const vals = inputs.map((v) => num(v));
1996
+ switch (strategy) {
1997
+ case "min":
1998
+ return [Math.min(...vals)];
1999
+ case "first":
2000
+ return [num(vals[0])];
2001
+ default:
2002
+ return [Math.max(...vals)];
2226
2003
  }
2227
- if (rule.operation === "world_align") props.add("align");
2228
- map.set(constraintKind, props);
2004
+ });
2005
+ const distributeOpId = `op.${node.kind}.${constraintId}.dist`;
2006
+ const distributeOutputs = [];
2007
+ for (const targetId of targets) {
2008
+ ensureSlot(graph, targetId, outputSlotName);
2009
+ const sid = slotId(targetId, outputSlotName);
2010
+ distributeOutputs.push(sid);
2011
+ addCandidate(graph, sid, void 0, `${node.kind}(${constraintId})`, strength, distributeOpId);
2229
2012
  }
2230
- return map;
2231
- }
2232
- function buildAllowedPropsMap() {
2233
- return deriveAllowedPropsMap(layoutRules, constraintRules);
2234
- }
2235
- var _allowedPropsMap;
2236
- function getAllowedProps(kind) {
2237
- if (!_allowedPropsMap) _allowedPropsMap = buildAllowedPropsMap();
2238
- return _allowedPropsMap.get(kind);
2013
+ addOperation(graph, distributeOpId, "copy", [aggSlotId], distributeOutputs, (inputs) => {
2014
+ return targets.map(() => num(inputs[0]));
2015
+ });
2239
2016
  }
2240
- function buildCatalogKindSet() {
2241
- const kinds = /* @__PURE__ */ new Set();
2242
- for (const [ruleKey, rule] of Object.entries(layoutRules)) {
2243
- if (ruleKey === "style_props") continue;
2244
- if (rule.applies_to) {
2245
- for (const subKind of Object.keys(rule.applies_to)) kinds.add(subKind);
2246
- continue;
2247
- }
2248
- kinds.add(ruleKey);
2249
- if (rule.grid) {
2250
- kinds.add(rule.grid.row_kind);
2251
- kinds.add(rule.grid.cell_kind);
2252
- }
2253
- }
2254
- for (const constraintKind of Object.keys(constraintRules)) {
2255
- kinds.add(constraintKind);
2017
+ function applyEnforceOrder(rule, node, graph) {
2018
+ const targets = node.props.targets;
2019
+ if (!targets || targets.length < 2) return;
2020
+ const axis = getStringProp(node, "axis", CONSTRAINT_DEFAULTS.orderAxis);
2021
+ const strength = node.props.strength ?? rule.default_priority;
2022
+ const posSlot = rule.axis_to_slot[axis];
2023
+ const sizeSlot = rule.axis_to_size_slot[axis];
2024
+ for (let i = 1; i < targets.length; i++) {
2025
+ const prev = targets[i - 1];
2026
+ const curr = targets[i];
2027
+ ensureSlot(graph, prev, posSlot);
2028
+ ensureSlot(graph, prev, sizeSlot);
2029
+ ensureSlot(graph, curr, posSlot);
2030
+ const opId = `op.order.${node.id}.${i}`;
2031
+ const inputSlots = [`${prev}.${posSlot}`, `${prev}.${sizeSlot}`];
2032
+ const outputSlotId = `${curr}.${posSlot}`;
2033
+ addCandidate(graph, outputSlotId, void 0, `order(${node.id})`, strength, opId);
2034
+ addOperation(graph, opId, "identity", inputSlots, [outputSlotId], (inputs) => {
2035
+ const prevPos = num(inputs[0]);
2036
+ const prevSize = num(inputs[1]);
2037
+ return [prevPos + prevSize];
2038
+ });
2256
2039
  }
2257
- return kinds;
2258
- }
2259
- var _catalogKinds;
2260
- function hasCatalogRule(kind) {
2261
- if (!_catalogKinds) _catalogKinds = buildCatalogKindSet();
2262
- return _catalogKinds.has(kind);
2263
- }
2264
- function unsupportedKindMessage(kind) {
2265
- return `Element kind '${kind}' has no layout rules in the Rule Catalog and is not yet supported`;
2266
2040
  }
2267
- var MAIN_AXIS_KINDS = {
2268
- vstack: "localY",
2269
- hstack: "localX",
2270
- row: "localX"
2271
- };
2272
- function baseMainSlot(mainSlot) {
2273
- return mainSlot === "localY" ? "baseLocalY" : "baseLocalX";
2041
+ function applyEnforceMinGap(rule, node, graph) {
2042
+ const targets = node.props.targets;
2043
+ if (!targets || targets.length < 2) return;
2044
+ const axis = getStringProp(node, "axis", CONSTRAINT_DEFAULTS.orderAxis);
2045
+ const strength = node.props.strength ?? rule.default_priority;
2046
+ const posSlot = rule.axis_to_position_slot[axis];
2047
+ const sizeSlot = rule.axis_to_size_slot[axis];
2048
+ const minGap = getNumericProp(node, rule.min_gap_from, 0);
2049
+ for (let i = 1; i < targets.length; i++) {
2050
+ const prev = targets[i - 1];
2051
+ const curr = targets[i];
2052
+ ensureSlot(graph, prev, posSlot);
2053
+ ensureSlot(graph, prev, sizeSlot);
2054
+ ensureSlot(graph, curr, posSlot);
2055
+ const opId = `op.gap.${node.id}.${i}`;
2056
+ const inputSlots = [`${prev}.${posSlot}`, `${prev}.${sizeSlot}`];
2057
+ const outputSlotId = `${curr}.${posSlot}`;
2058
+ addCandidate(graph, outputSlotId, void 0, `gap(${node.id})`, strength, opId);
2059
+ addOperation(graph, opId, "identity", inputSlots, [outputSlotId], (inputs) => {
2060
+ const prevPos = num(inputs[0]);
2061
+ const prevSize = num(inputs[1]);
2062
+ return [prevPos + prevSize + minGap];
2063
+ });
2064
+ }
2274
2065
  }
2275
- function getEffectiveSizeIntent(node, prop) {
2276
- if (node.props[prop] === void 0) {
2277
- const rule = layoutRules[node.kind];
2278
- if (rule?.size_from_axis) {
2279
- const axis = getStringProp(node, "axis", stringParamDefault(rule, "axis"));
2280
- const spec = rule.size_from_axis[axis]?.[prop];
2281
- if (spec === "fill") return "fill";
2282
- if (typeof spec === "number") return spec;
2066
+ function applyClampInside(rule, node, graph) {
2067
+ const targets = node.props.targets;
2068
+ if (!targets || targets.length < 2) return;
2069
+ const strength = node.props.strength ?? rule.default_priority;
2070
+ const containerId = targets[0];
2071
+ const contentIds = targets.slice(1);
2072
+ for (const contentId of contentIds) {
2073
+ for (let pi = 0; pi < rule.position_slots.length; pi++) {
2074
+ const posSlot = rule.position_slots[pi];
2075
+ const sizeSlot = rule.size_slots[pi];
2076
+ const containerSizeSlot = sizeSlot;
2077
+ ensureSlot(graph, containerId, containerSizeSlot);
2078
+ ensureSlot(graph, contentId, posSlot);
2079
+ ensureSlot(graph, contentId, sizeSlot);
2080
+ const opId = `op.keepInside.${node.id}.${contentId}.${posSlot}`;
2081
+ const inputSlots = [
2082
+ `${containerId}.${containerSizeSlot}`,
2083
+ `${contentId}.${posSlot}`,
2084
+ `${contentId}.${sizeSlot}`
2085
+ ];
2086
+ const outputSlotId = `${contentId}.${posSlot}`;
2087
+ addCandidate(graph, outputSlotId, void 0, `keepInside(${node.id})`, strength, opId);
2088
+ addOperation(graph, opId, "clamp", inputSlots, [outputSlotId], (inputs) => {
2089
+ const containerSize = num(inputs[0]);
2090
+ const currentPos = num(inputs[1]);
2091
+ const contentSize = num(inputs[2]);
2092
+ const maxPos = containerSize - contentSize;
2093
+ return [Math.max(0, Math.min(currentPos, maxPos))];
2094
+ });
2283
2095
  }
2284
2096
  }
2285
- return getSizeProp(node, prop);
2286
2097
  }
2287
- function suffixShiftSlotId(stackId, index) {
2288
- return slotId(stackId, `suffixShift.${index}`);
2098
+ var CONSTRAINT_HANDLERS = {
2099
+ world_align: applyWorldAlign,
2100
+ equalize: applyEqualize,
2101
+ enforce_order: applyEnforceOrder,
2102
+ enforce_min_gap: applyEnforceMinGap,
2103
+ clamp_inside: applyClampInside
2104
+ };
2105
+ function applyConstraintFromRule(kind, node, graph) {
2106
+ const rule = constraintRules[kind];
2107
+ if (!rule) return false;
2108
+ const handler = CONSTRAINT_HANDLERS[rule.operation];
2109
+ if (!handler) return false;
2110
+ handler(rule, node, graph);
2111
+ return true;
2289
2112
  }
2290
- function stackMainAxisContext(targetId, localSlot, graph) {
2291
- const parentId = graph.parentMap.get(targetId);
2292
- if (!parentId) return null;
2293
- const parentKind = graph.nodeKindMap.get(parentId);
2294
- if (!parentKind) return null;
2295
- const mainAxis = MAIN_AXIS_KINDS[parentKind];
2296
- if (!mainAxis || mainAxis !== localSlot) return null;
2297
- const order = graph.childrenOrderMap.get(parentId);
2298
- if (!order) return null;
2299
- const index = order.indexOf(targetId);
2300
- if (index < 0) return null;
2301
- return { stackId: parentId, index };
2113
+ var textMeasurer = new SimpleTextMeasurer();
2114
+ function setTextMeasurer(m) {
2115
+ textMeasurer = m;
2302
2116
  }
2303
- function pickReferenceTarget(targets, localSlot, graph, anchorProp, moverProp) {
2304
- if (anchorProp) {
2305
- return {
2306
- reference: anchorProp,
2307
- movers: targets.filter((t) => t !== anchorProp)
2308
- };
2309
- }
2310
- if (moverProp) {
2311
- const reference2 = targets.find((t) => t !== moverProp) ?? targets[0];
2312
- return { reference: reference2, movers: [moverProp] };
2313
- }
2314
- const scored = targets.map((t) => ({ id: t, score: computeFreedomScore(t, localSlot, graph) }));
2315
- const allMainAxis = scored.every((s) => s.score === 0);
2316
- if (allMainAxis) {
2317
- const stackParents = new Set(
2318
- targets.map((t) => graph.parentMap.get(t)).filter((p) => p !== void 0)
2319
- );
2320
- if (stackParents.size === 1) {
2321
- const stackId = [...stackParents][0];
2322
- const order = graph.childrenOrderMap.get(stackId);
2323
- if (order) {
2324
- let maxIdx = -1;
2325
- let reference2 = targets[0];
2326
- for (const t of targets) {
2327
- const idx = order.indexOf(t);
2328
- if (idx > maxIdx) {
2329
- maxIdx = idx;
2330
- reference2 = t;
2331
- }
2332
- }
2333
- return { reference: reference2, movers: targets.filter((t) => t !== reference2) };
2117
+ function applyRootRule(rule, node, graph) {
2118
+ const id = node.id;
2119
+ const width = getNumericProp(node, "width", numericParamDefault(rule, "width"));
2120
+ const height = getNumericProp(node, "height", numericParamDefault(rule, "height"));
2121
+ const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
2122
+ ensureSlot(graph, id, "resolvedWidth", width);
2123
+ ensureSlot(graph, id, "resolvedHeight", height);
2124
+ ensureSlot(graph, id, "availableWidth", width - padding * 2);
2125
+ ensureSlot(graph, id, "availableHeight", height - padding * 2);
2126
+ addCandidate(graph, slotId(id, "resolvedWidth"), width, "document(explicit)", "required");
2127
+ addCandidate(graph, slotId(id, "resolvedHeight"), height, "document(explicit)", "required");
2128
+ if (node.children) {
2129
+ for (const child of node.children) {
2130
+ if (child.id && !isConstraintKind(child.kind)) {
2131
+ ensureSlot(graph, child.id, "localX");
2132
+ ensureSlot(graph, child.id, "localY");
2133
+ addCandidate(graph, slotId(child.id, "localX"), padding, `document(${id}).origin`, "weak");
2134
+ addCandidate(graph, slotId(child.id, "localY"), padding, `document(${id}).origin`, "weak");
2334
2135
  }
2335
2136
  }
2336
2137
  }
2337
- scored.sort((a, b) => a.score - b.score);
2338
- const reference = scored[0].id;
2339
- return { reference, movers: scored.slice(1).map((s) => s.id) };
2340
2138
  }
2341
- function computeFreedomScore(targetId, localSlot, graph) {
2342
- const parentId = graph.parentMap.get(targetId);
2343
- if (!parentId) return 4;
2344
- const parentKind = graph.nodeKindMap.get(parentId);
2345
- if (!parentKind) return 4;
2346
- if (parentKind === "document") return 4;
2347
- if (parentKind === "absolute") return 3;
2348
- const mainAxis = MAIN_AXIS_KINDS[parentKind];
2349
- if (mainAxis) {
2350
- return mainAxis === localSlot ? 0 : 2;
2139
+ function applyStackRule(rule, axisConfig, kindName, node, graph, parentId) {
2140
+ const id = node.id;
2141
+ const gap = getNumericProp(node, "gap", numericParamDefault(rule, "gap"));
2142
+ const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
2143
+ const children = childrenOf(node);
2144
+ registerSizeSlots(node, graph, parentId);
2145
+ ensureSlot(graph, id, "contentWidth");
2146
+ ensureSlot(graph, id, "contentHeight");
2147
+ const childIds = children.filter((c) => !isConstraintKind(c.kind)).map((c) => c.id);
2148
+ if (childIds.length === 0) return;
2149
+ graph.childrenOrderMap.set(id, childIds);
2150
+ const mainSlot = axisConfig.main_slot;
2151
+ const crossSlot = axisConfig.cross_slot;
2152
+ const mainSize = axisConfig.main_size;
2153
+ const crossSize = axisConfig.cross_size;
2154
+ const contentMainSize = axisConfig.content_main_size;
2155
+ const contentCrossSize = axisConfig.content_cross_size;
2156
+ const baseMain = baseMainSlot(mainSlot);
2157
+ const opId = `op.${kindName}.${id}`;
2158
+ const inputSlots = [];
2159
+ for (const childId of childIds) {
2160
+ ensureSlot(graph, childId, mainSize);
2161
+ ensureSlot(graph, childId, crossSize);
2162
+ ensureSlot(graph, childId, baseMain);
2163
+ ensureSlot(graph, childId, crossSlot);
2164
+ inputSlots.push(slotId(childId, mainSize));
2351
2165
  }
2352
- if (parentKind === "table" || parentKind === "cell" || parentKind === "grid") return 0;
2353
- if (parentKind === "overlay") return 1;
2354
- return 2;
2355
- }
2356
- function describeFreedomContext(targetId, localSlot, graph) {
2357
- const parentId = graph.parentMap.get(targetId);
2358
- if (!parentId) return "root child";
2359
- const parentKind = graph.nodeKindMap.get(parentId) ?? "unknown";
2360
- const mainAxis = MAIN_AXIS_KINDS[parentKind];
2361
- if (mainAxis && mainAxis === localSlot) {
2362
- return `main-axis child of ${parentKind}(${parentId})`;
2166
+ const baseOutputs = [
2167
+ ...childIds.map((cid) => slotId(cid, baseMain)),
2168
+ slotId(id, contentMainSize),
2169
+ slotId(id, mainSize)
2170
+ ];
2171
+ for (const cid of childIds) {
2172
+ addCandidate(graph, slotId(cid, baseMain), void 0, `${kindName}(${id})`, "strong", opId);
2363
2173
  }
2364
- if (mainAxis && mainAxis !== localSlot) {
2365
- return `cross-axis child of ${parentKind}(${parentId})`;
2174
+ addCandidate(graph, slotId(id, contentMainSize), void 0, `${kindName}(${id}).content`, "strong", opId);
2175
+ addCandidate(graph, slotId(id, mainSize), void 0, `${kindName}(${id}).wrap`, "normal", opId);
2176
+ addOperation(graph, opId, "stackPosition", inputSlots, baseOutputs, (inputs) => {
2177
+ let pos = padding;
2178
+ const positions = [];
2179
+ for (let i = 0; i < inputs.length; i++) {
2180
+ positions.push(pos);
2181
+ pos += inputs[i] + (i < inputs.length - 1 ? gap : 0);
2182
+ }
2183
+ const contentMain = pos - padding;
2184
+ const totalMain = contentMain + padding * 2;
2185
+ return [...positions, contentMain, totalMain];
2186
+ });
2187
+ const suffixShiftSlotIds = [];
2188
+ for (let i = 0; i < childIds.length; i++) {
2189
+ const ssId = suffixShiftSlotId(id, i);
2190
+ ensureSlot(graph, id, `suffixShift.${i}`);
2191
+ addCandidate(graph, ssId, 0, `${kindName}(${id}).suffixShift.${i}`, "weak");
2192
+ addResolver(graph, ssId, "max");
2193
+ suffixShiftSlotIds.push(ssId);
2366
2194
  }
2367
- return `child of ${parentKind}(${parentId})`;
2368
- }
2369
- function collectPathLocalSlots(fromId, toAncestorId, localSlotKind, graph) {
2370
- const slots = [];
2371
- let current = fromId;
2372
- while (current !== toAncestorId) {
2373
- ensureSlot(graph, current, localSlotKind);
2374
- slots.push(slotId(current, localSlotKind));
2375
- const parent = graph.parentMap.get(current);
2376
- if (!parent) break;
2377
- current = parent;
2195
+ const composeOpId = `op.${kindName}.compose.${id}`;
2196
+ const composeInputs = [
2197
+ ...childIds.map((cid) => slotId(cid, baseMain)),
2198
+ ...suffixShiftSlotIds
2199
+ ];
2200
+ const composeOutputs = childIds.map((cid) => slotId(cid, mainSlot));
2201
+ for (const cid of childIds) {
2202
+ addCandidate(graph, slotId(cid, mainSlot), void 0, `${kindName}(${id}).compose`, "strong", composeOpId);
2378
2203
  }
2379
- return slots;
2380
- }
2381
- function applyWorldAlign(rule, node, graph) {
2382
- const targets = node.props.targets;
2383
- if (!targets || targets.length < 2) return;
2384
- const axis = getStringProp(node, "axis", CONSTRAINT_DEFAULTS.alignAxis);
2385
- const alignMode = getStringProp(node, "align", CONSTRAINT_DEFAULTS.alignMode);
2386
- const strength = node.props.strength ?? rule.default_priority;
2387
- const mapping = rule.axis_mapping;
2388
- if (!mapping) return;
2389
- const axisMap = mapping[axis];
2390
- if (!axisMap) return;
2391
- const { world_slot: worldSlot, local_slot: localSlot, size_slot: sizeSlot } = axisMap;
2392
- let reference;
2393
- let movers;
2394
- const anchorProp = node.props.anchor;
2395
- const moverProp = node.props.mover;
2396
- if (anchorProp) {
2397
- if (!targets.includes(anchorProp)) {
2398
- graph.diagnostics.push({
2399
- level: "error",
2400
- message: `AlignConstraint(${node.id}): anchor="${anchorProp}" is not in targets [${targets.join(", ")}].`,
2401
- path: node.id ?? ""
2402
- /* fallback-ok: diagnostic path label; constraint nodes without an explicit id fall back to an empty path */
2403
- });
2404
- return;
2204
+ addOperation(graph, composeOpId, "stackCompose", composeInputs, composeOutputs, (inputs) => {
2205
+ const n = childIds.length;
2206
+ const bases = inputs.slice(0, n);
2207
+ const shifts = inputs.slice(n, n + n);
2208
+ let runningMax = 0;
2209
+ const result = [];
2210
+ for (let j = 0; j < n; j++) {
2211
+ runningMax = Math.max(runningMax, num(shifts[j]));
2212
+ result.push(num(bases[j]) + runningMax);
2405
2213
  }
2406
- }
2407
- ({ reference, movers } = pickReferenceTarget(targets, localSlot, graph, anchorProp, moverProp));
2408
- if (moverProp) {
2409
- const score = computeFreedomScore(moverProp, localSlot, graph);
2410
- if (score <= 0) {
2411
- graph.diagnostics.push({
2412
- level: "warning",
2413
- message: `AlignConstraint(${node.id}): mover="${moverProp}" is ${describeFreedomContext(moverProp, localSlot, graph)}. Aligning may break sibling layout.`,
2414
- path: node.id ?? ""
2415
- /* fallback-ok: diagnostic path label; constraint nodes without an explicit id fall back to an empty path */
2214
+ return result;
2215
+ });
2216
+ const mainPropName = mainSize === "resolvedWidth" ? "width" : "height";
2217
+ const mainAxis = mainSize === "resolvedWidth" ? "horizontal" : "vertical";
2218
+ const selfMainIntent = getSizeProp(node, mainPropName);
2219
+ const mainSizeResolvable = sizeResolvableIndependently(id, mainAxis, graph);
2220
+ const contentChildrenList = children.filter((c) => !isConstraintKind(c.kind));
2221
+ const mainFillChildIndices = [];
2222
+ for (let i = 0; i < childIds.length; i++) {
2223
+ if (getEffectiveSizeIntent(contentChildrenList[i], mainPropName) === "fill") {
2224
+ mainFillChildIndices.push(i);
2225
+ }
2226
+ }
2227
+ const ownedByParentMain = selfMainIntent === "fill" && parentId ? classifyMainAxisFill(graph, mainSize, parentId) === "distributed" : false;
2228
+ const resolvableSlot = slotId(id, "stackMainResolvable");
2229
+ if (mainSizeResolvable && (selfMainIntent === "fill" || mainFillChildIndices.length > 0)) {
2230
+ ensureSlot(graph, id, "stackMainResolvable");
2231
+ const resolveMainOpId = `op.${kindName}.mainResolve.${id}`;
2232
+ if (typeof selfMainIntent === "number") {
2233
+ addCandidate(graph, resolvableSlot, void 0, `${kindName}(${id}).mainResolve`, "strong", resolveMainOpId);
2234
+ addOperation(graph, resolveMainOpId, "resolveSize", [], [resolvableSlot], () => [selfMainIntent]);
2235
+ } else if (!ownedByParentMain) {
2236
+ const parentAvailMainSlot = mainSize === "resolvedWidth" ? "availableWidth" : "availableHeight";
2237
+ const stackParentId = graph.parentMap.get(id);
2238
+ ensureSlot(graph, stackParentId, parentAvailMainSlot);
2239
+ addCandidate(graph, resolvableSlot, void 0, `${kindName}(${id}).mainResolve`, "strong", resolveMainOpId);
2240
+ addCandidate(graph, slotId(id, mainSize), void 0, `${kindName}(${id}).mainFill`, "strong", resolveMainOpId);
2241
+ addOperation(graph, resolveMainOpId, "resolveSize", [slotId(stackParentId, parentAvailMainSlot)], [resolvableSlot, slotId(id, mainSize)], (inputs) => {
2242
+ const v = num(inputs[0]);
2243
+ return [v, v];
2416
2244
  });
2417
2245
  }
2418
- } else if (!anchorProp) {
2419
- const scored = targets.map((t) => ({ id: t, score: computeFreedomScore(t, localSlot, graph) }));
2420
- const allLow = scored.every((s) => s.score <= 0);
2421
- const allMainAxis = scored.every((s) => s.score === 0);
2422
- const sameStackAllMain = allMainAxis && new Set(targets.map((t) => graph.parentMap.get(t))).size === 1;
2423
- if (allLow && !sameStackAllMain) {
2424
- graph.diagnostics.push({
2425
- level: "warning",
2426
- message: `AlignConstraint(${node.id}): all targets have low freedom on ${localSlot}. Alignment may break sibling layout. ` + targets.map((t) => `${t} is ${describeFreedomContext(t, localSlot, graph)}`).join("; ") + ".",
2427
- path: node.id ?? ""
2428
- /* fallback-ok: diagnostic path label; constraint nodes without an explicit id fall back to an empty path */
2246
+ if (mainFillChildIndices.length > 0) {
2247
+ const distributeOpId = `op.${kindName}.mainDistribute.${id}`;
2248
+ const nonFillMainSlots = [];
2249
+ for (let i = 0; i < childIds.length; i++) {
2250
+ if (!mainFillChildIndices.includes(i)) nonFillMainSlots.push(slotId(childIds[i], mainSize));
2251
+ }
2252
+ const distributeInputs = [resolvableSlot, ...nonFillMainSlots];
2253
+ const distributeOutputs = [];
2254
+ for (const i of mainFillChildIndices) {
2255
+ const childMainSlot = slotId(childIds[i], mainSize);
2256
+ distributeOutputs.push(childMainSlot);
2257
+ addCandidate(graph, childMainSlot, void 0, `${kindName}(${id}).mainFill`, "strong", distributeOpId);
2258
+ const childKind = contentChildrenList[i].kind;
2259
+ if (childKind in MAIN_AXIS_KINDS) {
2260
+ const childResolvableSlot = slotId(childIds[i], "stackMainResolvable");
2261
+ ensureSlot(graph, childIds[i], "stackMainResolvable");
2262
+ distributeOutputs.push(childResolvableSlot);
2263
+ addCandidate(graph, childResolvableSlot, void 0, `${kindName}(${id}).mainFill`, "strong", distributeOpId);
2264
+ }
2265
+ }
2266
+ const fillCount = mainFillChildIndices.length;
2267
+ const gapCount = childIds.length - 1;
2268
+ const nStructuralOutputs = distributeOutputs.length;
2269
+ addOperation(graph, distributeOpId, "resolveSize", distributeInputs, distributeOutputs, (inputs) => {
2270
+ const stackMain = num(inputs[0]);
2271
+ const nonFillSum = inputs.slice(1).reduce((s, v) => s + num(v), 0);
2272
+ const remaining = stackMain - padding * 2 - gap * gapCount - nonFillSum;
2273
+ const share = Math.max(0, remaining / fillCount);
2274
+ return new Array(nStructuralOutputs).fill(share);
2429
2275
  });
2430
2276
  }
2431
2277
  }
2432
- const alignRefs = node.props.alignRefs ?? {};
2433
- const refMeasure = alignRefs[reference] ?? reference;
2434
- ensureSlot(graph, refMeasure, worldSlot);
2435
- if (alignMode !== "start") {
2436
- ensureSlot(graph, refMeasure, sizeSlot);
2278
+ const align = getStringProp(node, "align", stringParamDefault(rule, "align"));
2279
+ const crossPropName = crossSize === "resolvedWidth" ? "width" : "height";
2280
+ const availableCrossSlot = crossSize === "resolvedWidth" ? "availableWidth" : "availableHeight";
2281
+ const availableMainSlot = mainSize === "resolvedWidth" ? "availableWidth" : "availableHeight";
2282
+ const selfCrossIntent = getSizeProp(node, crossPropName);
2283
+ const crossOwnedByParent = selfCrossIntent === "fill" && parentId ? classifyMainAxisFill(graph, crossSize, parentId) === "distributed" : false;
2284
+ const fillChildIndices = /* @__PURE__ */ new Set();
2285
+ for (let i = 0; i < childIds.length; i++) {
2286
+ if (getEffectiveSizeIntent(contentChildrenList[i], crossPropName) === "fill") {
2287
+ fillChildIndices.add(i);
2288
+ }
2289
+ }
2290
+ const crossInputSlots = [];
2291
+ for (let i = 0; i < childIds.length; i++) {
2292
+ if (!fillChildIndices.has(i)) {
2293
+ crossInputSlots.push(slotId(childIds[i], crossSize));
2294
+ }
2295
+ }
2296
+ const maxCrossOpId = `op.${kindName}.maxCross.${id}`;
2297
+ addCandidate(graph, slotId(id, contentCrossSize), void 0, `${kindName}(${id}).contentCross`, "strong", maxCrossOpId);
2298
+ addOperation(graph, maxCrossOpId, "max", crossInputSlots, [slotId(id, contentCrossSize)], (inputs) => {
2299
+ return [inputs.length > 0 ? Math.max(...inputs) : 0];
2300
+ });
2301
+ const wrapCrossOpId = `op.${kindName}.wrapCross.${id}`;
2302
+ addCandidate(graph, slotId(id, crossSize), void 0, `${kindName}(${id}).wrapCross`, "normal", wrapCrossOpId);
2303
+ addOperation(graph, wrapCrossOpId, "resolveSize", [slotId(id, contentCrossSize)], [slotId(id, crossSize)], (inputs) => {
2304
+ return [num(inputs[0]) + padding * 2];
2305
+ });
2306
+ if (selfCrossIntent === "fill" && parentId && !crossOwnedByParent) {
2307
+ const parentAvailSlot = crossSize === "resolvedWidth" ? "availableWidth" : "availableHeight";
2308
+ ensureSlot(graph, parentId, parentAvailSlot);
2309
+ const crossFillOpId = `op.${kindName}.crossFill.${id}`;
2310
+ addCandidate(graph, slotId(id, crossSize), void 0, `${kindName}(${id}).crossFill`, "strong", crossFillOpId);
2311
+ addOperation(graph, crossFillOpId, "resolveSize", [slotId(id, contentCrossSize), slotId(parentId, parentAvailSlot)], [slotId(id, crossSize)], (inputs) => {
2312
+ const contentCross = num(inputs[0]);
2313
+ const parentAvail = num(inputs[1]);
2314
+ return [Math.max(contentCross + padding * 2, parentAvail)];
2315
+ });
2316
+ }
2317
+ ensureSlot(graph, id, availableCrossSlot);
2318
+ ensureSlot(graph, id, availableMainSlot);
2319
+ const availCrossOpId = `op.${kindName}.availCross.${id}`;
2320
+ addCandidate(graph, slotId(id, availableCrossSlot), void 0, `${kindName}(${id}).availCross`, "strong", availCrossOpId);
2321
+ addOperation(graph, availCrossOpId, "resolveSize", [slotId(id, crossSize)], [slotId(id, availableCrossSlot)], (inputs) => {
2322
+ return [Math.max(num(inputs[0]) - padding * 2, 0)];
2323
+ });
2324
+ const availMainOpId = `op.${kindName}.availMain.${id}`;
2325
+ addCandidate(graph, slotId(id, availableMainSlot), void 0, `${kindName}(${id}).availMain`, "strong", availMainOpId);
2326
+ addOperation(graph, availMainOpId, "resolveSize", [slotId(id, mainSize)], [slotId(id, availableMainSlot)], (inputs) => {
2327
+ return [Math.max(num(inputs[0]) - padding * 2, 0)];
2328
+ });
2329
+ const crossAlignOpId = `op.${kindName}.crossAlign.${id}`;
2330
+ const allChildCrossSlots = childIds.map((cid) => slotId(cid, crossSize));
2331
+ const crossAlignInputs = [slotId(id, availableCrossSlot), ...allChildCrossSlots];
2332
+ const crossAlignOutputs = childIds.map((cid) => slotId(cid, crossSlot));
2333
+ for (const cid of childIds) {
2334
+ addCandidate(graph, slotId(cid, crossSlot), void 0, `${kindName}(${id}).crossAlign`, "strong", crossAlignOpId);
2335
+ }
2336
+ addOperation(graph, crossAlignOpId, "crossAlign", crossAlignInputs, crossAlignOutputs, (inputs) => {
2337
+ const availCross = num(inputs[0]);
2338
+ const positions = [];
2339
+ for (let i = 0; i < childIds.length; i++) {
2340
+ const childCross = num(inputs[1 + i]);
2341
+ let crossPos = padding;
2342
+ if (align === "center") {
2343
+ crossPos = padding + (availCross - childCross) / 2;
2344
+ } else if (align === "end") {
2345
+ crossPos = padding + availCross - childCross;
2346
+ }
2347
+ positions.push(crossPos);
2348
+ }
2349
+ return positions;
2350
+ });
2351
+ }
2352
+ function rejectMainAxisFill(node, graph, dim, priority, parentId) {
2353
+ const cls = classifyMainAxisFill(graph, dim, parentId);
2354
+ if (cls !== "circular") return cls;
2355
+ const id = node.id;
2356
+ const kind = node.kind;
2357
+ const parentKind = graph.nodeKindMap.get(parentId);
2358
+ const dimName = dim === "resolvedWidth" ? "width" : "height";
2359
+ const rule = layoutRules[kind];
2360
+ const hint = rule?.size_from_axis ? (() => {
2361
+ const axis = getStringProp(node, "axis", stringParamDefault(rule, "axis"));
2362
+ const otherAxis = axis === "horizontal" ? "vertical" : "horizontal";
2363
+ return ` (axis="${axis}") \u2014 use axis="${otherAxis}" or give the ${kind} a fixed-size container`;
2364
+ })() : ` \u2014 give the ${kind} a fixed ${dimName} or place it in a fixed-size container`;
2365
+ graph.diagnostics.push({
2366
+ level: "error",
2367
+ message: `${kind} '${id}' fills its ${dimName} along the stacking axis of ${parentKind} '${parentId}'; a stack's main-axis size is the sum of its children, so this fill is circular and has no defined size${hint}`,
2368
+ path: id
2369
+ });
2370
+ addCandidate(graph, slotId(id, dim), 0, `${kind}(${id}).fill-error`, priority);
2371
+ return "circular";
2372
+ }
2373
+ function applyContainerRule(rule, node, graph, parentId) {
2374
+ const id = node.id;
2375
+ const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
2376
+ registerSizeSlots(node, graph, parentId);
2377
+ ensureSlot(graph, id, "contentWidth");
2378
+ ensureSlot(graph, id, "contentHeight");
2379
+ const widthIntent = getSizeProp(node, "width");
2380
+ const heightIntent = getSizeProp(node, "height");
2381
+ if (widthIntent === "fill" && parentId && rejectMainAxisFill(node, graph, "resolvedWidth", "normal", parentId) === "cross") {
2382
+ const opId = `op.box.fillWidth.${id}`;
2383
+ const outSid = slotId(id, "resolvedWidth");
2384
+ ensureSlot(graph, parentId, "availableWidth");
2385
+ addCandidate(graph, outSid, void 0, `box(${id}).fill`, "normal", opId);
2386
+ addOperation(graph, opId, "resolveSize", [slotId(parentId, "availableWidth")], [outSid], (inputs) => {
2387
+ return [num(inputs[0])];
2388
+ });
2389
+ }
2390
+ if (heightIntent === "fill" && parentId && rejectMainAxisFill(node, graph, "resolvedHeight", "normal", parentId) === "cross") {
2391
+ const opId = `op.box.fillHeight.${id}`;
2392
+ const outSid = slotId(id, "resolvedHeight");
2393
+ ensureSlot(graph, parentId, "availableHeight");
2394
+ addCandidate(graph, outSid, void 0, `box(${id}).fill`, "normal", opId);
2395
+ addOperation(graph, opId, "resolveSize", [slotId(parentId, "availableHeight")], [outSid], (inputs) => {
2396
+ return [num(inputs[0])];
2397
+ });
2437
2398
  }
2438
- for (const moverId of movers) {
2439
- const moverParentId = graph.parentMap.get(moverId);
2440
- if (!moverParentId) continue;
2441
- const moverMeasure = alignRefs[moverId] ?? moverId;
2442
- const stackCtx = stackMainAxisContext(moverId, localSlot, graph);
2443
- const refStackCtx = stackMainAxisContext(reference, localSlot, graph);
2444
- const hasMoverPath = moverMeasure !== moverId;
2445
- const useSuffixShift = stackCtx !== null && !hasMoverPath && (refStackCtx === null || refStackCtx.stackId === stackCtx.stackId || anchorProp !== void 0);
2446
- if (useSuffixShift && stackCtx) {
2447
- applySuffixShiftAlign(
2448
- graph,
2449
- node,
2450
- moverId,
2451
- stackCtx.stackId,
2452
- stackCtx.index,
2453
- refMeasure,
2454
- moverMeasure,
2455
- alignMode,
2456
- strength,
2457
- worldSlot,
2458
- baseMainSlot(localSlot),
2459
- sizeSlot,
2460
- localSlot
2461
- );
2462
- continue;
2399
+ const wrapWidthOpId = `op.box.wrapWidth.${id}`;
2400
+ const wrapHeightOpId = `op.box.wrapHeight.${id}`;
2401
+ if (widthIntent === "wrap") {
2402
+ const outSid = slotId(id, "resolvedWidth");
2403
+ addCandidate(graph, outSid, void 0, `box(${id}).wrap`, "weak", wrapWidthOpId);
2404
+ addOperation(graph, wrapWidthOpId, "resolveSize", [slotId(id, "contentWidth")], [outSid], (inputs) => {
2405
+ return [num(inputs[0]) + padding * 2];
2406
+ });
2407
+ }
2408
+ if (heightIntent === "wrap") {
2409
+ const outSid = slotId(id, "resolvedHeight");
2410
+ addCandidate(graph, outSid, void 0, `box(${id}).wrap`, "weak", wrapHeightOpId);
2411
+ addOperation(graph, wrapHeightOpId, "resolveSize", [slotId(id, "contentHeight")], [outSid], (inputs) => {
2412
+ return [num(inputs[0]) + padding * 2];
2413
+ });
2414
+ }
2415
+ const availWidthOpId = `op.box.availW.${id}`;
2416
+ ensureSlot(graph, id, "availableWidth");
2417
+ addCandidate(graph, slotId(id, "availableWidth"), void 0, `box(${id}).availW`, "normal", availWidthOpId);
2418
+ addOperation(graph, availWidthOpId, "resolveSize", [slotId(id, "resolvedWidth")], [slotId(id, "availableWidth")], (inputs) => {
2419
+ return [Math.max(num(inputs[0]) - padding * 2, 0)];
2420
+ });
2421
+ const availHeightOpId = `op.box.availH.${id}`;
2422
+ ensureSlot(graph, id, "availableHeight");
2423
+ addCandidate(graph, slotId(id, "availableHeight"), void 0, `box(${id}).availH`, "normal", availHeightOpId);
2424
+ addOperation(graph, availHeightOpId, "resolveSize", [slotId(id, "resolvedHeight")], [slotId(id, "availableHeight")], (inputs) => {
2425
+ return [Math.max(num(inputs[0]) - padding * 2, 0)];
2426
+ });
2427
+ const children = childrenOf(node);
2428
+ const contentChildIds = children.filter((c) => !isConstraintKind(c.kind)).map((c) => c.id);
2429
+ if (contentChildIds.length > 0) {
2430
+ for (const childId of contentChildIds) {
2431
+ ensureSlot(graph, childId, "resolvedWidth");
2432
+ ensureSlot(graph, childId, "resolvedHeight");
2433
+ ensureSlot(graph, childId, "localX");
2434
+ ensureSlot(graph, childId, "localY");
2463
2435
  }
2464
- ensureSlot(graph, moverParentId, worldSlot);
2465
- ensureSlot(graph, moverId, localSlot);
2466
- const opId = `op.${node.kind}.${node.id}.${moverId}.${localSlot}`;
2467
- const outputSlotId = slotId(moverId, localSlot);
2468
- const inputSlots = [
2469
- slotId(refMeasure, worldSlot),
2470
- slotId(moverParentId, worldSlot)
2471
- ];
2472
- const localSlotKind = localSlot;
2473
- if (alignMode === "center" || alignMode === "end") {
2474
- ensureSlot(graph, refMeasure, sizeSlot);
2475
- inputSlots.push(slotId(refMeasure, sizeSlot));
2476
- if (moverMeasure === moverId) {
2477
- ensureSlot(graph, moverId, sizeSlot);
2478
- inputSlots.push(slotId(moverId, sizeSlot));
2479
- } else {
2480
- const pathLocalYSlots = collectPathLocalSlots(
2481
- moverMeasure,
2482
- moverId,
2483
- localSlotKind,
2484
- graph
2485
- );
2486
- ensureSlot(graph, moverMeasure, sizeSlot);
2487
- for (const s of pathLocalYSlots) inputSlots.push(s);
2488
- inputSlots.push(slotId(moverMeasure, sizeSlot));
2489
- }
2436
+ const contentOpId = `op.box.content.${id}`;
2437
+ const childWidthSlots = contentChildIds.map((cid) => slotId(cid, "resolvedWidth"));
2438
+ const childHeightSlots = contentChildIds.map((cid) => slotId(cid, "resolvedHeight"));
2439
+ const allInputs = [...childWidthSlots, ...childHeightSlots];
2440
+ const contentOutputs = [slotId(id, "contentWidth"), slotId(id, "contentHeight")];
2441
+ addCandidate(graph, slotId(id, "contentWidth"), void 0, `box(${id}).childContent`, "normal", contentOpId);
2442
+ addCandidate(graph, slotId(id, "contentHeight"), void 0, `box(${id}).childContent`, "normal", contentOpId);
2443
+ addOperation(graph, contentOpId, "resolveSize", allInputs, contentOutputs, (inputs) => {
2444
+ const nChildren = contentChildIds.length;
2445
+ const widths = inputs.slice(0, nChildren);
2446
+ const heights = inputs.slice(nChildren);
2447
+ return [Math.max(...widths, 0), Math.max(...heights, 0)];
2448
+ });
2449
+ const hasAlignParams = rule.params?.colAlign !== void 0;
2450
+ const colAlign = hasAlignParams ? node.props.colAlign ?? rule.params.colAlign.default : void 0;
2451
+ const rowAlign = hasAlignParams ? node.props.rowAlign ?? rule.params.rowAlign.default : void 0;
2452
+ const alignOpId = `op.box.center.${id}`;
2453
+ const alignInputs = [slotId(id, "resolvedWidth"), slotId(id, "resolvedHeight"), ...childWidthSlots, ...childHeightSlots];
2454
+ const alignOutputs = contentChildIds.flatMap((cid) => [slotId(cid, "localX"), slotId(cid, "localY")]);
2455
+ for (const cid of contentChildIds) {
2456
+ addCandidate(graph, slotId(cid, "localX"), void 0, `box(${id}).center`, "normal", alignOpId);
2457
+ addCandidate(graph, slotId(cid, "localY"), void 0, `box(${id}).center`, "normal", alignOpId);
2490
2458
  }
2491
- addCandidate(graph, outputSlotId, void 0, `${node.kind}(${node.id})`, strength, opId);
2492
- addOperation(graph, opId, "alignDelta", inputSlots, [outputSlotId], (inputs) => {
2493
- const refWorld = num(inputs[0]);
2494
- const moverParentWorld = num(inputs[1]);
2495
- if (alignMode === "center") {
2496
- const refSize = num(inputs[2]);
2497
- const refCenter = refWorld + refSize / 2;
2498
- if (!hasMoverPath) {
2499
- const moverSize = num(inputs[3]);
2500
- return [refCenter - moverParentWorld - moverSize / 2];
2459
+ addOperation(graph, alignOpId, "resolveSize", alignInputs, alignOutputs, (inputs) => {
2460
+ const boxW = num(inputs[0]);
2461
+ const boxH = num(inputs[1]);
2462
+ const nChildren = contentChildIds.length;
2463
+ const result = [];
2464
+ for (let i = 0; i < nChildren; i++) {
2465
+ const cw = num(inputs[2 + i]);
2466
+ const ch = num(inputs[2 + nChildren + i]);
2467
+ let cx;
2468
+ if (colAlign !== void 0) {
2469
+ switch (colAlign) {
2470
+ case "center":
2471
+ cx = (boxW - cw) / 2;
2472
+ break;
2473
+ case "right":
2474
+ cx = boxW - cw - padding;
2475
+ break;
2476
+ default:
2477
+ cx = padding;
2478
+ break;
2479
+ }
2480
+ } else {
2481
+ cx = (boxW - cw) / 2;
2501
2482
  }
2502
- const pathSlots = inputs.slice(3, -1);
2503
- const moverMeasureSize = num(inputs[inputs.length - 1]);
2504
- const internalOffset = pathSlots.reduce((sum, v) => sum + num(v), 0) + moverMeasureSize / 2;
2505
- return [refCenter - moverParentWorld - internalOffset];
2506
- }
2507
- if (alignMode === "end") {
2508
- const refSize = num(inputs[2]);
2509
- const refEnd = refWorld + refSize;
2510
- if (!hasMoverPath) {
2511
- const moverSize = num(inputs[3]);
2512
- return [refEnd - moverParentWorld - moverSize];
2483
+ let cy;
2484
+ if (rowAlign !== void 0) {
2485
+ switch (rowAlign) {
2486
+ case "center":
2487
+ cy = (boxH - ch) / 2;
2488
+ break;
2489
+ case "bottom":
2490
+ cy = boxH - ch - padding;
2491
+ break;
2492
+ default:
2493
+ cy = padding;
2494
+ break;
2495
+ }
2496
+ } else {
2497
+ cy = (boxH - ch) / 2;
2513
2498
  }
2514
- const pathSlots = inputs.slice(3, -1);
2515
- const moverMeasureSize = num(inputs[inputs.length - 1]);
2516
- const internalOffset = pathSlots.reduce((sum, v) => sum + num(v), 0) + moverMeasureSize;
2517
- return [refEnd - moverParentWorld - internalOffset];
2499
+ result.push(cx, cy);
2518
2500
  }
2519
- return [refWorld - moverParentWorld];
2501
+ return result;
2520
2502
  });
2521
2503
  }
2522
- }
2523
- function applySuffixShiftAlign(graph, node, moverId, stackId, index, refMeasure, moverMeasure, alignMode, strength, worldSlot, baseMainSlotKind, sizeSlot, _localSlot) {
2524
- const ssSlotId = suffixShiftSlotId(stackId, index);
2525
- ensureSlot(graph, stackId, `suffixShift.${index}`);
2526
- addResolver(graph, ssSlotId, "max");
2527
- ensureSlot(graph, refMeasure, worldSlot);
2528
- ensureSlot(graph, stackId, worldSlot);
2529
- ensureSlot(graph, moverId, baseMainSlotKind);
2530
- const opId = `op.${node.kind}.${node.id}.${moverId}.suffixShift`;
2531
- addCandidate(graph, ssSlotId, void 0, `${node.kind}(${node.id}).suffix`, strength, opId);
2532
- const inputSlots = [
2533
- slotId(refMeasure, worldSlot),
2534
- slotId(stackId, worldSlot),
2535
- slotId(moverId, baseMainSlotKind)
2536
- ];
2537
- if (alignMode === "center" || alignMode === "end") {
2538
- ensureSlot(graph, refMeasure, sizeSlot);
2539
- inputSlots.push(slotId(refMeasure, sizeSlot));
2540
- ensureSlot(graph, moverMeasure, sizeSlot);
2541
- inputSlots.push(slotId(moverMeasure, sizeSlot));
2504
+ }
2505
+ function applyTextMeasurementRule(rule, node, graph, parentId) {
2506
+ const id = node.id;
2507
+ const text = getStringProp(node, "text", stringParamDefault(rule, "text"));
2508
+ const fontSize = getNumericProp(node, "fontSize", numericParamDefault(rule, "fontSize"));
2509
+ const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
2510
+ const textAlign = getStringProp(node, "textAlign", stringParamDefault(rule, "textAlign"));
2511
+ ensureSlot(graph, id, "resolvedWidth");
2512
+ ensureSlot(graph, id, "resolvedHeight");
2513
+ ensureSlot(graph, id, "localX");
2514
+ ensureSlot(graph, id, "localY");
2515
+ const fontWeight = node.props.fontWeight;
2516
+ const measurement = textMeasurer.measure(text, fontSize, void 0, fontWeight);
2517
+ const intrinsicW = measurement.width + padding * 2;
2518
+ const intrinsicH = measurement.height + padding * 2;
2519
+ ensureSlot(graph, id, "intrinsicWidth", intrinsicW);
2520
+ ensureSlot(graph, id, "intrinsicHeight", intrinsicH);
2521
+ addCandidate(graph, slotId(id, "resolvedWidth"), intrinsicW, `text(${id}).intrinsic`, "normal");
2522
+ addCandidate(graph, slotId(id, "resolvedHeight"), intrinsicH, `text(${id}).intrinsic`, "normal");
2523
+ if (parentId) {
2524
+ ensureSlot(graph, id, "contentWidth", intrinsicW);
2525
+ ensureSlot(graph, id, "contentHeight", intrinsicH);
2526
+ }
2527
+ const lineCount = measurement.lines.length;
2528
+ const fontMetrics = textMeasurer.metrics(fontSize, fontWeight);
2529
+ const { capHeight, lineHeight } = fontMetrics;
2530
+ let textAnchorVal;
2531
+ switch (textAlign) {
2532
+ case "start":
2533
+ case "left":
2534
+ textAnchorVal = 0;
2535
+ break;
2536
+ case "end":
2537
+ case "right":
2538
+ textAnchorVal = 2;
2539
+ break;
2540
+ default:
2541
+ textAnchorVal = 1;
2542
+ break;
2542
2543
  }
2543
- addOperation(graph, opId, "suffixShiftDelta", inputSlots, [ssSlotId], (inputs) => {
2544
- const refWorld = num(inputs[0]);
2545
- const stackWorld = num(inputs[1]);
2546
- const baseLocal = num(inputs[2]);
2547
- let delta;
2548
- if (alignMode === "center") {
2549
- const refSize = num(inputs[3]);
2550
- const moverSize = num(inputs[4]);
2551
- delta = refWorld + refSize / 2 - stackWorld - baseLocal - moverSize / 2;
2552
- } else if (alignMode === "end") {
2553
- const refSize = num(inputs[3]);
2554
- const moverSize = num(inputs[4]);
2555
- delta = refWorld + refSize - stackWorld - baseLocal - moverSize;
2556
- } else {
2557
- delta = refWorld - stackWorld - baseLocal;
2544
+ ensureSlot(graph, id, "textBaseline");
2545
+ ensureSlot(graph, id, "textLineHeight");
2546
+ ensureSlot(graph, id, "textX");
2547
+ ensureSlot(graph, id, "textAnchor");
2548
+ const textLayoutOpId = `op.textLayout.${id}`;
2549
+ const textLayoutInputs = [slotId(id, "resolvedWidth"), slotId(id, "resolvedHeight")];
2550
+ const textLayoutOutputs = [
2551
+ slotId(id, "textBaseline"),
2552
+ slotId(id, "textX"),
2553
+ slotId(id, "textAnchor"),
2554
+ slotId(id, "textLineHeight")
2555
+ ];
2556
+ addCandidate(graph, slotId(id, "textBaseline"), void 0, `text(${id}).layout`, "normal", textLayoutOpId);
2557
+ addCandidate(graph, slotId(id, "textX"), void 0, `text(${id}).layout`, "normal", textLayoutOpId);
2558
+ addCandidate(graph, slotId(id, "textAnchor"), void 0, `text(${id}).layout`, "normal", textLayoutOpId);
2559
+ addCandidate(graph, slotId(id, "textLineHeight"), void 0, `text(${id}).layout`, "normal", textLayoutOpId);
2560
+ addOperation(graph, textLayoutOpId, "identity", textLayoutInputs, textLayoutOutputs, (inputs) => {
2561
+ const w = num(inputs[0]);
2562
+ const h = num(inputs[1]);
2563
+ const visualExtent = capHeight + (lineCount - 1) * lineHeight;
2564
+ const baseline = (h - visualExtent) / 2 + capHeight;
2565
+ let tx;
2566
+ switch (textAnchorVal) {
2567
+ case 0:
2568
+ tx = 0;
2569
+ break;
2570
+ case 2:
2571
+ tx = w;
2572
+ break;
2573
+ default:
2574
+ tx = w / 2;
2575
+ break;
2558
2576
  }
2559
- return [Math.max(0, delta)];
2577
+ return [baseline, tx, textAnchorVal, lineHeight];
2560
2578
  });
2561
2579
  }
2562
- function applyEqualize(rule, node, graph) {
2563
- const targets = node.props.targets;
2564
- if (!targets || targets.length < 2) return;
2565
- const strength = node.props.strength ?? rule.default_priority;
2566
- const strategy = getStringProp(node, "strategy", rule.default_strategy ?? CONSTRAINT_DEFAULTS.equalizeStrategy);
2567
- const outputSlotName = rule.slot;
2568
- const inputSlotName = rule.content_slot;
2569
- if (!outputSlotName || !inputSlotName) return;
2570
- const constraintId = node.id;
2571
- const aggSlotId = `${constraintId}._agg`;
2572
- ensureSlot(graph, constraintId, "_agg");
2573
- const gatherOpId = `op.${node.kind}.${constraintId}.gather`;
2574
- const gatherInputs = [];
2575
- for (const targetId of targets) {
2576
- ensureSlot(graph, targetId, inputSlotName);
2577
- gatherInputs.push(slotId(targetId, inputSlotName));
2580
+ function applyOverlayRule(rule, node, graph, parentId) {
2581
+ const id = node.id;
2582
+ const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
2583
+ registerSizeSlots(node, graph, parentId);
2584
+ ensureSlot(graph, id, "contentWidth");
2585
+ ensureSlot(graph, id, "contentHeight");
2586
+ const children = childrenOf(node);
2587
+ const childIds = children.filter((c) => !isConstraintKind(c.kind)).map((c) => c.id);
2588
+ for (const childId of childIds) {
2589
+ ensureSlot(graph, childId, "localX", padding);
2590
+ ensureSlot(graph, childId, "localY", padding);
2591
+ addCandidate(graph, slotId(childId, "localX"), padding, `overlay(${id})`, "normal");
2592
+ addCandidate(graph, slotId(childId, "localY"), padding, `overlay(${id})`, "normal");
2578
2593
  }
2579
- addCandidate(graph, aggSlotId, void 0, `${node.kind}(${constraintId}).agg`, "required", gatherOpId);
2580
- addOperation(graph, gatherOpId, strategy, gatherInputs, [aggSlotId], (inputs) => {
2581
- const vals = inputs.map((v) => num(v));
2582
- switch (strategy) {
2583
- case "min":
2584
- return [Math.min(...vals)];
2585
- case "first":
2586
- return [num(vals[0])];
2587
- default:
2588
- return [Math.max(...vals)];
2594
+ if (childIds.length > 0) {
2595
+ for (const childId of childIds) {
2596
+ ensureSlot(graph, childId, "resolvedWidth");
2597
+ ensureSlot(graph, childId, "resolvedHeight");
2589
2598
  }
2590
- });
2591
- const distributeOpId = `op.${node.kind}.${constraintId}.dist`;
2592
- const distributeOutputs = [];
2593
- for (const targetId of targets) {
2594
- ensureSlot(graph, targetId, outputSlotName);
2595
- const sid = slotId(targetId, outputSlotName);
2596
- distributeOutputs.push(sid);
2597
- addCandidate(graph, sid, void 0, `${node.kind}(${constraintId})`, strength, distributeOpId);
2599
+ const contentOpId = `op.overlay.content.${id}`;
2600
+ const childWidthSlots = childIds.map((cid) => slotId(cid, "resolvedWidth"));
2601
+ const childHeightSlots = childIds.map((cid) => slotId(cid, "resolvedHeight"));
2602
+ const contentInputs = [...childWidthSlots, ...childHeightSlots];
2603
+ const contentOutputs = [slotId(id, "contentWidth"), slotId(id, "contentHeight")];
2604
+ addCandidate(graph, slotId(id, "contentWidth"), void 0, `overlay(${id}).childContent`, "normal", contentOpId);
2605
+ addCandidate(graph, slotId(id, "contentHeight"), void 0, `overlay(${id}).childContent`, "normal", contentOpId);
2606
+ addOperation(graph, contentOpId, "resolveSize", contentInputs, contentOutputs, (inputs) => {
2607
+ const nChildren = childIds.length;
2608
+ const widths = inputs.slice(0, nChildren);
2609
+ const heights = inputs.slice(nChildren);
2610
+ return [Math.max(...widths, 0), Math.max(...heights, 0)];
2611
+ });
2598
2612
  }
2599
- addOperation(graph, distributeOpId, "copy", [aggSlotId], distributeOutputs, (inputs) => {
2600
- return targets.map(() => num(inputs[0]));
2601
- });
2602
- }
2603
- function applyEnforceOrder(rule, node, graph) {
2604
- const targets = node.props.targets;
2605
- if (!targets || targets.length < 2) return;
2606
- const axis = getStringProp(node, "axis", CONSTRAINT_DEFAULTS.orderAxis);
2607
- const strength = node.props.strength ?? rule.default_priority;
2608
- const posSlot = rule.axis_to_slot[axis];
2609
- const sizeSlot = rule.axis_to_size_slot[axis];
2610
- for (let i = 1; i < targets.length; i++) {
2611
- const prev = targets[i - 1];
2612
- const curr = targets[i];
2613
- ensureSlot(graph, prev, posSlot);
2614
- ensureSlot(graph, prev, sizeSlot);
2615
- ensureSlot(graph, curr, posSlot);
2616
- const opId = `op.order.${node.id}.${i}`;
2617
- const inputSlots = [`${prev}.${posSlot}`, `${prev}.${sizeSlot}`];
2618
- const outputSlotId = `${curr}.${posSlot}`;
2619
- addCandidate(graph, outputSlotId, void 0, `order(${node.id})`, strength, opId);
2620
- addOperation(graph, opId, "identity", inputSlots, [outputSlotId], (inputs) => {
2621
- const prevPos = num(inputs[0]);
2622
- const prevSize = num(inputs[1]);
2623
- return [prevPos + prevSize];
2613
+ const widthIntent = getSizeProp(node, "width");
2614
+ const heightIntent = getSizeProp(node, "height");
2615
+ if (widthIntent === "wrap") {
2616
+ const wrapWidthOpId = `op.overlay.wrapWidth.${id}`;
2617
+ const outSid = slotId(id, "resolvedWidth");
2618
+ addCandidate(graph, outSid, void 0, `overlay(${id}).wrap`, "weak", wrapWidthOpId);
2619
+ addOperation(graph, wrapWidthOpId, "resolveSize", [slotId(id, "contentWidth")], [outSid], (inputs) => {
2620
+ return [num(inputs[0]) + padding * 2];
2624
2621
  });
2625
2622
  }
2626
- }
2627
- function applyEnforceMinGap(rule, node, graph) {
2628
- const targets = node.props.targets;
2629
- if (!targets || targets.length < 2) return;
2630
- const axis = getStringProp(node, "axis", CONSTRAINT_DEFAULTS.orderAxis);
2631
- const strength = node.props.strength ?? rule.default_priority;
2632
- const posSlot = rule.axis_to_position_slot[axis];
2633
- const sizeSlot = rule.axis_to_size_slot[axis];
2634
- const minGap = getNumericProp(node, rule.min_gap_from, 0);
2635
- for (let i = 1; i < targets.length; i++) {
2636
- const prev = targets[i - 1];
2637
- const curr = targets[i];
2638
- ensureSlot(graph, prev, posSlot);
2639
- ensureSlot(graph, prev, sizeSlot);
2640
- ensureSlot(graph, curr, posSlot);
2641
- const opId = `op.gap.${node.id}.${i}`;
2642
- const inputSlots = [`${prev}.${posSlot}`, `${prev}.${sizeSlot}`];
2643
- const outputSlotId = `${curr}.${posSlot}`;
2644
- addCandidate(graph, outputSlotId, void 0, `gap(${node.id})`, strength, opId);
2645
- addOperation(graph, opId, "identity", inputSlots, [outputSlotId], (inputs) => {
2646
- const prevPos = num(inputs[0]);
2647
- const prevSize = num(inputs[1]);
2648
- return [prevPos + prevSize + minGap];
2623
+ if (heightIntent === "wrap") {
2624
+ const wrapHeightOpId = `op.overlay.wrapHeight.${id}`;
2625
+ const outSid = slotId(id, "resolvedHeight");
2626
+ addCandidate(graph, outSid, void 0, `overlay(${id}).wrap`, "weak", wrapHeightOpId);
2627
+ addOperation(graph, wrapHeightOpId, "resolveSize", [slotId(id, "contentHeight")], [outSid], (inputs) => {
2628
+ return [num(inputs[0]) + padding * 2];
2649
2629
  });
2650
2630
  }
2651
- }
2652
- function applyClampInside(rule, node, graph) {
2653
- const targets = node.props.targets;
2654
- if (!targets || targets.length < 2) return;
2655
- const strength = node.props.strength ?? rule.default_priority;
2656
- const containerId = targets[0];
2657
- const contentIds = targets.slice(1);
2658
- for (const contentId of contentIds) {
2659
- for (let pi = 0; pi < rule.position_slots.length; pi++) {
2660
- const posSlot = rule.position_slots[pi];
2661
- const sizeSlot = rule.size_slots[pi];
2662
- const containerSizeSlot = sizeSlot;
2663
- ensureSlot(graph, containerId, containerSizeSlot);
2664
- ensureSlot(graph, contentId, posSlot);
2665
- ensureSlot(graph, contentId, sizeSlot);
2666
- const opId = `op.keepInside.${node.id}.${contentId}.${posSlot}`;
2667
- const inputSlots = [
2668
- `${containerId}.${containerSizeSlot}`,
2669
- `${contentId}.${posSlot}`,
2670
- `${contentId}.${sizeSlot}`
2671
- ];
2672
- const outputSlotId = `${contentId}.${posSlot}`;
2673
- addCandidate(graph, outputSlotId, void 0, `keepInside(${node.id})`, strength, opId);
2674
- addOperation(graph, opId, "clamp", inputSlots, [outputSlotId], (inputs) => {
2675
- const containerSize = num(inputs[0]);
2676
- const currentPos = num(inputs[1]);
2677
- const contentSize = num(inputs[2]);
2678
- const maxPos = containerSize - contentSize;
2679
- return [Math.max(0, Math.min(currentPos, maxPos))];
2680
- });
2681
- }
2631
+ if (widthIntent === "fill" && parentId && rejectMainAxisFill(node, graph, "resolvedWidth", "normal", parentId) === "cross") {
2632
+ const fillWidthOpId = `op.overlay.fillWidth.${id}`;
2633
+ const outSid = slotId(id, "resolvedWidth");
2634
+ ensureSlot(graph, parentId, "availableWidth");
2635
+ addCandidate(graph, outSid, void 0, `overlay(${id}).fill`, "normal", fillWidthOpId);
2636
+ addOperation(graph, fillWidthOpId, "resolveSize", [slotId(parentId, "availableWidth")], [outSid], (inputs) => {
2637
+ return [num(inputs[0])];
2638
+ });
2639
+ }
2640
+ if (heightIntent === "fill" && parentId && rejectMainAxisFill(node, graph, "resolvedHeight", "normal", parentId) === "cross") {
2641
+ const fillHeightOpId = `op.overlay.fillHeight.${id}`;
2642
+ const outSid = slotId(id, "resolvedHeight");
2643
+ ensureSlot(graph, parentId, "availableHeight");
2644
+ addCandidate(graph, outSid, void 0, `overlay(${id}).fill`, "normal", fillHeightOpId);
2645
+ addOperation(graph, fillHeightOpId, "resolveSize", [slotId(parentId, "availableHeight")], [outSid], (inputs) => {
2646
+ return [num(inputs[0])];
2647
+ });
2682
2648
  }
2649
+ const availWidthOpId = `op.overlay.availW.${id}`;
2650
+ ensureSlot(graph, id, "availableWidth");
2651
+ addCandidate(graph, slotId(id, "availableWidth"), void 0, `overlay(${id}).availW`, "normal", availWidthOpId);
2652
+ addOperation(graph, availWidthOpId, "resolveSize", [slotId(id, "resolvedWidth")], [slotId(id, "availableWidth")], (inputs) => {
2653
+ return [Math.max(num(inputs[0]) - padding * 2, 0)];
2654
+ });
2655
+ const availHeightOpId = `op.overlay.availH.${id}`;
2656
+ ensureSlot(graph, id, "availableHeight");
2657
+ addCandidate(graph, slotId(id, "availableHeight"), void 0, `overlay(${id}).availH`, "normal", availHeightOpId);
2658
+ addOperation(graph, availHeightOpId, "resolveSize", [slotId(id, "resolvedHeight")], [slotId(id, "availableHeight")], (inputs) => {
2659
+ return [Math.max(num(inputs[0]) - padding * 2, 0)];
2660
+ });
2683
2661
  }
2684
- var CONSTRAINT_HANDLERS = {
2685
- world_align: applyWorldAlign,
2686
- equalize: applyEqualize,
2687
- enforce_order: applyEnforceOrder,
2688
- enforce_min_gap: applyEnforceMinGap,
2689
- clamp_inside: applyClampInside
2690
- };
2691
- function applyConstraintFromRule(kind, node, graph) {
2692
- const rule = constraintRules[kind];
2693
- if (!rule) return false;
2694
- const handler = CONSTRAINT_HANDLERS[rule.operation];
2695
- if (!handler) return false;
2696
- handler(rule, node, graph);
2697
- return true;
2662
+ function applyConnectorRule(_rule, node, graph) {
2663
+ const id = node.id;
2664
+ const fromId = node.props.from;
2665
+ const toId = node.props.to;
2666
+ ensureSlot(graph, id, "resolvedWidth", 0);
2667
+ ensureSlot(graph, id, "resolvedHeight", 0);
2668
+ ensureSlot(graph, id, "localX", 0);
2669
+ ensureSlot(graph, id, "localY", 0);
2670
+ ensureSlot(graph, id, "connectorPath");
2671
+ if (fromId && toId) {
2672
+ ensureSlot(graph, fromId, "localX");
2673
+ ensureSlot(graph, fromId, "localY");
2674
+ ensureSlot(graph, fromId, "resolvedWidth");
2675
+ ensureSlot(graph, fromId, "resolvedHeight");
2676
+ ensureSlot(graph, toId, "localX");
2677
+ ensureSlot(graph, toId, "localY");
2678
+ ensureSlot(graph, toId, "resolvedWidth");
2679
+ ensureSlot(graph, toId, "resolvedHeight");
2680
+ addCandidate(graph, slotId(id, "connectorPath"), 0, `connector(${id})`, "normal");
2681
+ }
2698
2682
  }
2699
- var textMeasurer = new SimpleTextMeasurer();
2700
- function setTextMeasurer(m) {
2701
- textMeasurer = m;
2683
+ function applyFixedSizeRule(rule, node, graph, parentId) {
2684
+ const id = node.id;
2685
+ const kind = node.kind;
2686
+ let widthSpec;
2687
+ let heightSpec;
2688
+ if (rule.size_from_axis) {
2689
+ const axis = getStringProp(node, "axis", stringParamDefault(rule, "axis"));
2690
+ const sizeConfig = rule.size_from_axis[axis];
2691
+ widthSpec = sizeConfig?.width ?? 0;
2692
+ heightSpec = sizeConfig?.height ?? 0;
2693
+ } else {
2694
+ widthSpec = getNumericProp(node, "width", numericParamDefault(rule, "width"));
2695
+ heightSpec = getNumericProp(node, "height", numericParamDefault(rule, "height"));
2696
+ }
2697
+ ensureSlot(graph, id, "localX", 0);
2698
+ ensureSlot(graph, id, "localY", 0);
2699
+ const priority = kind === "divider" ? "weak" : "normal";
2700
+ applyFixedSizeDimension(node, graph, "resolvedWidth", widthSpec, priority, parentId);
2701
+ applyFixedSizeDimension(node, graph, "resolvedHeight", heightSpec, priority, parentId);
2702
2702
  }
2703
- function applyRootRule(rule, node, graph) {
2703
+ function applyFixedSizeDimension(node, graph, dim, spec, priority, parentId) {
2704
2704
  const id = node.id;
2705
- const width = getNumericProp(node, "width", numericParamDefault(rule, "width"));
2706
- const height = getNumericProp(node, "height", numericParamDefault(rule, "height"));
2707
- const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
2708
- ensureSlot(graph, id, "resolvedWidth", width);
2709
- ensureSlot(graph, id, "resolvedHeight", height);
2710
- ensureSlot(graph, id, "availableWidth", width - padding * 2);
2711
- ensureSlot(graph, id, "availableHeight", height - padding * 2);
2712
- addCandidate(graph, slotId(id, "resolvedWidth"), width, "document(explicit)", "required");
2713
- addCandidate(graph, slotId(id, "resolvedHeight"), height, "document(explicit)", "required");
2714
- if (node.children) {
2715
- for (const child of node.children) {
2716
- if (child.id && !isConstraintKind(child.kind)) {
2717
- ensureSlot(graph, child.id, "localX");
2718
- ensureSlot(graph, child.id, "localY");
2719
- addCandidate(graph, slotId(child.id, "localX"), padding, `document(${id}).origin`, "weak");
2720
- addCandidate(graph, slotId(child.id, "localY"), padding, `document(${id}).origin`, "weak");
2721
- }
2722
- }
2705
+ const kind = node.kind;
2706
+ const outSid = slotId(id, dim);
2707
+ if (typeof spec === "number" && Number.isFinite(spec)) {
2708
+ ensureSlot(graph, id, dim, spec);
2709
+ addCandidate(graph, outSid, spec, `${kind}(${id})`, priority);
2710
+ return;
2711
+ }
2712
+ ensureSlot(graph, id, dim);
2713
+ if (spec === "fill" && parentId) {
2714
+ if (rejectMainAxisFill(node, graph, dim, priority, parentId) !== "cross") return;
2715
+ const dimName = dim === "resolvedWidth" ? "width" : "height";
2716
+ const availSlot = dim === "resolvedWidth" ? "availableWidth" : "availableHeight";
2717
+ const opId = `op.${kind}.fill.${dimName}.${id}`;
2718
+ ensureSlot(graph, parentId, availSlot);
2719
+ addCandidate(graph, outSid, void 0, `${kind}(${id}).fill`, priority, opId);
2720
+ addOperation(graph, opId, "resolveSize", [slotId(parentId, availSlot)], [outSid], (inputs) => {
2721
+ return [num(inputs[0])];
2722
+ });
2723
+ return;
2723
2724
  }
2725
+ addCandidate(graph, outSid, 0, `${kind}(${id})`, priority);
2724
2726
  }
2725
- function applyStackRule(rule, axisConfig, kindName, node, graph, parentId) {
2727
+ function applyGridRule(rule, node, graph, parentId) {
2726
2728
  const id = node.id;
2727
- const gap = getNumericProp(node, "gap", numericParamDefault(rule, "gap"));
2728
- const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
2729
- const children = childrenOf(node);
2729
+ const gap = getNumericProp(node, "gap", 0);
2730
+ const padding = getNumericProp(node, "padding", 0);
2731
+ const gridConfig = rule.grid;
2732
+ const rowKind = gridConfig.row_kind;
2733
+ const cellKind = gridConfig.cell_kind;
2730
2734
  registerSizeSlots(node, graph, parentId);
2731
2735
  ensureSlot(graph, id, "contentWidth");
2732
2736
  ensureSlot(graph, id, "contentHeight");
2733
- const childIds = children.filter((c) => !isConstraintKind(c.kind)).map((c) => c.id);
2734
- if (childIds.length === 0) return;
2735
- graph.childrenOrderMap.set(id, childIds);
2736
- const mainSlot = axisConfig.main_slot;
2737
- const crossSlot = axisConfig.cross_slot;
2738
- const mainSize = axisConfig.main_size;
2739
- const crossSize = axisConfig.cross_size;
2740
- const contentMainSize = axisConfig.content_main_size;
2741
- const contentCrossSize = axisConfig.content_cross_size;
2742
- const baseMain = baseMainSlot(mainSlot);
2743
- const opId = `op.${kindName}.${id}`;
2744
- const inputSlots = [];
2745
- for (const childId of childIds) {
2746
- ensureSlot(graph, childId, mainSize);
2747
- ensureSlot(graph, childId, crossSize);
2748
- ensureSlot(graph, childId, baseMain);
2749
- ensureSlot(graph, childId, crossSlot);
2750
- inputSlots.push(slotId(childId, mainSize));
2751
- }
2752
- const baseOutputs = [
2753
- ...childIds.map((cid) => slotId(cid, baseMain)),
2754
- slotId(id, contentMainSize),
2755
- slotId(id, mainSize)
2756
- ];
2757
- for (const cid of childIds) {
2758
- addCandidate(graph, slotId(cid, baseMain), void 0, `${kindName}(${id})`, "strong", opId);
2759
- }
2760
- addCandidate(graph, slotId(id, contentMainSize), void 0, `${kindName}(${id}).content`, "strong", opId);
2761
- addCandidate(graph, slotId(id, mainSize), void 0, `${kindName}(${id}).wrap`, "normal", opId);
2762
- addOperation(graph, opId, "stackPosition", inputSlots, baseOutputs, (inputs) => {
2763
- let pos = padding;
2764
- const positions = [];
2765
- for (let i = 0; i < inputs.length; i++) {
2766
- positions.push(pos);
2767
- pos += inputs[i] + (i < inputs.length - 1 ? gap : 0);
2768
- }
2769
- const contentMain = pos - padding;
2770
- const totalMain = contentMain + padding * 2;
2771
- return [...positions, contentMain, totalMain];
2772
- });
2773
- const suffixShiftSlotIds = [];
2774
- for (let i = 0; i < childIds.length; i++) {
2775
- const ssId = suffixShiftSlotId(id, i);
2776
- ensureSlot(graph, id, `suffixShift.${i}`);
2777
- addCandidate(graph, ssId, 0, `${kindName}(${id}).suffixShift.${i}`, "weak");
2778
- addResolver(graph, ssId, "max");
2779
- suffixShiftSlotIds.push(ssId);
2737
+ const rows = childrenOf(node).filter((c) => c.kind === rowKind);
2738
+ if (rows.length === 0) return;
2739
+ const rowIds = rows.map((r) => r.id);
2740
+ for (const rowId of rowIds) {
2741
+ ensureSlot(graph, rowId, "resolvedWidth");
2742
+ ensureSlot(graph, rowId, "resolvedHeight");
2743
+ ensureSlot(graph, rowId, "localX");
2744
+ ensureSlot(graph, rowId, "localY");
2780
2745
  }
2781
- const composeOpId = `op.${kindName}.compose.${id}`;
2782
- const composeInputs = [
2783
- ...childIds.map((cid) => slotId(cid, baseMain)),
2784
- ...suffixShiftSlotIds
2746
+ const rowPosOpId = `op.grid.rowPos.${id}`;
2747
+ const rowHeightSlots = rowIds.map((rid) => slotId(rid, "resolvedHeight"));
2748
+ const rowPosOutputs = [
2749
+ ...rowIds.map((rid) => slotId(rid, "localY")),
2750
+ ...rowIds.map((rid) => slotId(rid, "localX")),
2751
+ slotId(id, "contentHeight"),
2752
+ slotId(id, "resolvedHeight")
2785
2753
  ];
2786
- const composeOutputs = childIds.map((cid) => slotId(cid, mainSlot));
2787
- for (const cid of childIds) {
2788
- addCandidate(graph, slotId(cid, mainSlot), void 0, `${kindName}(${id}).compose`, "strong", composeOpId);
2754
+ for (const rid of rowIds) {
2755
+ addCandidate(graph, slotId(rid, "localY"), void 0, `grid(${id}).rowPos`, "strong", rowPosOpId);
2756
+ addCandidate(graph, slotId(rid, "localX"), void 0, `grid(${id}).rowX`, "normal", rowPosOpId);
2789
2757
  }
2790
- addOperation(graph, composeOpId, "stackCompose", composeInputs, composeOutputs, (inputs) => {
2791
- const n = childIds.length;
2792
- const bases = inputs.slice(0, n);
2793
- const shifts = inputs.slice(n, n + n);
2794
- let runningMax = 0;
2795
- const result = [];
2796
- for (let j = 0; j < n; j++) {
2797
- runningMax = Math.max(runningMax, num(shifts[j]));
2798
- result.push(num(bases[j]) + runningMax);
2758
+ addCandidate(graph, slotId(id, "contentHeight"), void 0, `grid(${id}).contentH`, "strong", rowPosOpId);
2759
+ addCandidate(graph, slotId(id, "resolvedHeight"), void 0, `grid(${id}).wrapH`, "normal", rowPosOpId);
2760
+ addOperation(graph, rowPosOpId, "stackPosition", rowHeightSlots, rowPosOutputs, (inputs) => {
2761
+ let y = padding;
2762
+ const yPositions = [];
2763
+ for (let i = 0; i < rowIds.length; i++) {
2764
+ yPositions.push(y);
2765
+ y += num(inputs[i]) + (i < rowIds.length - 1 ? gap : 0);
2799
2766
  }
2800
- return result;
2767
+ const contentH = y - padding;
2768
+ const totalH = contentH + padding * 2;
2769
+ const xPositions = rowIds.map(() => padding);
2770
+ return [...yPositions, ...xPositions, contentH, totalH];
2801
2771
  });
2802
- const align = getStringProp(node, "align", stringParamDefault(rule, "align"));
2803
- const crossPropName = crossSize === "resolvedWidth" ? "width" : "height";
2804
- const availableCrossSlot = crossSize === "resolvedWidth" ? "availableWidth" : "availableHeight";
2805
- const selfCrossIntent = getSizeProp(node, crossPropName);
2806
- const contentChildren = children.filter((c) => !isConstraintKind(c.kind));
2807
- const fillChildIndices = /* @__PURE__ */ new Set();
2808
- for (let i = 0; i < childIds.length; i++) {
2809
- if (getEffectiveSizeIntent(contentChildren[i], crossPropName) === "fill") {
2810
- fillChildIndices.add(i);
2811
- }
2772
+ const maxCols = Math.max(...rows.map((r) => childrenOf(r).filter((c) => c.kind === cellKind).length));
2773
+ const columnCellIds = [];
2774
+ for (let col = 0; col < maxCols; col++) {
2775
+ columnCellIds.push([]);
2812
2776
  }
2813
- const crossInputSlots = [];
2814
- for (let i = 0; i < childIds.length; i++) {
2815
- if (!fillChildIndices.has(i)) {
2816
- crossInputSlots.push(slotId(childIds[i], crossSize));
2777
+ for (const row of rows) {
2778
+ const cells = childrenOf(row).filter((c) => c.kind === cellKind);
2779
+ for (let col = 0; col < cells.length && col < maxCols; col++) {
2780
+ columnCellIds[col].push(cells[col].id);
2817
2781
  }
2818
2782
  }
2819
- const maxCrossOpId = `op.${kindName}.maxCross.${id}`;
2820
- addCandidate(graph, slotId(id, contentCrossSize), void 0, `${kindName}(${id}).contentCross`, "strong", maxCrossOpId);
2821
- addOperation(graph, maxCrossOpId, "max", crossInputSlots, [slotId(id, contentCrossSize)], (inputs) => {
2822
- return [inputs.length > 0 ? Math.max(...inputs) : 0];
2823
- });
2824
- ensureSlot(graph, id, availableCrossSlot);
2825
- const availCrossOpId = `op.${kindName}.availCross.${id}`;
2826
- const availCrossInputs = [slotId(id, contentCrossSize)];
2827
- if (selfCrossIntent === "fill" && parentId) {
2828
- const parentAvailSlot = crossSize === "resolvedWidth" ? "availableWidth" : "availableHeight";
2829
- ensureSlot(graph, parentId, parentAvailSlot);
2830
- availCrossInputs.push(slotId(parentId, parentAvailSlot));
2831
- }
2832
- addCandidate(graph, slotId(id, availableCrossSlot), void 0, `${kindName}(${id}).availCross`, "strong", availCrossOpId);
2833
- addOperation(graph, availCrossOpId, "max", availCrossInputs, [slotId(id, availableCrossSlot)], (inputs) => {
2834
- const contentCross = num(inputs[0]);
2835
- const parentAvail = inputs.length > 1 ? num(inputs[1]) - padding * 2 : 0;
2836
- return [Math.max(contentCross, parentAvail)];
2837
- });
2838
- const wrapCrossOpId = `op.${kindName}.wrapCross.${id}`;
2839
- addCandidate(graph, slotId(id, crossSize), void 0, `${kindName}(${id}).wrapCross`, "normal", wrapCrossOpId);
2840
- addOperation(graph, wrapCrossOpId, "resolveSize", [slotId(id, availableCrossSlot)], [slotId(id, crossSize)], (inputs) => {
2841
- return [num(inputs[0]) + padding * 2];
2842
- });
2843
- const crossAlignOpId = `op.${kindName}.crossAlign.${id}`;
2844
- const allChildCrossSlots = childIds.map((cid) => slotId(cid, crossSize));
2845
- const crossAlignInputs = [slotId(id, availableCrossSlot), ...allChildCrossSlots];
2846
- const crossAlignOutputs = childIds.map((cid) => slotId(cid, crossSlot));
2847
- for (const cid of childIds) {
2848
- addCandidate(graph, slotId(cid, crossSlot), void 0, `${kindName}(${id}).crossAlign`, "strong", crossAlignOpId);
2783
+ const cellPaddingMap = /* @__PURE__ */ new Map();
2784
+ for (const row of rows) {
2785
+ for (const cell of childrenOf(row).filter((c) => c.kind === cellKind)) {
2786
+ cellPaddingMap.set(cell.id, getNumericProp(cell, "padding", 0));
2787
+ }
2849
2788
  }
2850
- addOperation(graph, crossAlignOpId, "crossAlign", crossAlignInputs, crossAlignOutputs, (inputs) => {
2851
- const availCross = num(inputs[0]);
2852
- const positions = [];
2853
- for (let i = 0; i < childIds.length; i++) {
2854
- const childCross = num(inputs[1 + i]);
2855
- let crossPos = padding;
2856
- if (align === "center") {
2857
- crossPos = padding + (availCross - childCross) / 2;
2858
- } else if (align === "end") {
2859
- crossPos = padding + availCross - childCross;
2789
+ const colMinWidthSlots = [];
2790
+ for (let col = 0; col < maxCols; col++) {
2791
+ const cellIds = columnCellIds[col];
2792
+ const colMinSlot = `${id}.colMinWidth.${col}`;
2793
+ colMinWidthSlots.push(colMinSlot);
2794
+ ensureSlot(graph, id, `colMinWidth.${col}`);
2795
+ if (cellIds.length < 2) {
2796
+ if (cellIds.length === 1) {
2797
+ const cid = cellIds[0];
2798
+ const p = num(cellPaddingMap.get(cid));
2799
+ const singleOpId = `op.grid.colMin.${id}.${col}`;
2800
+ ensureSlot(graph, cid, "contentWidth");
2801
+ addCandidate(graph, colMinSlot, void 0, `grid(${id}).colMin[${col}]`, "strong", singleOpId);
2802
+ addOperation(graph, singleOpId, "columnWidthResolve", [slotId(cid, "contentWidth")], [colMinSlot], (inputs) => {
2803
+ return [num(inputs[0]) + p * 2];
2804
+ });
2860
2805
  }
2861
- positions.push(crossPos);
2806
+ continue;
2862
2807
  }
2863
- return positions;
2864
- });
2865
- }
2866
- function rejectMainAxisFill(node, graph, dim, priority, parentId) {
2867
- const parentKind = graph.nodeKindMap.get(parentId);
2868
- const parentAxisConfig = parentKind ? STACK_RULE.applies_to?.[parentKind] : void 0;
2869
- if (!parentAxisConfig || parentAxisConfig.main_size !== dim) return false;
2870
- const id = node.id;
2871
- const kind = node.kind;
2872
- const dimName = dim === "resolvedWidth" ? "width" : "height";
2873
- const rule = layoutRules[kind];
2874
- const hint = rule?.size_from_axis ? (() => {
2875
- const axis = getStringProp(node, "axis", stringParamDefault(rule, "axis"));
2876
- const otherAxis = axis === "horizontal" ? "vertical" : "horizontal";
2877
- return ` (axis="${axis}") \u2014 use axis="${otherAxis}" or give the ${kind} a fixed-size container`;
2878
- })() : ` \u2014 give the ${kind} a fixed ${dimName} or place it in a fixed-size container`;
2879
- graph.diagnostics.push({
2880
- level: "error",
2881
- message: `${kind} '${id}' fills its ${dimName} along the stacking axis of ${parentKind} '${parentId}'; a stack's main-axis size is the sum of its children, so this fill is circular and has no defined size${hint}`,
2882
- path: id
2883
- });
2884
- addCandidate(graph, slotId(id, dim), 0, `${kind}(${id}).fill-error`, priority);
2885
- return true;
2886
- }
2887
- function applyContainerRule(rule, node, graph, parentId) {
2888
- const id = node.id;
2889
- const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
2890
- registerSizeSlots(node, graph, parentId);
2891
- ensureSlot(graph, id, "contentWidth");
2892
- ensureSlot(graph, id, "contentHeight");
2893
- const widthIntent = getSizeProp(node, "width");
2894
- const heightIntent = getSizeProp(node, "height");
2895
- if (widthIntent === "fill" && parentId && !rejectMainAxisFill(node, graph, "resolvedWidth", "normal", parentId)) {
2896
- const opId = `op.box.fillWidth.${id}`;
2897
- const outSid = slotId(id, "resolvedWidth");
2898
- ensureSlot(graph, parentId, "availableWidth");
2899
- addCandidate(graph, outSid, void 0, `box(${id}).fill`, "normal", opId);
2900
- addOperation(graph, opId, "resolveSize", [slotId(parentId, "availableWidth")], [outSid], (inputs) => {
2901
- return [num(inputs[0])];
2808
+ const colEqOpId = `op.grid.colMin.${id}.${col}`;
2809
+ const widthInputs = cellIds.map((cid) => {
2810
+ ensureSlot(graph, cid, "contentWidth");
2811
+ return slotId(cid, "contentWidth");
2902
2812
  });
2903
- }
2904
- if (heightIntent === "fill" && parentId && !rejectMainAxisFill(node, graph, "resolvedHeight", "normal", parentId)) {
2905
- const opId = `op.box.fillHeight.${id}`;
2906
- const outSid = slotId(id, "resolvedHeight");
2907
- ensureSlot(graph, parentId, "availableHeight");
2908
- addCandidate(graph, outSid, void 0, `box(${id}).fill`, "normal", opId);
2909
- addOperation(graph, opId, "resolveSize", [slotId(parentId, "availableHeight")], [outSid], (inputs) => {
2910
- return [num(inputs[0])];
2813
+ const colPaddings = cellIds.map((cid) => num(cellPaddingMap.get(cid)));
2814
+ addCandidate(graph, colMinSlot, void 0, `grid(${id}).colMin[${col}]`, "strong", colEqOpId);
2815
+ addOperation(graph, colEqOpId, "columnWidthResolve", widthInputs, [colMinSlot], (inputs) => {
2816
+ const desiredWidths = inputs.map((w, i) => num(w) + colPaddings[i] * 2);
2817
+ return [Math.max(...desiredWidths, 0)];
2911
2818
  });
2912
2819
  }
2913
- const wrapWidthOpId = `op.box.wrapWidth.${id}`;
2914
- const wrapHeightOpId = `op.box.wrapHeight.${id}`;
2915
- if (widthIntent === "wrap") {
2916
- const outSid = slotId(id, "resolvedWidth");
2917
- addCandidate(graph, outSid, void 0, `box(${id}).wrap`, "weak", wrapWidthOpId);
2918
- addOperation(graph, wrapWidthOpId, "resolveSize", [slotId(id, "contentWidth")], [outSid], (inputs) => {
2919
- return [num(inputs[0]) + padding * 2];
2820
+ if (maxCols > 0) {
2821
+ const wrapWidthOpId = `op.grid.wrapWidth.${id}`;
2822
+ const wrapOutputs = [slotId(id, "contentWidth"), slotId(id, "resolvedWidth")];
2823
+ addCandidate(graph, slotId(id, "contentWidth"), void 0, `grid(${id}).wrapContentW`, "normal", wrapWidthOpId);
2824
+ addCandidate(graph, slotId(id, "resolvedWidth"), void 0, `grid(${id}).wrapW`, "normal", wrapWidthOpId);
2825
+ addOperation(graph, wrapWidthOpId, "resolveSize", colMinWidthSlots, wrapOutputs, (inputs) => {
2826
+ const contentW = inputs.reduce((sum, w) => sum + num(w), 0) + gap * Math.max(0, inputs.length - 1);
2827
+ return [contentW, contentW + padding * 2];
2920
2828
  });
2921
2829
  }
2922
- if (heightIntent === "wrap") {
2923
- const outSid = slotId(id, "resolvedHeight");
2924
- addCandidate(graph, outSid, void 0, `box(${id}).wrap`, "weak", wrapHeightOpId);
2925
- addOperation(graph, wrapHeightOpId, "resolveSize", [slotId(id, "contentHeight")], [outSid], (inputs) => {
2926
- return [num(inputs[0]) + padding * 2];
2830
+ const colResolvedWidthSlots = [];
2831
+ if (maxCols > 0) {
2832
+ const colFillOpId = `op.grid.colFill.${id}`;
2833
+ const colFillInputs = [slotId(id, "resolvedWidth"), ...colMinWidthSlots];
2834
+ const colFillOutputs = [];
2835
+ for (let col = 0; col < maxCols; col++) {
2836
+ const colResSlot = `${id}.colResolvedWidth.${col}`;
2837
+ colResolvedWidthSlots.push(colResSlot);
2838
+ ensureSlot(graph, id, `colResolvedWidth.${col}`);
2839
+ colFillOutputs.push(colResSlot);
2840
+ addCandidate(graph, colResSlot, void 0, `grid(${id}).colFill[${col}]`, "strong", colFillOpId);
2841
+ }
2842
+ addOperation(graph, colFillOpId, "columnFill", colFillInputs, colFillOutputs, (inputs) => {
2843
+ const resolvedW = num(inputs[0]);
2844
+ const availableW = resolvedW - padding * 2;
2845
+ const minWidths = inputs.slice(1).map((v) => num(v));
2846
+ const totalMin = minWidths.reduce((s, w) => s + w, 0) + gap * Math.max(0, maxCols - 1);
2847
+ const surplus = Math.max(0, availableW - totalMin);
2848
+ const surplusPerCol = surplus / maxCols;
2849
+ return minWidths.map((mw) => mw + surplusPerCol);
2927
2850
  });
2928
2851
  }
2929
- const availWidthOpId = `op.box.availW.${id}`;
2930
- ensureSlot(graph, id, "availableWidth");
2931
- addCandidate(graph, slotId(id, "availableWidth"), void 0, `box(${id}).availW`, "normal", availWidthOpId);
2932
- addOperation(graph, availWidthOpId, "resolveSize", [slotId(id, "resolvedWidth")], [slotId(id, "availableWidth")], (inputs) => {
2933
- return [Math.max(num(inputs[0]) - padding * 2, 0)];
2934
- });
2935
- const availHeightOpId = `op.box.availH.${id}`;
2936
- ensureSlot(graph, id, "availableHeight");
2937
- addCandidate(graph, slotId(id, "availableHeight"), void 0, `box(${id}).availH`, "normal", availHeightOpId);
2938
- addOperation(graph, availHeightOpId, "resolveSize", [slotId(id, "resolvedHeight")], [slotId(id, "availableHeight")], (inputs) => {
2939
- return [Math.max(num(inputs[0]) - padding * 2, 0)];
2940
- });
2941
- const children = childrenOf(node);
2942
- const contentChildIds = children.filter((c) => !isConstraintKind(c.kind)).map((c) => c.id);
2943
- if (contentChildIds.length > 0) {
2944
- for (const childId of contentChildIds) {
2945
- ensureSlot(graph, childId, "resolvedWidth");
2946
- ensureSlot(graph, childId, "resolvedHeight");
2947
- ensureSlot(graph, childId, "localX");
2948
- ensureSlot(graph, childId, "localY");
2852
+ for (let col = 0; col < maxCols; col++) {
2853
+ const cellIds = columnCellIds[col];
2854
+ if (cellIds.length === 0) continue;
2855
+ const cellWOpId = `op.grid.cellW.${id}.${col}`;
2856
+ const colResSlot = colResolvedWidthSlots[col];
2857
+ const cellWOutputs = cellIds.map((cid) => slotId(cid, "resolvedWidth"));
2858
+ for (const cid of cellIds) {
2859
+ addCandidate(graph, slotId(cid, "resolvedWidth"), void 0, `grid(${id}).cellW[${col}]`, "strong", cellWOpId);
2949
2860
  }
2950
- const contentOpId = `op.box.content.${id}`;
2951
- const childWidthSlots = contentChildIds.map((cid) => slotId(cid, "resolvedWidth"));
2952
- const childHeightSlots = contentChildIds.map((cid) => slotId(cid, "resolvedHeight"));
2953
- const allInputs = [...childWidthSlots, ...childHeightSlots];
2954
- const contentOutputs = [slotId(id, "contentWidth"), slotId(id, "contentHeight")];
2955
- addCandidate(graph, slotId(id, "contentWidth"), void 0, `box(${id}).childContent`, "normal", contentOpId);
2956
- addCandidate(graph, slotId(id, "contentHeight"), void 0, `box(${id}).childContent`, "normal", contentOpId);
2957
- addOperation(graph, contentOpId, "resolveSize", allInputs, contentOutputs, (inputs) => {
2958
- const nChildren = contentChildIds.length;
2959
- const widths = inputs.slice(0, nChildren);
2960
- const heights = inputs.slice(nChildren);
2961
- return [Math.max(...widths, 0), Math.max(...heights, 0)];
2861
+ addOperation(graph, cellWOpId, "copy", [colResSlot], cellWOutputs, (inputs) => {
2862
+ return cellIds.map(() => num(inputs[0]));
2962
2863
  });
2963
- const hasAlignParams = rule.params?.colAlign !== void 0;
2964
- const colAlign = hasAlignParams ? node.props.colAlign ?? rule.params.colAlign.default : void 0;
2965
- const rowAlign = hasAlignParams ? node.props.rowAlign ?? rule.params.rowAlign.default : void 0;
2966
- const alignOpId = `op.box.center.${id}`;
2967
- const alignInputs = [slotId(id, "resolvedWidth"), slotId(id, "resolvedHeight"), ...childWidthSlots, ...childHeightSlots];
2968
- const alignOutputs = contentChildIds.flatMap((cid) => [slotId(cid, "localX"), slotId(cid, "localY")]);
2969
- for (const cid of contentChildIds) {
2970
- addCandidate(graph, slotId(cid, "localX"), void 0, `box(${id}).center`, "normal", alignOpId);
2971
- addCandidate(graph, slotId(cid, "localY"), void 0, `box(${id}).center`, "normal", alignOpId);
2864
+ }
2865
+ for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
2866
+ const cells = childrenOf(rows[rowIdx]).filter((c) => c.kind === cellKind);
2867
+ const cellIds = cells.map((c) => c.id);
2868
+ if (cellIds.length < 2) continue;
2869
+ const rowEqOpId = `op.grid.rowEq.${id}.${rowIdx}`;
2870
+ const heightInputs = cellIds.map((cid) => {
2871
+ ensureSlot(graph, cid, "contentHeight");
2872
+ return slotId(cid, "contentHeight");
2873
+ });
2874
+ const rowEqOutputs = cellIds.map((cid) => slotId(cid, "resolvedHeight"));
2875
+ const rowPaddings = cellIds.map((cid) => num(cellPaddingMap.get(cid)));
2876
+ for (const cid of cellIds) {
2877
+ addCandidate(graph, slotId(cid, "resolvedHeight"), void 0, `grid(${id}).rowEq[${rowIdx}]`, "strong", rowEqOpId);
2972
2878
  }
2973
- addOperation(graph, alignOpId, "resolveSize", alignInputs, alignOutputs, (inputs) => {
2974
- const boxW = num(inputs[0]);
2975
- const boxH = num(inputs[1]);
2976
- const nChildren = contentChildIds.length;
2977
- const result = [];
2978
- for (let i = 0; i < nChildren; i++) {
2979
- const cw = num(inputs[2 + i]);
2980
- const ch = num(inputs[2 + nChildren + i]);
2981
- let cx;
2982
- if (colAlign !== void 0) {
2983
- switch (colAlign) {
2984
- case "center":
2985
- cx = (boxW - cw) / 2;
2986
- break;
2987
- case "right":
2988
- cx = boxW - cw - padding;
2989
- break;
2990
- default:
2991
- cx = padding;
2992
- break;
2993
- }
2994
- } else {
2995
- cx = (boxW - cw) / 2;
2996
- }
2997
- let cy;
2998
- if (rowAlign !== void 0) {
2999
- switch (rowAlign) {
3000
- case "center":
3001
- cy = (boxH - ch) / 2;
3002
- break;
3003
- case "bottom":
3004
- cy = boxH - ch - padding;
3005
- break;
3006
- default:
3007
- cy = padding;
3008
- break;
3009
- }
3010
- } else {
3011
- cy = (boxH - ch) / 2;
3012
- }
3013
- result.push(cx, cy);
3014
- }
3015
- return result;
2879
+ addOperation(graph, rowEqOpId, "rowHeightResolve", heightInputs, rowEqOutputs, (inputs) => {
2880
+ const desiredHeights = inputs.map((h, i) => num(h) + rowPaddings[i] * 2);
2881
+ const maxH = Math.max(...desiredHeights, 0);
2882
+ return cellIds.map(() => maxH);
2883
+ });
2884
+ }
2885
+ for (const rowId of rowIds) {
2886
+ const rowWidthOpId = `op.grid.rowWidth.${id}.${rowId}`;
2887
+ const outSid = slotId(rowId, "resolvedWidth");
2888
+ addCandidate(graph, outSid, void 0, `grid(${id}).rowWidth`, "normal", rowWidthOpId);
2889
+ addOperation(graph, rowWidthOpId, "resolveSize", [slotId(id, "resolvedWidth")], [outSid], (inputs) => {
2890
+ return [num(inputs[0]) - padding * 2];
2891
+ });
2892
+ }
2893
+ for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
2894
+ const cells = childrenOf(rows[rowIdx]).filter((c) => c.kind === cellKind);
2895
+ const cellIds = cells.map((c) => c.id);
2896
+ const rowHeightOpId = `op.grid.rowH.${id}.${rowIdx}`;
2897
+ const cellHeightInputs = cellIds.map((cid) => slotId(cid, "resolvedHeight"));
2898
+ const outSid = slotId(rowIds[rowIdx], "resolvedHeight");
2899
+ addCandidate(graph, outSid, void 0, `grid(${id}).rowH`, "normal", rowHeightOpId);
2900
+ addOperation(graph, rowHeightOpId, "max", cellHeightInputs, [outSid], (inputs) => {
2901
+ return [Math.max(...inputs, 0)];
3016
2902
  });
3017
2903
  }
3018
2904
  }
3019
- function applyTextMeasurementRule(rule, node, graph, parentId) {
2905
+ function applyStubRule(node, graph, parentId) {
3020
2906
  const id = node.id;
3021
- const text = getStringProp(node, "text", stringParamDefault(rule, "text"));
3022
- const fontSize = getNumericProp(node, "fontSize", numericParamDefault(rule, "fontSize"));
3023
- const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
3024
- const textAlign = getStringProp(node, "textAlign", stringParamDefault(rule, "textAlign"));
3025
- ensureSlot(graph, id, "resolvedWidth");
3026
- ensureSlot(graph, id, "resolvedHeight");
3027
- ensureSlot(graph, id, "localX");
3028
- ensureSlot(graph, id, "localY");
3029
- const fontWeight = node.props.fontWeight;
3030
- const measurement = textMeasurer.measure(text, fontSize, void 0, fontWeight);
3031
- const intrinsicW = measurement.width + padding * 2;
3032
- const intrinsicH = measurement.height + padding * 2;
3033
- ensureSlot(graph, id, "intrinsicWidth", intrinsicW);
3034
- ensureSlot(graph, id, "intrinsicHeight", intrinsicH);
3035
- addCandidate(graph, slotId(id, "resolvedWidth"), intrinsicW, `text(${id}).intrinsic`, "normal");
3036
- addCandidate(graph, slotId(id, "resolvedHeight"), intrinsicH, `text(${id}).intrinsic`, "normal");
3037
- if (parentId) {
3038
- ensureSlot(graph, id, "contentWidth", intrinsicW);
3039
- ensureSlot(graph, id, "contentHeight", intrinsicH);
2907
+ registerSizeSlots(node, graph, parentId);
2908
+ ensureSlot(graph, id, "contentWidth");
2909
+ ensureSlot(graph, id, "contentHeight");
2910
+ }
2911
+ var STACK_RULE = layoutRules["stack"];
2912
+ function applyLayoutFromRule(kind, node, graph, parentId) {
2913
+ if (STACK_RULE.applies_to && kind in STACK_RULE.applies_to) {
2914
+ const axisConfig = STACK_RULE.applies_to[kind];
2915
+ applyStackRule(STACK_RULE, axisConfig, kind, node, graph, parentId);
2916
+ return;
3040
2917
  }
3041
- const lineCount = measurement.lines.length;
3042
- const fontMetrics = textMeasurer.metrics(fontSize, fontWeight);
3043
- const { capHeight, lineHeight } = fontMetrics;
3044
- let textAnchorVal;
3045
- switch (textAlign) {
3046
- case "start":
3047
- case "left":
3048
- textAnchorVal = 0;
2918
+ let rule = layoutRules[kind];
2919
+ if (!rule) {
2920
+ applyStubRule(node, graph, parentId);
2921
+ return;
2922
+ }
2923
+ if (rule.inherits) {
2924
+ const base = layoutRules[rule.inherits];
2925
+ if (base) {
2926
+ rule = { ...base, ...rule };
2927
+ }
2928
+ }
2929
+ switch (rule.type) {
2930
+ case "root":
2931
+ applyRootRule(rule, node, graph);
3049
2932
  break;
3050
- case "end":
3051
- case "right":
3052
- textAnchorVal = 2;
2933
+ case "container":
2934
+ applyContainerRule(rule, node, graph, parentId);
2935
+ break;
2936
+ case "text_measurement":
2937
+ applyTextMeasurementRule(rule, node, graph, parentId);
2938
+ break;
2939
+ case "overlay":
2940
+ applyOverlayRule(rule, node, graph, parentId);
2941
+ break;
2942
+ case "connector":
2943
+ applyConnectorRule(rule, node, graph);
2944
+ break;
2945
+ case "fixed_size":
2946
+ applyFixedSizeRule(rule, node, graph, parentId);
2947
+ break;
2948
+ case "grid":
2949
+ applyGridRule(rule, node, graph, parentId);
3053
2950
  break;
3054
2951
  default:
3055
- textAnchorVal = 1;
2952
+ applyStubRule(node, graph, parentId);
3056
2953
  break;
3057
2954
  }
3058
- ensureSlot(graph, id, "textBaseline");
3059
- ensureSlot(graph, id, "textLineHeight");
3060
- ensureSlot(graph, id, "textX");
3061
- ensureSlot(graph, id, "textAnchor");
3062
- const textLayoutOpId = `op.textLayout.${id}`;
3063
- const textLayoutInputs = [slotId(id, "resolvedWidth"), slotId(id, "resolvedHeight")];
3064
- const textLayoutOutputs = [
3065
- slotId(id, "textBaseline"),
3066
- slotId(id, "textX"),
3067
- slotId(id, "textAnchor"),
3068
- slotId(id, "textLineHeight")
3069
- ];
3070
- addCandidate(graph, slotId(id, "textBaseline"), void 0, `text(${id}).layout`, "normal", textLayoutOpId);
3071
- addCandidate(graph, slotId(id, "textX"), void 0, `text(${id}).layout`, "normal", textLayoutOpId);
3072
- addCandidate(graph, slotId(id, "textAnchor"), void 0, `text(${id}).layout`, "normal", textLayoutOpId);
3073
- addCandidate(graph, slotId(id, "textLineHeight"), void 0, `text(${id}).layout`, "normal", textLayoutOpId);
3074
- addOperation(graph, textLayoutOpId, "identity", textLayoutInputs, textLayoutOutputs, (inputs) => {
3075
- const w = num(inputs[0]);
3076
- const h = num(inputs[1]);
3077
- const visualExtent = capHeight + (lineCount - 1) * lineHeight;
3078
- const baseline = (h - visualExtent) / 2 + capHeight;
3079
- let tx;
3080
- switch (textAnchorVal) {
3081
- case 0:
3082
- tx = 0;
3083
- break;
3084
- case 2:
3085
- tx = w;
3086
- break;
3087
- default:
3088
- tx = w / 2;
3089
- break;
2955
+ }
2956
+
2957
+ // src/ir/index.ts
2958
+ var IrNodeSchema = z.lazy(
2959
+ () => z.object({
2960
+ kind: z.string(),
2961
+ id: z.string().optional(),
2962
+ props: z.record(z.string(), z.unknown()),
2963
+ children: z.array(IrNodeSchema).optional()
2964
+ })
2965
+ );
2966
+ function validateNode(node, path) {
2967
+ if (!(node.kind in ELEMENT_CATALOG)) {
2968
+ throw new Error(`Invalid element kind '${node.kind}' at ${path}`);
2969
+ }
2970
+ const allowed = getAllowedProps(node.kind);
2971
+ if (allowed) {
2972
+ const unknownProps = Object.keys(node.props).filter((k) => !allowed.has(k));
2973
+ if (unknownProps.length > 0) {
2974
+ throw new Error(
2975
+ `Unknown properties for '${node.kind}' at ${path}: ${unknownProps.join(", ")}`
2976
+ );
3090
2977
  }
3091
- return [baseline, tx, textAnchorVal, lineHeight];
3092
- });
2978
+ }
2979
+ if (node.children) {
2980
+ for (let i = 0; i < node.children.length; i++) {
2981
+ validateNode(node.children[i], `${path}.children[${i}]`);
2982
+ }
2983
+ }
3093
2984
  }
3094
- function applyOverlayRule(rule, node, graph, parentId) {
3095
- const id = node.id;
3096
- const padding = getNumericProp(node, "padding", numericParamDefault(rule, "padding"));
3097
- registerSizeSlots(node, graph, parentId);
3098
- ensureSlot(graph, id, "contentWidth");
3099
- ensureSlot(graph, id, "contentHeight");
3100
- const children = childrenOf(node);
3101
- const childIds = children.filter((c) => !isConstraintKind(c.kind)).map((c) => c.id);
3102
- for (const childId of childIds) {
3103
- ensureSlot(graph, childId, "localX", padding);
3104
- ensureSlot(graph, childId, "localY", padding);
3105
- addCandidate(graph, slotId(childId, "localX"), padding, `overlay(${id})`, "normal");
3106
- addCandidate(graph, slotId(childId, "localY"), padding, `overlay(${id})`, "normal");
2985
+ function parseIr(json) {
2986
+ const parsed = IrNodeSchema.parse(json);
2987
+ validateNode(parsed, "root");
2988
+ return parsed;
2989
+ }
2990
+
2991
+ // src/parser/tokenizer.ts
2992
+ var SHAPE_PATTERNS = [
2993
+ { shape: "capsule", open: "([", close: "])" },
2994
+ { shape: "cylinder", open: "[(", close: ")]" },
2995
+ { shape: "circle", open: "((", close: "))" },
2996
+ { shape: "hexagon", open: "[[", close: "]]" },
2997
+ { shape: "roundedRect", open: "[", close: "]" },
2998
+ { shape: "diamond", open: "{", close: "}" },
2999
+ { shape: "rect", open: "(", close: ")" }
3000
+ ];
3001
+ var SHAPE_ALIASES = {
3002
+ stadium: "capsule",
3003
+ pill: "capsule",
3004
+ rounded: "roundedRect",
3005
+ db: "cylinder",
3006
+ database: "cylinder",
3007
+ cyl: "cylinder",
3008
+ decision: "diamond",
3009
+ hex: "hexagon",
3010
+ tri: "triangle"
3011
+ };
3012
+ function parseNodeShape(rest) {
3013
+ let shapeOverride;
3014
+ let cursor = 0;
3015
+ if (rest.startsWith("@")) {
3016
+ const atMatch = rest.match(/^@(\w+)/);
3017
+ if (!atMatch) return null;
3018
+ shapeOverride = SHAPE_ALIASES[atMatch[1]] ?? atMatch[1];
3019
+ cursor = atMatch[0].length;
3107
3020
  }
3108
- if (childIds.length > 0) {
3109
- for (const childId of childIds) {
3110
- ensureSlot(graph, childId, "resolvedWidth");
3111
- ensureSlot(graph, childId, "resolvedHeight");
3021
+ const remaining = rest.slice(cursor);
3022
+ for (const { shape, open, close } of SHAPE_PATTERNS) {
3023
+ if (!remaining.startsWith(open)) continue;
3024
+ const contentStart = open.length;
3025
+ const closeIdx = remaining.indexOf(close, contentStart);
3026
+ if (closeIdx === -1) continue;
3027
+ const afterClose = remaining.slice(closeIdx + close.length);
3028
+ if (afterClose.length > 0 && /^[a-zA-Z0-9_-]/.test(afterClose)) continue;
3029
+ let label = remaining.slice(contentStart, closeIdx);
3030
+ if (label.startsWith('"') && label.endsWith('"')) {
3031
+ label = label.slice(1, -1);
3032
+ }
3033
+ return {
3034
+ label,
3035
+ shape: shapeOverride ?? shape,
3036
+ shapeOverride,
3037
+ consumed: cursor + closeIdx + close.length
3038
+ };
3039
+ }
3040
+ return null;
3041
+ }
3042
+ function matchEdgeOp(s) {
3043
+ const trimmed = s.trimStart();
3044
+ for (const op of ["==>", "-.->", "-->", "---", "~~~"]) {
3045
+ if (!trimmed.startsWith(op)) continue;
3046
+ let after = trimmed.slice(op.length);
3047
+ let label;
3048
+ if (op !== "~~~" && after.startsWith("|")) {
3049
+ const pipeEnd = after.indexOf("|", 1);
3050
+ if (pipeEnd !== -1) {
3051
+ label = after.slice(1, pipeEnd).trim();
3052
+ after = after.slice(pipeEnd + 1);
3053
+ }
3054
+ }
3055
+ return { op, label, rest: after };
3056
+ }
3057
+ return null;
3058
+ }
3059
+ function parseNodeRef(s) {
3060
+ const trimmed = s.trimStart();
3061
+ const idMatch = trimmed.match(/^([a-zA-Z_][a-zA-Z0-9_-]*)/);
3062
+ if (!idMatch) return null;
3063
+ const nodeId = idMatch[1];
3064
+ let after = trimmed.slice(idMatch[0].length);
3065
+ const shapeParsed = parseNodeShape(after);
3066
+ let def;
3067
+ if (shapeParsed) {
3068
+ after = after.slice(shapeParsed.consumed);
3069
+ def = { label: shapeParsed.label, shape: shapeParsed.shape, shapeOverride: shapeParsed.shapeOverride };
3070
+ }
3071
+ if (after.startsWith(":::")) {
3072
+ const classMatch = after.slice(3).match(/^([a-zA-Z_][a-zA-Z0-9_-]*)/);
3073
+ if (classMatch) {
3074
+ if (def) {
3075
+ def.variant = classMatch[1];
3076
+ } else {
3077
+ def = { label: nodeId, shape: "roundedRect", variant: classMatch[1] };
3078
+ }
3079
+ after = after.slice(3 + classMatch[0].length);
3080
+ }
3081
+ }
3082
+ return { nodeId, def, rest: after };
3083
+ }
3084
+ function tokenizeLine(line, lineNum) {
3085
+ const trimmed = line.trim();
3086
+ if (trimmed === "") return null;
3087
+ if (trimmed.startsWith("%%")) {
3088
+ return { type: "comment", raw: line, line: lineNum };
3089
+ }
3090
+ const dirMatch = trimmed.match(/^(?:flowchart|graph)\s+(TD|TB|LR)$/i);
3091
+ if (dirMatch) {
3092
+ const dirRaw = dirMatch[1].toUpperCase();
3093
+ const dir = dirRaw === "TB" ? "TD" : dirRaw;
3094
+ if (dir !== "TD" && dir !== "LR") {
3095
+ return null;
3112
3096
  }
3113
- const contentOpId = `op.overlay.content.${id}`;
3114
- const childWidthSlots = childIds.map((cid) => slotId(cid, "resolvedWidth"));
3115
- const childHeightSlots = childIds.map((cid) => slotId(cid, "resolvedHeight"));
3116
- const contentInputs = [...childWidthSlots, ...childHeightSlots];
3117
- const contentOutputs = [slotId(id, "contentWidth"), slotId(id, "contentHeight")];
3118
- addCandidate(graph, slotId(id, "contentWidth"), void 0, `overlay(${id}).childContent`, "normal", contentOpId);
3119
- addCandidate(graph, slotId(id, "contentHeight"), void 0, `overlay(${id}).childContent`, "normal", contentOpId);
3120
- addOperation(graph, contentOpId, "resolveSize", contentInputs, contentOutputs, (inputs) => {
3121
- const nChildren = childIds.length;
3122
- const widths = inputs.slice(0, nChildren);
3123
- const heights = inputs.slice(nChildren);
3124
- return [Math.max(...widths, 0), Math.max(...heights, 0)];
3125
- });
3097
+ return { type: "direction", raw: line, line: lineNum, dir };
3126
3098
  }
3127
- const widthIntent = getSizeProp(node, "width");
3128
- const heightIntent = getSizeProp(node, "height");
3129
- if (widthIntent === "wrap") {
3130
- const wrapWidthOpId = `op.overlay.wrapWidth.${id}`;
3131
- const outSid = slotId(id, "resolvedWidth");
3132
- addCandidate(graph, outSid, void 0, `overlay(${id}).wrap`, "weak", wrapWidthOpId);
3133
- addOperation(graph, wrapWidthOpId, "resolveSize", [slotId(id, "contentWidth")], [outSid], (inputs) => {
3134
- return [num(inputs[0]) + padding * 2];
3135
- });
3099
+ const subMatch = trimmed.match(/^subgraph\s+(\S+)(?:\s+\[([^\]]*)\])?\s*$/);
3100
+ if (subMatch) {
3101
+ return {
3102
+ type: "subgraphStart",
3103
+ raw: line,
3104
+ line: lineNum,
3105
+ subgraphId: subMatch[1],
3106
+ label: subMatch[2] ?? void 0
3107
+ };
3136
3108
  }
3137
- if (heightIntent === "wrap") {
3138
- const wrapHeightOpId = `op.overlay.wrapHeight.${id}`;
3139
- const outSid = slotId(id, "resolvedHeight");
3140
- addCandidate(graph, outSid, void 0, `overlay(${id}).wrap`, "weak", wrapHeightOpId);
3141
- addOperation(graph, wrapHeightOpId, "resolveSize", [slotId(id, "contentHeight")], [outSid], (inputs) => {
3142
- return [num(inputs[0]) + padding * 2];
3143
- });
3109
+ if (trimmed === "end") {
3110
+ return { type: "subgraphEnd", raw: line, line: lineNum };
3144
3111
  }
3145
- if (widthIntent === "fill" && parentId && !rejectMainAxisFill(node, graph, "resolvedWidth", "normal", parentId)) {
3146
- const fillWidthOpId = `op.overlay.fillWidth.${id}`;
3147
- const outSid = slotId(id, "resolvedWidth");
3148
- ensureSlot(graph, parentId, "availableWidth");
3149
- addCandidate(graph, outSid, void 0, `overlay(${id}).fill`, "normal", fillWidthOpId);
3150
- addOperation(graph, fillWidthOpId, "resolveSize", [slotId(parentId, "availableWidth")], [outSid], (inputs) => {
3151
- return [num(inputs[0])];
3152
- });
3112
+ const localDirMatch = trimmed.match(/^direction\s+(TD|TB|LR)$/i);
3113
+ if (localDirMatch) {
3114
+ const dirRaw = localDirMatch[1].toUpperCase();
3115
+ const dir = dirRaw === "TB" ? "TD" : dirRaw;
3116
+ return { type: "localDirection", raw: line, line: lineNum, dir };
3153
3117
  }
3154
- if (heightIntent === "fill" && parentId && !rejectMainAxisFill(node, graph, "resolvedHeight", "normal", parentId)) {
3155
- const fillHeightOpId = `op.overlay.fillHeight.${id}`;
3156
- const outSid = slotId(id, "resolvedHeight");
3157
- ensureSlot(graph, parentId, "availableHeight");
3158
- addCandidate(graph, outSid, void 0, `overlay(${id}).fill`, "normal", fillHeightOpId);
3159
- addOperation(graph, fillHeightOpId, "resolveSize", [slotId(parentId, "availableHeight")], [outSid], (inputs) => {
3160
- return [num(inputs[0])];
3161
- });
3118
+ const classDefMatch = trimmed.match(/^classDef\s+(\S+)\s+(.+)$/);
3119
+ if (classDefMatch) {
3120
+ return {
3121
+ type: "classDef",
3122
+ raw: line,
3123
+ line: lineNum,
3124
+ className: classDefMatch[1],
3125
+ styles: classDefMatch[2]
3126
+ };
3162
3127
  }
3163
- const availWidthOpId = `op.overlay.availW.${id}`;
3164
- ensureSlot(graph, id, "availableWidth");
3165
- addCandidate(graph, slotId(id, "availableWidth"), void 0, `overlay(${id}).availW`, "normal", availWidthOpId);
3166
- addOperation(graph, availWidthOpId, "resolveSize", [slotId(id, "resolvedWidth")], [slotId(id, "availableWidth")], (inputs) => {
3167
- return [Math.max(num(inputs[0]) - padding * 2, 0)];
3168
- });
3169
- const availHeightOpId = `op.overlay.availH.${id}`;
3170
- ensureSlot(graph, id, "availableHeight");
3171
- addCandidate(graph, slotId(id, "availableHeight"), void 0, `overlay(${id}).availH`, "normal", availHeightOpId);
3172
- addOperation(graph, availHeightOpId, "resolveSize", [slotId(id, "resolvedHeight")], [slotId(id, "availableHeight")], (inputs) => {
3173
- return [Math.max(num(inputs[0]) - padding * 2, 0)];
3174
- });
3128
+ if (trimmed.startsWith("@")) {
3129
+ return parseDirective(trimmed, line, lineNum);
3130
+ }
3131
+ return parseEdgeOrNodeLine(trimmed, line, lineNum);
3175
3132
  }
3176
- function applyConnectorRule(_rule, node, graph) {
3177
- const id = node.id;
3178
- const fromId = node.props.from;
3179
- const toId = node.props.to;
3180
- ensureSlot(graph, id, "resolvedWidth", 0);
3181
- ensureSlot(graph, id, "resolvedHeight", 0);
3182
- ensureSlot(graph, id, "localX", 0);
3183
- ensureSlot(graph, id, "localY", 0);
3184
- ensureSlot(graph, id, "connectorPath");
3185
- if (fromId && toId) {
3186
- ensureSlot(graph, fromId, "localX");
3187
- ensureSlot(graph, fromId, "localY");
3188
- ensureSlot(graph, fromId, "resolvedWidth");
3189
- ensureSlot(graph, fromId, "resolvedHeight");
3190
- ensureSlot(graph, toId, "localX");
3191
- ensureSlot(graph, toId, "localY");
3192
- ensureSlot(graph, toId, "resolvedWidth");
3193
- ensureSlot(graph, toId, "resolvedHeight");
3194
- addCandidate(graph, slotId(id, "connectorPath"), 0, `connector(${id})`, "normal");
3133
+ var SAME_SIZE_DEFAULT_STRATEGY = "max";
3134
+ function parseDirective(trimmed, raw, lineNum) {
3135
+ const sameWidthMatch = trimmed.match(/^@same-width(?:\s+(\w+))?:\s*(.+)$/);
3136
+ if (sameWidthMatch) {
3137
+ const strategy = sameWidthMatch[1] ?? SAME_SIZE_DEFAULT_STRATEGY;
3138
+ const targets = sameWidthMatch[2].split(",").map((t) => t.trim()).filter(Boolean);
3139
+ return {
3140
+ type: "directive",
3141
+ raw,
3142
+ line: lineNum,
3143
+ directiveType: "same-width",
3144
+ strategy,
3145
+ targets
3146
+ };
3147
+ }
3148
+ const sameHeightMatch = trimmed.match(/^@same-height(?:\s+(\w+))?:\s*(.+)$/);
3149
+ if (sameHeightMatch) {
3150
+ const strategy = sameHeightMatch[1] ?? SAME_SIZE_DEFAULT_STRATEGY;
3151
+ const targets = sameHeightMatch[2].split(",").map((t) => t.trim()).filter(Boolean);
3152
+ return {
3153
+ type: "directive",
3154
+ raw,
3155
+ line: lineNum,
3156
+ directiveType: "same-height",
3157
+ strategy,
3158
+ targets
3159
+ };
3160
+ }
3161
+ const gapMatch = trimmed.match(/^@gap\s+min=(\d+):\s*(.+)$/);
3162
+ if (gapMatch) {
3163
+ const min = parseInt(gapMatch[1], 10);
3164
+ const targets = gapMatch[2].split(",").map((t) => t.trim()).filter(Boolean);
3165
+ return {
3166
+ type: "directive",
3167
+ raw,
3168
+ line: lineNum,
3169
+ directiveType: "gap",
3170
+ min,
3171
+ targets
3172
+ };
3173
+ }
3174
+ const moverMatch = trimmed.match(/^@mover\s+(\S+):\s*(.+)$/);
3175
+ if (moverMatch) {
3176
+ const moverId = moverMatch[1];
3177
+ const targets = moverMatch[2].split(",").map((t) => t.trim()).filter(Boolean);
3178
+ return {
3179
+ type: "directive",
3180
+ raw,
3181
+ line: lineNum,
3182
+ directiveType: "mover",
3183
+ moverId,
3184
+ targets
3185
+ };
3195
3186
  }
3187
+ return null;
3196
3188
  }
3197
- function applyFixedSizeRule(rule, node, graph, parentId) {
3198
- const id = node.id;
3199
- const kind = node.kind;
3200
- let widthSpec;
3201
- let heightSpec;
3202
- if (rule.size_from_axis) {
3203
- const axis = getStringProp(node, "axis", stringParamDefault(rule, "axis"));
3204
- const sizeConfig = rule.size_from_axis[axis];
3205
- widthSpec = sizeConfig?.width ?? 0;
3206
- heightSpec = sizeConfig?.height ?? 0;
3207
- } else {
3208
- widthSpec = getNumericProp(node, "width", numericParamDefault(rule, "width"));
3209
- heightSpec = getNumericProp(node, "height", numericParamDefault(rule, "height"));
3189
+ function parseEdgeOrNodeLine(trimmed, raw, lineNum) {
3190
+ const firstRef = parseNodeRef(trimmed);
3191
+ if (!firstRef) return null;
3192
+ let cursor = trimmed.length - firstRef.rest.length;
3193
+ let remaining = firstRef.rest;
3194
+ const edgeMatch = matchEdgeOp(remaining);
3195
+ if (!edgeMatch) {
3196
+ if (!firstRef.def) {
3197
+ return null;
3198
+ }
3199
+ return {
3200
+ type: "nodeDef",
3201
+ raw,
3202
+ line: lineNum,
3203
+ nodeId: firstRef.nodeId,
3204
+ label: firstRef.def.label,
3205
+ shape: firstRef.def.shape,
3206
+ variant: firstRef.def.variant,
3207
+ shapeOverride: firstRef.def.shapeOverride
3208
+ };
3210
3209
  }
3211
- ensureSlot(graph, id, "localX", 0);
3212
- ensureSlot(graph, id, "localY", 0);
3213
- const priority = kind === "divider" ? "weak" : "normal";
3214
- applyFixedSizeDimension(node, graph, "resolvedWidth", widthSpec, priority, parentId);
3215
- applyFixedSizeDimension(node, graph, "resolvedHeight", heightSpec, priority, parentId);
3210
+ if (edgeMatch.op === "~~~") {
3211
+ return parseInvisibleEdgeChain(trimmed, firstRef, raw, lineNum);
3212
+ }
3213
+ return parseVisibleEdgeChain(trimmed, firstRef, raw, lineNum);
3216
3214
  }
3217
- function applyFixedSizeDimension(node, graph, dim, spec, priority, parentId) {
3218
- const id = node.id;
3219
- const kind = node.kind;
3220
- const outSid = slotId(id, dim);
3221
- if (typeof spec === "number" && Number.isFinite(spec)) {
3222
- ensureSlot(graph, id, dim, spec);
3223
- addCandidate(graph, outSid, spec, `${kind}(${id})`, priority);
3224
- return;
3215
+ function parseInvisibleEdgeChain(input, firstRef, raw, lineNum) {
3216
+ const segments = [];
3217
+ let currentId = firstRef.nodeId;
3218
+ let remaining = firstRef.rest;
3219
+ while (true) {
3220
+ const edgeMatch = matchEdgeOp(remaining);
3221
+ if (!edgeMatch || edgeMatch.op !== "~~~") break;
3222
+ remaining = edgeMatch.rest;
3223
+ const nextRef = parseNodeRef(remaining);
3224
+ if (!nextRef) break;
3225
+ segments.push({ fromId: currentId, toId: nextRef.nodeId });
3226
+ currentId = nextRef.nodeId;
3227
+ remaining = nextRef.rest;
3225
3228
  }
3226
- ensureSlot(graph, id, dim);
3227
- if (spec === "fill" && parentId) {
3228
- if (rejectMainAxisFill(node, graph, dim, priority, parentId)) return;
3229
- const dimName = dim === "resolvedWidth" ? "width" : "height";
3230
- const availSlot = dim === "resolvedWidth" ? "availableWidth" : "availableHeight";
3231
- const opId = `op.${kind}.fill.${dimName}.${id}`;
3232
- ensureSlot(graph, parentId, availSlot);
3233
- addCandidate(graph, outSid, void 0, `${kind}(${id}).fill`, priority, opId);
3234
- addOperation(graph, opId, "resolveSize", [slotId(parentId, availSlot)], [outSid], (inputs) => {
3235
- return [num(inputs[0])];
3236
- });
3237
- return;
3229
+ return { type: "invisibleEdge", raw, line: lineNum, segments };
3230
+ }
3231
+ function parseVisibleEdgeChain(input, firstRef, raw, lineNum) {
3232
+ const segments = [];
3233
+ let currentId = firstRef.nodeId;
3234
+ let currentDef = firstRef.def;
3235
+ let remaining = firstRef.rest;
3236
+ while (true) {
3237
+ const edgeMatch = matchEdgeOp(remaining);
3238
+ if (!edgeMatch || edgeMatch.op === "~~~") break;
3239
+ remaining = edgeMatch.rest;
3240
+ let colonLabel;
3241
+ const nextRef = parseNodeRef(remaining);
3242
+ if (!nextRef) break;
3243
+ remaining = nextRef.rest;
3244
+ const colonMatch = remaining.match(/^\s*:\s*(.+?)$/);
3245
+ if (colonMatch) {
3246
+ colonLabel = colonMatch[1].trim();
3247
+ remaining = "";
3248
+ }
3249
+ const seg = {
3250
+ fromId: currentId,
3251
+ toId: nextRef.nodeId,
3252
+ edgeType: edgeMatch.op,
3253
+ edgeLabel: edgeMatch.label ?? colonLabel
3254
+ };
3255
+ if (currentDef) {
3256
+ seg.fromDef = currentDef;
3257
+ }
3258
+ if (nextRef.def) {
3259
+ seg.toDef = nextRef.def;
3260
+ }
3261
+ segments.push(seg);
3262
+ currentId = nextRef.nodeId;
3263
+ currentDef = nextRef.def;
3238
3264
  }
3239
- addCandidate(graph, outSid, 0, `${kind}(${id})`, priority);
3265
+ return { type: "edge", raw, line: lineNum, segments };
3240
3266
  }
3241
- function applyGridRule(rule, node, graph, parentId) {
3242
- const id = node.id;
3243
- const gap = getNumericProp(node, "gap", 0);
3244
- const padding = getNumericProp(node, "padding", 0);
3245
- const gridConfig = rule.grid;
3246
- const rowKind = gridConfig.row_kind;
3247
- const cellKind = gridConfig.cell_kind;
3248
- registerSizeSlots(node, graph, parentId);
3249
- ensureSlot(graph, id, "contentWidth");
3250
- ensureSlot(graph, id, "contentHeight");
3251
- const rows = childrenOf(node).filter((c) => c.kind === rowKind);
3252
- if (rows.length === 0) return;
3253
- const rowIds = rows.map((r) => r.id);
3254
- for (const rowId of rowIds) {
3255
- ensureSlot(graph, rowId, "resolvedWidth");
3256
- ensureSlot(graph, rowId, "resolvedHeight");
3257
- ensureSlot(graph, rowId, "localX");
3258
- ensureSlot(graph, rowId, "localY");
3259
- }
3260
- const rowPosOpId = `op.grid.rowPos.${id}`;
3261
- const rowHeightSlots = rowIds.map((rid) => slotId(rid, "resolvedHeight"));
3262
- const rowPosOutputs = [
3263
- ...rowIds.map((rid) => slotId(rid, "localY")),
3264
- ...rowIds.map((rid) => slotId(rid, "localX")),
3265
- slotId(id, "contentHeight"),
3266
- slotId(id, "resolvedHeight")
3267
- ];
3268
- for (const rid of rowIds) {
3269
- addCandidate(graph, slotId(rid, "localY"), void 0, `grid(${id}).rowPos`, "strong", rowPosOpId);
3270
- addCandidate(graph, slotId(rid, "localX"), void 0, `grid(${id}).rowX`, "normal", rowPosOpId);
3267
+ function tokenize(source) {
3268
+ const lines = source.split("\n");
3269
+ const tokens = [];
3270
+ for (let i = 0; i < lines.length; i++) {
3271
+ const token = tokenizeLine(lines[i], i + 1);
3272
+ if (token) {
3273
+ tokens.push(token);
3274
+ }
3271
3275
  }
3272
- addCandidate(graph, slotId(id, "contentHeight"), void 0, `grid(${id}).contentH`, "strong", rowPosOpId);
3273
- addCandidate(graph, slotId(id, "resolvedHeight"), void 0, `grid(${id}).wrapH`, "normal", rowPosOpId);
3274
- addOperation(graph, rowPosOpId, "stackPosition", rowHeightSlots, rowPosOutputs, (inputs) => {
3275
- let y = padding;
3276
- const yPositions = [];
3277
- for (let i = 0; i < rowIds.length; i++) {
3278
- yPositions.push(y);
3279
- y += num(inputs[i]) + (i < rowIds.length - 1 ? gap : 0);
3276
+ return tokens;
3277
+ }
3278
+
3279
+ // src/parser/parser.ts
3280
+ function parseDrawText(source) {
3281
+ const diagnostics = [];
3282
+ const tokens = tokenize(source);
3283
+ let rootDirection = "TD";
3284
+ const nodeMap = /* @__PURE__ */ new Map();
3285
+ const connectors = [];
3286
+ const constraints = [];
3287
+ const classDefMap = /* @__PURE__ */ new Map();
3288
+ const scopeStack = [];
3289
+ const groups = [];
3290
+ const rootNodeIds = [];
3291
+ function currentDirection() {
3292
+ for (let i = scopeStack.length - 1; i >= 0; i--) {
3293
+ if (scopeStack[i].direction) return scopeStack[i].direction;
3280
3294
  }
3281
- const contentH = y - padding;
3282
- const totalH = contentH + padding * 2;
3283
- const xPositions = rowIds.map(() => padding);
3284
- return [...yPositions, ...xPositions, contentH, totalH];
3285
- });
3286
- const maxCols = Math.max(...rows.map((r) => childrenOf(r).filter((c) => c.kind === cellKind).length));
3287
- const columnCellIds = [];
3288
- for (let col = 0; col < maxCols; col++) {
3289
- columnCellIds.push([]);
3295
+ return rootDirection;
3290
3296
  }
3291
- for (const row of rows) {
3292
- const cells = childrenOf(row).filter((c) => c.kind === cellKind);
3293
- for (let col = 0; col < cells.length && col < maxCols; col++) {
3294
- columnCellIds[col].push(cells[col].id);
3297
+ function registerNode(id, label, shape, variant) {
3298
+ if (!nodeMap.has(id)) {
3299
+ nodeMap.set(id, { id, label, shape, variant });
3300
+ }
3301
+ if (scopeStack.length > 0) {
3302
+ const top = scopeStack[scopeStack.length - 1];
3303
+ if (!top.nodeIds.includes(id)) top.nodeIds.push(id);
3304
+ } else {
3305
+ if (!rootNodeIds.includes(id)) rootNodeIds.push(id);
3295
3306
  }
3296
3307
  }
3297
- const cellPaddingMap = /* @__PURE__ */ new Map();
3298
- for (const row of rows) {
3299
- for (const cell of childrenOf(row).filter((c) => c.kind === cellKind)) {
3300
- cellPaddingMap.set(cell.id, getNumericProp(cell, "padding", 0));
3308
+ function ensureNode(id) {
3309
+ if (nodeMap.has(id)) return;
3310
+ nodeMap.set(id, { id, label: id, shape: "roundedRect" });
3311
+ if (scopeStack.length > 0) {
3312
+ const top = scopeStack[scopeStack.length - 1];
3313
+ if (!top.nodeIds.includes(id)) top.nodeIds.push(id);
3314
+ } else {
3315
+ if (!rootNodeIds.includes(id)) rootNodeIds.push(id);
3301
3316
  }
3302
3317
  }
3303
- const colMinWidthSlots = [];
3304
- for (let col = 0; col < maxCols; col++) {
3305
- const cellIds = columnCellIds[col];
3306
- const colMinSlot = `${id}.colMinWidth.${col}`;
3307
- colMinWidthSlots.push(colMinSlot);
3308
- ensureSlot(graph, id, `colMinWidth.${col}`);
3309
- if (cellIds.length < 2) {
3310
- if (cellIds.length === 1) {
3311
- const cid = cellIds[0];
3312
- const p = num(cellPaddingMap.get(cid));
3313
- const singleOpId = `op.grid.colMin.${id}.${col}`;
3314
- ensureSlot(graph, cid, "contentWidth");
3315
- addCandidate(graph, colMinSlot, void 0, `grid(${id}).colMin[${col}]`, "strong", singleOpId);
3316
- addOperation(graph, singleOpId, "columnWidthResolve", [slotId(cid, "contentWidth")], [colMinSlot], (inputs) => {
3317
- return [num(inputs[0]) + p * 2];
3318
+ for (const token of tokens) {
3319
+ switch (token.type) {
3320
+ case "comment":
3321
+ break;
3322
+ case "direction":
3323
+ rootDirection = token.dir;
3324
+ break;
3325
+ case "nodeDef": {
3326
+ const t = token;
3327
+ registerNode(t.nodeId, t.label, t.shape, t.variant);
3328
+ break;
3329
+ }
3330
+ case "edge": {
3331
+ const t = token;
3332
+ for (const seg of t.segments) {
3333
+ processEdgeSegment(seg);
3334
+ }
3335
+ break;
3336
+ }
3337
+ case "invisibleEdge": {
3338
+ const t = token;
3339
+ for (const seg of t.segments) {
3340
+ ensureNode(seg.fromId);
3341
+ ensureNode(seg.toId);
3342
+ }
3343
+ const dir = currentDirection();
3344
+ const allIds = /* @__PURE__ */ new Set();
3345
+ for (const seg of t.segments) {
3346
+ allIds.add(seg.fromId);
3347
+ allIds.add(seg.toId);
3348
+ }
3349
+ constraints.push(buildAlignConstraint([...allIds], dir));
3350
+ break;
3351
+ }
3352
+ case "subgraphStart": {
3353
+ const t = token;
3354
+ scopeStack.push({
3355
+ id: t.subgraphId,
3356
+ label: t.label,
3357
+ nodeIds: []
3318
3358
  });
3359
+ break;
3319
3360
  }
3320
- continue;
3361
+ case "subgraphEnd": {
3362
+ if (scopeStack.length === 0) {
3363
+ diagnostics.push({
3364
+ level: "warning",
3365
+ message: "Unexpected 'end' without matching subgraph",
3366
+ path: `line:${token.line}`
3367
+ });
3368
+ break;
3369
+ }
3370
+ const frame = scopeStack.pop();
3371
+ groups.push({ frame, children: [...frame.nodeIds] });
3372
+ if (scopeStack.length > 0) {
3373
+ const parent = scopeStack[scopeStack.length - 1];
3374
+ if (!parent.nodeIds.includes(frame.id)) parent.nodeIds.push(frame.id);
3375
+ } else {
3376
+ if (!rootNodeIds.includes(frame.id)) rootNodeIds.push(frame.id);
3377
+ }
3378
+ break;
3379
+ }
3380
+ case "localDirection": {
3381
+ const t = token;
3382
+ if (scopeStack.length > 0) {
3383
+ scopeStack[scopeStack.length - 1].direction = t.dir;
3384
+ } else {
3385
+ rootDirection = t.dir;
3386
+ }
3387
+ break;
3388
+ }
3389
+ case "classDef": {
3390
+ const t = token;
3391
+ classDefMap.set(t.className, t.styles);
3392
+ break;
3393
+ }
3394
+ case "directive": {
3395
+ const t = token;
3396
+ processDirective(t);
3397
+ break;
3398
+ }
3399
+ }
3400
+ }
3401
+ function processEdgeSegment(seg) {
3402
+ if (seg.fromDef) {
3403
+ registerNode(seg.fromId, seg.fromDef.label, seg.fromDef.shape, seg.fromDef.variant);
3404
+ } else {
3405
+ ensureNode(seg.fromId);
3406
+ }
3407
+ if (seg.toDef) {
3408
+ registerNode(seg.toId, seg.toDef.label, seg.toDef.shape, seg.toDef.variant);
3409
+ } else {
3410
+ ensureNode(seg.toId);
3411
+ }
3412
+ const connectorProps = {
3413
+ from: seg.fromId,
3414
+ to: seg.toId
3415
+ };
3416
+ switch (seg.edgeType) {
3417
+ case "-->":
3418
+ connectorProps.endArrow = "arrow";
3419
+ break;
3420
+ case "---":
3421
+ connectorProps.startArrow = "none";
3422
+ connectorProps.endArrow = "none";
3423
+ break;
3424
+ case "-.->":
3425
+ connectorProps.strokeStyle = "dashed";
3426
+ connectorProps.endArrow = "arrow";
3427
+ break;
3428
+ case "==>":
3429
+ connectorProps.strokeWidth = 3;
3430
+ connectorProps.endArrow = "arrow";
3431
+ break;
3432
+ }
3433
+ const children = [];
3434
+ if (seg.edgeLabel) {
3435
+ children.push({
3436
+ kind: "label",
3437
+ props: { text: seg.edgeLabel }
3438
+ });
3439
+ }
3440
+ const connector = {
3441
+ kind: "connector",
3442
+ props: connectorProps
3443
+ };
3444
+ if (children.length > 0) {
3445
+ connector.children = children;
3321
3446
  }
3322
- const colEqOpId = `op.grid.colMin.${id}.${col}`;
3323
- const widthInputs = cellIds.map((cid) => {
3324
- ensureSlot(graph, cid, "contentWidth");
3325
- return slotId(cid, "contentWidth");
3326
- });
3327
- const colPaddings = cellIds.map((cid) => num(cellPaddingMap.get(cid)));
3328
- addCandidate(graph, colMinSlot, void 0, `grid(${id}).colMin[${col}]`, "strong", colEqOpId);
3329
- addOperation(graph, colEqOpId, "columnWidthResolve", widthInputs, [colMinSlot], (inputs) => {
3330
- const desiredWidths = inputs.map((w, i) => num(w) + colPaddings[i] * 2);
3331
- return [Math.max(...desiredWidths, 0)];
3332
- });
3333
- }
3334
- if (maxCols > 0) {
3335
- const wrapWidthOpId = `op.grid.wrapWidth.${id}`;
3336
- const wrapOutputs = [slotId(id, "contentWidth"), slotId(id, "resolvedWidth")];
3337
- addCandidate(graph, slotId(id, "contentWidth"), void 0, `grid(${id}).wrapContentW`, "normal", wrapWidthOpId);
3338
- addCandidate(graph, slotId(id, "resolvedWidth"), void 0, `grid(${id}).wrapW`, "normal", wrapWidthOpId);
3339
- addOperation(graph, wrapWidthOpId, "resolveSize", colMinWidthSlots, wrapOutputs, (inputs) => {
3340
- const contentW = inputs.reduce((sum, w) => sum + num(w), 0) + gap * Math.max(0, inputs.length - 1);
3341
- return [contentW, contentW + padding * 2];
3342
- });
3447
+ connectors.push(connector);
3343
3448
  }
3344
- const colResolvedWidthSlots = [];
3345
- if (maxCols > 0) {
3346
- const colFillOpId = `op.grid.colFill.${id}`;
3347
- const colFillInputs = [slotId(id, "resolvedWidth"), ...colMinWidthSlots];
3348
- const colFillOutputs = [];
3349
- for (let col = 0; col < maxCols; col++) {
3350
- const colResSlot = `${id}.colResolvedWidth.${col}`;
3351
- colResolvedWidthSlots.push(colResSlot);
3352
- ensureSlot(graph, id, `colResolvedWidth.${col}`);
3353
- colFillOutputs.push(colResSlot);
3354
- addCandidate(graph, colResSlot, void 0, `grid(${id}).colFill[${col}]`, "strong", colFillOpId);
3449
+ function processDirective(t) {
3450
+ switch (t.directiveType) {
3451
+ case "same-width": {
3452
+ const props = { targets: t.targets };
3453
+ if (t.strategy) props.strategy = t.strategy;
3454
+ constraints.push({ kind: "equalizeWidth", props });
3455
+ break;
3456
+ }
3457
+ case "same-height": {
3458
+ const props = { targets: t.targets };
3459
+ if (t.strategy) props.strategy = t.strategy;
3460
+ constraints.push({ kind: "equalizeHeight", props });
3461
+ break;
3462
+ }
3463
+ case "gap": {
3464
+ const props = {
3465
+ targets: t.targets,
3466
+ gap: t.min
3467
+ };
3468
+ constraints.push({ kind: "minGap", props });
3469
+ break;
3470
+ }
3471
+ case "mover": {
3472
+ const props = {
3473
+ targets: t.targets,
3474
+ mover: t.moverId
3475
+ };
3476
+ constraints.push({ kind: "alignConstraint", props });
3477
+ break;
3478
+ }
3355
3479
  }
3356
- addOperation(graph, colFillOpId, "columnFill", colFillInputs, colFillOutputs, (inputs) => {
3357
- const resolvedW = num(inputs[0]);
3358
- const availableW = resolvedW - padding * 2;
3359
- const minWidths = inputs.slice(1).map((v) => num(v));
3360
- const totalMin = minWidths.reduce((s, w) => s + w, 0) + gap * Math.max(0, maxCols - 1);
3361
- const surplus = Math.max(0, availableW - totalMin);
3362
- const surplusPerCol = surplus / maxCols;
3363
- return minWidths.map((mw) => mw + surplusPerCol);
3364
- });
3365
3480
  }
3366
- for (let col = 0; col < maxCols; col++) {
3367
- const cellIds = columnCellIds[col];
3368
- if (cellIds.length === 0) continue;
3369
- const cellWOpId = `op.grid.cellW.${id}.${col}`;
3370
- const colResSlot = colResolvedWidthSlots[col];
3371
- const cellWOutputs = cellIds.map((cid) => slotId(cid, "resolvedWidth"));
3372
- for (const cid of cellIds) {
3373
- addCandidate(graph, slotId(cid, "resolvedWidth"), void 0, `grid(${id}).cellW[${col}]`, "strong", cellWOpId);
3481
+ const stackKind = rootDirection === "LR" ? "hstack" : "vstack";
3482
+ const groupNodes = /* @__PURE__ */ new Map();
3483
+ for (const g of groups) {
3484
+ const dir = g.frame.direction ?? rootDirection;
3485
+ const innerKind = dir === "LR" ? "hstack" : "vstack";
3486
+ const groupChildren = [];
3487
+ const innerStack = {
3488
+ kind: innerKind,
3489
+ props: { gap: 60, align: "center" },
3490
+ children: []
3491
+ };
3492
+ for (const childId of g.children) {
3493
+ const childGroup = groupNodes.get(childId);
3494
+ if (childGroup) {
3495
+ innerStack.children.push(childGroup);
3496
+ } else {
3497
+ const node = nodeMap.get(childId);
3498
+ if (node) {
3499
+ innerStack.children.push(buildBox(node));
3500
+ }
3501
+ }
3374
3502
  }
3375
- addOperation(graph, cellWOpId, "copy", [colResSlot], cellWOutputs, (inputs) => {
3376
- return cellIds.map(() => num(inputs[0]));
3377
- });
3378
- }
3379
- for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
3380
- const cells = childrenOf(rows[rowIdx]).filter((c) => c.kind === cellKind);
3381
- const cellIds = cells.map((c) => c.id);
3382
- if (cellIds.length < 2) continue;
3383
- const rowEqOpId = `op.grid.rowEq.${id}.${rowIdx}`;
3384
- const heightInputs = cellIds.map((cid) => {
3385
- ensureSlot(graph, cid, "contentHeight");
3386
- return slotId(cid, "contentHeight");
3387
- });
3388
- const rowEqOutputs = cellIds.map((cid) => slotId(cid, "resolvedHeight"));
3389
- const rowPaddings = cellIds.map((cid) => num(cellPaddingMap.get(cid)));
3390
- for (const cid of cellIds) {
3391
- addCandidate(graph, slotId(cid, "resolvedHeight"), void 0, `grid(${id}).rowEq[${rowIdx}]`, "strong", rowEqOpId);
3503
+ groupChildren.push(innerStack);
3504
+ const groupNode = {
3505
+ kind: "group",
3506
+ id: g.frame.id,
3507
+ props: {},
3508
+ children: groupChildren
3509
+ };
3510
+ if (g.frame.label) {
3511
+ groupNode.props.label = g.frame.label;
3392
3512
  }
3393
- addOperation(graph, rowEqOpId, "rowHeightResolve", heightInputs, rowEqOutputs, (inputs) => {
3394
- const desiredHeights = inputs.map((h, i) => num(h) + rowPaddings[i] * 2);
3395
- const maxH = Math.max(...desiredHeights, 0);
3396
- return cellIds.map(() => maxH);
3397
- });
3398
- }
3399
- for (const rowId of rowIds) {
3400
- const rowWidthOpId = `op.grid.rowWidth.${id}.${rowId}`;
3401
- const outSid = slotId(rowId, "resolvedWidth");
3402
- addCandidate(graph, outSid, void 0, `grid(${id}).rowWidth`, "normal", rowWidthOpId);
3403
- addOperation(graph, rowWidthOpId, "resolveSize", [slotId(id, "resolvedWidth")], [outSid], (inputs) => {
3404
- return [num(inputs[0]) - padding * 2];
3405
- });
3513
+ groupNodes.set(g.frame.id, groupNode);
3406
3514
  }
3407
- for (let rowIdx = 0; rowIdx < rows.length; rowIdx++) {
3408
- const cells = childrenOf(rows[rowIdx]).filter((c) => c.kind === cellKind);
3409
- const cellIds = cells.map((c) => c.id);
3410
- const rowHeightOpId = `op.grid.rowH.${id}.${rowIdx}`;
3411
- const cellHeightInputs = cellIds.map((cid) => slotId(cid, "resolvedHeight"));
3412
- const outSid = slotId(rowIds[rowIdx], "resolvedHeight");
3413
- addCandidate(graph, outSid, void 0, `grid(${id}).rowH`, "normal", rowHeightOpId);
3414
- addOperation(graph, rowHeightOpId, "max", cellHeightInputs, [outSid], (inputs) => {
3415
- return [Math.max(...inputs, 0)];
3416
- });
3515
+ const rootChildren = [];
3516
+ for (const id of rootNodeIds) {
3517
+ const groupNode = groupNodes.get(id);
3518
+ if (groupNode) {
3519
+ rootChildren.push(groupNode);
3520
+ } else {
3521
+ const node = nodeMap.get(id);
3522
+ if (node) {
3523
+ rootChildren.push(buildBox(node));
3524
+ }
3525
+ }
3417
3526
  }
3527
+ const rootStack = {
3528
+ kind: stackKind,
3529
+ props: { gap: 60, align: "center" },
3530
+ children: rootChildren
3531
+ };
3532
+ const documentChildren = [rootStack, ...connectors, ...constraints];
3533
+ const document = {
3534
+ kind: "document",
3535
+ props: { padding: 20 },
3536
+ children: documentChildren
3537
+ };
3538
+ return { ir: document, diagnostics };
3418
3539
  }
3419
- function applyStubRule(node, graph, parentId) {
3420
- const id = node.id;
3421
- registerSizeSlots(node, graph, parentId);
3422
- ensureSlot(graph, id, "contentWidth");
3423
- ensureSlot(graph, id, "contentHeight");
3424
- }
3425
- var STACK_RULE = layoutRules["stack"];
3426
- function applyLayoutFromRule(kind, node, graph, parentId) {
3427
- if (STACK_RULE.applies_to && kind in STACK_RULE.applies_to) {
3428
- const axisConfig = STACK_RULE.applies_to[kind];
3429
- applyStackRule(STACK_RULE, axisConfig, kind, node, graph, parentId);
3430
- return;
3431
- }
3432
- let rule = layoutRules[kind];
3433
- if (!rule) {
3434
- applyStubRule(node, graph, parentId);
3435
- return;
3540
+ function buildBox(node) {
3541
+ const props = { shape: node.shape };
3542
+ if (node.variant) {
3543
+ props.variant = node.variant;
3436
3544
  }
3437
- if (rule.inherits) {
3438
- const base = layoutRules[rule.inherits];
3439
- if (base) {
3440
- rule = { ...base, ...rule };
3545
+ return {
3546
+ kind: "box",
3547
+ id: node.id,
3548
+ props,
3549
+ children: [
3550
+ { kind: "text", props: { text: node.label } }
3551
+ ]
3552
+ };
3553
+ }
3554
+ function buildAlignConstraint(targets, direction) {
3555
+ const axis = direction === "TD" ? "vertical" : "horizontal";
3556
+ return {
3557
+ kind: "alignConstraint",
3558
+ props: {
3559
+ targets,
3560
+ axis,
3561
+ align: "center"
3441
3562
  }
3442
- }
3443
- switch (rule.type) {
3444
- case "root":
3445
- applyRootRule(rule, node, graph);
3446
- break;
3447
- case "container":
3448
- applyContainerRule(rule, node, graph, parentId);
3449
- break;
3450
- case "text_measurement":
3451
- applyTextMeasurementRule(rule, node, graph, parentId);
3452
- break;
3453
- case "overlay":
3454
- applyOverlayRule(rule, node, graph, parentId);
3455
- break;
3456
- case "connector":
3457
- applyConnectorRule(rule, node, graph);
3458
- break;
3459
- case "fixed_size":
3460
- applyFixedSizeRule(rule, node, graph, parentId);
3461
- break;
3462
- case "grid":
3463
- applyGridRule(rule, node, graph, parentId);
3464
- break;
3465
- default:
3466
- applyStubRule(node, graph, parentId);
3467
- break;
3468
- }
3563
+ };
3469
3564
  }
3470
3565
 
3471
3566
  // src/compiler/compiler.ts
3567
+ import ts from "typescript";
3472
3568
  function isParamRef(v) {
3473
3569
  return typeof v === "object" && v !== null && v.__paramRef === true;
3474
3570
  }
@@ -5428,6 +5524,7 @@ function createGraph() {
5428
5524
  dependencies: [],
5429
5525
  parentMap: /* @__PURE__ */ new Map(),
5430
5526
  nodeKindMap: /* @__PURE__ */ new Map(),
5527
+ irNodeMap: /* @__PURE__ */ new Map(),
5431
5528
  childrenOrderMap: /* @__PURE__ */ new Map(),
5432
5529
  diagnostics: []
5433
5530
  };
@@ -5448,16 +5545,19 @@ function evaluate(graph, ir) {
5448
5545
  return { artifact, diagnostics };
5449
5546
  }
5450
5547
  function buildFragments(graph, node, parentId) {
5451
- const factory = FRAGMENT_MAP[node.kind];
5452
- if (factory) {
5453
- factory(node, graph, parentId);
5454
- }
5455
5548
  const nodeId = node.id;
5456
5549
  if (nodeId && !isConstraintKind(node.kind)) {
5457
5550
  graph.nodeKindMap.set(nodeId, node.kind);
5551
+ graph.irNodeMap.set(nodeId, node);
5458
5552
  if (parentId) {
5459
5553
  graph.parentMap.set(nodeId, parentId);
5460
5554
  }
5555
+ }
5556
+ const factory = FRAGMENT_MAP[node.kind];
5557
+ if (factory) {
5558
+ factory(node, graph, parentId);
5559
+ }
5560
+ if (nodeId && !isConstraintKind(node.kind)) {
5461
5561
  addWorldCoordOps(graph, nodeId, parentId);
5462
5562
  }
5463
5563
  if (node.children) {