@jsb188/form 0.0.0-stage → 1.1.2
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 +132 -2
- package/css/form.css +2 -0
- package/package.json +40 -5
- package/src/assets.d.ts +1 -0
- package/src/libs/SchemaForm.tsx +158 -0
- package/src/libs/SchemaForm.types.ts +165 -0
- package/src/libs/defineForm.ts +11 -0
- package/src/libs/rules.ts +126 -0
- package/src/libs/useField.ts +16 -0
- package/src/libs/useSchemaForm.helpers.ts +71 -0
- package/src/libs/useSchemaForm.ts +268 -0
- package/src/libs/validation.ts +42 -0
- package/src/main.ts +40 -0
- package/src/modules/FieldLabel.tsx +28 -0
- package/src/modules/Form-Input.tsx +2 -0
- package/src/modules/Form-Line.tsx +126 -0
- package/src/modules/Form.helpers.ts +12 -0
- package/src/modules/Form.tsx +14 -0
- package/src/modules/FormItem.tsx +117 -0
- package/src/modules/FormOptions.tsx +12 -0
- package/src/modules/FormUI.tsx +2 -0
- package/src/modules/Input.tsx +16 -0
- package/src/modules/InputClick.tsx +48 -0
- package/src/modules/InputWithButton.tsx +37 -0
- package/src/modules/ListItemForm.tsx +345 -0
- package/src/modules/ListItemForm.types.ts +50 -0
- package/src/modules/PasswordInput.tsx +36 -0
- package/src/modules/PopOverInput.tsx +75 -0
- package/src/modules/SMSCodeInput.tsx +118 -0
- package/src/modules/SchemaField.tsx +104 -0
- package/src/modules/Select.tsx +163 -0
- package/src/modules/Textarea.tsx +33 -0
- package/src/modules/TimeInput.helpers.ts +73 -0
- package/src/modules/TimeInput.tsx +159 -0
- package/src/modules/TimeInput.types.ts +43 -0
- package/src/modules/UploadInput.tsx +141 -0
- package/src/modules/composeFormInput.tsx +88 -0
- package/src/types/form.ts +65 -0
- package/src/ui/ContentEditable.tsx +70 -0
- package/src/ui/Form.types.ts +138 -0
- package/src/ui/FormOptions.tsx +125 -0
- package/src/ui/FormUI.tsx +237 -0
- package/src/ui/Input.helpers.ts +7 -0
- package/src/ui/Input.tsx +199 -0
- package/src/ui/Input.types.ts +48 -0
- package/src/ui/InputButtons.tsx +41 -0
- package/src/ui/InputControls.tsx +68 -0
- package/src/ui/Label.tsx +46 -0
- package/src/ui/LineForm.tsx +34 -0
- package/src/ui/SMSCodeInput.tsx +51 -0
- package/src/ui/Select.tsx +33 -0
- package/src/ui/Textarea.tsx +96 -0
- package/src/ui/TimeInput.tsx +140 -0
- package/tests/controller.test.tsx +336 -0
- package/tests/controls.test.tsx +261 -0
- package/tests/schema-form.test.tsx +303 -0
- package/tests/settings-definitions.test.ts +129 -0
- package/tests/sms-input.test.tsx +131 -0
- package/tests/time-input.test.tsx +395 -0
- package/tests/types.ts +102 -0
- package/tests/upload-input.test.tsx +114 -0
- package/tests/validation.test.ts +65 -0
- package/tsconfig.json +13 -0
- package/vitest.config.ts +8 -0
|
@@ -0,0 +1,395 @@
|
|
|
1
|
+
import { usePopOverActions, usePopOverDefinition, usePopOverEvent } from '@jsb188/react/states';
|
|
2
|
+
import { createStore, Provider } from 'jotai';
|
|
3
|
+
import { JSDOM } from 'jsdom';
|
|
4
|
+
import { act, useState, type ReactNode } from 'react';
|
|
5
|
+
import type { Root } from 'react-dom/client';
|
|
6
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import { InputTimeFromDate } from '../src/modules/TimeInput';
|
|
8
|
+
import { checkTimeError, getTimeFormValues, resolveTimeInput } from '../src/modules/TimeInput.helpers';
|
|
9
|
+
import type { TimeFormValues, TimeInputValue } from '../src/modules/TimeInput.types';
|
|
10
|
+
|
|
11
|
+
/* Resolve clock parts with a fixed fallback date so calendar and DST assertions are deterministic. */
|
|
12
|
+
function resolve(value: TimeInputValue, values: TimeFormValues, timeZone = 'America/Toronto') {
|
|
13
|
+
return resolveTimeInput({ value, values, timeZone, fallbackDate: new Date('2026-09-20T01:02:03.456Z') });
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/* Read a successfully resolved instant without allowing an invalid branch to hide a failed assertion. */
|
|
17
|
+
function resolvedISO(result: ReturnType<typeof resolve>) {
|
|
18
|
+
expect(result.status).toBe('valid');
|
|
19
|
+
return result.status === 'valid' ? result.value.toISOString() : '';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
describe('timezone and twelve-hour math', () => {
|
|
23
|
+
it('formats midnight, noon and a different local calendar date in the requested zone', () => {
|
|
24
|
+
expect(getTimeFormValues('2026-01-02T05:00:00Z', 'America/Toronto')).toEqual({ hours: '12', minutes: '0', AMPM: 'AM' });
|
|
25
|
+
expect(getTimeFormValues('2026-01-02T17:05:00Z', 'America/Toronto')).toEqual({ hours: '12', minutes: '5', AMPM: 'PM' });
|
|
26
|
+
expect(getTimeFormValues('2026-01-02T01:20:30.456Z', 'America/Toronto')).toEqual({ hours: '8', minutes: '20', AMPM: 'PM' });
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
it('keeps afternoon edits in PM and preserves the local date, seconds and milliseconds', () => {
|
|
30
|
+
expect(resolvedISO(resolve('2026-01-02T01:20:30.456Z', { hours: '4', minutes: '20', AMPM: 'PM' }))).toBe(
|
|
31
|
+
'2026-01-01T21:20:30.456Z',
|
|
32
|
+
);
|
|
33
|
+
expect(resolvedISO(resolve('2026-01-02T01:20:30.456Z', { hours: '12', minutes: '5', AMPM: 'AM' }))).toBe(
|
|
34
|
+
'2026-01-01T05:05:30.456Z',
|
|
35
|
+
);
|
|
36
|
+
expect(resolvedISO(resolve('2026-01-02T01:20:30.456Z', { hours: '12', minutes: '5', AMPM: 'PM' }))).toBe(
|
|
37
|
+
'2026-01-01T17:05:30.456Z',
|
|
38
|
+
);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('uses the runtime local zone when none is supplied', () => {
|
|
42
|
+
expect(getTimeFormValues(new Date(2026, 0, 1, 9, 15))).toEqual({ hours: '9', minutes: '15', AMPM: 'AM' });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it.each([
|
|
46
|
+
['2026-03-08T06:30:00Z', 'America/Toronto', '2', '30'],
|
|
47
|
+
['2026-03-29T00:30:00Z', 'Europe/Berlin', '2', '30'],
|
|
48
|
+
['2026-10-03T15:00:00Z', 'Australia/Lord_Howe', '2', '15'],
|
|
49
|
+
])('rejects nonexistent DST clock time for %s in %s', (value, zone, hours, minutes) => {
|
|
50
|
+
expect(resolve(value, { hours, minutes, AMPM: 'AM' }, zone)).toMatchObject({ status: 'invalid', reason: 'gap' });
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
it.each([
|
|
54
|
+
['2026-11-01T05:30:00Z', '2026-11-01T05:15:00.000Z'],
|
|
55
|
+
['2026-11-01T06:30:00Z', '2026-11-01T06:15:00.000Z'],
|
|
56
|
+
])('preserves the original offset of repeated time %s', (value, expected) => {
|
|
57
|
+
expect(resolvedISO(resolve(value, { hours: '1', minutes: '15', AMPM: 'AM' }))).toBe(expected);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('chooses the earlier repeated instant when an empty value has no stored offset to preserve', () => {
|
|
61
|
+
const result = resolveTimeInput({
|
|
62
|
+
value: '',
|
|
63
|
+
values: { hours: '1', minutes: '15', AMPM: 'AM' },
|
|
64
|
+
timeZone: 'America/Toronto',
|
|
65
|
+
fallbackDate: new Date('2026-11-01T12:00:00Z'),
|
|
66
|
+
});
|
|
67
|
+
expect(resolvedISO(result)).toBe('2026-11-01T05:15:00.000Z');
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
it('initializes blank values on today in the requested zone without inheriting seconds', () => {
|
|
71
|
+
expect(resolvedISO(resolve('', { hours: '4', minutes: '30', AMPM: 'PM' }, 'America/Los_Angeles'))).toBe(
|
|
72
|
+
'2026-09-19T23:30:00.000Z',
|
|
73
|
+
);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('rejects invalid dates and zones without creating a fallback date', () => {
|
|
77
|
+
expect(resolve('not-a-date', { hours: '4', minutes: '30', AMPM: 'PM' })).toMatchObject({ status: 'invalid', reason: 'date' });
|
|
78
|
+
expect(resolve('2026-01-01T00:00:00Z', { hours: '4', minutes: '30', AMPM: 'PM' }, 'Not/A_Timezone')).toMatchObject({
|
|
79
|
+
status: 'invalid',
|
|
80
|
+
reason: 'zone',
|
|
81
|
+
});
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it('keeps incomplete values separate from malformed or out-of-range clock parts', () => {
|
|
85
|
+
expect(resolve('2026-01-01T00:00:00Z', { hours: '', minutes: '30', AMPM: 'PM' })).toEqual({ status: 'incomplete' });
|
|
86
|
+
expect(resolve('2026-01-01T00:00:00Z', { hours: '4', minutes: '', AMPM: 'PM' })).toEqual({ status: 'incomplete' });
|
|
87
|
+
for (const value of ['0', '13', '-1', '1.5', '001', '1e1']) expect(checkTimeError(value, 'hours')).toBe(true);
|
|
88
|
+
for (const value of ['60', '-1', '1.5', '001', '1e1']) expect(checkTimeError(value, 'minutes')).toBe(true);
|
|
89
|
+
expect(checkTimeError('00', 'minutes')).toBe(false);
|
|
90
|
+
expect(checkTimeError('12', 'hours')).toBe(false);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe('time control interactions', () => {
|
|
95
|
+
let dom: JSDOM;
|
|
96
|
+
let root: Root;
|
|
97
|
+
let container: HTMLDivElement;
|
|
98
|
+
let store: ReturnType<typeof createStore>;
|
|
99
|
+
|
|
100
|
+
beforeEach(async () => {
|
|
101
|
+
dom = new JSDOM('<!doctype html><html><body></body></html>');
|
|
102
|
+
vi.stubGlobal('window', dom.window);
|
|
103
|
+
vi.stubGlobal('document', dom.window.document);
|
|
104
|
+
vi.stubGlobal('HTMLInputElement', dom.window.HTMLInputElement);
|
|
105
|
+
vi.stubGlobal('Event', dom.window.Event);
|
|
106
|
+
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
|
|
107
|
+
const { createRoot } = await import('react-dom/client');
|
|
108
|
+
container = document.createElement('div');
|
|
109
|
+
document.body.append(container);
|
|
110
|
+
root = createRoot(container);
|
|
111
|
+
store = createStore();
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
afterEach(() => {
|
|
115
|
+
act(() => root.unmount());
|
|
116
|
+
container.remove();
|
|
117
|
+
dom.window.close();
|
|
118
|
+
vi.useRealTimers();
|
|
119
|
+
vi.unstubAllGlobals();
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
/* Mount or rerender a control without replacing its local draft state or popover store. */
|
|
123
|
+
const render = (children: ReactNode) => act(() => root.render(<Provider store={store}>{children}</Provider>));
|
|
124
|
+
|
|
125
|
+
/* Type through React's native input event integration, bypassing its value tracker as a browser edit would. */
|
|
126
|
+
const type = (name: 'hours' | 'minutes', value: string) => {
|
|
127
|
+
const input = container.querySelector<HTMLInputElement>(`[name="date_${name}"]`)!;
|
|
128
|
+
act(() => {
|
|
129
|
+
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value);
|
|
130
|
+
input.dispatchEvent(new Event('input', { bubbles: true }));
|
|
131
|
+
});
|
|
132
|
+
return input;
|
|
133
|
+
};
|
|
134
|
+
|
|
135
|
+
it('commits PM edits with the configured timezone and retains partial values until complete', () => {
|
|
136
|
+
const onChange = vi.fn();
|
|
137
|
+
render(
|
|
138
|
+
<InputTimeFromDate
|
|
139
|
+
name="date"
|
|
140
|
+
value="2026-01-01T20:30:12.123Z"
|
|
141
|
+
timeZone="America/Toronto"
|
|
142
|
+
onChange={onChange}
|
|
143
|
+
/>,
|
|
144
|
+
);
|
|
145
|
+
type('hours', '');
|
|
146
|
+
type('minutes', '10');
|
|
147
|
+
expect(onChange).not.toHaveBeenCalled();
|
|
148
|
+
type('hours', '4');
|
|
149
|
+
expect(onChange).toHaveBeenCalledOnce();
|
|
150
|
+
expect(onChange.mock.calls[0][2].toISOString()).toBe('2026-01-01T21:10:12.123Z');
|
|
151
|
+
expect(container.querySelector('[role="button"]')?.textContent).toBe('PM');
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
it('initializes an empty standalone control on today in its zone', () => {
|
|
155
|
+
vi.useFakeTimers({ toFake: ['Date'] });
|
|
156
|
+
vi.setSystemTime(new Date('2026-09-20T01:02:03.456Z'));
|
|
157
|
+
const onChange = vi.fn();
|
|
158
|
+
render(
|
|
159
|
+
<InputTimeFromDate
|
|
160
|
+
name="date"
|
|
161
|
+
value=""
|
|
162
|
+
timeZone="America/Los_Angeles"
|
|
163
|
+
onChange={onChange}
|
|
164
|
+
/>,
|
|
165
|
+
);
|
|
166
|
+
type('hours', '12');
|
|
167
|
+
expect(onChange).not.toHaveBeenCalled();
|
|
168
|
+
type('minutes', '5');
|
|
169
|
+
expect(onChange.mock.calls[0][2].toISOString()).toBe('2026-09-19T07:05:00.000Z');
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('preserves blank hours while real focus moves to minutes and completes the time', () => {
|
|
173
|
+
vi.useFakeTimers({ toFake: ['Date'] });
|
|
174
|
+
vi.setSystemTime(new Date('2026-09-20T01:02:03.456Z'));
|
|
175
|
+
const onChange = vi.fn();
|
|
176
|
+
const onBlur = vi.fn();
|
|
177
|
+
render(
|
|
178
|
+
<InputTimeFromDate
|
|
179
|
+
name="date"
|
|
180
|
+
value=""
|
|
181
|
+
timeZone="America/Los_Angeles"
|
|
182
|
+
onChange={onChange}
|
|
183
|
+
onBlur={onBlur}
|
|
184
|
+
/>,
|
|
185
|
+
);
|
|
186
|
+
const hours = container.querySelector<HTMLInputElement>('[name="date_hours"]')!;
|
|
187
|
+
const minutes = container.querySelector<HTMLInputElement>('[name="date_minutes"]')!;
|
|
188
|
+
act(() => hours.focus());
|
|
189
|
+
type('hours', '12');
|
|
190
|
+
act(() => minutes.focus());
|
|
191
|
+
expect(hours.value).toBe('12');
|
|
192
|
+
expect(onBlur).not.toHaveBeenCalled();
|
|
193
|
+
type('minutes', '5');
|
|
194
|
+
expect(onChange).toHaveBeenCalledOnce();
|
|
195
|
+
expect(onChange.mock.calls[0][2].toISOString()).toBe('2026-09-19T07:05:00.000Z');
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
it('preserves partial drafts through the period trigger and active popup before returning to minutes', () => {
|
|
199
|
+
vi.useFakeTimers({ toFake: ['Date'] });
|
|
200
|
+
vi.setSystemTime(new Date('2026-09-20T01:02:03.456Z'));
|
|
201
|
+
const onChange = vi.fn();
|
|
202
|
+
let actions: ReturnType<typeof usePopOverActions>;
|
|
203
|
+
/* Subscribe to the real bundled period events while its portal receives keyboard focus. */
|
|
204
|
+
const Harness = () => {
|
|
205
|
+
actions = usePopOverActions();
|
|
206
|
+
return (
|
|
207
|
+
<InputTimeFromDate
|
|
208
|
+
name="date"
|
|
209
|
+
value=""
|
|
210
|
+
timeZone="America/Los_Angeles"
|
|
211
|
+
onChange={onChange}
|
|
212
|
+
/>
|
|
213
|
+
);
|
|
214
|
+
};
|
|
215
|
+
render(<Harness />);
|
|
216
|
+
const hours = container.querySelector<HTMLInputElement>('[name="date_hours"]')!;
|
|
217
|
+
const minutes = container.querySelector<HTMLInputElement>('[name="date_minutes"]')!;
|
|
218
|
+
const period = container.querySelector<HTMLElement>('[role="button"]')!;
|
|
219
|
+
act(() => hours.focus());
|
|
220
|
+
type('hours', '12');
|
|
221
|
+
act(() => period.focus());
|
|
222
|
+
expect(hours.value).toBe('12');
|
|
223
|
+
act(() => period.click());
|
|
224
|
+
const popup = document.createElement('div');
|
|
225
|
+
popup.className = 'popover';
|
|
226
|
+
const option = document.createElement('button');
|
|
227
|
+
popup.append(option);
|
|
228
|
+
document.body.append(popup);
|
|
229
|
+
act(() => option.focus());
|
|
230
|
+
expect(hours.value).toBe('12');
|
|
231
|
+
act(() => actions!.publishPopOverEvent({ action: 'ITEM', value: 'PM' }));
|
|
232
|
+
expect(onChange).not.toHaveBeenCalled();
|
|
233
|
+
act(() => minutes.focus());
|
|
234
|
+
type('minutes', '5');
|
|
235
|
+
expect(onChange.mock.calls[0][2].toISOString()).toBe('2026-09-19T19:05:00.000Z');
|
|
236
|
+
popup.remove();
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it('restores incomplete drafts when focus leaves through the period trigger', () => {
|
|
240
|
+
render(
|
|
241
|
+
<InputTimeFromDate
|
|
242
|
+
name="date"
|
|
243
|
+
value="2026-01-01T20:30:00Z"
|
|
244
|
+
timeZone="America/Toronto"
|
|
245
|
+
/>,
|
|
246
|
+
);
|
|
247
|
+
const hours = container.querySelector<HTMLInputElement>('[name="date_hours"]')!;
|
|
248
|
+
const period = container.querySelector<HTMLElement>('[role="button"]')!;
|
|
249
|
+
const outside = document.createElement('button');
|
|
250
|
+
document.body.append(outside);
|
|
251
|
+
act(() => hours.focus());
|
|
252
|
+
type('hours', '');
|
|
253
|
+
act(() => period.focus());
|
|
254
|
+
expect(hours.value).toBe('');
|
|
255
|
+
act(() => outside.focus());
|
|
256
|
+
expect(hours.value).toBe('3');
|
|
257
|
+
outside.remove();
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
it('rejects gap edits and restores committed twelve-hour text on blur', () => {
|
|
261
|
+
const onChange = vi.fn();
|
|
262
|
+
render(
|
|
263
|
+
<InputTimeFromDate
|
|
264
|
+
name="date"
|
|
265
|
+
value="2026-03-08T06:30:00Z"
|
|
266
|
+
timeZone="America/Toronto"
|
|
267
|
+
onChange={onChange}
|
|
268
|
+
/>,
|
|
269
|
+
);
|
|
270
|
+
const hours = type('hours', '2');
|
|
271
|
+
expect(onChange).not.toHaveBeenCalled();
|
|
272
|
+
expect(hours.getAttribute('aria-invalid')).toBe('true');
|
|
273
|
+
act(() => hours.dispatchEvent(new Event('focusout', { bubbles: true })));
|
|
274
|
+
expect(hours.value).toBe('1');
|
|
275
|
+
expect(hours.hasAttribute('aria-invalid')).toBe(false);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
it('resets partial drafts when the value, timezone or explicit reset key changes', () => {
|
|
279
|
+
const props = { name: 'date', value: '2026-01-01T20:30:00Z', timeZone: 'America/Toronto', onChange: vi.fn() };
|
|
280
|
+
render(
|
|
281
|
+
<InputTimeFromDate
|
|
282
|
+
{...props}
|
|
283
|
+
resetKey={0}
|
|
284
|
+
/>,
|
|
285
|
+
);
|
|
286
|
+
const hours = type('hours', '');
|
|
287
|
+
render(
|
|
288
|
+
<InputTimeFromDate
|
|
289
|
+
{...props}
|
|
290
|
+
resetKey={0}
|
|
291
|
+
/>,
|
|
292
|
+
);
|
|
293
|
+
expect(hours.value).toBe('');
|
|
294
|
+
render(
|
|
295
|
+
<InputTimeFromDate
|
|
296
|
+
{...props}
|
|
297
|
+
resetKey={1}
|
|
298
|
+
/>,
|
|
299
|
+
);
|
|
300
|
+
expect(hours.value).toBe('3');
|
|
301
|
+
type('hours', '');
|
|
302
|
+
render(
|
|
303
|
+
<InputTimeFromDate
|
|
304
|
+
{...props}
|
|
305
|
+
timeZone="America/Los_Angeles"
|
|
306
|
+
resetKey={1}
|
|
307
|
+
/>,
|
|
308
|
+
);
|
|
309
|
+
expect(hours.value).toBe('12');
|
|
310
|
+
type('hours', '');
|
|
311
|
+
render(
|
|
312
|
+
<InputTimeFromDate
|
|
313
|
+
{...props}
|
|
314
|
+
value="2026-01-02T22:45:00Z"
|
|
315
|
+
resetKey={1}
|
|
316
|
+
/>,
|
|
317
|
+
);
|
|
318
|
+
expect(hours.value).toBe('5');
|
|
319
|
+
});
|
|
320
|
+
|
|
321
|
+
it.each(['locked', 'disabled'] as const)('ignores and acknowledges an already-open period event when %s', (flag) => {
|
|
322
|
+
const onChange = vi.fn();
|
|
323
|
+
let setGuard: (value: boolean) => void;
|
|
324
|
+
let state: {
|
|
325
|
+
actions: ReturnType<typeof usePopOverActions>;
|
|
326
|
+
definition: ReturnType<typeof usePopOverDefinition>;
|
|
327
|
+
event: ReturnType<typeof usePopOverEvent>;
|
|
328
|
+
};
|
|
329
|
+
/* Observe the real event store while the owner changes edit permissions. */
|
|
330
|
+
const Harness = () => {
|
|
331
|
+
const [guard, setState] = useState(false);
|
|
332
|
+
setGuard = setState;
|
|
333
|
+
state = { actions: usePopOverActions(), definition: usePopOverDefinition(), event: usePopOverEvent() };
|
|
334
|
+
return (
|
|
335
|
+
<InputTimeFromDate
|
|
336
|
+
name="date"
|
|
337
|
+
value="2026-01-01T20:30:00Z"
|
|
338
|
+
timeZone="America/Toronto"
|
|
339
|
+
onChange={onChange}
|
|
340
|
+
{...{ [flag]: guard }}
|
|
341
|
+
/>
|
|
342
|
+
);
|
|
343
|
+
};
|
|
344
|
+
render(<Harness />);
|
|
345
|
+
act(() => container.querySelector<HTMLElement>('[role="button"]')!.click());
|
|
346
|
+
expect(state!.definition).not.toBeNull();
|
|
347
|
+
act(() => {
|
|
348
|
+
setGuard!(true);
|
|
349
|
+
state!.actions.publishPopOverEvent({ action: 'ITEM', value: 'AM' });
|
|
350
|
+
});
|
|
351
|
+
expect(onChange).not.toHaveBeenCalled();
|
|
352
|
+
expect(state!.event).toBeNull();
|
|
353
|
+
expect(container.querySelector<HTMLInputElement>('input')!.disabled).toBe(true);
|
|
354
|
+
expect(state!.definition === null || state!.definition.closing).toBe(true);
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
it('isolates same-name time controls and acknowledges invalid period events without changes', () => {
|
|
358
|
+
const first = vi.fn();
|
|
359
|
+
const second = vi.fn();
|
|
360
|
+
let actions: ReturnType<typeof usePopOverActions>;
|
|
361
|
+
let event: ReturnType<typeof usePopOverEvent>;
|
|
362
|
+
/* Give both controls the same field name while retaining independently scoped popover IDs. */
|
|
363
|
+
const Harness = () => {
|
|
364
|
+
actions = usePopOverActions();
|
|
365
|
+
event = usePopOverEvent();
|
|
366
|
+
return (
|
|
367
|
+
<>
|
|
368
|
+
<InputTimeFromDate
|
|
369
|
+
name="date"
|
|
370
|
+
value="2026-01-01T20:30:00Z"
|
|
371
|
+
timeZone="America/Toronto"
|
|
372
|
+
onChange={first}
|
|
373
|
+
/>
|
|
374
|
+
<InputTimeFromDate
|
|
375
|
+
name="date"
|
|
376
|
+
value="2026-01-01T20:30:00Z"
|
|
377
|
+
timeZone="America/Toronto"
|
|
378
|
+
onChange={second}
|
|
379
|
+
/>
|
|
380
|
+
</>
|
|
381
|
+
);
|
|
382
|
+
};
|
|
383
|
+
render(<Harness />);
|
|
384
|
+
const trigger = container.querySelector<HTMLElement>('[role="button"]')!;
|
|
385
|
+
act(() => trigger.click());
|
|
386
|
+
act(() => actions!.publishPopOverEvent({ action: 'ITEM', value: 'AM' }));
|
|
387
|
+
expect(first.mock.calls[0][2].toISOString()).toBe('2026-01-01T08:30:00.000Z');
|
|
388
|
+
expect(second).not.toHaveBeenCalled();
|
|
389
|
+
expect(event!).toBeNull();
|
|
390
|
+
act(() => trigger.click());
|
|
391
|
+
act(() => actions!.publishPopOverEvent({ action: 'ITEM', value: 'not-a-period' }));
|
|
392
|
+
expect(first).toHaveBeenCalledOnce();
|
|
393
|
+
expect(event!).toBeNull();
|
|
394
|
+
});
|
|
395
|
+
});
|
package/tests/types.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { defineForm } from '../src/libs/defineForm';
|
|
3
|
+
import { useSchemaForm } from '../src/libs/useSchemaForm';
|
|
4
|
+
|
|
5
|
+
const profile = defineForm({
|
|
6
|
+
schema: z.object({
|
|
7
|
+
name: z.string(),
|
|
8
|
+
contact: z.object({ email: z.string(), label: z.string() }),
|
|
9
|
+
age: z.string().transform(Number),
|
|
10
|
+
createdAt: z.date(),
|
|
11
|
+
contacts: z.array(z.object({ email: z.string(), label: z.string() })),
|
|
12
|
+
}),
|
|
13
|
+
defaults: { name: '', contact: { email: '', label: '' }, age: '0', createdAt: new Date(), contacts: [] },
|
|
14
|
+
fields: {
|
|
15
|
+
name: {
|
|
16
|
+
kind: 'input',
|
|
17
|
+
visibleWhen: ({ values }) => {
|
|
18
|
+
values.age satisfies string;
|
|
19
|
+
// @ts-expect-error Presentation conditions read editable input values, not transformed output.
|
|
20
|
+
values.age satisfies number;
|
|
21
|
+
return !!values.name;
|
|
22
|
+
},
|
|
23
|
+
},
|
|
24
|
+
'contact.email': { kind: 'input' },
|
|
25
|
+
age: { kind: 'input' },
|
|
26
|
+
'contacts.0.email': { kind: 'input' },
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
defineForm({
|
|
31
|
+
...profile,
|
|
32
|
+
fields: {
|
|
33
|
+
name: { kind: 'input' },
|
|
34
|
+
// @ts-expect-error Unknown field names remain errors even beside a valid field.
|
|
35
|
+
missing: { kind: 'input' },
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
defineForm({
|
|
40
|
+
...profile,
|
|
41
|
+
layout: [
|
|
42
|
+
'name',
|
|
43
|
+
// @ts-expect-error Layout references must point to paths in the value schema.
|
|
44
|
+
'contact.missing',
|
|
45
|
+
],
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
const address = defineForm({
|
|
49
|
+
schema: z.object({ address: z.object({ city: z.string(), country: z.string() }) }),
|
|
50
|
+
defaults: { address: { city: '', country: '' } },
|
|
51
|
+
fields: {
|
|
52
|
+
'address.city': { kind: 'input', label: 'City' },
|
|
53
|
+
'address.country': {
|
|
54
|
+
kind: 'input',
|
|
55
|
+
resolve: ({ values }) => ({ placeholder: values.address.country }),
|
|
56
|
+
},
|
|
57
|
+
},
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
const organization = defineForm({
|
|
61
|
+
schema: address.schema.extend({ name: z.string() }),
|
|
62
|
+
defaults: { ...address.defaults, name: '' },
|
|
63
|
+
fields: {
|
|
64
|
+
...address.fields,
|
|
65
|
+
name: { kind: 'input', visibleWhen: ({ values }) => !!values.address.city },
|
|
66
|
+
},
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
organization.fields['address.city'].kind satisfies 'input';
|
|
70
|
+
|
|
71
|
+
/* Check the public editing and submission contracts at compile time; this fixture is never executed. */
|
|
72
|
+
export function assertFormTypes() {
|
|
73
|
+
const form = useSchemaForm(profile, {
|
|
74
|
+
initialValues: { contact: { email: 'member@example.com' }, createdAt: new Date() },
|
|
75
|
+
onSubmit: (values) => {
|
|
76
|
+
values.age satisfies number;
|
|
77
|
+
// @ts-expect-error Schema transforms apply to submitted output, not editable input.
|
|
78
|
+
values.age satisfies string;
|
|
79
|
+
},
|
|
80
|
+
});
|
|
81
|
+
form.values.age satisfies string;
|
|
82
|
+
form.getValues().age satisfies string;
|
|
83
|
+
form.setFieldValue('contact.email', 'member@example.com');
|
|
84
|
+
form.setFieldValue('contacts.0.email', 'member@example.com');
|
|
85
|
+
form.setFieldValue('contacts.0', { email: 'member@example.com', label: 'Work' });
|
|
86
|
+
form.setFieldValue('createdAt', new Date());
|
|
87
|
+
// @ts-expect-error Unknown paths are rejected by the controller.
|
|
88
|
+
form.setFieldValue('contact.missing', 'no');
|
|
89
|
+
// @ts-expect-error Nested field values retain their declared type.
|
|
90
|
+
form.setFieldValue('contact.email', 42);
|
|
91
|
+
// @ts-expect-error The form edits the input string even though submission yields a number.
|
|
92
|
+
form.setFieldValue('age', 42);
|
|
93
|
+
|
|
94
|
+
useSchemaForm(profile, {
|
|
95
|
+
// @ts-expect-error Arrays replace defaults, so each supplied item must be complete.
|
|
96
|
+
initialValues: { contacts: [{ email: 'member@example.com' }] },
|
|
97
|
+
});
|
|
98
|
+
useSchemaForm(profile, {
|
|
99
|
+
// @ts-expect-error Date values remain Dates instead of being made deeply partial objects.
|
|
100
|
+
initialValues: { createdAt: {} },
|
|
101
|
+
});
|
|
102
|
+
}
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { JSDOM } from 'jsdom';
|
|
2
|
+
import { act, createRef } from 'react';
|
|
3
|
+
import type { Root } from 'react-dom/client';
|
|
4
|
+
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
|
|
5
|
+
import { UploadInput, type UploadInputRef } from '../src/modules/UploadInput';
|
|
6
|
+
|
|
7
|
+
let root: Root;
|
|
8
|
+
let dom: JSDOM;
|
|
9
|
+
let container: HTMLDivElement;
|
|
10
|
+
|
|
11
|
+
beforeEach(async () => {
|
|
12
|
+
dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'https://example.test' });
|
|
13
|
+
vi.stubGlobal('window', dom.window);
|
|
14
|
+
vi.stubGlobal('document', dom.window.document);
|
|
15
|
+
vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
|
|
16
|
+
const { createRoot } = await import('react-dom/client');
|
|
17
|
+
container = document.createElement('div');
|
|
18
|
+
document.body.append(container);
|
|
19
|
+
root = createRoot(container);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
afterEach(() => {
|
|
23
|
+
act(() => root.unmount());
|
|
24
|
+
dom.window.close();
|
|
25
|
+
vi.unstubAllGlobals();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
/*
|
|
29
|
+
* Select a file through the native change event without a storage provider.
|
|
30
|
+
*/
|
|
31
|
+
function pickFile(file: File) {
|
|
32
|
+
const input = container.querySelector('input')!;
|
|
33
|
+
Object.defineProperty(input, 'files', { configurable: true, value: [file] });
|
|
34
|
+
act(() => input.dispatchEvent(new dom.window.Event('change', { bubbles: true })));
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
it('delegates uploads and keeps the picked file available for retries when requested', async () => {
|
|
38
|
+
const ref = createRef<UploadInputRef>();
|
|
39
|
+
const onChangeFile = vi.fn();
|
|
40
|
+
const onUpload = vi.fn().mockResolvedValueOnce(null).mockResolvedValueOnce({ fileUri: 'uploaded.csv' });
|
|
41
|
+
act(() =>
|
|
42
|
+
root.render(
|
|
43
|
+
<UploadInput
|
|
44
|
+
ref={ref}
|
|
45
|
+
onChangeFile={onChangeFile}
|
|
46
|
+
onUpload={onUpload}
|
|
47
|
+
/>,
|
|
48
|
+
),
|
|
49
|
+
);
|
|
50
|
+
const file = new dom.window.File(['name\nAlice'], 'people.csv', { type: 'text/csv' });
|
|
51
|
+
pickFile(file);
|
|
52
|
+
expect(onChangeFile).toHaveBeenLastCalledWith(expect.objectContaining({ file, name: 'people.csv', contentType: 'text/csv' }));
|
|
53
|
+
expect(await ref.current!.startUpload({ doNotClearInput: true })).toBe(false);
|
|
54
|
+
expect(await ref.current!.upload({ doNotClearInput: true })).toBe(true);
|
|
55
|
+
expect(onUpload.mock.calls).toEqual([[file], [file]]);
|
|
56
|
+
expect(onChangeFile).toHaveBeenCalledTimes(1);
|
|
57
|
+
act(() => ref.current!.clearPickedFile());
|
|
58
|
+
expect(onChangeFile).toHaveBeenLastCalledWith(null);
|
|
59
|
+
expect(await ref.current!.startUpload()).toBe(false);
|
|
60
|
+
expect(onUpload).toHaveBeenCalledTimes(2);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('clears selection before an ordinary upload and uses the latest callback', async () => {
|
|
64
|
+
const ref = createRef<UploadInputRef>();
|
|
65
|
+
const firstUpload = vi.fn();
|
|
66
|
+
const onChangeFile = vi.fn();
|
|
67
|
+
act(() =>
|
|
68
|
+
root.render(
|
|
69
|
+
<UploadInput
|
|
70
|
+
ref={ref}
|
|
71
|
+
onChangeFile={onChangeFile}
|
|
72
|
+
onUpload={firstUpload}
|
|
73
|
+
/>,
|
|
74
|
+
),
|
|
75
|
+
);
|
|
76
|
+
const file = new dom.window.File(['data'], 'attachment.txt');
|
|
77
|
+
pickFile(file);
|
|
78
|
+
const onUpload = vi.fn(async () => {
|
|
79
|
+
expect(onChangeFile).toHaveBeenLastCalledWith(null);
|
|
80
|
+
return true;
|
|
81
|
+
});
|
|
82
|
+
act(() =>
|
|
83
|
+
root.render(
|
|
84
|
+
<UploadInput
|
|
85
|
+
ref={ref}
|
|
86
|
+
onChangeFile={onChangeFile}
|
|
87
|
+
onUpload={onUpload}
|
|
88
|
+
/>,
|
|
89
|
+
),
|
|
90
|
+
);
|
|
91
|
+
expect(await ref.current!.startUpload()).toBe(true);
|
|
92
|
+
expect(onUpload).toHaveBeenCalledWith(file);
|
|
93
|
+
expect(firstUpload).not.toHaveBeenCalled();
|
|
94
|
+
expect(await ref.current!.startUpload()).toBe(false);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
it('uploads on pick when requested and allows selecting the same file again', async () => {
|
|
98
|
+
const onUpload = vi.fn().mockResolvedValue(true);
|
|
99
|
+
act(() =>
|
|
100
|
+
root.render(
|
|
101
|
+
<UploadInput
|
|
102
|
+
initiateUploadOnPick
|
|
103
|
+
onUpload={onUpload}
|
|
104
|
+
/>,
|
|
105
|
+
),
|
|
106
|
+
);
|
|
107
|
+
const file = new dom.window.File(['data'], 'attachment.txt');
|
|
108
|
+
pickFile(file);
|
|
109
|
+
await act(async () => {});
|
|
110
|
+
expect(container.querySelector('input')!.value).toBe('');
|
|
111
|
+
pickFile(file);
|
|
112
|
+
await act(async () => {});
|
|
113
|
+
expect(onUpload.mock.calls).toEqual([[file], [file]]);
|
|
114
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { rules } from '../src/libs/rules';
|
|
4
|
+
import { getFieldValue, initialFormValues, setFieldValue, valuesEqual } from '../src/libs/useSchemaForm.helpers';
|
|
5
|
+
import { submissionResult, validationErrors } from '../src/libs/validation';
|
|
6
|
+
|
|
7
|
+
describe('shared form validation and snapshots', () => {
|
|
8
|
+
it('does not treat aborted or partially failed saves as a saved baseline', () => {
|
|
9
|
+
expect(submissionResult({ aborted: true }).status).toBe('continue');
|
|
10
|
+
expect(submissionResult([{ saved: true }, { aborted: true }]).status).toBe('continue');
|
|
11
|
+
expect(submissionResult([{ saved: true }, { error: { message: 'Denied' } }])).toEqual({
|
|
12
|
+
status: 'error',
|
|
13
|
+
error: { message: 'Denied' },
|
|
14
|
+
});
|
|
15
|
+
expect(submissionResult([{ aborted: true }, { errors: [{ message: 'Denied' }] }]).status).toBe('error');
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
it('keeps empty optional text inputs distinct from invalid nonempty inputs', () => {
|
|
19
|
+
expect(rules.phone({ optional: true }).safeParse('').success).toBe(true);
|
|
20
|
+
expect(rules.phone().safeParse('').success).toBe(false);
|
|
21
|
+
expect(rules.phone({ optional: true }).safeParse('not a phone').success).toBe(false);
|
|
22
|
+
expect(rules.email().safeParse('person@example.com').success).toBe(true);
|
|
23
|
+
expect(rules.url({ optional: true }).safeParse('').success).toBe(true);
|
|
24
|
+
expect(rules.url().safeParse('javascript:alert(1)').success).toBe(false);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it('does not turn an empty required number into zero', () => {
|
|
28
|
+
expect(rules.number().safeParse('').success).toBe(false);
|
|
29
|
+
expect(rules.number().parse('0')).toBe(0);
|
|
30
|
+
expect(rules.number({ optional: true }).parse('')).toBeUndefined();
|
|
31
|
+
expect(rules.number({ integer: true }).safeParse('1.5').success).toBe(false);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('rejects impossible calendar dates', () => {
|
|
35
|
+
expect(rules.date().safeParse('2026-02-30').success).toBe(false);
|
|
36
|
+
expect(rules.date().safeParse('2024-02-29').success).toBe(true);
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it('retains all issues with their complete nested paths', () => {
|
|
40
|
+
const result = z
|
|
41
|
+
.object({ address: z.object({ city: z.string().min(1), zip: z.string().min(1) }) })
|
|
42
|
+
.safeParse({ address: { city: '', zip: '' } });
|
|
43
|
+
if (result.success) throw new Error('Expected invalid input');
|
|
44
|
+
expect(Object.keys(validationErrors(result.error.issues))).toEqual(['address.city', 'address.zip']);
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('updates arrays without mutating previous values and blocks unsafe paths', () => {
|
|
48
|
+
const previous = { contacts: [{ name: 'Before' }], stable: {} };
|
|
49
|
+
const next = setFieldValue(previous, 'contacts.0.name', 'After');
|
|
50
|
+
expect(previous.contacts[0].name).toBe('Before');
|
|
51
|
+
expect(next.contacts[0].name).toBe('After');
|
|
52
|
+
expect(next.stable).toBe(previous.stable);
|
|
53
|
+
expect(setFieldValue(previous, '__proto__.polluted', true)).toBe(previous);
|
|
54
|
+
expect(getFieldValue({}, '__proto__.polluted')).toBeUndefined();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('isolates merged default dates and treats changed types as dirty', () => {
|
|
58
|
+
const defaults = { address: { city: '', country: 'CA' }, date: new Date('2026-01-01') };
|
|
59
|
+
const values = initialFormValues(defaults, { address: { city: 'Toronto', country: 'CA' } });
|
|
60
|
+
values.date.setUTCFullYear(2027);
|
|
61
|
+
expect(defaults.date.getUTCFullYear()).toBe(2026);
|
|
62
|
+
expect(valuesEqual({ count: '1' }, { count: 1 })).toBe(false);
|
|
63
|
+
expect(valuesEqual(new Date('2026-01-01'), {})).toBe(false);
|
|
64
|
+
});
|
|
65
|
+
});
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
{
|
|
2
|
+
"compilerOptions": {
|
|
3
|
+
"target": "ESNext",
|
|
4
|
+
"module": "ESNext",
|
|
5
|
+
"moduleResolution": "Bundler",
|
|
6
|
+
"allowImportingTsExtensions": true,
|
|
7
|
+
"jsx": "react-jsx",
|
|
8
|
+
"noEmit": true,
|
|
9
|
+
"strict": true,
|
|
10
|
+
"esModuleInterop": true
|
|
11
|
+
},
|
|
12
|
+
"include": ["src/**/*", "tests/types.ts"]
|
|
13
|
+
}
|