Skip to content

Commit a5ddeb6

Browse files
fix(plugin-detail): the record page hides a field whose own visibleWhen is false (#35421)
Fixes #35314 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:记录详情页(默认页与自建页的详情块)不再显示「显示条件」对当前记录为假的字段,与编辑表单一致;条件写错时照旧显示该字段并在控制台告警一次,也与表单一致。 - 为什么改:默认记录页把只在特定状态才有意义的字段(如审批不需要时的「申请资格审批」)也画出来,读者看到空的或误导的字段,同一条记录的页面与表单说法不一。 - 风险与回滚:若判错,会把本应显示的字段藏起来(数据仍在、接口仍返回,只是不画);整体回滚一个提交即可,无数据迁移。 - 先看:`ui/packages/plugin-detail/src/renderers/record-details.tsx` 中新增的 `fieldPredicateVisible` 与 `dropPredicateHidden` 两处;其次同目录 `__tests__/record-details.fieldVisibleWhen-35314.test.tsx` 的对照矩阵。 - 两分钟验证:`pnpm --dir ui exec vitest run packages/plugin-detail/src/renderers/__tests__/record-details.fieldVisibleWhen-35314.test.tsx`,预期 19 项全绿,其中每一行都同时断言表单与详情页的结论。 - 需要你做的:无,席位落地。 ## What changes `record:details` now honours a field's own object-level `visibleWhen` (`Field.visibleWhen`: "field is shown only when TRUE (else hidden)") on every field it draws. Before, it evaluated a field GROUP's `visibleWhen` (the `{ group }` reference) and no field's, so the synthesized default record page drew a field whose predicate is false for the record, label and value. - **Where it was missing.** The section fold in `record:details` (`fields: dropHidden(normaliseList(filterList(s.fields)))`) and the flat-body fold (`filteredFields`) applied field security, the label ladder and the header dedupe, and never read the object's field `visibleWhen`; `DetailSection` draws whatever it is handed. The group derivation (`deriveFieldGroupDetailEntries` / `toField`) does not carry the field predicate either, so neither layer saw it. - **The fix.** One new fold, `dropPredicateHidden`, applied last to both lists. It reads the predicate off the object's field declaration by name and judges it with `fieldPredicateVisible`, which calls `resolveFieldRuleState` from `@object-ui/core`: the call the form renderer makes for a field's `visibleWhen`. So the fault direction is the field rule's (`VISIBLE_WHEN_FAULTED`, ADR-0137 D3): a predicate that cannot be evaluated SHOWS the field and warns once. That is the opposite of the group gate (fail-closed), on purpose; each slot keeps the direction the form gives it. - **Record context.** The same inputs the existing group gate passes: `sectionPredicateRecord` (every declared field seeded `null`, relations collapsed to their stored id) bound as `record` and `previous`, plus `usePredicateScope()`. The lazily assembled record is now shared by both gates (`predicateRecord()`), so a body with no predicate does no extra work. - **Scope of the guard.** It applies to every body `record:details` draws, because the renderer cannot tell the default page's enumerated sections from an authored page's: app-shell's running default page sends the ungrouped bucket, and the whole body of an object with no `fieldGroups`, as enumerated sections of the same shape an authored page writes. One guard closes the class instead of a default-page-only branch. ## Tests New `ui/packages/plugin-detail/src/renderers/__tests__/record-details.fieldVisibleWhen-35314.test.tsx` (19 tests): - **Parity matrix (10).** Each case renders the same row through `record:details` (the synthesized default page) AND through the entry form renderer with the field carrying the same predicate, and asserts `{ form, detail }` against the expected verdict: envelope and bare-string spellings, no predicate, three fault shapes (unbound bare identifier, parse error, unknown field: drawn, fail-open), a declared-but-absent column (null seed), a relation bound as its id, `previous`, and the host `current_user` scope. - **Every body (7).** Synthesized default page (grouped field, ungrouped bucket); running default page shape app-shell writes (grouped, ungrouped bucket, object with no `fieldGroups`); authored enumerated sections; authored flat `fields` list. - **Controls (2).** A field whose predicate holds and a field with none are drawn; a section whose every member is hidden draws no heading (and draws it on the record where they show). Harness guards: each render first finds an ungated anchor value and throws `HARNESS DEAD` otherwise, so an empty body cannot pass a hidden leg. <details><summary>Reverse verification: the pin against the BASE renderer (red), then restored</summary> `record-details.tsx` restored from the base commit with `git restore --source=BASE`, the pin run, the file restored with `git checkout HEAD --` in an EXIT trap. Mutation proof: `resolveFieldRuleState` count in the file = 0. ``` × envelope `record.stage == closed_won` — the card reproduction × bare-string `record.stage == closed_won` — the same verdict as the envelope × a declared field the row does not carry compares as null — evaluated, not faulted × a relation binds as its stored id, expanded or not × `previous` binds the persisted row, as on the record's edit form × the host `current_user` scope binds on both surfaces × synthesized default page — a field in a declared group: hidden on LOST, drawn on WON × synthesized default page — a field in the ungrouped bucket: hidden on LOST, drawn on WON × running default page — a field in a declared group: hidden on LOST, drawn on WON × running default page — a field in the ungrouped bucket: hidden on LOST, drawn on WON × running default page of an object with no fieldGroups: hidden on LOST, drawn on WON × authored page — enumerated sections of bare names: hidden on LOST, drawn on WON × authored page — a flat fields list: hidden on LOST, drawn on WON × a section every member of which the predicates hide draws no heading Test Files 1 failed (1) Tests 14 failed | 5 passed (19) card reproduction diff: form [false, true], detail [true, true] ``` The 5 that stay green on the base are the controls that must: no predicate, the three fail-open fault cases (drawn on both rows, which is also what the base did), and the predicate-holds control. Restore proof: `git diff HEAD` empty, `git status --porcelain` empty, `git hash-object` of the file equals the HEAD blob. </details> <details><summary>Package suite and type-check at head 43ff1a5</summary> ``` pnpm --dir ui exec vitest run --maxWorkers=2 packages/plugin-detail/ Test Files 387 passed | 1 skipped (388) Tests 3511 passed | 18 skipped (3529) pnpm --filter @object-ui/plugin-detail run type-check (tsc --noEmit && tsc -p tsconfig.test.json; the second program includes src/**/*.test.tsx) TC_EXIT=0 pnpm --dir ui exec vitest run --maxWorkers=2 scripts/ Test Files 171 passed | 2 skipped (173) Tests 5092 passed | 2 skipped (5094) ``` The group-gate pin `record-details.groupVisibleWhen-11630.test.tsx` (13 tests) is in that suite and stays green: an authored or synthesized `{ group }` section's own gate is unchanged. </details> ## Acceptance notes - **Authored pages change too, deliberately.** On the base, an authored `record:details` section (or flat `fields` list) naming a field whose `visibleWhen` is false also drew it (measured red above). The guard closes that in the same fold, under the bounded in-place rule: same defect class, mechanical, same file, no new gate surface. Nothing changes for a field with no predicate, a field whose predicate holds, or a `{ group }` section's own gate. - **Evaluated against the stored record, not the inline-edit draft**, like the group gate: editing `stage` inline reveals a gated field after save, not while typing. - **Display only.** The record API still returns the field, as with a form-hidden field. - **Not covered here:** `record:highlights` (the header strip) and the `detail-view` node / record drawer do not read a field's `visibleWhen` either. Not measured as reachable defects in this run; noted, not filed. - **Real app.** `showcase_invoice.paid_on` (`visibleWhen: record.status == 'paid'`, object with no `fieldGroups`) is the in-repo fixture of this shape; its body is the "object with no fieldGroups" leg above. A live browser run was not made (no built console bundle in this container). - The registry `inputs` text for `record:details` (and the generated reference page) says nothing false after this change, so it is not edited here. ## Verification Derived local gate families (`node scripts/pm/dispatch-gates.mjs --commands`, 38 commands) run, each with its exit code captured before any pipe; all 38 exit 0. Reconciliation with `--ran`: 38 derived, 38 run, 0 NOT-MEASURED, 0 UNRUN. Every other family is CI's; see this PR's check runs. --- _Generated by [Claude Code](https://claude.ai/code/session_01Utp6CZrgaiMgTJCnswR6jQ)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b7d2474 commit a5ddeb6

3 files changed

Lines changed: 455 additions & 9 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/plugin-detail': patch
3+
---
4+
5+
fix(plugin-detail): a record page no longer draws a field whose own `visibleWhen` is false for the record
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
`record:details` now honours a field's object-level `visibleWhen` (`Field.visibleWhen`: "field is shown only when TRUE") on every field it draws, the way the edit form does. The synthesized default record page used to draw such a field, label and value, on every record, so the page and the form disagreed about the same record. It applies to every body `record:details` draws: a `{ group }` reference, an enumerated section (the default page's ungrouped bucket, its split for an object with no `fieldGroups`, or an authored page's section) and a flat `fields` list.
11+
12+
The verdict is the form's own: the same evaluator call (`resolveFieldRuleState`), over the record the page shows (bound as `record` and as `previous`) and the host predicate scope (`current_user`). A field predicate that cannot be evaluated still shows the field and warns once in the console, as on the form (ADR-0137 D3). That is the opposite of a field GROUP's `visibleWhen`, which hides the group on a fault. A section whose every field is hidden this way draws no heading. Display only: the record API still returns the field.
Lines changed: 380 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,380 @@
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+
* objectstack#35314 — "the default record page honours a field's `visibleWhen`
11+
* the same way the form does."
12+
*
13+
* The reported shape: a field declares an object-level `visibleWhen`
14+
* (`@objectstack/spec` `Field.visibleWhen`: "field is shown only when TRUE
15+
* (else hidden)"). The edit form hides it on a record where the predicate is
16+
* false; the synthesized default record page drew it, label and value, on
17+
* every record. `record:details` evaluated a field GROUP's `visibleWhen`
18+
* (objectui#11630) and no field's.
19+
*
20+
* ## How "the same way the form does" is measured, not asserted
21+
*
22+
* Every predicate case is rendered on the same row TWICE: once through
23+
* `record:details`, and once through the entry form renderer itself
24+
* (`@object-ui/components`' `form`, an edit form of that row, the field
25+
* carrying the predicate). Each leg asserts the form's verdict, the detail
26+
* page's verdict AND the expected verdict, so two surfaces wrong the same way
27+
* still turn it red.
28+
*
29+
* The fault direction is the field rule's, not the group's: a field
30+
* `visibleWhen` that cannot be evaluated SHOWS the field (ADR-0137 D3, the
31+
* form's `VISIBLE_WHEN_FAULTED`), where a group's hides the group
32+
* (objectui#13055, pinned in `record-details.groupVisibleWhen-11630`).
33+
*
34+
* ## The harness cannot read as a refusal
35+
*
36+
* Each detail render first finds the ungated `Region` value, and each form
37+
* render the ungated `Stage` control. Both throw a textually distinct
38+
* `HARNESS DEAD` first, so a body that rendered nothing at all can never pass
39+
* a "hidden" leg.
40+
*/
41+
42+
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
43+
import { render, screen, cleanup } from '@testing-library/react';
44+
import * as React from 'react';
45+
import { ComponentRegistry } from '@object-ui/core';
46+
import { RecordContextProvider, PredicateScopeProvider } from '@object-ui/react';
47+
// Module-scope side-effect import (objectui#3010): the registry must hold the
48+
// entry form's `form` renderer before the parity legs look it up.
49+
import '@object-ui/components';
50+
import { RecordDetailsRenderer, resetUnresolvedSectionGroupReports } from '../record-details';
51+
import { buildDefaultDetails } from '../../synth/buildDefaultPageSchema';
52+
53+
/* ─────────────────────────────────────────────────────────────────────────────
54+
* Fixture
55+
*
56+
* `name` is DECLARED and left UNSET on every row, so the page-H1 dedupe ladder
57+
* resolves to it, finds no value and hides no row these legs read (the
58+
* objectui#8175 trap, as in `record-details.groupVisibleWhen-11630`).
59+
* ─────────────────────────────────────────────────────────────────────────── */
60+
61+
const OBJECT_NAME = 'qa_field_gate';
62+
const cel = (source: string) => ({ dialect: 'cel', source });
63+
64+
const WIN_LABEL = 'Win Reason';
65+
const MEMO_LABEL = 'Memo';
66+
67+
/**
68+
* `win_reason` (in the `outcome` group) and `memo` (in no group — the trailing
69+
* ungrouped bucket) carry the predicate under test. `loss_reason` carries a
70+
* fixed one, and `next_step` none.
71+
*/
72+
const objectSchemaWith = (visibleWhen: unknown, withGroups = true) => ({
73+
name: OBJECT_NAME,
74+
fields: {
75+
name: { type: 'text', label: 'Name' },
76+
region: { type: 'text', label: 'Region', group: 'basics' },
77+
stage: { type: 'text', label: 'Stage', group: 'basics' },
78+
// Declared, and carried by NO row: the null-seed case.
79+
tier: { type: 'text', label: 'Tier', group: 'basics' },
80+
// A relation: this page's record carries it expanded, the form its id.
81+
owner: { type: 'lookup', label: 'Owner', reference: 'sys_user', group: 'basics' },
82+
loss_reason: {
83+
type: 'text', label: 'Loss Reason', group: 'outcome', visibleWhen: "record.stage == 'closed_lost'",
84+
},
85+
win_reason: {
86+
type: 'text', label: WIN_LABEL, group: 'outcome', ...(visibleWhen !== undefined ? { visibleWhen } : {}),
87+
},
88+
next_step: { type: 'text', label: 'Next Step', group: 'outcome' },
89+
memo: { type: 'text', label: MEMO_LABEL, ...(visibleWhen !== undefined ? { visibleWhen } : {}) },
90+
},
91+
...(withGroups
92+
? { fieldGroups: [{ key: 'basics', label: 'Basics' }, { key: 'outcome', label: 'Outcome' }] }
93+
: {}),
94+
});
95+
96+
type Row = Record<string, any>;
97+
const LOST: Row = {
98+
id: 'R1',
99+
region: 'region-of-lost',
100+
stage: 'closed_lost',
101+
owner: { id: 'u1', name: 'Kim' },
102+
loss_reason: 'loss-of-lost',
103+
win_reason: 'win-of-lost',
104+
next_step: 'next-of-lost',
105+
memo: 'memo-of-lost',
106+
};
107+
const WON: Row = {
108+
id: 'R2',
109+
region: 'region-of-won',
110+
stage: 'closed_won',
111+
owner: { id: 'u2', name: 'Lee' },
112+
loss_reason: 'loss-of-won',
113+
win_reason: 'win-of-won',
114+
next_step: 'next-of-won',
115+
memo: 'memo-of-won',
116+
};
117+
118+
/** The host scope `ExpressionProvider` mounts (as in the group pin). */
119+
function hostScope(positions: string[]) {
120+
const user = { id: 'u1', name: 'Kim', positions };
121+
return { current_user: user, user, ctx: { user }, os: { user }, features: {} };
122+
}
123+
124+
const textCount = (text: string): number => screen.queryAllByText(text).length;
125+
126+
/* ── the detail page's body shapes ────────────────────────────────────────── */
127+
128+
type SchemaFor = (objectSchema: Record<string, any>) => Record<string, unknown>;
129+
130+
/** The synthesized default page's Details body: `{ group }` references plus the ungrouped bucket's names. */
131+
const synthesizedDefaultPage: SchemaFor = (objectSchema) => buildDefaultDetails(objectSchema as any).properties;
132+
133+
const descriptor = (objectSchema: Record<string, any>, name: string) => ({
134+
name,
135+
label: objectSchema.fields[name].label,
136+
type: objectSchema.fields[name].type,
137+
});
138+
139+
/**
140+
* The shape app-shell's `RecordDetailView` hands the running default page
141+
* (`deriveRecordDetailSections`): each declared group as `{ group, showBorder }`
142+
* and the ungrouped bucket as an enumerated section of rich descriptors.
143+
*/
144+
const runtimeDefaultPage: SchemaFor = (objectSchema) => ({
145+
sections: [
146+
{ group: 'basics', showBorder: true },
147+
{ group: 'outcome', showBorder: true },
148+
{ label: 'Other', showBorder: true, fields: [descriptor(objectSchema, 'memo')] },
149+
],
150+
});
151+
152+
/**
153+
* The running default page of an object with NO `fieldGroups`: app-shell's
154+
* primary/secondary split, one untitled enumerated section of descriptors.
155+
*/
156+
const runtimeDefaultPageUngrouped: SchemaFor = (objectSchema) => ({
157+
sections: [
158+
{
159+
showBorder: false,
160+
fields: ['region', 'stage', 'owner', 'loss_reason', 'win_reason', 'next_step', 'memo'].map((n) =>
161+
descriptor(objectSchema, n),
162+
),
163+
},
164+
],
165+
});
166+
167+
/** An authored page: enumerated sections of bare names, the spec's spelling. */
168+
const authoredSections: SchemaFor = () => ({
169+
sections: [
170+
{ name: 'basics', label: 'Basics', fields: ['region', 'stage', 'owner'] },
171+
{ name: 'outcome', label: 'Outcome', fields: ['loss_reason', 'win_reason', 'next_step', 'memo'] },
172+
],
173+
});
174+
175+
/** An authored page: a flat `fields` list. */
176+
const authoredFields: SchemaFor = () => ({
177+
fields: ['region', 'stage', 'loss_reason', 'win_reason', 'next_step', 'memo'],
178+
});
179+
180+
function renderDetails(schema: Record<string, unknown>, row: Row, objectSchema: Record<string, unknown>, scope: Record<string, unknown>) {
181+
return render(
182+
<PredicateScopeProvider scope={scope}>
183+
<RecordContextProvider objectName={OBJECT_NAME} recordId={row.id} data={row} objectSchema={objectSchema}>
184+
<RecordDetailsRenderer schema={schema as any} />
185+
</RecordContextProvider>
186+
</PredicateScopeProvider>,
187+
);
188+
}
189+
190+
/**
191+
* Is the gated field drawn on the detail page — label AND value? Returns the
192+
* verdict for `win_reason`, and for `memo` when `which` says so.
193+
*/
194+
function detailShows(
195+
visibleWhen: unknown,
196+
row: Row,
197+
{
198+
scope = {},
199+
schemaFor = synthesizedDefaultPage,
200+
withGroups = true,
201+
which = 'win_reason',
202+
}: { scope?: Record<string, unknown>; schemaFor?: SchemaFor; withGroups?: boolean; which?: 'win_reason' | 'memo' } = {},
203+
): boolean {
204+
const objectSchema = objectSchemaWith(visibleWhen, withGroups);
205+
renderDetails(schemaFor(objectSchema), row, objectSchema, scope);
206+
const anchor = textCount(row.region);
207+
if (anchor !== 1) {
208+
cleanup();
209+
throw new Error(`HARNESS DEAD: expected the ungated Region value once, found ${anchor}`);
210+
}
211+
const label = textCount(which === 'win_reason' ? WIN_LABEL : MEMO_LABEL);
212+
const value = textCount(row[which]);
213+
cleanup();
214+
// The field goes whole or stays whole: a label without its value (or the
215+
// reverse) is a defect of its own, never a verdict.
216+
if (label === 1 && value === 1) return true;
217+
if (label === 0 && value === 0) return false;
218+
throw new Error(`PARTIAL FIELD on the detail page: label ${label}, value ${value}`);
219+
}
220+
221+
/** The edit form for the same row, the field carrying the same predicate. */
222+
function formShows(visibleWhen: unknown, row: Row, scope: Record<string, unknown> = {}): boolean {
223+
const Form = ComponentRegistry.get('form')!;
224+
const values = { ...row, owner: row.owner?.id };
225+
render(
226+
<PredicateScopeProvider scope={scope}>
227+
<Form
228+
schema={{
229+
type: 'form',
230+
showSubmit: false,
231+
showCancel: false,
232+
defaultValues: values,
233+
previousValues: values,
234+
fields: [
235+
{ name: 'stage', label: 'Stage', type: 'input' },
236+
{ name: 'tier', label: 'Tier', type: 'input' },
237+
{ name: 'owner', label: 'Owner', type: 'input' },
238+
{ name: 'win_reason', label: WIN_LABEL, type: 'input', ...(visibleWhen !== undefined ? { visibleWhen } : {}) },
239+
],
240+
}}
241+
/>
242+
</PredicateScopeProvider>,
243+
);
244+
const anchor = screen.queryAllByLabelText(/^Stage/).length;
245+
if (anchor !== 1) {
246+
cleanup();
247+
throw new Error(`HARNESS DEAD: expected the ungated form field "Stage" once, found ${anchor}`);
248+
}
249+
const shown = screen.queryAllByLabelText(new RegExp(`^${WIN_LABEL}`)).length;
250+
cleanup();
251+
if (shown === 1) return true;
252+
if (shown === 0) return false;
253+
throw new Error(`form drew "${WIN_LABEL}" ${shown} times`);
254+
}
255+
256+
/* ── `useRecordEditable`'s explain probe — a router, not a sink ──────────────
257+
* Same double as `record-details.groupVisibleWhen-11630`: any URL outside the
258+
* one route it serves fails `afterEach`.
259+
* ─────────────────────────────────────────────────────────────────────────── */
260+
261+
const EXPLAIN_ROUTE = '/api/v1/security/explain';
262+
let explainCalls: string[] = [];
263+
264+
beforeEach(() => {
265+
explainCalls = [];
266+
resetUnresolvedSectionGroupReports();
267+
// A faulted predicate warns once per text on both surfaces — expected here.
268+
vi.spyOn(console, 'warn').mockImplementation(() => {});
269+
vi.stubGlobal(
270+
'fetch',
271+
vi.fn(async (input: unknown) => {
272+
const url = String(
273+
input && typeof input === 'object' && 'url' in input ? (input as { url: unknown }).url : input,
274+
);
275+
explainCalls.push(url);
276+
if (url !== EXPLAIN_ROUTE) return { ok: false, status: 404, json: async () => ({}) };
277+
return { ok: true, status: 200, json: async () => ({ record: { visible: true } }) };
278+
}),
279+
);
280+
});
281+
282+
afterEach(() => {
283+
expect(explainCalls.filter((url) => url !== EXPLAIN_ROUTE)).toEqual([]);
284+
cleanup();
285+
vi.unstubAllGlobals();
286+
vi.restoreAllMocks();
287+
});
288+
289+
/* ═══════════════════════════════════════════════════════════════════════════
290+
* The parity matrix — the synthesized default page against the form
291+
* ═══════════════════════════════════════════════════════════════════════════ */
292+
293+
type Case = {
294+
label: string;
295+
visibleWhen: unknown;
296+
/** Expected verdict on [LOST, WON]. */
297+
expected: [boolean, boolean];
298+
};
299+
300+
const MATRIX: Case[] = [
301+
{ label: 'envelope `record.stage == closed_won` — the card reproduction', visibleWhen: cel("record.stage == 'closed_won'"), expected: [false, true] },
302+
{ label: 'bare-string `record.stage == closed_won` — the same verdict as the envelope', visibleWhen: "record.stage == 'closed_won'", expected: [false, true] },
303+
{ label: 'no predicate — the control: the field is drawn on every row', visibleWhen: undefined, expected: [true, true] },
304+
{ label: 'bare identifier `stage == closed_won` is unbound and SHOWS the field (fail-open, ADR-0137 D3)', visibleWhen: "stage == 'closed_won'", expected: [true, true] },
305+
{ label: 'a parse error SHOWS the field (fail-open, ADR-0137 D3)', visibleWhen: cel('record.stage =='), expected: [true, true] },
306+
{ label: 'an unknown field SHOWS the field (fail-open, ADR-0137 D3)', visibleWhen: cel("record.no_such_field == 'x'"), expected: [true, true] },
307+
{ label: 'a declared field the row does not carry compares as null — evaluated, not faulted', visibleWhen: cel("record.tier == 'gold'"), expected: [false, false] },
308+
{ label: 'a relation binds as its stored id, expanded or not', visibleWhen: cel("record.owner == 'u2'"), expected: [false, true] },
309+
{ label: '`previous` binds the persisted row, as on the record\'s edit form', visibleWhen: cel("previous.stage == 'closed_won'"), expected: [false, true] },
310+
];
311+
312+
describe('record:details evaluates a field\'s visibleWhen exactly as the form does (objectstack#35314)', () => {
313+
for (const c of MATRIX) {
314+
it(c.label, () => {
315+
const detail = [detailShows(c.visibleWhen, LOST), detailShows(c.visibleWhen, WON)];
316+
const form = [formShows(c.visibleWhen, LOST), formShows(c.visibleWhen, WON)];
317+
expect({ form, detail }).toEqual({ form: c.expected, detail: c.expected });
318+
});
319+
}
320+
321+
it('the host `current_user` scope binds on both surfaces', () => {
322+
const gate = cel("'sales_manager' in current_user.positions");
323+
const denied = hostScope(['sales']);
324+
const allowed = hostScope(['sales_manager']);
325+
const detail = [detailShows(gate, WON, { scope: denied }), detailShows(gate, WON, { scope: allowed })];
326+
const form = [formShows(gate, WON, denied), formShows(gate, WON, allowed)];
327+
expect({ form, detail }).toEqual({ form: [false, true], detail: [false, true] });
328+
});
329+
});
330+
331+
/* ═══════════════════════════════════════════════════════════════════════════
332+
* Every body the default record page is drawn from, and the authored ones
333+
* ═══════════════════════════════════════════════════════════════════════════ */
334+
335+
describe('every record:details body draws a field only where its visibleWhen admits it (objectstack#35314)', () => {
336+
const gate = cel("record.stage == 'closed_won'");
337+
const bodies: Array<{ body: string; schemaFor: SchemaFor; withGroups?: boolean; which?: 'win_reason' | 'memo' }> = [
338+
{ body: 'synthesized default page — a field in a declared group', schemaFor: synthesizedDefaultPage },
339+
{ body: 'synthesized default page — a field in the ungrouped bucket', schemaFor: synthesizedDefaultPage, which: 'memo' },
340+
{ body: 'running default page — a field in a declared group', schemaFor: runtimeDefaultPage },
341+
{ body: 'running default page — a field in the ungrouped bucket', schemaFor: runtimeDefaultPage, which: 'memo' },
342+
{ body: 'running default page of an object with no fieldGroups', schemaFor: runtimeDefaultPageUngrouped, withGroups: false },
343+
{ body: 'authored page — enumerated sections of bare names', schemaFor: authoredSections },
344+
{ body: 'authored page — a flat fields list', schemaFor: authoredFields },
345+
];
346+
347+
for (const b of bodies) {
348+
it(`${b.body}: hidden on LOST, drawn on WON`, () => {
349+
const opts = { schemaFor: b.schemaFor, withGroups: b.withGroups ?? true, which: b.which ?? 'win_reason' };
350+
expect([detailShows(gate, LOST, opts), detailShows(gate, WON, opts)]).toEqual([false, true]);
351+
});
352+
}
353+
354+
it('CONTROL — a field whose predicate holds and a field with none are drawn on the default page', () => {
355+
const objectSchema = objectSchemaWith(gate);
356+
renderDetails(synthesizedDefaultPage(objectSchema), LOST, objectSchema, {});
357+
expect(textCount(LOST.region)).toBe(1);
358+
// `loss_reason`'s own predicate holds on LOST.
359+
expect([textCount('Loss Reason'), textCount(LOST.loss_reason)]).toEqual([1, 1]);
360+
// `next_step` declares none.
361+
expect([textCount('Next Step'), textCount(LOST.next_step)]).toEqual([1, 1]);
362+
});
363+
364+
it('a section every member of which the predicates hide draws no heading', () => {
365+
const objectSchema = {
366+
...objectSchemaWith(gate),
367+
fields: {
368+
...objectSchemaWith(gate).fields,
369+
loss_reason: { type: 'text', label: 'Loss Reason', group: 'outcome', visibleWhen: "record.stage == 'closed_won'" },
370+
next_step: { type: 'text', label: 'Next Step', group: 'outcome', visibleWhen: "record.stage == 'closed_won'" },
371+
},
372+
};
373+
renderDetails(synthesizedDefaultPage(objectSchema), LOST, objectSchema, {});
374+
expect(textCount(LOST.region)).toBe(1);
375+
expect(textCount('Outcome')).toBe(0);
376+
cleanup();
377+
renderDetails(synthesizedDefaultPage(objectSchema), WON, objectSchema, {});
378+
expect(textCount('Outcome')).toBe(1);
379+
});
380+
});

0 commit comments

Comments
 (0)