@x-cmd/draw 0.2.5 → 0.4.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 (131) hide show
  1. package/README.md +80 -166
  2. package/dist/lib.d.ts +27 -1
  3. package/dist/lib.js +39 -1
  4. package/dist/node/cli.js +109 -11
  5. package/dist/render/anno.d.ts +50 -0
  6. package/dist/render/anno.js +589 -0
  7. package/dist/render/arch.d.ts +106 -0
  8. package/dist/render/arch.js +1011 -0
  9. package/dist/render/archmap.d.ts +157 -0
  10. package/dist/render/archmap.js +683 -0
  11. package/dist/render/area.js +20 -14
  12. package/dist/render/bar-grouped.js +8 -5
  13. package/dist/render/bar-stacked.js +11 -7
  14. package/dist/render/bar.js +8 -3
  15. package/dist/render/butterfly.d.ts +3 -0
  16. package/dist/render/butterfly.js +355 -0
  17. package/dist/render/calendar.d.ts +6 -0
  18. package/dist/render/calendar.js +448 -0
  19. package/dist/render/combo.js +16 -8
  20. package/dist/render/compass.d.ts +6 -0
  21. package/dist/render/compass.js +77 -0
  22. package/dist/render/dispatch.js +26 -1
  23. package/dist/render/echarts-ssr.d.ts +51 -0
  24. package/dist/render/echarts-ssr.js +511 -0
  25. package/dist/render/gantt.d.ts +46 -0
  26. package/dist/render/gantt.js +415 -0
  27. package/dist/render/gantt2.d.ts +24 -0
  28. package/dist/render/gantt2.js +198 -0
  29. package/dist/render/hbar.js +8 -4
  30. package/dist/render/icons.d.ts +3 -0
  31. package/dist/render/icons.js +78 -0
  32. package/dist/render/kinds.d.ts +11 -0
  33. package/dist/render/kinds.js +176 -0
  34. package/dist/render/ladder.d.ts +21 -0
  35. package/dist/render/ladder.js +230 -0
  36. package/dist/render/layout.d.ts +46 -0
  37. package/dist/render/layout.js +57 -0
  38. package/dist/render/line-multi.js +7 -5
  39. package/dist/render/line.js +9 -5
  40. package/dist/render/maps.d.ts +46 -0
  41. package/dist/render/maps.js +237 -0
  42. package/dist/render/measure.d.ts +0 -1
  43. package/dist/render/measure.js +0 -1
  44. package/dist/render/mermaid.d.ts +30 -0
  45. package/dist/render/mermaid.js +277 -0
  46. package/dist/render/mindmap.d.ts +10 -0
  47. package/dist/render/mindmap.js +388 -0
  48. package/dist/render/orgicon.d.ts +12 -0
  49. package/dist/render/orgicon.js +31 -0
  50. package/dist/render/pie.js +1 -1
  51. package/dist/render/png.d.ts +21 -0
  52. package/dist/render/png.js +109 -0
  53. package/dist/render/quadrant.d.ts +6 -0
  54. package/dist/render/quadrant.js +201 -0
  55. package/dist/render/query.d.ts +2 -0
  56. package/dist/render/query.js +108 -1
  57. package/dist/render/route.d.ts +86 -0
  58. package/dist/render/route.js +1077 -0
  59. package/dist/render/scatter.js +87 -12
  60. package/dist/render/seq.d.ts +41 -0
  61. package/dist/render/seq.js +248 -0
  62. package/dist/render/svg.d.ts +34 -2
  63. package/dist/render/svg.js +159 -20
  64. package/dist/render/table.d.ts +30 -0
  65. package/dist/render/table.js +134 -0
  66. package/dist/render/tokei.d.ts +18 -0
  67. package/dist/render/tokei.js +230 -0
  68. package/dist/render/uc.d.ts +58 -0
  69. package/dist/render/uc.js +319 -0
  70. package/dist/render/units.d.ts +32 -0
  71. package/dist/render/units.js +84 -0
  72. package/dist/render/vendor/au.js +10 -0
  73. package/dist/render/vendor/br.js +10 -0
  74. package/dist/render/vendor/china.js +11 -0
  75. package/dist/render/vendor/de.js +10 -0
  76. package/dist/render/vendor/eu.js +10 -0
  77. package/dist/render/vendor/japan.js +10 -0
  78. package/dist/render/vendor/kr.js +10 -0
  79. package/dist/render/vendor/mermaid-flow-parser.js +1164 -0
  80. package/dist/render/vendor/mermaid-gantt-parser.js +810 -0
  81. package/dist/render/vendor/us-states.js +11 -0
  82. package/dist/render/vendor/world-geo.d.ts +22 -0
  83. package/dist/render/vendor/world-geo.js +9 -0
  84. package/dist/render/vendor/world.d.ts +13 -0
  85. package/dist/render/vendor/world.js +12 -0
  86. package/dist/specs/base.d.ts +16 -0
  87. package/dist/specs/base.js +34 -1
  88. package/dist/specs/butterfly.d.ts +46 -0
  89. package/dist/specs/butterfly.js +241 -0
  90. package/dist/specs/calendar.d.ts +90 -0
  91. package/dist/specs/calendar.js +296 -0
  92. package/dist/specs/compass.d.ts +27 -0
  93. package/dist/specs/compass.js +111 -0
  94. package/dist/specs/index.d.ts +5 -0
  95. package/dist/specs/index.js +5 -0
  96. package/dist/specs/ladder.d.ts +43 -0
  97. package/dist/specs/ladder.js +261 -0
  98. package/dist/specs/quadrant.d.ts +41 -0
  99. package/dist/specs/quadrant.js +200 -0
  100. package/dist/specs/scatter.d.ts +14 -8
  101. package/dist/specs/scatter.js +54 -5
  102. package/dist/specs/table.d.ts +24 -0
  103. package/dist/specs/table.js +154 -0
  104. package/dist/store.d.ts +1 -1
  105. package/dist/store.js +1 -1
  106. package/dist/styles/butterfly.d.ts +2 -0
  107. package/dist/styles/butterfly.js +74 -0
  108. package/dist/styles/calendar.d.ts +2 -0
  109. package/dist/styles/calendar.js +51 -0
  110. package/dist/styles/compass.d.ts +2 -0
  111. package/dist/styles/compass.js +19 -0
  112. package/dist/styles/fonts-banner.d.ts +5 -0
  113. package/dist/styles/fonts-banner.js +9 -0
  114. package/dist/styles/fonts-cjk.d.ts +2 -0
  115. package/dist/styles/fonts-cjk.js +6 -0
  116. package/dist/styles/fonts-ttf.d.ts +2 -0
  117. package/dist/styles/fonts-ttf.js +6 -0
  118. package/dist/styles/index.js +13 -0
  119. package/dist/styles/ladder.d.ts +3 -0
  120. package/dist/styles/ladder.js +66 -0
  121. package/dist/styles/quadrant.d.ts +2 -0
  122. package/dist/styles/quadrant.js +19 -0
  123. package/dist/styles/table.d.ts +2 -0
  124. package/dist/styles/table.js +12 -0
  125. package/dist/styles/types.d.ts +1 -0
  126. package/dist/styles/types.js +1 -0
  127. package/dist/theme.d.ts +1 -1
  128. package/dist/theme.js +3 -4
  129. package/dist/types/dagre.d.ts +39 -0
  130. package/dist/types/dagre.js +3 -0
  131. package/package.json +28 -3
