@sparkelf/dsh-genui 0.0.0-stage → 0.11.4-patch.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,9 @@
1
+ type StandaloneAssets = { __GenuiAssets__?: Record<string, unknown> }
2
+
3
+ /** 从启动代码预先载入的全局资源读取引擎。 */
4
+ export function loadGenuiAsset<T>(name: 'mermaid' | 'three' | 'echarts-core' | 'echarts-full'): Promise<T> {
5
+ const key = name.replace(/-(\w)/g, (_match, character: string) => character.toUpperCase())
6
+ const asset = (window as unknown as StandaloneAssets).__GenuiAssets__?.[key]
7
+ if (asset === undefined) return Promise.reject(new Error(`standalone asset '${name}' was not preloaded`))
8
+ return Promise.resolve(asset as T)
9
+ }
@@ -0,0 +1,11 @@
1
+ import type { GenuiArtifactV1 } from '../artifact/types.ts'
2
+
3
+ declare global {
4
+ interface Window {
5
+ __GenuiStandalone__?: {
6
+ mount(root: HTMLElement, artifact: GenuiArtifactV1): () => void
7
+ }
8
+ }
9
+ }
10
+
11
+ export {}
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,94 @@
1
+ import { createContext, useState, type CSSProperties, type ReactNode } from 'react'
2
+ import { t } from '../i18n/index.ts'
3
+
4
+ export interface DiffBlockLabels {
5
+ copy: string
6
+ copied: string
7
+ codeLabel: string
8
+ wrapLabel: string
9
+ unwrapLabel: string
10
+ collapseAria: string
11
+ expandAria: (hidden: number) => string
12
+ collapse: string
13
+ expand: (hidden: number) => string
14
+ files: (count: number) => string
15
+ }
16
+
17
+ export interface JsonTreeLabels {
18
+ copyValue: string
19
+ copyJson: string
20
+ copyPath: string
21
+ copyPrettyJson: string
22
+ copyCompactJson: string
23
+ copied: string
24
+ copyFailed: string
25
+ collapseNode: string
26
+ expandNode: string
27
+ copyButtonTitle: (action: string) => string
28
+ }
29
+
30
+ const codeStyle: CSSProperties = { overflow: 'auto', padding: 12, borderRadius: 8, background: 'var(--dsw-alias-bg-layer-2)', fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 12, lineHeight: 1.5, whiteSpace: 'pre-wrap' }
31
+
32
+ /** 在独立页面显示可复制的代码内容。 */
33
+ export function CodeBlock({ code, lang, copyLabel, copiedLabel }: { code: string; lang?: string; copyLabel?: string; copiedLabel?: string }): ReactNode {
34
+ const [copied, setCopied] = useState(false)
35
+ const copy = async (): Promise<void> => {
36
+ if (!await writeClipboard(code)) return
37
+ setCopied(true)
38
+ window.setTimeout(() => setCopied(false), 1200)
39
+ }
40
+ return <div><div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: 'var(--dsw-alias-label-secondary)' }}><span>{lang ?? t('label.code')}</span><button type="button" onClick={() => void copy()}>{copied ? copiedLabel ?? t('label.copied') : copyLabel ?? t('label.copy')}</button></div><pre style={codeStyle}><code>{code}</code></pre></div>
41
+ }
42
+
43
+ /** 在独立页面以差异文本显示文件变更。 */
44
+ export function DiffBlock({ diffs }: { diffs: Array<{ path: string; oldText?: string; newText?: string }>; labels?: DiffBlockLabels }): ReactNode {
45
+ return <div>{diffs.map((diff, index) => <section key={`${diff.path}:${index}`}><strong>{diff.path}</strong><pre style={codeStyle}>{(diff.oldText ?? '').split('\n').map(line => `- ${line}`).concat((diff.newText ?? '').split('\n').map(line => `+ ${line}`)).join('\n')}</pre></section>)}</div>
46
+ }
47
+
48
+ /** 在独立页面显示 JSON,并提供本地折叠控制。 */
49
+ export function JsonTree({ data, label, copyable, labels }: { data: object | unknown[]; label?: string; copyable?: boolean; labels?: JsonTreeLabels }): ReactNode {
50
+ const [expanded, setExpanded] = useState(true)
51
+ const [copied, setCopied] = useState(false)
52
+ const json = JSON.stringify(data, null, 2)
53
+ /** 复制当前 JSON 内容并更新按钮反馈。 */
54
+ const copy = async (): Promise<void> => {
55
+ if (!await writeClipboard(json)) return
56
+ setCopied(true)
57
+ window.setTimeout(() => setCopied(false), 1200)
58
+ }
59
+ return <section><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><button type="button" aria-expanded={expanded} onClick={() => setExpanded(value => !value)}>{expanded ? t('label.collapse') : t('label.expandNode')} {label ?? 'JSON'}</button>{copyable && <button type="button" onClick={() => void copy()}>{copied ? labels?.copied ?? t('label.copied') : labels?.copyJson ?? t('label.copy')}</button>}</div>{expanded && <pre style={codeStyle}>{json}</pre>}</section>
60
+ }
61
+
62
+ /** 将文本复制到系统剪贴板。 */
63
+ export async function writeClipboard(text: string): Promise<boolean> {
64
+ if (typeof navigator.clipboard?.writeText === 'function') {
65
+ try {
66
+ await navigator.clipboard.writeText(text)
67
+ return true
68
+ } catch {
69
+ return false
70
+ }
71
+ }
72
+ const textarea = document.createElement('textarea')
73
+ textarea.value = text
74
+ textarea.setAttribute('readonly', '')
75
+ textarea.style.position = 'fixed'
76
+ textarea.style.left = '-9999px'
77
+ document.body.appendChild(textarea)
78
+ try {
79
+ textarea.select()
80
+ return document.execCommand('copy')
81
+ } catch {
82
+ return false
83
+ } finally {
84
+ textarea.remove()
85
+ }
86
+ }
87
+
88
+ /** standalone 模式不连接 DSH 注册表,因此自定义组件始终不可用。 */
89
+ export function getGenuiComponent(_type: string): undefined {
90
+ return undefined
91
+ }
92
+
93
+ /** standalone 模式专用的空动作上下文。 */
94
+ export const GenuiActionContext = createContext<((action: string, payload: Record<string, unknown>) => void) | undefined>(undefined)
@@ -0,0 +1,27 @@
1
+ import { createRoot } from 'react-dom/client'
2
+ import { GenuiBlock } from '../GenuiBlock.tsx'
3
+ import { GenuiActionContext } from '../action-context.ts'
4
+ import { ErrorBoundary } from '../ErrorBoundary.tsx'
5
+ import { parseGenuiArtifact } from '../artifact/parse.ts'
6
+ import { setLocale } from '../i18n/runtime.ts'
7
+ import './katex-style.ts'
8
+ import './bootstrap-types.ts'
9
+
10
+ /** 挂载独立 artifact,并返回卸载该界面的函数。 */
11
+ function mount(root: HTMLElement, rawArtifact: unknown): () => void {
12
+ const artifact = parseGenuiArtifact(rawArtifact)
13
+ if (artifact === null) throw new Error('invalid GenUI artifact')
14
+ setLocale(artifact.presentation.locale)
15
+ document.body.toggleAttribute('data-ds-dark-theme', artifact.presentation.theme === 'dark')
16
+ const reactRoot = createRoot(root)
17
+ reactRoot.render(
18
+ <GenuiActionContext.Provider value={undefined}>
19
+ <ErrorBoundary label="GenUI">
20
+ <GenuiBlock spec={artifact.spec} initialState={artifact.state} animateEntrance={false} />
21
+ </ErrorBoundary>
22
+ </GenuiActionContext.Provider>,
23
+ )
24
+ return () => reactRoot.unmount()
25
+ }
26
+
27
+ window.__GenuiStandalone__ = { mount }
@@ -0,0 +1,150 @@
1
+ import { GENUI_LIMITS } from './genui-runtime/index.ts'
2
+ import type { GenuiSpec } from './spec.ts'
3
+ import { walkGenuiNodes } from './walk-spec.ts'
4
+
5
+ export type SubmissionMember = RadioSubmissionMember | CheckboxSubmissionMember | FieldSubmissionMember
6
+
7
+ export interface RadioSubmissionMember {
8
+ kind: 'radio'
9
+ key: string
10
+ label: string
11
+ options: string[]
12
+ answer?: number | string
13
+ explanation?: string
14
+ }
15
+
16
+ export interface CheckboxSubmissionMember {
17
+ kind: 'checkbox'
18
+ key: string
19
+ }
20
+
21
+ export interface FieldSubmissionMember {
22
+ kind: 'field'
23
+ key: string
24
+ fieldType: 'input' | 'textarea' | 'select' | 'slider'
25
+ secret: boolean
26
+ }
27
+
28
+ export interface SubmissionRegistry {
29
+ members: ReadonlyMap<string, SubmissionMember>
30
+ }
31
+
32
+ export interface SubmitInteractionState {
33
+ answers: Record<string, string>
34
+ multiAnswers: Record<string, string[]>
35
+ fields: Record<string, string>
36
+ secretFields: ReadonlySet<string>
37
+ }
38
+
39
+ export interface ResolvedSubmitState {
40
+ scope: SubmissionMember[]
41
+ answered: number
42
+ total: number
43
+ localGradeEligible: boolean
44
+ hasOutOfScopePayload: boolean
45
+ }
46
+
47
+ /** 从 spec 建立成员表,并诊断 submission key 和 submit.groups。 */
48
+ export function analyzeSubmissionRegistry(spec: GenuiSpec): { registry: SubmissionRegistry; diagnostics: string[] } {
49
+ const members = new Map<string, SubmissionMember>()
50
+ const paths = new Map<string, string>()
51
+ const diagnostics: string[] = []
52
+ const submits: Array<{ groups: string[]; path: string }> = []
53
+
54
+ walkGenuiNodes(spec, (node, path) => {
55
+ if (node.type === 'submit') {
56
+ if (node.groups !== undefined) submits.push({ groups: node.groups, path })
57
+ return
58
+ }
59
+ let member: SubmissionMember | undefined
60
+ let keyPath: string
61
+ switch (node.type) {
62
+ case 'radio':
63
+ if (node.group === undefined) return
64
+ member = { kind: 'radio', key: node.group, label: node.label ?? node.group, options: node.options.slice(0, GENUI_LIMITS.maxOptions), ...(node.answer === undefined ? {} : { answer: node.answer }), ...(node.explanation === undefined ? {} : { explanation: node.explanation }) }
65
+ keyPath = `${path}.group`
66
+ break
67
+ case 'checkbox':
68
+ if (node.group === undefined) return
69
+ member = { kind: 'checkbox', key: node.group }
70
+ keyPath = `${path}.group`
71
+ break
72
+ case 'input':
73
+ case 'textarea':
74
+ case 'select':
75
+ case 'slider':
76
+ if (node.id === undefined) return
77
+ member = { kind: 'field', key: node.id, fieldType: node.type, secret: node.type === 'input' && node.inputType === 'password' }
78
+ keyPath = `${path}.id`
79
+ break
80
+ default:
81
+ return
82
+ }
83
+ if (member === undefined) return
84
+ const existing = members.get(member.key)
85
+ if (existing !== undefined) {
86
+ if (existing.kind !== 'checkbox' || member.kind !== 'checkbox') {
87
+ diagnostics.push(`${keyPath} conflicts with ${paths.get(member.key)}: submission key '${member.key}' is already used`)
88
+ }
89
+ return
90
+ }
91
+ members.set(member.key, member)
92
+ paths.set(member.key, keyPath)
93
+ })
94
+
95
+ for (const { groups, path } of submits) {
96
+ const seen = new Set<string>()
97
+ groups.forEach((key, index) => {
98
+ const at = `${path}.groups[${index}]`
99
+ if (seen.has(key)) diagnostics.push(`${at}: duplicate submission member '${key}'`)
100
+ seen.add(key)
101
+ const member = members.get(key)
102
+ if (member === undefined) diagnostics.push(`${at}: submit.groups references unknown submission member '${key}'`)
103
+ else if (member.kind === 'field' && member.secret) diagnostics.push(`${at}: submit.groups cannot require secret field '${key}'`)
104
+ })
105
+ }
106
+ return { registry: { members }, diagnostics }
107
+ }
108
+
109
+ /** 编译供运行时读取的静态 submission 成员表。 */
110
+ export function compileSubmissionRegistry(spec: GenuiSpec): SubmissionRegistry {
111
+ return analyzeSubmissionRegistry(spec).registry
112
+ }
113
+
114
+ /** 根据当前交互状态判断一个 submission member 是否完成。 */
115
+ export function isSubmissionMemberAnswered(member: SubmissionMember, state: SubmitInteractionState): boolean {
116
+ switch (member.kind) {
117
+ case 'radio': return state.answers[member.key] !== undefined
118
+ case 'checkbox': return (state.multiAnswers[member.key]?.length ?? 0) > 0
119
+ case 'field': {
120
+ if (member.secret) return false
121
+ const value = state.fields[member.key]
122
+ return value !== undefined && value.trim() !== ''
123
+ }
124
+ }
125
+ }
126
+
127
+ /** 计算 submit 进度和纯本地判卷条件。 */
128
+ export function resolveSubmitState({ registry, groups, state }: {
129
+ registry: SubmissionRegistry
130
+ groups?: string[]
131
+ state: SubmitInteractionState
132
+ }): ResolvedSubmitState {
133
+ const hasUnknownMember = groups?.some(key => !registry.members.has(key)) ?? false
134
+ const scope = groups === undefined
135
+ ? [...registry.members.values()].filter(member => isSubmissionMemberAnswered(member, state))
136
+ : groups.flatMap(key => {
137
+ const member = registry.members.get(key)
138
+ return member === undefined ? [] : [member]
139
+ })
140
+ const answered = scope.filter(member => isSubmissionMemberAnswered(member, state)).length
141
+ const total = groups?.length ?? scope.length
142
+ const scopeKeys = new Set(scope.map(member => member.key))
143
+ const hasOutOfScopePayload = Object.keys(state.answers).some(key => !scopeKeys.has(key))
144
+ || Object.keys(state.multiAnswers).some(key => !scopeKeys.has(key))
145
+ || Object.entries(state.fields).some(([key, value]) => value.trim() !== '' && !state.secretFields.has(key) && !scopeKeys.has(key))
146
+ const localGradeEligible = !hasUnknownMember && scope.length > 0
147
+ && scope.every(member => member.kind === 'radio')
148
+ && scope.some(member => member.kind === 'radio' && member.answer !== undefined)
149
+ return { scope, answered, total, localGradeEligible, hasOutOfScopePayload }
150
+ }
@@ -0,0 +1,39 @@
1
+ import { useLayoutEffect, useRef, useState, type Key } from 'react'
2
+ import { CodeBlock } from '@deepseek-ai/dsh-client-ui-primitives'
3
+ import { SvgNode } from './blocks/svg.tsx'
4
+ import { codeBlockLabels } from './primitive-labels.ts'
5
+ import { useT } from './i18n/index.ts'
6
+ import css from './GenuiBlock.module.css'
7
+
8
+ function SvgFence({ raw }: { raw: string }) {
9
+ const t = useT()
10
+ const ref = useRef<HTMLDivElement>(null)
11
+ const [settled, setSettled] = useState(false)
12
+ const [source, setSource] = useState(false)
13
+ useLayoutEffect(() => {
14
+ const node = ref.current
15
+ if (node === null) return
16
+ const update = () => { setSettled(node.closest('[data-streaming]') === null) }
17
+ update()
18
+ const observer = new MutationObserver(update)
19
+ for (let ancestor = node.parentElement; ancestor !== null; ancestor = ancestor.parentElement) {
20
+ observer.observe(ancestor, { attributes: true, attributeFilter: ['data-streaming'] })
21
+ }
22
+ return () => { observer.disconnect() }
23
+ })
24
+ return (
25
+ <div ref={ref} data-genui-svg-fence className={`${css.block} ${css.tabs}`}>
26
+ {settled && <div role="group" aria-label={t('block.svgLabel')} className={css.tabBar}>
27
+ <button type="button" className={`${css.tab} ${!source ? css.tabActive : ''}`} aria-pressed={!source} onClick={() => { setSource(false) }}>{t('block.svgPreview')}</button>
28
+ <button type="button" className={`${css.tab} ${source ? css.tabActive : ''}`} aria-pressed={source} onClick={() => { setSource(true) }}>{t('block.svgSource')}</button>
29
+ </div>}
30
+ {!settled || source
31
+ ? <CodeBlock {...codeBlockLabels()} code={raw} lang="svg" />
32
+ : <SvgNode node={{ type: 'svg', code: raw }} />}
33
+ </div>
34
+ )
35
+ }
36
+
37
+ export function renderSvgFence(raw: string, key: Key) {
38
+ return <SvgFence key={key} raw={raw} />
39
+ }
@@ -0,0 +1,151 @@
1
+ import { GENUI_LIMITS } from './genui-runtime/index.ts'
2
+
3
+ /** 保存 repair 所需的原始 table 字段。 */
4
+ export interface TableDetailSource {
5
+ columns?: unknown
6
+ rows?: unknown
7
+ data?: unknown
8
+ types?: unknown
9
+ }
10
+
11
+ /** 保存 repair 后的 table 列和行。 */
12
+ export interface PreparedTableRows {
13
+ columns: string[]
14
+ rows: Array<Array<string | number>>
15
+ }
16
+
17
+ /** 使用 table repair 相同的转换规则处理列和行。 */
18
+ export function prepareTableRows(table: TableDetailSource): PreparedTableRows | null {
19
+ const declaredColumns = table.columns
20
+ const columnsSpecified = Array.isArray(declaredColumns) && declaredColumns.length > 0
21
+ const rawColumns = columnsSpecified && Array.isArray(declaredColumns)
22
+ && typeof declaredColumns[0] === 'object' && declaredColumns[0] !== null
23
+ ? declaredColumns.map(columnHeaderText)
24
+ : declaredColumns
25
+ let columns = repairColumnValues(rawColumns)
26
+ let rawRows = table.rows !== undefined ? table.rows : table.data
27
+
28
+ if (Array.isArray(rawRows) && rawRows.length > 0
29
+ && typeof rawRows[0] === 'object' && rawRows[0] !== null && !Array.isArray(rawRows[0])) {
30
+ const keys = Array.isArray(table.columns) && table.columns.length > 0
31
+ && typeof table.columns[0] === 'object' && table.columns[0] !== null
32
+ ? table.columns.map(columnKeyOf).filter((key): key is string => key !== undefined)
33
+ : Object.keys(rawRows[0] as Record<string, unknown>)
34
+ rawRows = rawRows.map(row => keys.map(key => cellText((row as Record<string, unknown>)[key])))
35
+ }
36
+
37
+ let derived: PreparedTableRows | null = null
38
+ if (!columnsSpecified && Array.isArray(rawRows) && rawRows.length > 0 && Array.isArray(rawRows[0])) {
39
+ const grid = repairRows(rawRows)
40
+ const candidate = grid.length === 0 ? null : deriveTableColumns(grid)
41
+ if (candidate !== null && repairRows(candidate.rows).length === candidate.rows.length) {
42
+ derived = candidate
43
+ columns = candidate.columns.map(column => column.slice(0, 128))
44
+ }
45
+ }
46
+
47
+ if (columns.length === 0 && !Array.isArray(table.columns)) return null
48
+ const rows = repairRows(derived === null ? rawRows : derived.rows)
49
+ if (!Array.isArray(rawRows)) return null
50
+ return { columns: columns.slice(0, GENUI_LIMITS.maxTableCols), rows }
51
+ }
52
+
53
+ /** 返回 repair 后可显示详情的 table 行。 */
54
+ export function tableRowsForDetails<Row = unknown>(table: TableDetailSource): Row[] {
55
+ return (prepareTableRows(table)?.rows ?? []) as Row[]
56
+ }
57
+
58
+ /** 按照 table renderer 的规则识别分组标题行。 */
59
+ export function isTableGroupHeaderRow(row: unknown, types: unknown): boolean {
60
+ if (!Array.isArray(row) || !Array.isArray(types) || types[0] !== 'group') return false
61
+ return String(row[0] ?? '').trim() !== ''
62
+ && row.slice(1).every(cell => String(cell ?? '').trim() === '')
63
+ }
64
+
65
+ /** 判断详情索引对应的行是否可展开并显示。 */
66
+ export function isTableDetailReachable(table: TableDetailSource, rowIndex: number): boolean {
67
+ const rows = tableRowsForDetails(table)
68
+ return rowIndex >= 0
69
+ && rowIndex < rows.length
70
+ && !isTableGroupHeaderRow(rows[rowIndex], table.types)
71
+ }
72
+
73
+ /** 按照 guard 接受的 object alias 规则修复 table 列。 */
74
+ function repairColumnValues(value: unknown): string[] {
75
+ if (!Array.isArray(value)) return []
76
+ const columns: string[] = []
77
+ for (const item of value) {
78
+ if (columns.length >= GENUI_LIMITS.maxTableCols) break
79
+ if (typeof item === 'string') columns.push(item.slice(0, 128))
80
+ else if (item !== null && typeof item === 'object') {
81
+ const column = item as Record<string, unknown>
82
+ const label = typeof column.label === 'string' ? column.label
83
+ : typeof column.value === 'string' ? column.value
84
+ : typeof column.title === 'string' ? column.title
85
+ : JSON.stringify(item)
86
+ columns.push(label.slice(0, 128))
87
+ }
88
+ }
89
+ return columns
90
+ }
91
+
92
+ /** 按照 table repair 的单元格规则裁剪并清理行。 */
93
+ function repairRows(value: unknown): Array<Array<string | number>> {
94
+ if (!Array.isArray(value)) return []
95
+ const rows: Array<Array<string | number>> = []
96
+ for (const row of value) {
97
+ if (rows.length >= GENUI_LIMITS.maxTableRows) break
98
+ if (!Array.isArray(row)) continue
99
+ const cells: Array<string | number> = []
100
+ for (const cell of row) {
101
+ if (cells.length >= GENUI_LIMITS.maxTableCols) break
102
+ if (typeof cell === 'string') cells.push(cell.slice(0, 256))
103
+ else if (typeof cell === 'number' && Number.isFinite(cell)) cells.push(cell)
104
+ }
105
+ if (cells.length > 0) rows.push(cells)
106
+ }
107
+ return rows
108
+ }
109
+
110
+ /** 从有效的首行表头生成 table 列。 */
111
+ function deriveTableColumns(rows: Array<Array<string | number>>): PreparedTableRows | null {
112
+ const header = rows[0]
113
+ if (header === undefined || header.length === 0) return null
114
+ const body = rows.slice(1)
115
+ if (body.length === 0) {
116
+ const columns = header.map(cell => String(cell).trim())
117
+ return columns.every(column => column !== '') ? { columns, rows: [] } : null
118
+ }
119
+ if (body.every(row => row.length === header.length)) {
120
+ return { columns: header.map(cell => String(cell).trim()), rows: body }
121
+ }
122
+ return { columns: Array.from({ length: header.length }, (_unused, index) => `列${index + 1}`), rows }
123
+ }
124
+
125
+ /** 读取 object row 映射到列时使用的 key。 */
126
+ function columnKeyOf(value: unknown): string | undefined {
127
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
128
+ const column = value as Record<string, unknown>
129
+ for (const key of ['key', 'dataIndex', 'title', 'label'] as const) {
130
+ if (typeof column[key] === 'string' && column[key] !== '') return column[key]
131
+ }
132
+ return undefined
133
+ }
134
+
135
+ /** 将 object row 中的值转换为 table 单元格,并保留列位置。 */
136
+ function cellText(value: unknown): string | number {
137
+ if (typeof value === 'string') return value
138
+ if (typeof value === 'number' && Number.isFinite(value)) return value
139
+ if (value === null || value === undefined) return ''
140
+ return JSON.stringify(value)
141
+ }
142
+
143
+ /** 读取 object column 显示的标题。 */
144
+ function columnHeaderText(value: unknown): string {
145
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return String(value)
146
+ const column = value as Record<string, unknown>
147
+ for (const key of ['title', 'label', 'key', 'dataIndex'] as const) {
148
+ if (typeof column[key] === 'string' && column[key] !== '') return column[key]
149
+ }
150
+ return JSON.stringify(value)
151
+ }