@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,494 @@
1
+ /**
2
+ * The recursive render dispatcher: maps the white-listed GenuiNode union to
3
+ * concrete components. Leaf cases render inline; compound families live in
4
+ * the sibling block modules. Depth-guarded against pathological specs.
5
+ * @module @changfenhuang/dsh-genui/client/blocks/render-node
6
+ */
7
+ import { type ComponentType, type ReactNode, useEffect, useState, type CSSProperties } from 'react'
8
+ import * as primitives from '../primitive-adapter.ts'
9
+ import css from '../GenuiBlock.module.css'
10
+ import { GENUI_LIMITS } from '../genui-runtime/index.ts'
11
+ import { renderInline } from '../inline.ts'
12
+ import { t } from '../i18n/index.ts'
13
+ import type { GenuiList, GenuiNode } from '../spec.ts'
14
+ import type { AnswersState, GenuiBlockProps } from './state.ts'
15
+ import { AudioNode, avatarColor, ClickFeedbackButton, VideoNode } from './basic.tsx'
16
+ import { ChartNode, TableNode } from './charts.tsx'
17
+ import {
18
+ InputNode, RadioNode, SelectNode, SliderNode, SubmitNode, SwitchNode, TextareaNode,
19
+ } from './forms.tsx'
20
+ import { CheckboxNode } from './checkbox.tsx'
21
+ import {
22
+ AccordionNode, BreadcrumbNode, CalloutNode, CodeNode, CopyNode, DiffNode, FileTreeNode, JsonNode, KeyValueNode,
23
+ MermaidNode, PlotNode, QuizNode, Scene3DNode, StepsNode, TabsNode, TimelineNode,
24
+ } from './advanced.tsx'
25
+ import { DiagramNode } from './diagram/index.tsx'
26
+ import { ImageNode } from './image.tsx'
27
+ import { SvgNode } from './svg.tsx'
28
+
29
+ import { EChartNode } from '../EChartNode.tsx'
30
+
31
+ /** Custom node data shape (declared locally: pristine hosts export no type). */
32
+ interface GenuiCustomNode {
33
+ type: string
34
+ [key: string]: unknown
35
+ }
36
+
37
+ /** Props a registered custom renderer receives. */
38
+ interface GenuiCustomProps {
39
+ node: GenuiCustomNode
40
+ onAction?: GenuiBlockProps['onAction']
41
+ renderChildren: (nodes: unknown[], keyBase: string) => unknown
42
+ }
43
+
44
+ /** Custom-component registry lookup, feature-detected (contract hosts only). */
45
+ type HostGenuiExt = {
46
+ getGenuiComponent?: (type: string) => ComponentType<GenuiCustomProps> | undefined
47
+ }
48
+ const getGenuiComponent = (primitives as unknown as HostGenuiExt).getGenuiComponent
49
+
50
+ function isListItemNode(item: GenuiList['items'][number]): item is GenuiNode {
51
+ return typeof item === 'object' && item !== null && 'type' in item
52
+ }
53
+
54
+ /**
55
+ * Split a stat value into its numeric core and unit suffix so the unit can
56
+ * render at half size on the same baseline (`99.96%` → `99.96` + `%`,
57
+ * `6.8 GB` → `6.8` + `GB`). Values that do not start with a number are left
58
+ * whole.
59
+ */
60
+ function splitStatValue(value: string): {
61
+ num: string
62
+ unit: string
63
+ /** Parsed number when the numeric core is a plain decimal (for count-up). */
64
+ numeric: number | undefined
65
+ /** Decimal places to keep while animating. */
66
+ decimals: number
67
+ } {
68
+ const match = /^([+\-−]?[\d.,]+(?:[eE][+\-]?\d+)?)\s*(.*)$/.exec(value.trim())
69
+ if (match === null || match[1] === undefined) return { num: value, unit: '', numeric: undefined, decimals: 0 }
70
+ const raw = match[1]
71
+ const plain = raw.replace(/[,,]/g, '')
72
+ const parsed = Number(plain)
73
+ // Commas are thousands separators in a number, but a grouped metric like
74
+ // "1,2" is not worth animating — keep it static.
75
+ const numeric = Number.isFinite(parsed) && !/[eE]/.test(plain) ? parsed : undefined
76
+ const decimals = plain.includes('.') ? (plain.split('.')[1] ?? '').length : 0
77
+ return { num: raw, unit: match[2] ?? '', numeric, decimals: Math.min(decimals, 4) }
78
+ }
79
+
80
+ /**
81
+ * Micro trend line for `stat.spark`: a 96×24 box stretched to the card width,
82
+ * with an area wash under the line and a constant-size end dot (a zero-length
83
+ * round-capped path with non-scaling stroke, so the stretched viewBox cannot
84
+ * turn the dot into an ellipse).
85
+ */
86
+ function Sparkline({ values }: { values: number[] }) {
87
+ const W = 96
88
+ const H = 24
89
+ const pad = 2
90
+ const min = Math.min(...values)
91
+ const max = Math.max(...values)
92
+ const span = max - min || 1
93
+ const step = values.length <= 1 ? 0 : (W - pad * 2) / (values.length - 1)
94
+ const coords = values.map((v, i) => [
95
+ pad + i * step,
96
+ H - pad - ((v - min) / span) * (H - pad * 2),
97
+ ] as const)
98
+ const points = coords.map(([px, py]) => `${px.toFixed(1)},${py.toFixed(1)}`).join(' ')
99
+ const last = coords[coords.length - 1]!
100
+ const area = `M ${pad},${H - pad} L ${points.split(' ').join(' L ')} L ${last[0].toFixed(1)},${H - pad} Z`
101
+ return (
102
+ <svg className={css.statSpark} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" aria-hidden="true">
103
+ <path d={area} fill="var(--dsl-g-accent)" opacity="0.14" />
104
+ <polyline
105
+ points={points}
106
+ fill="none"
107
+ stroke="var(--dsl-g-accent)"
108
+ strokeWidth="1.5"
109
+ strokeLinejoin="round"
110
+ strokeLinecap="round"
111
+ vectorEffect="non-scaling-stroke"
112
+ />
113
+ <path
114
+ d={`M ${last[0].toFixed(1)} ${last[1].toFixed(1)} L ${last[0].toFixed(1)} ${last[1].toFixed(1)}`}
115
+ stroke="var(--dsl-g-accent)"
116
+ strokeWidth={5}
117
+ strokeLinecap="round"
118
+ vectorEffect="non-scaling-stroke"
119
+ fill="none"
120
+ />
121
+ </svg>
122
+ )
123
+ }
124
+
125
+ /** Live value of a bound control (`node.filter` / `node.sortField`): the field id
126
+ * resolves against the block's shared field registry, so typing in an input
127
+ * re-renders every component bound to it. */
128
+ /**
129
+ * Animate a metric from 0 to its target once on mount. Only used for values
130
+ * that are pure numbers with an optional unit — counting up "v0.9.9" would be
131
+ * nonsense, and prefers-reduced-motion turns it off entirely.
132
+ */
133
+ function useCountUp(target: number, decimals: number, enabled: boolean): string {
134
+ const [value, setValue] = useState(enabled ? 0 : target)
135
+ useEffect(() => {
136
+ if (!enabled) { setValue(target); return }
137
+ const reduce = typeof window !== 'undefined'
138
+ && typeof window.matchMedia === 'function'
139
+ && window.matchMedia('(prefers-reduced-motion: reduce)').matches
140
+ if (reduce) { setValue(target); return }
141
+ let raf = 0
142
+ const start = performance.now()
143
+ const duration = 720
144
+ const tick = (now: number): void => {
145
+ const t = Math.min(1, (now - start) / duration)
146
+ const eased = 1 - Math.pow(1 - t, 3)
147
+ setValue(target * eased)
148
+ if (t < 1) raf = requestAnimationFrame(tick)
149
+ }
150
+ raf = requestAnimationFrame(tick)
151
+ return () => cancelAnimationFrame(raf)
152
+ }, [target, enabled])
153
+ return value.toFixed(decimals)
154
+ }
155
+
156
+ /** Animated metric text: splits the value into number + unit and counts the
157
+ * number up once. A component (not a helper) so the hook has a stable owner —
158
+ * renderNode's switch must never call hooks conditionally. */
159
+ function AnimatedValue({ value, unitClass, animate = false }: {
160
+ value: string
161
+ unitClass?: string | undefined
162
+ /** Only hero-scale numbers count up: a grid of eight stats all ticking at
163
+ * once reads as a gimmick, not as polish. */
164
+ animate?: boolean | undefined
165
+ }) {
166
+ const parts = splitStatValue(value)
167
+ const target = parts.numeric
168
+ const animated = useCountUp(target ?? 0, parts.decimals, animate && target !== undefined)
169
+ return (
170
+ <>
171
+ {target === undefined ? renderInline(parts.num) : animated}
172
+ {parts.unit !== '' && <span className={unitClass ?? css.statUnit}>{renderInline(parts.unit)}</span>}
173
+ </>
174
+ )
175
+ }
176
+
177
+ /** Plain text of a list item, for the local filter. */
178
+ function listItemText(item: GenuiList['items'][number]): string {
179
+ if (typeof item === 'string') return item
180
+ if (isListItemNode(item)) return ''
181
+ return `${item.title} ${item.desc ?? ''}`
182
+ }
183
+
184
+ function boundField(answers: AnswersState | undefined, id: string | undefined): string | undefined {
185
+ if (id === undefined) return undefined
186
+ const value = answers?.fields[id]
187
+ return value === undefined || value === '' ? undefined : value
188
+ }
189
+
190
+ export function renderNode(
191
+ node: GenuiNode,
192
+ key: number,
193
+ onAction: GenuiBlockProps['onAction'] | undefined,
194
+ depth = 0,
195
+ answers?: AnswersState,
196
+ ): ReactNode {
197
+ // Depth guard: a pathological spec must never recurse past the limit
198
+ // (stack overflow / DOM explosion). The fence path already repairs specs
199
+ // against the same limit; this is the belt-and-suspenders for direct
200
+ // GenuiBlock use and plugin-registered custom renderers.
201
+ if (depth > GENUI_LIMITS.maxDepth) return null
202
+
203
+ switch (node.type) {
204
+ case 'text': {
205
+ const size = node.size ?? 'body'
206
+ return (
207
+ <div key={key} className={`${css.text} ${css[size]}` + (node.center ? ` ${css.center}` : '')}>
208
+ {renderInline(node.content)}
209
+ </div>
210
+ )
211
+ }
212
+ case 'row': {
213
+ return (
214
+ <div key={key} className={css.row + (node.wrap ? ` ${css.wrap}` : '')}>
215
+ {node.items.map((c, i) => renderNode(c, i, onAction, depth + 1, answers))}
216
+ {node.spacer && <div className={css.spacer} />}
217
+ </div>
218
+ )
219
+ }
220
+ case 'col': {
221
+ return (
222
+ <div key={key} className={css.col} style={node.gap !== undefined ? { gap: `${node.gap}px` } : undefined}>
223
+ {node.items.map((c, i) => renderNode(c, i, onAction, depth + 1, answers))}
224
+ </div>
225
+ )
226
+ }
227
+ case 'grid': {
228
+ return (
229
+ <div key={key} className={css.grid} style={{ gridTemplateColumns: `repeat(${Math.max(1, node.cols)}, minmax(0, 1fr))` }}>
230
+ {/* `span` is the bento primitive: a child can occupy several columns,
231
+ so one wide hero card can sit next to two narrow ones. */}
232
+ {node.items.map((c, i) => {
233
+ const child = renderNode(c, i, onAction, depth + 1, answers)
234
+ const span = typeof c === 'object' && c !== null && typeof (c as { span?: unknown }).span === 'number'
235
+ ? Math.max(1, Math.min(12, (c as { span: number }).span))
236
+ : 1
237
+ return span > 1 ? <div key={i} className={css.gridSpan} style={{ gridColumn: `span ${span}` }}>{child}</div> : child
238
+ })}
239
+ </div>
240
+ )
241
+ }
242
+ case 'card': {
243
+ const toneClass = node.tone === undefined ? '' : ` ${css[`card${node.tone[0]!.toUpperCase()}${node.tone.slice(1)}`] ?? ''}`
244
+ // An explicit accent drives border + title + a very light wash; it is a
245
+ // colour hint, not a layout change, so it composes with tone.
246
+ // An accent card keeps its NEUTRAL surface: tinting the background with
247
+ // 7% of a warm hue over a dark theme produced a muddy olive block that
248
+ // read as a warning box. The hue now shows up only where it can stay
249
+ // clean — a blended border and the title — which also keeps charts and
250
+ // tables inside the card colour-neutral.
251
+ const accentStyle = node.accent === undefined ? undefined : {
252
+ borderColor: `color-mix(in srgb, ${node.accent} 18%, var(--dsl-g-border))`,
253
+ '--dsl-card-accent': node.accent,
254
+ } as CSSProperties
255
+ return (
256
+ <div key={key} className={`${css.card}${toneClass}`} style={accentStyle}>
257
+ {node.title !== undefined && <div className={css.cardTitle}>{renderInline(node.title)}</div>}
258
+ {node.items.map((c, i) => renderNode(c, i, onAction, depth + 1, answers))}
259
+ </div>
260
+ )
261
+ }
262
+ case 'button': {
263
+ const tone = node.tone ?? ''
264
+ const cls = `${css.button} ${css[tone] || ''}` + (node.full ? ` ${css.full}` : '') + (node.small ? ` ${css.small}` : '')
265
+ const action = node.action
266
+ // A button without an action (or without an action provider) is a
267
+ // display-only control: render it DISABLED so the affordance is honest
268
+ // — clickable-looking dead buttons were the top complaint in the field.
269
+ const interactive = action !== undefined && onAction !== undefined
270
+ return (
271
+ <ClickFeedbackButton
272
+ key={key}
273
+ className={cls}
274
+ disabled={!interactive}
275
+ onClick={interactive ? () => onAction(action, { type: 'button', label: node.label }) : undefined}
276
+ >
277
+ {node.icon !== undefined && <span aria-hidden>{node.icon} </span>}
278
+ {renderInline(node.label, false)}
279
+ </ClickFeedbackButton>
280
+ )
281
+ }
282
+ case 'input': return <InputNode key={key} node={node} onAction={onAction} answers={answers} />
283
+ case 'select': return <SelectNode key={key} node={node} onAction={onAction} answers={answers} />
284
+ case 'checkbox': return <CheckboxNode key={key} node={node} onAction={onAction} answers={answers} />
285
+ case 'link': {
286
+ // Honest affordance: with a whitelisted href this is a REAL anchor;
287
+ // without one it is plain styled text (a dead clickable-looking button
288
+ // was the same complaint class as the disabled-button fix).
289
+ const href = node.href
290
+ return href !== undefined
291
+ ? <a key={key} className={css.link} href={href} target="_blank" rel="noopener noreferrer">{renderInline(node.label, false)}</a>
292
+ : <span key={key} className={css.linkText}>{renderInline(node.label, false)}</span>
293
+ }
294
+ case 'image': return <ImageNode key={`${key}:${node.src}`} node={node} />
295
+ case 'audio': return <AudioNode key={`${key}:${node.src}`} node={node} />
296
+ case 'video': return <VideoNode key={`${key}:${node.src}`} node={node} />
297
+ case 'badge': {
298
+ const tone = node.tone ?? ''
299
+ return (
300
+ <span key={key} className={`${css.badge} ${css[tone] || ''}`}>
301
+ {node.icon !== undefined && <span aria-hidden>{node.icon} </span>}
302
+ <span className={css.badgeLabel}>{renderInline(node.label, false)}</span>
303
+ </span>
304
+ )
305
+ }
306
+ case 'hero': {
307
+ const tone = node.tone ?? 'accent'
308
+ const heroTone = css[`hero${tone[0]!.toUpperCase()}${tone.slice(1)}`] ?? ''
309
+ const heroDown = node.delta !== undefined && node.delta.startsWith('-')
310
+ return (
311
+ <div key={key} className={`${css.hero} ${heroTone}`}>
312
+ {node.label !== undefined && <span className={css.heroLabel}>{renderInline(node.label, false)}</span>}
313
+ <div className={css.heroTop}>
314
+ {node.value !== undefined && (
315
+ <span className={css.heroValue}><AnimatedValue value={node.value} unitClass={css.heroUnit} animate /></span>
316
+ )}
317
+ {node.delta !== undefined && (
318
+ <span className={`${css.statDelta} ${heroDown ? css.down : css.up}`}>{renderInline(node.delta)}</span>
319
+ )}
320
+ {node.spark !== undefined && <span className={css.heroSpark}><Sparkline values={node.spark} /></span>}
321
+ </div>
322
+ <span className={css.heroTitle}>{renderInline(node.title)}</span>
323
+ {node.subtitle !== undefined && <span className={css.heroSubtitle}>{renderInline(node.subtitle)}</span>}
324
+ </div>
325
+ )
326
+ }
327
+ case 'stat': {
328
+ const down = node.delta !== undefined && node.delta.startsWith('-')
329
+ return (
330
+ <div key={key} className={`${css.stat}${node.size === 'hero' ? ` ${css.statHero}` : ''}`}>
331
+ <span className={css.statLabel}>{renderInline(node.label, false)}</span>
332
+ <span className={css.statValue}>
333
+ <AnimatedValue value={node.value} animate={node.size === 'hero'} />
334
+ </span>
335
+ {node.delta !== undefined && <span className={`${css.statDelta} ${down ? css.down : css.up}`}>{renderInline(node.delta)}</span>}
336
+ {node.spark !== undefined && <Sparkline values={node.spark} />}
337
+ </div>
338
+ )
339
+ }
340
+ case 'progress': {
341
+ const v = Math.max(0, Math.min(100, Number(node.value) || 0))
342
+ if (node.variant === 'ring') {
343
+ const R = 34
344
+ const C = 2 * Math.PI * R
345
+ const size = 92
346
+ return (
347
+ <div
348
+ key={key}
349
+ className={css.ring}
350
+ role="progressbar"
351
+ aria-valuemin={0}
352
+ aria-valuemax={100}
353
+ aria-valuenow={v}
354
+ aria-label={node.label ?? node.valueLabel ?? undefined}
355
+ >
356
+ <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} aria-hidden="true">
357
+ <circle cx={size / 2} cy={size / 2} r={R} fill="none" strokeWidth={9} className={css.ringTrack} />
358
+ <circle
359
+ cx={size / 2}
360
+ cy={size / 2}
361
+ r={R}
362
+ fill="none"
363
+ strokeWidth={9}
364
+ strokeLinecap="round"
365
+ className={css.ringFill}
366
+ strokeDasharray={`${(v / 100) * C} ${C}`}
367
+ transform={`rotate(-90 ${size / 2} ${size / 2})`}
368
+ />
369
+ <text x={size / 2} y={size / 2 + 5} textAnchor="middle" className={css.ringValue}>{v}%</text>
370
+ </svg>
371
+ {(node.label !== undefined || node.valueLabel !== undefined) && (
372
+ <div className={css.ringMeta}>
373
+ {node.label !== undefined && <span className={css.ringLabel}>{renderInline(node.label, false)}</span>}
374
+ {node.valueLabel !== undefined && <span className={css.ringSub}>{renderInline(node.valueLabel)}</span>}
375
+ </div>
376
+ )}
377
+ </div>
378
+ )
379
+ }
380
+ return (
381
+ <div
382
+ key={key}
383
+ className={css.progress}
384
+ role="progressbar"
385
+ aria-valuemin={0}
386
+ aria-valuemax={100}
387
+ aria-valuenow={v}
388
+ aria-label={node.label ?? node.valueLabel ?? undefined}
389
+ >
390
+ {(node.label !== undefined || node.valueLabel !== undefined) && (
391
+ <div className={css.progressRow}>
392
+ <span>{renderInline(node.label ?? '')}</span>
393
+ {node.valueLabel !== undefined && <span>{renderInline(node.valueLabel)}</span>}
394
+ </div>
395
+ )}
396
+ <div className={css.track}>
397
+ <div className={css.fill} style={{ width: `${v}%` }} />
398
+ {node.target !== undefined && (
399
+ <span className={css.targetMark} style={{ left: `${node.target}%` }} title={t('block.target', { value: node.target })} />
400
+ )}
401
+ </div>
402
+ </div>
403
+ )
404
+ }
405
+ case 'divider': return <hr key={key} className={css.divider} />
406
+ case 'list': {
407
+ const bound = boundField(answers, node.filter)?.toLowerCase()
408
+ const all = node.items.slice(0, GENUI_LIMITS.maxListItems)
409
+ const items = bound === undefined
410
+ ? all
411
+ : all.filter(item => listItemText(item).toLowerCase().includes(bound))
412
+ return (
413
+ <div key={key} className={css.list}>
414
+ {items.map((item, i) => (
415
+ <div key={i} className={css.li}>
416
+ {isListItemNode(item)
417
+ ? renderNode(item, i, onAction, depth + 1, answers)
418
+ : <><div className={css.liTitle}>{renderInline(typeof item === 'string' ? item : item.title)}</div>{typeof item !== 'string' && item.desc !== undefined && <div className={css.liDesc}>{renderInline(item.desc)}</div>}</>}
419
+ </div>
420
+ ))}
421
+ {bound !== undefined && <span className={css.filterHint}>{t('block.filterMatch', { shown: items.length, total: all.length })}</span>}
422
+ </div>
423
+ )
424
+ }
425
+ case 'table':
426
+ return (
427
+ <TableNode
428
+ key={key}
429
+ node={node}
430
+ // Bound controls are resolved here: the table (and the chart below)
431
+ // receive plain strings, so they stay presentational and the live
432
+ // filtering never needs a model round trip.
433
+ filterValue={boundField(answers, node.filter)}
434
+ sortValue={boundField(answers, node.sortField)}
435
+ renderDetail={items => items.map((child, i) => renderNode(child, i, onAction, depth + 1, answers))}
436
+ />
437
+ )
438
+ case 'chart': return <ChartNode key={key} chart={node} filterValue={boundField(answers, node.filter)} />
439
+ case 'tabs': return <TabsNode key={key} tabs={node} onAction={onAction} depth={depth + 1} answers={answers} />
440
+ case 'avatar': {
441
+ return (
442
+ <div key={key} className={css.avatar} style={{ background: node.color ?? avatarColor(node.name) }}>
443
+ {node.name.slice(0, 1).toUpperCase()}
444
+ </div>
445
+ )
446
+ }
447
+ case 'spacer': return <div key={key} className={css.spacer} />
448
+ case 'plot': return <PlotNode key={key} plot={node} />
449
+ case 'callout': return <CalloutNode key={key} node={node} />
450
+ case 'steps': return <StepsNode key={key} steps={node} />
451
+ case 'keyvalue': return <KeyValueNode key={key} node={node} />
452
+ case 'diff': return <DiffNode key={key} node={node} />
453
+ case 'json': return <JsonNode key={key} node={node} />
454
+ case 'code': return <CodeNode key={key} node={node} />
455
+ case 'radio': return <RadioNode key={`${key}:r${answers?.round ?? 0}`} node={node} onAction={onAction} answers={answers} />
456
+ case 'submit': return <SubmitNode key={key} node={node} onAction={onAction} answers={answers} />
457
+ case 'switch': return <SwitchNode key={key} node={node} onAction={onAction} />
458
+ case 'slider': return <SliderNode key={key} node={node} onAction={onAction} answers={answers} />
459
+ case 'textarea': return <TextareaNode key={key} node={node} onAction={onAction} answers={answers} />
460
+ case 'accordion': return <AccordionNode key={key} node={node} onAction={onAction} depth={depth + 1} answers={answers} />
461
+ case 'copy': return <CopyNode key={key} node={node} />
462
+ case 'mermaid': return <MermaidNode key={key} node={node} />
463
+ case 'svg': return <SvgNode key={key} node={node} />
464
+ case 'scene3d': return <Scene3DNode key={key} node={node} />
465
+ case 'timeline': return <TimelineNode key={key} node={node} />
466
+ case 'file-tree': return <FileTreeNode key={key} node={node} />
467
+ case 'breadcrumb': return <BreadcrumbNode key={key} node={node} />
468
+ case 'quiz': return <QuizNode key={key} node={node} onAction={onAction} />
469
+ case 'diagram': return <DiagramNode key={key} node={node} />
470
+
471
+ case 'echart': return <EChartNode key={key} node={node} />
472
+ default: {
473
+ // Plugin-registered custom types: a plugin ships a renderer through
474
+ // registerGenuiComponent; unregistered unknowns render nothing. The
475
+ // spec union is exhaustive, so an unknown node arrives as a plugin
476
+ // extension — treat it as a generic data node.
477
+ const custom = node as unknown as GenuiCustomNode
478
+ const Custom = getGenuiComponent?.(custom.type)
479
+ if (Custom !== undefined) {
480
+ return (
481
+ <Custom
482
+ key={key}
483
+ node={custom}
484
+ onAction={onAction}
485
+ renderChildren={(nodes, base) => nodes.map((c, i) => renderNode(c as GenuiNode, Number(base) + i, onAction, depth + 1, answers))}
486
+ />
487
+ )
488
+ }
489
+ return null
490
+ }
491
+ }
492
+ }
493
+
494
+ /* ---------------- v1.1 nodes ---------------- */
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Shared block-level state types: the block props contract and the answers
3
+ * registry (grouped radios / checkboxes → submit aggregation). Lives OUTSIDE
4
+ * GenuiBlock.tsx so the per-family block modules can import the types without
5
+ * a cycle back into the block shell.
6
+ * @module @changfenhuang/dsh-genui/client/blocks/state
7
+ */
8
+ import type { GenuiSpec } from '../spec.ts'
9
+ import type { BlockInteractionState } from '../interaction-store.ts'
10
+ import type { SubmissionRegistry } from '../submission-registry.ts'
11
+
12
+ export interface GenuiBlockProps {
13
+ /** Parsed spec to render. */
14
+ spec: GenuiSpec
15
+ /**
16
+ * v2: optional action callback. Interactive components carrying an
17
+ * `action` field fire it (button click, switch toggle, form submit);
18
+ * absent = components are display-only (v1 behavior).
19
+ */
20
+ onAction?: ((action: string, payload: Record<string, unknown>) => void) | undefined
21
+ /**
22
+ * v2.7: durable-state key (session + slot + content fingerprint). When set,
23
+ * interaction state (radio answers, checkbox groups, submit lock, field
24
+ * values) persists to localStorage and restores on refresh / re-render of
25
+ * the same content. Changing an existing key starts a fresh interaction
26
+ * lifetime; a streaming instance adopts its first key without losing input.
27
+ * GenuiBlock owns the matching React identity.
28
+ */
29
+ stateKey?: string | undefined
30
+ /** Animate newly arriving items; settled message replays opt out. */
31
+ animateEntrance?: boolean | undefined
32
+ /** Native hosts own durable state instead of the browser store. Read once per stateKey. */
33
+ initialState?: BlockInteractionState | undefined
34
+ onStateChange?: ((state: BlockInteractionState) => void) | undefined
35
+ /** Observe the current secret-free durable state without changing persistence ownership. */
36
+ onStateSnapshot?: ((state: BlockInteractionState) => void) | undefined
37
+ }
38
+
39
+ /** Block-wide aggregation state. Grouped radios store one selected label in
40
+ * `answers`; grouped checkboxes store a selected-label array in
41
+ * `multiAnswers`. Keeping the registries separate preserves the existing
42
+ * radio/local-grading string contract while allowing submit to expose one
43
+ * unified `answers` payload (`string | string[]`). */
44
+ export interface AnswersState {
45
+ answers: Record<string, string>
46
+ /** Grouped checkbox selections. An empty array is meaningful: the user
47
+ * explicitly cleared the group, so model-provided `checked` defaults must
48
+ * not reappear after a durable restore. */
49
+ multiAnswers: Record<string, string[]>
50
+ /** Field values by id (input/textarea with an `id`), collected by submit. */
51
+ fields: Record<string, string>
52
+ /** Field ids whose value must never be persisted or collected (secrets). */
53
+ secretFields: ReadonlySet<string>
54
+ registry: SubmissionRegistry
55
+ /** True after a local grading: questions are locked until 重新作答. */
56
+ locked: boolean
57
+ /** Bumped by every reset; radios use it as their remount key. */
58
+ round: number
59
+ setAnswer: (group: string, choice: string) => void
60
+ setMultiAnswer: (group: string, choice: string, checked: boolean) => void
61
+ setField: (id: string, value: string) => void
62
+ registerSecretField: (id: string) => void
63
+ clear: () => void
64
+ setLocked: (locked: boolean) => void
65
+ }
@@ -0,0 +1,66 @@
1
+ import { useMemo, useState } from 'react'
2
+ import type { GenuiSvg } from '../spec.ts'
3
+ import { renderInline } from '../inline.ts'
4
+ import { t } from '../i18n/index.ts'
5
+ import css from '../GenuiBlock.module.css'
6
+
7
+ const SVG_NAMESPACE = 'http://www.w3.org/2000/svg'
8
+
9
+ /** Parse `code` as an XML document; its root element when the body is a bare `<svg>`. */
10
+ function parseSvgRoot(code: string): Element | null {
11
+ const doc = new DOMParser().parseFromString(code, 'image/svg+xml')
12
+ const root = doc.documentElement
13
+ if (doc.doctype !== null || doc.querySelector('parsererror') !== null || root.localName !== 'svg') return null
14
+ return root
15
+ }
16
+
17
+ function imageSource(code: string): string | null {
18
+ try {
19
+ const root = parseSvgRoot(code)
20
+ if (root === null) return null
21
+ if (root.namespaceURI !== SVG_NAMESPACE) {
22
+ // An explicitly foreign namespace on the root stays rejected; only the
23
+ // un-namespaced HTML-style form gets healed.
24
+ if (root.namespaceURI !== null) return null
25
+ // XML parsing performs no default-namespace inference: an HTML-style
26
+ // <svg> without xmlns — the most common shape models emit, since HTML
27
+ // infers the namespace — is well-formed but un-namespaced. Declare the
28
+ // namespace in the source and re-validate the patched text instead of
29
+ // rejecting the markup outright (issue #185). A mis-landed injection
30
+ // only fails the re-parse below; it can never render different markup.
31
+ const patched = code.replace(/<svg(?=[\s/>])/, `<svg xmlns="${SVG_NAMESPACE}"`)
32
+ const reparsed = parseSvgRoot(patched)
33
+ if (reparsed === null || reparsed.namespaceURI !== SVG_NAMESPACE) return null
34
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(patched)}`
35
+ }
36
+ return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(code)}`
37
+ } catch {
38
+ return null
39
+ }
40
+ }
41
+
42
+ export function SvgNode({ node }: { node: GenuiSvg }) {
43
+ const src = useMemo(() => imageSource(node.code), [node.code])
44
+ const [failedSource, setFailedSource] = useState<string | null>(null)
45
+ return (
46
+ <div data-genui-svg>
47
+ {node.title !== undefined && <div className={css.echartTitle}>{renderInline(node.title)}</div>}
48
+ {src === null || failedSource === src ? (
49
+ <div>
50
+ <div role="status">{t('block.svgError')}</div>
51
+ <pre style={{ overflow: 'auto', maxHeight: 400 }}><code>{node.code}</code></pre>
52
+ </div>
53
+ ) : (
54
+ // SVG stays in image mode: never inject model markup into the host DOM
55
+ // or expose this URL through a link, iframe, object, or embed.
56
+ <img
57
+ key={src}
58
+ src={src}
59
+ alt={node.title ?? t('block.svgLabel')}
60
+ style={{ display: 'block', width: '100%', height: node.height ?? 'auto', maxHeight: 800, objectFit: 'contain' }}
61
+ onError={() => { setFailedSource(src) }}
62
+ />
63
+ )}
64
+ </div>
65
+ )
66
+ }