@proteinjs/user-ui 1.11.1 → 1.11.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/index.d.ts +2 -0
  3. package/dist/index.d.ts.map +1 -1
  4. package/dist/index.js +3 -0
  5. package/dist/index.js.map +1 -1
  6. package/dist/src/auth/AuthFormFields.d.ts +18 -0
  7. package/dist/src/auth/AuthFormFields.d.ts.map +1 -0
  8. package/dist/src/auth/AuthFormFields.js +41 -0
  9. package/dist/src/auth/AuthFormFields.js.map +1 -0
  10. package/dist/src/auth/AuthTextField.d.ts +14 -2
  11. package/dist/src/auth/AuthTextField.d.ts.map +1 -1
  12. package/dist/src/auth/AuthTextField.js +5 -3
  13. package/dist/src/auth/AuthTextField.js.map +1 -1
  14. package/dist/src/auth/AuthValidation.d.ts +17 -4
  15. package/dist/src/auth/AuthValidation.d.ts.map +1 -1
  16. package/dist/src/auth/AuthValidation.js +41 -11
  17. package/dist/src/auth/AuthValidation.js.map +1 -1
  18. package/dist/src/pages/ForgotPassword.d.ts.map +1 -1
  19. package/dist/src/pages/ForgotPassword.js +14 -4
  20. package/dist/src/pages/ForgotPassword.js.map +1 -1
  21. package/dist/src/pages/Login.d.ts.map +1 -1
  22. package/dist/src/pages/Login.js +40 -14
  23. package/dist/src/pages/Login.js.map +1 -1
  24. package/dist/src/pages/PasswordReset.d.ts.map +1 -1
  25. package/dist/src/pages/PasswordReset.js +37 -17
  26. package/dist/src/pages/PasswordReset.js.map +1 -1
  27. package/dist/src/pages/Signup.d.ts.map +1 -1
  28. package/dist/src/pages/Signup.js +44 -21
  29. package/dist/src/pages/Signup.js.map +1 -1
  30. package/dist/test/authFormsReadTheirFields.test.d.ts +5 -0
  31. package/dist/test/authFormsReadTheirFields.test.d.ts.map +1 -0
  32. package/dist/test/authFormsReadTheirFields.test.js +595 -0
  33. package/dist/test/authFormsReadTheirFields.test.js.map +1 -0
  34. package/dist/test/authValidation.test.js +43 -8
  35. package/dist/test/authValidation.test.js.map +1 -1
  36. package/index.ts +4 -0
  37. package/package.json +2 -2
  38. package/src/auth/AuthFormFields.ts +35 -0
  39. package/src/auth/AuthTextField.tsx +23 -3
  40. package/src/auth/AuthValidation.ts +54 -15
  41. package/src/pages/ForgotPassword.tsx +18 -5
  42. package/src/pages/Login.tsx +27 -8
  43. package/src/pages/PasswordReset.tsx +22 -11
  44. package/src/pages/Signup.tsx +39 -16
  45. package/test/authFormsReadTheirFields.test.tsx +369 -0
  46. package/test/authValidation.test.ts +49 -16
