@h-ai/ui 0.1.0-alpha.71 → 0.1.0-alpha.73

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.
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[]` |
@@ -292,7 +293,7 @@ Client validation appears on the first blur and updates as invalid input is corr
292
293
  | ------------ | ----------- | ----------------------------------------------- |
293
294
  | `PageHeader` | Page header | `title`, `description`; supports `actions` slot |
294
295
 
295
- #### Scenes (40)
296
+ #### Scenes (41)
296
297
 
297
298
  ##### Guide (2)
298
299
 
@@ -319,7 +320,7 @@ Client validation appears on the first blur and updates as invalid input is corr
319
320
 
320
321
  Descriptions are optional. Call `prepare()` from `@h-ai/feedback/client` before opening the modal. Connect `onfileschange` to attachment preparation and `onannotate` to image editing that burns annotations into the pixels. Failed submissions retain input and support local export. The list shows the description or server summary and requests pages through `onquerychange`; UI permissions do not replace server authorization. See the [feedback module](../feedback/README.en.md) for integration and offline tools.
321
322
 
322
- ##### IAM authentication (10)
323
+ ##### IAM authentication (11)
323
324
 
324
325
  | Component | Description | Key props |
325
326
  | -------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
@@ -331,6 +332,7 @@ Descriptions are optional. Call `prepare()` from `@h-ai/feedback/client` before
331
332
  | `ResetPasswordForm` | Reset password | `loading`, `errors`, `showCode`, `onsubmit` |
332
333
  | `ChangePasswordForm` | Change password | `loading`, `errors`, `requireOldPassword`, `onsubmit` |
333
334
  | `PasswordInput` | Password input | `value`, `showToggle`, `showStrength`, `minLength` |
335
+ | `ReauthenticationDialog` | Sensitive action confirmation | `open`, `loading`, `error`, `onsubmit`, `onclose` |
334
336
  | `PermGuard` | Permission guard | `permissions`, `mode`, `fallback` |
335
337
  | `UserProfile` | User profile | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
336
338
 
@@ -640,6 +642,8 @@ Defaults match `@h-ai/crypto`: `SM4` for encrypted inputs, `SM3` for hashes, and
640
642
 
641
643
  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.
642
644
 
645
+ 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.
646
+
643
647
  ### Style dependencies
644
648
 
645
649
  Components use TailwindCSS v4 + DaisyUI. Configure application `app.css` as follows:
@@ -822,6 +826,8 @@ AuthPanel disables native form controls during SSR and enables input after clien
822
826
 
823
827
  When an authentication link points to the current complete URL, AuthPanel switches scenes without navigating again, so input entered after returning to login is preserved. Links with a different path, query, or hash use application routing. Modified clicks such as Ctrl/Cmd retain browser behavior.
824
828
 
829
+ `ReauthenticationDialog` renders password confirmation through `open/loading/error/onsubmit/onclose`. The service calls `actions.reauthenticate(password, operation)` and passes the short-lived single-use proof only to the intended request; cancellation, closing and submission clear input, and proofs never grant permissions. `Input` supports `datetime-local`: convert its browser-local value to an explicit timestamp in the service layer.
830
+
825
831
  [完整 IAM 配置 / IAM configuration](../iam/README.en.md)
826
832
 
827
833
  ### Onboarding and help center
@@ -932,6 +938,12 @@ HTTP errors expose localized safe messages followed by `(traceId: …)`, with th
932
938
 
933
939
  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.
934
940
 
941
+ ## Optional interactive challenges
942
+
943
+ AuthPanel uses actions.createCaptcha to automatically create and asynchronously solve self-hosted ALTCHA when config.captcha.enabled, submitting one-use proofs for login/register/sendOtp/passwordReset/renewPassword. The solver is not loaded when disabled. createAuthActions supplies the action; custom actions must preserve captcha and missing actions fail closed. Proofs stay in request memory and are always verified/consumed on the server.
944
+
945
+ See policy, defaults and recovery boundaries in [IAM](../iam/README.en.md).
946
+
935
947
  ## Development and testing
936
948
 
937
949
  ```sh
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[]` |
@@ -292,7 +293,7 @@ components/
292
293
  | -------------- | -------------- | ---------------------------------------------- |
293
294
  | `PageHeader` | ページヘッダー | `title`, `description`、`actions` スロット対応 |
294
295
 
295
- #### Scenes:用途別コンポーネント(40)
296
+ #### Scenes:用途別コンポーネント(41)
296
297
 
297
298
  ##### Guide:案内・ヘルプ(2)
298
299
 
@@ -319,7 +320,7 @@ components/
319
320
 
320
321
  説明は任意です。モーダルを開く前に `@h-ai/feedback/client` の `prepare()` で現場を固定します。`onfileschange` で添付を準備し、`onannotate` で注釈を画像のピクセルに反映します。送信失敗時は入力を保持し、ローカルに出力できます。一覧は説明またはサーバーの要約を表示し、`onquerychange` でページを取得します。UI の権限表示とは別にサーバーの認可が必要です。接続方法とオフラインツールは [feedback モジュール](../feedback/README.ja.md) を参照してください。
321
322
 
322
- ##### IAM:認証(10)
323
+ ##### IAM:認証(11)
323
324
 
324
325
  | コンポーネント | 説明 | 主なプロパティ |
325
326
  | -------------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------ |
@@ -331,6 +332,7 @@ components/
331
332
  | `ResetPasswordForm` | パスワードリセット | `loading`, `errors`, `showCode`, `onsubmit` |
332
333
  | `ChangePasswordForm` | パスワード変更 | `loading`, `errors`, `requireOldPassword`, `onsubmit` |
333
334
  | `PasswordInput` | パスワード入力 | `value`, `showToggle`, `showStrength`, `minLength` |
335
+ | `ReauthenticationDialog` | 機密操作の確認 | `open`, `loading`, `error`, `onsubmit`, `onclose` |
334
336
  | `PermGuard` | 権限ガード | `permissions`, `mode`, `fallback` |
335
337
  | `UserProfile` | ユーザープロフィール | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
336
338
 
@@ -640,6 +642,8 @@ components/
640
642
 
641
643
  フィードバックの `evidence` は脱敏済み資料の内容を表示します。`oncapture(id?)` はページ移動中に画面を閉じ、画像を追加・置換します。`onfileschange` 接続時はブラウザーの無音録画をWebM/MP4添付として確認・削除できます(最大60秒 / 5 MiB、動画は自動マスクされません)。`FeedbackDetail.onreplay` で完全な操作記録を必要時に取得して再生・移動し、ログと環境はページングで取得します。
642
644
 
645
+ フィードバックの資料部分は独立してスクロールし、操作ボタンを常に表示して展開内容との重なりを防ぎます。`FeedbackList` はアクセシブル名を保持し、ページ見出しはホストが表示して重複を避けます。
646
+
643
647
  ### スタイルの依存関係
644
648
 
645
649
  コンポーネントは TailwindCSS v4 + DaisyUI を使います。アプリの `app.css` に次を設定します:
@@ -822,6 +826,8 @@ AuthPanel は SSR 中のフォーム操作を無効にし、クライアント
822
826
 
823
827
  認証リンクが現在の完全な URL を指す場合、AuthPanel は再ナビゲーションせずに画面だけを切り替え、ログインに戻った直後の入力を保持します。パス、クエリー、hash が異なる場合はアプリのルーターに任せます。Ctrl/Cmd などの修飾キーを使ったクリックはブラウザーの動作を維持します。
824
828
 
829
+ `ReauthenticationDialog` は `open/loading/error/onsubmit/onclose` でパスワード確認を表示します。サービスが `actions.reauthenticate(password, operation)` を呼び、短期・一回限りの証明を対象リクエストだけに渡します。取消・終了・送信で入力を消去し、証明自体は権限を付与しません。`Input` の `datetime-local` はブラウザーのローカル時刻のため、サービスで明確なタイムスタンプへ変換して送信します。
830
+
825
831
  [完整 IAM 配置 / IAM configuration](../iam/README.ja.md)
826
832
 
827
833
  ### 初回ガイドとヘルプセンター
@@ -932,6 +938,12 @@ HTTP エラーはローカライズ済みの安全な表示に `(traceId: …)`
932
938
 
933
939
  HTTP/UI 境界には core.error.toPublic(error, traceId?)、再翻訳後の表示には core.error.formatMessage(error) を使い、ID を重複追加しません。ログには完全な Error を渡してください。DB ログにはドライバーコード、脱機密化したメッセージ・スタック、表・列を残し、SQL 本文、バインド値と接続認証情報を記録しません。
934
940
 
941
+ ## 任意の対話チャレンジ
942
+
943
+ AuthPanel は config.captcha.enabled の場合 actions.createCaptcha で自己ホスト ALTCHA を自動生成・非同期求解し、login/register/sendOtp/passwordReset/renewPassword 用の単用証明を送信します。無効時は求解器を読み込みません。createAuthActions は対応済みで、独自動作は captcha を保持し、不足時は通過しません。証明は現在のメモリ内だけに保持し、サーバーで必ず検証・消費します。
944
+
945
+ 方針・既定値・復旧範囲は次を参照: [IAM](../iam/README.ja.md)。
946
+
935
947
  ## 開発とテスト
936
948
 
937
949
  ```sh
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[]` |
@@ -292,7 +293,7 @@ components/
292
293
  | ------------ | -------- | ------------------------------------------- |
293
294
  | `PageHeader` | 页面头部 | `title`, `description`,支持 `actions` 插槽 |
294
295
 
295
- #### 场景组件 Scenes(40 个)
296
+ #### 场景组件 Scenes(41 个)
296
297
 
297
298
  ##### Guide 引导与帮助(2 个)
298
299
 
@@ -319,7 +320,7 @@ components/
319
320
 
320
321
  反馈说明可为空;宿主先用 `@h-ai/feedback/client` 的 `prepare()` 固定现场,再打开弹窗。表单通过 `onfileschange` 准备主动附件、通过 `onannotate` 将标注烧录到图片;受理失败保留输入并可本地导出。列表展示说明或服务端事实摘要,以 `onquerychange` 取得分页数据;界面权限不代替服务端授权。完整接入与离线工具见 [feedback 模块](../feedback/README.md)。
321
322
 
322
- ##### IAM 身份认证(10 个)
323
+ ##### IAM 身份认证(11 个)
323
324
 
324
325
  | 组件 | 描述 | 主要属性 |
325
326
  | -------------------- | ---------- | ----------------------------------------------------- |
@@ -331,6 +332,7 @@ components/
331
332
  | `ResetPasswordForm` | 重置密码 | `loading`, `errors`, `showCode`, `onsubmit` |
332
333
  | `ChangePasswordForm` | 修改密码 | `loading`, `errors`, `requireOldPassword`, `onsubmit` |
333
334
  | `PasswordInput` | 密码输入框 | `value`, `showToggle`, `showStrength`, `minLength` |
335
+ | `ReauthenticationDialog` | 敏感操作再认证 | `open`, `loading`, `error`, `onsubmit`, `onclose` |
334
336
  | `PermGuard` | 权限守卫 | `permissions`, `mode`, `fallback` |
335
337
  | `UserProfile` | 用户资料 | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
336
338
 
@@ -639,6 +641,8 @@ components/
639
641
 
640
642
  反馈的 `evidence` 显示实际已脱敏材料;`oncapture(id?)` 支持隐藏弹窗后跨页补图或替换。接入 `onfileschange` 后提供浏览器原生无声短录屏,停止后作为 WebM/MP4 附件预览或删除(最多 60 秒 / 5 MiB,录屏不自动脱敏)。`FeedbackDetail.onreplay` 按需返回完整页面事件,在“页面回放”播放和定位;日志/环境仍分页读取。
641
643
 
644
+ 反馈表单的材料内容独立滚动,底部按钮始终可见,展开内容不会穿过操作栏。`FeedbackList` 保留无障碍名称,页面标题由宿主显示,避免管理页重复标题。
645
+
642
646
  ### 样式依赖
643
647
 
644
648
  组件基于 TailwindCSS v4 + DaisyUI。应用层 `app.css` 需要以下配置:
@@ -838,6 +842,8 @@ AuthPanel 在 SSR 阶段禁用原生表单控件,客户端挂载并绑定事
838
842
 
839
843
  认证链接指向当前完整 URL 时,AuthPanel 只切换场景并阻止重复导航,返回登录后可立即输入。路径、查询串或 hash 不同时交给应用路由处理;Ctrl/Cmd 等修改键点击保留浏览器行为。
840
844
 
845
+ `ReauthenticationDialog` 只展示密码确认框,通过 `open/loading/error/onsubmit/onclose` 接入服务层。服务调用 `actions.reauthenticate(password, operation)`,拿到短期单次凭据后仅传给本次敏感请求;取消、关闭和提交会清除输入,凭据不提升原有权限。`Input` 支持 `datetime-local`,其值为浏览器本地时间,服务层转换为明确时间戳后提交。
846
+
841
847
  [完整 IAM 配置 / IAM configuration](../iam/README.md)
842
848
 
843
849
  ### 新手引导与帮助中心
@@ -935,6 +941,12 @@ HTTP 错误只向用户返回本地化的安全提示,末尾显示 `(traceId:
935
941
 
936
942
  `core.error.toPublic(error, traceId?)` 用于接口/UI 边界;`core.error.formatMessage(error)` 用于重新翻译后的提示,重复调用不会重复追加标识。日志传入完整 Error 对象,不能只记录通用标题或提前 String(error) 丢失上下文。数据库失败记录驱动错误码、消息、堆栈及表/列;SQL 原文、绑定值和连接凭据不进入日志。
937
943
 
944
+ ## 可选交互挑战
945
+
946
+ AuthPanel 在 config.captcha.enabled 时通过 actions.createCaptcha 自动生成并异步求解自托管 ALTCHA,按 login/register/sendOtp/passwordReset/renewPassword 用途提交单用证明;关闭时不加载求解器。createAuthActions 已提供动作,自定义动作须保留 captcha,缺少动作时不放行。证明仅存在当前请求内存,服务端始终校验与消费。
947
+
948
+ 策略、默认值和恢复边界见 [IAM](../iam/README.md)。
949
+
938
950
  ## 开发测试
939
951
 
940
952
  ```sh
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']
@@ -100,6 +101,7 @@ declare global {
100
101
  const LoginForm: typeof import('@h-ai/ui')['LoginForm']
101
102
  const PasswordInput: typeof import('@h-ai/ui')['PasswordInput']
102
103
  const PermGuard: typeof import('@h-ai/ui')['PermGuard']
104
+ const ReauthenticationDialog: typeof import('@h-ai/ui')['ReauthenticationDialog']
103
105
  const RegisterForm: typeof import('@h-ai/ui')['RegisterForm']
104
106
  const ResetPasswordForm: typeof import('@h-ai/ui')['ResetPasswordForm']
105
107
  const UserProfile: typeof import('@h-ai/ui')['UserProfile']
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',
@@ -91,6 +92,7 @@ const UI_COMPONENTS = new Set([
91
92
  'LoginForm',
92
93
  'PasswordInput',
93
94
  'PermGuard',
95
+ 'ReauthenticationDialog',
94
96
  'RegisterForm',
95
97
  'ResetPasswordForm',
96
98
  'UserProfile',
@@ -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';