Skip to content

Commit cf9a965

Browse files
committed
fix(components): a refused submit focuses the first invalid field instead of toasting the field list
The invalid-submit toast repeated what each field already says under its input, truncated its own list after three names, and was drawn over the record dialog's title row. Drop it; keep reveal + focus on the first invalid field (activating its tab first). A server rejection naming a field with no drawn input (a predicate-hidden tab or section) now falls through to the form-level banner, which the toast used to cover. Claude-Session: https://claude.ai/code/session_01CzUs1oNtFWhWUXT7rmoGy2 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 3518664 commit cf9a965

5 files changed

Lines changed: 133 additions & 59 deletions

File tree

‎ui/packages/components/src/renderers/form/__tests__/fieldtab-visiblewhen-6237.test.tsx‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
5757
import { render, screen, cleanup, fireEvent, waitFor } from '@testing-library/react';
5858
import { ComponentRegistry } from '@object-ui/core';
5959
import { PredicateScopeProvider } from '@object-ui/react';
60+
import { toast } from '../../../ui/sonner';
6061
// Module-scope import (not `beforeAll`) — objectui#3010/#3021.
6162
import '../../../renderers';
6263

@@ -208,6 +209,42 @@ describe('#6237 — a tab predicate gates the whole tab', () => {
208209
expect(document.body.textContent).not.toMatch(/required/i);
209210
});
210211

