Skip to content

Commit 3c535ee

Browse files
fix(fields): the grid reads a boolean column as a boolean in its requiredWhen / readonlyWhen rules (#35074)
🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WGufzi3ezPzTysQPDEjmVz Fixes #34972 repo:objectstack#3 · os-support-ai · session_01WGufzi3ezPzTysQPDEjmVz Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:主从表单的行内表格在计算每个单元格的 `requiredWhen` / `readonlyWhen` 时,把布尔列(下拉框里存的字符串 `'true'` / `'false'`)按真正的布尔值来读;单元格显示的内容和保存出去的数据都不变。 - 为什么改:布尔字段在表格里被画成选项值为字符串的下拉框,`record.won == true` 拿字符串去比布尔,必填标记和只读锁显示的状态与服务端相反;服务端(#34965 之后)按布尔判定,于是用户看到表格没提示、保存却被拒。 - 风险与回滚:只改规则求值时看到的那份行数据,读法与服务端写入归一化 `BOOLEAN_READINGS` 一致(`'true'`/`'1'`/`1` 与 `'false'`/`'0'`/`0`)。识别布尔列靠"select 且恰好两个选项 `'true'`/`'false'`"这一形状:若某个真正的 select 字段恰好就用这两个字符串当选项,它在规则里会被读成布尔(见 Acceptance notes)。回滚即撤销本 PR。 - 先看:`ui/packages/fields/src/widgets/GridField.tsx`(`ruleRecordOf`、`isBooleanSelectColumn` 与 `cellRules` 的改动)、`ui/packages/fields/src/widgets/GridField.test.tsx`(末尾新增的 describe)。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/fields/src/widgets/GridField.test.tsx`(需先构建 fields 的依赖闭包),预期 51 个测试全部通过,其中新增 4 个。 - 需要你做的:无,席位落地。 ## What changes - **`@object-ui/fields` — `GridField` cell rules.** `cellRules` used to hand the raw row to `resolveFieldRuleState`. A boolean / toggle child field is derived by `@object-ui/plugin-form` (`fieldTypeToColumnType`, `optionsFor` in `deriveMasterDetail.ts`) into a `select` column whose options store the strings `'true'` / `'false'`, and the select cell writes that string into the row. So `record.won == true` compared a string, and the required marker / readonly lock showed the opposite of what the server enforces. - New `isBooleanSelectColumn`: a `select` column whose exactly two options are `'true'` and `'false'` (the derived shape; a grid column carries no field definition, so the option pair is what names the type here). - New `ruleRecordOf`: the row the predicate reads as `record`, with each boolean column's cell read through `BOOLEAN_READINGS`, the same readings and comparison (SameValueZero, via `Map`) as the engine's write normalisation from #34965. Every other value is left as is. It copies only when a cell is actually read, and never mutates the row. - Boolean columns are taken from **all** columns (shown or `defaultHidden`), since a predicate may read any cell. - `readonlyWhen` shares the same path (`cellRules`), so it is covered. The grid has no `visibleWhen` reader; nothing to change there. - What the cell displays and what the row saves are unchanged. The save path does send the string, but since #34965 the engine stores it as a boolean, so the stored value is already the boolean; this PR does not touch the save path. - **Changeset:** `@object-ui/fields` patch, with both declaration lines. ## Tests New top-level describe in the shared harness `GridField.test.tsx`, "a boolean column read as a boolean by the cell rules": - `requiredWhen: record.won == true`: the row holding `'true'` gets the required marker, the row holding `'false'` gets none. - A stored boolean `true` reads the same as `'true'`, and the row value the select wrote stays `'true'` (no `onChange`). - `readonlyWhen: record.won == true`: `'true'` locks the cell, `'false'` does not. - CONTROL: a non-boolean select column (`open` / `closed`) keeps its string value in the predicate. <details><summary>Run on 3fd16f3: GridField.test.tsx 51/51, fields type-check exit 0</summary> ``` pnpm --dir ui exec vitest run --maxWorkers=2 packages/fields/src/widgets/GridField.test.tsx Test Files 1 passed (1) Tests 51 passed (51) os-verify-lock: VERDICT command-exit 0 pnpm --filter @object-ui/fields type-check os-verify-lock: VERDICT command-exit 0 ``` </details> <details><summary>Ablation: the coercion removed (scripts/ablation-replace.mjs), 3 pins red, control green, restored blob == HEAD</summary> ``` ablation-replace: anchor " ruleRecordOf(booleanColumns, row)," x1 (before) ablation-replace: replace " (row || {}) as Record<string, unknown>," x0 -> x1 ablation-replace: ok mutation landed: anchor 1 -> 0, blob 9d5bd99 -> 49d2eeda9771 × marks the dependent cell required when the select holds 'true', and not when it holds 'false' × reads a stored boolean the same way, and leaves the row the select wrote unchanged × locks a readonlyWhen cell over the same reading: 'true' locks, 'false' does not Test Files 1 failed (1) Tests 3 failed | 48 passed (51) ablation-replace: blob after restore 9d5bd99 ablation-replace: blob at HEAD 9d5bd99 git diff HEAD: empty ``` The CONTROL pin stayed green under the ablation, as it should: it does not depend on the coercion. The test imports `./GridField` from source, so no build sits between the mutation and the run. </details> ## Acceptance notes - **Detection by option shape.** The column carries no field type (the spec's `InlineGridColumn` has no such key, and adding one is a contract change), so a boolean column is recognised by its derived option pair. A genuine `select` child field whose options are exactly `'true'` and `'false'` would also be read as a boolean in the rules, while the server keeps it a string. The exact alternative is a host-supplied prop naming the boolean columns from the child schema (the pattern `lookupAutofill` / `columnCurrencies` already follow), which touches `MasterDetailForm.tsx` and `LineItemsPanel.tsx`, outside this claim's file surface. - **Live reading: NOT MEASURED.** Reason: no example app has a child object whose `requiredWhen` reads a boolean field (the showcase's `requiredWhen` rules on `invoice` read `status`), so a live reading needs authoring a new child object in an example plus a Console build and a browser run. The jsdom pins above render the real `GridField` over the derived column shape instead. ## Verification - Derived gate families: `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack` on 3fd16f3 named 38 commands; all 38 ran with exit 0 (plus `pnpm check:changeset-fixed`, exit 0). `--ran` reconciliation: "38 derived famil(ies) accounted for — 38 run, 0 NOT-MEASURED (a DERIVED zero — all 38 recorded an exit code and none of them is 3)". - `node scripts/pm/overlap-check.mjs`: VERDICT clean exit 0 against origin/main eb7b09d, 0 PR heads. - CI families (Lint & Repo Gates, Type Check UI, Test UI, …) are left to this PR's check-runs. --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufzi3ezPzTysQPDEjmVz)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzi3ezPzTysQPDEjmVz --> Co-authored-by: Claude <noreply@anthropic.com>
1 parent 526282e commit 3c535ee

3 files changed

Lines changed: 146 additions & 3 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@object-ui/fields': patch
3+
---
4+
5+
fix(fields): a line-items grid reads a boolean column as a boolean in its `requiredWhen` / `readonlyWhen` rules
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
A master-detail grid draws a `boolean` / `toggle` child field as a select whose two options store the strings `'true'` / `'false'`. Its per-cell rules evaluated `record.won == true` against that string, so the required marker and the readonly lock showed the opposite of what the server enforces: since the engine stores and judges these writes as booleans, a line the grid showed as complete was refused on save.
11+
12+
The grid now evaluates each column's `requiredWhen` and `readonlyWhen` over the row with every boolean column's cell read as the boolean it stands for. The readings are the ones the engine's write normalisation accepts (`'true'` / `'1'` / `1` and `'false'` / `'0'` / `0`). Only the predicate's view changes: what the cell shows and what the row saves are unchanged. A select column over any other field keeps its string value.

‎ui/packages/fields/src/widgets/GridField.test.tsx‎

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -703,3 +703,80 @@ describe('GridField / LineItemsField — editable line items', () => {
703703
});
704704
});
705705
});
706+
707+
describe('GridField — a boolean column read as a boolean by the cell rules (objectstack#34972)', () => {
708+
// The shape `@object-ui/plugin-form` derives for a `boolean` child field: a
709+
// select column whose two options store the strings 'true' / 'false'.
710+
const won = {
711+
name: 'won',
712+
label: 'Won',
713+
type: 'select' as const,
714+
options: [
715+
{ label: 'Yes', value: 'true' },
716+
{ label: 'No', value: 'false' },
717+
],
718+
};
719+
const requiredField = {
720+
columns: [won, { name: 'delivery_date', label: 'Delivery', type: 'text' as const, requiredWhen: 'record.won == true' }],
721+
} as any;
722+
723+
it("marks the dependent cell required when the select holds 'true', and not when it holds 'false'", () => {
724+
render(
725+
<GridField
726+
value={[{ won: 'true', delivery_date: '' }, { won: 'false', delivery_date: '' }]}
727+
onChange={() => {}}
728+
field={requiredField}
729+
/>,
730+
);
731+
expect(screen.getByTestId('line-items-invalid-0-delivery_date')).toBeTruthy();
732+
expect(screen.queryByTestId('line-items-invalid-1-delivery_date')).toBeNull();
733+
});
734+
735+
it('reads a stored boolean the same way, and leaves the row the select wrote unchanged', () => {
736+
const value = [{ won: true, delivery_date: '' }, { won: 'true', delivery_date: '' }];
737+
const onChange = vi.fn();
738+
render(<GridField value={value} onChange={onChange} field={requiredField} />);
739+
expect(screen.getByTestId('line-items-invalid-0-delivery_date')).toBeTruthy();
740+
expect(screen.getByTestId('line-items-invalid-1-delivery_date')).toBeTruthy();
741+
expect(value[1].won).toBe('true');
742+
expect(onChange).not.toHaveBeenCalled();
743+
});
744+
745+
it("locks a readonlyWhen cell over the same reading: 'true' locks, 'false' does not", () => {
746+
const lockField = {
747+
columns: [won, { name: 'note', label: 'Note', type: 'text' as const, readonlyWhen: 'record.won == true' }],
748+
} as any;
749+
render(
750+
<GridField value={[{ won: 'true', note: 'a' }, { won: 'false', note: 'b' }]} onChange={() => {}} field={lockField} />,
751+
);
752+
const notes = screen.getAllByLabelText('Note') as HTMLInputElement[];
753+
expect(notes[0].disabled).toBe(true);
754+
expect(notes[1].disabled).toBe(false);
755+
});
756+
757+
it('CONTROL: a non-boolean select column keeps its string value in the predicate', () => {
758+
const stageField = {
759+
columns: [
760+
{
761+
name: 'stage',
762+
label: 'Stage',
763+
type: 'select' as const,
764+
options: [
765+
{ label: 'Open', value: 'open' },
766+
{ label: 'Closed', value: 'closed' },
767+
],
768+
},
769+
{ name: 'reason', label: 'Reason', type: 'text' as const, requiredWhen: "record.stage == 'closed'" },
770+
],
771+
} as any;
772+
render(
773+
<GridField
774+
value={[{ stage: 'closed', reason: '' }, { stage: 'open', reason: '' }]}
775+
onChange={() => {}}
776+
field={stageField}
777+
/>,
778+
);
779+
expect(screen.getByTestId('line-items-invalid-0-reason')).toBeTruthy();
780+
expect(screen.queryByTestId('line-items-invalid-1-reason')).toBeNull();
781+
});
782+
});

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

