Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
+79
@@ -0,0 +1,79 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { UI_ACTION_IDS, UI_SURFACE_IDS, getSidebarSurfaceId, type UiLayout } from "~/application/ui/uiRegistry";
|
||||
import ShadcnSidebarLayout from "./ShadcnSidebarLayout";
|
||||
|
||||
vi.mock("~/hooks/use-mobile", () => ({
|
||||
useIsMobile: () => false,
|
||||
}));
|
||||
|
||||
vi.mock("~/components/ui/commandPalettes/CommandPalette", () => ({
|
||||
useCommandPalette: () => ({ toggle: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("~/modules/onboarding/components/OnboardingSession", () => ({
|
||||
default: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useTitleData", () => ({
|
||||
useTitleData: () => "Dashboard",
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({
|
||||
useAppOrAdminData: () => ({ currentTenant: null }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ userSession: { lightOrDarkMode: "light" } }),
|
||||
}));
|
||||
|
||||
vi.mock("~/stores/themePreviewStore", () => ({
|
||||
useThemePreviewStore: () => ({ isPreviewActive: false, previewConfig: null }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/theme/ThemeConfig", () => ({
|
||||
parseThemeConfig: () => ({}),
|
||||
}));
|
||||
|
||||
vi.mock("./app-sidebar", () => ({
|
||||
ShadcnAppSidebar: ({ layout }: { layout: string }) => <aside data-ui-id={`ui.surface.${layout}.sidebar`} />,
|
||||
}));
|
||||
|
||||
vi.mock("./nav-actions", () => ({
|
||||
NavActions: () => <button data-ui-id="ui.action.shell.search">Search</button>,
|
||||
}));
|
||||
|
||||
describe("ShadcnSidebarLayout UI IDs", () => {
|
||||
function renderLayout(layout: UiLayout) {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<ShadcnSidebarLayout layout={layout}>
|
||||
<section>Page content</section>
|
||||
</ShadcnSidebarLayout>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
function expectNoDuplicateDataUiIds() {
|
||||
const ids = [...document.querySelectorAll("[data-ui-id]")].map((element) => element.getAttribute("data-ui-id"));
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
}
|
||||
|
||||
it.each<UiLayout>(["app", "admin", "docs"])("renders stable %s shell surface and action IDs", (layout) => {
|
||||
renderLayout(layout);
|
||||
|
||||
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shell}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellInset}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${getSidebarSurfaceId(layout)}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellHeader}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellBreadcrumb}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellBreadcrumbCurrent}"]`)).toHaveTextContent("Dashboard");
|
||||
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellNavActions}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.sidebarTrigger}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.search}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellMain}"]`)).toContainElement(screen.getByText("Page content"));
|
||||
expectNoDuplicateDataUiIds();
|
||||
});
|
||||
});
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
import { SidebarInset, SidebarProvider, SidebarTrigger } from "../../../ui/sidebar";
|
||||
import { ShadcnAppSidebar } from "./app-sidebar";
|
||||
import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage } from "~/components/ui/breadcrumb";
|
||||
import { SideBarItem } from "~/application/sidebar/SidebarItem";
|
||||
import { useLocation, useParams, useSearchParams } from "react-router";
|
||||
import { useTitleData } from "~/utils/data/useTitleData";
|
||||
import { lazy, Suspense, useRef, useState } from "react";
|
||||
import { NavActions } from "./nav-actions";
|
||||
import { useCommandPalette } from "~/components/ui/commandPalettes/CommandPalette";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import { useThemePreviewStore } from "~/stores/themePreviewStore";
|
||||
import { parseThemeConfig } from "~/utils/theme/ThemeConfig";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { UI_ACTION_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
|
||||
|
||||
const OnboardingSession = lazy(() => import("~/modules/onboarding/components/OnboardingSession"));
|
||||
|
||||
export default function ShadcnSidebarLayout({
|
||||
children,
|
||||
layout,
|
||||
menuItems,
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
layout: "app" | "admin" | "docs";
|
||||
menuItems?: SideBarItem[];
|
||||
}) {
|
||||
const params = useParams();
|
||||
const title = useTitleData() ?? "";
|
||||
const location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const mainElement = useRef<HTMLElement>(null);
|
||||
|
||||
// Get the app data which includes tenant theme config
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const { userSession } = useRootData();
|
||||
const { isPreviewActive, previewConfig } = useThemePreviewStore();
|
||||
|
||||
const commandPalette = useCommandPalette();
|
||||
|
||||
const [onboardingModalOpen, setOnboardingModalOpen] = useState(false);
|
||||
|
||||
function onOpenCommandPalette() {
|
||||
commandPalette.toggle();
|
||||
}
|
||||
|
||||
const view = searchParams.get("view");
|
||||
const hasCalendar = ["month", "week", "day", "agenda"].includes(view ?? "");
|
||||
void location;
|
||||
void hasCalendar;
|
||||
|
||||
let themeConfig = isPreviewActive && previewConfig ? previewConfig : parseThemeConfig(appOrAdminData?.currentTenant?.themeConfig as string | null);
|
||||
|
||||
let sidebarStyle: Record<string, string> = {};
|
||||
|
||||
if (themeConfig?.colors) {
|
||||
let colors = themeConfig.colors;
|
||||
if (userSession?.lightOrDarkMode === "dark" && themeConfig?.darkColors) {
|
||||
colors = themeConfig.darkColors;
|
||||
}
|
||||
if (colors.sidebar) {
|
||||
// Sidebar specific colors
|
||||
sidebarStyle["--sidebar"] = colors.sidebar;
|
||||
}
|
||||
if (colors.sidebarForeground) {
|
||||
sidebarStyle["--sidebar-foreground"] = colors.sidebarForeground;
|
||||
}
|
||||
if (colors.sidebarPrimary) {
|
||||
sidebarStyle["--sidebar-primary"] = colors.sidebarPrimary;
|
||||
}
|
||||
if (colors.sidebarPrimaryForeground) {
|
||||
sidebarStyle["--sidebar-primary-foreground"] = colors.sidebarPrimaryForeground;
|
||||
}
|
||||
if (colors.sidebarAccent) {
|
||||
sidebarStyle["--sidebar-accent"] = colors.sidebarAccent;
|
||||
}
|
||||
if (colors.sidebarAccentForeground) {
|
||||
sidebarStyle["--sidebar-accent-foreground"] = colors.sidebarAccentForeground;
|
||||
}
|
||||
if (colors.sidebarBorder) {
|
||||
sidebarStyle["--sidebar-border"] = colors.sidebarBorder;
|
||||
}
|
||||
if (colors.sidebarRing) {
|
||||
sidebarStyle["--sidebar-ring"] = colors.sidebarRing;
|
||||
}
|
||||
}
|
||||
|
||||
if (!appOrAdminData.currentTenant) {
|
||||
sidebarStyle = {};
|
||||
themeConfig = {};
|
||||
}
|
||||
|
||||
return (
|
||||
<SidebarProvider style={sidebarStyle as React.CSSProperties} data-ui-id={UI_SURFACE_IDS.shell}>
|
||||
{appOrAdminData?.onboardingSession ? (
|
||||
<Suspense fallback={null}>
|
||||
<OnboardingSession open={onboardingModalOpen} setOpen={setOnboardingModalOpen} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
<ShadcnAppSidebar layout={layout} items={menuItems} themeConfig={themeConfig} style={sidebarStyle as React.CSSProperties} />
|
||||
<SidebarInset className="overflow-hidden" data-ui-id={UI_SURFACE_IDS.shellInset}>
|
||||
<header
|
||||
className="border-border bg-background flex h-16 shrink-0 items-center gap-2 border-b transition-[width,height] ease-linear group-has-data-[collapsible=icon]/sidebar-wrapper:h-12"
|
||||
data-ui-id={UI_SURFACE_IDS.shellHeader}
|
||||
>
|
||||
<div className="flex items-center gap-2 truncate px-4" data-ui-id={UI_SURFACE_IDS.shellBreadcrumb}>
|
||||
<SidebarTrigger className="-ml-1" data-ui-id={UI_ACTION_IDS.sidebarTrigger} />
|
||||
{title && <Separator orientation="vertical" className="mr-2 h-4" />}
|
||||
{title && (
|
||||
<Breadcrumb className="truncate">
|
||||
<BreadcrumbList className="truncate">
|
||||
<BreadcrumbItem className="block truncate">
|
||||
<BreadcrumbPage className="truncate" data-ui-id={UI_SURFACE_IDS.shellBreadcrumbCurrent}>
|
||||
{title}
|
||||
</BreadcrumbPage>
|
||||
</BreadcrumbItem>
|
||||
</BreadcrumbList>
|
||||
</Breadcrumb>
|
||||
)}
|
||||
</div>
|
||||
<div className="ml-auto px-3" data-ui-id={UI_SURFACE_IDS.shellNavActions}>
|
||||
<NavActions layout={layout} onOpenCommandPalette={onOpenCommandPalette} setOnboardingModalOpen={setOnboardingModalOpen} />
|
||||
</div>
|
||||
</header>
|
||||
<main id="main-content" ref={mainElement} className="flex-1 focus:outline-hidden" tabIndex={-1} data-ui-id={UI_SURFACE_IDS.shellMain}>
|
||||
<div key={params.tenant} className="pb-20 sm:pb-0">
|
||||
{children}
|
||||
</div>
|
||||
</main>
|
||||
</SidebarInset>
|
||||
{/* {showCalendar && <SidebarRight />} */}
|
||||
</SidebarProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import React from "react";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { SideBarItem } from "~/application/sidebar/SidebarItem";
|
||||
import { UI_NAV_IDS, UI_SURFACE_IDS, getSidebarSurfaceId, type UiLayout } from "~/application/ui/uiRegistry";
|
||||
import { SidebarProvider } from "~/components/ui/sidebar";
|
||||
import { ShadcnAppSidebar } from "./app-sidebar";
|
||||
|
||||
vi.mock("~/hooks/use-mobile", () => ({
|
||||
useIsMobile: () => false,
|
||||
}));
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (value: string) => value }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({ appConfiguration: null }),
|
||||
}));
|
||||
|
||||
let mockedPermissions = ["app.dashboard.view"];
|
||||
let mockedCurrentTenant: null | { slug: string; logo: string } = null;
|
||||
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({
|
||||
useAppOrAdminData: () => ({
|
||||
currentTenant: mockedCurrentTenant,
|
||||
entities: [],
|
||||
entityGroups: [],
|
||||
myTenants: [],
|
||||
permissions: mockedPermissions,
|
||||
user: { id: "user_1", email: "user@example.com", firstName: "User", lastName: "Example" },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("./nav-user", () => ({
|
||||
NavUser: ({ layout }: { layout: string }) => <div data-testid="nav-user">User {layout}</div>,
|
||||
}));
|
||||
|
||||
const baseItems = [
|
||||
{
|
||||
id: "ui.nav.test.main",
|
||||
title: "Main",
|
||||
path: "",
|
||||
items: [{ id: UI_NAV_IDS.appDashboard, title: "Dashboard", path: "/acme/dashboard" }],
|
||||
},
|
||||
{
|
||||
id: "ui.nav.test.quick",
|
||||
title: "Quick",
|
||||
path: "",
|
||||
isQuickLink: true,
|
||||
items: [{ id: "ui.nav.test.quick.reports", title: "Reports", path: "/reports" }],
|
||||
},
|
||||
{
|
||||
id: "ui.nav.test.secondary",
|
||||
title: "Secondary",
|
||||
path: "",
|
||||
isSecondary: true,
|
||||
items: [{ id: UI_NAV_IDS.appSettings, title: "Settings", path: "/acme/settings" }],
|
||||
},
|
||||
];
|
||||
|
||||
function renderSidebar(layout: UiLayout = "app", initialPath = "/") {
|
||||
return render(
|
||||
<MemoryRouter initialEntries={[initialPath]}>
|
||||
<SidebarProvider>
|
||||
<ShadcnAppSidebar layout={layout} items={baseItems} />
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
function expectNoDuplicateDataUiIds() {
|
||||
const ids = [...document.querySelectorAll("[data-ui-id]")].map((element) => element.getAttribute("data-ui-id"));
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
}
|
||||
|
||||
describe("ShadcnAppSidebar UI IDs", () => {
|
||||
afterEach(() => {
|
||||
mockedPermissions = ["app.dashboard.view"];
|
||||
mockedCurrentTenant = null;
|
||||
});
|
||||
|
||||
it.each<UiLayout>(["app", "admin", "docs"])("renders %s sidebar structure with stable data-ui-id attributes", (layout) => {
|
||||
renderSidebar(layout);
|
||||
|
||||
const surfaceId = getSidebarSurfaceId(layout);
|
||||
expect(document.querySelector(`[data-ui-id="${surfaceId}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${surfaceId}.header"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${surfaceId}.content"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${surfaceId}.footer"]`)).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Dashboard" })).toHaveAttribute("data-ui-id", UI_NAV_IDS.appDashboard);
|
||||
expect(screen.getByRole("link", { name: "Settings" })).toHaveAttribute("data-ui-id", UI_NAV_IDS.appSettings);
|
||||
expect(screen.getByRole("link", { name: "Reports" })).toHaveAttribute("data-ui-id", "ui.nav.test.quick.reports");
|
||||
expect(screen.queryByText("View Project")).not.toBeInTheDocument();
|
||||
expectNoDuplicateDataUiIds();
|
||||
});
|
||||
|
||||
it("marks only exact host-aware sibling routes as active without mutating source items", () => {
|
||||
const nestedItems: SideBarItem[] = [
|
||||
{
|
||||
id: "ui.nav.test.main",
|
||||
title: "Main",
|
||||
path: "",
|
||||
items: [
|
||||
{ id: "ui.nav.test.accounts", title: "Accounts", path: "/acme/accounts", exact: true },
|
||||
{ id: "ui.nav.test.accounting", title: "Accounting", path: "/acme/accounting" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/acme/accounts"]}>
|
||||
<SidebarProvider>
|
||||
<ShadcnAppSidebar layout="app" items={nestedItems} />
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Accounts" })).toHaveAttribute("data-active", "true");
|
||||
expect(screen.getByRole("link", { name: "Accounting" })).toHaveAttribute("data-active", "false");
|
||||
expect(nestedItems[0]?.items?.[0]?.isActive).toBeUndefined();
|
||||
});
|
||||
|
||||
it("uses redirect targets for links but base paths for active matching", () => {
|
||||
const secondaryItems: SideBarItem[] = [
|
||||
{
|
||||
id: "ui.nav.test.secondary",
|
||||
title: "Secondary",
|
||||
path: "",
|
||||
isSecondary: true,
|
||||
items: [
|
||||
{
|
||||
id: UI_NAV_IDS.appSettings,
|
||||
title: "Settings",
|
||||
path: "/acme/settings",
|
||||
redirectTo: "/acme/settings/profile",
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/acme/settings/members"]}>
|
||||
<SidebarProvider>
|
||||
<ShadcnAppSidebar layout="app" items={secondaryItems} />
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Settings" })).toHaveAttribute("href", "/acme/settings/profile");
|
||||
expect(screen.getByRole("link", { name: "Settings" })).toHaveAttribute("data-active", "true");
|
||||
});
|
||||
|
||||
it("does not render tenant logo links inside the admin sidebar", () => {
|
||||
mockedCurrentTenant = { slug: "acme", logo: "/tenant-logo.svg" };
|
||||
|
||||
renderSidebar("admin", "/dashboard");
|
||||
|
||||
expect(screen.queryByAltText("Logo")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Logo" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("filters sidebar items by declared permission", () => {
|
||||
const permissionItems: SideBarItem[] = [
|
||||
{
|
||||
id: "ui.nav.test.main",
|
||||
title: "Main",
|
||||
path: "",
|
||||
items: [
|
||||
{ id: "ui.nav.test.allowed", title: "Allowed", path: "/acme/allowed", permission: "app.dashboard.view" },
|
||||
{ id: "ui.nav.test.denied", title: "Denied", path: "/acme/denied", permission: "app.settings.account.update" },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/acme/dashboard"]}>
|
||||
<SidebarProvider>
|
||||
<ShadcnAppSidebar layout="app" items={permissionItems} />
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Allowed" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Denied" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hides disabled quick links", () => {
|
||||
const quickLinkItems: SideBarItem[] = [
|
||||
{
|
||||
id: "ui.nav.test.quick",
|
||||
title: "Quick",
|
||||
path: "",
|
||||
isQuickLink: true,
|
||||
items: [
|
||||
{ id: "ui.nav.test.quick.allowed", title: "Reports", path: "/reports" },
|
||||
{ id: "ui.nav.test.quick.disabled", title: "Disabled Report", path: "/disabled-report", disabled: true },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/acme/dashboard"]}>
|
||||
<SidebarProvider>
|
||||
<ShadcnAppSidebar layout="app" items={quickLinkItems} />
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Reports" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Disabled Report" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders permitted expandable parents as flat section headers", () => {
|
||||
mockedPermissions = ["admin.accounts.view", "admin.users.view"];
|
||||
const permissionItems: SideBarItem[] = [
|
||||
{
|
||||
id: "ui.nav.test.main",
|
||||
title: "Main",
|
||||
path: "",
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.test.accounts",
|
||||
title: "Accounts",
|
||||
path: "/accounts",
|
||||
permission: "admin.accounts.view",
|
||||
items: [{ id: "ui.nav.test.accounts.users", title: "Users", path: "/accounts/users", permission: "admin.users.view" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/dashboard"]}>
|
||||
<SidebarProvider>
|
||||
<ShadcnAppSidebar layout="admin" items={permissionItems} />
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
// Subframe flat sidebar: an expandable parent is a non-interactive section header (not a button/link).
|
||||
expect(document.querySelector('[data-ui-id="ui.nav.test.accounts"]')).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Accounts" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Accounts" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps a denied parent visible when at least one child is allowed", () => {
|
||||
mockedPermissions = ["admin.users.view"];
|
||||
const permissionItems: SideBarItem[] = [
|
||||
{
|
||||
id: "ui.nav.test.main",
|
||||
title: "Main",
|
||||
path: "",
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.test.accounts",
|
||||
title: "Accounts",
|
||||
path: "/accounts",
|
||||
permission: "admin.accounts.view",
|
||||
items: [
|
||||
{ id: "ui.nav.test.accounts.users", title: "Users", path: "/accounts/users", permission: "admin.users.view" },
|
||||
{ id: "ui.nav.test.accounts.roles", title: "Roles", path: "/accounts/roles", permission: "admin.roles.view" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/accounts/users"]}>
|
||||
<SidebarProvider>
|
||||
<ShadcnAppSidebar layout="admin" items={permissionItems} />
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByText("Accounts")).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /Accounts/ })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Accounts" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Users" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Roles" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps central surface constants stable", () => {
|
||||
expect(UI_SURFACE_IDS.appSidebar).toBe("ui.surface.app.sidebar");
|
||||
expect(UI_SURFACE_IDS.adminSidebar).toBe("ui.surface.admin.sidebar");
|
||||
expect(UI_SURFACE_IDS.docsSidebar).toBe("ui.surface.docs.sidebar");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,343 @@
|
||||
// // "use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { NavMain } from "./nav-main";
|
||||
import { NavQuickLinks } from "./nav-quick-links";
|
||||
import { NavSecondary } from "./nav-secondary";
|
||||
import { NavUser } from "./nav-user";
|
||||
import { Sidebar, SidebarContent, SidebarFooter, SidebarHeader, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "~/components/ui/sidebar";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { AppSidebar } from "~/application/sidebar/AppSidebar";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { SideBarItem } from "~/application/sidebar/SidebarItem";
|
||||
import { AdminSidebar } from "~/application/sidebar/AdminSidebar";
|
||||
import { useLocation, useParams } from "react-router";
|
||||
import { DocsSidebar } from "~/application/sidebar/DocsSidebar";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { SidebarGroupDto } from "~/application/sidebar/SidebarGroupDto";
|
||||
import { TeamSwitcher } from "./team-switcher";
|
||||
import { DARK_SIDEBAR_IN_LIGHT_MODE } from "~/application/Constants";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { ThemeConfig } from "~/utils/theme/ThemeConfig";
|
||||
import { getSidebarSurfaceId } from "~/application/ui/uiRegistry";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
|
||||
|
||||
export function ShadcnAppSidebar({
|
||||
themeConfig,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Sidebar> & {
|
||||
layout: "app" | "admin" | "docs";
|
||||
items?: SideBarItem[];
|
||||
themeConfig?: ThemeConfig | null;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const location = useLocation();
|
||||
const rootData = useRootData();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const appData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
|
||||
// const data = {
|
||||
// // user: {
|
||||
// // name: "shadcn",
|
||||
// // email: "m@example.com",
|
||||
// // avatar: "/avatars/shadcn.jpg",
|
||||
// // },
|
||||
// navMain: [
|
||||
// {
|
||||
// title: "Playground",
|
||||
// url: "#",
|
||||
// icon: SquareTerminal,
|
||||
// isActive: true,
|
||||
// items: [
|
||||
// {
|
||||
// title: "History",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Starred",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Settings",
|
||||
// url: "#",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// title: "Models",
|
||||
// url: "#",
|
||||
// icon: Bot,
|
||||
// items: [
|
||||
// {
|
||||
// title: "Genesis",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Explorer",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Quantum",
|
||||
// url: "#",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// title: "Documentation",
|
||||
// url: "#",
|
||||
// icon: BookOpen,
|
||||
// items: [
|
||||
// {
|
||||
// title: "Introduction",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Get Started",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Tutorials",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Changelog",
|
||||
// url: "#",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// {
|
||||
// title: "Settings",
|
||||
// url: "#",
|
||||
// icon: Settings2,
|
||||
// items: [
|
||||
// {
|
||||
// title: "General",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Team",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Billing",
|
||||
// url: "#",
|
||||
// },
|
||||
// {
|
||||
// title: "Limits",
|
||||
// url: "#",
|
||||
// },
|
||||
// ],
|
||||
// },
|
||||
// ],
|
||||
// navSecondary: [
|
||||
// {
|
||||
// title: "Support",
|
||||
// url: "#",
|
||||
// icon: LifeBuoy,
|
||||
// },
|
||||
// {
|
||||
// title: "Feedback",
|
||||
// url: "#",
|
||||
// icon: Send,
|
||||
// },
|
||||
// ],
|
||||
// projects: [
|
||||
// {
|
||||
// name: "Quick link 1",
|
||||
// url: "#",
|
||||
// icon: Frame,
|
||||
// },
|
||||
// {
|
||||
// name: "Quick link 2",
|
||||
// url: "#",
|
||||
// icon: PieChart,
|
||||
// },
|
||||
// {
|
||||
// name: "Quick link 3",
|
||||
// url: "#",
|
||||
// icon: Map,
|
||||
// },
|
||||
// ],
|
||||
// };
|
||||
|
||||
const getMenuItems = () => {
|
||||
let menu: SideBarItem[] = [];
|
||||
if (props.items) {
|
||||
menu = props.items;
|
||||
} else if (props.layout === "admin") {
|
||||
menu = AdminSidebar({ t, appConfiguration: rootData.appConfiguration, routing: rootData.routing });
|
||||
} else if (props.layout === "app") {
|
||||
menu = AppSidebar({
|
||||
t,
|
||||
i18n,
|
||||
tenantId: params.tenant ?? "",
|
||||
entities: appOrAdminData?.entities ?? [],
|
||||
entityGroups: appOrAdminData?.entityGroups ?? [],
|
||||
appConfiguration: rootData.appConfiguration,
|
||||
routing: rootData.routing,
|
||||
productAccess: appOrAdminData?.productAccess,
|
||||
});
|
||||
} else if (props.layout === "docs") {
|
||||
menu = DocsSidebar();
|
||||
}
|
||||
|
||||
return menu.map((item) => prepareMenuItem(item));
|
||||
};
|
||||
|
||||
function getPath(item: SideBarItem): string {
|
||||
return UrlUtils.replaceVariables(params, item.path) ?? "";
|
||||
}
|
||||
|
||||
function normalizePath(path: string): string {
|
||||
return path.length > 1 ? path.replace(/\/+$/, "") : path;
|
||||
}
|
||||
|
||||
function pathMatchesCurrent(path: string, exact?: boolean): boolean {
|
||||
if (!path) {
|
||||
return false;
|
||||
}
|
||||
const currentPath = normalizePath(location.pathname);
|
||||
const itemPath = normalizePath(path);
|
||||
if (exact) {
|
||||
return currentPath === itemPath;
|
||||
}
|
||||
return currentPath === itemPath || currentPath.startsWith(`${itemPath}/`);
|
||||
}
|
||||
|
||||
function isCurrent(menuItem: SideBarItem): boolean {
|
||||
return pathMatchesCurrent(getPath(menuItem), menuItem.exact);
|
||||
}
|
||||
|
||||
function currentIsChild(menuItem: SideBarItem): boolean {
|
||||
return menuItem.items?.some((item) => isCurrent(item) || currentIsChild(item)) ?? false;
|
||||
}
|
||||
|
||||
function prepareMenuItem(item: SideBarItem): SideBarItem {
|
||||
const childItems = item.isCollapsible === false ? [] : item.items?.map((child) => prepareMenuItem(child));
|
||||
const preparedItem: SideBarItem = {
|
||||
...item,
|
||||
path: UrlUtils.replaceVariables(params, item.path) ?? item.path,
|
||||
redirectTo: item.redirectTo ? (UrlUtils.replaceVariables(params, item.redirectTo) ?? item.redirectTo) : item.redirectTo,
|
||||
items: childItems,
|
||||
};
|
||||
const isActive = isCurrent(preparedItem);
|
||||
const hasActiveChild = currentIsChild(preparedItem);
|
||||
return {
|
||||
...preparedItem,
|
||||
isActive: preparedItem.isActive || isActive || hasActiveChild,
|
||||
};
|
||||
}
|
||||
function allowCurrentUserType(item: SideBarItem) {
|
||||
if (!item.adminOnly) {
|
||||
return true;
|
||||
}
|
||||
return Boolean(appData?.user?.admin);
|
||||
}
|
||||
function allowCurrentTenantUserType(item: SideBarItem) {
|
||||
const currentRole = "currentRole" in appData ? (appData.currentRole as TenantUserType) : null;
|
||||
return !item.tenantUserTypes || (currentRole !== null && item.tenantUserTypes.includes(currentRole));
|
||||
}
|
||||
function checkUserRolePermissions(item: SideBarItem) {
|
||||
return !item.permission || getUserHasPermission(appOrAdminData, item.permission);
|
||||
}
|
||||
function getVisibleItem(item: SideBarItem): SideBarItem | null {
|
||||
if (item.hidden === true || !allowCurrentUserType(item) || !allowCurrentTenantUserType(item)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const items = item.items?.map((child) => getVisibleItem(child)).filter((child): child is SideBarItem => child !== null) ?? [];
|
||||
const hasPermission = checkUserRolePermissions(item);
|
||||
if (!hasPermission && items.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
...item,
|
||||
path: hasPermission ? item.path : "",
|
||||
redirectTo: hasPermission ? item.redirectTo : undefined,
|
||||
items,
|
||||
};
|
||||
}
|
||||
const getMenu = (): SidebarGroupDto[] => {
|
||||
const _menu: SidebarGroupDto[] = [];
|
||||
getMenuItems()
|
||||
.forEach((f) => {
|
||||
const items = f.items?.map((item) => getVisibleItem(item)).filter((item): item is SideBarItem => item !== null) ?? [];
|
||||
if (f.hidden === true || items.length === 0) {
|
||||
return;
|
||||
}
|
||||
let type: "main" | "secondary" | "quick-link" = "main";
|
||||
if (f.isSecondary) {
|
||||
type = "secondary";
|
||||
} else if (f.isQuickLink) {
|
||||
type = "quick-link";
|
||||
}
|
||||
_menu.push({
|
||||
id: f.id,
|
||||
uiIdPattern: f.uiIdPattern,
|
||||
uiIdParams: f.uiIdParams,
|
||||
title: f.title.toString(),
|
||||
items,
|
||||
type,
|
||||
});
|
||||
});
|
||||
return _menu.filter((f) => f.items.length > 0);
|
||||
};
|
||||
|
||||
const navMain = getMenu().filter((f) => f.type === "main");
|
||||
const navSecondary = getMenu().find((f) => f.type === "secondary") || { items: [] };
|
||||
const navQuickLinks = getMenu().find((f) => f.type === "quick-link");
|
||||
|
||||
// Use theme config to determine sidebar variant and dark mode
|
||||
const sidebarVariant = themeConfig?.sidebarVariant || (DARK_SIDEBAR_IN_LIGHT_MODE(props) ? "sidebar" : "inset");
|
||||
const forceDarkMode = themeConfig?.sidebarDarkMode ?? DARK_SIDEBAR_IN_LIGHT_MODE(props);
|
||||
const sidebarSurfaceId = getSidebarSurfaceId(props.layout);
|
||||
|
||||
return (
|
||||
<Sidebar
|
||||
variant={sidebarVariant}
|
||||
collapsible="offcanvas"
|
||||
{...props}
|
||||
data-ui-id={sidebarSurfaceId}
|
||||
data-ui-layout={props.layout}
|
||||
className={cn(forceDarkMode && "dark")} // force dark mode
|
||||
>
|
||||
<SidebarHeader data-ui-id={`${sidebarSurfaceId}.header`}>
|
||||
<SidebarMenu className="select-none">
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton
|
||||
size="lg"
|
||||
asChild
|
||||
className="select-none"
|
||||
// className="dark:hover:bg-transparent dark:active:bg-transparent"
|
||||
>
|
||||
{props.layout === "app" && appData.currentTenant?.logo ? (
|
||||
<a href={appPath({ tenantSlug: appData.currentTenant.slug, path: "dashboard", mode: "host-aware" })} className="flex justify-center">
|
||||
<div className="flex shrink-0 items-center justify-center border-b border-transparent">
|
||||
<img className="mx-auto h-10 w-auto p-1.5" src={appData.currentTenant.logo} alt="Logo" />
|
||||
</div>
|
||||
</a>
|
||||
) : null}
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
|
||||
{props.layout === "app" && appData?.currentTenant && <TeamSwitcher key={params.tenant} size="sm" tenants={appData?.myTenants ?? []} />}
|
||||
</SidebarHeader>
|
||||
<SidebarContent className="pt-2" data-ui-id={`${sidebarSurfaceId}.content`}>
|
||||
<NavMain items={navMain} />
|
||||
{navQuickLinks && <NavQuickLinks item={navQuickLinks} />}
|
||||
<NavSecondary item={navSecondary} className="mt-auto" />
|
||||
</SidebarContent>
|
||||
{appOrAdminData.user && (
|
||||
<SidebarFooter data-ui-id={`${sidebarSurfaceId}.footer`}>
|
||||
<NavUser layout={props.layout} user={appOrAdminData.user} />
|
||||
</SidebarFooter>
|
||||
)}
|
||||
</Sidebar>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import React from "react";
|
||||
import { fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { createMemoryRouter, RouterProvider } from "react-router";
|
||||
import { beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { UI_ACTION_IDS } from "~/application/ui/uiRegistry";
|
||||
import { SidebarProvider } from "~/components/ui/sidebar";
|
||||
import { NavActions } from "./nav-actions";
|
||||
|
||||
const fetcherSubmit = vi.fn();
|
||||
|
||||
beforeAll(() => {
|
||||
Object.defineProperty(window, "matchMedia", {
|
||||
writable: true,
|
||||
value: vi.fn().mockImplementation((query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
addListener: vi.fn(),
|
||||
removeListener: vi.fn(),
|
||||
dispatchEvent: vi.fn(),
|
||||
})),
|
||||
});
|
||||
});
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (value: string) => value }),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({
|
||||
appConfiguration: {
|
||||
app: { features: { tenantFeedback: true } },
|
||||
notifications: { enabled: false },
|
||||
onboarding: { enabled: false },
|
||||
},
|
||||
chatWebsiteId: null,
|
||||
userSession: { lightOrDarkMode: "light" },
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({
|
||||
useAppOrAdminData: () => ({
|
||||
currentTenant: { id: "tenant-1", slug: "acme" },
|
||||
entities: [],
|
||||
permissions: ["app.settings.subscription.view", "app.settings.subscription.update"],
|
||||
user: { id: "user-1" },
|
||||
onboardingSession: null,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useAppData", () => ({
|
||||
useAppData: () => ({ mySubscription: { products: [] } }),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useFetcher: () => ({
|
||||
data: undefined,
|
||||
submit: fetcherSubmit,
|
||||
Form: (props: React.ComponentProps<"form">) => <form {...props} />,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
function renderNavActions({ layout, initialEntry }: { layout: "admin" | "app" | "docs"; initialEntry: string }) {
|
||||
const element = (
|
||||
<SidebarProvider>
|
||||
<NavActions layout={layout} onOpenCommandPalette={vi.fn()} setOnboardingModalOpen={vi.fn()} />
|
||||
</SidebarProvider>
|
||||
);
|
||||
const router = createMemoryRouter(
|
||||
[
|
||||
{ path: "/:tenant/*", element },
|
||||
{ path: "/*", element },
|
||||
],
|
||||
{ initialEntries: [initialEntry] }
|
||||
);
|
||||
|
||||
return render(<RouterProvider router={router} />);
|
||||
}
|
||||
|
||||
describe("NavActions UI IDs", () => {
|
||||
it("renders stable header action IDs for search and more", () => {
|
||||
renderNavActions({ layout: "app", initialEntry: "/acme/dashboard" });
|
||||
|
||||
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.search}"]`)).toBeInTheDocument();
|
||||
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.more}"]`)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("keeps icon-only header actions named, focusable, and mobile-scroll safe", () => {
|
||||
renderNavActions({ layout: "app", initialEntry: "/acme/dashboard" });
|
||||
|
||||
const search = screen.getByRole("button", { name: "shared.search" });
|
||||
const more = screen.getByRole("button", { name: "shared.openMenu" });
|
||||
const feedback = screen.getByRole("button", { name: "feedback.title" });
|
||||
const actionStrip = search.parentElement;
|
||||
|
||||
expect(actionStrip).toHaveClass("min-w-0", "max-w-[calc(100vw-4rem)]", "overflow-x-auto", "md:overflow-visible");
|
||||
expect(search).toHaveClass("size-10", "shrink-0", "focus-visible:ring-[3px]");
|
||||
expect(more).toHaveClass("size-10", "shrink-0", "data-[state=open]:bg-accent");
|
||||
expect(feedback).toHaveClass("size-10", "shrink-0");
|
||||
// The decorative search icon (a Subframe Feather icon: <span aria-hidden><svg/></span>)
|
||||
// is hidden from assistive tech at the icon wrapper, which contains the svg.
|
||||
const hiddenSearchIcon = search.querySelector("[aria-hidden='true']");
|
||||
expect(hiddenSearchIcon).not.toBeNull();
|
||||
expect(hiddenSearchIcon?.querySelector("svg")).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("NavActions host-aware links", () => {
|
||||
it("renders tenant profile and subscription paths without legacy app prefix", () => {
|
||||
renderNavActions({ layout: "app", initialEntry: "/acme/dashboard" });
|
||||
|
||||
fireEvent.click(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.more}"]`)!);
|
||||
|
||||
const profile = screen.getByRole("link", { name: /app\.navbar\.profile/i });
|
||||
const subscription = screen.getByRole("link", { name: /app\.navbar\.subscription/i });
|
||||
|
||||
expect(profile).toHaveAttribute("href", "/acme/settings/profile");
|
||||
expect(subscription).toHaveAttribute("href", "/acme/settings/subscription");
|
||||
expect(profile.getAttribute("href")).not.toContain("/app/");
|
||||
expect(subscription.getAttribute("href")).not.toContain("/app/");
|
||||
});
|
||||
|
||||
it("renders admin profile path without legacy admin prefix", () => {
|
||||
renderNavActions({ layout: "admin", initialEntry: "/dashboard" });
|
||||
|
||||
fireEvent.click(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.more}"]`)!);
|
||||
|
||||
const profile = screen.getByRole("link", { name: /app\.navbar\.profile/i });
|
||||
expect(profile).toHaveAttribute("href", "/settings/profile");
|
||||
expect(profile.getAttribute("href")).not.toContain("/admin/settings");
|
||||
});
|
||||
|
||||
it("submits feedback to the tenant-root action without legacy app prefix", () => {
|
||||
renderNavActions({ layout: "app", initialEntry: "/acme/dashboard" });
|
||||
|
||||
fireEvent.click(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.feedback}"]`)!);
|
||||
fireEvent.change(screen.getByPlaceholderText("feedback.placeholder"), { target: { value: "Helpful feedback" } });
|
||||
fireEvent.submit(within(screen.getByRole("dialog")).getByRole("button", { name: "feedback.send" }).closest("form")!);
|
||||
|
||||
expect(fetcherSubmit).toHaveBeenCalledWith(expect.any(HTMLFormElement), {
|
||||
method: "post",
|
||||
action: "/acme",
|
||||
});
|
||||
expect(fetcherSubmit.mock.calls[0][1].action).not.toContain("/app/");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,313 @@
|
||||
"use client";
|
||||
|
||||
import * as React from "react";
|
||||
import { CreditCard, LogOut, MoreHorizontal, GearIcon, SparklesIcon, SearchIcon, MessageCircleIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { Sidebar, SidebarContent, SidebarGroup, SidebarGroupContent, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "~/components/ui/sidebar";
|
||||
import NavBar from "../../NavBar";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { Form, useFetcher, useLocation, useParams } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import Modal from "~/components/ui/modals/Modal";
|
||||
import StarsIconFilled from "~/components/ui/icons/StarsIconFilled";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import OnboardingButton from "../../buttons/OnboardingButton";
|
||||
import { toast } from "sonner";
|
||||
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
|
||||
import { Textarea } from "~/components/ui/textarea";
|
||||
import { UI_ACTION_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
|
||||
import { subscriptionCheckoutPath } from "~/utils/app/SubscriptionUrlUtils";
|
||||
import NotificationsButton from "../../buttons/NotificationsButton";
|
||||
|
||||
const headerIconButtonClass = "size-10 shrink-0 text-muted-foreground";
|
||||
|
||||
export function NavActions({
|
||||
layout,
|
||||
onOpenCommandPalette,
|
||||
setOnboardingModalOpen,
|
||||
}: {
|
||||
layout: "admin" | "app" | "docs";
|
||||
onOpenCommandPalette: () => void;
|
||||
setOnboardingModalOpen: (value: boolean) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// const title = useTitleData() ?? "";
|
||||
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const appData = useAppData();
|
||||
const rootData = useRootData();
|
||||
const appConfiguration = rootData.appConfiguration;
|
||||
const params = useParams();
|
||||
|
||||
const tenantPath = (path?: string) => (params.tenant ? appPath({ tenantSlug: params.tenant, path, mode: "host-aware" }) : "");
|
||||
const adminShellPath = (path?: string) => adminPath(path, { mode: "host-aware" });
|
||||
|
||||
const [isOpen, setIsOpen] = React.useState(false);
|
||||
|
||||
function hasSubscription() {
|
||||
const myProducts = appData?.mySubscription?.products.map((f) => t(f.subscriptionProduct.title)) ?? [];
|
||||
return myProducts.length > 0;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-w-0 max-w-full overflow-hidden text-sm">
|
||||
{false && (
|
||||
<NavBar
|
||||
layout={layout}
|
||||
// title={title}
|
||||
buttons={{
|
||||
mySubscription: getUserHasPermission(appOrAdminData, "app.settings.subscription.update"),
|
||||
feedback: rootData.appConfiguration.app.features.tenantFeedback,
|
||||
chatSupport: !!rootData.chatWebsiteId,
|
||||
quickActions: appOrAdminData?.entities?.filter((f) => f.showInSidebar).length > 0,
|
||||
search: true,
|
||||
notifications: appConfiguration.notifications.enabled && (layout === "admin" || layout === "app"),
|
||||
onboarding: appConfiguration.onboarding.enabled,
|
||||
userProfile: false,
|
||||
}}
|
||||
onOpenCommandPalette={onOpenCommandPalette}
|
||||
onOpenOnboardingModal={() => setOnboardingModalOpen(true)}
|
||||
></NavBar>
|
||||
)}
|
||||
|
||||
<div className="flex min-w-0 max-w-[calc(100vw-4rem)] items-center gap-1 overflow-x-auto overscroll-x-contain py-1 [scrollbar-width:none] md:ml-6 md:max-w-none md:gap-2 md:overflow-visible md:py-0 [&::-webkit-scrollbar]:hidden">
|
||||
{appConfiguration.onboarding.enabled && appOrAdminData?.onboardingSession && (
|
||||
<div data-ui-id={UI_ACTION_IDS.onboarding}>
|
||||
<OnboardingButton item={appOrAdminData?.onboardingSession} onClick={() => setOnboardingModalOpen(true)} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* NavBar Button: My Subscription */}
|
||||
{layout === "app" && getUserHasPermission(appOrAdminData, "app.settings.subscription.update") && (
|
||||
<React.Fragment>
|
||||
{!hasSubscription() && (
|
||||
<a href={subscriptionCheckoutPath(params.tenant ?? "")}>
|
||||
<Button variant="outline" size="sm" data-ui-id={UI_ACTION_IDS.subscription}>
|
||||
<span>{t("pricing.subscribe")} </span>
|
||||
<SparklesIcon className="ml-2 h-4 w-4" />
|
||||
</Button>
|
||||
</a>
|
||||
)}
|
||||
</React.Fragment>
|
||||
)}
|
||||
|
||||
{/* NavBar Button: Notifications */}
|
||||
{appConfiguration.notifications.enabled && (layout === "admin" || layout === "app") && appOrAdminData?.user && (
|
||||
<div className="text-foreground/70 px-2 py-0.5">
|
||||
<NotificationsButton to={layout === "admin" ? adminShellPath("notifications") : tenantPath("notifications")} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* NavBar Button: Search */}
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={onOpenCommandPalette}
|
||||
className={headerIconButtonClass}
|
||||
aria-label={t("shared.search")}
|
||||
data-ui-id={UI_ACTION_IDS.search}
|
||||
>
|
||||
<SearchIcon className="size-5" aria-hidden="true" />
|
||||
</Button>
|
||||
|
||||
{/* NavBar Button: Feedback */}
|
||||
{appConfiguration.app.features.tenantFeedback && layout === "app" && <AddFeedbackButton />}
|
||||
|
||||
{/* NavBar Button: Chat Support */}
|
||||
{(layout === "app" || layout === "admin") && !!rootData.chatWebsiteId && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={headerIconButtonClass}
|
||||
aria-label={t("shared.openSupportChat")}
|
||||
data-ui-id={UI_ACTION_IDS.chatSupport}
|
||||
onClick={() => {
|
||||
try {
|
||||
// @ts-ignore
|
||||
$crisp?.push(["do", "chat:open"]);
|
||||
// @ts-ignore
|
||||
$crisp?.push(["do", "chat:show"]);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}}
|
||||
>
|
||||
<MessageCircleIcon className="size-5" aria-hidden="true" />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* NavBar Button: Profile */}
|
||||
{/* {(layout === "app" || layout === "admin") && <ProfileButton user={appOrAdminData?.user} layout={layout} />} */}
|
||||
|
||||
{/* NavBar Button: Theme Selector */}
|
||||
{/* {rootData.debug && <ThemeSelector variant="secondary" />} */}
|
||||
|
||||
{/* NavBar Button: Quick Actions */}
|
||||
{/* {layout === "app" && <QuickActionsButton entities={appOrAdminData?.entities?.filter((f) => f.showInSidebar)} />} */}
|
||||
|
||||
{/* NavBar Button: More */}
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={`${headerIconButtonClass} data-[state=open]:bg-accent`}
|
||||
aria-label={t("shared.openMenu")}
|
||||
data-ui-id={UI_ACTION_IDS.more}
|
||||
>
|
||||
<MoreHorizontal className="size-4" aria-hidden="true" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-56 overflow-hidden rounded-lg p-0" align="end">
|
||||
<Sidebar collapsible="none" className="bg-transparent">
|
||||
<SidebarContent>
|
||||
{layout === "app" ? (
|
||||
<SidebarGroup className="border-b last:border-none">
|
||||
<SidebarGroupContent className="gap-0">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<a href={tenantPath("settings/profile")}>
|
||||
<SidebarMenuButton data-ui-id={UI_ACTION_IDS.profile}>
|
||||
<GearIcon className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.profile")}
|
||||
</SidebarMenuButton>
|
||||
</a>
|
||||
</SidebarMenuItem>
|
||||
|
||||
{getUserHasPermission(appOrAdminData, "app.settings.subscription.view") && (
|
||||
<SidebarMenuItem>
|
||||
<a href={tenantPath("settings/subscription")}>
|
||||
<SidebarMenuButton data-ui-id={UI_ACTION_IDS.subscription}>
|
||||
<CreditCard className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.subscription")}
|
||||
</SidebarMenuButton>
|
||||
</a>
|
||||
</SidebarMenuItem>
|
||||
)}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
) : layout === "admin" ? (
|
||||
<SidebarGroup className="border-b last:border-none">
|
||||
<SidebarGroupContent className="gap-0">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<a href={adminShellPath("settings/profile")}>
|
||||
<SidebarMenuButton data-ui-id={UI_ACTION_IDS.profile}>
|
||||
<GearIcon className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.profile")}
|
||||
</SidebarMenuButton>
|
||||
</a>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
) : null}
|
||||
|
||||
<SidebarGroup className="border-b last:border-none">
|
||||
<SidebarGroupContent className="gap-0">
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<Form method="post" action="/logout">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<SidebarMenuButton data-ui-id={UI_ACTION_IDS.signOut} className="w-full" type="submit">
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.signOut")}
|
||||
</SidebarMenuButton>
|
||||
</Form>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
</SidebarContent>
|
||||
</Sidebar>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AddFeedbackButton() {
|
||||
const [isOpen, setIsOpen] = React.useState(false);
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<React.Fragment>
|
||||
<Button
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={headerIconButtonClass}
|
||||
aria-label={t("feedback.title")}
|
||||
data-ui-id={UI_ACTION_IDS.feedback}
|
||||
>
|
||||
<span className="sr-only">{t("feedback.title")}</span>
|
||||
<span aria-hidden="true">
|
||||
<StarsIconFilled className="size-5 p-0.5" />
|
||||
</span>
|
||||
</Button>
|
||||
<Modal open={isOpen} setOpen={setIsOpen} size="sm" data-ui-id={UI_SURFACE_IDS.feedbackDialog}>
|
||||
<FeedbackForm isOpen={isOpen} onClose={() => setIsOpen(false)} />
|
||||
</Modal>
|
||||
</React.Fragment>
|
||||
);
|
||||
}
|
||||
|
||||
function FeedbackForm({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
const params = useParams();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const fetcher = useFetcher<{ success?: string; error?: string }>();
|
||||
const location = useLocation();
|
||||
|
||||
const mainInput = React.useRef<HTMLTextAreaElement>(null);
|
||||
React.useEffect(() => {
|
||||
if (isOpen) {
|
||||
setTimeout(() => {
|
||||
mainInput.current?.focus();
|
||||
}, 100);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
React.useEffect(() => {
|
||||
if (fetcher.data?.success) {
|
||||
toast.success(fetcher.data.success);
|
||||
onClose();
|
||||
} else if (fetcher.data?.error) {
|
||||
toast.error(fetcher.data.error);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [fetcher.data]);
|
||||
|
||||
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
|
||||
e.preventDefault();
|
||||
fetcher.submit(e.currentTarget, {
|
||||
method: "post",
|
||||
action: params.tenant ? appPath({ tenantSlug: params.tenant, mode: "host-aware" }) : "",
|
||||
});
|
||||
// onClose();
|
||||
};
|
||||
return (
|
||||
<fetcher.Form onSubmit={onSubmit} method="post">
|
||||
<input type="hidden" name="action" value="add-feedback" readOnly hidden />
|
||||
<input type="hidden" name="tenantId" value={appOrAdminData.currentTenant?.id} readOnly hidden />
|
||||
<input type="hidden" name="fromUrl" value={location.pathname} readOnly hidden />
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-lg leading-6 font-medium">{t("feedback.title")}</h3>
|
||||
<p className="text-muted-foreground text-sm">{t("feedback.description")}</p>
|
||||
<Textarea ref={mainInput} name="message" defaultValue="" required rows={5} placeholder={t("feedback.placeholder")} />
|
||||
<div className="flex justify-between">
|
||||
<button type="button" onClick={onClose} className="text-muted-foreground text-sm hover:underline">
|
||||
{t("shared.cancel")}
|
||||
</button>
|
||||
<ButtonPrimary type="submit">{t("feedback.send")}</ButtonPrimary>
|
||||
</div>
|
||||
</div>
|
||||
</fetcher.Form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { SidebarProvider } from "~/components/ui/sidebar";
|
||||
import { UI_ID_PATTERNS, UI_NAV_IDS } from "~/application/ui/uiRegistry";
|
||||
import { NavMain } from "./nav-main";
|
||||
|
||||
vi.mock("~/hooks/use-mobile", () => ({
|
||||
useIsMobile: () => false,
|
||||
}));
|
||||
|
||||
describe("NavMain UI IDs", () => {
|
||||
it("renders group, static item and dynamic child data-ui-id attributes", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/acme/g/sales/contacts"]}>
|
||||
<SidebarProvider>
|
||||
<NavMain
|
||||
items={[
|
||||
{
|
||||
id: "ui.nav.app.primary",
|
||||
title: "Primary",
|
||||
type: "main",
|
||||
items: [
|
||||
{
|
||||
id: UI_NAV_IDS.appDashboard,
|
||||
title: "Dashboard",
|
||||
path: "/acme/dashboard",
|
||||
},
|
||||
{
|
||||
id: "ui.nav.app.entityGroup.sales",
|
||||
uiIdPattern: UI_ID_PATTERNS.appEntityGroup,
|
||||
uiIdParams: { groupSlug: "sales" },
|
||||
title: "Sales",
|
||||
path: "/acme/g/sales",
|
||||
isActive: true,
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.app.entityGroup.sales.entity.contacts",
|
||||
uiIdPattern: UI_ID_PATTERNS.appEntityGroupEntity,
|
||||
uiIdParams: { groupSlug: "sales", entityName: "contacts" },
|
||||
title: "Contacts",
|
||||
path: "/acme/g/sales/contacts",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(document.querySelector('[data-ui-id="ui.nav.app.primary"]')).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Dashboard" })).toHaveAttribute("data-ui-id", UI_NAV_IDS.appDashboard);
|
||||
// Subframe flat sidebar: an expandable parent is a non-interactive section header — not a button, not a link.
|
||||
expect(document.querySelector('[data-ui-id="ui.nav.app.entityGroup.sales"]')).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Sales" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Sales" })).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Sales")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Contacts" })).toHaveAttribute("data-ui-id", "ui.nav.app.entityGroup.sales.entity.contacts");
|
||||
expect(screen.getByRole("link", { name: "Contacts" })).toHaveAttribute("data-ui-id-pattern", UI_ID_PATTERNS.appEntityGroupEntity);
|
||||
expect(screen.getByRole("link", { name: "Contacts" })).toHaveAttribute("data-ui-id-param-entityname", "contacts");
|
||||
expect(screen.getByRole("link", { name: "Contacts" })).toHaveAttribute("data-active", "false");
|
||||
});
|
||||
|
||||
it("keeps active host-aware children expanded without duplicate data-ui-id values", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/acme/accounts/contacts"]}>
|
||||
<SidebarProvider>
|
||||
<NavMain
|
||||
items={[
|
||||
{
|
||||
id: "ui.nav.app.primary",
|
||||
title: "Primary",
|
||||
type: "main",
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.app.accounts",
|
||||
title: "Accounts",
|
||||
path: "/acme/accounts",
|
||||
isActive: true,
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.app.accounts.contacts",
|
||||
title: "Contacts",
|
||||
path: "/acme/accounts/contacts",
|
||||
isActive: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "ui.nav.app.accounting",
|
||||
title: "Accounting",
|
||||
path: "/acme/accounting",
|
||||
},
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(document.querySelector('[data-ui-id="ui.nav.app.accounts"]')).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: "Accounts" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Accounts" })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Contacts" })).toHaveAttribute("data-active", "true");
|
||||
expect(screen.getByRole("link", { name: "Accounting" })).toHaveAttribute("data-active", "false");
|
||||
const ids = [...document.querySelectorAll("[data-ui-id]")].map((element) => element.getAttribute("data-ui-id"));
|
||||
expect(new Set(ids).size).toBe(ids.length);
|
||||
});
|
||||
|
||||
it("renders expandable parents as flat, non-interactive section headers", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/admin/settings/general"]}>
|
||||
<SidebarProvider>
|
||||
<NavMain
|
||||
items={[
|
||||
{
|
||||
id: "ui.nav.admin.primary",
|
||||
title: "Primary",
|
||||
type: "main",
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.admin.settings",
|
||||
title: "Settings",
|
||||
path: "/settings",
|
||||
isActive: true,
|
||||
isExpandedByHref: true,
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.admin.settings.general",
|
||||
title: "General",
|
||||
path: "/settings/general",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.queryByRole("button", { name: "Settings" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Settings" })).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Settings")).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "General" })).toHaveAttribute("href", "/settings/general");
|
||||
});
|
||||
|
||||
it("hides disabled items and honors redirect targets for subitems", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/settings/profile"]}>
|
||||
<SidebarProvider>
|
||||
<NavMain
|
||||
items={[
|
||||
{
|
||||
title: "Primary",
|
||||
type: "main",
|
||||
items: [
|
||||
{
|
||||
title: "Settings",
|
||||
path: "/settings",
|
||||
isActive: true,
|
||||
items: [
|
||||
{ title: "Profile", path: "/settings", redirectTo: "/settings/profile" },
|
||||
{ title: "Disabled Plugin", path: "/disabled-plugin", disabled: true },
|
||||
],
|
||||
},
|
||||
{ title: "Disabled Root", path: "/disabled-root", disabled: true },
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Profile" })).toHaveAttribute("href", "/settings/profile");
|
||||
expect(screen.queryByRole("link", { name: "Disabled Plugin" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Disabled Root" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not turn parents with only disabled children into links", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/settings"]}>
|
||||
<SidebarProvider>
|
||||
<NavMain
|
||||
items={[
|
||||
{
|
||||
title: "Primary",
|
||||
type: "main",
|
||||
items: [
|
||||
{
|
||||
title: "Settings",
|
||||
path: "/settings",
|
||||
items: [{ title: "Disabled Plugin", path: "/settings/plugin", disabled: true }],
|
||||
},
|
||||
],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.queryByRole("link", { name: "Settings" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /Settings/ })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Disabled Plugin" })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
// // "use client";
|
||||
|
||||
import { type ReactNode } from "react";
|
||||
import { Fragment } from "react/jsx-runtime";
|
||||
import { SidebarGroupDto } from "~/application/sidebar/SidebarGroupDto";
|
||||
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupLabel,
|
||||
SidebarMenu,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
} from "~/components/ui/sidebar";
|
||||
import SidebarIcon from "../../icons/SidebarIcon";
|
||||
import { getUiIdAttributes } from "~/application/ui/uiRegistry";
|
||||
|
||||
type SidebarNavItem = SidebarGroupDto["items"][number];
|
||||
|
||||
function getEnabledItems(items: SidebarNavItem[] = []): SidebarNavItem[] {
|
||||
return items.filter((item) => !item.disabled);
|
||||
}
|
||||
|
||||
function hasConfiguredChildren(item: SidebarNavItem) {
|
||||
return (item.items?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
function SidebarLink({ to, children, ...props }: { to: string; children: ReactNode } & Record<string, unknown>) {
|
||||
return (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarItemContent({ item }: { item: SidebarNavItem }) {
|
||||
return (
|
||||
<>
|
||||
{item.icon !== undefined && <SidebarIcon className="size-4" item={item} />}
|
||||
<span>{item.title}</span>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Subframe SidebarWithSections is flat: a parent that groups children is a
|
||||
// (non-interactive) section header — like Subframe's NavSection label — with its
|
||||
// sub-items always visible beneath it. No collapse/accordion, no chevron, and
|
||||
// the parent is not a link (these parents never navigated; they were toggles).
|
||||
function NavMainExpandedItem({ item }: { item: SidebarNavItem }) {
|
||||
const subItems = getEnabledItems(item.items);
|
||||
return (
|
||||
<>
|
||||
<SidebarMenuItem>
|
||||
<div
|
||||
data-sidebar-group-parent=""
|
||||
className="text-sidebar-foreground/80 flex w-full items-center gap-2.5 rounded-md px-3 py-2 text-base font-medium sm:text-sm [&>svg]:size-4 [&>svg]:shrink-0"
|
||||
{...getUiIdAttributes(item)}
|
||||
>
|
||||
<SidebarItemContent item={item} />
|
||||
</div>
|
||||
</SidebarMenuItem>
|
||||
<SidebarMenuSub>
|
||||
{subItems.map((subItem) => (
|
||||
<SidebarMenuSubItem key={subItem.title}>
|
||||
<SidebarMenuSubButton asChild isActive={subItem.isActive} className="h-9 text-base sm:h-8 sm:text-sm">
|
||||
<SidebarLink to={subItem.redirectTo ?? subItem.path} {...getUiIdAttributes(subItem)}>
|
||||
<span>{subItem.title}</span>
|
||||
</SidebarLink>
|
||||
</SidebarMenuSubButton>
|
||||
</SidebarMenuSubItem>
|
||||
))}
|
||||
</SidebarMenuSub>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function NavMain({ items }: { items: SidebarGroupDto[] }) {
|
||||
return (
|
||||
<Fragment>
|
||||
{items.map((group, idxGroup) => (
|
||||
<SidebarGroup key={idxGroup} className="p-0 px-2" {...getUiIdAttributes(group)}>
|
||||
{group.title && <SidebarGroupLabel>{group.title}</SidebarGroupLabel>}
|
||||
<SidebarMenu>
|
||||
{getEnabledItems(group.items).map((item, idx) => {
|
||||
const enabledChildren = getEnabledItems(item.items);
|
||||
if (hasConfiguredChildren(item) && enabledChildren.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Fragment key={idx}>
|
||||
{enabledChildren.length === 0 ? (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild isActive={item.isActive} size="default" className="h-9 text-base font-medium sm:h-8 sm:text-sm">
|
||||
<SidebarLink to={item.path} {...getUiIdAttributes(item)}>
|
||||
<SidebarItemContent item={item} />
|
||||
</SidebarLink>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
) : (
|
||||
<NavMainExpandedItem item={item} />
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
))}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// // "use client";
|
||||
|
||||
import { SidebarGroupDto } from "~/application/sidebar/SidebarGroupDto";
|
||||
|
||||
import { SidebarGroup, SidebarGroupLabel, SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "~/components/ui/sidebar";
|
||||
import SidebarIcon from "../../icons/SidebarIcon";
|
||||
import { getUiIdAttributes } from "~/application/ui/uiRegistry";
|
||||
|
||||
export function NavQuickLinks({
|
||||
item,
|
||||
}: {
|
||||
// items: {
|
||||
// name: string;
|
||||
// url: string;
|
||||
// icon: LucideIcon;
|
||||
// }[];
|
||||
item: SidebarGroupDto;
|
||||
}) {
|
||||
const enabledItems = item.items.filter((item) => !item.disabled);
|
||||
|
||||
return (
|
||||
<SidebarGroup className="group-data-[collapsible=icon]:hidden" {...getUiIdAttributes(item)}>
|
||||
<SidebarGroupLabel>{item.title}</SidebarGroupLabel>
|
||||
<SidebarMenu>
|
||||
{enabledItems.map((item) => (
|
||||
<SidebarMenuItem key={item.path}>
|
||||
<SidebarMenuButton asChild size="default" className="h-9 text-base sm:h-8 sm:text-sm">
|
||||
<a href={item.path} {...getUiIdAttributes(item)}>
|
||||
{/* <item.icon /> */}
|
||||
{item.icon !== undefined && <SidebarIcon className="h-5 w-5" item={item} />}
|
||||
<span>{item.title}</span>
|
||||
</a>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
))}
|
||||
</SidebarMenu>
|
||||
</SidebarGroup>
|
||||
);
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { SidebarProvider } from "~/components/ui/sidebar";
|
||||
import { NavSecondary } from "./nav-secondary";
|
||||
|
||||
vi.mock("~/hooks/use-mobile", () => ({
|
||||
useIsMobile: () => false,
|
||||
}));
|
||||
|
||||
describe("NavSecondary", () => {
|
||||
it("renders permitted collapsible parents as links with separate toggle controls", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/settings/profile"]}>
|
||||
<SidebarProvider>
|
||||
<NavSecondary
|
||||
item={{
|
||||
id: "ui.nav.admin.secondary",
|
||||
title: "",
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.admin.settings",
|
||||
title: "Settings",
|
||||
path: "/settings",
|
||||
isActive: true,
|
||||
items: [
|
||||
{
|
||||
id: "ui.nav.admin.settings.profile",
|
||||
title: "Profile",
|
||||
path: "/settings/profile",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Settings" })).toHaveAttribute("href", "/settings");
|
||||
expect(screen.getByRole("link", { name: "Settings" })).toHaveAttribute("data-active", "true");
|
||||
expect(screen.getByRole("button", { name: "Toggle Settings" })).toBeInTheDocument();
|
||||
expect(screen.getByRole("link", { name: "Profile" })).toHaveAttribute("href", "/settings/profile");
|
||||
});
|
||||
|
||||
it("hides disabled secondary items and honors redirect targets", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/settings/profile"]}>
|
||||
<SidebarProvider>
|
||||
<NavSecondary
|
||||
item={{
|
||||
title: "",
|
||||
items: [
|
||||
{
|
||||
title: "Settings",
|
||||
path: "/settings",
|
||||
isActive: true,
|
||||
items: [
|
||||
{ title: "Profile", path: "/settings", redirectTo: "/settings/profile" },
|
||||
{ title: "Disabled Plugin", path: "/disabled-plugin", disabled: true },
|
||||
],
|
||||
},
|
||||
{ title: "Disabled Root", path: "/disabled-root", disabled: true },
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("link", { name: "Profile" })).toHaveAttribute("href", "/settings/profile");
|
||||
expect(screen.queryByRole("link", { name: "Disabled Plugin" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Disabled Root" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not turn parents with only disabled children into links", () => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={["/settings"]}>
|
||||
<SidebarProvider>
|
||||
<NavSecondary
|
||||
item={{
|
||||
title: "",
|
||||
items: [
|
||||
{
|
||||
title: "Settings",
|
||||
path: "/settings",
|
||||
items: [{ title: "Disabled Plugin", path: "/settings/plugin", disabled: true }],
|
||||
},
|
||||
],
|
||||
}}
|
||||
/>
|
||||
</SidebarProvider>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.queryByRole("link", { name: "Settings" })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /Settings/ })).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("link", { name: "Disabled Plugin" })).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,136 @@
|
||||
import * as React from "react";
|
||||
|
||||
import { ChevronRight } from "~/components/ui/icons/vendor";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "~/components/ui/collapsible";
|
||||
import {
|
||||
SidebarGroup,
|
||||
SidebarGroupContent,
|
||||
SidebarMenu,
|
||||
SidebarMenuAction,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
} from "~/components/ui/sidebar";
|
||||
import { SidebarGroupDto } from "~/application/sidebar/SidebarGroupDto";
|
||||
import SidebarIcon from "../../icons/SidebarIcon";
|
||||
import { getUiIdAttributes } from "~/application/ui/uiRegistry";
|
||||
import { t as i18nT } from "i18next";
|
||||
|
||||
type SidebarNavItem = SidebarGroupDto["items"][number];
|
||||
|
||||
function getEnabledItems(items: SidebarNavItem[] = []): SidebarNavItem[] {
|
||||
return items.filter((item) => !item.disabled);
|
||||
}
|
||||
|
||||
function hasConfiguredChildren(item: SidebarNavItem) {
|
||||
return (item.items?.length ?? 0) > 0;
|
||||
}
|
||||
|
||||
function SidebarLink({ to, children, ...props }: { to: string; children: React.ReactNode } & Record<string, unknown>) {
|
||||
return (
|
||||
<a href={to} {...props}>
|
||||
{children}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
function NavSecondaryCollapsibleItem({ item }: { item: SidebarNavItem }) {
|
||||
const [open, setOpen] = React.useState(Boolean(item.isActive));
|
||||
const subItems = getEnabledItems(item.items);
|
||||
const targetPath = item.redirectTo ?? item.path;
|
||||
|
||||
React.useEffect(() => {
|
||||
if (item.isActive) {
|
||||
setOpen(true);
|
||||
}
|
||||
}, [item.isActive]);
|
||||
|
||||
return (
|
||||
<Collapsible asChild open={open} onOpenChange={setOpen} className="group/collapsible">
|
||||
<SidebarMenuItem>
|
||||
{targetPath ? (
|
||||
<>
|
||||
<SidebarMenuButton asChild isActive={item.isActive} size="default" className="h-9 text-base sm:h-8 sm:text-sm">
|
||||
<SidebarLink to={targetPath} {...getUiIdAttributes(item)}>
|
||||
{item.icon !== undefined && <SidebarIcon className="h-5 w-5" item={item} />}
|
||||
<span>{item.title}</span>
|
||||
</SidebarLink>
|
||||
</SidebarMenuButton>
|
||||
<CollapsibleTrigger asChild>
|
||||
<SidebarMenuAction aria-label={i18nT("shared.toggleItem", { item: item.title })} className="data-[state=open]:rotate-90">
|
||||
<ChevronRight />
|
||||
</SidebarMenuAction>
|
||||
</CollapsibleTrigger>
|
||||
</>
|
||||
) : (
|
||||
<CollapsibleTrigger asChild>
|
||||
<SidebarMenuButton type="button" isActive={item.isActive} size="default" className="h-9 text-base sm:h-8 sm:text-sm" {...getUiIdAttributes(item)}>
|
||||
{item.icon !== undefined && <SidebarIcon className="h-5 w-5" item={item} />}
|
||||
<span>{item.title}</span>
|
||||
<ChevronRight className="ml-auto size-4 transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
|
||||
</SidebarMenuButton>
|
||||
</CollapsibleTrigger>
|
||||
)}
|
||||
<CollapsibleContent>
|
||||
<SidebarMenuSub>
|
||||
{subItems.map((subItem) => (
|
||||
<SidebarMenuSubItem key={subItem.id ?? subItem.title}>
|
||||
<SidebarMenuSubButton asChild isActive={subItem.isActive} className="h-9 text-base sm:h-8 sm:text-sm">
|
||||
<SidebarLink to={subItem.redirectTo ?? subItem.path} {...getUiIdAttributes(subItem)}>
|
||||
<span>{subItem.title}</span>
|
||||
</SidebarLink>
|
||||
</SidebarMenuSubButton>
|
||||
</SidebarMenuSubItem>
|
||||
))}
|
||||
</SidebarMenuSub>
|
||||
</CollapsibleContent>
|
||||
</SidebarMenuItem>
|
||||
</Collapsible>
|
||||
);
|
||||
}
|
||||
|
||||
export function NavSecondary({
|
||||
item,
|
||||
...props
|
||||
}: {
|
||||
// items: {
|
||||
// title: string;
|
||||
// url: string;
|
||||
// icon: LucideIcon;
|
||||
// }[];
|
||||
item: SidebarGroupDto;
|
||||
} & React.ComponentPropsWithoutRef<typeof SidebarGroup>) {
|
||||
return (
|
||||
<SidebarGroup {...props} {...getUiIdAttributes(item)}>
|
||||
<SidebarGroupContent>
|
||||
<SidebarMenu>
|
||||
{getEnabledItems(item.items).map((item) => {
|
||||
const enabledChildren = getEnabledItems(item.items);
|
||||
if (hasConfiguredChildren(item) && enabledChildren.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<React.Fragment key={item.id ?? item.title}>
|
||||
{enabledChildren.length === 0 ? (
|
||||
<SidebarMenuItem>
|
||||
<SidebarMenuButton asChild isActive={item.isActive} size="default" className="h-9 text-base sm:h-8 sm:text-sm">
|
||||
<SidebarLink to={item.redirectTo ?? item.path} {...getUiIdAttributes(item)}>
|
||||
{item.icon !== undefined && <SidebarIcon className="h-5 w-5" item={item} />}
|
||||
<span>{item.title}</span>
|
||||
</SidebarLink>
|
||||
</SidebarMenuButton>
|
||||
</SidebarMenuItem>
|
||||
) : (
|
||||
<NavSecondaryCollapsibleItem item={item} />
|
||||
)}
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</SidebarMenu>
|
||||
</SidebarGroupContent>
|
||||
</SidebarGroup>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
// // "use client";
|
||||
|
||||
import { BadgeCheck, ChevronsUpDown, CreditCard, LogOut } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Form, useFetcher, useLocation, useMatches, useParams, useSearchParams } from "react-router";
|
||||
import { Fragment } from "react";
|
||||
|
||||
import { Avatar, AvatarFallback, AvatarImage } from "~/components/ui/avatar";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu";
|
||||
import GearIcon from "~/components/ui/icons/GearIcon";
|
||||
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "~/components/ui/sidebar";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import UserDisplayUtils from "~/utils/app/UserDisplayUtils";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import AnalyticsHelper from "~/utils/helpers/AnalyticsHelper";
|
||||
import { DarkModeSvgs } from "~/components/ui/toggles/DarkModeToggle";
|
||||
import { DARK_MODE_IN_APP } from "~/application/Constants";
|
||||
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
|
||||
export function NavUser({
|
||||
user,
|
||||
layout,
|
||||
}: {
|
||||
user: { email: string; firstName: string | null; lastName: string | null; avatar: string | null; admin?: { userId: string } | null };
|
||||
layout: "app" | "admin" | "docs";
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { isMobile } = useSidebar();
|
||||
const { userSession } = useRootData();
|
||||
const appOrAdminData = useAppOrAdminData();
|
||||
const params = useParams();
|
||||
const fetcher = useFetcher();
|
||||
let location = useLocation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const rootData = useRootData();
|
||||
const matches = useMatches();
|
||||
|
||||
const onThemeToggle = async () => {
|
||||
const isDarkMode = userSession?.lightOrDarkMode === "dark";
|
||||
const form = new FormData();
|
||||
form.set("action", "toggleLightOrDarkMode");
|
||||
form.set("redirect", location.pathname + "?" + searchParams.toString());
|
||||
if (rootData.csrf) {
|
||||
form.set("csrf", rootData.csrf);
|
||||
}
|
||||
fetcher.submit(form, { method: "post", action: "/preferences", preventScrollReset: true });
|
||||
|
||||
const routeMatch = matches.find((m) => m.pathname == location.pathname);
|
||||
AnalyticsHelper.addEvent({
|
||||
url: location.pathname,
|
||||
route: routeMatch?.id,
|
||||
rootData,
|
||||
action: "toggleLightOrDarkMode",
|
||||
category: "user",
|
||||
label: "lightOrDarkMode",
|
||||
value: isDarkMode ? "light" : "dark",
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuButton size="lg" className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground">
|
||||
<Avatar className="h-8 w-8 rounded-lg">
|
||||
<AvatarImage src={user.avatar || ""} alt={UserDisplayUtils.fullName(user)} />
|
||||
<AvatarFallback className="rounded-lg">{UserDisplayUtils.avatarText(user)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-semibold">{UserDisplayUtils.fullName(user)}</span>
|
||||
<span className="truncate text-xs">{user.email}</span>
|
||||
</div>
|
||||
<ChevronsUpDown className="ml-auto size-4" />
|
||||
</SidebarMenuButton>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
|
||||
side={isMobile ? "bottom" : "right"}
|
||||
align="end"
|
||||
sideOffset={4}
|
||||
>
|
||||
<DropdownMenuLabel className="p-0 font-normal">
|
||||
<div className="flex items-center gap-2 px-1 py-1.5 text-left text-sm">
|
||||
<Avatar className="h-8 w-8 rounded-lg">
|
||||
<AvatarImage src={user.avatar || ""} alt={UserDisplayUtils.fullName(user)} />
|
||||
<AvatarFallback className="rounded-lg">{UserDisplayUtils.avatarText(user)}</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-semibold">{UserDisplayUtils.fullName(user)}</span>
|
||||
<span className="truncate text-xs">{user.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
{layout === "app" ? (
|
||||
<Fragment>
|
||||
<DropdownMenuGroup>
|
||||
<a href={!params.tenant ? "" : UrlUtils.currentTenantUrl(params, `settings/profile`)}>
|
||||
<DropdownMenuItem>
|
||||
<GearIcon className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.profile")}
|
||||
</DropdownMenuItem>
|
||||
</a>
|
||||
{getUserHasPermission(appOrAdminData, "app.settings.subscription.view") && (
|
||||
<a href={UrlUtils.currentTenantUrl(params, `settings/subscription`)}>
|
||||
<DropdownMenuItem>
|
||||
<CreditCard className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.subscription")}
|
||||
</DropdownMenuItem>
|
||||
</a>
|
||||
)}
|
||||
{getUserHasPermission(appOrAdminData, "app.settings.account.view") && (
|
||||
<a href={UrlUtils.currentTenantUrl(params, `settings/account`)}>
|
||||
<DropdownMenuItem>
|
||||
<BadgeCheck className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.tenant")}
|
||||
</DropdownMenuItem>
|
||||
</a>
|
||||
)}
|
||||
|
||||
{/* <DropdownMenuItem>
|
||||
<Bell className="mr-2 h-4 w-4" />
|
||||
Notifications
|
||||
</DropdownMenuItem> */}
|
||||
</DropdownMenuGroup>
|
||||
</Fragment>
|
||||
) : layout === "admin" ? (
|
||||
<Fragment>
|
||||
<DropdownMenuGroup>
|
||||
<a href={adminPath("settings/profile", { mode: "host-aware" })}>
|
||||
<DropdownMenuItem>
|
||||
<GearIcon className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.profile")}
|
||||
</DropdownMenuItem>
|
||||
</a>
|
||||
</DropdownMenuGroup>
|
||||
</Fragment>
|
||||
) : null}
|
||||
|
||||
{DARK_MODE_IN_APP && (
|
||||
<DropdownMenuItem className="gap-2" onClick={onThemeToggle}>
|
||||
<DarkModeSvgs className="mr-2 size-4" withLabel={false} />
|
||||
{userSession?.lightOrDarkMode === "dark" ? t("settings.profile.session.switchToLightMode") : t("settings.profile.session.switchToDarkMode")}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<Form method="post" action="/logout">
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<DropdownMenuItem asChild>
|
||||
<button type="submit" className="w-full">
|
||||
<LogOut className="mr-2 h-4 w-4" />
|
||||
{t("app.navbar.signOut")}
|
||||
</button>
|
||||
</DropdownMenuItem>
|
||||
</Form>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
import * as React from "react";
|
||||
import { ChevronsUpDown, Plus } from "~/components/ui/icons/vendor";
|
||||
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "~/components/ui/dropdown-menu";
|
||||
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "~/components/ui/sidebar";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useAppData } from "~/utils/data/useAppData";
|
||||
import { appPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import { absolutePublicAppPath, isAbsoluteHttpUrl } from "~/utils/app/CrossHostUrls";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import { TenantSimple } from "~/utils/db/tenants.db.server";
|
||||
import clsx from "clsx";
|
||||
|
||||
|
||||
export function TeamSwitcher({ tenants, size = "md" }: { tenants: TenantSimple[]; size?: "sm" | "md" }) {
|
||||
const { t } = useTranslation();
|
||||
const { isMobile } = useSidebar();
|
||||
|
||||
const appData = useAppData();
|
||||
const rootData = useRootData();
|
||||
const canCreateAccount = true; // appData.isSuperUser;
|
||||
|
||||
const [activeTenant] = React.useState(appData?.currentTenant);
|
||||
|
||||
let activeTenantDescription = getTenantDescription({
|
||||
subscription: appData.mySubscription,
|
||||
types: appData.currentTenant.types,
|
||||
t,
|
||||
});
|
||||
const newAccountPath = absolutePublicAppPath(rootData.routing, "new-account");
|
||||
|
||||
return (
|
||||
<SidebarMenu>
|
||||
<SidebarMenuItem>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<SidebarMenuButton
|
||||
size={size === "md" ? "lg" : "default"}
|
||||
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground h-11 select-none"
|
||||
>
|
||||
<div
|
||||
className={clsx(
|
||||
"flex aspect-square items-center justify-center rounded-lg",
|
||||
size === "sm" && "size-6",
|
||||
size === "md" && "text-foreground size-8"
|
||||
)}
|
||||
>
|
||||
{/* <activeTeam.logo className="size-4" /> */}
|
||||
{activeTenant.icon ? (
|
||||
<img className="size-6 shrink-0 rounded-md" src={activeTenant.icon} alt={activeTenant.name} />
|
||||
) : (
|
||||
<span className="bg-primary inline-flex size-6 shrink-0 items-center justify-center rounded-md">
|
||||
<span className="text-primary-foreground text-xs leading-none font-medium uppercase">{activeTenant.name.substring(0, 1)}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="grid flex-1 text-left text-sm leading-tight">
|
||||
<span className="truncate font-semibold">{activeTenant.name}</span>
|
||||
{size === "md" && <span className="truncate text-xs">{activeTenantDescription}</span>}
|
||||
</div>
|
||||
<ChevronsUpDown className="ml-auto" />
|
||||
</SidebarMenuButton>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent
|
||||
className="bg-background w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
|
||||
align="start"
|
||||
side={isMobile ? "bottom" : "right"}
|
||||
sideOffset={4}
|
||||
>
|
||||
<DropdownMenuLabel className="text-xs">{t("models.tenant.plural")}</DropdownMenuLabel>
|
||||
{tenants.map((tenant) => (
|
||||
<DropdownMenuItem
|
||||
key={tenant.name}
|
||||
asChild
|
||||
>
|
||||
<a href={appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" })} className="flex justify-between gap-2 truncate p-2">
|
||||
<div className="flex items-center gap-2 truncate">
|
||||
<div className="bg-background flex size-7 shrink-0 items-center justify-center overflow-hidden rounded-sm border">
|
||||
{/* <team.logo className="size-4 shrink-0" /> */}
|
||||
|
||||
{tenant.icon ? (
|
||||
<img className="size-7 shrink-0" src={tenant.icon} alt={tenant.name} />
|
||||
) : (
|
||||
<span className="inline-flex size-7 shrink-0 items-center justify-center rounded-md">
|
||||
<span className="text-xs leading-none font-medium uppercase">{tenant.name.substring(0, 1)}</span>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="truncate">
|
||||
<div className="text-foreground truncate text-sm">{tenant.name} </div>
|
||||
{/* {tenant.types.length > 0 && (
|
||||
<span className=" truncate text-xs">{getTenantDescription({ subscription: null, types: tenant.types, t })}</span>
|
||||
)} */}
|
||||
</div>
|
||||
</div>
|
||||
{/* <div className="shrink-0">
|
||||
<Button variant="ghost" size="icon">
|
||||
<Link to={appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" })} target="_blank" onClick={(e) => e.stopPropagation()}>
|
||||
<ExternalLinkIcon className="size-3" />
|
||||
</Link>
|
||||
</Button>
|
||||
</div> */}
|
||||
</a>
|
||||
{/* <DropdownMenuShortcut>⌘{index + 1}</DropdownMenuShortcut> */}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
{canCreateAccount && (
|
||||
<React.Fragment>
|
||||
<DropdownMenuSeparator />
|
||||
{isAbsoluteHttpUrl(newAccountPath) ? (
|
||||
<a href={newAccountPath}>
|
||||
<CreateAccountMenuItem label={t("app.tenants.create.title")} />
|
||||
</a>
|
||||
) : (
|
||||
<a href={newAccountPath}>
|
||||
<CreateAccountMenuItem label={t("app.tenants.create.title")} />
|
||||
</a>
|
||||
)}
|
||||
</React.Fragment>
|
||||
)}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</SidebarMenuItem>
|
||||
</SidebarMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function CreateAccountMenuItem({ label }: { label: string }) {
|
||||
return (
|
||||
<DropdownMenuItem className="gap-2 p-2">
|
||||
<div className="bg-background flex size-6 items-center justify-center rounded-md border">
|
||||
<Plus className="size-4" />
|
||||
</div>
|
||||
<div className="font-medium">{label}</div>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
function getTenantDescription({
|
||||
subscription,
|
||||
types,
|
||||
t,
|
||||
}: {
|
||||
subscription: {
|
||||
products: { subscriptionProduct: { title: string } }[];
|
||||
} | null;
|
||||
types: { title: string }[];
|
||||
t: any;
|
||||
}) {
|
||||
void subscription;
|
||||
void types;
|
||||
void t;
|
||||
return "";
|
||||
// let activeTenantDescription = subscription?.products.length
|
||||
// ? t(subscription.products.find((f) => f)?.subscriptionProduct.title || "")
|
||||
// : t("settings.subscription.noSubscription");
|
||||
// if (!subscription || !subscription.products.length) {
|
||||
// // if (types.length > 0) {
|
||||
// // activeTenantDescription = t(types[0].title);
|
||||
// // }
|
||||
// }
|
||||
// return activeTenantDescription;
|
||||
}
|
||||
Reference in new issue
Block a user