@jsb188/form 0.0.0-stage → 1.1.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +132 -2
  2. package/css/form.css +2 -0
  3. package/package.json +40 -5
  4. package/src/assets.d.ts +1 -0
  5. package/src/libs/SchemaForm.tsx +158 -0
  6. package/src/libs/SchemaForm.types.ts +165 -0
  7. package/src/libs/defineForm.ts +11 -0
  8. package/src/libs/rules.ts +126 -0
  9. package/src/libs/useField.ts +16 -0
  10. package/src/libs/useSchemaForm.helpers.ts +71 -0
  11. package/src/libs/useSchemaForm.ts +268 -0
  12. package/src/libs/validation.ts +42 -0
  13. package/src/main.ts +40 -0
  14. package/src/modules/FieldLabel.tsx +28 -0
  15. package/src/modules/Form-Input.tsx +2 -0
  16. package/src/modules/Form-Line.tsx +126 -0
  17. package/src/modules/Form.helpers.ts +12 -0
  18. package/src/modules/Form.tsx +14 -0
  19. package/src/modules/FormItem.tsx +117 -0
  20. package/src/modules/FormOptions.tsx +12 -0
  21. package/src/modules/FormUI.tsx +2 -0
  22. package/src/modules/Input.tsx +16 -0
  23. package/src/modules/InputClick.tsx +48 -0
  24. package/src/modules/InputWithButton.tsx +37 -0
  25. package/src/modules/ListItemForm.tsx +345 -0
  26. package/src/modules/ListItemForm.types.ts +50 -0
  27. package/src/modules/PasswordInput.tsx +36 -0
  28. package/src/modules/PopOverInput.tsx +75 -0
  29. package/src/modules/SMSCodeInput.tsx +118 -0
  30. package/src/modules/SchemaField.tsx +104 -0
  31. package/src/modules/Select.tsx +163 -0
  32. package/src/modules/Textarea.tsx +33 -0
  33. package/src/modules/TimeInput.helpers.ts +73 -0
  34. package/src/modules/TimeInput.tsx +159 -0
  35. package/src/modules/TimeInput.types.ts +43 -0
  36. package/src/modules/UploadInput.tsx +141 -0
  37. package/src/modules/composeFormInput.tsx +88 -0
  38. package/src/types/form.ts +65 -0
  39. package/src/ui/ContentEditable.tsx +70 -0
  40. package/src/ui/Form.types.ts +138 -0
  41. package/src/ui/FormOptions.tsx +125 -0
  42. package/src/ui/FormUI.tsx +237 -0
  43. package/src/ui/Input.helpers.ts +7 -0
  44. package/src/ui/Input.tsx +199 -0
  45. package/src/ui/Input.types.ts +48 -0
  46. package/src/ui/InputButtons.tsx +41 -0
  47. package/src/ui/InputControls.tsx +68 -0
  48. package/src/ui/Label.tsx +46 -0
  49. package/src/ui/LineForm.tsx +34 -0
  50. package/src/ui/SMSCodeInput.tsx +51 -0
  51. package/src/ui/Select.tsx +33 -0
  52. package/src/ui/Textarea.tsx +96 -0
  53. package/src/ui/TimeInput.tsx +140 -0
  54. package/tests/controller.test.tsx +336 -0
  55. package/tests/controls.test.tsx +261 -0
  56. package/tests/schema-form.test.tsx +303 -0
  57. package/tests/settings-definitions.test.ts +129 -0
  58. package/tests/sms-input.test.tsx +131 -0
  59. package/tests/time-input.test.tsx +395 -0
  60. package/tests/types.ts +102 -0
  61. package/tests/upload-input.test.tsx +114 -0
  62. package/tests/validation.test.ts +65 -0
  63. package/tsconfig.json +13 -0
  64. package/vitest.config.ts +8 -0
