@fengwk/kchart 0.1.0 → 0.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 (103) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +31 -2
  3. package/README.zh-CN.md +31 -2
  4. package/dist/esm/_virtual/_kchart-families.js +2 -1
  5. package/dist/esm/assets/themes/cloudmusic.js +1 -1
  6. package/dist/esm/chart/composition.js +7 -5
  7. package/dist/esm/chart/maps.js +9 -7
  8. package/dist/esm/chart/mindmap.js +19 -5
  9. package/dist/esm/chart/multivariate.js +99 -49
  10. package/dist/esm/chart/relations.js +15 -7
  11. package/dist/esm/chart/spec.js +11 -4
  12. package/dist/esm/core/context.js +29 -10
  13. package/dist/esm/core/scene.js +238 -21
  14. package/dist/esm/core/text.js +1 -1
  15. package/dist/esm/diagram/block.js +287 -295
  16. package/dist/esm/diagram/blocks.js +541 -605
  17. package/dist/esm/diagram/board-paint.js +594 -0
  18. package/dist/esm/diagram/board-route.js +60 -0
  19. package/dist/esm/diagram/c4.js +75 -35
  20. package/dist/esm/diagram/class.js +3 -2
  21. package/dist/esm/diagram/cynefin.js +55 -9
  22. package/dist/esm/diagram/eventmodeling.js +21 -10
  23. package/dist/esm/diagram/gantt.js +37 -15
  24. package/dist/esm/diagram/gitgraph.js +26 -5
  25. package/dist/esm/diagram/graph-layout.js +39 -2
  26. package/dist/esm/diagram/graph-route.js +296 -38
  27. package/dist/esm/diagram/info.js +32 -0
  28. package/dist/esm/diagram/journey.js +5 -5
  29. package/dist/esm/diagram/kanban.js +3 -3
  30. package/dist/esm/diagram/layers.js +9 -7
  31. package/dist/esm/diagram/mindmap.js +5 -1
  32. package/dist/esm/diagram/numeric-composition.js +24 -4
  33. package/dist/esm/diagram/numeric-model.js +1 -1
  34. package/dist/esm/diagram/numeric-radar.js +25 -7
  35. package/dist/esm/diagram/numeric-sankey.js +4 -3
  36. package/dist/esm/diagram/numeric-xy.js +14 -4
  37. package/dist/esm/diagram/packet.js +4 -4
  38. package/dist/esm/diagram/quadrant.js +12 -5
  39. package/dist/esm/diagram/railroad-parse.js +20 -10
  40. package/dist/esm/diagram/railroad.js +1 -1
  41. package/dist/esm/diagram/registry.js +46 -8
  42. package/dist/esm/diagram/sequence.js +43 -6
  43. package/dist/esm/diagram/swimlane.js +2 -2
  44. package/dist/esm/diagram/time.js +3 -3
  45. package/dist/esm/diagram/timeline.js +5 -5
  46. package/dist/esm/diagram/treeview.js +5 -3
  47. package/dist/esm/diagram/venn.js +117 -149
  48. package/dist/esm/diagram/wardley.js +61 -26
  49. package/dist/esm/diagram/zenuml.js +338 -0
  50. package/dist/esm/index.d.ts +3 -1
  51. package/dist/esm/mermaid.d.ts +1 -1
  52. package/dist/esm/mermaid.js +2 -1
  53. package/dist/esm/node.js +8 -2
  54. package/dist/esm/src/families.js +6 -1
  55. package/dist/units/chart/composition.js +1 -1
  56. package/dist/units/chart/maps.js +1 -1
  57. package/dist/units/chart/mindmap.js +1 -1
  58. package/dist/units/chart/multivariate.js +1 -1
  59. package/dist/units/chart/relations.js +1 -1
  60. package/dist/units/chart/spec.js +1 -1
  61. package/dist/units/core/context.js +1 -1
  62. package/dist/units/core/scene.js +1 -1
  63. package/dist/units/core/text.js +1 -1
  64. package/dist/units/core/theme.js +1 -1
  65. package/dist/units/diagram/block.js +2 -2
  66. package/dist/units/diagram/blocks.js +2 -2
  67. package/dist/units/diagram/board-paint.js +1 -0
  68. package/dist/units/diagram/board-route.js +1 -0
  69. package/dist/units/diagram/c4.js +1 -1
  70. package/dist/units/diagram/class.js +2 -2
  71. package/dist/units/diagram/cynefin.js +2 -2
  72. package/dist/units/diagram/eventmodeling.js +4 -4
  73. package/dist/units/diagram/gantt.js +3 -3
  74. package/dist/units/diagram/gitgraph.js +2 -1
  75. package/dist/units/diagram/graph-layout.js +1 -1
  76. package/dist/units/diagram/graph-route.js +1 -1
  77. package/dist/units/diagram/info.js +2 -0
  78. package/dist/units/diagram/journey.js +3 -3
  79. package/dist/units/diagram/kanban.js +1 -1
  80. package/dist/units/diagram/layers.js +1 -1
  81. package/dist/units/diagram/mindmap.js +1 -1
  82. package/dist/units/diagram/numeric-composition.js +1 -1
  83. package/dist/units/diagram/numeric-model.js +1 -1
  84. package/dist/units/diagram/numeric-radar.js +2 -2
  85. package/dist/units/diagram/numeric-sankey.js +1 -1
  86. package/dist/units/diagram/numeric-xy.js +1 -1
  87. package/dist/units/diagram/packet.js +1 -1
  88. package/dist/units/diagram/quadrant.js +1 -1
  89. package/dist/units/diagram/railroad-parse.js +2 -2
  90. package/dist/units/diagram/railroad.js +1 -1
  91. package/dist/units/diagram/registry.js +2 -2
  92. package/dist/units/diagram/sequence.js +1 -1
  93. package/dist/units/diagram/swimlane.js +2 -2
  94. package/dist/units/diagram/time.js +1 -1
  95. package/dist/units/diagram/timeline.js +1 -1
  96. package/dist/units/diagram/treeview.js +1 -1
  97. package/dist/units/diagram/venn.js +2 -2
  98. package/dist/units/diagram/wardley.js +4 -4
  99. package/dist/units/diagram/zenuml.js +2 -0
  100. package/dist/units.json +82 -52
  101. package/package.json +1 -1
  102. package/dist/esm/diagram/relations.js +0 -966
  103. package/dist/units/diagram/relations.js +0 -3
