Skip to content
Merged
15 changes: 15 additions & 0 deletions .changeset/29235-sidebar-recents-labels-by-name.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@object-ui/app-shell': patch
---

perf(app-shell): the app sidebar and recent rows label their items by name

Clause-②: no
Metadata-protocol: none

Two label readers still downloaded a whole metadata list to name one row:

- Inside an app, a navigation entry with no label of its own read the whole object registry (`GET /api/v1/meta/object`, with the `/meta/view` list it is composed with) on every page whose route had not loaded it: the sidebar named it, and so did the closed command palette, which names every entry to build its lists. Both now resolve labels with `useNavTargetLabel({ byName: true })`: the entry's object by name, which the app bundle answers, and a dashboard entry the bundle does not hold by name too.
- A recent dashboard, page or report row (Home, the command palette, the sidebar's recent list) read its type's whole list. Each row now asks its own item through the provider's by-name read (`useReadItemsByName`, beside `readObjectsByName`).

Once something else has loaded a list, these readers read it and ask nothing more. The labels shown are unchanged, in every language, and an item that has not landed shows its machine name, as before.
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#29235 — the palette labels an unlabelled navigation entry by
* reading its target by name, never the whole object registry.
*
* Inside an app the console mounts the palette closed, and it names every
* entry of the app's navigation on each render to build its filtered lists.
* An entry with no label of its own is named through `useNavTargetLabel`
* (objectui#9868), which read `useMetadata().objects`: the whole object
* registry and the `/meta/view` list, on every in-app page whose route had
* not loaded them (551 KB on app-crm). Measured on a production Console, it
* was the reader left once the sidebar asked by name. It now asks with
* `{ byName: true }`, as the sidebar does.
*
* Real subjects: `CommandPalette`, `CommandPaletteProvider` and
* `MetadataProvider` over a fake adapter that records each read; the harness
* is `CommandPalette.recentReadsByName-29121`'s.
*/

import '@testing-library/jest-dom/vitest';
import * as React from 'react';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, cleanup, act, screen } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { createI18n, I18nProvider } from '@object-ui/i18n';
import { MetadataProvider } from '../providers/MetadataProvider';

vi.mock('@object-ui/auth', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useAuth: () => ({ user: { id: 'u1' }, activeOrganization: null }),
}));

vi.mock('../context/RecentItemsProvider', async (importOriginal) => ({
...(await importOriginal<Record<string, unknown>>()),
useRecentItems: () => ({ recentItems: [], addRecentItem: () => {}, clearRecentItems: () => {} }),
}));

vi.mock('../utils/getIcon', () => ({
getIcon: () =>
function StubIcon(props: { className?: string }) {
return <svg data-testid="stub-icon" className={props.className} />;
},
}));

import { CommandPalette } from './CommandPalette';
import { CommandPaletteProvider } from '../context/CommandPaletteProvider';

// An app written without entry labels, as the spec allows (objectui#9868).
const APP = {
name: 'ops',
label: 'Ops',
navigation: [
{ id: 'nav_accounts', type: 'object', objectName: 'crm_account' },
{ id: 'nav_contacts', type: 'object', objectName: 'crm_contact' },
],
};

const OBJECTS = [
{ name: 'crm_account', label: 'Account', fields: {} },
{ name: 'crm_contact', label: 'Contact', fields: {} },
{ name: 'crm_lead', label: 'Lead', fields: {} },
];

function makeAdapter(calls: string[]) {
return {
clearCache: vi.fn(),
invalidateCache: vi.fn(),
getObjectSchema(this: { getClient(): any }, name: string) {
return this.getClient()
.meta.getItem('object', name)
.then((res: any) => (res && typeof res === 'object' && 'item' in res ? res.item : res));
},
getClient: () => ({
meta: {
getItems: (type: string, options?: { packageId?: string }) => {
calls.push(options?.packageId ? `${type}?package=${options.packageId}` : type);
const items = type === 'object' ? OBJECTS : type === 'app' ? [APP] : [];
return Promise.resolve({ type, items: structuredClone(items) });
},
getItem: (type: string, name: string) => {
calls.push(`${type}/${name}`);
const item = (type === 'object' ? OBJECTS : []).find((o) => o.name === name) ?? null;
return Promise.resolve({ item: structuredClone(item) });
},
},
}),
} as unknown as Parameters<typeof MetadataProvider>[0]['adapter'];
}

