diff --git a/docs/development/plugins.md b/docs/development/plugins.md index 606114fd..f30daedc 100644 --- a/docs/development/plugins.md +++ b/docs/development/plugins.md @@ -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.` 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 diff --git a/web/packages/plugin-sdk/src/core.ts b/web/packages/plugin-sdk/src/core.ts index 4d62a42b..d3ee5ed8 100644 --- a/web/packages/plugin-sdk/src/core.ts +++ b/web/packages/plugin-sdk/src/core.ts @@ -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 }), }) } diff --git a/web/packages/plugin-sdk/src/index.ts b/web/packages/plugin-sdk/src/index.ts index c1823a47..85e8a42a 100644 --- a/web/packages/plugin-sdk/src/index.ts +++ b/web/packages/plugin-sdk/src/index.ts @@ -17,6 +17,8 @@ export type { VisibilityExtensionRegistration, PresentationExtensionRegistration, ActionExtensionRegistration, + UserMenuTarget, + UserMenuItemDefinition, PluginDefinition, PluginInstance, RiseHostSDK, diff --git a/web/packages/plugin-sdk/src/types.ts b/web/packages/plugin-sdk/src/types.ts index df4630f6..b85ef91c 100644 --- a/web/packages/plugin-sdk/src/types.ts +++ b/web/packages/plugin-sdk/src/types.ts @@ -241,6 +241,21 @@ export interface ActionExtensionRegistration { evaluate: (context: { resourceType: string; resourceKey: string; resource: unknown; data: Record; 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. 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. */ @@ -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. diff --git a/web/packages/plugin-sdk/test/core.test.ts b/web/packages/plugin-sdk/test/core.test.ts index 12b45dd4..b17965af 100644 --- a/web/packages/plugin-sdk/test/core.test.ts +++ b/web/packages/plugin-sdk/test/core.test.ts @@ -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 = [ + { 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() diff --git a/web/packages/ui/src/components/ui/dropdown-menu.tsx b/web/packages/ui/src/components/ui/dropdown-menu.tsx index 7739339e..a324fa03 100644 --- a/web/packages/ui/src/components/ui/dropdown-menu.tsx +++ b/web/packages/ui/src/components/ui/dropdown-menu.tsx @@ -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, @@ -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 ( + ) @@ -266,6 +276,7 @@ export { DropdownMenuGroup, DropdownMenuLabel, DropdownMenuItem, + DropdownMenuLinkItem, DropdownMenuCheckboxItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, diff --git a/web/packages/ui/src/index.ts b/web/packages/ui/src/index.ts index 5dd64c27..d62627e7 100644 --- a/web/packages/ui/src/index.ts +++ b/web/packages/ui/src/index.ts @@ -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" diff --git a/web/src/shell/Layout.test.tsx b/web/src/shell/Layout.test.tsx new file mode 100644 index 00000000..06cd2557 --- /dev/null +++ b/web/src/shell/Layout.test.tsx @@ -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(), + useLayout: () => state.layout, +})); +vi.mock("@modelsphere/ui", async (importOriginal) => ({ + ...await importOriginal(), + DropdownMenuContent: ({ children }: { children: ReactNode }) =>
{children}
, +})); + +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( + + +
+ + , + ); +} + +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(/]*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); + }); +}); diff --git a/web/src/shell/Layout.tsx b/web/src/shell/Layout.tsx index b172c3ee..d059cd22 100644 --- a/web/src/shell/Layout.tsx +++ b/web/src/shell/Layout.tsx @@ -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, @@ -8,6 +8,7 @@ import { DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, + DropdownMenuLinkItem, DropdownMenuSeparator, DropdownMenuTrigger, DropdownMenuGroup, @@ -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"; @@ -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 =
{children}
; @@ -58,13 +60,13 @@ export function Layout({ modules, children }: { modules: ConsoleModule[]; childr
- setPrefsOpen(true)} /> + setPrefsOpen(true)} /> {page}
) : (
- setPrefsOpen(true)} /> + setPrefsOpen(true)} />