yuhwa 1.1.0 → 1.2.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 (39) hide show
  1. package/dist/astro.d.ts +1 -1
  2. package/dist/browser.d.ts +2 -2
  3. package/dist/browser.js +2 -2
  4. package/dist/cli.js +11 -6
  5. package/dist/editor/assets/index-BphHLTvA.js +689 -0
  6. package/dist/editor/assets/lsp.worker-sZtzIA6-.js +30 -0
  7. package/dist/editor/index.html +1 -1
  8. package/dist/{figure-db587hh6.d.ts → figure-CA2hy0xh.d.ts} +1 -1
  9. package/dist/{index-CAO4FUcz.d.ts → index-CnnoZYl0.d.ts} +29 -1
  10. package/dist/index.d.ts +2 -2
  11. package/dist/index.js +1 -1
  12. package/dist/ironmark.d.ts +1 -1
  13. package/dist/ironmark.js +1 -1
  14. package/dist/llms.txt +15 -10
  15. package/dist/lsp-browser.d.ts +2 -2
  16. package/dist/lsp-browser.js +1 -1
  17. package/dist/lsp-node.js +169 -31
  18. package/dist/lsp-server.d.ts +1 -1
  19. package/dist/lsp-server.js +1 -1
  20. package/dist/lsp.d.ts +44 -2
  21. package/dist/lsp.js +1 -1
  22. package/dist/markdown-it.d.ts +1 -1
  23. package/dist/markdown-it.js +1 -1
  24. package/dist/{node-DPojgovD.js → node-Bzn2uKXZ.js} +3 -3
  25. package/dist/remark.d.ts +1 -1
  26. package/dist/remark.js +1 -1
  27. package/dist/{server-BSHSx8uo.d.ts → server--jHjJjOS.d.ts} +1 -1
  28. package/dist/{server-CT_mbBNZ.js → server-Dxo7OG8K.js} +19 -2
  29. package/dist/{service-CNM6Z-RH.js → service-B1fpOg_L.js} +268 -29
  30. package/dist/{service-DquYYTVG.d.ts → service-Brvpt7Do.d.ts} +2 -0
  31. package/dist/{shared-B2rP00uA.js → shared-Ddw88O9D.js} +881 -417
  32. package/dist/{src-hrqH-a8K.js → src-DkQj7aIV.js} +855 -444
  33. package/dist/vite.d.ts +1 -1
  34. package/dist/vite.js +2 -2
  35. package/dist/vuepress.d.ts +1 -1
  36. package/dist/yuhwa.iife.js +63 -72
  37. package/package.json +1 -1
  38. package/dist/editor/assets/index-BGtCSg84.js +0 -689
  39. package/dist/editor/assets/lsp.worker-DUpBJRU2.js +0 -26
@@ -1,7 +1,44 @@
1
1
  import { readFileSync } from "node:fs";
2
+ // src/core/guard.ts
3
+ let sink = null;
4
+ /** run `fn` with plugin failures reported into `diags` */
5
+ function collecting(diags, fn) {
6
+ const prev = sink;
7
+ sink = diags;
8
+ try {
9
+ return fn();
10
+ } finally {
11
+ sink = prev;
12
+ }
13
+ }
14
+ /** record a plugin failure once per diagram */
15
+ function reportPluginError(plugin, what, e, line = 1) {
16
+ const message = `plugin "${plugin}": ${what} failed: ${e instanceof Error ? e.message : String(e)}`;
17
+ if (sink && !sink.some((d) => d.message === message)) sink.push({
18
+ line,
19
+ message,
20
+ severity: "error"
21
+ });
22
+ }
23
+ /** `fn`, but a throw reports and returns `fallback(...args)` */
24
+ function guard(plugin, what, fn, fallback) {
25
+ return function(...args) {
26
+ try {
27
+ return fn.apply(this, args);
28
+ } catch (e) {
29
+ reportPluginError(plugin, what, e);
30
+ return fallback(...args);
31
+ }
32
+ };
33
+ }
34
+ /**
35
+ * `o` without a prototype: a lookup by a name from the source (`theme:
36
+ * constructor`, `$toString`) then finds only the table's own keys.
37
+ */
38
+ const table = (o) => Object.setPrototypeOf(o, null);
2
39
  // src/core/theme.ts
3
40
  /** Colour ramps: [50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 950] */
