@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,303 @@
1
+ import i18n, { i18nTranslations } from '@jsb188/app/i18n/index.ts';
2
+ import { JSDOM } from 'jsdom';
3
+ import { act } from 'react';
4
+ import type { Root } from 'react-dom/client';
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
6
+ import { z } from 'zod';
7
+ import { defineForm } from '../src/libs/defineForm';
8
+ import SchemaForm from '../src/libs/SchemaForm';
9
+ import type { FormController, SubmitResult } from '../src/libs/SchemaForm.types';
10
+ import { useSchemaForm } from '../src/libs/useSchemaForm';
11
+
12
+ let dom: JSDOM;
13
+ let root: Root;
14
+ let container: HTMLDivElement;
15
+ let nativeSubmit: ReturnType<typeof vi.fn>;
16
+
17
+ beforeEach(async () => {
18
+ dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'https://example.com/auth/signin' });
19
+ vi.stubGlobal('window', dom.window);
20
+ vi.stubGlobal('document', dom.window.document);
21
+ vi.stubGlobal('HTMLInputElement', dom.window.HTMLInputElement);
22
+ vi.stubGlobal('HTMLFormElement', dom.window.HTMLFormElement);
23
+ vi.stubGlobal('Event', dom.window.Event);
24
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
25
+ const { createRoot } = await import('react-dom/client');
26
+ container = document.createElement('div');
27
+ document.body.append(container);
28
+ root = createRoot(container);
29
+ nativeSubmit = vi.fn();
30
+ vi.spyOn(dom.window.HTMLFormElement.prototype, 'submit').mockImplementation(nativeSubmit);
31
+ i18n.extend(i18nTranslations);
32
+ });
33
+
34
+ afterEach(() => {
35
+ act(() => root.unmount());
36
+ container.remove();
37
+ dom.window.close();
38
+ vi.restoreAllMocks();
39
+ vi.unstubAllGlobals();
40
+ });
41
+
42
+ /* Define the same identifier/password shape and conditional password presentation used by sign-in. */
43
+ function signInDefinition() {
44
+ return defineForm({
45
+ schema: z.object({ identifier: z.string().min(1, 'Enter an identifier'), password: z.string() }),
46
+ defaults: { identifier: '', password: '' },
47
+ fields: {
48
+ identifier: { kind: 'input', label: 'Identifier', suppressHydrationWarning: true },
49
+ password: {
50
+ kind: 'password',
51
+ label: 'Password',
52
+ visibleWhen: ({ context }) => !context?.hidePassword,
53
+ },
54
+ },
55
+ });
56
+ }
57
+
58
+ /* Deliver a browser input event without React's controlled-input value tracker swallowing the change. */
59
+ function typeInto(input: HTMLInputElement, value: string) {
60
+ Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value')!.set!.call(input, value);
61
+ input.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
62
+ }
63
+
64
+ describe('schema form browser submission and presentation', () => {
65
+ it('clears an incomplete time draft when resetting to the same saved date', () => {
66
+ const definition = defineForm({
67
+ schema: z.object({ date: z.date() }),
68
+ defaults: { date: new Date('2026-01-01T17:00:00Z') },
69
+ fields: { date: { kind: 'time', timeZone: 'UTC' } },
70
+ });
71
+ let form!: FormController<{ date: Date }>;
72
+ /* Expose explicit controller reset while rendering its real time field. */
73
+ const Harness = () => {
74
+ form = useSchemaForm(definition);
75
+ return <SchemaForm form={form} />;
76
+ };
77
+ act(() => root.render(<Harness />));
78
+ const hours = container.querySelector<HTMLInputElement>('[name="date_hours"]')!;
79
+ expect(hours.value).toBe('5');
80
+ act(() => typeInto(hours, ''));
81
+ expect(hours.value).toBe('');
82
+ expect(form.isDirty).toBe(false);
83
+ act(() => form.reset());
84
+ expect(hours.value).toBe('5');
85
+ });
86
+
87
+ it('allows a reset form to submit while its previous request is still finishing', async () => {
88
+ const pending: ((value: SubmitResult<{ name: string }>) => void)[] = [];
89
+ const onSubmit = vi.fn(() => new Promise<SubmitResult<{ name: string }>>((resolve) => pending.push(resolve)));
90
+ const definition = defineForm({
91
+ schema: z.object({ name: z.string() }),
92
+ defaults: { name: 'First' },
93
+ fields: { name: { kind: 'input' } },
94
+ });
95
+ let form!: FormController<{ name: string }>;
96
+ /* Keep the renderer mounted across a deliberate controller reset. */
97
+ const Harness = () => {
98
+ form = useSchemaForm(definition, { onSubmit });
99
+ return <SchemaForm form={form} />;
100
+ };
101
+ act(() => root.render(<Harness />));
102
+ await act(async () => container.querySelector<HTMLButtonElement>('button')!.click());
103
+ expect(onSubmit).toHaveBeenCalledOnce();
104
+ act(() => form.reset({ name: 'Second' }));
105
+ await act(async () => container.querySelector<HTMLButtonElement>('button')!.click());
106
+ expect(onSubmit).toHaveBeenCalledTimes(2);
107
+ await act(async () => pending[0]({ status: 'success' }));
108
+ expect(form.isSubmitting).toBe(true);
109
+ expect(form.values.name).toBe('Second');
110
+ await act(async () => pending[1]({ status: 'success' }));
111
+ expect(form.isSubmitting).toBe(false);
112
+ expect(form.isDirty).toBe(false);
113
+ });
114
+
115
+ it('preserves child, field, footer, and submit-button order while toggling password visibility', async () => {
116
+ const definition = signInDefinition();
117
+ const onSubmit = vi.fn(() => ({ status: 'continue' as const }));
118
+ /* Update only discovery context without remounting the form or discarding the entered identifier. */
119
+ const render = (hidePassword: boolean) =>
120
+ act(() =>
121
+ root.render(
122
+ <SchemaForm
123
+ definition={definition}
124
+ context={{ hidePassword }}
125
+ onSubmit={onSubmit}
126
+ className="py_df"
127
+ FooterComponent={<p data-testid="footer">Footer</p>}
128
+ >
129
+ <p data-testid="message">Existing error message</p>
130
+ </SchemaForm>,
131
+ ),
132
+ );
133
+ render(true);
134
+ const identifier = container.querySelector<HTMLInputElement>('input[name="identifier"]')!;
135
+ expect(container.querySelector('input[name="password"]')).toBeNull();
136
+ await act(async () => typeInto(identifier, 'member@example.com'));
137
+ render(false);
138
+ const password = container.querySelector<HTMLInputElement>('input[name="password"]')!;
139
+ const form = container.querySelector('form')!;
140
+ const message = form.querySelector('[data-testid="message"]')!;
141
+ const footer = form.querySelector('[data-testid="footer"]')!;
142
+ const submitWrapper = form.querySelector('.pt_df.fs.z2')!;
143
+ const follows = dom.window.Node.DOCUMENT_POSITION_FOLLOWING;
144
+
145
+ expect(form.className).toBe('schema_form py_df');
146
+ expect(identifier.value).toBe('member@example.com');
147
+ expect(message.compareDocumentPosition(identifier) & follows).toBeTruthy();
148
+ expect(identifier.compareDocumentPosition(password) & follows).toBeTruthy();
149
+ expect(password.compareDocumentPosition(footer) & follows).toBeTruthy();
150
+ expect(footer.compareDocumentPosition(submitWrapper) & follows).toBeTruthy();
151
+ expect(submitWrapper.querySelector('button')?.classList.contains('shadow')).toBe(true);
152
+
153
+ await act(async () => typeInto(password, 'ExistingPassword1!'));
154
+ const passwordToggle = Array.from(form.querySelectorAll('button')).find((button) =>
155
+ button.textContent?.includes(i18n.t('account.show_password')),
156
+ )!;
157
+ act(() => passwordToggle.click());
158
+ expect(password.type).toBe('text');
159
+ expect(password.value).toBe('ExistingPassword1!');
160
+ expect(onSubmit).not.toHaveBeenCalled();
161
+ expect(nativeSubmit).not.toHaveBeenCalled();
162
+ });
163
+
164
+ it('validates Enter submissions and keeps discovery and rejected requests from posting natively', async () => {
165
+ const onError = vi.fn();
166
+ const onSubmit = vi
167
+ .fn()
168
+ .mockReturnValueOnce({ status: 'continue' })
169
+ .mockReturnValueOnce({ status: 'error', error: { message: 'Server rejected' } });
170
+ act(() =>
171
+ root.render(
172
+ <SchemaForm
173
+ definition={signInDefinition()}
174
+ actionUrl="/auth/signin"
175
+ onSubmit={onSubmit}
176
+ onError={onError}
177
+ />,
178
+ ),
179
+ );
180
+ const form = container.querySelector('form')!;
181
+
182
+ await act(async () => {
183
+ form.dispatchEvent(new dom.window.Event('submit', { bubbles: true, cancelable: true }));
184
+ });
185
+
186
+ expect(onSubmit).not.toHaveBeenCalled();
187
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'Enter an identifier', path: 'identifier' }));
188
+ expect(nativeSubmit).not.toHaveBeenCalled();
189
+ await act(async () => typeInto(form.querySelector<HTMLInputElement>('input[name="identifier"]')!, 'member@example.com'));
190
+ await act(async () => {
191
+ form.dispatchEvent(new dom.window.Event('submit', { bubbles: true, cancelable: true }));
192
+ });
193
+ expect(onSubmit).toHaveBeenCalledTimes(1);
194
+ expect(nativeSubmit).not.toHaveBeenCalled();
195
+ await act(async () => {
196
+ form.querySelector<HTMLButtonElement>('.pt_df.fs.z2 button')!.click();
197
+ });
198
+ expect(onSubmit).toHaveBeenCalledTimes(2);
199
+ expect(onError).toHaveBeenLastCalledWith({ message: 'Server rejected' });
200
+ expect(nativeSubmit).not.toHaveBeenCalled();
201
+ });
202
+
203
+ it('posts enabled credential fields and hidden metadata exactly once after async native authorization', async () => {
204
+ let resolve!: (result: SubmitResult<z.input<ReturnType<typeof signInDefinition>['schema']>>) => void;
205
+ const authorization = new Promise<SubmitResult<z.input<ReturnType<typeof signInDefinition>['schema']>>>((resolvePromise) => {
206
+ resolve = resolvePromise;
207
+ });
208
+ const onSubmit = vi.fn(() => authorization);
209
+ act(() =>
210
+ root.render(
211
+ <SchemaForm
212
+ definition={signInDefinition()}
213
+ initialValues={{ identifier: 'member@example.com', password: 'ExistingPassword1!' }}
214
+ actionUrl="/auth/signin?returnTo=%2Fapp"
215
+ method="post"
216
+ onSubmit={onSubmit}
217
+ >
218
+ <input
219
+ type="hidden"
220
+ name="managedSessionVersion"
221
+ value="1"
222
+ />
223
+ </SchemaForm>,
224
+ ),
225
+ );
226
+ const form = container.querySelector('form')!;
227
+ const submitButton = form.querySelector<HTMLButtonElement>('.pt_df.fs.z2 button')!;
228
+ act(() => {
229
+ submitButton.click();
230
+ form.dispatchEvent(new dom.window.Event('submit', { bubbles: true, cancelable: true }));
231
+ });
232
+ await act(async () => {});
233
+
234
+ expect(onSubmit).toHaveBeenCalledTimes(1);
235
+ expect(nativeSubmit).not.toHaveBeenCalled();
236
+ expect(form.querySelector<HTMLInputElement>('input[name="identifier"]')!.disabled).toBe(false);
237
+ expect(form.querySelector<HTMLInputElement>('input[name="password"]')!.disabled).toBe(false);
238
+ await act(async () => {
239
+ resolve({ status: 'native' });
240
+ await authorization;
241
+ });
242
+
243
+ expect(nativeSubmit).toHaveBeenCalledTimes(1);
244
+ expect(form.method).toBe('post');
245
+ expect(form.getAttribute('action')).toBe('/auth/signin?returnTo=%2Fapp');
246
+ expect(Object.fromEntries(new dom.window.FormData(form))).toEqual({
247
+ identifier: 'member@example.com',
248
+ password: 'ExistingPassword1!',
249
+ managedSessionVersion: '1',
250
+ });
251
+ });
252
+ it('retains the existing loading shadow and row label association', () => {
253
+ const definition = defineForm({
254
+ schema: z.object({ firstName: z.string(), lastName: z.string() }),
255
+ defaults: { firstName: 'First', lastName: 'Last' },
256
+ fields: { firstName: { kind: 'input' }, lastName: { kind: 'input' } },
257
+ layout: [{ kind: 'row', label: 'Name', fields: ['firstName', 'lastName'] }],
258
+ });
259
+ act(() =>
260
+ root.render(
261
+ <SchemaForm
262
+ definition={definition}
263
+ busy
264
+ />,
265
+ ),
266
+ );
267
+ const button = container.querySelector<HTMLButtonElement>('.pt_df.fs.z2 button')!;
268
+ const input = container.querySelector<HTMLInputElement>('input[name="firstName"]')!;
269
+
270
+ expect(button.classList.contains('loading')).toBe(true);
271
+ expect(button.classList.contains('shadow')).toBe(true);
272
+ expect(container.querySelector('label')!.htmlFor).toBe(input.id);
273
+ });
274
+
275
+ it('keeps credential actions clickable on readonly fields while respecting whole-form restrictions', () => {
276
+ const onClickButton = vi.fn();
277
+ const definition = defineForm({
278
+ schema: z.object({ email: z.string() }),
279
+ defaults: { email: 'member@example.com' },
280
+ fields: {
281
+ email: { kind: 'action', disabled: true, buttonText: 'Change', onClickButton },
282
+ },
283
+ });
284
+ act(() =>
285
+ root.render(
286
+ <SchemaForm
287
+ definition={definition}
288
+ notAllowed
289
+ />,
290
+ ),
291
+ );
292
+ expect(container.querySelector('form')!.classList.contains('form_not_allowed')).toBe(true);
293
+ expect(container.querySelector('input')!.disabled).toBe(true);
294
+ act(() => container.querySelector<HTMLDivElement>('.form_el_hv')!.click());
295
+ expect(onClickButton).not.toHaveBeenCalled();
296
+
297
+ act(() => root.render(<SchemaForm definition={definition} />));
298
+ expect(container.querySelector('input')!.disabled).toBe(true);
299
+ act(() => container.querySelector<HTMLDivElement>('.form_el_hv')!.click());
300
+ expect(onClickButton).toHaveBeenCalledTimes(1);
301
+ expect(nativeSubmit).not.toHaveBeenCalled();
302
+ });
303
+ });
@@ -0,0 +1,129 @@
1
+ import type { AccountData } from '@jsb188/app/types/auth.d.ts';
2
+ import type { OrganizationGQL } from '@jsb188/mday/types/organization.d.ts';
3
+ import i18n, { i18nTranslations } from '@jsb188/app/i18n/index.ts';
4
+ import { makeEditAccountSchema } from '@jsb188/auth-web/schemas';
5
+ import { addressFormValues, makeAddressSchema } from '@jsb188/auth-web/schemas/address';
6
+ import { makeEditOrganizationSchema } from '@jsb188/mday-web/schemas/organization';
7
+ import { beforeAll, describe, expect, it, vi } from 'vitest';
8
+
9
+ /* Initialize the same translations used by the application for schema labels and errors. */
10
+ beforeAll(() => {
11
+ i18n.extend(Object.fromEntries(Object.entries(i18nTranslations).map(([namespace, translations]) => [namespace, translations.en])));
12
+ });
13
+
14
+ /* Build a complete saved address while retaining optional second-line behavior. */
15
+ function completeAddress() {
16
+ return addressFormValues({ line1: '1 Main St', postalCode: 'A1A 1A1', city: 'Toronto', state: 'ON', country: 'CA' });
17
+ }
18
+
19
+ /* Supply the saved account data used to test read-only verification controls. */
20
+ function savedAccount(): AccountData {
21
+ return {
22
+ id: 'account',
23
+ deleted: false,
24
+ plus: null,
25
+ profile: { id: 'profile', firstName: 'Ada', lastName: 'Lovelace', photoId: '', photoUri: '' },
26
+ settings: { language: 'en', theme: null, lightMode: 'SYSTEM', timeZone: null },
27
+ email: { id: 'email', address: 'ada@example.com', verified: true },
28
+ phone: { id: 'phone', number: '14165550123', verified: true },
29
+ };
30
+ }
31
+
32
+ describe('migrated settings definitions', () => {
33
+ it('accepts an empty optional address and a country-only selection', () => {
34
+ const definition = makeAddressSchema(null);
35
+ expect(definition.schema.safeParse(definition.defaults).success).toBe(true);
36
+ expect(definition.schema.safeParse({ address: addressFormValues({ country: 'CA' }) }).success).toBe(true);
37
+ });
38
+
39
+ it('reports missing partial-address fields by nested path and accepts a complete address without line two', () => {
40
+ const definition = makeAddressSchema(null);
41
+ const result = definition.schema.safeParse({ address: addressFormValues({ line1: '1 Main St' }) });
42
+ expect(result.success).toBe(false);
43
+ if (!result.success) {
44
+ expect(result.error.issues.map((issue) => issue.path.join('.'))).toEqual([
45
+ 'address.postalCode',
46
+ 'address.city',
47
+ 'address.state',
48
+ 'address.country',
49
+ ]);
50
+ expect(result.error.issues[0].message).toBe(i18n.t('error.msg_value_required', { value: i18n.t('c.postalCode') }));
51
+ }
52
+ expect(definition.schema.safeParse({ address: completeAddress() }).success).toBe(true);
53
+ });
54
+
55
+ it('preserves the grouped country popover and resolves selection from the current draft', () => {
56
+ const definition = makeAddressSchema(null, 'w_350');
57
+ const scope = { values: { address: completeAddress() }, context: undefined };
58
+ const popover = definition.fields['address.country'].resolve(scope).popOverProps;
59
+ expect(popover.iface.variables.designClassName).toBe('w_350');
60
+ expect(popover.iface.variables.options.slice(0, 4).map((option) => ('value' in option ? option.value : option.__type))).toEqual([
61
+ 'US',
62
+ 'MX',
63
+ 'CA',
64
+ 'BREAK',
65
+ ]);
66
+ expect(popover.iface.variables.initialState).toEqual({ 'address.country': 'CA' });
67
+ expect(popover.iface.variables.options[2]).toMatchObject({ value: 'CA', selected: true });
68
+ const countryItems = popover.iface.variables.options.filter((option) => option.__type === 'LIST_ITEM');
69
+ expect(new Set(countryItems.map((option) => option.id)).size).toBe(countryItems.length);
70
+ expect(definition.defaults.address.country).toBe('');
71
+ });
72
+
73
+ it('keeps verification actions explicit and resolves current account display values without altering editable defaults', () => {
74
+ const account = savedAccount();
75
+ const openModal = vi.fn();
76
+ const definition = makeEditAccountSchema(account, account.settings, openModal);
77
+ expect(definition.schema.safeParse(definition.defaults).success).toBe(true);
78
+ expect(definition.fields.change_emailAddress.getter()).toBe('ada@example.com');
79
+ expect(definition.fields.change_password.getter()).toBe('....');
80
+ expect(openModal).not.toHaveBeenCalled();
81
+ definition.fields.change_emailAddress.onClickButton();
82
+ expect(openModal).toHaveBeenCalledWith({ preset: 'CHANGE_EMAIL', name: 'edit_account_email' });
83
+ const refreshed = makeEditAccountSchema(
84
+ { ...account, email: { ...account.email, address: 'new@example.com' } },
85
+ account.settings,
86
+ openModal,
87
+ );
88
+ expect(refreshed.defaults).toEqual(definition.defaults);
89
+ expect(refreshed.fields.change_emailAddress.getter()).toBe('new@example.com');
90
+ const draft = { ...definition.defaults, settings: { language: 'es' } };
91
+ const options = definition.fields['settings.language'].resolve({ values: draft, context: undefined }).popOverProps.iface.variables
92
+ .options;
93
+ expect(options.find((option) => option.value === 'es')?.selected).toBe(true);
94
+ });
95
+
96
+ it('preserves organization section order, nullable language, and display preference', () => {
97
+ const organization = { name: 'Test', operation: 'ARABLE', address: completeAddress() } as OrganizationGQL;
98
+ const definition = makeEditOrganizationSchema(organization, {
99
+ translateLanguage: null,
100
+ displayTranslatedLogs: false,
101
+ });
102
+ expect(definition.schema.safeParse(definition.defaults).success).toBe(true);
103
+ expect(definition.layout?.slice(0, 7).map((item) => (typeof item === 'string' ? item : item.id))).toEqual([
104
+ 'information',
105
+ 'name',
106
+ 'operation',
107
+ 'language',
108
+ 'translateLanguage',
109
+ 'displayTranslatedLogs',
110
+ 'address',
111
+ ]);
112
+ const scope = { values: definition.defaults, context: undefined };
113
+ const language = definition.fields.translateLanguage.resolve(scope);
114
+ expect(language.inputClassName).toBe('cl_md');
115
+ expect(language.popOverProps.iface.variables.options[0]).toMatchObject({ value: null, selected: true });
116
+ expect(language.popOverProps.iface.variables.options.slice(1).map((option) => [option.value, option.text])).toEqual([
117
+ ['zh-Hans', 'Chinese (Simplified)'],
118
+ ['en', 'English'],
119
+ ['fr', 'French'],
120
+ ['de', 'German'],
121
+ ['it', 'Italian'],
122
+ ['pt', 'Portuguese'],
123
+ ['es', 'Spanish'],
124
+ ['vi', 'Vietnamese'],
125
+ ]);
126
+ const preference = definition.fields.displayTranslatedLogs.resolve(scope);
127
+ expect(preference.popOverProps.iface.variables.options[1]).toMatchObject({ value: false, selected: true });
128
+ });
129
+ });
@@ -0,0 +1,131 @@
1
+ import { JSDOM } from 'jsdom';
2
+ import { act, StrictMode } from 'react';
3
+ import type { Root } from 'react-dom/client';
4
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
+ import { SMSCodeInput } from '../src/modules/SMSCodeInput';
6
+
7
+ let dom: JSDOM;
8
+ let container: HTMLDivElement;
9
+ let root: Root;
10
+
11
+ beforeEach(async () => {
12
+ dom = new JSDOM('<!doctype html><html><body></body></html>');
13
+ vi.stubGlobal('window', dom.window);
14
+ vi.stubGlobal('document', dom.window.document);
15
+ vi.stubGlobal('HTMLInputElement', dom.window.HTMLInputElement);
16
+ vi.stubGlobal('Event', dom.window.Event);
17
+ vi.stubGlobal('KeyboardEvent', dom.window.KeyboardEvent);
18
+ vi.stubGlobal('addEventListener', dom.window.addEventListener.bind(dom.window));
19
+ vi.stubGlobal('removeEventListener', dom.window.removeEventListener.bind(dom.window));
20
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true);
21
+ const { createRoot } = await import('react-dom/client');
22
+ container = document.createElement('div');
23
+ document.body.append(container);
24
+ root = createRoot(container);
25
+ });
26
+
27
+ afterEach(() => {
28
+ act(() => root.unmount());
29
+ dom.window.close();
30
+ vi.unstubAllGlobals();
31
+ });
32
+
33
+ /* Keep Strict Mode enabled so verification never relies on a state updater executing only once. */
34
+ function render(props: React.ComponentProps<typeof SMSCodeInput>) {
35
+ act(() =>
36
+ root.render(
37
+ <StrictMode>
38
+ <SMSCodeInput {...props} />
39
+ </StrictMode>,
40
+ ),
41
+ );
42
+ return container.querySelector('input')!;
43
+ }
44
+
45
+ /* Simulate native typing or autofill without changing React's controlled-input tracker. */
46
+ function enterCode(input: HTMLInputElement, value: string) {
47
+ act(() => {
48
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, value);
49
+ input.dispatchEvent(new Event('input', { bubbles: true }));
50
+ });
51
+ }
52
+
53
+ /* Paste the full clipboard value, including spaces that browsers would otherwise truncate at maxLength. */
54
+ function pasteCode(input: HTMLInputElement, value: string) {
55
+ const event = new Event('paste', { bubbles: true, cancelable: true });
56
+ Object.defineProperty(event, 'clipboardData', { value: { getData: () => value } });
57
+ act(() => input.dispatchEvent(event));
58
+ }
59
+
60
+ describe('SMS verification input', () => {
61
+ it('accepts formatted paste and leading zeroes, submitting a complete code only once', () => {
62
+ const onSubmit = vi.fn();
63
+ const input = render({ onSubmit });
64
+ expect(input.type).toBe('text');
65
+ expect(input.inputMode).toBe('numeric');
66
+ expect(input.autocomplete).toBe('one-time-code');
67
+ pasteCode(input, '01 23456');
68
+ expect(input.value).toBe('01234');
69
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith('01234');
70
+ pasteCode(input, '01234');
71
+ act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })));
72
+ expect(onSubmit).toHaveBeenCalledOnce();
73
+ });
74
+
75
+ it('submits a global digit once in Strict Mode and ignores non-digit shortcuts', () => {
76
+ const onSubmit = vi.fn();
77
+ const input = render({ codeLength: 1, onSubmit });
78
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true })));
79
+ expect(input.value).toBe('');
80
+ act(() => window.dispatchEvent(new KeyboardEvent('keydown', { key: '7', bubbles: true, cancelable: true })));
81
+ expect(input.value).toBe('7');
82
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith('7');
83
+ const pasteShortcut = new KeyboardEvent('keydown', { key: 'v', ctrlKey: true, bubbles: true, cancelable: true });
84
+ act(() => input.dispatchEvent(pasteShortcut));
85
+ expect(pasteShortcut.defaultPrevented).toBe(false);
86
+ });
87
+
88
+ it('keeps partial input local, blocks busy verification, and allows the same code after an error', () => {
89
+ const onSubmit = vi.fn();
90
+ const onChangeCode = vi.fn();
91
+ const input = render({ onSubmit, onChangeCode });
92
+ enterCode(input, '00x2');
93
+ expect(input.value).toBe('002');
94
+ expect(onSubmit).not.toHaveBeenCalled();
95
+ expect(onChangeCode).toHaveBeenLastCalledWith('002');
96
+ enterCode(input, '00234');
97
+ expect(onSubmit).toHaveBeenCalledExactlyOnceWith('00234');
98
+ render({ onSubmit, saving: true });
99
+ expect(input.disabled).toBe(true);
100
+ pasteCode(input, '98765');
101
+ expect(onSubmit).toHaveBeenCalledOnce();
102
+ render({ onSubmit, error: { message: 'Try again' } });
103
+ expect(input.value).toBe('');
104
+ enterCode(input, '00234');
105
+ expect(onSubmit).toHaveBeenCalledTimes(2);
106
+ });
107
+
108
+ it('does not consume digits while another text field has focus', () => {
109
+ const onSubmit = vi.fn();
110
+ const input = render({ onSubmit });
111
+ const other = document.createElement('input');
112
+ document.body.append(other);
113
+ other.focus();
114
+ const event = new KeyboardEvent('keydown', { key: '3', bubbles: true, cancelable: true });
115
+ act(() => other.dispatchEvent(event));
116
+ expect(event.defaultPrevented).toBe(false);
117
+ expect(input.value).toBe('');
118
+ expect(onSubmit).not.toHaveBeenCalled();
119
+ });
120
+
121
+ it('allows an explicit retry after a request stops saving without clearing the entered code', () => {
122
+ const onSubmit = vi.fn();
123
+ const input = render({ onSubmit });
124
+ enterCode(input, '01234');
125
+ render({ onSubmit, saving: true });
126
+ render({ onSubmit, saving: false });
127
+ expect(input.value).toBe('01234');
128
+ act(() => input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true })));
129
+ expect(onSubmit).toHaveBeenCalledTimes(2);
130
+ });
131
+ });