@x-cmd/draw 0.3.0 → 0.4.1

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 (121) hide show
  1. package/README.md +79 -297
  2. package/dist/lib.d.ts +26 -3
  3. package/dist/lib.js +31 -4
  4. package/dist/node/cli.js +1 -1
  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 +90 -3
  10. package/dist/render/archmap.js +174 -102
  11. package/dist/render/area.js +9 -7
  12. package/dist/render/banner.d.ts +8 -0
  13. package/dist/render/banner.js +204 -0
  14. package/dist/render/bar-grouped.js +3 -2
  15. package/dist/render/bar-stacked.js +3 -2
  16. package/dist/render/bar.js +3 -2
  17. package/dist/render/butterfly.d.ts +3 -0
  18. package/dist/render/butterfly.js +355 -0
  19. package/dist/render/calendar.d.ts +6 -0
  20. package/dist/render/calendar.js +448 -0
  21. package/dist/render/combo.js +3 -2
  22. package/dist/render/compass.d.ts +6 -0
  23. package/dist/render/compass.js +77 -0
  24. package/dist/render/dispatch.js +26 -1
  25. package/dist/render/echarts-ssr.d.ts +30 -0
  26. package/dist/render/echarts-ssr.js +337 -16
  27. package/dist/render/gantt.d.ts +11 -0
  28. package/dist/render/gantt.js +12 -19
  29. package/dist/render/gantt2.d.ts +24 -0
  30. package/dist/render/gantt2.js +198 -0
  31. package/dist/render/hbar.js +8 -4
  32. package/dist/render/icons.d.ts +3 -0
  33. package/dist/render/icons.js +78 -0
  34. package/dist/render/kinds.d.ts +11 -0
  35. package/dist/render/kinds.js +176 -0
  36. package/dist/render/ladder.d.ts +21 -0
  37. package/dist/render/ladder.js +230 -0
  38. package/dist/render/layout.d.ts +46 -0
  39. package/dist/render/layout.js +57 -0
  40. package/dist/render/line-multi.js +2 -2
  41. package/dist/render/line.js +2 -2
  42. package/dist/render/maps.d.ts +34 -0
  43. package/dist/render/maps.js +197 -2
  44. package/dist/render/mermaid.js +25 -6
  45. package/dist/render/mindmap.js +3 -2
  46. package/dist/render/onepage.d.ts +62 -0
  47. package/dist/render/onepage.js +670 -0
  48. package/dist/render/orgicon.d.ts +12 -0
  49. package/dist/render/orgicon.js +31 -0
  50. package/dist/render/png.js +3 -1
  51. package/dist/render/quadrant.d.ts +6 -0
  52. package/dist/render/quadrant.js +201 -0
  53. package/dist/render/query.d.ts +2 -0
  54. package/dist/render/query.js +100 -1
  55. package/dist/render/route.d.ts +86 -0
  56. package/dist/render/route.js +1077 -0
  57. package/dist/render/scatter.js +73 -7
  58. package/dist/render/seq.d.ts +41 -0
  59. package/dist/render/seq.js +248 -0
  60. package/dist/render/src-spec.d.ts +5 -0
  61. package/dist/render/src-spec.js +49 -0
  62. package/dist/render/svg.d.ts +16 -2
  63. package/dist/render/svg.js +85 -7
  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/us-states.js +4 -6
  80. package/dist/render/vendor/world-geo.d.ts +22 -0
  81. package/dist/render/vendor/world-geo.js +9 -0
  82. package/dist/render/vendor/world.d.ts +13 -0
  83. package/dist/render/vendor/world.js +12 -0
  84. package/dist/specs/base.d.ts +5 -0
  85. package/dist/specs/base.js +14 -1
  86. package/dist/specs/butterfly.d.ts +46 -0
  87. package/dist/specs/butterfly.js +241 -0
  88. package/dist/specs/calendar.d.ts +90 -0
  89. package/dist/specs/calendar.js +296 -0
  90. package/dist/specs/compass.d.ts +27 -0
  91. package/dist/specs/compass.js +111 -0
  92. package/dist/specs/index.d.ts +5 -0
  93. package/dist/specs/index.js +5 -0
  94. package/dist/specs/ladder.d.ts +43 -0
  95. package/dist/specs/ladder.js +268 -0
  96. package/dist/specs/quadrant.d.ts +41 -0
  97. package/dist/specs/quadrant.js +200 -0
  98. package/dist/specs/scatter.d.ts +14 -8
  99. package/dist/specs/scatter.js +54 -5
  100. package/dist/specs/table.d.ts +24 -0
  101. package/dist/specs/table.js +154 -0
  102. package/dist/store.d.ts +1 -1
  103. package/dist/store.js +1 -1
  104. package/dist/styles/butterfly.d.ts +2 -0
  105. package/dist/styles/butterfly.js +74 -0
  106. package/dist/styles/calendar.d.ts +2 -0
  107. package/dist/styles/calendar.js +51 -0
  108. package/dist/styles/compass.d.ts +2 -0
  109. package/dist/styles/compass.js +19 -0
  110. package/dist/styles/index.js +13 -0
  111. package/dist/styles/ladder.d.ts +3 -0
  112. package/dist/styles/ladder.js +66 -0
  113. package/dist/styles/quadrant.d.ts +2 -0
  114. package/dist/styles/quadrant.js +19 -0
  115. package/dist/styles/table.d.ts +2 -0
  116. package/dist/styles/table.js +12 -0
  117. package/dist/styles/types.d.ts +1 -0
  118. package/dist/styles/types.js +1 -0
  119. package/dist/types/dagre.d.ts +39 -0
  120. package/dist/types/dagre.js +3 -0
  121. package/package.json +17 -1
@@ -1,14 +1,33 @@
1
1
  import { type VersionInfo } from '../version.js';
2
2
  import { type Skin } from '../styles/index.js';
3
+ import { type RoutingEngine } from './route.js';
3
4
  import { type DrawResult } from './query.js';
