Skip to content

Commit 4128213

Browse files
fix(console): a nav entry with no icon draws its object's icon, record labels in one style, a small count axis fits, a failed entry load retries (#30126) (#30573)
<!-- claude-projects-attribution: {"github_login":"os-sales"} --> _Requested by **Sales** · [project thread](https://claude.ai/code/project/chan_01D5bWFY3rFzgJcytD5gD4Uu?thread=cmsg_01D5bWFY3rFzgJcytD5gD4UuJQma3chFJMvv899DugzEi9)_ Part of #30126 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 1. **What:** the console rows of #30126 that still reproduce on `main` and are fixed in `ui/**`: rows 4, 6, 11 and 14. Rows 5 and 10 do not reproduce (readings below). Row 8 reproduces, but its fix is a server object definition, outside this PR. 2. **Row 4:** an `object` nav entry with no `icon` draws the icon its object declares, in the sidebar and in the `nav:menu` block. It reads the object by name from metadata the console already holds, adds no request and writes nothing to the navigation. 3. **Row 6:** a record section's field labels drop the uppercase transform, so `REPAIR COST` no longer reads in capitals beside `负责人`. They now use the highlights strip's label class. 4. **Row 11:** a count axis whose largest value is 1 to 3 tops out at that value, so one record's bar is full height (362×71 → 362×282 px). 5. **Row 14:** an entry script that fails to load before mount makes the page reload itself, backing off from 1 s and doubling (1/2/4/8/16 s), at most 5 times per tab. Before, the splash stayed forever. 6. **Contract:** `@object-ui/layout` gains `resolveNavItemIcon`, `NavIconTarget`, `NavTargetIconResolver` and an optional `resolveTargetIcon` prop on `NavigationRenderer`, which mirrors `resolveTargetLabel`. That is a widening, so `Clause-②: yes (widening)` (the claim said `no`, and the seat corrects it). No metadata key, no i18n key, nothing under `packages/**`. ## What changes - `ui/packages/layout/src/NavigationRenderer.tsx`: `resolveNavItemIcon(item, resolver)` returns the authored icon; failing that, for an `object` entry, the resolver's answer; otherwise `undefined` (the generic icon). The leaf row, including rows inside groups, draws it. - `ui/packages/app-shell/src/hooks/useNavTargetIcon.ts` (new): the console's resolver. It reads `readObjectsByName` from the metadata cache, the same by-name read the entry's label already makes. It is wired into `UnifiedSidebar` (app arm) and `nav-menu-renderer`, and added to the `openPathObjectReaders-12811` census as a `byName` reader. - `ui/packages/plugin-detail/src/DetailSection.tsx`: the field label class goes from `text-xs font-medium text-muted-foreground uppercase tracking-wide` to `text-xs font-medium text-muted-foreground` (the `HeaderHighlight` label class). - `ui/packages/plugin-charts/src/normalizeChartSchema.ts` + `AdvancedChartImpl.tsx`: `wholeNumberTickCount(axis, values)` gives `max + 1` ticks when every value is a non-negative integer, `1 ≤ max ≤ 3`, and the axis has no authored `min`/`max`/`stepSize`. Otherwise it returns `undefined`, and the axis is drawn as before. This is not exported from the package index. - `ui/apps/console/index.html`: the boot splash adds a capture `error` listener for a failed `type=module` entry script before mount. It keeps a per-tab retry count in `sessionStorage` (`os-boot-entry-retries`, max 5), backs off 1/2/4/8/16 s, clears the count on mount, and does not retry where storage is blocked. The splash still ships no copy. ## Row readings (real stack, `origin/main` `c045c341`, showcase app, zh, 1440×900 unless noted) | row | before | after | |:--|:--|:--| | 4 sidebar icons | all 6 Walkthrough rows `file-text` ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row4-sidebar.png?raw=true)) | `folder-kanban` / `check-square` / `building` / `receipt`, the dashboard row stays `file-text` ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/after-row4-sidebar.png?raw=true)) | | 5 Setup collapsed sidebar | **not reproduced**: hovering a collapsed icon shows its tooltip, both collapsed by hand at 1440 ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row5-setup-collapsed-hover.png?raw=true)) and on the auto rail at 1280 ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-1280-row5-1280-rail-hover.png?raw=true), tooltip `Users`). The Setup labels are English in zh, which belongs to #30504. | no change | | 6 record labels | Field Zoo: `负责人` beside `EMAIL` / `PHONE` ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row6-fieldzoo.png?raw=true)); en project record: `OWNER EMAIL`, `SPENT`, `START DATE` in capitals ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-en-row6-record.png?raw=true)) | one style, as authored ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/after-row6-fieldzoo.png?raw=true)) | | 8 inbox topic | **reproduces**: the `sys_inbox_message` view `mine` shows the raw topic `notify` ([list](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row8-list.png?raw=true), [popover](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row8-popover.png?raw=true)). The column list is in `packages/services/service-messaging/src/objects/inbox-message.object.ts`, outside `ui/**`, so it is left for the server lane. | no change | | 10 toast over assignee | **not reproduced**: 1440 page: toast y53–107, assignee y249–291 ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row10-toast.png?raw=true)); 1440 drawer: toast x340, drawer from x720 ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row10-toast-drawer.png?raw=true)); 1024 drawer: toast y136–190, assignee y249 ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-1024-row10-toast-drawer.png?raw=true)) | no change | | 11 one-bar count | axis 0–4, bar 362×71 in a 510×350 plot ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row11-one-bar.png?raw=true)) | axis 0–1, bar 362×282 ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/after-row11-one-bar.png?raw=true)) | | 14 entry fails | backend down after the HTML loads already reads "无法连接到服务器" + 重试 ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row14-backend-down.png?raw=true)); an entry module that fails to load left the splash forever ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/before-row14-entry-failed.png?raw=true)) | 2 aborted entry loads: recovered on load 3, about 15 s ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/after-row14-recovered.png?raw=true)); every load aborted: gives up after 6 loads, splash stays ([shot](https://github.com/objectstack-ai/objectstack/blob/a0ade7b68805c95f9a86334eea71f905f3578e12/evidence/30126/after-row14-gave-up.png?raw=true)) | Row 14 was emulated with a Playwright route abort on the entry chunk, not with a real `os dev` restart. ## Tests - `ui/packages/layout/src/__tests__/NavigationRenderer.iconInheritsObject-30126.test.tsx` (5): the resolver's precedence and controls, plus rows at the top level and in a group. - `ui/packages/app-shell/src/views/__tests__/nav-icon-inherits-object-30126.render.test.tsx` (3): both surfaces against one `MetadataCtx`. It checks that an authored icon stays, an object with no icon and a dashboard entry keep the generic glyph, and a changed object icon shows on rerender with the navigation unchanged. - `ui/packages/plugin-detail/src/__tests__/DetailSection.labelStyle-30126.test.tsx` (2): Latin and CJK labels share one class with no `uppercase`, and match the highlights strip. - `ChartRenderer.integerMeasureTicks-11681.test.tsx`: plus 6 tests for the small-count axis and its controls (fractional, count ≥ 4, authored max). - `apps/console/src/__tests__/bootSplash.test.ts`: plus 5 tests for the retry, back-off, cap, reset on mount, and storage blocked. - Ablations, each reverted with the restore diff at 0 lines, and each turned its tests red: the sidebar leaf back to `item.icon`, the `nav:menu` row back to `item.icon`, `uppercase` restored on the section label, the axis `tickCount` spread dropped, the splash's `location.reload()` removed, and the reset of the retry count on mount removed. ## Verification - Type-check exit 0: `@object-ui/layout`, `plugin-detail`, `plugin-charts`, `app-shell` (re-run after the `main` merge), `console`. - eslint on the 14 changed source/test files: 0 errors (warnings pre-existing; the one new `any` warning in `bootSplash.test.ts` fixed). - `node scripts/pm/dispatch-gates.mjs --commands`: 36 derived families plus `pnpm --dir ui run check:new-line-citations`, all exit 0. `pnpm --dir ui exec vitest run scripts/` was OOM-killed beside the loop and passed run alone: 170 files passed (2 skipped), 4985 tests. - After merging `origin/main` (`f33b094f`): `vitest run packages/layout/ packages/plugin-detail/ packages/plugin-charts/ apps/console/src/__tests__/ packages/app-shell/src/layout/ packages/app-shell/src/views/__tests__/ packages/app-shell/src/hooks/` + the `openPathObjectReaders-12811` census: 923 files passed (1 skipped), 8557 tests passed (27 skipped). - Evidence: shots at `a0ade7b6` (`evidence/30126/`, removed from the tree by the next commit). ## Acceptance notes - Open question for the seat (row 11): the one bar is still 362 px wide. Capping `maxBarSize` would change every bar chart, so it was left alone. - Row 8's fix (`columns` of view `mine`) and rows 9, 12, 13, 15, 16 stay on the card. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01L6bhgVUJuSB1qgbeFwydba <!-- signed: domain:ui#4 · os-sales · session_01L6bhgVfPeFZkN1FP93imKU --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b55d6ab commit 4128213

15 files changed

Lines changed: 736 additions & 10 deletions
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
---
2+
'@object-ui/layout': patch
3+
'@object-ui/app-shell': patch
4+
'@object-ui/plugin-detail': patch
5+
'@object-ui/plugin-charts': patch
6+
'@object-ui/console': patch
7+
---
8+
9+
fix(console): a nav entry with no icon draws its object's icon, record field labels read in one style, a count chart fits a small count, and a page whose entry failed to load retries (#30126)
10+
11+
Clause-②: yes (widening)
12+
Metadata-protocol: none
13+
14+
- **Navigation icons.** An app navigation entry of type `object` that names no `icon` now draws the icon its object declares, in the sidebar and in the `nav:menu` page block. Before, every such row drew the same generic page icon, so an app whose navigation names no icons showed one icon down the whole sidebar. The icon is read by object name from the metadata the console already holds, so no request is added and the navigation is not written to. An authored `icon` wins, and an object with no icon, a dashboard, page or report entry, and a host with no resolver keep the generic icon. `@object-ui/layout` exports `resolveNavItemIcon`, the types `NavIconTarget` and `NavTargetIconResolver`, and an optional `resolveTargetIcon` prop on `NavigationRenderer`, alongside the existing `resolveTargetLabel`.
15+
- **Record field labels.** A record page's section field labels no longer carry an uppercase transform. Only Latin text took it, so in a zh console an untranslated label (`REPAIR COST`) read in capitals beside a translated one (`负责人`). Section labels now render as authored, in the style of the highlights strip above them.
16+
- **Small count charts.** A count axis whose largest value is a small whole number (1 to 3) now tops out at that number, so a chart of one record draws its bar to the top of the axis instead of a quarter of the way up a 0–4 axis. An axis with an authored `min`, `max` or `stepSize`, fractional values, or a count of 4 or more draws as before.
17+
- **Boot retry.** When the page's entry script fails to load before anything mounts (the server went away between serving the page and serving its entry, as during an `os dev` restart), the page now reloads itself, backing off from 1 second and doubling, at most five times per tab. Before, the loading splash stayed forever. The count is cleared on the first mount, and where `sessionStorage` cannot be read nothing retries.

‎ui/apps/console/index.html‎

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,16 @@
406406
permanently pending one now — and it stays detectable: the
407407
`#root`-content assertion in `e2e/console-rendering.spec.ts` reads the
408408
React root, which this does not touch.
409+
410+
RETRY. One cause of a bundle that never evaluates is passing: the server
411+
went away between serving this page and serving its entry module, as it
412+
does while `os dev` restarts. So when a module script fails to load before
413+
anything has mounted, the page reloads itself, backing off (1, 2, 4, 8 and
414+
16 seconds), at most five times per tab; the count lives in
415+
sessionStorage and is cleared on the first mount. Where that storage
416+
cannot be read the count cannot be bounded, so nothing retries. After the
417+
last attempt the splash stays, as above. No copy is drawn: there is no
418+
locale pack to translate it with before the bundle loads.
409419
-->
410420
<script>
411421
(function installBootSplash() {
@@ -422,10 +432,47 @@
422432
var dark = stored === 'dark' || (followsOs && prefersDark);
423433
document.documentElement.setAttribute('data-boot-theme', dark ? 'dark' : 'light');
424434

435+
var RETRY_KEY = 'os-boot-entry-retries';
436+
var MAX_RETRIES = 5;
437+
function readRetries() {
438+
try {
439+
return Number(sessionStorage.getItem(RETRY_KEY)) || 0;
440+
} catch (_) {
441+
return null;
442+
}
443+
}
444+
function writeRetries(count) {
445+
try {
446+
if (count) sessionStorage.setItem(RETRY_KEY, String(count));
447+
else sessionStorage.removeItem(RETRY_KEY);
448+
} catch (_) {
449+
/* storage blocked — readRetries answers null, so nothing retries */
450+
}
451+
}
452+
function mounted() {
453+
var root = document.getElementById('root');
454+
return !!(root && root.firstChild);
455+
}
456+
window.addEventListener(
457+
'error',
458+
function (event) {
459+
var el = event.target;
460+
if (!el || el.tagName !== 'SCRIPT' || el.type !== 'module' || !el.src) return;
461+
if (mounted()) return;
462+
var tries = readRetries();
463+
if (tries === null || tries >= MAX_RETRIES) return;
464+
writeRetries(tries + 1);
465+
setTimeout(function () {
466+
if (!mounted()) location.reload();
467+
}, 1000 * Math.pow(2, tries));
468+
},
469+
true,
470+
);
471+
425472
if (typeof MutationObserver !== 'function') return;
426473
var observer = new MutationObserver(function () {
427-
var root = document.getElementById('root');
428-
if (!root || !root.firstChild) return;
474+
if (!mounted()) return;
475+
writeRetries(0);
429476
observer.disconnect();
430477
var splash = document.getElementById('boot-splash');
431478
if (splash && splash.parentNode) splash.parentNode.removeChild(splash);

‎ui/apps/console/src/__tests__/bootSplash.test.ts‎

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -302,3 +302,147 @@ describe('apps/console/index.html — boot splash behaviour', () => {
302302
expect(() => localStorage.getItem(THEME_STORAGE_KEY)).not.toThrow();
303303
});
304304
});
305+
306+
/**
307+
* objectstack#30126 row 14 — a page opened while the server restarts retries.
308+
*
309+
* The entry module failing to load before anything mounted (the server went
310+
* away between serving the page and serving its entry, as during an `os dev`
311+
* restart) makes the page reload itself, backing off, at most five times per
312+
* tab. The count is cleared on the first mount; where sessionStorage cannot be
313+
* read nothing retries, because the count could not be bounded.
314+
*/
315+
// Every run of the script installs a `window` error listener; each test's are
316+
// removed after it, so a failure dispatched in one test reaches only the
317+
// script that test ran. File-wide: every describe here runs the script.
318+
const installedListeners: Array<[string, EventListenerOrEventListenerObject, boolean]> = [];
319+
const windowAddEventListener = window.addEventListener;
320+
beforeEach(() => {
321+
window.addEventListener = function (
322+
this: Window,
323+
type: string,
324+
fn: EventListenerOrEventListenerObject,
325+
opts?: boolean | AddEventListenerOptions,
326+
) {
327+
installedListeners.push([type, fn, typeof opts === 'boolean' ? opts : !!opts?.capture]);
328+
return windowAddEventListener.call(this, type, fn, opts);
329+
} as typeof window.addEventListener;
330+
});
331+
afterEach(() => {
332+
window.addEventListener = windowAddEventListener;
333+
for (const [type, fn, capture] of installedListeners.splice(0)) window.removeEventListener(type, fn, capture);
334+
});
335+
336+
describe('apps/console/index.html — boot splash retries a failed entry', () => {
337+
const RETRY_KEY = 'os-boot-entry-retries';
338+
let reload: ReturnType<typeof vi.fn>;
339+
340+
function runBootSplash(): void {
341+
new Function(extractBootSplashSource())();
342+
}
343+
344+
/**
345+
* A script whose load failed, as `window`'s capture listener sees it: an
346+
* `error` event whose target is the script. Built detached and handed to
347+
* `window` directly, because happy-dom would otherwise try to fetch the
348+
* `src` of a connected script and report a second failure of its own.
349+
*/
350+
function failScript(attrs: { type?: string; src?: string } = { type: 'module', src: '/src/main.tsx' }): void {
351+
const script = document.createElement('script');
352+
if (attrs.type) script.type = attrs.type;
353+
if (attrs.src) script.setAttribute('src', attrs.src);
354+
const event = new Event('error');
355+
Object.defineProperty(event, 'target', { value: script });
356+
window.dispatchEvent(event);
357+
}
358+
359+
beforeEach(() => {
360+
vi.useFakeTimers();
361+
sessionStorage.clear();
362+
document.body.innerHTML = `<div id="${SPLASH_ID}"></div><div id="root"></div>`;
363+
reload = vi.fn();
364+
vi.stubGlobal('location', { ...window.location, reload });
365+
vi.stubGlobal('matchMedia', () => ({ matches: false }));
366+
});
367+
368+
afterEach(() => {
369+
vi.restoreAllMocks();
370+
vi.unstubAllGlobals();
371+
vi.useRealTimers();
372+
sessionStorage.clear();
373+
document.documentElement.removeAttribute('data-boot-theme');
374+
document.body.innerHTML = '';
375+
});
376+
377+
it('reloads after a failed entry, backing off, and counts the attempt', () => {
378+
runBootSplash();
379+
failScript();
380+
expect(sessionStorage.getItem(RETRY_KEY)).toBe('1');
381+
vi.advanceTimersByTime(999);
382+
expect(reload).not.toHaveBeenCalled();
383+
vi.advanceTimersByTime(1);
384+
expect(reload).toHaveBeenCalledTimes(1);
385+
386+
// The reloaded page's attempt waits twice as long. A reload is a fresh
387+
// page: the first page's listener goes with it.
388+
reload.mockClear();
389+
for (const [type, fn, capture] of installedListeners.splice(0)) window.removeEventListener(type, fn, capture);
390+
runBootSplash();
391+
failScript();
392+
expect(sessionStorage.getItem(RETRY_KEY)).toBe('2');
393+
vi.advanceTimersByTime(1999);
394+
expect(reload).not.toHaveBeenCalled();
395+
vi.advanceTimersByTime(1);
396+
expect(reload).toHaveBeenCalledTimes(1);
397+
});
398+
399+
it('stops after five attempts in a tab: the splash stays', () => {
400+
sessionStorage.setItem(RETRY_KEY, '5');
401+
runBootSplash();
402+
failScript();
403+
vi.advanceTimersByTime(60_000);
404+
expect(reload).not.toHaveBeenCalled();
405+
expect(document.getElementById(SPLASH_ID)).not.toBeNull();
406+
});
407+
408+
it('clears the count on the first mount', async () => {
409+
sessionStorage.setItem(RETRY_KEY, '3');
410+
vi.useRealTimers();
411+
runBootSplash();
412+
document.getElementById('root')!.appendChild(document.createElement('div'));
413+
await new Promise((resolve) => setTimeout(resolve, 0));
414+
expect(sessionStorage.getItem(RETRY_KEY)).toBeNull();
415+
});
416+
417+
it('controls: a classic script, a module failing after the mount, and blocked storage never reload', () => {
418+
runBootSplash();
419+
failScript({ src: '/vendor.js' });
420+
vi.advanceTimersByTime(60_000);
421+
expect(reload).not.toHaveBeenCalled();
422+
423+
document.getElementById('root')!.appendChild(document.createElement('div'));
424+
failScript();
425+
vi.advanceTimersByTime(60_000);
426+
expect(reload).not.toHaveBeenCalled();
427+
});
428+
429+
it('control: with sessionStorage blocked the count cannot be bounded, so nothing retries', () => {
430+
const storedDescriptor = Object.getOwnPropertyDescriptor(globalThis, 'sessionStorage');
431+
const blocked = () => {
432+
throw new Error('storage blocked');
433+
};
434+
Object.defineProperty(globalThis, 'sessionStorage', {
435+
configurable: true,
436+
value: { getItem: blocked, setItem: blocked, removeItem: blocked, clear: blocked, key: blocked, length: 0 },
437+
});
438+
try {
439+
expect(() => sessionStorage.getItem(RETRY_KEY)).toThrow('storage blocked');
440+
runBootSplash();
441+
failScript();
442+
vi.advanceTimersByTime(60_000);
443+
expect(reload).not.toHaveBeenCalled();
444+
} finally {
445+
if (storedDescriptor) Object.defineProperty(globalThis, 'sessionStorage', storedDescriptor);
446+
}
447+
});
448+
});

‎ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ const OBJECTS_READERS: Record<string, { kind: Kind; why: string }> = {
8080
kind: 'off',
8181
why: 'read when a label is resolved for a nav entry without its own label, or a view entry; with { byName: true } (Home, recent rows) the object is read by name',
8282
},
83+
'packages/app-shell/src/hooks/useNavTargetIcon.ts': { kind: 'byName', why: "an object nav entry with no icon, its object's icon by name, as the sidebar reads that entry's label (objectstack#30126)" },
8384
'packages/app-shell/src/hooks/useRecentItemLabel.ts': { kind: 'byName', why: "a recent object or view entry's object, by name (objectstack#29121)" },
8485
'packages/app-shell/src/layout/ActivityObjectLabel.tsx': { kind: 'byName', why: "the inbox's and the home rail's activity rows, each row's object by name (objectstack#29121)" },
8586
'packages/app-shell/src/chrome/CommandPalette.tsx': { kind: 'off', why: "the Studio scope's object list, read while the palette lists Studio entries" },
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* useNavTargetIcon — the console's answer to "which icon does the object this
11+
* navigation entry opens declare?", for `object` entries that name no `icon`,
12+
* as a {@link NavTargetIconResolver}.
13+
*
14+
* It reads the object by name from the metadata cache the shell already holds
15+
* (`readObjectsByName`, the same read `useNavTargetLabel({ byName: true })`
16+
* makes for the entry's text), so the sidebar loads no extra list for it.
17+
* Nothing is stored: a changed object icon shows on the next render. An object
18+
* with no `icon`, or one not loaded yet, answers `undefined` and the row keeps
19+
* the renderer's generic icon.
20+
*/
21+
22+
import { useMemo } from 'react';
23+
import type { NavIconTarget, NavTargetIconResolver } from '@object-ui/layout';
24+
import { useMetadata } from '../providers/MetadataProvider.js';
25+
import { readObjectsByName } from './useObjectPresence.js';
26+
27+
export function useNavTargetIcon(): NavTargetIconResolver {
28+
const metadata = useMetadata();
29+
return useMemo<NavTargetIconResolver>(
30+
() => (target: NavIconTarget) => {
31+
if (target.kind !== 'object') return undefined;
32+
const def = readObjectsByName(metadata, [target.objectName]).find(
33+
(item): item is { name: string; icon?: unknown } =>
34+
!!item && typeof item === 'object' && (item as { name?: unknown }).name === target.objectName,
35+
);
36+
return typeof def?.icon === 'string' && def.icon.trim() !== '' ? def.icon : undefined;
37+
},
38+
[metadata],
39+
);
40+
}

‎ui/packages/app-shell/src/layout/UnifiedSidebar.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import { useFavorites } from '../hooks/useFavorites.js';
5050
import { useNavPins } from '../hooks/useNavPins.js';
5151
import { useNavActionDispatch } from '../hooks/useNavActionDispatch.js';
5252
import { useNavTargetLabel } from '../hooks/useNavTargetLabel.js';
53+
import { useNavTargetIcon } from '../hooks/useNavTargetIcon.js';
5354
import { useNavDocTargetCheck } from '../hooks/useNavDocTargetCheck.js';
5455
import { useNavMemberGates } from '../hooks/useNavMemberGates.js';
5556
import { matchAppBySegment } from '../utils/index.js';
@@ -186,6 +187,7 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi
186187
// metadata cache at render time (objectui#9868). `nav:menu` wires the same
187188
// hook, so the two surfaces cannot name one entry two ways.
188189
const resolveNavTargetLabel = useNavTargetLabel({ byName: true });
190+
const resolveNavTargetIcon = useNavTargetIcon();
189191
// Below the fold width the sidebar is the icon rail and expands over the
190192
// content (objectstack#27593); `useResponsiveSidebar` folds and unfolds it.
191193
const rail = useConsoleSidebarRail({ enabled: railOverlay });
@@ -663,6 +665,7 @@ export function UnifiedSidebar({ activeAppName, railOverlay = false }: UnifiedSi
663665
pinnedOrder={pinnedIds}
664666
onPinnedReorder={reorderPins}
665667
resolveTargetLabel={resolveNavTargetLabel}
668+
resolveTargetIcon={resolveNavTargetIcon}
666669
locale={language}
667670
onAction={dispatchNavAction}
668671
t={t}

0 commit comments

Comments
 (0)