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 ButtonSecondary from "./buttons/ButtonSecondary";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import SlideOver from "./slideOvers/SlideOver";
import { useState } from "react";
import clsx from "clsx";
@@ -7,7 +7,7 @@ interface Props {
className?: string;
}
export default function ColorBadgeString({ color, size = "md", children, className }: Props) {
export default function ColorBadgeString({ color, size: _size = "md", children, className }: Props) {
function getColors() {
switch (color) {
case "primary":
@@ -1,4 +1,3 @@
import clsx from "clsx";
import { Colors } from "~/application/enums/shared/Colors";
import { cn } from "~/lib/utils";
import { getBadgeColor, getBadgeColorDark } from "~/utils/shared/ColorUtils";
@@ -12,7 +11,7 @@ interface Props {
darkMode?: boolean;
}
export default function SimpleBadge({ title, color, className, children, underline, darkMode }: Props) {
export default function SimpleBadge({ title, color, className, children, underline, darkMode: _darkMode }: Props) {
return (
<div
className={cn(
@@ -1,5 +1,5 @@
import InfoBanner from "./InfoBanner";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import WarningBanner from "./WarningBanner";
export default function PreviewBanners() {
@@ -2,7 +2,7 @@ import * as React from "react";
import { Slot } from "@radix-ui/react-slot";
import { cn } from "~/lib/utils";
import { ChevronRightIcon, DotsHorizontalIcon } from "~/components/ui/icons/vendor";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
return <nav aria-label={i18nT("components.breadcrumb.ariaLabel")} data-slot="breadcrumb" {...props} />;
@@ -1,5 +1,5 @@
import { useLocation } from "react-router";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import Breadcrumb from "./Breadcrumb";
import BreadcrumbSimple from "./BreadcrumbSimple";
@@ -1,9 +1,5 @@
import { useRef, useState } from "react";
import { useRef } from "react";
import { Button } from "./button";
import ModalOrSlide from "./modals/ModalOrSlide";
import { Label } from "./label";
import { Input } from "./input";
import { Form } from "react-router";
import ConfirmDialog, { RefConfirmDialog } from "./modals/ConfirmDialog";
import { useTranslation } from "react-i18next";
@@ -1,6 +1,6 @@
import { Button } from "../button";
import { cn } from "~/lib/utils";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
export default function BackButtonWithTitle({
href,
@@ -23,7 +23,7 @@ interface Props {
sendEvent?: boolean;
disabled?: boolean;
}
export default function ButtonSubmitForm({ submits, type, to, target, children, className, role, rel, event, onClick, sendEvent = true, disabled }: Props) {
export default function ButtonSubmitForm({ submits, type, to, target, children, className, role, rel, event, onClick: _onClick, sendEvent: _sendEvent = true, disabled }: Props) {
const submit = useSubmit();
const navigation = useNavigation();
const [searchParams] = useSearchParams();
@@ -1,5 +1,5 @@
import ButtonPrimary from "./ButtonPrimary";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import ButtonSecondary from "./ButtonSecondary";
import ButtonTertiary from "./ButtonTertiary";
import LoadingButton, { RefLoadingButton } from "./LoadingButton";
@@ -1,5 +1,5 @@
import { useLocation } from "react-router";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import ButtonPrimary from "./ButtonPrimary";
import ButtonSecondary from "./ButtonSecondary";
import ButtonTertiary from "./ButtonTertiary";
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import ButtonPrimary from "./ButtonPrimary";
import ButtonSecondary from "./ButtonSecondary";
import ButtonTertiary from "./ButtonTertiary";
@@ -7,6 +7,7 @@ import { cn } from "~/lib/utils";
import { Button, buttonVariants } from "~/components/ui/button";
import { getDateFnsLocale } from "~/locale/date-fns";
import { Calendar as SubframeCalendar } from "~/ui/components/Calendar";
import { APP_TIME_ZONE } from "~/locale/format";
// Subframe migration (strangler shim):
// This file keeps the original shadcn `Calendar` API but renders the Subframe design-system
@@ -43,7 +44,7 @@ function Calendar({
const { i18n } = useTranslation();
const language = i18n.language || undefined;
const dateFnsLocale = localeProp ?? getDateFnsLocale(language);
const monthDropdownFormatter = React.useMemo(() => new Intl.DateTimeFormat(language, { month: "short" }), [language]);
const monthDropdownFormatter = React.useMemo(() => new Intl.DateTimeFormat(language, { timeZone: APP_TIME_ZONE, month: "short" }), [language]);
return (
<SubframeCalendar
@@ -0,0 +1,18 @@
import { readFileSync } from "node:fs";
import path from "node:path";
import { describe, expect, it } from "vitest";
describe("carousel accessibility copy", () => {
it("uses translation keys for ARIA role descriptions", () => {
const source = readFileSync(
path.resolve(process.cwd(), "apps/web/app/components/ui/carousel.tsx"),
"utf8",
);
expect(source).toContain('aria-roledescription={t("shared.carousel")}');
expect(source).toContain('aria-roledescription={t("shared.slide")}');
expect(source).not.toContain('aria-roledescription="carousel"');
expect(source).not.toContain('aria-roledescription="slide"');
});
});
@@ -51,6 +51,7 @@ function Carousel({
children,
...props
}: React.ComponentProps<"div"> & CarouselProps) {
const { t } = useTranslation()
const [carouselRef, api] = useEmblaCarousel(
{
...opts,
@@ -122,7 +123,7 @@ function Carousel({
onKeyDownCapture={handleKeyDown}
className={cn("relative", className)}
role="region"
aria-roledescription="carousel"
aria-roledescription={t("shared.carousel")}
data-slot="carousel"
{...props}
>
@@ -155,11 +156,12 @@ function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
const { orientation } = useCarousel()
const { t } = useTranslation()
return (
<div
role="group"
aria-roledescription="slide"
aria-roledescription={t("shared.slide")}
data-slot="carousel-item"
className={cn(
"min-w-0 shrink-0 grow-0 basis-full",
@@ -1,273 +0,0 @@
import * as React from "react";
import * as RechartsPrimitive from "recharts";
import { cn } from "~/lib/utils";
import { useLocaleFormatters } from "~/locale/format";
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: "", dark: ".dark" } as const;
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode;
icon?: React.ComponentType;
} & ({ color?: string; theme?: never } | { color?: never; theme: Record<keyof typeof THEMES, string> });
};
type ChartContextProps = {
config: ChartConfig;
};
const ChartContext = React.createContext<ChartContextProps | null>(null);
function useChart() {
const context = React.useContext(ChartContext);
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />");
}
return context;
}
function ChartContainer({
id,
className,
children,
config,
...props
}: React.ComponentProps<"div"> & {
config: ChartConfig;
children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>["children"];
}) {
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`;
return (
<ChartContext.Provider value={{ config }}>
<div
data-slot="chart"
data-chart={chartId}
className={cn(
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>{children}</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
);
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(([, config]) => config.theme || config.color);
if (!colorConfig.length) {
return null;
}
return (
<style
dangerouslySetInnerHTML={{
__html: Object.entries(THEMES)
.map(
([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.color;
return color ? ` --color-${key}: ${color};` : null;
})
.join("\n")}
}
`
)
.join("\n"),
}}
/>
);
};
const ChartTooltip = RechartsPrimitive.Tooltip;
function ChartTooltipContent({
active,
payload,
className,
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
labelFormatter,
labelClassName,
formatter,
color,
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<"div"> & {
hideLabel?: boolean;
hideIndicator?: boolean;
indicator?: "line" | "dot" | "dashed";
nameKey?: string;
labelKey?: string;
}) {
const { config } = useChart();
const fmt = useLocaleFormatters();
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null;
}
const [item] = payload;
const key = `${labelKey || item?.dataKey || item?.name || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value = !labelKey && typeof label === "string" ? config[label as keyof typeof config]?.label || label : itemConfig?.label;
if (labelFormatter) {
return <div className={cn("font-medium", labelClassName)}>{labelFormatter(value, payload)}</div>;
}
if (!value) {
return null;
}
return <div className={cn("font-medium", labelClassName)}>{value}</div>;
}, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey]);
if (!active || !payload?.length) {
return null;
}
const nestLabel = payload.length === 1 && indicator !== "dot";
return (
<div className={cn("border-border-default/50 bg-surface-neutral-primary grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl", className)}>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color || item.payload.fill || item.color;
return (
<div
key={item.dataKey}
className={cn(
"[&>svg]:text-text-neutral-tertiary flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
formatter(item.value, item.name, item, index, item.payload)
) : (
<>
{itemConfig?.icon ? (
<itemConfig.icon />
) : (
!hideIndicator && (
<div
className={cn("shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)", {
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent": indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
})}
style={
{
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
)
)}
<div className={cn("flex flex-1 justify-between leading-none", nestLabel ? "items-end" : "items-center")}>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-text-neutral-tertiary">{itemConfig?.label || item.name}</span>
</div>
{item.value !== undefined && item.value !== null && (
<span className="text-text-neutral-primary font-mono font-medium tabular-nums">
{typeof item.value === "number" ? fmt.number(item.value) : String(item.value)}
</span>
)}
</div>
</>
)}
</div>
);
})}
</div>
</div>
);
}
const ChartLegend = RechartsPrimitive.Legend;
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<"div"> &
Pick<RechartsPrimitive.LegendProps, "payload" | "verticalAlign"> & {
hideIcon?: boolean;
nameKey?: string;
}) {
const { config } = useChart();
if (!payload?.length) {
return null;
}
return (
<div className={cn("flex items-center justify-center gap-4", verticalAlign === "top" ? "pb-3" : "pt-3", className)}>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || "value"}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
return (
<div key={item.value} className={cn("[&>svg]:text-text-neutral-tertiary flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3")}>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
style={{
backgroundColor: item.color,
}}
/>
)}
{itemConfig?.label}
</div>
);
})}
</div>
);
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
if (typeof payload !== "object" || payload === null) {
return undefined;
}
const payloadPayload = "payload" in payload && typeof payload.payload === "object" && payload.payload !== null ? payload.payload : undefined;
let configLabelKey: string = key;
if (key in payload && typeof payload[key as keyof typeof payload] === "string") {
configLabelKey = payload[key as keyof typeof payload] as string;
} else if (payloadPayload && key in payloadPayload && typeof payloadPayload[key as keyof typeof payloadPayload] === "string") {
configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string;
}
return configLabelKey in config ? config[configLabelKey] : config[key as keyof typeof config];
}
export { ChartContainer, ChartTooltip, ChartTooltipContent, ChartLegend, ChartLegendContent, ChartStyle };
@@ -1,19 +0,0 @@
import hljs from "highlight.js";
export default function CodeBlock({ code, language = "ts" }: { code: string; language?: "js" | "ts" | "shell" }) {
return (
<div className="prose">
<pre data-syntax={language}>
<code
className={`hljs language-${language}`}
dangerouslySetInnerHTML={{
__html: hljs.highlight(String(code), {
language,
ignoreIllegals: true,
}).value,
}}
/>
</pre>
</div>
);
}
@@ -13,7 +13,7 @@ interface ColorPickerProps {
}
const ColorPicker = forwardRef<HTMLInputElement, Omit<React.ComponentProps<"button">, "value" | "onChange" | "onBlur"> & ColorPickerProps>(
({ disabled, value, onChange, onBlur, name, className, ...props }, forwardedRef) => {
({ disabled, value, onChange, onBlur, name, className, ...props }, _forwardedRef) => {
const [open, setOpen] = useState(false);
const parsedValue = useMemo(() => {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
("use client");
import * as React from "react";
@@ -24,12 +24,16 @@ function CommandDialog({
children,
dataUiId,
onCloseAutoFocus,
shouldFilter,
onCommandKeyDownCapture,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string;
description?: string;
dataUiId?: string;
onCloseAutoFocus?: (event: Event) => void;
shouldFilter?: boolean;
onCommandKeyDownCapture?: React.KeyboardEventHandler<HTMLDivElement>;
}) {
return (
<Dialog {...props}>
@@ -37,8 +41,19 @@ function CommandDialog({
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent data-ui-id={dataUiId} onCloseAutoFocus={onCloseAutoFocus} className="overflow-hidden p-0">
<Command className="[&_[cmdk-group-heading]]:text-text-neutral-tertiary **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
<DialogContent
data-ui-id={dataUiId}
onCloseAutoFocus={onCloseAutoFocus}
overlayClassName="bg-black/35 backdrop-blur-[2px]"
closeButtonClassName="sm:hidden"
positioning="custom"
className="bg-surface-neutral-primary top-0 right-0 bottom-0 left-0 h-dvh max-h-none w-screen max-w-none min-w-0 overflow-hidden rounded-none border-0 p-0 shadow-2xl sm:top-[16vh] sm:right-auto sm:bottom-auto sm:left-1/2 sm:h-auto sm:max-h-[68vh] sm:w-[min(44rem,calc(100%-2rem))] sm:-translate-x-1/2 sm:translate-y-0 sm:rounded-lg sm:border"
>
<Command
shouldFilter={shouldFilter}
onKeyDownCapture={onCommandKeyDownCapture}
className="[&_[cmdk-group-heading]]:text-text-neutral-tertiary rounded-none sm:rounded-lg [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-2 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"
>
{children}
</Command>
</DialogContent>
@@ -46,16 +61,20 @@ function CommandDialog({
);
}
function CommandInput({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Input>) {
function CommandInput({ className, style, ...props }: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div data-slot="command-input-wrapper" className="flex h-9 items-center gap-2 border-b border-border-default px-3">
<SearchIcon className="size-4 shrink-0 opacity-50" />
<div
data-slot="command-input-wrapper"
className="group/command-search border-border-strong bg-surface-neutral-primary hover:bg-surface-neutral-secondary focus-within:bg-surface-neutral-secondary focus-within:shadow-focus m-2 flex h-10 items-center gap-2.5 rounded-sm border border-solid px-3 pr-10"
>
<SearchIcon className="text-icon-neutral-tertiary size-4 shrink-0" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-text-neutral-subtle flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",
"placeholder:text-text-neutral-subtle text-text-neutral-secondary text-body-default-regular-0 font-body-default-regular-0 flex h-full w-full border-0 bg-transparent py-0 outline-none focus:outline-none focus-visible:outline-none disabled:cursor-not-allowed disabled:opacity-50",
className
)}
style={{ boxShadow: "none", ...style }}
{...props}
/>
</div>
@@ -63,7 +82,13 @@ function CommandInput({ className, ...props }: React.ComponentProps<typeof Comma
}
function CommandList({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.List>) {
return <CommandPrimitive.List data-slot="command-list" className={cn("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto", className)} {...props} />;
return (
<CommandPrimitive.List
data-slot="command-list"
className={cn("max-h-[300px] scroll-py-1 overflow-x-hidden overflow-y-auto overscroll-contain", className)}
{...props}
/>
);
}
function CommandEmpty({ ...props }: React.ComponentProps<typeof CommandPrimitive.Empty>) {
@@ -75,7 +100,7 @@ function CommandGroup({ className, ...props }: React.ComponentProps<typeof Comma
<CommandPrimitive.Group
data-slot="command-group"
className={cn(
"text-text-neutral-primary [&_[cmdk-group-heading]]:text-text-neutral-tertiary overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",
"text-text-neutral-primary [&_[cmdk-group-heading]]:text-text-neutral-tertiary [&_[cmdk-group-heading]]:text-body-extra-small-medium-0 [&_[cmdk-group-heading]]:font-body-extra-small-medium-0 overflow-hidden px-1 py-1.5 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5",
className
)}
{...props}
@@ -92,7 +117,7 @@ function CommandItem({ className, ...props }: React.ComponentProps<typeof Comman
<CommandPrimitive.Item
data-slot="command-item"
className={cn(
"data-[selected=true]:bg-surface-neutral-secondary data-[selected=true]:text-text-neutral-primary [&_svg:not([class*='text-'])]:text-text-neutral-tertiary relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group/command-item hover:bg-surface-neutral-tertiary active:bg-surface-neutral-secondary data-[selected=true]:bg-surface-ui-subtle-blue-default data-[selected=true]:text-text-neutral-primary [&_svg:not([class*='text-'])]:text-text-neutral-tertiary text-body-small-medium-150 font-body-small-medium-150 relative flex cursor-pointer items-center gap-2 rounded-md px-2 py-2 outline-hidden transition-colors select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
@@ -1,27 +1,47 @@
import "@testing-library/jest-dom";
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { act, fireEvent, render, screen, waitFor, type RenderResult } from "@testing-library/react";
import React from "react";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { GlobalSearchEntityType, GlobalSearchResponse } from "~/services/search/globalSearch.server";
import { UI_ACTION_IDS, UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
import type { ScopedCommandAction } from "~/services/command-registry/commandRegistry";
import CommandPalette from "./CommandPalette";
type FetcherMock = {
state: "idle" | "loading";
data?: GlobalSearchResponse | { error: string };
load: ReturnType<typeof vi.fn>;
submit: ReturnType<typeof vi.fn>;
};
type CommandPaletteTestState = {
navigate: ReturnType<typeof vi.fn>;
openWindow: ReturnType<typeof vi.fn>;
getCommandRegistryActions: ReturnType<typeof vi.fn>;
useAppOrAdminData: ReturnType<typeof vi.fn>;
useRootData: ReturnType<typeof vi.fn>;
actionFetcher: FetcherMock;
searchFetcher: FetcherMock;
recentFetcher: FetcherMock;
};
declare global {
var __commandPaletteTest: CommandPaletteTestState;
}
function createFetcher(): FetcherMock {
return { state: "idle", data: undefined, load: vi.fn().mockResolvedValue(undefined), submit: vi.fn() };
}
globalThis.__commandPaletteTest = {
navigate: vi.fn(),
openWindow: vi.fn(),
getCommandRegistryActions: vi.fn(),
useAppOrAdminData: vi.fn(),
useRootData: vi.fn(),
actionFetcher: createFetcher(),
searchFetcher: createFetcher(),
recentFetcher: createFetcher(),
};
globalThis.ResizeObserver =
@@ -34,14 +54,18 @@ globalThis.ResizeObserver =
HTMLElement.prototype.scrollIntoView = HTMLElement.prototype.scrollIntoView ?? vi.fn();
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (value: string) => value }),
useTranslation: () => ({ t: (value: string) => value, i18n: { language: "en" } }),
}));
vi.mock("react-router", async () => {
const actual = await vi.importActual<typeof import("react-router")>("react-router");
return {
...actual,
useFetcher: () => ({ submit: vi.fn() }),
useFetcher: (options?: { key?: string }) => {
if (options?.key === "command-palette-search") return globalThis.__commandPaletteTest.searchFetcher;
if (options?.key === "command-palette-recent") return globalThis.__commandPaletteTest.recentFetcher;
return globalThis.__commandPaletteTest.actionFetcher;
},
useNavigate: () => globalThis.__commandPaletteTest.navigate,
};
});
@@ -58,111 +82,452 @@ vi.mock("~/services/command-registry/commandRegistry", () => ({
getCommandRegistryActions: (...args: unknown[]) => globalThis.__commandPaletteTest.getCommandRegistryActions(...args),
}));
const appData = { currentTenant: { slug: "acme" } };
const rootData = { appConfiguration: { app: { features: {} } } };
const appData = { currentTenant: { slug: "acme" }, permissions: ["search.use"] };
const rootData = { csrf: "csrf-token", appConfiguration: { app: { features: {} } } };
function renderPalette(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
return render(
function paletteElement(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
return (
<CommandPalette layout="app" {...props}>
<button data-ui-id={UI_ACTION_IDS.search}>Open search</button>
<button data-ui-id={UI_ACTION_IDS.searchMobile}>Open mobile search</button>
<div>Palette child</div>
</CommandPalette>
);
}
function renderPalette(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
return render(paletteElement(props));
}
function openPalette() {
fireEvent.keyDown(window, { key: "k", metaKey: true });
}
function openPaletteWithCtrl() {
fireEvent.keyDown(window, { key: "k", ctrlKey: true });
}
function searchInput() {
return document.querySelector<HTMLInputElement>(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteSearch}"]`)!;
}
function lastSearchRequest() {
const url = globalThis.__commandPaletteTest.searchFetcher.load.mock.calls.at(-1)?.[0] as string;
return new URL(url, "https://app.example.test");
}
function resultRow(entityType: GlobalSearchEntityType, entityId: string) {
const normalizedId = entityId
.split(/[^a-zA-Z0-9]+/u)
.filter(Boolean)
.map((word, index) => (index === 0 ? word.toLowerCase() : `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}`))
.join("");
return document.querySelector<HTMLElement>(`[data-ui-id="ui.surface.commandPalette.result.${entityType}.${normalizedId}"]`)!;
}
function searchResponse(requestUrl: URL, overrides: Partial<GlobalSearchResponse> = {}): GlobalSearchResponse {
const query = requestUrl.searchParams.get("q") ?? "";
const requestedEntityTypes = requestUrl.searchParams.getAll("type") as GlobalSearchEntityType[];
const requestId = requestUrl.searchParams.get("requestId");
const limit = requestUrl.searchParams.get("limit") ?? "20";
return {
query,
requestedEntityTypes,
requestId,
requestKey: `${encodeURIComponent(query)}|${requestedEntityTypes.join(",") || "*"}|${limit}`,
results: [],
recentSearches: [],
hiddenEntityTypes: [],
latencyHint: "Search index updates can take up to 10 seconds.",
...overrides,
};
}
async function sendSearchQuery(query: string) {
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: query } });
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
return lastSearchRequest();
}
async function applySearchResponse(
view: RenderResult,
response: GlobalSearchResponse | { error: string },
props?: Partial<React.ComponentProps<typeof CommandPalette>>
) {
globalThis.__commandPaletteTest.searchFetcher.state = "idle";
globalThis.__commandPaletteTest.searchFetcher.data = response;
view.rerender(paletteElement(props));
await act(async () => undefined);
}
describe("CommandPalette", () => {
// CommandPaletteDialog wird in der Komponente per React.lazy(() => import("./CommandPaletteDialog"))
// geladen. In der vollen Suite kann der KALTE erste dynamische Import unter CPU-Last die
// 1000ms-Default-Frist von findByText reissen (erster Test rot, danach Modul warm -> gruen).
// Vorwaermen macht den ersten Oeffnen-Pfad deterministisch synchron.
beforeAll(async () => {
await import("./CommandPaletteDialog");
});
}, 60000);
beforeEach(() => {
const state = globalThis.__commandPaletteTest;
state.navigate.mockReset();
state.openWindow.mockReset();
state.getCommandRegistryActions.mockReset();
state.useAppOrAdminData.mockReset();
state.useRootData.mockReset();
state.actionFetcher = createFetcher();
state.searchFetcher = createFetcher();
state.recentFetcher = createFetcher();
state.useAppOrAdminData.mockReturnValue(appData);
state.useRootData.mockReturnValue(rootData);
state.getCommandRegistryActions.mockReturnValue([
{ id: "registry-dashboard", name: "Dashboard", subtitle: "App", perform: vi.fn(), scope: { layout: "app", tenantSlug: "acme" } },
{ id: "registry-denied-looking", name: "Denied Looking", subtitle: "Filtered upstream", perform: vi.fn(), scope: { layout: "app", tenantSlug: "acme", permission: "entity.contacts.view" } },
{ id: "registry-profile", name: "Profile", subtitle: "Settings", perform: vi.fn(), scope: { layout: "app", tenantSlug: "acme" } },
]);
vi.spyOn(window, "open").mockImplementation(state.openWindow);
});
function openPalette() {
afterEach(() => {
vi.useRealTimers();
vi.restoreAllMocks();
});
it("passes registry actions through and opens from Cmd+K or Ctrl+K", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(globalThis.__commandPaletteTest.getCommandRegistryActions).toHaveBeenCalledWith(
expect.objectContaining({ layout: "app", navigate: globalThis.__commandPaletteTest.navigate, appData, rootData })
);
expect(screen.getByText("Palette child")).toBeInTheDocument();
expect(document.querySelector('[data-ui-id="ui.surface.commandPalette.action.registryDashboard"]')).toBeInTheDocument();
fireEvent.keyDown(window, { key: "k", metaKey: true });
}
function openPaletteWithCtrl() {
fireEvent.keyDown(window, { key: "k", ctrlKey: true });
}
it("passes the filtered registry-backed actions through for the active layout context", async () => {
renderPalette();
const state = globalThis.__commandPaletteTest;
expect(state.getCommandRegistryActions).not.toHaveBeenCalled();
openPalette();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(state.getCommandRegistryActions).toHaveBeenCalledWith(expect.objectContaining({
layout: "app",
t: expect.any(Function),
navigate: state.navigate,
appData,
rootData,
}));
expect(screen.getByText("Denied Looking")).toBeInTheDocument();
expect(screen.getByText("Palette child")).toBeInTheDocument();
});
it("uses a custom actions prop instead of registry actions", async () => {
const customActions: ScopedCommandAction[] = [{ id: "custom-action", name: "Custom Action", perform: vi.fn(), scope: { layout: "app" } }];
renderPalette({ actions: customActions });
const state = globalThis.__commandPaletteTest;
expect(state.getCommandRegistryActions).not.toHaveBeenCalled();
openPalette();
expect(await screen.findByText("Custom Action")).toBeInTheDocument();
expect(state.getCommandRegistryActions).not.toHaveBeenCalled();
});
it("opens from the Windows/Linux Ctrl+K shortcut", async () => {
renderPalette();
expect(screen.queryByText("Dashboard")).not.toBeInTheDocument();
openPaletteWithCtrl();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(screen.getByText("Denied Looking")).toBeInTheDocument();
expect(await screen.findByText("Dashboard")).toBeInTheDocument();
view.unmount();
});
it("renders a safe empty path when app/root data is missing", async () => {
const state = globalThis.__commandPaletteTest;
state.useAppOrAdminData.mockReturnValue(undefined);
state.useRootData.mockReturnValue(undefined);
state.getCommandRegistryActions.mockReturnValue([]);
renderPalette();
it("uses custom actions without consulting the registry", async () => {
const customActions: ScopedCommandAction[] = [{ id: "custom-action", name: "Custom Action", perform: vi.fn(), scope: { layout: "app" } }];
renderPalette({ actions: customActions });
openPalette();
await waitFor(() => {
expect(state.getCommandRegistryActions).toHaveBeenCalledWith(expect.objectContaining({ appData: undefined, rootData: undefined }));
expect(await screen.findByText("Custom Action")).toBeInTheDocument();
expect(globalThis.__commandPaletteTest.getCommandRegistryActions).not.toHaveBeenCalled();
});
it("debounces global search, requests 20 results, and does not reload after accepting a response", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
await waitFor(() => expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(1));
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: "solar" } });
await act(async () => {
await vi.advanceTimersByTimeAsync(299);
});
expect(screen.getByText("Palette child")).toBeInTheDocument();
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
vi.useRealTimers();
const request = lastSearchRequest();
expect(request.pathname).toContain("/search/api");
expect(request.searchParams.get("q")).toBe("solar");
expect(request.searchParams.get("limit")).toBe("20");
expect(request.searchParams.getAll("type")).toEqual(["contact", "company", "lead", "project", "file", "task", "employee", "user"]);
expect(request.searchParams.get("requestId")).toMatch(/^spotlight-/);
await applySearchResponse(view, searchResponse(request));
await screen.findByText("search.results.empty");
await act(async () => undefined);
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(2);
});
it("renders stable data-ui-id attributes for command palette surfaces and rows", async () => {
it("rejects a stale response after filters change and renders the current grouped response with permission hint", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const firstRequest = await sendSearchQuery("solar");
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: "search.entities.user" }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const currentRequest = lastSearchRequest();
expect(currentRequest.searchParams.get("requestId")).not.toBe(firstRequest.searchParams.get("requestId"));
expect(currentRequest.searchParams.getAll("type")).toEqual(["user"]);
await applySearchResponse(
view,
searchResponse(firstRequest, {
results: [
{
id: "stale",
entityType: "project",
title: "Stale solar project",
subtitle: "P-0",
href: "/projects/stale",
permissionSubject: "projects.read_all",
updatedAt: null,
},
],
})
);
expect(screen.queryByText("Stale solar project")).not.toBeInTheDocument();
await applySearchResponse(
view,
searchResponse(currentRequest, {
hiddenEntityTypes: ["user"],
results: [
{
id: "project-1",
entityType: "project",
title: "Solar roof",
subtitle: "P-100",
href: "/projects/project-1",
permissionSubject: "projects.read_all",
updatedAt: "2026-07-12T08:00:00.000Z",
},
{
id: "contact-1",
entityType: "contact",
title: "Solaris GmbH",
subtitle: "info@solaris.test",
href: "/contacts/contact-1",
permissionSubject: "crm.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("project", "project-1")).toHaveTextContent("Solar roof"));
const headings = [...document.querySelectorAll("[cmdk-group-heading]")].map((node) => node.textContent);
expect(headings.indexOf("search.entities.contact")).toBeLessThan(headings.indexOf("search.entities.project"));
expect(screen.getByText("search.results.hidden")).toBeInTheDocument();
expect(document.querySelector("mark")).toHaveTextContent(/solar/i);
});
it("narrows to a single category on the first tile click and resets to all when the last one is deselected", async () => {
renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
await sendSearchQuery("solar");
async function clickTile(entityType: GlobalSearchEntityType) {
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: `search.entities.${entityType}` }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
return lastSearchRequest().searchParams.getAll("type");
}
// All selected by default: first click focuses on the clicked category only.
expect(await clickTile("project")).toEqual(["project"]);
// Further clicks toggle categories in canonical order.
expect(await clickTile("contact")).toEqual(["contact", "project"]);
expect(await clickTile("contact")).toEqual(["project"]);
// Deselecting the last active category resets back to all.
expect(await clickTile("project")).toEqual(["contact", "company", "lead", "project", "file", "task", "employee", "user"]);
});
it("shows loading, error, empty, short-query, and recent-search states", async () => {
const view = renderPalette();
openPalette();
expect(await screen.findByText("search.command.minimumCharacters")).toBeInTheDocument();
const recentRequest = lastSearchRequest();
await applySearchResponse(
view,
searchResponse(recentRequest, {
recentSearches: [{ id: "recent-1", queryText: "heat pump", entityTypes: ["project", "task"], resultCount: 4, createdAt: "2026-07-12T08:00:00.000Z" }],
})
);
expect(await screen.findByText("heat pump")).toBeInTheDocument();
vi.useFakeTimers();
fireEvent.change(searchInput(), { target: { value: "nothing" } });
globalThis.__commandPaletteTest.searchFetcher.state = "loading";
view.rerender(paletteElement());
expect(screen.getByText("search.command.loading")).toBeInTheDocument();
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const emptyRequest = lastSearchRequest();
await applySearchResponse(view, searchResponse(emptyRequest));
expect(await screen.findByText("search.results.empty")).toBeInTheDocument();
await applySearchResponse(view, { error: "invalid_request_id" });
expect(await screen.findByText("search.command.error")).toBeInTheDocument();
const requestsBeforeRetry = globalThis.__commandPaletteTest.searchFetcher.load.mock.calls.length;
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: "shared.retry" }));
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
expect(globalThis.__commandPaletteTest.searchFetcher.load).toHaveBeenCalledTimes(requestsBeforeRetry + 1);
});
it("records a committed selection without waiting before Enter navigates in the same tab", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("anna");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "contact-1",
entityType: "contact",
title: "Anna Becker",
subtitle: "anna@example.test",
href: "/contacts/contact-1",
permissionSubject: "crm.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("contact", "contact-1")).toHaveTextContent("Anna Becker"));
const row = resultRow("contact", "contact-1");
row.focus();
fireEvent.keyDown(row, { key: "Enter" });
expect(globalThis.__commandPaletteTest.navigate).toHaveBeenCalledWith("/contacts/contact-1");
expect(globalThis.__commandPaletteTest.recentFetcher.submit).toHaveBeenCalledTimes(1);
const [form, options] = globalThis.__commandPaletteTest.recentFetcher.submit.mock.calls[0]!;
expect(form).toBeInstanceOf(FormData);
expect((form as FormData).get("intent")).toBe("recordRecent");
expect((form as FormData).get("query")).toBe("anna");
expect((form as FormData).get("selectedEntityType")).toBe("contact");
expect((form as FormData).get("selectedEntityId")).toBe("contact-1");
expect((form as FormData).get("csrf")).toBe("csrf-token");
expect(options).toEqual(expect.objectContaining({ method: "post", action: expect.stringContaining("/search/api") }));
});
it.each([
{ label: "Cmd", modifier: "metaKey" as const },
{ label: "Ctrl", modifier: "ctrlKey" as const },
])("opens the selected result in a new tab with $label+Enter", async ({ modifier }) => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("quote");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "file-1",
entityType: "file",
title: "Quote.pdf",
subtitle: "application/pdf",
href: "/files/file-1",
permissionSubject: "files.read_all",
updatedAt: null,
},
],
})
);
await waitFor(() => expect(resultRow("file", "file-1")).toHaveTextContent("Quote.pdf"));
const row = resultRow("file", "file-1");
row.focus();
fireEvent.keyDown(row, { key: "Enter", [modifier]: true });
await waitFor(() => expect(globalThis.__commandPaletteTest.openWindow).toHaveBeenCalledWith("/files/file-1", "_blank", "noopener,noreferrer"));
expect(globalThis.__commandPaletteTest.navigate).not.toHaveBeenCalled();
});
it("loads one additional page inside the modal up to the 50-result cap", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("project");
const results = Array.from({ length: 20 }, (_, index) => ({
id: `project-${index}`,
entityType: "project" as const,
title: `Project ${index}`,
subtitle: `P-${index}`,
href: `/projects/project-${index}`,
permissionSubject: "projects.read_all",
updatedAt: null,
}));
await applySearchResponse(view, searchResponse(request, { results }));
const loadMore = await screen.findByRole("button", { name: "search.command.loadMore" });
vi.useFakeTimers();
fireEvent.click(loadMore);
await act(async () => {
await vi.advanceTimersByTimeAsync(300);
});
vi.useRealTimers();
const expandedRequest = lastSearchRequest();
expect(expandedRequest.searchParams.get("limit")).toBe("50");
await applySearchResponse(view, searchResponse(expandedRequest, { results }));
expect(screen.queryByRole("button", { name: "search.command.loadMore" })).not.toBeInTheDocument();
});
it("renders unique registry-backed UI IDs for the mobile/desktop Spotlight surfaces and rows", async () => {
const view = renderPalette();
openPalette();
await screen.findByText("search.command.minimumCharacters");
const request = await sendSearchQuery("solar");
await applySearchResponse(
view,
searchResponse(request, {
results: [
{
id: "project-1",
entityType: "project",
title: "Solar roof",
subtitle: "P-100",
href: "/projects/project-1",
permissionSubject: "projects.read_all",
updatedAt: null,
},
],
})
);
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPalettePortal}"]`)).toHaveClass("h-dvh", "sm:h-auto");
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteSearch}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteFilters}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteResults}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteFooter}"]`)).toBeInTheDocument();
const ids = [...document.querySelectorAll("[data-ui-id]")].map((element) => element.getAttribute("data-ui-id"));
expect(new Set(ids).size).toBe(ids.length);
expect(ids).toContain("ui.surface.commandPalette.result.project.project1");
});
it("renders a safe action-only palette when app/root data is missing", async () => {
globalThis.__commandPaletteTest.useAppOrAdminData.mockReturnValue(undefined);
globalThis.__commandPaletteTest.useRootData.mockReturnValue(undefined);
globalThis.__commandPaletteTest.getCommandRegistryActions.mockReturnValue([]);
renderPalette();
openPalette();
await screen.findByText("Dashboard", undefined, { timeout: 4000 });
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPalettePortal}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteSearch}"]`)).toBeInTheDocument();
expect(document.querySelector(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteResults}"]`)).toBeInTheDocument();
expect(document.querySelectorAll(`[data-ui-id="${UI_SURFACE_IDS.commandPaletteRow}"]`)).toHaveLength(2);
expect(screen.getByText("Dashboard")).toBeInTheDocument();
expect(screen.getByText("Denied Looking")).toBeInTheDocument();
expect(await screen.findByText("app.commands.empty.title")).toBeInTheDocument();
expect(globalThis.__commandPaletteTest.searchFetcher.load).not.toHaveBeenCalled();
});
});
@@ -1,16 +1,27 @@
import { useEffect, useMemo, useState } from "react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { useFetcher, useNavigate } from "react-router";
import { UI_SURFACE_IDS } from "~/application/ui/uiRegistry";
import { CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "~/components/ui/command";
import {
buildSpotlightSearchGroups,
type SpotlightSearchDialogVM,
type SpotlightSearchEntityType,
type SpotlightSearchItemVM,
type SpotlightSearchRecentVM,
} from "@hivegrid/view-models";
import { UI_ACTION_IDS } from "~/application/ui/uiRegistry";
import type { GlobalSearchEntityType, GlobalSearchResponse } from "~/services/search/globalSearch.server";
import { getCommandRegistryActions, type CommandRegistryLayout, type ScopedCommandAction } from "~/services/command-registry/commandRegistry";
import { appPath } from "~/utils/app/CanonicalUrlUtils";
import type { AppLoaderData } from "~/utils/data/useAppData";
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
import { useRootData } from "~/utils/data/useRootData";
import { SpotlightSearchDialogView } from "./SpotlightSearchDialogView";
const globalSearchEntityTypes: GlobalSearchEntityType[] = ["contact", "company", "lead", "project", "file", "task", "user"];
const INITIAL_RESULT_LIMIT = 20;
const MAX_RESULT_LIMIT = 50;
const SEARCH_DEBOUNCE_MS = 300;
const globalSearchEntityTypes: GlobalSearchEntityType[] = ["contact", "company", "lead", "project", "file", "task", "employee", "user"];
type SearchFetcherData = GlobalSearchResponse | { error: string };
export default function CommandPaletteDialog({
actions,
@@ -25,35 +36,91 @@ export default function CommandPaletteDialog({
}) {
const { t, i18n } = useTranslation();
const navigate = useNavigate();
const fetcher = useFetcher();
const searchFetcher = useFetcher<GlobalSearchResponse>();
const fetcher = useFetcher({ key: "command-palette-actions" });
const searchFetcher = useFetcher<SearchFetcherData>({ key: "command-palette-search" });
const recentFetcher = useFetcher({ key: "command-palette-recent" });
const appData = useAppOrAdminData() as AppLoaderData | undefined;
const rootData = useRootData();
const [query, setQuery] = useState("");
const [selectedEntityTypes, setSelectedEntityTypes] = useState<GlobalSearchEntityType[]>(globalSearchEntityTypes);
const [resultLimit, setResultLimit] = useState(INITIAL_RESULT_LIMIT);
const [expectedRequestId, setExpectedRequestId] = useState<string | null>(null);
const [acceptedRequestId, setAcceptedRequestId] = useState<string | null>(null);
const [isDebouncing, setIsDebouncing] = useState(false);
const [searchFailed, setSearchFailed] = useState(false);
const [retryVersion, setRetryVersion] = useState(0);
const requestSequence = useRef(0);
const pendingRequestId = useRef<string | null>(null);
const openSelectionInNewTab = useRef(false);
const searchLoad = useRef(searchFetcher.load);
searchLoad.current = searchFetcher.load;
const canUseGlobalSearch = layout === "app" && !!appData?.currentTenant?.slug && appData.permissions?.includes("search.use");
const trimmedQuery = query.trim();
const searchResults = searchFetcher.data?.query === trimmedQuery ? (searchFetcher.data.results ?? []) : [];
const recentSearches = searchFetcher.data?.query === "" ? (searchFetcher.data.recentSearches ?? []) : [];
const activeTypeParams = useMemo(() => selectedEntityTypes.map((type) => `type=${encodeURIComponent(type)}`).join("&"), [selectedEntityTypes]);
const allResultsHref = useMemo(() => {
if (!appData?.currentTenant?.slug) return "";
const suffix = activeTypeParams ? `&${activeTypeParams}` : "";
return appPath({ tenantSlug: appData.currentTenant.slug, path: `search?q=${encodeURIComponent(trimmedQuery)}${suffix}`, mode: "host-aware" });
}, [activeTypeParams, appData?.currentTenant?.slug, trimmedQuery]);
const isSearchQuery = trimmedQuery.length >= 2;
const canonicalSelectedEntityTypes = useMemo(() => globalSearchEntityTypes.filter((type) => selectedEntityTypes.includes(type)), [selectedEntityTypes]);
const activeTypeParams = useMemo(
() => canonicalSelectedEntityTypes.map((type) => `type=${encodeURIComponent(type)}`).join("&"),
[canonicalSelectedEntityTypes]
);
const currentResponse =
isGlobalSearchResponse(searchFetcher.data) &&
searchFetcher.data.requestId &&
searchFetcher.data.requestId === expectedRequestId &&
searchFetcher.data.requestId === acceptedRequestId
? searchFetcher.data
: undefined;
const searchResults = isSearchQuery && currentResponse?.query === trimmedQuery ? currentResponse.results : [];
const recentSearches = !isSearchQuery && currentResponse?.query === "" ? currentResponse.recentSearches : [];
const searchGroups = useMemo(() => buildSpotlightSearchGroups(searchResults), [searchResults]);
const isLoading = canUseGlobalSearch && !searchFailed && (isDebouncing || searchFetcher.state !== "idle" || expectedRequestId !== acceptedRequestId);
const hiddenEntityTypes = currentResponse?.hiddenEntityTypes ?? [];
const canLoadMore = isSearchQuery && !isLoading && !searchFailed && resultLimit === INITIAL_RESULT_LIMIT && searchResults.length === INITIAL_RESULT_LIMIT;
useEffect(() => {
if (!open || !canUseGlobalSearch || !appData?.currentTenant?.slug) return;
if (trimmedQuery.length < 2) {
searchFetcher.load(appPath({ tenantSlug: appData.currentTenant.slug, path: "search/api?limit=6", mode: "host-aware" }));
const requestId = `spotlight-${++requestSequence.current}`;
pendingRequestId.current = requestId;
setExpectedRequestId(requestId);
setAcceptedRequestId(null);
setSearchFailed(false);
const typeSuffix = activeTypeParams ? `&${activeTypeParams}` : "";
const loadSearch = (path: string) => {
void searchLoad.current(appPath({ tenantSlug: appData.currentTenant.slug, path, mode: "host-aware" })).catch(() => {
if (pendingRequestId.current === requestId) {
setSearchFailed(true);
setIsDebouncing(false);
}
});
};
if (!isSearchQuery) {
setIsDebouncing(false);
loadSearch(`search/api?limit=6&requestId=${encodeURIComponent(requestId)}`);
return;
}
const typeSuffix = activeTypeParams ? `&${activeTypeParams}` : "";
setIsDebouncing(true);
const timeout = window.setTimeout(() => {
searchFetcher.load(appPath({ tenantSlug: appData.currentTenant.slug, path: `search/api?q=${encodeURIComponent(trimmedQuery)}&limit=6${typeSuffix}`, mode: "host-aware" }));
}, 300);
setIsDebouncing(false);
loadSearch(`search/api?q=${encodeURIComponent(trimmedQuery)}&limit=${resultLimit}${typeSuffix}&requestId=${encodeURIComponent(requestId)}`);
}, SEARCH_DEBOUNCE_MS);
return () => window.clearTimeout(timeout);
}, [activeTypeParams, appData?.currentTenant?.slug, canUseGlobalSearch, open, searchFetcher, trimmedQuery]);
}, [activeTypeParams, appData?.currentTenant?.slug, canUseGlobalSearch, isSearchQuery, open, resultLimit, retryVersion, trimmedQuery]);
useEffect(() => {
if (searchFetcher.state !== "idle" || !searchFetcher.data) return;
if (!isGlobalSearchResponse(searchFetcher.data)) {
setSearchFailed(true);
setIsDebouncing(false);
return;
}
if (!searchFetcher.data.requestId) return;
if (searchFetcher.data.requestId !== pendingRequestId.current) return;
setAcceptedRequestId(searchFetcher.data.requestId);
setSearchFailed(false);
}, [searchFetcher.data, searchFetcher.state]);
const resolvedActions =
actions ??
@@ -65,154 +132,144 @@ export default function CommandPaletteDialog({
navigate,
submitLogout: () => {
const form = new FormData();
if (rootData?.csrf) {
form.set("csrf", rootData.csrf);
}
if (rootData?.csrf) form.set("csrf", rootData.csrf);
fetcher.submit(form, { method: "post", action: "/logout" });
},
appData,
rootData,
})
: []);
const visibleActions = useMemo(() => {
const normalizedQuery = trimmedQuery.toLocaleLowerCase();
const matches = normalizedQuery
? resolvedActions.filter((action) =>
[action.name, action.subtitle, action.keywords, action.id].filter(Boolean).join(" ").toLocaleLowerCase().includes(normalizedQuery)
)
: resolvedActions;
return matches.slice(0, isSearchQuery ? 4 : 8);
}, [isSearchQuery, resolvedActions, trimmedQuery]);
function updateQuery(value: string) {
setQuery(value);
setResultLimit(INITIAL_RESULT_LIMIT);
}
function toggleEntityType(type: GlobalSearchEntityType) {
setSelectedEntityTypes((current) => {
// Default state is "all selected": the first tile click narrows to that category only.
if (current.length === globalSearchEntityTypes.length) {
return [type];
}
if (current.includes(type)) {
const next = current.filter((entry) => entry !== type);
// Deselecting the last active category resets back to "all selected".
return next.length > 0 ? next : globalSearchEntityTypes;
}
return globalSearchEntityTypes.filter((entry) => entry === type || current.includes(entry));
});
setResultLimit(INITIAL_RESULT_LIMIT);
}
function recordCommittedSelection(item: SpotlightSearchItemVM) {
if (!appData?.currentTenant?.slug || !rootData?.csrf) return;
const form = new FormData();
form.set("intent", "recordRecent");
form.set("query", trimmedQuery);
form.set("resultCount", String(searchResults.length));
canonicalSelectedEntityTypes.forEach((type) => form.append("type", type));
form.set("selectedEntityType", item.entityType);
form.set("selectedEntityId", item.id);
form.set("csrf", rootData.csrf);
recentFetcher.submit(form, {
method: "post",
action: appPath({ tenantSlug: appData.currentTenant.slug, path: "search/api", mode: "host-aware" }),
});
}
function openResult(item: SpotlightSearchItemVM) {
recordCommittedSelection(item);
const shouldOpenNewTab = openSelectionInNewTab.current;
openSelectionInNewTab.current = false;
if (shouldOpenNewTab) {
window.open(item.href, "_blank", "noopener,noreferrer");
} else {
navigate(item.href);
}
setOpen(false);
}
const searchState: SpotlightSearchDialogVM["searchState"] = !canUseGlobalSearch
? "idle"
: isLoading
? "loading"
: searchFailed
? "error"
: isSearchQuery && currentResponse && searchGroups.length === 0
? "empty"
: currentResponse
? "ready"
: "idle";
const vm = {
open,
query,
selectedEntityTypes: canonicalSelectedEntityTypes,
canUseGlobalSearch,
isSearchQuery,
searchState,
hasResolvedResponse: !!currentResponse,
searchGroups: searchGroups.map((group) => ({ ...group, items: [...group.items] })),
recentSearches: recentSearches.map(({ id, queryText, entityTypes, resultCount }) => ({ id, queryText, entityTypes, resultCount })),
hiddenEntityTypes,
canLoadMore,
visibleActions: visibleActions.map((action) => ({
id: action.id,
name: action.name,
subtitle: action.subtitle ?? null,
searchValue: [action.name, action.subtitle, action.keywords, action.id].filter(Boolean).join(" "),
})),
} satisfies SpotlightSearchDialogVM;
return (
<div>
<CommandDialog
open={open}
onOpenChange={setOpen}
dataUiId={UI_SURFACE_IDS.commandPalettePortal}
onCloseAutoFocus={(event) => {
// The palette opens via controlled state, not a Radix trigger, so Radix
// drops focus to <body> on close. Return focus to the search trigger.
const trigger = typeof document !== "undefined" ? document.querySelector<HTMLElement>('[data-ui-id="ui.action.shell.search"]') : null;
<SpotlightSearchDialogView
vm={vm}
actions={{
onOpenChange: setOpen,
onQueryChange: updateQuery,
onToggleEntityType: (entityType: SpotlightSearchEntityType) => toggleEntityType(entityType),
onSelectRecent: (recent: SpotlightSearchRecentVM) => {
if (recent.entityTypes.length > 0) setSelectedEntityTypes(recent.entityTypes);
updateQuery(recent.queryText);
},
onPrepareResultSelection: () => {
openSelectionInNewTab.current = false;
},
onSelectResult: openResult,
onLoadMore: () => setResultLimit(MAX_RESULT_LIMIT),
onRetry: () => setRetryVersion((current) => current + 1),
onSelectAction: (actionId) => {
const action = visibleActions.find((candidate) => candidate.id === actionId);
action?.perform?.(action);
setOpen(false);
},
onCommandKeyDownCapture: (event) => {
if (event.key === "Enter") openSelectionInNewTab.current = event.metaKey || event.ctrlKey;
},
onCloseAutoFocus: (event) => {
const triggers =
typeof document !== "undefined"
? Array.from(document.querySelectorAll<HTMLElement>(`[data-ui-id="${UI_ACTION_IDS.searchMobile}"], [data-ui-id="${UI_ACTION_IDS.search}"]`))
: [];
const trigger = triggers.find((candidate) => candidate.offsetParent !== null) ?? triggers[0];
if (trigger) {
event.preventDefault();
trigger.focus();
}
}}
>
<CommandInput data-ui-id={UI_SURFACE_IDS.commandPaletteSearch} value={query} onValueChange={setQuery} />
<CommandList data-ui-id={UI_SURFACE_IDS.commandPaletteResults}>
<CommandEmpty>{t("app.commands.empty.title")}</CommandEmpty>
{canUseGlobalSearch ? (
<div className="flex flex-wrap gap-1.5 border-b border-border-neutral px-2 py-2">
{globalSearchEntityTypes.map((type) => {
const active = selectedEntityTypes.includes(type);
return (
<button
key={type}
type="button"
aria-pressed={active}
className={
active
? "rounded-md bg-neutral-900 px-2 py-1 text-xs font-medium text-white"
: "text-text-neutral-secondary rounded-md border border-border-neutral px-2 py-1 text-xs font-medium hover:bg-neutral-50"
}
onMouseDown={(event) => event.preventDefault()}
onClick={() => {
setSelectedEntityTypes((current) => {
if (current.includes(type)) {
const next = current.filter((entry) => entry !== type);
return next.length > 0 ? next : current;
}
return [...current, type];
});
}}
>
{t(`search.entities.${type}`)}
</button>
);
})}
</div>
) : null}
{canUseGlobalSearch && searchResults.length > 0 ? (
<CommandGroup heading={t("search.command.group")}>
{searchResults.map((result) => (
<CommandItem
key={`${result.entityType}:${result.id}`}
data-ui-id={UI_SURFACE_IDS.commandPaletteRow}
value={[result.title, result.subtitle, result.entityType].filter(Boolean).join(" ")}
onSelect={() => {
navigate(result.href);
setOpen(false);
}}
>
<div className="flex w-full items-center justify-between gap-2">
<div className="min-w-0">
<div className="text-text-neutral-primary/80 truncate text-sm font-medium">{highlightMatch(result.title, trimmedQuery)}</div>
<div className="text-text-neutral-tertiary truncate text-xs">{highlightMatch(result.subtitle, trimmedQuery)}</div>
</div>
<div className="text-text-neutral-tertiary shrink-0 text-xs">{t(`search.entities.${result.entityType}`)}</div>
</div>
</CommandItem>
))}
<CommandItem
data-ui-id={UI_SURFACE_IDS.commandPaletteRow}
value={`${t("search.command.allResults")} ${query}`}
onSelect={() => {
navigate(allResultsHref);
setOpen(false);
}}
>
<div className="text-text-neutral-primary/80 text-sm font-medium">{t("search.command.allResults", { count: searchResults.length })}</div>
</CommandItem>
</CommandGroup>
) : null}
{canUseGlobalSearch && trimmedQuery.length < 2 && recentSearches.length > 0 ? (
<CommandGroup heading={t("search.command.recent")}>
{recentSearches.map((recent) => (
<CommandItem
key={recent.id}
data-ui-id={UI_SURFACE_IDS.commandPaletteRow}
value={recent.queryText}
onSelect={() => {
setQuery(recent.queryText);
}}
>
<div className="flex w-full items-center justify-between gap-2">
<span className="text-text-neutral-primary/80 truncate text-sm font-medium">{recent.queryText}</span>
<span className="text-text-neutral-tertiary shrink-0 text-xs">{t("search.results.title", { count: recent.resultCount })}</span>
</div>
</CommandItem>
))}
</CommandGroup>
) : null}
<CommandGroup>
{resolvedActions.map((action) => (
<CommandItem
key={action.id}
data-ui-id={UI_SURFACE_IDS.commandPaletteRow}
value={[action.name, action.subtitle, action.keywords, action.id].filter(Boolean).join(" ")}
onSelect={() => {
action.perform?.(action);
setOpen(false);
}}
>
<div className="flex w-full items-center justify-between gap-2">
<div className="text-text-neutral-primary/80 text-sm font-medium">{action.name}</div>
{action.subtitle ? <div className="text-text-neutral-tertiary truncate text-xs">{action.subtitle}</div> : null}
</div>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</CommandDialog>
</div>
},
}}
/>
);
}
function highlightMatch(value: string, query: string) {
if (!query) return value;
const index = value.toLocaleLowerCase().indexOf(query.toLocaleLowerCase());
if (index < 0) return value;
const before = value.slice(0, index);
const match = value.slice(index, index + query.length);
const after = value.slice(index + query.length);
return (
<>
{before}
<mark className="rounded bg-yellow-100 px-0.5 text-inherit">{match}</mark>
{after}
</>
);
function isGlobalSearchResponse(value: SearchFetcherData | undefined): value is GlobalSearchResponse {
return !!value && "results" in value && "requestKey" in value;
}
@@ -0,0 +1,394 @@
import { useTranslation } from "react-i18next";
import {
FeatherBuilding2,
FeatherCheckSquare,
FeatherChevronDown,
FeatherClock,
FeatherFile,
FeatherFolder,
FeatherLoader,
FeatherSearch,
FeatherShield,
FeatherTrendingUp,
FeatherUser,
FeatherUsers,
} from "@subframe/core";
import {
SPOTLIGHT_SEARCH_ENTITY_ORDER,
type SpotlightSearchDialogVM,
type SpotlightSearchEntityType,
type SpotlightSearchItemVM,
type SpotlightSearchRecentVM,
} from "@hivegrid/view-models";
import {
UI_ACTION_IDS,
UI_ID_PATTERNS,
UI_SURFACE_IDS,
getCommandPaletteActionId,
getCommandPaletteRecentId,
getCommandPaletteResultId,
} from "~/application/ui/uiRegistry";
import { CommandDialog, CommandGroup, CommandInput, CommandItem, CommandList } from "~/components/ui/command";
import {
ArrowLeftRightIcon,
ChevronRightIcon,
CodeIcon,
CreditCard,
FileTextIcon,
HomeIcon,
LogOut,
PlusIcon,
ShieldCheckIcon,
StoreIcon,
UserIcon,
} from "~/components/ui/icons/vendor";
import { useLocaleFormatters } from "~/locale/format";
import { BadgeShortcut } from "~/ui/components/BadgeShortcut";
import { Button } from "~/ui/components/Button";
import { IconWithBackground } from "~/ui/components/IconWithBackground";
export type SpotlightSearchDialogActions = {
readonly onOpenChange: (open: boolean) => void;
readonly onQueryChange: (query: string) => void;
readonly onToggleEntityType: (entityType: SpotlightSearchEntityType) => void;
readonly onSelectRecent: (recent: SpotlightSearchRecentVM) => void;
readonly onPrepareResultSelection: () => void;
readonly onSelectResult: (item: SpotlightSearchItemVM) => void;
readonly onLoadMore: () => void;
readonly onRetry: () => void;
readonly onSelectAction: (actionId: string) => void;
readonly onCommandKeyDownCapture: React.KeyboardEventHandler<HTMLDivElement>;
readonly onCloseAutoFocus: (event: Event) => void;
};
/** Presentational AD-28 interim UI. Data and side effects enter only through vm/actions. */
export function SpotlightSearchDialogView({ vm, actions }: { vm: SpotlightSearchDialogVM; actions: SpotlightSearchDialogActions }) {
const { t } = useTranslation();
const formatters = useLocaleFormatters();
return (
<CommandDialog
open={vm.open}
onOpenChange={actions.onOpenChange}
dataUiId={UI_SURFACE_IDS.commandPalettePortal}
shouldFilter={false}
onCommandKeyDownCapture={actions.onCommandKeyDownCapture}
onCloseAutoFocus={actions.onCloseAutoFocus}
>
<CommandInput
data-ui-id={UI_SURFACE_IDS.commandPaletteSearch}
value={vm.query}
onValueChange={actions.onQueryChange}
placeholder={t("search.command.placeholder")}
aria-label={t("search.form.label")}
/>
{vm.canUseGlobalSearch ? (
<div
className="border-border-default flex flex-nowrap gap-1 overflow-x-auto border-b px-3 py-2 [scrollbar-width:none] sm:px-4 [&::-webkit-scrollbar]:hidden"
data-ui-id={UI_SURFACE_IDS.commandPaletteFilters}
aria-label={t("search.command.filters")}
>
{SPOTLIGHT_SEARCH_ENTITY_ORDER.map((entityType) => {
const active = vm.selectedEntityTypes.includes(entityType);
return (
<button
key={entityType}
type="button"
aria-pressed={active}
className={
active
? "bg-surface-feedback-solid-neutral text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-on-solid shrink-0 rounded-md px-2.5 py-1 transition-colors"
: "border-border-default bg-surface-neutral-primary text-body-extra-small-medium-0 font-body-extra-small-medium-0 text-text-neutral-secondary hover:bg-surface-neutral-secondary shrink-0 rounded-md border px-2.5 py-1 transition-colors"
}
onMouseDown={(event) => event.preventDefault()}
onClick={() => actions.onToggleEntityType(entityType)}
>
{t(`search.entities.${entityType}`)}
</button>
);
})}
</div>
) : null}
<CommandList data-ui-id={UI_SURFACE_IDS.commandPaletteResults} className="max-h-none flex-1 pb-2 sm:max-h-[min(52vh,30rem)] sm:flex-none">
{vm.canUseGlobalSearch && !vm.isSearchQuery ? (
<SearchStatus icon={<FeatherSearch />} dataUiId={UI_SURFACE_IDS.commandPaletteQueryHint}>
{t("search.command.minimumCharacters")}
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState === "loading" ? (
<SearchStatus icon={<FeatherLoader className="animate-spin" />} dataUiId={UI_SURFACE_IDS.commandPaletteSearchStatus} live>
{t("search.command.loading")}
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState === "error" ? (
<SearchStatus icon={<FeatherSearch />} dataUiId={UI_SURFACE_IDS.commandPaletteSearchStatus} live>
<span className="flex flex-col items-center gap-2">
<span>{t("search.command.error")}</span>
<Button variant="tertiary" size="small" onMouseDown={(event) => event.preventDefault()} onClick={actions.onRetry}>
{t("shared.retry")}
</Button>
</span>
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState === "empty" ? (
<SearchStatus icon={<FeatherSearch />} dataUiId={UI_SURFACE_IDS.commandPaletteSearchStatus} live>
{t("search.results.empty")}
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && !vm.isSearchQuery && vm.searchState !== "loading" && vm.recentSearches.length > 0 ? (
<CommandGroup heading={t("search.command.recent")}>
{vm.recentSearches.map((recent) => (
<CommandItem
key={recent.id}
data-ui-id={getCommandPaletteRecentId(recent.id)}
data-ui-id-pattern={UI_ID_PATTERNS.commandPaletteRecent}
data-ui-id-param-recentid={recent.id}
value={recent.queryText}
onSelect={() => actions.onSelectRecent(recent)}
>
<IconWithBackground variant="secondary" size="small" icon={<FeatherClock />} className="size-8 shrink-0" />
<div className="min-w-0 grow">
<div className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary truncate">{recent.queryText}</div>
<div className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary">
{t("search.results.title", { count: recent.resultCount })}
</div>
</div>
</CommandItem>
))}
</CommandGroup>
) : null}
{vm.canUseGlobalSearch && !vm.isSearchQuery && vm.searchState !== "loading" && vm.hasResolvedResponse && vm.recentSearches.length === 0 ? (
<SearchStatus icon={<FeatherClock />} dataUiId={UI_SURFACE_IDS.commandPaletteRecentStatus}>
{t("search.recent.empty")}
</SearchStatus>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState !== "error"
? vm.searchGroups.map((group) => (
<CommandGroup key={group.entityType} heading={t(group.labelKey)}>
{group.items.map((item) => (
<CommandItem
key={item.key}
data-ui-id={getCommandPaletteResultId(item.entityType, item.id)}
data-ui-id-pattern={UI_ID_PATTERNS.commandPaletteResult}
data-ui-id-param-entitytype={item.entityType}
data-ui-id-param-entityid={item.id}
value={item.searchValue}
onPointerDownCapture={actions.onPrepareResultSelection}
onSelect={() => actions.onSelectResult(item)}
>
<IconWithBackground variant="secondary" size="small" icon={entityIcon(item.entityType)} className="size-9 shrink-0" />
<div className="min-w-0 grow">
<div className="text-body-small-medium-150 font-body-small-medium-150 text-text-neutral-primary truncate">
{highlightMatch(item.title, vm.query.trim())}
</div>
{item.subtitle ? (
<div className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary truncate">
{highlightMatch(item.subtitle, vm.query.trim())}
</div>
) : null}
</div>
{item.updatedAt ? (
<span className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary hidden shrink-0 sm:inline">
{formatters.relativeDate(item.updatedAt)}
</span>
) : null}
</CommandItem>
))}
</CommandGroup>
))
: null}
{vm.canLoadMore ? (
<div className="flex justify-center px-4 py-2">
<Button
variant="tertiary"
size="small"
iconRight={<FeatherChevronDown />}
data-ui-id={UI_ACTION_IDS.commandPaletteLoadMore}
onMouseDown={(event) => event.preventDefault()}
onClick={actions.onLoadMore}
>
{t("search.command.loadMore")}
</Button>
</div>
) : null}
{vm.canUseGlobalSearch && vm.isSearchQuery && vm.searchState !== "loading" && vm.hiddenEntityTypes.length > 0 ? (
<SearchStatus icon={<FeatherShield />} dataUiId={UI_SURFACE_IDS.commandPalettePermissionHint} subtle>
{t("search.results.hidden", {
entities: vm.hiddenEntityTypes.map((type) => t(`search.entities.${type}`)).join(", "),
})}
</SearchStatus>
) : null}
{vm.visibleActions.length > 0 ? (
<CommandGroup heading={t(vm.isSearchQuery ? "search.command.actions" : "search.command.quickAccess")}>
{vm.visibleActions.map((action) => (
<CommandItem key={action.id} {...commandActionUiIdAttrs(action.id)} value={action.searchValue} onSelect={() => actions.onSelectAction(action.id)}>
<div className="flex w-full min-w-0 items-center gap-2">
<IconWithBackground
data-slot="command-action-icon"
variant="neutral"
size="small"
icon={getActionIcon(action.id)}
className="size-7 shrink-0 p-1.5"
/>
<div className="text-text-neutral-secondary text-body-small-medium-150 font-body-small-medium-150 min-w-0 grow truncate">{action.name}</div>
{action.subtitle ? (
<div className="text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary hidden max-w-40 truncate sm:block">
{action.subtitle}
</div>
) : null}
<ChevronRightIcon className="text-icon-neutral-tertiary size-4 shrink-0 opacity-0 transition-opacity group-data-[selected=true]/command-item:opacity-100" />
</div>
</CommandItem>
))}
</CommandGroup>
) : null}
{!vm.canUseGlobalSearch && vm.visibleActions.length === 0 ? (
<SearchStatus icon={<FeatherSearch />} dataUiId={UI_SURFACE_IDS.commandPaletteSearchStatus}>
{t("app.commands.empty.title")}
</SearchStatus>
) : null}
</CommandList>
<div
className="border-border-default bg-surface-neutral-secondary text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary flex items-center justify-between gap-2 border-t px-3 py-2 sm:px-4"
data-ui-id={UI_SURFACE_IDS.commandPaletteFooter}
>
<span className="flex items-center gap-1.5">
<BadgeShortcut icon={null} size="small">
↑↓
</BadgeShortcut>
<span className="hidden sm:inline">{t("search.command.navigate")}</span>
</span>
<span className="flex items-center gap-1.5">
<BadgeShortcut icon={null} size="small">
↵
</BadgeShortcut>
<span>{t("search.command.open")}</span>
</span>
<span className="flex items-center gap-1.5">
<BadgeShortcut icon={null} size="small">
⌘↵
</BadgeShortcut>
<span className="hidden sm:inline">{t("search.command.openNewTab")}</span>
</span>
</div>
</CommandDialog>
);
}
function commandActionUiIdAttrs(actionId: string) {
return {
"data-ui-id": getCommandPaletteActionId(actionId),
"data-ui-id-pattern": UI_ID_PATTERNS.commandPaletteAction,
"data-ui-id-param-actionid": actionId,
};
}
function getActionIcon(actionId: string) {
switch (actionId) {
case "dashboard":
case "registry-dashboard":
return <HomeIcon />;
case "profile":
case "members":
return <UserIcon />;
case "subscription":
return <CreditCard />;
case "account":
return <StoreIcon />;
case "apiKeys":
return <CodeIcon />;
case "auditTrails":
case "events":
return <FileTextIcon />;
case "switch account":
return <ArrowLeftRightIcon />;
case "create account":
return <PlusIcon />;
case "switch to admin":
return <ShieldCheckIcon />;
case "logout":
return <LogOut />;
default:
return <ChevronRightIcon />;
}
}
function SearchStatus({
children,
icon,
dataUiId,
live = false,
subtle = false,
}: {
children: React.ReactNode;
icon: React.ReactNode;
dataUiId: string;
live?: boolean;
subtle?: boolean;
}) {
return (
<CommandItem disabled value={`status:${dataUiId}`} className="cursor-default p-0 data-[disabled=true]:opacity-100" data-ui-id={dataUiId}>
<div
className={
subtle
? "bg-surface-neutral-secondary text-body-extra-small-regular-0 font-body-extra-small-regular-0 text-text-neutral-tertiary mx-3 my-2 flex w-full items-center gap-2 rounded-md px-3 py-2 sm:mx-4"
: "text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary flex w-full items-center justify-center gap-2 px-4 py-5 text-center"
}
role={live ? "status" : undefined}
aria-live={live ? "polite" : undefined}
>
<span className="text-icon-neutral-tertiary shrink-0">{icon}</span>
<span>{children}</span>
</div>
</CommandItem>
);
}
function entityIcon(entityType: SpotlightSearchEntityType) {
switch (entityType) {
case "contact":
return <FeatherUser />;
case "company":
return <FeatherBuilding2 />;
case "lead":
return <FeatherTrendingUp />;
case "project":
return <FeatherFolder />;
case "file":
return <FeatherFile />;
case "task":
return <FeatherCheckSquare />;
case "employee":
return <FeatherUsers />;
case "user":
return <FeatherUsers />;
}
}
function highlightMatch(value: string, query: string) {
if (!query) return value;
const index = value.toLocaleLowerCase().indexOf(query.toLocaleLowerCase());
if (index < 0) return value;
const before = value.slice(0, index);
const match = value.slice(index, index + query.length);
const after = value.slice(index + query.length);
return (
<>
{before}
<mark className="bg-surface-feedback-subtle-warning rounded-sm px-0.5 text-inherit">{match}</mark>
{after}
</>
);
}
@@ -0,0 +1,119 @@
import { useMemo } from "react";
import { createMemoryRouter, Outlet, RouterProvider } from "react-router";
import CommandPaletteDialog from "./CommandPaletteDialog";
const rootData = {
csrf: "visual-csrf",
appConfiguration: { app: { features: {} } },
};
const appData = {
currentTenant: { id: "tenant-1", slug: "acme", name: "HiveGrid Demo" },
permissions: ["search.use", "crm.read_all", "projects.read_all"],
user: { id: "user-1", email: "visual@example.test", firstName: "Visual", lastName: "Fixture" },
myTenants: [],
allRoles: [],
myGroups: [],
isSuperUser: false,
isSuperAdmin: false,
onboardingSession: null,
};
/** Deterministic real-component fixture for the R-P11a interim pixel baseline. */
export function SpotlightSearchVisualFixture() {
const router = useMemo(
() =>
createMemoryRouter(
[
{
id: "root",
path: "/",
loader: () => rootData,
element: <Outlet />,
children: [
{
id: "routes/app.$tenant",
path: ":tenant",
loader: () => appData,
element: <Outlet />,
children: [
{
index: true,
element: <CommandPaletteDialog actions={[]} layout="app" open setOpen={() => undefined} />,
},
{
path: "search/api",
loader: ({ request }) => buildSearchResponse(request),
},
],
},
],
},
],
{ initialEntries: ["/acme"] }
),
[]
);
return <RouterProvider router={router} />;
}
function buildSearchResponse(request: Request) {
const url = new URL(request.url);
const query = url.searchParams.get("q")?.trim() ?? "";
const requestedEntityTypes = url.searchParams.getAll("type");
const limit = Number(url.searchParams.get("limit") ?? 20);
const requestId = url.searchParams.get("requestId");
return {
query,
requestedEntityTypes,
requestId,
requestKey: `${encodeURIComponent(query)}|${requestedEntityTypes.join(",") || "*"}|${limit}`,
results: query
? [
{
id: "contact-1",
entityType: "contact",
title: "Solaris GmbH",
subtitle: "info@solaris.test",
href: "/acme/contacts/contact-1",
permissionSubject: "crm.read_all",
updatedAt: null,
},
{
id: "project-1",
entityType: "project",
title: "Solardach Musterstraße",
subtitle: "P-100",
href: "/acme/projects/project-1",
permissionSubject: "projects.read_all",
updatedAt: null,
},
]
: [],
recentSearches: query
? []
: [
{
id: "recent-1",
queryText: "Wärmepumpe",
entityTypes: ["project", "task"],
resultCount: 4,
createdAt: "2026-07-12T08:00:00.000Z",
},
],
hiddenEntityTypes: ["lead", "file", "task", "user"],
latencyHint: "Suchindex-Aktualisierungen können bis zu 10 Sekunden dauern.",
} satisfies {
query: string;
requestedEntityTypes: string[];
requestId: string | null;
requestKey: string;
results: unknown[];
recentSearches: unknown[];
hiddenEntityTypes: string[];
latencyHint: string;
};
}
@@ -5,6 +5,7 @@ import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { CheckIcon, ChevronRightIcon, CircleIcon } from "~/components/ui/icons/vendor";
import { cn } from "~/lib/utils"
import { CONTEXT_MENU_MOTION_CLASS } from "~/ui/floating-motion"
function ContextMenu({
...props
@@ -86,8 +87,9 @@ function ContextMenuSubContent({
<ContextMenuPrimitive.SubContent
data-slot="context-menu-sub-content"
className={cn(
CONTEXT_MENU_MOTION_CLASS,
// Subframe DropdownMenuRoot surface layout: min-w-[192px] rounded-md p-1 shadow-lg
"bg-surface-neutral-modal text-text-neutral-primary data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[192px] origin-(--radix-context-menu-content-transform-origin) overflow-hidden rounded-md border border-border-default p-1 shadow-lg",
"bg-surface-neutral-modal text-text-neutral-primary z-50 min-w-[192px] overflow-hidden rounded-md border border-border-default p-1 shadow-lg",
className
)}
{...props}
@@ -104,8 +106,9 @@ function ContextMenuContent({
<ContextMenuPrimitive.Content
data-slot="context-menu-content"
className={cn(
CONTEXT_MENU_MOTION_CLASS,
// Subframe DropdownMenuRoot surface layout: min-w-[192px] rounded-md p-1 shadow-lg
"bg-surface-neutral-modal text-text-neutral-primary data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-context-menu-content-available-height) min-w-[192px] origin-(--radix-context-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border border-border-default p-1 shadow-lg",
"bg-surface-neutral-modal text-text-neutral-primary z-50 max-h-(--radix-context-menu-content-available-height) min-w-[192px] overflow-x-hidden overflow-y-auto rounded-md border border-border-default p-1 shadow-lg",
className
)}
{...props}
@@ -1,5 +1,5 @@
import { useState, useEffect, useMemo } from "react";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { useTranslation } from "react-i18next";
import { CalendarIcon } from "~/components/ui/icons/vendor";
import { DateRange } from "react-day-picker";
@@ -1,7 +1,7 @@
import { useEffect, useState } from "react";
import { useSearchParams } from "react-router";
import { DateRange } from "react-day-picker";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { FilterDto } from "~/components/ui/input/InputFilters";
import { DateRangeFilter, dateRangeToParams, paramsToDateRange } from "./DateRangeFilter";
@@ -1,6 +1,6 @@
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { XIcon } from "~/components/ui/icons/vendor";
import { cn } from "~/lib/utils";
@@ -38,24 +38,38 @@ function DialogContent({
className,
children,
withCloseButton = true,
overlayClassName,
closeButtonClassName,
positioning = "centered",
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & { withCloseButton?: boolean }) {
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
withCloseButton?: boolean;
overlayClassName?: string;
closeButtonClassName?: string;
positioning?: "centered" | "custom";
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogOverlay className={overlayClassName} />
<DialogPrimitive.Content
data-slot="dialog-content"
data-positioning={positioning}
className={cn(
// Subframe Dialog.Content layout: min-w 320px, rounded-md, gap-2, scrollable max-h-[90vh].
// Radix-only pieces kept: fixed centering, animations, max-width clamp, p-6, border token.
"bg-surface-neutral-modal data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid max-h-[90vh] w-full min-w-[320px] max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-2 overflow-auto rounded-md border border-solid border-border-default p-6 shadow-lg duration-200 sm:max-w-lg",
"bg-surface-neutral-modal data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 border-border-default fixed z-50 grid gap-2 overflow-auto rounded-md border border-solid p-6 shadow-lg duration-200",
positioning === "centered" &&
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 top-[50%] left-[50%] max-h-[90vh] w-full max-w-[calc(100%-2rem)] min-w-[320px] translate-x-[-50%] translate-y-[-50%] sm:max-w-lg",
className
)}
{...props}
>
{children}
{withCloseButton && (
<DialogPrimitive.Close className="data-[state=open]:bg-surface-neutral-secondary data-[state=open]:text-text-neutral-tertiary absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus-visible:shadow-focus focus-visible:border-brand-brand-border-solid-default focus-visible:outline-none disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4">
<DialogPrimitive.Close
className={cn(
"data-[state=open]:bg-surface-neutral-secondary data-[state=open]:text-text-neutral-tertiary focus-visible:shadow-focus focus-visible:border-brand-brand-border-solid-default absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus-visible:outline-none disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
closeButtonClassName
)}
>
<XIcon />
<span className="sr-only">{i18nT("shared.close")}</span>
</DialogPrimitive.Close>
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import CheckIcon from "../icons/CheckIcon";
import XIcon from "../icons/XIcon";
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { Link } from "react-router";
interface Props {
@@ -1,5 +1,5 @@
import { Fragment, useState } from "react";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "../sheet";
import { Button } from "../button";
import Logo from "~/components/brand/Logo";
@@ -1,5 +1,5 @@
import PreviewDropdownsSimple from "./PreviewDropdownsSimple";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import PreviewDropdownsWithClick from "./PreviewDropdownsWithClick";
export default function PreviewDropdowns() {
@@ -1,6 +1,6 @@
import { Link, useLocation } from "react-router";
import { Menu } from "@headlessui/react";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import clsx from "clsx";
import Dropdown from "./Dropdown";
@@ -1,5 +1,5 @@
import { Link, useLocation } from "react-router";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { Menu } from "@headlessui/react";
import clsx from "clsx";
import DropdownWithClick from "./DropdownWithClick";
@@ -1,6 +1,3 @@
import ButtonSecondary from "../buttons/ButtonSecondary";
import IconEmptyResults from "~/components/ui/icons/IconEmptyResults";
import clsx from "clsx";
import { cn } from "~/lib/utils";
export default function EmptyStateSimple({ children, className }: { children: React.ReactNode; className?: string }) {
@@ -1,5 +1,5 @@
import { useLocation } from "react-router";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import EmptyState from "./EmptyState";
export default function PreviewEmptyStates() {
@@ -38,7 +38,7 @@ vi.mock("react-i18next", () => ({
}),
}));
vi.mock("~/components/brand/Logo", () => ({ default: () => <div data-testid="logo">Logo</div> }));
vi.mock("~/ui/components/Logo", () => ({ Logo: () => <div data-testid="logo">Logo</div> }));
vi.mock("~/components/public/PublicFooter", () => ({ default: () => <footer data-testid="public-footer">Footer</footer> }));
describe("ErrorPage a11y", () => {
@@ -50,7 +50,7 @@ vi.mock("react-i18next", () => ({
}),
}));
vi.mock("~/components/brand/Logo", () => ({ default: () => <div data-testid="logo">Logo</div> }));
vi.mock("~/ui/components/Logo", () => ({ Logo: () => <div data-testid="logo">Logo</div> }));
vi.mock("~/components/public/PublicFooter", () => ({ default: () => <footer data-testid="public-footer">Footer</footer> }));
function renderErrorPage(status: ErrorStatus, props: Partial<React.ComponentProps<typeof ErrorPage>> = {}) {
@@ -74,9 +74,17 @@ describe("ErrorPage", () => {
expect(screen.getByRole("heading", { name: copy.title })).toBeInTheDocument();
expect(screen.getByText(copy.description)).toBeInTheDocument();
expect(screen.getByTestId("logo")).toBeInTheDocument();
expect(screen.getByTestId("error-page-logo")).toHaveAttribute("href", "/");
expect(screen.getByTestId("public-footer")).toBeInTheDocument();
});
it("keeps long error copy inside a constrained content column", () => {
renderErrorPage(500);
expect(screen.getByRole("heading", { name: expectedErrorCopy[500].title }).parentElement).toHaveClass("max-w-2xl");
expect(screen.getByText(expectedErrorCopy[500].description)).toHaveClass("max-w-xl");
});
it("omits footer and back controls when disabled", () => {
renderErrorPage(404, { withFooter: false, withGoBack: false });
@@ -1,7 +1,7 @@
import { useNavigate } from "react-router";
import { Link, useNavigate } from "react-router";
import { useTranslation } from "react-i18next";
import Logo from "~/components/brand/Logo";
import PublicFooter from "~/components/public/PublicFooter";
import { Logo } from "~/ui/components/Logo";
export type ErrorStatus = 401 | 403 | 404 | 500 | 503;
@@ -72,40 +72,37 @@ export function ErrorPage({
const resolvedEyebrow = eyebrow ?? t(preset.eyebrowKey);
const resolvedTitle = title ?? t(preset.titleKey);
const resolvedDescription = description ?? t(preset.descriptionKey);
const logoLabel = t("shared.logo", { ns: "translations" });
return (
<>
<div className="" data-error-status={status} data-testid="error-page">
<div className="flex min-h-full flex-col pt-16 pb-12">
<main className="mx-auto flex w-full max-w-7xl min-w-0 grow flex-col justify-center px-4 sm:px-6 lg:px-8">
{withLogo && (
<div className="flex shrink-0 justify-center">
{logo ? <img className="h-9 w-auto" src={logo} alt={t("shared.logo", { ns: "translations" })} /> : <Logo />}
<div className="flex min-h-screen flex-col" data-error-status={status} data-testid="error-page">
<main className="mx-auto flex w-full max-w-3xl min-w-0 grow flex-col items-center justify-center px-4 py-16 sm:px-6 lg:px-8">
{withLogo && (
<Link to="/" aria-label={logoLabel} className="flex shrink-0 justify-center" data-testid="error-page-logo">
{logo ? <img className="h-8 max-w-[min(16rem,80vw)] w-auto object-contain" src={logo} alt={logoLabel} /> : <Logo size="32" />}
</Link>
)}
<div className="w-full py-12 sm:py-16">
<div className="mx-auto min-w-0 max-w-2xl text-center [overflow-wrap:anywhere]">
<p className="text-brand-brand-surface-solid-default text-sm font-semibold tracking-wide uppercase">{resolvedEyebrow}</p>
<h1 className="mt-2 text-3xl font-extrabold tracking-tight sm:text-5xl">{resolvedTitle}</h1>
<p className="text-text-neutral-tertiary mx-auto mt-3 max-w-xl text-base leading-6">{resolvedDescription}</p>
{(withGoBack || customBackButton || actionSlot) && (
<div className="mt-6 min-w-0">
{customBackButton}
{!customBackButton && withGoBack && (
<button type="button" onClick={() => navigate(-1)} className="text-brand-brand-surface-solid-default hover:text-brand-brand-surface-solid-hover w-full text-center text-sm font-medium">
<span aria-hidden="true"> &larr;</span> {t("goBack")}
</button>
)}
{actionSlot}
</div>
)}
<div className="py-16">
<div className="min-w-0 text-center [overflow-wrap:anywhere]">
<p className="text-brand-brand-surface-solid-default text-sm font-semibold tracking-wide uppercase">{resolvedEyebrow}</p>
<h1 className="mt-2 text-4xl font-extrabold tracking-tight sm:text-5xl">{resolvedTitle}</h1>
<p className="text-text-neutral-tertiary mt-2 text-base">{resolvedDescription}</p>
{(withGoBack || customBackButton || actionSlot) && (
<div className="mt-4 min-w-0">
{customBackButton}
{!customBackButton && withGoBack && (
<button type="button" onClick={() => navigate(-1)} className="text-brand-brand-surface-solid-default hover:text-brand-brand-surface-solid-hover w-full text-center text-sm font-medium">
<span aria-hidden="true"> &larr;</span> {t("goBack")}
</button>
)}
{actionSlot}
</div>
)}
{diagnosticChildren && <div className="mt-6 text-left">{diagnosticChildren}</div>}
</div>
</div>
</main>
{diagnosticChildren && <div className="mt-6 text-left">{diagnosticChildren}</div>}
</div>
</div>
</div>
</main>
{withFooter && <PublicFooter />}
</>
</div>
);
}
@@ -55,7 +55,7 @@ vi.mock("i18next", () => ({
t: (key: string) => errorMessages[key] ?? key,
}));
vi.mock("~/components/brand/Logo", () => ({ default: () => <div data-testid="logo">Logo</div> }));
vi.mock("~/ui/components/Logo", () => ({ Logo: () => <div data-testid="logo">Logo</div> }));
vi.mock("~/components/public/PublicFooter", () => ({ default: () => <footer data-testid="public-footer">Footer</footer> }));
function renderServerError(error: unknown) {
@@ -1,5 +1,5 @@
import { isRouteErrorResponse, useRouteError } from "react-router";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { ErrorPage, type ErrorStatus } from "~/components/ui/errors/ErrorPage";
type KnownErrorCopy = { title: string; description?: string };
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
export default function HoneypotInput({ name = "codeId" }: { name?: string }) {
return (
@@ -1,7 +1,7 @@
import "@testing-library/jest-dom";
import { render, screen } from "@testing-library/react";
import { describe, expect, it } from "vitest";
import { createHotSwapDrillPage } from "@hivegrid/ui-mock";
import { createHotSwapDrillPage, translateMockText } from "@hivegrid/ui-mock";
import { HotSwapPageRenderer } from "./HotSwapPageRenderer";
describe("HotSwapPageRenderer", () => {
@@ -45,12 +45,13 @@ describe("HotSwapPageRenderer", () => {
expect(activityItems.length).toBe(descriptor.state.data?.activity.length ?? 0);
});
it("renders the label keys from the descriptor as text nodes", () => {
it("renders translated descriptor labels instead of literal keys", () => {
const descriptor = createHotSwapDrillPage();
render(<HotSwapPageRenderer descriptor={descriptor} />);
// The renderer surfaces translation keys verbatim so the i18n layer can hydrate them later.
expect(screen.getByText(descriptor.titleKey!)).toBeInTheDocument();
expect(screen.getByText(descriptor.descriptionKey!)).toBeInTheDocument();
expect(screen.getByText(translateMockText(descriptor.titleKey!))).toBeInTheDocument();
expect(screen.getByText(translateMockText(descriptor.descriptionKey!))).toBeInTheDocument();
expect(screen.queryByText(descriptor.titleKey!)).not.toBeInTheDocument();
expect(screen.queryByText(descriptor.descriptionKey!)).not.toBeInTheDocument();
});
});
@@ -1,6 +1,6 @@
import type { ReactElement } from "react";
import { createShellRegistries } from "@hivegrid/ui-app";
import type { HotSwapDrillData, MockPage } from "@hivegrid/ui-mock";
import { translateMockText, type HotSwapDrillData, type MockPage } from "@hivegrid/ui-mock";
export type HotSwapPageRendererProps = {
readonly descriptor: MockPage<HotSwapDrillData>;
@@ -30,27 +30,27 @@ export function HotSwapPageRenderer({ descriptor }: HotSwapPageRendererProps): R
data-mobile-count={registries.mobile.length}
data-portal-count={registries.portals.length}
>
<nav data-section="sidebar" aria-label={titleKey}>
<nav data-section="sidebar" aria-label={translateMockText(titleKey)}>
<ul>
{registries.sidebar.map((item) => (
<li key={item.id} data-sidebar-id={item.id}>
<a href={item.href} data-label-key={item.labelKey}>
{item.labelKey}
{translateMockText(item.labelKey)}
</a>
</li>
))}
</ul>
</nav>
<ol data-section="breadcrumbs" aria-label={`${descriptor.id}.breadcrumbs`}>
<ol data-section="breadcrumbs" aria-label={translateMockText("mock.ui.breadcrumbsAria", "Breadcrumbs")}>
{registries.breadcrumbs.map((item) => (
<li key={item.id} data-breadcrumb-id={item.id} data-label-key={item.labelKey}>
{item.labelKey}
{translateMockText(item.labelKey)}
</li>
))}
</ol>
<header data-section="header">
<h1 data-label-key={titleKey}>{titleKey}</h1>
<p data-label-key={descriptionKey}>{descriptionKey}</p>
<h1 data-label-key={titleKey}>{translateMockText(titleKey, descriptor.title)}</h1>
<p data-label-key={descriptionKey}>{translateMockText(descriptionKey, descriptor.description)}</p>
</header>
<section data-section="cards" aria-label={`${descriptor.id}.cards`}>
{(data?.cards ?? []).map((card, index) => (
@@ -60,7 +60,7 @@ export function HotSwapPageRenderer({ descriptor }: HotSwapPageRendererProps): R
data-label-key={card.labelKey}
>
<p data-card-label data-label-key={card.labelKey}>
{card.labelKey}
{translateMockText(card.labelKey)}
</p>
<p data-card-value>{card.value}</p>
</article>
@@ -70,7 +70,7 @@ export function HotSwapPageRenderer({ descriptor }: HotSwapPageRendererProps): R
<ul>
{(data?.activity ?? []).map((entry, index) => (
<li key={`${entry.labelKey}-${index}`} data-label-key={entry.labelKey}>
<span data-label-key={entry.labelKey}>{entry.labelKey}</span>
<span data-label-key={entry.labelKey}>{translateMockText(entry.labelKey)}</span>
<span data-meta>{entry.meta}</span>
</li>
))}
@@ -0,0 +1,5 @@
import { FeatherCalendarCheck } from "@subframe/core"
import { featherIcon } from "./_feather"
export default featherIcon(FeatherCalendarCheck)
@@ -0,0 +1,5 @@
import { FeatherCalendarClock } from "@subframe/core"
import { featherIcon } from "./_feather"
export default featherIcon(FeatherCalendarClock)
@@ -0,0 +1,5 @@
import { FeatherCalendarDays } from "@subframe/core"
import { featherIcon } from "./_feather"
export default featherIcon(FeatherCalendarDays)
@@ -0,0 +1,5 @@
import { FeatherCalendarRange } from "@subframe/core"
import { featherIcon } from "./_feather"
export default featherIcon(FeatherCalendarRange)
@@ -1,5 +0,0 @@
import { FeatherBot } from "@subframe/core"
import { featherIcon } from "../_feather"
export default featherIcon(FeatherBot)
@@ -69,11 +69,11 @@ const InputCombobox = (
help,
hint,
icon,
borderless,
borderless: _borderless,
darkMode,
autoFocus,
readOnly,
renderHiddenInputValue,
renderHiddenInputValue: _renderHiddenInputValue,
prefix,
onClear,
minDisplayCount = 3,
@@ -1,6 +1,5 @@
import * as React from "react";
import { t as i18nT } from "i18next";
import { parse } from "date-fns";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { CalendarIcon, ChevronDownIcon, XIcon } from "~/components/ui/icons/vendor";
import { Button } from "../button";
import { Popover, PopoverContent, PopoverTrigger } from "../popover";
@@ -32,12 +31,12 @@ export function InputDatePickerDeprecated({
name,
date,
setDate,
dirty,
dirty: _dirty,
canClear = true,
className,
closeOnSelect = false,
showInput = false,
placeholder,
showInput: _showInput = false,
placeholder: _placeholder,
required,
disabled,
autoFocus,
@@ -58,7 +57,7 @@ export function InputDatePickerDeprecated({
if (!isNaN(parsedDate.getTime())) {
setInputValue(parsedDate.toISOString().split("T")[0]);
}
} catch (e) {
} catch (_e) {
console.error("Invalid date:", date);
}
} else {
@@ -88,7 +87,7 @@ export function InputDatePickerDeprecated({
if (!isNaN(parsedDate.getTime())) {
return formatters.date(parsedDate, { dateStyle: "long" });
}
} catch (e) {
} catch (_e) {
console.error("Invalid date:", date);
}
return null;
@@ -1,4 +1,3 @@
import { Transition } from "@headlessui/react";
import clsx from "clsx";
import { FormEvent, Fragment, useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
@@ -12,9 +11,8 @@ import InputSearch from "./InputSearch";
import InputSelect from "./InputSelect";
import { Input } from "../input";
import { Button } from "../button";
import { cn } from "~/lib/utils";
import { Button as UiButton } from "~/ui/components/Button";
import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover";
import { PopoverClose } from "@radix-ui/react-popover";
import { translateLabel } from "~/utils/i18n/translateLabel";
// import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "../dropdown-menu";
@@ -144,7 +142,7 @@ export default function InputFilters({ filters, withSearch = true, size = "defau
<Fragment>
<Popover open={opened} onOpenChange={setOpened}>
<PopoverTrigger asChild>
<Button type="button" aria-label={t("shared.filters")} size={size} onClick={() => setOpened(!opened)} variant="outline" className="relative z-0 inline-flex shrink-0 gap-2">
<Button type="button" aria-label={t("shared.filters")} size={size} variant="outline" className="relative z-0 inline-flex shrink-0 gap-2">
<div className={clsx("relative inline-flex items-center gap-2", filteredItems === 0 ? "rounded-md" : "rounded-l-md")}>
<div>
{filteredItems === 0 && <FilterEmptyIcon className="h-3 w-3" />}
@@ -164,23 +162,18 @@ export default function InputFilters({ filters, withSearch = true, size = "defau
)}
</Button>
</PopoverTrigger>
<PopoverContent className="p-0">
<Form
onSubmit={onSubmit}
method="get"
className={cn(
"bg-surface-neutral-primary divide-border-default ring-opacity-5 z-40 divide-y rounded-md shadow-2xl ring-1 ring-black focus:outline-none",
position === "right" ? "right-0" : "left-0"
)}
>
<div className="flex items-center justify-between px-2 py-2 text-sm">
<Button type="button" variant="outline" onClick={onClear}>
{t("shared.reset")}
</Button>
<div className="font-bold">{t("shared.filters")}</div>
<Button type="submit" variant="outline">
{t("shared.apply")}
</Button>
<PopoverContent className="w-80 p-0" align={position === "right" ? "end" : "start"} collisionPadding={8}>
<Form onSubmit={onSubmit} method="get" className="divide-border-default divide-y rounded-md">
<div className="flex items-center justify-between gap-2 px-3 py-2 text-sm">
<div className="font-medium">{t("shared.filters")}</div>
<div className="flex shrink-0 items-center gap-2">
<UiButton type="button" variant="tertiary" size="small" onClick={onClear}>
{t("shared.reset")}
</UiButton>
<UiButton type="submit" size="small">
{t("shared.apply")}
</UiButton>
</div>
</div>
<div className="bg-surface-neutral-primary divide-border-default divide-y rounded-b-md text-sm">
{withSearch && (
@@ -190,8 +183,8 @@ export default function InputFilters({ filters, withSearch = true, size = "defau
)}
{items.map((filter, idx) => {
return (
<div key={filter.name} className="divide-border divide-y">
<div className="divide-y divide-gray-300 px-2 py-2">
<div key={filter.name} className="divide-border-default divide-y">
<div className="px-2 py-2">
<InputCheckboxInline
name={"filter-" + filter.name}
title={translateLabel(t, i18n, filter.title)}
@@ -27,7 +27,7 @@ type Props = (WithDefaultValue | WithValueAndSetValue) & {
description?: string;
className?: string;
};
const InputImage = (props: Props, ref: Ref<RefInputImage>) => {
const InputImage = (props: Props, _ref: Ref<RefInputImage>) => {
const value = "value" in props ? props.value : undefined;
const setValue = "setValue" in props ? props.setValue : undefined;
const defaultValue = "defaultValue" in props ? props.defaultValue : undefined;
@@ -48,7 +48,7 @@ const InputMultiText = (
withLabel = true,
value,
className,
classNameBg,
classNameBg: _classNameBg,
help,
disabled = false,
readOnly = false,
@@ -59,14 +59,14 @@ const InputMultiText = (
placeholder,
pattern,
hint,
rows,
rows: _rows,
button,
lowercase,
uppercase,
darkMode,
icon,
onBlur,
borderless,
borderless: _borderless,
autoFocus,
separator = ",",
}: Props,
@@ -1,9 +1,8 @@
import React, { useState, useRef, useEffect, KeyboardEvent, ReactNode, RefObject, Ref, forwardRef, useImperativeHandle } from "react";
import React, { useState, useRef, KeyboardEvent, ReactNode, RefObject, Ref, forwardRef, useImperativeHandle } from "react";
import clsx from "clsx";
import HintTooltip from "../tooltips/HintTooltip";
import EntityIcon from "~/components/layouts/icons/EntityIcon";
import { useTranslation } from "react-i18next";
import { RowValueMultipleDto } from "~/application/dtos/entities/RowValueMultipleDto";
import { SeparatorFormatType } from "~/utils/shared/SeparatorUtils";
import { Input } from "../input";
@@ -50,7 +49,7 @@ const InputMultipleText = (
value,
onChange,
className,
classNameBg,
classNameBg: _classNameBg,
help,
disabled = false,
readOnly = false,
@@ -61,14 +60,14 @@ const InputMultipleText = (
placeholder,
pattern,
hint,
rows,
rows: _rows,
button,
lowercase,
uppercase,
darkMode,
icon,
onBlur,
borderless,
borderless: _borderless,
autoFocus,
separator = ",",
}: Props,
@@ -7,7 +7,7 @@ import Color from "@tiptap/extension-color";
import { createTiptapEditorProps } from "~/modules/novel/ui/editor/props";
import { createTiptapExtensions } from "~/modules/novel/ui/editor/extensions";
import { cn } from "~/lib/utils";
import { useRootData } from "~/utils/data/useRootData";
import { sanitizeMarkedHtml } from "~/utils/html-sanitizer";
function MenuBar({ editor, disabled }: { editor: Editor | null; disabled?: boolean }) {
const { t } = useTranslation();
@@ -232,18 +232,16 @@ export interface InputRichTextEditorClientProps {
style?: React.CSSProperties;
}
export default function InputRichTextEditorClient({ content, onChange, disabled, className, dirty, placeholder, required, style }: InputRichTextEditorClientProps) {
const rootData = useRootData();
export default function InputRichTextEditorClient({ content, onChange, disabled, className, dirty, placeholder: _placeholder, required, style }: InputRichTextEditorClientProps) {
const [hydrated, setHydrated] = useState(false);
const imageUploadOptions = useMemo(() => ({ apiBaseUrl: rootData.apiBaseUrl, tenantId: rootData.currentTenant?.id ?? null }), [rootData.apiBaseUrl, rootData.currentTenant?.id]);
const extensions: Extensions = useMemo(
() => [
...createTiptapExtensions(imageUploadOptions),
...createTiptapExtensions(),
Color.configure({ types: ["textStyle"] }), // enables color
],
[imageUploadOptions]
[]
);
const editorProps = useMemo(() => createTiptapEditorProps(imageUploadOptions), [imageUploadOptions]);
const editorProps = useMemo(() => createTiptapEditorProps(), []);
const debouncedUpdates = useCallback(
({ editor }: { editor: Editor }) => {
@@ -308,7 +306,7 @@ export default function InputRichTextEditorClient({ content, onChange, disabled,
>
{disabled ? (
<div className="cursor-not-allowed">
<div dangerouslySetInnerHTML={{ __html: editor?.getHTML() || "" }} />
<div dangerouslySetInnerHTML={{ __html: sanitizeMarkedHtml(editor?.getHTML()) }} />
</div>
) : (
<EditorContent editor={editor} disabled={disabled} required={required} />
@@ -37,6 +37,8 @@ interface Props {
style?: React.CSSProperties;
hideIcon?: boolean;
icon?: React.ReactNode;
triggerAriaLabel?: string;
highContrastText?: boolean;
}
export default function InputSelect({
name,
@@ -62,6 +64,8 @@ export default function InputSelect({
style,
icon,
hideIcon = false,
triggerAriaLabel,
highContrastText = false,
}: Props) {
const { t } = useTranslation();
const refSearch = useRef<HTMLInputElement>(null);
@@ -132,6 +136,8 @@ export default function InputSelect({
label={labelContent}
icon={!hideIcon ? icon : undefined}
placeholder={getPlaceholder()}
triggerAriaLabel={triggerAriaLabel}
highContrastText={highContrastText}
>
{withSearch && options.length > 30 && (
<Input
@@ -15,5 +15,6 @@ describe("Lazy rich text editor boundary", () => {
expect(clientSource).toContain("@tiptap/react");
expect(clientSource).toContain("@tiptap/extension-color");
expect(clientSource).toContain("sanitizeMarkedHtml(editor?.getHTML())");
});
});
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { Switch } from "~/ui/components/Switch";
// Subframe migration (strangler shim):
@@ -241,7 +241,7 @@ const InputSelectorDarkMode = (
}
value={group}
>
{({ selected, active }) => (
{({ selected, active: _active }) => (
<Fragment>
<span className={clsx("text-muted-foreground text-xs font-medium", selected ? "font-semibold" : "font-normal")}>{group.name}</span>
</Fragment>
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputText from "../InputText";
export default function PreviewInputText() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputCheckbox from "~/components/ui/input/InputCheckbox";
export default function PreviewInputCheckbox() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { useState } from "react";
import InputCheckboxCards from "../../InputCheckboxCards";
@@ -1,5 +1,5 @@
import { useState } from "react";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputCheckbox from "~/components/ui/input/InputCheckbox";
export default function PreviewInputCheckboxWithState() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputDate from "~/components/ui/input/InputDate";
export default function PreviewInputDate() {
@@ -1,5 +1,5 @@
import { useState } from "react";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputDate from "~/components/ui/input/InputDate";
export default function PreviewInputDateWithState() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputNumber from "~/components/ui/input/InputNumber";
export default function PreviewInputNumber() {
@@ -1,5 +1,5 @@
import { useState } from "react";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputNumber from "~/components/ui/input/InputNumber";
export default function PreviewInputNumberWithAllOptions() {
@@ -1,5 +1,5 @@
import InputNumber from "~/components/ui/input/InputNumber";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
export default function PreviewInputNumberWithHintAndHelp() {
return (
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputRadioGroup from "~/components/ui/input/InputRadioGroup";
export default function PreviewInputRadioGroup() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputRadioGroupCards from "../../InputRadioGroupCards";
export default function PreviewInputRadioGroupCards() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { useState } from "react";
import InputRadioGroup from "~/components/ui/input/InputRadioGroup";
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputCombobox from "../../InputCombobox";
export default function PreviewInputCombobox() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputSelect from "~/components/ui/input/InputSelect";
export default function PreviewInputSelect() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { useState } from "react";
import InputSelect from "~/components/ui/input/InputSelect";
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputSelector from "~/components/ui/input/InputSelector";
export default function PreviewInputSelector() {
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import { useState } from "react";
import InputSelector from "~/components/ui/input/InputSelector";
@@ -1,5 +1,5 @@
import InputMultiText from "../../InputMultiText";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
export default function PreviewInputMultiText() {
return (
@@ -1,4 +1,4 @@
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputText from "~/components/ui/input/InputText";
export default function PreviewInputText() {
@@ -1,5 +1,5 @@
import { useState } from "react";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputText from "~/components/ui/input/InputText";
export default function PreviewInputTextWithAllOptions() {
@@ -1,5 +1,5 @@
import InputText from "~/components/ui/input/InputText";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
export default function PreviewInputTextWithHint() {
return (
@@ -15,7 +15,7 @@ export default function PreviewInputTextWithMonacoEditor() {
_Image_:
![Example](https://placehold.co/1200x630?text=${encodeURIComponent(t("shared.preview"))})
![${t("shared.preview")}](\/images\/placeholder.svg)
`
);
return (
@@ -1,5 +1,5 @@
import { useState } from "react";
import { t as i18nT } from "i18next";
import { requestScopedT as i18nT } from "~/locale/request-scoped-t";
import InputText from "~/components/ui/input/InputText";
export default function PreviewInputTextWithTranslation() {
@@ -50,7 +50,7 @@ export default function InputRangeNumber({
step,
placeholder,
icon,
borderless,
borderless: _borderless,
autoFocus,
}: Props) {
const { t } = useTranslation();
@@ -46,7 +46,7 @@ const InputEmail = (
value,
setValue,
className,
classNameBg,
classNameBg: _classNameBg,
help,
disabled = false,
readOnly = false,
@@ -62,7 +62,7 @@ const InputEmail = (
type = "email",
darkMode,
onBlur,
borderless,
borderless: _borderless,
autoFocus,
}: Props,
ref: Ref<RefInputEmail>
@@ -45,12 +45,12 @@ export default function InputPhone({
value,
setValue,
className,
classNameBg,
classNameBg: _classNameBg,
help,
disabled = false,
readOnly = false,
required = false,
minLength,
minLength: _minLength,
maxLength,
placeholder,
pattern,
@@ -61,7 +61,7 @@ export default function InputPhone({
type = "text",
darkMode,
onBlur,
borderless,
borderless: _borderless,
autoFocus,
}: Props) {
// useImperativeHandle(ref, () => ({ input }));
@@ -67,7 +67,7 @@ export function InputPhoneWithMaskControlled({
value,
onChange,
className = "",
placeholder = "",
placeholder: _placeholder = "",
required = false,
dirty = false,
style,
@@ -4,7 +4,6 @@ import * as React from "react";
import { OTPInput, OTPInputContext } from "input-otp";
import { Label } from "~/components/ui/label";
import { cn } from "~/lib/utils";
import { inputVariants } from "../../input";
interface InputTimeProps {
name?: string;
@@ -52,7 +51,7 @@ function TimeSlot({
);
}
export function InputTime({ name, value = "", onChange, required = false, disabled = false, style, label, description, format = "HH:MM:SS" }: InputTimeProps) {
export function InputTime({ name: _name, value = "", onChange, required = false, disabled = false, style, label, description, format = "HH:MM:SS" }: InputTimeProps) {
const maxLength = format === "HH:MM" ? 4 : 6;
// Convert value to OTP format (remove colons)
@@ -52,7 +52,7 @@ const InputUrl = (
value,
setValue,
className,
classNameBg,
classNameBg: _classNameBg,
help,
disabled = false,
readOnly = false,
@@ -65,14 +65,14 @@ const InputUrl = (
placeholder,
pattern,
hint,
rows,
rows: _rows,
button,
lowercase,
uppercase,
type = "text",
darkMode,
onBlur,
borderless,
borderless: _borderless,
autoFocus,
}: Props,
ref: Ref<RefInputUrl>
@@ -1,8 +1,7 @@
import clsx from "clsx";
import { ReactNode, useState } from "react";
import Modal from "../modals/Modal";
import ModalOrSlide from "../modals/ModalOrSlide";
import { Button, buttonVariants } from "../button";
import { Button } from "../button";
interface Props {
title: ReactNode;
@@ -21,7 +20,7 @@ interface Props {
export default function ShowModalButton({
title,
children,
className = "sm:max-w-md",
className: _className = "sm:max-w-md",
type = "modal",
size = "lg",
buttons,
@@ -2,7 +2,7 @@ import { useState } from "react";
import { useTranslation } from "react-i18next";
import Modal from "../modals/Modal";
import clsx from "clsx";
import toast from "react-hot-toast";
import { useCopyToast } from "~/hooks/use-copy-toast";
export default function ShowPayloadModalButton({
payload,
@@ -21,6 +21,7 @@ export default function ShowPayloadModalButton({
}) {
const { t } = useTranslation();
const [open, setOpen] = useState(false);
const copyText = useCopyToast();
function stringifyDetails() {
if (typeof payload === "string") {
@@ -28,7 +29,7 @@ export default function ShowPayloadModalButton({
}
try {
return JSON.stringify(JSON.parse(payload ?? "{}"), null, "\t");
} catch (e) {
} catch (_e) {
return JSON.stringify(payload, null, "\t");
}
}
@@ -54,10 +55,7 @@ export default function ShowPayloadModalButton({
{withCopy && (
<button
type="button"
onClick={() => {
navigator.clipboard.writeText(stringifyDetails());
toast.success(t("shared.copied"));
}}
onClick={() => void copyText(stringifyDetails(), { successKey: "shared.copyToast.jsonCopied" })}
className="bg-theme-100 text-theme-700 hover:bg-theme-200 focus:shadow-focus inline-flex items-center rounded-md border border-transparent px-3 py-2 text-sm font-medium leading-4 focus:outline-hidden"
>
{t("shared.copy")}
@@ -0,0 +1,164 @@
import { fireEvent, render, screen } from "@testing-library/react";
import type { ReactNode } from "react";
import { describe, expect, it, vi } from "vitest";
import { SortableKanbanBoard } from "./SortableKanbanBoard";
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
vi.mock("@dnd-kit/core", () => ({
DndContext: ({ children }: { children: ReactNode }) => <>{children}</>,
DragOverlay: () => null,
KeyboardSensor: class KeyboardSensor {},
PointerSensor: class PointerSensor {},
closestCorners: vi.fn(),
useDroppable: () => ({ setNodeRef: vi.fn(), isOver: false }),
useSensor: vi.fn(() => ({})),
useSensors: vi.fn(() => []),
}));
vi.mock("@dnd-kit/sortable", () => ({
SortableContext: ({ children }: { children: ReactNode }) => <>{children}</>,
sortableKeyboardCoordinates: vi.fn(),
useSortable: () => ({
attributes: {},
listeners: {},
setNodeRef: vi.fn(),
setActivatorNodeRef: vi.fn(),
transform: null,
transition: undefined,
isDragging: false,
}),
verticalListSortingStrategy: {},
}));
vi.mock("@dnd-kit/utilities", () => ({
CSS: { Transform: { toString: () => undefined } },
}));
type Card = { id: string; name: string; href: string };
const card: Card = { id: "p1", name: "Dach Nord", href: "/acme/projects/p1" };
function renderBoard(options: { placement?: "above" | "inline"; onTitleClick?: () => void } = {}) {
const onCardMove = vi.fn();
render(
<SortableKanbanBoard<Card>
columns={[{ id: "new", name: "Neu", cards: [card] }]}
renderCard={(item, dragHandle) => (
<div data-testid={`card-${item.id}`}>
{dragHandle}
<a
href={item.href}
onClick={(event) => {
event.preventDefault();
options.onTitleClick?.();
}}
>
{item.name}
</a>
</div>
)}
getCardLabel={(item) => item.name}
onCardMove={onCardMove}
dragHandlePlacement={options.placement}
/>,
);
return onCardMove;
}
describe("SortableKanbanBoard drag handle", () => {
it("puts a visible keyboard handle inside the card without intercepting its title link", () => {
const onTitleClick = vi.fn();
const onCardMove = renderBoard({ placement: "inline", onTitleClick });
// The handle used to be an invisible strip — the only place a pointer drag
// could start, which made the cards look undraggable. Pointer dragging now
// works on the whole tile; the handle stays as the keyboard activator and is
// visible so it can be found and focused.
const handle = screen.getByRole("button", { name: "kanban.dnd.reorderAria" });
expect(screen.getByTestId("card-p1").contains(handle)).toBe(true);
expect(handle.textContent).toBe("⋮⋮");
const title = screen.getByRole("link", { name: "Dach Nord" });
expect(title.getAttribute("href")).toBe("/acme/projects/p1");
fireEvent.click(title);
expect(onTitleClick).toHaveBeenCalledTimes(1);
expect(onCardMove).not.toHaveBeenCalled();
});
it("makes the whole card the pointer drag surface, not just the handle", () => {
renderBoard({ placement: "inline" });
const card = screen.getByTestId("card-p1");
// The wrapper carrying the dnd-kit pointer listeners is the card's own box.
const surface = card.closest("[data-card-id]")?.querySelector(".cursor-grab");
expect(surface).toBeTruthy();
expect(surface?.contains(card)).toBe(true);
});
it("keeps the existing visible handle above cards unless inline placement is requested", () => {
renderBoard();
const handle = screen.getByRole("button", { name: "kanban.dnd.reorderAria" });
expect(screen.getByTestId("card-p1").contains(handle)).toBe(false);
expect(screen.getByText("⋮⋮")).toBeTruthy();
});
});
describe("SortableKanbanBoard column forwarding", () => {
function renderColumns(column: { sumMode?: "visible" | "locked" | "hidden"; twoColumn?: boolean; wrapAfter?: number; accentColor?: string }) {
render(
<SortableKanbanBoard<Card>
columns={[{ id: "new", name: "Neu", price: "10.000,00 €", lockedSumSlot: "projects.board.sumLocked", cards: [card], ...column }]}
renderCard={(item) => <div data-testid={`card-${item.id}`}>{item.name}</div>}
getCardLabel={(item) => item.name}
onCardMove={vi.fn()}
data-ui-id="board"
/>,
);
}
it("forwards visible sum mode so the column shows its sum", () => {
renderColumns({ sumMode: "visible" });
expect(screen.getByText("10.000,00 €").className.split(" ")).toContain("inline");
expect(screen.getByText("10.000,00 €").className.split(" ")).not.toContain("hidden");
expect(screen.queryByText("projects.board.sumLocked")).toBeNull();
});
it("renders caller-provided locked copy only in locked mode", () => {
renderColumns({ sumMode: "locked" });
expect(screen.getByText("10.000,00 €").className.split(" ")).toContain("hidden");
expect(screen.getByText("projects.board.sumLocked")).toBeTruthy();
});
it("shows neither sum nor lock hint in hidden mode", () => {
renderColumns({ sumMode: "hidden" });
expect(screen.getByText("10.000,00 €").className.split(" ")).toContain("hidden");
expect(screen.queryByText("projects.board.sumLocked")).toBeNull();
});
it("forwards twoColumn/wrapAfter so the column widens into the two-column grid", () => {
renderColumns({ twoColumn: true, wrapAfter: 6 });
const column = document.querySelector("[data-ui-id='kanban.column.new']") as HTMLElement;
expect(column.className).toContain("w-[680px]");
});
it("keeps the single-column width without twoColumn", () => {
renderColumns({});
const column = document.querySelector("[data-ui-id='kanban.column.new']") as HTMLElement;
expect(column.className).not.toContain("w-[680px]");
});
it("tints the column with the stage accent color at low alpha", () => {
renderColumns({ accentColor: "#3b82f6" });
const column = document.querySelector("[data-ui-id='kanban.column.new']") as HTMLElement;
expect(column.style.backgroundColor).toBe("rgba(59, 130, 246, 0.1)");
});
it("keeps the neutral column background without an accent color", () => {
renderColumns({});
const column = document.querySelector("[data-ui-id='kanban.column.new']") as HTMLElement;
expect(column.style.backgroundColor).toBe("");
});
});
@@ -0,0 +1,427 @@
// Shared app-UI Kanban board with real drag & drop (dnd-kit). App-UI layer —
// NOT subframe-synced. It only encapsulates the dnd-kit mechanics and renders
// the existing ~/ui KanbanColumn shell plus a caller-supplied `renderCard` slot,
// so all boards reuse one implementation.
//
// Layer rules: this component is pure/presentational — it never imports the DB
// or ~/db, never calls useLoaderData/useFetcher. It receives VM-shaped columns
// as props and emits moves via the `onCardMove` callback; the route/screen owns
// the server submit and revalidation.
//
// dnd-kit wiring follows apps/web/app/modules/formWidget/builder/{Canvas,
// SortableField}.tsx: PointerSensor + KeyboardSensor(sortableKeyboardCoordinates)
// and CSS.Transform.toString on each sortable node.
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from "react";
import { useTranslation } from "react-i18next";
import {
DndContext,
DragOverlay,
KeyboardSensor,
PointerSensor,
closestCorners,
pointerWithin,
useDroppable,
useSensor,
useSensors,
type Announcements,
type CollisionDetection,
type DragEndEvent,
type DragStartEvent,
} from "@dnd-kit/core";
import { SortableContext, sortableKeyboardCoordinates, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import { KanbanColumn } from "~/ui/components/KanbanColumn";
import { columnDroppableId, computeKanbanMove } from "./kanbanMove";
/** Pointer hits are both cheaper and more intuitive than comparing every
* rectangle corner. Keyboard dragging has no pointer coordinates, so it keeps
* the established closest-corners fallback. */
const pointerFirstCollision: CollisionDetection = (args) => {
const pointerCollisions = pointerWithin(args);
return pointerCollisions.length > 0 ? pointerCollisions : closestCorners(args);
};
export interface SortableKanbanColumn<TCard extends { readonly id: string }> {
readonly id: string;
/** Plain-text column label used for aria/announcements (falls back to id). */
readonly label?: string;
readonly name?: ReactNode;
readonly price?: ReactNode;
readonly badge?: ReactNode;
/** Explicit aggregate presentation; domain copy is supplied by the caller. */
readonly sumMode?: "visible" | "locked" | "hidden";
readonly lockedSumSlot?: ReactNode;
/** Domain-specific empty state rendered inside an otherwise empty column. */
readonly emptyContent?: ReactNode;
/** Wrap the column into a two-column card grid (wide column) — see ~/ui KanbanColumn. */
readonly twoColumn?: boolean;
/** Row count after which the two-column grid wraps (forwarded to ~/ui KanbanColumn). */
readonly wrapAfter?: number;
/** Stage color (hex) — tints the column background subtly, matching the detail view's stage palette. */
readonly accentColor?: string;
readonly cards: readonly TCard[];
}
export interface SortableKanbanBoardProps<TCard extends { readonly id: string }> {
readonly columns: readonly SortableKanbanColumn<TCard>[];
/** Render slot for a single card body (e.g. the ~/ui KanbanCard). */
readonly renderCard: (card: TCard, dragHandle?: ReactNode) => ReactNode;
/**
* Menu of the column head — Davids export draws a kebab there. What it opens is
* the caller's business, so the board hands over the collapse state it owns and
* renders whatever comes back.
*/
readonly renderColumnMenu?: (column: SortableKanbanColumn<TCard>, api: { collapsed: boolean; toggleCollapse: () => void }) => ReactNode;
/** Plain-text label for a card, used for aria/announcements. */
readonly getCardLabel: (card: TCard) => string;
/**
* Fired when a card is dropped into a DIFFERENT column. `toIndex` is provided
* for completeness but same-column reordering is intentionally NOT reported
* (see intra-column note below).
*/
readonly onCardMove: (cardId: string, toColumnId: string, toIndex: number) => void;
/** When true, cards render read-only (no drag handles / no DnD). */
readonly disabled?: boolean;
/**
* Per-card veto. A column may hold entries that are not real cards — an empty
* column's placeholder, for instance. Those must not be draggable: the whole
* tile is the drag surface, so without this they would be picked up like any
* card and land in another column.
*/
readonly isCardDraggable?: (card: TCard) => boolean;
/**
* Rollback trigger. When this flips truthy (a failed server move surfaced by
* the host), the local optimistic state resyncs to `columns` (server truth).
*/
readonly errorKey?: string | null;
/**
* Explicit revert trigger. Bump this to force a resync to `columns` even when
* `columns` did not change — e.g. the host cancelled a confirm dialog after an
* optimistic drop, so the card must snap back.
*/
readonly resetToken?: string | number;
/** Keep the default visible handle above the card, or place an invisible handle in the caller's card layout. */
readonly dragHandlePlacement?: "above" | "inline";
readonly className?: string;
readonly "data-ui-id"?: string;
}
/** Structural fingerprint (column + ordered card ids). Changes only when the
* server truth reorders/moves a card — used to resync optimistic state without
* clobbering it on every parent re-render. */
function columnsSignature<TCard extends { readonly id: string }>(columns: readonly SortableKanbanColumn<TCard>[]): string {
return columns.map((column) => `${column.id}:${column.cards.map((card) => card.id).join(",")}`).join("|");
}
function cloneColumns<TCard extends { readonly id: string }>(
columns: readonly SortableKanbanColumn<TCard>[],
): SortableKanbanColumn<TCard>[] {
return columns.map((column) => ({ ...column, cards: [...column.cards] }));
}
interface SortableCardProps<TCard extends { readonly id: string }> {
readonly card: TCard;
readonly renderCard: (card: TCard, dragHandle?: ReactNode) => ReactNode;
readonly label: string;
readonly disabled: boolean;
readonly dragHandlePlacement: "above" | "inline";
}
function SortableCard<TCard extends { readonly id: string }>({ card, renderCard, label, disabled, dragHandlePlacement }: SortableCardProps<TCard>) {
const { t } = useTranslation();
const { attributes, listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = useSortable({
id: card.id,
disabled,
});
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
willChange: transform ? "transform" : undefined,
// The card itself is the drag surface, so the pointer gesture must not be
// claimed by touch scrolling before the sensor's distance threshold is met.
touchAction: disabled ? undefined : "manipulation",
// While a card is dragged the DragOverlay carries the visual; the original
// stays as a faint placeholder marking where it came from.
opacity: isDragging ? 0.4 : 1,
};
// Keyboard activator. Pointer dragging works anywhere on the card (the
// listeners sit on the wrapper below), but a keyboard user needs one focusable
// element to start the move from — that is this handle.
const dragHandle = disabled ? null : (
<button
type="button"
ref={setActivatorNodeRef}
className={
dragHandlePlacement === "inline"
? "inline-flex h-6 w-6 flex-none cursor-grab items-center justify-center rounded text-icon-neutral-tertiary hover:text-icon-neutral-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-200 active:cursor-grabbing"
: "inline-flex h-6 w-full cursor-grab items-center justify-center rounded text-icon-neutral-tertiary hover:text-icon-neutral-secondary focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-200"
}
aria-label={t("kanban.dnd.reorderAria", { name: label })}
data-ui-id={`kanban.dragHandle.${card.id}`}
{...listeners}
{...attributes}
>
<span aria-hidden="true" className="text-body-small-semibold-0 leading-none tracking-widest select-none">
{"⋮⋮"}
</span>
</button>
);
return (
<div ref={setNodeRef} style={style} className="flex w-full flex-col items-center" data-card-id={card.id}>
{/* Pointer listeners on the whole card: the tile is what a user grabs, not
a strip inside it. A plain click still reaches the link, the checkbox
and the context menu — the sensor only takes over past its distance
threshold, so a press without movement is never swallowed. */}
<div
className={disabled ? "flex w-72 flex-col items-stretch gap-1" : "flex w-72 cursor-grab flex-col items-stretch gap-1 active:cursor-grabbing"}
{...(disabled ? {} : listeners)}
>
{dragHandlePlacement === "above" ? dragHandle : null}
{renderCard(card, dragHandlePlacement === "inline" ? dragHandle : undefined)}
</div>
</div>
);
}
interface ColumnDropZoneProps<TCard extends { readonly id: string }> {
readonly column: SortableKanbanColumn<TCard>;
readonly children: ReactNode;
readonly collapsed: boolean;
readonly menu?: ReactNode;
/** Expands the column again: collapsed, its head is the only control left. */
readonly onToggleCollapse: () => void;
readonly expandLabel: string;
readonly "data-ui-id"?: string;
}
function ColumnDropZone<TCard extends { readonly id: string }>({
column,
children,
collapsed,
menu,
onToggleCollapse,
expandLabel,
...rest
}: ColumnDropZoneProps<TCard>) {
const { setNodeRef, isOver } = useDroppable({ id: columnDroppableId(column.id) });
return (
<KanbanColumn
ref={setNodeRef}
onToggleCollapse={onToggleCollapse}
expandLabel={expandLabel}
name={column.name}
price={column.price}
badge={column.badge}
sumMode={column.sumMode}
lockedSumSlot={column.lockedSumSlot}
twoColumn={column.twoColumn}
wrapAfter={column.wrapAfter}
collapsed={collapsed}
icon={menu}
className={isOver ? "border-border-brand" : undefined}
// 6-digit hex + alpha suffix: ~10% background tint. Border stays class-driven
// so the drag-over highlight keeps winning.
style={column.accentColor ? { backgroundColor: `${column.accentColor}1a` } : undefined}
cards={children}
data-ui-id={rest["data-ui-id"]}
/>
);
}
export function SortableKanbanBoard<TCard extends { readonly id: string }>(props: SortableKanbanBoardProps<TCard>) {
const {
columns,
renderCard,
renderColumnMenu,
getCardLabel,
onCardMove,
disabled = false,
errorKey,
resetToken,
dragHandlePlacement = "above",
} = props;
const { t } = useTranslation();
const [localColumns, setLocalColumns] = useState<SortableKanbanColumn<TCard>[]>(() => cloneColumns(columns));
const [activeId, setActiveId] = useState<string | null>(null);
// Collapsed columns are a view state of this session, not server truth: it says
// what this person wants to look at right now.
const [collapsedIds, setCollapsedIds] = useState<ReadonlySet<string>>(() => new Set());
// Resync to server truth on structural change, on error (rollback) and on an
// explicit reset bump. A ref avoids depending on the `columns` array identity,
// which the parent recreates every render (that would clobber optimistic UI).
const signature = columnsSignature(columns);
const columnsRef = useRef(columns);
columnsRef.current = columns;
useEffect(() => {
setLocalColumns(cloneColumns(columnsRef.current));
}, [signature, errorKey, resetToken]);
// Drag-over announcements and overlay lookup run for every pointer movement.
// Build them once per actual board shape instead of scanning every card on
// every movement (the route currently permits up to 50 cards per column).
const cardById = useMemo(() => {
const cards = new Map<string, TCard>();
const columnLabels = new Map<string, string>();
for (const column of localColumns) {
for (const card of column.cards) {
cards.set(card.id, card);
columnLabels.set(card.id, column.label ?? column.id);
}
}
return { cards, columnLabels };
}, [localColumns]);
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 5 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
);
// Grabbing cursor for as long as a card is in hand. It has to live on <html>
// rather than on the card: the pointer spends the drag over other columns and
// over the overlay, where a class on the source tile no longer applies. The
// cleanup also runs when the component unmounts mid-drag, so the fist can
// never get stuck on the page.
useEffect(() => {
if (activeId === null) return;
const root = document.documentElement;
root.classList.add("hg-kanban-dragging");
return () => root.classList.remove("hg-kanban-dragging");
}, [activeId]);
const findCard = useCallback(
(cardId: string | null): TCard | null => (cardId ? cardById.cards.get(cardId) ?? null : null),
[cardById],
);
const cardLabelForId = useCallback(
(cardId: string): string => {
const card = findCard(cardId);
return card ? getCardLabel(card) : cardId;
},
[findCard, getCardLabel],
);
const columnLabelForOverId = useCallback(
(overId: string): string => {
const columnId = overId.replace(/^kanban-col:/, "");
const byColumn = localColumns.find((candidate) => candidate.id === columnId);
if (byColumn) return byColumn.label ?? byColumn.id;
// `over` may be a card id — resolve it to its owning column.
return cardById.columnLabels.get(overId) ?? columnId;
},
[localColumns, cardById],
);
function handleDragStart(event: DragStartEvent) {
setActiveId(String(event.active.id));
}
function handleDragCancel() {
setActiveId(null);
}
function handleDragEnd(event: DragEndEvent) {
setActiveId(null);
const { active, over } = event;
if (!over) return;
const result = computeKanbanMove(localColumns, String(active.id), String(over.id));
if (!result) return;
setLocalColumns(result.columns); // optimistic
if (result.crossColumn) {
onCardMove(result.cardId, result.to.columnId, result.to.index);
}
// Intra-column reorder is visual-only and intentionally NOT persisted:
// Projekt has no position field, so same-column order is not stored. The
// next revalidation resyncs the server order. See kanbanMove.ts.
}
const announcements: Announcements = useMemo(
() => ({
onDragStart: ({ active }) => t("kanban.dnd.announceStart", { name: cardLabelForId(String(active.id)) }),
onDragOver: ({ active, over }) =>
over ? t("kanban.dnd.announceOver", { name: cardLabelForId(String(active.id)), column: columnLabelForOverId(String(over.id)) }) : "",
onDragEnd: ({ active, over }) =>
over
? t("kanban.dnd.announceEnd", { name: cardLabelForId(String(active.id)), column: columnLabelForOverId(String(over.id)) })
: t("kanban.dnd.announceCancel"),
onDragCancel: () => t("kanban.dnd.announceCancel"),
}),
[t, cardLabelForId, columnLabelForOverId],
);
const activeCard = findCard(activeId);
return (
<DndContext
sensors={sensors}
collisionDetection={pointerFirstCollision}
onDragStart={handleDragStart}
onDragEnd={handleDragEnd}
onDragCancel={handleDragCancel}
accessibility={{ announcements, screenReaderInstructions: { draggable: t("kanban.dnd.instructions") } }}
>
<div className={props.className ?? "flex w-full gap-4 overflow-x-auto pb-2"} data-ui-id={props["data-ui-id"]}>
{localColumns.map((column) => {
const toggleCollapse = () =>
setCollapsedIds((current) => {
const next = new Set(current);
if (next.has(column.id)) next.delete(column.id);
else next.add(column.id);
return next;
});
return (
<ColumnDropZone
key={column.id}
column={column}
collapsed={collapsedIds.has(column.id)}
onToggleCollapse={toggleCollapse}
expandLabel={t("kanban.column.expandAria", { name: column.label ?? column.id })}
menu={renderColumnMenu?.(column, {
collapsed: collapsedIds.has(column.id),
toggleCollapse,
})}
data-ui-id={`kanban.column.${column.id}`}
>
<SortableContext id={column.id} items={column.cards.map((card) => card.id)} strategy={verticalListSortingStrategy}>
{column.cards.length === 0 ? (
column.emptyContent ?? (disabled ? null : (
<div className="flex min-h-16 w-72 items-center justify-center rounded-md border border-dashed border-border-default text-body-small-regular-0 font-body-small-regular-0 text-text-neutral-tertiary">
{t("kanban.dnd.emptyColumn")}
</div>
))
) : (
column.cards.map((card) => (
<SortableCard
key={card.id}
card={card}
renderCard={renderCard}
label={getCardLabel(card)}
disabled={disabled || !(props.isCardDraggable?.(card) ?? true)}
dragHandlePlacement={dragHandlePlacement}
/>
))
)}
</SortableContext>
</ColumnDropZone>
);
})}
</div>
{/* The dragged card rides with the cursor: `dropAnimation={null}` keeps it
from flying back to its origin before the new order renders, and the
lift makes clear which tile is in hand. */}
<DragOverlay dropAnimation={null}>
{activeCard ? (
<div className="w-72 rotate-1 cursor-grabbing opacity-95 shadow-lg" data-ui-id="kanban.dragOverlay">
{renderCard(activeCard)}
</div>
) : null}
</DragOverlay>
</DndContext>
);
}
export default SortableKanbanBoard;
@@ -0,0 +1,85 @@
// Unit tests for the pure SortableKanbanBoard move reducer. No React / dnd-kit.
import { describe, expect, it } from "vitest";
import { columnDroppableId, computeKanbanMove, locateCard } from "./kanbanMove";
interface Card {
readonly id: string;
}
interface Col {
readonly id: string;
readonly title: string; // extra field: must be preserved across moves
readonly cards: readonly Card[];
}
function board(): Col[] {
return [
{ id: "todo", title: "To do", cards: [{ id: "a" }, { id: "b" }, { id: "c" }] },
{ id: "doing", title: "Doing", cards: [{ id: "d" }] },
{ id: "done", title: "Done", cards: [] },
];
}
const ids = (cols: Col[]) => cols.map((c) => `${c.id}:${c.cards.map((x) => x.id).join(",")}`).join("|");
describe("locateCard", () => {
it("finds the column and index of a card", () => {
expect(locateCard(board(), "b")).toEqual({ columnId: "todo", index: 1 });
expect(locateCard(board(), "d")).toEqual({ columnId: "doing", index: 0 });
});
it("returns null for an unknown card", () => {
expect(locateCard(board(), "zzz")).toBeNull();
});
});
describe("computeKanbanMove", () => {
it("moves a card into another column over a target card and flags crossColumn", () => {
const result = computeKanbanMove(board(), "a", "d");
expect(result).not.toBeNull();
expect(result!.crossColumn).toBe(true);
expect(result!.cardId).toBe("a");
expect(result!.to).toEqual({ columnId: "doing", index: 0 });
expect(ids(result!.columns)).toBe("todo:b,c|doing:a,d|done:");
});
it("appends to an empty column when dropped on the column droppable sentinel", () => {
const result = computeKanbanMove(board(), "b", columnDroppableId("done"));
expect(result).not.toBeNull();
expect(result!.crossColumn).toBe(true);
expect(result!.to).toEqual({ columnId: "done", index: 0 });
expect(ids(result!.columns)).toBe("todo:a,c|doing:d|done:b");
});
it("preserves extra column fields (title) when moving", () => {
const result = computeKanbanMove(board(), "a", "d");
expect(result!.columns.map((c) => c.title)).toEqual(["To do", "Doing", "Done"]);
});
it("reorders within a column (arrayMove semantics) without crossColumn", () => {
const result = computeKanbanMove(board(), "a", "c");
expect(result).not.toBeNull();
expect(result!.crossColumn).toBe(false);
expect(ids(result!.columns)).toBe("todo:b,c,a|doing:d|done:");
});
it("returns null when dropped on itself", () => {
expect(computeKanbanMove(board(), "a", "a")).toBeNull();
});
it("returns null for an unknown active card", () => {
expect(computeKanbanMove(board(), "zzz", "d")).toBeNull();
});
it("returns null for an unknown drop target", () => {
expect(computeKanbanMove(board(), "a", "nope")).toBeNull();
});
it("does not mutate the input columns", () => {
const input = board();
const before = ids(input);
computeKanbanMove(input, "a", "d");
expect(ids(input)).toBe(before);
});
});
@@ -0,0 +1,105 @@
// Pure move/reorder logic for the shared SortableKanbanBoard. Kept free of React
// and dnd-kit so it can be unit-tested directly (the board only wires dnd-kit
// events into `computeKanbanMove`). The reducer mirrors dnd-kit's arrayMove
// insertion semantics: dropping a card "over" another card inserts it at that
// card's slot (post-removal splice), and dropping over an (empty) column
// appends to the end.
/** Sentinel prefix for a column-level droppable id (see SortableKanbanBoard).
* Column drop-zones use this so an empty column is still a valid drop target and
* `over.id` can be told apart from a card id. */
export const COLUMN_DROPPABLE_PREFIX = "kanban-col:";
export function columnDroppableId(columnId: string): string {
return `${COLUMN_DROPPABLE_PREFIX}${columnId}`;
}
export interface KanbanMoveColumn<TCard extends { readonly id: string }> {
readonly id: string;
readonly cards: readonly TCard[];
}
export interface KanbanCardLocation {
readonly columnId: string;
readonly index: number;
}
export interface KanbanMoveResult<Col> {
/** New columns array with the card moved (extra column fields preserved). */
readonly columns: Col[];
readonly cardId: string;
readonly from: KanbanCardLocation;
readonly to: KanbanCardLocation;
/** True when the card changed column (the only case that is persisted). */
readonly crossColumn: boolean;
}
function clamp(value: number, min: number, max: number): number {
return Math.max(min, Math.min(max, value));
}
/** Find which column a card currently lives in, and at which index. */
export function locateCard<TCard extends { readonly id: string }>(
columns: readonly KanbanMoveColumn<TCard>[],
cardId: string,
): KanbanCardLocation | null {
for (const column of columns) {
const index = column.cards.findIndex((card) => card.id === cardId);
if (index >= 0) return { columnId: column.id, index };
}
return null;
}
/** Resolve a dnd-kit `over.id` (either a card id or a `kanban-col:<id>` sentinel)
* to a concrete drop target column + insert index. */
function resolveDropTarget<TCard extends { readonly id: string }>(
columns: readonly KanbanMoveColumn<TCard>[],
overId: string,
): KanbanCardLocation | null {
if (overId.startsWith(COLUMN_DROPPABLE_PREFIX)) {
const columnId = overId.slice(COLUMN_DROPPABLE_PREFIX.length);
const column = columns.find((candidate) => candidate.id === columnId);
if (!column) return null;
// Dropping onto the column background appends to the end.
return { columnId, index: column.cards.length };
}
return locateCard(columns, overId);
}
/**
* Compute the next board state for a drag from `activeId` dropped over `overId`.
* Returns `null` for no-ops (dropped on itself / unresolvable / same slot).
* Column identity and any extra column fields (name/price/badge) are preserved.
*/
export function computeKanbanMove<
TCard extends { readonly id: string },
Col extends KanbanMoveColumn<TCard>,
>(columns: readonly Col[], activeId: string, overId: string): KanbanMoveResult<Col> | null {
if (activeId === overId) return null;
const from = locateCard(columns, activeId);
if (!from) return null;
const target = resolveDropTarget(columns, overId);
if (!target) return null;
// Clone with mutable card arrays; keep every other column field by reference.
const next = columns.map((column) => ({ ...column, cards: [...column.cards] as TCard[] }));
const fromColumn = next.find((column) => column.id === from.columnId)!;
const toColumn = from.columnId === target.columnId ? fromColumn : next.find((column) => column.id === target.columnId)!;
const [moved] = fromColumn.cards.splice(from.index, 1);
const insertAt = clamp(target.index, 0, toColumn.cards.length);
toColumn.cards.splice(insertAt, 0, moved);
const crossColumn = from.columnId !== target.columnId;
if (!crossColumn && insertAt === from.index) return null; // same column, same slot
return {
columns: next as unknown as Col[],
cardId: activeId,
from,
to: { columnId: toColumn.id, index: insertAt },
crossColumn,
};
}
@@ -2,7 +2,6 @@ import { ReactNode } from "react";
import { useParams } from "react-router";
import BreadcrumbSimple from "../breadcrumbs/BreadcrumbSimple";
import Tabs, { TabItem } from "../tabs/Tabs";
import clsx from "clsx";
import { cn } from "~/lib/utils";
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
import UrlUtils from "~/utils/app/UrlUtils";
@@ -28,7 +27,7 @@ export default function EditPageLayout({ title, menu, buttons, children, withHom
{(title || buttons || menu || tabs) && (
<div className="space-y-1">
<div className="flex items-center justify-between space-x-2">
<h1 className="flex flex-1 items-center truncate text-xl font-medium">{title}</h1>
{title ? <h1 className="flex flex-1 items-center truncate text-xl font-medium">{title}</h1> : <div className="flex-1" />}
<div className="flex items-center space-x-2">{buttons}</div>
</div>
@@ -1,5 +1,4 @@
import { ReactNode } from "react";
import Breadcrumb from "../breadcrumbs/Breadcrumb";
import Tabs, { TabItem } from "../tabs/Tabs";
import BreadcrumbSimple from "../breadcrumbs/BreadcrumbSimple";
@@ -0,0 +1,230 @@
import "@testing-library/jest-dom";
import { act, fireEvent, render, within } from "@testing-library/react";
import { MemoryRouter } from "react-router";
import { describe, expect, it, vi } from "vitest";
import SidebarIconsLayout from "./SidebarIconsLayout";
function useDeterministicFakeTimers() {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-01-01T00:00:00.000Z"));
}
function renderLayout({ sticky = false }: { sticky?: boolean } = {}) {
const { container } = render(
<MemoryRouter initialEntries={["/overview"]}>
<SidebarIconsLayout
sticky={sticky}
items={[
{ name: "Overview", href: "/overview", icon: <span aria-hidden="true">O</span> },
{ name: "Campaigns", href: "/campaigns", icon: <span aria-hidden="true">C</span> },
]}
>
<main>Content</main>
</SidebarIconsLayout>
</MemoryRouter>
);
const sidebar = container.querySelector("nav:not([aria-label])");
expect(sidebar).not.toBeNull();
return sidebar as HTMLElement;
}
describe("SidebarIconsLayout", () => {
it("expands after 300 ms of hover and collapses after the pointer leaves", () => {
useDeterministicFakeTimers();
try {
const sidebar = renderLayout();
const hoverTarget = sidebar.parentElement;
expect(hoverTarget).not.toBeNull();
expect(sidebar).toHaveClass("w-12");
expect(within(sidebar).queryByRole("button")).not.toBeInTheDocument();
fireEvent.mouseEnter(hoverTarget!);
expect(sidebar).toHaveClass("w-12");
act(() => vi.advanceTimersByTime(299));
expect(sidebar).toHaveClass("w-12");
act(() => vi.advanceTimersByTime(1));
expect(sidebar).toHaveClass("w-[208px]");
fireEvent.mouseLeave(hoverTarget!);
act(() => vi.advanceTimersByTime(349));
expect(sidebar).toHaveClass("w-[208px]");
act(() => vi.advanceTimersByTime(1));
expect(sidebar).toHaveClass("w-12");
} finally {
vi.useRealTimers();
}
});
it("stays collapsed when the pointer leaves before the open delay", () => {
useDeterministicFakeTimers();
try {
const sidebar = renderLayout();
const hoverTarget = sidebar.parentElement!;
fireEvent.mouseEnter(hoverTarget);
act(() => vi.advanceTimersByTime(250));
fireEvent.mouseLeave(hoverTarget);
act(() => vi.runAllTimers());
expect(sidebar).toHaveClass("w-12");
fireEvent.mouseEnter(hoverTarget);
act(() => vi.advanceTimersByTime(299));
expect(sidebar).toHaveClass("w-12");
act(() => vi.advanceTimersByTime(1));
expect(sidebar).toHaveClass("w-[208px]");
} finally {
vi.useRealTimers();
}
});
it("does not expand after a pointer route click remounts the settings shell", () => {
useDeterministicFakeTimers();
try {
const firstRoute = render(
<MemoryRouter initialEntries={["/overview"]}>
<SidebarIconsLayout
items={[
{ name: "Overview", href: "/overview", icon: <span aria-hidden="true">O</span> },
{ name: "Campaigns", href: "/campaigns", icon: <span aria-hidden="true">C</span> },
]}
>
<main>Content</main>
</SidebarIconsLayout>
</MemoryRouter>
);
const sidebar = firstRoute.container.querySelector("nav:not([aria-label])") as HTMLElement;
const hoverTarget = sidebar.parentElement!;
const firstLink = within(sidebar).getByRole("link", { name: "Overview" });
fireEvent.mouseEnter(hoverTarget);
act(() => vi.advanceTimersByTime(150));
fireEvent.pointerDown(firstLink);
fireEvent.focus(firstLink);
fireEvent.pointerUp(firstLink);
act(() => vi.runAllTimers());
expect(sidebar).toHaveClass("w-12");
firstRoute.unmount();
const nextRoute = render(
<MemoryRouter initialEntries={["/campaigns"]}>
<SidebarIconsLayout
items={[
{ name: "Overview", href: "/overview", icon: <span aria-hidden="true">O</span> },
{ name: "Campaigns", href: "/campaigns", icon: <span aria-hidden="true">C</span> },
]}
>
<main>Next content</main>
</SidebarIconsLayout>
</MemoryRouter>
);
const nextSidebar = nextRoute.container.querySelector("nav:not([aria-label])") as HTMLElement;
const nextHoverTarget = nextSidebar.parentElement!;
fireEvent.mouseEnter(nextHoverTarget);
act(() => vi.advanceTimersByTime(1_000));
expect(nextSidebar).toHaveClass("w-12");
fireEvent.mouseLeave(nextHoverTarget);
fireEvent.mouseEnter(nextHoverTarget);
act(() => vi.advanceTimersByTime(300));
expect(nextSidebar).toHaveClass("w-[208px]");
} finally {
vi.useRealTimers();
}
});
it("cancels the delayed close when the pointer returns", () => {
useDeterministicFakeTimers();
try {
const sidebar = renderLayout();
const hoverTarget = sidebar.parentElement!;
fireEvent.mouseEnter(hoverTarget);
act(() => vi.advanceTimersByTime(300));
fireEvent.mouseLeave(hoverTarget);
act(() => vi.advanceTimersByTime(200));
fireEvent.mouseEnter(hoverTarget);
act(() => vi.advanceTimersByTime(350));
expect(sidebar).toHaveClass("w-[208px]");
} finally {
vi.useRealTimers();
}
});
it("stays expanded while keyboard focus is inside", () => {
const sidebar = renderLayout();
const firstLink = within(sidebar).getByRole("link", { name: "Overview" });
fireEvent.focus(firstLink);
expect(sidebar).toHaveClass("w-[208px]");
fireEvent.blur(firstLink, { relatedTarget: document.body });
expect(sidebar).toHaveClass("w-12");
});
it("smoothly magnifies the complete hovered navigation item", () => {
const sidebar = renderLayout();
const firstLink = within(sidebar).getByRole("link", { name: "Overview" });
const itemSurface = firstLink.querySelector('[data-slot="inner-sidebar-nav-item-surface"]');
expect(itemSurface).toHaveClass(
"pointer-events-none",
"scale-100",
"transition-[background-color,scale]",
"duration-150",
"ease-[cubic-bezier(0.4,0,0.2,1)]",
"motion-reduce:transition-none",
"group-hover/7aa51c7e:scale-[1.065]",
"data-[sidebar-sweep-hover=true]:scale-[1.065]"
);
});
it("keeps the desktop settings rail fixed when sticky is enabled", () => {
const sidebar = renderLayout({ sticky: true });
expect(sidebar.parentElement).toHaveClass("sm:sticky", "sm:top-0", "sm:self-start");
expect(sidebar).toHaveClass("min-h-[calc(100svh-3.5rem)]");
});
it("uses the selected icon and normalizes nested glyphs to the same size", () => {
const { container } = render(
<MemoryRouter initialEntries={["/overview"]}>
<SidebarIconsLayout
items={[
{
name: "Overview",
href: "/overview",
icon: (
<span data-icon="default">
<svg />
</span>
),
iconSelected: (
<span data-icon="selected">
<svg />
</span>
),
},
]}
>
<main>Content</main>
</SidebarIconsLayout>
</MemoryRouter>
);
const selected = container.querySelector('[data-icon="selected"]');
expect(selected).toBeInTheDocument();
expect(selected).toHaveClass("size-5", "[&_svg]:size-5");
expect(container.querySelector('[data-icon="default"]')).not.toBeInTheDocument();
});
});
@@ -1,9 +1,9 @@
import { Link, useLocation } from "react-router";
import { useEffect, useRef, useState } from "react";
import UrlUtils from "~/utils/app/UrlUtils";
import { cloneElement, isValidElement, useEffect, useRef, useState } from "react";
import Tabs from "../tabs/Tabs";
import EntityIcon from "~/components/layouts/icons/EntityIcon";
import { SidebarInside } from "~/ui";
import { isRouteActive } from "~/utils/navigation/routeMatching";
export type IconDto = {
name: string;
@@ -18,12 +18,26 @@ export type IconDto = {
hidden?: boolean;
};
// Pro-User gemerkter Collapse-Zustand der Inner-Sidebar (Default: aufgeklappt).
const COLLAPSE_STORAGE_KEY = "hg.innerSidebar.collapsed";
const HOVER_OPEN_DELAY_MS = 300;
const HOVER_CLOSE_DELAY_MS = 350;
const POINTER_ROUTE_SETTLE_MS = 750;
let suppressPointerHoverUntil = 0;
let lastPointerInteractionAt = 0;
function pointerHoverIsSuppressed() {
const now = Date.now();
if (now < lastPointerInteractionAt) {
lastPointerInteractionAt = 0;
suppressPointerHoverUntil = 0;
return false;
}
return now < suppressPointerHoverUntil;
}
export default function SidebarIconsLayout({
children,
items,
sticky = false,
}: {
children: React.ReactNode;
items: IconDto[];
@@ -32,59 +46,75 @@ export default function SidebarIconsLayout({
align: "bottom" | "right";
};
scrollRestoration?: boolean;
sticky?: boolean;
}) {
const location = useLocation();
const mainElement = useRef<HTMLDivElement>(null);
// SSR-safe: Server rendert immer aufgeklappt, der gemerkte Zustand wird erst nach Hydration geladen.
const [collapsed, setCollapsed] = useState(false);
// Transitions erst NACH dem Restore aktivieren, sonst animiert der gemerkte Zustand bei jedem Seitenaufruf.
const [animate, setAnimate] = useState(false);
const [hovered, setHovered] = useState(false);
const [focusWithin, setFocusWithin] = useState(false);
const openDelayRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const closeDelayRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const pointerInteractionRef = useRef(false);
const suppressHoverUntilLeaveRef = useRef(false);
const expanded = hovered || focusWithin;
useEffect(() => {
try {
setCollapsed(window.localStorage.getItem(COLLAPSE_STORAGE_KEY) === "1");
} catch {
// localStorage nicht verfügbar (Privatmodus o.ä.) -> Default aufgeklappt
}
const id = window.requestAnimationFrame(() => setAnimate(true));
return () => window.cancelAnimationFrame(id);
}, []);
function toggleCollapsed() {
setCollapsed((prev) => {
const next = !prev;
try {
window.localStorage.setItem(COLLAPSE_STORAGE_KEY, next ? "1" : "0");
} catch {
// persistieren best-effort
}
return next;
});
function cancelScheduledOpen() {
if (openDelayRef.current === null) return;
clearTimeout(openDelayRef.current);
openDelayRef.current = null;
}
function cancelScheduledClose() {
if (closeDelayRef.current === null) return;
clearTimeout(closeDelayRef.current);
closeDelayRef.current = null;
}
function handleMouseEnter() {
cancelScheduledClose();
if (suppressHoverUntilLeaveRef.current || pointerHoverIsSuppressed()) return;
if (hovered || openDelayRef.current !== null) return;
openDelayRef.current = setTimeout(() => {
setHovered(true);
openDelayRef.current = null;
}, HOVER_OPEN_DELAY_MS);
}
function handleMouseLeave() {
suppressHoverUntilLeaveRef.current = false;
pointerInteractionRef.current = false;
cancelScheduledOpen();
cancelScheduledClose();
if (!hovered) return;
closeDelayRef.current = setTimeout(() => {
setHovered(false);
closeDelayRef.current = null;
}, HOVER_CLOSE_DELAY_MS);
}
useEffect(
() => () => {
if (openDelayRef.current !== null) clearTimeout(openDelayRef.current);
if (closeDelayRef.current !== null) clearTimeout(closeDelayRef.current);
},
[]
);
function findExactRoute(element: IconDto) {
const hrefWithoutQuery = element.href.split("?")[0];
if (element.exact) {
return UrlUtils.stripTrailingSlash(location.pathname) === UrlUtils.stripTrailingSlash(hrefWithoutQuery);
}
return (location.pathname + location.search).includes(hrefWithoutQuery);
return isRouteActive(location.pathname, element.href, { exact: element.exact });
}
const currentTab = items.find((element) => findExactRoute(element));
function renderItem(item: IconDto, idx: number) {
const current = currentTab?.name === item.name;
const iconNode =
item.textIcon !== undefined ? (
<EntityIcon className="h-5 w-5" icon={current ? item.textIconSelected ?? item.textIcon : item.textIcon} />
) : current ? (
item.iconSelected ?? item.icon
) : (
item.icon
);
// Collapsed: center the icon-only item in the narrow rail. Expanded: keep the regular label row.
const textIcon = current ? (item.textIconSelected ?? item.textIcon) : item.textIcon;
const icon = current ? (item.iconSelected ?? item.icon) : item.icon;
const iconNode = textIcon !== undefined ? <EntityIcon className="size-5" icon={textIcon} /> : normalizeIcon(icon);
// The icon stays left-anchored in both states (NavItem keeps a constant 32px icon column),
// so the icon never shifts horizontally between the collapsed rail and the expanded label row.
return (
<Link key={idx} prefetch={item.prefetch} to={item.href} className="flex w-full justify-center" title={item.name}>
<SidebarInside.NavItem icon={iconNode} selected={current} variant={collapsed ? "icon-only" : "icon-and-text"}>
<Link key={idx} prefetch={item.prefetch} to={item.href} className="flex w-full justify-start" title={item.name}>
<SidebarInside.NavItem icon={iconNode} selected={current} variant={expanded ? "icon-and-text" : "icon-only"}>
{item.name}
</SidebarInside.NavItem>
</Link>
@@ -96,14 +126,34 @@ export default function SidebarIconsLayout({
return (
<div className="sm:flex sm:flex-row">
{/* Desktop: Inner sidebar uses the same mechanical width-collapse as the main navigation. */}
<div className="relative hidden sm:flex">
<SidebarInside
visible={true}
variant={collapsed ? "closed" : "open"}
onToggleCollapse={toggleCollapsed}
className={`min-h-[calc(100svh-4rem)] ${animate ? "" : "transition-none"}`}
>
{/* Desktop: expand on pointer hover or keyboard focus; otherwise keep a compact icon rail. */}
<div
className={sticky ? "relative hidden sm:sticky sm:top-0 sm:flex sm:self-start" : "relative hidden sm:flex"}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
onPointerDownCapture={() => {
const pointerInteractionAt = Date.now();
pointerInteractionRef.current = true;
suppressHoverUntilLeaveRef.current = true;
lastPointerInteractionAt = pointerInteractionAt;
suppressPointerHoverUntil = pointerInteractionAt + POINTER_ROUTE_SETTLE_MS;
cancelScheduledOpen();
setFocusWithin(false);
}}
onPointerUpCapture={() => {
pointerInteractionRef.current = false;
}}
onPointerCancelCapture={() => {
pointerInteractionRef.current = false;
}}
onFocusCapture={() => {
if (!pointerInteractionRef.current) setFocusWithin(true);
}}
onBlurCapture={(event) => {
if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setFocusWithin(false);
}}
>
<SidebarInside visible={true} variant={expanded ? "open" : "closed"} className="min-h-[calc(100svh-3.5rem)]">
{topItems.map(renderItem)}
{bottomItems.length > 0 && (
<div className="mt-auto flex w-full flex-col">
@@ -121,7 +171,7 @@ export default function SidebarIconsLayout({
tabs={items
.filter((f) => !f.hidden)
.map((i) => {
return { name: i.name, routePath: i.href };
return { name: i.name, routePath: i.href, exact: i.exact };
})}
className="grow"
/>
@@ -129,9 +179,16 @@ export default function SidebarIconsLayout({
</div>
{/* Hauptbereich */}
<div ref={mainElement} className="w-full overflow-x-hidden">
<div ref={mainElement} className="w-full overflow-x-hidden" data-route-transition-content="true">
{children}
</div>
</div>
);
}
function normalizeIcon(icon: React.ReactNode) {
if (!isValidElement<{ className?: string }>(icon)) return icon;
return cloneElement(icon, {
className: `${icon.props.className ?? ""} inline-flex size-5 items-center justify-center [&_svg]:size-5`,
});
}
@@ -17,7 +17,7 @@ export default function ViewToggle({ view, setView }: Props) {
onClick={() => setView("table")}
type="button"
className={clsx(
"border-border-default focus:border-brand-brand-border-solid-default focus:shadow-focus hover:bg-surface-neutral-secondary/90 relative inline-flex items-center rounded-l-md border px-4 py-2.5 text-sm font-medium focus:z-10 focus:outline-hidden",
"border-border-default focus:border-brand-brand-border-solid-default focus:shadow-focus hover:bg-surface-neutral-secondary/90 relative inline-flex h-9 items-center rounded-l-md border px-4 text-sm font-medium focus:z-10 focus:outline-hidden",
view === "table" ? "bg-accent-100 text-accent-500" : "text-text-neutral-tertiary bg-surface-neutral-primary"
)}
>
@@ -31,7 +31,7 @@ export default function ViewToggle({ view, setView }: Props) {
onClick={() => setView("board")}
type="button"
className={clsx(
"border-border-default focus:border-brand-brand-border-solid-default focus:shadow-focus hover:bg-surface-neutral-secondary/90 relative -ml-px inline-flex items-center rounded-r-md border px-4 py-2.5 text-sm font-medium focus:z-10 focus:outline-hidden",
"border-border-default focus:border-brand-brand-border-solid-default focus:shadow-focus hover:bg-surface-neutral-secondary/90 relative -ml-px inline-flex h-9 items-center rounded-r-md border px-4 text-sm font-medium focus:z-10 focus:outline-hidden",
view === "board" ? "bg-accent-100 text-accent-500" : "text-text-neutral-tertiary bg-surface-neutral-primary"
)}
>
@@ -0,0 +1,30 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("react-router", () => ({
useNavigation: () => ({ state: "loading", location: { pathname: "/acme/projects" } }),
}));
vi.mock("spin-delay", () => ({ useSpinDelay: () => true }));
vi.mock("@headlessui/react", () => ({ Transition: ({ children }: { children: React.ReactNode }) => children }));
vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: (key: string) => key }) }));
vi.mock("~/ui/components/Loader", () => ({ Loader: () => <span data-testid="loader" /> }));
import FloatingLoader from "./FloatingLoader";
afterEach(() => {
vi.restoreAllMocks();
});
describe("FloatingLoader", () => {
it("renders navigation progress without starting an unused update timer", () => {
const setIntervalSpy = vi.spyOn(globalThis, "setInterval");
render(<FloatingLoader />);
expect(screen.getByTestId("loader")).toBeTruthy();
expect(document.body.textContent).toContain("/acme/projects");
expect(setIntervalSpy).not.toHaveBeenCalled();
});
});
Loaded 100 of 5955 files, more files were not shown because too many files have changed in this diff. Show more