Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .changeset/37891-phone-card-highlight-fields.md
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions ui/packages/plugin-detail/src/RelatedList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2014,6 +2014,21 @@ export const RelatedList: React.FC<RelatedListProps> = ({
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]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof makeDataSource>): 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']);
});
});
69 changes: 61 additions & 8 deletions ui/packages/plugin-grid/src/ObjectGrid.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2112,7 +2112,7 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
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,
Expand Down Expand Up @@ -4414,8 +4414,37 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
// 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
Expand Down Expand Up @@ -4450,12 +4479,31 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
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];
Expand Down Expand Up @@ -4619,7 +4667,12 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
{subtitle.map((col, i) => (
<React.Fragment key={col.accessorKey}>
{i > 0 && <span className="shrink-0 whitespace-pre"> · </span>}
<span data-testid="grid-card-subtitle-part" className="min-w-0 truncate">{cardCell(col, row)}</span>
<span data-testid="grid-card-subtitle-part" className="min-w-0 truncate">
{subtitlePartLabel(col) !== undefined && (
<span data-testid="grid-card-subtitle-label">{subtitlePartLabel(col)} </span>
)}
{cardCell(col, row)}
</span>
</React.Fragment>
))}
</div>
Expand Down
138 changes: 138 additions & 0 deletions ui/packages/plugin-grid/src/__tests__/phoneCardAmount-34615.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(
<LocalizationProvider value={{ currency: 'CNY', locale: 'en' }}>
<ActionProvider>
<SchemaRendererProvider dataSource={dataSource}>
<ObjectGrid
schema={{ type: 'object-grid', objectName: LINE_OBJECT, columns: columns.map((field) => ({ field })), pagination: { pageSize: 50 } } as never}
dataSource={dataSource}
/>
</SchemaRendererProvider>
</ActionProvider>
</LocalizationProvider>,
);
// 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');
});
});
Loading
Loading