@sparkelf/dsh-genui 0.0.0-stage → 0.11.4-patch.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 (210) hide show
  1. package/CHANGELOG.md +597 -0
  2. package/LICENSE +21 -0
  3. package/README.md +292 -2
  4. package/README.zh-CN.md +307 -0
  5. package/SKILL.md +261 -0
  6. package/cordis.patch.yml +9 -0
  7. package/demo-prompts.md +118 -0
  8. package/lib/assets/echarts-core.js +43 -0
  9. package/lib/assets/echarts-full.js +72 -0
  10. package/lib/assets/mermaid.js +3591 -0
  11. package/lib/assets/standalone-runtime.js +1506 -0
  12. package/lib/assets/three.js +3844 -0
  13. package/lib/client.js +405 -0
  14. package/lib/index.js +5187 -0
  15. package/lib/invariant.js +19 -0
  16. package/lib/types/client/EChartNode.d.ts +13 -0
  17. package/lib/types/client/ErrorBoundary.d.ts +30 -0
  18. package/lib/types/client/GenuiBlock.d.ts +9 -0
  19. package/lib/types/client/PlotBlock.d.ts +44 -0
  20. package/lib/types/client/TemplateDrawer.d.ts +7 -0
  21. package/lib/types/client/achievement-store.d.ts +35 -0
  22. package/lib/types/client/achievement-toast.d.ts +2 -0
  23. package/lib/types/client/achievements.d.ts +63 -0
  24. package/lib/types/client/action-context.d.ts +7 -0
  25. package/lib/types/client/artifact/ExportableGenuiBlock.d.ts +6 -0
  26. package/lib/types/client/artifact/create.d.ts +5 -0
  27. package/lib/types/client/artifact/download.d.ts +9 -0
  28. package/lib/types/client/artifact/html.d.ts +5 -0
  29. package/lib/types/client/artifact/index.d.ts +8 -0
  30. package/lib/types/client/artifact/json.d.ts +3 -0
  31. package/lib/types/client/artifact/parse.d.ts +3 -0
  32. package/lib/types/client/artifact/portability.d.ts +4 -0
  33. package/lib/types/client/artifact/standalone-theme.d.ts +2 -0
  34. package/lib/types/client/artifact/types.d.ts +33 -0
  35. package/lib/types/client/asset-echarts-core.d.ts +1 -0
  36. package/lib/types/client/asset-echarts.d.ts +17 -0
  37. package/lib/types/client/asset-loader.d.ts +33 -0
  38. package/lib/types/client/asset-mermaid.d.ts +1 -0
  39. package/lib/types/client/asset-three.d.ts +1 -0
  40. package/lib/types/client/blocks/advanced.d.ts +101 -0
  41. package/lib/types/client/blocks/basic.d.ts +22 -0
  42. package/lib/types/client/blocks/charts.d.ts +53 -0
  43. package/lib/types/client/blocks/checkbox.d.ts +17 -0
  44. package/lib/types/client/blocks/diagram/geometry.d.ts +73 -0
  45. package/lib/types/client/blocks/diagram/index.d.ts +5 -0
  46. package/lib/types/client/blocks/diagram/layout.d.ts +41 -0
  47. package/lib/types/client/blocks/diagram/theme.d.ts +37 -0
  48. package/lib/types/client/blocks/forms.d.ts +77 -0
  49. package/lib/types/client/blocks/image.d.ts +6 -0
  50. package/lib/types/client/blocks/render-node.d.ts +10 -0
  51. package/lib/types/client/blocks/state.d.ts +63 -0
  52. package/lib/types/client/blocks/svg.d.ts +4 -0
  53. package/lib/types/client/dom-fence.d.ts +30 -0
  54. package/lib/types/client/echarts-engine.d.ts +4 -0
  55. package/lib/types/client/echarts-lazy.d.ts +18 -0
  56. package/lib/types/client/embed.d.ts +10 -0
  57. package/lib/types/client/fence-render.d.ts +106 -0
  58. package/lib/types/client/gallery.d.ts +7 -0
  59. package/lib/types/client/genui-runtime/diagnostics.d.ts +18 -0
  60. package/lib/types/client/genui-runtime/index.d.ts +1 -0
  61. package/lib/types/client/genui-runtime/limits.d.ts +54 -0
  62. package/lib/types/client/genui-runtime/normalize.d.ts +15 -0
  63. package/lib/types/client/genui-runtime/schema.d.ts +87 -0
  64. package/lib/types/client/genui-runtime/value-utils.d.ts +18 -0
  65. package/lib/types/client/guard.d.ts +144 -0
  66. package/lib/types/client/i18n/en.d.ts +307 -0
  67. package/lib/types/client/i18n/index.d.ts +44 -0
  68. package/lib/types/client/i18n/runtime.d.ts +64 -0
  69. package/lib/types/client/i18n/zh.d.ts +8 -0
  70. package/lib/types/client/index.d.ts +36 -0
  71. package/lib/types/client/inline.d.ts +5 -0
  72. package/lib/types/client/interaction-store.d.ts +48 -0
  73. package/lib/types/client/mermaid-core.d.ts +8 -0
  74. package/lib/types/client/mermaid-lazy.d.ts +9 -0
  75. package/lib/types/client/mermaid-safe.d.ts +52 -0
  76. package/lib/types/client/panel-command.d.ts +34 -0
  77. package/lib/types/client/panel-store.d.ts +94 -0
  78. package/lib/types/client/panel.d.ts +18 -0
  79. package/lib/types/client/parse-partial.d.ts +63 -0
  80. package/lib/types/client/primitive-adapter.d.ts +4 -0
  81. package/lib/types/client/primitive-labels.d.ts +18 -0
  82. package/lib/types/client/safe-math.d.ts +43 -0
  83. package/lib/types/client/scene3d-core.d.ts +21 -0
  84. package/lib/types/client/scene3d-lazy.d.ts +8 -0
  85. package/lib/types/client/session-resolver.d.ts +8 -0
  86. package/lib/types/client/source-fence.d.ts +29 -0
  87. package/lib/types/client/spec.d.ts +709 -0
  88. package/lib/types/client/standalone/asset-loader.d.ts +2 -0
  89. package/lib/types/client/standalone/bootstrap-types.d.ts +9 -0
  90. package/lib/types/client/standalone/katex-style.d.ts +1 -0
  91. package/lib/types/client/standalone/primitive-adapter.d.ts +54 -0
  92. package/lib/types/client/standalone/runtime.d.ts +2 -0
  93. package/lib/types/client/submission-registry.d.ts +51 -0
  94. package/lib/types/client/svg-fence.d.ts +2 -0
  95. package/lib/types/client/table-details.d.ts +20 -0
  96. package/lib/types/client/templates.d.ts +41 -0
  97. package/lib/types/client/toolview.d.ts +7 -0
  98. package/lib/types/client/walk-spec.d.ts +3 -0
  99. package/lib/types/index.d.ts +1 -0
  100. package/lib/types/plugin/chart-contract.d.ts +9 -0
  101. package/lib/types/plugin/fence-feedback.d.ts +151 -0
  102. package/lib/types/plugin/genui-diagnostic.d.ts +13 -0
  103. package/lib/types/plugin/index.d.ts +35 -0
  104. package/lib/types/plugin/inline-content-diagnostic.d.ts +8 -0
  105. package/lib/types/plugin/invariant.d.ts +15 -0
  106. package/lib/types/plugin/tool.d.ts +27 -0
  107. package/lib/types/shared/fence-repair.d.ts +78 -0
  108. package/lib/types/shared/fence-resolve.d.ts +39 -0
  109. package/package.json +249 -4
  110. package/src/client/EChartNode.tsx +466 -0
  111. package/src/client/ErrorBoundary.tsx +67 -0
  112. package/src/client/GenuiBlock.module.css +2221 -0
  113. package/src/client/GenuiBlock.tsx +235 -0
  114. package/src/client/PlotBlock.module.css +171 -0
  115. package/src/client/PlotBlock.tsx +492 -0
  116. package/src/client/TemplateDrawer.module.css +152 -0
  117. package/src/client/TemplateDrawer.tsx +147 -0
  118. package/src/client/achievement-store.ts +151 -0
  119. package/src/client/achievement-toast.tsx +71 -0
  120. package/src/client/achievements.ts +160 -0
  121. package/src/client/action-context.ts +32 -0
  122. package/src/client/artifact/ArtifactExport.module.css +64 -0
  123. package/src/client/artifact/ExportableGenuiBlock.tsx +100 -0
  124. package/src/client/artifact/create.ts +69 -0
  125. package/src/client/artifact/download.ts +42 -0
  126. package/src/client/artifact/html.ts +157 -0
  127. package/src/client/artifact/index.ts +15 -0
  128. package/src/client/artifact/json.ts +6 -0
  129. package/src/client/artifact/parse.ts +32 -0
  130. package/src/client/artifact/portability.ts +47 -0
  131. package/src/client/artifact/standalone-theme.ts +94 -0
  132. package/src/client/artifact/types.ts +44 -0
  133. package/src/client/asset-echarts-core.ts +39 -0
  134. package/src/client/asset-echarts.ts +27 -0
  135. package/src/client/asset-loader.ts +96 -0
  136. package/src/client/asset-mermaid.ts +13 -0
  137. package/src/client/asset-three.ts +12 -0
  138. package/src/client/blocks/advanced.tsx +537 -0
  139. package/src/client/blocks/basic.tsx +121 -0
  140. package/src/client/blocks/charts.tsx +999 -0
  141. package/src/client/blocks/checkbox.tsx +61 -0
  142. package/src/client/blocks/diagram/geometry.ts +151 -0
  143. package/src/client/blocks/diagram/index.tsx +293 -0
  144. package/src/client/blocks/diagram/layout.ts +202 -0
  145. package/src/client/blocks/diagram/theme.ts +127 -0
  146. package/src/client/blocks/forms.tsx +531 -0
  147. package/src/client/blocks/image.tsx +28 -0
  148. package/src/client/blocks/render-node.tsx +494 -0
  149. package/src/client/blocks/state.ts +65 -0
  150. package/src/client/blocks/svg.tsx +66 -0
  151. package/src/client/dom-fence.tsx +1123 -0
  152. package/src/client/echarts-engine.ts +9 -0
  153. package/src/client/echarts-lazy.ts +41 -0
  154. package/src/client/embed.ts +19 -0
  155. package/src/client/fence-render.tsx +266 -0
  156. package/src/client/gallery.ts +215 -0
  157. package/src/client/genui-runtime/diagnostics.ts +165 -0
  158. package/src/client/genui-runtime/index.ts +1 -0
  159. package/src/client/genui-runtime/limits.ts +54 -0
  160. package/src/client/genui-runtime/normalize.ts +329 -0
  161. package/src/client/genui-runtime/schema.ts +352 -0
  162. package/src/client/genui-runtime/value-utils.ts +67 -0
  163. package/src/client/guard.ts +1965 -0
  164. package/src/client/i18n/en.ts +335 -0
  165. package/src/client/i18n/index.ts +125 -0
  166. package/src/client/i18n/runtime.ts +130 -0
  167. package/src/client/i18n/zh.ts +330 -0
  168. package/src/client/index.tsx +228 -0
  169. package/src/client/inline.ts +106 -0
  170. package/src/client/interaction-store.ts +127 -0
  171. package/src/client/mermaid-core.ts +158 -0
  172. package/src/client/mermaid-lazy.ts +31 -0
  173. package/src/client/mermaid-safe.ts +122 -0
  174. package/src/client/panel-command.ts +138 -0
  175. package/src/client/panel-store.ts +471 -0
  176. package/src/client/panel.tsx +287 -0
  177. package/src/client/parse-partial.ts +170 -0
  178. package/src/client/primitive-adapter.ts +13 -0
  179. package/src/client/primitive-labels.ts +55 -0
  180. package/src/client/safe-math.ts +298 -0
  181. package/src/client/scene3d-core.ts +195 -0
  182. package/src/client/scene3d-lazy.ts +26 -0
  183. package/src/client/session-resolver.ts +33 -0
  184. package/src/client/source-fence.ts +70 -0
  185. package/src/client/spec.ts +896 -0
  186. package/src/client/standalone/asset-loader.ts +9 -0
  187. package/src/client/standalone/bootstrap-types.ts +11 -0
  188. package/src/client/standalone/katex-style.ts +1 -0
  189. package/src/client/standalone/primitive-adapter.tsx +94 -0
  190. package/src/client/standalone/runtime.tsx +27 -0
  191. package/src/client/submission-registry.ts +150 -0
  192. package/src/client/svg-fence.tsx +39 -0
  193. package/src/client/table-details.ts +151 -0
  194. package/src/client/templates.ts +322 -0
  195. package/src/client/toolview.tsx +67 -0
  196. package/src/client/walk-spec.ts +43 -0
  197. package/src/css-modules.d.ts +5 -0
  198. package/src/index.ts +9 -0
  199. package/src/plugin/chart-contract.ts +13 -0
  200. package/src/plugin/fence-feedback.ts +655 -0
  201. package/src/plugin/genui-diagnostic.ts +112 -0
  202. package/src/plugin/index.ts +224 -0
  203. package/src/plugin/inline-content-diagnostic.ts +178 -0
  204. package/src/plugin/invariant.ts +30 -0
  205. package/src/plugin/node-shims.d.ts +31 -0
  206. package/src/plugin/tool.ts +424 -0
  207. package/src/shared/fence-repair.ts +536 -0
  208. package/src/shared/fence-resolve.ts +80 -0
  209. package/tsconfig.json +35 -0
  210. package/tsdown.config.ts +275 -0
