@h-ai/ui 0.1.0-alpha.70 → 0.1.0-alpha.72

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 (33) hide show
  1. package/README.en.md +19 -6
  2. package/README.ja.md +19 -6
  3. package/README.md +19 -6
  4. package/auto-import.d.ts +1 -0
  5. package/auto-import.js +1 -0
  6. package/dist/components/compounds/JsonViewer.svelte +214 -0
  7. package/dist/components/compounds/JsonViewer.svelte.d.ts +26 -0
  8. package/dist/components/compounds/index.d.ts +1 -0
  9. package/dist/components/compounds/index.js +2 -0
  10. package/dist/components/scenes/ai/index.d.ts +1 -0
  11. package/dist/components/scenes/ai/index.js +2 -0
  12. package/dist/components/scenes/app/FeedbackDetail.svelte +14 -2
  13. package/dist/components/scenes/app/FeedbackDetail.svelte.d.ts +2 -0
  14. package/dist/components/scenes/app/FeedbackForm.svelte +128 -61
  15. package/dist/components/scenes/app/FeedbackForm.svelte.d.ts +14 -3
  16. package/dist/components/scenes/app/FeedbackList.svelte +3 -3
  17. package/dist/components/scenes/app/FeedbackModal.svelte +50 -2
  18. package/dist/components/scenes/app/FeedbackRecorder.svelte +154 -0
  19. package/dist/components/scenes/app/FeedbackRecorder.svelte.d.ts +9 -0
  20. package/dist/components/scenes/app/FeedbackReplay.svelte +142 -0
  21. package/dist/components/scenes/app/FeedbackReplay.svelte.d.ts +7 -0
  22. package/dist/components/scenes/app/FeedbackScreenshot.svelte +37 -23
  23. package/dist/components/scenes/app/feedback-functions.js +1 -0
  24. package/dist/components/scenes/app/feedback-types.d.ts +1 -1
  25. package/dist/components/scenes/iam/auth-error-message.d.ts +1 -1
  26. package/dist/components/scenes/iam/auth-error-message.js +2 -1
  27. package/dist/messages/en-US.json +29 -9
  28. package/dist/messages/ja-JP.json +29 -9
  29. package/dist/messages/zh-CN.json +29 -9
  30. package/dist/toast.svelte.d.ts +9 -0
  31. package/dist/toast.svelte.js +25 -4
  32. package/dist/types.d.ts +27 -0
  33. package/package.json +3 -2
package/README.en.md CHANGED
@@ -241,6 +241,7 @@ Client validation appears on the first blur and updates as invalid input is corr
241
241
  | Component | Description | Key props |
242
242
  | ----------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
243
243
  | `Card` | Card container | `title`, `bordered`, `shadow`, `padding` |
244
+ | `JsonViewer` | JSON tree viewer | `value`, `defaultExpandedDepth`, `maxScalarLength`, `showCopy`, `onCopy`; circular references are replaced with a placeholder |
244
245
  | `DataTable` | Data table | `data`, `columns`, `keyField`, `loading`, `sortKey`, `sortDir`, `onsort`; `cell` slot and `onrowclick` (`sortable` columns support sorting) |
245
246
  | `Accordion` | Accordion | `items: AccordionItem[]` |
246
247
  | `Timeline` | Timeline | `items: TimelineItem[]` |
@@ -636,6 +637,12 @@ Defaults match `@h-ai/crypto`: `SM4` for encrypted inputs, `SM3` for hashes, and
636
637
  />
637
638
  ```
638
639
 
640
+ ### Feedback capture and delivery checks
641
+
642
+ Feedback `evidence` shows sanitized material contents. `oncapture(id?)` hides the modal for navigation and adds or replaces a screenshot. With `onfileschange`, native silent screen recording produces a previewable, removable WebM/MP4 attachment (up to 60 seconds / 5 MiB; video is not automatically masked). `FeedbackDetail.onreplay` loads complete page events on demand for playback and seeking; logs and environment remain paginated.
643
+
644
+ Feedback materials scroll independently while action buttons remain visible, so expanded content never crosses the action bar. `FeedbackList` retains an accessible name; its host provides the page heading to avoid duplicate titles.
645
+
639
646
  ### Style dependencies
640
647
 
641
648
  Components use TailwindCSS v4 + DaisyUI. Configure application `app.css` as follows:
@@ -916,6 +923,18 @@ Browsers keep application-level `setGlobalLocale` / `createLocaleStore`. During
916
923
 
917
924
  Object keys are limited to 1024 UTF-8 bytes and reject absolute paths, backslashes, control characters and dot segments. Each public HTTP batch delete accepts 1–1000 entries. `@h-ai/storage/schemas` exposes the shared browser-safe rules. Presign expiry is an integer from 1 to 604800 seconds (Node default 3600, HTTP default 900). Upload signing accepts only key/contentType/expiresIn; contentLength/maxSize/metadata/checksum are unsupported. Invalid input returns HTTP 400 and the typed client maps it to VALIDATION_FAILED. FileUpload limits guide file selection; applications must validate actual objects on the server. Node streaming/checksum/conditional-write options have no default HTTP endpoints. See the [capability and authorization matrix (Chinese)](../storage/README.md#存储输入约束与跨端能力).
918
925
 
926
+ ## Design and interaction acceptance
927
+
928
+ Use [hai-ui-design](../cli/templates/skills/hai-ui-design/SKILL.md) for page decisions, [hai-ui](../cli/templates/skills/hai-ui/SKILL.md) for implementation, and [hai-ui-review](../cli/templates/skills/hai-ui-review/SKILL.md) for rendered UI review. See the [shared design guidance](../../.agents/instructions/ui-design.md).
929
+
930
+ Tabs support arrow/Home/End navigation, disabled items and one Tab stop. Tables expose sort/loading state and keyboard row activation. Pagination labels follow locale and external page changes update the jump input. Toolbar panels manage focus and view buttons expose selection. Empty/Alert wrap long content. theme.css imports shared tokens; focus follows the current theme and global.css respects reduced motion. Applications still implement filtering, sorting, paging and recovery.
931
+
932
+ ## Error messages and correlated logs
933
+
934
+ HTTP errors expose localized safe messages followed by `(traceId: …)`, with the same ID in `error.traceId` and `X-Trace-Id`. The framework reuses the request ID to correlate browser and server logs. Sanitized exceptions, stacks and operation context remain in logs; internal cause/ext are not exposed. Field validation returns localized field names and messages only.
935
+
936
+ Use `core.error.toPublic(error, traceId?)` at HTTP/UI boundaries and `core.error.formatMessage(error)` after translating messages; formatting is idempotent. Pass complete Error objects to logs instead of discarding their context. Database failures log driver codes, sanitized messages/stacks and table/column context; SQL text, bound values and connection credentials are excluded.
937
+
919
938
  ## Development and testing
920
939
 
921
940
  ```sh
