Skip to content

Commit f936b92

Browse files
committed
fix(console): mark the fields a refused form submit names
A refused submit on the console form page (public /f/:slug and the internal /forms/:name) now marks each field it names: aria-invalid on the control and the reason under it, for the client required check, a faulted visibleWhen (pointed at the banner that names it) and the server's field-level refusals, read with extractFieldErrors from @object-ui/react. The banner and the toast are unchanged. Claude-Session: https://claude.ai/code/session_01JQwxbX1Zhx8ST6DDF1AGvD Co-authored-by: Claude <noreply@anthropic.com>
1 parent 9f57dcc commit f936b92

2 files changed

Lines changed: 468 additions & 24 deletions

File tree

Lines changed: 314 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,314 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack-ai/objectstack#27417 — a refused submit marks the fields it names.
5+
*
6+
* Every refusal on this page used to end in one string, on the banner and the
7+
* outcome toast, and nothing on the inputs: the submitter read "Required: Name,
8+
* Email" or a server sentence and had to find the rows themselves. Each refused
9+
* row now carries `aria-invalid` and a reason under its control, which the
10+
* control names in `aria-describedby`.
11+
*
12+
* The server half reads the refusal with the record dialog's reader of the
13+
* server's field paths, `extractFieldErrors` (`@object-ui/react`); this page
14+
* only attaches the response body to the error it throws. So the fixtures below
15+
* are the envelopes the server actually answers: the flat `400
16+
* VALIDATION_FAILED` with `fields[]` the public submit route maps a validation
17+
* error to, the same refusal in the runtime dispatcher's wrapped envelope, and
18+
* the flat `409 UNIQUE_VIOLATION` naming its one `field`.
19+
*
20+
* The banner and the toast are unchanged: a refusal that names no field marks
21+
* no row and still says what it said before.
22+
*/
23+
24+
import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';
25+
import { render, screen, waitFor } from '@testing-library/react';
26+
import userEvent from '@testing-library/user-event';
27+
import { MemoryRouter, Route, Routes } from 'react-router-dom';
28+
import { toast } from 'sonner';
29+
import { createI18n } from '@object-ui/i18n';
30+
import { FormPage } from './FormPage';
31+
32+
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
33+
34+
const FIELDS = {
35+
name: { type: 'text', label: 'Name' },
36+
email: { type: 'text', label: 'Email' },
37+
company: { type: 'text', label: 'Company' },
38+
};
39+
40+
function publicPayload(sectionFields: unknown[], fields: Record<string, unknown> = FIELDS) {
41+
return {
42+
slug: 'contact-us',
43+
object: 'showcase_inquiry',
44+
label: 'Contact us',
45+
form: { type: 'simple', sections: [{ fields: sectionFields }] },
46+
objectSchema: { name: 'showcase_inquiry', fields },
47+
};
48+
}
49+
50+
let posts = 0;
51+
52+
/** Answers the resolver, and every submit with `refusal` (status + JSON body). */
53+
function stubPublic(
54+
sectionFields: unknown[],
55+
refusal: { status: number; body: unknown },
56+
fields?: Record<string, unknown>,
57+
) {
58+
vi.stubGlobal(
59+
'fetch',
60+
vi.fn(async (url: string, init?: RequestInit) => {
61+
if (init?.method === 'POST') {
62+
posts += 1;
63+
return {
64+
ok: false,
65+
status: refusal.status,
66+
statusText: 'Refused',
67+
text: async () => JSON.stringify(refusal.body),
68+
json: async () => refusal.body,
69+
} as unknown as Response;
70+
}
71+
if (!String(url).includes('/forms/')) throw new Error(`unstubbed fetch: ${url}`);
72+
const payload = publicPayload(sectionFields, fields);
73+
return {
74+
ok: true,
75+
status: 200,
76+
statusText: 'OK',
77+
json: async () => payload,
78+
text: async () => JSON.stringify(payload),
79+
} as unknown as Response;
80+
}),
81+
);
82+
return render(
83+
<MemoryRouter initialEntries={['/f/contact-us']}>
84+
<Routes>
85+
<Route path="/f/:slug" element={<FormPage mode="public" />} />
86+
</Routes>
87+
</MemoryRouter>,
88+
);
89+
}
90+
91+
/** The internal route, refusing its `POST /data/:object` with `refusal`. */
92+
function stubInternal(refusal: { status: number; body: unknown }) {
93+
const view = {
94+
name: 'showcase_inquiry.contact',
95+
object: 'showcase_inquiry',
96+
viewKind: 'form',
97+
label: 'Contact',
98+
config: { type: 'simple', sections: [{ fields: ['name', 'email', 'company'] }] },
99+
};
100+
const object = { name: 'showcase_inquiry', label: 'Inquiry', fields: FIELDS };
101+
vi.stubGlobal(
102+
'fetch',
103+
vi.fn(async (url: string, init?: RequestInit) => {
104+
const answer = (ok: boolean, status: number, body: unknown) =>
105+
({
106+
ok,
107+
status,
108+
statusText: ok ? 'OK' : 'Refused',
109+
json: async () => body,
110+
text: async () => JSON.stringify(body),
111+
}) as unknown as Response;
112+
if (init?.method === 'POST') {
113+
posts += 1;
114+
return answer(false, refusal.status, refusal.body);
115+
}
116+
if (String(url).includes('/meta/view/')) return answer(true, 200, view);
117+
if (String(url).includes('/meta/object/')) return answer(true, 200, object);
118+
throw new Error(`unstubbed fetch: ${url}`);
119+
}),
120+
);
121+
return render(
122+
<MemoryRouter initialEntries={['/forms/showcase_inquiry.contact']}>
123+
<Routes>
124+
<Route path="/forms/:name" element={<FormPage mode="internal" />} />
125+
</Routes>
126+
</MemoryRouter>,
127+
);
128+
}
129+
130+
/** The text a control names in `aria-describedby`, or null when it names none. */
131+
function describedText(control: HTMLElement): string | null {
132+
const id = control.getAttribute('aria-describedby');
133+
if (!id) return null;
134+
return id
135+
.split(/\s+/)
136+
.map((ref) => document.getElementById(ref)?.textContent ?? '')
137+
.join(' ')
138+
.trim();
139+
}
140+
141+
async function fillAndSubmit(fill: Record<string, string>) {
142+
await screen.findByLabelText(/^Name/);
143+
for (const [label, value] of Object.entries(fill)) {
144+
await userEvent.type(screen.getByLabelText(label), value);
145+
}
146+
await userEvent.click(screen.getByRole('button', { name: /Submit/ }));
147+
}
148+
149+
const VALIDATION_FAILED_FIELDS = [
150+
{ field: 'name', code: 'max_length', message: 'Name must be at most 3 characters' },
151+
{ field: 'email', code: 'invalid_format', message: 'Email is not a valid email address' },
152+
];
153+
154+
beforeEach(() => {
155+
posts = 0;
156+
vi.mocked(toast.error).mockClear();
157+
// The page's chrome reads the `en` pack through react-i18next's global, as
158+
// the sibling FormPage suites set it up.
159+
createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false });
160+
});
161+
162+
afterEach(() => {
163+
vi.unstubAllGlobals();
164+
});
165+
166+
describe('#27417 — a server refusal naming fields marks each of them', () => {
167+
it('public route: the flat 400 VALIDATION_FAILED marks both named fields and no other', async () => {
168+
stubPublic(['name', 'email', 'company'], {
169+
status: 400,
170+
body: { error: 'Validation failed', code: 'VALIDATION_FAILED', fields: VALIDATION_FAILED_FIELDS },
171+
});
172+
await fillAndSubmit({ Name: 'Ada Lovelace', Email: 'ada' });
173+
174+
const name = screen.getByLabelText('Name');
175+
const email = screen.getByLabelText('Email');
176+
await waitFor(() => expect(name).toHaveAttribute('aria-invalid', 'true'));
177+
expect(email).toHaveAttribute('aria-invalid', 'true');
178+
expect(describedText(name)).toContain('Name must be at most 3 characters');
179+
expect(describedText(email)).toContain('Email is not a valid email address');
180+
// The row the refusal does not name stays unmarked.
181+
expect(screen.getByLabelText('Company')).not.toHaveAttribute('aria-invalid');
182+
// The banner and the toast are unchanged.
183+
expect(vi.mocked(toast.error)).toHaveBeenCalledTimes(1);
184+
expect(String(vi.mocked(toast.error).mock.calls[0][0])).toContain('Submit failed (400)');
185+
});
186+
187+
it('internal route: the wrapped dispatcher envelope marks both named fields', async () => {
188+
stubInternal({
189+
status: 400,
190+
body: {
191+
success: false,
192+
error: {
193+
code: 'VALIDATION_FAILED',
194+
message: 'Validation failed',
195+
httpStatus: 400,
196+
details: { fields: VALIDATION_FAILED_FIELDS },
197+
},
198+
},
199+
});
200+
await fillAndSubmit({ Name: 'Ada Lovelace', Email: 'ada' });
201+
202+
const name = screen.getByLabelText('Name');
203+
await waitFor(() => expect(name).toHaveAttribute('aria-invalid', 'true'));
204+
expect(screen.getByLabelText('Email')).toHaveAttribute('aria-invalid', 'true');
205+
expect(screen.getByLabelText('Company')).not.toHaveAttribute('aria-invalid');
206+
expect(describedText(name)).toContain('Name must be at most 3 characters');
207+
});
208+
209+
it('marks the one field a 409 UNIQUE_VIOLATION names, with the server sentence', async () => {
210+
stubPublic(['name', 'email', 'company'], {
211+
status: 409,
212+
body: {
213+
error: 'An inquiry with this email already exists.',
214+
code: 'UNIQUE_VIOLATION',
215+
field: 'email',
216+
object: 'showcase_inquiry',
217+
},
218+
});
219+
await fillAndSubmit({ Name: 'Ada', Email: 'ada@example.com' });
220+
221+
const email = screen.getByLabelText('Email');
222+
await waitFor(() => expect(email).toHaveAttribute('aria-invalid', 'true'));
223+
expect(describedText(email)).toContain('An inquiry with this email already exists.');
224+
expect(screen.getByLabelText('Name')).not.toHaveAttribute('aria-invalid');
225+
});
226+
227+
it('an edit to a marked row clears its mark and leaves the others', async () => {
228+
stubPublic(['name', 'email', 'company'], {
229+
status: 400,
230+
body: { error: 'Validation failed', code: 'VALIDATION_FAILED', fields: VALIDATION_FAILED_FIELDS },
231+
});
232+
await fillAndSubmit({ Name: 'Ada Lovelace', Email: 'ada' });
233+
const name = screen.getByLabelText('Name');
234+
await waitFor(() => expect(name).toHaveAttribute('aria-invalid', 'true'));
235+
236+
await userEvent.type(name, '!');
237+
expect(name).not.toHaveAttribute('aria-invalid');
238+
expect(screen.queryByText('Name must be at most 3 characters')).toBeNull();
239+
expect(screen.getByLabelText('Email')).toHaveAttribute('aria-invalid', 'true');
240+
});
241+
});
242+
243+
describe('#27417 — a refusal naming no field marks none', () => {
244+
it('a 400 with no field list leaves every row unmarked and keeps the banner', async () => {
245+
stubPublic(['name', 'email', 'company'], {
246+
status: 400,
247+
body: { error: 'Invalid inquiry status transition.', code: 'VALIDATION_ERROR' },
248+
});
249+
await fillAndSubmit({ Name: 'Ada', Email: 'ada@example.com' });
250+
251+
expect(await screen.findByText(/Invalid inquiry status transition\./)).toBeInTheDocument();
252+
for (const label of ['Name', 'Email', 'Company']) {
253+
expect(screen.getByLabelText(label)).not.toHaveAttribute('aria-invalid');
254+
expect(screen.getByLabelText(label)).not.toHaveAttribute('aria-describedby');
255+
}
256+
});
257+
258+
it('a field the form does not draw marks nothing', async () => {
259+
stubPublic(['name', 'email'], {
260+
status: 400,
261+
body: {
262+
error: 'Validation failed',
263+
code: 'VALIDATION_FAILED',
264+
fields: [{ field: 'company', message: 'Company is required' }],
265+
},
266+
});
267+
await fillAndSubmit({ Name: 'Ada', Email: 'ada@example.com' });
268+
269+
await waitFor(() => expect(vi.mocked(toast.error)).toHaveBeenCalledTimes(1));
270+
expect(screen.getByLabelText('Name')).not.toHaveAttribute('aria-invalid');
271+
expect(screen.getByLabelText('Email')).not.toHaveAttribute('aria-invalid');
272+
expect(screen.queryByText('Company is required')).toBeNull();
273+
});
274+
});
275+
276+
describe('#27417 — the client required refusal marks the missing fields', () => {
277+
it('marks each required row left empty, writes nothing, and leaves the filled one', async () => {
278+
stubPublic(
279+
[{ field: 'name', required: true }, { field: 'email', required: true }, 'company'],
280+
{ status: 500, body: { error: 'must not be reached' } },
281+
);
282+
await fillAndSubmit({ Company: 'Analytical Engines' });
283+
284+
expect(await screen.findByText('Required: Name, Email')).toBeInTheDocument();
285+
expect(posts).toBe(0);
286+
const name = screen.getByLabelText(/^Name/);
287+
const email = screen.getByLabelText(/^Email/);
288+
expect(name).toHaveAttribute('aria-invalid', 'true');
289+
expect(email).toHaveAttribute('aria-invalid', 'true');
290+
expect(describedText(name)).toBe('Name is required');
291+
expect(describedText(email)).toBe('Email is required');
292+
expect(screen.getByLabelText('Company')).not.toHaveAttribute('aria-invalid');
293+
});
294+
});
295+
296+
describe('#27417 — a faulted visibleWhen marks its row and points it at the banner', () => {
297+
it('marks the faulted row, names the banner, and repeats no text under it', async () => {
298+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
299+
stubPublic(
300+
['name', 'email', 'company'],
301+
{ status: 500, body: { error: 'must not be reached' } },
302+
{ ...FIELDS, company: { type: 'text', label: 'Company', visibleWhen: 'record.name ==' } },
303+
);
304+
await fillAndSubmit({ Name: 'Ada', Email: 'ada@example.com' });
305+
306+
const banner = await screen.findByText(/visibleWhen rule of Company could not be evaluated/);
307+
expect(posts).toBe(0);
308+
const company = screen.getByLabelText('Company');
309+
expect(company).toHaveAttribute('aria-invalid', 'true');
310+
expect(company.getAttribute('aria-describedby')).toBe(banner.id);
311+
expect(screen.getByLabelText('Name')).not.toHaveAttribute('aria-invalid');
312+
warn.mockRestore();
313+
});
314+
});

0 commit comments

Comments
 (0)