Skip to content

Commit a78608f

Browse files
fix(components): create form no longer locks fields through readonlyWhen (objectui#13436) (#13441)
Closes #13436 Clause-②: no ## What changed objectql does not apply `readonlyWhen` on INSERT, but the form renderer evaluated it on a create form against the seeded defaults. So a predicate over a defaulted column (`record.status == 'pending_verify'` with `status` defaulting to `'pending_verify'`) or a `!=` over an unset column (`record.approval_status != 'returned'`) locked fields the API accepts on insert. `packages/components/src/renderers/form/form.tsx`: every `resolveFieldRuleState` call now passes `readonlyWhen: isCreateForm ? undefined : RULE`. That is the existing `isCreateForm` signal (no `previousValues`), and no second mode test is added. Each call site: - **Render path (`renderFormField`)**: the fix itself. On create the field is locked only by static `readonly: true`. - **`conditionallyHiddenFieldNames` / `faultedVisibleWhenFieldNames` memo** (the fault-reporting path): reads only `visible` and `faults.visibleWhen`. It would still evaluate `readonlyWhen` and `console.warn` a fault for a rule the create form no longer applies, so it is gated the same way. - **Section-divider memo (`hiddenSectionFieldNames`)** and **stale-error effect**: read only `visible` / `required`. Gated for the same no-stray-warning reason, so all sites read one answer. - **`readonlyFieldNames` (submit strip)**: already returns early on create (`if (!previousRecord)`). Gated anyway so all five sites read the same; this is a no-op there. `visibleWhen` / `requiredWhen` are unchanged, and `packages/core` (`resolveFieldRuleState`) is not touched. Docs: the `readonlyWhen` row in `content/docs/plugins/plugin-form.mdx` and `packages/plugin-form/README.md` now says it applies to an edit form only. Changeset: `@object-ui/components` patch. ## Tests New `form-readonly-when-create-13436.test.tsx` covers: - create form: both reproductions from the card stay editable - create form: static `readonly: true` still locks - edit form (`previousValues`): the same two predicates still lock - create form: no readonlyWhen fault is warned; an edit form still warns it `form-fullscreen-textarea-readonly-disabled.test.tsx`: the case "holds when `readonly` is resolved at runtime by a readonlyWhen rule" now renders an edit form. `packages/plugin-form/src/flatFieldRules.test.tsx`: - The case "locks a `readonlyWhen`-TRUE field" now renders ModalForm and DrawerForm in edit mode (`mode: 'edit'` with a `recordId`, so the container passes `previousValues`). The create mode it used before was incidental to the original fix. - A create-mode case was added: the same predicate leaves the field editable. `e2e/live/field-conditional-rules.spec.ts`: on the New dialog, the Paid step now asserts that `tax_rate` stays editable, because the server exempts INSERT from `readonlyWhen`. **This spec was not run here.** It is a live spec and is not in the `test:e2e:live:ci` allowlist. Results at 5a57d8eb52 (`vitest run --maxWorkers=2`): - The three form rule test files: 26/26 passed. - The whole form renderer directory with the downstream readonlyWhen suites (app-shell, fields, kanban, console): green except the 2 `flatFieldRules` cases that pinned create-mode locking. Those are now amended as above. - `packages/plugin-form/`: 199/199 files, 2379 passed, 1 skipped. - `type-check` of `@object-ui/components...`: 17/17 passed. - eslint on the five touched source and test files: 0 errors. - `check-changeset-presence` and `check:new-line-citations` both exit 0, with 0 new citations. Ablation (fix committed, then reverted in the working tree, and the restore proved by the HEAD blob hash): - Reverting all five gates in form.tsx turns the 3 create-form cases in the new file red, and the edit and static cases stay green. - The same revert turns the new `flatFieldRules` create case red for ModalForm and DrawerForm. - Reverting only the visibility-memo gate turns only the fault case red. - The edit-mode lock case is not vacuous: with a FALSE predicate it goes red. - [x] Adds no product-specific widget, dialog, hook or string (see AGENTS.md › Product-neutral renderer) ## Not in this PR - **A `mode: 'view'` ObjectForm.** It also gets no `previousValues`, so form.tsx reads it as create (the existing comment on the server-default hint already says so). A `readonlyWhen`-TRUE field there now renders as a disabled input instead of a read-only display. Every field in view mode is disabled already, so nothing becomes editable. - **`WizardForm`'s final-submit gate** (`gateFinalSubmit`, plugin-form). It still passes `readonlyWhen` on a create wizard. It reads only `required` and `faults.visibleWhen`, so it locks nothing, but it can still warn a `readonlyWhen` fault on create. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WJozybDmRH8z2c5SD7vJkj --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 7981384 commit a78608f

8 files changed

Lines changed: 185 additions & 14 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@object-ui/components": patch
3+
---
4+
5+
A create form no longer locks fields through `readonlyWhen`. The server does not apply `readonlyWhen` on insert, but the form evaluated it against the seeded defaults, so a predicate over a defaulted column (`record.status == 'pending_verify'` with `status` defaulting to `'pending_verify'`) or a `!=` over an unset one (`record.approval_status != 'returned'`) rendered fields read-only on New that the API accepts. `readonlyWhen` now applies only to an edit form (one given `previousValues`), and no longer warns a fault on a create form; static `readonly: true` still locks on create, and `visibleWhen` / `requiredWhen` are unchanged.

‎content/docs/plugins/plugin-form.mdx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -92,7 +92,7 @@ the spec. This page does not redeclare it, because a locally written
9292
| `options` | `SelectOption[] \| RadioOption[]` | choices for `select` / radio fields |
9393
| `validation` | `FieldValidationRules` | **an object keyed by rule name** — see below |
9494
| `condition` | `FieldCondition` | legacy `{ field, equals, notEquals, in }` matcher (`custom` is retired, objectui#7759: nothing ran it) |
95-
| `visibleWhen` / `readonlyWhen` / `requiredWhen` | `string \| { dialect?, source }` | CEL predicates over the live record, evaluated by `@objectstack/formula` — the same engine and dialect the server enforces. They fail open on screen; a `visibleWhen` that cannot be evaluated refuses the submit, naming the field and the rule |
95+
| `visibleWhen` / `readonlyWhen` / `requiredWhen` | `string \| { dialect?, source }` | CEL predicates over the live record, evaluated by `@objectstack/formula` — the same engine and dialect the server enforces. They fail open on screen; a `visibleWhen` that cannot be evaluated refuses the submit, naming the field and the rule. `readonlyWhen` applies to an edit form (one given `previousValues`) only: the server does not apply it on insert, so a create form leaves the field editable whatever the predicate says against the defaults. Static `readonly: true` locks on both |
9696
| `visibleOn` | `string \| { dialect?, source }` | view-level visibility predicate: the runtime slot a form view field's `visibleWhen` is carried into, ANDed with the field's own `visibleWhen` above. A form **view** field writes `visibleWhen`; the view's old `visibleOn` spelling is retired in `@objectstack/spec` 18 and is not read |
9797
| `dependsOn` | `DependsOnInput` | cascading parent(s): a bare name, a list of names, or `{ field, param }` entries |
9898
| `span` | `'auto' \| 'full'` | relative field width, independent of the column count (preferred) |

‎e2e/live/field-conditional-rules.spec.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import { selectOption } from './helpers';
1010
*
1111
* The showcase Invoice header declares:
1212
* • issued_on.requiredWhen = "record.status in ['sent', 'paid']"
13-
* • tax_rate.readonlyWhen = "record.status == 'paid'"
13+
* • tax_rate.readonlyWhen = "record.status == 'paid'" (edit forms only)
1414
* • paid_on.visibleWhen = "record.status == 'paid'" (UX-only)
1515
* paid_on.requiredWhen = "record.status == 'paid'"
1616
*
@@ -53,12 +53,14 @@ test('header fields react to Status via CEL visibleWhen / readonlyWhen / require
5353
await expect(taxRateReadonly).toHaveCount(0);
5454
expect(await isRequired(dialog, 'Issued On')).toBe(false);
5555

56-
// --- Paid: tax_rate locks (readonlyWhen), paid_on appears + required,
57-
// issued_on required. ---
56+
// --- Paid: paid_on appears + required, issued_on required. tax_rate stays
57+
// editable: this is a New dialog, and the server exempts INSERT from
58+
// readonlyWhen, so the create form does not apply it either
59+
// (objectui#13436). ---
5860
await selectOption(dialog, 'status', 'paid');
5961
await expect(paidOn).toHaveCount(1);
60-
await expect(taxRate).toHaveCount(0);
61-
await expect(taxRateReadonly).toBeVisible();
62+
await expect(taxRate).toBeEnabled();
63+
await expect(taxRateReadonly).toHaveCount(0);
6264
expect(await isRequired(dialog, 'Paid On')).toBe(true);
6365
expect(await isRequired(dialog, 'Issued On')).toBe(true);
6466

‎packages/components/src/renderers/form/__tests__/form-fullscreen-textarea-readonly-disabled.test.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,8 +152,11 @@ describe('form renderer — a read-only long text field is read-only (objectui#3
152152
it('holds when `readonly` is resolved at runtime by a readonlyWhen rule', () => {
153153
// Reachability, not a second code path: `readonly` reaching the branch as a
154154
// CEL verdict rather than a static flag is how a real form gets there.
155+
// An EDIT form (`previousValues` supplied): a create form does not apply
156+
// `readonlyWhen` at all, as the server exempts INSERT (objectui#13436).
155157
renderForm({
156158
defaultValues: { status: 'locked' },
159+
previousValues: { status: 'locked' },
157160
fields: [
158161
{ name: 'status', label: 'Status', type: 'input' },
159162
longText({ readonlyWhen: "record.status == 'locked'" }),
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
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 create form does not apply `readonlyWhen` (objectui#13436).
11+
*
12+
* objectql exempts INSERT from `readonlyWhen` entirely, but the renderer used
13+
* to evaluate it on a create form against the seeded defaults. Two shapes
14+
* locked fields the server accepts on insert:
15+
*
16+
* - a predicate over a column with a default:
17+
* `record.status == 'pending_verify' || record.status == 'active'` with
18+
* `status` defaulted to `'pending_verify'`;
19+
* - a `!=` predicate over an unset column:
20+
* `record.approval_status != 'returned'` (`null != 'returned'` is TRUE).
21+
*
22+
* A create form is the one the host hands no `previousValues` (the same
23+
* `isCreateForm` signal the read-only submit strip gates on). An edit form
24+
* (with `previousValues`) keeps applying the rule, and static `readonly: true`
25+
* still locks on create.
26+
*/
27+
28+
import { describe, it, expect, vi, afterEach } from 'vitest';
29+
import { render, screen } from '@testing-library/react';
30+
import { ComponentRegistry } from '@object-ui/core';
31+
// Module-scope import (not `beforeAll`) so the cold transform is billed to the
32+
// import phase — objectui#3010 / object-ui/no-dynamic-import-in-test-hook.
33+
import '../../../renderers';
34+
35+
function renderForm(schema: Record<string, unknown>) {
36+
const Form = ComponentRegistry.get('form')!;
37+
return render(<Form schema={{ type: 'form', showSubmit: false, showCancel: false, ...schema }} />);
38+
}
39+
40+
const LOCKED_ON_STATUS = "record.status == 'pending_verify' || record.status == 'active'";
41+
const LOCKED_UNLESS_RETURNED = "record.approval_status != 'returned'";
42+
43+
const defaultedFields = [
44+
{ name: 'status', label: 'Status', type: 'input', readonly: true },
45+
{ name: 'bank_name', label: 'Bank name', type: 'input', required: true, readonlyWhen: LOCKED_ON_STATUS },
46+
{ name: 'account_no', label: 'Account no', type: 'input', required: true, readonlyWhen: LOCKED_ON_STATUS },
47+
];
48+
49+
const unsetFields = [
50+
{ name: 'approval_status', label: 'Approval status', type: 'input' },
51+
{ name: 'title', label: 'Title', type: 'input', readonlyWhen: LOCKED_UNLESS_RETURNED },
52+
];
53+
54+
afterEach(() => {
55+
vi.restoreAllMocks();
56+
});
57+
58+
describe('form renderer — readonlyWhen on a create form (objectui#13436)', () => {
59+
it('leaves a field editable on create when the predicate is TRUE against a seeded default', () => {
60+
renderForm({ fields: defaultedFields, defaultValues: { status: 'pending_verify' } });
61+
62+
expect(screen.getByLabelText(/^Bank name/)).not.toHaveAttribute('readonly');
63+
expect(screen.getByLabelText(/^Account no/)).not.toHaveAttribute('readonly');
64+
});
65+
66+
it('still locks a static `readonly: true` field on create', () => {
67+
renderForm({ fields: defaultedFields, defaultValues: { status: 'pending_verify' } });
68+
69+
expect(screen.getByLabelText(/^Status/)).toHaveAttribute('readonly');
70+
});
71+
72+
it('leaves a field editable on create when a `!=` predicate is TRUE over an unset column', () => {
73+
renderForm({ fields: unsetFields });
74+
75+
expect(screen.getByLabelText(/^Title/)).not.toHaveAttribute('readonly');
76+
});
77+
78+
it('keeps locking on an edit form: the defaulted-column predicate', () => {
79+
renderForm({
80+
fields: defaultedFields,
81+
defaultValues: { status: 'pending_verify', bank_name: 'B', account_no: '1' },
82+
previousValues: { status: 'pending_verify', bank_name: 'B', account_no: '1' },
83+
});
84+
85+
expect(screen.getByLabelText(/^Bank name/)).toHaveAttribute('readonly');
86+
expect(screen.getByLabelText(/^Account no/)).toHaveAttribute('readonly');
87+
});
88+
89+
it('keeps locking on an edit form: the `!=` predicate over an unset column', () => {
90+
renderForm({
91+
fields: unsetFields,
92+
defaultValues: { title: 'T' },
93+
previousValues: { title: 'T' },
94+
});
95+
96+
expect(screen.getByLabelText(/^Title/)).toHaveAttribute('readonly');
97+
});
98+
99+
it('reports no readonlyWhen fault on create, where the rule is not applied; an edit form still does', () => {
100+
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
101+
const readonlyWhenWarnings = () =>
102+
warn.mock.calls.filter((args) => String(args[0]).includes('readonlyWhen of field'));
103+
104+
// Unique sources: `warnPredicateFailure` dedupes per source module-wide.
105+
renderForm({
106+
fields: [{ name: 'memo', label: 'Memo', type: 'input', visibleWhen: 'true', readonlyWhen: 'record.memo_13436_create ==' }],
107+
});
108+
expect(readonlyWhenWarnings()).toHaveLength(0);
109+
110+
renderForm({
111+
fields: [{ name: 'memo', label: 'Memo', type: 'input', visibleWhen: 'true', readonlyWhen: 'record.memo_13436_edit ==' }],
112+
defaultValues: { memo: 'm' },
113+
previousValues: { memo: 'm' },
114+
});
115+
expect(readonlyWhenWarnings().length).toBeGreaterThan(0);
116+
});
117+
});

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

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1699,6 +1699,17 @@ ComponentRegistry.register('form',
16991699
// answer the mode differently.
17001700
const isCreateForm = previousRecord === undefined;
17011701

1702+
// The same signal decides whether `readonlyWhen` binds (objectui#13436):
1703+
// UPDATE only. objectql exempts INSERT from it entirely, so a create form
1704+
// evaluating it against the seeded defaults (a `defaultValue` the
1705+
// predicate names, an unset column under `!=`) locked fields the server
1706+
// accepts on insert, and the user could not fill a form the API takes.
1707+
// Every `resolveFieldRuleState` call below therefore passes
1708+
// `readonlyWhen: isCreateForm ? undefined : RULE` — the render verdict and
1709+
// the memos that re-evaluate the same rules alike, so none of them warns a
1710+
// fault for a rule the create form never applies. Static `readonly: true`
1711+
// still locks on create; `visibleWhen` / `requiredWhen` are untouched.
1712+
17021713
// A two-state control has no third state, so a boolean field that nobody
17031714
// supplied a value for starts at `false` — not `undefined`. Without this
17041715
// the switch renders OFF while the form holds NOTHING: the create payload
@@ -1863,7 +1874,7 @@ ComponentRegistry.register('form',
18631874
// never by the triad (objectui#13055) — and this memo reads only
18641875
// `readonly`, so it has nothing to evaluate it for.
18651876
visibleWhen: isFailClosedSectionGate(f) ? undefined : (f as any).visibleWhen,
1866-
readonlyWhen: (f as any).readonlyWhen,
1877+
readonlyWhen: isCreateForm ? undefined : (f as any).readonlyWhen,
18671878
requiredWhen: (f as any).requiredWhen,
18681879
},
18691880
ruleRecord,
@@ -1938,7 +1949,7 @@ ComponentRegistry.register('form',
19381949
const st = resolveFieldRuleState(
19391950
{
19401951
visibleWhen: gate ? undefined : visibleWhen,
1941-
readonlyWhen: (f as any).readonlyWhen,
1952+
readonlyWhen: isCreateForm ? undefined : (f as any).readonlyWhen,
19421953
requiredWhen: (f as any).requiredWhen,
19431954
},
19441955
ruleRecord,
@@ -2034,7 +2045,7 @@ ComponentRegistry.register('form',
20342045
const st = resolveFieldRuleState(
20352046
{
20362047
visibleWhen: gate ? undefined : (divider as any).visibleWhen,
2037-
readonlyWhen: (divider as any).readonlyWhen,
2048+
readonlyWhen: isCreateForm ? undefined : (divider as any).readonlyWhen,
20382049
requiredWhen: (divider as any).requiredWhen,
20392050
},
20402051
ruleRecord,
@@ -2174,7 +2185,7 @@ ComponentRegistry.register('form',
21742185
const st = resolveFieldRuleState(
21752186
{
21762187
visibleWhen: (f as any).visibleWhen,
2177-
readonlyWhen: (f as any).readonlyWhen,
2188+
readonlyWhen: isCreateForm ? undefined : (f as any).readonlyWhen,
21782189
requiredWhen: (f as any).requiredWhen,
21792190
},
21802191
ruleRecord,
@@ -3219,7 +3230,7 @@ ComponentRegistry.register('form',
32193230
// see `isFailClosedSectionGate`.
32203231
const failClosedGate = isFailClosedSectionGate(field);
32213232
const ruleState = resolveFieldRuleState(
3222-
{ visibleWhen: failClosedGate ? undefined : visibleWhen, readonlyWhen, requiredWhen },
3233+
{ visibleWhen: failClosedGate ? undefined : visibleWhen, readonlyWhen: isCreateForm ? undefined : readonlyWhen, requiredWhen },
32233234
ruleRecord,
32243235
{
32253236
required: staticRequired,

‎packages/plugin-form/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -253,7 +253,7 @@ key:
253253
| `options` | `SelectOption[] \| RadioOption[]` | for `select` / radio fields |
254254
| `validation` | `FieldValidationRules` | **an object keyed by rule name** — see below |
255255
| `condition` | `FieldCondition` | legacy `{ field, equals, notEquals, in }` matcher (`custom` is retired, objectui#7759: nothing ran it) |
256-
| `visibleWhen` / `readonlyWhen` / `requiredWhen` | `string \| { dialect?, source }` | CEL predicates over the live record, evaluated by `@objectstack/formula` — the same engine and dialect the server uses. Fail open |
256+
| `visibleWhen` / `readonlyWhen` / `requiredWhen` | `string \| { dialect?, source }` | CEL predicates over the live record, evaluated by `@objectstack/formula` — the same engine and dialect the server uses. Fail open. `readonlyWhen` applies to an edit form (one given `previousValues`) only, as the server does not apply it on insert; static `readonly: true` locks on both |
257257
| `visibleOn` | `string \| { dialect?, source }` | view-level visibility predicate: objectui's runtime slot (not a spec key) a form view field's `visibleWhen` is carried into, ANDed with the field's own `visibleWhen` above. A form **view** field writes `visibleWhen` (its old `visibleOn` spelling is retired in `@objectstack/spec` 18 and is not read), and a section entry written as a bare field name carries no view-level predicate |
258258
| `dependsOn` | `DependsOnInput` | cascading parent(s): a bare name, a list of names, or `{ field, param }` entries |
259259
| `span` | `'auto' \| 'full'` | relative width, independent of the column count (preferred) |

‎packages/plugin-form/src/flatFieldRules.test.tsx‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,30 @@ describe.each(CONTAINERS)('%s — no-sections form honours field-level rules (#4
101101
/>,
102102
);
103103

104+
/**
105+
* The same form on an EDIT of a stored row: with `mode: 'edit'` and a
106+
* `recordId` the container hands the renderer `previousValues`, which is
107+
* what makes it an edit form. `readonlyWhen` binds there only — the server
108+
* exempts INSERT from it (objectui#13436).
109+
*/
110+
const renderFlatEdit = (ds: any, status: string) => {
111+
ds.findOne.mockResolvedValue({ id: 'r1', status });
112+
return render(
113+
<Container
114+
schema={{
115+
type: 'object-form',
116+
formType,
117+
objectName: 'invoice',
118+
mode: 'edit',
119+
recordId: 'r1',
120+
open: true,
121+
initialData: { id: 'r1', status },
122+
} as any}
123+
dataSource={ds}
124+
/>,
125+
);
126+
};
127+
104128
it('hides a `visibleWhen`-FALSE field and shows it when the predicate holds', async () => {
105129
renderFlat(makeDS(), 'draft');
106130
await screen.findByLabelText(/^Status$/);
@@ -112,10 +136,19 @@ describe.each(CONTAINERS)('%s — no-sections form honours field-level rules (#4
112136
expect(await screen.findByLabelText(/^Sent at$/)).toBeTruthy();
113137
});
114138

115-
it('locks a `readonlyWhen`-TRUE field', async () => {
139+
it('locks a `readonlyWhen`-TRUE field on an edit form', async () => {
140+
renderFlatEdit(makeDS(), 'sent');
141+
await waitFor(() => expect(document.body.querySelector('[data-field="amount"]')).toBeTruthy());
142+
await waitFor(() => expect(controlOf('amount')).toBeNull());
143+
});
144+
145+
it('leaves a `readonlyWhen`-TRUE field editable on a create form (objectui#13436)', async () => {
146+
// The server does not apply `readonlyWhen` on INSERT, so a create form
147+
// must not lock the field either: the user could not fill a form the API
148+
// accepts.
116149
renderFlat(makeDS(), 'sent');
117150
await waitFor(() => expect(document.body.querySelector('[data-field="amount"]')).toBeTruthy());
118-
expect(controlOf('amount')).toBeNull();
151+
expect(controlOf('amount')).not.toBeNull();
119152
});
120153

121154
it('leaves the same field editable when the predicate is FALSE', async () => {

0 commit comments

Comments
 (0)