diff --git a/.changeset/29235-sidebar-recents-labels-by-name.md b/.changeset/29235-sidebar-recents-labels-by-name.md new file mode 100644 index 00000000000..8927bcfc500 --- /dev/null +++ b/.changeset/29235-sidebar-recents-labels-by-name.md @@ -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. diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.navLabelReadsByName-29235.test.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.navLabelReadsByName-29235.test.tsx new file mode 100644 index 00000000000..c36939ed15f --- /dev/null +++ b/ui/packages/app-shell/src/chrome/CommandPalette.navLabelReadsByName-29235.test.tsx @@ -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>()), + useAuth: () => ({ user: { id: 'u1' }, activeOrganization: null }), +})); + +vi.mock('../context/RecentItemsProvider', async (importOriginal) => ({ + ...(await importOriginal>()), + useRecentItems: () => ({ recentItems: [], addRecentItem: () => {}, clearRecentItems: () => {} }), +})); + +vi.mock('../utils/getIcon', () => ({ + getIcon: () => + function StubIcon(props: { className?: string }) { + return ; + }, +})); + +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[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( + + + + + {}} /> + + + + , + ); + 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([]); + }); +}); diff --git a/ui/packages/app-shell/src/chrome/CommandPalette.tsx b/ui/packages/app-shell/src/chrome/CommandPalette.tsx index acdf34ce380..a968caf54e0 100644 --- a/ui/packages/app-shell/src/chrome/CommandPalette.tsx +++ b/ui/packages/app-shell/src/chrome/CommandPalette.tsx @@ -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); diff --git a/ui/packages/app-shell/src/hooks/__tests__/useRecentItemLabel.readsByName-29235.test.tsx b/ui/packages/app-shell/src/hooks/__tests__/useRecentItemLabel.readsByName-29235.test.tsx new file mode 100644 index 00000000000..d62428419c2 --- /dev/null +++ b/ui/packages/app-shell/src/hooks/__tests__/useRecentItemLabel.readsByName-29235.test.tsx @@ -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>> = { + 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[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 }) => ( + + {children} + + ); +} + +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([]); + }); +}); diff --git a/ui/packages/app-shell/src/hooks/useNavTargetLabel.ts b/ui/packages/app-shell/src/hooks/useNavTargetLabel.ts index b90cd1a1cb1..f201309d685 100644 --- a/ui/packages/app-shell/src/hooks/useNavTargetLabel.ts +++ b/ui/packages/app-shell/src/hooks/useNavTargetLabel.ts @@ -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 @@ -141,12 +141,14 @@ function listViewsOf(def: LabelledRecord | undefined): Record 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 ?? '' })); @@ -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], ); } diff --git a/ui/packages/app-shell/src/hooks/useObjectPresence.ts b/ui/packages/app-shell/src/hooks/useObjectPresence.ts index 03f9579e3ce..dd858c37938 100644 --- a/ui/packages/app-shell/src/hooks/useObjectPresence.ts +++ b/ui/packages/app-shell/src/hooks/useObjectPresence.ts @@ -53,6 +53,7 @@ * type is still `idle` (`MetadataProvider`'s `readType`). No consumer of this * hook adds a request; the point is to remove one. */ +import { useCallback, useRef, useState } from 'react'; import { useMetadata, type MetadataContextValue, type MetadataTypeStatus } from '@object-ui/react'; import { useExpressionContext } from '../providers/ExpressionProvider.js'; @@ -98,6 +99,69 @@ export function readObjectsByName( return metadata.objects ?? NO_OBJECTS; } +/** + * {@link readObjectsByName} for a type the cache keeps no names-only scope for + * (a dashboard, a page, a report): `read(type, names, list)`. + */ +export type ReadItemsByName = ( + type: string, + names: readonly string[], + list: () => readonly unknown[] | undefined, +) => readonly unknown[]; + +const NO_ANSWERS: ReadonlyMap = new Map(); + +/** + * The definitions of `names` of one metadata type, without that type's whole + * list (objectstack#29235): what {@link readObjectsByName} is to objects, for + * a reader that labels a few rows (a recent dashboard, page or report). While + * nothing has asked for the type's list, each name is asked once through the + * provider's by-name read (`getItem`, which the app bundle answers for an item + * it holds), and the answer is the names that have landed so far; the reader + * re-renders as each lands. Once the list is loaded, or on its way, it is + * `list()`, and nothing more is asked. A provider without a status or a + * by-name read (a hand-rolled context) answers with `list()`, as before. + * + * A name that answered an item is asked again once the provider's metadata + * changes (a refresh, an invalidation): the provider's by-name cache answers it + * at once, without a request, unless that change dropped it, so a renamed item + * shows its new label. A name that answered none (absent, or a failed read) is + * not asked again while the reader is mounted. + * + * Asking for no name asks for nothing. + */ +export function useReadItemsByName( + metadata: Pick, +): ReadItemsByName { + const { getItem, getTypeStatus } = metadata; + const [answers, setAnswers] = useState(NO_ANSWERS); + // What this reader asked of which provider value: a new value (its + // `getTypeStatus` is rebuilt with it) starts a new set. + const askedRef = useRef<{ of: unknown; keys: Set }>({ of: undefined, keys: new Set() }); + return useCallback( + (type, names, list) => { + if (typeof getItem !== 'function' || getTypeStatus?.(type) !== 'idle') return list() ?? NO_OBJECTS; + if (askedRef.current.of !== getTypeStatus) askedRef.current = { of: getTypeStatus, keys: new Set() }; + const asked = askedRef.current.keys; + const found: unknown[] = []; + for (const name of names) { + if (typeof name !== 'string' || name === '') continue; + const key = `${type}/${name}`; + if (!asked.has(key) && answers.get(key) !== null) { + asked.add(key); + const settle = (item: unknown) => + setAnswers((prev) => (prev.has(key) && prev.get(key) === item ? prev : new Map(prev).set(key, item))); + void getItem(type, name).then((item) => settle(item ?? null), () => settle(null)); + } + const item = answers.get(key); + if (item) found.push(item); + } + return found; + }, + [getItem, getTypeStatus, answers], + ); +} + /** What the metadata registry can say about one object name. */ export type ObjectPresence = 'present' | 'absent' | 'unknown'; diff --git a/ui/packages/app-shell/src/hooks/useRecentItemLabel.ts b/ui/packages/app-shell/src/hooks/useRecentItemLabel.ts index c7946e9542e..e5de17f210b 100644 --- a/ui/packages/app-shell/src/hooks/useRecentItemLabel.ts +++ b/ui/packages/app-shell/src/hooks/useRecentItemLabel.ts @@ -63,7 +63,7 @@ import type { RecentItem } from '../context/RecentItemsProvider.js'; import { useMetadata } from '../providers/MetadataProvider.js'; import { bundledFirst, useBundledReads } from '../providers/bundledReads.js'; import { findByName, metadataText, useNavTargetLabel, type LabelledRecord, type NavTargetLabelOptions } from './useNavTargetLabel.js'; -import { readObjectsByName } from './useObjectPresence.js'; +import { readObjectsByName, useReadItemsByName } from './useObjectPresence.js'; const BY_NAME: NavTargetLabelOptions = { byName: true }; @@ -86,6 +86,9 @@ export function useRecentItemLabel( // whole registry: a few recent entries, on Home before anything else asks it. const targetLabel = useNavTargetLabel(BY_NAME); const metadata = useMetadata(); + // objectstack#29235 — a page or report row reads its item by name, never its + // type's whole list (a dashboard row does too, through `targetLabel`). + const readItemsByName = useReadItemsByName(metadata); const bundledReads = useBundledReads(); const { objectPluralLabel, pageLabel, reportLabel } = useObjectLabel(); const { language } = useObjectTranslation(); @@ -109,11 +112,13 @@ export function useRecentItemLabel( case 'dashboard': return targetLabel({ kind: 'dashboard', dashboardName: item.name }) ?? item.name; case 'page': { - const text = metadataText(bundledFirst(bundledReads, 'page', item.name, () => metadata.pages)?.label, language); + const pages = () => readItemsByName('page', [item.name], () => metadata.pages); + const text = metadataText(bundledFirst(bundledReads, 'page', item.name, pages)?.label, language); return nonEmpty(pageLabel({ name: item.name, label: text ?? '' })) ?? item.name; } case 'report': { - const text = metadataText(findByName(metadata.reports, item.name)?.label, language); + const reports = readItemsByName('report', [item.name], () => metadata.reports); + const text = metadataText(findByName(reports, item.name)?.label, language); return nonEmpty(reportLabel({ name: item.name, label: text ?? '' })) ?? item.name; } case 'package': @@ -122,6 +127,6 @@ export function useRecentItemLabel( return item.label; } }, - [targetLabel, metadata, bundledReads, objectPluralLabel, pageLabel, reportLabel, language, packages], + [targetLabel, metadata, readItemsByName, bundledReads, objectPluralLabel, pageLabel, reportLabel, language, packages], ); } diff --git a/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx b/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx index acf40396751..6f5d42bb5cc 100644 --- a/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx +++ b/ui/packages/app-shell/src/layout/UnifiedSidebar.tsx @@ -184,7 +184,7 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi // An entry with no `label` shows its target's CURRENT label, read from the // metadata cache at render time (objectui#9868). `nav:menu` wires the same // hook, so the two surfaces cannot name one entry two ways. - const resolveNavTargetLabel = useNavTargetLabel(); + const resolveNavTargetLabel = useNavTargetLabel({ byName: true }); // Below the fold width the sidebar is the icon rail and expands over the // content (objectstack#27593); `useResponsiveSidebar` folds and unfolds it. const rail = useConsoleSidebarRail({ enabled: railOverlay }); diff --git a/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.labelReadsByName-29235.test.tsx b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.labelReadsByName-29235.test.tsx new file mode 100644 index 00000000000..711b58b32c7 --- /dev/null +++ b/ui/packages/app-shell/src/layout/__tests__/UnifiedSidebar.labelReadsByName-29235.test.tsx @@ -0,0 +1,189 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#29235 — the app sidebar labels an entry that has no label of its + * own by reading its target by name, never the whole object registry. + * + * `UnifiedSidebar` hands `NavigationRenderer` the `useNavTargetLabel` resolver + * (objectui#9868). It read an unlabelled object entry's label from + * `useMetadata().objects`, which loads the whole object registry (and the + * `/meta/view` list it is composed with) on every in-app page whose route has + * not loaded it already: on app-crm, 551 KB for two labels. The sidebar now + * asks with `{ byName: true }`: the entry's object by name (which the app + * bundle answers in the console), and a dashboard entry the bundle does not + * hold by name too. + * + * Real subjects: `UnifiedSidebar`, `useNavTargetLabel`, `MetadataProvider`, + * `@object-ui/layout` and `@object-ui/components`, over a fake adapter that + * records each read. The chrome mocks are those of + * `UnifiedSidebar.navLabelInheritsTarget-9868.test.tsx`. + */ + +import '@testing-library/jest-dom/vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import React from 'react'; +import { render, screen, cleanup, act } from '@testing-library/react'; +import { MemoryRouter } from 'react-router-dom'; +import type { NavigationItem } from '@object-ui/types'; + +const i18nState = vi.hoisted(() => ({ language: 'en' })); + +vi.mock('@object-ui/i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useObjectTranslation: () => ({ + t: (key: string, options?: Record) => String(options?.defaultValue ?? key), + language: i18nState.language, + }), + // No translation bundle: every convention lookup answers its fallback. + useObjectLabel: () => ({ + objectLabel: ({ label }: { label?: string }) => label, + objectPluralLabel: ({ label }: { label?: string }) => label, + viewLabel: (_o: string, _v: string, fallback?: string) => fallback, + dashboardLabel: ({ label }: { label?: string }) => label, + pageLabel: ({ label }: { label?: string }) => label, + reportLabel: ({ label }: { label?: string }) => label, + appLabel: ({ label }: { label?: string }) => label, + }), +})); + +vi.mock('@object-ui/auth', async (importOriginal) => ({ + ...(await importOriginal>()), + useAuth: () => ({ user: null, activeOrganization: null }), + useWorkspaceAdminStatus: () => ({ isAdmin: false, isResolved: true }), +})); + +vi.mock('@object-ui/permissions', async (importOriginal) => ({ + ...(await importOriginal()), + usePermissions: () => ({ can: () => true, hasCapabilities: () => true }), +})); + +vi.mock('../../providers/ExpressionProvider', () => ({ + useExpressionContext: () => ({ evaluator: null }), + evaluateVisibility: (expr: unknown) => expr !== false && expr !== 'false', + evaluateNavigationVisibility: (expr: unknown) => expr !== false && expr !== 'false', + useHasExpressionScope: () => true, +})); + +vi.mock('../../utils', () => ({ + resolveKeyedI18nLabel: (label: unknown) => (typeof label === 'string' ? label : ''), + matchAppBySegment: (apps: Array<{ name?: string }>, segment?: string) => apps.find((a) => a?.name === segment), + appRouteSegment: (app: { name?: string }) => app?.name, +})); + +vi.mock('../../utils/getIcon', () => ({ getIcon: () => () => null })); +vi.mock('../../hooks/useRecentItems', () => ({ useRecentItems: () => ({ recentItems: [] }) })); +vi.mock('../../hooks/useFavorites', () => ({ + useFavorites: () => ({ favorites: [], removeFavorite: vi.fn() }), +})); +vi.mock('../../hooks/useNavPins', () => ({ + useNavPins: () => ({ togglePin: vi.fn(), applyPins: (items: unknown) => items }), +})); +vi.mock('../../hooks/useNavActionDispatch', () => ({ + useNavActionDispatch: () => vi.fn(), +})); +vi.mock('../../context/NavigationContext', () => ({ + useNavigationContext: () => ({ context: 'app', currentAppName: 'ops' }), +})); +vi.mock('../ContextSelectors', () => ({ + useAppContextSelectors: () => ({ contextValues: {}, element: null }), + contextSelectorQueryKey: (id: string) => (id === 'active_package' ? 'package' : id), + STUDIO_PACKAGE_SELECTOR_ID: 'active_package', +})); +vi.mock('../LocalizedSidebarTrigger', () => ({ + LocalizedSidebarTrigger: () => null, +})); + +import { SidebarProvider } from '@object-ui/components'; +import { MetadataProvider } from '../../providers/MetadataProvider'; +import { UnifiedSidebar } from '../UnifiedSidebar'; + +// An app written without entry labels, as the spec allows (objectui#9868). +const navigation: NavigationItem[] = [ + { id: 'nav_accounts', type: 'object', objectName: 'crm_account' }, + { id: 'nav_contacts', type: 'object', objectName: 'crm_contact' }, + { id: 'nav_pipeline', type: 'dashboard', dashboardName: 'pipeline' }, +]; +const APP = { name: 'ops', label: 'Ops', active: true, navigation }; +const OBJECTS = [ + { name: 'crm_account', label: { en: 'Account', 'zh-CN': '客户' }, fields: {} }, + { name: 'crm_contact', label: 'Contact', fields: {} }, + { name: 'crm_lead', label: 'Lead', fields: {} }, +]; +const DASHBOARDS = [{ name: 'pipeline', label: { en: 'Pipeline', 'zh-CN': '销售漏斗' } }]; +const ITEMS: Record = { app: [APP], object: OBJECTS, dashboard: DASHBOARDS, view: [] }; + +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) => { + calls.push(type); + return Promise.resolve({ type, items: structuredClone(ITEMS[type] ?? []) }); + }, + getItem: (type: string, name: string) => { + calls.push(`${type}/${name}`); + const item = ((ITEMS[type] ?? []) as Array<{ name: string }>).find((it) => it.name === name) ?? null; + return Promise.resolve({ item: structuredClone(item) }); + }, + }, + }), + } as unknown as Parameters[0]['adapter']; +} + +function renderSidebar(): string[] { + const calls: string[] = []; + render( + + + + + + + , + ); + return calls; +} + +/** The whole-list reads a label could cost: the object registry, its views, the dashboards. */ +const listReads = (calls: string[]) => calls.filter((c) => c === 'object' || c === 'view' || c === 'dashboard'); + +const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 50))); + +beforeEach(() => { + localStorage.clear(); + sessionStorage.clear(); + i18nState.language = 'en'; +}); +afterEach(() => cleanup()); + +describe('the app sidebar labels an unlabelled entry by name (objectstack#29235)', () => { + it('each object and dashboard entry reads its target by name, never a whole list', async () => { + const calls = renderSidebar(); + expect(await screen.findByRole('link', { name: 'Account' })).toHaveAttribute('href', '/apps/ops/crm_account'); + expect(await screen.findByRole('link', { name: 'Contact' })).toHaveAttribute('href', '/apps/ops/crm_contact'); + expect(await screen.findByRole('link', { name: 'Pipeline' })).toHaveAttribute('href', '/apps/ops/dashboard/pipeline'); + await settle(); + expect(listReads(calls)).toEqual([]); + expect(calls.filter((c) => c.includes('/')).sort()).toEqual([ + 'dashboard/pipeline', + 'object/crm_account', + 'object/crm_contact', + ]); + }); + + it('zh-CN: an inline locale map reads the viewer’s language, as the whole list gave it', async () => { + i18nState.language = 'zh-CN'; + const calls = renderSidebar(); + expect(await screen.findByRole('link', { name: '客户' })).toHaveAttribute('href', '/apps/ops/crm_account'); + expect(await screen.findByRole('link', { name: '销售漏斗' })).toHaveAttribute('href', '/apps/ops/dashboard/pipeline'); + await settle(); + expect(listReads(calls)).toEqual([]); + }); +});