diff --git a/.changeset/36290-field-change-history-card.md b/.changeset/36290-field-change-history-card.md new file mode 100644 index 00000000000..eeadc299827 --- /dev/null +++ b/.changeset/36290-field-change-history-card.md @@ -0,0 +1,23 @@ +--- +'@object-ui/plugin-detail': patch +'@object-ui/plugin-grid': patch +'@object-ui/components': patch +'@object-ui/types': patch +'@object-ui/i18n': patch +'@objectstack/spec': patch +--- + +feat(record-page): one field's change history, opened in place from the field or from a list cell's context menu + +Clause-②: yes (widening) — three new `detail.*` language-pack keys in every locale `@object-ui/i18n` ships (`fieldHistory`, `fieldHistoryNone`, `fieldHistoryNoneRecent`); new exports from `@object-ui/plugin-detail` (`FieldHistoryButton`, `FieldHistoryCard`, `FieldHistoryPopover`, `useFieldHistory`, `useFieldHistoryOffered`, `fieldHistoryOffered`, the constants `FIELD_HISTORY_PAGE_SIZE`, `FIELD_HISTORY_SCAN_BATCH` and `FIELD_HISTORY_SCAN_BATCHES_PER_LOAD`, and their types); an optional `column` member on the context `data-table` hands a host's `renderRowContextMenu`; `FieldChangeItem` draws no label for `label: ''`; nothing is removed or renamed +Metadata-protocol: none + +A reader can now see one field's past changes on one record without reading the whole activity stream. + +- On the record page, each field of the object has a history button beside its value, shown on hover and focus like the copy button. In a list, right-clicking a cell of a field the object declares adds 「Change history」 to the row's menu. Both open the same small card in place. Neither is offered on a field whose old → new values are not recorded (`fieldHistory: false` on the field, `enable.fieldHistory: false` on the object, a credential field, or a media or JSON-like type that does not opt in), judged by the same `resolveFieldHistory` the audit writer keeps values by. +- The card lists only that field's changes: who, when, and old → new in the reader's words (an option by its label, an empty side as the pack's word for empty), newest first, ten at a time with 「Load more」. +- A field never changed reads 「No changes recorded」 with who created the record and when. +- The changes are the record's activity rows the server already serves, narrowed to the reader: a change of a field the reader may not read is never sent. A field the reader may not read offers no entry point at all. The full audit log is not read. +- The rows are read by record, newest first, fifty at a time, keeping those that changed the field; a query naming the change columns is refused for a reader withheld any field of the object, so the field is never part of the query. Opening the card reads at most four batches, and each 「Load more」 at most four more; when they hold no change of the field and older rows remain, the card reads 「No changes in the recent activity」 and offers 「Load more」 to read on. + +`@objectstack/spec`: the authoring hint for the mistyped field key `tracked` now names what turns one field's change history on or off today (`fieldHistory: false`, `true` for a media or JSON field, `enable.fieldHistory: false` on the object), where it named `trackHistory: true`, which changes nothing for most field types. Wording only; `tracked` stays rejected. diff --git a/content/docs/frontend/plugins/plugin-detail.mdx b/content/docs/frontend/plugins/plugin-detail.mdx index 50d68a5e397..603b69e00bb 100644 --- a/content/docs/frontend/plugins/plugin-detail.mdx +++ b/content/docs/frontend/plugins/plugin-detail.mdx @@ -227,6 +227,39 @@ draws its own field editor reuses the write by rendering shortcuts (its dialogs only), and `ref.current(draft)` saves. The default `face` is `"bar"`. +## A field's change history + +Each field of the object on the record page has a history button beside its +value, shown on hover and on keyboard focus like the copy button. In a list, +right-clicking a cell of a field the object declares adds **Change history** +to the row's menu. Both open the same small card in place +(`FieldHistoryButton`, `FieldHistoryPopover`, both drawing `FieldHistoryCard`): + +- only that field's changes on that record: who, when, and old → new in the + reader's words (an option by its label, an empty side as the word for empty), + newest first, ten at a time with **Load more**; +- for a field never changed, **No changes recorded** with who created the + record and when. + +The card reads the record's activity rows (`sys_activity`), the rows the +activity stream draws, and keeps those that changed the field. The server +serves each row's changes narrowed to the reader, so a value the reader may not +read never reaches the browser, and a field the reader may not read +(`checkField(object, field, 'read')`) offers no history at all. Nor does a +field whose old → new values are not recorded (`resolveFieldHistory` from +`@objectstack/spec/data`: `fieldHistory: false` on the field, +`enable.fieldHistory: false` on the object, a credential field, or a media or +JSON-like type that does not opt in with `fieldHistory: true`), and nor do the +platform's own record columns (`id`, `created_at`, …). + +The rows are read by record, fifty at a time: a query naming a change column +is refused for a reader withheld any field of the object, so the field is never +part of the query. Opening the card reads at most four batches +(`FIELD_HISTORY_SCAN_BATCHES_PER_LOAD`), and each **Load more** at most four +more. When they hold no change of the field and older rows remain, the card +says **No changes in the recent activity** and offers **Load more** to read on; +it says **No changes recorded** only once every row has been read. + ## The record's comment panel On the desktop console, a record's comments live in a panel of their own, diff --git a/content/docs/frontend/plugins/plugin-grid.mdx b/content/docs/frontend/plugins/plugin-grid.mdx index d7434c5a67d..7da2aa31002 100644 --- a/content/docs/frontend/plugins/plugin-grid.mdx +++ b/content/docs/frontend/plugins/plugin-grid.mdx @@ -332,6 +332,18 @@ authored `navigation: { mode: 'none' }` or `navigation.preventNavigation: true` (whatever its mode, objectstack#33549) and for an object whose data API serves no single-record read (objectstack#33317). +### A cell's change history + +Right-clicking a cell of a field the object declares adds **Change history** +to the row's context menu, when the grid's data source can read activity +(`find`), the field's changes are recorded with their values +(`resolveFieldHistory` from `@objectstack/spec/data`) and the reader may read +the field. Choosing it opens +`@object-ui/plugin-detail`'s `FieldHistoryPopover` at that point: that +record's changes of that field, newest first, ten at a time, or **No changes +recorded** with who created the record. `data-table` names the cell's column to +the host's `renderRowContextMenu` as `context.column`. + ### Inline Editing Enable inline cell editing for quick data updates: diff --git a/packages/spec/src/data/field.test.ts b/packages/spec/src/data/field.test.ts index 7437396da75..0ea0579aca3 100644 --- a/packages/spec/src/data/field.test.ts +++ b/packages/spec/src/data/field.test.ts @@ -188,6 +188,26 @@ describe('FieldSchema — field-level `currency` key guidance, naming `currencyC }); }); +// objectstack#36615 — the `tracked` answer names the switch a field's change +// history has today (`fieldHistory`), not `trackHistory: true`, which turns +// nothing on for most field types since field history became on by default. +describe('FieldSchema — field-level `tracked` key guidance, naming `fieldHistory`', () => { + const FIELD = { name: 'notes', label: 'Notes', type: 'textarea' } as const; + + it('`tracked` stays rejected and names `fieldHistory`, whose off form really parses', () => { + const m = unrecognizedKeyMessage({ ...FIELD, tracked: true }); + expect(m).toContain('`tracked` is not a field key'); + expect(m).toContain('fieldHistory: false'); + expect(m).not.toContain('trackHistory: true'); + expect(FieldSchema.safeParse({ ...FIELD, fieldHistory: false }).success).toBe(true); + }); + + it('a sibling unknown key does NOT get the field-history prescription (anti-vacuity)', () => { + const m = unrecognizedKeyMessage({ ...FIELD, totallyBogusKey: true }); + expect(m).not.toContain('fieldHistory'); + }); +}); + describe('FieldSchema', () => { describe('Basic Field Properties', () => { it('should accept valid field with minimal properties', () => { diff --git a/packages/spec/src/data/field.zod.ts b/packages/spec/src/data/field.zod.ts index 8a752d1f9a2..8a0abdb9ccc 100644 --- a/packages/spec/src/data/field.zod.ts +++ b/packages/spec/src/data/field.zod.ts @@ -1685,7 +1685,10 @@ export const FieldSchema = lazySchema(() => { // CASE-SENSITIVELY on the authored spelling, so a row per spelling is the // only way this channel can cover a family, and `not_null` was the spelling // it would have missed. - tracked: '`tracked` is not a field key — per-field timeline tracking is `trackHistory: true` (ADR-0052 §5b).', + tracked: + '`tracked` is not a field key — a field\'s old → new values show on the record activity timeline ' + + 'by default. Write `fieldHistory: false` to turn them off for this field (`true` opts a media or ' + + 'structured-JSON field in), or `enable.fieldHistory: false` on the object to turn them off for every field.', // [ADR-0158 L3] The natural spellings of a quantity's unit on the field // itself, answered in prose because the targets are NESTED keys of // `unitConfig` — the form the `currency` answer above takes. None of them diff --git a/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx b/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx index e88ca831f23..111b2d1ad59 100644 --- a/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx +++ b/ui/packages/components/src/renderers/complex/__tests__/data-table-row-context-menu-28434.test.tsx @@ -129,7 +129,27 @@ describe('objectstack#28434 · a host renderer decides alone', () => { // The host's items only — the table's own are not mixed in. expect(itemIds(menu)).toEqual(['host-item']); expect(menu).toHaveTextContent('Host item for r2'); - expect(renderRowContextMenu).toHaveBeenCalledWith(expect.objectContaining({ id: 'r2' }), { selected: false }); + // objectstack#36290 — the context also names the data cell's column. + expect(renderRowContextMenu).toHaveBeenCalledWith(expect.objectContaining({ id: 'r2' }), { selected: false, column: 'name' }); + }); + + it('objectstack#36290 · names the column of the data cell it opened on, and none off a data cell', async () => { + const renderRowContextMenu = vi.fn(() => Host item); + renderTable({ + ...RELATED_LIST_SCHEMA, + columns: [{ header: 'Name', accessorKey: 'name' }, { header: 'Code', accessorKey: 'code' }], + data: ROWS.map((row) => ({ ...row, code: `C-${row.id}` })), + renderRowContextMenu, + }); + act(() => { rightClick(cellOf('C-r1')); }); + await screen.findByTestId('row-context-menu'); + expect(renderRowContextMenu).toHaveBeenLastCalledWith(expect.objectContaining({ id: 'r1' }), { selected: false, column: 'code' }); + await userEvent.keyboard('{Escape}'); + await waitFor(() => expect(contextMenu()).toBeNull()); + // The row's own "⋮" cell is not a data cell: no column. + act(() => { rightClick(within(rowOf('Open contract')).getByTestId('data-table-row-actions').closest('td') as HTMLElement); }); + await screen.findByTestId('row-context-menu'); + expect(renderRowContextMenu).toHaveBeenLastCalledWith(expect.objectContaining({ id: 'r1' }), { selected: false }); }); it('a host answering null keeps the browser\'s menu', () => { diff --git a/ui/packages/components/src/renderers/complex/data-table.tsx b/ui/packages/components/src/renderers/complex/data-table.tsx index d14ee64676c..ce628475adf 100644 --- a/ui/packages/components/src/renderers/complex/data-table.tsx +++ b/ui/packages/components/src/renderers/complex/data-table.tsx @@ -2232,7 +2232,7 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // objectstack#28434 — the row context menu: which row it is open on, where, // and the element focus goes back to when it closes (the focused cell for // the keyboard, the cell under the pointer for a right-click). - const [rowContextMenu, setRowContextMenu] = useState<{ row: any; selected: boolean; x: number; y: number } | null>(null); + const [rowContextMenu, setRowContextMenu] = useState<{ row: any; selected: boolean; column?: string; x: number; y: number } | null>(null); const rowContextMenuReturnFocusRef = useRef(null); // The last pointer that pressed a row: a touch long-press raises // `contextmenu` too, and touch keeps the row's "⋮" instead. @@ -4426,9 +4426,9 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { * selection of two or more — a selection is a bulk act, and this table holds * no bulk actions to offer it — and never on a row with nothing to offer. */ - const rowContextMenuItems = (row: any, selected: boolean): React.ReactNode => { + const rowContextMenuItems = (row: any, selected: boolean, column?: string): React.ReactNode => { if (schema.renderRowContextMenu) { - const items = schema.renderRowContextMenu(row, { selected }); + const items = schema.renderRowContextMenu(row, column !== undefined ? { selected, column } : { selected }); return items === false || items === undefined ? null : items; } if (!rowActions || rowActionsColumnIsEditOnly) return null; @@ -4472,7 +4472,10 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { if (pointerType === 'touch') return; } if (keepsBrowserContextMenu(target, rowEl)) return; - const items = rowContextMenuItems(row, selected); + // The data cell the menu opened on (objectstack#36290): its column's + // accessor, for the host's cell-level items. + const column = target.closest('[data-cell-column]')?.getAttribute('data-cell-column') ?? undefined; + const items = rowContextMenuItems(row, selected, column); if (items == null) return; e.preventDefault(); const pointer = fromKeyboard ? null : (e as React.MouseEvent); @@ -4491,11 +4494,11 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { const focusable = fromKeyboard ? target : target.closest('[tabindex]'); rowContextMenuReturnFocusRef.current = focusable && rowEl.contains(focusable) ? focusable : null; rowContextMenuClosedOutsideRef.current = false; - setRowContextMenu({ row, selected, x, y }); + setRowContextMenu({ row, selected, column, x, y }); }; // The open menu's items, re-asked each render so they follow the row. const openRowContextMenuItems = rowContextMenu - ? rowContextMenuItems(rowContextMenu.row, rowContextMenu.selected) + ? rowContextMenuItems(rowContextMenu.row, rowContextMenu.selected, rowContextMenu.column) : null; const showToolbar = searchEnabled || exportable || (showSelectionCount && selectable && selectedRowIds.size > 0) || hasPendingChanges; @@ -5431,6 +5434,8 @@ const DataTableRenderer = ({ schema }: { schema: DataTableSchema }) => { // focus tracking exist only in the first case. tabIndex={keyboardNavigation ? (rowIndex === rovingRowIndex && colIndex === rovingColIndex && !isSelectedCell ? 0 : -1) : 0} data-grid-cell={keyboardNavigation ? `${rowIndex}:${colIndex}` : undefined} + // objectstack#36290 — which column a context menu opened on. + data-cell-column={col.accessorKey} onFocus={keyboardNavigation ? () => rove(rowIndex, colIndex) : undefined} aria-invalid={cellError !== undefined || undefined} // objectstack#28434 — a cell in edit mode keeps the diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 0679e2e1ccf..efed7903528 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1707,6 +1707,9 @@ const ar = { fieldChangeEmpty: "فارغ", fieldChangeExpand: "عرض الكل", fieldChangeCollapse: "عرض أقل", + fieldHistory: "سجل التغييرات", + fieldHistoryNone: "لا توجد تغييرات مسجلة", + fieldHistoryNoneRecent: "لا توجد تغييرات في النشاط الأخير", replyCount: "{{count}} رد", replyCount_zero: "{{count}} رد", replyCount_one: "{{count}} رد", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 910717801c8..ca379477090 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1526,6 +1526,9 @@ const de = { fieldChangeEmpty: "Leer", fieldChangeExpand: "Alles anzeigen", fieldChangeCollapse: "Weniger anzeigen", + fieldHistory: "Änderungsverlauf", + fieldHistoryNone: "Keine Änderungen erfasst", + fieldHistoryNoneRecent: "Keine Änderungen in den letzten Aktivitäten", replyCount: "{{count}} Antwort", replyCount_one: "{{count}} Antwort", replyCount_other: "{{count}} Antworten", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index ccc2bfd0238..bc07718d562 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2068,6 +2068,11 @@ const en = { fieldChangeEmpty: 'Empty', fieldChangeExpand: 'Show all', fieldChangeCollapse: 'Show less', + // objectstack#36290 — one field's change-history card: its entry point's + // name and what it says for a field never changed. + fieldHistory: 'Change history', + fieldHistoryNone: 'No changes recorded', + fieldHistoryNoneRecent: 'No changes in the recent activity', // Replies replyCount: '{{count}} reply', replyCount_one: '{{count}} reply', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 6aee49a0be6..58798ab35be 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1571,6 +1571,9 @@ const es = { fieldChangeEmpty: "Vacío", fieldChangeExpand: "Ver todo", fieldChangeCollapse: "Ver menos", + fieldHistory: "Historial de cambios", + fieldHistoryNone: "No hay cambios registrados", + fieldHistoryNoneRecent: "No hay cambios en la actividad reciente", replyCount: "{{count}} respuesta", replyCount_one: "{{count}} respuesta", replyCount_many: "{{count}} de respuestas", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 39b45f2e033..bc1bbe22337 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1575,6 +1575,9 @@ const fr = { fieldChangeEmpty: "Vide", fieldChangeExpand: "Tout afficher", fieldChangeCollapse: "Afficher moins", + fieldHistory: "Historique des modifications", + fieldHistoryNone: "Aucune modification enregistrée", + fieldHistoryNoneRecent: "Aucune modification dans l'activité récente", replyCount: "{{count}} réponse", replyCount_one: "{{count}} réponse", replyCount_many: "{{count}} de réponses", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 3fe7cbbe72d..a3e7cb34f6a 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1610,6 +1610,9 @@ const ja = { fieldChangeEmpty: "空", fieldChangeExpand: "すべて表示", fieldChangeCollapse: "折りたたむ", + fieldHistory: "変更履歴", + fieldHistoryNone: "変更の記録はありません", + fieldHistoryNoneRecent: "最近のアクティビティに変更はありません", replyCount: "{{count}} 件の返信", replyCount_one: "{{count}} 件の返信", replyCount_other: "{{count}} 件の返信", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 18a7a4d3436..568c54c0e49 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1526,6 +1526,9 @@ const ko = { fieldChangeEmpty: "비어 있음", fieldChangeExpand: "모두 보기", fieldChangeCollapse: "접기", + fieldHistory: "변경 기록", + fieldHistoryNone: "변경 기록이 없습니다", + fieldHistoryNoneRecent: "최근 활동에 변경 내역이 없습니다", replyCount: "답글 {{count}}개", replyCount_one: "답글 {{count}}개", replyCount_other: "답글 {{count}}개", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 9ba1bffd5a6..2bb4db5c7f6 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1575,6 +1575,9 @@ const pt = { fieldChangeEmpty: "Vazio", fieldChangeExpand: "Ver tudo", fieldChangeCollapse: "Ver menos", + fieldHistory: "Histórico de alterações", + fieldHistoryNone: "Nenhuma alteração registrada", + fieldHistoryNoneRecent: "Nenhuma alteração na atividade recente", replyCount: "{{count}} resposta", replyCount_one: "{{count}} resposta", replyCount_many: "{{count}} de respostas", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ee2a1dd4590..6d683bef7ec 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1722,6 +1722,9 @@ const ru = { fieldChangeEmpty: "Пусто", fieldChangeExpand: "Показать полностью", fieldChangeCollapse: "Свернуть", + fieldHistory: "История изменений", + fieldHistoryNone: "Изменений не зафиксировано", + fieldHistoryNoneRecent: "Нет изменений в недавней активности", replyCount: "{{count}} ответ", replyCount_one: "{{count}} ответ", replyCount_few: "{{count}} ответа", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 64aa3bb029b..ca2264da231 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1755,6 +1755,9 @@ const zh = { fieldChangeEmpty: '空', fieldChangeExpand: '展开', fieldChangeCollapse: '收起', + fieldHistory: '修改历史', + fieldHistoryNone: '没有修改记录', + fieldHistoryNoneRecent: '最近的动态里没有修改记录', // Replies replyCount: '{{count}} 条回复', replyCount_one: '{{count}} 条回复', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index f3c31a110dc..4ff6272221f 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1755,6 +1755,9 @@ const zhHant = { fieldChangeEmpty: '空', fieldChangeExpand: '展開', fieldChangeCollapse: '收起', + fieldHistory: '修改歷史', + fieldHistoryNone: '沒有修改記錄', + fieldHistoryNoneRecent: '最近的動態裡沒有修改記錄', // Replies replyCount: '{{count}} 條回覆', replyCount_one: '{{count}} 條回覆', diff --git a/ui/packages/plugin-detail/README.md b/ui/packages/plugin-detail/README.md index 1081b20d2ae..8d85d0d74c0 100644 --- a/ui/packages/plugin-detail/README.md +++ b/ui/packages/plugin-detail/README.md @@ -848,6 +848,39 @@ Polish shipped in #2572: the band decide through one rule, `resolveApprovalLock` from `@object-ui/react`. +## A field's change history + +Each field of the object on the record page has a history button beside its +value, shown on hover and on keyboard focus like the copy button. In a list, +right-clicking a cell of a field the object declares adds **Change history** +to the row's menu. Both open the same small card in place +(`FieldHistoryButton`, `FieldHistoryPopover`, both drawing `FieldHistoryCard`): + +- only that field's changes on that record: who, when, and old → new in the + reader's words (an option by its label, an empty side as the word for empty), + newest first, ten at a time with **Load more**; +- for a field never changed, **No changes recorded** with who created the + record and when. + +The card reads the record's activity rows (`sys_activity`), the rows the +activity stream draws, and keeps those that changed the field. The server +serves each row's changes narrowed to the reader, so a value the reader may not +read never reaches the browser, and a field the reader may not read +(`checkField(object, field, 'read')`) offers no history at all. Nor does a +field whose old → new values are not recorded (`resolveFieldHistory` from +`@objectstack/spec/data`: `fieldHistory: false` on the field, +`enable.fieldHistory: false` on the object, a credential field, or a media or +JSON-like type that does not opt in with `fieldHistory: true`), and nor do the +platform's own record columns (`id`, `created_at`, …). + +The rows are read by record, fifty at a time: a query naming a change column +is refused for a reader withheld any field of the object, so the field is never +part of the query. Opening the card reads at most four batches +(`FIELD_HISTORY_SCAN_BATCHES_PER_LOAD`), and each **Load more** at most four +more. When they hold no change of the field and older rows remain, the card +says **No changes in the recent activity** and offers **Load more** to read on; +it says **No changes recorded** only once every row has been read. + ## Links - 📚 [Documentation](https://objectstack.ai/docs/frontend/plugins/plugin-detail) diff --git a/ui/packages/plugin-detail/src/DetailSection.tsx b/ui/packages/plugin-detail/src/DetailSection.tsx index fe8516f314c..ce13b35e77b 100644 --- a/ui/packages/plugin-detail/src/DetailSection.tsx +++ b/ui/packages/plugin-detail/src/DetailSection.tsx @@ -61,6 +61,7 @@ import { useSafeFieldLabel } from '@object-ui/react'; import { NON_EDITABLE_SYSTEM_FIELDS } from './systemFields'; import { InlineFieldInput } from './InlineFieldInput'; import { FieldInPlaceEditor, isToggleFieldType, type FieldInPlaceWriter } from './FieldInPlaceEditor'; +import { FieldHistoryButton, fieldHistoryOffered } from './FieldHistory'; import { headerColorClass } from './headerColor'; import { DetailsColumnCapContext, framelessSectionColumns, useDefaultRecordPage } from './defaultRecordPage'; import { hasCellValue } from './emptiness'; @@ -343,6 +344,16 @@ export const DetailSection: React.FC = ({ React.useEffect(() => { if (isEditing) setFieldsInPlace([]); }, [isEditing]); + /** + * objectstack#36290 — the record a field's change history is read for: the + * page's own record, as `inPlaceWriter` reads it, so a section drawing + * another record (or none) offers no history button. + */ + const historyRecord = + recordCtx?.dataSource && recordCtx.recordId != null && recordCtx.recordId !== '' + && objectName && recordCtx.objectName === objectName + ? { dataSource: recordCtx.dataSource, objectName, recordId: recordCtx.recordId } + : null; const closeInPlace = React.useCallback((name: string) => { setFieldsInPlace((open) => open.filter((n) => n !== name)); }, []); @@ -1081,6 +1092,19 @@ export const DetailSection: React.FC = ({ )} + {/* objectstack#36290 — the field's change history, opened in place, + for a field of the object whose changes are recorded with their + values and that the reader may read. */} + {historyRecord && objectDefField && fieldHistoryOffered(perms, objectName, field.name, objectSchema) && ( + + )} {/* On the field face an editable value is copied from the same hover / focus button a read-only one is: its click is the way into edit, so the button is the way to copy. Elsewhere diff --git a/ui/packages/plugin-detail/src/FieldChangeItem.tsx b/ui/packages/plugin-detail/src/FieldChangeItem.tsx index 1791f3a69e7..8c2656abf72 100644 --- a/ui/packages/plugin-detail/src/FieldChangeItem.tsx +++ b/ui/packages/plugin-detail/src/FieldChangeItem.tsx @@ -16,7 +16,8 @@ export interface FieldChangeItemProps { /** * The field's label as the reader reads it, drawn as given (a host adds its * own separator, e.g. `Status:`). Absent: `change.fieldLabel`, else the - * field key made readable. + * field key made readable. `''` draws no label: a host that names the field + * once above its lines (a field's change-history card). */ label?: string; /** @@ -115,11 +116,15 @@ export const FieldChangeItem: React.FC = ({ data-field-change={change.field} data-field-change-expanded={expanded ? 'true' : 'false'} > - - {shownLabel} - - {/* A space a flex line does not lay out, so the line reads and copies as `Label: old → new`. */} - {' '} + {shownLabel !== '' && ( + <> + + {shownLabel} + + {/* A space a flex line does not lay out, so the line reads and copies as `Label: old → new`. */} + {' '} + + )} {value(before, 'old', oldRef)} {/* The arrow is text, so the line reads and copies as `Label: old → new`. */} diff --git a/ui/packages/plugin-detail/src/FieldHistory.tsx b/ui/packages/plugin-detail/src/FieldHistory.tsx new file mode 100644 index 00000000000..d1c3607d1be --- /dev/null +++ b/ui/packages/plugin-detail/src/FieldHistory.tsx @@ -0,0 +1,498 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * One field's change history (objectstack#36290, part ③): a small card, opened + * in place from the record page's field or a list cell's context menu, that + * lists only that field's changes on one record — who, when, old → new, + * newest first, ten at a time — or, when the field was never changed, says so + * with who created the record and when. + * + * The changes are the record's activity rows (`sys_activity`), the same rows + * the record page's activity stream draws. The server serves each row's + * field-change code narrowed to the reader (plugin-audit + * `activity-field-redaction.ts`): a change of a field the reader may not read + * is never sent. So the card reads what it is served and adds nothing, and + * the entry points are not offered at all on a field the reader may not read + * ({@link useFieldHistoryOffered}). Nor on a field whose old → new values the + * writer never records (`resolveFieldHistory` from `@objectstack/spec/data`, + * the predicate plugin-audit's writer keeps values by): there the card could + * only say 「No changes recorded」 of a field that was changed. The compliance + * ledger (`sys_audit_log`) is not read: it stays the administrators'. + * + * The rows are read by record, never by field: a query naming the change + * columns (`changed_fields`, `metadata`) is refused for a reader withheld any + * field of the object (plugin-audit `parent-field-query-guard.ts`), so the + * card pages the record's rows newest first and keeps those that changed the + * field. One open, and each "Load more", reads at most + * {@link FIELD_HISTORY_SCAN_BATCHES_PER_LOAD} batches of + * {@link FIELD_HISTORY_SCAN_BATCH} rows: it stops sooner when it has the page it + * shows or the rows run out, and otherwise stops there and offers "Load more" + * to read on, so a rarely-changed field on a busy record costs a bounded + * number of reads per click, never one read per fifty rows of the record. + */ + +import * as React from 'react'; +import { + Button, + Popover, + PopoverContent, + PopoverTrigger, + Tooltip, + TooltipContent, + TooltipProvider, + TooltipTrigger, + cn, +} from '@object-ui/components'; +import { History, Loader2 } from 'lucide-react'; +import { useDisplayLocale, useSafeTranslate } from '@object-ui/i18n'; +import { usePermissions } from '@object-ui/permissions'; +import type { DataSource } from '@object-ui/types'; +import { resolveFieldHistory } from '@objectstack/spec/data'; +import { FieldChangeItem } from './FieldChangeItem'; +import { useFieldChangeWording } from './fieldChangeText'; +import { + activityActorLine, + activityFieldChangesOf, + activityTimestamp, + isRefusedFeedRead, + IMPERSONATED_ACTOR_FALLBACK, + type ActivityFieldChange, + type SysActivityRow, +} from './renderers/recordActivityFeed'; +import { NON_EDITABLE_SYSTEM_FIELDS } from './systemFields'; +import { useDetailTranslation } from './useDetailTranslation'; + +/** How many changes the card shows at first, and how many more each "Load more" adds. */ +export const FIELD_HISTORY_PAGE_SIZE = 10; + +/** How many activity rows of the record one read asks for while looking for the field's changes. */ +export const FIELD_HISTORY_SCAN_BATCH = 50; + +/** + * How many batches one user action reads at most — the open, or one "Load + * more" — before it stops and offers "Load more" to read on. + */ +export const FIELD_HISTORY_SCAN_BATCHES_PER_LOAD = 4; + +/** One change of the field, as the card draws it. */ +export interface FieldHistoryEntry { + id: string; + /** Who made the change, as the activity row names them. */ + actor: string; + /** When, as the row's timestamp. */ + at: string; + change: ActivityFieldChange; +} + +/** Who created the record and when, as its creation row says. */ +export interface FieldHistoryCreation { + actor: string; + at: string; +} + +export interface FieldHistoryState { + /** The changes found so far, newest first. */ + entries: FieldHistoryEntry[]; + /** How many of them the card shows. */ + shown: number; + /** The record's creation row, once a read reached it. */ + creation: FieldHistoryCreation | null; + /** The record's rows have all been read. */ + exhausted: boolean; + /** + * This action's batches are spent with rows left unread: the scan has + * stopped and waits for "Load more". With no change found yet, the card says + * the recent activity holds none rather than that the field was never changed. + */ + paused: boolean; + loading: boolean; + /** The read was refused (401 / 403): the reader may not see this record's activity. */ + denied: boolean; + /** The read failed otherwise. */ + failed: boolean; + /** Whether "Load more" is offered: a found change not shown yet, or the scan paused with rows not read yet. */ + hasMore: boolean; + loadMore: () => void; +} + +export interface UseFieldHistoryOptions { + dataSource: DataSource | null | undefined; + objectName: string | null | undefined; + recordId: string | number | null | undefined; + field: string | null | undefined; +} + +function rowsOf(res: unknown): SysActivityRow[] { + const raw = (res as { data?: unknown } | null | undefined)?.data; + return Array.isArray(raw) ? (raw as SysActivityRow[]) : []; +} + +/** + * Read one field's changes on one record, newest first, a page at a time + * (see the file header for why the rows are read by record). + */ +export function useFieldHistory({ dataSource, objectName, recordId, field }: UseFieldHistoryOptions): FieldHistoryState { + // The actor words `record:activity` reads, read the same way: the + // impersonation line is a template its caller fills, so it is read raw. + const tt = useSafeTranslate(); + const systemActorLabel = tt('detail.systemActor', 'System'); + const impersonatedActorTemplate = tt('detail.impersonatedActor', IMPERSONATED_ACTOR_FALLBACK); + const unknownUserLabel = tt('detail.unknownUser', 'Unknown'); + + const [wanted, setWanted] = React.useState(FIELD_HISTORY_PAGE_SIZE); + const [entries, setEntries] = React.useState([]); + const [creation, setCreation] = React.useState(null); + const [scanned, setScanned] = React.useState(0); + // Batches this action may still read: the open, or the latest "Load more". + const [budget, setBudget] = React.useState(FIELD_HISTORY_SCAN_BATCHES_PER_LOAD); + const [exhausted, setExhausted] = React.useState(false); + const [loading, setLoading] = React.useState(false); + const [denied, setDenied] = React.useState(false); + const [failed, setFailed] = React.useState(false); + + const id = recordId === null || recordId === undefined || recordId === '' ? null : String(recordId); + const canRead = typeof dataSource?.find === 'function' && !!objectName && id !== null && !!field; + + // A different record or field starts over. + React.useEffect(() => { + setWanted(FIELD_HISTORY_PAGE_SIZE); + setEntries([]); + setCreation(null); + setScanned(0); + setBudget(FIELD_HISTORY_SCAN_BATCHES_PER_LOAD); + setExhausted(false); + setDenied(false); + setFailed(false); + }, [dataSource, objectName, id, field]); + + // Read the next batch of the record's rows while the card wants more changes + // than it has found, rows remain, and this action has batches left. Each + // answer moves `scanned` and spends one batch, which runs this again until + // one of the three stops it. + const wantsMore = canRead && !exhausted && !denied && !failed && entries.length < wanted; + const needsRead = wantsMore && budget > 0; + React.useEffect(() => { + if (!needsRead) return undefined; + let cancelled = false; + setLoading(true); + Promise.resolve( + (dataSource as DataSource).find('sys_activity', { + $filter: { object_name: objectName as string, record_id: id as string }, + $orderby: { timestamp: 'desc' }, + $skip: scanned, + // One row past the batch says whether rows remain. + $top: FIELD_HISTORY_SCAN_BATCH + 1, + // The actor's record in place of its id, for a row with no `actor_name`. + $expand: ['actor_id'], + }), + ) + .then((res) => { + if (cancelled) return; + const rows = rowsOf(res); + const batch = rows.slice(0, FIELD_HISTORY_SCAN_BATCH); + const found: FieldHistoryEntry[] = []; + let created: FieldHistoryCreation | null = null; + batch.forEach((row, index) => { + const actor = activityActorLine(row, systemActorLabel, impersonatedActorTemplate, unknownUserLabel); + const at = activityTimestamp(row); + if (row.type === 'created') { + created = { actor, at }; + return; + } + const change = activityFieldChangesOf(row)?.find((c) => c.field === field); + if (change) found.push({ id: String(row.id ?? `${scanned + index}`), actor, at, change }); + }); + // A row written while the card pages shifts `$skip` by one, so the next + // batch can repeat the last row read: keep each change once. + if (found.length > 0) { + setEntries((prev) => { + const seen = new Set(prev.map((e) => e.id)); + return [...prev, ...found.filter((e) => !seen.has(e.id))]; + }); + } + if (created) setCreation(created); + setScanned(scanned + batch.length); + setBudget((b) => b - 1); + setExhausted(rows.length <= FIELD_HISTORY_SCAN_BATCH); + }) + .catch((err: unknown) => { + if (cancelled) return; + if (isRefusedFeedRead(err)) setDenied(true); + else setFailed(true); + }) + .finally(() => { + if (!cancelled) setLoading(false); + }); + return () => { + cancelled = true; + }; + }, [needsRead, dataSource, objectName, id, field, scanned, systemActorLabel, impersonatedActorTemplate, unknownUserLabel]); + + // One more page to show, and a fresh budget of batches to find it with. + const loadMore = React.useCallback(() => { + setWanted((n) => n + FIELD_HISTORY_PAGE_SIZE); + setBudget(FIELD_HISTORY_SCAN_BATCHES_PER_LOAD); + }, []); + const shown = Math.min(entries.length, wanted); + const paused = wantsMore && budget <= 0; + return { + entries, + shown, + creation, + exhausted, + paused, + loading: loading || needsRead, + denied, + failed, + hasMore: !denied && !failed && (entries.length > wanted || (!exhausted && entries.length >= wanted) || paused), + loadMore, + }; +} + +/** + * Whether a field offers its change history to this reader: a field of the + * object, not one of the platform's own record columns (`id`, `created_at`, …, + * which no edit changes), one whose changes the writer records with their + * values, and one the reader may read. + * + * - Recorded: `resolveFieldHistory(field, object)` from `@objectstack/spec/data`, + * the one predicate plugin-audit's writer keeps old → new by. It is false for + * `fieldHistory: false` on the field, `enable.fieldHistory: false` on the + * object, a credential field, and a type whose values are off by default + * (image, file, JSON, …) unless the field opts in. Asked of the object schema + * the caller passes; a caller with no schema in hand is not narrowed by it. + * - Readable: the answer `usePermissions().checkField(object, field, 'read')` + * gives, the gate the record page and the list already draw the field by; + * with no permission provider mounted there is no answer to narrow by and + * the server's narrowing of the served changes is the floor. + */ +export function useFieldHistoryOffered( + objectName: string | null | undefined, + field: string | null | undefined, + objectSchema?: unknown, +): boolean { + return fieldHistoryOffered(usePermissions(), objectName, field, objectSchema); +} + +interface FieldHistorySchema { + managedBy?: unknown; + enable?: { fieldHistory?: unknown } | null; + fields?: Record | null; +} + +/** {@link useFieldHistoryOffered}'s answer for a caller that already holds the permissions (one call per field of a list). */ +export function fieldHistoryOffered( + perms: Pick, 'isLoaded' | 'checkField'> | null | undefined, + objectName: string | null | undefined, + field: string | null | undefined, + objectSchema?: unknown, +): boolean { + if (!objectName || !field) return false; + if (NON_EDITABLE_SYSTEM_FIELDS.has(field)) return false; + if (objectSchema && typeof objectSchema === 'object') { + const schema = objectSchema as FieldHistorySchema; + const def = schema.fields && Object.prototype.hasOwnProperty.call(schema.fields, field) ? schema.fields[field] : undefined; + if (!resolveFieldHistory(def, schema)) return false; + } + if (perms?.isLoaded && !perms.checkField(objectName, field, 'read')) return false; + return true; +} + +function formatWhen(at: string, locale: string): string { + const date = new Date(at); + if (Number.isNaN(date.getTime())) return at; + try { + return new Intl.DateTimeFormat(locale, { dateStyle: 'medium', timeStyle: 'short' }).format(date); + } catch { + return date.toISOString(); + } +} + +export interface FieldHistoryCardProps { + dataSource: DataSource | null | undefined; + objectName: string; + recordId: string | number; + field: string; + /** The object's schema, for the field's label and option labels. */ + objectSchema?: unknown; + className?: string; +} + +/** + * The card's content: the field's name, then its changes newest first, each + * `who · when` over `old → new`, with "Load more"; or, for a field never + * changed, 「No changes recorded」 and who created the record and when. + */ +export const FieldHistoryCard: React.FC = ({ + dataSource, + objectName, + recordId, + field, + objectSchema, + className, +}) => { + const { t } = useDetailTranslation(); + const locale = useDisplayLocale(); + const { labelOfField, changeSideText } = useFieldChangeWording(objectName, objectSchema); + const history = useFieldHistory({ dataSource, objectName, recordId, field }); + const label = labelOfField(field); + const visible = history.entries.slice(0, history.shown); + const settled = !history.loading || visible.length > 0; + const none = settled && !history.loading && visible.length === 0 && history.exhausted; + // The scan stopped at this action's batches with nothing found: the recent + // activity holds no change of the field, which is not "never changed". + const noneRecent = settled && !history.loading && visible.length === 0 && history.paused; + + return ( +
+
+ {label} + {t('detail.fieldHistory')} +
+ {history.denied ? ( +

+ {t('detail.activityAccessDenied')} +

+ ) : history.failed ? ( +

+ {t('detail.activityLoadFailed')} +

+ ) : none ? ( +
+

{t('detail.fieldHistoryNone')}

+ {history.creation && ( +

+ {t('detail.createdBy')} {history.creation.actor} + {' · '} + +

+ )} +
+ ) : noneRecent ? ( +

+ {t('detail.fieldHistoryNoneRecent')} +

+ ) : ( +
    + {visible.map((entry) => ( +
  1. + + {entry.actor} + {' · '} + + + +
  2. + ))} +
+ )} + {history.loading && ( + + + {t('detail.loading')} + + )} + {!history.loading && history.hasMore && ( + + )} +
+ ); +}; + +/** The card's width and padding, one face for every entry point. */ +const FIELD_HISTORY_POPOVER_CLASS = 'w-80 p-3'; + +export interface FieldHistoryButtonProps extends Omit { + className?: string; +} + +/** + * The record page's entry point: a history button beside a field's value, + * shown on hover and focus like the field's copy button, that opens the card + * in place. + */ +export const FieldHistoryButton: React.FC = ({ className, ...card }) => { + const { t } = useDetailTranslation(); + const [open, setOpen] = React.useState(false); + const label = t('detail.fieldHistory'); + return ( + + + + + + + + + {label} + + + e.stopPropagation()}> + {open && } + + + ); +}; + +export interface FieldHistoryPopoverProps extends FieldHistoryCardProps { + /** Where to open, in viewport coordinates (a list cell's context-menu point). */ + at: { x: number; y: number }; + onClose: () => void; +} + +/** + * The list's entry point: the card opened at a point, after the cell's + * context menu chose 「Change history」. Mounted only while open. + */ +export const FieldHistoryPopover: React.FC = ({ at, onClose, className, ...card }) => ( + { if (!open) onClose(); }}> + + + + + + + +); diff --git a/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx b/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx index 5cc789c3a1d..11e92a43e6e 100644 --- a/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx +++ b/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx @@ -38,15 +38,15 @@ import { RichTextCommentInput } from './RichTextCommentInput'; import { CommentAttachment, type Attachment } from './CommentAttachment'; import { CommentBody } from './CommentAuthorControls'; import { useDisplayLocale } from '@object-ui/i18n'; -import { useRecordContext, useSafeFieldLabel } from '@object-ui/react'; +import { useRecordContext } from '@object-ui/react'; import { useDetailTranslation } from './useDetailTranslation'; import { CommentAuthorAvatar } from './CommentAuthorAvatar'; import { FieldChangeItem } from './FieldChangeItem'; +import { useFieldChangeWording } from './fieldChangeText'; import { foldFeedItems, readerRecordNameOf, withReaderRecordName, - type ActivityFieldChange, type ActivityTimelineEntry, } from './renderers/recordActivityFeed'; import { @@ -653,47 +653,13 @@ export const RecordActivityTimeline: React.FC = ({ }); }, []); - // A changed field's label: the object's field label where the page has the - // object schema (`RecordContextProvider`), through the same translated - // `fieldLabel` the record's own sections use; the machine name otherwise. - const { fieldLabel, fieldOptionLabel } = useSafeFieldLabel(); - const labelOfField = React.useCallback( - (name: string): string => { - const objectName = recordContext?.objectName; - const def = (recordContext?.objectSchema as { fields?: Record } | undefined) - ?.fields?.[name]; - const authored = typeof def?.label === 'string' && def.label ? def.label : name; - return objectName ? fieldLabel(objectName, name, authored) : authored; - }, - [recordContext?.objectName, recordContext?.objectSchema, fieldLabel], - ); - - // A changed field's side as this reader reads it, `null` when it is empty: an - // option by the field's option label in the reader's language (the served - // text, the label the writer read, when the field declares none for it), a - // yes/no by the pack's word, anything else by its served text. - const changeSideText = React.useCallback( - (change: FieldChangeEntry, side: 'old' | 'new'): string | null => { - const facts = change as ActivityFieldChange; - const option = side === 'old' ? facts.oldOption : facts.newOption; - const value = side === 'old' ? change.oldValue : change.newValue; - const display = side === 'old' ? change.oldDisplayValue : change.newDisplayValue; - if (option !== undefined) { - const objectName = recordContext?.objectName; - const options = (recordContext?.objectSchema as - | { fields?: Record }> } - | undefined)?.fields?.[change.field]?.options; - const declared = Array.isArray(options) ? options.find((o) => String(o?.value) === option) : undefined; - const authored = typeof declared?.label === 'string' && declared.label ? declared.label : (display ?? option); - return objectName ? fieldOptionLabel(objectName, change.field, option, authored) : authored; - } - if (display !== undefined && display !== '') return display; - if (typeof value === 'boolean') { - return value ? t('common.yes', { defaultValue: 'Yes' }) : t('common.no', { defaultValue: 'No' }); - } - return value === null || value === undefined || value === '' ? null : String(value); - }, - [recordContext?.objectName, recordContext?.objectSchema, fieldOptionLabel, t], + // A changed field's label and each side of it as this reader reads it, from + // the object schema the page has (`RecordContextProvider`); the machine name + // and the served text otherwise. One wording with a field's change-history + // card (`useFieldChangeWording`). + const { labelOfField, changeSideText } = useFieldChangeWording( + recordContext?.objectName, + recordContext?.objectSchema, ); const handleFilterChange = React.useCallback( diff --git a/ui/packages/plugin-detail/src/__tests__/FieldHistory-36290.test.tsx b/ui/packages/plugin-detail/src/__tests__/FieldHistory-36290.test.tsx new file mode 100644 index 00000000000..b46b20489a9 --- /dev/null +++ b/ui/packages/plugin-detail/src/__tests__/FieldHistory-36290.test.tsx @@ -0,0 +1,338 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36290, part ③ — one field's change history, opened in place. + * + * 1. The card lists only that field's changes on the record, newest first: + * who, when, old → new in the reader's words (an option by its label), ten + * at a time with "Load more". + * 2. It reads the record's activity by record, never by a change column, and + * pages past rows of other fields until it finds the field's changes. + * 3. A field never changed: 「No changes recorded」 and who created the record. + * 4. A refused read says so. + * 5. The record page's field offers it only for a field of the object the + * reader may read: a field the reader may not read has no entry. + * 6. One open, and each "Load more", reads a bounded number of batches; a + * rarely-changed field on a busy record stops there and offers "Load more". + * 7. A field whose old → new values the writer never records (history off on + * the field or the object, a default-off type, a credential) has no entry. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, waitFor, cleanup, fireEvent, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; + +const permissions = vi.hoisted(() => ({ denied: new Set() })); +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + usePermissions: () => ({ + ...actual.usePermissions(), + isLoaded: true, + checkField: (_object: string, field: string) => !permissions.denied.has(field), + }), + }; +}); + +import { RecordContextProvider } from '@object-ui/react'; +import { + FieldHistoryCard, + FIELD_HISTORY_PAGE_SIZE, + FIELD_HISTORY_SCAN_BATCH, + FIELD_HISTORY_SCAN_BATCHES_PER_LOAD, +} from '../FieldHistory'; +import { DetailSection } from '../DetailSection'; + +afterEach(() => { + cleanup(); + permissions.denied.clear(); +}); + +const OBJECT = 'crm_account'; +const SCHEMA = { + name: OBJECT, + fields: { + notes: { type: 'textarea', label: 'Customer notes' }, + phone: { type: 'phone', label: 'Phone' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'prospect', label: 'Prospect' }, + { value: 'won', label: 'Closed won' }, + ], + }, + }, +}; + +type Side = Record; +/** An `updated` row as plugin-audit serves it: the field-change code narrowed to the reader. */ +const updated = (id: string, at: string, actor: string, changes: Array<{ field: string; from: Side; to: Side }>) => ({ + id, + type: 'updated', + summary: 'stored summary', + timestamp: at, + actor_name: actor, + metadata: JSON.stringify({ summary_message: { key: 'fieldChanges', object: OBJECT, changes } }), +}); +const created = (at: string, actor: string) => ({ id: 'c0', type: 'created', summary: 'Created', timestamp: at, actor_name: actor }); + +/** A data source whose `sys_activity` read pages `rows` (newest first) by `$skip` / `$top`. */ +function pagingSource(rows: unknown[], fail?: unknown) { + return { + find: vi.fn(async (_object: string, params: { $skip?: number; $top?: number }) => { + if (fail) throw fail; + const skip = params.$skip ?? 0; + return { data: rows.slice(skip, skip + (params.$top ?? rows.length)) }; + }), + }; +} + +const mountCard = (source: ReturnType, field = 'notes') => + render( + , + ); + +const entriesOf = (container: HTMLElement) => + Array.from(container.querySelectorAll('[data-field-history-entry]')).map((entry) => ({ + actor: entry.querySelector('[data-field-history-actor]')?.textContent, + old: entry.querySelector('[data-field-change-side="old"]')?.textContent, + new: entry.querySelector('[data-field-change-side="new"]')?.textContent, + })); + +describe('FieldHistoryCard — one field\'s changes (objectstack#36290)', () => { + it('lists only this field\'s changes, newest first: who, when, old → new; a save of two fields gives this one\'s line', async () => { + const source = pagingSource([ + updated('u3', '2026-11-22T10:00:00.000Z', 'Grace', [{ field: 'notes', from: { text: 'Second' }, to: { text: 'Third' } }]), + updated('u2', '2026-11-21T10:00:00.000Z', 'Ada', [ + { field: 'phone', from: { text: '1' }, to: { text: '2' } }, + { field: 'notes', from: { text: 'First' }, to: { text: 'Second' } }, + ]), + updated('u1', '2026-11-20T10:00:00.000Z', 'Ada', [{ field: 'phone', from: { text: '0' }, to: { text: '1' } }]), + created('2026-11-19T10:00:00.000Z', 'Ada'), + ]); + const { container } = mountCard(source); + await waitFor(() => expect(container.querySelectorAll('[data-field-history-entry]')).toHaveLength(2)); + expect(entriesOf(container)).toEqual([ + { actor: 'Grace', old: 'Second', new: 'Third' }, + { actor: 'Ada', old: 'First', new: 'Second' }, + ]); + expect(container.querySelector('[data-field-history-label]')).toHaveTextContent('Customer notes'); + // Each line is the values; the card names the field once, above. + expect(container.querySelector('[data-field-history-entry] [data-field-change-label]')).toBeNull(); + expect(container.querySelector('[data-field-history-entry] time')?.getAttribute('datetime')).toBe('2026-11-22T10:00:00.000Z'); + expect(container.querySelector('[data-field-history-none]')).toBeNull(); + expect(container.querySelector('[data-field-history-more]')).toBeNull(); + }); + + it('reads by record only: the read names no change column', async () => { + const source = pagingSource([created('2026-11-19T10:00:00.000Z', 'Ada')]); + mountCard(source); + await waitFor(() => expect(source.find).toHaveBeenCalled()); + const [object, params] = source.find.mock.calls[0] as [string, Record]; + expect(object).toBe('sys_activity'); + expect(params.$filter).toEqual({ object_name: OBJECT, record_id: 'rec-1' }); + expect(params.$orderby).toEqual({ timestamp: 'desc' }); + expect(JSON.stringify(params)).not.toMatch(/changed_fields|metadata/); + }); + + it('an option reads as its label; an empty side as the word for empty', async () => { + const source = pagingSource([ + updated('u1', '2026-11-20T10:00:00.000Z', 'Ada', [ + { field: 'stage', from: { text: '∅' }, to: { text: 'won', option: 'won' } }, + ]), + ]); + const { container } = mountCard(source, 'stage'); + await waitFor(() => expect(container.querySelectorAll('[data-field-history-entry]')).toHaveLength(1)); + expect(entriesOf(container)).toEqual([{ actor: 'Ada', old: 'Empty', new: 'Closed won' }]); + }); + + it(`shows the newest ${FIELD_HISTORY_PAGE_SIZE}, and "Load more" shows the rest`, async () => { + const rows = Array.from({ length: 13 }, (_, i) => + updated(`u${i}`, new Date(Date.UTC(2026, 10, 20, 12 - i)).toISOString(), 'Ada', [ + { field: 'notes', from: { text: `v${i + 1}` }, to: { text: `v${i}` } }, + ]), + ); + const { container } = mountCard(pagingSource(rows)); + await waitFor(() => expect(container.querySelectorAll('[data-field-history-entry]')).toHaveLength(FIELD_HISTORY_PAGE_SIZE)); + expect(entriesOf(container)[0].new).toBe('v0'); + fireEvent.click(await screen.findByText('Load more')); + await waitFor(() => expect(container.querySelectorAll('[data-field-history-entry]')).toHaveLength(13)); + expect(entriesOf(container)[12].new).toBe('v12'); + expect(container.querySelector('[data-field-history-more]')).toBeNull(); + }); + + it('pages past rows of other fields until it finds this field\'s changes', async () => { + const others = Array.from({ length: FIELD_HISTORY_SCAN_BATCH + 5 }, (_, i) => + updated(`p${i}`, new Date(Date.UTC(2026, 10, 22, 0, 0, 0) - i * 60_000).toISOString(), 'Ada', [ + { field: 'phone', from: { text: `${i + 1}` }, to: { text: `${i}` } }, + ]), + ); + const source = pagingSource([ + ...others, + updated('n1', '2026-11-01T10:00:00.000Z', 'Grace', [{ field: 'notes', from: { text: 'Before' }, to: { text: 'After' } }]), + ]); + const { container } = mountCard(source); + await waitFor(() => expect(container.querySelectorAll('[data-field-history-entry]')).toHaveLength(1)); + expect(entriesOf(container)).toEqual([{ actor: 'Grace', old: 'Before', new: 'After' }]); + expect(source.find).toHaveBeenCalledTimes(2); + expect((source.find.mock.calls[1] as [string, Record])[1].$skip).toBe(FIELD_HISTORY_SCAN_BATCH); + }); + + it(`one open reads at most ${FIELD_HISTORY_SCAN_BATCHES_PER_LOAD} batches, then "Load more" reads on`, async () => { + const capped = FIELD_HISTORY_SCAN_BATCHES_PER_LOAD * FIELD_HISTORY_SCAN_BATCH; + const others = Array.from({ length: capped + 10 }, (_, i) => + updated(`p${i}`, new Date(Date.UTC(2026, 10, 22, 0, 0, 0) - i * 60_000).toISOString(), 'Ada', [ + { field: 'phone', from: { text: `${i + 1}` }, to: { text: `${i}` } }, + ]), + ); + const source = pagingSource([ + ...others, + updated('n1', '2026-10-01T10:00:00.000Z', 'Grace', [{ field: 'notes', from: { text: 'Before' }, to: { text: 'After' } }]), + created('2026-09-01T10:00:00.000Z', 'Grace'), + ]); + const { container } = mountCard(source); + // The open stops at its batches: the recent activity holds no change of + // the field, which the card says, and it does not say "never changed". + await waitFor(() => expect(container.querySelector('[data-field-history-none-recent]')).not.toBeNull()); + expect(container.querySelector('[data-field-history-none-recent]')).toHaveTextContent('No changes in the recent activity'); + expect(source.find).toHaveBeenCalledTimes(FIELD_HISTORY_SCAN_BATCHES_PER_LOAD); + expect(container.querySelector('[data-field-history-none]')).toBeNull(); + // Nothing more is read without a click. + await new Promise((r) => setTimeout(r, 20)); + expect(source.find).toHaveBeenCalledTimes(FIELD_HISTORY_SCAN_BATCHES_PER_LOAD); + fireEvent.click(container.querySelector('[data-field-history-more]') as HTMLElement); + await waitFor(() => expect(container.querySelectorAll('[data-field-history-entry]')).toHaveLength(1)); + expect(entriesOf(container)).toEqual([{ actor: 'Grace', old: 'Before', new: 'After' }]); + expect(source.find).toHaveBeenCalledTimes(FIELD_HISTORY_SCAN_BATCHES_PER_LOAD + 1); + expect((source.find.mock.calls[FIELD_HISTORY_SCAN_BATCHES_PER_LOAD] as [string, Record])[1].$skip).toBe(capped); + expect(container.querySelector('[data-field-history-none-recent]')).toBeNull(); + expect(container.querySelector('[data-field-history-more]')).toBeNull(); + }); + + it('a field never changed: 「No changes recorded」 and who created the record, when', async () => { + const source = pagingSource([ + updated('u1', '2026-11-20T10:00:00.000Z', 'Ada', [{ field: 'phone', from: { text: '0' }, to: { text: '1' } }]), + created('2026-11-19T10:00:00.000Z', 'Grace'), + ]); + const { container } = mountCard(source); + await waitFor(() => expect(container.querySelector('[data-field-history-none]')).not.toBeNull()); + expect(container.querySelector('[data-field-history-none]')).toHaveTextContent('No changes recorded'); + const createdLine = container.querySelector('[data-field-history-created]') as HTMLElement; + expect(createdLine).toHaveTextContent('Created by Grace'); + expect(createdLine.querySelector('time')?.getAttribute('datetime')).toBe('2026-11-19T10:00:00.000Z'); + expect(container.querySelector('[data-field-history-entry]')).toBeNull(); + }); + + it('a refused read says the reader may not see this record\'s activity', async () => { + const { container } = mountCard(pagingSource([], Object.assign(new Error('Forbidden'), { status: 403 }))); + await waitFor(() => expect(container.querySelector('[data-field-history-denied]')).not.toBeNull()); + expect(container.querySelector('[data-field-history-none]')).toBeNull(); + }); +}); + +describe('the record page field\'s 「Change history」 entry (objectstack#36290)', () => { + const SECTION_FIELDS = [{ name: 'notes', label: 'Customer notes' }, { name: 'phone', label: 'Phone' }, { name: 'created_at', label: 'Created' }]; + const SECTION_DATA = { id: 'rec-1', notes: 'Third', phone: '2', created_at: '2026-11-19T10:00:00.000Z' }; + const mountSection = ( + source: ReturnType, + schema: Record = SCHEMA, + fields: Array<{ name: string; label: string }> = SECTION_FIELDS, + data: Record = SECTION_DATA, + ) => + render( + + + , + ); + const triggers = (container: HTMLElement) => + Array.from(container.querySelectorAll('[data-field-history-trigger]')).map((el) => el.getAttribute('data-field-history-trigger')); + + it('each field of the object offers it; a platform column does not; it opens the card in place', async () => { + const source = pagingSource([ + updated('u1', '2026-11-20T10:00:00.000Z', 'Ada', [{ field: 'notes', from: { text: 'Second' }, to: { text: 'Third' } }]), + ]); + const { container } = mountSection(source); + expect(triggers(container)).toEqual(['notes', 'phone']); + expect(source.find).not.toHaveBeenCalled(); + fireEvent.click(container.querySelector('[data-field-history-trigger="notes"]') as HTMLElement); + const card = await waitFor(() => { + const el = document.querySelector('[data-field-history="notes"]'); + expect(el).not.toBeNull(); + return el as HTMLElement; + }); + await waitFor(() => expect(card.querySelectorAll('[data-field-history-entry]')).toHaveLength(1)); + expect(within(card).getByText('Third')).toBeInTheDocument(); + }); + + it('a field the reader may not read has no entry (control: the readable one keeps it)', () => { + permissions.denied.add('notes'); + const { container } = mountSection(pagingSource([])); + expect(triggers(container)).toEqual(['phone']); + }); + + it('a field whose values are not recorded has no entry (control: a default-off type that opts in keeps it)', () => { + const schema = { + name: OBJECT, + fields: { + notes: { type: 'textarea', label: 'Customer notes' }, + quiet: { type: 'text', label: 'Quiet', fieldHistory: false }, + spec: { type: 'json', label: 'Spec' }, + spec_on: { type: 'json', label: 'Spec (on)', fieldHistory: true }, + secret: { type: 'password', label: 'Secret' }, + }, + }; + const fields = [ + { name: 'notes', label: 'Customer notes' }, + { name: 'quiet', label: 'Quiet' }, + { name: 'spec', label: 'Spec' }, + { name: 'spec_on', label: 'Spec (on)' }, + { name: 'secret', label: 'Secret' }, + ]; + const data = { id: 'rec-1', notes: 'Third', quiet: 'q', spec: '{"a":1}', spec_on: '{"b":2}', secret: '••••' }; + const { container } = mountSection(pagingSource([]), schema, fields, data); + expect(triggers(container)).toEqual(['notes', 'spec_on']); + }); + + it('an object with field history off offers none (control: the same object with it on)', () => { + const on = mountSection(pagingSource([])); + expect(triggers(on.container)).toEqual(['notes', 'phone']); + cleanup(); + const { container } = mountSection(pagingSource([]), { ...SCHEMA, enable: { fieldHistory: false } }); + expect(triggers(container)).toEqual([]); + }); + + it('a section not drawing the page\'s record offers none', () => { + const source = pagingSource([]); + const { container } = render( + , + ); + expect(triggers(container)).toEqual([]); + }); +}); diff --git a/ui/packages/plugin-detail/src/fieldChangeText.ts b/ui/packages/plugin-detail/src/fieldChangeText.ts new file mode 100644 index 00000000000..49069204563 --- /dev/null +++ b/ui/packages/plugin-detail/src/fieldChangeText.ts @@ -0,0 +1,68 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +import * as React from 'react'; +import { useSafeFieldLabel } from '@object-ui/react'; +import type { FieldChangeEntry } from '@object-ui/types'; +import type { ActivityFieldChange } from './renderers/recordActivityFeed'; +import { useDetailTranslation } from './useDetailTranslation'; + +interface ObjectSchemaFields { + fields?: Record }>; +} + +/** + * How the record page words one changed field (objectstack#36290): its label, + * and each side of the change as this reader reads it. One reading for every + * surface that draws a change, the activity stream's lines and a field's + * change-history card, so the two cannot word the same change apart. + * + * - The label: the object's field label through the translated `fieldLabel` + * the record's own sections use; the machine name where no schema names it. + * - A side, `null` when it is empty: an option by the field's option label in + * the reader's language (the served text, the label the writer read, when + * the field declares none for it), a yes/no by the pack's word, anything + * else by its served text. + */ +export function useFieldChangeWording(objectName: string | undefined, objectSchema: unknown) { + const { t } = useDetailTranslation(); + const { fieldLabel, fieldOptionLabel } = useSafeFieldLabel(); + const fields = (objectSchema as ObjectSchemaFields | undefined)?.fields; + + const labelOfField = React.useCallback( + (name: string): string => { + const def = fields?.[name]; + const authored = typeof def?.label === 'string' && def.label ? def.label : name; + return objectName ? fieldLabel(objectName, name, authored) : authored; + }, + [objectName, fields, fieldLabel], + ); + + const changeSideText = React.useCallback( + (change: FieldChangeEntry, side: 'old' | 'new'): string | null => { + const facts = change as ActivityFieldChange; + const option = side === 'old' ? facts.oldOption : facts.newOption; + const value = side === 'old' ? change.oldValue : change.newValue; + const display = side === 'old' ? change.oldDisplayValue : change.newDisplayValue; + if (option !== undefined) { + const options = fields?.[change.field]?.options; + const declared = Array.isArray(options) ? options.find((o) => String(o?.value) === option) : undefined; + const authored = typeof declared?.label === 'string' && declared.label ? declared.label : (display ?? option); + return objectName ? fieldOptionLabel(objectName, change.field, option, authored) : authored; + } + if (display !== undefined && display !== '') return display; + if (typeof value === 'boolean') { + return value ? t('common.yes', { defaultValue: 'Yes' }) : t('common.no', { defaultValue: 'No' }); + } + return value === null || value === undefined || value === '' ? null : String(value); + }, + [objectName, fields, fieldOptionLabel, t], + ); + + return { labelOfField, changeSideText }; +} diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 4543302a442..c43592e5b85 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -162,6 +162,19 @@ export { CommentAttachment } from './CommentAttachment'; export { RecordActivityTimeline } from './RecordActivityTimeline'; export { RecordChatterPanel } from './RecordChatterPanel'; export { FieldChangeItem } from './FieldChangeItem'; +// objectstack#36290 — one field's change history, opened in place: the record +// page's field button, and the card a list cell's context menu opens. +export { + FieldHistoryButton, + FieldHistoryCard, + FieldHistoryPopover, + fieldHistoryOffered, + useFieldHistory, + useFieldHistoryOffered, + FIELD_HISTORY_PAGE_SIZE, + FIELD_HISTORY_SCAN_BATCH, + FIELD_HISTORY_SCAN_BATCHES_PER_LOAD, +} from './FieldHistory'; export { SubscriptionToggle } from './SubscriptionToggle'; export { ReactionPicker } from './ReactionPicker'; export { ThreadedReplies } from './ThreadedReplies'; @@ -187,6 +200,15 @@ export type { CommentAttachmentProps, Attachment } from './CommentAttachment'; export type { RecordActivityTimelineProps, FeedFilterMode } from './RecordActivityTimeline'; export type { RecordChatterPanelProps } from './RecordChatterPanel'; export type { FieldChangeItemProps } from './FieldChangeItem'; +export type { + FieldHistoryButtonProps, + FieldHistoryCardProps, + FieldHistoryCreation, + FieldHistoryEntry, + FieldHistoryPopoverProps, + FieldHistoryState, + UseFieldHistoryOptions, +} from './FieldHistory'; export type { SubscriptionToggleProps } from './SubscriptionToggle'; export type { ReactionPickerProps } from './ReactionPicker'; export type { ThreadedRepliesProps } from './ThreadedReplies'; diff --git a/ui/packages/plugin-detail/src/useDetailTranslation.ts b/ui/packages/plugin-detail/src/useDetailTranslation.ts index 52d63a6ab67..a7c487f00f0 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -283,6 +283,12 @@ export const DETAIL_DEFAULT_TRANSLATIONS: Record = { 'detail.fieldChangeEmpty': 'Empty', 'detail.fieldChangeExpand': 'Show all', 'detail.fieldChangeCollapse': 'Show less', + // objectstack#36290 — one field's change-history card: its entry point's + // name (the record page's field button, the list cell's context menu) and + // what it says for a field never changed. + 'detail.fieldHistory': 'Change history', + 'detail.fieldHistoryNone': 'No changes recorded', + 'detail.fieldHistoryNoneRecent': 'No changes in the recent activity', // …and the punctuation that joins its field list: the shared list key the // form's field lists already use, not a second spelling of it. 'validation.formInvalidJoiner': ', ', diff --git a/ui/packages/plugin-grid/README.md b/ui/packages/plugin-grid/README.md index 9871f93d5fe..9e7117ba9c0 100644 --- a/ui/packages/plugin-grid/README.md +++ b/ui/packages/plugin-grid/README.md @@ -957,6 +957,18 @@ schema key: list metadata cannot set it. The console passes `false` for a view authored `navigation: { mode: 'none' }` and for an object whose data API serves no single-record read (objectstack#33317). +### A cell's change history + +Right-clicking a cell of a field the object declares adds **Change history** +to the row's context menu, when the grid's data source can read activity +(`find`), the field's changes are recorded with their values +(`resolveFieldHistory` from `@objectstack/spec/data`) and the reader may read +the field. Choosing it opens +`@object-ui/plugin-detail`'s `FieldHistoryPopover` at that point: that +record's changes of that field, newest first, ten at a time, or **No changes +recorded** with who created the record. `data-table` names the cell's column to +the host's `renderRowContextMenu` as `context.column`. + ### Inline Editing Enable inline cell editing for quick updates: diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index 9c9db9f89b0..1ff0b150b82 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -81,6 +81,8 @@ import { useDetailTranslation, StageChangeStarts, useRecordUpdateStarts, + FieldHistoryPopover, + fieldHistoryOffered, type ConcurrentUpdateConflict, } from '@object-ui/plugin-detail'; import { ChevronRight, ChevronLeft, ChevronsLeft, ChevronsRight, Download, Rows2, Rows3, Rows4, AlignJustify, Loader2, Check } from 'lucide-react'; @@ -958,6 +960,11 @@ export const ObjectGrid: React.FC = ({ onRowGroupsChange, }) => { const [data, setData] = useState([]); + // objectstack#36290 — the field change-history card a cell's context menu + // opened: which record and field, and where. Ephemeral, like the menu. + const [fieldHistoryAt, setFieldHistoryAt] = useState< + { recordId: string; field: string; x: number; y: number } | null + >(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); // Tenant default currency (ADR-0053) backstops amount cells that lack a code. @@ -3567,6 +3574,21 @@ export const ObjectGrid: React.FC = ({ return (orderedColumns as any[]).map((c) => (c === titleColumn ? adorned : c)); })(); + // objectstack#36290 — the card a cell's 「Change history」 item opened + // (`fieldHistoryAt`, declared with the grid's other state above). + const fieldHistoryPopover = fieldHistoryAt && dataSource && schema.objectName ? ( + setFieldHistoryAt(null)} + dataSource={dataSource} + objectName={schema.objectName} + recordId={fieldHistoryAt.recordId} + field={fieldHistoryAt.field} + objectSchema={objectSchema} + /> + ) : null; + /** * objectstack#28434 — what a right-click (or the context-menu key) on a row * opens; `data-table` owns the menu and calls this for its items. @@ -3582,7 +3604,7 @@ export const ObjectGrid: React.FC = ({ * browser's menu: the menu is a second way to reach the row's actions, not * a new surface. */ - const renderRowContextMenu = (row: any, context: { selected: boolean }): React.ReactNode => { + const renderRowContextMenu = (row: any, context: { selected: boolean; column?: string }): React.ReactNode => { if (context.selected && selectedRows.length >= 2) { return ( = ({ /> ); } + const recordId = rowRecordId(row); + // objectstack#36290 — the change history of the field whose cell the menu + // opened on: a field the object declares, whose changes are recorded with + // their values, that the reader may read, on a stored record. Offered on + // any table that reads its rows from a data source, row actions or none. + const historyField = + context.column + && typeof dataSource?.find === 'function' + && schema.objectName + && recordId != null && recordId !== '' + && Object.prototype.hasOwnProperty.call(objectSchema?.fields ?? {}, context.column) + && fieldHistoryOffered(perms, schema.objectName, context.column, objectSchema) + ? context.column + : null; + const onFieldHistory = historyField + ? (at: { x: number; y: number }) => + setFieldHistoryAt({ recordId: String(recordId), field: historyField, ...at }) + : undefined; // The browser's menu stays on a table that offers no row action at all and // whose rows cannot be selected — a face-level answer, so a row whose own // actions are all hidden by their predicates still opens Open / Open in - // new tab like its neighbours. - if (!tableOffersRowActions && !selectionMode) return null; - const recordId = rowRecordId(row); + // new tab like its neighbours — unless the cell offers its field's history. + if (!tableOffersRowActions && !selectionMode && !onFieldHistory) return null; const newTabHref = schema.objectName && recordId != null && recordId !== '' && recordLinkHost?.recordHref ? recordLinkHost.recordHref(schema.objectName, recordId) @@ -3615,13 +3654,14 @@ export const ObjectGrid: React.FC = ({ const opens = rowOpensRecord !== false && (!!onRowClick || (navigation.mode !== 'none' && !schema.navigation?.preventNavigation)); const openHref = rowOpensRecord === false ? null : newTabHref; - // Nothing at all to list for this row: no Open, no URL, no action. - if (!opens && !openHref && !rowOffersAction(row)) return null; + // Nothing at all to list for this row: no Open, no URL, no history, no action. + if (!opens && !openHref && !onFieldHistory && !rowOffersAction(row)) return null; return ( navigation.handleClick(row) : undefined} newTabHref={openHref} + onFieldHistory={onFieldHistory} /> ); }; @@ -5035,6 +5075,7 @@ export const ObjectGrid: React.FC = ({ {selectionBar && {selectionBar}} {groupedPager} + {fieldHistoryPopover} ) : (
@@ -5047,6 +5088,7 @@ export const ObjectGrid: React.FC = ({
{summaryFooter} + {fieldHistoryPopover} ); diff --git a/ui/packages/plugin-grid/src/__tests__/fieldHistoryCellMenu-36290.test.tsx b/ui/packages/plugin-grid/src/__tests__/fieldHistoryCellMenu-36290.test.tsx new file mode 100644 index 00000000000..78ad5ac77b3 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/fieldHistoryCellMenu-36290.test.tsx @@ -0,0 +1,189 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * objectstack#36290, part ③ — a list cell's context menu offers the cell's + * field's change history, and choosing it opens the same card the record page + * opens, in place. Driven through the real `ObjectGrid` → `data-table` chain. + * + * 1. A right-click on a cell of a field the object declares lists + * 「Change history」; choosing it opens the card with that record's changes + * of that field. + * 2. A field the reader may not read is not drawn as a column, and a cell of a + * column the object does not declare offers no history. + * 3. A data source that cannot read activity (no `find`) offers none. + * 4. A field whose old → new values the writer never records + * (`fieldHistory: false`) offers none. + */ + +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, screen, waitFor, cleanup, fireEvent, within, act } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +const permissions = vi.hoisted(() => ({ denied: new Set() })); +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + usePermissions: () => ({ + isLoaded: true, + checkField: (_object: string, field: string) => !permissions.denied.has(field), + getObjectApiOperations: () => undefined, + can: () => true, + check: () => ({ allowed: true }), + }), + }; +}); + +import { ObjectGrid } from '../ObjectGrid'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; + +registerAllFields(); + +afterEach(() => { + cleanup(); + permissions.denied.clear(); +}); + +const OBJECT = 'account'; +const ROWS = [ + { id: 'a1', name: 'Acme', status: 'draft', score: 3, derived: 'x', quiet: 'q1' }, + { id: 'a2', name: 'Globex', status: 'active', score: 5, derived: 'y', quiet: 'q2' }, +]; + +const activityRow = (id: string, field: string, from: string, to: string) => ({ + id, + type: 'updated', + summary: 'stored summary', + timestamp: '2026-11-20T10:00:00.000Z', + actor_name: 'Grace', + metadata: JSON.stringify({ + summary_message: { key: 'fieldChanges', object: OBJECT, changes: [{ field, from: { text: from }, to: { text: to } }] }, + }), +}); + +function renderGrid(opts: { withFind?: boolean } = {}) { + const find = vi.fn(async (object: string, params: Record) => { + if (object !== 'sys_activity') return { data: [] }; + return params.$filter?.record_id === 'a2' + ? { data: [activityRow('h1', 'status', 'draft', 'active'), activityRow('h0', 'score', '4', '5')] } + : { data: [] }; + }); + const dataSource: any = { + getObjectSchema: async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + name: { type: 'text', label: 'Name' }, + status: { type: 'text', label: 'Status' }, + score: { type: 'number', label: 'Score' }, + // History off on the field: the writer records no values for it. + quiet: { type: 'text', label: 'Quiet', fieldHistory: false }, + }, + }), + ...(opts.withFind === false ? {} : { find }), + }; + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + columns: [ + { field: 'name', label: 'Name' }, + { field: 'status', label: 'Status' }, + { field: 'score', label: 'Score' }, + { field: 'quiet', label: 'Quiet' }, + // A host-joined column the object does not declare. + { field: 'derived', label: 'Derived' }, + ], + data: { provider: 'value', items: ROWS }, + selection: { type: 'none' }, + }; + render( + + + + + , + ); + return { find }; +} + +const cellOf = (rowName: string, text: string) => + within(screen.getByText(rowName).closest('tr') as HTMLElement).getByText(text).closest('td') as HTMLElement; +const rightClick = (el: HTMLElement) => fireEvent.contextMenu(el, { button: 2, clientX: 40, clientY: 60 }); + +async function settle() { + await waitFor(() => expect(screen.getByText('Globex')).toBeInTheDocument()); + // The offer reads the object's declared fields; wait for the schema. + await waitFor(() => expect(screen.getByText('Score')).toBeInTheDocument()); + await act(async () => { await new Promise((r) => setTimeout(r, 0)); }); +} + +describe('a list cell\'s 「Change history」 (objectstack#36290)', () => { + it('a right-click on a field\'s cell lists it; choosing it opens that record\'s changes of that field', async () => { + const { find } = renderGrid(); + await settle(); + act(() => { rightClick(cellOf('Globex', 'active')); }); + const menu = await screen.findByTestId('row-context-menu'); + fireEvent.click(within(menu).getByTestId('row-context-field-history')); + const card = await waitFor(() => { + const el = document.querySelector('[data-field-history="status"]'); + expect(el).not.toBeNull(); + return el as HTMLElement; + }); + await waitFor(() => expect(card.querySelectorAll('[data-field-history-entry]')).toHaveLength(1)); + expect(card.querySelector('[data-field-change-side="old"]')).toHaveTextContent('draft'); + expect(card.querySelector('[data-field-change-side="new"]')).toHaveTextContent('active'); + expect(find).toHaveBeenCalledWith('sys_activity', expect.objectContaining({ + $filter: { object_name: OBJECT, record_id: 'a2' }, + })); + }); + + it('a field the reader may not read has no column, so no cell offers its history', async () => { + permissions.denied.add('status'); + renderGrid(); + await settle(); + expect(screen.queryByText('draft')).toBeNull(); + // CONTROL: a readable field's cell still offers its own. + act(() => { rightClick(cellOf('Acme', '3')); }); + const menu = await screen.findByTestId('row-context-menu'); + expect(within(menu).getByTestId('row-context-field-history')).toBeInTheDocument(); + }); + + it('a column the object does not declare offers no history', async () => { + renderGrid(); + await settle(); + act(() => { rightClick(cellOf('Acme', 'x')); }); + expect(screen.queryByTestId('row-context-field-history')).toBeNull(); + }); + + it('a field whose values are not recorded offers none (control: a recorded field\'s cell does)', async () => { + renderGrid(); + await settle(); + act(() => { rightClick(cellOf('Acme', 'q1')); }); + // This table offers no row action of its own, so with no history to offer + // the cell keeps the browser's menu: no row menu opens at all. + await act(async () => { await new Promise((r) => setTimeout(r, 20)); }); + expect(screen.queryByTestId('row-context-menu')).toBeNull(); + expect(screen.queryByTestId('row-context-field-history')).toBeNull(); + cleanup(); + renderGrid(); + await settle(); + act(() => { rightClick(cellOf('Acme', '3')); }); + const menu = await screen.findByTestId('row-context-menu'); + expect(within(menu).getByTestId('row-context-field-history')).toBeInTheDocument(); + }); + + it('a data source that cannot read activity offers none', async () => { + renderGrid({ withFind: false }); + await settle(); + act(() => { rightClick(cellOf('Acme', 'draft')); }); + expect(screen.queryByTestId('row-context-field-history')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-grid/src/components/RowContextMenu.tsx b/ui/packages/plugin-grid/src/components/RowContextMenu.tsx index 6f066b30d1e..38780daeca3 100644 --- a/ui/packages/plugin-grid/src/components/RowContextMenu.tsx +++ b/ui/packages/plugin-grid/src/components/RowContextMenu.tsx @@ -14,7 +14,7 @@ import { LazyIcon, toKebabIconName, } from '@object-ui/components'; -import { ExternalLink, PanelRightOpen, Trash2, X } from 'lucide-react'; +import { ExternalLink, History, PanelRightOpen, Trash2, X } from 'lucide-react'; import type { BulkActionDef } from '@object-ui/types'; import { useObjectTranslation } from '@object-ui/react'; import { @@ -37,6 +37,7 @@ import { BULK_SELECT_ALL_MATCHING_CAP, exceedsBulkSelectAllMatchingCap } from '. const CONTEXT_MENU_FALLBACKS: Record = { 'table.open': 'Open', 'detail.openInNewTab': 'Open in new tab', + 'detail.fieldHistory': 'Change history', }; function useContextMenuTranslation() { @@ -61,10 +62,16 @@ export const RowContextMenuItems: React.FC<{ onOpen?: () => void; /** The record URL the row links to. Absent ⇒ no Open in new tab item. */ newTabHref?: string | null; -}> = ({ menu, onOpen, newTabHref }) => { + /** + * Open the change history of the field whose cell the menu opened on + * (objectstack#36290), at the point the item was chosen. Absent ⇒ no + * Change history item. + */ + onFieldHistory?: (at: { x: number; y: number }) => void; +}> = ({ menu, onOpen, newTabHref, onFieldHistory }) => { const t = useContextMenuTranslation(); const plan = useRowActionPlan(menu, 0); - const hasOpen = !!onOpen || !!newTabHref; + const hasOpen = !!onOpen || !!newTabHref || !!onFieldHistory; return ( <> {onOpen && ( @@ -81,6 +88,21 @@ export const RowContextMenuItems: React.FC<{ )} + {onFieldHistory && ( + { + // A pointer click opens the card where it was; the keyboard has no + // pointer, so the card opens at the item. + const rect = (e.currentTarget as HTMLElement).getBoundingClientRect(); + const pointer = e.clientX !== 0 || e.clientY !== 0; + onFieldHistory(pointer ? { x: e.clientX, y: e.clientY } : { x: rect.left, y: rect.top }); + }} + data-testid="row-context-field-history" + > + + {t('detail.fieldHistory')} + + )} {hasOpen && plan.menuCount > 0 && } diff --git a/ui/packages/types/src/data-display.ts b/ui/packages/types/src/data-display.ts index d13572f638c..b09a2c5ab34 100644 --- a/ui/packages/types/src/data-display.ts +++ b/ui/packages/types/src/data-display.ts @@ -1686,8 +1686,13 @@ export interface DataTableSchema extends BaseSchema { * Answering `null` (or `undefined` / `false`) keeps the browser's menu for * that row. Absent, a table with its own row "⋮" menu opens those items, and * every other table keeps the browser's menu, exactly as before. + * + * `context.column` (objectstack#36290) is the accessor of the data cell the + * menu opened on, absent when it opened elsewhere on the row (the selection + * or "⋮" cell, or the keyboard on the row itself), so a host can add items + * about that cell, such as the field's change history. */ - renderRowContextMenu?: (row: any, context: { selected: boolean }) => React.ReactNode; + renderRowContextMenu?: (row: any, context: { selected: boolean; column?: string }) => React.ReactNode; /** * Group bands (objectui#12620): draw the table as ONE table, with one header, * whose body is a band row per group followed by that group's rows.