@@ -0,0 +1,369 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ * @jest-environment-options {"customExportConditions": ["node", "node-addons"]}
4
+ *
5
+ * The auth forms submit what their fields HOLD, however the value got there — through the real
6
+ * page components, with global `fetch` (and the signup service) as the only mocks.
7
+ *
8
+ * The class these tests pin down: a password manager, the platform's autofill service or an
9
+ * input method can write a field's value WITHOUT the `input` event React listens for. The field
10
+ * then looks filled while a controlled component's state is still empty, so a submit that sends
11
+ * the state posts blanks (the server answers "Email and password cannot be blank"). Worse, the
12
+ * next re-render of a controlled field — the focus ring moving as the person taps the button is
13
+ * enough — writes the empty state back over the filled value. The forms therefore own their
14
+ * values in the DOM (uncontrolled fields) and read them from the form at submit; a blank submit
15
+ * is refused in the page with the field marked, so a real form never sends a blank.
16
+ *
17
+ * `fillSilently` is the autofill shape: the value goes in through the native value setter (the
18
+ * path the browser's own filler takes — it never touches React's instance-level value tracker)
19
+ * and no event is dispatched.
20
+ */
21
+ import React from 'react';
22
+ import { createRoot, Root } from 'react-dom/client';
23
+ import { act } from 'react-dom/test-utils';
24
+ import { routes } from '@proteinjs/user';
25
+ import type { InitializeSignupResponse } from '@proteinjs/user';
26
+ import { loginPage } from '../src/pages/Login';
27
+ import { forgotPasswordPage } from '../src/pages/ForgotPassword';
28
+ import { passwordResetPage } from '../src/pages/PasswordReset';
29
+ import { signupPage } from '../src/pages/Signup';
30
+
31
+ declare global {
32
+ // eslint-disable-next-line no-var
33
+ var IS_REACT_ACT_ENVIRONMENT: boolean;
34
+ }
35
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true;
36
+
37
+ const initializeSignup = jest.fn<Promise<InitializeSignupResponse>, [string | undefined]>();
38
+
39
+ jest.mock('@proteinjs/user', () => ({
40
+ ...jest.requireActual('@proteinjs/user'),
41
+ getSignupService: () => ({ initializeSignup }),
42
+ }));
43
+
44
+ const EMAIL = 'ada@example.com';
45
+ const PASSWORD = 'correct horse battery';
46
+
47
+ type FetchCall = { path: string; body: any };
48
+
49
+ let container: HTMLDivElement;
50
+ let root: Root;
51
+ let posts: FetchCall[];
52
+
53
+ beforeEach(() => {
54
+ posts = [];
55
+ initializeSignup.mockReset();
56
+ container = document.createElement('div');
57
+ document.body.appendChild(container);
58
+ root = createRoot(container);
59
+ });
60
+
61
+ afterEach(async () => {
62
+ await act(async () => root.unmount());
63
+ container.remove();
64
+ delete (global as any).fetch;
65
+ });
66
+
67
+ /**
68
+ * Records every POST body; answers each route the way the page needs to stay put (the login and
69
+ * signup answers carry an error so the page never navigates away inside jsdom).
70
+ */
71
+ function mockServer() {
72
+ (global as any).fetch = jest.fn(async (path: string, init?: { method?: string; body?: string }) => {
73
+ if (init?.method === 'post') {
74
+ posts.push({ path, body: JSON.parse(init.body ?? '{}') });
75
+ }
76
+ const body = path.startsWith(routes.validateResetToken.path)
77
+ ? { isValid: true, email: EMAIL }
78
+ : path === routes.login.path
79
+ ? { error: 'User name or password incorrect' }
80
+ : path === routes.signup.path
81
+ ? { error: 'Signups are closed' }
82
+ : {};
83
+ return { status: 200, statusText: 'OK', json: async () => body };
84
+ });
85
+ }
86
+
87
+ async function renderPage(Component: React.ComponentType<any>, url: string) {
88
+ window.history.replaceState({}, '', url);
89
+ await act(async () => {
90
+ root.render(<Component urlParams={{}} />);
91
+ });
92
+ }
93
+
94
+ function field(label: string): HTMLInputElement {
95
+ const input = document.getElementById(`auth-field-${label}`);
96
+ expect(input).not.toBeNull();
97
+ return input as HTMLInputElement;
98
+ }
99
+
100
+ /** The autofill shape: the native value setter, and no event at all. */
101
+ function fillSilently(input: HTMLInputElement, value: string) {
102
+ const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
103
+ act(() => {
104
+ nativeSetter.call(input, value);
105
+ });
106
+ }
107
+
108
+ /** A filler that announces its write with a bare `change` (no `input`). */
109
+ function fillWithChangeOnly(input: HTMLInputElement, value: string) {
110
+ const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
111
+ act(() => {
112
+ nativeSetter.call(input, value);
113
+ input.dispatchEvent(new Event('change', { bubbles: true }));
114
+ });
115
+ }
116
+
117
+ /** Typing: each write followed by the `input` event a keyboard produces. */
118
+ function type(input: HTMLInputElement, value: string) {
119
+ const nativeSetter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
120
+ act(() => {
121
+ nativeSetter.call(input, value);
122
+ input.dispatchEvent(new Event('input', { bubbles: true }));
123
+ });
124
+ }
125
+
126
+ function submitButton(): HTMLButtonElement {
127
+ const button = container.querySelector('button[type="submit"]');
128
+ expect(button).not.toBeNull();
129
+ return button as HTMLButtonElement;
130
+ }
131
+
132
+ async function submit() {
133
+ await act(async () => {
134
+ submitButton().click();
135
+ });
136
+ }
137
+
138
+ /** The field's own error line (MUI wires it to the input through aria-describedby). */
139
+ function fieldError(input: HTMLInputElement): string | null {
140
+ if (input.getAttribute('aria-invalid') !== 'true') {
141
+ return null;
142
+ }
143
+ const describedBy = input.getAttribute('aria-describedby');
144
+ return describedBy ? document.getElementById(describedBy)?.textContent ?? null : null;
145
+ }
146
+
147
+ describe('sign-in form', () => {
148
+ it('an autofill that fires no event reaches the server with the values', async () => {
149
+ mockServer();
150
+ await renderPage(loginPage.component, '/login');
151
+
152
+ fillSilently(field('Email'), EMAIL);
153
+ fillSilently(field('Password'), PASSWORD);
154
+ await submit();
155
+
156
+ expect(posts).toEqual([{ path: routes.login.path, body: { email: EMAIL, password: PASSWORD } }]);
157
+ });
158
+
159
+ it('a silent fill survives the focus moving to the button (the re-render a tap causes)', async () => {
160
+ mockServer();
161
+ await renderPage(loginPage.component, '/login');
162
+
163
+ fillSilently(field('Email'), EMAIL);
164
+ fillSilently(field('Password'), PASSWORD);
165
+ // The person taps into the password field, then taps the button: the field gains and then
166
+ // loses focus, and the text field re-renders its focus ring each time.
167
+ act(() => field('Password').focus());
168
+ act(() => submitButton().focus());
169
+
170
+ expect(field('Password').value).toBe(PASSWORD);
171
+ await submit();
172
+ expect(posts).toEqual([{ path: routes.login.path, body: { email: EMAIL, password: PASSWORD } }]);
173
+ });
174
+
175
+ it('a filler that fires only `change` reaches the server with the values', async () => {
176
+ mockServer();
177
+ await renderPage(loginPage.component, '/login');
178
+
179
+ fillWithChangeOnly(field('Email'), EMAIL);
180
+ fillWithChangeOnly(field('Password'), PASSWORD);
181
+ await submit();
182
+
183
+ expect(posts).toEqual([{ path: routes.login.path, body: { email: EMAIL, password: PASSWORD } }]);
184
+ });
185
+
186
+ it('typed values reach the server', async () => {
187
+ mockServer();
188
+ await renderPage(loginPage.component, '/login');
189
+
190
+ type(field('Email'), EMAIL);
191
+ type(field('Password'), PASSWORD);
192
+ await submit();
193
+
194
+ expect(posts).toEqual([{ path: routes.login.path, body: { email: EMAIL, password: PASSWORD } }]);
195
+ });
196
+
197
+ it('a blank submit never leaves the page: each empty field is marked', async () => {
198
+ mockServer();
199
+ await renderPage(loginPage.component, '/login');
200
+
201
+ await submit();
202
+
203
+ expect(posts).toEqual([]);
204
+ expect(fieldError(field('Email'))).toBe('Enter your email');
205
+ expect(fieldError(field('Password'))).toBe('Enter your password');
206
+ // The first marked field takes the focus, so the keyboard opens where the person must type.
207
+ expect(document.activeElement).toBe(field('Email'));
208
+ });
209
+
210
+ it('a submit with only the password blank marks only the password', async () => {
211
+ mockServer();
212
+ await renderPage(loginPage.component, '/login');
213
+
214
+ fillSilently(field('Email'), EMAIL);
215
+ await submit();
216
+
217
+ expect(posts).toEqual([]);
218
+ expect(fieldError(field('Email'))).toBeNull();
219
+ expect(fieldError(field('Password'))).toBe('Enter your password');
220
+ });
221
+
222
+ it("editing a marked field clears that field's mark", async () => {
223
+ mockServer();
224
+ await renderPage(loginPage.component, '/login');
225
+
226
+ await submit();
227
+ type(field('Email'), EMAIL);
228
+
229
+ expect(fieldError(field('Email'))).toBeNull();
230
+ expect(fieldError(field('Password'))).toBe('Enter your password');
231
+ });
232
+ });
233
+
234
+ describe('forgot-password form', () => {
235
+ it('an autofill that fires no event reaches the server with the email', async () => {
236
+ mockServer();
237
+ await renderPage(forgotPasswordPage.component, '/login/forgot-password');
238
+
239
+ fillSilently(field('Email'), EMAIL);
240
+ await submit();
241
+
242
+ expect(posts).toEqual([{ path: routes.initiatePasswordReset.path, body: { email: EMAIL } }]);
243
+ });
244
+
245
+ it('a blank submit never leaves the page: the email is marked', async () => {
246
+ mockServer();
247
+ await renderPage(forgotPasswordPage.component, '/login/forgot-password');
248
+
249
+ await submit();
250
+
251
+ expect(posts).toEqual([]);
252
+ expect(fieldError(field('Email'))).toBe('Enter your email');
253
+ });
254
+ });
255
+
256
+ describe('password-reset form', () => {
257
+ it('an autofill that fires no event (a suggested password) reaches the server', async () => {
258
+ mockServer();
259
+ await renderPage(passwordResetPage.component, '/login/password-reset?token=reset-token-1');
260
+
261
+ fillSilently(field('New password'), PASSWORD);
262
+ fillSilently(field('Confirm new password'), PASSWORD);
263
+ await submit();
264
+
265
+ expect(posts).toEqual([
266
+ { path: routes.executePasswordReset.path, body: { token: 'reset-token-1', newPassword: PASSWORD } },
267
+ ]);
268
+ });
269
+
270
+ it('a blank submit never leaves the page: the new password is marked', async () => {
271
+ mockServer();
272
+ await renderPage(passwordResetPage.component, '/login/password-reset?token=reset-token-1');
273
+
274
+ await submit();
275
+
276
+ expect(posts).toEqual([]);
277
+ expect(fieldError(field('New password'))).toBe('Enter a new password');
278
+ });
279
+
280
+ it('a mismatched confirmation marks the confirmation', async () => {
281
+ mockServer();
282
+ await renderPage(passwordResetPage.component, '/login/password-reset?token=reset-token-1');
283
+
284
+ fillSilently(field('New password'), PASSWORD);
285
+ fillSilently(field('Confirm new password'), `${PASSWORD}!`);
286
+ await submit();
287
+
288
+ expect(posts).toEqual([]);
289
+ expect(fieldError(field('New password'))).toBeNull();
290
+ expect(fieldError(field('Confirm new password'))).toBe('Passwords do not match');
291
+ });
292
+ });
293
+
294
+ describe('signup form', () => {
295
+ it('an autofill that fires no event reaches the server with the values', async () => {
296
+ mockServer();
297
+ initializeSignup.mockResolvedValue({ isReady: true, isInviteOnly: false });
298
+ await renderPage(signupPage.component, '/signup');
299
+
300
+ fillSilently(field('Name'), 'Ada Lovelace');
301
+ fillSilently(field('Email'), EMAIL);
302
+ fillSilently(field('Password'), PASSWORD);
303
+ fillSilently(field('Confirm password'), PASSWORD);
304
+ await submit();
305
+
306
+ expect(posts).toEqual([
307
+ { path: routes.signup.path, body: { name: 'Ada Lovelace', email: EMAIL, password: PASSWORD } },
308
+ ]);
309
+ });
310
+
311
+ it('a blank submit never leaves the page: each empty field is marked', async () => {
312
+ mockServer();
313
+ initializeSignup.mockResolvedValue({ isReady: true, isInviteOnly: false });
314
+ await renderPage(signupPage.component, '/signup');
315
+
316
+ await submit();
317
+
318
+ expect(posts).toEqual([]);
319
+ expect(fieldError(field('Name'))).toBe('Enter your name');
320
+ expect(fieldError(field('Email'))).toBe('Enter your email');
321
+ expect(fieldError(field('Password'))).toBe('Enter a password');
322
+ });
323
+ });
324
+
325
+ describe('the fields own their values (what the fix rests on)', () => {
326
+ it('a silently filled password survives the show-password toggle and reaches the server', async () => {
327
+ mockServer();
328
+ await renderPage(loginPage.component, '/login');
329
+
330
+ fillSilently(field('Email'), EMAIL);
331
+ fillSilently(field('Password'), PASSWORD);
332
+ // The reveal toggle re-renders the field with type='text': the same input, its value kept.
333
+ await act(async () => {
334
+ (container.querySelector('button[aria-label="Show password"]') as HTMLButtonElement).click();
335
+ });
336
+ expect(field('Password').type).toBe('text');
337
+ expect(field('Password').value).toBe(PASSWORD);
338
+
339
+ await submit();
340
+ expect(posts).toEqual([{ path: routes.login.path, body: { email: EMAIL, password: PASSWORD } }]);
341
+ });
342
+
343
+ it('no field switches between controlled and uncontrolled across a refusal, typing and a submit (React warns on that)', async () => {
344
+ const consoleError = jest.spyOn(console, 'error').mockImplementation(() => {});
345
+ try {
346
+ mockServer();
347
+ await renderPage(loginPage.component, '/login');
348
+
349
+ await submit(); // refused: both fields marked
350
+ type(field('Email'), EMAIL); // the mark clears
351
+ fillSilently(field('Password'), PASSWORD);
352
+ await submit(); // sent; `busy` flips the fields disabled and back
353
+
354
+ expect(posts).toHaveLength(1);
355
+ const warnings = consoleError.mock.calls.map((call) => call.map(String).join(' '));
356
+ expect(warnings.filter((warning) => /controlled/i.test(warning))).toEqual([]);
357
+ } finally {
358
+ consoleError.mockRestore();
359
+ }
360
+ });
361
+ });
362
+
363
+ describe('the package surface', () => {
364
+ it('exports the form reader, so a consumer page reads its own form the same way', async () => {
365
+ const surface = await import('../index');
366
+ expect(typeof surface.AuthFormFields.read).toBe('function');
367
+ expect(typeof surface.AuthFormFields.focusFirstInvalid).toBe('function');
368
+ });
369
+ });
@@ -7,19 +7,50 @@ const validSignup = {
7
7
  confirmPassword: 'hunter22',
8
8
  };