4
- const RAMPS = {
41
+ const RAMPS = table({
5
42
  slate: [
6
43
  "#f8fafc",
7
44
  "#f1f5f9",
@@ -171,7 +208,7 @@ const RAMPS = {
171
208
  "#831843",
172
209
  "#500724"
173
210
  ]
174
- };
211
+ });
175
212
  RAMPS.violet = RAMPS.purple;
176
213
  RAMPS.rose = RAMPS.red;
177
214
  RAMPS.emerald = RAMPS.green;
@@ -233,7 +270,7 @@ const darkGroupTone = (t) => RAMPS[t] && {
233
270
  stroke: ramp(t, 800),
234
271
  text: ramp(t, 300)
235
272
  };
236
- const THEMES = { paper: {
273
+ const THEMES = table({ paper: {
237
274
  name: "paper",
238
275
  dark: false,
239
276
  background: "#fbfaf7",
@@ -268,7 +305,7 @@ const THEMES = { paper: {
268
305
  tone: lightTone,
269
306
  groupTone: lightGroupTone,
270
307
  edgeTone: (t) => ramp(t, 500)
271
- } };
308
+ } });
272
309
  const THEME_NAMES = Object.keys(THEMES);
273
310
  /** Add a theme (or replace one with the same name). Plugins call this through `use`. */
274
311
  function registerTheme(input) {
@@ -370,7 +407,7 @@ function fontStack(font) {
370
407
  * The keys a `theme name { … }` block (or `createTheme`) takes. Colours take
371
408
  * palette names (`slate-800`) or any CSS colour.
372
409
  */
373
- const THEME_KEYS = {
410
+ const THEME_KEYS = table({
374
411
  base: {
375
412
  info: "the theme to start from (default: paper)",
376
413
  kind: "word"
@@ -470,7 +507,7 @@ const THEME_KEYS = {
470
507
  kind: "color",
471
508
  values: ["none"]
472
509
  }
473
- };
510
+ });
474
511
  /**
475
512
  * Build a theme from flat `key: value` props (see `THEME_KEYS`) on top of a
476
513
  * base theme. Keys left out keep the base's value; palette colours in nodes
@@ -612,8 +649,91 @@ const isSafeLink = (v) => {
612
649
  ].includes(scheme[1].toLowerCase());
613
650
  };
614
651
  // src/core/inline.ts
652
+ /** the theme's node ink, with an optional text and line colour */
653
+ const nodeInk = (theme, text = theme.node.text, stroke = theme.node.stroke) => ({
654
+ text,
655
+ sub: theme.node.sub,
656
+ stroke
657
+ });
658
+ /** the same ink drawn in its muted colour: subtitles, meta and caps lines */
659
+ const subInk = (col) => ({
660
+ ...col,
661
+ text: col.sub
662
+ });
615
663
  const COLOR_RE = /^(#[0-9a-fA-F]{3,8}|[a-z]+(?:-\d{2,3})?)$/;
616
- const INLINE_RE = /\*\*(.+?)\*\*|~~(.+?)~~|`([^`]+)`|\[\[(.+?)\]\]|\{(#[0-9a-fA-F]{3,8}|[a-z]+(?:-\d{2,3})?):[ ]?(.+?)\}|\*(.+?)\*/g;
664
+ const LEGACY_RE = /^\{(#[0-9a-fA-F]{3,8}|[a-z]+(?:-\d{2,3})?):[ ]?(.+)\}$/;
665
+ const INLINE_RE = /\*\*(.{1,1000}?)\*\*|~~(.{1,1000}?)~~|`([^`]+)`|\[\[(.{1,1000}?)\]\]|\{([^{}|\n]{1,1000}?)[ ]?\|[ ]?(.{1,1000}?)\}|\{(#[0-9a-fA-F]{3,8}|[a-z]+(?:-\d{2,3})?):[ ]?(.{1,1000}?)\}|\*(.{1,1000}?)\*/g;
666
+ /** the span keys: `parseSpanStyle` and the LSP completion and hover read this */
667
+ const SPAN_KEYS = table({
668
+ color: {
669
+ aliases: ["text"],
670
+ info: "text colour: a palette name or any CSS colour",
671
+ values: TONES
672
+ },
673
+ size: {
674
+ aliases: ["font-size"],
675
+ info: "font size, px",
676
+ values: []
677
+ },
678
+ weight: {
679
+ aliases: ["font-weight"],
680
+ info: "font weight: 400, 600, 700 ...",
681
+ values: [
682
+ "300",
683
+ "400",
684
+ "500",
685
+ "600",
686
+ "700",
687
+ "800",
688
+ "900"
689
+ ]
690
+ },
691
+ italic: {
692
+ aliases: [],
693
+ info: "italic text",
694
+ values: ["true", "false"],
695
+ flag: true
696
+ },
697
+ bold: {
698
+ aliases: [],
699
+ info: "bold text, weight 700",
700
+ values: ["true", "false"],
701
+ flag: true
702
+ }
703
+ });
704
+ /** the span key a name or alias stands for */
705
+ const spanKey = (k) => k in SPAN_KEYS ? k : Object.keys(SPAN_KEYS).find((n) => SPAN_KEYS[n].aliases.includes(k));
706
+ /**
707
+ * `color: red, size: 18, weight: 700, italic` → a style; a bare colour sets the
708
+ * colour and a bare flag (`bold`, `italic`) means `true`. Undefined when any key is unknown.
709
+ */
710
+ function parseSpanStyle(spec) {
711
+ const st = {};
712
+ for (const part of spec.split(",")) {
713
+ const [k0, ...rest] = part.split(":");
714
+ const name = k0.trim();
715
+ if (!rest.length && isColorName(name)) {
716
+ st.color = name;
717
+ continue;
718
+ }
719
+ const k = spanKey(name);
720
+ if (!k) return;
721
+ const flag = SPAN_KEYS[k].flag;
722
+ const v = rest.length ? rest.join(":").trim() : flag ? "true" : "";
723
+ if (flag) {
724
+ if (v !== "true" && v !== "false") return;
725
+ if (v === "true") k === "italic" ? st.italic = true : st.weight = 700;
726
+ } else if (k === "color") {
727
+ if (!isColor(v)) return;
728
+ st.color = v;
729
+ } else {
730
+ const n = parseFloat(v);
731
+ if (!(n > 0 && n <= 1e3)) return;
732
+ k === "size" ? st.size = n : st.weight = n;
733
+ }
734
+ }
735
+ return st;
736
+ }
617
737
  /** true for `#hex` or a tone name (`green`, `green-600`) */
618
738
  const isColorName = (c) => COLOR_RE.test(c) && (c.startsWith("#") || isTone(c.replace(/-\d+$/, "")));
619
739
  /** Split one line of text into styled segments. */
@@ -655,10 +775,27 @@ function parseInline(s) {
655
775
  text: m[4]
656
776
  });
657
777
  } else if (m[5] !== void 0) {
658
- if (isColorName(m[5])) push({
778
+ const st = parseSpanStyle(m[5]);
779
+ const legacy = st ? null : m[0].match(LEGACY_RE);
780
+ if (st) push({
659
781
  kind: "color",
660
782
  text: m[6],
661
- color: m[5]
783
+ ...st
784
+ });
785
+ else if (legacy && isColorName(legacy[1])) push({
786
+ kind: "color",
787
+ text: legacy[2],
788
+ color: legacy[1]
789
+ });
790
+ else push({
791
+ kind: "text",
792
+ text: m[0]
793
+ });
794
+ } else if (m[7] !== void 0) {
795
+ if (isColorName(m[7])) push({
796
+ kind: "color",
797
+ text: m[8],
798
+ color: m[7]
662
799
  });
663
800
  else push({
664
801
  kind: "text",
@@ -666,7 +803,7 @@ function parseInline(s) {
666
803
  });
667
804
  } else push({
668
805
  kind: "muted",
669
- text: m[7]
806
+ text: m[9]
670
807
  });
671
808
  }
672
809
  push({
@@ -675,6 +812,60 @@ function parseInline(s) {
675
812
  });
676
813
  return out;
677
814
  }
815
+ /**
816
+ * Split a paragraph at spaces for wrapping, keeping each markup span whole so a
817
+ * `{red | two words}` never breaks across lines.
818
+ */
819
+ function splitWords(para) {
820
+ const keep = [];
821
+ for (const m of para.matchAll(INLINE_RE)) keep.push([m.index, m.index + m[0].length]);
822
+ const out = [];
823
+ let cur = "";
824
+ let k = 0;
825
+ for (let i = 0; i < para.length; i++) {
826
+ while (k < keep.length && keep[k][1] <= i) k++;
827
+ const inside = k < keep.length && keep[k][0] <= i;
828
+ if (para[i] === " " && !inside) {
829
+ if (cur) out.push(cur);
830
+ cur = "";
831
+ } else cur += para[i];
832
+ }
833
+ if (cur) out.push(cur);
834
+ return out;
835
+ }
836
+ /** a line with no markup characters needs no parsing (the common plain label) */
837
+ const MARKUP_RE = /[*~`[{]/;
838
+ /** segments of a label line; `caps` upper-cases the text, not the markup */
839
+ function richSegs(line, caps = false) {
840
+ const segs = MARKUP_RE.test(line) ? parseInline(line) : line ? [{
841
+ kind: "text",
842
+ text: line
843
+ }] : [];
844
+ if (caps) for (const x of segs) x.text = x.text.toUpperCase();
845
+ return segs;
846
+ }
847
+ /** width of one label line with markup, plus `spacing` per character */
848
+ function richW(line, fs, weight, mono, m, caps = false, spacing = 0) {
849
+ const segs = richSegs(line, caps);
850
+ return segsW(segs, fs, mono, m, weight) + (spacing ? spacing * [...plain(segs)].length : 0);
851
+ }
852
+ /** largest font size over label lines: a `{size: …}` span can make a line taller */
853
+ const linesSize = (lines, fs) => lines.reduce((a, l) => MARKUP_RE.test(l) ? parseInline(l).reduce((b, x) => Math.max(b, x.size ?? 0), a) : a, fs);
854
+ /** a line's height factor over its font size */
855
+ const LINE_HEIGHT = 1.3;
856
+ /** the line height of a block of label lines: its largest font size times `k` */
857
+ const lineHeight = (lines, fs, k = LINE_HEIGHT) => linesSize(lines, fs) * k;
858
+ /** one `<tspan>` per line at `x`, line `i` at `y(i)` */
859
+ const textLines = (lines, x, y, body) => lines.map((l, i) => `<tspan x="${f$2(x)}" y="${f$2(y(i))}">${body(l)}</tspan>`).join("");
860
+ /**
861
+ * The inside of a `<text>`/`<tspan>` for a label line: escaped text when it
862
+ * has no markup (so plain labels render as before), styled tspans otherwise.
863
+ */
864
+ function richText(line, col, theme, caps = false) {
865
+ const segs = richSegs(line, caps);
866
+ if (segs.every((x) => x.kind === "text")) return esc$1(plain(segs));
867
+ return tspans(segs, col, theme);
868
+ }
678
869
  /** the text without markup */
679
870
  const plain = (segs) => segs.map((x) => x.text).join("");
680
871
  /** Remove the common leading whitespace of the non-empty lines. */
@@ -693,13 +884,14 @@ const textEl = (x, y, fs, fill, body, extra = "") => `<text x="${f$2(x)}" y="${f
693
884
  /** resolve a tone or CSS colour for marks drawn on top of an element */
694
885
  const inkColor = (c, theme, fallback) => c && resolveColor(c, theme, theme.dark ? 400 : 600) || fallback;
695
886
  const CHIP_PAD = .55;
696
- const segWeight = (s, base) => s.kind === "bold" ? 700 : base;
887
+ const segWeight = (s, base) => s.weight ?? (s.kind === "bold" ? 700 : base);
697
888
  /** Measure segments (stores each width on the segment) and return the total. */
698
889
  function segsW(segs, fs, mono, m, weight = 400) {
699
890
  let total = 0;
700
891
  for (const s of segs) {
701
- const w = m(s.text, fs, segWeight(s, weight), mono);
702
- s.w = s.kind === "chip" ? w + fs * CHIP_PAD * 2 : w;
892
+ const size = s.size ?? fs;
893
+ const w = m(s.text, size, segWeight(s, weight), mono);
894
+ s.w = s.kind === "chip" ? w + size * CHIP_PAD * 2 : w;
703
895
  total += s.w;
704
896
  }
705
897
  return total;
@@ -728,7 +920,8 @@ function renderSegs(segs, x, cy, fs, col, theme, muted = false, weight = 400) {
728
920
  out.push(textEl(x + fs * CHIP_PAD, cy, fs, s.color ? c : col.text, esc$1(s.text), " xml:space=\"preserve\""));
729
921
  } else {
730
922
  const wt = segWeight(s, weight);
731
- out.push(textEl(x, cy, fs, c, esc$1(s.text), ` xml:space="preserve"${wt !== 400 ? ` font-weight="${wt}"` : ""}`));
923
+ const it = s.italic ? " font-style=\"italic\"" : "";
924
+ out.push(textEl(x, cy, s.size ?? fs, c, esc$1(s.text), ` xml:space="preserve"${wt !== 400 ? ` font-weight="${wt}"` : ""}${it}`));
732
925
  if (s.kind === "strike") {
733
926
  const lead = s.text.length - s.text.trimStart().length;
734
927
  const x0 = x + w * lead / Math.max(1, s.text.length);
@@ -746,7 +939,10 @@ function renderSegs(segs, x, cy, fs, col, theme, muted = false, weight = 400) {
746
939
  function tspans(segs, col, theme, muted = false) {
747
940
  return segs.map((s) => {
748
941
  const a = [`fill="${segColor(s, col, theme, muted)}"`];
749
- if (s.kind === "bold") a.push("font-weight=\"750\"");
942
+ if (s.size) a.push(`font-size="${f$2(s.size)}"`);
943
+ if (s.weight) a.push(`font-weight="${s.weight}"`);
944
+ else if (s.kind === "bold") a.push("font-weight=\"750\"");
945
+ if (s.italic) a.push("font-style=\"italic\"");
750
946
  if (s.kind === "strike") a.push("text-decoration=\"line-through\"");
751
947
  if (s.kind === "chip") a.push("font-weight=\"600\"");
752
948
  return `<tspan ${a.join(" ")}>${esc$1(s.text)}</tspan>`;
@@ -790,10 +986,27 @@ function withEdgeInk(t, p) {
790
986
  * thinner than the theme's edges unless the author asks for more
791
987
  */
792
988
  function edgeWidthOf(p) {
793
- const w = num$1(p["edge-width"], NaN);
794
- return w > 0 ? w : void 0;
989
+ return posNum(p["edge-width"]);
795
990
  }
991
+ /** a size, gap or width: 0 or more, else the default (a negative one breaks the SVG) */
992
+ const size = (v, d) => {
993
+ const n = num$1(v, NaN);
994
+ return n >= 0 ? n : d;
995
+ };
996
+ /** a positive number, else undefined */
997
+ const posNum = (v) => {
998
+ const n = num$1(v, NaN);
999
+ return n > 0 ? n : void 0;
1000
+ };
796
1001
  /** Merge class props then own props (own wins). */
1002
+ /** the shared text props (`font-size`, `font-weight`, `italic`) over an element's defaults */
1003
+ const textFont = (p, size, weight) => ({
1004
+ size: posNum(p["font-size"]) ?? size,
1005
+ weight: posNum(p["font-weight"]) ?? weight,
1006
+ italic: bool(p.italic, false)
1007
+ });
1008
+ /** an edge label's font */
1009
+ const edgeFont = (p, theme) => textFont(p, theme.fontSize * .86, 500);
797
1010
  function effectiveProps(d, decl) {
798
1011
  const out = {};
799
1012
  for (const c of decl.classes ?? []) Object.assign(out, d.classes[c]);
@@ -810,10 +1023,12 @@ function dashFor(style, width) {
810
1023
  function resolveNodeStyle(d, n, p, theme) {
811
1024
  const s = d.settings;
812
1025
  const tone = p.color ? theme.tone(p.color) : void 0;
813
- const strokeWidth = num$1(p.border ?? p["stroke-width"], num$1(s["stroke-width"], theme.strokeWidth));
1026
+ const strokeWidth = size(p.border ?? p["stroke-width"], size(s["stroke-width"], theme.strokeWidth));
814
1027
  const fill = resolveColor(p.fill, theme, theme.dark ? 900 : 100) ?? tone?.fill ?? theme.node.fill;
815
1028
  const stroke = resolveColor(p.stroke, theme, 500) ?? tone?.stroke ?? theme.node.stroke;
816
1029
  const text = resolveColor(p.text, theme, theme.dark ? 100 : 800) ?? tone?.text ?? theme.node.text;
1030
+ const font = textFont(p, posNum(s["font-size"]) ?? theme.fontSize, 500);
1031
+ const fontSize = font.size;
817
1032
  return {
818
1033
  fill,
819
1034
  stroke,
@@ -821,10 +1036,14 @@ function resolveNodeStyle(d, n, p, theme) {
821
1036
  sub: resolveColor(p["sub-color"], theme, 500) ?? (tone ? text : theme.node.sub),
822
1037
  strokeWidth,
823
1038
  dash: dashFor(lineStyle(p), strokeWidth),
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),
827
- italic: bool(p.italic, false),
1039
+ radius: size(p.radius, size(s.radius, theme.radius)),
1040
+ fontSize,
1041
+ fontWeight: bool(p.bold, false) ? 650 : font.weight,
1042
+ body: resolveColor(p["body-color"], theme, theme.dark ? 100 : 800) ?? text,
1043
+ bodySize: posNum(p["body-size"]) ?? Math.round(fontSize * .86 * 10) / 10,
1044
+ bodyWeight: posNum(p["body-weight"]) ?? 400,
1045
+ lineHeight: posNum(p["line-height"]) ?? 1.75,
1046
+ italic: font.italic,
828
1047
  shadow: bool(p.shadow, bool(s.shadow, theme.shadow !== null)),
829
1048
  opacity: num$1(p.opacity, 1)
830
1049
  };
@@ -875,9 +1094,9 @@ function resolvePanelStyle(p, T, base) {
875
1094
  fill,
876
1095
  stroke: noBorder ? "none" : resolveColor(p.stroke ?? borderColor, T, 300) ?? tone?.stroke ?? T.group.stroke,
877
1096
  text: resolveColor(p.text, T, T.dark ? 200 : 700) ?? tone?.text ?? T.title,
878
- width: num$1(p["border-width"], border && !borderColor && !noBorder ? num$1(border, 1) : 1),
1097
+ width: size(p["border-width"], border && !borderColor && !noBorder ? size(border, 1) : 1),
879
1098
  dash: borderDash(p, null),
880
- radius: num$1(p.radius, Math.min(14, T.radius + 4)),
1099
+ radius: size(p.radius, Math.min(14, T.radius + 4)),
881
1100
  shadow: bool(p.shadow, false)
882
1101
  };
883
1102
  }
@@ -885,7 +1104,7 @@ function resolveEdgeStyle(d, e, p, theme, defaultCurve) {
885
1104
  const toneColor = p.color ? theme.edgeTone(p.color) ?? resolveColor(p.color, theme, 500) : void 0;
886
1105
  const stroke = resolveColor(p.stroke, theme, theme.dark ? 400 : 500) ?? toneColor ?? theme.edge.stroke;
887
1106
  const base = e.line === "thick" || bool(p.thick, false) ? theme.edgeWidth * 2 : theme.edgeWidth;
888
- const width = num$1(p.width, base);
1107
+ const width = size(p.width, base);
889
1108
  const line = lineStyle(p, "style") ?? (e.line === "dashed" || e.line === "dotted" ? e.line : void 0);
890
1109
  const curve = [
891
1110
  "smooth",
@@ -893,12 +1112,16 @@ function resolveEdgeStyle(d, e, p, theme, defaultCurve) {
893
1112
  "straight"
894
1113
  ].includes(p.curve) ? p.curve : defaultCurve;
895
1114
  const flow = bool(p.flow ?? p.animate, false);
1115
+ const font = edgeFont(p, theme);
896
1116
  return {
897
1117
  stroke,
898
1118
  width,
899
1119
  dash: dashFor(line, width) ?? (flow ? `${width * 4} ${width * 3}` : null),
900
1120
  curve,
901
- text: resolveColor(p["label-color"], theme, 700) ?? (toneColor && !theme.dark ? resolveColor(p.color, theme, 700) : theme.edge.text),
1121
+ text: resolveColor(p.text ?? p["label-color"], theme, 700) ?? (toneColor && !theme.dark ? resolveColor(p.color, theme, 700) : theme.edge.text),
1122
+ fontSize: font.size,
1123
+ fontWeight: font.weight,
1124
+ italic: font.italic,
902
1125
  labelBg: resolveColor(p["label-bg"], theme, theme.dark ? 900 : 50) ?? theme.edge.labelBg,
903
1126
  flow,
904
1127
  opacity: num$1(p.opacity, 1)
@@ -1021,6 +1244,8 @@ function routeEdges(d, nodes, ctx) {
1021
1244
  bundles.get(k).push(e.key);
1022
1245
  }
1023
1246
  const fanGap = ctx.theme.fontSize * 2.1;
1247
+ const edgeByKey = new Map(d.edges.map((e) => [e.key, e]));
1248
+ const laneOffs = /* @__PURE__ */ new Map();
1024
1249
  for (const e of d.edges) {
1025
1250
  const a = nodes.get(e.from);
1026
1251
  const b = nodes.get(e.to);
@@ -1034,16 +1259,24 @@ function routeEdges(d, nodes, ctx) {
1034
1259
  if (bundle && bundle.length > 1) {
1035
1260
  const [lo, hi] = e.from < e.to ? [a, b] : [b, a];
1036
1261
  const dir = norm(sub(center(hi), center(lo)));
1037
- const lfs = ctx.theme.fontSize * .86;
1038
- const lane = (k) => {
1039
- const l = d.edges.find((x) => x.key === k)?.label;
1040
- const w = l ? Math.max(...l.split("\n").map((t) => ctx.measure(t, lfs, 500, ctx.theme.mono))) + 18 : 0;
1041
- return Math.max(fanGap, Math.abs(dir.y) * w + Math.abs(dir.x) * fanGap + 6);
1042
- };
1043
- const lanes = bundle.map(lane);
1044
- const total = lanes.reduce((x, y) => x + y, 0);
1045
- const i = bundle.indexOf(e.key);
1046
- const off = lanes.slice(0, i).reduce((x, y) => x + y, 0) + lanes[i] / 2 - total / 2;
1262
+ let offs = laneOffs.get(bundle);
1263
+ if (!offs) {
1264
+ const lanes = bundle.map((k) => {
1265
+ const x = edgeByKey.get(k);
1266
+ const font = x?.label ? edgeFont(effectiveProps(d, x), ctx.theme) : void 0;
1267
+ const w = font ? Math.max(...x.label.split("\n").map((t) => richW(t, font.size, font.weight, ctx.theme.mono, ctx.measure))) + 18 : 0;
1268
+ return Math.max(fanGap, Math.abs(dir.y) * w + Math.abs(dir.x) * fanGap + 6);
1269
+ });
1270
+ const total = lanes.reduce((x, y) => x + y, 0);
1271
+ offs = /* @__PURE__ */ new Map();
1272
+ let run = 0;
1273
+ for (let i = 0; i < bundle.length; i++) {
1274
+ offs.set(bundle[i], run + lanes[i] / 2 - total / 2);
1275
+ run += lanes[i];
1276
+ }
1277
+ laneOffs.set(bundle, offs);
1278
+ }
1279
+ const off = offs.get(e.key);
1047
1280
  const ca = center(a);
1048
1281
  const cb = center(b);
1049
1282
  if (off) via.push(add({
@@ -1165,14 +1398,17 @@ function buildEdge(it, ctx) {
1165
1398
  let label;
1166
1399
  const caption = it.e.props.caption;
1167
1400
  if (it.e.label || caption) {
1168
- const fs = ctx.theme.fontSize * .86;
1401
+ const fs = style.fontSize;
1402
+ const { mono } = ctx.theme;
1169
1403
  const lines = it.e.label ? it.e.label.split("\n") : [];
1170
- const pw = lines.length ? Math.max(...lines.map((l) => ctx.measure(l, fs, 500, ctx.theme.mono))) + (ctx.theme.edge.labelStroke ? 18 : 12) : 0;
1171
- const ph = lines.length ? lines.length * fs * 1.3 + 6 : 0;
1404
+ const pw = lines.length ? Math.max(...lines.map((l) => richW(l, fs, style.fontWeight, mono, ctx.measure))) + (ctx.theme.edge.labelStroke ? 18 : 12) : 0;
1405
+ const lh = lineHeight(lines, fs);
1406
+ const ph = lines.length ? lines.length * lh + 6 : 0;
1172
1407
  const cs = fs * .88;
1173
1408
  const capLines = caption ? caption.split("\n") : [];
1174
- const cw = capLines.length ? Math.max(...capLines.map((l) => ctx.measure(l, cs, 400, ctx.theme.mono))) + 8 : 0;
1175
- const chh = capLines.length * cs * 1.3 + (capLines.length ? 4 : 0);
1409
+ const cw = capLines.length ? Math.max(...capLines.map((l) => richW(l, cs, 400, mono, ctx.measure))) + 8 : 0;
1410
+ const clh = lineHeight(capLines, cs);
1411
+ const chh = capLines.length * clh + (capLines.length ? 4 : 0);
1176
1412
  const dx = Math.max(pw, cw) / 2;
1177
1413
  const dy0 = ph ? -ph / 2 : 0;
1178
1414
  const dy1 = (ph ? ph / 2 : 0) + chh;
@@ -1199,6 +1435,8 @@ function buildEdge(it, ctx) {
1199
1435
  w: pw,
1200
1436
  h: ph
1201
1437
  },
1438
+ lineHeight: lh,
1439
+ captionLineHeight: clh,
1202
1440
  rotate
1203
1441
  };
1204
1442
  }
@@ -1417,6 +1655,19 @@ function orthoRoute(S, n0, E, n1, via, a, b, obstacles) {
1417
1655
  x: B.x,
1418
1656
  y: my
1419
1657
  }]);
1658
+ let x0 = 1e400, y0 = 1e400, x1 = -1e400, y1 = -1e400;
1659
+ for (const q of [
1660
+ ...pts,
1661
+ ...candidates.flat(),
1662
+ B,
1663
+ E
1664
+ ]) {
1665
+ x0 = Math.min(x0, q.x);
1666
+ y0 = Math.min(y0, q.y);
1667
+ x1 = Math.max(x1, q.x);
1668
+ y1 = Math.max(y1, q.y);
1669
+ }
1670
+ const near = obstacles.filter((o) => o.x < x1 && o.x + o.w > x0 && o.y < y1 && o.y + o.h > y0);
1420
1671
  let best = null;
1421
1672
  let bestScore = 1e400;
1422
1673
  for (const c of candidates) {
@@ -1426,7 +1677,7 @@ function orthoRoute(S, n0, E, n1, via, a, b, obstacles) {
1426
1677
  B,
1427
1678
  E
1428
1679
  ]);
1429
- const s = scoreOrtho(full, obstacles);
1680
+ const s = scoreOrtho(full, near);
1430
1681
  if (s < bestScore) {
1431
1682
  bestScore = s;
1432
1683
  best = full;
@@ -1594,7 +1845,7 @@ const SHAPES$2 = [
1594
1845
  "note",
1595
1846
  "text"
1596
1847
  ];
1597
- const SHAPE_ALIASES = {
1848
+ const SHAPE_ALIASES = table({
1598
1849
  rect: "box",
1599
1850
  rectangle: "box",
1600
1851
  square: "box",
@@ -1613,7 +1864,7 @@ const SHAPE_ALIASES = {
1613
1864
  label: "text",
1614
1865
  plain: "text",
1615
1866
  none: "text"
1616
- };
1867
+ });
1617
1868
  function normalizeShape(s) {
1618
1869
  if (!s) return "rounded";
1619
1870
  const k = s.toLowerCase();
@@ -1853,12 +2104,23 @@ const PLACEMENT_PROPS = [
1853
2104
  "left-of",
1854
2105
  "rank"
1855
2106
  ];
2107
+ /**
2108
+ * Text props every element takes: nodes (label), edges (label), groups and
2109
+ * panels (title). Inline `{color: …, size: …, weight: …, italic | text}` spans
2110
+ * style part of a text.
2111
+ */
2112
+ const TEXT_PROPS = [
2113
+ "text",
2114
+ "font-size",
2115
+ "font-weight",
2116
+ "italic"
2117
+ ];
1856
2118
  const NODE_PROPS = [
1857
2119
  "shape",
1858
2120
  "color",
1859
2121
  "fill",
1860
2122
  "stroke",
1861
- "text",
2123
+ ...TEXT_PROPS,
1862
2124
  "sub",
1863
2125
  "sub-color",
1864
2126
  "icon",
@@ -1869,9 +2131,6 @@ const NODE_PROPS = [
1869
2131
  "dotted",
1870
2132
  "radius",
1871
2133
  "bold",
1872
- "italic",
1873
- "font-size",
1874
- "font-weight",
1875
2134
  "shadow",
1876
2135
  "opacity",
1877
2136
  "width",
@@ -1881,6 +2140,10 @@ const NODE_PROPS = [
1881
2140
  "meta",
1882
2141
  "caps",
1883
2142
  "mono",
2143
+ "body-size",
2144
+ "body-color",
2145
+ "body-weight",
2146
+ "line-height",
1884
2147
  "max-width",
1885
2148
  ...PLACEMENT_PROPS
1886
2149
  ];
@@ -1895,6 +2158,7 @@ const EDGE_PROPS = [
1895
2158
  "flow",
1896
2159
  "animate",
1897
2160
  "opacity",
2161
+ ...TEXT_PROPS,
1898
2162
  "label-color",
1899
2163
  "label-bg",
1900
2164
  "dashed",
@@ -1913,7 +2177,7 @@ const GROUP_PROPS = [
1913
2177
  "color",
1914
2178
  "fill",
1915
2179
  "stroke",
1916
- "text",
2180
+ ...TEXT_PROPS,
1917
2181
  "border-style",
1918
2182
  "dashed",
1919
2183
  "dotted",
@@ -1928,7 +2192,7 @@ const PANEL_PROPS = [
1928
2192
  "fill",
1929
2193
  "border",
1930
2194
  "stroke",
1931
- "text",
2195
+ ...TEXT_PROPS,
1932
2196
  "border-width",
1933
2197
  "border-style",
1934
2198
  "radius",
@@ -1938,7 +2202,7 @@ const PANEL_PROPS = [
1938
2202
  "edge-width"
1939
2203
  ];
1940
2204
  /** allowed values for enum-like props */
1941
- const ENUMS = {
2205
+ const ENUMS = table({
1942
2206
  shape: [...SHAPES$2, ...Object.keys(SHAPE_ALIASES)],
1943
2207
  "border-style": LINE_STYLES,
1944
2208
  style: LINE_STYLES,
@@ -1949,9 +2213,27 @@ const ENUMS = {
1949
2213
  "from-side": SIDES$1,
1950
2214
  enter: SIDES$1,
1951
2215
  "to-side": SIDES$1
1952
- };
1953
- /** props whose value must be a colour */
1954
- const COLOR_PROPS = ["color"];
2216
+ });
2217
+ /** props whose value must be a colour (or `none`/`transparent`), on nodes, edges, groups and panels */
2218
+ const COLORS = [
2219
+ "color",
2220
+ "fill",
2221
+ "stroke",
2222
+ "text",
2223
+ "sub-color",
2224
+ "body-color",
2225
+ "label-color",
2226
+ "label-bg",
2227
+ "background",
2228
+ "edge-color"
2229
+ ];
2230
+ const badColor = (v) => ![
2231
+ "none",
2232
+ "transparent",
2233
+ "currentcolor",
2234
+ "inherit"
2235
+ ].includes(v.toLowerCase()) && !/^var\(--[\w-]+\)$/.test(v) && !isColor(v);
2236
+ const colorHint = (v) => didYouMean(v, TONES) || `: use a palette name (${TONES.join(", ")}), #hex, rgb(), hsl() or a CSS colour name`;
1955
2237
  const BOOLS = [
1956
2238
  "dashed",
1957
2239
  "dotted",
@@ -1976,7 +2258,10 @@ const NUMBERS = [
1976
2258
  "width",
1977
2259
  "height",
1978
2260
  "max-width",
1979
- "length"
2261
+ "length",
2262
+ "body-size",
2263
+ "body-weight",
2264
+ "line-height"
1980
2265
  ];
1981
2266
  function distance(a, b) {
1982
2267
  const dp = Array.from({ length: b.length + 1 }, (_, i) => i);
@@ -2017,12 +2302,12 @@ function checkProps$1(props, allowed, what, line0, warn, propLines) {
2017
2302
  }
2018
2303
  const opts = ENUMS[k];
2019
2304
  const word = k === "frame" ? v.trim().split(/\s+/)[0].toLowerCase() : v.toLowerCase();
2020
- if (COLOR_PROPS.includes(k) && !isColor(v)) warn(line, `Unknown ${k} "${v}"${didYouMean(v, TONES) || `: use a palette name (${TONES.join(", ")}), #hex, rgb(), hsl() or a CSS colour name`}`);
2305
+ if (COLORS.includes(k) && badColor(v)) warn(line, `Unknown ${k} "${v}"${colorHint(v)}`);
2021
2306
  else if (opts && !opts.includes(word)) {
2022
2307
  const shown = k === "shape" ? SHAPES$2 : opts;
2023
2308
  warn(line, `Unknown ${k} "${v}"${didYouMean(v, opts) || ` (use one of: ${shown.join(", ")})`}`);
2024
2309
  } else if (BOOLS.includes(k) && !["true", "false"].includes(v)) warn(line, `${k} expects true or false, got "${v}"`);
2025
- else if (NUMBERS.includes(k) && !Number.isFinite(parseFloat(v))) warn(line, `${k} expects a number, got "${v}"`);
2310
+ else if (NUMBERS.includes(k) && !(parseFloat(v) >= 0 && Number.isFinite(parseFloat(v)))) warn(line, `${k} expects a number of 0 or more, got "${v}"`);
2026
2311
  else if (k === "link" && !isSafeLink(v)) warn(line, `link "${v}" is not rendered: use http(s), mailto, an #anchor or a relative path`);
2027
2312
  }
2028
2313
  }
@@ -2045,6 +2330,8 @@ function checkPanelOptions(props, options, line, warn) {
2045
2330
  * The placement prop a node uses (the first one written) and its anchor id.
2046
2331
  * Layout reads the same choice, so the warnings below describe what it does.
2047
2332
  */
2333
+ /** the 0-based line where a node's prop `key` was written: its own line below, its `[...]`, or the declaration */
2334
+ const propLine = (n, key) => n.ref?.propLines?.[key] ?? n.propAt?.[key] ?? n.ref?.line;
2048
2335
  function placementOf(props) {
2049
2336
  for (const [k, v] of Object.entries(props)) if (PLACEMENT_PROPS.includes(k) && v) return [k, v.trim()];
2050
2337
  }
@@ -2055,10 +2342,9 @@ function checkPlacement(d, warn) {
2055
2342
  const p = effectiveProps(d, n);
2056
2343
  const used = placementOf(p);
2057
2344
  if (!used) continue;
2058
- const at = (k) => n.ref?.propLines?.[k] ?? n.ref?.line;
2059
2345
  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`);
2346
+ const line = propLine(n, key);
2347
+ for (const k of Object.keys(p)) if (k !== key && PLACEMENT_PROPS.includes(k) && n.ref) warn(propLine(n, k), `${n.id} already has ${key}: ${id}, so ${k} is ignored. A node takes one placement prop`);
2062
2348
  if (id === n.id) {
2063
2349
  if (n.ref) warn(line, `${key}: ${id} places ${n.id} next to itself; use another node's id`);
2064
2350
  continue;
@@ -2083,7 +2369,7 @@ function checkPlacement(d, warn) {
2083
2369
  chain.forEach((id) => reported.add(id));
2084
2370
  const n = d.nodes.get(start);
2085
2371
  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`);
2372
+ if (n.ref) warn(propLine(n, key), `placement loop: ${[...chain, start].join(" → ")}. These nodes cannot all be placed; remove one placement prop`);
2087
2373
  }
2088
2374
  }
2089
2375
  /** ids that differ only in their numbers (`s1`, `s2`) are a series, not a typo */
@@ -2120,7 +2406,10 @@ function lint(d, panelOptions) {
2120
2406
  message,
2121
2407
  severity: "warning"
2122
2408
  });
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);
2409
+ for (const n of d.nodes.values()) if (n.ref) checkProps$1(n.props, NODE_PROPS, "node", n.ref.line, warn, {
2410
+ ...n.propAt,
2411
+ ...n.ref.propLines
2412
+ });
2124
2413
  checkPlacement(d, warn);
2125
2414
  const seen = /* @__PURE__ */ new Set();
2126
2415
  for (const e of d.edges) {
@@ -2138,13 +2427,7 @@ function lint(d, panelOptions) {
2138
2427
  const line = p.lines?.[0] ?? p.ref.line;
2139
2428
  const pp = p.props;
2140
2429
  if (pp.theme && !names.includes(pp.theme)) warn(line, `Unknown theme "${pp.theme}"${didYouMean(pp.theme, names) || ` (themes: ${names.join(", ")})`}`);
2141
- for (const k of [
2142
- "background",
2143
- "fill",
2144
- "stroke",
2145
- "text",
2146
- "edge-color"
2147
- ]) if (pp[k] && !["none", "transparent"].includes(pp[k]) && !isColor(pp[k])) warn(line, `Unknown ${k} "${pp[k]}"${didYouMean(pp[k], TONES) || ": use a palette name, #hex, rgb(), hsl() or a CSS colour name"}`);
2430
+ for (const k of COLORS) if (pp[k] && badColor(pp[k])) warn(line, `Unknown ${k} "${pp[k]}"${colorHint(pp[k])}`);
2148
2431
  const b = pp.border;
2149
2432
  if (b && !["none", "false"].includes(b) && !isColor(b) && !Number.isFinite(parseFloat(b))) warn(line, `border takes a colour, a width or none, got "${b}"`);
2150
2433
  if (pp["border-style"] && !LINE_STYLES.includes(pp["border-style"])) warn(line, `Unknown border-style "${pp["border-style"]}" (use one of: ${LINE_STYLES.join(", ")})`);
@@ -2161,38 +2444,6 @@ function lint(d, panelOptions) {
2161
2444
  }
2162
2445
  d.diagnostics.sort((a, b) => a.line - b.line);
2163
2446
  }
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
- }
2196
2447
  // src/core/parse.ts
2197
2448
  const THEME_KEY_NAMES = Object.keys(THEME_KEYS);
2198
2449
  const KNOWN_SETTINGS = /* @__PURE__ */ new Set([
@@ -2221,7 +2472,7 @@ const KNOWN_SETTINGS = /* @__PURE__ */ new Set([
2221
2472
  "edge-width"
2222
2473
  ]);
2223
2474
  /** other tools' diagram names → the yuhwa panel header to write instead (`ID` is the panel id) */
2224
- const PANEL_ALIASES = {
2475
+ const PANEL_ALIASES = table({
2225
2476
  pie: "chart ID [type: pie]",
2226
2477
  donut: "chart ID [type: donut]",
2227
2478
  bar: "chart ID",
@@ -2235,7 +2486,7 @@ const PANEL_ALIASES = {
2235
2486
  board: "kanban ID",
2236
2487
  tree: "treeview ID",
2237
2488
  filetree: "treeview ID"
2238
- };
2489
+ });
2239
2490
  /** panel kinds by keyword, filled by `use` (see plugin.ts) */
2240
2491
  const PANELS = /* @__PURE__ */ new Map();
2241
2492
  /** plugin statements by keyword, filled by `use` */
@@ -2244,7 +2495,7 @@ const STATEMENTS = /* @__PURE__ */ new Map();
2244
2495
  const TRANSFORMS = [];
2245
2496
  /** Mermaid-style direction names are accepted too */
2246
2497
  /** settings with a fixed set of values; `theme` is checked against the registered themes */
2247
- const SETTING_VALUES = {
2498
+ const SETTING_VALUES = table({
2248
2499
  direction: [
2249
2500
  "right",
2250
2501
  "down",
@@ -2262,14 +2513,14 @@ const SETTING_VALUES = {
2262
2513
  "grid",
2263
2514
  "wrap"
2264
2515
  ]
2265
- };
2266
- const DIRECTION_ALIASES = {
2516
+ });
2517
+ const DIRECTION_ALIASES = table({
2267
2518
  lr: "right",
2268
2519
  rl: "left",
2269
2520
  tb: "down",
2270
2521
  td: "down",
2271
2522
  bt: "up"
2272
- };
2523
+ });
2273
2524
  const TONE_SET = /* @__PURE__ */ new Set([...TONES, "violet"]);
2274
2525
  const CURVES = /* @__PURE__ */ new Set([
2275
2526
  "smooth",
@@ -2305,7 +2556,7 @@ const SIDES = /* @__PURE__ */ new Set([
2305
2556
  ]);
2306
2557
  const IDENT_RE = /^[\p{L}_][\p{L}\p{N}_]*(?:-[\p{L}\p{N}_]+)*/u;
2307
2558
  const ARROW_RE = /^(<)?(--|-|\.\.|==|=)(>)?/;
2308
- const CLASS_RE = /^\.[\p{L}_][\p{L}\p{N}_-]*/u;
2559
+ const CLASS_RE$1 = /^\.[\p{L}_][\p{L}\p{N}_-]*/u;
2309
2560
  const NUMBER_RE = /^-?\d+(?:\.\d+)?/;
2310
2561
  function unescape(s) {
2311
2562
  return s.replace(/\\(n|t|"|'|\\)/g, (_, c) => c === "n" ? "\n" : c === "t" ? " " : c);
@@ -2370,7 +2621,7 @@ function lex(line) {
2370
2621
  i += m[0].length;
2371
2622
  continue;
2372
2623
  }
2373
- if (m = rest.match(CLASS_RE)) {
2624
+ if (m = rest.match(CLASS_RE$1)) {
2374
2625
  tokens.push({
2375
2626
  kind: "class",
2376
2627
  value: m[0].slice(1),
@@ -2448,6 +2699,11 @@ function blockBraces(tokens) {
2448
2699
  }
2449
2700
  return out;
2450
2701
  }
2702
+ /** Merge `[...]` props into a node, noting the line each one came from. */
2703
+ function addNodeProps(n, props, li) {
2704
+ Object.assign(n.props, props);
2705
+ for (const k in props) (n.propAt ??= {})[k] = li;
2706
+ }
2451
2707
  /** Parse the inside of a `[...]` block: `key: value, key: value, flag` */
2452
2708
  /** `[...]` after a node id. `A[Web Server]` is Mermaid for a label, not a prop list. */
2453
2709
  function nodeProps(tok, id, li, warn) {
@@ -2510,8 +2766,13 @@ function parseProps(raw = "") {
2510
2766
  }
2511
2767
  return out;
2512
2768
  }
2769
+ /** `text // comment` → `text`; a search for one fixed-width mark, so a long whitespace run stays linear */
2770
+ const stripComment = (s) => {
2771
+ const i = s.search(/\s\/\//);
2772
+ return i < 0 ? s : s.slice(0, i).trimEnd();
2773
+ };
2513
2774
  /** a `[props]` group ending a line; `[[x]]` (an inline chip) is not one */
2514
- const TRAILING_PROPS$1 = /\s*(?<!\[)\[([^[\]]*)\]\s*$/;
2775
+ const TRAILING_PROPS$1 = /(?<!\[)\[([^[\]]*)\]\s*$/;
2515
2776
  /**
2516
2777
  * `text [props]` → the text before the bracket and its props. `accept` may
2517
2778
  * refuse a bracket (it then stays part of the text), e.g. one whose keys
@@ -2520,7 +2781,7 @@ const TRAILING_PROPS$1 = /\s*(?<!\[)\[([^[\]]*)\]\s*$/;
2520
2781
  function splitTrailingProps(text, accept) {
2521
2782
  const m = text.match(TRAILING_PROPS$1);
2522
2783
  const p = m ? parseProps(m[1]) : void 0;
2523
- return p && (!accept || accept(p)) ? [text.slice(0, m.index), p] : [text, {}];
2784
+ return p && (!accept || accept(p)) ? [text.slice(0, m.index).trimEnd(), p] : [text, {}];
2524
2785
  }
2525
2786
  /**
2526
2787
  * Set or remove one prop in the `[...]` at the end of a line, adding or
@@ -2570,7 +2831,7 @@ function serializeProps(props) {
2570
2831
  return Object.entries(props).map(([k, v]) => {
2571
2832
  if (v === "true" && !TONE_SET.has(k) && !isShape(k) && !CURVES.has(k) && !isColor(k)) return k;
2572
2833
  if (k === "color" && isColor(v) && !isShape(v) && !CURVES.has(v.toLowerCase()) && !/[;[\]]/.test(v)) return v;
2573
- return `${k}: ${/[,;[\]]|^\s|\s$|^$/.test(v) || v.includes("\n") ? JSON.stringify(v) : v}`;
2834
+ return `${k}: ${/[,;[\]"'()\n\r]|^\s|\s$|^$/.test(v) ? quote(v) : v}`;
2574
2835
  }).join(", ");
2575
2836
  }
2576
2837
  function arrowInfo(a) {
@@ -2589,8 +2850,11 @@ function arrowInfo(a) {
2589
2850
  line
2590
2851
  };
2591
2852
  }
2853
+ /** caps that keep a hostile source from hanging `render()` */
2854
+ const MAX_LINE = 1e5;
2855
+ const MAX_EXPANSION = 5e4;
2592
2856
  const VAR_RE = /\$\$|\$\{([A-Za-z_]\w*)\}|\$([A-Za-z_]\w*)/g;
2593
- const VAR_DEF_RE = /^\s*\$([A-Za-z_]\w*)\s*[:=]\s*(.*?)\s*$/;
2857
+ const VAR_DEF_RE = /^\s*\$([A-Za-z_]\w*)\s*[:=]\s*(.*)$/;
2594
2858
  const DEF_RE = /^\s*def\s+([\p{L}_][\p{L}\p{N}_-]*)\s*\(([^)]*)\)\s*\{\s*$/u;
2595
2859
  const CALL_RE = /^\s*([\p{L}_][\p{L}\p{N}_-]*)\s*\((.*)\)\s*$/u;
2596
2860
  /** the components a component sees: those of the file it was defined in */
@@ -2621,6 +2885,8 @@ function splitList$1(s) {
2621
2885
  if (cur.trim() || out.length) out.push(cur.trim());
2622
2886
  return out;
2623
2887
  }
2888
+ /** `s` as a double-quoted string the lexer reads back unchanged (the inverse of `unescape`) */
2889
+ const quote = (s) => `"${s.replace(/[\\"]/g, "\\$&").replace(/\r\n?|\n/g, "\\n").replace(/\t/g, "\\t")}"`;
2624
2890
  const unquote = (s) => /^(["']).*\1$/s.test(s.trim()) ? unescape(s.trim().slice(1, -1)) : s.trim();
2625
2891
  function parse(source, opts = {}) {
2626
2892
  const d = {
@@ -2628,7 +2894,7 @@ function parse(source, opts = {}) {
2628
2894
  nodes: /* @__PURE__ */ new Map(),
2629
2895
  edges: [],
2630
2896
  groups: /* @__PURE__ */ new Map(),
2631
- classes: {},
2897
+ classes: table({}),
2632
2898
  layout: {
2633
2899
  nodes: {},
2634
2900
  edges: {}
@@ -2636,11 +2902,15 @@ function parse(source, opts = {}) {
2636
2902
  panels: [],
2637
2903
  diagnostics: []
2638
2904
  };
2639
- const lines = source.split("\n");
2905
+ const lines = source.split(/\r?\n/);
2640
2906
  const merged = opts.seen ??= /* @__PURE__ */ new Set();
2641
2907
  if (opts.file) merged.add(opts.file);
2642
2908
  /** names marked with `export` (filtered to what exists at the end) */
2643
- const exported = /* @__PURE__ */ new Set();
2909
+ /** exported name to the line that exports it */
2910
+ const exported = /* @__PURE__ */ new Map();
2911
+ /** every `.class` written on a node, edge or group, with its line: checked once all classes are known */
2912
+ const classUses = [];
2913
+ const useClass = (c, li) => classUses.push([c, li]);
2644
2914
  let hasExport = false;
2645
2915
  const stack = [];
2646
2916
  const edgeCount = /* @__PURE__ */ new Map();
@@ -2660,7 +2930,7 @@ function parse(source, opts = {}) {
2660
2930
  const themeLines = /* @__PURE__ */ new Map();
2661
2931
  const defineTheme = (name, props, li) => {
2662
2932
  if (themeLines.has(name)) warn(li, `Theme "${name}" is defined twice`);
2663
- (d.themes ??= {})[name] = props;
2933
+ (d.themes ??= table({}))[name] = props;
2664
2934
  themeLines.set(name, li);
2665
2935
  };
2666
2936
  const currentGroup = () => {
@@ -2730,33 +3000,47 @@ function parse(source, opts = {}) {
2730
3000
  mergeDiagram(d, narrowed, edgeCount);
2731
3001
  (d.imports ??= []).push(path, ...sub.imports ?? []);
2732
3002
  };
2733
- const vars = d.vars = {};
2734
- const defs = d.defs = {};
3003
+ const vars = d.vars = table({});
3004
+ const defs = d.defs = table({});
2735
3005
  const used = d.used = /* @__PURE__ */ new Set();
2736
3006
  SCOPE.set(defs, defs);
2737
3007
  /** set while a line comes from a variable or a component: refs then carry `generated` */
2738
3008
  let gen = false;
2739
3009
  let depth = 0;
3010
+ /** lines stamped out by component calls so far: recursion that fans out stops at MAX_EXPANSION */
3011
+ let expanded = 0;
3012
+ const tooDeep = /* @__PURE__ */ new Set();
2740
3013
  let lastDecl = null;
2741
3014
  const indentOf = (line) => line.match(/^\s*/)[0].length;
2742
3015
  /** `$name` → its value; params of a component call shadow the file's variables */
2743
3016
  const substitute = (line, li, local, quiet = false) => {
2744
3017
  const v = line.match(VAR_DEF_RE);
2745
3018
  if (v) return line.slice(0, line.length - v[2].length) + substitute(v[2], li, local, quiet);
2746
- return line.replace(VAR_RE, (all, braced, bare) => {
3019
+ let size = line.length;
3020
+ const out = line.replace(VAR_RE, (all, braced, bare) => {
2747
3021
  const name = braced ?? bare;
2748
3022
  if (!name) return "$";
2749
3023
  const value = local?.[name] ?? vars[name];
2750
3024
  if (local?.[name] === void 0 && value !== void 0) used.add("$" + name);
2751
- if (value !== void 0) return value;
3025
+ if (value !== void 0) return (size += value.length) > MAX_LINE ? all : value;
2752
3026
  if (!quiet) warn(li, `Unknown variable "$${name}"${didYouMean(name, [...Object.keys(local ?? {}), ...Object.keys(vars)])}`);
2753
3027
  return all;
2754
3028
  });
3029
+ if (size > MAX_LINE) warn(li, `Variables make this line longer than ${MAX_LINE} characters`, "error");
3030
+ return out;
2755
3031
  };
2756
3032
  const expand = (def, argText, li) => {
2757
- if (depth >= 16) return void warn(li, `${def.name}(): calls nest too deep`, "error");
3033
+ if (depth >= 16) {
3034
+ if (!tooDeep.has(def.name)) warn(li, `${def.name}(): calls nest too deep`, "error");
3035
+ tooDeep.add(def.name);
3036
+ return;
3037
+ }
3038
+ if ((expanded += def.body.length) > MAX_EXPANSION) {
3039
+ if (expanded - def.body.length <= MAX_EXPANSION) warn(li, `${def.name}(): components expand to more than ${MAX_EXPANSION} lines`, "error");
3040
+ return;
3041
+ }
2758
3042
  const args = splitList$1(argText);
2759
- const local = {};
3043
+ const local = table({});
2760
3044
  let pos = 0;
2761
3045
  for (const a of args) {
2762
3046
  const named = a.match(/^([A-Za-z_]\w*)\s*[:=]\s*([\s\S]*)$/);
@@ -2793,7 +3077,7 @@ function parse(source, opts = {}) {
2793
3077
  stack.pop();
2794
3078
  if (raw0.trim() !== "}") warn(li, `Expected "}" alone on the line that closes ${top.id}()`, "error");
2795
3079
  const params = top.params;
2796
- const own = Object.fromEntries(params.map((p) => [p.name, `\${${p.name}}`]));
3080
+ const own = table(Object.fromEntries(params.map((p) => [p.name, `\${${p.name}}`])));
2797
3081
  const def = {
2798
3082
  name: top.id,
2799
3083
  params,
@@ -2809,7 +3093,7 @@ function parse(source, opts = {}) {
2809
3093
  if (!verbatim && top?.kind !== "layout") {
2810
3094
  const v = raw0.match(VAR_DEF_RE);
2811
3095
  if (v) {
2812
- vars[v[1]] = unquote((done ? v[2] : substitute(v[2], li)).replace(/\s+\/\/.*$/, ""));
3096
+ vars[v[1]] = unquote(stripComment(done ? v[2] : substitute(v[2], li)).trimEnd());
2813
3097
  (d.varLines ??= {})[v[1]] = li;
2814
3098
  return;
2815
3099
  }
@@ -2834,7 +3118,7 @@ function parse(source, opts = {}) {
2834
3118
  });
2835
3119
  return;
2836
3120
  }
2837
- const c = raw0.replace(/\s+\/\/.*$/, "").match(CALL_RE);
3121
+ const c = stripComment(raw0).match(CALL_RE);
2838
3122
  if (c) {
2839
3123
  const def = scope[c[1]] ?? defs[c[1]];
2840
3124
  if (def) {
@@ -2927,9 +3211,10 @@ function parse(source, opts = {}) {
2927
3211
  }
2928
3212
  hasExport = true;
2929
3213
  const list = t.slice(1).every((x) => x.kind === "ident" || x.kind === "class" || x.value === ",");
2930
- if (t[1].value === "def" && t[2]) exported.add(t[2].value);
2931
- else if (t[1].value.startsWith("$") && (t[2]?.value === ":" || t[2]?.value === "=")) exported.add(t[1].value);
2932
- else for (const x of t.slice(1)) if (x.kind === "ident" || x.kind === "class") exported.add(x.kind === "class" ? `.${x.value}` : x.value);
3214
+ const exp = (name) => exported.has(name) || exported.set(name, li);
3215
+ if (t[1].value === "def" && t[2]) exp(t[2].value);
3216
+ else if (t[1].value.startsWith("$") && (t[2]?.value === ":" || t[2]?.value === "=")) exp(t[1].value);
3217
+ else for (const x of t.slice(1)) if (x.kind === "ident" || x.kind === "class") exp(x.kind === "class" ? `.${x.value}` : x.value);
2933
3218
  if (list && !t.slice(1).some((x) => x.kind === "ident" && PANELS.has(x.value))) return;
2934
3219
  return step(raw.slice(0, t[0].start) + " ".repeat(6) + raw.slice(t[0].end), li);
2935
3220
  };
@@ -3041,7 +3326,10 @@ function parse(source, opts = {}) {
3041
3326
  at: t[1].end
3042
3327
  };
3043
3328
  if (gen) g.labelRef.generated = true;
3044
- while (t[k]?.kind === "class") (g.classes ??= []).push(t[k++].value);
3329
+ while (t[k]?.kind === "class") {
3330
+ useClass(t[k].value, li);
3331
+ (g.classes ??= []).push(t[k++].value);
3332
+ }
3045
3333
  const ref = {
3046
3334
  line: li,
3047
3335
  insertAt: t[k - 1].end,
@@ -3126,7 +3414,7 @@ function parse(source, opts = {}) {
3126
3414
  };
3127
3415
  const edgeStmt = (t, raw, li, codeEnd) => {
3128
3416
  const ne = d.edges.length;
3129
- parseEdgeStatement(t, li, raw.slice(0, codeEnd), d, touchNode, edgeCount, warn, relabel);
3417
+ parseEdgeStatement(t, li, raw.slice(0, codeEnd), d, touchNode, edgeCount, warn, relabel, useClass);
3130
3418
  lastDecl = {
3131
3419
  indent: indentOf(raw),
3132
3420
  targets: d.edges.slice(ne)
@@ -3190,6 +3478,7 @@ function parse(source, opts = {}) {
3190
3478
  };
3191
3479
  while (t[k]?.kind === "class") {
3192
3480
  const c = t[k++].value;
3481
+ useClass(c, li);
3193
3482
  if (!n.classes.includes(c)) n.classes.push(c);
3194
3483
  }
3195
3484
  const ref = {
@@ -3198,7 +3487,7 @@ function parse(source, opts = {}) {
3198
3487
  generated: gen || void 0
3199
3488
  };
3200
3489
  if (t[k]?.kind === "props") {
3201
- Object.assign(n.props, nodeProps(t[k], n.id, li, warn));
3490
+ addNodeProps(n, nodeProps(t[k], n.id, li, warn), li);
3202
3491
  ref.props = [t[k].start, t[k].end];
3203
3492
  k++;
3204
3493
  }
@@ -3260,18 +3549,16 @@ function parse(source, opts = {}) {
3260
3549
  if (themeLine !== void 0 && theme && !theme.includes("$")) {
3261
3550
  if (!names.includes(theme)) warn(themeLine, `Unknown theme "${theme}"${didYouMean(theme, names) || ` (use one of: ${names.join(", ")})`}`);
3262
3551
  }
3263
- for (const n of d.nodes.values()) for (const c of n.classes) if (!d.classes[c]) warn(n.ref?.line ?? 0, `Unknown class ".${c}"`);
3264
3552
  const seen = /* @__PURE__ */ new Set();
3265
- for (const x of [...d.edges, ...d.groups.values()]) for (const c of x.classes ?? []) {
3266
- const line = x.ref?.line ?? 0;
3553
+ for (const [c, line] of classUses) {
3267
3554
  if (d.classes[c] || seen.has(`${line}.${c}`)) continue;
3268
3555
  seen.add(`${line}.${c}`);
3269
3556
  warn(line, `Unknown class ".${c}"`);
3270
3557
  }
3271
3558
  if (hasExport) {
3272
3559
  const panelIds = new Set(d.panels.map((p) => p.id));
3273
- d.exports = [...exported].filter((x) => x.startsWith(".") ? x.slice(1) in d.classes : x.startsWith("$") ? x.slice(1) in vars : d.nodes.has(x) || d.groups.has(x) || panelIds.has(x) || x in defs || x in (d.themes ?? {}));
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`);
3560
+ d.exports = [...exported.keys()].filter((x) => x.startsWith(".") ? x.slice(1) in d.classes : x.startsWith("$") ? x.slice(1) in vars : d.nodes.has(x) || d.groups.has(x) || panelIds.has(x) || x in defs || x in (d.themes ?? {}));
3561
+ for (const [x, line] of exported) if (!d.exports.includes(x) && !PANELS.has(x) && x !== "group" && x !== "def") warn(line, `export: "${x}" is not declared in this file`);
3275
3562
  }
3276
3563
  for (const p of d.panels) {
3277
3564
  if (d.nodes.get(p.id)?.implicit) d.nodes.delete(p.id);
@@ -3283,6 +3570,12 @@ function parse(source, opts = {}) {
3283
3570
  };
3284
3571
  delete d.layout.nodes[p.id];
3285
3572
  }
3573
+ const panelAt = /* @__PURE__ */ new Map();
3574
+ for (const p of d.panels) {
3575
+ const first = panelAt.get(p.id);
3576
+ if (!first) panelAt.set(p.id, p);
3577
+ else if (p.lines) warn(p.lines[0], `panel id "${p.id}" is already used${first.lines ? ` on line ${first.lines[0] + 1}` : " by an import"}: layout, edges and edits can't tell them apart, rename one`);
3578
+ }
3286
3579
  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`);
3287
3580
  lint(d, (kind) => PANELS.get(kind)?.options);
3288
3581
  if (!opts.chain) collecting(d.diagnostics, () => TRANSFORMS.forEach((t) => t(d)));
@@ -3363,7 +3656,7 @@ function narrow(sub, wanted, fail) {
3363
3656
  nodes: /* @__PURE__ */ new Map(),
3364
3657
  edges: [],
3365
3658
  groups: /* @__PURE__ */ new Map(),
3366
- classes: {},
3659
+ classes: table({}),
3367
3660
  layout: {
3368
3661
  nodes: {},
3369
3662
  edges: {}
@@ -3485,9 +3778,9 @@ function mergeDiagram(d, sub, edgeCount) {
3485
3778
  if (sub.layout.ranks?.length) (d.layout.ranks ??= []).push(...sub.layout.ranks);
3486
3779
  for (const [k, v] of Object.entries(sub.vars ?? {})) (d.vars ??= {})[k] ??= v;
3487
3780
  for (const [k, v] of Object.entries(sub.defs ?? {})) (d.defs ??= {})[k] ??= v;
3488
- for (const [k, v] of Object.entries(sub.themes ?? {})) (d.themes ??= {})[k] ??= v;
3781
+ for (const [k, v] of Object.entries(sub.themes ?? {})) (d.themes ??= table({}))[k] ??= v;
3489
3782
  }
3490
- function parseEdgeStatement(t, li, raw, d, touchNode, edgeCount, warn, relabel) {
3783
+ function parseEdgeStatement(t, li, raw, d, touchNode, edgeCount, warn, relabel, useClass) {
3491
3784
  let k = 0;
3492
3785
  let inlineLabel = false;
3493
3786
  /** `a`, `a "Label" .cls [props]`, `a, b, c` — inline declarations bind to their node */
@@ -3525,11 +3818,12 @@ function parseEdgeStatement(t, li, raw, d, touchNode, edgeCount, warn, relabel)
3525
3818
  }
3526
3819
  while (t[k]?.kind === "class") {
3527
3820
  const c = t[k++].value;
3821
+ useClass(c, li);
3528
3822
  if (!n.classes.includes(c)) n.classes.push(c);
3529
3823
  }
3530
3824
  const own = !n.ref || n.implicit;
3531
3825
  if (t[k]?.kind === "props") {
3532
- Object.assign(n.props, nodeProps(t[k], id, li, warn));
3826
+ addNodeProps(n, nodeProps(t[k], id, li, warn), li);
3533
3827
  if (own) n.ref = {
3534
3828
  line: li,
3535
3829
  props: [t[k].start, t[k].end],
@@ -3594,6 +3888,7 @@ function parseEdgeStatement(t, li, raw, d, touchNode, edgeCount, warn, relabel)
3594
3888
  labelRef.range = [t[lblStart].start, t[k - 1].end];
3595
3889
  }
3596
3890
  while (t[k]?.kind === "class") {
3891
+ useClass(t[k].value, li);
3597
3892
  classes.push(t[k].value);
3598
3893
  ref.insertAt = t[k++].end;
3599
3894
  }
@@ -4711,11 +5006,7 @@ const footer = {
4711
5006
  const items = split$1(v);
4712
5007
  const fs = theme.fontSize * .82;
4713
5008
  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
- };
5009
+ const ink = nodeInk(theme);
4719
5010
  const x0 = area.x + pad;
4720
5011
  const x1 = area.x + area.w - pad;
4721
5012
  const out = [`<path d="M${f$2(x0)},${f$2(area.y)}H${f$2(x1)}" stroke="${theme.group.stroke}" stroke-width="1"/>`];
@@ -4841,11 +5132,7 @@ const legend = {
4841
5132
  const list = items(v);
4842
5133
  const { fs, gap, space, sw } = metrics(theme);
4843
5134
  const ws = widths(list, theme, approxMeasure);
4844
- const ink = {
4845
- text: theme.node.text,
4846
- sub: theme.node.sub,
4847
- stroke: theme.node.stroke
4848
- };
5135
+ const ink = nodeInk(theme);
4849
5136
  const out = [];
4850
5137
  rows(ws, Math.min(MAX_W, area.w - pad * 2), space).forEach((row, r) => {
4851
5138
  let x = area.x + pad;
@@ -5067,11 +5354,7 @@ function renderSeq(s, box, ctx) {
5067
5354
  const { fs, boxH, xs } = g;
5068
5355
  const X = (i) => box.x + xs[i];
5069
5356
  const edgeStroke = T.edge.ink;
5070
- const inkBase = {
5071
- text: T.node.text,
5072
- sub: T.node.sub,
5073
- stroke: T.node.stroke
5074
- };
5357
+ const inkBase = nodeInk(T);
5075
5358
  const P = ctx.props;
5076
5359
  const lifeStroke = resolveColor(P.lifeline, T, T.dark ? 600 : 300) ?? T.node.stroke;
5077
5360
  const lifeDash = dashArray(lineStyle(P, "lifeline-style") ?? "dashed", 1);
@@ -5353,11 +5636,7 @@ function renderTimeline(ev, box, ctx) {
5353
5636
  const T = ctx.theme;
5354
5637
  const g = geometry$7(ev, ctx);
5355
5638
  const { fs } = g;
5356
- const ink = {
5357
- text: T.node.text,
5358
- sub: T.node.sub,
5359
- stroke: T.node.stroke
5360
- };
5639
+ const ink = nodeInk(T);
5361
5640
  const axis = T.group.stroke;
5362
5641
  const out = [];
5363
5642
  const dot = (x, y, e) => {
@@ -6094,11 +6373,7 @@ function renderGit(g, box, ctx) {
6094
6373
  T.background,
6095
6374
  T.node.fill
6096
6375
  ].find((c) => c && c !== "none");
6097
- const ink = {
6098
- text: T.node.text,
6099
- sub: T.node.sub,
6100
- stroke: T.node.stroke
6101
- };
6376
+ const ink = nodeInk(T);
6102
6377
  const out = [];
6103
6378
  const pos = G.pos.map((p) => ({
6104
6379
  x: box.x + p.x,
@@ -6256,10 +6531,19 @@ const PALETTE$1 = [
6256
6531
  "lime"
6257
6532
  ];
6258
6533
  const BULLET$1 = /^[-*+]\s+/;
6259
- /** `[pink, shape: plain]`, `[#f80]`, `[color: rgb(0, 120, 200)]`; any other bracket is text */
6534
+ const isNum = (v) => posNum(v) !== void 0;
6535
+ /** the keys a node tail takes, each with the values that make it one */
6536
+ const TAIL = {
6537
+ color: isColor,
6538
+ shape: () => true,
6539
+ text: isColor,
6540
+ "font-size": isNum,
6541
+ "font-weight": isNum
6542
+ };
6543
+ /** `[pink, shape: plain]`, `[#f80]`, `[text: red, font-size: 18]`; any other bracket is text */
6260
6544
  const isTail = (p) => {
6261
6545
  const keys = Object.keys(p);
6262
- return keys.length > 0 && keys.every((k) => k === "color" || k === "shape") && (!p.color || isColor(p.color));
6546
+ return keys.length > 0 && keys.every((k) => TAIL[k]?.(p[k]));
6263
6547
  };
6264
6548
  const splitNode = (line) => splitTrailingProps(line, isTail);
6265
6549
  function parseMindmap(body, _props, warn) {
@@ -6276,6 +6560,9 @@ function parseMindmap(body, _props, warn) {
6276
6560
  text: text.trim(),
6277
6561
  tone: p.color,
6278
6562
  shape: p.shape,
6563
+ ink: p.text,
6564
+ size: posNum(p["font-size"]),
6565
+ weight: posNum(p["font-weight"]),
6279
6566
  line: i,
6280
6567
  children: []
6281
6568
  };
@@ -6320,15 +6607,19 @@ function nodeParts(nodes) {
6320
6607
  for (const n of nodes) counts.set(n.text, (counts.get(n.text) ?? 0) + 1);
6321
6608
  return nodes.map((n, i) => /^[\w-]+$/.test(n.text) && counts.get(n.text) === 1 && !/^n\d+$/.test(n.text) ? n.text : `n${i + 1}`);
6322
6609
  }
6610
+ const LAYOUTS = [
6611
+ "both",
6612
+ "vertical",
6613
+ "right",
6614
+ "left",
6615
+ "down",
6616
+ "up"
6617
+ ];
6323
6618
  const geometry$4 = perPass(function geometry(root, ctx) {
6324
6619
  const { theme, measure, props } = ctx;
6325
- const fs = ctx.fs * .9;
6326
- const mode = [
6327
- "right",
6328
- "left",
6329
- "down"
6330
- ].includes(props.layout) ? props.layout : "both";
6331
- const down = mode === "down";
6620
+ const fs = posNum(props["font-size"]) ?? ctx.fs * .9;
6621
+ const mode = LAYOUTS.includes(props.layout) ? props.layout : "both";
6622
+ const vert = mode === "down" || mode === "up" || mode === "vertical";
6332
6623
  const mono = props.colors === "mono";
6333
6624
  const nodes = walk$1(root);
6334
6625
  const parts = nodeParts(nodes);
@@ -6336,8 +6627,8 @@ const geometry$4 = perPass(function geometry(root, ctx) {
6336
6627
  const placed = /* @__PURE__ */ new Map();
6337
6628
  const size = (n, depth, color, parent) => {
6338
6629
  const shape = SHAPES$1.includes(n.shape ?? "") ? n.shape : depth === 0 ? "pill" : depth === 1 ? "box" : "plain";
6339
- const font = depth === 0 ? fs * 1.2 : depth === 1 ? fs : fs * .92;
6340
- const weight = depth === 0 ? 700 : depth === 1 ? 600 : 400;
6630
+ const font = n.size ?? (depth === 0 ? fs * 1.2 : depth === 1 ? fs : fs * .92);
6631
+ const weight = n.weight ?? (depth === 0 ? 700 : depth === 1 ? 600 : 400);
6341
6632
  const tw = segsW(parseInline(n.text), font, theme.mono, measure, weight);
6342
6633
  const pad = shape === "plain" ? {
6343
6634
  x: fs * .15,
@@ -6372,9 +6663,9 @@ const geometry$4 = perPass(function geometry(root, ctx) {
6372
6663
  const p = placed.get(n);
6373
6664
  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
6665
  }
6375
- const gapOf = (depth) => down ? fs * .8 : depth <= 1 ? fs * .9 : fs * .35;
6666
+ const gapOf = (depth) => vert ? fs * .8 : depth <= 1 ? fs * .9 : fs * .35;
6376
6667
  const extra = (n, k, depth) => k ? Math.max(-gapOf(depth) * .75, ctx.offsets[partOf.get(n)]?.x ?? 0) : 0;
6377
- const across = (p) => down ? p.w : p.h;
6668
+ const across = (p) => vert ? p.w : p.h;
6378
6669
  const ext = /* @__PURE__ */ new Map();
6379
6670
  /** extent of `list` (children of `n`, all already measured) stacked next to each other */
6380
6671
  const extent = (n, list) => {
@@ -6387,10 +6678,9 @@ const geometry$4 = perPass(function geometry(root, ctx) {
6387
6678
  };
6388
6679
  for (let i = nodes.length - 1; i >= 0; i--) ext.set(nodes[i], extent(nodes[i], nodes[i].children));
6389
6680
  const kids = root.children;
6390
- let right = kids;
6391
- let left = [];
6392
- if (mode === "left") [right, left] = [[], kids];
6393
- else if (mode === "both" && kids.length > 1) {
6681
+ let first = kids;
6682
+ let rest = [];
6683
+ if ((mode === "both" || mode === "vertical") && kids.length > 1) {
6394
6684
  const total = kids.reduce((s, c) => s + ext.get(c), 0);
6395
6685
  let acc = 0;
6396
6686
  let cut = 1;
@@ -6400,22 +6690,23 @@ const geometry$4 = perPass(function geometry(root, ctx) {
6400
6690
  const diff = Math.abs(total - 2 * acc);
6401
6691
  if (diff < best) [best, cut] = [diff, k];
6402
6692
  }
6403
- right = kids.slice(0, cut);
6404
- left = kids.slice(cut);
6693
+ first = kids.slice(0, cut);
6694
+ rest = kids.slice(cut);
6405
6695
  }
6406
- const reach = (depth) => down ? fs * 1.9 : depth === 0 ? fs * 2.6 : fs * 1.7;
6696
+ const firstSide = mode === "left" || mode === "up" || mode === "vertical" ? -1 : 1;
6697
+ const reach = (depth) => vert ? fs * 1.9 : depth === 0 ? fs * 2.6 : fs * 1.7;
6407
6698
  const todo = [];
6408
6699
  const place = (p, list, side) => {
6409
6700
  const total = extent(p.node, list);
6410
- let at = (down ? p.x + p.w / 2 : p.y + p.h / 2) - total / 2;
6701
+ let at = (vert ? p.x + p.w / 2 : p.y + p.h / 2) - total / 2;
6411
6702
  list.forEach((c, k) => {
6412
6703
  at += (k ? gapOf(p.depth) : 0) + extra(c, k, p.depth);
6413
6704
  const q = placed.get(c);
6414
6705
  const e = ext.get(c);
6415
- q.side = down ? 0 : side;
6416
- if (down) {
6706
+ q.side = side;
6707
+ if (vert) {
6417
6708
  q.x = at + e / 2 - q.w / 2;
6418
- q.y = p.y + p.h + reach(p.depth);
6709
+ q.y = side > 0 ? p.y + p.h + reach(p.depth) : p.y - reach(p.depth) - q.h;
6419
6710
  } else {
6420
6711
  q.y = at + e / 2 - q.h / 2;
6421
6712
  q.x = side > 0 ? p.x + p.w + reach(p.depth) : p.x - reach(p.depth) - q.w;
@@ -6431,12 +6722,12 @@ const geometry$4 = perPass(function geometry(root, ctx) {
6431
6722
  const r = placed.get(root);
6432
6723
  todo.push([
6433
6724
  r,
6434
- right,
6435
- 1
6725
+ first,
6726
+ firstSide
6436
6727
  ], [
6437
6728
  r,
6438
- left,
6439
- -1
6729
+ rest,
6730
+ -firstSide
6440
6731
  ]);
6441
6732
  while (todo.length) place(...todo.pop());
6442
6733
  const all = nodes.map((n) => placed.get(n));
@@ -6448,7 +6739,7 @@ const geometry$4 = perPass(function geometry(root, ctx) {
6448
6739
  }
6449
6740
  return {
6450
6741
  all,
6451
- down,
6742
+ vert,
6452
6743
  w: maxOf(all.map((p) => p.x + p.w)),
6453
6744
  h: maxOf(all.map((p) => p.y + p.h))
6454
6745
  };
@@ -6462,26 +6753,27 @@ function renderMindmap(root, box, ctx) {
6462
6753
  const shapes = [];
6463
6754
  const X = (v) => box.x + v;
6464
6755
  const Y = (v) => box.y + v;
6465
- /** where a link meets a node: an edge's middle, or a plain node's underline end */
6466
- const anchor = (p, out) => {
6467
- if (g.down) return [p.x + p.w / 2, out ? p.y + p.h : p.y];
6468
- return [(out ? p.side >= 0 : p.side < 0) ? p.x + p.w : p.x, p.shape === "plain" ? p.y + p.h : p.y + p.h / 2];
6756
+ /**
6757
+ * where a link meets a node on its `dir` side (1 right or bottom, -1 left or
6758
+ * top): that edge's middle, or a plain node's underline end
6759
+ */
6760
+ const anchor = (p, dir) => {
6761
+ if (g.vert) return [p.x + p.w / 2, dir > 0 ? p.y + p.h : p.y];
6762
+ return [dir > 0 ? p.x + p.w : p.x, p.shape === "plain" ? p.y + p.h : p.y + p.h / 2];
6469
6763
  };
6470
6764
  for (const p of g.all) {
6471
6765
  const c = ink(T, p.color);
6472
6766
  if (p.parent) {
6473
- const out = anchor(p.parent, true);
6474
- if (!g.down && p.parent.depth === 0) out[0] = p.side < 0 ? p.parent.x : p.parent.x + p.parent.w;
6475
- const [ax, ay] = out;
6476
- const [bx, by] = anchor(p, false);
6767
+ const [ax, ay] = anchor(p.parent, p.side);
6768
+ const [bx, by] = anchor(p, -p.side);
6477
6769
  const width = Math.max(1.4, 3.6 - p.depth * .7);
6478
- const d = g.down ? `M${f$2(X(ax))},${f$2(Y(ay))}C${f$2(X(ax))},${f$2(Y((ay + by) / 2))} ${f$2(X(bx))},${f$2(Y((ay + by) / 2))} ${f$2(X(bx))},${f$2(Y(by))}` : `M${f$2(X(ax))},${f$2(Y(ay))}C${f$2(X((ax + bx) / 2))},${f$2(Y(ay))} ${f$2(X((ax + bx) / 2))},${f$2(Y(by))} ${f$2(X(bx))},${f$2(Y(by))}`;
6770
+ const d = g.vert ? `M${f$2(X(ax))},${f$2(Y(ay))}C${f$2(X(ax))},${f$2(Y((ay + by) / 2))} ${f$2(X(bx))},${f$2(Y((ay + by) / 2))} ${f$2(X(bx))},${f$2(Y(by))}` : `M${f$2(X(ax))},${f$2(Y(ay))}C${f$2(X((ax + bx) / 2))},${f$2(Y(ay))} ${f$2(X((ax + bx) / 2))},${f$2(Y(by))} ${f$2(X(bx))},${f$2(Y(by))}`;
6479
6771
  links.push(`<path d="${d}" fill="none" stroke="${c}" stroke-width="${f$2(width)}" stroke-linecap="round" opacity="0.9"/>`);
6480
6772
  }
6481
6773
  const tc = p.color ? T.tone(p.color) : void 0;
6482
6774
  const fill = p.depth === 0 && !tc ? T.node.fill : tc?.fill ?? T.node.fill;
6483
6775
  const stroke = p.depth === 0 && !tc ? T.accent : tc?.stroke ?? T.node.stroke;
6484
- const text = p.shape === "plain" ? T.node.text : tc?.text ?? T.node.text;
6776
+ const text = resolveColor(p.node.ink, T, T.dark ? 100 : 800) ?? (p.shape === "plain" ? T.node.text : tc?.text ?? T.node.text);
6485
6777
  const x = X(p.x);
6486
6778
  const y = Y(p.y);
6487
6779
  if (p.shape === "plain") shapes.push(`<path d="M${f$2(x)},${f$2(y + p.h)}H${f$2(x + p.w)}" stroke="${c}" stroke-width="${f$2(Math.max(1.4, 3.6 - p.depth * .7))}" stroke-linecap="round"/>`);
@@ -6490,11 +6782,7 @@ function renderMindmap(root, box, ctx) {
6490
6782
  shapes.push(`<rect x="${f$2(x)}" y="${f$2(y)}" width="${f$2(p.w)}" height="${f$2(p.h)}" rx="${f$2(rx)}" fill="${fill}" stroke="${stroke}" stroke-width="${p.depth === 0 ? 2.5 : 1.5}"/>`);
6491
6783
  }
6492
6784
  const cy = p.shape === "plain" ? y + p.h / 2 - ctx.fs * .05 : y + p.h / 2;
6493
- shapes.push(`<text x="${f$2(x + p.w / 2)}" y="${f$2(cy)}" dominant-baseline="central" text-anchor="middle" font-size="${f$2(p.font)}"${p.weight !== 400 ? ` font-weight="${p.weight}"` : ""} xml:space="preserve">${tspans(parseInline(p.node.text), {
6494
- text,
6495
- sub: T.node.sub,
6496
- stroke
6497
- }, T)}</text>`);
6785
+ shapes.push(`<text x="${f$2(x + p.w / 2)}" y="${f$2(cy)}" dominant-baseline="central" text-anchor="middle" font-size="${f$2(p.font)}"${p.weight !== 400 ? ` font-weight="${p.weight}"` : ""} xml:space="preserve">${tspans(parseInline(p.node.text), nodeInk(T, text, stroke), T)}</text>`);
6498
6786
  }
6499
6787
  return links.join("") + shapes.join("");
6500
6788
  }
@@ -6502,16 +6790,11 @@ const mindmap$1 = {
6502
6790
  name: "mindmap",
6503
6791
  panels: [{
6504
6792
  name: "mindmap",
6505
- guide: "indentation is the tree, the first line the root; `-` / `*` bullets are optional. A trailing `[color]` tints a subtree, `[shape: box|pill|plain|circle]` changes one node.",
6793
+ guide: "indentation is the tree, the first line the root; `-` / `*` bullets are optional. A trailing `[color]` tints a subtree, `[shape: box|pill|plain|circle]` changes one node, `[text: red, font-size: 18, font-weight: 700]` styles its text.",
6506
6794
  layoutParts: "a node by its one-word text, else `n<k>`, adds room before it among its siblings",
6507
6795
  syntax: "mindmap id \"Title\" [layout: both] { Root\\n Branch [green]\\n Leaf }",
6508
6796
  options: {
6509
- layout: [
6510
- "both",
6511
- "right",
6512
- "left",
6513
- "down"
6514
- ],
6797
+ layout: LAYOUTS,
6515
6798
  colors: ["branches", "mono"]
6516
6799
  },
6517
6800
  parse: parseMindmap,
@@ -6565,9 +6848,9 @@ const mindmap$1 = {
6565
6848
  }
6566
6849
  out.push({
6567
6850
  part: p.part,
6568
- x: box.x + (g.down ? p.x : p.side < 0 ? p.x + p.w : p.x),
6851
+ x: box.x + (g.vert ? p.x : p.side < 0 ? p.x + p.w : p.x),
6569
6852
  y: box.y + p.y + p.h / 2,
6570
- axis: g.down ? "x" : "y",
6853
+ axis: g.vert ? "x" : "y",
6571
6854
  title: `move ${p.node.text}`
6572
6855
  });
6573
6856
  }
@@ -6581,6 +6864,8 @@ const DAY = 864e5;
6581
6864
  const MAX_TIME = 864e13;
6582
6865
  /** at most this many axis ticks, however wide the chart */
6583
6866
  const MAX_TICKS = 2e3;
6867
+ /** the widest plot, in font sizes: about 12000px at the default size */
6868
+ const MAX_PLOT = 1e3;
6584
6869
  /** weekends are shaded only over spans up to this many days */
6585
6870
  const MAX_WEEKEND_DAYS = 3660;
6586
6871
  const MONTHS = [
@@ -6872,11 +7157,12 @@ const geometry$3 = perPass(function geometry(g, ctx) {
6872
7157
  const min = Math.floor(g.min / DAY) * DAY;
6873
7158
  const max = Math.max(min + DAY, Math.ceil(g.max / DAY) * DAY);
6874
7159
  const days = (max - min) / DAY;
6875
- const dayW = {
7160
+ const zoom = {
6876
7161
  day: fs * 2.4,
6877
7162
  week: fs * .8,
6878
7163
  month: fs * .22
6879
- }[props.scale ?? ""] ?? Math.min(fs * 3, Math.max(fs * .35, fs * 38 / days));
7164
+ }[props.scale ?? ""];
7165
+ const dayW = Math.min(zoom ?? Math.min(fs * 3, Math.max(fs * .35, fs * 38 / days)), fs * MAX_PLOT / days);
6880
7166
  const x = (t) => labelW + (t - min) / DAY * dayW;
6881
7167
  const plotW = days * dayW;
6882
7168
  const rows = [];
@@ -7024,11 +7310,7 @@ function renderGantt(g, box, ctx) {
7024
7310
  const bottom = box.y + G.h;
7025
7311
  const grid = T.group.stroke;
7026
7312
  const out = [];
7027
- const ink = {
7028
- text: T.node.text,
7029
- sub: T.node.sub,
7030
- stroke: T.node.stroke
7031
- };
7313
+ const ink = nodeInk(T);
7032
7314
  const text = (tx, ty, s, weight, fill, end = false) => `<text x="${f$2(tx)}" y="${f$2(ty)}" dominant-baseline="central"${end ? " text-anchor=\"end\"" : ""} font-size="${f$2(fs)}"${weight !== 400 ? ` font-weight="${weight}"` : ""} xml:space="preserve">${tspans(parseInline(s), fill ? {
7033
7315
  ...ink,
7034
7316
  text: fill
@@ -7526,11 +7808,7 @@ function renderQuadrant(q, box, ctx) {
7526
7808
  const px = box.x + G.left;
7527
7809
  const py = box.y;
7528
7810
  const out = [];
7529
- const ink = {
7530
- text: T.node.text,
7531
- sub: T.node.sub,
7532
- stroke: T.node.stroke
7533
- };
7811
+ const ink = nodeInk(T);
7534
7812
  const half = S / 2;
7535
7813
  const at = [
7536
7814
  [half, 0],
@@ -7890,11 +8168,7 @@ function renderKanban(cols, box, ctx) {
7890
8168
  const G = geometry$1(cols, ctx);
7891
8169
  const { fs } = G;
7892
8170
  const out = [];
7893
- const ink = {
7894
- text: T.node.text,
7895
- sub: T.node.sub,
7896
- stroke: T.node.stroke
7897
- };
8171
+ const ink = nodeInk(T);
7898
8172
  const r = Math.min(T.radius, fs * .6);
7899
8173
  const red = inkColor("red", T, T.accent);
7900
8174
  cols.forEach((c, i) => {
@@ -8081,8 +8355,8 @@ const TREE_ICONS = [
8081
8355
  ];
8082
8356
  const PREFIX = /^(?:[ \t │┃┆┊╎]|[├└┣┗╰][─━]*|[|`+\\]-+|\|)*/u;
8083
8357
  const BULLET = /^[-*+]\s+/;
8084
- const TRAILING_PROPS = /\s\[([^\]]*)\]\s*$/;
8085
- const NOTE = /(?::\s+|\s+#\s+|:$)/;
8358
+ const TRAILING_PROPS = /\s\[([^[\]]*)\]\s*$/;
8359
+ const NOTE = /:\s|\s#\s|:$/;
8086
8360
  const TREE_SUMMARY = /^\d+ director(?:y|ies)(?:, \d+ files?)?$/;
8087
8361
  const MATCH = /^match\s+(\S+)\s+\[([^\]]*)\]\s*$/;
8088
8362
  const ELLIPSIS = /^(?:\.{3}|…)$/;
@@ -8210,7 +8484,7 @@ function compileGlob(glob) {
8210
8484
  }
8211
8485
  /** `s` with every closed `[...]` blanked out, so a `: ` inside props is not a note */
8212
8486
  function outsideBrackets(s) {
8213
- return s.replace(/\[[^\]]*\]/g, (m) => "x".repeat(m.length));
8487
+ return s.replace(/\[[^[\]]*\]/g, (m) => "x".repeat(m.length));
8214
8488
  }
8215
8489
  const bare$1 = (text) => text.replace(/\/$/, "");
8216
8490
  function checkProps(props, warn) {
@@ -8218,11 +8492,13 @@ function checkProps(props, warn) {
8218
8492
  if (props.status && !STATUSES.includes(props.status)) warn(`treeview: unknown status "${props.status}" (use one of: ${STATUSES.join(", ")})`);
8219
8493
  if (props.color && !isSafeCss(props.color)) delete props.color;
8220
8494
  }
8495
+ const MAX_DEPTH = 100;
8221
8496
  function parseTreeview(body, _props, warn) {
8222
8497
  const roots = [];
8223
8498
  const stack = [];
8224
8499
  const rules = [];
8225
8500
  const own = /* @__PURE__ */ new Map();
8501
+ let tooDeep = false;
8226
8502
  body.forEach((raw, i) => {
8227
8503
  if (!raw.trim() || /^\s*#/.test(raw)) return;
8228
8504
  const rule = raw.trim().match(MATCH);
@@ -8284,6 +8560,11 @@ function parseTreeview(body, _props, warn) {
8284
8560
  note
8285
8561
  });
8286
8562
  while (stack.length && stack[stack.length - 1].indent >= indent) stack.pop();
8563
+ if (stack.length >= MAX_DEPTH) {
8564
+ if (!tooDeep) warn(i, `treeview: entries nest at most ${MAX_DEPTH} levels deep`);
8565
+ tooDeep = true;
8566
+ stack.length = 99;
8567
+ }
8287
8568
  (stack.length ? stack[stack.length - 1].node.children : roots).push(node);
8288
8569
  stack.push({
8289
8570
  indent,
@@ -8410,7 +8691,7 @@ function glyph(name, fill, ink) {
8410
8691
  default: return page;
8411
8692
  }
8412
8693
  }
8413
- const EMOJI = {
8694
+ const EMOJI = table({
8414
8695
  folder: "📁",
8415
8696
  "folder-open": "📂",
8416
8697
  image: "🖼️",
@@ -8423,7 +8704,7 @@ const EMOJI = {
8423
8704
  font: "🔤",
8424
8705
  media: "🎬",
8425
8706
  terminal: "💻"
8426
- };
8707
+ });
8427
8708
  function entryParts(nodes) {
8428
8709
  const counts = /* @__PURE__ */ new Map();
8429
8710
  for (const n of nodes) counts.set(bare$1(n.text), (counts.get(bare$1(n.text)) ?? 0) + 1);
@@ -8680,11 +8961,7 @@ function renderTreeview(roots, box, ctx) {
8680
8961
  n.status === "ignored" ? " opacity=\"0.55\"" : "",
8681
8962
  r.folder ? " font-weight=\"600\"" : ""
8682
8963
  ].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>`);
8964
+ 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), nodeInk(T, text, text), T)}</text>`);
8688
8965
  if (n.badge) {
8689
8966
  const tc = T.tone(n.tone ?? badgeTone);
8690
8967
  const bx = X(g.badgeX(r));
@@ -8848,8 +9125,9 @@ function parseBody(lines) {
8848
9125
  return rows;
8849
9126
  }
8850
9127
  const rowKind = (r) => registry.rows.find((k) => k.kind === r.kind);
8851
- function measureBody(rows, fs, mono, m, theme) {
8852
- const lh = fs * 1.75;
9128
+ function measureBody(rows, fs, mono, m, theme, opts = {}) {
9129
+ const { weight } = opts;
9130
+ const lh = fs * (opts.lineHeight ?? 1.75);
8853
9131
  const ctx = {
8854
9132
  fs,
8855
9133
  lh,
@@ -8865,7 +9143,7 @@ function measureBody(rows, fs, mono, m, theme) {
8865
9143
  let h = lh;
8866
9144
  if (r.kind === "text") {
8867
9145
  const t = r;
8868
- w = Math.max(w, segsW(t.left, fs, mono, m) + (t.right ? fs * 2 + segsW(t.right, fs, mono, m) : 0));
9146
+ w = Math.max(w, segsW(t.left, fs, mono, m, weight) + (t.right ? fs * 2 + segsW(t.right, fs, mono, m, weight) : 0));
8869
9147
  } else if (r.kind === "rule") h = fs * 1.1;
8870
9148
  else if (r.kind === "gap") h = fs * .6;
8871
9149
  else {
@@ -8885,6 +9163,7 @@ function measureBody(rows, fs, mono, m, theme) {
8885
9163
  fs,
8886
9164
  lh,
8887
9165
  mono,
9166
+ weight,
8888
9167
  ys,
8889
9168
  hs,
8890
9169
  w,
@@ -8894,24 +9173,27 @@ function measureBody(rows, fs, mono, m, theme) {
8894
9173
  function cardBlock(c, theme, m) {
8895
9174
  const labelSize = c.caps ? Math.round(c.fontSize * .8 * 10) / 10 : c.fontSize;
8896
9175
  const letterSpacing = c.caps ? labelSize * .12 : 0;
8897
- const label = c.label ? (c.caps ? c.label.toUpperCase() : c.label).split("\n") : [];
9176
+ const label = c.label ? c.label.split("\n") : [];
8898
9177
  const sub = c.sub ? c.sub.split("\n") : [];
8899
9178
  const subSize = Math.round(c.fontSize * .82 * 10) / 10;
8900
9179
  const labelLh = labelSize * 1.35;
8901
9180
  const subLh = subSize * 1.4;
8902
9181
  const iconSize = Math.round(labelSize * 1.15);
8903
9182
  const weight = c.caps ? 650 : c.weight;
8904
- const spaced = (t, fs, wt) => m(t, fs, wt, theme.mono) + letterSpacing * [...t].length;
9183
+ const spaced = (t, fs, wt) => richW(t, fs, wt, theme.mono, m, c.caps, letterSpacing);
8905
9184
  let headW = 0;
8906
9185
  label.forEach((l, i) => {
8907
9186
  headW = Math.max(headW, spaced(l, labelSize, weight) + (i === 0 && c.icon ? iconSize + 8 : 0));
8908
9187
  });
8909
- for (const l of sub) headW = Math.max(headW, m(l, subSize, 400, theme.mono));
8910
- if (c.meta) headW += subSize * 2.4 + m(c.meta, subSize, 400, theme.mono);
8911
- if (!label.length && c.meta) headW = m(c.meta, subSize, 400, theme.mono);
9188
+ const subW = (t) => richW(t, subSize, 400, theme.mono, m);
9189
+ for (const l of sub) headW = Math.max(headW, subW(l));
9190
+ if (c.meta) headW += subSize * 2.4 + subW(c.meta);
9191
+ if (!label.length && c.meta) headW = subW(c.meta);
8912
9192
  const headH = label.length || c.meta ? Math.max(label.length * labelLh, c.meta ? subLh : 0) + (sub.length ? sub.length * subLh + 2 : 0) : 0;
8913
- const bodyFs = Math.round(c.fontSize * .86 * 10) / 10;
8914
- const body = c.body?.length ? measureBody(parseBody(c.body), bodyFs, c.mono, m, theme) : void 0;
9193
+ const body = c.body?.length ? measureBody(parseBody(c.body), c.bodySize, c.mono, m, theme, {
9194
+ weight: c.bodyWeight,
9195
+ lineHeight: c.lineHeight
9196
+ }) : void 0;
8915
9197
  const divider = !c.frameless && !!body && headH > 0;
8916
9198
  const sep = body && headH > 0 ? divider ? 21 : 8 : 0;
8917
9199
  const pad = c.frameless ? 4 : 14;
@@ -8927,12 +9209,13 @@ function cardBlock(c, theme, m) {
8927
9209
  pad,
8928
9210
  frameless: c.frameless,
8929
9211
  labelWeight: weight,
8930
- metaW: c.meta ? m(c.meta, subSize, 400, theme.mono) : 0,
9212
+ metaW: c.meta ? subW(c.meta) : 0,
8931
9213
  label,
8932
9214
  sub,
8933
9215
  icon: c.icon,
8934
9216
  meta: c.meta,
8935
9217
  caps: c.caps,
9218
+ italic: !!c.italic,
8936
9219
  labelSize,
8937
9220
  labelLh,
8938
9221
  subSize,
@@ -8967,19 +9250,22 @@ function renderCard(cb, x, y, w, h, col, theme) {
8967
9250
  lx += cb.iconSize + 8;
8968
9251
  }
8969
9252
  const ls = cb.letterSpacing ? ` letter-spacing="${f$2(cb.letterSpacing)}"` : "";
8970
- cb.label.forEach((l, i) => out.push(textEl(i ? left : lx, first + i * cb.labelLh, cb.labelSize, cb.caps ? col.sub : col.text, esc$1(l), ` font-weight="${cb.labelWeight}"${ls}`)));
9253
+ cb.label.forEach((l, i) => out.push(textEl(i ? left : lx, first + i * cb.labelLh, cb.labelSize, cb.caps ? col.sub : col.text, richText(l, cb.caps ? subInk(col) : col, theme, cb.caps), ` font-weight="${cb.labelWeight}"${ls}${cb.italic ? " font-style=\"italic\"" : ""} xml:space="preserve"`)));
8971
9254
  let sy = top + cb.label.length * cb.labelLh + 2;
8972
9255
  for (const l of cb.sub) {
8973
- out.push(textEl(left, sy + cb.subLh / 2, cb.subSize, col.sub, esc$1(l)));
9256
+ out.push(textEl(left, sy + cb.subLh / 2, cb.subSize, col.sub, richText(l, subInk(col), theme), " xml:space=\"preserve\""));
8974
9257
  sy += cb.subLh;
8975
9258
  }
8976
- if (cb.meta) out.push(textEl(right, first, cb.subSize, col.sub, esc$1(cb.meta), " text-anchor=\"end\""));
9259
+ if (cb.meta) out.push(textEl(right, first, cb.subSize, col.sub, richText(cb.meta, subInk(col), theme), " text-anchor=\"end\" xml:space=\"preserve\""));
8977
9260
  }
8978
9261
  if (cb.divider) {
8979
9262
  const dy = top + cb.headH + cb.sep / 2;
8980
9263
  out.push(`<path d="M${f$2(x)},${f$2(dy)}H${f$2(x + w)}" stroke="${col.stroke}" stroke-width="1"/>`);
8981
9264
  }
8982
- if (cb.body) out.push(renderBody(cb.body, left, right, top + cb.headH + cb.sep, col, theme));
9265
+ if (cb.body) out.push(renderBody(cb.body, left, right, top + cb.headH + cb.sep, {
9266
+ ...col,
9267
+ text: col.body
9268
+ }, theme));
8983
9269
  return out.join("");
8984
9270
  }
8985
9271
  function renderBody(b, left, right, top, col, theme) {
@@ -8999,8 +9285,8 @@ function renderBody(b, left, right, top, col, theme) {
8999
9285
  if (r.kind === "text") {
9000
9286
  const t = r;
9001
9287
  const cy = ry + rh / 2;
9002
- out.push(renderSegs(t.left, left, cy, fs, col, theme));
9003
- if (t.right) out.push(renderSegs(t.right, right - sumW(t.right), cy, fs, col, theme));
9288
+ out.push(renderSegs(t.left, left, cy, fs, col, theme, false, b.weight));
9289
+ if (t.right) out.push(renderSegs(t.right, right - sumW(t.right), cy, fs, col, theme, false, b.weight));
9004
9290
  } else if (r.kind === "rule") out.push(`<path d="M${f$2(left)},${f$2(ry + rh / 2)}H${f$2(right)}" stroke="${col.stroke}" stroke-width="1"/>`);
9005
9291
  else if (r.kind !== "gap") out.push(rowKind(r)?.render(r, {
9006
9292
  x: left,
@@ -9020,7 +9306,7 @@ function wrapText(text, max, width) {
9020
9306
  continue;
9021
9307
  }
9022
9308
  let line = "";
9023
- for (const word of para.split(/ +/)) {
9309
+ for (const word of splitWords(para)) {
9024
9310
  const next = line ? `${line} ${word}` : word;
9025
9311
  if (line && width(next) > max) {
9026
9312
  out.push(line);
@@ -9033,17 +9319,22 @@ function wrapText(text, max, width) {
9033
9319
  }
9034
9320
  function textBlock(label, sub, icon, fontSize, weight, theme, measure, caps = false, maxWidth = 0) {
9035
9321
  const letterSpacing = caps ? fontSize * .1 : 0;
9036
- const subSize0 = Math.round(fontSize * .82 * 10) / 10;
9037
- const lines = wrapText(caps ? label.toUpperCase() : label, maxWidth, (l) => measure(l, fontSize, weight, theme.mono) + letterSpacing * [...l].length);
9038
- const subLines = sub ? wrapText(sub, maxWidth, (l) => measure(l, subSize0, 400, theme.mono)) : [];
9039
9322
  const subSize = Math.round(fontSize * .82 * 10) / 10;
9040
- const lineHeight = fontSize * 1.3;
9041
- const subLineHeight = subSize * 1.35;
9323
+ const memo = (w) => {
9324
+ const seen = /* @__PURE__ */ new Map();
9325
+ return (l) => seen.get(l) ?? (seen.set(l, w(l)), seen.get(l));
9326
+ };
9327
+ const labelW = memo((l) => richW(l, fontSize, weight, theme.mono, measure, caps, letterSpacing));
9328
+ const subW = memo((l) => richW(l, subSize, 400, theme.mono, measure));
9329
+ const lines = wrapText(label, maxWidth, labelW);
9330
+ const subLines = sub ? wrapText(sub, maxWidth, subW) : [];
9331
+ const lineHeight$1 = lineHeight(lines, fontSize);
9332
+ const subLineHeight = lineHeight(subLines, subSize, 1.35);
9042
9333
  const iconSize = Math.round(fontSize * 1.6);
9043
9334
  let w = 0;
9044
- for (const l of lines) w = Math.max(w, measure(l, fontSize, weight, theme.mono) + letterSpacing * [...l].length);
9045
- for (const l of subLines) w = Math.max(w, measure(l, subSize, 400, theme.mono));
9046
- let h = lines.length * lineHeight + subLines.length * subLineHeight + (subLines.length ? 3 : 0);
9335
+ for (const l of lines) w = Math.max(w, labelW(l));
9336
+ for (const l of subLines) w = Math.max(w, subW(l));
9337
+ let h = lines.length * lineHeight$1 + subLines.length * subLineHeight + (subLines.length ? 3 : 0);
9047
9338
  if (icon) {
9048
9339
  h += iconSize + 4;
9049
9340
  w = Math.max(w, iconSize);
@@ -9052,11 +9343,12 @@ function textBlock(label, sub, icon, fontSize, weight, theme, measure, caps = fa
9052
9343
  lines,
9053
9344
  sub: subLines,
9054
9345
  icon,
9055
- lineHeight,
9346
+ lineHeight: lineHeight$1,
9056
9347
  subSize,
9057
9348
  subLineHeight,
9058
9349
  iconSize,
9059
9350
  letterSpacing,
9351
+ caps,
9060
9352
  w,
9061
9353
  h
9062
9354
  };
@@ -9079,10 +9371,10 @@ function groupPath(d, groupId) {
9079
9371
  let g = groupId;
9080
9372
  while (g && d.groups.has(g) && !seen.has(g)) {
9081
9373
  seen.add(g);
9082
- path.unshift(g);
9374
+ path.push(g);
9083
9375
  g = d.groups.get(g).parent;
9084
9376
  }
9085
- return path;
9377
+ return path.reverse();
9086
9378
  }
9087
9379
  /** mean relative position of each group across all layers: its place among its siblings */
9088
9380
  function groupRanks(layers) {
@@ -9253,9 +9545,9 @@ function place(d, opts) {
9253
9545
  "up"
9254
9546
  ].includes(d.settings.direction) ? d.settings.direction : "right";
9255
9547
  const horiz = isHorizontal(dir);
9256
- const gap = num$1(d.settings.gap, 36);
9548
+ const gap = size(d.settings.gap, 36);
9257
9549
  const hasGroups = [...d.nodes.values()].some((n) => n.group);
9258
- const baseRankGap = num$1(d.settings["rank-gap"], hasGroups ? 96 : 72);
9550
+ const baseRankGap = size(d.settings["rank-gap"], hasGroups ? 96 : 72);
9259
9551
  const defaultCurve = [
9260
9552
  "smooth",
9261
9553
  "orthogonal",
@@ -9269,7 +9561,7 @@ function place(d, opts) {
9269
9561
  const style = resolveNodeStyle(d, n, p, theme);
9270
9562
  const shape = normalizeShape(p.shape ?? defaultShape);
9271
9563
  const caps = p.caps !== void 0 && p.caps !== "false";
9272
- const wrap = num$1(p["max-width"], num$1(d.settings.wrap, 0));
9564
+ const wrap = size(p["max-width"], size(d.settings.wrap, 0));
9273
9565
  const tb = textBlock(n.label, p.sub, p.icon, style.fontSize, style.fontWeight, theme, measure, caps, wrap);
9274
9566
  let sz;
9275
9567
  if (n.body?.length || p.meta || p.frame) {
@@ -9279,12 +9571,16 @@ function place(d, opts) {
9279
9571
  icon: p.icon,
9280
9572
  meta: p.meta,
9281
9573
  caps,
9574
+ italic: style.italic,
9282
9575
  body: n.body,
9283
9576
  mono: p.mono !== "false",
9284
9577
  frameless: shape === "text",
9285
9578
  fontSize: style.fontSize,
9286
9579
  weight: style.fontWeight,
9287
- frame: p.frame
9580
+ frame: p.frame,
9581
+ bodySize: style.bodySize,
9582
+ bodyWeight: style.bodyWeight,
9583
+ lineHeight: style.lineHeight
9288
9584
  }, theme, measure);
9289
9585
  sz = {
9290
9586
  w: tb.card.w,
@@ -9293,8 +9589,8 @@ function place(d, opts) {
9293
9589
  } else sz = sizeForShape(shape, tb.w, tb.h);
9294
9590
  blocks.set(n.id, tb);
9295
9591
  const o = d.layout.nodes[n.id];
9296
- const w = o?.w ?? even(num$1(p.width, sz.w));
9297
- const h = o?.h ?? even(num$1(p.height, sz.h));
9592
+ const w = o?.w ?? even(size(p.width, sz.w));
9593
+ const h = o?.h ?? even(size(p.height, sz.h));
9298
9594
  nodes.set(n.id, {
9299
9595
  id: n.id,
9300
9596
  decl: n,
@@ -9351,7 +9647,8 @@ function place(d, opts) {
9351
9647
  oExt: horiz ? n.h : n.w,
9352
9648
  rExt: horiz ? n.w : n.h,
9353
9649
  rank: rank.get(id),
9354
- pos: 0
9650
+ pos: 0,
9651
+ u: 0
9355
9652
  });
9356
9653
  }
9357
9654
  const vedges = [];
@@ -9391,7 +9688,8 @@ function place(d, opts) {
9391
9688
  oExt: 6,
9392
9689
  rExt: 0,
9393
9690
  rank: r,
9394
- pos: 0
9691
+ pos: 0,
9692
+ u: 0
9395
9693
  });
9396
9694
  vedges.push([
9397
9695
  prev,
@@ -9445,25 +9743,37 @@ function place(d, opts) {
9445
9743
  const off = (widest - span(l)) / 2;
9446
9744
  for (const v of l) v.pos += off;
9447
9745
  }
9746
+ const toNb = (es) => es.map(([id, w]) => [vnodes.get(id), w]);
9747
+ const predNb = [];
9748
+ const succNb = [];
9749
+ const bothNb = [];
9750
+ for (const v of vnodes.values()) {
9751
+ predNb[v.u] = toNb(preds.get(v.id));
9752
+ succNb[v.u] = toNb(succs.get(v.id));
9753
+ bothNb[v.u] = [...predNb[v.u], ...succNb[v.u]];
9754
+ }
9755
+ const layerSeps = layers.map((layer) => layer.slice(1).map((v, i) => sepOf(layer[i], v)));
9756
+ const reversed = layers.map((_, i) => layers.length - 1 - i);
9757
+ const forward = layers.map((_, i) => i);
9448
9758
  for (let iter = 0; iter < 16; iter++) {
9449
9759
  const mode = iter < 12 ? iter % 2 === 0 ? "down" : "up" : "both";
9450
- const order = mode === "up" ? [...layers].reverse() : layers;
9451
- for (const layer of order) {
9760
+ const nbs = mode === "down" ? predNb : mode === "up" ? succNb : bothNb;
9761
+ for (const r of mode === "up" ? reversed : forward) {
9762
+ const layer = layers[r];
9452
9763
  if (!layer.length) continue;
9453
9764
  const desired = [];
9454
9765
  const weights = [];
9455
9766
  for (const v of layer) {
9456
- const nb = mode === "down" ? preds.get(v.id) : mode === "up" ? succs.get(v.id) : [...preds.get(v.id), ...succs.get(v.id)];
9457
9767
  let sw = 0;
9458
9768
  let s = 0;
9459
- for (const [id, w] of nb) {
9460
- s += vnodes.get(id).pos * w;
9769
+ for (const [u, w] of nbs[v.u]) {
9770
+ s += u.pos * w;
9461
9771
  sw += w;
9462
9772
  }
9463
9773
  desired.push(sw ? s / sw : v.pos);
9464
9774
  weights.push(sw ? sw : .25);
9465
9775
  }
9466
- const solved = isotonic(desired, weights, layer.slice(1).map((v, i) => sepOf(layer[i], v)));
9776
+ const solved = isotonic(desired, weights, layerSeps[r]);
9467
9777
  layer.forEach((v, i) => v.pos = solved[i]);
9468
9778
  }
9469
9779
  }
@@ -9474,9 +9784,9 @@ function place(d, opts) {
9474
9784
  if (!e.label || !rank.has(e.from) || !rank.has(e.to)) return;
9475
9785
  const r = Math.min(rank.get(e.from), rank.get(e.to));
9476
9786
  if (Math.abs(rank.get(e.from) - rank.get(e.to)) !== 1) return;
9477
- const fs = theme.fontSize * .86;
9787
+ const font = edgeFont(effectiveProps(d, e), theme);
9478
9788
  const lines = e.label.split("\n");
9479
- const ext = horiz ? Math.max(...lines.map((l) => measure(l, fs, 500, theme.mono))) + 16 : lines.length * fs * 1.3 + 10;
9789
+ const ext = horiz ? Math.max(...lines.map((l) => richW(l, font.size, font.weight, theme.mono, measure))) + 16 : lines.length * lineHeight(lines, font.size) + 10;
9480
9790
  labelRoom[r] = Math.max(labelRoom[r], ext);
9481
9791
  });
9482
9792
  const rankPos = [];
@@ -9536,7 +9846,7 @@ function place(d, opts) {
9536
9846
  p.y = Math.round(p.y + oy);
9537
9847
  }
9538
9848
  }
9539
- const maxW = num$1(d.settings["max-width"], 0);
9849
+ const maxW = size(d.settings["max-width"], 0);
9540
9850
  const channels = /* @__PURE__ */ new Set();
9541
9851
  const pins = [...nodes.keys()].some((id) => d.layout.nodes[id]?.x !== void 0);
9542
9852
  if (maxW > 0 && horiz && nodes.size && !pins) {
@@ -9619,7 +9929,7 @@ function place(d, opts) {
9619
9929
  * the other side.
9620
9930
  */
9621
9931
  function wrapRows(d, nodes, rank, dummyPts, dummyRank, channels, o) {
9622
- const pad = num$1(d.settings.padding, 24);
9932
+ const pad = size(d.settings.padding, 24);
9623
9933
  const maxRank = Math.max(...[...nodes.keys()].map((id) => rank.get(id)));
9624
9934
  const outer = /* @__PURE__ */ new Map();
9625
9935
  for (const n of nodes.values()) {
@@ -9769,7 +10079,7 @@ function checkPlacements(d, placed, rank) {
9769
10079
  const n = d.nodes.get(id);
9770
10080
  const key = placementOf(effectiveProps(d, n))?.[0];
9771
10081
  if (!n.ref || !key) continue;
9772
- const line = (n.ref.propLines?.[key] ?? n.ref.line) + 1;
10082
+ const line = propLine(n, key) + 1;
9773
10083
  const message = `${id} [${key}: ${anchor}] cannot be met: the edges between them run the other way, and the edges win`;
9774
10084
  if (!d.diagnostics.some((x) => x.line === line && x.message === message)) d.diagnostics.push({
9775
10085
  line,
@@ -9921,21 +10231,60 @@ function assignRanks(ids, edges) {
9921
10231
  return rank;
9922
10232
  }
9923
10233
  function orderLayers(layers, preds, succs, attach = /* @__PURE__ */ new Map()) {
9924
- const index = /* @__PURE__ */ new Map();
9925
- const reindex = () => layers.forEach((l) => l.forEach((v, i) => index.set(v.id, i)));
10234
+ const uid = /* @__PURE__ */ new Map();
10235
+ for (const l of layers) for (const v of l) {
10236
+ v.u = uid.size;
10237
+ uid.set(v.id, v.u);
10238
+ }
10239
+ const n = uid.size;
10240
+ const predU = new Array(n);
10241
+ const succU = new Array(n);
10242
+ for (const [id, u] of uid) {
10243
+ predU[u] = preds.get(id).map(([w]) => uid.get(w));
10244
+ succU[u] = succs.get(id).map(([w]) => uid.get(w));
10245
+ }
10246
+ const index = new Int32Array(n);
10247
+ const reindex = (l) => l.forEach((v, i) => index[v.u] = i);
10248
+ const bary = new Float64Array(n);
10249
+ const layerOf = new Int32Array(n);
10250
+ layers.forEach((l, r) => l.forEach((v) => layerOf[v.u] = r));
10251
+ const pins = [];
10252
+ for (const [loose, [anchor, side]] of attach) {
10253
+ const lu = uid.get(loose);
10254
+ const au = uid.get(anchor);
10255
+ if (lu !== void 0 && au !== void 0) pins.push([
10256
+ lu,
10257
+ au,
10258
+ side
10259
+ ]);
10260
+ }
9926
10261
  /** attached nodes ride right after (or before) their partner; repeat so chains follow */
9927
- const pin = (bary) => {
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);
9929
- return bary;
9930
- };
9931
- for (const l of layers) sortLayer(l, pin(new Map(l.map((v, i) => [v.id, i]))));
9932
- reindex();
10262
+ const pin = (r) => {
10263
+ for (let pass = 0; pass < Math.min(attach.size, 8); pass++) for (const [lu, au, side] of pins) if (layerOf[lu] === r && layerOf[au] === r) bary[lu] = bary[au] + side * .001;
10264
+ };
10265
+ layers.forEach((l, r) => {
10266
+ l.forEach((v, i) => bary[v.u] = i);
10267
+ pin(r);
10268
+ sortLayer(l, bary);
10269
+ reindex(l);
10270
+ });
9933
10271
  const crossings = () => {
9934
10272
  let c = 0;
9935
10273
  for (let r = 0; r < layers.length - 1; r++) {
9936
- const es = [];
9937
- for (const v of layers[r]) for (const [w] of succs.get(v.id)) es.push([index.get(v.id), index.get(w)]);
9938
- for (let i = 0; i < es.length; i++) for (let j = i + 1; j < es.length; j++) if ((es[i][0] - es[j][0]) * (es[i][1] - es[j][1]) < 0) c++;
10274
+ const size = layers[r + 1].length;
10275
+ const tree = new Int32Array(size + 1);
10276
+ let seen = 0;
10277
+ for (const v of layers[r]) {
10278
+ const ts = succU[v.u].map((w) => index[w]);
10279
+ if (ts.length > 1) ts.sort((a, b) => a - b);
10280
+ for (const t of ts) {
10281
+ let le = 0;
10282
+ for (let i = t + 1; i > 0; i -= i & -i) le += tree[i];
10283
+ c += seen - le;
10284
+ }
10285
+ for (const t of ts) for (let i = t + 1; i <= size; i += i & -i) tree[i]++;
10286
+ seen += ts.length;
10287
+ }
9939
10288
  }
9940
10289
  return c;
9941
10290
  };
@@ -9943,16 +10292,19 @@ function orderLayers(layers, preds, succs, attach = /* @__PURE__ */ new Map()) {
9943
10292
  let bestC = crossings();
9944
10293
  for (let iter = 0; iter < 24 && bestC > 0; iter++) {
9945
10294
  const down = iter % 2 === 0;
9946
- const range = down ? layers.map((_, i) => i).slice(1) : layers.map((_, i) => i).reverse().slice(1);
9947
- for (const r of range) {
10295
+ const nbs = down ? predU : succU;
10296
+ for (let k = 1; k < layers.length; k++) {
10297
+ const r = down ? k : layers.length - 1 - k;
9948
10298
  const layer = layers[r];
9949
- const bary = /* @__PURE__ */ new Map();
9950
10299
  for (const v of layer) {
9951
- const ps = (down ? preds.get(v.id) : succs.get(v.id)).map(([id]) => index.get(id));
9952
- bary.set(v.id, ps.length ? ps.reduce((a, b) => a + b, 0) / ps.length : index.get(v.id));
10300
+ const nb = nbs[v.u];
10301
+ let s = 0;
10302
+ for (const w of nb) s += index[w];
10303
+ bary[v.u] = nb.length ? s / nb.length : index[v.u];
9953
10304
  }
9954
- sortLayer(layer, pin(bary));
9955
- layer.forEach((v, i) => index.set(v.id, i));
10305
+ pin(r);
10306
+ sortLayer(layer, bary);
10307
+ reindex(layer);
9956
10308
  }
9957
10309
  const c = crossings();
9958
10310
  if (c < bestC) {
@@ -9992,35 +10344,45 @@ function alignGroupOrder(layers) {
9992
10344
  };
9993
10345
  for (let r = 0; r < layers.length; r++) layers[r] = reorder(layers[r], 0);
9994
10346
  }
9995
- /** Sort a layer by barycentre while keeping members of each group contiguous. */
10347
+ /** Sort a layer by barycentre (indexed by `VNode.u`) while keeping members of each group contiguous. */
9996
10348
  function sortLayer(layer, bary) {
10349
+ if (layer.every((v) => !v.path.length)) {
10350
+ const keyed = layer.map((v, orig) => ({
10351
+ v,
10352
+ orig,
10353
+ b: bary[v.u]
10354
+ }));
10355
+ keyed.sort((ka, kb) => ka.b - kb.b || ka.orig - kb.orig);
10356
+ keyed.forEach((k, i) => layer[i] = k.v);
10357
+ return;
10358
+ }
9997
10359
  const groupAvg = /* @__PURE__ */ new Map();
9998
10360
  const sums = /* @__PURE__ */ new Map();
9999
10361
  for (const v of layer) for (const g of v.path) {
10000
10362
  const s = sums.get(g) ?? [0, 0];
10001
- s[0] += bary.get(v.id);
10363
+ s[0] += bary[v.u];
10002
10364
  s[1]++;
10003
10365
  sums.set(g, s);
10004
10366
  }
10005
10367
  for (const [g, [s, c]] of sums) groupAvg.set(g, s / c);
10006
- const key = (v) => ({
10368
+ const keyed = layer.map((v, orig) => ({
10369
+ v,
10370
+ orig,
10007
10371
  ent: [...v.path, v.id],
10008
- val: [...v.path.map((g) => groupAvg.get(g)), bary.get(v.id)]
10009
- });
10010
- const keys = new Map(layer.map((v) => [v.id, key(v)]));
10011
- const orig = new Map(layer.map((v, i) => [v.id, i]));
10012
- layer.sort((a, b) => {
10013
- const ka = keys.get(a.id);
10014
- const kb = keys.get(b.id);
10015
- for (let i = 0; i < Math.max(ka.ent.length, kb.ent.length); i++) {
10372
+ val: [...v.path.map((g) => groupAvg.get(g)), bary[v.u]]
10373
+ }));
10374
+ keyed.sort((ka, kb) => {
10375
+ const n = Math.max(ka.ent.length, kb.ent.length);
10376
+ for (let i = 0; i < n; i++) {
10016
10377
  if (ka.ent[i] === kb.ent[i]) continue;
10017
10378
  const va = ka.val[i] ?? 0;
10018
10379
  const vb = kb.val[i] ?? 0;
10019
10380
  if (va !== vb) return va - vb;
10020
- return orig.get(a.id) - orig.get(b.id);
10381
+ return ka.orig - kb.orig;
10021
10382
  }
10022
- return orig.get(a.id) - orig.get(b.id);
10383
+ return ka.orig - kb.orig;
10023
10384
  });
10385
+ keyed.forEach((k, i) => layer[i] = k.v);
10024
10386
  }
10025
10387
  /**
10026
10388
  * Weighted least squares placement with minimum separations:
@@ -10094,17 +10456,26 @@ function applyOverrides(d, nodes, horiz, gap) {
10094
10456
  */
10095
10457
  function groupHeadText(g, theme, measure) {
10096
10458
  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;
10459
+ const { size, weight, caps, spacing } = groupFont(g, theme);
10460
+ const width = (l) => richW(l, size, weight, theme.mono, measure, caps, spacing);
10461
+ const meta = p.meta ? richW(p.meta, theme.fontSize * .82, 400, theme.mono, measure) : 0;
10103
10462
  return {
10104
- text,
10463
+ text: g.label,
10105
10464
  width,
10106
- meta: p.meta ? measure(p.meta, fs, 400, theme.mono) : 0,
10107
- lineHeight: Math.round(size * 1.3 * 10) / 10
10465
+ meta,
10466
+ lineHeight: Math.round(lineHeight(g.label.split("\n"), size) * 10) / 10
10467
+ };
10468
+ }
10469
+ /** a group label's font: `font-size`, `font-weight`, `italic` and `caps` */
10470
+ function groupFont(g, theme) {
10471
+ const caps = bool(g.props.caps, false);
10472
+ const font = textFont(g.props, theme.fontSize * .82, 600);
10473
+ const size = caps ? font.size * .92 : font.size;
10474
+ return {
10475
+ ...font,
10476
+ size,
10477
+ caps,
10478
+ spacing: size * (caps ? .1 : .02)
10108
10479
  };
10109
10480
  }
10110
10481
  const META_GAP = 12;
@@ -10124,20 +10495,19 @@ function fitGroupHead(d, gid, box, nodes, laid, theme, measure) {
10124
10495
  const inside = (gr) => groupPath(d, gr).includes(gid);
10125
10496
  const others = [];
10126
10497
  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);
10498
+ const padded = (b, path, self) => {
10130
10499
  let c = 0;
10131
10500
  while (c < path.length && path[c] === own[c]) c++;
10132
- const pad = (path.length - c) * 18;
10501
+ const pad = (path.length - self - c + own.length - 1 - c) * 18;
10133
10502
  others.push({
10134
- x: n.x - pad,
10135
- y: n.y - pad,
10136
- w: n.w + 2 * pad,
10137
- h: n.h + 2 * pad
10503
+ x: b.x - pad,
10504
+ y: b.y - pad,
10505
+ w: b.w + 2 * pad,
10506
+ h: b.h + 2 * pad
10138
10507
  });
10139
- }
10140
- for (const [cid, b] of laid) if (!inside(cid) && !groupPath(d, gid).includes(cid)) others.push(b);
10508
+ };
10509
+ for (const n of nodes.values()) if (!inside(n.decl.group)) padded(n, groupPath(d, n.decl.group), 0);
10510
+ for (const [cid, b] of laid) if (!inside(cid) && !own.includes(cid)) padded(b, groupPath(d, cid), 1);
10141
10511
  const m = 9;
10142
10512
  let lo = -1e400;
10143
10513
  let hi = 1e400;
@@ -10160,7 +10530,8 @@ function fitGroupHead(d, gid, box, nodes, laid, theme, measure) {
10160
10530
  box.h += grow;
10161
10531
  return {
10162
10532
  lines: wrapped,
10163
- header: 26 + grow
10533
+ header: 26 + grow,
10534
+ lineHeight: head.lineHeight
10164
10535
  };
10165
10536
  }
10166
10537
  function layoutGroups(d, nodes, theme, measure) {
@@ -10191,10 +10562,7 @@ function layoutGroups(d, nodes, theme, measure) {
10191
10562
  decl: g,
10192
10563
  depth: depth(gid),
10193
10564
  ...box,
10194
- ...head ? {
10195
- lines: head.lines,
10196
- header: head.header
10197
- } : {},
10565
+ ...head ?? {},
10198
10566
  style: resolveGroupStyle({
10199
10567
  ...g,
10200
10568
  props: effectiveProps(d, g)
@@ -10242,7 +10610,7 @@ function computeBounds(box, d, theme, measure) {
10242
10610
  empty,
10243
10611
  empty
10244
10612
  ];
10245
- const pad = num$1(d.settings.padding, 24);
10613
+ const pad = size(d.settings.padding, 24);
10246
10614
  x0 -= pad;
10247
10615
  y0 -= pad;
10248
10616
  x1 += pad;
@@ -10302,14 +10670,14 @@ function computeBounds(box, d, theme, measure) {
10302
10670
  decor
10303
10671
  };
10304
10672
  }
10305
- /** panel title height (0 without a title) */
10306
- const panelHead = (label, theme) => label ? theme.fontSize * 2.3 : 0;
10673
+ /** height of a panel's title row, for the panel's base font size */
10674
+ const panelHead = (label, fs) => label ? fs * 2.3 : 0;
10307
10675
  /** what a panel plugin gets in `measure`, `render` and `handles` */
10308
10676
  function panelCtx(decl, offsets, theme, measure) {
10309
10677
  return {
10310
10678
  theme,
10311
10679
  measure,
10312
- fs: theme.fontSize,
10680
+ fs: posNum(decl.props["font-size"]) ?? theme.fontSize,
10313
10681
  props: decl.props,
10314
10682
  offsets
10315
10683
  };
@@ -10327,8 +10695,8 @@ function placePanels(d, theme, measure, graph) {
10327
10695
  const offsets = d.layout.panels?.[decl.id]?.parts ?? {};
10328
10696
  const ctx = panelCtx(decl, offsets, panelTheme(theme, decl.props, d.themes), measure);
10329
10697
  const c = kind.measure(decl.data, ctx);
10330
- const head = panelHead(decl.label, theme);
10331
- const tw = decl.label ? measure(decl.label, theme.fontSize * 1.05, 650, theme.mono) : 0;
10698
+ const head = panelHead(decl.label, ctx.fs);
10699
+ const tw = decl.label ? richW(decl.label, ctx.fs * 1.05, textFont(decl.props, ctx.fs, 650).weight, theme.mono, measure) : 0;
10332
10700
  const w = even(Math.max(c.w, tw) + 32);
10333
10701
  const h = even(c.h + head + 32);
10334
10702
  const inner = {
@@ -10355,7 +10723,7 @@ function placePanels(d, theme, measure, graph) {
10355
10723
  });
10356
10724
  }
10357
10725
  if (!out.length) return out;
10358
- const gap = num$1(d.settings["panel-gap"], 48);
10726
+ const gap = size(d.settings["panel-gap"], 48);
10359
10727
  const mode = d.settings.panels ?? "row";
10360
10728
  const cells = [...graph ? [graph] : [], ...out.map((p) => p.box)];
10361
10729
  const ox = graph?.x ?? 0;
@@ -10399,7 +10767,7 @@ function placePanels(d, theme, measure, graph) {
10399
10767
  p.box.y = at.y;
10400
10768
  }
10401
10769
  p.inner.x = p.box.x + 16;
10402
- p.inner.y = p.box.y + 16 + panelHead(p.decl.label, theme);
10770
+ p.inner.y = p.box.y + 16 + panelHead(p.decl.label, p.ctx.fs);
10403
10771
  }
10404
10772
  return out;
10405
10773
  }
@@ -10455,11 +10823,7 @@ function draw(d, L, opts) {
10455
10823
  if (head) {
10456
10824
  const pad = parseFloat(d.settings.padding) || 24;
10457
10825
  let y = B.y + pad;
10458
- const ink = {
10459
- text: T.title,
10460
- sub: T.node.sub,
10461
- stroke: T.node.stroke
10462
- };
10826
+ const ink = nodeInk(T, T.title);
10463
10827
  if (title) {
10464
10828
  out.push(`<text x="${f(B.x + pad)}" y="${f(y + head.titleSize * .8)}" font-size="${f(head.titleSize)}" font-weight="650" xml:space="preserve">${tspans(parseInline(title), ink, T)}</text>`);
10465
10829
  y += head.titleSize * 1.3;
@@ -10469,7 +10833,7 @@ function draw(d, L, opts) {
10469
10833
  for (const dc of L.decor ?? []) {
10470
10834
  const dec = registry.decorations.find((x) => x.name === dc.name);
10471
10835
  if (dec) out.push(dec.render(dc.value, dc.area, T, {
10472
- pad: num$1(d.settings.padding, 24),
10836
+ pad: size(d.settings.padding, 24),
10473
10837
  bounds: B,
10474
10838
  d
10475
10839
  }));
@@ -10496,14 +10860,11 @@ function renderPanel(p, L, measure, shadow, id) {
10496
10860
  const T = p.ctx.theme;
10497
10861
  const s = resolvePanelStyle(p.decl.props, T, base);
10498
10862
  const { box } = p;
10499
- const head = panelHead(p.decl.label, T);
10863
+ const head = panelHead(p.decl.label, p.ctx.fs);
10864
+ const tf = textFont(p.decl.props, p.ctx.fs, 650);
10500
10865
  const out = [`<g${attr("data-panel", p.decl.id)}${attr("class", `panel panel-${p.decl.kind}`)}>`];
10501
10866
  if (s.framed) out.push(`<rect x="${f(box.x)}" y="${f(box.y)}" width="${f(box.w)}" height="${f(box.h)}" rx="${f(s.radius)}" fill="${s.fill}" stroke="${s.stroke}" stroke-width="${f(s.width)}"${attr("stroke-dasharray", s.dash)}${s.shadow && shadow ? ` filter="url(#${shadow})"` : ""}/>`);
10502
- if (p.decl.label) out.push(`<text x="${f(box.x + 16)}" y="${f(box.y + 16 + head * .32)}" dominant-baseline="central" font-size="${f(T.fontSize * 1.05)}" font-weight="650" fill="${s.text}" xml:space="preserve">${tspans(parseInline(p.decl.label), {
10503
- text: s.text,
10504
- sub: T.node.sub,
10505
- stroke: T.node.stroke
10506
- }, T)}</text>`);
10867
+ if (p.decl.label) out.push(`<text x="${f(box.x + 16)}" y="${f(box.y + 16 + head * .32)}" dominant-baseline="central" font-size="${f(p.ctx.fs * 1.05)}" font-weight="${tf.weight}"${tf.italic ? " font-style=\"italic\"" : ""} fill="${s.text}" xml:space="preserve">${tspans(parseInline(p.decl.label), nodeInk(T, s.text), T)}</text>`);
10507
10868
  p.ctx.idPrefix = `${id}-${p.decl.id}`;
10508
10869
  out.push(kind.render(p.decl.data, p.inner, !measure || measure === p.ctx.measure ? p.ctx : {
10509
10870
  ...p.ctx,
@@ -10517,13 +10878,13 @@ function renderGroup(g, L, interactive) {
10517
10878
  const s = g.style;
10518
10879
  const fs = T.fontSize * .82;
10519
10880
  const p = g.decl.props;
10520
- const caps = p.caps !== void 0 && p.caps !== "false";
10521
- const text = caps ? g.decl.label.toUpperCase() : g.decl.label;
10881
+ const font = groupFont(g.decl, T);
10882
+ const text = g.decl.label;
10883
+ const ink = nodeInk(T, s.text, s.stroke);
10522
10884
  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>` : "";
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>` : "";
10885
+ const body = lines.length > 1 ? textLines(lines, g.x + 18 - 4, (i) => g.y + 17 + i * g.lineHeight, (l) => richText(l, ink, T, font.caps)) : richText(text, ink, T, font.caps);
10886
+ const label = text ? `<text x="${f(g.x + 18 - 4)}" y="${f(g.y + 17)}" font-size="${f(font.size)}" font-weight="${font.weight}"${font.italic ? " font-style=\"italic\"" : ""} letter-spacing="${font.caps ? "0.1em" : "0.02em"}" fill="${s.text}" xml:space="preserve">${body}</text>` : "";
10887
+ 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}" xml:space="preserve">${richText(p.meta, subInk(ink), T)}</text>` : "";
10527
10888
  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>";
10528
10889
  }
10529
10890
  /**
@@ -10564,27 +10925,30 @@ function groupTint(x, y, e, L) {
10564
10925
  function renderEdgeLabel(e, L) {
10565
10926
  const lb = e.label;
10566
10927
  const T = L.theme;
10567
- const fs = T.fontSize * .86;
10928
+ const s = e.style;
10929
+ const fs = s.fontSize;
10568
10930
  const { x: ax, y: ay } = lb.anchor;
10569
10931
  const parts = [];
10570
10932
  const lines = lb.text ? lb.text.split("\n") : [];
10933
+ const ink = nodeInk(T, s.text, s.stroke);
10571
10934
  if (lines.length) {
10572
10935
  const { w, h } = lb.pill;
10573
- const lh = fs * 1.3;
10936
+ const lh = lb.lineHeight;
10574
10937
  const y0 = ay - (lines.length - 1) * lh / 2;
10575
- const text = lines.map((l, i) => `<tspan x="${f(ax)}" y="${f(y0 + i * lh)}">${esc(l)}</tspan>`).join("");
10938
+ const text = textLines(lines, ax, (i) => y0 + i * lh, (l) => richText(l, ink, T));
10576
10939
  const stroke = T.edge.labelStroke;
10577
10940
  const box = `x="${f(ax - w / 2)}" y="${f(ay - h / 2)}" width="${f(w)}" height="${f(h)}" rx="${stroke ? f(h / 2) : 4}"`;
10578
- parts.push(`<rect ${box} fill="${e.style.labelBg}"` + (stroke ? ` stroke="${stroke}" stroke-width="1"` : "") + "/>", ...groupTint(ax, ay, e, L).map((fill) => `<rect ${box} fill="${fill}"/>`), `<text text-anchor="middle" dominant-baseline="central" font-size="${f(fs)}" font-weight="500" fill="${e.style.text}">${text}</text>`);
10941
+ parts.push(`<rect ${box} fill="${e.style.labelBg}"` + (stroke ? ` stroke="${stroke}" stroke-width="1"` : "") + "/>", ...groupTint(ax, ay, e, L).map((fill) => `<rect ${box} fill="${fill}"/>`), `<text text-anchor="middle" dominant-baseline="central" font-size="${f(fs)}" font-weight="${s.fontWeight}"${s.italic ? " font-style=\"italic\"" : ""} fill="${s.text}" xml:space="preserve">${text}</text>`);
10579
10942
  }
10580
10943
  if (lb.caption) {
10581
10944
  const cs = fs * .88;
10582
10945
  const cl = lb.caption.split("\n");
10946
+ const clh = lb.captionLineHeight;
10583
10947
  const top = ay + (lines.length ? lb.pill.h / 2 : 0) + 2;
10584
10948
  const cw = Math.max(lb.pill.w, lb.w);
10585
- const bg = `<rect x="${f(ax - (lb.rotate ? lb.h : cw) / 2)}" y="${f(top)}" width="${f(lb.rotate ? lb.h : cw)}" height="${f(cl.length * cs * 1.3 + 2)}" fill="${T.background === "none" ? "none" : e.style.labelBg}" opacity="0.85"/>`;
10586
- const text = cl.map((l, i) => `<tspan x="${f(ax)}" y="${f(top + cs * 1.3 * (i + .5) + 1)}">${esc(l)}</tspan>`).join("");
10587
- parts.push(bg, `<text text-anchor="middle" dominant-baseline="central" font-size="${f(cs)}" fill="${T.node.sub}">${text}</text>`);
10949
+ const bg = `<rect x="${f(ax - (lb.rotate ? lb.h : cw) / 2)}" y="${f(top)}" width="${f(lb.rotate ? lb.h : cw)}" height="${f(cl.length * clh + 2)}" fill="${T.background === "none" ? "none" : e.style.labelBg}" opacity="0.85"/>`;
10950
+ const text = textLines(cl, ax, (i) => top + clh * (i + .5) + 1, (l) => richText(l, subInk(ink), T));
10951
+ parts.push(bg, `<text text-anchor="middle" dominant-baseline="central" font-size="${f(cs)}" fill="${T.node.sub}" xml:space="preserve">${text}</text>`);
10588
10952
  }
10589
10953
  const rot = lb.rotate ? ` transform="rotate(-90 ${f(ax)} ${f(ay)})"` : "";
10590
10954
  return `<g${attr("data-edge-label", e.key)}${rot}>${parts.join("")}</g>`;
@@ -10614,11 +10978,13 @@ function renderNode(d, n, L, shadowId) {
10614
10978
  radius: s.radius,
10615
10979
  fs: s.fontSize
10616
10980
  }));
10617
- parts.push(renderCard(tb.card, n.x, n.y, n.w, n.h, {
10981
+ const col = {
10618
10982
  text: s.text,
10619
10983
  sub: s.sub,
10620
- stroke: s.stroke
10621
- }, L.theme));
10984
+ stroke: s.stroke,
10985
+ body: s.body
10986
+ };
10987
+ parts.push(renderCard(tb.card, n.x, n.y, n.w, n.h, col, L.theme));
10622
10988
  parts.push("</g>");
10623
10989
  let g = parts.join("");
10624
10990
  g = withLink(g, p.link);
@@ -10631,13 +10997,18 @@ function renderNode(d, n, L, shadowId) {
10631
10997
  y += tb.iconSize + 4;
10632
10998
  }
10633
10999
  const textAttrs = `text-anchor="middle" dominant-baseline="central" font-size="${f(s.fontSize)}" font-weight="${s.fontWeight}" fill="${s.text}"` + (s.italic ? " font-style=\"italic\"" : "") + (tb.letterSpacing ? ` letter-spacing="${f(tb.letterSpacing)}"` : "");
10634
- const spans = tb.lines.map((l, i) => `<tspan x="${f(cx)}" y="${f(y + tb.lineHeight * (i + .5))}">${esc(l)}</tspan>`).join("");
10635
- parts.push(`<text ${textAttrs}>${spans}</text>`);
11000
+ const ink = {
11001
+ text: s.text,
11002
+ sub: s.sub,
11003
+ stroke: s.stroke
11004
+ };
11005
+ const spans = textLines(tb.lines, cx, (i) => y + tb.lineHeight * (i + .5), (l) => richText(l, ink, L.theme, tb.caps));
11006
+ parts.push(`<text ${textAttrs} xml:space="preserve">${spans}</text>`);
10636
11007
  y += tb.lines.length * tb.lineHeight;
10637
11008
  if (tb.sub.length) {
10638
11009
  y += 3;
10639
- const subSpans = tb.sub.map((l, i) => `<tspan x="${f(cx)}" y="${f(y + tb.subLineHeight * (i + .5))}">${esc(l)}</tspan>`).join("");
10640
- parts.push(`<text text-anchor="middle" dominant-baseline="central" font-size="${f(tb.subSize)}" fill="${s.sub}">${subSpans}</text>`);
11010
+ const subSpans = textLines(tb.sub, cx, (i) => y + tb.subLineHeight * (i + .5), (l) => richText(l, subInk(ink), L.theme));
11011
+ parts.push(`<text text-anchor="middle" dominant-baseline="central" font-size="${f(tb.subSize)}" fill="${s.sub}" xml:space="preserve">${subSpans}</text>`);
10641
11012
  }
10642
11013
  parts.push("</g>");
10643
11014
  let g = parts.join("");
@@ -10673,17 +11044,24 @@ const ARROWS = /* @__PURE__ */ new Set([
10673
11044
  "-"
10674
11045
  ]);
10675
11046
  const ID_RE = /^[\p{L}_][\p{L}\p{N}_]*(?:-[\p{L}\p{N}_]+)*$/u;
10676
- const q$1 = (s) => JSON.stringify(s);
10677
- function props(bag, skip) {
11047
+ const CLASS_RE = /^[\p{L}_][\p{L}\p{N}_-]*$/u;
11048
+ const KEY_RE = /^[\p{L}_][\p{L}\p{N}_-]*$/u;
11049
+ const q$1 = quote;
11050
+ function props(bag, skip, errors) {
10678
11051
  const p = {};
10679
11052
  for (const [k, v] of Object.entries(bag)) {
10680
11053
  if (skip.includes(k) || v === void 0 || v === null) continue;
11054
+ if (!KEY_RE.test(k)) {
11055
+ errors.push(`prop name ${JSON.stringify(k)} must use only letters, digits, "_" and "-"`);
11056
+ continue;
11057
+ }
10681
11058
  p[k] = typeof v === "object" ? JSON.stringify(v) : String(v);
10682
11059
  }
10683
11060
  const s = serializeProps(p);
10684
11061
  return s ? ` [${s}]` : "";
10685
11062
  }
10686
- const classes = (c) => (Array.isArray(c) ? c : c ? [c] : []).map((x) => ` .${x}`).join("");
11063
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
11064
+ const classes = (c, errors) => (Array.isArray(c) ? c : c ? [c] : []).filter((x) => typeof x === "string" && CLASS_RE.test(x) || (errors.push(`class name ${JSON.stringify(x)} is not a valid name`), false)).map((x) => ` .${x}`).join("");
10687
11065
  const list = (v) => Array.isArray(v) ? v : [v];
10688
11066
  function fromJSON(input) {
10689
11067
  const errors = [];
@@ -10700,30 +11078,47 @@ function fromJSON(input) {
10700
11078
  source: "",
10701
11079
  errors: ["JSON diagram must be an object"]
10702
11080
  };
11081
+ /** `j[key]` when it is an array of objects; anything else is reported and skipped */
11082
+ const items = (key) => {
11083
+ const v = j[key];
11084
+ if (v === void 0 || v === null) return [];
11085
+ if (!Array.isArray(v)) return errors.push(`"${key}" must be an array`), [];
11086
+ return v.filter((x, i) => isObj(x) || (errors.push(`${key}[${i}] must be an object`), false));
11087
+ };
11088
+ const bag = (key) => {
11089
+ const v = j[key];
11090
+ if (v === void 0 || v === null || isObj(v)) return v ?? {};
11091
+ errors.push(`"${key}" must be an object`);
11092
+ return {};
11093
+ };
10703
11094
  const out = [];
10704
- const settings = { ...j.settings };
11095
+ const settings = { ...bag("settings") };
10705
11096
  for (const k of [
10706
11097
  "title",
10707
11098
  "direction",
10708
11099
  "theme"
10709
11100
  ]) if (j[k] !== void 0) settings[k] = j[k];
10710
- for (const [k, v] of Object.entries(settings)) out.push(`${k}: ${String(v)}`);
11101
+ for (const [k, v] of Object.entries(settings)) if (!KEY_RE.test(k)) errors.push(`setting name ${JSON.stringify(k)} must use only letters, digits, "_" and "-"`);
11102
+ else out.push(`${k}: ${/[\n\r"'{}]|\s\/\/|^\s|\s$/.test(String(v)) ? q$1(String(v)) : String(v)}`);
10711
11103
  if (out.length) out.push("");
10712
- for (const [name, p] of Object.entries(j.classes ?? {})) out.push(`.${name}${props(p, [])}`);
10713
- if (j.classes && Object.keys(j.classes).length) out.push("");
11104
+ const classDefs = Object.entries(bag("classes"));
11105
+ for (const [name, p] of classDefs) if (!CLASS_RE.test(name)) errors.push(`class name ${JSON.stringify(name)} is not a valid name`);
11106
+ else if (isObj(p)) out.push(`.${name}${props(p, [], errors)}`);
11107
+ else errors.push(`class "${name}" must be an object of props`);
11108
+ if (classDefs.length) out.push("");
10714
11109
  const checkId = (id, what) => {
10715
11110
  if (typeof id === "string" && ID_RE.test(id)) return true;
10716
11111
  errors.push(`${what} id ${JSON.stringify(id)} must start with a letter and use only letters, digits, "_" and "-"`);
10717
11112
  return false;
10718
11113
  };
10719
11114
  const nodeLine = (n, pad) => {
10720
- const head = `${n.id}${n.label !== void 0 ? " " + q$1(String(n.label)) : ""}${classes(n.class)}${props(n, [
11115
+ const head = `${n.id}${n.label !== void 0 ? " " + q$1(String(n.label)) : ""}${classes(n.class, errors)}${props(n, [
10721
11116
  "id",
10722
11117
  "label",
10723
11118
  "group",
10724
11119
  "class",
10725
11120
  "body"
10726
- ])}`;
11121
+ ], errors)}`;
10727
11122
  const body = n.body === void 0 ? [] : Array.isArray(n.body) ? n.body.map(String) : String(n.body).split("\n");
10728
11123
  if (!body.length) return pad + head;
10729
11124
  if (body.some((l) => l.trim() === "}")) errors.push(`node "${n.id}" body must not contain a line that is only "}"`);
@@ -10733,20 +11128,20 @@ function fromJSON(input) {
10733
11128
  `${pad}}`
10734
11129
  ].join("\n");
10735
11130
  };
10736
- const groups = (j.groups ?? []).filter((g) => checkId(g.id, "group"));
11131
+ const groups = items("groups").filter((g) => checkId(g.id, "group"));
10737
11132
  const groupIds = new Set(groups.map((g) => g.id));
10738
- const nodes = (j.nodes ?? []).filter((n) => checkId(n.id, "node"));
10739
- for (const n of nodes) if (n.group && !groupIds.has(n.group)) groups.push({ id: n.group }), groupIds.add(n.group);
11133
+ const nodes = items("nodes").filter((n) => checkId(n.id, "node"));
11134
+ for (const n of nodes) if (n.group && !groupIds.has(n.group) && checkId(n.group, "group")) groups.push({ id: n.group }), groupIds.add(n.group);
10740
11135
  const emitGroup = (gid, depth) => {
10741
11136
  const pad = " ".repeat(depth);
10742
11137
  for (const n of nodes.filter((x) => (x.group || void 0) === gid)) out.push(nodeLine(n, pad));
10743
11138
  for (const g of groups.filter((x) => (x.parent || void 0) === gid)) {
10744
- out.push(`${pad}group ${g.id}${g.label !== void 0 ? " " + q$1(String(g.label)) : ""}${classes(g.class)}${props(g, [
11139
+ out.push(`${pad}group ${g.id}${g.label !== void 0 ? " " + q$1(String(g.label)) : ""}${classes(g.class, errors)}${props(g, [
10745
11140
  "id",
10746
11141
  "label",
10747
11142
  "parent",
10748
11143
  "class"
10749
- ])} {`);
11144
+ ], errors)} {`);
10750
11145
  emitGroup(g.id, depth + 1);
10751
11146
  out.push(`${pad}}`);
10752
11147
  }
@@ -10754,7 +11149,7 @@ function fromJSON(input) {
10754
11149
  for (const g of groups) if (g.parent && !groupIds.has(g.parent)) errors.push(`group "${g.id}" has unknown parent "${g.parent}"`);
10755
11150
  emitGroup(void 0, 0);
10756
11151
  if (nodes.length || groups.length) out.push("");
10757
- for (const e of j.edges ?? []) {
11152
+ for (const e of items("edges")) {
10758
11153
  if (e.from === void 0 || e.to === void 0) {
10759
11154
  errors.push(`edge ${JSON.stringify(e)} needs "from" and "to"`);
10760
11155
  continue;
@@ -10764,13 +11159,13 @@ function fromJSON(input) {
10764
11159
  if (!from.length || !to.length) continue;
10765
11160
  const arrow = e.arrow ?? "->";
10766
11161
  if (!ARROWS.has(arrow)) errors.push(`edge arrow "${arrow}" must be one of ${[...ARROWS].join(" ")}`);
10767
- const tail = `${e.label !== void 0 ? " " + q$1(String(e.label)) : ""}${classes(e.class)}${props(e, [
11162
+ const tail = `${e.label !== void 0 ? " " + q$1(String(e.label)) : ""}${classes(e.class, errors)}${props(e, [
10768
11163
  "from",
10769
11164
  "to",
10770
11165
  "label",
10771
11166
  "arrow",
10772
11167
  "class"
10773
- ])}`;
11168
+ ], errors)}`;
10774
11169
  out.push(`${from.join(", ")} ${ARROWS.has(arrow) ? arrow : "->"} ${to.join(", ")}${tail ? ":" + tail : ""}`);
10775
11170
  }
10776
11171
  return {
@@ -10853,7 +11248,7 @@ function splitList(s) {
10853
11248
  }
10854
11249
  /** an edge label: bare when it is plain words, else quoted */
10855
11250
  const edgeLabel = (s) => /^[\p{L}\p{N}][\p{L}\p{N} ,!?'()+-]*$/u.test(s) ? s : q(s);
10856
- const CSS_MAP = {
11251
+ const CSS_MAP = table({
10857
11252
  fill: "fill",
10858
11253
  stroke: "stroke",
10859
11254
  color: "text",
@@ -10863,7 +11258,7 @@ const CSS_MAP = {
10863
11258
  "font-size": "font-size",
10864
11259
  rx: "radius",
10865
11260
  opacity: "opacity"
10866
- };
11261
+ });
10867
11262
  /** Mermaid `fill:#f96,stroke:#333` → yuhwa props */
10868
11263
  function cssProps(css, warn) {
10869
11264
  const parts = [];
@@ -10958,14 +11353,14 @@ function emit(title, direction, classDefs, cards, root, scopes, rels) {
10958
11353
  ...out
10959
11354
  ];
10960
11355
  }
10961
- const MARK = {
11356
+ const MARK = table({
10962
11357
  "<|": "open",
10963
11358
  "|>": "open",
10964
11359
  "*": "diamond",
10965
11360
  o: "diamond",
10966
11361
  "<": "arrow",
10967
11362
  ">": "arrow"
10968
- };
11363
+ });
10969
11364
  const REL_SPACED = /^(\S+?)\s+(?:"([^"]*)"\s+)?(<\||\*|o|<|)(--|\.\.)(\|>|\*|o|>|)\s+(?:"([^"]*)"\s+)?(\S+?)\s*(?::\s*(.*))?$/;
10970
11365
  const REL_TIGHT = /^([^\s<*.-]+?)\s*(?:"([^"]*)"\s*)?(<\||\*|<|)(--|\.\.)(\|>|\*|>|)\s*(?:"([^"]*)"\s*)?([^\s:]+?)\s*(?::\s*(.*))?$/;
10971
11366
  const generic = (s) => s.replace(/~([^~]*)~/g, "<$1>");
@@ -11730,13 +12125,13 @@ const quadrant = (lines, ctx) => {
11730
12125
  }
11731
12126
  return panel("quadrant", panelId(st.title, "matrix"), st.title, [], body);
11732
12127
  };
11733
- const PRIORITY = {
12128
+ const PRIORITY = table({
11734
12129
  "very high": "high",
11735
12130
  high: "high",
11736
12131
  medium: "medium",
11737
12132
  low: "low",
11738
12133
  "very low": "low"
11739
- };
12134
+ });
11740
12135
  function kanbanItem(t) {
11741
12136
  const meta = {};
11742
12137
  const at = t.match(/@\{(.*)\}\s*$/);
@@ -12075,7 +12470,7 @@ const DIRECTIONS = {
12075
12470
  RL: "left"
12076
12471
  };
12077
12472
  /** Mermaid diagram keywords yuhwa converts, besides flowcharts */
12078
- const CONVERTERS = {
12473
+ const CONVERTERS = table({
12079
12474
  sequenceDiagram: sequence,
12080
12475
  timeline,
12081
12476
  gitGraph: git,
@@ -12092,7 +12487,7 @@ const CONVERTERS = {
12092
12487
  classDiagram,
12093
12488
  "classDiagram-v2": classDiagram,
12094
12489
  erDiagram
12095
- };
12490
+ });
12096
12491
  /** Mermaid diagram keywords with no yuhwa equivalent */
12097
12492
  const UNSUPPORTED = /^(requirementDiagram|C4Context|C4Container|C4Component|C4Dynamic|C4Deployment|sankey(?:-beta)?|block(?:-beta)?|architecture(?:-beta)?|packet(?:-beta)?|radar(?:-beta)?|treemap(?:-beta)?|zenuml)$/;
12098
12493
  /** number of lines taken by a leading `---` ... `---` front matter block (0 when none) */
@@ -12261,7 +12656,7 @@ const SHAPES = [
12261
12656
  ]
12262
12657
  ];
12263
12658
  const MID_RE = /^[A-Za-z0-9_][\w]*(?:[.-](?![-.=>ox]\s|[-.=>])[\w]+)*/;
12264
- const LINK_TEXT_RE = /^([<ox])?(--|==|-\.)\s*([^-=.>|][^>|]*?)\s*(-{2,}>?|={2,}>?|\.+-+>?|-\.+-*>?)(?:([ox])(?=\s|$))?/;
12659
+ const LINK_TEXT_RE = /^([<ox])?(--|==|-\.)([^-=.>|][^>|]*?)(-{2,}>?|={2,}>?|\.+-+>?|-\.+-*>?)(?:([ox])(?=\s|$))?/;
12265
12660
  const LINK_RE = /^([<ox])?(-{2,}|={2,}|-\.+-)(>|[ox](?=[\s|]|$))?(?:\s*\|([^|]*)\|)?/;
12266
12661
  /** Mermaid flowchart → yuhwa nodes, edges and groups */
12267
12662
  function fromFlowchart(source) {
@@ -12686,6 +13081,7 @@ function tidy(source, d, toks) {
12686
13081
  * as a whole and keep their inner indentation. Lines of a `def` body are moved
12687
13082
  * the same way, since they may hold such bodies.
12688
13083
  */
13084
+ const INDENT = " ";
12689
13085
  const lead = (l) => l.match(/^\s*/)[0].length;
12690
13086
  const leadTabs = (l) => l.match(/^[ \t]*/)[0].length;
12691
13087
  /** line ranges `[open, close]` whose inner lines are kept as they are */
@@ -12839,7 +13235,75 @@ function applyChange(text, change) {
12839
13235
  const b = Math.max(a, offsetAt(text, change.range.end));
12840
13236
  return text.slice(0, a) + change.text + text.slice(b);
12841
13237
  }
13238
+ /**
13239
+ * The indent for a line broken at `offset`: the current line's own, one step
13240
+ * deeper when the text before the break opens a block. Indentation-shaped
13241
+ * bodies (mind maps, tree views) keep their depth, so Enter starts a sibling.
13242
+ */
13243
+ function newlineIndent(text, offset) {
13244
+ const before = text.slice(text.lastIndexOf("\n", offset - 1) + 1, offset);
13245
+ const own = before.match(/^[ \t]*/)[0];
13246
+ let open = 0;
13247
+ for (const b of blockBraces(lex(before).tokens)) open = Math.max(0, open + (b === "{" ? 1 : -1));
13248
+ return open ? own + INDENT : own;
13249
+ }
13250
+ /** The indent for a `}` typed on the line holding `offset`: that of its opener. */
13251
+ function closeIndent(text, offset) {
13252
+ let depth = 1;
13253
+ for (let end = text.lastIndexOf("\n", offset - 1); end >= 0;) {
13254
+ const start = end > 0 ? text.lastIndexOf("\n", end - 1) + 1 : 0;
13255
+ const line = text.slice(start, text[end - 1] === "\r" ? end - 1 : end);
13256
+ for (const b of blockBraces(lex(line).tokens).reverse()) {
13257
+ depth += b === "}" ? 1 : -1;
13258
+ if (!depth) return line.match(/^[ \t]*/)[0];
13259
+ }
13260
+ end = start - 1;
13261
+ }
13262
+ return "";
13263
+ }
13264
+ /**
13265
+ * What a line broken at `offset` starts with: its indent, plus the bullet of
13266
+ * an outline item (`- ` or `* `), so a list in a mind map or tree view goes on.
13267
+ */
13268
+ function newlinePrefix(text, offset) {
13269
+ const indent = newlineIndent(text, offset);
13270
+ const before = text.slice(text.lastIndexOf("\n", offset - 1) + 1, offset);
13271
+ return indent + ((indent === before.match(/^[ \t]*/)[0] ? before.match(/^[ \t]*([-*] +)\S/)?.[1] : void 0) ?? "");
13272
+ }
13273
+ /**
13274
+ * Edits after a character was typed at `pos`: a newline re-indents the new
13275
+ * line and continues a bullet, a `}` alone on its line lines up with its opener.
13276
+ */
13277
+ function onTypeEdits(text, pos, ch) {
13278
+ const start = offsetAt(text, {
13279
+ line: pos.line,
13280
+ character: 0
13281
+ });
13282
+ const nl = text.indexOf("\n", start);
13283
+ const line = text.slice(start, nl < 0 ? text.length : nl).replace(/\r$/, "");
13284
+ let end = line.match(/^[ \t]*/)[0].length;
13285
+ let want;
13286
+ if (ch === "\n" && pos.line > 0) {
13287
+ want = newlinePrefix(text, start - (text[start - 2] === "\r" ? 2 : 1));
13288
+ const bullet = line.slice(end).match(/^[-*] +/)?.[0];
13289
+ if (bullet && want.endsWith(bullet)) end += bullet.length;
13290
+ } else if (ch === "}" && /^[ \t]*\}$/.test(line.slice(0, pos.character))) want = closeIndent(text, offsetAt(text, pos));
13291
+ if (want === void 0 || want === line.slice(0, end)) return [];
13292
+ return [{
13293
+ range: {
13294
+ start: {
13295
+ line: pos.line,
13296
+ character: 0
13297
+ },
13298
+ end: {
13299
+ line: pos.line,
13300
+ character: end
13301
+ }
13302
+ },
13303
+ newText: want
13304
+ }];
13305
+ }
12842
13306
  // src/version.ts
12843
13307
  /** the package version, inlined by the build */
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 };
13308
+ const VERSION = "1.2.0";
13309
+ export { PLACEMENT_PROPS as A, themeNames as B, COLORS as C, NODE_PROPS as D, GROUP_PROPS as E, spanKey as F, THEME_KEYS as I, THEME_NAMES as L, SPAN_KEYS as M, esc$1 as N, NUMBERS as O, parseSpanStyle as P, TONES as R, BOOLS as S, ENUMS as T, table as V, isYuhwaPath as _, onTypeEdits as a, parse as b, render as c, optionKind as d, registry as f, blockBraces as g, SETTING_VALUES as h, format as i, SHAPES$2 as j, PANEL_PROPS as k, toSource as l, PANELS as m, applyChange as n, tidy as o, KNOWN_SETTINGS as p, diffEdits as r, diskResolve as s, VERSION as t, canvasMeasure as u, joinPath as v, EDGE_PROPS as w, serializeProps as x, lex as y, isSafeCss as z };