4
5
  declare const TYPES: readonly ["ext", "fe", "be", "db", "cloud", "sec", "bus", "svc"];
5
- type NodeType = (typeof TYPES)[number];
6
- type EdgeVariant = 'plain' | 'main' | 'dash';
6
+ export type NodeType = (typeof TYPES)[number];
7
+ export declare const TYPE_COLOR: Partial<Record<NodeType, number>>;
8
+ export type EdgeVariant = 'plain' | 'main' | 'dash';
9
+ export declare const ID_RE: RegExp;
10
+ export declare const GRID_POS_RE: RegExp;
11
+ export declare const PX_POS_RE: RegExp;
12
+ export interface Box {
13
+ x: number;
14
+ y: number;
15
+ w: number;
16
+ h: number;
17
+ }
7
18
  export interface ArchNode {
8
19
  id: string;
9
20
  type: NodeType;
10
21
  label: string;
11
22
  sub?: string;
23
+ /** 图标(diagrams 图标库的名字,如 aws:ec2)—— 画在角标的位置 */
24
+ icon?: string;
25
+ /**
26
+ * 图标解析结果(data URI 或 SVG 片段)。渲染前填一次:内置图标库命中就用它,
27
+ * 调用方注入的图标优先(见 ArchOpts.icons)。公开仓自己不带第三方素材 ——
28
+ * 公司/机构图标那族(org:)在私有仓里,由调用方注入;查不到就画组图标。
29
+ */
30
+ iconData?: string;
12
31
  /** mermaid 源形状:方/菱(判定)/圆柱(存储)/圆角胶囊;缺省 rect */
13
32
  shape?: 'rect' | 'diamond' | 'cylinder' | 'round';
14
33
  grid?: {
@@ -33,13 +52,75 @@ export interface ArchEdge {
33
52
  export interface ArchBoundary {
34
53
  label: string;
35
54
  ids: string[];
55
+ /** 可选的色板编号(1–10):b=名称;id id…;9 —— v2 用它给边界上色,v1 不用 */
56
+ color?: number;
36
57
  }
37
- export declare function naturalSize(n: ArchNode): {
58
+ /**
59
+ * 切节点字段:末尾的空段丢掉(至少留 id;type;label 三段)。
60
+ * 这样 `n=id;type;label;;` 和 `n=id;type;label` 一样,不用作者数分号。
61
+ */
62
+ export declare function splitFields(v: string): string[];
63
+ /**
64
+ * 图标字段:provider:名字(aws:ec2 / azure:vm / gcp:gce / org:verisign)
65
+ *
66
+ * `org:` 是公司/机构图标 —— 那一族住在私有仓的内部图库里(商标图形不能公开分发),
67
+ * 公开请求查不到就画组图标(见 render/orgicon.ts)。其余前缀是云服务图标,公开可用。
68
+ */
69
+ export declare const ICON_FIELD_RE: RegExp;
70
+ export declare function parseNodes(raw: string[]): ArchNode[];
71
+ export declare function parseEdges(raw: string[], ids: Set<string>): ArchEdge[];
72
+ export declare function parseBoundaries(raw: string[], ids: Set<string>): ArchBoundary[];
73
+ export declare function naturalSize(n: ArchNode, scale?: number): {
38
74
  w: number;
39
75
  h: number;
40
76
  };
77
+ export interface Placed extends ArchNode {
78
+ box: Box;
79
+ color: number;
80
+ }
81
+ export interface GridOpts {
82
+ /** 轨道间距(默认 GAP_X / GAP_Y) */
83
+ gapX?: number;
84
+ gapY?: number;
85
+ /** 画布留白(默认 PAD) */
86
+ pad?: number;
87
+ /** 节点尺寸的量尺(默认 naturalSize) */
88
+ sizeOf?: (n: ArchNode) => {
89
+ w: number;
90
+ h: number;
91
+ };
92
+ /** 某一列之后的额外间距(下标=列号):给太宽的边标签腾地方;没给的列用 gapX */
93
+ gapAfter?: number[];
94
+ /** 连线:没写位置的节点会尽量落在邻居旁边(用得上就用) */
95
+ edges?: ArchEdge[];
96
+ }
97
+ export declare function packGrid(nodes: ArchNode[], gridCols: number, opts?: GridOpts): {
98
+ placed: Placed[];
99
+ W: number;
100
+ H: number;
101
+ };
102
+ export type Side = 'left' | 'right' | 'top' | 'bottom';
103
+ export declare function port(b: Box, side: Side, i: number, n: number): [number, number];
104
+ export declare function step(p: [number, number], side: Side, d: number): [number, number];
105
+ export interface Routed {
106
+ e: ArchEdge;
107
+ pts: [number, number][];
108
+ stroke: string;
109
+ width: number;
110
+ dash: string;
111
+ marker: string;
112
+ }
113
+ /**
114
+ * 走线:几何交给布线内核(见 render/route.ts),这里只管样式。
115
+ *
116
+ * 内核那套规矩:不同源的边不共用一段、不首尾相接;端口进出一组排、间距 ≥ 9px。
117
+ * (旧写法进出端口分开数 → 落同一个点;竖通道只避让盒子、不看别的线 →
118
+ * 两条边选了同一个通道,接成一根线。见 x-cmd-hub/draw#92。)
119
+ */
120
+ export declare function computeRoutes(placed: Placed[], edges: ArchEdge[], bounds?: Box[], routing?: RoutingEngine, dir?: 'LR' | 'TB'): Routed[];
41
121
  export type ArchStyle = 'base' | 'mono' | 'soft';
42
122
  export declare const ARCH_STYLES: ArchStyle[];
123
+ export declare function boundaryBox(byId: Map<string, Placed>, bd: ArchBoundary): Box;
43
124
  /**
44
125
  * Render an architecture map from a URL's query params (`/draw/archmap`).
45
126
  *
@@ -64,7 +145,13 @@ export interface ArchmapCoreOpts {
64
145
  aria?: string;
65
146
  /** 正交折线(默认,格位架构图)或直连线(mermaid 流程图:迎面边直连,零弯折) */
66
147
  edgeMode?: 'ortho' | 'straight';
148
+ /** 布线引擎(线怎么走)—— 不给就用库里那个基础版;调用方的事,不是 URL 参数 */
149
+ routing?: RoutingEngine;
67
150
  straightDir?: 'TB' | 'LR';
151
+ /** 原始 URL 查询串:角标直链 explore 落地页用(#44) */
152
+ tagQuery?: string;
153
+ /** 角标 explore 路径段(mermaid 复用本引擎时为 'mermaid') */
154
+ tagKind?: string;
68
155
  }
69
156
  export declare function renderArchmapCore(o: ArchmapCoreOpts): DrawResult;
70
157
  export {};
@@ -12,16 +12,18 @@
12
12
  import { ApiError } from '../specs/index.js';
13
13
  import { resolveVersion } from '../version.js';
14
14
  import { resolveSkin } from '../styles/index.js';
15
- import { esc, r2, sVar, segRectIntersect, svgDoc, textW } from './svg.js';
15
+ import { esc, r2, roundedPath, sVar, segRectIntersect, svgDoc, textW } from './svg.js';
16
+ import { routeEdges } from './route.js';
16
17
  import { clampInt, schemeParam } from './query.js';
17
18
  const TYPES = ['ext', 'fe', 'be', 'db', 'cloud', 'sec', 'bus', 'svc'];
18
19
  // 语义类型 → 系列色序号(ext 无色,走中性虚线框)
19
- const TYPE_COLOR = {
20
+ export const TYPE_COLOR = {
20
21
  fe: 0, be: 1, db: 2, cloud: 3, sec: 4, bus: 5, svc: 6,
21
22
  };
22
- const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
23
- const GRID_POS_RE = /^r(\d+)c(\d+)(?:w([1-3]))?(?:h([1-3]))?$/;
24
- const PX_POS_RE = /^p(\d+(?:\.\d+)?),(\d+(?:\.\d+)?)(?:,(\d+)x(\d+))?$/;
23
+ export const ID_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
24
+ export const GRID_POS_RE = /^r(\d+)c(\d+)(?:w([1-3]))?(?:h([1-3]))?$/;
25
+ // 负数要能写:像素位置可以是负的(球面图里的经度就是负的)
26
+ export const PX_POS_RE = /^p(-?\d+(?:\.\d+)?),(-?\d+(?:\.\d+)?)(?:,(\d+)x(\d+))?$/;
25
27
  const GAP_X = 30;
26
28
  const GAP_Y = 34;
27
29
  const PAD = 26;
@@ -31,19 +33,45 @@ const N_EXAMPLE = 'n=api;be;API Gateway;auth;r1c0w2';
31
33
  function bad(detail) {
32
34
  throw new ApiError(400, `${detail} Example: ${N_EXAMPLE}`);
33
35
  }
34
- function parseNodes(raw) {
36
+ /**
37
+ * 切节点字段:末尾的空段丢掉(至少留 id;type;label 三段)。
38
+ * 这样 `n=id;type;label;;` 和 `n=id;type;label` 一样,不用作者数分号。
39
+ */
40
+ export function splitFields(v) {
41
+ const f = v.split(';');
42
+ while (f.length > 3 && f[f.length - 1].trim() === '')
43
+ f.pop();
44
+ return f;
45
+ }
46
+ /**
47
+ * 图标字段:provider:名字(aws:ec2 / azure:vm / gcp:gce / org:verisign)
48
+ *
49
+ * `org:` 是公司/机构图标 —— 那一族住在私有仓的内部图库里(商标图形不能公开分发),
50
+ * 公开请求查不到就画组图标(见 render/orgicon.ts)。其余前缀是云服务图标,公开可用。
51
+ */
52
+ export const ICON_FIELD_RE = /^(?:aws|azure|gcp|org):[a-z0-9][a-z0-9-]*$/;
53
+ export function parseNodes(raw) {
35
54
  return raw.map((v, i) => {
36
- const f = v.split(';');
55
+ const f = splitFields(v);
37
56
  const where = `"n=${v}" (#${i + 1})`;
38
- if (f.length < 3 || f.length > 5)
39
- bad(`${where}: expected id;type;label[;sublabel][;pos] fields`);
57
+ if (f.length < 3 || f.length > 6)
58
+ bad(`${where}: expected id;type;label[;sublabel][;pos][;icon] fields`);
40
59
  const [id, type, label] = f;
41
- let sub = f[3];
42
- let pos = f[4];
43
- // 4 字段时第 4 段按形状判别:像格位/像素坐标 → pos,否则视作 sublabel
44
- if (f.length === 4 && (GRID_POS_RE.test(f[3]) || PX_POS_RE.test(f[3]))) {
45
- pos = f[3];
46
- sub = undefined;
60
+ // 图标按形状认(provider:name),拿掉之后剩下的还是「副标题 + 位置」的老规矩
61
+ const icon = f.slice(3).find((seg) => ICON_FIELD_RE.test(seg));
62
+ const rest = f.slice(3).filter((seg) => !ICON_FIELD_RE.test(seg));
63
+ let sub;
64
+ let pos;
65
+ if (rest.length === 1) {
66
+ // 一段:像格位/像素坐标 → pos,否则视作 sublabel
67
+ if (GRID_POS_RE.test(rest[0]) || PX_POS_RE.test(rest[0]))
68
+ pos = rest[0];
69
+ else
70
+ sub = rest[0];
71
+ }
72
+ else if (rest.length >= 2) {
73
+ sub = rest[0];
74
+ pos = rest[1];
47
75
  }
48
76
  if (!ID_RE.test(id))
49
77
  bad(`${where}: id must be alnum/dot/dash/underscore, not starting with a digit-punct`);
@@ -64,10 +92,10 @@ function parseNodes(raw) {
64
92
  px = { x: +p[1], y: +p[2], ...(p[3] ? { w: +p[3], h: +p[4] } : {}) };
65
93
  }
66
94
  }
67
- return { id, type: type, label: label.trim(), sub: sub?.trim() || undefined, grid, px };
95
+ return { id, type: type, label: label.trim(), sub: sub?.trim() || undefined, icon, grid, px };
68
96
  });
69
97
  }
70
- function parseEdges(raw, ids) {
98
+ export function parseEdges(raw, ids) {
71
99
  return raw.map((v, i) => {
72
100
  const f = v.split(';');
73
101
  const where = `"e=${v}" (#${i + 1})`;
@@ -87,30 +115,46 @@ function parseEdges(raw, ids) {
87
115
  return { from, to, label: label?.trim() || undefined, variant: va };
88
116
  });
89
117
  }
90
- function parseBoundaries(raw, ids) {
118
+ export function parseBoundaries(raw, ids) {
91
119
  return raw.map((v, i) => {
92
120
  const sep = v.indexOf(';');
93
121
  if (sep < 1)
94
122
  bad(`"b=${v}" (#${i + 1}): expected <label>;<id> <id> ...`);
95
123
  const label = v.slice(0, sep).trim();
96
- const members = v.slice(sep + 1).trim().split(/\s+/).filter(Boolean);
124
+ let rest = v.slice(sep + 1).trim();
125
+ // 可选的第三段:色板编号 1–10(b=名称;id id…;9)
126
+ let color;
127
+ const csep = rest.lastIndexOf(';');
128
+ if (csep > 0) {
129
+ const tail = rest.slice(csep + 1).trim();
130
+ if (/^\d{1,2}$/.test(tail)) {
131
+ const n = Number(tail);
132
+ if (n < 1 || n > 10)
133
+ bad(`"b=${v}": colour must be a palette number 1-10, got "${tail}"`);
134
+ color = n;
135
+ rest = rest.slice(0, csep).trim();
136
+ }
137
+ }
138
+ const members = rest.split(/\s+/).filter(Boolean);
97
139
  if (!label || !members.length)
98
140
  bad(`"b=${v}" (#${i + 1}): label and at least one member id required`);
99
141
  for (const m of members)
100
142
  if (!ids.has(m))
101
143
  bad(`"b=${v}": unknown node "${m}"`);
102
- return { label, ids: members };
144
+ return { label, ids: members, ...(color ? { color } : {}) };
103
145
  });
104
146
  }
105
147
  // 自然尺寸:label 13px 加左右内边距;副标 11px;盒高 40(带副标 56)
106
- export function naturalSize(n) {
107
- const w = Math.max(MIN_CELL_W, textW(n.label, 13) + 34, n.sub ? textW(n.sub, 11) + 34 : 0);
108
- const h = n.sub ? 56 : 40;
148
+ export function naturalSize(n, scale = 1) {
149
+ const w = Math.max(MIN_CELL_W * scale, textW(n.label, 13 * scale) + 34 * scale, n.sub ? textW(n.sub, 11 * scale) + 34 * scale : 0);
150
+ const h = (n.sub ? 56 : 40) * scale;
109
151
  return { w: Math.min(w, 360), h };
110
152
  }
111
- // auto 轨道打包:单格成员先定轨道宽高,跨格节点不足则补差均摊到跨越轨道。
112
- // 返回 placed(含最终盒)与轨道联合画布尺寸;纯像素图无轨道,W/H 由调用侧从盒推。
113
- function packGrid(nodes, gridCols) {
153
+ export function packGrid(nodes, gridCols, opts = {}) {
154
+ const gapX = opts.gapX ?? GAP_X;
155
+ const gapY = opts.gapY ?? GAP_Y;
156
+ const pad = opts.pad ?? PAD;
157
+ const sizeOf = opts.sizeOf ?? ((n) => naturalSize(n));
114
158
  // 格子占用(显式先标,冲突即报);无 pos 节点自动落入首个空格(行优先,确定性,回程记录落位)
115
159
  const cell = new Map();
116
160
  const mark = (n) => {
@@ -126,18 +170,49 @@ function packGrid(nodes, gridCols) {
126
170
  for (const n of nodes)
127
171
  if (n.grid)
128
172
  mark(n);
173
+ // 没写位置的节点:落在邻居旁边(离邻居最近的空格);没邻居就按给的顺序排。
174
+ // grid= 给了列数 → 每行几格就按几格换行(文档里「强制分成 N 列」是这个意思)。
175
+ const wrap = gridCols > 0 ? gridCols : 12;
176
+ const cellOf = new Map();
177
+ for (const n of nodes)
178
+ if (n.grid)
179
+ cellOf.set(n.id, { row: n.grid.row, col: n.grid.col });
180
+ const freeCell = (want) => {
181
+ let best = null;
182
+ let bestD = Infinity;
183
+ for (let r = 0; r < 64; r++) {
184
+ for (let c = 0; c < wrap; c++) {
185
+ if (cell.has(`${r},${c}`))
186
+ continue;
187
+ // 目标格子附近的最优;没有目标就取最靠前的空格(行优先)
188
+ const d = want ? Math.abs(r - want.row) + Math.abs(c - want.col) : 0;
189
+ const key = d * 100000 + r * 100 + c;
190
+ if (key < bestD) {
191
+ bestD = key;
192
+ best = { row: r, col: c };
193
+ }
194
+ }
195
+ }
196
+ return best ?? { row: 0, col: 0 };
197
+ };
129
198
  for (const n of nodes) {
130
199
  if (n.grid || n.px)
131
200
  continue;
132
- search: for (let r = 0; r < 64; r++)
133
- for (let c = 0; c < 12; c++) {
134
- const k = `${r},${c}`;
135
- if (!cell.has(k)) {
136
- n.grid = { row: r, col: c, w: 1, h: 1 };
137
- cell.set(k, n.id);
138
- break search;
139
- }
201
+ // 邻居(已经定下位置的)格子的中位数 —— 没写位置的节点往那儿靠
202
+ const nb = (opts.edges ?? [])
203
+ .filter((e) => e.from === n.id || e.to === n.id)
204
+ .map((e) => cellOf.get(e.from === n.id ? e.to : e.from))
205
+ .filter((g) => !!g);
206
+ const want = nb.length
207
+ ? {
208
+ row: Math.round(nb.reduce((a, g) => a + g.row, 0) / nb.length),
209
+ col: Math.round(nb.reduce((a, g) => a + g.col, 0) / nb.length),
140
210
  }
211
+ : null;
212
+ const g = freeCell(want);
213
+ n.grid = { row: g.row, col: g.col, w: 1, h: 1 };
214
+ cell.set(`${g.row},${g.col}`, n.id);
215
+ cellOf.set(n.id, g);
141
216
  }
142
217
  const gridNodes = nodes.filter(n => n.grid);
143
218
  const rows = Math.max(0, ...gridNodes.map(n => n.grid.row + n.grid.h));
@@ -147,11 +222,11 @@ function packGrid(nodes, gridCols) {
147
222
  let colW = [];
148
223
  let rowH = [];
149
224
  if (cols > 0 && rows > 0) {
150
- colW = new Array(cols).fill(MIN_CELL_W);
151
- rowH = new Array(rows).fill(MIN_CELL_H);
225
+ colW = new Array(cols).fill(sizeOf({ id: '', type: 'be', label: '' }).w);
226
+ rowH = new Array(rows).fill(sizeOf({ id: '', type: 'be', label: '' }).h);
152
227
  const spans = [];
153
228
  for (const n of gridNodes) {
154
- const sz = naturalSize(n);
229
+ const sz = sizeOf(n);
155
230
  if (n.grid.w === 1)
156
231
  colW[n.grid.col] = Math.max(colW[n.grid.col], sz.w);
157
232
  if (n.grid.h === 1)
@@ -160,32 +235,32 @@ function packGrid(nodes, gridCols) {
160
235
  spans.push(n);
161
236
  }
162
237
  for (const n of spans) {
163
- const sz = naturalSize(n);
238
+ const sz = sizeOf(n);
164
239
  const { col, row, w, h } = n.grid;
165
- const needW = sz.w - (colW.slice(col, col + w).reduce((a, b) => a + b, 0) + GAP_X * (w - 1));
240
+ const needW = sz.w - (colW.slice(col, col + w).reduce((a, b) => a + b, 0) + gapX * (w - 1));
166
241
  if (needW > 0)
167
242
  for (let c = col; c < col + w; c++)
168
243
  colW[c] += needW / w;
169
- const needH = sz.h - (rowH.slice(row, row + h).reduce((a, b) => a + b, 0) + GAP_Y * (h - 1));
244
+ const needH = sz.h - (rowH.slice(row, row + h).reduce((a, b) => a + b, 0) + gapY * (h - 1));
170
245
  if (needH > 0)
171
246
  for (let r = row; r < row + h; r++)
172
247
  rowH[r] += needH / h;
173
248
  }
174
249
  trackX = new Array(cols);
175
250
  trackY = new Array(rows);
176
- let x = PAD;
251
+ let x = pad;
177
252
  for (let c = 0; c < cols; c++) {
178
253
  trackX[c] = x;
179
- x += colW[c] + GAP_X;
254
+ x += colW[c] + (opts.gapAfter?.[c] ?? gapX);
180
255
  }
181
- let y = PAD;
256
+ let y = pad;
182
257
  for (let r = 0; r < rows; r++) {
183
258
  trackY[r] = y;
184
- y += rowH[r] + GAP_Y;
259
+ y += rowH[r] + gapY;
185
260
  }
186
261
  }
187
- const W = cols > 0 && rows > 0 ? trackX[cols - 1] + colW[cols - 1] + PAD : 0;
188
- const H = cols > 0 && rows > 0 ? trackY[rows - 1] + rowH[rows - 1] + PAD : 0;
262
+ const W = cols > 0 && rows > 0 ? trackX[cols - 1] + colW[cols - 1] + pad : 0;
263
+ const H = cols > 0 && rows > 0 ? trackY[rows - 1] + rowH[rows - 1] + pad : 0;
189
264
  const placed = nodes.map(n => {
190
265
  if (n.grid) {
191
266
  const { row, col, w, h } = n.grid;
@@ -196,7 +271,7 @@ function packGrid(nodes, gridCols) {
196
271
  };
197
272
  return { ...n, box, color: TYPE_COLOR[n.type] ?? -1 };
198
273
  }
199
- const sz = naturalSize(n);
274
+ const sz = sizeOf(n);
200
275
  return { ...n, box: { x: n.px.x, y: n.px.y, w: n.px.w ?? sz.w, h: n.px.h ?? sz.h }, color: TYPE_COLOR[n.type] ?? -1 };
201
276
  });
202
277
  return { placed, W, H };
@@ -204,7 +279,7 @@ function packGrid(nodes, gridCols) {
204
279
  const boxCx = (b) => b.x + b.w / 2;
205
280
  const boxCy = (b) => b.y + b.h / 2;
206
281
  // 端口:同面多边均匀扩散(第 i/n 条落在面长 (i+1)/(n+1) 处)
207
- function port(b, side, i, n) {
282
+ export function port(b, side, i, n) {
208
283
  const len = side === 'left' || side === 'right' ? b.h : b.w;
209
284
  const off = ((i + 1) / (n + 1) - 0.5) * len;
210
285
  switch (side) {
@@ -214,7 +289,7 @@ function port(b, side, i, n) {
214
289
  case 'bottom': return [boxCx(b) + off, b.y + b.h];
215
290
  }
216
291
  }
217
- function step(p, side, d) {
292
+ export function step(p, side, d) {
218
293
  switch (side) {
219
294
  case 'left': return [p[0] - d, p[1]];
220
295
  case 'right': return [p[0] + d, p[1]];
@@ -309,61 +384,36 @@ function straightRoutes(placed, edges, dir) {
309
384
  };
310
385
  });
311
386
  }
312
- function computeRoutes(placed, edges) {
387
+ /**
388
+ * 走线:几何交给布线内核(见 render/route.ts),这里只管样式。
389
+ *
390
+ * 内核那套规矩:不同源的边不共用一段、不首尾相接;端口进出一组排、间距 ≥ 9px。
391
+ * (旧写法进出端口分开数 → 落同一个点;竖通道只避让盒子、不看别的线 →
392
+ * 两条边选了同一个通道,接成一根线。见 x-cmd-hub/draw#92。)
393
+ */
394
+ export function computeRoutes(placed, edges, bounds = [], routing, dir = 'TB') {
313
395
  const byId = new Map(placed.map(p => [p.id, p]));
314
- const boxes = placed.map(p => p.box);
315
- const exitSeen = new Map();
316
- const entrySeen = new Map();
317
- const exitAt = [];
318
- const entryAt = [];
319
- const sides = edges.map(e => {
320
- const a = byId.get(e.from).box;
321
- const b = byId.get(e.to).box;
322
- const horiz = Math.abs(boxCx(b) - boxCx(a)) >= Math.abs(boxCy(b) - boxCy(a));
323
- const toRight = boxCx(b) >= boxCx(a);
324
- const down = boxCy(b) >= boxCy(a);
325
- return {
326
- exit: horiz ? (toRight ? 'right' : 'left') : down ? 'bottom' : 'top',
327
- entry: horiz ? (toRight ? 'left' : 'right') : down ? 'top' : 'bottom',
328
- };
329
- });
330
- edges.forEach((e, i) => {
331
- const ek = `${e.from}|${sides[i].exit}`;
332
- exitAt[i] = exitSeen.get(ek) ?? 0;
333
- exitSeen.set(ek, exitAt[i] + 1);
334
- const rk = `${e.to}|${sides[i].entry}`;
335
- entryAt[i] = entrySeen.get(rk) ?? 0;
336
- entrySeen.set(rk, entryAt[i] + 1);
337
- });
396
+ const ctx = {
397
+ nodes: placed,
398
+ boxes: new Map(placed.map(p => [p.id, p.box])),
399
+ edges,
400
+ bounds,
401
+ dir,
402
+ portBox: (id) => byId.get(id).box,
403
+ };
404
+ const paths = (routing ?? routeEdges)(ctx);
338
405
  return edges.map((e, i) => {
339
- const a = byId.get(e.from);
340
- const b = byId.get(e.to);
341
- const { exit, entry } = sides[i];
342
- const p0 = port(a.box, exit, exitAt[i], exitSeen.get(`${e.from}|${exit}`) ?? 1);
343
- const p4 = port(b.box, entry, entryAt[i], entrySeen.get(`${e.to}|${entry}`) ?? 1);
344
- const OUT = 14;
345
- const p1 = step(p0, exit, OUT);
346
- const p3 = step(p4, entry, OUT);
347
- let pts;
348
- if (exit === 'left' || exit === 'right') {
349
- const mid = nudgeMid('v', (p1[0] + p3[0]) / 2, p1, p3, a.box, b.box, boxes);
350
- pts = [p0, p1, [mid, p1[1]], [mid, p3[1]], p3, p4];
351
- }
352
- else {
353
- const mid = nudgeMid('h', (p1[1] + p3[1]) / 2, p1, p3, a.box, b.box, boxes);
354
- pts = [p0, p1, [p1[0], mid], [p3[0], mid], p3, p4];
355
- }
356
406
  const style = e.variant === 'main'
357
407
  ? { stroke: 'var(--d-ink)', width: 1.8, marker: 'am-m', dash: '' }
358
408
  : e.variant === 'dash'
359
409
  ? { stroke: 'var(--d-faint)', width: 1.4, marker: 'am-d', dash: ' stroke-dasharray="5 4"' }
360
410
  : { stroke: 'var(--d-muted)', width: 1.4, marker: 'am-p', dash: '' };
361
- return { e, pts, ...style };
411
+ return { e, pts: paths[i] ?? [], ...style };
362
412
  });
363
413
  }
364
414
  function drawRoutes(routed, interactive = false, style = 'base', byId) {
365
415
  return routed.map(rt => {
366
- const d = rt.pts.map((p, j) => `${j === 0 ? 'M' : 'L'}${r2(p[0])} ${r2(p[1])}`).join('');
416
+ const d = roundedPath(rt.pts, 10);
367
417
  const ia = interactive ? ` data-from="${esc(rt.e.from)}" data-to="${esc(rt.e.to)}"` : '';
368
418
  let stroke = rt.stroke;
369
419
  let width = rt.width;
@@ -407,7 +457,13 @@ function drawEdgeLabels(routed, avoid, interactive = false) {
407
457
  const attrs = place.horiz
408
458
  ? `x="${r2(place.p[0])}" y="${r2(place.p[1] + (place.mirror ? 14 : -6))}" text-anchor="middle"`
409
459
  : `x="${r2(place.p[0] + (place.mirror ? -6 : 6))}" y="${r2(place.p[1] + 3.5)}" text-anchor="${place.mirror ? 'end' : 'start'}"`;
410
- out.push(`<text${ia} ${attrs} font-size="11" fill="var(--d-text)">${esc(text)}</text>`);
460
+ // 底衬:标签比两个节点之间的空档还宽时会压到节点上,给个画布色的胶囊,
461
+ // 线从底下过、字浮在上面 —— 和 v2 的边标签一个样。
462
+ const tx = place.horiz ? place.p[0] : place.p[0] + (place.mirror ? -6 : 6);
463
+ const ty = place.horiz ? place.p[1] + (place.mirror ? 14 : -6) : place.p[1] + 3.5;
464
+ const chipX = place.horiz ? tx - w / 2 : place.mirror ? tx - w : tx;
465
+ const chipY = place.horiz ? ty - 12 : ty - 11;
466
+ out.push(`<rect x="${r2(chipX)}" y="${r2(chipY)}" width="${r2(w)}" height="15" rx="4" fill="var(--d-card)" stroke="var(--d-border)" stroke-width="1"/>`, `<text${ia} ${attrs} font-size="11" fill="var(--d-text)">${esc(text)}</text>`);
411
467
  }
412
468
  return out.join('');
413
469
  }
@@ -453,7 +509,7 @@ function drawNode(n, interactive = false, degree = 0, style = 'base') {
453
509
  sub +
454
510
  `</g>`);
455
511
  }
456
- function boundaryBox(byId, bd) {
512
+ export function boundaryBox(byId, bd) {
457
513
  const boxes = bd.ids.map(id => byId.get(id).box);
458
514
  const x = Math.min(...boxes.map(o => o.x)) - 14;
459
515
  const y = Math.min(...boxes.map(o => o.y)) - 14;
@@ -549,21 +605,36 @@ export function renderArchmapFromUrl(url, interactive = false) {
549
605
  const style = tParam === 'mono' || tParam === 'soft' ? tParam : 'base';
550
606
  const skin = resolveSkin('sankey', style === 'base' ? tParam : null, schemeParam(params));
551
607
  return renderArchmapCore({ nodes, edges, boundaries, title, style, interactive, gridCols, v, skin,
552
- minW: clampInt(params, 'w', 0, 200, 2000), minH: clampInt(params, 'h', 0, 140, 2000) });
608
+ minW: clampInt(params, 'w', 0, 200, 2000), minH: clampInt(params, 'h', 0, 140, 2000),
609
+ tagQuery: url.search });
553
610
  }
554
611
  export function renderArchmapCore(o) {
555
612
  const { placed, W, H } = packGrid(o.nodes, o.gridCols);
556
- const titleH = o.title ? 40 : 0;
613
+ // 无标题也留 30px 角标带(#44):Edit 胶囊占右上 y≈25–45,不留带会压住首行节点
614
+ const titleH = o.title ? 40 : 30;
557
615
  let width = Math.max(W, 320);
558
616
  let bodyH = H;
559
617
  for (const p of placed) { // 像素节点可能超出轨道画布
560
618
  width = Math.max(width, p.box.x + p.box.w + PAD);
561
619
  bodyH = Math.max(bodyH, p.box.y + p.box.h + PAD);
562
620
  }
621
+ // 分组框先算好:走线要避开它(绕行时别跑出这个框)
622
+ const byIdEarly = new Map(placed.map(p => [p.id, p]));
623
+ const bboxes = o.boundaries.map(bd => boundaryBox(byIdEarly, bd));
624
+ // 管线:路由 → 边界标签选角(避开走线) → 边标签避让(节点盒 ∪ 边界标签区)
625
+ const routed = o.edgeMode === 'straight'
626
+ ? straightRoutes(placed, o.edges, o.straightDir ?? 'TB')
627
+ : computeRoutes(placed, o.edges, bboxes, o.routing);
628
+ // 画布要盖住走线:反向边绕到节点外面(U 形),边标签又贴在走线上 ——
629
+ // 只按节点盒算尺寸,那一段会被裁掉(字看不全)。
630
+ for (const rt of routed) {
631
+ for (const p of rt.pts) {
632
+ width = Math.max(width, p[0] + PAD);
633
+ bodyH = Math.max(bodyH, p[1] + PAD);
634
+ }
635
+ }
563
636
  width = Math.max(width, o.minW ?? 0);
564
637
  const height = Math.max(bodyH + titleH, o.minH ?? 0);
565
- // 管线:路由 → 边界标签选角(避开走线) → 边标签避让(节点盒 ∪ 边界标签区)
566
- const routed = o.edgeMode === 'straight' ? straightRoutes(placed, o.edges, o.straightDir ?? 'TB') : computeRoutes(placed, o.edges);
567
638
  const byId = new Map(placed.map(p => [p.id, p]));
568
639
  const boxes = placed.map(p => p.box);
569
640
  const corners = o.boundaries.map(bd => boundaryLabelCorner(boundaryBox(byId, bd), bd.label.toUpperCase(), routed, boxes));
@@ -600,12 +671,13 @@ export function renderArchmapCore(o) {
600
671
  const body = iStyle + DEFS
601
672
  + drawBoundaries(placed, o.boundaries, corners, o.interactive)
602
673
  + drawRoutes(routed, o.interactive, o.style, byId)
603
- + drawEdgeLabels(routed, avoid, o.interactive)
604
- + placed.map(p => drawNode(p, o.interactive, degree.get(p.id) ?? 0, o.style)).join('');
674
+ + placed.map(p => drawNode(p, o.interactive, degree.get(p.id) ?? 0, o.style)).join('')
675
+ // 边标签画在节点之上:标签比空档宽时会伸进节点里,压在节点下面就看不见了
676
+ + drawEdgeLabels(routed, avoid, o.interactive);
605
677
  // 标题占位下移 + h 垫高的剩余空间上下均分(内容垂直居中,标题仍在顶部)
606
678
  const dy = titleH + (height - titleH - bodyH) / 2;
607
679
  const children = titleSvg + `<g id="am" transform="translate(0 ${r2(dy)})">` + body + `</g>`;
608
680
  const spec = { type: 'archmap', ...(o.title ? { title: o.title } : {}), nodes: o.nodes, edges: o.edges, boundaries: o.boundaries };
609
- const svg = svgDoc(width, height, 'archmap', o.v.version, o.aria ?? o.title ?? `architecture map, ${o.nodes.length} nodes`, spec, o.skin, children);
681
+ const svg = svgDoc(width, height, 'archmap', o.v.version, o.aria ?? o.title ?? `architecture map, ${o.nodes.length} nodes`, spec, o.skin, children, o.tagQuery, o.tagKind);
610
682
  return { svg, version: o.v.version, cacheControl: o.v.cacheControl };
611
683
  }
@@ -1,7 +1,7 @@
1
1
  // 面积图:行为由皮肤规则驱动(规范 面积图 1-3)。
2
2
  import { ApiError } from '../specs/index.js';
3
3
  import { card, TAB } from '../theme.js';
4
- import { esc, fmtFull, fmtNum, niceStep, niceTicks, r2, reserveBands, snap, smoothPath, trunc, LabelPlacer, pushLineLabelsAllOrNothing, pushPoints, toSegments, svgDoc, titleBlock, editorialTitle, yAxisGrid, axisTitleY, topLegend, findPeak, sVar, markPoints, marksLayer, } from './svg.js';
4
+ import { esc, fmtFull, fmtNum, niceStep, niceTicks, r2, reserveBands, snap, smoothPath, roundedPath, trunc, LabelPlacer, pushLineLabelsAllOrNothing, pushPoints, toSegments, svgDoc, titleBlock, editorialTitle, yAxisGrid, axisTitleY, topLegend, findPeak, sVar, markPoints, marksLayer, } from './svg.js';
5
5
  import { xOverhang, yTickInset } from './measure.js';
6
6
  import { HANDEE_WOFF2 } from '../styles/handlee.js';
7
7
  const SKETCH_FONT = "Handlee,'Comic Sans MS','Chalkboard SE','Comic Neue','Segoe Print',cursive";
@@ -107,8 +107,9 @@ export function renderArea(spec, o) {
107
107
  const n = spec.data.length;
108
108
  const xs = (i) => (n === 1 ? (left + right) / 2 : xFirst + ((right - xFirst) * i) / (n - 1));
109
109
  const pts = spec.data.map((d, i) => [xs(i), y(d.value)]);
110
- const path = rules.smooth ? smoothPath(pts) : `M${pts.map((p) => `${r2(p[0])} ${r2(p[1])}`).join('L')}`;
111
- const parts = [card(width, height, rules.canvas === 'plain')];
110
+ const path = rules.smooth ? smoothPath(pts) : roundedPath(pts);
111
+ const bg = card(width, height, rules.canvas === 'plain');
112
+ const parts = [];
112
113
  parts.push(`<defs><linearGradient id="dg-area" x1="0" y1="0" x2="0" y2="1">` +
113
114
  `<stop offset="0" stop-color="var(--d-s1)" stop-opacity="${rules.areaTop}"/>` +
114
115
  `<stop offset="1" stop-color="var(--d-s1)" stop-opacity="${rules.areaBottom}"/></linearGradient></defs>`);
@@ -156,7 +157,7 @@ export function renderArea(spec, o) {
156
157
  const mpts = markPoints(o.marks, spec.data.map((d) => d.label), xs, y, [contentTop, bottom]);
157
158
  if (mpts.length > 0)
158
159
  parts.push(marksLayer(mpts, width));
159
- return svgDoc(width, height, 'area', version, spec.title ?? 'area chart', spec, skin, headSvg + parts.join(''));
160
+ return svgDoc(width, height, 'area', version, spec.title ?? 'area chart', spec, skin, bg + headSvg + parts.join(''));
160
161
  }
161
162
  // 多系列面积(area-1):三遍绘制(面积 → 虚线描边 → 点)
162
163
  export function renderAreaMulti(spec, o) {
@@ -172,8 +173,9 @@ export function renderAreaMulti(spec, o) {
172
173
  const xs = (i) => (n === 1 ? (left + right) / 2 : xFirst + ((right - xFirst) * i) / (n - 1));
173
174
  const colors = spec.series.map((_, i) => sVar(i % skin.series.length));
174
175
  const allPts = spec.series.map((s) => s.values.map((v, i) => [xs(i), y(v)]));
175
- const pathOf = (pts) => rules.smooth ? smoothPath(pts) : `M${pts.map((p) => `${r2(p[0])} ${r2(p[1])}`).join('L')}`;
176
- const parts = [card(width, height, rules.canvas === 'plain')];
176
+ const pathOf = (pts) => rules.smooth ? smoothPath(pts) : roundedPath(pts);
177
+ const bg = card(width, height, rules.canvas === 'plain');
178
+ const parts = [];
177
179
  parts.push(`<defs>${spec.series.map((_, i) => `<linearGradient id="dg-area-${i}" x1="0" y1="0" x2="0" y2="1">` +
178
180
  `<stop offset="0" stop-color="${colors[i]}" stop-opacity="${rules.areaTop}"/>` +
179
181
  `<stop offset="1" stop-color="${colors[i]}" stop-opacity="${rules.areaBottom}"/></linearGradient>`).join('')}</defs>`);
@@ -221,7 +223,7 @@ export function renderAreaMulti(spec, o) {
221
223
  const mpts = markPoints(o.marks, spec.labels, xs, y, [contentTop, bottom]);
222
224
  if (mpts.length > 0)
223
225
  parts.push(marksLayer(mpts, width));
224
- return svgDoc(width, height, 'area', version, spec.title ?? 'area chart', spec, skin, headSvg + parts.join(''));
226
+ return svgDoc(width, height, 'area', version, spec.title ?? 'area chart', spec, skin, bg + headSvg + parts.join(''));
225
227
  }
226
228
  // 手绘风面积图(area-2):xkcd 滤镜 + Handlee 手写字体 + 端点标注
227
229
  function renderSketchArea(spec, o) {
@@ -0,0 +1,8 @@
1
+ import type { DrawResult } from './query.js';
2
+ export declare const BANNER_FACE_CSS: string;
3
+ /**
4
+ * GET /draw/x-cmd/release-banner?title=<slogan[|slogan2]>&version=<x.y.z>&cmd=<cmd>[&paper=<yellow|orange|pink|purple|green|cyan|blue|gray|apple>]
5
+ * x-cmd 命名空间的发布封面(1200×630);位图加 &format=png(og:image 尺寸,scale=2 为 retina)。
6
+ * @throws ApiError(400) with a corrective example on bad input
7
+ */
8
+ export declare function renderReleaseBannerFromUrl(url: URL): DrawResult;