Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -1,5 +1,5 @@
import { AnimatePresence, motion } from "framer-motion";
import { t as i18nT } from "i18next";
import { AnimatePresence, motion } from "motion/react";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { useState } from "react";
import LinkOrAhref from "../ui/buttons/LinkOrAhref";
import clsx from "clsx";
@@ -1,9 +1,10 @@
import React, { useRef } from "react";
import { t as i18nT } from "i18next";
import { motion, useScroll, useSpring, useTransform } from "framer-motion";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { motion, useScroll, useSpring, useTransform } from "motion/react";
import type { Transition } from "motion/react";
export const MovingLine = () => {
const transition = {
const transition: Transition = {
duration: 14,
ease: "easeInOut",
};
@@ -27,7 +27,7 @@ const filters = [
function renderToolbar(initialEntry: string) {
return render(
<MemoryRouter initialEntries={[initialEntry]}>
<TenantActivityLogToolbar filters={filters} />
<TenantActivityLogToolbar filters={filters} exportTo="/acme/settings/logs/export" />
</MemoryRouter>
);
}
@@ -42,12 +42,12 @@ describe("TenantActivityLogToolbar", () => {
expect(screen.getByText("models.log.actor")).toBeInTheDocument();
});
it("preserves active filters while replacing stale pagination with CSV export", () => {
it("preserves active filters while dropping stale pagination on the export href", () => {
renderToolbar("/acme/settings/logs?q=login&action=auth&url=%2Flogin&actor=Grace&page=3&pageSize=25");
const exportUrl = new URL(screen.getByRole("link", { name: "Export" }).getAttribute("href") ?? "", "https://example.test");
expect(exportUrl.pathname).toBe("/acme/settings/logs");
expect(exportUrl.pathname).toBe("/acme/settings/logs/export");
expect(exportUrl.searchParams.get("q")).toBe("login");
expect(exportUrl.searchParams.get("action")).toBe("auth");
expect(exportUrl.searchParams.get("url")).toBe("/login");
@@ -55,22 +55,21 @@ describe("TenantActivityLogToolbar", () => {
expect(exportUrl.searchParams.get("pageSize")).toBe("25");
expect(exportUrl.searchParams.get("tenantId")).toBeNull();
expect(exportUrl.searchParams.get("page")).toBeNull();
expect(exportUrl.searchParams.get("export")).toBe("csv");
});
it("replaces an existing export value with csv", () => {
it("drops a stale export param from the current search", () => {
renderToolbar("/acme/settings/logs?export=json&actor=user-1");
const exportUrl = new URL(screen.getByRole("link", { name: "Export" }).getAttribute("href") ?? "", "https://example.test");
expect(exportUrl.pathname).toBe("/acme/settings/logs");
expect(exportUrl.pathname).toBe("/acme/settings/logs/export");
expect(exportUrl.searchParams.get("actor")).toBe("user-1");
expect(exportUrl.searchParams.get("export")).toBe("csv");
expect(exportUrl.searchParams.get("export")).toBeNull();
});
it("creates a valid tenant-relative CSV export href without existing search params", () => {
renderToolbar("/acme/settings/logs");
expect(screen.getByRole("link", { name: "Export" })).toHaveAttribute("href", "/acme/settings/logs?export=csv");
expect(screen.getByRole("link", { name: "Export" })).toHaveAttribute("href", "/acme/settings/logs/export");
});
});
@@ -6,16 +6,19 @@ import { Button } from "~/components/ui/button";
type Props = {
filters: FilterablePropertyDto[];
// Path of the CSV export resource route; active filters are carried over.
exportTo: string;
};
export default function TenantActivityLogToolbar({ filters }: Props) {
export default function TenantActivityLogToolbar({ filters, exportTo }: Props) {
const { t } = useTranslation();
const location = useLocation();
const exportLabel = getFallbackTranslation(t("shared.export"), "Export");
const exportSearchParams = new URLSearchParams(location.search);
exportSearchParams.delete("page");
exportSearchParams.set("export", "csv");
const exportHref = `${location.pathname}?${exportSearchParams.toString()}`;
exportSearchParams.delete("export");
const exportQuery = exportSearchParams.toString();
const exportHref = exportQuery ? `${exportTo}?${exportQuery}` : exportTo;
return (
<div className="flex items-center gap-2">
@@ -1,5 +1,5 @@
import { Link } from "react-router";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import clsx from "clsx";
import { lazy, Suspense, useEffect, useId, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -69,7 +69,7 @@ interface TopItemDto {
tabTitle?: string;
}
function TopItemsData({ title, items, viewMoreRoute, fallbackName, bgClassName }: TopItemDto) {
function TopItemsData({ title: _title, items, viewMoreRoute, fallbackName, bgClassName }: TopItemDto) {
const { authenticated } = useRootData();
const formatters = useLocaleFormatters();
const maxCount = useMemo(() => Math.max(0, ...items.map((item) => item.count)), [items]);
@@ -249,7 +249,21 @@ export default function AnalyticsOverview({ overview, withUsers, rootUrl }: { ov
<path strokeLinecap="round" strokeLinejoin="round" d="M17.25 6.75L22.5 12l-5.25 5.25m-10.5 0L1.5 12l5.25-5.25m7.5-3l-4.5 16.5" />
</svg>
) : (
<img className="h-4 w-4" src={`http://www.google.com/s2/favicons?domain=${item.name}&sz=256`} alt={item.name} />
<svg
className="text-muted-foreground h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 21a9 9 0 1 0 0-18m0 18c2.1 0 3.8-4 3.8-9S14.1 3 12 3m0 18c-2.1 0-3.8-4-3.8-9S9.9 3 12 3M3.5 9h17m-17 6h17"
/>
</svg>
),
name: UrlUtils.stripTrailingSlash(item.name?.replace("https://", "").replace("http://", "").replace("www.", "") ?? ""),
count: item.count,
@@ -2,6 +2,7 @@ import { ReactNode } from "react";
import CommandPalette from "../ui/commandPalettes/CommandPalette";
import SubframeAppShell from "./SubframeAppShell";
import SkipToContent from "../core/SkipToContent";
import { UiPreferencesProvider } from "./UiPreferencesContext";
interface Props {
layout: "app" | "admin" | "docs";
@@ -12,11 +13,13 @@ export default function AppLayout({ layout, children }: Props) {
// D-D0a: App-Rahmen ist jetzt Davids Subframe-Shell (SidebarWithSections + Topbar) statt der
// shadcn-Shell. Der CommandPalette-Wrapper bleibt (liefert den useCommandPalette-Kontext fuer die Topbar).
return (
<div>
<SkipToContent />
<CommandPalette key={layout} layout={layout}>
<SubframeAppShell layout={layout}>{children}</SubframeAppShell>
</CommandPalette>
</div>
<UiPreferencesProvider>
<div>
<SkipToContent />
<CommandPalette key={layout} layout={layout}>
<SubframeAppShell layout={layout}>{children}</SubframeAppShell>
</CommandPalette>
</div>
</UiPreferencesProvider>
);
}
@@ -0,0 +1,28 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { MemoryRouter, useLocation } from "react-router";
import { describe, expect, it } from "vitest";
import { AppLink } from "./AppLink";
function LocationProbe() {
const location = useLocation();
return <output>{`${location.pathname}${location.search}`}</output>;
}
describe("AppLink", () => {
it("stays a semantic anchor in isolated presentational tests", () => {
render(<AppLink href="/acme/projects/p1">Project</AppLink>);
expect(screen.getByRole("link", { name: "Project" }).getAttribute("href")).toBe("/acme/projects/p1");
});
it("navigates through React Router when the app shell is present", () => {
render(
<MemoryRouter initialEntries={["/acme/projects"]}>
<AppLink href="/acme/projects/p1?tab=details">Project</AppLink>
<LocationProbe />
</MemoryRouter>,
);
fireEvent.click(screen.getByRole("link", { name: "Project" }));
expect(screen.getByRole("status").textContent).toBe("/acme/projects/p1?tab=details");
});
});
@@ -0,0 +1,42 @@
import { forwardRef, type ComponentPropsWithoutRef } from "react";
import { Link, useInRouterContext } from "react-router";
export type AppLinkProps = Omit<ComponentPropsWithoutRef<"a">, "href"> & {
href: string;
replace?: boolean;
preventScrollReset?: boolean;
};
/**
* Internal navigation for presentational screens.
*
* In the running app this uses React Router, preserving the shell and its page
* transition. Isolated screen/component tests do not always mount a router, so
* the same component deliberately falls back to a semantic anchor there.
* Downloads, OAuth hops, mailto/tel and external URLs must keep using <a>.
*/
export const AppLink = forwardRef<HTMLAnchorElement, AppLinkProps>(function AppLink(
{ href, replace, preventScrollReset, children, ...anchorProps },
ref,
) {
const inRouter = useInRouterContext();
if (!inRouter) {
return (
<a ref={ref} href={href} {...anchorProps}>
{children}
</a>
);
}
return (
<Link
ref={ref}
to={href}
replace={replace}
preventScrollReset={preventScrollReset}
{...anchorProps}
>
{children}
</Link>
);
});
@@ -0,0 +1,71 @@
// @vitest-environment jsdom
import { useLayoutEffect } from "react";
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { AppShellSidebarContext, useRecommendedSidebarCollapse } from "./AppShellSidebarContext";
function BoardWorkspace({ workspaceKey }: { workspaceKey: string | null }) {
useRecommendedSidebarCollapse(workspaceKey);
return null;
}
function BoardWorkspaceWithLayoutProbe({ onLayout }: { onLayout: () => void }) {
useRecommendedSidebarCollapse("projects:pipeline-a");
useLayoutEffect(() => {
onLayout();
}, [onLayout]);
return null;
}
describe("useRecommendedSidebarCollapse", () => {
it("requests a collapse when a board opens and whenever its board identity changes", () => {
const collapseSidebarIfPreferred = vi.fn();
const value = { collapseSidebar: vi.fn(), collapseSidebarIfPreferred };
const { rerender } = render(
<AppShellSidebarContext.Provider value={value}>
<BoardWorkspace workspaceKey="projects:pipeline-a" />
</AppShellSidebarContext.Provider>
);
expect(collapseSidebarIfPreferred).toHaveBeenCalledOnce();
rerender(
<AppShellSidebarContext.Provider value={value}>
<BoardWorkspace workspaceKey="projects:pipeline-a" />
</AppShellSidebarContext.Provider>
);
expect(collapseSidebarIfPreferred).toHaveBeenCalledOnce();
rerender(
<AppShellSidebarContext.Provider value={value}>
<BoardWorkspace workspaceKey="projects:pipeline-b" />
</AppShellSidebarContext.Provider>
);
expect(collapseSidebarIfPreferred).toHaveBeenCalledTimes(2);
});
it("does nothing when no board is available", () => {
const collapseSidebarIfPreferred = vi.fn();
render(
<AppShellSidebarContext.Provider value={{ collapseSidebar: vi.fn(), collapseSidebarIfPreferred }}>
<BoardWorkspace workspaceKey={null} />
</AppShellSidebarContext.Provider>
);
expect(collapseSidebarIfPreferred).not.toHaveBeenCalled();
});
it("requests the collapse during layout before the board can paint", () => {
const order: string[] = [];
const collapseSidebarIfPreferred = vi.fn(() => order.push("collapse"));
render(
<AppShellSidebarContext.Provider value={{ collapseSidebar: vi.fn(), collapseSidebarIfPreferred }}>
<BoardWorkspaceWithLayoutProbe onLayout={() => order.push("layout-probe")} />
</AppShellSidebarContext.Provider>
);
expect(order).toEqual(["collapse", "layout-probe"]);
});
});
@@ -0,0 +1,25 @@
import { createContext, useContext, useLayoutEffect } from "react";
export type AppShellSidebarControls = {
collapseSidebar: () => void;
collapseSidebarIfPreferred: () => void;
};
const NOOP_CONTROLS: AppShellSidebarControls = {
collapseSidebar: () => undefined,
collapseSidebarIfPreferred: () => undefined,
};
export const AppShellSidebarContext = createContext<AppShellSidebarControls>(NOOP_CONTROLS);
export function useAppShellSidebar(): AppShellSidebarControls {
return useContext(AppShellSidebarContext);
}
export function useRecommendedSidebarCollapse(workspaceKey: string | null): void {
const { collapseSidebarIfPreferred } = useAppShellSidebar();
useLayoutEffect(() => {
if (workspaceKey) collapseSidebarIfPreferred();
}, [collapseSidebarIfPreferred, workspaceKey]);
}
@@ -17,17 +17,21 @@ type Props = {
// section).
// - "Remind me in 7 days" → POSTs to a tiny resource route which sets a
// short-lived UX cookie. While that cookie is in the future the tenant
// layout omits the banner entirely.
// layout omits the banner entirely. The route lives under /auth/* so it
// stays reachable on the tenant app host (the host-routing runtime
// 404s all other /api/* paths there).
//
// The banner also offers a local "dismiss for this page-load" close button
// so the user can hide it without committing to either action.
const REMIND_ACTION_PATH = "/auth/password-policy-remind";
export default function PasswordPolicyBanner({ changePasswordHref }: Props) {
const { t } = useTranslation("auth");
const fetcher = useFetcher();
const [locallyDismissed, setLocallyDismissed] = useState(false);
if (locallyDismissed) return null;
if (fetcher.state !== "idle" && fetcher.formAction === "/api/password-policy-remind") {
if (fetcher.state !== "idle" && fetcher.formAction === REMIND_ACTION_PATH) {
// Optimistically hide while the remind cookie is being set so the user
// gets immediate feedback on click.
return null;
@@ -61,7 +65,7 @@ export default function PasswordPolicyBanner({ changePasswordHref }: Props) {
>
{t("passwordPolicyBanner.changeNow")}
</Link>
<fetcher.Form method="post" action="/api/password-policy-remind">
<fetcher.Form method="post" action={REMIND_ACTION_PATH}>
<button
type="submit"
data-testid="password-policy-banner-remind"
@@ -0,0 +1,136 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { Link, MemoryRouter, Route, Routes } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import { RouteContentTransition } from "./RouteContentTransition";
const originalAnimate = HTMLElement.prototype.animate;
const originalMatchMedia = window.matchMedia;
function renderTransition() {
render(
<MemoryRouter initialEntries={["/first"]}>
<Link to="/second">Next</Link>
<Routes>
<Route
path="*"
element={
<RouteContentTransition>
<span>Content</span>
</RouteContentTransition>
}
/>
</Routes>
</MemoryRouter>
);
}
describe("RouteContentTransition", () => {
afterEach(() => {
HTMLElement.prototype.animate = originalAnimate;
window.matchMedia = originalMatchMedia;
vi.restoreAllMocks();
});
it("animates the existing content wrapper only after a pathname change", () => {
const cancel = vi.fn();
const animate = vi.fn(() => ({ cancel }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: false }) as MediaQueryList);
renderTransition();
expect(animate).not.toHaveBeenCalled();
const wrapper = document.querySelector('[data-route-content-transition="true"]');
fireEvent.click(screen.getByRole("link", { name: "Next" }));
expect(document.querySelector('[data-route-content-transition="true"]')).toBe(wrapper);
expect(animate).toHaveBeenCalledWith(
[
{ opacity: 0.15, filter: "blur(5px)" },
{ opacity: 1, filter: "blur(0px)" },
],
expect.objectContaining({ duration: 420, easing: "cubic-bezier(0.22, 1, 0.36, 1)" })
);
});
it("does not animate when reduced motion is requested", () => {
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: true }) as MediaQueryList);
renderTransition();
fireEvent.click(screen.getByRole("link", { name: "Next" }));
expect(animate).not.toHaveBeenCalled();
});
it("does not animate filter-only navigation", () => {
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: false }) as MediaQueryList);
render(
<MemoryRouter initialEntries={["/first"]}>
<Link to="/first?q=compact">Change filter</Link>
<RouteContentTransition>
<span>Content</span>
</RouteContentTransition>
</MemoryRouter>
);
fireEvent.click(screen.getByRole("link", { name: "Change filter" }));
expect(animate).not.toHaveBeenCalled();
});
it("animates structural tab and view changes on the same pathname", () => {
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: false }) as MediaQueryList);
render(
<MemoryRouter initialEntries={["/first?tab=overview"]}>
<Link to="/first?tab=details">Open details tab</Link>
<RouteContentTransition>
<span>Content</span>
</RouteContentTransition>
</MemoryRouter>
);
fireEvent.click(screen.getByRole("link", { name: "Open details tab" }));
expect(animate).toHaveBeenCalledOnce();
});
it("animates marked page content without touching a stable inner sidebar", () => {
const animate = vi.fn(() => ({ cancel: vi.fn() }) as unknown as Animation);
HTMLElement.prototype.animate = animate;
window.matchMedia = vi.fn(() => ({ matches: false }) as MediaQueryList);
render(
<MemoryRouter initialEntries={["/first"]}>
<Link to="/second">Next inner page</Link>
<Routes>
<Route
path="*"
element={
<RouteContentTransition>
<aside data-testid="inner-sidebar">Inner sidebar</aside>
<section data-testid="page-content" data-route-transition-content="true">
Page content
</section>
</RouteContentTransition>
}
/>
</Routes>
</MemoryRouter>
);
const wrapper = document.querySelector<HTMLElement>('[data-route-content-transition="true"]');
const pageContent = screen.getByTestId("page-content");
fireEvent.click(screen.getByRole("link", { name: "Next inner page" }));
expect(animate).toHaveBeenCalledOnce();
expect(animate.mock.contexts[0]).toBe(pageContent);
expect(animate.mock.contexts[0]).not.toBe(wrapper);
});
});
@@ -0,0 +1,75 @@
import { useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from "react";
import { useLocation } from "react-router";
import { useUiPreferences } from "./UiPreferencesContext";
const ROUTE_TRANSITION_DURATION_MS = 420;
const ROUTE_TRANSITION_TARGET_SELECTOR = '[data-route-transition-content="true"]';
// Tabs and view-mode routes render a genuinely different subpage while keeping
// the same pathname. Filters/search/pagination deliberately stay out: animating
// every query refinement would make dense working screens feel unstable.
const STRUCTURAL_SEARCH_PARAMS = ["tab", "view"] as const;
/**
* Adds a restrained transition after real pathname changes. The wrapper stays
* mounted, so route state, forms and dialogs are not reset by the animation.
*
* Blur plus a pronounced fade makes the route change clearly visible without
* moving or scaling the content column. Inner sidebars stay outside the marked
* page target and therefore remain visually stable.
*/
export function RouteContentTransition({ children }: { children: ReactNode }) {
const location = useLocation();
const { preferences } = useUiPreferences();
const contentRef = useRef<HTMLDivElement>(null);
const transitionKey = useMemo(() => {
const params = new URLSearchParams(location.search);
return `${location.pathname}?${STRUCTURAL_SEARCH_PARAMS.map((key) => `${key}=${params.get(key) ?? ""}`).join("&")}`;
}, [location.pathname, location.search]);
const previousTransitionKeyRef = useRef(transitionKey);
const animationRef = useRef<Animation | null>(null);
// Start before the browser paints the new route. useEffect runs one frame
// later, which made fast subpages briefly appear complete before fading in
// and was perceived as a missing/inconsistent transition.
useLayoutEffect(() => {
if (previousTransitionKeyRef.current === transitionKey) return;
previousTransitionKeyRef.current = transitionKey;
const content = contentRef.current;
const reduceMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches === true;
if (!content || !preferences.visualEffectsEnabled || reduceMotion || typeof content.animate !== "function") return;
const target = content.querySelector<HTMLElement>(ROUTE_TRANSITION_TARGET_SELECTOR) ?? content;
animationRef.current?.cancel();
animationRef.current = target.animate(
[
{ opacity: 0.15, filter: "blur(5px)" },
{ opacity: 1, filter: "blur(0px)" },
],
{
duration: ROUTE_TRANSITION_DURATION_MS,
easing: "cubic-bezier(0.22, 1, 0.36, 1)",
fill: "both",
}
);
return () => {
animationRef.current?.cancel();
animationRef.current = null;
};
}, [transitionKey, preferences.visualEffectsEnabled]);
useEffect(
() => () => {
animationRef.current?.cancel();
},
[]
);
return (
<div ref={contentRef} className="pb-20 sm:pb-0" data-route-content-transition="true">
{children}
</div>
);
}
@@ -1,20 +1,30 @@
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { createMemoryRouter, RouterProvider } from "react-router";
import { describe, expect, it, vi } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { UI_ACTION_IDS, UI_SURFACE_IDS, getSidebarSurfaceId, type UiLayout } from "~/application/ui/uiRegistry";
import SubframeAppShell from "./SubframeAppShell";
import { useAppShellSidebar } from "./AppShellSidebarContext";
// D-D0a — Contract-Test der neuen Subframe-App-Shell: stabile Shell-Surface-/Action-data-ui-ids
// (analog zum bisherigen ShadcnSidebarLayout-Test), damit der Reachability-Kontrakt erhalten bleibt.
const { commandPaletteToggle } = vi.hoisted(() => ({ commandPaletteToggle: vi.fn() }));
vi.mock("~/components/ui/commandPalettes/CommandPalette", () => ({
useCommandPalette: () => ({ toggle: vi.fn() }),
useCommandPalette: () => ({ toggle: commandPaletteToggle }),
}));
vi.mock("~/modules/onboarding/components/OnboardingSession", () => ({ default: () => null }));
vi.mock("~/utils/data/useTitleData", () => ({ useTitleData: () => "Dashboard" }));
vi.mock("~/utils/data/useTitleData", () => ({
useTitleData: () => "Dashboard",
useBreadcrumbTrail: () => [
{ label: "Parent", href: "/parent" },
{ label: "Dashboard", href: "/" },
],
shouldShowParentNavCrumb: () => false,
}));
vi.mock("~/utils/data/useAppOrAdminData", () => ({
useAppOrAdminData: () => ({
@@ -35,11 +45,23 @@ vi.mock("../layouts/sidebars/shadcn/nav-actions", () => ({
NavActions: () => <button data-ui-id="ui.action.shell.search">Search</button>,
}));
vi.mock("~/application/sidebar/AppSidebar", () => ({ AppSidebar: () => [] }));
let mockedAppSidebarItems: any[] = [];
function CollapseSidebarButton() {
const { collapseSidebar } = useAppShellSidebar();
return <button onClick={collapseSidebar}>Collapse sidebar</button>;
}
vi.mock("~/application/sidebar/AppSidebar", () => ({ AppSidebar: () => mockedAppSidebarItems }));
vi.mock("~/application/sidebar/AdminSidebar", () => ({ AdminSidebar: () => [] }));
vi.mock("~/application/sidebar/DocsSidebar", () => ({ DocsSidebar: () => [] }));
describe("SubframeAppShell UI IDs", () => {
afterEach(() => {
mockedAppSidebarItems = [];
commandPaletteToggle.mockReset();
});
function renderShell(layout: UiLayout) {
const router = createMemoryRouter(
[
@@ -70,11 +92,184 @@ describe("SubframeAppShell UI IDs", () => {
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(screen.getByRole("link", { name: "Parent" }).firstElementChild).toHaveClass("text-text-neutral-secondary");
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_ACTION_IDS.searchMobile}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellMain}"]`)).toContainElement(screen.getByText("Page content"));
expectNoDuplicateDataUiIds();
});
it("never renders the notification bell as a dead link", () => {
// The bell fell back to href="#" whenever no tenant was in scope, which made
// it dead on every admin page (admin audit 2026-07-26, A11Y-01). A surface
// without a notification centre omits the bell instead.
for (const layout of ["app", "admin", "docs"] as UiLayout[]) {
renderShell(layout);
const bell = document.querySelector(`[data-ui-id="${UI_ACTION_IDS.notifications}"]`);
if (bell) {
expect(bell.getAttribute("href"), `${layout} bell href`).not.toBe("#");
expect(bell.getAttribute("href"), `${layout} bell href`).toBeTruthy();
}
cleanup();
}
});
it("points the admin bell at the admin notification centre with accessible markup", () => {
renderShell("admin");
const bell = document.querySelector(`[data-ui-id="${UI_ACTION_IDS.notifications}"]`);
expect(bell).toBeInTheDocument();
expect(bell?.tagName).toBe("A");
expect(bell?.getAttribute("href")).toContain("notifications");
expect(bell).toHaveAttribute("aria-label");
expect(bell).toHaveClass("focus-visible:shadow-focus");
expect(bell?.querySelector("button")).toBeNull();
});
it("opens the same command palette from the desktop field and mobile icon triggers", () => {
renderShell("app");
const desktopTrigger = document.querySelector<HTMLElement>(`[data-ui-id="${UI_ACTION_IDS.search}"]`);
const mobileTrigger = document.querySelector<HTMLElement>(`[data-ui-id="${UI_ACTION_IDS.searchMobile}"]`);
expect(desktopTrigger).toHaveClass("hidden", "md:flex");
expect(mobileTrigger).toHaveClass("md:hidden");
expect(desktopTrigger?.tagName).toBe("BUTTON");
expect(desktopTrigger?.querySelector("input")).toBeNull();
desktopTrigger?.focus();
expect(desktopTrigger).toHaveFocus();
fireEvent.click(desktopTrigger!);
fireEvent.click(mobileTrigger!);
expect(commandPaletteToggle).toHaveBeenCalledTimes(2);
});
it("uses named native controls for shell icon actions", () => {
renderShell("app");
const sidebar = document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.appSidebar}"]`);
const collapseTrigger = sidebar?.querySelector("button");
const userMenu = document.querySelector(`[data-ui-id="${UI_ACTION_IDS.more}"]`);
expect(collapseTrigger).toHaveAttribute("aria-label");
expect(collapseTrigger?.getAttribute("aria-label")).not.toBe("");
// The bell's own contract moved to the admin-surface test above: without a
// tenant in scope the app layout has no notification target, so the bell is
// omitted rather than rendered as a dead link.
expect(userMenu?.tagName).toBe("BUTTON");
expect(userMenu).toHaveAttribute("aria-label");
expect(userMenu).toHaveClass("focus-visible:shadow-focus");
expect(userMenu).toBeEmptyDOMElement();
});
it("marks internal sidebar links for client-side navigation", () => {
mockedAppSidebarItems = [
{
id: "ui.nav.test.main",
title: "Main",
path: "",
items: [{ id: "ui.nav.test.target", title: "Target", path: "/target" }],
},
];
const router = createMemoryRouter(
[
{
path: "*",
element: (
<SubframeAppShell layout="app">
<section>Page content</section>
</SubframeAppShell>
),
},
],
{ initialEntries: ["/"] }
);
render(<RouterProvider router={router} />);
expect(screen.getByRole("link", { name: "Target" })).toHaveAttribute("data-navigation-kind", "client");
});
it("closes the mobile sidebar after internal navigation", () => {
mockedAppSidebarItems = [
{
id: "ui.nav.test.main",
title: "Main",
path: "",
items: [{ id: "ui.nav.test.target", title: "Target", path: "/target" }],
},
];
const router = createMemoryRouter(
[
{
path: "*",
element: (
<SubframeAppShell layout="app">
<section>Page content</section>
</SubframeAppShell>
),
},
],
{ initialEntries: ["/"] }
);
render(<RouterProvider router={router} />);
const sidebar = document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.appSidebar}"]`);
expect(sidebar).toHaveClass("max-md:-translate-x-full");
fireEvent.click(document.querySelector(`[data-ui-id="${UI_ACTION_IDS.sidebarTrigger}"]`)!);
expect(sidebar).toHaveClass("max-md:translate-x-0");
fireEvent.click(screen.getByRole("link", { name: "Target" }));
expect(sidebar).toHaveClass("max-md:-translate-x-full");
});
it("keeps the sidebar width independent from route content", () => {
renderShell("app");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.appSidebar}"]`)).toHaveClass("w-60", "shrink-0");
});
it("lets nested screens collapse the desktop sidebar without toggling it back open", () => {
const router = createMemoryRouter(
[
{
path: "/",
element: (
<SubframeAppShell layout="app">
<CollapseSidebarButton />
</SubframeAppShell>
),
},
],
{ initialEntries: ["/"] }
);
render(<RouterProvider router={router} />);
const sidebar = document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.appSidebar}"]`);
expect(sidebar).toHaveClass("w-60");
fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" }));
fireEvent.click(screen.getByRole("button", { name: "Collapse sidebar" }));
expect(sidebar).toHaveClass("w-16");
});
it("contains page scrolling inside the shell viewport", () => {
renderShell("app");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shell}"]`)).toHaveClass("h-screen", "overflow-hidden");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellInset}"]`)).toHaveClass("h-full", "min-h-0", "overflow-hidden");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.shellMain}"]`)).toHaveClass(
"min-h-0",
"flex-1",
"overflow-auto",
"overscroll-y-contain"
);
});
});
@@ -1,26 +1,20 @@
import { useMemo, useRef, useState } from "react";
import { useFetcher, useLocation, useNavigate, useParams, useSearchParams, useSubmit } from "react-router";
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Link, useFetcher, useLocation, useNavigate, useParams, useSearchParams, useSubmit } from "react-router";
import { useTranslation } from "react-i18next";
import {
FeatherBell,
FeatherLogOut,
FeatherMenu,
FeatherMoon,
FeatherSettings,
FeatherSun,
FeatherUserSearch,
} from "@subframe/core";
import { FeatherBell, FeatherLogOut, FeatherMenu, FeatherMoon, FeatherSearch, FeatherSettings, FeatherSun, FeatherUserSearch } from "@subframe/core";
import * as SubframeCore from "@subframe/core";
import { SidebarWithSections } from "~/ui/components/SidebarWithSections";
import { Breadcrumbs } from "~/ui/components/Breadcrumbs";
import { SearchInput } from "~/ui/components/SearchInput";
import { IconButton } from "~/ui/components/IconButton";
import { Avatar } from "~/ui/components/Avatar";
import { DropdownMenu } from "~/ui/components/DropdownMenu";
import { BadgeShortcut } from "~/ui/components/BadgeShortcut";
import { useCommandPalette } from "~/components/ui/commandPalettes/CommandPalette";
import { useTitleData } from "~/utils/data/useTitleData";
import { McpConnectLauncher } from "~/components/mcp/McpConnectLauncher";
import { NotificationToasts, useShellNotifications } from "~/components/notifications/NotificationToasts";
import { shouldShowParentNavCrumb, useBreadcrumbTrail, useTitleData } from "~/utils/data/useTitleData";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useRootData } from "~/utils/data/useRootData";
import { UI_ACTION_IDS, UI_SURFACE_IDS, getSidebarSurfaceId } from "~/application/ui/uiRegistry";
@@ -32,12 +26,20 @@ import { SidebarGroupDto } from "~/application/sidebar/SidebarGroupDto";
import UrlUtils from "~/utils/app/UrlUtils";
import UserDisplayUtils from "~/utils/app/UserDisplayUtils";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { adminPath, appPath } from "~/utils/app/CanonicalUrlUtils";
import { TenantUserType } from "~/application/enums/tenants/TenantUserType";
import { DARK_MODE_IN_APP } from "~/application/Constants";
import { RouteContentTransition } from "./RouteContentTransition";
import { useIsMobile } from "~/hooks/use-mobile";
import { AppShellSidebarContext } from "./AppShellSidebarContext";
import { useUiPreferences } from "./UiPreferencesContext";
type UiLayout = "app" | "admin" | "docs";
function isInternalNavigationPath(to: string) {
return to.startsWith("/") && !to.startsWith("//");
}
// D-D0a — App-Shell nach Davids Subframe-Design (DefaultPageLayout: SidebarWithSections + HeaderNavigation).
// Ersetzt die shadcn-Shell. Sidebar mit funktionierendem Collapse-Toggle; Topbar = Breadcrumb + Suchfeld
// (-> Cmd+K) + Notification-Bell + User-Avatar-Dropdown (Profil/Theme/Logout + "Arbeitsbereich wechseln"
@@ -51,18 +53,130 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
const appData = useAppOrAdminData();
const rootData = useRootData();
const title = useTitleData() ?? "";
const breadcrumbTrail = useBreadcrumbTrail();
const commandPalette = useCommandPalette();
const fetcher = useFetcher();
const submit = useSubmit();
const navigate = useNavigate();
const [searchParams] = useSearchParams();
const mainElement = useRef<HTMLElement>(null);
const sidebarElement = useRef<HTMLElement>(null);
const sidebarTriggerElement = useRef<HTMLButtonElement>(null);
const restoreMobileTriggerFocus = useRef(false);
const isMobile = useIsMobile();
const { preferences, preferencesReady } = useUiPreferences();
const shellNotifications = useShellNotifications(layout === "app" && params.tenant ? params.tenant : null);
const [collapsed, setCollapsed] = useState(false); // Desktop-Collapse (Davids Toggle)
const [mobileOpen, setMobileOpen] = useState(false); // Mobile-Drawer
const collapseSidebar = useCallback(() => {
restoreMobileTriggerFocus.current = false;
setCollapsed(true);
setMobileOpen(false);
}, []);
const collapseSidebarIfPreferred = useCallback(() => {
if (preferencesReady && preferences.autoCollapseSidebar) collapseSidebar();
}, [collapseSidebar, preferences.autoCollapseSidebar, preferencesReady]);
const sidebarControls = useMemo(
() => ({ collapseSidebar, collapseSidebarIfPreferred }),
[collapseSidebar, collapseSidebarIfPreferred]
);
const sidebarSurfaceId = getSidebarSurfaceId(layout);
function closeMobileSidebar({ restoreFocus = false }: { restoreFocus?: boolean } = {}) {
restoreMobileTriggerFocus.current = restoreFocus;
setMobileOpen(false);
}
useEffect(() => {
if (!isMobile || !mobileOpen) {
if (restoreMobileTriggerFocus.current) {
restoreMobileTriggerFocus.current = false;
window.requestAnimationFrame(() => sidebarTriggerElement.current?.focus());
}
return;
}
const sidebar = sidebarElement.current;
if (!sidebar) return;
const focusableSelector = [
"a[href]",
"button:not([disabled])",
"input:not([disabled])",
"select:not([disabled])",
"textarea:not([disabled])",
'[tabindex]:not([tabindex="-1"])',
].join(",");
const focusableItems = () =>
Array.from(sidebar.querySelectorAll<HTMLElement>(focusableSelector)).filter(
(element) => element.getClientRects().length > 0 && window.getComputedStyle(element).visibility !== "hidden"
);
window.requestAnimationFrame(() => focusableItems()[0]?.focus());
function handleKeyDown(event: KeyboardEvent) {
if (event.key === "Escape") {
event.preventDefault();
closeMobileSidebar({ restoreFocus: true });
return;
}
if (event.key !== "Tab") return;
const items = focusableItems();
if (items.length === 0) {
event.preventDefault();
return;
}
const first = items[0];
const last = items.at(-1)!;
if (event.shiftKey && document.activeElement === first) {
event.preventDefault();
last.focus();
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault();
first.focus();
}
}
document.addEventListener("keydown", handleKeyDown);
return () => document.removeEventListener("keydown", handleKeyDown);
}, [isMobile, mobileOpen]);
useEffect(() => {
function handleSidebarShortcut(event: KeyboardEvent) {
if (!isMobile || event.key.toLowerCase() !== "e" || (!event.ctrlKey && !event.metaKey)) return;
event.preventDefault();
if (mobileOpen) {
closeMobileSidebar({ restoreFocus: true });
} else {
setMobileOpen(true);
}
}
document.addEventListener("keydown", handleSidebarShortcut);
return () => document.removeEventListener("keydown", handleSidebarShortcut);
}, [isMobile, mobileOpen]);
// How much of the viewport the sidebar takes, published for chrome that sits
// outside this shell — the save toast centres over the content rather than
// over the whole window. On mobile the sidebar is off-canvas and takes none.
useEffect(() => {
const root = document.documentElement;
root.style.setProperty("--app-content-inset-left", isMobile ? "0px" : collapsed ? "4rem" : "15rem");
return () => {
root.style.removeProperty("--app-content-inset-left");
};
}, [collapsed, isMobile]);
// Notification target per surface. `null` means the surface has no notification
// centre, and the bell is then omitted rather than rendered as a dead link.
const notificationsHref =
layout === "admin" ? adminPath("notifications", { mode: "host-aware" }) : params.tenant ? UrlUtils.currentTenantUrl(params, "notifications") : null;
// ---- Menü bauen (identisches Gating wie shadcn-Shell) ----
function getPath(item: SideBarItem): string {
return UrlUtils.replaceVariables(params, item.path) ?? "";
@@ -77,7 +191,15 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
return exact ? currentPath === itemPath : currentPath === itemPath || currentPath.startsWith(`${itemPath}/`);
}
function isCurrent(item: SideBarItem): boolean {
return pathMatchesCurrent(getPath(item), item.exact);
// excludePaths trump activePaths: a broad prefix match (e.g. Boards on
// /projects) must not light up on sibling entries' subroutes (Plantafel).
if (item.excludePaths?.some((path) => pathMatchesCurrent(UrlUtils.replaceVariables(params, path) ?? path))) {
return false;
}
return (
pathMatchesCurrent(getPath(item), item.exact) ||
(item.activePaths?.some((path) => pathMatchesCurrent(UrlUtils.replaceVariables(params, path) ?? path)) ?? false)
);
}
function currentIsChild(item: SideBarItem): boolean {
return item.items?.some((child) => isCurrent(child) || currentIsChild(child)) ?? false;
@@ -100,14 +222,24 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
return !item.tenantUserTypes || (currentRole !== null && item.tenantUserTypes.includes(currentRole));
}
function checkUserRolePermissions(item: SideBarItem) {
return !item.permission || getUserHasPermission(appData, item.permission);
const hasRequired = !item.permission || getUserHasPermission(appData, item.permission);
const hasAny = !item.anyPermissions || item.anyPermissions.some((permission) => getUserHasPermission(appData, permission));
return hasRequired && hasAny;
}
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((c): c is SideBarItem => c !== null) ?? [];
const contextItems = item.contextItems?.map((child) => getVisibleItem(child)).filter((c): c is SideBarItem => c !== null) ?? [];
const hasPermission = checkUserRolePermissions(item);
if (!hasPermission && items.length === 0) return null;
return { ...item, path: hasPermission ? item.path : "", redirectTo: hasPermission ? item.redirectTo : undefined, items };
if ((!hasPermission && items.length === 0 && contextItems.length === 0) || ((item.contextItems?.length ?? 0) > 0 && contextItems.length === 0)) return null;
const ownPathVisible = contextItems.some((child) => child.path === item.path);
return {
...item,
path: hasPermission && (contextItems.length === 0 || ownPathVisible) ? item.path : (contextItems[0]?.path ?? ""),
redirectTo: hasPermission ? item.redirectTo : undefined,
items,
contextItems,
};
}
function getMenuItems(): SideBarItem[] {
let menu: SideBarItem[] = [];
@@ -138,9 +270,66 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [layout, menuItems, location.pathname, params.tenant, appData?.productAccess]);
// Same entitlement decision the MCP runtime enforces server-side; the topbar
// entry must not advertise a connector the tenant cannot use.
const canConnectMcp = "productAccess" in appData ? appData.productAccess?.["mcp"]?.allowed === true : false;
const navMain = menu.filter((g) => g.type === "main");
const navSecondary = menu.filter((g) => g.type === "secondary");
// Sidebar entry responsible for the current route (longest matching own path
// or activePaths prefix, excludePaths respected — e.g. Plantafel over Boards).
// Used as crumb fallback for routes without a loader title and as clickable
// parent crumb on sub-pages.
const activeNavItem = useMemo(() => {
const flat: SideBarItem[] = [];
const walk = (items: SideBarItem[]) =>
items.forEach((item) => {
flat.push(item);
if (item.items) walk(item.items);
});
menu.forEach((group) => walk(group.items));
const currentPath = normalizePath(location.pathname);
const matchLength = (rawPath: string | undefined): number => {
const candidate = normalizePath(rawPath ?? "");
if (!candidate) return 0;
return currentPath === candidate || currentPath.startsWith(`${candidate}/`) ? candidate.length : 0;
};
let best: { title: string; path: string; length: number; contextPaths: (string | undefined)[] } | null = null;
for (const item of flat) {
if (item.excludePaths?.some((path) => matchLength(path) > 0)) continue;
const length = Math.max(matchLength(item.path), ...(item.activePaths?.map(matchLength) ?? [0]));
if (length > 0 && (!best || length > best.length)) {
best = {
title: item.title?.toString() ?? "",
path: normalizePath(item.path ?? ""),
length,
// Pages with their own row in the inner sub-sidenav do not get this
// entry as a parent crumb — see shouldShowParentNavCrumb.
contextPaths: item.contextItems?.map((context) => context.path) ?? [],
};
}
}
return best;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [menu, location.pathname]);
const currentCrumbLabel = breadcrumbTrail.at(-1)?.label || title || activeNavItem?.title || t("app.sidebar.dashboard");
// Clickable parent crumb on sub-pages: the responsible nav entry, unless it
// IS the current page or already covered by the trail (by label or by path).
const parentNavCrumb =
activeNavItem &&
shouldShowParentNavCrumb({
navPath: activeNavItem.path,
navTitle: activeNavItem.title,
currentPathname: location.pathname,
currentCrumbLabel,
trail: breadcrumbTrail,
navContextPaths: activeNavItem.contextPaths,
})
? activeNavItem
: null;
// ---- User + Theme-Toggle + Tenant-Switch ----
const isDarkMode = rootData.userSession?.lightOrDarkMode === "dark";
function onThemeToggle() {
@@ -164,30 +353,72 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
function renderNavItem(item: SideBarItem) {
const href = item.redirectTo || item.path;
const label = item.title?.toString() ?? "";
return (
<a key={item.id ?? href ?? label} href={href || undefined} title={label} className="w-full no-underline" {...uiIdAttrs(item)}>
<SidebarWithSections.NavItem
icon={item.icon}
selected={item.isActive}
variant={collapsed ? "icon-only" : "icon-and-text"}
className={item.disabled ? "pointer-events-none opacity-50" : undefined}
const navContent = (
<SidebarWithSections.NavItem
icon={item.icon}
selected={item.isActive}
variant={collapsed ? "icon-only" : "icon-and-text"}
className={item.disabled ? "pointer-events-none opacity-50" : undefined}
>
{label}
</SidebarWithSections.NavItem>
);
if (href && isInternalNavigationPath(href)) {
return (
<Link
key={item.id ?? href ?? label}
to={href}
title={label}
className="w-full no-underline"
data-navigation-kind="client"
onClick={() => setMobileOpen(false)}
{...uiIdAttrs(item)}
>
{label}
</SidebarWithSections.NavItem>
{navContent}
</Link>
);
}
return (
<a
key={item.id ?? href ?? label}
href={href || undefined}
title={label}
className="w-full no-underline"
data-navigation-kind="document"
onClick={() => setMobileOpen(false)}
{...uiIdAttrs(item)}
>
{navContent}
</a>
);
}
return (
<div className="flex h-screen w-full items-stretch bg-surface-neutral-primary" data-ui-id={UI_SURFACE_IDS.shell}>
<AppShellSidebarContext.Provider value={sidebarControls}>
<div className="bg-surface-neutral-primary flex h-screen w-full items-stretch overflow-hidden" data-ui-id={UI_SURFACE_IDS.shell}>
{/* Mobile-Backdrop */}
{mobileOpen ? <div className="fixed inset-0 z-40 bg-surface-neutral-overlay md:hidden" onClick={() => setMobileOpen(false)} aria-hidden /> : null}
{mobileOpen ? (
<div className="bg-surface-neutral-overlay fixed inset-0 z-40 md:hidden" onClick={() => closeMobileSidebar({ restoreFocus: true })} aria-hidden />
) : null}
<SidebarWithSections
ref={sidebarElement}
data-ui-id={sidebarSurfaceId}
data-ui-layout={layout}
role={isMobile ? "dialog" : undefined}
aria-modal={isMobile && mobileOpen ? true : undefined}
aria-hidden={isMobile && !mobileOpen ? true : undefined}
aria-label={isMobile ? t("components.sidebar.title") : undefined}
inert={isMobile && !mobileOpen}
variant={collapsed ? "closed" : "open"}
onToggleCollapse={() => setCollapsed((v) => !v)}
toggleLabel={t("components.sidebar.toggle")}
onLogoClick={
layout === "app" && params.tenant
? () => navigate(appPath({ tenantSlug: params.tenant!, path: "dashboard", mode: "host-aware" }))
: undefined
}
logoLabel={t("app.sidebar.dashboard")}
className={SubframeCore.twClassNames(
"z-50 max-md:fixed max-md:inset-y-0 max-md:left-0 max-md:transition-transform",
mobileOpen ? "max-md:translate-x-0" : "max-md:-translate-x-full"
@@ -195,12 +426,7 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
>
<div data-ui-id={`${sidebarSurfaceId}.content`} className="flex w-full flex-col gap-1">
{navMain.map((group) => (
<SidebarWithSections.NavSection
key={group.id ?? group.title}
label={group.title}
showLabel={!collapsed && !!group.title}
{...uiIdAttrs(group)}
>
<SidebarWithSections.NavSection key={group.id ?? group.title} label={group.title} showLabel={!collapsed && !!group.title} {...uiIdAttrs(group)}>
{group.items.map((item) => renderNavItem(item))}
</SidebarWithSections.NavSection>
))}
@@ -209,17 +435,24 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
</div>
</SidebarWithSections>
<div className="flex h-full min-w-0 grow flex-col" data-ui-id={UI_SURFACE_IDS.shellInset}>
{/* macOS-style unread-notification toasts, top-right below the header. */}
{layout === "app" && params.tenant ? <NotificationToasts tenantSlug={params.tenant} items={shellNotifications.items} /> : null}
<div className="flex h-full min-h-0 min-w-0 grow flex-col overflow-hidden" data-ui-id={UI_SURFACE_IDS.shellInset}>
{/* Topbar (Davids HeaderNavigation: Breadcrumb + Suche + Bell + Avatar) */}
<header
className="flex h-14 w-full shrink-0 items-center justify-between gap-2 border-b border-solid border-border-default bg-surface-neutral-secondary pl-6 pr-3 py-3 mobile:px-4"
className="border-border-default bg-surface-neutral-secondary mobile:px-4 flex h-14 w-full shrink-0 items-center justify-between gap-2 border-b border-solid py-3 pr-3 pl-6"
data-ui-id={UI_SURFACE_IDS.shellHeader}
>
<div className="flex min-w-0 items-center gap-3" data-ui-id={UI_SURFACE_IDS.shellBreadcrumb}>
<button
ref={sidebarTriggerElement}
type="button"
className="inline-flex h-8 w-8 items-center justify-center rounded-md text-icon-neutral-secondary hover:bg-surface-neutral-tertiary md:hidden"
onClick={() => setMobileOpen((v) => !v)}
className="text-icon-neutral-secondary hover:bg-surface-neutral-tertiary inline-flex h-8 w-8 items-center justify-center rounded-md md:hidden"
onClick={() => {
if (mobileOpen) closeMobileSidebar({ restoreFocus: true });
else setMobileOpen(true);
}}
aria-label={t("shared.menu")}
data-ui-id={UI_ACTION_IDS.sidebarTrigger}
>
@@ -228,48 +461,119 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
<Breadcrumbs>
{currentTenant ? (
<>
<Breadcrumbs.Item>{currentTenant.name}</Breadcrumbs.Item>
{layout === "app" && params.tenant ? (
<Link to={appPath({ tenantSlug: params.tenant, path: "dashboard", mode: "host-aware" })} className="no-underline">
<Breadcrumbs.Item className="text-text-neutral-secondary">{currentTenant.name}</Breadcrumbs.Item>
</Link>
) : (
<Breadcrumbs.Item className="text-text-neutral-secondary">{currentTenant.name}</Breadcrumbs.Item>
)}
<Breadcrumbs.Divider />
</>
) : null}
{parentNavCrumb ? (
<>
<Link to={parentNavCrumb.path} className="no-underline">
<Breadcrumbs.Item className="text-text-neutral-secondary">{parentNavCrumb.title}</Breadcrumbs.Item>
</Link>
<Breadcrumbs.Divider />
</>
) : null}
{breadcrumbTrail.slice(0, -1).map((crumb) => (
<Fragment key={crumb.href}>
<Link to={crumb.href} className="no-underline">
<Breadcrumbs.Item className="text-text-neutral-secondary">{crumb.label}</Breadcrumbs.Item>
</Link>
<Breadcrumbs.Divider />
</Fragment>
))}
<Breadcrumbs.Item active data-ui-id={UI_SURFACE_IDS.shellBreadcrumbCurrent}>
{title || t("app.sidebar.dashboard")}
{currentCrumbLabel}
</Breadcrumbs.Item>
</Breadcrumbs>
</div>
<div className="flex items-center gap-2 self-stretch pl-1" data-ui-id={UI_SURFACE_IDS.shellNavActions}>
<div
role="button"
tabIndex={0}
className="hidden cursor-pointer md:flex md:min-w-[192px] md:max-w-[320px] md:grow"
{/*
MCP lives left of the search bar: connecting an AI client is a
per-user setup step, not a navigation target, so it stays out of
the sidebar. Hidden entirely when the tenant has no MCP module.
*/}
{layout === "app" && params.tenant && canConnectMcp ? <McpConnectLauncher tenantSlug={params.tenant} /> : null}
<button
type="button"
className="border-border-strong bg-surface-neutral-primary text-text-neutral-secondary hover:bg-surface-neutral-secondary focus-visible:bg-surface-neutral-secondary focus-visible:shadow-focus hidden h-8 min-w-[192px] cursor-pointer items-center gap-2.5 rounded-sm border px-3 text-left outline-none md:flex md:max-w-[320px] md:grow"
onClick={() => commandPalette.toggle()}
onKeyDown={(event) => {
if (event.key === "Enter" || event.key === " ") {
event.preventDefault();
commandPalette.toggle();
}
}}
aria-label={t("shared.search")}
data-ui-id={UI_ACTION_IDS.search}
>
<SearchInput className="pointer-events-none h-auto w-full min-w-0 max-w-none" size="small" fillContainer placeholder={t("shared.searchPlaceholder")} />
</div>
<a href={params.tenant ? UrlUtils.currentTenantUrl(params, "notifications") : "#"} aria-label={t("app.sidebar.notifications", { defaultValue: "Notifications" })} data-ui-id={UI_ACTION_IDS.notifications}>
<IconButton variant="ghost" size="small" icon={<FeatherBell />} />
</a>
<FeatherSearch className="text-icon-neutral-tertiary size-4 shrink-0" />
<span className="text-body-default-regular-0 font-body-default-regular-0 min-w-0 grow truncate">{t("shared.searchPlaceholder")}</span>
<BadgeShortcut className="shrink-0">K</BadgeShortcut>
</button>
<IconButton
variant="ghost"
size="small"
icon={<FeatherSearch />}
className="md:hidden"
onClick={() => commandPalette.toggle()}
aria-label={t("shared.search")}
data-ui-id={UI_ACTION_IDS.searchMobile}
/>
{/*
The bell used to fall back to `href="#"` whenever no tenant was in
scope, which made it a dead link on every admin page (admin audit
2026-07-26, A11Y-01). The admin surface has its own notification
centre, so each layout now points at its own target.
*/}
{notificationsHref ? (
<Link
to={notificationsHref}
aria-label={t("app.sidebar.notifications", { defaultValue: "Notifications" })}
className="hover:bg-surface-neutral-tertiary rounded-round focus-visible:shadow-focus relative flex h-8 w-8 items-center justify-center focus-visible:outline-none"
data-ui-id={UI_ACTION_IDS.notifications}
>
<SubframeCore.IconWrapper
aria-hidden="true"
className="text-icon-neutral-secondary inline-flex h-5 w-5 items-center justify-center [&>svg]:h-full [&>svg]:w-full"
>
<FeatherBell />
</SubframeCore.IconWrapper>
{shellNotifications.unreadCount > 0 ? (
<span
className="rounded-round bg-surface-feedback-solid-information text-text-neutral-on-solid absolute -top-0.5 -right-0.5 flex h-4 min-w-4 items-center justify-center px-1 text-[10px] leading-none font-semibold"
data-ui-id="ui.notifications.bell.unreadCount"
>
{shellNotifications.unreadCount > 9 ? "9+" : shellNotifications.unreadCount}
</span>
) : null}
</Link>
) : null}
{user ? (
<SubframeCore.DropdownMenu.Root>
<SubframeCore.DropdownMenu.Trigger asChild>
<Avatar className="cursor-pointer" border image={user.avatar ?? undefined} data-ui-id={UI_ACTION_IDS.more}>
<SubframeCore.DropdownMenu.Root modal={false}>
<div className="relative">
<Avatar aria-hidden="true" className="cursor-pointer" border image={user.avatar ?? undefined}>
{UserDisplayUtils.avatarText(user)}
</Avatar>
</SubframeCore.DropdownMenu.Trigger>
<SubframeCore.DropdownMenu.Trigger asChild>
<button
type="button"
aria-label={t("shell.profile.userMenu")}
className="rounded-round focus-visible:shadow-focus absolute inset-0 border-0 bg-transparent p-0 focus-visible:outline-none"
data-ui-id={UI_ACTION_IDS.more}
/>
</SubframeCore.DropdownMenu.Trigger>
</div>
<SubframeCore.DropdownMenu.Portal>
<SubframeCore.DropdownMenu.Content side="bottom" align="end" sideOffset={4} asChild>
<DropdownMenu className="min-w-56">
<DropdownMenu.DropdownUserItem title={UserDisplayUtils.fullName(user)} subtitle={user.email} image={user.avatar ?? undefined} />
<DropdownMenu.DropdownUserItem
title={UserDisplayUtils.fullName(user)}
subtitle={user.email}
image={user.avatar ?? undefined}
initials={UserDisplayUtils.avatarText(user)}
/>
<DropdownMenu.DropdownDivider />
{layout === "app" && params.tenant ? (
<DropdownMenu.DropdownItem
@@ -292,11 +596,24 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
<>
<DropdownMenu.DropdownDivider />
<DropdownMenu.DropdownNestedItem label={t("account.selectTenant.title")} icon={<FeatherUserSearch />}>
{myTenants.map((tenant) => (
<a key={tenant.id} href={appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" })} className="no-underline">
<DropdownMenu.DropdownItem selected={tenant.id === currentTenant.id}>{tenant.name}</DropdownMenu.DropdownItem>
</a>
))}
{/* The anchors are inline by default, which cut the selected row's
background off after the tenant name. `block w-full` lets each row
span the card like the trigger above it; the padding keeps the
expanded list from sitting flush against the trigger and the card edge. */}
<div className="flex w-full flex-col gap-1 pt-2 pb-1">
{myTenants.map((tenant) => (
<a
key={tenant.id}
href={appPath({ tenantSlug: tenant.slug, path: "dashboard", mode: "host-aware" })}
className="block w-full no-underline"
>
{/* pl-9 lines the tenant name up with the trigger's label (px-3 + icon + gap). */}
<DropdownMenu.DropdownItem className="py-1.5 pr-3 pl-9" selected={tenant.id === currentTenant.id}>
{tenant.name}
</DropdownMenu.DropdownItem>
</a>
))}
</div>
</DropdownMenu.DropdownNestedItem>
</>
) : null}
@@ -308,13 +625,21 @@ export default function SubframeAppShell({ children, layout, menuItems }: { chil
</div>
</header>
<main id="main-content" ref={mainElement} className="flex-1 overflow-auto 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
id="main-content"
ref={mainElement}
// scrollbar-gutter: stable reserves the scrollbar's space so the content
// column does not shift sideways when a route toggles the vertical
// scrollbar (no horizontal "bounce"). No-op with macOS overlay scrollbars.
className="min-h-0 flex-1 overflow-auto overscroll-y-contain [scrollbar-gutter:stable] focus:outline-hidden"
tabIndex={-1}
data-ui-id={UI_SURFACE_IDS.shellMain}
>
<RouteContentTransition>{children}</RouteContentTransition>
</main>
</div>
</div>
</div>
</AppShellSidebarContext.Provider>
);
}
@@ -0,0 +1,113 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { UI_PREFERENCES_STORAGE_KEY, UiPreferencesProvider, useUiPreferences } from "./UiPreferencesContext";
const originalLocalStorage = Object.getOwnPropertyDescriptor(window, "localStorage");
const originalGetAnimations = document.getAnimations;
function memoryStorage(): Storage {
const values = new Map<string, string>();
return {
get length() {
return values.size;
},
clear: () => values.clear(),
getItem: (key) => values.get(key) ?? null,
key: (index) => [...values.keys()][index] ?? null,
removeItem: (key) => values.delete(key),
setItem: (key, value) => values.set(key, value),
};
}
function PreferenceControls() {
const { preferences, preferencesReady, setAutoCollapseSidebar, setVisualEffectsEnabled } = useUiPreferences();
return (
<>
<output>ready:{String(preferencesReady)}</output>
<button onClick={() => setAutoCollapseSidebar(!preferences.autoCollapseSidebar)}>
auto:{String(preferences.autoCollapseSidebar)}
</button>
<button onClick={() => setVisualEffectsEnabled(!preferences.visualEffectsEnabled)}>
effects:{String(preferences.visualEffectsEnabled)}
</button>
</>
);
}
describe("UiPreferencesProvider", () => {
beforeEach(() => {
Object.defineProperty(window, "localStorage", { configurable: true, value: memoryStorage() });
});
afterEach(() => {
if (originalLocalStorage) Object.defineProperty(window, "localStorage", originalLocalStorage);
else delete (window as Partial<Window>).localStorage;
document.getAnimations = originalGetAnimations;
delete document.documentElement.dataset.hgVisualEffects;
vi.restoreAllMocks();
});
it("restores browser-local preferences and applies the visual-effects mode", async () => {
window.localStorage.setItem(
UI_PREFERENCES_STORAGE_KEY,
JSON.stringify({ autoCollapseSidebar: false, visualEffectsEnabled: false })
);
const cancel = vi.fn();
document.getAnimations = vi.fn(() => [{ cancel }] as unknown as Animation[]);
render(
<UiPreferencesProvider>
<PreferenceControls />
</UiPreferencesProvider>
);
await waitFor(() => expect(screen.getByRole("button", { name: "auto:false" })).toBeInTheDocument());
expect(screen.getByText("ready:true")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "effects:false" })).toBeInTheDocument();
expect(document.documentElement).toHaveAttribute("data-hg-visual-effects", "off");
expect(cancel).toHaveBeenCalledOnce();
});
it("does not expose the default auto-collapse value as ready before stored preferences load", async () => {
window.localStorage.setItem(
UI_PREFERENCES_STORAGE_KEY,
JSON.stringify({ autoCollapseSidebar: false, visualEffectsEnabled: true })
);
const renderStates: Array<{ ready: boolean; autoCollapse: boolean }> = [];
function PreferenceLifecycleProbe() {
const { preferences, preferencesReady } = useUiPreferences();
renderStates.push({ ready: preferencesReady, autoCollapse: preferences.autoCollapseSidebar });
return null;
}
render(
<UiPreferencesProvider>
<PreferenceLifecycleProbe />
</UiPreferencesProvider>
);
await waitFor(() => expect(renderStates.at(-1)).toEqual({ ready: true, autoCollapse: false }));
expect(renderStates).not.toContainEqual({ ready: true, autoCollapse: true });
});
it("persists changes and enables or disables effects immediately", () => {
render(
<UiPreferencesProvider>
<PreferenceControls />
</UiPreferencesProvider>
);
fireEvent.click(screen.getByRole("button", { name: "auto:true" }));
fireEvent.click(screen.getByRole("button", { name: "effects:true" }));
expect(JSON.parse(window.localStorage.getItem(UI_PREFERENCES_STORAGE_KEY) ?? "{}")).toEqual({
autoCollapseSidebar: false,
visualEffectsEnabled: false,
});
expect(document.documentElement).toHaveAttribute("data-hg-visual-effects", "off");
});
});
@@ -0,0 +1,110 @@
import { createContext, useCallback, useContext, useLayoutEffect, useMemo, useState, type ReactNode } from "react";
export type UiPreferences = {
autoCollapseSidebar: boolean;
visualEffectsEnabled: boolean;
};
export const UI_PREFERENCES_STORAGE_KEY = "hg.ui-preferences.v1";
export const DEFAULT_UI_PREFERENCES: UiPreferences = {
autoCollapseSidebar: true,
visualEffectsEnabled: true,
};
type UiPreferencesContextValue = {
preferences: UiPreferences;
preferencesReady: boolean;
setAutoCollapseSidebar: (enabled: boolean) => void;
setVisualEffectsEnabled: (enabled: boolean) => void;
};
const NOOP_CONTEXT: UiPreferencesContextValue = {
preferences: DEFAULT_UI_PREFERENCES,
preferencesReady: true,
setAutoCollapseSidebar: () => undefined,
setVisualEffectsEnabled: () => undefined,
};
const UiPreferencesContext = createContext<UiPreferencesContextValue>(NOOP_CONTEXT);
function parseStoredPreferences(raw: string | null): UiPreferences {
if (!raw) return DEFAULT_UI_PREFERENCES;
try {
const value = JSON.parse(raw) as Partial<UiPreferences>;
return {
autoCollapseSidebar:
typeof value.autoCollapseSidebar === "boolean" ? value.autoCollapseSidebar : DEFAULT_UI_PREFERENCES.autoCollapseSidebar,
visualEffectsEnabled:
typeof value.visualEffectsEnabled === "boolean" ? value.visualEffectsEnabled : DEFAULT_UI_PREFERENCES.visualEffectsEnabled,
};
} catch {
return DEFAULT_UI_PREFERENCES;
}
}
function readStoredPreferences(): UiPreferences {
try {
return parseStoredPreferences(window.localStorage.getItem(UI_PREFERENCES_STORAGE_KEY));
} catch {
return DEFAULT_UI_PREFERENCES;
}
}
function applyVisualEffectsPreference(enabled: boolean): void {
if (typeof document === "undefined") return;
document.documentElement.dataset.hgVisualEffects = enabled ? "on" : "off";
if (!enabled) document.getAnimations?.().forEach((animation) => animation.cancel());
}
export function UiPreferencesProvider({ children }: { children: ReactNode }): React.JSX.Element {
const [preferences, setPreferences] = useState<UiPreferences>(DEFAULT_UI_PREFERENCES);
const [preferencesReady, setPreferencesReady] = useState(false);
useLayoutEffect(() => {
const stored = readStoredPreferences();
setPreferences(stored);
setPreferencesReady(true);
applyVisualEffectsPreference(stored.visualEffectsEnabled);
const handleStorage = (event: StorageEvent) => {
if (event.key !== UI_PREFERENCES_STORAGE_KEY) return;
const next = parseStoredPreferences(event.newValue);
setPreferences(next);
applyVisualEffectsPreference(next.visualEffectsEnabled);
};
window.addEventListener("storage", handleStorage);
return () => window.removeEventListener("storage", handleStorage);
}, []);
const updatePreferences = useCallback((patch: Partial<UiPreferences>) => {
setPreferencesReady(true);
setPreferences((current) => {
const next = { ...current, ...patch };
try {
window.localStorage.setItem(UI_PREFERENCES_STORAGE_KEY, JSON.stringify(next));
} catch {
// A blocked storage API must not make a purely visual preference fatal.
}
applyVisualEffectsPreference(next.visualEffectsEnabled);
return next;
});
}, []);
const value = useMemo<UiPreferencesContextValue>(
() => ({
preferences,
preferencesReady,
setAutoCollapseSidebar: (enabled) => updatePreferences({ autoCollapseSidebar: enabled }),
setVisualEffectsEnabled: (enabled) => updatePreferences({ visualEffectsEnabled: enabled }),
}),
[preferences, preferencesReady, updatePreferences]
);
return <UiPreferencesContext.Provider value={value}>{children}</UiPreferencesContext.Provider>;
}
export function useUiPreferences(): UiPreferencesContextValue {
return useContext(UiPreferencesContext);
}
@@ -3,10 +3,12 @@ import { useTranslation } from "react-i18next";
import Modal from "~/components/ui/modals/Modal";
import { LogWithDetails } from "~/utils/db/logs.db.server";
import { redactDiagnosticJsonString } from "~/utils/redaction";
import { useCopyToast } from "~/hooks/use-copy-toast";
export default function LogDetailsButton({ item }: { item: LogWithDetails }) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const copyText = useCopyToast();
function stringifyDetails() {
return redactDiagnosticJsonString(item.details);
@@ -27,9 +29,7 @@ export default function LogDetailsButton({ item }: { item: LogWithDetails }) {
<div>
<button
type="button"
onClick={() => {
navigator.clipboard.writeText(stringifyDetails());
}}
onClick={() => void copyText(stringifyDetails(), { successKey: "models.log.detailsCopied" })}
className="bg-theme-100 text-theme-700 hover:bg-theme-200 focus:ring-ring inline-flex items-center rounded-md border border-transparent px-3 py-2 text-sm font-medium leading-4 focus:outline-hidden focus:ring-2 focus:ring-offset-2"
>
{t("shared.copy")}
@@ -90,7 +90,8 @@ describe("log action i18n", () => {
.filter((action): action is string => typeof action === "string");
});
expect(actions).toEqual(expect.arrayContaining(["admin.pricing.plan.created", "portal.pricing.plan.updated"]));
expect(actions).toEqual(expect.arrayContaining(["admin.pricing.plan.created", "admin.pricing.deletedPlan"]));
expect(actions).not.toContain("admin.pricing.createdPlans");
for (const action of actions) {
expect(getLogActionI18nKey(action), action).toBeDefined();
}
@@ -42,33 +42,33 @@ describe("AdminAuditLogToolbar", () => {
expect(screen.getByText("models.tenant.object")).toBeInTheDocument();
});
it("preserves active filters while replacing stale pagination with CSV export", () => {
it("preserves active filters while dropping stale pagination on the export href", () => {
renderToolbar("/audit-trails?q=login&action=auth&url=%2Flogin&tenantId=tenant-1&page=3&pageSize=25");
const exportUrl = new URL(screen.getByRole("link", { name: "Export" }).getAttribute("href") ?? "", "https://example.test");
expect(exportUrl.pathname).toBe("/audit-trails");
expect(exportUrl.pathname).toBe("/audit-trails-export");
expect(exportUrl.searchParams.get("q")).toBe("login");
expect(exportUrl.searchParams.get("action")).toBe("auth");
expect(exportUrl.searchParams.get("url")).toBe("/login");
expect(exportUrl.searchParams.get("tenantId")).toBe("tenant-1");
expect(exportUrl.searchParams.get("pageSize")).toBe("25");
expect(exportUrl.searchParams.get("page")).toBeNull();
expect(exportUrl.searchParams.get("export")).toBe("csv");
});
it("replaces an existing export value with csv", () => {
it("drops a stale export param from the current search", () => {
renderToolbar("/audit-trails?export=json&userId=user-1");
const exportUrl = new URL(screen.getByRole("link", { name: "Export" }).getAttribute("href") ?? "", "https://example.test");
expect(exportUrl.pathname).toBe("/audit-trails-export");
expect(exportUrl.searchParams.get("userId")).toBe("user-1");
expect(exportUrl.searchParams.get("export")).toBe("csv");
expect(exportUrl.searchParams.get("export")).toBeNull();
});
it("creates a valid CSV export href without existing search params", () => {
renderToolbar("/audit-trails");
expect(screen.getByRole("link", { name: "Export" })).toHaveAttribute("href", "/audit-trails?export=csv");
expect(screen.getByRole("link", { name: "Export" })).toHaveAttribute("href", "/audit-trails-export");
});
});
@@ -15,8 +15,9 @@ export default function AdminAuditLogToolbar({ filters }: Props) {
const exportLabel = getFallbackTranslation(t("shared.export"), "Export");
const exportSearchParams = new URLSearchParams(location.search);
exportSearchParams.delete("page");
exportSearchParams.set("export", "csv");
const exportHref = adminPath(`audit-trails?${exportSearchParams.toString()}`, { mode: "host-aware" });
exportSearchParams.delete("export");
const exportQuery = exportSearchParams.toString();
const exportHref = adminPath(exportQuery ? `audit-trails-export?${exportQuery}` : "audit-trails-export", { mode: "host-aware" });
return (
<div className="flex items-center gap-2">
@@ -1,4 +1,4 @@
import type { ReactNode } from "react";
import type { ComponentProps, ReactNode } from "react";
import { twClassNames } from "~/ui/utils";
import { Card } from "~/ui/components/Card";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
@@ -9,9 +9,9 @@ type CardSize = "small" | "medium" | "large" | "extra-large";
type SubtitleVariant = "regular-0" | "regular-150" | "medium-150";
const SUBTITLE_CLS: Record<SubtitleVariant, string> = {
"regular-0": "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary",
"regular-150": "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary",
"medium-150": "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-tertiary",
"regular-0": "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary",
"regular-150": "text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary",
"medium-150": "text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-secondary",
};
// Gemeinsames Auth-Layout nach Davids WF-P2-Subframe-Auth-Screens (Login/Signup/Reset/2FA/Magic-Link):
@@ -30,6 +30,7 @@ export function AuthShell({
cardClassName = "max-w-[448px]",
showLogo = true,
logoIconOnly = false,
logoSize = "64",
titleAlign = "center",
headerGap = "gap-1.5",
subtitleVariant = "regular-150",
@@ -47,6 +48,8 @@ export function AuthShell({
showLogo?: boolean;
/** Icon-only-Logo (wie Davids Auth-Screens, Logo size=64 hideText) statt vollem Wortmarken-Logo. */
logoIconOnly?: boolean;
/** Visuelle Logo-Groesse. Auth-Defaults bleiben bei 64; breite Mehrschritt-Flows duerfen kompakter sein. */
logoSize?: ComponentProps<typeof Logo>["size"];
/** Titel-/Untertitel-Ausrichtung. David: Login=center, Signup/Forgot/Reset/2FA=start. */
titleAlign?: "center" | "start";
/** Abstand Titel<->Untertitel. David: S01 Login = gap-1.5, sonst gap-1. */
@@ -60,7 +63,7 @@ export function AuthShell({
className="flex min-h-screen w-full flex-col items-center justify-center gap-8 bg-surface-neutral-primary px-4 py-12 mobile:gap-6 mobile:py-6"
data-ui-id={dataUiId}
>
{showLogo ? <Logo size="64" showIcon={logoIconOnly || undefined} hideText={logoIconOnly || undefined} /> : null}
{showLogo ? <Logo size={logoSize} showIcon={logoIconOnly || undefined} hideText={logoIconOnly || undefined} /> : null}
<Card size={cardSize} variant="default" className={twClassNames("items-stretch", cardClassName)}>
<div className={twClassNames("flex w-full flex-col", headerGap, titleAlign === "center" ? "items-center" : "items-start")}>
<h1 className="text-heading- font-heading- text-text-neutral-primary">{title}</h1>
@@ -130,7 +133,7 @@ export function AuthDivider({ label, labelSize = "small" }: { label: ReactNode;
<div className="flex h-px grow shrink-0 basis-0 flex-col items-center bg-border-default" />
<span
className={twClassNames(
"text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary",
"text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary",
{
"text-body-extra-small-regular-150 font-body-extra-small-regular-150":
labelSize === "extra-small",
@@ -0,0 +1,61 @@
import "@testing-library/jest-dom";
import { cleanup, render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { afterEach, describe, expect, it, vi } from "vitest";
import Icon from "./Icon";
import Logo from "./Logo";
import LogoLightMode from "./LogoLightMode";
vi.mock("react-i18next", () => ({
useTranslation: () => ({
t: (key: string) => ({ "shared.icon": "Symbol", "shared.logo": "Logo" })[key] ?? key,
}),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
appConfiguration: {
app: { name: "HiveGrid" },
branding: {
icon: "/icon-light.svg",
iconDarkMode: "/icon-dark.svg",
logo: "/logo-light.svg",
logoDarkMode: "/logo-dark.svg",
},
},
}),
}));
afterEach(cleanup);
describe("brand asset alt text", () => {
it("localizes the configured product logo label", () => {
render(
<MemoryRouter>
<Logo />
</MemoryRouter>
);
expect(screen.getAllByAltText("HiveGrid Logo")).toHaveLength(2);
});
it("localizes the configured product icon label", () => {
render(
<MemoryRouter>
<Icon />
</MemoryRouter>
);
expect(screen.getAllByAltText("HiveGrid Symbol")).toHaveLength(2);
});
it("localizes the light-mode product logo label", () => {
render(
<MemoryRouter>
<LogoLightMode />
</MemoryRouter>
);
expect(screen.getByAltText("HiveGrid Logo")).toBeInTheDocument();
});
});
@@ -3,6 +3,7 @@ import { Link } from "react-router";
import { iconLight, iconDark } from "~/assets/brand/default";
import { useRootData } from "~/utils/data/useRootData";
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
interface Props {
className?: string;
@@ -12,17 +13,20 @@ interface Props {
export default function Icon({ className = "", size = "h-9", fromConfig = true }: Props) {
const { appConfiguration } = useRootData();
const { t } = useTranslation();
const productName = appConfiguration?.app?.name?.trim();
const iconAlt = productName ? `${productName} ${t("shared.icon")}` : t("shared.icon");
return (
<Link to="/" className={clsx(className, "flex")}>
{fromConfig && appConfiguration?.branding.icon ? (
<Fragment>
<img className={clsx(size, "hidden w-auto dark:block")} src={appConfiguration.branding.iconDarkMode ?? appConfiguration.branding.icon} alt="Icon" />
<img className={clsx(size, "w-auto dark:hidden")} src={appConfiguration.branding.icon} alt="Icon" />
<img className={clsx(size, "hidden w-auto dark:block")} src={appConfiguration.branding.iconDarkMode ?? appConfiguration.branding.icon} alt={iconAlt} />
<img className={clsx(size, "w-auto dark:hidden")} src={appConfiguration.branding.icon} alt={iconAlt} />
</Fragment>
) : (
<Fragment>
<img className={clsx(size, "hidden w-auto dark:block")} src={iconDark} alt="Logo" />
<img className={clsx(size, "w-auto dark:hidden")} src={iconLight} alt="Logo" />
<img className={clsx(size, "hidden w-auto dark:block")} src={iconDark} alt={iconAlt} />
<img className={clsx(size, "w-auto dark:hidden")} src={iconLight} alt={iconAlt} />
</Fragment>
)}
</Link>
@@ -3,6 +3,7 @@ import clsx from "clsx";
import { Link } from "react-router";
import { useRootData } from "~/utils/data/useRootData";
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
interface Props {
className?: string;
@@ -12,6 +13,9 @@ interface Props {
export default function Logo({ className = "", size = "h-9", to }: Props) {
const { appConfiguration } = useRootData();
const { t } = useTranslation();
const productName = appConfiguration?.app?.name?.trim();
const logoAlt = productName ? `${productName} ${t("shared.logo")}` : t("shared.logo");
return (
<Link to={to ?? "/"} className={clsx(className, "flex")}>
{/* <BrandLogo className="h-10 w-auto mx-auto" /> */}
@@ -20,14 +24,14 @@ export default function Logo({ className = "", size = "h-9", to }: Props) {
<img
className={clsx(size, "mx-auto hidden w-auto dark:block")}
src={appConfiguration.branding.logoDarkMode ?? appConfiguration.branding.logo}
alt="Logo"
alt={logoAlt}
/>
<img className={clsx(size, "mx-auto w-auto dark:hidden")} src={appConfiguration.branding.logo} alt="Logo" />
<img className={clsx(size, "mx-auto w-auto dark:hidden")} src={appConfiguration.branding.logo} alt={logoAlt} />
</Fragment>
) : (
<Fragment>
<img className={clsx(size, "mx-auto hidden w-auto dark:block")} src={logoDark} alt="Logo" />
<img className={clsx(size, "mx-auto w-auto dark:hidden")} src={logoLight} alt="Logo" />
<img className={clsx(size, "mx-auto hidden w-auto dark:block")} src={logoDark} alt={logoAlt} />
<img className={clsx(size, "mx-auto w-auto dark:hidden")} src={logoLight} alt={logoAlt} />
</Fragment>
)}
</Link>
@@ -3,6 +3,7 @@ import clsx from "clsx";
import { Link } from "react-router";
import { useRootData } from "~/utils/data/useRootData";
import { Fragment } from "react";
import { useTranslation } from "react-i18next";
interface Props {
className?: string;
@@ -12,16 +13,19 @@ interface Props {
export default function LogoLightMode({ className = "", size = "h-9", to }: Props) {
const { appConfiguration } = useRootData();
const { t } = useTranslation();
const productName = appConfiguration?.app?.name?.trim();
const logoAlt = productName ? `${productName} ${t("shared.logo")}` : t("shared.logo");
return (
<Link to={to ?? "/"} className={clsx(className, "flex")}>
{/* <BrandLogo className="h-10 w-auto mx-auto" /> */}
{appConfiguration?.branding.logo ? (
<Fragment>
<img className={clsx(size, "mx-auto w-auto")} src={appConfiguration.branding.logo} alt="Logo" />
<img className={clsx(size, "mx-auto w-auto")} src={appConfiguration.branding.logo} alt={logoAlt} />
</Fragment>
) : (
<Fragment>
<img className={clsx(size, "mx-auto w-auto")} src={logoLight} alt="Logo" />
<img className={clsx(size, "mx-auto w-auto")} src={logoLight} alt={logoAlt} />
</Fragment>
)}
</Link>
@@ -0,0 +1,30 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom/vitest";
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import Captcha from "./Captcha";
describe("Captcha CAP status contract", () => {
it("reports solve, reset and client errors to the enclosing form", () => {
const onStatusChange = vi.fn();
const { container } = render(
<Captcha enabled provider="cap" instanceUrl="https://captcha.example.test" sitekey="registration" onStatusChange={onStatusChange} />
);
const widget = container.querySelector("cap-widget");
expect(widget).not.toBeNull();
expect(onStatusChange).toHaveBeenLastCalledWith("pending");
widget!.dispatchEvent(new CustomEvent("solve"));
expect(onStatusChange).toHaveBeenLastCalledWith("solved");
widget!.dispatchEvent(new CustomEvent("reset"));
expect(onStatusChange).toHaveBeenLastCalledWith("pending");
widget!.dispatchEvent(new CustomEvent("error"));
expect(onStatusChange).toHaveBeenLastCalledWith("error");
});
it("renders nothing when the public provider configuration is incomplete", () => {
const { container } = render(<Captcha enabled provider="cap" />);
expect(container).toBeEmptyDOMElement();
});
});
@@ -1,4 +1,6 @@
import { createElement, useEffect, useRef } from "react";
import type { Ref } from "react";
import { getCurrentDocumentCspNonce } from "~/utils/security/documentCspNonce";
interface Props {
/** Render the captcha widget. When false (or unconfigured) nothing is rendered. */
@@ -9,6 +11,8 @@ interface Props {
instanceUrl?: string;
/** Public sitekey for this surface. */
sitekey?: string;
/** Reports whether a reusable form may submit a fresh proof. */
onStatusChange?: (status: "pending" | "solved" | "error") => void;
}
// mCaptcha's vanilla glue mounts the widget into an element with this id and
@@ -23,13 +27,33 @@ const MOUNT_ID = "mcaptcha__widget-container";
* hidden token field (`cap-token` or `mcaptcha__token`), so it is submitted
* with the form and verified server-side by `@hivegrid/captcha`.
*
* Client load failures are non-fatal. The server verifier applies
* CAPTCHA_FAIL_OPEN for provider outages, while a missing token remains a hard
* failure when captcha is required.
* Client load failures leave the form unsolved. The server verifier fails
* closed in deployed runtimes; a local development/test process may explicitly
* opt into fail-open behavior.
*/
export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, sitekey }: Props) {
export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, sitekey, onStatusChange }: Props) {
const active = enabled && Boolean(instanceUrl && sitekey);
const initialized = useRef(false);
const capWidgetRef = useRef<HTMLElement | null>(null);
useEffect(() => {
if (!active) return;
onStatusChange?.("pending");
if (provider !== "cap") return;
const widget = capWidgetRef.current;
if (!widget) return;
const solved = () => onStatusChange?.("solved");
const reset = () => onStatusChange?.("pending");
const failed = () => onStatusChange?.("error");
widget.addEventListener("solve", solved);
widget.addEventListener("reset", reset);
widget.addEventListener("error", failed);
return () => {
widget.removeEventListener("solve", solved);
widget.removeEventListener("reset", reset);
widget.removeEventListener("error", failed);
};
}, [active, onStatusChange, provider]);
useEffect(() => {
if (!active || initialized.current) return;
@@ -62,15 +86,16 @@ export default function Captcha({ enabled, provider = "mcaptcha", instanceUrl, s
Cap's custom element injects <input name="cap-token"> into the
enclosing form when solved.
*/}
{createCapWidget(instanceUrl!, sitekey!)}
{createCapWidget(instanceUrl!, sitekey!, capWidgetRef)}
</>
);
}
return <div id={MOUNT_ID} className="m-captcha" data-ui-id="ui.captcha.mount" />;
}
function createCapWidget(instanceUrl: string, sitekey: string) {
function createCapWidget(instanceUrl: string, sitekey: string, ref: Ref<HTMLElement>) {
return createElement("cap-widget", {
ref,
required: true,
"data-cap-api-endpoint": `${instanceUrl.replace(/\/+$/, "")}/${sitekey}/`,
"data-ui-id": "ui.captcha.mount",
@@ -88,6 +113,8 @@ function loadCapAssets(instanceUrl: string): void {
script.defer = true;
script.src = scriptSrc;
script.dataset.capWidgetLoader = "true";
const nonce = getCurrentDocumentCspNonce(document);
if (nonce) script.nonce = nonce;
document.head.appendChild(script);
}
@@ -31,7 +31,7 @@ describe("CookiesList", () => {
fireEvent.click(screen.getByRole("button", { name: /cookies\.categories\.REQUIRED\.name/i }));
expect(screen.getByText("cookies.expiry.oneMonth")).toBeInTheDocument();
expect(screen.getAllByText("cookies.expiry.oneMonth").length).toBeGreaterThan(0);
expect(screen.queryByText("1 month")).not.toBeInTheDocument();
});
});
@@ -10,13 +10,23 @@ vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
Link: ({ children, to, onClick, className }: { children: React.ReactNode; to: string; onClick?: React.MouseEventHandler<HTMLAnchorElement>; className?: string }) => (
Link: ({
children,
to,
onClick,
className,
}: {
children: React.ReactNode;
to: string;
onClick?: React.MouseEventHandler<HTMLAnchorElement>;
className?: string;
}) => (
<a href={to} onClick={onClick} className={className}>
{children}
</a>
),
useNavigate: () => navigate,
useLocation: () => ({ pathname: "/acme/settings/api/keys/new" }),
useLocation: () => ({ pathname: "/acme/api/keys/new" }),
useMatches: () => [],
};
});
@@ -37,7 +47,7 @@ describe("ApiKeyCreatedModal", () => {
});
it("labels the plaintext as one-time and copies it only when requested", async () => {
render(<ApiKeyCreatedModal apiKey={{ key: "tc_live_plaintext_secret_once", alias: "Primary integration" }} redirectTo="/acme/settings/api/keys" />);
render(<ApiKeyCreatedModal apiKey={{ key: "tc_live_plaintext_secret_once", alias: "Primary integration" }} redirectTo="/acme/api/keys" />);
expect(screen.getByText("models.apiKey.createdTitle")).toBeInTheDocument();
expect(screen.getByText("models.apiKey.aliasWithValue")).toBeInTheDocument();
@@ -5,6 +5,7 @@ import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import InputText from "~/components/ui/input/InputText";
import OpenModal from "~/components/ui/modals/OpenModal";
import { useCopyToast } from "~/hooks/use-copy-toast";
interface Props {
apiKey: {
@@ -19,10 +20,14 @@ export default function ApiKeyCreatedModal({ apiKey, redirectTo, action = "creat
const navigate = useNavigate();
const [copied, setCopied] = useState(false);
const isRotated = action === "rotated";
const copyText = useCopyToast();
async function copyApiKey() {
await navigator.clipboard.writeText(apiKey.key);
setCopied(true);
const didCopy = await copyText(apiKey.key, {
successKey: "models.apiKey.copied",
errorKey: "models.apiKey.copyFailed",
});
if (didCopy) setCopied(true);
}
return (
@@ -13,7 +13,7 @@ import type { RedactedApiKeyWithDetails } from "~/utils/db/apiKeys.db.server";
interface Props {
item?: RedactedApiKeyWithDetails | null;
tenants?: Tenant[];
tenants?: Pick<Tenant, "id" | "name">[];
canUpdate?: boolean;
canDelete?: boolean;
canRotate?: boolean;
@@ -5,7 +5,6 @@ describe("API log details i18n", () => {
it("keeps visible API log labels behind semantic translation keys", () => {
const tableSource = readRepoFile("apps/web/app/components/core/apiKeys/ApiKeyLogsTable.tsx");
const keysSource = readRepoFile("apps/web/app/components/core/apiKeys/ApiKeysTable.tsx");
const summarySource = readRepoFile("apps/web/app/modules/api/components/ApiKeyLogsSummary.tsx");
const apiDetailsSource = readRepoFile("apps/web/app/modules/api/components/ApiKeyLogsDetails.tsx");
const logDetailsSource = readRepoFile("apps/web/app/components/app/events/LogDetailsButton.tsx");
@@ -15,7 +14,7 @@ describe("API log details i18n", () => {
expect(tableSource).toContain('t("shared.notSet")');
expect(apiDetailsSource).toContain('t("shared.notSet")');
expect(logDetailsSource).toContain("models.log.details");
for (const source of [tableSource, keysSource, summarySource, apiDetailsSource]) {
for (const source of [tableSource, keysSource, apiDetailsSource]) {
expect(source).toContain("useLocaleFormatters");
expect(source).not.toContain('from "~/utils/shared/DateUtils"');
expect(source).not.toContain('from "~/utils/shared/NumberUtils"');
@@ -1,8 +1,17 @@
// API keys list (tenant settings + admin) on the interim ~/ui kit: search
// filters client-side, "Neu" links to the create route, rows link to the edit
// route. Keys render redacted only (prefix…last four); the raw secret never
// reaches this component (RedactedApiKeyWithDetails).
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import ButtonTertiary from "~/components/ui/buttons/ButtonTertiary";
import EmptyState from "~/components/ui/emptyState/EmptyState";
import InputSearch from "~/components/ui/input/InputSearch";
import { Link } from "react-router";
import { FeatherPlus } from "@subframe/core";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { Button } from "~/ui/components/Button";
import { EmptyState } from "~/ui/components/EmptyState";
import { Table } from "~/ui/components/Table";
import { FacetFilterBar } from "~/components/screens/shared/FacetFilterBar";
import { useLocaleFormatters } from "~/locale/format";
import type { RedactedApiKeyWithDetails } from "~/utils/db/apiKeys.db.server";
@@ -11,16 +20,14 @@ interface Props {
withTenant?: boolean;
canCreate?: boolean;
}
type Header = {
name?: string;
title: string;
};
type ApiKeyTableRow = {
item: RedactedApiKeyWithDetails;
redactedKey: string;
};
const cellText = "text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary";
function getRedactedKey(item: RedactedApiKeyWithDetails) {
return [item.keyPrefix, item.keyLastFour ? `••••${item.keyLastFour}` : undefined].filter(Boolean).join("…") || "••••";
}
@@ -31,26 +38,16 @@ export default function ApiKeysTable({ items, withTenant, canCreate }: Props) {
const [searchInput, setSearchInput] = useState("");
const headers = useMemo(() => {
const nextHeaders: Header[] = [];
if (withTenant) {
nextHeaders.push({ name: "tenant", title: t("models.tenant.object") });
}
nextHeaders.push({ name: "key", title: t("models.apiKey.key") });
nextHeaders.push({ name: "alias", title: t("models.apiKey.alias") });
nextHeaders.push({ name: "usage", title: t("models.apiKey.usage") });
nextHeaders.push({ name: "expires", title: t("models.apiKey.expires") });
nextHeaders.push({ name: "createdAt", title: t("shared.createdAt") });
nextHeaders.push({ name: "createdByUser", title: t("shared.createdBy") });
return nextHeaders;
}, [t, withTenant]);
const filteredSortedRows = useMemo<ApiKeyTableRow[]>(() => {
if (!items) {
return [];
}
const normalizedSearchInput = searchInput.trim().toUpperCase();
const filtered = normalizedSearchInput ? items.filter((item) => item.tenant?.name?.toString()?.toUpperCase().includes(normalizedSearchInput)) : [...items];
const filtered = normalizedSearchInput
? items.filter((item) =>
[item.tenant?.name, item.alias, item.keyPrefix].some((value) => value?.toString().toUpperCase().includes(normalizedSearchInput))
)
: [...items];
return filtered
.sort((x, y) => {
@@ -65,117 +62,94 @@ export default function ApiKeysTable({ items, withTenant, canCreate }: Props) {
}));
}, [items, searchInput]);
// function deleteApiKey(item: ApiKey) {
// if (confirmDelete.current) {
// confirmDelete.current.setValue(item);
// confirmDelete.current.show(t("shared.delete"), t("shared.delete"), t("shared.cancel"), t("shared.warningCannotUndo"));
// }
// }
// function confirmDeleteApiKey(item: ApiKey) {
// const form = new FormData();
// form.set("action", "delete");
// form.set("id", item.id);
// submit(form, {
// method: "post",
// });
// }
return (
<div className="space-y-2">
<InputSearch value={searchInput} setValue={setSearchInput} onNewRoute={canCreate ? "new" : ""} />
{(() => {
if (filteredSortedRows.length === 0) {
return (
<div>
<EmptyState
className="bg-background"
captions={{
thereAreNo: t("shared.noRecords"),
}}
/>
</div>
);
} else {
return (
<div>
<div>
<div className="flex flex-col">
<div className="overflow-x-auto">
<div className="inline-block min-w-full py-2 align-middle">
<div className="border-border overflow-hidden border shadow-xs sm:rounded-lg">
<table className="divide-border min-w-full divide-y">
<thead className="bg-secondary">
<tr>
{headers.map((header, idx) => {
return (
<th
key={idx}
scope="col"
className="text-muted-foreground truncate px-3 py-2 text-left text-xs font-medium tracking-wider select-none"
>
<div className="text-muted-foreground flex items-center space-x-1">
<div>{header.title}</div>
</div>
</th>
);
})}
</tr>
</thead>
<tbody className="divide-border bg-background divide-y">
{filteredSortedRows.map(({ item, redactedKey }, idx) => {
return (
<tr key={idx}>
{withTenant && (
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
{item.tenant?.name ?? t("models.apiKey.adminTenant")}
</td>
)}
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<span className="font-mono text-xs" aria-label={`${t("models.apiKey.key")} ${redactedKey}`}>
{redactedKey}
</span>
{!item.active && <span className="ml-2 text-red-600">{t("shared.inactive")}</span>}
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">{item.alias}</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
{formatters.number(item._count.apiKeyLogs)}{" "}
{item._count.apiKeyLogs === 1 ? t("models.apiCall.object") : t("models.apiCall.plural")}
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<time
dateTime={item.expires ? new Date(item.expires).toISOString() : undefined}
title={item.expires ? formatters.dateTime(item.expires) : undefined}
>
{item.expires === null ? <span>-</span> : <span>{formatters.relativeDate(item.expires)}</span>}
</time>
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<time dateTime={new Date(item.createdAt).toISOString()} title={formatters.dateTime(item.createdAt)}>
{formatters.dateTime(item.createdAt)}
</time>
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<span className="text-muted-foreground text-xs">{item.createdByUser.email}</span>
</td>
<td className="text-muted-foreground px-3 py-2 text-sm whitespace-nowrap">
<div className="flex items-center space-x-2">
<ButtonTertiary to={item.id}>{t("shared.edit")}</ButtonTertiary>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
);
<div className="flex w-full flex-col gap-4" data-ui-id="ui.settings.apiKeys.table">
{/* The same bar the calls and overview tabs carry — this list is fully
loaded, so the term filters client-side and there are no facets. */}
<FacetFilterBar
variant="inline"
uiId="ui.settings.apiKeys"
facets={[]}
onToggle={() => undefined}
search={searchInput}
onSearchChange={setSearchInput}
searchPlaceholder={t("shared.searchDot")}
onReset={() => setSearchInput("")}
labels={{ reset: t("shared.reset"), removeChip: t("settings.members.filters.removeChip") }}
trailing={
canCreate ? (
<Link to="new" data-ui-id="ui.settings.apiKeys.new">
<Button icon={<FeatherPlus />}>{t("shared.new")}</Button>
</Link>
) : undefined
}
})()}
/>
{filteredSortedRows.length === 0 ? (
<div data-ui-id="ui.settings.apiKeys.empty">
<EmptyState title={t("shared.noRecords")} />
</div>
) : (
<div className="w-full overflow-x-auto">
<Table
header={
<Table.HeaderRow>
{withTenant ? <Table.HeaderCell>{t("models.tenant.object")}</Table.HeaderCell> : null}
<Table.HeaderCell>{t("models.apiKey.key")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKey.alias")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKey.usage")}</Table.HeaderCell>
<Table.HeaderCell>{t("models.apiKey.expires")}</Table.HeaderCell>
<Table.HeaderCell>{t("shared.createdAt")}</Table.HeaderCell>
<Table.HeaderCell>{t("shared.createdBy")}</Table.HeaderCell>
<Table.HeaderCell />
</Table.HeaderRow>
}
>
{filteredSortedRows.map(({ item, redactedKey }) => (
<Table.Row key={item.id} data-row-id={item.id}>
{withTenant ? <Table.Cell><span className={cellText}>{item.tenant?.name ?? t("models.apiKey.adminTenant")}</span></Table.Cell> : null}
<Table.Cell>
<div className="flex items-center gap-2">
<span className="font-mono text-body-small-regular-0 text-text-neutral-primary" aria-label={`${t("models.apiKey.key")} ${redactedKey}`}>
{redactedKey}
</span>
{!item.active ? <BadgeFeedback farbe="subtle-negative" size="small">{t("shared.inactive")}</BadgeFeedback> : null}
</div>
</Table.Cell>
<Table.Cell><span className={cellText}>{item.alias}</span></Table.Cell>
<Table.Cell>
<span className={cellText}>
{formatters.number(item._count.apiKeyLogs)} {item._count.apiKeyLogs === 1 ? t("models.apiCall.object") : t("models.apiCall.plural")}
</span>
</Table.Cell>
<Table.Cell>
<span className={cellText}>
<time
dateTime={item.expires ? new Date(item.expires).toISOString() : undefined}
title={item.expires ? formatters.dateTime(item.expires) : undefined}
>
{item.expires === null ? "-" : formatters.relativeDate(item.expires)}
</time>
</span>
</Table.Cell>
<Table.Cell>
<span className={cellText}>
<time dateTime={new Date(item.createdAt).toISOString()} title={formatters.dateTime(item.createdAt)}>
{formatters.dateTime(item.createdAt)}
</time>
</span>
</Table.Cell>
<Table.Cell><span className={cellText}>{item.createdByUser.email}</span></Table.Cell>
<Table.Cell>
<Link to={item.id}>
<Button variant="tertiary" size="small">{t("shared.edit")}</Button>
</Link>
</Table.Cell>
</Table.Row>
))}
</Table>
</div>
)}
</div>
);
}
@@ -7,6 +7,7 @@ import InputText from "~/components/ui/input/InputText";
import CollapsibleRow from "~/components/ui/tables/CollapsibleRow";
import { updateItemByIdx } from "~/utils/shared/ObjectUtils";
import { useLocaleFormatters } from "~/locale/format";
import { getSubscriptionFeatureTitle } from "~/utils/app/SubscriptionFeatureText";
import { CheckCircleIcon, XCircleIcon, PlusIcon } from "~/components/ui/icons/vendor";
interface Props {
@@ -66,7 +67,7 @@ export default function PricingFeaturesForm({ items, setItems }: Props) {
{item.type === SubscriptionFeatureLimitType.MONTHLY && <span>{t("admin.pricing.features.limitTypes.monthly")}</span>}
{item.type === SubscriptionFeatureLimitType.MAX && <span>{t("admin.pricing.features.limitTypes.max")}</span>}
{item.type === SubscriptionFeatureLimitType.UNLIMITED && <span>{t("admin.pricing.features.limitTypes.unlimited")}</span>}
<div>{t(item.title)}</div>
<div>{getSubscriptionFeatureTitle(t, item, { 0: formatters.number(item.value) })}</div>
{(item.type === SubscriptionFeatureLimitType.MONTHLY || item.type === SubscriptionFeatureLimitType.MAX) && <div>{formatters.number(item.value)}</div>}
</>
) : (
@@ -14,7 +14,6 @@ import ToggleBillingPeriod from "../settings/subscription/ToggleBillingPeriod";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import PricingFeaturesTable from "./PricingFeaturesTable";
import { PricingModel } from "~/application/enums/subscriptions/PricingModel";
import ButtonSecondary from "~/components/ui/buttons/ButtonSecondary";
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import FlatPrices from "./FlatPrices";
import UsageBasedPrices from "./UsageBasedPrices";
@@ -49,15 +48,10 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
const navigate = useNavigate();
const submit = useSubmit();
let pricingModels = HIVEGRID_SUBSCRIPTION_PRICING_MODELS.map((value) => ({
const pricingModels = HIVEGRID_SUBSCRIPTION_PRICING_MODELS.map((value) => ({
name: t("pricing." + PricingModel[value]),
value,
}));
if (isPortalPlan) {
pricingModels = pricingModels.filter(
(f) => f.value !== PricingModel.USAGE_BASED && f.value !== PricingModel.FLAT_RATE_USAGE_BASED
);
}
const inputTitle = useRef<RefInputText>(null);
const confirmRemove = useRef<RefConfirmModal>(null);
@@ -433,6 +427,7 @@ export default function PricingPlanForm({ plans, item, canUpdate = true, canDele
usageBasedPrices={usageBasedPrices}
billingProviderCoupon={null}
isPreview={true}
showFeatures
/>
</div>
</SettingSection>
@@ -360,7 +360,7 @@ export default function UsageBasedPricesUnit({ item, onUpdate, disabled }: Props
<TrashIcon className="text-muted-foreground h-4 w-4" />
</div>
),
onClick: (idx, i) => removeTier(idx),
onClick: (idx, _i) => removeTier(idx),
disabled: () => disabled || allTiers.length === 1,
},
]}
@@ -380,7 +380,7 @@ export default function UsageBasedPricesUnit({ item, onUpdate, disabled }: Props
<TrashIcon className="text-muted-foreground h-4 w-4" />
</div>
),
onClick: (idx, i) => removeTier(idx),
onClick: (idx, _i) => removeTier(idx),
disabled: () => disabled || allTiers.length === 1,
},
]}
@@ -16,7 +16,7 @@ interface Props {
canReorder?: boolean;
}
export default function PermissionsTable({ items, className, canCreate, canUpdate = true, tenantId, canReorder }: Props) {
export default function PermissionsTable({ items, className: _className, canCreate: _canCreate, canUpdate = true, tenantId: _tenantId, canReorder }: Props) {
const { t } = useTranslation();
const [actions, setActions] = useState<any[]>([]);
@@ -24,7 +24,7 @@ interface Props {
};
}
export default function UserRolesTable({ items, roles, className, onChange, tenantId = null, disabled, onRoleClick, actions }: Props) {
export default function UserRolesTable({ items, roles, className: _className, onChange, tenantId = null, disabled, onRoleClick, actions }: Props) {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
@@ -35,6 +35,10 @@ describe("roleDisplay", () => {
"translated:models.role.defaultRoles.names.billingAdmin"
);
expect(roleDisplayName({ name: "Regional Admin", description: "Custom tenant role" }, t)).toBe("Regional Admin");
expect(roleDisplayName({ name: "Geschäftsführer", description: null }, t)).toBe(
"translated:models.role.templateRoles.names.managingDirector"
);
expect(roleDisplayName({ name: "Monteur", description: null }, t)).toBe("translated:models.role.templateRoles.names.fieldTechnician");
});
it("localizes seeded default role descriptions without changing custom descriptions", () => {
@@ -66,6 +70,18 @@ describe("roleDisplay", () => {
expect(roleDisplayDescription({ name: "Approver", description: "Genehmigt Rechnungen." }, tNs)).toBe("Genehmigt Rechnungen.");
});
it("localizes legacy German SHK descriptions for existing tenants", () => {
expect(
roleDisplayDescription(
{
name: "Vertriebsleiter",
description: "Leitung Vertrieb: CRM- und Lead-Verwaltung, Vertriebs-Reports und Umsatzkennzahlen.",
},
t
)
).toBe("translated:models.role.templateRoles.descriptions.salesManager");
});
it("keeps the raw database value when no translator is provided", () => {
expect(roleDisplayName({ name: "SuperUser", description: "Has all app permissions" })).toBe("SuperUser");
expect(roleDisplayDescription({ name: "SuperUser", description: "Has all app permissions" })).toBe("Has all app permissions");
@@ -84,6 +100,12 @@ describe("roleDisplay", () => {
expect(permissionDisplayDescription({ name: "app.settings.members.view", description: "Default permission app.settings.members.view" }, t)).toBe(
"translated:models.permission.defaultPermissions.description"
);
expect(permissionDisplayName({ name: "portal.admin", description: "Default permission portal.admin" }, t)).toBe(
"translated:models.permission.defaultPermissions.title"
);
expect(permissionDisplayName({ name: "portal.activity.manage", description: "Default permission portal.activity.manage" }, t)).toBe(
"translated:models.permission.defaultPermissions.title"
);
});
it("has translation coverage for every default permission seed scope and action", () => {
@@ -58,6 +58,28 @@ const DEFAULT_ROLE_DESCRIPTION_KEYS: Record<string, string> = {
"Has regular permissions": "regularPermissions",
};
const SHK_TEMPLATE_ROLE_NAME_KEYS: Record<string, string> = {
"Geschäftsführer": "managingDirector",
Vertriebsleiter: "salesManager",
Vertriebler: "salesRepresentative",
"Büro/Backoffice": "backOffice",
Marketing: "marketing",
"Projektleiter/Bauleiter": "projectManager",
Monteur: "fieldTechnician",
};
// Existing tenants can still carry the original German seed copy. Resolve it
// at display time so they become locale-aware without overwriting tenant edits.
const LEGACY_SHK_TEMPLATE_ROLE_DESCRIPTION_KEYS: Record<string, string> = {
"Voller Zugriff auf alle Bereiche inklusive Nutzerverwaltung, Rollen und Abrechnung.": "managingDirector",
"Leitung Vertrieb: CRM- und Lead-Verwaltung, Vertriebs-Reports und Umsatzkennzahlen.": "salesManager",
"Vertrieb im Tagesgeschäft: eigene Kontakte und Projekte, Angebote und Termine.": "salesRepresentative",
"Backoffice: Kontakte, Projektabwicklung, Dateien, Personal, Terminbuchung und Rechnungswesen.": "backOffice",
"Marketing: Kampagnen, Formulare, Lead-Erfassung und Segmentierung.": "marketing",
"Projekt-/Bauleitung: eigene Projekte steuern, Plantafel, Aufgaben, Dateien und Abnahmen.": "projectManager",
"Feld/Baustelle: eigene Aufträge, Aufgaben, Abnahmen, Foto-Formulare und Dateien.": "fieldTechnician",
};
const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
view: "view",
create: "create",
@@ -69,6 +91,7 @@ const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
reset: "reset",
subscription: "subscription",
use: "use",
export: "export",
users: "users",
impersonate: "impersonate",
changePassword: "changePassword",
@@ -79,9 +102,13 @@ const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
read_own_pl: "read_own_pl",
read_all: "read_all",
write: "write",
write_all: "write_all",
bulk_reassign: "bulk_reassign",
change_stage: "change_stage",
manage_members: "manage_members",
// WF-P8 baseline: internal-note reader gate and pipeline handover.
read_internal_notes: "read_internal_notes",
handover: "handover",
read_volume_own: "read_volume_own",
read_volume_all: "read_volume_all",
read_aggregates: "read_aggregates",
@@ -108,6 +135,23 @@ const DEFAULT_PERMISSION_ACTION_KEYS: Record<string, string> = {
tenant_export: "tenant_export",
tenant_deletion: "tenant_deletion",
accept: "accept",
// P15 Telephony (AK-P15a) — initiate a provider-backed call.
call: "call",
// P15 Team-Chat (AK-P15b) — channel-scoped read/create capabilities.
read_own_channels: "read_own_channels",
create_channel: "create_channel",
create_dm: "create_dm",
read_all_channels: "read_all_channels",
manage_users: "manage_users",
manage_access: "manage_access",
delete_user: "delete_user",
assign: "assign",
merge: "merge",
track: "track",
bulk_send: "bulk_send",
recording: "recording",
enroll: "enroll",
start: "start",
};
const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
@@ -124,9 +168,11 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
"app.plugins": "app.plugins",
"app.onboarding.demoData": "app.onboarding.demoData",
"app.onboarding.checklist": "app.onboarding.checklist",
// P26 Customer Portal (VA-P26a) — tenant-side configuration scope.
portal: "portal",
"portal.activity": "portalActivity",
"admin.account": "admin.account",
"admin.account.settings": "admin.account.settings",
"admin.accountTypes": "admin.accountTypes",
"admin.accounts": "admin.accounts",
"admin.apiKeys": "admin.apiKeys",
"admin.auditTrails": "admin.auditTrails",
@@ -139,6 +185,7 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
"admin.marketing.funnels": "admin.marketing.funnels",
"admin.marketing.integrations": "admin.marketing.integrations",
"admin.marketing.leads": "admin.marketing.leads",
"admin.leads": "admin.leads",
"admin.metrics": "admin.metrics",
"admin.notifications": "admin.notifications",
"admin.pricing": "admin.pricing",
@@ -146,7 +193,6 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
"admin.relationships": "admin.relationships",
"admin.roles": "admin.roles",
"admin.settings.authentication": "admin.settings.authentication",
"admin.settings.cookies": "admin.settings.cookies",
"admin.settings.danger": "admin.settings.danger",
"admin.settings.general": "admin.settings.general",
"admin.settings.internationalization": "admin.settings.internationalization",
@@ -199,11 +245,32 @@ const DEFAULT_PERMISSION_SCOPE_KEYS: Record<string, string> = {
dashboard: "dashboard",
// P12 Automation (R-P12a) — typed automation rules, executions and guards.
automation: "automation",
// P15 Telephony (AK-P15a) — Aircall connection, calls and bindings.
telephony: "telephony",
// P15 Team-Chat (AK-P15b) — internal realtime collaboration.
chat: "chat",
// P21 Privacy/GDPR (AK-P21). Flat keys avoid colliding with the privacy leaf.
privacy: "privacy",
"privacy.user_export": "privacyUserExport",
"privacy.avv": "privacyAvv",
"privacy.subprocessors": "privacySubprocessors",
"admin_identity.users": "adminIdentityUsers",
"admin_identity.roles": "adminIdentityRoles",
"admin_identity.sessions": "adminIdentitySessions",
"admin_identity.audit": "adminIdentityAudit",
"admin_identity.impersonation": "adminIdentityImpersonation",
"admin_identity.tenants": "adminIdentityTenants",
"admin_sales.crm": "adminSalesCrm",
"admin_sales.communication": "adminSalesCommunication",
"admin_sales.email": "adminSalesEmail",
"admin_sales.phone": "adminSalesPhone",
"admin_sales.sequence": "adminSalesSequence",
"admin_sales.booking": "adminSalesBooking",
"admin_sales.quote": "adminSalesQuote",
"admin_sales.signature": "adminSalesSignature",
"admin_sales.reporting": "adminSalesReporting",
"admin_sales.automation": "adminSalesAutomation",
"admin_sales.integrations": "adminSalesIntegrations",
};
function humanizeIdentifier(value: string) {
@@ -270,8 +337,12 @@ function isDefaultPermissionDescription(item: DisplayItem) {
}
export function roleDisplayName(item: DisplayItem, t?: Translate) {
const key = DEFAULT_ROLE_NAME_KEYS[item.name];
return key && t ? t(`models.role.defaultRoles.names.${key}`) : item.name;
const defaultRoleKey = DEFAULT_ROLE_NAME_KEYS[item.name];
if (defaultRoleKey && t) {
return t(`models.role.defaultRoles.names.${defaultRoleKey}`);
}
const templateRoleKey = SHK_TEMPLATE_ROLE_NAME_KEYS[item.name];
return templateRoleKey && t ? t(`models.role.templateRoles.names.${templateRoleKey}`) : item.name;
}
export function roleDisplayDescription(item: DisplayItem, t?: Translate) {
@@ -284,6 +355,10 @@ export function roleDisplayDescription(item: DisplayItem, t?: Translate) {
return t(`models.role.defaultRoles.descriptions.${key}`);
}
if (t) {
const legacyTemplateKey = LEGACY_SHK_TEMPLATE_ROLE_DESCRIPTION_KEYS[description];
if (legacyTemplateKey) {
return t(`models.role.templateRoles.descriptions.${legacyTemplateKey}`);
}
const resolved = resolveStoredDescriptionKey(description, t);
if (resolved !== null) {
return resolved;
@@ -1,14 +1,14 @@
import clsx from "clsx";
import { useRef, useState, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Form, useActionData, useLocation, useNavigate, useNavigation, useParams } from "react-router";
import { Form, useActionData, useNavigate, useNavigation, useParams } from "react-router";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { NewMemberActionData } from "~/routes/app.$tenant/settings/members/new";
import { NewMemberActionData } from "~/routes/app.$tenant/settings/team/members/new";
import UrlUtils from "~/utils/app/UrlUtils";
import { useEscapeKeypress } from "~/utils/shared/KeypressUtils";
import CheckPlanFeatureLimit from "../subscription/CheckPlanFeatureLimit";
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
import toast from "react-hot-toast";
import { toast } from "sonner";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { useRootData } from "~/utils/data/useRootData";
@@ -18,7 +18,6 @@ interface Props {
export default function NewMember({ featurePlanUsage }: Props) {
const params = useParams();
const location = useLocation();
const actionData = useActionData<NewMemberActionData>();
const { t } = useTranslation();
const navigate = useNavigate();
@@ -50,7 +49,7 @@ export default function NewMember({ featurePlanUsage }: Props) {
function close() {
if (params.tenant) {
navigate(UrlUtils.currentTenantUrl(params, "settings/members"), { replace: true });
navigate(UrlUtils.currentTenantUrl(params, "settings/team"), { replace: true });
} else {
navigate(adminPath("accounts/users", { mode: "host-aware" }), { replace: true });
}
@@ -15,6 +15,7 @@ import Modal from "~/components/ui/modals/Modal";
import LoadingButton from "~/components/ui/buttons/LoadingButton";
import { useLocaleFormatters } from "~/locale/format";
import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
import { getSubscriptionFeatureTitle } from "~/utils/app/SubscriptionFeatureText";
import { CheckCircleIcon, XCircleIcon } from "~/components/ui/icons/vendor";
interface Props {
@@ -52,7 +53,7 @@ export default function ChangeSubscription({ items, current, billingPeriod, curr
}
function getPriceAmount(product: SubscriptionProductDto, quantity = 1) {
const price = getPrice(product);
return formatters.currency(Number(price?.price ?? 0) * quantity, (price?.currency ?? currency).toUpperCase(), { maximumFractionDigits: 0 });
return formatters.currency(Number(price?.price ?? 0) * quantity, (price?.currency ?? currency).toUpperCase());
}
function getPricePeriodSuffix(product: SubscriptionProductDto) {
@@ -198,7 +199,7 @@ export default function ChangeSubscription({ items, current, billingPeriod, curr
<XCircleIcon className="h-4 w-4 text-gray-300 opacity-70" />
)}
<span className="ml-3 truncate text-sm">
<span>{t(feature.title, { 0: feature.value })}</span>
<span>{getSubscriptionFeatureTitle(t, feature, { 0: feature.value })}</span>
</span>
</div>
</li>
@@ -11,7 +11,7 @@ interface Props {
hideContent?: boolean;
showRemaining?: boolean;
}
export default function CheckPlanFeatureLimit({ item, children, hideContent = true, showRemaining }: Props) {
export default function CheckPlanFeatureLimit({ item, children, hideContent = true, showRemaining: _showRemaining }: Props) {
const params = useParams();
const { t } = useTranslation();
function getTitle() {
@@ -24,7 +24,7 @@ export default function CheckPlanFeatureLimit({ item, children, hideContent = tr
<div>
{item && !item.enabled ? (
<div className="space-y-2">
<WarningBanner redirect={UrlUtils.currentTenantUrl(params, `settings/subscription`)} title={getTitle().toUpperCase()} text={``}>
<WarningBanner redirect={UrlUtils.currentTenantUrl(params, "settings/billing")} title={getTitle().toUpperCase()} text={``}>
<div className="mt-2">
<span>{t(item.message)}</span>
</div>
@@ -12,48 +12,31 @@ export default function MyPlanFeatureUsage({ item }: Props) {
return (
<div>
{item ? (
<div>
{/* {JSON.stringify(item)} */}
<div className="flex items-baseline space-x-1 font-medium">
<div className="flex flex-col gap-0.5">
<div className="text-foreground flex items-baseline gap-1 text-lg font-semibold tabular-nums">
{item.type === SubscriptionFeatureLimitType.INCLUDED && (
<span className="text-foreground flex items-center space-x-1 truncate text-sm">
{/* <CheckIcon className={clsx(" text-center h-5 w-5")} /> */}
<span>{t("pricing.included")}</span>
</span>
<span>{t("pricing.included")}</span>
)}
{item.type === SubscriptionFeatureLimitType.NOT_INCLUDED && (
<span className="text-foreground flex items-center space-x-1 truncate text-sm">
{/* <XIcon className={clsx(" text-center h-5 w-5")} /> */}
<span>{t("pricing.notIncluded")}</span>
</span>
<span>{t("pricing.notIncluded")}</span>
)}
{item.type === SubscriptionFeatureLimitType.MONTHLY && (
<span className="text-foreground flex items-baseline space-x-1 text-sm lowercase">
<span>
{item.used}/{item.value}
</span>
<span className="text-muted-foreground text-xs font-normal lowercase">
{item.period?.firstDay && item.period.lastDay ? (
<span>
({formatters.date(item.period.firstDay, { dateStyle: "medium" })} - {formatters.date(item.period.lastDay, { dateStyle: "medium" })})
</span>
) : (
<span>({t("pricing.thisMonth")})</span>
)}
</span>
</span>
<span>{formatters.number(item.used)} / {formatters.number(item.value)}</span>
)}
{item.type === SubscriptionFeatureLimitType.MAX && (
<span className="text-foreground lowercase">
{item.used}/{item.value}
</span>
<span>{formatters.number(item.used)} / {formatters.number(item.value)}</span>
)}
{item.type === SubscriptionFeatureLimitType.UNLIMITED && (
<span className="text-foreground flex items-center space-x-1 truncate text-sm">{t("shared.unlimited")}</span>
<span>{t("shared.unlimited")}</span>
)}
</div>
{/* <span className="mt-2 text-red-700 text-xs font-normal">{item.message ?? ""}</span> */}
{item.type === SubscriptionFeatureLimitType.MONTHLY ? (
<span className="text-muted-foreground text-xs font-normal">
{item.period?.firstDay && item.period.lastDay
? `${formatters.date(item.period.firstDay, { dateStyle: "medium" })} – ${formatters.date(item.period.lastDay, { dateStyle: "medium" })}`
: t("pricing.thisMonth")}
</span>
) : null}
</div>
) : (
<span className=" text-muted-foreground">-</span>
@@ -0,0 +1,54 @@
// @vitest-environment jsdom
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import type { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import MySubscriptionFeatures from "./MySubscriptionFeatures";
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("~/locale/format", () => ({
useLocaleFormatters: () => ({
number: (value: number) => new Intl.NumberFormat("de-DE").format(value),
date: () => "01.07.2026",
}),
}));
function feature(overrides: Partial<PlanFeatureUsageDto>): PlanFeatureUsageDto {
return {
order: 1,
title: "Feature",
name: "feature",
type: SubscriptionFeatureLimitType.INCLUDED,
value: 1,
used: 0,
remaining: 1,
enabled: true,
message: "",
...overrides,
};
}
describe("MySubscriptionFeatures", () => {
it("shows only commercial quantity limits and the calculated storage pool", () => {
render(
<MySubscriptionFeatures
storageLimitGb={250}
features={[
feature({ name: "dashboard", type: SubscriptionFeatureLimitType.INCLUDED }),
feature({ name: "email-marketing", type: SubscriptionFeatureLimitType.MONTHLY, value: 10_000, used: 125 }),
feature({ name: "rate-limit-per-minute", type: SubscriptionFeatureLimitType.MAX, value: 600, used: 12 }),
feature({ name: "automation", type: SubscriptionFeatureLimitType.NOT_INCLUDED, value: 0 }),
]}
/>
);
expect(screen.getByText("app.subscription.features.storage")).toBeInTheDocument();
expect(screen.getByText("250 shared.storage.gb")).toBeInTheDocument();
expect(screen.getByText("app.subscription.features.emailMarketing")).toBeInTheDocument();
expect(screen.getByText("125 / 10.000")).toBeInTheDocument();
expect(screen.queryByText("dashboard")).not.toBeInTheDocument();
expect(screen.queryByText("rate-limit-per-minute")).not.toBeInTheDocument();
expect(screen.queryByText("app.subscription.features.automation")).not.toBeInTheDocument();
});
});
@@ -1,56 +1,67 @@
import { useTranslation } from "react-i18next";
import clsx from "clsx";
import MyPlanFeatureUsage from "./MyPlanFeatureUsage";
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import { useLocaleFormatters } from "~/locale/format";
interface Props {
features: PlanFeatureUsageDto[];
className?: string;
withCurrentPlan: boolean;
storageLimitGb?: number | null;
}
export default function MySubscriptionFeatures({
features,
className = "",
withCurrentPlan = false,
}: Props) {
const commercialLimitTitleKeys: Record<string, string> = {
"email-marketing": "app.subscription.features.emailMarketing",
automation: "app.subscription.features.automation",
"workflow-engine": "app.subscription.features.workflows",
"import-export": "app.subscription.features.importExport",
};
export default function MySubscriptionFeatures({ features, className = "", storageLimitGb = null }: Props) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const visibleFeatures = features.filter(
(feature) =>
commercialLimitTitleKeys[feature.name] &&
[SubscriptionFeatureLimitType.MONTHLY, SubscriptionFeatureLimitType.MAX, SubscriptionFeatureLimitType.UNLIMITED].includes(feature.type)
);
function getTitle(item: PlanFeatureUsageDto) {
const commercialTitleKey = commercialLimitTitleKeys[item.name];
if (commercialTitleKey) {
return t(commercialTitleKey);
}
if (item?.entity) {
return t(item.entity.titlePlural);
}
return item?.name ?? "";
return item?.title ?? "";
}
const hasLimits = storageLimitGb !== null || visibleFeatures.length > 0;
return (
<div className={className} data-ui-id="ui.subscription.features">
{features.length === 0 ? (
{!hasLimits ? (
<div className="text-muted-foreground text-sm italic">{t("settings.subscription.noSubscription")}</div>
) : (
<>
<dl
className={clsx(
"grid gap-2",
withCurrentPlan && "mt-2 ",
features.length === 1 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-1",
features.length === 2 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-2",
features.length === 3 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-1",
features.length === 4 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-2",
features.length === 5 && "grid-cols-1 md:grid-cols-1 xl:grid-cols-1",
features.length === 6 && "grid-cols-1 md:grid-cols-3 xl:grid-cols-2"
)}
>
{features.map((item, idx) => {
return (
<div key={idx} className="border-border bg-background rounded-lg border p-4 shadow-2xs">
<dt className="text-muted-foreground truncate text-xs uppercase tracking-wide">{getTitle(item)}</dt>
<dd className="mt-1">
<span>{<MyPlanFeatureUsage item={item} />}</span>
</dd>
</div>
);
})}
</dl>
</>
<dl className="grid grid-cols-1 gap-3 md:grid-cols-2 xl:grid-cols-3">
{storageLimitGb !== null ? (
<div className="border-border bg-background rounded-lg border p-4 shadow-2xs">
<dt className="text-muted-foreground text-xs font-medium tracking-wide uppercase">{t("app.subscription.features.storage")}</dt>
<dd className="text-foreground mt-1 text-lg font-semibold tabular-nums">
{formatters.number(storageLimitGb, { maximumFractionDigits: 0 })} {t("shared.storage.gb")}
</dd>
</div>
) : null}
{visibleFeatures.map((item) => (
<div key={item.name} className="border-border bg-background rounded-lg border p-4 shadow-2xs">
<dt className="text-muted-foreground text-xs font-medium tracking-wide uppercase">{getTitle(item)}</dt>
<dd className="mt-1 text-lg font-semibold tabular-nums">
<MyPlanFeatureUsage item={item} />
</dd>
</div>
))}
</dl>
)}
</div>
);
@@ -17,6 +17,7 @@ import InputNumber from "~/components/ui/input/InputNumber";
import PlanChangePreviewModal from "./PlanChangePreviewModal";
import { useLocaleFormatters } from "~/locale/format";
import SubscriptionUtils from "~/utils/app/SubscriptionUtils";
import { annualSepaExtraPriceEur, type SeatPackageDefinition } from "@hivegrid/entitlements";
export interface CurrentPlanInfo {
title: string;
@@ -45,6 +46,8 @@ interface Props {
billingProviderCoupon: BillingProviderCouponDto | null;
isPreview?: boolean;
onClickFeature?: (name: string) => void;
showFeatures?: boolean;
seatPackage?: SeatPackageDefinition;
/** When set, the user has an existing active subscription on a *different* plan. Click opens a proration preview before submitting. */
currentPlanInfo?: CurrentPlanInfo | null;
}
@@ -68,6 +71,8 @@ export default function Plan({
billingProviderCoupon,
isPreview,
onClickFeature,
showFeatures = false,
seatPackage,
currentPlanInfo,
}: Props) {
const { t } = useTranslation();
@@ -101,7 +106,7 @@ export default function Plan({
return "?";
}
let total = applyDiscount(Number(price.price || 0));
return formatters.currency(total, price.currency.toUpperCase(), { maximumFractionDigits: 0 });
return formatters.currency(total, price.currency.toUpperCase());
}
function getBeforePrice() {
@@ -109,7 +114,7 @@ export default function Plan({
if (!price) {
return "?";
}
return formatters.currency(Number(price.price || 0), price.currency.toUpperCase(), { maximumFractionDigits: 0 });
return formatters.currency(Number(price.price || 0), price.currency.toUpperCase());
}
function getPricePeriodSuffix(price?: SubscriptionPriceDto) {
@@ -252,14 +257,20 @@ export default function Plan({
>
{badge && (
<div className="bg-primary text-primary-foreground absolute top-0 -translate-y-1/2 transform rounded-full px-4 py-1.5 text-xs font-semibold tracking-wide uppercase">
{t(badge)}
{badge.startsWith("settings.subscription.checkout.plans.packages.") ? t(badge) : badge}
</div>
)}
<div className="flex-1 space-y-4">
{/* Title and Description */}
<div className="shrink-0 space-y-2">
<h2 className="text-xl font-medium">{t(title)}</h2>
{description && <p className="text-muted-foreground text-sm">{t(description)}</p>}
<h2 className="text-xl font-medium">
{title.startsWith("settings.subscription.checkout.plans.packages.") ? t(title) : title}
</h2>
{description && (
<p className="text-muted-foreground text-sm">
{description.startsWith("settings.subscription.checkout.plans.packages.") ? t(description) : description}
</p>
)}
</div>
{/* Price */}
@@ -350,19 +361,47 @@ export default function Plan({
);
})}
{/* <div className="w-full border-t"></div> */}
{/* Features */}
<ul className="flex-1 space-y-1.5">
{features
.sort((a, b) => (a.order > b.order ? 1 : -1))
.map((feature, idxFeature) => {
return (
{showFeatures ? (
<ul className="flex-1 space-y-1.5">
{[...features]
.sort((a, b) => (a.order > b.order ? 1 : -1))
.map((feature, idxFeature) => (
<li key={idxFeature}>
<PlanFeatureDescription feature={feature} onClickFeature={onClickFeature} />
</li>
);
})}
</ul>
))}
</ul>
) : null}
{seatPackage ? (
<div className="border-border text-muted-foreground space-y-1.5 border-t pt-4 text-sm">
<p className="text-foreground font-medium">{t("billing:selfServiceSubscription.packageTerms.core")}</p>
<p>
{t("billing:selfServiceSubscription.packageTerms.seats", {
office: seatPackage.seats.office.included,
field: seatPackage.seats.field.included,
})}
</p>
<p>{t("billing:selfServiceSubscription.packageTerms.storage", { storage: seatPackage.storage.includedGb })}</p>
<p>
{t("billing:selfServiceSubscription.packageTerms.annualSepa", {
price: formatters.currency(seatPackage.annualSepaEur, "EUR"),
})}
</p>
<p>
{t("billing:selfServiceSubscription.packageTerms.extraSeatsMonthly", {
office: formatters.currency(seatPackage.seats.office.extraPriceEur, "EUR"),
field: formatters.currency(seatPackage.seats.field.extraPriceEur, "EUR"),
})}
</p>
<p>
{t("billing:selfServiceSubscription.packageTerms.extraSeatsAnnualSepa", {
office: formatters.currency(annualSepaExtraPriceEur(seatPackage.seats.office.extraPriceEur), "EUR"),
field: formatters.currency(annualSepaExtraPriceEur(seatPackage.seats.field.extraPriceEur), "EUR"),
})}
</p>
</div>
) : null}
{/* {canSubmit && ( */}
<div className="mt-4 space-y-2">
@@ -432,8 +471,8 @@ export default function Plan({
}
setShowPreview(false);
}}
fromPlanTitle={t(currentPlanInfo.title)}
toPlanTitle={t(title)}
fromPlanTitle={currentPlanInfo.title.startsWith("settings.subscription.checkout.plans.packages.") ? t(currentPlanInfo.title) : currentPlanInfo.title}
toPlanTitle={title.startsWith("settings.subscription.checkout.plans.packages.") ? t(title) : title}
fromPriceAmount={currentPlanInfo.priceAmount}
toPriceAmount={Number(getFlatPrice()?.price ?? 0)}
currency={currency}
@@ -480,7 +519,8 @@ function SubscribeOrBuyButton({
currency,
}: SubscribeOrBuyButtonProps) {
const { t } = useTranslation();
const planLabel = title ? t(title) : (product?.title ? t(product.title) : "");
const rawPlanLabel = title ?? product?.title ?? "";
const planLabel = rawPlanLabel.startsWith("settings.subscription.checkout.plans.packages.") ? t(rawPlanLabel) : rawPlanLabel;
// alreadyOwned takes a distinctive non-clickable badge instead of a button —
// signals "this is your plan" rather than "click to do nothing".
@@ -5,6 +5,7 @@ import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
import { SubscriptionFeatureLimitType } from "~/application/enums/subscriptions/SubscriptionFeatureLimitType";
import { useLocaleFormatters } from "~/locale/format";
import { CreditTypes } from "~/modules/usage/dtos/CreditType";
import { getSubscriptionFeatureBadge, getSubscriptionFeatureTitle } from "~/utils/app/SubscriptionFeatureText";
import { CheckCircleIcon, XCircleIcon } from "~/components/ui/icons/vendor";
interface Props {
@@ -70,13 +71,14 @@ export default function PlanFeatureDescription({ feature, editing, onClickFeatur
);
}
function FeatureTitle({ feature }: { feature: { title: string; value: number; href?: string | null; badge?: string | null } }) {
function FeatureTitle({ feature }: { feature: { name: string; title: string; value: number; href?: string | null; badge?: string | null } }) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
const value = typeof feature.value === "number" ? formatters.number(feature.value, { maximumFractionDigits: 0 }) : feature.value;
const badge = getSubscriptionFeatureBadge(t, feature);
return (
<span>
{t(feature.title, { 0: value })} {feature.badge && <span className="bg-primary text-theme-50 ml-1 rounded-md px-1 py-0.5 text-xs">{feature.badge}</span>}
{getSubscriptionFeatureTitle(t, feature, { 0: value })} {badge && <span className="bg-primary text-theme-50 ml-1 rounded-md px-1 py-0.5 text-xs">{badge}</span>}
</span>
);
}
@@ -12,6 +12,7 @@ import type { SubscriptionPriceDto } from "~/application/dtos/subscriptions/Subs
import type { BillingProviderCouponDto } from "~/application/dtos/billing/BillingProviderCouponDto";
import { useSearchParams } from "react-router";
import { useLocaleFormatters } from "~/locale/format";
import { getSeatPackage, resolveSeatPackageId } from "@hivegrid/entitlements";
interface Props {
items: SubscriptionProductDto[];
@@ -138,13 +139,14 @@ export default function Plans({ items, tenantSubscription, canSubmit, className,
: null;
return items.map((plan, index) => {
const seatPackageId = resolveSeatPackageId(plan.title, plan.id);
return (
<Plan
key={index}
className={clsx((items.length === 1 || (items.length === 4 && index === 3)) && "lg:col-span-1")}
product={plan}
title={plan.title}
description={plan.description ?? undefined}
title={seatPackageId ? `settings.subscription.checkout.plans.packages.${seatPackageId}.title` : plan.title}
description={seatPackageId ? `settings.subscription.checkout.plans.packages.${seatPackageId}.description` : (plan.description ?? undefined)}
badge={plan.badge ?? undefined}
features={plan.features}
billingPeriod={billingPeriod}
@@ -159,6 +161,8 @@ export default function Plans({ items, tenantSubscription, canSubmit, className,
billingProviderCoupon={billingProviderCoupon}
onClickFeature={onClickFeature}
currentPlanInfo={currentPlanInfo}
showFeatures={false}
seatPackage={seatPackageId ? getSeatPackage(seatPackageId) : undefined}
/>
);
});
@@ -0,0 +1,14 @@
// @vitest-environment node
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
describe("customer billing plan cards", () => {
it("hide feature matrices while the admin plan preview keeps them available", () => {
const customerPlans = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/components/core/settings/subscription/Plans.tsx"), "utf8");
const adminPreview = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/components/core/pricing/PricingPlanForm.tsx"), "utf8");
expect(customerPlans).toContain("showFeatures={false}");
expect(adminPreview).toContain("showFeatures");
});
});
@@ -29,6 +29,7 @@ describe("pricing card locale formatting", () => {
expect(source).not.toContain('from "~/utils/helpers/PricingHelper"');
expect(source).not.toContain("NumberUtils.");
expect(source).not.toContain("getFormattedPriceInCurrency");
expect(source).not.toMatch(/formatters\.currency\([^\n]*maximumFractionDigits:\s*0/);
expect(source).not.toContain('"$"');
expect(source).not.toContain('"License"');
expect(source).not.toContain('"Metered"');
@@ -0,0 +1,81 @@
import { useTranslation } from "react-i18next";
import type { SeatUsageCategoryVM, SeatUsageVM } from "@hivegrid/view-models";
import { useLocaleFormatters } from "~/locale/format";
import { Progress } from "~/ui/components/Progress";
/**
* Seat-usage section (Fundament E) — additive, VM-driven, render-only.
*
* Shows how many Büro/Baustelle seats the tenant occupies against the seat
* package limits, and — on overage — the extra seats and their cost in plain
* language. All copy comes through i18n; euro amounts are locale-formatted here.
*/
export default function SeatUsageSection({ vm }: { vm: SeatUsageVM }) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
if (vm.status !== "ready") {
return (
<div className="text-text-neutral-tertiary text-sm" data-ui-id="ui.subscription.seats.empty">
{t("settings.subscription.seats.empty")}
</div>
);
}
const { data } = vm;
const formatEur = (value: number) => formatters.currency(value, data.currency);
return (
<div className="space-y-4" data-ui-id="ui.subscription.seats">
{data.hasPackage && data.packageNameKey ? (
<p className="text-text-neutral-secondary text-sm">{t("settings.subscription.seats.currentPackage", { package: t(data.packageNameKey) })}</p>
) : (
<p className="text-text-neutral-tertiary text-sm">{t(data.noPackageHintKey)}</p>
)}
<ul className="space-y-3">
{data.categories.map((category) => (
<SeatCategoryRow key={category.seatType} category={category} hasPackage={data.hasPackage} />
))}
</ul>
{data.hasOverage ? (
<div className="border-border-default rounded-md border border-dashed px-3 py-2 text-sm" data-ui-id="ui.subscription.seats.overage">
<p className="text-text-neutral-primary font-medium">{t(data.overageNoticeKey)}</p>
<ul className="mt-1 space-y-1">
{data.categories
.filter((category) => category.overLimit && category.extraPriceEur !== null)
.map((category) => (
<li key={category.seatType} className="text-text-neutral-secondary">
{t("settings.subscription.seats.extraLine", {
count: category.extra,
seat: t(category.labelKey),
price: formatEur(category.extraPriceEur ?? 0),
})}
</li>
))}
</ul>
<p className="text-text-neutral-primary mt-2 font-medium">{t("settings.subscription.seats.extraTotal", { total: formatEur(data.totalExtraCostEur) })}</p>
</div>
) : null}
</div>
);
}
function SeatCategoryRow({ category, hasPackage }: { category: SeatUsageCategoryVM; hasPackage: boolean }) {
const { t } = useTranslation();
const hasLimit = hasPackage && category.included !== null;
const percent = hasLimit && (category.included ?? 0) > 0 ? Math.min(100, Math.round((category.used / (category.included ?? 1)) * 100)) : 0;
return (
<li className="space-y-1">
<div className="flex items-baseline justify-between">
<span className="text-text-neutral-primary text-sm font-medium">{t(category.labelKey)}</span>
<span className="text-text-neutral-secondary text-sm tabular-nums">
{hasLimit ? t("settings.subscription.seats.occupancy", { used: category.used, included: category.included }) : t("settings.subscription.seats.occupancyNoLimit", { used: category.used })}
</span>
</div>
{hasLimit ? <Progress value={category.overLimit ? 100 : percent} /> : null}
</li>
);
}
@@ -12,7 +12,7 @@ interface Props {
onCancel: () => void;
}
export default function SubscriptionProducts({ products, subscription, canCancel, onCancel }: Props) {
export default function SubscriptionProducts({ products, subscription: _subscription, canCancel: _canCancel, onCancel: _onCancel }: Props) {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
@@ -26,8 +26,8 @@ export default function ToggleBillingPeriod({
disabled,
possibleBillingPeriods,
darkMode,
currency,
products,
currency: _currency,
products: _products,
}: Props) {
const { t } = useTranslation();
// const [discounts, setDiscounts] = useState<{ billingPeriod: SubscriptionBillingPeriod; discount?: number }[]>([]);
@@ -13,7 +13,6 @@ import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
import { useRootData } from "~/utils/data/useRootData";
import { createLocaleFormatters } from "~/locale/format";
import { translateLabel } from "~/utils/i18n/translateLabel";
interface Props {
items: TenantWithUsage[];
@@ -99,16 +98,6 @@ export default function TenantsTable({ items, pagination, actions = [] }: Props)
</span>
),
});
headers.push({
name: "types",
title: t("shared.types"),
value: (i) =>
i.types.length === 0 ? (
<span className="text-muted-foreground">{t("shared.default")}</span>
) : (
i.types.map((f) => translateLabel(t, i18n, f.title)).join(", ")
),
});
headers.push({
name: "users",
title: t("models.user.plural"),
@@ -7,32 +7,20 @@ import InputText from "~/components/ui/input/InputText";
import UrlUtils from "~/utils/app/UrlUtils";
import type { TenantWithDetails } from "~/utils/db/tenants.db.server";
import LoadingButton from "~/components/ui/buttons/LoadingButton";
import InputCombobox from "~/components/ui/input/InputCombobox";
import { useRootData } from "~/utils/data/useRootData";
import { translateLabel } from "~/utils/i18n/translateLabel";
import { UserIcon } from "~/components/ui/icons/vendor";
type TenantTypeOption = {
id: string;
title: string;
};
interface Props {
tenant: TenantWithDetails;
disabled: boolean;
tenantTypes?: TenantTypeOption[];
options?: {
canChangeType: boolean;
};
}
export default function UpdateTenantDetailsForm({ tenant, disabled, tenantTypes, options }: Props) {
const { i18n, t } = useTranslation();
export default function UpdateTenantDetailsForm({ tenant, disabled }: Props) {
const { t } = useTranslation();
const rootData = useRootData();
const [slug, setSlug] = useState<string | undefined>(tenant?.slug ?? "");
const [icon, setIcon] = useState<string | undefined>(tenant?.icon ?? "");
const [types, setTypes] = useState<string[]>(tenant.types.map((f) => f.id));
function loadedImage(image: string | undefined) {
setIcon(image);
@@ -71,27 +59,6 @@ export default function UpdateTenantDetailsForm({ tenant, disabled, tenantTypes,
}}
/>
</div>
{tenantTypes !== undefined && tenantTypes.length > 0 && (
<div className="col-span-6 sm:col-span-6">
{types?.map((item, idx) => {
return <input key={idx} type="hidden" name={`typeIds[]`} value={item} hidden readOnly />;
})}
<InputCombobox
withSearch={false}
disabled={!options?.canChangeType}
name="typeIds"
title={t("shared.type")}
value={types}
onChange={(e) => setTypes(e as string[])}
options={tenantTypes.map((f) => {
return {
value: f.id,
name: translateLabel(t, i18n, f.title),
};
})}
/>
</div>
)}
<div className="col-span-6 sm:col-span-6">
<label htmlFor="icon" className="text-foreground/80 block text-xs leading-5 font-medium">
{t("shared.icon")}
@@ -1,65 +0,0 @@
import { useEffect, useState } from "react";
import { useFetcher } from "react-router";
import { useTranslation } from "react-i18next";
import { toast } from "sonner";
import { TenantWithProfile } from "~/utils/db/tenants.db.server";
import { useRootData } from "~/utils/data/useRootData";
import { defaultAnrede, isAnrede, type Anrede } from "@hivegrid/i18n";
import SettingSection from "~/components/ui/sections/SettingSection";
import InputChoicebox from "~/components/ui/input/InputChoicebox";
type Props = {
tenant: TenantWithProfile;
};
/**
* Schlichter du/Sie-Umschalter (Anrede). Persistiert `Tenant.anrede` und setzt
* den `_anrede`-Cookie (Server-Action `update-anrede`). Default "du" verhaelt
* sich byte-identisch zum Status quo; "sie" schaltet die App auf die
* "<locale>-formal"-Sprachvariante um (Fallback auf Basis-Locale).
*/
export default function UpdateTenantFormAnrede({ tenant }: Props) {
const { t } = useTranslation();
const { csrf } = useRootData();
const fetcher = useFetcher<{ success?: string; error?: string }>();
const initial: Anrede = isAnrede(tenant?.anrede ?? undefined) ? (tenant.anrede as Anrede) : defaultAnrede;
const [anrede, setAnrede] = useState<Anrede>(initial);
useEffect(() => {
if (fetcher.data?.success) {
toast.success(fetcher.data.success);
} else if (fetcher.data?.error) {
toast.error(fetcher.data.error);
}
}, [fetcher.data]);
const onChange = (value: string) => {
if (!isAnrede(value) || value === anrede) {
return;
}
setAnrede(value);
const form = new FormData();
form.set("action", "update-anrede");
form.set("anrede", value);
if (csrf) {
form.set("csrf", csrf);
}
fetcher.submit(form, { method: "post", preventScrollReset: true });
};
return (
<SettingSection title={t("settings:tenant.anrede.title")} description={t("settings:tenant.anrede.description")}>
<InputChoicebox
name="anrede"
value={anrede}
onChange={onChange}
disabled={fetcher.state !== "idle"}
options={[
{ value: "du", name: t("settings:tenant.anrede.du") },
{ value: "sie", name: t("settings:tenant.anrede.sie") },
]}
/>
</SettingSection>
);
}
@@ -1,809 +0,0 @@
import { useTranslation } from "react-i18next";
import { useEffect, useState } from "react";
import { Link, useFetcher, useSearchParams } from "react-router";
import { toast } from "sonner";
import { Button } from "~/components/ui/button";
import { cn } from "~/lib/utils";
import { Label } from "~/components/ui/label";
import { TenantWithProfile } from "~/utils/db/tenants.db.server";
import { ColorPicker } from "~/components/ui/colors/ColorPicker";
import InputSelect from "~/components/ui/input/InputSelect";
import SettingSection from "~/components/ui/sections/SettingSection";
import { defaultThemes, getThemeConfig } from "~/utils/theme/defaultThemes";
import { useThemePreviewStore } from "~/stores/themePreviewStore";
import { ThemeConfig, defaultThemeConfig, parseThemeConfig } from "~/utils/theme/ThemeConfig";
import { Input } from "~/components/ui/input";
import { useRootData } from "~/utils/data/useRootData";
import { parseCssConfig } from "~/utils/theme/cssConfigParser";
import { exportConfigToCss } from "~/utils/theme/cssConfigExporter";
import { ExternalLinkIcon, ArrowLeftIcon, ArrowRightIcon, ImportIcon, EraserIcon, SunIcon, MoonIcon } from "~/components/ui/icons/vendor";
import ModalOrSlide from "~/components/ui/modals/ModalOrSlide";
import MonacoEditor from "~/components/editors/MonacoEditor";
import InputChoicebox from "~/components/ui/input/InputChoicebox";
type Props = {
tenant: TenantWithProfile;
};
export default function UpdateTenantFormTheme({ tenant }: Props) {
const { t } = useTranslation();
const { csrf, userSession } = useRootData();
const [searchParams] = useSearchParams();
const fetcher = useFetcher<{ success?: string; error?: string }>();
const { setPreviewTheme, setPreviewConfig, enablePreview, disablePreview, resetPreview } = useThemePreviewStore();
const isDarkMode = userSession?.lightOrDarkMode === "dark";
const [theme, setTheme] = useState(tenant?.theme || "");
const [config, setConfig] = useState<ThemeConfig>(() => parseThemeConfig(tenant?.themeConfig as string | null));
const [cssDialogOpen, setCssDialogOpen] = useState(false);
const [cssEditorValue, setCssEditorValue] = useState("");
const isUserInDarkMode = userSession?.lightOrDarkMode === "dark";
// Enable preview mode when component mounts
useEffect(() => {
enablePreview();
return () => {
disablePreview();
};
}, [enablePreview, disablePreview]);
// Update preview whenever state changes
useEffect(() => {
setPreviewTheme(theme || null);
setPreviewConfig(config);
}, [theme, config, setPreviewTheme, setPreviewConfig]);
useEffect(() => {
if (fetcher.data?.success) {
toast.success(fetcher.data.success);
} else if (fetcher.data?.error) {
toast.error(fetcher.data.error);
}
}, [fetcher.data]);
const updateConfigColor = (key: keyof NonNullable<ThemeConfig["colors"]>, value: string) => {
if (isUserInDarkMode) {
setConfig((prev) => ({
...prev,
darkColors: {
...prev.darkColors,
[key]: value || undefined,
},
}));
} else {
setConfig((prev) => ({
...prev,
colors: {
...prev.colors,
[key]: value || undefined,
},
}));
}
};
const getConfigColor = (key: keyof NonNullable<ThemeConfig["colors"]>) => {
if (isUserInDarkMode) {
return config.darkColors?.[key] || "";
}
return config.colors?.[key] || "";
};
const resetToDefaults = () => {
setTheme("");
setConfig({});
resetPreview();
};
const handleApplyCss = () => {
try {
const parsedConfig = parseCssConfig(cssEditorValue);
// Merge the parsed config with existing config
setConfig((prev) => ({
...prev,
...parsedConfig,
colors: {
...prev.colors,
...parsedConfig.colors,
},
darkColors: {
...prev.darkColors,
...parsedConfig.darkColors,
},
}));
// Clear theme preset since we're using custom config
setTheme("");
toast.success(t("settings:tenant.theme.editor.cssApplied"));
setCssDialogOpen(false);
} catch {
toast.error(t("settings:tenant.theme.editor.cssParseFailed"));
}
};
const openCssDialog = () => {
// Pre-populate with current config when opening
setCssEditorValue(exportConfigToCss(config));
setCssDialogOpen(true);
};
function previousTheme() {
const currentIndex = defaultThemes.findIndex((t) => t.value === theme);
const previousIndex = currentIndex - 1;
setTheme(defaultThemes[previousIndex].value);
setConfig(getThemeConfig(defaultThemes[previousIndex].value) || defaultThemeConfig);
}
function nextTheme() {
const currentIndex = defaultThemes.findIndex((t) => t.value === theme);
const nextIndex = currentIndex + 1;
setTheme(defaultThemes[nextIndex].value);
setConfig(getThemeConfig(defaultThemes[nextIndex].value) || defaultThemeConfig);
}
const onThemeToggle = async () => {
const form = new FormData();
form.set("action", "toggleLightOrDarkMode");
form.set("redirect", location.pathname + "?" + searchParams.toString());
if (csrf) {
form.set("csrf", csrf);
}
fetcher.submit(form, { method: "post", action: "/preferences", preventScrollReset: true });
};
return (
<div className="space-y-6">
<fetcher.Form method="post">
<input type="hidden" name="action" value="update-theme" readOnly hidden />
<input type="hidden" name="theme" value={theme} readOnly hidden />
<input type="hidden" name="themeConfig" value={JSON.stringify(config)} readOnly hidden />
<div className="space-y-6">
{/* Appearance Section */}
<SettingSection
title={t("settings:tenant.theme.appearance.title")}
description={t("settings:tenant.theme.appearance.description")}
>
<div className="grid grid-cols-2 gap-4">
{/* Theme Selection */}
<div className="col-span-1">
<div className="mb-2 flex items-center justify-between">
<Label className="block text-sm font-medium">{t("settings:tenant.theme.appearance.themePreset")}</Label>
</div>
<div className="flex items-center gap-2">
<InputSelect
name="themeSelect"
value={theme}
selectClassName="bg-background"
setValue={(value) => {
const newTheme = value?.toString() || "";
setTheme(newTheme);
// Apply theme preset colors if available
if (newTheme) {
const themePreset = getThemeConfig(newTheme);
if (themePreset) {
setConfig((prev) => ({
...prev,
fontFamily: themePreset.fontFamily || prev.fontFamily,
radius: themePreset.radius || prev.radius,
sidebarVariant: themePreset.sidebarVariant || prev.sidebarVariant,
sidebarDarkMode: themePreset.sidebarDarkMode ?? prev.sidebarDarkMode,
colors: {
...prev.colors,
...themePreset.colors,
},
darkColors: {
...prev.darkColors,
...themePreset.darkColors,
},
}));
}
}
}}
options={[
{ value: "", name: t("settings:tenant.theme.appearance.useDefaultTheme") },
...defaultThemes.map((theme) => {
const label = t(theme.labelKey, { defaultValue: theme.name });
return {
value: theme.value,
name: (
<div className="flex items-center space-x-2">
<div
className={cn(
`theme-${theme.value}`,
"inline-flex shrink-0 items-center rounded-sm text-xs font-medium",
"size-2.5",
"bg-primary text-primary"
)}
/>
<span>{label}</span>
</div>
),
};
}),
]}
className="flex-1"
/>
</div>
</div>
<div>
{/* Import/Export Theme */}
<div className="mb-2 flex items-center justify-between">
<Label className="invisible block text-sm font-medium">{t("settings:tenant.theme.appearance.themeActions")}</Label>
</div>
<div className="flex items-center gap-2">
{/* Previous theme */}
<Button type="button" variant="outline" size="sm" onClick={previousTheme} aria-label={t("shared.previous")}>
<ArrowLeftIcon className="size-3.5" aria-hidden="true" />
</Button>
{/* Next theme */}
<Button type="button" variant="outline" size="sm" onClick={nextTheme} aria-label={t("shared.next")}>
<ArrowRightIcon className="size-3.5" aria-hidden="true" />
</Button>
<Button type="button" variant="outline" size="sm" onClick={openCssDialog} aria-label={t("shared.import")}>
<ImportIcon className="size-3.5" aria-hidden="true" />
</Button>
{/* Reset theme */}
<Button type="button" variant="outline" size="sm" onClick={resetToDefaults} aria-label={t("shared.reset")}>
<EraserIcon className="size-3.5" aria-hidden="true" />
</Button>
<Button type="button" variant="outline" size="sm" onClick={onThemeToggle} aria-label={t(isDarkMode ? "shared.light" : "shared.dark")}>
{/* <DarkModeSvgs className="size-3.5" withLabel={false} /> */}
{isDarkMode ? <SunIcon className="size-3.5" aria-hidden="true" /> : <MoonIcon className="size-3.5" aria-hidden="true" />}
</Button>
</div>
</div>
{/* Font Family */}
<div>
<Label className="mb-2 block text-sm font-medium">{t("settings:tenant.theme.appearance.fontFamily")}</Label>
<InputSelect
name="fontFamily"
value={config.fontFamily || ""}
selectClassName="bg-background"
setValue={(value) => setConfig({ ...config, fontFamily: value?.toString() || undefined })}
options={[
{ value: "", name: t("settings:tenant.theme.appearance.defaultSystemUi") },
{
value: "ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif",
name: t("settings:tenant.theme.appearance.fontFamilies.sansSerif"),
},
{ value: "ui-serif, Georgia, Cambria, 'Times New Roman', Times, serif", name: t("settings:tenant.theme.appearance.fontFamilies.serif") },
{
value: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace",
name: t("settings:tenant.theme.appearance.fontFamilies.monospace"),
},
{ value: "Inter, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.inter") },
{ value: "Geist, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.geist") },
{ value: "Outfit, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.outfit") },
{ value: "'Open Sans', sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.openSans") },
{ value: "Roboto, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.roboto") },
{ value: "Poppins, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.poppins") },
{ value: "Montserrat, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.montserrat") },
{ value: "Lato, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.lato") },
{ value: "'Source Sans Pro', sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.sourceSansPro") },
{ value: "Raleway, sans-serif", name: t("settings:tenant.theme.appearance.fontFamilies.raleway") },
{ value: "'Playfair Display', serif", name: t("settings:tenant.theme.appearance.fontFamilies.playfairDisplay") },
{ value: "Merriweather, serif", name: t("settings:tenant.theme.appearance.fontFamilies.merriweather") },
{ value: "'JetBrains Mono', monospace", name: t("settings:tenant.theme.appearance.fontFamilies.jetbrainsMono") },
{ value: "'Fira Code', monospace", name: t("settings:tenant.theme.appearance.fontFamilies.firaCode") },
]}
/>
</div>
{/* Border Radius */}
<div>
<Label className="mb-2 block text-sm font-medium">{t("settings:tenant.theme.appearance.borderRadius")}</Label>
<div className="flex items-center gap-2">
<Input
type="number"
step="0.01"
min={0}
max={2}
value={parseFloat(config.radius?.replace("rem", "") || "0.5")}
onChange={(e) => setConfig({ ...config, radius: `${e.target.value}rem` })}
placeholder="0.5"
className="bg-background w-full"
/>
</div>
</div>
</div>
</SettingSection>
{/*Separator */}
<div className="block">
<div className="py-5">
<div className="border-border border-t"></div>
</div>
</div>
{/* Colors Section */}
<SettingSection title={t("settings:tenant.theme.colors.title")} description={t(isUserInDarkMode ? "settings.tenant.theme.colors.modes.dark" : "settings.tenant.theme.colors.modes.light")}>
<div className="space-y-4">
<div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.background")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.background")}
value={getConfigColor("background")}
onChange={(color) => updateConfigColor("background", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("background") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.foreground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.foreground")}
value={getConfigColor("foreground")}
onChange={(color) => updateConfigColor("foreground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("foreground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.primary")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.primary")}
value={getConfigColor("primary")}
onChange={(color) => updateConfigColor("primary", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("primary") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.primaryForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.primaryForeground")}
value={getConfigColor("primaryForeground")}
onChange={(color) => updateConfigColor("primaryForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("primaryForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.secondary")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.secondary")}
value={getConfigColor("secondary")}
onChange={(color) => updateConfigColor("secondary", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("secondary") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.secondaryForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.secondaryForeground")}
value={getConfigColor("secondaryForeground")}
onChange={(color) => updateConfigColor("secondaryForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("secondaryForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.accent")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.accent")}
value={getConfigColor("accent")}
onChange={(color) => updateConfigColor("accent", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("accent") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.accentForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.accentForeground")}
value={getConfigColor("accentForeground")}
onChange={(color) => updateConfigColor("accentForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("accentForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.destructive")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.destructive")}
value={getConfigColor("destructive")}
onChange={(color) => updateConfigColor("destructive", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("destructive") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.destructiveForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.destructiveForeground")}
value={getConfigColor("destructiveForeground")}
onChange={(color) => updateConfigColor("destructiveForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("destructiveForeground") || t("shared.default")}</span>
</div>
</div>
</div>
</div>
<div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.card")}</Label>
<div className="flex items-center gap-2">
<ColorPicker title={t("settings:tenant.theme.tokens.card")} value={getConfigColor("card")} onChange={(color) => updateConfigColor("card", color)} className="size-10" />
<span className="text-muted-foreground text-xs">{getConfigColor("card") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.cardForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.cardForeground")}
value={getConfigColor("cardForeground")}
onChange={(color) => updateConfigColor("cardForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("cardForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.popover")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.popover")}
value={getConfigColor("popover")}
onChange={(color) => updateConfigColor("popover", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("popover") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.popoverForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.popoverForeground")}
value={getConfigColor("popoverForeground")}
onChange={(color) => updateConfigColor("popoverForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("popoverForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.muted")}</Label>
<div className="flex items-center gap-2">
<ColorPicker title={t("settings:tenant.theme.tokens.muted")} value={getConfigColor("muted")} onChange={(color) => updateConfigColor("muted", color)} className="size-10" />
<span className="text-muted-foreground text-xs">{getConfigColor("muted") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.mutedForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.mutedForeground")}
value={getConfigColor("mutedForeground")}
onChange={(color) => updateConfigColor("mutedForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("mutedForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.border")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.border")}
value={getConfigColor("border")}
onChange={(color) => updateConfigColor("border", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("border") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.input")}</Label>
<div className="flex items-center gap-2">
<ColorPicker title={t("settings:tenant.theme.tokens.input")} value={getConfigColor("input")} onChange={(color) => updateConfigColor("input", color)} className="size-10" />
<span className="text-muted-foreground text-xs">{getConfigColor("input") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.ring")}</Label>
<div className="flex items-center gap-2">
<ColorPicker title={t("settings:tenant.theme.tokens.ring")} value={getConfigColor("ring")} onChange={(color) => updateConfigColor("ring", color)} className="size-10" />
<span className="text-muted-foreground text-xs">{getConfigColor("ring") || t("shared.default")}</span>
</div>
</div>
</div>
</div>
</div>
</SettingSection>
{/*Separator */}
<div className="block">
<div className="py-5">
<div className="border-border border-t"></div>
</div>
</div>
{/* Sidebar Section */}
<SettingSection
title={t("settings:tenant.theme.sidebar.title")}
description={t("settings:tenant.theme.sidebar.description")}
>
<div className="space-y-6">
{/* Sidebar Settings */}
<div>
<div className="space-y-4">
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.sidebar.style")}</Label>
<InputChoicebox
name="sidebarVariant"
value={config.sidebarVariant || "inset"}
// selectClassName="bg-background"
onChange={(value) => setConfig({ ...config, sidebarVariant: value as "inset" | "sidebar" })}
options={[
{ value: "inset", name: t("settings:tenant.theme.sidebar.styleOptions.inset") },
{ value: "sidebar", name: t("settings:tenant.theme.sidebar.styleOptions.sidebar") },
]}
/>
</div>
{/*
<InputCheckboxInline
name="sidebarDarkMode"
title={t("settings:tenant.theme.sidebar.forceDark")}
value={config.sidebarDarkMode || false}
setValue={(value) => setConfig({ ...config, sidebarDarkMode: value as boolean })}
/> */}
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.sidebar.theme")}</Label>
<InputChoicebox
name="sidebarDarkMode"
value={config.sidebarDarkMode ? "true" : "false"}
onChange={(value) => setConfig({ ...config, sidebarDarkMode: value === "true" })}
options={[
{ value: "false", name: t("shared.light") },
{ value: "true", name: t("shared.dark") },
]}
/>
</div>
</div>
</div>
{/* Sidebar Colors */}
<div>
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.sidebar")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebar")}
value={getConfigColor("sidebar")}
onChange={(color) => updateConfigColor("sidebar", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebar") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.background")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarBackground")}
value={getConfigColor("sidebarBackground")}
onChange={(color) => updateConfigColor("sidebarBackground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarBackground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.foreground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarForeground")}
value={getConfigColor("sidebarForeground")}
onChange={(color) => updateConfigColor("sidebarForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.primary")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarPrimary")}
value={getConfigColor("sidebarPrimary")}
onChange={(color) => updateConfigColor("sidebarPrimary", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarPrimary") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.primaryForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarPrimaryForeground")}
value={getConfigColor("sidebarPrimaryForeground")}
onChange={(color) => updateConfigColor("sidebarPrimaryForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarPrimaryForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.accent")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarAccent")}
value={getConfigColor("sidebarAccent")}
onChange={(color) => updateConfigColor("sidebarAccent", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarAccent") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.accentForeground")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarAccentForeground")}
value={getConfigColor("sidebarAccentForeground")}
onChange={(color) => updateConfigColor("sidebarAccentForeground", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarAccentForeground") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.border")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarBorder")}
value={getConfigColor("sidebarBorder")}
onChange={(color) => updateConfigColor("sidebarBorder", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarBorder") || t("shared.default")}</span>
</div>
</div>
<div>
<Label className="mb-1 block text-xs">{t("settings:tenant.theme.tokens.ring")}</Label>
<div className="flex items-center gap-2">
<ColorPicker
title={t("settings:tenant.theme.tokens.sidebarRing")}
value={getConfigColor("sidebarRing")}
onChange={(color) => updateConfigColor("sidebarRing", color)}
className="size-10"
/>
<span className="text-muted-foreground text-xs">{getConfigColor("sidebarRing") || t("shared.default")}</span>
</div>
</div>
</div>
</div>
</div>
</SettingSection>
{/*Separator */}
<div className="block">
<div className="py-1">
<div className=""></div>
</div>
</div>
<div className="flex items-center justify-end gap-2">
<Button type="button" variant="outline" onClick={resetToDefaults}>
{t("shared.reset")}
</Button>
<Button
type="submit"
variant={"default"}
disabled={fetcher.state === "submitting"}
className={cn(fetcher.state === "submitting" && "base-spinner")}
>
{t("shared.save")}
</Button>
</div>
</div>
</fetcher.Form>
{/* CSS Configuration Modal */}
<ModalOrSlide
type="slide"
open={cssDialogOpen}
setOpen={setCssDialogOpen}
title={t("settings:tenant.theme.editor.title")}
description={t("settings:tenant.theme.editor.description")}
size="3xl"
buttons={
<div className="flex justify-end gap-2">
<div className="flex gap-2">
<Button type="button" variant="outline" size="sm" asChild>
<Link to="https://tweakcn.com/editor/theme" target="_blank">
<ExternalLinkIcon className="mr-2 h-4 w-4" />
{t("settings:tenant.theme.editor.externalEditor")}
</Link>
</Button>
{/* <Button
type="button"
variant="outline"
size="sm"
onClick={() => {
navigator.clipboard.writeText(cssEditorValue);
toast.success(t("settings:tenant.theme.editor.cssCopied"));
}}
>
<CopyIcon className="mr-2 h-4 w-4" />
Copy
</Button> */}
<Button type="button" onClick={handleApplyCss} size="sm">
{t("settings:tenant.theme.editor.applyChanges")}
</Button>
</div>
</div>
}
>
<MonacoEditor
className="h-[calc(100vh-180px)] overflow-hidden"
value={cssEditorValue}
onChange={(value) => setCssEditorValue(value || "")}
language="css"
theme="vs-dark"
/>
</ModalOrSlide>
</div>
);
}
@@ -1,32 +0,0 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
const sourcePath = path.resolve(process.cwd(), "apps/web/app/components/core/tenants/forms/UpdateTenantFormTheme.tsx");
describe("tenant theme form i18n", () => {
it("uses semantic settings keys for appearance, color tokens, sidebar, and CSS editor copy", () => {
const source = fs.readFileSync(sourcePath, "utf8");
expect(source).toContain("settings:tenant.theme.appearance.title");
expect(source).toContain("settings:tenant.theme.appearance.themePreset");
expect(source).toContain("theme.labelKey");
expect(source).toContain("settings:tenant.theme.appearance.defaultSystemUi");
expect(source).toContain("settings:tenant.theme.appearance.fontFamilies.sansSerif");
expect(source).toContain("settings:tenant.theme.appearance.fontFamilies.jetbrainsMono");
expect(source).toContain("settings:tenant.theme.colors.title");
expect(source).toContain("settings:tenant.theme.tokens.primaryForeground");
expect(source).toContain("settings:tenant.theme.sidebar.styleOptions.inset");
expect(source).toContain("settings:tenant.theme.editor.cssApplied");
expect(source).toContain("settings:tenant.theme.editor.applyChanges");
expect(source).not.toContain("ui.autogenerated");
expect(source).not.toContain('"Use default theme"');
expect(source).not.toContain(">Reset<");
expect(source).not.toContain('"Default"');
expect(source).not.toContain('"Colors"');
expect(source).not.toContain('"Inset (Light)"');
expect(source).not.toContain('name: "Sans Serif"');
expect(source).not.toContain('name: "JetBrains Mono"');
expect(source).not.toContain("<span>{theme.name}</span>");
});
});
@@ -1,72 +0,0 @@
import { useState, useEffect, useRef, Fragment } from "react";
import { getUserHasPermission } from "~/utils/helpers/PermissionsHelper";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useTranslation } from "react-i18next";
import FormGroup from "~/components/ui/forms/FormGroup";
import InputText, { RefInputText } from "~/components/ui/input/InputText";
import { useNavigate } from "react-router";
import { TenantTypeWithDetails } from "~/utils/db/tenants/tenantTypes.db.server";
import { SubscriptionProductDto } from "~/application/dtos/subscriptions/SubscriptionProductDto";
import InputCheckboxCards from "~/components/ui/input/InputCheckboxCards";
import InputCheckboxWithDescription from "~/components/ui/input/InputCheckboxWithDescription";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
export function TenantTypeForm({ item, allSubscriptionProducts }: { item?: TenantTypeWithDetails; allSubscriptionProducts: SubscriptionProductDto[] }) {
const { t } = useTranslation();
const appOrAdminData = useAppOrAdminData();
const navigate = useNavigate();
const [title, setTitle] = useState(item?.title || "");
const [titlePlural, setTitlePlural] = useState(item?.titlePlural || "");
const [description, setDescription] = useState(item?.description || "");
const [isDefault, setIsDefault] = useState(item?.isDefault || false);
const [subscriptionProducts, setSubscriptionProducts] = useState(item?.subscriptionProducts.map((p) => p.id) || []);
const input = useRef<RefInputText>(null);
useEffect(() => {
setTimeout(() => {
input.current?.input.current?.focus();
}, 100);
}, []);
return (
<FormGroup
id={item?.id}
onCancel={() => navigate(adminPath("settings/accounts/types", { mode: "host-aware" }))}
editing={true}
canDelete={getUserHasPermission(appOrAdminData, "admin.accountTypes.delete")}
>
<div className="space-y-2">
<InputText ref={input} autoFocus name="title" title={t("shared.title")} value={title} setValue={setTitle} required />
<InputText name="titlePlural" title={t("shared.titlePlural")} value={titlePlural} setValue={setTitlePlural} required />
<InputText name="description" title={t("shared.description")} value={description} setValue={setDescription} />
<InputCheckboxWithDescription
name="isDefault"
title={t("settings.admin.tenants.types.fields.isDefault.title")}
value={isDefault}
setValue={setIsDefault}
description={t("settings.admin.tenants.types.fields.isDefault.description")}
/>
<Fragment>
{subscriptionProducts?.map((item, idx) => {
return <input key={idx} type="hidden" name={`subscriptionProducts[]`} value={item} />;
})}
<InputCheckboxCards
columns={1}
title={t("models.subscriptionProduct.plural")}
value={subscriptionProducts}
onChange={(e) => setSubscriptionProducts(e as string[])}
display={"name"}
options={allSubscriptionProducts.map((f) => {
return {
value: f.id ?? "",
name: t(f.title),
};
})}
/>
</Fragment>
<input type="hidden" name="action" value="create" hidden readOnly />
</div>
</FormGroup>
);
}
@@ -1,4 +1,4 @@
import { AdminUser, Role, UserRole } from "@hivegrid/db/prisma-browser";
import { Role, UserRole } from "@hivegrid/db/prisma-browser";
import { useTranslation } from "react-i18next";
import AtSymbolIcon from "~/components/ui/icons/AtSymbolIcon";
import UserAvatarBadge from "./UserAvatarBadge";
@@ -14,7 +14,7 @@ interface Props {
lastName: string;
avatar?: string | null;
};
admin?: AdminUser | null;
admin?: { userId: string } | null;
withEmail?: boolean;
withAvatar?: boolean;
withSignUpMethod?: boolean;
@@ -1,4 +1,4 @@
import { Log, Role, User } from "@hivegrid/db/prisma-browser";
import { Role, User } from "@hivegrid/db/prisma-browser";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Link, useSubmit } from "react-router";
@@ -14,6 +14,10 @@ import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import { absoluteAppPath } from "~/utils/app/CrossHostUrls";
import { useRootData } from "~/utils/data/useRootData";
import { roleDisplayName } from "../roles/roleDisplay";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { TextArea } from "~/ui/components/TextArea";
import type { AdminUserLastActivity } from "~/utils/db/logs.db.server";
interface Props {
items: UserWithDetails[];
@@ -22,7 +26,7 @@ interface Props {
canSetUserRoles?: boolean;
canDelete: boolean;
pagination?: PaginationDto;
lastLogs?: { userId: string; log: Log }[];
lastLogs?: { userId: string; log: AdminUserLastActivity }[];
}
export default function UsersTable({ items, canImpersonate, canChangePassword, canSetUserRoles, canDelete, pagination, lastLogs }: Props) {
const { i18n, t } = useTranslation();
@@ -34,6 +38,8 @@ export default function UsersTable({ items, canImpersonate, canChangePassword, c
const [headers, setHeaders] = useState<RowHeaderDisplayDto<UserWithDetails>[]>([]);
const [actions, setActions] = useState<RowHeaderActionDto<UserWithDetails>[]>([]);
const [impersonatingUser, setImpersonatingUser] = useState<UserWithDetails | null>(null);
const [impersonationReason, setImpersonationReason] = useState("");
useEffect(() => {
function getRoleNames(user: UserWithDetails, tenantId: string | null) {
@@ -123,7 +129,10 @@ export default function UsersTable({ items, canImpersonate, canChangePassword, c
if (canImpersonate) {
actions.push({
title: t("models.user.impersonate"),
onClick: (_, item) => impersonate(item),
onClick: (_, item) => {
setImpersonationReason("");
setImpersonatingUser(item);
},
disabled: (_) => !canImpersonate,
});
}
@@ -155,13 +164,14 @@ export default function UsersTable({ items, canImpersonate, canChangePassword, c
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [formatters, items, lastLogs, t]);
function impersonate(user: UserWithDetails) {
function impersonate(user: UserWithDetails, reason: string) {
const form = new FormData();
if (rootData.csrf) {
form.set("csrf", rootData.csrf);
}
form.set("action", "impersonate");
form.set("user-id", user.id);
form.set("reason", reason.trim());
submit(form, {
action: adminPath("accounts/users", { mode: "host-aware" }),
method: "post",
@@ -205,6 +215,41 @@ export default function UsersTable({ items, canImpersonate, canChangePassword, c
return (
<div>
<TableSimple items={items} headers={headers} actions={actions} pagination={pagination} />
<Dialog open={impersonatingUser !== null} onOpenChange={(open: boolean) => (open ? undefined : setImpersonatingUser(null))}>
<Dialog.Content className="w-[560px] max-w-[90vw] p-4">
{impersonatingUser ? (
<div className="flex w-full flex-col gap-6" data-ui-id="ui.admin.users.impersonate.dialog">
<div className="flex flex-col gap-2">
<span className="text-heading-3 font-heading-3 text-text-neutral-primary">{t("admin.users.impersonation.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">
{t("admin.users.impersonation.body", { email: impersonatingUser.email })}
</span>
</div>
<TextArea showLabel label={t("admin.users.impersonation.reasonLabel")} helpText={t("admin.users.impersonation.reasonHelp")}>
<TextArea.Input
value={impersonationReason}
onChange={(event) => setImpersonationReason(event.currentTarget.value)}
placeholder={t("admin.users.impersonation.reasonPlaceholder")}
data-ui-id="ui.admin.users.impersonate.reason"
/>
</TextArea>
<div className="flex w-full items-center justify-end gap-2">
<Button variant="tertiary" onClick={() => setImpersonatingUser(null)}>{t("shared.cancel")}</Button>
<Button
disabled={impersonationReason.trim().length < 10}
onClick={() => {
impersonate(impersonatingUser, impersonationReason);
setImpersonatingUser(null);
}}
data-ui-id="ui.admin.users.impersonate.confirm"
>
{t("models.user.impersonate")}
</Button>
</div>
</div>
) : null}
</Dialog.Content>
</Dialog>
<ConfirmModal ref={confirmDelete} onYes={confirmDeleteUser} destructive />
</div>
);
@@ -217,7 +262,7 @@ function LastActivity({
formatters,
}: {
item: UserWithDetails;
lastLogs?: { userId: string; log: Log }[];
lastLogs?: { userId: string; log: AdminUserLastActivity }[];
action?: string;
formatters: LocaleFormatters;
}) {
@@ -1,430 +0,0 @@
// R-P6 (P6 CRM core, Variante A) — presentational contact/organisation detail.
// Pure component: it receives the server-built KontaktDetailVM data + the
// Activity-Stream VM + option lists and renders the inline-edit forms (DoD 3).
// It NEVER calls useLoaderData/useFetcher (the route injects the data) and holds
// no server imports; every form posts back to the current route's action.
import { useTranslation } from "react-i18next";
import type { ActivityStreamVM, KontaktDetailData } from "@hivegrid/view-models";
export type KontaktDetailViewProps = {
data: KontaktDetailData;
activity: ActivityStreamVM;
allTags: { id: string; name: string; farbe: string }[];
customFieldDefs: { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string }[];
ownerOptions: { id: string; label: string }[];
backHref: string;
listLabelKey: string;
errorKey?: string | null;
};
const crmFieldLabelClass = "block text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary";
const crmFieldControlClass =
"mt-1 h-9 w-full rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle focus:shadow-focus";
const crmTextareaClass =
"mt-1 w-full rounded-sm border border-solid border-border-strong bg-surface-neutral-primary px-3 py-2 text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary outline-none placeholder:text-text-neutral-subtle focus:shadow-focus";
export default function KontaktDetailView(props: KontaktDetailViewProps) {
const { t, i18n } = useTranslation();
const { data } = props;
const isOrg = data.kontaktTyp === "organisation";
const dateTime = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium", timeStyle: "short" });
return (
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.crm.detail">
<nav className="text-muted-foreground mb-4 text-sm" aria-label={t("crm.detail.breadcrumb")} data-ui-id="ui.crm.detail.breadcrumb">
<a href={props.backHref} className="hover:text-foreground" data-ui-id="ui.crm.detail.back">
{t(props.listLabelKey)}
</a>
<span className="px-2">{"/"}</span>
<span className="text-foreground">{data.displayName}</span>
</nav>
<header className="flex flex-wrap items-center gap-3">
<h1 className="text-foreground text-xl font-semibold">{data.displayName}</h1>
<span className="border-border rounded border px-2 py-0.5 text-xs">{t(data.typLabelKey)}</span>
<span className="border-border rounded border px-2 py-0.5 text-xs">{t(data.statusLabelKey)}</span>
{data.isArchived ? <span className="text-destructive text-xs">{t("crm.detail.archivedBadge")}</span> : null}
</header>
{props.errorKey ? (
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.detail.error">
{t(props.errorKey)}
</p>
) : null}
{/* --- Basics (inline edit) --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.basics">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.basics")}</h2>
{data.canWrite ? (
<form method="post" className="mt-2 grid gap-2 sm:grid-cols-2">
<input type="hidden" name="intent" value="updateBasics" />
{isOrg ? (
<>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.orgName")}</span>
<input name="orgName" defaultValue={data.orgName ?? ""} className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.orgMerkmal")}</span>
<select name="orgMerkmal" defaultValue={data.orgMerkmal ?? ""} className={crmFieldControlClass}>
<option value="">{t("crm.fields.none")}</option>
{(["gmbh", "kg", "oeffentliche_einrichtung", "sonstige"] as const).map((merkmal) => (
<option key={merkmal} value={merkmal}>
{t(`crm.orgMerkmal.${merkmal}`)}
</option>
))}
</select>
</label>
</>
) : (
<>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.vorname")}</span>
<input name="vorname" defaultValue={data.vorname ?? ""} className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.nachname")}</span>
<input name="nachname" defaultValue={data.nachname ?? ""} className={crmFieldControlClass} />
</label>
</>
)}
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.status")}</span>
<select name="kontaktStatus" defaultValue={data.kontaktStatus} className={crmFieldControlClass}>
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
<option key={status} value={status}>
{t(`crm.kontaktStatus.${status}`)}
</option>
))}
</select>
</label>
<div className="sm:col-span-2">
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.detail.basics.save">
{t("crm.actions.save")}
</button>
</div>
</form>
) : (
<dl className="mt-2 grid grid-cols-[8rem_1fr] gap-y-1 text-sm">
<dt className="text-muted-foreground">{t("crm.fields.status")}</dt>
<dd>{t(data.statusLabelKey)}</dd>
{data.orgMerkmalLabelKey ? (
<>
<dt className="text-muted-foreground">{t("crm.fields.orgMerkmal")}</dt>
<dd>{t(data.orgMerkmalLabelKey)}</dd>
</>
) : null}
</dl>
)}
</section>
{/* --- Emails --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.emails">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.emails")}</h2>
<ul className="mt-2 text-sm">
{data.emails.map((email) => (
<li key={email.id} className="flex items-center gap-2 py-0.5" data-row-id={email.id}>
<span>{email.email}</span>
{email.primaer ? <span className="text-theme-600 text-xs">{t("crm.detail.primary")}</span> : null}
{data.canWrite && !email.primaer ? (
<form method="post">
<input type="hidden" name="intent" value="setPrimaryEmail" />
<input type="hidden" name="emailId" value={email.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.makePrimary")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeEmail" />
<input type="hidden" name="emailId" value={email.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addEmail" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.email")}</span>
<input name="email" type="email" required className={crmFieldControlClass} />
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="primaer" value="1" /> {t("crm.detail.primary")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Phones --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.telefone">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.telefone")}</h2>
<ul className="mt-2 text-sm">
{data.telefone.map((tel) => (
<li key={tel.id} className="flex items-center gap-2 py-0.5" data-row-id={tel.id}>
<span>{tel.telefon}</span>
{tel.primaer ? <span className="text-theme-600 text-xs">{t("crm.detail.primary")}</span> : null}
{data.canWrite && !tel.primaer ? (
<form method="post">
<input type="hidden" name="intent" value="setPrimaryTelefon" />
<input type="hidden" name="telefonId" value={tel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.makePrimary")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeTelefon" />
<input type="hidden" name="telefonId" value={tel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addTelefon" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.telefon")}</span>
<input name="telefon" required className={crmFieldControlClass} />
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="primaer" value="1" /> {t("crm.detail.primary")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Address (read-only) --- */}
{data.adresse ? (
<section className="mt-6" data-ui-id="ui.crm.detail.adresse">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.adresse")}</h2>
<p className="mt-1 text-sm">
{[data.adresse.strasse, data.adresse.hausnummer].filter(Boolean).join(" ")}
{data.adresse.plz || data.adresse.ort ? `, ${[data.adresse.plz, data.adresse.ort].filter(Boolean).join(" ")}` : ""}
{`, ${data.adresse.land}`}
</p>
</section>
) : null}
{/* --- Relations --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.relations">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.relations")}</h2>
<ul className="mt-2 text-sm">
{data.relationen.map((rel) => (
<li key={rel.id} className="flex items-center gap-2 py-0.5" data-row-id={rel.id}>
<span>{rel.otherKontaktId}</span>
<span className="text-muted-foreground text-xs">{t(rel.rolleLabelKey)}</span>
{rel.kontext ? <span className="text-muted-foreground text-xs">{rel.kontext}</span> : null}
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeRelation" />
<input type="hidden" name="relationId" value={rel.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="addRelation" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationTarget")}</span>
<input name="zuKontaktId" required className={crmFieldControlClass} />
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationRole")}</span>
<select name="rolle" className={crmFieldControlClass}>
{(["hauptkontakt", "sekundaerkontakt", "mitarbeiter", "sonstige"] as const).map((rolle) => (
<option key={rolle} value={rolle}>
{t(`crm.kontaktArt.${rolle}`)}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.relationContext")}</span>
<input name="kontext" className={crmFieldControlClass} />
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Tags --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.tags">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.tags")}</h2>
<ul className="mt-2 flex flex-wrap gap-2 text-sm">
{data.tags.map((tag) => (
<li key={tag.id} className="border-border flex items-center gap-1 rounded border px-2 py-0.5" data-row-id={tag.id}>
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
<span>{tag.name}</span>
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value="removeTag" />
<input type="hidden" name="tagId" value={tag.id} />
<button type="submit" className="text-muted-foreground text-xs underline">
{t("crm.actions.remove")}
</button>
</form>
) : null}
</li>
))}
</ul>
{data.canWrite && props.allTags.length > 0 ? (
<form method="post" className="mt-2 flex items-end gap-2">
<input type="hidden" name="intent" value="addTag" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.tag")}</span>
<select name="tagId" className={crmFieldControlClass}>
{props.allTags.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.add")}
</button>
</form>
) : null}
</section>
{/* --- Custom fields --- */}
<section className="mt-6" data-ui-id="ui.crm.detail.customFields">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.customFields")}</h2>
<dl className="mt-2 grid grid-cols-[10rem_1fr] gap-y-1 text-sm">
{data.customFields.map((cf) => (
<div key={cf.definitionId} className="contents" data-row-id={cf.definitionId}>
<dt className="text-muted-foreground">{cf.label}</dt>
<dd>{cf.wert == null ? "" : String(cf.wert)}</dd>
</div>
))}
</dl>
{data.canWrite && props.customFieldDefs.length > 0 ? (
<form method="post" className="mt-2 flex flex-wrap items-end gap-2">
<input type="hidden" name="intent" value="setCustomField" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.customField")}</span>
<select name="definitionId" className={crmFieldControlClass}>
{props.customFieldDefs.map((def) => (
<option key={def.id} value={def.id}>
{def.label}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.value")}</span>
<input name="wert" className={crmFieldControlClass} />
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.save")}
</button>
</form>
) : null}
</section>
{/* --- Quick actions --- */}
{data.canWrite || data.canDelete ? (
<section className="mt-8 border-t pt-4" data-ui-id="ui.crm.detail.actions">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.actions")}</h2>
<div className="mt-2 flex flex-wrap items-end gap-4">
{data.canWrite ? (
<form method="post" className="flex items-end gap-2">
<input type="hidden" name="intent" value="reassign" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.owner")}</span>
<select name="zustaendigerUserId" defaultValue={data.zustaendigerUserId ?? ""} className={crmFieldControlClass}>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.reassign")}
</button>
</form>
) : null}
{data.canWrite ? (
<form method="post" className="flex-1">
<input type="hidden" name="intent" value="addNote" />
<label className="text-sm">
<span className={crmFieldLabelClass}>{t("crm.fields.note")}</span>
<textarea name="note" required rows={2} className={crmTextareaClass} />
</label>
<button type="submit" className="text-theme-600 mt-1 text-sm font-medium" data-ui-id="ui.crm.detail.addNote">
{t("crm.actions.addNote")}
</button>
</form>
) : null}
</div>
<div className="mt-3 flex flex-wrap gap-3">
{data.canWrite ? (
<form method="post">
<input type="hidden" name="intent" value={data.isArchived ? "reactivate" : "archive"} />
<button type="submit" className="text-theme-600 text-sm font-medium" data-ui-id="ui.crm.detail.archive">
{t(data.isArchived ? "crm.actions.reactivate" : "crm.actions.archive")}
</button>
</form>
) : null}
{data.canDelete ? (
<form method="post">
<input type="hidden" name="intent" value="delete" />
<button type="submit" className="text-destructive text-sm font-medium" data-ui-id="ui.crm.detail.delete">
{t("crm.actions.delete")}
</button>
</form>
) : null}
</div>
</section>
) : null}
{/* --- Activity stream --- */}
<section className="mt-8 border-t pt-4" data-ui-id="ui.crm.detail.activity">
<h2 className="text-muted-foreground text-xs font-semibold uppercase">{t("crm.detail.section.activity")}</h2>
{props.activity.status === "ready" && props.activity.data ? (
<ul className="mt-2 space-y-2 text-sm">
{props.activity.data.entries.map((entry) => (
<li key={entry.id} className="border-border border-l-2 pl-3" data-row-id={entry.id}>
<p>{entry.summaryText}</p>
<p className="text-muted-foreground text-xs">
{t(entry.activityLabelKey)}
{entry.actorLabel ? ` · ${entry.actorLabel}` : ""} · <time dateTime={entry.createdAtIso}>{dateTime.format(new Date(entry.createdAtIso))}</time>
</p>
</li>
))}
</ul>
) : (
<p className="text-muted-foreground mt-2 text-sm" data-ui-id="ui.crm.detail.activity.empty">
{t("crm.detail.activityEmpty")}
</p>
)}
</section>
</main>
);
}
@@ -1,256 +0,0 @@
// R-P6 (P6 CRM core, Variante A) — presentational contact/organisation browser.
// Pure component: it renders the server-built KontaktListVM (filter / sort /
// paginate / bulk / CSV, DoD 2). The filter bar is a GET form (state lives in the
// URL); bulk actions are a POST form whose checkboxes carry the selected ids.
// No useLoaderData/useFetcher, no server imports.
import { useTranslation } from "react-i18next";
import type { KontaktListVM } from "@hivegrid/view-models";
import { kontaktListQueryToParams, type KontaktListQuery } from "~/utils/integrations/crm/kontaktListQuery";
export type KontaktListViewProps = {
moduleActive: boolean;
variant: "contacts" | "companies";
vm: KontaktListVM;
tagOptions: { id: string; name: string; farbe: string }[];
ownerOptions: { id: string; label: string }[];
query: KontaktListQuery;
baseHref: string;
newHref: string;
exportHref: string;
errorKey?: string | null;
};
function pageHref(baseHref: string, query: KontaktListQuery, page: number): string {
const params = kontaktListQueryToParams({ ...query, page });
const qs = params.toString();
return qs ? `${baseHref}?${qs}` : baseHref;
}
export default function KontaktListView(props: KontaktListViewProps) {
const { t } = useTranslation();
const titleKey = props.variant === "companies" ? "crm.companies.title" : "crm.contacts.title";
const emptyHeadlineKey = props.variant === "companies" ? "crm.empty.companies.headline" : "crm.empty.contacts.headline";
const emptyBodyKey = props.variant === "companies" ? "crm.empty.companies.body" : "crm.empty.contacts.body";
if (!props.moduleActive) {
return (
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.crm.list">
<div className="mt-10 text-center" data-ui-id="ui.crm.list.locked">
<p className="text-foreground font-medium">{t("crm.locked.headline")}</p>
<p className="text-muted-foreground mt-1 text-sm">{t("crm.locked.body")}</p>
</div>
</main>
);
}
const data = props.vm.status === "ready" ? props.vm.data : null;
const { filter, sort } = props.query;
return (
<main className="mx-auto max-w-6xl px-4 py-10" data-ui-id="ui.crm.list">
<header className="flex flex-wrap items-center justify-between gap-3">
<h1 className="text-foreground text-xl font-semibold">{t(titleKey)}</h1>
<div className="flex gap-3 text-sm">
<a href={props.exportHref} className="text-theme-600 font-medium" data-ui-id="ui.crm.list.export">
{t("crm.actions.exportCsv")}
</a>
<a href={props.newHref} className="text-theme-600 font-medium" data-ui-id="ui.crm.list.new">
{t("crm.actions.newContact")}
</a>
</div>
</header>
{/* --- Filter bar (GET, URL-driven, server-side) --- */}
<form method="get" action={props.baseHref} className="mt-6 flex flex-wrap items-end gap-2" data-ui-id="ui.crm.list.filter">
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.search")}</span>
<input name="q" defaultValue={filter.search ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1" />
</label>
{props.variant === "contacts" ? (
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.type")}</span>
<select name="typ" defaultValue={filter.kontaktTyp ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
<option value="privatperson">{t("crm.kontaktTyp.privatperson")}</option>
<option value="organisation">{t("crm.kontaktTyp.organisation")}</option>
</select>
</label>
) : null}
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.status")}</span>
<select name="status" defaultValue={filter.kontaktStatus ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
{(["kontakt", "kunde", "bestandskunde"] as const).map((status) => (
<option key={status} value={status}>
{t(`crm.kontaktStatus.${status}`)}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.owner")}</span>
<select name="owner" defaultValue={filter.zustaendigerUserId ?? ""} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="">{t("crm.filter.any")}</option>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.tags")}</span>
<select name="tags" multiple defaultValue={filter.tagIds ?? []} className="border-muted-foreground/40 rounded border px-2 py-1">
{props.tagOptions.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.tagMatch")}</span>
<select name="tagMatch" defaultValue={filter.tagMatch} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="or">{t("crm.filter.tagMatchOr")}</option>
<option value="and">{t("crm.filter.tagMatchAnd")}</option>
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.sort")}</span>
<select name="sort" defaultValue={sort.field} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="createdAt">{t("crm.filter.sortCreated")}</option>
<option value="name">{t("crm.filter.sortName")}</option>
<option value="kontaktStatus">{t("crm.filter.sortStatus")}</option>
</select>
</label>
<label className="text-sm">
<span className="text-muted-foreground block text-xs">{t("crm.filter.direction")}</span>
<select name="dir" defaultValue={sort.dir} className="border-muted-foreground/40 rounded border px-2 py-1">
<option value="desc">{t("crm.filter.dirDesc")}</option>
<option value="asc">{t("crm.filter.dirAsc")}</option>
</select>
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="archived" value="1" defaultChecked={filter.includeArchived} /> {t("crm.filter.includeArchived")}
</label>
<label className="text-muted-foreground flex items-center gap-1 text-xs">
<input type="checkbox" name="demo" value="show" defaultChecked={filter.includeDemoData} /> {t("onboarding.demoData.showInLists")}
</label>
<button type="submit" className="text-theme-600 text-sm font-medium">
{t("crm.actions.applyFilter")}
</button>
</form>
{props.errorKey ? (
<p className="border-destructive text-destructive mt-4 rounded border px-3 py-2 text-sm" role="alert" data-ui-id="ui.crm.list.error">
{t(props.errorKey)}
</p>
) : null}
{!data ? (
<div className="mt-10 text-center" data-ui-id="ui.crm.list.empty">
<p className="text-foreground font-medium">{t(emptyHeadlineKey)}</p>
<p className="text-muted-foreground mt-1 text-sm">{t(emptyBodyKey)}</p>
<a href={props.newHref} className="text-theme-600 mt-2 inline-block text-sm font-medium">
{t("crm.actions.newContact")}
</a>
</div>
) : (
<form method="post" className="mt-6" data-ui-id="ui.crm.list.bulkForm">
<div className="overflow-x-auto">
<table className="w-full text-left text-sm" data-ui-id="ui.crm.list.table">
<thead>
<tr className="text-muted-foreground border-b">
<th className="py-2" />
<th className="py-2">{t("crm.column.name")}</th>
<th className="py-2">{t("crm.column.type")}</th>
<th className="py-2">{t("crm.column.status")}</th>
<th className="py-2">{t("crm.column.email")}</th>
<th className="py-2">{t("crm.column.telefon")}</th>
<th className="py-2">{t("crm.column.owner")}</th>
<th className="py-2">{t("crm.column.tags")}</th>
</tr>
</thead>
<tbody>
{data.rows.map((row) => (
<tr key={row.id} className="border-b" data-row-id={row.id}>
<td className="py-2">
<input type="checkbox" name="kontaktId" value={row.id} aria-label={t("crm.actions.select")} />
</td>
<td className="py-2">
<a href={row.detailHref} className="text-theme-600">
{row.displayName}
</a>
{row.isArchived ? <span className="text-muted-foreground ml-1 text-xs">{t("crm.detail.archivedBadge")}</span> : null}
</td>
<td className="py-2">{t(row.typLabelKey)}</td>
<td className="py-2">{t(row.statusLabelKey)}</td>
<td className="py-2">{row.primaerEmail ?? ""}</td>
<td className="py-2">{row.primaerTelefon ?? ""}</td>
<td className="py-2">{row.zustaendigerLabel ?? ""}</td>
<td className="py-2">
{row.tagChips.map((tag) => (
<span key={tag.id} className="mr-1 inline-flex items-center gap-1">
<span aria-hidden className="inline-block h-2 w-2 rounded-full" style={{ backgroundColor: tag.farbe }} />
{tag.name}
</span>
))}
</td>
</tr>
))}
</tbody>
</table>
</div>
{/* --- Bulk actions (operate on the checked rows) --- */}
<div className="mt-4 flex flex-wrap items-end gap-3" data-ui-id="ui.crm.list.bulk">
<button type="submit" name="intent" value="bulkArchive" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkArchive")}
</button>
<span className="flex items-end gap-1">
<select name="zustaendigerUserId" className="border-muted-foreground/40 rounded border px-2 py-1 text-sm" aria-label={t("crm.fields.owner")}>
{props.ownerOptions.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
<button type="submit" name="intent" value="bulkReassign" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkReassign")}
</button>
</span>
<span className="flex items-end gap-1">
<select name="tagId" className="border-muted-foreground/40 rounded border px-2 py-1 text-sm" aria-label={t("crm.fields.tag")}>
{props.tagOptions.map((tag) => (
<option key={tag.id} value={tag.id}>
{tag.name}
</option>
))}
</select>
<button type="submit" name="intent" value="bulkTag" className="text-theme-600 text-sm font-medium">
{t("crm.actions.bulkTag")}
</button>
</span>
</div>
<nav className="mt-4 flex items-center gap-4 text-sm" data-ui-id="ui.crm.list.pagination">
{data.pagination.hasPrev ? (
<a href={pageHref(props.baseHref, props.query, data.pagination.page - 1)} className="text-theme-600">
{t("crm.pagination.prev")}
</a>
) : null}
<span className="text-muted-foreground">
{t("crm.pagination.page", { page: data.pagination.page, pageCount: Math.max(data.pagination.pageCount, 1), total: data.pagination.total })}
</span>
{data.pagination.hasNext ? (
<a href={pageHref(props.baseHref, props.query, data.pagination.page + 1)} className="text-theme-600">
{t("crm.pagination.next")}
</a>
) : null}
</nav>
</form>
)}
</main>
);
}
@@ -14,5 +14,14 @@ describe("Lazy Monaco editor boundary", () => {
const clientSource = readRepoFile("apps/web/app/components/editors/MonacoEditor.client.tsx");
expect(clientSource).toContain('from "@monaco-editor/react"');
expect(clientSource).toContain('from "monaco-editor/esm/vs/editor/editor.api.js"');
expect(clientSource).not.toContain('from "monaco-editor"');
expect(clientSource).toContain("loader.config({ monaco })");
expect(clientSource).toContain("globalThis.MonacoEnvironment");
expect(clientSource.match(/monaco-editor\/.+\?worker/g)).toHaveLength(5);
expect(clientSource).toContain("globalThis.location.origin");
expect(clientSource).toContain("new Worker(sameOriginUrl");
expect(clientSource).not.toMatch(/https?:\/\//);
expect(clientSource).not.toContain("cdn.jsdelivr.net");
});
});
@@ -1,8 +1,57 @@
import { Editor, useMonaco } from "@monaco-editor/react";
import { Editor, loader, useMonaco } from "@monaco-editor/react";
import clsx from "clsx";
import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
import "monaco-editor/esm/vs/editor/editor.all.js";
import "monaco-editor/esm/vs/language/css/monaco.contribution.js";
import "monaco-editor/esm/vs/language/html/monaco.contribution.js";
import "monaco-editor/esm/vs/language/json/monaco.contribution.js";
import "monaco-editor/esm/vs/language/typescript/monaco.contribution.js";
import "monaco-editor/esm/vs/basic-languages/css/css.contribution.js";
import "monaco-editor/esm/vs/basic-languages/html/html.contribution.js";
import "monaco-editor/esm/vs/basic-languages/javascript/javascript.contribution.js";
import "monaco-editor/esm/vs/basic-languages/markdown/markdown.contribution.js";
import "monaco-editor/esm/vs/basic-languages/sql/sql.contribution.js";
import "monaco-editor/esm/vs/basic-languages/typescript/typescript.contribution.js";
import "monaco-editor/esm/vs/basic-languages/yaml/yaml.contribution.js";
import CssWorkerUrl from "monaco-editor/esm/vs/language/css/css.worker?worker&url";
import EditorWorkerUrl from "monaco-editor/esm/vs/editor/editor.worker?worker&url";
import HtmlWorkerUrl from "monaco-editor/esm/vs/language/html/html.worker?worker&url";
import JsonWorkerUrl from "monaco-editor/esm/vs/language/json/json.worker?worker&url";
import TypeScriptWorkerUrl from "monaco-editor/esm/vs/language/typescript/ts.worker?worker&url";
import { Fragment, useEffect } from "react";
import { useTranslation } from "react-i18next";
const MONACO_WORKER_URLS: Readonly<Record<string, string>> = {
css: CssWorkerUrl,
handlebars: HtmlWorkerUrl,
html: HtmlWorkerUrl,
javascript: TypeScriptWorkerUrl,
json: JsonWorkerUrl,
less: CssWorkerUrl,
razor: HtmlWorkerUrl,
scss: CssWorkerUrl,
typescript: TypeScriptWorkerUrl,
};
export function createMonacoWorker(label: string): Worker {
const emittedUrl = MONACO_WORKER_URLS[label] ?? EditorWorkerUrl;
const resolvedUrl = new URL(emittedUrl, globalThis.location.href);
// Worker constructors require same-origin URLs. Keep worker entry points on
// the application origin even when the regular Vite asset base points at a
// first-party CDN; the immutable assets remain available at the origin.
const sameOriginUrl = new URL(`${resolvedUrl.pathname}${resolvedUrl.search}${resolvedUrl.hash}`, globalThis.location.origin);
return new Worker(sameOriginUrl, { name: `monaco-${label || "editor"}` });
}
if (typeof window !== "undefined") {
globalThis.MonacoEnvironment = {
getWorker: (_moduleId: string, label: string) => createMonacoWorker(label),
};
// Passing the locally installed ESM runtime prevents @monaco-editor/react's
// default AMD loader from downloading executable code from jsDelivr.
loader.config({ monaco });
}
export type MonacoAutoCompletion = {
label: string;
kind: any;
@@ -1,6 +1,7 @@
import { useState } from "react";
import { useParams } from "react-router";
import { useFetcher, useParams } from "react-router";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useRootData } from "~/utils/data/useRootData";
import AddFeedbackButton from "./buttons/AddFeedbackButton";
import ChatSupportButton from "./buttons/ChatSupportButton";
import CurrentSubscriptionButton from "./buttons/CurrentSubscriptionButton";
@@ -36,16 +37,40 @@ export default function NavBar({
children?: React.ReactNode;
}) {
const appOrAdminData = useAppOrAdminData();
const rootData = useRootData();
const params = useParams();
const notificationsPath =
layout === "admin" ? adminPath("notifications", { mode: "host-aware" }) : params.tenant ? appPath({ tenantSlug: params.tenant, path: "notifications", mode: "host-aware" }) : "/notifications";
// AK-P3 (AD-28): tenant-app bell opens the notifications drawer with a live
// SSE unseen count; the stream route is tenant-scoped, so the admin layout
// keeps the plain link (documented Dev-Nachzug in the ticket doc).
const canReadPlatformLeads = appOrAdminData.permissions?.some(
(permission) => permission === "admin.leads.read_own" || permission === "admin.leads.read_all"
);
const isPlatformLeadAdmin = layout === "admin" && canReadPlatformLeads;
const notificationsPath = isPlatformLeadAdmin
? adminPath("leads", { mode: "host-aware" })
: layout === "admin"
? adminPath("notifications", { mode: "host-aware" })
: params.tenant
? appPath({ tenantSlug: params.tenant, path: "notifications", mode: "host-aware" })
: "/notifications";
const isTenantApp = layout === "app" && Boolean(params.tenant);
const streamPath = isTenantApp && params.tenant ? appPath({ tenantSlug: params.tenant, path: "notifications/stream", mode: "host-aware" }) : null;
const streamPath = isPlatformLeadAdmin
? adminPath("leads/notifications-stream", { mode: "host-aware" })
: isTenantApp && params.tenant
? appPath({ tenantSlug: params.tenant, path: "notifications/stream", mode: "host-aware" })
: null;
const notificationsStream = useNotificationsStream(streamPath, []);
const notificationReadFetcher = useFetcher();
const [notificationsDrawerOpen, setNotificationsDrawerOpen] = useState(false);
const hasNotificationDrawer = isTenantApp || isPlatformLeadAdmin;
function openNotificationsDrawer() {
setNotificationsDrawerOpen(true);
if (!isPlatformLeadAdmin || !streamPath) return;
const unreadIds = notificationsStream.items.filter((item) => !item.isRead).map((item) => item.id);
if (unreadIds.length === 0) return;
const form = new FormData();
if (rootData.csrf) form.set("csrf", rootData.csrf);
for (const deliveryId of unreadIds) form.append("deliveryId", deliveryId);
void notificationReadFetcher.submit(form, { method: "post", action: streamPath });
}
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>
@@ -53,7 +78,7 @@ export default function NavBar({
{/* {layout === "app" && (
<CreditsRemaining
feature={appOrAdminData.featureSyncs}
redirectTo={appOrAdminData.currentTenant ? `/${appOrAdminData.currentTenant.slug}/settings/subscription` : "/settings/subscription"}
redirectTo={appOrAdminData.currentTenant ? `/${appOrAdminData.currentTenant.slug}/settings/billing` : "/settings/billing"}
/>
)} */}
{buttons.onboarding && appOrAdminData?.onboardingSession && (
@@ -64,11 +89,11 @@ export default function NavBar({
{buttons.notifications && appOrAdminData?.user && (
<NotificationsButton
to={notificationsPath}
unseenCount={isTenantApp ? notificationsStream.unreadCount : undefined}
onOpen={isTenantApp ? () => setNotificationsDrawerOpen(true) : undefined}
unseenCount={hasNotificationDrawer ? notificationsStream.unreadCount : undefined}
onOpen={hasNotificationDrawer ? openNotificationsDrawer : undefined}
/>
)}
{isTenantApp && (
{hasNotificationDrawer && (
<NotificationsDrawer
open={notificationsDrawerOpen}
items={notificationsStream.items}
@@ -1,54 +1,76 @@
// AK-P21 (AD-28 interim polish) — global feedback widget. The mini form is a
// real ~/ui Dialog (size XS 420) with a category select (bug/feature/question,
// designer brief P21); the category is prefixed into the message because the
// support-ticket contract intentionally has no category column. Shared by the
// legacy NavBar trigger (mobile visibility restriction removed) and the shadcn
// nav-actions trigger. Submission keeps the established add-feedback intent on
// the tenant root route (rate limit 3/24h lives in Feedback.server).
//
// Instead of the originally sketched screenshot checkbox, the reporter attaches
// an image themselves (decision 2026-07-21): the client never captures the page
// on its own, so no third-party personal data leaves the workspace without the
// reporter consciously picking the file. The upload is fail-closed scanned and
// ClamAV-checked server-side.
import { useFetcher, useLocation, useParams } from "react-router";
import { Fragment, useEffect, useState } from "react";
import toast from "react-hot-toast";
import { toast } from "sonner";
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";
import { Button } from "~/ui/components/Button";
import { Dialog } from "~/ui/components/Dialog";
import { Select } from "~/ui/components/Select";
import { TextArea } from "~/ui/components/TextArea";
const FEEDBACK_CATEGORIES = ["bug", "feature", "question"] as const;
type FeedbackCategory = (typeof FEEDBACK_CATEGORIES)[number];
/** Mirrors the server-side contract in Feedback.server. */
const FEEDBACK_ATTACHMENT_ACCEPT = "image/png,image/jpeg,image/webp,image/gif";
const FEEDBACK_ATTACHMENT_MAX_MB = 5;
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 className="relative inline-flex">
<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="dialog"
aria-expanded={isOpen}
aria-label={t("feedback.title")}
>
<span className="sr-only">{t("feedback.title")}</span>
<StarsIconFilled className="h-5 w-5 p-0.5" />
</button>
</div>
<Modal open={isOpen} setOpen={setIsOpen} size="sm">
<FeedbackForm onClose={() => setIsOpen(false)} />
</Modal>
<FeedbackFormDialog open={isOpen} onClose={() => setIsOpen(false)} />
</Fragment>
);
}
function FeedbackForm({ onClose }: { onClose: () => void }) {
export function FeedbackFormDialog({ open, onClose }: { open: boolean; onClose: () => void }) {
const { t } = useTranslation();
const params = useParams();
const appOrAdminData = useAppOrAdminData();
const { csrf } = useRootData();
const fetcher = useFetcher<{ success?: string; error?: string }>();
const location = useLocation();
const [category, setCategory] = useState<FeedbackCategory>("bug");
const [attachmentError, setAttachmentError] = useState<string | null>(null);
useEffect(() => {
if (open) {
setCategory("bug");
setAttachmentError(null);
}
}, [open]);
useEffect(() => {
if (fetcher.data?.success) {
@@ -60,31 +82,109 @@ function FeedbackForm({ onClose }: { onClose: () => void }) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [fetcher.data]);
const onSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
const submitting = fetcher.state !== "idle";
const onSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
fetcher.submit(e.currentTarget, {
if (attachmentError) return;
void fetcher.submit(e.currentTarget, {
method: "post",
action: appPath({ tenantSlug: params.tenant ?? "", mode: "host-aware" }),
encType: "multipart/form-data",
action: params.tenant ? appPath({ tenantSlug: params.tenant, mode: "host-aware" }) : "",
});
// onClose();
};
// Reject oversized or non-image picks before the upload is attempted; the
// server enforces the same limits again.
const onAttachmentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.currentTarget.files?.[0] ?? null;
if (!file) {
setAttachmentError(null);
return;
}
if (file.size > FEEDBACK_ATTACHMENT_MAX_MB * 1024 * 1024) {
setAttachmentError(t("feedback.attachment.tooLarge", { megabytes: FEEDBACK_ATTACHMENT_MAX_MB }));
return;
}
if (!FEEDBACK_ATTACHMENT_ACCEPT.split(",").includes(file.type)) {
setAttachmentError(t("feedback.attachment.unsupportedType"));
return;
}
setAttachmentError(null);
};
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>
<Dialog open={open} onOpenChange={(nextOpen: boolean) => (nextOpen ? undefined : onClose())}>
<Dialog.Content className="w-[420px] max-w-[90vw] p-4" aria-label={t("feedback.title")} data-ui-id="ui.feedback.dialog">
<fetcher.Form onSubmit={onSubmit} method="post" className="flex w-full flex-col items-start">
<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 />
{/* Radix Select is not a native form control — mirror the picked category. */}
<input type="hidden" name="category" value={category} readOnly hidden />
<div className="flex w-full flex-col items-start gap-2">
<span className="text-heading-0 font-heading-0 text-text-neutral-primary">{t("feedback.title")}</span>
<span className="text-body-default-regular-150 font-body-default-regular-150 text-text-neutral-secondary">{t("feedback.description")}</span>
</div>
<div className="flex w-full flex-col items-start gap-4 pt-4">
<Select
className="w-full max-w-none"
showLabel
label={t("feedback.category.label")}
value={category}
onValueChange={(value: string) => setCategory(FEEDBACK_CATEGORIES.includes(value as FeedbackCategory) ? (value as FeedbackCategory) : "bug")}
data-ui-id="ui.feedback.category"
>
{FEEDBACK_CATEGORIES.map((key) => (
<Select.Item key={key} value={key}>
{t(`feedback.category.${key}`)}
</Select.Item>
))}
</Select>
<TextArea className="w-full max-w-none" label={t("feedback.message")} showLabel>
<TextArea.Input name="message" defaultValue="" rows={5} placeholder={t("feedback.placeholder")} required data-ui-id="ui.feedback.message" />
</TextArea>
<div className="flex w-full flex-col items-start gap-1">
<label
className="text-body-small-medium-0 font-body-small-medium-0 text-text-neutral-primary"
htmlFor="feedback-attachment"
>
{t("feedback.attachment.label")}
</label>
<input
id="feedback-attachment"
type="file"
name="attachment"
accept={FEEDBACK_ATTACHMENT_ACCEPT}
onChange={onAttachmentChange}
data-ui-id="ui.feedback.attachment"
className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary w-full"
/>
{attachmentError ? (
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-feedback-negative" role="alert">
{attachmentError}
</span>
) : (
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("feedback.attachment.hint", { megabytes: FEEDBACK_ATTACHMENT_MAX_MB })}
</span>
)}
</div>
<span className="text-body-extra-small-regular-150 font-body-extra-small-regular-150 text-text-neutral-tertiary">
{t("feedback.rateLimitHint")}
</span>
</div>
<div className="flex w-full items-center justify-end gap-2 pt-4">
<Button type="button" variant="tertiary" disabled={submitting} onClick={onClose}>
{t("shared.cancel")}
</Button>
<Button type="submit" loading={submitting} disabled={Boolean(attachmentError)} data-ui-id="ui.feedback.send">
{t("feedback.send")}
</Button>
</div>
</fetcher.Form>
</Dialog.Content>
</Dialog>
);
}
@@ -19,7 +19,7 @@ export default function ChatSupportButton() {
$crisp?.push(["do", "chat:hide"]);
setIsOpen(false);
}
} catch (e) {
} catch (_e) {
// ignore
}
}
@@ -22,7 +22,7 @@ export default function CurrentSubscriptionButton() {
<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 ? "" : appPath({ tenantSlug: params.tenant, path: "settings/subscription", mode: "host-aware" })}
to={!params.tenant ? "" : appPath({ tenantSlug: params.tenant, path: "settings/billing", 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",
hasSubscription() &&
@@ -75,7 +75,7 @@ describe("layout button UI IDs", () => {
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");
expect(screen.getByRole("menuitem", { name: "app.navbar.subscription" })).toHaveAttribute("href", "/acme/settings/billing");
});
it("localizes the public admin menu link", () => {
@@ -12,4 +12,11 @@ describe("ProfileButton route fallbacks", () => {
expect(source).toContain('defaultTenantPath("settings/profile") ?? publicHeaderAdminPath("settings/profile")');
expect(source).not.toContain('defaultTenantPath("settings/profile") ?? adminShellPath("settings/profile")');
});
it("gives the tenant menu item additional vertical padding", () => {
const source = fs.readFileSync(path.resolve(process.cwd(), "apps/web/app/components/layouts/buttons/ProfileButton.tsx"), "utf8");
expect(source).toContain('className="hover:bg-secondary block px-4 py-3 text-sm transition duration-150 ease-in-out"');
expect(source).toContain('data-ui-id="ui.profile.menu.tenant"');
});
});
@@ -48,7 +48,7 @@ export default function ProfileButton({ user, layout, items }: Props) {
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",
"bg-background text-muted-foreground hover:bg-secondary border-border focus-visible:ring-ring relative inline-flex items-center rounded-full border font-medium shadow-inner focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none",
!user?.avatar && "p-2",
user?.avatar && "p-1"
)}
@@ -58,7 +58,9 @@ export default function ProfileButton({ user, layout, items }: Props) {
>
{(() => {
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")} />;
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">
@@ -81,7 +83,7 @@ export default function ProfileButton({ user, layout, items }: Props) {
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="bg-background rounded-sm py-1 shadow-2xs" 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>
@@ -106,7 +108,7 @@ export default function ProfileButton({ user, layout, items }: Props) {
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")}
to={tenantPath("settings/team")}
>
{t("app.navbar.members")}
</Link>
@@ -117,7 +119,7 @@ export default function ProfileButton({ user, layout, items }: Props) {
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")}
to={tenantPath("settings/billing")}
>
{t("app.navbar.subscription")}
</Link>
@@ -125,10 +127,11 @@ export default function ProfileButton({ user, layout, items }: Props) {
{getUserHasPermission(appOrAdminData, "app.settings.account.view") && (
<Link
className="hover:bg-secondary block px-4 py-2 text-sm transition duration-150 ease-in-out"
className="hover:bg-secondary block px-4 py-3 text-sm transition duration-150 ease-in-out"
data-ui-id="ui.profile.menu.tenant"
role="menuitem"
onClick={closeDropdownUser}
to={tenantPath("settings/account")}
to={tenantPath("settings/workspace")}
>
{t("app.navbar.tenant")}
</Link>
@@ -139,7 +142,7 @@ export default function ProfileButton({ user, layout, items }: Props) {
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")}
to={tenantPath("settings/team/roles")}
>
{t("models.role.plural")}
</Link>
@@ -149,7 +152,7 @@ export default function ProfileButton({ user, layout, items }: Props) {
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")}
to={tenantPath("settings/team/groups")}
>
{t("models.group.plural")}
</Link> */}
@@ -159,7 +162,7 @@ export default function ProfileButton({ user, layout, items }: Props) {
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")}
to={tenantPath("api")}
>
{t("models.apiKey.plural")}
</Link>
@@ -170,7 +173,7 @@ export default function ProfileButton({ user, layout, items }: Props) {
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")}
to={tenantPath("settings/compliance")}
>
{t("models.log.plural")}
</Link>
@@ -209,12 +212,12 @@ export default function ProfileButton({ user, layout, items }: Props) {
{t("app.navbar.profile")}
</Link>
)}
{defaultTenantPath("settings/subscription") && (
{defaultTenantPath("settings/billing") && (
<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")!}
to={defaultTenantPath("settings/billing")!}
>
{t("app.navbar.subscription")}
</Link>
@@ -1,4 +1,5 @@
import { ReactNode } from "react";
import { cn } from "~/lib/utils";
import { sanitizeIconSvg } from "~/utils/html-sanitizer";
interface Props {
@@ -13,7 +14,7 @@ export default function SidebarIcon({ className, item }: Props) {
let icon = item.icon;
let title = item.title;
if (typeof icon !== "string") {
return icon;
return icon ? <span className={cn("inline-flex shrink-0 [&>*]:size-full", className)}>{icon}</span> : null;
}
return (
<>
@@ -0,0 +1,50 @@
import "@testing-library/jest-dom";
import { render } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { beforeEach, describe, expect, it, vi } from "vitest";
import NewTenantSelector from "./NewTenantSelector";
let capturedOptions: Array<Record<string, unknown>> = [];
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("~/components/ui/input/InputSelector", () => ({
default: ({ options }: { options: Array<Record<string, unknown>> }) => {
capturedOptions = options;
return <div data-testid="tenant-selector" />;
},
}));
vi.mock("~/utils/data/useAppData", () => ({
useAppData: () => ({
currentTenant: { id: "tenant_1", slug: "acme", name: "Acme" },
myTenants: [
{ id: "tenant_1", slug: "acme", name: "Acme", icon: null },
{ id: "tenant_2", slug: "beta", name: "Beta", icon: null },
],
}),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({ routing: {} }),
}));
describe("NewTenantSelector", () => {
beforeEach(() => {
capturedOptions = [];
});
it("does not expose placeholder copy as option metadata", () => {
render(
<MemoryRouter initialEntries={["/acme/dashboard"]}>
<NewTenantSelector />
</MemoryRouter>
);
const createOption = capturedOptions.find((option) => option.value === "{new}");
expect(createOption).toBeDefined();
expect(createOption).not.toHaveProperty("title");
});
});
@@ -6,15 +6,14 @@ 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();
export default function TenantSelector({ className: _className }: Props) {
const { t } = useTranslation();
const appData = useAppData();
const rootData = useRootData();
const location = useLocation();
@@ -39,12 +38,8 @@ export default function TenantSelector({ className }: Props) {
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,
group: t("models.tenant.plural"),
value: f.slug,
name: (
<div className="flex items-center space-x-2">
@@ -66,7 +61,6 @@ export default function TenantSelector({ className }: Props) {
return [
...unique,
{
title: "hey",
value: "{new}",
className: "border-t border-border rounded-none",
name: (
@@ -3,15 +3,14 @@ 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();
export default function TenantSelector({ className: _className }: Props) {
const { t } = useTranslation();
const appData = useAppData();
const location = useLocation();
const navigate = useNavigate();
@@ -35,12 +34,8 @@ export default function TenantSelector({ className }: Props) {
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,
group: t("models.tenant.plural"),
value: f.slug,
name: f.name,
img: f.icon ? (
@@ -25,18 +25,6 @@ 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`} />,
}));
@@ -8,10 +8,7 @@ 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"));
@@ -31,10 +28,7 @@ export default function ShadcnSidebarLayout({
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();
@@ -49,55 +43,14 @@ export default function ShadcnSidebarLayout({
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}>
<SidebarProvider 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} />
<ShadcnAppSidebar layout={layout} items={menuItems} />
<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"
@@ -21,7 +21,7 @@ vi.mock("~/utils/data/useRootData", () => ({
}));
let mockedPermissions = ["app.dashboard.view"];
let mockedCurrentTenant: null | { slug: string; logo: string } = null;
let mockedCurrentTenant: null | { slug: string; name: string; logo: string } = null;
vi.mock("~/utils/data/useAppOrAdminData", () => ({
useAppOrAdminData: () => ({
@@ -38,6 +38,10 @@ vi.mock("./nav-user", () => ({
NavUser: ({ layout }: { layout: string }) => <div data-testid="nav-user">User {layout}</div>,
}));
vi.mock("./team-switcher", () => ({
TeamSwitcher: () => <div data-testid="team-switcher" />,
}));
const baseItems = [
{
id: "ui.nav.test.main",
@@ -153,8 +157,44 @@ describe("ShadcnAppSidebar UI IDs", () => {
expect(screen.getByRole("link", { name: "Settings" })).toHaveAttribute("data-active", "true");
});
it("keeps consolidated workspace entries active on alternate area routes", () => {
const workspaceItems: SideBarItem[] = [
{
id: "ui.nav.test.main",
title: "Main",
path: "",
items: [
{
id: "ui.nav.test.communication",
title: "Communication",
path: "/acme/emails",
activePaths: ["/acme/emails", "/acme/email-marketing", "/acme/forms"],
contextItems: [
{ title: "Mailbox", path: "/acme/emails" },
{ title: "Campaigns", path: "/acme/email-marketing" },
{ title: "Forms", path: "/acme/forms" },
],
},
],
},
];
render(
<MemoryRouter initialEntries={["/acme/forms/form_1"]}>
<SidebarProvider>
<ShadcnAppSidebar layout="app" items={workspaceItems} />
</SidebarProvider>
</MemoryRouter>
);
expect(screen.getByRole("link", { name: "Communication" })).toHaveAttribute("data-active", "true");
expect(screen.queryByRole("link", { name: "Mailbox" })).not.toBeInTheDocument();
expect(screen.queryByRole("link", { name: "Campaigns" })).not.toBeInTheDocument();
expect(screen.queryByRole("link", { name: "Forms" })).not.toBeInTheDocument();
});
it("does not render tenant logo links inside the admin sidebar", () => {
mockedCurrentTenant = { slug: "acme", logo: "/tenant-logo.svg" };
mockedCurrentTenant = { slug: "acme", name: "Acme", logo: "/tenant-logo.svg" };
renderSidebar("admin", "/dashboard");
@@ -162,6 +202,15 @@ describe("ShadcnAppSidebar UI IDs", () => {
expect(screen.queryByRole("link", { name: "Logo" })).not.toBeInTheDocument();
});
it("uses the tenant name for the tenant logo link", () => {
mockedCurrentTenant = { slug: "acme", name: "Acme", logo: "/tenant-logo.svg" };
renderSidebar("app", "/acme/dashboard");
expect(screen.getByRole("link", { name: "Acme" })).toHaveAttribute("href", "/acme/dashboard");
expect(screen.getByAltText("Acme")).toHaveAttribute("src", "/tenant-logo.svg");
});
it("filters sidebar items by declared permission", () => {
const permissionItems: SideBarItem[] = [
{
@@ -207,7 +207,13 @@ export function ShadcnAppSidebar({
}
function isCurrent(menuItem: SideBarItem): boolean {
return pathMatchesCurrent(getPath(menuItem), menuItem.exact);
if (menuItem.excludePaths?.some((path) => pathMatchesCurrent(UrlUtils.replaceVariables(params, path) ?? path))) {
return false;
}
return (
pathMatchesCurrent(getPath(menuItem), menuItem.exact) ||
(menuItem.activePaths?.some((path) => pathMatchesCurrent(UrlUtils.replaceVariables(params, path) ?? path)) ?? false)
);
}
function currentIsChild(menuItem: SideBarItem): boolean {
@@ -240,7 +246,9 @@ export function ShadcnAppSidebar({
return !item.tenantUserTypes || (currentRole !== null && item.tenantUserTypes.includes(currentRole));
}
function checkUserRolePermissions(item: SideBarItem) {
return !item.permission || getUserHasPermission(appOrAdminData, item.permission);
const hasRequired = !item.permission || getUserHasPermission(appOrAdminData, item.permission);
const hasAny = !item.anyPermissions || item.anyPermissions.some((permission) => getUserHasPermission(appOrAdminData, permission));
return hasRequired && hasAny;
}
function getVisibleItem(item: SideBarItem): SideBarItem | null {
if (item.hidden === true || !allowCurrentUserType(item) || !allowCurrentTenantUserType(item)) {
@@ -248,16 +256,20 @@ export function ShadcnAppSidebar({
}
const items = item.items?.map((child) => getVisibleItem(child)).filter((child): child is SideBarItem => child !== null) ?? [];
const contextItems = item.contextItems?.map((child) => getVisibleItem(child)).filter((child): child is SideBarItem => child !== null) ?? [];
const hasPermission = checkUserRolePermissions(item);
if (!hasPermission && items.length === 0) {
if ((!hasPermission && items.length === 0 && contextItems.length === 0) || ((item.contextItems?.length ?? 0) > 0 && contextItems.length === 0)) {
return null;
}
const ownPathVisible = contextItems.some((child) => child.path === item.path);
return {
...item,
path: hasPermission ? item.path : "",
path: hasPermission && (contextItems.length === 0 || ownPathVisible) ? item.path : (contextItems[0]?.path ?? ""),
redirectTo: hasPermission ? item.redirectTo : undefined,
items,
contextItems,
};
}
const getMenu = (): SidebarGroupDto[] => {
@@ -316,7 +328,7 @@ export function ShadcnAppSidebar({
{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" />
<img className="mx-auto h-10 w-auto p-1.5" src={appData.currentTenant.logo} alt={appData.currentTenant.name} />
</div>
</a>
) : null}
@@ -122,7 +122,7 @@ describe("NavActions host-aware links", () => {
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(subscription).toHaveAttribute("href", "/acme/settings/billing");
expect(profile.getAttribute("href")).not.toContain("/app/");
expect(subscription.getAttribute("href")).not.toContain("/app/");
});
@@ -147,6 +147,10 @@ describe("NavActions host-aware links", () => {
expect(fetcherSubmit).toHaveBeenCalledWith(expect.any(HTMLFormElement), {
method: "post",
action: "/acme",
// AK-P21 — the widget carries an optional image attachment, which only
// reaches the action as multipart. Pinned here because a silent fall back
// to urlencoded would drop the file without any visible error.
encType: "multipart/form-data",
});
expect(fetcherSubmit.mock.calls[0][1].action).not.toContain("/app/");
});
@@ -10,15 +10,12 @@ 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 { Form, 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 OnboardingButton from "../../buttons/OnboardingButton";
import { toast } from "sonner";
import ButtonPrimary from "~/components/ui/buttons/ButtonPrimary";
import { Textarea } from "~/components/ui/textarea";
import { FeedbackFormDialog } from "../../buttons/AddFeedbackButton";
import { UI_ACTION_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
import NotificationsButton from "../../buttons/NotificationsButton";
@@ -155,7 +152,7 @@ export function NavActions({
{getUserHasPermission(appOrAdminData, "app.settings.subscription.view") && (
<SidebarMenuItem>
<a href={tenantPath("settings/subscription")}>
<a href={tenantPath("settings/billing")}>
<SidebarMenuButton data-ui-id={UI_ACTION_IDS.subscription}>
<CreditCard className="mr-2 h-4 w-4" />
{t("app.navbar.subscription")}
@@ -225,63 +222,10 @@ function AddFeedbackButton() {
<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>
{/* AK-P21: shared ~/ui Dialog (category select + rate-limit hint), see AddFeedbackButton.tsx. */}
<span data-ui-id={UI_SURFACE_IDS.feedbackDialog}>
<FeedbackFormDialog open={isOpen} onClose={() => setIsOpen(false)} />
</span>
</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>
);
}
@@ -2,6 +2,7 @@
import { type ReactNode } from "react";
import { Fragment } from "react/jsx-runtime";
import { Link } from "react-router";
import { SidebarGroupDto } from "~/application/sidebar/SidebarGroupDto";
import {
@@ -27,9 +28,21 @@ function hasConfiguredChildren(item: SidebarNavItem) {
return (item.items?.length ?? 0) > 0;
}
function isInternalNavigationPath(to: string) {
return to.startsWith("/") && !to.startsWith("//");
}
function SidebarLink({ to, children, ...props }: { to: string; children: ReactNode } & Record<string, unknown>) {
if (isInternalNavigationPath(to)) {
return (
<Link to={to} data-navigation-kind="client" {...props}>
{children}
</Link>
);
}
return (
<a href={to} {...props}>
<a href={to} data-navigation-kind="document" {...props}>
{children}
</a>
);
@@ -38,7 +51,7 @@ function SidebarLink({ to, children, ...props }: { to: string; children: ReactNo
function SidebarItemContent({ item }: { item: SidebarNavItem }) {
return (
<>
{item.icon !== undefined && <SidebarIcon className="size-4" item={item} />}
{item.icon !== undefined && <SidebarIcon className="size-5" item={item} />}
<span>{item.title}</span>
</>
);
@@ -16,7 +16,7 @@ import {
import { SidebarGroupDto } from "~/application/sidebar/SidebarGroupDto";
import SidebarIcon from "../../icons/SidebarIcon";
import { getUiIdAttributes } from "~/application/ui/uiRegistry";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
type SidebarNavItem = SidebarGroupDto["items"][number];
@@ -114,7 +114,7 @@ export function NavUser({
</DropdownMenuItem>
</a>
{getUserHasPermission(appOrAdminData, "app.settings.subscription.view") && (
<a href={UrlUtils.currentTenantUrl(params, `settings/subscription`)}>
<a href={UrlUtils.currentTenantUrl(params, `settings/billing`)}>
<DropdownMenuItem>
<CreditCard className="mr-2 h-4 w-4" />
{t("app.navbar.subscription")}
@@ -122,7 +122,7 @@ export function NavUser({
</a>
)}
{getUserHasPermission(appOrAdminData, "app.settings.account.view") && (
<a href={UrlUtils.currentTenantUrl(params, `settings/account`)}>
<a href={UrlUtils.currentTenantUrl(params, `settings/workspace`)}>
<DropdownMenuItem>
<BadgeCheck className="mr-2 h-4 w-4" />
{t("app.navbar.tenant")}
@@ -29,11 +29,6 @@ export function TeamSwitcher({ tenants, size = "md" }: { tenants: TenantSimple[]
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 (
@@ -63,7 +58,6 @@ export function TeamSwitcher({ tenants, size = "md" }: { tenants: TenantSimple[]
</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>
@@ -95,9 +89,6 @@ export function TeamSwitcher({ tenants, size = "md" }: { tenants: TenantSimple[]
</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">
@@ -142,29 +133,3 @@ function CreateAccountMenuItem({ label }: { label: string }) {
</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;
}
@@ -0,0 +1,85 @@
// Official brand marks of the AI clients HiveGrid connects to, inlined so the
// app never pulls a logo from a third-party CDN and the marks stay crisp at the
// 16px the topbar pill and the setup dialog render them at.
//
// Gradient ids are namespaced per mark (`hg-<client>-…`): two marks on the same
// page would otherwise share an id and one would silently take the other's
// colours.
export type AiClientMarkProps = { className?: string };
/** ChatGPT. */
export function ChatGptMark({ className }: AiClientMarkProps) {
return (
<svg viewBox="0 0 320 320" className={className} aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg">
<path d="m297.06 130.97c7.26-21.79 4.76-45.66-6.85-65.48-17.46-30.4-52.56-46.04-86.84-38.68-15.25-17.18-37.16-26.95-60.13-26.81-35.04-.08-66.13 22.48-76.91 55.82-22.51 4.61-41.94 18.7-53.31 38.67-17.59 30.32-13.58 68.54 9.92 94.54-7.26 21.79-4.76 45.66 6.85 65.48 17.46 30.4 52.56 46.04 86.84 38.68 15.24 17.18 37.16 26.95 60.13 26.8 35.06.09 66.16-22.49 76.94-55.86 22.51-4.61 41.94-18.7 53.31-38.67 17.57-30.32 13.55-68.51-9.94-94.51zm-120.28 168.11c-14.03.02-27.62-4.89-38.39-13.88.49-.26 1.34-.73 1.89-1.07l63.72-36.8c3.26-1.85 5.26-5.32 5.24-9.07v-89.83l26.93 15.55c.29.14.48.42.52.74v74.39c-.04 33.08-26.83 59.9-59.91 59.97zm-128.84-55.03c-7.03-12.14-9.56-26.37-7.15-40.18.47.28 1.3.79 1.89 1.13l63.72 36.8c3.23 1.89 7.23 1.89 10.47 0l77.79-44.92v31.1c.02.32-.13.63-.38.83l-64.41 37.19c-28.69 16.52-65.33 6.7-81.92-21.95zm-16.77-139.09c7-12.16 18.05-21.46 31.21-26.29 0 .55-.03 1.52-.03 2.2v73.61c-.02 3.74 1.98 7.21 5.23 9.06l77.79 44.91-26.93 15.55c-.27.18-.61.21-.91.08l-64.42-37.22c-28.63-16.58-38.45-53.21-21.95-81.89zm221.26 51.49-77.79-44.92 26.93-15.54c.27-.18.61-.21.91-.08l64.42 37.19c28.68 16.57 38.51 53.26 21.94 81.94-7.01 12.14-18.05 21.44-31.2 26.28v-75.81c.03-3.74-1.96-7.2-5.2-9.06zm26.8-40.34c-.47-.29-1.3-.79-1.89-1.13l-63.72-36.8c-3.23-1.89-7.23-1.89-10.47 0l-77.79 44.92v-31.1c-.02-.32.13-.63.38-.83l64.41-37.16c28.69-16.55 65.37-6.7 81.91 22 6.99 12.12 9.52 26.31 7.15 40.1zm-168.51 55.43-26.94-15.55c-.29-.14-.48-.42-.52-.74v-74.39c.02-33.12 26.89-59.96 60.01-59.94 14.01 0 27.57 4.92 38.34 13.88-.49.26-1.33.73-1.89 1.07l-63.72 36.8c-3.26 1.85-5.26 5.31-5.24 9.06l-.04 89.79zm14.63-31.54 34.65-20.01 34.65 20v40.01l-34.65 20-34.65-20z" fill="currentColor" />
</svg>
);
}
/** Claude. */
export function ClaudeMark({ className }: AiClientMarkProps) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg">
<path d="M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z" fill="#D97757" fillRule="nonzero" />
</svg>
);
}
/** Claude Code — the CLI mark, distinct from the Claude app mark above. */
export function ClaudeCodeMark({ className }: AiClientMarkProps) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg">
<path
clipRule="evenodd"
d="M20.998 10.949H24v3.102h-3v3.028h-1.487V20H18v-2.921h-1.487V20H15v-2.921H9V20H7.488v-2.921H6V20H4.487v-2.921H3V14.05H0V10.95h3V5h17.998v5.949zM6 10.949h1.488V8.102H6v2.847zm10.51 0H18V8.102h-1.49v2.847z"
fill="#D97757"
fillRule="evenodd"
/>
</svg>
);
}
/**
* OpenAI Codex. The glyph is inset in its 24-unit box because the upstream mark
* centres it on a plate; without that plate it reads 20% smaller than the other
* marks, so the viewBox is tightened by exactly that factor around the centre.
*/
export function CodexMark({ className }: AiClientMarkProps) {
return (
<svg viewBox="2 2 20 20" className={className} aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg">
{/* The upstream mark ships a white rounded-square plate behind the glyph.
Dropped: on the app surfaces this sits on, the plate reads as a stray
white tile rather than part of the logo. */}
<path
d="M9.064 3.344a4.578 4.578 0 012.285-.312c1 .115 1.891.54 2.673 1.275.01.01.024.017.037.021a.09.09 0 00.043 0 4.55 4.55 0 013.046.275l.047.022.116.057a4.581 4.581 0 012.188 2.399c.209.51.313 1.041.315 1.595a4.24 4.24 0 01-.134 1.223.123.123 0 00.03.115c.594.607.988 1.33 1.183 2.17.289 1.425-.007 2.71-.887 3.854l-.136.166a4.548 4.548 0 01-2.201 1.388.123.123 0 00-.081.076c-.191.551-.383 1.023-.74 1.494-.9 1.187-2.222 1.846-3.711 1.838-1.187-.006-2.239-.44-3.157-1.302a.107.107 0 00-.105-.024c-.388.125-.78.143-1.204.138a4.441 4.441 0 01-1.945-.466 4.544 4.544 0 01-1.61-1.335c-.152-.202-.303-.392-.414-.617a5.81 5.81 0 01-.37-.961 4.582 4.582 0 01-.014-2.298.124.124 0 00.006-.056.085.085 0 00-.027-.048 4.467 4.467 0 01-1.034-1.651 3.896 3.896 0 01-.251-1.192 5.189 5.189 0 01.141-1.6c.337-1.112.982-1.985 1.933-2.618.212-.141.413-.251.601-.33.215-.089.43-.164.646-.227a.098.098 0 00.065-.066 4.51 4.51 0 01.829-1.615 4.535 4.535 0 011.837-1.388zm3.482 10.565a.637.637 0 000 1.272h3.636a.637.637 0 100-1.272h-3.636zM8.462 9.23a.637.637 0 00-1.106.631l1.272 2.224-1.266 2.136a.636.636 0 101.095.649l1.454-2.455a.636.636 0 00.005-.64L8.462 9.23z"
fill="url(#hg-codex-0)"
/>
<defs>
<linearGradient gradientUnits="userSpaceOnUse" id="hg-codex-0" x1="12" x2="12" y1="3" y2="21">
<stop stopColor="#B1A7FF" />
<stop offset=".5" stopColor="#7A9DFF" />
<stop offset="1" stopColor="#3941FF" />
</linearGradient>
</defs>
</svg>
);
}
/** GitHub Copilot. */
export function CopilotMark({ className }: AiClientMarkProps) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg">
<path d="M17.533 1.829A2.528 2.528 0 0015.11 0h-.737a2.531 2.531 0 00-2.484 2.087l-1.263 6.937.314-1.08a2.528 2.528 0 012.424-1.833h4.284l1.797.706 1.731-.706h-.505a2.528 2.528 0 01-2.423-1.829l-.715-2.453z" fill="url(#hg-copilot-0)" transform="translate(0 1)" /><path d="M6.726 20.16A2.528 2.528 0 009.152 22h1.566c1.37 0 2.49-1.1 2.525-2.48l.17-6.69-.357 1.228a2.528 2.528 0 01-2.423 1.83h-4.32l-1.54-.842-1.667.843h.497c1.124 0 2.113.75 2.426 1.84l.697 2.432z" fill="url(#hg-copilot-1)" transform="translate(0 1)" /><path d="M15 0H6.252c-2.5 0-4 3.331-5 6.662-1.184 3.947-2.734 9.225 1.75 9.225H6.78c1.13 0 2.12-.753 2.43-1.847.657-2.317 1.809-6.359 2.713-9.436.46-1.563.842-2.906 1.43-3.742A1.97 1.97 0 0115 0" fill="url(#hg-copilot-2)" transform="translate(0 1)" /><path d="M15 0H6.252c-2.5 0-4 3.331-5 6.662-1.184 3.947-2.734 9.225 1.75 9.225H6.78c1.13 0 2.12-.753 2.43-1.847.657-2.317 1.809-6.359 2.713-9.436.46-1.563.842-2.906 1.43-3.742A1.97 1.97 0 0115 0" fill="url(#hg-copilot-3)" transform="translate(0 1)" /><path d="M9 22h8.749c2.5 0 4-3.332 5-6.663 1.184-3.948 2.734-9.227-1.75-9.227H17.22c-1.129 0-2.12.754-2.43 1.848a1149.2 1149.2 0 01-2.713 9.437c-.46 1.564-.842 2.907-1.43 3.743A1.97 1.97 0 019 22" fill="url(#hg-copilot-4)" transform="translate(0 1)" /><path d="M9 22h8.749c2.5 0 4-3.332 5-6.663 1.184-3.948 2.734-9.227-1.75-9.227H17.22c-1.129 0-2.12.754-2.43 1.848a1149.2 1149.2 0 01-2.713 9.437c-.46 1.564-.842 2.907-1.43 3.743A1.97 1.97 0 019 22" fill="url(#hg-copilot-5)" transform="translate(0 1)" /><defs><radialGradient cx="85.44%" cy="100.653%" fx="85.44%" fy="100.653%" gradientTransform="scale(-.8553 -1) rotate(50.927 2.041 -1.946)" id="hg-copilot-0" r="105.116%"><stop offset="9.6%" stopColor="#00AEFF" /><stop offset="77.3%" stopColor="#2253CE" /><stop offset="100%" stopColor="#0736C4" /></radialGradient><radialGradient cx="18.143%" cy="32.928%" fx="18.143%" fy="32.928%" gradientTransform="scale(.8897 1) rotate(52.069 .193 .352)" id="hg-copilot-1" r="95.612%"><stop offset="0%" stopColor="#FFB657" /><stop offset="63.4%" stopColor="#FF5F3D" /><stop offset="92.3%" stopColor="#C02B3C" /></radialGradient><radialGradient cx="82.987%" cy="-9.792%" fx="82.987%" fy="-9.792%" gradientTransform="scale(-1 -.9441) rotate(-70.872 .142 1.17)" id="hg-copilot-4" r="140.622%"><stop offset="6.6%" stopColor="#8C48FF" /><stop offset="50%" stopColor="#F2598A" /><stop offset="89.6%" stopColor="#FFB152" /></radialGradient><linearGradient id="hg-copilot-2" x1="39.465%" x2="46.884%" y1="12.117%" y2="103.774%"><stop offset="15.6%" stopColor="#0D91E1" /><stop offset="48.7%" stopColor="#52B471" /><stop offset="65.2%" stopColor="#98BD42" /><stop offset="93.7%" stopColor="#FFC800" /></linearGradient><linearGradient id="hg-copilot-3" x1="45.949%" x2="50%" y1="0%" y2="100%"><stop offset="0%" stopColor="#3DCBFF" /><stop offset="24.7%" stopColor="#0588F7" stopOpacity="0" /></linearGradient><linearGradient id="hg-copilot-5" x1="83.507%" x2="83.453%" y1="-6.106%" y2="21.131%"><stop offset="5.8%" stopColor="#F8ADFA" /><stop offset="70.8%" stopColor="#A86EDD" stopOpacity="0" /></linearGradient></defs>
</svg>
);
}
/** Gemini. */
export function GeminiMark({ className }: AiClientMarkProps) {
return (
<svg viewBox="0 0 24 24" className={className} aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg">
<path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="#3186FF" /><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#hg-gemini-0)" /><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#hg-gemini-1)" /><path d="M20.616 10.835a14.147 14.147 0 01-4.45-3.001 14.111 14.111 0 01-3.678-6.452.503.503 0 00-.975 0 14.134 14.134 0 01-3.679 6.452 14.155 14.155 0 01-4.45 3.001c-.65.28-1.318.505-2.002.678a.502.502 0 000 .975c.684.172 1.35.397 2.002.677a14.147 14.147 0 014.45 3.001 14.112 14.112 0 013.679 6.453.502.502 0 00.975 0c.172-.685.397-1.351.677-2.003a14.145 14.145 0 013.001-4.45 14.113 14.113 0 016.453-3.678.503.503 0 000-.975 13.245 13.245 0 01-2.003-.678z" fill="url(#hg-gemini-2)" /><defs><linearGradient gradientUnits="userSpaceOnUse" id="hg-gemini-0" x1="7" x2="11" y1="15.5" y2="12"><stop stopColor="#08B962" /><stop offset="1" stopColor="#08B962" stopOpacity="0" /></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="hg-gemini-1" x1="8" x2="11.5" y1="5.5" y2="11"><stop stopColor="#F94543" /><stop offset="1" stopColor="#F94543" stopOpacity="0" /></linearGradient><linearGradient gradientUnits="userSpaceOnUse" id="hg-gemini-2" x1="3.5" x2="17.5" y1="13.5" y2="12"><stop stopColor="#FABC12" /><stop offset=".46" stopColor="#FABC12" stopOpacity="0" /></linearGradient></defs>
</svg>
);
}
@@ -0,0 +1,31 @@
// Shared mark lookup for everything that names an AI client: the connect
// dialog's setup guides and connection rows, and the OAuth consent screen.
// The icon id itself is decided in the view-model (`resolveMcpClientIcon`), so
// this module only maps an id to a glyph.
import { FeatherCode, FeatherLink } from "@subframe/core";
import { ChatGptMark, ClaudeCodeMark, ClaudeMark, CodexMark, CopilotMark, GeminiMark } from "./AiClientMarks";
// Brand marks where a client has one, generic icons for the catch-all rows.
export const CLIENT_ICONS: Record<string, React.ReactNode> = {
claude: <ClaudeMark className="h-full w-full" />,
"claude-code": <ClaudeCodeMark className="h-full w-full" />,
chatgpt: <ChatGptMark className="text-icon-neutral-primary h-full w-full" />,
codex: <CodexMark className="h-full w-full" />,
copilot: <CopilotMark className="h-full w-full" />,
gemini: <GeminiMark className="h-full w-full" />,
code: <FeatherCode />,
link: <FeatherLink />,
};
/** Square, currentColor-tinted slot for one client's mark. */
export function ClientIcon({ icon, className = "h-4 w-4" }: { icon: string; className?: string }) {
return (
<span
className={`text-icon-neutral-secondary flex shrink-0 items-center justify-center [&>svg]:h-full [&>svg]:w-full ${className}`}
>
{CLIENT_ICONS[icon] ?? <FeatherLink />}
</span>
);
}
@@ -0,0 +1,81 @@
import { describe, expect, it, vi } from "vitest";
import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import { buildMcpConnectVM, type McpConnectVM } from "@hivegrid/view-models";
import { McpConnectDialog } from "./McpConnectDialog";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key, i18n: { language: "de" } }),
}));
function readyVM(tokens: Parameters<typeof buildMcpConnectVM>[0]["tokens"] = []): McpConnectVM {
return buildMcpConnectVM({
connectorUrl: "https://staging-mcp.hivegrid.de",
tenantName: "Acme",
appName: "HiveGrid",
tokens,
canRevoke: true,
nowIso: "2026-07-28T12:00:00.000Z",
});
}
describe("McpConnectDialog", () => {
it("shows the connector URL a client has to be pointed at", () => {
render(<McpConnectDialog open vm={readyVM()} onOpenChange={() => {}} onRevoke={() => {}} />);
expect(screen.getByText("https://staging-mcp.hivegrid.de")).toBeInTheDocument();
});
it("offers a setup guide per supported client", () => {
render(<McpConnectDialog open vm={readyVM()} onOpenChange={() => {}} onRevoke={() => {}} />);
for (const guide of ["claude-code", "claude-desktop", "chatgpt", "copilot", "codex", "gemini", "editors", "manual"]) {
expect(document.querySelector(`[data-ui-id="ui.mcp.connect.guide.${guide}"]`)).not.toBeNull();
}
});
it("explains the empty state instead of showing a bare list", () => {
render(<McpConnectDialog open vm={readyVM()} onOpenChange={() => {}} onRevoke={() => {}} />);
expect(screen.getByText("mcp.connect.connections.empty")).toBeInTheDocument();
});
it("hands the client id to the revoke callback", () => {
const onRevoke = vi.fn();
const vm = readyVM([
{
clientId: "client-1",
clientName: "Claude",
scopes: ["mcp:read"],
createdAtIso: "2026-07-20T08:00:00.000Z",
expiresAtIso: "2026-07-28T18:00:00.000Z",
revoked: false,
},
]);
render(<McpConnectDialog open vm={vm} onOpenChange={() => {}} onRevoke={onRevoke} />);
fireEvent.click(screen.getByText("mcp.connect.connections.revoke"));
expect(onRevoke).toHaveBeenCalledWith("client-1");
});
it("says what is happening while the data is still loading", () => {
render(<McpConnectDialog open vm={{ status: "loading" }} onOpenChange={() => {}} onRevoke={() => {}} />);
expect(screen.getByText("mcp.connect.loading")).toBeInTheDocument();
});
it("shows plain-text error copy instead of an endless spinner", () => {
render(
<McpConnectDialog
open
vm={{ status: "error", error: { messageKey: "mcp.connect.error" } }}
onOpenChange={() => {}}
onRevoke={() => {}}
/>
);
expect(screen.getByText("mcp.connect.error")).toBeInTheDocument();
});
});
@@ -0,0 +1,189 @@
// VD-MCP Interim-UI (AD-28) — "Mit KI verbinden" as a shell dialog, modelled on
// the Subframe "Connect to code" modal: one accordion per client, each step a
// copyable command or URL. Presentational only: the shell injects the VM and the
// revoke callback, so there is no useLoaderData/useFetcher in here (DoD A.5).
// Final Subframe optics land as a tracked design-nachzug.
import { useTranslation } from "react-i18next";
import { FeatherX } from "@subframe/core";
import type { McpClientGuideVM, McpConnectionVM, McpConnectVM } from "@hivegrid/view-models";
import { Accordion } from "~/ui/components/Accordion";
import { Button } from "~/ui/components/Button";
import { CopyToClipboardButton } from "~/ui/components/CopyToClipboardButton";
import { Dialog } from "~/ui/components/Dialog";
import { IconButton } from "~/ui/components/IconButton";
import { useLocaleFormatters } from "~/locale/format";
import { ClientIcon } from "./ClientIcon";
export type McpConnectDialogProps = {
open: boolean;
onOpenChange: (open: boolean) => void;
vm: McpConnectVM;
/** Cuts one client's tokens; the shell reloads the VM afterwards. */
onRevoke: (clientId: string) => void;
/** Client id currently being revoked, for the pending button state. */
revokingClientId?: string | null;
};
export function McpConnectDialog({ open, onOpenChange, vm, onRevoke, revokingClientId = null }: McpConnectDialogProps) {
const { t } = useTranslation();
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<Dialog.Content className="w-[620px] max-w-[94vw] p-0" data-ui-id="ui.mcp.connect.dialog">
<div className="flex w-full flex-col gap-6 p-6">
<div className="flex w-full items-start justify-between gap-4">
<div className="flex flex-col items-start gap-3">
<div className="flex flex-col gap-1">
<span className="text-heading- font-heading- text-text-neutral-primary">{t("mcp.connect.title")}</span>
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">
{vm.status === "ready"
? t("mcp.connect.subtitle", { tenantName: vm.data.tenantName, appName: vm.data.appName })
: t("mcp.connect.subtitleFallback")}
</span>
</div>
</div>
<IconButton variant="ghost" size="small" icon={<FeatherX />} aria-label={t("shared.close")} onClick={() => onOpenChange(false)} />
</div>
{vm.status === "loading" || vm.status === "idle" ? (
<p className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary" data-ui-id="ui.mcp.connect.loading">
{t("mcp.connect.loading")}
</p>
) : null}
{vm.status === "error" ? (
<p className="text-body-default-regular-0 font-body-default-regular-0 text-text-feedback-negative" data-ui-id="ui.mcp.connect.error">
{t(vm.error.messageKey, { defaultValue: t("mcp.connect.error") })}
</p>
) : null}
{vm.status === "ready" ? (
<>
<section className="flex w-full flex-col gap-2">
<span className="text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary">{t("mcp.connect.connectorHeading")}</span>
<CopyRow value={vm.data.connectorUrl} label={t("mcp.connect.connectorCopy")} uiId="ui.mcp.connect.connectorUrl" />
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t("mcp.connect.connectorHint")}</span>
</section>
<section className="flex w-full flex-col gap-2">
<span className="text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary">{t("mcp.connect.setupHeading")}</span>
{vm.data.guides.map((guide) => (
<GuideAccordion key={guide.id} guide={guide} />
))}
</section>
<section className="flex w-full flex-col gap-2">
<span className="text-body-default-semibold-0 font-body-default-semibold-0 text-text-neutral-primary">
{t("mcp.connect.connectionsHeading")}
</span>
{vm.data.connections.length === 0 ? (
<p
className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary"
data-ui-id="ui.mcp.connect.connections.empty"
>
{t("mcp.connect.connections.empty")}
</p>
) : (
<ul className="flex w-full list-none flex-col gap-2 p-0">
{vm.data.connections.map((connection) => (
<ConnectionRow
key={connection.id}
connection={connection}
canRevoke={vm.data.canRevoke}
pending={revokingClientId === connection.id}
onRevoke={onRevoke}
/>
))}
</ul>
)}
</section>
</>
) : null}
</div>
</Dialog.Content>
</Dialog>
);
}
function GuideAccordion({ guide }: { guide: McpClientGuideVM }) {
const { t } = useTranslation();
return (
<Accordion
data-ui-id={`ui.mcp.connect.guide.${guide.id}`}
trigger={
<div className="flex w-full items-center gap-2 px-3 py-2.5">
<ClientIcon icon={guide.icon} />
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary grow">{t(guide.labelKey)}</span>
<Accordion.Chevron />
</div>
}
>
<div className="flex w-full flex-col gap-3 px-3 pb-3">
{guide.steps.map((step) => (
<div key={step.id} className="flex w-full flex-col gap-1">
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary">{t(step.titleKey)}</span>
{step.hintKey ? (
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">{t(step.hintKey)}</span>
) : null}
{step.copyText ? <CopyRow value={step.copyText} label={t("mcp.connect.copy")} uiId={`ui.mcp.connect.guide.${guide.id}.${step.id}`} /> : null}
</div>
))}
</div>
</Accordion>
);
}
function CopyRow({ value, label, uiId }: { value: string; label: string; uiId: string }) {
return (
<div
className="border-border-default bg-surface-neutral-secondary flex w-full items-start gap-2 rounded-md border border-solid px-3 py-2"
data-ui-id={uiId}
>
<code className="text-body-small-regular-0 text-text-neutral-primary min-w-0 grow font-mono break-all whitespace-pre-wrap">{value}</code>
<CopyToClipboardButton clipboardText={value} tooltipText={label} aria-label={label} successKey="mcp.connect.toast.configurationCopied" />
</div>
);
}
function ConnectionRow({
connection,
canRevoke,
pending,
onRevoke,
}: {
connection: McpConnectionVM;
canRevoke: boolean;
pending: boolean;
onRevoke: (clientId: string) => void;
}) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<li
className="border-border-default flex w-full items-center gap-3 rounded-md border border-solid px-3 py-2"
data-ui-id={`ui.mcp.connect.connection.${connection.id}`}
>
{/* The client's own mark identifies the row; the live/expired state moved
into the meta line so the icon slot can carry the brand. */}
<ClientIcon icon={connection.icon} />
<div className="flex min-w-0 grow flex-col">
<span className="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-primary truncate">
{connection.clientName || t("mcp.connect.connections.unnamedClient")}
</span>
<span className="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">
<span className={connection.expired ? "text-text-neutral-tertiary" : "text-text-feedback-positive"}>
{t(connection.expired ? "mcp.connect.connections.statusExpired" : "mcp.connect.connections.statusActive")}
</span>{" "}
· {t(connection.accessKey)} · {t("mcp.connect.connections.connectedAt", { date: formatters.date(connection.connectedAtIso) })}
</span>
</div>
{canRevoke ? (
<Button variant="destructive" size="small" loading={pending} onClick={() => onRevoke(connection.id)}>
{t("mcp.connect.connections.revoke")}
</Button>
) : null}
</li>
);
}
@@ -0,0 +1,120 @@
// VD-MCP — topbar entry point for the MCP connector: the pill left of the
// global search plus the dialog it opens. Container half of the pair; it owns
// the fetchers and the `?connect=mcp` deep link, the dialog stays purely
// presentational.
import { useEffect, useState } from "react";
import { useFetcher, useSearchParams } from "react-router";
import { useTranslation } from "react-i18next";
import type { McpConnectVM } from "@hivegrid/view-models";
import { useRootData } from "~/utils/data/useRootData";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import { ChatGptMark, ClaudeCodeMark, ClaudeMark, CodexMark, CopilotMark, GeminiMark } from "./AiClientMarks";
import { McpConnectDialog } from "./McpConnectDialog";
// Every client the connect dialog has a guide for. At rest the first three sit
// in the pill; on hover the whole set rides past (see `.hg-mcp-*` in globals.css).
const PILL_MARKS = [
<ClaudeMark className="h-3.5 w-3.5" />,
<ChatGptMark className="text-icon-neutral-primary h-3.5 w-3.5" />,
<CopilotMark className="h-3.5 w-3.5" />,
<ClaudeCodeMark className="h-3.5 w-3.5" />,
<CodexMark className="h-3.5 w-3.5" />,
<GeminiMark className="h-3.5 w-3.5" />,
];
/** Query param that opens the dialog from a link (docs, onboarding mail). */
export const MCP_CONNECT_SEARCH_PARAM = "connect";
export const MCP_CONNECT_SEARCH_VALUE = "mcp";
type FetcherPayload = McpConnectVM | { error: string } | undefined;
function asVM(payload: FetcherPayload): McpConnectVM | null {
return payload && "status" in payload ? payload : null;
}
export function McpConnectLauncher({ tenantSlug }: { tenantSlug: string }) {
const { t } = useTranslation();
const rootData = useRootData();
const [searchParams, setSearchParams] = useSearchParams();
const loadFetcher = useFetcher<McpConnectVM>();
const revokeFetcher = useFetcher<FetcherPayload>();
const [open, setOpen] = useState(false);
const [revokingClientId, setRevokingClientId] = useState<string | null>(null);
const href = appPath({ tenantSlug, path: "mcp/connect", mode: "host-aware" });
const deepLinked = searchParams.get(MCP_CONNECT_SEARCH_PARAM) === MCP_CONNECT_SEARCH_VALUE;
useEffect(() => {
if (deepLinked) setOpen(true);
}, [deepLinked]);
// Load once per opening; the revoke action returns a fresh VM, so there is no
// second round-trip after cutting a connection.
useEffect(() => {
if (open && loadFetcher.state === "idle" && loadFetcher.data === undefined) {
loadFetcher.load(href);
}
}, [open, href, loadFetcher]);
useEffect(() => {
if (revokeFetcher.state === "idle") setRevokingClientId(null);
}, [revokeFetcher.state]);
function onOpenChange(next: boolean) {
setOpen(next);
if (!next && deepLinked) {
const params = new URLSearchParams(searchParams);
params.delete(MCP_CONNECT_SEARCH_PARAM);
setSearchParams(params, { replace: true, preventScrollReset: true });
}
}
function onRevoke(clientId: string) {
const form = new FormData();
form.set("intent", "revoke");
form.set("clientId", clientId);
if (rootData?.csrf) form.set("csrf", rootData.csrf);
setRevokingClientId(clientId);
revokeFetcher.submit(form, { method: "post", action: href, preventScrollReset: true });
}
const loaded = asVM(revokeFetcher.data) ?? asVM(loadFetcher.data);
// A payload that arrived but is not a VM means the route answered with an
// error envelope — show plain text instead of an endless spinner (DoD E.24).
const failed = loadFetcher.state === "idle" && loadFetcher.data !== undefined && asVM(loadFetcher.data) === null;
const vm: McpConnectVM = loaded ?? (failed ? { status: "error", error: { messageKey: "mcp.connect.error" } } : { status: "loading" });
return (
<>
{/*
Box instead of a bare icon: the client marks say what this connects to
faster than any label, and the label says what it is. Under md the label
drops and the marks carry the button on their own.
*/}
<button
type="button"
onClick={() => setOpen(true)}
// No `title`: the native tooltip would cover the hover animation with a
// grey box repeating the label that is already next to the marks.
aria-label={t("mcp.connect.open")}
className="hg-mcp-pill border-border-default bg-surface-neutral-primary hover:bg-surface-neutral-secondary focus-visible:shadow-focus text-text-neutral-secondary flex h-8 shrink-0 cursor-pointer items-center gap-2 rounded-md border border-solid pr-3 pl-2.5 outline-none"
data-ui-id="ui.mcp.connect.trigger"
>
<span className="hg-mcp-marks shrink-0" aria-hidden="true">
{/* Doubled so the conveyor loops seamlessly at -50%. */}
<span className="hg-mcp-marks-track">
{[...PILL_MARKS, ...PILL_MARKS].map((mark, index) => (
<span key={index} className="flex h-3.5 w-3.5 items-center justify-center">
{mark}
</span>
))}
</span>
</span>
<span className="text-body-small-medium-0 font-body-small-medium-0 hidden md:inline">{t("mcp.connect.open")}</span>
</button>
<McpConnectDialog open={open} onOpenChange={onOpenChange} vm={vm} onRevoke={onRevoke} revokingClientId={revokingClientId} />
</>
);
}
@@ -0,0 +1,52 @@
import { buildMcpConnectVM } from "@hivegrid/view-models";
import { McpConnectDialog } from "./McpConnectDialog";
/**
* Deterministic real-component fixture for the VD-MCP interim pixel baseline
* (AD-28). Every input is frozen — connector host, product name, token
* timestamps — so a diff means the UI moved, not the environment.
*/
const VM = buildMcpConnectVM({
connectorUrl: "https://mcp.hivegrid.example",
tenantName: "HiveGrid Demo",
appName: "HiveGrid",
canRevoke: true,
nowIso: "2026-07-28T12:00:00.000Z",
tokens: [
{
clientId: "client-claude",
clientName: "Claude",
scopes: ["mcp:read", "mcp:write"],
createdAtIso: "2026-07-20T08:00:00.000Z",
expiresAtIso: "2026-07-28T18:00:00.000Z",
revoked: false,
},
{
clientId: "client-cursor",
clientName: "Cursor",
scopes: ["mcp:read"],
// Deliberately in the past: pins the expired state next to the live one.
createdAtIso: "2026-07-02T08:00:00.000Z",
expiresAtIso: "2026-07-03T08:00:00.000Z",
revoked: false,
},
],
});
export function McpConnectVisualFixture() {
return <McpConnectDialog open vm={VM} onOpenChange={() => {}} onRevoke={() => {}} />;
}
/** Empty state is its own baseline — it is what every new tenant sees first. */
export function McpConnectEmptyVisualFixture() {
const vm = buildMcpConnectVM({
connectorUrl: "https://mcp.hivegrid.example",
tenantName: "HiveGrid Demo",
appName: "HiveGrid",
canRevoke: true,
nowIso: "2026-07-28T12:00:00.000Z",
tokens: [],
});
return <McpConnectDialog open vm={vm} onOpenChange={() => {}} onRevoke={() => {}} />;
}
@@ -0,0 +1,151 @@
// AK-P3 follow-up — macOS-style in-app notification toasts (top-right, below
// the shell header). Unread IN_APP deliveries pop up as dismissible toasts:
// X hides the toast (persisted per browser via localStorage, the delivery
// stays unread in the center), clicking the body marks it read and follows
// the deeplink. Data comes from the notifications route loader plus the
// shared SSE hook, so live arrivals toast too when the stream is available.
import { useEffect, useMemo, useState } from "react";
import { useFetcher, useNavigate } from "react-router";
import { useTranslation } from "react-i18next";
import { FeatherX } from "@subframe/core";
import type { NotificationCenterVM } from "@hivegrid/view-models";
import { Toast } from "~/ui/components/Toast";
import { BadgeFeedback } from "~/ui/components/BadgeFeedback";
import { useNotificationsStream, type NotificationsStreamState } from "~/components/notifications/useNotificationsStream";
import { useRootData } from "~/utils/data/useRootData";
import { useLocaleFormatters } from "~/locale/format";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
const MAX_VISIBLE_TOASTS = 3;
const MAX_STORED_DISMISSED_IDS = 200;
function storageKeyFor(tenantSlug: string): string {
return `hg.notification-toasts.dismissed.${tenantSlug}`;
}
function readDismissedIds(tenantSlug: string): string[] {
if (typeof window === "undefined") return [];
try {
const raw = window.localStorage.getItem(storageKeyFor(tenantSlug));
const parsed = raw ? JSON.parse(raw) : [];
return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === "string") : [];
} catch {
return [];
}
}
function persistDismissedIds(tenantSlug: string, ids: string[]): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(storageKeyFor(tenantSlug), JSON.stringify(ids.slice(-MAX_STORED_DISMISSED_IDS)));
} catch {
// Storage may be unavailable (private mode) — toasts then reappear on reload.
}
}
/**
* Shared shell notification state: loads the notification-center data once per
* tenant and keeps it live via the SSE hook. Drives both the bell badge
* (unreadCount) and the toast stack (items).
*/
export function useShellNotifications(tenantSlug: string | null): { items: NotificationsStreamState["items"]; unreadCount: number } {
const loadFetcher = useFetcher<{ vm: NotificationCenterVM; streamUrl: string }>({ key: "notification-toasts" });
useEffect(() => {
if (tenantSlug) loadFetcher.load(appPath({ tenantSlug, path: "notifications", mode: "host-aware" }));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tenantSlug]);
const initialItems = useMemo(
() => (loadFetcher.data?.vm.status === "ready" && loadFetcher.data.vm.data ? loadFetcher.data.vm.data.items : []),
[loadFetcher.data]
);
const stream = useNotificationsStream(tenantSlug && loadFetcher.data ? loadFetcher.data.streamUrl : null, initialItems);
return { items: stream.items, unreadCount: stream.unreadCount };
}
export function NotificationToasts({ tenantSlug, items }: { tenantSlug: string; items: NotificationsStreamState["items"] }) {
const { t } = useTranslation();
const navigate = useNavigate();
const rootData = useRootData();
const formatters = useLocaleFormatters();
const markFetcher = useFetcher({ key: "notification-toasts-mark" });
const [dismissedIds, setDismissedIds] = useState<string[]>(() => readDismissedIds(tenantSlug));
const notificationsPath = appPath({ tenantSlug, path: "notifications", mode: "host-aware" });
useEffect(() => {
setDismissedIds(readDismissedIds(tenantSlug));
}, [tenantSlug]);
const visibleToasts = items
.filter((item) => !item.isRead && !dismissedIds.includes(item.id))
.slice(0, MAX_VISIBLE_TOASTS);
function dismiss(id: string) {
const next = [...dismissedIds, id];
setDismissedIds(next);
persistDismissedIds(tenantSlug, next);
}
function open(item: (typeof visibleToasts)[number]) {
dismiss(item.id);
const form = new FormData();
form.set("action", "mark-read");
form.set("deliveryId", item.id);
if (rootData?.csrf) form.set("csrf", rootData.csrf);
markFetcher.submit(form, { method: "post", action: notificationsPath });
navigate(item.deeplinkHref ?? notificationsPath);
}
if (visibleToasts.length === 0) return null;
return (
<div
className="pointer-events-none fixed right-4 top-16 z-50 flex w-full max-w-[336px] flex-col items-end gap-2"
data-ui-id="ui.notifications.toasts"
>
{visibleToasts.map((item) => (
<div key={item.id} className="pointer-events-auto relative w-full" data-ui-id={`ui.notifications.toast.${item.id}`}>
<button
type="button"
className="absolute right-2.5 top-2.5 z-10 flex h-5 w-5 items-center justify-center rounded-md text-icon-neutral-primary hover:bg-surface-neutral-tertiary"
aria-label={t("notifications.toasts.dismiss")}
onClick={() => dismiss(item.id)}
data-ui-id={`ui.notifications.toast.${item.id}.dismiss`}
>
<FeatherX />
</button>
<button type="button" className="w-full text-left" onClick={() => open(item)} data-ui-id={`ui.notifications.toast.${item.id}.open`}>
<Toast
variant="neutral"
hideProgress
hideUndo
className="w-full min-w-0 gap-0 px-4 py-2.5 pr-9"
title={
<span className="flex min-w-0 flex-col gap-1">
<span className="line-clamp-1 min-w-0 break-all" title={item.subjectLabel ? `${t(item.messageKey)}: ${item.subjectLabel}` : String(t(item.messageKey))}>
{item.subjectLabel ? `${t(item.messageKey)}: ${item.subjectLabel}` : t(item.messageKey)}
</span>
<span className="flex min-w-0 items-center gap-2 text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-secondary">
{item.createdAtIso ? (
<span className="whitespace-nowrap">{formatters.date(item.createdAtIso, { dateStyle: "short", timeStyle: "short" })}</span>
) : null}
{item.tagKey && item.tagTone ? (
<BadgeFeedback farbe={item.tagTone} size="small">
{t(item.tagKey)}
</BadgeFeedback>
) : null}
</span>
</span>
}
/>
</button>
</div>
))}
</div>
);
}
export default NotificationToasts;
@@ -0,0 +1,65 @@
// The confirmation that drops in at the top of the screen after a save.
//
// Two rules it exists to enforce:
// 1. Success is never optimistic. The toast is driven by the server's answer
// (`ok: true`), not by the click, so "Gespeichert" cannot appear over a
// write that failed.
// 2. An error says what went wrong. The message comes from the action's
// i18n key, never from a raw provider string or an HTTP code (A.1).
//
// Pure/presentational: it renders the copy it is handed. Firing it is the
// `useSaveToast` hook's job.
import { FeatherAlertCircle, FeatherCheckCircle } from "@subframe/core";
export type SaveToastVariant = "success" | "error";
export type SaveToastProps = {
variant: SaveToastVariant;
/** Resolved headline, e.g. "Gespeichert". */
title: string;
/** Resolved detail. On an error this is what went wrong and what to do. */
description?: string | null;
};
const VARIANT = {
success: {
frame: "border-border-positive-subtle bg-surface-feedback-subtle-positive",
icon: "text-icon-feedback-positive",
title: "text-text-feedback-positive",
},
error: {
frame: "border-border-negative-subtle bg-surface-feedback-subtle-negative",
icon: "text-icon-feedback-negative",
title: "text-text-feedback-negative",
},
} as const;
export function SaveToast({ variant, title, description }: SaveToastProps) {
const tone = VARIANT[variant];
return (
<div
// `role="status"` for the success and `role="alert"` for the failure: a
// screen reader should interrupt for a save that did not happen, and not
// for one that did.
role={variant === "error" ? "alert" : "status"}
aria-live={variant === "error" ? "assertive" : "polite"}
className={`flex w-full max-w-[420px] items-start gap-3 rounded-md border border-solid px-4 py-3 shadow-lg ${tone.frame}`}
data-ui-id={`ui.saveToast.${variant}`}
>
{variant === "success" ? (
<FeatherCheckCircle className={`mt-0.5 text-body-large-0 font-body-large-0 ${tone.icon}`} aria-hidden />
) : (
<FeatherAlertCircle className={`mt-0.5 text-body-large-0 font-body-large-0 ${tone.icon}`} aria-hidden />
)}
<div className="flex min-w-0 grow flex-col gap-0.5">
<span className={`text-body-default-medium-0 font-body-default-medium-0 ${tone.title}`}>{title}</span>
{description ? (
<span className="break-words text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-secondary">{description}</span>
) : null}
</div>
</div>
);
}
export default SaveToast;
@@ -14,6 +14,12 @@ import {
const RECONNECT_DELAY_MS = 1_000;
const MAX_RECONNECT_DELAY_MS = 30_000;
/**
* A connection only counts as healthy once it survived this long. Resetting the
* backoff on every `open`/message meant a stream that dropped right after the
* snapshot reconnected once per second forever instead of backing off.
*/
const STABLE_CONNECTION_MS = 15_000;
type StreamPayload = {
cursor?: unknown;
@@ -46,6 +52,7 @@ function normalizeStreamItem(value: unknown): NotificationCenterItemVM | null {
sentAtIso: serializeDateField(record.sentAt),
readAtIso: serializeDateField(record.readAt),
lastError: typeof record.lastError === "string" ? record.lastError : null,
payloadMetadata: typeof record.payloadMetadata === "object" ? record.payloadMetadata : undefined,
deeplink: typeof record.deeplink === "string" ? record.deeplink : null,
});
}
@@ -97,10 +104,13 @@ export function useNotificationsStream(
const cursorRef = useRef<string | null>(null);
const reconnectTimerRef = useRef<number | null>(null);
const reconnectDelayRef = useRef(RECONNECT_DELAY_MS);
const connectedAtRef = useRef<number | null>(null);
useEffect(() => {
// Revalidated loader data merges over the live state (never truncates it).
setItems((currentItems) => mergeNotificationCenterItems(initialItems.slice(0, NOTIFICATION_CENTER_MAX_ITEMS), currentItems));
// merge(current, incoming): incoming wins per id — the fresh loader data
// must be the incoming side, otherwise stale live state shadows it.
setItems((currentItems) => mergeNotificationCenterItems(currentItems, initialItems.slice(0, NOTIFICATION_CENTER_MAX_ITEMS)));
}, [initialItems]);
useEffect(() => {
@@ -116,6 +126,7 @@ export function useNotificationsStream(
}
function connect() {
clearReconnectTimer();
connectedAtRef.current = null;
source = new EventSource(buildReconnectUrl(activeStreamUrl, cursorRef.current));
setConnectionStatusKey("notifications.center.realtime.connecting");
function handleMessage(event: MessageEvent) {
@@ -123,17 +134,24 @@ export function useNotificationsStream(
if (!parsed) return;
if (parsed.cursor && parsed.items.length > 0) cursorRef.current = parsed.cursor;
setItems((currentItems) => mergeNotificationCenterItems(currentItems, parsed.items));
reconnectDelayRef.current = RECONNECT_DELAY_MS;
setConnectionStatusKey("notifications.center.realtime.connected");
}
function handleOpen() {
reconnectDelayRef.current = RECONNECT_DELAY_MS;
connectedAtRef.current = Date.now();
setConnectionStatusKey("notifications.center.realtime.connected");
}
function handleError() {
if (closed) return;
source?.close();
setConnectionStatusKey("notifications.center.realtime.reconnecting");
// Only a connection that actually held counts as healthy. Otherwise a
// stream that dies right after opening keeps resetting the backoff and
// reconnects once per second forever.
const openedAt = connectedAtRef.current;
if (openedAt !== null && Date.now() - openedAt >= STABLE_CONNECTION_MS) {
reconnectDelayRef.current = RECONNECT_DELAY_MS;
}
connectedAtRef.current = null;
const reconnectDelay = reconnectDelayRef.current;
reconnectDelayRef.current = Math.min(reconnectDelay * 2, MAX_RECONNECT_DELAY_MS);
reconnectTimerRef.current = window.setTimeout(connect, reconnectDelay);
@@ -0,0 +1,34 @@
import { useEffect } from "react";
import { bootstrapTelephonyPush } from "~/lib/pwa/telephonyPush";
type TelephonyPushBootstrapProps = {
enabled: boolean;
tenantSlug: string;
vapidPublicKey?: string;
csrfToken?: string;
isDev?: boolean;
onError?: (error: unknown) => void;
};
/** Non-visual bootstrap for users who have already granted Web Push. */
export function TelephonyPushBootstrap({
enabled,
tenantSlug,
vapidPublicKey,
csrfToken,
isDev,
onError,
}: TelephonyPushBootstrapProps): null {
useEffect(() => {
let active = true;
void bootstrapTelephonyPush({ enabled, tenantSlug, vapidPublicKey, csrfToken, isDev }).catch((error: unknown) => {
if (active) onError?.(error);
});
return () => {
active = false;
};
}, [csrfToken, enabled, isDev, onError, tenantSlug, vapidPublicKey]);
return null;
}
@@ -0,0 +1,3 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`AK-P20 interim visual baseline > renders representative ready states for all five real ~/ui screens 1`] = `"<main data-ui-id="ui.akP20.interim.visualBaseline"><div class="flex w-full flex-col items-start bg-surface-neutral-primary" data-ui-id="ui.billing.subscriptionOverview.page"><div class="flex w-full items-start gap-4 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:flex-col mobile:px-4"><div class="flex grow shrink-0 basis-0 flex-col items-start gap-1"><div class="flex items-center gap-2"><span class="text-heading- font-heading- text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><h1 class="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">billing:subscriptionOverview.title</h1></div><p class="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">billing:subscriptionOverview.description</p></div><div class="flex items-center gap-2 mobile:w-full mobile:flex-none mobile:flex-wrap"><button class="group/3b777358 flex h-9 cursor-pointer items-center justify-center gap-3 rounded-md border-none px-4 py-2.5 text-left focus-within:shadow-focus disabled:cursor-default disabled:bg-surface-neutral-disabled disabled:pointer-events-none hover:disabled:cursor-default hover:disabled:bg-surface-neutral-disabled active:disabled:cursor-default active:disabled:bg-surface-neutral-disabled bg-brand-brand-secondary-surface-subtle-default hover:bg-brand-brand-secondary-surface-subtle-hover active:bg-brand-brand-secondary-surface-subtle-active" type="button" data-ui-id="ui.billing.subscriptionOverview.contact"><span class="text-body-default-regular-0 font-body-default-regular-0 group-disabled/3b777358:text-icon-neutral-disabled text-icon-neutral-primary icon-wrapper-module_root__-l6uP"><span class="icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></span><div class="hidden h-4 w-4 flex-none items-center justify-center gap-2"><div class="text-body-extra-small-regular-150 font-body-extra-small-regular-150 group-disabled/3b777358:text-icon-neutral-disabled group-hover/3b777358:group-disabled/3b777358:text-icon-neutral-on-solid group-active/3b777358:group-disabled/3b777358:text-icon-neutral-disabled text-icon-neutral-primary loader-module_root__-0Kak"></div></div><span class="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 group-disabled/3b777358:text-text-neutral-disabled text-text-neutral-primary">billing:subscriptionOverview.contact</span></button></div></div><div class="flex w-full flex-col gap-6 p-6 mobile:p-4 items-start"><div class="group/3a65613d flex w-full flex-col items-start gap-2 rounded-md px-4 py-5 relative border border-solid border-border-positive-subtle bg-surface-feedback-subtle-positive"><div class="flex w-full items-start gap-3"><span class="text-heading-0 font-heading-0 text-icon-feedback-information hidden icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="text-heading-0 font-heading-0 text-icon-feedback-positive inline-flex icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-feedback-warning icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-feedback-negative icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-neutral-secondary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><div class="flex grow shrink-0 basis-0 flex-col items-start gap-2"><span class="w-full whitespace-pre-wrap text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-positive">settings.subscription.banner.trial.title</span><span class="w-full whitespace-pre-wrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">settings.subscription.banner.trial.description:2</span></div></div><div class="hidden items-start justify-center absolute top-3 right-3"><span class="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-secondary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></div></div><div class="mobile:grid-cols-1 grid w-full grid-cols-4 gap-4"><div class="group/63f809c7 flex w-full cursor-pointer flex-col items-start gap-3 rounded-md border border-solid border-border-default bg-surface-neutral-primary px-4 py-4 hover:shadow-lg"><div class="flex w-full flex-col items-start gap-5"><div class="flex w-full items-center justify-between"><span class="text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">billing:subscriptionOverview.summary.plan</span><span class="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><span classLine truncated
@@ -0,0 +1,3 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
exports[`AK-P21 interim visual baseline > renders representative ready states for all five privacy ~/ui screens 1`] = `"<main data-ui-id="ui.akP21.interim.visualBaseline"><div class="flex w-full flex-col items-start bg-surface-neutral-primary" data-ui-id="ui.settings.privacy.page"><div class="flex w-full items-start gap-4 border-b border-solid border-border-default bg-surface-neutral-secondary px-6 py-5 mobile:flex-col mobile:px-4"><div class="flex grow shrink-0 basis-0 flex-col items-start gap-1"><div class="flex items-center gap-2"><span class="text-heading- font-heading- text-icon-neutral-tertiary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><h1 class="text-subtitle font-subtitle text-text-neutral-primary mobile:text-heading- mobile:font-heading-">settings.privacy.title</h1></div><p class="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">settings.privacy.description</p></div></div><div class="flex w-full flex-col gap-6 p-6 mobile:p-4 items-start"><div class="group/3a65613d flex w-full flex-col items-start gap-2 rounded-md px-4 py-5 relative border border-solid border-border-warning-subtle bg-surface-feedback-subtle-warning"><div class="flex w-full items-start gap-3"><span class="text-heading-0 font-heading-0 text-icon-feedback-information hidden icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-feedback-positive icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="text-heading-0 font-heading-0 text-icon-feedback-warning inline-flex icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-feedback-negative icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><span class="hidden text-heading-0 font-heading-0 text-icon-neutral-secondary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span><div class="flex grow shrink-0 basis-0 flex-col items-start gap-2"><span class="w-full whitespace-pre-wrap text-body-default-medium-0 font-body-default-medium-0 text-text-feedback-warning">settings.privacy.hub.tenantDeletionBanner.title:20</span><span class="w-full whitespace-pre-wrap text-body-default-regular-0 font-body-default-regular-0 text-text-neutral-secondary">settings.privacy.hub.tenantDeletionBanner.description:2026-08-01T12:00:00.000Z</span></div></div><div class="hidden items-start justify-center absolute top-3 right-3"><span class="text-body-default-regular-0 font-body-default-regular-0 text-icon-neutral-secondary icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></div></div><div class="group/56067c50 flex w-full flex-col items-start gap-4 rounded-md border border-solid border-border-default bg-surface-neutral-secondary px-4 py-4 shadow-sm" data-ui-id="ui.settings.privacy.selfExport"><div class="flex w-full flex-col items-start gap-4"><div class="flex w-full flex-col items-start"><span class="text-body-large font-body-large text-text-neutral-primary">settings.privacy.export.title</span><span class="text-body-small-regular-150 font-body-small-regular-150 text-text-neutral-tertiary">settings.privacy.export.description</span></div><form method="post" data-ui-id="ui.settings.privacy.export.form" class="flex w-full flex-col items-start gap-2"><input type="hidden" value="export" name="intent"><input type="hidden" value="test-csrf" name="csrf"><button class="group/3b777358 flex h-9 cursor-pointer items-center justify-center gap-3 rounded-md border-none px-4 py-2.5 text-left focus-within:shadow-focus disabled:cursor-default disabled:bg-surface-neutral-disabled disabled:pointer-events-none hover:disabled:cursor-default hover:disabled:bg-surface-neutral-disabled active:disabled:cursor-default active:disabled:bg-surface-neutral-disabled bg-brand-brand-secondary-surface-subtle-default hover:bg-brand-brand-secondary-surface-subtle-hover active:bg-brand-brand-secondary-surface-subtle-active" type="submit"><span class="text-body-default-regular-0 font-body-default-regular-0 group-disabled/3b777358:text-icon-neutral-disabled text-icon-neutral-primary icon-wrapper-module_root__-l6uP"><span class="icon-wrapper-module_root__-l6uP"><svg data-visual-icon="true"></svg></span></span><div class="hidden h-4 w-4 flex-none items-center justify-center gap-2"><div class="text-body-extra-small-regular-150 font-body-extra-small-regular-150 group-disabled/3b777358:text-icon-neutral-disabled group-hover/3b777358:group-disabled/3b777358:text-icon-neutral-on-solid group-active/3b777358:group-disabled/3b777358:text-icon-neutral-disabled text-icon-neutral-primary loader-module_root__-0Kak"></div></div><span class="whitespace-nowrap text-body-default-regular-0 font-body-default-regular-0 group-disabled/3b777358:text-text-neutral-disabled text-text-neutral-primary">settings.privacy.export.submit</span></button><span classLine truncated
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff. Show more