nav cleanup

This commit is contained in:
robert dennis
2026-10-12 21:44:55 -04:00
parent a106396179
commit b2a31fe8ea
13 changed files with 124 additions and 168 deletions
+2 -2
View File
@@ -461,8 +461,8 @@ place, in a `<div>` when it has a `className`.
The other layouts each frame an **area**, a part of the panel with navigation of its own: the account, a
server, or the admin area. They have `model.nav.items`: the area's `NavItem`s, filtered by subuser
permissions and egg rules, extension screens included. Links and items have an `icon`, a lucide name for
`<NamedIcon>`, and a `destination` for `PanelLink` and `usePanelNavigate()`. `<Navigation>` calls its
child with each item and `{ active, badge }`, and keeps an extension screen hidden until its runtime
`<NamedIcon>`, and a `destination` for `PanelLink` and `usePanelNavigate()`. `<Navigation items>` calls
its child with each item and `{ active, badge }`, and keeps an extension screen hidden until its runtime
condition allows it. `NavigationLink` links to an item and carries `data-status="active"` while the item
is active. [`AreaNav`](#the-shell-knows-the-area) below uses both.
+1 -1
View File
@@ -1,7 +1,7 @@
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
export { defineTheme, useTheme, useThemeSettings, type ThemeDefinition, type ThemeIcon, type ThemeIcons, type ThemeScheme, type ThemeSchemePreference, type ThemeSettings, type ThemeSettingValue, type ThemeState, } from "../views/theme.js";
export { skin, useSkin, UI_PRIMITIVE_PARTS, type CompleteSkin, type CompleteSkins, type NoState, type PrimitiveName, type PrimitiveProps, type PrimitiveState, type ReplaceableName, type Skin, type SkinBelow, type SkinBinding, type SkinClassName, type SkinCompoundVariant, type SkinPart, type SkinPartProps, type SkinRecipe, type SkinRecipeConfig, type SkinStateMap, type SkinStateValue, type ThemeSkins, type UiPrimitives, type UiTone, } from "../themes/skins.js";
export { View, ViewFixtureProvider, type ViewElementProps, type ViewFixtureSelection } from "../views/View.js";
export { View, type ViewElementProps } from "../views/View.js";
export { lazyView } from "../views/lazy.js";
export { Main } from "../views/a11y.js";
export { usePageTitle } from "../views/pageTitle.js";
+12 -21
View File
@@ -1,18 +1,14 @@
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
import { type ComponentProps, type ReactElement, type ReactNode } from 'react';
import { type ReactElement, type ReactNode } from 'react';
import { type ScreenArea, type ScreenParent } from "../extensions/registry.js";
import type { PanelDestination } from "../sdk/navigation.js";
import { type PanelDestination, type PanelLinkProps } from "../sdk/navigation.js";
export type NavArea = ScreenArea;
/** An entry of an area's navigation. */
export interface NavItem {
/** The path below the area root (`index` for the root itself); an extension item's screen id. */
readonly id: string;
readonly label: string;
/** The route path, e.g. `/server/$id/files`, filled in from `params`. */
readonly to: string;
readonly params: Readonly<Record<string, string>>;
readonly hash?: string;
/** Where the item leads, for `usePanelNavigate`, `PanelLink` and keyboard shortcuts. */
/** Where the item leads, for `NavigationLink`, `PanelLink`, `usePanelNavigate` and keyboard shortcuts. */
readonly destination: PanelDestination;
/** A lucide icon name, as `NamedIcon` takes it. */
readonly icon: string | null;
@@ -35,8 +31,8 @@ export interface NavItemState {
export type NavigationRenderer = (item: NavItem, state: NavItemState) => ReactNode;
/** A key that is unique within one navigation. */
export declare const navItemKey: (item: NavItem) => string;
/** An item's route path and params as a destination; extension screens' paths resolve the same way. */
export declare const navItemDestination: ({ to, params, hash }: Pick<NavItem, "to" | "params" | "hash">) => PanelDestination;
/** A route path, such as `/server/$id/files`, with its params as a destination; extension screens' paths resolve the same way. */
export declare const navItemDestination: (to: string, params: Readonly<Record<string, string>>, hash?: string) => PanelDestination;
/**
* The navigation of an area, filtered by subuser permissions and egg rules. Screens with a runtime
* predicate stay listed; `<Navigation>` renders them once the predicate allows it.
@@ -55,22 +51,17 @@ export declare function navItemBadge(item: NavItem): ReactNode;
export declare function useNavItemActive(): (item: NavItem) => boolean;
/** The most specific active item, e.g. to title a collapsed navigation. */
export declare function useActiveNavItem(items: readonly NavItem[]): NavItem | undefined;
export type NavigationProps = {
readonly children: NavigationRenderer;
} & ({
readonly area: NavArea;
readonly items?: undefined;
} | {
export interface NavigationProps {
/** Usually a layout model's `nav.items`. */
readonly items: readonly NavItem[];
readonly area?: undefined;
});
readonly children: NavigationRenderer;
}
/**
* Renders each item through `children`, inside the runtime gate of its extension screen, so a
* screen hidden by its predicate renders nothing. `items` (usually a layout model's) take the
* place of the area's live navigation.
* screen hidden by its predicate renders nothing.
*/
export declare function Navigation(props: NavigationProps): import("react").JSX.Element;
export interface NavigationLinkProps extends Omit<ComponentProps<'a'>, 'href'> {
export declare function Navigation({ items, children }: NavigationProps): import("react").JSX.Element;
export interface NavigationLinkProps extends Omit<PanelLinkProps, 'destination' | 'exact' | 'includeSearch'> {
readonly item: NavItem;
}
/** A link to an item; it carries `data-status="active"` while the item is active. */
-2
View File
@@ -24,8 +24,6 @@ export interface AppSearchModel {
readonly shortcut: Shortcut;
/** The search term for an input; its error asks for three characters. */
readonly field: FieldModel;
/** Replaces the term, for a search drawn without an input of its own. */
readonly setQuery: (query: string) => void;
/** The first five servers that match. */
readonly results: readonly AppSearchResult[];
readonly loading: boolean;
@@ -46,22 +46,16 @@ function fakeRect(this: HTMLElement): DOMRect {
return rect(left, widthOf(this));
}
const navItem = ({ label, extension }: Item, order: number): NavItem => {
const to = `/account/${label.toLowerCase()}`;
return {
id: label.toLowerCase(),
label,
to,
params: {},
destination: navItemDestination({ to, params: {} }),
icon: null,
group: null,
order,
exact: false,
extensionId: extension ? 'tabs' : undefined,
};
};
const navItem = ({ label, extension }: Item, order: number): NavItem => ({
id: label.toLowerCase(),
label,
destination: navItemDestination(`/account/${label.toLowerCase()}`, {}),
icon: null,
group: null,
order,
exact: false,
extensionId: extension ? 'tabs' : undefined,
});
async function renderNavigation(
items: Item[],
@@ -1,5 +1,5 @@
import React, { useId, useLayoutEffect, useRef, useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { usePanelNavigate } from '@/sdk/navigation';
import { ChevronDown, Menu } from 'lucide-react';
import { cn } from '@/lib/cn';
import Icon from '@/components/elements/Icon';
@@ -283,14 +283,11 @@ function MenuEntry({
item: NavItem;
render: (item: NavItem, state: SubNavigationItemState) => React.ReactNode;
}) {
const navigate = useNavigate();
const navigate = usePanelNavigate();
const active = useNavItemActive()(item);
return (
<DropdownMenu.Item
className={cn(active && 'bg-muted')}
onClick={() => void navigate({ to: item.to as never, params: item.params as never, hash: item.hash })}
>
<DropdownMenu.Item className={cn(active && 'bg-muted')} onClick={() => void navigate(item.destination)}>
<span className='inline-flex items-center gap-2'>
{render(item, { active, badge: navItemBadge(item), placement: 'menu' })}
</span>
-5
View File
@@ -13,15 +13,10 @@ export interface RawSearch {
email?: string | number | boolean | null;
event?: string | number | boolean | null;
filter?: string | number | boolean | null;
fixture?: string | number | boolean | null;
page?: string | number | boolean | null;
scheme?: string | number | boolean | null;
sort?: string | number | boolean | null;
type?: string | number | boolean | null;
ui?: string | number | boolean | null;
user?: string | number | boolean | null;
view?: string | number | boolean | null;
width?: string | number | boolean | null;
}
/** The URL text of a search value the router JSON-parsed. */
+1 -1
View File
@@ -41,7 +41,7 @@ export {
type UiPrimitives,
type UiTone,
} from '@/themes/skins';
export { View, ViewFixtureProvider, type ViewElementProps, type ViewFixtureSelection } from '@/views/View';
export { View, type ViewElementProps } from '@/views/View';
export { lazyView } from '@/views/lazy';
export { Main } from '@/views/a11y';
export { usePageTitle } from '@/views/pageTitle';
+7 -1
View File
@@ -284,7 +284,13 @@ describe('layout.admin', () => {
nav: {
items: [
...model.nav.items,
{ ...settings, id: 'settings/mail', label: 'Mail', to: '/panel/settings/mail', icon: null },
{
...settings,
id: 'settings/mail',
label: 'Mail',
destination: { to: '/panel/settings/mail' },
icon: null,
},
],
},
};
+17 -22
View File
@@ -145,14 +145,10 @@ function useAccountLayoutModel(): AccountLayoutModel {
}
const adminLink = (internalId: number, order: number): NavItem => {
const params = { id: String(internalId) };
return {
id: 'admin',
label: 'Open Admin Area',
to: '/panel/servers/$id',
params,
destination: { to: '/panel/servers/$id', params },
destination: { to: '/panel/servers/$id', params: { id: String(internalId) } },
icon: 'external-link',
group: null,
order,
@@ -308,24 +304,23 @@ const SERVER_ID = 'a1b2c3d4';
/** Core items of an area as `useNavigation` lists them, from `[path, label, icon, options]`. */
function navFixture(
area: NavArea,
entries: readonly (readonly [string, string, string, Partial<NavItem>?])[]
entries: readonly (readonly [string, string, string, (Partial<NavItem> & { readonly hash?: string })?])[]
): NavigationModel {
return {
items: entries.map(([path, label, icon, options], order) => {
const item = {
id: path || 'index',
label,
to: path ? `${SCREEN_ROOTS[area]}/${path}` : SCREEN_ROOTS[area],
params: area === 'server' ? { id: SERVER_ID } : {},
icon,
group: null,
order,
exact: path === '',
...options,
};
return { ...item, destination: navItemDestination(item) };
}),
items: entries.map(([path, label, icon, { hash, ...options } = {}], order) => ({
id: path || 'index',
label,
destination: navItemDestination(
path ? `${SCREEN_ROOTS[area]}/${path}` : SCREEN_ROOTS[area],
area === 'server' ? { id: SERVER_ID } : {},
hash
),
icon,
group: null,
order,
exact: path === '',
...options,
})),
};
}
@@ -335,7 +330,7 @@ const extensionItem = (area: NavArea, order: number): Partial<NavItem> => ({
icon: 'life-buoy',
group: 'Support',
order,
to: `${SCREEN_ROOTS[area]}/tickets`,
destination: navItemDestination(`${SCREEN_ROOTS[area]}/tickets`, area === 'server' ? { id: SERVER_ID } : {}),
});
const accountNav = (extension = false) =>
+10 -15
View File
@@ -128,9 +128,6 @@ it('lists the server items the subuser may open and whose egg rules match', asyn
expect(listed()[1]).toEqual({
id: 'files',
label: 'Files',
to: '/server/$id/files',
params: { id: 'abc' },
hash: '/',
destination: { to: '/server/$id/files', params: { id: 'abc' }, hash: '/' },
icon: null,
group: null,
@@ -159,22 +156,24 @@ it('picks the most specific active item', async () => {
expect(screen.getAllByRole('listitem').find((entry) => entry.dataset.active)?.textContent).toContain('"files"');
});
it('renders gated items once their predicate allows them, with their live badge', async () => {
let visible = false;
await renderServer(
function ServerNavigation() {
return (
<nav>
<Navigation area='server'>
<Navigation items={useNavigation('server').items}>
{(item, state) => (
<NavigationLink item={item} data-active={state.active || undefined}>
{item.label} {state.badge}
</NavigationLink>
)}
</Navigation>
</nav>,
subuser(),
'/server/abc/files'
</nav>
);
}
it('renders gated items once their predicate allows them, with their live badge', async () => {
let visible = false;
await renderServer(<ServerNavigation />, subuser(), '/server/abc/files');
expect(screen.getByRole('link', { name: 'Console' })).toHaveAttribute('href', '/server/abc');
expect(screen.getByRole('link', { name: 'Files' })).toHaveAttribute('data-active');
@@ -204,8 +203,6 @@ it('builds admin resource tabs from its own and the extension screens beneath it
{
id: 'about',
label: 'About',
to: '/panel/nodes/$id',
params: { id: '42' },
destination: { to: '/panel/nodes/$id', params: { id: '42' } },
icon: null,
group: null,
@@ -215,8 +212,6 @@ it('builds admin resource tabs from its own and the extension screens beneath it
{
id: 'probe',
label: 'Probe',
to: '/panel/nodes/$id/probe',
params: { id: '42' },
destination: { to: '/panel/nodes/$id/probe', params: { id: '42' } },
icon: null,
group: null,
+61 -72
View File
@@ -1,5 +1,5 @@
import { useCallback, useMemo, type ComponentProps, type ReactElement, type ReactNode } from 'react';
import { Link, useMatchRoute } from '@tanstack/react-router';
import { useCallback, useMemo, type ReactElement, type ReactNode } from 'react';
import { useMatchRoute } from '@tanstack/react-router';
import { selectServerPermissions, useServerQuery } from '@/api/server/queries';
import type { Server } from '@/api/server/types';
import {
@@ -15,7 +15,13 @@ import { ScreenBadge, ScreenGate } from '@/extensions/screenNavigation';
import { hasPermission } from '@/plugins/usePermissions';
import { getAreaNav, type AreaNavEntry } from '@/router/nav';
import { useServerRouteId } from '@/router/params';
import type { CorePanelDestination, PanelDestination } from '@/sdk/navigation';
import {
PanelLink,
resolvePanelDestination,
type CorePanelDestination,
type PanelDestination,
type PanelLinkProps,
} from '@/sdk/navigation';
export type NavArea = ScreenArea;
@@ -24,11 +30,7 @@ export interface NavItem {
/** The path below the area root (`index` for the root itself); an extension item's screen id. */
readonly id: string;
readonly label: string;
/** The route path, e.g. `/server/$id/files`, filled in from `params`. */
readonly to: string;
readonly params: Readonly<Record<string, string>>;
readonly hash?: string;
/** Where the item leads, for `usePanelNavigate`, `PanelLink` and keyboard shortcuts. */
/** Where the item leads, for `NavigationLink`, `PanelLink`, `usePanelNavigate` and keyboard shortcuts. */
readonly destination: PanelDestination;
/** A lucide icon name, as `NamedIcon` takes it. */
readonly icon: string | null;
@@ -56,28 +58,27 @@ export type NavigationRenderer = (item: NavItem, state: NavItemState) => ReactNo
/** A key that is unique within one navigation. */
export const navItemKey = (item: NavItem): string => `${item.extensionId ?? ''}:${item.id}`;
/** An item's route path and params as a destination; extension screens' paths resolve the same way. */
export const navItemDestination = ({ to, params, hash }: Pick<NavItem, 'to' | 'params' | 'hash'>): PanelDestination =>
({ to, params, hash }) as CorePanelDestination;
/** A route path, such as `/server/$id/files`, with its params as a destination; extension screens' paths resolve the same way. */
export const navItemDestination = (
to: string,
params: Readonly<Record<string, string>>,
hash?: string
): PanelDestination => ({ to, params, hash }) as CorePanelDestination;
const withDestination = (item: Omit<NavItem, 'destination'>): NavItem => ({
...item,
destination: navItemDestination(item),
});
const toNavItem = (area: NavArea, entry: AreaNavEntry, order: number, params: Record<string, string>): NavItem =>
withDestination({
id: entry.screen?.id ?? (entry.segment || 'index'),
label: entry.label,
to: entry.segment ? `${SCREEN_ROOTS[area]}/${entry.segment}` : SCREEN_ROOTS[area],
const toNavItem = (area: NavArea, entry: AreaNavEntry, order: number, params: Record<string, string>): NavItem => ({
id: entry.screen?.id ?? (entry.segment || 'index'),
label: entry.label,
destination: navItemDestination(
entry.segment ? `${SCREEN_ROOTS[area]}/${entry.segment}` : SCREEN_ROOTS[area],
params,
hash: entry.hash,
icon: entry.icon ?? null,
group: entry.group ?? null,
order,
exact: entry.exact ?? false,
extensionId: entry.screen?.extensionId,
});
entry.hash
),
icon: entry.icon ?? null,
group: entry.group ?? null,
order,
exact: entry.exact ?? false,
extensionId: entry.screen?.extensionId,
});
/** Server items need one of their subuser permissions and, for extension screens, a matching egg. */
function isListed(entry: AreaNavEntry, server: Server | undefined): boolean {
@@ -128,22 +129,25 @@ export function resourceNavigation(
);
return [
...tabs.map((tab, order) =>
withDestination({ ...tab, params, icon: null, group: null, order, exact: tab.exact ?? false })
),
...screens.map(({ id, path, nav, extensionId }, index) =>
withDestination({
id,
label: nav.label,
to: `${SCREEN_ROOTS[parent]}/${resolveScreenPath(path, nav.params)}`,
params,
icon: nav.icon ?? null,
group: nav.group ?? null,
order: tabs.length + index,
exact: nav.exact ?? false,
extensionId,
})
),
...tabs.map(({ id, label, to, exact }, order) => ({
id,
label,
destination: navItemDestination(to, params),
icon: null,
group: null,
order,
exact: exact ?? false,
})),
...screens.map(({ id, path, nav, extensionId }, index) => ({
id,
label: nav.label,
destination: navItemDestination(`${SCREEN_ROOTS[parent]}/${resolveScreenPath(path, nav.params)}`, params),
icon: nav.icon ?? null,
group: nav.group ?? null,
order: tabs.length + index,
exact: nav.exact ?? false,
extensionId,
})),
];
}
@@ -163,8 +167,7 @@ export function useNavItemActive(): (item: NavItem) => boolean {
return useCallback(
(item: NavItem) =>
matchRoute({
to: item.to as never,
params: item.params as never,
to: resolvePanelDestination(item.destination).pathname as never,
fuzzy: !item.exact,
includeSearch: false,
}) !== false,
@@ -172,11 +175,13 @@ export function useNavItemActive(): (item: NavItem) => boolean {
);
}
const pathLength = (item: NavItem): number => resolvePanelDestination(item.destination).pathname.length;
/** The most specific active item, e.g. to title a collapsed navigation. */
export function useActiveNavItem(items: readonly NavItem[]): NavItem | undefined {
const isActive = useNavItemActive();
return items.filter(isActive).sort((a, b) => b.to.length - a.to.length)[0];
return items.filter(isActive).sort((a, b) => pathLength(b) - pathLength(a))[0];
}
function NavigationItems({ items, render }: { items: readonly NavItem[]; render: NavigationRenderer }) {
@@ -189,41 +194,25 @@ function NavigationItems({ items, render }: { items: readonly NavItem[]; render:
));
}
function AreaNavigation({ area, render }: { area: NavArea; render: NavigationRenderer }) {
return <NavigationItems items={useNavigation(area).items} render={render} />;
export interface NavigationProps {
/** Usually a layout model's `nav.items`. */
readonly items: readonly NavItem[];
readonly children: NavigationRenderer;
}
export type NavigationProps = { readonly children: NavigationRenderer } & (
| { readonly area: NavArea; readonly items?: undefined }
| { readonly items: readonly NavItem[]; readonly area?: undefined }
);
/**
* Renders each item through `children`, inside the runtime gate of its extension screen, so a
* screen hidden by its predicate renders nothing. `items` (usually a layout model's) take the
* place of the area's live navigation.
* screen hidden by its predicate renders nothing.
*/
export function Navigation(props: NavigationProps) {
return props.items ? (
<NavigationItems items={props.items} render={props.children} />
) : (
<AreaNavigation area={props.area} render={props.children} />
);
export function Navigation({ items, children }: NavigationProps) {
return <NavigationItems items={items} render={children} />;
}
export interface NavigationLinkProps extends Omit<ComponentProps<'a'>, 'href'> {
export interface NavigationLinkProps extends Omit<PanelLinkProps, 'destination' | 'exact' | 'includeSearch'> {
readonly item: NavItem;
}
/** A link to an item; it carries `data-status="active"` while the item is active. */
export function NavigationLink({ item, ...props }: NavigationLinkProps): ReactElement {
return (
<Link
to={item.to as never}
params={item.params as never}
hash={item.hash}
activeOptions={{ exact: item.exact, includeSearch: false }}
{...props}
/>
);
return <PanelLink destination={item.destination} exact={item.exact} {...props} />;
}
-4
View File
@@ -34,8 +34,6 @@ export interface AppSearchModel {
readonly shortcut: Shortcut;
/** The search term for an input; its error asks for three characters. */
readonly field: FieldModel;
/** Replaces the term, for a search drawn without an input of its own. */
readonly setQuery: (query: string) => void;
/** The first five servers that match. */
readonly results: readonly AppSearchResult[];
readonly loading: boolean;
@@ -90,7 +88,6 @@ function useAppSearchModel(): AppSearchModel {
},
shortcut,
field: { ...field, error: term.length > 0 && term.length < 3 ? SHORT : null },
setQuery: setTerm,
results: enabled ? (data?.data.slice(0, 5) ?? []).map(searchResult) : [],
loading: enabled && isFetching,
searched: enabled && !isFetching && !error && data !== undefined,
@@ -112,7 +109,6 @@ const searchFixture = (options: Partial<AppSearchModel> = {}): AppSearchModel =>
close: noop,
shortcut,
field: fixtureField('term', {}, 'surv'),
setQuery: noop,
results,
loading: false,
searched: true,