Skip to content
10 changes: 10 additions & 0 deletions .changeset/36822-related-list-zero-badge-refetch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'@object-ui/plugin-detail': patch
---

fix(plugin-detail): a related list that already shows 0 keeps showing 0 while it reloads

Clause-②: no
Metadata-protocol: none

A related list on a record page whose count was known to be 0 used to drop its count badge for as long as a reload took (after a delete, a filter change or any other refetch), because an empty list being read looked like a list read for the first time. Once a read the list issued has answered, its count is known, so a later reload keeps drawing that count until the new one lands. A read that fails forgets the count, so its Retry draws no count until it answers, never a false 0; so do rows emptied without a read (the parent record reloading, or no data adapter), so the next parent's read draws no count either. A list's first read, including one that starts only once its parent record has loaded, still draws no count while it is in flight.
25 changes: 24 additions & 1 deletion ui/packages/plugin-detail/src/RelatedList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1515,6 +1515,15 @@ export const RelatedList: React.FC<RelatedListProps> = ({
// value may itself be falsy. Cleared by every re-read (the fetch effect's
// first statement) and by Retry.
const [loadFailure, setLoadFailure] = React.useState<{ error: unknown } | null>(null);
// objectstack#36822 — whether `relatedData` holds the answer of a read this
// list actually issued, so the badge may keep drawing its count while a
// later read is in flight. Set only where an issued read resolves, cleared
// where one rejects (the rejection empties the rows, and 0 is not their
// count). A path that reads nothing (no scope yet, a refused filter, no
// adapter) never sets it, so the first real read still draws no count; one
// that empties the rows without reading (no scope, no adapter) clears it,
// so the next parent's read draws no count either.
const [countKnown, setCountKnown] = React.useState(false);
// Per-lookup-field cache of resolved labels: fieldName -> Map<id, label>
const [lookupLabels, setLookupLabels] = React.useState<Record<string, Record<string, string>>>({});
const { t } = useDetailTranslation();
Expand Down Expand Up @@ -2249,6 +2258,8 @@ export const RelatedList: React.FC<RelatedListProps> = ({
setRelatedData([]);
setTotal(null);
setHasMore(false);
// Nothing is read, and the emptied rows hold no count (objectstack#36822).
setCountKnown(false);
setLoading(false);
return;
}
Expand Down Expand Up @@ -2280,13 +2291,15 @@ export const RelatedList: React.FC<RelatedListProps> = ({
setRelatedData(result.rows as any[]);
setTotal(result.total);
setHasMore(result.total > result.rows.length);
setCountKnown(true);
setLoading(false);
},
(err) => {
if (cancelled) return;
setRelatedData([]);
setTotal(null);
setHasMore(false);
setCountKnown(false);
setLoadFailure({ error: err });
setLoading(false);
},
Expand Down Expand Up @@ -2380,6 +2393,7 @@ export const RelatedList: React.FC<RelatedListProps> = ({
setTotal(null);
setHasMore(false);
}
setCountKnown(true);
setLoading(false);
}).catch((err) => {
console.error('Failed to fetch related data:', err);
Expand All @@ -2389,6 +2403,7 @@ export const RelatedList: React.FC<RelatedListProps> = ({
setRelatedData([]);
setTotal(null);
setHasMore(false);
setCountKnown(false);
setLoadFailure({ error: err });
setLoading(false);
});
Expand All @@ -2406,6 +2421,7 @@ export const RelatedList: React.FC<RelatedListProps> = ({
setRelatedData([]);
setTotal(null);
setHasMore(false);
setCountKnown(false);
setLoading(false);
} else if (referenceFieldIsMultiValue) {
// The same refusal as the arm above, one cause earlier: this path's
Expand All @@ -2432,6 +2448,7 @@ export const RelatedList: React.FC<RelatedListProps> = ({
setRelatedData([]);
setTotal(null);
setHasMore(false);
setCountKnown(false);
setLoading(false);
} else {
const qs = new URLSearchParams({
Expand All @@ -2451,13 +2468,15 @@ export const RelatedList: React.FC<RelatedListProps> = ({
setRelatedData(items);
setTotal(null);
setHasMore(false);
setCountKnown(true);
})
.catch(err => {
console.error('Failed to fetch related data:', err);
if (cancelled) return;
setRelatedData([]);
setTotal(null);
setHasMore(false);
setCountKnown(false);
setLoadFailure({ error: err });
})
.finally(() => { if (!cancelled) setLoading(false); });
Expand Down Expand Up @@ -4028,7 +4047,11 @@ export const RelatedList: React.FC<RelatedListProps> = ({
// the 0 an empty first read holds: while the first rows are in flight (or a
// card out of view has not asked) and no count answers for them, the badge
// waits. A refetch over rows already drawn keeps their count.
const countPending = !countAnswers && loading && relatedData.length === 0 && !(windowed && total != null);
// objectstack#36822 — and so does a refetch over a list that already
// answered 0: once a read has answered, the count is known (`countKnown`),
// so a later read in flight keeps drawing the last answer.
const countPending =
!countAnswers && loading && !countKnown && relatedData.length === 0 && !(windowed && total != null);
// In windowed mode an empty page beyond page 0 is a transient overflow (the
// step-back effect above corrects it), not an empty collection.
// A failed read is never empty: it draws its own line (objectstack#26415).
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,166 @@ describe('a related list\'s count before it is known (objectstack#36235)', () =>
await waitFor(() => expect(cardCount()).toBe('2'));
});
});

/**
* objectstack#36822 — a refetch over a list whose count is already known keeps
* drawing that count. A list that answered 0 used to blank its badge for the
* length of the refetch, because an empty list in flight read as a first read.
*/
describe('a related list\'s count across a refetch (objectstack#36822)', () => {
/** Every badge reading the DOM goes through, from now until `stop()`. */
function watchBadge() {
const seen: Array<string | null> = [headBadge()];
const observer = new MutationObserver(() => seen.push(headBadge()));
observer.observe(document.body, { subtree: true, childList: true, characterData: true, attributes: true });
return { seen, stop: () => observer.disconnect() };
}

const refetch = () =>
act(async () => {
window.dispatchEvent(new CustomEvent('objectui:related-changed', { detail: { objectName: 'contact' } }));
});

it('a list that answered 0 keeps drawing 0 through a refetch that answers no rows', async () => {
const read = deferredFind();
renderList(read.find);
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(1));
await read.answer([]);
await waitFor(() => expect(headBadge()).toBe('0'));

const watch = watchBadge();
await refetch();
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(2));
await flush();
// The refetch is held in flight here: the badge still reads 0.
expect(headBadge()).toBe('0');
await read.answer([]);
await flush();
watch.stop();
expect(headBadge()).toBe('0');
expect(watch.seen.length).toBeGreaterThan(1);
expect(watch.seen.filter((v) => v !== '0')).toEqual([]);
});

it('a list that answered rows draws their count through a refetch, then the 0 it answers', async () => {
const read = deferredFind();
renderList(read.find);
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(1));
await read.answer(ROWS);
await waitFor(() => expect(headBadge()).toBe('2'));

const watch = watchBadge();
await refetch();
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(2));
await flush();
expect(headBadge()).toBe('2');
await read.answer([]);
await waitFor(() => expect(headBadge()).toBe('0'));
watch.stop();
expect(watch.seen.filter((v) => v !== '2' && v !== '0')).toEqual([]);
});

/** A `find` whose current read is answered or refused by hand. */
function heldFind() {
let settle = { resolve: (_: unknown) => {}, reject: (_: unknown) => {} };
const find = vi.fn(
() => new Promise((resolve, reject) => {
settle = { resolve, reject };
}),
);
return {
find,
answer: (rows: unknown[]) => act(async () => { settle.resolve({ data: rows, total: rows.length }); }),
fail: () => act(async () => { settle.reject(new Error('network down')); }),
};
}

it('a read that fails after rows were known draws no count while Retry reads, never a false 0', async () => {
const quiet = vi.spyOn(console, 'error').mockImplementation(() => {});
const read = heldFind();
renderList(read.find);
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(1));
await read.answer(ROWS);
await waitFor(() => expect(headBadge()).toBe('2'));

await refetch();
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(2));
await read.fail();
const retry = await waitFor(() => {
const button = document.querySelector('[data-testid="related-list-load-failed-retry"]');
expect(button).not.toBeNull();
return button as HTMLElement;
});
await act(async () => { retry.click(); });
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(3));
await flush();
// Retry's read is held in flight: the failed read emptied the rows, so
// their count is not known and the badge waits.
expect(document.querySelector('[data-related-list-head]')).not.toBeNull();
expect(headBadge()).toBeNull();
await read.answer([]);
await waitFor(() => expect(headBadge()).toBe('0'));
quiet.mockRestore();
});

it('a list with no scope on its first render draws no count during its first real read', async () => {
const read = heldFind();
const list = (parentId: string | null) => (
<RelatedList
title="Contacts"
type="table"
api="contact"
objectName="contact"
referenceField="account"
parentId={parentId as any}
columns={[{ accessorKey: 'name', header: 'Name' }]}
dataSource={{ find: read.find } as any}
/>
);
// The parent is still loading: no scope, so nothing is read.
const view = render(list(null));
await flush();
expect(read.find).not.toHaveBeenCalled();
// The parent lands: the first real read is held in flight.
view.rerender(list('ACC-1'));
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(1));
await flush();
expect(document.querySelector('[data-related-list-head]')).not.toBeNull();
expect(headBadge()).toBeNull();
await read.answer(ROWS);
await waitFor(() => expect(headBadge()).toBe('2'));
});

it('a list whose parent reloads through no scope draws no count during the new parent\'s read', async () => {
const read = heldFind();
const list = (parentId: string | null) => (
<RelatedList
title="Contacts"
type="table"
api="contact"
objectName="contact"
referenceField="account"
parentId={parentId as any}
columns={[{ accessorKey: 'name', header: 'Name' }]}
dataSource={{ find: read.find } as any}
/>
);
const view = render(list('ACC-1'));
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(1));
await read.answer(ROWS);
await waitFor(() => expect(headBadge()).toBe('2'));
// The parent reloads: no scope, so nothing is read and the rows empty.
view.rerender(list(null));
await flush();
expect(read.find).toHaveBeenCalledTimes(1);
// The new parent lands: its read is held in flight, and the emptied rows
// are no count of it.
view.rerender(list('ACC-2'));
await waitFor(() => expect(read.find).toHaveBeenCalledTimes(2));
await flush();
expect(document.querySelector('[data-related-list-head]')).not.toBeNull();
expect(headBadge()).toBeNull();
await read.answer([{ id: 'c3', name: 'Linus' }]);
await waitFor(() => expect(headBadge()).toBe('1'));
});
});
Loading