@h-ai/ui 1.0.0-beta.30 → 1.0.0-beta.31

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 (48) hide show
  1. package/README.en.md +10 -1183
  2. package/README.ja.md +9 -1182
  3. package/README.md +12 -1183
  4. package/auto-import.d.ts +4 -0
  5. package/auto-import.js +4 -0
  6. package/dist/components/compounds/Popover.svelte +1 -0
  7. package/dist/components/scenes/ai/AiDocumentEditor.svelte +73 -7
  8. package/dist/components/scenes/ai/document-download.js +49 -86
  9. package/dist/components/scenes/ai/document-parse.js +6 -28
  10. package/dist/components/scenes/ai/document-pdf-pages.d.ts +26 -0
  11. package/dist/components/scenes/ai/document-pdf-pages.js +111 -0
  12. package/dist/components/scenes/ai/document-pdf-worker.d.ts +11 -0
  13. package/dist/components/scenes/ai/document-pdf-worker.js +29 -0
  14. package/dist/components/scenes/ai/document-render-pool.d.ts +19 -0
  15. package/dist/components/scenes/ai/document-render-pool.js +20 -0
  16. package/dist/components/scenes/ai/document-render-worker.d.ts +13 -0
  17. package/dist/components/scenes/ai/document-render-worker.js +7 -0
  18. package/dist/components/scenes/ai/document-types.d.ts +2 -0
  19. package/dist/components/scenes/ai/index.d.ts +3 -0
  20. package/dist/components/scenes/ai/index.js +2 -0
  21. package/dist/components/scenes/ai/mind/AiMindMapEditor.svelte +519 -0
  22. package/dist/components/scenes/ai/mind/AiMindMapEditor.svelte.d.ts +8 -0
  23. package/dist/components/scenes/ai/mind/mind-adapter.d.ts +38 -0
  24. package/dist/components/scenes/ai/mind/mind-adapter.js +59 -0
  25. package/dist/components/scenes/ai/mind/mind-types.d.ts +116 -0
  26. package/dist/components/scenes/ai/mind/mind-types.js +1 -0
  27. package/dist/components/scenes/index.d.ts +1 -0
  28. package/dist/components/scenes/index.js +2 -0
  29. package/dist/components/scenes/tools/ArtifactWorkspace.svelte +561 -0
  30. package/dist/components/scenes/tools/ArtifactWorkspace.svelte.d.ts +17 -0
  31. package/dist/components/scenes/tools/ToolWorkspace.svelte +435 -0
  32. package/dist/components/scenes/tools/ToolWorkspace.svelte.d.ts +17 -0
  33. package/dist/components/scenes/tools/artifact-data.d.ts +35 -0
  34. package/dist/components/scenes/tools/artifact-data.js +127 -0
  35. package/dist/components/scenes/tools/artifact-markdown.d.ts +58 -0
  36. package/dist/components/scenes/tools/artifact-markdown.js +308 -0
  37. package/dist/components/scenes/tools/artifact-preview.d.ts +9 -0
  38. package/dist/components/scenes/tools/artifact-preview.js +31 -0
  39. package/dist/components/scenes/tools/index.d.ts +4 -0
  40. package/dist/components/scenes/tools/index.js +3 -0
  41. package/dist/components/scenes/tools/tool-form.d.ts +74 -0
  42. package/dist/components/scenes/tools/tool-form.js +179 -0
  43. package/dist/components/scenes/tools/workspace-types.d.ts +221 -0
  44. package/dist/components/scenes/tools/workspace-types.js +1 -0
  45. package/dist/messages/en-US.json +99 -1
  46. package/dist/messages/ja-JP.json +99 -1
  47. package/dist/messages/zh-CN.json +99 -1
  48. package/package.json +8 -2
package/README.en.md CHANGED
@@ -12,1200 +12,27 @@ HTTP/UI boundaries expose business messages only for explicit valid 4xx statuses
12
12
 
13
13
  ## Quick Start
14
14
 
15
- ### Installation
15
+ Install with pnpm: `pnpm add @h-ai/ui`.
16
16
 
