diff --git a/.changeset/37891-phone-card-highlight-fields.md b/.changeset/37891-phone-card-highlight-fields.md new file mode 100644 index 00000000000..ba96731fe75 --- /dev/null +++ b/.changeset/37891-phone-card-highlight-fields.md @@ -0,0 +1,12 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/plugin-list': patch +'@object-ui/plugin-detail': patch +--- + +Clause-②: no +Metadata-protocol: none + +Phone list cards now follow the object's `highlightFields`. When an object declares them, a card's amount is the first of those fields that draws as money, and its subtitle is the next three, in that order, with empty values dropped and each number, currency or percent part under its field label (`Quantity 2 · Sales Price ¥6,000.00 · Discount % 10.00%`). The view's column order no longer decides the card, so an order line that declares `highlightFields: ['total_price', 'quantity', 'unit_price', 'discount']` shows its line total bottom right while its wide table keeps its columns. A highlighted field no column shows is drawn too: the grid's own fetch, the list page's fetch and the related list's fetch now ask for the object's `highlightFields` beside its name field, through the same field-level security gate. + +This changes the phone card of every object that declares `highlightFields` and shows its fields in a different order, or shows more than two of them: review an object's `highlightFields` order if its phone list now reads differently. An object without `highlightFields` keeps the column-order card. Nothing changes on desktop tables, apart from the fetch asking for the highlighted fields. diff --git a/ui/packages/plugin-detail/src/RelatedList.tsx b/ui/packages/plugin-detail/src/RelatedList.tsx index 899b72305bd..5097bd657c9 100644 --- a/ui/packages/plugin-detail/src/RelatedList.tsx +++ b/ui/packages/plugin-detail/src/RelatedList.tsx @@ -2014,6 +2014,21 @@ export const RelatedList: React.FC = ({ projection.add(declaredName); } } + // [objectstack#37891] The child object's `highlightFields` (ADR-0085). + // On a phone the enlarged tab's grid draws each row as a card whose + // amount and subtitle are those fields, in that order, whether or not a + // column shows them. Fetched, never drawn as columns; on every + // viewport, as the gallery cover above, so crossing the breakpoint never + // refetches. Through the name field's gates: declared, readable, and not + // one the block redacts. + const highlights = (objectSchema as { highlightFields?: unknown } | undefined)?.highlightFields; + if (Array.isArray(highlights)) { + for (const field of highlights) { + if (typeof field !== 'string' || field === '' || redactedFields.has(field)) continue; + if (parentRelationshipFieldDef(fields, field) === undefined || !readable(field)) continue; + projection.add(field); + } + } } return Array.from(projection); }, [columns, redactedFields, referenceField, objectName, api, perms, expandFields, objectSchema, rowActions]); diff --git a/ui/packages/plugin-detail/src/__tests__/RelatedList.selectFls-10186.test.tsx b/ui/packages/plugin-detail/src/__tests__/RelatedList.selectFls-10186.test.tsx index 1dc35bbb898..7fbdfeb072b 100644 --- a/ui/packages/plugin-detail/src/__tests__/RelatedList.selectFls-10186.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RelatedList.selectFls-10186.test.tsx @@ -341,3 +341,46 @@ describe('RelatedList row fetch — the derived-columns boundary (objectui#10186 for (const params of rowFetches(ds)) expect('$select' in params).toBe(false); }); }); + +/** + * objectstack#37891 — the child object's `highlightFields` (ADR-0085) ride + * along. On a phone the enlarged tab's grid draws each row as a card whose + * amount and subtitle are those fields, in that order, whether or not a + * column shows them, so the rows this list reads must carry them. Through the + * name field's gates: declared, readable, not redacted. + * + * Directions on the base tree, measured by reverting the fix: + * a declared, readable highlighted field no column shows is requested RED + * a highlighted field FLS denies is not requested RED (the readable one is missing too) + * control: no highlightFields keeps the projection byte-identical GREEN + */ +describe('RelatedList row fetch — the child object\'s highlightFields ride along (objectstack#37891)', () => { + const withHighlights = { name: OBJECT, highlightFields: ['salary', 'title', 'undeclared_field'], fields: baseFields }; + const lastSelect = (ds: ReturnType): string[] => + rowFetches(ds).at(-1)?.$select ?? []; + const schemaLanded = (): boolean => + tableDrawn() && typeof (h.schema?.columns ?? []).find((c: any) => c.accessorKey === 'name')?.cell === 'function'; + + it('requests a declared, readable highlighted field no column shows, and never an undeclared one', async () => { + const ds = makeDataSource(withHighlights); + renderList(ds, [], { columns: ['name'] }); + await waitFor(() => expect(lastSelect(ds)).toContain('salary')); + expect(lastSelect(ds)).toEqual(['id', 'name', 'salary', 'title']); + expect(drawnKeys()).not.toContain('salary'); + }); + + it('does not request a highlighted field FLS denies', async () => { + const ds = makeDataSource(withHighlights); + renderList(ds, denying('salary'), { columns: ['name'] }); + await waitFor(() => expect(schemaLanded()).toBe(true)); + for (const params of rowFetches(ds)) expect(params.$select).not.toContain('salary'); + expect(lastSelect(ds)).toEqual(['id', 'name', 'title']); + }); + + it('control: a child with no highlightFields sends the projection it sent before', async () => { + const ds = makeDataSource(); + renderList(ds, [], { columns: ['name'] }); + await waitFor(() => expect(schemaLanded()).toBe(true)); + expect(lastSelect(ds)).toEqual(['id', 'name']); + }); +}); diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 605747b9c0b..73acc468b93 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -2112,7 +2112,7 @@ export const ObjectGrid: React.FC = ({ useObjectGridDiagnostics(schema); // `generateColumns`, the column generator, in hook order (`./objectGridGenerateColumns`). - const { generateColumns } = useObjectGridGenerateColumns({ + const { generateColumns, synthesizeFieldColumn } = useObjectGridGenerateColumns({ schema, dataSource, data, dataConfig, hasInlineData, objectName, objectSchema, objectFields, objectTypesPending, schemaFields, schemaColumns, perms, navigation, executeAction, predicateScope, resolveFieldLabel, translateOptions, uiLanguage, recordLinkAdornment, rowOpensRecord, @@ -4414,8 +4414,37 @@ export const ObjectGrid: React.FC = ({ // A WITHHELD column (objectui#10657: the object's field types are still // unknown, and the column has no type of its own) is handled the same way: // its `cell` draws the mask. + // objectstack#37891 — the card's BODY. When the object declares + // `highlightFields` (ADR-0085's "which fields matter most", in priority + // order) the card reads its amount and subtitle from that list, in that + // order, whether or not the view shows each field as a column: the wide + // table keeps its own columns and the phone card follows the object. A + // shown column is drawn through its own draft; a field no column shows is + // drawn through the draft the synthesized grid would give it + // (`synthesizeFieldColumn`: the field's renderer, its translated label, and + // field-level security, so a field the viewer may not read is left out). + // The fetches that feed this grid ask for those fields beside the name + // field. An object that declares none keeps the shown columns' order. + const highlightNames = Array.isArray((objectSchema as any)?.highlightFields) + ? [...new Set(((objectSchema as any).highlightFields as unknown[]) + .filter((n): n is string => typeof n === 'string' && !!objectFields?.[n]))] + : []; + const followsHighlights = highlightNames.length > 0; + const cardColMap = new Map(colMap); + const highlightColumns = highlightNames + .filter((n) => n !== titleKey) + .map((n) => { + const shown = colMap.get(n); + if (shown) return shown; + const drafted = synthesizeFieldColumn(n); + if (drafted) cardColMap.set(n, drafted); + return drafted; + }) + .filter((c): c is ObjectGridColumnDraft => c !== null && c !== undefined); + const cardBodyColumns = followsHighlights ? highlightColumns : bodyColumns; + const isMaskedCardColumn = (key: string) => - isMaskedGridColumn(colMap.get(key)?.type, objectFields?.[key]?.type, objectTypesPending); + isMaskedGridColumn(cardColMap.get(key)?.type, objectFields?.[key]?.type, objectTypesPending); // objectstack#28484 — a phone's card row is the board's list row: the // title, ONE subtitle line and ONE status chip at the right, with no @@ -4450,12 +4479,31 @@ export const ObjectGrid: React.FC = ({ const def = objectFields?.[c.accessorKey]; return def?.type === c.type && resolveFormulaValueType(def, 0) === 'currency'; }; - const amountCol = bodyColumns.find( - (c) => c !== statusCol && drawsAsMoney(c) && !isMaskedCardColumn(c.accessorKey), + // objectstack#37891 — read from the card body above: with `highlightFields` + // the amount is the first of them that draws as money (an order line + // declaring `['total_price', 'quantity', 'unit_price', 'discount']` shows + // its total, not the unit price its table happens to show first), and the + // subtitle takes the next three, in that order, each number, currency and + // percent part under its field label, so `2 · 10` reads as quantities. + const amountCol = cardBodyColumns.find( + (c) => c.accessorKey !== statusKey && drawsAsMoney(c) && !isMaskedCardColumn(c.accessorKey), ); - const subtitleColumns = bodyColumns - .filter((c) => c !== statusCol && c !== amountCol && !titleReads.has(c.accessorKey)) - .slice(0, 2); + const subtitleColumns = cardBodyColumns + .filter((c) => c.accessorKey !== statusKey && c !== amountCol && !titleReads.has(c.accessorKey)) + .slice(0, followsHighlights ? 3 : 2); + const labelsSubtitlePart = (c: ObjectGridColumnDraft): boolean => { + if (!followsHighlights) return false; + if (c.type === 'number' || c.type === 'currency' || c.type === 'percent') return true; + if (c.type !== 'formula' && c.type !== 'summary') return false; + const def = objectFields?.[c.accessorKey]; + if (def?.type !== c.type) return false; + const valueType = resolveFormulaValueType(def, 0); + return valueType === 'number' || valueType === 'currency' || valueType === 'percent'; + }; + const subtitlePartLabel = (c: ObjectGridColumnDraft): string | undefined => { + if (!labelsSubtitlePart(c)) return undefined; + return typeof c.header === 'string' && c.header !== '' ? c.header : undefined; + }; const isEmptyCardValue = (value: unknown) => value == null || value === ''; const cardCell = (col: ObjectGridColumnDraft, row: any): React.ReactNode => { const value = row[col.accessorKey]; @@ -4619,7 +4667,12 @@ export const ObjectGrid: React.FC = ({ {subtitle.map((col, i) => ( {i > 0 && · } - {cardCell(col, row)} + + {subtitlePartLabel(col) !== undefined && ( + {subtitlePartLabel(col)} + )} + {cardCell(col, row)} + ))} diff --git a/ui/packages/plugin-grid/src/__tests__/phoneCardAmount-34615.test.tsx b/ui/packages/plugin-grid/src/__tests__/phoneCardAmount-34615.test.tsx index eefba0b3901..5acdbf82ad3 100644 --- a/ui/packages/plugin-grid/src/__tests__/phoneCardAmount-34615.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/phoneCardAmount-34615.test.tsx @@ -257,3 +257,141 @@ describe('the phone card amount slot takes a formula or summary that draws as mo expect(within(card).queryByTestId('grid-card-amount-line')).toBeNull(); }); }); + +/** + * objectstack#37891 — when the object declares `highlightFields` (ADR-0085, + * "which fields matter most", in order), the phone card reads its amount and + * subtitle from that list, not from the view's column order: the amount is + * the first highlighted field that draws as money, the subtitle the next + * three, in that order, empty values dropped, and a number, currency or + * percent part carries its field label. A highlighted field no column shows + * is drawn too, and the grid's fetch asks for it. An object that declares no + * `highlightFields` keeps the column-order rule above. + * + * The fixture is HotCRM's order line (`crm_sales_order_line`), whose related + * list shows `line_number, product_title, quantity, unit_price, discount, + * total_price`: on the base tree its card read `1 · 2` with the unit price as + * the amount, whatever `highlightFields` said. + * + * ── Directions on the base tree (measured by reverting the fix) ────────── + * amount is the highlighted total, not the unit price RED + * subtitle is the labelled highlighted parts, in order RED + * a text part is drawn bare RED + * a highlighted field no column shows is drawn and fetched RED + * an empty highlighted part is dropped RED + * control: a masked highlighted field is neither amount nor part RED (its amount half: the base tree shows the unit price) + * control: no highlightFields keeps `1 · 2`, unit price, no labels GREEN + */ +describe('the phone card follows the object\'s highlightFields (objectstack#37891)', () => { + const LINE_OBJECT = 'crm_sales_order_line_37891'; + const LINE_FIELDS = { + id: { type: 'text' }, + product_title: { type: 'text', label: 'Product Title' }, + crm_product: { type: 'text', label: 'Product' }, + quantity: { type: 'number', label: 'Quantity', scale: 0 }, + unit_price: { type: 'currency', label: 'Sales Price' }, + discount: { type: 'percent', label: 'Discount %', scale: 2 }, + total_price: { + type: 'formula', + label: 'Total', + returnType: 'currency', + expression: 'record.quantity * record.unit_price * (1 - record.discount)', + }, + line_number: { type: 'number', label: 'Line #', scale: 0 }, + access_pin: { type: 'password', label: 'Access PIN' }, + }; + const LINE_ROWS = [ + { id: 'l1', line_number: 1, product_title: 'Admin Training Workshop', crm_product: 'Training', quantity: 2, unit_price: 6000, discount: 0.1, total_price: 10800, access_pin: 's3cr3t-pin' }, + { id: 'l2', line_number: 2, product_title: 'AI Agent Seat (Annual)', crm_product: 'Seat', quantity: 10, unit_price: 1000, discount: null, total_price: 10000, access_pin: 's3cr3t-pin' }, + ]; + /** HotCRM's `relatedListColumns` for the order's lines. */ + const RELATED = ['line_number', 'product_title', 'quantity', 'unit_price', 'discount', 'total_price']; + + async function lineCards(columns: string[], highlightFields?: string[]) { + setWidth(390); + const find = vi.fn(async () => ({ data: LINE_ROWS, total: LINE_ROWS.length, hasMore: false, pageSize: 50 })); + const dataSource = { + find, + getObjectSchema: async (name: string) => ({ + name, + nameField: 'product_title', + ...(highlightFields ? { highlightFields } : {}), + fields: structuredClone(LINE_FIELDS), + }), + } as never; + render( + + + + ({ field })), pagination: { pageSize: 50 } } as never} + dataSource={dataSource} + /> + + + , + ); + // The money cells read the field defs, so a CN¥ amount proves they landed. + await waitFor(() => expect(cards()).toHaveLength(2)); + await waitFor(() => expect(document.body.textContent).toContain('CN¥')); + expect(document.querySelector('table'), 'the card layout, not the table').toBeNull(); + return { find, first: cardOf('Admin Training Workshop'), second: cardOf('AI Agent Seat (Annual)') }; + } + const parts = (card: HTMLElement) => within(card).getAllByTestId('grid-card-subtitle-part'); + const labels = (card: HTMLElement) => + within(card).queryAllByTestId('grid-card-subtitle-label').map((el) => el.textContent?.trim()); + + it('takes the first highlighted money field as the amount: the line total, not the unit price the table shows first', async () => { + const { first } = await lineCards(RELATED, ['total_price', 'quantity', 'unit_price', 'discount']); + expect(within(first).getByTestId('grid-card-amount').textContent).toBe('CN¥10,800.00'); + }); + + it('draws the next highlighted fields as the subtitle, in order, each figure under its field label', async () => { + const { first } = await lineCards(RELATED, ['total_price', 'quantity', 'unit_price', 'discount']); + expect(parts(first)).toHaveLength(3); + expect(labels(first)).toEqual(['Quantity', 'Sales Price', 'Discount %']); + const [quantity, price, discount] = parts(first).map((p) => p.textContent); + expect(quantity).toBe('Quantity 2'); + expect(price).toBe('Sales Price CN¥6,000.00'); + expect(discount).toMatch(/^Discount % 10\.00\s?%$/); + // The line number the table shows first is no longer a subtitle part. + expect(within(first).getByTestId('grid-card-subtitle').textContent).not.toMatch(/^1 ·/); + }); + + it('labels only figures: a text part is drawn bare', async () => { + const { first } = await lineCards(RELATED, ['total_price', 'crm_product', 'quantity']); + expect(parts(first).map((p) => p.textContent)).toEqual(['Training', 'Quantity 2']); + expect(labels(first)).toEqual(['Quantity']); + }); + + it('drops an empty highlighted part rather than drawing it', async () => { + const { second } = await lineCards(RELATED, ['total_price', 'quantity', 'unit_price', 'discount']); + expect(within(second).getByTestId('grid-card-amount').textContent).toBe('CN¥10,000.00'); + expect(labels(second)).toEqual(['Quantity', 'Sales Price']); + }); + + it('draws a highlighted field no column shows, and the fetch asks for it', async () => { + const { first, find } = await lineCards( + ['line_number', 'product_title', 'quantity', 'unit_price'], + ['total_price', 'quantity', 'unit_price', 'discount'], + ); + expect(within(first).getByTestId('grid-card-amount').textContent).toBe('CN¥10,800.00'); + expect(labels(first)).toEqual(['Quantity', 'Sales Price', 'Discount %']); + const select = (find.mock.calls.at(-1) as unknown[] | undefined)?.[1] as { $select?: string[] } | undefined; + expect(select?.$select).toEqual(expect.arrayContaining(['total_price', 'discount'])); + }); + + it('CONTROL: an object with no highlightFields keeps the column-order card (line number · quantity, unit price, no labels)', async () => { + const { first } = await lineCards(RELATED); + expect(within(first).getByTestId('grid-card-subtitle').textContent).toBe('1 · 2'); + expect(within(first).getByTestId('grid-card-amount').textContent).toBe('CN¥6,000.00'); + expect(labels(first)).toEqual([]); + }); + + it('CONTROL: a masked highlighted field is neither the amount nor a subtitle part, and its value is never printed', async () => { + const { first } = await lineCards(RELATED, ['access_pin', 'total_price', 'quantity']); + expect(within(first).getByTestId('grid-card-amount').textContent).toBe('CN¥10,800.00'); + expect(labels(first)).toEqual(['Quantity']); + expect(first.textContent).not.toContain('s3cr3t-pin'); + }); +}); diff --git a/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx b/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx index b32b539f018..0ea62cc0ce4 100644 --- a/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx +++ b/ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx @@ -74,6 +74,55 @@ export function useObjectGridGenerateColumns({ /** objectstack#33317 — `false` ⇒ the host's row click opens nothing (`ObjectGrid`'s prop). */ rowOpensRecord?: boolean; }) { + // One object field's column draft, as the SYNTHESIZED path (no authored + // `columns` / `fields`) draws it: the field's own renderer, its translated + // label, and field-level security (`null` for a field the viewer may not + // read, or one the object does not declare). Shared with the phone card, + // which draws the object's `highlightFields` (ADR-0085) whether or not the + // view shows them as columns (objectstack#37891). + const synthesizeFieldColumn = useCallback((fieldName: string): ObjectGridColumnDraft | null => { + if (!objectSchema) return null; + const settledFor = (field: unknown, row: Record | undefined): boolean => + isDeadlineSettled(field as Parameters[0], row, { scope: predicateScope, fields: objectFields }); + const field = objectSchema.fields?.[fieldName]; + if (!field) return null; + + // FLS: drop columns the current user cannot read (server-resolved + // /me/permissions via checkField — the schema itself carries no + // per-caller permission bits, objectstack#3661). Same gate ListView + // applies to its auto-derived columns. + if (perms?.isLoaded && schema.objectName + && !perms.checkField(schema.objectName, fieldName, 'read')) return null; + + // Annotated for the same reason as paths A-C (objectui#6004): `field` is + // `any`, so these values have to be named before they reach a spread + // below — the naming now lives on `GridCellRendering`'s `string | null` + // members. `fieldType` is the DECLARED type the emit forwards to the + // inline editor; the renderer comes from the `format`-promoted key, which + // this path used to skip (objectui#8920). + const { declaredType: fieldType, rendererType, Renderer: CellRenderer } = resolveGridCellRendering(field); + const translatedField = field.options + ? { ...field, options: translateOptions(schema.objectName, fieldName, field.options) } + : field; + const header = schema.objectName ? resolveFieldLabel(schema.objectName, fieldName, field.label || fieldName) : field.label || fieldName; + // The face is handed the header's label, as paths A-C hand it + // (objectui#11689). + const fieldForCell: any = field.label ? { ...translatedField, label: header } : translatedField; + // A `referenceVia` pointer column (objectui#12608), as path A. + const pointerFace = recordPointerFace(fieldName, fieldType, field, dataSource); + return { + header, + accessorKey: fieldName, + // Forward the field type for the type-aware inline editor. + ...(fieldType && { type: fieldType }), + // Aligned on the RENDERER key, like paths A-C: a `text` column with + // `format: 'currency'` renders as currency, so it aligns as currency. + ...(alignsAsNumber(rendererType, field.returnType) && { align: 'right' as const }), + cell: (value: any, row: any) => pointerFace?.(row) ?? , + sortable: field.sortable !== false, + }; + }, [objectSchema, objectFields, resolveFieldLabel, translateOptions, schema.objectName, perms, dataSource, predicateScope]); + const generateColumns = useCallback((): ObjectGridColumnDraft[] => { // objectui#11815 — the host's verdict on a declared deadline's // `settledWhen` for ONE row, handed to the cell as `deadlineSettled`. The @@ -965,47 +1014,12 @@ export function useObjectGridGenerateColumns({ } fieldsToShow.forEach((fieldName) => { - const field = objectSchema.fields?.[fieldName]; - if (!field) return; - - // FLS: drop columns the current user cannot read (server-resolved - // /me/permissions via checkField — the schema itself carries no - // per-caller permission bits, objectstack#3661). Same gate ListView - // applies to its auto-derived columns. - if (perms?.isLoaded && schema.objectName - && !perms.checkField(schema.objectName, fieldName, 'read')) return; - - // Annotated for the same reason as paths A-C (objectui#6004): `field` is - // `any`, so these values have to be named before they reach a spread - // below — the naming now lives on `GridCellRendering`'s `string | null` - // members. `fieldType` is the DECLARED type the emit forwards to the - // inline editor; the renderer comes from the `format`-promoted key, which - // this path used to skip (objectui#8920). - const { declaredType: fieldType, rendererType, Renderer: CellRenderer } = resolveGridCellRendering(field); - const translatedField = field.options - ? { ...field, options: translateOptions(schema.objectName, fieldName, field.options) } - : field; - const header = schema.objectName ? resolveFieldLabel(schema.objectName, fieldName, field.label || fieldName) : field.label || fieldName; - // The face is handed the header's label, as paths A-C hand it - // (objectui#11689). - const fieldForCell: any = field.label ? { ...translatedField, label: header } : translatedField; - // A `referenceVia` pointer column (objectui#12608), as path A. - const pointerFace = recordPointerFace(fieldName, fieldType, field, dataSource); - generatedColumns.push({ - header, - accessorKey: fieldName, - // Forward the field type for the type-aware inline editor. - ...(fieldType && { type: fieldType }), - // Aligned on the RENDERER key, like paths A-C: a `text` column with - // `format: 'currency'` renders as currency, so it aligns as currency. - ...(alignsAsNumber(rendererType, field.returnType) && { align: 'right' as const }), - cell: (value: any, row: any) => pointerFace?.(row) ?? , - sortable: field.sortable !== false, - }); + const column = synthesizeFieldColumn(fieldName); + if (column) generatedColumns.push(column); }); return generatedColumns; - }, [objectSchema, objectFields, objectTypesPending, schemaFields, schemaColumns, dataConfig, hasInlineData, objectName, navigation.handleClick, executeAction, data, resolveFieldLabel, translateOptions, schema.objectName, perms, uiLanguage, dataSource, predicateScope, recordLinkAdornment, rowOpensRecord]); + }, [objectSchema, objectFields, objectTypesPending, schemaFields, schemaColumns, dataConfig, hasInlineData, objectName, navigation.handleClick, executeAction, data, resolveFieldLabel, translateOptions, schema.objectName, perms, uiLanguage, dataSource, predicateScope, recordLinkAdornment, rowOpensRecord, synthesizeFieldColumn]); - return { generateColumns }; + return { generateColumns, synthesizeFieldColumn }; } diff --git a/ui/packages/plugin-grid/src/objectGridRowLoad.ts b/ui/packages/plugin-grid/src/objectGridRowLoad.ts index 210b2ed107d..fb1267c7840 100644 --- a/ui/packages/plugin-grid/src/objectGridRowLoad.ts +++ b/ui/packages/plugin-grid/src/objectGridRowLoad.ts @@ -541,9 +541,23 @@ export function useObjectGridRowLoad({ .filter((f) => isProjectableField(f, declared as Record)) .filter((f) => passesProjectionGate(f)) : []; + // objectstack#37891 — the object's `highlightFields` (ADR-0085). + // A phone draws each row as a card whose amount and subtitle are + // those fields, in that order, whether or not a column shows them, + // so a list showing `unit_price` but not `total_price` still has + // the total to put in the amount slot. Asked whatever the viewport, + // like the name field: a width change must not refetch. Fetched, + // never drawn as columns. The same two gates as the name field. + const declaredHighlights = (resolvedSchema as { highlightFields?: unknown } | undefined)?.highlightFields; + const highlightFields = declared && Array.isArray(declaredHighlights) + ? declaredHighlights + .filter((f): f is string => typeof f === 'string' && f !== '') + .filter((f) => isProjectableField(f, declared as Record)) + .filter((f) => passesProjectionGate(f)) + : []; // A UNION, never an append: a grouping field that IS also a column // must not produce a duplicate `$select` entry. - const extraFields = [...predicateFields, ...groupingFields, ...concurrencyFields, ...rowColorFields, ...deadlineFields, ...lockOperandFields, ...referenceViaFields, ...dependsOnFields, ...nameFields, ...recordCurrencyFields, ...quantityUnitFields]; + const extraFields = [...predicateFields, ...groupingFields, ...concurrencyFields, ...rowColorFields, ...deadlineFields, ...lockOperandFields, ...referenceViaFields, ...dependsOnFields, ...nameFields, ...highlightFields, ...recordCurrencyFields, ...quantityUnitFields]; const withHarvestedFields = (list: any[]): any[] => { if (extraFields.length === 0) return list; const names = new Set(list.map((f: any) => columnIdentity(f))); diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 700c97a247f..8abfaf8d5d6 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -4644,6 +4644,17 @@ export const ListView = React.forwardRef(({ // grid owns. addSpeculative(declaredNameField(objectDef)); + // [objectstack#37891] The object's `highlightFields` (ADR-0085). On + // a phone the grid draws each row this fetch hands it as a card + // whose amount and subtitle are those fields, in that order, whether + // or not a column shows them. Fetched, never drawn as columns; asked + // whatever the viewport, like the name field above. Through + // `addSpeculative`, like every binding here. `ObjectGrid`'s + // `getSelectFields` carries the same arm for the fetch a grouped + // grid owns. + const highlights = (objectDef as { highlightFields?: unknown } | undefined)?.highlightFields; + if (Array.isArray(highlights)) for (const f of highlights) addSpeculative(f); + for (const f of collectPredicateFieldRefs(listViewPredicates({ conditionalFormatting: schema.conditionalFormatting as unknown[] | undefined, /** diff --git a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx index 0b797714097..a6ab7d0642c 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.harness.test.tsx @@ -3109,6 +3109,94 @@ describe('ListView.nameFieldSelect-13116', () => { }); }); +// ── ListView.highlightFieldsSelect-37891 ─────────────────────────────────────── + +/** + * objectstack#37891 — an ungrouped list asks for the object's + * `highlightFields` (ADR-0085). On a phone the grid draws each row this fetch + * hands it as a card whose amount and subtitle are those fields, in that + * order, whether or not a column shows them; without this arm a list showing + * `unit_price` but not `total_price` handed the grid rows with no total to + * put in the amount slot. Fetched, never drawn as columns. A grouped grid + * that owns its fetch projects through `ObjectGrid`'s `getSelectFields`, + * pinned in plugin-grid's `phoneCardAmount-34615.test.tsx`. + * + * Directions on the base tree, measured by reverting the fix: + * a highlighted field no column shows is in `$select`, not drawn RED + * control: an object with no highlightFields sends the same select GREEN + */ +describe('ListView.highlightFieldsSelect-37891', () => { + restoreAfterBlock(); + + const LINE = 'crm_sales_order_line'; + const lineFields = { + id: { name: 'id', type: 'text' }, + product_title: { name: 'product_title', type: 'text', label: 'Product Title' }, + quantity: { name: 'quantity', type: 'number', label: 'Quantity' }, + unit_price: { name: 'unit_price', type: 'currency', label: 'Sales Price' }, + discount: { name: 'discount', type: 'percent', label: 'Discount %' }, + total_price: { name: 'total_price', type: 'formula', returnType: 'currency', label: 'Total', expression: 'record.quantity * record.unit_price' }, + }; + const ROWS = [{ id: 'l1', product_title: 'Workshop', quantity: 2, unit_price: 6000, discount: 10, total_price: 10800 }]; + + let lastGridProps: any = null; + let prevObjectGrid: any; + beforeAll(() => { + prevObjectGrid = ComponentRegistry.get('object-grid'); + ComponentRegistry.register('object-grid', (props: any) => { + lastGridProps = props; + return
; + }); + }); + afterAll(() => { + if (prevObjectGrid) ComponentRegistry.register('object-grid', prevObjectGrid); + else ComponentRegistry.unregister('object-grid'); + }); + beforeEach(() => { + vi.clearAllMocks(); + lastGridProps = null; + }); + afterEach(() => { + cleanup(); + lastGridProps = null; + }); + + async function mount(def: Record, columns: string[]) { + const dataSource = { + find: vi.fn(async () => ({ data: ROWS, total: ROWS.length })), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async (name: string) => (name === def.name ? def : null)), + } as any; + render( + + + , + ); + await waitFor(() => expect(dataSource.find).toHaveBeenCalled()); + return [...((dataSource.find.mock.calls.at(-1)?.[1]?.$select as string[] | undefined) ?? [])].sort(); + } + + it('asks for a highlighted field no column shows, and does not draw it as a column', async () => { + const def = { name: LINE, nameField: 'product_title', highlightFields: ['total_price', 'quantity', 'unit_price', 'discount'], fields: lineFields }; + const select = await mount(def, ['product_title', 'quantity', 'unit_price']); + expect(select).toEqual(['discount', 'id', 'product_title', 'quantity', 'total_price', 'unit_price']); + const drawn = (lastGridProps?.columns ?? lastGridProps?.fields ?? []) as unknown[]; + expect(JSON.stringify(drawn)).not.toContain('total_price'); + }); + + it('control: an object with no highlightFields sends the same $select as before', async () => { + const def = { name: LINE, nameField: 'product_title', fields: lineFields }; + const select = await mount(def, ['product_title', 'quantity', 'unit_price']); + expect(select).toEqual(['id', 'product_title', 'quantity', 'unit_price']); + }); +}); + // ── ListView.recordDrawerCount-27545 ──────────────────────────────────────────── /**