Lines changed: 57 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -583,6 +583,54 @@ function cellDisplayText(c: GridColumn, value: any, locale: string, fileText: Fi
583583
return String(value);
584584
}
585585

586+
/**
587+
* The cell values a `boolean` / `toggle` field's write is stored as, each with
588+
* the boolean it stands for: the readings the engine's write normalisation
589+
* (`BOOLEAN_READINGS` in `@objectstack/objectql`'s record validator) turns into
590+
* a boolean before it validates a row, compared the same way (SameValueZero).
591+
* Every other value is no reading, and is left as it is.
592+
*/
593+
const BOOLEAN_READINGS: ReadonlyMap<unknown, boolean> = new Map<unknown, boolean>([
594+
['true', true],
595+
['1', true],
596+
[1, true],
597+
['false', false],
598+
['0', false],
599+
[0, false],
600+
]);
601+
602+
/**
603+
* A column over a `boolean` / `toggle` child field: the `select` column
604+
* `@object-ui/plugin-form` derives for one, whose two options store the
605+
* strings `'true'` / `'false'` (`optionsFor` in `deriveMasterDetail.ts`). A
606+
* grid column carries no field definition, so this option pair is what names
607+
* the field's type here.
608+
*/
609+
function isBooleanSelectColumn(c: GridColumn): boolean {
610+
if (c.type !== 'select' || !Array.isArray(c.options) || c.options.length !== 2) return false;
611+
const values = new Set(c.options.map((o) => o.value));
612+
return values.has('true') && values.has('false');
613+
}
614+
615+
/**
616+
* The row a column's `readonlyWhen` / `requiredWhen` predicate reads as
617+
* `record`: the row, with each boolean column's cell read as the boolean it
618+
* stands for. The select cell writes the string `'true'` / `'false'` into the
619+
* row, so `record.won == true` compared a string and the cell marker showed
620+
* the wrong state, while the server — which stores and judges the boolean —
621+
* refused the row. Only the predicate's view changes: the cell still shows,
622+
* and the row still saves, what the select wrote.
623+
*/
624+
function ruleRecordOf(booleanColumns: readonly string[], row: Row | undefined): Record<string, unknown> {
625+
const base: Row = row || {};
626+
let out: Row | undefined;
627+
for (const name of booleanColumns) {
628+
const judged = BOOLEAN_READINGS.get(base[name]);
629+
if (judged !== undefined) (out ??= { ...base })[name] = judged;
630+
}
631+
return out ?? base;
632+
}
633+
586634
function coerce(type: string | undefined, raw: string): any {
587635
if (isNumeric(type)) {
588636
if (raw === '' || raw == null) return null;
@@ -788,22 +836,28 @@ function GridFieldBody({
788836

789837
// Per-cell CEL rule state (B2 in grids). A column with no readonlyWhen/
790838
// requiredWhen resolves to its static flags (cheap fast-path — no engine
791-
// call). Otherwise evaluate against the row (`record`) + header (`parent`).
839+
// call). Otherwise evaluate against the row (`record`) + header (`parent`),
840+
// the row's boolean cells read as booleans (`ruleRecordOf`). Every column,
841+
// shown or not, since a predicate may read any cell of the row.
842+
const booleanColumns = React.useMemo(
843+
() => allColumns.filter(isBooleanSelectColumn).map((c) => c.name),
844+
[allColumns],
845+
);
792846
const cellRules = useCallback(
793847
(c: GridColumn, row: Row): { readonly: boolean; required: boolean } => {
794848
if (!c.readonlyWhen && !c.requiredWhen) {
795849
return { readonly: false, required: !!c.required };
796850
}
797851
const s = resolveFieldRuleState(
798852
{ readonlyWhen: c.readonlyWhen, requiredWhen: c.requiredWhen },
799-
(row || {}) as Record<string, unknown>,
853+
ruleRecordOf(booleanColumns, row),
800854
{ required: !!c.required, readonly: false },
801855
undefined,
802856
contextRecord ? { parent: contextRecord } : undefined,
803857
);
804858
return { readonly: s.readonly, required: s.required };
805859
},
806-
[contextRecord],
860+
[contextRecord, booleanColumns],
807861
);
808862
// List mode: rows are read-only at-a-glance; editing happens in the full form.
809863
const isList = displayMode === 'list' && !readonly;

0 commit comments

Comments
 (0)