/** The whole-list reads a label could cost: the object registry and its views. */
const listReads = (calls: string[]) => calls.filter((c) => c === 'object' || c === 'view');

function mount(path: string): string[] {
const calls: string[] = [];
render(
<I18nProvider instance={createI18n({ defaultLanguage: 'en', detectBrowserLanguage: false })} persistLanguage={false}>
<MemoryRouter initialEntries={[path]}>
<MetadataProvider adapter={makeAdapter(calls)}>
<CommandPaletteProvider>
<CommandPalette apps={[APP]} activeApp={APP} objects={[]} onAppChange={() => {}} />
</CommandPaletteProvider>
</MetadataProvider>
</MemoryRouter>
</I18nProvider>,
);
return calls;
}

const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 50)));

beforeEach(() => sessionStorage.clear());
afterEach(() => cleanup());

describe('objectstack#29235 — the palette names an unlabelled entry by name', () => {
it('closed inside an app: each entry’s object is read by name, never the whole list', async () => {
const calls = mount('/apps/ops/page/home');
await settle();
await settle();
expect(listReads(calls)).toEqual([]);
expect(calls.filter((c) => c.startsWith('object/')).sort()).toEqual(['object/crm_account', 'object/crm_contact']);
});

it('opened: the entries show their objects’ labels, as the whole list gave them', async () => {
const calls = mount('/apps/ops/page/home?palette=1');
expect(await screen.findByText('Account')).toBeInTheDocument();
expect(await screen.findByText('Contact')).toBeInTheDocument();
await settle();
expect(listReads(calls)).toEqual([]);
});
});
2 changes: 1 addition & 1 deletion ui/packages/app-shell/src/chrome/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ function CommandPaletteBody(props: CommandPaletteProps & { gates: NavMemberGates
// such entries through `useNavigationWrites`). A present
// label renders as authored — an inline locale map in the viewer's `language`,
// the locale the sidebar passes (objectui#11299).
const targetLabel = useNavTargetLabel();
const targetLabel = useNavTargetLabel(RECENT_ROW_LABELS);
const navLabel = (item: NavigationItem) =>
resolveNavItemLabel(item, t, targetLabel, language);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* objectstack#29235 — a recent dashboard, page or report row reads its item by
* name, never its type's whole list.
*
* `useRecentItemLabel` labelled those rows from `metadata.dashboards` (through
* `useNavTargetLabel`), `metadata.pages` and `metadata.reports`, so a Home with
* one such recent row downloaded the whole `/meta/dashboard`, `/meta/page` or
* `/meta/report` list for one label. Each row now asks its own item through
* the provider's by-name read (`useReadItemsByName`), and reads the list only
* once something else has loaded it.
*
* Real subjects: `useRecentItemLabel`, `MetadataProvider` and the i18n
* provider, over a fake adapter that records each read. What the rows print is
* pinned beside the reads: the same text the whole list gave, in en and in
* zh-CN (an inline locale map, and a translation bundle key), and the machine
* name while nothing has landed.
*/

import { describe, it, expect, vi, afterEach } from 'vitest';
import type { ReactNode } from 'react';
import { renderHook, waitFor, cleanup, act } from '@testing-library/react';
import { createI18n, I18nProvider } from '@object-ui/i18n';
import { useMetadata } from '@object-ui/react';
import { MetadataProvider } from '../../providers/MetadataProvider';
import { useRecentItemLabel } from '../useRecentItemLabel';
import type { RecentItem } from '../../context/RecentItemsProvider';

const ITEMS: Record<string, Array<Record<string, unknown>>> = {
dashboard: [
{ name: 'pipeline', label: 'Pipeline' },
{ name: 'other_dashboard', label: 'Other' },
],
page: [
{ name: 'welcome', label: { en: 'Welcome', 'zh-CN': '欢迎' } },
{ name: 'other_page', label: 'Other page' },
],
report: [
{ name: 'q3_results', label: 'Q3 Results' },
{ name: 'other_report', label: 'Other report' },
],
};

function makeAdapter(calls: string[]) {
return {
clearCache: vi.fn(),
invalidateCache: vi.fn(),
getClient: () => ({
meta: {
getItems: (type: string) => {
calls.push(type);
return Promise.resolve({ type, items: structuredClone(ITEMS[type] ?? []) });
},
getItem: (type: string, name: string) => {
calls.push(`${type}/${name}`);
const item = (ITEMS[type] ?? []).find((it) => it.name === name);
if (!item) return Promise.reject(Object.assign(new Error('not found'), { status: 404, code: 'NOT_FOUND' }));
return Promise.resolve({ item: structuredClone(item) });
},
},
}),
} as unknown as Parameters<typeof MetadataProvider>[0]['adapter'];
}

function wrapperFor(calls: string[], language = 'en') {
const i18n = createI18n({
defaultLanguage: language,
detectBrowserLanguage: false,
resources: { 'zh-CN': { showcase: { reports: { q3_results: { label: '第三季度结果' } } } } },
});
const adapter = makeAdapter(calls);
return ({ children }: { children: ReactNode }) => (
<I18nProvider instance={i18n} persistLanguage={false}>
<MetadataProvider adapter={adapter}>{children}</MetadataProvider>
</I18nProvider>
);
}

const at = '2026-11-02T09:00:00.000Z';
const ROWS: RecentItem[] = [
{ id: 'dashboard:pipeline', type: 'dashboard', name: 'pipeline', href: '/d', visitedAt: at },
{ id: 'page:welcome', type: 'page', name: 'welcome', href: '/p', visitedAt: at },
{ id: 'report:q3_results', type: 'report', name: 'q3_results', href: '/r', visitedAt: at },
];

/** The whole-list reads of the three types. */
const listReads = (calls: string[]) => calls.filter((c) => c === 'dashboard' || c === 'page' || c === 'report');

const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 50)));

