@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,147 @@
1
+ /**
2
+ * TemplateDrawer — the GenUI template center (new-user onboarding).
3
+ *
4
+ * Browse by category → click a card → inline preview (the demo spec rendered
5
+ * directly by GenuiBlock, dogfooding) + "try it" (insert into the composer) /
6
+ * "copy instruction". The user sees the result first and only then decides to
7
+ * send the instruction to the model — the genui capability manual.
8
+ */
9
+ import { useMemo, useRef, useState } from 'react'
10
+ import { genuiTemplates, TEMPLATE_CATEGORIES, categoryLabelKey, type GenuiTemplate, type TemplateCategory } from './templates.ts'
11
+ import { useLocaleRevision, useT } from './i18n/index.ts'
12
+ import { GenuiBlock } from './GenuiBlock.tsx'
13
+ import { ErrorBoundary } from './ErrorBoundary.tsx'
14
+ import { panelStateKey } from './interaction-store.ts'
15
+ import { buildAchievementsSpec } from './achievements.ts'
16
+ import { getAchievementSnapshot, subscribeAchievements } from './achievement-store.ts'
17
+ import { useSyncExternalStore } from 'react'
18
+ import css from './TemplateDrawer.module.css'
19
+
20
+ export interface TemplateDrawerProps {
21
+ /** Try it: insert the template instruction into the composer draft. */
22
+ onUse: (instruction: string) => void
23
+ /** Which drawer is open (template center / trophies), driven by the header. */
24
+ tab: 'templates' | 'achievements'
25
+ }
26
+
27
+ /** Filter ids: `all` plus every template category. Labels are localized. */
28
+ const CATEGORIES = ['all', ...TEMPLATE_CATEGORIES] as const
29
+ type Category = TemplateCategory | 'all'
30
+
31
+ /** Copy to clipboard with a legacy fallback (like GenuiCopy). */
32
+ function copyText(text: string): Promise<void> {
33
+ if (navigator.clipboard !== undefined) return navigator.clipboard.writeText(text)
34
+ return new Promise((resolve, reject) => {
35
+ try {
36
+ const ta = document.createElement('textarea')
37
+ ta.value = text
38
+ ta.style.position = 'fixed'
39
+ ta.style.opacity = '0'
40
+ document.body.appendChild(ta)
41
+ ta.select()
42
+ document.execCommand('copy')
43
+ ta.remove()
44
+ resolve()
45
+ } catch (error) {
46
+ reject(error instanceof Error ? error : new Error(String(error)))
47
+ }
48
+ })
49
+ }
50
+
51
+ export function TemplateDrawer({ onUse, tab }: TemplateDrawerProps) {
52
+ const t = useT()
53
+ const localeRevision = useLocaleRevision()
54
+ const [category, setCategory] = useState<Category>('all')
55
+ const [selected, setSelected] = useState<GenuiTemplate | null>(null)
56
+ const [copied, setCopied] = useState(false)
57
+ const timer = useRef(0)
58
+ // Achievements tab: live state snapshot.
59
+ const achievements = useSyncExternalStore(subscribeAchievements, () => getAchievementSnapshot())
60
+ const achievementSpec = useMemo(
61
+ () => buildAchievementsSpec(achievements.state, achievements.unlocked),
62
+ [achievements, localeRevision],
63
+ )
64
+
65
+ // Rebuilt when the locale changes: `t` keeps a stable identity, so the
66
+ // revision — not `t` — is what invalidates this memo.
67
+ const items = useMemo(
68
+ () => {
69
+ const all = genuiTemplates()
70
+ return category === 'all' ? [...all] : all.filter(tpl => tpl.category === category)
71
+ },
72
+ [category, localeRevision],
73
+ )
74
+
75
+ const copy = async (text: string): Promise<void> => {
76
+ try {
77
+ await copyText(text)
78
+ setCopied(true)
79
+ window.clearTimeout(timer.current)
80
+ timer.current = window.setTimeout(() => setCopied(false), 1500)
81
+ } catch {
82
+ // Clipboard denied: the instruction stays in the drawer; nothing else
83
+ // to do — the use flow does not depend on it.
84
+ }
85
+ }
86
+
87
+ return (
88
+ <div className={css.wrap} data-genui-templates={tab === 'templates' ? undefined : 'achievements'}>
89
+ {tab === 'achievements' ? (
90
+ <div className={css.achievements} data-genui-achievements>
91
+ <ErrorBoundary label={t('tpl.boundary.achievements')}>
92
+ <GenuiBlock spec={achievementSpec} stateKey={panelStateKey('genui-achievements', JSON.stringify(achievementSpec))} />
93
+ </ErrorBoundary>
94
+ </div>
95
+ ) : (
96
+ <>
97
+ <div className={css.cats} role="tablist" aria-label={t('tpl.categories.aria')}>
98
+ {CATEGORIES.map(c => (
99
+ <button
100
+ key={c}
101
+ type="button"
102
+ role="tab"
103
+ aria-selected={category === c}
104
+ className={`${css.cat}${category === c ? ` ${css.catActive}` : ''}`}
105
+ onClick={() => { setCategory(c); setSelected(null) }}
106
+ >
107
+ {t(categoryLabelKey(c))}
108
+ </button>
109
+ ))}
110
+ </div>
111
+ <div className={css.list}>
112
+ {items.map(tpl => (
113
+ <button
114
+ key={tpl.id}
115
+ type="button"
116
+ className={`${css.card}${selected?.id === tpl.id ? ` ${css.cardActive}` : ''}`}
117
+ onClick={() => setSelected(prev => (prev?.id === tpl.id ? null : tpl))}
118
+ >
119
+ <span className={css.cardName}>{tpl.name}</span>
120
+ <span className={css.cardMeta}>{t(categoryLabelKey(tpl.category))}</span>
121
+ <span className={css.cardDesc}>{tpl.description}</span>
122
+ </button>
123
+ ))}
124
+ </div>
125
+ {selected !== null && (
126
+ <div className={css.detail} data-genui-template-preview>
127
+ <div className={css.toolbar}>
128
+ <span className={css.toolbarTitle}>{selected.name}</span>
129
+ <button type="button" className={css.try} onClick={() => onUse(selected.instruction)}>
130
+ {t('tpl.try')}
131
+ </button>
132
+ <button type="button" className={css.copy} onClick={() => void copy(selected.instruction)}>
133
+ {copied ? t('tpl.copied') : t('tpl.copy')}
134
+ </button>
135
+ </div>
136
+ <div className={css.preview}>
137
+ <ErrorBoundary label={t('tpl.boundary.preview')}>
138
+ <GenuiBlock spec={selected.demo} stateKey={panelStateKey('genui-tpl', selected.id)} />
139
+ </ErrorBoundary>
140
+ </div>
141
+ </div>
142
+ )}
143
+ </>
144
+ )}
145
+ </div>
146
+ )
147
+ }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * achievement-store.ts — 成就状态存储与埋点入口(模块级单例)。
3
+ *
4
+ * 只存计数与解锁时间戳;绝不含消息/内容。localStorage 持久化,
5
+ * 订阅接口供 toast 与成就页消费。埋点入口:
6
+ * - recordFence(spec):一次「内容不重复」的界面渲染(按 spec 指纹去重,
7
+ * LRU 指纹表跨刷新防重放重复计数)
8
+ * - recordPanel():面板 dock 出现
9
+ * - recordInteraction():组件动作回传(去抖后)
10
+ * - recordTemplateUse():模板中心试用
11
+ */
12
+ import type { GenuiSpec } from './spec.ts'
13
+ import { ACHIEVEMENTS, checkAchievements, countSpecKinds, emptyState, type AchieveState, type AchievementDef } from './achievements.ts'
14
+
15
+ const STORE_KEY = 'dsh.genui.achievements'
16
+ const SEEN_KEY = 'dsh.genui.achievements.seen'
17
+ const SEEN_MAX = 200
18
+
19
+ interface AchieveStore {
20
+ state: AchieveState
21
+ unlocked: Record<string, number>
22
+ }
23
+
24
+ let store: AchieveStore = loadStore()
25
+ const listeners = new Set<() => void>()
26
+ /** 解锁 toast 队列(FIFO;成就页打开时也读)。 */
27
+ let toastQueue: AchievementDef[] = []
28
+
29
+ function loadStore(): AchieveStore {
30
+ try {
31
+ const raw = localStorage.getItem(STORE_KEY)
32
+ if (raw === null) return { state: emptyState(), unlocked: {} }
33
+ const parsed = JSON.parse(raw) as Partial<AchieveStore>
34
+ const state = { ...emptyState(), ...(parsed.state ?? {}) }
35
+ return { state, unlocked: typeof parsed.unlocked === 'object' && parsed.unlocked !== null ? parsed.unlocked as Record<string, number> : {} }
36
+ } catch {
37
+ return { state: emptyState(), unlocked: {} }
38
+ }
39
+ }
40
+
41
+ function saveStore(): void {
42
+ try {
43
+ localStorage.setItem(STORE_KEY, JSON.stringify(store))
44
+ } catch {
45
+ // Quota / privacy-mode failures are non-fatal: achievements still tick
46
+ // in memory for this page session.
47
+ }
48
+ }
49
+
50
+ function readSeen(): string[] {
51
+ try {
52
+ const raw = localStorage.getItem(SEEN_KEY)
53
+ if (raw === null) return []
54
+ const parsed = JSON.parse(raw) as unknown
55
+ return Array.isArray(parsed) ? parsed.filter((v): v is string => typeof v === 'string') : []
56
+ } catch {
57
+ return []
58
+ }
59
+ }
60
+
61
+ function writeSeen(list: string[]): void {
62
+ try {
63
+ localStorage.setItem(SEEN_KEY, JSON.stringify(list.slice(0, SEEN_MAX)))
64
+ } catch {
65
+ // non-fatal
66
+ }
67
+ }
68
+
69
+ function emit(): void {
70
+ for (const listener of listeners) listener()
71
+ }
72
+
73
+ /** 应用一次状态更新:持久化 + 检查新解锁(进 toast 队列)+ 通知订阅者。 */
74
+ function applyDelta(patch: Partial<AchieveState>): void {
75
+ store.state = { ...store.state, ...patch }
76
+ const fresh = checkAchievements(store.state, store.unlocked)
77
+ for (const ach of fresh) store.unlocked[ach.id] = Date.now()
78
+ if (fresh.length > 0) toastQueue.push(...fresh)
79
+ saveStore()
80
+ emit()
81
+ }
82
+
83
+ /** 53-bit string hash (cyrb53-style): dedupe fingerprints are stored as
84
+ * hashes, never as the serialized spec itself — localStorage must not
85
+ * persist conversation-derived content (table rows, text, …). */
86
+ function fingerprintOf(spec: GenuiSpec): string {
87
+ const s = JSON.stringify(spec)
88
+ let h1 = 0xdeadbeef
89
+ let h2 = 0x41c6ce57
90
+ for (let i = 0; i < s.length; i++) {
91
+ const ch = s.charCodeAt(i)
92
+ h1 = Math.imul(h1 ^ ch, 2654435761)
93
+ h2 = Math.imul(h2 ^ ch, 1597334677)
94
+ }
95
+ return `${(h1 >>> 0).toString(36)}-${(h2 >>> 0).toString(36)}`
96
+ }
97
+
98
+ /** 记录一次「内容不重复」的 fence 渲染。 */
99
+ export function recordFence(spec: GenuiSpec): void {
100
+ const fingerprint = fingerprintOf(spec)
101
+ const seen = readSeen()
102
+ if (seen.includes(fingerprint)) return
103
+ writeSeen([fingerprint, ...seen])
104
+ const kinds = countSpecKinds(spec)
105
+ applyDelta({
106
+ fences: store.state.fences + 1,
107
+ charts: store.state.charts + (kinds.charts > 0 ? 1 : 0),
108
+ advanced: store.state.advanced + (kinds.advanced > 0 ? 1 : 0),
109
+ })
110
+ }
111
+
112
+ /** 记录一次面板 dock 出现(仅会话从无到有时)。 */
113
+ export function recordPanel(): void {
114
+ applyDelta({ panels: store.state.panels + 1 })
115
+ }
116
+
117
+ /** 记录一次组件交互动作回传。 */
118
+ export function recordInteraction(): void {
119
+ applyDelta({ interactions: store.state.interactions + 1 })
120
+ }
121
+
122
+ /** 记录一次模板试用。 */
123
+ export function recordTemplateUse(): void {
124
+ applyDelta({ templates: store.state.templates + 1 })
125
+ }
126
+
127
+ /** 当前状态快照(订阅者读取)。 */
128
+ export function getAchievementSnapshot(): { state: AchieveState, unlocked: Record<string, number> } {
129
+ return store
130
+ }
131
+
132
+ /** 取走新解锁(toast 消费;一次性)。 */
133
+ export function consumeUnlocks(): AchievementDef[] {
134
+ const queue = toastQueue
135
+ toastQueue = []
136
+ return queue
137
+ }
138
+
139
+ /** 订阅状态变化(toast 与成就页)。 */
140
+ export function subscribeAchievements(listener: () => void): () => void {
141
+ listeners.add(listener)
142
+ return () => listeners.delete(listener)
143
+ }
144
+
145
+ /** 成就页 spec 数据源(面板内渲染用)。 */
146
+ export function achievementCount(): { total: number, unlocked: number } {
147
+ return {
148
+ total: ACHIEVEMENTS.length,
149
+ unlocked: ACHIEVEMENTS.filter(a => store.unlocked[a.id] !== undefined).length,
150
+ }
151
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * achievement-toast.tsx — the unlock toast stack (bottom right, 3.6s auto-fade).
3
+ *
4
+ * Its own React root at document.body level: an unlock from the panel OR an
5
+ * inline fence pops a toast, so it does not depend on the panel existing.
6
+ * Consumes achievement-store's new-unlock queue.
7
+ */
8
+ import { createElement, useEffect, useRef, useState, useSyncExternalStore } from 'react'
9
+ import { createRoot } from 'react-dom/client'
10
+ import { consumeUnlocks, subscribeAchievements } from './achievement-store.ts'
11
+ import { useT } from './i18n/index.ts'
12
+ import type { AchievementDef } from './achievements.ts'
13
+ import css from './GenuiBlock.module.css'
14
+
15
+ interface ToastItem {
16
+ key: number
17
+ ach: AchievementDef
18
+ }
19
+
20
+ let toastKey = 0
21
+
22
+ /** Fixed bottom stack: the queue rendered FIFO as a vertical stack. */
23
+ function AchievementToasts() {
24
+ const t = useT()
25
+ const [, force] = useSyncExternalStore(subscribeAchievements, () => '')
26
+ const [items, setItems] = useState<ToastItem[]>([])
27
+ const timers = useRef<Map<number, number>>(new Map())
28
+
29
+ useEffect(() => {
30
+ const queue = consumeUnlocks()
31
+ if (queue.length === 0) return
32
+ const next: ToastItem[] = queue.map(ach => ({ key: ++toastKey, ach }))
33
+ setItems(prev => [...prev, ...next])
34
+ for (const item of next) {
35
+ const t = window.setTimeout(() => {
36
+ setItems(prev => prev.filter(i => i.key !== item.key))
37
+ timers.current.delete(item.key)
38
+ }, 3600)
39
+ timers.current.set(item.key, t)
40
+ }
41
+ }, [force])
42
+
43
+ useEffect(() => () => {
44
+ for (const t of timers.current.values()) window.clearTimeout(t)
45
+ }, [])
46
+
47
+ if (items.length === 0) return null
48
+ return createElement('div', { className: css.achToasts, 'data-genui-achievement-toasts': true },
49
+ items.map(item => createElement('div', { key: item.key, className: css.achToast },
50
+ createElement('span', { className: css.achToastBadge, 'aria-hidden': true }, '🏆'),
51
+ createElement('div', { className: css.achToastBody },
52
+ createElement('div', { className: css.achToastName }, t('ach.toast.unlocked', { name: item.ach.name })),
53
+ createElement('div', { className: css.achToastDesc }, item.ach.description),
54
+ ),
55
+ )),
56
+ )
57
+ }
58
+
59
+ /** Mount the toast stack (called from apply; returns the unmount disposer). */
60
+ export function mountAchievementToasts(): () => void {
61
+ if (typeof document === 'undefined') return () => {}
62
+ const host = document.createElement('div')
63
+ host.dataset.dshGenuiAchievements = '1'
64
+ document.body.appendChild(host)
65
+ const root = createRoot(host)
66
+ root.render(createElement(AchievementToasts))
67
+ return () => {
68
+ root.unmount()
69
+ host.remove()
70
+ }
71
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * achievements.ts — GenUI exploration trophies.
3
+ *
4
+ * Lightweight local trophies: they count USAGE EVENTS only (fences rendered,
5
+ * panels shown, actions sent back, templates tried) and never read message
6
+ * or interface content. State lives in localStorage and survives across
7
+ * sessions. An unlock enters the toast queue (consumed by achievement-toast),
8
+ * and the panel's trophy tab renders its own page through dsh-ui (dogfooding).
9
+ *
10
+ * The design mirrors dsh-achievements' layered snapshot, with zero host
11
+ * changes: every counter sits on this package's own render/interaction paths
12
+ * (GenuiBlock / TemplateDrawer / GenuiPanel).
13
+ *
14
+ * Trophy NAMES and DESCRIPTIONS resolve from the i18n dictionaries at read
15
+ * time (`ach.<id>.name` / `.desc`); only the ids are persisted, so a language
16
+ * switch never orphans an unlocked trophy.
17
+ */
18
+ import type { GenuiSpec, GenuiNode } from './spec.ts'
19
+ import { t } from './i18n/index.ts'
20
+
21
+ /** Cumulative usage counters (the trophy inputs). */
22
+ export interface AchieveState {
23
+ /** Distinct fences rendered. */
24
+ fences: number
25
+ /** Sessions in which the panel dock appeared. */
26
+ panels: number
27
+ /** Component action round-trips (after debounce). */
28
+ interactions: number
29
+ /** Templates tried. */
30
+ templates: number
31
+ /** Fences containing a chart node (chart/plot/echart). */
32
+ charts: number
33
+ /** Fences containing an advanced node (scene3d/mermaid/diagram). */
34
+ advanced: number
35
+ }
36
+
37
+ export function emptyState(): AchieveState {
38
+ return { fences: 0, panels: 0, interactions: 0, templates: 0, charts: 0, advanced: 0 }
39
+ }
40
+
41
+ export interface AchievementDef {
42
+ id: string
43
+ /** Display name in the active locale (read through {@link achievementName}). */
44
+ readonly name: string
45
+ /** Description in the active locale (read through {@link achievementDesc}). */
46
+ readonly description: string
47
+ /** Hide name/description until unlocked (easter egg). */
48
+ hidden?: boolean
49
+ /** Rarity tier. */
50
+ rarity: 'common' | 'rare' | 'legendary'
51
+ check: (s: AchieveState) => boolean
52
+ }
53
+
54
+ const fences = (n: number) => (s: AchieveState): boolean => s.fences >= n
55
+
56
+ /** Localized display name of a trophy. */
57
+ export function achievementName(id: string): string {
58
+ return t(`ach.${id}.name`)
59
+ }
60
+
61
+ /** Localized description of a trophy. */
62
+ export function achievementDesc(id: string): string {
63
+ return t(`ach.${id}.desc`)
64
+ }
65
+
66
+ /** Localized rarity badge label. */
67
+ export function rarityLabel(rarity: AchievementDef['rarity']): string {
68
+ return t(`ach.rarity.${rarity}`)
69
+ }
70
+
71
+ /**
72
+ * Trophy definitions. `name`/`description` are GETTERS reading the active
73
+ * locale, so a definition captured before a language switch still renders in
74
+ * the language on screen.
75
+ */
76
+ function def(
77
+ id: string,
78
+ rarity: AchievementDef['rarity'],
79
+ check: (s: AchieveState) => boolean,
80
+ hidden = false,
81
+ ): AchievementDef {
82
+ return {
83
+ id,
84
+ rarity,
85
+ check,
86
+ ...(hidden ? { hidden: true } : {}),
87
+ get name() { return achievementName(id) },
88
+ get description() { return achievementDesc(id) },
89
+ }
90
+ }
91
+
92
+ export const ACHIEVEMENTS: readonly AchievementDef[] = [
93
+ def('first-fence', 'common', fences(1)),
94
+ def('fence-5', 'common', fences(5)),
95
+ def('fence-25', 'rare', fences(25)),
96
+ def('fence-50', 'legendary', fences(50), true),
97
+ def('first-interaction', 'common', s => s.interactions >= 1),
98
+ def('interaction-10', 'rare', s => s.interactions >= 10),
99
+ def('first-panel', 'common', s => s.panels >= 1),
100
+ def('panel-5', 'rare', s => s.panels >= 5),
101
+ def('first-chart', 'common', s => s.charts >= 1),
102
+ def('chart-10', 'rare', s => s.charts >= 10),
103
+ def('first-advanced', 'rare', s => s.advanced >= 1),
104
+ def('template-1', 'common', s => s.templates >= 1),
105
+ ]
106
+
107
+ /** Count the relevant node families in a spec (same walk as the guard). */
108
+ export function countSpecKinds(spec: GenuiSpec): { charts: number, advanced: number } {
109
+ let charts = 0
110
+ let advanced = 0
111
+ const walk = (list: unknown): void => {
112
+ if (!Array.isArray(list)) return
113
+ for (const item of list) {
114
+ if (typeof item !== 'object' || item === null) continue
115
+ const v = item as Record<string, unknown>
116
+ const type = v.type
117
+ if (type === 'chart' || type === 'plot' || type === 'echart') charts += 1
118
+ if (type === 'scene3d' || type === 'mermaid' || type === 'diagram') advanced += 1
119
+ // Recurse into containers and list items.
120
+ if (Array.isArray(v.items)) walk(v.items as unknown[])
121
+ if (Array.isArray((v as { tabs?: unknown }).tabs)) {
122
+ for (const tab of (v as { tabs: Array<{ items?: unknown }> }).tabs) walk(tab.items)
123
+ }
124
+ }
125
+ }
126
+ walk(spec.items)
127
+ return { charts, advanced }
128
+ }
129
+
130
+ /** Build the trophy page spec (rendered by dsh-ui): progress stats, the
131
+ * unlock list, and rarity badges — all in the active locale. */
132
+ export function buildAchievementsSpec(state: AchieveState, unlocked: Record<string, number>): GenuiSpec {
133
+ const total = ACHIEVEMENTS.length
134
+ const unlockedCount = ACHIEVEMENTS.filter(a => unlocked[a.id] !== undefined).length
135
+ const items: GenuiNode[] = [
136
+ { type: 'grid', cols: 3, items: [
137
+ { type: 'stat', label: t('ach.stat.unlocked'), value: `${unlockedCount} / ${total}` },
138
+ { type: 'stat', label: t('ach.stat.rendered'), value: String(state.fences) },
139
+ { type: 'stat', label: t('ach.stat.interactions'), value: String(state.interactions) },
140
+ ] },
141
+ { type: 'progress', label: t('ach.progress'), value: Math.round(unlockedCount / total * 100), valueLabel: `${Math.round(unlockedCount / total * 100)}%` },
142
+ { type: 'list', items: ACHIEVEMENTS.map(a => {
143
+ const locked = a.hidden === true && unlocked[a.id] === undefined
144
+ return {
145
+ type: 'row',
146
+ items: [
147
+ { type: 'badge', label: rarityLabel(a.rarity), tone: unlocked[a.id] !== undefined ? 'success' : 'warn' },
148
+ { type: 'text', size: 'body', content: locked ? t('ach.hidden.name') : a.name },
149
+ { type: 'text', size: 'muted', content: locked ? t('ach.hidden.desc') : a.description },
150
+ ],
151
+ }
152
+ }) },
153
+ ]
154
+ return { title: t('ach.page.title'), items }
155
+ }
156
+
157
+ /** New unlocks for a state (hidden trophies included — rules are thresholds). */
158
+ export function checkAchievements(state: AchieveState, unlocked: Record<string, number>): AchievementDef[] {
159
+ return ACHIEVEMENTS.filter(a => unlocked[a.id] === undefined && a.check(state))
160
+ }
@@ -0,0 +1,32 @@
1
+ /**
2
+ * GenUI action context, plugin-owned.
3
+ *
4
+ * Contract hosts (`dsh-host-0812-contract` and later) ship the same context
5
+ * in `@deepseek-ai/dsh-client-ui-primitives` and MarkdownText installs the
6
+ * provider around fence renders — the renderer MUST consume that exact
7
+ * context instance so the host's action wiring reaches our components.
8
+ * Pristine hosts (the stock snapshot line) export no such symbol; the DOM
9
+ * render channel then falls back to the local context and installs its own
10
+ * provider (this package wraps every tree it mounts).
11
+ *
12
+ * Absent provider = v1 behavior: interactive components are display-only
13
+ * (their `action` is ignored). The hook never throws.
14
+ */
15
+ import { createContext, useContext } from 'react'
16
+ import type { Context } from 'react'
17
+ import * as primitives from './primitive-adapter.ts'
18
+
19
+ /** v2 action handler: component action + its collected data. */
20
+ export type GenuiActionHandler = (action: string, payload: Record<string, unknown>) => void
21
+
22
+ /** Local fallback context (pristine hosts). */
23
+ const localContext = createContext<GenuiActionHandler | undefined>(undefined)
24
+
25
+ /** Host-provided context when the deployment ships it, else the local one. */
26
+ export const GenuiActionContext: Context<GenuiActionHandler | undefined> =
27
+ (primitives as unknown as { GenuiActionContext?: Context<GenuiActionHandler | undefined> }).GenuiActionContext ?? localContext
28
+
29
+ /** Read the installed action handler, if any. */
30
+ export function useGenuiAction(): GenuiActionHandler | undefined {
31
+ return useContext(GenuiActionContext)
32
+ }
@@ -0,0 +1,64 @@
1
+ .chrome {
2
+ position: relative;
3
+ display: flex;
4
+ align-items: center;
5
+ justify-content: flex-end;
6
+ gap: 8px;
7
+ margin: 8px 0 6px;
8
+ font: 12px/1.4 system-ui, sans-serif;
9
+ }
10
+
11
+ .trigger,
12
+ .item {
13
+ border: 1px solid var(--dsw-alias-border-l1);
14
+ border-radius: 7px;
15
+ padding: 5px 9px;
16
+ background: var(--dsw-alias-bg-layer-1);
17
+ color: var(--dsw-alias-label-secondary);
18
+ cursor: pointer;
19
+ }
20
+
21
+ .trigger:hover,
22
+ .item:hover {
23
+ background: var(--dsw-alias-fill-hover);
24
+ color: var(--dsw-alias-label-primary);
25
+ }
26
+
27
+ .menu {
28
+ position: absolute;
29
+ z-index: 20;
30
+ top: calc(100% + 4px);
31
+ right: 0;
32
+ display: grid;
33
+ min-width: 140px;
34
+ gap: 3px;
35
+ padding: 5px;
36
+ border: 1px solid var(--dsw-alias-border-l1);
37
+ border-radius: 9px;
38
+ background: var(--dsw-alias-bg-layer-1);
39
+ box-shadow: 0 8px 24px #0002;
40
+ }
41
+
42
+ .item {
43
+ border-color: transparent;
44
+ text-align: left;
45
+ }
46
+
47
+ .item:disabled {
48
+ opacity: .5;
49
+ cursor: not-allowed;
50
+ }
51
+
52
+ .menuNotice {
53
+ max-width: 260px;
54
+ padding: 2px 9px 6px;
55
+ color: var(--dsw-alias-state-error-primary, #d94848);
56
+ }
57
+
58
+ .notice {
59
+ color: var(--dsw-alias-label-tertiary);
60
+ }
61
+
62
+ .statusError {
63
+ color: var(--dsw-alias-state-error-primary, #d94848);
64
+ }