17
- ```bash
18
- npm install @h-ai/ui @h-ai/core
19
- ```
20
-
21
- For a Node server, declare both UI and core as production dependencies so the adapter preserves native logging and runtime dependencies.
22
-
23
- ### 1. Configure application imports in package.json
24
-
25
- ```json
26
- { "imports": { "#lib/*": "./src/lib/*" } }
27
- ```
28
-
29
- ### 2. Configure vite.config.ts
30
-
31
- SvelteKit 3 configures preprocessing, the compiler and the adapter in the Vite plugin; only a plain Svelte/Vite project keeps svelte.config.js.
32
-
33
- Run `vitePreprocess()` or other style/template language transforms before `autoImportHaiUi()`. Auto-import reads the complete Svelte AST and does not accept unprocessed SCSS, Pug or other nonstandard syntax. Its direct markup API remains synchronous.
34
-
35
- ```ts
36
- import { autoImportHaiUi } from '@h-ai/ui/auto-import'
37
- import { haiOptimizeExclude, haiPrebundledDeps } from '@h-ai/ui/vite'
38
- import adapter from '@sveltejs/adapter-node'
39
- import { sveltekit } from '@sveltejs/kit/vite'
40
- import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'
41
- import tailwindcss from '@tailwindcss/vite'
42
- import { defineConfig } from 'vite'
43
-
44
- export default defineConfig({
45
- plugins: [
46
- sveltekit({
47
- preprocess: [vitePreprocess(), autoImportHaiUi()],
48
- compilerOptions: { runes: true },
49
- adapter: adapter(),
50
- paths: { relative: false },
51
- }),
52
- tailwindcss(),
53
- ],
54
- optimizeDeps: { exclude: [...haiOptimizeExclude], include: [...haiPrebundledDeps] },
55
- ssr: { noExternal: ['@h-ai/ui', '@h-ai/kit'], external: ['@h-ai/core', 'sm-crypto'] },
56
- })
57
- ```
58
-
59
- ### 3. Configure src/app.css
60
-
61
- When using Crypto or Kit/IAM, include `sm-crypto@0.5.8` in application production dependencies. CLI projects already do this; for manual setup, run `pnpm add sm-crypto@0.5.8`. The external option alone is insufficient: adapter-node also uses direct production dependencies to preserve native package loading.
62
-
63
- ```css
64
- @import 'tailwindcss';
65
- @import '@h-ai/ui/styles/global.css';
66
- @import '@h-ai/ui/styles/theme.css';
67
- @source "../node_modules/@h-ai/ui/dist/**/*.{svelte,js,ts}";
68
- @source "../../../node_modules/@h-ai/ui/dist/**/*.{svelte,js,ts}";
69
-
70
- @plugin "daisyui" {
71
- themes: light --default, dark --prefersdark, cupcake, emerald, corporate, nord, dracula, night;
72
- }
73
-
74
- /* 图标(可选) */
75
- @plugin "@iconify/tailwind4" {
76
- prefixes: tabler;
77
- }
78
- ```
79
-
80
- > `@source` makes TailwindCSS scan classes in `@h-ai/ui`; without it, component styles are missing. In nested monorepo apps, dependencies may be hoisted to root `node_modules`, so retain both paths.
81
-
82
- ### 4. Use components
17
+ [Open the quick-start guide](../../docs/usage/function/ui.en.md#quick-start).
83
18
 
84
- ```svelte
85
- <script>
86
- import { Button, Input, Card } from '@h-ai/ui'
87
- </script>
19
+ ## Configuration Reference
88
20
 
89
- <Card title="示例表单">
90
- <Input placeholder="请输入用户名" />
91
- <Button variant="primary" onclick={handleSubmit}>提交</Button>
92
- </Card>
93
- ```
94
-
95
- With auto-import enabled, use components directly in templates without individual imports:
96
-
97
- ```svelte
98
- <!-- 无需 import { Button } from '@h-ai/ui' -->
99
- <Button variant="primary">提交</Button>
100
- ```
101
-
102
- > `@h-ai/ui/auto-import` injects all public Svelte components except `toast`, type imports, and `Range` (which conflicts with the DOM `Range` constructor).
103
-
104
- Pages using a subset of components, such as administration screens, can import public component-directory entry points directly. Import theme utilities from the lightweight `@h-ai/ui/theme` entry so theme consumers do not load the root entry's AI and chart components. Use `@h-ai/ui/i18n` for locale utilities in stores without loading components or tour CSS. Check the installed package's exports; do not import its internal `src/` or `dist/` paths.
105
-
106
- The preprocessor imports only components actually used in the template AST; examples in comments, textarea content and script strings do not trigger imports. Script declarations and local each, await and snippet bindings take precedence. Real semicolon-free, multiline and aliased imports are recognized through the syntax tree, without duplicating existing runtime bindings. Type-only component bindings from the root `@h-ai/ui` entry are promoted to values when needed. A conflicting type-only import from another module causes a build error naming the file and component; alias the type, or explicitly import the component under another local name.
107
-
108
- ```ts
109
- import { Card } from '@h-ai/ui/components/compounds/index'
110
- import { Button } from '@h-ai/ui/components/primitives/index'
111
- import { getThemeInfo, THEMES } from '@h-ai/ui/theme'
112
- ```
21
+ This module has no standalone runtime configuration file. See [file ownership](../../docs/usage/configuration/ui.en.md); arguments or response structures are in the [reference](../../docs/usage/function/ui.en.md#call-options).
113
22
 
114
23
  ## Features
115
24
 
116
- ### Purpose, inputs and outputs
117
-
118
- UI has no init/close. Use these fragments in the application component or browser interaction context. Named variables stand for application-provided requests, schemas, resource definitions or options. Follow the corresponding examples for setup and failure handling. Check HaiResult.success and await asynchronous calls.
119
-
120
- | Entry | Use case | Input | Output | Call fragment |
121
- | --- | --- | --- | --- | --- |
122
- | `autoImportHaiUi` | Auto-import | `preprocessed Svelte source and filename through markup` | `PreprocessorGroup; synchronous { code }` | `autoImportHaiUi()` |
123
- | `parseMarkdown` | Safe Markdown | `Markdown source, MarkdownParseOptions?` | `HTML string; raw HTML escaped or allowlisted` | `parseMarkdown("# Hello", { allowHtmlTags: false })` |
124
- | `renderMarkdownDocument` | Editor document model | `Markdown source, MarkdownDocumentParseOptions?` | `MarkdownRenderResult with outline/codeBlocks/blocks` | `renderMarkdownDocument("# Report", { allowHtmlTags: false })` |
125
- | `isLanguageSupported` | Check highlight language | `language name` | `boolean` | `isLanguageSupported("typescript")` |
126
- | `highlightCode` | Highlight code | `code text, supported language` | `escaped/highlighted HTML string` | `highlightCode("const total = 1", "typescript")` |
127
- | `resolveDocumentMarkdownContent` | Fence code content | `text, sourceKind?, language?` | `Markdown string with a safe fence length` | `resolveDocumentMarkdownContent("const x = 1", "code", "ts")` |
128
- | `resolveDocumentDownloadActions` | Download menu | `MarkdownToolbarDownloadAction[]?` | `AiDocumentResolvedDownloadAction[]` | `resolveDocumentDownloadActions([{ id: "markdown", label: "Markdown" }])` |
129
- | `downloadAiDocument` | Download selected format | `AiDocumentDownloadRequest` | `Promise<void>; browser failure rejects, SSR does nothing` | `downloadAiDocument({ actionId: "markdown", content: "# Report", filename: "report.md" })` |
130
- | `createLocaleStore` | Component locale state | `{ defaultLocale?, supportedLocales?, detectBrowser?, persistKey? }` | `locale store with current/set/isSupported` | `createLocaleStore({ defaultLocale: "zh-CN", detectBrowser: false })` |
131
- | `getGlobalLocale` | Read current locale | `none` | `locale string from current context` | `getGlobalLocale()` |
132
- | `setGlobalLocale` | Set browser/startup locale | `locale` | `void; use request context for SSR` | `setGlobalLocale("en-US")` |
133
- | `detectBrowserLocale` | Detect browser locale | `supportedLocales?` | `supported locale or null` | `detectBrowserLocale()` |
134
- | `isLocaleSupported` | Check supported locale | `locale, supportedLocales?` | `boolean` | `isLocaleSupported("ja-JP")` |
135
- | `resolveLocale` | Normalize locale | `locale, supportedLocales?, fallback?` | `supported locale` | `resolveLocale("en")` |
136
- | `interpolate` | Interpolate message | `template string, InterpolationParams` | `string` | `interpolate("Hello {name}", { name: "Ada" })` |
137
- | `getThemeInfo` | Theme metadata | `theme ID` | `ThemeInfo or undefined` | `getThemeInfo("light")` |
138
- | `isDarkTheme` | Dark theme check | `theme ID` | `boolean` | `isDarkTheme("dark")` |
139
- | `normalizeThemeId` | Normalize theme | `candidate theme ID, fallback?` | `supported theme ID` | `normalizeThemeId("unknown", "light")` |
140
- | `normalizeHexColor` | Normalize color | `string or null/undefined` | `six-digit lowercase hex string or null` | `normalizeHexColor("#5765F0")` |
141
- | `resolveThemeTone` | Theme tone | `theme ID` | `light or dark` | `resolveThemeTone("light")` |
142
- | `createThemeBootstrapScript` | Bootstrap theme | `ThemeBootstrapScriptOptions from trusted host config` | `script string for the application HTML shell` | `createThemeBootstrapScript({ storageKey: "theme", defaultThemeId: "light" })` |
143
- | `getThemeInitScript` | Default theme bootstrap | `none` | `script string` | `getThemeInitScript()` |
144
- | `applyTheme` | Apply theme | `theme ID, persist? (default true)` | `void; updates DOM/browser preference` | `applyTheme("dark")` |
145
- | `getCurrentTheme` | Current theme | `none` | `theme ID string` | `getCurrentTheme()` |
146
- | `getSavedTheme` | Saved theme | `fallback theme ID?` | `theme ID string` | `getSavedTheme("light")` |
147
- | `createGuide` | Guide controller | `GuideOptions: tours, articles?, nav?, persistence?, persistKey?` | `GuideController; no init/close` | `createGuide({ tours: [], persistence: "memory" })` |
148
- | `resolveGuideText` | Resolve guide text | `string or translation callback?` | `string` | `resolveGuideText(() => m.help())` |
149
- | `matchPermission` | Permission visibility | `required permission, userPermissions[]` | `boolean; not server authorization` | `matchPermission("orders:read", ["orders:*"])` |
150
- | `setPermissionContext` | Provide permission context | `() => current permissions; component initialization only` | `void` | `setPermissionContext(() => user.permissions)` |
151
- | `usePermission` | Consume permissions | `none; component initialization only` | `PermissionContext with hasPerm/hasAnyPerm/hasAllPerms` | `usePermission()` |
152
- | `createSensitiveActions` | Sensitive confirmation | `standard auth actions providing reauthenticate/publicConfig?` | `SensitiveActions: configure/authorize/submit/cancel` | `createSensitiveActions(actions)` |
153
- | `createSessionRecovery` | In-place session recovery | `none; configure public config and current user afterward` | `SessionRecovery controller` | `createSessionRecovery()` |
154
- | `defineCrud` | Define CRUD | `CrudResource with fields/API callbacks` | `CrudDef for CrudPage` | `defineCrud(resourceDefinition)` |
155
- | `createCrudController` | Manage list state | `CrudDef, { autoLoad? }?` | `controller data/nav/loading/loaded/error/load/reload` | `createCrudController(crud, { autoLoad: false })` |
156
- | `mapPaginated` | Map paginated items | `PaginatedResult<T>, (item,index) => R` | `PaginatedResult<R> retaining total/page/pageSize` | `mapPaginated(page, item => ({ ...item, selected: false }))` |
157
- | `createBrowserNavAdapter` | Browser navigation | `none` | `NavAdapter` | `createBrowserNavAdapter()` |
158
- | `registerClipboardHostWriter` | Register host clipboard | `async text => boolean or null to unregister` | `void` | `registerClipboardHostWriter(null)` |
159
- | `writeTextToClipboard` | Copy and check result | `text: string` | `Promise<boolean>; true only when write succeeds` | `writeTextToClipboard("trace-001")` |
160
- | `cn` | Combine classes | `...string\|boolean\|null\|undefined values` | `string` | `cn("flex", active && "text-primary")` |
161
- | `getDataAttributes` | Forward data attributes | `props record` | `ForwardedDataAttributes` | `getDataAttributes({ "data-testid": "save" })` |
162
- | `generateId` | UI identifier | `prefix?; not a security token generator` | `string` | `generateId("field")` |
163
- | `portal` | Portal a node | `HTMLElement, target HTMLElement or selector?` | `Svelte action result with cleanup` | `portal(node, document.body)` |
164
- | `detectPlatform` | Detect platform | `none` | `Platform` | `detectPlatform()` |
165
- | `isMobile` | Check mobile | `none` | `boolean` | `isMobile()` |
166
- | `isNativeApp` | Check native shell | `none` | `boolean` | `isNativeApp()` |
167
- | `usePlatform` | Reactive platform view | `none; component initialization` | `{ current, isMobile, isApp }` | `usePlatform()` |
168
- | `getVariantClass` | Map theme classes | `Variant, prefix?` | `string class name` | `getVariantClass("primary", "btn")` |
169
- | `getSizeClass` | Map theme classes | `Size, prefix?` | `string class name` | `getSizeClass("sm", "btn")` |
170
- | `getInputSizeClass` | Map theme classes | `Size` | `string class name` | `getInputSizeClass("sm")` |
171
- | `getBadgeVariantClass` | Map theme classes | `Variant` | `string class name` | `getBadgeVariantClass("info")` |
172
- | `getBadgeSizeClass` | Map theme classes | `Size` | `string class name` | `getBadgeSizeClass("sm")` |
173
- | `getAlertVariantClass` | Map theme classes | `Variant` | `string class name` | `getAlertVariantClass("info")` |
174
- | `getProgressVariantClass` | Map theme classes | `Variant` | `string class name` | `getProgressVariantClass("primary")` |
175
- | `useToastFeedback` | Operation feedback | `() => safely localized message, variant?` | `void; source-owned toast lifecycle` | `useToastFeedback(() => errorMessage(error))` |
176
- | `notifySuccess` | Operation feedback | `localized message, duration?` | `toast ID string` | `notifySuccess(m.saved())` |
177
- | `notifyInfo` | Operation feedback | `localized message, duration?` | `toast ID string` | `notifyInfo(m.loading())` |
178
- | `notifyWarning` | Operation feedback | `localized message, duration?` | `toast ID string` | `notifyWarning(m.warning())` |
179
- | `notifyError` | Operation feedback | `unknown error, safe fallback?, duration?` | `toast ID string; internal exception text hidden` | `notifyError(error, m.retry())` |
180
- | `errorMessage` | Operation feedback | `unknown error, safe fallback?` | `safe localized string` | `errorMessage(error, m.retry())` |
181
- | `toast.add` | Shared feedback queue | `localized options/message` | `string item ID` | `toast.add({ message: m.saved(), variant: "success" })` |
182
- | `toast.success` | Shared feedback queue | `localized safe message, duration?` | `string item ID` | `toast.success(m.result())` |
183
- | `toast.info` | Shared feedback queue | `localized safe message, duration?` | `string item ID` | `toast.info(m.result())` |
184
- | `toast.warning` | Shared feedback queue | `localized safe message, duration?` | `string item ID` | `toast.warning(m.result())` |
185
- | `toast.error` | Shared feedback queue | `localized safe message, duration?` | `string item ID` | `toast.error(m.result())` |
186
- | `toast.remove` | Shared feedback queue | `item ID` | `void` | `toast.remove(id)` |
187
- | `toast.clear` | Shared feedback queue | `none` | `void` | `toast.clear()` |
188
- | `message.add` | Shared feedback queue | `localized options/message` | `string item ID` | `message.add({ message: m.saved(), type: "success" })` |
189
- | `message.success` | Shared feedback queue | `localized safe message, duration?` | `string item ID` | `message.success(m.result())` |
190
- | `message.info` | Shared feedback queue | `localized safe message, duration?` | `string item ID` | `message.info(m.result())` |
191
- | `message.warning` | Shared feedback queue | `localized safe message, duration?` | `string item ID` | `message.warning(m.result())` |
192
- | `message.error` | Shared feedback queue | `localized safe message, duration?` | `string item ID` | `message.error(m.result())` |
193
- | `message.remove` | Shared feedback queue | `item ID` | `void` | `message.remove(id)` |
194
- | `message.clear` | Shared feedback queue | `none` | `void` | `message.clear()` |
195
- | `toast.pause` | Toast timing | `toast ID` | `void` | `toast.pause(id)` |
196
- | `toast.resume` | Toast timing | `toast ID` | `void` | `toast.resume(id)` |
197
- | `messageBox.confirm` | Async confirmation | `localized string or MessageBoxOptions` | `Promise<boolean>; host handles confirmation/cancellation` | `messageBox.confirm({ message: m.confirm() })` |
198
- | `messageBox.alert` | Async confirmation | `localized string or MessageBoxOptions` | `Promise<boolean>; host handles confirmation/cancellation` | `messageBox.alert({ message: m.confirm() })` |
199
-
200
- - Forms, tables, dialogs, navigation, charts and application components.
201
- - Authentication, CRUD, AI content, onboarding and a help center.
202
- - Svelte 5, themes, responsive layouts and Chinese/English/Japanese component messages.
203
-
204
- Markdown underline and highlight markers support escaping; unclosed markers remain text. Toasts and document downloads handle unusually long text without repeated scanning, while trace identifiers remain hidden by default.
205
-
206
- ### data-\* attribute forwarding
207
-
208
- Public Svelte components forward caller-supplied `data-*` attributes to their root or primary interactive element for tests, analytics, and automation. Other unknown attributes are not forwarded.
209
-
210
- ```svelte
211
- <Button data-testid='save-button' data-analytics-id='settings.save'>保存</Button>
212
- <Input data-testid='username-input' bind:value={username} />
213
- <Modal data-testid='confirm-modal' bind:open={open}>...</Modal>
214
- ```
215
-
216
- No extra button, input, or overlay wrappers are needed just for `data-testid`.
217
-
218
- ### Component-family inputs, events and outputs
219
-
220
- These families cover the interaction categories in the component catalog. Supply application-owned m, rows, user, controllers and callbacks. Display components render DOM; interactive components report through bindings/callbacks and do not grant server authorization. See Examples, catalog notes and the UI skill for complete compositions. Exported Props types constrain further options.
221
-
222
- | Component family | Input | Output/events | Example fragment |
223
- | --- | --- | --- | --- |
224
- | Button / IconButton / BareButton | variant, size, loading, disabled; icon/snippet; onclick | click event; loading/disabled block repeated action | `<Button loading={saving} onclick={save}>{m.save()}</Button>` |
225
- | Input / BareInput / Textarea / PasswordInput | type, value, label/validation props | bind:value; input/change/focus events; file input exposes FileList | `<Input bind:value={draft} required />` |
226
- | Select / Radio / Range / Rating / Combobox | options or min/max/step, current value | bound selected value and selection callbacks | `<Select options={options} bind:value={selected} />` |
227
- | Checkbox / Switch / ToggleCheckbox / ToggleInput / ToggleRadio | checked/name/label, disabled | bind:checked and change events | `<Checkbox bind:checked={enabled} label={m.enabled()} />` |
228
- | Form / FormLayout / FormField / TagInput | columns, labels, error/hint, tags, submit callback | validated submit event, tag changes, accessible field association | `<Form onsubmit={save}><FormField label={m.name()}><Input bind:value={name} /></FormField></Form>` |
229
- | Modal / Drawer / Popover / Dropdown / Tooltip / Calendar | open, trigger/content snippets, dimensions, selected value | bound open/selection; focus handling and close actions | `<Modal bind:open={open} title={m.details()}>{m.content()}</Modal>` |
230
- | DataTable / TableToolbar / Pagination / FilterBar | rows, columns, total/page, draft search/filter, loading | row/sort/page/query callbacks; host performs the request | `<DataTable {columns} data={rows} sortKey={sortKey} sortDir={sortDir} onsort={sortRows} />` |
231
- | Tabs / Breadcrumb / Steps / BottomNav / AppBar | items/current key, links, titles and action snippets | selected key/navigation callbacks; host owns routing | `<Tabs {items} bind:active={activeTab} />` |
232
- | Alert / Badge / Avatar / Tag / Spinner / Progress / Skeleton / Empty / Result | status/variant/value/text/image and state props | presentational DOM; tag/alert close callbacks when enabled | `<Progress value={completed} max={total} />` |
233
- | WorkspaceLayout / PageHeader / SettingsLayout / SettingsModal | title, sections, active key, leading/actions/footer/children | layout DOM; selection/open callbacks; no business writes | `<WorkspaceLayout title={m.title()}>{m.content()}</WorkspaceLayout>` |
234
- | FileUpload / ImageUpload / AvatarUpload / FileList | accept/size limits, File values, uploadHandler, files | selected files/progress/result URL and delete/download callbacks | `<ImageUpload bind:value={imageUrl} uploadHandler={uploadImage} />` |
235
- | AuthPanel / AuthShell / LoginForm / RegisterForm / password forms / PermGuard | public IAM config, standard actions, errors, permission context | authenticated/submit/reset callbacks; server still authorizes | `<AuthPanel {config} {actions} />` |
236
- | UserProfile / SensitiveOperationsForm / ReauthenticationDialog / SessionRecoveryDialog | profile or operations, async submit, current controller/state | UserProfile closes only on true; other confirmations report explicit completion | `<UserProfile {user} editable onsubmit={saveProfile} />` |
237
- | CrudPage / CrudFilterBar / CrudEditPanel / CrudDetailPanel / CrudDeleteConfirm | CrudDef, data/nav, loading/error/permissions, API callbacks | resource-bound query/edit/delete callbacks; server enforces resource access | `<CrudPage {crud} data={controller.data} nav={controller.nav} />` |
238
- | MarkdownRenderer / AiDocumentEditor / AiTableEditor / AiDocumentDownloadMenu | content or columns/rows, action callbacks, safe HTML options | Markdown HTML, content/cell changes and explicit download/run requests | `<MarkdownRenderer content={markdown} allowHtmlTags={false} />` |
239
- | EncryptedInput / HashDisplay / SignatureDisplay | plaintext/hash/signature, algorithm label, real onencrypt callback | display DOM; bound encryptedValue only after current request succeeds | `<EncryptedInput bind:value={plain} bind:encryptedValue={cipher} onencrypt={encrypt} />` |
240
- | FeedbackModal / FeedbackForm / FeedbackList / FeedbackDetail / FeedbackScreenshot | prepared evidence, attachments, rows/report, permissions and actions | submission/query/status/export/retry/annotation callbacks | `<FeedbackForm attachments={attachments} onsubmit={submitFeedback} />` |
241
- | Chart / DashboardGrid / MetricCard / ReportCard | chart data/preset and raw chart props; metrics and loading state | rendered chart/dashboard; native chart callbacks pass through | `<MetricCard title={m.revenue()} value={revenue} trend={growth} />` |
242
- | GuideHost / HelpCenter | GuideController, locale/scope, articles/tours | onboarding/help UI; start/close callbacks and nonsensitive preferences | `<GuideHost {guide} scope={user.id} locale={locale} />` |
243
-
244
- ### Component architecture
245
-
246
- Three layers (primitives → compounds → scenes):
247
-
248
- ```
249
- components/
250
- ├── primitives/ # Indivisible base UI elements
251
- ├── compounds/ # Primitives + Bits UI headless composition
252
- └── scenes/ # Complete UI workflows for business scenarios
253
- ├── ai/ # AI documents / spreadsheets / Markdown preview
254
- ├── app/ # Settings / feedback / themes / language
255
- ├── crud/ # CRUD pages / drawers / filters / delete confirmation
256
- ├── iam/ # Authentication
257
- ├── storage/ # Storage management
258
- └── crypto/ # Cryptographic display
259
- ```
260
-
261
- ### Component catalog
262
-
263
- #### Primitives
264
-
265
- | Component | Description | Key props |
266
- | ---------------- | ------------------- | ------------------------------------------------------------------------------ |
267
- | `Button` | Button | `variant`, `size`, `loading`, `disabled`, `outline`, `circle` |
268
- | `IconButton` | Icon button | `icon: trusted SVG string \| Snippet`, `variant`, `size`, `tooltip`, `loading` |
269
- | `BareButton` | Unstyled button | `class`, `ariaLabel`, `role`, `tabindex` |
270
- | `Input` | Input | `type`, `value`, `size`, `error`, `validationMessage` |
271
- | `BareInput` | Unstyled input | `type`, `class`, `accept`, `multiple` |
272
- | `Textarea` | Text area | `value`, `rows`, `size`, `autoResize`, `error` |
273
- | `Select` | Select | `options`, `value`, `placeholder`, `size`, `clearable`, `filterable` |
274
- | `Checkbox` | Checkbox | `checked`, `label`, `size`, `indeterminate` |
275
- | `Switch` | Switch | `checked`, `label`, `size` |
276
- | `Radio` | Radio group | `options`, `value`, `direction`, `size` |
277
- | `ToggleCheckbox` | Native switch input | `checked`, `name`, `onchange` |
278
- | `ToggleInput` | Native toggle input | `checked`, `name` |
279
- | `ToggleRadio` | Native radio input | `checked`, `name`, `onchange` |
280
- | `Range` | Slider | `value`, `min`, `max`, `step` |
281
- | `Rating` | Rating | `value`, `max` |
282
- | `Badge` | Badge | `variant`, `size`, `outline` |
283
- | `Avatar` | Avatar | `src`, `name`, `size`, `shape`, `ring` |
284
- | `Tag` | Tag | `text`, `variant`, `size`, `closable` |
285
- | `Spinner` | Loading animation | `size`, `variant` |
286
- | `Progress` | Progress bar | `value`, `max`, `variant`, `striped`, `animated` |
287
-
288
- `Checkbox`, `Switch` and `Radio` default to the theme primary color, and their checked states follow the current DaisyUI theme; `Checkbox` colors can be overridden with a `checkbox-*` class.
289
-
290
- For `BareInput` with `type="file"`, read `event.currentTarget.files` in `onchange` and leave the file path `value` unbound. Other input types support `bind:value`.
291
-
292
- #### Compounds
293
-
294
- ##### Forms
295
-
296
- | Component | Description | Key props |
297
- | ----------- | -------------- | -------------------------------------------- |
298
- | `Form` | Form container | `columns`, `labelPosition`, `labelWidth`, `loading`, `disabled`, `onsubmit` |
299
- | `FormField` | Form field | `label`, `for`, `colSpan`, `labelPosition`, `error`, `hint`, `required` |
300
- | `FormLayout` | Form layout | `columns`, `labelPosition`, `labelWidth` |
301
- | `TagInput` | Tag input | `tags`, `maxTags`, `allowDuplicates`, `size` |
302
-
303
- ##### Form layouts and validation
304
-
305
- `Form` and `FormLayout` (for native `<form>` elements) share `columns={1 | 2}`, `labelPosition="top" | "left"` and `labelWidth` (default `8rem`). Defaults are one column and stacked labels. Two columns collapse below a container width of `36rem`; inline labels stack below `28rem`.
306
-
307
- `FormField.colSpan` defaults to `'auto'`: textareas, file/image uploads, TagInput and multiple Combobox controls span both columns. Use `1` or `2` to override, or mark a custom wide control with `data-form-wide`. Non-field content, including headings, error summaries and actions, spans the full row. Fields may override `labelPosition` / `labelWidth`.
308
-
309
- Labels connect to nested UI controls automatically; use `<FormField for="control-id">` for explicit IDs or native controls. Errors and hints use `aria-describedby`, invalid controls use `aria-invalid`, and field errors appear once. `label` / `error` / `hint` accept strings or deferred translation functions.
310
-
311
- `Input`, `Textarea`, `Select` and `PasswordInput` provide Chinese/English/Japanese native validation messages. `validationMessage` overrides failures without keeping valid input invalid. Sync locale with the UI `setGlobalLocale` / `createLocaleStore` to update visible validation errors immediately. `Textarea` supports `minlength` / `maxlength`; `Select` supports `name`, required validation and FormData serialization.
312
-
313
- Field errors appear through Toast. Submitting the same invalid input again shows the error even after the previous notification was dismissed or expired. Correcting input clears the stale notification. Controls retain error borders, `aria-invalid` and linked screen-reader descriptions.
314
-
315
- Text controls validate on blur after input and update errors as input is corrected. Pristine empty fields validate on submit, so leaving default focus does not shift actions. CRUD create/edit forms also validate on blur after input or on submit, honor custom messages and reset validation when reopened. `Select` validates when focus leaves both its trigger and options. `PasswordInput.minLength` enforces length and informs strength; omitting it leaves login password length unrestricted while strength uses an eight-character baseline.
316
-
317
- `UserProfile.fieldConstraints` accepts per-field `required`, `minlength`, `maxlength`, `pattern` and `validationMessage` (`pattern` applies to single-line inputs), so application rules such as username formats share blur validation. `validationMessage` also accepts a deferred translation function.
318
-
319
- `UserProfile.onsubmit` must return `true` to confirm a successful save, or `false` to keep the editor and draft. Thrown errors also keep editing open and use the shared Toast feedback. Cancel restores the saved values from `user`.
320
-
321
- `CrudEditPanel.onsubmit` receives only writable fields declared by the form. Fields marked `readonly` are omitted when editing and remain available when creating. Primary keys, related display values and audit timestamps are not copied from the entire row. Null values, `false` and `0` are preserved. Keep strict schema validation on the server.
322
-
323
- `LoginForm`, `RegisterForm`, `ChangePasswordForm`, `ForgotPasswordForm`, `ResetPasswordForm`, `AuthPanel`, `UserProfile` and `FeedbackModal` accept the same layout options. Pass them through `CrudPage.form` or directly to `CrudEditPanel`. CRUD fields support `colSpan` and deferred `validation.message`. Buttons and Enter both validate before submission; corrections clear errors. Server validation remains required.
324
-
325
- ```svelte
326
- <!-- m、save、name、notes 为应用自己的翻译、提交回调和状态 -->
327
- <Form columns={2} labelPosition="left" labelWidth="6rem" onsubmit={save}>
328
- <FormField label={() => m.name()} required>
329
- <Input name="name" bind:value={name} required />
330
- </FormField>
331
- <FormField label={() => m.notes()}>
332
- <Textarea name="notes" bind:value={notes} />
333
- </FormField>
334
- <Button type="submit">{m.save()}</Button>
335
- </Form>
336
- ```
337
-
338
- ##### Feedback
339
-
340
- | Component | Description | Key props |
341
- | ---------------- | --------------- | ------------------------------------------------- |
342
- | `Alert` | Alert | `variant`, `title`, `dismissible` |
343
- | `ToastContainer` | Toast container | Place globally and use with the `toast` singleton |
344
-
345
- ##### Overlays
346
-
347
- | Component | Description | Key props |
348
- | --------- | ------------------- | ---------------------------------------------------------------------------- |
349
- | `Modal` | Modal with dialog semantics, focus trap and restoration | `open`, `title`, `size`, `radius`, `bodyOverflow`, `showClose` |
350
- | `Drawer` | Drawer | `open`, `position`, `title`, `size`, `width`, `resizable`, `widthStorageKey` |
351
- | `Confirm` | Confirmation dialog | `open`, `title`, `message`, `variant`, `onconfirm` |
352
- | `Popover` | Popover | `open`, `position`, `trigger`, `offset`, `portal` |
353
-
354
- `Popover` renders in `body` by default. In `click` mode, Enter or Space opens the panel and moves focus into it. Escape closes the panel and returns focus to the trigger. Use `portal={false}` to render inline.
355
-
356
- Inside a Modal or Drawer, portal controls participate in the owning dialog's Tab and Shift+Tab order. Closing the Popover removes that registration and restores focus to its trigger.
357
-
358
- ##### Data display
359
-
360
- | Component | Description | Key props |
361
- | ----------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
362
- | `Card` | Card container | `title`, `bordered`, `shadow`, `padding` |
363
- | `JsonViewer` | JSON tree viewer | `value`, `defaultExpandedDepth`, `maxScalarLength`, `showCopy`, `onCopy`; circular references are replaced with a placeholder |
364
- | `DataTable` | Data table | `data`, `columns`, `keyField`, `loading`, `sortKey`, `sortDir`, `onsort`; `cell` slot and `onrowclick` (`sortable` columns support sorting) |
365
- | `Accordion` | Accordion | `items: AccordionItem[]` |
366
- | `Timeline` | Timeline | `items: TimelineItem[]` |
367
-
368
- ##### Bits UI headless interactions
369
-
370
- | Component | Description | Key props |
371
- | ------------ | ----------------------------------- | ----------------------------------------------------------- |
372
- | `Combobox` | Searchable select (single/multiple) | `options`, `value`, `multiple`, `placeholder`, `size` |
373
- | `Calendar` | Standalone calendar | `value: DateValue`, `minValue`, `maxValue` |
374
- | `DatePicker` | Date input with popover | `value: DateValue`, `minValue`, `maxValue`, `error`, `size` |
375
-
376
- > Dates use `DateValue` / `CalendarDate` from `@internationalized/date`.
377
-
378
- ##### Mobile / enhanced interactions
379
-
380
- | Component | Description | Key props |
381
- | ---------------- | ------------------- | ------------------------------------------------------ |
382
- | `ActionSheet` | Bottom action sheet | `open`, `title`, `items`, `cancelText`, `onselect` |
383
- | `AppBar` | Top navigation | `title`, `backHref`, `onback`, `fixed`, `safeArea` |
384
- | `BottomNav` | Bottom navigation | `items`, `active`, `centered`, `maxWidth` |
385
- | `InfiniteScroll` | Infinite scrolling | `loading`, `finished`, `threshold`, `onload` |
386
- | `PullRefresh` | Pull to refresh | `refreshing`, `threshold`, `onrefresh` |
387
- | `SafeArea` | Safe area container | `top`, `bottom`, `left`, `right` |
388
- | `SwipeCell` | Swipe actions | `leftActions`, `rightActions`, `threshold`, `onaction` |
389
-
390
- ##### Navigation
391
-
392
- | Component | Description | Key props |
393
- | ------------ | ------------------------------- | ---------------------------------------------------------------------------------------------------------- |
394
- | `Tabs` | Tabs | `items`, `active`, `type`, `size`, `lazy`, `onactivate` |
395
- | `Pagination` | Pagination (shared table style) | `page`, `total`, `pageSize`, `showTotal`, `showJumper`, `showSizeChanger`, `showPageInfo`, `showFirstLast` |
396
- | `Breadcrumb` | Breadcrumbs | `items`, `separator` |
397
- | `Steps` | Steps | `items`, `current`, `direction`, `clickable` |
398
- | `Dropdown` | Dropdown menu | `items`, `trigger`, `triggerClass`, `position` |
399
- | `Tooltip` | Tooltip | `content`, `position`, `delay`, `portal` (use inside overflow-clipped containers) |
400
-
401
- `Dropdown` renders the menu in `body` in `click` and `hover` modes. In `manual` mode, toggle `dropdown-open` through `class` to control the inline menu.
402
-
403
- ##### State placeholders
404
-
405
- | Component | Description | Key props |
406
- | ---------- | ----------- | ------------------------------------- |
407
- | `Skeleton` | Skeleton | `variant`, `width`, `height`, `count` |
408
- | `Empty` | Empty state | `title`, `description`, `icon` |
409
- | `Result` | Result page | `status`, `title`, `description` |
410
-
411
- ##### Page-level
412
-
413
- | Component | Description | Key props |
414
- | ------------ | ----------- | ----------------------------------------------- |
415
- | `PageHeader` | Page header | `title`, `description`; supports `actions` slot |
416
-
417
- #### Scenes
418
-
419
- ##### Code workspace
420
-
421
- Use `CodeWorkspace` to browse read-only source files. A directory listing and a file reader are enough to get started. The directory callback receives `null` for the root. Opening a file creates or reuses a tab keyed by file ID and version. Switching tabs restores the cursor and scroll position for recently viewed files.
422
-
423
- ```svelte
424
- <script lang="ts">
425
- import type { CodeWorkspaceSource } from '@h-ai/ui/components/scenes/code/index'
426
- import { CodeWorkspace } from '@h-ai/ui/components/scenes/code/index'
427
-
428
- const source: CodeWorkspaceSource = {
429
- listChildren: () => [{ kind: 'file', id: 'readme', name: 'README.md' }],
430
- readFile: () => ({ text: '# Hello', language: 'markdown' }),
431
- }
432
- </script>
433
-
434
- <CodeWorkspace {source} />
435
- ```
436
-
437
- Supply `source.search` for filename and workspace content search, and return `nextCursor` when another page is available. File and folder `markers` can show risk and Git state. Return `annotations` from `readFile` to mark lines or ranges. Use the `inspector` and `selectionActions` snippets to render the side panel and actions for the selected code. See the [code workspace guide](../../docs/usage/development/ui.md#代码工作区).
438
-
439
- Vite loads Monaco and its same-origin workers on demand in the browser. The editor follows the Hai theme by default and supports presets and custom palettes. Monaco editors on the same page share a theme. Mobile devices and editor load failures use a plain-text view.
440
-
441
- Use the `annotationIcon` snippet to render a gutter icon. On hover, `hoverText` displays plain text, or `annotationHover` renders a custom component when `hoverText` is omitted. Press Enter to enter the popup and Escape to close it.
442
-
443
- ##### Guide
444
-
445
- | Component | Description | Key props |
446
- | --- | --- | --- |
447
- | `GuideHost` | First-use invitations, tours and help dialog host | `guide`, `locale`, `scope`, `autoStart` |
448
- | `HelpCenter` | Standalone searchable help center | `articles`, `tours`, `locale`, `selectedId`, `onstart` |
449
-
450
- ##### App
451
-
452
- | Component | Description | Key props |
453
- | ------------------ | ---------------------------------------------- | -------------------------------------------------------- |
454
- | `FeedbackModal` | Feedback modal | `open`, `onsubmit` |
455
- | `FeedbackForm` | Standalone feedback form | `attachments`, `evidenceSummary`, `onsubmit`, `onfileschange` |
456
- | `FeedbackList` | Server pagination, filters and processing actions | `data`, `query`, `permissions`, `onquerychange`, `onstatus` |
457
- | `FeedbackDetail` | Diagnostic evidence, history and exports | `report`, `evidence`, `attachments`, `history`, `webhook`, `onretry`, `onexport` |
458
- | `FeedbackScreenshot` | Image preview, highlighting and masking | `attachment`, `onannotate` |
459
- | `SettingsModal` | Settings modal | `open`, `onclose` |
460
- | `SettingsLayout` | Settings layout (section navigation + content) | `title`, `description`, `sections`, `active`, `onselect` |
461
- | `LanguageSwitch` | Language switcher | No props required |
462
- | `ThemeColorPicker` | Theme color picker | `value`, `presets`, `onchange` |
463
- | `ThemeSelector` | Full theme selector | No props required |
464
- | `ThemeToggle` | Light/dark toggle | No props required |
465
-
466
- Pass the type: webhook task from report jobs into FeedbackDetail.webhook to show status, attempts and safe error codes; onretry calls the authenticated retry API. The Business evidence tab paginates kind: business, and archives download from the scene tab.
467
-
468
- 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.
469
-
470
- ##### IAM authentication
471
-
472
- | Component | Description | Key props |
473
- | -------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
474
- | `AuthPanel` | Configuration driven authentication | `config`, `actions`, `loginHeader/loginFields/loginFooter`, `registerHeader/registerFields/registerFooter` |
475
- | `AuthShell` | Auth page layout (centered card / split columns) | `variant`, `title`, `subtitle`, `brandTitle`, `brandText`, `illustration`, `description`, `highlights` |
476
- | `LoginForm` | Login form | `loading`, `errors`, `showForgotPassword`, `onsubmit` |
477
- | `RegisterForm` | Registration form | `loading`, `errors`, `fields`, `onsubmit` |
478
- | `ForgotPasswordForm` | Forgot password | `mode`, `loading`, `errors`, `onsubmit` |
479
- | `ResetPasswordForm` | Reset password | `loading`, `errors`, `showCode`, `onsubmit` |
480
- | `ChangePasswordForm` | Change password | `loading`, `errors`, `requireOldPassword`, `onsubmit` |
481
- | `PasswordInput` | Password input | `value`, `showToggle`, `showStrength`, `minLength` |
482
- | `ReauthenticationDialog` | Sensitive action confirmation | `open`, `loading`, `error`, `onsubmit`, `onclose` |
483
- | `PermGuard` | Permission guard | `permissions`, `mode`, `fallback` |
484
- | `UserProfile` | User profile | `user`, `editable`, `fields`, `avatarAccept`, `avatarHint`, `onsubmit` |
485
- | `SessionRecoveryDialog` | In-place session recovery | `recovery`, `actions` |
486
- | `SensitiveOperationsForm` | Permission operation editor | `operations`, `onsubmit`, `ondone` |
487
-
488
- ##### Storage
489
-
490
- | Component | Description | Key props |
491
- | -------------- | ------------- | ------------------------------------------------------------ |
492
- | `FileUpload` | File upload | `accept`, `maxSize`, `maxFiles`, `multiple`, `uploadHandler` |
493
- | `ImageUpload` | Image upload | `value`, `accept`, `maxSize`, `aspectRatio`, `uploadHandler` |
494
- | `AvatarUpload` | Avatar upload | `value`, `size`, `maxSize`, `fallback`, `uploadHandler` |
495
- | `FileList` | File list | `files`, `layout`, `showDelete`, `showDownload` |
496
-
497
- Upload components do not embed presigning, headers, or PUT/POST protocols. Applications call their service through `uploadHandler(file, { signal, onProgress })` and return `{ url?, response? }`. Image/avatar uploads require a displayable `url`. Without a handler, `FileUpload` only selects files, and image/avatar components generate local previews only.
498
-
499
- ##### Crypto display
500
-
501
- Input changes immediately clear `encryptedValue`; only successful results for current input are restored. Clearing, callback replacement, and unmounting invalidate old requests. Failures show built-in errors and leave ciphertext empty. Submit encrypted inputs only when current ciphertext is nonempty.
502
-
503
- Callers must connect `EncryptedInput` to a real encryption service through `onencrypt`; `algorithm` describes that service's algorithm only. Without a callback, the component shows unavailability and generates no ciphertext, with no Base64 fallback.
504
-
505
- | Component | Description | Key props |
506
- | ------------------ | ----------------- | ------------------------------------------------------- |
507
- | `EncryptedInput` | Encrypted input | `value`, `encryptedValue`, `algorithm`, `showEncrypted` |
508
- | `HashDisplay` | Hash display | `value`, `algorithm`, `copyable`, `truncate` |
509
- | `SignatureDisplay` | Signature display | `signature`, `publicKey`, `algorithm`, `verified` |
510
-
511
- Defaults match `@h-ai/crypto`: `SM4` for encrypted inputs, `SM3` for hashes, and `SM2` for signatures.
512
-
513
- ##### AI documents and spreadsheets
514
-
515
- | Component | Description | Key props / capabilities |
516
- | ------------------------ | ---------------------- | ---------------------------------------------------------------------------------------------------------- |
517
- | `MarkdownRenderer` | Markdown renderer | `content`, `fontSize`, `allowHtmlTags`, `showCopyButton`, `enableHighlight` |
518
- | `AiDocumentDownloadMenu` | Document download menu | `actions`, `ondownload` |
519
- | `AiDocumentEditor` | AI document editor | `content`, `fontSize`, `allowHtmlTags`, `showRunButton`, `showCodePreviewToggle`, `allowUnsafeCodePreview` |
520
- | `AiTableEditor` | AI spreadsheet editor | `columns`, `rows`, `editable`, `ondownload` |
521
-
522
- > `AiDocumentEditor` permits only built-in Markdown preview by default. High-risk HTML / JS / CSS previews require explicit `allowUnsafeCodePreview` or controlled results from `oncoderun`.
523
- >
524
- > Mermaid works out of the box: ` ```mermaid ` blocks in documents (`sourceKind='document'`) render automatically in reading mode. Code mode (`sourceKind='code'` + `showCodePreviewToggle`) supports code/preview switching. Mermaid uses `securityLevel: 'strict'` and sanitized SVG without `allowUnsafeCodePreview`.
525
- >
526
- > `MarkdownRenderer` and `AiDocumentEditor` also support presentation options:
527
- >
528
- > - `fontSize` accepts a `number` in px or any CSS length such as `1.125rem`.
529
- > - `allowHtmlTags` is off by default; when enabled, tags such as `<b>` / `<i>` / `<u>` / `<mark>` use a safe allowlist, with dangerous tags/attributes still sanitized.
530
- > - Text entities in safe HTML retain one level of meaning, so quotes, comparison operators and `&` in configuration snippets remain readable. Encoded tags remain text and are never reparsed as markup.
531
- > - HTML code blocks such as `<pre><code class="language-yaml">` also receive safely rebuilt highlighting and copy buttons. Input styles and events are discarded. Supported languages include YAML, TypeScript, Shell, PowerShell, dotenv, Nginx, Dockerfile and Svelte.
532
- > - Raw `<img>` tags retain `width` / `height` as positive integer pixel values from 1 to 99999. These reserve space before lazy images load and keep document layout and anchor positions stable. Percentages, negatives, decimals, events, and arbitrary `style` are removed.
533
-
534
- ```svelte
535
- <MarkdownRenderer content={markdown} fontSize='1.125rem' allowHtmlTags />
536
-
537
- <AiDocumentEditor
538
- title='方案文档'
539
- content={documentMarkdown}
540
- fontSize={18}
541
- allowHtmlTags
542
- showToolbar
543
- showOutline={false}
544
- />
545
- ```
546
-
547
- ##### Charts
548
-
549
- Lightweight dashboards use `MetricCard` (value, unit and percentage change), `ReportCard` (heading, actions, content, loading/empty states), and `DashboardGrid` (one, two or more columns based on container width). MetricCard alone does not load a chart engine. `trend={12.8}` means +12.8%; `trendTone` expresses business meaning independently, so a decrease can be success. Missing and non-finite values show “—”; zero remains visible.
550
-
551
- `Chart` supports `preset`: `grouped-bar`, `stacked-bar`, `stacked-area`, `donut`, and `sparkline`. Presets supply defaults; explicit `type` and native props take precedence, such as `innerRadius={0.8}` overriding the donut radius. Other LayerChart props and snippets continue to pass through.
552
-
553
- Renderers load dynamically by type. SSR reserves height and shows a loading placeholder; drawing starts after browser mount. Loading and empty charts do not load renderers. Prefer the public charts entry for dashboard-only consumers. For advanced charts, place native LayerChart components in ReportCard children, beyond Chart's five types. Declare a compatible `layerchart` dependency and use its actual public entries such as `layerchart/svg` or `layerchart/hierarchy`. Load advanced components dynamically when needed; see the admin native ArcChart example.
554
-
555
- ```svelte
556
- <script lang="ts">
557
- import { Chart, DashboardGrid, MetricCard, ReportCard } from '@h-ai/ui/components/scenes/charts/index'
558
- const data = [{ month: 'Jan', revenue: 42, cost: 24 }, { month: 'Feb', revenue: 58, cost: 31 }]
559
- </script>
560
-
561
- <DashboardGrid label="Key metrics" columns={4}>
562
- <MetricCard title="Revenue" value="128,430" unit="CNY" trend={12.8} trendTone="success" trendLabel="vs previous month" />
563
- </DashboardGrid>
564
- <ReportCard title="Revenue and cost">
565
- <Chart preset="grouped-bar" {data} x="month" y={['revenue', 'cost']} />
566
- </ReportCard>
567
- ```
568
-
569
- `Chart type='line'` uses LayerChart's native line chart by default. For monitoring dashboards with segmented lines, points, nearest-point hover, and vertical reference lines, use `lineVariant='segmented-point'`:
570
-
571
- ```svelte
572
- <Chart
573
- type='line'
574
- data={trendData}
575
- x='label'
576
- y={['rateLimit', 'circuitBreak']}
577
- series={trendSeries}
578
- lineVariant='segmented-point'
579
- tooltipMode='nearest'
580
- showCrosshair
581
- legend
582
- grid
583
- />
584
- ```
585
-
586
- ##### CRUD scenes
587
-
588
- | Component | Description | Key props / capabilities |
589
- | ------------------- | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
590
- | `CrudPage` | CRUD page | `crud`, `data`, `permissions`, `form`, `pagination`, `density`, `detailColumns`, `showHeader`, `toolbarLeading`, `toolbarActions`, `card`, `tableCell`, `onrowclick`, `sortableColumns`, `nav`, `loading`, `loaded`, `error`, `onRetry`, `keepPreviousData` |
591
- | `CrudFilterBar` | Filter toolbar (search + typed filters + reset) | `filterFields`, `searchValue`, `onsearch`, `onfilterchange`, `onreset` |
592
- | `CrudDetailPanel` | Details panel (drawer/modal) | `open`, `item`, `fields`, `variant`, `drawerWidth`, `modalSize` |
593
- | `CrudEditPanel` | Edit panel (drawer/modal) | `open`, `fields`, `variant`, `drawerWidth`, `modalSize`, `onsubmit` |
594
- | `CrudDeleteConfirm` | Delete confirmation | `open`, `loading`, `onconfirm` |
595
-
596
- > `CrudPage` and `FeedbackList` share a query bar inside the list card, an independently scrolling table and bottom pagination. Search, Query and Reset stay visible; extra filters start collapsed and retain their drafts. Query or Enter submits all conditions once; editing fields does not query automatically. Paging and sorting use applied conditions. Reset clears search, filters and sorting and returns to page one. Sorting buttons appear in column headers; `sortableColumns` must contain only fields supported by the backend. `detailColumns` configures detail links, `toolbarLeading` / `toolbarActions` add content above the card, and `card` / `tableCell` customize records. Filters support `select`, `boolean`, `number`, `date`, `date-range` and `text`. Without `sortableColumns`, CrudPage shows no sort buttons; list pages must declare backend-supported fields.
597
- >
598
- > The page fills available parent height. Tables fill remaining space even without data; only the data area scrolls, with headers fixed at its top and pagination fixed at the list card bottom.
599
- > Pass remaining height through every host container, for example with `flex flex-1 min-h-0 flex-col`, from the viewport shell to the content area. Intermediate wrappers must not size only to their content. Pagination stays at the bottom for empty, short and scrolling lists.
600
- >
601
- > Columns first shrink to 7rem and truncate long text; horizontal scrolling appears only if total width still exceeds the container. The action column stays fixed on the right.
602
-
603
- ##### Error pages
604
-
605
- | Component | Description | Key props / capabilities |
606
- | ----------- | --------------------------------------------------- | ----------------------------------------------------------------------- |
607
- | `ErrorPage` | Generic error page with 401/403/404/500/503 presets | `status`, `code`, `title`, `description`, `homeUrl`, `onhome`, `onback` |
608
-
609
- > `CrudPage` uses `form` to configure create/edit presentation: Without `sortableColumns`, CrudPage shows no sort buttons; list pages must declare backend-supported fields.
610
- >
611
- > - `form.variant`: `'drawer'` (default) or `'modal'`.
612
- > - Drawer: `form.drawerSize` selects a preset; `form.drawerWidth` accepts any CSS width and takes precedence. The left edge is resizable by default and remembered per resource; disable with `form.drawerResizable=false`.
613
- > - Modal: `form.modalSize` selects a preset; `form.modalWidth` / `form.modalHeight` accept CSS sizes.
614
- >
615
- > `pagination` configures the always-visible pagination bar. `showSizeChanger`, `pageSizeOptions`, `showJumper`, and `showTotal` are on by default. For compact views, disable page text with `showPageInfo` and first/last buttons with `showFirstLast`.
616
- >
617
- > `density` is `'normal'` (default) or `'compact'`. It affects list rows/actions, pagination, and create/edit/detail forms, not headers or filters.
618
- >
619
- > Controlled loading: `loading` / `loaded` / `error` / `onRetry` / `keepPreviousData`. Empty state appears only when `loaded && total === 0`, avoiding false empty results before the first response. Initial queries show loading; failures without usable data show errors/retry (`onRetry`). `keepPreviousData` (default true) retains old data during refresh/failure.
620
- >
621
- > Pure clients without SvelteKit SSR can use framework `defineCrud` + `createCrudController` to manage `data` and `nav`, with latest-wins (seq + AbortSignal), old-data retention on failure, lazy loading, and concurrent deduplication:
622
- >
623
- > ```svelte
624
- > <script>
625
- > import { CrudPage, createCrudController, defineCrud } from '@h-ai/ui'
626
- > const crud = defineCrud({ name: 'user', label: '用户', fields: [/* ... */], api: { list: params => listUsers(params) } })
627
- > const c = createCrudController(crud) // 惰性页签传 { autoLoad: false },首次激活时 c.load()
628
- > </script>
629
- > <CrudPage {crud} data={c.data} nav={c.nav} loading={c.loading} loaded={c.loaded} error={c.error} onRetry={c.reload} />
630
- > ```
631
- >
632
- > `Tabs` supports lazy content. With `lazy`, never-activated panes are not rendered (`children` receives `isActivated(key)`); `onactivate(key)` runs once on first activation. Combine with `createCrudController({ autoLoad: false })` to load only when first visible.
633
-
634
- ### Examples
635
-
636
- #### Toast notifications
637
-
638
- ```svelte
639
- <script>
640
- import { toast, ToastContainer } from '@h-ai/ui'
641
-
642
- function notify() {
643
- toast.success('操作成功')
644
- toast.error('操作失败')
645
- toast.warning('请注意')
646
- toast.info('提示信息', 5000) // 自定义持续时间
647
- }
648
- </script>
649
-
650
- <button onclick={notify}>通知</button>
651
- <ToastContainer />
652
- ```
653
-
654
- Toasts float at the bottom right by default without shifting layout, using UI-owned semantic colors for information, success, warning and error, with a soft tinted background, a narrow color border, a distinct icon and a subtle shadow. They can be dismissed manually. Notifications share one FIFO queue and appear one at a time; each timer starts when its notification is shown (3 seconds by default, `duration: 0` waits for dismissal). Mount `<ToastContainer />` once in the root layout. Set a position with `toast.add({ message: m.saved(), variant: 'success', position: 'bottom-center' })`, where `m.saved()` is an application translation. Positions: `bottom-right` (default), `top-right`, `bottom-center`, `top-center`, `bottom-left`, `top-left`. Use Toast for login, password changes, saves, deletes and uploads, including failures. All warnings and errors, including field validation, use ToastContainer. Fields retain invalid markers and accessible descriptions; persistent status and recovery actions remain in place. `Alert` only accepts info/success.
655
-
656
- Press F8 to focus the current notification and F8 again to return. Escape dismisses a dismissible notification and restores focus; Enter activates its dismiss button. This also works inside Modal without closing the dialog. Non-dismissible notifications can be focused for reading and exited with F8; automatic dismissal restores focus too.
657
-
658
- > Built-in `notifySuccess` / `notifyError` / `notifyInfo` / `notifyWarning` remove the need for application wrappers. `notifyError(err, fallback?)` hides an ordinary Error's internal message, displays a fallback and preserves traceId. String arguments must be safe localized messages; do not pass an unknown `err.message`. Success lasts 3s and errors 5s by default.
659
-
660
- When a Promise-based component requires an exception, preserve the complete failure with `throw new Error(result.error.message, { cause: result.error })`. `errorMessage` / `notifyError` follow the bounded, cycle-safe Error.cause chain to recover a safe business message and traceId. Server errors and unknown exceptions still use a safe fallback; internal exception text is not displayed.
661
-
662
- Reactive components can call `useToastFeedback(() => error)` during initialization with safe localized messages. Queued duplicates of the same type are merged; notifications survive component unmount. Updating or clearing a source replaces or removes its previous notification; duplicate matching also includes traceId. The `message` API shares this queue, style and dismissal behavior. `MessageContainer` renders `ToastContainer`; choose one container in the root layout.
663
-
664
- State modules can import `toast`, `useToastFeedback`, `notifySuccess` / `notifyError` / `notifyInfo` / `notifyWarning` and `errorMessage` from the lightweight `@h-ai/ui/toast` entry without loading components or tour CSS. Import `ToastContainer` from a component entry and mount it in the root layout.
665
-
666
- The traceId is hidden by default. Use `toast.add({ message: m.retry(), variant: 'warning', traceId })`; existing safe messages containing `(traceId: …)` are separated automatically. The diagnostic icon reveals an issue reference ID, a copy action, and guidance to provide it to customer support or the development team. If copying fails, the ID can be selected manually. Hovering, focusing or expanding pauses the timer; closing the details and leaving resumes the remaining time. `toast.pause(id)` / `toast.resume(id)` are also available. Migrate warning/error Alert components to Toast; field errors retain aria-invalid and accessible descriptions, with recovery actions in place.
667
-
668
- #### Choosing a Toast position
669
-
670
- The application provides the `m.saved()` translation below. Notifications at different positions still share one queue and appear in order.
671
-
672
- ```ts
673
- import { toast } from '@h-ai/ui/toast'
674
-
675
- toast.add({ message: m.saved(), variant: 'success', position: 'top-right' })
676
- toast.add({ message: m.saved(), position: 'bottom-center' })
677
- ```
678
-
679
- #### Typical CRUD page
680
-
681
- ```svelte
682
- <script>
683
- import {
684
- PageHeader, Card, DataTable, Button,
685
- Modal, Input, Select, toast, ToastContainer,
686
- } from '@h-ai/ui'
687
-
688
- let items = $state([])
689
- let showModal = $state(false)
690
- let loading = $state(false)
691
- let formData = $state({ name: '', type: '' })
692
-
693
- const columns = [
694
- { key: 'name', label: '名称' },
695
- { key: 'type', label: '类型' },
696
- { key: 'createdAt', label: '创建时间' },
697
- ]
698
-
699
- async function handleCreate() {
700
- loading = true
701
- try {
702
- await fetch('/api/items', { method: 'POST', body: JSON.stringify(formData) })
703
- showModal = false
704
- toast.success('创建成功')
705
- } finally {
706
- loading = false
707
- }
708
- }
709
- </script>
710
-
711
- <PageHeader title="项目管理" description="管理所有项目">
712
- {#snippet actions()}
713
- <Button onclick={() => showModal = true}>新建</Button>
714
- {/snippet}
715
- </PageHeader>
716
-
717
- <Card>
718
- <DataTable data={items} {columns} keyField="id" {loading}>
719
- {#snippet actions(item)}
720
- <Button size="xs">编辑</Button>
721
- <Button size="xs" variant="error">删除</Button>
722
- {/snippet}
723
- </DataTable>
724
- </Card>
725
-
726
- <Modal bind:open={showModal} title="新建项目">
727
- <form onsubmit={(e) => { e.preventDefault(); handleCreate() }} class="space-y-4">
728
- <Input placeholder="名称" bind:value={formData.name} required />
729
- <Select
730
- placeholder="选择类型"
731
- bind:value={formData.type}
732
- options={[
733
- { value: 'a', label: '类型 A' },
734
- { value: 'b', label: '类型 B' },
735
- ]}
736
- />
737
- </form>
738
- {#snippet footer()}
739
- <Button variant="ghost" onclick={() => showModal = false}>取消</Button>
740
- <Button {loading} onclick={handleCreate}>创建</Button>
741
- {/snippet}
742
- </Modal>
743
-
744
- <ToastContainer />
745
- ```
746
-
747
- `Modal` retains the top-right close button without a `title` / `header`, but does not render a full header row. Use `radius="1.4rem"` for rounded corners and `bodyOverflow="visible"` when internal dropdowns/overlays need to extend outside.
748
-
749
- #### Declarative CRUD page (CrudPage)
750
-
751
- ```svelte
752
- <script lang='ts'>
753
- import { createSvelteKitNavAdapter } from '@h-ai/kit/client'
754
- import { CrudPage } from '@h-ai/ui'
755
-
756
- let { data } = $props()
757
- const nav = createSvelteKitNavAdapter()
758
- </script>
759
-
760
- <CrudPage
761
- crud={roleCrud}
762
- {data}
763
- permissions={{ create: true, update: true, delete: true }}
764
- form={{ variant: 'modal', modalSize: '3xl', columns: 2, labelPosition: 'top' }}
765
- pagination={{ showSizeChanger: true, showJumper: true, pageSizeOptions: [10, 20, 50] }}
766
- density='compact'
767
- detailColumns={['name']}
768
- sortableColumns={[{ key: 'createdAt', label: '创建时间' }]}
769
- {nav}
770
- />
771
- ```
772
-
773
- > Use `form={{ variant: 'drawer', drawerWidth: '40rem' }}` for drawers. User resizing overrides the initial width and is remembered per resource.
774
-
775
- #### Login page
776
-
777
- ```svelte
778
- <script>
779
- import { LoginForm } from '@h-ai/ui'
780
-
781
- let loading = $state(false)
782
- let errors = $state({})
783
-
784
- async function handleLogin(data) {
785
- loading = true
786
- errors = {}
787
- try {
788
- await fetch('/api/login', { method: 'POST', body: JSON.stringify(data) })
789
- } catch {
790
- errors = { general: '登录失败,请检查用户名和密码' }
791
- } finally {
792
- loading = false
793
- }
794
- }
795
- </script>
796
-
797
- <!-- 场景组件内置 i18n,无需传入翻译 props -->
798
- <LoginForm {loading} {errors} onsubmit={handleLogin} showRegisterLink />
799
- ```
800
-
801
- #### Controlled PasswordInput
802
-
803
- ```svelte
804
- <script>
805
- import { PasswordInput } from '@h-ai/ui'
806
-
807
- let password = $state('')
808
- </script>
809
-
810
- <PasswordInput
811
- value={password}
812
- oninput={(e) => { password = e.currentTarget.value }}
813
- placeholder="请输入密码"
814
- showStrength
815
- />
816
- ```
817
-
818
- ### Feedback capture and delivery checks
819
-
820
- 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.
821
-
822
- 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.
823
-
824
- ### Style dependencies
825
-
826
- Components use TailwindCSS v4 + DaisyUI. Configure application `app.css` as follows:
827
-
828
- ```css
829
- /* 必须 */
830
- @import 'tailwindcss';
831
- @import '@h-ai/ui/styles/global.css'; /* 基础重置、滚动条、焦点样式 */
832
- @import '@h-ai/ui/styles/theme.css'; /* Tailwind v4 @theme Token(品牌色/阴影/动效) */
833
- @source "../node_modules/@h-ai/ui/dist/**/*.{svelte,js,ts}";
834
- @source "../../../node_modules/@h-ai/ui/dist/**/*.{svelte,js,ts}";
835
-
836
- /* 移动端项目追加(可选) */
837
- @import '@h-ai/ui/styles/design-tokens.css'; /* CSS 自定义属性 */
838
- @import '@h-ai/ui/styles/mobile.css'; /* 安全区域/触摸优化 */
839
-
840
- /* DaisyUI 主题 */
841
- @plugin "daisyui" {
842
- themes: light --default, dark --prefersdark, cupcake, emerald, corporate, nord, dracula, night;
843
- }
844
- ```
845
-
846
- - `global.css`: base HTML reset, scrollbars, and form focus rings.
847
- - `theme.css`: Tailwind v4 `@theme` with brand colors, shadows, animation curves, and font features.
848
- - `design-tokens.css`: spacing/radius/z-index/transition custom properties; recommended for mobile.
849
- - `mobile.css`: safe-area padding, momentum scrolling, keyboard adaptation, and mobile shells (`hai-mobile-viewport` / `hai-mobile-shell` / `hai-mobile-main`).
850
-
851
- On mobile pages, match `BottomNav` width to the page shell to avoid spanning the entire desktop preview viewport:
852
-
853
- ```svelte
854
- <div class="hai-mobile-viewport">
855
- <div class="hai-mobile-shell max-w-lg">
856
- <AppBar title="Home" fixed={false} safeArea />
857
- <main class="hai-mobile-main">...</main>
858
- <BottomNav items={items} active="home" centered maxWidth="lg" safeArea />
859
- </div>
860
- </div>
861
- ```
862
-
863
- `BottomNav` and `ThemeSelector` keep their trigger buttons disabled until the client has mounted and the event handlers are ready.
864
-
865
- #### Icons
866
-
867
- Components use Iconify (Tabler Icons):
868
-
869
- ```bash
870
- npm install -D @iconify/tailwind4 @iconify-json/tabler
871
- ```
872
-
873
- ```css
874
- /* app.css 中追加 */
875
- @plugin "@iconify/tailwind4" {
876
- prefixes: tabler;
877
- }
878
- ```
879
-
880
- #### Theme switching
881
-
882
- Manage 15 curated DaisyUI themes plus high contrast, square business and eye-care themes through built-in utilities:
883
-
884
- `high-contrast` ships in shared theme.css with bright text on dark surfaces, clear borders/focus, and stronger muted text/placeholders. ThemeSelector has localized labels; examples and default generated projects offer it. Explicit fullstack themes lists remain host controlled. Palette checks target 7:1 for normal text; arbitrary application content still needs accessibility review.
885
-
886
- `eye-care` ships in shared theme.css with warm green surfaces, dark text, readable placeholders and clear focus outlines. Select “Eye care” in examples and default templates; the preference survives reloads. Existing default themes and explicit fullstack themes lists are preserved.
887
-
888
- `formal` provides square corners for business buttons, fields, cards and dialogs, with localized labels in examples and default templates. Button submitHint displays the native Enter action only for type=submit; it adds no global shortcut. LoginForm focuses its identifier on desktop when ready and no element has focus; autoFocus=false opts out. Search Enter submits immediately while respecting IME composition. Theme choices support arrows/Home/End, Enter/Space and Escape focus restoration. Confirmation dialogs initially focus Cancel and synchronize Escape cancellation.
889
-
890
- ```ts
891
- import {
892
- applyTheme, // 应用主题(自动持久化到 localStorage)
893
- createThemeBootstrapScript, // 生成可注入 app.html 的首屏主题恢复脚本
894
- getCurrentTheme, // 获取当前主题
895
- getSavedTheme, // Read saved appearance, with an optional application default
896
- getThemeInitScript, // 返回可注入到 HTML shell 的防闪烁脚本文本
897
- isDarkTheme, // 检查是否暗色主题
898
- normalizeHexColor, // 归一化 #RGB / #RRGGBB 主题色
899
- normalizeThemeId, // 校验主题 ID 并自动回退
900
- THEME_GROUPS, // 按亮色/暗色分组
901
- THEMES, // ThemeInfo[] — 18 个主题元数据
902
- } from '@h-ai/ui/theme'
903
- ```
904
-
905
- Use `getThemeInitScript()` for simple cases. For custom storage keys, theme color CSS variables, or language preferences, generate `createThemeBootstrapScript()` on the server and inject it into `app.html`.
906
-
907
- Place a placeholder in SvelteKit `app.html`:
908
-
909
- ```html
910
- <head>
911
- <script>%theme_bootstrap%</script>
912
- </head>
913
- ```
914
-
915
- Then inject it from `hooks.server.ts`:
916
-
917
- ```ts
918
- import { createThemeBootstrapScript, DEFAULT_THEME_COLOR_CSS_VAR } from '@h-ai/ui/theme'
919
-
920
- const themeBootstrapScript = createThemeBootstrapScript({
921
- storageKey: 'hai-demo-preferences',
922
- defaultThemeColor: '#5765f0',
923
- colorCssVar: DEFAULT_THEME_COLOR_CSS_VAR,
924
- })
925
-
926
- transformPageChunk: ({ html }) => html.replace('%theme_bootstrap%', themeBootstrapScript)
927
- ```
928
-
929
- ### Internationalization (i18n)
930
-
931
- @h-ai/ui uses **built-in component translations**:
932
-
933
- - Scene components (`scenes/`) include Chinese/English/Japanese translations (zh-CN / en-US / ja-JP) out of the box.
934
- - Components respond automatically to global locale changes, synchronized through `@h-ai/core`.
935
- - Applications handle **page text** only; @h-ai/ui manages internal component text.
936
- - Override specific text with props such as `submitText` or `labels`.
937
-
938
- #### createLocaleStore
939
-
940
- Client locale state management, automatically synchronized with the `@h-ai/core` global locale manager:
941
-
942
- ```svelte
943
- <script>
944
- import { createLocaleStore, setGlobalLocale } from '@h-ai/ui/i18n'
945
- import { setLocale } from '#lib/paraglide/runtime.js'
946
-
947
- const localeStore = createLocaleStore()
948
-
949
- function changeLocale(code) {
950
- localeStore.set(code) // 更新 UI store + 同步到 @h-ai/core
951
- setLocale(code) // 同步到 Paraglide(应用层)
952
- }
953
- </script>
954
-
955
- <select value={localeStore.current} onchange={(e) => changeLocale(e.currentTarget.value)}>
956
- {#each localeStore.supported as l}
957
- <option value={l.code}>{l.label}</option>
958
- {/each}
959
- </select>
960
- ```
961
-
962
- `createLocaleStore` from `@h-ai/ui/i18n` selects a resolvable saved locale, then the complete navigator.languages list (followed by navigator.language), then defaultLocale and the first supported entry. An unsupported candidate never triggers an early default. Matching handles case, language shorthand and progressively less specific region/script tags, returning the configured code. Same-language variants follow supportedLocales order. detectBrowserLocale returns null without an actual match; an empty supported list ultimately keeps the caller default. SSR neither reads browser candidates nor changes global locale. Paraglide applications must still synchronize their own setLocale; custom store entries do not add built-in UI dictionaries.
963
-
964
- #### Exported i18n utilities
965
-
966
- ```ts
967
- import {
968
- createLocaleStore, // Svelte 响应式 locale store
969
- DEFAULT_LOCALE, // 默认 locale: 'zh-CN'
970
- DEFAULT_LOCALES, // 支持的 locale 列表
971
- detectBrowserLocale, // 检测浏览器语言
972
- getGlobalLocale, // 获取当前全局 locale
973
- interpolate, // 字符串插值(如 "Hello {name}")
974
- isLocaleSupported, // 检查 locale 是否支持
975
- resolveLocale, // 解析 locale(支持回退)
976
- setGlobalLocale, // 设置全局 locale(同步 @h-ai/core)
977
- } from '@h-ai/ui/i18n'
978
- ```
979
-
980
- ### Configuration driven authentication
981
-
982
- State modules can import `authErrorMessage` from the lightweight `@h-ai/ui/i18n` entry without loading scene components. Admin profile password changes, mobile/desktop examples and generated templates share these messages.
983
-
984
- Password login submits only `identifier` and `password`; `AuthPanel` maps the `LoginForm` field `username` to `identifier`. Server settings `session.maxAge` / `session.refreshTokenMaxAge` control session lifetimes. The login form has no per-login persistent-session option.
985
-
986
- Agreement content can be configured as `agreements.userAgreementMarkdown` and `privacyPolicyMarkdown` using YAML `|`. The modal safely renders configured Markdown and prefers it over the URL of the same agreement. URL-only content stays in a sandboxed iframe.
987
-
988
- ```yaml
989
- agreements:
990
- showOnRegister: true
991
- showOnLogin: false
992
- userAgreementMarkdown: |
993
- # 用户协议
994
-
995
- **账户使用条款**
996
-
997
- - 请妥善保管账户凭据。
998
- privacyPolicyMarkdown: |
999
- # 隐私政策
1000
-
1001
- 注册资料用于账户管理,会话信息用于身份认证。
1002
- # 可选 URL;同主题同时配置 Markdown 和 URL 时,弹窗优先显示 Markdown。
1003
- # userAgreementUrl: https://example.com/terms
1004
- # privacyPolicyUrl: https://example.com/privacy
1005
- ```
1006
-
1007
- AuthPanel accepts public IAM config and actions for password/LDAP/email/SMS login, registration and recovery. config.ui supplies layout, branding and images. LoginForm supports methods, onsendotp, otpLength and resendInterval; password forms accept passwordPolicy. Network and token storage remain in actions.
1008
-
1009
- Use `authErrorMessage(error)` from `@h-ai/ui/components/scenes/iam/index` for authentication failures. It maps public codes to the current UI language, combines username/password failures, hides raw unknown/server errors and preserves a valid `traceId`. AuthPanel, OTP sending, sensitive confirmation and fullstack password changes share this mapping. Initial/expired passwords, reuse of the current password (`hai:iam:034`) and session limits have actionable messages. Authentication errors and successful operations use the unified Toast. Password confirmation compares exact strings without Unicode normalization or trimming and reports mismatches through Toast while retaining field associations. AuthPanel displays the server’s UTC time and synchronization guidance for time errors verified by Kit or API Client.
1010
-
1011
- AuthPanel disables native form controls during SSR and enables input after client mount binds events, preventing early input from being lost during hydration. Applications need no extra readiness code. E2E tests wait for editable controls and cover delayed client scripts.
1012
-
1013
- 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.
1014
-
1015
- `createSensitiveActions` can refresh database rules before an action through standard `actions.publicConfig()`. `SensitiveOperationsForm` shares line-based input, deduplication, validation and errors. Pass `operations`, async `onsubmit(operations)` returning HaiResult, and optional `ondone` for successful saves. Clearing database additions does not remove file rules.
1016
-
1017
- Use `createSessionRecovery()` with `SessionRecoveryDialog` for expired sessions. Configure it with the public config and original `{ id, username }`, pass `recovery.recover` as Kit/API client's `recoverSession`, and give the dialog the same controller and standard actions. Call `cancel()` on teardown. The UI stores no passwords or business requests. `expectedUserId` restricts server session issuance to the original principal; captcha, lockout, access and password-renewal policies remain active. Cancellation preserves input and stops continuation; ambiguous network writes are never replayed. Reloaded/closed documents cannot recover lost in-memory drafts.
1018
-
1019
- `createSensitiveActions(actions)` accepts Kit/API client authentication actions and shares confirmation, cancellation, retry, duplicate-submit and late-response handling. Create one per application root layout, update it with `configure(publicPolicy)`, and call `cancel()` on teardown. `authorize(operation)` returns undefined when confirmation is unnecessary, null when cancelled/busy, or the proof for that action. Do not send the business request on cancellation; pass a proof only to its intended request, never to global headers or persistent storage. Bind `ReauthenticationDialog` to the controller’s `open/loading/error/submit/cancel`; confirmation grants no permissions. `Input` supports `datetime-local`: convert its browser-local value to an explicit timestamp in the service layer.
1020
-
1021
- ```svelte
1022
- <!-- actions comes from Kit/API client; policy is the public IAM reauthentication policy. -->
1023
- <script lang='ts'>
1024
- import type { SensitiveActionsOptions } from '@h-ai/ui'
1025
- import { createSensitiveActions, ReauthenticationDialog } from '@h-ai/ui'
1026
-
1027
- const { actions, policy }: { actions: SensitiveActionsOptions, policy: { enabled: boolean, operations: string[] } } = $props()
1028
- const confirmation = createSensitiveActions(actions)
1029
- $effect(() => {
1030
- confirmation.configure(policy)
1031
- return () => confirmation.cancel()
1032
- })
1033
- // Await confirmation.authorize(operation) in the business action; stop on null.
1034
- </script>
1035
- <ReauthenticationDialog
1036
- open={confirmation.open}
1037
- loading={confirmation.loading}
1038
- error={confirmation.error}
1039
- onsubmit={password => confirmation.submit(password)}
1040
- onclose={() => confirmation.cancel()}
1041
- />
1042
- ```
1043
-
1044
- [完整 IAM 配置 / IAM configuration](../iam/README.en.md)
1045
-
1046
- ### Onboarding and help center
1047
-
1048
- Import `createGuide`, `GuideHost` and `HelpCenter` from `@h-ai/ui/guide`. No init/close is required. The tour engine loads when a tour starts; controls follow the current theme and include Chinese/English/Japanese translations. Business text uses application i18n callbacks.
1049
-
1050
- The same entry exports `resolveGuideText(text?)` to evaluate strings or i18n callbacks; host components resolve text automatically.
1051
-
1052
- Create the controller inside a layout component, register tours with id/title/steps and optional route/version, then mount `<GuideHost {guide} {locale} scope={user.id} autoStart='overview' />`. Add `data-guide` to existing target components. Supply the application's NavAdapter for SPA navigation.
1053
-
1054
- ```svelte
1055
- <script lang='ts'>
1056
- import { createGuide, GuideHost } from '@h-ai/ui/guide'
1057
-
1058
- const guide = createGuide({
1059
- nav,
1060
- persistKey: 'my-app-guide',
1061
- tours: [{
1062
- id: 'users',
1063
- version: 1,
1064
- route: '/users',
1065
- title: () => m.guide_users_title(),
1066
- description: () => m.guide_users_description(),
1067
- steps: [{
1068
- target: 'users-create',
1069
- title: () => m.guide_create_title(),
1070
- description: () => m.guide_create_description(),
1071
- }],
1072
- }],
1073
- articles: [{
1074
- id: 'users-help',
1075
- title: () => m.guide_users_title(),
1076
- content: () => m.guide_users_markdown(),
1077
- tourId: 'users',
1078
- }],
1079
- })
1080
- </script>
1081
-
1082
- <GuideHost {guide} {locale} scope={user.id} autoStart='users' />
1083
- <Button onclick={() => guide.openHelp()}>{m.help()}</Button>
1084
- <!-- 在目标页面为现有按钮添加锚点,无需额外包装。 -->
1085
- <Button data-guide='users-create' onclick={createUser}>{m.create_user()}</Button>
1086
- ```
1087
-
1088
- `start(id)` returns Promise<boolean> and always allows replay; failure returns false and sets error. `startIfNeeded(id)` returns boolean and offers a first-use invitation. `openHelp(articleId?)` opens searchable Markdown help; `stop()` cancels without marking completion; `reset(id)` clears the current user's preference.
1089
-
1090
- The close button, Escape, and overlay clicks cancel pending highlighting and clear `busy` even before the first positioning frame completes. A pending `start()` resolves to false without recording completion.
1091
-
1092
- Persistence supports cookie (default), localStorage and memory, with an in-instance fallback when storage is restricted. Preferences are isolated by user and version. Later delays reminders for one day; Cookie preferences expire after one year. The default full-page navigation uses a short-lived sessionStorage record to start on the destination page.
1093
-
1094
- Use `() => m.key()` for localized content and pass the current locale. Steps render as plain text; help uses the existing safe Markdown renderer with raw HTML disabled. Targets wait up to 3000ms by default; before(signal) prepares tabs or drawers, optional skips nonessential missing targets, and missing required targets stop the tour. Unmounting cancels pending work. Never share controllers across SSR users.
1095
-
1096
- HelpCenter can also render a standalone page using articles, optional tours, locale, selectedId and onstart. The admin-console example and CLI fullstack Web/App/Desktop include first-use invitations, help and profile tours by default. See the [complete integration guide](../cli/templates/skills/hai-ui/guide.md).
1097
-
1098
- ### Other exports
1099
-
1100
- ```ts
1101
- // 类型
1102
- import type { ButtonProps, InputProps, ModalProps } from '@h-ai/ui'
1103
- ```
1104
-
1105
- ```ts
1106
- // 样式工具
1107
- import { cn, generateId, getSizeClass, getVariantClass } from '@h-ai/ui'
1108
- ```
1109
-
1110
- ```ts
1111
- // Toast 单例
1112
- import { toast } from '@h-ai/ui'
1113
- ```
1114
-
1115
- Agreements open in a Modal and preserve form input. Pages must allow iframe embedding; scripts are disabled and a new-window fallback is provided. LoginForm/RegisterForm expose `header/extraFields/footer`. AuthPanel forwards `loginHeader/loginFields/loginFooter` and `registerHeader/registerFields/registerFooter` while preserving navigation. Bind additional fields to application state and handle them in custom actions; they are not automatically sent to IAM. Use `type="button"` for extension buttons.
1116
-
1117
- ```svelte
1118
- <!-- config 来自 IAM 公开配置,actions 来自 Kit/API client;m 为应用翻译。 -->
1119
- <AuthPanel {config} {actions}>
1120
- {#snippet loginHeader()}
1121
- <p>{m.loginHelp()}</p>
1122
- {/snippet}
1123
- {#snippet registerFields()}
1124
- <label><input type='checkbox' bind:checked={subscribe} />{m.subscribe()}</label>
1125
- {/snippet}
1126
- </AuthPanel>
1127
- ```
1128
-
1129
- Component subpaths expose only explicit barrels in package.exports, such as `@h-ai/ui/components/primitives/index`. Component internals and storage helpers stay private; host clipboard registration remains public.
1130
-
1131
- ### Request locale isolation
1132
-
1133
- Wrap Node requests and SSR in `core.i18n.runWithLocale(locale, () => handleRequest())`. SvelteKit can use `kit.i18n.runWithLocale(locale, () => resolve(event))`; serv creates the scope automatically from request headers. Async descendants inherit it. Explicit `MessageOptions.locale` takes precedence over the request locale and the startup default. Within a scope, `setGlobalLocale` only changes that request; outside a scope it configures the startup default and must not be called by request hooks.
1134
-
1135
- Browsers keep application-level `setGlobalLocale` / `createLocaleStore`. During SSR, UI store initialization and setters only update the store; messages read the request scope. `runWithLocale` requires the Node entry; browser translations use explicit locale options or application state.
1136
-
1137
- ### Input limits and HTTP capabilities
1138
-
1139
- 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#存储输入约束与跨端能力).
1140
-
1141
- ### Compact workspaces and collapsible filters
1142
-
1143
- `WorkspaceLayout` shares a compact navigation header, a content area with 12/16px padding and an optional footer. An omitted footer reserves no space. title is the page title in navigation; leading/actions/footer are snippets. data-* attributes reach the content main. The host must pass down available height and min-height: 0.
1144
-
1145
- A matching `PageHeader` omits the repeated title and retains its description and actions; `SettingsLayout` shares this behavior. Inside a workspace, `CrudPage` defaults to one navigation title and keeps actions in its toolbar. Standalone usage retains its title; showHeader explicitly overrides the default.
1146
-
1147
- `FilterBar` keeps leading and actions visible, with children collapsed by default. bind:expanded controls disclosure, activeCount reports active conditions, and onreset supplies the built-in localized reset button. Collapsing preserves controls and values. The host resets state and performs queries. `TableToolbar` reuses this layout with a native query form; `CrudFilterBar` shares its implementation. `onsearch` submits the current bound search and filter drafts; `onfilterchange` only reports draft changes. `onreset` (`onclearfilters` on TableToolbar) must clear applied host conditions and query again. The old `toolbarStyle`, sorting popup and TableToolbar sorting props were removed; use DataTable `sortKey`, `sortDir` and `onsort`. Expanded filters adapt to 1/2/4/6 columns with 20px horizontal and 16px vertical gaps, aligned labels and equal control heights. Date ranges span two columns or the full row on narrow screens.
1148
-
1149
- In this example, m, statusOptions, clearFilters and loadRows belong to the host application. The reset callback must clear search and all conditions.
1150
-
1151
- ```svelte
1152
- <script lang="ts">
1153
- import { Button, FilterBar, Input, Select, WorkspaceLayout } from '@h-ai/ui'
1154
- let search = $state('')
1155
- let status = $state('')
1156
- </script>
1157
-
1158
- <div class="flex h-dvh min-h-0">
1159
- <WorkspaceLayout title={m.page_title()}>
1160
- <FilterBar activeCount={status ? 1 : 0} onreset={clearFilters}>
1161
- {#snippet leading()}<Input size="sm" bind:value={search} placeholder={m.search()} />{/snippet}
1162
- {#snippet actions()}<Button size="sm" onclick={loadRows}>{m.search()}</Button>{/snippet}
1163
- <div class="w-40"><Select size="sm" bind:value={status} options={statusOptions} /></div>
1164
- </FilterBar>
1165
- </WorkspaceLayout>
1166
- </div>
1167
- ```
1168
-
1169
- ### Design and interaction acceptance
1170
-
1171
- 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).
1172
-
1173
- 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. Expanded filters follow document focus order 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.
1174
-
1175
- ### Optional interactive challenges
1176
-
1177
- 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.
1178
-
1179
- See policy, defaults and recovery boundaries in [IAM](../iam/README.en.md).
1180
-
1181
- ## Configuration
1182
-
1183
- ### Choose configuration by task
1184
-
1185
- | Configuration entry | Scenario | Input | Effect | Example |
1186
- | --- | --- | --- | --- | --- |
1187
- | `Component Props` | Rendering and interaction | typed props, bound values, callbacks, children snippets | DOM, bindings and callback events | `<Input bind:value={draft} />` |
1188
- | `Theme` | Themes and colors | supported theme ID, color values, preference key | DOM theme/CSS variables; nonsensitive browser preference | `applyTheme("light")` |
1189
- | `Locale` | Interface language | supportedLocales, defaultLocale, persistKey, detectBrowser | component-tree locale; isolated SSR state | `createLocaleStore({ defaultLocale: "ja-JP", detectBrowser: false })` |
1190
- | `Guide` | Help and onboarding | tours, articles, nonsecret scope/version, nav adapter | guide/help state and nonsensitive progress | `createGuide({ tours: [], persistence: "memory" })` |
1191
- | `CRUD` | Resource fields and API | CrudResource fields/API callbacks and controller options | resource view model; API must implement authorization | `createCrudController(crud, { autoLoad: false })` |
1192
- | `Authentication` | Public auth policy | IAM-whitelisted config and standard actions | AuthPanel submits to host actions; no secret persistence | `<AuthPanel {config} {actions} />` |
1193
-
1194
- When building Svelte applications with pnpm, register the `deepmerge@4.3.1` patch in the project's `patchedDependencies` and keep the patch file. Retain the DaisyUI style patch when that package is used. CLI-generated projects include applicable entries. Installing a framework npm package does not propagate this repository's pnpm patch configuration; manual integrations must copy the relevant [patch files](../../patches/) and registrations before reinstalling dependencies.
1195
-
1196
- This package contains Svelte components and utilities and has no init/close lifecycle. Inputs are component props, callbacks and theme options; outputs are rendered UI, bound values and events. Configure Tailwind/DaisyUI and preprocessing as shown above. There is no shared _ui.yml or module environment variable for component props.
1197
-
1198
- ## Error Handling
25
+ [Browse the API list](../../docs/usage/function/ui.en.md#api-reference) for entry points, inputs, results and examples.
1199
26
 
1200
- The host provides loading/error and completion state. Check business HaiResult.success in the application adapter, then pass safe localized messages. UI helpers use the direct return types above rather than a universal HaiResult wrapper. notifyError/errorMessage hide unknown internal exception text. Catch rejected browser helpers such as downloadAiDocument at the interaction boundary and release loading. UserProfile.onsubmit ends editing only when it returns true.
27
+ [Tool and artifact workspaces](../../docs/usage/function/ui.en.md#tool-workspaces) provide parameter forms, examples, task progress, document editing, version conflicts, and media previews. Applications connect authorized read, write, and execution callbacks.
1201
28
 
1202
- ### Error messages and correlated logs
29
+ ## Data Structures
1203
30
 
1204
- HTTP errors carry safe localized messages and a reference ID. ToastContainer shows only the readable message by default; its diagnostic icon reveals the ID and copy action. The same ID remains 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.
31
+ The module creates no database tables of its own.
1205
32
 
1206
- 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.
33
+ See the [data reference](../../docs/usage/data/ui.en.md) for where themes, language settings, and onboarding progress are stored in the browser.
1207
34
 
1208
- ## Development
35
+ ## Development and Testing
1209
36
 
1210
37
  ```sh
1211
38
  pnpm --filter @h-ai/ui typecheck