Skip to content

Commit 6303e74

Browse files
fix(fields): a refused location draft blocks the record form's save (#32224)
<!-- claude-projects-attribution: {"github_login":"huangyiirene"} --> _Requested by **Irene** · [project thread](https://claude.ai/code/project/chan_01TJXtQ1tVD26ecLDZxFS67x?thread=cmsg_01TJXtQ1tVD26ecLDZxFS67xSyNNRkJL7R2XBYfyfNzGZE)_ Fixes #32139 Clause-②: no Metadata-protocol: none ## 维护者速读 - **改了什么**:位置字段里输入的不是坐标(如 `Shenzhen 深圳`)时,表单现在把它当作该字段的校验错误,阻止保存,并在字段下用当前语言显示原因;不再静默保存。 - **为什么改**:之前控件拒收了这段文字,但表单不知道,点「更新」照样成功;用户先清空再输入时,原有位置被写成 `null`,提示却是保存成功。 - **风险与回滚**:只影响位置字段输错时的提交;合法坐标与故意清空照旧保存。回滚即还原两个源文件。 - **先看**:`ui/packages/fields/src/widgets/LocationField.tsx`(上报拒收)、`ui/packages/components/src/renderers/form/form.tsx`(把 `location` 加入上报白名单)、`ObjectForm.locationRefusal.test.tsx`(编辑表单端到端)。 - **两分钟验证**:`pnpm --dir ui exec vitest run packages/plugin-form/src/ObjectForm.locationRefusal.test.tsx`,预期 11 个全绿;或在 showcase 编辑任一 Account,Headquarters 输入 `Shenzhen 深圳` 点 Update,预期字段下出现红字、对话框不关闭。 - **需要你做的**:无,等席位评审后落地。 ## What changes - `LocationField` reports its refusal through `onInvalidInputChange`, the channel the date picker already uses for text it cannot read (objectstack#27483). It reports when the refusal message changes, withdraws it when the refusal clears, when the field turns readonly, and on unmount. - The record-form validation seam is `INVALID_INPUT_REPORTING_WIDGET_TYPES` in `ui/packages/components/src/renderers/form/form.tsx`. Adding `location` to it hands the widget the callback, and the form's existing `invalidInput` validator turns the report into the field's error, which blocks submit the way a missing required value does. No new validator, no new locale key: the message is the widget's existing translated refusal sentence (`fields.location.refusedFormat` / `refusedRange` / `refusedResidue*`, present in every pack). - No double display: the widget keeps drawing its own line until the host's `error` carries the same sentence, then leaves it to the form's `FormMessage`, so the reason never blinks out between the keystroke and the asynchronous validation. Hosts that do not pass the callback (inline edit through `FieldEditWidget`) keep the widget's own line exactly as before. - Clearing the box on purpose still emits `null` and saves it; a valid pair still emits and saves. ## Tests - New top-level describe in `ui/packages/plugin-form/src/ObjectForm.locationRefusal.test.tsx`, driving a real edit `ObjectForm` with `userEvent` (typing, then a click on the submit button): non-coordinate text typed after clearing and typed over the selected value both refuse Update with `update` never called, `aria-invalid="true"`, the sentence in the form's own error line and shown once; the zh-CN reader sees the Chinese sentence; a valid pair saves; a deliberate clear saves `null`; correcting a refused draft withdraws the error and saves. - New top-level describe in `ui/packages/fields/src/__tests__/LocationField.refusalDiagnostic.test.tsx` for the widget side: report, withdraw on clear and on a valid pair, once per message change, withdraw on unmount, own line until the host shows the sentence, own line kept without the channel. - Existing pins changed (deviation, named for review): the create-mode pins in `ObjectForm.locationRange`, `ObjectForm.locationRefusal`, `ObjectForm.locationResidue` and `ObjectForm.locationStoredRange` asserted that a refused coordinate still let the create go through (`create` called, `place` absent). That half is exactly what this card reverses, so each now asserts the stronger reading: nothing is written at all and the field carries the refusal. Every "never stored" assertion, every announcement assertion and every pass-through assertion is unchanged. The stored-range pin still proves the refusal is the widget's and not the `location` rule's: the field error is the widget's `Not saved:` sentence, never the rule's `Invalid location:`. ## Acceptance notes - **Second observation on the card (not fixed here):** a no-change edit sends the whole record. That is `dirtyEditPayload` in `ui/packages/plugin-form/src/sanitize.ts` by design (objectui#10156): an EMPTY diff sends the full sanitized payload, so a save with nothing changed stays a real request with the OCC guard and a server record for `onSuccess`. The card's typed-over case is that path: the refusal left nothing changed. A whole record sent TOGETHER with a real change (`hq: null` beside every other field, as the card reports) would mean the loaded-record snapshot did not apply on the host the QA run used; that is not measured here. - The QA route that wrote `null` is reproduced by clearing the box first, which emits a legitimate `null` before the refused text is typed. The other route (typing over the selected value) left the old value standing and still reported success. Both are now refused. ## Verification <details><summary>Repro on origin/main 8523ef9 (new pins, before the fix)</summary> ``` × non-coordinate text cleared first, then typed refuses the save and writes nothing expected "vi.fn()" to not be called at all, but actually been called 1 times ("place": null) × non-coordinate text typed over the selected value refuses the save and writes nothing expected "vi.fn()" to not be called at all, but actually been called 1 times ("place": { lat: 22.54, lng: 114.05 }) × the refusal is translated: a zh-CN reader sees the field error in Chinese ("place": null) × correcting a refused draft withdraws the error and saves the pair ("place": null) Tests 4 failed | 7 passed (11) ``` </details> <details><summary>After the fix</summary> Head `21e59a53` (fix `d39e14b9` + changeset `da15605a` + merge of `origin/main` `171cf6d9`, which touched `packages/spec` only). ``` pnpm --dir ui exec vitest run packages/plugin-form/src/ObjectForm.location packages/fields/src/__tests__/LocationField packages/components/src/renderers/form/__tests__/form-invalid-input-refuses-submit-27483.test.tsx packages/fields/src/__tests__/date-picker-invalid-text-blocks-submit-27483.test.tsx Test Files 14 passed (14) Tests 219 passed (219) ``` ``` pnpm --filter @object-ui/fields run type-check :: exit 0 pnpm --filter @object-ui/components run type-check :: exit 0 pnpm --filter @object-ui/plugin-form run type-check :: exit 0 pnpm --dir ui exec vitest run packages/fields/ packages/components/ packages/plugin-form/ Test Files 1006 passed | 2 skipped (1008) Tests 11628 passed | 32 skipped (11660) ``` </details> <details><summary>Reverse verification (fix committed first, then reverted on disk, then restored from HEAD)</summary> - Both source files restored from origin/main: 19 of 69 pins red across the five location files: the four refusal pins of the new edit-form describe (its two preservation pins, valid pair saves and deliberate clear writes `null`, stay green as they should), five of the six new widget pins (the sixth, own line kept without the channel, is a preservation pin), and the ten create-mode pins whose submit is now refused. Restored with `git checkout HEAD --`, `git diff HEAD` empty. - Only the form seam removed (`location` dropped from `INVALID_INPUT_REPORTING_WIDGET_TYPES` via `scripts/ablation-replace.mjs`): 6 of 11 red in `ObjectForm.locationRefusal.test.tsx`; restored blob identical to HEAD. </details> <details><summary>Gates</summary> All 36 commands `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` derives for this diff exit 0, plus `node scripts/check-sdui-manifest.mjs` (derived) and `pnpm --dir ui run check:spec-symbols` and `pnpm --dir ui run check:new-line-citations` (not derived), both exit 0. `pnpm check:type-check-debt` needed three runs: a 300 s local timeout and a verify-lock queue behind this card's own test run were NOT MEASURED, the third run on `21e59a53` exited 0. `--ran` reconciliation: 36 derived, 36 run, 0 NOT-MEASURED, 0 UNRUN. Every other CI family is read from this PR's check-runs. </details> --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent ca2a2e9 commit 6303e74

8 files changed

Lines changed: 353 additions & 29 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@object-ui/fields': patch
3+
'@object-ui/components': patch
4+
---
5+
6+
fix(fields): a refused location draft now blocks the record form's save
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
Text in a `location` box that is not a coordinate pair (`Shenzhen 深圳`) was refused by the widget but never reached the form, so the form value stayed what it was and Update saved it with a success message. When the person had emptied the box first, the stored location was overwritten with `null`. `LocationField` now reports the refusal through `onInvalidInputChange`, and the form renderer turns it into the field's validation error, which blocks submit and is drawn by `<FormMessage/>` in the reader's language. Clearing the box on purpose still writes `null`, and a valid pair still saves. Hosts that do not pass `onInvalidInputChange` (inline edit) keep the widget's own refusal line, as before.

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1377,8 +1377,12 @@ function stripRegisteredFieldProps(type: string, props: RenderFieldProps): Rende
13771377
/** The registered widgets whose pick writes `lookupAutofill` targets through `onAutofill`. */
13781378
const LOOKUP_AUTOFILL_WIDGET_TYPES: ReadonlySet<string> = new Set(['lookup', 'master_detail']);
13791379

1380-
/** The registered widgets that fire `onInvalidInputChange`: the date picker's two faces. */
1381-
const INVALID_INPUT_REPORTING_WIDGET_TYPES: ReadonlySet<string> = new Set(['date', 'datetime']);
1380+
/**
1381+
* The registered widgets that fire `onInvalidInputChange`: the date picker's two
1382+
* faces, and the location box, whose refused coordinate text is never written
1383+
* (objectstack#32139).
1384+
*/
1385+
const INVALID_INPUT_REPORTING_WIDGET_TYPES: ReadonlySet<string> = new Set(['date', 'datetime', 'location']);
13821386

13831387
/**
13841388
* FullscreenTextarea — `<Textarea>` with a top-right "expand" button that

‎ui/packages/fields/src/__tests__/LocationField.refusalDiagnostic.test.tsx‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -315,3 +315,78 @@ describe('LocationField leaves the published `error` slot single-authored (objec
315315
expect(box()).toHaveAttribute('aria-invalid', 'true');
316316
});
317317
});
318+
319+
/* -------------------------------------------------------------------------- */
320+
/* objectstack#32139 — the refusal is reported to the host. */
321+
/* -------------------------------------------------------------------------- */
322+
323+
describe('LocationField reports a refused draft through `onInvalidInputChange` (objectstack#32139)', () => {
324+
const FORMAT = 'Not saved: enter a latitude, longitude pair (example: 30.2741, 120.1551).';
325+
326+
it('reports the refusal, and withdraws it once the box is cleared', async () => {
327+
const user = userEvent.setup();
328+
const onInvalidInputChange = vi.fn();
329+
const { onChange } = mount(STORED, { onInvalidInputChange });
330+
await user.clear(box());
331+
await user.keyboard('Shenzhen');
332+
expect(onInvalidInputChange).toHaveBeenLastCalledWith(FORMAT);
333+
334+
await user.clear(box());
335+
expect(onInvalidInputChange).toHaveBeenLastCalledWith(null);
336+
// Clearing on purpose is still a write of `null`.
337+
expect(onChange).toHaveBeenLastCalledWith(null);
338+
});
339+
340+
it('withdraws the refusal when a valid pair replaces it, and emits the pair', () => {
341+
const onInvalidInputChange = vi.fn();
342+
const { onChange } = mount(STORED, { onInvalidInputChange });
343+
fireEvent.change(box(), { target: { value: '12abc, 34' } });
344+
expect(onInvalidInputChange).toHaveBeenLastCalledWith(expect.stringContaining('Not saved:'));
345+
fireEvent.change(box(), { target: { value: '30.2741, 120.1551' } });
346+
expect(onInvalidInputChange).toHaveBeenLastCalledWith(null);
347+
expect(onChange).toHaveBeenLastCalledWith({ lat: 30.2741, lng: 120.1551 });
348+
});
349+
350+
it('reports each arm once per change of message, never per render', () => {
351+
const onInvalidInputChange = vi.fn();
352+
mount(STORED, { onInvalidInputChange });
353+
// Nothing refused yet: nothing reported.
354+
expect(onInvalidInputChange).not.toHaveBeenCalled();
355+
fireEvent.change(box(), { target: { value: 'abc' } });
356+
fireEvent.change(box(), { target: { value: 'abcd' } });
357+
expect(onInvalidInputChange).toHaveBeenCalledTimes(1);
358+
fireEvent.change(box(), { target: { value: '999, 999' } });
359+
expect(onInvalidInputChange).toHaveBeenCalledTimes(2);
360+
expect(onInvalidInputChange).toHaveBeenLastCalledWith(expectedRangeMessage({ lat: 999, lng: 999 }));
361+
});
362+
363+
it('withdraws a standing refusal on unmount', () => {
364+
const onInvalidInputChange = vi.fn();
365+
const { unmount } = render(
366+
<LocationField field={field} value={STORED} onChange={vi.fn()} onInvalidInputChange={onInvalidInputChange} />,
367+
);
368+
fireEvent.change(box(), { target: { value: 'abc' } });
369+
expect(onInvalidInputChange).toHaveBeenLastCalledWith(FORMAT);
370+
unmount();
371+
expect(onInvalidInputChange).toHaveBeenLastCalledWith(null);
372+
});
373+
374+
it('draws its own line until the host shows the same sentence, then leaves it to the host', () => {
375+
const onInvalidInputChange = vi.fn();
376+
const props = { field, value: STORED, onChange: vi.fn(), onInvalidInputChange };
377+
const { container, rerender } = render(<LocationField {...props} />);
378+
fireEvent.change(box(), { target: { value: 'abc' } });
379+
// The host has not validated yet: the reason must not blink out.
380+
expect(diagnostic(container)).toBe(FORMAT);
381+
// The host's `<FormMessage/>` now draws it: the widget does not repeat it.
382+
rerender(<LocationField {...props} error={FORMAT} />);
383+
expect(diagnostic(container)).toBeNull();
384+
expect(box()).toHaveAttribute('aria-invalid', 'true');
385+
});
386+
387+
it('a host without the channel keeps the widget\'s own line (inline edit)', () => {
388+
const { container } = mount(STORED, { error: FORMAT });
389+
fireEvent.change(box(), { target: { value: 'abc' } });
390+
expect(diagnostic(container)).toBe(FORMAT);
391+
});
392+
});

‎ui/packages/fields/src/widgets/LocationField.tsx‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,15 @@ function placeholderPair(t: TranslateFn): string {
439439
* which read the spec spelling first. That cost was presented and accepted as
440440
* part of the A1 ruling; it is not an oversight to route around with a shim.
441441
*/
442-
export function LocationField({ value, onChange, field, readonly, error, ...props }: FieldWidgetComponentProps<LocationValue | null>) {
442+
export function LocationField({
443+
value,
444+
onChange,
445+
field,
446+
readonly,
447+
error,
448+
onInvalidInputChange,
449+
...props
450+
}: FieldWidgetComponentProps<LocationValue | null>) {
443451
const config = field;
444452

445453
/**
@@ -518,12 +526,50 @@ export function LocationField({ value, onChange, field, readonly, error, ...prop
518526
setDraft(coordinateText(value));
519527
}, [value, draft, refusalError]);
520528

529+
/**
530+
* Tell the host about a refused draft (objectstack#32139).
531+
*
532+
* A refusal never reaches `onChange`, so the form value stays what it was —
533+
* `null` after the person first emptied the box — and the form saved it with
534+
* a success message while the box still showed the refused text. Through
535+
* `onInvalidInputChange` the form renderer turns the refusal into this
536+
* field's validation error, which blocks submit the way a missing required
537+
* value does. Reported when the refusal changes, withdrawn once it clears,
538+
* when the field turns readonly, and on unmount — the date picker's pattern
539+
* for the same channel.
540+
*/
541+
const invalidMessage = readonly ? null : refusalError;
542+
const reportInvalid = useRef(onInvalidInputChange);
543+
useEffect(() => {
544+
reportInvalid.current = onInvalidInputChange;
545+
});
546+
const reported = useRef<string | null>(null);
547+
useEffect(() => {
548+
if (reported.current === invalidMessage) return;
549+
reported.current = invalidMessage;
550+
reportInvalid.current?.(invalidMessage);
551+
}, [invalidMessage]);
552+
useEffect(() => () => {
553+
if (reported.current === null) return;
554+
reported.current = null;
555+
reportInvalid.current?.(null);
556+
}, []);
557+
521558
if (readonly) {
522559
// The STORED value, never the draft: a readonly field renders what is
523560
// saved, and nothing can have been typed into it.
524561
return <span className="text-sm">{coordinateText(value) || <EmptyValue />}</span>;
525562
}
526563

564+
/**
565+
* The refusal line this widget draws itself. A host that takes the report
566+
* draws the same sentence as the field's error (`<FormMessage/>`) once its
567+
* validation has run, and from then on the widget's copy would repeat it; it
568+
* stays up until then, so the reason never blinks out between the keystroke
569+
* and the host's asynchronous validation.
570+
*/
571+
const ownNotice = refusalError && !(onInvalidInputChange && error === refusalError) ? refusalError : null;
572+
527573
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
528574
const text = e.target.value;
529575
// The box keeps what was typed — including text about to be refused, which
@@ -592,7 +638,7 @@ export function LocationField({ value, onChange, field, readonly, error, ...prop
592638
// produce (objectui#6716). Same OR, and same reason, as `ObjectField`.
593639
aria-invalid={!!error || !!refusalError}
594640
/>
595-
{refusalError && <p className="text-xs text-red-500">{refusalError}</p>}
641+
{ownNotice && <p className="text-xs text-red-500">{ownNotice}</p>}
596642
</div>
597643
);
598644
}

‎ui/packages/plugin-form/src/ObjectForm.locationRange.test.tsx‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,15 @@ const waitInput = (c: HTMLElement, name: string) =>
7676
return el;
7777
});
7878

79+
/**
80+
* The form's own error line for a field — `<FormMessage/>`, the text a submit
81+
* refusal draws — or `null` while the field carries none. Distinct from the
82+
* widget's own refusal line, which shows before any validation has run.
83+
*/
84+
function formError(container: HTMLElement, name: string): string | null {
85+
return container.querySelector(`[data-field="${name}"] [id$="-form-item-message"]`)?.textContent ?? null;
86+
}
87+
7988
/** Type a title + a coordinate string into a real create form and submit it. */
8089
async function submitWith(coordinateText: string) {
8190
const ds = makeDS();
@@ -90,8 +99,16 @@ async function submitWith(coordinateText: string) {
9099
fireEvent.change(await waitInput(container, 'place'), { target: { value: coordinateText } });
91100
fireEvent.submit(container.querySelector('form') as HTMLFormElement);
92101

93-
await waitFor(() => expect(ds.create).toHaveBeenCalled());
94-
return { payload: ds.create.mock.calls[0][1] as Record<string, unknown>, container };
102+
// Settle either way: since objectstack#32139 a refused coordinate is the
103+
// field's validation error, so the submit writes nothing and `create` is
104+
// never called — waiting on `create` alone would wait on the thing under test.
105+
await waitFor(() => {
106+
if (!ds.create.mock.calls.length && formError(container, 'place') === null) {
107+
throw new Error('form has neither written nor refused yet');
108+
}
109+
});
110+
const payload = ds.create.mock.calls[0]?.[1] as Record<string, unknown> | undefined;
111+
return { payload, written: payload !== undefined, container };
95112
}
96113

97114
describe('ObjectForm never stores an out-of-range location (objectui#6714)', () => {
@@ -104,24 +121,26 @@ describe('ObjectForm never stores an out-of-range location (objectui#6714)', ()
104121
refused.success ? [] : refused.error.issues.map((i: any) => `${i.code}@[${i.path.join('.')}]`),
105122
).toEqual(['too_big@[lat]', 'too_big@[lng]']);
106123

107-
const { payload } = await submitWith('999, 999');
108-
expect(payload.place).toBeUndefined();
109-
expect(payload).toMatchObject({ title: 'HQ' });
124+
// Since objectstack#32139 the refusal also blocks the submit: nothing at
125+
// all is written, and the form says why on the field.
126+
const { written, container } = await submitWith('999, 999');
127+
expect(written).toBe(false);
128+
expect(formError(container, 'place')).toContain('Not saved:');
110129
});
111130

112131
it('passes an in-range coordinate through to the data source unchanged', async () => {
113132
// The other half, and the pass-through evidence the measurement rests on:
114133
// whatever the widget emits is what gets stored, byte for byte. Nothing on
115134
// this path would have caught the bad value — which is why the widget must.
116135
const { payload } = await submitWith('30.2741, 120.1551');
117-
expect(payload.place).toEqual({ lat: 30.2741, lng: 120.1551 });
118-
expect(LOCATION_SCHEMA.safeParse(payload.place).success).toBe(true);
136+
expect(payload?.place).toEqual({ lat: 30.2741, lng: 120.1551 });
137+
expect(LOCATION_SCHEMA.safeParse(payload?.place).success).toBe(true);
119138
});
120139

121140
it('stores nothing the platform validator would refuse, for either input', async () => {
122141
for (const typed of ['999, 999', '91, 0', '0, 181', '30.2741, 120.1551']) {
123142
const { payload } = await submitWith(typed);
124-
if (payload.place !== undefined) {
143+
if (payload?.place !== undefined) {
125144
expect(LOCATION_SCHEMA.safeParse(payload.place).success, `stored for "${typed}"`).toBe(true);
126145
}
127146
}

0 commit comments

Comments
 (0)