yuhwa 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +13 -12
  2. package/client.d.ts +9 -1
  3. package/dist/astro.d.ts +2 -2
  4. package/dist/astro.js +8 -1
  5. package/dist/browser.d.ts +11 -5
  6. package/dist/browser.js +27 -7
  7. package/dist/cli.js +602 -44
  8. package/dist/editor/assets/index-BGtCSg84.js +689 -0
  9. package/dist/editor/assets/lsp.worker-DUpBJRU2.js +26 -0
  10. package/dist/editor/index.html +5 -4
  11. package/dist/figure-db587hh6.d.ts +48 -0
  12. package/dist/{index-Dl845tUQ.d.ts → index-CAO4FUcz.d.ts} +48 -7
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +1 -1
  15. package/dist/ironmark.d.ts +4 -2
  16. package/dist/ironmark.js +18 -7
  17. package/dist/llms.txt +12 -8
  18. package/dist/lsp-browser.d.ts +2 -2
  19. package/dist/lsp-browser.js +1 -1
  20. package/dist/lsp-node.js +40 -182
  21. package/dist/lsp-server.d.ts +1 -1
  22. package/dist/lsp-server.js +1 -1
  23. package/dist/lsp.d.ts +1 -1
  24. package/dist/lsp.js +1 -1
  25. package/dist/markdown-it.d.ts +2 -1
  26. package/dist/markdown-it.js +7 -6
  27. package/dist/node-DPojgovD.js +224 -0
  28. package/dist/remark.d.ts +2 -1
  29. package/dist/remark.js +16 -5
  30. package/dist/{server-DJC_fQMe.d.ts → server-BSHSx8uo.d.ts} +2 -2
  31. package/dist/{server-DmQuHQrG.js → server-CT_mbBNZ.js} +1 -1
  32. package/dist/{service-BYS9Qfkq.js → service-CNM6Z-RH.js} +81 -16
  33. package/dist/{service-ClZ8clSQ.d.ts → service-DquYYTVG.d.ts} +1 -1
  34. package/dist/{shared-qo_r6RUN.js → shared-B2rP00uA.js} +2292 -429
  35. package/dist/{src-wk7tBpWs.js → src-hrqH-a8K.js} +2094 -407
  36. package/dist/style.css +14 -0
  37. package/dist/vite.d.ts +1 -1
  38. package/dist/vite.js +19 -12
  39. package/dist/vuepress.d.ts +3 -1
  40. package/dist/vuepress.js +7 -2
  41. package/dist/yuhwa.iife.js +90 -65
  42. package/dist/zoom-CCSUbX1X.d.ts +49 -0
  43. package/dist/zoom-QeqB6QlH.js +275 -0
  44. package/dist/zoom-script-CVdAzMhX.js +51 -0
  45. package/dist/zoom.d.ts +35 -0
  46. package/dist/zoom.js +19 -0
  47. package/package.json +10 -2
  48. package/dist/editor/assets/index-BQLsumas.js +0 -587
  49. package/dist/editor/assets/lsp.worker-RlPj9blG.js +0 -26
  50. package/dist/figure-BZHIKnxv.d.ts +0 -27
  51. package/dist/node-Bneu5eJV.js +0 -108
@@ -679,7 +679,8 @@ function parseInline(s) {
679
679
  const plain = (segs) => segs.map((x) => x.text).join("");
680
680
  /** Remove the common leading whitespace of the non-empty lines. */
681
681
  function dedent(lines) {
682
- const ind = Math.min(...lines.filter((l) => l.trim()).map((l) => l.match(/^[ \t]*/)[0].length));
682
+ let ind = 1e400;
683
+ for (const l of lines) if (l.trim()) ind = Math.min(ind, l.match(/^[ \t]*/)[0].length);
683
684
  const cut = Number.isFinite(ind) ? ind : 0;
684
685
  while (lines.length && !lines[0].trim()) lines.shift();
685
686
  while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
@@ -752,7 +753,7 @@ function tspans(segs, col, theme, muted = false) {
752
753
  }).join("");
753
754
  }
754
755
  // src/core/style.ts
