@haposoft/cafekit 0.13.4 → 0.14.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 (114) hide show
  1. package/README.md +1 -2
  2. package/bin/lib/i18n.js +2 -2
  3. package/bin/lib/manifest.js +15 -0
  4. package/bin/lib/opencode-install.js +0 -14
  5. package/bin/phases/claude-runtime.js +4 -1
  6. package/bin/phases/claude-settings.js +38 -7
  7. package/package.json +1 -1
  8. package/src/claude/agents/ui-ux-designer.md +4 -4
  9. package/src/claude/hooks/__tests__/privacy-block.test.js +79 -0
  10. package/src/claude/hooks/__tests__/session-writeenv.test.js +68 -0
  11. package/src/claude/hooks/__tests__/spec-gate.test.js +270 -0
  12. package/src/claude/hooks/privacy-block.cjs +22 -2
  13. package/src/claude/hooks/session.cjs +5 -1
  14. package/src/claude/hooks/spec-gate.cjs +173 -0
  15. package/src/claude/hooks/spec-state.cjs +10 -17
  16. package/src/claude/hooks/task-scaffold-guard.cjs +4 -2
  17. package/src/claude/migration-manifest.json +5 -4
  18. package/src/claude/rules/skill-domain-routing.md +2 -3
  19. package/src/claude/rules/skill-workflow-routing.md +2 -3
  20. package/src/claude/rules/state-sync.md +4 -0
  21. package/src/claude/runtime.json +4 -0
  22. package/src/claude/scripts/validate-docs.cjs +4 -7
  23. package/src/claude/scripts/validate-spec-output.cjs +29 -9
  24. package/src/claude/settings/settings.json +4 -0
  25. package/src/claude/skills/ai-multimodal/.env.example +11 -13
  26. package/src/claude/skills/ai-multimodal/SKILL.md +1 -1
  27. package/src/claude/skills/ai-multimodal/references/audio-processing.md +25 -27
  28. package/src/claude/skills/ai-multimodal/references/video-analysis.md +23 -27
  29. package/src/claude/skills/ai-multimodal/references/vision-understanding.md +26 -26
  30. package/src/claude/skills/ai-multimodal/scripts/check_setup.py +1 -1
  31. package/src/claude/skills/ai-multimodal/scripts/gemini_batch_process.py +7 -9
  32. package/src/claude/skills/brainstorm/SKILL.md +1 -2
  33. package/src/claude/skills/docx/SKILL.md +1 -1
  34. package/src/claude/skills/frontend-design/SKILL.md +1 -1
  35. package/src/claude/skills/frontend-design/references/ai-multimodal-overview.md +4 -4
  36. package/src/claude/skills/frontend-design/references/analysis-techniques.md +3 -3
  37. package/src/claude/skills/frontend-design/references/asset-generation.md +2 -2
  38. package/src/claude/skills/frontend-design/references/design-extraction-overview.md +4 -4
  39. package/src/claude/skills/frontend-design/references/extraction-best-practices.md +3 -3
  40. package/src/claude/skills/frontend-design/references/technical-accessibility.md +1 -1
  41. package/src/claude/skills/frontend-design/references/technical-optimization.md +1 -1
  42. package/src/claude/skills/frontend-design/references/technical-overview.md +2 -2
  43. package/src/claude/skills/frontend-design/references/technical-workflows.md +6 -6
  44. package/src/claude/skills/frontend-design/references/visual-analysis-overview.md +3 -3
  45. package/src/claude/skills/inspect/SKILL.md +3 -3
  46. package/src/claude/skills/inspect/references/external-gemini-inspection.md +9 -9
  47. package/src/claude/skills/pdf/SKILL.md +1 -1
  48. package/src/claude/skills/pptx/SKILL.md +1 -1
  49. package/src/claude/skills/specs/SKILL.md +1 -1
  50. package/src/claude/skills/xlsx/SKILL.md +1 -1
  51. package/src/opencode/AGENTS.md +1 -2
  52. package/src/opencode/plugins/session.ts +2 -2
  53. package/src/opencode/plugins/spec-state.ts +244 -0
  54. package/src/opencode/plugins/task-scaffold-guard.ts +161 -0
  55. package/src/claude/scripts/browser-tool.cjs +0 -138
  56. package/src/claude/skills/generate-graph/LICENSE +0 -21
  57. package/src/claude/skills/generate-graph/README.md +0 -523
  58. package/src/claude/skills/generate-graph/SKILL.md +0 -429
  59. package/src/claude/skills/generate-graph/agentloop-core.svg +0 -101
  60. package/src/claude/skills/generate-graph/agents/openai.yaml +0 -4
  61. package/src/claude/skills/generate-graph/assets/samples/sample-style1-flat.png +0 -0
  62. package/src/claude/skills/generate-graph/assets/samples/sample-style2-dark.png +0 -0
  63. package/src/claude/skills/generate-graph/assets/samples/sample-style3-blueprint.png +0 -0
  64. package/src/claude/skills/generate-graph/assets/samples/sample-style4-notion.png +0 -0
  65. package/src/claude/skills/generate-graph/assets/samples/sample-style5-glass.png +0 -0
  66. package/src/claude/skills/generate-graph/assets/samples/sample-style6-claude.png +0 -0
  67. package/src/claude/skills/generate-graph/assets/samples/sample-style7-openai.png +0 -0
  68. package/src/claude/skills/generate-graph/fixtures/agent-memory-types-style4.json +0 -181
  69. package/src/claude/skills/generate-graph/fixtures/api-flow-style7.json +0 -40
  70. package/src/claude/skills/generate-graph/fixtures/mem0-style1.json +0 -297
  71. package/src/claude/skills/generate-graph/fixtures/microservices-style3.json +0 -64
  72. package/src/claude/skills/generate-graph/fixtures/multi-agent-style5.json +0 -45
  73. package/src/claude/skills/generate-graph/fixtures/system-architecture-style6.json +0 -48
  74. package/src/claude/skills/generate-graph/fixtures/tool-call-style2.json +0 -182
  75. package/src/claude/skills/generate-graph/package.json +0 -42
  76. package/src/claude/skills/generate-graph/references/icons.md +0 -281
  77. package/src/claude/skills/generate-graph/references/style-1-flat-icon.md +0 -108
  78. package/src/claude/skills/generate-graph/references/style-2-dark-terminal.md +0 -107
  79. package/src/claude/skills/generate-graph/references/style-3-blueprint.md +0 -113
  80. package/src/claude/skills/generate-graph/references/style-4-notion-clean.md +0 -94
  81. package/src/claude/skills/generate-graph/references/style-5-glassmorphism.md +0 -125
  82. package/src/claude/skills/generate-graph/references/style-6-claude-official.md +0 -209
  83. package/src/claude/skills/generate-graph/references/style-7-openai.md +0 -215
  84. package/src/claude/skills/generate-graph/references/style-diagram-matrix.md +0 -135
  85. package/src/claude/skills/generate-graph/references/svg-layout-best-practices.md +0 -100
  86. package/src/claude/skills/generate-graph/scripts/generate-diagram.sh +0 -157
  87. package/src/claude/skills/generate-graph/scripts/generate-from-template.py +0 -1556
  88. package/src/claude/skills/generate-graph/scripts/test-all-styles.sh +0 -135
  89. package/src/claude/skills/generate-graph/scripts/validate-svg.sh +0 -292
  90. package/src/claude/skills/generate-graph/templates/agent-architecture.svg +0 -28
  91. package/src/claude/skills/generate-graph/templates/architecture.svg +0 -23
  92. package/src/claude/skills/generate-graph/templates/comparison-matrix.svg +0 -14
  93. package/src/claude/skills/generate-graph/templates/data-flow.svg +0 -28
  94. package/src/claude/skills/generate-graph/templates/er-diagram.svg +0 -21
  95. package/src/claude/skills/generate-graph/templates/flowchart.svg +0 -21
  96. package/src/claude/skills/generate-graph/templates/sequence.svg +0 -20
  97. package/src/claude/skills/generate-graph/templates/state-machine.svg +0 -20
  98. package/src/claude/skills/generate-graph/templates/timeline.svg +0 -19
  99. package/src/claude/skills/generate-graph/templates/use-case.svg +0 -21
  100. package/src/claude/skills/impact-analysis/SKILL.md +0 -276
  101. package/src/claude/skills/impact-analysis/references/change-detection.md +0 -270
  102. package/src/claude/skills/impact-analysis/references/dependency-scouting.md +0 -338
  103. package/src/claude/skills/impact-analysis/references/edge-case-identification.md +0 -439
  104. package/src/claude/skills/impact-analysis/references/industry-techniques.md +0 -695
  105. package/src/claude/skills/impact-analysis/references/practical-techniques-guide.md +0 -753
  106. package/src/claude/skills/impact-analysis/references/project-detection.md +0 -704
  107. package/src/claude/skills/impact-analysis/references/react-native-customization.md +0 -508
  108. package/src/claude/skills/impact-analysis/references/report-template.md +0 -604
  109. package/src/claude/skills/impact-analysis/references/test-scenario-generation.md +0 -459
  110. package/src/claude/skills/impact-analysis/scripts/README.md +0 -476
  111. package/src/claude/skills/impact-analysis/scripts/ast-analyze.js +0 -403
  112. package/src/claude/skills/impact-analysis/scripts/calculate-risk.js +0 -475
  113. package/src/claude/skills/impact-analysis/scripts/find-dependencies.sh +0 -202
  114. package/src/claude/skills/impact-analysis/scripts/run-analysis.sh +0 -312
