@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,537 @@
1
+ /**
2
+ * Advanced family: callout/steps/keyvalue, plot/diff/json/code, tabs and
3
+ * accordion containers (recursing through renderNode), copy, mermaid,
4
+ * scene3d, timeline, file-tree, quiz, breadcrumb.
5
+ * @module @changfenhuang/dsh-genui/client/blocks/advanced
6
+ */
7
+ import { memo, useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react'
8
+ import { CodeBlock, DiffBlock, JsonTree, writeClipboard } from '../primitive-adapter.ts'
9
+ import { renderInline } from '../inline.ts'
10
+ import css from '../GenuiBlock.module.css'
11
+ import { GENUI_LIMITS } from '../genui-runtime/index.ts'
12
+ import { PlotBlock } from '../PlotBlock.tsx'
13
+ import { renderNode } from './render-node.tsx'
14
+ import { codeBlockLabels, diffBlockLabels, jsonTreeLabels } from '../primitive-labels.ts'
15
+ import { useT } from '../i18n/index.ts'
16
+ import type { AnswersState, GenuiBlockProps } from './state.ts'
17
+ import type {
18
+ GenuiAccordion, GenuiBreadcrumb, GenuiCallout, GenuiCode, GenuiCopy, GenuiDiff, GenuiFileTree, GenuiFileTreeNode,
19
+ GenuiJson, GenuiKeyValue, GenuiMermaid, GenuiPlot, GenuiQuiz, GenuiScene3D, GenuiSteps, GenuiTabs, GenuiTimeline,
20
+ } from '../spec.ts'
21
+
22
+ const CALLOUT_TONES: Record<string, string> = {
23
+ info: css.calloutInfo!, success: css.calloutSuccess!, warning: css.calloutWarning!, error: css.calloutError!,
24
+ }
25
+
26
+ /** Callout: a tinted notice box with an optional heading. */
27
+ export const CalloutNode = memo(function CalloutNode({ node }: { node: GenuiCallout }) {
28
+ const tone = node.tone ?? 'info'
29
+ const toneClass = CALLOUT_TONES[tone] ?? css.calloutInfo
30
+ return (
31
+ <div className={`${css.callout} ${toneClass}`} data-genui-callout>
32
+ {node.title !== undefined && <div className={css.calloutTitle}>{renderInline(node.title)}</div>}
33
+ <div className={css.calloutBody}>{renderInline(node.content)}</div>
34
+ </div>
35
+ )
36
+ })
37
+
38
+ /** Steps: a vertical progress checklist with an optional current index. */
39
+ export const StepsNode = memo(function StepsNode({ steps }: { steps: GenuiSteps }) {
40
+ const list = steps.steps.slice(0, GENUI_LIMITS.maxSteps)
41
+ const current = steps.current ?? list.length
42
+ return (
43
+ <ol className={css.steps}>
44
+ {list.map((step, i) => {
45
+ const done = i < current
46
+ const active = i === current
47
+ return (
48
+ <li key={i} className={`${css.step} ${done ? css.stepDone : ''} ${active ? css.stepActive : ''}`}>
49
+ <span className={css.stepMarker}>{done ? '✓' : String(i + 1)}</span>
50
+ <span className={css.stepContent}>
51
+ <span className={css.stepTitle}>{renderInline(step.title)}</span>
52
+ {step.desc !== undefined && <span className={css.stepDesc}>{renderInline(step.desc)}</span>}
53
+ </span>
54
+ </li>
55
+ )
56
+ })}
57
+ </ol>
58
+ )
59
+ })
60
+
61
+ /** KeyValue: a definition list for configs and metadata. */
62
+ export const KeyValueNode = memo(function KeyValueNode({ node }: { node: GenuiKeyValue }) {
63
+ const pairs = node.pairs.slice(0, GENUI_LIMITS.maxKeyValuePairs)
64
+ return (
65
+ <dl className={css.keyvalue}>
66
+ {pairs.map((pair, i) => (
67
+ <div key={i} className={css.kvRow}>
68
+ <dt className={css.kvKey}>{renderInline(pair.key)}</dt>
69
+ <dd className={css.kvValue}>{renderInline(pair.value)}</dd>
70
+ </div>
71
+ ))}
72
+ </dl>
73
+ )
74
+ })
75
+
76
+ /** Plot: SVG function plot over the SafeMath evaluator. The series mapping
77
+ * is memoized on the stable spec node so the memo boundary actually skips
78
+ * sibling-state re-renders (a fresh mapped array would defeat it). */
79
+ export const PlotNode = memo(function PlotNode({ plot }: { plot: GenuiPlot }) {
80
+ const series = useMemo(
81
+ () => plot.series.slice(0, GENUI_LIMITS.maxPlotSeries)
82
+ .map(s => ({ expr: s.expr, label: s.label, color: s.color, kind: s.kind, params: s.params })),
83
+ [plot],
84
+ )
85
+ return (
86
+ <PlotBlock
87
+ series={series}
88
+ xMin={plot.xMin} xMax={plot.xMax} yMin={plot.yMin} yMax={plot.yMax} title={plot.title}
89
+ />
90
+ )
91
+ })
92
+
93
+ /** Diff: 收编 dsh DiffBlock (same path/oldText/newText shape as DiffHunk). */
94
+ export const DiffNode = memo(function DiffNode({ node }: { node: GenuiDiff }) {
95
+ useT()
96
+ return <DiffBlock diffs={node.diffs} labels={diffBlockLabels()} />
97
+ })
98
+
99
+ /** Json: 收编 dsh JsonTree. */
100
+ export const JsonNode = memo(function JsonNode({ node }: { node: GenuiJson }) {
101
+ useT()
102
+ const data = node.value
103
+ if (typeof data !== 'object' || data === null) {
104
+ return <div className={css.jsonScalar}>{String(data)}</div>
105
+ }
106
+ return <JsonTree data={data as object | unknown[]} label="JSON" labels={jsonTreeLabels()} copyable />
107
+ })
108
+
109
+ /** Code: 收编 dsh CodeBlock with explicit language. */
110
+ export const CodeNode = memo(function CodeNode({ node }: { node: GenuiCode }) {
111
+ useT()
112
+ return <CodeBlock {...codeBlockLabels()} code={node.code.slice(0, GENUI_LIMITS.maxCode)} lang={node.lang} />
113
+ })
114
+
115
+ /**
116
+ * Table: LOCAL sorting (v2.9) — click a header to sort ascending, click
117
+ * again for descending, a third click restores the spec order. Zero model
118
+ * round trip. Numeric cells (numbers or numeric strings) compare numerically;
119
+ * everything else compares as text.
120
+ */
121
+ export function TabsNode({ tabs, onAction, depth = 0, answers }: {
122
+ tabs: GenuiTabs
123
+ onAction?: GenuiBlockProps['onAction']
124
+ depth?: number
125
+ answers?: AnswersState | undefined
126
+ }) {
127
+ const [active, setActive] = useState(0)
128
+ const uid = useId()
129
+ const list = tabs.tabs.slice(0, GENUI_LIMITS.maxTabs)
130
+ const safeActive = list.length === 0 ? 0 : Math.min(active, list.length - 1)
131
+ const current = list[safeActive]
132
+ useEffect(() => {
133
+ if (safeActive !== active) setActive(safeActive)
134
+ }, [active, safeActive])
135
+ const move = (next: number): void => {
136
+ if (list.length === 0) return
137
+ const n = (next + list.length) % list.length
138
+ setActive(n)
139
+ document.getElementById(`${uid}-tab-${n}`)?.focus()
140
+ }
141
+ return (
142
+ <div className={css.tabs}>
143
+ <div
144
+ className={css.tabBar}
145
+ role="tablist"
146
+ aria-orientation="horizontal"
147
+ onKeyDown={e => {
148
+ if (e.key === 'ArrowRight') { e.preventDefault(); move(safeActive + 1) }
149
+ else if (e.key === 'ArrowLeft') { e.preventDefault(); move(safeActive - 1) }
150
+ else if (e.key === 'Home') { e.preventDefault(); move(0) }
151
+ else if (e.key === 'End') { e.preventDefault(); move(list.length - 1) }
152
+ }}
153
+ >
154
+ {list.map((tab, i) => (
155
+ <button
156
+ key={i}
157
+ id={`${uid}-tab-${i}`}
158
+ type="button"
159
+ role="tab"
160
+ aria-selected={i === safeActive}
161
+ aria-controls={`${uid}-panel-${i}`}
162
+ tabIndex={i === safeActive ? 0 : -1}
163
+ className={`${css.tab} ${i === safeActive ? css.tabActive : ''}`}
164
+ onClick={() => setActive(i)}
165
+ >
166
+ {renderInline(tab.label, false)}
167
+ </button>
168
+ ))}
169
+ </div>
170
+ {current !== undefined && (
171
+ <div className={css.col} role="tabpanel" id={`${uid}-panel-${safeActive}`} aria-labelledby={`${uid}-tab-${safeActive}`}>
172
+ {current.items.map((c, i) => renderNode(c, i, onAction, depth + 1, answers))}
173
+ </div>
174
+ )}
175
+ </div>
176
+ )
177
+ }
178
+
179
+ /** Radio: one option from a group; local selection state. The group name is
180
+ * useId-based so sibling groups never collide (deterministic per mount).
181
+ *
182
+ * v2.5 aggregation: when `group` is set, the selection is recorded into the
183
+ * block-wide answers registry instead of firing a per-click action — a
184
+ * sibling `submit` node then grades the paper IN PLACE (v2.6, questions
185
+ * carry `answer` data) or collects all groups in ONE action. Without
186
+ * `group`, the legacy per-click action fires. After a local grading the
187
+ * group locks until 重新作答 resets it. */
188
+ export function AccordionNode({ node, onAction, depth = 0, answers }: {
189
+ node: GenuiAccordion
190
+ onAction?: GenuiBlockProps['onAction']
191
+ depth?: number
192
+ answers?: AnswersState | undefined
193
+ }) {
194
+ const [open, setOpen] = useState<number | null>(0)
195
+ const uid = useId()
196
+ const items = node.items.slice(0, GENUI_LIMITS.maxAccordionItems)
197
+ return (
198
+ <div className={css.accordion}>
199
+ {items.map((item, i) => (
200
+ <div key={i} className={css.accItem}>
201
+ <button
202
+ type="button"
203
+ className={css.accHead}
204
+ id={`${uid}-head-${i}`}
205
+ aria-expanded={open === i}
206
+ aria-controls={`${uid}-body-${i}`}
207
+ onClick={() => setOpen(open === i ? null : i)}
208
+ >
209
+ <span className={css.accTitle}>{renderInline(item.title, false)}</span>
210
+ <span className={css.accChevron} data-open={open === i} aria-hidden>▸</span>
211
+ </button>
212
+ {open === i && (
213
+ <div className={css.accBody} id={`${uid}-body-${i}`} aria-labelledby={`${uid}-head-${i}`}>
214
+ {item.items.map((c, ci) => renderNode(c, ci, onAction, depth + 1, answers))}
215
+ </div>
216
+ )}
217
+ </div>
218
+ ))}
219
+ </div>
220
+ )
221
+ }
222
+
223
+ async function writeCopyText(text: string): Promise<boolean> {
224
+ /* oxlint-disable-next-line typescript/no-unnecessary-condition */
225
+ const hasAsyncClipboard = typeof navigator.clipboard?.writeText === 'function'
226
+ const accepted = await writeClipboard(text)
227
+ if (accepted || !hasAsyncClipboard) return accepted
228
+
229
+ // ponytail: remove this retry once the host helper falls back after Clipboard API rejection.
230
+ /* oxlint-disable typescript/no-deprecated */
231
+ const exec = typeof document.execCommand === 'function'
232
+ ? document.execCommand.bind(document)
233
+ : undefined
234
+ if (exec === undefined) return false
235
+ const el = document.createElement('textarea')
236
+ el.value = text
237
+ el.setAttribute('readonly', '')
238
+ el.style.position = 'fixed'
239
+ el.style.left = '-9999px'
240
+ document.body.appendChild(el)
241
+ el.select()
242
+ try {
243
+ return exec('copy')
244
+ } catch {
245
+ return false
246
+ } finally {
247
+ el.remove()
248
+ }
249
+ /* oxlint-enable typescript/no-deprecated */
250
+ }
251
+
252
+ /** Copy: a one-click copy chip. The live region is a visually-hidden SIBLING
253
+ * (not inside the button) — button content is atomic to screen readers, so a
254
+ * live region inside it would never announce. */
255
+ export const CopyNode = memo(function CopyNode({ node }: { node: GenuiCopy }) {
256
+ const t = useT()
257
+ const [copied, setCopied] = useState(false)
258
+ return (
259
+ <>
260
+ <button
261
+ type="button"
262
+ className={`${css.copyChip} ${copied ? css.copyChipDone : ''}`}
263
+ onClick={() => {
264
+ void writeCopyText(node.text).then((ok) => {
265
+ if (ok) {
266
+ setCopied(true)
267
+ setTimeout(() => setCopied(false), 1500)
268
+ }
269
+ })
270
+ }}
271
+ >
272
+ {copied ? t('label.copiedShort') : renderInline(node.label ?? t('label.copy'), false)}
273
+ </button>
274
+ <span className={css.visuallyHidden} role="status">{copied ? t('label.copiedToClipboard') : ''}</span>
275
+ </>
276
+ )
277
+ })
278
+
279
+ type MermaidRenderState =
280
+ | { status: 'loading' }
281
+ | { status: 'ready'; html: string }
282
+ | { status: 'error' }
283
+
284
+ /** Mermaid: lazily loaded diagram renderer. */
285
+ export const MermaidNode = memo(function MermaidNode({ node }: { node: GenuiMermaid }) {
286
+ const t = useT()
287
+ const [state, setState] = useState<MermaidRenderState>({ status: 'loading' })
288
+ const code = node.code.slice(0, GENUI_LIMITS.maxMermaid)
289
+ useEffect(() => {
290
+ let alive = true
291
+ setState({ status: 'loading' })
292
+ void (async () => {
293
+ try {
294
+ const m = await import('../mermaid-lazy.ts')
295
+ const svg = await m.renderMermaid(code)
296
+ if (alive) setState({ status: 'ready', html: svg })
297
+ } catch {
298
+ if (alive) setState({ status: 'error' })
299
+ }
300
+ })()
301
+ return () => { alive = false }
302
+ }, [code])
303
+ if (state.status === 'error') return <div className={css.mermaidFallback}><pre>{code}</pre><div className={css.mermaidErr}>{t('block.mermaidError')}</div></div>
304
+ if (state.status === 'loading') return <div className={css.mermaidFallback}><pre>{code}</pre><div className={css.mermaidHint}>{t('block.mermaidLoading')}</div></div>
305
+ return <div className={css.mermaid} dangerouslySetInnerHTML={{ __html: state.html }} data-genui-mermaid />
306
+ })
307
+
308
+ /** Scene3D: three.js WebGL canvas, lazily imported. */
309
+ export const Scene3DNode = memo(function Scene3DNode({ node }: { node: GenuiScene3D }) {
310
+ const t = useT()
311
+ const [status, setStatus] = useState<'loading' | 'ready' | 'error'>('loading')
312
+ const ref = useRef<HTMLDivElement | null>(null)
313
+ // Mesh cap mirrored from the guard: a pathological scene never reaches
314
+ // three.js (per-frame cost scales with mesh count).
315
+ const scene = node.meshes.length > GENUI_LIMITS.maxMeshes ? { ...node, meshes: node.meshes.slice(0, GENUI_LIMITS.maxMeshes) } : node
316
+ useEffect(() => {
317
+ let alive = true
318
+ let dispose: (() => void) | undefined
319
+ void import('../scene3d-lazy.ts').then(async m => {
320
+ if (!alive || ref.current === null) return
321
+ try {
322
+ dispose = await m.mountScene(ref.current, scene)
323
+ if (alive) setStatus('ready')
324
+ } catch {
325
+ if (alive) setStatus('error')
326
+ }
327
+ })
328
+ return () => { alive = false; dispose?.() }
329
+ }, [scene])
330
+ return (
331
+ <div className={css.scene3dWrap} data-genui-scene3d>
332
+ {node.title !== undefined && <div className={css.scene3dTitle}>{renderInline(node.title)}</div>}
333
+ <div ref={ref} className={css.scene3dCanvas} />
334
+ {status === 'loading' && <div className={css.scene3dHint}>{t('block.scene3dLoading')}</div>}
335
+ {status === 'error' && <div className={css.scene3dHint}>{t('block.scene3dError')}</div>}
336
+ </div>
337
+ )
338
+ })
339
+
340
+ /** Timeline: vertical event list with time markers. */
341
+ export const TimelineNode = memo(function TimelineNode({ node }: { node: GenuiTimeline }) {
342
+ const items = node.items.slice(0, GENUI_LIMITS.maxTimelineItems)
343
+ return (
344
+ <div className={css.timeline}>
345
+ {items.map((item, i) => (
346
+ <div key={i} className={css.tlItem}>
347
+ <div className={css.tlRail}>
348
+ <span className={css.tlDot} />
349
+ {i < items.length - 1 && <span className={css.tlLine} />}
350
+ </div>
351
+ <div className={css.tlBody}>
352
+ <div className={css.tlHead}>
353
+ <span className={css.tlTitle}>{renderInline(item.title, false)}</span>
354
+ {item.time !== undefined && <span className={css.tlTime}>{renderInline(item.time)}</span>}
355
+ </div>
356
+ {item.desc !== undefined && <div className={css.tlDesc}>{renderInline(item.desc)}</div>}
357
+ </div>
358
+ </div>
359
+ ))}
360
+ </div>
361
+ )
362
+ })
363
+
364
+ /** FileTree: indented tree of files and folders. Directory rows are LOCAL
365
+ * collapsible (spec.ts promised "collapsible children"; this makes it true)
366
+ * — click a dir to fold/unfold, default fully open. Zero model round trip. */
367
+ /** 14px folder / file glyphs: an emoji-free way to tell rows apart at a glance. */
368
+ function FolderGlyph() {
369
+ return (
370
+ <svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true" focusable="false">
371
+ <path d="M1.6 3.4h4.1l1.3 1.7h7.4v7.2a1 1 0 0 1-1 1H2.6a1 1 0 0 1-1-1z" fill="currentColor" opacity="0.85" />
372
+ </svg>
373
+ )
374
+ }
375
+
376
+ function FileGlyph() {
377
+ return (
378
+ <svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true" focusable="false">
379
+ <path d="M3.8 1.6h4.9L13 5.9v8.5a1 1 0 0 1-1 1H4.8a1 1 0 0 1-1-1z" fill="none" stroke="currentColor" strokeWidth="1.2" />
380
+ <path d="M8.7 1.7v4.3h4.2" fill="none" stroke="currentColor" strokeWidth="1.2" />
381
+ </svg>
382
+ )
383
+ }
384
+
385
+ export const FileTreeNode = memo(function FileTreeNode({ node }: { node: GenuiFileTree }) {
386
+ const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set())
387
+ const toggle = (k: string): void => {
388
+ setCollapsed(prev => {
389
+ const next = new Set(prev)
390
+ if (next.has(k)) next.delete(k)
391
+ else next.add(k)
392
+ return next
393
+ })
394
+ }
395
+ // Children live in their OWN container under the row. They used to be
396
+ // appended inside `.ftRow` (display: flex), so a nested tree rendered
397
+ // side-by-side on one line instead of stacking.
398
+ const renderNode = (n: GenuiFileTreeNode, depth: number, path: string): ReactNode => {
399
+ if (depth > GENUI_LIMITS.maxTreeDepth) return null
400
+ const isDir = n.type === 'dir' || (n.children !== undefined && n.children.length > 0)
401
+ const folded = isDir && collapsed.has(path)
402
+ return (
403
+ <div key={path}>
404
+ <div className={css.ftRow} style={{ paddingLeft: `${depth * 14 + 4}px` }}>
405
+ {Array.from({ length: depth }, (_v, i) => (
406
+ <span key={i} className={css.ftGuide} style={{ left: `${4 + i * 14 + 6}px` }} aria-hidden />
407
+ ))}
408
+ <button
409
+ type="button"
410
+ className={css.ftNameBtn}
411
+ aria-expanded={isDir ? !folded : undefined}
412
+ onClick={isDir ? () => toggle(path) : undefined}
413
+ >
414
+ <span
415
+ className={css.ftChevron}
416
+ data-open={isDir ? String(!folded) : undefined}
417
+ aria-hidden
418
+ >
419
+ {isDir ? '▸' : ''}
420
+ </span>
421
+ <span className={`${css.ftGlyph} ${isDir ? css.ftGlyphDir : ''}`} aria-hidden>
422
+ {isDir ? <FolderGlyph /> : <FileGlyph />}
423
+ </span>
424
+ <span className={`${css.ftName} ${isDir ? css.ftDir : ''}`}>{n.name}</span>
425
+ </button>
426
+ </div>
427
+ {isDir && !folded && (
428
+ <div className={css.ftChildren}>
429
+ {(n.children ?? []).map((c, ci) => renderNode(c, depth + 1, `${path}/${ci}`))}
430
+ </div>
431
+ )}
432
+ </div>
433
+ )
434
+ }
435
+ return <div className={css.fileTree}>{node.items.slice(0, GENUI_LIMITS.maxListItems).map((n, i) => renderNode(n, 0, String(i)))}</div>
436
+ })
437
+
438
+ /** Quiz: a self-contained teaching question. Selecting an option marks it
439
+ * correct/incorrect in place and reveals feedback + explanation. With
440
+ * `action`, the chosen answer is ALSO sent back to the model
441
+ * (`{type:'quiz', question, answer, correct}`) so the model can collect or
442
+ * grade it — the in-place judging stays local (no round trip needed). */
443
+ export const QuizNode = memo(function QuizNode({ node, onAction }: {
444
+ node: GenuiQuiz
445
+ onAction?: GenuiBlockProps['onAction']
446
+ }) {
447
+ const t = useT()
448
+ const [selected, setSelected] = useState<number | null>(null)
449
+ // `id` is the documented reset signal: when the model swaps the quiz in
450
+ // place (same tree position, new question), the component instance is
451
+ // reused, so the answered state must not leak onto the new question.
452
+ const [prevId, setPrevId] = useState(node.id)
453
+ if (node.id !== prevId) {
454
+ setPrevId(node.id)
455
+ setSelected(null)
456
+ }
457
+ const options = node.options.slice(0, GENUI_LIMITS.maxQuizOptions)
458
+ const answered = selected !== null
459
+ const chosen = selected === null ? undefined : options[selected]
460
+ const correct = chosen?.correct === true
461
+ const action = node.action
462
+ return (
463
+ <div className={css.quiz} data-genui-quiz>
464
+ <div className={css.quizQuestion}>{renderInline(node.question)}</div>
465
+ <div className={css.quizOptions}>
466
+ {options.map((opt, i) => {
467
+ const isChosen = selected === i
468
+ const cls = answered
469
+ ? isChosen
470
+ ? opt.correct === true ? css.quizOptCorrect : css.quizOptWrong
471
+ : opt.correct === true ? css.quizOptReveal : css.quizOpt
472
+ : css.quizOpt
473
+ return (
474
+ <button
475
+ key={i}
476
+ type="button"
477
+ className={cls}
478
+ disabled={answered}
479
+ onClick={() => {
480
+ setSelected(i)
481
+ if (action !== undefined && onAction !== undefined) {
482
+ onAction(action, {
483
+ type: 'quiz',
484
+ question: node.question,
485
+ answer: opt.label,
486
+ correct: opt.correct === true,
487
+ })
488
+ }
489
+ }}
490
+ >
491
+ {/* Before answering: a radio affordance so the row reads as a
492
+ choice. After: ✓ on the right answer, ✗ on a wrong pick. */}
493
+ <span className={css.quizMarker}>
494
+ {answered ? (opt.correct === true ? '✓' : isChosen ? '✗' : '') : isChosen ? '●' : '○'}
495
+ </span>
496
+ {renderInline(opt.label, false)}
497
+ </button>
498
+ )
499
+ })}
500
+ </div>
501
+ {answered && (
502
+ <div className={css.quizResult} aria-live="polite">
503
+ <div className={correct ? css.quizCorrectMsg : css.quizWrongMsg}>
504
+ {correct ? t('block.quizCorrect') : t('block.quizWrong')}
505
+ {chosen?.feedback !== undefined && <div className={css.quizFeedback}>{renderInline(chosen.feedback)}</div>}
506
+ </div>
507
+ {node.explanation !== undefined && <div className={css.quizExplanation}>{renderInline(node.explanation)}</div>}
508
+ <button type="button" className={css.quizRetry} onClick={() => setSelected(null)}>{t('block.quizRetry')}</button>
509
+ </div>
510
+ )}
511
+ </div>
512
+ )
513
+ })
514
+
515
+ /** Breadcrumb: path-style navigation trail. */
516
+ export const BreadcrumbNode = memo(function BreadcrumbNode({ node }: { node: GenuiBreadcrumb }) {
517
+ const items = node.items.slice(0, GENUI_LIMITS.maxBreadcrumbItems)
518
+ return (
519
+ <nav className={css.breadcrumb} aria-label="breadcrumb">
520
+ {items.map((item, i) => (
521
+ <span key={i} className={css.bcItem}>
522
+ <span className={`${css.bcText} ${i === items.length - 1 ? css.bcCurrent : ''}`}>{renderInline(item)}</span>
523
+ {i < items.length - 1 && <span className={css.bcSep}>/</span>}
524
+ </span>
525
+ ))}
526
+ </nav>
527
+ )
528
+ })
529
+
530
+ /**
531
+ * Trailing debounce window (ms) for one `[genui-action]` name: rapid
532
+ * repeated interactions on one control (button mashing, switch flipping)
533
+ * collapse into a single action with the LAST payload. Different action
534
+ * names stay independent. The model round-trip takes seconds, so a few
535
+ * hundred ms of trailing delay is imperceptible — and it stops bursts of
536
+ * queued user turns.
537
+ */
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Basic display family: avatar palette, and the local click-feedback button
3
+ * (the actionable-button chip). Used by the render dispatcher.
4
+ * @module @changfenhuang/dsh-genui/client/blocks/basic
5
+ */
6
+ import { renderInline } from '../inline.ts'
7
+ import { memo, useEffect, useRef, useState, type ReactNode } from 'react'
8
+ import css from '../GenuiBlock.module.css'
9
+ import { useT } from '../i18n/index.ts'
10
+ import type { GenuiAudio, GenuiVideo } from '../spec.ts'
11
+
12
+ /** Deterministic avatar color by name hash. Host static tokens ONLY —
13
+ * design system v2: no off-brand hexes, the palette always matches the
14
+ * theme's families (deepseek/blue/green/amber/red/neutral). */
15
+ const AVATAR_COLORS = [
16
+ 'var(--dsw-static-deepseek-400)',
17
+ 'var(--dsw-static-deepseek-450)',
18
+ 'var(--dsw-static-blue-450)',
19
+ 'var(--dsw-static-green-400)',
20
+ 'var(--dsw-static-amber-400)',
21
+ 'var(--dsw-static-red-400)',
22
+ 'var(--dsw-static-deepseek-300)',
23
+ 'var(--dsw-static-neutral-bluish-400)',
24
+ ]
25
+
26
+ export function avatarColor(name: string): string {
27
+ let h = 0
28
+ for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0
29
+ // The array is a literal with 8 entries; the index is always in range.
30
+ return AVATAR_COLORS[h % AVATAR_COLORS.length]!
31
+ }
32
+
33
+ /** Button with LOCAL click feedback: clicking an actionable button shows a
34
+ * brief "✓ 已触发" chip so the user sees the click registered even while the
35
+ * model round trip is in flight — no more "点了没反应" perception. The chip
36
+ * is purely cosmetic; the action fires through `onClick` as before. */
37
+ export function ClickFeedbackButton({ className, disabled, onClick, children }: {
38
+ className: string
39
+ disabled?: boolean
40
+ onClick?: (() => void) | undefined
41
+ children: ReactNode
42
+ }) {
43
+ const t = useT()
44
+ const [sent, setSent] = useState(false)
45
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
46
+ useEffect(() => {
47
+ return () => {
48
+ if (timer.current !== null) clearTimeout(timer.current)
49
+ }
50
+ }, [])
51
+ return (
52
+ <>
53
+ <button
54
+ type="button"
55
+ className={className}
56
+ disabled={disabled}
57
+ onClick={onClick === undefined ? undefined : () => {
58
+ onClick()
59
+ if (timer.current !== null) clearTimeout(timer.current)
60
+ setSent(true)
61
+ timer.current = setTimeout(() => setSent(false), 1400)
62
+ }}
63
+ >
64
+ {children}
65
+ {sent && <span className={css.btnSent} aria-hidden>{t('block.triggered')}</span>}
66
+ </button>
67
+ {/* Live-region sibling: button content is atomic to screen readers, so
68
+ * the confirmation announces from a hidden status region. */}
69
+ <span className={css.visuallyHidden} role="status">{sent ? t('block.triggeredPlain') : ''}</span>
70
+ </>
71
+ )
72
+ }
73
+
74
+ /** Native controls intentionally own play/pause/seek/volume. Model-authored
75
+ * autoplay and controls hints are ignored: media starts only after the user
76
+ * asks for it. */
77
+ export const AudioNode = memo(function AudioNode({ node }: { node: GenuiAudio }): ReactNode {
78
+ const t = useT()
79
+ const [failed, setFailed] = useState(false)
80
+ return (
81
+ <figure className={css.media}>
82
+ {node.alt !== undefined && <figcaption className={css.mediaLabel}>{renderInline(node.alt)}</figcaption>}
83
+ {failed
84
+ ? <div className={css.mediaError} role="alert">{t('block.audioError')}</div>
85
+ : <audio
86
+ className={css.mediaPlayer}
87
+ src={node.src}
88
+ aria-label={node.alt ?? t('block.audio')}
89
+ controls
90
+ preload="metadata"
91
+ loop={node.loop === true}
92
+ onError={() => setFailed(true)}
93
+ />}
94
+ </figure>
95
+ )
96
+ })
97
+
98
+ export const VideoNode = memo(function VideoNode({ node }: { node: GenuiVideo }): ReactNode {
99
+ const t = useT()
100
+ const [failed, setFailed] = useState(false)
101
+ return (
102
+ <figure className={css.media}>
103
+ {node.alt !== undefined && <figcaption className={css.mediaLabel}>{renderInline(node.alt)}</figcaption>}
104
+ {failed
105
+ ? <div className={css.mediaError} role="alert">{t('block.videoError')}</div>
106
+ : <video
107
+ className={`${css.mediaPlayer} ${css.videoPlayer}`}
108
+ src={node.src}
109
+ poster={node.poster}
110
+ aria-label={node.alt ?? t('block.video')}
111
+ controls
112
+ preload="metadata"
113
+ playsInline
114
+ loop={node.loop === true}
115
+ muted={node.muted === true}
116
+ style={node.aspectRatio === undefined ? undefined : { aspectRatio: node.aspectRatio.replace(':', ' / ') }}
117
+ onError={() => setFailed(true)}
118
+ />}
119
+ </figure>
120
+ )
121
+ })