@@ -0,0 +1,61 @@
1
+ import { renderInline } from '../inline.ts'
2
+ import { useEffect, useState } from 'react'
3
+ import css from '../GenuiBlock.module.css'
4
+ import type { GenuiCheckbox } from '../spec.ts'
5
+ import type { AnswersState, GenuiBlockProps } from './state.ts'
6
+
7
+ /**
8
+ * Checkbox with two backwards-compatible modes:
9
+ *
10
+ * - no `group`: legacy local toggle + optional per-click action;
11
+ * - with `group`: local-only multi-select state collected by a sibling submit.
12
+ *
13
+ * A persisted group key wins over `checked`, including an explicit empty
14
+ * array. This lets a user clear every default-checked option without those
15
+ * defaults reappearing after refresh.
16
+ */
17
+ export function CheckboxNode({ node, onAction, answers }: {
18
+ node: GenuiCheckbox
19
+ onAction?: GenuiBlockProps['onAction']
20
+ answers?: AnswersState | undefined
21
+ }) {
22
+ const group = node.group
23
+ const grouped = group !== undefined
24
+ const hasRecordedGroup = group !== undefined
25
+ && Object.prototype.hasOwnProperty.call(answers?.multiAnswers ?? {}, group)
26
+ const recorded = group === undefined ? undefined : answers?.multiAnswers[group]
27
+ const groupChecked = hasRecordedGroup
28
+ ? Array.isArray(recorded) && recorded.includes(node.label)
29
+ : node.checked === true
30
+ const [checked, setChecked] = useState(node.checked === true)
31
+
32
+ useEffect(() => {
33
+ if (group === undefined || node.checked !== true || hasRecordedGroup) return
34
+ // Model-provided defaults are real initial selections, but never override
35
+ // a restored user choice (including an explicitly empty group).
36
+ answers?.setMultiAnswer(group, node.label, true)
37
+ // answers is intentionally omitted: the callbacks are stable and a
38
+ // registry update should not re-register the same default.
39
+ // eslint-disable-next-line react-hooks/exhaustive-deps
40
+ }, [group, node.checked, node.label, hasRecordedGroup])
41
+
42
+ return (
43
+ <label className={css.checkbox}>
44
+ <input
45
+ type="checkbox"
46
+ checked={grouped ? groupChecked : checked}
47
+ onChange={e => {
48
+ const next = e.currentTarget.checked
49
+ setChecked(next)
50
+ if (grouped) {
51
+ // Aggregation mode: update local multi-answer state only.
52
+ answers?.setMultiAnswer(group, node.label, next)
53
+ } else if (node.action !== undefined && onAction !== undefined) {
54
+ onAction(node.action, { type: 'checkbox', checked: next })
55
+ }
56
+ }}
57
+ />
58
+ <span>{renderInline(node.label, false)}</span>
59
+ </label>
60
+ )
61
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * Editorial diagram geometry: the mandatory orthogonal-connector system from
3
+ * diagram-design §6, ported to pure functions producing SVG path strings.
4
+ *
5
+ * Rules enforced here (the "non-negotiable" list):
6
+ * 1. Rounded right-angle (orthogonal) elbows with r=8 — never diagonal lines
7
+ * between off-axis nodes.
8
+ * 2. Edge labels sit 6–10px off the stroke behind an opaque mask.
9
+ * 3. No two connectors share a path — parallel connectors offset ≥12px.
10
+ * 4. Shared-edge attach points fan ≥12px apart.
11
+ * 5. A connector never passes behind a non-endpoint box (dashed-transit
12
+ * exception only when geometrically unavoidable).
13
+ * 6. Label masks never overlap nodes (nodes paint after labels).
14
+ * @module @changfenhuang/dsh-genui/client/blocks/diagram/geometry
15
+ */
16
+
17
+ /** Axis-aligned box. */
18
+ export interface Box {
19
+ x: number
20
+ y: number
21
+ w: number
22
+ h: number
23
+ }
24
+
25
+ export interface Point {
26
+ x: number
27
+ y: number
28
+ }
29
+
30
+ export type Port = 'left' | 'right' | 'top' | 'bottom'
31
+
32
+ /** Attachment on a box edge. */
33
+ export interface Attach {
34
+ x: number
35
+ y: number
36
+ port: Port
37
+ }
38
+
39
+ const R = 8 // elbow radius (r=6 minimum allowed for tight layouts)
40
+
41
+ function centerOf(b: Box): Point {
42
+ return { x: b.x + b.w / 2, y: b.y + b.h / 2 }
43
+ }
44
+
45
+ /** Center of a box. */
46
+ export function center(b: Box): Point {
47
+ return centerOf(b)
48
+ }
49
+
50
+ /**
51
+ * Pick the attach point on `from` toward `to`. Port choice follows the
52
+ * dominant axis: mostly-horizontal travel uses left/right ports, mostly-
53
+ * vertical uses top/bottom. An explicit `prefer` overrides the heuristic.
54
+ */
55
+ export function attachPoint(box: Box, toward: Box, prefer: Port | undefined): Attach {
56
+ if (prefer === 'left') return { x: box.x, y: box.y + box.h / 2, port: 'left' }
57
+ if (prefer === 'right') return { x: box.x + box.w, y: box.y + box.h / 2, port: 'right' }
58
+ if (prefer === 'top') return { x: box.x + box.w / 2, y: box.y, port: 'top' }
59
+ if (prefer === 'bottom') return { x: box.x + box.w / 2, y: box.y + box.h, port: 'bottom' }
60
+ const c = centerOf(box)
61
+ const t = centerOf(toward)
62
+ const dx = t.x - c.x
63
+ const dy = t.y - c.y
64
+ if (Math.abs(dx) >= Math.abs(dy)) {
65
+ return dx >= 0
66
+ ? { x: box.x + box.w, y: box.y + box.h / 2, port: 'right' }
67
+ : { x: box.x, y: box.y + box.h / 2, port: 'left' }
68
+ }
69
+ return dy >= 0
70
+ ? { x: box.x + box.w / 2, y: box.y + box.h, port: 'bottom' }
71
+ : { x: box.x + box.w / 2, y: box.y, port: 'top' }
72
+ }
73
+
74
+ /**
75
+ * Build an orthogonal path between two attach points. Same-axis endpoints use
76
+ * a straight segment (the one sanctioned case); every bend is a quarter arc
77
+ * of radius R.
78
+ */
79
+ export function orthogonalPath(a: Attach, b: Attach): string {
80
+ if (a.x === b.x) return `M ${a.x} ${a.y} L ${b.x} ${b.y}`
81
+ if (a.y === b.y) return `M ${a.x} ${a.y} L ${b.x} ${b.y}`
82
+
83
+ const horizA = a.port === 'left' || a.port === 'right'
84
+ const horizB = b.port === 'left' || b.port === 'right'
85
+
86
+ // Horizontal exit + horizontal entry: two elbows through the midpoint x.
87
+ if (horizA && horizB) {
88
+ const midX = (a.x + b.x) / 2
89
+ const dirA = a.port === 'right' ? 1 : -1
90
+ return `M ${a.x} ${a.y} H ${midX - dirA * R} Q ${midX} ${a.y} ${midX} ${a.y + R} V ${b.y - R} Q ${midX} ${b.y} ${midX + R} ${b.y} H ${b.x}`
91
+ }
92
+
93
+ // Vertical exit + vertical entry: two elbows through the midpoint y.
94
+ if (!horizA && !horizB) {
95
+ const midY = (a.y + b.y) / 2
96
+ const dirA = a.port === 'bottom' ? 1 : -1
97
+ return `M ${a.x} ${a.y} V ${midY - dirA * R} Q ${a.x} ${midY} ${a.x + R} ${midY} H ${b.x - R} Q ${b.x} ${midY} ${b.x} ${midY + R} V ${b.y}`
98
+ }
99
+
100
+ // Mixed exit/entry: one orthogonal bend, then travel along the entry axis.
101
+ if (horizA) {
102
+ const dirA = a.port === 'right' ? 1 : -1
103
+ return `M ${a.x} ${a.y} H ${a.x + dirA * R * 2} Q ${a.x + dirA * R * 2} ${a.y} ${a.x + dirA * R * 2} ${b.y} V ${b.y} H ${b.x}`
104
+ }
105
+ const dirA = a.port === 'bottom' ? 1 : -1
106
+ return `M ${a.x} ${a.y} V ${a.y + dirA * R * 2} Q ${a.x} ${a.y + dirA * R * 2} ${b.x} ${a.y + dirA * R * 2} H ${b.x} V ${b.y}`
107
+ }
108
+
109
+ /**
110
+ * Route a connector between two boxes with default port selection, returning
111
+ * the path plus both attach points (for label placement and fan offsets).
112
+ */
113
+ export function routeEdge(from: Box, to: Box, opts?: { fromPort?: Port; toPort?: Port }): { d: string; a: Attach; b: Attach } {
114
+ const a = attachPoint(from, to, opts?.fromPort)
115
+ const b = attachPoint(to, from, opts?.toPort)
116
+ return { d: orthogonalPath(a, b), a, b }
117
+ }
118
+
119
+ /** Fan an attach point along a box edge (≥12px apart via the (k+1)/(n+1) rule). */
120
+ export function fanPoint(box: Box, edge: 'top' | 'bottom' | 'left' | 'right', index: number, count: number): Attach {
121
+ const n = Math.max(1, count)
122
+ const t = (index + 1) / (n + 1)
123
+ if (edge === 'top' || edge === 'bottom') {
124
+ const x = box.x + box.w * t
125
+ return edge === 'top' ? { x, y: box.y, port: 'top' } : { x, y: box.y + box.h, port: 'bottom' }
126
+ }
127
+ const y = box.y + box.h * t
128
+ return edge === 'left' ? { x: box.x, y, port: 'left' } : { x: box.x + box.w, y, port: 'right' }
129
+ }
130
+
131
+ /**
132
+ * Edge-label geometry: centered on the dominant segment, offset 6–10px from
133
+ * the stroke so the connector stays visible.
134
+ */
135
+ export function labelGeometry(a: Attach, b: Attach): { cx: number; cy: number; maskY: number; vertical: boolean } {
136
+ const cx = (a.x + b.x) / 2
137
+ const cy = (a.y + b.y) / 2
138
+ const vertical = Math.abs(a.x - b.x) < Math.abs(a.y - b.y)
139
+ if (vertical) {
140
+ const side = b.x >= a.x ? 1 : -1
141
+ return { cx: cx + side * 16, cy, maskY: cy - 6, vertical }
142
+ }
143
+ return { cx, cy, maskY: cy - 20, vertical }
144
+ }
145
+
146
+ /** Hop / bridge arc for a crossing connector (applied to the less important edge). */
147
+ export function bridgePath(cx: number, cy: number, horizontal: boolean): string {
148
+ return horizontal
149
+ ? `M ${cx - 8} ${cy} a 8,8 0 0,1 16,0`
150
+ : `M ${cx} ${cy - 8} a 8,8 0 0,0 0,16`
151
+ }
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Editorial diagram renderer: `diagram` node → inline SVG. The browser-side
3
+ * port of the diagram-design editorial design system — semantic tokens,
4
+ * dotted-paper ground, orthogonal connectors, 4px grid, complexity budget,
5
+ * zone grouping, legend strip — as a white-listed dsh-genui component.
6
+ *
7
+ * Layout is resolved by `resolveLayout`, routing by `routeEdge`, and every
8
+ * value is sanitized by the guard before this component ever sees it.
9
+ * @module @changfenhuang/dsh-genui/client/blocks/diagram
10
+ */
11
+ import { renderInline } from '../../inline.ts'
12
+ import { useMemo } from 'react'
13
+ import type { GenuiDiagram } from '../../spec.ts'
14
+ import { GENUI_LIMITS } from '../../genui-runtime/index.ts'
15
+ import { resolveLayout } from './layout.ts'
16
+ import { routeEdge, labelGeometry, type Box } from './geometry.ts'
17
+ import { resolvePalette, nodeTreatment, edgeStroke, inkAt } from './theme.ts'
18
+
19
+ const FONT_SANS = "'Geist', -apple-system, 'Segoe UI', sans-serif"
20
+ const FONT_MONO = "'Geist Mono', ui-monospace, 'SF Mono', monospace"
21
+
22
+ /** Editorial constants (diagram-design §5–7). */
23
+ const NODE_H = 64 // node box height (48→64 for the editorial ramp)
24
+ const LEGEND_COL_W = 150
25
+ const LEGEND_ROW_H = 22
26
+ const LEGEND_ITEMS: Array<{ label: string; type: string | undefined }> = [
27
+ { label: 'Focal', type: 'focal' },
28
+ { label: 'Backend', type: 'backend' },
29
+ { label: 'Store', type: 'store' },
30
+ { label: 'External', type: 'external' },
31
+ { label: 'Optional', type: 'optional' },
32
+ { label: 'Security', type: 'security' },
33
+ ]
34
+
35
+ /**
36
+ * Compute a deterministic parent map for tree-like kinds: the first edge
37
+ * into each node is its parent (a stable convention the model can rely on).
38
+ */
39
+ function buildParentMap(edges: Array<{ from: string; to: string }>): (id: string) => string | undefined {
40
+ const parents = new Map<string, string>()
41
+ for (const e of edges) {
42
+ if (!parents.has(e.to)) parents.set(e.to, e.from)
43
+ }
44
+ return id => parents.get(id)
45
+ }
46
+
47
+ /** Render one node box + its text content (tag / name / sublabel). */
48
+ function renderNodeBox(
49
+ box: Box,
50
+ label: string,
51
+ sub: string | undefined,
52
+ type: string | undefined,
53
+ tag: string | undefined,
54
+ palette: ReturnType<typeof resolvePalette>,
55
+ ): React.ReactNode {
56
+ const treatment = nodeTreatment(type, palette)
57
+ const cx = box.x + box.w / 2
58
+ // Editorial 64px ramp: name centered, sublabel below, tag top-left.
59
+ const nameY = box.y + (box.h - NODE_H) / 2 + 28
60
+ const subY = box.y + (box.h - NODE_H) / 2 + 44
61
+ const tagW = Math.min(44, Math.max(24, (tag ?? '').length * 7 + 8))
62
+ return (
63
+ <g>
64
+ {/* opaque paper mask: arrows must not bleed through transparent fills */}
65
+ <rect x={box.x} y={box.y} width={box.w} height={box.h} rx={6} fill={palette.paper} />
66
+ <rect
67
+ x={box.x}
68
+ y={box.y}
69
+ width={box.w}
70
+ height={box.h}
71
+ rx={6}
72
+ fill={treatment.fill}
73
+ stroke={treatment.stroke}
74
+ strokeWidth={1}
75
+ strokeDasharray={treatment.dashed === true ? '5,4' : undefined}
76
+ />
77
+ {tag !== undefined && (
78
+ <>
79
+ <rect x={box.x + 8} y={box.y + 6} width={tagW} height={12} rx={2} fill="transparent" stroke={inkAt(treatment.stroke, 0.4)} strokeWidth={0.8} />
80
+ <text x={box.x + 8 + tagW / 2} y={box.y + 15} fill={inkAt(treatment.stroke, 0.8)} fontSize={7} fontFamily={FONT_MONO} textAnchor="middle" letterSpacing={0.8}>{tag}</text>
81
+ </>
82
+ )}
83
+ <text x={cx} y={nameY} fill={palette.ink} fontSize={12} fontWeight={600} fontFamily={FONT_SANS} textAnchor="middle">{label}</text>
84
+ {sub !== undefined && (
85
+ <text x={cx} y={subY} fill={palette.soft} fontSize={9} fontFamily={FONT_MONO} textAnchor="middle">{sub}</text>
86
+ )}
87
+ </g>
88
+ )
89
+ }
90
+
91
+ /** Render one routed edge: path, optional label mask + text. */
92
+ function renderEdge(edge: { from: Box; to: Box; label?: string | undefined; kind?: string | undefined }, key: number, palette: ReturnType<typeof resolvePalette>, markerId: string): React.ReactNode {
93
+ const routed = routeEdge(edge.from, edge.to)
94
+ const stroke = edgeStroke(edge.kind, palette)
95
+ const dashed = edge.kind === 'dashed'
96
+ // Accent arrows are the focal signal: slightly heavier stroke (1.4).
97
+ const width = edge.kind === 'accent' ? 1.4 : 1.2
98
+ const lg = labelGeometry(routed.a, routed.b)
99
+ return (
100
+ <g key={key}>
101
+ <path
102
+ d={routed.d}
103
+ fill="none"
104
+ stroke={stroke}
105
+ strokeWidth={width}
106
+ strokeDasharray={dashed ? '5,4' : undefined}
107
+ markerEnd={`url(#${markerId})`}
108
+ />
109
+ {edge.label !== undefined && (
110
+ <g>
111
+ <rect
112
+ x={lg.cx - (edge.label.length * 5 + 8) / 2}
113
+ y={lg.maskY}
114
+ width={edge.label.length * 5 + 8}
115
+ height={12}
116
+ rx={2}
117
+ fill={palette.paper}
118
+ />
119
+ <text x={lg.cx} y={lg.maskY + 9} fill={palette.soft} fontSize={8} fontFamily={FONT_MONO} textAnchor="middle" letterSpacing={0.5}>{edge.label}</text>
120
+ </g>
121
+ )}
122
+ </g>
123
+ )
124
+ }
125
+
126
+ /** Arrow marker defs (default / accent / link), per-diagram unique ids. */
127
+ function renderMarkers(uid: string, palette: ReturnType<typeof resolvePalette>): React.ReactNode {
128
+ return (
129
+ <defs>
130
+ <marker id={`${uid}-arrow`} markerWidth={8} markerHeight={6} refX={7} refY={3} orient="auto">
131
+ <polygon points="0 0, 8 3, 0 6" fill={palette.muted} />
132
+ </marker>
133
+ <marker id={`${uid}-arrow-accent`} markerWidth={8} markerHeight={6} refX={7} refY={3} orient="auto">
134
+ <polygon points="0 0, 8 3, 0 6" fill={palette.accent} />
135
+ </marker>
136
+ <marker id={`${uid}-arrow-link`} markerWidth={8} markerHeight={6} refX={7} refY={3} orient="auto">
137
+ <polygon points="0 0, 8 3, 0 6" fill={palette.link} />
138
+ </marker>
139
+ </defs>
140
+ )
141
+ }
142
+
143
+ /** Dotted-paper ground: the editorial backdrop behind every diagram. */
144
+ function renderGround(uid: string, palette: ReturnType<typeof resolvePalette>): React.ReactNode {
145
+ return (
146
+ <>
147
+ <defs>
148
+ <pattern id={`${uid}-dots`} width={22} height={22} patternUnits="userSpaceOnUse">
149
+ <circle cx={1} cy={1} r={0.9} fill={inkAt(palette.ink, 0.10)} />
150
+ </pattern>
151
+ </defs>
152
+ <rect width="100%" height="100%" fill={palette.paper} />
153
+ <rect width="100%" height="100%" fill={`url(#${uid}-dots)`} opacity={0.55} />
154
+ </>
155
+ )
156
+ }
157
+
158
+ /** Zone container: hairline dashed rect + mono uppercase eyebrow label. */
159
+ function renderZone(z: { label: string; x: number; y: number; w: number; h: number }, palette: ReturnType<typeof resolvePalette>): React.ReactNode {
160
+ const labelW = z.label.length * 7 + 12
161
+ const cx = z.x + z.w / 2
162
+ return (
163
+ <g>
164
+ <rect x={z.x} y={z.y} width={z.w} height={z.h} rx={8} fill={inkAt(palette.ink, 0.02)} stroke={inkAt(palette.ink, 0.10)} strokeWidth={0.8} />
165
+ <rect x={cx - labelW / 2} y={z.y + 4} width={labelW} height={12} rx={2} fill={palette.paper} />
166
+ <text x={cx} y={z.y + 13} fill={inkAt(palette.ink, 0.40)} fontSize={7} fontFamily={FONT_MONO} textAnchor="middle" letterSpacing={1.2}>{z.label}</text>
167
+ </g>
168
+ )
169
+ }
170
+
171
+ /** Legend strip at the bottom: hairline separator + treatment swatches. */
172
+ function renderLegend(palette: ReturnType<typeof resolvePalette>, items: typeof LEGEND_ITEMS, width: number, cols: number): React.ReactNode {
173
+ return (
174
+ <g>
175
+ <line x1={40} y1={0} x2={Math.max(120, width - 40)} y2={0} stroke={inkAt(palette.ink, 0.10)} strokeWidth={0.8} />
176
+ <text x={40} y={16} fill={palette.soft} fontSize={8} fontFamily={FONT_MONO} letterSpacing={1.6}>LEGEND</text>
177
+ {items.map((item, i) => {
178
+ const t = nodeTreatment(item.type, palette)
179
+ const x = 40 + (i % cols) * LEGEND_COL_W
180
+ const y = 32 + Math.floor(i / cols) * LEGEND_ROW_H
181
+ return (
182
+ <g key={item.label}>
183
+ <rect x={x} y={y} width={14} height={10} rx={2} fill={t.fill} stroke={t.stroke} strokeWidth={1} strokeDasharray={t.dashed === true ? '3,2' : undefined} />
184
+ <text x={x + 20} y={y + 9} fill={palette.soft} fontSize={8.5} fontFamily={FONT_SANS}>{item.label}</text>
185
+ </g>
186
+ )
187
+ })}
188
+ </g>
189
+ )
190
+ }
191
+
192
+ function markerFor(kind: string | undefined, uid: string): string {
193
+ if (kind === 'accent') return `${uid}-arrow-accent`
194
+ if (kind === 'link') return `${uid}-arrow-link`
195
+ return `${uid}-arrow`
196
+ }
197
+
198
+ /** Stable per-render uid (avoid id collisions across diagrams on one page). */
199
+ let uidCounter = 0
200
+ function nextUid(): string {
201
+ uidCounter += 1
202
+ return `genui-diagram-${uidCounter}`
203
+ }
204
+
205
+ /** The `diagram` node renderer. */
206
+ export function DiagramNode({ node }: { node: GenuiDiagram }) {
207
+ const uid = useMemo(nextUid, [])
208
+ // CSS token references follow the surrounding theme without remounting SVG nodes.
209
+ const palette = useMemo(() => resolvePalette(node.variant, node.theme), [node.variant, node.theme])
210
+ const layout = useMemo(() => resolveLayout(node, buildParentMap(node.edges ?? [])), [node])
211
+
212
+ const byId = useMemo(() => new Map(layout.nodes.map(l => [l.node.id, l.box])), [layout])
213
+ // figcaption gets its own id so aria-labelledby can point at the SVG <title>
214
+ // alone — sharing one id between the two renders duplicates ids in the DOM.
215
+ const titleId = `${uid}-title`
216
+ const captionId = `${uid}-caption`
217
+ const descId = `${uid}-desc`
218
+
219
+ // Complexity budget is enforced by the guard; belt-and-suspenders here.
220
+ const nodes = layout.nodes.slice(0, GENUI_LIMITS.maxDiagramNodes)
221
+ const edges = layout.edges.slice(0, GENUI_LIMITS.maxDiagramEdges)
222
+ const zones = (node.zones ?? []).slice(0, GENUI_LIMITS.maxDiagramZones)
223
+
224
+ // Focal budget: accent on 1–2 nodes max; extra focal nodes downgrade to backend.
225
+ let focalSeen = 0
226
+ const focalBudget = GENUI_LIMITS.maxDiagramFocal
227
+
228
+ // Canvas: content bounds + editorial chrome (bottom legend strip).
229
+ const contentH = layout.height
230
+ // Legend: only the types this diagram actually uses, wrapped to the canvas
231
+ // width (the old fixed 170px pitch + hardcoded 1000px rule overflowed any
232
+ // narrow canvas and printed "Extern…").
233
+ const legendItems = LEGEND_ITEMS.filter(item => item.type !== undefined
234
+ && nodes.some(n => (n.node.type ?? 'backend') === item.type))
235
+ const legendCols = Math.max(1, Math.floor((layout.width - 40) / LEGEND_COL_W))
236
+ const legendRows = Math.max(1, Math.ceil(legendItems.length / legendCols))
237
+ const legendH = 24 + legendRows * LEGEND_ROW_H
238
+ const canvasH = contentH + legendH + 12
239
+
240
+ return (
241
+ <figure className="genui-diagram" data-genui-diagram>
242
+ {node.title !== undefined && (
243
+ <figcaption id={captionId} style={{ fontFamily: "Instrument Serif, 'Times New Roman', serif", fontSize: 20, marginBottom: 8, color: palette.ink }}>
244
+ {renderInline(node.title)}
245
+ </figcaption>
246
+ )}
247
+ <svg
248
+ role="img"
249
+ aria-labelledby={titleId}
250
+ aria-describedby={descId}
251
+ viewBox={`0 0 ${layout.width} ${canvasH}`}
252
+ style={{ maxWidth: '100%', height: 'auto', background: palette.paper }}
253
+ >
254
+ <title id={titleId}>{node.title ?? node.kind}</title>
255
+ <desc id={descId}>{`${node.kind} diagram with ${nodes.length} nodes and ${edges.length} connectors`}</desc>
256
+ {renderMarkers(uid, palette)}
257
+ {renderGround(uid, palette)}
258
+ {/* zones drawn before arrows and nodes */}
259
+ <g>
260
+ {zones.map((z, i) => (
261
+ <g key={`zone-${i}`}>
262
+ {renderZone({ label: z.label, x: z.x ?? 0, y: z.y ?? 0, w: z.w ?? 100, h: z.h ?? 100 }, palette)}
263
+ </g>
264
+ ))}
265
+ </g>
266
+ <g>
267
+ {edges.map((e, i) => {
268
+ const from = byId.get(e.fromId)
269
+ const to = byId.get(e.toId)
270
+ if (from === undefined || to === undefined) return null
271
+ return renderEdge({ from, to, label: e.edge.label, kind: e.edge.kind }, i, palette, markerFor(e.edge.kind, uid))
272
+ })}
273
+ </g>
274
+ {/* nodes after edges */}
275
+ <g>
276
+ {nodes.map(l => {
277
+ const effectiveType = l.node.type === 'focal' && focalSeen >= focalBudget ? undefined : l.node.type
278
+ if (l.node.type === 'focal') focalSeen += 1
279
+ return (
280
+ <g key={l.node.id}>
281
+ {renderNodeBox(l.box, l.node.label, l.node.sub, effectiveType, l.node.tag, palette)}
282
+ </g>
283
+ )
284
+ })}
285
+ </g>
286
+ {/* legend strip */}
287
+ <g transform={`translate(0, ${contentH + 8})`}>
288
+ {renderLegend(palette, legendItems, layout.width, legendCols)}
289
+ </g>
290
+ </svg>
291
+ </figure>
292
+ )
293
+ }