@@ -925,12 +944,6 @@ pnpm --filter @h-ai/ui build
925
944
  pnpm --filter @h-ai/ui test
926
945
  ```
927
946
 
928
- ## Design and interaction acceptance
929
-
930
- Use [hai-ui-design](../cli/templates/skills/hai-ui-design/SKILL.md) for page decisions, [hai-ui](../cli/templates/skills/hai-ui/SKILL.md) for implementation, and [hai-ui-review](../cli/templates/skills/hai-ui-review/SKILL.md) for rendered UI review. See the [shared design guidance](../../.agents/instructions/ui-design.md).
931
-
932
- Tabs support arrow/Home/End navigation, disabled items and one Tab stop. Tables expose sort/loading state and keyboard row activation. Pagination labels follow locale and external page changes update the jump input. Toolbar panels manage focus and view buttons expose selection. Empty/Alert wrap long content. theme.css imports shared tokens; focus follows the current theme and global.css respects reduced motion. Applications still implement filtering, sorting, paging and recovery.
933
-
934
947
  ## License
935
948
 
936
949
  Apache-2.0
package/README.ja.md CHANGED
@@ -241,6 +241,7 @@ components/
241
241
  | コンポーネント | 説明 | 主なプロパティ |
242
242
  | -------------- | ---------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
243
243
  | `Card` | カードコンテナー | `title`, `bordered`, `shadow`, `padding` |
244
+ | `JsonViewer` | JSON ツリービューアー | `value`, `defaultExpandedDepth`, `maxScalarLength`, `showCopy`, `onCopy`;循環参照はプレースホルダーに置換 |
244
245
  | `DataTable` | データテーブル | `data`, `columns`, `keyField`, `loading`, `sortKey`, `sortDir`, `onsort`、`cell` スロット、`onrowclick`(列の `sortable` で並び替え) |
245
246
  | `Accordion` | アコーディオン | `items: AccordionItem[]` |
246
247
  | `Timeline` | タイムライン | `items: TimelineItem[]` |
@@ -636,6 +637,12 @@ components/
636
637
  />
637
638
  ```
638
639
 
640
+ ### フィードバック収集と配布確認
641
+
642
+ フィードバックの `evidence` は脱敏済み資料の内容を表示します。`oncapture(id?)` はページ移動中に画面を閉じ、画像を追加・置換します。`onfileschange` 接続時はブラウザーの無音録画をWebM/MP4添付として確認・削除できます(最大60秒 / 5 MiB、動画は自動マスクされません)。`FeedbackDetail.onreplay` で完全な操作記録を必要時に取得して再生・移動し、ログと環境はページングで取得します。
643
+
644
+ フィードバックの資料部分は独立してスクロールし、操作ボタンを常に表示して展開内容との重なりを防ぎます。`FeedbackList` はアクセシブル名を保持し、ページ見出しはホストが表示して重複を避けます。
645
+
639
646
  ### スタイルの依存関係
640
647
 
641
648
  コンポーネントは TailwindCSS v4 + DaisyUI を使います。アプリの `app.css` に次を設定します:
