@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,999 @@
1
+ /**
2
+ * Chart family: categorical palette, the sortable table, and the bars / line
3
+ * / donut renderers. All local-first; no model round trips.
4
+ *
5
+ * Design system v3: the native charts draw in REAL CSS pixels — the plot width
6
+ * is measured from the container and the SVG viewBox matches it 1:1 — instead
7
+ * of a fixed 460×150 viewBox whose axis text scaled with the container (wide
8
+ * screens got oversized labels, narrow ones got unreadable ones). Every chart
9
+ * gets a y-axis with nice 1/2/5 ticks, and single-series bars render against a
10
+ * true zero line so negative values are drawn, not clamped away.
11
+ * @module @changfenhuang/dsh-genui/client/blocks/charts
12
+ */
13
+ import { Fragment, memo, useCallback, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'
14
+ import type { MouseEvent as ReactMouseEvent, ReactNode, RefObject } from 'react'
15
+ import { writeClipboard } from '../primitive-adapter.ts'
16
+ import { renderInline } from '../inline.ts'
17
+ // Aliased: `t` is already used throughout this module as a tick-value
18
+ // local (ticks.map(t => …)), so the translator rides a distinct name.
19
+ import { t as tr, useT } from '../i18n/index.ts'
20
+ import css from '../GenuiBlock.module.css'
21
+ import { GENUI_LIMITS } from '../genui-runtime/index.ts'
22
+ import type { GenuiChart, GenuiTable } from '../spec.ts'
23
+ import { isTableGroupHeaderRow, tableRowsForDetails } from '../table-details.ts'
24
+
25
+ export const CHART_COLORS = [
26
+ 'var(--dsw-static-deepseek-400)',
27
+ 'var(--dsw-static-green-400)',
28
+ 'var(--dsw-static-amber-400)',
29
+ 'var(--dsw-static-red-400)',
30
+ 'var(--dsw-static-blue-450)',
31
+ 'var(--dsw-static-deepseek-450)',
32
+ 'var(--dsw-static-neutral-bluish-400)',
33
+ 'var(--dsw-static-deepseek-300)',
34
+ ]
35
+
36
+ /** Series color: explicit color wins; then an explicit `palette` from the
37
+ * spec; then the host categorical tokens. */
38
+ const seriesColor = (i: number, n: number, c?: string, palette?: readonly string[]): string | undefined =>
39
+ c ?? (palette !== undefined && palette.length > 0
40
+ ? palette[i % palette.length]
41
+ : n > 1 ? CHART_COLORS[i % CHART_COLORS.length] : undefined)
42
+
43
+ /**
44
+ * Sortable numeric value of a cell. Human-written table cells are rarely
45
+ * plain numbers, so the sort accepts the usual decorations:
46
+ * `1,234` / `1,234`(千分位)、`1.2k`/`3M`/`5b`、`3.5万`/`2亿`、`0.3%`、
47
+ * `¥99`/`$12`。A cell that cannot be read as a number returns NaN and the
48
+ * row falls back to the text comparison — mixed columns sort deterministically
49
+ * (numbers first, then text).
50
+ */
51
+ export function parseSortableNumber(v: unknown): number {
52
+ if (typeof v === 'number') return Number.isFinite(v) ? v : NaN
53
+ if (typeof v !== 'string') return NaN
54
+ let s = v.trim()
55
+ if (s === '') return NaN
56
+ s = s.replace(/^[¥$€£]/, '')
57
+ const pct = s.endsWith('%')
58
+ if (pct) s = s.slice(0, -1)
59
+ // 中文单位在前:3.5万 → 35000、2亿 → 200000000;再是 k/m/b 后缀。
60
+ let mult = 1
61
+ if (s.endsWith('万')) { mult = 10_000; s = s.slice(0, -1) }
62
+ else if (s.endsWith('亿')) { mult = 100_000_000; s = s.slice(0, -1) }
63
+ else if (/[kmb]$/i.test(s)) {
64
+ const unit = s.slice(-1).toLowerCase()
65
+ mult = unit === 'k' ? 1e3 : unit === 'm' ? 1e6 : 1e9
66
+ s = s.slice(0, -1)
67
+ }
68
+ s = s.replace(/[,,\s]/g, '')
69
+ const n = Number(s)
70
+ if (!Number.isFinite(n)) return NaN
71
+ return n * mult
72
+ }
73
+
74
+ /** A column is numeric when every non-empty cell parses to a finite number —
75
+ * those columns right-align with tabular numerals (the table's data voice). */
76
+ function numericColumns(rows: GenuiTable['rows'], nCols: number): boolean[] {
77
+ return Array.from({ length: nCols }, (_, j) => {
78
+ let any = false
79
+ for (const row of rows) {
80
+ const cell = row[j]
81
+ if (cell === undefined || cell === null || cell === '') continue
82
+ if (!Number.isFinite(parseSortableNumber(cell))) return false
83
+ any = true
84
+ }
85
+ return any
86
+ })
87
+ }
88
+
89
+ /**
90
+ * Does this cell carry real line breaks? Table cells default to `nowrap` (the
91
+ * data voice), which also collapses the leading whitespace of a pasted code
92
+ * block — indentation is lost and the snippet no longer runs. Cells that do
93
+ * contain a line break get `pre-line` (see `.tdMultiline`), so the line
94
+ * structure survives and the text still copies back as multiple lines.
95
+ */
96
+ function hasLineBreak(value: string | number): boolean {
97
+ return typeof value === 'string' && /[\n\r]/.test(value)
98
+ }
99
+
100
+ /**
101
+ * Is this cell code rather than prose? Only then is leading indentation
102
+ * significant (`pre-wrap`), while a prose line break stays `pre-line` so its
103
+ * surrounding spaces collapse exactly like the rest of the UI.
104
+ */
105
+ function isCodeCell(value: string | number): boolean {
106
+ if (typeof value !== 'string') return false
107
+ return /(^|\n)[ \t]/.test(value) || value.includes('```')
108
+ }
109
+
110
+ /** The whitespace class a multi-line cell needs, or undefined for single-line. */
111
+ function cellWrapClass(value: string | number): string | undefined {
112
+ if (!hasLineBreak(value)) return undefined
113
+ return isCodeCell(value) ? css.tdCode : css.tdMultiline
114
+ }
115
+
116
+ /** Signed cell text (`+12.4%`, `-3`, `−2.1k`) reads as a delta without any
117
+ * new spec field — the renderer classifies the string. */
118
+ function deltaTone(value: unknown): 'up' | 'down' | null {
119
+ if (typeof value !== 'string') return null
120
+ const s = value.trim()
121
+ if (!/^[+][\s]*[\d.]/.test(s) && !/^[-−][\s]*[\d.]/.test(s)) return null
122
+ return s.startsWith('+') ? 'up' : 'down'
123
+ }
124
+
125
+ /** `types: ["spark"]` cell: comma/space separated numbers drawn as a micro
126
+ * trend line (area wash + end dot, same geometry as stat.spark). */
127
+ function CellSpark({ cell }: { cell: string | number }) {
128
+ const values = String(cell).split(/[\s,;]+/).map(Number).filter(Number.isFinite)
129
+ if (values.length < 2) return <>{renderInline(String(cell), false)}</>
130
+ const W = 88
131
+ const H = 22
132
+ const pad = 2
133
+ const min = Math.min(...values)
134
+ const max = Math.max(...values)
135
+ const span = max - min || 1
136
+ const step = (W - pad * 2) / (values.length - 1)
137
+ const coords = values.map((v, i) => [pad + i * step, H - pad - ((v - min) / span) * (H - pad * 2)] as const)
138
+ const points = coords.map(([px, py]) => `${px.toFixed(1)},${py.toFixed(1)}`).join(' ')
139
+ const last = coords[coords.length - 1]!
140
+ const area = `M ${pad},${H - pad} L ${points.split(' ').join(' L ')} L ${last[0].toFixed(1)},${H - pad} Z`
141
+ return (
142
+ <svg className={css.cellSpark} viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" aria-hidden="true">
143
+ <path d={area} fill="var(--dsl-g-accent)" opacity="0.14" />
144
+ <polyline points={points} fill="none" stroke="var(--dsl-g-accent)" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" vectorEffect="non-scaling-stroke" />
145
+ <path d={`M ${last[0].toFixed(1)} ${last[1].toFixed(1)} L ${last[0].toFixed(1)} ${last[1].toFixed(1)}`} stroke="var(--dsl-g-accent)" strokeWidth={4} strokeLinecap="round" vectorEffect="non-scaling-stroke" fill="none" />
146
+ </svg>
147
+ )
148
+ }
149
+
150
+ /** `types: ["ring"]` cell: a 28px ring gauge read as 0-100. */
151
+ function CellRing({ cell }: { cell: string | number }) {
152
+ const n = parseSortableNumber(cell)
153
+ const pct = Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : 0
154
+ const R = 11
155
+ const C = 2 * Math.PI * R
156
+ return (
157
+ <span className={css.cellRing}>
158
+ <svg width={28} height={28} viewBox="0 0 28 28" aria-hidden="true">
159
+ <circle cx={14} cy={14} r={R} fill="none" strokeWidth={4} className={css.ringTrack} />
160
+ <circle
161
+ cx={14} cy={14} r={R} fill="none" strokeWidth={4} strokeLinecap="round" className={css.ringFill}
162
+ strokeDasharray={`${(pct / 100) * C} ${C}`} transform="rotate(-90 14 14)"
163
+ />
164
+ </svg>
165
+ <span className={css.cellRingText}>{renderInline(String(cell), false)}</span>
166
+ </span>
167
+ )
168
+ }
169
+
170
+ /** Markdown table text for the 复制 Markdown chip (pipes escaped). */
171
+ export function tableToMarkdown(columns: string[], rows: Array<Array<string | number>>): string {
172
+ const escape = (v: unknown): string => String(v ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ')
173
+ const head = `| ${columns.map(escape).join(' | ')} |`
174
+ const rule = `| ${columns.map(() => '---').join(' | ')} |`
175
+ const body = rows.map(row => `| ${columns.map((_c, i) => escape(row[i])).join(' | ')} |`)
176
+ return [head, rule, ...body].join('\n')
177
+ }
178
+
179
+ /** RFC 4180 CSV text for the 复制 CSV chip. */
180
+ export function tableToCsv(rows: Array<Array<string | number>>): string {
181
+ const cell = (v: unknown): string => {
182
+ const s = String(v ?? '')
183
+ return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
184
+ }
185
+ return rows.map(row => row.map(cell).join(',')).join('\n')
186
+ }
187
+
188
+ /** Copy chips above a table (`table.export`). Local clipboard only — no action,
189
+ * no round trip; the label confirms for a moment and then resets. */
190
+ function TableExportChips({ columns, rows }: { columns: string[]; rows: Array<Array<string | number>> }) {
191
+ useT()
192
+ const [copied, setCopied] = useState<'md' | 'csv' | null>(null)
193
+ const copy = (kind: 'md' | 'csv'): void => {
194
+ const text = kind === 'md' ? tableToMarkdown(columns, rows) : tableToCsv(rows)
195
+ void writeClipboard(text).then(ok => {
196
+ if (!ok) return
197
+ setCopied(kind)
198
+ window.setTimeout(() => setCopied(null), 1200)
199
+ })
200
+ }
201
+ return (
202
+ <div className={css.tableTools}>
203
+ <button type="button" className={css.tableTool} onClick={() => copy('md')}>
204
+ {copied === 'md' ? tr('label.copiedDone') : tr('block.copyMarkdown')}
205
+ </button>
206
+ <button type="button" className={css.tableTool} onClick={() => copy('csv')}>
207
+ {copied === 'csv' ? tr('label.copiedDone') : tr('block.copyCsv')}
208
+ </button>
209
+ </div>
210
+ )
211
+ }
212
+
213
+ /** `types: ["bar"]` cell: an inline 0-100 track with the value printed on it. */
214
+ function CellBar({ cell }: { cell: string | number }) {
215
+ const n = parseSortableNumber(cell)
216
+ const pct = Number.isFinite(n) ? Math.max(0, Math.min(100, n)) : 0
217
+ return (
218
+ <span className={css.cellBar}>
219
+ <span className={css.cellBarFill} style={{ width: `${pct}%` }} />
220
+ <span className={css.cellBarText}>{renderInline(String(cell), false)}</span>
221
+ </span>
222
+ )
223
+ }
224
+
225
+ export const TableNode = memo(function TableNode({ node, renderDetail, filterValue, sortValue }: {
226
+ node: GenuiTable
227
+ /** Live value of `node.filter`: substring-match rows locally. */
228
+ filterValue?: string | undefined
229
+ /** Live value of `node.sortField`: a column header to sort by. */
230
+ sortValue?: string | undefined
231
+ /** Renders a row's detail nodes. Supplied by render-node so the table never
232
+ * has to import the renderer back (import cycle). */
233
+ renderDetail?: ((items: NonNullable<GenuiTable['details']>[number] & object[]) => ReactNode) | undefined
234
+ }) {
235
+ useT()
236
+ const columns = node.columns.slice(0, GENUI_LIMITS.maxTableCols)
237
+ const rows = tableRowsForDetails<GenuiTable['rows'][number]>(node)
238
+ const types = node.types ?? []
239
+ const [sort, setSort] = useState<{ col: number; dir: 1 | -1 } | null>(null)
240
+ const [collapsed, setCollapsed] = useState<ReadonlySet<number>>(() => new Set())
241
+ const [expanded, setExpanded] = useState<ReadonlySet<number>>(() => new Set())
242
+
243
+ const compare = (a: GenuiTable['rows'][number], b: GenuiTable['rows'][number], col: number, dir: 1 | -1): number => {
244
+ const an = parseSortableNumber(a[col])
245
+ const bn = parseSortableNumber(b[col])
246
+ if (Number.isFinite(an) && Number.isFinite(bn) && an !== bn) return (an - bn) * dir
247
+ if (Number.isFinite(an) !== Number.isFinite(bn)) return Number.isFinite(an) ? -dir : dir
248
+ const as = String(a[col] ?? '')
249
+ const bs = String(b[col] ?? '')
250
+ return (as < bs ? -1 : as > bs ? 1 : 0) * dir
251
+ }
252
+
253
+ // Group header rows: with `types[0] === 'group'`, a row whose first cell is
254
+ // filled and every other cell empty opens a section. Data rows after it are
255
+ // its CHILDREN — indented, counted, and collapsible — so the relationship is
256
+ // unmistakable instead of "one more row at the same level".
257
+ const isGroupRow = (row: GenuiTable['rows'][number]): boolean => isTableGroupHeaderRow(row, types)
258
+
259
+ // Local filtering (bound control): the model ships the full data set once and
260
+ // the reader narrows it live — no round trip, no re-generation.
261
+ const needle = filterValue?.trim().toLowerCase()
262
+ const filtered = needle === undefined || needle === ''
263
+ ? rows.map((row, index) => ({ row, index }))
264
+ : rows.map((row, index) => ({ row, index })).filter(({ row }) => {
265
+ const cells = node.filterColumn === undefined
266
+ ? row
267
+ : [row[node.filterColumn]]
268
+ return cells.some(cell => String(cell ?? '').toLowerCase().includes(needle))
269
+ })
270
+ const visibleRows = filtered.map(entry => entry.row)
271
+ const hiddenCount = rows.length - visibleRows.length
272
+
273
+ interface Section { header: { row: GenuiTable['rows'][number]; index: number } | null; children: Array<{ row: GenuiTable['rows'][number]; index: number }> }
274
+ const sections: Section[] = []
275
+ visibleRows.forEach((row, index) => {
276
+ if (isGroupRow(row)) { sections.push({ header: { row, index }, children: [] }); return }
277
+ if (sections.length === 0 || sections[sections.length - 1]!.header === null) {
278
+ if (sections.length === 0) sections.push({ header: null, children: [] })
279
+ }
280
+ sections[sections.length - 1]!.children.push({ row, index })
281
+ })
282
+
283
+ // Sorting keeps sections intact: each section's children sort among
284
+ // themselves, so a grouped table can never scramble its own structure.
285
+ // `sortField` is a select whose value is a column header: apply it as the
286
+ // active sort (a click on the header still overrides it).
287
+ const boundSortCol = sortValue === undefined ? -1 : columns.indexOf(sortValue)
288
+ const effectiveSort = sort !== null ? sort : (boundSortCol >= 0 ? { col: boundSortCol, dir: 1 as const } : null)
289
+
290
+ const sortedSections = sections.map(section => ({
291
+ header: section.header,
292
+ children: effectiveSort === null
293
+ ? section.children
294
+ : [...section.children].sort((a, b) => compare(a.row, b.row, effectiveSort.col, effectiveSort.dir)),
295
+ }))
296
+
297
+ const numeric = numericColumns(visibleRows, columns.length)
298
+ const toggleSection = (index: number): void => {
299
+ setCollapsed(prev => {
300
+ const next = new Set(prev)
301
+ if (next.has(index)) next.delete(index)
302
+ else next.add(index)
303
+ return next
304
+ })
305
+ }
306
+ const toggleDetail = (index: number): void => {
307
+ setExpanded(prev => {
308
+ const next = new Set(prev)
309
+ if (next.has(index)) next.delete(index)
310
+ else next.add(index)
311
+ return next
312
+ })
313
+ }
314
+ const clickHeader = (i: number): void => {
315
+ setSort(prev => prev !== null && prev.col === i
316
+ ? prev.dir === 1 ? { col: i, dir: -1 } : null
317
+ : { col: i, dir: 1 })
318
+ }
319
+ // Optional 合计 footer: sums every numeric column (section headers excluded).
320
+ const totals = columns.map((_c, j) => {
321
+ if (!numeric[j]) return null
322
+ let sum = 0
323
+ for (const row of visibleRows) {
324
+ if (isGroupRow(row)) continue
325
+ const n = parseSortableNumber(row[j])
326
+ if (Number.isFinite(n)) sum += n
327
+ }
328
+ return sum
329
+ })
330
+ const hasTotals = node.total === true && totals.some(t => t !== null)
331
+ const formatTotal = (n: number): string =>
332
+ Number.isInteger(n) ? n.toLocaleString('en-US') : String(Math.round(n * 100) / 100)
333
+
334
+ const renderCell = (cell: string | number, j: number, rowIndex: number): ReactNode => {
335
+ const type = types[j]
336
+ const wrap = cellWrapClass(cell)
337
+ const tone = type === 'delta'
338
+ ? (String(cell).trim().startsWith('-') ? 'down' : 'up')
339
+ : deltaTone(cell)
340
+ return (
341
+ <td
342
+ key={j}
343
+ className={[numeric[j] || type === 'num' ? css.tdNum : undefined, wrap]
344
+ .filter(part => part !== undefined)
345
+ .join(' ') || undefined}
346
+ >
347
+ {type === 'badge'
348
+ ? <span className={css.cellBadge}>{renderInline(String(cell), false)}</span>
349
+ : type === 'bar'
350
+ ? <CellBar cell={cell} />
351
+ : type === 'spark'
352
+ ? <CellSpark cell={cell} />
353
+ : type === 'ring'
354
+ ? <CellRing cell={cell} />
355
+ : type === 'index'
356
+ ? <span className={css.cellIndex}>{rowIndex + 1}</span>
357
+ : tone === null
358
+ // Format displayed text without changing sorting or exported data.
359
+ ? renderInline(String(cell), false)
360
+ : <span className={`${css.tdDelta} ${tone === 'up' ? css.tdDeltaUp : css.tdDeltaDown}`}>{renderInline(String(cell), false)}</span>}
361
+ </td>
362
+ )
363
+ }
364
+
365
+ return (
366
+ <div className={css.tableWrap}>
367
+ {node.export === true && <TableExportChips columns={columns} rows={rows} />}
368
+ <table className={css.table}>
369
+ <thead>
370
+ <tr>
371
+ {columns.map((c, i) => (
372
+ <th
373
+ key={i}
374
+ className={[numeric[i] ? css.thNum : undefined, cellWrapClass(c)]
375
+ .filter(part => part !== undefined)
376
+ .join(' ') || undefined}
377
+ aria-sort={sort !== null && sort.col === i ? (sort.dir === 1 ? 'ascending' : 'descending') : 'none'}
378
+ >
379
+ <button type="button" className={css.thSort} onClick={() => clickHeader(i)}>
380
+ {renderInline(c, false)}
381
+ {sort !== null && sort.col === i && <span className={css.thSortMark} aria-hidden>{sort.dir === 1 ? ' ▲' : ' ▼'}</span>}
382
+ </button>
383
+ </th>
384
+ ))}
385
+ </tr>
386
+ </thead>
387
+ <tbody>
388
+ {sortedSections.map((section, si) => {
389
+ const headerIndex = section.header?.index ?? si
390
+ const isCollapsed = collapsed.has(headerIndex)
391
+ return (
392
+ <Fragment key={section.header === null ? `s-${si}` : `g-${section.header.index}`}>
393
+ {section.header !== null && (
394
+ <tr className={css.groupRow}>
395
+ <td colSpan={columns.length} className={cellWrapClass(String(section.header.row[0]))}>
396
+ <button
397
+ type="button"
398
+ className={css.groupToggle}
399
+ aria-expanded={!isCollapsed}
400
+ onClick={() => toggleSection(headerIndex)}
401
+ >
402
+ <span className={css.groupChevron} aria-hidden>{isCollapsed ? '▸' : '▾'}</span>
403
+ {renderInline(String(section.header.row[0]), false)}
404
+ <span className={css.groupCount}>{section.children.length}</span>
405
+ </button>
406
+ </td>
407
+ </tr>
408
+ )}
409
+ {!isCollapsed && section.children.map(child => {
410
+ const detail = node.details?.[child.index] ?? null
411
+ const open = expanded.has(child.index)
412
+ return (
413
+ <Fragment key={child.index}>
414
+ <tr className={section.header === null ? undefined : css.groupChild}>
415
+ {child.row.slice(0, columns.length).map((cell, j) => (
416
+ j === 0 && detail !== null
417
+ ? (
418
+ <td key={j} className={css.detailCell}>
419
+ <button
420
+ type="button"
421
+ className={css.detailToggle}
422
+ aria-expanded={open}
423
+ onClick={() => toggleDetail(child.index)}
424
+ >
425
+ <span className={css.detailChevron} data-open={open} aria-hidden>▸</span>
426
+ {renderInline(String(cell), false)}
427
+ </button>
428
+ </td>
429
+ )
430
+ : renderCell(cell, j, child.index)
431
+ ))}
432
+ </tr>
433
+ {open && detail !== null && (
434
+ <tr className={css.detailRow}>
435
+ <td colSpan={columns.length}>
436
+ <div className={css.detailBody}>
437
+ {renderDetail === undefined ? null : renderDetail(detail)}
438
+ </div>
439
+ </td>
440
+ </tr>
441
+ )}
442
+ </Fragment>
443
+ )
444
+ })}
445
+ </Fragment>
446
+ )
447
+ })}
448
+ </tbody>
449
+ {hiddenCount > 0 && (
450
+ <tfoot>
451
+ <tr className={css.filterRow}>
452
+ <td colSpan={columns.length}>{tr('block.filteredRows', { visible: visibleRows.length, total: rows.length })}</td>
453
+ </tr>
454
+ </tfoot>
455
+ )}
456
+ {hasTotals && (
457
+ <tfoot>
458
+ <tr>
459
+ {columns.map((_c, j) => (
460
+ <td key={j} className={numeric[j] ? css.tdNum : undefined}>
461
+ {j === 0 ? tr('block.total') : totals[j] === null ? '' : formatTotal(totals[j]!)}
462
+ </td>
463
+ ))}
464
+ </tr>
465
+ </tfoot>
466
+ )}
467
+ </table>
468
+ </div>
469
+ )
470
+ })
471
+
472
+ /** One tooltip line: label on the left, value on the right. */
473
+ type TipRow = [string, string]
474
+
475
+ interface TipState { x: number; y: number; rows: TipRow[] }
476
+
477
+ /**
478
+ * Instant, self-drawn hover readout. The browser's native `title` takes about
479
+ * a second to appear and cannot show a stacked breakdown, which is exactly
480
+ * what a stacked bar needs ("hover 上去要会显示各自部分的具体数值").
481
+ */
482
+ function useChartTip(): {
483
+ tip: TipState | null
484
+ show: (event: ReactMouseEvent<Element>, rows: TipRow[]) => void
485
+ hide: () => void
486
+ } {
487
+ const [tip, setTip] = useState<TipState | null>(null)
488
+ const show = useCallback((event: ReactMouseEvent<Element>, rows: TipRow[]) => {
489
+ const target = event.currentTarget as Element
490
+ const host = target.closest('[data-genui-chart], [data-genui-line], [data-genui-donut]')
491
+ if (host === null) return
492
+ const hostRect = host.getBoundingClientRect()
493
+ const rect = target.getBoundingClientRect()
494
+ setTip({
495
+ x: rect.left - hostRect.left + rect.width / 2,
496
+ y: rect.top - hostRect.top,
497
+ rows,
498
+ })
499
+ }, [])
500
+ const hide = useCallback(() => setTip(null), [])
501
+ return { tip, show, hide }
502
+ }
503
+
504
+ function ChartTip({ tip }: { tip: TipState | null }) {
505
+ if (tip === null) return null
506
+ return (
507
+ <div className={css.chartTip} style={{ left: `${tip.x}px`, top: `${tip.y}px` }} role="tooltip">
508
+ {tip.rows.map(([label, value], i) => (
509
+ <span key={`${label}-${i}`} className={css.chartTipRow}>
510
+ <span>{renderInline(label)}</span>
511
+ <span className={css.chartTipValue}>{renderInline(String(value))}</span>
512
+ </span>
513
+ ))}
514
+ </div>
515
+ )
516
+ }
517
+
518
+ /** Measured plot width. Charts draw in CSS pixels: 1 SVG unit = 1px, so axis
519
+ * text keeps its designed size at every container width. */
520
+ function useMeasuredWidth(): [RefObject<HTMLDivElement>, number] {
521
+ const ref = useRef<HTMLDivElement>(null)
522
+ const [width, setWidth] = useState(560)
523
+ useLayoutEffect(() => {
524
+ const el = ref.current
525
+ if (el === null) return
526
+ const measure = (): void => {
527
+ const next = el.clientWidth
528
+ if (next > 0) setWidth(next)
529
+ }
530
+ measure()
531
+ if (typeof ResizeObserver === 'undefined') return
532
+ const observer = new ResizeObserver(measure)
533
+ observer.observe(el)
534
+ return () => observer.disconnect()
535
+ }, [])
536
+ return [ref, width]
537
+ }
538
+
539
+ /** Axis ticks on 1/2/5×10^n steps covering [min, max] inclusively. */
540
+ function niceTicks(min: number, max: number, target = 4): number[] {
541
+ const lo = Math.min(min, 0)
542
+ const hi = Math.max(max, 0)
543
+ if (lo === hi) return [0, 1]
544
+ const raw = (hi - lo) / Math.max(target, 1)
545
+ const magnitude = Math.pow(10, Math.floor(Math.log10(Math.max(raw, Number.MIN_VALUE))))
546
+ const normalized = raw / magnitude
547
+ const step = (normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10) * magnitude
548
+ const start = Math.floor(lo / step) * step
549
+ const end = Math.ceil(hi / step) * step
550
+ const ticks: number[] = []
551
+ for (let t = start; t <= end + step / 2; t += step) ticks.push(Math.abs(t) < step / 1e6 ? 0 : t)
552
+ return ticks
553
+ }
554
+
555
+ /** Compact tick text: 1200 → 1.2k, 0.5 → 0.5, integers bare. */
556
+ function formatTick(t: number): string {
557
+ const abs = Math.abs(t)
558
+ if (abs >= 1e9) return `${(t / 1e9).toFixed(abs % 1e9 === 0 ? 0 : 1)}b`
559
+ if (abs >= 1e6) return `${(t / 1e6).toFixed(abs % 1e6 === 0 ? 0 : 1)}m`
560
+ if (abs >= 1000) return `${(t / 1000).toFixed(abs % 1000 === 0 ? 0 : 1)}k`
561
+ if (Number.isInteger(t)) return String(t)
562
+ return String(Math.round(t * 100) / 100)
563
+ }
564
+
565
+ /** 计算数字用普通或指数形式表示时所需的小数位数。 */
566
+ export function fractionDigits(value: number): number {
567
+ if (!Number.isFinite(value)) return 0
568
+ const [coefficient, exponentText] = String(value).toLowerCase().split('e')
569
+ const decimalDigits = coefficient!.split('.')[1]?.length ?? 0
570
+ const exponent = exponentText === undefined ? 0 : Number(exponentText)
571
+ return Math.max(decimalDigits - exponent, 0)
572
+ }
573
+
574
+ /** 按参与计算的原始数值精度格式化图表合计。 */
575
+ export function formatChartValue(value: number, maxFractionDigits: number): string {
576
+ if (!Number.isFinite(value)) return String(value)
577
+ if (Math.abs(value) >= 1e21 || maxFractionDigits > 100) return String(value)
578
+ const formatted = value.toFixed(maxFractionDigits)
579
+ return formatted.includes('.') ? formatted.replace(/\.?0+$/, '') : formatted
580
+ }
581
+
582
+ /** Shared y-axis gutter: ticks positioned against the same percentage scale
583
+ * the plot uses, so labels line up with the gridlines. */
584
+ function YAxis({ ticks, lo, span }: { ticks: number[]; lo: number; span: number }) {
585
+ return (
586
+ <div className={css.chartYAxis} style={{ height: 160 }}>
587
+ {ticks.map(t => (
588
+ <span key={t} className={css.chartYTick} style={{ bottom: `${((t - lo) / span) * 100}%` }}>
589
+ {formatTick(t)}
590
+ </span>
591
+ ))}
592
+ </div>
593
+ )
594
+ }
595
+
596
+ /** Chart: bars (default), line (trend), or donut (share); multi-series bars via `series`. */
597
+ export const ChartNode = memo(function ChartNode({ chart, filterValue }: {
598
+ chart: GenuiChart
599
+ /** Live value of the control bound via `chart.filter`; keeps matching
600
+ * categories only (label substring), so a chart is explorable locally. */
601
+ filterValue?: string | undefined
602
+ }) {
603
+ const filtered = useMemo(() => applyChartFilter(chart, filterValue), [chart, filterValue])
604
+ const kind = filtered.kind ?? 'bars'
605
+ if (kind === 'donut') return <DonutNode chart={filtered} />
606
+ if (kind === 'line') return <LineChartNode chart={filtered} />
607
+ return <BarsNode chart={filtered} />
608
+ })
609
+
610
+ /** Keep the categories whose label matches the bound filter (case-insensitive).
611
+ * Bars/donut filter `data`, line filters each series' points. */
612
+ function applyChartFilter(chart: GenuiChart, filterValue: string | undefined): GenuiChart {
613
+ const needle = filterValue?.trim().toLowerCase()
614
+ if (needle === undefined || needle === '') return chart
615
+ const keep = (datum: { label: string }): boolean => datum.label.toLowerCase().includes(needle)
616
+ const data = chart.data.filter(keep)
617
+ if (chart.series === undefined) return data.length === chart.data.length ? chart : { ...chart, data }
618
+ const series = chart.series.map(entry => ({ ...entry, data: entry.data.filter(keep) }))
619
+ return { ...chart, data, series }
620
+ }
621
+
622
+ /** Bars: one column per datum (grouped bars when `series` is present).
623
+ * Single-series bars render against a true zero line, so negative values
624
+ * draw downward instead of clamping to zero height. */
625
+ export const BarsNode = memo(function BarsNode({ chart }: { chart: GenuiChart }) {
626
+ useT()
627
+ const { tip, show, hide } = useChartTip()
628
+ const grouped = chart.series !== undefined ? chart.series.slice(0, GENUI_LIMITS.maxPlotSeries) : undefined
629
+ const isGrouped = grouped !== undefined && grouped.length > 0
630
+ const data = chart.data.slice(0, GENUI_LIMITS.maxChartPoints)
631
+ const labels = isGrouped ? grouped[0]!.data.map(d => d.label) : data.map(d => d.label)
632
+ const seriesValues = isGrouped
633
+ ? grouped.map(s => s.data.map(d => Number(d.value) || 0))
634
+ : [data.map(d => Number(d.value) || 0)]
635
+ const colors = seriesValues.map((_values, si) =>
636
+ seriesColor(si, seriesValues.length, isGrouped ? grouped[si]?.color : undefined, chart.palette) ?? 'var(--dsw-alias-state-business-primary, #4f8ef7)')
637
+ const flat = seriesValues.flat()
638
+ const showValues = labels.length <= 12
639
+ const stacked = chart.stacked === true && isGrouped
640
+ const categoryTotals = labels.map((_l, i) => seriesValues.reduce((sum, values) => sum + Math.max(0, values[i] ?? 0), 0))
641
+ const categoryFractionDigits = labels.map((_label, i) => Math.max(...seriesValues.map(values => fractionDigits(values[i] ?? 0)), 0))
642
+ const positiveMax = stacked ? Math.max(...categoryTotals, 0) : Math.max(...flat, 0)
643
+
644
+ // Horizontal: label column + one track per series. The axis is always
645
+ // 0..max (a horizontal track has no zero line to cross).
646
+ if (chart.horizontal === true) {
647
+ const scale = Math.max(positiveMax, 1)
648
+ const legend = isGrouped
649
+ ? (
650
+ <div className={css.chartLegend}>
651
+ {grouped.map((entry, si) => (
652
+ <span key={si} className={css.legendItem}>
653
+ <span className={css.legendSwatch} style={{ background: colors[si] }} />
654
+ {renderInline(entry.label)}
655
+ </span>
656
+ ))}
657
+ </div>
658
+ )
659
+ : null
660
+ return (
661
+ <div className={css.chart} data-genui-chart="bars" role="img" aria-label={tr('block.chart.barsAria', { count: labels.length })} onMouseLeave={hide}>
662
+ <div className={css.hbars}>
663
+ {labels.map((label, i) => (
664
+ <div key={i} className={css.hbarRow}>
665
+ <span className={css.hbarLabel} title={label}>{renderInline(label)}</span>
666
+ <div className={css.hbarTracks}>
667
+ {stacked
668
+ ? (
669
+ <div className={css.hbarTrack} title={`${label}: ${formatChartValue(categoryTotals[i] ?? 0, categoryFractionDigits[i] ?? 0)}`}>
670
+ {seriesValues.map((values, si) => {
671
+ const v = Math.max(0, values[i] ?? 0)
672
+ const total = categoryTotals[i] ?? 0
673
+ const width = total === 0 ? 0 : (v / total) * Math.max(0, Math.min(100, (total / scale) * 100))
674
+ return (
675
+ <div
676
+ key={si}
677
+ className={css.hbarSeg}
678
+ style={{ width: `${width}%`, background: colors[si] }}
679
+ onMouseEnter={event => show(event, [[grouped[si]!.label, String(v)], [tr('block.total'), formatChartValue(total, categoryFractionDigits[i] ?? 0)]])}
680
+ onMouseMove={event => show(event, [[grouped[si]!.label, String(v)], [tr('block.total'), formatChartValue(total, categoryFractionDigits[i] ?? 0)]])}
681
+ />
682
+ )
683
+ })}
684
+ </div>
685
+ )
686
+ : seriesValues.map((values, si) => {
687
+ const v = values[i] ?? 0
688
+ const width = Math.max(0, Math.min(100, (Math.max(0, v) / scale) * 100))
689
+ return (
690
+ <div key={si} className={css.hbarTrack}>
691
+ <div
692
+ className={css.hbarFill}
693
+ style={{ width: `${width}%`, background: colors[si] }}
694
+ onMouseEnter={event => show(event, isGrouped ? [[grouped[si]!.label, String(v)], [tr('block.total'), formatChartValue(categoryTotals[i] ?? 0, categoryFractionDigits[i] ?? 0)]] : [[label, String(v)]])}
695
+ onMouseMove={event => show(event, isGrouped ? [[grouped[si]!.label, String(v)], [tr('block.total'), formatChartValue(categoryTotals[i] ?? 0, categoryFractionDigits[i] ?? 0)]] : [[label, String(v)]])}
696
+ />
697
+ </div>
698
+ )
699
+ })}
700
+ </div>
701
+ {showValues && (
702
+ <span className={css.hbarValue}>
703
+ {isGrouped ? formatChartValue(categoryTotals[i] ?? 0, categoryFractionDigits[i] ?? 0) : String(data[i]?.value ?? '')}
704
+ </span>
705
+ )}
706
+ </div>
707
+ ))}
708
+ </div>
709
+ {legend}
710
+ <ChartTip tip={tip} />
711
+ </div>
712
+ )
713
+ }
714
+
715
+ // Vertical: grouped bars clamp negatives (the flex layout stacks upward), so
716
+ // the axis starts at zero for that shape; single-series bars render against
717
+ // a true zero line and draw negatives downward.
718
+ const ticks = niceTicks(isGrouped ? 0 : Math.min(...flat, 0), positiveMax, 4)
719
+ const lo = ticks[0]!
720
+ const hi = ticks[ticks.length - 1]!
721
+ const span = hi - lo || 1
722
+ const pct = (v: number): number => ((v - lo) / span) * 100
723
+ const zero = pct(0)
724
+ const summary = tr('block.chart.barsSummary', { count: labels.length, max: formatTick(Math.max(...flat, 0)) })
725
+ return (
726
+ <div className={css.chart} data-genui-chart="bars" role="img" aria-label={summary} onMouseLeave={hide}>
727
+ <ChartTip tip={tip} />
728
+ <div className={css.chartBody}>
729
+ <YAxis ticks={ticks} lo={lo} span={span} />
730
+ <div className={css.chartPlot}>
731
+ {ticks.map(t => (
732
+ <span key={t} className={t === 0 ? css.baseline : css.gridline} style={{ bottom: `${pct(t)}%` }} />
733
+ ))}
734
+ {labels.map((label, i) => (
735
+ <div key={i} className={css.barCol}>
736
+ {stacked
737
+ ? (
738
+ <>
739
+ {showValues && (
740
+ <span className={css.barValue} style={{ bottom: `calc(${pct(categoryTotals[i] ?? 0)}% + 4px)` }}>
741
+ {formatChartValue(categoryTotals[i] ?? 0, categoryFractionDigits[i] ?? 0)}
742
+ </span>
743
+ )}
744
+ <div className={css.stack} style={{ height: `${Math.max(0, pct(categoryTotals[i] ?? 0))}%` }}>
745
+ {grouped.map((entry, si) => {
746
+ const datum = entry.data[i]
747
+ const raw = datum === undefined ? 0 : Number(datum.value) || 0
748
+ const v = Math.max(0, raw)
749
+ const total = categoryTotals[i] ?? 0
750
+ const segHeight = total === 0 ? 0 : (v / total) * pct(total)
751
+ const rows: TipRow[] = [[entry.label, String(raw)], [tr('block.total'), formatChartValue(total, categoryFractionDigits[i] ?? 0)]]
752
+ return (
753
+ <div
754
+ key={si}
755
+ className={css.stackSeg}
756
+ style={{ height: total === 0 ? '0%' : `${(v / total) * 100}%`, background: colors[si] }}
757
+ onMouseEnter={event => show(event, rows)}
758
+ onMouseMove={event => show(event, rows)}
759
+ >
760
+ {segHeight >= 11 && <span className={css.stackValue}>{raw}</span>}
761
+ </div>
762
+ )
763
+ })}
764
+ </div>
765
+ </>
766
+ )
767
+ : isGrouped
768
+ ? (
769
+ <div className={css.groupedBars}>
770
+ {grouped.map((entry, si) => {
771
+ const datum = entry.data[i]
772
+ const v = datum === undefined ? 0 : Number(datum.value) || 0
773
+ return (
774
+ <div key={si} className={css.groupedBar}>
775
+ {showValues && <span className={css.groupValue}>{datum === undefined ? '' : String(datum.value)}</span>}
776
+ <div
777
+ className={css.groupedFill}
778
+ style={{
779
+ height: `${Math.max(0, pct(Math.max(0, v)))}%`,
780
+ background: colors[si],
781
+ }}
782
+ onMouseEnter={event => show(event, [[entry.label, String(datum?.value ?? '')], [tr('block.total'), formatChartValue(categoryTotals[i] ?? 0, categoryFractionDigits[i] ?? 0)]])}
783
+ onMouseMove={event => show(event, [[entry.label, String(datum?.value ?? '')], [tr('block.total'), formatChartValue(categoryTotals[i] ?? 0, categoryFractionDigits[i] ?? 0)]])}
784
+ />
785
+ </div>
786
+ )
787
+ })}
788
+ </div>
789
+ )
790
+ : (() => {
791
+ const v = seriesValues[0]![i] ?? 0
792
+ const top = Math.max(pct(v), zero)
793
+ const bottom = Math.min(pct(v), zero)
794
+ return (
795
+ <>
796
+ {showValues && (
797
+ <span className={css.barValue} style={{ bottom: `calc(${top}% + 4px)` }}>{String(data[i]?.value ?? '')}</span>
798
+ )}
799
+ <div
800
+ className={css.barFill}
801
+ style={{
802
+ bottom: `${bottom}%`,
803
+ height: `${Math.max(top - bottom, 0.6)}%`,
804
+ ...(v < 0 ? { borderRadius: '0 0 5px 5px' } : {}),
805
+ ...(data[i]?.color !== undefined ? { background: data[i]!.color } : {}),
806
+ }}
807
+ onMouseEnter={event => show(event, [[label, String(data[i]?.value ?? '')]])}
808
+ onMouseMove={event => show(event, [[label, String(data[i]?.value ?? '')]])}
809
+ />
810
+ </>
811
+ )
812
+ })()}
813
+ </div>
814
+ ))}
815
+ </div>
816
+ </div>
817
+ <div className={css.chartLabels}>
818
+ {labels.map((label, i) => <span key={`${label}-${i}`} className={css.barLabel}>{renderInline(label)}</span>)}
819
+ </div>
820
+ {isGrouped && (
821
+ <div className={css.chartLegend}>
822
+ {grouped.map((entry, si) => (
823
+ <span key={si} className={css.legendItem}>
824
+ <span className={css.legendSwatch} style={{ background: colors[si] }} />
825
+ {renderInline(entry.label)}
826
+ </span>
827
+ ))}
828
+ </div>
829
+ )}
830
+ </div>
831
+ )
832
+ })
833
+
834
+ /** Line: responsive polyline with an area wash, nice y ticks and sampled x
835
+ * labels drawn in SVG at their real size. */
836
+ export const LineChartNode = memo(function LineChartNode({ chart }: { chart: GenuiChart }) {
837
+ useT()
838
+ const [ref, measured] = useMeasuredWidth()
839
+ const { tip, show, hide } = useChartTip()
840
+ const gradientId = `genui-line-${useId().replace(/:/g, '')}`
841
+ const grouped = chart.series !== undefined && chart.series.length > 0
842
+ ? chart.series.slice(0, GENUI_LIMITS.maxPlotSeries)
843
+ : undefined
844
+ const data = chart.data.slice(0, GENUI_LIMITS.maxChartPoints)
845
+ const labels = grouped !== undefined ? grouped[0]!.data.map(d => d.label) : data.map(d => d.label)
846
+ const seriesValues = grouped !== undefined
847
+ ? grouped.map(entry => entry.data.map(d => Number(d.value) || 0))
848
+ : [data.map(d => Number(d.value) || 0)]
849
+ const colors = seriesValues.map((_values, si) =>
850
+ seriesColor(si, seriesValues.length, grouped !== undefined ? grouped[si]?.color : undefined, chart.palette) ?? 'var(--dsl-g-accent)')
851
+ const multi = seriesValues.length > 1
852
+ const flat = seriesValues.flat()
853
+ const pointCount = Math.max(...seriesValues.map(values => values.length), 0)
854
+ const W = Math.max(measured, 260)
855
+ const H = 176
856
+ const padL = 44
857
+ const padR = 12
858
+ const padT = 14
859
+ const padB = 26
860
+ const ticks = niceTicks(Math.min(...flat, 0), Math.max(...flat, 0), 4)
861
+ const lo = ticks[0]!
862
+ const hi = ticks[ticks.length - 1]!
863
+ const span = hi - lo || 1
864
+ const innerW = W - padL - padR
865
+ const innerH = H - padT - padB
866
+ const x = (i: number): number => padL + (pointCount <= 1 ? innerW / 2 : (i / (pointCount - 1)) * innerW)
867
+ const y = (v: number): number => padT + (1 - (v - lo) / span) * innerH
868
+ const paths = seriesValues.map(values =>
869
+ values.map((v, i) => `${i === 0 ? 'M' : 'L'} ${x(i).toFixed(1)} ${y(v).toFixed(1)}`).join(' '))
870
+ const area = !multi && pointCount > 1
871
+ ? `${paths[0]} L ${x(pointCount - 1).toFixed(1)} ${y(lo).toFixed(1)} L ${x(0).toFixed(1)} ${y(lo).toFixed(1)} Z`
872
+ : null
873
+ // Keep x labels readable: at most one per ~64px of plot width.
874
+ const labelStep = Math.max(1, Math.ceil(pointCount / Math.max(1, Math.floor(innerW / 64))))
875
+ const summary = tr(multi ? 'block.chart.lineSeries' : 'block.chart.linePoints', {
876
+ count: multi ? seriesValues.length : pointCount,
877
+ min: formatTick(Math.min(...flat, 0)),
878
+ max: formatTick(Math.max(...flat, 0)),
879
+ })
880
+ return (
881
+ <div className={css.lineChart} data-genui-chart="line" data-genui-line ref={ref} role="img" aria-label={summary} onMouseLeave={hide}>
882
+ <ChartTip tip={tip} />
883
+ <svg width="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none">
884
+ <defs>
885
+ <linearGradient id={gradientId} x1="0" y1="0" x2="0" y2="1">
886
+ <stop offset="0%" stopColor="var(--dsl-g-accent)" stopOpacity="0.22" />
887
+ <stop offset="100%" stopColor="var(--dsl-g-accent)" stopOpacity="0.02" />
888
+ </linearGradient>
889
+ </defs>
890
+ {ticks.map((t, i) => {
891
+ const ty = y(t)
892
+ return (
893
+ <g key={t}>
894
+ <line x1={padL} x2={W - padR} y1={ty} y2={ty} className={i === 0 ? css.lineGridAxis : css.lineGrid} />
895
+ <text x={padL - 8} y={ty + 4} textAnchor="end" className={css.lineTick}>{formatTick(t)}</text>
896
+ </g>
897
+ )
898
+ })}
899
+ {area !== null && <path d={area} fill={`url(#${gradientId})`} />}
900
+ {paths.map((d, si) => <path key={si} d={d} className={css.linePath} style={{ stroke: colors[si] }} />)}
901
+ {seriesValues.map((values, si) => values.map((v, i) => {
902
+ const rows: TipRow[] = multi
903
+ ? [[grouped![si]!.label, String(v)], [tr('block.chart.node'), labels[i] ?? '']]
904
+ : [[labels[i] ?? '', String(v)]]
905
+ return (
906
+ <circle
907
+ key={`${si}-${i}`}
908
+ cx={x(i)}
909
+ cy={y(v)}
910
+ r={multi ? 3 : 3.5}
911
+ className={css.lineDot}
912
+ style={{ fill: colors[si] }}
913
+ onMouseEnter={event => show(event, rows)}
914
+ onMouseMove={event => show(event, rows)}
915
+ />
916
+ )
917
+ }))}
918
+ {labels.map((label, i) => (
919
+ i % labelStep === 0
920
+ ? <text key={`l-${i}`} x={x(i)} y={H - 8} textAnchor="middle" className={css.lineLabel}>{label}</text>
921
+ : null
922
+ ))}
923
+ </svg>
924
+ {multi && (
925
+ <div className={css.chartLegend}>
926
+ {grouped!.map((entry, si) => (
927
+ <span key={si} className={css.legendItem}>
928
+ <span className={css.legendSwatch} style={{ background: colors[si] }} />
929
+ {renderInline(entry.label)}
930
+ </span>
931
+ ))}
932
+ </div>
933
+ )}
934
+ </div>
935
+ )
936
+ })
937
+
938
+ /** Donut: share of total with a center total and a legend that shows each
939
+ * slice's value AND percentage (the old legend was unstyled text). */
940
+ export const DonutNode = memo(function DonutNode({ chart }: { chart: GenuiChart }) {
941
+ useT()
942
+ const { tip, show, hide } = useChartTip()
943
+ const data = chart.data.slice(0, GENUI_LIMITS.maxChartPoints)
944
+ const clamped = data.map(d => ({ ...d, v: Math.max(0, Number(d.value) || 0) }))
945
+ const total = clamped.reduce((s, d) => s + d.v, 0) || 1
946
+ // Center total: 1 decimal for fractional sums — a share-of-total figure
947
+ // like 3.3/9.9 used to print the raw float as 6.6000000000000005.
948
+ const totalText = total >= 1000
949
+ ? `${Math.round(total / 100) / 10}k`
950
+ : Number.isInteger(total) ? String(total) : total.toFixed(1)
951
+ const R = 62
952
+ const STROKE = 18
953
+ const SIZE = 160
954
+ const C = 2 * Math.PI * R
955
+ let offset = 0
956
+ const summary = tr('block.chart.donutSummary', { count: clamped.length, total: totalText })
957
+ return (
958
+ <div className={css.donut} data-genui-chart="donut" data-genui-donut role="img" aria-label={summary} onMouseLeave={hide}>
959
+ <ChartTip tip={tip} />
960
+ <svg width={SIZE} height={SIZE} viewBox={`0 0 ${SIZE} ${SIZE}`}>
961
+ <circle cx={SIZE / 2} cy={SIZE / 2} r={R} fill="none" strokeWidth={STROKE} className={css.donutTrack} />
962
+ {clamped.map((d, i) => {
963
+ const frac = d.v / total
964
+ const len = frac * C
965
+ const el = (
966
+ <circle
967
+ key={i}
968
+ cx={SIZE / 2}
969
+ cy={SIZE / 2}
970
+ r={R}
971
+ fill="none"
972
+ strokeWidth={STROKE}
973
+ className={css.donutSeg}
974
+ style={{ stroke: seriesColor(i, data.length, d.color, chart.palette) ?? 'var(--dsw-alias-state-business-primary, #4f8ef7)' }}
975
+ strokeDasharray={`${len} ${C - len}`}
976
+ strokeDashoffset={-offset}
977
+ transform={`rotate(-90 ${SIZE / 2} ${SIZE / 2})`}
978
+ onMouseEnter={event => show(event, [[d.label, `${String(d.value)} · ${(frac * 100).toFixed(1)}%`]])}
979
+ onMouseMove={event => show(event, [[d.label, `${String(d.value)} · ${(frac * 100).toFixed(1)}%`]])}
980
+ />
981
+ )
982
+ offset += len
983
+ return el
984
+ })}
985
+ <text x={SIZE / 2} y={SIZE / 2 - 2} textAnchor="middle" className={css.donutTotal}>{totalText}</text>
986
+ <text x={SIZE / 2} y={SIZE / 2 + 16} textAnchor="middle" className={css.donutTotalLabel}>{tr('block.total')}</text>
987
+ </svg>
988
+ <div className={css.donutLegend}>
989
+ {clamped.map((d, i) => (
990
+ <span key={i} className={css.legendItem}>
991
+ <span className={css.legendSwatch} style={{ background: seriesColor(i, data.length, d.color, chart.palette) ?? 'var(--dsw-alias-state-business-primary, #4f8ef7)' }} />
992
+ <span>{renderInline(d.label)}</span>
993
+ <span className={css.donutPct}>{String(d.value)} · {(d.v / total * 100).toFixed(1)}%</span>
994
+ </span>
995
+ ))}
996
+ </div>
997
+ </div>
998
+ )
999
+ })