@@ -0,0 +1,336 @@
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
+ });
@@ -0,0 +1,261 @@
1
+ import { usePopOverActions, usePopOverDefinition, usePopOverEvent } from '@jsb188/react/states';
2
+ import { createStore, Provider } from 'jotai';
3
+ import { act, useState, type ReactNode } from 'react';
4
+ import type { Root } from 'react-dom/client';
5
+ import { JSDOM } from 'jsdom';
6
+ import { afterEach, beforeEach, expect, it, vi } from 'vitest';
7
+ import { composeFormInput } from '../src/modules/composeFormInput';
8
+ import { Input } from '../src/modules/Input';
9
+ import { PasswordInput } from '../src/modules/PasswordInput';
10
+ import { Select } from '../src/modules/Select';
11
+ import { Textarea } from '../src/modules/Textarea';
12
+ import { InputTimeFromDate } from '../src/modules/TimeInput';
13
+
14
+ let root: Root;
15
+ let dom: JSDOM;
16
+ let container: HTMLDivElement;
17
+ let resizeCallback: ResizeObserverCallback;
18
+ const disconnect = vi.fn();
19
+
20
+ beforeEach(async () => {
21
+ dom = new JSDOM('<!doctype html><html><body></body></html>');
22
+ vi.stubGlobal('window', dom.window);
23
+ vi.stubGlobal('document', dom.window.document);
24
+ vi.stubGlobal('HTMLInputElement', dom.window.HTMLInputElement);
25
+ vi.stubGlobal('Event', dom.window.Event);
26
+ const { createRoot } = await import('react-dom/client');
27
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
28
+ vi.stubGlobal(
29
+ 'ResizeObserver',
30
+ class {
31
+ /*
32
+ * Keep the resize notification available so textarea measurement can be tested without browser layout.
33
+ */
34
+ constructor(callback: ResizeObserverCallback) {
35
+ resizeCallback = callback;
36
+ }
37
+ observe = vi.fn();
38
+ disconnect = disconnect;
39
+ },
40
+ );
41
+ container = document.createElement('div');
42
+ document.body.append(container);
43
+ root = createRoot(container);
44
+ });
45
+
46
+ afterEach(() => {
47
+ act(() => root.unmount());
48
+ container.remove();
49
+ vi.clearAllMocks();
50
+ dom.window.close();
51
+ vi.unstubAllGlobals();
52
+ });
53
+
54
+ /*
55
+ * Mount controls in an isolated instance of the existing popover state store.
56
+ */
57
+ function render(children: ReactNode) {
58
+ act(() => root.render(<Provider store={createStore()}>{children}</Provider>));
59
+ }
60
+
61
+ it('routes select events to their owning control and acknowledges handled selections', () => {
62
+ let state: {
63
+ actions: ReturnType<typeof usePopOverActions>;
64
+ definition: ReturnType<typeof usePopOverDefinition>;
65
+ event: ReturnType<typeof usePopOverEvent>;
66
+ };
67
+ const onFirstChange = vi.fn();
68
+ const onSecondChange = vi.fn();
69
+ /*
70
+ * Observe the real bundled popover store while both select modules are mounted.
71
+ */
72
+ const Harness = () => {
73
+ state = { actions: usePopOverActions(), definition: usePopOverDefinition(), event: usePopOverEvent() };
74
+ return (
75
+ <>
76
+ <Select
77
+ name='first'
78
+ value='a'
79
+ options={[
80
+ { value: 'a', text: 'First' },
81
+ { value: 'b', text: 'Second' },
82
+ ]}
83
+ onChange={onFirstChange}
84
+ />
85
+ <Select
86
+ name='second'
87
+ options={[{ value: 'c', text: 'Other' }]}
88
+ onChange={onSecondChange}
89
+ />
90
+ </>
91
+ );
92
+ };
93
+ render(<Harness />);
94
+ act(() => container.querySelector<HTMLButtonElement>('#first-form')!.click());
95
+ expect(state!.definition?.name).toBe('PO_LIST');
96
+ const variables = state!.definition!.variables as { options: { name: string }[] };
97
+ const optionName = variables.options[0].name;
98
+ act(() => state!.actions.publishPopOverEvent({ action: 'ITEM', name: 'unrelated', value: 'b' }));
99
+ expect(onFirstChange).not.toHaveBeenCalled();
100
+ act(() => state!.actions.publishPopOverEvent({ action: 'ITEM', name: optionName, value: 'b' }));
101
+ expect(onFirstChange).toHaveBeenCalledExactlyOnceWith('b', 'first', { value: 'b', text: 'Second' });
102
+ expect(onSecondChange).not.toHaveBeenCalled();
103
+ expect(state!.event).toBeNull();
104
+ expect(state!.definition?.closing || !state!.definition).toBe(true);
105
+ });
106
+
107
+ it.each(['disabled', 'locked', 'readonly', 'removed', 'option-disabled'] as const)(
108
+ 'ignores an already-open selection after the control becomes %s',
109
+ (restriction) => {
110
+ let actions!: ReturnType<typeof usePopOverActions>;
111
+ let definition!: ReturnType<typeof usePopOverDefinition>;
112
+ let restrict!: () => void;
113
+ const onChange = vi.fn();
114
+ /* Refresh control permissions or options while its original popover is still mounted. */
115
+ const Harness = () => {
116
+ const [restricted, setRestricted] = useState(false);
117
+ restrict = () => setRestricted(true);
118
+ actions = usePopOverActions();
119
+ definition = usePopOverDefinition();
120
+ return (
121
+ <Select
122
+ name='choice'
123
+ disabled={restricted && restriction === 'disabled'}
124
+ locked={restricted && restriction === 'locked'}
125
+ editable={!(restricted && restriction === 'readonly')}
126
+ options={
127
+ restricted && restriction === 'removed'
128
+ ? []
129
+ : [{ value: 'a', text: 'First', disabled: restricted && restriction === 'option-disabled' }]
130
+ }
131
+ onChange={onChange}
132
+ />
133
+ );
134
+ };
135
+ render(<Harness />);
136
+ act(() => container.querySelector<HTMLButtonElement>('#choice-form')!.click());
137
+ const variables = definition!.variables as { options: { name: string }[] };
138
+ act(restrict);
139
+ act(() => actions.publishPopOverEvent({ action: 'ITEM', name: variables.options[0].name, value: 'a' }));
140
+ expect(onChange).not.toHaveBeenCalled();
141
+ },
142
+ );
143
+
144
+ it('updates nested standalone form fields without mutating the saved value snapshot', () => {
145
+ const initial = Object.freeze({ contact: Object.freeze({ email: 'before@example.com' }), other: Object.freeze({ value: 1 }) });
146
+ let current = initial;
147
+ const BoundInput = composeFormInput(Input);
148
+ /*
149
+ * Bind the compatibility adapter to React state and retain both snapshots for comparison.
150
+ */
151
+ const Harness = () => {
152
+ const [values, setValues] = useState(initial);
153
+ current = values;
154
+ return (
155
+ <BoundInput
156
+ name='contact.email'
157
+ formValues={values}
158
+ setFormValues={setValues}
159
+ />
160
+ );
161
+ };
162
+ render(<Harness />);
163
+ const input = container.querySelector('input')!;
164
+ act(() => {
165
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'after@example.com');
166
+ input.dispatchEvent(new Event('input', { bubbles: true }));
167
+ });
168
+ expect(current.contact.email).toBe('after@example.com');
169
+ expect(initial.contact.email).toBe('before@example.com');
170
+ expect(current.contact).not.toBe(initial.contact);
171
+ expect(current.other).toBe(initial.other);
172
+ });
173
+
174
+ it('toggles controlled password visibility without changing its value or submitting its form', () => {
175
+ const onSubmit = vi.fn();
176
+ render(
177
+ <form onSubmit={onSubmit}>
178
+ <PasswordInput
179
+ name='password'
180
+ value='secret'
181
+ onChange={() => undefined}
182
+ />
183
+ </form>,
184
+ );
185
+ const input = container.querySelector('input')!;
186
+ expect(input.type).toBe('password');
187
+ act(() => container.querySelector<HTMLButtonElement>('button')!.click());
188
+ expect(input.type).toBe('text');
189
+ expect(input.value).toBe('secret');
190
+ expect(onSubmit).not.toHaveBeenCalled();
191
+ act(() => container.querySelector<HTMLButtonElement>('button')!.click());
192
+ expect(input.type).toBe('password');
193
+ });
194
+
195
+ it('sizes textarea text with existing classes while keeping pasted HTML inert', () => {
196
+ const value = '<img src=x onerror=alert(1)>\n Indented second line';
197
+ render(
198
+ <Textarea
199
+ name='note'
200
+ value={value}
201
+ onChange={() => undefined}
202
+ />,
203
+ );
204
+ const virtualizer = container.querySelector<HTMLDivElement>('.tx_virtualizer')!;
205
+ const textarea = container.querySelector('textarea')!;
206
+ expect(textarea.value).toBe(value);
207
+ expect(virtualizer.querySelector('img')).toBeNull();
208
+ expect(virtualizer.textContent).toBe(value);
209
+ expect(virtualizer.getAttribute('aria-hidden')).toBe('true');
210
+ Object.defineProperty(virtualizer, 'offsetHeight', { configurable: true, value: 230 });
211
+ act(() => resizeCallback([], {} as ResizeObserver));
212
+ expect(textarea.style.height).toBe('230px');
213
+ expect(textarea.style.minHeight).toBe('150px');
214
+ expect(textarea.className).toBe('form_input bl of rel w_f r_sm');
215
+ Object.defineProperty(virtualizer, 'offsetHeight', { configurable: true, value: 252 });
216
+ render(
217
+ <Textarea
218
+ name='note'
219
+ value={`${value}\n`}
220
+ onChange={() => undefined}
221
+ />,
222
+ );
223
+ // Text changes must resize without waiting for a ResizeObserver notification.
224
+ expect(textarea.style.height).toBe('252px');
225
+ });
226
+
227
+ it('resets controlled time values from the owner and keeps invalid edits out of the saved date', () => {
228
+ const onChange = vi.fn();
229
+ const onBlur = vi.fn();
230
+ render(
231
+ <InputTimeFromDate
232
+ name='date'
233
+ value={new Date(2026, 0, 1, 3, 20)}
234
+ onChange={onChange}
235
+ onBlur={onBlur}
236
+ />,
237
+ );
238
+ const hours = container.querySelector<HTMLInputElement>('[name="date_hours"]')!;
239
+ const minutes = container.querySelector<HTMLInputElement>('[name="date_minutes"]')!;
240
+ expect(hours.value).toBe('3');
241
+ expect(minutes.value).toBe('20');
242
+ act(() => {
243
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(hours, '13');
244
+ hours.dispatchEvent(new Event('input', { bubbles: true }));
245
+ });
246
+ expect(onChange).not.toHaveBeenCalled();
247
+ expect(hours.classList.contains('error')).toBe(true);
248
+ act(() => hours.dispatchEvent(new Event('focusout', { bubbles: true })));
249
+ expect(hours.value).toBe('3');
250
+ expect(onBlur).toHaveBeenCalledOnce();
251
+ render(
252
+ <InputTimeFromDate
253
+ name='date'
254
+ value={new Date(2026, 0, 1, 21, 9)}
255
+ onChange={onChange}
256
+ />,
257
+ );
258
+ expect(hours.value).toBe('9');
259
+ expect(minutes.value).toBe('9');
260
+ expect(container.querySelector('[role="button"]')?.textContent).toBe('PM');
261
+ });