diff --git a/.changeset/35437-field-visiblewhen-highlights-drawer.md b/.changeset/35437-field-visiblewhen-highlights-drawer.md new file mode 100644 index 00000000000..1242defda7d --- /dev/null +++ b/.changeset/35437-field-visiblewhen-highlights-drawer.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-detail': patch +--- + +fix(plugin-detail): the highlights strip, the detail view and the record drawer no longer draw a field whose own `visibleWhen` is false for the record + +Clause-②: no +Metadata-protocol: none + +A field's object-level `visibleWhen` (`Field.visibleWhen`: "field is shown only when TRUE") now hides it on every record surface that draws fields, not only on the `record:details` body: the header highlights strip (`record:highlights`, and the strip a `detail-view` draws from `highlightFields`), the `detail-view` node's body and its header summary chips, and the record drawer that list, kanban, calendar, gantt and the other views open. Before, these surfaces drew such a field, label and value, on every record, so they disagreed with the edit form and the details body about the same record. + +Every surface calls the one implementation the details body uses, so the verdict is the form's own (`resolveFieldRuleState`), over the record shown (bound as `record` and as `previous`) and the host predicate scope (`current_user`). A predicate that cannot be evaluated still shows the field and warns once, as on the form (ADR-0137 D3). The verdict is the saved record's: an inline edit reveals a gated field after save. Display only: the record API still returns the field. diff --git a/ui/packages/plugin-detail/src/DetailView.tsx b/ui/packages/plugin-detail/src/DetailView.tsx index 1c488ed5f14..4f96ca65a25 100644 --- a/ui/packages/plugin-detail/src/DetailView.tsx +++ b/ui/packages/plugin-detail/src/DetailView.tsx @@ -46,7 +46,7 @@ import { ActivityTimeline } from './ActivityTimeline'; import { HistoryTimeline } from './HistoryTimeline'; import { RecordMetaFooter } from './RecordMetaFooter'; import { RecordPageProvenanceContext } from './recordPageProvenance'; -import { SchemaRenderer, SchemaErrorBoundary, toRenderableSchema, useSafeFieldLabel, useDataInvalidation, useInlineEdit, useRowPredicate, resolveApprovalLock, usePrintPage, useRecordContext } from '@object-ui/react'; +import { SchemaRenderer, SchemaErrorBoundary, toRenderableSchema, useSafeFieldLabel, useDataInvalidation, useInlineEdit, useRowPredicate, resolveApprovalLock, usePrintPage, useRecordContext, usePredicateScope } from '@object-ui/react'; import { buildExpandFields, declaredNameField, getRecordDisplayName, formatTitleTemplate, recordDelete, recordDisplayValueAt, resolveAffordance, toDisplayDate, userActionPredicates, withoutDeniedFields } from '@object-ui/core'; import { usePermissions } from '@object-ui/permissions'; import { useLocalization, useDisplayLocale, resolveFieldCurrency, recordCurrencyPath } from '@object-ui/i18n'; @@ -56,6 +56,7 @@ import { useRecordEditable } from './useRecordEditable'; import { getCellRenderer, resolveCellRendererType, coerceToSafeValue, formatPercent, percentCellScale } from '@object-ui/fields'; import { resolveFieldScale } from '@objectstack/spec/data'; import { hasCellValue } from './emptiness'; +import { dropFieldPredicateHidden, lazyPredicateRecord, type FieldPredicateGate } from './fieldPredicateVisibility'; import { enrichDetailField } from './fieldEnrichment'; import { chipTakesCellRenderer } from './summaryChipRenderers'; import { summaryChipPercentPoints } from './summaryChipPercent'; @@ -587,6 +588,39 @@ export const DetailView: React.FC = ({ ); + /** + * The field lists this view DRAWS: `schema`'s, less every field whose own + * `visibleWhen` is false for this record — judged by + * `dropFieldPredicateHidden` (`./fieldPredicateVisibility`), the one + * implementation the details body and the highlights strip call too, so the + * drawer and the `detail-view` node hide what the form hides (fail-open on a + * predicate that cannot be evaluated). The predicate is the object's + * declaration, so nothing is hidden before the object schema is known. + * + * Render-only: the record read above keeps `schema`'s lists (a `$expand` + * built from what is drawn would refetch whenever the verdict moved), and + * the verdict is the SAVED record's, as on the details body. + */ + const predicateScope = usePredicateScope(); + const drawn = React.useMemo(() => { + const gate: FieldPredicateGate = { + objectFields, + record: lazyPredicateRecord(data, objectFields), + scope: predicateScope, + where: (n) => `field '${n}' of detail-view on object '${schema.objectName ?? ''}'`, + }; + const dropSection = (section: S): S => ({ + ...section, + fields: dropFieldPredicateHidden(section.fields, gate), + }); + return { + fields: dropFieldPredicateHidden(schema.fields, gate), + sections: schema.sections?.map(dropSection), + sectionGroups: schema.sectionGroups?.map((group) => ({ ...group, sections: group.sections.map(dropSection) })), + shows: (name: string) => dropFieldPredicateHidden([name], gate).length === 1, + }; + }, [schema.fields, schema.sections, schema.sectionGroups, schema.objectName, objectFields, data, predicateScope]); + // Fire onDataLoaded whenever the record changes so hosts can publish it // (e.g. to the navigation breadcrumb or document title). React.useEffect(() => { @@ -1168,9 +1202,9 @@ export const DetailView: React.FC = ({ // for the whole body (`EmptySectionsFold`). Only when the sections ARE the // body: section groups draw fields of their own beside them. const foldEmptySections = (rendered: React.ReactNode) => - schema.sectionGroups?.length ? rendered : ( + drawn.sectionGroups?.length ? rendered : ( @@ -1230,7 +1264,7 @@ export const DetailView: React.FC = ({