9
9
 
10
+ describe('AuthValidation.login', () => {
11
+ it('accepts an email and a password', () => {
12
+ expect(AuthValidation.login({ email: 'ada@example.com', password: 'hunter22' })).toBeUndefined();
13
+ });
14
+
15
+ it('marks every blank field', () => {
16
+ expect(AuthValidation.login({ email: '', password: '' })).toEqual({
17
+ email: 'Enter your email',
18
+ password: 'Enter your password',
19
+ });
20
+ });
21
+
22
+ it('treats a whitespace-only email as blank, and marks only the blank field', () => {
23
+ expect(AuthValidation.login({ email: ' ', password: 'hunter22' })).toEqual({ email: 'Enter your email' });
24
+ });
25
+ });
26
+
27
+ describe('AuthValidation.forgotPassword', () => {
28
+ it('accepts an email', () => {
29
+ expect(AuthValidation.forgotPassword({ email: 'ada@example.com' })).toBeUndefined();
30
+ });
31
+
32
+ it('marks a blank email', () => {
33
+ expect(AuthValidation.forgotPassword({ email: ' ' })).toEqual({ email: 'Enter your email' });
34
+ });
35
+ });
36
+
10
37
  describe('AuthValidation.signup', () => {
11
38
  it('accepts a complete, matching signup', () => {
12
39
  expect(AuthValidation.signup(validSignup, false)).toBeUndefined();
13
40
  });
14
41
 
15
42
  it('requires a name', () => {
16
- expect(AuthValidation.signup({ ...validSignup, name: ' ' }, false)).toBe('Please enter your name.');
43
+ expect(AuthValidation.signup({ ...validSignup, name: ' ' }, false)).toEqual({ name: 'Enter your name' });
44
+ });
45
+
46
+ it('requires an email when not invited', () => {
47
+ expect(AuthValidation.signup({ ...validSignup, email: '' }, false)).toEqual({ email: 'Enter your email' });
17
48
  });
18
49
 
19
50
  it('requires a valid email when not invited', () => {
20
- expect(AuthValidation.signup({ ...validSignup, email: 'not-an-email' }, false)).toBe(
21
- 'Please enter a valid email address.'
22
- );
51
+ expect(AuthValidation.signup({ ...validSignup, email: 'not-an-email' }, false)).toEqual({
52
+ email: 'Enter a valid email address',
53
+ });
23
54
  });
24
55
 
25
56
  it('skips the email check for invited users (the invite token carries the email)', () => {
@@ -27,15 +58,15 @@ describe('AuthValidation.signup', () => {
27
58
  });
28
59
 
29
60
  it('requires a password', () => {
30
- expect(AuthValidation.signup({ ...validSignup, password: '', confirmPassword: '' }, false)).toBe(
31
- 'Please enter a password.'
32
- );
61
+ expect(AuthValidation.signup({ ...validSignup, password: '', confirmPassword: '' }, false)).toEqual({
62
+ password: 'Enter a password',
63
+ });
33
64
  });
34
65
 
35
- it('rejects a mismatched password confirmation', () => {
36
- expect(AuthValidation.signup({ ...validSignup, confirmPassword: 'different' }, false)).toBe(
37
- 'Passwords do not match.'
38
- );
66
+ it('marks a mismatched password confirmation on the confirmation', () => {
67
+ expect(AuthValidation.signup({ ...validSignup, confirmPassword: 'different' }, false)).toEqual({
68
+ confirmPassword: 'Passwords do not match',
69
+ });
39
70
  });
40
71
  });
41
72
 
@@ -45,12 +76,14 @@ describe('AuthValidation.passwordReset', () => {
45
76
  });
46
77
 
47
78
  it('requires a new password', () => {
48
- expect(AuthValidation.passwordReset({ newPassword: '', confirmPassword: '' })).toBe('Please enter a new password.');
79
+ expect(AuthValidation.passwordReset({ newPassword: '', confirmPassword: '' })).toEqual({
80
+ newPassword: 'Enter a new password',
81
+ });
49
82
  });
50
83
 
51
- it('rejects a mismatched confirmation', () => {
52
- expect(AuthValidation.passwordReset({ newPassword: 'hunter22', confirmPassword: 'hunter23' })).toBe(
53
- 'Passwords do not match.'
54
- );
84
+ it('marks a mismatched confirmation on the confirmation', () => {
85
+ expect(AuthValidation.passwordReset({ newPassword: 'hunter22', confirmPassword: 'hunter23' })).toEqual({
86
+ confirmPassword: 'Passwords do not match',
87
+ });
55
88
  });
56
89
  });