afterEach(() => cleanup());

describe('recent dashboard / page / report rows read their item by name (objectstack#29235)', () => {
it('each row asks its own item, never its type’s list, and prints what the list gave', async () => {
const calls: string[] = [];
const { result } = renderHook(() => useRecentItemLabel(), { wrapper: wrapperFor(calls) });
await waitFor(() => expect(ROWS.map((row) => result.current(row))).toEqual(['Pipeline', 'Welcome', 'Q3 Results']));
await settle();
expect(listReads(calls)).toEqual([]);
expect(calls.filter((c) => c.includes('/')).sort()).toEqual(['dashboard/pipeline', 'page/welcome', 'report/q3_results']);
});

it('zh-CN: an inline locale map and a translation bundle key read as the list gave them', async () => {
const calls: string[] = [];
const { result } = renderHook(() => useRecentItemLabel(), { wrapper: wrapperFor(calls, 'zh-CN') });
await waitFor(() => expect(ROWS.map((row) => result.current(row))).toEqual(['Pipeline', '欢迎', '第三季度结果']));
expect(listReads(calls)).toEqual([]);
});

it('the machine name until the item lands, and for an item the server does not have (asked once)', async () => {
const calls: string[] = [];
const gone: RecentItem = { id: 'report:gone', type: 'report', name: 'gone', href: '/r', visitedAt: at };
const { result, rerender } = renderHook(() => useRecentItemLabel(), { wrapper: wrapperFor(calls) });
expect(ROWS.map((row) => result.current(row))).toEqual(['pipeline', 'welcome', 'q3_results']);
expect(result.current(gone)).toBe('gone');
await waitFor(() => expect(result.current(ROWS[2])).toBe('Q3 Results'));
await settle();
rerender();
expect(result.current(gone)).toBe('gone');
expect(calls.filter((c) => c === 'report/gone')).toEqual(['report/gone']);
expect(listReads(calls)).toEqual([]);
});

it('CONTROL: once the lists are loaded, the rows read them and ask no item', async () => {
const calls: string[] = [];
const { result } = renderHook(
() => {
const metadata = useMetadata();
return { label: useRecentItemLabel(), metadata };
},
{ wrapper: wrapperFor(calls) },
);
await act(async () => {
await Promise.all(['dashboard', 'page', 'report'].map((type) => result.current.metadata.ensureType(type)));
});
await waitFor(() => expect(ROWS.map((row) => result.current.label(row))).toEqual(['Pipeline', 'Welcome', 'Q3 Results']));
await settle();
expect(listReads(calls).sort()).toEqual(['dashboard', 'page', 'report']);
expect(calls.filter((c) => c.includes('/'))).toEqual([]);
});
});
19 changes: 12 additions & 7 deletions ui/packages/app-shell/src/hooks/useNavTargetLabel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ import { useObjectLabel, useObjectTranslation } from '@object-ui/i18n';
import type { NavLabelTarget, NavTargetLabelResolver } from '@object-ui/layout';
import { useMetadata } from '../providers/MetadataProvider.js';
import { bundledFirst, useBundledReads } from '../providers/bundledReads.js';
import { readObjectsByName } from './useObjectPresence.js';
import { readObjectsByName, useReadItemsByName } from './useObjectPresence.js';