@@ -916,6 +923,18 @@ Node リクエストと SSR は `core.i18n.runWithLocale(locale, () => handleReq
916
923
 
917
924
  キーは UTF-8 で最大 1024 バイトで、絶対パス、バックスラッシュ、制御文字、ドットセグメントを拒否します。公開 HTTP 一括削除は一度に 1–1000 件です。共通規則はブラウザー対応の `@h-ai/storage/schemas` から参照できます。署名有効期限は整数 1–604800 秒(Node 既定 3600、HTTP 既定 900)。アップロード署名の入力は key/contentType/expiresIn のみで、contentLength/maxSize/metadata/checksum は未対応です。不正入力は HTTP 400、typed client では VALIDATION_FAILED です。FileUpload の制限は選択時の補助であり、実際のオブジェクトはサーバーで検証してください。Node のストリーム/checksum/条件付き書き込みには既定の HTTP エンドポイントがありません。[機能と認可の対応表(中国語)](../storage/README.md#存储输入约束与跨端能力)を参照してください。
918
925
 
926
+ ## デザインと操作の検証
927
+
928
+ 画面設計は [hai-ui-design](../cli/templates/skills/hai-ui-design/SKILL.md)、実装は [hai-ui](../cli/templates/skills/hai-ui/SKILL.md)、実画面の確認は [hai-ui-review](../cli/templates/skills/hai-ui-review/SKILL.md) を参照してください。[共通設計指針](../../.agents/instructions/ui-design.md) も利用できます。
929
+
930
+ Tabs は方向キー・Home/End、無効項目のスキップと単一の Tab 入口に対応します。表は並べ替え・読み込み状態と行のキーボード操作を提供します。ページ切り替えのラベルは言語に従い、外部ページ変更を入力欄に同期します。ツールバーはフォーカスと表示切り替え状態を管理します。Empty/Alert は長文を折り返します。theme.css は共通 tokens を読み込み、global.css は動きを減らす設定に対応します。業務側で検索、並べ替え、ページ切り替えと復旧処理を接続してください。
931
+
932
+ ## エラー表示とログの関連付け
933
+
934
+ HTTP エラーはローカライズ済みの安全な表示に `(traceId: …)` を付け、同じ ID を error.traceId と X-Trace-Id に返します。requestId を traceId として共有し、ブラウザーとサーバーのログを関連付けます。脱機密化した例外・スタック・操作情報はログに残し、内部 cause/ext は公開しません。項目検証は翻訳済みの項目名とメッセージだけを返します。
935
+
936
+ HTTP/UI 境界には core.error.toPublic(error, traceId?)、再翻訳後の表示には core.error.formatMessage(error) を使い、ID を重複追加しません。ログには完全な Error を渡してください。DB ログにはドライバーコード、脱機密化したメッセージ・スタック、表・列を残し、SQL 本文、バインド値と接続認証情報を記録しません。
937
+
919
938
  ## 開発とテスト
920
939
 
921
940
  ```sh
@@ -925,12 +944,6 @@ pnpm --filter @h-ai/ui build
925
944
  pnpm --filter @h-ai/ui test
926
945
  ```
927
946
 
928
- ## デザインと操作の検証
929
-
930
- 画面設計は [hai-ui-design](../cli/templates/skills/hai-ui-design/SKILL.md)、実装は [hai-ui](../cli/templates/skills/hai-ui/SKILL.md)、実画面の確認は [hai-ui-review](../cli/templates/skills/hai-ui-review/SKILL.md) を参照してください。[共通設計指針](../../.agents/instructions/ui-design.md) も利用できます。
931
-
932
- Tabs は方向キー・Home/End、無効項目のスキップと単一の Tab 入口に対応します。表は並べ替え・読み込み状態と行のキーボード操作を提供します。ページ切り替えのラベルは言語に従い、外部ページ変更を入力欄に同期します。ツールバーはフォーカスと表示切り替え状態を管理します。Empty/Alert は長文を折り返します。theme.css は共通 tokens を読み込み、global.css は動きを減らす設定に対応します。業務側で検索、並べ替え、ページ切り替えと復旧処理を接続してください。
933
-
934
947
  ## ライセンス
935
948
 
936
949
  Apache-2.0
package/README.md CHANGED
@@ -241,6 +241,7 @@ components/
241
241
  | 组件 | 描述 | 主要属性 |
242
242
  | ----------- | -------- | ---------------------------------------- |
243
243
  | `Card` | 卡片容器 | `title`, `bordered`, `shadow`, `padding` |
244
+ | `JsonViewer` | JSON 树查看器 | `value`, `defaultExpandedDepth`, `maxScalarLength`, `showCopy`, `onCopy`;循环引用自动替换为占位符 |
244
245
  | `DataTable` | 数据表格 | `data`, `columns`, `keyField`, `loading`, `sortKey`, `sortDir`, `onsort`,`cell` 单元格插槽、`onrowclick`(列 `sortable` 可排序) |
245
246
  | `Accordion` | 手风琴 | `items: AccordionItem[]` |
246
247
  | `Timeline` | 时间线 | `items: TimelineItem[]` |
@@ -635,6 +636,12 @@ components/
635
636
  />
636
637
  ```
637
638
 
639
+ ### 反馈现场与交付检查
640
+
641
+ 反馈的 `evidence` 显示实际已脱敏材料;`oncapture(id?)` 支持隐藏弹窗后跨页补图或替换。接入 `onfileschange` 后提供浏览器原生无声短录屏,停止后作为 WebM/MP4 附件预览或删除(最多 60 秒 / 5 MiB,录屏不自动脱敏)。`FeedbackDetail.onreplay` 按需返回完整页面事件,在“页面回放”播放和定位;日志/环境仍分页读取。
642
+
643
+ 反馈表单的材料内容独立滚动,底部按钮始终可见,展开内容不会穿过操作栏。`FeedbackList` 保留无障碍名称,页面标题由宿主显示,避免管理页重复标题。
644
+
638
645
  ### 样式依赖
