Track HiveGrid Cloud planning reference

This commit is contained in:
david committed 2026-06-26 20:48:01 +02:00
1 parent b3d5ea6764
commit e341c5938a
5784 files changed
+1104929 -3

No files matched your search

@@ -0,0 +1,67 @@
import { useParams } from "react-router";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import AddFeedbackButton from "./buttons/AddFeedbackButton";
import ChatSupportButton from "./buttons/ChatSupportButton";
import CurrentSubscriptionButton from "./buttons/CurrentSubscriptionButton";
import OnboardingButton from "./buttons/OnboardingButton";
import ProfileButton from "./buttons/ProfileButton";
import QuickActionsButton from "./buttons/QuickActionsButton";
import SearchButton from "./buttons/SearchButton";
import NotificationsButton from "./buttons/NotificationsButton";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
export default function NavBar({
layout,
title,
buttons,
onOpenCommandPalette,
onOpenOnboardingModal,
children,
}: {
layout?: string;
title?: string;
buttons: {
mySubscription: boolean;
feedback: boolean;
chatSupport: boolean;
quickActions: boolean;
search: boolean;
notifications: boolean;
onboarding: boolean;
userProfile: boolean;
};
onOpenCommandPalette: () => void;
onOpenOnboardingModal: () => void;
children?: React.ReactNode;
}) {
const appOrAdminData = useAppOrAdminData();
const params = useParams();
const notificationsPath =
layout === "admin" ? adminPath("notifications", { mode: "host-aware" }) : params.tenant ? appPath({ tenantSlug: params.tenant, path: "notifications", mode: "host-aware" }) : "/notifications";
return (
<div className="flex flex-1 justify-between space-x-2">
<div className="flex flex-1 items-center">{title && <div className="font-extrabold">{title}</div>}</div>
<div className="flex items-center space-x-2 md:ml-6">
{/* {layout === "app" && (
<CreditsRemaining
feature={appOrAdminData.featureSyncs}
redirectTo={appOrAdminData.currentTenant ? `/${appOrAdminData.currentTenant.slug}/settings/subscription` : "/settings/subscription"}
/>
)} */}
{buttons.onboarding && appOrAdminData?.onboardingSession && (
<OnboardingButton item={appOrAdminData?.onboardingSession} onClick={onOpenOnboardingModal} />
)}
{layout === "app" && buttons.mySubscription && <CurrentSubscriptionButton />}
{/* <LocaleSelector /> */}
{buttons.notifications && appOrAdminData?.user && <NotificationsButton to={notificationsPath} />}
{buttons.search && <SearchButton onClick={onOpenCommandPalette} />}
{layout === "app" && buttons.feedback && <AddFeedbackButton />}
{layout === "app" && buttons.chatSupport && <ChatSupportButton />}
{layout === "app" && buttons.quickActions && <QuickActionsButton entities={appOrAdminData?.entities?.filter((f) => f.showInSidebar)} />}
{/* {(layout === "app" || layout === "admin") && <ThemeSelector variant="secondary" />} */}
{(layout === "app" || layout === "admin") && buttons.userProfile && <ProfileButton user={appOrAdminData?.user} layout={layout} />}
{children}
</div>
</div>
);
}
@@ -0,0 +1,90 @@
import { useFetcher, useLocation, useParams } from "react-router";
import { Fragment, useEffect, useState } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import StarsIconFilled from "~/components/ui/icons/StarsIconFilled";
import InputText from "~/components/ui/input/InputText";
import Modal from "~/components/ui/modals/Modal";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useRootData } from "~/utils/data/useRootData";
export default function AddFeedbackButton() {
const [isOpen, setIsOpen] = useState(false);
const { t } = useTranslation();
return (
<Fragment>
<div className="relative hidden sm:inline-flex">
<div className="relative">
<div className="inline-flex divide-x divide-gray-300 rounded-sm shadow-none">
<div className="relative z-0 inline-flex rounded-full text-sm shadow-none">
<button
onClick={() => setIsOpen(!isOpen)}
type="button"
className="text-muted-foreground bg-secondary hover:bg-secondary/90 border-border relative inline-flex items-center rounded-full border p-2 font-medium shadow-inner focus:z-10 focus:outline-hidden focus:ring-2 focus:ring-offset-2"
aria-haspopup="listbox"
aria-expanded="true"
aria-label={t("feedback.title")}
>
<span className="sr-only">{t("feedback.title")}</span>
<StarsIconFilled className="h-5 w-5 p-0.5" />
</button>
</div>
</div>
</div>
</div>
<Modal open={isOpen} setOpen={setIsOpen} size="sm">
<FeedbackForm onClose={() => setIsOpen(false)} />
</Modal>
</Fragment>
);
}
function FeedbackForm({ onClose }: { onClose: () => void }) {
const { t } = useTranslation();
const params = useParams();
const appOrAdminData = useAppOrAdminData();
const { csrf } = useRootData();
const fetcher = useFetcher<{ success?: string; error?: string }>();
const location = useLocation();
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: 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="csrf" value={csrf ?? ""} 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 font-medium leading-6">{t("feedback.title")}</h3>
<p className="text-muted-foreground text-sm">{t("feedback.description")}</p>
<InputText name="message" title="feedback.message" withLabel={false} 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,49 @@
import clsx from "clsx";
import { useTranslation } from "react-i18next";
import { useState } from "react";
import { MessageCircleIcon } from "~/components/ui/icons/vendor";
export default function ChatSupportButton() {
const [isOpen, setIsOpen] = useState(false);
const { t } = useTranslation();
function onClick() {
try {
if (!isOpen) {
// @ts-ignore
$crisp?.push(["do", "chat:open"]);
// @ts-ignore
$crisp?.push(["do", "chat:show"]);
setIsOpen(true);
} else {
// @ts-ignore
$crisp?.push(["do", "chat:hide"]);
setIsOpen(false);
}
} catch (e) {
// ignore
}
}
return (
<div className="relative hidden sm:inline-flex">
<div className="relative">
<div className="inline-flex divide-x divide-gray-300 rounded-sm shadow-none">
<div className="relative z-0 inline-flex rounded-full text-sm shadow-none">
<button
onClick={onClick}
type="button"
className={clsx(
"text-muted-foreground bg-secondary hover:bg-secondary/90 border-border relative inline-flex items-center rounded-full border p-2 font-medium shadow-inner focus:z-10 focus:outline-hidden focus:ring-2 focus:ring-offset-2"
)}
aria-haspopup="listbox"
aria-expanded="true"
aria-label={t("shared.openSupportChat")}
>
<span className="sr-only">{t("shared.openSupportChat")}</span>
<MessageCircleIcon className="h-5 w-5" aria-hidden="true" />
</button>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,53 @@
import { useTranslation } from "react-i18next";
import { useAppData } from "~/utils/data/useAppData";
import { Link, useParams } from "react-router";
import clsx from "~/utils/shared/ClassesUtils";
import { subscriptionCheckoutPath } from "~/utils/app/SubscriptionUrlUtils";
import { SparklesIcon } from "~/components/ui/icons/vendor";
export default function CurrentSubscriptionButton() {
const params = useParams();
const { t } = useTranslation();
const appData = useAppData();
function getSubscriptionProducts() {
return appData.mySubscription?.products.map((f) => t(f.subscriptionProduct.title)) ?? [];
}
function hasSubscription() {
return getSubscriptionProducts().length > 0;
}
return (
<>
{!hasSubscription() && (
<div className="hidden divide-x divide-gray-300 rounded-sm shadow-none lg:inline-flex">
<div className="relative z-0 inline-flex rounded-full text-xs shadow-none sm:text-sm">
<Link
to={!params.tenant ? "" : subscriptionCheckoutPath(params.tenant)}
className={clsx(
"text-muted-foreground bg-secondary border-border relative inline-flex items-center space-x-1 rounded-md border p-2 font-medium shadow-inner hover:bg-teal-50 hover:text-teal-800 focus:z-10 focus:bg-teal-100 focus:text-teal-900 focus:outline-hidden",
hasSubscription() &&
"flex space-x-2 px-3 text-teal-900 hover:bg-teal-50 hover:text-teal-800 focus:z-10 focus:bg-teal-100 focus:text-teal-900 focus:outline-hidden",
!hasSubscription() &&
" border-yellow-200 bg-yellow-50 text-yellow-800 hover:bg-yellow-100 hover:text-yellow-900 focus:z-10 focus:bg-yellow-100 focus:text-yellow-900 focus:outline-hidden"
)}
aria-haspopup="listbox"
aria-expanded="true"
aria-labelledby="listbox-label"
>
{hasSubscription() ? (
<div>
<span>{getSubscriptionProducts().join(", ")} </span>
</div>
) : (
<div>
<span>{t("pricing.subscribe")} </span>
</div>
)}
<SparklesIcon className="h-4 w-4" />
</Link>
</div>
</div>
)}
</>
);
}
@@ -0,0 +1,93 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { UI_ACTION_IDS } from "~/application/ui/uiRegistry";
import NotificationsButton from "./NotificationsButton";
import ProfileButton from "./ProfileButton";
import SearchButton from "./SearchButton";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (value: string) => value }),
}));
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
Form: ({ children, ...props }: React.ComponentProps<"form">) => <form {...props}>{children}</form>,
};
});
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => (globalThis as any).__layoutButtonsRootData,
}));
vi.mock("~/utils/data/useAppOrAdminData", () => ({
useAppOrAdminData: () => ({ permissions: [] }),
}));
describe("layout button UI IDs", () => {
beforeEach(() => {
(globalThis as any).__layoutButtonsRootData = { appConfiguration: { app: { features: { tenantApiKeys: false } } } };
});
it("renders SearchButton with a stable action ID", () => {
render(<SearchButton onClick={vi.fn()} />);
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.search}"]`)).toBeInTheDocument();
});
it("renders NotificationsButton with a stable action ID", () => {
render(
<MemoryRouter>
<NotificationsButton unseenCount={2} to="/acme/notifications" />
</MemoryRouter>
);
expect(screen.getByLabelText("shell.notifications.ariaLabel")).toHaveAttribute("data-ui-id", UI_ACTION_IDS.notifications);
expect(screen.getByLabelText("shell.notifications.ariaLabel")).toHaveAttribute("href", "/acme/notifications");
});
it("renders ProfileButton with stable action and menu IDs", () => {
render(
<MemoryRouter>
<ProfileButton user={{ email: "user@example.com", firstName: "Ada", lastName: "Lovelace", avatar: null }} layout="admin" />
</MemoryRouter>
);
expect(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.profile}.menu"]`)).toBeInTheDocument();
expect(screen.getByLabelText("shell.profile.userMenu")).toHaveAttribute("data-ui-id", UI_ACTION_IDS.profile);
});
it("uses default tenant settings links in the public profile menu when available", () => {
(globalThis as any).__layoutButtonsRootData = {
...(globalThis as any).__layoutButtonsRootData,
currentTenant: { id: "tenant_1", slug: "acme" },
};
render(
<MemoryRouter>
<ProfileButton user={{ email: "user@example.com", firstName: "Ada", lastName: "Lovelace", avatar: null }} layout="/" />
</MemoryRouter>
);
fireEvent.click(screen.getByLabelText("shell.profile.userMenu"));
expect(screen.getByRole("menuitem", { name: "app.navbar.profile" })).toHaveAttribute("href", "/acme/settings/profile");
expect(screen.getByRole("menuitem", { name: "app.navbar.subscription" })).toHaveAttribute("href", "/acme/settings/subscription");
});
it("localizes the public admin menu link", () => {
render(
<MemoryRouter>
<ProfileButton user={{ email: "admin@example.com", firstName: "Ada", lastName: "Lovelace", avatar: null, admin: { userId: "user_1" } }} layout="/" />
</MemoryRouter>
);
fireEvent.click(screen.getByLabelText("shell.profile.userMenu"));
expect(screen.getByRole("menuitem", { name: "shared.admin" })).toHaveAttribute("href", "/dashboard");
expect(screen.queryByRole("menuitem", { name: "Admin" })).not.toBeInTheDocument();
});
});
@@ -0,0 +1,60 @@
import clsx from "clsx";
import { useTranslation } from "react-i18next";
import { UI_ACTION_IDS } from "~/application/ui/uiRegistry";
import { BellIcon } from "~/components/ui/icons/vendor";
interface Props {
unseenCount?: number;
to: string;
}
export default function NotificationsButton({ unseenCount, to }: Props) {
const { t } = useTranslation();
return (
<div className="relative">
<div className="inline-flex divide-x divide-gray-300 rounded-sm shadow-none">
<a
href={to}
data-ui-id={UI_ACTION_IDS.notifications}
aria-label={t("shell.notifications.ariaLabel")}
className={clsx(
"text-muted-foreground bg-secondary hover:bg-secondary/90 border-border relative inline-flex items-center rounded-full border p-2 font-medium shadow-inner focus-visible:z-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
)}
>
<span className="relative inline-block h-5 w-5 overflow-hidden rounded-full">
<BellIcon className="h-5 w-5" />
</span>
{unseenCount?.toString() !== "0" && (
<span className="absolute inset-0 -mr-6 object-right-top">
<div className="inline-flex items-center rounded-full border-2 border-white bg-red-500 px-1.5 py-0.5 text-xs font-semibold leading-4 text-white">
{unseenCount}
</div>
</span>
)}
</a>
</div>
</div>
);
// <div className="w-full flex md:ml-0">
// <div className="align-baseline w-full text-slate-200 pl-1">
// <div className="w-full">
// <label htmlFor="command-palette" className="sr-only">
// {t("shared.commandPalette")}
// </label>
// <div className="relative text-muted-foreground hover:text-muted-foreground truncate">
// <button
// type="button"
// onClick={onOpenCommandPalette}
// className="flex space-x-2 text-left w-full pl-3 pr-3 py-1.5 text-sm sm:py-2 border border-border rounded-md leading-5 bg-secondary text-muted-foreground focus:outline-hidden hover:ring-0 hover:placeholder-gray-500 hover:text-muted-foreground truncate"
// >
// <div className="font-medium hidden lg:block">⌘K</div>
// <div className="hidden lg:block truncate">{t("shared.commandPalette")}</div>
// <div className="lg:hidden">{t("shared.search")}</div>
// </button>
// </div>
// </div>
// </div>
// </div>
}
@@ -0,0 +1,26 @@
import clsx from "~/utils/shared/ClassesUtils";
import { OnboardingSessionWithDetails } from "~/modules/onboarding/db/onboardingSessions.db.server";
import BycicleIcon from "~/components/ui/icons/onboardings/BycicleIcon";
export default function OnboardingButton({ item, onClick }: { item: OnboardingSessionWithDetails; onClick?: () => void }) {
return (
<div className="inline-flex divide-x divide-theme-300 rounded-full shadow-none sm:rounded-md">
<div className="relative z-0 inline-flex rounded-full text-xs shadow-none sm:text-sm">
<button
type="button"
onClick={onClick}
className={clsx(
"relative inline-flex items-center rounded-full border border-theme-100 bg-theme-50 p-2 font-medium text-theme-500 shadow-inner hover:bg-theme-100 hover:text-theme-800 focus:z-10 focus:bg-theme-100 focus:text-theme-900 focus:outline-hidden sm:rounded-md",
"flex px-3 text-theme-900 hover:bg-theme-200 hover:text-theme-800 focus:z-10 focus:bg-theme-100 focus:text-theme-900 focus:outline-hidden"
)}
aria-haspopup="listbox"
aria-expanded="true"
aria-label={item.onboarding.title}
>
<div className="hidden lg:block">{item.onboarding.title}</div>
<BycicleIcon className={clsx("h-5 w-5", item.onboarding.title.length > 0 && "lg:ml-2")} />
</button>
</div>
</div>
);
}
@@ -0,0 +1,15 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
describe("ProfileButton route fallbacks", () => {
it("does not emit root-relative tenant settings fallbacks from the public header menu", () => {
const source = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/components/layouts/buttons/ProfileButton.tsx"), "utf8");
expect(source).not.toContain('?? "/settings"');
expect(source).not.toContain('?? "/settings/subscription"');
expect(source).toContain('publicHeaderAdminPath("dashboard")');
expect(source).toContain('defaultTenantPath("settings/profile") ?? publicHeaderAdminPath("settings/profile")');
expect(source).not.toContain('defaultTenantPath("settings/profile") ?? adminShellPath("settings/profile")');
});
});
@@ -0,0 +1,259 @@
import { Form, Link, useParams } from "react-router";
import { useTranslation } from "react-i18next";
import { Transition } from "@headlessui/react";
import { Fragment, useState } from "react";
import clsx from "~/utils/shared/ClassesUtils";
import { useOuterClick } from "~/utils/shared/KeypressUtils";
import UserDisplayUtils from "~/utils/app/UserDisplayUtils";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { useRootData } from "~/utils/data/useRootData";
import { UI_ACTION_IDS } from "~/application/ui/uiRegistry";
import { absoluteAdminPath } from "~/utils/app/CrossHostUrls";
import { UserIcon } from "~/components/ui/icons/vendor";
interface Props {
user: { email: string; firstName: string | null; lastName: string | null; avatar: string | null; admin?: { userId: string } | null } | null | undefined;
layout?: "/" | "app" | "admin" | "docs";
items?: { title: string; path: string; hidden?: boolean; onClick?: () => void }[];
}
export default function ProfileButton({ user, layout, items }: Props) {
const params = useParams();
const { t } = useTranslation();
const rootData = useRootData();
const appOrAdminData = useAppOrAdminData();
const tenantPath = (path?: string) => (params.tenant ? appPath({ tenantSlug: params.tenant, path, mode: "host-aware" }) : "");
const defaultTenantPath = (path?: string) =>
rootData.currentTenant?.slug ? appPath({ tenantSlug: rootData.currentTenant.slug, path, mode: "host-aware" }) : undefined;
const adminShellPath = (path?: string) => adminPath(path, { mode: "host-aware" });
const publicHeaderAdminPath = (path?: string) => absoluteAdminPath(rootData.routing, path);
const [opened, setOpened] = useState(false);
function closeDropdownUser() {
setOpened(false);
}
// function signOut() {
// submit(null, { method: "post", action: "/logout" });
// }
const clickOutside = useOuterClick(() => setOpened(false));
return (
<div ref={clickOutside} className="relative" data-ui-id={`${UI_ACTION_IDS.profile}.menu`}>
<div className="inline-flex divide-x divide-gray-300 rounded-sm shadow-none">
<button
onClick={() => setOpened(!opened)}
data-ui-id={UI_ACTION_IDS.profile}
className={clsx(
"bg-background text-muted-foreground hover:bg-secondary border-border relative inline-flex items-center rounded-full border font-medium shadow-inner focus-visible:z-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
!user?.avatar && "p-2",
user?.avatar && "p-1"
)}
id="user-menu"
aria-label={t("shell.profile.userMenu")}
aria-haspopup="true"
>
{(() => {
if (user?.avatar) {
return <img className="inline-flex h-8 w-8 items-center justify-center rounded-full bg-slate-800" src={user.avatar} alt={t("models.user.avatarAlt")} />;
} else {
return (
<span className="inline-block h-5 w-5 overflow-hidden rounded-full">
<UserIcon className="h-full w-full" />
</span>
);
}
})()}
</button>
</div>
<Transition
as={Fragment}
show={opened}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<div className="divide-border border-border absolute right-0 z-40 mt-2 w-64 origin-top-right divide-y overflow-hidden rounded-sm border shadow-lg focus:outline-hidden">
<div className="shadow-2xs bg-background rounded-sm py-1" role="menu" aria-orientation="vertical" aria-labelledby="user-menu">
<div className="text-muted-foreground group flex items-center truncate px-4 py-2 text-sm transition duration-150 ease-in-out" role="menuitem">
<div className="flex flex-col space-y-1 truncate">
<div className="font-medium">{UserDisplayUtils.profileName(user)}</div>
<div className="truncate font-bold">{user?.email}</div>
</div>
</div>
<div className="border-border border-t"></div>
{layout === "app" ? (
<>
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/profile")}
>
{t("app.navbar.profile")}
</Link>
{getUserHasPermission(appOrAdminData, "app.settings.members.view") && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/members")}
>
{t("app.navbar.members")}
</Link>
)}
{getUserHasPermission(appOrAdminData, "app.settings.subscription.view") && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/subscription")}
>
{t("app.navbar.subscription")}
</Link>
)}
{getUserHasPermission(appOrAdminData, "app.settings.account.view") && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/account")}
>
{t("app.navbar.tenant")}
</Link>
)}
{/* {getUserHasPermission(appOrAdminData, "app.settings.roles.view") && (
<Link
className="block px-4 py-2 text-sm transition duration-150 ease-in-out hover:bg-secondary"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/roles-and-permissions")}
>
{t("models.role.plural")}
</Link>
)} */}
{/* <Link
className="block px-4 py-2 text-sm transition duration-150 ease-in-out hover:bg-secondary"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/groups")}
>
{t("models.group.plural")}
</Link> */}
{rootData.appConfiguration.app.features.tenantApiKeys && getUserHasPermission(appOrAdminData, "app.settings.apiKeys.view") && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/api")}
>
{t("models.apiKey.plural")}
</Link>
)}
{getUserHasPermission(appOrAdminData, "app.settings.auditTrails.view") && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/logs")}
>
{t("models.log.plural")}
</Link>
)}
<div className="border-border mt-1 border-t"></div>
</>
) : layout === "admin" ? (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={!user ? "" : adminShellPath("settings/profile")}
>
{t("app.navbar.profile")}
</Link>
) : layout === "/" ? (
<Fragment>
{user?.admin && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={publicHeaderAdminPath("dashboard")}
>
{t("shared.admin")}
</Link>
)}
{(defaultTenantPath("settings/profile") || user?.admin) && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={defaultTenantPath("settings/profile") ?? publicHeaderAdminPath("settings/profile")}
>
{t("app.navbar.profile")}
</Link>
)}
{defaultTenantPath("settings/subscription") && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={closeDropdownUser}
to={defaultTenantPath("settings/subscription")!}
>
{t("app.navbar.subscription")}
</Link>
)}
</Fragment>
) : items ? (
items.map((item) => (
<Link
key={item.path}
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
role="menuitem"
onClick={() => {
if (item.onClick) {
item.onClick();
}
closeDropdownUser();
}}
to={item.path}
>
{item.title}
</Link>
))
) : null}
{!items && (
<Form method="post" action="/logout">
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
<button
type="submit"
className="hover:bg-secondary block w-full px-4 py-2 text-left text-sm transition duration-150 ease-in-out focus:outline-hidden"
role="menuitem"
>
{t("app.navbar.signOut")}
</button>
</Form>
)}
</div>
</div>
</Transition>
</div>
);
}
@@ -0,0 +1,12 @@
import { describe, expect, it } from "vitest";
import { quickActionEntityPath } from "./QuickActionsButton";
describe("quickActionEntityPath", () => {
it("keeps create links inside the active group route", () => {
expect(quickActionEntityPath({ tenant: "acme", group: "sales" }, "contacts")).toBe("/acme/g/sales/contacts/new");
});
it("uses the tenant entity route outside groups", () => {
expect(quickActionEntityPath({ tenant: "acme" }, "contacts")).toBe("/acme/contacts/new");
});
});
@@ -0,0 +1,90 @@
import { Link, useParams } from "react-router";
import { useTranslation } from "react-i18next";
import { Transition } from "@headlessui/react";
import { Fragment, useState } from "react";
import { useOuterClick } from "~/utils/shared/KeypressUtils";
import { useAppData } from "~/utils/data/useAppData";
import UrlUtils from "~/utils/app/UrlUtils";
import { EntitySimple } from "~/utils/db/entities/entities.db.server";
import { getEntityPermission, getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { PlusIcon } from "~/components/ui/icons/vendor";
interface Props {
entities: EntitySimple[];
className?: string;
}
export function quickActionEntityPath(params: { tenant?: string; group?: string }, entitySlug: string) {
const path = params.group ? `g/${params.group}/${entitySlug}/new` : `${entitySlug}/new`;
return UrlUtils.currentTenantUrl(params, path);
}
export default function QuickActionsButton({ entities, className }: Props) {
const { t } = useTranslation();
const params = useParams();
const appData = useAppData();
const [opened, setOpened] = useState(false);
const creatableEntities = entities.filter((entity) => getUserHasPermission(appData, getEntityPermission(entity, "create")));
const hasQuickActions = creatableEntities.length > 0;
const clickOutside = useOuterClick(() => setOpened(false));
return (
<span className={className} ref={clickOutside}>
{hasQuickActions && (
<div className="relative">
<div className="inline-flex divide-x divide-gray-300 rounded-sm shadow-none">
<div className="relative z-0 inline-flex rounded-full text-sm shadow-none">
<button
onClick={() => setOpened(!opened)}
type="button"
className="text-muted-foreground bg-secondary hover:bg-secondary/90 border-border relative inline-flex items-center rounded-full border p-2 font-medium shadow-inner focus:z-10 focus:outline-hidden focus:ring-2 focus:ring-offset-2"
aria-haspopup="listbox"
aria-expanded="true"
aria-label={t("shared.new")}
>
<span className="sr-only">{t("shared.new")}</span>
<PlusIcon className="h-5 w-5" />
</button>
</div>
</div>
<Transition
as={Fragment}
show={opened}
enter="transition ease-out duration-100"
enterFrom="transform opacity-0 scale-95"
enterTo="transform opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="transform opacity-100 scale-100"
leaveTo="transform opacity-0 scale-95"
>
<ul
className="divide-border bg-background absolute right-0 z-40 mt-2 w-72 origin-top-right divide-y overflow-hidden rounded-sm shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-hidden"
tabIndex={-1}
aria-labelledby="listbox-label"
>
{creatableEntities.map((entity) => {
return (
<li key={entity.name} className="text-foreground relative cursor-default select-none text-sm" id="listbox-option-0">
<Link
to={quickActionEntityPath(params, entity.slug)}
onClick={() => setOpened(false)}
className="hover:bg-secondary flex flex-col p-4"
>
<div className="flex justify-between">
<p className="font-semibold">
{t("shared.new")} {t(entity.title)}
</p>
</div>
</Link>
</li>
);
})}
</ul>
</Transition>
</div>
)}
</span>
);
}
@@ -0,0 +1,52 @@
import clsx from "clsx";
import { useTranslation } from "react-i18next";
import { UI_ACTION_IDS } from "~/application/ui/uiRegistry";
import { SearchIcon } from "~/components/ui/icons/vendor";
interface Props {
onClick: () => void;
}
export default function SearchButton({ onClick }: Props) {
const { t } = useTranslation();
return (
<div className="relative">
<div className="inline-flex divide-x divide-gray-300 rounded-sm shadow-none">
<button
type="button"
onClick={onClick}
data-ui-id={UI_ACTION_IDS.search}
aria-label={t("shared.search")}
className={clsx(
"text-muted-foreground bg-secondary hover:bg-secondary/90 border-border relative inline-flex items-center rounded-full border p-2 font-medium shadow-inner focus-visible:z-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
)}
>
<span className="inline-block h-5 w-5 overflow-hidden rounded-full">
<SearchIcon className="h-5 w-5" aria-hidden="true" />
</span>
</button>
</div>
</div>
);
// <div className="w-full flex md:ml-0">
// <div className="align-baseline w-full text-slate-200 pl-1">
// <div className="w-full">
// <label htmlFor="command-palette" className="sr-only">
// {t("shared.commandPalette")}
// </label>
// <div className="relative text-muted-foreground hover:text-muted-foreground truncate">
// <button
// type="button"
// onClick={onOpenCommandPalette}
// className="flex space-x-2 text-left w-full pl-3 pr-3 py-1.5 text-sm sm:py-2 border border-border rounded-md leading-5 bg-secondary text-muted-foreground focus:outline-hidden hover:ring-0 hover:placeholder-gray-500 hover:text-muted-foreground truncate"
// >
// <div className="font-medium hidden lg:block">⌘K</div>
// <div className="hidden lg:block truncate">{t("shared.commandPalette")}</div>
// <div className="lg:hidden">{t("shared.search")}</div>
// </button>
// </div>
// </div>
// </div>
// </div>
}
@@ -0,0 +1,35 @@
import { Link } from "react-router";
import { useTranslation } from "react-i18next";
import clsx from "~/utils/shared/ClassesUtils";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { SparklesIcon } from "~/components/ui/icons/vendor";
export default function UpdateAvailableButton({ hasUpdate }: { hasUpdate: boolean }) {
const { t } = useTranslation();
return (
<>
{hasUpdate && (
<div className="hidden divide-x divide-gray-300 rounded-sm shadow-none lg:inline-flex">
<div className="relative z-0 inline-flex rounded-full text-xs shadow-none sm:text-sm">
<Link
to={adminPath("settings", { mode: "host-aware" })}
className={clsx(
"text-muted-foreground bg-secondary border-border relative inline-flex items-center space-x-1 rounded-md border p-2 font-medium shadow-inner hover:bg-teal-50 hover:text-teal-800 focus:z-10 focus:bg-teal-100 focus:text-teal-900 focus:outline-hidden",
" border-green-200 bg-green-50 text-green-800 hover:bg-green-100 hover:text-green-900 focus:z-10 focus:bg-green-100 focus:text-green-900 focus:outline-hidden"
)}
aria-haspopup="listbox"
aria-expanded="true"
aria-labelledby="listbox-label"
>
<div>
<span>{t("shell.updateAvailable")}</span>
</div>
<SparklesIcon className="h-4 w-4" />
</Link>
</div>
</div>
)}
</>
);
}
@@ -0,0 +1,19 @@
import { sanitizeIconSvg } from "~/utils/html-sanitizer";
export default function EntityIcon({ className, icon, title }: { className?: string; icon?: string; title?: string }) {
return (
<>
{icon && (
<>
{icon.startsWith("<svg") ? (
<div dangerouslySetInnerHTML={{ __html: sanitizeIconSvg(icon, className) }} />
) : icon.includes("http") ? (
<img className={className} src={icon} alt={title} />
) : (
<></>
)}
</>
)}
</>
);
}
@@ -0,0 +1,5 @@
import { FeatherShield } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherShield)
@@ -0,0 +1,5 @@
import { FeatherBarChart2 } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherBarChart2)
@@ -0,0 +1,5 @@
import { FeatherLayoutGrid } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherLayoutGrid)
@@ -0,0 +1,5 @@
import { FeatherUsers } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherUsers)
@@ -0,0 +1,5 @@
import { FeatherCode } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherCode)
@@ -0,0 +1,5 @@
import { FeatherComponent } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherComponent)
@@ -0,0 +1,5 @@
import { FeatherLayoutDashboard } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherLayoutDashboard)
@@ -0,0 +1,5 @@
import { FeatherFileText } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherFileText)
@@ -0,0 +1,5 @@
import { FeatherMail } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherMail)
@@ -0,0 +1,5 @@
import { FeatherDatabase } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherDatabase)
@@ -0,0 +1,5 @@
import { FeatherCalendar } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherCalendar)
@@ -0,0 +1,5 @@
import { FeatherFlag } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherFlag)
@@ -0,0 +1,5 @@
import { FeatherLifeBuoy } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherLifeBuoy)
@@ -0,0 +1,5 @@
import { FeatherHistory } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherHistory)
@@ -0,0 +1,5 @@
import { FeatherKey } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherKey)
@@ -0,0 +1,5 @@
import { FeatherLink } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherLink)
@@ -0,0 +1,5 @@
import { FeatherUsers } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherUsers)
@@ -0,0 +1,5 @@
import { FeatherActivity } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherActivity)
@@ -0,0 +1,5 @@
import { FeatherCompass } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherCompass)
@@ -0,0 +1,15 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import IconNotifications from "./IconNotifications";
describe("IconNotifications", () => {
it("forwards className onto a rendered Subframe Feather icon", () => {
const markup = renderToStaticMarkup(<IconNotifications className="size-4" />);
// Migrated to the Subframe @subframe/core Feather icon set via the shared
// icons/_feather wrapper, which forwards `className` onto the icon and
// renders an <svg> (Feather uses a 24x24 viewBox).
expect(markup).toContain("size-4");
expect(markup).toContain("<svg");
});
});
@@ -0,0 +1,5 @@
import { FeatherBell } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherBell)
@@ -0,0 +1,5 @@
import { FeatherRocket } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherRocket)
@@ -0,0 +1,5 @@
import { FeatherFile } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherFile)
@@ -0,0 +1,5 @@
import { FeatherGlobe } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherGlobe)
@@ -0,0 +1,5 @@
import { FeatherUser } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherUser)
@@ -0,0 +1,5 @@
import { FeatherSparkles } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherSparkles)
@@ -0,0 +1,5 @@
import { FeatherPlug } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherPlug)
@@ -0,0 +1,5 @@
import { FeatherShield } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherShield)
@@ -0,0 +1,5 @@
import { FeatherSettings } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherSettings)
@@ -0,0 +1,5 @@
import { FeatherBuilding2 } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherBuilding2)
@@ -0,0 +1,5 @@
import { FeatherUsers } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherUsers)
@@ -0,0 +1,5 @@
import { FeatherBox } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherBox)
@@ -0,0 +1,5 @@
import { FeatherWorkflow } from "@subframe/core"
import { featherIcon } from "~/components/ui/icons/_feather"
export default featherIcon(FeatherWorkflow)
@@ -0,0 +1,33 @@
import { ReactNode } from "react";
import { sanitizeIconSvg } from "~/utils/html-sanitizer";
interface Props {
className: string;
item: {
title?: string;
icon?: ReactNode;
};
}
export default function SidebarIcon({ className, item }: Props) {
let icon = item.icon;
let title = item.title;
if (typeof icon !== "string") {
return icon;
}
return (
<>
{icon && (
<>
{icon.startsWith("<svg") ? (
<div dangerouslySetInnerHTML={{ __html: sanitizeIconSvg(icon, className) }} />
) : icon.includes("http") ? (
<img className={className} src={icon} alt={title} />
) : (
<></>
)}
</>
)}
</>
);
}
@@ -0,0 +1,47 @@
import { useAppData } from "~/utils/data/useAppData";
interface Props {
onOpenCommandPalette: () => void;
}
export default function NewTenantSelect({ onOpenCommandPalette }: Props) {
const appData = useAppData();
if (!appData.currentTenant) {
return null;
}
return (
<>
<button type="button" onClick={onOpenCommandPalette} className="text-foreground group flex w-full shrink-0 focus:outline-hidden">
<div className="group block w-full shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center truncate text-left">
{appData?.currentTenant?.icon ? (
<img className="inline-block h-9 w-9 shrink-0 rounded-full shadow-2xs" src={appData?.currentTenant?.icon} alt={appData?.currentTenant?.name} />
) : (
<span className="bg-primary inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full">
<span className="text-primary-foreground text-sm font-medium leading-none">{appData?.currentTenant?.name.substring(0, 1)}</span>
</span>
)}
<div className="ml-3 truncate">
<p className="text-sm font-medium">{appData?.currentTenant?.name}</p>
<p className="text-muted-foreground truncate text-xs font-normal">{appData?.user.email}</p>
</div>
</div>
{/* <svg
xmlns="http://www.w3.org/2000/svg"
className="text-muted-foreground group-hover:text-foreground h-4 w-4"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M10 3a1 1 0 01.707.293l3 3a1 1 0 01-1.414 1.414L10 5.414 7.707 7.707a1 1 0 01-1.414-1.414l3-3A1 1 0 0110 3zm-3.707 9.293a1 1 0 011.414 0L10 14.586l2.293-2.293a1 1 0 011.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg> */}
</div>
</div>
</button>
</>
);
}
@@ -0,0 +1,108 @@
import { useLocation, useNavigate } from "react-router";
import { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import PlusIcon from "~/components/ui/icons/PlusIcon";
import InputSelector from "~/components/ui/input/InputSelector";
import { useAppData } from "~/utils/data/useAppData";
import { useRootData } from "~/utils/data/useRootData";
import { absolutePublicAppPath, isAbsoluteHttpUrl } from "~/utils/app/CrossHostUrls";
import { translateLabel } from "~/utils/i18n/translateLabel";
import { getTenantSwitchPath } from "./tenant-switch-url";
interface Props {
className?: string;
}
export default function TenantSelector({ className }: Props) {
const { t, i18n } = useTranslation();
const appData = useAppData();
const rootData = useRootData();
const location = useLocation();
const navigate = useNavigate();
const [selected, setSelected] = useState(appData?.currentTenant?.slug);
function switchTenantPath(tenantSlug: string) {
return getTenantSwitchPath({ currentTenant: appData.currentTenant, location, tenantSlug });
}
useEffect(() => {
if (selected) {
const tenant = appData?.myTenants.find((f) => f.slug === selected);
if (tenant && tenant.id !== appData.currentTenant.id) {
navigate(switchTenantPath(tenant.slug));
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selected]);
function getAllTenants() {
const items = appData?.myTenants
.map((f) => {
let group = t("models.tenant.plural");
if (f.types.length > 0) {
group = translateLabel(t, i18n, f.types[0].titlePlural) || t("models.tenant.plural");
}
return {
group,
value: f.slug,
name: (
<div className="flex items-center space-x-2">
{f.icon ? (
<img className="inline-block h-4 w-4 shrink-0 rounded-md shadow-xs" src={f.icon} alt={f.name} />
) : (
<span className="bg-primary inline-flex h-4 w-4 shrink-0 items-center justify-center rounded-md">
<span className="text-primary-foreground text-xs font-medium leading-none">{f?.name.substring(0, 1)}</span>
</span>
)}
<div>{f.name}</div>
</div>
),
};
})
.sort((a, b) => a.group.localeCompare(b.group));
// return unique slugs
const unique = items.filter((item, index, self) => self.findIndex((t) => t.value === item.value) === index);
return [
...unique,
{
title: "hey",
value: "{new}",
className: "border-t border-border rounded-none",
name: (
<div className="flex items-center gap-2">
<div className="w-4 shrink-0">
<PlusIcon className="h-4 w-4 p-0.5" />
</div>
<div>{t("app.tenants.create.title")}</div>
</div>
),
},
];
}
return (
<div className="text-foreground">
{appData?.myTenants.length > 1 && (
<InputSelector
selectPlaceholder=""
withSearch={false}
value={selected}
options={getAllTenants()}
setValue={(e) => {
if (e === "{new}") {
const newAccountPath = absolutePublicAppPath(rootData.routing, "new-account");
if (isAbsoluteHttpUrl(newAccountPath)) {
window.location.assign(newAccountPath);
} else {
navigate(newAccountPath);
}
setSelected(e?.toString() ?? "");
} else {
setSelected(e?.toString() ?? "");
}
}}
/>
)}
</div>
);
}
@@ -0,0 +1,41 @@
import { useAppData } from "~/utils/data/useAppData";
import { ChevronsUpDown } from "~/components/ui/icons/vendor";
interface Props {
onOpenCommandPalette: () => void;
}
export default function TenantSelect({ onOpenCommandPalette }: Props) {
const appData = useAppData();
if (!appData.currentTenant) {
return null;
}
return (
<>
<button type="button" onClick={onOpenCommandPalette} className="group flex shrink-0 bg-slate-800 p-4 focus:outline-hidden">
<div className="group block w-full shrink-0">
<div className="flex items-center justify-between">
<div className="flex items-center truncate text-left">
{appData?.currentTenant?.icon ? (
<img
className="inline-block h-9 w-9 shrink-0 rounded-full bg-gray-500 shadow-2xs"
src={appData?.currentTenant?.icon}
alt={appData?.currentTenant?.name}
/>
) : (
<span className="bg-primary inline-flex h-9 w-9 shrink-0 items-center justify-center rounded-full">
<span className="text-primary-foreground text-sm font-medium leading-none">{appData?.currentTenant?.name.substring(0, 1)}</span>
</span>
)}
<div className="ml-3 truncate">
<p className="text-sm font-medium text-gray-200 group-hover:text-white">{appData?.currentTenant?.name}</p>
<p className="truncate text-xs font-medium text-gray-300 group-hover:text-gray-200">{appData?.user.email}</p>
</div>
</div>
<ChevronsUpDown className="text-muted-foreground h-5 w-5 group-hover:text-white" />
</div>
</div>
</button>
</>
);
}
@@ -0,0 +1,76 @@
import { useLocation, useNavigate } from "react-router";
import { Fragment, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import InputSelectorDarkMode from "~/components/ui/input/dark/InputSelectorDarkMode";
import { useAppData } from "~/utils/data/useAppData";
import { translateLabel } from "~/utils/i18n/translateLabel";
import { getTenantSwitchPath } from "./tenant-switch-url";
interface Props {
className?: string;
}
export default function TenantSelector({ className }: Props) {
const { t, i18n } = useTranslation();
const appData = useAppData();
const location = useLocation();
const navigate = useNavigate();
const [selected, setSelected] = useState(appData?.currentTenant?.slug);
function switchTenantPath(tenantSlug: string) {
return getTenantSwitchPath({ currentTenant: appData.currentTenant, location, tenantSlug });
}
useEffect(() => {
if (selected) {
const tenant = appData.myTenants.find((f) => f.slug === selected);
if (tenant && tenant.id !== appData.currentTenant.id) {
navigate(switchTenantPath(tenant.slug));
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selected]);
function getAllTenants() {
const items = appData.myTenants
.map((f) => {
let group = t("models.tenant.plural");
if (f.types.length > 0) {
group = translateLabel(t, i18n, f.types[0].titlePlural) || t("models.tenant.plural");
}
return {
group,
value: f.slug,
name: f.name,
img: f.icon ? (
<img className="inline-block h-6 w-6 shrink-0 rounded-md bg-gray-700 shadow-xs" src={f.icon} alt={f.name} />
) : (
<span className="bg-primary inline-flex h-6 w-6 shrink-0 items-center justify-center rounded-md">
<span className="text-theme-200 text-xs font-medium leading-none">{f?.name.substring(0, 1)}</span>
</span>
),
};
})
.sort((a, b) => a.group.localeCompare(b.group));
// return unique slugs
const unique = items.filter((item, index, self) => self.findIndex((t) => t.value === item.value) === index);
return unique;
}
return (
<Fragment>
{appData.myTenants.length > 1 && (
<InputSelectorDarkMode
withSearch={false}
value={selected}
renderSelected={(e) => {
const tenant = appData.myTenants.find((f) => f.slug === e.value);
return <div>{tenant?.name}</div>;
}}
options={getAllTenants()}
setValue={(e) => setSelected(e?.toString() ?? "")}
/>
)}
</Fragment>
);
}
@@ -0,0 +1,39 @@
import { describe, expect, it } from "vitest";
import { getTenantSwitchPath } from "./tenant-switch-url";
const currentTenant = {
id: "tenant_123",
slug: "acme",
};
describe("getTenantSwitchPath", () => {
it("keeps the current child path when switching tenants", () => {
expect(
getTenantSwitchPath({
currentTenant,
location: { pathname: "/acme/settings/members" },
tenantSlug: "beta",
}),
).toBe("/beta/settings/members");
});
it("supports legacy app-prefixed tenant paths without preserving the legacy prefix", () => {
expect(
getTenantSwitchPath({
currentTenant,
location: { pathname: "/app/acme/entities/rows" },
tenantSlug: "beta",
}),
).toBe("/beta/entities/rows");
});
it("does not carry scope-bearing query or hash state into the next tenant", () => {
expect(
getTenantSwitchPath({
currentTenant,
location: { pathname: "/acme/entities/rows", search: "?tenantId=tenant_123", hash: "#row_1" },
tenantSlug: "beta",
}),
).toBe("/beta/entities/rows");
});
});
@@ -0,0 +1,29 @@
import { appPath } from "~/utils/app/CanonicalUrlUtils";
type TenantSwitchLocation = {
pathname: string;
search?: string;
hash?: string;
};
type TenantSwitchOptions = {
currentTenant: {
id: string;
slug: string;
};
location: TenantSwitchLocation;
tenantSlug: string;
};
export function getTenantSwitchPath({ currentTenant, location, tenantSlug }: TenantSwitchOptions) {
const pathSegments = location.pathname.split("/").filter(Boolean);
let childPath = "";
if (pathSegments[0] === "app" && (pathSegments[1] === currentTenant.slug || pathSegments[1] === currentTenant.id)) {
childPath = pathSegments.slice(2).join("/");
} else if (pathSegments[0] === currentTenant.slug || pathSegments[0] === currentTenant.id) {
childPath = pathSegments.slice(1).join("/");
}
return appPath({ tenantSlug, path: childPath, mode: "host-aware" });
}
@@ -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();
});
});
@@ -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>
);
}
@@ -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;
}