Skip to content

Commit a9b36ef

Browse files
fix(fields): hold the filter-condition builder until the object schema answers (#35392)
Fixes #35057 Clause-②: no Metadata-protocol: none ## 维护者速读 1. 用户能看到什么变化:管理员在共享规则里编辑已保存的筛选条件时,字段类型读回来之前,条件编辑器会短暂置灰、不接受输入;读回后照常可编辑,输入的数字按数字保存,不再存成文本。 2. 为什么做:控制台操作体验一系列卡片中的一张;之前的测试修复发现,类型读得慢时,提前输入的数字会被存成文本。 3. 出错会怎样:最坏情况是编辑器一直置灰、改不了条件(读取失败或宿主不提供字段类型时不会置灰);回滚这一个提交即可恢复。 4. 要你做什么:无,席位落地。 ## What changes `ui/packages/fields/src/widgets/FilterConditionField.tsx` (the `filter-condition` widget behind `sys_sharing_rule.criteria_json`): - The schema answer is keyed by the object it answers for, so a render that names a new object never reads the previous object's field types. - `schemaPending` = the host offers `getObjectSchema` and it has not answered for this object yet. While it holds, the builder sits in a `fieldset disabled` with `aria-busy`, and `handleBuilderChange` emits nothing. - A failed read settles to an empty field list and releases the builder. A host with no `getObjectSchema` never holds it. Raw-JSON mode is not held. Route chosen: hold, not retype on arrival. Retyping would have to survive the widget's re-seed effect, which replaces the rows whenever what they emit differs from the stored value, so a held-then-retyped edit would be wiped by that effect. ## The reading (os-dev-report 7002349726) Rows `amount` 5, 6, 12, 30, 100, a `number` field, through the real ObjectQL engine and SqlDriver. Each cell is the amounts returned. | comparand | number | raw driver, `"6"` | engine `where`, `"6"` | engine `filter`, `"6"` | |:--|:--|:--|:--|:--| | `$eq` / implicit | [6] | [6] | [6] | [6] | | `$gt` | [12,30,100] | same | same | same | | `$lte` | [5,6] | same | same | same | | `$gte`+`$lte` 6..30 | [6,12,30] | same | same | same | | `$in` [6,12] | [6,12] | same | same | same | SQLite (better-sqlite3) and PostgreSQL 16.15 gave identical results. No stored filter compares wrongly, and the card stays p2. The engine's number-comparand declared-type door already narrows a numeric string to its number before any driver. This PR removes the race at the producer. ## Tests New pin `FilterConditionField.schemaPendingHold-35057.test.tsx` (6 cases): - A held `getObjectSchema`, for implicit equality, `$gt` and `$lte`: the stored row's box is disabled, and a change fired at it emits nothing. After the answer, typing `6` emits the number (`{"amount":{"$gt":6}}`). - CONTROL: when the schema answers first, the same number is emitted straight away. - Bounds of the hold: a failed read releases the builder, and a host without `getObjectSchema` never holds it. Both of these still emit the typed text, because no type is known. <details><summary>Readings</summary> All readings below were taken on the working tree that was then committed unchanged as `53cd5c9d` (component blob `ace20001`), on base `8b550f81`. The reverse verification ran before the commit, so its restore was proven by hash rather than by checking out `HEAD`. - Pin: `pnpm --dir ui exec vitest run packages/fields/src/widgets/__tests__/FilterConditionField.schemaPendingHold-35057.test.tsx`: Tests 6 passed. - Reverse verification, component file swapped back to base `8b550f81` and then restored (hash `ace20001` checked after restore): 4 failed, 2 passed. The three held cases failed with "Received element is not disabled", and so did the failed-read release case, whose pre-answer leg asserts the hold. The two controls passed. This is the predicted direction. - `pnpm --dir ui exec vitest run packages/fields/src/widgets/` on the final tree: Test Files 147 passed (147), Tests 1437 passed (1437). - `pnpm --filter @object-ui/fields run type-check`: 0 `error TS`. - Derived gates (`dispatch-gates --commands`): 38 derived, 38 run, every one exit 0. That includes `pnpm --dir ui exec vitest run scripts/` (Test Files 171 passed, 2 skipped). </details> ## Acceptance notes - The app-shell `FilterConditionField` (dataset / related-list filters) has no such window, read at source: it mounts the builder only once the caller's typed field list is non-empty. - A criteria already stored with a string bound is not rewritten. The server reads it as the number it spells. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CajiB6BSQKWowy6YLB)_ Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8596c80 commit a9b36ef

3 files changed

Lines changed: 196 additions & 12 deletions

File tree

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
fix(fields): the filter-condition builder takes no edit until the object's schema has answered, so a number bound is never saved as text
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
The criteria builder (the `filter-condition` widget a sharing rule's criteria uses) shows a stored criteria as soon as it opens, but it reads the object's field types from a schema request that answers later. Until that answer arrived, a value box was a plain text box, and a number typed into it was saved as text: `{"amount":{"$gt":"6"}}` instead of `{"amount":{"$gt":6}}`. Once the answer arrived, the box changed to a number box but the text already saved stayed. The server reads such a value as the number it spells, so this changed no rule's matches. It did make the saved document depend on whether the admin typed before or after a network read.
11+
12+
The builder's controls are now disabled while that request is in flight, and nothing is emitted from them. When the answer arrives they are enabled, and each value box has its column's type. If the request fails, the builder is released with no field types, as before. A host that offers no schema request never holds the builder. The raw-JSON editor is not held.
13+
14+
No metadata key, value or default changes. A criteria already saved is not rewritten.

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

Lines changed: 45 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -679,24 +679,50 @@ export function FilterConditionField({
679679
const dependentValues: Record<string, any> = (props as any).dependentValues ?? {};
680680
const objectName = String(dependentValues.object_name ?? '');
681681

682-
const [fields, setFields] = React.useState<FilterFieldDef[] | null>(null);
682+
/**
683+
* The schema's answer, keyed by the object it answers for, so a render that
684+
* names a new object never reads the previous object's field types.
685+
*/
686+
const [schemaAnswer, setSchemaAnswer] = React.useState<{ object: string; fields: FilterFieldDef[] } | null>(null);
687+
const canReadSchema = !!dataSource && !!objectName && typeof dataSource.getObjectSchema === 'function';
683688

684689
React.useEffect(() => {
685-
setFields(null);
686-
if (!dataSource || !objectName || typeof dataSource.getObjectSchema !== 'function') return;
690+
if (!canReadSchema) return;
687691
let cancelled = false;
688692
(async () => {
689693
try {
690694
const schema = await dataSource.getObjectSchema(objectName);
691-
if (!cancelled) setFields(deriveFilterFields(schema));
695+
if (!cancelled) setSchemaAnswer({ object: objectName, fields: deriveFilterFields(schema) });
692696
} catch {
693-
if (!cancelled) setFields([]);
697+
if (!cancelled) setSchemaAnswer({ object: objectName, fields: [] });
694698
}
695699
})();
696700
return () => {
697701
cancelled = true;
698702
};
699-
}, [dataSource, objectName]);
703+
}, [canReadSchema, dataSource, objectName]);
704+
705+
const fields: FilterFieldDef[] | null =
706+
canReadSchema && schemaAnswer?.object === objectName ? schemaAnswer.fields : null;
707+
708+
/**
709+
* The schema read is still in flight, so no column has a type yet.
710+
*
711+
* A stored row is on screen before `getObjectSchema` answers, with a TEXT
712+
* box for its value: the builder types the box from a field list that is
713+
* still empty. A bound typed into that box was emitted as the string the box
714+
* holds — `{"amount":{"$gt":"6"}}` rather than `{"amount":{"$gt":6}}` — and
715+
* nothing retyped it when the schema arrived, so what got stored depended on
716+
* whether the admin typed before or after a network read.
717+
*
718+
* So the builder takes no edit until the schema has answered: its controls
719+
* sit in a disabled fieldset, and {@link handleBuilderChange} emits nothing
720+
* while this holds. A failed read settles to an empty field list and
721+
* releases the hold, and a host with no `getObjectSchema` never holds at
722+
* all — there is no answer coming, so holding would lock the builder for
723+
* good. Raw-JSON mode is not held: its text is the author's own document.
724+
*/
725+
const schemaPending = canReadSchema && fields === null;
700726

701727
const rawValue = React.useMemo(() => stringifyValue(value), [value]);
702728

@@ -772,6 +798,7 @@ export function FilterConditionField({
772798
}, [group, storedKey, localKey]);
773799

774800
const handleBuilderChange = (g: BuilderGroup) => {
801+
if (schemaPending) return;
775802
setLocalGroup(g);
776803
const mongo = filterGroupToMongo(g, typeOf);
777804
onChange((mongo == null ? '' : JSON.stringify(mongo)) as any);
@@ -838,12 +865,18 @@ export function FilterConditionField({
838865
)}
839866
</>
840867
) : (
841-
<FilterBuilder
842-
fields={fields ?? []}
843-
value={localGroup as any}
844-
onChange={handleBuilderChange as any}
845-
extraOperators={FILTER_CONDITION_EXTRA_OPERATORS}
846-
/>
868+
<fieldset
869+
disabled={schemaPending}
870+
aria-busy={schemaPending || undefined}
871+
className="m-0 min-w-0 border-0 p-0"
872+
>
873+
<FilterBuilder
874+
fields={fields ?? []}
875+
value={localGroup as any}
876+
onChange={handleBuilderChange as any}
877+
extraOperators={FILTER_CONDITION_EXTRA_OPERATORS}
878+
/>
879+
</fieldset>
847880
)}
848881
{/*
849882
The server refuses to save a criteria that would select every record
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* A number bound typed before `getObjectSchema` answers is never stored as a
11+
* string (objectstack#35057).
12+
*
13+
* The widget draws a stored row as soon as it mounts, but the row's value box
14+
* is typed from the object schema, which arrives later. Until it did, the box
15+
* was a TEXT input, and a bound typed into it was emitted as the string it
16+
* held: with the schema held back, typing `6` into a stored `$gt` row emitted
17+
* `{"amount":{"$gt":"6"}}`, and the schema's arrival retyped the box to a
18+
* number input without re-emitting, so the string was what got saved. With the
19+
* schema answering first the same keystroke emitted `{"amount":{"$gt":6}}`.
20+
* The stored document depended on a network race.
21+
*
22+
* What is pinned is the EMITTED document, beside the browser-level fact that
23+
* the controls are disabled while the read is in flight. Both bounds of the
24+
* hold are pinned too: a failed read releases it, and a host with no
25+
* `getObjectSchema` never holds, because no answer is coming.
26+
*/
27+
import { describe, it, expect, vi } from 'vitest';
28+
import React from 'react';
29+
import { render, screen, fireEvent, act } from '@testing-library/react';
30+
import '@testing-library/jest-dom';
31+
import { FilterConditionField } from '../FilterConditionField';
32+
33+
const OBJECT_SCHEMA = {
34+
name: 'account',
35+
fields: [{ name: 'amount', label: 'Amount', type: 'number' }],
36+
};
37+
38+
/** A `getObjectSchema` that answers only when the test says so. */
39+
function heldSchema(answer: () => Promise<unknown>) {
40+
let release: () => void = () => {};
41+
const gate = new Promise<void>((resolve) => {
42+
release = resolve;
43+
});
44+
const dataSource = {
45+
getObjectSchema: async () => {
46+
await gate;
47+
return answer();
48+
},
49+
};
50+
return { dataSource, release: () => act(async () => release()) };
51+
}
52+
53+
/** The widget under its real contract: a parent that stores what it emits. */
54+
function renderWidget(initial: string, dataSource: unknown) {
55+
const onChange = vi.fn();
56+
function Harness() {
57+
const [value, setValue] = React.useState<string | object>(initial);
58+
return (
59+
<FilterConditionField
60+
value={value}
61+
onChange={(next: string | object) => {
62+
onChange(next);
63+
setValue(next);
64+
}}
65+
dataSource={dataSource}
66+
dependentValues={{ object_name: 'account' }}
67+
field={{ name: 'criteria_json', type: 'textarea' }}
68+
/>
69+
);
70+
}
71+
render(<Harness />);
72+
return onChange;
73+
}
74+
75+
const emitted = (onChange: ReturnType<typeof vi.fn>) => onChange.mock.calls.map((c) => String(c[0]));
76+
77+
describe('a number bound and a schema that has not answered yet', () => {
78+
it.each([
79+
['implicit equality', '{"amount":5}', '{"amount":6}'],
80+
['$gt', '{"amount":{"$gt":5}}', '{"amount":{"$gt":6}}'],
81+
['$lte', '{"amount":{"$lte":5}}', '{"amount":{"$lte":6}}'],
82+
])('%s: no edit is taken before the answer, and the bound typed after it is a number', async (_label, stored, typed) => {
83+
const { dataSource, release } = heldSchema(async () => OBJECT_SCHEMA);
84+
const onChange = renderWidget(stored, dataSource);
85+
86+
// The stored row is on screen, but its box takes no input yet.
87+
const early = await screen.findByDisplayValue('5');
88+
expect(early).toBeDisabled();
89+
// A browser sends no input to a disabled control; a change event fired at
90+
// it anyway is still not emitted. (`7`, so the post-answer `6` below is a
91+
// real change of the box's value.)
92+
fireEvent.change(early, { target: { value: '7' } });
93+
expect(onChange).not.toHaveBeenCalled();
94+
95+
await release();
96+
const box = await screen.findByRole('spinbutton');
97+
expect(box).toBeEnabled();
98+
fireEvent.change(box, { target: { value: '6' } });
99+
expect(emitted(onChange)).toEqual([typed]);
100+
for (const doc of emitted(onChange)) {
101+
expect(doc, 'a string comparand reached storage').not.toMatch(/"[67]"/);
102+
}
103+
});
104+
105+
it('CONTROL: the schema answering first emits the same number straight away', async () => {
106+
const onChange = renderWidget('{"amount":{"$gt":5}}', { getObjectSchema: async () => OBJECT_SCHEMA });
107+
const box = await screen.findByRole('spinbutton');
108+
expect(box).toBeEnabled();
109+
fireEvent.change(box, { target: { value: '6' } });
110+
expect(emitted(onChange)).toEqual(['{"amount":{"$gt":6}}']);
111+
});
112+
});
113+
114+
describe('the bounds of the hold', () => {
115+
it('a failed schema read releases the builder', async () => {
116+
const { dataSource, release } = heldSchema(async () => {
117+
throw new Error('schema read failed');
118+
});
119+
const onChange = renderWidget('{"amount":5}', dataSource);
120+
expect(await screen.findByDisplayValue('5')).toBeDisabled();
121+
122+
await release();
123+
const box = screen.getByDisplayValue('5');
124+
expect(box).toBeEnabled();
125+
// No schema, no type: the box holds text, and the edit is taken as typed.
126+
fireEvent.change(box, { target: { value: '6' } });
127+
expect(emitted(onChange)).toEqual(['{"amount":"6"}']);
128+
});
129+
130+
it('a host with no getObjectSchema never holds the builder', async () => {
131+
const onChange = renderWidget('{"amount":5}', {});
132+
const box = await screen.findByDisplayValue('5');
133+
expect(box).toBeEnabled();
134+
fireEvent.change(box, { target: { value: '6' } });
135+
expect(emitted(onChange)).toEqual(['{"amount":"6"}']);
136+
});
137+
});

0 commit comments

Comments
 (0)