639
646
 
640
647
  组件基于 TailwindCSS v4 + DaisyUI。应用层 `app.css` 需要以下配置:
@@ -919,6 +926,18 @@ Node 请求与 SSR 使用 `core.i18n.runWithLocale(locale, () => handleRequest()
919
926
 
920
927
  存储 key 按 UTF-8 最多 1024 字节,并拒绝绝对路径、反斜线、控制字符及点路径段;公开 HTTP 批量删除每次 1–1000 项。`@h-ai/storage/schemas` 提供浏览器安全的共同规则。预签名有效期为整数 1–604800 秒(Node 默认 3600,HTTP 默认 900);HTTP 上传仅接受 key/contentType/expiresIn,不支持 contentLength/maxSize/metadata/checksum。无效输入返回 HTTP 400,typed client 映射 VALIDATION_FAILED。FileUpload 的大小/类型限制仅为前端体验,实际对象须由应用服务端复核。Node 流式读写/checksum/条件写等没有默认 HTTP 端点。完整映射与授权边界见 [存储 API 能力](../storage/README.md#存储输入约束与跨端能力)。
921
928
 
929
+ ## 设计与交互验收
930
+
931
+ 页面设计使用 [hai-ui-design](../cli/templates/skills/hai-ui-design/SKILL.md),组件实现使用 [hai-ui](../cli/templates/skills/hai-ui/SKILL.md),真实界面走查使用 [hai-ui-review](../cli/templates/skills/hai-ui-review/SKILL.md)。[设计约定](../../.agents/instructions/ui-design.md) 说明布局、状态和示例。
932
+
933
+ Tabs 支持方向键/Home/End、禁用项跳过和单一 Tab 入口;表格提供排序与加载状态和行键盘操作;分页导航/输入名称跟随语言,外部页码同步跳页输入;工具栏弹层管理焦点,视图按钮提供选中状态。Empty/Alert 支持长内容换行。theme.css 引入共享 tokens,焦点跟随当前主题,global.css 响应减少动态效果。应用仍需接入实际筛选、排序、分页与失败恢复。
934
+
935
+ ## 错误提示与关联日志
936
+
937
+ HTTP 错误只向用户返回本地化的安全提示,末尾显示 `(traceId: …)`;响应同时包含 `error.traceId` 和 `X-Trace-Id`。框架复用本次 requestId 作为 traceId,前后端日志自动关联。底层异常、堆栈和操作上下文经凭据脱敏后写入日志,不通过 cause/ext 向用户公开。字段校验只返回本地化的字段名和错误。
938
+
939
+ `core.error.toPublic(error, traceId?)` 用于接口/UI 边界;`core.error.formatMessage(error)` 用于重新翻译后的提示,重复调用不会重复追加标识。日志传入完整 Error 对象,不能只记录通用标题或提前 String(error) 丢失上下文。数据库失败记录驱动错误码、消息、堆栈及表/列;SQL 原文、绑定值和连接凭据不进入日志。
940
+
922
941
  ## 开发测试
923
942
 
924
943
  ```sh
@@ -928,12 +947,6 @@ pnpm --filter @h-ai/ui build
928
947
  pnpm --filter @h-ai/ui test