@@ -70,15 +70,15 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
70
70
  const normalize = mapLabels(lang, (item) => errors.push(item));
71
71
  const readLabel = (value, line) => normalize(readName(value), line);
72
72
  if (title) ({text: model.title, icon: model.titleIcon} = normalize(title, headerLine));
73
- const bad = (line, zh, en) => errors.push(error(lang, line, zh, en, "检查 Wardley 地图语法", "Check Wardley map syntax"));
74
- const hint = (key, line, zh, en) => {
73
+ const bad = (line, zh, en, fixZh, fixEn) => errors.push(error(lang, line, zh, en, fixZh, fixEn));
74
+ const hint = (key, line, zh, en, fixZh, fixEn) => {
75
75
  if (hints.has(key)) return;
76
76
  hints.add(key);
77
- errors.push(warning("DIAGRAM_HINT", lang, line, zh, en));
77
+ errors.push(warning("DIAGRAM_HINT", lang, line, zh, en, fixZh, fixEn));
78
78
  };
79
79
  const percent = (raw, line) => {
80
80
  const value = Number(raw);
81
- if (value > 100) bad(line, "坐标超出 0–100 范围", "Coordinate is outside 0–100");
81
+ if (value > 100) bad(line, "坐标超出 0–100 范围", "Coordinate is outside 0–100", "使用 0.0–1.0 的比例或 0.0–100.0 的百分数,例如 0.3", "Use a decimal fraction from 0.0 to 1.0 or a percentage up to 100.0, such as 0.3");
82
82
  return value <= 1 ? value * 100 : value;
83
83
  };
84
84
  const coords = (v, e, line) => ({
@@ -92,14 +92,14 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
92
92
  const add = (node) => {
93
93
  const previous = nodes.get(node.id);
94
94
  if (previous) {
95
- if (previous.visibility !== node.visibility || previous.evolution !== node.evolution) bad(node.line, `「${node.id}」有不同的坐标`, `Conflicting coordinates for "${node.id}"`);
95
+ if (previous.visibility !== node.visibility || previous.evolution !== node.evolution) bad(node.line, `「${node.id}」有不同的坐标`, `Conflicting coordinates for "${node.id}"`, "保留一处声明,或给不同的节点使用不同的名称", "Keep one declaration or give distinct nodes different names");
96
96
  return;
97
97
  }
98
98
  nodes.set(node.id, node);
99
99
  model.nodes.push(node);
100
100
  };
101
101
  if (body.length > 2e5) {
102
- bad(firstLine, "地图源文本过长", "Map source exceeds 200,000 characters");
102
+ bad(firstLine, "地图源文本过长", "Map source exceeds 200,000 characters", "拆成多张地图,每张最多 200,000 个字符", "Split into maps of at most 200,000 characters each");
103
103
  return {
104
104
  model,
105
105
  errors
@@ -114,7 +114,7 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
114
114
  let m;
115
115
  if (pipeline) {
116
116
  if (text === "}") {
117
- if (!pipeline.children.length) bad(line, "演进管道没有组件", "Pipeline needs at least one component");
117
+ if (!pipeline.children.length) bad(line, "演进管道没有组件", "Pipeline needs at least one component", "在 } 前添加组件,例如 component Child [0.4]", "Add a component before }, for example component Child [0.4]");
118
118
  pipeline = null;
119
119
  } else if (m = childPattern.exec(text)) {
120
120
  const [, name, evo, dx, dy] = m, { text: label, icon } = readLabel(name, line);
@@ -129,7 +129,7 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
129
129
  parent: pipeline.parent,
130
130
  line
131
131
  });
132
- } else bad(line, "无效的演进管道组件", "Invalid pipeline component");
132
+ } else bad(line, "无效的演进管道组件", "Invalid pipeline component", "管道内只填写演进坐标,例如 component Child [0.4]", "Use one evolution coordinate inside a pipeline, as in component Child [0.4]");
133
133
  continue;
134
134
  }
135
135
  if (accessibility) {
@@ -145,13 +145,13 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
145
145
  width: Number(m[1]),
146
146
  height: Number(m[2])
147
147
  };
148
- if (Object.values(model.size).some((n) => n > 16e3)) bad(line, "地图尺寸超过 16000 像素", "Map size exceeds 16,000 pixels");
148
+ if (Object.values(model.size).some((n) => n > 16e3)) bad(line, "地图尺寸超过 16000 像素", "Map size exceeds 16,000 pixels", "减小 size [宽, 高],两项均不得超过 16000", "Reduce both dimensions in size [width, height] to at most 16000");
149
149
  } else if (text.startsWith("evolution ")) {
150
150
  const parts = text.slice(10).match(/"(?:\\.|[^"\\])*"|->|[^"-]+|-/g) || [];
151
151
  const stages = [""];
152
152
  for (const part of parts) part === "->" ? stages.push("") : stages[stages.length - 1] += part;
153
153
  const matches = stages.map((stage) => stagePattern.exec(stage.trim()));
