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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .changeset/33827-record-page-save-answer.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/app-shell': patch
---

fix(app-shell): the record page shows a save's new values as soon as the save succeeds

Clause-②: no
Metadata-protocol: none

After a save through the edit dialog (or any other update of the record), the record page and the record drawer kept showing the old field values until the page read the record again, a read that goes out beside the page's other post-save reads and could take seconds, while the "updated" toast was already on screen. The page now lays the save's own answer, the record as the server holds it after the write, over the record it shows, in the same moment the write lands, so the new values are on screen when the toast appears. The re-read still runs and then replaces the record as before. A related record the page shows by name keeps its name when the save did not change it; one the save changed shows its new value at once and its name when the re-read answers.
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,10 @@ function pageAnswer(id: string, body: any, answers: Answers) {
}

function answerFor(h: Held, answers: Answers): unknown {
if (h.method === 'PATCH') return { success: true, data: { object: OBJECT, id: 'c1', record: { id: 'c1', name: 'Contact c1', account: 'a1', ...h.body } } };
if (h.method === 'PATCH') {
const id = h.path.slice(h.path.lastIndexOf('/') + 1);
return { success: true, data: { object: OBJECT, id, record: { id, name: `Contact ${id}`, account: 'a1', ...h.body } } };
}
const meta = /\/api\/v1\/meta\/object\/([^/?]+)/.exec(h.path);
if (meta) return { success: true, data: ALL.find((o) => o.name === meta[1]) ?? null };
const page = /\/api\/v1\/data\/[^/?]+\/([^/?]+)\/page$/.exec(h.path);
Expand Down Expand Up @@ -366,3 +369,46 @@ describe('objectstack#30035 — the 动态 stream is read again after a save', (
expect(held.slice(before).filter(isPage)).toEqual([]);
});
});

/**
* objectstack#33827 — a save through the edit dialog draws the saved values
* from the save's own answer, by the time the save resolves (the moment the
* dialog's success toast shows), while every read the save triggers is still
* on the wire. The re-read still goes out (objectstack#30035 above).
*/
describe('objectstack#33827 — the saved values are on screen when the save resolves', () => {
const isPatch = (h: Held) => h.method === 'PATCH';

async function saveWithReadsHeld(embedded: boolean, id = 'c1') {
const { held, open, ds } = await boot({ activity: { total: 1, records: [ACTIVITY] }, timeline: { total: 2 } }, undefined, ALL, embedded);
const view = open();
await settle(held);
expect(view.container.textContent).toContain('Contact c1');
expect(view.container.textContent).not.toContain('Renamed');
const before = held.length;

const saved = ds.update(OBJECT, id, { name: 'Renamed' });
await idle();
const patch = held.slice(before).filter(isPatch);
expect(patch).toHaveLength(1);
await act(async () => { patch[0].release(); await saved; });
const reads = held.slice(before).filter((h) => !isPatch(h) && !isMeta(h));
return { view, reads };
}

for (const [surface, embedded] of [['the record page', false], ['the drawer', true]] as const) {
it(`${surface}: the saved value is drawn when the save resolves, with every re-read still held`, async () => {
const { view, reads } = await saveWithReadsHeld(embedded);
// The save did trigger the re-read, and nothing it asked has answered.
expect(reads.length).toBeGreaterThan(0);
expect(reads.every((h) => !h.released)).toBe(true);
expect(view.container.textContent).toContain('Renamed');
});
}

it('a save to another record of the object leaves this one as it is', async () => {
const { view } = await saveWithReadsHeld(false, 'c2');
expect(view.container.textContent).not.toContain('Renamed');
expect(view.container.textContent).toContain('Contact c1');
});
});
18 changes: 18 additions & 0 deletions ui/packages/app-shell/src/views/RecordDetailView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import {
seedRecordPageReaders,
type RecordPageStreamsAsk,
} from './recordPagePayload.js';
import { applySavedRecordEcho } from './recordSaveEcho.js';
import { withPageTabsUrlSync } from '../utils/pageTabsUrlSync.js';
import { RECORD_DETAIL_TAB_PARAM, RECORD_DRAWER_PARAM, RECORD_RELATED_ENLARGE_PARAM, RECORD_RELATED_ENLARGE_PUSHED_STATE as RELATED_ENLARGE_PUSHED, RECORD_TRAIL_PARAM, decodeRecordTrail, buildRecordTrailHref } from '../urlParams.js';
import { resolveActionParams } from '@object-ui/fields';
Expand Down Expand Up @@ -1491,6 +1492,23 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri
// above instead (AGENTS.md #10).
}, [hasPage, objectName, pureRecordId, dataSource, pageRecordExpand, recordInvalidationNonce, childInvalidationNonce]);

// objectstack#33827 — a save to THIS record draws its saved values from the
// save's own answer, not from the re-read above. The adapter hands the answer
// over with the write's MutationEvent, in the same dispatch that invalidates
// the record on the bus and before the write's promise resolves, so the page
// already holds the saved record when the save's success toast shows. The
// re-read still runs and replaces it whole (expanded relations, anything the
// answer leaves out); `applySavedRecordEcho` says what the answer may change.
useEffect(() => {
if (!hasPage || !objectName || !pureRecordId || typeof dataSource?.onMutation !== 'function') return;
const object = objectName.toLowerCase();
return dataSource.onMutation((e: { type?: string; resource?: string; id?: string | number; record?: unknown }) => {
if (e?.type !== 'update' || e.id == null || String(e.id) !== pureRecordId) return;
if (String(e.resource ?? '').toLowerCase() !== object) return;
setPageRecord((held: unknown) => applySavedRecordEcho(held, e.record, pureRecordId));
});
}, [hasPage, dataSource, objectName, pureRecordId]);

