yuhwa 1.3.0 → 1.5.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 (60) hide show
  1. package/README.md +5 -3
  2. package/dist/astro.d.ts +28 -2
  3. package/dist/astro.js +30 -6
  4. package/dist/browser.d.ts +10 -4
  5. package/dist/browser.js +85 -22
  6. package/dist/canvas.d.ts +2 -0
  7. package/dist/canvas.js +40 -0
  8. package/dist/cli.js +488 -236
  9. package/dist/editor/assets/index-BAdhu8vV.js +689 -0
  10. package/dist/editor/assets/lsp.worker-PVetuBwo.js +36 -0
  11. package/dist/editor/index.html +4 -1
  12. package/dist/{figure-QAwSU1Ry.d.ts → figure-BXrdbiqy.d.ts} +28 -5
  13. package/dist/{index-6ZPJGThY.d.ts → index-DVU2kSdX.d.ts} +48 -3
  14. package/dist/index.d.ts +3 -3
  15. package/dist/index.js +5 -3
  16. package/dist/ironmark.d.ts +7 -3
  17. package/dist/ironmark.js +13 -5
  18. package/dist/lsp-browser.d.ts +2 -2
  19. package/dist/lsp-browser.js +2 -1
  20. package/dist/lsp-node.js +52 -33
  21. package/dist/lsp-server.d.ts +5 -1
  22. package/dist/lsp-server.js +1 -1
  23. package/dist/lsp.d.ts +1 -1
  24. package/dist/lsp.js +1 -1
  25. package/dist/markdown-it.d.ts +1 -1
  26. package/dist/markdown-it.js +19 -5
  27. package/dist/{node-CLu2Pp_2.js → node-B8dLsEzl.js} +146 -20
  28. package/dist/{plugin-Bs4eiAuz.js → parse-CD6SmUc1.js} +81 -378
  29. package/dist/{plugin-NSkNyoUj.d.ts → plugin-Dj66dvC1.d.ts} +17 -2
  30. package/dist/plugin-Dq5VmHe8.js +300 -0
  31. package/dist/plugin.d.ts +1 -1
  32. package/dist/plugin.js +3 -1
  33. package/dist/raster-Cul5L1bT.js +299 -0
  34. package/dist/remark.d.ts +1 -1
  35. package/dist/remark.js +8 -20
  36. package/dist/rolldown-runtime-CEjnN5Q1.js +37 -0
  37. package/dist/satteri.d.ts +32 -0
  38. package/dist/satteri.js +41 -0
  39. package/dist/{server--jHjJjOS.d.ts → server-Bb5_7tRV.d.ts} +1 -1
  40. package/dist/{server-D6BSNC1P.js → server-DCZj9bmz.js} +42 -64
  41. package/dist/{service-D7DNWBAU.js → service-Cno307YA.js} +39 -9
  42. package/dist/{service-Brvpt7Do.d.ts → service-wlaqtXGz.d.ts} +3 -1
  43. package/dist/{shared-6aCU_HaV.js → shared-DgVcoAJb.js} +456 -279
  44. package/dist/{src-BjOhvTAB.js → src-CBd46GH5.js} +116 -97
  45. package/dist/svg-uri-Dx8SGV-n.js +7 -0
  46. package/dist/vite.d.ts +1 -1
  47. package/dist/vite.js +3 -3
  48. package/dist/vuepress.d.ts +3 -2
  49. package/dist/vuepress.js +4 -2
  50. package/dist/watch-2VeW5DUN.js +35 -0
  51. package/dist/yuhwa.iife.js +55 -54
  52. package/dist/zoom-script-CaJ5MNUw.js +29 -0
  53. package/dist/{zoom-QeqB6QlH.js → zoom-yxhxX16c.js} +1 -1
  54. package/dist/zoom.d.ts +16 -7
  55. package/dist/zoom.js +2 -2
  56. package/package.json +24 -2
  57. package/skills/yuhwa/SKILL.md +12 -0
  58. package/dist/editor/assets/index-DAk6b1UB.js +0 -689
  59. package/dist/editor/assets/lsp.worker-CMSpDTsX.js +0 -30
  60. package/dist/zoom-script-CVdAzMhX.js +0 -51
@@ -263,6 +263,7 @@ function ramp(tone, level) {
263
263
  }
264
264
  const SANS = "Inter, ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif";
265
265
  const MONO = "'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
266
+ const SERIF = "ui-serif, Georgia, Cambria, 'Times New Roman', Times, serif";
266
267
  const lightTone = (t) => RAMPS[t] && {
267
268
  fill: ramp(t, 50),
268
269
  stroke: ramp(t, 300),
@@ -374,7 +375,10 @@ const rgb = (hex) => {
374
375
  ].map((i) => parseInt(h.slice(i, i + 2), 16));
375
376
  };
376
377
  /** `a` mixed into `b` by `t` (0..1), both hex */
377
- const mix = (a, b, t) => "#" + rgb(a).map((v, i) => Math.round(v * t + rgb(b)[i] * (1 - t))).map((v) => v.toString(16).padStart(2, "0")).join("");
378
+ const mix = (a, b, t) => {
379
+ const rb = rgb(b);
380
+ return "#" + rgb(a).map((v, i) => Math.round(v * t + rb[i] * (1 - t))).map((v) => v.toString(16).padStart(2, "0")).join("");
381
+ };
378
382
  /** colours for any CSS colour (not a palette name): a tint of it on the theme background */
