From 8e7395a5010e74448e9db5d0f73d42873b9d4471 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 17:04:55 +0000 Subject: [PATCH 1/7] wip(plugin-grid): resident footer row with a per-column calculation picker Claude-Session: https://claude.ai/code/session_01L6bhgVb7fsaFeMStucvNWA Co-authored-by: Claude --- ui/packages/i18n/src/locales/ar.ts | 7 ++ ui/packages/i18n/src/locales/de.ts | 7 ++ ui/packages/i18n/src/locales/en.ts | 7 ++ ui/packages/i18n/src/locales/es.ts | 7 ++ ui/packages/i18n/src/locales/fr.ts | 7 ++ ui/packages/i18n/src/locales/ja.ts | 7 ++ ui/packages/i18n/src/locales/ko.ts | 7 ++ ui/packages/i18n/src/locales/pt-BR.ts | 7 ++ ui/packages/i18n/src/locales/ru.ts | 7 ++ ui/packages/i18n/src/locales/zh-Hans.ts | 7 ++ ui/packages/i18n/src/locales/zh-Hant.ts | 7 ++ ui/packages/plugin-grid/src/ObjectGrid.tsx | 74 +++++++++++++- .../plugin-grid/src/objectGridSummaries.ts | 56 +++++++++-- .../src/objectGridSummaryPicker.tsx | 99 +++++++++++++++++++ .../plugin-grid/src/useColumnSummary.ts | 86 +++++++++++++--- 15 files changed, 369 insertions(+), 23 deletions(-) create mode 100644 ui/packages/plugin-grid/src/objectGridSummaryPicker.tsx diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 14b652d847d..37071b6325e 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -684,6 +684,13 @@ const ar = { avg: "المتوسط", min: "الأدنى", max: "الأعلى", + earliest: "الأقدم", + latest: "الأحدث", + pageName: "{{label}} (هذه الصفحة)", + calculate: "حساب", + none: "لا شيء", + menuPercentEmpty: "نسبة الفارغ", + menuPercentFilled: "نسبة المعبأ", }, toolbar: { densityMode: "الكثافة", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 58e70f7edbe..97ad5735281 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -630,6 +630,13 @@ const de = { avg: "Mittelwert", min: "Min.", max: "Max.", + earliest: "Frühestes", + latest: "Spätestes", + pageName: "{{label}} (diese Seite)", + calculate: "Berechnen", + none: "Keine", + menuPercentEmpty: "Anteil leer", + menuPercentFilled: "Anteil gefüllt", }, toolbar: { densityMode: "Dichte", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index dff9e7910d5..51b93667fca 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -876,6 +876,13 @@ const en = { avg: 'Avg', min: 'Min', max: 'Max', + earliest: 'Earliest', + latest: 'Latest', + pageName: '{{label}} (this page)', + calculate: 'Calculate', + none: 'None', + menuPercentEmpty: 'Percent empty', + menuPercentFilled: 'Percent filled', }, toolbar: { densityMode: 'Density', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index e0c7e224bfd..bb1d1773134 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -647,6 +647,13 @@ const es = { avg: "Promedio", min: "Mín.", max: "Máx.", + earliest: "Más antigua", + latest: "Más reciente", + pageName: "{{label}} (esta página)", + calculate: "Calcular", + none: "Ninguno", + menuPercentEmpty: "Porcentaje vacío", + menuPercentFilled: "Porcentaje con valor", }, toolbar: { densityMode: "Densidad", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 82acd914de1..d86ff421e71 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -642,6 +642,13 @@ const fr = { avg: "Moyenne", min: "Min", max: "Max", + earliest: "Plus ancienne", + latest: "Plus récente", + pageName: "{{label}} (cette page)", + calculate: "Calculer", + none: "Aucun", + menuPercentEmpty: "Pourcentage vide", + menuPercentFilled: "Pourcentage rempli", }, toolbar: { densityMode: "Densité", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 6991ebb6490..02de93b6bc4 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -630,6 +630,13 @@ const ja = { avg: "平均", min: "最小", max: "最大", + earliest: "最も早い", + latest: "最も遅い", + pageName: "{{label}}(このページ)", + calculate: "計算", + none: "なし", + menuPercentEmpty: "空の割合", + menuPercentFilled: "入力済みの割合", }, toolbar: { densityMode: "密度", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 13f7a980535..a342d6b47ce 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -630,6 +630,13 @@ const ko = { avg: "평균", min: "최소", max: "최대", + earliest: "가장 이른", + latest: "가장 늦은", + pageName: "{{label}} (이 페이지)", + calculate: "계산", + none: "없음", + menuPercentEmpty: "빈 값 비율", + menuPercentFilled: "입력된 값 비율", }, toolbar: { densityMode: "밀도", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 171f9615455..f4caf67f328 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -642,6 +642,13 @@ const pt = { avg: "Média", min: "Mín.", max: "Máx.", + earliest: "Mais antiga", + latest: "Mais recente", + pageName: "{{label}} (esta página)", + calculate: "Calcular", + none: "Nenhum", + menuPercentEmpty: "Percentual vazio", + menuPercentFilled: "Percentual preenchido", }, toolbar: { densityMode: "Densidade", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0629e208996..ebe168321f9 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -657,6 +657,13 @@ const ru = { avg: "Среднее", min: "Мин.", max: "Макс.", + earliest: "Самая ранняя", + latest: "Самая поздняя", + pageName: "{{label}} (эта страница)", + calculate: "Вычислить", + none: "Нет", + menuPercentEmpty: "Доля пустых", + menuPercentFilled: "Доля заполненных", }, toolbar: { densityMode: "Плотность", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 3812641e6a2..2764930fd42 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -610,6 +610,13 @@ const zh = { avg: '平均值', min: '最小值', max: '最大值', + earliest: '最早', + latest: '最晚', + pageName: '{{label}}(本页)', + calculate: '计算', + none: '无', + menuPercentEmpty: '空值占比', + menuPercentFilled: '非空占比', }, toolbar: { densityMode: '密度', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 3ff3be4e69d..c5bc24cd3fe 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -610,6 +610,13 @@ const zhHant = { avg: '平均值', min: '最小值', max: '最大值', + earliest: '最早', + latest: '最晚', + pageName: '{{label}}(本頁)', + calculate: '計算', + none: '無', + menuPercentEmpty: '空值佔比', + menuPercentFilled: '非空佔比', }, toolbar: { densityMode: '密度', diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 15b1a552dc1..1880908f434 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -102,7 +102,11 @@ import { useObjectGridGroupingDecisions } from './objectGridGroupingDecisions'; import { useObjectGridRowLoad } from './objectGridRowLoad'; import { useObjectGridGrouping } from './objectGridGrouping'; import { temporalCellText } from './temporalCellFace'; -import { useObjectGridSummaries } from './objectGridSummaries'; +import { useObjectGridSummaries, declaredColumnSummaryKey } from './objectGridSummaries'; +import { SummaryCellPicker } from './objectGridSummaryPicker'; +import { + offeredColumnSummaries, isTemporalSummaryField, useSummaryTranslation, type ColumnSummaryType, +} from './useColumnSummary'; import { useObjectGridRowHeightSync } from './objectGridRowHeight'; import { useObjectGridColumnState } from './objectGridColumnState'; import { useObjectGridMobile } from './objectGridMobile'; @@ -241,6 +245,22 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * of identity. A RUNTIME prop, never authored metadata. */ onColumnSummaryChange?: (summaries: readonly ObjectGridFooterSummary[] | null) => void; + /** + * [objectstack#35702] Draw the footer row on a flat table even when no + * column declares a calculation: the record count in its first cell, each + * column's calculation, if any, under it. A HOST prop (the list page), never + * authored metadata. + */ + residentSummaryRow?: boolean; + /** + * [objectstack#35702] Wired only for a reader who may change the view: each + * footer cell becomes the menu that picks the column's calculation (`null` = + * None). The grid draws the pick at once; the host saves it on the view and + * hands it back as the column's `summary`. + */ + onColumnSummaryPick?: (field: string, summary: ColumnSummaryType | null) => void; + /** [objectstack#35702] Whether the resident footer row is drawn (it carries the record count). */ + onResidentSummaryRowChange?: (drawn: boolean) => void; /** * [objectstack#28461] The rows a GROUPED grid shows, group by group: every * open leaf group on the current page of groups, in display order, with its @@ -746,6 +766,9 @@ export const ObjectGrid: React.FC = ({ objectFields: hostObjectFields, showRowNumbers: hostShowRowNumbers, onColumnSummaryChange, + residentSummaryRow, + onColumnSummaryPick, + onResidentSummaryRowChange, onRowGroupsChange, }) => { const [data, setData] = useState([]); @@ -1535,13 +1558,36 @@ export const ObjectGrid: React.FC = ({ // The fan-out query, the resolved match total and the column summaries, in // hook order (`./objectGridSummaries`). + // objectstack#35702 — the reader's footer picks, each held until the view + // the host hands back declares it. + const [summaryPicks, setSummaryPicks] = useState>>({}); const { - bulkFanoutParams, resolvedTotalMatching, summaries, hasSummary, + bulkFanoutParams, resolvedTotalMatching, summaries, hasSummary, summaryTypes, } = useObjectGridSummaries({ schema, dataSource, objectName, objectSchema, objectFields, objectTypesPending, data, hasInlineData, externalManualPagination, hostFindParams, hostRowCount, lastFindParamsRef, totalMatching, refreshKey, serverPage, - fetchWindow, serverGroupedFetch, isGrouped, + fetchWindow, serverGroupedFetch, isGrouped, summaryPicks, }); + const declaredSummaryKey = declaredColumnSummaryKey(schema.columns); + useEffect(() => { + setSummaryPicks((picks) => { + const declared = new Map(declaredSummaryKey.split('|').filter(Boolean).map((e) => e.split('=') as [string, string])); + const kept = Object.entries(picks).filter(([field, pick]) => (declared.get(field) ?? null) !== pick); + return kept.length === Object.keys(picks).length ? picks : Object.fromEntries(kept); + }); + // Keyed on the declared calculations' content, never the columns' identity. + }, [declaredSummaryKey]); + const pickColumnSummary = useCallback((field: string, summary: ColumnSummaryType | null) => { + setSummaryPicks((picks) => ({ ...picks, [field]: summary })); + onColumnSummaryPick?.(field, summary); + }, [onColumnSummaryPick]); + const { t: summaryT } = useSummaryTranslation(); + // A host's resident row is drawn with no calculation too, and under a + // reader who may change the view each cell is its picker. + const residentRowDrawn = !!residentSummaryRow && !onColumnSummaryChange && !isGrouped && !useCardView; + useEffect(() => { + onResidentSummaryRowChange?.(residentRowDrawn); + }, [onResidentSummaryRowChange, residentRowDrawn]); // objectstack#35554 — tell the page bar whether a selection is open and how // many rows the list's query matches (the count beside the view name). @@ -2963,12 +3009,30 @@ export const ObjectGrid: React.FC = ({ // objectstack#35548 — the column summaries as the table's own last row, each // under its column, led by the count of the records they summarise. A host // that draws them itself (`onColumnSummaryChange`) gets no row here. - const summaryRow: ObjectGridDataTableSchema['summaryRow'] = hasSummary && !onColumnSummaryChange + const summaryRow: ObjectGridDataTableSchema['summaryRow'] = (hasSummary || residentRowDrawn) && !onColumnSummaryChange ? { lead: t('grid.summary.countLead', { value: (typeof resolvedTotalMatching === 'number' ? resolvedTotalMatching : data.length).toLocaleString(displayLocale), }), - cells: Object.fromEntries(Array.from(summaries, ([key, summary]) => [key, summary.label])), + cells: residentRowDrawn + ? Object.fromEntries(tableColumns.flatMap((col: { accessorKey: string }) => { + const field = col.accessorKey; + const def = objectFields?.[field] as Parameters[0]; + const summary = summaries.get(field); + if (!def && !summary) return []; + return [[field, ( + + )]]; + })) + : Object.fromEntries(Array.from(summaries, ([key, summary]) => [key, summary.label])), } : undefined; // objectstack#35685 — a row a select-first save redrew, in place of the row diff --git a/ui/packages/plugin-grid/src/objectGridSummaries.ts b/ui/packages/plugin-grid/src/objectGridSummaries.ts index 45a606bf1b2..8094a02cb23 100644 --- a/ui/packages/plugin-grid/src/objectGridSummaries.ts +++ b/ui/packages/plugin-grid/src/objectGridSummaries.ts @@ -8,7 +8,7 @@ import React from 'react'; import type { ObjectGridSchema, DataSource, ListColumn } from '@object-ui/types'; -import { useScopedColumnSummary } from './useColumnSummary'; +import { useScopedColumnSummary, type ColumnSummaryType } from './useColumnSummary'; import { useWholeSetSummary, type WholeSetSummaryFields } from './useWholeSetSummary'; import { normalizeColumns } from './objectGridColumns'; import type { ObjectGridExternalPaginationProps } from './objectGridProps'; @@ -24,7 +24,7 @@ type Grouping = ReturnType; export function useObjectGridSummaries({ schema, dataSource, objectName, objectSchema, objectFields, objectTypesPending, data, hasInlineData, externalManualPagination, hostFindParams, hostRowCount, lastFindParamsRef, totalMatching, refreshKey, serverPage, - fetchWindow, serverGroupedFetch, isGrouped, + fetchWindow, serverGroupedFetch, isGrouped, summaryPicks, }: { schema: ObjectGridSchema; dataSource: DataSource | undefined; @@ -45,6 +45,12 @@ export function useObjectGridSummaries({ fetchWindow: GroupingDecisions['fetchWindow']; serverGroupedFetch: GroupingDecisions['serverGroupedFetch']; isGrouped: Grouping['isGrouped']; + /** + * objectstack#35702 — calculations the reader picked in the footer, by + * field, drawn at once over the view's own until the host's save comes back + * as the view (`null` = None). + */ + summaryPicks?: Readonly>; }) { // The query the cross-page fan-out would replay — from whichever side owns the // fetch (objectui#4501). ONE value, read by the fan-out AND by the affordance @@ -94,11 +100,27 @@ export function useObjectGridSummaries({ // --- Column summary support --- const summaryColumns = React.useMemo(() => { const cols = normalizeColumns(schema.columns); - if (cols && cols.length > 0 && typeof cols[0] === 'object') { - return cols as ListColumn[]; + const declared = cols && cols.length > 0 && typeof cols[0] === 'object' ? cols as ListColumn[] : undefined; + const picked = summaryPicks ? Object.keys(summaryPicks) : []; + if (picked.length === 0) return declared; + const pickedOf = (c: ListColumn): ListColumn => (c.field in summaryPicks! + ? { ...c, summary: summaryPicks![c.field] ?? undefined } + : c); + const merged = (declared ?? []).map(pickedOf); + for (const field of picked) { + if (!merged.some((c) => c.field === field)) merged.push({ field, summary: summaryPicks![field] ?? undefined } as ListColumn); } - return undefined; - }, [schema.columns]); + return merged; + }, [schema.columns, summaryPicks]); + // The calculation in force per field, for the footer's menu tick. + const summaryTypes = React.useMemo(() => { + const types = new Map(); + for (const c of summaryColumns ?? []) { + if (!c.summary) continue; + types.set(c.field, (typeof c.summary === 'string' ? c.summary : c.summary.type) as ColumnSummaryType); + } + return types; + }, [summaryColumns]); // [objectui#12081 item 3] Whether the rows the footer reads ARE the set it // is drawn beside. Under server paging they are one page of it: a host // (`ListView`) hands this grid one window with the set's `rowCount`, or this @@ -134,6 +156,26 @@ export function useObjectGridSummaries({ ); return { - bulkFanoutParams, resolvedTotalMatching, summaries, hasSummary, + bulkFanoutParams, resolvedTotalMatching, summaries, hasSummary, summaryTypes, }; } + +/** + * objectstack#35702 — the calculation each column of `columns` declares, by + * field (the string shorthand and the object form alike; `none` included). + */ +export function declaredColumnSummaries(columns: ObjectGridSchema['columns']): Map { + const declared = new Map(); + const cols = normalizeColumns(columns); + if (!cols || typeof cols[0] !== 'object') return declared; + for (const c of cols as ListColumn[]) { + if (!c.summary) continue; + declared.set(c.field, (typeof c.summary === 'string' ? c.summary : c.summary.type) as ColumnSummaryType); + } + return declared; +} + +/** The declared calculations as one string, for keying an effect on their content. */ +export function declaredColumnSummaryKey(columns: ObjectGridSchema['columns']): string { + return Array.from(declaredColumnSummaries(columns), ([field, type]) => `${field}=${type}`).join('|'); +} diff --git a/ui/packages/plugin-grid/src/objectGridSummaryPicker.tsx b/ui/packages/plugin-grid/src/objectGridSummaryPicker.tsx new file mode 100644 index 00000000000..2c109d8b6cd --- /dev/null +++ b/ui/packages/plugin-grid/src/objectGridSummaryPicker.tsx @@ -0,0 +1,99 @@ +/** + * One cell of the list's resident footer row (objectstack#35702): the + * column's calculation, drawn as its name in the secondary text colour and its + * figure in the normal one (「Sum ¥1,234,500」). For a reader who may change + * the view it is also the control: a click opens one menu of the calculations + * the column's field type allows, the current one ticked and 「None」 last; an + * empty cell shows 「Calculate」 on hover. Without `onPick` it only draws. + */ + +import React from 'react'; +import { + cn, + DropdownMenu, + DropdownMenuContent, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@object-ui/components'; +import { Check } from 'lucide-react'; +import type { ColumnSummaryType, SummaryTranslate } from './useColumnSummary'; +import { summaryMenuLabel } from './useColumnSummary'; + +export interface SummaryCellFigure { + name: string; + text: string; + label: string; +} + +export interface SummaryCellPickerProps { + field: string; + /** The figure drawn, when the column has one. */ + figure?: SummaryCellFigure; + /** The column's calculation in force (`'none'` / absent ⇒ none). */ + current?: ColumnSummaryType; + /** The calculations the menu lists, in order. */ + offered: ReadonlyArray; + /** The column's field is a date or time (its min / max read Earliest / Latest). */ + temporal: boolean; + /** Wired only for a reader who may change the view. `null` = None. */ + onPick?: (field: string, summary: ColumnSummaryType | null) => void; + t: SummaryTranslate; +} + +function Figure({ figure }: { figure: SummaryCellFigure }) { + return ( + + {figure.name}{' '} + {figure.text} + + ); +} + +export function SummaryCellPicker({ field, figure, current, offered, temporal, onPick, t }: SummaryCellPickerProps) { + if (!onPick) return figure ?
: null; + const active = current && current !== 'none' ? current : undefined; + return ( + + + + + + {offered.map((summary) => ( + onPick(field, summary)} + > + + {summaryMenuLabel(summary, temporal, t)} + + ))} + + onPick(field, null)}> + + {t('grid.summary.none')} + + + + ); +} diff --git a/ui/packages/plugin-grid/src/useColumnSummary.ts b/ui/packages/plugin-grid/src/useColumnSummary.ts index 33553f2c370..b0b062dccca 100644 --- a/ui/packages/plugin-grid/src/useColumnSummary.ts +++ b/ui/packages/plugin-grid/src/useColumnSummary.ts @@ -11,7 +11,7 @@ import type { ListColumn } from '@object-ui/types'; import type { ColumnSummary, ListViewGroupHeaderRow } from '@objectstack/spec/ui'; import { deriveColumnSummary } from '@objectstack/spec/ui'; import type { CurrencyConfig } from '@objectstack/spec/data'; -import { resolveFieldScale } from '@objectstack/spec/data'; +import { resolveFieldScale, isAggregateCompatibleWithFieldType } from '@objectstack/spec/data'; import { useLocalization, useDisplayLocale, resolveFieldCurrency, recordCurrencyField, createSafeTranslation } from '@object-ui/i18n'; import { formatCurrency, formatPercent, percentCellScale, summaryDeclaresCurrency } from '@object-ui/fields'; import { temporalCellFaceOf, temporalCellText, temporalExtreme, temporalInstant } from './temporalCellFace'; @@ -56,6 +56,13 @@ export interface ColumnSummaryResult { */ value: number | null; label: string; + /** + * The two halves of `label`, for a footer that draws them apart: `name` is + * the calculation's word with its scope (「合计」, 「合计(本页)」), `text` + * the formatted figure (「¥1,234,500」). + */ + name: string; + text: string; } /** A data row as the aggregations read it — cells are untyped until inspected. */ @@ -131,15 +138,59 @@ const SUMMARY_DEFAULT_TRANSLATIONS: Record = { 'grid.summary.avg': 'Avg', 'grid.summary.min': 'Min', 'grid.summary.max': 'Max', + 'grid.summary.earliest': 'Earliest', + 'grid.summary.latest': 'Latest', + 'grid.summary.pageName': '{{label}} (this page)', + 'grid.summary.calculate': 'Calculate', + 'grid.summary.none': 'None', + 'grid.summary.menuPercentEmpty': 'Percent empty', + 'grid.summary.menuPercentFilled': 'Percent filled', }; -const useSummaryTranslation = createSafeTranslation( +export const useSummaryTranslation = createSafeTranslation( SUMMARY_DEFAULT_TRANSLATIONS, 'grid.summary.sum', ); +/** + * The calculations the footer's menu offers for a field type, in menu order. + * Each one the footer can draw for that type: an aggregate the spec allows on + * the type (`isAggregateCompatibleWithFieldType`), and the count family on + * any. ⛔ No `count`: the row's first cell already carries the record count. + * Booleans get the count family only, and a record-currency amount (whose sum + * the footer withholds) likewise. + */ +const MENU_AGGREGATES: ReadonlyArray = ['sum', 'avg', 'min', 'max']; +const MENU_COUNTS: ReadonlyArray = [ + 'count_unique', 'count_filled', 'count_empty', 'percent_filled', 'percent_empty', +]; +export function offeredColumnSummaries( + field: ({ type?: string } & NonNullable[0]>) | undefined, +): ColumnSummaryType[] { + const type = field?.type; + const numeric = !!type && type !== 'boolean' && !recordCurrencyField(field); + return [ + ...(numeric ? MENU_AGGREGATES.filter((m) => isAggregateCompatibleWithFieldType(m, type!)) : []), + ...MENU_COUNTS.filter((m) => m !== 'count_unique' || (!!type && isAggregateCompatibleWithFieldType('count_distinct', type))), + ]; +} + +/** Is `field` drawn as a date or time, so its `min` / `max` read 「Earliest」 / 「Latest」? */ +export function isTemporalSummaryField(field: { type?: string; format?: string | null; widget?: string | null } | undefined): boolean { + return !!temporalCellFaceOf({ type: field?.type, format: field?.format, widget: field?.widget }); +} + +/** A calculation's name in the footer's menu. */ +export function summaryMenuLabel(type: ColumnSummaryType, temporal: boolean, t: SummaryTranslate): string { + if (temporal && type === 'min') return t('grid.summary.earliest'); + if (temporal && type === 'max') return t('grid.summary.latest'); + if (type === 'percent_empty') return t('grid.summary.menuPercentEmpty'); + if (type === 'percent_filled') return t('grid.summary.menuPercentFilled'); + return type === 'none' ? t('grid.summary.none') : t(TYPE_LABEL_KEYS[type]); +} + /** The translator shape `formatSummaryLabel` needs — i18next's `t`, narrowed. */ -type SummaryTranslate = (key: string, options?: Record) => string; +export type SummaryTranslate = (key: string, options?: Record) => string; /** * Every aggregation name the renderer computes. A Set rather than an `in` check @@ -351,15 +402,28 @@ const WELL_FORMED_CURRENCY_CODE = /^[A-Za-z]{3}$/; * ordinary German number — for a value three orders of magnitude away — and * the arms below include a currency total. */ -function joinSummaryLabel(type: string, formatted: string, t: SummaryTranslate, pageOnly: boolean): string { - const labelKey = TYPE_LABEL_KEYS[type as ColumnSummaryType]; +/** + * The footer's label and its two halves. A `min` / `max` over a date reads + * 「Earliest」 / 「Latest」 (`temporal`); the scope rides on the word, so the + * figure stays the figure. + */ +function summaryLabelParts( + type: string, formatted: string, t: SummaryTranslate, pageOnly: boolean, temporal = false, +): { label: string; name: string; text: string } { + const labelKey = temporal && (type === 'min' || type === 'max') + ? (type === 'min' ? 'grid.summary.earliest' : 'grid.summary.latest') + : TYPE_LABEL_KEYS[type as ColumnSummaryType]; // `|| type` is the backstop for an aggregation with no key — it echoes the // raw kind, as before, never a half-resolved `grid.summary.`. const label = labelKey ? t(labelKey) : type; // The page scope is its own whole pattern, not a suffix glued onto the // label: where the scope sits, and its brackets, are the translator's, as // the separator is (objectui#4024). - return t(pageOnly ? 'grid.summary.pagePattern' : 'grid.summary.pattern', { label, value: formatted }); + return { + label: t(pageOnly ? 'grid.summary.pagePattern' : 'grid.summary.pattern', { label, value: formatted }), + name: pageOnly ? t('grid.summary.pageName', { label }) : label, + text: formatted, + }; } /** @@ -428,9 +492,9 @@ function formatSummaryLabel( // Required for the reason the two above are: a dropped argument must not // type-check into a label that reads as the whole set's total. pageOnly: boolean, -): string { - if (value === null) return ''; - const join = (formatted: string): string => joinSummaryLabel(type, formatted, t, pageOnly); +): { label: string; name: string; text: string } { + if (value === null) return { label: '', name: '', text: '' }; + const join = (formatted: string) => summaryLabelParts(type, formatted, t, pageOnly); if (PERCENT_TYPES.has(type)) { return join(`${value.toLocaleString(displayLocale, { maximumFractionDigits: 1 })}%`); @@ -711,7 +775,7 @@ export function useScopedColumnSummary( summaries.set(col.field, { field: col.field, value: temporalInstant(raw) ?? null, - label: joinSummaryLabel(config.type, text, t, scope === 'page' || (scope === 'whole' && !fromWhole)), + ...summaryLabelParts(config.type, text, t, scope === 'page' || (scope === 'whole' && !fromWhole), true), }); continue; } @@ -777,7 +841,7 @@ export function useScopedColumnSummary( summaries.set(col.field, { field: col.field, value: result, - label: formatSummaryLabel( + ...formatSummaryLabel( config.type, result, t, From cb396325f8157e6939fd12ba37a513745ffcf4fb Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 17:14:50 +0000 Subject: [PATCH 2/7] wip(ui): save the footer calculation on the open view Claude-Session: https://claude.ai/code/session_01L6bhgVb7fsaFeMStucvNWA Co-authored-by: Claude --- .../app-shell/src/views/ObjectView.tsx | 27 ++++++++++++++ .../app-shell/src/views/columnSummaryWrite.ts | 37 +++++++++++++++++++ .../src/views/objectViewListRenderer.tsx | 9 ++++- ui/packages/plugin-grid/src/ObjectGrid.tsx | 11 ++++-- ui/packages/plugin-list/src/ListView.tsx | 33 +++++++++++++++-- 5 files changed, 109 insertions(+), 8 deletions(-) create mode 100644 ui/packages/app-shell/src/views/columnSummaryWrite.ts diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 4c24e16db0a..af683d63e0b 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -9,6 +9,9 @@ * - ListView delegation for non-grid view types (kanban, calendar, chart, etc.) */ +import type { ColumnSummary } from '@objectstack/spec/ui'; +import type { ListColumn } from '@object-ui/types'; +import { columnsWithSummary } from './columnSummaryWrite'; import { useMemo, useState, useCallback, useEffect, useRef, lazy, Suspense } from 'react'; import { useParams, useSearchParams, useNavigate, useLocation, useHref, createSearchParams } from 'react-router-dom'; import { resolveAffordance, type FilterTokenScope, type SchemaLike } from '@object-ui/core'; @@ -821,6 +824,21 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co activeViewId, baseView, }); + const handlePickPersonalViewSummary = (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => { + if (!activeView) return; + const row = personalViews.views.find((v) => v.id === activeView.id); + if (!row) return; + const columns = columnsWithSummary(row.config.columns as ListColumn[] | string[] | undefined, field, summary, drawnFields); + personalViews.update(row.id, { ...row.config, columns }).catch((err) => { + console.error('[ObjectView] Failed to save a footer calculation:', err); + toast.error(t('form.saveError'), { description: err instanceof Error ? err.message : String(err) }); + }); + }; + const handlePickSharedViewSummary = (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => { + if (!activeView) return; + const columns = columnsWithSummary(activeView.columns as ListColumn[] | string[] | undefined, field, summary, drawnFields); + void handleViewConfigSave({ ...activeView, columns }); + }; // objectstack#29635 — creating one of the reader's own views, and Rename // and Delete on them. Creating is offered to any reader the server lets @@ -1094,6 +1112,15 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co : undefined, save: !isEnvironmentList && canUpdatePersonalView && listPersonalizedParts.length > 0 ? () => { void handleSaveToPersonalView(); } : undefined, reset: !isEnvironmentList && listPersonalizedParts.length > 0 ? handleResetView : undefined, + // objectstack#35702 — the footer's calculation, saved on the open + // view (ruling 7045525672): a personal view at once; a shared one, + // by a reader who may edit it, as a draft through the view panel's + // save, which others see once published. + pickSummary: isEnvironmentList || !activeView + ? undefined + : activeIsPersonal + ? (canUpdatePersonalView ? handlePickPersonalViewSummary : undefined) + : isAdmin ? handlePickSharedViewSummary : undefined, }, }); diff --git a/ui/packages/app-shell/src/views/columnSummaryWrite.ts b/ui/packages/app-shell/src/views/columnSummaryWrite.ts new file mode 100644 index 00000000000..77913985475 --- /dev/null +++ b/ui/packages/app-shell/src/views/columnSummaryWrite.ts @@ -0,0 +1,37 @@ +/** + * objectstack#35702 — a view's `columns` with one column's footer calculation + * set (`null` = None), as the list's footer menu saves it on the view. The + * view's own columns are the base; a view that declares none takes the columns + * the grid draws, so the saved view keeps drawing them. A field the view does + * not list (a column the reader added) is appended. Every entry comes back in + * the object form, the one that carries `summary`. + */ + +import type { ListColumn } from '@object-ui/types'; +import type { ColumnSummary } from '@objectstack/spec/ui'; + +export function columnsWithSummary( + authored: ReadonlyArray | undefined, + field: string, + summary: ColumnSummary | null, + drawnFields: readonly string[], +): ListColumn[] { + const base: ReadonlyArray = authored && authored.length > 0 ? authored : drawnFields; + let found = false; + const columns = base.map((entry): ListColumn => { + const column: ListColumn = typeof entry === 'string' ? { field: entry } : { ...entry }; + if (column.field !== field) return column; + found = true; + if (summary === null) { + delete column.summary; + return column; + } + // The object form keeps its `field` override; only the calculation moves. + column.summary = typeof column.summary === 'object' && column.summary !== null + ? { ...column.summary, type: summary } + : summary; + return column; + }); + if (!found && summary !== null) columns.push({ field, summary }); + return columns; +} diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index 47ab0125be3..d6dbd1bed37 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -8,6 +8,7 @@ * passed in; the component reads the returned callback. */ +import type { ColumnSummary } from '@objectstack/spec/ui'; import { useCallback, useLayoutEffect, useRef, useState, useSyncExternalStore, lazy, Suspense, type ReactNode } from 'react'; import { DENSITY_MODE_TO_ROW_HEIGHT, columnIdentity, normalizeListViewSchema, servedPackageId, type FilterTokenScope } from '@object-ui/core'; import { buildListFilterKey, writeListFilterState } from './listFilterStorage.js'; @@ -169,6 +170,8 @@ export function useObjectViewListRenderer({ rename?: (label: string) => boolean | Promise; save?: () => void; reset?: () => void; + /** objectstack#35702 — save a footer calculation on the open view (wired only for a reader who may change it). */ + pickSummary?: (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => void; }; }) { // objectstack#35551 — the host hands fresh closures every render; the list @@ -178,6 +181,7 @@ export function useObjectViewListRenderer({ const offersRename = !!listViewActions?.rename; const offersSave = !!listViewActions?.save; const offersReset = !!listViewActions?.reset; + const offersSummaryPick = !!listViewActions?.pickSummary; // objectstack#27058 — below `sm` the title switcher is the phone's one // view control, so the list offers no layout switcher of its own there. const wideViewport = useViewTabsFit(); @@ -1043,6 +1047,9 @@ export function useObjectViewListRenderer({ onRenameView={offersRename ? (label: string) => listViewActionsRef.current?.rename?.(label) ?? false : undefined} onSaveView={offersSave ? () => listViewActionsRef.current?.save?.() : undefined} onResetView={offersReset ? () => listViewActionsRef.current?.reset?.() : undefined} + onColumnSummaryPick={offersSummaryPick + ? (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => listViewActionsRef.current?.pickSummary?.(field, summary, drawnFields) + : undefined} className={className} onEdit={editHandler} // objectui#13089 — the view's Add button is the header New: @@ -1143,7 +1150,7 @@ export function useObjectViewListRenderer({ dataSource={ds} /> ); - }, [activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, recordOpen, openAsPage, rowOpensRecord, handleListRowsChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, previewDrafts, previewDataSource, unpublishedObjects]); + }, [activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, recordOpen, openAsPage, rowOpensRecord, handleListRowsChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 1880908f434..c5f6ce02f22 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -256,9 +256,10 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * [objectstack#35702] Wired only for a reader who may change the view: each * footer cell becomes the menu that picks the column's calculation (`null` = * None). The grid draws the pick at once; the host saves it on the view and - * hands it back as the column's `summary`. + * hands it back as the column's `summary`. `drawnFields` are the field + * columns drawn, in order, for a view that declares no `columns` of its own. */ - onColumnSummaryPick?: (field: string, summary: ColumnSummaryType | null) => void; + onColumnSummaryPick?: (field: string, summary: ColumnSummaryType | null, drawnFields: readonly string[]) => void; /** [objectstack#35702] Whether the resident footer row is drawn (it carries the record count). */ onResidentSummaryRowChange?: (drawn: boolean) => void; /** @@ -1577,9 +1578,10 @@ export const ObjectGrid: React.FC = ({ }); // Keyed on the declared calculations' content, never the columns' identity. }, [declaredSummaryKey]); + const drawnFieldsRef = React.useRef([]); const pickColumnSummary = useCallback((field: string, summary: ColumnSummaryType | null) => { setSummaryPicks((picks) => ({ ...picks, [field]: summary })); - onColumnSummaryPick?.(field, summary); + onColumnSummaryPick?.(field, summary, drawnFieldsRef.current); }, [onColumnSummaryPick]); const { t: summaryT } = useSummaryTranslation(); // A host's resident row is drawn with no calculation too, and under a @@ -3009,6 +3011,7 @@ export const ObjectGrid: React.FC = ({ // objectstack#35548 — the column summaries as the table's own last row, each // under its column, led by the count of the records they summarise. A host // that draws them itself (`onColumnSummaryChange`) gets no row here. + const drawnFields: string[] = []; const summaryRow: ObjectGridDataTableSchema['summaryRow'] = (hasSummary || residentRowDrawn) && !onColumnSummaryChange ? { lead: t('grid.summary.countLead', { @@ -3016,6 +3019,7 @@ export const ObjectGrid: React.FC = ({ }), cells: residentRowDrawn ? Object.fromEntries(tableColumns.flatMap((col: { accessorKey: string }) => { + if (objectFields?.[col.accessorKey]) drawnFields.push(col.accessorKey); const field = col.accessorKey; const def = objectFields?.[field] as Parameters[0]; const summary = summaries.get(field); @@ -3035,6 +3039,7 @@ export const ObjectGrid: React.FC = ({ : Object.fromEntries(Array.from(summaries, ([key, summary]) => [key, summary.label])), } : undefined; + drawnFieldsRef.current = drawnFields; // objectstack#35685 — a row a select-first save redrew, in place of the row // the grid read, while that read is the one held. const patchedRowOf = (row: any): any => { diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index e865e1e8a1a..c59c31395a5 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -64,7 +64,7 @@ import { useObjectLabel, useSafeFieldLabel, createSafeTranslation, useDisplayLoc // on the FLAT `schema.ariaLabel` and is resolved by `SchemaRenderer` instead // (objectui#5134). import { resolveI18nLabel as resolveInlineI18nLabel, normalizeFilterOperator, PaginationConfigSchema } from '@objectstack/spec/ui'; -import type { GroupingConfig } from '@objectstack/spec/ui'; +import type { ColumnSummary, GroupingConfig } from '@objectstack/spec/ui'; import { canonicalAstOperator, isVirtualSearchField, platformProvisionsStorage, resolveInjectedSystemColumns, resolveSearchFieldResolution, type SearchFieldMeta } from '@objectstack/spec/data'; import { SystemFieldName } from '@objectstack/spec/system'; import { usePermissions } from '@object-ui/permissions'; @@ -387,6 +387,15 @@ export interface ListViewProps { onInlineEditChange?: (next: boolean) => void; /** Called when the user resizes/reorders columns in the underlying grid. */ onColumnStateChange?: (state: { order?: string[]; widths?: Record }) => void; + /** + * objectstack#35702 — the grid's footer calculation picked by the reader + * (`null` = None). Wired only for a reader who may change the open view; + * absent ⇒ the footer draws its figures and offers no menu. The host saves + * the pick as the column's `summary` on the view; `drawnFields` are the + * field columns drawn, for a view that declares no `columns`. A HOST prop, + * never a schema key. + */ + onColumnSummaryPick?: (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => void; /** * Callback when a row/item is clicked (overrides NavigationConfig). * @@ -2110,6 +2119,7 @@ export const ListView = React.forwardRef(({ addedFields, onAddedFieldsChange, onColumnStateChange, + onColumnSummaryPick, onRowClick, showViewSwitcher: showViewSwitcherProp, userFilterSelections, @@ -2264,6 +2274,8 @@ export const ListView = React.forwardRef(({ // The object definition, read from the data source below ("Fetch object // definition"). Declared here because the toolbar's search decision reads it. const [objectDef, setObjectDef] = React.useState(null); + // objectstack#35702 — the grid draws its resident footer row, which says the record count. + const [gridDrawsCount, setGridDrawsCount] = React.useState(false); const [objectDefLoaded, setObjectDefLoaded] = React.useState(false); /** @@ -5130,6 +5142,16 @@ export const ListView = React.forwardRef(({ // does not opt out (`inlineEditOffered`); objectstack#35684 retired // the mode that used to gate this as well. editable: inlineEditOffered, + // objectstack#35702 — the resident footer row (the record count in + // its first cell, so the list draws no count bar of its own), and, + // for a reader who may change the view, each cell's calculation menu. + ...(!compact && !cappedWindow + ? { + residentSummaryRow: true, + onResidentSummaryRowChange: setGridDrawsCount, + ...(onColumnSummaryPick ? { onColumnSummaryPick } : {}), + } + : {}), ...(schema.wrapHeaders != null ? { wrapHeaders: schema.wrapHeaders } : {}), ...(schema.resizable != null ? { resizable: schema.resizable } : {}), ...(schema.selection ? { selection: schema.selection } : {}), @@ -5698,7 +5720,7 @@ export const ListView = React.forwardRef(({ // asynchronously (`/me/permissions`) and `objectDef` loads into state, so a // grid schema built before either resolved must be rebuilt when they do — // otherwise `editable` keeps the pre-verdict answer for the session. - }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged]); + }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged, compact, cappedWindow, onColumnSummaryPick]); // The count the toolbar shows: a record-mode amount's code condition is // part of its amount row (objectstack#27188), not a filter of its own, and a @@ -6627,6 +6649,9 @@ export const ListView = React.forwardRef(({ // table, each under its column). const recordCountShown = !loading && data.length > 0 && surfaceDrawsFetchedRows && schema.showRecordCount !== false; + // objectstack#35702 — a grid that draws its resident footer row says the + // count there, in its first cell; the bar keeps only the cap warning. + const recordCountTextShown = recordCountShown && !(currentView === 'grid' && gridDrawsCount); const dataLimitWarningShown = recordCountShown && dataLimitReached && !(paginate && serverTotal != null) && !infiniteScroll; // objectui#12619 — a board that pages its own lanes draws every record of the @@ -8328,7 +8353,7 @@ export const ListView = React.forwardRef(({ tooltip when they do not fit. */} {/* The compact posture prints its count in its header (objectui#12703), the capped one in its 「View all N」 link (objectstack#26613). */} - {listChromeShown && (recordCountShown || dataLimitWarningShown || boardRecordCountShown) && ( + {listChromeShown && (recordCountTextShown || dataLimitWarningShown || boardRecordCountShown) && (
(({ {t('list.recordCount', { count: fetchedTotal })} )} - {recordCountShown && ( + {recordCountTextShown && ( {/* Under server pagination `data` is only the current page, so the honest record count is the server's grand total (#586). When the From c116220c2da6c31a210005f210f500b340ce239c Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:36:24 +0000 Subject: [PATCH 3/7] test(ui): pin the resident footer row and its calculation menu; migrate count assertions to the row's lead Claude-Session: https://claude.ai/code/session_01L6bhgVb7fsaFeMStucvNWA Co-authored-by: Claude --- .changeset/35702-footer-calculation-row.md | 17 ++ content/docs/frontend/plugins/plugin-grid.mdx | 12 ++ ...bjectView.recordCountFooter-10636.test.tsx | 12 +- .../app-shell/src/views/ObjectView.tsx | 2 +- .../columnSummaryWrite-35702.test.ts | 29 ++++ ui/packages/plugin-grid/README.md | 17 ++ ui/packages/plugin-grid/src/ObjectGrid.tsx | 15 +- .../footerCalculationPicker-35702.test.tsx | 162 ++++++++++++++++++ .../footerSummaryScope-12081.test.tsx | 6 +- ui/packages/plugin-list/src/ListView.tsx | 9 +- .../src/__tests__/ListView.test.tsx | 31 ++-- 11 files changed, 283 insertions(+), 29 deletions(-) create mode 100644 .changeset/35702-footer-calculation-row.md create mode 100644 ui/packages/app-shell/src/views/__tests__/columnSummaryWrite-35702.test.ts create mode 100644 ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx diff --git a/.changeset/35702-footer-calculation-row.md b/.changeset/35702-footer-calculation-row.md new file mode 100644 index 00000000000..fbb068bc572 --- /dev/null +++ b/.changeset/35702-footer-calculation-row.md @@ -0,0 +1,17 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/plugin-list': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(ui): a resident footer row on list tables, where a reader who may change the view picks each column's calculation + +Clause-②: yes (widening) +Metadata-protocol: none + +A list's table view now always ends in one footer row, aligned with the columns and held at the bottom of the table: the record count in its first cell, and under each column its calculation, if any, written as the calculation's name in the secondary text colour and the figure in the normal one, with a space and no colon (`Sum ¥1,234,500`). A `min` / `max` over a date reads Earliest / Latest. The list's own "N records" line at the foot of the page is gone from a table that draws this row; the data-cap notice stays there. A grouped table, the phone's card list and every other view type are unchanged. + +A reader who may change the open view clicks a cell to pick the column's calculation from one menu that lists what the field type allows (sum and average on numbers and amounts, earliest and latest on dates, the counts on any field), the current one ticked and None last. The pick shows at once. The console saves it as the column's `summary` on the view: a personal view at once; a shared view, for a reader who may edit it, as a draft through the view settings' own save, which other readers see once it is published. A reader who may not change the view sees the figures and no menu. + +New host props, all optional and never authored metadata: `ObjectGrid` takes `residentSummaryRow`, `onColumnSummaryPick(field, summary, drawnFields)` and `onResidentSummaryRowChange(drawn)`; `ListView` takes `onColumnSummaryPick`. `ColumnSummaryResult` gains `name` and `text`, the two halves of its `label`. `@object-ui/i18n` adds the `grid.summary` keys `earliest`, `latest`, `pageName`, `calculate`, `none`, `menuPercentEmpty` and `menuPercentFilled` in every pack. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 31d1c45621c..4c3e7ca23a2 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -396,6 +396,18 @@ row whose new value would sort it elsewhere stays in place until the next load re-reads the list, "Overwrite anyway" writes over it and keeps the row in place. +### Footer calculations + +A column's `summary` draws its calculation in the table's last row, under the +column. A host that passes `residentSummaryRow` draws that row on a flat table +even when nothing is declared, led by the record count. With +`onColumnSummaryPick` as well (wired only for a reader who may change the view), +clicking a cell opens one menu of the calculations its field type allows, the +current one ticked and None last; the grid draws the pick at once and the host +saves it as the column's `summary`. The console's list saves it on a personal +view at once, and on a shared view as a draft that others see once it is +published. + ### Keyboard navigation `keyboardNavigation` turns the grid's data cells into one roving Tab stop, on the diff --git a/ui/packages/app-shell/src/views/ObjectView.recordCountFooter-10636.test.tsx b/ui/packages/app-shell/src/views/ObjectView.recordCountFooter-10636.test.tsx index c3276896ba0..3287e3921de 100644 --- a/ui/packages/app-shell/src/views/ObjectView.recordCountFooter-10636.test.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.recordCountFooter-10636.test.tsx @@ -197,10 +197,12 @@ async function footer(lang: Lang, count: number): Promise { , ); await screen.findByRole('dialog', undefined, { timeout: 5000 }); - const bar = await screen.findByTestId('record-count-bar', undefined, { timeout: 5000 }); - // The split pane's footer is gone: the bar is the one count on the page. + // objectstack#35702 — the grid's footer row leads with the count, the one + // count at the foot of the page: no split-pane footer, no count bar. + const lead = await screen.findByTestId('data-table-summary-lead', undefined, { timeout: 5000 }); expect(screen.queryByTestId('record-count-footer')).toBeNull(); - const text = bar.querySelector('span')?.textContent ?? ''; + expect(screen.queryByTestId('record-count-bar')).toBeNull(); + const text = lead.textContent ?? ''; cleanup(); return text; } @@ -335,8 +337,8 @@ describe('a list page load reads its object once, and the bar counts that answer render(); const reads = () => find.mock.calls.filter(([object]) => object === OBJECT_NAME); const barCount = async () => - (await screen.findByTestId('record-count-bar', undefined, { timeout: 5000 })).querySelector('span') - ?.textContent ?? ''; + // objectstack#35702 — the count leads the grid's footer row. + (await screen.findByTestId('data-table-summary-lead', undefined, { timeout: 5000 })).textContent ?? ''; return { reads, barCount, bump: () => act(async () => { bump(); }) }; } diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index af683d63e0b..1e3e182681c 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -11,7 +11,7 @@ import type { ColumnSummary } from '@objectstack/spec/ui'; import type { ListColumn } from '@object-ui/types'; -import { columnsWithSummary } from './columnSummaryWrite'; +import { columnsWithSummary } from './columnSummaryWrite.js'; import { useMemo, useState, useCallback, useEffect, useRef, lazy, Suspense } from 'react'; import { useParams, useSearchParams, useNavigate, useLocation, useHref, createSearchParams } from 'react-router-dom'; import { resolveAffordance, type FilterTokenScope, type SchemaLike } from '@object-ui/core'; diff --git a/ui/packages/app-shell/src/views/__tests__/columnSummaryWrite-35702.test.ts b/ui/packages/app-shell/src/views/__tests__/columnSummaryWrite-35702.test.ts new file mode 100644 index 00000000000..7be9d9e1865 --- /dev/null +++ b/ui/packages/app-shell/src/views/__tests__/columnSummaryWrite-35702.test.ts @@ -0,0 +1,29 @@ +/** objectstack#35702 — the view's `columns` the footer menu saves. */ +import { describe, it, expect } from 'vitest'; +import { columnsWithSummary } from '../columnSummaryWrite'; + +describe('columnsWithSummary (objectstack#35702)', () => { + it('sets the calculation on the view\'s own column, in the object form', () => { + expect(columnsWithSummary(['name', 'amount'], 'amount', 'sum', [])).toEqual([ + { field: 'name' }, { field: 'amount', summary: 'sum' }, + ]); + }); + it('keeps the object form\'s field override and moves only the calculation', () => { + expect(columnsWithSummary([{ field: 'amount', summary: { type: 'sum', field: 'amount_base' } }], 'amount', 'avg', [])) + .toEqual([{ field: 'amount', summary: { type: 'avg', field: 'amount_base' } }]); + }); + it('takes the calculation off for None', () => { + expect(columnsWithSummary([{ field: 'amount', label: 'Amount', summary: 'sum' }], 'amount', null, [])) + .toEqual([{ field: 'amount', label: 'Amount' }]); + }); + it('writes the drawn columns for a view that declares none, so it keeps drawing them', () => { + expect(columnsWithSummary(undefined, 'amount', 'max', ['name', 'amount'])).toEqual([ + { field: 'name' }, { field: 'amount', summary: 'max' }, + ]); + }); + it('appends a column the view does not list', () => { + expect(columnsWithSummary(['name'], 'amount', 'sum', ['name', 'amount'])).toEqual([ + { field: 'name' }, { field: 'amount', summary: 'sum' }, + ]); + }); +}); diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index c5cd0fda3ad..84124548fbf 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -356,6 +356,23 @@ The accepted values are `ColumnSummarySchema` from `@objectstack/spec`: | `min` | smallest | numeric values | | `max` | largest | numeric values | +#### The resident footer row and its calculation menu + +A host that passes `residentSummaryRow` gets the footer row on a flat table +even when no column declares a `summary`: the record count in its first cell, +each column's calculation, if any, under it, drawn as the calculation's name in +the secondary text colour and the figure in the normal one (`Sum 1,234.00`). +A grouped grid and the phone's card list draw no such row; the grid reports +whether it drew one through `onResidentSummaryRowChange`. + +A host that also passes `onColumnSummaryPick(field, summary, drawnFields)` +(wire it only for a reader who may change the view) turns each cell into a +menu of the calculations the column's field type allows — `sum`/`avg` on +numbers and amounts, `min`/`max` on numbers and dates (named Earliest and +Latest on a date), the count family on any field, the current one ticked and +None last. The grid draws a pick at once; the host saves it as the column's +`summary` and hands the view back. + A cell counts as empty when it is `null`, `undefined`, `""` or an empty array, so an unset multi-select or lookup reads as empty rather than as a filled `[]`. diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index c5f6ce02f22..2ec5a609bf5 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -252,6 +252,12 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * authored metadata. */ residentSummaryRow?: boolean; + /** + * [objectstack#35702] The host's own wording of the record count that leads + * the footer row (the list's 「42 records」, plural forms included). Absent ⇒ + * the grid's 「Count 42」. + */ + summaryRowLead?: (count: number) => React.ReactNode; /** * [objectstack#35702] Wired only for a reader who may change the view: each * footer cell becomes the menu that picks the column's calculation (`null` = @@ -768,6 +774,7 @@ export const ObjectGrid: React.FC = ({ showRowNumbers: hostShowRowNumbers, onColumnSummaryChange, residentSummaryRow, + summaryRowLead, onColumnSummaryPick, onResidentSummaryRowChange, onRowGroupsChange, @@ -3014,9 +3021,11 @@ export const ObjectGrid: React.FC = ({ const drawnFields: string[] = []; const summaryRow: ObjectGridDataTableSchema['summaryRow'] = (hasSummary || residentRowDrawn) && !onColumnSummaryChange ? { - lead: t('grid.summary.countLead', { - value: (typeof resolvedTotalMatching === 'number' ? resolvedTotalMatching : data.length).toLocaleString(displayLocale), - }), + lead: summaryRowLead + ? summaryRowLead(typeof resolvedTotalMatching === 'number' ? resolvedTotalMatching : data.length) + : t('grid.summary.countLead', { + value: (typeof resolvedTotalMatching === 'number' ? resolvedTotalMatching : data.length).toLocaleString(displayLocale), + }), cells: residentRowDrawn ? Object.fromEntries(tableColumns.flatMap((col: { accessorKey: string }) => { if (objectFields?.[col.accessorKey]) drawnFields.push(col.accessorKey); diff --git a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx new file mode 100644 index 00000000000..9985d9564ac --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx @@ -0,0 +1,162 @@ +/** + * objectstack#35702 — the list's resident footer row: the record count in its + * first cell, and, for a reader who may change the view, each column's cell + * the menu that picks its calculation by the field's type. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import '@testing-library/jest-dom'; +import React from 'react'; +import type { DataSource, ObjectGridSchema } from '@object-ui/types'; + +import { ObjectGrid } from '../ObjectGrid'; +import { offeredColumnSummaries, isTemporalSummaryField } from '../useColumnSummary'; +import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; +import { installExplainDouble } from './explainDouble'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider } from '@object-ui/react'; + +beforeAll(() => { + registerAllFields(); + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as unknown as Element['scrollIntoView']; + } +}); +beforeEach(() => { + __clearRecordCrudVerdictCache(); + installExplainDouble(); +}); +afterEach(() => { + cleanup(); +}); + +describe('offeredColumnSummaries (objectstack#35702)', () => { + it('offers the numeric calculations on an amount and the counts on any field', () => { + expect(offeredColumnSummaries({ type: 'currency' })).toEqual([ + 'sum', 'avg', 'min', 'max', 'count_unique', 'count_filled', 'count_empty', 'percent_filled', 'percent_empty', + ]); + }); + it('offers no sum or average on a text field', () => { + const offered = offeredColumnSummaries({ type: 'text' }); + expect(offered).not.toContain('sum'); + expect(offered).not.toContain('avg'); + expect(offered).toContain('count_filled'); + }); + it('offers only counts on a lookup', () => { + expect(offeredColumnSummaries({ type: 'lookup' }).every((s) => s.startsWith('count') || s.startsWith('percent'))).toBe(true); + }); + it('offers earliest / latest on a date, named so', () => { + const offered = offeredColumnSummaries({ type: 'date' }); + expect(offered).toEqual(expect.arrayContaining(['min', 'max'])); + expect(offered).not.toContain('sum'); + expect(isTemporalSummaryField({ type: 'date' })).toBe(true); + expect(isTemporalSummaryField({ type: 'number' })).toBe(false); + }); + it('offers a boolean no sum, average or extremes', () => { + expect(offeredColumnSummaries({ type: 'boolean' }).filter((s) => ['sum', 'avg', 'min', 'max'].includes(s))).toEqual([]); + }); + it('offers an unknown field the counts it can draw, never count_unique', () => { + expect(offeredColumnSummaries(undefined)).toEqual(['count_filled', 'count_empty', 'percent_filled', 'percent_empty']); + }); +}); + +const OBJECT = 'plan_line'; +const ROWS = [ + { id: 'r1', name: 'Line 1', amount: 100, due: '2026-01-05' }, + { id: 'r2', name: 'Line 2', amount: 250, due: '2026-03-09' }, +]; +const FIELDS = { + id: { type: 'text', label: 'Id' }, + name: { type: 'text', label: 'Name' }, + amount: { type: 'number', label: 'Amount' }, + due: { type: 'date', label: 'Due' }, +}; + +const dataSource = () => ({ + find: vi.fn(async () => ({ data: ROWS.map((r) => ({ ...r })), total: ROWS.length })), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + getObjectSchema: vi.fn(async () => ({ name: OBJECT, fields: FIELDS })), +}); + +function renderGrid(props: Partial>, columns: unknown[] = [ + { field: 'name', label: 'Name' }, + { field: 'amount', label: 'Amount' }, + { field: 'due', label: 'Due' }, +]) { + return render( + + + , + ); +} + +describe('the resident footer row (objectstack#35702)', () => { + it('is drawn with no calculation declared, the record count in its first cell, and reports itself', async () => { + const reported = vi.fn(); + renderGrid({ residentSummaryRow: true, onResidentSummaryRowChange: reported }); + const row = await screen.findByTestId('data-table-summary-row'); + expect(within(row).getByTestId('data-table-summary-lead')).toHaveTextContent('Count 2'); + expect(reported).toHaveBeenLastCalledWith(true); + }); + + it('is not drawn for a host that does not ask for it', async () => { + renderGrid({}); + await screen.findByText('Line 1'); + expect(screen.queryByTestId('data-table-summary-row')).toBeNull(); + }); + + it('offers no menu to a reader who may not change the view, and still draws the figure', async () => { + renderGrid({ residentSummaryRow: true }, [ + { field: 'name', label: 'Name' }, + { field: 'amount', label: 'Amount', summary: 'sum' }, + ]); + const row = await screen.findByTestId('data-table-summary-row'); + expect(within(row).queryByRole('button')).toBeNull(); + expect(within(row).getByTestId('data-table-summary-amount')).toHaveTextContent('Sum 350'); + }); + + it('picks a calculation from the cell, draws it at once, ticks it, and None takes it off', async () => { + const user = userEvent.setup(); + const onPick = vi.fn(); + renderGrid({ residentSummaryRow: true, onColumnSummaryPick: onPick }); + await screen.findByTestId('data-table-summary-row'); + expect(screen.getByTestId('summary-picker-hint-amount')).toHaveTextContent('Calculate'); + + await user.click(screen.getByTestId('summary-picker-amount')); + const menu = await screen.findByTestId('summary-menu-amount'); + expect(within(menu).getByTestId('summary-option-sum')).toHaveTextContent('Sum'); + expect(within(menu).getByTestId('summary-option-none')).toHaveTextContent('None'); + await user.click(within(menu).getByTestId('summary-option-sum')); + + expect(onPick).toHaveBeenLastCalledWith('amount', 'sum', ['name', 'amount', 'due']); + await waitFor(() => expect(screen.getByTestId('summary-picker-amount')).toHaveTextContent('Sum 350')); + + await user.click(screen.getByTestId('summary-picker-amount')); + const again = await screen.findByTestId('summary-menu-amount'); + expect(within(again).getByTestId('summary-option-sum').querySelector('svg')).toHaveClass('opacity-100'); + await user.click(within(again).getByTestId('summary-option-none')); + expect(onPick).toHaveBeenLastCalledWith('amount', null, ['name', 'amount', 'due']); + await waitFor(() => expect(screen.getByTestId('summary-picker-amount')).not.toHaveTextContent('Sum')); + }); + + it('names a date column\'s extremes Earliest and Latest', async () => { + const user = userEvent.setup(); + renderGrid({ residentSummaryRow: true, onColumnSummaryPick: vi.fn() }); + await screen.findByTestId('data-table-summary-row'); + await user.click(screen.getByTestId('summary-picker-due')); + const menu = await screen.findByTestId('summary-menu-due'); + expect(within(menu).getByTestId('summary-option-min')).toHaveTextContent('Earliest'); + expect(within(menu).getByTestId('summary-option-max')).toHaveTextContent('Latest'); + expect(within(menu).queryByTestId('summary-option-sum')).toBeNull(); + await user.click(within(menu).getByTestId('summary-option-max')); + await waitFor(() => expect(screen.getByTestId('summary-picker-due')).toHaveTextContent(/^Latest /)); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx index 0807c5f1904..e43662de4e7 100644 --- a/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/footerSummaryScope-12081.test.tsx @@ -593,17 +593,17 @@ describe('a date-family `min` / `max` in the footer reads as its cell, never as render(hostGrid(ds, { rows, columns: CLOSED_MAX })); await waitFor(() => expect(footerText('closed_at')).toBeTruthy()); await waitFor(() => expect(closedAtCell('Line 9')).toBeTruthy()); - expect(footerText('closed_at')).toBe(`Closed At: Max: ${closedAtCell('Line 9')}`); + expect(footerText('closed_at')).toBe(`Closed At: Latest: ${closedAtCell('Line 9')}`); expect(footerText('closed_at')).not.toMatch(/2,025|NaN/); }); it('own fetch, one page of 300: the whole set\'s `max` (the server\'s stored text) reads as the last row\'s cell', async () => { const ds = makeDataSource(); render(ownFetchGrid(ds, CLOSED_MAX)); - await waitFor(() => expect(footerText('closed_at')).toMatch(/^Closed At: Max: /)); + await waitFor(() => expect(footerText('closed_at')).toMatch(/^Closed At: Latest: /)); const footer = footerText('closed_at'); expect(footer).not.toMatch(/2,025|NaN|this page/); - expect(footer).toBe(`Closed At: Max: ${await cellOf(ROWS[299])}`); + expect(footer).toBe(`Closed At: Latest: ${await cellOf(ROWS[299])}`); }); it('a `sum` / `avg` over a datetime column draws no figure; CONTROL — a `max` over a number column still reads as a number', async () => { diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index c59c31395a5..7bbfd15f78a 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -2152,6 +2152,8 @@ export const ListView = React.forwardRef(({ const showViewSwitcher = showViewSwitcherProp ?? (propSchema as any)?.showViewSwitcher ?? false; // i18n support for record count and other labels const { t } = useListViewTranslation(); + // objectstack#35702 — the grid's footer row leads with the list's own count wording. + const recordCountLead = React.useCallback((count: number) => t('list.recordCount', { count }), [t]); const { fieldLabel: resolveFieldLabel, actionLabel: resolveActionLabel, objectLabel: resolveObjectLabel } = useListFieldLabel(); const { translateOptions } = useSafeFieldLabel(); // The audience's BCP-47 tag (tenant locale → UI language → `en`), used below @@ -5145,9 +5147,12 @@ export const ListView = React.forwardRef(({ // objectstack#35702 — the resident footer row (the record count in // its first cell, so the list draws no count bar of its own), and, // for a reader who may change the view, each cell's calculation menu. - ...(!compact && !cappedWindow + // A view that hides its record count (`showRecordCount: false`) + // keeps the old row: drawn only under a declared calculation. + ...(!compact && !cappedWindow && schema.showRecordCount !== false ? { residentSummaryRow: true, + summaryRowLead: recordCountLead, onResidentSummaryRowChange: setGridDrawsCount, ...(onColumnSummaryPick ? { onColumnSummaryPick } : {}), } @@ -5720,7 +5725,7 @@ export const ListView = React.forwardRef(({ // asynchronously (`/me/permissions`) and `objectDef` loads into state, so a // grid schema built before either resolved must be rebuilt when they do — // otherwise `editable` keeps the pre-verdict answer for the session. - }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged, compact, cappedWindow, onColumnSummaryPick]); + }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged, compact, cappedWindow, onColumnSummaryPick, recordCountLead]); // The count the toolbar shows: a record-mode amount's code condition is // part of its amount row (objectstack#27188), not a filter of its own, and a diff --git a/ui/packages/plugin-list/src/__tests__/ListView.test.tsx b/ui/packages/plugin-list/src/__tests__/ListView.test.tsx index cb0cd2c4d1a..ded3ca9fe44 100644 --- a/ui/packages/plugin-list/src/__tests__/ListView.test.tsx +++ b/ui/packages/plugin-list/src/__tests__/ListView.test.tsx @@ -682,7 +682,7 @@ describe('ListView', () => { expect(screen.queryByTestId('sharing-locked-by')).not.toBeInTheDocument(); }); - it('should show record count bar when data is loaded', async () => { + it('should show the record count in the grid\'s footer row, and no count bar (objectstack#35702)', async () => { const mockItems = [ { id: '1', name: 'Alice', email: 'alice@test.com' }, { id: '2', name: 'Bob', email: 'bob@test.com' }, @@ -700,9 +700,10 @@ describe('ListView', () => { renderWithProvider(); await vi.waitFor(() => { - expect(screen.getByTestId('record-count-bar')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toBeInTheDocument(); }); - expect(screen.getByText('3 records')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toHaveTextContent('3 records'); + expect(screen.queryByTestId('record-count-bar')).not.toBeInTheDocument(); }); it('should not show record count bar when no data', async () => { @@ -1431,7 +1432,7 @@ describe('ListView', () => { }); }); - it('should show record count bar by default (showRecordCount undefined)', async () => { + it('should show the record count by default (showRecordCount undefined), in the grid\'s footer row', async () => { const mockItems = [ { id: '1', name: 'Alice', email: 'alice@test.com' }, ]; @@ -1447,7 +1448,7 @@ describe('ListView', () => { renderWithProvider(); await vi.waitFor(() => { - expect(screen.getByTestId('record-count-bar')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toBeInTheDocument(); }); }); }); @@ -2056,7 +2057,7 @@ describe('ListView', () => { renderWithProvider(); await vi.waitFor(() => { - expect(screen.getByTestId('record-count-bar')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toBeInTheDocument(); }); expect(screen.queryByTestId('page-size-selector')).not.toBeInTheDocument(); }); @@ -2116,9 +2117,9 @@ describe('ListView', () => { renderWithProvider(); await vi.waitFor(() => { - expect(screen.getByTestId('record-count-bar')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toBeInTheDocument(); }); - expect(screen.getByText('2 records')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toHaveTextContent('2 records'); expect(mockDataSource.find).not.toHaveBeenCalled(); }); @@ -2138,9 +2139,9 @@ describe('ListView', () => { renderWithProvider(); await vi.waitFor(() => { - expect(screen.getByTestId('record-count-bar')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toBeInTheDocument(); }); - expect(screen.getByText('2 records')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toHaveTextContent('2 records'); expect(mockDataSource.find).not.toHaveBeenCalled(); }); @@ -2161,7 +2162,7 @@ describe('ListView', () => { renderWithProvider(); await vi.waitFor(() => { - expect(screen.getByText('3 records')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toHaveTextContent('3 records'); }); // Open search popover and type search query @@ -2169,7 +2170,7 @@ describe('ListView', () => { fireEvent.change(screen.getByPlaceholderText(/search/i), { target: { value: 'alice' } }); await vi.waitFor(() => { - expect(screen.getByText('1 record')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toHaveTextContent('1 record'); }); expect(mockDataSource.find).not.toHaveBeenCalled(); }); @@ -2193,7 +2194,7 @@ describe('ListView', () => { renderWithProvider(); await vi.waitFor(() => { - expect(screen.getByText('2 records')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toHaveTextContent('2 records'); }); // Open search popover and type search query @@ -2201,7 +2202,7 @@ describe('ListView', () => { fireEvent.change(screen.getByPlaceholderText(/search/i), { target: { value: 'bob' } }); await vi.waitFor(() => { - expect(screen.getByText('1 record')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toHaveTextContent('1 record'); }); expect(mockDataSource.find).not.toHaveBeenCalled(); }); @@ -2586,7 +2587,7 @@ describe('ListView', () => { renderWithProvider(); await vi.waitFor(() => { - expect(screen.getByTestId('record-count-bar')).toBeInTheDocument(); + expect(screen.getByTestId('data-table-summary-lead')).toBeInTheDocument(); }); expect(screen.queryByTestId('page-size-selector')).not.toBeInTheDocument(); From bd759bb7aae5a815e8de4a768a51be6fd66e9826 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 18:56:44 +0000 Subject: [PATCH 4/7] fix(app-shell): offer the footer menu on a shared view only where the metadata door stores it; migrate e2e count reads to the footer row Claude-Session: https://claude.ai/code/session_01L6bhgVb7fsaFeMStucvNWA Co-authored-by: Claude --- ui/e2e/list-condition-row-35549.spec.ts | 8 ++++---- ui/e2e/live/saved-view-filter.spec.ts | 4 ++-- ui/e2e/live/user-filters.spec.ts | 8 ++++---- ui/packages/app-shell/src/views/ObjectView.tsx | 9 +++++++-- 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/ui/e2e/list-condition-row-35549.spec.ts b/ui/e2e/list-condition-row-35549.spec.ts index d11f59615db..79258f1ef64 100644 --- a/ui/e2e/list-condition-row-35549.spec.ts +++ b/ui/e2e/list-condition-row-35549.spec.ts @@ -37,7 +37,7 @@ import { uiRoot } from '../scripts/ui-root.mjs'; * * - The data source is in memory: one object definition and twelve records. * It records every `find` it is asked, and answers the stage filter - * (`in`) and the sort the list sends, so the count bar and the row order + * (`in`) and the sort the list sends, so the footer row's count and the row order * move as they do against a server. * - The translator is the English defaults table (no provider). * - Animations are off, so a closed popover leaves the page at once rather @@ -256,7 +256,7 @@ async function mount(page: Page): Promise { await page.goto('http://localhost/list-condition-row'); await page.addScriptTag({ content: bundle, type: 'module' }); await page.getByTestId('toolbar-filter-trigger').waitFor({ state: 'attached', timeout: 30_000 }); - await page.getByTestId('record-count-bar').waitFor({ state: 'attached', timeout: 30_000 }); + await page.getByTestId('data-table-summary-lead').waitFor({ state: 'attached', timeout: 30_000 }); await style(page); } @@ -268,8 +268,8 @@ async function click(page: Page, testId: string): Promise { const slot = (page: Page) => page.getByTestId('list-condition-row'); const slotHeight = (page: Page) => slot(page).evaluate((el) => el.getBoundingClientRect().height); -/** The number the count bar reads, once the list has answered. */ -const count = async (page: Page) => (await page.getByTestId('record-count-bar').textContent())?.match(/\d+/)?.[0]; +/** The number the grid's footer row leads with (objectstack#35702), once the list has answered. */ +const count = async (page: Page) => (await page.getByTestId('data-table-summary-lead').textContent())?.match(/\d+/)?.[0]; const sortNow = (page: Page) => page.evaluate(() => (window as unknown as { __sort: Array<{ field: string; order: string }> }).__sort.map((s) => `${s.field}:${s.order}`)); diff --git a/ui/e2e/live/saved-view-filter.spec.ts b/ui/e2e/live/saved-view-filter.spec.ts index fd36de76649..001b81025a4 100644 --- a/ui/e2e/live/saved-view-filter.spec.ts +++ b/ui/e2e/live/saved-view-filter.spec.ts @@ -27,7 +27,7 @@ import { test, expect } from '@playwright/test'; * `showcase_task.in_progress` is a SHIPPED saved view whose stored filter is * exactly that rule array (`src/ui/views/task.view.ts`), so no fixture setup is * needed — opening it is the reproduction. Before the fix the list renders no - * rows at all (the request 400s, so `record-count-bar` never mounts); after it, + * rows at all (the request 400s, so the footer row's count never mounts); after it, * the 2 in-progress tasks out of 10. * * Prereqs: the usual live-e2e pair (see playwright.live.config.ts). Run: @@ -60,7 +60,7 @@ test('a saved view filter reaches $filter as AST, and the server answers 200', a await page.goto(`/apps/${APP}/showcase_task/view/showcase_task.in_progress`); // The filter applied: 2 of the 10 seeded tasks are in_progress. - await expect(page.getByTestId('record-count-bar')).toContainText(/^2 /, { timeout: 20000 }); + await expect(page.getByTestId('data-table-summary-lead')).toContainText(/^2 /, { timeout: 20000 }); // And it applied by being ACCEPTED, not by some later rescue. expect(refused, `data requests the backend refused:\n${refused.join('\n')}`).toEqual([]); diff --git a/ui/e2e/live/user-filters.spec.ts b/ui/e2e/live/user-filters.spec.ts index 3cf37dbe6cb..5bb7b625466 100644 --- a/ui/e2e/live/user-filters.spec.ts +++ b/ui/e2e/live/user-filters.spec.ts @@ -33,12 +33,12 @@ test.describe('ADR-0053 interface mode — Task Triage tabs element', () => { // Picking a tab filters the grid and mirrors into the URL. await urgentTab.click(); await expect(page).toHaveURL(/uf__tab=urgent/); - await expect(page.getByTestId('record-count-bar')).toContainText(/^2 /, { timeout: 15000 }); + await expect(page.getByTestId('data-table-summary-lead')).toContainText(/^2 /, { timeout: 15000 }); // Reload: the tab selection and its filter survive. await page.reload(); await expect(page).toHaveURL(/uf__tab=urgent/); - await expect(page.getByTestId('record-count-bar')).toContainText(/^2 /, { timeout: 15000 }); + await expect(page.getByTestId('data-table-summary-lead')).toContainText(/^2 /, { timeout: 15000 }); }); }); @@ -105,7 +105,7 @@ test.describe('ADR-0047 interface mode — Task Workbench', () => { // Select Urgent: the grid narrows and the URL picks up the selection. await options.getByText('Urgent').click(); await expect(page).toHaveURL(/uf_priority=urgent/); - await expect(page.getByTestId('record-count-bar')).toContainText(/^2 /, { timeout: 15000 }); + await expect(page.getByTestId('data-table-summary-lead')).toContainText(/^2 /, { timeout: 15000 }); // Counts snapshot: with Urgent active the OTHER options keep their // pre-selection counts instead of collapsing to 0 (the server already @@ -123,6 +123,6 @@ test.describe('ADR-0047 interface mode — Task Workbench', () => { await page.reload(); await expect(page).toHaveURL(/uf_priority=urgent/); await expect(page.getByTestId('filter-badge-priority')).toContainText('1'); - await expect(page.getByTestId('record-count-bar')).toContainText(/^2 /, { timeout: 15000 }); + await expect(page.getByTestId('data-table-summary-lead')).toContainText(/^2 /, { timeout: 15000 }); }); }); diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 1e3e182681c..fb818e1ce7d 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -59,7 +59,7 @@ import { useRecordOpenPreference } from '../utils/recordOpenPreference.js'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; import { LIST_PINNED_VIEW_PREFERENCE, objectPreferenceScope, useWorkspacePreference } from '../utils/workspacePreference.js'; import type { ListViewProps } from '@object-ui/plugin-list'; -import { defaultListViewId, viewRowId } from '../utils/viewIdentity.js'; +import { defaultListViewId, isSavedViewId, viewRowId } from '../utils/viewIdentity.js'; import { useObjectActions } from '../hooks/useObjectActions.js'; import { useObjectTranslation, useObjectLabel } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; @@ -1120,7 +1120,12 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co ? undefined : activeIsPersonal ? (canUpdatePersonalView ? handlePickPersonalViewSummary : undefined) - : isAdmin ? handlePickSharedViewSummary : undefined, + // Only a view the metadata door stores: a package view + // (a qualified, dotted name) or a saved one, never the + // fallback tab an object with no views is drawn with. + : isAdmin && (String(activeView.id).includes('.') || isSavedViewId(savedViews, String(activeView.id))) + ? handlePickSharedViewSummary + : undefined, }, }); From 6243bf8c92c2cb68f7371daf2e52177a8b33b502 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:38:08 +0000 Subject: [PATCH 5/7] fix(ui): a footer pick saves only the column's calculation, and is taken back when not saved L1 7048239634 on #35919. The pick no longer materialises the reader's drawn columns into the view or appends a column the reader added: the stored view's own columns are the base, and the menu is offered on the columns the view declares only (`summaryPickFields`). A personal view writes from its stored row, so unsaved hides and order never ride along. A save the host refuses (answer false, a promise of false, or a rejection) takes the pick back; the shared save also restores the prior view draft. A shared view the console saves is named `object.key` too (`showcase_product.team_products` in the custom package), so the gate stays the overlay read's list rather than the name's shape; a view a read-only package ships is refused by the door and the pick is taken back with the refusal said, as measured in the browser. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgVb7fsaFeMStucvNWA --- .changeset/35702-footer-calculation-row.md | 4 +- content/docs/frontend/plugins/plugin-grid.mdx | 8 ++- .../app-shell/src/views/ObjectView.tsx | 57 +++++++++++++------ .../columnSummaryWrite-35702.test.ts | 30 ++++++---- .../app-shell/src/views/columnSummaryWrite.ts | 35 +++++++----- .../src/views/objectViewListRenderer.tsx | 16 ++++-- ui/packages/plugin-grid/README.md | 9 ++- ui/packages/plugin-grid/src/ObjectGrid.tsx | 40 ++++++++++--- .../footerCalculationPicker-35702.test.tsx | 46 ++++++++++++++- ui/packages/plugin-list/src/ListView.tsx | 26 +++++++-- 10 files changed, 199 insertions(+), 72 deletions(-) diff --git a/.changeset/35702-footer-calculation-row.md b/.changeset/35702-footer-calculation-row.md index fbb068bc572..305a120e647 100644 --- a/.changeset/35702-footer-calculation-row.md +++ b/.changeset/35702-footer-calculation-row.md @@ -12,6 +12,6 @@ Metadata-protocol: none A list's table view now always ends in one footer row, aligned with the columns and held at the bottom of the table: the record count in its first cell, and under each column its calculation, if any, written as the calculation's name in the secondary text colour and the figure in the normal one, with a space and no colon (`Sum ¥1,234,500`). A `min` / `max` over a date reads Earliest / Latest. The list's own "N records" line at the foot of the page is gone from a table that draws this row; the data-cap notice stays there. A grouped table, the phone's card list and every other view type are unchanged. -A reader who may change the open view clicks a cell to pick the column's calculation from one menu that lists what the field type allows (sum and average on numbers and amounts, earliest and latest on dates, the counts on any field), the current one ticked and None last. The pick shows at once. The console saves it as the column's `summary` on the view: a personal view at once; a shared view, for a reader who may edit it, as a draft through the view settings' own save, which other readers see once it is published. A reader who may not change the view sees the figures and no menu. +A reader who may change the open view clicks a cell to pick the column's calculation from one menu that lists what the field type allows (sum and average on numbers and amounts, earliest and latest on dates, the counts on any field), the current one ticked and None last. The pick shows at once. The console saves it as the column's `summary` on the view, and nothing else of the reader's layout: a personal view at once; a shared view the console saved, for a reader who may edit it, as a draft through the view settings' own save, which other readers see once it is published. The menu is offered on the columns the view itself declares; a column the reader added for themselves and a view that declares no columns draw the figures with no menu. A pick that is not saved is taken back, with the refusal said (a view a read-only package ships is refused this way: its changes go to the package's customization). A reader who may not change the view sees the figures and no menu. -New host props, all optional and never authored metadata: `ObjectGrid` takes `residentSummaryRow`, `onColumnSummaryPick(field, summary, drawnFields)` and `onResidentSummaryRowChange(drawn)`; `ListView` takes `onColumnSummaryPick`. `ColumnSummaryResult` gains `name` and `text`, the two halves of its `label`. `@object-ui/i18n` adds the `grid.summary` keys `earliest`, `latest`, `pageName`, `calculate`, `none`, `menuPercentEmpty` and `menuPercentFilled` in every pack. +New host props, all optional and never authored metadata: `ObjectGrid` takes `residentSummaryRow`, `onColumnSummaryPick(field, summary)` (answer `false` to have the pick taken back), `summaryPickFields` and `onResidentSummaryRowChange(drawn)`; `ListView` takes `onColumnSummaryPick` and `columnSummaryPickFields`. `ColumnSummaryResult` gains `name` and `text`, the two halves of its `label`. `@object-ui/i18n` adds the `grid.summary` keys `earliest`, `latest`, `pageName`, `calculate`, `none`, `menuPercentEmpty` and `menuPercentFilled` in every pack. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index 4c3e7ca23a2..c6909fe381a 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -404,9 +404,11 @@ even when nothing is declared, led by the record count. With `onColumnSummaryPick` as well (wired only for a reader who may change the view), clicking a cell opens one menu of the calculations its field type allows, the current one ticked and None last; the grid draws the pick at once and the host -saves it as the column's `summary`. The console's list saves it on a personal -view at once, and on a shared view as a draft that others see once it is -published. +saves it as the column's `summary` (an answer of `false` takes the pick back). +`summaryPickFields` limits the menu to the columns the host can save. The +console's list offers it on the columns the view declares and saves only the +calculation: on a personal view at once, and on a shared view as a draft that +others see once it is published. ### Keyboard navigation diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index fb818e1ce7d..7444bb66953 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -11,7 +11,7 @@ import type { ColumnSummary } from '@objectstack/spec/ui'; import type { ListColumn } from '@object-ui/types'; -import { columnsWithSummary } from './columnSummaryWrite.js'; +import { columnsWithSummary, declaredColumnFields } from './columnSummaryWrite.js'; import { useMemo, useState, useCallback, useEffect, useRef, lazy, Suspense } from 'react'; import { useParams, useSearchParams, useNavigate, useLocation, useHref, createSearchParams } from 'react-router-dom'; import { resolveAffordance, type FilterTokenScope, type SchemaLike } from '@object-ui/core'; @@ -824,20 +824,35 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co activeViewId, baseView, }); - const handlePickPersonalViewSummary = (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => { - if (!activeView) return; - const row = personalViews.views.find((v) => v.id === activeView.id); - if (!row) return; - const columns = columnsWithSummary(row.config.columns as ListColumn[] | string[] | undefined, field, summary, drawnFields); - personalViews.update(row.id, { ...row.config, columns }).catch((err) => { + // objectstack#35702 — a footer pick saves the column's calculation and + // nothing else (L1 7048239634): the stored view's own columns are the + // base, so the reader's unsaved hides, order or added columns never ride + // along, and a column the view does not declare is not offered. Each + // resolves whether the pick was saved; on `false` the grid takes it back. + const personalViewRow = activeView ? personalViews.views.find((v) => v.id === activeView.id) : undefined; + const handlePickPersonalViewSummary = async (field: string, summary: ColumnSummary | null): Promise => { + if (!personalViewRow) return false; + const columns = columnsWithSummary(personalViewRow.config.columns as ListColumn[] | string[] | undefined, field, summary); + if (!columns) return false; + try { + await personalViews.update(personalViewRow.id, { ...personalViewRow.config, columns }); + return true; + } catch (err) { console.error('[ObjectView] Failed to save a footer calculation:', err); toast.error(t('form.saveError'), { description: err instanceof Error ? err.message : String(err) }); - }); + return false; + } }; - const handlePickSharedViewSummary = (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => { - if (!activeView) return; - const columns = columnsWithSummary(activeView.columns as ListColumn[] | string[] | undefined, field, summary, drawnFields); - void handleViewConfigSave({ ...activeView, columns }); + const handlePickSharedViewSummary = async (field: string, summary: ColumnSummary | null): Promise => { + if (!activeView) return false; + const columns = columnsWithSummary(activeView.columns as ListColumn[] | string[] | undefined, field, summary); + if (!columns) return false; + const priorDraft = viewDraft; + const saved = await handleViewConfigSave({ ...activeView, columns }); + // The panel's save keeps a refused draft on screen (the panel stays + // dirty); a refused pick is taken back instead. + if (!saved) setViewDraft(priorDraft); + return saved; }; // objectstack#29635 — creating one of the reader's own views, and Rename @@ -1119,13 +1134,21 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co pickSummary: isEnvironmentList || !activeView ? undefined : activeIsPersonal - ? (canUpdatePersonalView ? handlePickPersonalViewSummary : undefined) - // Only a view the metadata door stores: a package view - // (a qualified, dotted name) or a saved one, never the - // fallback tab an object with no views is drawn with. - : isAdmin && (String(activeView.id).includes('.') || isSavedViewId(savedViews, String(activeView.id))) + ? (canUpdatePersonalView && personalViewRow ? handlePickPersonalViewSummary : undefined) + // Only a view the metadata door stores (one the overlay + // read lists), never the fallback tab an object with no + // views is drawn with. Every stored view has a qualified, + // dotted name, the console's own saved views included + // (`object.key` in the custom package), so the name cannot + // tell a view a read-only package ships; the door refuses + // that save by design (it goes to the custom package) and + // the refused pick is taken back, as the panel's save is. + : isAdmin && isSavedViewId(savedViews, String(activeView.id)) ? handlePickSharedViewSummary : undefined, + summaryPickFields: declaredColumnFields( + (activeIsPersonal ? personalViewRow?.config.columns : activeView?.columns) as ListColumn[] | string[] | undefined, + ), }, }); diff --git a/ui/packages/app-shell/src/views/__tests__/columnSummaryWrite-35702.test.ts b/ui/packages/app-shell/src/views/__tests__/columnSummaryWrite-35702.test.ts index 7be9d9e1865..bf178461623 100644 --- a/ui/packages/app-shell/src/views/__tests__/columnSummaryWrite-35702.test.ts +++ b/ui/packages/app-shell/src/views/__tests__/columnSummaryWrite-35702.test.ts @@ -1,29 +1,35 @@ /** objectstack#35702 — the view's `columns` the footer menu saves. */ import { describe, it, expect } from 'vitest'; -import { columnsWithSummary } from '../columnSummaryWrite'; +import { columnsWithSummary, declaredColumnFields } from '../columnSummaryWrite'; describe('columnsWithSummary (objectstack#35702)', () => { it('sets the calculation on the view\'s own column, in the object form', () => { - expect(columnsWithSummary(['name', 'amount'], 'amount', 'sum', [])).toEqual([ + expect(columnsWithSummary(['name', 'amount'], 'amount', 'sum')).toEqual([ { field: 'name' }, { field: 'amount', summary: 'sum' }, ]); }); it('keeps the object form\'s field override and moves only the calculation', () => { - expect(columnsWithSummary([{ field: 'amount', summary: { type: 'sum', field: 'amount_base' } }], 'amount', 'avg', [])) + expect(columnsWithSummary([{ field: 'amount', summary: { type: 'sum', field: 'amount_base' } }], 'amount', 'avg')) .toEqual([{ field: 'amount', summary: { type: 'avg', field: 'amount_base' } }]); }); it('takes the calculation off for None', () => { - expect(columnsWithSummary([{ field: 'amount', label: 'Amount', summary: 'sum' }], 'amount', null, [])) + expect(columnsWithSummary([{ field: 'amount', label: 'Amount', summary: 'sum' }], 'amount', null)) .toEqual([{ field: 'amount', label: 'Amount' }]); }); - it('writes the drawn columns for a view that declares none, so it keeps drawing them', () => { - expect(columnsWithSummary(undefined, 'amount', 'max', ['name', 'amount'])).toEqual([ - { field: 'name' }, { field: 'amount', summary: 'max' }, - ]); + // L1 7048239634: the pick writes the calculation, never the reader's layout. + it('writes only the calculation: the view\'s columns stay, whatever the reader hid or added', () => { + // The view declares [a, b]; the reader hid b and added c for themselves. + expect(columnsWithSummary(['a', 'b'], 'a', 'sum')).toEqual([{ field: 'a', summary: 'sum' }, { field: 'b' }]); }); - it('appends a column the view does not list', () => { - expect(columnsWithSummary(['name'], 'amount', 'sum', ['name', 'amount'])).toEqual([ - { field: 'name' }, { field: 'amount', summary: 'sum' }, - ]); + it('saves nothing for a column the view does not declare', () => { + expect(columnsWithSummary(['a', 'b'], 'c', 'sum')).toBeNull(); + }); + it('saves nothing on a view that declares no columns', () => { + expect(columnsWithSummary(undefined, 'amount', 'max')).toBeNull(); + expect(columnsWithSummary([], 'amount', 'max')).toBeNull(); + }); + it('names the declared fields, in the view\'s order, for the menu offer', () => { + expect(declaredColumnFields(['b', { field: 'a', summary: 'sum' }])).toEqual(['b', 'a']); + expect(declaredColumnFields(undefined)).toEqual([]); }); }); diff --git a/ui/packages/app-shell/src/views/columnSummaryWrite.ts b/ui/packages/app-shell/src/views/columnSummaryWrite.ts index 77913985475..346e243065b 100644 --- a/ui/packages/app-shell/src/views/columnSummaryWrite.ts +++ b/ui/packages/app-shell/src/views/columnSummaryWrite.ts @@ -1,27 +1,36 @@ /** * objectstack#35702 — a view's `columns` with one column's footer calculation - * set (`null` = None), as the list's footer menu saves it on the view. The - * view's own columns are the base; a view that declares none takes the columns - * the grid draws, so the saved view keeps drawing them. A field the view does - * not list (a column the reader added) is appended. Every entry comes back in - * the object form, the one that carries `summary`. + * set (`null` = None), as the list's footer menu saves it on the view. Only the + * calculation moves: the view's own columns are kept, in their order, each in + * the object form (`columns` is all names or all objects, never a mix, and only + * the object form carries `summary`). A column the view does not declare — a column the reader + * added for themselves, or any column of a view that declares none — is not + * the view's to change (L1 7048239634): the answer is `null` and nothing is + * saved, which is why the menu is offered on the declared columns only + * ({@link declaredColumnFields}). */ import type { ListColumn } from '@object-ui/types'; import type { ColumnSummary } from '@objectstack/spec/ui'; +type AuthoredColumns = ReadonlyArray | undefined; + +/** The fields of the columns a view declares, in its order. */ +export function declaredColumnFields(authored: AuthoredColumns): string[] { + return (authored ?? []) + .map((entry) => (typeof entry === 'string' ? entry : entry?.field)) + .filter((field): field is string => typeof field === 'string' && field.length > 0); +} + export function columnsWithSummary( - authored: ReadonlyArray | undefined, + authored: AuthoredColumns, field: string, summary: ColumnSummary | null, - drawnFields: readonly string[], -): ListColumn[] { - const base: ReadonlyArray = authored && authored.length > 0 ? authored : drawnFields; - let found = false; - const columns = base.map((entry): ListColumn => { +): ListColumn[] | null { + if (!declaredColumnFields(authored).includes(field)) return null; + return (authored ?? []).map((entry): ListColumn => { const column: ListColumn = typeof entry === 'string' ? { field: entry } : { ...entry }; if (column.field !== field) return column; - found = true; if (summary === null) { delete column.summary; return column; @@ -32,6 +41,4 @@ export function columnsWithSummary( : summary; return column; }); - if (!found && summary !== null) columns.push({ field, summary }); - return columns; } diff --git a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx index d6dbd1bed37..f899aa275b0 100644 --- a/ui/packages/app-shell/src/views/objectViewListRenderer.tsx +++ b/ui/packages/app-shell/src/views/objectViewListRenderer.tsx @@ -170,8 +170,13 @@ export function useObjectViewListRenderer({ rename?: (label: string) => boolean | Promise; save?: () => void; reset?: () => void; - /** objectstack#35702 — save a footer calculation on the open view (wired only for a reader who may change it). */ - pickSummary?: (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => void; + /** + * objectstack#35702 — save a footer calculation on the open view (wired + * only for a reader who may change it); resolves whether it was saved. + */ + pickSummary?: (field: string, summary: ColumnSummary | null) => boolean | Promise; + /** objectstack#35702 — the columns the view declares: the only ones a pick may change. */ + summaryPickFields?: readonly string[]; }; }) { // objectstack#35551 — the host hands fresh closures every render; the list @@ -182,6 +187,8 @@ export function useObjectViewListRenderer({ const offersSave = !!listViewActions?.save; const offersReset = !!listViewActions?.reset; const offersSummaryPick = !!listViewActions?.pickSummary; + // Keyed on content, never the array's identity (a fresh one every render). + const summaryPickKey = (listViewActions?.summaryPickFields ?? []).join('\n'); // objectstack#27058 — below `sm` the title switcher is the phone's one // view control, so the list offers no layout switcher of its own there. const wideViewport = useViewTabsFit(); @@ -1048,8 +1055,9 @@ export function useObjectViewListRenderer({ onSaveView={offersSave ? () => listViewActionsRef.current?.save?.() : undefined} onResetView={offersReset ? () => listViewActionsRef.current?.reset?.() : undefined} onColumnSummaryPick={offersSummaryPick - ? (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => listViewActionsRef.current?.pickSummary?.(field, summary, drawnFields) + ? (field: string, summary: ColumnSummary | null) => listViewActionsRef.current?.pickSummary?.(field, summary) ?? false : undefined} + columnSummaryPickFields={offersSummaryPick ? summaryPickKey.split('\n').filter(Boolean) : undefined} className={className} onEdit={editHandler} // objectui#13089 — the view's Add button is the header New: @@ -1150,7 +1158,7 @@ export function useObjectViewListRenderer({ dataSource={ds} /> ); - }, [activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, recordOpen, openAsPage, rowOpensRecord, handleListRowsChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, previewDrafts, previewDataSource, unpublishedObjects]); + }, [activeView, activeViewDeclaresColumns, activeViewIsSaved, objectDef, objectName, refreshKey, createRecord, urlFilters, initialUfSelections, handleUserFilterSelectionsChange, writeListUrlState, listPage, user?.id, pageOffersCreate, listAddRecordOpensCreate, listIdentityKey, listPrefs.ready, listPrefs.preference, listPrefs.patchView, managedUsers, managedUserMarker, recordOpen, openAsPage, rowOpensRecord, handleListRowsChange, hasPhoneTitle, leadStore, wideViewport, handleListPersonalizationChange, workspaceTimeZone, viewPanelFilters, offersRename, offersSave, offersReset, offersSummaryPick, summaryPickKey, previewDrafts, previewDataSource, unpublishedObjects]); return { renderListView }; } diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index 84124548fbf..1c72257fbbb 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -365,13 +365,16 @@ the secondary text colour and the figure in the normal one (`Sum 1,234.00`). A grouped grid and the phone's card list draw no such row; the grid reports whether it drew one through `onResidentSummaryRowChange`. -A host that also passes `onColumnSummaryPick(field, summary, drawnFields)` +A host that also passes `onColumnSummaryPick(field, summary)` (wire it only for a reader who may change the view) turns each cell into a menu of the calculations the column's field type allows — `sum`/`avg` on numbers and amounts, `min`/`max` on numbers and dates (named Earliest and Latest on a date), the count family on any field, the current one ticked and -None last. The grid draws a pick at once; the host saves it as the column's -`summary` and hands the view back. +None last. `summaryPickFields` limits the menu to the columns the host can +save (the console passes the columns the view itself declares); the other cells +draw their figure only. The grid draws a pick at once; the host saves it as the +column's `summary` and hands the view back, or answers `false` (or a promise of +it) when it did not, and the grid takes the pick back. A cell counts as empty when it is `null`, `undefined`, `""` or an empty array, so an unset multi-select or lookup reads as empty rather than as a filled `[]`. diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 2ec5a609bf5..12518485d6d 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -262,10 +262,17 @@ export interface ObjectGridComponentProps extends ObjectGridExternalPaginationPr * [objectstack#35702] Wired only for a reader who may change the view: each * footer cell becomes the menu that picks the column's calculation (`null` = * None). The grid draws the pick at once; the host saves it on the view and - * hands it back as the column's `summary`. `drawnFields` are the field - * columns drawn, in order, for a view that declares no `columns` of its own. + * hands it back as the column's `summary`. A host that answers `false` + * (or a promise of it, or one that rejects) did not save it, and the grid + * takes the pick back. */ - onColumnSummaryPick?: (field: string, summary: ColumnSummaryType | null, drawnFields: readonly string[]) => void; + onColumnSummaryPick?: (field: string, summary: ColumnSummaryType | null) => void | boolean | Promise; + /** + * [objectstack#35702] The fields whose calculation `onColumnSummaryPick` can + * save (the columns the view itself declares); every other footer cell draws + * its figure with no menu. Absent ⇒ every field column is offered. + */ + summaryPickFields?: readonly string[]; /** [objectstack#35702] Whether the resident footer row is drawn (it carries the record count). */ onResidentSummaryRowChange?: (drawn: boolean) => void; /** @@ -776,6 +783,7 @@ export const ObjectGrid: React.FC = ({ residentSummaryRow, summaryRowLead, onColumnSummaryPick, + summaryPickFields, onResidentSummaryRowChange, onRowGroupsChange, }) => { @@ -1585,11 +1593,26 @@ export const ObjectGrid: React.FC = ({ }); // Keyed on the declared calculations' content, never the columns' identity. }, [declaredSummaryKey]); - const drawnFieldsRef = React.useRef([]); const pickColumnSummary = useCallback((field: string, summary: ColumnSummaryType | null) => { setSummaryPicks((picks) => ({ ...picks, [field]: summary })); - onColumnSummaryPick?.(field, summary, drawnFieldsRef.current); + // A pick the host did not save is taken back, unless a later pick on the + // same column has replaced it meanwhile. + const withdraw = () => setSummaryPicks((picks) => { + if (!(field in picks) || picks[field] !== summary) return picks; + const { [field]: _withdrawn, ...rest } = picks; + return rest; + }); + const saved = onColumnSummaryPick?.(field, summary); + if (saved === false) withdraw(); + else if (saved && typeof (saved as Promise).then === 'function') { + (saved as Promise).then((ok) => { if (ok === false) withdraw(); }, withdraw); + } }, [onColumnSummaryPick]); + const summaryPickKey = summaryPickFields ? summaryPickFields.join('\n') : undefined; + const pickableSummaryFields = useMemo( + () => (summaryPickKey === undefined ? undefined : new Set(summaryPickKey.split('\n').filter(Boolean))), + [summaryPickKey], + ); const { t: summaryT } = useSummaryTranslation(); // A host's resident row is drawn with no calculation too, and under a // reader who may change the view each cell is its picker. @@ -3018,7 +3041,6 @@ export const ObjectGrid: React.FC = ({ // objectstack#35548 — the column summaries as the table's own last row, each // under its column, led by the count of the records they summarise. A host // that draws them itself (`onColumnSummaryChange`) gets no row here. - const drawnFields: string[] = []; const summaryRow: ObjectGridDataTableSchema['summaryRow'] = (hasSummary || residentRowDrawn) && !onColumnSummaryChange ? { lead: summaryRowLead @@ -3028,7 +3050,6 @@ export const ObjectGrid: React.FC = ({ }), cells: residentRowDrawn ? Object.fromEntries(tableColumns.flatMap((col: { accessorKey: string }) => { - if (objectFields?.[col.accessorKey]) drawnFields.push(col.accessorKey); const field = col.accessorKey; const def = objectFields?.[field] as Parameters[0]; const summary = summaries.get(field); @@ -3040,7 +3061,9 @@ export const ObjectGrid: React.FC = ({ current={summaryTypes.get(field)} offered={offeredColumnSummaries(def)} temporal={isTemporalSummaryField(def)} - onPick={onColumnSummaryPick && def ? pickColumnSummary : undefined} + onPick={onColumnSummaryPick && def && (!pickableSummaryFields || pickableSummaryFields.has(field)) + ? pickColumnSummary + : undefined} t={summaryT} /> )]]; @@ -3048,7 +3071,6 @@ export const ObjectGrid: React.FC = ({ : Object.fromEntries(Array.from(summaries, ([key, summary]) => [key, summary.label])), } : undefined; - drawnFieldsRef.current = drawnFields; // objectstack#35685 — a row a select-first save redrew, in place of the row // the grid read, while that read is the one held. const patchedRowOf = (row: any): any => { diff --git a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx index 9985d9564ac..7e23c79a816 100644 --- a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx @@ -136,14 +136,14 @@ describe('the resident footer row (objectstack#35702)', () => { expect(within(menu).getByTestId('summary-option-none')).toHaveTextContent('None'); await user.click(within(menu).getByTestId('summary-option-sum')); - expect(onPick).toHaveBeenLastCalledWith('amount', 'sum', ['name', 'amount', 'due']); + expect(onPick).toHaveBeenLastCalledWith('amount', 'sum'); await waitFor(() => expect(screen.getByTestId('summary-picker-amount')).toHaveTextContent('Sum 350')); await user.click(screen.getByTestId('summary-picker-amount')); const again = await screen.findByTestId('summary-menu-amount'); expect(within(again).getByTestId('summary-option-sum').querySelector('svg')).toHaveClass('opacity-100'); await user.click(within(again).getByTestId('summary-option-none')); - expect(onPick).toHaveBeenLastCalledWith('amount', null, ['name', 'amount', 'due']); + expect(onPick).toHaveBeenLastCalledWith('amount', null); await waitFor(() => expect(screen.getByTestId('summary-picker-amount')).not.toHaveTextContent('Sum')); }); @@ -159,4 +159,46 @@ describe('the resident footer row (objectstack#35702)', () => { await user.click(within(menu).getByTestId('summary-option-max')); await waitFor(() => expect(screen.getByTestId('summary-picker-due')).toHaveTextContent(/^Latest /)); }); + + // L1 7048239634: the menu only where the host can save the pick, and a pick + // the host did not save is taken back. + it('offers the menu only on the columns the host can save; the others draw their figure only', async () => { + renderGrid({ residentSummaryRow: true, onColumnSummaryPick: vi.fn(), summaryPickFields: ['amount'] }, [ + { field: 'name', label: 'Name', summary: 'count_filled' }, + { field: 'amount', label: 'Amount' }, + { field: 'due', label: 'Due' }, + ]); + await screen.findByTestId('data-table-summary-row'); + expect(screen.getByTestId('summary-picker-amount')).toBeInTheDocument(); + expect(screen.queryByTestId('summary-picker-due')).toBeNull(); + expect(screen.queryByTestId('summary-picker-name')).toBeNull(); + expect(screen.getByTestId('data-table-summary-name')).toHaveTextContent('Filled 2'); + }); + + it.each([ + ['answers false', () => false], + ['resolves false', async () => false], + ['rejects', async () => { throw new Error('refused'); }], + ])('takes a pick back when the host %s', async (_label, answer) => { + const user = userEvent.setup(); + const onPick = vi.fn(answer); + renderGrid({ residentSummaryRow: true, onColumnSummaryPick: onPick }); + await screen.findByTestId('data-table-summary-row'); + await user.click(screen.getByTestId('summary-picker-amount')); + await user.click(within(await screen.findByTestId('summary-menu-amount')).getByTestId('summary-option-sum')); + expect(onPick).toHaveBeenLastCalledWith('amount', 'sum'); + await waitFor(() => expect(screen.getByTestId('summary-picker-amount')).not.toHaveTextContent('Sum')); + expect(screen.getByTestId('summary-picker-hint-amount')).toHaveTextContent('Calculate'); + }); + + it('keeps a pick the host saved', async () => { + const user = userEvent.setup(); + renderGrid({ residentSummaryRow: true, onColumnSummaryPick: vi.fn(async () => true) }); + await screen.findByTestId('data-table-summary-row'); + await user.click(screen.getByTestId('summary-picker-amount')); + await user.click(within(await screen.findByTestId('summary-menu-amount')).getByTestId('summary-option-sum')); + await waitFor(() => expect(screen.getByTestId('summary-picker-amount')).toHaveTextContent('Sum 350')); + await new Promise((r) => setTimeout(r, 20)); + expect(screen.getByTestId('summary-picker-amount')).toHaveTextContent('Sum 350'); + }); }); diff --git a/ui/packages/plugin-list/src/ListView.tsx b/ui/packages/plugin-list/src/ListView.tsx index 7bbfd15f78a..13a8f6705a5 100644 --- a/ui/packages/plugin-list/src/ListView.tsx +++ b/ui/packages/plugin-list/src/ListView.tsx @@ -391,11 +391,17 @@ export interface ListViewProps { * objectstack#35702 — the grid's footer calculation picked by the reader * (`null` = None). Wired only for a reader who may change the open view; * absent ⇒ the footer draws its figures and offers no menu. The host saves - * the pick as the column's `summary` on the view; `drawnFields` are the - * field columns drawn, for a view that declares no `columns`. A HOST prop, - * never a schema key. + * the pick as the column's `summary` on the view and resolves whether it + * did; on `false` the grid takes the pick back. A HOST prop, never a schema + * key. */ - onColumnSummaryPick?: (field: string, summary: ColumnSummary | null, drawnFields: readonly string[]) => void; + onColumnSummaryPick?: (field: string, summary: ColumnSummary | null) => void | boolean | Promise; + /** + * objectstack#35702 — the fields whose calculation the host can save (the + * columns the open view itself declares); the menu is offered on those + * only. Absent ⇒ every field column. A HOST prop, never a schema key. + */ + columnSummaryPickFields?: readonly string[]; /** * Callback when a row/item is clicked (overrides NavigationConfig). * @@ -2120,6 +2126,7 @@ export const ListView = React.forwardRef(({ onAddedFieldsChange, onColumnStateChange, onColumnSummaryPick, + columnSummaryPickFields, onRowClick, showViewSwitcher: showViewSwitcherProp, userFilterSelections, @@ -2154,6 +2161,8 @@ export const ListView = React.forwardRef(({ const { t } = useListViewTranslation(); // objectstack#35702 — the grid's footer row leads with the list's own count wording. const recordCountLead = React.useCallback((count: number) => t('list.recordCount', { count }), [t]); + // objectstack#35702 — keyed on content, never the host array's identity. + const columnSummaryPickKey = columnSummaryPickFields ? columnSummaryPickFields.join('\n') : undefined; const { fieldLabel: resolveFieldLabel, actionLabel: resolveActionLabel, objectLabel: resolveObjectLabel } = useListFieldLabel(); const { translateOptions } = useSafeFieldLabel(); // The audience's BCP-47 tag (tenant locale → UI language → `en`), used below @@ -5154,7 +5163,12 @@ export const ListView = React.forwardRef(({ residentSummaryRow: true, summaryRowLead: recordCountLead, onResidentSummaryRowChange: setGridDrawsCount, - ...(onColumnSummaryPick ? { onColumnSummaryPick } : {}), + ...(onColumnSummaryPick ? { + onColumnSummaryPick, + ...(columnSummaryPickKey !== undefined + ? { summaryPickFields: columnSummaryPickKey.split('\n').filter(Boolean) } + : {}), + } : {}), } : {}), ...(schema.wrapHeaders != null ? { wrapHeaders: schema.wrapHeaders } : {}), @@ -5725,7 +5739,7 @@ export const ListView = React.forwardRef(({ // asynchronously (`/me/permissions`) and `objectDef` loads into state, so a // grid schema built before either resolved must be rebuilt when they do — // otherwise `editable` keeps the pre-verdict answer for the session. - }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged, compact, cappedWindow, onColumnSummaryPick, recordCountLead]); + }, [currentView, schema, authoredFilter, serverSort, searchFieldsSent, effectiveFields, hasAuthoredColumns, groupingConfig, rowColorConfig, navigation.handleClick, hostRoutesRowClicks, density.mode, galleryCardSize, inlineEditOffered, objectDef, selfQueryFilter, ganttSearchTerm, gridOwnsGroupedFetch, calendarWindowed, handleCalendarVisibleRange, kanbanLanesPaged, compact, cappedWindow, onColumnSummaryPick, columnSummaryPickKey, recordCountLead]); // The count the toolbar shows: a record-mode amount's code condition is // part of its amount row (objectstack#27188), not a filter of its own, and a From ad2d94c5ab999979d4c03dc29faf966f39f50a2d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 19:46:58 +0000 Subject: [PATCH 6/7] fix(ui): a pickable footer figure follows its column's alignment L1 7049007771 on #35919. The picker's trigger is a flex box, which the cell's `text-align` does not move, so a right-aligned amount's figure was drawn at the column's left edge. It is now justified from the column's `align`, and its menu opens from the same edge. The changeset says what a shared view's draft save does to the drawn pick until it is published (#35932). Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgVb7fsaFeMStucvNWA --- .changeset/35702-footer-calculation-row.md | 2 +- content/docs/frontend/plugins/plugin-grid.mdx | 4 ++-- ui/packages/plugin-grid/src/ObjectGrid.tsx | 1 + .../footerCalculationPicker-35702.test.tsx | 14 ++++++++++++++ .../plugin-grid/src/objectGridSummaryPicker.tsx | 13 ++++++++++--- 5 files changed, 28 insertions(+), 6 deletions(-) diff --git a/.changeset/35702-footer-calculation-row.md b/.changeset/35702-footer-calculation-row.md index 305a120e647..4ea0f6aaef9 100644 --- a/.changeset/35702-footer-calculation-row.md +++ b/.changeset/35702-footer-calculation-row.md @@ -12,6 +12,6 @@ Metadata-protocol: none A list's table view now always ends in one footer row, aligned with the columns and held at the bottom of the table: the record count in its first cell, and under each column its calculation, if any, written as the calculation's name in the secondary text colour and the figure in the normal one, with a space and no colon (`Sum ¥1,234,500`). A `min` / `max` over a date reads Earliest / Latest. The list's own "N records" line at the foot of the page is gone from a table that draws this row; the data-cap notice stays there. A grouped table, the phone's card list and every other view type are unchanged. -A reader who may change the open view clicks a cell to pick the column's calculation from one menu that lists what the field type allows (sum and average on numbers and amounts, earliest and latest on dates, the counts on any field), the current one ticked and None last. The pick shows at once. The console saves it as the column's `summary` on the view, and nothing else of the reader's layout: a personal view at once; a shared view the console saved, for a reader who may edit it, as a draft through the view settings' own save, which other readers see once it is published. The menu is offered on the columns the view itself declares; a column the reader added for themselves and a view that declares no columns draw the figures with no menu. A pick that is not saved is taken back, with the refusal said (a view a read-only package ships is refused this way: its changes go to the package's customization). A reader who may not change the view sees the figures and no menu. +A reader who may change the open view clicks a cell to pick the column's calculation from one menu that lists what the field type allows (sum and average on numbers and amounts, earliest and latest on dates, the counts on any field), the current one ticked and None last. The console saves it as the column's `summary` on the view, and nothing else of the reader's layout. On a personal view it is saved at once and stays drawn. On a shared view the console saved, a reader who may edit it saves it as a draft through the view settings' own save: the draft save reloads the list, which then draws the published view again, so the pick shows for a moment and comes back once the draft is published, for every reader (#35932). The menu is offered on the columns the view itself declares; a column the reader added for themselves and a view that declares no columns draw the figures with no menu. A pick that is not saved is taken back, with the refusal said (a view a read-only package ships is refused this way: its changes go to the package's customization). A reader who may not change the view sees the figures and no menu. New host props, all optional and never authored metadata: `ObjectGrid` takes `residentSummaryRow`, `onColumnSummaryPick(field, summary)` (answer `false` to have the pick taken back), `summaryPickFields` and `onResidentSummaryRowChange(drawn)`; `ListView` takes `onColumnSummaryPick` and `columnSummaryPickFields`. `ColumnSummaryResult` gains `name` and `text`, the two halves of its `label`. `@object-ui/i18n` adds the `grid.summary` keys `earliest`, `latest`, `pageName`, `calculate`, `none`, `menuPercentEmpty` and `menuPercentFilled` in every pack. diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index c6909fe381a..86cac4475b8 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -407,8 +407,8 @@ current one ticked and None last; the grid draws the pick at once and the host saves it as the column's `summary` (an answer of `false` takes the pick back). `summaryPickFields` limits the menu to the columns the host can save. The console's list offers it on the columns the view declares and saves only the -calculation: on a personal view at once, and on a shared view as a draft that -others see once it is published. +calculation: on a personal view at once, and on a shared view as a draft, which +the list draws, for the editor and everyone else, once it is published. ### Keyboard navigation diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 12518485d6d..f19492a5c5b 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -3061,6 +3061,7 @@ export const ObjectGrid: React.FC = ({ current={summaryTypes.get(field)} offered={offeredColumnSummaries(def)} temporal={isTemporalSummaryField(def)} + align={(col as { align?: 'left' | 'center' | 'right' }).align} onPick={onColumnSummaryPick && def && (!pickableSummaryFields || pickableSummaryFields.has(field)) ? pickColumnSummary : undefined} diff --git a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx index 7e23c79a816..c2b5f996b95 100644 --- a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx @@ -201,4 +201,18 @@ describe('the resident footer row (objectstack#35702)', () => { await new Promise((r) => setTimeout(r, 20)); expect(screen.getByTestId('summary-picker-amount')).toHaveTextContent('Sum 350'); }); + + // L1 7049007771: the trigger is a flex box, which the cell's text-align does + // not move; a right-aligned amount's figure ends under the amounts. + it('justifies the cell from its column\'s alignment', async () => { + renderGrid({ residentSummaryRow: true, onColumnSummaryPick: vi.fn() }, [ + { field: 'name', label: 'Name' }, + { field: 'amount', label: 'Amount', align: 'right', summary: 'sum' }, + { field: 'due', label: 'Due', align: 'center' }, + ]); + await screen.findByTestId('data-table-summary-row'); + expect(screen.getByTestId('summary-picker-amount')).toHaveClass('justify-end'); + expect(screen.getByTestId('summary-picker-due')).toHaveClass('justify-center'); + expect(screen.getByTestId('summary-picker-name')).toHaveClass('justify-start'); + }); }); diff --git a/ui/packages/plugin-grid/src/objectGridSummaryPicker.tsx b/ui/packages/plugin-grid/src/objectGridSummaryPicker.tsx index 2c109d8b6cd..7913feda2e1 100644 --- a/ui/packages/plugin-grid/src/objectGridSummaryPicker.tsx +++ b/ui/packages/plugin-grid/src/objectGridSummaryPicker.tsx @@ -36,6 +36,12 @@ export interface SummaryCellPickerProps { offered: ReadonlyArray; /** The column's field is a date or time (its min / max read Earliest / Latest). */ temporal: boolean; + /** + * The column's alignment, as its cells take it. The trigger is a flex box, + * which the cell's `text-align` does not move, so the figure is justified + * from this (a right-aligned amount's sum ends under the amounts). + */ + align?: 'left' | 'center' | 'right'; /** Wired only for a reader who may change the view. `null` = None. */ onPick?: (field: string, summary: ColumnSummaryType | null) => void; t: SummaryTranslate; @@ -50,7 +56,7 @@ function Figure({ figure }: { figure: SummaryCellFigure }) { ); } -export function SummaryCellPicker({ field, figure, current, offered, temporal, onPick, t }: SummaryCellPickerProps) { +export function SummaryCellPicker({ field, figure, current, offered, temporal, align, onPick, t }: SummaryCellPickerProps) { if (!onPick) return figure ?
: null; const active = current && current !== 'none' ? current : undefined; return ( @@ -61,7 +67,8 @@ export function SummaryCellPicker({ field, figure, current, offered, temporal, o data-testid={`summary-picker-${field}`} aria-label={figure ? figure.label : t('grid.summary.calculate')} className={cn( - 'group/summary flex h-8 w-full min-w-0 items-center gap-1 rounded-sm [text-align:inherit] [justify-content:inherit]', + 'group/summary flex h-8 w-full min-w-0 items-center gap-1 rounded-sm [text-align:inherit]', + align === 'right' ? 'justify-end' : align === 'center' ? 'justify-center' : 'justify-start', 'hover:bg-muted/60 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring', )} > @@ -77,7 +84,7 @@ export function SummaryCellPicker({ field, figure, current, offered, temporal, o )} - + {offered.map((summary) => ( Date: Fri, 20 Nov 2026 19:55:57 +0000 Subject: [PATCH 7/7] fix(ui): a toggle column's footer offers counts only; say what a second shared pick does L2 7049212622 on #35919. The spec's boolean class is `boolean` and `toggle`, so a toggle column no longer offers Sum, Average, Min or Max. The changeset says that, until #35932, a second pick on a shared view before Publish replaces the first in the draft. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01L6bhgVb7fsaFeMStucvNWA --- .changeset/35702-footer-calculation-row.md | 2 +- .../src/__tests__/footerCalculationPicker-35702.test.tsx | 5 +++-- ui/packages/plugin-grid/src/useColumnSummary.ts | 4 +++- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/.changeset/35702-footer-calculation-row.md b/.changeset/35702-footer-calculation-row.md index 4ea0f6aaef9..8413c4383a3 100644 --- a/.changeset/35702-footer-calculation-row.md +++ b/.changeset/35702-footer-calculation-row.md @@ -12,6 +12,6 @@ Metadata-protocol: none A list's table view now always ends in one footer row, aligned with the columns and held at the bottom of the table: the record count in its first cell, and under each column its calculation, if any, written as the calculation's name in the secondary text colour and the figure in the normal one, with a space and no colon (`Sum ¥1,234,500`). A `min` / `max` over a date reads Earliest / Latest. The list's own "N records" line at the foot of the page is gone from a table that draws this row; the data-cap notice stays there. A grouped table, the phone's card list and every other view type are unchanged. -A reader who may change the open view clicks a cell to pick the column's calculation from one menu that lists what the field type allows (sum and average on numbers and amounts, earliest and latest on dates, the counts on any field), the current one ticked and None last. The console saves it as the column's `summary` on the view, and nothing else of the reader's layout. On a personal view it is saved at once and stays drawn. On a shared view the console saved, a reader who may edit it saves it as a draft through the view settings' own save: the draft save reloads the list, which then draws the published view again, so the pick shows for a moment and comes back once the draft is published, for every reader (#35932). The menu is offered on the columns the view itself declares; a column the reader added for themselves and a view that declares no columns draw the figures with no menu. A pick that is not saved is taken back, with the refusal said (a view a read-only package ships is refused this way: its changes go to the package's customization). A reader who may not change the view sees the figures and no menu. +A reader who may change the open view clicks a cell to pick the column's calculation from one menu that lists what the field type allows (sum and average on numbers and amounts, earliest and latest on dates, the counts on any field), the current one ticked and None last. The console saves it as the column's `summary` on the view, and nothing else of the reader's layout. On a personal view it is saved at once and stays drawn. On a shared view the console saved, a reader who may edit it saves it as a draft through the view settings' own save: the draft save reloads the list, which then draws the published view again, so the pick shows for a moment and is drawn again, for every reader, once the draft is published. Until #35932, each pick's draft is built on the published view, so a second pick before Publish replaces the first in the draft: only the latest pick is published. The menu is offered on the columns the view itself declares; a column the reader added for themselves and a view that declares no columns draw the figures with no menu. A pick that is not saved is taken back, with the refusal said (a view a read-only package ships is refused this way: its changes go to the package's customization). A reader who may not change the view sees the figures and no menu. New host props, all optional and never authored metadata: `ObjectGrid` takes `residentSummaryRow`, `onColumnSummaryPick(field, summary)` (answer `false` to have the pick taken back), `summaryPickFields` and `onResidentSummaryRowChange(drawn)`; `ListView` takes `onColumnSummaryPick` and `columnSummaryPickFields`. `ColumnSummaryResult` gains `name` and `text`, the two halves of its `label`. `@object-ui/i18n` adds the `grid.summary` keys `earliest`, `latest`, `pageName`, `calculate`, `none`, `menuPercentEmpty` and `menuPercentFilled` in every pack. diff --git a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx index c2b5f996b95..dd2286c4843 100644 --- a/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/footerCalculationPicker-35702.test.tsx @@ -53,8 +53,9 @@ describe('offeredColumnSummaries (objectstack#35702)', () => { expect(isTemporalSummaryField({ type: 'date' })).toBe(true); expect(isTemporalSummaryField({ type: 'number' })).toBe(false); }); - it('offers a boolean no sum, average or extremes', () => { - expect(offeredColumnSummaries({ type: 'boolean' }).filter((s) => ['sum', 'avg', 'min', 'max'].includes(s))).toEqual([]); + it.each(['boolean', 'toggle'])('offers a %s no sum, average or extremes', (type) => { + expect(offeredColumnSummaries({ type }).filter((s) => ['sum', 'avg', 'min', 'max'].includes(s))).toEqual([]); + expect(offeredColumnSummaries({ type })).toContain('count_filled'); }); it('offers an unknown field the counts it can draw, never count_unique', () => { expect(offeredColumnSummaries(undefined)).toEqual(['count_filled', 'count_empty', 'percent_filled', 'percent_empty']); diff --git a/ui/packages/plugin-grid/src/useColumnSummary.ts b/ui/packages/plugin-grid/src/useColumnSummary.ts index b0b062dccca..029ba95ec79 100644 --- a/ui/packages/plugin-grid/src/useColumnSummary.ts +++ b/ui/packages/plugin-grid/src/useColumnSummary.ts @@ -161,6 +161,8 @@ export const useSummaryTranslation = createSafeTranslation( * the footer withholds) likewise. */ const MENU_AGGREGATES: ReadonlyArray = ['sum', 'avg', 'min', 'max']; +/** The spec's boolean class (`BOOLEAN_AGGREGATE_FIELD_TYPES`): `toggle` is a boolean too. */ +const BOOLEAN_FIELD_TYPES: ReadonlySet = new Set(['boolean', 'toggle']); const MENU_COUNTS: ReadonlyArray = [ 'count_unique', 'count_filled', 'count_empty', 'percent_filled', 'percent_empty', ]; @@ -168,7 +170,7 @@ export function offeredColumnSummaries( field: ({ type?: string } & NonNullable[0]>) | undefined, ): ColumnSummaryType[] { const type = field?.type; - const numeric = !!type && type !== 'boolean' && !recordCurrencyField(field); + const numeric = !!type && !BOOLEAN_FIELD_TYPES.has(type) && !recordCurrencyField(field); return [ ...(numeric ? MENU_AGGREGATES.filter((m) => isAggregateCompatibleWithFieldType(m, type!)) : []), ...MENU_COUNTS.filter((m) => m !== 'count_unique' || (!!type && isAggregateCompatibleWithFieldType('count_distinct', type))),