@jsb188/form 1.1.12 → 1.1.13

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jsb188
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -130,4 +130,4 @@ For signed storage uploads, call `useSignedFileUpload` from `@jsb188/react-web/h
130
130
 
131
131
  Run `yarn workspace @jsb188/form test` and `yarn workspace @jsb188/form typecheck`. Focused tests cover nested state, asynchronous validation and saving, native submission, domain definitions, and standalone control interactions.
132
132
 
133
- Application integration tests live in `apps/marketday/tests/AuthFormIntegration.test.tsx` and `SchemaSettingsIntegration.test.tsx`. They exercise actual form components and their existing request/state boundaries without sending live email, SMS, or OAuth requests. Real provider delivery, real server-issued sessions, and password-manager/OS autofill still require a configured account/device check; they are not simulated by a desktop DOM test.
133
+ Application integration tests live in `client/tests/AuthFormIntegration.test.tsx` and `SchemaSettingsIntegration.test.tsx`. They exercise actual form components and their existing request/state boundaries without sending live email, SMS, or OAuth requests. Real provider delivery, real server-issued sessions, and password-manager/OS autofill still require a configured account/device check; they are not simulated by a desktop DOM test.
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@jsb188/form",
3
- "version": "1.1.12",
3
+ "version": "1.1.13",
4
4
  "description": "Form controls, presentation, interactions, and typed schema forms for web.",
5
- "license": "ISC",
5
+ "license": "MIT",
6
6
  "author": "jsb188",
7
7
  "type": "module",
8
8
  "sideEffects": [
@@ -22,10 +22,10 @@
22
22
  "./ui/Input.helpers": "./src/ui/Input.helpers.ts"
23
23
  },
24
24
  "peerDependencies": {
25
- "@jsb188/app": "1.1.12",
26
- "@jsb188/css": "1.1.12",
27
- "@jsb188/react": "1.1.12",
28
- "@jsb188/react-web": "1.1.12",
25
+ "@jsb188/app": "1.1.13",
26
+ "@jsb188/css": "1.1.13",
27
+ "@jsb188/react": "1.1.13",
28
+ "@jsb188/react-web": "1.1.13",
29
29
  "luxon": "^3.7.2",
30
30
  "react": "^19.3.0",
31
31
  "react-dom": "^19.3.0",
@@ -37,5 +37,14 @@
37
37
  "scripts": {
38
38
  "test": "vitest run --config ./vitest.config.ts",
39
39
  "typecheck": "tsc -p tsconfig.json"
40
- }
40
+ },
41
+ "files": [
42
+ "css/**/*.{ts,tsx,css,svg}",
43
+ "src/**/*.{ts,tsx,css,svg}",
44
+ "!**/*.test.*",
45
+ "!**/*.spec.*",
46
+ "!**/tests/**",
47
+ "!**/*.md",
48
+ "!**/.DS_Store"
49
+ ]
41
50
  }
@@ -3,6 +3,7 @@ import { memo, type KeyboardEvent } from 'react';
3
3
  import { Icon } from '@jsb188/react-web/svgs/Icon';
4
4
  import { LineRow } from '../ui/FormUI';
5
5
  import { Select, type SelectOptionType } from './Select';
6
+ import type { TooltipButtonProps } from '@jsb188/react/types/PopOver.d';
6
7
  import { TooltipButton } from '@jsb188/react-web/modules/popover/Tooltip';
7
8
 
8
9
  /**
@@ -13,9 +14,10 @@ import { TooltipButton } from '@jsb188/react-web/modules/popover/Tooltip';
13
14
  /*
14
15
  * Render the trailing info tooltip of a line row, if the row has one.
15
16
  */
16
- const LineTooltip = (p: { message?: string }) =>
17
+ const LineTooltip = (p: { message?: string; position?: TooltipButtonProps['position'] }) =>
17
18
  p.message ? (
18
19
  <TooltipButton
20
+ position={p.position}
19
21
  ariaLabel={p.message}
20
22
  className="p_10 ic_sm"
21
23
  message={p.message}
@@ -43,6 +45,7 @@ export const LineInput = memo(
43
45
  onKeyDown?: (event: KeyboardEvent<HTMLInputElement>) => void;
44
46
  placeholder?: string;
45
47
  tooltipInfo?: string;
48
+ tooltipPosition?: TooltipButtonProps['position'];
46
49
  type: 'email' | 'text';
47
50
  value: string;
48
51
  }) => (
@@ -63,7 +66,10 @@ export const LineInput = memo(
63
66
  onChange={(event) => p.onChange(event.target.value)}
64
67
  onKeyDown={p.onKeyDown}
65
68
  />
66
- <LineTooltip message={p.tooltipInfo} />
69
+ <LineTooltip
70
+ message={p.tooltipInfo}
71
+ position={p.tooltipPosition}
72
+ />
67
73
  </LineRow>
68
74
  ),
69
75
  );
@@ -45,7 +45,7 @@ const ListItemFormFieldControl = memo(
45
45
  >
46
46
  {field.label ? (
47
47
  <label
48
- className="abs_tl ft_xxs lh_1 cl_md px_8 pt_2 ellip max_w_f"
48
+ className="abs_tl ft_xxxs lh_1 cl_md px_8 pt_2 ellip max_w_f"
49
49
  htmlFor={id}
50
50
  >
51
51
  {field.label}
@@ -316,14 +316,15 @@ export const ListItemForm = <V extends ListItemFormValues>(p: ListItemFormProps<
316
316
  </>
317
317
  ) : (
318
318
  <>
319
- {iconName ? (
320
- <ListItemFormIcon
321
- iconName={iconName}
322
- tooltipText={iconTooltipText}
323
- />
324
- ) : null}
319
+ {p.leadingItem ??
320
+ (iconName ? (
321
+ <ListItemFormIcon
322
+ iconName={iconName}
323
+ tooltipText={iconTooltipText}
324
+ />
325
+ ) : null)}
325
326
  <span className="f min_w_0 h_item gap_8">
326
- <span className="ellip no_shrink">{text}</span>
327
+ <span className="ellip">{text}</span>
327
328
  {secondaryText ? <span className="ellip ft_xs cl_md">{secondaryText}</span> : null}
328
329
  </span>
329
330
  {confirmingDelete ? null : RightItemComponent}
@@ -21,6 +21,7 @@ export interface ListItemFormProps<V extends ListItemFormValues> {
21
21
  text: string;
22
22
  // Muted text shown after the main text in display mode.
23
23
  secondaryText?: string;
24
+ leadingItem?: ReactNode;
24
25
  iconName?: string;
25
26
  // Hover tooltip of the icon; without it the icon is plain and not interactive.
26
27
  iconTooltipText?: string;
@@ -51,6 +51,7 @@ export const POInput = memo(
51
51
  return (
52
52
  <Input
53
53
  className="m_3 ft_sm"
54
+ inputClassName={item.inputClassName}
54
55
  borderRadiusClassName="r_xs"
55
56
  name={name}
56
57
  preset={item.preset}
package/src/ui/FormUI.tsx CHANGED
@@ -175,14 +175,23 @@ FormSectionTitle.displayName = 'FormSectionTitle';
175
175
  * Form break
176
176
  */
177
177
 
178
- export const FormBreak = memo((p: { children?: string; className?: string; heightClassName?: string; colorClassName?: string }) => {
179
- const { children, className, heightClassName, colorClassName } = p;
180
- return (
181
- <div className={cn('pattern_texture rel h_center', colorClassName ?? 'strong_bf', heightClassName ?? 'h_10', className)}>
182
- {children ? <span className="text ft_sm bg rel z2 px_xs lh_1 cl_bd">{children}</span> : null}
183
- </div>
184
- );
185
- });
178
+ export const FormBreak = memo(
179
+ (p: {
180
+ alignContent?: 'left' | 'center' | 'right';
181
+ children?: string;
182
+ className?: string;
183
+ heightClassName?: string;
184
+ colorClassName?: string;
185
+ }) => {
186
+ const { alignContent = 'center', children, className, heightClassName, colorClassName } = p;
187
+ const alignmentClass = { left: 'h_item px_18', center: 'h_center', right: 'h_right px_18' }[alignContent];
188
+ return (
189
+ <div className={cn('pattern_texture rel', alignmentClass, colorClassName ?? 'strong_bf', heightClassName ?? 'h_10', className)}>
190
+ {children ? <span className="text ft_sm bg rel z2 px_xs lh_1 cl_md">{children}</span> : null}
191
+ </div>
192
+ );
193
+ },
194
+ );
186
195
 
187
196
  FormBreak.displayName = 'FormBreak';
188
197
 
@@ -231,7 +240,9 @@ LineRow.displayName = 'LineRow';
231
240
  * Render one selected item as a chip inside a line form row.
232
241
  */
233
242
  export const LineChip = memo((p: { children: ReactNode; className?: string }) => (
234
- <span className={cn('rel ls_5 h_32 max_w_200 px_8 py_3 h_item r_sm bg_alt bd_1 bd_lt', p.className)}>{p.children}</span>
243
+ <span className={cn('rel ls_5 min_h_32 max_w_f min_w_0 ofw px_8 py_3 h_item r_sm bg_alt bd_1 bd_lt', p.className)}>
244
+ {p.children}
245
+ </span>
235
246
  ));
236
247
 
237
248
  LineChip.displayName = 'LineChip';
package/src/ui/Input.tsx CHANGED
@@ -149,6 +149,7 @@ export function InputUI(
149
149
  disabled={disabled || locked || editable === false || disabledButClickable}
150
150
  // biome-ignore lint/a11y/noAutofocus: Preserve explicit autofocus requested by the existing form flow.
151
151
  autoFocus={autoFocus}
152
+ data-autofocus={autoFocus || undefined}
152
153
  autoComplete={autoComplete || 'off'}
153
154
  spellCheck={spellCheck}
154
155
  maxLength={maxLength}
@@ -1,4 +1,4 @@
1
- export type InputPresetName = 'none' | 'fill' | 'fill_large' | 'inside_outline' | 'lighter' | 'subtle' | 'tiny';
1
+ export type InputPresetName = 'none' | 'fill' | 'fill_large' | 'inside_outline' | 'lighter' | 'subtle' | 'smaller' | 'tiny';
2
2
  export type InputFocusStyle = 'outline' | 'shadow';
3
3
 
4
4
  export interface InputPresentationProps {
@@ -19,14 +19,17 @@ export const LineSelections = memo(
19
19
  }) => (
20
20
  <LineRow
21
21
  label={p.label}
22
+ labelClassName="no_shrink"
22
23
  labelWidthClassName={p.labelWidthClassName}
23
24
  >
24
25
  <div className="f h_item f_wrap gap_5 py_5 min_w_0">
25
26
  {p.selections.map((item) => (
26
- <LineChip key={item.id}>{item.text}</LineChip>
27
+ <LineChip key={item.id}>
28
+ <span className="ellip">{item.text}</span>
29
+ </LineChip>
27
30
  ))}
28
31
  </div>
29
- {p.summary && <span className="ft_sm cl_md no_shrink pr_10">{p.summary}</span>}
32
+ {p.summary && <span className="ft_sm cl_md no_shrink px_10">{p.summary}</span>}
30
33
  </LineRow>
31
34
  ),
32
35
  );
@@ -1,336 +0,0 @@
1
- import { act } from 'react';
2
- import type { Root } from 'react-dom/client';
3
- import { JSDOM } from 'jsdom';
4
- import { afterEach, beforeEach, describe, expect, expectTypeOf, it, vi } from 'vitest';
5
- import { z } from 'zod';
6
- import { defineForm } from '../src/libs/defineForm';
7
- import type { FormController, FormDefinition, FormOptions, SubmitResult } from '../src/libs/SchemaForm.types';
8
- import { useSchemaForm } from '../src/libs/useSchemaForm';
9
- import { useField } from '../src/libs/useField';
10
-
11
- const roots = new Set<Root>();
12
- let dom: JSDOM;
13
- let createRoot: typeof import('react-dom/client').createRoot;
14
-
15
- beforeEach(async () => {
16
- dom = new JSDOM('<!doctype html><html><body></body></html>');
17
- vi.stubGlobal('window', dom.window);
18
- vi.stubGlobal('document', dom.window.document);
19
- vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
20
- ({ createRoot } = await import('react-dom/client'));
21
- });
22
-
23
- /* Release asynchronous validation or persistence only when a test reaches the relevant edit state. */
24
- function deferred<T>() {
25
- let resolve!: (value: T) => void;
26
- const promise = new Promise<T>((resolvePromise) => {
27
- resolve = resolvePromise;
28
- });
29
- return { promise, resolve };
30
- }
31
-
32
- /* Render the real controller without depending on presentation components or external application state. */
33
- function renderForm<S extends z.ZodTypeAny>(definition: FormDefinition<S>, options: FormOptions<z.input<S>, z.output<S>> = {}) {
34
- const root = createRoot(document.createElement('div'));
35
- roots.add(root);
36
- let form!: FormController<z.input<S>, z.output<S>>;
37
- let latestOptions = options;
38
-
39
- /* Expose each committed controller snapshot for assertions and user-like actions. */
40
- const Harness = () => {
41
- form = useSchemaForm(definition, latestOptions);
42
- return null;
43
- };
44
-
45
- act(() => root.render(<Harness />));
46
- return {
47
- get form() {
48
- return form;
49
- },
50
- /* Simulate refreshed props without replacing the mounted form record. */
51
- rerender(nextOptions: FormOptions<z.input<S>, z.output<S>>) {
52
- latestOptions = nextOptions;
53
- act(() => root.render(<Harness />));
54
- },
55
- };
56
- }
57
-
58
- /* Use named nested fields to exercise immutable path updates and independent draft snapshots. */
59
- function addressDefinition() {
60
- return defineForm({
61
- schema: z.object({ address: z.object({ city: z.string().min(1), postal: z.string() }), note: z.string() }),
62
- defaults: { address: { city: 'Toronto', postal: '' }, note: '' },
63
- fields: {
64
- 'address.city': { kind: 'input' },
65
- 'address.postal': { kind: 'input' },
66
- note: { kind: 'textarea' },
67
- },
68
- });
69
- }
70
-
71
- afterEach(() => {
72
- act(() => {
73
- for (const root of roots) root.unmount();
74
- });
75
- roots.clear();
76
- dom.window.close();
77
- vi.unstubAllGlobals();
78
- });
79
-
80
- describe('form controller', () => {
81
- it('tracks custom field dirty state and resets without requiring automatic field definitions', async () => {
82
- const definition = defineForm({
83
- schema: z.object({ contact: z.object({ email: z.string() }) }),
84
- defaults: { contact: { email: 'before@example.com' } },
85
- fields: {},
86
- });
87
- let form!: FormController<z.input<typeof definition.schema>>;
88
- let field!: ReturnType<typeof useField<z.input<typeof definition.schema>, 'contact.email'>>;
89
- /* Bind an individual custom control without asking the schema renderer to render any fields. */
90
- const Harness = () => {
91
- form = useSchemaForm(definition);
92
- field = useField(form, 'contact.email');
93
- return null;
94
- };
95
- const root = createRoot(document.createElement('div'));
96
- roots.add(root);
97
- act(() => root.render(<Harness />));
98
- expect(field.dirty).toBe(false);
99
- act(() => field.setValue('after@example.com'));
100
- expect(field.dirty).toBe(true);
101
- expect(form.isFieldDirty('contact')).toBe(true);
102
- await act(async () => {
103
- await form.submit();
104
- });
105
- expect(field.dirty).toBe(false);
106
- const resetKey = form.resetKey;
107
- act(() => form.reset());
108
- expect(form.resetKey).toBe(resetKey + 1);
109
- expect(field.value).toBe('after@example.com');
110
- });
111
-
112
- it('accepts nested partial initial values while retaining complete dates and array items', () => {
113
- type Values = { profile: { name: string; birthday: Date }; contacts: { email: string; label: string }[] };
114
- expectTypeOf<FormOptions<Values>['initialValues']>().toEqualTypeOf<
115
- | {
116
- profile?: { name?: string; birthday?: Date };
117
- contacts?: { email: string; label: string }[];
118
- }
119
- | undefined
120
- >();
121
- });
122
-
123
- it('tracks nested edits without mutating defaults, initial values, or saved snapshots', () => {
124
- const definition = addressDefinition();
125
- const initialValues = { address: { city: 'Ottawa' } };
126
- const harness = renderForm(definition, { initialValues });
127
- const originalValues = harness.form.values;
128
-
129
- act(() => harness.form.setFieldValue('address.city', 'Montreal'));
130
-
131
- expect(harness.form.values.address.city).toBe('Montreal');
132
- expect(harness.form.values.address.postal).toBe('');
133
- const mutableSnapshot = harness.form.getValues();
134
- mutableSnapshot.address.city = 'External mutation';
135
- expect(harness.form.values.address.city).toBe('Montreal');
136
- expect(harness.form.dirtyFields).toEqual({ 'address.city': true });
137
- expect(harness.form.isDirty).toBe(true);
138
- expect(originalValues.address.city).toBe('Ottawa');
139
- expect(initialValues.address.city).toBe('Ottawa');
140
- expect(definition.defaults.address.city).toBe('Toronto');
141
-
142
- act(() => harness.form.reset());
143
-
144
- expect(harness.form.values.address.city).toBe('Ottawa');
145
- expect(harness.form.isDirty).toBe(false);
146
- expect(harness.form.dirtyFields).toEqual({});
147
- });
148
-
149
- it('keeps draft values across refreshed props and reinitializes only on explicit reset', () => {
150
- const harness = renderForm(addressDefinition());
151
- act(() => harness.form.setFieldValue('note', 'unsaved note'));
152
-
153
- harness.rerender({ initialValues: { note: 'background refresh' } });
154
-
155
- expect(harness.form.values.note).toBe('unsaved note');
156
- act(() => harness.form.reset({ address: { city: 'Vancouver', postal: '' }, note: 'next record' }));
157
- expect(harness.form.values.note).toBe('next record');
158
- expect(harness.form.isDirty).toBe(false);
159
- });
160
-
161
- it('deduplicates concurrent submits and keeps edits made during persistence dirty', async () => {
162
- const save = deferred<SubmitResult<z.input<ReturnType<typeof addressDefinition>['schema']>>>();
163
- const onSubmit = vi.fn((_values: z.input<ReturnType<typeof addressDefinition>['schema']>) => save.promise);
164
- const harness = renderForm(addressDefinition(), { onSubmit });
165
- act(() => harness.form.setFieldValue('note', 'submitted note'));
166
- let first!: ReturnType<typeof harness.form.submit>;
167
- let second!: ReturnType<typeof harness.form.submit>;
168
-
169
- act(() => {
170
- first = harness.form.submit();
171
- second = harness.form.submit();
172
- });
173
- expect(first).toBe(second);
174
- await act(async () => {});
175
- expect(onSubmit).toHaveBeenCalledTimes(1);
176
- expect(harness.form.isSubmitting).toBe(true);
177
-
178
- act(() => harness.form.setFieldValue('note', 'newer note'));
179
- await act(async () => {
180
- save.resolve({ status: 'success' });
181
- await first;
182
- });
183
-
184
- expect(onSubmit.mock.calls[0][0].note).toBe('submitted note');
185
- expect(harness.form.values.note).toBe('newer note');
186
- expect(harness.form.isDirty).toBe(true);
187
- expect(harness.form.isSubmitting).toBe(false);
188
- act(() => harness.form.reset());
189
- expect(harness.form.values.note).toBe('submitted note');
190
- });
191
-
192
- it('keeps failed saves dirty and forwards thrown errors to the existing error UI', async () => {
193
- const onError = vi.fn();
194
- const harness = renderForm(addressDefinition(), {
195
- onSubmit: async () => {
196
- throw new Error('Connection lost');
197
- },
198
- onError,
199
- });
200
- act(() => harness.form.setFieldValue('note', 'unsaved note'));
201
-
202
- await act(async () => {
203
- await harness.form.submit();
204
- });
205
-
206
- expect(harness.form.isDirty).toBe(true);
207
- expect(harness.form.isSubmitting).toBe(false);
208
- expect(harness.form.submitError?.message).toBe('Connection lost');
209
- expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'Connection lost' }));
210
- act(() => harness.form.reset());
211
- expect(harness.form.values.note).toBe('');
212
- });
213
-
214
- it('discards stale async validation results after a newer edit has been validated', async () => {
215
- const oldValidation = deferred<boolean>();
216
- const definition = defineForm({
217
- schema: z.object({ name: z.string().refine((value) => (value === 'old' ? oldValidation.promise : true), 'Unavailable') }),
218
- defaults: { name: 'old' },
219
- fields: { name: { kind: 'input' } },
220
- });
221
- const harness = renderForm(definition);
222
- let oldResult!: ReturnType<typeof harness.form.validate>;
223
- act(() => {
224
- oldResult = harness.form.validate();
225
- });
226
- act(() => harness.form.setFieldValue('name', 'new'));
227
- await act(async () => {
228
- await harness.form.validate();
229
- });
230
- await act(async () => {
231
- oldValidation.resolve(false);
232
- await oldResult;
233
- });
234
-
235
- expect(harness.form.values.name).toBe('new');
236
- expect(harness.form.errors).toEqual({});
237
- expect(harness.form.isValidating).toBe(false);
238
- });
239
-
240
- it('isolates a reset and subsequent save from a previous in-flight save', async () => {
241
- const oldSave = deferred<SubmitResult<z.input<ReturnType<typeof addressDefinition>['schema']>>>();
242
- const nextSave = deferred<SubmitResult<z.input<ReturnType<typeof addressDefinition>['schema']>>>();
243
- const onSubmit = vi.fn().mockReturnValueOnce(oldSave.promise).mockReturnValueOnce(nextSave.promise);
244
- const harness = renderForm(addressDefinition(), { onSubmit });
245
- act(() => harness.form.setFieldValue('note', 'old record'));
246
- let oldResult!: ReturnType<typeof harness.form.submit>;
247
- act(() => {
248
- oldResult = harness.form.submit();
249
- });
250
- await act(async () => {});
251
-
252
- act(() => harness.form.reset({ address: { city: 'Ottawa', postal: '' }, note: 'next record' }));
253
- act(() => harness.form.setFieldValue('note', 'next record edited'));
254
- let nextResult!: ReturnType<typeof harness.form.submit>;
255
- act(() => {
256
- nextResult = harness.form.submit();
257
- });
258
- await act(async () => {});
259
- await act(async () => {
260
- oldSave.resolve({ status: 'success' });
261
- await oldResult;
262
- });
263
-
264
- expect(harness.form.values.note).toBe('next record edited');
265
- expect(harness.form.isSubmitting).toBe(true);
266
- expect(harness.form.isDirty).toBe(true);
267
- await act(async () => {
268
- nextSave.resolve({ status: 'success' });
269
- await nextResult;
270
- });
271
- expect(harness.form.isDirty).toBe(false);
272
- expect(harness.form.isSubmitting).toBe(false);
273
- });
274
-
275
- it('discards validation captured before a successful save normalizes editable values', async () => {
276
- const staleValidation = deferred<boolean>();
277
- const save = deferred<SubmitResult<{ name: string }>>();
278
- let delayValidation = false;
279
- const definition = defineForm({
280
- schema: z.object({ name: z.string().refine(() => (delayValidation ? staleValidation.promise : true), 'Draft is unavailable') }),
281
- defaults: { name: 'draft' },
282
- fields: { name: { kind: 'input' } },
283
- });
284
- const harness = renderForm(definition, { onSubmit: () => save.promise });
285
- let submitted!: ReturnType<typeof harness.form.submit>;
286
- act(() => {
287
- submitted = harness.form.submit();
288
- });
289
- await act(async () => {});
290
- delayValidation = true;
291
- let oldResult!: ReturnType<typeof harness.form.validate>;
292
- act(() => {
293
- oldResult = harness.form.validate();
294
- });
295
- await act(async () => {});
296
- await act(async () => {
297
- save.resolve({ status: 'success', values: { name: 'normalized' } });
298
- await submitted;
299
- });
300
- await act(async () => {
301
- staleValidation.resolve(false);
302
- await oldResult;
303
- });
304
-
305
- expect(harness.form.values.name).toBe('normalized');
306
- expect(harness.form.isDirty).toBe(false);
307
- expect(harness.form.errors).toEqual({});
308
- expect(harness.form.isValidating).toBe(false);
309
- });
310
-
311
- it('preserves newer validation errors when a pending save reports another field error', async () => {
312
- const save = deferred<SubmitResult<{ name: string; note: string }>>();
313
- const definition = defineForm({
314
- schema: z.object({ name: z.string().min(3), note: z.string().min(3, 'Note is too short') }),
315
- defaults: { name: 'Alice', note: 'Valid note' },
316
- fields: { name: { kind: 'input' }, note: { kind: 'textarea' } },
317
- });
318
- const harness = renderForm(definition, { onSubmit: () => save.promise });
319
- let submitted!: ReturnType<typeof harness.form.submit>;
320
- act(() => {
321
- submitted = harness.form.submit();
322
- });
323
- await act(async () => {});
324
- await act(async () => {
325
- harness.form.setFieldValue('note', 'x');
326
- });
327
- expect(harness.form.errors.note).toEqual(['Note is too short']);
328
-
329
- await act(async () => {
330
- save.resolve({ status: 'error', error: { message: 'Name is taken' }, fieldErrors: { name: ['Name is taken'] } });
331
- await submitted;
332
- });
333
-
334
- expect(harness.form.errors).toEqual({ name: ['Name is taken'], note: ['Note is too short'] });
335
- });
336
- });