@@ -1,5 +1,5 @@
1
1
  import { TAB, card } from '../theme.js';
2
- import { esc, fmtNum, niceStep, r2, snap, trunc, LabelPlacer, pushLineLabelsAllOrNothing, reserveBands, reserveEdges, sVar, svgDoc, titleBlock } from './svg.js';
2
+ import { esc, fmtNum, niceStep, r2, snap, textW, trunc, TAG_RESERVE, LabelPlacer, pushLineLabelsAllOrNothing, reserveBands, reserveEdges, sVar, marksLayer, svgDoc, titleBlock } from './svg.js';
3
3
  import { tickColW } from './measure.js';
4
4
  // 取整量程刻度:数据向下/向上取整到步长(规范 -18..19 → -20..20),刻度线铺满整域
5
5
  function spanTicks(min, max, count) {
@@ -11,6 +11,20 @@ function spanTicks(min, max, count) {
11
11
  out.push(snap(v, step));
12
12
  return out;
13
13
  }
14
+ // 对数轴刻度:1/2/5 × 10^k(价格这类量级差得远的轴:1 块和 20 块挤在一起就分不开了)
15
+ function logTicks(min, max) {
16
+ const lo = Math.floor(Math.log10(min));
17
+ const hi = Math.ceil(Math.log10(max));
18
+ const out = [];
19
+ for (let e = lo; e <= hi; e++) {
20
+ for (const m of [1, 2, 5]) {
21
+ const v = m * Math.pow(10, e);
22
+ if (v >= min * 0.999 && v <= max * 1.001)
23
+ out.push(v);
24
+ }
25
+ }
26
+ return out.length >= 2 ? out : spanTicks(min, max, 4);
27
+ }
14
28
  /**
15
29
  * Scatter plot with two numeric axes; negative values allowed.
16
30
  */
@@ -22,10 +36,12 @@ export function renderScatter(spec, o) {
22
36
  const all = series.flatMap((s) => s.points);
23
37
  const xs = all.map((p) => p.x);
24
38
  const ys = all.map((p) => p.y);
25
- const xTicks = spanTicks(Math.min(...xs), Math.max(...xs), 4);
39
+ const logx = spec.logx === true;
40
+ const xTicks = logx ? logTicks(Math.min(...xs), Math.max(...xs)) : spanTicks(Math.min(...xs), Math.max(...xs), 4);
26
41
  const yTicks = spanTicks(Math.min(...ys), Math.max(...ys), 6);
27
- const minX = xTicks[0];
28
- const maxX = xTicks[xTicks.length - 1];
42
+ // 对数轴:量程取数据本身(刻度只是参考线,不能把最远的点切掉)
43
+ const minX = logx ? Math.min(...xs) : xTicks[0];
44
+ const maxX = logx ? Math.max(...xs) : xTicks[xTicks.length - 1];
29
45
  const minY = yTicks[0];
30
46
  const maxY = yTicks[yTicks.length - 1];
31
47
  let peakS = 0;
@@ -44,7 +60,17 @@ export function renderScatter(spec, o) {
44
60
  const bottom = Math.round(height * 0.857);
45
61
  const top = Math.round(height * 0.184);
46
62
  const tickY = Math.round(height * 0.906);
47
- const px = (x) => maxX === minX ? (left + right) / 2 : left + ((x - minX) / (maxX - minX)) * (right - left);
63
+ // 对数轴:x 先取 log10 再线性映射(刻度按 1/2/5×10^k 排)
64
+ const px = (x) => {
65
+ if (maxX === minX)
66
+ return (left + right) / 2;
67
+ if (!logx)
68
+ return left + ((x - minX) / (maxX - minX)) * (right - left);
69
+ const lx = Math.log10(x);
70
+ const lo = Math.log10(minX);
71
+ const hi = Math.log10(maxX);
72
+ return left + ((lx - lo) / (hi - lo)) * (right - left);
73
+ };
48
74
  const py = (y) => maxY === minY ? (top + bottom) / 2 : bottom - ((y - minY) / (maxY - minY)) * (bottom - top);
49
75
  const parts = [card(width, height, true)];
50
76
  // 网格 + 刻度(虚线 4 6)
@@ -61,8 +87,8 @@ export function renderScatter(spec, o) {
61
87
  parts.push(`<line x1="${left}" y1="${r2(bottom)}" x2="${right}" y2="${r2(bottom)}" stroke="var(--d-baseline)" stroke-width="1"/>`);
62
88
  // 轴标题:画布太小则省(会与刻度挤在一起)
63
89
  if (showTitles) {
64
- parts.push(`<text x="${r2((left + right) / 2)}" y="${r2(height * 0.959)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(spec.unit ?? 'X value')}</text>`);
65
- parts.push(`<text x="${r2(width * 0.024)}" y="${r2(height / 2)}" text-anchor="middle" font-size="12" fill="var(--d-muted)" transform="rotate(-90 ${r2(width * 0.024)} ${r2(height / 2)})">Y value</text>`);
90
+ parts.push(`<text x="${r2((left + right) / 2)}" y="${r2(height * 0.959)}" text-anchor="middle" font-size="12" fill="var(--d-muted)">${esc(spec.xname ?? spec.unit ?? 'X value')}</text>`);
91
+ parts.push(`<text x="${r2(width * 0.024)}" y="${r2(height / 2)}" text-anchor="middle" font-size="12" fill="var(--d-muted)" transform="rotate(-90 ${r2(width * 0.024)} ${r2(height / 2)})">${esc(spec.yname ?? 'Y value')}</text>`);
66
92
  }
67
93
  // 数据点:每系列一色,点径交替(每 4 个大点),半透明+白描边
68
94
  const num = o.valueLabels ?? 'none';
@@ -71,7 +97,7 @@ export function renderScatter(spec, o) {
71
97
  const color = sVar(si % skin.series.length);
72
98
  s.points.forEach((p, pi) => {
73
99
  const isPeak = si === peakS && pi === peakP;
74
- parts.push(`<circle cx="${r2(px(p.x))}" cy="${r2(py(p.y))}" r="${pi % 4 === 0 ? 7 : 5}" fill="${color}" fill-opacity="0.78" stroke="var(--d-halo)" stroke-width="2"/>`);
100
+ parts.push(`<circle cx="${r2(px(p.x))}" cy="${r2(py(p.y))}" r="${pi % 4 === 0 ? 7 : 5}" fill="${color}" fill-opacity="0.78" stroke="var(--d-halo)" stroke-width="2"${o.interactive ? ` data-tip="${esc(`${fmtNum(p.x)}${spec.unit ? ' ' + spec.unit : ''} · ${fmtNum(p.y)}`)}" data-series="${si}"` : ''}/>`);
75
101
  if (num === 'all' || (num === 'peak' && isPeak)) {
76
102
  numItems.push({ px: px(p.x), py: py(p.y), text: fmtNum(p.y), isPeak });
77
103
  }
@@ -81,14 +107,54 @@ export function renderScatter(spec, o) {
81
107
  // 预留 Y 刻度带/X 刻度带/图例带与画布边带:标签不得压轴文字、不得出画布
82
108
  if (numItems.length > 0) {
83
109
  const placer = new LabelPlacer();
84
- reserveBands(placer, left, right, top, bottom, tickY, spec.series ?? [], right, Math.round(height * 0.09));
110
+ reserveBands(placer, left, right, top, bottom, tickY, spec.series ?? [], right, 24 + 14);
85
111
  reserveEdges(placer, width, height);
86
112
  pushLineLabelsAllOrNothing(parts, placer, numItems);
87
113
  }
88
- // 多系列:右上圆点图例
114
+ // 点旁边的名字(榜单类散点:名字是信息本身)。放不下就不画 —— 宁可少一个名字,不可叠字。
115
+ const labelled = series.flatMap((sr, si) => sr.points.map((p, pi) => ({ p, si, pi })))
116
+ .filter((it) => !!it.p.label);
117
+ if (labelled.length) {
118
+ const placer = new LabelPlacer();
119
+ reserveBands(placer, left, right, top, bottom, tickY, spec.series ?? [], right, 24 + 14);
120
+ reserveEdges(placer, width, height);
121
+ // 点本身占位:名字不能压在别的点上
122
+ series.forEach((sr) => sr.points.forEach((p) => {
123
+ placer.reserve(px(p.x) - 8, py(p.y) - 8, 16, 16);
124
+ }));
125
+ for (const it of labelled) {
126
+ const lines = it.p.label.split('\n');
127
+ const tw = Math.max(...lines.map((l) => textW(l, 11)));
128
+ const th = lines.length * 13;
129
+ const cx = px(it.p.x);
130
+ const cy = py(it.p.y);
131
+ // 候选位:先右后左,再上/下 —— 挨着的点多了就往空的一边挪
132
+ const cands = [
133
+ [cx + 10, cy - th / 2, 'start'],
134
+ [cx - 12 - tw, cy - th / 2, 'end'],
135
+ [cx - tw / 2, cy - 10 - th, 'start'],
136
+ [cx - tw / 2, cy + 10, 'start'],
137
+ [cx + 10, cy - th - 10, 'start'],
138
+ [cx - 12 - tw, cy - th - 10, 'end'],
139
+ [cx + 10, cy + 6, 'start'],
140
+ [cx - 12 - tw, cy + 6, 'end'],
141
+ ];
142
+ for (const [lx, by, anchor] of cands) {
143
+ // 候选位给的是文字的左边缘;占位框按左边缘算,画的时候再按对齐方式收口
144
+ if (!placer.fits(lx, by, tw + 4, th + 2))
145
+ continue;
146
+ const tx = anchor === 'end' ? lx + tw : lx;
147
+ lines.forEach((l, li) => {
148
+ parts.push(`<text x="${r2(tx)}" y="${r2(by + 10 + li * 13)}" text-anchor="${anchor}" font-size="11" fill="var(--d-text)" style="${TAB}">${esc(l)}</text>`);
149
+ });
150
+ break;
151
+ }
152
+ }
153
+ }
154
+ // 多系列:右上圆点图例(坐标题基线,与 Edit 角标同排,向左让出角标宽度 #27)
89
155
  if (spec.series?.length) {
90
- let lx = right;
91
- const legendY = Math.round(height * 0.09);
156
+ let lx = right - TAG_RESERVE;
157
+ const legendY = 24 + 14;
92
158
  for (let i = spec.series.length - 1; i >= 0; i--) {
93
159
  const name = trunc(spec.series[i].name, 12);
94
160
  parts.push(`<text x="${r2(lx)}" y="${r2(legendY)}" text-anchor="end" font-size="12" fill="var(--d-muted)">${esc(name)}</text>`);
@@ -97,5 +163,14 @@ export function renderScatter(spec, o) {
97
163
  lx -= 24;
98
164
  }
99
165
  }
166
+ // 标注层(散点为双数值锚):锚值直接按量程映射,夹在绘图区内
167
+ if (o.marks && o.marks.length > 0) {
168
+ const mpts = o.marks.map((m) => ({
169
+ x: Math.min(Math.max(px(Number(m.ax)), left), right),
170
+ y: Math.min(Math.max(py(m.ay), top), bottom),
171
+ text: m.text,
172
+ }));
173
+ parts.push(marksLayer(mpts, width));
174
+ }
100
175
  return svgDoc(width, height, 'scatter', version, spec.title ?? 'scatter chart', spec, skin, titleBlock(spec.title) + parts.join(''));
101
176
  }
@@ -0,0 +1,41 @@
1
+ import type { ArchBoundary, ArchNode } from './archmap.js';
2
+ import { resolveSkin } from '../styles/index.js';
3
+ import { type DrawResult } from './query.js';
4
+ interface Msg {
5
+ from: string;
6
+ to: string;
7
+ label?: string;
8
+ dash: boolean;
9
+ }
10
+ /** 一个分支框:kind=alt|else|opt|loop|par|break,label=守卫文字,start/end=消息下标(含两端) */
11
+ interface Frag {
12
+ kind: string;
13
+ label: string;
14
+ start: number;
15
+ end: number;
16
+ }
17
+ export interface SeqOpts {
18
+ nodes: ArchNode[];
19
+ msgs: Msg[];
20
+ frags: Frag[];
21
+ /** b= 画出来的泳道(可以有多条) */
22
+ boundaries: ArchBoundary[];
23
+ /** 原始 URL 查询串:角标直链 explore 落地页用 */
24
+ tagQuery?: string;
25
+ title?: string;
26
+ interactive: boolean;
27
+ version: number;
28
+ cacheControl: string;
29
+ skin: ReturnType<typeof resolveSkin>;
30
+ minW?: number;
31
+ minH?: number;
32
+ }
33
+ /**
34
+ * 渲染时序图。
35
+ */
36
+ export declare function renderSeqCore(o: SeqOpts): DrawResult;
37
+ /**
38
+ * `/draw/seq` 入口:GET ?n=…&e=…(n= 参与方,e= 消息,顺序即时间)。
39
+ */
40
+ export declare function renderSeqFromUrl(url: URL, interactive?: boolean): DrawResult;
41
+ export {};
@@ -0,0 +1,248 @@
1
+ // /draw/seq —— 时序图:参与方在上一行,消息一行一条,时间往下走。
2
+ //
3
+ // 模型(和 archmap 同一套 n= 语法;e= 里的边按 URL 里的顺序就是时间顺序):
4
+ // n=id;type;label[;sub][;pos] 参与方(位置一般写 r0c0 / r0c1 / …)
5
+ // e=from;to[;label][;dash] 一条消息;URL 里的先后就是发生的先后
6
+ // b=label;id id … 框:把一组参与方圈成一条「泳道」(可写多次)
7
+ //
8
+ // 画法:参与方一行,下面拖出生命线;每条消息在下一行,从发方生命线画一条箭头到收方,
9
+ // 收方在这段时间画一根激活条(细竖条)。回信写 dash → 虚线箭头。
10
+ import { ApiError } from '../specs/index.js';
11
+ import { packGrid, parseBoundaries, parseNodes } from './archmap.js';
12
+ import { resolveSkin } from '../styles/index.js';
13
+ import { clampInt, schemeParam } from './query.js';
14
+ import { esc, r2, svgDoc, textW } from './svg.js';
15
+ const PAD = 40;
16
+ const HEADER_H = 56; // 参与方标题盒高
17
+ const MSG_GAP = 78; // 两条消息之间的行距(要给分支框的标签留位置)
18
+ const ARROW = 10; // 箭头长度
19
+ const LABEL_FS = 12;
20
+ const LANE_TOP = 30; // 有 b= 时,给泳道标签留出来的那一行
21
+ /** f=kind;label;start;end —— 分支框罩住第 start..end 条消息(含两端) */
22
+ function parseFrags(raw, msgCount) {
23
+ return raw.map((v, i) => {
24
+ const f = v.split(';').map((x) => x.trim());
25
+ if (f.length < 4) {
26
+ throw new ApiError(400, `"f" #${i + 1} must be "kind;label;start;end". Example: f=alt;ok;0;2`);
27
+ }
28
+ const kind = f[0].toLowerCase();
29
+ if (!['alt', 'else', 'opt', 'loop', 'par', 'break'].includes(kind)) {
30
+ throw new ApiError(400, `"f" #${i + 1}: kind must be one of alt, else, opt, loop, par, break`);
31
+ }
32
+ const start = Number(f[2]);
33
+ const end = Number(f[3]);
34
+ if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end >= msgCount) {
35
+ throw new ApiError(400, `"f" #${i + 1}: start/end must be message indexes within 0..${msgCount - 1}`);
36
+ }
37
+ return { kind, label: f[1], start, end };
38
+ });
39
+ }
40
+ /** e=from;to[;label][;dash] —— 按 URL 里的顺序就是时间顺序 */
41
+ function parseMessages(raw) {
42
+ return raw.map((v, i) => {
43
+ const f = v.split(';').map((x) => x.trim());
44
+ if (f.length < 2 || !f[0] || !f[1]) {
45
+ throw new ApiError(400, `"e" #${i + 1} must be "from;to[;label][;dash]". Example: e=app;worker;GET /draw?type=pie`);
46
+ }
47
+ const last = f[f.length - 1];
48
+ const dash = f.length > 2 && last.toLowerCase() === 'dash';
49
+ const rest = dash ? f.slice(0, -1) : f;
50
+ return { from: rest[0], to: rest[1], label: rest[2] || undefined, dash };
51
+ });
52
+ }
53
+ /** 参与方标题盒:和 archmap 一样的底子,但自己画(时序图里它是「头顶」不是方块) */
54
+ function headerBox(x, y, w, label, sub, color, interactive = false, id = '') {
55
+ const c = color >= 0 ? `var(--d-s${color + 1})` : 'var(--d-muted)';
56
+ const fill = color >= 0 ? c : 'var(--d-muted)';
57
+ const labelY = sub ? y + 26 : y + HEADER_H / 2 + 5;
58
+ const ia = interactive ? ` data-node="${esc(id)}" data-tip="${esc(sub ? `${label} · ${sub}` : label)}" tabindex="0"` : '';
59
+ return (`<g${ia}>` +
60
+ `<rect x="${r2(x)}" y="${r2(y)}" width="${r2(w)}" height="${HEADER_H}" rx="10"` +
61
+ ` fill="${fill}" fill-opacity="${color >= 0 ? 0.12 : 0.06}" stroke="${c}" stroke-opacity="0.55" stroke-width="1.2"/>` +
62
+ `<text x="${r2(x + w / 2)}" y="${r2(labelY)}" text-anchor="middle" font-size="14" font-weight="600" fill="var(--d-ink)">${esc(label)}</text>` +
63
+ (sub ? `<text x="${r2(x + w / 2)}" y="${r2(y + 44)}" text-anchor="middle" font-size="11" fill="var(--d-muted)">${esc(sub)}</text>` : '') +
64
+ `</g>`);
65
+ }
66
+ /**
67
+ * 渲染时序图。
68
+ */
69
+ export function renderSeqCore(o) {
70
+ const { placed } = packGrid(o.nodes, 0, { gapX: 56, gapY: 40, pad: PAD, sizeOf: (n) => {
71
+ const w = Math.max(150, textW(n.label, 14) + 44, n.sub ? textW(n.sub, 11) + 44 : 0);
72
+ return { w: Math.min(w, 320), h: HEADER_H };
73
+ } });
74
+ const titleH = o.title ? 40 : 0;
75
+ if (titleH)
76
+ for (const p of placed)
77
+ p.box.y += titleH; // 有标题就往下挪一格,别压住
78
+ // 有泳道就整体往下挪一行,给泳道标签腾地方(所有参与方一起挪,标题行才对齐)
79
+ if (o.boundaries.length)
80
+ for (const p of placed)
81
+ p.box.y += LANE_TOP;
82
+ const byId = new Map(placed.map((p) => [p.id, p]));
83
+ for (const m of o.msgs) {
84
+ if (!byId.has(m.from))
85
+ throw new ApiError(400, `message references unknown participant "${m.from}"`);
86
+ if (!byId.has(m.to))
87
+ throw new ApiError(400, `message references unknown participant "${m.to}"`);
88
+ }
89
+ // 参与方的中心 x(生命线所在)
90
+ const cxOf = (id) => {
91
+ const b = byId.get(id).box;
92
+ return b.x + b.w / 2;
93
+ };
94
+ const headerBottom = Math.max(...placed.map((p) => p.box.y + p.box.h));
95
+ const rowY = (i) => headerBottom + 58 + i * MSG_GAP;
96
+ let width = Math.max(320, ...placed.map((p) => p.box.x + p.box.w + PAD));
97
+ let height = rowY(Math.max(0, o.msgs.length - 1)) + 34 + PAD;
98
+ width = Math.max(width, o.minW ?? 0);
99
+ height = Math.max(height, o.minH ?? 0);
100
+ const parts = [];
101
+ // 生命线:从标题盒底到最后一条消息
102
+ const lastY = o.msgs.length ? rowY(o.msgs.length - 1) : headerBottom;
103
+ // 泳道(b=):把一组参与方圈起来 —— 虚线框 + 框内左上角的标签。
104
+ // 框从参与方标题盒上面开始(那一行留给标签),一直到生命线底下。
105
+ // 颜色和架构图的边界一个规矩:用「节点类型没占用的颜色」,不跟盒子撞色。
106
+ const laneSvg = () => {
107
+ const out = [];
108
+ // 架构图那八种类型占了 s1–s7,泳道用 s8/s9/s10
109
+ const LANE_COLORS = ['var(--d-s8)', 'var(--d-s9)', 'var(--d-s10)'];
110
+ o.boundaries.forEach((b, i) => {
111
+ const ms = b.ids.map((id) => byId.get(id)).filter(Boolean);
112
+ if (!ms.length)
113
+ return;
114
+ const c = b.color ? `var(--d-s${b.color})` : LANE_COLORS[i % LANE_COLORS.length];
115
+ const x0 = Math.min(...ms.map((m) => m.box.x)) - 16;
116
+ const x1 = Math.max(...ms.map((m) => m.box.x + m.box.w)) + 16;
117
+ const y0 = Math.min(...ms.map((m) => m.box.y)) - LANE_TOP;
118
+ const y1 = Math.max(lastY + 18, ...ms.map((m) => m.box.y + m.box.h));
119
+ const label = b.label.toUpperCase();
120
+ const lw = textW(label, 10) + b.label.length * 1.2 + 20;
121
+ out.push(`<g data-boundary="${esc(b.ids.join(' '))}">` +
122
+ `<rect x="${r2(x0)}" y="${r2(y0)}" width="${r2(x1 - x0)}" height="${r2(y1 - y0)}" rx="12" fill="none" stroke="${c}" stroke-opacity="0.65" stroke-width="1.4" stroke-dasharray="7 5"/>` +
123
+ `<rect x="${r2(x0 + 10)}" y="${r2(y0 + 5)}" width="${r2(lw)}" height="19" rx="6" fill="var(--d-card)"/>` +
124
+ `<rect x="${r2(x0 + 11)}" y="${r2(y0 + 6)}" width="${r2(lw - 2)}" height="17" rx="5" fill="${c}" fill-opacity="0.16"/>` +
125
+ `<text x="${r2(x0 + 10 + lw / 2)}" y="${r2(y0 + 18)}" text-anchor="middle" font-size="10" font-weight="700" letter-spacing="1.2" fill="${c}">${esc(label)}</text>` +
126
+ `</g>`);
127
+ });
128
+ return out.join('');
129
+ };
130
+ parts.push(laneSvg());
131
+ for (const p of placed) {
132
+ const x = cxOf(p.id);
133
+ parts.push(`<line x1="${r2(x)}" y1="${r2(p.box.y + p.box.h)}" x2="${r2(x)}" y2="${r2(lastY + 18)}" stroke="var(--d-border)" stroke-width="1.4"/>`);
134
+ }
135
+ // 激活条:收到消息的一方,到它下一次发消息为止
136
+ const act = new Map();
137
+ o.msgs.forEach((m, i) => {
138
+ const cur = act.get(m.to);
139
+ if (!cur)
140
+ act.set(m.to, { from: i, to: rowY(i) + 16 });
141
+ else
142
+ cur.to = rowY(i) + 16;
143
+ });
144
+ // 消息
145
+ o.msgs.forEach((m, i) => {
146
+ const y = rowY(i);
147
+ const x1 = cxOf(m.from);
148
+ const x2 = cxOf(m.to);
149
+ const dir = x2 >= x1 ? 1 : -1;
150
+ const ax = x2 - dir * ARROW;
151
+ const stroke = m.dash ? 'var(--d-faint)' : 'var(--d-muted)';
152
+ const dash = m.dash ? ' stroke-dasharray="5 4"' : '';
153
+ const ia = o.interactive ? ` data-from="${esc(m.from)}" data-to="${esc(m.to)}"` : '';
154
+ parts.push(`<path d="M${r2(x1)} ${r2(y)}L${r2(ax)} ${r2(y)}" fill="none" stroke="${stroke}" stroke-width="1.4"${dash}${ia}/>`, `<path d="M${r2(x2)} ${r2(y)}L${r2(ax)} ${r2(y)}L${r2(x2 - dir * 4)} ${r2(y - 4)}M${r2(x2)} ${r2(y)}L${r2(x2 - dir * 4)} ${r2(y + 4)}" fill="none" stroke="${stroke}" stroke-width="1.4"${dash}/>`);
155
+ if (m.label) {
156
+ const w = textW(m.label, LABEL_FS) + 14;
157
+ const lx = (x1 + x2) / 2;
158
+ parts.push(`<rect x="${r2(lx - w / 2)}" y="${r2(y - LABEL_FS - 12)}" width="${r2(w)}" height="${LABEL_FS + 7}" rx="5" fill="var(--d-card)" stroke="var(--d-border)" stroke-width="1"/>`, `<text x="${r2(lx)}" y="${r2(y - 7)}" text-anchor="middle" font-size="${LABEL_FS}" fill="var(--d-text)">${esc(m.label)}</text>`);
159
+ }
160
+ });
161
+ // 激活条画在消息之上(盖住生命线)
162
+ for (const [id, r] of act) {
163
+ const x = cxOf(id);
164
+ parts.push(`<rect x="${r2(x - 3)}" y="${r2(rowY(r.from) - 12)}" width="6" height="${r2(r.to - rowY(r.from) + 24)}" rx="3" fill="var(--d-ink)" fill-opacity="0.85"/>`);
165
+ }
166
+ // 分支框(alt / else / opt / loop / par / break):
167
+ // 一个 alt 后面连续的 else 归成一组,共用一个外框,中间一条虚线分开两支。
168
+ const fragSvg = () => {
169
+ if (!o.frags.length)
170
+ return '';
171
+ const groups = [];
172
+ for (const f of o.frags) {
173
+ const last = groups[groups.length - 1];
174
+ const join = last && ((last.frags[0].kind === 'alt' && f.kind === 'else') || (last.frags[0].kind !== 'alt' && f.kind === last.frags[0].kind && f.kind !== 'else'));
175
+ if (join)
176
+ last.frags.push(f);
177
+ else
178
+ groups.push({ frags: [f] });
179
+ }
180
+ const out = [];
181
+ for (const g of groups) {
182
+ const first = g.frags[0];
183
+ const lastF = g.frags[g.frags.length - 1];
184
+ const rows = [];
185
+ for (let i = first.start; i <= lastF.end; i++)
186
+ rows.push(i);
187
+ const xs = rows.flatMap((i) => [cxOf(o.msgs[i].from), cxOf(o.msgs[i].to)]);
188
+ const x0 = Math.min(...xs) - 18;
189
+ const x1 = Math.max(...xs) + 18;
190
+ const y0 = rowY(first.start) - 50;
191
+ const y1 = rowY(lastF.end) + 24;
192
+ out.push(`<rect x="${r2(x0)}" y="${r2(y0)}" width="${r2(x1 - x0)}" height="${r2(y1 - y0)}" rx="8" fill="var(--d-muted)" fill-opacity="0.06" stroke="var(--d-border)" stroke-width="1.2"/>`);
193
+ // 标签:alt [ok] / else [fail] / loop [each]
194
+ g.frags.forEach((f, i) => {
195
+ const text = f.label ? `${f.kind} [${f.label}]` : f.kind;
196
+ const w = textW(text, 10.5) + 12;
197
+ const lx = x0 + 12;
198
+ // 第一支的标签贴在框顶;后面的支(else)贴在分隔线上
199
+ const ly = i === 0 ? y0 + 14 : rowY(f.start) - 34 + 4;
200
+ if (i > 0) {
201
+ const dy = rowY(f.start) - 34;
202
+ out.push(`<line x1="${r2(x0)}" y1="${r2(dy)}" x2="${r2(x1)}" y2="${r2(dy)}" stroke="var(--d-border)" stroke-width="1.2" stroke-dasharray="5 4"/>`);
203
+ }
204
+ out.push(`<rect x="${r2(lx - 6)}" y="${r2(ly - 11)}" width="${r2(w)}" height="17" rx="5" fill="var(--d-card)" stroke="var(--d-border)" stroke-width="1"/>`, `<text x="${r2(lx)}" y="${r2(ly + 1)}" font-size="10.5" font-weight="600" letter-spacing="0.4" fill="var(--d-muted)">${esc(text)}</text>`);
205
+ });
206
+ }
207
+ return out.join('');
208
+ };
209
+ const titleSvg = o.title
210
+ ? `<text x="${PAD}" y="${PAD + 16}" font-size="18" font-weight="600" letter-spacing="-0.02em" fill="var(--d-ink)">${esc(o.title)}</text>`
211
+ : '';
212
+ const headSvg = placed.map((p) => headerBox(p.box.x, p.box.y, p.box.w, p.label, p.sub, p.color, o.interactive, p.id)).join('');
213
+ const spec = { type: 'seq', title: o.title, participants: o.nodes, messages: o.msgs };
214
+ const svg = svgDoc(width, height, 'seq', o.version, o.title ?? `sequence diagram, ${o.msgs.length} messages`, spec, o.skin, titleSvg + headSvg + fragSvg() + parts.join(''), o.tagQuery, 'seq');
215
+ return { svg, version: o.version, cacheControl: o.cacheControl };
216
+ }
217
+ /**
218
+ * `/draw/seq` 入口:GET ?n=…&e=…(n= 参与方,e= 消息,顺序即时间)。
219
+ */
220
+ export function renderSeqFromUrl(url, interactive = false) {
221
+ const params = url.searchParams;
222
+ const nRaw = params.getAll('n');
223
+ if (!nRaw.length) {
224
+ throw new ApiError(400, `at least one participant is required. Example: /draw/seq?n=app;fe;Your app;r0c0&n=worker;be;Worker;r0c1&e=app;worker;GET /draw?type=pie`);
225
+ }
226
+ const nodes = parseNodes(nRaw);
227
+ const seen = new Set();
228
+ for (const n of nodes) {
229
+ if (seen.has(n.id))
230
+ throw new ApiError(400, `duplicate participant id "${n.id}"`);
231
+ seen.add(n.id);
232
+ }
233
+ const msgs = parseMessages(params.getAll('e'));
234
+ const frags = parseFrags(params.getAll('f'), msgs.length);
235
+ const boundaries = parseBoundaries(params.getAll('b'), seen);
236
+ const v = parseInt(params.get('v') ?? '1', 10) || 1;
237
+ const skin = resolveSkin('sankey', params.get('t'), schemeParam(params));
238
+ return renderSeqCore({
239
+ nodes, msgs, frags, boundaries, tagQuery: url.search,
240
+ title: params.get('title')?.trim() || undefined,
241
+ interactive,
242
+ version: v,
243
+ cacheControl: 'public, max-age=300',
244
+ skin,
245
+ minW: clampInt(params, 'w', 0, 200, 2400),
246
+ minH: clampInt(params, 'h', 0, 140, 2400),
247
+ });
248
+ }
@@ -1,3 +1,4 @@
1
+ import { type Mark } from '../specs/base.js';
1
2
  import type { Skin } from '../styles/types.js';
2
3
  export declare function esc(s: string): string;
3
4
  export declare function fmtNum(n: number): string;
@@ -8,14 +9,35 @@ export declare function niceStep(raw: number): number;
8
9
  export declare function snap(v: number, step: number): number;
9
10
  export declare function niceTicks(max: number, count?: number): number[];
10
11
  export declare function rangeTicks(min: number, max: number, count?: number): number[];
12
+ export declare function metaTag(template: string, version: number, spec: unknown): string;
11
13
  export declare function topLegend(items: readonly {
12
14
  name: string;
13
15
  color: string;
14
16
  index?: number;
15
17
  }[], x: number, y: number, anchor?: 'left' | 'right', shape?: 'circle' | 'square'): string;
18
+ export declare const TAG_RESERVE = 150;
19
+ export declare const EDIT_TAG_TEXT = "Edit @X-CMD";
20
+ /** 剥离角标的正则源(onepage/explore 内联/gantt 前端换图共用;rect 段可选兼容旧纯文本形) */
21
+ export declare const EDIT_TAG_STRIP_SRC = "<a [^>]*>(?:<rect[^>]*>(?:</rect>)?)?<text[^>]*>Edit @X-CMD<\\/text><\\/a>";
22
+ /** Edit @X-CMD 角标:蓝色链接胶囊(描边+淡底+同色文字),一眼可点;色值走 --d-link 明暗自适应。
23
+ * baselineY 为文字基线(与标题同基线),胶囊以其光学中心对齐 */
24
+ export declare function editTag(href: string, width: number, baselineY: number, fs: number): string;
25
+ /** 像素锚点已换算好的标注层;文字带底色描边保证压线可读,右缘放不下翻到圈左侧 */
26
+ export declare function marksLayer(pts: readonly {
27
+ x: number;
28
+ y: number;
29
+ text: string;
30
+ }[], width: number): string;
16
31
  export declare const sVar: (i: number) => string;
17
32
  export declare const onVar: (i: number) => string;
18
- export declare function svgDoc(width: number, height: number, template: string, version: number, aria: string, spec: unknown, skin: Skin, children: string): string;
33
+ /** 类目轴图标注锚点 → 像素:ax 按 labels 找列(找不到抛 400),y 数值映射并夹在绘图区内 */
34
+ export declare function markPoints(marks: readonly Mark[] | undefined, labels: readonly string[], xOf: (i: number) => number, yOf: (v: number) => number, clamp: readonly [number, number]): {
35
+ x: number;
36
+ y: number;
37
+ text: string;
38
+ }[];
39
+ export declare function skinStyle(skin: Skin): string;
40
+ export declare function svgDoc(width: number, height: number, template: string, version: number, aria: string, spec: unknown, skin: Skin, children: string, tagQuery?: string, tagKind?: string): string;
19
41
  export declare function editorialTitle(title: string, width: number, pad: number): {
20
42
  svg: string;
21
43
  height: number;
@@ -48,9 +70,19 @@ export interface RenderOpts {
48
70
  refLabel?: string;
49
71
  /** Interactive embedders (/explore): emit data-tip on data shapes for client tooltips */
50
72
  interactive?: boolean;
73
+ /** 标注层(?mark=锚;值;文字,可重复);undefined=无标注;[] 也不会画任何东西 */
74
+ marks?: Mark[];
51
75
  }
52
76
  export declare function textW(s: string, fs: number): number;
53
77
  export declare function smoothPath(pts: [number, number][]): string;
78
+ /**
79
+ * 折线的角点改成圆角(x-cmd-hub/draw#116)。
80
+ *
81
+ * 尖角在数据图上很扎眼:一段折线的每个拐角都是一个小小的尖刺。
82
+ * 做法:每个拐角切掉一小段,拿二次贝塞尔补过去 —— 半径 r,
83
+ * 相邻两段短于 2r 就自动收小(免得弧画到线外面去)。
84
+ */
85
+ export declare function roundedPath(pts: readonly [number, number][], r?: number): string;
54
86
  export declare function onColor(hex: string): string;
55
87
  export declare class LabelPlacer {
56
88
  private boxes;
@@ -66,7 +98,7 @@ export declare function reserveEdges(placer: LabelPlacer, width: number, height:
66
98
  export declare function pushPoints(parts: string[], pts: readonly (readonly [number, number])[], color: string, rules: {
67
99
  points: 'filled' | 'hollow' | 'none';
68
100
  pointR: number;
69
- }): void;
101
+ }, tips?: readonly string[], series?: number): void;
70
102
  export declare function pushBarLabelsAllOrNothing(parts: string[], items: readonly {
71
103
  x: number;
72
104
  yt: number;