Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions docs/development/plugins.md
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,34 @@ Authenticated `/clusters/{value}/oapis/` aliases do not select another cluster.
not authorization aggregation. See the [single-cluster design](single-cluster-applications-design.md)
for the unchanged original Dashboard Charts and browser verification.

### Account menu links

Set `userMenu` on `createPlugin()` to add links to the account dropdown. Use
an entry name from your plugin or an application ID from a registered
navigation composition.

```ts
userMenu: [
{ id: "overview", title: "My Plugin", target: { kind: "entry", name: "my-plugin" } },
{ id: "settings", title: "Settings", target: { kind: "application", id: "my-settings/platform" } },
],
```

- Each `id` is unique within the plugin and uses kebab-case. Translate the
label at `userMenu.<id>` in the plugin's namespace. The declared `title`
serves as the fallback.
- Set `order` to place the link among other plugin links. It defaults to
`999`, with ties sorted by plugin ID and link ID.
- An entry target resolves to a static page owned by this plugin. Console
checks the same visibility and permission rules it uses for navigation.
- An application target opens its default page if the user can access it
and the first accessible landing page otherwise. Console hides the link
if the application has no accessible landing page.

Console resolves these links from the currently available plugins and pages.
Page guards and backend authorization still apply. An older Console with the
same SDK major version ignores account menu declarations.

### Routes