929
948
  ```
930
949
 
931
- ## 设计与交互验收
932
-
933
- 页面设计使用 [hai-ui-design](../cli/templates/skills/hai-ui-design/SKILL.md),组件实现使用 [hai-ui](../cli/templates/skills/hai-ui/SKILL.md),真实界面走查使用 [hai-ui-review](../cli/templates/skills/hai-ui-review/SKILL.md)。[设计约定](../../.agents/instructions/ui-design.md) 说明布局、状态和示例。
934
-
935
- Tabs 支持方向键/Home/End、禁用项跳过和单一 Tab 入口;表格提供排序与加载状态和行键盘操作;分页导航/输入名称跟随语言,外部页码同步跳页输入;工具栏弹层管理焦点,视图按钮提供选中状态。Empty/Alert 支持长内容换行。theme.css 引入共享 tokens,焦点跟随当前主题,global.css 响应减少动态效果。应用仍需接入实际筛选、排序、分页与失败恢复。
936
-
937
950
  ## 许可证
938
951
 
939
952
  Apache-2.0
package/auto-import.d.ts CHANGED
@@ -60,6 +60,7 @@ declare global {
60
60
  const FormField: typeof import('@h-ai/ui')['FormField']
61
61
  const FormLayout: typeof import('@h-ai/ui')['FormLayout']
62
62
  const InfiniteScroll: typeof import('@h-ai/ui')['InfiniteScroll']
63
+ const JsonViewer: typeof import('@h-ai/ui')['JsonViewer']
63
64
  const MessageContainer: typeof import('@h-ai/ui')['MessageContainer']
64
65
  const MessageBoxContainer: typeof import('@h-ai/ui')['MessageBoxContainer']
65
66
  const MessageBoxDialog: typeof import('@h-ai/ui')['MessageBoxDialog']
package/auto-import.js CHANGED
@@ -51,6 +51,7 @@ const UI_COMPONENTS = new Set([
51
51
  'FormField',
52
52
  'FormLayout',
53
53
  'InfiniteScroll',
54
+ 'JsonViewer',
54
55
  'MessageContainer',
55
56
  'MessageBoxContainer',
56
57
  'MessageBoxDialog',
@@ -0,0 +1,214 @@
1
+ <!--
2
+ @component JsonViewer
3
+ =============================================================================
4
+ @h-ai/ui - JsonViewer 组件
5
+ =============================================================================
6
+ JSON 数据查看组件:可折叠树、类型着色(DaisyUI 语义色,跟随主题与暗色模式)、
7
+ 复制按钮、超长文本截断。用于诊断数据、运行快照等任意 JSON 展示场景。
8
+
9
+ 使用 Svelte 5 Runes ($props, $state, $derived, $props)
10
+ =============================================================================
11
+
12
+ @example
13
+ ```ts
14
+ import { mount, unmount } from 'svelte'
15
+ import type { ComponentProps } from 'svelte'
16
+ import { JsonViewer } from '@h-ai/ui'
17
+ const props: ComponentProps<typeof JsonViewer> = { value: { name: 'wf', nested: { list: [1, 2] } } }
18
+ const component = mount(JsonViewer, { target: document.body, props })
19
+ await unmount(component)
20
+ ```
21
+ -->
22
+
23
+ <script lang='ts'>
24
+ import type { DataAttributes, JsonViewerProps } from '../../types.js'
25
+ import { onDestroy } from 'svelte'
26
+ import { uiM } from '../../messages.js'
27
+ import { cn, getDataAttributes } from '../../utils.js'
28
+
29
+ const {
30
+ value,
31
+ defaultExpandedDepth = 0,
32
+ maxScalarLength = 240,
33
+ showCopy = true,
34
+ class: className = '',
35
+ onCopy,
36
+ ...restProps
37
+ }: JsonViewerProps & DataAttributes = $props()
38
+
39
+ const dataAttributes = $derived(getDataAttributes(restProps))
40
+
41
+ /// 循环引用会出现在诊断数据中,渲染和复制前统一替换为占位符而不是抛错。
42
+ function decycle(input: unknown): unknown {
43
+ const seen = new WeakSet<object>()
44
+ function walk(current: unknown): unknown {
45
+ if (typeof current !== 'object' || current === null)
46
+ return current
47
+ if (seen.has(current))
48
+ return '[Circular]'
49
+ seen.add(current)
50
+ if (Array.isArray(current))
51
+ return current.map(walk)
52
+ const next: Record<string, unknown> = {}
53
+ for (const [key, val] of Object.entries(current))
54
+ next[key] = walk(val)
55
+ return next
56
+ }
57
+ return walk(input)
58
+ }
59
+
60
+ const safeValue = $derived(decycle(value))
61
+ const serialized = $derived(JSON.stringify(safeValue, null, 2) ?? 'undefined')
62
+
63
+ let copied = $state(false)
64
+ let copyTimer: ReturnType<typeof setTimeout> | undefined
65
+
66
+ function truncate(text: string): string {
67
+ return text.length > maxScalarLength ? `${text.slice(0, maxScalarLength)}…` : text
68
+ }
69
+
70
+ async function copyValue(event: Event) {
71
+ event.preventDefault()
72
+ event.stopPropagation()
73
+ try {
74
+ await navigator.clipboard.writeText(serialized)
75
+ copied = true
76
+ onCopy?.(serialized)
77
+ clearTimeout(copyTimer)
78
+ copyTimer = setTimeout(() => (copied = false), 2000)
79
+ }
80
+ catch {
81
+ // 剪贴板不可用(非安全上下文或权限拒绝)时静默降级,不打断树浏览。
82
+ }
83
+ }
84
+
85
+ /**
86
+ * 节点自描述:标量直接渲染,容器交给递归片段。
87
+ * @example 模块内部上下文
88
+ * ```ts
89
+ * const node: NodeModel = { key: 'enabled', value: true, depth: 1 }
90
+ * ```
91
+ */
92
+ interface NodeModel {
93
+ key: string | null
94
+ value: unknown
95
+ depth: number
96
+ }
97
+
98
+ function isContainer(v: unknown): v is Record<string, unknown> | unknown[] {
99
+ return typeof v === 'object' && v !== null
100
+ }
101
+
102
+ function containerSize(v: Record<string, unknown> | unknown[]): number {
103
+ return Array.isArray(v) ? v.length : Object.keys(v).length
104
+ }
105
+
106
+ function containerEntries(v: Record<string, unknown> | unknown[]): Array<[string, unknown]> {
107
+ if (Array.isArray(v))
108
+ return v.map((item, index) => [String(index), item] as [string, unknown])
109
+ return Object.entries(v)
110
+ }
111
+
112
+ function typeClass(v: unknown): string {
113
+ if (v === null)
114
+ return 'text-base-content/50'
115
+ switch (typeof v) {
116
+ case 'string': return 'text-success'
117
+ case 'number': return 'text-info'
118
+ case 'boolean': return 'text-warning'
119
+ case 'undefined': return 'text-base-content/50'
120
+ default: return 'text-base-content'
121
+ }
122
+ }
123
+
124
+ function scalarText(v: unknown): string {
125
+ if (v === undefined)
126
+ return 'undefined'
127
+ if (v === null)
128
+ return 'null'
129
+ if (typeof v === 'string')
130
+ return JSON.stringify(truncate(v))
131
+ return truncate(String(v))
132
+ }
133
+
134
+ /** 大容器折叠可显著降低 DOM 数量,200 条以内保持完整交互。 */
135
+ function childKeys(v: Record<string, unknown> | unknown[]): Array<[string, unknown]> {
136
+ return containerSize(v) > 200 ? containerEntries(v).slice(0, 200) : containerEntries(v)
137
+ }
138
+
139
+ onDestroy(() => clearTimeout(copyTimer))
140
+ </script>
141
+
142
+ {#snippet treeNode(node: NodeModel)}
143
+ {#if isContainer(node.value)}
144
+ {#each childKeys(node.value) as [key, child] (key)}
145
+ {#if isContainer(child)}
146
+ <details
147
+ class='group'
148
+ open={node.depth < defaultExpandedDepth}
149
+ data-testid='json-viewer-node'
150
+ >
151
+ <summary class='flex min-w-0 cursor-pointer select-none items-center gap-1 py-0.5 text-base-content/80'>
152
+ <span class='text-base-content/40 group-open:hidden transition-transform' aria-hidden='true'>▶</span>
153
+ <span class='text-base-content/40 hidden group-open:inline transition-transform' aria-hidden='true'>▼</span>
154
+ <span class='font-mono text-xs font-medium'>{key}:</span>
155
+ <span class='font-mono text-xs text-base-content/50'>
156
+ {Array.isArray(child) ? `Array(${containerSize(child)})` : `Object(${containerSize(child)})`}
157
+ </span>
158
+ </summary>
159
+ <div class='ml-3 border-l border-base-content/10 pl-3'>
160
+ {@render treeNode({ key, value: child, depth: node.depth + 1 })}
161
+ </div>
162
+ </details>
163
+ {:else}
164
+ <div class='flex min-w-0 items-baseline gap-1 py-0.5'>
165
+ <span class='font-mono text-xs font-medium text-base-content/80'>{key}:</span>
166
+ <span class='font-mono text-xs {typeClass(child)} [overflow-wrap:anywhere]'>{scalarText(child)}</span>
167
+ </div>
168
+ {/if}
169
+ {/each}
170
+ {:else}
171
+ <div class='flex min-w-0 items-baseline gap-1 py-0.5'>
172
+ <span class='font-mono text-xs {typeClass(node.value)} [overflow-wrap:anywhere]'>{scalarText(node.value)}</span>
173
+ </div>
174
+ {/if}
175
+ {/snippet}
176
+
177
+ <div
178
+ {...dataAttributes}
179
+ class={cn(
180
+ 'flex min-w-0 flex-col gap-2 rounded-container bg-base-200/40 p-3',
181
+ className,
182
+ )}
183
+ data-testid='json-viewer'
184
+ >
185
+ {#if showCopy}
186
+ <div class='flex justify-end'>
187
+ <button
188
+ type='button'
189
+ class='btn btn-ghost btn-xs gap-1 font-normal text-base-content/60'
190
+ data-testid='json-viewer-copy'
191
+ onclick={copyValue}
192
+ >
193
+ {#if copied}
194
+ <svg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke-width='2' stroke='currentColor' class='size-3.5' aria-hidden='true'>
195
+ <path stroke-linecap='round' stroke-linejoin='round' d='M4.5 12.75l6 6 9-13.5' />
196
+ </svg>
197
+ {uiM('json_viewer_copied')}
198
+ {:else}
199
+ <svg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke-width='1.5' stroke='currentColor' class='size-3.5' aria-hidden='true'>
200
+ <path stroke-linecap='round' stroke-linejoin='round' d='M15.75 17.25v3.375c0 .621-.504 1.125-1.125 1.125h-9.75a1.125 1.125 0 01-1.125-1.125V7.875c0-.621.504-1.125 1.125-1.125H6.75a9.06 9.06 0 011.5.124m7.5 10.376h3.375c.621 0 1.125-.504 1.125-1.125V11.25c0-15.043-6.603-8.25-8.25-9.75L15.75 17.25z' />
201
+ </svg>
202
+ {uiM('json_viewer_copy')}
203
+ {/if}
204
+ </button>
205
+ </div>
206
+ {/if}
207
+ <div class='min-w-0 overflow-x-auto font-mono text-xs leading-relaxed'>
208
+ {#if isContainer(safeValue)}
209
+ {@render treeNode({ key: null, value: safeValue, depth: 0 })}
210
+ {:else}
211
+ <span class={typeClass(safeValue)}>{scalarText(safeValue)}</span>
212
+ {/if}
213
+ </div>
214
+ </div>
@@ -0,0 +1,26 @@
1
+ import type { DataAttributes, JsonViewerProps } from '../../types.js';
2
+ type $$ComponentProps = JsonViewerProps & DataAttributes;
3
+ /**
4
+ * JsonViewer
5
+ * =============================================================================
6
+ * @h-ai/ui - JsonViewer 组件
7
+ * =============================================================================
8
+ * JSON 数据查看组件:可折叠树、类型着色(DaisyUI 语义色,跟随主题与暗色模式)、
9
+ * 复制按钮、超长文本截断。用于诊断数据、运行快照等任意 JSON 展示场景。
10
+ *
11
+ * 使用 Svelte 5 Runes ($props, $state, $derived, $props)
12
+ * =============================================================================
13
+ *
14
+ * @example
15
+ * ```ts
16
+ * import { mount, unmount } from 'svelte'
17
+ * import type { ComponentProps } from 'svelte'
18
+ * import { JsonViewer } from '@h-ai/ui'
19
+ * const props: ComponentProps<typeof JsonViewer> = { value: { name: 'wf', nested: { list: [1, 2] } } }
20
+ * const component = mount(JsonViewer, { target: document.body, props })
21
+ * await unmount(component)
22
+ * ```
23
+ */
24
+ declare const JsonViewer: import("svelte").Component<$$ComponentProps, {}, "">;
25
+ type JsonViewer = ReturnType<typeof JsonViewer>;
26
+ export default JsonViewer;
@@ -26,6 +26,7 @@ export { default as Form } from './Form.svelte';
26
26
  export { default as FormField } from './FormField.svelte';
27
27
  export { default as FormLayout } from './FormLayout.svelte';
28
28
  export { default as InfiniteScroll } from './InfiniteScroll.svelte';
29
+ export { default as JsonViewer } from './JsonViewer.svelte';
29
30
  export { default as MessageBoxContainer } from './MessageBoxContainer.svelte';
30
31
  export { default as MessageBoxDialog } from './MessageBoxDialog.svelte';
31
32
  export { default as MessageContainer } from './MessageContainer.svelte';
@@ -34,6 +34,8 @@ export { default as FormField } from './FormField.svelte';
34
34
  export { default as FormLayout } from './FormLayout.svelte';
35
35
  // 无限滚动 / 上拉加载
36
36
  export { default as InfiniteScroll } from './InfiniteScroll.svelte';
37
+ // JSON 树查看器(可折叠、复制、主题自适应)
38
+ export { default as JsonViewer } from './JsonViewer.svelte';
37
39
  // MessageBox 命令式弹框(类似 ElementUI MessageBox)
38
40
  export { default as MessageBoxContainer } from './MessageBoxContainer.svelte';
39
41
  export { default as MessageBoxDialog } from './MessageBoxDialog.svelte';
@@ -12,6 +12,7 @@ export type { AiDocumentDownloadFormat, AiDocumentDownloadRequest, AiDocumentRes
12
12
  export { renderMarkdownDocument } from './document-parse.js';
13
13
  export type { MarkdownDocumentBlock, MarkdownDocumentHtmlBlock, MarkdownDocumentMermaidBlock, MarkdownDocumentParseOptions, MarkdownRenderResult, } from './document-parse.js';
14
14
  export type { AiDocumentEditorProps, MarkdownBlockFormatKind, MarkdownBlockStyleKind, MarkdownCodeBlockItem, MarkdownCodeRunRequest, MarkdownCodeRunResult, MarkdownColorFormatRequest, MarkdownInlineFormatKind, MarkdownOutlineItem, MarkdownRewriteAction, MarkdownRewriteRequest, MarkdownTextAlignKind, MarkdownToolbarDownloadAction, } from './document-types.js';
15
+ export { highlightCode, isLanguageSupported } from './highlight.js';
15
16
  export { parseMarkdown } from './markdown-parse.js';
16
17
  export type { MarkdownParseOptions } from './markdown-parse.js';
17
18
  export { default as MarkdownRenderer } from './MarkdownRenderer.svelte';
@@ -9,6 +9,8 @@ export { default as AiDocumentDownloadMenu } from './AiDocumentDownloadMenu.svel
9
9
  export { default as AiDocumentEditor } from './AiDocumentEditor.svelte';
10
10
  export { downloadAiDocument, resolveDocumentDownloadActions, resolveDocumentMarkdownContent, } from './document-download.js';
11
11
  export { renderMarkdownDocument } from './document-parse.js';
12
+ // Shiki 同步语法高亮(CSS Variables 主题,DaisyUI 自适应)
13
+ export { highlightCode, isLanguageSupported } from './highlight.js';
12
14
  export { parseMarkdown } from './markdown-parse.js';
13
15
  export { default as MarkdownRenderer } from './MarkdownRenderer.svelte';
14
16
  export { default as AiTableEditor } from './table/AiTableEditor.svelte';
@@ -12,6 +12,7 @@
12
12
  import type { DataAttributes } from '../../../types.js'
13
13
  import type { FeedbackAttachmentView, FeedbackEvidenceQuery, FeedbackEvidenceView, FeedbackHistoryView, FeedbackPage, FeedbackPermissions, FeedbackReportView, FeedbackStatusChange } from './feedback-types.js'
14
14
  import { uiM } from '../../../messages.js'
15
+ import { errorMessage } from '../../../toast.svelte.js'
15
16
  import { getDataAttributes } from '../../../utils.js'
16
17
  import FormField from '../../compounds/FormField.svelte'
17
18
  import FormLayout from '../../compounds/FormLayout.svelte'
@@ -22,6 +23,7 @@
22
23
  import Input from '../../primitives/Input.svelte'
23
24
  import Textarea from '../../primitives/Textarea.svelte'
24
25
  import { collectionLabel, evidenceText, feedbackTime, imagePreviewUrl, notificationLabel } from './feedback-functions.js'
26
+ import FeedbackReplay from './FeedbackReplay.svelte'
25
27
 
26
28
  let {
27
29
  report,
@@ -37,6 +39,7 @@
37
39
  onexport,
38
40
  onretry,
39
41
  onattachment,
42
+ onreplay,
40
43
  onclose,
41
44
  class: className = '',
42
45
  ...restProps
@@ -54,6 +57,8 @@
54
57
  onexport?: (report: FeedbackReportView) => void | Promise<void>
55
58
  onretry?: (report: FeedbackReportView) => void | Promise<void>
56
59
  onattachment?: (attachment: FeedbackAttachmentView) => void | Promise<void>
60
+ /** 按需取得完整回放事件;普通材料分页不能代替完整快照。 */
61
+ onreplay?: () => Promise<FeedbackEvidenceView[]>
57
62
  onclose?: () => void
58
63
  class?: string
59
64
  } & DataAttributes = $props()
@@ -72,6 +77,7 @@
72
77
  const tabs = $derived([
73
78
  { key: 'overview', label: uiM('feedback_overview') },
74
79
  { key: 'scene', label: uiM('feedback_scene') },
80
+ { key: 'replay', label: uiM('feedback_replay') },
75
81
  { key: 'logs', label: uiM('feedback_logs') },
76
82
  { key: 'environment', label: uiM('feedback_environment') },
77
83
  { key: 'history', label: uiM('feedback_history') },
@@ -86,7 +92,7 @@
86
92
  await action()
87
93
  }
88
94
  catch (cause) {
89
- actionError = cause instanceof Error ? cause.message : uiM('feedback_action_failed')
95
+ actionError = errorMessage(cause, uiM('feedback_action_failed'))
90
96
  }
91
97
  finally {
92
98
  busy = false
@@ -102,7 +108,7 @@
102
108
  }
103
109
  catch (cause) {
104
110
  if (generation === queryGeneration)
105
- actionError = cause instanceof Error ? cause.message : uiM('feedback_action_failed')
111
+ actionError = errorMessage(cause, uiM('feedback_action_failed'))
106
112
  }
107
113
  finally {
108
114
  if (generation === queryGeneration)
@@ -147,6 +153,10 @@
147
153
  {#if report.commit}<div><dt class='text-base-content/55'>{uiM('feedback_commit')}</dt><dd class='break-all'>{report.commit}</dd></div>{/if}
148
154
  </dl>
149
155
  </div>
156
+ {:else if tab === 'replay'}
157
+ <div class='py-4'>
158
+ {#if onreplay}<FeedbackReplay load={onreplay} />{:else}<p class='text-sm'>{uiM('feedback_replay_empty')}</p>{/if}
159
+ </div>
150
160
  {:else if tab === 'scene' || tab === 'logs' || tab === 'environment'}
151
161
  <div class='space-y-4 py-4'>
152
162
  {#if tab === 'scene'}
@@ -155,6 +165,8 @@
155
165
  <article class='rounded-lg border border-base-content/10 p-3 min-w-0 space-y-2'>
156
166
  <p class='font-medium text-sm break-all'>{attachment.name}</p>
157
167
  {#if attachment.mimeType?.startsWith('image/') && imagePreviewUrl(attachment.url)}<img src={imagePreviewUrl(attachment.url)} alt={attachment.name} class='max-w-full rounded' loading='lazy' referrerpolicy='no-referrer' onerror={() => failedPreviews = [...failedPreviews, attachment.id]} onload={() => failedPreviews = failedPreviews.filter(id => id !== attachment.id)} />{/if}
168
+ {#if attachment.mimeType?.startsWith('video/') && imagePreviewUrl(attachment.url)}<!-- svelte-ignore a11y_media_has_caption (用户上传的无声录屏) -->
169
+ <video src={imagePreviewUrl(attachment.url)} controls preload='metadata' class='max-w-full rounded' aria-label={attachment.name}></video>{/if}
158
170
  {#if failedPreviews.includes(attachment.id)}<p class='text-warning text-sm'>{uiM('feedback_preview_failed')}</p>{/if}
159
171
  {#if attachment.missingReason}<p class='text-warning break-words'>{uiM('feedback_missing')}: {attachment.missingReason}</p>
160
172
  {:else if onattachment}<Button size='sm' variant='ghost' disabled={busy} onclick={() => run(() => onattachment(attachment))}>{uiM('feedback_download')}</Button>{/if}
@@ -14,6 +14,8 @@ type $$ComponentProps = {
14
14
  onexport?: (report: FeedbackReportView) => void | Promise<void>;
15
15
  onretry?: (report: FeedbackReportView) => void | Promise<void>;
16
16
  onattachment?: (attachment: FeedbackAttachmentView) => void | Promise<void>;
17
+ /** 按需取得完整回放事件;普通材料分页不能代替完整快照。 */
18
+ onreplay?: () => Promise<FeedbackEvidenceView[]>;
17
19
  onclose?: () => void;
18
20
  class?: string;
19
21
  } & DataAttributes;