// The loaded record AS THE VIEWER MAY READ IT (objectui#10434,
// objectui#10499): `withoutDeniedFields` removes the fields the loaded
// policy denies on this object, `id` kept, which leaves the row
Expand Down
64 changes: 64 additions & 0 deletions ui/packages/app-shell/src/views/recordSaveEcho.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* ObjectUI
* Copyright (c) 2024-present ObjectStack Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

/**
* objectstack#33827 — what a save's answer may change on the record the page
* holds. The page-level pin (the saved value drawn when the save resolves) is
* in `RecordDetailView.timelineCount-28737.test.tsx`.
*/
import { describe, it, expect } from 'vitest';
import { applySavedRecordEcho } from './recordSaveEcho';

const held = {
id: 'r1',
name: 'Initech',
phone: null,
owner: { id: 'u1', name: 'Dev Admin' },
tags: [{ id: 't1', name: 'Gold' }, { id: 't2', name: 'Key' }],
score: 3,
};

describe('applySavedRecordEcho', () => {
it('takes the saved values and keeps a key the answer leaves out', () => {
const next = applySavedRecordEcho(held, { id: 'r1', name: 'Initech', phone: '021-55550100' }, 'r1');
expect(next).toEqual({ ...held, phone: '021-55550100' });
expect(held.phone).toBeNull();
});

it('keeps a relation the page read expanded when the answer names the same record', () => {
const next = applySavedRecordEcho(held, { id: 'r1', owner: 'u1', tags: ['t1', 't2'], score: 4 }, 'r1');
expect(next.owner).toBe(held.owner);
expect(next.tags).toBe(held.tags);
expect(next.score).toBe(4);
});

it('takes a relation the save changed', () => {
const next = applySavedRecordEcho(held, { id: 'r1', owner: 'u2', tags: ['t1'] }, 'r1');
expect(next.owner).toBe('u2');
expect(next.tags).toEqual(['t1']);
});

it('hands back the held object itself when the answer changes nothing', () => {
expect(applySavedRecordEcho(held, { id: 'r1', name: 'Initech', owner: 'u1' }, 'r1')).toBe(held);
});

it('takes nothing from an answer that does not name this record', () => {
expect(applySavedRecordEcho(held, { id: 'r2', name: 'Other' }, 'r1')).toBe(held);
expect(applySavedRecordEcho(held, { name: 'No id' }, 'r1')).toBe(held);
expect(applySavedRecordEcho(held, undefined, 'r1')).toBe(held);
expect(applySavedRecordEcho(held, ['r1'], 'r1')).toBe(held);
});

it('reads `_id` as the record id', () => {
expect(applySavedRecordEcho(held, { _id: 'r1', name: 'Renamed' }, 'r1').name).toBe('Renamed');
});

it('lays nothing over a record that has not loaded', () => {
expect(applySavedRecordEcho(null, { id: 'r1', name: 'Initech' }, 'r1')).toBeNull();
});
});
69 changes: 69 additions & 0 deletions ui/packages/app-shell/src/views/recordSaveEcho.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/**
* 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.
*/

/**
* The record a save answered, laid over the record the page holds
* (objectstack#33827).
*
* A write's MutationEvent carries the server's answer to it — the record as
* the server now holds it, field-masked for the caller like any read. The
* record page draws the saved values from that answer the moment the write
* lands, so the page and the save's success toast agree; the re-read the same
* write triggers still runs and replaces the result whole.
*
* Invariants:
*
* - An answer that does not name this record (`id`, or `_id`, equal to it) is
* not taken: the page keeps what it holds and waits for its re-read.
* - Nothing loaded yet ⇒ nothing to lay the answer over: the load answers.
* - A key the answer does not carry keeps the held value (the re-read settles
* it).
* - A relation the page read EXPANDED (`{ id, name, … }`) and the answer gives
* back as the same bare id keeps the expanded value, so a save that did not
* touch it never trades the related record's name for its id. A relation the
* save CHANGED takes the answer's value.
* - When the answer changes nothing the held object itself comes back, so an
* equal answer never republishes the record as a new object (ui/AGENTS.md
* #10).
*/
export function applySavedRecordEcho<R>(held: R, answer: unknown, recordId: string): R {
if (!held || typeof held !== 'object' || !isRecordObject(answer)) return held;
const answerId = answer.id ?? answer._id;
if (answerId == null || String(answerId) !== recordId) return held;

const base = held as unknown as Record<string, unknown>;
let next: Record<string, unknown> | null = null;
for (const [key, value] of Object.entries(answer)) {
const current = base[key];
if (Object.is(current, value) || sameReference(current, value)) continue;
next ??= { ...base };
next[key] = value;
}
return (next ?? held) as R;
}

function isRecordObject(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === 'object' && !Array.isArray(value);
}

function idOf(value: unknown): unknown {
return isRecordObject(value) ? value.id ?? value._id : undefined;
}

function sameId(expanded: unknown, bare: unknown): boolean {
const id = idOf(expanded);
return id != null && (typeof bare === 'string' || typeof bare === 'number') && String(id) === String(bare);
}

/** True when `held` is the expanded form of the reference(s) `answer` names. */
function sameReference(held: unknown, answer: unknown): boolean {
if (Array.isArray(held) && Array.isArray(answer)) {
return held.length === answer.length && held.every((h, i) => sameId(h, answer[i]));
}
return sameId(held, answer);
}
Loading