@open-document/core 0.14.0 → 0.14.2
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.
- package/dist/{build-CyBlmrjS.js → build-I0cgoERP.js} +1 -1
- package/dist/{check-DUKDEem-.js → check-Dys96QSL.js} +3 -3
- package/dist/cli/bin.js +9 -9
- package/dist/{context-BPApOW9n.js → context-C-osJW5f.js} +1 -1
- package/dist/{dev-DrnOvsX3.js → dev-CC4PrIOC.js} +1 -1
- package/dist/{diff-BPMD2Knh.js → diff-DhutD4TJ.js} +2 -2
- package/dist/{export-DeVtL8aX.js → export-KrajVJO7.js} +3 -3
- package/dist/{import-WAgWsuOv.js → import-Yv34za3L.js} +3 -3
- package/dist/ops/index.js +2 -2
- package/dist/{ops-raK6424A.js → ops-Dux5HlkH.js} +2 -422
- package/dist/{preview-B8Vw9QCh.js → preview-7eqn9Wzf.js} +1 -1
- package/dist/{config-cNpYUpF6.js → session-BSbrC5gK.js} +510 -4
- package/dist/{templates-D9jAFJ8R.js → templates-s-VLTSRc.js} +3 -3
- package/dist/vite/index.js +1 -1
- package/package.json +6 -1
- package/src/agent/check-after-turn.ts +59 -0
- package/src/agent/detect.ts +158 -0
- package/src/agent/install.ts +73 -0
- package/src/agent/prompt.ts +175 -0
- package/src/agent/provider.ts +126 -0
- package/src/agent/providers/codex.ts +209 -0
- package/src/agent/providers/index.ts +7 -0
- package/src/agent/providers/sdk-types.ts +71 -0
- package/src/agent/runner.ts +392 -0
- package/src/agent/status.ts +64 -0
- package/src/agent/store.ts +271 -0
- package/src/agent/types.ts +174 -0
- package/src/app/components/agent/agent-panel.tsx +6 -1
- package/src/app/components/agent/transcript.tsx +111 -3
- package/src/app/lib/i18n-ja/agent-panel.ts +8 -0
- package/src/app/lib/i18n-ko/agent-panel.ts +8 -0
- package/src/app/lib/i18n-zh-cn/agent-panel.ts +8 -0
- package/src/app/lib/i18n-zh-tw/agent-panel.ts +8 -0
- package/src/app/lib/use-locale.ts +7 -0
- package/src/diagram/index.ts +46 -0
- package/src/diagram/layout.ts +627 -0
- package/src/diagram/parse.ts +335 -0
- package/src/diagram/render.ts +162 -0
- package/src/editing/placeholder-id.ts +2 -0
- package/src/app/lib/chart.test.ts +0 -123
- package/src/app/lib/docx/ooxml.test.ts +0 -484
- package/src/app/lib/flow-measure.test.ts +0 -30
- package/src/app/lib/flow.test.ts +0 -129
- package/src/app/lib/footnotes.test.tsx +0 -102
- package/src/app/lib/i18n.test.ts +0 -24
- package/src/app/lib/inspector/inline-edit.test.ts +0 -244
- package/src/app/lib/page-range.test.ts +0 -104
- package/src/app/lib/records.test.ts +0 -38
- package/src/app/lib/sdk.test.ts +0 -30
- package/src/app/lib/view-mode.test.ts +0 -46
|
@@ -0,0 +1,335 @@
|
|
|
1
|
+
export type Direction = 'TD' | 'LR';
|
|
2
|
+
|
|
3
|
+
export type NodeShape = 'rect' | 'round' | 'stadium' | 'diamond' | 'circle' | 'cylinder';
|
|
4
|
+
|
|
5
|
+
export type DiagramNode = {
|
|
6
|
+
id: string;
|
|
7
|
+
label: string;
|
|
8
|
+
shape: NodeShape;
|
|
9
|
+
subgraph?: string;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export type EdgeStyle = 'solid' | 'dashed' | 'thick';
|
|
13
|
+
|
|
14
|
+
export type DiagramEdge = {
|
|
15
|
+
from: string;
|
|
16
|
+
to: string;
|
|
17
|
+
label: string | null;
|
|
18
|
+
style: EdgeStyle;
|
|
19
|
+
/** A `---` link draws no arrowhead. */
|
|
20
|
+
arrow: boolean;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type DiagramSubgraph = {
|
|
24
|
+
id: string;
|
|
25
|
+
label: string;
|
|
26
|
+
nodeIds: string[];
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export type SequenceParticipant = {
|
|
30
|
+
id: string;
|
|
31
|
+
label: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type SequenceMessage = {
|
|
35
|
+
from: string;
|
|
36
|
+
to: string;
|
|
37
|
+
label: string;
|
|
38
|
+
style: EdgeStyle;
|
|
39
|
+
arrow: boolean;
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export type Diagram = {
|
|
43
|
+
kind?: 'flowchart' | 'sequence';
|
|
44
|
+
direction: Direction;
|
|
45
|
+
nodes: DiagramNode[];
|
|
46
|
+
edges: DiagramEdge[];
|
|
47
|
+
subgraphs?: DiagramSubgraph[];
|
|
48
|
+
participants?: SequenceParticipant[];
|
|
49
|
+
messages?: SequenceMessage[];
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
export class DiagramSyntaxError extends Error {
|
|
53
|
+
readonly line: number;
|
|
54
|
+
constructor(message: string, line: number) {
|
|
55
|
+
super(`line ${line}: ${message}`);
|
|
56
|
+
this.name = 'DiagramSyntaxError';
|
|
57
|
+
this.line = line;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const HEADER_RE = /^(?:flowchart|graph)(?:\s+(TB|TD|BT|LR|RL))?$/i;
|
|
62
|
+
const SEQ_HEADER_RE = /^sequenceDiagram$/i;
|
|
63
|
+
const SUBGRAPH_RE = /^subgraph\s+(?:([A-Za-z0-9_.-]+)\s*\[([\s\S]*?)\]|([\s\S]+))$/i;
|
|
64
|
+
const PARTICIPANT_RE = /^(?:participant|actor)\s+([A-Za-z0-9_.-]+)(?:\s+as\s+([\s\S]+))?$/i;
|
|
65
|
+
const SEQ_MSG_RE =
|
|
66
|
+
/^([A-Za-z0-9_.-]+?)\s*(-->>|--\)|-->|->|->>|-\))\s*([+-]?[A-Za-z0-9_.-]+)\s*:\s*([\s\S]*)$/;
|
|
67
|
+
|
|
68
|
+
/** `A[Label]`, `A(Label)`, `A([Label])`, `A[(Label)]`, `A{Label}`, `A((Label))`, or a bare `A`. */
|
|
69
|
+
const NODE_RE =
|
|
70
|
+
/^([A-Za-z0-9_.-]+)(?:(\(\(|\(\[|\[\(|\[|\(|\{)([\s\S]*?)(\)\)|\]\)|\)\]|\]|\)|\}))?$/;
|
|
71
|
+
|
|
72
|
+
const SHAPES: Record<string, NodeShape> = {
|
|
73
|
+
'[': 'rect',
|
|
74
|
+
'(': 'round',
|
|
75
|
+
'([': 'stadium',
|
|
76
|
+
'{': 'diamond',
|
|
77
|
+
'((': 'circle',
|
|
78
|
+
'[(': 'cylinder',
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Links, longest first: `-.->` must be tried before `-->` or the dash prefix
|
|
83
|
+
* would match and leave a stray dot in the label.
|
|
84
|
+
*/
|
|
85
|
+
const LINKS: Array<{ re: RegExp; style: EdgeStyle; arrow: boolean }> = [
|
|
86
|
+
{ re: /-\.->/, style: 'dashed', arrow: true },
|
|
87
|
+
{ re: /-\.-/, style: 'dashed', arrow: false },
|
|
88
|
+
{ re: /==>/, style: 'thick', arrow: true },
|
|
89
|
+
{ re: /===/, style: 'thick', arrow: false },
|
|
90
|
+
{ re: /-->/, style: 'solid', arrow: true },
|
|
91
|
+
{ re: /---/, style: 'solid', arrow: false },
|
|
92
|
+
];
|
|
93
|
+
|
|
94
|
+
function normalizeDirection(raw: string | undefined): Direction {
|
|
95
|
+
const value = (raw ?? 'TD').toUpperCase();
|
|
96
|
+
// Reversed axes are drawn in their natural direction; a proposal diagram
|
|
97
|
+
// gains nothing from BT/RL, and supporting them doubles the layout cases.
|
|
98
|
+
return value === 'LR' || value === 'RL' ? 'LR' : 'TD';
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function stripComment(line: string): string {
|
|
102
|
+
const at = line.indexOf('%%');
|
|
103
|
+
return at === -1 ? line : line.slice(0, at);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Splits `A --> B --> C` into consecutive pairs, keeping each link's own style. */
|
|
107
|
+
function splitChain(
|
|
108
|
+
text: string,
|
|
109
|
+
): Array<{ raw: string; link?: (typeof LINKS)[number]; label: string | null }> {
|
|
110
|
+
const parts: Array<{ raw: string; link?: (typeof LINKS)[number]; label: string | null }> = [];
|
|
111
|
+
let rest = text;
|
|
112
|
+
|
|
113
|
+
for (;;) {
|
|
114
|
+
let best: { index: number; link: (typeof LINKS)[number]; length: number } | null = null;
|
|
115
|
+
for (const link of LINKS) {
|
|
116
|
+
const match = link.re.exec(rest);
|
|
117
|
+
if (!match) continue;
|
|
118
|
+
if (!best || match.index < best.index) {
|
|
119
|
+
best = { index: match.index, link, length: match[0].length };
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (!best) {
|
|
123
|
+
parts.push({ raw: rest, label: null });
|
|
124
|
+
return parts;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const head = rest.slice(0, best.index);
|
|
128
|
+
let tail = rest.slice(best.index + best.length);
|
|
129
|
+
|
|
130
|
+
let label: string | null = null;
|
|
131
|
+
const labelled = /^\s*\|([\s\S]*?)\|/.exec(tail);
|
|
132
|
+
if (labelled) {
|
|
133
|
+
label = labelled[1].trim();
|
|
134
|
+
tail = tail.slice(labelled[0].length);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
parts.push({ raw: head, link: best.link, label });
|
|
138
|
+
rest = tail;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function parseNode(raw: string, line: number): DiagramNode {
|
|
143
|
+
const text = raw.trim();
|
|
144
|
+
if (!text) throw new DiagramSyntaxError('empty node', line);
|
|
145
|
+
|
|
146
|
+
const match = NODE_RE.exec(text);
|
|
147
|
+
if (!match) throw new DiagramSyntaxError(`cannot read node "${text}"`, line);
|
|
148
|
+
|
|
149
|
+
const [, id, open, label] = match;
|
|
150
|
+
if (!open) return { id, label: id, shape: 'rect' };
|
|
151
|
+
|
|
152
|
+
const shape = SHAPES[open];
|
|
153
|
+
if (!shape) throw new DiagramSyntaxError(`unknown node shape "${open}"`, line);
|
|
154
|
+
return { id, label: unquote(label ?? ''), shape };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function unquote(label: string): string {
|
|
158
|
+
const trimmed = label.trim();
|
|
159
|
+
if (trimmed.length > 1 && trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
|
160
|
+
return trimmed.slice(1, -1);
|
|
161
|
+
}
|
|
162
|
+
return trimmed;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function parseSequence(lines: string[]): Diagram {
|
|
166
|
+
const participants = new Map<string, SequenceParticipant>();
|
|
167
|
+
const messages: SequenceMessage[] = [];
|
|
168
|
+
|
|
169
|
+
const ensureParticipant = (id: string, label?: string) => {
|
|
170
|
+
const cleanId = id.replace(/^[+-]/, '');
|
|
171
|
+
const existing = participants.get(cleanId);
|
|
172
|
+
if (!existing) {
|
|
173
|
+
participants.set(cleanId, { id: cleanId, label: label ? unquote(label) : cleanId });
|
|
174
|
+
} else if (label && existing.label === existing.id) {
|
|
175
|
+
existing.label = unquote(label);
|
|
176
|
+
}
|
|
177
|
+
return cleanId;
|
|
178
|
+
};
|
|
179
|
+
|
|
180
|
+
lines.forEach((rawLine, index) => {
|
|
181
|
+
const lineNumber = index + 1;
|
|
182
|
+
const line = stripComment(rawLine).trim();
|
|
183
|
+
if (!line || SEQ_HEADER_RE.test(line) || /^autonumber$/i.test(line)) return;
|
|
184
|
+
|
|
185
|
+
const partMatch = PARTICIPANT_RE.exec(line);
|
|
186
|
+
if (partMatch) {
|
|
187
|
+
ensureParticipant(partMatch[1], partMatch[2]);
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const msgMatch = SEQ_MSG_RE.exec(line);
|
|
192
|
+
if (msgMatch) {
|
|
193
|
+
const from = ensureParticipant(msgMatch[1]);
|
|
194
|
+
const arrowToken = msgMatch[2];
|
|
195
|
+
const to = ensureParticipant(msgMatch[3]);
|
|
196
|
+
const label = msgMatch[4].trim();
|
|
197
|
+
const dashed = arrowToken.startsWith('--');
|
|
198
|
+
messages.push({
|
|
199
|
+
from,
|
|
200
|
+
to,
|
|
201
|
+
label,
|
|
202
|
+
style: dashed ? 'dashed' : 'solid',
|
|
203
|
+
arrow: true,
|
|
204
|
+
});
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
throw new DiagramSyntaxError(`cannot read sequence line "${line}"`, lineNumber);
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
if (participants.size === 0)
|
|
212
|
+
throw new DiagramSyntaxError('sequence diagram has no participants', 1);
|
|
213
|
+
|
|
214
|
+
const partList = [...participants.values()];
|
|
215
|
+
return {
|
|
216
|
+
kind: 'sequence',
|
|
217
|
+
direction: 'LR',
|
|
218
|
+
nodes: partList.map((p) => ({ id: p.id, label: p.label, shape: 'rect' })),
|
|
219
|
+
edges: messages.map((m) => ({
|
|
220
|
+
from: m.from,
|
|
221
|
+
to: m.to,
|
|
222
|
+
label: m.label || null,
|
|
223
|
+
style: m.style,
|
|
224
|
+
arrow: m.arrow,
|
|
225
|
+
})),
|
|
226
|
+
participants: partList,
|
|
227
|
+
messages,
|
|
228
|
+
};
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* A practical subset of Mermaid's flowchart and sequenceDiagram syntax — the
|
|
233
|
+
* shapes, subgraphs and links a report actually uses. Agents already write this
|
|
234
|
+
* dialect fluently, which is the whole reason to borrow it rather than invent
|
|
235
|
+
* one; the renderer is ours, so the output follows the document's theme instead
|
|
236
|
+
* of Mermaid's.
|
|
237
|
+
*/
|
|
238
|
+
export function parseDiagram(source: string): Diagram {
|
|
239
|
+
const lines = source.split('\n');
|
|
240
|
+
const firstMeaningful = lines.map((l) => stripComment(l).trim()).find((l) => l.length > 0);
|
|
241
|
+
|
|
242
|
+
if (firstMeaningful && SEQ_HEADER_RE.test(firstMeaningful)) {
|
|
243
|
+
return parseSequence(lines);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
let direction: Direction = 'TD';
|
|
247
|
+
let sawHeader = false;
|
|
248
|
+
|
|
249
|
+
const nodes = new Map<string, DiagramNode>();
|
|
250
|
+
const edges: DiagramEdge[] = [];
|
|
251
|
+
const subgraphs: DiagramSubgraph[] = [];
|
|
252
|
+
const subgraphStack: DiagramSubgraph[] = [];
|
|
253
|
+
|
|
254
|
+
const remember = (node: DiagramNode) => {
|
|
255
|
+
const activeSubgraph = subgraphStack[subgraphStack.length - 1];
|
|
256
|
+
const existing = nodes.get(node.id);
|
|
257
|
+
// A later mention without a label must not blank out the declared one:
|
|
258
|
+
// `A[Start] --> B` then `B --> A` is ordinary.
|
|
259
|
+
if (!existing) {
|
|
260
|
+
const created: DiagramNode = activeSubgraph ? { ...node, subgraph: activeSubgraph.id } : node;
|
|
261
|
+
nodes.set(node.id, created);
|
|
262
|
+
} else {
|
|
263
|
+
if (existing.label === existing.id && node.label !== node.id) {
|
|
264
|
+
existing.label = node.label;
|
|
265
|
+
existing.shape = node.shape;
|
|
266
|
+
}
|
|
267
|
+
if (!existing.subgraph && activeSubgraph) {
|
|
268
|
+
existing.subgraph = activeSubgraph.id;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (activeSubgraph && !activeSubgraph.nodeIds.includes(node.id)) {
|
|
272
|
+
activeSubgraph.nodeIds.push(node.id);
|
|
273
|
+
}
|
|
274
|
+
return node.id;
|
|
275
|
+
};
|
|
276
|
+
|
|
277
|
+
lines.forEach((rawLine, index) => {
|
|
278
|
+
const lineNumber = index + 1;
|
|
279
|
+
const line = stripComment(rawLine).trim();
|
|
280
|
+
if (!line) return;
|
|
281
|
+
|
|
282
|
+
if (!sawHeader) {
|
|
283
|
+
const header = HEADER_RE.exec(line);
|
|
284
|
+
if (header) {
|
|
285
|
+
direction = normalizeDirection(header[1]);
|
|
286
|
+
sawHeader = true;
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
if (/^end$/i.test(line)) {
|
|
292
|
+
subgraphStack.pop();
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const subMatch = SUBGRAPH_RE.exec(line);
|
|
297
|
+
if (subMatch) {
|
|
298
|
+
const id = subMatch[1] ?? `sg-${subgraphs.length + 1}`;
|
|
299
|
+
const label = unquote(subMatch[2] ?? subMatch[3] ?? id);
|
|
300
|
+
const sg: DiagramSubgraph = { id, label, nodeIds: [] };
|
|
301
|
+
subgraphs.push(sg);
|
|
302
|
+
subgraphStack.push(sg);
|
|
303
|
+
return;
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
if (/^direction\s+(?:TB|TD|BT|LR|RL)$/i.test(line)) {
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const chain = splitChain(line);
|
|
311
|
+
if (chain.length === 1) {
|
|
312
|
+
remember(parseNode(chain[0].raw, lineNumber));
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
for (let i = 0; i < chain.length - 1; i += 1) {
|
|
317
|
+
const left = chain[i];
|
|
318
|
+
const right = chain[i + 1];
|
|
319
|
+
const from = remember(parseNode(left.raw, lineNumber));
|
|
320
|
+
const to = remember(parseNode(right.raw, lineNumber));
|
|
321
|
+
const link = left.link;
|
|
322
|
+
if (!link) throw new DiagramSyntaxError('malformed link', lineNumber);
|
|
323
|
+
edges.push({ from, to, label: left.label, style: link.style, arrow: link.arrow });
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
if (nodes.size === 0) throw new DiagramSyntaxError('diagram has no nodes', 1);
|
|
328
|
+
return {
|
|
329
|
+
kind: 'flowchart',
|
|
330
|
+
direction,
|
|
331
|
+
nodes: [...nodes.values()],
|
|
332
|
+
edges,
|
|
333
|
+
...(subgraphs.length > 0 ? { subgraphs } : {}),
|
|
334
|
+
};
|
|
335
|
+
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type LaidOutDiagram,
|
|
3
|
+
type LaidOutEdge,
|
|
4
|
+
type LaidOutLifeline,
|
|
5
|
+
type LaidOutNode,
|
|
6
|
+
type LaidOutSubgraph,
|
|
7
|
+
measureText,
|
|
8
|
+
} from './layout.ts';
|
|
9
|
+
|
|
10
|
+
export type RenderOptions = {
|
|
11
|
+
fontSize?: number;
|
|
12
|
+
/** Suffix for the arrowhead marker ids, so two diagrams on a page cannot collide. */
|
|
13
|
+
idSuffix?: string;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
const LINE_HEIGHT = 1.35;
|
|
17
|
+
|
|
18
|
+
function escapeXml(text: string): string {
|
|
19
|
+
return text
|
|
20
|
+
.replace(/&/g, '&')
|
|
21
|
+
.replace(/</g, '<')
|
|
22
|
+
.replace(/>/g, '>')
|
|
23
|
+
.replace(/"/g, '"');
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function subgraphMarkup(sg: LaidOutSubgraph, fontSize: number): string {
|
|
27
|
+
const titleSize = round(fontSize * 0.85);
|
|
28
|
+
return (
|
|
29
|
+
`<rect x="${round(sg.x)}" y="${round(sg.y)}" width="${round(sg.width)}" height="${round(sg.height)}" ` +
|
|
30
|
+
`style="rx: var(--od-radius, 4px)" fill="color-mix(in srgb, var(--od-accent, #2563eb) 5%, var(--od-bg, #ffffff))" ` +
|
|
31
|
+
`stroke="var(--od-rule, #d1d5db)" stroke-width="1" stroke-dasharray="4 3" />` +
|
|
32
|
+
`<text x="${round(sg.x + 10)}" y="${round(sg.y + titleSize + 5)}" ` +
|
|
33
|
+
`font-family="var(--od-font-heading, sans-serif)" font-size="${titleSize}" font-weight="600" ` +
|
|
34
|
+
`fill="var(--od-muted, #6b7280)">${escapeXml(sg.label)}</text>`
|
|
35
|
+
);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function lifelineMarkup(line: LaidOutLifeline): string {
|
|
39
|
+
return (
|
|
40
|
+
`<line x1="${round(line.x)}" y1="${round(line.y1)}" x2="${round(line.x)}" y2="${round(line.y2)}" ` +
|
|
41
|
+
`stroke="var(--od-rule, #d1d5db)" stroke-width="1.25" stroke-dasharray="4 4" />`
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Every colour and face is a `--od-*` variable rather than a literal, which is
|
|
47
|
+
* the entire reason this renderer exists: the drawing inherits the document's
|
|
48
|
+
* theme, in the viewer and in the PDF, instead of arriving with a palette of
|
|
49
|
+
* its own. Each carries a fallback, since a document without a `design` sets
|
|
50
|
+
* none of them and an unset `fill` paints the shapes solid black.
|
|
51
|
+
*/
|
|
52
|
+
function shapePath(node: LaidOutNode): string {
|
|
53
|
+
const { x, y, width: w, height: h } = node;
|
|
54
|
+
const common =
|
|
55
|
+
'fill="var(--od-bg, #ffffff)" stroke="var(--od-text, #16181d)" stroke-width="1.25"';
|
|
56
|
+
|
|
57
|
+
switch (node.shape) {
|
|
58
|
+
case 'diamond': {
|
|
59
|
+
const points = [
|
|
60
|
+
`${x + w / 2},${y}`,
|
|
61
|
+
`${x + w},${y + h / 2}`,
|
|
62
|
+
`${x + w / 2},${y + h}`,
|
|
63
|
+
`${x},${y + h / 2}`,
|
|
64
|
+
].join(' ');
|
|
65
|
+
return `<polygon points="${points}" ${common} />`;
|
|
66
|
+
}
|
|
67
|
+
case 'circle':
|
|
68
|
+
return `<ellipse cx="${x + w / 2}" cy="${y + h / 2}" rx="${w / 2}" ry="${h / 2}" ${common} />`;
|
|
69
|
+
case 'stadium':
|
|
70
|
+
return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${h / 2}" ry="${h / 2}" ${common} />`;
|
|
71
|
+
case 'cylinder': {
|
|
72
|
+
// A database: a body with an elliptical lid, the lid's front edge drawn
|
|
73
|
+
// again over the body so it reads as a rim rather than a flat top.
|
|
74
|
+
const ry = Math.min(8, h / 6);
|
|
75
|
+
const body =
|
|
76
|
+
`M${x},${y + ry} A${w / 2},${ry} 0 0 1 ${x + w},${y + ry} ` +
|
|
77
|
+
`L${x + w},${y + h - ry} A${w / 2},${ry} 0 0 1 ${x},${y + h - ry} Z`;
|
|
78
|
+
const rim = `M${x},${y + ry} A${w / 2},${ry} 0 0 0 ${x + w},${y + ry}`;
|
|
79
|
+
return `<path d="${body}" ${common} /><path d="${rim}" fill="none" stroke="var(--od-text, #16181d)" stroke-width="1.25" />`;
|
|
80
|
+
}
|
|
81
|
+
case 'round':
|
|
82
|
+
return `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="10" ry="10" ${common} />`;
|
|
83
|
+
default:
|
|
84
|
+
// `rx` as an attribute takes a length, not a CSS variable; as a style it takes both.
|
|
85
|
+
return `<rect x="${x}" y="${y}" width="${w}" height="${h}" style="rx: var(--od-radius, 2px)" ${common} />`;
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function nodeText(node: LaidOutNode, fontSize: number): string {
|
|
90
|
+
const centreY = node.y + node.height / 2;
|
|
91
|
+
const block = node.lines.length * fontSize * LINE_HEIGHT;
|
|
92
|
+
const firstBaseline = centreY - block / 2 + fontSize * 0.98;
|
|
93
|
+
|
|
94
|
+
return node.lines
|
|
95
|
+
.map((line, i) => {
|
|
96
|
+
const y = firstBaseline + i * fontSize * LINE_HEIGHT;
|
|
97
|
+
return (
|
|
98
|
+
`<text x="${node.x + node.width / 2}" y="${y}" text-anchor="middle" ` +
|
|
99
|
+
`font-family="var(--od-font-body, sans-serif)" font-size="${fontSize}" fill="var(--od-text, #16181d)">` +
|
|
100
|
+
`${escapeXml(line)}</text>`
|
|
101
|
+
);
|
|
102
|
+
})
|
|
103
|
+
.join('');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function edgePath(edge: LaidOutEdge, marker: string): string {
|
|
107
|
+
const d = edge.points
|
|
108
|
+
.map((point, i) => `${i === 0 ? 'M' : 'L'}${round(point.x)},${round(point.y)}`)
|
|
109
|
+
.join(' ');
|
|
110
|
+
|
|
111
|
+
const dash = edge.style === 'dashed' ? ' stroke-dasharray="5 4"' : '';
|
|
112
|
+
const width = edge.style === 'thick' ? 2.25 : 1.25;
|
|
113
|
+
const head = edge.arrow ? ` marker-end="url(#${marker})"` : '';
|
|
114
|
+
|
|
115
|
+
return (
|
|
116
|
+
`<path d="${d}" fill="none" stroke="var(--od-text, #16181d)" stroke-width="${width}"` +
|
|
117
|
+
`${dash} stroke-linejoin="round"${head} />`
|
|
118
|
+
);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function edgeLabel(edge: LaidOutEdge, fontSize: number): string {
|
|
122
|
+
if (!edge.labelAt || !edge.label) return '';
|
|
123
|
+
const size = fontSize * 0.85;
|
|
124
|
+
// The label sits on the line, so it needs the page colour painted behind it.
|
|
125
|
+
const width = measureText(edge.label, size) + 10;
|
|
126
|
+
return (
|
|
127
|
+
`<rect x="${round(edge.labelAt.x - width / 2)}" y="${round(edge.labelAt.y - size * 0.8)}" ` +
|
|
128
|
+
`width="${round(width)}" height="${round(size * 1.6)}" fill="var(--od-bg, #ffffff)" />` +
|
|
129
|
+
`<text x="${round(edge.labelAt.x)}" y="${round(edge.labelAt.y + size * 0.34)}" ` +
|
|
130
|
+
`text-anchor="middle" font-family="var(--od-font-body, sans-serif)" font-size="${size}" ` +
|
|
131
|
+
`fill="var(--od-muted, #6b7280)">${escapeXml(edge.label)}</text>`
|
|
132
|
+
);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
function round(value: number): number {
|
|
136
|
+
return Math.round(value * 100) / 100;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function renderDiagram(diagram: LaidOutDiagram, options: RenderOptions = {}): string {
|
|
140
|
+
const fontSize = options.fontSize ?? 13;
|
|
141
|
+
const marker = `od-arrow${options.idSuffix ? `-${options.idSuffix}` : ''}`;
|
|
142
|
+
|
|
143
|
+
const defs =
|
|
144
|
+
`<defs><marker id="${marker}" viewBox="0 0 10 10" refX="9" refY="5" ` +
|
|
145
|
+
`markerWidth="7" markerHeight="7" orient="auto-start-reverse">` +
|
|
146
|
+
`<path d="M0,1 L10,5 L0,9 z" fill="var(--od-text, #16181d)" /></marker></defs>`;
|
|
147
|
+
|
|
148
|
+
const body = [
|
|
149
|
+
...(diagram.subgraphs ?? []).map((sg) => subgraphMarkup(sg, fontSize)),
|
|
150
|
+
...(diagram.lifelines ?? []).map((ll) => lifelineMarkup(ll)),
|
|
151
|
+
...diagram.edges.map((edge) => edgePath(edge, marker)),
|
|
152
|
+
...diagram.nodes.map((node) => shapePath(node)),
|
|
153
|
+
...diagram.nodes.map((node) => nodeText(node, fontSize)),
|
|
154
|
+
...diagram.edges.map((edge) => edgeLabel(edge, fontSize)),
|
|
155
|
+
].join('');
|
|
156
|
+
|
|
157
|
+
return (
|
|
158
|
+
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${round(diagram.width)} ${round(diagram.height)}" ` +
|
|
159
|
+
`width="${round(diagram.width)}" height="${round(diagram.height)}" role="img">` +
|
|
160
|
+
`${defs}${body}</svg>`
|
|
161
|
+
);
|
|
162
|
+
}
|
|
@@ -1,123 +0,0 @@
|
|
|
1
|
-
import { describe, expect, it } from 'vitest';
|
|
2
|
-
import { formatChartValue, layoutChart, niceTicks, toNumber } from './chart';
|
|
3
|
-
|
|
4
|
-
const DATA = [
|
|
5
|
-
{ month: 'Jan', cost: 120, budget: 100 },
|
|
6
|
-
{ month: 'Feb', cost: 80, budget: 100 },
|
|
7
|
-
{ month: 'Mar', cost: 150, budget: 120 },
|
|
8
|
-
];
|
|
9
|
-
|
|
10
|
-
describe('niceTicks', () => {
|
|
11
|
-
it('steps by 1, 2 or 5 times a power of ten', () => {
|
|
12
|
-
expect(niceTicks(0, 150)).toEqual([0, 50, 100, 150]);
|
|
13
|
-
expect(niceTicks(0, 0.87)).toEqual([0, 0.2, 0.4, 0.6, 0.8, 1]);
|
|
14
|
-
expect(niceTicks(-30, 70)).toEqual([-40, -20, 0, 20, 40, 60, 80]);
|
|
15
|
-
});
|
|
16
|
-
|
|
17
|
-
it('opens a flat range so there is still an axis to draw', () => {
|
|
18
|
-
expect(niceTicks(0, 0)).toEqual([0, 1]);
|
|
19
|
-
expect(niceTicks(5, 5).length).toBeGreaterThan(1);
|
|
20
|
-
});
|
|
21
|
-
});
|
|
22
|
-
|
|
23
|
-
describe('values', () => {
|
|
24
|
-
it('reads CSV cells and typed numbers alike', () => {
|
|
25
|
-
expect(toNumber('1,204')).toBe(1204);
|
|
26
|
-
expect(toNumber(3.5)).toBe(3.5);
|
|
27
|
-
expect(toNumber('')).toBeNull();
|
|
28
|
-
expect(toNumber('n/a')).toBeNull();
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
it('formats like DataTable', () => {
|
|
32
|
-
expect(formatChartValue(0.123, 'percent')).toBe('12.3%');
|
|
33
|
-
expect(formatChartValue(1234.6, 'integer')).toBe((1235).toLocaleString());
|
|
34
|
-
expect(formatChartValue(7, (v) => `${v} ms`)).toBe('7 ms');
|
|
35
|
-
});
|
|
36
|
-
});
|
|
37
|
-
|
|
38
|
-
describe('layoutChart', () => {
|
|
39
|
-
const base = { data: DATA, x: 'month', width: 400, height: 200 } as const;
|
|
40
|
-
|
|
41
|
-
it('stands bars on zero and keeps them inside the plot', () => {
|
|
42
|
-
const chart = layoutChart({ ...base, type: 'bar', y: ['cost'] });
|
|
43
|
-
expect(chart.bars).toHaveLength(3);
|
|
44
|
-
const floor = chart.plot.y + chart.plot.height;
|
|
45
|
-
for (const bar of chart.bars) {
|
|
46
|
-
expect(bar.y).toBeGreaterThanOrEqual(chart.plot.y);
|
|
47
|
-
expect(bar.y + bar.height).toBeCloseTo(floor, 1);
|
|
48
|
-
}
|
|
49
|
-
// The tallest value draws the tallest bar.
|
|
50
|
-
const tallest = chart.bars.reduce((a, b) => (b.height > a.height ? b : a));
|
|
51
|
-
expect(tallest.value).toBe(150);
|
|
52
|
-
expect(chart.ticks[0]?.value).toBe(0);
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
it('groups series side by side, or stacks them', () => {
|
|
56
|
-
const grouped = layoutChart({ ...base, type: 'bar', y: ['cost', 'budget'] });
|
|
57
|
-
const [jan, janBudget] = grouped.bars;
|
|
58
|
-
expect(janBudget && jan && janBudget.x).toBeGreaterThan(jan?.x ?? 0);
|
|
59
|
-
expect(grouped.legend.map((item) => item.name)).toEqual(['cost', 'budget']);
|
|
60
|
-
|
|
61
|
-
const stacked = layoutChart({ ...base, type: 'bar', y: ['cost', 'budget'], stacked: true });
|
|
62
|
-
const [a, b] = stacked.bars;
|
|
63
|
-
expect(a?.x).toBe(b?.x);
|
|
64
|
-
expect(b && a && b.y + b.height).toBeCloseTo(a?.y ?? 0, 1);
|
|
65
|
-
// The axis has room for the stacked total, 270.
|
|
66
|
-
expect(stacked.ticks[stacked.ticks.length - 1]?.value).toBeGreaterThanOrEqual(270);
|
|
67
|
-
});
|
|
68
|
-
|
|
69
|
-
it('draws one line per series through the band centres', () => {
|
|
70
|
-
const chart = layoutChart({
|
|
71
|
-
...base,
|
|
72
|
-
type: 'line',
|
|
73
|
-
y: ['cost', 'budget'],
|
|
74
|
-
labels: { cost: 'Cost', budget: 'Budget' },
|
|
75
|
-
});
|
|
76
|
-
expect(chart.lines).toHaveLength(2);
|
|
77
|
-
expect(chart.lines[0]?.points.map((p) => p.x)).toEqual(chart.categories.map((c) => c.x));
|
|
78
|
-
expect(chart.legend.map((item) => item.name)).toEqual(['Cost', 'Budget']);
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
it('thins category labels that would collide', () => {
|
|
82
|
-
const many = Array.from({ length: 40 }, (_, i) => ({ day: `Day ${i + 1}`, n: i }));
|
|
83
|
-
const chart = layoutChart({
|
|
84
|
-
type: 'bar',
|
|
85
|
-
data: many,
|
|
86
|
-
x: 'day',
|
|
87
|
-
y: ['n'],
|
|
88
|
-
width: 300,
|
|
89
|
-
height: 160,
|
|
90
|
-
});
|
|
91
|
-
expect(chart.categories.length).toBeLessThan(40);
|
|
92
|
-
const xs = chart.categories.map((c) => c.x);
|
|
93
|
-
for (let i = 1; i < xs.length; i++) expect((xs[i] ?? 0) - (xs[i - 1] ?? 0)).toBeGreaterThan(30);
|
|
94
|
-
});
|
|
95
|
-
|
|
96
|
-
it('cuts a pie into shares that add up to the whole', () => {
|
|
97
|
-
const chart = layoutChart({ ...base, type: 'pie', y: ['cost'], values: true });
|
|
98
|
-
expect(chart.slices).toHaveLength(3);
|
|
99
|
-
expect(chart.slices.reduce((sum, s) => sum + s.share, 0)).toBeCloseTo(1, 6);
|
|
100
|
-
expect(chart.legend[0]?.name).toContain('Jan');
|
|
101
|
-
expect(chart.values.map((v) => v.text)).toEqual(['34.3%', '22.9%', '42.9%']);
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
it('draws a single-slice pie as a full circle', () => {
|
|
105
|
-
const chart = layoutChart({ ...base, type: 'pie', data: [DATA[0] ?? {}], y: ['cost'] });
|
|
106
|
-
expect(chart.slices[0]?.path).toMatch(/ a.* a/);
|
|
107
|
-
});
|
|
108
|
-
|
|
109
|
-
it('fills an area path closed down to the baseline for area charts', () => {
|
|
110
|
-
const chart = layoutChart({ ...base, type: 'area', y: ['cost'] });
|
|
111
|
-
expect(chart.lines).toHaveLength(1);
|
|
112
|
-
expect(chart.lines[0]?.areaPath).toMatch(/^M.* L.* Z$/);
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
it('lays out horizontal bars from left to right', () => {
|
|
116
|
-
const chart = layoutChart({ ...base, type: 'horizontal-bar', y: ['cost'] });
|
|
117
|
-
expect(chart.bars).toHaveLength(3);
|
|
118
|
-
for (const bar of chart.bars) {
|
|
119
|
-
expect(bar.x).toBeCloseTo(chart.plot.x, 1);
|
|
120
|
-
expect(bar.width).toBeGreaterThan(0);
|
|
121
|
-
}
|
|
122
|
-
});
|
|
123
|
-
});
|