layout views

This commit is contained in:
robert dennis
2026-10-12 14:22:58 -04:00
parent 9cf7804d20
commit 3bb514cefa
47 changed files with 1751 additions and 648 deletions
+1 -1
View File
@@ -25,7 +25,7 @@ final readonly class ThemeDocument
public array $tokens = [],
public array $attributes = [],
public string $scheme = 'dark',
public array $schemes = ThemeDefinition::SCHEMES,
public array $schemes = ThemeRepository::CLASSIC_SCHEMES,
public bool $systemScheme = false,
public bool $safeMode = false,
public bool $preview = false,
+5 -2
View File
@@ -20,6 +20,9 @@ class ThemeRepository
/** The built-in theme every chain ends in. */
public const string CLASSIC = 'classic';
/** Classic's light tokens are unaudited, so it only offers its dark scheme. */
public const array CLASSIC_SCHEMES = ['dark'];
/** The `settings` row naming the active theme; without it classic is active. */
public const string SETTING = 'pterodactyl:theme';
@@ -98,7 +101,7 @@ class ThemeRepository
}
/**
* The schemes of the nearest theme in the chain that declares them.
* The schemes of the nearest theme in the chain that declares them, else classic's.
*
* @param list<ExtensionManifest> $chain
* @return non-empty-list<'dark'|'light'>
@@ -111,7 +114,7 @@ class ThemeRepository
}
}
return ThemeDefinition::SCHEMES;
return self::CLASSIC_SCHEMES;
}
/** Why the theme's stylesheet would be laid over the panel's instead of replacing it, or null. */
+3 -4
View File
@@ -24,11 +24,10 @@ const anchorFiles = [
'../../resources/scripts/components/auth/LoginContainer.tsx',
'../../resources/scripts/components/server/users/EditSubuserModal.tsx',
'../../resources/scripts/views/pages.ts',
'../../resources/scripts/router/layouts/AccountLayout.tsx',
'../../resources/scripts/router/layouts/AdminLayout.tsx',
'../../resources/scripts/router/layouts/ServerNavigationLayout.tsx',
'../../resources/scripts/themes/classic/views/layout/AccountLayout.tsx',
'../../resources/scripts/themes/classic/views/layout/AdminLayout.tsx',
'../../resources/scripts/themes/classic/views/layout/ServerLayout.tsx',
'../../resources/scripts/themes/classic/views/layout/AppLayout.tsx',
'../../resources/scripts/components/admin/AdminSidebar.tsx',
'../../resources/scripts/themes/classic/views/dashboard/ServerList.tsx',
'../../resources/scripts/components/dashboard/AccountOverviewContainer.tsx',
'../../resources/scripts/themes/classic/views/dashboard/ServerCard.tsx',
@@ -0,0 +1,27 @@
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
import React from 'react';
import { type NavItem, type NavItemState } from "../../views/navigation.js";
export interface SubNavigationItemState extends NavItemState {
/** In the row, or in the "More" menu once the row ran out of room. */
readonly placement: 'row' | 'menu';
}
export interface SubNavigationProps extends Omit<React.ComponentProps<'div'>, 'children'> {
readonly items: readonly NavItem[];
/** Rendered around the items, typically the area's navigation slots; it never moves into the menu. */
readonly before?: React.ReactNode;
readonly after?: React.ReactNode;
/** The items that may move into the "More" menu; by default those of extensions. */
readonly canOverflow?: (item: NavItem) => boolean;
/** The content of an item's link and menu entry; by default its icon, label and badge. */
readonly renderItem?: (item: NavItem, state: SubNavigationItemState) => React.ReactNode;
}
/**
* An area's horizontal navigation. Items that do not fit move into a "More" menu, and when even
* the pinned ones do not, the row collapses behind a toggle. `<html data-sub-navigation="side">`
* turns it into a sidebar.
*/
declare const SubNavigation: {
({ items, before, after, canOverflow, renderItem, className, ...props }: SubNavigationProps): React.JSX.Element;
displayName: string;
};
export default SubNavigation;
@@ -0,0 +1,9 @@
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
import React from 'react';
interface Props {
navigation: React.ReactNode;
children?: React.ReactNode;
}
/** Stacked by default; a sidebar row when `<html data-sub-navigation="side">` is set. */
declare const SubNavigationLayout: ({ navigation, children }: Props) => React.JSX.Element;
export default SubNavigationLayout;
+13
View File
@@ -0,0 +1,13 @@
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
import type { ReactNode } from 'react';
export interface NavigationLabelProps {
label: string;
/** Shown as the label's title. */
group?: string | null;
/** A lucide icon name. */
icon?: string | null;
/** A navigation item's `state.badge`. */
badge?: ReactNode;
}
/** A navigation item's icon, label and badge. */
export default function NavigationLabel({ label, group, icon, badge }: NavigationLabelProps): import("react").JSX.Element;
+13 -15
View File
@@ -8,33 +8,31 @@ import type { UserData as SdkUser } from "../api/account/types.js";
import type { SiteSettings as SdkSiteSettings } from "../api/settings/types.js";
import type { Server as SdkServer } from "../api/server/types.js";
import { SocketEvent } from "../components/server/events.js";
export { default as Button, LinkButton, RouterLinkButton, type ButtonColor, type ButtonProps, type ButtonSize, } from "../components/elements/Button.js";
export { default as Spinner, type SpinnerProps, type SpinnerSize } from "../components/elements/Spinner.js";
export { default as Button } from "../components/elements/Button.js";
export { default as Spinner } from "../components/elements/Spinner.js";
export { default as Icon } from "../components/elements/Icon.js";
export { default as NamedIcon, loadIconNames, type NamedIconProps } from "../components/elements/NamedIcon.js";
export { default as Can } from "../components/elements/Can.js";
export { default as Card, type CardProps } from "../components/elements/Card.js";
export { default as ListRow, type ListRowProps } from "../components/elements/ListRow.js";
export { default as Badge, type BadgeProps, type BadgeSize, type BadgeVariant } from "../components/elements/Badge.js";
export { default as ProgressBar, type ProgressBarProps, type ProgressBarVariant, } from "../components/elements/ProgressBar.js";
export { default as Code, type CodeProps } from "../components/elements/Code.js";
export { default as ContentBox } from "../components/elements/ContentBox.js";
export { default as PageContentBlock } from "../components/elements/PageContentBlock.js";
export { default as ServerContentBlock } from "../components/elements/ServerContentBlock.js";
export { default as TitledGreyBox } from "../components/elements/TitledGreyBox.js";
export { default as CopyOnClick, type CopyOnClickProps } from "../components/elements/CopyOnClick.js";
export { default as CopyOnClick } from "../components/elements/CopyOnClick.js";
export { default as ScreenBlock, ServerError, NotFound } from "../components/elements/ScreenBlock.js";
export { default as Label, type LabelProps } from "../components/elements/Label.js";
export { default as PageHeading, type PageHeadingProps } from "../components/elements/PageHeading.js";
export { NewButton, NewLinkButton, type NewButtonProps, type NewLinkButtonProps, } from "../components/elements/NewButton.js";
export { default as SpinnerOverlay, type SpinnerOverlayProps } from "../components/elements/SpinnerOverlay.js";
export { TextInput as Input, TextArea, NumberInput, FileInput, type TextInputProps as InputProps, type TextAreaProps, type NumberInputProps, type FileInputProps, } from "../components/form/controls.js";
export { default as Label } from "../components/elements/Label.js";
export { default as PageHeading } from "../components/elements/PageHeading.js";
export { NewButton, NewLinkButton } from "../components/elements/NewButton.js";
export { default as SpinnerOverlay } from "../components/elements/SpinnerOverlay.js";
export { default as SubNavigation, type SubNavigationItemState, type SubNavigationProps, } from "../components/elements/SubNavigation.js";
export { default as SubNavigationLayout } from "../components/elements/SubNavigationLayout.js";
export { default as NavigationLabel, type NavigationLabelProps } from "../extensions/NavigationLabel.js";
export { TextInput as Input, TextArea, NumberInput } from "../components/form/controls.js";
export { Form, useAppForm, useFieldContext, useFormContext, type AppForm, type SelectOption } from "../components/form/index.js";
export { default as Select, type SelectGroup, type SelectProps, type SelectValue } from "../components/ui/Select.js";
export { default as Checkbox, type CheckboxProps } from "../components/ui/Checkbox.js";
export { default as Switch, type SwitchProps } from "../components/ui/Switch.js";
export { Alert, type AlertProps, type AlertType } from "../components/elements/alert/index.js";
export { Dialog, type DialogIconProps, type RenderDialogProps as DialogProps } from "../components/elements/dialog/index.js";
export { Alert } from "../components/elements/alert/index.js";
export { Dialog } from "../components/elements/dialog/index.js";
export { toast } from 'sonner';
export * from "./ui.js";
export { default as http, httpErrorToHuman } from "../api/http.js";
+1
View File
@@ -4,6 +4,7 @@ export { skin, useSkin, UI_PRIMITIVES, type CompleteSkin, type CompleteSkins, ty
export { View, ViewFixtureProvider, type ViewElementProps, type ViewFixtureSelection } from "../views/View.js";
export { lazyView } from "../views/lazy.js";
export { Main } from "../views/a11y.js";
export { Navigation, NavigationLink, useActiveNavItem, useNavigation, type NavArea, type NavigationLinkProps, type NavigationModel, type NavigationProps, type NavigationRenderer, type NavItem, type NavItemState, } from "../views/navigation.js";
export { default as Slot } from "../extensions/Slot.js";
export type { DefaultViewProps, ExtensionViewOptions, ExtensionViewProps, ThemeViews, ViewComponent, ViewContext, ViewImporter, ViewInput, ViewInputs, ViewModel, ViewModels, ViewName, ViewOverride, ViewPartNames, ViewPartProps, ViewParts, ViewProps, } from "../views/registry.js";
export type * from "../views/models.js";
+52 -7
View File
@@ -1,9 +1,21 @@
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
import type { Server } from "../api/server/types.js";
import type { CorePanelDestination } from "../sdk/navigation.js";
import { type NavigationModel, type NavItem } from "./navigation.js";
import { type ThemeScheme } from "./theme.js";
/** A model with nothing in it yet: the view's default renders the existing container as is. */
export type OpaqueModel = Readonly<Record<never, never>>;
export declare const opaqueModel: OpaqueModel;
export declare const useOpaqueModel: () => OpaqueModel;
export interface LayoutBrand {
/** The panel's name. */
readonly name: string;
/** The image the active theme's setting mapped to `--brand-logo` holds, if it has one. */
readonly logoUrl: string | null;
}
export interface AuthLayoutModel {
readonly brand: LayoutBrand;
}
export interface AppLayoutLink {
readonly id: 'dashboard' | 'admin' | 'account';
readonly label: string;
@@ -12,9 +24,7 @@ export interface AppLayoutLink {
readonly exact: boolean;
}
export interface AppLayoutModel {
readonly brand: {
readonly name: string;
};
readonly brand: LayoutBrand;
/** The dashboard, the admin area for root admins, and the account. */
readonly links: readonly AppLayoutLink[];
readonly user: {
@@ -23,17 +33,52 @@ export interface AppLayoutModel {
readonly email: string;
readonly rootAdmin: boolean;
};
readonly scheme: ThemeScheme;
/** The schemes the theme offers; the first is its default. */
readonly schemes: readonly ThemeScheme[];
/** Switches the scheme without a reload; null unless the theme offers more than one. */
readonly setScheme: ((preference: ThemeScheme | 'system') => void) | null;
readonly signOut: () => void;
readonly signingOut: boolean;
}
export interface AccountLayoutModel {
readonly nav: NavigationModel;
}
/** Why a server's pages show a notice instead of their content. */
export type ServerConflict = 'installing' | 'suspended' | 'maintenance' | 'transferring' | 'restoring-backup';
/**
* The server area's frame. Its `children` already hold the server's console, which stays mounted
* while another page shows, and swap the pages for the conflict notice when `conflict` is set.
*/
export interface ServerLayoutModel {
readonly name: string;
readonly identifier: string;
/** The server's id in the admin area. */
readonly internalId: number;
readonly conflict: ServerConflict | null;
/** The server's admin page, for root admins. */
readonly adminLink: NavItem | null;
readonly nav: NavigationModel;
/** The server as the API returns it, which the navigation slots receive. */
readonly server: Server;
}
export interface AdminLayoutModel {
readonly nav: NavigationModel;
readonly user: {
readonly uuid: string;
readonly username: string;
readonly email: string;
};
}
declare module './registry' {
interface ViewModels {
'layout.auth': OpaqueModel;
'layout.auth': AuthLayoutModel;
'layout.app': AppLayoutModel;
'layout.account': OpaqueModel;
'layout.server': OpaqueModel;
'layout.admin': OpaqueModel;
'layout.account': AccountLayoutModel;
'layout.server': ServerLayoutModel;
'layout.admin': AdminLayoutModel;
'app.search': OpaqueModel;
}
}
export declare function serverConflict({ attributes }: Server): ServerConflict | null;
export declare const layoutViews: (import("./registry.js").ViewDefinition<"layout.auth"> | import("./registry.js").ViewDefinition<"layout.app"> | import("./registry.js").ViewDefinition<"layout.account"> | import("./registry.js").ViewDefinition<"layout.server"> | import("./registry.js").ViewDefinition<"layout.admin"> | import("./registry.js").ViewDefinition<"app.search">)[];
+2 -2
View File
@@ -1,5 +1,5 @@
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
export type { DashboardModel, DashboardScope, ServerCardMetric, ServerCardModel, ServerCardState, ServerListItem, ServerListModel, ServerListPagination, ServerPower, } from "./dashboard.js";
export type { DashboardModel, DashboardScope, ServerCardMetric, ServerCardModel, ServerCardState, ServerListItem, ServerListModel, ServerPower, } from "./dashboard.js";
export type { FileDetailsModel, FileEditorModel, FileManagerActions, FileManagerEntry, FileManagerModel, FileManagerPermissions, } from "./files.js";
export type { AppLayoutLink, AppLayoutModel, OpaqueModel } from "./layouts.js";
export type { AccountLayoutModel, AdminLayoutModel, AppLayoutLink, AppLayoutModel, AuthLayoutModel, LayoutBrand, OpaqueModel, ServerConflict, ServerLayoutModel, } from "./layouts.js";
export type { OpaquePageName, PageViewName } from "./pages.js";
+72
View File
@@ -0,0 +1,72 @@
// Generated by scripts/generate-sdk-types.mjs. Do not edit.
import { type ComponentProps, type ReactElement, type ReactNode } from 'react';
import { type ScreenArea, type ScreenParent } from "../extensions/registry.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;
/** A lucide icon name, as `NamedIcon` takes it. */
readonly icon: string | null;
readonly group: string | null;
/** The position in the area navigation: core items in route order, then extension screens by their `order`. */
readonly order: number;
/** Active only on its own path, not below it. */
readonly exact: boolean;
/** The extension whose screen the item opens; core items have none. */
readonly extensionId?: string;
}
export interface NavigationModel {
readonly items: readonly NavItem[];
}
export interface NavItemState {
readonly active: boolean;
/** An extension screen's live badge, its manifest badge until that answers, or null. It suspends locally. */
readonly badge: ReactNode;
}
export type NavigationRenderer = (item: NavItem, state: NavItemState) => ReactNode;
/** A key that is unique within one navigation. */
export declare const navItemKey: (item: NavItem) => string;
/**
* 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.
*/
export declare function useNavigation(area: NavArea): NavigationModel;
export interface ResourceTab {
readonly id: string;
readonly label: string;
readonly to: string;
readonly exact?: boolean;
}
/** The tabs of an admin resource: its own, then the screens extensions add beneath it. */
export declare function resourceNavigation(parent: ScreenParent, params: Readonly<Record<string, string>>, tabs: readonly ResourceTab[]): NavItem[];
export declare function navItemBadge(item: NavItem): ReactNode;
/** Whether an item is active: on its path, or below it unless it is exact. */
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;
} | {
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.
*/
export declare function Navigation(props: NavigationProps): import("react").JSX.Element;
export interface NavigationLinkProps extends Omit<ComponentProps<'a'>, 'href'> {
readonly item: NavItem;
}
/** A link to an item; it carries `data-status="active"` while the item is active. */
export declare function NavigationLink({ item, ...props }: NavigationLinkProps): ReactElement;
+22 -5
View File
@@ -41,7 +41,10 @@
"account.navigation.before",
"account.navigation.after"
],
"fixtures": []
"fixtures": [
"default",
"extension"
]
},
"layout.admin": {
"kind": "layout",
@@ -50,7 +53,10 @@
"panel.navigation.before",
"panel.navigation.after"
],
"fixtures": []
"fixtures": [
"default",
"extension"
]
},
"layout.app": {
"kind": "layout",
@@ -61,14 +67,19 @@
],
"fixtures": [
"user",
"admin"
"admin",
"schemes",
"logo"
]
},
"layout.auth": {
"kind": "layout",
"context": "auth",
"slots": [],
"fixtures": []
"fixtures": [
"default",
"logo"
]
},
"layout.server": {
"kind": "layout",
@@ -77,7 +88,13 @@
"server.navigation.before",
"server.navigation.after"
],
"fixtures": []
"fixtures": [
"owner",
"subuser",
"admin",
"installing",
"suspended"
]
},
"page.account.activity": {
"kind": "page",
@@ -1,82 +0,0 @@
/** @vitest-environment jsdom */
import {
createMemoryHistory,
createRootRoute,
createRoute,
createRouter,
Outlet,
RouterProvider,
} from '@tanstack/react-router';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { publishAreaNav } from '@/router/nav';
import AdminSidebar from './AdminSidebar';
vi.mock('@/extensions/Slot', () => ({ default: () => null }));
afterEach(cleanup);
vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
async function renderSidebar(pathname: string) {
publishAreaNav('admin', [
{ segment: '', label: 'Overview', exact: true },
{ segment: 'settings', label: 'Settings' },
{ segment: 'settings/mail', label: 'Mail' },
{ segment: 'users', label: 'Users' },
]);
const root = createRootRoute({
component: () => (
<>
<AdminSidebar />
<Outlet />
</>
),
});
const route = createRoute({
getParentRoute: () => root,
path: '/panel/$',
component: () => <div>Admin screen</div>,
});
const router = createRouter({
routeTree: root.addChildren([route]),
history: createMemoryHistory({ initialEntries: [pathname] }),
defaultHashScrollIntoView: false,
});
await router.load();
render(<RouterProvider router={router} />);
await screen.findByText('Admin screen');
return router;
}
describe('admin sidebar', () => {
it('labels the mobile disclosure with the most specific matching entry', async () => {
await renderSidebar('/panel/settings/mail');
expect(screen.getByRole('button', { name: 'Mail' })).toHaveAttribute('aria-expanded', 'false');
});
it('toggles the disclosure and closes it after navigation', async () => {
const router = await renderSidebar('/panel/settings');
const disclosure = screen.getByRole('button', { name: 'Settings' });
fireEvent.click(disclosure);
expect(disclosure).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(disclosure);
expect(disclosure).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(disclosure);
await act(async () => router.navigate({ to: '/panel/users' }));
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Users' })).toHaveAttribute('aria-expanded', 'false')
);
expect(screen.getByRole('link', { name: 'Users' })).toHaveAttribute('data-status', 'active');
});
it('does not confuse entries with a shared path prefix', async () => {
await renderSidebar('/panel/users-extra');
expect(screen.getByRole('button', { name: 'Administration' })).toBeInTheDocument();
});
});
@@ -12,9 +12,16 @@ import Icon from '@/components/elements/Icon';
import SubNavigation from '@/components/elements/SubNavigation';
import Spinner from '@/components/elements/Spinner';
import { ServerError } from '@/components/elements/ScreenBlock';
import ResourceExtensionTabs from '@/extensions/ResourceExtensionTabs';
import { ExtensionResourceProvider, type ExtensionResourceContext } from '@/extensions/resourceContext';
import Slot from '@/extensions/Slot';
import { resourceNavigation, type ResourceTab } from '@/views/navigation';
const tabs: ResourceTab[] = [
{ id: 'configuration', label: 'Configuration', to: '/panel/eggs/$eggId', exact: true },
{ id: 'tags', label: 'Tags', to: '/panel/eggs/$eggId/tags' },
{ id: 'variables', label: 'Variables', to: '/panel/eggs/$eggId/variables' },
{ id: 'script', label: 'Install Script', to: '/panel/eggs/$eggId/script' },
];
export default function EggDetailContainer() {
const loadedEgg = eggDetailRoute.useLoaderData();
@@ -58,26 +65,10 @@ export default function EggDetailContainer() {
</div>
</div>
<Slot name='panel.eggs.detail.actions' data={resourceContext} />
<SubNavigation className='mb-4 rounded-sm'>
<Link
data-core
to='/panel/eggs/$eggId'
params={{ eggId }}
activeOptions={{ exact: true, includeSearch: false }}
>
Configuration
</Link>
<Link data-core to='/panel/eggs/$eggId/tags' params={{ eggId }}>
Tags
</Link>
<Link data-core to='/panel/eggs/$eggId/variables' params={{ eggId }}>
Variables
</Link>
<Link data-core to='/panel/eggs/$eggId/script' params={{ eggId }}>
Install Script
</Link>
<ResourceExtensionTabs parent='admin.egg' basePath={`/panel/eggs/${eggId}`} />
</SubNavigation>
<SubNavigation
className='mb-4 rounded-sm'
items={resourceNavigation('admin.egg', { eggId: String(eggId) }, tabs)}
/>
<Outlet />
</AdminContentBlock>
</ExtensionResourceProvider.Provider>
@@ -9,9 +9,18 @@ import Icon from '@/components/elements/Icon';
import SubNavigation from '@/components/elements/SubNavigation';
import Spinner from '@/components/elements/Spinner';
import { ServerError } from '@/components/elements/ScreenBlock';
import ResourceExtensionTabs from '@/extensions/ResourceExtensionTabs';
import { ExtensionResourceProvider, type ExtensionResourceContext } from '@/extensions/resourceContext';
import Slot from '@/extensions/Slot';
import { resourceNavigation, type ResourceTab } from '@/views/navigation';
const tabs: ResourceTab[] = [
{ id: 'about', label: 'About', to: '/panel/nodes/$id', exact: true },
{ id: 'settings', label: 'Settings', to: '/panel/nodes/$id/settings' },
{ id: 'configuration', label: 'Configuration', to: '/panel/nodes/$id/configuration' },
{ id: 'allocation', label: 'Allocation', to: '/panel/nodes/$id/allocation' },
{ id: 'tags', label: 'Tags', to: '/panel/nodes/$id/tags' },
{ id: 'servers', label: 'Servers', to: '/panel/nodes/$id/servers' },
];
export default function NodeDetailContainer() {
const loadedNode = nodeDetailRoute.useLoaderData();
@@ -33,7 +42,6 @@ export default function NodeDetailContainer() {
}
const { attributes } = node;
const params = { id: attributes.id };
return (
<ExtensionResourceProvider.Provider value={resourceContext}>
@@ -50,32 +58,10 @@ export default function NodeDetailContainer() {
Back to Nodes
</Link>
<Slot name='panel.nodes.detail.actions' data={resourceContext} />
<SubNavigation className='mb-6 rounded-sm'>
<Link
data-core
to='/panel/nodes/$id'
params={params}
activeOptions={{ exact: true, includeSearch: false }}
>
About
</Link>
<Link data-core to='/panel/nodes/$id/settings' params={params}>
Settings
</Link>
<Link data-core to='/panel/nodes/$id/configuration' params={params}>
Configuration
</Link>
<Link data-core to='/panel/nodes/$id/allocation' params={params}>
Allocation
</Link>
<Link data-core to='/panel/nodes/$id/tags' params={params}>
Tags
</Link>
<Link data-core to='/panel/nodes/$id/servers' params={params}>
Servers
</Link>
<ResourceExtensionTabs parent='admin.node' basePath={`/panel/nodes/${attributes.id}`} />
</SubNavigation>
<SubNavigation
className='mb-6 rounded-sm'
items={resourceNavigation('admin.node', { id: String(attributes.id) }, tabs)}
/>
<Outlet />
</AdminContentBlock>
</ExtensionResourceProvider.Provider>
@@ -9,9 +9,22 @@ import Icon from '@/components/elements/Icon';
import SubNavigation from '@/components/elements/SubNavigation';
import Spinner from '@/components/elements/Spinner';
import { ServerError } from '@/components/elements/ScreenBlock';
import ResourceExtensionTabs from '@/extensions/ResourceExtensionTabs';
import { ExtensionResourceProvider, type ExtensionResourceContext } from '@/extensions/resourceContext';
import Slot from '@/extensions/Slot';
import { resourceNavigation, type ResourceTab } from '@/views/navigation';
const aboutTab: ResourceTab = { id: 'about', label: 'About', to: '/panel/servers/$id', exact: true };
const installedTabs: ResourceTab[] = [
{ id: 'details', label: 'Details', to: '/panel/servers/$id/details' },
{ id: 'build', label: 'Build', to: '/panel/servers/$id/build' },
{ id: 'startup', label: 'Startup', to: '/panel/servers/$id/startup' },
{ id: 'database', label: 'Database', to: '/panel/servers/$id/database' },
{ id: 'mounts', label: 'Mounts', to: '/panel/servers/$id/mounts' },
];
const manageTabs: ResourceTab[] = [
{ id: 'manage', label: 'Manage', to: '/panel/servers/$id/manage' },
{ id: 'delete', label: 'Delete', to: '/panel/servers/$id/delete' },
];
export default function ServerDetailContainer() {
const loadedServer = serverDetailRoute.useLoaderData();
@@ -33,8 +46,7 @@ export default function ServerDetailContainer() {
}
const { attributes } = server;
const params = { id: attributes.id };
const isInstalled = attributes.container.installed === 1;
const tabs = [aboutTab, ...(attributes.container.installed === 1 ? installedTabs : []), ...manageTabs];
return (
<ExtensionResourceProvider.Provider value={resourceContext}>
@@ -61,42 +73,10 @@ export default function ServerDetailContainer() {
</Link>
</div>
<Slot name='panel.servers.detail.actions' data={resourceContext} />
<SubNavigation className='mb-6 rounded-sm'>
<Link
data-core
to='/panel/servers/$id'
params={params}
activeOptions={{ exact: true, includeSearch: false }}
>
About
</Link>
{isInstalled && (
<>
<Link data-core to='/panel/servers/$id/details' params={params}>
Details
</Link>
<Link data-core to='/panel/servers/$id/build' params={params}>
Build
</Link>
<Link data-core to='/panel/servers/$id/startup' params={params}>
Startup
</Link>
<Link data-core to='/panel/servers/$id/database' params={params}>
Database
</Link>
<Link data-core to='/panel/servers/$id/mounts' params={params}>
Mounts
</Link>
</>
)}
<Link data-core to='/panel/servers/$id/manage' params={params}>
Manage
</Link>
<Link data-core to='/panel/servers/$id/delete' params={params}>
Delete
</Link>
<ResourceExtensionTabs parent='admin.server' basePath={`/panel/servers/${attributes.id}`} />
</SubNavigation>
<SubNavigation
className='mb-6 rounded-sm'
items={resourceNavigation('admin.server', { id: String(attributes.id) }, tabs)}
/>
<Outlet />
</AdminContentBlock>
</ExtensionResourceProvider.Provider>
@@ -26,7 +26,6 @@ import Spinner from '@/components/elements/Spinner';
import { Dialog } from '@/components/elements/dialog';
import { ServerError } from '@/components/elements/ScreenBlock';
import SubNavigation from '@/components/elements/SubNavigation';
import ResourceExtensionTabs from '@/extensions/ResourceExtensionTabs';
import {
ExtensionResourceProvider,
useCurrentResource,
@@ -49,9 +48,12 @@ import { actionsColumn, RowActions } from '@/components/elements/table/RowAction
import ServerEditAction from '@/components/admin/servers/ServerEditAction';
import { Empty, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from '@/components/ui/empty';
import { relationshipData } from '@/api/relationships';
import { resourceNavigation, type ResourceTab } from '@/views/navigation';
type UserForm = AppForm<UserValues>;
const tabs: ResourceTab[] = [{ id: 'about', label: 'About', to: '/panel/users/$id', exact: true }];
const IdentityCard = ({
form,
languageOptions,
@@ -359,17 +361,10 @@ export function UserDetailLayout() {
Back to Users
</Link>
<Slot name='panel.users.detail.actions' data={resourceContext} />
<SubNavigation className='mb-6 rounded-sm'>
<Link
data-core
to='/panel/users/$id'
params={{ id: user.attributes.id }}
activeOptions={{ exact: true, includeSearch: false }}
>
About
</Link>
<ResourceExtensionTabs parent='admin.user' basePath={`/panel/users/${user.attributes.id}`} />
</SubNavigation>
<SubNavigation
className='mb-6 rounded-sm'
items={resourceNavigation('admin.user', { id: String(user.attributes.id) }, tabs)}
/>
<Outlet />
</AdminContentBlock>
</ExtensionResourceProvider.Provider>
@@ -1,6 +1,9 @@
/** @vitest-environment jsdom */
import { cleanup, render, screen } from '@testing-library/react';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { createExtensionTestHost, type ExtensionTestHost } from '@/sdk/testing';
import type { NavItem } from '@/views/navigation';
import SubNavigation from './SubNavigation';
interface Layout {
@@ -12,52 +15,70 @@ interface Layout {
interface Item {
label: string;
width: number;
core?: boolean;
active?: boolean;
/** Extension items may move into the menu; the panel's own stay. */
extension?: boolean;
}
let layout: Layout;
let widths: Map<string, number>;
let host: ExtensionTestHost | undefined;
const rect = (left: number, width: number) => DOMRect.fromRect({ x: left, y: 0, width, height: 40 });
const widthOf = (element: Element) =>
element instanceof HTMLElement ? (widths.get(element.dataset.navItem ?? element.textContent ?? '') ?? 0) : 0;
/** Lays the row's items out left to right at their `data-width`, starting at x = 0 with no padding. */
/** Lays the row's children out left to right at their widths, starting at x = 0 with no padding. */
function fakeRect(this: HTMLElement): DOMRect {
const parent = this.parentElement;
if (parent?.dataset.testid === 'nav') {
if (this.parentElement?.dataset.testid === 'nav') {
return rect(0, layout.rowWidth);
}
if (this.dataset.width === undefined) {
if (this.parentElement?.parentElement?.dataset.testid !== 'nav' || this.querySelector('[aria-haspopup]')) {
return rect(0, layout.moreWidth);
}
let left = 0;
for (let sibling = this.previousElementSibling; sibling instanceof HTMLElement;) {
left += Number(sibling.dataset.width ?? 0);
sibling = sibling.previousElementSibling;
for (let sibling = this.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {
left += widthOf(sibling);
}
return rect(left, Number(this.dataset.width));
return rect(left, widthOf(this));
}
const renderNavigation = (items: Item[]) =>
render(
<SubNavigation data-testid='nav'>
{items.map((item) => (
<a
key={item.label}
href={`#${item.label}`}
data-width={item.width}
data-core={item.core ? '' : undefined}
data-status={item.active ? 'active' : undefined}
>
{item.label}
</a>
))}
</SubNavigation>
);
const navItem = ({ label, extension }: Item, order: number): NavItem => ({
id: label.toLowerCase(),
label,
to: `/account/${label.toLowerCase()}`,
params: {},
icon: null,
group: null,
order,
exact: false,
extensionId: extension ? 'tabs' : undefined,
});
async function renderNavigation(
items: Item[],
options: { path?: string; before?: ReactNode; widths?: Record<string, number> } = {}
) {
const navItems = items.map(navItem);
widths = new Map([
...items.map(
(item, index) => [`${navItems[index].extensionId ?? ''}:${navItems[index].id}`, item.width] as const
),
...Object.entries(options.widths ?? {}),
]);
host = createExtensionTestHost({ path: options.path ?? '/account' });
await act(async () => {
render(<SubNavigation data-testid='nav' items={navItems} before={options.before} />, {
wrapper: host!.Wrapper,
});
});
await screen.findByTestId('nav');
}
const overflowed = () =>
screen
@@ -95,12 +116,14 @@ describe('SubNavigation overflow', () => {
afterEach(() => {
cleanup();
host?.dispose();
host = undefined;
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it('shows every item when they fit', () => {
renderNavigation([
it('shows every item when they fit', async () => {
await renderNavigation([
{ label: 'Console', width: 100 },
{ label: 'Files', width: 100 },
{ label: 'Backups', width: 100 },
@@ -111,27 +134,70 @@ describe('SubNavigation overflow', () => {
expect(moreToggle().hidden).toBe(true);
});
it('keeps core and active items, then fills the rest in order', () => {
renderNavigation([
{ label: 'Console', width: 100, core: true },
{ label: 'Files', width: 100 },
{ label: 'Backups', width: 100 },
{ label: 'Startup', width: 100, active: true },
{ label: 'Settings', width: 40 },
]);
it('keeps the panel items and the active item, fills the rest in order, and lists the others in the menu', async () => {
await renderNavigation(
[
{ label: 'Console', width: 100 },
{ label: 'Files', width: 100, extension: true },
{ label: 'Backups', width: 100, extension: true },
{ label: 'Startup', width: 100, extension: true },
{ label: 'Settings', width: 40, extension: true },
],
{ path: '/account/startup' }
);
// Budget is 400 - 50 = 350: Console + Startup + Files fill 300, Backups would exceed it,
// and filling stops there even though Settings alone would still fit.
expect(overflowed()).toEqual(['Backups', 'Settings']);
expect(screen.getByTestId('nav')).not.toHaveAttribute('data-collapsed');
expect(moreToggle().hidden).toBe(false);
fireEvent.click(screen.getByRole('button', { name: /More/ }));
expect((await screen.findAllByRole('menuitem')).map((entry) => entry.textContent)).toEqual([
'Backups',
'Settings',
]);
});
it('collapses when the core items alone exceed the budget', () => {
renderNavigation([
{ label: 'Console', width: 200, core: true },
{ label: 'Files', width: 200, core: true },
{ label: 'Backups', width: 100 },
it('highlights the menu holding the active item and navigates from it', async () => {
await renderNavigation(
[
{ label: 'Console', width: 300 },
{ label: 'Files', width: 100, extension: true },
{ label: 'Backups', width: 100, extension: true },
],
{ path: '/account/backups' }
);
expect(overflowed()).toEqual(['Files', 'Backups']);
expect(screen.getByRole('button', { name: /More/ })).toHaveClass('shadow-navigation-active');
fireEvent.click(screen.getByRole('button', { name: /More/ }));
fireEvent.click(await screen.findByRole('menuitem', { name: 'Files' }));
await waitFor(() => expect(host!.location().pathname).toBe('/account/files'));
});
it('keeps slot content in the row', async () => {
await renderNavigation(
[
{ label: 'Files', width: 100, extension: true },
{ label: 'Backups', width: 100, extension: true },
],
{ before: <a href='#slot'>Slot link</a>, widths: { 'Slot link': 250 } }
);
// Budget is 350: the slot's 250 always stays, Files fits beside it and Backups does not.
expect(overflowed()).toEqual(['Backups']);
expect(screen.getByText('Slot link')).not.toHaveAttribute('data-overflowed');
});
it('collapses when the pinned items alone exceed the budget', async () => {
await renderNavigation([
{ label: 'Console', width: 200 },
{ label: 'Files', width: 200 },
{ label: 'Backups', width: 100, extension: true },
]);
expect(screen.getByTestId('nav')).toHaveAttribute('data-collapsed');
@@ -140,22 +206,25 @@ describe('SubNavigation overflow', () => {
expect(screen.getByRole('button', { name: /Navigation/ })).toHaveAttribute('aria-expanded', 'false');
});
it('names the collapsed toggle after the active item', () => {
renderNavigation([
{ label: 'Console', width: 300, core: true },
{ label: 'Files', width: 150, core: true, active: true },
]);
it('names the collapsed toggle after the active item', async () => {
await renderNavigation(
[
{ label: 'Console', width: 300 },
{ label: 'Files', width: 150 },
],
{ path: '/account/files' }
);
expect(screen.getByTestId('nav')).toHaveAttribute('data-collapsed');
expect(screen.getByRole('button', { name: /^Files$/ })).toHaveAttribute('aria-expanded', 'false');
});
it('never overflows a column layout', () => {
it('never overflows a column layout', async () => {
layout.direction = 'column';
renderNavigation([
{ label: 'Console', width: 300, core: true },
{ label: 'Files', width: 300 },
{ label: 'Backups', width: 300 },
await renderNavigation([
{ label: 'Console', width: 300 },
{ label: 'Files', width: 300, extension: true },
{ label: 'Backups', width: 300, extension: true },
]);
expect(overflowed()).toEqual([]);
@@ -1,8 +1,20 @@
import React, { useId, useLayoutEffect, useRef, useState } from 'react';
import { useNavigate } from '@tanstack/react-router';
import { ChevronDown, Menu } from 'lucide-react';
import { cn } from '@/lib/cn';
import Icon from '@/components/elements/Icon';
import DropdownMenu from '@/components/elements/dropdown/DropdownMenu';
import NavigationLabel from '@/extensions/NavigationLabel';
import {
Navigation,
NavigationLink,
navItemBadge,
navItemKey,
useActiveNavItem,
useNavItemActive,
type NavItem,
type NavItemState,
} from '@/views/navigation';
const subNavigationClass = [
'w-full bg-card shadow-sm overflow-x-auto scrollbar-none [&::-webkit-scrollbar]:hidden',
@@ -42,60 +54,47 @@ const collapsedNavigationClass = [
'[&[data-collapsed]>div>a[data-status=active]]:bg-popover [&[data-collapsed]>div>div[data-status=active]]:bg-popover',
].join(' ');
const activeSelector = '.active, [data-status=active], [aria-current=page]';
export interface SubNavigationItemState extends NavItemState {
/** In the row, or in the "More" menu once the row ran out of room. */
readonly placement: 'row' | 'menu';
}
interface OverflowItem {
key: number;
element: HTMLElement;
html: string;
label: string;
active: boolean;
export interface SubNavigationProps extends Omit<React.ComponentProps<'div'>, 'children'> {
readonly items: readonly NavItem[];
/** Rendered around the items, typically the area's navigation slots; it never moves into the menu. */
readonly before?: React.ReactNode;
readonly after?: React.ReactNode;
/** The items that may move into the "More" menu; by default those of extensions. */
readonly canOverflow?: (item: NavItem) => boolean;
/** The content of an item's link and menu entry; by default its icon, label and badge. */
readonly renderItem?: (item: NavItem, state: SubNavigationItemState) => React.ReactNode;
}
interface OverflowState {
items: OverflowItem[];
/** Keys of the items moved into the menu, in row order. */
overflowed: string[];
collapsed: boolean;
current: string;
}
const elementKeys = new WeakMap<HTMLElement, number>();
let lastElementKey = 0;
const keyFor = (element: HTMLElement) => {
const key = elementKeys.get(element) ?? ++lastElementKey;
elementKeys.set(element, key);
return key;
};
const isActive = (element: HTMLElement) =>
element.matches(activeSelector) || element.querySelector(activeSelector) !== null;
const isCore = (element: HTMLElement) => element.dataset.core !== undefined;
const labelFor = (element: HTMLElement) =>
element.textContent?.trim() || element.getAttribute('aria-label') || element.title;
const sameState = (previous: OverflowState, next: OverflowState) =>
previous.collapsed === next.collapsed &&
previous.current === next.current &&
previous.items.length === next.items.length &&
previous.items.every(
(item, index) =>
item.element === next.items[index].element &&
item.html === next.items[index].html &&
item.active === next.items[index].active
);
const activate = (element: HTMLElement) =>
(element.matches('a, button') ? element : (element.querySelector<HTMLElement>('a, button') ?? element)).click();
/** What the measurement needs from the model; read through a ref so observers see the latest. */
interface OverflowPolicy {
movable: ReadonlySet<string>;
active: string | undefined;
}
type OverflowLayout = {
collapsed: boolean;
overflowed: HTMLElement[];
};
const itemKeyOf = (element: HTMLElement) => element.dataset.navItem;
const defaultOverflow = (item: NavItem) => item.extensionId !== undefined;
const defaultRender = (item: NavItem, state: SubNavigationItemState) => (
<NavigationLabel label={item.label} group={item.group} icon={item.icon} badge={state.badge} />
);
/** Each child's width including the gap before it, so the widths add up to the row's used space. */
const measureWidths = (row: HTMLElement, children: HTMLElement[], style: CSSStyleDeclaration) => {
const rect = row.getBoundingClientRect();
@@ -113,16 +112,25 @@ const measureWidths = (row: HTMLElement, children: HTMLElement[], style: CSSStyl
return { available, widths };
};
/** Core items always stay; the active item claims the budget next, then the rest in order until it runs out. */
const fitWithinBudget = (children: HTMLElement[], widths: number[], budget: number): OverflowLayout => {
const visible = new Set(children.filter(isCore));
/**
* Pinned children (core items and slot content) always stay; the active item claims the budget
* next, then the rest in order until it runs out.
*/
const fitWithinBudget = (
children: HTMLElement[],
widths: number[],
budget: number,
policy: OverflowPolicy
): OverflowLayout => {
const isMovable = (child: HTMLElement) => policy.movable.has(itemKeyOf(child) ?? '');
const visible = new Set(children.filter((child) => !isMovable(child)));
let used = children.reduce((sum, child, index) => sum + (visible.has(child) ? widths[index] : 0), 0);
if (used > budget) {
return { collapsed: true, overflowed: [] };
}
const active = children.findIndex((child) => !visible.has(child) && isActive(child));
const active = children.findIndex((child) => !visible.has(child) && itemKeyOf(child) === policy.active);
if (active !== -1 && used + widths[active] <= budget) {
visible.add(children[active]);
@@ -146,7 +154,12 @@ const fitWithinBudget = (children: HTMLElement[], widths: number[], budget: numb
};
/** Shows the "more" toggle while measuring its width when the row overflows. */
const overflowLayout = (row: HTMLElement, children: HTMLElement[], more: HTMLElement): OverflowLayout => {
const overflowLayout = (
row: HTMLElement,
children: HTMLElement[],
more: HTMLElement,
policy: OverflowPolicy
): OverflowLayout => {
const style = getComputedStyle(row);
if (style.flexDirection === 'column') {
@@ -163,15 +176,28 @@ const overflowLayout = (row: HTMLElement, children: HTMLElement[], more: HTMLEle
more.hidden = false;
const budget = available - more.getBoundingClientRect().width - parseFloat(getComputedStyle(more).marginLeft);
return fitWithinBudget(children, widths, budget);
return fitWithinBudget(children, widths, budget, policy);
};
const sameState = (previous: OverflowState, next: OverflowState) =>
previous.collapsed === next.collapsed && previous.overflowed.join('\n') === next.overflowed.join('\n');
/**
* Measures the rendered row and marks what does not fit with `data-overflowed` (or the whole
* navigation with `data-collapsed`). Gated items render nothing, so the row is what counts; the
* menu is then built from the model.
*/
function useOverflowNavigation(
rootRef: React.RefObject<HTMLDivElement | null>,
rowRef: React.RefObject<HTMLDivElement | null>,
moreRef: React.RefObject<HTMLSpanElement | null>
moreRef: React.RefObject<HTMLSpanElement | null>,
policy: OverflowPolicy
) {
const [state, setState] = useState<OverflowState>({ items: [], collapsed: false, current: '' });
const [state, setState] = useState<OverflowState>({ overflowed: [], collapsed: false });
const policyRef = useRef(policy);
const updateRef = useRef<() => void>(undefined);
policyRef.current = policy;
useLayoutEffect(() => {
const root = rootRef.current;
@@ -196,7 +222,7 @@ function useOverflowNavigation(
delete root.dataset.collapsed;
more.hidden = true;
const { collapsed, overflowed } = overflowLayout(row, children, more);
const { collapsed, overflowed } = overflowLayout(row, children, more, policyRef.current);
if (collapsed) {
root.dataset.collapsed = '';
@@ -208,22 +234,15 @@ function useOverflowNavigation(
more.hidden = overflowed.length === 0;
const activeChild = children.find(isActive);
const next: OverflowState = {
collapsed,
current: activeChild ? labelFor(activeChild) : '',
items: overflowed.map((element) => ({
key: keyFor(element),
element,
html: element.innerHTML,
label: element.textContent?.trim() ? '' : labelFor(element),
active: isActive(element),
})),
overflowed: overflowed.flatMap((child) => itemKeyOf(child) ?? []),
};
setState((previous) => (sameState(previous, next) ? previous : next));
};
updateRef.current = update;
update();
const mutationObserver = new MutationObserver(update);
@@ -232,7 +251,7 @@ function useOverflowNavigation(
childList: true,
subtree: true,
characterData: true,
attributeFilter: ['class', 'data-status', 'aria-current', 'data-core'],
attributeFilter: ['class', 'data-status', 'aria-current'],
});
const resizeObserver = new ResizeObserver(update);
@@ -243,22 +262,69 @@ function useOverflowNavigation(
return () => {
mounted = false;
updateRef.current = undefined;
mutationObserver.disconnect();
resizeObserver.disconnect();
};
}, [rootRef, rowRef, moreRef]);
const movable = [...policy.movable].join('\n');
// A model change that leaves the row's DOM alone still changes what may move.
useLayoutEffect(() => updateRef.current?.(), [movable, policy.active]);
return state;
}
const SubNavigation = ({ className, children, ...props }: React.ComponentProps<'div'>) => {
function MenuEntry({
item,
render,
}: {
item: NavItem;
render: (item: NavItem, state: SubNavigationItemState) => React.ReactNode;
}) {
const navigate = useNavigate();
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 })}
>
<span className='inline-flex items-center gap-2'>
{render(item, { active, badge: navItemBadge(item), placement: 'menu' })}
</span>
</DropdownMenu.Item>
);
}
/**
* An area's horizontal navigation. Items that do not fit move into a "More" menu, and when even
* the pinned ones do not, the row collapses behind a toggle. `<html data-sub-navigation="side">`
* turns it into a sidebar.
*/
const SubNavigation = ({
items,
before,
after,
canOverflow = defaultOverflow,
renderItem = defaultRender,
className,
...props
}: SubNavigationProps) => {
const rootRef = useRef<HTMLDivElement>(null);
const rowRef = useRef<HTMLDivElement>(null);
const moreRef = useRef<HTMLSpanElement>(null);
const rowId = useId();
const [open, setOpen] = useState(false);
const { items, collapsed, current } = useOverflowNavigation(rootRef, rowRef, moreRef);
const isActive = useNavItemActive();
const current = useActiveNavItem(items);
const { overflowed, collapsed } = useOverflowNavigation(rootRef, rowRef, moreRef, {
movable: new Set(items.filter(canOverflow).map(navItemKey)),
active: current && navItemKey(current),
});
const expanded = collapsed && open;
const menu = items.filter((item) => overflowed.includes(navItemKey(item)));
return (
<div
@@ -275,7 +341,7 @@ const SubNavigation = ({ className, children, ...props }: React.ComponentProps<'
className='mx-auto hidden w-full max-w-panel cursor-pointer items-center gap-3 px-6 py-3 text-sm text-foreground'
>
<Icon icon={Menu} className='h-4 w-4 shrink-0' aria-hidden />
<span className='min-w-0 flex-1 truncate text-left'>{current || 'Navigation'}</span>
<span className='min-w-0 flex-1 truncate text-left'>{current?.label || 'Navigation'}</span>
<Icon
icon={ChevronDown}
className={cn('h-4 w-4 shrink-0 transition-transform', expanded && 'rotate-180')}
@@ -283,13 +349,21 @@ const SubNavigation = ({ className, children, ...props }: React.ComponentProps<'
/>
</button>
<div ref={rowRef} id={rowId} onClick={() => setOpen(false)}>
{children}
{before}
<Navigation items={items}>
{(item, state) => (
<NavigationLink item={item} data-nav-item={navItemKey(item)}>
{renderItem(item, { ...state, placement: 'row' })}
</NavigationLink>
)}
</Navigation>
{after}
<span ref={moreRef} className='ml-2 shrink-0'>
<DropdownMenu
openOnHover
triggerClassName={cn(
'inline-flex cursor-pointer items-center gap-1 whitespace-nowrap px-4 py-3 text-muted-foreground transition-colors duration-150 hover:text-foreground',
items.some((item) => item.active) && 'text-foreground shadow-navigation-active'
menu.some(isActive) && 'text-foreground shadow-navigation-active'
)}
triggerContent={
<>
@@ -298,17 +372,8 @@ const SubNavigation = ({ className, children, ...props }: React.ComponentProps<'
</>
}
>
{items.map((item) => (
<DropdownMenu.Item
key={item.key}
className={cn(item.active && 'bg-muted')}
onClick={() => activate(item.element)}
>
<span className='inline-flex items-center gap-2'>
<span data-overflowed dangerouslySetInnerHTML={{ __html: item.html }} />
{item.label && <span>{item.label}</span>}
</span>
</DropdownMenu.Item>
{menu.map((item) => (
<MenuEntry key={navItemKey(item)} item={item} render={renderItem} />
))}
</DropdownMenu>
</span>
@@ -1,18 +1,23 @@
import type { ReactNode } from 'react';
import NamedIcon from '@/components/elements/NamedIcon';
import type { ExtensionScreenDefinition, ExtensionScreenRegistration } from './registry';
import { ScreenBadge } from './screenNavigation';
type Props = NonNullable<ExtensionScreenDefinition['nav']> & {
/** Enables the screen's live badge. */
screen?: ExtensionScreenRegistration;
};
export interface NavigationLabelProps {
label: string;
/** Shown as the label's title. */
group?: string | null;
/** A lucide icon name. */
icon?: string | null;
/** A navigation item's `state.badge`. */
badge?: ReactNode;
}
export default function NavigationLabel({ label, group, badge, icon, screen }: Props) {
/** A navigation item's icon, label and badge. */
export default function NavigationLabel({ label, group, icon, badge }: NavigationLabelProps) {
return (
<span className='inline-flex items-center gap-2 align-top' title={group}>
<span className='inline-flex items-center gap-2 align-top' title={group ?? undefined}>
{icon && <NamedIcon name={icon} size={16} className='shrink-0' aria-hidden />}
<span>{label}</span>
<ScreenBadge screen={screen} badge={badge} />
{badge}
</span>
);
}
@@ -1,19 +0,0 @@
import NavLink from '@/router/NavLink';
import { getExtensionScreens, resolveScreenPath, type ScreenParent } from './registry';
import NavigationLabel from './NavigationLabel';
import { ScreenGate } from './screenNavigation';
export default function ResourceExtensionTabs({ parent, basePath }: { parent: ScreenParent; basePath: string }) {
return getExtensionScreens('admin', parent).map((screen) =>
screen.nav ? (
<ScreenGate key={`${screen.extensionId}:${screen.id}`} screen={screen}>
<NavLink
to={`${basePath}/${resolveScreenPath(screen.path, screen.nav.params)}`}
exact={screen.nav.exact}
>
<NavigationLabel {...screen.nav} screen={screen} />
</NavLink>
</ScreenGate>
) : null
);
}
@@ -41,7 +41,7 @@ afterEach(() => {
async function mountPanel(entries: SiteExtensionEntry[], options: { server?: SdkServer; path?: string } = {}) {
const registry = await import('@/extensions/registry');
const { ScreenGate } = await import('@/extensions/screenNavigation');
const { ScreenBadge, ScreenGate } = await import('@/extensions/screenNavigation');
const { default: NavigationLabel } = await import('@/extensions/NavigationLabel');
const { extensionScreenComponent } = await import('@/extensions/screen');
const { serverQueryKey } = await import('@/api/server/queries');
@@ -64,7 +64,10 @@ async function mountPanel(entries: SiteExtensionEntry[], options: { server?: Sdk
{screens.map((registration) => (
<ScreenGate key={`${registration.extensionId}:${registration.id}`} screen={registration}>
<a href={`/${registration.path}`}>
<NavigationLabel {...registration.nav!} screen={registration} />
<NavigationLabel
{...registration.nav!}
badge={<ScreenBadge screen={registration} badge={registration.nav?.badge} />}
/>
</a>
</ScreenGate>
))}
@@ -1,35 +0,0 @@
import type { ReactNode } from 'react';
import SubNavigation from '@/components/elements/SubNavigation';
import SubNavigationLayout from '@/components/elements/SubNavigationLayout';
import NavLink from '@/router/NavLink';
import { getAreaNav } from '@/router/nav';
import Slot from '@/extensions/Slot';
import NavigationLabel from '@/extensions/NavigationLabel';
import { ScreenGate } from '@/extensions/screenNavigation';
import { Main } from '@/views/a11y';
export default function AccountLayout({ children }: { children?: ReactNode }) {
return (
<SubNavigationLayout
navigation={
<SubNavigation>
<Slot name='account.navigation.before' />
{getAreaNav('account').map(({ segment, label, exact = false, ...meta }) => (
<ScreenGate key={segment || '/'} screen={meta.screen}>
<NavLink
to={`/account${segment ? `/${segment}` : ''}`}
exact={exact}
data-core={meta.screen ? undefined : ''}
>
<NavigationLabel label={label} {...meta} />
</NavLink>
</ScreenGate>
))}
<Slot name='account.navigation.after' />
</SubNavigation>
}
>
<Main>{children}</Main>
</SubNavigationLayout>
);
}
@@ -1,14 +0,0 @@
import type { ReactNode } from 'react';
import AdminSidebar from '@/components/admin/AdminSidebar';
import { Main } from '@/views/a11y';
export default function AdminLayout({ children }: { children?: ReactNode }) {
return (
<div className='mx-auto flex w-full max-w-panel flex-col lg:flex-row'>
<AdminSidebar />
<div className='min-w-0 flex-1 xl:pl-4'>
<Main>{children}</Main>
</div>
</div>
);
}
@@ -1,10 +0,0 @@
import type { ReactNode } from 'react';
import { Main } from '@/views/a11y';
export default function AuthLayout({ children }: { children?: ReactNode }) {
return (
<div className='pt-8 xl:pt-32'>
<Main>{children}</Main>
</div>
);
}
@@ -16,7 +16,10 @@ import { useCurrentUser } from '@/api/account/queries';
import { LayoutView } from '@/router/viewRoutes';
import { View } from '@/views/View';
/** The routed content of `layout.server`: the server's listeners, its console and the current page. */
/**
* The children of `layout.server`: the server's listeners, its console and the current page, or
* the conflict notice instead of both. The engine owns them, so a theme's layout only places them in <Main>.
*/
function ServerContent({ id, server }: { id: string; server: Server }) {
const location = useLocation();
const rootAdmin = useCurrentUser().rootAdmin;
@@ -1,78 +0,0 @@
import type { ReactNode } from 'react';
import { Link, useParams } from '@tanstack/react-router';
import { ExternalLink } from 'lucide-react';
import { useServerQuery } from '@/api/server/queries';
import { useCurrentUser } from '@/api/account/queries';
import SubNavigation from '@/components/elements/SubNavigation';
import SubNavigationLayout from '@/components/elements/SubNavigationLayout';
import NavLink from '@/router/NavLink';
import Can from '@/components/elements/Can';
import Icon from '@/components/elements/Icon';
import { getAreaNav } from '@/router/nav';
import Slot from '@/extensions/Slot';
import NavigationLabel from '@/extensions/NavigationLabel';
import { ScreenGate } from '@/extensions/screenNavigation';
import { Main } from '@/views/a11y';
/** The classic server layout: the server's sub-navigation beside its pages. */
export default function ServerNavigationLayout({ children }: { children?: ReactNode }) {
const { id } = useParams({ from: '/authenticated/server/$id' });
const rootAdmin = useCurrentUser().rootAdmin;
// The engine renders the layout once the server has loaded.
const server = useServerQuery(id).data!;
const to = (segment: string) => `/server/${id}${segment ? `/${segment}` : ''}`;
return (
<SubNavigationLayout
navigation={
<SubNavigation>
<Slot name='server.navigation.before' data={server} />
{getAreaNav('server').map(({ segment, label, exact, permission, ...meta }) => (
<ScreenGate key={segment || '/'} screen={meta.screen}>
{permission ? (
<Can action={permission} matchAny>
<NavLink
to={to(segment)}
exact={exact}
hash={segment === 'files' ? '/' : ''}
data-core={meta.screen ? undefined : ''}
>
<NavigationLabel label={label} {...meta} />
</NavLink>
</Can>
) : (
<NavLink
to={to(segment)}
exact={exact}
hash={segment === 'files' ? '/' : ''}
data-core={meta.screen ? undefined : ''}
>
<NavigationLabel label={label} {...meta} />
</NavLink>
)}
</ScreenGate>
))}
{rootAdmin && (
<Link
to='/panel/servers/$id'
params={{ id: server.attributes.internal_id }}
aria-label='Open server administration'
title='Open server administration'
>
<span className='inline-flex items-center gap-2 align-top'>
<Icon icon={ExternalLink} />
<span className='hidden in-data-collapsed:inline in-data-overflowed:inline'>
Open Admin Area
</span>
</span>
</Link>
)}
<Slot name='server.navigation.after' data={server} />
</SubNavigation>
}
>
<Main>{children}</Main>
</SubNavigationLayout>
);
}
+2
View File
@@ -8,6 +8,8 @@ export interface RouteNavMeta {
/** Subuser permissions; any one shows the link. */
permission?: string | string[];
params?: Record<string, string>;
/** Sent with the link, e.g. the file manager's root directory. */
hash?: string;
group?: string;
badge?: string;
/** A lucide icon name. */
+14 -14
View File
@@ -256,7 +256,7 @@ const serverChildren = [
createRoute({
getParentRoute: () => serverRoute,
path: 'files',
staticData: { nav: { label: 'Files', permission: 'file.*' } },
staticData: { nav: { label: 'Files', permission: 'file.*', hash: '/' } },
beforeLoad: requireServerPermission('file.*'),
component: pageRoute('page.server.files', 'file.*'),
}),
@@ -695,7 +695,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: '/',
staticData: { nav: { label: 'Overview', exact: true } },
staticData: { nav: { label: 'Overview', exact: true, icon: 'layout-dashboard' } },
loader: async ({ context }) => {
await context.queryClient.ensureQueryData({ ...adminVersionQueryOptions(), revalidateIfStale: true });
},
@@ -725,7 +725,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'settings',
staticData: { nav: { label: 'Settings' } },
staticData: { nav: { label: 'Settings', icon: 'settings' } },
loader: async ({ context }) => {
await context.queryClient.ensureQueryData({ ...adminSettingsQueryOptions(), revalidateIfStale: true });
},
@@ -750,7 +750,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'users',
staticData: { nav: { label: 'Users' } },
staticData: { nav: { label: 'Users', icon: 'users' } },
validateSearch: parseUserListSearch,
loaderDeps: ({ search }) => ({ page: search.page ?? 1, filter: search.filter ?? '', sort: search.sort }),
loader: async ({ context, deps }) => {
@@ -769,7 +769,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'locations',
staticData: { nav: { label: 'Locations' } },
staticData: { nav: { label: 'Locations', icon: 'map-pin' } },
validateSearch: parseLocationListSearch,
loaderDeps: ({ search }) => ({ page: search.page ?? 1, filter: search.filter ?? '', sort: search.sort }),
loader: async ({ context, deps }) => {
@@ -784,7 +784,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'nodes',
staticData: { nav: { label: 'Nodes' } },
staticData: { nav: { label: 'Nodes', icon: 'network' } },
validateSearch: parseNodeListSearch,
loaderDeps: ({ search }) => ({ page: search.page ?? 1, filter: search.filter ?? '', sort: search.sort }),
loader: async ({ context, deps }) => {
@@ -803,7 +803,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'servers',
staticData: { nav: { label: 'Servers' } },
staticData: { nav: { label: 'Servers', icon: 'server' } },
validateSearch: parseServerListSearch,
loaderDeps: ({ search }) => ({ page: search.page ?? 1, filter: search.filter ?? '', sort: search.sort }),
loader: async ({ context, deps }) => {
@@ -839,7 +839,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'databases',
staticData: { nav: { label: 'Database Hosts' } },
staticData: { nav: { label: 'Database Hosts', icon: 'database' } },
validateSearch: parseDatabaseHostListSearch,
loaderDeps: ({ search }) => ({ page: search.page ?? 1, filter: search.filter ?? '', sort: search.sort }),
loader: async ({ context, deps }) => {
@@ -859,7 +859,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'mounts',
staticData: { nav: { label: 'Mounts' } },
staticData: { nav: { label: 'Mounts', icon: 'folder-tree' } },
validateSearch: parseMountListSearch,
loaderDeps: ({ search }) => ({ page: search.page ?? 1, filter: search.filter ?? '', sort: search.sort }),
loader: async ({ context, deps }) => {
@@ -879,7 +879,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'eggs',
staticData: { nav: { label: 'Eggs' } },
staticData: { nav: { label: 'Eggs', icon: 'egg' } },
loader: async ({ context }) => {
await context.queryClient.ensureQueryData({ ...adminEggsQueryOptions(), revalidateIfStale: true });
},
@@ -901,7 +901,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'tags',
staticData: { nav: { label: 'Tags' } },
staticData: { nav: { label: 'Tags', icon: 'tag' } },
validateSearch: parseTagListSearch,
loaderDeps: ({ search }) => ({ page: search.page ?? 1, filter: search.filter ?? '', sort: search.sort }),
loader: async ({ context, deps }) => {
@@ -915,7 +915,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'extensions',
staticData: { nav: { label: 'Extensions' } },
staticData: { nav: { label: 'Extensions', icon: 'blocks' } },
loader: async ({ context }) => {
await context.queryClient.ensureQueryData({ ...adminExtensionsQueryOptions(), revalidateIfStale: true });
},
@@ -924,7 +924,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'themes',
staticData: { nav: { label: 'Themes' } },
staticData: { nav: { label: 'Themes', icon: 'palette' } },
loader: async ({ context }) => {
await context.queryClient.ensureQueryData({ ...adminThemesQueryOptions(), revalidateIfStale: true });
},
@@ -933,7 +933,7 @@ const panelChildren = [
createRoute({
getParentRoute: () => panelRoute,
path: 'api',
staticData: { nav: { label: 'API Keys' } },
staticData: { nav: { label: 'API Keys', icon: 'key-round' } },
validateSearch: parseApiKeyListSearch,
loaderDeps: ({ search }) => ({ page: search.page ?? 1, filter: search.filter ?? '', sort: search.sort }),
loader: async ({ context, deps }) => {
+7
View File
@@ -77,6 +77,13 @@ export {
type NumberInputProps,
type FileInputProps,
} from '@/components/form/controls';
export {
default as SubNavigation,
type SubNavigationItemState,
type SubNavigationProps,
} from '@/components/elements/SubNavigation';
export { default as SubNavigationLayout } from '@/components/elements/SubNavigationLayout';
export { default as NavigationLabel, type NavigationLabelProps } from '@/extensions/NavigationLabel';
export { Form, useAppForm, useFieldContext, useFormContext, type AppForm, type SelectOption } from '@/components/form';
export { default as Select, type SelectGroup, type SelectProps, type SelectValue } from '@/components/ui/Select';
export { default as Checkbox, type CheckboxProps } from '@/components/ui/Checkbox';
+13
View File
@@ -45,6 +45,19 @@ export {
export { View, ViewFixtureProvider, type ViewElementProps, type ViewFixtureSelection } from '@/views/View';
export { lazyView } from '@/views/lazy';
export { Main } from '@/views/a11y';
export {
Navigation,
NavigationLink,
useActiveNavItem,
useNavigation,
type NavArea,
type NavigationLinkProps,
type NavigationModel,
type NavigationProps,
type NavigationRenderer,
type NavItem,
type NavItemState,
} from '@/views/navigation';
export { default as Slot } from '@/extensions/Slot';
export type {
DefaultViewProps,
@@ -1,11 +1,16 @@
import { lazyView, type ThemeViews } from '@/sdk/theme';
import AuthLayout from './layout/AuthLayout';
const layout = () => import('./layout/AppLayout');
const dashboard = () => import('./dashboard');
/** Classic's own views; the rest still render the existing containers as their default. */
export const classicViews: ThemeViews = {
'layout.app': lazyView(layout),
// The sign-in screen renders without waiting for a chunk.
'layout.auth': AuthLayout,
'layout.app': lazyView(() => import('./layout/AppLayout')),
'layout.account': lazyView(() => import('./layout/AccountLayout')),
'layout.server': lazyView(() => import('./layout/ServerLayout')),
'layout.admin': lazyView(() => import('./layout/AdminLayout')),
'page.dashboard': lazyView(dashboard, 'Dashboard'),
'dashboard.serverList': lazyView(dashboard, 'ServerList'),
'dashboard.serverCard': lazyView(dashboard, 'ServerCard'),
@@ -0,0 +1,18 @@
import { SubNavigation, SubNavigationLayout } from '@/sdk';
import { Main, Slot, type ViewProps } from '@/sdk/theme';
export default function AccountLayout({ model, children }: ViewProps<'layout.account'>) {
return (
<SubNavigationLayout
navigation={
<SubNavigation
items={model.nav.items}
before={<Slot name='account.navigation.before' />}
after={<Slot name='account.navigation.after' />}
/>
}
>
<Main>{children}</Main>
</SubNavigationLayout>
);
}
@@ -1,5 +1,4 @@
import { useEffect, useState } from 'react';
import { useLocation } from '@tanstack/react-router';
import { useEffect, useState, type ReactNode } from 'react';
import {
Blocks,
ChevronDown,
@@ -19,32 +18,35 @@ import {
Users,
type LucideIcon,
} from 'lucide-react';
import NavLink from '@/router/NavLink';
import Icon from '@/components/elements/Icon';
import Slot from '@/extensions/Slot';
import NavigationLabel from '@/extensions/NavigationLabel';
import { ScreenGate } from '@/extensions/screenNavigation';
import { getAreaNav, type AreaNavEntry } from '@/router/nav';
import { cn } from '@/lib/cn';
import { cn, Icon, NavigationLabel, usePanelLocation } from '@/sdk';
import {
Main,
Navigation,
NavigationLink,
Slot,
useActiveNavItem,
type NavigationModel,
type NavItem,
type ViewProps,
} from '@/sdk/theme';
// The panel's own items render these directly, so they never wait for the icon catalog.
const icons = new Map<string, LucideIcon>([
['', LayoutDashboard],
['layout-dashboard', LayoutDashboard],
['settings', Settings],
['users', Users],
['locations', MapPin],
['nodes', Network],
['servers', Server],
['databases', Database],
['mounts', FolderTree],
['eggs', Egg],
['tags', Tag],
['extensions', Blocks],
['themes', Palette],
['api', KeyRound],
['map-pin', MapPin],
['network', Network],
['server', Server],
['database', Database],
['folder-tree', FolderTree],
['egg', Egg],
['tag', Tag],
['blocks', Blocks],
['palette', Palette],
['key-round', KeyRound],
]);
const iconFor = (segment: string): LucideIcon => icons.get(segment) ?? Puzzle;
const itemClass = [
'flex items-center gap-3 rounded-md px-3 py-2 text-sm no-underline',
'text-muted-foreground transition-colors duration-150',
@@ -60,26 +62,24 @@ const extensionItemsClass = [
'[&_a[data-status=active]]:bg-popover [&_a[data-status=active]]:text-foreground',
].join(' ');
const hrefFor = ({ segment }: AreaNavEntry) => `/panel${segment ? `/${segment}` : ''}`;
function ItemLabel({ item, badge }: { item: NavItem; badge: ReactNode }) {
const glyph = item.extensionId === undefined && item.icon ? icons.get(item.icon) : undefined;
const activeEntry = (entries: AreaNavEntry[], pathname: string) =>
entries
.filter((entry) => {
const href = hrefFor(entry);
return (
<>
{(glyph !== undefined || !item.icon) && <Icon icon={glyph ?? Puzzle} className='w-4 h-4 shrink-0' />}
<NavigationLabel label={item.label} group={item.group} icon={glyph ? null : item.icon} badge={badge} />
</>
);
}
return entry.exact ? pathname === href : pathname === href || pathname.startsWith(`${href}/`);
})
.sort((a, b) => b.segment.length - a.segment.length)[0];
export default function AdminSidebar() {
function AdminSidebar({ nav }: { nav: NavigationModel }) {
const [open, setOpen] = useState(false);
const { pathname } = useLocation();
const entries = getAreaNav('admin');
const { pathname } = usePanelLocation();
const current = useActiveNavItem(nav.items);
useEffect(() => setOpen(false), [pathname]);
const current = activeEntry(entries, pathname);
return (
<div className={cn('w-full shrink-0 px-4 pt-4', 'lg:w-sidebar lg:px-0 lg:pt-0')}>
<button
@@ -111,14 +111,13 @@ export default function AdminSidebar() {
<div className={extensionItemsClass}>
<Slot name='panel.navigation.before' />
</div>
{entries.map((entry) => (
<ScreenGate key={entry.segment || '/'} screen={entry.screen}>
<NavLink to={hrefFor(entry)} exact={entry.exact ?? false} className={itemClass}>
{!entry.icon && <Icon icon={iconFor(entry.segment)} className='w-4 h-4 shrink-0' />}
<NavigationLabel {...entry} />
</NavLink>
</ScreenGate>
))}
<Navigation items={nav.items}>
{(item, state) => (
<NavigationLink item={item} className={itemClass}>
<ItemLabel item={item} badge={state.badge} />
</NavigationLink>
)}
</Navigation>
<div className={extensionItemsClass}>
<Slot name='panel.navigation.after' />
</div>
@@ -126,3 +125,14 @@ export default function AdminSidebar() {
</div>
);
}
export default function AdminLayout({ model, children }: ViewProps<'layout.admin'>) {
return (
<div className='mx-auto flex w-full max-w-panel flex-col lg:flex-row'>
<AdminSidebar nav={model.nav} />
<div className='min-w-0 flex-1 xl:pl-4'>
<Main>{children}</Main>
</div>
</div>
);
}
@@ -1,5 +1,5 @@
import { Layers, LogOut, UserCog } from 'lucide-react';
import { Avatar, Icon, PanelLink, SpinnerOverlay, Tooltip } from '@/sdk';
import { Layers, LogOut, Moon, Sun, UserCog } from 'lucide-react';
import { Avatar, DropdownMenu, Icon, PanelLink, SpinnerOverlay, Tooltip, cn } from '@/sdk';
import { Main, Slot, View, type AppLayoutLink, type AppLayoutModel, type ViewProps } from '@/sdk/theme';
const navItemClass = [
@@ -10,6 +10,8 @@ const navItemClass = [
'data-[status=active]:shadow-navigation-active',
].join(' ');
const schemeLabels = { dark: 'Dark', light: 'Light' } as const;
function LinkIcon({ link, user }: { link: AppLayoutLink; user: AppLayoutModel['user'] }) {
if (link.id === 'account') {
return (
@@ -22,6 +24,38 @@ function LinkIcon({ link, user }: { link: AppLayoutLink; user: AppLayoutModel['u
return <Icon icon={link.id === 'admin' ? UserCog : Layers} />;
}
/** Only rendered when the theme offers more than one scheme. */
function SchemeMenu({
model,
setScheme,
}: {
model: AppLayoutModel;
setScheme: NonNullable<AppLayoutModel['setScheme']>;
}) {
return (
<DropdownMenu
triggerClassName={navItemClass}
triggerContent={
<>
<Icon icon={model.scheme === 'light' ? Sun : Moon} aria-hidden />
<span className='sr-only'>Color scheme</span>
</>
}
>
{model.schemes.map((scheme) => (
<DropdownMenu.Item
key={scheme}
className={cn(scheme === model.scheme && 'bg-muted')}
onClick={() => setScheme(scheme)}
>
{schemeLabels[scheme]}
</DropdownMenu.Item>
))}
<DropdownMenu.Item onClick={() => setScheme('system')}>System</DropdownMenu.Item>
</DropdownMenu>
);
}
function NavigationBar({ model }: { model: AppLayoutModel }) {
return (
<div className='w-full bg-background shadow-md overflow-x-auto scrollbar-none [&::-webkit-scrollbar]:hidden'>
@@ -32,7 +66,11 @@ function NavigationBar({ model }: { model: AppLayoutModel }) {
destination={{ to: '/' }}
className='block truncate text-xl sm:text-2xl font-header font-medium px-4 no-underline text-foreground hover:text-accent transition-colors duration-150'
>
{model.brand.name}
{model.brand.logoUrl ? (
<img src={model.brand.logoUrl} alt={model.brand.name} className='h-8 w-auto' />
) : (
model.brand.name
)}
</PanelLink>
</div>
<div className='flex h-full shrink-0 items-center justify-center'>
@@ -50,6 +88,7 @@ function NavigationBar({ model }: { model: AppLayoutModel }) {
</PanelLink>
</Tooltip>
))}
{model.setScheme && <SchemeMenu model={model} setScheme={model.setScheme} />}
<Tooltip placement='bottom' content='Sign Out'>
<button type='button' aria-label='Sign Out' onClick={model.signOut} className={navItemClass}>
<Icon icon={LogOut} />
@@ -0,0 +1,9 @@
import { Main, type ViewProps } from '@/sdk/theme';
export default function AuthLayout({ children }: ViewProps<'layout.auth'>) {
return (
<div className='pt-8 xl:pt-32'>
<Main>{children}</Main>
</div>
);
}
@@ -0,0 +1,47 @@
import { ExternalLink } from 'lucide-react';
import { Icon, NavigationLabel, SubNavigation, SubNavigationLayout } from '@/sdk';
import { Main, Slot, type NavItem, type ViewProps } from '@/sdk/theme';
/** An icon in the row; it is named once the navigation collapses or moves it into the menu. */
function AdminLinkLabel({ placement }: { placement: 'row' | 'menu' }) {
return (
<span className='inline-flex items-center gap-2 align-top' title='Open server administration'>
<Icon icon={ExternalLink} aria-hidden />
<span className={placement === 'row' ? 'sr-only in-data-collapsed:not-sr-only' : undefined}>
Open Admin Area
</span>
</span>
);
}
export default function ServerLayout({ model, children }: ViewProps<'layout.server'>) {
const { adminLink } = model;
const items: readonly NavItem[] = adminLink ? [...model.nav.items, adminLink] : model.nav.items;
return (
<SubNavigationLayout
navigation={
<SubNavigation
items={items}
canOverflow={(item) => item.extensionId !== undefined || item === adminLink}
renderItem={(item, state) =>
item === adminLink ? (
<AdminLinkLabel placement={state.placement} />
) : (
<NavigationLabel
label={item.label}
group={item.group}
icon={item.icon}
badge={state.badge}
/>
)
}
before={<Slot name='server.navigation.before' data={model.server} />}
after={<Slot name='server.navigation.after' data={model.server} />}
/>
}
>
<Main>{children}</Main>
</SubNavigationLayout>
);
}
+48
View File
@@ -0,0 +1,48 @@
import { useSyncExternalStore } from 'react';
import { onThemeChange, readThemeToken } from '@/lib/theme';
const URL_TOKEN = /^url\(\s*(?:"((?:[^"\\]|\\.)*)"|'((?:[^'\\]|\\.)*)'|([^\s"'()\\]*))\s*\)$/s;
const ESCAPE = /\\(?:([0-9a-fA-F]{1,6})\s?|(.))/gs;
const codePoint = (hex: string) => {
const value = Number.parseInt(hex, 16);
return String.fromCodePoint(value > 0 && value <= 0x10ffff ? value : 0xfffd);
};
/** The address in a `url(…)` token value, with CSS escapes undone; null for any other value. */
export function cssUrl(value: string): string | null {
const match = URL_TOKEN.exec(value.trim());
const raw = match?.[1] ?? match?.[2] ?? match?.[3];
return raw
? raw.replaceAll(ESCAPE, (_, hex?: string, char?: string) => (hex ? codePoint(hex) : (char ?? '')))
: null;
}
let logo: string | null | undefined;
const readLogo = () => cssUrl(readThemeToken('--brand-logo'));
function subscribeLogo(listener: () => void): () => void {
return onThemeChange(() => {
logo = readLogo();
listener();
});
}
function currentLogo(): string | null {
if (logo === undefined) {
logo = readLogo();
}
return logo;
}
/**
* The logo of the active theme: the `--brand-logo` token its image setting writes. It follows the
* admin's live preview of the theme settings.
*/
export function useBrandLogo(): string | null {
return useSyncExternalStore(subscribeLogo, currentLogo, () => null);
}
+200 -45
View File
@@ -1,16 +1,26 @@
/** @vitest-environment jsdom */
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeAll, expect, it, vi } from 'vitest';
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { createExtensionTestHost, type ExtensionTestHost } from '@/sdk/testing';
import { cssUrl } from './brand';
import { registerClassicTheme } from './classic';
import { registerViewLayer } from './registry';
import { ViewFixtureProvider, View, ViewArea } from './View';
import { getViewDefinition, registerViewLayer, type ViewModels } from './registry';
import { ViewFixtureProvider, View, ViewArea, type ViewFixtureSelection } from './View';
import type { LayoutViewName } from '@/router/viewRoutes';
import type { AppLayoutModel } from './layouts';
import './layouts';
let host: ExtensionTestHost | undefined;
beforeAll(() => {
// The sub-navigation measures its row as it resizes.
vi.stubGlobal(
'ResizeObserver',
class {
observe() {}
disconnect() {}
}
);
registerClassicTheme();
registerViewLayer('classic', 'classic', {
'app.search': ({ className }: { className?: string }) => (
@@ -25,56 +35,201 @@ afterEach(() => {
cleanup();
host?.dispose();
host = undefined;
delete (window as Window & { SiteConfiguration?: unknown }).SiteConfiguration;
});
const model = (rootAdmin: boolean, signOut = vi.fn()): AppLayoutModel => ({
brand: { name: 'Panel' },
links: [
{ id: 'dashboard', label: 'Dashboard', destination: { to: '/' }, exact: true },
...(rootAdmin ? [{ id: 'admin', label: 'Admin', destination: { to: '/panel' }, exact: false } as const] : []),
{ id: 'account', label: 'Account Settings', destination: { to: '/account' }, exact: false },
],
user: { uuid: 'user', username: 'alex', email: 'alex@example.test', rootAdmin },
signOut,
signingOut: false,
});
const contexts = {
'layout.auth': 'auth',
'layout.app': 'app',
'layout.account': 'account',
'layout.server': 'server',
'layout.admin': 'admin',
} as const satisfies Record<LayoutViewName, string>;
async function renderLayout(layout: AppLayoutModel) {
host = createExtensionTestHost({ path: '/' });
async function renderLayout(name: LayoutViewName, selection: ViewFixtureSelection | null, path = '/') {
host = createExtensionTestHost({ path });
const layout = (
<ViewArea area={contexts[name]}>
<View name={name}>
<p>Routed page</p>
</View>
</ViewArea>
);
await act(async () => {
render(
<ViewFixtureProvider models={{ 'layout.app': layout }}>
<ViewArea area='app'>
<View name='layout.app'>
<p>Routed page</p>
</View>
</ViewArea>
</ViewFixtureProvider>,
{ wrapper: host!.Wrapper }
);
render(selection ? <ViewFixtureProvider {...selection}>{layout}</ViewFixtureProvider> : layout, {
wrapper: host!.Wrapper,
});
});
return host;
}
it('renders the navigation from its model and the routed page inside main', async () => {
const signOut = vi.fn();
await renderLayout(model(true, signOut));
expect(await screen.findByRole('link', { name: 'Panel' })).toHaveAttribute('href', '/');
expect(screen.getByRole('link', { name: 'Dashboard' })).toHaveAttribute('data-status', 'active');
expect(screen.getByRole('link', { name: 'Admin' })).toHaveAttribute('href', '/panel');
expect(screen.getByRole('link', { name: 'Account Settings' })).toHaveAttribute('href', '/account');
expect(screen.getByRole('button', { name: 'Search' })).toHaveClass('px-3', 'sm:px-6');
expect(screen.getByRole('main')).toHaveTextContent('Routed page');
fireEvent.click(screen.getByRole('button', { name: 'Sign Out' }));
expect(signOut).toHaveBeenCalledOnce();
const appModel = (overrides: Partial<AppLayoutModel> = {}): AppLayoutModel => ({
...(getViewDefinition('layout.app')!.fixtures!.admin!() as AppLayoutModel),
brand: { name: 'Panel', logoUrl: null },
...overrides,
});
it('leaves the admin link out for other users', async () => {
await renderLayout(model(false));
describe('classic layouts', () => {
const fixtures = Object.keys(contexts).flatMap((name) =>
Object.keys(getViewDefinition(name)?.fixtures ?? {}).map(
(fixture) => [name as LayoutViewName, fixture] as const
)
);
expect(await screen.findByRole('link', { name: 'Dashboard' })).toBeVisible();
expect(screen.queryByRole('link', { name: 'Admin' })).not.toBeInTheDocument();
it.each(fixtures)('renders %s from its %s fixture with the page inside main', async (name, fixture) => {
await renderLayout(name, { fixtures: { [name]: fixture } });
expect(await screen.findByRole('main')).toHaveTextContent('Routed page');
});
});
describe('layout.app', () => {
it('renders the navigation from its model and the routed page inside main', async () => {
const signOut = vi.fn();
await renderLayout('layout.app', { models: { 'layout.app': appModel({ signOut }) } });
expect(await screen.findByRole('link', { name: 'Panel' })).toHaveAttribute('href', '/');
expect(screen.getByRole('link', { name: 'Dashboard' })).toHaveAttribute('data-status', 'active');
expect(screen.getByRole('link', { name: 'Admin' })).toHaveAttribute('href', '/panel');
expect(screen.getByRole('link', { name: 'Account Settings' })).toHaveAttribute('href', '/account');
expect(screen.getByRole('button', { name: 'Search' })).toHaveClass('px-3', 'sm:px-6');
expect(screen.getByRole('main')).toHaveTextContent('Routed page');
fireEvent.click(screen.getByRole('button', { name: 'Sign Out' }));
expect(signOut).toHaveBeenCalledOnce();
});
it('leaves the admin link out for other users', async () => {
await renderLayout('layout.app', { fixtures: { 'layout.app': 'user' } });
expect(await screen.findByRole('link', { name: 'Dashboard' })).toBeVisible();
expect(screen.queryByRole('link', { name: 'Admin' })).not.toBeInTheDocument();
});
it('shows the theme logo in place of the panel name', async () => {
await renderLayout('layout.app', { fixtures: { 'layout.app': 'logo' } });
expect(await screen.findByRole('img', { name: 'Pterodactyl' })).toHaveAttribute(
'src',
'/favicons/android-chrome-192x192.png'
);
});
it('offers a scheme switcher only when the theme has more than one scheme', async () => {
await renderLayout('layout.app', { fixtures: { 'layout.app': 'user' } });
expect(screen.queryByRole('button', { name: 'Color scheme' })).not.toBeInTheDocument();
cleanup();
host?.dispose();
const setScheme = vi.fn();
await renderLayout('layout.app', {
models: { 'layout.app': appModel({ schemes: ['dark', 'light'], setScheme }) },
});
fireEvent.click(screen.getByRole('button', { name: 'Color scheme' }));
fireEvent.click(await screen.findByRole('menuitem', { name: 'Light' }));
expect(setScheme).toHaveBeenCalledWith('light');
});
it('switches the scheme of the live page without a reload', async () => {
(window as Window & { SiteConfiguration?: unknown }).SiteConfiguration = {
theme: { scheme: 'dark', schemes: ['dark', 'light'] },
};
document.documentElement.className = 'dark';
await renderLayout('layout.app', null);
fireEvent.click(await screen.findByRole('button', { name: 'Color scheme' }));
fireEvent.click(await screen.findByRole('menuitem', { name: 'Light' }));
expect(document.documentElement).toHaveClass('light');
expect(document.documentElement).not.toHaveClass('dark');
expect(document.cookie).toContain('pterodactyl_scheme=light');
});
});
describe('layout.server', () => {
it('lists the model navigation and, for root admins, the admin link', async () => {
await renderLayout('layout.server', { fixtures: { 'layout.server': 'admin' } }, '/server/a1b2c3d4/files');
const navigation = screen.getByRole('link', { name: 'Console' }).parentElement!;
expect(within(navigation).getByRole('link', { name: 'Files' })).toHaveAttribute('data-status', 'active');
expect(within(navigation).getByRole('link', { name: 'Files' })).toHaveAttribute(
'href',
'/server/a1b2c3d4/files#/'
);
expect(within(navigation).getByRole('link', { name: 'Open Admin Area' })).toHaveAttribute(
'href',
'/panel/servers/1'
);
});
it('leaves out what a subuser cannot open', async () => {
await renderLayout('layout.server', { fixtures: { 'layout.server': 'subuser' } }, '/server/a1b2c3d4');
expect(screen.getAllByRole('link').map((link) => link.textContent)).toEqual(['Console', 'Files', 'Backups']);
});
});
describe('layout.admin', () => {
const settingsModel = (): ViewModels['layout.admin'] => {
const model = getViewDefinition('layout.admin')!.fixtures!.default!() as ViewModels['layout.admin'];
const settings = model.nav.items.find((item) => item.id === 'settings')!;
return {
...model,
nav: {
items: [
...model.nav.items,
{ ...settings, id: 'settings/mail', label: 'Mail', to: '/panel/settings/mail', icon: null },
],
},
};
};
it('labels the mobile disclosure with the most specific active item', async () => {
await renderLayout('layout.admin', { models: { 'layout.admin': settingsModel() } }, '/panel/settings/mail');
expect(screen.getByRole('button', { name: 'Mail' })).toHaveAttribute('aria-expanded', 'false');
});
it('toggles the disclosure and closes it after navigation', async () => {
const panel = await renderLayout(
'layout.admin',
{ fixtures: { 'layout.admin': 'default' } },
'/panel/settings'
);
const disclosure = screen.getByRole('button', { name: 'Settings' });
fireEvent.click(disclosure);
expect(disclosure).toHaveAttribute('aria-expanded', 'true');
fireEvent.click(disclosure);
expect(disclosure).toHaveAttribute('aria-expanded', 'false');
fireEvent.click(disclosure);
await act(async () => panel.navigate({ to: '/panel/users' }));
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Users' })).toHaveAttribute('aria-expanded', 'false')
);
expect(screen.getByRole('link', { name: 'Users' })).toHaveAttribute('data-status', 'active');
});
it('does not confuse items with a shared path prefix', async () => {
await renderLayout('layout.admin', { fixtures: { 'layout.admin': 'default' } }, '/panel/users-extra');
expect(screen.getByRole('button', { name: 'Administration' })).toBeInTheDocument();
});
});
it('reads the logo from a url() token, undoing CSS escapes', () => {
expect(cssUrl('url("/files/logo.png")')).toBe('/files/logo.png');
expect(cssUrl(" url('/a b.svg') ")).toBe('/a b.svg');
expect(cssUrl('url("/files/\\3c x\\22.png")')).toBe('/files/<x".png');
expect(cssUrl('url(/plain.png)')).toBe('/plain.png');
expect(cssUrl('"/not-a-url.png"')).toBeNull();
expect(cssUrl('')).toBeNull();
});
+281 -15
View File
@@ -1,15 +1,34 @@
import { useMemo } from 'react';
import { useCurrentUser } from '@/api/account/queries';
import { useLogout } from '@/api/auth/queries';
import { useCurrentServer } from '@/api/server/queries';
import type { Server } from '@/api/server/types';
import { useSiteSettings } from '@/api/settings/queries';
import { SCREEN_ROOTS } from '@/extensions/registry';
import { isInstallingStatus } from '@/lib/serverStatus';
import type { CorePanelDestination } from '@/sdk/navigation';
import { useBrandLogo } from './brand';
import { createTestServer } from './fixtures';
import { useNavigation, type NavArea, type NavigationModel, type NavItem } from './navigation';
import { defineView } from './registry';
import { useTheme, type ThemeScheme } from './theme';
/** A model with nothing in it yet: the view's default renders the existing container as is. */
export type OpaqueModel = Readonly<Record<never, never>>;
export const opaqueModel: OpaqueModel = Object.freeze({});
export const useOpaqueModel = (): OpaqueModel => opaqueModel;
export interface LayoutBrand {
/** The panel's name. */
readonly name: string;
/** The image the active theme's setting mapped to `--brand-logo` holds, if it has one. */
readonly logoUrl: string | null;
}
export interface AuthLayoutModel {
readonly brand: LayoutBrand;
}
export interface AppLayoutLink {
readonly id: 'dashboard' | 'admin' | 'account';
readonly label: string;
@@ -18,7 +37,7 @@ export interface AppLayoutLink {
readonly exact: boolean;
}
export interface AppLayoutModel {
readonly brand: { readonly name: string };
readonly brand: LayoutBrand;
/** The dashboard, the admin area for root admins, and the account. */
readonly links: readonly AppLayoutLink[];
readonly user: {
@@ -27,24 +46,76 @@ export interface AppLayoutModel {
readonly email: string;
readonly rootAdmin: boolean;
};
readonly scheme: ThemeScheme;
/** The schemes the theme offers; the first is its default. */
readonly schemes: readonly ThemeScheme[];
/** Switches the scheme without a reload; null unless the theme offers more than one. */
readonly setScheme: ((preference: ThemeScheme | 'system') => void) | null;
readonly signOut: () => void;
readonly signingOut: boolean;
}
export interface AccountLayoutModel {
readonly nav: NavigationModel;
}
/** Why a server's pages show a notice instead of their content. */
export type ServerConflict = 'installing' | 'suspended' | 'maintenance' | 'transferring' | 'restoring-backup';
/**
* The server area's frame. Its `children` already hold the server's console, which stays mounted
* while another page shows, and swap the pages for the conflict notice when `conflict` is set.
*/
export interface ServerLayoutModel {
readonly name: string;
readonly identifier: string;
/** The server's id in the admin area. */
readonly internalId: number;
readonly conflict: ServerConflict | null;
/** The server's admin page, for root admins. */
readonly adminLink: NavItem | null;
readonly nav: NavigationModel;
/** The server as the API returns it, which the navigation slots receive. */
readonly server: Server;
}
export interface AdminLayoutModel {
readonly nav: NavigationModel;
readonly user: {
readonly uuid: string;
readonly username: string;
readonly email: string;
};
}
declare module './registry' {
interface ViewModels {
'layout.auth': OpaqueModel;
'layout.auth': AuthLayoutModel;
'layout.app': AppLayoutModel;
'layout.account': OpaqueModel;
'layout.server': OpaqueModel;
'layout.admin': OpaqueModel;
'layout.account': AccountLayoutModel;
'layout.server': ServerLayoutModel;
'layout.admin': AdminLayoutModel;
'app.search': OpaqueModel;
}
}
function useAppLayoutModel(): AppLayoutModel {
function useBrand(): LayoutBrand {
const { name } = useSiteSettings();
const logoUrl = useBrandLogo();
return useMemo(() => ({ name, logoUrl }), [name, logoUrl]);
}
function useAuthLayoutModel(): AuthLayoutModel {
const brand = useBrand();
return useMemo(() => ({ brand }), [brand]);
}
function useAppLayoutModel(): AppLayoutModel {
const brand = useBrand();
const { uuid, username, email, rootAdmin } = useCurrentUser();
const { scheme, schemes, setScheme } = useTheme();
const { mutate, isPending } = useLogout();
return useMemo(() => {
@@ -57,51 +128,246 @@ function useAppLayoutModel(): AppLayoutModel {
links.push({ id: 'account', label: 'Account Settings', destination: { to: '/account' }, exact: false });
return {
brand: { name },
brand,
links,
user: { uuid, username, email, rootAdmin },
scheme,
schemes,
setScheme: schemes.length > 1 ? setScheme : null,
signOut: () => mutate({}),
signingOut: isPending,
};
}, [name, uuid, username, email, rootAdmin, mutate, isPending]);
}, [brand, uuid, username, email, rootAdmin, scheme, schemes, setScheme, mutate, isPending]);
}
function useAccountLayoutModel(): AccountLayoutModel {
const nav = useNavigation('account');
return useMemo(() => ({ nav }), [nav]);
}
export function serverConflict({ attributes }: Server): ServerConflict | null {
if (isInstallingStatus(attributes.status)) {
return 'installing';
}
if (attributes.status === 'suspended') {
return 'suspended';
}
if (attributes.is_node_under_maintenance) {
return 'maintenance';
}
if (attributes.is_transferring) {
return 'transferring';
}
return attributes.status === null ? null : 'restoring-backup';
}
const adminLink = (internalId: number, order: number): NavItem => ({
id: 'admin',
label: 'Open Admin Area',
to: '/panel/servers/$id',
params: { id: String(internalId) },
icon: 'external-link',
group: null,
order,
exact: false,
});
function useServerLayoutModel(): ServerLayoutModel {
const server = useCurrentServer();
const { rootAdmin } = useCurrentUser();
const nav = useNavigation('server');
const model = useMemo(() => {
if (!server) {
return null;
}
const { name, identifier, internal_id: internalId } = server.attributes;
return {
name,
identifier,
internalId,
conflict: serverConflict(server),
adminLink: rootAdmin ? adminLink(internalId, nav.items.length) : null,
nav,
server,
};
}, [server, rootAdmin, nav]);
if (!model) {
throw new Error('layout.server renders once its server has loaded.');
}
return model;
}
function useAdminLayoutModel(): AdminLayoutModel {
const nav = useNavigation('admin');
const { uuid, username, email } = useCurrentUser();
return useMemo(() => ({ nav, user: { uuid, username, email } }), [nav, uuid, username, email]);
}
const noop = () => {};
const appLayoutFixture = (rootAdmin: boolean): AppLayoutModel => ({
brand: { name: 'Pterodactyl' },
const brand: LayoutBrand = { name: 'Pterodactyl', logoUrl: null };
const logo: LayoutBrand = { ...brand, logoUrl: '/favicons/android-chrome-192x192.png' };
const appLayoutFixture = (rootAdmin: boolean, schemes: readonly ThemeScheme[] = ['dark']): AppLayoutModel => ({
brand,
links: [
{ id: 'dashboard', label: 'Dashboard', destination: { to: '/' }, exact: true },
...(rootAdmin ? [{ id: 'admin', label: 'Admin', destination: { to: '/panel' }, exact: false } as const] : []),
{ id: 'account', label: 'Account Settings', destination: { to: '/account' }, exact: false },
],
user: { uuid: '11111111-1111-4111-8111-111111111111', username: 'alex', email: 'alex@example.test', rootAdmin },
scheme: schemes[0] ?? 'dark',
schemes,
setScheme: schemes.length > 1 ? noop : null,
signOut: noop,
signingOut: false,
});
const SERVER_ID = 'a1b2c3d4';
/** Core items of an area as `useNavigation` lists them, from `[path, label, options]`. */
function navFixture(
area: NavArea,
entries: readonly (readonly [string, string, Partial<NavItem>?])[]
): NavigationModel {
return {
items: entries.map(([path, label, options], order) => ({
id: path || 'index',
label,
to: path ? `${SCREEN_ROOTS[area]}/${path}` : SCREEN_ROOTS[area],
params: area === 'server' ? { id: SERVER_ID } : {},
icon: null,
group: null,
order,
exact: path === '',
...options,
})),
};
}
const extensionItem = (area: NavArea, order: number): Partial<NavItem> => ({
id: 'tickets',
extensionId: 'support',
icon: 'life-buoy',
group: 'Support',
order,
to: `${SCREEN_ROOTS[area]}/tickets`,
});
const accountNav = (extension = false) =>
navFixture('account', [
['', 'Account'],
['api', 'API Credentials'],
['ssh', 'SSH Keys'],
['activity', 'Activity'],
...(extension ? [['tickets', 'Tickets', extensionItem('account', 4)] as const] : []),
]);
const serverPaths = [
['', 'Console'],
['files', 'Files', { hash: '/' }],
['databases', 'Databases'],
['schedules', 'Schedules'],
['users', 'Users'],
['backups', 'Backups'],
['network', 'Network'],
['startup', 'Startup'],
['settings', 'Settings'],
['activity', 'Activity'],
] as const;
function serverLayoutFixture(
options: { status?: Server['attributes']['status']; rootAdmin?: boolean; allowed?: readonly string[] } = {}
): ServerLayoutModel {
const server = createTestServer({ identifier: SERVER_ID, name: 'Survival', status: options.status ?? null });
const { items } = navFixture('server', serverPaths);
const nav = { items: items.filter((item) => !options.allowed || options.allowed.includes(item.id)) };
return {
name: server.attributes.name,
identifier: SERVER_ID,
internalId: server.attributes.internal_id,
conflict: serverConflict(server),
adminLink: options.rootAdmin ? adminLink(server.attributes.internal_id, nav.items.length) : null,
nav,
server,
};
}
const adminNav = (extension = false) =>
navFixture('admin', [
['', 'Overview', { icon: 'layout-dashboard' }],
['activity', 'Activity'],
['settings', 'Settings', { icon: 'settings' }],
['users', 'Users', { icon: 'users' }],
['locations', 'Locations', { icon: 'map-pin' }],
['nodes', 'Nodes', { icon: 'network' }],
['servers', 'Servers', { icon: 'server' }],
['databases', 'Database Hosts', { icon: 'database' }],
['mounts', 'Mounts', { icon: 'folder-tree' }],
['eggs', 'Eggs', { icon: 'egg' }],
['tags', 'Tags', { icon: 'tag' }],
['extensions', 'Extensions', { icon: 'blocks' }],
['themes', 'Themes', { icon: 'palette' }],
['api', 'API Keys', { icon: 'key-round' }],
...(extension ? [['tickets', 'Tickets', extensionItem('admin', 14)] as const] : []),
]);
const adminUser = { uuid: '11111111-1111-4111-8111-111111111111', username: 'alex', email: 'alex@example.test' };
export const layoutViews = [
defineView('layout.auth', { context: 'auth', use: useOpaqueModel }),
defineView('layout.auth', {
context: 'auth',
use: useAuthLayoutModel,
fixtures: { default: () => ({ brand }), logo: () => ({ brand: logo }) },
}),
defineView('layout.app', {
context: 'app',
use: useAppLayoutModel,
slots: ['nav.items.before', 'nav.items.after'],
fixtures: { user: () => appLayoutFixture(false), admin: () => appLayoutFixture(true) },
fixtures: {
user: () => appLayoutFixture(false),
admin: () => appLayoutFixture(true),
schemes: () => appLayoutFixture(false, ['dark', 'light']),
logo: () => ({ ...appLayoutFixture(false), brand: logo }),
},
}),
defineView('layout.account', {
context: 'account',
use: useOpaqueModel,
use: useAccountLayoutModel,
slots: ['account.navigation.before', 'account.navigation.after'],
fixtures: { default: () => ({ nav: accountNav() }), extension: () => ({ nav: accountNav(true) }) },
}),
defineView('layout.server', {
context: 'server',
use: useOpaqueModel,
use: useServerLayoutModel,
slots: ['server.navigation.before', 'server.navigation.after'],
fixtures: {
owner: () => serverLayoutFixture(),
subuser: () => serverLayoutFixture({ allowed: ['index', 'files', 'backups'] }),
admin: () => serverLayoutFixture({ rootAdmin: true }),
installing: () => serverLayoutFixture({ status: 'installing' }),
suspended: () => serverLayoutFixture({ status: 'suspended' }),
},
}),
defineView('layout.admin', {
context: 'admin',
use: useOpaqueModel,
use: useAdminLayoutModel,
slots: ['panel.navigation.before', 'panel.navigation.after'],
fixtures: {
default: () => ({ nav: adminNav(), user: adminUser }),
extension: () => ({ nav: adminNav(true), user: adminUser }),
},
}),
defineView('app.search', { context: 'app', use: useOpaqueModel }),
];
+11 -2
View File
@@ -7,7 +7,6 @@ export type {
ServerCardState,
ServerListItem,
ServerListModel,
ServerListPagination,
ServerPower,
} from './dashboard';
export type {
@@ -18,5 +17,15 @@ export type {
FileManagerModel,
FileManagerPermissions,
} from './files';
export type { AppLayoutLink, AppLayoutModel, OpaqueModel } from './layouts';
export type {
AccountLayoutModel,
AdminLayoutModel,
AppLayoutLink,
AppLayoutModel,
AuthLayoutModel,
LayoutBrand,
OpaqueModel,
ServerConflict,
ServerLayoutModel,
} from './layouts';
export type { OpaquePageName, PageViewName } from './pages';
+223
View File
@@ -0,0 +1,223 @@
/** @vitest-environment jsdom */
import type { ReactElement } from 'react';
import { act, cleanup, render, screen } from '@testing-library/react';
import { afterEach, beforeAll, expect, it } from 'vitest';
import {
commitExtensionRegistryBatch,
createExtensionRegistryBatch,
getExtensionScreens,
prepareExtensions,
registerScreen,
type ScreenOptions,
} from '@/extensions/registry';
import { publishAreaNav } from '@/router/nav';
import {
createExtensionTestHost,
createTestServer,
type ExtensionTestHost,
type TestServerOptions,
} from '@/sdk/testing';
import {
Navigation,
NavigationLink,
resourceNavigation,
useActiveNavItem,
useNavigation,
type NavArea,
} from './navigation';
let host: ExtensionTestHost | undefined;
beforeAll(() => {
prepareExtensions([
{
id: 'tabs',
entry: '/tabs.js',
screens: [
{
id: 'mods',
area: 'server',
path: 'mods',
nav: { label: 'Mods' },
when: { eggTags: { any: ['Minecraft'] } },
},
{
id: 'domains',
area: 'server',
path: 'domains',
nav: { label: 'Subdomains', icon: 'globe', group: 'Network' },
when: { runtime: true },
},
{ id: 'tickets', area: 'server', path: 'tickets', nav: { label: 'Tickets', badge: 'New' } },
{ id: 'logs', area: 'server', path: 'logs', nav: { label: 'Logs' }, permission: ['backup.read'] },
{ id: 'probe', area: 'admin', parent: 'admin.node', path: 'probe', nav: { label: 'Probe' } },
],
},
]);
publishAreaNav('server', [
{ segment: '', label: 'Console', exact: true },
{ segment: 'files', label: 'Files', permission: 'file.*', hash: '/' },
{ segment: 'backups', label: 'Backups', permission: 'backup.*' },
// As the route tree publishes extension screens.
...getExtensionScreens('server').map((screen) => ({
label: screen.nav!.label,
icon: screen.nav!.icon,
group: screen.nav!.group,
permission: screen.permission,
screen,
segment: screen.path,
})),
]);
});
afterEach(() => {
cleanup();
host?.dispose();
host = undefined;
});
const subuser = (options: TestServerOptions = {}) =>
createTestServer({
identifier: 'abc',
owner: false,
permissions: ['file.read'],
eggTags: ['palworld'],
...options,
});
async function renderServer(children: ReactElement, server = subuser(), path = '/server/abc') {
host = createExtensionTestHost({ server, path });
await act(async () => {
render(children, { wrapper: host!.Wrapper });
});
}
function Items({ area }: { area: NavArea }) {
const { items } = useNavigation(area);
const active = useActiveNavItem(items);
return (
<ul>
{items.map((item) => (
<li key={item.id} data-active={item === active || undefined}>
{JSON.stringify(item)}
</li>
))}
</ul>
);
}
const listed = () => screen.getAllByRole('listitem').map((entry) => JSON.parse(entry.textContent ?? '{}'));
function load(options: Record<string, ScreenOptions>) {
const batch = createExtensionRegistryBatch();
for (const id of ['mods', 'domains', 'tickets', 'logs', 'probe']) {
registerScreen('tabs', id, async () => ({ default: () => null }), batch, options[id]);
}
act(() => commitExtensionRegistryBatch('tabs', batch));
}
it('lists the server items the subuser may open and whose egg rules match', async () => {
await renderServer(<Items area='server' />);
expect(listed().map((item) => item.id)).toEqual(['index', 'files', 'domains', 'tickets']);
expect(listed()[1]).toEqual({
id: 'files',
label: 'Files',
to: '/server/$id/files',
params: { id: 'abc' },
hash: '/',
icon: null,
group: null,
order: 1,
exact: false,
});
expect(listed()[2]).toMatchObject({
id: 'domains',
extensionId: 'tabs',
icon: 'globe',
group: 'Network',
order: 4,
});
cleanup();
host?.dispose();
await renderServer(<Items area='server' />, subuser({ permissions: ['backup.read'], eggTags: ['minecraft'] }));
expect(listed().map((item) => item.id)).toEqual(['index', 'backups', 'mods', 'domains', 'tickets', 'logs']);
});
it('picks the most specific active item', async () => {
await renderServer(<Items area='server' />, subuser({ owner: true }), '/server/abc/files');
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(
<nav>
<Navigation area='server'>
{(item, state) => (
<NavigationLink item={item} data-active={state.active || undefined}>
{item.label} {state.badge}
</NavigationLink>
)}
</Navigation>
</nav>,
subuser(),
'/server/abc/files'
);
expect(screen.getByRole('link', { name: 'Console' })).toHaveAttribute('href', '/server/abc');
expect(screen.getByRole('link', { name: 'Files' })).toHaveAttribute('data-active');
expect(screen.getByRole('link', { name: 'Files' })).toHaveAttribute('data-status', 'active');
expect(screen.getByRole('link', { name: 'Tickets New' })).toBeVisible();
expect(screen.queryByRole('link', { name: 'Subdomains' })).not.toBeInTheDocument();
load({ domains: { visible: () => visible }, tickets: { badge: () => 3 } });
expect(await screen.findByRole('link', { name: 'Tickets 3' })).toBeVisible();
expect(screen.queryByRole('link', { name: 'Subdomains' })).not.toBeInTheDocument();
visible = true;
await act(async () => {
await host!.navigate({ to: '/server/$id', params: { id: 'abc' } });
});
expect(await screen.findByRole('link', { name: 'Subdomains' })).toHaveAttribute('href', '/server/abc/domains');
});
it('builds admin resource tabs from its own and the extension screens beneath it', () => {
const items = resourceNavigation('admin.node', { id: '42' }, [
{ id: 'about', label: 'About', to: '/panel/nodes/$id', exact: true },
]);
expect(items).toEqual([
{
id: 'about',
label: 'About',
to: '/panel/nodes/$id',
params: { id: '42' },
icon: null,
group: null,
order: 0,
exact: true,
},
{
id: 'probe',
label: 'Probe',
to: '/panel/nodes/$id/probe',
params: { id: '42' },
icon: null,
group: null,
order: 1,
exact: false,
extensionId: 'tabs',
},
]);
});
+212
View File
@@ -0,0 +1,212 @@
import { useCallback, useMemo, type ComponentProps, type ReactElement, type ReactNode } from 'react';
import { Link, useMatchRoute } from '@tanstack/react-router';
import { selectServerPermissions, useServerQuery } from '@/api/server/queries';
import type { Server } from '@/api/server/types';
import {
findExtensionScreen,
getExtensionScreens,
matchesScreenCondition,
resolveScreenPath,
SCREEN_ROOTS,
type ScreenArea,
type ScreenParent,
} from '@/extensions/registry';
import { ScreenBadge, ScreenGate } from '@/extensions/screenNavigation';
import { hasPermission } from '@/plugins/usePermissions';
import { getAreaNav, type AreaNavEntry } from '@/router/nav';
import { useServerRouteId } from '@/router/params';
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;
/** A lucide icon name, as `NamedIcon` takes it. */
readonly icon: string | null;
readonly group: string | null;
/** The position in the area navigation: core items in route order, then extension screens by their `order`. */
readonly order: number;
/** Active only on its own path, not below it. */
readonly exact: boolean;
/** The extension whose screen the item opens; core items have none. */
readonly extensionId?: string;
}
export interface NavigationModel {
readonly items: readonly NavItem[];
}
export interface NavItemState {
readonly active: boolean;
/** An extension screen's live badge, its manifest badge until that answers, or null. It suspends locally. */
readonly badge: ReactNode;
}
export type NavigationRenderer = (item: NavItem, state: NavItemState) => ReactNode;
/** A key that is unique within one navigation. */
export const navItemKey = (item: NavItem): string => `${item.extensionId ?? ''}:${item.id}`;
const toNavItem = (area: NavArea, entry: AreaNavEntry, order: number, params: Record<string, string>): NavItem => ({
id: entry.screen?.id ?? (entry.segment || 'index'),
label: entry.label,
to: 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,
});
/** Server items need one of their subuser permissions and, for extension screens, a matching egg. */
function isListed(entry: AreaNavEntry, server: Server | undefined): boolean {
const permissions = server ? selectServerPermissions(server) : [];
const required = entry.permission === undefined ? [] : [entry.permission].flat();
return (
(!required.length || required.some((permission) => hasPermission(permissions, permission))) &&
matchesScreenCondition(entry.screen?.when, server)
);
}
/**
* 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.
*/
export function useNavigation(area: NavArea): NavigationModel {
const id = useServerRouteId();
const serverId = area === 'server' ? (id ?? '') : '';
const server = useServerQuery(serverId).data;
return useMemo(() => {
const params: Record<string, string> = serverId ? { id: serverId } : {};
const items = getAreaNav(area)
.map((entry, order) => ({ entry, item: toNavItem(area, entry, order, params) }))
.filter(({ entry }) => area !== 'server' || isListed(entry, server))
.map(({ item }) => item);
return { items };
}, [area, serverId, server]);
}
export interface ResourceTab {
readonly id: string;
readonly label: string;
readonly to: string;
readonly exact?: boolean;
}
/** The tabs of an admin resource: its own, then the screens extensions add beneath it. */
export function resourceNavigation(
parent: ScreenParent,
params: Readonly<Record<string, string>>,
tabs: readonly ResourceTab[]
): NavItem[] {
const screens = getExtensionScreens('admin', parent).flatMap(({ id, path, nav, extensionId }) =>
nav ? [{ id, path, nav, extensionId }] : []
);
return [
...tabs.map((tab, order) => ({ ...tab, params, icon: null, group: null, order, exact: tab.exact ?? false })),
...screens.map(({ id, path, nav, extensionId }, index) => ({
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,
})),
];
}
const itemScreen = (item: NavItem) =>
item.extensionId === undefined ? undefined : findExtensionScreen(item.extensionId, item.id);
export function navItemBadge(item: NavItem): ReactNode {
const screen = itemScreen(item);
return screen ? <ScreenBadge screen={screen} badge={screen.nav?.badge} /> : null;
}
/** Whether an item is active: on its path, or below it unless it is exact. */
export function useNavItemActive(): (item: NavItem) => boolean {
const matchRoute = useMatchRoute();
return useCallback(
(item: NavItem) =>
matchRoute({
to: item.to as never,
params: item.params as never,
fuzzy: !item.exact,
includeSearch: false,
}) !== false,
[matchRoute]
);
}
/** 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];
}
function NavigationItems({ items, render }: { items: readonly NavItem[]; render: NavigationRenderer }) {
const isActive = useNavItemActive();
return items.map((item) => (
<ScreenGate key={navItemKey(item)} screen={itemScreen(item)}>
{render(item, { active: isActive(item), badge: navItemBadge(item) })}
</ScreenGate>
));
}
function AreaNavigation({ area, render }: { area: NavArea; render: NavigationRenderer }) {
return <NavigationItems items={useNavigation(area).items} render={render} />;
}
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.
*/
export function Navigation(props: NavigationProps) {
return props.items ? (
<NavigationItems items={props.items} render={props.children} />
) : (
<AreaNavigation area={props.area} render={props.children} />
);
}
export interface NavigationLinkProps extends Omit<ComponentProps<'a'>, 'href'> {
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}
/>
);
}
+1 -6
View File
@@ -1,17 +1,12 @@
import type { JSXElementConstructor } from 'react';
import { lazyRouteComponent } from '@tanstack/react-router';
import AuthLayout from '@/router/layouts/AuthLayout';
import type { ThemeViews } from './registry';
import type { OpaquePageName } from './pages';
const page = lazyRouteComponent;
/** Classic defaults that are still the existing containers and layouts, until they become real classic views. */
/** Classic defaults that are still the existing containers, until they become real classic views. */
export const opaqueViews = {
'layout.auth': AuthLayout,
'layout.account': lazyRouteComponent(() => import('@/router/layouts/AccountLayout')),
'layout.server': lazyRouteComponent(() => import('@/router/layouts/ServerNavigationLayout')),
'layout.admin': lazyRouteComponent(() => import('@/router/layouts/AdminLayout')),
'app.search': lazyRouteComponent(() => import('@/components/dashboard/search/SearchContainer')),
'page.auth.login': page(() => import('@/components/auth/LoginContainer')),
@@ -78,7 +78,7 @@ test('lists the built-in theme and every installed theme', function (): void {
expect(array_keys($themes))->toBe(['classic', 'aurora', 'nebula']);
expect($themes['classic'])->toMatchArray(['builtin' => true, 'active' => true, 'enabled' => true, 'extends' => null, 'problem' => null, 'settings_count' => 0]);
expect($themes['aurora'])->toMatchArray(['builtin' => false, 'active' => false, 'extends' => 'classic', 'schemes' => ['dark', 'light'], 'settings_count' => 6, 'problem' => null]);
expect($themes['aurora'])->toMatchArray(['builtin' => false, 'active' => false, 'extends' => 'classic', 'schemes' => ['dark'], 'settings_count' => 6, 'problem' => null]);
expect($themes['nebula'])->toMatchArray(['enabled' => false, 'problem' => 'Theme "nebula" is not enabled or failed to load.']);
});
+1 -1
View File
@@ -95,7 +95,7 @@ test('guests get the classic theme with the panel stylesheet and a zoomable view
'chain' => [],
'settings' => [],
'scheme' => 'dark',
'schemes' => ['dark', 'light'],
'schemes' => ['dark'],
'safeMode' => false,
'preview' => false,
'stylesheetFallback' => false,
@@ -106,6 +106,8 @@ test('a child theme needs its parent enabled, and the chain resolves parent firs
expect(array_map(fn ($theme): string => $theme->id, $themes->chain('child')))->toBe(['base', 'child']);
expect($themes->schemes($themes->chain('child')))->toBe(['light']);
// Without a declaration anywhere in the chain, a theme offers classic's dark scheme only.
expect($themes->schemes($themes->chain('base')))->toBe(['dark']);
expect(fn () => app(SetsExtensionEnabled::class)->setEnabled('base', false))->toThrow(InvalidExtensionException::class, 'Disable dependent extension "child" before "base".');
expect($themes->activationProblem('base'))->toBeNull();
});