{resolveDisplayTitle(titleRow, schema, objectSchema, t('detail.details'))}

- {effectiveSummaryFields.map((fieldName) => { + {effectiveSummaryFields.filter(drawn.shows).map((fieldName) => { const val = data?.[fieldName]; // Same definition as `has` above and as every other band of // the page (`./emptiness`, objectui#8376/#8394). A raw test @@ -1971,8 +2005,8 @@ export const DetailView: React.FC = ({ const detailsContent = (
{/* Section Groups */} - {schema.sectionGroups && schema.sectionGroups.length > 0 && ( - schema.sectionGroups.map((group, index) => ( + {drawn.sectionGroups && drawn.sectionGroups.length > 0 && ( + drawn.sectionGroups.map((group, index) => ( = ({ /> )) )} - {schema.sections && schema.sections.length > 0 && foldEmptySections( - schema.sections.map((section, index) => ( + {drawn.sections && drawn.sections.length > 0 && foldEmptySections( + drawn.sections.map((section, index) => ( = ({ )) )} - {schema.fields && schema.fields.length > 0 && !schema.sections?.length && ( + {drawn.fields && drawn.fields.length > 0 && !drawn.sections?.length && ( = ({ })() : ( <> {/* Section Groups */} - {schema.sectionGroups && schema.sectionGroups.length > 0 && ( + {drawn.sectionGroups && drawn.sectionGroups.length > 0 && (
- {schema.sectionGroups.map((group, index) => ( + {drawn.sectionGroups.map((group, index) => ( = ({ )} {/* Sections */} - {schema.sections && schema.sections.length > 0 && ( + {drawn.sections && drawn.sections.length > 0 && (
{(() => { - const renderSectionAt = (section: NonNullable[number], index: number) => ( + const renderSectionAt = (section: NonNullable[number], index: number) => ( = ({ /> ); - return emptySectionsAsLine && !schema.sectionGroups?.length ? ( + return emptySectionsAsLine && !drawn.sectionGroups?.length ? ( - ) : foldEmptySections(schema.sections!.map(renderSectionAt)); + ) : foldEmptySections(drawn.sections!.map(renderSectionAt)); })()}
)} {/* Direct Fields (if no sections) */} - {schema.fields && schema.fields.length > 0 && !schema.sections?.length && ( + {drawn.fields && drawn.fields.length > 0 && !drawn.sections?.length && ( = ({ if (!fields.length || !data) return null; + // A highlight whose field's own `visibleWhen` is false for this record is + // not drawn, in either mode: the strip judges it as the form and the details + // body do (`../fieldPredicateVisibility`, fail-open), against the SAVED + // record, as the details body does, so a draft edit reveals a gated field + // after save, not while typing. + const drawnFields = dropFieldPredicateHidden(fields, { + objectFields: objectSchema?.fields, + record: lazyPredicateRecord(data, objectSchema?.fields), + scope: predicateScope, + where: (n) => `field '${n}' of the highlights strip on object '${objectName ?? ''}'`, + }); + // In read mode we hide value-less fields to keep the strip dense; WHILE // EDITING we keep them so the user can fill an empty highlight in place. const hasValue = (f: HighlightField) => { const val = data?.[f.name]; return val !== null && val !== undefined && val !== ''; }; - const visibleFields = editing ? fields : fields.filter(hasValue); + const visibleFields = editing ? drawnFields : drawnFields.filter(hasValue); if (visibleFields.length === 0) return null; diff --git a/ui/packages/plugin-detail/src/__tests__/fieldVisibleWhen.surfaces-35437.test.tsx b/ui/packages/plugin-detail/src/__tests__/fieldVisibleWhen.surfaces-35437.test.tsx new file mode 100644 index 00000000000..9c5a6b50b76 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/fieldVisibleWhen.surfaces-35437.test.tsx @@ -0,0 +1,384 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#35437 — the record page's other surfaces honour a field's own + * `visibleWhen` the way the form and the details body do. + * + * `@objectstack/spec` `Field.visibleWhen`: "field is shown only when TRUE + * (else hidden)". The details body (`record:details`) applies it since + * objectstack#35314, through `dropFieldPredicateHidden` + * (`../fieldPredicateVisibility`). The surfaces pinned here drew the field on + * every record before this card: + * + * - the header highlights strip — `record:highlights`, drawn by + * `HeaderHighlight`; + * - the `detail-view` node — its body, its own highlights strip and its + * header summary chips; + * - the record drawer — `RecordDetailDrawer`, whose body is a `DetailView`. + * + * ## How "the way the form does" is measured, not asserted + * + * Every case renders the same row on every surface AND through the entry form + * renderer (`@object-ui/components`' `form`, an edit form of that row, the + * field carrying the same predicate). The assertion compares all of them with + * the expected verdict at once, so two surfaces wrong the same way still turn + * it red, and a red names the surface. + * + * ## The harness cannot read as a refusal + * + * Every render first finds an ungated anchor value (and the form its ungated + * `Stage` control), and the two `DetailView` surfaces wait for their own + * object-schema read to land. Each throws `HARNESS DEAD` otherwise, so a + * surface that rendered nothing, or rendered before it knew the predicate, + * can never pass a "hidden" leg. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor, act } from '@testing-library/react'; +import * as React from 'react'; +import { ComponentRegistry } from '@object-ui/core'; +import { + RecordContextProvider, + PredicateScopeProvider, + SchemaRenderer, + SchemaRendererProvider, +} from '@object-ui/react'; +// Module-scope side-effect imports (objectui#3010): the registry must hold the +// entry form's `form` renderer and the `detail-view` node before a leg looks +// them up. +import '@object-ui/components'; +import '@object-ui/fields'; +import '../index'; +import { RecordHighlightsRenderer } from '../renderers/record-highlights'; +import { RecordDetailDrawer } from '../RecordDetailDrawer'; +import { DetailView } from '../DetailView'; + +/* ───────────────────────────────────────────────────────────────────────────── + * Fixture + * ─────────────────────────────────────────────────────────────────────────── */ + +const OBJECT_NAME = 'qa_field_gate_surfaces'; +const cel = (source: string) => ({ dialect: 'cel', source }); + +const WIN_LABEL = 'Win Reason'; + +/** + * `win_reason` carries the predicate under test, `loss_reason` a fixed one + * that holds on LOST, `next_step` none. `region` is the ungated anchor and + * `name` the record's title, so no header title ladder reads a leg's value. + */ +const objectSchemaWith = (visibleWhen: unknown) => ({ + name: OBJECT_NAME, + fields: { + name: { type: 'text', label: 'Name' }, + region: { type: 'text', label: 'Region' }, + stage: { type: 'text', label: 'Stage' }, + // Declared, and carried by NO row: the null-seed case. + tier: { type: 'text', label: 'Tier' }, + // A relation: these surfaces carry it expanded, the form its id. + owner: { type: 'lookup', label: 'Owner', reference: 'sys_user' }, + loss_reason: { type: 'text', label: 'Loss Reason', visibleWhen: "record.stage == 'closed_lost'" }, + win_reason: { type: 'text', label: WIN_LABEL, ...(visibleWhen !== undefined ? { visibleWhen } : {}) }, + next_step: { type: 'text', label: 'Next Step' }, + }, +}); + +type Row = Record; +const LOST: Row = { + id: 'R1', + name: 'Deal one', + region: 'region-of-lost', + stage: 'closed_lost', + owner: { id: 'u1', name: 'Kim' }, + loss_reason: 'loss-of-lost', + win_reason: 'win-of-lost', + next_step: 'next-of-lost', +}; +const WON: Row = { + id: 'R2', + name: 'Deal two', + region: 'region-of-won', + stage: 'closed_won', + owner: { id: 'u2', name: 'Lee' }, + loss_reason: 'loss-of-won', + win_reason: 'win-of-won', + next_step: 'next-of-won', +}; + +/** The host scope `ExpressionProvider` mounts. */ +function hostScope(positions: string[]) { + const user = { id: 'u1', name: 'Kim', positions }; + return { current_user: user, user, ctx: { user }, os: { user }, features: {} }; +} + +const textCount = (text: string): number => screen.queryAllByText(text).length; + +/** A data source whose only read is the object schema the surface asks for. */ +function dataSourceFor(objectSchema: Record) { + return { getObjectSchema: vi.fn().mockResolvedValue(objectSchema) } as any; +} + +/* ── the surfaces ─────────────────────────────────────────────────────────── */ + +type Surface = 'highlights' | 'node' | 'nodeStrip' | 'drawer'; +const SURFACES: Surface[] = ['highlights', 'node', 'nodeStrip', 'drawer']; + +const STRIP_FIELDS = ['region', 'stage', 'loss_reason', 'win_reason', 'next_step']; + +async function mountSurface( + surface: Surface, + row: Row, + objectSchema: Record, + scope: Record, +): Promise { + const ds = dataSourceFor(objectSchema); + const wrap = (ui: React.ReactElement) => render({ui}); + if (surface === 'highlights') { + wrap( + + + , + ); + return; + } + if (surface === 'node') { + wrap( + + ({ name, label: (objectSchema.fields as any)[name].label })), + }], + } as never} + /> + , + ); + } else if (surface === 'nodeStrip') { + // The node's own highlights strip, with nothing gated in its body. + wrap( + n !== 'region').map((name) => ({ name })), + } as any} + />, + ); + } else { + wrap( + {}} + title="Deal" + record={row} + objectName={OBJECT_NAME} + recordId={row.id} + dataSource={ds} + objectSchema={objectSchema as any} + />, + ); + } + // A `DetailView` learns the predicate from its own object-schema read: wait + // for it to land, so a "hidden" leg is never read off the pre-schema frame. + await waitFor(() => expect(ds.getObjectSchema).toHaveBeenCalledWith(OBJECT_NAME)); + await act(async () => {}); +} + +/** + * Is `field` drawn on `surface` — label AND value? The field goes whole or + * stays whole: a label without its value (or the reverse) is a defect of its + * own, never a verdict. + */ +async function surfaceShows( + surface: Surface, + visibleWhen: unknown, + row: Row, + { scope = {}, field = 'win_reason', label = WIN_LABEL }: { scope?: Record; field?: string; label?: string } = {}, +): Promise { + await mountSurface(surface, row, objectSchemaWith(visibleWhen), scope); + const anchor = textCount(row.region); + if (anchor !== 1) { + cleanup(); + throw new Error(`HARNESS DEAD on ${surface}: expected the ungated Region value once, found ${anchor}`); + } + const labels = textCount(label); + const values = textCount(row[field]); + cleanup(); + if (labels === 1 && values === 1) return true; + if (labels === 0 && values === 0) return false; + throw new Error(`PARTIAL FIELD on ${surface}: label ${labels}, value ${values}`); +} + +/** The edit form for the same row, the field carrying the same predicate. */ +function formShows(visibleWhen: unknown, row: Row, scope: Record = {}): boolean { + const Form = ComponentRegistry.get('form')!; + const values = { ...row, owner: row.owner?.id }; + render( + +
+ , + ); + const anchor = screen.queryAllByLabelText(/^Stage/).length; + if (anchor !== 1) { + cleanup(); + throw new Error(`HARNESS DEAD: expected the ungated form field "Stage" once, found ${anchor}`); + } + const shown = screen.queryAllByLabelText(new RegExp(`^${WIN_LABEL}`)).length; + cleanup(); + if (shown === 1) return true; + if (shown === 0) return false; + throw new Error(`form drew "${WIN_LABEL}" ${shown} times`); +} + +/** Every surface's verdict on [LOST, WON], keyed by surface. */ +async function surfaceVerdicts( + visibleWhen: unknown, + rows: [Row, Row], + scopes: [Record, Record] = [{}, {}], +): Promise> { + const out = {} as Record; + for (const s of SURFACES) { + out[s] = [ + await surfaceShows(s, visibleWhen, rows[0], { scope: scopes[0] }), + await surfaceShows(s, visibleWhen, rows[1], { scope: scopes[1] }), + ]; + } + return out; +} + +const every = (v: [boolean, boolean]): Record => + Object.fromEntries(SURFACES.map((s) => [s, v])) as Record; + +/* ── `useRecordEditable`'s explain probe — a router, not a sink ──────────── */ + +const EXPLAIN_ROUTE = '/api/v1/security/explain'; +let fetchCalls: string[] = []; + +beforeEach(() => { + fetchCalls = []; + // A faulted predicate warns once per text on every surface — expected here. + vi.spyOn(console, 'warn').mockImplementation(() => {}); + vi.stubGlobal( + 'fetch', + vi.fn(async (input: unknown) => { + const url = String( + input && typeof input === 'object' && 'url' in input ? (input as { url: unknown }).url : input, + ); + fetchCalls.push(url); + if (url !== EXPLAIN_ROUTE) return { ok: false, status: 404, json: async () => ({}) }; + return { ok: true, status: 200, json: async () => ({ record: { visible: true } }) }; + }), + ); +}); + +afterEach(() => { + expect(fetchCalls.filter((url) => url !== EXPLAIN_ROUTE)).toEqual([]); + cleanup(); + vi.unstubAllGlobals(); + vi.restoreAllMocks(); +}); + +/* ═══════════════════════════════════════════════════════════════════════════ + * The parity matrix — every surface against the form + * ═══════════════════════════════════════════════════════════════════════════ */ + +type Case = { label: string; visibleWhen: unknown; expected: [boolean, boolean] }; + +const MATRIX: Case[] = [ + { label: 'envelope `record.stage == closed_won` — the card reproduction; CONTROL: drawn where it holds', visibleWhen: cel("record.stage == 'closed_won'"), expected: [false, true] }, + { label: 'bare-string `record.stage == closed_won` — the same verdict as the envelope', visibleWhen: "record.stage == 'closed_won'", expected: [false, true] }, + { label: 'CONTROL — no predicate: the field is drawn on every row', visibleWhen: undefined, expected: [true, true] }, + { label: 'CONTROL — a parse error SHOWS the field (fail-open, ADR-0137 D3)', visibleWhen: cel('record.stage =='), expected: [true, true] }, + { label: 'CONTROL — a bare identifier is unbound and SHOWS the field (fail-open, ADR-0137 D3)', visibleWhen: "stage == 'closed_won'", expected: [true, true] }, + { label: 'a declared field the row does not carry compares as null — evaluated, not faulted', visibleWhen: cel("record.tier == 'gold'"), expected: [false, false] }, + { label: 'a relation binds as its stored id, expanded or not', visibleWhen: cel("record.owner == 'u2'"), expected: [false, true] }, + { label: '`previous` binds the persisted row, as on the record\'s edit form', visibleWhen: cel("previous.stage == 'closed_won'"), expected: [false, true] }, +]; + +describe('the highlights strip, the detail-view node and the record drawer judge a field\'s visibleWhen as the form does (objectstack#35437)', () => { + for (const c of MATRIX) { + it(c.label, async () => { + const form = [formShows(c.visibleWhen, LOST), formShows(c.visibleWhen, WON)]; + const surfaces = await surfaceVerdicts(c.visibleWhen, [LOST, WON]); + expect({ form, ...surfaces }).toEqual({ form: c.expected, ...every(c.expected) }); + }); + } + + it('the host `current_user` scope binds on every surface', async () => { + const gate = cel("'sales_manager' in current_user.positions"); + const denied = hostScope(['sales']); + const allowed = hostScope(['sales_manager']); + const form = [formShows(gate, WON, denied), formShows(gate, WON, allowed)]; + const surfaces = await surfaceVerdicts(gate, [WON, WON], [denied, allowed]); + expect({ form, ...surfaces }).toEqual({ form: [false, true], ...every([false, true]) }); + }); + + it('CONTROL — beside a hidden field, a field whose predicate holds and a field with none stay drawn', async () => { + const gate = cel("record.stage == 'closed_won'"); + for (const s of SURFACES) { + expect(await surfaceShows(s, gate, LOST, { field: 'loss_reason', label: 'Loss Reason' })).toBe(true); + expect(await surfaceShows(s, gate, LOST, { field: 'next_step', label: 'Next Step' })).toBe(true); + expect(await surfaceShows(s, gate, LOST)).toBe(false); + } + }); +}); + +/* ═══════════════════════════════════════════════════════════════════════════ + * The detail-view node's header summary chips + * ═══════════════════════════════════════════════════════════════════════════ */ + +describe('the detail-view header draws no summary chip for a field its visibleWhen hides (objectstack#35437)', () => { + async function chipShows(row: Row): Promise { + // `stage` is the chip the header picks on its own (a status-like field + // with a value); here it is the gated field. + const objectSchema = objectSchemaWith(undefined); + (objectSchema.fields as Record).stage = { + type: 'text', label: 'Stage', visibleWhen: "record.region == 'region-of-won'", + }; + await mountSurface('node', row, objectSchema, {}); + const header = document.querySelector('h1')?.parentElement; + if (!header || !header.textContent?.includes(row.name)) { + cleanup(); + throw new Error('HARNESS DEAD: the record title never drew'); + } + const shown = Array.from(header.querySelectorAll('*')).some((el) => el.textContent === row.stage); + cleanup(); + return shown; + } + + it('a `stage` chip is drawn on WON and not on LOST', async () => { + expect([await chipShows(LOST), await chipShows(WON)]).toEqual([false, true]); + }); +}); diff --git a/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts b/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts new file mode 100644 index 00000000000..9e5f3813a9d --- /dev/null +++ b/ui/packages/plugin-detail/src/fieldPredicateVisibility.ts @@ -0,0 +1,127 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * A field's own `visibleWhen` on the record surfaces of this package — the ONE + * implementation every surface that draws a record's fields calls: the details + * body (`record:details`), the header highlights strip (`HeaderHighlight`, for + * `record:highlights` and `DetailView`'s own strip) and `DetailView`'s body and + * summary chips (the `detail-view` node and the record drawer). + * + * Module-internal: not exported from the package barrel. + */ + +import { + columnIdentity, + resolveFieldRuleState, + toPredicateRecord, + type FieldRulePredicate, +} from '@object-ui/core'; + +/** + * The record a field's or a field group's `visibleWhen` is evaluated against — + * assembled the way the entry form assembles its own (objectui#11630). + * + * The form's `ruleRecord` (`@object-ui/components`' form renderer) seeds every + * declared field to `null` and then overlays the DEFINED values it holds, so a + * predicate naming a column the read did not return compares against `null` + * instead of faulting on a missing key. This does the same over the object's + * declared fields and the bound record. + * + * Relations are collapsed back to their stored foreign key first + * (`toPredicateRecord`): the edit form reads its record without `$expand`, so + * `record.owner == 'u1'` sees the id there, while a record page's record may + * arrive expanded. Without the collapse one predicate would reach two verdicts + * on the same record. + */ +export function assemblePredicateRecord( + data: Record | null | undefined, + objectFields: Record | undefined, +): Record { + const out: Record = {}; + if (objectFields && typeof objectFields === 'object' && !Array.isArray(objectFields)) { + for (const name of Object.keys(objectFields)) out[name] = null; + } + const row = toPredicateRecord(data ?? {}, objectFields) as Record; + for (const key of Object.keys(row)) { + if (row[key] !== undefined) out[key] = row[key]; + } + return out; +} + +/** + * {@link assemblePredicateRecord}, assembled on first use and then reused — so + * a surface whose fields declare no predicate does no extra work. + */ +export function lazyPredicateRecord( + data: Record | null | undefined, + objectFields: Record | undefined, +): () => Record { + let record: Record | undefined; + return () => (record ??= assemblePredicateRecord(data, objectFields)); +} + +/** + * Does a FIELD's own `visibleWhen` (`@objectstack/spec` `Field.visibleWhen`: + * "field is shown only when TRUE (else hidden)") admit its row on this record? + * + * ⭐ The form's judge, called the form's way: `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 a field group's gate + * (fail-closed, `record:details`' `sectionPredicateVisible`), deliberately — + * each slot keeps the direction the form gives it. The record is bound as + * `record` AND as `previous`: an edit form binds `previous` to the persisted + * row, and the row a record surface shows IS the persisted row. + * + * Display only, as on the form: the record API serves the field either way. + */ +export function fieldPredicateVisible( + visibleWhen: FieldRulePredicate, + record: Record, + scope: Record, + where: string, +): boolean { + return resolveFieldRuleState({ visibleWhen }, record, {}, record, scope, where).visible; +} + +/** What {@link dropFieldPredicateHidden} judges a list against. */ +export interface FieldPredicateGate { + /** The OBJECT's field declarations — where a field's `visibleWhen` is read, by name. */ + objectFields: Record | null | undefined; + /** The record, as {@link lazyPredicateRecord} hands it: asked only when a predicate is declared. */ + record: () => Record; + /** The host predicate scope (`usePredicateScope()`): `current_user`, `features`. */ + scope: Record; + /** Names the surface in the one-time fault warning, for the field `name`. */ + where: (name: string) => string; +} + +/** + * Drop every entry whose field's own `visibleWhen` is FALSE for the record — + * see {@link fieldPredicateVisible}. An entry is a field name, a `{ name }` or + * a `{ field }` descriptor (`columnIdentity`); the predicate is the OBJECT's + * declaration of that field, never a key on the entry. An entry whose field + * declares no predicate, or that names no field, is kept as it is. + */ +export function dropFieldPredicateHidden(list: T[], gate: FieldPredicateGate): T[]; +export function dropFieldPredicateHidden(list: T[] | undefined, gate: FieldPredicateGate): T[] | undefined; +export function dropFieldPredicateHidden(list: T[] | undefined, gate: FieldPredicateGate): T[] | undefined { + if (!list) return list; + return list.filter((entry) => { + const name = columnIdentity(entry); + const declared = name ? (gate.objectFields?.[name] as { visibleWhen?: unknown } | undefined) : undefined; + const visibleWhen = declared?.visibleWhen; + if (visibleWhen == null) return true; + return fieldPredicateVisible( + visibleWhen as FieldRulePredicate, + gate.record(), + gate.scope, + gate.where(name!), + ); + }); +} diff --git a/ui/packages/plugin-detail/src/renderers/record-details.tsx b/ui/packages/plugin-detail/src/renderers/record-details.tsx index 5bbc6fd16e1..e8c63e5d429 100644 --- a/ui/packages/plugin-detail/src/renderers/record-details.tsx +++ b/ui/packages/plugin-detail/src/renderers/record-details.tsx @@ -28,9 +28,7 @@ import { type FieldRulePredicate, recordDisplayValueAt, evalFieldPredicate, - resolveFieldRuleState, resolveNameField, - toPredicateRecord, withoutDeniedFields, } from '@object-ui/core'; import { DetailView } from '../DetailView'; @@ -41,6 +39,7 @@ import { RecordFieldAccessForRecord } from '../recordFieldAccess'; import { deriveFieldGroupDetailEntries, type FieldGroupDetailEntry } from '../synth/buildDefaultPageSchema'; import { useRecordAriaProps } from './recordComponentAria'; import { recordBindingBlock } from './recordBinding'; +import { dropFieldPredicateHidden, lazyPredicateRecord } from '../fieldPredicateVisibility'; /** Normalize a field entry (string | {field} | {name}) to its machine name. */ const fieldName = (entry: any): string | null => columnIdentity(entry) ?? null; @@ -168,37 +167,6 @@ function fillSectionHeadingCount(heading: string, count: number): string { return heading.replace(new RegExp(SECTION_HEADING_COUNT_HOLE.source, 'g'), String(count)); } -/** - * The record a section's `visibleWhen` is evaluated against — assembled the - * way the entry form assembles its own (objectui#11630). - * - * The form's `ruleRecord` (`@object-ui/components`' form renderer) seeds every - * declared field to `null` and then overlays the DEFINED values it holds, so a - * predicate naming a column the read did not return compares against `null` - * instead of faulting on a missing key. This does the same over the object's - * declared fields and the bound record. - * - * Relations are collapsed back to their stored foreign key first - * (`toPredicateRecord`): the edit form reads its record without `$expand`, so - * `record.owner == 'u1'` sees the id there, while this page's record may arrive - * expanded. Without the collapse one predicate would reach two verdicts on the - * same record. - */ -function sectionPredicateRecord( - data: Record | null | undefined, - objectFields: Record | undefined, -): Record { - const out: Record = {}; - if (objectFields && typeof objectFields === 'object' && !Array.isArray(objectFields)) { - for (const name of Object.keys(objectFields)) out[name] = null; - } - const row = toPredicateRecord(data ?? {}, objectFields) as Record; - for (const key of Object.keys(row)) { - if (row[key] !== undefined) out[key] = row[key]; - } - return out; -} - /** * Does a field GROUP's ADR-0089 `visibleWhen` admit its section on this * record? (objectui#11630 — "the detail page evaluates `visibleWhen` per group @@ -224,9 +192,9 @@ function sectionPredicateRecord( * (`sectionGateVisible` in `@object-ui/components`' form renderer), with the * same three inputs it passes — * - * - `record` — {@link sectionPredicateRecord}; values bind under `record.` - * only, so a bare `kind == 'pro'` is an unbound identifier on both - * surfaces; + * - `record` — `assemblePredicateRecord` (`../fieldPredicateVisibility`); + * values bind under `record.` only, so a bare `kind == 'pro'` is an + * unbound identifier on both surfaces; * - `previous` — the SAME record. An edit form binds `previous` to the * persisted row, and the row this page shows IS the persisted row, so a * `previous.*` predicate reaches the verdict it reaches on that record's @@ -262,38 +230,6 @@ function sectionPredicateVisible( }); } -/** - * Does a FIELD's own `visibleWhen` (`@objectstack/spec` `Field.visibleWhen`: - * "field is shown only when TRUE (else hidden)") admit its row on this record? - * - * Asked of every field this body draws, whatever section carries it — a - * `{ group }` reference, an enumerated section (the default page's ungrouped - * bucket and its no-`fieldGroups` split are enumerated sections, the same - * shape an authored page writes) or the flat `fields` list. The predicate is - * the OBJECT's declaration of the field, read by name, never a key on the - * section entry. - * - * ⭐ The form's judge, called the form's way: `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 a group's gate - * ({@link sectionPredicateVisible}, fail-closed), deliberately — each slot - * keeps the direction the form gives it. The inputs are the ones the group - * gate passes: {@link sectionPredicateRecord} as `record` and as `previous`, - * and the host predicate scope. - * - * Display only, as on the form: the record API serves the field either way. - */ -function fieldPredicateVisible( - visibleWhen: FieldRulePredicate, - record: Record, - scope: Record, - where: string, -): boolean { - return resolveFieldRuleState({ visibleWhen }, record, {}, record, scope, where).visible; -} - /** * Fold a declared pointer pair's TYPE half into its id half's card * (objectui#13102). @@ -912,29 +848,22 @@ const RecordDetailsBody: React.FC = ({ // The record a group's or a field's `visibleWhen` is evaluated against — // assembled only when a predicate is actually declared, so a body without // one does no extra work and renders exactly as before. - let sectionRecord: Record | undefined; - const predicateRecord = (): Record => - (sectionRecord ??= sectionPredicateRecord(ctx.data, objSchemaFields)); + const predicateRecord = lazyPredicateRecord(ctx.data, objSchemaFields); /** * Drop every row whose field's own `visibleWhen` is FALSE for this record — - * see {@link fieldPredicateVisible}. Applied to every list this body draws, - * after the other folds, so it reads only the rows that would be drawn. + * `dropFieldPredicateHidden` (`../fieldPredicateVisibility`), the one + * implementation the highlights strip and `DetailView` call too. Applied to + * every list this body draws, after the other folds, so it reads only the + * rows that would be drawn. */ - const dropPredicateHidden = (list: any[] | undefined): any[] | undefined => { - if (!list) return list; - return list.filter((e) => { - const n = fieldName(e); - const visibleWhen = n ? objSchemaFields?.[n]?.visibleWhen : undefined; - if (visibleWhen == null) return true; - return fieldPredicateVisible( - visibleWhen as FieldRulePredicate, - predicateRecord(), - predicateScope, - `field '${n}' of record:details on object '${objectName}'`, - ); + const dropPredicateHidden = (list: any[] | undefined): any[] | undefined => + dropFieldPredicateHidden(list, { + objectFields: objSchemaFields, + record: predicateRecord, + scope: predicateScope, + where: (n) => `field '${n}' of record:details on object '${objectName}'`, }); - }; // ── The declared fallback body (objectui#12433) ───────────────────────── //