154
- if (matches.length < 2 || matches.some((match) => !match)) bad(line, "无效的演进阶段", "Invalid evolution stages");
154
+ if (matches.length < 2 || matches.some((match) => !match)) bad(line, "无效的演进阶段", "Invalid evolution stages", "用 -> 分隔至少两个阶段,例如 evolution Genesis -> Product", "Separate at least two stages with ->, as in evolution Genesis -> Product");
155
155
  else {
156
156
  model.stages = matches.map(([, name, end, second]) => {
157
157
  const primary = readLabel(name, line), secondary = second ? readLabel(second, line) : null;
@@ -165,14 +165,14 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
165
165
  });
166
166
  const ends = model.stages.map((stage) => stage.boundary);
167
167
  if (ends.some((end) => end !== null) && (ends.some((end, i) => end === null || end <= (ends[i - 1] ?? 0)) || ends.at(-1) !== 100)) {
168
- hint("stages", line, "阶段边界不完整或未递增至 100;使用等宽阶段", "Incomplete or unordered stage boundaries; using equal bands");
168
+ hint("stages", line, "阶段边界不完整或未递增至 100;使用等宽阶段", "Incomplete or unordered stage boundaries; using equal bands", "为每个阶段写递增边界,例如 evolution Genesis @ 0.4 -> Product @ 1.0", "Give each stage an increasing boundary, as in evolution Genesis @ 0.4 -> Product @ 1.0");
169
169
  for (const stage of model.stages) stage.boundary = null;
170
170
  }
171
171
  }
172
172
  } else if (m = nodePattern.exec(text)) {
173
173
  const [, kind, name, vis, evo, dx, dy, strategy, inertia] = m;
174
174
  const { text: label, icon } = readLabel(name, line), point = coords(vis, evo, line);
175
- if (kind !== "component" && (dx != null || strategy || inertia) || kind === "note" && !name.startsWith("\"")) bad(line, "无效的装饰或备注", "Invalid decorator or note");
175
+ if (kind !== "component" && (dx != null || strategy || inertia) || kind === "note" && !name.startsWith("\"")) bad(line, "无效的装饰或备注", "Invalid decorator or note", "只给 component 添加装饰;备注使用 note \"文字\" [0.3, 0.2]", "Apply decorators only to component; write notes as note \"Text\" [0.3, 0.2]");
176
176
  else if (kind === "note") model.notes.push({
177
177
  text: label,
178
178
  icon,
@@ -216,7 +216,7 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
216
216
  line
217
217
  });
218
218
  else if (m = boxPattern.exec(text)) {
219
- if (model.annotationBox) hint("box", line, "只使用第一个注释框", "Only the first annotation box is used");
219
+ if (model.annotationBox) hint("box", line, "只使用第一个注释框", "Only the first annotation box is used", "只保留一条 annotations [x, y] 语句", "Keep only one annotations [x, y] statement");
220
220
  else model.annotationBox = coords(m[1], m[2], line);
221
221
  } else if ((m = linkPattern.exec(text)) && (m[2] || m[3] || m[7] || m[8] || m[1].startsWith("\"") || m[6].startsWith("\""))) {
222
222
  const [, from, sourcePort, arrow, flowLabel, arrowPort, to, targetPort, label] = m;
@@ -240,10 +240,10 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
240
240
  line
241
241
  });
242
242
  }
