diff --git a/.changeset/36290-activity-field-change-lines.md b/.changeset/36290-activity-field-change-lines.md new file mode 100644 index 00000000000..01a616c54b8 --- /dev/null +++ b/.changeset/36290-activity-field-change-lines.md @@ -0,0 +1,20 @@ +--- +'@object-ui/plugin-detail': patch +'@object-ui/i18n': patch +--- + +feat(record-page): each changed field is its own line under an activity entry, `Label: old → new` + +Clause-②: yes (widening) — four new `detail.*` language-pack keys in every locale `@object-ui/i18n` ships (`fieldChangeLabel`, `fieldChangeEmpty`, `fieldChangeExpand`, `fieldChangeCollapse`), and six new optional props on the exported `FieldChangeItem` (`label`, `oldText` / `newText`, `emptyLabel`, `expandLabel` / `collapseLabel`); nothing is removed or renamed +Metadata-protocol: none + +The record page's activity named a saved change by its fields only (「更新了 客户备注」), or carried every value on one cut line. An activity entry now reads as the fields it changed, with one line per changed field under it: `Customer notes: Old words → New words`. A save that changed the phone and the email is one entry with two lines. + +- The values come from the field-change code the server already serves on each `sys_activity` row (`metadata.summary_message`), narrowed per reader by plugin-audit: a field the reader may not read has no change in it, so it draws no line. Nothing new is read, and nothing is filtered in the browser. +- An empty side reads as the language pack's word for empty (`Empty`, `空`), never the stored `∅`. +- A select side reads as the field's option label in the reader's language; a lookup or user side reads as the record's name the server served; a yes/no reads as the pack's Yes / No. +- Each side is cut to its line. A side that does not fit, or holds more than one line, offers a control that shows both sides in full and one that cuts them again. +- An audit-log entry (objects with `enable.trackHistory`) draws its changes the same way, and an activity row paired with its audit entry keeps its own summary with the audit's lines under it. The record's creation is unchanged: one row with its values beside the summary. +- The compact one-line text of a change (the activity panel's peek rows) now reads `Label: old → new` with the same words, where it read `Label old → new` with `—` for empty. + +What does not change: which entries the activity shows, how consecutive edits by one person on one day fold into one row, the activity filters, and no metadata key, value or default. diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index 06ab8289558..7a689405533 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -711,14 +711,14 @@ describe('RecordDetailView.auditDisplayLocale-10442', () => { /** * The rendered diff line for `close_date`, under an ENGLISH UI with `locale` as * the display locale. Since objectstack#27055 the record page draws the audit - * entries in the one 动态 stream, each change as one compact line - * (`data-stream-change`). + * entries in the one 动态 stream; since objectstack#36290 each changed field + * is its own line under the entry (`data-field-change`). */ async function diffLine(locale: string): Promise { renderHistory(locale); let text = ''; await waitFor(() => { - const line = Array.from(document.querySelectorAll('[data-stream-change]')).find((el) => + const line = Array.from(document.querySelectorAll('[data-field-change]')).find((el) => (el.textContent ?? '').startsWith('Close date'), ); expect(line).toBeTruthy(); @@ -729,7 +729,7 @@ describe('RecordDetailView.auditDisplayLocale-10442', () => { } const expected = (locale: string) => - `Close date ${new Date(`${FROM_DATE}T00:00:00Z`).toLocaleDateString(locale)} → ${new Date(`${TO_DATE}T00:00:00Z`).toLocaleDateString(locale)}`; + `Close date: ${new Date(`${FROM_DATE}T00:00:00Z`).toLocaleDateString(locale)} → ${new Date(`${TO_DATE}T00:00:00Z`).toLocaleDateString(locale)}`; beforeEach(() => { // Unrelated chrome on this view reaches for the platform API; answering it @@ -754,13 +754,13 @@ describe('RecordDetailView.auditDisplayLocale-10442', () => { describe('RecordDetailView — the audit history dates follow the display locale (objectui#10442)', () => { it('formats the date diff as de-CH under an English UI with a de-CH display locale', async () => { const text = await diffLine('de-CH'); - expect(text, `got: ${text}`).toBe('Close date 3.3.2020 → 4.3.2020'); + expect(text, `got: ${text}`).toBe('Close date: 3.3.2020 → 4.3.2020'); expect(text).toBe(expected('de-CH')); }); it('control: formats the date diff as en-US under an en-US display locale', async () => { const text = await diffLine('en-US'); - expect(text, `got: ${text}`).toBe('Close date 3/3/2020 → 3/4/2020'); + expect(text, `got: ${text}`).toBe('Close date: 3/3/2020 → 3/4/2020'); expect(text).toBe(expected('en-US')); }); @@ -892,17 +892,16 @@ describe('RecordDetailView.auditTenantCurrency-27640', () => { , ); - // One audit entry draws its changes as one compact line (`data-stream-change`), - // joined with `; `, so each field's part is split out and keyed by label. + // One audit entry draws each changed field as its own line under the entry + // (`data-field-change`, objectstack#36290), keyed here by label. const lines: Record = {}; await waitFor(() => { - const line = Array.from(document.querySelectorAll('[data-stream-change]')).find((el) => - (el.textContent ?? '').includes('Amount'), + const parts = Array.from(document.querySelectorAll('[data-field-change]')).map((el) => + (el.textContent ?? '').replace(/\s+/g, ' ').trim(), ); - expect(line, 'no History diff line').toBeTruthy(); - const parts = (line!.textContent ?? '').replace(/\s+/g, ' ').trim().split('; '); + expect(parts.length, 'no History diff line').toBeGreaterThan(0); for (const label of ['Amount', 'List price']) { - const part = parts.find((p) => p.startsWith(`${label} `)); + const part = parts.find((p) => p.startsWith(`${label}: `)); expect(part, `no change for ${label} in: ${parts.join(' | ')}`).toBeTruthy(); lines[label] = part!; } @@ -934,17 +933,17 @@ describe('RecordDetailView.auditTenantCurrency-27640', () => { describe('RecordDetailView — a dynamic currency diff reads in the tenant currency (objectstack#27640)', () => { it('formats a dynamic-mode change from 1500 to 2500 with the EUR face under an EUR tenant', async () => { const lines = await diffLines('EUR'); - expect(lines['Amount'], `got: ${lines['Amount']}`).toBe('Amount €1,500.00 → €2,500.00'); + expect(lines['Amount'], `got: ${lines['Amount']}`).toBe('Amount: €1,500.00 → €2,500.00'); }); it('keeps a record-mode change a plain number: the tenant currency is not its fallback', async () => { const lines = await diffLines('EUR'); - expect(lines['List price'], `got: ${lines['List price']}`).toBe('List price 1,500.00 → 2,500.00'); + expect(lines['List price'], `got: ${lines['List price']}`).toBe('List price: 1,500.00 → 2,500.00'); }); it('control: with no tenant currency, the dynamic change reads as a plain number', async () => { const lines = await diffLines(undefined); - expect(lines['Amount'], `got: ${lines['Amount']}`).toBe('Amount 1,500.00 → 2,500.00'); + expect(lines['Amount'], `got: ${lines['Amount']}`).toBe('Amount: 1,500.00 → 2,500.00'); }); }); }); diff --git a/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts b/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts index cc8a5774a7c..6dd86035ff8 100644 --- a/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts +++ b/ui/packages/i18n/src/__tests__/untranslated-identity-4376.test.ts @@ -126,6 +126,7 @@ const LEGITIMATE_IDENTITIES: Record = { // value is the hole alone — a fit decision held by app-shell's // `appTileOpenedLine-12601.test.ts`, not an omission. 'home.appOpened': 'Tile last-opened line — the bare `{{time}}` hole where no verb fits the tile.', + 'detail.fieldChangeLabel': 'Activity field-change line label — the field hole and a separator, no prose; zh-Hans, zh-Hant and ja set a fullwidth colon, fr its space-before-colon, ko/ru/ar keep `:` as their punctuation (objectstack#36290).', 'console.changeOwner.failure': 'Change Owner report row — the row id and the server\'s own sentence joined by a colon, a format string with no word to translate; zh-Hans and fr use their own colon (objectstack#35403).', // Loanwords these packs have adopted as their OWN vocabulary (checked against diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 7e116670ffe..4a66f7769b0 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1685,6 +1685,10 @@ const ar = { foldedMoreFields_other: "{{count}} أخرى", expandFolded: "عرض كل تحديث", collapseFolded: "إخفاء التحديثات", + fieldChangeLabel: "{{field}}:", + fieldChangeEmpty: "فارغ", + fieldChangeExpand: "عرض الكل", + fieldChangeCollapse: "عرض أقل", 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 99a04f8246c..ea9717f9e4c 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1504,6 +1504,10 @@ const de = { foldedMoreFields_other: "{{count}} weitere", expandFolded: "Jede Aktualisierung anzeigen", collapseFolded: "Aktualisierungen ausblenden", + fieldChangeLabel: "{{field}}:", + fieldChangeEmpty: "Leer", + fieldChangeExpand: "Alles anzeigen", + fieldChangeCollapse: "Weniger anzeigen", 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 6e0203855d0..c0948fd1a0e 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -2043,6 +2043,13 @@ const en = { foldedMoreFields_other: '{{count}} more', expandFolded: 'Show each update', collapseFolded: 'Hide updates', + // objectstack#36290 — one line per changed field under an activity entry: + // the field's label before its values, the word for an empty side, and + // the control that shows a long value in full and clamps it again. + fieldChangeLabel: '{{field}}:', + fieldChangeEmpty: 'Empty', + fieldChangeExpand: 'Show all', + fieldChangeCollapse: 'Show less', // 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 14d1435d08b..ddd838ee2d1 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1549,6 +1549,10 @@ const es = { foldedMoreFields_other: "{{count}} más", expandFolded: "Mostrar cada actualización", collapseFolded: "Ocultar actualizaciones", + fieldChangeLabel: "{{field}}:", + fieldChangeEmpty: "Vacío", + fieldChangeExpand: "Ver todo", + fieldChangeCollapse: "Ver menos", 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 ae5ec6e7760..b3e90d834e4 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1553,6 +1553,10 @@ const fr = { foldedMoreFields_other: "{{count}} autres", expandFolded: "Afficher chaque mise à jour", collapseFolded: "Masquer les mises à jour", + fieldChangeLabel: "{{field}} :", + fieldChangeEmpty: "Vide", + fieldChangeExpand: "Tout afficher", + fieldChangeCollapse: "Afficher moins", 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 e1659e47807..eda82502f38 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1588,6 +1588,10 @@ const ja = { foldedMoreFields_other: "他 {{count}} 件", expandFolded: "各更新を表示", collapseFolded: "更新を隠す", + fieldChangeLabel: "{{field}}:", + fieldChangeEmpty: "空", + fieldChangeExpand: "すべて表示", + fieldChangeCollapse: "折りたたむ", 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 0dca5d4ab09..df6ae83c57a 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1504,6 +1504,10 @@ const ko = { foldedMoreFields_other: "외 {{count}}개", expandFolded: "각 업데이트 보기", collapseFolded: "업데이트 숨기기", + fieldChangeLabel: "{{field}}:", + fieldChangeEmpty: "비어 있음", + fieldChangeExpand: "모두 보기", + fieldChangeCollapse: "접기", 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 a6e96fc7d35..a0ac235cab2 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1553,6 +1553,10 @@ const pt = { foldedMoreFields_other: "mais {{count}}", expandFolded: "Mostrar cada atualização", collapseFolded: "Ocultar atualizações", + fieldChangeLabel: "{{field}}:", + fieldChangeEmpty: "Vazio", + fieldChangeExpand: "Ver tudo", + fieldChangeCollapse: "Ver menos", 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 d55af6d586b..8a6cf9f67ae 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1700,6 +1700,10 @@ const ru = { foldedMoreFields_other: "ещё {{count}}", expandFolded: "Показать каждое обновление", collapseFolded: "Скрыть обновления", + fieldChangeLabel: "{{field}}:", + fieldChangeEmpty: "Пусто", + fieldChangeExpand: "Показать полностью", + fieldChangeCollapse: "Свернуть", 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 223c008a9d5..081de27b449 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1733,6 +1733,10 @@ const zh = { foldedMoreFields_other: '其他 {{count}} 项', expandFolded: '展开每次更新', collapseFolded: '收起更新', + fieldChangeLabel: '{{field}}:', + fieldChangeEmpty: '空', + fieldChangeExpand: '展开', + fieldChangeCollapse: '收起', // 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 e73353699ec..9e476d06c23 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1733,6 +1733,10 @@ const zhHant = { foldedMoreFields_other: '其他 {{count}} 項', expandFolded: '展開每次更新', collapseFolded: '收起更新', + fieldChangeLabel: '{{field}}:', + fieldChangeEmpty: '空', + fieldChangeExpand: '展開', + fieldChangeCollapse: '收起', // Replies replyCount: '{{count}} 條回覆', replyCount_one: '{{count}} 條回覆', diff --git a/ui/packages/plugin-detail/src/FieldChangeItem.tsx b/ui/packages/plugin-detail/src/FieldChangeItem.tsx index 92584f3e417..1791f3a69e7 100644 --- a/ui/packages/plugin-detail/src/FieldChangeItem.tsx +++ b/ui/packages/plugin-detail/src/FieldChangeItem.tsx @@ -8,39 +8,135 @@ import * as React from 'react'; import { cn } from '@object-ui/components'; -import { ArrowRight } from 'lucide-react'; import type { FieldChangeEntry } from '@object-ui/types'; export interface FieldChangeItemProps { /** The field change entry to render */ change: FieldChangeEntry; + /** + * 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. + */ + label?: string; + /** + * Each side's text as the reader reads it; `null` is an empty side, drawn as + * `emptyLabel`. Absent: the side's display value, else its value as text, + * else empty. + */ + oldText?: string | null; + newText?: string | null; + /** What an empty side reads as. */ + emptyLabel?: string; + /** The control that shows a long value in full, and the one that clamps it again. */ + expandLabel?: string; + collapseLabel?: string; className?: string; } /** - * FieldChangeItem — Renders a single field change entry. - * Shows: field label → old value → new value with human-readable display values. - * Aligned with @objectstack/spec FieldChangeEntrySchema. + * A value longer than this, or one with a line break, offers the expand + * control even where the line has not been laid out (a test DOM, a hidden tab). + */ +export const FIELD_CHANGE_LONG_VALUE_CHARS = 48; + +const isLongValue = (text: string | null): boolean => + text !== null && (text.includes('\n') || text.length > FIELD_CHANGE_LONG_VALUE_CHARS); + +const sideOf = (display: string | undefined, value: unknown): string | null => + display !== undefined && display !== '' + ? display + : value === null || value === undefined || value === '' + ? null + : String(value); + +/** + * FieldChangeItem: one changed field on one line, `Label old → new`, each + * side cut to the line. A side that does not fit, or holds more than one + * line, offers a control that shows both sides in full; an empty side reads + * as `emptyLabel`. */ export const FieldChangeItem: React.FC = ({ change, + label, + oldText, + newText, + emptyLabel = '(empty)', + expandLabel = 'Show more', + collapseLabel = 'Show less', className, }) => { - const label = + const shownLabel = + label ?? change.fieldLabel ?? change.field.charAt(0).toUpperCase() + change.field.slice(1).replace(/_/g, ' '); + const before = oldText !== undefined ? oldText : sideOf(change.oldDisplayValue, change.oldValue); + const after = newText !== undefined ? newText : sideOf(change.newDisplayValue, change.newValue); + + const [expanded, setExpanded] = React.useState(false); + // Whether a side is wider than its line, as laid out; the length rule above + // answers where nothing is laid out. + const [overflows, setOverflows] = React.useState(false); + const oldRef = React.useRef(null); + const newRef = React.useRef(null); + React.useLayoutEffect(() => { + if (expanded) return undefined; + const measure = () => { + const cut = (el: HTMLSpanElement | null) => !!el && el.scrollWidth > el.clientWidth; + setOverflows(cut(oldRef.current) || cut(newRef.current)); + }; + measure(); + if (typeof ResizeObserver === 'undefined') return undefined; + const observer = new ResizeObserver(measure); + if (oldRef.current) observer.observe(oldRef.current); + if (newRef.current) observer.observe(newRef.current); + return () => observer.disconnect(); + }, [before, after, expanded]); + const offersToggle = expanded || overflows || isLongValue(before) || isLongValue(after); - const oldDisplay = - change.oldDisplayValue ?? (change.oldValue != null ? String(change.oldValue) : '(empty)'); - const newDisplay = - change.newDisplayValue ?? (change.newValue != null ? String(change.newValue) : '(empty)'); + const value = (text: string | null, side: 'old' | 'new', ref: React.RefObject) => ( + + {text ?? emptyLabel} + + ); return ( -
- {label} - {oldDisplay} - - {newDisplay} +
+ + {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`. */} + + {' → '} + + {value(after, 'new', newRef)} + {offersToggle && ( + + )}
); }; diff --git a/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx b/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx index 2947e474edd..5cc789c3a1d 100644 --- a/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx +++ b/ui/packages/plugin-detail/src/RecordActivityTimeline.tsx @@ -29,7 +29,7 @@ import { AlertTriangle, RefreshCw, } from 'lucide-react'; -import type { FeedItem, FeedItemType, RecordActivityComponentProps, RecordSubscription } from '@object-ui/types'; +import type { FeedItem, FeedItemType, FieldChangeEntry, RecordActivityComponentProps, RecordSubscription } from '@object-ui/types'; import type { FeedFilterMode } from '@objectstack/spec/data'; import { ReactionPicker } from './ReactionPicker'; import { ThreadedReplies } from './ThreadedReplies'; @@ -41,10 +41,12 @@ import { useDisplayLocale } from '@object-ui/i18n'; import { useRecordContext, useSafeFieldLabel } from '@object-ui/react'; import { useDetailTranslation } from './useDetailTranslation'; import { CommentAuthorAvatar } from './CommentAuthorAvatar'; +import { FieldChangeItem } from './FieldChangeItem'; import { foldFeedItems, readerRecordNameOf, withReaderRecordName, + type ActivityFieldChange, type ActivityTimelineEntry, } from './renderers/recordActivityFeed'; import { @@ -296,6 +298,25 @@ function streamChangedFieldsOf(item: FeedItem): string[] { return changes.map((change) => change.field); } +/** + * The changed fields an entry draws one line each for, under its row + * (objectstack#36290): its own changes (an activity row's served change code, + * or an audit entry's), else those of the audit entry paired onto it. `null` + * for an entry with none, and for the record's creation, which stays one row + * with its values beside the summary. Only what the server served is here: + * a field the reader may not read has no change in the list, so it draws no + * line. + */ +export function fieldChangeLinesOf(item: FeedItem): readonly FieldChangeEntry[] | null { + if (isRecordCreationEntry(item)) return null; + if (item.fieldChanges && item.fieldChanges.length > 0) return item.fieldChanges; + const paired = fieldHistoryOf(item); + if (paired && !isRecordCreationEntry(paired) && paired.fieldChanges && paired.fieldChanges.length > 0) { + return paired.fieldChanges; + } + return null; +} + /** * The dropdown's options, given whether the record's field history is shown * (`RecordFieldHistoryContext`): `changes_only` is offered exactly when the @@ -635,7 +656,7 @@ 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 } = useSafeFieldLabel(); + const { fieldLabel, fieldOptionLabel } = useSafeFieldLabel(); const labelOfField = React.useCallback( (name: string): string => { const objectName = recordContext?.objectName; @@ -647,6 +668,34 @@ export const RecordActivityTimeline: React.FC = ({ [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], + ); + const handleFilterChange = React.useCallback( (mode: FeedFilterMode) => { if (onFilterChange) { @@ -715,13 +764,14 @@ export const RecordActivityTimeline: React.FC = ({ // same function when expanded (objectstack#25959). // objectstack#27055 — a system entry of the stream: ONE muted line, the // change itself, then who and when. 「状态 新建 → 已联系 · Dev Admin · 昨天」. + // Each change reads as its line under a row does (objectstack#36290): the + // same label, the same sides, the same word for empty. const changesText = (item: FeedItem): string => (item.fieldChanges ?? []) .map((change) => { - const label = change.fieldLabel || labelOfField(change.field); - const from = change.oldDisplayValue ?? (change.oldValue == null ? '' : String(change.oldValue)); - const to = change.newDisplayValue ?? (change.newValue == null ? '' : String(change.newValue)); - return `${label} ${from || '—'} → ${to || '—'}`; + const label = t('detail.fieldChangeLabel', { field: change.fieldLabel || labelOfField(change.field) }); + const empty = t('detail.fieldChangeEmpty'); + return `${label} ${changeSideText(change, 'old') ?? empty} → ${changeSideText(change, 'new') ?? empty}`; }) .join('; '); // An activity row paired with its audit entry (objectstack#30122) reads as @@ -749,15 +799,15 @@ export const RecordActivityTimeline: React.FC = ({ whatTitle: string, extra?: React.ReactNode, rowProps?: Record, + below?: React.ReactNode, ): React.ReactNode => { const when = formatTimestamp(item.createdAt, t, displayLocale); - return ( + const line = (
@@ -775,9 +825,62 @@ export const RecordActivityTimeline: React.FC = ({
); + if (!below) return line; + // The row is its line and what sits under it: the row's markers go on the + // whole, so a reader of the row reads both. + return ( +
+ {line} + {below} +
+ ); }; + // One line per changed field under the entry's row (objectstack#36290): + // `Label: old → new`, an empty side as the pack's word for empty, each side + // cut to the line with a control that shows it in full. Indented to the + // row's text, past its icon. + const renderFieldChangeLines = (changes: readonly FieldChangeEntry[]): React.ReactNode => ( +
    + {changes.map((change, index) => ( +
  • + +
  • + ))} +
+ ); const renderSystemLine = (item: FeedItem): React.ReactNode => { const Icon = FEED_TYPE_ICONS[item.type] || Zap; + const lines = fieldChangeLinesOf(item); + if (lines) { + // The values are the lines under the row. An entry whose own changes + // they are names the fields it changed (its stored summary would say the + // lines again); an activity row carrying its paired audit entry keeps its + // own summary. + const what = lines === item.fieldChanges + ? t('detail.foldedUpdates', { + fields: Array.from(new Set(lines.map((change) => change.fieldLabel || labelOfField(change.field)))).join( + t('validation.formInvalidJoiner'), + ), + }) + : systemLineText(item); + return streamRow( + item, + Icon, + {what}, + what, + undefined, + { 'data-stream-system-row': '' }, + renderFieldChangeLines(lines), + ); + } const what = systemLineText(item); const paired = fieldHistoryOf(item); const diff = paired ? changesText(paired) : ''; diff --git a/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel-27524.test.tsx b/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel-27524.test.tsx index 5c3d934fdeb..c42c3c1ac31 100644 --- a/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel-27524.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/RecordTimelinePanel-27524.test.tsx @@ -91,7 +91,7 @@ describe('the 动态 panel (objectstack#27524, Target 5)', () => { // Newest first: the change (00:20), Note 5 (00:05), Note 4 — the reply (00:30) is not a root. const lines = peekLines(container); expect(lines).toHaveLength(3); - expect(lines[0]).toContain('Status New → Contacted'); + expect(lines[0]).toContain('Status: New → Contacted'); expect(lines[1]).toContain('Note 5'); expect(lines[2]).toContain('Note 4'); expect(lines.join(' ')).not.toContain('A reply'); diff --git a/ui/packages/plugin-detail/src/__tests__/recordTimelineStream-27055.test.tsx b/ui/packages/plugin-detail/src/__tests__/recordTimelineStream-27055.test.tsx index 90f9dc989c8..7cae3b4a8f0 100644 --- a/ui/packages/plugin-detail/src/__tests__/recordTimelineStream-27055.test.tsx +++ b/ui/packages/plugin-detail/src/__tests__/recordTimelineStream-27055.test.tsx @@ -38,6 +38,14 @@ import { DefaultRecordPageContext } from '../defaultRecordPage'; afterEach(cleanup); +/** + * Each changed field's line as it reads (objectstack#36290): `Label: old → new`, + * drawn over several elements, so read off the line rather than matched as one + * element's text. + */ +const changeLines = (): string[] => + Array.from(document.querySelectorAll('[data-field-change]')).map((line) => line.textContent ?? ''); + const comment: FeedItem = { id: 'c1', type: 'comment', actor: 'Ada', body: 'Budget is set', createdAt: '2026-10-23T10:00:00Z' }; const call: FeedItem = { id: 'a1', type: 'task', actor: 'Dev', body: 'Logged a call', createdAt: '2026-10-28T10:20:00Z' }; const updated = { id: 'a2', type: 'field_change', actor: 'Dev', body: 'updated', createdAt: '2026-10-27T16:05:00Z', activityType: 'updated' } as FeedItem; @@ -87,7 +95,7 @@ describe('RecordActivityTimeline — the stream face', () => { expect(screen.queryByRole('combobox')).toBeNull(); const lines = Array.from(container.querySelectorAll('[data-stream-system-row]')).map((l) => l.textContent); expect(lines).toHaveLength(2); - expect(lines[0]).toContain('Status New → Contacted'); + expect(lines[0]).toContain('Status: New → Contacted'); // A comment keeps its full row. expect(screen.getByText('Budget is set')).toBeTruthy(); }); @@ -155,7 +163,7 @@ describe('record:activity on the default record page is the stream', () => { expect(container.querySelector('[data-stream-filters]')).toBeNull(); expect(screen.getByRole('combobox')).toBeTruthy(); // The change is one line with its before and after (objectstack#35602). - expect(screen.getAllByText(/New → Contacted/).length).toBeGreaterThan(0); + expect(changeLines()).toContain('Status: New → Contacted'); }); }); @@ -245,7 +253,7 @@ describe("the panel's `changes_only` is offered by the same rule as the 变更 c it('CONTROL: with history shown, the same `changes_only` holds the field change only', () => { render(panel(true, 'changes_only')); - expect(screen.getAllByText(/Status New → Contacted/).length).toBeGreaterThan(0); + expect(changeLines()).toContain('Status: New → Contacted'); expect(screen.queryByText('Logged a call')).toBeNull(); expect(screen.queryByText('Budget is set')).toBeNull(); }); @@ -287,20 +295,20 @@ describe('an activity row sits under 活动 whatever the history flag; 变更 ho const shown = events.filter((e) => !(fieldHistory && e.activityType === 'updated')); for (const event of shown) expect(screen.getByText(`Event ${event.activityType}`)).toBeTruthy(); expect(screen.getByText('Logged a call')).toBeTruthy(); - expect(screen.queryByText(/New → Contacted/)).toBeNull(); + expect(changeLines().some((line) => line.includes('New → Contacted'))).toBe(false); }); } it('CONTROL, history on: 变更 holds the field change with its old and new values, and no activity event', () => { const { container } = render(page(true)); choose(container, 'changes'); - expect(screen.getByText(/Status New → Contacted/)).toBeTruthy(); + expect(changeLines()).toEqual(['Status: New → Contacted']); for (const event of events) expect(screen.queryByText(`Event ${event.activityType}`)).toBeNull(); }); it("the panel's `changes_only` keeps the same rule as the stream", () => { render(); - expect(screen.getAllByText(/Status New → Contacted/).length).toBeGreaterThan(0); + expect(changeLines()).toContain('Status: New → Contacted'); expect(screen.queryByText('Created the lead')).toBeNull(); expect(screen.queryByText('Logged a call')).toBeNull(); }); @@ -381,7 +389,7 @@ describe('one action, one row: an activity row carries its audit entry (objectst expect(rows).toHaveLength(1); expect(rows[0].querySelector('[data-stream-change]')?.textContent).toBe('Activity r1'); expect(rows[0].textContent).toContain('Dev Admin'); - expect(rows[0].querySelector('[data-stream-change-diff]')?.textContent).toBe('Company Old Co → New Co 11'); + expect(rows[0].querySelector('[data-stream-change-diff]')?.textContent).toBe('Company: Old Co → New Co 11'); }); it('a reader without the audit log sees the same ONE row, without a diff', () => { @@ -397,7 +405,7 @@ describe('one action, one row: an activity row carries its audit entry (objectst fireEvent.click(container.querySelector('[data-stream-filter="changes"]')!); const rows = container.querySelectorAll('[data-stream-system-row]'); expect(rows).toHaveLength(1); - expect(rows[0].querySelector('[data-stream-change]')?.textContent).toBe('Company Old Co → New Co 12'); + expect(rows[0].querySelector('[data-stream-change]')?.textContent).toBe('Company: Old Co → New Co 12'); expect(rows[0].querySelector('[data-stream-change-diff]')).toBeNull(); }); @@ -498,16 +506,16 @@ describe("an authored page's feed panels hold the record's field history (object mount(block, {}); expect(screen.getByText('Updated the deal')).toBeTruthy(); // Each change is one line with its before and after (objectstack#35602). - expect(screen.getAllByText(/Prospecting → Negotiation/).length).toBeGreaterThan(0); - expect(screen.getAllByText(/100 → 250/).length).toBeGreaterThan(0); + expect(changeLines().some((line) => line.includes('Prospecting → Negotiation'))).toBe(true); + expect(changeLines().some((line) => line.includes('100 → 250'))).toBe(true); expect(screen.getByText('Kick-off note')).toBeTruthy(); }); it('an authored `filterMode: changes_only` opens on Field Changes and holds the field history only', () => { mount(block, { filterMode: 'changes_only' }); expect(screen.getByRole('combobox').textContent).toContain('Field Changes'); - expect(screen.getAllByText(/Prospecting → Negotiation/).length).toBeGreaterThan(0); - expect(screen.getAllByText(/100 → 250/).length).toBeGreaterThan(0); + expect(changeLines().some((line) => line.includes('Prospecting → Negotiation'))).toBe(true); + expect(changeLines().some((line) => line.includes('100 → 250'))).toBe(true); expect(screen.queryByText('Kick-off note')).toBeNull(); expect(screen.queryByText('Updated the deal')).toBeNull(); }); diff --git a/ui/packages/plugin-detail/src/renderers/__tests__/record-activity.test.tsx b/ui/packages/plugin-detail/src/renderers/__tests__/record-activity.test.tsx index 29816e6c916..a8028b156e7 100644 --- a/ui/packages/plugin-detail/src/renderers/__tests__/record-activity.test.tsx +++ b/ui/packages/plugin-detail/src/renderers/__tests__/record-activity.test.tsx @@ -38,7 +38,8 @@ import { render, screen, waitFor, cleanup, fireEvent } from '@testing-library/re import { RecordContextProvider, DiscussionContextProvider } from '@object-ui/react'; import type { FeedItem } from '@object-ui/types'; import { RecordActivityRenderer } from '../record-activity'; -import { resetWithheldCommentComposerWarnings } from '../recordActivityFeed'; +import { activityRowToFeedItem, resetWithheldCommentComposerWarnings } from '../recordActivityFeed'; +import { RecordActivityTimeline } from '../../RecordActivityTimeline'; const COMPOSER_PLACEHOLDER = 'Leave a comment… (Ctrl+Enter to submit)'; const EMPTY_FEED = 'No activity recorded'; @@ -427,3 +428,182 @@ describe('record:activity — a types list without comment offers no comment com expect(withheldWarnings()).toHaveLength(0); }); }); + +describe('record:activity — one line per changed field, old → new (objectstack#36290)', () => { + /** An `updated` row as plugin-audit serves it: the summary, and the field-change code narrowed to this reader. */ + const updatedRow = ( + id: string, + changes: Array<{ field: string; from: Record; to: Record }>, + extra: Record = {}, + ) => ({ + id, + type: 'updated', + summary: 'stored summary', + timestamp: '2026-11-20T09:00:00.000Z', + actor_name: 'Grace', + metadata: JSON.stringify({ summary_message: { key: 'fieldChanges', object: 'crm_account', changes } }), + ...extra, + }); + const SCHEMA = { + name: 'crm_account', + fields: { + notes: { type: 'textarea', label: 'Customer notes' }, + phone: { type: 'phone', label: 'Phone' }, + email: { type: 'email', label: 'Email' }, + stage: { + type: 'select', + label: 'Stage', + options: [ + { value: 'prospect', label: 'Prospect' }, + { value: 'won', label: 'Closed won' }, + ], + }, + parent_id: { type: 'lookup', label: 'Parent account' }, + owner_id: { type: 'user', label: 'Owner' }, + vip: { type: 'boolean', label: 'VIP' }, + }, + }; + const mount = (rows: unknown[]) => + render( + + + , + ); + const linesOf = (container: HTMLElement) => + Array.from(container.querySelectorAll('[data-stream-field-change] [data-field-change]')).map((line) => ({ + field: line.getAttribute('data-field-change'), + label: line.querySelector('[data-field-change-label]')?.textContent, + old: line.querySelector('[data-field-change-side="old"]')?.textContent, + new: line.querySelector('[data-field-change-side="new"]')?.textContent, + text: line.textContent, + })); + + it('a save that changed one field: the entry, and under it `Label: old → new`', async () => { + const { container } = mount([ + updatedRow('a1', [{ field: 'notes', from: { text: 'Old words' }, to: { text: 'New words' } }]), + ]); + await waitFor(() => expect(container.querySelector('[data-stream-field-change]')).not.toBeNull()); + expect(container.querySelectorAll('[data-stream-system-row]')).toHaveLength(1); + expect(linesOf(container)).toEqual([ + { field: 'notes', label: 'Customer notes:', old: 'Old words', new: 'New words', text: 'Customer notes: Old words → New words' }, + ]); + }); + + it('one save that changed the phone and the email: ONE entry, two lines under it', async () => { + const { container } = mount([ + updatedRow('a2', [ + { field: 'phone', from: { text: '111' }, to: { text: '222' } }, + { field: 'email', from: { text: 'a@x.io' }, to: { text: 'b@x.io' } }, + ]), + ]); + await waitFor(() => expect(container.querySelectorAll('[data-stream-field-change]')).toHaveLength(2)); + const entries = container.querySelectorAll('[data-stream-system-row]'); + expect(entries).toHaveLength(1); + // The entry is ONE row: its line and the field lines under it. + expect(container.querySelectorAll('[data-stream-row]')).toHaveLength(1); + expect(entries[0].hasAttribute('data-stream-row')).toBe(true); + expect(entries[0].querySelectorAll('[data-stream-field-change]')).toHaveLength(2); + expect(entries[0].querySelector('[data-stream-change]')?.textContent).toBe('Updated Phone, Email'); + expect(linesOf(container).map((l) => [l.field, l.old, l.new])).toEqual([ + ['phone', '111', '222'], + ['email', 'a@x.io', 'b@x.io'], + ]); + }); + + it('an empty side reads as the word for empty, never the writer\'s `∅`', async () => { + const { container } = mount([updatedRow('a3', [{ field: 'phone', from: { text: '∅' }, to: { text: '222' } }])]); + await waitFor(() => expect(container.querySelector('[data-field-change]')).not.toBeNull()); + const old = container.querySelector('[data-field-change-side="old"]')!; + expect(old.textContent).toBe('Empty'); + expect(old.hasAttribute('data-field-change-empty')).toBe(true); + expect(container.textContent).not.toContain('∅'); + }); + + it('an option, a lookup and a user read as the option label and the record names, never the stored ids', async () => { + const { container } = mount([ + updatedRow('a4', [ + { field: 'stage', from: { text: 'Prospect', option: 'prospect' }, to: { text: 'Won', option: 'won' } }, + { field: 'parent_id', from: { text: '∅' }, to: { text: 'Acme Corp' } }, + { field: 'owner_id', from: { text: 'Ada Lovelace' }, to: { text: 'Grace Hopper' } }, + { field: 'vip', from: { text: 'No', boolean: false }, to: { text: 'Yes', boolean: true } }, + ]), + ]); + await waitFor(() => expect(container.querySelectorAll('[data-field-change]')).toHaveLength(4)); + expect(linesOf(container).map((l) => [l.label, l.old, l.new])).toEqual([ + // The field's option label as the page reads it, not the label the writer stored. + ['Stage:', 'Prospect', 'Closed won'], + ['Parent account:', 'Empty', 'Acme Corp'], + ['Owner:', 'Ada Lovelace', 'Grace Hopper'], + ['VIP:', 'No', 'Yes'], + ]); + expect(container.textContent).not.toMatch(/\bwon\b|prospect/); + }); + + it('draws only the changes the server served: a field the reader may not read has no line', async () => { + // The row's stored change touched `phone` and `salary`; the reader is not + // served `salary`, so plugin-audit's redaction left its change out of the code. + const { container } = mount([ + updatedRow('a5', [{ field: 'phone', from: { text: '111' }, to: { text: '222' } }], { changed_fields: ['phone'] }), + ]); + await waitFor(() => expect(container.querySelector('[data-field-change]')).not.toBeNull()); + expect(linesOf(container).map((l) => l.field)).toEqual(['phone']); + expect(container.querySelector('[data-field-change="salary"]')).toBeNull(); + }); + + it('a long value is cut to its line, with a control that shows it in full and clamps it again', async () => { + const long = 'A long note that runs well past one line of the activity column, and then some more.'; + const { container } = mount([updatedRow('a6', [{ field: 'notes', from: { text: 'Short' }, to: { text: long } }])]); + await waitFor(() => expect(container.querySelector('[data-field-change]')).not.toBeNull()); + const line = container.querySelector('[data-field-change="notes"]')!; + const side = line.querySelector('[data-field-change-side="new"]')!; + expect(side.className).toContain('truncate'); + const toggle = line.querySelector('[data-field-change-toggle]') as HTMLButtonElement; + expect(toggle.getAttribute('aria-expanded')).toBe('false'); + expect(toggle.textContent).toBe('Show all'); + fireEvent.click(toggle); + expect(toggle.getAttribute('aria-expanded')).toBe('true'); + expect(toggle.textContent).toBe('Show less'); + expect(side.className).toContain('whitespace-pre-wrap'); + expect(side.className).not.toContain('truncate'); + expect(side.textContent).toBe(long); + }); + + it('the 动态 stream: two saves by one person on one day fold, and each save opens to its own lines', () => { + const at = (minute: number) => { + const d = new Date(); + d.setHours(9, minute, 0, 0); + return d.toISOString(); + }; + const items = [ + updatedRow('s1', [{ field: 'phone', from: { text: '111' }, to: { text: '222' } }], { timestamp: at(5) }), + updatedRow('s2', [ + { field: 'notes', from: { text: '∅' }, to: { text: 'First note' } }, + { field: 'email', from: { text: 'a@x.io' }, to: { text: 'b@x.io' } }, + ], { timestamp: at(4) }), + ].map((row) => activityRowToFeedItem(row, 'System')!); + const { container } = render(); + const fold = container.querySelector('[data-testid="activity-fold"]')!; + expect(fold.getAttribute('data-fold-count')).toBe('2'); + fireEvent.click(fold.querySelector('button[aria-expanded]')!); + const rows = Array.from(container.querySelectorAll('[data-testid="activity-fold-entries"] [data-stream-row]')); + expect(rows.map((row) => row.querySelectorAll('[data-stream-field-change]').length)).toEqual([1, 2]); + expect(rows[1].querySelector('[data-field-change="notes"]')?.textContent).toBe('notes: Empty → First note'); + }); + + it('CONTROL — a short value offers no control, and a row with no served code draws its summary as before', async () => { + const { container } = mount([ + updatedRow('a7', [{ field: 'phone', from: { text: '111' }, to: { text: '222' } }]), + { id: 'a8', type: 'updated', summary: 'Stage: draft to qualified', timestamp: '2026-11-19T09:00:00.000Z', actor_name: 'Ada' }, + ]); + await waitFor(() => expect(container.querySelector('[data-field-change]')).not.toBeNull()); + expect(container.querySelector('[data-field-change-toggle]')).toBeNull(); + expect(screen.getByText('Stage: draft to qualified')).toBeTruthy(); + expect(container.querySelectorAll('[data-stream-field-change]')).toHaveLength(1); + }); +}); diff --git a/ui/packages/plugin-detail/src/renderers/__tests__/recordActivityFeed.test.ts b/ui/packages/plugin-detail/src/renderers/__tests__/recordActivityFeed.test.ts index 33d31184485..85041f293e2 100644 --- a/ui/packages/plugin-detail/src/renderers/__tests__/recordActivityFeed.test.ts +++ b/ui/packages/plugin-detail/src/renderers/__tests__/recordActivityFeed.test.ts @@ -21,6 +21,7 @@ import type { FeedItem } from '@object-ui/types'; import { ACTIVITY_TYPE_TO_FEED_TYPE, DEFAULT_ACTIVITY_LIMIT, + activityFieldChangesOf, activityRowToFeedItem, activityTimestamp, applyFeedConfig, @@ -974,3 +975,54 @@ describe('an unrecognised `filterMode` still folds onto `all`, but says so (obje resetUnrecognisedFeedTypeWarnings(); }); }); + +describe('activityFieldChangesOf — the served field-change code as one entry per field (objectstack#36290)', () => { + const rowWith = (code: unknown, extra: Record = {}) => ({ + id: 'r1', + type: 'updated', + metadata: JSON.stringify({ summary_message: code, ...extra }), + }); + const code = (changes: unknown) => ({ key: 'fieldChanges', object: 'crm_account', changes }); + + it('maps each change: text, option, yes/no, and the writer\'s empty mark', () => { + expect( + activityFieldChangesOf( + rowWith( + code([ + { field: 'notes', from: { text: 'Old' }, to: { text: 'New' } }, + { field: 'stage', from: { text: 'Prospect', option: 'prospect' }, to: { text: '∅' } }, + { field: 'vip', from: { text: 'No', boolean: false }, to: { text: '' } }, + ]), + ), + ), + ).toEqual([ + { field: 'notes', oldValue: 'Old', newValue: 'New', oldDisplayValue: 'Old', newDisplayValue: 'New' }, + { field: 'stage', oldValue: 'prospect', newValue: null, oldDisplayValue: 'Prospect', oldOption: 'prospect' }, + { field: 'vip', oldValue: false, newValue: null }, + ]); + }); + + it('rides onto the feed item, beside the summary', () => { + const fed = activityRowToFeedItem( + { ...rowWith(code([{ field: 'phone', from: { text: '1' }, to: { text: '2' } }])), summary: 'Phone: 1 → 2' }, + 'System', + ); + expect(fed?.body).toBe('Phone: 1 → 2'); + expect(fed?.fieldChanges).toEqual([ + { field: 'phone', oldValue: '1', newValue: '2', oldDisplayValue: '1', newDisplayValue: '2' }, + ]); + }); + + it('gives nothing for a row with no code, another code, or a code it cannot read whole', () => { + expect(activityFieldChangesOf({ id: 'r', type: 'updated' })).toBeUndefined(); + expect(activityFieldChangesOf({ id: 'r', type: 'updated', metadata: 'not json' })).toBeUndefined(); + expect(activityFieldChangesOf(rowWith({ key: 'activityUpdated', object: 'crm_account', label: 'A' }))).toBeUndefined(); + expect(activityFieldChangesOf(rowWith(code([])))).toBeUndefined(); + expect( + activityFieldChangesOf( + rowWith(code([{ field: 'a', from: { text: '1' }, to: { text: '2' } }, { field: 'b', from: { text: 1 }, to: { text: '2' } }])), + ), + ).toBeUndefined(); + expect(activityRowToFeedItem({ id: 'r', type: 'updated', summary: 's' }, 'System')).not.toHaveProperty('fieldChanges'); + }); +}); diff --git a/ui/packages/plugin-detail/src/renderers/recordActivityFeed.ts b/ui/packages/plugin-detail/src/renderers/recordActivityFeed.ts index 3ac7a17b9be..3f2abc9af0e 100644 --- a/ui/packages/plugin-detail/src/renderers/recordActivityFeed.ts +++ b/ui/packages/plugin-detail/src/renderers/recordActivityFeed.ts @@ -41,7 +41,7 @@ import { FeedFilterMode as FeedFilterModeEnum, FeedItemType as FeedItemTypeEnum import { RECORD_TIMELINE_UNDRAWN_ACTIVITY_TYPES } from '@objectstack/spec/api'; import { classifyLoadError } from '@object-ui/react'; import { recordDisplayValueAt, resolveNameField } from '@object-ui/core'; -import type { FeedItem, FeedItemType } from '@object-ui/types'; +import type { FeedItem, FeedItemType, FieldChangeEntry } from '@object-ui/types'; import type { FeedFilterMode } from '../RecordActivityTimeline'; const FILTER_MODE_VALUES: readonly string[] = FeedFilterModeEnum.options; @@ -449,6 +449,94 @@ function activityChangedFields(row: SysActivityRow): string[] | undefined { return raw.filter((f): f is string => typeof f === 'string' && f.length > 0); } +/** + * One changed field of an activity row (objectstack#36290): a + * {@link FieldChangeEntry} as the served change code gives it, plus the option + * each side matched. The timeline words each side from these facts in the + * reader's language: the option by the field's option label, a yes/no + * (`oldValue` / `newValue` a boolean, no display text) by the pack's word, and + * an empty side (`null`, no display text) by the pack's word for empty. + * Package-local hand-off: written by {@link activityFieldChangesOf}, read by + * `RecordActivityTimeline`, never authored. + */ +export interface ActivityFieldChange extends FieldChangeEntry { + oldOption?: string; + newOption?: string; +} + +/** + * How plugin-audit writes an empty side of a change into the change code: the + * writer's `summaryValueOf` renders a null, undefined or `''` value as this + * text (`packages/plugins/plugin-audit/src/audit-writers.ts`), and the code + * carries no other mark for it. + */ +const WRITER_EMPTY_VALUE_TEXT = '∅'; + +/** One side of a served change: `{ text, option?, boolean? }`, or `null` when it is not that shape. */ +function servedChangeSide(value: unknown): { value: unknown; display?: string; option?: string } | null { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return null; + const { text, option, boolean } = value as { text?: unknown; option?: unknown; boolean?: unknown }; + if (typeof text !== 'string') return null; + if (option !== undefined && typeof option !== 'string') return null; + if (boolean !== undefined && typeof boolean !== 'boolean') return null; + if (typeof option === 'string') return { value: option, display: text, option }; + if (typeof boolean === 'boolean') return { value: boolean }; + if (text === '' || text === WRITER_EMPTY_VALUE_TEXT) return { value: null }; + return { value: text, display: text }; +} + +/** + * The changed fields of a `sys_activity` row, one entry per field, from the + * field-change code plugin-audit serves in `metadata.summary_message` + * (`{ key: 'fieldChanges', object, changes: [{ field, from, to }] }`), or + * `undefined` when the row carries none. + * + * The server narrows that code to the reader before it is served + * (objectstack#36290, plugin-audit `activity-field-redaction.ts`): a change of + * a field the reader may not read is dropped, and a reference field's change + * is kept only for a reader served the referenced record's title. So this + * reads the changes it is handed and adds none; the record page draws one line + * for each of them. A reference side's text is the record's title the writer + * read, and an option side names the option it matched. + * + * Read from the `metadata` JSON string only, as {@link activityKindOf} reads + * the kind. A code this version cannot read whole (any change not of the + * shape above) gives `undefined`, and the row draws its summary as before. + */ +export function activityFieldChangesOf(row: SysActivityRow): ActivityFieldChange[] | undefined { + const raw = row?.metadata; + if (typeof raw !== 'string') return undefined; + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return undefined; + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return undefined; + const code = (parsed as { summary_message?: unknown }).summary_message; + if (typeof code !== 'object' || code === null || Array.isArray(code)) return undefined; + const { key, changes } = code as { key?: unknown; changes?: unknown }; + if (key !== 'fieldChanges' || !Array.isArray(changes) || changes.length === 0) return undefined; + const out: ActivityFieldChange[] = []; + for (const change of changes) { + if (typeof change !== 'object' || change === null) return undefined; + const { field, from, to } = change as { field?: unknown; from?: unknown; to?: unknown }; + const before = servedChangeSide(from); + const after = servedChangeSide(to); + if (typeof field !== 'string' || !field || !before || !after) return undefined; + out.push({ + field, + oldValue: before.value, + newValue: after.value, + ...(before.display !== undefined ? { oldDisplayValue: before.display } : {}), + ...(after.display !== undefined ? { newDisplayValue: after.display } : {}), + ...(before.option !== undefined ? { oldOption: before.option } : {}), + ...(after.option !== undefined ? { newOption: after.option } : {}), + }); + } + return out; +} + /** A row as `sys_activity` returns it. Loose on purpose: the block reads a * system table it does not own, and an unknown column is not an error. */ export interface SysActivityRow { @@ -1102,6 +1190,7 @@ export function activityRowToFeedItem( ? MILESTONE_ACTIVITY_FEED_TYPE : mapped; const changedFields = activityChangedFields(row); + const fieldChanges = activityFieldChangesOf(row); const recordFacts = activityRecordFacts(row); const item: FeedItem & ActivityRecordFacts = { id: row.id as string | number, @@ -1125,6 +1214,9 @@ export function activityRowToFeedItem( ...(activityKind ? { activityKind } : {}), actorId: activityActorId(row), ...(changedFields ? { changedFields } : {}), + // Each changed field with its before and after values, as served to this + // reader (objectstack#36290). See `activityFieldChangesOf`. + ...(fieldChanges ? { fieldChanges } : {}), // Which record the summary names, and by what name, as stored // (objectstack#29962). See `withReaderRecordName`. ...recordFacts, diff --git a/ui/packages/plugin-detail/src/useDetailTranslation.ts b/ui/packages/plugin-detail/src/useDetailTranslation.ts index f7865120bb5..52d63a6ab67 100644 --- a/ui/packages/plugin-detail/src/useDetailTranslation.ts +++ b/ui/packages/plugin-detail/src/useDetailTranslation.ts @@ -278,6 +278,11 @@ export const DETAIL_DEFAULT_TRANSLATIONS: Record = { 'detail.foldedMoreFields_other': '{{count}} more', 'detail.expandFolded': 'Show each update', 'detail.collapseFolded': 'Hide updates', + // objectstack#36290 — the per-field lines under an activity entry. + 'detail.fieldChangeLabel': '{{field}}:', + 'detail.fieldChangeEmpty': 'Empty', + 'detail.fieldChangeExpand': 'Show all', + 'detail.fieldChangeCollapse': 'Show less', // …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': ', ',