@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,9 @@
1
+ import type { GenuiEChart } from './spec.ts'
2
+
3
+ export const CORE_PRESETS: ReadonlySet<string> = new Set(['bar', 'line', 'area', 'pie', 'scatter', 'bigline'])
4
+
5
+ /** 依照 renderer 共用的 preset 规则选择 ECharts 资源。 */
6
+ export function echartEngineFor(node: GenuiEChart): 'echarts-core' | 'echarts-full' {
7
+ if (node.option !== undefined) return 'echarts-full'
8
+ return CORE_PRESETS.has(node.preset ?? 'bar') ? 'echarts-core' : 'echarts-full'
9
+ }
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Runtime loader for the ECharts engine. The heavy echarts bundle ships as a
3
+ * separate asset (`lib/assets/echarts.js`, served by the plugin's own HTTP
4
+ * route) and is fetched ONLY when a spec contains an `echart` node — the
5
+ * main client bundle stays small and most conversations never download
6
+ * echarts at all. On a host that does not serve the asset the load rejects
7
+ * and the EChartNode shows its fallback.
8
+ * @module @changfenhuang/dsh-genui/client/echarts-lazy
9
+ */
10
+ import { loadGenuiAsset } from './asset-loader.ts'
11
+ export { CORE_PRESETS } from './echarts-engine.ts'
12
+
13
+ /** The ECharts instance surface (the subset the component uses). */
14
+ export interface EChartsInstance {
15
+ setOption: (opt: unknown, notMerge?: boolean) => void
16
+ resize: () => void
17
+ dispose: () => void
18
+ }
19
+
20
+ /** The engine surface registered by the echarts asset bundle. */
21
+ interface EChartsAssetApi {
22
+ createChart: (el: HTMLElement, option: unknown, opts?: { height?: number }) => EChartsInstance
23
+ }
24
+
25
+ /**
26
+ * Create an ECharts instance on `el` with the given option (engine loaded on
27
+ * demand). The caller owns the returned instance and must dispose it.
28
+ * @param el - the DOM node to host the chart canvas.
29
+ * @param option - the ECharts option object.
30
+ * @param opts - optional height override.
31
+ * @returns the ECharts instance (setOption/resize/dispose).
32
+ */
33
+ export async function createChart(
34
+ el: HTMLElement,
35
+ option: unknown,
36
+ opts?: { height?: number },
37
+ engine: 'core' | 'full' = 'core',
38
+ ): Promise<EChartsInstance> {
39
+ const api = await loadGenuiAsset<EChartsAssetApi>(engine === 'full' ? 'echarts-full' : 'echarts-core')
40
+ return api.createChart(el, option, opts)
41
+ }
@@ -0,0 +1,19 @@
1
+ /// <reference path="../css-modules.d.ts" />
2
+ /** Public bundler entry for hosts that embed GenUI without the DSH plugin runtime. */
3
+ export { GenuiBlock } from './GenuiBlock.tsx'
4
+ export { GenuiActionContext } from './action-context.ts'
5
+ export { ErrorBoundary } from './ErrorBoundary.tsx'
6
+ export { isRenderableProcess, processGenuiSpec } from './guard.ts'
7
+ export { setGenuiAssetBase } from './asset-loader.ts'
8
+ export type { GenuiSpec } from './spec.ts'
9
+ export type { BlockInteractionState } from './interaction-store.ts'
10
+ export {
11
+ analyzeGenuiPortability,
12
+ buildStandaloneHtml,
13
+ createGenuiArtifact,
14
+ downloadGenuiArtifactHtml,
15
+ downloadGenuiArtifactJson,
16
+ parseGenuiArtifact,
17
+ serializeGenuiArtifact,
18
+ } from './artifact/index.ts'
19
+ export type { GenuiArtifactV1, GenuiPortabilityReport } from './artifact/index.ts'
@@ -0,0 +1,266 @@
1
+ /**
2
+ * The dsh-ui fence render pipeline, shared by both render channels:
3
+ *
4
+ * - **Registry channel** (contract hosts): the host's MarkdownText resolves
5
+ * ```dsh-ui fences through the fence-registry extension point and calls
6
+ * {@link renderGenuiFence} with a session-scoped context (sessionId + the
7
+ * settled source identity). An unrepairable body renders {@link FenceFallback}.
8
+ * - **DOM channel** (pristine hosts, no extension point): the DOM observer
9
+ * (`dom-fence.ts`) finds stock code blocks labelled `dsh-ui` and mounts
10
+ * {@link renderResolvedFenceNode} into its own React root, wrapped in the
11
+ * plugin-owned action context. An unrepairable body returns `null` so the
12
+ * stock code block stays visible, with {@link FenceDiagnostic} mounted above
13
+ * it so the defect is never silent (issue #158).
14
+ *
15
+ * Structural types are declared locally on purpose: the context contract is
16
+ * a data shape, and pristine hosts do not export the host-side type names.
17
+ */
18
+ import { Fragment, useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type Key, type ReactNode } from 'react'
19
+ import { CodeBlock } from '@deepseek-ai/dsh-client-ui-primitives'
20
+ import { codeBlockLabels } from './primitive-labels.ts'
21
+ import { t, useT } from './i18n/index.ts'
22
+ import { ErrorBoundary } from './ErrorBoundary.tsx'
23
+ import { ExportableGenuiBlock } from './artifact/ExportableGenuiBlock.tsx'
24
+ import { fenceStateKey } from './interaction-store.ts'
25
+ import { applyPanelOperation, diagnosePanelBudget, type PanelOperationStatus } from './panel-store.ts'
26
+ import type { GenuiSpec } from './spec.ts'
27
+ import { describeJsonFailure, isCompleteJson } from '../shared/fence-repair.ts'
28
+ import { resolveFence, resolveFenceSpec, type FenceResolution } from '../shared/fence-resolve.ts'
29
+
30
+ /** Settled fence source identity (data shape, host-independent). */
31
+ export interface GenuiFenceSource {
32
+ /** Stable structural id, e.g. `['assistant', seq, block, fence]` or `dom:<anchor>:<i>`. */
33
+ readonly id: string
34
+ /** Three-part order: [messageSeq, textBlockIndex, fenceIndex]. */
35
+ readonly order: readonly [number, number, number]
36
+ }
37
+
38
+ /** Context a fence renderer receives beside the raw source and React key. */
39
+ export interface GenuiFenceContext {
40
+ /** Owning session route; absent outside a session-scoped render. */
41
+ readonly sessionId?: string
42
+ /** Present only for settled/interrupted renders with a stable identity. */
43
+ readonly source?: GenuiFenceSource
44
+ }
45
+
46
+ const FENCE_ERROR_STYLE: CSSProperties = {
47
+ margin: '0 0 6px',
48
+ padding: '6px 10px',
49
+ borderRadius: 6,
50
+ background: 'rgba(239, 68, 68, 0.14)',
51
+ border: '1px solid rgba(239, 68, 68, 0.4)',
52
+ color: '#f87171',
53
+ fontSize: 12,
54
+ lineHeight: 1.55,
55
+ whiteSpace: 'pre-wrap',
56
+ }
57
+
58
+ /** Format chart-specific process errors without maintaining a second validator. */
59
+ function formatChartProcessErrors(errors: string[]): string | null {
60
+ const chartErrors = errors.filter(error => /(?:variant is unsupported|kind must be bars, line, or donut|requires data or series|(?:data|series) is required for|(?:\.data|\.series)(?:\[\d+\])?(?:\.(?:data|label|value|color))? must|series is only supported for bars)/.test(error))
61
+ return chartErrors.length === 0 ? null : chartErrors.join(';')
62
+ }
63
+
64
+ /** Return a semantic/schema diagnostic from the unified fence resolution. */
65
+ function processSemanticFailure(resolution: FenceResolution): string | null {
66
+ if (resolution.spec !== null || resolution.processed === null) return null
67
+ const chartErrors = formatChartProcessErrors(resolution.processed.errors)
68
+ return chartErrors === null
69
+ ? t('err.fieldValidation', { errors: resolution.processed.errors.join(';') })
70
+ : t('err.chartValidation', { errors: chartErrors })
71
+ }
72
+
73
+ /**
74
+ * Fallback for a ```dsh-ui fence whose body has no finished component yet.
75
+ * Two very different situations land here and they must not be conflated:
76
+ *
77
+ * 1. **Streaming partial** — the reply is still being written and the JSON
78
+ * simply is not complete. The host marks the streaming message with
79
+ * `[data-streaming]` on the AssistantMarkdown root, which is an ancestor
80
+ * of every fence. While that marker is present, a plain code block is the
81
+ * correct rendering (partial JSON must never look like an error).
82
+ *
83
+ * 2. **Settled defect** — the message is finished but the body still does
84
+ * not parse as JSON (a malformed fence like a missing `}`) or violates the
85
+ * native chart contract. This used to fail silently: the fence degraded to
86
+ * a code block with no hint, and the author had no way to know the UI never
87
+ * rendered. Once the streaming marker is gone, surface a compact diagnostic
88
+ * so the defect is visible instead of silent.
89
+ */
90
+ /**
91
+ * Explain why a ```dsh-ui body cannot render, as the one-line message both
92
+ * channels show. Returns null when there is nothing to report (the body is
93
+ * renderable, or it is an empty/streaming half).
94
+ *
95
+ * @param raw - the raw fence body.
96
+ * @param options - whether settled-only structural repair may be used.
97
+ * @returns the diagnostic text, or null.
98
+ */
99
+ export function describeFenceFailure(raw: string, options: { settled?: boolean } = {}): string | null {
100
+ const resolution = resolveFence(raw, { settled: options.settled ?? true })
101
+ if (resolution.spec !== null) return null
102
+ const processDiagnostic = processSemanticFailure(resolution)
103
+ if (processDiagnostic !== null) {
104
+ return t('err.fenceKeptAsCode', { diagnostic: processDiagnostic })
105
+ }
106
+ if (raw.trim() === '') return null
107
+ const parseDiagnostic = describeJsonFailure(raw)
108
+ if (parseDiagnostic === null) return null
109
+ return t('err.fenceParse', { diagnostic: parseDiagnostic })
110
+ }
111
+
112
+ /**
113
+ * The visible diagnostic for a settled, unrenderable ```dsh-ui body.
114
+ *
115
+ * Shared by both channels: the registry channel renders it above its own
116
+ * fallback code block, the DOM channel above the host's stock code block. A
117
+ * fence that keeps degrading to raw JSON must say why it degraded — the
118
+ * console-only path left the defect invisible (issues #158/#172).
119
+ *
120
+ * @param raw - the raw fence body.
121
+ * @returns the alert strip, or null when the body has nothing to report.
122
+ */
123
+ export function FenceDiagnostic({ raw, settled = false }: { raw: string; settled?: boolean }): ReactNode {
124
+ // Subscribe so a language switch re-renders an already-visible diagnostic.
125
+ useT()
126
+ const message = describeFenceFailure(raw, { settled })
127
+ if (message === null) return null
128
+ return <div style={FENCE_ERROR_STYLE} role="alert">{message}</div>
129
+ }
130
+
131
+ function FenceFallback({ raw, fenceKey }: { raw: string; fenceKey: Key }) {
132
+ // Subscribed for the CodeBlock copy labels below.
133
+ useT()
134
+ const ref = useRef<HTMLDivElement | null>(null)
135
+ const [settled, setSettled] = useState(false)
136
+ useLayoutEffect(() => {
137
+ const node = ref.current
138
+ if (node !== null && node.closest('[data-streaming]') === null) setSettled(true)
139
+ })
140
+ const diagnostic = settled ? <FenceDiagnostic raw={raw} /> : null
141
+ return (
142
+ <div ref={ref}>
143
+ {diagnostic}
144
+ <CodeBlock key={fenceKey} {...codeBlockLabels()} code={`${raw}\n`} lang="dsh-ui" />
145
+ </div>
146
+ )
147
+ }
148
+
149
+ /**
150
+ * Keyed publisher for a settled `panel:true` fence: submits ONE panel
151
+ * operation from the host-provided stable source (id + order), in an
152
+ * effect — never inside the render function. StrictMode's duplicate effects
153
+ * are absorbed by the operation map's per-source dedup, so the panel folds
154
+ * and notifies exactly once per source. Renders nothing.
155
+ */
156
+ function FencePanelPublisher({ sessionId, sourceId, order, spec }: {
157
+ sessionId: string
158
+ sourceId: string
159
+ order: readonly [number, number, number]
160
+ spec: GenuiSpec
161
+ }) {
162
+ useEffect(() => {
163
+ const status: PanelOperationStatus = applyPanelOperation(sessionId, {
164
+ sourceId,
165
+ order,
166
+ mode: spec.append === true ? 'append' : 'replace',
167
+ spec,
168
+ })
169
+ if (status === 'overflow') diagnosePanelBudget(sessionId, sourceId)
170
+ }, [sessionId, sourceId, order, spec])
171
+ return null
172
+ }
173
+
174
+ /**
175
+ * Resolve a raw fence body to a guarded spec.
176
+ *
177
+ * - Tier-1 repair (quote escape + trailing commas): safe at any time —
178
+ * adopted only when the whole body parses, so a still-growing streaming
179
+ * half keeps falling back to the code block, never flashing a banner.
180
+ * - Tier-2 completion (missing quotes/brackets): settled renders only —
181
+ * `context.source` exists exclusively once the message finished, so
182
+ * streaming halves are never completed early.
183
+ * - Native chart semantics are checked before repair on every candidate so
184
+ * aliases, empty collections, or line/donut series cannot repair into a
185
+ * default/blank chart.
186
+ */
187
+ export function resolveGenuiSpec(raw: string, context?: GenuiFenceContext): GenuiSpec | null {
188
+ return resolveFenceSpec(raw, { settled: context?.source !== undefined })
189
+ }
190
+
191
+ /** The inline GenuiBlock tree for a resolved non-panel spec. */
192
+ function renderInlineFence(key: Key, context: GenuiFenceContext | undefined, spec: GenuiSpec): ReactNode {
193
+ const sessionId = context?.sessionId
194
+ const stateKey = sessionId === undefined || context?.source === undefined
195
+ ? undefined
196
+ : fenceStateKey(sessionId, context.source.id, JSON.stringify(spec))
197
+ return (
198
+ // Keep the document slot mounted across streaming→settled; GenuiBlock
199
+ // owns durable-state changes, while a session change resets the tree.
200
+ // Repaired specs render SILENTLY: once the UI renders, no amber note
201
+ // tells the user something was wrong — only an unrecoverable body keeps
202
+ // the red diagnostic.
203
+ <ErrorBoundary key={JSON.stringify([sessionId, key])} label={t('err.boundary.fence')}>
204
+ <ExportableGenuiBlock spec={spec} animateEntrance={context?.source === undefined} stateKey={stateKey} exportEnabled={context?.source !== undefined} />
205
+ </ErrorBoundary>
206
+ )
207
+ }
208
+
209
+ /**
210
+ * The resolved fence render for the DOM channel: `null` when the body is
211
+ * unrepairable (the stock code block stays visible), otherwise the panel
212
+ * publisher (`panel:true`; renders nothing in the flow — mounted as an empty
213
+ * root so the taken-over block is hidden) or the inline GenuiBlock tree.
214
+ * Shared verbatim by both channels.
215
+ */
216
+ export function renderResolvedFenceNode(raw: string, key: Key, context?: GenuiFenceContext): ReactNode | null {
217
+ const spec = resolveGenuiSpec(raw, context)
218
+ if (spec === null) return null
219
+ if (spec.panel === true) {
220
+ // Publish only with a settled stable source — streaming/identity-less
221
+ // renders keep the panel untouched. Appends additionally gate on a
222
+ // complete body (a settled-but-malformed append never merges partial
223
+ // content).
224
+ if (context !== undefined && context.sessionId !== undefined && context.source !== undefined) {
225
+ if (spec.append === true && !isCompleteJson(raw)) return <Fragment key={key} />
226
+ return (
227
+ <FencePanelPublisher
228
+ key={key}
229
+ sessionId={context.sessionId}
230
+ sourceId={context.source.id}
231
+ order={context.source.order}
232
+ spec={spec}
233
+ />
234
+ )
235
+ }
236
+ return <Fragment key={key} />
237
+ }
238
+ return renderInlineFence(key, context, spec)
239
+ }
240
+
241
+ /**
242
+ * Registry-channel fence renderer (contract hosts): like the resolved node,
243
+ * but an unrepairable body renders the fallback code block + settled
244
+ * diagnostic — the host replaced its own block with our output — and an
245
+ * unpublishable `panel:true` fence renders `null` (nothing in the flow).
246
+ */
247
+ export function renderGenuiFence(raw: string, key: Key, context?: GenuiFenceContext): ReactNode {
248
+ const spec = resolveGenuiSpec(raw, context)
249
+ if (spec === null) return <FenceFallback key={key} fenceKey={key} raw={raw} />
250
+ if (spec.panel === true) {
251
+ if (context !== undefined && context.sessionId !== undefined && context.source !== undefined) {
252
+ if (spec.append === true && !isCompleteJson(raw)) return null
253
+ return (
254
+ <FencePanelPublisher
255
+ key={key}
256
+ sessionId={context.sessionId}
257
+ sourceId={context.source.id}
258
+ order={context.source.order}
259
+ spec={spec}
260
+ />
261
+ )
262
+ }
263
+ return null
264
+ }
265
+ return renderInlineFence(key, context, spec)
266
+ }
@@ -0,0 +1,215 @@
1
+ /**
2
+ * GenUI gallery: canonical broad-coverage sample of built-in node types.
3
+ * Docs, demos, and renderer tests reuse it as the component gallery fence.
4
+ */
5
+ import type { GenuiSpec } from './spec.ts'
6
+
7
+ /** Canonical gallery spec for the built-in GenUI component vocabulary. */
8
+ export const gallerySpec: GenuiSpec = {
9
+ title: 'GenUI · 组件画廊',
10
+ gap: 14,
11
+ items: [
12
+ { type: 'hero', label: '可用率 · 近 30 天', value: '99.96%', delta: '+0.02%', tone: 'accent', spark: [99.8, 99.85, 99.9, 99.88, 99.94, 99.96], title: 'hero 封面块', subtitle: '一条回答最多一个:eyebrow + 超大数字 + 标题 + 副标题,带 tone 渐变底色。' },
13
+ { type: 'grid', cols: 3, items: [
14
+ { type: 'card', title: '默认', items: [{ type: 'text', size: 'body', content: '不写 accent:中性表面。' }] },
15
+ { type: 'card', accent: '#f59e0b', title: 'accent #f59e0b', items: [{ type: 'text', size: 'body', content: '只有边框与标题带上色相,表面保持中性。' }] },
16
+ { type: 'card', accent: '#3ecf8e', title: 'accent #3ecf8e', items: [{ type: 'text', size: 'body', content: '深色主题下不会发脏。' }] },
17
+ ] },
18
+ { type: 'grid', cols: 3, items: [
19
+ { type: 'card', span: 2, title: 'span:2 · 宽卡', items: [
20
+ { type: 'text', size: 'body', content: 'grid 子节点加 span 就能跨列:一张宽卡 + 一张窄卡。卡片高度由该行最高的一张决定,内容会自动撑满或居中。' },
21
+ { type: 'chart', kind: 'line', data: [], series: [
22
+ { label: '本周', data: [{ label: '一', value: 8 }, { label: '二', value: 12 }, { label: '三', value: 9 }, { label: '四', value: 14 }] },
23
+ { label: '上周', data: [{ label: '一', value: 6 }, { label: '二', value: 9 }, { label: '三', value: 7 }, { label: '四', value: 10 }] }] }] },
24
+ { type: 'card', title: 'span:1', items: [{ type: 'chart', kind: 'donut', data: [{ label: '视觉', value: 42 }, { label: '采纳', value: 33 }, { label: '可靠', value: 25 }] }] },
25
+ ] },
26
+ { type: 'text', size: 'h1', content: '排版层级' },
27
+ { type: 'text', size: 'h2', content: '二级标题' },
28
+ { type: 'text', size: 'h3', content: '三级标题' },
29
+ { type: 'text', size: 'body', content: '正文:组件白名单渲染,不经过任意 HTML 路径。' },
30
+ { type: 'text', size: 'muted', content: '弱化文本' },
31
+ { type: 'text', size: 'caption', content: '说明文字', center: true },
32
+ { type: 'row', items: [
33
+ { type: 'badge', label: '成功', tone: 'success' },
34
+ { type: 'badge', label: '警告', tone: 'warn' },
35
+ { type: 'badge', label: '危险', tone: 'danger' },
36
+ { type: 'badge', label: '强调', tone: 'accent', icon: '★' },
37
+ { type: 'avatar', name: 'Alice' },
38
+ { type: 'avatar', name: 'Bob', color: '#3d9e8f' },
39
+ { type: 'link', label: '详情链接' },
40
+ ], wrap: true },
41
+ { type: 'divider' },
42
+ { type: 'image', src: '/demo-image.png', alt: '图片展示演示' },
43
+ { type: 'audio', src: '/demo-audio.mp3', alt: '音频播放器演示' },
44
+ { type: 'video', src: '/demo-video.mp4', alt: '视频播放器演示', poster: '/demo-video.jpg', aspectRatio: '16:9' },
45
+ { type: 'grid', cols: 3, items: [
46
+ { type: 'stat', label: '在线率', value: '99.96%', size: 'hero', delta: '+0.02%' },
47
+ { type: 'stat', label: 'CPU', value: '42%', delta: '+3.1%', spark: [31, 38, 35, 44, 40, 42] },
48
+ { type: 'stat', label: '内存', value: '6.8 GB', delta: '-1.2%' },
49
+ { type: 'stat', label: '请求数', value: '128.4k', spark: [90, 104, 98, 121, 116, 128] },
50
+ ] },
51
+ { type: 'progress', label: '训练进度', value: 72, valueLabel: '72%' },
52
+ { type: 'progress', label: '覆盖率', value: 64, target: 80, valueLabel: '64% / 目标 80%' },
53
+ { type: 'progress', variant: 'ring', value: 72, label: '本轮完成度', valueLabel: '第 3 / 4 轮' },
54
+ { type: 'card', title: '性能指标', items: [
55
+ // 表头可点击排序:数值感知(千分位 / k / 万 / % 都能正确比较),
56
+ // 数值列自动右对齐。
57
+ { type: 'table', columns: ['指标', 'Q1', 'Q2', 'Q3'], rows: [
58
+ ['延迟', 92, 87, 81], ['吞吐', '1.2k', '1.4k', '1.6k'], ['错误率', '0.3%', '0.2%', '0.1%'],
59
+ ['营收', '3.5万', '4.1万', '5.2万'], ['注册', '1,234', '2,345', '3,456'],
60
+ ] },
61
+ { type: 'keyvalue', pairs: [
62
+ { key: '版本', value: 'v0.1.0' }, { key: '环境', value: 'production' }, { key: '区域', value: 'cn-east' },
63
+ ] },
64
+ ] },
65
+ { type: 'list', items: [
66
+ { title: '标题项', desc: '带描述的列表项' },
67
+ '纯文本列表项',
68
+ { title: '另一个标题' },
69
+ ] },
70
+ { type: 'chart', kind: 'bars', data: [
71
+ { label: '一', value: 10 }, { label: '二', value: 20 }, { label: '三', value: 15 },
72
+ ] },
73
+ { type: 'chart', kind: 'line', data: [
74
+ { label: '周一', value: 8 }, { label: '周二', value: 12 }, { label: '周三', value: 9 },
75
+ ] },
76
+ { type: 'chart', kind: 'donut', data: [
77
+ { label: 'A', value: 30 }, { label: 'B', value: 70 },
78
+ ] },
79
+ { type: 'chart', data: [], series: [
80
+ { label: '本月', data: [{ label: 'Q1', value: 3 }, { label: 'Q2', value: 5 }] },
81
+ { label: '上月', data: [{ label: 'Q1', value: 2 }, { label: 'Q2', value: 4 }] },
82
+ ] },
83
+ { type: 'chart', kind: 'line', data: [], series: [
84
+ { label: '本月', data: [{ label: '一', value: 8 }, { label: '二', value: 12 }, { label: '三', value: 9 }] },
85
+ { label: '上月', data: [{ label: '一', value: 6 }, { label: '二', value: 9 }, { label: '三', value: 7 }] },
86
+ ] },
87
+ { type: 'chart', kind: 'bars', data: [], stacked: true, series: [
88
+ { label: '已完成', data: [{ label: 'Q1', value: 42 }, { label: 'Q2', value: 58 }, { label: 'Q3', value: 61 }] },
89
+ { label: '进行中', data: [{ label: 'Q1', value: 18 }, { label: 'Q2', value: 14 }, { label: 'Q3', value: 9 }] },
90
+ ] },
91
+ { type: 'chart', horizontal: true, data: [
92
+ { label: '自然搜索', value: 82 }, { label: '直接访问', value: 64 }, { label: '社交媒体', value: 41 },
93
+ ] },
94
+ { type: 'input', label: '筛选服务 / 状态', placeholder: '输入关键字即时过滤下表', id: 'gallery-filter' },
95
+ { type: 'table', columns: ['服务', 'P95', '状态'], types: ['text', 'num', 'badge'], filter: 'gallery-filter', rows: [
96
+ ['API 网关', '128', '正常'],
97
+ ['搜索', '190', '关注'],
98
+ ['推荐', '250', '偏高'],
99
+ ] },
100
+ { type: 'table', columns: ['服务', 'P95', '状态'], types: ['text', 'num', 'badge'], details: [
101
+ [{ type: 'keyvalue', pairs: [{ key: '负责人', value: '平台组' }, { key: 'SLO', value: 'P95 < 150ms' }] },
102
+ { type: 'text', size: 'body', content: '展开行可以放任意组件:指标、图表、列表、表单都可以。' }],
103
+ null,
104
+ [{ type: 'progress', value: 91, target: 80, label: '负载水位', valueLabel: '91% / 目标 80%' }],
105
+ ], rows: [
106
+ ['API 网关', '128', '正常'],
107
+ ['搜索', '190', '关注'],
108
+ ['推荐', '250', '偏高'],
109
+ ] },
110
+ { type: 'table', columns: ['区域', 'Q1', 'Q2', 'Q3'], types: ['group', 'num', 'num', 'num'], total: true, rows: [
111
+ ['华东', '', '', ''],
112
+ ['上海', '120', '138', '151'],
113
+ ['杭州', '96', '104', '118'],
114
+ ['华北', '', '', ''],
115
+ ['北京', '88', '95', '103'],
116
+ ] },
117
+ { type: 'card', tone: 'success', title: '已通过', items: [
118
+ { type: 'text', size: 'body', content: '分组表:首列为 group 时,只有第一格有内容的行会渲染成跨列小标题;total 追加一行合计。' },
119
+ ] },
120
+ { type: 'table', columns: ['#', '服务', '近 6 期延迟', '可用率', '负载', '状态'], types: ['index', 'text', 'spark', 'ring', 'bar', 'badge'], rows: [
121
+ ['1', 'API 网关', '180,164,150,140,133,128', '99.96', '62', '正常'],
122
+ ['2', '搜索', '220,210,230,205,198,190', '99.82', '78', '关注'],
123
+ ['3', '推荐', '310,340,300,280,260,250', '99.41', '91', '偏高'],
124
+ ] },
125
+ { type: 'table', columns: ['渠道', '完成度', '状态'], types: ['text', 'bar', 'badge'], rows: [
126
+ ['自然搜索', '82', '健康'], ['直接访问', '64', '关注'], ['社交媒体', '41', '偏低'],
127
+ ] },
128
+ { type: 'tabs', tabs: [
129
+ { label: '概览', items: [{ type: 'text', content: '标签页一的内容' }] },
130
+ { label: '明细', items: [{ type: 'list', items: ['明细 A', '明细 B'] }] },
131
+ { label: '图表', items: [{ type: 'chart', kind: 'donut', data: [{ label: 'X', value: 40 }, { label: 'Y', value: 60 }] }] },
132
+ ] },
133
+ { type: 'col', gap: 8, items: [
134
+ { type: 'button', label: '主按钮', tone: 'primary' },
135
+ { type: 'button', label: '危险', tone: 'danger', small: true },
136
+ { type: 'button', label: '成功', tone: 'success' },
137
+ { type: 'button', label: '幽灵', tone: 'ghost', icon: '↗' },
138
+ ] },
139
+ { type: 'row', items: [
140
+ { type: 'input', label: '名称', placeholder: '输入…' },
141
+ { type: 'select', label: '环境', options: ['dev', 'staging', 'production'] },
142
+ ], wrap: true },
143
+ { type: 'row', items: [
144
+ { type: 'checkbox', label: '自动保存', checked: true },
145
+ { type: 'switch', label: '通知', checked: true },
146
+ { type: 'radio', label: '主题', options: ['浅色', '深色', '跟随系统'] },
147
+ ], wrap: true },
148
+ { type: 'textarea', label: '备注', placeholder: '多行输入…', rows: 3 },
149
+ { type: 'accordion', items: [
150
+ { title: '第一项', items: [{ type: 'json', value: { ok: true, count: 3 } }] },
151
+ { title: '第二项', items: [{ type: 'code', lang: 'ts', code: 'export const x = 1' }] },
152
+ ] },
153
+ { type: 'copy', label: '复制令牌', text: 'sk-1234567890' },
154
+ { type: 'echart', preset: 'bar', title: 'echart · preset:bar(只下载 core 引擎)', height: 240, data: [
155
+ { label: '自然搜索', value: 82 }, { label: '直接访问', value: 64 }, { label: '社交媒体', value: 41 },
156
+ ] },
157
+ { type: 'echart', preset: 'radar', title: 'echart · preset:radar(按需拉完整引擎)', height: 280, series: [
158
+ { label: '本轮', data: [{ label: '视觉', value: 86 }, { label: '可用', value: 92 }, { label: '性能', value: 74 }, { label: '采纳', value: 88 }, { label: '稳定', value: 90 }] },
159
+ { label: '上轮', data: [{ label: '视觉', value: 62 }, { label: '可用', value: 70 }, { label: '性能', value: 58 }, { label: '采纳', value: 61 }, { label: '稳定', value: 72 }] },
160
+ ] },
161
+ { type: 'echart', preset: 'sankey', title: 'echart · preset:sankey(links 驱动)', height: 260, links: [
162
+ { from: '入口', to: 'API', value: 40 },
163
+ { from: '入口', to: '缓存', value: 25 },
164
+ { from: 'API', to: '渲染', value: 32 },
165
+ { from: '渲染', to: '完成', value: 30 },
166
+ { from: '缓存', to: '完成', value: 28 },
167
+ ] },
168
+ { type: 'echart', preset: 'wordCloud', title: 'echart · preset:wordCloud(词云,完整引擎 + 扩展)', height: 240, data: [
169
+ { label: '系统', value: 90 }, { label: '用户', value: 70 }, { label: '权限', value: 60 },
170
+ { label: '模块', value: 50 }, { label: '数据', value: 45 }, { label: '安全', value: 40 },
171
+ { label: '扩展', value: 30 }, { label: '渲染', value: 25 },
172
+ ] },
173
+ { type: 'svg', title: 'svg · 独立图片预览(隔离渲染)', height: 160, code: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 220 120"><rect width="220" height="120" rx="10" fill="#534ab7"/><rect x="16" y="16" width="88" height="40" rx="6" fill="#7f74f2"/><text x="60" y="42" text-anchor="middle" fill="#fff" font-size="13">网关</text><rect x="116" y="64" width="88" height="40" rx="6" fill="#3ecf8e"/><text x="160" y="90" text-anchor="middle" fill="#fff" font-size="13">服务</text><path d="M104 56 L116 76" stroke="#fff" stroke-width="2"/></svg>' },
174
+ { type: 'plot', title: '波动叠加', xMin: -6.28, xMax: 6.28, series: [
175
+ { expr: 'sin(x)', label: 'sin(x)', color: '#4f8ef7' },
176
+ { expr: '0.8*cos(x)', label: 'cos', color: '#3ecf8e' },
177
+ ] },
178
+ { type: 'callout', tone: 'info', title: '提示', content: '画廊覆盖全部组件词汇。' },
179
+ { type: 'steps', current: 2, steps: [
180
+ { title: '起草', desc: '写规格' }, { title: '渲染', desc: '画组件' }, { title: '验证', desc: '跑测试' },
181
+ ] },
182
+ { type: 'diff', diffs: [
183
+ { path: 'a.ts', oldText: 'const x = 1', newText: 'const x = 2' },
184
+ ] },
185
+ { type: 'code', lang: 'json', code: '{"hello": "world"}' },
186
+ { type: 'mermaid', code: 'graph TD\nA[模型] --> B[渲染器]\nB --> C[组件]' },
187
+ { type: 'diagram', kind: 'architecture', title: '架构图(配色跟随宿主令牌)', nodes: [
188
+ { id: 'm', label: '模型', type: 'external', x: 20, y: 40, w: 100, h: 44 },
189
+ { id: 'f', label: '围栏 JSON', type: 'focal', x: 160, y: 40, w: 112, h: 44 },
190
+ { id: 'g', label: 'guard', type: 'backend', x: 312, y: 40, w: 104, h: 44 },
191
+ { id: 's', label: '组件库', type: 'store', x: 456, y: 40, w: 100, h: 44 },
192
+ ], edges: [{ from: 'm', to: 'f' }, { from: 'f', to: 'g' }, { from: 'g', to: 's' }] },
193
+ { type: 'scene3d', title: '几何演示', ambient: 1, meshes: [
194
+ { shape: 'box', color: '#4f8ef7', position: [-1.4, 0, 0], rotation: [0.5, 0.8, 0] },
195
+ { shape: 'sphere', color: '#3ecf8e', position: [0, 0, 0] },
196
+ { shape: 'cone', color: '#e0a458', position: [1.4, 0, 0] },
197
+ ] },
198
+ { type: 'timeline', items: [
199
+ { title: '发布 v0.1', desc: '首个可用版本', time: '08-01' },
200
+ { title: '事件循环', desc: 'action 回流', time: '08-08' },
201
+ ] },
202
+ { type: 'file-tree', items: [
203
+ { name: 'src', type: 'dir', children: [
204
+ { name: 'client', type: 'dir', children: [{ name: 'GenuiBlock.tsx', type: 'file' }] },
205
+ { name: 'spec.ts', type: 'file' },
206
+ ] },
207
+ { name: 'README.md', type: 'file' },
208
+ ] },
209
+ { type: 'breadcrumb', items: ['首页', '组件', '画廊'] },
210
+ { type: 'quiz', question: '1 + 1 = ?', id: 'gallery-q1', options: [
211
+ { label: '1', feedback: '再想想' }, { label: '2', correct: true }, { label: '3' },
212
+ ], explanation: '二进制里 1+1=10,十进制里是 2。' },
213
+ { type: 'spacer' },
214
+ ],
215
+ }