212+
it('a SERVER rejection of a hidden tab\'s field is said at form level — no input can carry it (objectstack#25874)', async () => {
213+
// The invalid-submit toast that used to name every rejected field is gone:
214+
// a drawn field carries its own message. A field on a hidden tab has no
215+
// drawn input, so its rejection must not be taken over as "marked inline"
216+
// — the form-level banner says the server's sentence instead.
217+
const toastError = vi.spyOn(toast, 'error').mockImplementation(() => 'id' as never);
218+
const message = 'Salary is required';
219+
const fields = [{ field: 'salary', code: 'required', message }];
220+
const onSubmit = vi.fn().mockRejectedValue(
221+
Object.assign(new Error(message), {
222+
code: 'VALIDATION_FAILED',
223+
httpStatus: 400,
224+
details: { error: message, code: 'VALIDATION_FAILED', fields, object: 'crm_employee' },
225+
}),
226+
);
227+
renderForm(
228+
{
229+
fields: FIELDS(),
230+
fieldTabs: TABS(GATE),
231+
showSubmit: true,
232+
submitLabel: 'Save',
233+
onSubmit,
234+
},
235+
DENIED,
236+
);
237+
expect(member(/salary/i)).toBeNull();
238+
fireEvent.click(submitBtn());
239+
240+
await waitFor(() => expect(screen.getByText(message)).toBeTruthy());
241+
expect(toastError).toHaveBeenCalledTimes(1);
242+
expect(String(toastError.mock.calls[0][0])).toBe(message);
243+
// The hidden tab is never activated to "reveal" a field it cannot draw.
244+
expect(trigger()).toBeNull();
245+
expect(screen.getByRole('tab', { name: /basics/i })).toHaveAttribute('data-state', 'active');
246+
});
247+
211248
it('control: the SAME required field on a VISIBLE (even inactive) tab still blocks the submit', async () => {
212249
const onSubmit = vi.fn();
213250
renderForm(

‎ui/packages/components/src/renderers/form/__tests__/form-invalid-scroll.test.tsx‎

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,15 @@
88

99
/**
1010
* #2793: submitting a form with a missing required field must give visible
11-
* feedback — a toast naming the fields (already shipped in #2329) AND scroll
12-
* the first errored field into view + focus it. Before this, react-hook-form's
13-
* native focus-on-error silently no-opped for custom widgets (lookup / select /
14-
* master-detail), so on a long form the user clicked 创建 and saw nothing.
11+
* feedback — scroll the first errored field into view + focus it. Before this,
12+
* react-hook-form's native focus-on-error silently no-opped for custom widgets
13+
* (lookup / select / master-detail), so on a long form the user clicked 创建
14+
* and saw nothing.
15+
*
16+
* And NO toast (objectstack#25874). The toast that used to name the fields
17+
* (#2329) repeated what each field already says under its input, truncated its
18+
* own list after three names, and was drawn over the record dialog's title. The
19+
* inline messages carry the detail; focus carries the "something is wrong".
1520
*/
1621

1722
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
@@ -58,7 +63,7 @@ function renderForm(fields: any[], defaultValues?: Record<string, unknown>) {
5863
const submit = () => fireEvent.click(screen.getByRole('button', { name: /create/i }));
5964

6065
describe('form renderer — invalid-submit feedback (#2793)', () => {
61-
it('toasts and scrolls+focuses the first errored field on a missing required field', async () => {
66+
it('scrolls+focuses the first errored field on a missing required field, with no toast', async () => {
6267
const { container } = renderForm([
6368
{ name: 'title', label: 'Title', type: 'input', required: true },
6469
{ name: 'project', label: 'Project', type: 'input', required: true },
@@ -70,14 +75,15 @@ describe('form renderer — invalid-submit feedback (#2793)', () => {
7075

7176
submit();
7277

73-
await waitFor(() => expect(toastErrorSpy).toHaveBeenCalled());
74-
// Names the missing field(s).
75-
expect(String(toastErrorSpy.mock.calls[0][0])).toMatch(/Title/);
7678
// First errored field (visual order) scrolled into view + focused.
77-
expect(scrollSpy).toHaveBeenCalled();
79+
await waitFor(() => expect(scrollSpy).toHaveBeenCalled());
7880
await waitFor(() =>
7981
expect(titleWrap.contains(document.activeElement)).toBe(true),
8082
);
83+
// The per-field message is the only error text: it is under the input…
84+
expect(titleWrap.textContent).toMatch(/required/i);
85+
// …and no toast repeats it over the dialog.
86+
expect(toastErrorSpy).not.toHaveBeenCalled();
8187
});
8288

8389
it('scrolls the first errored field even when an earlier field is valid', async () => {
@@ -98,9 +104,8 @@ describe('form renderer — invalid-submit feedback (#2793)', () => {
98104

99105
submit();
100106

101-
await waitFor(() => expect(toastErrorSpy).toHaveBeenCalled());
102107
// Only `project` is invalid → it, not the valid `title`, is scrolled to.
103-
expect(projectScroll).toHaveBeenCalled();
108+
await waitFor(() => expect(projectScroll).toHaveBeenCalled());
104109
expect(titleScroll).not.toHaveBeenCalled();
105110
});
106111

‎ui/packages/components/src/renderers/form/__tests__/form-invalid-toast-joiner.test.tsx‎

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,14 @@
77
*/
88

99
/**
10-
* The invalid-submit toast joins the field names with a PER-LOCALE separator —
10+
* A refused submit joins the field names with a PER-LOCALE separator —
1111
* objectstack#5407.
1212
*
13+
* The list was first built for the invalid-submit toast, which is gone
14+
* (objectstack#25874: each field's own message carries the detail). The form's
15+
* remaining field-name list is the faulted-`visibleWhen` refusal, which reads
16+
* the same `validation.formInvalidJoiner` entry, so the pin moved there.
17+
*
1318
* `announceFieldErrors` used to build the list with a hardcoded `、` (U+3001).
1419
* That is the CJK enumeration comma: correct for zh/ja by accident, wrong in
1520
* every Latin locale, and most visibly wrong in English, where the toast read
@@ -42,6 +47,8 @@ let toastErrorSpy: ReturnType<typeof vi.spyOn>;
4247

4348
beforeEach(() => {
4449
toastErrorSpy = vi.spyOn(toast, 'error').mockImplementation(() => 'id' as any);
50+
// The faulted predicates are reported once each; not what this file asserts.
51+
vi.spyOn(console, 'warn').mockImplementation(() => {});
4552
if (!(Element.prototype as any).scrollIntoView) {
4653
(Element.prototype as any).scrollIntoView = () => {};
4754
}
@@ -52,11 +59,14 @@ afterEach(() => {
5259
vi.restoreAllMocks();
5360
});
5461

55-
/** Three required fields, so the joiner appears twice and truncation does not. */
62+
/** A predicate the engine cannot parse: a fault whatever the record holds. */
63+
const BROKEN = 'record.stage ==';
64+
65+
/** Three faulted fields, so the joiner appears twice. */
5666
const fields = [
57-
{ name: 'subject', label: 'Subject', type: 'input', required: true },
58-
{ name: 'account', label: 'Account', type: 'input', required: true },
59-
{ name: 'status', label: 'Status', type: 'input', required: true },
67+
{ name: 'subject', label: 'Subject', type: 'input', visibleWhen: BROKEN },
68+
{ name: 'account', label: 'Account', type: 'input', visibleWhen: BROKEN },
69+
{ name: 'status', label: 'Status', type: 'input', visibleWhen: BROKEN },
6070
];
6171

6272
function renderFormIn(language: string) {
@@ -84,7 +94,7 @@ async function toastTextAfterSubmit(language: string): Promise<string> {
8494
return String(toastErrorSpy.mock.calls[0][0]);
8595
}
8696

87-
describe('form renderer — invalid-submit toast list joiner (objectstack#5407)', () => {
97+
describe('form renderer — refused-submit field list joiner (objectstack#5407)', () => {
8898
it('joins with a comma+space under an en session, never the CJK comma', async () => {
8999
const text = await toastTextAfterSubmit('en');
90100

@@ -100,6 +110,6 @@ describe('form renderer — invalid-submit toast list joiner (objectstack#5407)'
100110
expect(text).toContain('Subject、Account、Status');
101111
// zh's sentence, to prove the joiner is being read from the zh pack and not
102112
// from an `en` fallback that happens to carry the same punctuation.
103-
expect(text).toContain('请检查表单中标记的字段');
113+
expect(text).toContain('无法提交');
104114
});
105115
});

‎ui/packages/components/src/renderers/form/__tests__/form-server-field-errors.test.tsx‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -104,17 +104,20 @@ describe('form renderer — server-rejected fields', () => {
104104
await waitFor(() => expect(stageWrap.contains(document.activeElement)).toBe(true));
105105
});
106106

107-
it('names the rejected fields in the toast', async () => {
107+
it('raises no toast when every rejected field carries its own message (objectstack#25874)', async () => {
108108
const onSubmit = vi.fn().mockRejectedValue(
109109
validationFailure([{ field: 'title', message: 'Title is required' }]),
110110
);
111-
renderForm(FIELDS, onSubmit);
111+
const { container } = renderForm(FIELDS, onSubmit);
112+
const titleWrap = container.querySelector('[data-field="title"]') as HTMLElement;
112113

113114
submit();
114115

115-
await waitFor(() => expect(toastErrorSpy).toHaveBeenCalled());
116-
// The field LABEL, not its machine name.
117-
expect(String(toastErrorSpy.mock.calls[0][0])).toMatch(/Title/);
116+
// The reason is written under the input it belongs to…
117+
await waitFor(() => expect(titleWrap.textContent).toMatch(/Title is required/));
118+
// …so a toast naming the same field, drawn over the dialog's title, would
119+
// only repeat it.
120+
expect(toastErrorSpy).not.toHaveBeenCalled();
118121
});
119122

120123
it('marks every rejected field, not just the first', async () => {

‎ui/packages/components/src/renderers/form/form.tsx‎

Lines changed: 55 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -2843,13 +2843,16 @@ ComponentRegistry.register('form',
28432843
* carries `data-field` (FormItem), so this reaches custom widgets that RHF's
28442844
* own focus cannot (#2793).
28452845
*/
2846-
const revealField = (name: string) => {
2846+
const fieldWrapper = (name: string): HTMLElement | null => {
28472847
const root: ParentNode = formRef.current ?? document;
28482848
const escaped =
28492849
typeof CSS !== 'undefined' && typeof CSS.escape === 'function'
28502850
? CSS.escape(name)
28512851
: name.replace(/["\\]/g, '\\$&');
2852-
const target = root.querySelector<HTMLElement>(`[data-field="${escaped}"]`);
2852+
return root.querySelector<HTMLElement>(`[data-field="${escaped}"]`);
2853+
};
2854+
const revealField = (name: string) => {
2855+
const target = fieldWrapper(name);
28532856
if (target) {
28542857
target.scrollIntoView?.({ behavior: 'smooth', block: 'center' });
28552858
const focusable = target.querySelector<HTMLElement>(
@@ -2860,54 +2863,64 @@ ComponentRegistry.register('form',
28602863
};
28612864

28622865
/**
2863-
* Tell the user WHICH fields are wrong, wherever the verdict came from.
2866+
* Point the user at the fields that are wrong, wherever the verdict came
2867+
* from: reveal and focus the FIRST of them (in declared/visual order, not
2868+
* the caller's key order), activating its tab first when it sits on a
2869+
* background one.
2870+
*
2871+
* No toast. Every field this reaches carries its own message under the
2872+
* input, so a toast naming the same fields only repeated them — truncated
2873+
* after three names, and drawn over the record dialog's title row, which it
2874+
* hid. Moving focus to the first offender is what makes a refused submit
2875+
* visible on a long form; the inline messages say the rest.
28642876
*
2865-
* Toast naming the offending fields, then reveal the FIRST of them (in
2866-
* declared/visual order, not the caller's key order) — activating its tab
2867-
* first when it sits on a background one.
2877+
* Returns the rejected names that have NO drawn input — a field on a
2878+
* predicate-hidden tab (#6237) or section, or hidden by its own rule. Only
2879+
* the SERVER can reject those (their client rules are skipped with them),
2880+
* and nothing inline can carry the message, so the caller must say it at
2881+
* form level instead.
28682882
*
28692883
* Shared by the client-side invalid handler and the SERVER-rejection path:
28702884
* the two failures are the same event as far as the person filling the form
28712885
* is concerned; only the referee differs.
28722886
*/
2873-
const announceFieldErrors = (names: string[]) => {
2874-
if (names.length === 0) return;
2887+
const announceFieldErrors = (names: string[]): string[] => {
2888+
if (names.length === 0) return [];
28752889
setRejectedFieldNames(names);
2876-
const labels = names.map((n) => fieldLabelByName[n] || n);
2877-
const MAX = 3;
2878-
const fieldsText =
2879-
labels.slice(0, MAX).join(t('validation.formInvalidJoiner')) +
2880-
(labels.length > MAX ? '…' : '');
2881-
toast.error(t('validation.formInvalid', { fields: fieldsText }), { id: outcomeToastId });
2882-
28832890
const errored = new Set(names);
2884-
const firstName =
2885-
(fields as FormFieldConfig[])
2891+
const ordered = [
2892+
...(fields as FormFieldConfig[])
28862893
.map((f) => f?.name)
2887-
.find((n): n is string => Boolean(n) && errored.has(n as string)) ?? names[0];
2894+
.filter((n): n is string => Boolean(n) && errored.has(n as string)),
2895+
...names.filter((n) => !(fields as FormFieldConfig[]).some((f) => f?.name === n)),
2896+
];
2897+
// A field is drawn when its wrapper is in the DOM. A background tab's
2898+
// panel stays mounted (CSS-hidden), so its fields count as drawn and are
2899+
// reached below by activating the tab; a predicate-hidden tab's panel is
2900+
// not rendered at all, so its fields do not.
2901+
const undrawn = ordered.filter((n) => !fieldWrapper(n));
2902+
const firstName = ordered.find((n) => !undrawn.includes(n));
2903+
if (!firstName) return undrawn;
28882904

28892905
// In a tabbed layout the offending field may sit on a tab the user is not
2890-
// looking at — naming it is useless if they can't see it. Activate its tab
2891-
// first, then reveal it once that panel has actually been painted (it is
2892-
// display:none until then, so scroll/focus would no-op).
2893-
//
2894-
// Unless the tab is predicate-HIDDEN (#6237): only the SERVER can reject
2895-
// a field there (its client rules are skipped with it), and there is no
2896-
// panel to activate or control to reveal — the toast above already names
2897-
// the field. Recording the activation as a pick anyway would yank the
2898-
// view to that tab whenever its predicate later re-admits it.
2906+
// looking at — the message under it is useless if they can't see it.
2907+
// Activate its tab first, then reveal it once that panel has actually
2908+
// been painted (it is display:none until then, so scroll/focus would
2909+
// no-op). A predicate-HIDDEN tab is never activated: recording that as a
2910+
// pick would yank the view to it whenever its predicate later re-admits
2911+
// it, and a drawn field it also claims is rendered in a visible panel.
28992912
const tabKey = tabKeyByFieldName.get(firstName);
2900-
if (tabKey && hiddenFieldTabKeys.has(tabKey)) return;
2901-
if (tabKey && tabKey !== activeFieldTab) {
2913+
if (tabKey && !hiddenFieldTabKeys.has(tabKey) && tabKey !== activeFieldTab) {
29022914
setPickedFieldTab(tabKey);
29032915
if (typeof requestAnimationFrame === 'function') {
29042916
requestAnimationFrame(() => revealField(firstName));
29052917
} else {
29062918
setTimeout(() => revealField(firstName), 0);
29072919
}
2908-
return;
2920+
return undrawn;
29092921
}
29102922
revealField(firstName);
2923+
return undrawn;
29112924
};
29122925

29132926
// Handle form submission — react-hook-form's validation, then the write.
@@ -3008,11 +3021,14 @@ ComponentRegistry.register('form',
30083021
// this form does not render, fall through: the top-level message
30093022
// concatenates every field's reason, so the part the user cannot see
30103023
// inline is still said out loud instead of silently dropped.
3024+
// The same holds for a rendered-schema field with no DRAWN input
3025+
// (a predicate-hidden tab or section): `announceFieldErrors` names
3026+
// those, and any one of them sends the failure down the same path.
30113027
if (known.length > 0 && known.length === fieldErrors.length) {
3012-
announceFieldErrors(known.map((fe) => fe.field));
3028+
const undrawn = announceFieldErrors(known.map((fe) => fe.field));
30133029
// A fully-attributed rejection is not a form-level failure — the
30143030
// banner would just repeat what is now written under each input.
3015-
return;
3031+
if (undrawn.length === 0) return;
30163032
}
30173033
}
30183034
// A rejected write used to be rendered verbatim, which put raw server
@@ -3055,8 +3071,10 @@ ComponentRegistry.register('form',
30553071
// Client-side (react-hook-form) validation blocked the submit. The
30563072
// per-field errors render inline, but in long forms the offending field
30573073
// is often scrolled out of view — the user clicks 创建 and sees nothing
3058-
// happen. Surface a toast naming the fields so the feedback is visible
3059-
// regardless of scroll position (mirrors the server-error toast above).
3074+
// happen. Move focus to the first offender so the feedback is visible
3075+
// regardless of scroll position. Every name here has a drawn input:
3076+
// react-hook-form validates only mounted controls, and an undrawn field
3077+
// is unmounted, so the returned list is always empty on this path.
30603078
announceFieldErrors(Object.keys(validationErrors || {}));
30613079
});
30623080

@@ -3458,8 +3476,9 @@ ComponentRegistry.register('form',
34583476
// parents still read two ways (objectui#4026). The separator is a
34593477
// property of the locale, so all of them now read
34603478
// `validation.formInvalidJoiner`: the key objectstack#5407 added for the
3461-
// invalid-submit toast a few hundred lines up, which is the same class
3462-
// of truncated-name list, rather than a second gate-only twin that would
3479+
// invalid-submit field list (that toast is gone; the `visibleWhen`
3480+
// refusal a few hundred lines up still joins with it), which is the same
3481+
// class of name list, rather than a second gate-only twin that would
34633482
// reintroduce the divergence.
34643483
const gatedHint = optionGroupGated
34653484
? t('fields.options.selectFirst', {

0 commit comments

Comments
 (0)