@@ -1,1556 +0,0 @@
1
- #!/usr/bin/env python3
2
- """
3
- Style-driven SVG diagram generator.
4
-
5
- Usage:
6
- python3 generate-from-template.py <template-type> <output-path> [data-json]
7
-
8
- This generator intentionally does more than "fill a template".
9
- It encodes the visual language from the documented style guides so the output
10
- tracks the showcase quality more closely than the previous generic renderer.
11
- """
12
-
13
- from __future__ import annotations
14
-
15
- import copy
16
- import json
17
- import math
18
- import os
19
- import re
20
- import sys
21
- from dataclasses import dataclass
22
- from typing import Dict, Iterable, List, Optional, Sequence, Tuple
23
- from xml.sax.saxutils import escape
24
-
25
- Point = Tuple[float, float]
26
- Bounds = Tuple[float, float, float, float]
27
-
28
- SCRIPT_DIR = os.path.dirname(__file__)
29
- TEMPLATE_DIR = os.path.join(SCRIPT_DIR, "..", "templates")
30
- DEFAULT_VIEWBOX = {
31
- "architecture": (960, 600),
32
- "data-flow": (960, 600),
33
- "flowchart": (960, 640),
34
- "sequence": (960, 700),
35
- "comparison": (960, 620),
36
- "timeline": (960, 520),
37
- "mind-map": (960, 620),
38
- "agent": (960, 700),
39
- "memory": (960, 720),
40
- "use-case": (960, 600),
41
- "class": (960, 700),
42
- "state-machine": (960, 620),
43
- "er-diagram": (960, 680),
44
- "network-topology": (960, 620),
45
- }
46
-
47
- FLOW_ALIASES = {
48
- "main": "control",
49
- "api": "control",
50
- "control": "control",
51
- "write": "write",
52
- "read": "read",
53
- "data": "data",
54
- "async": "async",
55
- "feedback": "feedback",
56
- "neutral": "neutral",
57
- }
58
-
59
- MARKER_IDS = {
60
- "control": "arrowA",
61
- "write": "arrowB",
62
- "read": "arrowC",
63
- "data": "arrowE",
64
- "async": "arrowF",
65
- "feedback": "arrowG",
66
- "neutral": "arrowH",
67
- }
68
-
69
- STYLE_PROFILES: Dict[int, Dict[str, object]] = {
70
- 1: {
71
- "name": "Flat Icon",
72
- "font_family": "'Helvetica Neue', Helvetica, Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif",
73
- "background": "#ffffff",
74
- "shadow": True,
75
- "title_align": "center",
76
- "title_fill": "#111827",
77
- "title_size": 30,
78
- "subtitle_fill": "#6b7280",
79
- "subtitle_size": 14,
80
- "node_fill": "#ffffff",
81
- "node_stroke": "#d1d5db",
82
- "node_radius": 10,
83
- "node_shadow": "url(#shadowSoft)",
84
- "section_fill": "none",
85
- "section_stroke": "#dbe5f1",
86
- "section_dash": "6 5",
87
- "section_label_fill": "#2563eb",
88
- "section_sub_fill": "#94a3b8",
89
- "title_divider": False,
90
- "section_upper": True,
91
- "arrow_width": 2.4,
92
- "arrow_colors": {
93
- "control": "#7c3aed",
94
- "write": "#10b981",
95
- "read": "#2563eb",
96
- "data": "#f97316",
97
- "async": "#7c3aed",
98
- "feedback": "#ef4444",
99
- "neutral": "#6b7280",
100
- },
101
- "arrow_label_bg": "#ffffff",
102
- "arrow_label_opacity": 0.94,
103
- "arrow_label_fill": "#6b7280",
104
- "type_label_fill": "#9ca3af",
105
- "type_label_size": 12,
106
- "text_primary": "#111827",
107
- "text_secondary": "#6b7280",
108
- "text_muted": "#94a3b8",
109
- "legend_fill": "#6b7280",
110
- },
111
- 2: {
112
- "name": "Dark Terminal",
113
- "font_family": "'SF Mono', 'Fira Code', Menlo, monospace",
114
- "background": "#0f172a",
115
- "shadow": False,
116
- "title_align": "center",
117
- "title_fill": "#e2e8f0",
118
- "title_size": 30,
119
- "subtitle_fill": "#94a3b8",
120
- "subtitle_size": 14,
121
- "node_fill": "#111827",
122
- "node_stroke": "#334155",
123
- "node_radius": 10,
124
- "node_shadow": "",
125
- "section_fill": "rgba(15,23,42,0.28)",
126
- "section_stroke": "#334155",
127
- "section_dash": "7 6",
128
- "section_label_fill": "#38bdf8",
129
- "section_sub_fill": "#64748b",
130
- "title_divider": False,
131
- "section_upper": True,
132
- "arrow_width": 2.3,
133
- "arrow_colors": {
134
- "control": "#a855f7",
135
- "write": "#22c55e",
136
- "read": "#38bdf8",
137
- "data": "#fb7185",
138
- "async": "#f59e0b",
139
- "feedback": "#f97316",
140
- "neutral": "#94a3b8",
141
- },
142
- "arrow_label_bg": "#0f172a",
143
- "arrow_label_opacity": 0.92,
144
- "arrow_label_fill": "#cbd5e1",
145
- "type_label_fill": "#64748b",
146
- "type_label_size": 12,
147
- "text_primary": "#e2e8f0",
148
- "text_secondary": "#94a3b8",
149
- "text_muted": "#64748b",
150
- "legend_fill": "#94a3b8",
151
- },
152
- 3: {
153
- "name": "Blueprint",
154
- "font_family": "'SF Mono', 'Fira Code', Menlo, monospace",
155
- "background": "#082f49",
156
- "shadow": False,
157
- "title_align": "center",
158
- "title_fill": "#e0f2fe",
159
- "title_size": 30,
160
- "subtitle_fill": "#7dd3fc",
161
- "subtitle_size": 14,
162
- "node_fill": "#0b3b5e",
163
- "node_stroke": "#67e8f9",
164
- "node_radius": 8,
165
- "node_shadow": "",
166
- "section_fill": "none",
167
- "section_stroke": "#0ea5e9",
168
- "section_dash": "6 4",
169
- "section_label_fill": "#67e8f9",
170
- "section_sub_fill": "#7dd3fc",
171
- "title_divider": False,
172
- "section_upper": True,
173
- "arrow_width": 2.1,
174
- "arrow_colors": {
175
- "control": "#67e8f9",
176
- "write": "#22d3ee",
177
- "read": "#38bdf8",
178
- "data": "#fde047",
179
- "async": "#c084fc",
180
- "feedback": "#fb7185",
181
- "neutral": "#bae6fd",
182
- },
183
- "arrow_label_bg": "#082f49",
184
- "arrow_label_opacity": 0.9,
185
- "arrow_label_fill": "#e0f2fe",
186
- "type_label_fill": "#7dd3fc",
187
- "type_label_size": 11,
188
- "text_primary": "#e0f2fe",
189
- "text_secondary": "#bae6fd",
190
- "text_muted": "#7dd3fc",
191
- "legend_fill": "#bae6fd",
192
- },
193
- 4: {
194
- "name": "Notion Clean",
195
- "font_family": "-apple-system, BlinkMacSystemFont, 'Segoe UI', 'Helvetica Neue', Arial, sans-serif",
196
- "background": "#ffffff",
197
- "shadow": False,
198
- "title_align": "left",
199
- "title_fill": "#111827",
200
- "title_size": 18,
201
- "subtitle_fill": "#9ca3af",
202
- "subtitle_size": 13,
203
- "node_fill": "#f9fafb",
204
- "node_stroke": "#e5e7eb",
205
- "node_radius": 4,
206
- "node_shadow": "",
207
- "section_fill": "none",
208
- "section_stroke": "#e5e7eb",
209
- "section_dash": "",
210
- "section_label_fill": "#9ca3af",
211
- "section_sub_fill": "#d1d5db",
212
- "title_divider": True,
213
- "section_upper": True,
214
- "arrow_width": 1.8,
215
- "arrow_colors": {
216
- "control": "#3b82f6",
217
- "write": "#3b82f6",
218
- "read": "#3b82f6",
219
- "data": "#3b82f6",
220
- "async": "#9ca3af",
221
- "feedback": "#9ca3af",
222
- "neutral": "#d1d5db",
223
- },
224
- "arrow_label_bg": "#ffffff",
225
- "arrow_label_opacity": 0.96,
226
- "arrow_label_fill": "#6b7280",
227
- "type_label_fill": "#9ca3af",
228
- "type_label_size": 11,
229
- "text_primary": "#111827",
230
- "text_secondary": "#374151",
231
- "text_muted": "#9ca3af",
232
- "legend_fill": "#6b7280",
233
- },
234
- 5: {
235
- "name": "Glassmorphism",
236
- "font_family": "'Helvetica Neue', Helvetica, Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif",
237
- "background": "#0f172a",
238
- "shadow": True,
239
- "title_align": "center",
240
- "title_fill": "#f8fafc",
241
- "title_size": 30,
242
- "subtitle_fill": "#cbd5e1",
243
- "subtitle_size": 14,
244
- "node_fill": "rgba(255,255,255,0.12)",
245
- "node_stroke": "rgba(255,255,255,0.28)",
246
- "node_radius": 18,
247
- "node_shadow": "url(#shadowGlass)",
248
- "section_fill": "rgba(255,255,255,0.05)",
249
- "section_stroke": "rgba(255,255,255,0.18)",
250
- "section_dash": "7 6",
251
- "section_label_fill": "#e2e8f0",
252
- "section_sub_fill": "#94a3b8",
253
- "title_divider": False,
254
- "section_upper": True,
255
- "arrow_width": 2.2,
256
- "arrow_colors": {
257
- "control": "#c084fc",
258
- "write": "#34d399",
259
- "read": "#60a5fa",
260
- "data": "#fb923c",
261
- "async": "#f472b6",
262
- "feedback": "#f59e0b",
263
- "neutral": "#cbd5e1",
264
- },
265
- "arrow_label_bg": "rgba(15,23,42,0.7)",
266
- "arrow_label_opacity": 1,
267
- "arrow_label_fill": "#e2e8f0",
268
- "type_label_fill": "#cbd5e1",
269
- "type_label_size": 12,
270
- "text_primary": "#f8fafc",
271
- "text_secondary": "#cbd5e1",
272
- "text_muted": "#94a3b8",
273
- "legend_fill": "#cbd5e1",
274
- },
275
- 6: {
276
- "name": "Claude Official",
277
- "font_family": "'Helvetica Neue', Helvetica, Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif",
278
- "background": "#f8f6f3",
279
- "shadow": False,
280
- "title_align": "left",
281
- "title_fill": "#141413",
282
- "title_size": 24,
283
- "subtitle_fill": "#8f8a80",
284
- "subtitle_size": 13,
285
- "node_fill": "#fffcf7",
286
- "node_stroke": "#d9d0c3",
287
- "node_radius": 10,
288
- "node_shadow": "",
289
- "section_fill": "none",
290
- "section_stroke": "#ded8cf",
291
- "section_dash": "5 4",
292
- "section_label_fill": "#8b7355",
293
- "section_sub_fill": "#b4aba0",
294
- "title_divider": True,
295
- "section_upper": True,
296
- "arrow_width": 2.0,
297
- "arrow_colors": {
298
- "control": "#d97757",
299
- "write": "#7b8b5c",
300
- "read": "#8c6f5a",
301
- "data": "#b45309",
302
- "async": "#9a6fb0",
303
- "feedback": "#d97757",
304
- "neutral": "#8f8a80",
305
- },
306
- "arrow_label_bg": "#f8f6f3",
307
- "arrow_label_opacity": 0.96,
308
- "arrow_label_fill": "#6b6257",
309
- "type_label_fill": "#a29a8f",
310
- "type_label_size": 11,
311
- "text_primary": "#141413",
312
- "text_secondary": "#6b6257",
313
- "text_muted": "#a29a8f",
314
- "legend_fill": "#6b6257",
315
- },
316
- 7: {
317
- "name": "OpenAI",
318
- "font_family": "'Helvetica Neue', Helvetica, Arial, 'PingFang SC', 'Microsoft YaHei', sans-serif",
319
- "background": "#ffffff",
320
- "shadow": False,
321
- "title_align": "left",
322
- "title_fill": "#0f172a",
323
- "title_size": 24,
324
- "subtitle_fill": "#64748b",
325
- "subtitle_size": 13,
326
- "node_fill": "#ffffff",
327
- "node_stroke": "#dce5e3",
328
- "node_radius": 14,
329
- "node_shadow": "",
330
- "section_fill": "none",
331
- "section_stroke": "#e2e8f0",
332
- "section_dash": "5 4",
333
- "section_label_fill": "#10a37f",
334
- "section_sub_fill": "#94a3b8",
335
- "title_divider": True,
336
- "section_upper": True,
337
- "arrow_width": 2.0,
338
- "arrow_colors": {
339
- "control": "#10a37f",
340
- "write": "#0f766e",
341
- "read": "#0891b2",
342
- "data": "#f59e0b",
343
- "async": "#64748b",
344
- "feedback": "#10a37f",
345
- "neutral": "#94a3b8",
346
- },
347
- "arrow_label_bg": "#ffffff",
348
- "arrow_label_opacity": 0.96,
349
- "arrow_label_fill": "#475569",
350
- "type_label_fill": "#94a3b8",
351
- "type_label_size": 11,
352
- "text_primary": "#0f172a",
353
- "text_secondary": "#475569",
354
- "text_muted": "#94a3b8",
355
- "legend_fill": "#475569",
356
- },
357
- }
358
-
359
-
360
- @dataclass
361
- class Node:
362
- node_id: str
363
- kind: str
364
- shape: str
365
- data: Dict[str, object]
366
- bounds: Bounds
367
- cx: float
368
- cy: float
369
-
370
-
371
- def style_value(style: Dict[str, object], key: str) -> object:
372
- return style[key]
373
-
374
-
375
- def to_float(value: object, default: float = 0.0) -> float:
376
- try:
377
- return float(value)
378
- except (TypeError, ValueError):
379
- return default
380
-
381
-
382
- def normalize_text(value: object) -> str:
383
- return escape(str(value)) if value is not None else ""
384
-
385
-
386
- def parse_style(raw: object) -> Tuple[int, Dict[str, object]]:
387
- if raw is None:
388
- index = 1
389
- elif isinstance(raw, int):
390
- index = raw
391
- else:
392
- text = str(raw).strip().lower()
393
- if text.isdigit():
394
- index = int(text)
395
- else:
396
- names = {profile["name"].lower(): key for key, profile in STYLE_PROFILES.items()}
397
- index = names.get(text, 1)
398
- if index not in STYLE_PROFILES:
399
- raise ValueError(f"Unsupported style: {raw}")
400
- return index, copy.deepcopy(STYLE_PROFILES[index])
401
-
402
-
403
- def parse_template_viewbox(template_type: str) -> Tuple[float, float]:
404
- template_path = os.path.join(TEMPLATE_DIR, f"{template_type}.svg")
405
- if os.path.exists(template_path):
406
- content = open(template_path, "r", encoding="utf-8").read()
407
- match = re.search(r'viewBox="0 0 ([0-9.]+) ([0-9.]+)"', content)
408
- if match:
409
- return float(match.group(1)), float(match.group(2))
410
- return DEFAULT_VIEWBOX.get(template_type, (960, 600))
411
-
412
-
413
- def render_defs(style_index: int, style: Dict[str, object]) -> str:
414
- marker_size = "8" if style_index == 4 else "10"
415
- marker_height = "6" if style_index == 4 else "7"
416
- ref_x = "7" if style_index == 4 else "9"
417
- ref_y = "3" if style_index == 4 else "3.5"
418
- color_map = style_value(style, "arrow_colors")
419
- marker_lines = []
420
- for key, color in color_map.items():
421
- marker_id = MARKER_IDS.get(key, "arrowA")
422
- marker_lines.append(
423
- f' <marker id="{marker_id}" markerWidth="{marker_size}" markerHeight="{marker_height}" '
424
- f'refX="{ref_x}" refY="{ref_y}" orient="auto">'
425
- )
426
- if style_index == 4:
427
- marker_lines.append(f' <polygon points="0 0, 8 3, 0 6" fill="{color}"/>')
428
- else:
429
- marker_lines.append(f' <polygon points="0 0, 10 3.5, 0 7" fill="{color}"/>')
430
- marker_lines.append(" </marker>")
431
-
432
- filters = []
433
- if style_value(style, "shadow"):
434
- filters.extend(
435
- [
436
- ' <filter id="shadowSoft" x="-20%" y="-20%" width="140%" height="160%">',
437
- ' <feDropShadow dx="0" dy="3" stdDeviation="6" flood-color="#0f172a" flood-opacity="0.12"/>',
438
- " </filter>",
439
- ' <filter id="shadowGlass" x="-20%" y="-20%" width="140%" height="160%">',
440
- ' <feDropShadow dx="0" dy="10" stdDeviation="16" flood-color="#020617" flood-opacity="0.28"/>',
441
- " </filter>",
442
- ]
443
- )
444
-
445
- if style_index == 3:
446
- filters.extend(
447
- [
448
- ' <pattern id="blueprintGrid" width="32" height="32" patternUnits="userSpaceOnUse">',
449
- ' <path d="M 32 0 L 0 0 0 32" fill="none" stroke="#0ea5e9" stroke-opacity="0.12" stroke-width="1"/>',
450
- " </pattern>",
451
- ]
452
- )
453
- if style_index == 2:
454
- filters.extend(
455
- [
456
- ' <linearGradient id="terminalGradient" x1="0%" y1="0%" x2="100%" y2="100%">',
457
- ' <stop offset="0%" stop-color="#0f0f1a"/>',
458
- ' <stop offset="100%" stop-color="#1a1a2e"/>',
459
- " </linearGradient>",
460
- ' <filter id="glowBlue" x="-30%" y="-30%" width="160%" height="160%">',
461
- ' <feDropShadow dx="0" dy="0" stdDeviation="5" flood-color="#3b82f6" flood-opacity="0.65"/>',
462
- " </filter>",
463
- ' <filter id="glowPurple" x="-30%" y="-30%" width="160%" height="160%">',
464
- ' <feDropShadow dx="0" dy="0" stdDeviation="5" flood-color="#a855f7" flood-opacity="0.72"/>',
465
- " </filter>",
466
- ' <filter id="glowGreen" x="-30%" y="-30%" width="160%" height="160%">',
467
- ' <feDropShadow dx="0" dy="0" stdDeviation="5" flood-color="#22c55e" flood-opacity="0.62"/>',
468
- " </filter>",
469
- ' <filter id="glowOrange" x="-30%" y="-30%" width="160%" height="160%">',
470
- ' <feDropShadow dx="0" dy="0" stdDeviation="5" flood-color="#f97316" flood-opacity="0.62"/>',
471
- " </filter>",
472
- ]
473
- )
474
-
475
- styles = [
476
- f" text {{ font-family: {style_value(style, 'font_family')}; }}",
477
- f" .title {{ font-size: {style_value(style, 'title_size')}px; font-weight: 700; fill: {style_value(style, 'title_fill')}; }}",
478
- f" .subtitle {{ font-size: {style_value(style, 'subtitle_size')}px; font-weight: 500; fill: {style_value(style, 'subtitle_fill')}; }}",
479
- f" .section {{ font-size: 13px; font-weight: 700; fill: {style_value(style, 'section_label_fill')}; letter-spacing: 1.4px; }}",
480
- f" .section-sub {{ font-size: 12px; font-weight: 500; fill: {style_value(style, 'section_sub_fill')}; }}",
481
- f" .node-title {{ font-size: 18px; font-weight: 700; fill: {style_value(style, 'text_primary')}; }}",
482
- f" .node-sub {{ font-size: 12px; font-weight: 500; fill: {style_value(style, 'text_secondary')}; }}",
483
- f" .node-type {{ font-size: {style_value(style, 'type_label_size')}px; font-weight: 700; fill: {style_value(style, 'type_label_fill')}; letter-spacing: 0.08em; }}",
484
- f" .arrow-label {{ font-size: 12px; font-weight: 600; fill: {style_value(style, 'arrow_label_fill')}; }}",
485
- f" .legend {{ font-size: 12px; font-weight: 500; fill: {style_value(style, 'legend_fill')}; }}",
486
- f" .footnote {{ font-size: 12px; font-weight: 500; fill: {style_value(style, 'text_muted')}; }}",
487
- ]
488
- return "\n".join(
489
- [" <defs>"] + marker_lines + filters + [" <style>"] + styles + [" </style>", " </defs>"]
490
- )
491
-
492
-
493
- def render_canvas(style_index: int, style: Dict[str, object], width: float, height: float) -> str:
494
- background = str(style_value(style, "background"))
495
- if style_index == 2:
496
- parts = [f' <rect width="{width}" height="{height}" fill="url(#terminalGradient)"/>']
497
- else:
498
- parts = [f' <rect width="{width}" height="{height}" fill="{background}"/>']
499
-
500
- return "\n".join(parts)
501
-
502
-
503
- def title_position(style: Dict[str, object], width: float) -> Tuple[float, str]:
504
- if style_value(style, "title_align") == "left":
505
- return 48.0, "start"
506
- return width / 2.0, "middle"
507
-
508
-
509
- def render_title_block(style: Dict[str, object], data: Dict[str, object], width: float) -> Tuple[str, float]:
510
- title = normalize_text(data.get("title", "Diagram"))
511
- subtitle = normalize_text(data.get("subtitle", ""))
512
- x, anchor = title_position(style, width)
513
- if anchor == "middle":
514
- parts = [f' <text x="{x}" y="56" text-anchor="{anchor}" class="title">{title}</text>']
515
- cursor_y = 82
516
- if subtitle:
517
- parts.append(f' <text x="{x}" y="{cursor_y}" text-anchor="{anchor}" class="subtitle">{subtitle}</text>')
518
- cursor_y += 24
519
- return "\n".join(parts), cursor_y + 10
520
-
521
- parts = [f' <text x="{x}" y="48" text-anchor="{anchor}" class="title">{title}</text>']
522
- cursor_y = 72
523
- if subtitle:
524
- parts.append(f' <text x="{x}" y="{cursor_y}" text-anchor="{anchor}" class="subtitle">{subtitle}</text>')
525
- cursor_y += 18
526
- if style_value(style, "title_divider"):
527
- parts.append(
528
- f' <line x1="48" y1="{cursor_y + 10}" x2="{width - 48}" y2="{cursor_y + 10}" '
529
- f'stroke="{style_value(style, "section_stroke")}" stroke-width="1"/>'
530
- )
531
- cursor_y += 26
532
- return "\n".join(parts), cursor_y + 8
533
-
534
-
535
- def render_window_controls(data: Dict[str, object], style_index: int, width: float) -> str:
536
- controls = data.get("window_controls")
537
- if not controls:
538
- return ""
539
- if controls is True:
540
- controls = ["#ef4444", "#f59e0b", "#10b981"]
541
- if style_index != 2:
542
- return ""
543
- cursor_x = 20.0
544
- lines = []
545
- for color in controls:
546
- lines.append(f' <circle cx="{cursor_x}" cy="20" r="5.5" fill="{color}"/>')
547
- cursor_x += 18
548
- return "\n".join(lines)
549
-
550
-
551
- def render_header_meta(data: Dict[str, object], style: Dict[str, object], width: float) -> str:
552
- meta_left = normalize_text(data.get("meta_left", ""))
553
- meta_center = normalize_text(data.get("meta_center", ""))
554
- meta_right = normalize_text(data.get("meta_right", ""))
555
- if not any([meta_left, meta_center, meta_right]):
556
- return ""
557
- fill = str(data.get("meta_fill", style_value(style, "text_muted")))
558
- size = to_float(data.get("meta_size", 11))
559
- lines = []
560
- if meta_left:
561
- lines.append(f' <text x="28" y="24" font-size="{size}" font-weight="600" fill="{fill}">{meta_left}</text>')
562
- if meta_center:
563
- lines.append(f' <text x="{width / 2}" y="24" text-anchor="middle" font-size="{size}" font-weight="600" fill="{fill}">{meta_center}</text>')
564
- if meta_right:
565
- lines.append(f' <text x="{width - 28}" y="24" text-anchor="end" font-size="{size}" font-weight="600" fill="{fill}">{meta_right}</text>')
566
- return "\n".join(lines)
567
-
568
-
569
- def render_blueprint_title_block(
570
- data: Dict[str, object],
571
- style: Dict[str, object],
572
- style_index: int,
573
- width: float,
574
- height: float,
575
- ) -> Tuple[str, Optional[Bounds]]:
576
- if style_index != 3:
577
- return "", None
578
- block = data.get("blueprint_title_block")
579
- if not block:
580
- return "", None
581
- block_width = to_float(block.get("width", 256))
582
- block_height = to_float(block.get("height", 92))
583
- x = to_float(block.get("x", width - block_width - 28))
584
- y = to_float(block.get("y", height - block_height - 18))
585
- title = normalize_text(block.get("title", data.get("title", "")))
586
- subtitle = normalize_text(block.get("subtitle", "SYSTEM ARCHITECTURE"))
587
- left_caption = normalize_text(block.get("left_caption", "REV: 1.0"))
588
- center_caption = normalize_text(block.get("center_caption", "AUTO-GENERATED"))
589
- right_caption = normalize_text(block.get("right_caption", "DWG: ARCH-001"))
590
- stroke = str(block.get("stroke", style_value(style, "section_stroke")))
591
- fill = str(block.get("fill", "#0b3552"))
592
- title_fill = str(block.get("title_fill", style_value(style, "text_primary")))
593
- sub_fill = str(block.get("subtitle_fill", style_value(style, "section_label_fill")))
594
- muted_fill = str(block.get("muted_fill", style_value(style, "text_muted")))
595
- lines = [
596
- f' <rect x="{x}" y="{y}" width="{block_width}" height="{block_height}" fill="{fill}" stroke="{stroke}" stroke-width="1.2"/>',
597
- f' <line x1="{x}" y1="{y + 18}" x2="{x + block_width}" y2="{y + 18}" stroke="{stroke}" stroke-width="1"/>',
598
- f' <line x1="{x}" y1="{y + 54}" x2="{x + block_width}" y2="{y + 54}" stroke="{stroke}" stroke-width="1"/>',
599
- f' <text x="{x + block_width / 2}" y="{y + 13}" text-anchor="middle" font-size="10" font-weight="600" fill="{muted_fill}">{subtitle}</text>',
600
- f' <text x="{x + block_width / 2}" y="{y + 42}" text-anchor="middle" font-size="18" font-weight="700" fill="{title_fill}">{title}</text>',
601
- f' <text x="{x + 12}" y="{y + 75}" font-size="9.5" font-weight="600" fill="{muted_fill}">{left_caption}</text>',
602
- f' <text x="{x + block_width / 2}" y="{y + 75}" text-anchor="middle" font-size="9.5" font-weight="600" fill="{sub_fill}">{center_caption}</text>',
603
- f' <text x="{x + block_width - 12}" y="{y + 75}" text-anchor="end" font-size="9.5" font-weight="600" fill="{muted_fill}">{right_caption}</text>',
604
- ]
605
- return "\n".join(lines), rectangle_bounds(x - 6, y - 6, block_width + 12, block_height + 12)
606
-
607
-
608
- def infer_shape(kind: str) -> str:
609
- mapping = {
610
- "rect": "rect",
611
- "double_rect": "rect",
612
- "cylinder": "rect",
613
- "document": "rect",
614
- "folder": "rect",
615
- "terminal": "rect",
616
- "hexagon": "rect",
617
- "circle_cluster": "cluster",
618
- "user_avatar": "rect",
619
- "bot": "rect",
620
- "speech": "rect",
621
- "icon_box": "rect",
622
- }
623
- return mapping.get(kind, "rect")
624
-
625
-
626
- def node_bounds(data: Dict[str, object]) -> Bounds:
627
- kind = str(data.get("kind", data.get("shape", "rect")))
628
- x = to_float(data.get("x"))
629
- y = to_float(data.get("y"))
630
- if kind == "circle":
631
- r = to_float(data.get("r", 50))
632
- return (x - r, y - r, x + r, y + r)
633
- width = to_float(data.get("width", 180))
634
- height = to_float(data.get("height", 76))
635
- return (x, y, x + width, y + height)
636
-
637
-
638
- def normalize_node(node_data: Dict[str, object], fallback_id: str) -> Node:
639
- kind = str(node_data.get("kind", node_data.get("shape", "rect")))
640
- bounds = node_bounds(node_data)
641
- left, top, right, bottom = bounds
642
- return Node(
643
- node_id=str(node_data.get("id", fallback_id)),
644
- kind=kind,
645
- shape=infer_shape(kind),
646
- data=node_data,
647
- bounds=bounds,
648
- cx=(left + right) / 2,
649
- cy=(top + bottom) / 2,
650
- )
651
-
652
-
653
- def anchor_on_side(node: Node, side: str) -> Point:
654
- left, top, right, bottom = node.bounds
655
- cx, cy = node.cx, node.cy
656
- side = side.lower()
657
- if side == "left":
658
- return (left, cy)
659
- if side == "right":
660
- return (right, cy)
661
- if side == "top":
662
- return (cx, top)
663
- if side == "bottom":
664
- return (cx, bottom)
665
- if side == "top-left":
666
- return (left, top)
667
- if side == "top-right":
668
- return (right, top)
669
- if side == "bottom-left":
670
- return (left, bottom)
671
- if side == "bottom-right":
672
- return (right, bottom)
673
- return (cx, cy)
674
-
675
-
676
- def anchor_point(node: Node, toward: Point, port: Optional[str] = None) -> Point:
677
- if port:
678
- return anchor_on_side(node, port)
679
- left, top, right, bottom = node.bounds
680
- dx = toward[0] - node.cx
681
- dy = toward[1] - node.cy
682
- width = right - left
683
- height = bottom - top
684
- if abs(dx) * height >= abs(dy) * width:
685
- return (right, node.cy) if dx >= 0 else (left, node.cy)
686
- return (node.cx, bottom) if dy >= 0 else (node.cx, top)
687
-
688
-
689
- def expand_bounds(bounds: Bounds, padding: float) -> Bounds:
690
- left, top, right, bottom = bounds
691
- return (left - padding, top - padding, right + padding, bottom + padding)
692
-
693
-
694
- def segment_hits_bounds(p1: Point, p2: Point, bounds: Bounds) -> bool:
695
- x1, y1 = p1
696
- x2, y2 = p2
697
- left, top, right, bottom = bounds
698
- eps = 1e-6
699
-
700
- if abs(y1 - y2) < eps:
701
- y = y1
702
- if not (top + eps < y < bottom - eps):
703
- return False
704
- seg_left = min(x1, x2)
705
- seg_right = max(x1, x2)
706
- overlap_left = max(seg_left, left)
707
- overlap_right = min(seg_right, right)
708
- if overlap_right - overlap_left <= eps:
709
- return False
710
- if abs(overlap_left - x1) < eps and abs(overlap_right - x1) < eps:
711
- return False
712
- if abs(overlap_left - x2) < eps and abs(overlap_right - x2) < eps:
713
- return False
714
- return True
715
-
716
- if abs(x1 - x2) < eps:
717
- x = x1
718
- if not (left + eps < x < right - eps):
719
- return False
720
- seg_top = min(y1, y2)
721
- seg_bottom = max(y1, y2)
722
- overlap_top = max(seg_top, top)
723
- overlap_bottom = min(seg_bottom, bottom)
724
- if overlap_bottom - overlap_top <= eps:
725
- return False
726
- if abs(overlap_top - y1) < eps and abs(overlap_bottom - y1) < eps:
727
- return False
728
- if abs(overlap_top - y2) < eps and abs(overlap_bottom - y2) < eps:
729
- return False
730
- return True
731
-
732
- return False
733
-
734
-
735
- def segment_axis(p1: Point, p2: Point) -> str:
736
- if abs(p1[1] - p2[1]) < 1e-6:
737
- return "horizontal"
738
- if abs(p1[0] - p2[0]) < 1e-6:
739
- return "vertical"
740
- return "other"
741
-
742
-
743
- def port_axis(port: Optional[str]) -> Optional[str]:
744
- if not port:
745
- return None
746
- port = port.lower()
747
- if port in {"left", "right"}:
748
- return "horizontal"
749
- if port in {"top", "bottom"}:
750
- return "vertical"
751
- return None
752
-
753
-
754
- def offset_point(point: Point, port: Optional[str], distance: float) -> Point:
755
- if not port:
756
- return point
757
- x, y = point
758
- port = port.lower()
759
- if port == "left":
760
- return (x - distance, y)
761
- if port == "right":
762
- return (x + distance, y)
763
- if port == "top":
764
- return (x, y - distance)
765
- if port == "bottom":
766
- return (x, y + distance)
767
- return point
768
-
769
-
770
- def route_length(points: Sequence[Point]) -> float:
771
- return sum(abs(x1 - x2) + abs(y1 - y2) for (x1, y1), (x2, y2) in zip(points, points[1:]))
772
-
773
-
774
- def route_uses_lane(points: Sequence[Point], value: float, axis: str, tolerance: float = 1.0) -> bool:
775
- if axis == "x":
776
- return any(abs(x - value) <= tolerance for x, _ in points)
777
- return any(abs(y - value) <= tolerance for _, y in points)
778
-
779
-
780
- def route_score(
781
- points: Sequence[Point],
782
- hint_x: Sequence[float],
783
- hint_y: Sequence[float],
784
- source_port: Optional[str],
785
- target_port: Optional[str],
786
- ) -> float:
787
- length = route_length(points)
788
- bends = max(0, len(points) - 2)
789
- score = length + bends * 22
790
- if len(points) >= 2 and source_port:
791
- first_axis = segment_axis(points[0], points[1])
792
- if first_axis != port_axis(source_port):
793
- score += 180
794
- if len(points) >= 2 and target_port:
795
- last_axis = segment_axis(points[-2], points[-1])
796
- if last_axis != port_axis(target_port):
797
- score += 180
798
- for lane in hint_x:
799
- score -= 28 if route_uses_lane(points, lane, "x") else 0
800
- for lane in hint_y:
801
- score -= 28 if route_uses_lane(points, lane, "y") else 0
802
- return score
803
-
804
-
805
- def simplify_points(points: Sequence[Point]) -> List[Point]:
806
- simplified: List[Point] = []
807
- for x, y in points:
808
- pt = (round(x, 2), round(y, 2))
809
- if simplified and pt == simplified[-1]:
810
- continue
811
- simplified.append(pt)
812
-
813
- collapsed: List[Point] = []
814
- for point in simplified:
815
- if len(collapsed) < 2:
816
- collapsed.append(point)
817
- continue
818
- x0, y0 = collapsed[-2]
819
- x1, y1 = collapsed[-1]
820
- x2, y2 = point
821
- if (x0 == x1 == x2) or (y0 == y1 == y2):
822
- collapsed[-1] = point
823
- else:
824
- collapsed.append(point)
825
- return collapsed
826
-
827
-
828
- def route_collides(points: Sequence[Point], obstacles: Sequence[Bounds]) -> bool:
829
- for p1, p2 in zip(points, points[1:]):
830
- for obstacle in obstacles:
831
- if segment_hits_bounds(p1, p2, obstacle):
832
- return True
833
- return False
834
-
835
-
836
- def build_orthogonal_route(
837
- start: Point,
838
- end: Point,
839
- obstacles: Sequence[Bounds],
840
- arrow_data: Dict[str, object],
841
- ) -> List[Point]:
842
- if arrow_data.get("route_points"):
843
- raw_points = [tuple(point) for point in arrow_data["route_points"]]
844
- return simplify_points([start] + [(float(x), float(y)) for x, y in raw_points] + [end])
845
-
846
- sx, sy = start
847
- ex, ey = end
848
- routing_padding = to_float(arrow_data.get("routing_padding", 24))
849
- port_clearance = to_float(arrow_data.get("port_clearance", max(18, routing_padding * 0.85)))
850
- source_port = str(arrow_data.get("source_port", "")).strip().lower() or None
851
- target_port = str(arrow_data.get("target_port", "")).strip().lower() or None
852
- inner_start = offset_point(start, source_port, port_clearance)
853
- inner_end = offset_point(end, target_port, port_clearance)
854
- ssx, ssy = inner_start
855
- eex, eey = inner_end
856
- expanded = [expand_bounds(bounds, routing_padding) for bounds in obstacles]
857
- hint_x = [to_float(value) for value in arrow_data.get("corridor_x", [])]
858
- hint_y = [to_float(value) for value in arrow_data.get("corridor_y", [])]
859
- lane_x = sorted({ssx, eex, round((ssx + eex) / 2, 2), *hint_x, *[b[0] for b in expanded], *[b[2] for b in expanded]})
860
- lane_y = sorted({ssy, eey, round((ssy + eey) / 2, 2), *hint_y, *[b[1] for b in expanded], *[b[3] for b in expanded]})
861
- if expanded:
862
- left_rail = min(b[0] for b in expanded) - 24
863
- right_rail = max(b[2] for b in expanded) + 24
864
- top_rail = min(b[1] for b in expanded) - 24
865
- bottom_rail = max(b[3] for b in expanded) + 24
866
- else:
867
- left_rail = min(ssx, eex) - 48
868
- right_rail = max(ssx, eex) + 48
869
- top_rail = min(ssy, eey) - 48
870
- bottom_rail = max(ssy, eey) + 48
871
-
872
- candidates = [
873
- [start, inner_start, inner_end, end],
874
- [start, inner_start, (eex, ssy), inner_end, end],
875
- [start, inner_start, (ssx, eey), inner_end, end],
876
- [start, inner_start, ((ssx + eex) / 2, ssy), ((ssx + eex) / 2, eey), inner_end, end],
877
- [start, inner_start, (ssx, (ssy + eey) / 2), (eex, (ssy + eey) / 2), inner_end, end],
878
- [start, inner_start, (left_rail, ssy), (left_rail, eey), inner_end, end],
879
- [start, inner_start, (right_rail, ssy), (right_rail, eey), inner_end, end],
880
- [start, inner_start, (ssx, top_rail), (eex, top_rail), inner_end, end],
881
- [start, inner_start, (ssx, bottom_rail), (eex, bottom_rail), inner_end, end],
882
- ]
883
- for x in lane_x:
884
- candidates.append([start, inner_start, (x, ssy), (x, eey), inner_end, end])
885
- for y in lane_y:
886
- candidates.append([start, inner_start, (ssx, y), (eex, y), inner_end, end])
887
- for x in hint_x:
888
- for y in hint_y:
889
- candidates.append([start, inner_start, (x, ssy), (x, y), (eex, y), inner_end, end])
890
-
891
- best_route: Optional[List[Point]] = None
892
- best_score = float("inf")
893
- for candidate in candidates:
894
- simplified = simplify_points(candidate)
895
- if route_collides(simplified, expanded):
896
- continue
897
- score = route_score(simplified, hint_x, hint_y, source_port, target_port)
898
- if score < best_score:
899
- best_score = score
900
- best_route = simplified
901
-
902
- if best_route is not None:
903
- return best_route
904
- return simplify_points([start, inner_start, (eex, ssy), inner_end, end])
905
-
906
-
907
- def choose_label_position(points: Sequence[Point]) -> Point:
908
- segments = list(zip(points, points[1:]))
909
- if not segments:
910
- return points[0]
911
- best = max(segments, key=lambda seg: abs(seg[0][0] - seg[1][0]) + abs(seg[0][1] - seg[1][1]))
912
- return ((best[0][0] + best[1][0]) / 2, (best[0][1] + best[1][1]) / 2)
913
-
914
-
915
- def color_for_flow(style: Dict[str, object], arrow_data: Dict[str, object]) -> str:
916
- if arrow_data.get("color"):
917
- return str(arrow_data["color"])
918
- flow = FLOW_ALIASES.get(str(arrow_data.get("flow", "control")).lower(), "control")
919
- return str(style_value(style, "arrow_colors")[flow])
920
-
921
-
922
- def marker_for_color(style: Dict[str, object], color: str, arrow_data: Dict[str, object]) -> str:
923
- if arrow_data.get("marker"):
924
- return f"url(#{arrow_data['marker']})"
925
- colors = style_value(style, "arrow_colors")
926
- for name, token in colors.items():
927
- if token == color:
928
- return f"url(#{MARKER_IDS.get(name, 'arrowA')})"
929
- return "url(#arrowA)"
930
-
931
-
932
- def render_label_badge(x: float, y: float, text: str, style: Dict[str, object]) -> str:
933
- width = max(36, len(text) * 7 + 14)
934
- bg = style_value(style, "arrow_label_bg")
935
- opacity = style_value(style, "arrow_label_opacity")
936
- return "\n".join(
937
- [
938
- f' <rect x="{round(x - width / 2, 2)}" y="{round(y - 10, 2)}" width="{width}" height="20" rx="6" fill="{bg}" opacity="{opacity}"/>',
939
- f' <text x="{round(x, 2)}" y="{round(y + 4, 2)}" text-anchor="middle" class="arrow-label">{normalize_text(text)}</text>',
940
- ]
941
- )
942
-
943
-
944
- def rectangle_bounds(x: float, y: float, width: float, height: float) -> Bounds:
945
- return (x, y, x + width, y + height)
946
-
947
-
948
- def bounds_intersect(a: Bounds, b: Bounds, padding: float = 0.0) -> bool:
949
- ax1, ay1, ax2, ay2 = a
950
- bx1, by1, bx2, by2 = b
951
- return not (
952
- ax2 + padding <= bx1
953
- or bx2 + padding <= ax1
954
- or ay2 + padding <= by1
955
- or by2 + padding <= ay1
956
- )
957
-
958
-
959
- def estimate_label_bounds(x: float, y: float, text: str) -> Bounds:
960
- width = max(36, len(text) * 7 + 14)
961
- return rectangle_bounds(x - width / 2, y - 10, width, 20)
962
-
963
-
964
- def section_header_text(container: Dict[str, object], style: Dict[str, object]) -> str:
965
- if container.get("header_text"):
966
- text = str(container.get("header_text", ""))
967
- else:
968
- label = str(container.get("label", ""))
969
- prefix = str(container.get("header_prefix", "")).strip()
970
- separator = str(container.get("header_separator", " // " if prefix else ""))
971
- text = f"{prefix}{separator}{label}" if prefix else label
972
- if style_value(style, "section_upper") and not container.get("preserve_case"):
973
- text = text.upper()
974
- return text
975
-
976
-
977
- def render_section(container: Dict[str, object], style: Dict[str, object]) -> str:
978
- x = to_float(container["x"])
979
- y = to_float(container["y"])
980
- width = to_float(container["width"])
981
- height = to_float(container["height"])
982
- rx = to_float(container.get("rx", 16 if style_value(style, "name") != "Notion Clean" else 4))
983
- fill = str(container.get("fill", style_value(style, "section_fill")))
984
- stroke = str(container.get("stroke", style_value(style, "section_stroke")))
985
- dash = str(container.get("stroke_dasharray", style_value(style, "section_dash")))
986
- label = section_header_text(container, style)
987
- subtitle = str(container.get("subtitle", ""))
988
- side_label = str(container.get("side_label", "")).strip()
989
- side_label_fill = str(container.get("side_label_fill", style_value(style, "text_secondary")))
990
- side_label_size = to_float(container.get("side_label_size", 14))
991
- side_label_weight = str(container.get("side_label_weight", "600"))
992
- side_label_anchor = str(container.get("side_label_anchor", "end"))
993
- lines = [f' <rect x="{x}" y="{y}" width="{width}" height="{height}" rx="{rx}" fill="{fill}" stroke="{stroke}" stroke-width="1.4"']
994
- if dash:
995
- lines[-1] += f' stroke-dasharray="{dash}"'
996
- lines[-1] += "/>"
997
- if label:
998
- lines.append(f' <text x="{x + 18}" y="{y + 24}" class="section">{normalize_text(label)}</text>')
999
- if subtitle:
1000
- lines.append(f' <text x="{x + 18}" y="{y + 44}" class="section-sub">{normalize_text(subtitle)}</text>')
1001
- if side_label:
1002
- side_x = to_float(container.get("side_label_x", max(28, x - 18)))
1003
- side_y = to_float(container.get("side_label_y", y + height / 2))
1004
- lines.append(
1005
- f' <text x="{side_x}" y="{side_y}" text-anchor="{side_label_anchor}" dominant-baseline="middle" '
1006
- f'font-size="{side_label_size}" font-weight="{side_label_weight}" fill="{side_label_fill}">{normalize_text(side_label)}</text>'
1007
- )
1008
- return "\n".join(lines)
1009
-
1010
-
1011
- def container_header_bounds(container: Dict[str, object]) -> Optional[Bounds]:
1012
- label = str(container.get("header_text", "") or container.get("label", "")).strip()
1013
- subtitle = str(container.get("subtitle", "")).strip()
1014
- if not label and not subtitle:
1015
- return None
1016
- x = to_float(container["x"])
1017
- y = to_float(container["y"])
1018
- width = to_float(container["width"])
1019
- header_height = to_float(container.get("header_height", 54 if subtitle else 30))
1020
- return rectangle_bounds(x + 6, y + 6, width - 12, header_height)
1021
-
1022
-
1023
- def label_position_candidates(points: Sequence[Point]) -> List[Point]:
1024
- segments = list(zip(points, points[1:]))
1025
- if not segments:
1026
- return [points[0]]
1027
- ranked_segments = sorted(
1028
- segments,
1029
- key=lambda seg: abs(seg[0][0] - seg[1][0]) + abs(seg[0][1] - seg[1][1]),
1030
- reverse=True,
1031
- )
1032
- candidates: List[Point] = []
1033
- for (x1, y1), (x2, y2) in ranked_segments:
1034
- length = abs(x1 - x2) + abs(y1 - y2)
1035
- if length < 34:
1036
- continue
1037
- mx = (x1 + x2) / 2
1038
- my = (y1 + y2) / 2
1039
- if abs(y1 - y2) < 1e-6:
1040
- candidates.extend([(mx, my - 16), (mx, my + 16), (mx, my - 28), (mx, my + 28), (mx, my)])
1041
- elif abs(x1 - x2) < 1e-6:
1042
- candidates.extend([(mx - 18, my), (mx + 18, my), (mx - 30, my), (mx + 30, my), (mx, my)])
1043
- else:
1044
- candidates.extend([(mx, my - 16), (mx, my + 16), (mx, my)])
1045
- return candidates or [choose_label_position(points)]
1046
-
1047
-
1048
- def choose_label_position_avoiding(points: Sequence[Point], text: str, occupied: Sequence[Bounds]) -> Point:
1049
- for candidate in label_position_candidates(points):
1050
- label_box = estimate_label_bounds(candidate[0], candidate[1], text)
1051
- if not any(bounds_intersect(label_box, other, 4) for other in occupied):
1052
- return candidate
1053
- return choose_label_position(points)
1054
-
1055
-
1056
- def legend_layout(data: Dict[str, object], legend: Sequence[Dict[str, object]], width: float, height: float) -> Optional[Tuple[float, float, Bounds]]:
1057
- if not legend:
1058
- return None
1059
- x = to_float(data.get("legend_x", 42))
1060
- y = to_float(data.get("legend_y", height - (len(legend) * 22 + 34)))
1061
- position = str(data.get("legend_position", "bottom-left"))
1062
- max_label = max((len(str(item.get("label", ""))) for item in legend), default=12)
1063
- block_width = 40 + max_label * 7 + 12
1064
- block_height = len(legend) * 22 + 6
1065
- if position == "bottom-right":
1066
- x = to_float(data.get("legend_x", width - block_width - 42))
1067
- elif position == "top-right":
1068
- x = to_float(data.get("legend_x", width - block_width - 42))
1069
- y = to_float(data.get("legend_y", 96))
1070
- elif position == "top-left":
1071
- x = to_float(data.get("legend_x", 42))
1072
- y = to_float(data.get("legend_y", 96))
1073
- return (x, y, rectangle_bounds(x - 4, y - 10, block_width + 8, block_height + 12))
1074
-
1075
-
1076
- def footer_layout(data: Dict[str, object], width: float, height: float) -> Optional[Tuple[float, float, Bounds]]:
1077
- text = str(data.get("footer", "")).strip()
1078
- if not text:
1079
- return None
1080
- footer_width = max(140, len(text) * 7)
1081
- x = to_float(data.get("footer_x", 42))
1082
- y = to_float(data.get("footer_y", height - 16))
1083
- position = str(data.get("footer_position", "bottom-left"))
1084
- if position == "bottom-right":
1085
- x = to_float(data.get("footer_x", width - footer_width - 42))
1086
- return (x, y, rectangle_bounds(x, y - 12, footer_width, 16))
1087
-
1088
-
1089
- def render_tags(node: Dict[str, object], x: float, y: float, style: Dict[str, object]) -> List[str]:
1090
- tags = node.get("tags", [])
1091
- if not tags:
1092
- return []
1093
- cursor_x = x
1094
- lines = []
1095
- for tag in tags:
1096
- label = normalize_text(tag.get("label", ""))
1097
- width = max(62, len(str(tag.get("label", ""))) * 8 + 18)
1098
- fill = tag.get("fill", "#eff6ff")
1099
- stroke = tag.get("stroke", "#bfdbfe")
1100
- text_fill = tag.get("text_fill", style_value(style, "arrow_colors")["read"])
1101
- lines.append(
1102
- f' <rect x="{cursor_x}" y="{y}" width="{width}" height="16" rx="3" fill="{fill}" stroke="{stroke}" stroke-width="1"/>'
1103
- )
1104
- lines.append(
1105
- f' <text x="{cursor_x + width / 2}" y="{y + 11.5}" text-anchor="middle" font-size="11" font-weight="500" fill="{text_fill}">{label}</text>'
1106
- )
1107
- cursor_x += width + 8
1108
- return lines
1109
-
1110
-
1111
- def render_rect_node(node: Dict[str, object], style: Dict[str, object], kind: str) -> str:
1112
- x = to_float(node["x"])
1113
- y = to_float(node["y"])
1114
- width = to_float(node.get("width", 180))
1115
- height = to_float(node.get("height", 76))
1116
- rx = to_float(node.get("rx", style_value(style, "node_radius")))
1117
- fill = str(node.get("fill", style_value(style, "node_fill")))
1118
- stroke = str(node.get("stroke", style_value(style, "node_stroke")))
1119
- stroke_width = to_float(node.get("stroke_width", 2.0 if kind != "rect" else 1.8))
1120
- filter_attr = ""
1121
- node_shadow = node.get("filter")
1122
- if node_shadow:
1123
- filter_attr = f' filter="url(#{node_shadow})"'
1124
- elif node.get("glow"):
1125
- glow_name = str(node.get("glow"))
1126
- glow_map = {
1127
- "blue": "glowBlue",
1128
- "purple": "glowPurple",
1129
- "green": "glowGreen",
1130
- "orange": "glowOrange",
1131
- }
1132
- if glow_name in glow_map:
1133
- filter_attr = f' filter="url(#{glow_map[glow_name]})"'
1134
- elif style_value(style, "node_shadow"):
1135
- if not node.get("flat", False):
1136
- filter_attr = f' filter="{style_value(style, "node_shadow")}"'
1137
- title = normalize_text(node.get("label", ""))
1138
- subtitle = normalize_text(node.get("sublabel", ""))
1139
- type_label = normalize_text(node.get("type_label", ""))
1140
- accent_fill = node.get("accent_fill")
1141
- lines = []
1142
-
1143
- if kind == "double_rect":
1144
- lines.append(
1145
- f' <rect x="{x}" y="{y}" width="{width}" height="{height}" rx="{rx}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"{filter_attr}/>'
1146
- )
1147
- lines.append(
1148
- f' <rect x="{x + 6}" y="{y + 6}" width="{width - 12}" height="{height - 12}" rx="{max(rx - 3, 4)}" fill="none" stroke="{stroke}" stroke-width="1.2" opacity="0.65"/>'
1149
- )
1150
- elif kind == "terminal":
1151
- lines.append(
1152
- f' <rect x="{x}" y="{y}" width="{width}" height="{height}" rx="{rx}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"{filter_attr}/>'
1153
- )
1154
- lines.append(
1155
- f' <rect x="{x}" y="{y}" width="{width}" height="18" rx="{rx}" fill="{node.get("header_fill", "#1f2937")}" opacity="0.95"/>'
1156
- )
1157
- header_colors = node.get("header_dots", ["#ef4444", "#f59e0b", "#10b981"])
1158
- for idx, color in enumerate(header_colors):
1159
- lines.append(f' <circle cx="{x + 16 + idx * 14}" cy="{y + 9}" r="4" fill="{color}"/>')
1160
- lines.append(
1161
- f' <text x="{x + 18}" y="{y + 44}" font-size="28" font-weight="700" fill="{node.get("prompt_fill", "#10b981")}">$</text>'
1162
- )
1163
- lines.append(
1164
- f' <text x="{x + 38}" y="{y + 44}" font-size="22" font-weight="500" fill="{style_value(style, "text_secondary")}">_</text>'
1165
- )
1166
- elif kind == "document":
1167
- fold = min(18, width * 0.18, height * 0.22)
1168
- path = (
1169
- f"M {x} {y} L {x + width - fold} {y} L {x + width} {y + fold} "
1170
- f"L {x + width} {y + height} L {x} {y + height} Z"
1171
- )
1172
- lines.append(
1173
- f' <path d="{path}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"{filter_attr}/>'
1174
- )
1175
- lines.append(
1176
- f' <path d="M {x + width - fold} {y} L {x + width - fold} {y + fold} L {x + width} {y + fold}" fill="none" stroke="{stroke}" stroke-width="{stroke_width}"/>'
1177
- )
1178
- for idx in range(4):
1179
- line_y = y + 26 + idx * 14
1180
- lines.append(
1181
- f' <line x1="{x + 18}" y1="{line_y}" x2="{x + width - 28}" y2="{line_y}" stroke="{node.get("line_stroke", "#c4b5fd")}" stroke-width="1.2"/>'
1182
- )
1183
- elif kind == "folder":
1184
- tab_w = min(54, width * 0.34)
1185
- tab_h = 18
1186
- path = (
1187
- f"M {x} {y + tab_h} L {x + tab_w * 0.4} {y + tab_h} L {x + tab_w * 0.58} {y} "
1188
- f"L {x + tab_w} {y} L {x + width} {y} L {x + width} {y + height} L {x} {y + height} Z"
1189
- )
1190
- lines.append(
1191
- f' <path d="{path}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"{filter_attr}/>'
1192
- )
1193
- for idx in range(3):
1194
- line_y = y + 42 + idx * 14
1195
- lines.append(
1196
- f' <line x1="{x + 22}" y1="{line_y}" x2="{x + width - 22}" y2="{line_y}" stroke="{node.get("line_stroke", stroke)}" stroke-opacity="0.35" stroke-width="1.2"/>'
1197
- )
1198
- elif kind == "hexagon":
1199
- inset = 22
1200
- path = (
1201
- f"M {x + inset} {y} L {x + width - inset} {y} L {x + width} {y + height / 2} "
1202
- f"L {x + width - inset} {y + height} L {x + inset} {y + height} L {x} {y + height / 2} Z"
1203
- )
1204
- lines.append(f' <path d="{path}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"{filter_attr}/>')
1205
- elif kind == "speech":
1206
- tail = 18
1207
- path = (
1208
- f"M {x + rx} {y} L {x + width - rx} {y} Q {x + width} {y} {x + width} {y + rx} "
1209
- f"L {x + width} {y + height - rx} Q {x + width} {y + height} {x + width - rx} {y + height} "
1210
- f"L {x + 26} {y + height} L {x + 12} {y + height + tail} L {x + 16} {y + height} "
1211
- f"L {x + rx} {y + height} Q {x} {y + height} {x} {y + height - rx} "
1212
- f"L {x} {y + rx} Q {x} {y} {x + rx} {y} Z"
1213
- )
1214
- lines.append(f' <path d="{path}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"{filter_attr}/>')
1215
- else:
1216
- lines.append(
1217
- f' <rect x="{x}" y="{y}" width="{width}" height="{height}" rx="{rx}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"{filter_attr}/>'
1218
- )
1219
-
1220
- if accent_fill and kind == "icon_box":
1221
- lines.append(
1222
- f' <rect x="{x + 12}" y="{y + 12}" width="{width - 24}" height="{height - 24}" rx="{max(rx - 4, 4)}" fill="{accent_fill}" opacity="0.9"/>'
1223
- )
1224
-
1225
- if kind == "user_avatar":
1226
- circle_fill = node.get("icon_fill", "#dbeafe")
1227
- icon_stroke = node.get("icon_stroke", stroke)
1228
- cx = x + 26
1229
- cy = y + height / 2
1230
- lines.append(f' <circle cx="{cx}" cy="{cy}" r="18" fill="{circle_fill}" stroke="{icon_stroke}" stroke-width="1.6"/>')
1231
- lines.append(f' <circle cx="{cx}" cy="{cy - 6}" r="5" fill="{icon_stroke}"/>')
1232
- lines.append(f' <path d="M {cx - 10} {cy + 11} Q {cx} {cy + 2} {cx + 10} {cy + 11}" fill="none" stroke="{icon_stroke}" stroke-width="2"/>')
1233
-
1234
- if kind == "bot":
1235
- cx = x + width / 2
1236
- cy = y + height / 2 + 2
1237
- body_fill = node.get("body_fill", "#1e293b")
1238
- accent = node.get("accent_fill", "#34d399")
1239
- lines.append(f' <rect x="{cx - 42}" y="{cy - 32}" width="84" height="84" rx="18" fill="{body_fill}" stroke="#334155" stroke-width="1.8"{filter_attr}/>')
1240
- lines.append(f' <rect x="{cx - 26}" y="{cy - 16}" width="52" height="22" rx="6" fill="#0f172a" stroke="#475569" stroke-width="1.2"/>')
1241
- lines.append(f' <circle cx="{cx - 12}" cy="{cy - 5}" r="5" fill="{accent}"/>')
1242
- lines.append(f' <circle cx="{cx + 12}" cy="{cy - 5}" r="5" fill="{accent}"/>')
1243
- lines.append(f' <rect x="{cx - 14}" y="{cy + 14}" width="28" height="6" rx="3" fill="#334155"/>')
1244
- lines.append(f' <line x1="{cx}" y1="{cy - 36}" x2="{cx}" y2="{cy - 50}" stroke="{accent}" stroke-width="3"/>')
1245
- lines.append(f' <circle cx="{cx}" cy="{cy - 54}" r="5" fill="{accent}"/>')
1246
-
1247
- if kind == "circle_cluster":
1248
- r = min(width, height) / 4.0
1249
- centers = [(x + width * 0.36, y + height * 0.56), (x + width * 0.58, y + height * 0.45), (x + width * 0.74, y + height * 0.58)]
1250
- for cx, cy in centers:
1251
- lines.append(f' <circle cx="{cx}" cy="{cy}" r="{r}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"/>')
1252
-
1253
- type_offset = y + 18 if kind not in {"terminal", "bot"} else y + 18
1254
- title_y = y + height / 2 - (4 if type_label and kind not in {"terminal", "bot"} else 0)
1255
- if kind in {"document", "folder"}:
1256
- title_y = y + height + 26
1257
- elif kind == "circle_cluster":
1258
- title_y = y + height / 2 + 8
1259
- elif kind == "bot":
1260
- title_y = y + height + 22
1261
- elif kind == "user_avatar":
1262
- title_y = y + height / 2 + 6
1263
-
1264
- if type_label:
1265
- lines.append(f' <text x="{x + (54 if kind == "user_avatar" else width / 2)}" y="{type_offset}" text-anchor="middle" class="node-type">{type_label}</text>')
1266
- title_y += 10 if kind not in {"document", "folder", "circle_cluster", "bot"} else 0
1267
-
1268
- title_x = x + width / 2
1269
- text_anchor = "middle"
1270
- if kind == "user_avatar":
1271
- title_x = x + 64
1272
- text_anchor = "start"
1273
- if kind == "terminal":
1274
- title_y = y + height - 14
1275
- if kind == "bot":
1276
- title_x = x + width / 2
1277
- text_anchor = "middle"
1278
- lines.append(f' <text x="{title_x}" y="{title_y}" text-anchor="{text_anchor}" class="node-title">{title}</text>')
1279
-
1280
- if subtitle:
1281
- sub_y = title_y + 22
1282
- if kind == "document":
1283
- sub_y = y + height + 44
1284
- title_y = y + height + 24
1285
- if kind == "folder":
1286
- sub_y = y + height + 44
1287
- if kind == "circle_cluster":
1288
- sub_y = y + height / 2 + 28
1289
- if kind == "bot":
1290
- sub_y = y + height + 42
1291
- if kind == "terminal":
1292
- sub_y = y + height + 20
1293
- if kind == "user_avatar":
1294
- sub_y = title_y + 22
1295
- lines.append(f' <text x="{title_x}" y="{sub_y}" text-anchor="{text_anchor}" class="node-sub">{subtitle}</text>')
1296
-
1297
- tag_lines = []
1298
- if node.get("tags"):
1299
- tag_x = x + 18
1300
- tag_y = y + height - 20
1301
- if kind in {"document", "folder", "circle_cluster", "bot", "terminal"}:
1302
- tag_y = y + height + 52
1303
- tag_lines = render_tags(node, tag_x, tag_y, style)
1304
- lines.extend(tag_lines)
1305
-
1306
- return "\n".join(lines)
1307
-
1308
-
1309
- def render_node(node: Dict[str, object], style: Dict[str, object]) -> str:
1310
- kind = str(node.get("kind", node.get("shape", "rect")))
1311
- if kind == "cylinder":
1312
- x = to_float(node["x"])
1313
- y = to_float(node["y"])
1314
- width = to_float(node.get("width", 160))
1315
- height = to_float(node.get("height", 120))
1316
- rx = width / 2
1317
- ry = min(18, height / 8)
1318
- fill = str(node.get("fill", "#ecfdf5"))
1319
- stroke = str(node.get("stroke", "#10b981"))
1320
- stroke_width = to_float(node.get("stroke_width", 2.2))
1321
- label = normalize_text(node.get("label", ""))
1322
- subtitle = normalize_text(node.get("sublabel", ""))
1323
- lines = [
1324
- f' <ellipse cx="{x + width / 2}" cy="{y + ry}" rx="{rx / 2}" ry="{ry}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"/>',
1325
- f' <rect x="{x}" y="{y + ry}" width="{width}" height="{height - 2 * ry}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"/>',
1326
- f' <ellipse cx="{x + width / 2}" cy="{y + height - ry}" rx="{rx / 2}" ry="{ry}" fill="{fill}" stroke="{stroke}" stroke-width="{stroke_width}"/>',
1327
- f' <ellipse cx="{x + width / 2}" cy="{y + height * 0.38}" rx="{rx / 2}" ry="{ry}" fill="none" stroke="{stroke}" stroke-opacity="0.45" stroke-width="1.2"/>',
1328
- f' <ellipse cx="{x + width / 2}" cy="{y + height * 0.6}" rx="{rx / 2}" ry="{ry}" fill="none" stroke="{stroke}" stroke-opacity="0.25" stroke-width="1.2"/>',
1329
- f' <text x="{x + width / 2}" y="{y + height / 2 - 6}" text-anchor="middle" class="node-title">{label}</text>',
1330
- ]
1331
- if subtitle:
1332
- lines.append(f' <text x="{x + width / 2}" y="{y + height / 2 + 18}" text-anchor="middle" class="node-sub">{subtitle}</text>')
1333
- return "\n".join(lines)
1334
- return render_rect_node(node, style, kind)
1335
-
1336
-
1337
- def render_arrow(
1338
- arrow: Dict[str, object],
1339
- style: Dict[str, object],
1340
- node_map: Dict[str, Node],
1341
- route_obstacles: Sequence[Bounds],
1342
- label_obstacles: Sequence[Bounds],
1343
- ) -> Tuple[str, str, Optional[Bounds]]:
1344
- start_hint = (to_float(arrow.get("x1")), to_float(arrow.get("y1")))
1345
- end_hint = (to_float(arrow.get("x2")), to_float(arrow.get("y2")))
1346
- source_node = node_map.get(str(arrow.get("source"))) if arrow.get("source") else None
1347
- target_node = node_map.get(str(arrow.get("target"))) if arrow.get("target") else None
1348
- source_port = arrow.get("source_port")
1349
- target_port = arrow.get("target_port")
1350
-
1351
- if source_node is not None:
1352
- toward = end_hint if target_node is None else (target_node.cx, target_node.cy)
1353
- start = anchor_point(source_node, toward, str(source_port) if source_port else None)
1354
- else:
1355
- start = start_hint
1356
-
1357
- if target_node is not None:
1358
- toward = start_hint if source_node is None else (source_node.cx, source_node.cy)
1359
- end = anchor_point(target_node, toward, str(target_port) if target_port else None)
1360
- else:
1361
- end = end_hint
1362
-
1363
- obstacles = list(route_obstacles)
1364
- if source_node is not None:
1365
- obstacles = [bounds for bounds in obstacles if bounds != source_node.bounds]
1366
- if target_node is not None:
1367
- obstacles = [bounds for bounds in obstacles if bounds != target_node.bounds]
1368
-
1369
- route = build_orthogonal_route(start, end, obstacles, arrow)
1370
- path_d = "M " + " L ".join(f"{round(x, 2)},{round(y, 2)}" for x, y in route)
1371
- color = color_for_flow(style, arrow)
1372
- width = to_float(arrow.get("stroke_width", style_value(style, "arrow_width")))
1373
- dash = arrow.get("stroke_dasharray")
1374
- if dash is None and arrow.get("dashed"):
1375
- dash = "6,4"
1376
- marker = marker_for_color(style, color, arrow)
1377
- path = f' <path d="{path_d}" fill="none" stroke="{color}" stroke-width="{width}" marker-end="{marker}"'
1378
- if dash:
1379
- path += f' stroke-dasharray="{dash}"'
1380
- if arrow.get("opacity") is not None:
1381
- path += f' opacity="{arrow["opacity"]}"'
1382
- path += "/>"
1383
- label_svg = ""
1384
- label_bounds = None
1385
-
1386
- label = str(arrow.get("label", "")).strip()
1387
- if label:
1388
- label_x, label_y = choose_label_position_avoiding(route, label, label_obstacles)
1389
- label_x += to_float(arrow.get("label_dx", 0))
1390
- label_y += to_float(arrow.get("label_dy", -4))
1391
- label_svg = render_label_badge(label_x, label_y, label, style)
1392
- label_bounds = estimate_label_bounds(label_x, label_y, label)
1393
- return path, label_svg, label_bounds
1394
-
1395
-
1396
- def render_legend(
1397
- legend: Sequence[Dict[str, object]],
1398
- style: Dict[str, object],
1399
- width: float,
1400
- height: float,
1401
- data: Dict[str, object],
1402
- ) -> str:
1403
- layout = legend_layout(data, legend, width, height)
1404
- if not layout:
1405
- return ""
1406
- legend_x, legend_y, _ = layout
1407
- lines = []
1408
- for idx, item in enumerate(legend):
1409
- y = legend_y + idx * 22
1410
- color = item.get("color")
1411
- if not color:
1412
- color = style_value(style, "arrow_colors")[FLOW_ALIASES.get(str(item.get("flow", "control")).lower(), "control")]
1413
- marker = marker_for_color(style, str(color), {"flow": item.get("flow", "control")})
1414
- lines.append(f' <line x1="{legend_x}" y1="{y}" x2="{legend_x + 30}" y2="{y}" stroke="{color}" stroke-width="{style_value(style, "arrow_width")}" marker-end="{marker}"/>')
1415
- lines.append(f' <text x="{legend_x + 40}" y="{y + 4}" class="legend">{normalize_text(item.get("label", ""))}</text>')
1416
- if data.get("legend_box"):
1417
- max_label = max((len(str(item.get("label", ""))) for item in legend), default=12)
1418
- block_width = 40 + max_label * 7 + 12
1419
- block_height = len(legend) * 22 + 6
1420
- bg = data.get("legend_box_fill", style_value(style, "arrow_label_bg"))
1421
- opacity = data.get("legend_box_opacity", 0.88)
1422
- lines.insert(0, f' <rect x="{legend_x - 10}" y="{legend_y - 14}" width="{block_width + 20}" height="{block_height + 18}" rx="10" fill="{bg}" opacity="{opacity}"/>')
1423
- return "\n".join(lines)
1424
-
1425
-
1426
- def render_footer(data: Dict[str, object], style: Dict[str, object], width: float, height: float) -> str:
1427
- layout = footer_layout(data, width, height)
1428
- if not layout:
1429
- return ""
1430
- x, y, _ = layout
1431
- text = str(data.get("footer", "")).strip()
1432
- return f' <text x="{x}" y="{y}" class="footnote">{normalize_text(text)}</text>'
1433
-
1434
-
1435
- def build_svg(template_type: str, data: Dict[str, object]) -> str:
1436
- style_index, style = parse_style(data.get("style"))
1437
- if data.get("style_overrides"):
1438
- style.update(data["style_overrides"])
1439
- width, height = parse_template_viewbox(template_type)
1440
- width = to_float(data.get("width", width))
1441
- height = to_float(data.get("height", height))
1442
- if data.get("viewBox"):
1443
- match = re.match(r"0 0 ([0-9.]+) ([0-9.]+)", str(data["viewBox"]))
1444
- if match:
1445
- width = float(match.group(1))
1446
- height = float(match.group(2))
1447
-
1448
- containers = data.get("containers", [])
1449
- nodes_data = data.get("nodes", [])
1450
- arrows_data = data.get("arrows", [])
1451
- legend = data.get("legend", [])
1452
-
1453
- normalized_nodes = [normalize_node(node, f"node-{idx}") for idx, node in enumerate(nodes_data)]
1454
- node_map = {node.node_id: node for node in normalized_nodes}
1455
-
1456
- defs = render_defs(style_index, style)
1457
- canvas = render_canvas(style_index, style, width, height)
1458
- title_block, content_start_y = render_title_block(style, data, width)
1459
- window_controls = render_window_controls(data, style_index, width)
1460
- header_meta = render_header_meta(data, style, width)
1461
-
1462
- lines = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {int(width)} {int(height)}" width="{int(width)}" height="{int(height)}">']
1463
- lines.append(defs)
1464
- lines.append(canvas)
1465
- if window_controls:
1466
- lines.append(window_controls)
1467
- if header_meta:
1468
- lines.append(header_meta)
1469
- lines.append(title_block)
1470
-
1471
- if containers:
1472
- for container in containers:
1473
- lines.append(render_section(container, style))
1474
-
1475
- section_obstacles = [bounds for container in containers if (bounds := container_header_bounds(container)) is not None]
1476
- legend_reserved = legend_layout(data, legend, width, height)
1477
- footer_reserved = footer_layout(data, width, height)
1478
- blueprint_block_svg, blueprint_block_bounds = render_blueprint_title_block(data, style, style_index, width, height)
1479
- reserved_bounds = list(section_obstacles)
1480
- if legend_reserved:
1481
- reserved_bounds.append(legend_reserved[2])
1482
- if footer_reserved:
1483
- reserved_bounds.append(footer_reserved[2])
1484
- if blueprint_block_bounds:
1485
- reserved_bounds.append(blueprint_block_bounds)
1486
-
1487
- arrow_paths: List[str] = []
1488
- arrow_labels: List[str] = []
1489
- node_obstacles = [node.bounds for node in normalized_nodes]
1490
- route_obstacles = node_obstacles + reserved_bounds
1491
- label_obstacles = node_obstacles + reserved_bounds
1492
- for arrow in arrows_data:
1493
- path_svg, label_svg, label_bounds = render_arrow(arrow, style, node_map, route_obstacles, label_obstacles)
1494
- arrow_paths.append(path_svg)
1495
- if label_svg:
1496
- arrow_labels.append(label_svg)
1497
- if label_bounds:
1498
- label_obstacles.append(label_bounds)
1499
-
1500
- lines.extend(path for path in arrow_paths if path)
1501
-
1502
- for node_data in nodes_data:
1503
- if "y" not in node_data and node_data.get("auto_place"):
1504
- node_data["y"] = content_start_y + to_float(node_data.get("offset_y", 0))
1505
- lines.append(render_node(node_data, style))
1506
-
1507
- lines.extend(label for label in arrow_labels if label)
1508
-
1509
- legend_svg = render_legend(legend, style, width, height, data)
1510
- if legend_svg:
1511
- lines.append(legend_svg)
1512
-
1513
- if blueprint_block_svg:
1514
- lines.append(blueprint_block_svg)
1515
-
1516
- footer_svg = render_footer(data, style, width, height)
1517
- if footer_svg:
1518
- lines.append(footer_svg)
1519
-
1520
- lines.append("</svg>")
1521
- return "\n".join(line for line in lines if line)
1522
-
1523
-
1524
- def main() -> None:
1525
- if len(sys.argv) < 3:
1526
- print("Usage: python3 generate-from-template.py <template-type> <output-path> [data-json]")
1527
- sys.exit(1)
1528
-
1529
- template_type = sys.argv[1]
1530
- output_path = sys.argv[2]
1531
-
1532
- try:
1533
- if len(sys.argv) > 3:
1534
- data = json.loads(sys.argv[3])
1535
- else:
1536
- data = json.load(sys.stdin)
1537
- svg_content = build_svg(template_type, data)
1538
- with open(output_path, "w", encoding="utf-8") as handle:
1539
- handle.write(svg_content)
1540
- print(f"✓ SVG generated: {output_path}")
1541
- except FileNotFoundError as exc:
1542
- print(f"Error: {exc}")
1543
- sys.exit(1)
1544
- except json.JSONDecodeError as exc:
1545
- print(f"Error: Invalid JSON: {exc}")
1546
- sys.exit(1)
1547
- except ValueError as exc:
1548
- print(f"Error: {exc}")
1549
- sys.exit(1)
1550
- except Exception as exc: # pragma: no cover
1551
- print(f"Unexpected error: {exc}")
1552
- sys.exit(1)
1553
-
1554
-
1555
- if __name__ == "__main__":
1556
- main()