755
- const num = (v, d) => {
756
+ const num$1 = (v, d) => {
756
757
  const n = v === void 0 ? NaN : parseFloat(v);
757
758
  return Number.isFinite(n) ? n : d;
758
759
  };
@@ -773,17 +774,25 @@ function lineStyle(p, key = "border-style") {
773
774
  */
774
775
  function withEdgeInk(t, p) {
775
776
  const color = resolveColor(p["edge-color"], t, t.dark ? 400 : 500);
776
- const width = num(p["edge-width"], NaN);
777
- if (!color && !(width > 0)) return t;
777
+ const width = edgeWidthOf(p);
778
+ if (!color && !width) return t;
778
779
  const out = Object.create(t);
779
780
  if (color) out.edge = {
780
781
  ...t.edge,
781
782
  stroke: color,
782
783
  ink: color
783
784
  };
784
- if (width > 0) out.edgeWidth = width;
785
+ if (width) out.edgeWidth = width;
785
786
  return out;
786
787
  }
788
+ /**
789
+ * `edge-width` when written, else undefined: for a panel whose lines are
790
+ * thinner than the theme's edges unless the author asks for more
791
+ */
792
+ function edgeWidthOf(p) {
793
+ const w = num$1(p["edge-width"], NaN);
794
+ return w > 0 ? w : void 0;
795
+ }
787
796
  /** Merge class props then own props (own wins). */
788
797
  function effectiveProps(d, decl) {
789
798
  const out = {};
@@ -801,7 +810,7 @@ function dashFor(style, width) {
801
810
  function resolveNodeStyle(d, n, p, theme) {
802
811
  const s = d.settings;
803
812
  const tone = p.color ? theme.tone(p.color) : void 0;
804
- const strokeWidth = num(p.border ?? p["stroke-width"], num(s["stroke-width"], theme.strokeWidth));
813
+ const strokeWidth = num$1(p.border ?? p["stroke-width"], num$1(s["stroke-width"], theme.strokeWidth));
805
814
  const fill = resolveColor(p.fill, theme, theme.dark ? 900 : 100) ?? tone?.fill ?? theme.node.fill;
806
815
  const stroke = resolveColor(p.stroke, theme, 500) ?? tone?.stroke ?? theme.node.stroke;
807
816
  const text = resolveColor(p.text, theme, theme.dark ? 100 : 800) ?? tone?.text ?? theme.node.text;
@@ -812,12 +821,12 @@ function resolveNodeStyle(d, n, p, theme) {
812
821
  sub: resolveColor(p["sub-color"], theme, 500) ?? (tone ? text : theme.node.sub),
813
822
  strokeWidth,
814
823
  dash: dashFor(lineStyle(p), strokeWidth),
815
- radius: num(p.radius, num(s.radius, theme.radius)),
816
- fontSize: num(p["font-size"], num(s["font-size"], theme.fontSize)),
817
- fontWeight: bool(p.bold, false) ? 650 : num(p["font-weight"], 500),
824
+ radius: num$1(p.radius, num$1(s.radius, theme.radius)),
825
+ fontSize: num$1(p["font-size"], num$1(s["font-size"], theme.fontSize)),
826
+ fontWeight: bool(p.bold, false) ? 650 : num$1(p["font-weight"], 500),
818
827
  italic: bool(p.italic, false),
819
828
  shadow: bool(p.shadow, bool(s.shadow, theme.shadow !== null)),
820
- opacity: num(p.opacity, 1)
829
+ opacity: num$1(p.opacity, 1)
821
830
  };
822
831
  }
823
832
  function resolveGroupStyle(g, theme) {
@@ -866,9 +875,9 @@ function resolvePanelStyle(p, T, base) {
866
875
  fill,
867
876
  stroke: noBorder ? "none" : resolveColor(p.stroke ?? borderColor, T, 300) ?? tone?.stroke ?? T.group.stroke,
868
877
  text: resolveColor(p.text, T, T.dark ? 200 : 700) ?? tone?.text ?? T.title,
869
- width: num(p["border-width"], border && !borderColor && !noBorder ? num(border, 1) : 1),
878
+ width: num$1(p["border-width"], border && !borderColor && !noBorder ? num$1(border, 1) : 1),
870
879
  dash: borderDash(p, null),
871
- radius: num(p.radius, Math.min(14, T.radius + 4)),
880
+ radius: num$1(p.radius, Math.min(14, T.radius + 4)),
872
881
  shadow: bool(p.shadow, false)
873
882
  };
874
883
  }
@@ -876,7 +885,7 @@ function resolveEdgeStyle(d, e, p, theme, defaultCurve) {
876
885
  const toneColor = p.color ? theme.edgeTone(p.color) ?? resolveColor(p.color, theme, 500) : void 0;
877
886
  const stroke = resolveColor(p.stroke, theme, theme.dark ? 400 : 500) ?? toneColor ?? theme.edge.stroke;
878
887
  const base = e.line === "thick" || bool(p.thick, false) ? theme.edgeWidth * 2 : theme.edgeWidth;
879
- const width = num(p.width, base);
888
+ const width = num$1(p.width, base);
880
889
  const line = lineStyle(p, "style") ?? (e.line === "dashed" || e.line === "dotted" ? e.line : void 0);
881
890
  const curve = [
882
891
  "smooth",
@@ -892,7 +901,7 @@ function resolveEdgeStyle(d, e, p, theme, defaultCurve) {
892
901
  text: resolveColor(p["label-color"], theme, 700) ?? (toneColor && !theme.dark ? resolveColor(p.color, theme, 700) : theme.edge.text),
893
902
  labelBg: resolveColor(p["label-bg"], theme, theme.dark ? 900 : 50) ?? theme.edge.labelBg,
894
903
  flow,
895
- opacity: num(p.opacity, 1)
904
+ opacity: num$1(p.opacity, 1)
896
905
  };
897
906
  }
898
907
  // src/core/route.ts
@@ -944,12 +953,27 @@ function autoSide(box, target, other, dir) {
944
953
  if (hgap >= vgap) return dx >= 0 ? "right" : "left";
945
954
  return dy >= 0 ? "bottom" : "top";
946
955
  }
956
+ const OPPOSITE = {
957
+ left: "right",
958
+ right: "left",
959
+ top: "bottom",
960
+ bottom: "top"
961
+ };
947
962
  /** Facing side on the other axis, e.g. right -> top/bottom towards the target. */
948
963
  function altSide(box, target, s) {
949
964
  const c = center(box);
950
965
  if (s === "left" || s === "right") return target.y >= c.y ? "bottom" : "top";
951
966
  return target.x >= c.x ? "right" : "left";
952
967
  }
968
+ /** `s`, the facing side on the other axis, and the far side too: two top ports arc over what sits between */
969
+ function turns(s, box, to) {
970
+ const alt = altSide(box, to, s);
971
+ return [
972
+ s,
973
+ alt,
974
+ OPPOSITE[alt]
975
+ ];
976
+ }
953
977
  /** Pick the side combination whose provisional curve crosses the fewest other nodes. */
954
978
  function avoidObstacles(a, b, s0, s1, free0, free1, obstacles) {
955
979
  const m = 80;
@@ -963,11 +987,15 @@ function avoidObstacles(a, b, s0, s1, free0, free1, obstacles) {
963
987
  };
964
988
  const others = obstacles.filter((o) => o !== a && o !== b && hits(o, near));
965
989
  if (!others.length) return [s0, s1];
966
- const c0 = free0 ? [s0, altSide(a, center(b), s0)] : [s0];
967
- const c1 = free1 ? [s1, altSide(b, center(a), s1)] : [s1];
968
- let best = [s0, s1];
969
- let bestCost = 1e400;
970
- for (const x of c0) for (const y of c1) {
990
+ const c0 = free0 ? turns(s0, a, center(b)) : [s0];
991
+ const c1 = free1 ? turns(s1, b, center(a)) : [s1];
992
+ const pairs = c0.flatMap((x) => c1.map((y) => [x, y]));
993
+ const changes = ([x, y]) => +(x !== s0) + +(y !== s1);
994
+ pairs.sort((p, q) => changes(p) - changes(q));
995
+ let best = pairs[0];
996
+ let bestHits = 1e400;
997
+ for (const pair of pairs) {
998
+ const [x, y] = pair;
971
999
  const S = portPoint(a.shape, a, x, 0);
972
1000
  const E = portPoint(b.shape, b, y, 0);
973
1001
  const pts = sample({
@@ -976,11 +1004,8 @@ function avoidObstacles(a, b, s0, s1, free0, free1, obstacles) {
976
1004
  });
977
1005
  let hits = 0;
978
1006
  for (const o of others) if (pts.some((p) => p.x > o.x + 2 && p.x < o.x + o.w - 2 && p.y > o.y + 2 && p.y < o.y + o.h - 2)) hits++;
979
- const cost = hits * 1e3 + (x !== s0 ? 40 : 0) + (y !== s1 ? 40 : 0);
980
- if (cost < bestCost) {
981
- bestCost = cost;
982
- best = [x, y];
983
- }
1007
+ if (!hits) return pair;
1008
+ if (hits < bestHits) [best, bestHits] = [pair, hits];
984
1009
  }
985
1010
  return best;
986
1011
  }
@@ -1108,7 +1133,16 @@ function buildEdge(it, ctx) {
1108
1133
  E = portPoint(b.shape, b, it.sides[1], it.t[1]);
1109
1134
  const n0 = SIDE_NORMAL[it.sides[0]];
1110
1135
  const n1 = SIDE_NORMAL[it.sides[1]];
1111
- if (style.curve === "orthogonal") geo = {
1136
+ if (ctx.channels?.has(it.e.key) && it.via.length >= 2) {
1137
+ const via = it.via.map((q) => ({ ...q }));
1138
+ via[0].y = S.y;
1139
+ via[via.length - 1].y = E.y;
1140
+ geo = {
1141
+ kind: "poly",
1142
+ pts: orthoRoute(S, n0, E, n1, via, a, b, ctx.obstacles),
1143
+ radius: 10
1144
+ };
1145
+ } else if (style.curve === "orthogonal") geo = {
1112
1146
  kind: "poly",
1113
1147
  pts: orthoRoute(S, n0, E, n1, it.via, a, b, ctx.obstacles),
1114
1148
  radius: 10
@@ -1807,6 +1841,18 @@ const SIDES$1 = [
1807
1841
  "left",
1808
1842
  "auto"
1809
1843
  ];
1844
+ /**
1845
+ * Node props that place a node next to another one: the value is that node's
1846
+ * id. `below`/`above`/`right-of`/`left-of` are screen directions, whatever the
1847
+ * diagram's `direction`; `rank` puts the node in the other node's rank.
1848
+ */
1849
+ const PLACEMENT_PROPS = [
1850
+ "below",
1851
+ "above",
1852
+ "right-of",
1853
+ "left-of",
1854
+ "rank"
1855
+ ];
1810
1856
  const NODE_PROPS = [
1811
1857
  "shape",
1812
1858
  "color",
@@ -1835,7 +1881,8 @@ const NODE_PROPS = [
1835
1881
  "meta",
1836
1882
  "caps",
1837
1883
  "mono",
1838
- "max-width"
1884
+ "max-width",
1885
+ ...PLACEMENT_PROPS
1839
1886
  ];
1840
1887
  const EDGE_PROPS = [
1841
1888
  "style",
@@ -1944,17 +1991,23 @@ function distance(a, b) {
1944
1991
  }
1945
1992
  return dp[b.length];
1946
1993
  }
1947
- /** " (did you mean "x"?)" for a close match, else "" */
1948
- function didYouMean(v, options) {
1994
+ /** the option nearest to `v` and its edit distance, ignoring case */
1995
+ function closest(v, options) {
1996
+ const lv = v.toLowerCase();
1949
1997
  let best = "";
1950
1998
  let bestD = 1e400;
1951
1999
  for (const o of options) {
1952
- const dd = distance(v.toLowerCase(), o);
2000
+ const dd = distance(lv, o.toLowerCase());
1953
2001
  if (dd < bestD) [best, bestD] = [o, dd];
1954
2002
  }
2003
+ return [best, bestD];
2004
+ }
2005
+ /** " (did you mean "x"?)" for a close match, else "" */
2006
+ function didYouMean(v, options) {
2007
+ const [best, bestD] = closest(v, options);
1955
2008
  return bestD <= (v.length <= 3 ? 1 : Math.max(2, Math.floor(v.length / 3))) ? ` (did you mean "${best}"?)` : "";
1956
2009
  }
1957
- function checkProps(props, allowed, what, line0, warn, propLines) {
2010
+ function checkProps$1(props, allowed, what, line0, warn, propLines) {
1958
2011
  for (const [k, v] of Object.entries(props)) {
1959
2012
  const line = propLines?.[k] ?? line0;
1960
2013
  if (!allowed.includes(k)) {
@@ -1973,22 +2026,112 @@ function checkProps(props, allowed, what, line0, warn, propLines) {
1973
2026
  else if (k === "link" && !isSafeLink(v)) warn(line, `link "${v}" is not rendered: use http(s), mailto, an #anchor or a relative path`);
1974
2027
  }
1975
2028
  }
1976
- function lint(d) {
2029
+ /** a panel's own header props against the types its `options` declare */
2030
+ function checkPanelOptions(props, options, line, warn) {
2031
+ if (!options) return;
2032
+ for (const [k, v] of Object.entries(props)) {
2033
+ const o = options[k];
2034
+ if (o === void 0 || o === "text") continue;
2035
+ if (o === "color") {
2036
+ if (!isColor(v)) warn(line, `Unknown ${k} "${v}"${didYouMean(v, TONES) || ": use a palette name, #hex, rgb(), hsl() or a CSS colour name"}`);
2037
+ } else if (o === "number") {
2038
+ if (!Number.isFinite(parseFloat(v))) warn(line, `${k} expects a number, got "${v}"`);
2039
+ } else if (o === "flag") {
2040
+ if (!["true", "false"].includes(v)) warn(line, `${k} expects true or false, got "${v}"`);
2041
+ } else if (!o.includes(v.toLowerCase())) warn(line, `Unknown ${k} "${v}"${didYouMean(v, [...o]) || ` (use one of: ${o.join(", ")})`}`);
2042
+ }
2043
+ }
2044
+ /**
2045
+ * The placement prop a node uses (the first one written) and its anchor id.
2046
+ * Layout reads the same choice, so the warnings below describe what it does.
2047
+ */
2048
+ function placementOf(props) {
2049
+ for (const [k, v] of Object.entries(props)) if (PLACEMENT_PROPS.includes(k) && v) return [k, v.trim()];
2050
+ }
2051
+ /** placement props: the anchor must be another node, one prop per node, no loops */
2052
+ function checkPlacement(d, warn) {
2053
+ const anchor = /* @__PURE__ */ new Map();
2054
+ for (const n of d.nodes.values()) {
2055
+ const p = effectiveProps(d, n);
2056
+ const used = placementOf(p);
2057
+ if (!used) continue;
2058
+ const at = (k) => n.ref?.propLines?.[k] ?? n.ref?.line;
2059
+ const [key, id] = used;
2060
+ const line = at(key);
2061
+ for (const k of Object.keys(p)) if (k !== key && PLACEMENT_PROPS.includes(k) && n.ref) warn(at(k), `${n.id} already has ${key}: ${id}, so ${k} is ignored. A node takes one placement prop`);
2062
+ if (id === n.id) {
2063
+ if (n.ref) warn(line, `${key}: ${id} places ${n.id} next to itself; use another node's id`);
2064
+ continue;
2065
+ }
2066
+ if (!d.nodes.has(id)) {
2067
+ if (!n.ref) continue;
2068
+ if (d.groups.has(id)) warn(line, `${key}: ${id} names a group; placement takes a node id`);
2069
+ else warn(line, `${key}: unknown node "${id}"${didYouMean(id, [...d.nodes.keys()])}`);
2070
+ continue;
2071
+ }
2072
+ anchor.set(n.id, id);
2073
+ }
2074
+ const reported = /* @__PURE__ */ new Set();
2075
+ for (const start of anchor.keys()) {
2076
+ const chain = [];
2077
+ let cur = start;
2078
+ while (cur !== void 0 && !chain.includes(cur)) {
2079
+ chain.push(cur);
2080
+ cur = anchor.get(cur);
2081
+ }
2082
+ if (cur !== start || reported.has(start)) continue;
2083
+ chain.forEach((id) => reported.add(id));
2084
+ const n = d.nodes.get(start);
2085
+ const key = placementOf(effectiveProps(d, n))[0];
2086
+ if (n.ref) warn(n.ref.propLines?.[key] ?? n.ref.line, `placement loop: ${[...chain, start].join(" → ")}. These nodes cannot all be placed; remove one placement prop`);
2087
+ }
2088
+ }
2089
+ /** ids that differ only in their numbers (`s1`, `s2`) are a series, not a typo */
2090
+ const series = (id) => id.toLowerCase().replace(/\d+/g, "#");
2091
+ /**
2092
+ * A node that only an edge mentions, while a declared node has an id one or
2093
+ * two edits away, is almost always a typo: `api -> dbb` next to `db "Postgres"`
2094
+ * draws a second, unlabelled box. Short ids are skipped (`a`, `b` are a series).
2095
+ */
2096
+ function checkNodeTypos(d, warn) {
2097
+ const nodes = [...d.nodes.values()];
2098
+ const declared = nodes.filter((n) => !n.implicit).map((n) => ({
2099
+ id: n.id,
2100
+ series: series(n.id)
2101
+ }));
2102
+ if (!declared.length || nodes.every((n) => !n.implicit || n.id.length < 3)) return;
2103
+ const edgeLine = /* @__PURE__ */ new Map();
2104
+ for (const e of d.edges) if (e.ref) {
2105
+ for (const id of [e.from, e.to]) if (!edgeLine.has(id)) edgeLine.set(id, e.ref.line);
2106
+ }
2107
+ for (const n of nodes) {
2108
+ const line = edgeLine.get(n.id);
2109
+ if (!n.implicit || n.id.length < 3 || line === void 0) continue;
2110
+ const s = series(n.id);
2111
+ const max = n.id.length < 7 ? 1 : 2;
2112
+ const options = declared.filter((o) => o.series !== s && Math.abs(o.id.length - n.id.length) <= max);
2113
+ const [best, bestD] = closest(n.id, options.map((o) => o.id));
2114
+ if (bestD <= max) warn(line, `Node "${n.id}" is only used in edges (did you mean "${best}"?). If it is a separate node, declare it: ${n.id} "Label"`);
2115
+ }
2116
+ }
2117
+ function lint(d, panelOptions) {
1977
2118
  const warn = (line, message) => d.diagnostics.push({
1978
2119
  line: line + 1,
1979
2120
  message,
1980
2121
  severity: "warning"
1981
2122
  });
1982
- for (const n of d.nodes.values()) if (n.ref) checkProps(n.props, NODE_PROPS, "node", n.ref.line, warn, n.ref.propLines);
2123
+ for (const n of d.nodes.values()) if (n.ref) checkProps$1(n.props, NODE_PROPS, "node", n.ref.line, warn, n.ref.propLines);
2124
+ checkPlacement(d, warn);
1983
2125
  const seen = /* @__PURE__ */ new Set();
1984
2126
  for (const e of d.edges) {
1985
2127
  if (!e.ref) continue;
1986
2128
  const line = e.ref.line;
1987
2129
  if (seen.has(line)) continue;
1988
2130
  seen.add(line);
1989
- checkProps(e.props, EDGE_PROPS, "edge", line, warn, e.ref.propLines);
2131
+ checkProps$1(e.props, EDGE_PROPS, "edge", line, warn, e.ref.propLines);
1990
2132
  }
1991
- for (const g of d.groups.values()) if (g.ref) checkProps(g.props, GROUP_PROPS, "group", g.ref.line, warn, g.ref.propLines);
2133
+ for (const g of d.groups.values()) if (g.ref) checkProps$1(g.props, GROUP_PROPS, "group", g.ref.line, warn, g.ref.propLines);
2134
+ checkNodeTypos(d, warn);
1992
2135
  const names = themeNames(d.themes);
1993
2136
  for (const p of d.panels) {
1994
2137
  if (!p.ref) continue;
@@ -2005,6 +2148,7 @@ function lint(d) {
2005
2148
  const b = pp.border;
2006
2149
  if (b && !["none", "false"].includes(b) && !isColor(b) && !Number.isFinite(parseFloat(b))) warn(line, `border takes a colour, a width or none, got "${b}"`);
2007
2150
  if (pp["border-style"] && !LINE_STYLES.includes(pp["border-style"])) warn(line, `Unknown border-style "${pp["border-style"]}" (use one of: ${LINE_STYLES.join(", ")})`);
2151
+ checkPanelOptions(pp, panelOptions?.(p.kind), line, warn);
2008
2152
  }
2009
2153
  const any = [.../* @__PURE__ */ new Set([
2010
2154
  ...NODE_PROPS,
@@ -2013,10 +2157,42 @@ function lint(d) {
2013
2157
  ])];
2014
2158
  for (const [c, props] of Object.entries(d.classes)) {
2015
2159
  const line = d.classLines?.[c];
2016
- if (line !== void 0) checkProps(props, any, `class .${c}`, line, warn);
2160
+ if (line !== void 0) checkProps$1(props, any, `class .${c}`, line, warn);
2017
2161
  }
2018
2162
  d.diagnostics.sort((a, b) => a.line - b.line);
2019
2163
  }
2164
+ // src/core/guard.ts
2165
+ let sink = null;
2166
+ /** run `fn` with plugin failures reported into `diags` */
2167
+ function collecting(diags, fn) {
2168
+ const prev = sink;
2169
+ sink = diags;
2170
+ try {
2171
+ return fn();
2172
+ } finally {
2173
+ sink = prev;
2174
+ }
2175
+ }
2176
+ /** record a plugin failure once per diagram */
2177
+ function reportPluginError(plugin, what, e, line = 1) {
2178
+ const message = `plugin "${plugin}": ${what} failed: ${e instanceof Error ? e.message : String(e)}`;
2179
+ if (sink && !sink.some((d) => d.message === message)) sink.push({
2180
+ line,
2181
+ message,
2182
+ severity: "error"
2183
+ });
2184
+ }
2185
+ /** `fn`, but a throw reports and returns `fallback(...args)` */
2186
+ function guard(plugin, what, fn, fallback) {
2187
+ return function(...args) {
2188
+ try {
2189
+ return fn.apply(this, args);
2190
+ } catch (e) {
2191
+ reportPluginError(plugin, what, e);
2192
+ return fallback(...args);
2193
+ }
2194
+ };
2195
+ }
2020
2196
  // src/core/parse.ts
2021
2197
  const THEME_KEY_NAMES = Object.keys(THEME_KEYS);
2022
2198
  const KNOWN_SETTINGS = /* @__PURE__ */ new Set([
@@ -2028,6 +2204,7 @@ const KNOWN_SETTINGS = /* @__PURE__ */ new Set([
2028
2204
  "curve",
2029
2205
  "gap",
2030
2206
  "rank-gap",
2207
+ "max-width",
2031
2208
  "font",
2032
2209
  "font-size",
2033
2210
  "background",
@@ -2055,7 +2232,9 @@ const PANEL_ALIASES = {
2055
2232
  quadrantChart: "quadrant ID",
2056
2233
  mindMap: "mindmap ID",
2057
2234
  roadmap: "gantt ID",
2058
- board: "kanban ID"
2235
+ board: "kanban ID",
2236
+ tree: "treeview ID",
2237
+ filetree: "treeview ID"
2059
2238
  };
2060
2239
  /** panel kinds by keyword, filled by `use` (see plugin.ts) */
2061
2240
  const PANELS = /* @__PURE__ */ new Map();
@@ -2099,10 +2278,10 @@ const CURVES = /* @__PURE__ */ new Set([
2099
2278
  ]);
2100
2279
  const isShape = (k) => SHAPES$2.includes(k) || k in SHAPE_ALIASES || SHAPE_KINDS.has(k);
2101
2280
  /**
2102
- * Imports only read `.yuhwa` files: a diagram must not pull other files
2281
+ * Imports only read `.yu` (or the older `.yuhwa`) files: a diagram must not pull other files
2103
2282
  * (keys, configs) into its output or errors, whatever the resolver.
2104
2283
  */
2105
- const isYuhwaPath = (path) => /\.yuhwa$/i.test(path);
2284
+ const isYuhwaPath = (path) => /\.(yu|yuhwa)$/i.test(path);
2106
2285
  /** Join an import path to the importing file's folder and normalise `.`/`..`. */
2107
2286
  function joinPath(from, rel) {
2108
2287
  if (/^[a-z][a-z0-9+.-]*:/i.test(rel)) return rel;
@@ -2332,14 +2511,14 @@ function parseProps(raw = "") {
2332
2511
  return out;
2333
2512
  }
2334
2513
  /** a `[props]` group ending a line; `[[x]]` (an inline chip) is not one */
2335
- const TRAILING_PROPS = /\s*(?<!\[)\[([^[\]]*)\]\s*$/;
2514
+ const TRAILING_PROPS$1 = /\s*(?<!\[)\[([^[\]]*)\]\s*$/;
2336
2515
  /**
2337
2516
  * `text [props]` → the text before the bracket and its props. `accept` may
2338
2517
  * refuse a bracket (it then stays part of the text), e.g. one whose keys
2339
2518
  * the statement does not know.
2340
2519
  */
2341
2520
  function splitTrailingProps(text, accept) {
2342
- const m = text.match(TRAILING_PROPS);
2521
+ const m = text.match(TRAILING_PROPS$1);
2343
2522
  const p = m ? parseProps(m[1]) : void 0;
2344
2523
  return p && (!accept || accept(p)) ? [text.slice(0, m.index), p] : [text, {}];
2345
2524
  }
@@ -2525,7 +2704,7 @@ function parse(source, opts = {}) {
2525
2704
  const importFile = (rel, li, names) => {
2526
2705
  if (!opts.resolve) return warn(li, `Cannot import "${rel}": no resolver (pass { resolve } to render, or use the CLI)`, "error");
2527
2706
  const path = joinPath(opts.file, rel);
2528
- if (!isYuhwaPath(path)) return warn(li, `Cannot import "${rel}": imports must be .yuhwa files`, "error");
2707
+ if (!isYuhwaPath(path)) return warn(li, `Cannot import "${rel}": imports must be .yu files`, "error");
2529
2708
  const chain = [...opts.chain ?? (opts.file ? [opts.file] : [])];
2530
2709
  if (chain.includes(path)) return warn(li, `Import cycle: ${[...chain, path].join(" -> ")}`, "error");
2531
2710
  const key = names ? `${path}{${names.map((n) => n.join(" as ")).join(",")}}` : path;
@@ -2553,6 +2732,7 @@ function parse(source, opts = {}) {
2553
2732
  };
2554
2733
  const vars = d.vars = {};
2555
2734
  const defs = d.defs = {};
2735
+ const used = d.used = /* @__PURE__ */ new Set();
2556
2736
  SCOPE.set(defs, defs);
2557
2737
  /** set while a line comes from a variable or a component: refs then carry `generated` */
2558
2738
  let gen = false;
@@ -2567,6 +2747,7 @@ function parse(source, opts = {}) {
2567
2747
  const name = braced ?? bare;
2568
2748
  if (!name) return "$";
2569
2749
  const value = local?.[name] ?? vars[name];
2750
+ if (local?.[name] === void 0 && value !== void 0) used.add("$" + name);
2570
2751
  if (value !== void 0) return value;
2571
2752
  if (!quiet) warn(li, `Unknown variable "$${name}"${didYouMean(name, [...Object.keys(local ?? {}), ...Object.keys(vars)])}`);
2572
2753
  return all;
@@ -2621,6 +2802,7 @@ function parse(source, opts = {}) {
2621
2802
  SCOPE.set(def, scope);
2622
2803
  if (defs[def.name]) warn(top.start, `Component "${def.name}" is defined twice`);
2623
2804
  defs[def.name] = def;
2805
+ (d.defLines ??= {})[def.name] = top.start;
2624
2806
  return;
2625
2807
  }
2626
2808
  const verbatim = top?.kind === "body" || top?.kind === "panel";
@@ -2628,6 +2810,7 @@ function parse(source, opts = {}) {
2628
2810
  const v = raw0.match(VAR_DEF_RE);
2629
2811
  if (v) {
2630
2812
  vars[v[1]] = unquote((done ? v[2] : substitute(v[2], li)).replace(/\s+\/\/.*$/, ""));
2813
+ (d.varLines ??= {})[v[1]] = li;
2631
2814
  return;
2632
2815
  }
2633
2816
  const h = raw0.match(DEF_RE);
@@ -2654,7 +2837,11 @@ function parse(source, opts = {}) {
2654
2837
  const c = raw0.replace(/\s+\/\/.*$/, "").match(CALL_RE);
2655
2838
  if (c) {
2656
2839
  const def = scope[c[1]] ?? defs[c[1]];
2657
- if (def) return void expand(def, done ? c[2] : substitute(c[2], li), li);
2840
+ if (def) {
2841
+ used.add(c[1]);
2842
+ expand(def, done ? c[2] : substitute(c[2], li), li);
2843
+ return;
2844
+ }
2658
2845
  if (!lex(raw0).tokens.some((x) => x.kind === "arrow")) return void warn(li, `Unknown component "${c[1]}"${didYouMean(c[1], Object.keys(defs))}`, "error");
2659
2846
  }
2660
2847
  }
@@ -2677,13 +2864,17 @@ function parse(source, opts = {}) {
2677
2864
  const panelLine = (top, raw, li) => {
2678
2865
  if (raw.trim() === "}") {
2679
2866
  stack.pop();
2680
- const p = top.panel;
2681
- const lead = top.lines.findIndex((l) => l.trim());
2682
- p.body = dedent(top.lines);
2683
- p.lines = [top.start, li];
2684
- p.data = PANELS.get(p.kind).parse(p.body, p.props, (i, msg) => warn(i < 0 ? top.start : top.start + 1 + Math.max(0, lead) + i, msg));
2867
+ closePanel(top, li);
2685
2868
  } else top.lines.push(raw.slice(0, lex(raw).codeEnd).trimEnd());
2686
2869
  };
2870
+ /** hand a panel's body to its plugin; `end` is the line of its "}" (or the last line when it is missing) */
2871
+ const closePanel = (top, end) => {
2872
+ const p = top.panel;
2873
+ const lead = top.lines.findIndex((l) => l.trim());
2874
+ p.body = dedent(top.lines);
2875
+ p.lines = [top.start, end];
2876
+ p.data = PANELS.get(p.kind).parse(p.body, p.props, ((i, msg, sev) => warn(i < 0 ? top.start : top.start + 1 + Math.max(0, lead) + i, msg, sev)));
2877
+ };
2687
2878
  /** theme body: `key: value` lines */
2688
2879
  const themeBodyLine = (top, raw, li) => {
2689
2880
  const code = raw.slice(0, lex(raw).codeEnd).trim();
@@ -2713,10 +2904,10 @@ function parse(source, opts = {}) {
2713
2904
  else stack.pop();
2714
2905
  lastDecl = null;
2715
2906
  };
2716
- /** import "./shared.yuhwa" | import { api, db as store, .svc } from "./shared.yuhwa" */
2907
+ /** import "./shared.yu" | import { api, db as store, .svc } from "./shared.yu" */
2717
2908
  const importStmt = (t, li, selective) => {
2718
2909
  if (stack.length) warn(li, "import must be at the top level", "error");
2719
- else if (!t[1]) warn(li, "import needs a path: import \"./shared.yuhwa\"", "error");
2910
+ else if (!t[1]) warn(li, "import needs a path: import \"./shared.yu\"", "error");
2720
2911
  else if (!selective) {
2721
2912
  if (t.length > 2) warn(li, `Unexpected "${t[2].value}" after import path`, "error");
2722
2913
  importFile(t[1].value, li);
@@ -3054,8 +3245,10 @@ function parse(source, opts = {}) {
3054
3245
  for (let li = 0; li < lines.length; li++) step(lines[li], li);
3055
3246
  for (const ctx of stack) if (ctx.kind === "group") warn(lines.length - 1, `Group "${ctx.id}" is missing "}"`, "error");
3056
3247
  else if (ctx.kind === "body") warn(ctx.start, `Body of "${ctx.id}" is missing a closing "}" line`, "error");
3057
- else if (ctx.kind === "panel") warn(ctx.start, `${ctx.panel.kind} "${ctx.id}" is missing a closing "}" line`, "error");
3058
- else if (ctx.kind === "def") warn(ctx.start, `def ${ctx.id}() is missing "}"`, "error");
3248
+ else if (ctx.kind === "panel") {
3249
+ warn(ctx.start, `${ctx.panel.kind} "${ctx.id}" is missing a closing "}" line`, "error");
3250
+ closePanel(ctx, lines.length - 1);
3251
+ } else if (ctx.kind === "def") warn(ctx.start, `def ${ctx.id}() is missing "}"`, "error");
3059
3252
  else if (ctx.kind === "theme") warn(ctx.start, `theme ${ctx.id} is missing "}"`, "error");
3060
3253
  else warn(lines.length - 1, "layout block is missing \"}\"", "error");
3061
3254
  const names = themeNames(d.themes);
@@ -3081,6 +3274,7 @@ function parse(source, opts = {}) {
3081
3274
  for (const x of exported) if (!d.exports.includes(x) && !PANELS.has(x) && x !== "group" && x !== "def") warn(0, `export: "${x}" is not declared in this file`);
3082
3275
  }
3083
3276
  for (const p of d.panels) {
3277
+ if (d.nodes.get(p.id)?.implicit) d.nodes.delete(p.id);
3084
3278
  const o = d.layout.nodes[p.id];
3085
3279
  if (!o) continue;
3086
3280
  if (o.x !== void 0 && o.y !== void 0) panelOverride(d, p.id).at = {
@@ -3090,8 +3284,8 @@ function parse(source, opts = {}) {
3090
3284
  delete d.layout.nodes[p.id];
3091
3285
  }
3092
3286
  for (const [id, g] of d.groups) if (d.nodes.has(id)) warn(d.edges.find((e) => e.ref && (e.from === id || e.to === id))?.ref?.line ?? g.ref?.line ?? 0, `"${id}" is both a node and a group. Edges connect nodes, not groups: use a node inside "${id}", or rename one of them`);
3093
- lint(d);
3094
- for (const t of TRANSFORMS) t(d);
3287
+ lint(d, (kind) => PANELS.get(kind)?.options);
3288
+ if (!opts.chain) collecting(d.diagnostics, () => TRANSFORMS.forEach((t) => t(d)));
3095
3289
  for (const id of Object.keys(d.layout.nodes)) {
3096
3290
  const at = layoutLines.get(id);
3097
3291
  if (at !== void 0 && !d.nodes.has(id) && !d.groups.has(id)) warn(at, `layout: there is no node "${id}" (renamed or deleted?); remove this line${didYouMean(id, [...d.nodes.keys()])}`);
@@ -3101,7 +3295,7 @@ function parse(source, opts = {}) {
3101
3295
  /** `import { a, b as c, .svc } from "path"` → names and path, or null after an error */
3102
3296
  function readImportList(t, li, warn) {
3103
3297
  const close = t.findIndex((x) => x.value === "}");
3104
- const fail = (msg) => (warn(li, `${msg}: import { a, b as c, .style } from "./file.yuhwa"`, "error"), null);
3298
+ const fail = (msg) => (warn(li, `${msg}: import { a, b as c, .style } from "./file.yu"`, "error"), null);
3105
3299
  if (close < 0) return fail("import list is missing \"}\"");
3106
3300
  const names = [];
3107
3301
  let k = 2;
@@ -3539,18 +3733,14 @@ function parseLayoutLine(code, li, d, warn) {
3539
3733
  } else return warn(li, `Unknown layout keyword "${kw}"`);
3540
3734
  }
3541
3735
  }
3542
- // src/integrations/node.ts
3543
- /** Node-only helper for the CLI and build-time integrations: `import` reads from disk. */
3544
- /** Reads an `import "..."` target from disk; like `parse`, only `.yuhwa` files. */
3545
- function diskResolve(path) {
3546
- if (!isYuhwaPath(path)) return void 0;
3547
- try {
3548
- return readFileSync(path, "utf8");
3549
- } catch {
3550
- return;
3551
- }
3552
- }
3553
3736
  // src/core/plugin.ts
3737
+ /** what `options[key]` asks for: a select of values, or one kind of field */
3738
+ function optionKind(o) {
3739
+ return typeof o === "string" ? { kind: o } : {
3740
+ kind: "select",
3741
+ values: o
3742
+ };
3743
+ }
3554
3744
  /**
3555
3745
  * `fn` computed once per panel per layout pass: `measure`, `render` and
3556
3746
  * `handles` share one ctx, so a plugin's geometry wrapped in this is worked
@@ -3560,7 +3750,7 @@ function perPass(fn) {
3560
3750
  const cache = /* @__PURE__ */ new WeakMap();
3561
3751
  return (data, ctx) => {
3562
3752
  const hit = cache.get(ctx);
3563
- if (hit?.data === data) return hit.g;
3753
+ if (hit && hit.data === data) return hit.g;
3564
3754
  const g = fn(data, ctx);
3565
3755
  cache.set(ctx, {
3566
3756
  data,
@@ -3594,28 +3784,192 @@ const registry = {
3594
3784
  const addAll = (list, items) => {
3595
3785
  for (const i of items ?? []) if (!list.includes(i)) list.push(i);
3596
3786
  };
3787
+ /** data of a panel whose `parse` threw: measure, render and friends skip it */
3788
+ const FAILED_PANEL = Symbol("yuhwa.failedPanel");
3789
+ const none = () => {};
3790
+ /** copies of a plugin's parts whose every function reports a throw instead of passing it on */
3791
+ function guarded(p) {
3792
+ const n = p.name;
3793
+ const g = (what, fn, fb) => guard(n, what, fn, fb);
3794
+ const opt = (what, fn, fb) => fn && g(what, fn.bind(void 0), fb);
3795
+ const live = (what, fn, fb) => fn && g(what, (data, ...a) => data === FAILED_PANEL ? fb : fn(data, ...a), () => fb);
3796
+ return {
3797
+ rows: (p.rows ?? []).map((r) => ({
3798
+ ...r,
3799
+ parse: g(`row "${r.kind}"`, r.parse.bind(r), () => null),
3800
+ finish: opt(`row "${r.kind}"`, r.finish?.bind(r), none),
3801
+ measure: g(`row "${r.kind}"`, r.measure.bind(r), () => ({
3802
+ w: 0,
3803
+ h: 0
3804
+ })),
3805
+ render: g(`row "${r.kind}"`, r.render.bind(r), () => "")
3806
+ })),
3807
+ frames: (p.frames ?? []).map((fr) => ({
3808
+ ...fr,
3809
+ inset: g(`frame "${fr.name}"`, fr.inset.bind(fr), () => ({ top: 0 })),
3810
+ render: g(`frame "${fr.name}"`, fr.render.bind(fr), () => "")
3811
+ })),
3812
+ decorations: (p.decorations ?? []).map((dc) => ({
3813
+ ...dc,
3814
+ measure: g(`decoration "${dc.name}"`, dc.measure.bind(dc), () => null),
3815
+ render: g(`decoration "${dc.name}"`, dc.render.bind(dc), () => "")
3816
+ })),
3817
+ panels: (p.panels ?? []).map((pk) => {
3818
+ const what = `${pk.name} panel`;
3819
+ return {
3820
+ ...pk,
3821
+ parse(body, props, warn) {
3822
+ try {
3823
+ return pk.parse(body, props, warn);
3824
+ } catch (e) {
3825
+ warn(-1, `plugin "${n}": ${what} failed to parse: ${e instanceof Error ? e.message : String(e)}`, "error");
3826
+ return FAILED_PANEL;
3827
+ }
3828
+ },
3829
+ measure: live(`${what} measure`, pk.measure.bind(pk), {
3830
+ w: 0,
3831
+ h: 0
3832
+ }),
3833
+ render: live(`${what} render`, pk.render.bind(pk), ""),
3834
+ handles: live(`${what} handles`, pk.handles?.bind(pk), []),
3835
+ parts: live(`${what} parts`, pk.parts?.bind(pk), []),
3836
+ editPart: pk.editPart && g(`${what} edit`, (body, edit, data) => data === FAILED_PANEL ? null : pk.editPart(body, edit, data), () => null)
3837
+ };
3838
+ }),
3839
+ statements: (p.statements ?? []).map((st) => ({
3840
+ ...st,
3841
+ parse(args, d, ctx) {
3842
+ try {
3843
+ st.parse(args, d, ctx);
3844
+ } catch (e) {
3845
+ ctx.warn(`plugin "${n}": ${st.keyword} failed: ${e instanceof Error ? e.message : String(e)}`, "error");
3846
+ }
3847
+ }
3848
+ })),
3849
+ shapes: (p.shapes ?? []).map((sh) => ({
3850
+ ...sh,
3851
+ path: g(`shape "${sh.name}"`, sh.path.bind(sh), (b) => `M${b.x},${b.y}h${b.w}v${b.h}h${-b.w}Z`),
3852
+ size: sh.size && g(`shape "${sh.name}"`, (cw, ch) => sh.size(cw, ch), (w, h) => ({
3853
+ w,
3854
+ h
3855
+ })),
3856
+ detail: sh.detail && g(`shape "${sh.name}"`, (b) => sh.detail(b), () => null)
3857
+ })),
3858
+ markers: (p.markers ?? []).map((mk) => ({
3859
+ ...mk,
3860
+ render: g(`marker "${mk.name}"`, mk.render.bind(mk), () => ""),
3861
+ inset: typeof mk.inset === "function" ? g(`marker "${mk.name}"`, mk.inset.bind(mk), () => 0) : mk.inset
3862
+ })),
3863
+ transform: p.transform && g("transform", (d) => p.transform(d), none),
3864
+ afterLayout: p.afterLayout && g("afterLayout", (L, d) => p.afterLayout(L, d), none),
3865
+ postRender: p.postRender && g("postRender", (svg, d, L) => p.postRender(svg, d, L), (svg) => svg)
3866
+ };
3867
+ }
3868
+ /** who registered each panel, statement, shape, marker, frame and row kind */
3869
+ const owners = /* @__PURE__ */ new Map();
3870
+ /** a plugin replacing what another one registered is allowed, but worth a word */
3871
+ function claim(what, name, plugin) {
3872
+ const key = `${what} ${name}`;
3873
+ const prev = owners.get(key);
3874
+ if (prev && prev !== plugin) console.warn(`yuhwa: plugin "${plugin}" replaces ${what} "${name}" of plugin "${prev}"`);
3875
+ owners.set(key, plugin);
3876
+ }
3877
+ /** the tables as they were before the first plugin, so `unuse` can rebuild them */
3878
+ let baseline;
3879
+ function snapshot() {
3880
+ const sets = [KNOWN_SETTINGS].map((s) => [s, [...s]]);
3881
+ const maps = [
3882
+ PANELS,
3883
+ STATEMENTS,
3884
+ SHAPE_KINDS,
3885
+ MARKER_KINDS,
3886
+ registry.frames
3887
+ ].map((m) => [m, [...m]]);
3888
+ const lists = [
3889
+ TRANSFORMS,
3890
+ AFTER_LAYOUT,
3891
+ POST_RENDER,
3892
+ NODE_PROPS,
3893
+ EDGE_PROPS,
3894
+ GROUP_PROPS,
3895
+ BOOLS,
3896
+ NUMBERS,
3897
+ THEME_NAMES,
3898
+ registry.rows,
3899
+ registry.decorations
3900
+ ].map((l) => [l, [...l]]);
3901
+ const enums = Object.entries(ENUMS).map(([k, v]) => [
3902
+ k,
3903
+ v,
3904
+ [...v]
3905
+ ]);
3906
+ const themes = { ...THEMES };
3907
+ return () => {
3908
+ for (const [s, v] of sets) {
3909
+ s.clear();
3910
+ for (const x of v) s.add(x);
3911
+ }
3912
+ for (const [m, v] of maps) {
3913
+ m.clear();
3914
+ for (const [k, x] of v) m.set(k, x);
3915
+ }
3916
+ for (const [l, v] of lists) l.splice(0, l.length, ...v);
3917
+ for (const k of Object.keys(ENUMS)) delete ENUMS[k];
3918
+ for (const [k, arr, v] of enums) {
3919
+ arr.splice(0, arr.length, ...v);
3920
+ ENUMS[k] = arr;
3921
+ }
3922
+ for (const k of Object.keys(THEMES)) delete THEMES[k];
3923
+ Object.assign(THEMES, themes);
3924
+ owners.clear();
3925
+ };
3926
+ }
3597
3927
  /** Register plugins. Registering the same plugin name twice is a no-op. */
3598
3928
  function use(...plugins) {
3929
+ baseline ??= snapshot();
3599
3930
  for (const p of plugins) {
3600
3931
  if (registry.plugins.some((q) => q.name === p.name)) continue;
3601
3932
  registry.plugins.push(p);
3933
+ const w = guarded(p);
3602
3934
  for (const t of p.themes ?? []) registerTheme(t);
3603
- registry.rows.push(...p.rows ?? []);
3604
- for (const fr of p.frames ?? []) registry.frames.set(fr.name, fr);
3605
- for (const dec of p.decorations ?? []) {
3606
- registry.decorations.push(dec);
3935
+ for (const r of w.rows) {
3936
+ claim("row", r.kind, p.name);
3937
+ const at = registry.rows.findIndex((x) => x.kind === r.kind);
3938
+ if (at >= 0) registry.rows[at] = r;
3939
+ else registry.rows.push(r);
3940
+ }
3941
+ for (const fr of w.frames) {
3942
+ claim("frame", fr.name, p.name);
3943
+ registry.frames.set(fr.name, fr);
3944
+ }
3945
+ for (const dec of w.decorations) {
3946
+ const at = registry.decorations.findIndex((x) => x.name === dec.name);
3947
+ if (at >= 0) registry.decorations[at] = dec;
3948
+ else registry.decorations.push(dec);
3607
3949
  KNOWN_SETTINGS.add(dec.setting);
3608
3950
  }
3609
- for (const pk of p.panels ?? []) PANELS.set(pk.name, pk);
3610
- for (const st of p.statements ?? []) STATEMENTS.set(st.keyword, st);
3611
- for (const sh of p.shapes ?? []) SHAPE_KINDS.set(sh.name, sh);
3612
- for (const mk of p.markers ?? []) MARKER_KINDS.set(mk.name, mk);
3951
+ for (const pk of w.panels) {
3952
+ claim("panel", pk.name, p.name);
3953
+ PANELS.set(pk.name, pk);
3954
+ }
3955
+ for (const st of w.statements) {
3956
+ claim("statement", st.keyword, p.name);
3957
+ STATEMENTS.set(st.keyword, st);
3958
+ }
3959
+ for (const sh of w.shapes) {
3960
+ claim("shape", sh.name, p.name);
3961
+ SHAPE_KINDS.set(sh.name, sh);
3962
+ }
3963
+ for (const mk of w.markers) {
3964
+ claim("marker", mk.name, p.name);
3965
+ MARKER_KINDS.set(mk.name, mk);
3966
+ }
3613
3967
  addAll(ENUMS.shape ??= [], p.shapes?.map((x) => x.name));
3614
3968
  addAll(ENUMS.head ??= [], p.markers?.map((x) => x.name));
3615
3969
  if (ENUMS.tail !== ENUMS.head) addAll(ENUMS.tail ??= [], p.markers?.map((x) => x.name));
3616
- if (p.transform) TRANSFORMS.push(p.transform);
3617
- if (p.afterLayout) AFTER_LAYOUT.push(p.afterLayout);
3618
- if (p.postRender) POST_RENDER.push(p.postRender);
3970
+ if (w.transform) TRANSFORMS.push(w.transform);
3971
+ if (w.afterLayout) AFTER_LAYOUT.push(w.afterLayout);
3972
+ if (w.postRender) POST_RENDER.push(w.postRender);
3619
3973
  for (const s of p.settings ?? []) KNOWN_SETTINGS.add(s);
3620
3974
  addAll(NODE_PROPS, p.props?.node);
3621
3975
  addAll(EDGE_PROPS, p.props?.edge);
@@ -4008,6 +4362,16 @@ const themes = {
4008
4362
  };
4009
4363
  // src/plugins/charts.ts
4010
4364
  const nums = (s) => s.split(/[\s,]+/).map(Number).filter((v) => Number.isFinite(v));
4365
+ /** smallest and largest value; loops, since spreading 100k+ values overflows the stack */
4366
+ function extent$1(values) {
4367
+ let lo = 1e400;
4368
+ let hi = -1e400;
4369
+ for (const v of values) {
4370
+ if (v < lo) lo = v;
4371
+ if (v > hi) hi = v;
4372
+ }
4373
+ return [lo, hi];
4374
+ }
4011
4375
  const toneOf = (c, ctx) => inkColor(c, ctx.theme, ctx.theme.accent);
4012
4376
  /** `name [color]: rest`: a palette name, `#hex`, `rgb(…)`, `hsl(…)` or CSS name */
4013
4377
  const head = (name, line) => line.match(new RegExp(`^${name}(?:\\s+(${COLOR_TOKEN}))?:\\s*(.*)$`));
@@ -4028,7 +4392,7 @@ const bars = {
4028
4392
  }),
4029
4393
  render(r, box, ctx) {
4030
4394
  const { fs } = ctx;
4031
- const max = Math.max(...r.values, 0) || 1;
4395
+ const max = Math.max(extent$1(r.values)[1], 0) || 1;
4032
4396
  const base = box.y + box.h - fs * .35;
4033
4397
  const full = box.h - fs * .7;
4034
4398
  const color = toneOf(r.color, ctx);
@@ -4054,14 +4418,15 @@ const spark = {
4054
4418
  h: fs * 3.2
4055
4419
  }),
4056
4420
  render(r, box, ctx) {
4057
- const v = r.values;
4058
- if (v.length < 2) return "";
4421
+ if (!r.values.length) return "";
4422
+ const v = r.values.length === 1 ? [r.values[0], r.values[0]] : r.values;
4059
4423
  const { fs } = ctx;
4060
- const lo = Math.min(...v);
4061
- const span = Math.max(...v) - lo || 1;
4424
+ const [lo, hi] = extent$1(v);
4425
+ const span = hi / 2 - lo / 2;
4062
4426
  const top = box.y + fs * .45;
4063
4427
  const bottom = box.y + box.h - fs * .45;
4064
- const pts = v.map((y, i) => [box.x + i / (v.length - 1) * box.w, bottom - (y - lo) / span * (bottom - top)]);
4428
+ const at = (y) => span ? (y / 2 - lo / 2) / span : .5;
4429
+ const pts = v.map((y, i) => [box.x + i / (v.length - 1) * box.w, bottom - at(y) * (bottom - top)]);
4065
4430
  const line = pts.map(([x, y], i) => `${i ? "L" : "M"}${f$2(x)},${f$2(y)}`).join("");
4066
4431
  const c = toneOf(r.color, ctx);
4067
4432
  const [lx, ly] = pts[pts.length - 1];
@@ -4260,7 +4625,7 @@ const browser = {
4260
4625
  const ph = fs * 1.35;
4261
4626
  const py = b.y + (h - ph) / 2;
4262
4627
  const sub = fs * .78;
4263
- const pill = x1 - x0 > fs * 3 ? `<rect x="${f$2(x0)}" y="${f$2(py)}" width="${f$2(x1 - x0)}" height="${f$2(ph)}" rx="${f$2(ph / 2)}" fill="${theme.background}" stroke="${col.stroke}" stroke-width="1"/>` + (arg ? textEl(x0 + fs * .7, b.y + h / 2, sub, col.sub, esc$1(arg)) : "") : "";
4628
+ const pill = x1 - x0 > fs * 3 ? `<rect x="${f$2(x0)}" y="${f$2(py)}" width="${f$2(x1 - x0)}" height="${f$2(ph)}" rx="${f$2(ph / 2)}" fill="${theme.background === "none" ? theme.node.fill : theme.background}" stroke="${col.stroke}" stroke-width="1"/>` + (arg ? textEl(x0 + fs * .7, b.y + h / 2, sub, col.sub, esc$1(arg)) : "") : "";
4264
4629
  return `<g class="frame">${bar(b, fs, radius, col.stroke, theme.dark)}${pill}</g>`;
4265
4630
  }
4266
4631
  };
@@ -4282,44 +4647,6 @@ const frames = {
4282
4647
  ],
4283
4648
  props: { node: ["frame"] }
4284
4649
  };
4285
- // src/plugins/footer.ts
4286
- const split$1 = (v) => v.split("|").map((s) => s.trim()).filter(Boolean);
4287
- const footer = {
4288
- name: "footer",
4289
- decorations: [{
4290
- name: "footer",
4291
- setting: "footer",
4292
- measure(v, theme, m) {
4293
- const items = split$1(v);
4294
- if (!items.length) return null;
4295
- const fs = theme.fontSize * .82;
4296
- const w = items.reduce((a, it) => a + m(it.replace(/[*`~[\]{}]/g, ""), fs, 400, theme.mono), 0) + fs * 3 * (items.length - 1);
4297
- return {
4298
- bottom: fs * 2.8,
4299
- w
4300
- };
4301
- },
4302
- render(v, area, theme, { pad }) {
4303
- const items = split$1(v);
4304
- const fs = theme.fontSize * .82;
4305
- const y = area.y + area.h * .55;
4306
- const ink = {
4307
- text: theme.node.text,
4308
- sub: theme.node.sub,
4309
- stroke: theme.node.stroke
4310
- };
4311
- const x0 = area.x + pad;
4312
- const x1 = area.x + area.w - pad;
4313
- const out = [`<path d="M${f$2(x0)},${f$2(area.y)}H${f$2(x1)}" stroke="${theme.group.stroke}" stroke-width="1"/>`];
4314
- items.forEach((it, i) => {
4315
- const n = items.length;
4316
- const [x, anchor] = n === 1 ? [x0, "start"] : i === 0 ? [x0, "start"] : i === n - 1 ? [x1, "end"] : [x0 + (x1 - x0) * i / (n - 1), "middle"];
4317
- out.push(`<text x="${f$2(x)}" y="${f$2(y)}" dominant-baseline="central" text-anchor="${anchor}" font-size="${f$2(fs)}" xml:space="preserve">${tspans(parseInline(it), ink, theme, true)}</text>`);
4318
- });
4319
- return `<g class="footer">${out.join("")}</g>`;
4320
- }
4321
- }]
4322
- };
4323
4650
  // src/core/measure.ts
4324
4651
  const NARROW = new Set("iljtfr.,;:'!|()[]{} \"`".split(""));
4325
4652
  const WIDE = new Set("mwMW@%".split(""));
@@ -4354,6 +4681,56 @@ function canvasMeasure(fontFamily) {
4354
4681
  return canvasCtx.measureText(text).width;
4355
4682
  };
4356
4683
  }
4684
+ // src/plugins/footer.ts
4685
+ const split$1 = (v) => v.split("|").map((s) => s.trim()).filter(Boolean);
4686
+ /** item widths from the last measure, so render places them with the real metrics */
4687
+ const measured = /* @__PURE__ */ new Map();
4688
+ const key = (v, fs, mono) => `${fs}|${mono}|${v}`;
4689
+ function widths$1(items, fs, mono, m) {
4690
+ return items.map((it) => segsW(parseInline(it), fs, mono, m));
4691
+ }
4692
+ const footer = {
4693
+ name: "footer",
4694
+ decorations: [{
4695
+ name: "footer",
4696
+ setting: "footer",
4697
+ measure(v, theme, m) {
4698
+ const items = split$1(v);
4699
+ if (!items.length) return null;
4700
+ const fs = theme.fontSize * .82;
4701
+ const ws = widths$1(items, fs, theme.mono, m);
4702
+ if (measured.size > 64) measured.clear();
4703
+ measured.set(key(v, fs, theme.mono), ws);
4704
+ const w = ws.reduce((a, b) => a + b, 0) + fs * 3 * (items.length - 1);
4705
+ return {
4706
+ bottom: fs * 2.8,
4707
+ w
4708
+ };
4709
+ },
4710
+ render(v, area, theme, { pad }) {
4711
+ const items = split$1(v);
4712
+ const fs = theme.fontSize * .82;
4713
+ const y = area.y + area.h * .55;
4714
+ const ink = {
4715
+ text: theme.node.text,
4716
+ sub: theme.node.sub,
4717
+ stroke: theme.node.stroke
4718
+ };
4719
+ const x0 = area.x + pad;
4720
+ const x1 = area.x + area.w - pad;
4721
+ const out = [`<path d="M${f$2(x0)},${f$2(area.y)}H${f$2(x1)}" stroke="${theme.group.stroke}" stroke-width="1"/>`];
4722
+ const ws = measured.get(key(v, fs, theme.mono)) ?? widths$1(items, fs, theme.mono, approxMeasure);
4723
+ const n = items.length;
4724
+ const gap = n > 1 ? (x1 - x0 - ws.reduce((a, b) => a + b, 0)) / (n - 1) : 0;
4725
+ let x = x0;
4726
+ items.forEach((it, i) => {
4727
+ out.push(`<text x="${f$2(x)}" y="${f$2(y)}" dominant-baseline="central" font-size="${f$2(fs)}" xml:space="preserve">${tspans(parseInline(it), ink, theme, true)}</text>`);
4728
+ x += ws[i] + gap;
4729
+ });
4730
+ return `<g class="footer">${out.join("")}</g>`;
4731
+ }
4732
+ }]
4733
+ };
4357
4734
  // src/plugins/legend.ts
4358
4735
  const ARROW = /^(<->|==>|=>|-->|\.\.>|->|--)$/;
4359
4736
  function items(v) {
@@ -4485,7 +4862,10 @@ const legend = {
4485
4862
  }]
4486
4863
  };
4487
4864
  // src/plugins/sequence.ts
4488
- const ID = String.raw`[\p{L}_][\p{L}\p{N}_-]*`;
4865
+ /** an id never ends in `-`, so `a-->b` reads as `a --> b` */
4866
+ const ID = String.raw`[\p{L}_](?:[\p{L}\p{N}_-]*[\p{L}\p{N}_])?`;
4867
+ /** the part names rows take, see stepParts */
4868
+ const ROW_ID = /^(?:m|note|d)\d+$/;
4489
4869
  const PART_RE = new RegExp(String.raw`^(participant|actor)\s+(${ID})(?:\s+"([^"]*)")?(?:\s*\[([^\]]*)\])?$`, "u");
4490
4870
  const MSG_RE$1 = new RegExp(String.raw`^(${ID})\s*(-->|->|\.\.>|=>)\s*(${ID})\s*(?::\s*(.*))?$`, "u");
4491
4871
  /** `a -> b [red]: hi`: props before the colon, which messages do not take */
@@ -4506,12 +4886,12 @@ const TAIL_KEYS = [
4506
4886
  "thick",
4507
4887
  "head"
4508
4888
  ];
4509
- const isTail = (p) => {
4889
+ const isTail$1 = (p) => {
4510
4890
  const keys = Object.keys(p);
4511
4891
  return keys.length > 0 && keys.every((k) => TAIL_KEYS.includes(k)) && (!p.color || isColor(p.color));
4512
4892
  };
4513
- const splitTail = (text) => splitTrailingProps(text, isTail);
4514
- const LINES = {
4893
+ const splitTail = (text) => splitTrailingProps(text, isTail$1);
4894
+ const LINES$1 = {
4515
4895
  "->": "solid",
4516
4896
  "-->": "dashed",
4517
4897
  "..>": "dotted",
@@ -4525,6 +4905,7 @@ function parseSeq(body, _props, warn) {
4525
4905
  let p = parts.find((x) => x.id === id);
4526
4906
  if (!p) parts.push(p = {
4527
4907
  id,
4908
+ key: id,
4528
4909
  label: id,
4529
4910
  actor: false,
4530
4911
  first: i
@@ -4570,7 +4951,7 @@ function parseSeq(body, _props, warn) {
4570
4951
  from: m[1],
4571
4952
  to: m[3],
4572
4953
  text: text.trim().replace(/^"(.*)"$/, "$1"),
4573
- line: LINES[m[2]],
4954
+ line: LINES$1[m[2]],
4574
4955
  n: ++n,
4575
4956
  tone,
4576
4957
  props: rest,
@@ -4583,6 +4964,14 @@ function parseSeq(body, _props, warn) {
4583
4964
  else if (m = line.match(MSG_PROPS_RE)) warn(i, `sequence: props go at the end of a message: "${m[1]}${m[3] ? `: ${m[3]}` : ""} [${m[2]}]"`);
4584
4965
  else warn(i, `sequence: cannot read "${line}" (expected "a -> b: message", "note a: text", "participant a \\"Label\\"" or "--- section ---")`);
4585
4966
  });
4967
+ const taken = new Set(parts.map((p) => p.id));
4968
+ for (const p of parts) {
4969
+ if (!ROW_ID.test(p.id)) continue;
4970
+ let key = `p-${p.id}`;
4971
+ while (taken.has(key)) key = `p-${key}`;
4972
+ taken.add(key);
4973
+ p.key = key;
4974
+ }
4586
4975
  return {
4587
4976
  parts,
4588
4977
  steps
@@ -4597,7 +4986,7 @@ function stepParts(s) {
4597
4986
  return s.steps.map((st) => st.kind === "msg" ? `m${st.n}` : st.kind === "note" ? `note${++count.note}` : `d${++count.divider}`);
4598
4987
  }
4599
4988
  /** everything measured once, shared by measure, render and handles */
4600
- const geometry$7 = perPass(function geometry(s, ctx) {
4989
+ const geometry$8 = perPass(function geometry(s, ctx) {
4601
4990
  const { theme, measure, props } = ctx;
4602
4991
  const fs = ctx.fs * .88;
4603
4992
  const numbered = props.numbered !== void 0 && props.numbered !== "false";
@@ -4627,21 +5016,29 @@ const geometry$7 = perPass(function geometry(s, ctx) {
4627
5016
  }
4628
5017
  const nudge = (k) => ctx.offsets[k]?.x ?? 0;
4629
5018
  gaps.forEach((gap, i) => {
4630
- gaps[i] = Math.max((widths[i] + widths[i + 1]) / 2 + 8, gap + nudge(s.parts[i + 1].id));
5019
+ gaps[i] = Math.max((widths[i] + widths[i + 1]) / 2 + 8, gap + nudge(s.parts[i + 1].key));
4631
5020
  });
4632
5021
  const xs = [widths[0] / 2];
4633
5022
  gaps.forEach((g, i) => xs.push(xs[i] + g));
5023
+ /** left edge of a note relative to the first lifeline at xs[0] = 0: centred over one participant, 20px out over several */
5024
+ const noteLeft = (st) => {
5025
+ const x = xs[Math.min(...st.over.map(idx))];
5026
+ return st.over.length > 1 ? x - 20 : Math.min(x - (textW(st.text) + 24) / 2, x - 20);
5027
+ };
5028
+ let shift = 0;
5029
+ for (const st of s.steps) if (st.kind === "note") shift = Math.max(shift, -noteLeft(st));
5030
+ for (let i = 0; i < xs.length; i++) xs[i] += shift;
4634
5031
  let w = s.parts.length ? xs[xs.length - 1] + widths[widths.length - 1] / 2 + Math.max(0, tail) : 0;
4635
- for (const st of s.steps) if (st.kind === "note" && st.over.length === 1) w = Math.max(w, xs[idx(st.over[0])] + (textW(st.text) + 24) / 2);
5032
+ for (const st of s.steps) if (st.kind === "note") {
5033
+ const ii = st.over.map(idx);
5034
+ const x0 = noteLeft(st);
5035
+ const tw = textW(st.text) + 24;
5036
+ w = Math.max(w, x0 + tw, st.over.length > 1 ? xs[Math.max(...ii)] + 20 : 0);
5037
+ }
4636
5038
  const rowH = (st) => st.kind === "msg" ? st.from === st.to ? fs * 3.6 : fs * 2.6 : st.kind === "note" ? fs * 2.6 : fs * 2.4;
4637
5039
  const parts = stepParts(s);
4638
5040
  const extra = s.steps.map((st, i) => Math.max(-rowH(st) * .3, nudge(parts[i])));
4639
5041
  const h = boxH * 2 + fs * 1.4 + s.steps.reduce((a, st, i) => a + rowH(st) + extra[i], 0);
4640
- /** left edge of a note, relative to the box */
4641
- const noteX = (st) => {
4642
- const x = xs[Math.min(...st.over.map(idx))];
4643
- return Math.min(x - (textW(st.text) + 24) / 2, x - 20);
4644
- };
4645
5042
  return {
4646
5043
  fs,
4647
5044
  boxH,
@@ -4655,7 +5052,7 @@ const geometry$7 = perPass(function geometry(s, ctx) {
4655
5052
  idx,
4656
5053
  num,
4657
5054
  textW,
4658
- noteX
5055
+ noteX: noteLeft
4659
5056
  };
4660
5057
  });
4661
5058
  /** ` stroke-dasharray` for a line style at a stroke width, or "" */
@@ -4666,7 +5063,7 @@ function dashArray(style, w) {
4666
5063
  function renderSeq(s, box, ctx) {
4667
5064
  if (!s.parts.length) return "";
4668
5065
  const T = ctx.theme;
4669
- const g = geometry$7(s, ctx);
5066
+ const g = geometry$8(s, ctx);
4670
5067
  const { fs, boxH, xs } = g;
4671
5068
  const X = (i) => box.x + xs[i];
4672
5069
  const edgeStroke = T.edge.ink;
@@ -4698,7 +5095,7 @@ function renderSeq(s, box, ctx) {
4698
5095
  const b = g.idx(st.to);
4699
5096
  const p = st.props;
4700
5097
  const style = lineStyle(p, "style") ?? (st.line === "thick" ? "solid" : st.line);
4701
- const sw = num(p.width, st.line === "thick" || bool(p.thick, false) ? T.edgeWidth * 2 : T.edgeWidth);
5098
+ const sw = num$1(p.width, st.line === "thick" || bool(p.thick, false) ? T.edgeWidth * 2 : T.edgeWidth);
4702
5099
  const dash = dashArray(style, sw);
4703
5100
  const head = p.head ?? (st.line === "dashed" ? "open" : "arrow");
4704
5101
  const label = parseInline(g.num(st) + st.text);
@@ -4758,10 +5155,10 @@ function renderSeq(s, box, ctx) {
4758
5155
  }
4759
5156
  function seqHandles(s, box, ctx) {
4760
5157
  if (!s.parts.length) return [];
4761
- const g = geometry$7(s, ctx);
5158
+ const g = geometry$8(s, ctx);
4762
5159
  const X = (i) => box.x + g.xs[i];
4763
5160
  const out = s.parts.slice(1).map((p, i) => ({
4764
- part: p.id,
5161
+ part: p.key,
4765
5162
  x: X(i + 1),
4766
5163
  y: box.y + g.boxH,
4767
5164
  axis: "x",
@@ -4775,7 +5172,7 @@ function seqHandles(s, box, ctx) {
4775
5172
  x: X(g.idx(st.from)),
4776
5173
  y: y + g.fs * (st.from === st.to ? 1.6 : 1.85)
4777
5174
  } : st.kind === "note" ? {
4778
- x: g.noteX(st) - 9,
5175
+ x: box.x + g.noteX(st) - 9,
4779
5176
  y: y + rh / 2
4780
5177
  } : {
4781
5178
  x: box.x,
@@ -4797,11 +5194,11 @@ const sequence$1 = {
4797
5194
  panels: [{
4798
5195
  name: "sequence",
4799
5196
  guide: "`participant|actor id \"Label\" [color]` (`participant a, b, c` fixes the order), `a -> b: msg` (`-->` reply, `..>` dotted, `=>` thick, `a -> a` self call), `note a, b: text`, `--- section ---`. A message takes edge props at its end: `a -> b: retry [red, style: dotted]`.",
4800
- layoutParts: "a participant id moves its lifeline and the ones after it; `m<n>` (message), `note<n>`, `d<n>` (divider) add room above that row",
5197
+ layoutParts: "a participant id (`p-<id>` when the id looks like a row) moves its lifeline and the ones after it; `m<n>` (message), `note<n>`, `d<n>` (divider) add room above that row",
4801
5198
  syntax: "sequence id \"Title\" [numbered] { a -> b: message }",
4802
5199
  parse: parseSeq,
4803
5200
  measure(s, ctx) {
4804
- const g = geometry$7(s, ctx);
5201
+ const g = geometry$8(s, ctx);
4805
5202
  return {
4806
5203
  w: g.w,
4807
5204
  h: s.parts.length ? g.h : 0
@@ -4810,8 +5207,8 @@ const sequence$1 = {
4810
5207
  render: renderSeq,
4811
5208
  handles: seqHandles,
4812
5209
  options: {
4813
- numbered: ["true", "false"],
4814
- lifeline: [],
5210
+ numbered: "flag",
5211
+ lifeline: "color",
4815
5212
  "lifeline-style": [
4816
5213
  "dashed",
4817
5214
  "dotted",
@@ -4821,7 +5218,7 @@ const sequence$1 = {
4821
5218
  parts(s) {
4822
5219
  const ids = stepParts(s);
4823
5220
  return [...s.parts.map((p) => ({
4824
- id: p.id,
5221
+ id: p.key,
4825
5222
  label: p.label,
4826
5223
  kind: p.actor ? "actor" : "participant",
4827
5224
  tone: p.tone
@@ -4834,7 +5231,7 @@ const sequence$1 = {
4834
5231
  },
4835
5232
  editPart: recolor((body, id, tone, s) => {
4836
5233
  const out = [...body];
4837
- const p = s.parts.find((x) => x.id === id);
5234
+ const p = s.parts.find((x) => x.key === id);
4838
5235
  if (p) {
4839
5236
  if (p.decl !== void 0) {
4840
5237
  out[p.decl] = setTrailingProp(body[p.decl], "color", tone);
@@ -4864,6 +5261,12 @@ const sequence$1 = {
4864
5261
  }]
4865
5262
  };
4866
5263
  // src/plugins/timeline.ts
5264
+ /** largest of `init` and every value; a loop, since spreading 100k+ values overflows the stack */
5265
+ function maxOf$2(values, init) {
5266
+ let m = init;
5267
+ for (const v of values) if (v > m) m = v;
5268
+ return m;
5269
+ }
4867
5270
  const EVENT_RE = /^(.+?)(?:\s*\[([^\]]+)\])?:\s+(.*)$/;
4868
5271
  const HEAD_RE$3 = /^(\s*.+?)(?:\s*\[([^\]]*)\])?(:\s+.*)$/;
4869
5272
  function parseTimeline(body, _props, warn) {
@@ -4902,17 +5305,17 @@ function eventLines(body) {
4902
5305
  const out = [];
4903
5306
  body.forEach((raw, i) => {
4904
5307
  const line = raw.trim();
4905
- if (line && !/^(\/\/|#|[-*]\s)/.test(line) && EVENT_RE.test(line)) out.push(i);
5308
+ if (line && !/^(\/\/|#|[-*]\s)/.test(line) && EVENT_RE.test(splitTrailingProps(line, onlyColor)[0])) out.push(i);
4906
5309
  });
4907
5310
  return out;
4908
5311
  }
4909
- const geometry$6 = perPass(function geometry(ev, ctx) {
5312
+ const geometry$7 = perPass(function geometry(ev, ctx) {
4910
5313
  const { theme, measure, props } = ctx;
4911
5314
  const fs = ctx.fs * .9;
4912
5315
  const vertical = props.direction === "down";
4913
5316
  const tw = (t, size = fs, weight = 400) => segsW(parseInline(t), size, theme.mono, measure, weight);
4914
5317
  const whenW = ev.map((e) => measure(e.when, fs * .9, 600, theme.mono));
4915
- const bodyW = ev.map((e) => Math.max(tw(e.title, fs, 600), ...e.details.map((d) => tw(d, fs * .92))));
5318
+ const bodyW = ev.map((e) => maxOf$2(e.details.map((d) => tw(d, fs * .92)), tw(e.title, fs, 600)));
4916
5319
  const lines = ev.map((e) => 1 + e.details.length);
4917
5320
  const parts = eventParts(ev);
4918
5321
  const steps = vertical ? ev.map((_, i) => lines[i] * fs * 1.45 + fs * 1.2) : ev.map((_, i) => Math.max(whenW[i], bodyW[i], fs * 7) + fs * 1.6);
@@ -4924,14 +5327,14 @@ const geometry$6 = perPass(function geometry(ev, ctx) {
4924
5327
  });
4925
5328
  const end = ev.length ? at[at.length - 1] + steps[steps.length - 1] - gap : 0;
4926
5329
  if (vertical) {
4927
- const left = Math.max(0, ...whenW) + 18;
5330
+ const left = maxOf$2(whenW, 0) + 18;
4928
5331
  return {
4929
5332
  fs,
4930
5333
  vertical,
4931
5334
  left,
4932
5335
  at,
4933
5336
  parts,
4934
- w: left + 22 + Math.max(0, ...bodyW),
5337
+ w: left + 22 + maxOf$2(bodyW, 0),
4935
5338
  h: end + fs * .6
4936
5339
  };
4937
5340
  }
@@ -4942,13 +5345,13 @@ const geometry$6 = perPass(function geometry(ev, ctx) {
4942
5345
  at,
4943
5346
  parts,
4944
5347
  w: end,
4945
- h: fs * 3.4 + Math.max(1, ...lines) * fs * 1.45
5348
+ h: fs * 3.4 + maxOf$2(lines, 1) * fs * 1.45
4946
5349
  };
4947
5350
  });
4948
5351
  function renderTimeline(ev, box, ctx) {
4949
5352
  if (!ev.length) return "";
4950
5353
  const T = ctx.theme;
4951
- const g = geometry$6(ev, ctx);
5354
+ const g = geometry$7(ev, ctx);
4952
5355
  const { fs } = g;
4953
5356
  const ink = {
4954
5357
  text: T.node.text,
@@ -4999,7 +5402,7 @@ const timeline$1 = {
4999
5402
  w: 0,
5000
5403
  h: 0
5001
5404
  };
5002
- const g = geometry$6(ev, ctx);
5405
+ const g = geometry$7(ev, ctx);
5003
5406
  return {
5004
5407
  w: g.w,
5005
5408
  h: g.h
@@ -5021,7 +5424,7 @@ const timeline$1 = {
5021
5424
  }),
5022
5425
  handles(ev, box, ctx) {
5023
5426
  if (!ev.length) return [];
5024
- const g = geometry$6(ev, ctx);
5427
+ const g = geometry$7(ev, ctx);
5025
5428
  return ev.slice(1).map((e, k) => g.vertical ? {
5026
5429
  part: g.parts[k + 1],
5027
5430
  x: box.x + g.left,
@@ -5061,6 +5464,14 @@ const PALETTE$3 = [
5061
5464
  ];
5062
5465
  const ITEM_RE = /^(.+?)(?:\s*\[([^\]]+)\])?\s*:\s*(-?\d+(?:\.\d+)?)\s*%?$/;
5063
5466
  const HEAD_RE$2 = /^(\s*.+?)(?:\s*\[([^\]]*)\])?(\s*:.*)$/;
5467
+ /** larger values would overflow sums and scaling to Infinity */
5468
+ const MAX_VALUE = 1e300;
5469
+ /** largest of `init` and every value; a loop, since spreading 100k+ values overflows the stack */
5470
+ function maxOf$1(values, init) {
5471
+ let m = init;
5472
+ for (const v of values) if (v > m) m = v;
5473
+ return m;
5474
+ }
5064
5475
  function parseChart(body, props, warn) {
5065
5476
  const t = props.type ?? "bar";
5066
5477
  if (!TYPES$1.includes(t)) warn(-1, `chart: unknown type "${props.type}" (use ${TYPES$1.join(", ")})`);
@@ -5070,10 +5481,12 @@ function parseChart(body, props, warn) {
5070
5481
  if (!line) return;
5071
5482
  const [core, tail] = splitTrailingProps(line, onlyColor);
5072
5483
  const m = core.match(ITEM_RE);
5073
- if (m) items.push({
5484
+ const value = m ? Number(m[3]) : NaN;
5485
+ if (m && !(Math.abs(value) <= MAX_VALUE)) warn(i, `chart: "${m[3].slice(0, 24)}…" is too large a number`);
5486
+ else if (m) items.push({
5074
5487
  label: m[1].trim().replace(/^"(.*)"$/, "$1"),
5075
5488
  tone: tail.color ?? parseProps(m[2]).color,
5076
- value: Number(m[3])
5489
+ value
5077
5490
  });
5078
5491
  else warn(i, `chart: cannot read "${line}" (expected "label: number")`);
5079
5492
  });
@@ -5082,18 +5495,18 @@ function parseChart(body, props, warn) {
5082
5495
  items
5083
5496
  };
5084
5497
  }
5085
- const fmt = (v, unit = "") => `${Math.round(v * 100) / 100}${unit}`;
5498
+ const fmt = (v, unit = "") => `${Math.abs(v) < 1e15 ? Math.round(v * 100) / 100 : v}${unit}`;
5086
5499
  function colorOf(it, i, ctx, multi) {
5087
5500
  if (it.tone) return inkColor(it.tone, ctx.theme, ctx.theme.accent);
5088
5501
  if (!multi) return ctx.theme.accent;
5089
5502
  return ramp(PALETTE$3[i % PALETTE$3.length], ctx.theme.dark ? 400 : 500);
5090
5503
  }
5091
- const geometry$5 = perPass(function geometry(c, ctx) {
5504
+ const geometry$6 = perPass(function geometry(c, ctx) {
5092
5505
  const { theme, measure, props } = ctx;
5093
5506
  const fs = ctx.fs * .88;
5094
5507
  const unit = props.unit ?? "";
5095
- const lw = Math.max(0, ...c.items.map((it) => measure(it.label, fs, 400, theme.mono)));
5096
- const vw = Math.max(0, ...c.items.map((it) => measure(fmt(it.value, unit), fs, 600, theme.mono)));
5508
+ const lw = maxOf$1(c.items.map((it) => measure(it.label, fs, 400, theme.mono)), 0);
5509
+ const vw = maxOf$1(c.items.map((it) => measure(fmt(it.value, unit), fs, 600, theme.mono)), 0);
5097
5510
  const total = c.items.reduce((a, it) => a + Math.max(0, it.value), 0);
5098
5511
  const size = ctx.offsets.size ?? {
5099
5512
  x: 0,
@@ -5131,7 +5544,7 @@ const geometry$5 = perPass(function geometry(c, ctx) {
5131
5544
  barMax,
5132
5545
  pitch,
5133
5546
  w: lw + 12 + barMax + 10 + vw,
5134
- h: c.items.length * pitch - fs * .6
5547
+ h: (c.items.length - 1) * pitch + fs * 1.4
5135
5548
  };
5136
5549
  }
5137
5550
  default: {
@@ -5164,11 +5577,11 @@ function arc(cx, cy, r, a0, a1, ir) {
5164
5577
  function renderChart(c, box, ctx) {
5165
5578
  if (!c.items.length) return "";
5166
5579
  const T = ctx.theme;
5167
- const g = geometry$5(c, ctx);
5580
+ const g = geometry$6(c, ctx);
5168
5581
  const { fs, unit } = g;
5169
5582
  const out = [];
5170
5583
  const label = (x, y, s, anchor = "start", fill = T.node.text, weight = 400, size = fs) => `<text x="${f$2(x)}" y="${f$2(y)}" dominant-baseline="central" text-anchor="${anchor}" font-size="${f$2(size)}"${weight !== 400 ? ` font-weight="${weight}"` : ""} fill="${fill}">${esc$1(s)}</text>`;
5171
- const max = Math.max(0, ...c.items.map((it) => it.value)) || 1;
5584
+ const max = maxOf$1(c.items.map((it) => it.value), 0) || 1;
5172
5585
  if (c.type === "pie" || c.type === "donut") {
5173
5586
  const cx = box.x + g.r;
5174
5587
  const cy = box.y + g.h / 2;
@@ -5252,7 +5665,7 @@ const chart = {
5252
5665
  w: 0,
5253
5666
  h: 0
5254
5667
  };
5255
- const g = geometry$5(c, ctx);
5668
+ const g = geometry$6(c, ctx);
5256
5669
  return {
5257
5670
  w: g.w,
5258
5671
  h: g.h
@@ -5261,7 +5674,7 @@ const chart = {
5261
5674
  render: renderChart,
5262
5675
  options: {
5263
5676
  type: [...TYPES$1],
5264
- unit: []
5677
+ unit: "text"
5265
5678
  },
5266
5679
  parts: (c) => c.items.map((it, i) => ({
5267
5680
  id: `i${i + 1}`,
@@ -5282,7 +5695,7 @@ const chart = {
5282
5695
  }),
5283
5696
  handles(c, box, ctx) {
5284
5697
  if (!c.items.length) return [];
5285
- const g = geometry$5(c, ctx);
5698
+ const g = geometry$6(c, ctx);
5286
5699
  return [{
5287
5700
  part: "size",
5288
5701
  x: box.x + g.w,
@@ -5320,7 +5733,7 @@ const MERGE_RE = new RegExp(String.raw`^merge\s+(${NAME})(?:\s+(.*?))?${PROPS}$`
5320
5733
  const PICK_RE = new RegExp(String.raw`^cherry-pick\s+(\S+?)(?:\s+(.*?))?${PROPS}$`, "u");
5321
5734
  const TAG_RE = /^tag\s+(\S+)$/;
5322
5735
  /** `tag: v1, red, highlight` → { tag: 'v1', color: 'red', type: 'highlight' }: the core prop reader plus commit types */
5323
- function readProps$1(s) {
5736
+ function readProps(s) {
5324
5737
  const p = parseProps(s ?? "");
5325
5738
  for (const t of TYPES) if (p[t] === "true") {
5326
5739
  p.type = t;
@@ -5374,7 +5787,7 @@ function parseGit(body, props, warn) {
5374
5787
  if (at === void 0) return warn(i, `git: unknown branch, commit or tag "${m[2]}"`);
5375
5788
  head = at;
5376
5789
  }
5377
- const p = readProps$1(m[3]);
5790
+ const p = readProps(m[3]);
5378
5791
  const order = p.order !== void 0 ? Number(p.order) : void 0;
5379
5792
  if (order !== void 0 && !Number.isFinite(order)) warn(i, `git: order must be a number, got "${p.order}"`);
5380
5793
  const b = {
@@ -5402,7 +5815,7 @@ function parseGit(body, props, warn) {
5402
5815
  msg: unquote(m[2] ?? "") || `Merge ${b.name}`,
5403
5816
  parents,
5404
5817
  merge: true
5405
- }, readProps$1(m[3]), i);
5818
+ }, readProps(m[3]), i);
5406
5819
  } else if (m = line.match(PICK_RE)) {
5407
5820
  const src = ref(m[1]);
5408
5821
  if (src === void 0) return warn(i, `git: cherry-pick: unknown commit, tag or branch "${m[1]}" (give the commit an id: commit "msg" [id: abc])`);
@@ -5412,7 +5825,7 @@ function parseGit(body, props, warn) {
5412
5825
  parents: cur.head >= 0 ? [cur.head] : [],
5413
5826
  merge: false,
5414
5827
  pick: src
5415
- }, readProps$1(m[3]), i);
5828
+ }, readProps(m[3]), i);
5416
5829
  } else if (m = line.match(TAG_RE)) {
5417
5830
  if (cur.head < 0) warn(i, "git: nothing to tag yet");
5418
5831
  else commits[cur.head].tags.push(m[1]);
@@ -5420,7 +5833,7 @@ function parseGit(body, props, warn) {
5420
5833
  msg: unquote(m[1] ?? ""),
5421
5834
  parents: cur.head >= 0 ? [cur.head] : [],
5422
5835
  merge: false
5423
- }, readProps$1(m[2]), i);
5836
+ }, readProps(m[2]), i);
5424
5837
  else warn(i, `git: cannot read "${line}" (expected commit, branch, checkout, merge, cherry-pick or tag)`);
5425
5838
  });
5426
5839
  return {
@@ -5441,16 +5854,22 @@ function laneColor(g, lane, ctx) {
5441
5854
  */
5442
5855
  function commitParts(g) {
5443
5856
  const seen = new Set(g.branches.map((b) => b.name));
5444
- return g.commits.map((c, i) => {
5445
- let k = c.id ?? c.tags[0];
5446
- if (!k || seen.has(k) || /\s/.test(k)) k = `c${i + 1}`;
5857
+ return g.commits.map((c) => {
5858
+ const k = c.id ?? c.tags[0];
5859
+ if (!k || seen.has(k) || /\s/.test(k)) return "";
5860
+ seen.add(k);
5861
+ return k;
5862
+ }).map((k, i) => {
5863
+ if (k) return k;
5864
+ k = `c${i + 1}`;
5865
+ for (let n = 2; seen.has(k); n++) k = `c${i + 1}-${n}`;
5447
5866
  seen.add(k);
5448
5867
  return k;
5449
5868
  });
5450
5869
  }
5451
5870
  /** measure, handles and render ask for the same geometry within one layout; keep the last one */
5452
5871
  const memo = /* @__PURE__ */ new WeakMap();
5453
- const geometry$4 = perPass(function geometry(g, ctx) {
5872
+ const geometry$5 = perPass(function geometry(g, ctx) {
5454
5873
  const key = JSON.stringify([
5455
5874
  ctx.fs,
5456
5875
  ctx.props,
@@ -5668,7 +6087,7 @@ function routes(g, G, box) {
5668
6087
  function renderGit(g, box, ctx) {
5669
6088
  if (!g.commits.length) return "";
5670
6089
  const T = ctx.theme;
5671
- const G = geometry$4(g, ctx);
6090
+ const G = geometry$5(g, ctx);
5672
6091
  const { fs, r } = G;
5673
6092
  const bg = ctx.props.color && T.groupTone(ctx.props.color)?.fill || [
5674
6093
  T.group.fill,
@@ -5767,7 +6186,7 @@ const git$1 = {
5767
6186
  w: 0,
5768
6187
  h: 0
5769
6188
  };
5770
- const G = geometry$4(g, ctx);
6189
+ const G = geometry$5(g, ctx);
5771
6190
  return {
5772
6191
  w: G.w,
5773
6192
  h: G.h
@@ -5776,7 +6195,7 @@ const git$1 = {
5776
6195
  render: renderGit,
5777
6196
  handles(g, box, ctx) {
5778
6197
  if (!g.commits.length) return [];
5779
- const G = geometry$4(g, ctx);
6198
+ const G = geometry$5(g, ctx);
5780
6199
  const time = G.vertical ? "y" : "x";
5781
6200
  const across = G.vertical ? "x" : "y";
5782
6201
  const R = routes(g, G, box);
@@ -5836,9 +6255,13 @@ const PALETTE$1 = [
5836
6255
  "red",
5837
6256
  "lime"
5838
6257
  ];
5839
- const NODE_RE = /^(?:[-*+]\s+)?(.*?)(?:\s*\[([^\]]*)\])?$/;
5840
- /** `[pink, shape: plain]`, `[#f80]`, `[color: rgb(0, 120, 200)]` */
5841
- const readProps = (s) => parseProps(s ?? "");
6258
+ const BULLET$1 = /^[-*+]\s+/;
6259
+ /** `[pink, shape: plain]`, `[#f80]`, `[color: rgb(0, 120, 200)]`; any other bracket is text */
6260
+ const isTail = (p) => {
6261
+ const keys = Object.keys(p);
6262
+ return keys.length > 0 && keys.every((k) => k === "color" || k === "shape") && (!p.color || isColor(p.color));
6263
+ };
6264
+ const splitNode = (line) => splitTrailingProps(line, isTail);
5842
6265
  function parseMindmap(body, _props, warn) {
5843
6266
  let root = null;
5844
6267
  let rootIndent = 0;
@@ -5847,11 +6270,10 @@ function parseMindmap(body, _props, warn) {
5847
6270
  const line = raw.trim();
5848
6271
  if (!line) return;
5849
6272
  let indent = raw.match(/^\s*/)[0].replace(/\t/g, " ").length;
5850
- const m = line.match(NODE_RE);
5851
- const p = readProps(m[2]);
6273
+ const [text, p] = splitNode(line.replace(BULLET$1, ""));
5852
6274
  if (p.shape && !SHAPES$1.includes(p.shape)) warn(i, `mindmap: unknown shape "${p.shape}" (use one of: ${SHAPES$1.join(", ")})`);
5853
6275
  const node = {
5854
- text: m[1].trim(),
6276
+ text: text.trim(),
5855
6277
  tone: p.color,
5856
6278
  shape: p.shape,
5857
6279
  line: i,
@@ -5880,18 +6302,25 @@ function parseMindmap(body, _props, warn) {
5880
6302
  });
5881
6303
  return root;
5882
6304
  }
5883
- /** every node in reading order */
5884
- function walk(n, out = []) {
5885
- out.push(n);
5886
- for (const c of n.children) walk(c, out);
6305
+ /** every node in reading order (no recursion: a map can be thousands of levels deep) */
6306
+ function walk$1(root) {
6307
+ const out = [];
6308
+ const todo = [root];
6309
+ while (todo.length) {
6310
+ const n = todo.pop();
6311
+ out.push(n);
6312
+ for (let k = n.children.length - 1; k >= 0; k--) todo.push(n.children[k]);
6313
+ }
5887
6314
  return out;
5888
6315
  }
6316
+ const minOf = (xs) => xs.reduce((a, b) => Math.min(a, b), 1e400);
6317
+ const maxOf = (xs) => xs.reduce((a, b) => Math.max(a, b), -1e400);
5889
6318
  function nodeParts(nodes) {
5890
6319
  const counts = /* @__PURE__ */ new Map();
5891
6320
  for (const n of nodes) counts.set(n.text, (counts.get(n.text) ?? 0) + 1);
5892
6321
  return nodes.map((n, i) => /^[\w-]+$/.test(n.text) && counts.get(n.text) === 1 && !/^n\d+$/.test(n.text) ? n.text : `n${i + 1}`);
5893
6322
  }
5894
- const geometry$3 = perPass(function geometry(root, ctx) {
6323
+ const geometry$4 = perPass(function geometry(root, ctx) {
5895
6324
  const { theme, measure, props } = ctx;
5896
6325
  const fs = ctx.fs * .9;
5897
6326
  const mode = [
@@ -5901,7 +6330,7 @@ const geometry$3 = perPass(function geometry(root, ctx) {
5901
6330
  ].includes(props.layout) ? props.layout : "both";
5902
6331
  const down = mode === "down";
5903
6332
  const mono = props.colors === "mono";
5904
- const nodes = walk(root);
6333
+ const nodes = walk$1(root);
5905
6334
  const parts = nodeParts(nodes);
5906
6335
  const partOf = new Map(nodes.map((n, i) => [n, parts[i]]));
5907
6336
  const placed = /* @__PURE__ */ new Map();
@@ -5936,24 +6365,27 @@ const geometry$3 = perPass(function geometry(root, ctx) {
5936
6365
  parent
5937
6366
  };
5938
6367
  placed.set(n, p);
5939
- n.children.forEach((c, k) => size(c, depth + 1, c.tone ?? (depth === 0 ? mono ? void 0 : PALETTE$1[k % PALETTE$1.length] : p.color), p));
6368
+ return p;
5940
6369
  };
5941
6370
  size(root, 0, root.tone);
6371
+ for (const n of nodes) {
6372
+ const p = placed.get(n);
6373
+ n.children.forEach((c, k) => size(c, p.depth + 1, c.tone ?? (p.depth === 0 ? mono ? void 0 : PALETTE$1[k % PALETTE$1.length] : p.color), p));
6374
+ }
5942
6375
  const gapOf = (depth) => down ? fs * .8 : depth <= 1 ? fs * .9 : fs * .35;
5943
6376
  const extra = (n, k, depth) => k ? Math.max(-gapOf(depth) * .75, ctx.offsets[partOf.get(n)]?.x ?? 0) : 0;
5944
6377
  const across = (p) => down ? p.w : p.h;
5945
6378
  const ext = /* @__PURE__ */ new Map();
5946
- const extent = (n, list = n.children) => {
6379
+ /** extent of `list` (children of `n`, all already measured) stacked next to each other */
6380
+ const extent = (n, list) => {
5947
6381
  const p = placed.get(n);
5948
6382
  let sum = 0;
5949
6383
  list.forEach((c, k) => {
5950
- sum += extent(c) + (k ? gapOf(p.depth) : 0) + extra(c, k, p.depth);
6384
+ sum += ext.get(c) + (k ? gapOf(p.depth) : 0) + extra(c, k, p.depth);
5951
6385
  });
5952
- const e = Math.max(across(p), sum);
5953
- if (list === n.children) ext.set(n, e);
5954
- return e;
6386
+ return Math.max(across(p), sum);
5955
6387
  };
5956
- extent(root);
6388
+ for (let i = nodes.length - 1; i >= 0; i--) ext.set(nodes[i], extent(nodes[i], nodes[i].children));
5957
6389
  const kids = root.children;
5958
6390
  let right = kids;
5959
6391
  let left = [];
@@ -5972,6 +6404,7 @@ const geometry$3 = perPass(function geometry(root, ctx) {
5972
6404
  left = kids.slice(cut);
5973
6405
  }
5974
6406
  const reach = (depth) => down ? fs * 1.9 : depth === 0 ? fs * 2.6 : fs * 1.7;
6407
+ const todo = [];
5975
6408
  const place = (p, list, side) => {
5976
6409
  const total = extent(p.node, list);
5977
6410
  let at = (down ? p.x + p.w / 2 : p.y + p.h / 2) - total / 2;
@@ -5988,15 +6421,27 @@ const geometry$3 = perPass(function geometry(root, ctx) {
5988
6421
  q.x = side > 0 ? p.x + p.w + reach(p.depth) : p.x - reach(p.depth) - q.w;
5989
6422
  }
5990
6423
  at += e;
5991
- place(q, c.children, side);
6424
+ todo.push([
6425
+ q,
6426
+ c.children,
6427
+ side
6428
+ ]);
5992
6429
  });
5993
6430
  };
5994
6431
  const r = placed.get(root);
5995
- place(r, right, 1);
5996
- place(r, left, -1);
6432
+ todo.push([
6433
+ r,
6434
+ right,
6435
+ 1
6436
+ ], [
6437
+ r,
6438
+ left,
6439
+ -1
6440
+ ]);
6441
+ while (todo.length) place(...todo.pop());
5997
6442
  const all = nodes.map((n) => placed.get(n));
5998
- const x0 = Math.min(...all.map((p) => p.x));
5999
- const y0 = Math.min(...all.map((p) => p.y));
6443
+ const x0 = minOf(all.map((p) => p.x));
6444
+ const y0 = minOf(all.map((p) => p.y));
6000
6445
  for (const p of all) {
6001
6446
  p.x -= x0;
6002
6447
  p.y -= y0;
@@ -6004,15 +6449,15 @@ const geometry$3 = perPass(function geometry(root, ctx) {
6004
6449
  return {
6005
6450
  all,
6006
6451
  down,
6007
- w: Math.max(...all.map((p) => p.x + p.w)),
6008
- h: Math.max(...all.map((p) => p.y + p.h))
6452
+ w: maxOf(all.map((p) => p.x + p.w)),
6453
+ h: maxOf(all.map((p) => p.y + p.h))
6009
6454
  };
6010
6455
  });
6011
6456
  const ink = (T, c) => c ? inkColor(c, T, T.accent) : T.accent;
6012
6457
  function renderMindmap(root, box, ctx) {
6013
6458
  if (!root) return "";
6014
6459
  const T = ctx.theme;
6015
- const g = geometry$3(root, ctx);
6460
+ const g = geometry$4(root, ctx);
6016
6461
  const links = [];
6017
6462
  const shapes = [];
6018
6463
  const X = (v) => box.x + v;
@@ -6075,7 +6520,7 @@ const mindmap$1 = {
6075
6520
  w: 0,
6076
6521
  h: 0
6077
6522
  };
6078
- const g = geometry$3(root, ctx);
6523
+ const g = geometry$4(root, ctx);
6079
6524
  return {
6080
6525
  w: g.w,
6081
6526
  h: g.h
@@ -6084,7 +6529,7 @@ const mindmap$1 = {
6084
6529
  render: renderMindmap,
6085
6530
  parts(root) {
6086
6531
  if (!root) return [];
6087
- const nodes = walk(root);
6532
+ const nodes = walk$1(root);
6088
6533
  const depth = /* @__PURE__ */ new Map([[root, 0]]);
6089
6534
  for (const n of nodes) for (const c of n.children) depth.set(c, depth.get(n) + 1);
6090
6535
  return nodeParts(nodes).map((id, i) => ({
@@ -6096,23 +6541,21 @@ const mindmap$1 = {
6096
6541
  },
6097
6542
  editPart: recolor((body, id, tone, root) => {
6098
6543
  if (!root) return null;
6099
- const nodes = walk(root);
6544
+ const nodes = walk$1(root);
6100
6545
  const n = nodes[nodeParts(nodes).indexOf(id)];
6101
6546
  if (!n) return null;
6102
6547
  const out = [...body];
6103
- const line = body[n.line];
6104
- const m = line.match(/\s*\[([^\]]*)\]\s*$/);
6105
- const { color: _, ...rest } = readProps(m?.[1]);
6548
+ const [head, { color: _, ...rest }] = splitNode(body[n.line]);
6106
6549
  const props = serializeProps(tone ? {
6107
6550
  color: tone,
6108
6551
  ...rest
6109
6552
  } : rest);
6110
- out[n.line] = (m ? line.slice(0, m.index) : line.trimEnd()) + (props ? ` [${props}]` : "");
6553
+ out[n.line] = head.trimEnd() + (props ? ` [${props}]` : "");
6111
6554
  return out;
6112
6555
  }),
6113
6556
  handles(root, box, ctx) {
6114
6557
  if (!root) return [];
6115
- const g = geometry$3(root, ctx);
6558
+ const g = geometry$4(root, ctx);
6116
6559
  const out = [];
6117
6560
  for (const p of g.all) {
6118
6561
  if (!p.parent || p.parent.node.children[0] === p.node) continue;
@@ -6134,6 +6577,12 @@ const mindmap$1 = {
6134
6577
  };
6135
6578
  // src/plugins/gantt.ts
6136
6579
  const DAY = 864e5;
6580
+ /** the largest |ms| a JS Date can hold */
6581
+ const MAX_TIME = 864e13;
6582
+ /** at most this many axis ticks, however wide the chart */
6583
+ const MAX_TICKS = 2e3;
6584
+ /** weekends are shaded only over spans up to this many days */
6585
+ const MAX_WEEKEND_DAYS = 3660;
6137
6586
  const MONTHS = [
6138
6587
  "Jan",
6139
6588
  "Feb",
@@ -6156,9 +6605,10 @@ function parseDate(s) {
6156
6605
  const m = s.trim().match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:[ T](\d{1,2}):(\d{2}))?$/);
6157
6606
  if (!m) return NaN;
6158
6607
  const [y, mo, d, h = "0", mi = "0"] = m.slice(1);
6159
- const t = Date.UTC(+y, +mo - 1, +d, +h, +mi);
6160
- const back = new Date(t);
6161
- return back.getUTCMonth() === +mo - 1 && back.getUTCDate() === +d ? t : NaN;
6608
+ const back = /* @__PURE__ */ new Date(0);
6609
+ back.setUTCFullYear(+y, +mo - 1, +d);
6610
+ back.setUTCHours(+h, +mi, 0, 0);
6611
+ return back.getUTCFullYear() === +y && back.getUTCMonth() === +mo - 1 && back.getUTCDate() === +d ? back.getTime() : NaN;
6162
6612
  }
6163
6613
  /** ms of `3h`, `5d`, `2w`, NaN when not a length */
6164
6614
  function parseLength(s) {
@@ -6243,29 +6693,19 @@ function parseGantt(body, _props, warn) {
6243
6693
  const byId = new Map(tasks.map((t, i) => [t.id, i]));
6244
6694
  const state = tasks.map(() => 0);
6245
6695
  const known = specs.map((s) => s.date).filter((x) => !Number.isNaN(x));
6246
- const fallback = known.length ? Math.min(...known) : Date.UTC(2025, 0, 1);
6247
- const resolve = (i) => {
6696
+ const fallback = known.length ? known.reduce((a, b) => Math.min(a, b)) : Date.UTC(2025, 0, 1);
6697
+ const depsOf = (i) => {
6698
+ const s = specs[i];
6699
+ if (s.after.length) return s.after;
6700
+ return Number.isNaN(s.date) && i > 0 ? [i - 1] : [];
6701
+ };
6702
+ const finish = (i, ends) => {
6248
6703
  const t = tasks[i];
6249
- if (state[i] === 2) return t.end;
6250
- if (state[i] === 1) {
6251
- warn(specs[i].line, `gantt: "${t.id}" depends on itself through "after"`);
6252
- return fallback;
6253
- }
6254
- state[i] = 1;
6255
6704
  const s = specs[i];
6256
6705
  let start = s.date;
6257
- if (s.after.length) {
6258
- const ends = s.after.flatMap((a) => {
6259
- const j = byId.get(a);
6260
- if (j === void 0) {
6261
- warn(s.line, `gantt: "after ${a}": no task "${a}"`);
6262
- return [];
6263
- }
6264
- return [resolve(j)];
6265
- });
6266
- start = ends.length ? Math.max(...ends) : fallback;
6267
- } else if (Number.isNaN(start)) {
6268
- if (i > 0) start = resolve(i - 1);
6706
+ if (s.after.length) start = ends.length ? ends.reduce((a, b) => Math.max(a, b)) : fallback;
6707
+ else if (Number.isNaN(start)) {
6708
+ if (i > 0) start = ends[0];
6269
6709
  else {
6270
6710
  warn(s.line, `gantt: the first task needs a start date`);
6271
6711
  start = fallback;
@@ -6273,16 +6713,61 @@ function parseGantt(body, _props, warn) {
6273
6713
  }
6274
6714
  t.start = start;
6275
6715
  t.end = t.milestone ? start : !Number.isNaN(s.len) ? start + s.len : !Number.isNaN(s.endDate) ? Math.max(start, s.endDate) : start + DAY;
6716
+ if (!(Math.abs(t.end) <= MAX_TIME)) {
6717
+ warn(s.line, `gantt: task "${t.id}" ends past the last date a chart can show`);
6718
+ t.end = start;
6719
+ }
6276
6720
  state[i] = 2;
6277
6721
  return t.end;
6278
6722
  };
6723
+ const resolve = (root) => {
6724
+ if (state[root] !== 0) return;
6725
+ state[root] = 1;
6726
+ const stack = [{
6727
+ i: root,
6728
+ deps: depsOf(root),
6729
+ k: 0,
6730
+ ends: []
6731
+ }];
6732
+ while (stack.length) {
6733
+ const fr = stack[stack.length - 1];
6734
+ if (fr.k < fr.deps.length) {
6735
+ const d = fr.deps[fr.k++];
6736
+ const j = typeof d === "number" ? d : byId.get(d);
6737
+ if (j === void 0) warn(specs[fr.i].line, `gantt: "after ${d}": no task "${d}"`);
6738
+ else if (state[j] === 2) fr.ends.push(tasks[j].end);
6739
+ else if (state[j] === 1) {
6740
+ warn(specs[j].line, `gantt: "${tasks[j].id}" depends on itself through "after"`);
6741
+ fr.ends.push(fallback);
6742
+ } else {
6743
+ state[j] = 1;
6744
+ stack.push({
6745
+ i: j,
6746
+ deps: depsOf(j),
6747
+ k: 0,
6748
+ ends: []
6749
+ });
6750
+ }
6751
+ continue;
6752
+ }
6753
+ stack.pop();
6754
+ const end = finish(fr.i, fr.ends);
6755
+ if (stack.length) stack[stack.length - 1].ends.push(end);
6756
+ }
6757
+ };
6279
6758
  tasks.forEach((_, i) => resolve(i));
6759
+ let min = tasks.length ? 1e400 : 0;
6760
+ let max = tasks.length ? -1e400 : 0;
6761
+ for (const t of tasks) {
6762
+ min = Math.min(min, t.start);
6763
+ max = Math.max(max, t.end);
6764
+ }
6280
6765
  return {
6281
6766
  tasks,
6282
6767
  sections,
6283
6768
  sectionTones,
6284
- min: tasks.length ? Math.min(...tasks.map((t) => t.start)) : 0,
6285
- max: tasks.length ? Math.max(...tasks.map((t) => t.end)) : 0
6769
+ min,
6770
+ max
6286
6771
  };
6287
6772
  }
6288
6773
  /** body index of each task line, in task order */
@@ -6325,11 +6810,14 @@ function ticks(min, max, dayW, minGap) {
6325
6810
  ]) {
6326
6811
  if (step * dayW < minGap) continue;
6327
6812
  let t = Math.ceil(min / DAY) * DAY;
6328
- if (step >= 7) while (new Date(t).getUTCDay() !== 1) t += DAY;
6329
- for (; t <= max; t += step * DAY) out.push({
6330
- t,
6331
- label: dateLabel(t)
6332
- });
6813
+ if (step >= 7) for (let k = 0; k < 7 && new Date(t).getUTCDay() !== 1; k++) t += DAY;
6814
+ for (; t <= max && out.length < MAX_TICKS; t += step * DAY) {
6815
+ if (!Number.isFinite(new Date(t).getTime())) break;
6816
+ out.push({
6817
+ t,
6818
+ label: dateLabel(t)
6819
+ });
6820
+ }
6333
6821
  return out;
6334
6822
  }
6335
6823
  for (const months of [
@@ -6351,7 +6839,7 @@ function ticks(min, max, dayW, minGap) {
6351
6839
  y += Math.floor(m / 12);
6352
6840
  m %= 12;
6353
6841
  const t = Date.UTC(y, m, 1);
6354
- if (t > max) break;
6842
+ if (!Number.isFinite(t) || t > max || out.length >= MAX_TICKS) break;
6355
6843
  out.push({
6356
6844
  t,
6357
6845
  label: months >= 12 ? `${y}` : m === 0 || first ? `${MONTHS[m]} ${y}` : MONTHS[m]
@@ -6368,7 +6856,7 @@ const DENSITY = {
6368
6856
  normal: 2.1,
6369
6857
  loose: 2.7
6370
6858
  };
6371
- const geometry$2 = perPass(function geometry(g, ctx) {
6859
+ const geometry$3 = perPass(function geometry(g, ctx) {
6372
6860
  const { theme, measure, props } = ctx;
6373
6861
  const fs = ctx.fs * .88;
6374
6862
  const rowH = fs * (DENSITY[props.density ?? ""] ?? DENSITY.normal);
@@ -6530,7 +7018,7 @@ function renderGantt(g, box, ctx) {
6530
7018
  if (!g.tasks.length) return "";
6531
7019
  const T = ctx.theme;
6532
7020
  const P = ctx.props;
6533
- const G = geometry$2(g, ctx);
7021
+ const G = geometry$3(g, ctx);
6534
7022
  const { fs, x } = G;
6535
7023
  const X = (t) => box.x + x(t);
6536
7024
  const bottom = box.y + G.h;
@@ -6546,7 +7034,7 @@ function renderGantt(g, box, ctx) {
6546
7034
  text: fill
6547
7035
  } : ink, T)}</text>`;
6548
7036
  const note = (tx, ty, s, fill, end = false) => `<text x="${f$2(tx)}" y="${f$2(ty)}" dominant-baseline="central"${end ? " text-anchor=\"end\"" : ""} font-size="${f$2(fs * .82)}" font-weight="500" fill="${fill}">${esc$1(s)}</text>`;
6549
- if (P.weekends === "show" && G.dayW >= fs * .3) for (let t = G.min; t < G.max; t += DAY) {
7037
+ if (P.weekends === "show" && G.dayW >= fs * .3 && (G.max - G.min) / DAY <= MAX_WEEKEND_DAYS) for (let t = G.min; t < G.max; t += DAY) {
6550
7038
  const wd = new Date(t).getUTCDay();
6551
7039
  if (wd === 0 || wd === 6) out.push(`<rect x="${f$2(X(t))}" y="${f$2(box.y + G.axisH * .8)}" width="${f$2(G.dayW)}" height="${f$2(G.h - G.axisH * .8)}" fill="${grid}" opacity="0.14"/>`);
6552
7040
  }
@@ -6642,7 +7130,7 @@ function renderGantt(g, box, ctx) {
6642
7130
  const key = `${c}|${style}`;
6643
7131
  let id = hatches.get(key);
6644
7132
  if (!id) {
6645
- id = `mg-hatch-${Math.round(box.x)}-${Math.round(box.y)}-${hatches.size}`;
7133
+ id = `${ctx.idPrefix ?? "mg"}-hatch-${Math.round(box.x)}-${Math.round(box.y)}-${hatches.size}`;
6646
7134
  hatches.set(key, id);
6647
7135
  const sc = style === "solid" ? contrast(c) : c;
6648
7136
  out.push(`<defs><pattern id="${id}" patternUnits="userSpaceOnUse" width="7" height="7" patternTransform="rotate(45)"><rect width="3" height="7" fill="${sc}" opacity="${style === "solid" ? .28 : .22}"/></pattern></defs>`);
@@ -6699,7 +7187,7 @@ const gantt$1 = {
6699
7187
  layoutParts: "a task id adds room above its row",
6700
7188
  syntax: "gantt id \"Title\" [today: 2025-01-20] { api \"Build API\": 2025-01-06, 2w }",
6701
7189
  options: {
6702
- today: [],
7190
+ today: "text",
6703
7191
  scale: [
6704
7192
  "day",
6705
7193
  "week",
@@ -6738,7 +7226,7 @@ const gantt$1 = {
6738
7226
  w: 0,
6739
7227
  h: 0
6740
7228
  };
6741
- const G = geometry$2(g, ctx);
7229
+ const G = geometry$3(g, ctx);
6742
7230
  return {
6743
7231
  w: G.w,
6744
7232
  h: G.h
@@ -6760,7 +7248,7 @@ const gantt$1 = {
6760
7248
  }),
6761
7249
  handles(g, box, ctx) {
6762
7250
  if (!g.tasks.length) return [];
6763
- const G = geometry$2(g, ctx);
7251
+ const G = geometry$3(g, ctx);
6764
7252
  return G.rows.flatMap((r) => r.task === void 0 ? [] : [{
6765
7253
  part: g.tasks[r.task].id,
6766
7254
  x: box.x + G.labelW - G.fs * .5,
@@ -6850,15 +7338,6 @@ function parseQuadrant(body, _props, warn) {
6850
7338
  });
6851
7339
  return out;
6852
7340
  }
6853
- /** body index of each point line, in point order */
6854
- function pointLines(body) {
6855
- const out = [];
6856
- body.forEach((raw, i) => {
6857
- const line = raw.trim();
6858
- if (line && !/^(\/\/|#)/.test(line) && !AXIS_RE.test(line) && !Q_RE.test(line) && POINT_RE.test(splitTrailingProps(line, onlyColor)[0])) out.push(i);
6859
- });
6860
- return out;
6861
- }
6862
7341
  /** Replace just the numeric tokens, retaining labels, colour, spacing and percent signs. */
6863
7342
  function movePoint(body, q, point, x, y) {
6864
7343
  const out = [...body];
@@ -6879,7 +7358,7 @@ function movePoint(body, q, point, x, y) {
6879
7358
  }
6880
7359
  return out;
6881
7360
  }
6882
- const geometry$1 = perPass(function geometry(q, ctx) {
7361
+ const geometry$2 = perPass(function geometry(q, ctx) {
6883
7362
  const { theme, measure } = ctx;
6884
7363
  const fs = ctx.fs * .88;
6885
7364
  const size = ctx.offsets.size ?? {
@@ -6901,25 +7380,58 @@ const geometry$1 = perPass(function geometry(q, ctx) {
6901
7380
  y: Math.min(S, Math.max(0, (1 - p.y) * S + o.y))
6902
7381
  };
6903
7382
  });
6904
- const taken = pts.map((p) => ({
7383
+ const taken = [];
7384
+ const cell = fs * 2;
7385
+ const grid = /* @__PURE__ */ new Map();
7386
+ let maxW = 0;
7387
+ let maxH = 0;
7388
+ const take = (a) => {
7389
+ taken.push(a);
7390
+ maxW = Math.max(maxW, a.w);
7391
+ maxH = Math.max(maxH, a.h);
7392
+ const key = Math.floor(a.x / cell) * 1048576 + Math.floor(a.y / cell);
7393
+ const list = grid.get(key);
7394
+ if (list) list.push(a);
7395
+ else grid.set(key, [a]);
7396
+ };
7397
+ for (const p of pts) take({
6905
7398
  x: p.x - r,
6906
7399
  y: p.y - r,
6907
7400
  w: r * 2,
6908
7401
  h: r * 2
6909
- }));
7402
+ });
6910
7403
  q.q.forEach((t, k) => {
6911
7404
  if (!t.text) return;
6912
7405
  const w = segsW(parseInline(t.text), fs, theme.mono, measure, 700);
6913
7406
  const cx = k === 0 || k === 3 ? S * .75 : S * .25;
6914
7407
  const cy = k < 2 ? fs * 1.1 : S / 2 + fs * 1.1;
6915
- taken.push({
7408
+ take({
6916
7409
  x: cx - w / 2,
6917
7410
  y: cy - fs * .6,
6918
7411
  w,
6919
7412
  h: fs * 1.2
6920
7413
  });
6921
7414
  });
6922
- const overlap = (a, b) => Math.max(0, Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x)) * Math.max(0, Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y));
7415
+ /** overlap of `c` with everything taken; stops once it reaches `limit` */
7416
+ const covered = (c, limit) => {
7417
+ let sum = 0;
7418
+ const x1 = Math.floor((c.x + c.w) / cell);
7419
+ const y0 = Math.floor((c.y - maxH) / cell);
7420
+ const y1 = Math.floor((c.y + c.h) / cell);
7421
+ for (let cx = Math.floor((c.x - maxW) / cell); cx <= x1; cx++) for (let cy = y0; cy <= y1; cy++) {
7422
+ const list = grid.get(cx * 1048576 + cy);
7423
+ if (!list) continue;
7424
+ for (const t of list) {
7425
+ const ow = Math.min(c.x + c.w, t.x + t.w) - Math.max(c.x, t.x);
7426
+ if (ow <= 0) continue;
7427
+ const oh = Math.min(c.y + c.h, t.y + t.h) - Math.max(c.y, t.y);
7428
+ if (oh <= 0) continue;
7429
+ sum += ow * oh;
7430
+ if (sum >= limit) return sum;
7431
+ }
7432
+ }
7433
+ return sum;
7434
+ };
6923
7435
  const g = r + 4;
6924
7436
  const labels = q.points.map(() => ({
6925
7437
  x: 0,
@@ -6986,11 +7498,13 @@ const geometry$1 = perPass(function geometry(q, ctx) {
6986
7498
  let bestScore = 1e400;
6987
7499
  for (const c of cands) {
6988
7500
  const out = Math.max(0, -c.x) + Math.max(0, c.x + c.w - S) + Math.max(0, -c.y) + Math.max(0, c.y + c.h - S);
6989
- const score = taken.reduce((a, t) => a + overlap(c, t), 0) + out * h * 4;
7501
+ const limit = bestScore - .01 - out * h * 4;
7502
+ if (limit <= 0) continue;
7503
+ const score = covered(c, limit) + out * h * 4;
6990
7504
  if (score < bestScore - .01) [best, bestScore] = [c, score];
6991
7505
  }
6992
7506
  labels[i] = best;
6993
- taken.push(best);
7507
+ take(best);
6994
7508
  }
6995
7509
  return {
6996
7510
  fs,
@@ -7007,7 +7521,7 @@ const geometry$1 = perPass(function geometry(q, ctx) {
7007
7521
  });
7008
7522
  function renderQuadrant(q, box, ctx) {
7009
7523
  const T = ctx.theme;
7010
- const G = geometry$1(q, ctx);
7524
+ const G = geometry$2(q, ctx);
7011
7525
  const { fs, S } = G;
7012
7526
  const px = box.x + G.left;
7013
7527
  const py = box.y;
@@ -7061,7 +7575,7 @@ const quadrant$1 = {
7061
7575
  syntax: "quadrant id \"Title\" { x-axis Low -> High; q1: Quick wins; Search: 0.3, 0.8 }",
7062
7576
  parse: parseQuadrant,
7063
7577
  measure(q, ctx) {
7064
- const G = geometry$1(q, ctx);
7578
+ const G = geometry$2(q, ctx);
7065
7579
  return {
7066
7580
  w: G.w,
7067
7581
  h: G.h
@@ -7088,14 +7602,14 @@ const quadrant$1 = {
7088
7602
  const s = tone ? ` [${tone}]` : "";
7089
7603
  return [...body, `q${qm[1]}${s}:`];
7090
7604
  }
7091
- } else i = pointLines(body)[q.points.findIndex((p) => p.id === id)];
7605
+ } else i = q.points.find((p) => p.id === id)?.line;
7092
7606
  if (i === void 0) return null;
7093
7607
  const out = [...body];
7094
7608
  out[i] = setLineProp(body[i], HEAD_RE, "color", tone, onlyColor);
7095
7609
  return out;
7096
7610
  }),
7097
7611
  handles(q, box, ctx) {
7098
- const G = geometry$1(q, ctx);
7612
+ const G = geometry$2(q, ctx);
7099
7613
  const px = box.x + G.left;
7100
7614
  return [...q.points.map((p, i) => ({
7101
7615
  part: p.id,
@@ -7130,6 +7644,12 @@ const slug = (s) => s.toLowerCase().replace(/[*~`{}[\]]/g, "").replace(/[^a-z0-9
7130
7644
  const indent = (l) => l.match(/^\s*/)[0].length;
7131
7645
  const skip = (l) => !l.trim();
7132
7646
  const CARD = /^[-*]\s+/;
7647
+ /** a WIP limit, or undefined when blank or not a number of 0 or more */
7648
+ function readLimit(v) {
7649
+ if (v === void 0 || !v.trim()) return void 0;
7650
+ const n = Number(v);
7651
+ return Number.isFinite(n) && n >= 0 ? n : void 0;
7652
+ }
7133
7653
  function parseKanban(body, _props, warn) {
7134
7654
  const cols = [];
7135
7655
  const base = Math.min(...body.filter((l) => !skip(l)).map(indent));
@@ -7191,8 +7711,8 @@ function parseKanban(body, _props, warn) {
7191
7711
  close(card, prev + 1);
7192
7712
  close(cols[cols.length - 1], prev + 1);
7193
7713
  const { text, props } = split(line);
7194
- const limit = props.limit !== void 0 ? Number(props.limit) : void 0;
7195
- if (limit !== void 0 && !(limit >= 0)) warn(i, `kanban: limit expects a number, got "${props.limit}"`);
7714
+ const limit = readLimit(props.limit);
7715
+ if (props.limit !== void 0 && limit === void 0) warn(i, `kanban: limit expects a number of 0 or more, got "${props.limit}"`);
7196
7716
  let id = slug(text);
7197
7717
  if (!id || seen.has(id) || /^[ck]\d+$/.test(id)) id = `c${cols.length + 1}`;
7198
7718
  seen.add(id);
@@ -7202,7 +7722,7 @@ function parseKanban(body, _props, warn) {
7202
7722
  end: -1,
7203
7723
  title: text,
7204
7724
  tone: props.color,
7205
- limit: limit >= 0 ? limit : void 0,
7725
+ limit,
7206
7726
  cards: []
7207
7727
  });
7208
7728
  card = void 0;
@@ -7275,14 +7795,22 @@ function editKanban(body, edit, cols) {
7275
7795
  return done(move(card, to.end, add), [ti, -1]);
7276
7796
  }
7277
7797
  if (!(key === "text" || key === "color" || (card ? CARD_KEYS : ["limit"]).includes(key))) return null;
7798
+ if (value && /[\r\n]/.test(value)) return null;
7799
+ if (key === "limit" && value && readLimit(value) === void 0) return null;
7800
+ const text = key === "text" ? value?.trim() : void 0;
7278
7801
  const out = [...body];
7279
- out[part.start] = rewrite(body[part.start], (text, p) => {
7280
- if (key === "text") return value?.trim() || text;
7802
+ out[part.start] = rewrite(body[part.start], (t, p) => {
7803
+ if (key === "text") return text || t;
7281
7804
  if (value === null || value === "") delete p[key];
7282
7805
  else p[key] = value;
7283
- return text;
7806
+ return t;
7284
7807
  });
7285
- return done(out, here);
7808
+ const change = done(out, here);
7809
+ if (text) {
7810
+ const c = parseKanban(out, {}, () => {})[here[0]];
7811
+ if ((here[1] === void 0 ? c?.title : c?.cards[here[1]]?.text) !== text) return null;
7812
+ }
7813
+ return change;
7286
7814
  }
7287
7815
  case "up":
7288
7816
  case "down": {
@@ -7311,7 +7839,7 @@ function editKanban(body, edit, cols) {
7311
7839
  }
7312
7840
  }
7313
7841
  }
7314
- const geometry = perPass(function geometry(cols, ctx) {
7842
+ const geometry$1 = perPass(function geometry(cols, ctx) {
7315
7843
  const { theme, measure } = ctx;
7316
7844
  const fs = ctx.fs * .88;
7317
7845
  const pad = fs * .7;
@@ -7359,7 +7887,7 @@ const geometry = perPass(function geometry(cols, ctx) {
7359
7887
  function renderKanban(cols, box, ctx) {
7360
7888
  if (!cols.length) return "";
7361
7889
  const T = ctx.theme;
7362
- const G = geometry(cols, ctx);
7890
+ const G = geometry$1(cols, ctx);
7363
7891
  const { fs } = G;
7364
7892
  const out = [];
7365
7893
  const ink = {
@@ -7414,106 +7942,864 @@ function renderKanban(cols, box, ctx) {
7414
7942
  });
7415
7943
  return out.join("");
7416
7944
  }
7417
- // src/setup.ts
7418
- /** Registers the built-in plugins. Imported for its side effect by every entry point. */
7419
- use(...[
7420
- themes,
7421
- charts,
7422
- tables,
7423
- frames,
7424
- legend,
7425
- footer,
7426
- sequence$1,
7427
- timeline$1,
7428
- chart,
7429
- git$1,
7430
- mindmap$1,
7431
- gantt$1,
7432
- quadrant$1,
7433
- {
7945
+ const kanban$1 = {
7946
+ name: "kanban",
7947
+ panels: [{
7434
7948
  name: "kanban",
7435
- panels: [{
7436
- name: "kanban",
7437
- guide: "a line at the outer indent is a column `Todo [color, limit: 3]`, `- text [owner: ana, ticket: X-1, priority: low|medium|high, color]` a card, deeper lines its details.",
7438
- layoutParts: "a column by its title (lower case, `-` for spaces), else `c<n>`, adds room before it",
7439
- syntax: "kanban id \"Title\" { Todo [gray]\n - Write docs [owner: ana] }",
7440
- parse: parseKanban,
7441
- measure(cols, ctx) {
7442
- if (!cols.length) return {
7443
- w: 0,
7444
- h: 0
7445
- };
7446
- const G = geometry(cols, ctx);
7447
- return {
7448
- w: G.w,
7449
- h: G.h
7450
- };
7451
- },
7452
- render: renderKanban,
7453
- parts(cols) {
7454
- const colIds = cols.map((c) => c.id);
7455
- return cols.flatMap((c) => [{
7456
- id: c.id,
7457
- label: c.title,
7458
- kind: "column",
7459
- tone: c.tone,
7460
- fields: {
7461
- text: [],
7462
- limit: []
7463
- },
7464
- values: {
7465
- text: c.title,
7466
- ...c.limit !== void 0 && { limit: String(c.limit) }
7467
- },
7468
- actions: [
7469
- "up",
7470
- "down",
7471
- "remove",
7472
- "add"
7473
- ],
7474
- adds: "card"
7475
- }, ...c.cards.map((k) => ({
7476
- id: k.id,
7477
- label: k.text,
7478
- kind: "card",
7479
- tone: k.tone,
7480
- fields: {
7481
- text: [],
7482
- column: colIds,
7483
- owner: [],
7484
- ticket: [],
7485
- priority: [
7486
- "",
7487
- "low",
7488
- "medium",
7489
- "high"
7490
- ]
7491
- },
7492
- values: {
7493
- text: k.text,
7494
- column: c.id,
7495
- ...k.props
7496
- },
7497
- actions: [
7498
- "up",
7499
- "down",
7500
- "remove"
7949
+ guide: "a line at the outer indent is a column `Todo [color, limit: 3]`, `- text [owner: ana, ticket: X-1, priority: low|medium|high, color]` a card, deeper lines its details.",
7950
+ layoutParts: "a column by its title (lower case, `-` for spaces), else `c<n>`, adds room before it",
7951
+ syntax: "kanban id \"Title\" { Todo [gray]\n - Write docs [owner: ana] }",
7952
+ parse: parseKanban,
7953
+ measure(cols, ctx) {
7954
+ if (!cols.length) return {
7955
+ w: 0,
7956
+ h: 0
7957
+ };
7958
+ const G = geometry$1(cols, ctx);
7959
+ return {
7960
+ w: G.w,
7961
+ h: G.h
7962
+ };
7963
+ },
7964
+ render: renderKanban,
7965
+ parts(cols) {
7966
+ const colIds = cols.map((c) => c.id);
7967
+ return cols.flatMap((c) => [{
7968
+ id: c.id,
7969
+ label: c.title,
7970
+ kind: "column",
7971
+ tone: c.tone,
7972
+ fields: {
7973
+ text: [],
7974
+ limit: []
7975
+ },
7976
+ values: {
7977
+ text: c.title,
7978
+ ...c.limit !== void 0 && { limit: String(c.limit) }
7979
+ },
7980
+ actions: [
7981
+ "up",
7982
+ "down",
7983
+ "remove",
7984
+ "add"
7985
+ ],
7986
+ adds: "card"
7987
+ }, ...c.cards.map((k) => ({
7988
+ id: k.id,
7989
+ label: k.text,
7990
+ kind: "card",
7991
+ tone: k.tone,
7992
+ fields: {
7993
+ text: [],
7994
+ column: colIds,
7995
+ owner: [],
7996
+ ticket: [],
7997
+ priority: [
7998
+ "",
7999
+ "low",
8000
+ "medium",
8001
+ "high"
7501
8002
  ]
7502
- }))]);
8003
+ },
8004
+ values: {
8005
+ text: k.text,
8006
+ column: c.id,
8007
+ ...k.props
8008
+ },
8009
+ actions: [
8010
+ "up",
8011
+ "down",
8012
+ "remove"
8013
+ ]
8014
+ }))]);
8015
+ },
8016
+ editPart: editKanban,
8017
+ adds: "column",
8018
+ handles(cols, box, ctx) {
8019
+ if (!cols.length) return [];
8020
+ const G = geometry$1(cols, ctx);
8021
+ return cols.slice(1).map((c, k) => ({
8022
+ part: c.id,
8023
+ x: box.x + G.at[k + 1],
8024
+ y: box.y + G.headH / 2,
8025
+ axis: "x",
8026
+ title: `move ${c.title}`
8027
+ }));
8028
+ }
8029
+ }]
8030
+ };
8031
+ // src/plugins/treeview.ts
8032
+ const STATUS_TONE = {
8033
+ added: "green",
8034
+ modified: "amber",
8035
+ deleted: "red",
8036
+ renamed: "blue",
8037
+ ignored: "gray"
8038
+ };
8039
+ const STATUSES = Object.keys(STATUS_TONE);
8040
+ const STATUS_MARK = {
8041
+ added: "A",
8042
+ modified: "M",
8043
+ deleted: "D",
8044
+ renamed: "R",
8045
+ ignored: ""
8046
+ };
8047
+ const FLAGS = [
8048
+ "collapsed",
8049
+ "highlight",
8050
+ "dim",
8051
+ "folder",
8052
+ "file",
8053
+ ...STATUSES
8054
+ ];
8055
+ const KEYS = [
8056
+ "color",
8057
+ "icon",
8058
+ "badge",
8059
+ "note",
8060
+ "size",
8061
+ "status"
8062
+ ];
8063
+ /** the icons drawn as vector glyphs; anything else in `icon:` is shown as text */
8064
+ const TREE_ICONS = [
8065
+ "folder",
8066
+ "folder-open",
8067
+ "file",
8068
+ "code",
8069
+ "doc",
8070
+ "image",
8071
+ "config",
8072
+ "lock",
8073
+ "package",
8074
+ "git",
8075
+ "database",
8076
+ "test",
8077
+ "font",
8078
+ "media",
8079
+ "terminal",
8080
+ "yuhwa"
8081
+ ];
8082
+ const PREFIX = /^(?:[ \t │┃┆┊╎]|[├└┣┗╰][─━]*|[|`+\\]-+|\|)*/u;
8083
+ const BULLET = /^[-*+]\s+/;
8084
+ const TRAILING_PROPS = /\s\[([^\]]*)\]\s*$/;
8085
+ const NOTE = /(?::\s+|\s+#\s+|:$)/;
8086
+ const TREE_SUMMARY = /^\d+ director(?:y|ies)(?:, \d+ files?)?$/;
8087
+ const MATCH = /^match\s+(\S+)\s+\[([^\]]*)\]\s*$/;
8088
+ const ELLIPSIS = /^(?:\.{3}|…)$/;
8089
+ /**
8090
+ * `*`, `**`, `?` and `{a,b}` over a name or a `/` path, case-insensitive:
8091
+ * `*` and `?` stay inside one segment, `**` crosses `/`, and `**` right
8092
+ * before a `/` may also match nothing. Run as a state set, not a backtracking regex, so it is linear in
8093
+ * the name whatever the glob.
8094
+ */
8095
+ function compileGlob(glob) {
8096
+ const states = [];
8097
+ const add = (st) => states.push(st) - 1;
8098
+ let i = 0;
8099
+ const seq = (inBraces) => {
8100
+ const alts = [[]];
8101
+ while (i < glob.length) {
8102
+ const c = glob[i++];
8103
+ const cur = alts[alts.length - 1];
8104
+ if (c === "*") {
8105
+ if (glob[i] === "*") {
8106
+ i++;
8107
+ if (glob[i] === "/") {
8108
+ i++;
8109
+ cur.push({ t: "**/" });
8110
+ } else cur.push({ t: "**" });
8111
+ } else cur.push({ t: "*" });
8112
+ } else if (c === "?") cur.push({ t: "?" });
8113
+ else if (c === "{") cur.push({
8114
+ t: "alt",
8115
+ alts: seq(true)
8116
+ });
8117
+ else if (c === "}" && inBraces) return alts;
8118
+ else if (c === "," && inBraces) alts.push([]);
8119
+ else cur.push({
8120
+ t: "lit",
8121
+ c: c.toLowerCase()
8122
+ });
8123
+ }
8124
+ return alts;
8125
+ };
8126
+ const build = (items, next) => {
8127
+ for (let k = items.length - 1; k >= 0; k--) {
8128
+ const it = items[k];
8129
+ if (it.t === "lit") next = add({
8130
+ k: "char",
8131
+ c: it.c,
8132
+ next
8133
+ });
8134
+ else if (it.t === "?") next = add({
8135
+ k: "seg",
8136
+ next
8137
+ });
8138
+ else if (it.t === "*" || it.t === "**") {
8139
+ const fork = add({
8140
+ k: "split",
8141
+ outs: []
8142
+ });
8143
+ const loop = add({
8144
+ k: it.t === "*" ? "seg" : "any",
8145
+ next: fork
8146
+ });
8147
+ states[fork].outs.push(loop, next);
8148
+ next = fork;
8149
+ } else if (it.t === "**/") {
8150
+ const inner = add({
8151
+ k: "split",
8152
+ outs: []
8153
+ });
8154
+ const loop = add({
8155
+ k: "any",
8156
+ next: inner
8157
+ });
8158
+ const slash = add({
8159
+ k: "char",
8160
+ c: "/",
8161
+ next
8162
+ });
8163
+ states[inner].outs.push(loop, slash);
8164
+ next = add({
8165
+ k: "split",
8166
+ outs: [inner, next]
8167
+ });
8168
+ } else next = add({
8169
+ k: "split",
8170
+ outs: it.alts.map((a) => build(a, next))
8171
+ });
8172
+ }
8173
+ return next;
8174
+ };
8175
+ const top = seq(false);
8176
+ const start = build(top.length > 1 ? [{
8177
+ t: "alt",
8178
+ alts: top
8179
+ }] : top[0], add({ k: "end" }));
8180
+ const close = (from) => {
8181
+ const seen = /* @__PURE__ */ new Set();
8182
+ const todo = [...from];
8183
+ while (todo.length) {
8184
+ const n = todo.pop();
8185
+ if (seen.has(n)) continue;
8186
+ seen.add(n);
8187
+ const st = states[n];
8188
+ if (st.k === "split") todo.push(...st.outs);
8189
+ }
8190
+ return seen;
8191
+ };
8192
+ const first = close([start]);
8193
+ return { test(s) {
8194
+ let cur = first;
8195
+ const low = s.toLowerCase();
8196
+ for (let k = 0; k < low.length; k++) {
8197
+ const ch = low[k];
8198
+ const next = [];
8199
+ for (const n of cur) {
8200
+ const st = states[n];
8201
+ if (st.k === "split" || st.k === "end") continue;
8202
+ if (st.k === "char" ? st.c === ch : st.k === "seg" ? ch !== "/" : true) next.push(st.next);
8203
+ }
8204
+ if (!next.length) return false;
8205
+ cur = close(next);
8206
+ }
8207
+ for (const n of cur) if (states[n].k === "end") return true;
8208
+ return false;
8209
+ } };
8210
+ }
8211
+ /** `s` with every closed `[...]` blanked out, so a `: ` inside props is not a note */
8212
+ function outsideBrackets(s) {
8213
+ return s.replace(/\[[^\]]*\]/g, (m) => "x".repeat(m.length));
8214
+ }
8215
+ const bare$1 = (text) => text.replace(/\/$/, "");
8216
+ function checkProps(props, warn) {
8217
+ for (const k of Object.keys(props)) if (!FLAGS.includes(k) && !KEYS.includes(k)) warn(`treeview: unknown prop "${k}" (use a colour, ${[...KEYS.slice(1), ...FLAGS].join(", ")})`);
8218
+ if (props.status && !STATUSES.includes(props.status)) warn(`treeview: unknown status "${props.status}" (use one of: ${STATUSES.join(", ")})`);
8219
+ if (props.color && !isSafeCss(props.color)) delete props.color;
8220
+ }
8221
+ function parseTreeview(body, _props, warn) {
8222
+ const roots = [];
8223
+ const stack = [];
8224
+ const rules = [];
8225
+ const own = /* @__PURE__ */ new Map();
8226
+ body.forEach((raw, i) => {
8227
+ if (!raw.trim() || /^\s*#/.test(raw)) return;
8228
+ const rule = raw.trim().match(MATCH);
8229
+ if (rule) {
8230
+ const props = parseProps(rule[2]);
8231
+ checkProps(props, (m) => warn(i, m));
8232
+ const glob = rule[1];
8233
+ rules.push({
8234
+ re: compileGlob(bare$1(glob)),
8235
+ path: bare$1(glob).includes("/"),
8236
+ folders: glob.endsWith("/"),
8237
+ props,
8238
+ line: i,
8239
+ glob,
8240
+ hits: 0
8241
+ });
8242
+ return;
8243
+ }
8244
+ const prefix = raw.match(PREFIX)[0];
8245
+ let rest = raw.slice(prefix.length);
8246
+ const bullet = rest.match(BULLET);
8247
+ if (bullet) rest = rest.slice(bullet[0].length);
8248
+ const base = raw.length - rest.trimStart().length;
8249
+ rest = rest.trim();
8250
+ if (!rest || TREE_SUMMARY.test(rest)) return;
8251
+ const indent = (prefix + (bullet?.[0] ?? "")).replace(/\t/g, " ").length;
8252
+ let props = {};
8253
+ let propSpan;
8254
+ const pm = rest.match(TRAILING_PROPS);
8255
+ if (pm) {
8256
+ props = parseProps(pm[1]);
8257
+ propSpan = [base + pm.index, base + rest.length];
8258
+ rest = rest.slice(0, pm.index).trimEnd();
8259
+ }
8260
+ let note;
8261
+ const nm = outsideBrackets(rest).match(NOTE);
8262
+ if (nm && nm.index > 0) {
8263
+ note = rest.slice(nm.index + nm[0].length).trim() || void 0;
8264
+ rest = rest.slice(0, nm.index).trimEnd();
8265
+ const hp = rest.match(TRAILING_PROPS);
8266
+ if (hp && !pm) {
8267
+ props = parseProps(hp[1]);
8268
+ propSpan = [base + hp.index, base + rest.length];
8269
+ rest = rest.slice(0, hp.index).trimEnd();
8270
+ }
8271
+ }
8272
+ checkProps(props, (m) => warn(i, m));
8273
+ const node = {
8274
+ text: rest,
8275
+ collapsed: false,
8276
+ highlight: false,
8277
+ dim: false,
8278
+ line: i,
8279
+ children: []
8280
+ };
8281
+ if (propSpan) node.propSpan = propSpan;
8282
+ own.set(node, {
8283
+ props,
8284
+ note
8285
+ });
8286
+ while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
8287
+ (stack.length ? stack[stack.length - 1].node.children : roots).push(node);
8288
+ stack.push({
8289
+ indent,
8290
+ node
8291
+ });
8292
+ });
8293
+ const resolve = (list, dir) => {
8294
+ for (const n of list) {
8295
+ const path = dir + bare$1(n.text);
8296
+ const { props: mine, note } = own.get(n);
8297
+ const folder = mine.folder === "true" || mine.file !== "true" && (n.children.length > 0 || n.text.endsWith("/"));
8298
+ const props = {};
8299
+ for (const r of rules) if ((!r.folders || folder) && r.re.test(r.path ? path : bare$1(n.text))) {
8300
+ r.hits++;
8301
+ Object.assign(props, r.props);
8302
+ }
8303
+ if (mine.folder === "true") delete props.file;
8304
+ if (mine.file === "true") delete props.folder;
8305
+ if (STATUSES.some((s) => mine[s] === "true") || mine.status) {
8306
+ for (const s of STATUSES) delete props[s];
8307
+ delete props.status;
8308
+ }
8309
+ Object.assign(props, mine);
8310
+ n.note = mine.note ?? note ?? props.note;
8311
+ n.tone = props.color;
8312
+ n.icon = props.icon;
8313
+ n.badge = props.badge;
8314
+ n.size = props.size;
8315
+ n.status = STATUSES.find((s) => props[s] === "true") ?? (STATUSES.includes(props.status) ? props.status : void 0);
8316
+ n.collapsed = props.collapsed === "true";
8317
+ n.highlight = props.highlight === "true";
8318
+ n.dim = props.dim === "true";
8319
+ n.type = props.folder === "true" ? "folder" : props.file === "true" ? "file" : void 0;
8320
+ resolve(n.children, path + "/");
8321
+ }
8322
+ };
8323
+ resolve(roots, "");
8324
+ for (const r of rules) if (!r.hits) warn(r.line, `treeview: "match ${r.glob}" matches no entry`);
8325
+ return roots;
8326
+ }
8327
+ /** every entry in reading order */
8328
+ function walk(list, out = []) {
8329
+ for (const n of list) {
8330
+ out.push(n);
8331
+ walk(n.children, out);
8332
+ }
8333
+ return out;
8334
+ }
8335
+ const isFolder = (n) => n.type === "folder" || n.type !== "file" && (n.children.length > 0 || n.text.endsWith("/"));
8336
+ const ext = (base) => {
8337
+ const dot = base.lastIndexOf(".");
8338
+ return dot > 0 ? base.slice(dot + 1) : "";
8339
+ };
8340
+ const BY_EXT = {};
8341
+ const byExt = (tone, icon, exts) => {
8342
+ for (const e of exts.split(" ")) BY_EXT[e] = [icon, tone];
8343
+ };
8344
+ byExt("blue", "code", "ts tsx mts cts py c cpp");
8345
+ byExt("amber", "code", "js jsx mjs cjs zig");
8346
+ byExt("green", "code", "vue");
8347
+ byExt("orange", "code", "svelte rs swift html");
8348
+ byExt("purple", "code", "astro kt h cs css");
8349
+ byExt("cyan", "code", "go");
8350
+ byExt("red", "code", "java rb");
8351
+ byExt("indigo", "code", "php lua");
8352
+ byExt("pink", "code", "scss");
8353
+ byExt("green", "terminal", "sh bash zsh fish ps1");
8354
+ byExt("blue", "doc", "md");
8355
+ byExt("amber", "doc", "mdx");
8356
+ byExt("gray", "doc", "txt rst");
8357
+ byExt("red", "doc", "pdf");
8358
+ byExt("green", "doc", "csv");
8359
+ byExt("purple", "image", "png jpg jpeg gif webp avif ico");
8360
+ byExt("amber", "image", "svg");
8361
+ byExt("red", "font", "woff woff2 ttf otf");
8362
+ byExt("pink", "media", "mp3 wav ogg flac mp4 mov webm mkv");
8363
+ byExt("amber", "config", "json");
8364
+ byExt("purple", "config", "yaml yml");
8365
+ byExt("gray", "config", "toml ini");
8366
+ byExt("orange", "config", "xml");
8367
+ byExt("slate", "config", "env");
8368
+ byExt("cyan", "database", "sql db sqlite");
8369
+ byExt("amber", "package", "zip tar gz");
8370
+ byExt("pink", "yuhwa", "yu yuhwa");
8371
+ /** folders that hold generated or vendored files get a grey icon */
8372
+ const QUIET_FOLDERS = /^(node_modules|dist|build|out|target|coverage|vendor|\.git|\.next|\.nuxt|\.cache|__pycache__)$/;
8373
+ /** icon and tone for a file by its name */
8374
+ function fileIcon(name) {
8375
+ const base = bare$1(name).toLowerCase();
8376
+ if (/(^|\.)lock$|-lock\.(json|yaml)$|^lockfile$/.test(base)) return ["lock", "gray"];
8377
+ if (/^\.git(ignore|attributes|modules|keep)?$/.test(base)) return ["git", "orange"];
8378
+ if (/^(package\.json|cargo\.toml|go\.mod|pyproject\.toml|gemfile|composer\.json|pom\.xml|build\.gradle)$/.test(base)) return ["package", "red"];
8379
+ if (/^(dockerfile|makefile|\.env.*|\.editorconfig|\.npmrc|\.prettierrc.*|tsconfig.*\.json)$/.test(base)) return ["config", "slate"];
8380
+ if (/^(readme|license|licence|changelog|contributing)(\..*)?$/.test(base)) return ["doc", "blue"];
8381
+ if (/\.(test|spec)\.[a-z]+$|^test_.*\.py$|_test\.go$/.test(base)) return ["test", "green"];
8382
+ return BY_EXT[ext(base)] ?? ["file", void 0];
8383
+ }
8384
+ /** the glyphs, drawn in a 16 × 16 box */
8385
+ const PAGE = "M3.5 1.5h6l3.5 3.5v9.5h-9.5z";
8386
+ const FOLD = "M9.5 1.5v3.5h3.5";
8387
+ function glyph(name, fill, ink) {
8388
+ const line = (d) => `<path d="${d}" fill="none" stroke="${ink}"/>`;
8389
+ const page = `<path d="${PAGE}" fill="${fill}" stroke="${ink}"/>${line(FOLD)}`;
8390
+ switch (name) {
8391
+ case "folder": return `<path d="M1.5 4.5a1 1 0 0 1 1-1h3.6l1.6 1.8h5.8a1 1 0 0 1 1 1v6.7a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1z" fill="${fill}" stroke="${ink}"/>`;
8392
+ case "folder-open": return `<path d="M1.5 12.5v-8a1 1 0 0 1 1-1h3.6l1.6 1.8h5a1 1 0 0 1 1 1v1.2" fill="none" stroke="${ink}"/><path d="M3.4 7.5h11.3l-1.9 6H1.5z" fill="${fill}" stroke="${ink}" stroke-linejoin="round"/>`;
8393
+ case "code": return page + line("M6.6 8.2l-1.6 1.9 1.6 1.9M9.4 8.2l1.6 1.9-1.6 1.9");
8394
+ case "doc": return page + line("M5.8 8h4.4M5.8 10.2h4.4M5.8 12.4h2.8");
8395
+ case "image": return page + `<path d="M5 13l2.1-2.8 1.5 1.6 1.4-1.8L11.8 13z" fill="${ink}"/><circle cx="6.4" cy="7.8" r="1" fill="${ink}"/>`;
8396
+ case "config": return page + line("M5.5 8.6h5M5.5 11.6h5") + `<circle cx="7" cy="8.6" r="1.1" fill="${fill}" stroke="${ink}"/><circle cx="9" cy="11.6" r="1.1" fill="${fill}" stroke="${ink}"/>`;
8397
+ case "lock": return `<rect x="3.5" y="7" width="9" height="7.5" rx="1.3" fill="${fill}" stroke="${ink}"/>${line("M5.5 7V5a2.5 2.5 0 0 1 5 0v2")}<circle cx="8" cy="10.7" r="1" fill="${ink}"/>`;
8398
+ case "package": return `<path d="M8 1.8l5.6 3.1v6.2L8 14.2l-5.6-3.1V4.9z" fill="${fill}" stroke="${ink}" stroke-linejoin="round"/>${line("M2.4 4.9L8 8l5.6-3.1M8 8v6.2")}`;
8399
+ case "git": return line("M5 5.6v4.8M11 7.6c0 2.4-6 1.6-6 2.8") + [
8400
+ [5, 4],
8401
+ [5, 12],
8402
+ [11, 6]
8403
+ ].map(([x, y]) => `<circle cx="${x}" cy="${y}" r="1.6" fill="${fill}" stroke="${ink}"/>`).join("");
8404
+ case "database": return `<path d="M3 4v8c0 1.1 2.2 2 5 2s5-.9 5-2V4" fill="${fill}" stroke="${ink}"/><ellipse cx="8" cy="4" rx="5" ry="2" fill="${fill}" stroke="${ink}"/>` + line("M3 8c0 1.1 2.2 2 5 2s5-.9 5-2");
8405
+ case "test": return `<path d="M6.4 2v4.3L2.9 12.4a1.2 1.2 0 0 0 1 1.8h8.2a1.2 1.2 0 0 0 1-1.8L9.6 6.3V2" fill="${fill}" stroke="${ink}"/>` + line("M5.4 2h5.2M4.6 9.8h6.8");
8406
+ case "font": return page + line("M5.5 13l2.5-6 2.5 6M6.4 11h3.2");
8407
+ case "media": return page + `<path d="M6.6 7.8l4 2.4-4 2.4z" fill="${ink}"/>`;
8408
+ case "terminal": return `<rect x="1.5" y="2.5" width="13" height="11" rx="1.5" fill="${fill}" stroke="${ink}"/>` + line("M4.5 6.3l2.2 1.9-2.2 1.9M8.3 10.6h3.2");
8409
+ case "yuhwa": return page + `<circle cx="6.2" cy="9" r="1.2" fill="${ink}"/><circle cx="9.8" cy="11.6" r="1.2" fill="${ink}"/>${line("M7.1 9.7l1.8 1.3")}`;
8410
+ default: return page;
8411
+ }
8412
+ }
8413
+ const EMOJI = {
8414
+ folder: "📁",
8415
+ "folder-open": "📂",
8416
+ image: "🖼️",
8417
+ lock: "🔒",
8418
+ package: "📦",
8419
+ database: "🗄️",
8420
+ config: "⚙️",
8421
+ git: "🔀",
8422
+ test: "🧪",
8423
+ font: "🔤",
8424
+ media: "🎬",
8425
+ terminal: "💻"
8426
+ };
8427
+ function entryParts(nodes) {
8428
+ const counts = /* @__PURE__ */ new Map();
8429
+ for (const n of nodes) counts.set(bare$1(n.text), (counts.get(bare$1(n.text)) ?? 0) + 1);
8430
+ return nodes.map((n, i) => /^[\w.-]+$/.test(bare$1(n.text)) && counts.get(bare$1(n.text)) === 1 && !/^n\d+$/.test(bare$1(n.text)) ? bare$1(n.text) : `n${i + 1}`);
8431
+ }
8432
+ const num = (v) => v !== void 0 && /^\d+(\.\d+)?$/.test(v) ? Number(v) : void 0;
8433
+ const on = (v) => v !== void 0 && v !== "false";
8434
+ const pick = (v, values, fallback) => values.includes(v) ? v : fallback;
8435
+ const colorProp = (v) => v && isSafeCss(v) ? v : void 0;
8436
+ const COLLATOR = new Intl.Collator("en", {
8437
+ numeric: true,
8438
+ sensitivity: "base"
8439
+ });
8440
+ /** the status a folder shows for the changes under it: one kind keeps its colour, a mix reads as modified */
8441
+ function rollupOf(n, memo) {
8442
+ let set = memo.get(n);
8443
+ if (set) return set;
8444
+ set = /* @__PURE__ */ new Set();
8445
+ for (const c of n.children) {
8446
+ if (c.status && c.status !== "ignored") set.add(c.status);
8447
+ for (const s of rollupOf(c, memo)) set.add(s);
8448
+ }
8449
+ memo.set(n, set);
8450
+ return set;
8451
+ }
8452
+ const ICONS = [
8453
+ "color",
8454
+ "mono",
8455
+ "emoji",
8456
+ "none"
8457
+ ];
8458
+ const LINES = [
8459
+ "solid",
8460
+ "rounded",
8461
+ "dashed",
8462
+ "dotted",
8463
+ "none"
8464
+ ];
8465
+ const SORTS = [
8466
+ "none",
8467
+ "name",
8468
+ "folders"
8469
+ ];
8470
+ const COUNTS = [
8471
+ "collapsed",
8472
+ "all",
8473
+ "none"
8474
+ ];
8475
+ const MARKS = [
8476
+ "letter",
8477
+ "dot",
8478
+ "none"
8479
+ ];
8480
+ const geometry = perPass(function geometry(roots, ctx) {
8481
+ const { theme, measure, props } = ctx;
8482
+ const fs = ctx.fs * .92;
8483
+ const icons = pick(props.icons, ICONS, ICONS[0]);
8484
+ const sort = pick(props.sort, SORTS, SORTS[0]);
8485
+ const counts = props.counts === "true" ? "all" : pick(props.counts, COUNTS, COUNTS[0]);
8486
+ const marks = pick(props.marks, MARKS, MARKS[0]);
8487
+ const rollup = props.rollup !== "false" && marks !== "none";
8488
+ const compact = on(props.compact);
8489
+ const chevrons = on(props.chevrons);
8490
+ const maxDepth = num(props.depth);
8491
+ const folderTone = colorProp(props["folder-color"]) ?? "amber";
8492
+ const rowH = fs * ({
8493
+ compact: 1.45,
8494
+ relaxed: 2.15
8495
+ }[props.spacing] ?? 1.8);
8496
+ const iconW = icons === "none" ? 0 : fs * 1.1;
8497
+ const chevW = chevrons ? fs * .85 : 0;
8498
+ const gap = icons === "none" ? 0 : fs * .45;
8499
+ const anchor = chevW + (iconW ? iconW / 2 : fs * .3);
8500
+ const indent = num(props.indent) ?? anchor + fs * .75;
8501
+ const all = walk(roots);
8502
+ const parts = entryParts(all);
8503
+ const partOf = new Map(all.map((n, i) => [n, parts[i]]));
8504
+ const memo = /* @__PURE__ */ new Map();
8505
+ const sizes = /* @__PURE__ */ new Map();
8506
+ const descendants = (n) => {
8507
+ let c = sizes.get(n);
8508
+ if (c === void 0) sizes.set(n, c = n.children.reduce((s, k) => s + 1 + descendants(k), 0));
8509
+ return c;
8510
+ };
8511
+ const smallFs = fs * .7;
8512
+ const pillW = (t) => measure(t, smallFs, 600, theme.mono) + fs * .8;
8513
+ const ordered = (list) => {
8514
+ if (sort === "none") return list;
8515
+ const more = (n) => Number(ELLIPSIS.test(n.text));
8516
+ return [...list].sort((a, b) => more(a) - more(b) || (sort === "folders" ? Number(isFolder(b)) - Number(isFolder(a)) : 0) || COLLATOR.compare(a.text, b.text));
8517
+ };
8518
+ const plain = (n) => !n.note && !n.badge && !n.size && !n.status && !n.highlight && !n.dim && !n.icon && !n.tone && !n.collapsed;
8519
+ const rows = [];
8520
+ const visit = (list, depth, parent) => {
8521
+ const sorted = ordered(list);
8522
+ sorted.forEach((top, k) => {
8523
+ let n = top;
8524
+ const closedAt = (e) => e.collapsed || maxDepth !== void 0 && depth + 1 >= maxDepth;
8525
+ const chain = [bare$1(n.text)];
8526
+ while (compact && n.children.length === 1 && isFolder(n) && isFolder(n.children[0]) && plain(n) && !closedAt(n)) {
8527
+ n = n.children[0];
8528
+ chain.push(bare$1(n.text));
8529
+ }
8530
+ const folder = isFolder(n);
8531
+ const more = !folder && ELLIPSIS.test(n.text);
8532
+ const open = folder && !closedAt(n) && n.children.length > 0;
8533
+ let label = more ? "…" : chain.length > 1 ? chain.join("/") + (n.text.endsWith("/") ? "/" : "") : n.text;
8534
+ if (props.slashes === "false") label = label.replace(/\/$/, "");
8535
+ else if (props.slashes === "true" && folder && !label.endsWith("/")) label += "/";
8536
+ const [auto, autoTone] = folder ? [open ? "folder-open" : "folder", QUIET_FOLDERS.test(bare$1(n.text)) ? "gray" : folderTone] : fileIcon(n.text);
8537
+ const iconName = n.icon ?? auto;
8538
+ const glyphName = TREE_ICONS.includes(iconName) ? iconName : void 0;
8539
+ const weight = folder ? 600 : 400;
8540
+ const count = folder && (counts === "all" || counts === "collapsed" && !open) && n.children.length ? String(descendants(n)) : void 0;
8541
+ const changes = folder && rollup && !n.status ? rollupOf(n, memo) : void 0;
8542
+ const r = {
8543
+ node: n,
8544
+ part: partOf.get(n),
8545
+ depth,
8546
+ folder,
8547
+ open,
8548
+ last: k === sorted.length - 1,
8549
+ parent,
8550
+ more,
8551
+ label,
8552
+ icon: glyphName ?? "file",
8553
+ iconTone: n.tone ?? (n.status ? STATUS_TONE[n.status] : void 0) ?? (n.icon ? void 0 : autoTone),
8554
+ iconText: glyphName ? void 0 : n.icon,
8555
+ textW: segsW(parseInline(label), fs, theme.mono, measure, weight),
8556
+ badgeW: n.badge ? measure(n.badge, fs * .72, 600, theme.mono) + fs * .9 : 0,
8557
+ count,
8558
+ countW: count ? pillW(count) : 0,
8559
+ rollup: changes?.size ? changes.size === 1 ? [...changes][0] : "modified" : void 0,
8560
+ sizeW: n.size ? measure(n.size, fs * .82, 400, theme.mono) : 0,
8561
+ y: rows.length * rowH,
8562
+ x: depth * indent
8563
+ };
8564
+ rows.push(r);
8565
+ if (open) visit(n.children, depth + 1, r);
8566
+ });
8567
+ };
8568
+ visit(roots, 0);
8569
+ const textX = (r) => r.more ? r.x + chevW : r.x + chevW + iconW + gap;
8570
+ const badgeX = (r) => textX(r) + r.textW + fs * .5;
8571
+ const countX = (r) => (r.badgeW ? badgeX(r) + r.badgeW : textX(r) + r.textW) + fs * .45;
8572
+ const nameEnd = (r) => r.countW ? countX(r) + r.countW : r.badgeW ? badgeX(r) + r.badgeW : textX(r) + r.textW;
8573
+ const inline = props.notes === "inline";
8574
+ const noteFs = fs * .88;
8575
+ let widest = 0;
8576
+ for (const r of rows) widest = Math.max(widest, nameEnd(r));
8577
+ const noteCol = widest + fs * 1.6;
8578
+ const noteX = (r) => inline ? nameEnd(r) + fs * .9 : noteCol;
8579
+ const noteW = (r) => r.node.note ? segsW(parseInline(r.node.note), noteFs, theme.mono, measure, 400) : 0;
8580
+ const mark = (r) => marks !== "none" && (r.node.status && STATUS_MARK[r.node.status] !== "" || r.rollup !== void 0);
8581
+ const anyMark = rows.some(mark);
8582
+ let contentW = fs * 4;
8583
+ for (const r of rows) contentW = Math.max(contentW, r.node.note ? noteX(r) + noteW(r) : nameEnd(r));
8584
+ const sizeW = Math.max(0, ...rows.map((r) => r.sizeW));
8585
+ const sizeRight = sizeW ? contentW + fs * 1.4 + sizeW : contentW;
8586
+ const markX = sizeRight + fs * 1.2;
8587
+ return {
8588
+ rows,
8589
+ fs,
8590
+ smallFs,
8591
+ noteFs,
8592
+ rowH,
8593
+ icons,
8594
+ marks,
8595
+ iconW,
8596
+ chevW,
8597
+ anchor,
8598
+ textX,
8599
+ badgeX,
8600
+ countX,
8601
+ noteX,
8602
+ sizeRight,
8603
+ markX,
8604
+ mark,
8605
+ w: anyMark ? markX + fs * .8 : sizeRight,
8606
+ h: rows.length * rowH
8607
+ };
8608
+ });
8609
+ const dash = (s) => {
8610
+ const d = dashFor(s, 1);
8611
+ return d ? ` stroke-dasharray="${d}"${s === "dotted" ? " stroke-linecap=\"round\"" : ""}` : "";
8612
+ };
8613
+ function renderTreeview(roots, box, ctx) {
8614
+ if (!roots.length) return "";
8615
+ const T = ctx.theme;
8616
+ const g = geometry(roots, ctx);
8617
+ const { props } = ctx;
8618
+ const X = (v) => box.x + v;
8619
+ const Y = (v) => box.y + v;
8620
+ const bands = [];
8621
+ const guides = [];
8622
+ const out = [];
8623
+ const lines = pick(props.lines, LINES, LINES[0]);
8624
+ const ink = (c, fallback) => c ? inkColor(c, T, fallback) : fallback;
8625
+ const guide = ink(colorProp(props["line-color"]), T.edge.stroke);
8626
+ const highlightTone = colorProp(props["highlight-color"]);
8627
+ const badgeTone = colorProp(props["badge-color"]) ?? "blue";
8628
+ const noteInk = ink(colorProp(props["note-color"]), T.node.sub);
8629
+ const strikeInk = ink(colorProp(props["strike-color"]), T.node.sub);
8630
+ const strikeW = num(props["strike-width"]) ?? Math.max(1.25, g.fs * .11);
8631
+ const guideW = edgeWidthOf(props) ?? 1;
8632
+ const guideStyle = `fill="none" stroke="${guide}" stroke-width="${f$2(guideW)}" stroke-opacity="0.55"${dash(lines)}${lines === "rounded" ? " stroke-linejoin=\"round\"" : ""}`;
8633
+ const bandR = Math.min(num(props.radius) ?? T.radius, (g.rowH - 2) / 2);
8634
+ const bandX = f$2(X(-g.fs * .35));
8635
+ const bandW = f$2(g.w + g.fs * .7);
8636
+ g.rows.forEach((r, k) => {
8637
+ const n = r.node;
8638
+ const cy = r.y + g.rowH / 2;
8639
+ const row = [];
8640
+ if (n.highlight) {
8641
+ const tone = n.tone ?? highlightTone;
8642
+ const tc = tone ? T.tone(tone) : void 0;
8643
+ bands.push(`<rect x="${bandX}" y="${f$2(Y(r.y + 1))}" width="${bandW}" height="${f$2(g.rowH - 2)}" rx="${f$2(props.radius ? bandR : Math.min(T.radius, g.rowH / 3))}" fill="${tc?.fill ?? T.accent}"${tc ? "" : " fill-opacity=\"0.14\""}/>`);
8644
+ } else if (props.rows === "striped" && k % 2 === 1) bands.push(`<rect x="${bandX}" y="${f$2(Y(r.y))}" width="${bandW}" height="${f$2(g.rowH)}" fill="${T.node.text}" fill-opacity="0.045"/>`);
8645
+ if (lines !== "none" && r.parent) {
8646
+ const px = r.parent.x + g.anchor;
8647
+ const tick = Math.max(px, r.x - g.fs * .2);
8648
+ if (r.last) {
8649
+ const top = r.parent.y + g.rowH / 2 + (g.iconW ? g.iconW / 2 + g.fs * .1 : g.fs * .5);
8650
+ const rr = lines === "rounded" ? Math.min(g.fs * .45, tick - px, cy - top) : 0;
8651
+ guides.push(rr > 0 ? `<path d="M${f$2(X(px))},${f$2(Y(top))}V${f$2(Y(cy - rr))}Q${f$2(X(px))},${f$2(Y(cy))} ${f$2(X(px + rr))},${f$2(Y(cy))}H${f$2(X(tick))}" ${guideStyle}/>` : `<path d="M${f$2(X(px))},${f$2(Y(top))}V${f$2(Y(cy))}H${f$2(X(tick))}" ${guideStyle}/>`);
8652
+ } else guides.push(`<path d="M${f$2(X(px))},${f$2(Y(cy))}H${f$2(X(tick))}" ${guideStyle}/>`);
8653
+ }
8654
+ if (g.chevW && r.folder) {
8655
+ const cx = X(r.x + g.chevW * .45);
8656
+ const s = g.fs * .22;
8657
+ const d = r.open ? `M${f$2(cx - s)},${f$2(Y(cy) - s / 2)}L${f$2(cx)},${f$2(Y(cy) + s / 2)}L${f$2(cx + s)},${f$2(Y(cy) - s / 2)}` : `M${f$2(cx - s / 2)},${f$2(Y(cy) - s)}L${f$2(cx + s / 2)},${f$2(Y(cy))}L${f$2(cx - s / 2)},${f$2(Y(cy) + s)}`;
8658
+ row.push(`<path d="${d}" fill="none" stroke="${T.node.sub}" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"/>`);
8659
+ }
8660
+ if (g.iconW && !r.more) {
8661
+ const ix = X(r.x + g.chevW);
8662
+ const iy = Y(cy - g.iconW / 2);
8663
+ if (r.iconText || g.icons === "emoji") row.push(`<text x="${f$2(ix + g.iconW / 2)}" y="${f$2(Y(cy))}" dominant-baseline="central" text-anchor="middle" font-size="${f$2(g.fs * .95)}">${esc$1(r.iconText ?? EMOJI[r.icon] ?? "📄")}</text>`);
8664
+ else {
8665
+ const mono = g.icons === "mono";
8666
+ const tc = !mono && r.iconTone ? T.tone(r.iconTone) : void 0;
8667
+ const stroke = mono || !r.iconTone ? T.node.sub : ink(r.iconTone, T.node.sub);
8668
+ const fill = tc?.fill ?? T.node.fill;
8669
+ row.push(`<g transform="translate(${f$2(ix)},${f$2(iy)}) scale(${f$2(g.iconW / 16)})" stroke-width="1.3" stroke-linejoin="round">${glyph(r.icon, fill, stroke)}</g>`);
8670
+ }
8671
+ }
8672
+ if (n.status === "deleted") {
8673
+ const sx = X(g.textX(r));
8674
+ row.push(`<line x1="${f$2(sx - g.fs * .15)}" y1="${f$2(Y(cy))}" x2="${f$2(sx + r.textW + g.fs * .15)}" y2="${f$2(Y(cy))}" stroke="${strikeInk}" stroke-width="${f$2(strikeW)}" stroke-linecap="round"/>`);
8675
+ }
8676
+ const statusInk = n.status ? ink(STATUS_TONE[n.status], T.node.text) : void 0;
8677
+ const text = r.more ? T.node.sub : n.tone ? ink(n.tone, T.node.text) : statusInk ?? T.node.text;
8678
+ const attrs = [
8679
+ n.status === "deleted" ? " opacity=\"0.8\"" : "",
8680
+ n.status === "ignored" ? " opacity=\"0.55\"" : "",
8681
+ r.folder ? " font-weight=\"600\"" : ""
8682
+ ].join("");
8683
+ row.push(`<text x="${f$2(X(g.textX(r)))}" y="${f$2(Y(cy))}" dominant-baseline="central" font-size="${f$2(g.fs)}"${attrs} xml:space="preserve">${tspans(parseInline(r.label), {
8684
+ text,
8685
+ sub: T.node.sub,
8686
+ stroke: text
8687
+ }, T)}</text>`);
8688
+ if (n.badge) {
8689
+ const tc = T.tone(n.tone ?? badgeTone);
8690
+ const bx = X(g.badgeX(r));
8691
+ const bh = g.fs * 1.15;
8692
+ row.push(`<rect x="${f$2(bx)}" y="${f$2(Y(cy) - bh / 2)}" width="${f$2(r.badgeW)}" height="${f$2(bh)}" rx="${f$2(bh / 2)}" fill="${tc?.fill ?? T.node.fill}" stroke="${tc?.stroke ?? T.node.stroke}"/><text x="${f$2(bx + r.badgeW / 2)}" y="${f$2(Y(cy))}" dominant-baseline="central" text-anchor="middle" font-size="${f$2(g.fs * .72)}" font-weight="600" fill="${tc?.text ?? T.node.text}">${esc$1(n.badge)}</text>`);
8693
+ }
8694
+ if (r.count) {
8695
+ const cx = X(g.countX(r));
8696
+ const ch = g.fs * 1.05;
8697
+ row.push(`<rect x="${f$2(cx)}" y="${f$2(Y(cy) - ch / 2)}" width="${f$2(r.countW)}" height="${f$2(ch)}" rx="${f$2(ch / 2)}" fill="${T.node.sub}" fill-opacity="0.12"/><text x="${f$2(cx + r.countW / 2)}" y="${f$2(Y(cy))}" dominant-baseline="central" text-anchor="middle" font-size="${f$2(g.smallFs)}" font-weight="600" fill="${T.node.sub}">${r.count}</text>`);
8698
+ }
8699
+ if (n.note) row.push(`<text x="${f$2(X(g.noteX(r)))}" y="${f$2(Y(cy))}" dominant-baseline="central" font-size="${f$2(g.noteFs)}" xml:space="preserve">${tspans(parseInline(n.note), {
8700
+ text: noteInk,
8701
+ sub: noteInk,
8702
+ stroke: noteInk
8703
+ }, T, true)}</text>`);
8704
+ if (n.size) row.push(`<text x="${f$2(X(g.sizeRight))}" y="${f$2(Y(cy))}" dominant-baseline="central" text-anchor="end" font-size="${f$2(g.fs * .82)}" fill="${T.node.sub}">${esc$1(n.size)}</text>`);
8705
+ if (g.mark(r)) {
8706
+ const status = n.status ?? r.rollup;
8707
+ const color = ink(STATUS_TONE[status], T.node.text);
8708
+ if (g.marks === "dot" || !n.status) row.push(`<circle cx="${f$2(X(g.markX))}" cy="${f$2(Y(cy))}" r="${f$2(g.fs * .22)}" fill="${color}"/>`);
8709
+ else row.push(`<text x="${f$2(X(g.markX))}" y="${f$2(Y(cy))}" dominant-baseline="central" text-anchor="middle" font-size="${f$2(g.fs * .85)}" font-weight="700" fill="${color}">${STATUS_MARK[status]}</text>`);
8710
+ }
8711
+ out.push(n.dim ? `<g opacity="0.45">${row.join("")}</g>` : row.join(""));
8712
+ });
8713
+ return bands.join("") + guides.join("") + out.join("");
8714
+ }
8715
+ // src/setup.ts
8716
+ /** Registers the built-in plugins. Imported for its side effect by every entry point. */
8717
+ use(...[
8718
+ themes,
8719
+ charts,
8720
+ tables,
8721
+ frames,
8722
+ legend,
8723
+ footer,
8724
+ sequence$1,
8725
+ timeline$1,
8726
+ chart,
8727
+ git$1,
8728
+ mindmap$1,
8729
+ gantt$1,
8730
+ quadrant$1,
8731
+ kanban$1,
8732
+ {
8733
+ name: "treeview",
8734
+ panels: [{
8735
+ name: "treeview",
8736
+ guide: "indentation is the tree (several top-level entries are fine); `-` bullets and the `├──` / `│` prefixes of `tree` output are optional; `...` stands for more files. A folder has children, ends in `/` or says `[folder]`. `name: note` or `name # note` adds a note. Trailing props: a colour, `icon: " + TREE_ICONS.join("|") + "|<emoji>`, `badge: text`, `size: text`, `collapsed`, `highlight`, `dim`, `" + STATUSES.join("|") + "`. `match <glob> [props]` gives every matching entry those props (`*`, `**`, `?`, `{a,b}`; a trailing `/` matches folders only).",
8737
+ syntax: "treeview id \"Title\" [icons: color] { match *.test.ts [dim]\\n src/\\n index.ts: entry\\n util.ts [modified] }",
8738
+ options: {
8739
+ icons: [...ICONS],
8740
+ lines: [...LINES],
8741
+ sort: [...SORTS],
8742
+ notes: ["column", "inline"],
8743
+ chevrons: "flag",
8744
+ rows: ["plain", "striped"],
8745
+ spacing: [
8746
+ "compact",
8747
+ "normal",
8748
+ "relaxed"
8749
+ ],
8750
+ slashes: ["true", "false"],
8751
+ compact: "flag",
8752
+ counts: [...COUNTS],
8753
+ marks: [...MARKS],
8754
+ rollup: ["true", "false"],
8755
+ depth: "number",
8756
+ indent: "number",
8757
+ "folder-color": "color",
8758
+ "line-color": "color",
8759
+ "highlight-color": "color",
8760
+ "badge-color": "color",
8761
+ "note-color": "color",
8762
+ "strike-color": "color",
8763
+ "strike-width": "number"
7503
8764
  },
7504
- editPart: editKanban,
7505
- adds: "column",
7506
- handles(cols, box, ctx) {
7507
- if (!cols.length) return [];
7508
- const G = geometry(cols, ctx);
7509
- return cols.slice(1).map((c, k) => ({
7510
- part: c.id,
7511
- x: box.x + G.at[k + 1],
7512
- y: box.y + G.headH / 2,
7513
- axis: "x",
7514
- title: `move ${c.title}`
8765
+ parse: parseTreeview,
8766
+ measure(roots, ctx) {
8767
+ if (!roots.length) return {
8768
+ w: 0,
8769
+ h: 0
8770
+ };
8771
+ const g = geometry(roots, ctx);
8772
+ return {
8773
+ w: g.w,
8774
+ h: g.h
8775
+ };
8776
+ },
8777
+ render: renderTreeview,
8778
+ parts(roots) {
8779
+ const all = walk(roots);
8780
+ return entryParts(all).map((id, i) => ({
8781
+ id,
8782
+ label: all[i].text,
8783
+ kind: isFolder(all[i]) ? "folder" : "file",
8784
+ tone: all[i].tone
7515
8785
  }));
7516
- }
8786
+ },
8787
+ editPart: recolor((body, id, tone, roots) => {
8788
+ const all = walk(roots);
8789
+ const n = all[entryParts(all).indexOf(id)];
8790
+ if (!n) return null;
8791
+ const out = [...body];
8792
+ const line = body[n.line];
8793
+ const [from, to] = n.propSpan ?? [line.trimEnd().length, line.trimEnd().length];
8794
+ const m = line.slice(from, to).match(/\[([^\]]*)\]/);
8795
+ const { color: _, ...rest } = m ? parseProps(m[1]) : {};
8796
+ const props = serializeProps(tone ? {
8797
+ color: tone,
8798
+ ...rest
8799
+ } : rest);
8800
+ out[n.line] = line.slice(0, from) + (props ? ` [${props}]` : "") + line.slice(to);
8801
+ return out;
8802
+ })
7517
8803
  }]
7518
8804
  }
7519
8805
  ]);
@@ -7953,7 +9239,11 @@ function applySettings(base, s) {
7953
9239
  return withEdgeInk(t, s);
7954
9240
  }
7955
9241
  const isHorizontal = (dir) => dir === "right" || dir === "left";
9242
+ /** place nodes, route edges and size panels; a plugin that throws becomes a diagnostic on `d` */
7956
9243
  function layout(d, opts = {}) {
9244
+ return collecting(d.diagnostics, () => place(d, opts));
9245
+ }
9246
+ function place(d, opts) {
7957
9247
  const theme = applySettings(getTheme(opts.theme ?? d.settings.theme, d.themes), d.settings);
7958
9248
  const measure = opts.measure ?? opts.measureFor?.(theme) ?? approxMeasure;
7959
9249
  const dir = [
@@ -7963,9 +9253,9 @@ function layout(d, opts = {}) {
7963
9253
  "up"
7964
9254
  ].includes(d.settings.direction) ? d.settings.direction : "right";
7965
9255
  const horiz = isHorizontal(dir);
7966
- const gap = num(d.settings.gap, 36);
9256
+ const gap = num$1(d.settings.gap, 36);
7967
9257
  const hasGroups = [...d.nodes.values()].some((n) => n.group);
7968
- const baseRankGap = num(d.settings["rank-gap"], hasGroups ? 96 : 72);
9258
+ const baseRankGap = num$1(d.settings["rank-gap"], hasGroups ? 96 : 72);
7969
9259
  const defaultCurve = [
7970
9260
  "smooth",
7971
9261
  "orthogonal",
@@ -7979,7 +9269,7 @@ function layout(d, opts = {}) {
7979
9269
  const style = resolveNodeStyle(d, n, p, theme);
7980
9270
  const shape = normalizeShape(p.shape ?? defaultShape);
7981
9271
  const caps = p.caps !== void 0 && p.caps !== "false";
7982
- const wrap = num(p["max-width"], num(d.settings.wrap, 0));
9272
+ const wrap = num$1(p["max-width"], num$1(d.settings.wrap, 0));
7983
9273
  const tb = textBlock(n.label, p.sub, p.icon, style.fontSize, style.fontWeight, theme, measure, caps, wrap);
7984
9274
  let sz;
7985
9275
  if (n.body?.length || p.meta || p.frame) {
@@ -8003,8 +9293,8 @@ function layout(d, opts = {}) {
8003
9293
  } else sz = sizeForShape(shape, tb.w, tb.h);
8004
9294
  blocks.set(n.id, tb);
8005
9295
  const o = d.layout.nodes[n.id];
8006
- const w = o?.w ?? even(num(p.width, sz.w));
8007
- const h = o?.h ?? even(num(p.height, sz.h));
9296
+ const w = o?.w ?? even(num$1(p.width, sz.w));
9297
+ const h = o?.h ?? even(num$1(p.height, sz.h));
8008
9298
  nodes.set(n.id, {
8009
9299
  id: n.id,
8010
9300
  decl: n,
@@ -8022,7 +9312,7 @@ function layout(d, opts = {}) {
8022
9312
  d.edges.forEach((e, idx) => {
8023
9313
  if (e.from === e.to || !nodes.has(e.from) || !nodes.has(e.to)) return;
8024
9314
  if (e.props.constraint === "false") return;
8025
- const len = Math.max(1, Math.min(12, Math.round(num(e.props.length, 1))));
9315
+ const len = Math.max(1, Math.min(12, Math.round(num$1(e.props.length, 1))));
8026
9316
  rankEdges.push({
8027
9317
  from: e.from,
8028
9318
  to: e.to,
@@ -8031,19 +9321,26 @@ function layout(d, opts = {}) {
8031
9321
  len
8032
9322
  });
8033
9323
  });
9324
+ const placed = placements(d, nodes, dir);
9325
+ rankEdges.unshift(...placed.edges);
8034
9326
  breakCycles(ids, rankEdges);
8035
9327
  const rank = assignRanks(ids, rankEdges);
8036
- const sameRank = (d.layout.ranks ?? []).map((set) => set.filter((id) => nodes.has(id))).filter((set) => set.length > 1);
9328
+ const sameRank = [...d.layout.ranks ?? [], ...placed.same].map((set) => set.filter((id) => nodes.has(id))).filter((set) => set.length > 1);
8037
9329
  if (sameRank.length) alignRanks(rank, rankEdges, sameRank);
8038
9330
  const ranked = new Set(rankEdges.flatMap((e) => [e.from, e.to]));
8039
9331
  const attach = /* @__PURE__ */ new Map();
8040
9332
  for (const e of d.edges) {
8041
9333
  if (e.props.constraint !== "false" || !nodes.has(e.from) || !nodes.has(e.to)) continue;
8042
9334
  for (const [loose, anchor] of [[e.from, e.to], [e.to, e.from]]) if (!ranked.has(loose) && ranked.has(anchor) && !attach.has(loose)) {
8043
- attach.set(loose, anchor);
9335
+ attach.set(loose, [anchor, 1]);
8044
9336
  rank.set(loose, rank.get(anchor));
8045
9337
  }
8046
9338
  }
9339
+ if (placed.order.size) {
9340
+ alignRanks(rank, rankEdges, [...sameRank, ...[...placed.order].map(([id, [anchor]]) => [id, anchor])]);
9341
+ for (const [id, a] of placed.order) attach.set(id, a);
9342
+ }
9343
+ checkPlacements(d, placed, rank);
8047
9344
  const vnodes = /* @__PURE__ */ new Map();
8048
9345
  for (const id of ids) {
8049
9346
  const n = nodes.get(id);
@@ -8063,6 +9360,14 @@ function layout(d, opts = {}) {
8063
9360
  const [u, v] = re.reversed ? [re.to, re.from] : [re.from, re.to];
8064
9361
  const ru = rank.get(u);
8065
9362
  const rv = rank.get(v);
9363
+ if (re.hidden) {
9364
+ vedges.push([
9365
+ u,
9366
+ v,
9367
+ 2
9368
+ ]);
9369
+ continue;
9370
+ }
8066
9371
  if (rv - ru <= 1) {
8067
9372
  vedges.push([
8068
9373
  u,
@@ -8231,9 +9536,21 @@ function layout(d, opts = {}) {
8231
9536
  p.y = Math.round(p.y + oy);
8232
9537
  }
8233
9538
  }
9539
+ const maxW = num$1(d.settings["max-width"], 0);
9540
+ const channels = /* @__PURE__ */ new Set();
9541
+ const pins = [...nodes.keys()].some((id) => d.layout.nodes[id]?.x !== void 0);
9542
+ if (maxW > 0 && horiz && nodes.size && !pins) {
9543
+ const dummyRank = /* @__PURE__ */ new Map();
9544
+ for (const [idx, chain] of chains) dummyRank.set(idx, chain.map((id) => vnodes.get(id).rank));
9545
+ wrapRows(d, nodes, rank, dummyPts, dummyRank, channels, {
9546
+ maxW,
9547
+ dir,
9548
+ rankGap: baseRankGap
9549
+ });
9550
+ }
8234
9551
  applyOverrides(d, nodes, horiz, gap);
8235
9552
  const anyPinned = [...nodes.values()].some((n) => n.pinned);
8236
- const groups = layoutGroups(d, nodes, theme);
9553
+ const groups = layoutGroups(d, nodes, theme, measure);
8237
9554
  const dummyVia = /* @__PURE__ */ new Map();
8238
9555
  if (!anyPinned) d.edges.forEach((e, idx) => dummyPts.has(idx) && dummyVia.set(e.key, dummyPts.get(idx)));
8239
9556
  const edges = routeEdges(d, nodes, {
@@ -8242,6 +9559,7 @@ function layout(d, opts = {}) {
8242
9559
  direction: dir,
8243
9560
  defaultCurve,
8244
9561
  dummyVia,
9562
+ channels: anyPinned ? void 0 : channels,
8245
9563
  obstacles: [...nodes.values()],
8246
9564
  groups: groups.map((g) => ({
8247
9565
  box: g,
@@ -8249,11 +9567,35 @@ function layout(d, opts = {}) {
8249
9567
  x: g.x,
8250
9568
  y: g.y,
8251
9569
  w: g.w,
8252
- h: 35
9570
+ h: (g.header ?? 26) + 9
8253
9571
  }
8254
9572
  }))
8255
9573
  });
8256
- const { bounds, decor, panels } = computeBounds(nodes, groups, edges, d, theme, measure);
9574
+ const linkPanels = (panels) => {
9575
+ if (!panels.length) return [];
9576
+ const linked = d.edges.filter((e) => !nodes.has(e.from) || !nodes.has(e.to));
9577
+ if (!linked.length) return [];
9578
+ const ends = new Map(nodes);
9579
+ for (const p of panels) ends.set(p.decl.id, {
9580
+ ...p.box,
9581
+ id: p.decl.id,
9582
+ shape: "box"
9583
+ });
9584
+ return routeEdges({
9585
+ ...d,
9586
+ edges: linked
9587
+ }, ends, {
9588
+ theme,
9589
+ measure,
9590
+ direction: dir,
9591
+ defaultCurve,
9592
+ dummyVia: /* @__PURE__ */ new Map(),
9593
+ obstacles: [...ends.values()]
9594
+ });
9595
+ };
9596
+ const panels = placePanels(d, theme, measure, extent(nodes, groups, edges, []));
9597
+ edges.push(...linkPanels(panels));
9598
+ const { bounds, decor } = computeBounds(extent(nodes, groups, edges, panels), d, theme, measure);
8257
9599
  const L = {
8258
9600
  nodes,
8259
9601
  groups,
@@ -8269,6 +9611,222 @@ function layout(d, opts = {}) {
8269
9611
  return L;
8270
9612
  }
8271
9613
  /**
9614
+ * `max-width` for left-to-right and right-to-left diagrams: when the graph is
9615
+ * wider than that, cut it into rows of whole ranks and stack the rows top to
9616
+ * bottom. A cut never falls inside a group, so a group wider than the limit
9617
+ * stays one row. An edge between rows leaves its node in the flow direction,
9618
+ * runs through the gap above the target's row and enters the target from
9619
+ * the other side.
9620
+ */
9621
+ function wrapRows(d, nodes, rank, dummyPts, dummyRank, channels, o) {
9622
+ const pad = num$1(d.settings.padding, 24);
9623
+ const maxRank = Math.max(...[...nodes.keys()].map((id) => rank.get(id)));
9624
+ const outer = /* @__PURE__ */ new Map();
9625
+ for (const n of nodes.values()) {
9626
+ const k = groupPath(d, n.decl.group).length;
9627
+ outer.set(n.id, {
9628
+ x: n.x - k * 18,
9629
+ y: n.y - k * 44,
9630
+ w: n.w + 2 * k * 18,
9631
+ h: n.h + k * 62
9632
+ });
9633
+ }
9634
+ const joined = new Array(maxRank + 1).fill(false);
9635
+ const span = /* @__PURE__ */ new Map();
9636
+ for (const n of nodes.values()) for (const g of groupPath(d, n.decl.group)) {
9637
+ const r = rank.get(n.id);
9638
+ const sp = span.get(g) ?? [r, r];
9639
+ span.set(g, [Math.min(sp[0], r), Math.max(sp[1], r)]);
9640
+ }
9641
+ for (const [r0, r1] of span.values()) for (let r = r0; r < r1; r++) joined[r] = true;
9642
+ const byRank = Array.from({ length: maxRank + 1 }, () => []);
9643
+ for (const n of nodes.values()) byRank[rank.get(n.id)].push(outer.get(n.id));
9644
+ const ext = (bs) => ({
9645
+ x0: Math.min(...bs.map((b) => b.x)),
9646
+ x1: Math.max(...bs.map((b) => b.x + b.w)),
9647
+ y0: Math.min(...bs.map((b) => b.y)),
9648
+ y1: Math.max(...bs.map((b) => b.y + b.h))
9649
+ });
9650
+ const all = ext([...outer.values()]);
9651
+ if (all.x1 - all.x0 + 2 * pad <= o.maxW) return;
9652
+ const room = Math.min(o.rankGap / 2, 36);
9653
+ const rowOf = new Array(maxRank + 1).fill(0);
9654
+ let row = 0;
9655
+ let rowBoxes = [];
9656
+ let r = 0;
9657
+ while (r <= maxRank) {
9658
+ let end = r;
9659
+ while (end < maxRank && joined[end]) end++;
9660
+ const block = byRank.slice(r, end + 1).flat();
9661
+ const next = [...rowBoxes, ...block];
9662
+ if (rowBoxes.length && block.length) {
9663
+ const e = ext(next);
9664
+ if (e.x1 - e.x0 + 2 * pad + 2 * room > o.maxW) {
9665
+ row++;
9666
+ rowBoxes = [];
9667
+ }
9668
+ }
9669
+ rowBoxes.push(...block);
9670
+ for (let k = r; k <= end; k++) rowOf[k] = row;
9671
+ r = end + 1;
9672
+ }
9673
+ if (row === 0) return;
9674
+ const rows = Array.from({ length: row + 1 }, (_, k) => ext(byRank.filter((_, rr) => rowOf[rr] === k).flat()));
9675
+ const shift = [];
9676
+ const top = [];
9677
+ let y = all.y0;
9678
+ for (const e of rows) {
9679
+ if (!Number.isFinite(e.x0)) {
9680
+ shift.push({
9681
+ x: 0,
9682
+ y: 0
9683
+ });
9684
+ top.push(y);
9685
+ continue;
9686
+ }
9687
+ shift.push({
9688
+ x: o.dir === "left" ? all.x1 - e.x1 : all.x0 - e.x0,
9689
+ y: y - e.y0
9690
+ });
9691
+ top.push(y);
9692
+ y += e.y1 - e.y0 + o.rankGap;
9693
+ }
9694
+ const rowOfNode = (id) => rowOf[rank.get(id)];
9695
+ for (const n of nodes.values()) {
9696
+ const s = shift[rowOfNode(n.id)];
9697
+ n.x += s.x;
9698
+ n.y += s.y;
9699
+ }
9700
+ const rankBox = byRank.map((_, rr) => {
9701
+ const ns = [...nodes.values()].filter((n) => rank.get(n.id) === rr);
9702
+ return ns.length ? ext(ns) : void 0;
9703
+ });
9704
+ const fwd = o.dir === "left" ? -1 : 1;
9705
+ /** the x of the channel after (side 1) or before (side -1) rank rr, in flow order */
9706
+ const channel = (rr, side) => {
9707
+ const b = rankBox[rr];
9708
+ const edge = fwd * side > 0 ? b.x1 : b.x0;
9709
+ const nb = rankBox[rr + side];
9710
+ if (nb && rowOf[rr + side] === rowOf[rr]) return (edge + (fwd * side > 0 ? nb.x0 : nb.x1)) / 2;
9711
+ return edge + fwd * side * room;
9712
+ };
9713
+ d.edges.forEach((e, idx) => {
9714
+ if (!nodes.has(e.from) || !nodes.has(e.to) || e.from === e.to) return;
9715
+ const [ra, rb] = [rowOfNode(e.from), rowOfNode(e.to)];
9716
+ if (ra === rb) {
9717
+ const s = shift[ra];
9718
+ const pts = dummyPts.get(idx);
9719
+ if (pts && dummyRank.get(idx).every((rr) => rowOf[rr] === ra)) for (const p of pts) {
9720
+ p.x += s.x;
9721
+ p.y += s.y;
9722
+ }
9723
+ else dummyPts.delete(idx);
9724
+ return;
9725
+ }
9726
+ const a = nodes.get(e.from);
9727
+ const b = nodes.get(e.to);
9728
+ const xa = channel(rank.get(e.from), 1);
9729
+ const xb = channel(rank.get(e.to), -1);
9730
+ const gy = top[Math.max(ra, rb)] - o.rankGap / 2;
9731
+ channels.add(e.key);
9732
+ dummyPts.set(idx, [
9733
+ {
9734
+ x: xa,
9735
+ y: a.y + a.h / 2
9736
+ },
9737
+ {
9738
+ x: xa,
9739
+ y: gy
9740
+ },
9741
+ {
9742
+ x: xb,
9743
+ y: gy
9744
+ },
9745
+ {
9746
+ x: xb,
9747
+ y: b.y + b.h / 2
9748
+ }
9749
+ ]);
9750
+ });
9751
+ }
9752
+ /**
9753
+ * Placement props, turned into what the ranking understands. Along the rank
9754
+ * axis (`right-of` in a left-to-right diagram) a node goes one rank past its
9755
+ * anchor: a hidden edge. Across it (`below` there) the node shares the
9756
+ * anchor's rank and sits right after it (+1) or before it (-1). `rank` only
9757
+ * shares the rank. Unknown ids and self references are skipped; lint reports them.
9758
+ */
9759
+ /**
9760
+ * A placement that loses to the edges (`a -> b` and `b [left-of: a]` in a
9761
+ * left-to-right diagram) gets a warning instead of failing silently.
9762
+ */
9763
+ function checkPlacements(d, placed, rank) {
9764
+ const bad = [];
9765
+ for (const e of placed.edges) if (rank.get(e.to) <= rank.get(e.from)) bad.push([e.byNode, e.from === e.byNode ? e.to : e.from]);
9766
+ for (const [id, [anchor]] of placed.order) if (rank.get(id) !== rank.get(anchor)) bad.push([id, anchor]);
9767
+ for (const [id, anchor] of placed.same) if (rank.get(id) !== rank.get(anchor)) bad.push([id, anchor]);
9768
+ for (const [id, anchor] of bad) {
9769
+ const n = d.nodes.get(id);
9770
+ const key = placementOf(effectiveProps(d, n))?.[0];
9771
+ if (!n.ref || !key) continue;
9772
+ const line = (n.ref.propLines?.[key] ?? n.ref.line) + 1;
9773
+ const message = `${id} [${key}: ${anchor}] cannot be met: the edges between them run the other way, and the edges win`;
9774
+ if (!d.diagnostics.some((x) => x.line === line && x.message === message)) d.diagnostics.push({
9775
+ line,
9776
+ message,
9777
+ severity: "warning"
9778
+ });
9779
+ }
9780
+ }
9781
+ function placements(d, nodes, dir) {
9782
+ const edges = [];
9783
+ const order = /* @__PURE__ */ new Map();
9784
+ const same = [];
9785
+ const horiz = isHorizontal(dir);
9786
+ const forward = {
9787
+ right: "right-of",
9788
+ left: "left-of",
9789
+ down: "below",
9790
+ up: "above"
9791
+ }[dir];
9792
+ const back = {
9793
+ right: "left-of",
9794
+ left: "right-of",
9795
+ down: "above",
9796
+ up: "below"
9797
+ }[dir];
9798
+ for (const n of nodes.values()) {
9799
+ const p = placementOf(effectiveProps(d, n.decl));
9800
+ if (!p) continue;
9801
+ const [key, anchor] = p;
9802
+ if (anchor === n.id || !nodes.has(anchor)) continue;
9803
+ const edge = {
9804
+ idx: -1,
9805
+ reversed: false,
9806
+ len: 1,
9807
+ hidden: true,
9808
+ byNode: n.id
9809
+ };
9810
+ if (key === forward) edges.push({
9811
+ from: anchor,
9812
+ to: n.id,
9813
+ ...edge
9814
+ });
9815
+ else if (key === back) edges.push({
9816
+ from: n.id,
9817
+ to: anchor,
9818
+ ...edge
9819
+ });
9820
+ else if (key === "rank") same.push([n.id, anchor]);
9821
+ else order.set(n.id, [anchor, key === (horiz ? "below" : "right-of") ? 1 : -1]);
9822
+ }
9823
+ return {
9824
+ edges,
9825
+ order,
9826
+ same
9827
+ };
9828
+ }
9829
+ /**
8272
9830
  * Pull each set onto one rank (the deepest of its members), then push
8273
9831
  * successors down again so every edge still points forward. Edges inside a
8274
9832
  * set are ignored: the set wins.
@@ -8365,9 +9923,9 @@ function assignRanks(ids, edges) {
8365
9923
  function orderLayers(layers, preds, succs, attach = /* @__PURE__ */ new Map()) {
8366
9924
  const index = /* @__PURE__ */ new Map();
8367
9925
  const reindex = () => layers.forEach((l) => l.forEach((v, i) => index.set(v.id, i)));
8368
- /** attached nodes ride right after their partner */
9926
+ /** attached nodes ride right after (or before) their partner; repeat so chains follow */
8369
9927
  const pin = (bary) => {
8370
- for (const [loose, anchor] of attach) if (bary.has(anchor) && bary.has(loose)) bary.set(loose, bary.get(anchor) + .001);
9928
+ for (let pass = 0; pass < Math.min(attach.size, 8); pass++) for (const [loose, [anchor, side]] of attach) if (bary.has(anchor) && bary.has(loose)) bary.set(loose, bary.get(anchor) + side * .001);
8371
9929
  return bary;
8372
9930
  };
8373
9931
  for (const l of layers) sortLayer(l, pin(new Map(l.map((v, i) => [v.id, i]))));
@@ -8530,7 +10088,82 @@ function applyOverrides(d, nodes, horiz, gap) {
8530
10088
  placed.push(n);
8531
10089
  }
8532
10090
  }
8533
- function layoutGroups(d, nodes, theme) {
10091
+ /**
10092
+ * The header text of a group: its label (bold, left) and `meta` (right) on
10093
+ * the first line. Font sizes match `renderGroup`.
10094
+ */
10095
+ function groupHeadText(g, theme, measure) {
10096
+ const p = g.props;
10097
+ const caps = p.caps !== void 0 && p.caps !== "false";
10098
+ const fs = theme.fontSize * .82;
10099
+ const size = caps ? fs * .92 : fs;
10100
+ const spacing = size * (caps ? .1 : .02);
10101
+ const text = caps ? g.label.toUpperCase() : g.label;
10102
+ const width = (l) => measure(l, size, 600, theme.mono) + spacing * [...l].length;
10103
+ return {
10104
+ text,
10105
+ width,
10106
+ meta: p.meta ? measure(p.meta, fs, 400, theme.mono) : 0,
10107
+ lineHeight: Math.round(size * 1.3 * 10) / 10
10108
+ };
10109
+ }
10110
+ const META_GAP = 12;
10111
+ /**
10112
+ * Groups wrap their members. A label that does not fit widens the group into
10113
+ * the free space to its right, then to its left, like a node grows to fit its
10114
+ * label. When neighbours leave too little room, the label wraps and the header
10115
+ * grows upward.
10116
+ */
10117
+ function fitGroupHead(d, gid, box, nodes, laid, theme, measure) {
10118
+ const g = d.groups.get(gid);
10119
+ if (!g.label) return;
10120
+ const head = groupHeadText(g, theme, measure);
10121
+ const need = 28 + Math.max(...head.text.split("\n").map(head.width)) + (head.meta ? head.meta + META_GAP : 0);
10122
+ if (need <= box.w && !head.text.includes("\n")) return;
10123
+ if (need > box.w) {
10124
+ const inside = (gr) => groupPath(d, gr).includes(gid);
10125
+ const others = [];
10126
+ const own = groupPath(d, gid);
10127
+ for (const n of nodes.values()) {
10128
+ if (inside(n.decl.group)) continue;
10129
+ const path = groupPath(d, n.decl.group);
10130
+ let c = 0;
10131
+ while (c < path.length && path[c] === own[c]) c++;
10132
+ const pad = (path.length - c) * 18;
10133
+ others.push({
10134
+ x: n.x - pad,
10135
+ y: n.y - pad,
10136
+ w: n.w + 2 * pad,
10137
+ h: n.h + 2 * pad
10138
+ });
10139
+ }
10140
+ for (const [cid, b] of laid) if (!inside(cid) && !groupPath(d, gid).includes(cid)) others.push(b);
10141
+ const m = 9;
10142
+ let lo = -1e400;
10143
+ let hi = 1e400;
10144
+ for (const o of others) {
10145
+ if (o.y >= box.y + box.h + m || o.y + o.h <= box.y - m) continue;
10146
+ if (o.x + o.w <= box.x + 1) lo = Math.max(lo, o.x + o.w + m);
10147
+ else if (o.x >= box.x + box.w - 1) hi = Math.min(hi, o.x - m);
10148
+ }
10149
+ const extra = need - box.w;
10150
+ const right = Math.max(0, Math.min(extra, hi - box.x - box.w));
10151
+ const left = Math.max(0, Math.min(extra - right, box.x - lo));
10152
+ box.x = Math.floor(box.x - left);
10153
+ box.w = Math.ceil(box.w + left + right);
10154
+ }
10155
+ const room = box.w - 28 - (head.meta ? head.meta + META_GAP : 0);
10156
+ const wrapped = wrapText(head.text, Math.max(room, 40), head.width);
10157
+ if (wrapped.length === 1) return;
10158
+ const grow = (wrapped.length - 1) * head.lineHeight;
10159
+ box.y -= grow;
10160
+ box.h += grow;
10161
+ return {
10162
+ lines: wrapped,
10163
+ header: 26 + grow
10164
+ };
10165
+ }
10166
+ function layoutGroups(d, nodes, theme, measure) {
8534
10167
  const depth = (id) => groupPath(d, id).length;
8535
10168
  const ids = [...d.groups.keys()].sort((a, b) => depth(b) - depth(a));
8536
10169
  const boxes = /* @__PURE__ */ new Map();
@@ -8550,6 +10183,7 @@ function layoutGroups(d, nodes, theme) {
8550
10183
  w: x1 - x0,
8551
10184
  h: y1 - y0
8552
10185
  };
10186
+ const head = fitGroupHead(d, gid, box, nodes, boxes, theme, measure);
8553
10187
  boxes.set(gid, box);
8554
10188
  const g = d.groups.get(gid);
8555
10189
  out.push({
@@ -8557,6 +10191,10 @@ function layoutGroups(d, nodes, theme) {
8557
10191
  decl: g,
8558
10192
  depth: depth(gid),
8559
10193
  ...box,
10194
+ ...head ? {
10195
+ lines: head.lines,
10196
+ header: head.header
10197
+ } : {},
8560
10198
  style: resolveGroupStyle({
8561
10199
  ...g,
8562
10200
  props: effectiveProps(d, g)
@@ -8565,7 +10203,8 @@ function layoutGroups(d, nodes, theme) {
8565
10203
  }
8566
10204
  return out.sort((a, b) => a.depth - b.depth);
8567
10205
  }
8568
- function computeBounds(nodes, groups, edges, d, theme, measure) {
10206
+ /** the box around nodes, groups, edges (samples and labels) and panels; null when empty */
10207
+ function extent(nodes, groups, edges, panels) {
8569
10208
  let x0 = 1e400;
8570
10209
  let y0 = 1e400;
8571
10210
  let x1 = -1e400;
@@ -8573,38 +10212,37 @@ function computeBounds(nodes, groups, edges, d, theme, measure) {
8573
10212
  const add = (b) => {
8574
10213
  x0 = Math.min(x0, b.x);
8575
10214
  y0 = Math.min(y0, b.y);
8576
- x1 = Math.max(x1, b.x + b.w);
8577
- y1 = Math.max(y1, b.y + b.h);
10215
+ x1 = Math.max(x1, b.x + (b.w ?? 0));
10216
+ y1 = Math.max(y1, b.y + (b.h ?? 0));
8578
10217
  };
8579
10218
  for (const n of nodes.values()) add(n);
8580
10219
  for (const g of groups) add(g);
8581
10220
  for (const e of edges) {
8582
- for (const p of e.samples) add({
8583
- x: p.x,
8584
- y: p.y,
8585
- w: 0,
8586
- h: 0
8587
- });
8588
- if (e.label) add({
8589
- x: e.label.x,
8590
- y: e.label.y,
8591
- w: e.label.w,
8592
- h: e.label.h
8593
- });
8594
- }
8595
- const hasGraph = Number.isFinite(x0);
8596
- if (!hasGraph) {
8597
- x0 = y0 = 0;
8598
- x1 = y1 = d.panels.length ? 0 : 100;
10221
+ for (const p of e.samples) add(p);
10222
+ if (e.label) add(e.label);
8599
10223
  }
8600
- const panels = placePanels(d, theme, measure, hasGraph ? {
10224
+ for (const p of panels) add(p.box);
10225
+ return Number.isFinite(x0) ? {
8601
10226
  x: x0,
8602
10227
  y: y0,
8603
10228
  w: x1 - x0,
8604
10229
  h: y1 - y0
8605
- } : null);
8606
- for (const p of panels) add(p.box);
8607
- const pad = num(d.settings.padding, 24);
10230
+ } : null;
10231
+ }
10232
+ function computeBounds(box, d, theme, measure) {
10233
+ const empty = d.panels.length ? 0 : 100;
10234
+ let [x0, y0, x1, y1] = box ? [
10235
+ box.x,
10236
+ box.y,
10237
+ box.x + box.w,
10238
+ box.y + box.h
10239
+ ] : [
10240
+ 0,
10241
+ 0,
10242
+ empty,
10243
+ empty
10244
+ ];
10245
+ const pad = num$1(d.settings.padding, 24);
8608
10246
  x0 -= pad;
8609
10247
  y0 -= pad;
8610
10248
  x1 += pad;
@@ -8661,8 +10299,7 @@ function computeBounds(nodes, groups, edges, d, theme, measure) {
8661
10299
  }
8662
10300
  return {
8663
10301
  bounds,
8664
- decor,
8665
- panels
10302
+ decor
8666
10303
  };
8667
10304
  }
8668
10305
  /** panel title height (0 without a title) */
@@ -8718,7 +10355,7 @@ function placePanels(d, theme, measure, graph) {
8718
10355
  });
8719
10356
  }
8720
10357
  if (!out.length) return out;
8721
- const gap = num(d.settings["panel-gap"], 48);
10358
+ const gap = num$1(d.settings["panel-gap"], 48);
8722
10359
  const mode = d.settings.panels ?? "row";
8723
10360
  const cells = [...graph ? [graph] : [], ...out.map((p) => p.box)];
8724
10361
  const ox = graph?.x ?? 0;
@@ -8779,13 +10416,17 @@ const attr = (name, v) => v === null || v === void 0 || v === "" ? "" : ` ${name
8779
10416
  let counter = 0;
8780
10417
  /** text alternative for screen readers and search: subtitle, then who connects to whom */
8781
10418
  function describe(d) {
8782
- const name = (id) => plain(parseInline(d.nodes.get(id)?.label ?? id));
10419
+ const name = (id) => plain(parseInline((d.nodes.get(id) ?? d.panels.find((p) => p.id === id))?.label ?? id));
8783
10420
  const MAX = 40;
8784
10421
  const edges = d.edges.slice(0, MAX).map((e) => `${name(e.from)} to ${name(e.to)}${e.label ? ` (${plain(parseInline(e.label))})` : ""}`);
8785
10422
  if (d.edges.length > MAX) edges.push(`${d.edges.length - MAX} more`);
8786
10423
  return [d.settings.subtitle && plain(parseInline(d.settings.subtitle)), d.nodes.size ? `${d.nodes.size} nodes, ${d.edges.length} edges${edges.length ? `: ${edges.join("; ")}` : ""}.` : ""].filter(Boolean).join(". ");
8787
10424
  }
10425
+ /** the SVG for a laid out diagram; a plugin that throws becomes a diagnostic on `d` */
8788
10426
  function renderSvg(d, L, opts = {}) {
10427
+ return collecting(d.diagnostics, () => draw(d, L, opts));
10428
+ }
10429
+ function draw(d, L, opts) {
8789
10430
  const T = L.theme;
8790
10431
  const id = opts.idPrefix ?? `yuhwa${(counter++).toString(36)}`;
8791
10432
  const B = L.bounds;
@@ -8828,7 +10469,7 @@ function renderSvg(d, L, opts = {}) {
8828
10469
  for (const dc of L.decor ?? []) {
8829
10470
  const dec = registry.decorations.find((x) => x.name === dc.name);
8830
10471
  if (dec) out.push(dec.render(dc.value, dc.area, T, {
8831
- pad: parseFloat(d.settings.padding) || 24,
10472
+ pad: num$1(d.settings.padding, 24),
8832
10473
  bounds: B,
8833
10474
  d
8834
10475
  }));
@@ -8837,18 +10478,18 @@ function renderSvg(d, L, opts = {}) {
8837
10478
  for (const g of [...L.groups].sort((a, b) => a.depth - b.depth)) out.push(renderGroup(g, L, !!opts.interactive));
8838
10479
  out.push("</g><g class=\"edges\">");
8839
10480
  for (const e of L.edges) out.push(renderEdge(e, id, !!opts.interactive));
8840
- out.push("</g><g class=\"nodes\">");
10481
+ out.push("</g>");
10482
+ if (L.panels?.length) out.push(`<g class="panels">${L.panels.map((p) => renderPanel(p, L, opts.measure, shadow ? `${id}-sh` : null, id)).join("")}</g>`);
10483
+ out.push("<g class=\"nodes\">");
8841
10484
  for (const n of L.nodes.values()) out.push(renderNode(d, n, L, shadow ? `${id}-sh` : null));
8842
10485
  out.push("</g><g class=\"labels\">");
8843
10486
  for (const e of L.edges) if (e.label) out.push(renderEdgeLabel(e, L));
8844
- out.push("</g>");
8845
- if (L.panels?.length) out.push(`<g class="panels">${L.panels.map((p) => renderPanel(p, L, opts.measure, shadow ? `${id}-sh` : null)).join("")}</g>`);
8846
- out.push("</svg>");
10487
+ out.push("</g></svg>");
8847
10488
  let svg = out.join("");
8848
10489
  for (const hook of POST_RENDER) svg = hook(svg, d, L);
8849
10490
  return svg;
8850
10491
  }
8851
- function renderPanel(p, L, measure, shadow) {
10492
+ function renderPanel(p, L, measure, shadow, id) {
8852
10493
  const base = L.theme;
8853
10494
  const kind = registry.panels.get(p.decl.kind);
8854
10495
  if (!kind) return "";
@@ -8863,6 +10504,7 @@ function renderPanel(p, L, measure, shadow) {
8863
10504
  sub: T.node.sub,
8864
10505
  stroke: T.node.stroke
8865
10506
  }, T)}</text>`);
10507
+ p.ctx.idPrefix = `${id}-${p.decl.id}`;
8866
10508
  out.push(kind.render(p.decl.data, p.inner, !measure || measure === p.ctx.measure ? p.ctx : {
8867
10509
  ...p.ctx,
8868
10510
  measure
@@ -8877,7 +10519,10 @@ function renderGroup(g, L, interactive) {
8877
10519
  const p = g.decl.props;
8878
10520
  const caps = p.caps !== void 0 && p.caps !== "false";
8879
10521
  const text = caps ? g.decl.label.toUpperCase() : g.decl.label;
8880
- const label = text ? `<text x="${f(g.x + 18 - 4)}" y="${f(g.y + 17)}" font-size="${f(caps ? fs * .92 : fs)}" font-weight="600" letter-spacing="${caps ? "0.1em" : "0.02em"}" fill="${s.text}">${esc(text)}</text>` : "";
10522
+ const lines = g.lines ?? [text];
10523
+ const lh = Math.round((caps ? fs * .92 : fs) * 1.3 * 10) / 10;
10524
+ const body = lines.length > 1 ? lines.map((l, i) => `<tspan x="${f(g.x + 18 - 4)}" y="${f(g.y + 17 + i * lh)}">${esc(l)}</tspan>`).join("") : esc(text);
10525
+ const label = text ? `<text x="${f(g.x + 18 - 4)}" y="${f(g.y + 17)}" font-size="${f(caps ? fs * .92 : fs)}" font-weight="600" letter-spacing="${caps ? "0.1em" : "0.02em"}" fill="${s.text}">${body}</text>` : "";
8881
10526
  const meta = p.meta ? `<text x="${f(g.x + g.w - 18 + 4)}" y="${f(g.y + 17)}" text-anchor="end" font-size="${f(fs)}" fill="${T.node.sub}">${esc(p.meta)}</text>` : "";
8882
10527
  return `<g${attr("data-group", g.id)}${interactive ? " cursor=\"move\"" : ""}><rect x="${f(g.x)}" y="${f(g.y)}" width="${f(g.w)}" height="${f(g.h)}" rx="${f(Math.min(14, T.radius + 4))}" fill="${s.fill}" stroke="${s.stroke}" stroke-width="1"${attr("stroke-dasharray", s.dash)}/>` + label + meta + "</g>";
8883
10528
  }
@@ -10976,7 +12621,225 @@ function render(input, opts = {}) {
10976
12621
  diagnostics: diagram.diagnostics
10977
12622
  };
10978
12623
  }
12624
+ // src/integrations/node.ts
12625
+ /** Node-only helper for the CLI and build-time integrations: `import` reads from disk. */
12626
+ /** Reads an `import "..."` target from disk; like `parse`, only `.yu` files. */
12627
+ function diskResolve(path) {
12628
+ if (!isYuhwaPath(path)) return void 0;
12629
+ try {
12630
+ return readFileSync(path, "utf8");
12631
+ } catch {
12632
+ return;
12633
+ }
12634
+ }
12635
+ // src/core/tidy.ts
12636
+ /**
12637
+ * Hygiene rules for `yuhwa lint`. The diagram renders fine without fixing
12638
+ * these, so `check` stays quiet about them: unused classes, variables and
12639
+ * components, and edges written twice. A file that draws nothing is a library
12640
+ * for importers, so its definitions count as used.
12641
+ */
12642
+ /** `toks`: per-line tokens the caller already has; an empty line entry is lexed here */
12643
+ function tidy(source, d, toks) {
12644
+ const out = [];
12645
+ const warn = (code, line, message) => out.push({
12646
+ line: line + 1,
12647
+ message,
12648
+ severity: "warning",
12649
+ code
12650
+ });
12651
+ const library = !d.nodes.size && !d.edges.length && !d.panels.length;
12652
+ const exported = new Set(d.exports ?? []);
12653
+ const used = d.used ?? /* @__PURE__ */ new Set();
12654
+ if (!library) {
12655
+ const classes = Object.entries(d.classLines ?? {});
12656
+ const applied = new Set(classes.length ? source.split(/\r?\n/).flatMap((l, li) => (toks?.[li]?.length ? toks[li] : lex(l).tokens).filter((t, i) => i && t.kind === "class").map((t) => t.value)) : []);
12657
+ for (const [c, line] of classes) if (!exported.has("." + c) && !applied.has(c)) warn("unused-class", line, `Class .${c} is never used: apply it (node .${c}) or remove it`);
12658
+ for (const [v, line] of Object.entries(d.varLines ?? {})) if (!exported.has("$" + v) && !used.has("$" + v)) warn("unused-variable", line, `Variable $${v} is never used: use it ($${v}) or remove it`);
12659
+ for (const [f, line] of Object.entries(d.defLines ?? {})) if (!exported.has(f) && !used.has(f)) warn("unused-component", line, `Component ${f}() is never called: call it or remove it`);
12660
+ }
12661
+ const seen = /* @__PURE__ */ new Map();
12662
+ for (const e of d.edges) {
12663
+ if (!e.ref || e.ref.generated) continue;
12664
+ const key = [
12665
+ e.from,
12666
+ e.to,
12667
+ e.label ?? "",
12668
+ e.line,
12669
+ e.startHead,
12670
+ e.endHead
12671
+ ].join("\0");
12672
+ const first = seen.get(key);
12673
+ if (first === void 0) seen.set(key, e.ref.line);
12674
+ else if (first !== e.ref.line) warn("duplicate-edge", e.ref.line, `Edge ${e.from} -> ${e.to} is already drawn on line ${first + 1}: remove one`);
12675
+ }
12676
+ return out;
12677
+ }
12678
+ // src/lsp/format.ts
12679
+ /**
12680
+ * Formatting and text edits, without a parser of their own beyond `lex`.
12681
+ *
12682
+ * The formatter only touches whitespace: it re-indents blocks by two spaces,
12683
+ * trims line ends, keeps one blank line between statements and ends the file
12684
+ * with a newline. Panel and node bodies (`timeline t { … }`, `card { … }`)
12685
+ * belong to their plugin and may give indentation meaning, so they are moved
12686
+ * as a whole and keep their inner indentation. Lines of a `def` body are moved
12687
+ * the same way, since they may hold such bodies.
12688
+ */
12689
+ const lead = (l) => l.match(/^\s*/)[0].length;
12690
+ const leadTabs = (l) => l.match(/^[ \t]*/)[0].length;
12691
+ /** line ranges `[open, close]` whose inner lines are kept as they are */
12692
+ function verbatimBlocks(text, lines) {
12693
+ const d = parse(text);
12694
+ const out = [];
12695
+ const add = (r) => {
12696
+ if (r && r[1] > r[0] && /\{\s*(\/\/.*)?$/.test(lines[r[0]] ?? "") && lines[r[1]]?.trim() === "}") out.push(r);
12697
+ };
12698
+ for (const p of d.panels) add(p.lines);
12699
+ for (const n of d.nodes.values()) add(n.bodyLines);
12700
+ return out;
12701
+ }
12702
+ /** Format yuhwa source. Returns the new text; whitespace is all that changes. */
12703
+ function format(text) {
12704
+ if (isMermaid(text)) return text;
12705
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
12706
+ const lines = text.split(/\r?\n/);
12707
+ const verbatim = /* @__PURE__ */ new Map();
12708
+ for (const [s, e] of verbatimBlocks(text, lines)) for (let i = s + 1; i < e; i++) verbatim.set(i, s);
12709
+ const stack = [];
12710
+ const parent = [];
12711
+ const closes = [];
12712
+ const code = [];
12713
+ for (let i = 0; i < lines.length; i++) {
12714
+ if (verbatim.has(i)) {
12715
+ parent.push(void 0);
12716
+ closes.push(false);
12717
+ code.push(false);
12718
+ continue;
12719
+ }
12720
+ const toks = lex(lines[i]).tokens;
12721
+ const first = toks[0];
12722
+ const close = first?.kind === "punct" && first.value === "}";
12723
+ closes.push(close);
12724
+ parent.push(stack[stack.length - 1]);
12725
+ code.push(toks.length > 0);
12726
+ for (const b of blockBraces(toks)) if (b === "{") stack.push({
12727
+ open: i,
12728
+ def: /^\s*(export\s+)?def\b/.test(lines[i]) || !!stack[stack.length - 1]?.def
12729
+ });
12730
+ else stack.pop();
12731
+ }
12732
+ const level = [];
12733
+ const stacks = /* @__PURE__ */ new Map();
12734
+ lines.forEach((l, i) => {
12735
+ level.push(0);
12736
+ const closed = closes[i] && parent[i];
12737
+ if (closed) stacks.delete(parent[closed.open]?.open ?? -1);
12738
+ if (verbatim.has(i) || !l.trim() || closes[i] || parent[i]?.def) return;
12739
+ const k = parent[i]?.open ?? -1;
12740
+ const st = stacks.get(k) ?? [];
12741
+ stacks.set(k, st);
12742
+ const w = lead(l);
12743
+ if (!code[i]) {
12744
+ level[i] = Math.max(0, st.filter((x) => x <= w).length - 1);
12745
+ return;
12746
+ }
12747
+ while (st.length && st[st.length - 1] > w) st.pop();
12748
+ if (!st.length || st[st.length - 1] < w) st.push(w);
12749
+ level[i] = st.length - 1;
12750
+ });
12751
+ const indentOf = [];
12752
+ const out = [];
12753
+ const cuts = /* @__PURE__ */ new Map();
12754
+ const cutOf = (open, from) => {
12755
+ let c = cuts.get(open);
12756
+ if (c === void 0) {
12757
+ c = 1e400;
12758
+ for (let j = from; verbatim.get(j) === open; j++) if (lines[j].trim()) c = Math.min(c, leadTabs(lines[j]));
12759
+ cuts.set(open, c = Number.isFinite(c) ? c : 0);
12760
+ }
12761
+ return c;
12762
+ };
12763
+ const defCut = /* @__PURE__ */ new Map();
12764
+ for (let i = 0; i < lines.length; i++) {
12765
+ const raw = lines[i].replace(/\s+$/, "");
12766
+ const open = verbatim.get(i);
12767
+ if (open !== void 0) {
12768
+ const base = (indentOf[open] ?? 0) + 2;
12769
+ indentOf.push(base);
12770
+ out.push(raw ? " ".repeat(base) + raw.slice(cutOf(open, i)) : "");
12771
+ continue;
12772
+ }
12773
+ const p = parent[i];
12774
+ const base = p ? indentOf[p.open] + (closes[i] ? 0 : 2) : 0;
12775
+ let width = base;
12776
+ if (raw && !closes[i]) {
12777
+ if (p?.def) {
12778
+ let c = defCut.get(p.open);
12779
+ if (c === void 0) {
12780
+ c = 1e400;
12781
+ for (let j = i; j < lines.length; j++) if (parent[j] === p && lines[j].trim() && !closes[j]) c = Math.min(c, lead(lines[j]));
12782
+ defCut.set(p.open, c = Number.isFinite(c) ? c : 0);
12783
+ }
12784
+ width = base + Math.max(0, lead(raw) - c);
12785
+ } else width = base + level[i] * 2;
12786
+ }
12787
+ indentOf.push(width);
12788
+ out.push(raw ? " ".repeat(width) + raw.trimStart() : "");
12789
+ }
12790
+ const kept = [];
12791
+ for (const [i, l] of out.entries()) {
12792
+ const blank = !l;
12793
+ const inBody = verbatim.has(i);
12794
+ if (blank && !inBody && (!kept.length || kept[kept.length - 1] === "")) continue;
12795
+ kept.push(l);
12796
+ }
12797
+ while (kept.length && kept[kept.length - 1] === "") kept.pop();
12798
+ return kept.length ? kept.join(eol) + eol : "";
12799
+ }
12800
+ /** One edit that turns `a` into `b`, covering only what differs. */
12801
+ function diffEdits(a, b) {
12802
+ if (a === b) return [];
12803
+ let p = 0;
12804
+ while (p < a.length && p < b.length && a[p] === b[p]) p++;
12805
+ let q = 0;
12806
+ while (q < a.length - p && q < b.length - p && a[a.length - 1 - q] === b[b.length - 1 - q]) q++;
12807
+ return [{
12808
+ range: {
12809
+ start: positionAt(a, p),
12810
+ end: positionAt(a, a.length - q)
12811
+ },
12812
+ newText: b.slice(p, b.length - q)
12813
+ }];
12814
+ }
12815
+ /** LSP position of an offset. */
12816
+ function positionAt(text, offset) {
12817
+ const before = text.slice(0, offset).split("\n");
12818
+ return {
12819
+ line: before.length - 1,
12820
+ character: before[before.length - 1].length
12821
+ };
12822
+ }
12823
+ /** Offset of an LSP position (UTF-16 code units, as JS strings count). */
12824
+ function offsetAt(text, p) {
12825
+ let off = 0;
12826
+ for (let line = 0; line < p.line; line++) {
12827
+ const nl = text.indexOf("\n", off);
12828
+ if (nl < 0) return text.length;
12829
+ off = nl + 1;
12830
+ }
12831
+ const end = text.indexOf("\n", off);
12832
+ const lineEnd = end < 0 ? text.length : end;
12833
+ return Math.min(off + Math.max(0, p.character), lineEnd);
12834
+ }
12835
+ /** Apply one `didChange` content change: a range edit, or the whole text when it has no range. */
12836
+ function applyChange(text, change) {
12837
+ if (!change.range) return change.text;
12838
+ const a = offsetAt(text, change.range.start);
12839
+ const b = Math.max(a, offsetAt(text, change.range.end));
12840
+ return text.slice(0, a) + change.text + text.slice(b);
12841
+ }
10979
12842
  // src/version.ts
10980
12843
  /** the package version, inlined by the build */
10981
- const VERSION = "1.0.2";
10982
- export { PANEL_PROPS as C, TONES as D, THEME_NAMES as E, themeNames as O, NUMBERS as S, THEME_KEYS as T, BOOLS as _, canvasMeasure as a, GROUP_PROPS as b, KNOWN_SETTINGS as c, blockBraces as d, isYuhwaPath as f, serializeProps as g, parse as h, isMermaid as i, PANELS as l, lex as m, render as n, registry as o, joinPath as p, toSource as r, diskResolve as s, VERSION as t, SETTING_VALUES as u, EDGE_PROPS as v, SHAPES$2 as w, NODE_PROPS as x, ENUMS as y };
12844
+ const VERSION = "1.1.0";
12845
+ export { THEME_KEYS as A, ENUMS as C, PANEL_PROPS as D, NUMBERS as E, TONES as M, isSafeCss as N, SHAPES$2 as O, themeNames as P, EDGE_PROPS as S, NODE_PROPS as T, joinPath as _, tidy as a, serializeProps as b, toSource as c, registry as d, KNOWN_SETTINGS as f, isYuhwaPath as g, blockBraces as h, format as i, THEME_NAMES as j, esc$1 as k, canvasMeasure as l, SETTING_VALUES as m, applyChange as n, diskResolve as o, PANELS as p, diffEdits as r, render as s, VERSION as t, optionKind as u, lex as v, GROUP_PROPS as w, BOOLS as x, parse as y };