@fibrae/semi-ui-svelte 0.9.1 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -4
- package/README.zh-CN.md +8 -4
- package/dist/components/anchor/interface.d.ts +14 -0
- package/dist/components/audio-player/interface.d.ts +5 -0
- package/dist/components/auto-complete/interface.d.ts +29 -0
- package/dist/components/avatar/interface.d.ts +24 -0
- package/dist/components/backtop/interface.d.ts +2 -0
- package/dist/components/badge/interface.d.ts +7 -0
- package/dist/components/banner/interface.d.ts +7 -0
- package/dist/components/breadcrumb/interface.d.ts +10 -0
- package/dist/components/button/interface.d.ts +18 -0
- package/dist/components/calendar/interface.d.ts +16 -0
- package/dist/components/card/interface.d.ts +18 -0
- package/dist/components/carousel/interface.d.ts +16 -0
- package/dist/components/cascader/interface.d.ts +57 -0
- package/dist/components/checkbox/interface.d.ts +19 -0
- package/dist/components/code-highlight/interface.d.ts +3 -0
- package/dist/components/collapse/interface.d.ts +16 -0
- package/dist/components/collapsible/interface.d.ts +10 -0
- package/dist/components/color-picker/interface.d.ts +10 -0
- package/dist/components/config-provider/interface.d.ts +7 -0
- package/dist/components/cropper/interface.d.ts +11 -0
- package/dist/components/date-picker/interface.d.ts +47 -0
- package/dist/components/descriptions/interface.d.ts +6 -0
- package/dist/components/divider/interface.d.ts +4 -0
- package/dist/components/dropdown/interface.d.ts +8 -0
- package/dist/components/empty/interface.d.ts +7 -0
- package/dist/components/feedback/interface.d.ts +16 -0
- package/dist/components/float-button/interface.d.ts +14 -0
- package/dist/components/form/interface.d.ts +47 -0
- package/dist/components/grid/interface.d.ts +13 -0
- package/dist/components/highlight/interface.d.ts +7 -0
- package/dist/components/hot-keys/interface.d.ts +3 -0
- package/dist/components/image/interface.d.ts +59 -0
- package/dist/components/input/interface.d.ts +67 -0
- package/dist/components/input-number/interface.d.ts +24 -0
- package/dist/components/json-viewer/interface.d.ts +7 -0
- package/dist/components/layout/interface.d.ts +3 -0
- package/dist/components/list/interface.d.ts +18 -0
- package/dist/components/locale/interface.d.ts +4 -0
- package/dist/components/lottie/interface.d.ts +2 -0
- package/dist/components/markdown-render/interface.d.ts +5 -0
- package/dist/components/modal/interface.d.ts +29 -0
- package/dist/components/navigation/interface.d.ts +47 -0
- package/dist/components/overflow-list/interface.d.ts +11 -0
- package/dist/components/pagination/interface.d.ts +12 -0
- package/dist/components/pincode/interface.d.ts +8 -0
- package/dist/components/popconfirm/interface.d.ts +12 -0
- package/dist/components/popover/interface.d.ts +30 -0
- package/dist/components/progress/interface.d.ts +13 -0
- package/dist/components/radio/interface.d.ts +22 -0
- package/dist/components/rating/interface.d.ts +12 -0
- package/dist/components/resizable/interface.d.ts +30 -0
- package/dist/components/scroll-list/interface.d.ts +6 -0
- package/dist/components/select/interface.d.ts +63 -0
- package/dist/components/side-sheet/interface.d.ts +19 -0
- package/dist/components/skeleton/interface.d.ts +7 -0
- package/dist/components/slider/interface.d.ts +23 -0
- package/dist/components/space/interface.d.ts +4 -0
- package/dist/components/spin/interface.d.ts +7 -0
- package/dist/components/steps/interface.d.ts +9 -0
- package/dist/components/switch/interface.d.ts +7 -0
- package/dist/components/table/interface.d.ts +48 -0
- package/dist/components/tabs/interface.d.ts +29 -0
- package/dist/components/tag/interface.d.ts +22 -0
- package/dist/components/tag-input/interface.d.ts +29 -0
- package/dist/components/time-picker/interface.d.ts +31 -0
- package/dist/components/timeline/interface.d.ts +5 -0
- package/dist/components/tooltip/interface.d.ts +20 -0
- package/dist/components/transfer/interface.d.ts +18 -0
- package/dist/components/tree/interface.d.ts +45 -0
- package/dist/components/tree-select/interface.d.ts +55 -0
- package/dist/components/typography/interface.d.ts +33 -0
- package/dist/components/upload/interface.d.ts +64 -0
- package/dist/components/user-guide/interface.d.ts +15 -0
- package/dist/components/video-player/interface.d.ts +22 -0
- package/docs/advanced/dark-mode.md +288 -0
- package/docs/basic/button.md +605 -0
- package/docs/basic/divider.md +103 -0
- package/docs/basic/float-button.md +246 -0
- package/docs/basic/grid.md +427 -0
- package/docs/basic/layout.md +459 -0
- package/docs/basic/resizable.md +584 -0
- package/docs/basic/space.md +163 -0
- package/docs/basic/tokens.md +425 -0
- package/docs/basic/typography.md +615 -0
- package/docs/changes-from-semi.md +105 -0
- package/docs/ecosystem/tailwind.md +210 -0
- package/docs/experience/accessibility.md +82 -0
- package/docs/experience/content-guidelines.md +819 -0
- package/docs/experience/internationalization.md +7 -0
- package/docs/feedback/banner.md +198 -0
- package/docs/feedback/feedback.md +294 -0
- package/docs/feedback/notification.md +401 -0
- package/docs/feedback/popconfirm.md +243 -0
- package/docs/feedback/progress.md +389 -0
- package/docs/feedback/skeleton.md +388 -0
- package/docs/feedback/spin.md +172 -0
- package/docs/feedback/toast.md +393 -0
- package/docs/input/auto-complete.md +399 -0
- package/docs/input/cascader.md +1558 -0
- package/docs/input/checkbox.md +408 -0
- package/docs/input/color-picker.md +175 -0
- package/docs/input/date-picker.md +942 -0
- package/docs/input/form.md +2550 -0
- package/docs/input/input-number.md +451 -0
- package/docs/input/input.md +640 -0
- package/docs/input/pincode.md +191 -0
- package/docs/input/radio.md +337 -0
- package/docs/input/rating.md +214 -0
- package/docs/input/select.md +1230 -0
- package/docs/input/slider.md +347 -0
- package/docs/input/switch.md +206 -0
- package/docs/input/tag-input.md +465 -0
- package/docs/input/time-picker.md +358 -0
- package/docs/input/transfer.md +1061 -0
- package/docs/input/tree-select.md +1300 -0
- package/docs/input/upload.md +1811 -0
- package/docs/llms.txt +147 -0
- package/docs/navigation/anchor.md +377 -0
- package/docs/navigation/backtop.md +100 -0
- package/docs/navigation/breadcrumb.md +284 -0
- package/docs/navigation/navigation.md +851 -0
- package/docs/navigation/pagination.md +217 -0
- package/docs/navigation/steps.md +315 -0
- package/docs/navigation/tabs.md +754 -0
- package/docs/navigation/tree.md +1956 -0
- package/docs/other/config-provider.md +599 -0
- package/docs/other/locale.md +353 -0
- package/docs/plus/audio-player.md +155 -0
- package/docs/plus/code-highlight.md +150 -0
- package/docs/plus/drag-move.md +214 -0
- package/docs/plus/hot-keys.md +174 -0
- package/docs/plus/json-viewer.md +392 -0
- package/docs/plus/lottie.md +176 -0
- package/docs/plus/markdown-render.md +240 -0
- package/docs/plus/video-player.md +325 -0
- package/docs/show/avatar.md +475 -0
- package/docs/show/badge.md +276 -0
- package/docs/show/calendar.md +352 -0
- package/docs/show/card.md +485 -0
- package/docs/show/carousel.md +592 -0
- package/docs/show/collapse.md +289 -0
- package/docs/show/collapsible.md +216 -0
- package/docs/show/cropper.md +285 -0
- package/docs/show/descriptions.md +325 -0
- package/docs/show/dropdown.md +466 -0
- package/docs/show/empty.md +225 -0
- package/docs/show/highlight.md +144 -0
- package/docs/show/image.md +433 -0
- package/docs/show/list.md +927 -0
- package/docs/show/modal.md +517 -0
- package/docs/show/overflow-list.md +272 -0
- package/docs/show/popover.md +534 -0
- package/docs/show/scroll-list.md +156 -0
- package/docs/show/side-sheet.md +274 -0
- package/docs/show/table.md +5437 -0
- package/docs/show/tag.md +428 -0
- package/docs/show/timeline.md +277 -0
- package/docs/show/tooltip.md +442 -0
- package/docs/show/user-guide.md +419 -0
- package/docs/start/getting-started.md +234 -0
- package/docs/start/introduction.md +57 -0
- package/docs/start/overview.md +21 -0
- package/package.json +5 -4
|
@@ -0,0 +1,2550 @@
|
|
|
1
|
+
# Form
|
|
2
|
+
|
|
3
|
+
> Form collects, validates and submits data, with built-in layouts, field linkage and on-demand rerendering.
|
|
4
|
+
|
|
5
|
+
Package: `@fibrae/semi-ui-svelte`. Web page: https://semi-design-next.pages.dev/en-US/svelte/input/form/
|
|
6
|
+
|
|
7
|
+
## Form
|
|
8
|
+
|
|
9
|
+
- **Rerender on demand**, avoids unnecessary full-volume rendering, higher performance
|
|
10
|
+
- Easy to use, **simple structure**, avoids unnecessary hierarchical nesting
|
|
11
|
+
- Perfect accessibility support
|
|
12
|
+
- FormState / FieldState can also be easily obtained from outside the Form Provides an external method to operate inside the form: formApi / fieldApi
|
|
13
|
+
- Support for encapsulating custom components into form controls, and you can quickly access your team's components through the extension mechanism provided by Form (through `withField`)
|
|
14
|
+
- Support Form level / Field level assignment, verification (synchronous / asynchronous)
|
|
15
|
+
|
|
16
|
+
## Field
|
|
17
|
+
|
|
18
|
+
Semi encapsulates all form field components (Input, Select, Checkbox, DatePicker etc.) once.\
|
|
19
|
+
Taking over their data flow (`value` & `onChange`)\
|
|
20
|
+
When in use, you need to use the components whose names start with Form (note: only these components have data synchronization). They are named exports and are not mounted under Form.
|
|
21
|
+
|
|
22
|
+
### Supported Field Component
|
|
23
|
+
|
|
24
|
+
- Fields: `FormInput`, `FormInputNumber`, `FormTextArea`, `FormSelect`, `FormCheckbox`, `FormCheckboxGroup`, `FormRadio`, `FormRadioGroup`, `FormSwitch`, `FormDatePicker`, `FormTimePicker`, `FormSlider`, `FormTreeSelect`, `FormCascader`, `FormTransfer`, `FormRating`, `FormAutoComplete`, `FormUpload`, `FormPinCode`, `FormTagInput`
|
|
25
|
+
- Other parts: `FormField`, `ArrayField`, `FormInputGroup`, `FormLabel`, `FormErrorMessage`, `FormSection`, `FormSlot`
|
|
26
|
+
|
|
27
|
+
```svelte
|
|
28
|
+
<script lang="ts">
|
|
29
|
+
// A field takes over its data flow when used inside <Form>
|
|
30
|
+
import { Form, FormInput, FormSelect } from '@fibrae/semi-ui-svelte';
|
|
31
|
+
// A plain Input is left untouched by the Form
|
|
32
|
+
import { Input } from '@fibrae/semi-ui-svelte';
|
|
33
|
+
</script>
|
|
34
|
+
|
|
35
|
+
<Form>
|
|
36
|
+
<FormInput field="name" />
|
|
37
|
+
<FormSelect field="role" optionList={[{ label: 'Developer', value: 'rd' }]} />
|
|
38
|
+
</Form>
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
The Field level component provided by Form, its `value` (or other properties specified by `fieldOptions.valueKey`) and `onChange` (or other callbacks specified by `onKeyChangeFnName`) are taken over by Form, so
|
|
42
|
+
|
|
43
|
+
> **Notice**
|
|
44
|
+
>
|
|
45
|
+
> 1. No longer need to use `bind:value` or `onChange` to keep the value in sync. But you can continue to listen to `onChange` for the latest values if you want
|
|
46
|
+
> 2. You cannot set the state of component with attributes such as `value`, `defaultValue`, `checked`, `defaultChecked`, etc. The default value can be set by Field's `initValue` or Form's `initValues`
|
|
47
|
+
> 3. You should not modify the value of Form State directly, all changes to the data in the Form should be done by providing `formApi`, `fieldApi`
|
|
48
|
+
|
|
49
|
+
## Demos
|
|
50
|
+
|
|
51
|
+
### Various ways to declare form
|
|
52
|
+
|
|
53
|
+
Semi Form supports multiple writing at the same time.
|
|
54
|
+
|
|
55
|
+
#### Basic Usage
|
|
56
|
+
|
|
57
|
+
Use the fields whose names start with Form, such as `FormInput` and `FormSelect`, add the `field` property to each of them, and place them inside the Form. You can also set `label` properties for each field, by default is the same as field
|
|
58
|
+
|
|
59
|
+
`label` can be passed in a string directly, or declared in the form of an object, configure `required`, `optional`, `align`, `width` and other attributes to deal with more complex scenarios. To place nodes, use snippets: `fieldLabel` replaces the label content and `labelExtra` places content right after it (the help icon in the example below); snippets take precedence over the label property
|
|
60
|
+
|
|
61
|
+
> **Notice**
|
|
62
|
+
>
|
|
63
|
+
> The field attribute is required props
|
|
64
|
+
|
|
65
|
+
```svelte
|
|
66
|
+
<script lang="ts">
|
|
67
|
+
import { IconHelpCircle } from '@fibrae/semi-icons-svelte';
|
|
68
|
+
import { Form, FormInput, FormSelect, Tooltip } from '@fibrae/semi-ui-svelte';
|
|
69
|
+
|
|
70
|
+
const roleOptions = [
|
|
71
|
+
{ label: '管理员', value: 'admin' },
|
|
72
|
+
{ label: '普通用户', value: 'user' },
|
|
73
|
+
{ label: '访客', value: 'guest' },
|
|
74
|
+
];
|
|
75
|
+
</script>
|
|
76
|
+
|
|
77
|
+
{#snippet help()}
|
|
78
|
+
详情
|
|
79
|
+
{/snippet}
|
|
80
|
+
|
|
81
|
+
<Form layout="horizontal" onValueChange={(values) => console.log(values)}>
|
|
82
|
+
<FormInput field="UserName" label="用户名" style="width: 80px" />
|
|
83
|
+
<FormInput field="Password" label="密码" style="width: 176px">
|
|
84
|
+
{#snippet labelExtra()}
|
|
85
|
+
<Tooltip content={help}>
|
|
86
|
+
<IconHelpCircle aria-label="帮助" style="color: var(--semi-color-text-2)" />
|
|
87
|
+
</Tooltip>
|
|
88
|
+
{/snippet}
|
|
89
|
+
</FormInput>
|
|
90
|
+
<FormSelect field="Role" label={{ text: '角色', optional: true }} optionList={roleOptions} style="width: 176px" />
|
|
91
|
+
</Form>
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
#### Other declaration methods
|
|
95
|
+
|
|
96
|
+
When you need to get `formState`, `formApi`, `values`, etc. directly inside the Form structure, you can use the following writing
|
|
97
|
+
|
|
98
|
+
#### Via the children snippet
|
|
99
|
+
|
|
100
|
+
The `children` snippet of Form receives `{ formState, formApi, values }`; destructure what you need with `{#snippet children({ formState })}`. The render props, child render function and props.component of React all correspond to this one form in Svelte, so they are not distinguished
|
|
101
|
+
|
|
102
|
+
```svelte
|
|
103
|
+
<script lang="ts">
|
|
104
|
+
import { Form, FormInput, FormSelect } from '@fibrae/semi-ui-svelte';
|
|
105
|
+
|
|
106
|
+
const roleOptions = [
|
|
107
|
+
{ label: '管理员', value: 'admin' },
|
|
108
|
+
{ label: '普通用户', value: 'user' },
|
|
109
|
+
{ label: '访客', value: 'guest' },
|
|
110
|
+
];
|
|
111
|
+
</script>
|
|
112
|
+
|
|
113
|
+
<Form layout="horizontal" onValueChange={(values) => console.log(values)}>
|
|
114
|
+
{#snippet children(form)}
|
|
115
|
+
<FormSelect field="Role" label="角色" optionList={roleOptions} style="width: 176px" />
|
|
116
|
+
<FormInput field="UserName" label="用户名" style="width: 80px" />
|
|
117
|
+
<FormInput field="Password" label="密码" style="width: 176px" />
|
|
118
|
+
<code style="margin-block-start: 24px">{JSON.stringify(form.formState)}</code>
|
|
119
|
+
{/snippet}
|
|
120
|
+
</Form>
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
### All supported field components
|
|
124
|
+
|
|
125
|
+
```svelte
|
|
126
|
+
<script lang="ts">
|
|
127
|
+
import { IconUpload } from '@fibrae/semi-icons-svelte';
|
|
128
|
+
import {
|
|
129
|
+
Button,
|
|
130
|
+
Col,
|
|
131
|
+
Form,
|
|
132
|
+
FormCascader,
|
|
133
|
+
FormCheckbox,
|
|
134
|
+
FormCheckboxGroup,
|
|
135
|
+
FormDatePicker,
|
|
136
|
+
FormInput,
|
|
137
|
+
FormInputNumber,
|
|
138
|
+
FormRadio,
|
|
139
|
+
FormRadioGroup,
|
|
140
|
+
FormRating,
|
|
141
|
+
FormSection,
|
|
142
|
+
FormSelect,
|
|
143
|
+
FormSlider,
|
|
144
|
+
FormSwitch,
|
|
145
|
+
FormTagInput,
|
|
146
|
+
FormTextArea,
|
|
147
|
+
FormTimePicker,
|
|
148
|
+
FormTreeSelect,
|
|
149
|
+
FormUpload,
|
|
150
|
+
Row,
|
|
151
|
+
Space,
|
|
152
|
+
} from '@fibrae/semi-ui-svelte';
|
|
153
|
+
import { mockUpload } from '#/lib/mock-upload';
|
|
154
|
+
|
|
155
|
+
const today = new Date(2024, 4, 6, 10, 30, 0);
|
|
156
|
+
|
|
157
|
+
const initValues = {
|
|
158
|
+
name: 'semi',
|
|
159
|
+
business: ['ulikeCam'],
|
|
160
|
+
role: 'ued',
|
|
161
|
+
switch: true,
|
|
162
|
+
files: [
|
|
163
|
+
{
|
|
164
|
+
uid: '1',
|
|
165
|
+
name: 'vigo.png',
|
|
166
|
+
status: 'success',
|
|
167
|
+
size: '130KB',
|
|
168
|
+
preview: true,
|
|
169
|
+
url: '/assets/placeholder/avatar-d.svg',
|
|
170
|
+
},
|
|
171
|
+
{
|
|
172
|
+
uid: '2',
|
|
173
|
+
name: 'resso.jpeg',
|
|
174
|
+
status: 'validateFail',
|
|
175
|
+
size: '222KB',
|
|
176
|
+
percent: 50,
|
|
177
|
+
preview: true,
|
|
178
|
+
fileInstance: new File([new ArrayBuffer(2048)], 'resso.jpeg', { type: 'image/jpeg' }),
|
|
179
|
+
url: '/assets/placeholder/avatar-b.svg',
|
|
180
|
+
},
|
|
181
|
+
{
|
|
182
|
+
uid: '3',
|
|
183
|
+
name: 'video.jpeg',
|
|
184
|
+
status: 'uploading',
|
|
185
|
+
size: '222KB',
|
|
186
|
+
percent: 50,
|
|
187
|
+
preview: true,
|
|
188
|
+
fileInstance: new File([new ArrayBuffer(2048)], 'dy.jpeg', { type: 'image/jpeg' }),
|
|
189
|
+
url: '/assets/placeholder/avatar-a.svg',
|
|
190
|
+
},
|
|
191
|
+
],
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
const treeData = [
|
|
195
|
+
{
|
|
196
|
+
label: '亚洲',
|
|
197
|
+
value: 'Asia',
|
|
198
|
+
key: '0',
|
|
199
|
+
children: [
|
|
200
|
+
{
|
|
201
|
+
label: '中国',
|
|
202
|
+
value: 'China',
|
|
203
|
+
key: '0-0',
|
|
204
|
+
children: [
|
|
205
|
+
{ label: '北京', value: 'Beijing', key: '0-0-0' },
|
|
206
|
+
{ label: '上海', value: 'Shanghai', key: '0-0-1' },
|
|
207
|
+
],
|
|
208
|
+
},
|
|
209
|
+
],
|
|
210
|
+
},
|
|
211
|
+
{
|
|
212
|
+
label: '北美洲',
|
|
213
|
+
value: 'North America',
|
|
214
|
+
key: '1',
|
|
215
|
+
},
|
|
216
|
+
];
|
|
217
|
+
|
|
218
|
+
const roleOptions = [
|
|
219
|
+
{ label: '运营', value: 'operate' },
|
|
220
|
+
{ label: '开发', value: 'rd' },
|
|
221
|
+
{ label: '产品', value: 'pm' },
|
|
222
|
+
{ label: '设计', value: 'ued' },
|
|
223
|
+
];
|
|
224
|
+
const businessOptions = [
|
|
225
|
+
{ label: 'Semi', value: 'abc' },
|
|
226
|
+
{ label: '轻颜相机', value: 'ulikeCam' },
|
|
227
|
+
{ label: '资讯', value: 'news' },
|
|
228
|
+
];
|
|
229
|
+
|
|
230
|
+
const style = 'width: 90%';
|
|
231
|
+
</script>
|
|
232
|
+
|
|
233
|
+
<Form {initValues} onValueChange={(values) => console.log(values)} style="padding: 10px; width: 100%">
|
|
234
|
+
<FormSection>
|
|
235
|
+
{#snippet text()}基本信息{/snippet}
|
|
236
|
+
<Row>
|
|
237
|
+
<Col span={12}>
|
|
238
|
+
<FormInput field="name" initValue="mikeya" label="名称(Input)" {style} trigger="blur" />
|
|
239
|
+
</Col>
|
|
240
|
+
<Col span={12}>
|
|
241
|
+
<FormDatePicker field="date" initValue={today} label="日期(DatePicker)" placeholder="请选择生效日期" {style} />
|
|
242
|
+
</Col>
|
|
243
|
+
</Row>
|
|
244
|
+
<Row>
|
|
245
|
+
<Col span={12}>
|
|
246
|
+
<FormSelect field="role" label="角色(Select)" optionList={roleOptions} placeholder="请选择你的角色" {style} />
|
|
247
|
+
</Col>
|
|
248
|
+
<Col span={12}>
|
|
249
|
+
<FormSelect field="business" label="业务线(多选Select)" multiple optionList={businessOptions} placeholder="请选择业务线" {style}>
|
|
250
|
+
{#snippet extraText()}
|
|
251
|
+
<div style="color: var(--semi-blue-5); font-size: 14px; user-select: none; cursor: pointer">没有找到合适的业务线?</div>
|
|
252
|
+
{/snippet}
|
|
253
|
+
</FormSelect>
|
|
254
|
+
</Col>
|
|
255
|
+
</Row>
|
|
256
|
+
<Row>
|
|
257
|
+
<Col span={12}>
|
|
258
|
+
<FormCascader field="area" label="地区(Cascader)" placeholder="请选择所在地区" {style} {treeData} />
|
|
259
|
+
</Col>
|
|
260
|
+
<Col span={12}>
|
|
261
|
+
<FormTreeSelect field="tree" filterTreeNode label="节点(TreeSelect)" placeholder="请选择服务节点" {style} {treeData} />
|
|
262
|
+
</Col>
|
|
263
|
+
</Row>
|
|
264
|
+
<Row>
|
|
265
|
+
<Col span={12}>
|
|
266
|
+
<FormTagInput field="product" initValue={['abc', 'ulikeCam']} label="产品(TagInput)" placeholder="请输入产品" {style} />
|
|
267
|
+
</Col>
|
|
268
|
+
</Row>
|
|
269
|
+
<Row>
|
|
270
|
+
<Col span={24}>
|
|
271
|
+
<FormUpload action="/upload" customRequest={mockUpload} field="files" label="证明文件(Upload)">
|
|
272
|
+
<Button theme="light">
|
|
273
|
+
{#snippet icon()}
|
|
274
|
+
<IconUpload />
|
|
275
|
+
{/snippet}
|
|
276
|
+
点击上传
|
|
277
|
+
</Button>
|
|
278
|
+
</FormUpload>
|
|
279
|
+
</Col>
|
|
280
|
+
</Row>
|
|
281
|
+
</FormSection>
|
|
282
|
+
<FormSection>
|
|
283
|
+
{#snippet text()}资源详情{/snippet}
|
|
284
|
+
<Row>
|
|
285
|
+
<Col span={12}>
|
|
286
|
+
<FormTextArea field="description" label="申请理由(TextArea)" placeholder="请填写申请资源理由" style="width: 90%; height: 120px" />
|
|
287
|
+
</Col>
|
|
288
|
+
<Col span={12}>
|
|
289
|
+
<FormCheckboxGroup direction="horizontal" field="type" initValue={['user', 'admin']} label="申请类型(CheckboxGroup)" rules={[{ required: true }]}>
|
|
290
|
+
<FormCheckbox value="admin">admin</FormCheckbox>
|
|
291
|
+
<FormCheckbox value="user">user</FormCheckbox>
|
|
292
|
+
<FormCheckbox value="guest">guest</FormCheckbox>
|
|
293
|
+
<FormCheckbox value="root">root</FormCheckbox>
|
|
294
|
+
</FormCheckboxGroup>
|
|
295
|
+
<FormRadioGroup field="isMonopolize" label="是否独占资源(Radio)" rules={[{ type: 'boolean' }, { required: true, message: '必须选择是否独占 ' }]}>
|
|
296
|
+
<FormRadio value={1}>是</FormRadio>
|
|
297
|
+
<FormRadio value={0}>否</FormRadio>
|
|
298
|
+
</FormRadioGroup>
|
|
299
|
+
</Col>
|
|
300
|
+
</Row>
|
|
301
|
+
<Row>
|
|
302
|
+
<Col span={12}>
|
|
303
|
+
<FormTimePicker field="time" label="截止时刻(TimePicker)" {style} />
|
|
304
|
+
</Col>
|
|
305
|
+
<Col span={12}>
|
|
306
|
+
<FormInputNumber field="number" initValue={20} label="申请数量(InputNumber)" {style} />
|
|
307
|
+
</Col>
|
|
308
|
+
</Row>
|
|
309
|
+
<Row>
|
|
310
|
+
<Col span={12}>
|
|
311
|
+
<FormSlider field="range" initValue={10} label="资源使用报警阈值(%)(Slider)" {style} />
|
|
312
|
+
</Col>
|
|
313
|
+
<Col span={12}>
|
|
314
|
+
<FormSwitch field="switch" label="开关(Switch)" />
|
|
315
|
+
</Col>
|
|
316
|
+
</Row>
|
|
317
|
+
<Row>
|
|
318
|
+
<Col span={12}>
|
|
319
|
+
<FormRating field="rating" initValue={2} label="满意度(Rating)" {style} />
|
|
320
|
+
</Col>
|
|
321
|
+
</Row>
|
|
322
|
+
</FormSection>
|
|
323
|
+
<FormCheckbox field="agree" noLabel value="false">我已阅读并清楚相关规定(Checkbox)</FormCheckbox>
|
|
324
|
+
<Space>
|
|
325
|
+
<Button class="btn-margin-right" htmlType="submit" type="primary">提交(submit)</Button>
|
|
326
|
+
<Button htmlType="reset">重置(reset)</Button>
|
|
327
|
+
</Space>
|
|
328
|
+
</Form>
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
#### Transfer field
|
|
332
|
+
|
|
333
|
+
The value of a Transfer field is the array of the selected items' values. Its initial value, validation and reset work like any other field. With `blur` in `trigger`, validation runs and the field is marked touched only once the focus leaves the whole Transfer, not when it moves between the search box and the lists.
|
|
334
|
+
|
|
335
|
+
```svelte
|
|
336
|
+
<script lang="ts">
|
|
337
|
+
import { Form, FormTransfer, type RuleItem } from '@fibrae/semi-ui-svelte';
|
|
338
|
+
|
|
339
|
+
const dataSource = Array.from({ length: 6 }, (_, index) => ({ label: `成员 ${index + 1}`, value: index + 1, key: index + 1 }));
|
|
340
|
+
const initValues = { members: [1, 3] };
|
|
341
|
+
const rules: RuleItem[] = [{ required: true, type: 'array', message: '请至少选择一名成员' }];
|
|
342
|
+
</script>
|
|
343
|
+
|
|
344
|
+
<Form {initValues}>
|
|
345
|
+
<FormTransfer {dataSource} field="members" label="项目成员" {rules} style="width: 480px; height: 320px" />
|
|
346
|
+
</Form>
|
|
347
|
+
```
|
|
348
|
+
|
|
349
|
+
### Field binding syntax
|
|
350
|
+
|
|
351
|
+
Every Field component must have a `field` property. This is how the form manages the state of this field. See the field syntax section below for additional details on what you can pass in for field.
|
|
352
|
+
|
|
353
|
+
The field can be a simple string, can be contained`.`Or`[]`String that supports multi-level nesting\
|
|
354
|
+
Below is an example of the field name and their mapping path in FormState
|
|
355
|
+
|
|
356
|
+
| Field | Resolution |
|
|
357
|
+
| - | - |
|
|
358
|
+
| username | formState.values.username |
|
|
359
|
+
| user\[0] | formState.values.user\[0] |
|
|
360
|
+
| siblings.1 | formState.values.siblings\[1] |
|
|
361
|
+
| siblings\['2'] | formState.values.siblings\[2] |
|
|
362
|
+
| parents\[0].name | formState.values.parents\[0].name |
|
|
363
|
+
| parents\[1]\['name'] | formState.values.parents\[1].name |
|
|
364
|
+
|
|
365
|
+
```svelte
|
|
366
|
+
<script lang="ts">
|
|
367
|
+
import { Col, Form, FormInput, FormLabel, Row, TextArea, Toast } from '@fibrae/semi-ui-svelte';
|
|
368
|
+
</script>
|
|
369
|
+
|
|
370
|
+
<Form onSubmit={(values) => Toast.info({ content: JSON.stringify(values) })}>
|
|
371
|
+
{#snippet children(form)}
|
|
372
|
+
<Row>
|
|
373
|
+
<Col span={12}>
|
|
374
|
+
<FormInput aria-label="username" field="username" placeholder="请尝试输入值" />
|
|
375
|
+
<FormInput aria-label="user[0]" field="user[0]" placeholder="请尝试输入值" />
|
|
376
|
+
<FormInput aria-label="siblings.1" field="siblings.1" placeholder="请尝试输入值" />
|
|
377
|
+
<FormInput aria-label="siblings['2']" field="siblings['2']" placeholder="请尝试输入值" />
|
|
378
|
+
<FormInput aria-label="parents[0].name" field="parents[0].name" placeholder="请尝试输入值" />
|
|
379
|
+
<FormInput aria-label="parents[1]['name']" field="parents[1]['name']" placeholder="请尝试输入值" />
|
|
380
|
+
</Col>
|
|
381
|
+
<Col offset={1} span={10} style="margin-block-start: 12px">
|
|
382
|
+
<FormLabel text="FormState实时映射值:" />
|
|
383
|
+
<TextArea aria-label="FormState实时映射值" value={JSON.stringify(form.formState.values)} />
|
|
384
|
+
</Col>
|
|
385
|
+
</Row>
|
|
386
|
+
{/snippet}
|
|
387
|
+
</Form>
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
### Form layout
|
|
391
|
+
|
|
392
|
+
- Vertical Layout: Arrange each field vertically (By default)\
|
|
393
|
+
Semi Design Next recommends a vertical layout.
|
|
394
|
+
|
|
395
|
+
```svelte
|
|
396
|
+
<script lang="ts">
|
|
397
|
+
import { Button, Form, FormCheckbox, FormInput, Toast } from '@fibrae/semi-ui-svelte';
|
|
398
|
+
|
|
399
|
+
const handleSubmit = (values: Record<string, unknown>) => {
|
|
400
|
+
console.log(values);
|
|
401
|
+
Toast.info('表单已提交');
|
|
402
|
+
};
|
|
403
|
+
</script>
|
|
404
|
+
|
|
405
|
+
<Form onSubmit={handleSubmit} style="width: 400px">
|
|
406
|
+
{#snippet children(form)}
|
|
407
|
+
<FormInput field="phone" label="PhoneNumber" placeholder="Enter your phone number" style="width: 100%" />
|
|
408
|
+
<FormInput field="password" label="Password" placeholder="Enter your password" style="width: 100%" />
|
|
409
|
+
<FormCheckbox field="agree" noLabel>I have read and agree to the terms of service</FormCheckbox>
|
|
410
|
+
<div style="display: flex; justify-content: space-between; align-items: center">
|
|
411
|
+
<p>
|
|
412
|
+
<span>Or</span>
|
|
413
|
+
<Button style="color: var(--semi-color-primary); margin-inline-start: 10px; cursor: pointer" theme="borderless">Sign up</Button>
|
|
414
|
+
</p>
|
|
415
|
+
<Button disabled={!form.values.agree} htmlType="submit" type="tertiary">Log in</Button>
|
|
416
|
+
</div>
|
|
417
|
+
{/snippet}
|
|
418
|
+
</Form>
|
|
419
|
+
```
|
|
420
|
+
|
|
421
|
+
- Horizontal Layout: Arrange each field horizontally You can use the horizontal layout by setting `layout='horizontal'`
|
|
422
|
+
|
|
423
|
+
```svelte
|
|
424
|
+
<script lang="ts">
|
|
425
|
+
import { Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
426
|
+
</script>
|
|
427
|
+
|
|
428
|
+
<Form layout="horizontal">
|
|
429
|
+
<FormInput field="phone" label="PhoneNumber" placeholder="Enter your phone number" />
|
|
430
|
+
<FormInput field="password" label="Password" placeholder="Enter your password" />
|
|
431
|
+
</Form>
|
|
432
|
+
```
|
|
433
|
+
|
|
434
|
+
- Label Position, Label Align\
|
|
435
|
+
You can control the position of the label in the Field and the direction of text alignment by setting `labelPosition`, `labelAlign`
|
|
436
|
+
|
|
437
|
+
```svelte
|
|
438
|
+
<script lang="ts">
|
|
439
|
+
import { Form, FormCheckbox, FormCheckboxGroup, FormInput, FormInputNumber, FormLabel, FormRadio, FormRadioGroup, FormSelect, FormSwitch, Select, type FormProps, type RuleItem } from '@fibrae/semi-ui-svelte';
|
|
440
|
+
|
|
441
|
+
let labelPosition = $state<NonNullable<FormProps['labelPosition']>>('left');
|
|
442
|
+
let labelAlign = $state<NonNullable<FormProps['labelAlign']>>('left');
|
|
443
|
+
const labelWidth = $derived(labelPosition === 'left' ? '180px' : 'auto');
|
|
444
|
+
|
|
445
|
+
const rules: RuleItem[] = [
|
|
446
|
+
{ required: true, message: 'required error' },
|
|
447
|
+
{ type: 'string', message: 'type error' },
|
|
448
|
+
{ validator: (value) => value === 'semi', message: 'should be semi' },
|
|
449
|
+
];
|
|
450
|
+
const positionOptions = [
|
|
451
|
+
{ label: 'top', value: 'top' },
|
|
452
|
+
{ label: 'left', value: 'left' },
|
|
453
|
+
];
|
|
454
|
+
const alignOptions = [
|
|
455
|
+
{ label: 'left', value: 'left' },
|
|
456
|
+
{ label: 'right', value: 'right' },
|
|
457
|
+
];
|
|
458
|
+
const nameOptions = [
|
|
459
|
+
{ label: 'mike', value: 'mike' },
|
|
460
|
+
{ label: 'jane', value: 'jane' },
|
|
461
|
+
{ label: 'kate', value: 'kate' },
|
|
462
|
+
];
|
|
463
|
+
</script>
|
|
464
|
+
|
|
465
|
+
<div style="border-block-end: 1px solid var(--semi-color-border); padding-block-end: 12px">
|
|
466
|
+
<FormLabel style="margin-inline-start: 10px">切换Label位置:</FormLabel>
|
|
467
|
+
<Select aria-label="labelPosition" bind:value={() => labelPosition, (next) => (labelPosition = next as typeof labelPosition)} optionList={positionOptions} style="width: 200px">
|
|
468
|
+
{#snippet prefix()}labelPosition{/snippet}
|
|
469
|
+
</Select>
|
|
470
|
+
<FormLabel style="margin-inline-start: 10px">切换Label文本对齐方向:</FormLabel>
|
|
471
|
+
<Select aria-label="labelAlign" bind:value={() => labelAlign, (next) => (labelAlign = next as typeof labelAlign)} optionList={alignOptions} style="width: 200px">
|
|
472
|
+
{#snippet prefix()}labelAlign{/snippet}
|
|
473
|
+
</Select>
|
|
474
|
+
</div>
|
|
475
|
+
{#key `${labelPosition}${labelAlign}`}
|
|
476
|
+
<Form {labelAlign} {labelPosition} {labelWidth} style="padding: 10px; width: 600px">
|
|
477
|
+
<FormInput field="input" label="手机号码" {rules} style="width: 200px" trigger="blur" />
|
|
478
|
+
<FormSwitch field="agree" label="是否同意" />
|
|
479
|
+
<FormInputNumber field="price" label="价格" style="width: 200px" />
|
|
480
|
+
<FormSelect field="name" label="姓名" optionList={nameOptions} style="width: 200px" />
|
|
481
|
+
<FormCheckboxGroup direction="horizontal" field="role" label="角色">
|
|
482
|
+
<FormCheckbox value="admin">admin</FormCheckbox>
|
|
483
|
+
<FormCheckbox value="user">user</FormCheckbox>
|
|
484
|
+
<FormCheckbox value="guest">guest</FormCheckbox>
|
|
485
|
+
<FormCheckbox value="root">root</FormCheckbox>
|
|
486
|
+
</FormCheckboxGroup>
|
|
487
|
+
<FormRadioGroup field="性别">
|
|
488
|
+
<FormRadio value="1">man</FormRadio>
|
|
489
|
+
<FormRadio value="2">woman</FormRadio>
|
|
490
|
+
</FormRadioGroup>
|
|
491
|
+
</Form>
|
|
492
|
+
{/key}
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
- A more complex layout.\
|
|
496
|
+
You can also combine the `Row` and `Col` provided by the `Grid` to arrange the form structure as you want.
|
|
497
|
+
|
|
498
|
+
```svelte
|
|
499
|
+
<script lang="ts">
|
|
500
|
+
import { Col, Form, FormDatePicker, FormInput, FormSelect, Row, type RuleItem } from '@fibrae/semi-ui-svelte';
|
|
501
|
+
|
|
502
|
+
const nickNameRules: RuleItem[] = [
|
|
503
|
+
{ required: true, message: 'required error' },
|
|
504
|
+
{ type: 'string', message: 'type error' },
|
|
505
|
+
{ validator: (value) => value === 'semi', message: 'should be semi' },
|
|
506
|
+
];
|
|
507
|
+
const businessOptions = [
|
|
508
|
+
{ label: 'Semi', value: 'abc' },
|
|
509
|
+
{ label: '轻颜相机', value: 'ulikeCam' },
|
|
510
|
+
{ label: '资讯', value: 'news' },
|
|
511
|
+
];
|
|
512
|
+
const roleOptions = [
|
|
513
|
+
{ label: '运营', value: 'operate' },
|
|
514
|
+
{ label: '开发', value: 'rd' },
|
|
515
|
+
{ label: '产品', value: 'pm' },
|
|
516
|
+
{ label: '设计', value: 'ued' },
|
|
517
|
+
];
|
|
518
|
+
</script>
|
|
519
|
+
|
|
520
|
+
<Form labelPosition="top" style="padding: 10px">
|
|
521
|
+
<Row>
|
|
522
|
+
<Col span={8}>
|
|
523
|
+
<FormInput field="nickName1" label="用户名" rules={nickNameRules} style="width: 250px" trigger="blur" />
|
|
524
|
+
</Col>
|
|
525
|
+
<Col span={8}>
|
|
526
|
+
<FormDatePicker field="date1" label="有效日期" style="width: 250px" />
|
|
527
|
+
</Col>
|
|
528
|
+
<Col span={8}>
|
|
529
|
+
<FormSelect field="business1" label="业务线" optionList={businessOptions} style="width: 250px" />
|
|
530
|
+
</Col>
|
|
531
|
+
</Row>
|
|
532
|
+
<Row>
|
|
533
|
+
<Col span={6}>
|
|
534
|
+
<FormInput field="nickName2" label="用户名" rules={nickNameRules} style="width: 200px" trigger="blur" />
|
|
535
|
+
</Col>
|
|
536
|
+
<Col span={6}>
|
|
537
|
+
<FormDatePicker field="date2" label="有效日期" style="width: 200px" />
|
|
538
|
+
</Col>
|
|
539
|
+
<Col span={6}>
|
|
540
|
+
<FormSelect field="business2" label="业务线" optionList={businessOptions} style="width: 200px" />
|
|
541
|
+
</Col>
|
|
542
|
+
<Col span={6}>
|
|
543
|
+
<FormSelect field="role" label="角色" optionList={roleOptions} style="width: 200px" />
|
|
544
|
+
</Col>
|
|
545
|
+
</Row>
|
|
546
|
+
</Form>
|
|
547
|
+
```
|
|
548
|
+
|
|
549
|
+
### Form grouping
|
|
550
|
+
|
|
551
|
+
Forms with many fields should group them. Use `FormSection` to group Fields and put the title in the `text` snippet (it only affects layout and does not change the data structure).
|
|
552
|
+
|
|
553
|
+
```svelte
|
|
554
|
+
<script lang="ts">
|
|
555
|
+
import { Button, Form, FormCheckbox, FormDatePicker, FormInput, FormInputNumber, FormRadio, FormRadioGroup, FormSection, FormSelect, FormSwitch, Space } from '@fibrae/semi-ui-svelte';
|
|
556
|
+
|
|
557
|
+
const today = new Date(2024, 4, 6, 10, 30, 0);
|
|
558
|
+
const userOptions = [
|
|
559
|
+
{ label: '曲晨一', value: '1' },
|
|
560
|
+
{ label: '夏可曼', value: '2' },
|
|
561
|
+
{ label: '曲晨三', value: '3' },
|
|
562
|
+
{ label: '蔡妍', value: '4' },
|
|
563
|
+
];
|
|
564
|
+
</script>
|
|
565
|
+
|
|
566
|
+
<Form style="width: 560px">
|
|
567
|
+
<FormSection>
|
|
568
|
+
{#snippet text()}基本信息{/snippet}
|
|
569
|
+
<FormInput field="name" initValue="TCS任务平台使用" label="考试名称" style="width: 560px" />
|
|
570
|
+
</FormSection>
|
|
571
|
+
<FormSection>
|
|
572
|
+
{#snippet text()}合格标准{/snippet}
|
|
573
|
+
<div style="display: flex">
|
|
574
|
+
<FormInputNumber field="pass" initValue={60} label={{ text: '及格正确率', required: true }} style="width: 80px" />
|
|
575
|
+
<FormInputNumber field="number" initValue={10} label={{ text: '合格人数', required: true }} style="width: 80px" />
|
|
576
|
+
</div>
|
|
577
|
+
</FormSection>
|
|
578
|
+
<FormSection>
|
|
579
|
+
{#snippet text()}考试时间{/snippet}
|
|
580
|
+
<FormDatePicker field="date" initValue={today} label={{ text: '开始时间', required: true }} style="width: 272px" type="dateTime" />
|
|
581
|
+
<div style="display: flex">
|
|
582
|
+
<FormInput field="time" initValue="60" label="考试时长" style="width: 176px">
|
|
583
|
+
{#snippet addonAfter()}分钟{/snippet}
|
|
584
|
+
</FormInput>
|
|
585
|
+
<FormCheckbox field="auto" initValue noLabel style="padding-block-start: 30px; margin-inline-start: 12px">到时间自动交卷</FormCheckbox>
|
|
586
|
+
</div>
|
|
587
|
+
<FormRadioGroup direction="vertical" field="type" initValue="always" label="有效时间">
|
|
588
|
+
<FormRadio value="always">永久有效</FormRadio>
|
|
589
|
+
<FormRadio value="user">自定义有效期</FormRadio>
|
|
590
|
+
</FormRadioGroup>
|
|
591
|
+
<FormRadioGroup direction="vertical" field="answerTime" initValue="always" label="答案放出时间" rules={[{ required: true }]}>
|
|
592
|
+
<FormRadio value="always">自动放出</FormRadio>
|
|
593
|
+
<FormRadio value="user">
|
|
594
|
+
<div style="display: inline-block">
|
|
595
|
+
自定义放出时间
|
|
596
|
+
<FormDatePicker field="customTime" noLabel style="width: 464px; display: inline-block" type="dateTimeRange" />
|
|
597
|
+
</div>
|
|
598
|
+
</FormRadio>
|
|
599
|
+
</FormRadioGroup>
|
|
600
|
+
</FormSection>
|
|
601
|
+
<FormSection>
|
|
602
|
+
{#snippet text()}考试人员{/snippet}
|
|
603
|
+
<div style="display: flex">
|
|
604
|
+
<FormSwitch field="open" label={{ text: '对外开放', required: true }}>
|
|
605
|
+
{#snippet checkedText()}开{/snippet}
|
|
606
|
+
{#snippet uncheckedText()}关{/snippet}
|
|
607
|
+
</FormSwitch>
|
|
608
|
+
</div>
|
|
609
|
+
<FormSelect field="users" initValue={['1', '2', '3', '4']} label={{ text: '考生', required: true }} multiple optionList={userOptions} style="width: 560px" />
|
|
610
|
+
</FormSection>
|
|
611
|
+
<Space>
|
|
612
|
+
<Button style="width: 120px; margin-block-start: 12px; margin-inline-end: 4px" theme="solid" type="primary">创建考试</Button>
|
|
613
|
+
<Button style="margin-block-start: 12px">预览</Button>
|
|
614
|
+
</Space>
|
|
615
|
+
</Form>
|
|
616
|
+
```
|
|
617
|
+
|
|
618
|
+
### wrapper Col / label Col
|
|
619
|
+
|
|
620
|
+
When you need to set a uniform layout for all Fields in a Form, you can set `wrapperCol` and `labelCol` on the `Form` to quickly generate the layout. No need to manually use `Row`, `Col` manual layout.\
|
|
621
|
+
`wrapperCol`,`labelCol`Property Configuration Reference [Col components](../basic/grid.md#Col)
|
|
622
|
+
|
|
623
|
+
```svelte
|
|
624
|
+
<script lang="ts">
|
|
625
|
+
import { Form, FormInput, FormSelect } from '@fibrae/semi-ui-svelte';
|
|
626
|
+
|
|
627
|
+
const roleOptions = [
|
|
628
|
+
{ label: '运营', value: 'operate' },
|
|
629
|
+
{ label: '开发', value: 'rd' },
|
|
630
|
+
{ label: '产品', value: 'pm' },
|
|
631
|
+
{ label: '设计', value: 'ued' },
|
|
632
|
+
];
|
|
633
|
+
</script>
|
|
634
|
+
|
|
635
|
+
<Form labelAlign="right" labelCol={{ span: 2 }} labelPosition="left" wrapperCol={{ span: 20 }}>
|
|
636
|
+
<FormInput field="name" label="姓名" placeholder="请输入姓名" style="width: 250px" trigger="blur" />
|
|
637
|
+
<FormSelect field="role" label="角色" optionList={roleOptions} placeholder="请选择角色" style="width: 250px" />
|
|
638
|
+
</Form>
|
|
639
|
+
```
|
|
640
|
+
|
|
641
|
+
### Remove automatically added Label
|
|
642
|
+
|
|
643
|
+
Form will automatically insert `Label` for Field control. If you don't need to automatically insert the Label module, you can turn off the automatic label insertion function by setting `noLabel=true` in the Field (at this time, the Field still has the ability to automatically display ErrorMessage, so the DOM structure is still different from the original component)\
|
|
644
|
+
If you want to keep the DOM structure consistent with the original component, you can use `pure=true`. At this time, the DOM structure will not change except that the data flow is taken over (you need to be responsible for the rendering of ErrorMessage, and it cannot be used by formProps.wrapperCol property impact)
|
|
645
|
+
|
|
646
|
+
```svelte
|
|
647
|
+
<script lang="ts">
|
|
648
|
+
import { Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
649
|
+
</script>
|
|
650
|
+
|
|
651
|
+
<Form onSubmit={(values) => console.log(values)} style="width: 400px">
|
|
652
|
+
<FormInput field="name" label="姓名" noLabel placeholder="请输入姓名" style="width: 250px" trigger="blur" />
|
|
653
|
+
<FormInput field="purename" placeholder="DOM结构与普通 Input 组件完全一致" pure />
|
|
654
|
+
</Form>
|
|
655
|
+
```
|
|
656
|
+
|
|
657
|
+
### Embedded Label
|
|
658
|
+
|
|
659
|
+
A Label can be inlined in a field control by setting labelPosition to `inset`. Components currently supporting this feature include `Input`, `InputNumber`, `DatePicker`, `TimePicker`, `Select`, `TreeSelect`, `Cascader`, `TagInput`, `AutoComplete`. With labelPosition `inset`, the other fields are laid out as `top` and warn in development mode.
|
|
660
|
+
|
|
661
|
+
A custom component wrapped with `FormField` is laid out with an inset label when `fieldOptions.insetLabel` is `true` (the default): it receives the `insetLabel` and `insetLabelId` props, has to render the inset label itself and write `insetLabelId` to the element that holds the label. A component that does not render an inset label sets `insetLabel` to `false` and is then laid out as `top`.
|
|
662
|
+
|
|
663
|
+
```svelte
|
|
664
|
+
<script lang="ts">
|
|
665
|
+
import { Form, FormDatePicker, FormInput, FormSelect } from '@fibrae/semi-ui-svelte';
|
|
666
|
+
|
|
667
|
+
const today = new Date(2024, 4, 6, 10, 30, 0);
|
|
668
|
+
const roleOptions = [
|
|
669
|
+
{ label: '运营', value: 'operate' },
|
|
670
|
+
{ label: '开发', value: 'rd' },
|
|
671
|
+
{ label: '产品', value: 'pm' },
|
|
672
|
+
{ label: '设计', value: 'ued' },
|
|
673
|
+
];
|
|
674
|
+
</script>
|
|
675
|
+
|
|
676
|
+
<Form labelPosition="inset" layout="horizontal">
|
|
677
|
+
<FormInput field="name" initValue="semi" label="姓名" placeholder="请输入姓名" style="width: 250px" trigger="blur" />
|
|
678
|
+
<FormSelect field="role" initValue="rd" label="角色" optionList={roleOptions} style="width: 250px" />
|
|
679
|
+
<FormDatePicker field="date" initValue={today} label="开始日期" style="width: 250px" />
|
|
680
|
+
</Form>
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
### Export Label, ErrorMessage use
|
|
684
|
+
|
|
685
|
+
When the built-in Label and ErrorMessage layout does not meet the business requirements, you need to combine the positions yourself, but you want to use the default styles of Label and ErrorMessage directly.\
|
|
686
|
+
you can import `FormLabel` / `FormErrorMessage` and combine them by yourself.\
|
|
687
|
+
For details of their API, refer to [FormLabel](#FormLabel) / [FormErrorMessage](#FormErrorMessage)
|
|
688
|
+
|
|
689
|
+
```ts
|
|
690
|
+
import { FormErrorMessage, FormLabel } from '@fibrae/semi-ui-svelte';
|
|
691
|
+
```
|
|
692
|
+
|
|
693
|
+
### Use FormSlot
|
|
694
|
+
|
|
695
|
+
When your custom component needs to maintain the same layout style as the Field component, you can place your custom component in `FormSlot`\
|
|
696
|
+
`labelWidth`, `labelAlign`, `wrapperCol`, `labelCol` set on the Form component automatically acts on `FormSlot`\
|
|
697
|
+
For the FormSlot property configuration, refer to [FormSlot](#FormSlot)
|
|
698
|
+
|
|
699
|
+
```svelte
|
|
700
|
+
<script lang="ts">
|
|
701
|
+
import { Form, FormInput, FormSlot } from '@fibrae/semi-ui-svelte';
|
|
702
|
+
</script>
|
|
703
|
+
|
|
704
|
+
<Form labelPosition="left" labelWidth={100} onChange={(v) => console.log(v)} onSubmit={(v) => console.log(v)} style="width: 600px">
|
|
705
|
+
<FormInput field="特效名称" style="width: 250px" />
|
|
706
|
+
<FormSlot error={['我是SlotA的ErrorMessage']} label={{ text: 'SlotA' }}>
|
|
707
|
+
<div style="display: flex; align-items: center; height: 32px; margin-block-start: 8px">我是Semi Form SlotA, 我是自定义的节点</div>
|
|
708
|
+
</FormSlot>
|
|
709
|
+
<FormSlot label={{ text: 'SlotB', width: 160, align: 'right' }}>
|
|
710
|
+
<div style="display: flex; align-items: center; height: 100%">我是Semi Form SlotB, 我的Label Align、Width与众不同</div>
|
|
711
|
+
</FormSlot>
|
|
712
|
+
</Form>
|
|
713
|
+
```
|
|
714
|
+
|
|
715
|
+
### Use helpText、extraText set prompt information
|
|
716
|
+
|
|
717
|
+
You can place custom prompt information through the `helpText` snippet, and display it in the same block as the verification information (error). When both have values, the verification information will be displayed first.\
|
|
718
|
+
Additional prompt information can be placed through the `extraText` snippet. When the error message and prompt text need to appear at the same time, this snippet can be used. It is always displayed and located after helpText/error\
|
|
719
|
+
When `validateStatus` is passed in, the UI style corresponding to the value of validateStatus will be displayed first. If not passed in, the internal verification status of the field shall prevail.
|
|
720
|
+
|
|
721
|
+
```svelte
|
|
722
|
+
<script lang="ts">
|
|
723
|
+
import { Form, FormInput, type FormApi, type ValidateStatus } from '@fibrae/semi-ui-svelte';
|
|
724
|
+
|
|
725
|
+
let helpText = $state('');
|
|
726
|
+
let validateStatus = $state<ValidateStatus>('default');
|
|
727
|
+
let formApi: FormApi | undefined;
|
|
728
|
+
|
|
729
|
+
const validator = (val?: string) => {
|
|
730
|
+
if (!val) {
|
|
731
|
+
validateStatus = 'error';
|
|
732
|
+
return '密码不能为空';
|
|
733
|
+
} else if (val.length <= 3) {
|
|
734
|
+
validateStatus = 'warning';
|
|
735
|
+
helpText = '密码强度:弱'; // 展示 helpText
|
|
736
|
+
return ''; // 校验通过
|
|
737
|
+
}
|
|
738
|
+
helpText = '';
|
|
739
|
+
validateStatus = 'success';
|
|
740
|
+
return '';
|
|
741
|
+
};
|
|
742
|
+
|
|
743
|
+
const random = () => {
|
|
744
|
+
const pw = (Math.random() * 100000).toString().slice(0, 5);
|
|
745
|
+
formApi?.setValue('Password', pw);
|
|
746
|
+
formApi?.setError('Password', '');
|
|
747
|
+
helpText = '';
|
|
748
|
+
validateStatus = 'success';
|
|
749
|
+
};
|
|
750
|
+
</script>
|
|
751
|
+
|
|
752
|
+
{#snippet weak()}
|
|
753
|
+
<span style="color: var(--semi-color-warning)">{helpText}</span>
|
|
754
|
+
{/snippet}
|
|
755
|
+
|
|
756
|
+
{#snippet generate()}
|
|
757
|
+
<button style="padding: 0; border: none; background: none; font: inherit; color: var(--semi-color-link); font-size: 14px; user-select: none; cursor: pointer" type="button" onclick={random}> 没有想到合适的密码?点击随机生成一个 </button>
|
|
758
|
+
{/snippet}
|
|
759
|
+
|
|
760
|
+
<Form getFormApi={(api) => (formApi = api)} onSubmit={() => console.log('submit success')} onSubmitFail={(errors) => console.log(errors)} showValidateIcon>
|
|
761
|
+
<FormInput extraText={generate} field="Password" helpText={helpText ? weak : undefined} {validateStatus} {validator} />
|
|
762
|
+
</Form>
|
|
763
|
+
```
|
|
764
|
+
|
|
765
|
+
By configuring `extraTextPosition`, you can control the display position of extraText. Optional values `bottom`, `middle`\
|
|
766
|
+
For example, when you want to display the extraText prompt information between the Label and Field component.\
|
|
767
|
+
This attribute can be configured uniformly on the Form or individually on each Field. When passing in at the same time, the configuration of the Field shall prevail.
|
|
768
|
+
|
|
769
|
+
```svelte
|
|
770
|
+
<script lang="ts">
|
|
771
|
+
import { Form, FormCheckboxGroup, FormInputNumber } from '@fibrae/semi-ui-svelte';
|
|
772
|
+
|
|
773
|
+
const options = [
|
|
774
|
+
{ label: '办公通知', value: 'office' },
|
|
775
|
+
{ label: '邮件通知', value: 'email' },
|
|
776
|
+
{ label: '顶部横幅通知', value: 'notification' },
|
|
777
|
+
];
|
|
778
|
+
const notifyText = '未勾选时,默认为红点提醒,消息默认进入收件人消息列表。对于重要通知,可同时勾选相应的通知方式。';
|
|
779
|
+
const forceText = '对于对话框通知,可指定该消息必须在指定时长后才可置为已读。';
|
|
780
|
+
</script>
|
|
781
|
+
|
|
782
|
+
<Form extraTextPosition="middle">
|
|
783
|
+
<FormCheckboxGroup direction="horizontal" field="notify" label="通知方式" {options}>
|
|
784
|
+
{#snippet extraText()}
|
|
785
|
+
{notifyText}
|
|
786
|
+
{/snippet}
|
|
787
|
+
</FormCheckboxGroup>
|
|
788
|
+
<FormInputNumber extraTextPosition="bottom" field="force" label="强制读取(可选)" placeholder="秒">
|
|
789
|
+
{#snippet extraText()}
|
|
790
|
+
{forceText}
|
|
791
|
+
{/snippet}
|
|
792
|
+
</FormInputNumber>
|
|
793
|
+
</Form>
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
### Using Input Group
|
|
797
|
+
|
|
798
|
+
When you need to combine some fields to use, you can use `FormInputGroup` to wrap them. Only the direct children that set `field` are rendered inside the group.\
|
|
799
|
+
When you add the field property to fields such as `FormSelect` and `FormInput`, `Form` automatically inserts a `Label` for each of them by default.\
|
|
800
|
+
But usually, in `FormInputGroup` you only need a Label belonging to the entire Group. You can set the label property in the `FormInputGroup` to insert a Label belonging to the Group\
|
|
801
|
+
`label` configurable properties, see [FormLabel](#FormLabel)
|
|
802
|
+
|
|
803
|
+
```svelte
|
|
804
|
+
<script lang="ts">
|
|
805
|
+
import { Button, Form, FormInput, FormInputGroup, FormSelect } from '@fibrae/semi-ui-svelte';
|
|
806
|
+
|
|
807
|
+
const prefixOptions = [
|
|
808
|
+
{ label: '美国+1', value: '+1' },
|
|
809
|
+
{ label: '香港+852', value: '+852' },
|
|
810
|
+
{ label: '中国+86', value: '+86' },
|
|
811
|
+
{ label: '日本+81', value: '+81' },
|
|
812
|
+
];
|
|
813
|
+
</script>
|
|
814
|
+
|
|
815
|
+
<Form labelPosition="top" onSubmit={(values) => console.log(values)} style="width: 400px">
|
|
816
|
+
<FormInputGroup label={{ text: '手机号码', required: true }} labelPosition="top">
|
|
817
|
+
<FormSelect field="phonePrefix" initValue="+86" optionList={prefixOptions} rules={[{ required: true }]} showClear style="width: 150px" />
|
|
818
|
+
<FormInput field="phoneNumber" initValue="18912345678" rules={[{ required: true }]} showClear style="width: 250px" />
|
|
819
|
+
</FormInputGroup>
|
|
820
|
+
<FormInput field="姓名" initValue="Semi" trigger="blur" />
|
|
821
|
+
<Button htmlType="submit">提交</Button>
|
|
822
|
+
</Form>
|
|
823
|
+
```
|
|
824
|
+
|
|
825
|
+
### Form in the Modal pop-up layer
|
|
826
|
+
|
|
827
|
+
You can place the Form in Modal and load it as a popup.\
|
|
828
|
+
When submitting, use `formApi.validate()` to centrally verify the Field
|
|
829
|
+
|
|
830
|
+
```svelte
|
|
831
|
+
<script lang="ts">
|
|
832
|
+
import { Button, Col, Form, FormInput, FormSelect, Modal, Row, type FormApi } from '@fibrae/semi-ui-svelte';
|
|
833
|
+
|
|
834
|
+
const message = '该项为必填项';
|
|
835
|
+
const rules = [{ required: true, message }];
|
|
836
|
+
const regions = [
|
|
837
|
+
{ value: 'China', label: '中国' },
|
|
838
|
+
{ value: 'US', label: '美国' },
|
|
839
|
+
{ value: 'Europe', label: '欧洲' },
|
|
840
|
+
{ value: 'Japan', label: '日本' },
|
|
841
|
+
];
|
|
842
|
+
|
|
843
|
+
let visible = $state(false);
|
|
844
|
+
let formApi: FormApi | undefined;
|
|
845
|
+
|
|
846
|
+
const handleOk = () => {
|
|
847
|
+
formApi
|
|
848
|
+
?.validate()
|
|
849
|
+
.then((values) => {
|
|
850
|
+
console.log(values);
|
|
851
|
+
})
|
|
852
|
+
.catch((errors) => {
|
|
853
|
+
console.log(errors);
|
|
854
|
+
});
|
|
855
|
+
};
|
|
856
|
+
</script>
|
|
857
|
+
|
|
858
|
+
<Button onclick={() => (visible = true)}>打开弹窗</Button>
|
|
859
|
+
<Modal bind:visible onOk={handleOk} style="width: 600px" title="新建">
|
|
860
|
+
<Form getFormApi={(api) => (formApi = api)}>
|
|
861
|
+
<Row>
|
|
862
|
+
<Col span={5}>
|
|
863
|
+
<FormSelect field="region" label="国家/地区" optionList={regions} placeholder="请选择" {rules} style="width: 100%" />
|
|
864
|
+
</Col>
|
|
865
|
+
<Col offset={2} span={15}>
|
|
866
|
+
<FormInput field="owner" label="业务执行人" {rules} trigger="blur" />
|
|
867
|
+
</Col>
|
|
868
|
+
</Row>
|
|
869
|
+
<Row>
|
|
870
|
+
<Col span={5}>
|
|
871
|
+
<FormSelect field="area" label="投放区域" optionList={regions} placeholder="请选择" {rules} style="width: 100%" />
|
|
872
|
+
</Col>
|
|
873
|
+
<Col offset={2} span={15}>
|
|
874
|
+
<FormInput field="department" label="业务执行部门" {rules} trigger="blur" />
|
|
875
|
+
</Col>
|
|
876
|
+
</Row>
|
|
877
|
+
</Form>
|
|
878
|
+
</Modal>
|
|
879
|
+
```
|
|
880
|
+
|
|
881
|
+
### Configure initial values and verification rules
|
|
882
|
+
|
|
883
|
+
- You can configure check rules for each Field through `rules`. Rules are run by Semi's built-in rule engine, see the table below
|
|
884
|
+
- You can uniformly set the initial value for the entire form through the `initValues` of form, or you can set the initial value through `initValue` in each field (the latter has a higher priority)
|
|
885
|
+
- You can configure different verification trigger timings for each Field through `trigger`, and the default is `change` (that is, the verification is performed automatically when the value changes). Also supports `change`, `blur`, `mount`, `custom` or a combination of the above. It also supports unified configuration through FormProps. If both are configured, FieldProps shall prevail
|
|
886
|
+
- You can use the `stopValidateWithError` switch to decide whether to continue to trigger the validation of subsequent rules when the first rule that fails the validation is encountered. Unified configuration through FormProps is also supported. If both are configured, FieldProps shall prevail
|
|
887
|
+
|
|
888
|
+
```svelte
|
|
889
|
+
<script lang="ts">
|
|
890
|
+
import { Button, Form, FormInput, type RuleItem } from '@fibrae/semi-ui-svelte';
|
|
891
|
+
|
|
892
|
+
const initValues = {
|
|
893
|
+
name: 'semi',
|
|
894
|
+
shortcut: 'se',
|
|
895
|
+
};
|
|
896
|
+
|
|
897
|
+
const style = 'width: 100%';
|
|
898
|
+
|
|
899
|
+
const rules: RuleItem[] = [
|
|
900
|
+
{ required: true, message: 'required error' },
|
|
901
|
+
{ type: 'string', message: 'type error' },
|
|
902
|
+
{ validator: (value) => value === 'semi', message: 'should be semi' },
|
|
903
|
+
{
|
|
904
|
+
validator: (value) => Boolean(value && value.startsWith('se')),
|
|
905
|
+
message: 'should startsWith se',
|
|
906
|
+
},
|
|
907
|
+
];
|
|
908
|
+
</script>
|
|
909
|
+
|
|
910
|
+
<Form {initValues}>
|
|
911
|
+
<FormInput field="name" {rules} {style} trigger="blur" />
|
|
912
|
+
<FormInput field="shortcut" {rules} stopValidateWithError {style} />
|
|
913
|
+
<Button htmlType="submit">提交</Button>
|
|
914
|
+
</Form>
|
|
915
|
+
```
|
|
916
|
+
|
|
917
|
+
Each rule (`RuleItem`) is checked from top to bottom in the table below, and the message of the first failing check becomes the error of that rule. When the value is empty (`undefined`, `null`, `''`, `[]`) and not required, the built-in checks are skipped and only `validator` runs.
|
|
918
|
+
|
|
919
|
+
| Property | Description |
|
|
920
|
+
| - | - |
|
|
921
|
+
| transform | `(value) => any`, converts the value before validation, affecting this rule only |
|
|
922
|
+
| required | Fails when the value is empty; with `whitespace: true`, a string containing only whitespace also counts as empty |
|
|
923
|
+
| type | Value type: `string`, `number`, `integer`, `float`, `boolean`, `array`, `object`, `date`, `email`, `url`, `regexp`, `method` |
|
|
924
|
+
| len, min, max | Compares the character count of a string, the value of a number, and the item count of an array |
|
|
925
|
+
| pattern | A RegExp or a regex string; only checks strings |
|
|
926
|
+
| enum | The value must be one of the items in the array |
|
|
927
|
+
| validator | `(value, values) => string \| string[] \| boolean \| Promise<...>`, runs after the built-in checks pass. Fails when it returns `false` or throws; a non-empty string or string array is used as the error message; any other result counts as passed |
|
|
928
|
+
| message | Replaces the default message of any check in this rule; pass `''` to fail without showing text |
|
|
929
|
+
|
|
930
|
+
Default messages come from the `Form` section of the locale and follow LocaleProvider (for example "This field is required" and "At least 3 characters").
|
|
931
|
+
|
|
932
|
+
### Custom Validate (Form Level)
|
|
933
|
+
|
|
934
|
+
You can set a custom validation function for the `Form` as a whole with `validator`. It will be called on submit or when calling `formApi.validate()`.
|
|
935
|
+
|
|
936
|
+
> **Notice**
|
|
937
|
+
>
|
|
938
|
+
> After the Form level validator is configured, the Field level validators (fieldProps.validator, fieldProps.rules) no longer take effect
|
|
939
|
+
|
|
940
|
+
#### Synchronous Validate
|
|
941
|
+
|
|
942
|
+
When validation passes, return an empty value or `{}`.\
|
|
943
|
+
When validation fails, return an error object with the same shape as the values, whose leaves are error messages (a string or an array of strings); an empty string means that field passes. Errors in `formState.errors` are always arrays of strings: after returning `{ name: 'Required' }`, `formApi.getError('name')` gives `['Required']`
|
|
944
|
+
|
|
945
|
+
```svelte
|
|
946
|
+
<script lang="ts">
|
|
947
|
+
import { Button, Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
948
|
+
|
|
949
|
+
interface FormValues {
|
|
950
|
+
name?: string;
|
|
951
|
+
sex?: string;
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const syncValidate = (values: FormValues) => {
|
|
955
|
+
const errors: Record<string, unknown> = {};
|
|
956
|
+
if (values.name !== 'mike') {
|
|
957
|
+
errors.name = 'you must name mike';
|
|
958
|
+
}
|
|
959
|
+
if (values.sex !== 'female') {
|
|
960
|
+
errors.sex = 'must be woman';
|
|
961
|
+
}
|
|
962
|
+
errors.familyName = [{ before: 'before error balabala ', after: 'after error balabala' }, 'familyName[1] error balabala'];
|
|
963
|
+
return errors;
|
|
964
|
+
};
|
|
965
|
+
</script>
|
|
966
|
+
|
|
967
|
+
<Form layout="horizontal" validator={syncValidate}>
|
|
968
|
+
<FormInput field="name" trigger="blur" />
|
|
969
|
+
<FormInput field="familyName[0].before" trigger="blur" />
|
|
970
|
+
<FormInput field="familyName[0].after" trigger="blur" />
|
|
971
|
+
<FormInput field="familyName[1]" trigger="blur" />
|
|
972
|
+
<div style="display: flex; align-items: flex-end">
|
|
973
|
+
<Button class="btn-margin-right" htmlType="submit" type="primary">Submit</Button>
|
|
974
|
+
<Button htmlType="reset">reset</Button>
|
|
975
|
+
</div>
|
|
976
|
+
</Form>
|
|
977
|
+
```
|
|
978
|
+
|
|
979
|
+
#### Asynchronous Validate
|
|
980
|
+
|
|
981
|
+
For asynchronous validation, you should return a promise. In promise.then() you need to return the corresponding error message.
|
|
982
|
+
|
|
983
|
+
```svelte
|
|
984
|
+
<script lang="ts">
|
|
985
|
+
import { Button, Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
986
|
+
|
|
987
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
988
|
+
|
|
989
|
+
interface FormValues {
|
|
990
|
+
name?: string;
|
|
991
|
+
sex?: string;
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
const asyncValidate = (values: FormValues) =>
|
|
995
|
+
sleep(2000).then(() => {
|
|
996
|
+
const errors: FormValues = {};
|
|
997
|
+
if (values.name !== 'mike') {
|
|
998
|
+
errors.name = 'you must name mike';
|
|
999
|
+
}
|
|
1000
|
+
if (values.sex !== 'female') {
|
|
1001
|
+
errors.sex = 'sex not valid';
|
|
1002
|
+
}
|
|
1003
|
+
return errors;
|
|
1004
|
+
});
|
|
1005
|
+
</script>
|
|
1006
|
+
|
|
1007
|
+
<Form layout="horizontal" validator={asyncValidate}>
|
|
1008
|
+
<FormInput field="name" trigger="blur" />
|
|
1009
|
+
<FormInput field="familyName[0].before" trigger="blur" />
|
|
1010
|
+
<FormInput field="familyName[1]" trigger="blur" />
|
|
1011
|
+
<FormInput field="sex" trigger="blur" />
|
|
1012
|
+
<div style="display: flex; align-items: flex-end">
|
|
1013
|
+
<Button class="btn-margin-right" htmlType="submit" type="primary">Submit</Button>
|
|
1014
|
+
<Button htmlType="reset">reset</Button>
|
|
1015
|
+
</div>
|
|
1016
|
+
</Form>
|
|
1017
|
+
```
|
|
1018
|
+
|
|
1019
|
+
### Validate with a Schema
|
|
1020
|
+
|
|
1021
|
+
`schema` accepts any validation library that implements [Standard Schema](https://standardschema.dev), such as [Zod](https://zod.dev), [Valibot](https://valibot.dev) and [ArkType](https://arktype.io). You install the library yourself; Semi does not depend on it.
|
|
1022
|
+
|
|
1023
|
+
Fields validate on their own `trigger` as usual, and submit validates all of them. Once all fields pass, the submit callback and `formApi.validate()` receive the schema's output (trimmed or coerced values, for example) while `formState.values` keeps what the user typed. `formApi.validate(['fieldA'])` validates only some fields and resolves with the raw values.
|
|
1024
|
+
|
|
1025
|
+
```svelte
|
|
1026
|
+
<script lang="ts">
|
|
1027
|
+
import * as z from 'zod';
|
|
1028
|
+
import { Button, Form, FormInput, Toast } from '@fibrae/semi-ui-svelte';
|
|
1029
|
+
|
|
1030
|
+
const schema = z
|
|
1031
|
+
.object({
|
|
1032
|
+
name: z.string({ error: '请输入姓名' }).trim().min(2, '姓名至少 2 个字符'),
|
|
1033
|
+
age: z.coerce.number({ error: '年龄要填数字' }).min(18, '需要年满 18 岁'),
|
|
1034
|
+
password: z.string({ error: '请输入密码' }).min(8, '密码至少 8 位'),
|
|
1035
|
+
confirm: z.string({ error: '请再次输入密码' }),
|
|
1036
|
+
})
|
|
1037
|
+
.refine((values) => values.password === values.confirm, { path: ['confirm'], error: '两次输入的密码不一致' });
|
|
1038
|
+
</script>
|
|
1039
|
+
|
|
1040
|
+
<Form onSubmit={(values) => Toast.success(`姓名:${values.name},明年 ${values.age + 1} 岁`)} {schema}>
|
|
1041
|
+
<FormInput field="name" label={{ text: '姓名', required: true }} />
|
|
1042
|
+
<FormInput field="age" label={{ text: '年龄', required: true }} />
|
|
1043
|
+
<FormInput field="password" label={{ text: '密码', required: true }} type="password" />
|
|
1044
|
+
<FormInput field="confirm" label={{ text: '确认密码', required: true }} type="password" />
|
|
1045
|
+
<Button htmlType="submit" type="primary">提交</Button>
|
|
1046
|
+
</Form>
|
|
1047
|
+
```
|
|
1048
|
+
|
|
1049
|
+
Where validation comes from and where errors go:
|
|
1050
|
+
|
|
1051
|
+
- A Form validates from one source. With a `schema`, the `validator` and `rules` of the fields no longer run, and the Form warns in development; a field sits on another component, so TypeScript cannot catch this combination. Passing both the Form `validator` and `schema` is a TypeScript error; past the types, the Form warns in development and uses only `validator`.
|
|
1052
|
+
- One validation round runs the schema once. Asynchronous checks in the schema, such as a uniqueness request, run every round. To limit requests, set `schemaDebounce` (in milliseconds) on the Form: validation triggered by a value change waits until input pauses, while validation triggered by submit, `formApi.validate()` or blur does not wait. You can also set the field's `trigger` to `blur`.
|
|
1053
|
+
- Write errors returned by a server after submit with `formApi.setError`; the schema's result replaces them the next time that field validates.
|
|
1054
|
+
- Changing a field shows errors only on that field and on touched fields, so a cross-field error needs a `path` pointing at the field that shows it, like the password confirmation in the demo.
|
|
1055
|
+
- An error whose path points inside a field (`tags[0]` of a TagInput, for example) shows on the field holding that value. An error without a matching field is not displayed and stays in `formState.errors`; root-level schema errors go to `errors['']`.
|
|
1056
|
+
|
|
1057
|
+
When using Zod:
|
|
1058
|
+
|
|
1059
|
+
- With `allowEmpty` off, a field left blank or cleared holds `undefined`, not an empty string. Write a required field as `z.string({ error: 'Please enter a name' })`; `.min(1, '...')` alone shows Zod's type error.
|
|
1060
|
+
- While a field is blank, Zod does not run an object-level `refine`, so a cross-field error appears only after the related fields have values.
|
|
1061
|
+
- `z.object` drops undeclared keys by default, so those fields are missing from the values the submit callback receives. Use `z.looseObject` to keep them.
|
|
1062
|
+
- Zod decides the error language; Semi's locale does not affect it. Call `z.config(z.locales.en())`, or write your own messages as in the demo.
|
|
1063
|
+
- Write `import * as z from 'zod'` so the bundler can drop the parts you do not use.
|
|
1064
|
+
|
|
1065
|
+
With a `schema`, the required asterisk and `aria-required` are decided only by `required: true` in the field's `label` config; they do not read `rules` and are not derived from the schema. A field's `transform` does not change the value the schema receives.
|
|
1066
|
+
|
|
1067
|
+
### Custom Validate (Field Level)
|
|
1068
|
+
|
|
1069
|
+
You can specify custom validation for a single Field with `validator`. Supports synchronous and asynchronous validation (by returning promises)
|
|
1070
|
+
|
|
1071
|
+
- When a function is passed, its signature is `(fieldValue, values) => string | string[] | Promise<string | string[]>`. An empty string, an empty array or an empty value means passed; anything else is used as the error message.
|
|
1072
|
+
- You can also pass a Standard Schema object (such as `z.string().min(3)`); the error message comes from the issues of the schema.
|
|
1073
|
+
|
|
1074
|
+
> **validator and rules are mutually exclusive**
|
|
1075
|
+
>
|
|
1076
|
+
> A Field takes either `validator` or `rules`, not both. Passing both is a TypeScript error; past the types, it warns in development and only `validator` runs. Use `validator` for whole-field custom checks; use `rules` when you need multiple rules or want to reuse built-in checks such as required, type and pattern. Custom checks inside a single rule go in `rules[].validator`.
|
|
1077
|
+
|
|
1078
|
+
```svelte
|
|
1079
|
+
<script lang="ts">
|
|
1080
|
+
import { Button, Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
1081
|
+
|
|
1082
|
+
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1083
|
+
|
|
1084
|
+
const validateName = (val?: string) => {
|
|
1085
|
+
if (!val) {
|
|
1086
|
+
return "【sync】can't be empty";
|
|
1087
|
+
} else if (val.length <= 5) {
|
|
1088
|
+
return '【sync】must more than 5';
|
|
1089
|
+
}
|
|
1090
|
+
return '';
|
|
1091
|
+
};
|
|
1092
|
+
|
|
1093
|
+
const asyncValidate = (val?: string) =>
|
|
1094
|
+
sleep(2000).then(() => {
|
|
1095
|
+
if (!val) {
|
|
1096
|
+
return "【async】can't be empty";
|
|
1097
|
+
} else if (val.length <= 5) {
|
|
1098
|
+
return '【async】must more than 5';
|
|
1099
|
+
} else {
|
|
1100
|
+
return '';
|
|
1101
|
+
}
|
|
1102
|
+
});
|
|
1103
|
+
</script>
|
|
1104
|
+
|
|
1105
|
+
<Form>
|
|
1106
|
+
<FormInput field="name" label="【name】asyncValidate after 2s" trigger="blur" validator={asyncValidate} />
|
|
1107
|
+
<FormInput field="familyName" label="【familyName】syncValidate" trigger="blur" validator={validateName} />
|
|
1108
|
+
<Button htmlType="reset">reset</Button>
|
|
1109
|
+
</Form>
|
|
1110
|
+
```
|
|
1111
|
+
|
|
1112
|
+
Passing a schema to the field `validator`, compared with `rules`:
|
|
1113
|
+
|
|
1114
|
+
```svelte
|
|
1115
|
+
<script lang="ts">
|
|
1116
|
+
import * as z from 'zod';
|
|
1117
|
+
import { Button, Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
1118
|
+
|
|
1119
|
+
const nickname = z.string('请输入昵称').min(3, '昵称至少 3 个字符').max(12, '昵称最多 12 个字符');
|
|
1120
|
+
|
|
1121
|
+
const usernameRules = [
|
|
1122
|
+
{ required: true, message: '请输入用户名' },
|
|
1123
|
+
{ pattern: /^[a-z0-9_]+$/, message: '只能包含小写字母、数字和下划线' },
|
|
1124
|
+
];
|
|
1125
|
+
</script>
|
|
1126
|
+
|
|
1127
|
+
<Form style="width: 400px">
|
|
1128
|
+
<FormInput field="nickname" label="昵称(validator 传 schema)" validator={nickname} />
|
|
1129
|
+
<FormInput field="username" label="用户名(rules)" rules={usernameRules} />
|
|
1130
|
+
<Button htmlType="submit">提交</Button>
|
|
1131
|
+
</Form>
|
|
1132
|
+
```
|
|
1133
|
+
|
|
1134
|
+
### Manually Trigger specified validation
|
|
1135
|
+
|
|
1136
|
+
When you want to manually trigger the validation of some specific Field, you can do it through `formApi.validate`.\
|
|
1137
|
+
When no parameters are passed in, all Fields are checked by default. When parameters are passed in, the parameters specified shall prevail
|
|
1138
|
+
|
|
1139
|
+
### Silent Validation
|
|
1140
|
+
|
|
1141
|
+
When you need to get the validation result without triggering UI updates (no error messages shown, no touched state set), you can use `formApi.validate({ silent: true })`. This is useful in scenarios where you want to decide whether to make a backend request based on the validation result.
|
|
1142
|
+
|
|
1143
|
+
```svelte
|
|
1144
|
+
<script lang="ts">
|
|
1145
|
+
import { Button, Form, FormInput, Toast, type FormApi } from '@fibrae/semi-ui-svelte';
|
|
1146
|
+
|
|
1147
|
+
let formApi: FormApi | undefined;
|
|
1148
|
+
|
|
1149
|
+
const usernameRules = [
|
|
1150
|
+
{ required: true, message: '用户名不能为空' },
|
|
1151
|
+
{ min: 3, message: '用户名至少 3 个字符' },
|
|
1152
|
+
];
|
|
1153
|
+
const emailRules = [
|
|
1154
|
+
{ required: true, message: '邮箱不能为空' },
|
|
1155
|
+
{ type: 'email' as const, message: '邮箱格式不正确' },
|
|
1156
|
+
];
|
|
1157
|
+
|
|
1158
|
+
const handleSilentValidate = () => {
|
|
1159
|
+
formApi
|
|
1160
|
+
?.validate({ silent: true })
|
|
1161
|
+
.then((values) => {
|
|
1162
|
+
Toast.success('表单校验通过,准备发起请求');
|
|
1163
|
+
console.log('发起后端请求:', values);
|
|
1164
|
+
})
|
|
1165
|
+
.catch((errors) => {
|
|
1166
|
+
Toast.error('表单校验未通过,但不显示错误提示');
|
|
1167
|
+
console.log('校验错误:', errors);
|
|
1168
|
+
});
|
|
1169
|
+
};
|
|
1170
|
+
|
|
1171
|
+
const handleNormalValidate = () => {
|
|
1172
|
+
formApi
|
|
1173
|
+
?.validate()
|
|
1174
|
+
.then(() => {
|
|
1175
|
+
Toast.success('表单校验通过');
|
|
1176
|
+
})
|
|
1177
|
+
.catch(() => {
|
|
1178
|
+
Toast.error('表单校验未通过,显示错误提示');
|
|
1179
|
+
});
|
|
1180
|
+
};
|
|
1181
|
+
</script>
|
|
1182
|
+
|
|
1183
|
+
<Form getFormApi={(api) => (formApi = api)} layout="horizontal">
|
|
1184
|
+
<FormInput field="username" label="用户名" rules={usernameRules} />
|
|
1185
|
+
<FormInput field="email" label="邮箱" rules={emailRules} />
|
|
1186
|
+
<div style="display: flex; gap: 12px; margin-block-start: 12px">
|
|
1187
|
+
<Button type="primary" onclick={handleSilentValidate}>静默校验(不显示错误)</Button>
|
|
1188
|
+
<Button onclick={handleNormalValidate}>普通校验(显示错误)</Button>
|
|
1189
|
+
</div>
|
|
1190
|
+
</Form>
|
|
1191
|
+
```
|
|
1192
|
+
|
|
1193
|
+
```svelte
|
|
1194
|
+
<script lang="ts">
|
|
1195
|
+
import { Button, Form, FormCheckboxGroup, FormInput, Space, Toast, type FormApi } from '@fibrae/semi-ui-svelte';
|
|
1196
|
+
|
|
1197
|
+
const allFields = ['a', 'b', 'c', 'd', 'b.name'];
|
|
1198
|
+
const options = allFields.map((item) => ({ label: item, value: item }));
|
|
1199
|
+
|
|
1200
|
+
const validate = (val?: string) => {
|
|
1201
|
+
if (!val) {
|
|
1202
|
+
return "can't be empty";
|
|
1203
|
+
} else if (val.length <= 5) {
|
|
1204
|
+
return '长度需大于 5';
|
|
1205
|
+
}
|
|
1206
|
+
return undefined;
|
|
1207
|
+
};
|
|
1208
|
+
|
|
1209
|
+
let formApi: FormApi | undefined;
|
|
1210
|
+
|
|
1211
|
+
const validatePartial = (type?: 'all') => {
|
|
1212
|
+
const scope = type === 'all' ? allFields : (formApi?.getValue('validateScope') ?? []);
|
|
1213
|
+
formApi
|
|
1214
|
+
?.validate(scope)
|
|
1215
|
+
.then((values) => {
|
|
1216
|
+
console.log(values);
|
|
1217
|
+
Toast.success('pass');
|
|
1218
|
+
})
|
|
1219
|
+
.catch((error) => {
|
|
1220
|
+
Toast.error('error');
|
|
1221
|
+
console.log(error);
|
|
1222
|
+
});
|
|
1223
|
+
};
|
|
1224
|
+
|
|
1225
|
+
const resetPartial = () => {
|
|
1226
|
+
formApi?.reset(formApi.getValue('resetScope'));
|
|
1227
|
+
};
|
|
1228
|
+
</script>
|
|
1229
|
+
|
|
1230
|
+
<Form autoScrollToError getFormApi={(api) => (formApi = api)} layout="horizontal">
|
|
1231
|
+
{#snippet children(form)}
|
|
1232
|
+
<div>
|
|
1233
|
+
<FormInput field="a[1]" trigger="blur" validator={validate} />
|
|
1234
|
+
<FormInput field="a[0]" trigger="blur" validator={validate} />
|
|
1235
|
+
<FormInput field="b.name[0]" trigger="blur" validator={validate} />
|
|
1236
|
+
<FormInput field="b.name[1]" trigger="blur" validator={validate} />
|
|
1237
|
+
<FormInput field="b.type" trigger="blur" validator={validate} />
|
|
1238
|
+
<FormInput field="c" trigger="blur" validator={validate} />
|
|
1239
|
+
<FormInput field="d" trigger="blur" validator={validate} />
|
|
1240
|
+
</div>
|
|
1241
|
+
<div>
|
|
1242
|
+
<FormCheckboxGroup direction="horizontal" field="validateScope" initValue={['a', 'b']} label="当前希望校验的Field" {options} />
|
|
1243
|
+
<FormCheckboxGroup direction="horizontal" field="resetScope" label="当前需要Reset的Field" {options} />
|
|
1244
|
+
<Space>
|
|
1245
|
+
<Button htmlType="reset">reset</Button>
|
|
1246
|
+
<Button onclick={() => validatePartial('all')}>all validate</Button>
|
|
1247
|
+
<Button onclick={() => validatePartial()}>partial validate {JSON.stringify(form.values.validateScope)}</Button>
|
|
1248
|
+
<Button onclick={resetPartial}>partial reset</Button>
|
|
1249
|
+
</Space>
|
|
1250
|
+
</div>
|
|
1251
|
+
{/snippet}
|
|
1252
|
+
</Form>
|
|
1253
|
+
```
|
|
1254
|
+
|
|
1255
|
+
### Linkage Fields
|
|
1256
|
+
|
|
1257
|
+
You can achieve the linkage between Fields by listening to the `onChange` of Field and then using formApi (for example saved through `getFormApi`) to make modifications.
|
|
1258
|
+
|
|
1259
|
+
```svelte
|
|
1260
|
+
<script lang="ts">
|
|
1261
|
+
import { Button, Form, FormInput, FormSelect, Row, type FormApi } from '@fibrae/semi-ui-svelte';
|
|
1262
|
+
|
|
1263
|
+
let formApi: FormApi | undefined;
|
|
1264
|
+
|
|
1265
|
+
const sexOptions = [
|
|
1266
|
+
{ label: 'female', value: 'female' },
|
|
1267
|
+
{ label: 'male', value: 'male' },
|
|
1268
|
+
];
|
|
1269
|
+
|
|
1270
|
+
const handleSelectChange = (value: unknown) => {
|
|
1271
|
+
const text = value === 'male' ? 'Hi male' : 'Hi female!';
|
|
1272
|
+
formApi?.setValue('Note', text);
|
|
1273
|
+
};
|
|
1274
|
+
</script>
|
|
1275
|
+
|
|
1276
|
+
<Form getFormApi={(api) => (formApi = api)} onValueChange={(values) => console.log(values)} style="width: 250px">
|
|
1277
|
+
<span>Note will change after Sex select</span>
|
|
1278
|
+
<FormInput field="Note" style="width: 250px" />
|
|
1279
|
+
<FormSelect field="Sex" onChange={handleSelectChange} optionList={sexOptions} style="width: 250px" />
|
|
1280
|
+
<Row>
|
|
1281
|
+
<Button class="btn-margin-right" htmlType="submit" type="primary">Submit</Button>
|
|
1282
|
+
<Button htmlType="reset">reset</Button>
|
|
1283
|
+
</Row>
|
|
1284
|
+
</Form>
|
|
1285
|
+
```
|
|
1286
|
+
|
|
1287
|
+
### Dynamic form
|
|
1288
|
+
|
|
1289
|
+
#### Dynamically add and delete fields
|
|
1290
|
+
|
|
1291
|
+
```svelte
|
|
1292
|
+
<script lang="ts">
|
|
1293
|
+
import { Button, Form, FormInput, FormRadio, FormRadioGroup } from '@fibrae/semi-ui-svelte';
|
|
1294
|
+
</script>
|
|
1295
|
+
|
|
1296
|
+
<Form style="width: 450px">
|
|
1297
|
+
{#snippet children(form)}
|
|
1298
|
+
<FormInput field="name" label="用户名称:" />
|
|
1299
|
+
<FormRadioGroup field="isAnchor" label="是否已注册主播">
|
|
1300
|
+
<FormRadio value="yes">yes</FormRadio>
|
|
1301
|
+
<FormRadio value="no">no</FormRadio>
|
|
1302
|
+
</FormRadioGroup>
|
|
1303
|
+
{#if form.formState.values?.isAnchor === 'yes'}
|
|
1304
|
+
<FormInput field="liveRoom" label="直播间名称" />
|
|
1305
|
+
{/if}
|
|
1306
|
+
<Button htmlType="submit">提交</Button>
|
|
1307
|
+
{/snippet}
|
|
1308
|
+
</Form>
|
|
1309
|
+
```
|
|
1310
|
+
|
|
1311
|
+
#### Keep empty values (allowEmpty)
|
|
1312
|
+
|
|
1313
|
+
By default a field whose value becomes empty is removed from `values`. Set `allowEmpty` on a Field to keep its key with an `undefined` value, or on Form to apply it to every field. Clear both selects below and compare the keys of `values`.
|
|
1314
|
+
|
|
1315
|
+
```svelte
|
|
1316
|
+
<script lang="ts">
|
|
1317
|
+
import { Form, FormSelect } from '@fibrae/semi-ui-svelte';
|
|
1318
|
+
|
|
1319
|
+
const initValues = { keep: 'admin', drop: 'admin' };
|
|
1320
|
+
|
|
1321
|
+
const roleOptions = [
|
|
1322
|
+
{ label: '管理员', value: 'admin' },
|
|
1323
|
+
{ label: '访客', value: 'guest' },
|
|
1324
|
+
];
|
|
1325
|
+
</script>
|
|
1326
|
+
|
|
1327
|
+
<Form {initValues}>
|
|
1328
|
+
{#snippet children(form)}
|
|
1329
|
+
<FormSelect allowEmpty field="keep" label="设置了 allowEmpty" optionList={roleOptions} showClear style="width: 176px" />
|
|
1330
|
+
<FormSelect field="drop" label="未设置" optionList={roleOptions} showClear style="width: 176px" />
|
|
1331
|
+
<code>{JSON.stringify(Object.keys(form.values))}</code>
|
|
1332
|
+
{/snippet}
|
|
1333
|
+
</Form>
|
|
1334
|
+
```
|
|
1335
|
+
|
|
1336
|
+
#### Keep field state on unmount (keepState)
|
|
1337
|
+
|
|
1338
|
+
By default, a Field keeps its value, error and touched state after it is unmounted, and restores them by field path when it mounts again. This suits conditional rendering, step-by-step forms and similar scenarios. To reset the field after it is unmounted, set `keepState` to `false`.
|
|
1339
|
+
|
|
1340
|
+
`keepState` can be set on Form, ArrayField and Field. A field that does not set it takes the value of its ArrayField, then of its Form, and defaults to `true` when none is set.
|
|
1341
|
+
|
|
1342
|
+
```svelte
|
|
1343
|
+
<script lang="ts">
|
|
1344
|
+
import { Button, Form, FormInput, FormSwitch, Switch } from '@fibrae/semi-ui-svelte';
|
|
1345
|
+
|
|
1346
|
+
let show = $state(true);
|
|
1347
|
+
</script>
|
|
1348
|
+
|
|
1349
|
+
<Form style="width: 450px">
|
|
1350
|
+
<FormSwitch field="alwaysShow" label="始终显示的字段" />
|
|
1351
|
+
<Switch aria-labelledby="form-keep-state-toggle" bind:checked={show} style="margin-block-end: 12px" />
|
|
1352
|
+
<span id="form-keep-state-toggle" style="margin-inline-start: 8px; color: var(--semi-color-text-2)"> 显示条件字段 </span>
|
|
1353
|
+
{#if show}
|
|
1354
|
+
<FormInput field="kept" label="条件字段(默认保留状态)" rules={[{ required: true, message: '必填' }]} />
|
|
1355
|
+
<FormInput field="reset" initValue="初始值" keepState={false} label={'条件字段(keepState={false})'} />
|
|
1356
|
+
{/if}
|
|
1357
|
+
<Button htmlType="submit">提交</Button>
|
|
1358
|
+
</Form>
|
|
1359
|
+
```
|
|
1360
|
+
|
|
1361
|
+
In the example above, a field whose `keepState` is `false` returns to its initial value after being hidden and shown again, while the other fields keep their previous input and validation state.
|
|
1362
|
+
|
|
1363
|
+
When an ArrayField is unmounted, it handles the whole group by its own `keepState`: when kept, mounting again renders the rows from the kept values, and `reset()` still restores the original `initValue`; when not kept, the value, errors and touched state of the whole group are deleted. When rows are removed or moved inside an ArrayField, the state of a row moves with it, and a new row does not inherit the state of a removed row.
|
|
1364
|
+
|
|
1365
|
+
### ArrayField Usage
|
|
1366
|
+
|
|
1367
|
+
For array items that are dynamically added or deleted, we provide the `ArrayField` component to simplify the operation of adding and removing rows. The `children` snippet of ArrayField provides `onAdd` and `onAddWithInitValue` to add a blank row or a row with an initial value, and the `onRemove` of each row removes that row.
|
|
1368
|
+
|
|
1369
|
+
For the detailed API of ArrayField, please refer to [ArrayField](#arrayfield) below
|
|
1370
|
+
|
|
1371
|
+
> Note: The initValue type of ArrayField must be an array
|
|
1372
|
+
|
|
1373
|
+
```svelte
|
|
1374
|
+
<script lang="ts">
|
|
1375
|
+
import { IconMinusCircle, IconPlusCircle } from '@fibrae/semi-icons-svelte';
|
|
1376
|
+
import { ArrayField, Button, Form, FormInput, FormSelect, TextArea } from '@fibrae/semi-ui-svelte';
|
|
1377
|
+
|
|
1378
|
+
const data = [
|
|
1379
|
+
{ name: 'Semi Core', role: 'Engineer' },
|
|
1380
|
+
{ name: 'Semi C2D', role: 'Designer' },
|
|
1381
|
+
];
|
|
1382
|
+
const roleOptions = [
|
|
1383
|
+
{ label: 'Engineer', value: 'Engineer' },
|
|
1384
|
+
{ label: 'Designer', value: 'Designer' },
|
|
1385
|
+
];
|
|
1386
|
+
</script>
|
|
1387
|
+
|
|
1388
|
+
{#snippet plus()}
|
|
1389
|
+
<IconPlusCircle />
|
|
1390
|
+
{/snippet}
|
|
1391
|
+
|
|
1392
|
+
{#snippet minus()}
|
|
1393
|
+
<IconMinusCircle />
|
|
1394
|
+
{/snippet}
|
|
1395
|
+
|
|
1396
|
+
<Form allowEmpty labelPosition="left" labelWidth="100px" style="width: 800px">
|
|
1397
|
+
{#snippet children(form)}
|
|
1398
|
+
<ArrayField field="rules" initValue={data}>
|
|
1399
|
+
{#snippet children(arrayField)}
|
|
1400
|
+
<Button icon={plus} theme="light" onclick={arrayField.onAdd}>Add new line</Button>
|
|
1401
|
+
<Button icon={plus} style="margin-inline-start: 8px" onclick={() => arrayField.onAddWithInitValue({ name: 'Semi Theme', role: 'Designer' })}>Add new line with init value</Button>
|
|
1402
|
+
{#each arrayField.arrayFields as item (item.key)}
|
|
1403
|
+
<div style="width: 1000px; display: flex">
|
|
1404
|
+
<FormInput field={`${item.field}[name]`} label={`${item.field}.name`} style="width: 200px; margin-inline-end: 16px" />
|
|
1405
|
+
<FormSelect field={`${item.field}[role]`} label={`${item.field}.role`} optionList={roleOptions} style="width: 120px" />
|
|
1406
|
+
<Button aria-label="Delete" icon={minus} style="margin: 12px" theme="borderless" type="danger" onclick={item.onRemove} />
|
|
1407
|
+
</div>
|
|
1408
|
+
{/each}
|
|
1409
|
+
{/snippet}
|
|
1410
|
+
</ArrayField>
|
|
1411
|
+
<TextArea aria-label="Form state" style="margin-block-start: 10px" value={JSON.stringify(form.formState)} />
|
|
1412
|
+
{/snippet}
|
|
1413
|
+
</Form>
|
|
1414
|
+
```
|
|
1415
|
+
|
|
1416
|
+
#### Moving rows
|
|
1417
|
+
|
|
1418
|
+
`onMove(from, to)` in the `children` snippet moves row `from` to `to`. The row's value, validation error, touched state and key move with it; out-of-range indexes are clamped to the first or last row.
|
|
1419
|
+
|
|
1420
|
+
```svelte
|
|
1421
|
+
<script lang="ts">
|
|
1422
|
+
import { IconArrowDown, IconArrowUp, IconDelete } from '@fibrae/semi-icons-svelte';
|
|
1423
|
+
import { ArrayField, Button, Form, FormInput, IconButton } from '@fibrae/semi-ui-svelte';
|
|
1424
|
+
|
|
1425
|
+
const initValue = [{ name: '需求评审' }, { name: '开发' }, { name: '上线' }];
|
|
1426
|
+
</script>
|
|
1427
|
+
|
|
1428
|
+
{#snippet up()}
|
|
1429
|
+
<IconArrowUp />
|
|
1430
|
+
{/snippet}
|
|
1431
|
+
|
|
1432
|
+
{#snippet down()}
|
|
1433
|
+
<IconArrowDown />
|
|
1434
|
+
{/snippet}
|
|
1435
|
+
|
|
1436
|
+
{#snippet remove()}
|
|
1437
|
+
<IconDelete />
|
|
1438
|
+
{/snippet}
|
|
1439
|
+
|
|
1440
|
+
<Form style="width: 480px">
|
|
1441
|
+
{#snippet children(form)}
|
|
1442
|
+
<ArrayField field="steps" {initValue}>
|
|
1443
|
+
{#snippet children(arrayField)}
|
|
1444
|
+
{#each arrayField.arrayFields as item, index (item.key)}
|
|
1445
|
+
<div style="display: flex; align-items: flex-start; gap: 4px">
|
|
1446
|
+
<FormInput field={`${item.field}.name`} label={`第 ${index + 1} 步`} style="width: 280px" />
|
|
1447
|
+
<!-- the field's top padding and the label sit above the input; an error message only grows the field downward -->
|
|
1448
|
+
<div style="display: flex; gap: 4px; padding-block-start: 36px">
|
|
1449
|
+
<IconButton aria-label={`上移第 ${index + 1} 步`} disabled={index === 0} icon={up} theme="borderless" onclick={() => arrayField.onMove(index, index - 1)} />
|
|
1450
|
+
<IconButton aria-label={`下移第 ${index + 1} 步`} disabled={index === arrayField.arrayFields.length - 1} icon={down} theme="borderless" onclick={() => arrayField.onMove(index, index + 1)} />
|
|
1451
|
+
<IconButton aria-label={`删除第 ${index + 1} 步`} icon={remove} theme="borderless" type="danger" onclick={item.onRemove} />
|
|
1452
|
+
</div>
|
|
1453
|
+
</div>
|
|
1454
|
+
{/each}
|
|
1455
|
+
<Button theme="light" onclick={arrayField.onAdd}>添加一步</Button>
|
|
1456
|
+
{/snippet}
|
|
1457
|
+
</ArrayField>
|
|
1458
|
+
<pre><code>{JSON.stringify(form.formState.values)}</code></pre>
|
|
1459
|
+
{/snippet}
|
|
1460
|
+
</Form>
|
|
1461
|
+
```
|
|
1462
|
+
|
|
1463
|
+
#### Nesting ArrayField
|
|
1464
|
+
|
|
1465
|
+
ArrayField supports multi-level nesting. The following is an example of two-level nesting.
|
|
1466
|
+
|
|
1467
|
+
```svelte
|
|
1468
|
+
<script lang="ts">
|
|
1469
|
+
import { IconMinusCircle, IconPlusCircle } from '@fibrae/semi-icons-svelte';
|
|
1470
|
+
import { ArrayField, Button, Card, Form, FormInput, FormSelect, Typography } from '@fibrae/semi-ui-svelte';
|
|
1471
|
+
|
|
1472
|
+
const selectOption = [
|
|
1473
|
+
{ label: '发件人地址', value: 'address' },
|
|
1474
|
+
{ label: '邮件主题', value: 'title' },
|
|
1475
|
+
{ label: '发送时间', value: 'sendTime' },
|
|
1476
|
+
{ label: '接收时间', value: 'receiveTime' },
|
|
1477
|
+
{ label: '正文', value: 'main' },
|
|
1478
|
+
{ label: '附件名称', value: 'attachmentName' },
|
|
1479
|
+
];
|
|
1480
|
+
const typeOption = [
|
|
1481
|
+
{ label: '包含', value: 'include' },
|
|
1482
|
+
{ label: '不包含', value: 'exclude' },
|
|
1483
|
+
];
|
|
1484
|
+
|
|
1485
|
+
const initValue = {
|
|
1486
|
+
group: [
|
|
1487
|
+
{
|
|
1488
|
+
name: '收信规则1',
|
|
1489
|
+
rules: [
|
|
1490
|
+
{ ruleType: 'address', type: 'include', text: 'example.com' },
|
|
1491
|
+
{ ruleType: 'title', type: 'exclude', text: '更新日志' },
|
|
1492
|
+
],
|
|
1493
|
+
},
|
|
1494
|
+
{
|
|
1495
|
+
name: '收信规则2',
|
|
1496
|
+
rules: [{ ruleType: 'sendTime', type: 'include', text: '2019' }],
|
|
1497
|
+
},
|
|
1498
|
+
],
|
|
1499
|
+
};
|
|
1500
|
+
|
|
1501
|
+
const newRule = {
|
|
1502
|
+
name: '新规则名称',
|
|
1503
|
+
rules: [
|
|
1504
|
+
{ ruleType: 'main', type: 'include', text: '' },
|
|
1505
|
+
{ ruleType: 'attachmentName', type: 'include', text: '' },
|
|
1506
|
+
],
|
|
1507
|
+
};
|
|
1508
|
+
|
|
1509
|
+
const rowStyle = 'margin-block-start: 12px; margin-inline-start: 12px';
|
|
1510
|
+
</script>
|
|
1511
|
+
|
|
1512
|
+
{#snippet plus()}
|
|
1513
|
+
<IconPlusCircle />
|
|
1514
|
+
{/snippet}
|
|
1515
|
+
|
|
1516
|
+
{#snippet minus()}
|
|
1517
|
+
<IconMinusCircle />
|
|
1518
|
+
{/snippet}
|
|
1519
|
+
|
|
1520
|
+
<Form allowEmpty initValues={initValue} labelPosition="left" onValueChange={(values) => console.log(values)} style="text-align: start">
|
|
1521
|
+
<ArrayField field="group">
|
|
1522
|
+
{#snippet children(group)}
|
|
1523
|
+
<Button icon={plus} theme="solid" onclick={() => group.onAddWithInitValue(newRule)}>新增收信规则</Button>
|
|
1524
|
+
{#each group.arrayFields as item (item.key)}
|
|
1525
|
+
<div style="width: 1000px; display: flex; flex-wrap: wrap">
|
|
1526
|
+
<FormInput field={`${item.field}[name]`} label="规则名称" labelPosition="top" style="width: 600px" />
|
|
1527
|
+
<Button aria-label="删除规则" icon={minus} style="margin-block-start: 36px; margin-inline-start: 12px" type="danger" onclick={item.onRemove} />
|
|
1528
|
+
<Typography.Text strong style="flex-basis: 100%">当邮件到达,满足以下条件时:</Typography.Text>
|
|
1529
|
+
<Card shadows="hover" style="width: 620px; margin-block-start: 12px; margin-inline-start: 24px">
|
|
1530
|
+
<ArrayField field={`${item.field}.rules`}>
|
|
1531
|
+
{#snippet children(rules)}
|
|
1532
|
+
{#each rules.arrayFields as rule, i (rule.key)}
|
|
1533
|
+
<div style="display: flex">
|
|
1534
|
+
<FormSelect field={`${rule.field}[ruleType]`} label={`${rule.field}.ruleType`} noLabel optionList={selectOption} style="width: 120px; margin-inline-end: 12px" />
|
|
1535
|
+
<FormSelect field={`${rule.field}[type]`} label={`${rule.field}.type`} noLabel optionList={typeOption} style="width: 100px; margin-inline-end: 12px" />
|
|
1536
|
+
<FormInput aria-label="条件内容" field={`${rule.field}[text]`} label={`${rule.field}.text`} noLabel style="width: 200px" />
|
|
1537
|
+
<Button aria-label="删除条件" icon={minus} style={rowStyle} theme="borderless" type="danger" onclick={rule.onRemove} />
|
|
1538
|
+
<Button aria-label="新增条件" disabled={i !== rules.arrayFields.length - 1} icon={plus} style={rowStyle} onclick={() => rules.onAddWithInitValue({ ruleType: `条件${rules.arrayFields.length + 1}`, type: 'include' })} />
|
|
1539
|
+
</div>
|
|
1540
|
+
{/each}
|
|
1541
|
+
{/snippet}
|
|
1542
|
+
</ArrayField>
|
|
1543
|
+
</Card>
|
|
1544
|
+
</div>
|
|
1545
|
+
{/each}
|
|
1546
|
+
{/snippet}
|
|
1547
|
+
</ArrayField>
|
|
1548
|
+
</Form>
|
|
1549
|
+
```
|
|
1550
|
+
|
|
1551
|
+
#### Add or delete form items dynamically - by use formApi
|
|
1552
|
+
|
|
1553
|
+
If you don't use ArrayField, you can use the provided formApi to manually add or delete formState.
|
|
1554
|
+
|
|
1555
|
+
```svelte
|
|
1556
|
+
<script lang="ts">
|
|
1557
|
+
import { Button, Form, FormInput, FormSelect, TextArea, type FormApi } from '@fibrae/semi-ui-svelte';
|
|
1558
|
+
|
|
1559
|
+
interface Effect {
|
|
1560
|
+
name: string;
|
|
1561
|
+
type: string;
|
|
1562
|
+
key: number;
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
interface FormValues {
|
|
1566
|
+
effects: Effect[];
|
|
1567
|
+
}
|
|
1568
|
+
|
|
1569
|
+
const initValues: FormValues = {
|
|
1570
|
+
effects: [
|
|
1571
|
+
{ name: '脸部贴纸', type: '2D', key: 1 },
|
|
1572
|
+
{ name: '背景贴纸', type: '3D', key: 2 },
|
|
1573
|
+
],
|
|
1574
|
+
};
|
|
1575
|
+
const typeOptions = [
|
|
1576
|
+
{ label: '2D', value: '2D' },
|
|
1577
|
+
{ label: '3D', value: '3D' },
|
|
1578
|
+
];
|
|
1579
|
+
|
|
1580
|
+
let formApi: FormApi<FormValues> | undefined;
|
|
1581
|
+
let nextKey = 3;
|
|
1582
|
+
|
|
1583
|
+
const add = () => {
|
|
1584
|
+
const effects = formApi?.getValue('effects') ?? [];
|
|
1585
|
+
formApi?.setValue('effects', [...effects, { name: '', type: '', key: nextKey++ }]);
|
|
1586
|
+
};
|
|
1587
|
+
|
|
1588
|
+
const remove = (key: number) => {
|
|
1589
|
+
const effects = (formApi?.getValue('effects') ?? []).filter((effect) => key !== effect.key);
|
|
1590
|
+
formApi?.setValue('effects', effects.length ? effects : undefined);
|
|
1591
|
+
};
|
|
1592
|
+
</script>
|
|
1593
|
+
|
|
1594
|
+
<Form getFormApi={(api) => (formApi = api)} {initValues} labelPosition="left" labelWidth="180px" style="width: 500px">
|
|
1595
|
+
{#snippet children(form)}
|
|
1596
|
+
<Button onclick={add}>添加</Button>
|
|
1597
|
+
{#each form.values.effects ?? [] as effect, i (effect.key)}
|
|
1598
|
+
<div style="width: 1000px; display: flex">
|
|
1599
|
+
<FormInput aria-label={`特效 ${i + 1} 名称`} field={`effects[${i}].name`} style="width: 200px; margin-inline-end: 12px" />
|
|
1600
|
+
<FormSelect field={`effects[${i}].type`} optionList={typeOptions} style="width: 90px" />
|
|
1601
|
+
<Button style="margin: 12px" type="danger" onclick={() => remove(effect.key)}>删除</Button>
|
|
1602
|
+
</div>
|
|
1603
|
+
{/each}
|
|
1604
|
+
<TextArea aria-label="表单值" style="margin-block-start: 10px" value={JSON.stringify(form.formState.values)} />
|
|
1605
|
+
{/snippet}
|
|
1606
|
+
</Form>
|
|
1607
|
+
```
|
|
1608
|
+
|
|
1609
|
+
### Render a form from a Schema
|
|
1610
|
+
|
|
1611
|
+
SchemaForm renders a whole form directly from a schema. With the Form `schema` passed in, SchemaForm derives a JSON Schema from it and renders a field for each property in property order. Deriving requires the validation library to implement [Standard JSON Schema](https://standardschema.dev/json-schema) (such as Zod 4); a JSON Schema from any other source can be passed directly to `jsonSchema`, which takes precedence over the derived result. SchemaForm accepts all Form props, and renders children after the fields, which suits a submit button.
|
|
1612
|
+
|
|
1613
|
+
SchemaForm and SchemaField render no UI themselves: they walk the schema, bind each field's value and validation, and hand every node to the render function of its kind in `renderers`. `semiRenderers` is a set of render functions built from Semi Form controls; pass it to `renderers` for the UI below. Without `renderers`, only the properties of objects render; fields and arrays render nothing, and a warning is shown in development.
|
|
1614
|
+
|
|
1615
|
+
```svelte
|
|
1616
|
+
<script lang="ts">
|
|
1617
|
+
import * as z from 'zod';
|
|
1618
|
+
import { Button, SchemaForm, semiRenderers } from '@fibrae/semi-ui-svelte';
|
|
1619
|
+
|
|
1620
|
+
const schema = z.object({
|
|
1621
|
+
email: z.email('邮箱格式不正确').meta({ title: '邮箱' }),
|
|
1622
|
+
bio: z.string().max(500).optional().meta({ title: '简介', description: '最多 500 字' }),
|
|
1623
|
+
age: z.int().min(0).max(150).meta({ title: '年龄' }),
|
|
1624
|
+
subscribed: z.boolean().default(false).meta({ title: '订阅周报' }),
|
|
1625
|
+
role: z.enum(['engineer', 'designer', 'pm']).meta({ title: '角色' }),
|
|
1626
|
+
address: z
|
|
1627
|
+
.object({
|
|
1628
|
+
city: z.string().meta({ title: '城市' }),
|
|
1629
|
+
street: z.string().optional().meta({ title: '街道' }),
|
|
1630
|
+
})
|
|
1631
|
+
.meta({ title: '地址' }),
|
|
1632
|
+
contacts: z
|
|
1633
|
+
.array(
|
|
1634
|
+
z.object({
|
|
1635
|
+
name: z.string().meta({ title: '联系人' }),
|
|
1636
|
+
phone: z.string().optional().meta({ title: '电话' }),
|
|
1637
|
+
})
|
|
1638
|
+
)
|
|
1639
|
+
.max(3)
|
|
1640
|
+
.meta({ title: '紧急联系人' }),
|
|
1641
|
+
tags: z.array(z.enum(['frontend', 'backend', 'design'])).meta({ title: '标签' }),
|
|
1642
|
+
});
|
|
1643
|
+
|
|
1644
|
+
let output = $state<z.output<typeof schema>>();
|
|
1645
|
+
</script>
|
|
1646
|
+
|
|
1647
|
+
<SchemaForm onSubmit={(values) => (output = values)} renderers={semiRenderers} {schema} style="width: 480px">
|
|
1648
|
+
<Button htmlType="submit" type="primary">提交</Button>
|
|
1649
|
+
{#if output}
|
|
1650
|
+
<pre style="margin-block-start: 12px">{JSON.stringify(output, null, 2)}</pre>
|
|
1651
|
+
{/if}
|
|
1652
|
+
</SchemaForm>
|
|
1653
|
+
```
|
|
1654
|
+
|
|
1655
|
+
How `semiRenderers` maps JSON Schema to controls:
|
|
1656
|
+
|
|
1657
|
+
| JSON Schema | Control |
|
|
1658
|
+
| - | - |
|
|
1659
|
+
| `string` | Input; TextArea when `maxLength` is greater than 160 |
|
|
1660
|
+
| `number`, `integer` | InputNumber; only integers can be entered for `integer` |
|
|
1661
|
+
| `boolean` | Switch |
|
|
1662
|
+
| `enum`, or `oneOf` / `anyOf` where every item has a `const` | Select; option text comes from the `title` of each item |
|
|
1663
|
+
| `array` whose items are options | Multi-select Select |
|
|
1664
|
+
| `object` with `properties` | Section; the heading comes from `title` |
|
|
1665
|
+
| Any other `array` | ArrayField; each row has move up, move down and remove buttons, with an add button below the list; the row count is fixed when `minItems` equals `maxItems` |
|
|
1666
|
+
|
|
1667
|
+
The label comes from `title` (the property name when absent), the help text from `description`, the initial value from `default`, and properties listed in `required` show the required asterisk. Rows of a single-value array (items that are neither objects nor arrays) show no label or help text and are named "array title item N"; the array's description shows in its Section. A node that maps to no control is not rendered, and a warning is shown in development.
|
|
1668
|
+
|
|
1669
|
+
SchemaField renders part of a schema inside an existing Form: `field` sets the path (the root by default), and it can be mixed with hand-written fields. Both can be customized at two levels:
|
|
1670
|
+
|
|
1671
|
+
- `renderers`: replaces the render function of one kind of node. Spread `semiRenderers` and override one entry, such as `{ ...semiRenderers, field: myField }`; the rest keep the default UI.
|
|
1672
|
+
- `renderField`: the key is a node path, with array rows written as `[]` (such as `contacts[].email`). A match replaces the render function of that node and receives what the function of its kind receives.
|
|
1673
|
+
|
|
1674
|
+
```svelte
|
|
1675
|
+
<script lang="ts">
|
|
1676
|
+
import * as z from 'zod';
|
|
1677
|
+
import { IconLink } from '@fibrae/semi-icons-svelte';
|
|
1678
|
+
import { Button, Form, FormInput, FormRating, SchemaField, semiRenderers, Toast, type SchemaFieldContext, type SchemaLeafContext } from '@fibrae/semi-ui-svelte';
|
|
1679
|
+
|
|
1680
|
+
const schema = z.object({
|
|
1681
|
+
title: z.string().min(2, '标题至少 2 个字符'),
|
|
1682
|
+
profile: z
|
|
1683
|
+
.object({
|
|
1684
|
+
homepage: z.url('请输入完整的网址').meta({ title: '主页' }),
|
|
1685
|
+
score: z.int().min(1).max(5).meta({ title: '评分' }),
|
|
1686
|
+
intro: z.string().optional().meta({ title: '介绍' }),
|
|
1687
|
+
})
|
|
1688
|
+
.meta({ title: '资料' }),
|
|
1689
|
+
});
|
|
1690
|
+
</script>
|
|
1691
|
+
|
|
1692
|
+
{#snippet prefix()}
|
|
1693
|
+
<IconLink />
|
|
1694
|
+
{/snippet}
|
|
1695
|
+
|
|
1696
|
+
{#snippet field(context: SchemaLeafContext)}
|
|
1697
|
+
{#if context.node.format === 'uri'}
|
|
1698
|
+
<FormInput field={context.node.field} label={{ text: context.node.title, required: context.node.required }} placeholder="https://" {prefix} />
|
|
1699
|
+
{:else}
|
|
1700
|
+
{@render semiRenderers.field(context)}
|
|
1701
|
+
{/if}
|
|
1702
|
+
{/snippet}
|
|
1703
|
+
|
|
1704
|
+
{#snippet score(context: SchemaFieldContext)}
|
|
1705
|
+
<FormRating field={context.node.field} label={{ text: context.node.title, required: context.node.required }} />
|
|
1706
|
+
{/snippet}
|
|
1707
|
+
|
|
1708
|
+
<Form onSubmit={(values) => Toast.success(JSON.stringify(values))} {schema} style="width: 480px">
|
|
1709
|
+
<FormInput field="title" label={{ text: '标题', required: true }} />
|
|
1710
|
+
<SchemaField field="profile" renderField={{ 'profile.score': score }} renderers={{ ...semiRenderers, field }} />
|
|
1711
|
+
<Button htmlType="submit" type="primary">提交</Button>
|
|
1712
|
+
</Form>
|
|
1713
|
+
```
|
|
1714
|
+
|
|
1715
|
+
#### Build your own UI
|
|
1716
|
+
|
|
1717
|
+
A render function (a snippet in Svelte) receives the node's information and behavior, and the caller builds the whole UI from Semi components:
|
|
1718
|
+
|
|
1719
|
+
- Every kind receives `kind`, `node` and `render(field)`. `node` holds `field`, `title`, `description`, `required`, `depth` and, on an array row, `item: { index, arrayTitle, arrayKey }` (the row index and the owning array's title and property name). `depth` counts levels from the schema root, 0 for the root, also when SchemaField starts at a sub-path. `render(field)` renders the node at that path with the same render functions.
|
|
1720
|
+
- `object` also receives `content`, the properties rendered in schema order.
|
|
1721
|
+
- `array` also receives `items`, each `{ key, field, index, node, value, remove }`; `key` survives moves, so use it as the row key.
|
|
1722
|
+
- Array behavior: `add` inserts a row the schema prefills, and a click event is not taken as a position; `addWithInitValue` and `move` are also given.
|
|
1723
|
+
- Array state: `count`, `minItems`, `maxItems`, `fixed`, `canAdd`, `canRemove`, and `error`, the error of the array itself (such as a broken `minItems`).
|
|
1724
|
+
- Spread the array's `fieldProps` on the element holding the rows so that `formApi.scrollToField` can reach the array.
|
|
1725
|
+
|
|
1726
|
+
The `title` and `description` an item declares in the schema are passed through as they are, neither merged nor dropped. `formApi.scrollToField` and `formApi.focusField` accept any path, array and object nodes included: when nothing is rendered at the path (or it sits inside `inert` or `hidden` collapsed content), the Form calls `onRevealField(field)` so that the caller expands the collapsed card holding it, and scrolls once it mounts. `focusField` then focuses the first focusable control inside, skipping the tooltip button beside the label.
|
|
1727
|
+
|
|
1728
|
+
The example below renders contacts as collapsible cards titled by each row's name; the button locates the email inside a collapsed card.
|
|
1729
|
+
|
|
1730
|
+
```svelte
|
|
1731
|
+
<script lang="ts">
|
|
1732
|
+
import * as z from 'zod';
|
|
1733
|
+
import { Button, Collapse, Form, SchemaField, semiRenderers, Typography, type FormApi, type SchemaArrayContext, type SchemaFieldContext } from '@fibrae/semi-ui-svelte';
|
|
1734
|
+
|
|
1735
|
+
const schema = z.object({
|
|
1736
|
+
contacts: z
|
|
1737
|
+
.array(
|
|
1738
|
+
z.object({
|
|
1739
|
+
name: z.string().min(1, '请填写姓名').meta({ title: '姓名' }),
|
|
1740
|
+
email: z.email('邮箱格式不正确').meta({ title: '邮箱' }),
|
|
1741
|
+
})
|
|
1742
|
+
)
|
|
1743
|
+
.min(1, '至少一位联系人')
|
|
1744
|
+
.meta({ title: '联系人', description: '每位联系人折叠成一张卡片,卡片标题取姓名' }),
|
|
1745
|
+
});
|
|
1746
|
+
|
|
1747
|
+
const rowOf = (field: string) => /^contacts\[\d+\]/.exec(field)?.[0];
|
|
1748
|
+
|
|
1749
|
+
let open = $state(['contacts[0]']);
|
|
1750
|
+
let formApi: FormApi | undefined;
|
|
1751
|
+
</script>
|
|
1752
|
+
|
|
1753
|
+
{#snippet contacts(context: SchemaArrayContext)}
|
|
1754
|
+
<div {...context.fieldProps} style="display: grid; gap: 8px">
|
|
1755
|
+
<Typography.Text strong>{context.node.title}({context.count})</Typography.Text>
|
|
1756
|
+
<Typography.Text type="tertiary">{context.node.description}</Typography.Text>
|
|
1757
|
+
<Collapse activeKey={open} onChange={(keys) => (open = keys)}>
|
|
1758
|
+
{#each context.items as item (item.key)}
|
|
1759
|
+
<Collapse.Panel itemKey={item.field}>
|
|
1760
|
+
{#snippet header()}{(item.value as { name?: string } | undefined)?.name || `联系人 ${item.index + 1}`}{/snippet}
|
|
1761
|
+
<div {...{ 'x-field-id': item.field }}>
|
|
1762
|
+
{@render context.render(item.field)}
|
|
1763
|
+
</div>
|
|
1764
|
+
</Collapse.Panel>
|
|
1765
|
+
{/each}
|
|
1766
|
+
</Collapse>
|
|
1767
|
+
{#if context.error}
|
|
1768
|
+
<Typography.Text type="danger">{context.error.join(' ')}</Typography.Text>
|
|
1769
|
+
{/if}
|
|
1770
|
+
<Button disabled={!context.canAdd} style="justify-self: start" onclick={context.add}>添加联系人</Button>
|
|
1771
|
+
</div>
|
|
1772
|
+
{/snippet}
|
|
1773
|
+
|
|
1774
|
+
{#snippet contactRow(context: SchemaFieldContext)}
|
|
1775
|
+
{#if context.kind === 'object'}
|
|
1776
|
+
{@render context.content()}
|
|
1777
|
+
{/if}
|
|
1778
|
+
{/snippet}
|
|
1779
|
+
|
|
1780
|
+
<Form
|
|
1781
|
+
getFormApi={(api) => (formApi = api)}
|
|
1782
|
+
initValues={{ contacts: [{ name: 'Ann', email: 'ann@example.com' }, { name: 'Bob' }] }}
|
|
1783
|
+
onRevealField={(field) => {
|
|
1784
|
+
const row = rowOf(field);
|
|
1785
|
+
if (row) open = [...open, row];
|
|
1786
|
+
}}
|
|
1787
|
+
{schema}
|
|
1788
|
+
style="width: 480px"
|
|
1789
|
+
>
|
|
1790
|
+
<SchemaField renderField={{ 'contacts[]': contactRow }} renderers={{ ...semiRenderers, array: contacts }} />
|
|
1791
|
+
<Button style="margin-block-start: 12px" onclick={() => formApi?.focusField('contacts[1].email')}>定位到 Bob 的邮箱</Button>
|
|
1792
|
+
</Form>
|
|
1793
|
+
```
|
|
1794
|
+
|
|
1795
|
+
### Use of Hook
|
|
1796
|
+
|
|
1797
|
+
We provide four hooks so that you can easily access Form internal state and call Form and Field related api in a component placed inside the Form structure without passing through props. They depend on the context provided by Form, so call them while a component inside the Form initializes (the top level of `<script>`); calling them outside a Form throws an error
|
|
1798
|
+
|
|
1799
|
+
```ts
|
|
1800
|
+
import { useFormApi, useFormState, useFieldApi, useFieldState } from '@fibrae/semi-ui-svelte';
|
|
1801
|
+
```
|
|
1802
|
+
|
|
1803
|
+
#### useFormApi
|
|
1804
|
+
|
|
1805
|
+
`useFormApi` allows you to directly access the formApi of the parent Form component within a component inside the Form
|
|
1806
|
+
|
|
1807
|
+
```svelte
|
|
1808
|
+
<script lang="ts">
|
|
1809
|
+
import { Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
1810
|
+
import ChangeNameByFormApi from './parts/change-name-by-form-api.svelte';
|
|
1811
|
+
</script>
|
|
1812
|
+
|
|
1813
|
+
<Form>
|
|
1814
|
+
<FormInput field="name" initValue="mike" />
|
|
1815
|
+
<ChangeNameByFormApi />
|
|
1816
|
+
</Form>
|
|
1817
|
+
```
|
|
1818
|
+
|
|
1819
|
+
#### useFormState
|
|
1820
|
+
|
|
1821
|
+
`useFormState` allows you to directly access the form State of the parent Form component within a component inside the Form. It returns an accessor (`() => FormState`), read through `formState()`, which follows the form when read in the template
|
|
1822
|
+
|
|
1823
|
+
```svelte
|
|
1824
|
+
<script lang="ts">
|
|
1825
|
+
import { Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
1826
|
+
import ShowFormState from './parts/show-form-state.svelte';
|
|
1827
|
+
</script>
|
|
1828
|
+
|
|
1829
|
+
<Form>
|
|
1830
|
+
<FormInput field="name" initValue="mike" />
|
|
1831
|
+
<h5>FormState read by 【useFormState】:</h5>
|
|
1832
|
+
<ShowFormState />
|
|
1833
|
+
</Form>
|
|
1834
|
+
```
|
|
1835
|
+
|
|
1836
|
+
#### useFieldApi
|
|
1837
|
+
|
|
1838
|
+
`useFieldApi` allows you to call the api of the specified Field directly within a component inside the Form. The parameter can be a field name or a function that returns one, which follows the field name when it changes
|
|
1839
|
+
|
|
1840
|
+
```svelte
|
|
1841
|
+
<script lang="ts">
|
|
1842
|
+
import { Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
1843
|
+
import ChangeNameByFieldApi from './parts/change-name-by-field-api.svelte';
|
|
1844
|
+
</script>
|
|
1845
|
+
|
|
1846
|
+
<Form>
|
|
1847
|
+
<FormInput field="name" initValue="mike" />
|
|
1848
|
+
<ChangeNameByFieldApi />
|
|
1849
|
+
</Form>
|
|
1850
|
+
```
|
|
1851
|
+
|
|
1852
|
+
#### useFieldState
|
|
1853
|
+
|
|
1854
|
+
`useFieldState` allows you to directly access the State of the specified Field within a component inside the Form. The parameter can be a field name or a function that returns one, and it returns an accessor: `fieldState()` gives `{ value, error, touched }`
|
|
1855
|
+
|
|
1856
|
+
```svelte
|
|
1857
|
+
<script lang="ts">
|
|
1858
|
+
import { Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
1859
|
+
import ShowFieldState from './parts/show-field-state.svelte';
|
|
1860
|
+
</script>
|
|
1861
|
+
|
|
1862
|
+
<Form layout="horizontal">
|
|
1863
|
+
<div style="width: 400px">
|
|
1864
|
+
<FormInput field="name" initValue="mike" />
|
|
1865
|
+
<FormInput field="country" initValue="china" />
|
|
1866
|
+
</div>
|
|
1867
|
+
<div style="width: 500px; margin-block-start: 30px">
|
|
1868
|
+
<ShowFieldState field="name" />
|
|
1869
|
+
<ShowFieldState field="country" />
|
|
1870
|
+
</div>
|
|
1871
|
+
</Form>
|
|
1872
|
+
```
|
|
1873
|
+
|
|
1874
|
+
### Access formApi and formState through the children snippet
|
|
1875
|
+
|
|
1876
|
+
Svelte has no `withFormApi` or `withFormState`. The `children` snippet of Form already provides `formApi` and `formState`; use `useFormApi` and `useFormState` above inside a child component
|
|
1877
|
+
|
|
1878
|
+
#### Access formApi
|
|
1879
|
+
|
|
1880
|
+
```svelte
|
|
1881
|
+
<script lang="ts">
|
|
1882
|
+
import { Button, Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
1883
|
+
</script>
|
|
1884
|
+
|
|
1885
|
+
<Form>
|
|
1886
|
+
{#snippet children(form)}
|
|
1887
|
+
<FormInput field="name" initValue="semi" />
|
|
1888
|
+
<FormInput field="familyName" initValue="design" />
|
|
1889
|
+
<Button htmlType="submit" style="margin-inline-end: 4px">submit</Button>
|
|
1890
|
+
<Button onclick={() => form.formApi.setValue('name', Math.random())}>Click Me!!! ChangeName By【formApi】</Button>
|
|
1891
|
+
{/snippet}
|
|
1892
|
+
</Form>
|
|
1893
|
+
```
|
|
1894
|
+
|
|
1895
|
+
#### Access formState
|
|
1896
|
+
|
|
1897
|
+
```svelte
|
|
1898
|
+
<script lang="ts">
|
|
1899
|
+
import { Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
1900
|
+
</script>
|
|
1901
|
+
|
|
1902
|
+
<Form>
|
|
1903
|
+
{#snippet children(form)}
|
|
1904
|
+
<FormInput field="name" initValue="semi" />
|
|
1905
|
+
<FormInput field="familyName" initValue="design" />
|
|
1906
|
+
<code>{JSON.stringify(form.formState)}</code>
|
|
1907
|
+
{/snippet}
|
|
1908
|
+
</Form>
|
|
1909
|
+
```
|
|
1910
|
+
|
|
1911
|
+
### Take over custom components
|
|
1912
|
+
|
|
1913
|
+
Svelte has no HOC. Use `FormField` to extend other custom components into Field, and Form will take over their behavior. It is the counterpart of `withField` in the other frameworks.
|
|
1914
|
+
|
|
1915
|
+
> **Notice**
|
|
1916
|
+
>
|
|
1917
|
+
> Custom components must be controlled components.
|
|
1918
|
+
|
|
1919
|
+
FormField did the following things.
|
|
1920
|
+
|
|
1921
|
+
- Take over the `value` of the component (or other properties specified by `fieldOptions.valueKey`), the `onChange` callback (or other callbacks specified by `onKeyChangeFnName`)
|
|
1922
|
+
- Insert Field's `FormLabel` above the field
|
|
1923
|
+
- Insert Field's ErrorMessage under the field
|
|
1924
|
+
- Insert Field's extraText under the field
|
|
1925
|
+
|
|
1926
|
+
For the specific configuration of `fieldOptions`, see [fieldOptions](#fieldoptions)
|
|
1927
|
+
|
|
1928
|
+
Your custom controlled component needs to do the following:
|
|
1929
|
+
|
|
1930
|
+
- Declare a bindable `value` (`$bindable()`, or `checked` or `fileList` specified by `valueKey`), follow its changes and update your component UI rendering results
|
|
1931
|
+
- When the value changes, call `onChange` (or the callback specified by `onKeyChangeFnName`) with the latest value as the argument
|
|
1932
|
+
|
|
1933
|
+
```svelte
|
|
1934
|
+
<FormField component={YourComponent} field="name" {fieldOptions} />
|
|
1935
|
+
```
|
|
1936
|
+
|
|
1937
|
+
The props type of FormField is inferred from the props of `component`: the component's own props plus [Field Props](#field-props), without `value`, `checked`, `fileList`, `defaultValue` and `defaultChecked` (the Form owns the value).
|
|
1938
|
+
|
|
1939
|
+
```svelte
|
|
1940
|
+
<script lang="ts">
|
|
1941
|
+
import { Form, FormField, type WithFieldOption } from '@fibrae/semi-ui-svelte';
|
|
1942
|
+
import HtmlInput from './parts/html-input.svelte';
|
|
1943
|
+
import ShowFormState from './parts/show-form-state.svelte';
|
|
1944
|
+
|
|
1945
|
+
const fieldOptions: WithFieldOption = {
|
|
1946
|
+
valueKey: 'value',
|
|
1947
|
+
onKeyChangeFnName: 'oninput',
|
|
1948
|
+
onBlurFnName: 'onblur',
|
|
1949
|
+
valuePath: 'target.value',
|
|
1950
|
+
validateStatus: false,
|
|
1951
|
+
};
|
|
1952
|
+
</script>
|
|
1953
|
+
|
|
1954
|
+
<Form>
|
|
1955
|
+
<FormField component={HtmlInput} field="name" {fieldOptions} />
|
|
1956
|
+
<ShowFormState />
|
|
1957
|
+
</Form>
|
|
1958
|
+
```
|
|
1959
|
+
|
|
1960
|
+
```svelte
|
|
1961
|
+
<script lang="ts">
|
|
1962
|
+
import { Form, FormField } from '@fibrae/semi-ui-svelte';
|
|
1963
|
+
import BaseInfo from './parts/base-info.svelte';
|
|
1964
|
+
import ShowFormState from './parts/show-form-state.svelte';
|
|
1965
|
+
</script>
|
|
1966
|
+
|
|
1967
|
+
<Form>
|
|
1968
|
+
<FormField component={BaseInfo} field="baseInfo" label={{ text: '基本信息', required: true }} />
|
|
1969
|
+
<ShowFormState />
|
|
1970
|
+
</Form>
|
|
1971
|
+
```
|
|
1972
|
+
|
|
1973
|
+
## API reference
|
|
1974
|
+
|
|
1975
|
+
## Form
|
|
1976
|
+
|
|
1977
|
+
```svelte
|
|
1978
|
+
<script lang="ts">
|
|
1979
|
+
import { Form } from '@fibrae/semi-ui-svelte';
|
|
1980
|
+
</script>
|
|
1981
|
+
```
|
|
1982
|
+
|
|
1983
|
+
**Props**
|
|
1984
|
+
|
|
1985
|
+
| Property | Description | Type | Default |
|
|
1986
|
+
| - | - | - | - |
|
|
1987
|
+
| allowEmpty | Whether a field whose value became empty keeps its key in values. The same prop on a field takes precedence. | `boolean` | `false` |
|
|
1988
|
+
| autoScrollToError | Whether to scroll to the failing field when submit or formApi.validate fails; an object is passed on as options of scroll-into-view-if-needed. | `boolean \| ScrollOptions` | `false` |
|
|
1989
|
+
| children | Content of the form, with `{ formState, formApi, values }`, for reading only; change the form through formApi. | `Snippet<[FormRenderProps<Values, Output>]>` | - |
|
|
1990
|
+
| disabled | The disabled applied to every field; the disabled of a field takes precedence. | `boolean` | - |
|
|
1991
|
+
| extraTextPosition | Position of extraText applied to every field: middle puts it between the Label and the control, bottom after the control. The same prop on a field takes precedence. | `'bottom' \| 'middle'` | - |
|
|
1992
|
+
| form | The formApi returned by useForm, to control the form from outside the Form. | `FormApi<Values, Output>` | - |
|
|
1993
|
+
| getFormApi | Called once the Form has mounted, with the formApi, to keep a reference to it. | `(formApi: FormApi<Values, Output>) => void` | - |
|
|
1994
|
+
| id | The id of the form element, also written to x-form-id; generated when omitted. | `string` | - |
|
|
1995
|
+
| initValues | Initial values of the form, copied once when the Form is created. | `DeepPartial<Values>` | - |
|
|
1996
|
+
| keepState | Whether an unmounted field keeps its value, error and touched state, restored by path when it mounts again. Fields and ArrayFields without their own setting use this value. | `boolean` | `true` |
|
|
1997
|
+
| labelAlign | Label text alignment applied to every field. The same prop on a field takes precedence. | `'left' \| 'right'` | - |
|
|
1998
|
+
| labelCol | Label grid layout applied to every field, with the span, offset and other props of Col; set it together with wrapperCol. | `ColProps` | - |
|
|
1999
|
+
| labelPosition | Label position applied to every field; inset is only supported by some fields, the others lay out as top. The same prop on a field takes precedence. | `'inset' \| 'left' \| 'top'` | `"top"` |
|
|
2000
|
+
| labelWidth | Label width applied to every field; a number is in px. | `number \| string` | - |
|
|
2001
|
+
| layout | Direction the fields are laid out in, vertical or horizontal. | `'horizontal' \| 'vertical'` | `"vertical"` |
|
|
2002
|
+
| onChange | Called when the form state updates, including field mount, unmount, value change, blur, and changes of validation status and errors, with the formState. | `(formState: FormState<Values>) => void` | - |
|
|
2003
|
+
| onErrorChange | Called when the validation state updates, with all errors and the changed field errors. A batch such as validate, submit or reset calls it once, and silent validation does not call it. | `(errors: AllErrors<Values>, changedError?: Partial<Record<FieldPath<Values>, FieldError>>) => void` | - |
|
|
2004
|
+
| onReset | Called when the reset button or formApi.reset resets the form. | `() => void` | - |
|
|
2005
|
+
| onRevealField | Called when formApi.scrollToField or formApi.focusField finds nothing rendered at a path (an element inside inert or hidden collapsed content counts as not rendered), with the path. Expand the collapsed card that holds it here; the Form waits up to a second and scrolls and focuses once it mounts. | `(field: FieldPath<Values>) => void` | - |
|
|
2006
|
+
| onSubmit | Called after the submit button or formApi.submitForm and a passing validation, with the values and the submit event. With `schema`, the values are the schema's output. | `(values: Output, e?: SubmitEvent) => void` | - |
|
|
2007
|
+
| onSubmitFail | Called after the submit button or formApi.submitForm and a failing validation, with the errors, the values and the submit event. Each error in errors is a string array; an exception thrown by a validator is passed as is. | `(errors: Partial<AllErrors<Values>> \| unknown, values: Partial<Values>, e?: SubmitEvent) => void` | - |
|
|
2008
|
+
| onValueChange | Called when a field value changes, with all values and the changed field values. | `(values: Values, changedValues: Partial<Values>) => void` | - |
|
|
2009
|
+
| schema | A Standard Schema object (Zod, Valibot, ArkType and so on), mutually exclusive with the validator and rules of the fields, which no longer run. Once all fields pass, `onSubmit` and formApi.validate receive the schema's output. When `validator` is also set, only `validator` applies. | `StandardSchema<Values, Output>` | - |
|
|
2010
|
+
| schemaDebounce | With `schema`, how many milliseconds of pause in input a change-triggered validation waits for. Validation on submit, formApi.validate and blur does not wait. | `number` | `0` |
|
|
2011
|
+
| showValidateIcon | Whether the icon of the status shows before the validation message. | `boolean` | `true` |
|
|
2012
|
+
| stopPropagation | Whether the submit and reset events stop bubbling, to keep a nested Form from triggering the outer Form. | `{ submit?: boolean; reset?: boolean }` | - |
|
|
2013
|
+
| stopValidateWithError | Whether validation with rules stops at the first failing rule. The same prop on a field takes precedence. | `boolean` | - |
|
|
2014
|
+
| trigger | When fields validate: change, blur, mount, custom or an array of them. The same prop on a field takes precedence. | `FieldValidateTriggerType` | - |
|
|
2015
|
+
| validator | Form-level validation, called by submit and formApi.validate; it may return a Promise and excludes `schema`. Once set, the validator and rules of the fields no longer apply. An empty value or object means valid; on failure return an error object shaped like the values, each error a string or a string array. | `FormValidator<Values>` | - |
|
|
2016
|
+
| wrapperCol | Control grid layout applied to every field, with the span, offset and other props of Col; set it together with labelCol. | `ColProps` | - |
|
|
2017
|
+
|
|
2018
|
+
**Methods**
|
|
2019
|
+
|
|
2020
|
+
| Method | Description | Type |
|
|
2021
|
+
| - | - | - |
|
|
2022
|
+
| getFormApi | Returns the formApi; call it on the instance from `bind:this`. | `() => FormApi<Values, Output>` |
|
|
2023
|
+
|
|
2024
|
+
`class`, `style` and native attributes and events (such as `aria-*` and `onkeydown`) land on the `form` element. When `labelCol` and `wrapperCol` are set, the `form` is wrapped in a Row, and the other attributes still land on the `form`. The `form` element has `novalidate` by default, so only Semi validates; pass `novalidate={false}` to restore native validation.
|
|
2025
|
+
|
|
2026
|
+
After getting the Form instance through `bind:this`, call its `getFormApi()` to get the formApi.
|
|
2027
|
+
|
|
2028
|
+
## FormState
|
|
2029
|
+
|
|
2030
|
+
FormState stores all the state values within the Form, including the values of each field, error information, touched status
|
|
2031
|
+
|
|
2032
|
+
| Name | Instructions | Initial value | Example |
|
|
2033
|
+
| - | - | - | - |
|
|
2034
|
+
| values | Value Collection of the form | {} | {fieldA: 'str', fieldB: true} |
|
|
2035
|
+
| errors | Form error information collection, with the same shape as values; the error of each field is an array of strings | {} | {fieldA: \['length not valid']} |
|
|
2036
|
+
| touched | The collection of fields the user has clicked on | {} | {fieldA: true} |
|
|
2037
|
+
|
|
2038
|
+
### How to access the form state
|
|
2039
|
+
|
|
2040
|
+
- By calling `formApi.getFormState()`
|
|
2041
|
+
- Via the [children snippet](#Other%20declaration%20methods), formState will injected as a parameter
|
|
2042
|
+
- Via [useFormState](#useFormState) in a component inside the Form
|
|
2043
|
+
- Via the formState created by [useForm](#useForm), read the reactive `formState` property outside the Form
|
|
2044
|
+
|
|
2045
|
+
## FormApi
|
|
2046
|
+
|
|
2047
|
+
We provide FormApi. You have easy access to FormApi both inside and outside the Form, which allows you to use getter and setter to get and manipulate the values of FormState.\
|
|
2048
|
+
The table below describes the features available in the formApi.
|
|
2049
|
+
|
|
2050
|
+
> **About scope isolation**
|
|
2051
|
+
>
|
|
2052
|
+
> In order to prevent the user from accidentally modifying the internal state of the Form component after reading the internal state of formState, values.
|
|
2053
|
+
>
|
|
2054
|
+
> Semi will automatically execute deepClone once for input parameters of `formApi.setValue` and `setValues` and the return results of `formApi.getFormState`, `getValue` and `getValues`.
|
|
2055
|
+
|
|
2056
|
+
| Function | Description | example |
|
|
2057
|
+
| - | - | - |
|
|
2058
|
+
| getFormProps | Get Form Component Props | formApi.getFormProps(propNames?: string\[]) |
|
|
2059
|
+
| getFormState | Get FormState | formApi.getFormState() |
|
|
2060
|
+
| submitForm | Manually submit form operation | formApi.submitForm() |
|
|
2061
|
+
| reset | Reset the form manually | formApi.reset(fields?: Array \<string>) |
|
|
2062
|
+
| validate | Manually trigger validation of the entire form. the verification of the entire Field will be triggered by default when no parameters are passed , if you want to trigger the verification of some fields, pass in the target field array After the Form level validator is configured, the Field level validator will not be triggered again when submit or formApi.validate()**Silent validation**: Pass `{ silent: true }` to get validation results without triggering UI updates (no error messages shown, no touched state set). You can also use `{ fields: ['fieldA'], silent: true }` to perform silent validation on specific fields.With a `schema`, validating all fields resolves with the schema's output, and validating some fields resolves with the raw values. | formApi.validate() .then(values => {}).catch(errors => {})OR formApi.validate(\['fieldA','fieldB'])OR formApi.validate({ silent: true })OR formApi.validate({ fields: \['fieldA'], silent: true }) |
|
|
2063
|
+
| setValues | Set the values of the entire form. The isOverride in the second parameter is false by default. **When isOverride is false**: Iterate through all registered fields in the Form, and update the values from `newValues` to `formState.values`. If a registered field is not included in `newValues`, that field will be set to undefined. **When isOverride is true**: Directly replace `formState.values` with `newValues`, including extra keys in `newValues` that don't have corresponding fields in the form. **Recommended usage**: If you only need to update some fields, it's recommended to use `formApi.setValue(field, value)` for individual updates, or get current values first then merge: `formApi.setValues({ ...formApi.getValues(), name: newValue })` | formApi.setValues(newValues: object, {isOverride: boolean}) |
|
|
2064
|
+
| getValues | Get the values of all Field | formApi.getValues() |
|
|
2065
|
+
| setValue | provides direct modification of formState.values method.The difference from `setValues` is that it only modifies a single field. | formApi.setValue(field: string, newFieldValue: any) |
|
|
2066
|
+
| getValue | Get the value of all / single Field | formApi.getValue()formApi.getValue(field: string) |
|
|
2067
|
+
| setTouched | Modify formState.touched | formApi.setTouched(field: string, isTouched: boolean) |
|
|
2068
|
+
| getTouched | Get the touched state of the Field; returns the whole touched object when field is not passed | formApi.getTouched(field?: string) |
|
|
2069
|
+
| setError | Modify the error information of a field. A string is converted to a single-item array; an empty string, an empty array or undefined clears the error; passing an object or array to a parent path writes the errors of its child fields by structure | formApi.setError(field: string, error: string \| string\[]) |
|
|
2070
|
+
| getError | Get the error information of a Field (an array of strings); a parent path returns an object of the errors of its child fields, and undefined when there is no error | formApi.getError(field: string) |
|
|
2071
|
+
| getFieldExist | Get whether the field exists in the Form | formApi.getFieldExist(field: string) |
|
|
2072
|
+
| scrollToField | Scroll to the field, array or object node at a path; the second parameter is passed to scroll-into-view-if-needed. When the path is not rendered, the Form's `onRevealField` is called first and the Form waits up to a second. Returns a Promise that resolves after scrolling | formApi.scrollToField(field: string, scrollOpts: [ScrollIntoViewOptions](https://github.com/stipsan/scroll-into-view-if-needed#options)) |
|
|
2073
|
+
| focusField | Same as scrollToField, then focuses the first focusable control inside, skipping the tooltip button beside the label | formApi.focusField(field: string, scrollOpts: [ScrollIntoViewOptions](https://github.com/stipsan/scroll-into-view-if-needed#options)) |
|
|
2074
|
+
| scrollToError | Scroll to the field with validation error. You can pass a specified field or index. If you pass index, scroll to the index-th error DOM. If you do not pass any parameters, scroll to the first validation error position in the DOM tree. | formApi.scrollToError(`{field?: string; index?: number; scrollOpts?: ScrollIntoViewOptions }`) |
|
|
2075
|
+
|
|
2076
|
+
### How to access formApi
|
|
2077
|
+
|
|
2078
|
+
- Use `useForm()` to create formApi outside Form, then pass it via the `form` property to the Form component. This allows you to get formApi before Form renders, suitable for scenarios where you need to control the form from outside the component.
|
|
2079
|
+
- After the Form component mounts, it calls the `getFormApi` callback passed in props. You can save a reference to formApi in the callback function for subsequent calls (example code below) In addition, we provide other ways to get formApi, and you can choose different ways of calling
|
|
2080
|
+
- Use `bind:this` to get the Form instance and call its `getFormApi()`
|
|
2081
|
+
- Via the [children snippet](#Other%20declaration%20methods), formApi will injected as a parameter
|
|
2082
|
+
- Via [useFormApi](#useFormApi) for children component of Form
|
|
2083
|
+
|
|
2084
|
+
#### useForm
|
|
2085
|
+
|
|
2086
|
+
`useForm()` is used to **create** a formApi **outside** the Form component, suitable for scenarios where you need to control the form before it renders. It returns an object `{ formApi, formState, values }`: `formState` and `values` are read-only properties that follow the form once bound through the `form` property of Form, when read in the template.
|
|
2087
|
+
|
|
2088
|
+
> **Difference between useForm() and useFormApi**
|
|
2089
|
+
>
|
|
2090
|
+
> - **useForm()**: Creates formApi **outside** Form, needs to be passed to Form via the `form` property. Used for parent components controlling child Form.
|
|
2091
|
+
> - **useFormApi**: Gets formApi **inside** Form, used for child components of Form to access the parent Form. See [useFormApi](#useFormApi).
|
|
2092
|
+
|
|
2093
|
+
Usage example:
|
|
2094
|
+
|
|
2095
|
+
```svelte
|
|
2096
|
+
<script lang="ts">
|
|
2097
|
+
import { Button, Form, FormInput, useForm } from '@fibrae/semi-ui-svelte';
|
|
2098
|
+
|
|
2099
|
+
const form = useForm();
|
|
2100
|
+
|
|
2101
|
+
const handleClick = () => {
|
|
2102
|
+
form.formApi.setValue('username', 'semi');
|
|
2103
|
+
console.log('当前表单值:', form.values);
|
|
2104
|
+
};
|
|
2105
|
+
</script>
|
|
2106
|
+
|
|
2107
|
+
<Button onclick={handleClick}>外部设置值</Button>
|
|
2108
|
+
<Button onclick={() => form.formApi.reset()}>重置表单</Button>
|
|
2109
|
+
|
|
2110
|
+
<Form form={form.formApi}>
|
|
2111
|
+
<FormInput field="username" label="用户名" />
|
|
2112
|
+
<FormInput field="email" label="邮箱" />
|
|
2113
|
+
</Form>
|
|
2114
|
+
|
|
2115
|
+
<div style="margin-block-start: 16px">
|
|
2116
|
+
<div>表单值:{JSON.stringify(form.values)}</div>
|
|
2117
|
+
<div>touched 状态:{JSON.stringify(form.formState.touched)}</div>
|
|
2118
|
+
</div>
|
|
2119
|
+
```
|
|
2120
|
+
|
|
2121
|
+
> **Notice**
|
|
2122
|
+
>
|
|
2123
|
+
> When using formApi created by `useForm()` before the Form component mounts, a warning will be logged in the console. It is recommended to call formApi methods after the Form has mounted.
|
|
2124
|
+
|
|
2125
|
+
```svelte
|
|
2126
|
+
<script lang="ts">
|
|
2127
|
+
import { Button, Form, FormInput } from '@fibrae/semi-ui-svelte';
|
|
2128
|
+
import type { FormApi } from '@fibrae/semi-ui-svelte';
|
|
2129
|
+
|
|
2130
|
+
let formApiA: FormApi | undefined;
|
|
2131
|
+
let formB: { getFormApi: () => FormApi } | undefined;
|
|
2132
|
+
|
|
2133
|
+
const changeValues = () => {
|
|
2134
|
+
// use formApi to update formA. After getting the formApi object, you can use it to make any changes you want to the form
|
|
2135
|
+
formApiA?.setValues({ a: 1 });
|
|
2136
|
+
// use formApi to update formB
|
|
2137
|
+
formB?.getFormApi().setValues({ b: 2 });
|
|
2138
|
+
};
|
|
2139
|
+
</script>
|
|
2140
|
+
|
|
2141
|
+
<!-- save the formApi from the getFormApi callback -->
|
|
2142
|
+
<Form getFormApi={(formApi) => (formApiA = formApi)}>
|
|
2143
|
+
<FormInput field="a" />
|
|
2144
|
+
</Form>
|
|
2145
|
+
<!-- read the formApi from the Form instance received by bind:this -->
|
|
2146
|
+
<Form bind:this={formB}>
|
|
2147
|
+
<FormInput field="b" />
|
|
2148
|
+
</Form>
|
|
2149
|
+
<Button onclick={changeValues}>Change</Button>
|
|
2150
|
+
```
|
|
2151
|
+
|
|
2152
|
+
## Field Props
|
|
2153
|
+
|
|
2154
|
+
A Field is a component whose name starts with Form, such as `FormInput` and `FormSelect`, or one made by `FormField`; the tables below list its own properties.
|
|
2155
|
+
|
|
2156
|
+
**Props**
|
|
2157
|
+
|
|
2158
|
+
| Properties | Description | Type | Default |
|
|
2159
|
+
| - | - | - | - |
|
|
2160
|
+
| convert | After the field value changes, before it is stored in formState and shown, update the value of the field | `(fieldValue) => any` | |
|
|
2161
|
+
| field | The mapping path of the field's value in formState.values. Form will use this value to distinguish the internal form control. **Required!!!** (except a FormCheckbox or FormRadio inside its group) | `string` | |
|
|
2162
|
+
| label | The label text for this field. When not passed, it defaults to the same name as field. An object can set `text`, `required`, `optional`, `align`, `width`, `disabled` and `id` (the id of the label element), and its `text` takes only a string or number. The `fieldLabel` and `labelExtra` snippets take precedence | `string \| number \| FieldLabel` | |
|
|
2163
|
+
| labelPosition | Label position of this field. When passed on both Form and Field, the Field props prevail | `'top' \| 'left' \| 'inset'` | |
|
|
2164
|
+
| labelAlign | Text-align of the label text of this field. When passed on both Form and Field, the Field props prevail | `'left' \| 'right'` | |
|
|
2165
|
+
| labelWidth | The width of the label text of this field, a number is in px. When passed on both Form and Field, the Field props prevail | `string \| number` | |
|
|
2166
|
+
| labelCol | Grid layout of the label of this field, with [Col component](../basic/grid.md#Col). It overrides the same property of Form. When it is set together with wrapperCol while the Form does not set both, the Field wraps itself in a Row | `ColProps` | |
|
|
2167
|
+
| wrapperCol | Grid layout of the control of this field, with [Col component](../basic/grid.md#Col). It overrides the same property of Form. Used the same way as labelCol | `ColProps` | |
|
|
2168
|
+
| noLabel | When you don't need to add label automatically, you can set this value to true | `boolean` | |
|
|
2169
|
+
| noErrorMessage | When you don't need to add the ErrorMessage module automatically, you can set this value to true. Note that helpText is not shown either | `boolean` | |
|
|
2170
|
+
| name | Field name. When passed in, the corresponding className will be automatically added to the field wrapper div, such as: money => '.semi-form-field-money'. It is also passed to the underlying component, for example to configure the name attribute of an input | `string` | |
|
|
2171
|
+
| id | The id of the control, generated when omitted. The `for` of the label and the ids of the label, helpText, extraText and errormessage are derived from it | `string` | |
|
|
2172
|
+
| fieldClassName | The className of the entire fieldWrapper is the same as the name parameter, except that the prefix is not automatically appended | `string` | |
|
|
2173
|
+
| fieldStyle | The inline style of the entire fieldWrapper | `string` | |
|
|
2174
|
+
| initValue | The initial value of the field (consumed only once when Field mounted, subsequent updates are invalid), it has higher priority than the values in Form's initValues | `unknown` (type depends on current component) | |
|
|
2175
|
+
| validator | The custom validation of this form control: a function or a Standard Schema object (such as `z.string().min(3)`). A function supports synchronous and asynchronous validation (by returning a promise); an empty string, an empty array or an empty value means valid, and a string or an array of strings is the error message. Use the `error` snippet to render an error differently. Mutually exclusive with rules | `(fieldValue, values) => string \| string[] \| undefined \| Promise<...>` or `StandardSchema` | |
|
|
2176
|
+
| rules | validation rules, run by Semi's built-in rule engine; see [Configure initial values and verification rules](#configure-initial-values-and-verification-rules) for the rule properties. Mutually exclusive with validator | `RuleItem[]` | |
|
|
2177
|
+
| validateStatus | The validation result status of this form control, which only affects the style, optional: `success` / `error` / `warning` / `default`. When omitted, the Field's own validation status is used | `string` | |
|
|
2178
|
+
| trigger | The timing of triggering the verification, optional: `blur` / `change` / `custom` / `mount`, or an array of them 1. When set to custom, only formApi will trigger the verification 2.mount (triggered once when mounting) | `FieldValidateTriggerType` | `'change'` |
|
|
2179
|
+
| onChange | Callback when the value changes. The parameters are those of the callback of the wrapped component, followed by the latest form values `latestValues`, so you never read a stale value from a closure; a FormCheckbox or FormRadio without `field` is a plain control and has no `latestValues` (see the onChange of each component) | `(...args, latestValues) => void` | |
|
|
2180
|
+
| transform | transform field values before validation. The transformed value is only used for validation and does not affect formState | `(fieldValue) => any` | |
|
|
2181
|
+
| allowEmpty | Whether to keep the key of this field in `values` (as `undefined`) when its value is empty. Setting it on either the Field or the Form takes effect | `boolean` | `false` |
|
|
2182
|
+
| allowEmptyString | Whether to allow values to be empty strings. When the value is '' by default, the key corresponding to this field will be removed from `values`. If you want to keep the key, you need to set allowEmptyString to true | `boolean` | `false` |
|
|
2183
|
+
| emptyValue | The value that counts as empty. When the value changes to it, the key of this field is removed from `values` (kept as `undefined` when `allowEmpty` is true) | `unknown` | `''` |
|
|
2184
|
+
| keepState | Whether to retain the field state (value, error, touched) after the field is unmounted; retained state is restored automatically on remount. When not set, it takes the keepState of the enclosing ArrayField, then of the Form | `boolean` | `true` |
|
|
2185
|
+
| stopValidateWithError | When it is true, the rules check is used. After encountering the first rule that fails the check, it will no longer trigger the check of subsequent rules | `boolean` | `false` |
|
|
2186
|
+
| pure | Whether to only take over the data stream, when true, it will not automatically insert modules such as ErrorMessage, Label, extraText, etc. The style and DOM structure are consistent with the original components | `boolean` | `false` |
|
|
2187
|
+
| extraTextPosition | controls the display position of extraText. Middle (the vertical direction is displayed in the order of Label, extraText, and Field), bottom (the vertical direction is displayed in the order of Label, Field, and extraText); when passed on both Form and Field, the Field props prevail | `'middle' \| 'bottom'` | `'bottom'` |
|
|
2188
|
+
|
|
2189
|
+
The other properties of the component (such as `size` and `placeholder` of Input) are written on the Field together with the properties above. **The Field passes them to the wrapped component itself**, not to the fieldWrapper. `disabled` takes the value of the Form and a `disabled` written on the Field wins.
|
|
2190
|
+
|
|
2191
|
+
**Snippets**
|
|
2192
|
+
|
|
2193
|
+
| Snippet | Description | Parameters |
|
|
2194
|
+
| - | - | - |
|
|
2195
|
+
| fieldLabel | Label content, takes precedence over the text in the label property | |
|
|
2196
|
+
| labelExtra | Content that follows the label text | |
|
|
2197
|
+
| helpText | Custom prompt information, which is displayed in the same block as the verification information. When both have values, the verification information is displayed first | |
|
|
2198
|
+
| extraText | Additional prompt information, you can use this when both error information and prompt copy are required, after helpText/errorMessage | |
|
|
2199
|
+
| error | Custom rendering of the error message | `{ error }` |
|
|
2200
|
+
|
|
2201
|
+
The custom trigger snippet of FormSelect, FormCascader, FormTreeSelect, FormAutoComplete, FormDatePicker and FormTimePicker is named `triggerContent` on the Field and forwarded to the control's `trigger`, with the same parameters: the Field's own `trigger` prop is the validation timing. A Field with `triggerContent` and `labelPosition` `inset` is laid out as `top`.
|
|
2202
|
+
|
|
2203
|
+
## Field Api
|
|
2204
|
+
|
|
2205
|
+
We also provide `fieldApi`, most of which is similar to `formApi`, with the difference that fieldApi limits the scope of modification, and it can only modify the bound field. Get it through [useFieldApi](#useFieldApi)
|
|
2206
|
+
|
|
2207
|
+
| Function | Instructions | example |
|
|
2208
|
+
| - | - | - |
|
|
2209
|
+
| setValue | Modify the value of the current Field | fieldApi.setValue(newValue: any) |
|
|
2210
|
+
| getValue | Gets the value of the current Field | fieldApi.getValue() |
|
|
2211
|
+
| setTouched | Modify the touched state of the current Field | fieldApi.setTouched(true) |
|
|
2212
|
+
| getTouched | Get the touched state of the current Field | fieldApi.getTouched() |
|
|
2213
|
+
| setError | Modify the error information of the current Field | fieldApi.setError(error: string \| string\[]) |
|
|
2214
|
+
| getError | Gets field's error status | fieldApi.getError() |
|
|
2215
|
+
|
|
2216
|
+
## ArrayField
|
|
2217
|
+
|
|
2218
|
+
For dynamically added and deleted array form items, we provide the ArrayField scope to simplify adding and removing rows
|
|
2219
|
+
|
|
2220
|
+
```ts
|
|
2221
|
+
import { ArrayField } from '@fibrae/semi-ui-svelte';
|
|
2222
|
+
```
|
|
2223
|
+
|
|
2224
|
+
**Props**
|
|
2225
|
+
|
|
2226
|
+
| Property | Description | Type | Default |
|
|
2227
|
+
| - | - | - | - |
|
|
2228
|
+
| children | Content of the rows, with `{ arrayFields, onAdd, onAddWithInitValue, onMove }`. `onMove(from, to)` moves a row with its values, errors and touched state, clamping indexes out of range. | `Snippet<[ArrayFieldSnippetProps]>` | - |
|
|
2229
|
+
| field | Path of the array in formState.values, required. For row fields such as a\[0].name and a\[1].name, pass a. | `string` | - |
|
|
2230
|
+
| initValue | Initial value of the array, which must be an array; it takes precedence over the initValues of the Form. | `unknown[]` | - |
|
|
2231
|
+
| keepState | Whether the whole array keeps its data when unmounted, and the default keepState of the fields in its rows. Defaults to the Form's keepState. When kept, the rows render from the kept values on remount. | `boolean` | - |
|
|
2232
|
+
|
|
2233
|
+
ArrayField has no DOM of its own, so undeclared attributes are dropped. The argument of the `children` snippet has this type:
|
|
2234
|
+
|
|
2235
|
+
```ts
|
|
2236
|
+
interface ArrayFieldSnippetProps {
|
|
2237
|
+
arrayFields: ArrayFieldItem[]; // The current array form, which can be used to render each row with {#each}
|
|
2238
|
+
onAdd: (index?: number | Event) => void; // Add a blank line; a number inserts it at that position, an event is ignored so it can be used directly as onclick={onAdd}
|
|
2239
|
+
onAddWithInitValue: (row: unknown, index?: number) => void; // Add a new row with an initial value, index is the insert position
|
|
2240
|
+
onMove: (from: number, to: number) => void; // Move row `from` to `to`; its value, error, touched and key move with it, out-of-range indexes are clamped
|
|
2241
|
+
}
|
|
2242
|
+
|
|
2243
|
+
interface ArrayFieldItem {
|
|
2244
|
+
key: string; // A key used to identify the current row, to be used as the {#each} key
|
|
2245
|
+
field: string; // This row fieldPath, which is equivalent to the field of ArrayField + [index]
|
|
2246
|
+
onRemove: () => void; // Remove operation function of this line, when called, this line will be deleted directly
|
|
2247
|
+
}
|
|
2248
|
+
```
|
|
2249
|
+
|
|
2250
|
+
## SchemaField
|
|
2251
|
+
|
|
2252
|
+
```ts
|
|
2253
|
+
import { SchemaField } from '@fibrae/semi-ui-svelte';
|
|
2254
|
+
```
|
|
2255
|
+
|
|
2256
|
+
**Props**
|
|
2257
|
+
|
|
2258
|
+
| Property | Description | Type | Default |
|
|
2259
|
+
| - | - | - | - |
|
|
2260
|
+
| field | Path of the subtree to render; the root by default. | `string` | `""` |
|
|
2261
|
+
| jsonSchema | The JSON Schema to render, which takes precedence over the one exported from the enclosing Form's `schema`. With neither, nothing renders and a development warning is logged. | `JsonSchema` | - |
|
|
2262
|
+
| renderers | Same as the renderers of SchemaForm: render snippets by node kind. Pass `semiRenderers` for the default UI; without it no field renders. | `SchemaFieldRenderers` | - |
|
|
2263
|
+
| renderField | Same as the renderField of SchemaForm: replaces the snippet of a node by its path, with array rows written as `[]`. | `Record<string, Snippet<[SchemaFieldContext]>>` | - |
|
|
2264
|
+
|
|
2265
|
+
## SchemaForm
|
|
2266
|
+
|
|
2267
|
+
```ts
|
|
2268
|
+
import { SchemaForm } from '@fibrae/semi-ui-svelte';
|
|
2269
|
+
```
|
|
2270
|
+
|
|
2271
|
+
**Props**
|
|
2272
|
+
|
|
2273
|
+
| Property | Description | Type | Default |
|
|
2274
|
+
| - | - | - | - |
|
|
2275
|
+
| allowEmpty | Whether a field whose value became empty keeps its key in values. The same prop on a field takes precedence. | `boolean` | - |
|
|
2276
|
+
| autoScrollToError | Whether to scroll to the failing field when submit or formApi.validate fails; an object is passed on as options of scroll-into-view-if-needed. | `boolean \| ScrollOptions` | - |
|
|
2277
|
+
| children | Content rendered after the fields, with the same parameter as the children of Form; a good place for the submit button. | `Snippet<[FormRenderProps<Values, Output>]>` | - |
|
|
2278
|
+
| disabled | The disabled applied to every field; the disabled of a field takes precedence. | `boolean` | - |
|
|
2279
|
+
| extraTextPosition | Position of extraText applied to every field: middle puts it between the Label and the control, bottom after the control. The same prop on a field takes precedence. | `'bottom' \| 'middle'` | - |
|
|
2280
|
+
| form | The formApi returned by useForm, to control the form from outside the Form. | `FormApi<Values, Output>` | - |
|
|
2281
|
+
| getFormApi | Called once the Form has mounted, with the formApi, to keep a reference to it. | `(formApi: FormApi<Values, Output>) => void` | - |
|
|
2282
|
+
| id | The id of the form element, also written to x-form-id; generated when omitted. | `string` | - |
|
|
2283
|
+
| initValues | Initial values of the form, copied once when the Form is created. | `DeepPartial<Values>` | - |
|
|
2284
|
+
| jsonSchema | The JSON Schema to render, which takes precedence over the one exported from the Form's `schema`. With neither, no field renders and a development warning is logged. | `JsonSchema` | - |
|
|
2285
|
+
| keepState | Whether an unmounted field keeps its value, error and touched state, restored by path when it mounts again. Fields and ArrayFields without their own setting use this value. | `boolean` | - |
|
|
2286
|
+
| labelAlign | Label text alignment applied to every field. The same prop on a field takes precedence. | `'left' \| 'right'` | - |
|
|
2287
|
+
| labelCol | Label grid layout applied to every field, with the span, offset and other props of Col; set it together with wrapperCol. | `ColProps` | - |
|
|
2288
|
+
| labelPosition | Label position applied to every field; inset is only supported by some fields, the others lay out as top. The same prop on a field takes precedence. | `'inset' \| 'left' \| 'top'` | - |
|
|
2289
|
+
| labelWidth | Label width applied to every field; a number is in px. | `number \| string` | - |
|
|
2290
|
+
| layout | Direction the fields are laid out in, vertical or horizontal. | `'horizontal' \| 'vertical'` | - |
|
|
2291
|
+
| onChange | Called when the form state updates, including field mount, unmount, value change, blur, and changes of validation status and errors, with the formState. | `(formState: FormState<Values>) => void` | - |
|
|
2292
|
+
| onErrorChange | Called when the validation state updates, with all errors and the changed field errors. A batch such as validate, submit or reset calls it once, and silent validation does not call it. | `(errors: AllErrors<Values>, changedError?: Partial<Record<FieldPath<Values>, FieldError>>) => void` | - |
|
|
2293
|
+
| onReset | Called when the reset button or formApi.reset resets the form. | `() => void` | - |
|
|
2294
|
+
| onRevealField | Called when formApi.scrollToField or formApi.focusField finds nothing rendered at a path (an element inside inert or hidden collapsed content counts as not rendered), with the path. Expand the collapsed card that holds it here; the Form waits up to a second and scrolls and focuses once it mounts. | `(field: FieldPath<Values>) => void` | - |
|
|
2295
|
+
| onSubmit | Called after the submit button or formApi.submitForm and a passing validation, with the values and the submit event. With `schema`, the values are the schema's output. | `(values: Output, e?: SubmitEvent) => void` | - |
|
|
2296
|
+
| onSubmitFail | Called after the submit button or formApi.submitForm and a failing validation, with the errors, the values and the submit event. Each error in errors is a string array; an exception thrown by a validator is passed as is. | `(errors: Partial<AllErrors<Values>> \| unknown, values: Partial<Values>, e?: SubmitEvent) => void` | - |
|
|
2297
|
+
| onValueChange | Called when a field value changes, with all values and the changed field values. | `(values: Values, changedValues: Partial<Values>) => void` | - |
|
|
2298
|
+
| renderers | Render snippets by node kind, `{ object, array, field }`; SchemaField itself renders no UI. Pass `semiRenderers` for the default UI built from Semi Form controls, and replace one kind with `{ ...semiRenderers, field: mySnippet }`. Without `object` an object renders its properties as they are; without `array` or `field` those nodes render nothing and a warning is logged in development. Each snippet receives a `context` with `node` and a `render` snippet: `{@render context.render(field)}` renders the node at `field`, and a list keys its rows with the `{#each}` key. An object also has a `content` snippet, an array also has `items`, `add`, `move`, `error`, `fieldProps` and so on. | `SchemaFieldRenderers` | - |
|
|
2299
|
+
| renderField | Replaces the `renderers` snippet of a node by its path, with array rows written as `[]` (such as `contacts[].email`). It receives what the snippet of that node's kind receives. | `Record<string, Snippet<[SchemaFieldContext]>>` | - |
|
|
2300
|
+
| schema | A Standard Schema object (Zod, Valibot, ArkType and so on), mutually exclusive with the validator and rules of the fields, which no longer run. Once all fields pass, `onSubmit` and formApi.validate receive the schema's output. When `validator` is also set, only `validator` applies. | `StandardSchema<Values, Output>` | - |
|
|
2301
|
+
| schemaDebounce | With `schema`, how many milliseconds of pause in input a change-triggered validation waits for. Validation on submit, formApi.validate and blur does not wait. | `number` | - |
|
|
2302
|
+
| showValidateIcon | Whether the icon of the status shows before the validation message. | `boolean` | - |
|
|
2303
|
+
| stopPropagation | Whether the submit and reset events stop bubbling, to keep a nested Form from triggering the outer Form. | `{ submit?: boolean; reset?: boolean }` | - |
|
|
2304
|
+
| stopValidateWithError | Whether validation with rules stops at the first failing rule. The same prop on a field takes precedence. | `boolean` | - |
|
|
2305
|
+
| trigger | When fields validate: change, blur, mount, custom or an array of them. The same prop on a field takes precedence. | `FieldValidateTriggerType` | - |
|
|
2306
|
+
| validator | Form-level validation, called by submit and formApi.validate; it may return a Promise and excludes `schema`. Once set, the validator and rules of the fields no longer apply. An empty value or object means valid; on failure return an error object shaped like the values, each error a string or a string array. | `FormValidator<Values>` | - |
|
|
2307
|
+
| wrapperCol | Control grid layout applied to every field, with the span, offset and other props of Col; set it together with labelCol. | `ColProps` | - |
|
|
2308
|
+
|
|
2309
|
+
**Methods**
|
|
2310
|
+
|
|
2311
|
+
| Method | Description | Type |
|
|
2312
|
+
| - | - | - |
|
|
2313
|
+
| getFormApi | Returns the formApi; call it on the instance from `bind:this`. | `() => FormApi<Values, Output> \| undefined` |
|
|
2314
|
+
|
|
2315
|
+
## FormSection
|
|
2316
|
+
|
|
2317
|
+
```ts
|
|
2318
|
+
import { FormSection } from '@fibrae/semi-ui-svelte';
|
|
2319
|
+
```
|
|
2320
|
+
|
|
2321
|
+
**Props**
|
|
2322
|
+
|
|
2323
|
+
| Property | Description | Type | Default |
|
|
2324
|
+
| - | - | - | - |
|
|
2325
|
+
| children | The fields in the section. | `Snippet` | - |
|
|
2326
|
+
| extraText | A description snippet below the title, also the accessible description of the group (`aria-describedby`). | `Snippet` | - |
|
|
2327
|
+
| text | Title of the section; without content the title element is not rendered. | `Snippet` | - |
|
|
2328
|
+
|
|
2329
|
+
`class`, `style` and native attributes land on the `fieldset` element.
|
|
2330
|
+
|
|
2331
|
+
## FormLabel
|
|
2332
|
+
|
|
2333
|
+
By default, `Label` is self-inserted into each `Field` by `Form`.\
|
|
2334
|
+
If you need to self-insert Label elsewhere, we have provided the `FormLabel` component for you.
|
|
2335
|
+
|
|
2336
|
+
```ts
|
|
2337
|
+
import { FormLabel } from '@fibrae/semi-ui-svelte';
|
|
2338
|
+
```
|
|
2339
|
+
|
|
2340
|
+
**Props**
|
|
2341
|
+
|
|
2342
|
+
| Property | Description | Type | Default |
|
|
2343
|
+
| - | - | - | - |
|
|
2344
|
+
| align | Alignment of the Label text. | `string` | `"left"` |
|
|
2345
|
+
| children | Label content, which takes precedence over text. | `Snippet` | - |
|
|
2346
|
+
| disabled | Whether it has the disabled style. | `boolean` | - |
|
|
2347
|
+
| extra | Content that follows the label text. | `Snippet` | - |
|
|
2348
|
+
| name | The id of the labeled control, written to the for attribute of the label. | `string` | - |
|
|
2349
|
+
| optional | Whether the optional text of the locale follows the text. The required \* is then hidden. | `boolean` | `false` |
|
|
2350
|
+
| required | Whether to show the required \* mark. | `boolean` | `false` |
|
|
2351
|
+
| text | Label text; the `children` snippet takes precedence. | `string \| number` | - |
|
|
2352
|
+
| tooltip | Tooltip content of the help button beside the label, a snippet, string or number. The button sits outside the label element, so it is not part of the field's accessible name, and its name comes from the locale. | `Snippet \| string \| number` | - |
|
|
2353
|
+
| width | Label width; a number is in px. | `number \| string` | - |
|
|
2354
|
+
|
|
2355
|
+
`class`, `style` and native attributes land on the `label` element.
|
|
2356
|
+
|
|
2357
|
+
## FormInputGroup
|
|
2358
|
+
|
|
2359
|
+
```ts
|
|
2360
|
+
import { FormInputGroup } from '@fibrae/semi-ui-svelte';
|
|
2361
|
+
```
|
|
2362
|
+
|
|
2363
|
+
**Props**
|
|
2364
|
+
|
|
2365
|
+
| Property | Description | Type | Default |
|
|
2366
|
+
| - | - | - | - |
|
|
2367
|
+
| aria-describedby | The aria-describedby of the Group, merged with the id of extraText on the group element. | `string \| null` | - |
|
|
2368
|
+
| aria-errormessage | Has no effect; the Group generates the id of the error message itself. | `string \| null` | - |
|
|
2369
|
+
| aria-labelledby | The aria-labelledby of the Group, merged with the id of the Label on the group element. | `string \| null` | - |
|
|
2370
|
+
| children | The fields in the group; only direct children with a field are rendered. | `Snippet` | - |
|
|
2371
|
+
| disabled | The disabled of the fields in the group; the disabled of the Form applies when omitted. | `boolean` | - |
|
|
2372
|
+
| extraText | Extra hint, always shown, referred to by the aria-describedby of every control in the group. | `Snippet` | - |
|
|
2373
|
+
| extraTextPosition | Position of extraText: middle puts it between the Label and the Group, bottom after the Group. | `'bottom' \| 'middle'` | `"bottom"` |
|
|
2374
|
+
| fieldLabel | Label content of the Group, which takes precedence over the text in the label prop. | `Snippet` | - |
|
|
2375
|
+
| label | The Label of the whole Group: a string is the text, an object is a Label configuration whose id is the id of the Label; the `fieldLabel` snippet takes precedence. | `string \| number \| (FieldLabel & { id?: string })` | - |
|
|
2376
|
+
| labelExtra | Content that follows the Group Label text. | `Snippet` | - |
|
|
2377
|
+
| labelPosition | Position of the Label, taken from the Form by default: top or left. | `'left' \| 'top'` | - |
|
|
2378
|
+
| onBlur | Called when focus leaves the whole Group. | `(event: FocusEvent) => void` | - |
|
|
2379
|
+
| onFocus | Called when focus enters the whole Group. | `(event: FocusEvent) => void` | - |
|
|
2380
|
+
| size | Size of the controls in the group. | `InputSize` | - |
|
|
2381
|
+
|
|
2382
|
+
`class`, `style` and native attributes land on the InputGroup inside. `aria-labelledby` and `aria-describedby` are merged with the ids generated by the group, the caller's first. The root has `role="group"` when a label is set, and has none without a label.
|
|
2383
|
+
|
|
2384
|
+
When extraTextPosition is middle and labelPosition is left. Since the content of `extraText` has a variable height, the Label will no longer ensure that it can be aligned with the first line of text in the Field / FormInputGroup.
|
|
2385
|
+
|
|
2386
|
+
## FormSlot
|
|
2387
|
+
|
|
2388
|
+
```ts
|
|
2389
|
+
import { FormSlot } from '@fibrae/semi-ui-svelte';
|
|
2390
|
+
```
|
|
2391
|
+
|
|
2392
|
+
**Props**
|
|
2393
|
+
|
|
2394
|
+
| Property | Description | Type | Default |
|
|
2395
|
+
| - | - | - | - |
|
|
2396
|
+
| children | The custom content to place. | `Snippet` | - |
|
|
2397
|
+
| error | The error, a string array, rendered after the content; omitted when not given. | `FieldError` | - |
|
|
2398
|
+
| errorContent | Custom rendering of the error, with `{ error }`. | `Snippet<[{ error: FieldError }]>` | - |
|
|
2399
|
+
| fieldLabel | Label content, which takes precedence over the text in the label prop. | `Snippet` | - |
|
|
2400
|
+
| label | The Label text, or a Label configuration such as text, align, width, required, optional and id; the `fieldLabel` snippet takes precedence. | `string \| number \| FieldLabel` | - |
|
|
2401
|
+
| labelExtra | Content that follows the Label text. | `Snippet` | - |
|
|
2402
|
+
| labelPosition | Position of the Label, taken from the Form by default: top or left. | `'left' \| 'top'` | - |
|
|
2403
|
+
| noLabel | Whether to leave out the Label; with both labelCol and wrapperCol set on the Form, the Label column stays. | `boolean` | - |
|
|
2404
|
+
|
|
2405
|
+
`class`, `style` and native attributes land on the root element. The root element has `role="group"` when `aria-label` or `aria-labelledby` is passed, and a `role` passed by the caller wins. The label width and alignment come from `labelWidth` and `labelAlign` of the Form, and `width` and `align` in the label object win.
|
|
2406
|
+
|
|
2407
|
+
## FormErrorMessage
|
|
2408
|
+
|
|
2409
|
+
```ts
|
|
2410
|
+
import { FormErrorMessage } from '@fibrae/semi-ui-svelte';
|
|
2411
|
+
```
|
|
2412
|
+
|
|
2413
|
+
- The error is an array of strings; multiple errors are joined with commas; use the `errorContent` snippet to render it differently
|
|
2414
|
+
- When the error is `['']`, only the error container is rendered, without text; when it is empty, nothing is rendered
|
|
2415
|
+
|
|
2416
|
+
**Props**
|
|
2417
|
+
|
|
2418
|
+
| Property | Description | Type | Default |
|
|
2419
|
+
| - | - | - | - |
|
|
2420
|
+
| error | The error, a string array whose messages show joined by commas, skipping empty strings; `['']` fails without text and hides helpText too; an empty array or empty value renders nothing. | `FieldError` | - |
|
|
2421
|
+
| errorContent | Custom rendering of the error, with `{ error }`. | `Snippet<[{ error: FieldError }]>` | - |
|
|
2422
|
+
| errorMessageId | The id of the error text element, for aria-errormessage to refer to. | `string` | - |
|
|
2423
|
+
| helpText | Help text, shown when there is no error, in the same block as the error. | `Snippet` | - |
|
|
2424
|
+
| helpTextId | The id of the help text element, for aria-describedby to refer to. | `string` | - |
|
|
2425
|
+
| isInInputGroup | Whether it sits in an InputGroup; with true and showValidateIcon true, the error icon shows whatever validateStatus is. | `boolean` | - |
|
|
2426
|
+
| showValidateIcon | Whether the icon of validateStatus shows. | `boolean` | - |
|
|
2427
|
+
| validateStatus | Validation status of the message: default, error, warning or success. | `ValidateStatus` | - |
|
|
2428
|
+
|
|
2429
|
+
`class`, `style` and native attributes land on the root element.
|
|
2430
|
+
|
|
2431
|
+
## fieldOptions
|
|
2432
|
+
|
|
2433
|
+
The `fieldOptions` property of `FormField`, which describes how it takes over the wrapped component.
|
|
2434
|
+
|
|
2435
|
+
| key | Description | Default |
|
|
2436
|
+
| - | - | - |
|
|
2437
|
+
| valueKey | The bindable property of the component that represents the value; only `'value'`, `'checked'` and `'fileList'` are supported, such as `checked` of Switch and `value` of Input | 'value' |
|
|
2438
|
+
| onKeyChangeFnName | The name of the callback property the component calls when its value changes, generally `onChange`; the callback on the Field receives `latestValues` after the original arguments | 'onChange' |
|
|
2439
|
+
| onBlurFnName | The name of the callback property the component calls when it loses focus; `onblur` for a component that forwards native events, an empty string for a component without one | 'onBlur' |
|
|
2440
|
+
| valuePath | The path of the value in the first argument of the callback, such as `target.checked` of Checkbox and `target.value` of RadioGroup; not needed when the first argument is the value itself | '' |
|
|
2441
|
+
| shouldInject | When false, a component without `field` is rendered as it is and not taken over by the Form, such as a FormCheckbox or FormRadio inside its group | true |
|
|
2442
|
+
| insetLabel | When false, the component renders no inset label, and labelPosition `inset` is laid out as `top` | true |
|
|
2443
|
+
| validateStatus | When false, the component has no `validateStatus` property and the Form no longer passes it, so it does not land on the DOM | true |
|
|
2444
|
+
|
|
2445
|
+
## Accessibility
|
|
2446
|
+
|
|
2447
|
+
### ARIA
|
|
2448
|
+
|
|
2449
|
+
- [aria-labelledby](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-labelledby)、for
|
|
2450
|
+
- Field component will automatically add label DOM. The id of the control is `props.id`, generated when omitted; the for attribute of label is the same as this id; the `id` attribute of label is `${control id}-label`;
|
|
2451
|
+
- When the props.labelPosition of the Form or Field is set to `inset`, there is no label tag at this time, but a div tag. The div tag corresponding to insetLabel will be automatically appended with `id`, the value is the same as the id of the above label, corresponding to the `aria-labelledby` of the Field component. A field that does not support the inset label is laid out as `top`, and its `aria-labelledby` points to the label actually rendered
|
|
2452
|
+
- The Field component will be automatically appended with `aria-labelledby`, the value is the same as the id of the above label; the `aria-labelledby` passed by the caller comes first and the two are merged instead of overwritten
|
|
2453
|
+
- [aria-required](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-required_attribute)
|
|
2454
|
+
- When the Field is configured with required fields (that is, props.rules contains required: true or props.label is configured with required: true without optional: true; with a Form `schema`, only label is read), the Field component will be automatically appended with `aria-required = true` (except CheckboxGroup, Slider, Upload and a single Radio); an aria-required passed on the Field takes precedence
|
|
2455
|
+
- [aria-invalid](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-invalid_attribute) 、[aria-errormessage](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-errormessage)
|
|
2456
|
+
- When the Field check fails, or validateStatus is error, the Field component will be automatically added with the `aria-invalid` = true attribute.
|
|
2457
|
+
- When the Field check fails, the Field component will be automatically appended with the `aria-errormessage` attribute, the value of which is the id of the DOM element corresponding to the errorMessage (format like: `${control id}-errormessage`); for CheckboxGroup it is set on every checkbox in the group.
|
|
2458
|
+
- [aria-describedby](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_aria-describedby_attribute)
|
|
2459
|
+
- When the Field is configured with `helpText` or `extraText`, the Field component will be automatically added with the `aria-describedby` attribute, whose value is the id of the DOM element corresponding to helpText and extraText (format like: `${control id}-helpText` , `${control id}-extraText`); the `aria-describedby` passed by the caller comes first and the two are merged instead of overwritten
|
|
2460
|
+
|
|
2461
|
+
## Content Guidelines
|
|
2462
|
+
|
|
2463
|
+
- Form title
|
|
2464
|
+
- The title of the form needs to follow the writing specification of the title
|
|
2465
|
+
- Form label
|
|
2466
|
+
- The label is a short description of the input box. The label is not a help text, so it should not be a description of the input
|
|
2467
|
+
- Labels must:
|
|
2468
|
+
- Place it above or below the input box
|
|
2469
|
+
- Short (1-3 words)
|
|
2470
|
+
- Use case conventions for statements (first letter uppercase, others lowercase)
|
|
2471
|
+
- Help text
|
|
2472
|
+
- Help text use statement writing conventions, capitalized
|
|
2473
|
+
- Form button
|
|
2474
|
+
- For the content Guidelines of the form button, refer to [Button component](../basic/button.md)
|
|
2475
|
+
|
|
2476
|
+
## Design Tokens
|
|
2477
|
+
|
|
2478
|
+
The design token table of this component is on the web page: <https://semi-design-next.pages.dev/en-US/svelte/input/form/>
|
|
2479
|
+
|
|
2480
|
+
## FAQ
|
|
2481
|
+
|
|
2482
|
+
- **Why did I declare the form, modify the value, and the data is not automatically mapped to formState.values?**\
|
|
2483
|
+
Check that the field has been passed correctly, and the `field` attribute on the Field component is a must-fill property !
|
|
2484
|
+
|
|
2485
|
+
- **Why doesn't the passed `defaultValue` or `defaultChecked` take effect?**\
|
|
2486
|
+
Refer to the beginning of the document [Field](#Field). The Field component unifies the default value. You should pass the default value using `initValue` or `initValues`
|
|
2487
|
+
|
|
2488
|
+
- **Why did the component not change and the value not take effect after `initValue` and `initValues` were updated asynchronously?**\
|
|
2489
|
+
`initValue`, `initValues` are only consumed once when Field and Form mount, and subsequent asynchronous updates will not take effect.\
|
|
2490
|
+
If your initial value needs to be taken remotely, you can update it using `formApi.setValue / setValues` after you get the value\
|
|
2491
|
+
Or send a new `key` directly to Form or Field to force it to remount.
|
|
2492
|
+
|
|
2493
|
+
- **Why is the error message not shown when the validator in rules fails?**
|
|
2494
|
+
|
|
2495
|
+
`rules[].validator` fails when it returns `false` or throws, and shows the `message` of the rule (the default message or the message of the error when there is none); when it returns a string or an array of strings, that is used directly as the error message. Any other return value, such as `true`, `undefined` or an empty string, counts as passed. Also, when `message` is an empty string, the field is only marked red and no text is shown.
|
|
2496
|
+
|
|
2497
|
+
- **Why can't getValues get a certain field?**
|
|
2498
|
+
|
|
2499
|
+
If the field has no initial value, `getValues` cannot get this item. You can set `initValues`/`initValue` or set the `allowEmpty` attribute to the form.
|
|
2500
|
+
|
|
2501
|
+
- **Why does hitting enter on the input box trigger the form's submit?**
|
|
2502
|
+
|
|
2503
|
+
This is standard HTML behavior. We do not plan to intervene and we will remain the same as the HTML. If there is really only one input element in the form, and you don't want to trigger the submit callback when you press Enter, it is recommended to use preventDefault for the enter of the keydown event of input to prevent the default behavior.
|
|
2504
|
+
|
|
2505
|
+
Click [#767](https://github.com/DouyinFE/semi-design/issues/767) for background and content.
|
|
2506
|
+
|
|
2507
|
+
- **The form will automatically save the historical input items, what should I do if I don't want this function?**\
|
|
2508
|
+
Form configures `for`, `name`, `id` and other attributes for input controls strictly according to the W3C standard, so the browser automatically saves history input items. If you don't want the browser to automatically save history input items, you can also turn it off by setting `autoComplete=off` at the Form level or Field level
|
|
2509
|
+
|
|
2510
|
+
## Changes from Semi Design
|
|
2511
|
+
|
|
2512
|
+
From the project release notes (written in Chinese). Your knowledge of Semi Design does not cover these.
|
|
2513
|
+
|
|
2514
|
+
- 破坏性:React、Solid、Svelte 的 `Form` 不再挂静态成员(`Form.Input` 等字段、`Form.Section`、`Form.Label`、`Form.ErrorMessage`、`Form.Slot`、`Form.InputGroup`、`Form.useForm`、`Form.SchemaField`),改用具名导出:字段 `FormInput` 至 `FormPinCode`,部件 `FormSection`、`FormLabel`、`FormErrorMessage`、`FormSlot`、`FormInputGroup`,以及 `useForm`、`SchemaField`;四个框架的导出一致(F17)。新增类型导出 `FormErrorMessageProps`。字段自身的子组件不变,仍写 `FormSelect.Option`。
|
|
2515
|
+
- 破坏性:删除字段属性 `validate`(只认 `validator`)与 Form 级 `validateFields`;`<form>` 默认带 `noValidate`,传 `noValidate={false}` 恢复浏览器原生校验。
|
|
2516
|
+
- 破坏性:`onErrorChange` 在 validate、submit、表单级 validator 失败与转为通过、reset 时各触发一次,字段注册、keepState 恢复、ArrayField 增删行不再单独触发。
|
|
2517
|
+
- 破坏性:表单状态改为不可变更新,每次变化 `onChange`、`useFormState`、render props 拿到新对象;读最新值用 `formApi.getValue(s)()` 或 Field `onChange` 的 `latestValues`。
|
|
2518
|
+
- 破坏性:未传 `id` 的字段,控件 DOM id 由 `useId` 生成,依赖 `#<field>` 或 `htmlFor` 字面值的代码需显式传 `id`;Form 的 ref 为 `FormHandle { formApi }`,实例上的 `submit`、`reset`、`foundation` 不再存在。
|
|
2519
|
+
- 破坏性(类型):`withField` 返回 `ComponentType<FieldProps<ComponentProps<C>>>`,删除 `T`、`R` 类型参数与 `maintainCursor`;字段不再接受 `value`、`defaultValue`、`checked`、`defaultChecked`,改用 `initValue`;`trigger` 收窄为 `FieldValidateTriggerType`;`ArrayField` 的 `field`、`children` 必填。
|
|
2520
|
+
- 破坏性:`useForm()` 等返回的 formApi 上不再有 `__bind`、`__unbind`、`__updateState`、`__realApi`;破坏性(类型):Vue、Solid、Svelte 的 `form` 属性类型由 `FormApi<Values> & FormApiProxyInternals<Values>` 改为 `FormApi<Values>`。
|
|
2521
|
+
- 破坏性(类型):`FormState.errors`、`touched` 与 `onErrorChange` 的 `errors` 改为与值同构的嵌套结构;`FieldPath` 展开深度上限为 5;删除只作类型用的 `Field` 类与 `FormSelectType` 等,改用 `FieldProps<P>`、`FormSelectProps<V, Multiple, WithObject>`(`FormSelect` 现为字段组件的具名导出,泛型同 Select)。
|
|
2522
|
+
- 表单级 `validator` 返回或 resolve `{}` 视为通过;Form 卸载或整表 `reset()` 时挂起的 `validate()` 以取消原因 reject;静默校验不再写入 `formState.errors`;`labelPosition="inset"` 下无法内嵌标签的字段(TextArea、Checkbox、Radio、Switch、Upload 等)按 `top` 布局渲染 Label 并在开发模式警告;FormInputGroup 的 `label` 接受 `LabelProps | ReactNode`。
|
|
2523
|
+
- 表单值深拷贝时 `Blob`、`File` 按引用保留,不再复制(`File` 不可变,按引用与深拷贝语义相同)。
|
|
2524
|
+
- 新增 Form 属性 `schema`,接受实现了 Standard Schema 的校验对象(Zod、Valibot、ArkType 等),与字段的 `validator`、`rules` 互斥,设置后它们不再运行,开发模式下警告;校验全部字段通过后,提交回调与 `formApi.validate()` 拿到 schema 的输出;与 Form 的 `validator` 同传时类型报错,绕过类型时开发模式警告,并且只用 `validator`。Semi 不依赖这些校验库。有 `schema` 时,必填星号与 `aria-required` 只由 `label.required` 决定,不再读 `rules`。
|
|
2525
|
+
- 新增 Form 属性 `schemaDebounce`(毫秒,默认 0):值变化触发的 schema 校验等输入停顿后再执行一次;submit、`validate()`、blur 与挂载时的校验立即执行,整表 `reset()` 与 Form 卸载取消等待中的校验。
|
|
2526
|
+
- 破坏性:错误一律为字符串数组(`FieldError = string[]`):`formState.errors` 的叶子、`formApi.getError`、`onErrorChange`、`onSubmitFail`、`validate()` 的 rejection 与 ErrorMessage 的 `error` 都是 `string[]`,不再支持 ReactNode 与布尔错误,多条消息用 `, ` 连接显示。字段 `validator`、规则的 `validator` 与 `formApi.setError` 接受 `string | string[]`:空串、空数组、`undefined`、`null` 视为通过,字符串转为单元素数组,`['']` 表示失败但不显示文本。表单级 `validator` 返回与值同构的错误树,叶子为 `string | string[]`,空串叶子丢弃;`setError` 给父路径传对象或数组时按同样规则归一化。数组路径上的错误:全为字符串的数组是该路径自身的错误叶子,各行的错误写成嵌套数组(`{ items: [['第 1 行错误']] }`)或对象。
|
|
2527
|
+
- 破坏性:删除 `async-validator` 依赖,字段 `rules` 由 Semi 自带的规则引擎执行,`RuleItem` 为 Semi 自己的类型(`required`、`type`、`len`、`min`、`max`、`pattern`、`enum`、`whitespace`、`message`、`transform`、`validator`),不再支持 async-validator 的 `fields`、`defaultField`、`asyncValidator`、`warningOnly` 等字段。`type` 取 `string`、`number`、`integer`、`float`、`boolean`、`array`、`object`、`date`、`email`、`url`、`regexp`、`method`;`len`、`min`、`max` 对字符串按字符(code point)计数,对数字比较数值,对数组比较项数;规则的 `validator` 签名改为 `(value, values) => string | string[] | boolean | Promise<...>`,返回 `false` 或抛错即失败,其余返回值按上一条归一化。默认错误文案来自语言包 `Form` 切片(新增 `required`、`invalid`、`stringLen`、`stringMin`、`stringMax`、`numberLen`、`numberMin`、`numberMax`、`arrayLen`、`arrayMin`、`arrayMax`),`message` 替换该规则任一检查的文案。每条规则的内置检查至多产生一条消息,`stopValidateWithError` 时在第一条失败的规则处停止。
|
|
2528
|
+
- 破坏性:字段的 `rules` 与 `validator` 互斥,同传时类型报错,绕过类型时开发模式警告一次并只用 `validator`。字段 `validator` 除函数外还接受 Standard Schema 对象(如 `z.string().min(3)`),失败时错误为 schema 的 issue 文案,`stopValidateWithError` 时只取第一条。
|
|
2529
|
+
- 破坏性:Form `keepState` 默认 `true`,字段卸载后保留值、错误与 touched,重新挂载时恢复;字段与 ArrayField 的 `keepState` 未设时依次跟随所在 ArrayField、Form。ArrayField 新增 `keepState`,ArrayField 内的字段不再忽略 `keepState`(原来强制为 false 并警告)。ArrayField 以 keepState 卸载后保留整组数据,重新挂载时按保留的值渲染行,`reset()` 仍恢复到最初的 `initValue`;不保留时删除整组的值、错误与 touched。
|
|
2530
|
+
- ArrayField 的 children 参数新增 `move(from, to)`(Vue 插槽、Svelte snippet 为 `onMove`):移动一行的值、错误与 touched,行的 key 随行移动;下标越界时钳制到首尾,`from === to` 不做事。删除行时 touched 随值一起左移。行内字段的值全为空(如唯一字段为 `''`)时,该行不再从渲染和校验中消失。
|
|
2531
|
+
- 破坏性(类型):`FormApi<Values, Output = Values>` 区分输入与输出类型:`formState`、`getValues` 与字段路径用输入类型,`onSubmit` 与不带字段的 `validate()` 用输出类型(`schema` 的 `InferOutput`),带字段的 `validate(fields)` 仍为输入类型;`getTouched(field?)` 返回 `boolean | Record<string, any> | undefined`,不传字段时返回整棵 touched 树,与 `setTouched` 一致;`getError` 返回 `string[]`(父路径为错误树)或 `undefined`;删除类型 `CommonFieldError`、`BasicFieldError`、`FieldValidateResult`(React 另删 `ErrorMsg`、`ReactFieldError`,Vue 另删 `FormValidateResult`),改用 `FieldError`、`FieldErrorInput`,并新增导出 `FieldValidator`、`FormValidator`、`RuleType`、`JsonSchema`、`SchemaFieldKind`、`SchemaFieldNode`、`SchemaFieldProps`、`SchemaFieldRenderers`、`SchemaFieldContext`、`SchemaObjectContext`、`SchemaArrayContext`、`SchemaArrayItem`、`SchemaLeafContext`、`SchemaFormProps`;React、Solid 的 FormSlot 的 `error` 只接受 ErrorMessage 的属性对象、字符串或字符串数组,不再接受 ReactNode(Solid 为 JSX);FormInputGroup 把组内各字段的错误摊平后合并显示;`StandardSchema` 的类型参数改为 `<Input, Output>`,并带可选的 `types` 与 `jsonSchema`。
|
|
2532
|
+
- 新增 SchemaField 与 SchemaForm:SchemaField 在 Form 内按 JSON Schema 渲染某个路径(`field`,默认根)下的字段,JSON Schema 取显式传入的 `jsonSchema`,否则由 Form `schema` 的 `~standard.jsonSchema` 导出(Zod 4 等实现了 Standard JSON Schema 的库)。两者自身不渲染界面:遍历 schema、绑定字段的值与校验,把每个节点交给 `renderers: { object, array, field }` 里对应种类的渲染函数(Svelte 为 snippet),`renderField` 按路径(数组项写作 `[]`,如 `contacts[].email`)替换单个节点的渲染函数;不传 `renderers` 时只渲染对象的属性,字段与数组不渲染并在开发模式警告。渲染函数收到 `node`(`title`、`description`、`required`、从 schema 根算起的 `depth`、数组行的 `item: { index, arrayTitle, arrayKey }`)与 `render(field)`,对象另收到渲染好的 `content`,数组另收到 `items`(`{ key, field, index, node, value, remove }`)、`add`(按 schema 生成新行)、`addWithInitValue`、`move`、`count`、`minItems`、`maxItems`、`fixed`、`canAdd`、`canRemove`、数组自身的 `error` 与要挂到行容器上的 `fieldProps`(`x-field-id`)。项在 schema 里的 `title`、`description` 原样交出。导出的 `semiRenderers` 用 Semi 控件实现默认界面:字符串、长文本(`maxLength` 大于 160)、数字、布尔、枚举分别渲染为 Input、TextArea、InputNumber、Switch、Select,对象渲染为 Section,选项数组渲染为多选 Select,其他数组渲染为可增删、上下移动的行(`minItems` 等于 `maxItems` 时行数固定),单值数组的行不显示标签与说明、以「数组标题 第 N 项」命名,无法映射的节点不渲染并在开发模式警告;标签取 `title`,说明取 `description`,初值取 `default`,必填取 `required`。另导出 `blankRow(jsonSchema, arrayField)`,按 schema 生成数组新行的初值;导出 `controlProps(node)`,返回 `semiRenderers` 交给叶子控件的约束(Input 的 `maxLength`、TextArea 的 `maxCount`、InputNumber 的 `min`、`max`、`precision`,Select 的 `multiple`、`optionList`),自写渲染器展开它即可跟上 schema 约束;导出 `singleItemName(node, locale)`,返回单值数组行的名称(其他节点为 `undefined`)。枚举的布尔值原样作为 Select 的选项值。由 Form `schema` 导出的 JSON Schema 按 schema 对象缓存,同一 Form 下的多个 SchemaField 只转换一次。SchemaForm 是 Form 加根 SchemaField 的封装,children 渲染在字段之后,不接受 `render`、`component` 与函数形式的 children;它的全局默认值只覆盖 `jsonSchema`、`renderers`、`renderField`,内部 Form 读 Form 的全局默认值。两者读全局默认值(F7)。Svelte 的 SchemaForm 经 `bind:this` 调用 `getFormApi()`。语言包 `Form` 新增 `addItem`、`removeItem`、`moveUpItem`、`moveDownItem`、`item`、`arrayItem`,用作 `semiRenderers` 数组行按钮的可访问名称与行标签。
|
|
2533
|
+
- 新增 `formApi.focusField(field, scrollOpts?)` 与 Form 的 `onRevealField(field)`;`formApi.scrollToField` 支持任意路径(字段、ArrayField 容器与 SchemaField 渲染器挂了 `x-field-id` 的节点),返回 Promise。路径上没有已渲染的元素(或元素在 `inert`、`hidden` 的折叠内容里)时先调用 `onRevealField`,由调用方展开折叠容器,最多等待一秒,挂载后再滚动;`focusField` 滚动后聚焦其中第一个可聚焦的控件,跳过标签旁的 tooltip 按钮。原来只能滚到已注册且已渲染的字段。
|
|
2534
|
+
- 新增 FormSection 的 `extraText`:标题下方的说明文字,经 `aria-describedby` 关联到分组(Vue 另有 `#extraText` 插槽,Svelte 为 snippet)。
|
|
2535
|
+
- 行为变化:字段卸载造成的值删除与 `onChange` 推迟到 Form 的下一次提交时发出,删除中间一行时 `onChange` 只发一次完整值;卸载整个 Form 不再逐字段触发 `onChange` 与更新。首帧 `formState.values` 是传入的 `initValues` 对象本身,不再是它的克隆。
|
|
2536
|
+
- 字段首次挂载时显示 `formState.errors` 里已有的错误;整表 `reset()` 清空全部错误,包括没有对应字段的错误。
|
|
2537
|
+
- 破坏性:FormSection 的根元素由 `section` 改为 `fieldset`,标题由 `h5` 改为 `legend`:分组以标题为可访问名称(`role="group"`),不再向页面插入固定层级的标题,外观不变。`ref` 类型改为 `HTMLFieldSetElement`,Props 的原生属性改为 fieldset 的属性;传入原生 `disabled` 时浏览器禁用其中全部表单控件,Form 的 `disabled` 状态不随之变化。
|
|
2538
|
+
- 新增 Transfer 字段 `FormTransfer`:值为 Transfer 的 `value`(Vue `modelValue`)数组,`onChange`(Vue `change`)末参追加 `latestValues`;`labelPosition="inset"` 按 `top` 布局。`trigger="blur"` 在焦点离开整个 Transfer 时校验并标 touched(见 Transfer 的 blur 事件)。
|
|
2539
|
+
- Svelte:`FormSelect`、`FormCascader`、`FormTreeSelect`、`FormAutoComplete`、`FormDatePicker`、`FormTimePicker` 的自定义触发器 snippet 在字段上叫 `triggerContent`(字段的 `trigger` 是校验时机),转发给控件的 `trigger`,传了它时 `labelPosition="inset"` 按 `top` 布局。
|
|
2540
|
+
- Svelte:新增 `FormCascader`、`FormTreeSelect`;Form 字段不接受原生 `defaultValue`、`defaultChecked`,用 `initValue` 代替;FormInputGroup 只渲染一个 group,标签由 InputGroup 渲染。
|
|
2541
|
+
- Svelte:字段组件经 `bind:this` 调用 `getControl()` 取得被包裹控件的实例,再调用控件自己的方法(如 `getControl()?.focus()`、`getControl()?.open()`)。
|
|
2542
|
+
- Solid、Svelte:嵌套 ArrayField 未设 `keepState` 时先跟随父 ArrayField,再跟随 Form(F16);原来直接跟随 Form。
|
|
2543
|
+
- Svelte:ArrayField 改 `field` 时,旧路径按解析后的 `keepState` 处理,为 false 时移除旧路径的值、错误与 touched(原来总是保留),与其余三个框架一致。
|
|
2544
|
+
- 类型:`initValues` 改为 `DeepPartial<Values>`(foundation 新增导出 `DeepPartial`):Values 由 `schema` 推导时(SchemaForm、带 `schema` 的 Form)可以只给部分初值,嵌套对象与数组元素同样可省略;没有 `schema` 时 Values 仍从 `initValues` 推导。
|
|
2545
|
+
- React 类型:`FormCheckbox`、`FormRadio`、`FormSelect` 的 `onChange` 末参带上 `latestValues`;Checkbox、Radio 不传 `field`(作为组内控件)时只收到事件,所以 `latestValues` 为可选。
|
|
2546
|
+
- Vue、Svelte:字段 `label` 配置新增 `id`,作为 label 元素的 id(控件的 `aria-labelledby` 指向它),不传时自动生成;FormSlot 同样采用配置里的 `id`。
|
|
2547
|
+
- Svelte:Form 的 `onsubmit`、`onreset` 在 Form 处理提交、重置之后调用使用方传入的回调(原来被吞掉)。
|
|
2548
|
+
- 破坏性(类型):foundation `form/interface` 的 `setValuesConfig` 改名 `SetValuesConfig`;Solid、Svelte 的 `useFieldState` 返回值中 `error`、`touched` 改为可选属性。
|
|
2549
|
+
- 新增标签属性 `tooltip`(FormLabel 的 prop,字段 `label` 对象里的同名配置):label 旁显示问号按钮(描边图标,与标签文字同大),悬停或聚焦时用 Tooltip 显示说明。按钮在 `<label>` 元素之外,不进入字段的可访问名称,名称取语言包 `Form.labelTooltip`;设了 `width` 时宽度落在外层容器上。类型:React、Solid 为节点,Vue 为 `string | number` 加 `#tooltip` 插槽(只在 FormLabel 上),Svelte 的 FormLabel 为 snippet 或 `string | number`、字段 `label` 配置为 `string | number`。
|
|
2550
|
+
- 行为变化:必填星号由标签文字之后移到文字之前(`.semi-form-field-label-required` 的 `::before`),`optional`、`extra`、tooltip 的位置不变;按旧位置写的样式覆盖需调整。
|