243
- if (pipeline) bad(pipeline.line, "演进管道缺少结束括号", "Unclosed pipeline");
243
+ if (pipeline) bad(pipeline.line, "演进管道缺少结束括号", "Unclosed pipeline", "在管道的最后一个组件之后单独写一行 }", "Add } on its own line after the last pipeline component");
244
244
  for (const group of model.pipelines) {
245
245
  const parent = nodes.get(group.parent);
246
- if (parent?.kind !== "component") bad(group.line, `管道父级「${group.parent}」不是组件`, `Pipeline parent "${group.parent}" is not a component`);
246
+ if (parent?.kind !== "component") bad(group.line, `管道父级「${group.parent}」不是组件`, `Pipeline parent "${group.parent}" is not a component`, "先声明同名 component,例如 component Parent [0.3, 0.2]", "Declare a component with the same name, as in component Parent [0.3, 0.2]");
247
247
  else for (const child of group.children) add({
248
248
  ...child,
249
249
  visibility: parent.visibility
@@ -269,19 +269,20 @@ function parse(body, { lang, firstLine = 2, title = "", headerLine = 1 } = {}) {
269
269
  label: "",
270
270
  line
271
271
  });
272
- else bad(line, "无法识别 Wardley 地图语句", "Unrecognized Wardley map statement");
272
+ else bad(line, "无法识别 Wardley 地图语句", "Unrecognized Wardley map statement", "用 component \"需求\" [0.3, 0.2] 声明组件;连线使用 \"需求\" --> \"网关\",名称外不要加方括号", "Declare components as component \"Demand\" [0.3, 0.2]; link them as \"Demand\" --> \"Gateway\" without square brackets around names");
273
273
  }
274
274
  model.links.sort((a, b) => a.line - b.line);
275
275
  for (const link of model.links) {
276
276
  link.from = resolve(link.from);
277
277
  link.to = resolve(link.to);
278
- if (!nodes.has(link.from) || !nodes.has(link.to)) bad(link.line, "依赖引用未定义的节点", "Dependency references an undefined node");
278
+ const missing = [link.from, link.to].find((id) => !nodes.has(id));
279
+ if (missing !== void 0) bad(link.line, `依赖引用未定义的节点「${missing}」`, `Dependency references undefined node "${missing}"`, "声明同名组件,例如 component Gateway [0.4, 0.3],或更正连线端点名称", "Declare a matching component, as in component Gateway [0.4, 0.3], or correct the endpoint name");
279
280
  }
280
281
  for (const trend of model.trends) {
281
282
  trend.nodeId = resolve(trend.nodeId);
282
- if (!nodes.has(trend.nodeId)) hint("trend", trend.line, "演进引用未定义的组件", "Evolution references an undefined component");
283
+ if (!nodes.has(trend.nodeId)) hint("trend", trend.line, "演进引用未定义的组件", "Evolution references an undefined component", "将 evolve 后的名称改为已声明的组件,例如 evolve Gateway 0.7", "Use a declared component name after evolve, as in evolve Gateway 0.7");
283
284
  }
284
- if (model.nodes.length > 300 || model.links.length + model.trends.length > 600) bad(firstLine, "地图超过 300 个节点或 600 条连线,请拆分", "Split maps exceeding 300 nodes or 600 connections");
285
+ if (model.nodes.length > 300 || model.links.length + model.trends.length > 600) bad(firstLine, "地图超过 300 个节点或 600 条连线,请拆分", "Map exceeds 300 nodes or 600 connections", "按主题拆分地图,每张最多 300 个节点、600 条连线", "Split the map by topic into maps of at most 300 nodes and 600 connections");
285
286
  return {
286
287
  model,
287
288
  errors
@@ -344,8 +345,12 @@ var arrowhead = (ctx, a, b, fill) => {
344
345
  const p = move(b, a, 7), dx = p.y - b.y, dy = b.x - p.x;
345
346
  return ctx.path(`M${b.x} ${b.y} L${p.x + dx * .48} ${p.y + dy * .48} L${p.x - dx * .48} ${p.y - dy * .48} Z`, { fill });
346
347
  };
347
- function layout(model, { width, lang, ctx }, info = {}) {
348
+ function layout(model, { width, lang, ctx, compact = false, embedHeading }, info = {}) {
348
349
  const t = appearance(ctx), edge = ctx.color("muted"), grid = ctx.color("grid"), axis = t.fg4;
350
+ const titleFont = compact ? {
351
+ ...FONT.title,
352
+ size: 13
353
+ } : FONT.title;
349
354
  const config = mapConfig(info.config, "wardley");
350
355
  const pad = 48;
351
356
  const stageParts = model.stages.map((stage) => [{
@@ -364,7 +369,8 @@ function layout(model, { width, lang, ctx }, info = {}) {
364
369
  const bandFraction = (i) => fractions[i] - (fractions[i - 1] || 0);
365
370
  const stageWidth = Math.max(...stageParts.map((rows, i) => (Math.max(...rows.map(stageInkWidth)) + 22) / bandFraction(i)));
366
371
  const dimension = (value, fallback) => typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.min(16e3, value)) : fallback;
367
- const W = Math.max(96 + stageWidth, 420, dimension(model.size?.width ?? mapConfig(config, "width"), 900));
372
+ const compactWidth = Math.max(96 + stageWidth, Math.min(720, 540 + model.nodes.length * 4 + model.links.length * 2));
373
+ const W = compact ? compactWidth : Math.max(96 + stageWidth, 420, dimension(model.size?.width ?? mapConfig(config, "width"), 900));
368
374
  const right = W - pad, plotW = right - pad;
369
375
  const stages = stageParts.map((parts, i) => {
370
376
  if (parts.length !== 2 || model.stages[i].secondName === null || [model.stages[i].name, model.stages[i].secondName].some((text) => text.includes("\n"))) return parts;
@@ -374,10 +380,11 @@ function layout(model, { width, lang, ctx }, info = {}) {
374
380
  };
375
381
  return stageInkWidth(together) + 22 <= plotW * bandFraction(i) ? [together] : parts;
376
382
  });
377
- const titleRows = model.title || model.titleIcon ? ctx.wrap(model.title, plotW - iconGap(model.titleIcon), FONT.title.size, FONT.title.weight) : [];
383
+ const titleRows = !embedHeading && (model.title || model.titleIcon) ? ctx.wrap(model.title, plotW - iconGap(model.titleIcon), titleFont.size, titleFont.weight) : [];
378
384
  const top = 48 + Math.max(0, titleRows.length - 1) * 16;
379
385
  const stagesExtra = Math.max(0, ...stages.map((rows) => rows.length - 2)) * 16;
380
- const H = Math.max(top + 212 + stagesExtra, dimension(model.size?.height ?? mapConfig(config, "height"), 600));
386
+ const compactHeight = Math.max(top + 212 + stagesExtra, Math.min(540, 400 + model.nodes.length * 2 + model.links.length));
387
+ const H = compact ? compactHeight : Math.max(top + 212 + stagesExtra, dimension(model.size?.height ?? mapConfig(config, "height"), 600));
381
388
  const bottom = H - 86 - stagesExtra, plotH = bottom - top;
382
389
  const project = ({ evolution, visibility }) => ({
383
390
  x: pad + plotW * evolution / 100,
@@ -547,7 +554,34 @@ function layout(model, { width, lang, ctx }, info = {}) {
547
554
  const b = grow(centerBox(x, y, w, h), clearance);
548
555
  return b.x > 31 && b.x + b.w < W - 8 && b.y > top - 20 && b.y + b.h < bottom + 9 && !obstacles.some((o) => collides(b, o)) && !occupied.some((o) => collides(b, o)) && !wires.some(([a, z]) => crosses(a, z, b));
549
556
  };
550
- let chosen = fixed || candidates.find(fits);
557
+ let chosen = fixed && compact && (() => {
558
+ const offsets = [
559
+ [0, 0],
560
+ [0, -1],
561
+ [1, 0],
562
+ [-1, 0],
563
+ [0, 1],
564
+ [1, -1],
565
+ [-1, -1],
566
+ [1, 1],
567
+ [-1, 1]
568
+ ];
569
+ const alternatives = [fixed];
570
+ for (const distance of [
571
+ 12,
572
+ 24,
573
+ 36,
574
+ 52,
575
+ 72
576
+ ]) for (const [dx, dy] of offsets.slice(1)) alternatives.push({
577
+ x: fixed.x + dx * distance,
578
+ y: fixed.y + dy * distance
579
+ });
580
+ return alternatives.find(({ x, y }) => {
581
+ const b = grow(centerBox(x, y, w, h), clearance);
582
+ return b.x > 31 && b.x + b.w < W - 8 && b.y > top - 20 && b.y + b.h < bottom + 9 && !obstacles.some((o) => collides(b, o)) && !occupied.some((o) => collides(b, o));
583
+ });
584
+ })() || fixed || candidates.find(fits);
551
585
  const leader = !fixed && chosen && leaderFor(chosen);
552
586
  if (leader) addLeader(...leader);
553
587
  if (!chosen) {
@@ -628,7 +662,7 @@ function layout(model, { width, lang, ctx }, info = {}) {
628
662
  y: a.y
629
663
  }, {}, true);
630
664
  }
631
- if (titleRows.length) guides.push(caption(W / 2, 23 + (titleRows.length - 1) * 8, titleRows, model.titleIcon, FONT.title));
665
+ if (titleRows.length) guides.push(caption(W / 2, 23 + (titleRows.length - 1) * 8, titleRows, model.titleIcon, titleFont));
632
666
  guides.push(ctx.line(pad, top, pad, bottom, stroke(axis)), ctx.line(pad, bottom, right, bottom, stroke(axis)));
633
667
  const axisMiddle = (top + bottom) / 2;
634
668
  guides.push(ctx.el("g", { transform: `rotate(-90 18 ${axisMiddle})` }, [label(18, axisMiddle, [word(lang, "visibility")], bold, t.fg2)]));
@@ -812,12 +846,13 @@ function layout(model, { width, lang, ctx }, info = {}) {
812
846
  labels.push(label(pad, footerY + rows.length * 8, rows, FONT.label, t.fg2, "start"));
813
847
  footerY += rows.length * 16 + 8;
814
848
  }
815
- const errors = W > width * 2 || nodes.size > 60 ? [warning("LARGE_DIAGRAM", lang, info.headerLine || 1, "地图较大,可拆成多张地图", "Large map; consider splitting it into smaller maps")] : [];
849
+ const errors = W > width * 2 || nodes.size > 60 ? [warning("LARGE_DIAGRAM", lang, info.headerLine || 1, "地图较大,可在图框内滚动", "Large map; scroll inside the frame", "按主题拆分组件及其依赖", "Split components and their dependencies into maps by topic")] : [];
816
850
  return {
817
851
  scene: {
818
852
  width: W,
819
853
  height: footerY + 8,
820
854
  title: model.title || void 0,
855
+ ...embedHeading ? { heading: model.title } : {},
821
856
  children: [
822
857
  ...guides,
823
858
  ...frames,
@@ -0,0 +1,338 @@
1
+ import { __exportAll } from "../_virtual/_rolldown/runtime.js";
2
+ import { error, warning } from "./support.js";
3
+ import { stripEmphasis } from "./emphasis.js";
4
+ import { LIMITS, implementations as implementations$1 } from "./sequence.js";
5
+ // src/diagram/zenuml.js
6
+ var zenuml_exports = /* @__PURE__ */ __exportAll({ implementations: () => implementations });
7
+ var ID = "[\\p{L}\\p{N}_$][\\p{L}\\p{N}_$-]*";
8
+ var participant = new RegExp(`^(?:@(\\w+)\\s+)?(${ID})(?:\\s+as\\s+(.+))?$`, "u");
9
+ var annotationCall = new RegExp(`^@(\\w+)\\s*\\(\\s*(${ID})\\s*\\)$`, "u");
10
+ var asyncMessage = new RegExp(`^(${ID}?)\\s*(-->>|-->|->>|->|<<--|<--|<-|==>|=>|\\.\\.>)\\s*(${ID})\\s*:\\s*(.*)$`, "u");
11
+ var call = new RegExp(`^(?:(?:[\\w.$<>\\[\\]]+\\s+)?(${ID})\\s*=\\s*)?(?:(${ID}?)\\s*->\\s*)?(${ID})\\.(${ID})(?:\\s*\\((.*)\\))?$`, "u");
12
+ var creation = new RegExp(`^new\\s+(${ID})(?:\\s*\\((.*)\\))?$`, "u");
13
+ var fragments = /^(while|for|foreach|loop|if|opt|par|try|else\s+if|else|catch|finally)\s*(?:\((.*)\))?$/iu;
14
+ var kinds = /* @__PURE__ */ new Set([
15
+ "actor",
16
+ "boundary",
17
+ "control",
18
+ "entity",
19
+ "database",
20
+ "collections",
21
+ "queue",
22
+ "participant"
23
+ ]);
24
+ var STARTER = ":starter";
25
+ var MAX_LINES = 240;
26
+ var MAX_PARTICIPANTS = 40;
27
+ function tokenize(lines, firstLine) {
28
+ const tokens = [];
29
+ for (const [index, raw] of lines.entries()) {
30
+ const line = firstLine + index, text = raw.trim();
31
+ let start = 0, quote = "", depth = 0;
32
+ const push = (value) => {
33
+ if (value.trim()) tokens.push({
34
+ text: value.trim(),
35
+ line
36
+ });
37
+ };
38
+ if (/^title\s/i.test(text)) {
39
+ push(text);
40
+ continue;
41
+ }
42
+ for (let i = 0; i < text.length; i++) {
43
+ const ch = text[i];
44
+ if (quote) {
45
+ if (ch === "\\") i++;
46
+ else if (ch === quote) quote = "";
47
+ } else if (ch === "\"" || ch === "'" && depth) quote = ch;
48
+ else if (ch === "(") depth++;
49
+ else if (ch === ")") depth = Math.max(0, depth - 1);
50
+ else if (!depth) {
51
+ if (ch === ":") break;
52
+ if (ch === "/" && text[i + 1] === "/") {
53
+ push(text.slice(start, i));
54
+ push(text.slice(i));
55
+ start = text.length;
56
+ break;
57
+ }
58
+ if ("{};".includes(ch)) {
59
+ push(text.slice(start, i));
60
+ if (ch !== ";") push(ch);
61
+ start = i + 1;
62
+ }
63
+ }
64
+ }
65
+ push(text.slice(start));
66
+ }
67
+ return tokens;
68
+ }
69
+ function parse(source, info) {
70
+ const { lang = "zh", firstLine = 2 } = info;
71
+ const actors = /* @__PURE__ */ new Map(), statements = [], errors = [], stack = [], ignored = /* @__PURE__ */ new Set();
72
+ let title = info.title || "", comments = [], replyLine, ignoredLine, messages = 0;
73
+ const bad = (line, zh, en, fixZh, fixEn) => errors.push(error(lang, line, zh, en, fixZh, fixEn));
74
+ const unrecognized = (line, text) => bad(line, `无法识别 ZenUML 语句:「${text}」`, `Unrecognized ZenUML statement: "${text}"`, "例如:@Actor Client、Client->API: 请求 或 API.call()", "For example: @Actor Client, Client->API: request, or API.call()");
75
+ const touch = (id, line) => {
76
+ if (!actors.has(id)) actors.set(id, {
77
+ id,
78
+ name: id === STARTER ? "" : id,
79
+ kind: id === STARTER ? "actor" : "participant",
80
+ line
81
+ });
82
+ return actors.get(id);
83
+ };
84
+ const caller = () => stack.findLast((item) => item.call);
85
+ const beginUnit = (line) => {
86
+ const parent = stack.at(-1);
87
+ if (parent?.keyword === "par" && parent.units++) {
88
+ const section = {
89
+ type: "section",
90
+ keyword: "",
91
+ line
92
+ };
93
+ parent.event.sections.push(section);
94
+ statements.push(section);
95
+ }
96
+ };
97
+ const addComment = (from, to, line) => {
98
+ const text = stripEmphasis(comments.join("\n"));
99
+ if (text) statements.push({
100
+ type: "note",
101
+ place: "over",
102
+ ids: from === to ? [from] : [from, to],
103
+ text,
104
+ line
105
+ });
106
+ comments = [];
107
+ };
108
+ const send = (from, to, text, line, extra = {}) => {
109
+ touch(from, line).used = true;
110
+ touch(to, line).used = true;
111
+ messages++;
112
+ statements.push({
113
+ type: "message",
114
+ from,
115
+ to,
116
+ text,
117
+ line,
118
+ arrow: {
119
+ head: "open",
120
+ dashed: false
121
+ },
122
+ ...extra
123
+ });
124
+ };
125
+ const reply = (from, to, text, line) => send(from, to, text, line, { arrow: {
126
+ head: "open",
127
+ dashed: true
128
+ } });
129
+ const finishCall = (entry, line) => {
130
+ if (entry.assignment) reply(entry.to, entry.from, entry.assignment, line);
131
+ statements.push({
132
+ type: "deactivate",
133
+ id: entry.to,
134
+ line
135
+ });
136
+ };
137
+ const missingBlock = (line) => bad(line, "ZenUML 语句缺少花括号块", "ZenUML statement is missing a brace block", "在语句后添加 { … }", "Add { … } after the statement");
138
+ const missingReply = (line) => bad(line, "回复注解后缺少消息", "Expected a message after the reply annotation", "写成 @return A->B: 结果", "Write @return A->B: result");
139
+ for (const key of Object.keys(info.options || {})) bad(firstLine - 1, `ZenUML 头行不接受选项「${key}」`, `The ZenUML header does not accept option "${key}"`, "头行只保留 zenuml", "Use only zenuml on the header line");
140
+ const lines = String(source).split(/\r\n?|\n/u);
141
+ if (lines.length > MAX_LINES) bad(firstLine + MAX_LINES, `ZenUML 正文超过 ${MAX_LINES} 行`, `ZenUML body exceeds ${MAX_LINES} lines`, "拆分为多张图", "Split into several diagrams");
142
+ const tokens = tokenize(lines.slice(0, MAX_LINES), firstLine);
143
+ for (let i = 0; i < tokens.length; i++) {
144
+ const { text, line } = tokens[i];
145
+ if (text.startsWith("//")) {
146
+ comments.push(text.slice(2).trim());
147
+ continue;
148
+ }
149
+ let syntax = text;
150
+ const annotation = /^@(?:return|reply)(?:\s+(.*))?$/iu.exec(text);
151
+ if (annotation) {
152
+ if (replyLine) missingReply(replyLine);
153
+ replyLine = line;
154
+ if (!annotation[1]) continue;
155
+ syntax = annotation[1];
156
+ }
157
+ let match = asyncMessage.exec(syntax);
158
+ const isReply = Boolean(replyLine);
159
+ if (replyLine && !match) missingReply(replyLine);
160
+ replyLine = void 0;
161
+ if (match) {
162
+ const [, from, operator, to, label] = match;
163
+ if (operator !== "->") {
164
+ const example = `${from}->${to}: ${label}`;
165
+ bad(line, `ZenUML 消息箭头写法无效:「${operator}」`, `Invalid ZenUML message arrow "${operator}"`, `异步消息用 ${example};回复用 @return ${example} 或调用块内的 return`, `For an async message use ${example}; for a reply use @return ${example} or return inside a call block`);
166
+ } else {
167
+ beginUnit(line);
168
+ addComment(from, to, line);
169
+ if (isReply) reply(from, to, label, line);
170
+ else send(from, to, label, line);
171
+ }
172
+ } else if (syntax === "}") {
173
+ const entry = stack.at(-1);
174
+ if (!entry) bad(line, "ZenUML 多余的 }", "Unexpected } in ZenUML", "删除多余的 }", "Remove the unmatched }");
175
+ else if (entry.call) {
176
+ stack.pop();
177
+ finishCall(entry, line);
178
+ } else {
179
+ const next = tokens.slice(i + 1).find((token) => !token.text.startsWith("//"));
180
+ const branch = next && fragments.exec(next.text)?.[1].toLowerCase().replace(/\s+/g, " ");
181
+ if (entry.keyword === "if" && entry.branch !== "else" && (branch === "else" || branch === "else if") || entry.keyword === "try" && entry.branch !== "finally" && (branch === "catch" || branch === "finally")) entry.awaitingBranch = true;
182
+ else {
183
+ stack.pop();
184
+ statements.push({
185
+ type: "end",
186
+ line
187
+ });
188
+ }
189
+ }
190
+ } else if (match = fragments.exec(syntax)) {
191
+ const keyword = match[1].toLowerCase().replace(/\s+/g, " "), label = match[2]?.trim() || "";
192
+ const parent = stack.at(-1);
193
+ const branch = /^(else|catch|finally)/u.test(keyword);
194
+ if (tokens[i + 1]?.text !== "{") missingBlock(line);
195
+ else if (branch && !parent?.awaitingBranch) unrecognized(line, syntax);
196
+ else if (stack.length >= LIMITS.fragmentDepth && !branch) bad(line, "ZenUML 块嵌套过深", "ZenUML blocks are nested too deeply", "减少块的嵌套层数", "Reduce block nesting");
197
+ else {
198
+ i++;
199
+ if (branch) {
200
+ const section = {
201
+ type: "section",
202
+ keyword,
203
+ text: label,
204
+ line
205
+ };
206
+ parent.event.sections.push(section);
207
+ statements.push(section);
208
+ Object.assign(parent, {
209
+ branch: keyword,
210
+ awaitingBranch: false
211
+ });
212
+ } else {
213
+ beginUnit(line);
214
+ const event = {
215
+ type: "fragment",
216
+ keyword: keyword === "if" ? "alt" : /^(while|for|foreach)$/u.test(keyword) ? "loop" : keyword,
217
+ text: label,
218
+ sections: [],
219
+ line
220
+ };
221
+ statements.push(event);
222
+ stack.push({
223
+ event,
224
+ keyword,
225
+ line,
226
+ units: 0
227
+ });
228
+ }
229
+ }
230
+ } else if (match = /^return(?:\s+(.*))?$/u.exec(syntax)) {
231
+ const entry = caller();
232
+ if (!entry) bad(line, "return 应放在 ZenUML 同步调用块内", "Put return inside a ZenUML synchronous call block", "在调用的 { … } 内使用 return,或用 @return A->B: 结果", "Use return inside the call’s { … }, or use @return A->B: result");
233
+ else {
234
+ beginUnit(line);
235
+ addComment(entry.to, entry.from, line);
236
+ reply(entry.to, entry.from, match[1] || "", line);
237
+ }
238
+ } else if (match = creation.exec(syntax)) {
239
+ const [, to, args] = match, from = caller()?.to || STARTER;
240
+ if (touch(to, line).used || from === to) bad(line, `应在首次使用「${to}」前创建它`, `Create "${to}" before its first message`, "将 new 移到该参与者的其他消息前", "Move new before other messages involving this participant");
241
+ else {
242
+ beginUnit(line);
243
+ addComment(from, to, line);
244
+ send(from, to, args?.trim() ? `«${args.trim()}»` : "«create»", line, {
245
+ create: to,
246
+ activateOn: to,
247
+ arrow: {
248
+ head: "open",
249
+ dashed: true
250
+ }
251
+ });
252
+ finishCall({ to }, line);
253
+ }
254
+ } else if (match = call.exec(syntax)) {
255
+ const [, assignment, explicit, to, method, args] = match, from = explicit || caller()?.to || STARTER;
256
+ beginUnit(line);
257
+ addComment(from, to, line);
258
+ send(from, to, args === void 0 ? method : `${method}(${args})`, line, {
259
+ activateOn: to,
260
+ arrow: {
261
+ head: "arrow",
262
+ dashed: false
263
+ }
264
+ });
265
+ const entry = {
266
+ call: true,
267
+ from,
268
+ to,
269
+ assignment,
270
+ line
271
+ };
272
+ if (tokens[i + 1]?.text !== "{") finishCall(entry, line);
273
+ else if (stack.length >= LIMITS.fragmentDepth) bad(line, "ZenUML 块嵌套过深", "ZenUML blocks are nested too deeply", "减少块的嵌套层数", "Reduce block nesting");
274
+ else {
275
+ i++;
276
+ stack.push(entry);
277
+ }
278
+ } else if (match = /^title\s+(.+)$/iu.exec(syntax)) {
279
+ if (title) bad(line, "ZenUML 标题重复", "Duplicate ZenUML title", "只保留一个 title 或前置元数据标题", "Keep one title statement or front-matter title");
280
+ else title = match[1];
281
+ } else if (/^@(?:startuml|enduml)$/iu.test(syntax)) {} else if (match = annotationCall.exec(syntax)) {
282
+ const form = `@${match[1]} ${match[2]}`;
283
+ bad(line, `ZenUML 参与者注解写法无效:「${syntax}」`, `Invalid ZenUML participant annotation "${syntax}"`, `去掉括号,写成 ${form}`, `Remove the parentheses: ${form}`);
284
+ } else if (match = participant.exec(syntax)) {
285
+ const [, type, id, name] = match, actor = touch(id, line);
286
+ const kind = type?.toLowerCase() || "participant";
287
+ if (actor.declared) bad(line, `ZenUML 参与者「${id}」重复声明`, `Duplicate ZenUML participant "${id}"`, "删除重复声明", "Remove the duplicate declaration");
288
+ else Object.assign(actor, {
289
+ declared: true,
290
+ name: name?.replace(/^(["'])(.*)\1$/u, "$2") || id,
291
+ kind: kinds.has(kind) ? kind : "participant",
292
+ line
293
+ });
294
+ if (!kinds.has(kind)) {
295
+ ignored.add(`@${type}`);
296
+ ignoredLine ??= line;
297
+ }
298
+ } else unrecognized(line, syntax);
299
+ comments = [];
300
+ }
301
+ if (replyLine) missingReply(replyLine);
302
+ for (const entry of stack) bad(entry.line, "ZenUML 块缺少 }", "ZenUML block is missing }", "添加匹配的 }", "Add a matching }");
303
+ if (!actors.size && !errors.length) bad(firstLine, "ZenUML 缺少参与者", "ZenUML needs at least one participant", "添加参与者 Client 或消息 Client->API: 请求", "Add a participant Client or a message Client->API: request");
304
+ const participants = [...actors.values()];
305
+ if (participants.length > MAX_PARTICIPANTS) bad(participants[MAX_PARTICIPANTS].line, `ZenUML 参与者超过 ${MAX_PARTICIPANTS} 个`, `ZenUML has more than ${MAX_PARTICIPANTS} participants`, "拆分为多张图", "Split into several diagrams");
306
+ if (ignored.size) {
307
+ const names = [...ignored].join(", ");
308
+ errors.push(warning("DIAGRAM_HINT", lang, ignoredLine, `以下注解使用普通参与者外观:${names}`, `Using standard participants for these annotations: ${names}`, "如需图标,使用受支持的参与者类型", "Use a supported participant type if an icon is needed"));
309
+ }
310
+ if (actors.has(STARTER)) participants.unshift(participants.splice(participants.indexOf(actors.get(STARTER)), 1)[0]);
311
+ participants.forEach((actor, index) => {
312
+ actor.index = index;
313
+ });
314
+ return {
315
+ model: {
316
+ type: "sequence",
317
+ title,
318
+ participants,
319
+ statements,
320
+ messages,
321
+ zenuml: true
322
+ },
323
+ errors
324
+ };
325
+ }
326
+ var shared = implementations$1.sequenceDiagram;
327
+ var implementations = { zenuml: {
328
+ parse,
329
+ layout: (model, options, info) => shared.layout(model, {
330
+ ...options,
331
+ compact: true
332
+ }, {
333
+ ...info,
334
+ config: { sequence: { mirrorActors: false } }
335
+ }),
336
+ scene: shared.scene
337
+ } };
338
+ export { implementations, zenuml_exports };
@@ -48,6 +48,7 @@ export interface RenderOptions {
48
48
  lang?: string;
49
49
  theme?: string | Theme;
50
50
  media?: Media;
51
+ /** Draw the outer frame and its title (default true). With false the host shows the title; see Scene.heading. */
51
52
  frame?: boolean;
52
53
  prefix?: string;
53
54
  measure?: (text: string, size: number, weight: number, fontFamily: string) => number;
@@ -55,7 +56,7 @@ export interface RenderOptions {
55
56
  }
56
57
 
57
58
  export interface CheckOptions { syntax?: Syntax; lang?: string }
58
- export interface DiagramOptions extends RenderOptions { syntax?: Syntax }
59
+ export interface DiagramOptions extends RenderOptions { syntax?: Syntax; compact?: boolean }
59
60
  export interface ChartDiagnostic {
60
61
  code: string;
61
62
  message: string;
@@ -87,6 +88,7 @@ export interface Scene {
87
88
  height: number;
88
89
  children: SceneNode[];
89
90
  title?: string;
91
+ /** Visible diagram title. With frame: false (and no compact) the drawing leaves it out for the host to show. */
90
92
  heading?: string;
91
93
  subtitle?: string;
92
94
  source?: string;
@@ -6,7 +6,7 @@ import type { DiagramDiagnostic, RenderOptions } from './index.js';
6
6
  * `startOnLoad` pass silently, and the rest, such as `themeVariables` or the theme name `dark`, produce one
7
7
  * `IGNORED_CONFIG` warning.
8
8
  */
9
- export type MermaidOptions = Omit<RenderOptions, 'assets'> & { [setting: string]: unknown };
9
+ export type MermaidOptions = Omit<RenderOptions, 'assets'> & { compact?: boolean; [setting: string]: unknown };
10
10
  export interface MermaidError extends Error { diagnostics: DiagramDiagnostic[] }
11
11
  /** `diagnostics` holds only warnings: any error rejects instead. */
12
12
  export interface MermaidParseResult { diagramType: string; diagnostics: DiagramDiagnostic[] }
@@ -9,7 +9,8 @@ var RENDER_OPTIONS = /* @__PURE__ */ new Set([
9
9
  "media",
10
10
  "frame",
11
11
  "prefix",
12
- "measure"
12
+ "measure",
13
+ "compact"
13
14
  ]);
14
15
  function optionsOf(settings) {
15
16
  const options = { syntax: "mermaid" }, site = {};