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 (
+