/**
* A metadata label (plain string or inline locale map) as display text, or
Expand Down Expand Up @@ -141,12 +141,14 @@ function listViewsOf(def: LabelledRecord | undefined): Record<string, LabelledRe

/**
* How the resolver reads an object (objectstack#29121). By default from the
* whole `objects` list, as the sidebar and every other caller does. With
* whole `objects` list, as the Studio's and the search page's callers do. With
* `byName`, an `object` or `view` target reads its object by name
* (`readObjectsByName`) while nothing has loaded the whole list, so a surface
* that names a few objects (Home's recent rows) never loads the registry for
* their labels; a `view` target's object is read with its views, which its
* label is.
* that names a few objects (Home's recent rows, the app sidebar) never loads
* the registry for their labels; a `view` target's object is read with its
* views, which its label is. A `dashboard` target the app bundle does not hold
* is read by name the same way (`useReadItemsByName`, objectstack#29235),
* never through the whole `/meta/dashboard` list.
*/
export interface NavTargetLabelOptions {
byName?: boolean;
Expand All @@ -155,6 +157,7 @@ export interface NavTargetLabelOptions {
export function useNavTargetLabel(options?: NavTargetLabelOptions): NavTargetLabelResolver {
const metadata = useMetadata();
const byName = options?.byName === true;
const readItemsByName = useReadItemsByName(metadata);
const bundledReads = useBundledReads();
const { objectLabel, viewLabel, dashboardLabel } = useObjectLabel();
const { language, t } = useObjectTranslation();
Expand All @@ -180,7 +183,9 @@ export function useNavTargetLabel(options?: NavTargetLabelOptions): NavTargetLab
case 'dashboard': {
// objectstack#28645 — the app bundle holds every dashboard its
// navigation names; the list is read only for one it does not hold.
const def = bundledFirst(bundledReads, 'dashboard', target.dashboardName, () => metadata.dashboards);
const def = bundledFirst(bundledReads, 'dashboard', target.dashboardName, () =>
byName ? readItemsByName('dashboard', [target.dashboardName], () => metadata.dashboards) : metadata.dashboards,
);
const text =
metadataText(def?.label, language) ?? draftText(drafts, 'dashboard', target.dashboardName, language);
return nonEmpty(dashboardLabel({ name: target.dashboardName, label: text ?? '' }));
Expand All @@ -191,6 +196,6 @@ export function useNavTargetLabel(options?: NavTargetLabelOptions): NavTargetLab
return undefined;
}
},
[metadata, byName, bundledReads, objectLabel, viewLabel, dashboardLabel, language, t, drafts],
[metadata, byName, readItemsByName, bundledReads, objectLabel, viewLabel, dashboardLabel, language, t, drafts],
);
}
Loading
Loading