379
383
  function hexTone(css, theme, group) {
380
384
  const c = cssHex(css);
@@ -404,15 +408,31 @@ const LINE_STYLES = [
404
408
  ];
405
409
  /** the group border dash for a line style; `fallback` when no style is set */
406
410
  const groupDash = (style, fallback) => style === "dashed" ? "6 4" : style === "dotted" ? "1.5 4" : style === "solid" ? null : fallback;
407
- /** a font setting (`mono`, `sans` or a family name) as a CSS font stack */
411
+ const FONT_KEYWORDS = {
412
+ sans: SANS,
413
+ serif: SERIF,
414
+ mono: MONO
415
+ };
416
+ const GENERIC_FONT = /^(serif|sans-serif|monospace|cursive|fantasy|math|emoji|system-ui|ui-(serif|sans-serif|monospace|rounded))$/i;
417
+ /** whether `family` is a CSS generic family such as `serif` or `system-ui` */
418
+ const isGenericFont = (family) => GENERIC_FONT.test(family);
419
+ /** the family names of a CSS font stack, unquoted */
420
+ const fontFamilies = (stack) => stack.split(",").map((f) => f.trim().replace(/^(['"])(.*)\1$/, "$2")).filter(Boolean);
421
+ /**
422
+ * a font setting as a CSS font stack: a family name or a fallback list such
423
+ * as `Lora, Georgia, serif`. `sans`, `serif` and `mono` expand to their
424
+ * stacks; a list that ends without a generic family gets one that matches
425
+ * the first font
426
+ */
408
427
  function fontStack(font) {
409
- const mono = font === "mono" || /mono|code|courier/i.test(font);
410
- if (font === "mono" || font === "sans") return {
411
- font: mono ? MONO : SANS,
412
- mono
413
- };
428
+ const names = font.split(",").map((f) => f.trim()).filter(Boolean);
429
+ const first = fontFamilies(font)[0] ?? "sans";
430
+ const mono = first === "mono" || /mono|code|courier/i.test(first);
431
+ const stack = names.map((f) => FONT_KEYWORDS[f] ?? f);
432
+ const last = names.at(-1) ?? "";
433
+ if (!FONT_KEYWORDS[last] && !isGenericFont(last)) stack.push(mono ? "ui-monospace, monospace" : "ui-sans-serif, system-ui, sans-serif");
414
434
  return {
415
- font: `${font}, ${mono ? "ui-monospace, monospace" : "ui-sans-serif, system-ui, sans-serif"}`,
435
+ font: stack.join(", "),
416
436
  mono
417
437
  };
418
438
  }
@@ -586,8 +606,8 @@ function createTheme(name, props, base) {
586
606
  };
587
607
  }
588
608
  /**
589
- * The themes a diagram defines (`theme name { … }`), built on their bases.
590
- * A base may be another theme of the same diagram; cycles fall back to paper.
609
+ * A theme the diagram defines (`theme name { … }`), built on its base. The
610
+ * base may be another theme of the same diagram; cycles fall back to paper.
591
611
  */
592
612
  function customTheme(name, custom, seen = []) {
593
613
  const props = custom[name];
@@ -871,7 +891,7 @@ const LINE_HEIGHT = 1.3;
871
891
  /** the line height of a block of label lines: its largest font size times `k` */
872
892
  const lineHeight = (lines, fs, k = LINE_HEIGHT) => linesSize(lines, fs) * k;
873
893
  /** one `<tspan>` per line at `x`, line `i` at `y(i)` */
874
- const textLines = (lines, x, y, body) => lines.map((l, i) => `<tspan x="${f$1(x)}" y="${f$1(y(i))}">${body(l)}</tspan>`).join("");
894
+ const textLines = (lines, x, y, body) => lines.map((l, i) => `<tspan x="${f(x)}" y="${f(y(i))}">${body(l)}</tspan>`).join("");
875
895
  /**
876
896
  * The inside of a `<text>`/`<tspan>` for a label line: escaped text when it
877
897
  * has no markup (so plain labels render as before), styled tspans otherwise.
@@ -893,9 +913,9 @@ function dedent(lines) {
893
913
  return lines.map((l) => l.slice(cut).replace(/\t/g, " "));
894
914
  }
895
915
  const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
896
- const f$1 = (n) => (Math.round(n * 100) / 100).toString();
916
+ const f = (n) => (Math.round(n * 100) / 100).toString();
897
917
  /** a single-line `<text>` centred vertically on `y` */
898
- const textEl = (x, y, fs, fill, body, extra = "") => `<text x="${f$1(x)}" y="${f$1(y)}" dominant-baseline="central" font-size="${f$1(fs)}" fill="${fill}"${extra}>${body}</text>`;
918
+ const textEl = (x, y, fs, fill, body, extra = "") => `<text x="${f(x)}" y="${f(y)}" dominant-baseline="central" font-size="${f(fs)}" fill="${fill}"${extra}>${body}</text>`;
899
919
  /** resolve a tone or CSS colour for marks drawn on top of an element */
900
920
  const inkColor = (c, theme, fallback) => c && resolveColor(c, theme, theme.dark ? 400 : 600) || fallback;
901
921
  const CHIP_PAD = .55;
@@ -931,7 +951,7 @@ function renderSegs(segs, x, cy, fs, col, theme, muted = false, weight = 400) {
931
951
  if (s.kind === "chip") {
932
952
  const ch = fs * 1.6;
933
953
  const fill = s.color && c.startsWith("#") && c.length === 7 ? `${c}1f` : "none";
934
- out.push(`<rect x="${f$1(x)}" y="${f$1(cy - ch / 2)}" width="${f$1(w)}" height="${f$1(ch)}" rx="4" fill="${fill}" stroke="${s.color ? c : col.stroke}" stroke-width="1"/>`);
954
+ out.push(`<rect x="${f(x)}" y="${f(cy - ch / 2)}" width="${f(w)}" height="${f(ch)}" rx="4" fill="${fill}" stroke="${s.color ? c : col.stroke}" stroke-width="1"/>`);
935
955
  out.push(textEl(x + fs * CHIP_PAD, cy, fs, s.color ? c : col.text, esc(s.text), " xml:space=\"preserve\""));
936
956
  } else {
937
957
  const wt = segWeight(s, weight);
@@ -940,7 +960,7 @@ function renderSegs(segs, x, cy, fs, col, theme, muted = false, weight = 400) {
940
960
  if (s.kind === "strike") {
941
961
  const lead = s.text.length - s.text.trimStart().length;
942
962
  const x0 = x + w * lead / Math.max(1, s.text.length);
943
- out.push(`<path d="M${f$1(x0)},${f$1(cy)}H${f$1(x + w)}" stroke="${col.sub}" stroke-width="1"/>`);
963
+ out.push(`<path d="M${f(x0)},${f(cy)}H${f(x + w)}" stroke="${col.sub}" stroke-width="1"/>`);
944
964
  }
945
965
  }
946
966
  x += w;
@@ -954,7 +974,7 @@ function renderSegs(segs, x, cy, fs, col, theme, muted = false, weight = 400) {
954
974
  function tspans(segs, col, theme, muted = false) {
955
975
  return segs.map((s) => {
956
976
  const a = [`fill="${segColor(s, col, theme, muted)}"`];
957
- if (s.size) a.push(`font-size="${f$1(s.size)}"`);
977
+ if (s.size) a.push(`font-size="${f(s.size)}"`);
958
978
  if (s.weight) a.push(`font-weight="${s.weight}"`);
959
979
  else if (s.kind === "bold") a.push("font-weight=\"750\"");
960
980
  if (s.italic) a.push("font-style=\"italic\"");
@@ -1013,7 +1033,6 @@ const posNum = (v) => {
1013
1033
  const n = num(v, NaN);
1014
1034
  return n > 0 ? n : void 0;
1015
1035
  };
1016
- /** Merge class props then own props (own wins). */
1017
1036
  /** the shared text props (`font-size`, `font-weight`, `italic`) over an element's defaults */
1018
1037
  const textFont = (p, size, weight) => ({
1019
1038
  size: posNum(p["font-size"]) ?? size,
@@ -1022,6 +1041,7 @@ const textFont = (p, size, weight) => ({
1022
1041
  });
1023
1042
  /** an edge label's font */
1024
1043
  const edgeFont = (p, theme) => textFont(p, theme.fontSize * .86, 500);
1044
+ /** Merge class props then own props (own wins). */
1025
1045
  function effectiveProps(d, decl) {
1026
1046
  const out = {};
1027
1047
  for (const c of decl.classes ?? []) Object.assign(out, d.classes[c]);
@@ -1030,8 +1050,8 @@ function effectiveProps(d, decl) {
1030
1050
  /** the `stroke-dasharray` of a line style at a stroke width; null for solid */
1031
1051
  function dashFor(style, width) {
1032
1052
  switch (style) {
1033
- case "dashed": return `${f$1(width * 4)} ${f$1(width * 3)}`;
1034
- case "dotted": return `${f$1(width * .1)} ${f$1(width * 2.6)}`;
1053
+ case "dashed": return `${f(width * 4)} ${f(width * 3)}`;
1054
+ case "dotted": return `${f(width * .1)} ${f(width * 2.6)}`;
1035
1055
  default: return null;
1036
1056
  }
1037
1057
  }
@@ -1330,10 +1350,11 @@ function routeEdges(d, nodes, ctx) {
1330
1350
  });
1331
1351
  }
1332
1352
  }
1353
+ const order = new Map(items.map((it, i) => [it, i]));
1333
1354
  for (const [k, list] of slots) {
1334
1355
  const side = k.split("\0")[1];
1335
1356
  const horizSide = side === "top" || side === "bottom";
1336
- list.sort((p, q) => (horizSide ? p.other.x - q.other.x : p.other.y - q.other.y) || items.indexOf(p.it) - items.indexOf(q.it));
1357
+ list.sort((p, q) => (horizSide ? p.other.x - q.other.x : p.other.y - q.other.y) || order.get(p.it) - order.get(q.it));
1337
1358
  const n = list.length;
1338
1359
  list.forEach((s, i) => s.it.t[s.end] = n === 1 ? 0 : (i + 1) / (n + 1) * 2 - 1);
1339
1360
  }
@@ -1844,7 +1865,6 @@ function sizeForShape(shape, cw, ch) {
1844
1865
  function textOffset(shape) {
1845
1866
  return SHAPE_KINDS.get(shape)?.textOffset ?? 0;
1846
1867
  }
1847
- const f = (n) => (Math.round(n * 100) / 100).toString();
1848
1868
  /** SVG path data for the outline of a shape; a rounded box when no plugin registered it. */
1849
1869
  function shapePath(shape, b, radius) {
1850
1870
  const custom = SHAPE_KINDS.get(shape);
@@ -2156,12 +2176,12 @@ function checkPanelOptions(props, options, line, warn) {
2156
2176
  } else if (!o.includes(v.toLowerCase())) warn(line, `Unknown ${k} "${v}"${didYouMean(v, [...o]) || ` (use one of: ${o.join(", ")})`}`);
2157
2177
  }
2158
2178
  }
2179
+ /** the 0-based line where a node's prop `key` was written: its own line below, its `[...]`, or the declaration */
2180
+ const propLine = (n, key) => n.ref?.propLines?.[key] ?? n.propAt?.[key] ?? n.ref?.line;
2159
2181
  /**
2160
2182
  * The placement prop a node uses (the first one written) and its anchor id.
2161
2183
  * Layout reads the same choice, so the warnings below describe what it does.
2162
2184
  */
2163
- /** the 0-based line where a node's prop `key` was written: its own line below, its `[...]`, or the declaration */
2164
- const propLine = (n, key) => n.ref?.propLines?.[key] ?? n.propAt?.[key] ?? n.ref?.line;
2165
2185
  function placementOf(props) {
2166
2186
  for (const [k, v] of Object.entries(props)) if (PLACEMENT_PROPS.includes(k) && v) return [k, v.trim()];
2167
2187
  }
@@ -2323,7 +2343,6 @@ const PANELS = /* @__PURE__ */ new Map();
2323
2343
  const STATEMENTS = /* @__PURE__ */ new Map();
2324
2344
  /** diagram transforms, run in order at the end of `parse` */
2325
2345
  const TRANSFORMS = [];
2326
- /** Mermaid-style direction names are accepted too */
2327
2346
  /** settings with a fixed set of values; `theme` is checked against the registered themes */
2328
2347
  const SETTING_VALUES = table({
2329
2348
  direction: [
@@ -2344,6 +2363,7 @@ const SETTING_VALUES = table({
2344
2363
  "wrap"
2345
2364
  ]
2346
2365
  });
2366
+ /** Mermaid-style direction names are accepted too */
2347
2367
  const DIRECTION_ALIASES = table({
2348
2368
  lr: "right",
2349
2369
  rl: "left",
@@ -2352,11 +2372,7 @@ const DIRECTION_ALIASES = table({
2352
2372
  bt: "up"
2353
2373
  });
2354
2374
  const TONE_SET = /* @__PURE__ */ new Set([...TONES, "violet"]);
2355
- const CURVES = /* @__PURE__ */ new Set([
2356
- "smooth",
2357
- "orthogonal",
2358
- "straight"
2359
- ]);
2375
+ const CURVES = new Set(SETTING_VALUES.curve);
2360
2376
  const isShape = (k) => SHAPE_KINDS.has(k) || k in SHAPE_ALIASES;
2361
2377
  /**
2362
2378
  * Imports only read `.yu` (or the older `.yuhwa`) files: a diagram must not pull other files
@@ -2534,7 +2550,6 @@ function addNodeProps(n, props, li) {
2534
2550
  Object.assign(n.props, props);
2535
2551
  for (const k in props) (n.propAt ??= {})[k] = li;
2536
2552
  }
2537
- /** Parse the inside of a `[...]` block: `key: value, key: value, flag` */
2538
2553
  /** `[...]` after a node id. `A[Web Server]` is Mermaid for a label, not a prop list. */
2539
2554
  function nodeProps(tok, id, li, warn) {
2540
2555
  const v = tok.value.trim();
@@ -2549,6 +2564,7 @@ const propKey = (k) => {
2549
2564
  const key = k.trim().toLowerCase();
2550
2565
  return key === "tone" ? "color" : key;
2551
2566
  };
2567
+ /** Parse the inside of a `[...]` block: `key: value, key: value, flag` */
2552
2568
  function parseProps(raw = "") {
2553
2569
  const out = {};
2554
2570
  const parts = [];
@@ -2718,24 +2734,24 @@ function splitList(s) {
2718
2734
  /** `s` as a double-quoted string the lexer reads back unchanged (the inverse of `unescape`) */
2719
2735
  const quote = (s) => `"${s.replace(/[\\"]/g, "\\$&").replace(/\r\n?|\n/g, "\\n").replace(/\t/g, "\\t")}"`;
2720
2736
  const unquote = (s) => /^(["']).*\1$/s.test(s.trim()) ? unescape(s.trim().slice(1, -1)) : s.trim();
2737
+ const emptyDiagram = () => ({
2738
+ settings: {},
2739
+ nodes: /* @__PURE__ */ new Map(),
2740
+ edges: [],
2741
+ groups: /* @__PURE__ */ new Map(),
2742
+ classes: table({}),
2743
+ layout: {
2744
+ nodes: {},
2745
+ edges: {}
2746
+ },
2747
+ panels: [],
2748
+ diagnostics: []
2749
+ });
2721
2750
  function parse(source, opts = {}) {
2722
- const d = {
2723
- settings: {},
2724
- nodes: /* @__PURE__ */ new Map(),
2725
- edges: [],
2726
- groups: /* @__PURE__ */ new Map(),
2727
- classes: table({}),
2728
- layout: {
2729
- nodes: {},
2730
- edges: {}
2731
- },
2732
- panels: [],
2733
- diagnostics: []
2734
- };
2751
+ const d = emptyDiagram();
2735
2752
  const lines = source.split(/\r?\n/);
2736
2753
  const merged = opts.seen ??= /* @__PURE__ */ new Set();
2737
2754
  if (opts.file) merged.add(opts.file);
2738
- /** names marked with `export` (filtered to what exists at the end) */
2739
2755
  /** exported name to the line that exports it */
2740
2756
  const exported = /* @__PURE__ */ new Map();
2741
2757
  /** every `.class` written on a node, edge or group, with its line: checked once all classes are known */
@@ -3038,12 +3054,13 @@ function parse(source, opts = {}) {
3038
3054
  };
3039
3055
  /** export api, .svc | export api "API" [blue] | export group g { ... } */
3040
3056
  const exportStmt = (t, raw, li) => {
3057
+ const reread = () => step(raw.slice(0, t[0].start) + " ".repeat(6) + raw.slice(t[0].end), li);
3041
3058
  if (stack.length) warn(li, "export must be at the top level", "error");
3042
3059
  const setting = t[1].kind === "ident" && t[2]?.value === ":" && KNOWN_SETTINGS.has(t[1].value.toLowerCase());
3043
3060
  if (setting || t[1].value === "theme" && t[2]?.kind === "ident") {
3044
3061
  const key = t[1].value.toLowerCase();
3045
3062
  if (setting && !d.sharedSettings?.includes(key)) (d.sharedSettings ??= []).push(key);
3046
- return step(raw.slice(0, t[0].start) + " ".repeat(6) + raw.slice(t[0].end), li);
3063
+ return reread();
3047
3064
  }
3048
3065
  hasExport = true;
3049
3066
  const list = t.slice(1).every((x) => x.kind === "ident" || x.kind === "class" || x.value === ",");
@@ -3052,7 +3069,7 @@ function parse(source, opts = {}) {
3052
3069
  else if (t[1].value.startsWith("$") && (t[2]?.value === ":" || t[2]?.value === "=")) exp(t[1].value);
3053
3070
  else for (const x of t.slice(1)) if (x.kind === "ident" || x.kind === "class") exp(x.kind === "class" ? `.${x.value}` : x.value);
3054
3071
  if (list && !t.slice(1).some((x) => x.kind === "ident" && PANELS.has(x.value))) return;
3055
- return step(raw.slice(0, t[0].start) + " ".repeat(6) + raw.slice(t[0].end), li);
3072
+ return reread();
3056
3073
  };
3057
3074
  /** theme brand [base: midnight] { | theme brand [base: midnight, accent: red] */
3058
3075
  const themeStmt = (t, li) => {
@@ -3343,7 +3360,7 @@ function parse(source, opts = {}) {
3343
3360
  if (top?.kind === "layout") return layoutLine(raw, li);
3344
3361
  const { tokens: t, codeEnd } = lex(raw);
3345
3362
  if (!t.length) return;
3346
- const foreign = /^\s*%%/.test(raw) ? "Comments start with # or //" : /(--|==|-\.|->|=>)\|[^|]*\|/.test(raw) ? "Edge labels go after a colon: a -> b: label" : void 0;
3363
+ const foreign = /^\s*%%/.test(raw) ? "Comments start with //" : /(--|==|-\.|->|=>)\|[^|]*\|/.test(raw) ? "Edge labels go after a colon: a -> b: label" : void 0;
3347
3364
  if (foreign) return void warn(li, foreign, "error");
3348
3365
  if (t[0].kind === "punct" && t[0].value === "}") return closeBlock(li);
3349
3366
  const head = t[0].kind === "ident" ? t[0].value : void 0;
@@ -3382,9 +3399,7 @@ function parse(source, opts = {}) {
3382
3399
  if (base && base !== name && !names.includes(base)) warn(li, `Unknown base theme "${base}"${didYouMean(base, names)}`);
3383
3400
  }
3384
3401
  const theme = d.settings.theme;
3385
- if (themeLine !== void 0 && theme && !theme.includes("$")) {
3386
- if (!names.includes(theme)) warn(themeLine, `Unknown theme "${theme}"${didYouMean(theme, names) || ` (use one of: ${names.join(", ")})`}`);
3387
- }
3402
+ if (themeLine !== void 0 && theme && !theme.includes("$") && !names.includes(theme)) warn(themeLine, `Unknown theme "${theme}"${didYouMean(theme, names) || ` (use one of: ${names.join(", ")})`}`);
3388
3403
  const seen = /* @__PURE__ */ new Set();
3389
3404
  for (const [c, line] of classUses) {
3390
3405
  if (d.classes[c] || seen.has(`${line}.${c}`)) continue;
@@ -3487,19 +3502,7 @@ function narrow(sub, wanted, fail) {
3487
3502
  for (let g = group; g; g = sub.groups.get(g)?.parent) if (names.has(g)) return true;
3488
3503
  return false;
3489
3504
  };
3490
- const out = {
3491
- settings: {},
3492
- nodes: /* @__PURE__ */ new Map(),
3493
- edges: [],
3494
- groups: /* @__PURE__ */ new Map(),
3495
- classes: table({}),
3496
- layout: {
3497
- nodes: {},
3498
- edges: {}
3499
- },
3500
- panels: [],
3501
- diagnostics: []
3502
- };
3505
+ const out = emptyDiagram();
3503
3506
  const id = (x) => rename.get(x)?.replace(/^\./, "") ?? x;
3504
3507
  const cls = (c) => rename.get(`.${c}`)?.slice(1) ?? c;
3505
3508
  const used = /* @__PURE__ */ new Set();
@@ -3551,6 +3554,13 @@ function narrow(sub, wanted, fail) {
3551
3554
  out.themes = sub.themes;
3552
3555
  return out;
3553
3556
  }
3557
+ /** `a->b` for the first edge between two nodes, then `a->b#2`, `a->b#3`, … */
3558
+ function edgeKey(edgeCount, from, to) {
3559
+ const base = `${from}->${to}`;
3560
+ const n = (edgeCount.get(base) ?? 0) + 1;
3561
+ edgeCount.set(base, n);
3562
+ return n === 1 ? base : `${base}#${n}`;
3563
+ }
3554
3564
  /**
3555
3565
  * Merge an imported diagram into `d`. Things `d` already has keep their
3556
3566
  * values; imported declarations carry no source refs, so editors write
@@ -3593,17 +3603,12 @@ function mergeDiagram(d, sub, edgeCount) {
3593
3603
  own.group ??= n.group;
3594
3604
  if (!own.body && n.body) own.body = n.body;
3595
3605
  }
3596
- for (const e of sub.edges) {
3597
- const base = `${e.from}->${e.to}`;
3598
- const n = (edgeCount.get(base) ?? 0) + 1;
3599
- edgeCount.set(base, n);
3600
- d.edges.push({
3601
- ...e,
3602
- key: n === 1 ? base : `${base}#${n}`,
3603
- ref: void 0,
3604
- labelRef: void 0
3605
- });
3606
- }
3606
+ for (const e of sub.edges) d.edges.push({
3607
+ ...e,
3608
+ key: edgeKey(edgeCount, e.from, e.to),
3609
+ ref: void 0,
3610
+ labelRef: void 0
3611
+ });
3607
3612
  for (const p of sub.panels) d.panels.push({
3608
3613
  ...p,
3609
3614
  lines: void 0,
@@ -3749,11 +3754,8 @@ function parseEdgeStatement(t, li, raw, d, touchNode, edgeCount, warn, relabel,
3749
3754
  [from, to] = [to, from];
3750
3755
  [startHead, endHead] = [false, true];
3751
3756
  }
3752
- const base = `${from}->${to}`;
3753
- const n = (edgeCount.get(base) ?? 0) + 1;
3754
- edgeCount.set(base, n);
3755
3757
  const e = {
3756
- key: n === 1 ? base : `${base}#${n}`,
3758
+ key: edgeKey(edgeCount, from, to),
3757
3759
  from,
3758
3760
  to,
3759
3761
  label,
@@ -3864,303 +3866,4 @@ function parseLayoutLine(code, li, d, warn) {
3864
3866
  } else return warn(li, `Unknown layout keyword "${kw}"`);
3865
3867
  }
3866
3868
  }
3867
- // src/core/plugin.ts
3868
- /** what `options[key]` asks for: a select of values, or one kind of field */
3869
- function optionKind(o) {
3870
- return typeof o === "string" ? { kind: o } : {
3871
- kind: "select",
3872
- values: o
3873
- };
3874
- }
3875
- /**
3876
- * `fn` computed once per panel per layout pass: `measure`, `render` and
3877
- * `handles` share one ctx, so a plugin's geometry wrapped in this is worked
3878
- * out (and its text measured) once instead of three times.
3879
- */
3880
- function perPass(fn) {
3881
- const cache = /* @__PURE__ */ new WeakMap();
3882
- return (data, ctx) => {
3883
- const hit = cache.get(ctx);
3884
- if (hit && hit.data === data) return hit.g;
3885
- const g = fn(data, ctx);
3886
- cache.set(ctx, {
3887
- data,
3888
- g
3889
- });
3890
- return g;
3891
- };
3892
- }
3893
- /**
3894
- * an `editPart` for kinds whose parts only take a colour: `fn` gets the part
3895
- * id and the tone (a tone name or `#hex`; null removes it)
3896
- */
3897
- function recolor(fn) {
3898
- return (body, edit, data) => {
3899
- if (edit.op !== "set" || edit.key !== "color") return null;
3900
- const out = fn(body, edit.id, edit.value || null, data);
3901
- return out && {
3902
- body: out,
3903
- id: edit.id
3904
- };
3905
- };
3906
- }
3907
- /** everything registered through `use` */
3908
- const registry = {
3909
- plugins: [],
3910
- rows: [],
3911
- frames: /* @__PURE__ */ new Map(),
3912
- decorations: [],
3913
- panels: PANELS
3914
- };
3915
- const addAll = (list, items) => {
3916
- for (const i of items ?? []) if (!list.includes(i)) list.push(i);
3917
- };
3918
- /** marker names go in front of `none`, so the choices list the drawn ones first */
3919
- const addMarkers = (list, markers) => {
3920
- for (const m of markers ?? []) {
3921
- if (list.includes(m.name)) continue;
3922
- const none = list.indexOf("none");
3923
- list.splice(none < 0 ? list.length : none, 0, m.name);
3924
- }
3925
- };
3926
- const none = () => {};
3927
- const empty = () => "";
3928
- const zero = () => ({
3929
- w: 0,
3930
- h: 0
3931
- });
3932
- /** what each kind's functions return instead when they throw */
3933
- const FALLBACK = {
3934
- row: {
3935
- parse: () => null,
3936
- finish: none,
3937
- measure: zero,
3938
- render: empty
3939
- },
3940
- frame: {
3941
- inset: () => ({ top: 0 }),
3942
- render: empty
3943
- },
3944
- decoration: {
3945
- measure: () => null,
3946
- render: empty
3947
- },
3948
- shape: {
3949
- path: (b) => rectPath(b.x, b.y, b.w, b.h, 0),
3950
- size: (w, h) => ({
3951
- w,
3952
- h
3953
- }),
3954
- detail: () => null,
3955
- port: (b) => ({
3956
- x: b.x + b.w / 2,
3957
- y: b.y + b.h / 2
3958
- })
3959
- },
3960
- marker: {
3961
- render: empty,
3962
- inset: () => 0
3963
- },
3964
- panel: {
3965
- measure: zero,
3966
- render: empty,
3967
- handles: () => [],
3968
- parts: () => [],
3969
- editPart: () => null
3970
- },
3971
- hook: {
3972
- transform: none,
3973
- afterLayout: none,
3974
- postRender: (svg) => svg
3975
- }
3976
- };
3977
- /** `k` with each function named in `fb` wrapped by `guard` */
3978
- function wrap(plugin, what, k, fb) {
3979
- const out = { ...k };
3980
- for (const [m, f] of Object.entries(fb)) {
3981
- const fn = out[m];
3982
- if (typeof fn === "function") out[m] = guard(plugin, what(m), fn.bind(k), f);
3983
- }
3984
- return out;
3985
- }
3986
- /** copies of a plugin's parts whose every function reports a throw instead of passing it on */
3987
- function guarded(p) {
3988
- const n = p.name;
3989
- const kinds = (list, what, fb) => (list ?? []).map((k) => wrap(n, (m) => what(k, m), k, fb));
3990
- return {
3991
- rows: kinds(p.rows, (r) => `row "${r.kind}"`, FALLBACK.row),
3992
- frames: kinds(p.frames, (f) => `frame "${f.name}"`, FALLBACK.frame),
3993
- decorations: kinds(p.decorations, (d) => `decoration "${d.name}"`, FALLBACK.decoration),
3994
- shapes: kinds(p.shapes, (s) => `shape "${s.name}"`, FALLBACK.shape),
3995
- markers: kinds(p.markers, (k) => `marker "${k.name}"`, FALLBACK.marker),
3996
- panels: kinds(p.panels, (pk, m) => `${pk.name} panel ${m === "editPart" ? "edit" : m}`, FALLBACK.panel),
3997
- statements: (p.statements ?? []).map((st) => ({
3998
- ...st,
3999
- parse: guard(n, st.keyword, st.parse.bind(st), none, (msg, [, , ctx]) => ctx.warn(msg, "error"))
4000
- })),
4001
- hooks: wrap(n, (m) => m, {
4002
- transform: p.transform,
4003
- afterLayout: p.afterLayout,
4004
- postRender: p.postRender
4005
- }, FALLBACK.hook)
4006
- };
4007
- }
4008
- /** the tables as they were before the first plugin, so `unuse` can rebuild them */
4009
- let baseline;
4010
- function snapshot() {
4011
- const sets = [KNOWN_SETTINGS].map((s) => [s, [...s]]);
4012
- const maps = [
4013
- PANELS,
4014
- STATEMENTS,
4015
- SHAPE_KINDS,
4016
- MARKER_KINDS,
4017
- registry.frames
4018
- ].map((m) => [m, [...m]]);
4019
- const lists = [
4020
- TRANSFORMS,
4021
- AFTER_LAYOUT,
4022
- POST_RENDER,
4023
- NODE_PROPS,
4024
- EDGE_PROPS,
4025
- GROUP_PROPS,
4026
- BOOLS,
4027
- NUMBERS,
4028
- THEME_NAMES,
4029
- SHAPES,
4030
- registry.rows,
4031
- registry.decorations
4032
- ].map((l) => [l, [...l]]);
4033
- const enums = Object.entries(ENUMS).map(([k, v]) => [
4034
- k,
4035
- v,
4036
- [...v]
4037
- ]);
4038
- const themes = { ...THEMES };
4039
- const aliases = { ...SHAPE_ALIASES };
4040
- return () => {
4041
- for (const [s, v] of sets) {
4042
- s.clear();
4043
- for (const x of v) s.add(x);
4044
- }
4045
- for (const [m, v] of maps) {
4046
- m.clear();
4047
- for (const [k, x] of v) m.set(k, x);
4048
- }
4049
- for (const [l, v] of lists) l.splice(0, l.length, ...v);
4050
- for (const k of Object.keys(ENUMS)) delete ENUMS[k];
4051
- for (const [k, arr, v] of enums) {
4052
- arr.splice(0, arr.length, ...v);
4053
- ENUMS[k] = arr;
4054
- }
4055
- for (const k of Object.keys(THEMES)) delete THEMES[k];
4056
- Object.assign(THEMES, themes);
4057
- for (const k of Object.keys(SHAPE_ALIASES)) delete SHAPE_ALIASES[k];
4058
- Object.assign(SHAPE_ALIASES, aliases);
4059
- clearOwners();
4060
- };
4061
- }
4062
- /** `item` replaces the entry with the same name where it was (order matters for rows), or goes last */
4063
- function place(list, item, same) {
4064
- const at = list.findIndex(same);
4065
- if (at >= 0) list[at] = item;
4066
- else list.push(item);
4067
- }
4068
- /** Register plugins. Registering the same plugin name twice is a no-op. */
4069
- function use(...plugins) {
4070
- baseline ??= snapshot();
4071
- for (const p of plugins) {
4072
- if (registry.plugins.some((q) => q.name === p.name)) continue;
4073
- registry.plugins.push(p);
4074
- const w = guarded(p);
4075
- /** each item, under its name, into `into`: a map, or a function for more work */
4076
- const own = (what, items, key, into) => {
4077
- for (const x of items) {
4078
- const k = key(x);
4079
- claim(what, k, p.name);
4080
- if (typeof into === "function") into(x, k);
4081
- else into.set(k, x);
4082
- }
4083
- };
4084
- for (const t of p.themes ?? []) registerTheme(t);
4085
- own("row", w.rows, (r) => r.kind, (r, k) => place(registry.rows, r, (x) => x.kind === k));
4086
- own("decoration", w.decorations, (dec) => dec.name, (dec, k) => {
4087
- place(registry.decorations, dec, (x) => x.name === k);
4088
- KNOWN_SETTINGS.add(dec.setting);
4089
- });
4090
- own("frame", w.frames, (f) => f.name, registry.frames);
4091
- own("panel", w.panels, (pk) => pk.name, PANELS);
4092
- own("statement", w.statements, (st) => st.keyword, STATEMENTS);
4093
- own("marker", w.markers, (mk) => mk.name, MARKER_KINDS);
4094
- own("shape", w.shapes, (sh) => sh.name, (sh, k) => {
4095
- SHAPE_KINDS.set(k, sh);
4096
- if (!SHAPES.includes(k)) SHAPES.push(k);
4097
- for (const a of sh.aliases ?? []) SHAPE_ALIASES[a] = k;
4098
- });
4099
- addAll(ENUMS.shape ??= [], [...p.shapes?.map((x) => x.name) ?? [], ...p.shapes?.flatMap((x) => x.aliases ?? []) ?? []]);
4100
- addMarkers(ENUMS.head ??= [], p.markers);
4101
- if (ENUMS.tail !== ENUMS.head) addMarkers(ENUMS.tail ??= [], p.markers);
4102
- const { transform, afterLayout, postRender } = w.hooks;
4103
- if (transform) TRANSFORMS.push(transform);
4104
- if (afterLayout) AFTER_LAYOUT.push(afterLayout);
4105
- if (postRender) POST_RENDER.push(postRender);
4106
- for (const s of p.settings ?? []) KNOWN_SETTINGS.add(s);
4107
- addAll(NODE_PROPS, p.props?.node);
4108
- addAll(EDGE_PROPS, p.props?.edge);
4109
- addAll(GROUP_PROPS, p.props?.group);
4110
- for (const [k, v] of Object.entries(p.enums ?? {})) addAll(ENUMS[k] ??= [], v);
4111
- addAll(BOOLS, p.bools);
4112
- addAll(NUMBERS, p.numbers);
4113
- }
4114
- if (registry.frames.size) addAll(ENUMS.frame ??= [], [...registry.frames.keys()]);
4115
- }
4116
- /**
4117
- * Unregister a plugin by name: every table is rebuilt from the state before
4118
- * the first `use` and the other plugins are registered again, in order.
4119
- * Returns false when no plugin has that name.
4120
- */
4121
- function unuse(name) {
4122
- if (!baseline || !registry.plugins.some((p) => p.name === name)) return false;
4123
- const keep = registry.plugins.filter((p) => p.name !== name);
4124
- registry.plugins.length = 0;
4125
- baseline();
4126
- use(...keep);
4127
- return true;
4128
- }
4129
- // src/core/measure.ts
4130
- const NARROW = new Set("iljtfr.,;:'!|()[]{} \"`".split(""));
4131
- const WIDE = new Set("mwMW@%".split(""));
4132
- /** Font-independent width estimate, tuned for Inter / system UI fonts. */
4133
- const approxMeasure = (text, fontSize, weight, mono) => {
4134
- if (mono) return [...text].length * fontSize * .6;
4135
- let w = 0;
4136
- for (const ch of text) {
4137
- const cp = ch.codePointAt(0);
4138
- if (cp > 8192) w += cp > 126976 ? 1.2 : 1;
4139
- else if (NARROW.has(ch)) w += .3;
4140
- else if (WIDE.has(ch)) w += .86;
4141
- else if (ch >= "A" && ch <= "Z") w += .66;
4142
- else if (ch >= "0" && ch <= "9") w += .58;
4143
- else w += .54;
4144
- }
4145
- return w * fontSize * (weight >= 600 ? 1.05 : 1);
4146
- };
4147
- const MONO_STACK = "'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, Consolas, monospace";
4148
- let canvasCtx;
4149
- /** Accurate measurement using a canvas when running in a browser. */
4150
- function canvasMeasure(fontFamily) {
4151
- return (text, fontSize, weight, mono) => {
4152
- if (canvasCtx === void 0) try {
4153
- canvasCtx = typeof document !== "undefined" ? document.createElement("canvas").getContext("2d") : null;
4154
- } catch {
4155
- canvasCtx = null;
4156
- }
4157
- if (!canvasCtx) return approxMeasure(text, fontSize, weight, mono);
4158
- const family = mono && !/mono|courier|consolas|menlo/i.test(fontFamily) ? MONO_STACK : fontFamily;
4159
- canvasCtx.font = `${weight} ${fontSize}px ${family}`;
4160
- return canvasCtx.measureText(text).width;
4161
- };
4162
- }
4163
- // src/plugin.ts
4164
- /** `p` as it is, typed: no annotation needed for the kinds inside */
4165
- const definePlugin = (p) => p;
4166
- export { edgeWidthOf as $, table as $t, ENUMS as A, tspans as At, normalizeShape as B, createTheme as Bt, setLineProp as C, segsW as Ct, BOOLS as D, sumW as Dt, unquote as E, subInk as Et, PLACEMENT_PROPS as F, THEMES as Ft, sizeForShape as G, isSafeCss as Gt, rectPath as H, fontStack as Ht, lint as I, THEME_KEYS as It, POST_RENDER as J, ramp as Jt, textOffset as K, isSafeLink as Kt, placementOf as L, THEME_NAMES as Lt, NODE_PROPS as M, MONO as Mt, NUMBERS as N, RAMPS as Nt, COLORS as O, textEl as Ot, PANEL_PROPS as P, SANS as Pt, edgeFont as Q, collecting as Qt, propLine as R, TONES as Rt, serializeProps as S, richW as St, splitTrailingProps as T, splitWords as Tt, shapeDetail as U, getTheme as Ut, portOn as V, cssHex as Vt, shapePath as W, isColor as Wt, routeEdges as X, resolveColor as Xt, renderHead as Y, registerTheme as Yt, dashFor as Z, themeNames as Zt, onlyColor as _, parseInline as _t, perPass as a, resolveGroupStyle as at, propKey as b, renderSegs as bt, unuse as c, size as ct, PANELS as d, SPAN_KEYS as dt, effectiveProps as et, SETTING_VALUES as f, esc as ft, lex as g, nodeInk as gt, joinPath as h, lineHeight as ht, optionKind as i, posNum as it, GROUP_PROPS as j, COLOR_TOKEN as jt, EDGE_PROPS as k, textLines as kt, use as l, textFont as lt, isYuhwaPath as m, inkColor as mt, approxMeasure as n, num as nt, recolor as o, resolveNodeStyle as ot, blockBraces as p, f$1 as pt, AFTER_LAYOUT as q, isToneOrHex as qt, canvasMeasure as r, panelTheme as rt, registry as s, resolvePanelStyle as st, definePlugin as t, lineStyle as tt, KNOWN_SETTINGS as u, withEdgeInk as ut, parse as v, parseSpanStyle as vt, setTrailingProp as w, spanKey as wt, quote as x, richText as xt, parseProps as y, plain as yt, SHAPES as z, bool as zt };
3869
+ export { panelTheme as $, guard as $t, placementOf as A, SANS as At, textOffset as B, getTheme as Bt, ENUMS as C, sumW as Ct, PANEL_PROPS as D, COLOR_TOKEN as Dt, NUMBERS as E, tspans as Et, portOn as F, bool as Ft, renderHead as G, isToneOrHex as Gt, MARKER_KINDS as H, isGenericFont as Ht, rectPath as I, createTheme as It, edgeFont as J, resolveColor as Jt, routeEdges as K, ramp as Kt, shapeDetail as L, cssHex as Lt, SHAPES as M, THEME_KEYS as Mt, SHAPE_ALIASES as N, THEME_NAMES as Nt, PLACEMENT_PROPS as O, MONO as Ot, normalizeShape as P, TONES as Pt, num as Q, collecting as Qt, shapePath as R, fontFamilies as Rt, EDGE_PROPS as S, subInk as St, NODE_PROPS as T, textLines as Tt, POST_RENDER as U, isSafeCss as Ut, AFTER_LAYOUT as V, isColor as Vt, SHAPE_KINDS as W, isSafeLink as Wt, effectiveProps as X, claim as Xt, edgeWidthOf as Y, themeNames as Yt, lineStyle as Z, clearOwners as Zt, setTrailingProp as _, richText as _t, TRANSFORMS as a, textFont as at, BOOLS as b, spanKey as bt, joinPath as c, esc as ct, parse as d, lineHeight as dt, table as en, posNum as et, parseProps as f, nodeInk as ft, setLineProp as g, renderSegs as gt, serializeProps as h, plain as ht, STATEMENTS as i, size as it, propLine as j, THEMES as jt, lint as k, RAMPS as kt, lex as l, f as lt, quote as m, parseSpanStyle as mt, PANELS as n, resolveNodeStyle as nt, blockBraces as o, withEdgeInk as ot, propKey as p, parseInline as pt, dashFor as q, registerTheme as qt, SETTING_VALUES as r, resolvePanelStyle as rt, isYuhwaPath as s, SPAN_KEYS as st, KNOWN_SETTINGS as t, resolveGroupStyle as tt, onlyColor as u, inkColor as ut, splitTrailingProps as v, richW as vt, GROUP_PROPS as w, textEl as wt, COLORS as x, splitWords as xt, unquote as y, segsW as yt, sizeForShape as z, fontStack as zt };