Menu paths and route keys are normalized before matching; a matching route
Expand Down
1 change: 1 addition & 0 deletions web/packages/plugin-sdk/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -427,6 +427,7 @@ function registerDefinition(sdk: RiseHostSDK, def: PluginDefinition): void {
scope: '', // plugin-level scope left empty for child plugins
scopes: def.scopes || undefined,
menus: bridgedMenus,
...(def.userMenu === undefined ? {} : { userMenu: def.userMenu }),
})

}
Expand Down
2 changes: 2 additions & 0 deletions web/packages/plugin-sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export type {
VisibilityExtensionRegistration,
PresentationExtensionRegistration,
ActionExtensionRegistration,
UserMenuTarget,
UserMenuItemDefinition,
PluginDefinition,
PluginInstance,
RiseHostSDK,
Expand Down
18 changes: 18 additions & 0 deletions web/packages/plugin-sdk/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,21 @@ export interface ActionExtensionRegistration {
evaluate: (context: { resourceType: string; resourceKey: string; resource: unknown; data: Record<string, unknown>; action: string }) => false | string
}

export type UserMenuTarget =
| { kind: 'entry'; name: string }
| { kind: 'application'; id: string }

export interface UserMenuItemDefinition {
/** Unique kebab-case identifier within this plugin. */
id: string
/** Fallback label for the plugin's userMenu.<id> translation. */
title: string
/** Sort order, defaulting to 999. */
order?: number
/** Own static entry or the stable ID of an application. */
target: UserMenuTarget
}

// ── Scope Declaration (Dock metadata) ────────────────────────

/** Declares a Dock entry for a specific scope. */
Expand Down Expand Up @@ -284,6 +299,9 @@ export interface PluginDefinition {
/** Menu items to register */
menus?: PluginMenu[]

/** Links contributed to the Console account menu. */
userMenu?: UserMenuItemDefinition[]

/**
* React components to register. Keys are component names,
* values are React component functions/classes.
Expand Down
13 changes: 13 additions & 0 deletions web/packages/plugin-sdk/test/core.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -357,6 +357,19 @@ describe('typed events', () => {
})

describe('registration contract validation', () => {
it('forwards account menu links with the plugin definition', async () => {
const { registerPlugin } = installHost()
const createPlugin = await loadCreatePlugin()
const userMenu: NonNullable<PluginDefinition['userMenu']> = [
{ id: 'reports', title: 'Reports', order: 50, target: { kind: 'entry', name: 'reports' } },
{ id: 'settings', title: 'Settings', target: { kind: 'application', id: 'example/platform' } },
]

createPlugin({ ...baseDefinition, userMenu })

expect(registerPlugin).toHaveBeenCalledWith(expect.objectContaining({ userMenu }))
})

it('preserves scope visibility restrictions and recursive menus across the host bridge', async () => {
const { registerPlugin } = installHost()
const createPlugin = await loadCreatePlugin()
Expand Down
19 changes: 15 additions & 4 deletions web/packages/ui/src/components/ui/dropdown-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,8 @@ function DropdownMenuLabel({
)
}

const dropdownMenuItemClassName = "group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive"

function DropdownMenuItem({
className,
inset,
Expand All @@ -96,10 +98,18 @@ function DropdownMenuItem({
data-slot="dropdown-menu-item"
data-inset={inset}
data-variant={variant}
className={cn(
"group/dropdown-menu-item relative flex cursor-default items-center gap-1.5 rounded-md px-1.5 py-1 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground not-data-[variant=destructive]:focus:**:text-accent-foreground data-inset:pl-7 data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 data-[variant=destructive]:focus:text-destructive dark:data-[variant=destructive]:focus:bg-destructive/20 data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 data-[variant=destructive]:*:[svg]:text-destructive",
className
)}
className={cn(dropdownMenuItemClassName, className)}
{...props}
/>
)
}

function DropdownMenuLinkItem({ className, ...props }: MenuPrimitive.LinkItem.Props) {
return (
<MenuPrimitive.LinkItem
data-slot="dropdown-menu-item"
data-variant="default"
className={cn(dropdownMenuItemClassName, className)}
{...props}
/>
)
Expand Down Expand Up @@ -266,6 +276,7 @@ export {
DropdownMenuGroup,
DropdownMenuLabel,
DropdownMenuItem,
DropdownMenuLinkItem,
DropdownMenuCheckboxItem,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
Expand Down
2 changes: 1 addition & 1 deletion web/packages/ui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ export { Button, buttonVariants } from "./components/ui/button"
export { Card, CardAction, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from "./components/ui/card"
export { Checkbox } from "./components/ui/checkbox"
export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger } from "./components/ui/dialog"
export { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "./components/ui/dropdown-menu"
export { DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuLinkItem, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "./components/ui/dropdown-menu"
export { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyMedia, EmptyTitle } from "./components/ui/empty"
export { EmptyState } from "./components/empty-state"
export type { EmptyStateProps, EmptySituation, EmptyStateSize, EmptyUnavailable, EmptyForbidden } from "./components/empty-state"
Expand Down
93 changes: 93 additions & 0 deletions web/src/shell/Layout.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { Boxes } from "lucide-react";
import type { ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Layout } from "./Layout";
import { getLocale, i18n, registerI18n, setLocale } from "./i18n";
import type { ConsoleModule } from "./module";
import { PermissionsProvider } from "./permissions";

const state = vi.hoisted(() => ({
authDisabled: false,
layout: "minimal",
permissions: ["reports.read"],
}));

vi.mock("@/shell/auth", () => ({
useAuth: () => ({
me: { name: "tester", isAdmin: state.authDisabled, authDisabled: state.authDisabled, permissions: state.permissions },
logout: vi.fn(),
}),
}));
vi.mock("@/shell/preferences", async (importOriginal) => ({
...await importOriginal<typeof import("./preferences")>(),
useLayout: () => state.layout,
}));
vi.mock("@modelsphere/ui", async (importOriginal) => ({
...await importOriginal<typeof import("@modelsphere/ui")>(),
DropdownMenuContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,
}));

const module: ConsoleModule = {
id: "reports",
title: "Reports",
basePath: "/reports",
pages: [{ path: "", element: null, permission: "reports.read", menu: { key: "index", label: "Reports", icon: Boxes } }],
userMenu: [{ id: "reports-home", title: "Open reports", target: { kind: "entry", name: "index" } }],
};

const locale = getLocale();
afterEach(() => {
state.authDisabled = false;
state.layout = "minimal";
state.permissions = ["reports.read"];
setLocale(locale);
i18n.removeResourceBundle("en-US", module.id);
i18n.removeResourceBundle("zh-CN", module.id);
});

function render() {
return renderToStaticMarkup(
<MemoryRouter>
<PermissionsProvider>
<Layout modules={[module]}><div /></Layout>
</PermissionsProvider>
</MemoryRouter>,
);
}

describe("plug-in account menu links", () => {
it.each(["minimal", "classic", "mixed-nav"])("renders the resolved link before the account actions in %s", layout => {
state.layout = layout;
setLocale("en-US");
const html = render();
expect(html).toMatch(/<a\b(?=[^>]*href="\/reports")(?=[^>]*role="menuitem")[^>]*>Open reports<\/a>/);
expect(html.indexOf("Open reports")).toBeLessThan(html.indexOf("Change password"));
expect(html).toContain("Sign out");
});

it("renders the contribution's translation and keeps links in no-login mode", () => {
registerI18n(module.id, {
"zh-CN": { userMenu: { "reports-home": "打开报告" } },
"en-US": { userMenu: { "reports-home": "View reports" } },
});
state.authDisabled = true;
setLocale("zh-CN");
expect(render()).toContain("打开报告");

setLocale("en-US");
const html = render();
expect(html).toContain("View reports");
expect(html.indexOf("Sign-in off")).toBeLessThan(html.indexOf("View reports"));
expect(html).not.toContain("Change password");
expect(html).not.toContain("Sign out");
});

it("omits the link and the extra separator when the target is unauthorized", () => {
state.permissions = [];
const html = render();
expect(html).not.toContain("Open reports");
expect(html.match(/data-slot="dropdown-menu-separator"/g)).toHaveLength(2);
});
});
24 changes: 20 additions & 4 deletions web/src/shell/Layout.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Fragment, useState, type ReactNode } from "react";
import { NavLink, useLocation } from "react-router";
import { Link, NavLink, useLocation } from "react-router";
import {
Avatar,
AvatarFallback,
Expand All @@ -8,6 +8,7 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuLinkItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
DropdownMenuGroup,
Expand All @@ -18,7 +19,7 @@ import { usePermissions } from "@/shell/permissions";
import { ChangePasswordDialog } from "@/shell/ChangePasswordDialog";
import { PreferencesPanel } from "@/shell/PreferencesPanel";
import { useLayout } from "@/shell/preferences";
import { userMenuIdentity, userMenuState } from "@/shell/user-menu";
import { resolveUserMenuItems, userMenuIdentity, userMenuState, type UserMenuLink } from "@/shell/user-menu";
import { topbarItems, type ConsoleModule, type NavItem } from "@/shell/module";
import { Sidebar } from "./Sidebar";
import { ApplicationLauncher } from "./ApplicationLauncher";
Expand Down Expand Up @@ -46,6 +47,7 @@ export function Layout({ modules, children }: { modules: ConsoleModule[]; childr
const [prefsOpen, setPrefsOpen] = useState(false);
const { groups, applications, activeID } = applicationNavigation(modules, has, pathname);
const links = topbarItems(modules, has);
const userMenuLinks = resolveUserMenuItems(modules, applications, has);
const toggle = () => setCollapsed((c) => !c);
const page = <main className="relative min-h-0 min-w-0 flex-1 overflow-auto bg-surface-page">{children}</main>;

Expand All @@ -58,13 +60,13 @@ export function Layout({ modules, children }: { modules: ConsoleModule[]; childr
</nav>
</aside>
<div className="m-2 ml-0 flex min-w-0 flex-1 flex-col overflow-hidden rounded-xl bg-card shadow-[0_1px_3px_0_rgb(0_0_0/0.1),0_1px_2px_-1px_rgb(0_0_0/0.1)]">
<TopBar tone="light" links={links} applications={applications} collapse={{ collapsed, toggle }} onPreferences={() => setPrefsOpen(true)} />
<TopBar tone="light" links={links} applications={applications} userMenuLinks={userMenuLinks} collapse={{ collapsed, toggle }} onPreferences={() => setPrefsOpen(true)} />
{page}
</div>
</div>
) : (
<div className={`flex h-screen flex-col ${layout === "classic" ? "bg-[var(--shell-classic-canvas)]" : "bg-background"}`}>
<TopBar tone="dark" links={links} applications={applications} onPreferences={() => setPrefsOpen(true)} />
<TopBar tone="dark" links={links} applications={applications} userMenuLinks={userMenuLinks} onPreferences={() => setPrefsOpen(true)} />
<div className="flex min-h-0 flex-1">
<aside
className={`flex shrink-0 flex-col bg-[var(--shell-sidebar)] transition-[width] duration-300 ${collapsed ? "w-16" : "w-64"} ${
Expand Down Expand Up @@ -131,12 +133,14 @@ function TopBar({
tone,
links,
applications,
userMenuLinks,
collapse,
onPreferences,
}: {
tone: "light" | "dark";
links: NavItem[];
applications: ApplicationItem[];
userMenuLinks: UserMenuLink[];
collapse?: { collapsed: boolean; toggle: () => void };
onPreferences: () => void;
}) {
Expand Down Expand Up @@ -225,6 +229,18 @@ function TopBar({
</Badge>
</>
)}
{userMenuLinks.length > 0 && (
<>
<DropdownMenuSeparator />
<DropdownMenuGroup>
{userMenuLinks.map(({ key, id, namespace, title, to }) => (
<DropdownMenuLinkItem key={key} render={<Link to={to} />} closeOnClick>
{tr(`${namespace}:userMenu.${id}`, { defaultValue: title })}
</DropdownMenuLinkItem>
))}
</DropdownMenuGroup>
</>
)}
{menu.entries.map((entry) => {
const Icon = entry === "changePassword" ? KeyRound : LogOut;
return (
Expand Down
Loading
Loading