Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
+26
@@ -0,0 +1,26 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import * as React from "react";
|
||||
import { describe, it } from "vitest";
|
||||
|
||||
import { Alert, AlertDescription, AlertTitle } from "./alert";
|
||||
import { expectNoAxeViolations } from "@toolctrl/ui-app/test-setup/axe";
|
||||
|
||||
describe("Alert axe-core a11y", () => {
|
||||
it("info alert has no axe violations", async () => {
|
||||
await expectNoAxeViolations(
|
||||
<Alert>
|
||||
<AlertTitle>Heads up</AlertTitle>
|
||||
<AlertDescription>Your subscription renews tomorrow.</AlertDescription>
|
||||
</Alert>,
|
||||
);
|
||||
});
|
||||
|
||||
it("destructive alert with role=alert has no axe violations", async () => {
|
||||
await expectNoAxeViolations(
|
||||
<Alert variant="destructive" role="alert">
|
||||
<AlertTitle>Error</AlertTitle>
|
||||
<AlertDescription>Could not save changes.</AlertDescription>
|
||||
</Alert>,
|
||||
);
|
||||
});
|
||||
});
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
import ButtonSecondary from "./buttons/ButtonSecondary";
|
||||
import { t as i18nT } from "i18next";
|
||||
import SlideOver from "./slideOvers/SlideOver";
|
||||
import { useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import PreviewBreadcrumbs from "./breadcrumbs/PreviewBreadcrumbs";
|
||||
import PreviewButtons from "./buttons/PreviewButtons";
|
||||
import PreviewButtonsAsLinks from "./buttons/PreviewButtonsAsLinks";
|
||||
import PreviewButtonsDestructive from "./buttons/PreviewButtonsDestructive";
|
||||
import PreviewModals from "./modals/PreviewModals";
|
||||
import PreviewBanners from "./banners/PreviewBanners";
|
||||
import PreviewEmptyStates from "./emptyState/PreviewEmptyStates";
|
||||
import PreviewUploadersDocument from "./uploaders/PreviewUploadersDocument";
|
||||
import PreviewPdfViewers from "./pdf/PreviewPdfViewers";
|
||||
import PreviewLoaders from "./loaders/PreviewLoaders";
|
||||
import PreviewInputs from "./input/PreviewInputs";
|
||||
// import PreviewDatepickers from "./datepickers/PreviewDatepickers";
|
||||
import PreviewDropdowns from "./dropdowns/PreviewDropdowns";
|
||||
import PreviewTabs from "./tabs/PreviewTabs";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
withSlideOvers?: boolean;
|
||||
}
|
||||
|
||||
export default function AllComponentsList({ className, withSlideOvers }: Props) {
|
||||
const [showRightSlideOver, setShowRightSlideOver] = useState(false);
|
||||
return (
|
||||
<div>
|
||||
<div className={clsx(className, "space-y-6 text-slate-900")}>
|
||||
<PreviewInputs />
|
||||
|
||||
<PreviewBreadcrumbs />
|
||||
|
||||
<PreviewTabs />
|
||||
|
||||
<PreviewButtons />
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.catalog.buttonsAsLinks")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<PreviewButtonsAsLinks />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.catalog.buttonsDestructive")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<PreviewButtonsDestructive />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PreviewDropdowns />
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.catalog.modals")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<PreviewModals />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.catalog.banners")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<PreviewBanners />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.catalog.emptyStates")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<PreviewEmptyStates />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<PreviewUploadersDocument />
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.catalog.pdfViewer")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<PreviewPdfViewers />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.catalog.loaders")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<PreviewLoaders />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{withSlideOvers && (
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.catalog.slideOvers")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<ButtonSecondary onClick={() => setShowRightSlideOver(!showRightSlideOver)}>{i18nT("components.catalog.rightSlideOver")}</ButtonSecondary>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/*SlideOver */}
|
||||
{showRightSlideOver && <SlideOver onClose={() => setShowRightSlideOver(false)}>{i18nT("components.catalog.yourContentHere")}</SlideOver>}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import * as React from "react";
|
||||
import { describe, it } from "vitest";
|
||||
|
||||
import { Button } from "./button";
|
||||
import BackButtonWithTitle from "./buttons/BackButtonWithTitle";
|
||||
import { expectNoAxeViolations } from "@toolctrl/ui-app/test-setup/axe";
|
||||
|
||||
/**
|
||||
* Complementary to button.a11y.test.tsx (which uses the static helper at
|
||||
* apps/web/app/utils/test/a11y.tsx). This file runs the full axe-core engine
|
||||
* via @toolctrl/ui-app/test-setup/axe to catch issues the static heuristic
|
||||
* can't (e.g. aria-disabled vs disabled, redundant roles).
|
||||
*/
|
||||
describe("Button axe-core a11y", () => {
|
||||
it("text button has no axe violations", async () => {
|
||||
await expectNoAxeViolations(<Button>Save changes</Button>);
|
||||
});
|
||||
|
||||
it("icon-only button with aria-label has no axe violations", async () => {
|
||||
await expectNoAxeViolations(
|
||||
<Button aria-label="Close dialog" size="icon">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M6 6l12 12M6 18L18 6" />
|
||||
</svg>
|
||||
</Button>,
|
||||
);
|
||||
});
|
||||
|
||||
it("arrow-only back button has a translated accessible name", async () => {
|
||||
await expectNoAxeViolations(<BackButtonWithTitle href="/settings">Settings</BackButtonWithTitle>);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import * as React from "react";
|
||||
import { describe, it } from "vitest";
|
||||
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "./card";
|
||||
import { expectNoAxeViolations } from "@toolctrl/ui-app/test-setup/axe";
|
||||
|
||||
describe("Card axe-core a11y", () => {
|
||||
it("Card with header + content has no axe violations", async () => {
|
||||
await expectNoAxeViolations(
|
||||
<main>
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>Plan summary</CardTitle>
|
||||
<CardDescription>Includes seats, billing cycle and renewal date.</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p>Pro plan, billed monthly.</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</main>,
|
||||
);
|
||||
});
|
||||
});
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import * as React from "react";
|
||||
import { describe, it } from "vitest";
|
||||
|
||||
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "./dialog";
|
||||
import { Button } from "./button";
|
||||
import { expectNoAxeViolations } from "@toolctrl/ui-app/test-setup/axe";
|
||||
|
||||
describe("Dialog axe-core a11y", () => {
|
||||
it("open dialog with title + description has no axe violations", async () => {
|
||||
await expectNoAxeViolations(
|
||||
<Dialog open>
|
||||
<DialogTrigger asChild>
|
||||
<Button>Open</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Confirm deletion</DialogTitle>
|
||||
<DialogDescription>This action cannot be undone.</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="destructive">Delete</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import * as React from "react";
|
||||
import { describe, it } from "vitest";
|
||||
|
||||
import { Button } from "./button";
|
||||
import { Input } from "./input";
|
||||
import { Label } from "./label";
|
||||
import { expectNoAxeViolations } from "@toolctrl/ui-app/test-setup/axe";
|
||||
|
||||
describe("Form composition axe-core a11y", () => {
|
||||
it("login-shaped form (label/input/required/submit) has no axe violations", async () => {
|
||||
await expectNoAxeViolations(
|
||||
<form aria-labelledby="signin-heading">
|
||||
<h2 id="signin-heading">Sign in</h2>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="login-email">Email</Label>
|
||||
<Input id="login-email" name="email" type="email" autoComplete="email" required aria-required="true" />
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label htmlFor="login-password">Password</Label>
|
||||
<Input
|
||||
id="login-password"
|
||||
name="password"
|
||||
type="password"
|
||||
autoComplete="current-password"
|
||||
required
|
||||
aria-required="true"
|
||||
aria-describedby="login-password-help"
|
||||
/>
|
||||
<p id="login-password-help">At least 12 characters.</p>
|
||||
</div>
|
||||
|
||||
<Button type="submit">Sign in</Button>
|
||||
</form>,
|
||||
);
|
||||
});
|
||||
});
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import * as React from "react";
|
||||
import { describe, it } from "vitest";
|
||||
|
||||
import { Input } from "./input";
|
||||
import { Label } from "./label";
|
||||
import { expectNoAxeViolations } from "@toolctrl/ui-app/test-setup/axe";
|
||||
|
||||
describe("Input axe-core a11y", () => {
|
||||
it("paired with a <Label htmlFor> has no axe violations", async () => {
|
||||
await expectNoAxeViolations(
|
||||
<div>
|
||||
<Label htmlFor="email">Email address</Label>
|
||||
<Input id="email" type="email" />
|
||||
</div>,
|
||||
);
|
||||
});
|
||||
|
||||
it("uses aria-invalid + aria-describedby for an error state without violations", async () => {
|
||||
await expectNoAxeViolations(
|
||||
<div>
|
||||
<Label htmlFor="pw">Password</Label>
|
||||
<Input id="pw" type="password" aria-invalid="true" aria-describedby="pw-err" />
|
||||
<div id="pw-err" role="alert">
|
||||
Password is required.
|
||||
</div>
|
||||
</div>,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,3 @@
|
||||
export default function Preview() {
|
||||
return <div className="w-full space-y-2">{/* */}</div>;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import * as React from "react";
|
||||
import * as AccordionPrimitive from "@radix-ui/react-accordion";
|
||||
import { ChevronRightIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Accordion({ ...props }: React.ComponentProps<typeof AccordionPrimitive.Root>) {
|
||||
return <AccordionPrimitive.Root data-slot="accordion" {...props} />;
|
||||
}
|
||||
|
||||
function AccordionItem({ className, ...props }: React.ComponentProps<typeof AccordionPrimitive.Item>) {
|
||||
return (
|
||||
<AccordionPrimitive.Item
|
||||
data-slot="accordion-item"
|
||||
// Subframe Accordion.Root (item) layout: rounded card with border + hover surface shift
|
||||
className={cn(
|
||||
"flex w-full flex-col items-start rounded-md border border-solid border-border-default bg-surface-neutral-secondary hover:bg-surface-neutral-tertiary",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AccordionTrigger({ className, children, ...props }: React.ComponentProps<typeof AccordionPrimitive.Trigger>) {
|
||||
return (
|
||||
<AccordionPrimitive.Header className="flex w-full">
|
||||
<AccordionPrimitive.Trigger
|
||||
data-slot="accordion-trigger"
|
||||
// Subframe Accordion.Trigger layout: full-width row, items-start, gap-2, chevron rotates on open
|
||||
className={cn(
|
||||
"focus-visible:border-brand-brand-border-solid-default focus-visible:shadow-focus group flex w-full flex-1 cursor-pointer items-start justify-between gap-2 rounded-md p-3 text-left text-sm font-medium transition-all outline-none disabled:pointer-events-none disabled:text-text-neutral-disabled [&[data-state=open]>svg]:rotate-90",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
{/* Subframe Chevron: FeatherChevronRight rotated 90deg on open, neutral icon color */}
|
||||
<ChevronRightIcon className="text-icon-neutral-primary pointer-events-none size-4 shrink-0 transition-transform duration-200" />
|
||||
</AccordionPrimitive.Trigger>
|
||||
</AccordionPrimitive.Header>
|
||||
);
|
||||
}
|
||||
|
||||
function AccordionContent({ className, children, ...props }: React.ComponentProps<typeof AccordionPrimitive.Content>) {
|
||||
return (
|
||||
<AccordionPrimitive.Content
|
||||
data-slot="accordion-content"
|
||||
className="data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm"
|
||||
{...props}
|
||||
>
|
||||
{/* Subframe Accordion.Content layout: full-width column, gap-2, item padding */}
|
||||
<div className={cn("flex w-full flex-col items-start gap-2 px-3 pt-0 pb-3", className)}>{children}</div>
|
||||
</AccordionPrimitive.Content>
|
||||
);
|
||||
}
|
||||
|
||||
export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
|
||||
@@ -0,0 +1,90 @@
|
||||
// // "use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { buttonVariants } from "~/components/ui/button";
|
||||
|
||||
function AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
|
||||
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogTrigger({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
|
||||
return <AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
|
||||
return <AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<AlertDialogPrimitive.Overlay
|
||||
data-slot="alert-dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDialogContent({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Content>) {
|
||||
return (
|
||||
<AlertDialogPortal>
|
||||
<AlertDialogOverlay />
|
||||
<AlertDialogPrimitive.Content
|
||||
className={cn(
|
||||
// Subframe Confirm/Result Dialog panel layout: gap-6 between blocks, rounded-lg, px-6 py-6, border-solid.
|
||||
// Radix-only pieces kept: fixed centering, max-width clamp, animation duration.
|
||||
"fixed z-50 grid w-full max-w-[calc(100%-2rem)]",
|
||||
"top-[50%] left-[50%] !translate-x-[-50%] !translate-y-[-50%] !transform",
|
||||
"bg-surface-neutral-modal rounded-lg border border-solid border-border-default px-6 py-6 shadow-lg duration-200 gap-6 sm:max-w-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</AlertDialogPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function AlertDialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return <div data-slot="alert-dialog-header" className={cn("flex flex-col gap-2 text-center sm:text-left", className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
// Subframe Confirm/Result Dialog footer: row with items-center + justify-end, gap-2; mobile stacks reversed.
|
||||
return <div data-slot="alert-dialog-footer" className={cn("flex flex-col-reverse gap-2 sm:flex-row sm:items-center sm:justify-end", className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
|
||||
return <AlertDialogPrimitive.Title data-slot="alert-dialog-title" className={cn("text-lg font-semibold", className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogDescription({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
|
||||
return <AlertDialogPrimitive.Description data-slot="alert-dialog-description" className={cn("text-text-neutral-tertiary text-sm", className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogAction({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Action>) {
|
||||
return <AlertDialogPrimitive.Action className={cn(buttonVariants(), className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertDialogCancel({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Cancel>) {
|
||||
return <AlertDialogPrimitive.Cancel className={cn(buttonVariants({ variant: "outline" }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export {
|
||||
AlertDialog,
|
||||
AlertDialogPortal,
|
||||
AlertDialogOverlay,
|
||||
AlertDialogTrigger,
|
||||
AlertDialogContent,
|
||||
AlertDialogHeader,
|
||||
AlertDialogFooter,
|
||||
AlertDialogTitle,
|
||||
AlertDialogDescription,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const alertVariants = cva(
|
||||
"relative w-full rounded-lg border px-4 py-3 text-sm grid has-[>svg]:grid-cols-[calc(var(--spacing)*4)_1fr] grid-cols-[0_1fr] has-[>svg]:gap-x-3 gap-y-0.5 items-start [&>svg]:size-4 [&>svg]:translate-y-0.5 [&>svg]:text-current",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-surface-neutral-primary text-text-neutral-primary",
|
||||
destructive: "text-text-feedback-negative bg-surface-neutral-primary [&>svg]:text-current *:data-[slot=alert-description]:text-text-feedback-negative/90",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
function Alert({ className, variant, ...props }: React.ComponentProps<"div"> & VariantProps<typeof alertVariants>) {
|
||||
return <div data-slot="alert" role="alert" className={cn(alertVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return <div data-slot="alert-title" className={cn("col-start-2 line-clamp-1 min-h-4 font-medium tracking-tight", className)} {...props} />;
|
||||
}
|
||||
|
||||
function AlertDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="alert-description"
|
||||
className={cn("text-text-neutral-tertiary col-start-2 grid justify-items-start gap-1 text-sm [&_p]:leading-relaxed", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Alert, AlertTitle, AlertDescription };
|
||||
@@ -0,0 +1,7 @@
|
||||
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio";
|
||||
|
||||
function AspectRatio({ ...props }: React.ComponentProps<typeof AspectRatioPrimitive.Root>) {
|
||||
return <AspectRatioPrimitive.Root data-slot="aspect-ratio" {...props} />;
|
||||
}
|
||||
|
||||
export { AspectRatio };
|
||||
@@ -0,0 +1,26 @@
|
||||
// // "use client";
|
||||
|
||||
import * as React from "react";
|
||||
import * as AvatarPrimitive from "@radix-ui/react-avatar";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
|
||||
return <AvatarPrimitive.Root data-slot="avatar" className={cn("relative flex size-8 shrink-0 overflow-hidden rounded-full", className)} {...props} />;
|
||||
}
|
||||
|
||||
function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
|
||||
return <AvatarPrimitive.Image data-slot="avatar-image" className={cn("aspect-square size-full", className)} {...props} />;
|
||||
}
|
||||
|
||||
function AvatarFallback({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Fallback>) {
|
||||
return (
|
||||
<AvatarPrimitive.Fallback
|
||||
data-slot="avatar-fallback"
|
||||
className={cn("bg-surface-neutral-secondary text-text-neutral-tertiary flex size-full items-center justify-center rounded-full text-xs", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Avatar, AvatarImage, AvatarFallback };
|
||||
@@ -0,0 +1,110 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center justify-center rounded-md border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-brand-brand-border-solid-default focus-visible:shadow-focus aria-invalid:shadow-focus aria-invalid:border-surface-feedback-subtle-negative transition-[color,box-shadow] overflow-hidden",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-transparent bg-brand-brand-surface-solid-default text-text-neutral-on-solid [a&]:hover:bg-brand-brand-surface-solid-hover",
|
||||
secondary: "border-transparent bg-surface-neutral-secondary text-text-neutral-primary [a&]:hover:bg-surface-neutral-tertiary",
|
||||
destructive:
|
||||
"border-transparent bg-surface-feedback-solid-negative-default text-white [a&]:hover:bg-surface-feedback-solid-negative-hover focus-visible:shadow-focus dark:bg-surface-feedback-solid-negative-default",
|
||||
outline: "text-text-neutral-primary [a&]:hover:bg-surface-neutral-secondary [a&]:hover:text-text-neutral-primary",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
export type BadgeColor = "green" | "red" | "yellow" | "blue" | "gray" | "orange" | "purple" | "emerald";
|
||||
|
||||
function getColorClasses(color: BadgeColor): string {
|
||||
switch (color) {
|
||||
case "green":
|
||||
case "emerald":
|
||||
return "border-green-500 bg-green-500/5 text-green-800 dark:text-green-300";
|
||||
case "red":
|
||||
return "border-red-500 bg-red-500/5 text-red-800 dark:text-red-300";
|
||||
case "yellow":
|
||||
return "border-yellow-500 bg-yellow-500/5 text-yellow-800 dark:text-yellow-300";
|
||||
case "blue":
|
||||
return "border-blue-500 bg-blue-500/5 text-blue-800 dark:text-blue-300";
|
||||
case "orange":
|
||||
return "border-orange-500 bg-orange-500/5 text-orange-800 dark:text-orange-300";
|
||||
case "purple":
|
||||
return "border-purple-500 bg-purple-500/5 text-purple-800 dark:text-purple-300";
|
||||
case "gray":
|
||||
default:
|
||||
return "border-gray-500 bg-gray-500/5 text-gray-800 dark:text-gray-300";
|
||||
}
|
||||
}
|
||||
|
||||
function getDotColor(color: BadgeColor): string {
|
||||
switch (color) {
|
||||
case "green":
|
||||
case "emerald":
|
||||
return "bg-green-400";
|
||||
case "red":
|
||||
return "bg-red-400";
|
||||
case "yellow":
|
||||
return "bg-yellow-400";
|
||||
case "blue":
|
||||
return "bg-blue-400";
|
||||
case "orange":
|
||||
return "bg-orange-400";
|
||||
case "purple":
|
||||
return "bg-purple-400";
|
||||
case "gray":
|
||||
default:
|
||||
return "bg-gray-400";
|
||||
}
|
||||
}
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
color,
|
||||
withColorDot = false,
|
||||
asChild = false,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> &
|
||||
VariantProps<typeof badgeVariants> & {
|
||||
asChild?: boolean;
|
||||
color?: BadgeColor;
|
||||
withColorDot?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "span";
|
||||
|
||||
// If color is provided, use color-based styling
|
||||
if (color) {
|
||||
return (
|
||||
<Comp
|
||||
data-slot="badge"
|
||||
className={cn(
|
||||
"inline-flex w-fit shrink-0 items-center justify-center gap-1.5 overflow-hidden rounded-md border px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow]",
|
||||
getColorClasses(color),
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{withColorDot && <span className={cn("size-2 shrink-0 rounded-full", getDotColor(color))} />}
|
||||
{children}
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Comp data-slot="badge" className={cn(badgeVariants({ variant }), className)} {...props}>
|
||||
{children}
|
||||
</Comp>
|
||||
);
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants, getColorClasses, getDotColor };
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import clsx from "clsx";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { getBadgeColor } from "~/utils/shared/ColorUtils";
|
||||
|
||||
interface Props {
|
||||
color?: Colors | null;
|
||||
size?: "sm" | "md";
|
||||
}
|
||||
|
||||
export default function ColorBadge({ color, size = "md" }: Props) {
|
||||
return (
|
||||
<span
|
||||
className={clsx(
|
||||
" inline-flex shrink-0 items-center rounded-full text-xs font-medium",
|
||||
getBadgeColor(color),
|
||||
size === "md" && "p-1",
|
||||
size === "sm" && "p-0.5"
|
||||
)}
|
||||
>
|
||||
<svg className={clsx(size === "md" && "h-2 w-2", size === "sm" && "h-1.5 w-1.5")} fill="currentColor" viewBox="0 0 8 8">
|
||||
<circle cx={4} cy={4} r={3} />
|
||||
</svg>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import clsx from "clsx";
|
||||
|
||||
interface Props {
|
||||
color?: string | null;
|
||||
size?: "xs" | "sm" | "md";
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export default function ColorBadgeString({ color, size = "md", children, className }: Props) {
|
||||
function getColors() {
|
||||
switch (color) {
|
||||
case "primary":
|
||||
return { bgColor: "bg-brand-brand-surface-solid-default", textColor: "text-brand-brand-surface-solid-default" };
|
||||
case "sky":
|
||||
return { bgColor: "bg-sky-400", textColor: "text-sky-800" };
|
||||
case "amber":
|
||||
return { bgColor: "bg-amber-400", textColor: "text-amber-800" };
|
||||
case "violet":
|
||||
return { bgColor: "bg-violet-400", textColor: "text-violet-800" };
|
||||
case "rose":
|
||||
return { bgColor: "bg-rose-400", textColor: "text-rose-800" };
|
||||
case "emerald":
|
||||
return { bgColor: "bg-emerald-400", textColor: "text-emerald-800" };
|
||||
case "orange":
|
||||
return { bgColor: "bg-orange-400", textColor: "text-orange-800" };
|
||||
case "blue":
|
||||
return { bgColor: "bg-blue-400", textColor: "text-blue-800" };
|
||||
case "gray":
|
||||
return { bgColor: "bg-gray-400", textColor: "text-gray-800" };
|
||||
case "green":
|
||||
return { bgColor: "bg-green-400", textColor: "text-green-800" };
|
||||
case "yellow":
|
||||
return { bgColor: "bg-yellow-400", textColor: "text-yellow-800" };
|
||||
case "red":
|
||||
return { bgColor: "bg-red-400", textColor: "text-red-800" };
|
||||
case "pink":
|
||||
return { bgColor: "bg-pink-400", textColor: "text-pink-800" };
|
||||
case "purple":
|
||||
return { bgColor: "bg-purple-400", textColor: "text-purple-800" };
|
||||
case "indigo":
|
||||
return { bgColor: "bg-indigo-400", textColor: "text-indigo-800" };
|
||||
case "teal":
|
||||
return { bgColor: "bg-teal-400", textColor: "text-teal-800" };
|
||||
case "cyan":
|
||||
return { bgColor: "bg-cyan-400", textColor: "text-cyan-800" };
|
||||
default:
|
||||
return { bgColor: "bg-gray-400", textColor: "text-gray-800" };
|
||||
}
|
||||
}
|
||||
const { bgColor, textColor } = getColors();
|
||||
return <div className={clsx("inline-flex shrink-0 items-center rounded-full text-xs font-medium", bgColor, textColor, "size-2", className)}>{children}</div>;
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import ColorBadge from "./ColorBadge";
|
||||
|
||||
export default function PreviewBadges() {
|
||||
return (
|
||||
<div id="badges">
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<div id="badges" className="w-full space-y-2">
|
||||
<div className="mx-auto flex max-w-3xl flex-col items-center justify-center space-y-4 sm:flex-row sm:items-end sm:justify-center sm:space-x-4 sm:space-y-0">
|
||||
<ColorBadge color={Colors.UNDEFINED} />
|
||||
<ColorBadge color={Colors.SLATE} />
|
||||
<ColorBadge color={Colors.GRAY} />
|
||||
<ColorBadge color={Colors.NEUTRAL} />
|
||||
<ColorBadge color={Colors.STONE} />
|
||||
<ColorBadge color={Colors.RED} />
|
||||
<ColorBadge color={Colors.ORANGE} />
|
||||
<ColorBadge color={Colors.AMBER} />
|
||||
<ColorBadge color={Colors.YELLOW} />
|
||||
<ColorBadge color={Colors.LIME} />
|
||||
<ColorBadge color={Colors.GREEN} />
|
||||
<ColorBadge color={Colors.EMERALD} />
|
||||
<ColorBadge color={Colors.TEAL} />
|
||||
<ColorBadge color={Colors.CYAN} />
|
||||
<ColorBadge color={Colors.SKY} />
|
||||
<ColorBadge color={Colors.BLUE} />
|
||||
<ColorBadge color={Colors.INDIGO} />
|
||||
<ColorBadge color={Colors.VIOLET} />
|
||||
<ColorBadge color={Colors.PURPLE} />
|
||||
<ColorBadge color={Colors.FUCHSIA} />
|
||||
<ColorBadge color={Colors.PINK} />
|
||||
<ColorBadge color={Colors.ROSE} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import SimpleBadge from "./SimpleBadge";
|
||||
|
||||
export default function PreviewBadges() {
|
||||
return (
|
||||
<div id="badges-simple">
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<div id="badges" className="w-full space-y-2">
|
||||
<div className="mx-auto flex max-w-3xl flex-col items-center justify-center space-y-4 sm:flex-row sm:items-end sm:justify-center sm:space-x-4 sm:space-y-0">
|
||||
<SimpleBadge title={"GRAY"} color={Colors.GRAY} />
|
||||
<SimpleBadge title={"RED"} color={Colors.RED} />
|
||||
<SimpleBadge title={"ORANGE"} color={Colors.ORANGE} />
|
||||
<SimpleBadge title={"YELLOW"} color={Colors.YELLOW} />
|
||||
<SimpleBadge title={"GREEN"} color={Colors.GREEN} />
|
||||
<SimpleBadge title={"BLUE"} color={Colors.BLUE} />
|
||||
<SimpleBadge title={"INDIGO"} color={Colors.INDIGO} />
|
||||
<SimpleBadge title={"PURPLE"} color={Colors.PURPLE} />
|
||||
<SimpleBadge title={"PINK"} color={Colors.PINK} />
|
||||
<SimpleBadge title={"ROSE"} color={Colors.ROSE} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
import clsx from "~/utils/shared/ClassesUtils";
|
||||
import { StarIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
export default function RatingBadge({ value, size = 4, starsCount = 5 }: { value: number; size?: number; starsCount?: number }) {
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center">
|
||||
{Array.from({ length: starsCount }).map((_, index) => (
|
||||
<Star key={index} size={size} color={index < value ? "yellow" : "gray"} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Star({ color, size = 5 }: { color: "gray" | "yellow"; size?: number }) {
|
||||
return (
|
||||
<StarIcon
|
||||
aria-hidden="true"
|
||||
className={clsx(
|
||||
size === 2 && "h-2 w-2",
|
||||
size === 3 && "h-3 w-3",
|
||||
size === 4 && "h-4 w-4",
|
||||
size === 5 && "h-5 w-5",
|
||||
size === 6 && "h-6 w-6",
|
||||
size === 7 && "h-7 w-7",
|
||||
color === "gray" ? "text-gray-300" : "text-yellow-400"
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
import clsx from "clsx";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { getBadgeColor, getBadgeColorDark } from "~/utils/shared/ColorUtils";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
color: Colors;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
underline?: boolean;
|
||||
darkMode?: boolean;
|
||||
}
|
||||
|
||||
export default function SimpleBadge({ title, color, className, children, underline, darkMode }: Props) {
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
className,
|
||||
!underline && "inline-flex",
|
||||
"items-center rounded-md px-1 py-0 text-xs font-bold",
|
||||
getBadgeColor(color),
|
||||
getBadgeColorDark(color)
|
||||
)}
|
||||
>
|
||||
{title ?? children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
import clsx from "clsx";
|
||||
import { Colors } from "~/application/enums/shared/Colors";
|
||||
import { getTextColor } from "~/utils/shared/ColorUtils";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
color: Colors;
|
||||
className?: string;
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export default function TextColor({ title, color, className, children }: Props) {
|
||||
return <div className={clsx(className, getTextColor(color))}>{title ?? children}</div>;
|
||||
}
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
import { XIcon } from "~/components/ui/icons/vendor";
|
||||
import { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import { BannerAlert } from "~/ui/components/BannerAlert";
|
||||
|
||||
// Subframe migration (strangler shim):
|
||||
// Keeps the original ErrorBanner API but renders the Subframe design-system BannerAlert
|
||||
// (type="error"). BannerAlert has no separate title slot, so the title is composed into the
|
||||
// content (rendered bold) alongside text/redirect/children — same as before, all ReactNode.
|
||||
// `redirect` maps to BannerAlert's `actionLabel` (the underlined action). `onDismiss` is NOT
|
||||
// mapped to BannerAlert's `dismissible` button because that button is a non-functional design
|
||||
// mock (no onClick); the original functional dismiss button is overlaid to preserve behavior.
|
||||
|
||||
interface Props {
|
||||
title?: ReactNode;
|
||||
text?: ReactNode | string;
|
||||
redirect?: string;
|
||||
children?: ReactNode;
|
||||
onDismiss?: () => void;
|
||||
}
|
||||
|
||||
export default function ErrorBanner({ title, text = "", redirect, children, onDismiss }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div className="not-prose relative">
|
||||
<BannerAlert
|
||||
type="error"
|
||||
fillContainer
|
||||
actionLabel={
|
||||
redirect ? (
|
||||
<Link to={redirect}>
|
||||
{t("shared.goTo")} {redirect}
|
||||
</Link>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<span className="font-medium">{title ?? t("shared.error")}</span>{" "}
|
||||
{text}
|
||||
{children}
|
||||
</BannerAlert>
|
||||
|
||||
{onDismiss && (
|
||||
<div className="absolute top-4 right-4">
|
||||
<button type="button" onClick={onDismiss} className="text-red-600 hover:text-red-800 dark:text-red-400 dark:hover:text-red-200">
|
||||
<span className="sr-only">{t("shared.close")}</span>
|
||||
<XIcon className="size-4" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import { BannerAlert } from "~/ui/components/BannerAlert";
|
||||
|
||||
// Subframe migration (strangler shim):
|
||||
// Keeps the original InfoBanner API but renders the Subframe design-system BannerAlert
|
||||
// (type="information"). BannerAlert has no separate title slot, so the title is composed into the
|
||||
// content (rendered bold) alongside text/redirect/children — same as before, all ReactNode.
|
||||
// `redirect` maps to BannerAlert's `actionLabel` (the underlined action).
|
||||
|
||||
interface Props {
|
||||
title?: ReactNode;
|
||||
text?: ReactNode | string;
|
||||
redirect?: string;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export default function InfoBanner({ title, text = "", redirect, children }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<BannerAlert
|
||||
className="not-prose"
|
||||
type="information"
|
||||
fillContainer
|
||||
actionLabel={
|
||||
redirect ? (
|
||||
<Link to={redirect}>
|
||||
{t("shared.goTo")} {redirect}
|
||||
</Link>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<span className="font-medium">{title ?? t("shared.note")}</span>{" "}
|
||||
{text}
|
||||
{children}
|
||||
</BannerAlert>
|
||||
);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
import InfoBanner from "./InfoBanner";
|
||||
import { t as i18nT } from "i18next";
|
||||
import WarningBanner from "./WarningBanner";
|
||||
|
||||
export default function PreviewBanners() {
|
||||
return (
|
||||
<div id="banners" className="not-prose text-foreground w-full space-y-2">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.banners.preview.info")}</h3>
|
||||
<InfoBanner title={i18nT("components.banners.preview.infoTitle")} text={i18nT("components.banners.preview.sampleText")} />
|
||||
|
||||
<h3 className="text-sm font-medium">{i18nT("components.banners.preview.warning")}</h3>
|
||||
<WarningBanner title={i18nT("components.banners.preview.warning")} text={i18nT("components.banners.preview.sampleText")} />
|
||||
|
||||
<h3 className="text-sm font-medium">{i18nT("components.banners.preview.warningWithLink")}</h3>
|
||||
<WarningBanner
|
||||
title={i18nT("components.banners.preview.warningWithRedirect")}
|
||||
text={i18nT("components.banners.preview.sampleText")}
|
||||
redirect="https://www.example.com"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import { BannerAlert } from "~/ui/components/BannerAlert";
|
||||
|
||||
// Subframe migration (strangler shim):
|
||||
// Keeps the original SuccessBanner API but renders the Subframe design-system BannerAlert
|
||||
// (type="success"). BannerAlert has no separate title slot, so the (optional, translated) title
|
||||
// is composed into the content (rendered bold) alongside text/redirect/children. As before, the
|
||||
// title is only shown when provided and is passed through `t()`. `redirect` maps to
|
||||
// BannerAlert's `actionLabel` (the underlined action).
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
text?: ReactNode | string;
|
||||
redirect?: string;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export default function SuccessBanner({ title, text = "", redirect, children }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<BannerAlert
|
||||
className="not-prose"
|
||||
type="success"
|
||||
fillContainer
|
||||
actionLabel={
|
||||
redirect ? (
|
||||
<Link to={redirect}>
|
||||
{t("shared.goTo")} {redirect}
|
||||
</Link>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{title && <span className="font-medium">{t(title)} </span>}
|
||||
{text}
|
||||
{children}
|
||||
</BannerAlert>
|
||||
);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
import { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import { BannerAlert } from "~/ui/components/BannerAlert";
|
||||
|
||||
// Subframe migration (strangler shim):
|
||||
// Keeps the original WarningBanner API but renders the Subframe design-system BannerAlert
|
||||
// (type="warning"). BannerAlert has no separate title slot, so the title is composed into the
|
||||
// content (rendered bold) alongside text/redirect/children — same as before, all ReactNode.
|
||||
// `redirect` maps to BannerAlert's `actionLabel` (the underlined action).
|
||||
|
||||
interface Props {
|
||||
title?: ReactNode;
|
||||
text?: ReactNode;
|
||||
redirect?: string;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export default function WarningBanner({ title, text = "", redirect, children }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<BannerAlert
|
||||
className="not-prose"
|
||||
type="warning"
|
||||
fillContainer
|
||||
actionLabel={
|
||||
redirect ? (
|
||||
<Link to={redirect}>
|
||||
{t("shared.goTo")} {redirect}
|
||||
</Link>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<span className="font-medium">{title ?? t("shared.warning")}</span>{" "}
|
||||
{text}
|
||||
{children}
|
||||
</BannerAlert>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
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";
|
||||
|
||||
function Breadcrumb({ ...props }: React.ComponentProps<"nav">) {
|
||||
return <nav aria-label={i18nT("components.breadcrumb.ariaLabel")} data-slot="breadcrumb" {...props} />;
|
||||
}
|
||||
|
||||
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
|
||||
return (
|
||||
<ol
|
||||
data-slot="breadcrumb-list"
|
||||
// Subframe Breadcrumbs layout: BreadcrumbsRoot "flex items-center gap-2", 14px text
|
||||
className={cn("text-text-neutral-tertiary flex flex-wrap items-center gap-2 text-sm leading-5 break-words", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
|
||||
// Subframe Breadcrumbs layout: uniform gap-2 between item content
|
||||
return <li data-slot="breadcrumb-item" className={cn("inline-flex items-center gap-2", className)} {...props} />;
|
||||
}
|
||||
|
||||
function BreadcrumbLink({
|
||||
asChild,
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"a"> & {
|
||||
asChild?: boolean;
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "a";
|
||||
|
||||
return <Comp data-slot="breadcrumb-link" className={cn("hover:text-text-neutral-primary transition-colors", className)} {...props} />;
|
||||
}
|
||||
|
||||
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-page"
|
||||
role="link"
|
||||
aria-disabled="true"
|
||||
aria-current="page"
|
||||
className={cn("text-text-neutral-primary font-normal", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function BreadcrumbSeparator({ children, className, ...props }: React.ComponentProps<"li">) {
|
||||
return (
|
||||
<li data-slot="breadcrumb-separator" role="presentation" aria-hidden="true" className={cn("[&>svg]:size-3.5", className)} {...props}>
|
||||
{children ?? <ChevronRightIcon />}
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function BreadcrumbEllipsis({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="breadcrumb-ellipsis"
|
||||
role="presentation"
|
||||
aria-hidden="true"
|
||||
className={cn("flex size-9 items-center justify-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<DotsHorizontalIcon className="size-4" />
|
||||
<span className="sr-only">{i18nT("shared.more")}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export { Breadcrumb, BreadcrumbList, BreadcrumbItem, BreadcrumbLink, BreadcrumbPage, BreadcrumbSeparator, BreadcrumbEllipsis };
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
import { Link, useParams } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { adminPath } from "~/utils/app/CanonicalUrlUtils";
|
||||
import UrlUtils from "~/utils/app/UrlUtils";
|
||||
import { HomeIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface MenuItem {
|
||||
title: string;
|
||||
routePath?: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
menu: MenuItem[];
|
||||
className?: string;
|
||||
home?: string;
|
||||
}
|
||||
|
||||
export default function Breadcrumb({ className = "", home = "", menu = [] }: Props) {
|
||||
const params = useParams();
|
||||
const { t } = useTranslation();
|
||||
function getHomeItem() {
|
||||
if (params.tenant) {
|
||||
return UrlUtils.currentTenantUrl(params, "dashboard");
|
||||
} else {
|
||||
return adminPath("dashboard", { mode: "host-aware" });
|
||||
}
|
||||
}
|
||||
return (
|
||||
<nav className={clsx(className, "border-border-default bg-surface-neutral-primary flex overflow-x-auto border-b")} aria-label={t("components.breadcrumb.ariaLabel")}>
|
||||
<ol className="flex w-full max-w-(--breakpoint-xl) space-x-4 px-4 sm:px-6 lg:px-8">
|
||||
<li className="flex">
|
||||
<div className="flex items-center">
|
||||
<Link to={home.length > 0 ? home : getHomeItem()} className="hover:text-text-neutral-tertiary text-text-neutral-tertiary">
|
||||
<HomeIcon className="h-5 w-5 shrink-0" aria-hidden="true" />
|
||||
<span className="sr-only">{t("shared.home")}</span>
|
||||
</Link>
|
||||
</div>
|
||||
</li>
|
||||
{menu.map((item, idx) => {
|
||||
return (
|
||||
<li key={idx} className="flex">
|
||||
<div className="flex items-center">
|
||||
<svg
|
||||
className="h-full w-5 shrink-0 text-gray-200 sm:w-6"
|
||||
viewBox="0 0 24 44"
|
||||
preserveAspectRatio="none"
|
||||
fill="currentColor"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M.293 0l22 22-22 22h1.414l22-22-22-22H.293z" />
|
||||
</svg>
|
||||
|
||||
{/* Subframe Breadcrumbs typo: 14px/normal item text (font-[400] leading-[20px]) */}
|
||||
{(() => {
|
||||
if (!item.routePath) {
|
||||
return (
|
||||
<div className="text-text-neutral-tertiary hover:text-text-neutral-primary ml-2 select-none truncate text-sm font-normal leading-5 sm:ml-4">
|
||||
{item.title}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<Link to={item.routePath} className="text-text-neutral-tertiary hover:text-text-neutral-primary ml-2 truncate text-sm font-normal leading-5 sm:ml-4">
|
||||
{item.title}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
})()}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import clsx from "clsx";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Link } from "react-router";
|
||||
import RightIcon from "../icons/RightIcon";
|
||||
import { HomeIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface MenuItem {
|
||||
title: string;
|
||||
routePath?: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
menu: MenuItem[];
|
||||
className?: string;
|
||||
home?: string;
|
||||
}
|
||||
|
||||
export default function BreadcrumbSimple({ menu = [], className = "", home = "" }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<nav className={clsx("not-prose flex truncate", className)} aria-label={t("components.breadcrumb.ariaLabel")}>
|
||||
{/* Subframe Breadcrumbs layout: BreadcrumbsRoot "flex items-center gap-2" */}
|
||||
<ol className="flex items-center gap-2">
|
||||
{home && (
|
||||
<li>
|
||||
<div>
|
||||
<Link to={home.length > 0 ? home : "/"} className="hover:text-text-neutral-tertiary text-gray-300">
|
||||
<HomeIcon className="h-4 w-4 shrink-0" aria-hidden="true" />
|
||||
<span className="sr-only">{t("shared.home")}</span>
|
||||
</Link>
|
||||
</div>
|
||||
</li>
|
||||
)}
|
||||
{menu
|
||||
.filter((f) => f.title)
|
||||
.map((item, idx) => (
|
||||
<li key={item.title}>
|
||||
{/* Subframe Breadcrumbs layout: uniform gap-2, divider sized to 14px text */}
|
||||
<div className="flex items-center gap-2">
|
||||
{(idx > 0 || home) && <RightIcon className="text-text-neutral-tertiary h-3.5 w-3.5 shrink-0" />}
|
||||
{item.routePath ? (
|
||||
<Link
|
||||
to={item.routePath}
|
||||
className="hover:text-text-neutral-tertiary text-text-neutral-tertiary select-none text-sm leading-5 font-normal"
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
) : (
|
||||
<span className="text-text-neutral-tertiary select-none text-sm leading-5 font-normal">{item.title}</span>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { useLocation } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import Breadcrumb from "./Breadcrumb";
|
||||
import BreadcrumbSimple from "./BreadcrumbSimple";
|
||||
|
||||
export default function PreviewBreadcrumbs() {
|
||||
const currentRoute = useLocation().pathname;
|
||||
return (
|
||||
<div id="breadcrumbs" className="not-prose w-full">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.breadcrumb.preview.breadcrumb")}</h3>
|
||||
<div className="border-border flex items-center space-x-2 border border-dashed p-2">
|
||||
<Breadcrumb
|
||||
className="w-full"
|
||||
home="/"
|
||||
menu={[
|
||||
{ title: i18nT("components.breadcrumb.preview.docs"), routePath: "/docs" },
|
||||
{ title: i18nT("components.catalog.title"), routePath: "/docs/components" },
|
||||
{ title: i18nT("components.breadcrumb.preview.breadcrumbs"), routePath: currentRoute },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<h3 className="text-sm font-medium">{i18nT("components.breadcrumb.preview.simple")}</h3>
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<BreadcrumbSimple
|
||||
className="not-prose w-full"
|
||||
home="/"
|
||||
menu={[
|
||||
{ title: i18nT("components.breadcrumb.preview.docs"), routePath: "/docs" },
|
||||
{ title: i18nT("components.catalog.title"), routePath: "/docs/components" },
|
||||
{ title: i18nT("components.breadcrumb.preview.breadcrumbs"), routePath: currentRoute },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
import { useRef, useState } 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";
|
||||
|
||||
interface Props {
|
||||
type?: "button" | "submit";
|
||||
variant: "default" | "outline" | "ghost" | "link" | "destructive" | "secondary";
|
||||
size?: "xs" | "icon" | "default" | "sm" | "lg";
|
||||
children: React.ReactNode;
|
||||
title?: string;
|
||||
description?: string;
|
||||
confirmText?: string;
|
||||
cancelText?: string;
|
||||
onClick: () => void;
|
||||
isLoading?: boolean;
|
||||
destructive?: boolean;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
export default function ButtonConfirm({
|
||||
type = "button",
|
||||
variant = "default",
|
||||
size = "default",
|
||||
children,
|
||||
title,
|
||||
description,
|
||||
confirmText,
|
||||
cancelText,
|
||||
onClick,
|
||||
isLoading,
|
||||
destructive = true,
|
||||
className,
|
||||
disabled,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const confirmDialog = useRef<RefConfirmDialog>(null);
|
||||
|
||||
const onShowDialog = () => {
|
||||
confirmDialog.current?.show({
|
||||
title: title || t("shared.confirmDelete"),
|
||||
description,
|
||||
destructive,
|
||||
confirmText: confirmText || t("shared.confirm"),
|
||||
cancelText: cancelText || t("shared.cancel"),
|
||||
onConfirm: () => onClick(),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Button
|
||||
type={type}
|
||||
variant={variant}
|
||||
size={size}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
onShowDialog();
|
||||
}}
|
||||
isLoading={isLoading}
|
||||
className={className}
|
||||
disabled={disabled}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
|
||||
{/* <ModalOrSlide title={title} type="dialog" open={isOpen.open} setOpen={() => setIsOpen({ ...isOpen, open: false })} size="sm">
|
||||
<Form
|
||||
method="post"
|
||||
className="space-y-2 p-4"
|
||||
onSubmit={() => {
|
||||
onClick(isOpen.value);
|
||||
setIsOpen({ open: false, value: "" });
|
||||
}}
|
||||
>
|
||||
<Label>{label}</Label>
|
||||
<Input value={isOpen.value} onChange={(e) => setIsOpen({ open: true, value: e.target.value })} />
|
||||
<div className="flex justify-end">
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setIsOpen({ open: false, value: "" })}>
|
||||
Accept
|
||||
</Button>
|
||||
</div>
|
||||
</Form>
|
||||
</ModalOrSlide> */}
|
||||
|
||||
<ConfirmDialog ref={confirmDialog} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import * as React from "react";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Button } from "./button";
|
||||
import { Tabs as TabsComponent, TabsList, TabsTrigger } from "./tabs";
|
||||
import { ButtonGroup as SubframeButtonGroup } from "~/ui/components/ButtonGroup";
|
||||
import { Fragment, useState } from "react";
|
||||
import { Link } from "react-router";
|
||||
import HintTooltip from "./tooltips/HintTooltip";
|
||||
|
||||
interface ButtonGroupProps {
|
||||
items: {
|
||||
name: string;
|
||||
href?: string;
|
||||
target?: string;
|
||||
component?: React.ReactNode;
|
||||
hidden?: boolean;
|
||||
onClick?: () => void;
|
||||
active?: boolean;
|
||||
disabled?: boolean;
|
||||
}[];
|
||||
variant?: "default" | "tabs";
|
||||
size?: "xs" | "sm" | "default" | "lg";
|
||||
className?: string;
|
||||
}
|
||||
export function ButtonGroup({ items, variant = "tabs", size = "sm", className }: ButtonGroupProps) {
|
||||
let activeItems = items.filter((item) => !item.hidden);
|
||||
const [value, setValue] = useState(activeItems.find((item) => item.active)?.name || (activeItems.length > 0 ? activeItems[0].name : ""));
|
||||
if (variant === "tabs") {
|
||||
return (
|
||||
<TabsComponent value={value} onValueChange={(v) => setValue(v)} className={cn(className)}>
|
||||
<TabsList className="w-full">
|
||||
{activeItems.map((item) =>
|
||||
item.href ? (
|
||||
<TabsTrigger
|
||||
key={item.name}
|
||||
value={item.name}
|
||||
onClick={item.onClick}
|
||||
className={cn(item.active && "bg-secondary text-secondary-foreground")}
|
||||
asChild
|
||||
>
|
||||
<Link to={item.href} target={item.target}>
|
||||
{item.component || item.name}
|
||||
</Link>
|
||||
</TabsTrigger>
|
||||
) : (
|
||||
<TabsTrigger key={item.name} value={item.name} onClick={item.onClick} className={cn(item.active && "bg-secondary text-secondary-foreground")}>
|
||||
{item.component || item.name}
|
||||
</TabsTrigger>
|
||||
)
|
||||
)}
|
||||
</TabsList>
|
||||
</TabsComponent>
|
||||
);
|
||||
}
|
||||
return (
|
||||
// Subframe ButtonGroup `variant="split"` (gap-0) is the design-system container for the
|
||||
// connected-button row. The original `isolate inline-flex rounded-md` look + width sizing
|
||||
// are restored via className (neutralizing Subframe's `w-full`); per-button border/radius
|
||||
// math stays on the buttons, unchanged.
|
||||
<SubframeButtonGroup variant="split" align="start" className={cn("isolate inline-flex w-fit rounded-md", className)}>
|
||||
{activeItems.map((item, idx) => (
|
||||
<Fragment key={item.name}>
|
||||
<Button
|
||||
size={size}
|
||||
variant="outline"
|
||||
type="button"
|
||||
onClick={(e) => {
|
||||
// e.preventDefault();
|
||||
e.stopPropagation();
|
||||
item.onClick?.();
|
||||
}}
|
||||
className={cn(
|
||||
item.active && "bg-secondary text-secondary-foreground",
|
||||
idx > 0 && idx < activeItems.length - 1 && "rounded-none border-x-0",
|
||||
idx === 0 && "rounded-l-md rounded-r-none border-r-0",
|
||||
idx === activeItems.length - 1 && "rounded-l-none rounded-r-md border-l-0",
|
||||
idx < activeItems.length - 1 && "border-r"
|
||||
)}
|
||||
asChild={item.href ? true : false}
|
||||
disabled={item.disabled}
|
||||
>
|
||||
{item.href && !item.disabled ? (
|
||||
<Link to={item.href} target={item.target}>
|
||||
{item.component ? (
|
||||
<HintTooltip text={<div className="overflow-hidden">{item.name}</div>}>
|
||||
<span>{item.component || item.name}</span>
|
||||
</HintTooltip>
|
||||
) : (
|
||||
<div>{item.name}</div>
|
||||
)}
|
||||
</Link>
|
||||
) : (
|
||||
<span>{item.component || item.name}</span>
|
||||
)}
|
||||
</Button>
|
||||
</Fragment>
|
||||
))}
|
||||
</SubframeButtonGroup>
|
||||
);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import * as React from "react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Button } from "./button";
|
||||
import { expectNoA11yViolations, findA11yViolations } from "~/utils/test/a11y";
|
||||
import { render } from "@testing-library/react";
|
||||
|
||||
describe("Button a11y", () => {
|
||||
it("renders text button without a11y violations", async () => {
|
||||
await expectNoA11yViolations(<Button>Save changes</Button>);
|
||||
});
|
||||
|
||||
it("icon-only button passes when aria-label is supplied", async () => {
|
||||
await expectNoA11yViolations(
|
||||
<Button aria-label="Close dialog" size="icon">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M6 6l12 12M6 18L18 6" />
|
||||
</svg>
|
||||
</Button>
|
||||
);
|
||||
});
|
||||
|
||||
it("disabled button keeps its accessible name", async () => {
|
||||
await expectNoA11yViolations(
|
||||
<Button disabled>Submitting</Button>
|
||||
);
|
||||
});
|
||||
|
||||
it("destructive variant with text passes", async () => {
|
||||
await expectNoA11yViolations(<Button variant="destructive">Delete</Button>);
|
||||
});
|
||||
|
||||
it("icon-only button WITHOUT an accessible name is flagged (negative control)", () => {
|
||||
const { container } = render(
|
||||
<Button size="icon">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true">
|
||||
<path d="M6 6l12 12M6 18L18 6" />
|
||||
</svg>
|
||||
</Button>
|
||||
);
|
||||
const violations = findA11yViolations(container);
|
||||
expect(violations.some((v) => v.rule === "button-name")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { Button as SubframeButton } from "~/ui/components/Button";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
// Subframe migration (strangler shim):
|
||||
// This file keeps the original shadcn `Button` API but renders the Subframe design-system
|
||||
// Button for the common case. The legacy shadcn rendering is retained for:
|
||||
// - `asChild` (polymorphic Link-as-button), and `size="icon"` — neither is expressible with
|
||||
// Subframe's Button; these migrate to Subframe LinkButton / IconButton later, and
|
||||
// - external consumers that import `buttonVariants` directly (alert-dialog, calendar,
|
||||
// pagination, json/ShowModalButton).
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",
|
||||
destructive:
|
||||
"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
|
||||
outline: "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",
|
||||
secondary: "bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
xs: "h-7 rounded-md px-2 text-xs",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
// shadcn variant/size -> Subframe Button props. See docs/subframe/COMPONENT-MAPPING.md.
|
||||
const SUBFRAME_VARIANT = {
|
||||
default: "primary",
|
||||
destructive: "destructive",
|
||||
outline: "tertiary",
|
||||
secondary: "secondary",
|
||||
ghost: "ghost",
|
||||
link: "ghost",
|
||||
} as const;
|
||||
|
||||
const SUBFRAME_SIZE = {
|
||||
default: "medium",
|
||||
xs: "small",
|
||||
sm: "small",
|
||||
lg: "large",
|
||||
icon: "medium",
|
||||
} as const;
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
isLoading = false,
|
||||
dirty = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean;
|
||||
isLoading?: boolean;
|
||||
dirty?: boolean;
|
||||
}) {
|
||||
const dirtyClass = dirty ? "bg-yellow-50 dark:bg-yellow-100 dark:text-yellow-900" : undefined;
|
||||
|
||||
// Legacy shadcn path — preserves exact original behavior for polymorphic and icon buttons.
|
||||
if (asChild || size === "icon") {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }), isLoading && "base-spinner", dirtyClass)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Default path — Subframe design-system Button behind the shadcn API.
|
||||
// `type` keeps the native HTML default ("submit") rather than Subframe's forced "button",
|
||||
// so form-submit buttons that rely on the implicit default keep working.
|
||||
return (
|
||||
<SubframeButton
|
||||
{...props}
|
||||
variant={SUBFRAME_VARIANT[variant ?? "default"]}
|
||||
size={SUBFRAME_SIZE[size ?? "default"]}
|
||||
loading={isLoading}
|
||||
type={props.type ?? "submit"}
|
||||
className={cn(dirtyClass, className)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Button, buttonVariants };
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import { Button } from "../button";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { t as i18nT } from "i18next";
|
||||
|
||||
export default function BackButtonWithTitle({
|
||||
href,
|
||||
children,
|
||||
className,
|
||||
size = "xs",
|
||||
}: {
|
||||
href: string;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
size?: "default" | "sm" | "xs" | "sm" | "lg";
|
||||
}) {
|
||||
return (
|
||||
<div className={cn("flex items-center space-x-2 truncate", className)}>
|
||||
<Button size={size} variant="outline" asChild className="truncate font-normal">
|
||||
<a href={href} aria-label={i18nT("shared.back")}>
|
||||
←
|
||||
</a>
|
||||
</Button>
|
||||
<div className="truncate">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+83
@@ -0,0 +1,83 @@
|
||||
import { useLocation, useMatches } from "react-router";
|
||||
import { ReactNode } from "react";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import AnalyticsHelper from "~/utils/helpers/AnalyticsHelper";
|
||||
import LinkOrAhref from "./LinkOrAhref";
|
||||
import clsx from "clsx";
|
||||
|
||||
const DEBUG_MODE = false;
|
||||
|
||||
interface Props {
|
||||
type?: "button" | "submit";
|
||||
to?: string | undefined;
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
target?: undefined | "_blank";
|
||||
role?: string;
|
||||
rel?: string;
|
||||
event: {
|
||||
action: string;
|
||||
category: string;
|
||||
label: string;
|
||||
value: string;
|
||||
};
|
||||
onClick?: () => void;
|
||||
sendEvent?: boolean;
|
||||
disabled?: boolean;
|
||||
isLoading?: boolean;
|
||||
reloadDocument?: boolean;
|
||||
}
|
||||
export default function ButtonEvent({
|
||||
type,
|
||||
to,
|
||||
target,
|
||||
children,
|
||||
className,
|
||||
role,
|
||||
rel,
|
||||
event,
|
||||
onClick,
|
||||
sendEvent = true,
|
||||
disabled,
|
||||
isLoading,
|
||||
reloadDocument,
|
||||
}: Props) {
|
||||
let location = useLocation();
|
||||
const rootData = useRootData();
|
||||
const matches = useMatches();
|
||||
|
||||
function onClicked() {
|
||||
if (onClick) {
|
||||
onClick();
|
||||
}
|
||||
if (!event || !sendEvent) {
|
||||
return;
|
||||
}
|
||||
const routeMatch = matches.find((m) => m.pathname == location.pathname);
|
||||
AnalyticsHelper.addEvent({
|
||||
url: location.pathname,
|
||||
route: routeMatch?.id,
|
||||
rootData,
|
||||
action: event.action,
|
||||
category: event.category,
|
||||
label: event.label,
|
||||
value: event.value,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<LinkOrAhref
|
||||
type={type}
|
||||
to={to}
|
||||
target={target}
|
||||
className={clsx(className, DEBUG_MODE && "ring-2 ring-red-500 ring-offset-2")}
|
||||
role={role}
|
||||
rel={rel}
|
||||
onClick={onClicked}
|
||||
disabled={disabled}
|
||||
isLoading={isLoading}
|
||||
reloadDocument={reloadDocument}
|
||||
>
|
||||
{children}
|
||||
</LinkOrAhref>
|
||||
);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/* This example requires Tailwind CSS v2.0+ */
|
||||
import { Fragment, ReactNode } from "react";
|
||||
import { Popover, Transition } from "@headlessui/react";
|
||||
import ChevronDownIcon from "../icons/ChevronDownIcon";
|
||||
import { Button } from "../button";
|
||||
|
||||
interface Props {
|
||||
title: string;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
export default function ButtonFlyout({ title, className, disabled, children }: Props) {
|
||||
return (
|
||||
<Popover className="relative">
|
||||
{() => (
|
||||
<>
|
||||
<Popover.Button as={Button} type="button" variant="outline" disabled={disabled} className={className}>
|
||||
<span className="inline-flex items-center space-x-2">
|
||||
<span>{title}</span>
|
||||
<ChevronDownIcon className="h-5 w-5 text-muted-foreground" />
|
||||
</span>
|
||||
</Popover.Button>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-200"
|
||||
enterFrom="opacity-0 translate-y-1"
|
||||
enterTo="opacity-100 translate-y-0"
|
||||
leave="transition ease-in duration-150"
|
||||
leaveFrom="opacity-100 translate-y-0"
|
||||
leaveTo="opacity-0 translate-y-1"
|
||||
>
|
||||
<Popover.Panel className="absolute left-1/2 z-10 mt-3 w-screen max-w-xs -translate-x-1/2 transform px-2 sm:px-0">
|
||||
<div className="overflow-hidden rounded-lg shadow-lg ring-1 ring-black ring-opacity-5">
|
||||
<div className="bg-background relative grid gap-6 px-5 py-6 sm:gap-8 sm:p-8">{children}</div>
|
||||
</div>
|
||||
</Popover.Panel>
|
||||
</Transition>
|
||||
</>
|
||||
)}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
import { MouseEventHandler, ReactNode, Ref, useEffect, useRef } from "react";
|
||||
import LinkOrAhref from "./LinkOrAhref";
|
||||
import { Button } from "../button";
|
||||
import { useLocation, useMatches } from "react-router";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import AnalyticsHelper from "~/utils/helpers/AnalyticsHelper";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
type?: "button" | "submit" | "reset" | undefined;
|
||||
to?: string;
|
||||
target?: undefined | "_blank";
|
||||
rel?: string;
|
||||
disabled?: boolean;
|
||||
destructive?: boolean;
|
||||
isExternal?: boolean;
|
||||
onClick?: MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;
|
||||
autoFocus?: boolean;
|
||||
children: ReactNode;
|
||||
prefetch?: "intent" | "render" | "none";
|
||||
event?: { action: string; category: string; label: string; value: string };
|
||||
sendEvent?: boolean;
|
||||
dataUiId?: string;
|
||||
}
|
||||
|
||||
export default function ButtonPrimary({
|
||||
className = "",
|
||||
type = "button",
|
||||
onClick,
|
||||
disabled,
|
||||
destructive,
|
||||
to,
|
||||
target,
|
||||
rel,
|
||||
isExternal = false,
|
||||
autoFocus,
|
||||
prefetch,
|
||||
children,
|
||||
event,
|
||||
sendEvent = true,
|
||||
dataUiId,
|
||||
}: Props) {
|
||||
// const combinedClassName = clsx(
|
||||
// className,
|
||||
// "inline-flex items-center space-x-2 px-4 py-2 border border-transparent shadow-2xs text-sm font-medium rounded-md text-white focus:outline-hidden focus:ring-2 focus:ring-accent-300",
|
||||
// disabled && "cursor-not-allowed opacity-75",
|
||||
// !destructive && "bg-primary",
|
||||
// destructive && "bg-red-600",
|
||||
// !disabled && !destructive && !className && "hover:bg-accent-900 focus:ring-ring hover:text-accent-100",
|
||||
// !disabled && destructive && "hover:bg-red-700 focus:ring-red-500"
|
||||
// );
|
||||
|
||||
let location = useLocation();
|
||||
const rootData = useRootData();
|
||||
const matches = useMatches();
|
||||
const focusRef = useRef<HTMLButtonElement | HTMLAnchorElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoFocus) {
|
||||
return;
|
||||
}
|
||||
const timeout = window.setTimeout(() => focusRef.current?.focus(), 0);
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [autoFocus]);
|
||||
|
||||
function onClicked(e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) {
|
||||
if (onClick) {
|
||||
onClick(e);
|
||||
}
|
||||
if (!event || !sendEvent) {
|
||||
return;
|
||||
}
|
||||
const routeMatch = matches.find((m) => m.pathname == location.pathname);
|
||||
AnalyticsHelper.addEvent({
|
||||
url: location.pathname,
|
||||
route: routeMatch?.id,
|
||||
rootData,
|
||||
action: event.action,
|
||||
category: event.category,
|
||||
label: event.label,
|
||||
value: event.value,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<span>
|
||||
{(() => {
|
||||
if (!to || disabled) {
|
||||
return (
|
||||
<Button
|
||||
variant={destructive ? "destructive" : undefined}
|
||||
className={clsx("inline-flex items-center space-x-2", className)}
|
||||
onClick={onClicked}
|
||||
type={type}
|
||||
disabled={disabled}
|
||||
ref={focusRef as Ref<HTMLButtonElement>}
|
||||
data-ui-id={dataUiId}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
} else if (to && isExternal) {
|
||||
return (
|
||||
<Button asChild>
|
||||
<a
|
||||
href={to}
|
||||
target={target}
|
||||
rel={rel}
|
||||
ref={focusRef as Ref<HTMLAnchorElement>}
|
||||
onClick={onClicked}
|
||||
data-ui-id={dataUiId}
|
||||
className={clsx("inline-flex items-center space-x-2", className)}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
</Button>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<Button asChild>
|
||||
<LinkOrAhref
|
||||
to={disabled ? "" : to}
|
||||
target={target}
|
||||
rel={rel}
|
||||
prefetch={prefetch}
|
||||
className={clsx("inline-flex items-center space-x-2", className)}
|
||||
// className={clsx(
|
||||
// className,
|
||||
// "borde1-transparent focus:ring-accent-300 inline-flex items-center space-x-2 rounded-md border px-4 py-2 text-sm font-medium text-white shadow-2xs focus:outline-hidden focus:ring-2",
|
||||
// disabled && "cursor-not-allowed opacity-75",
|
||||
// !destructive && "bg-primary",
|
||||
// destructive && "bg-red-600",
|
||||
// !disabled && !destructive && !className && "hover:bg-accent-900 hover:text-accent-100 focus:ring-ring",
|
||||
// !disabled && destructive && "hover:bg-red-700 focus:ring-red-500"
|
||||
// )}
|
||||
autoFocus={autoFocus}
|
||||
onClick={onClicked}
|
||||
data-ui-id={dataUiId}
|
||||
>
|
||||
{children}
|
||||
</LinkOrAhref>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
})()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import { MouseEventHandler, ReactNode } from "react";
|
||||
import LinkOrAhref from "./LinkOrAhref";
|
||||
import { Button } from "../button";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
type?: "button" | "submit" | "reset" | undefined;
|
||||
to?: string;
|
||||
target?: undefined | "_blank";
|
||||
rel?: string;
|
||||
ariaLabel?: string;
|
||||
disabled?: boolean;
|
||||
destructive?: boolean;
|
||||
children: ReactNode;
|
||||
onClick?: MouseEventHandler<HTMLButtonElement>;
|
||||
isLoading?: boolean;
|
||||
prefetch?: "intent" | "render" | "none";
|
||||
reloadDocument?: boolean;
|
||||
}
|
||||
|
||||
export default function ButtonSecondary({
|
||||
className = "",
|
||||
type = "button",
|
||||
onClick,
|
||||
disabled,
|
||||
destructive,
|
||||
to,
|
||||
target,
|
||||
rel,
|
||||
ariaLabel,
|
||||
children,
|
||||
isLoading,
|
||||
prefetch,
|
||||
reloadDocument,
|
||||
}: Props) {
|
||||
return (
|
||||
<span>
|
||||
{(() => {
|
||||
if (!to || disabled) {
|
||||
return (
|
||||
<Button
|
||||
variant={destructive ? "destructive" : "secondary"}
|
||||
onClick={onClick}
|
||||
type={type}
|
||||
disabled={disabled || isLoading}
|
||||
className={clsx("inline-flex items-center space-x-2", className)}
|
||||
aria-label={ariaLabel}
|
||||
// className={clsx(
|
||||
// isLoading && "base-spinner cursor-not-allowed",
|
||||
// className,
|
||||
// "focus:border-accent-300 inline-flex items-center space-x-2 rounded-md border border-border px-3 py-2 text-sm font-medium shadow-2xs focus:outline-hidden focus:ring-2",
|
||||
// disabled ? "cursor-not-allowed bg-secondary/90 opacity-75" : "bg-background",
|
||||
// !destructive && "text-accent-700",
|
||||
// destructive && "text-red-700",
|
||||
// !disabled && !destructive && !className && "hover:border-accent-300 hover:text-accent-900 focus:ring-ring hover:bg-secondary",
|
||||
// !disabled && destructive && "hover:bg-red-50 focus:ring-red-500"
|
||||
// )}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<Button asChild variant="secondary">
|
||||
<LinkOrAhref
|
||||
to={to}
|
||||
target={target}
|
||||
rel={rel}
|
||||
prefetch={prefetch}
|
||||
reloadDocument={reloadDocument}
|
||||
className={clsx("inline-flex items-center space-x-2", className)}
|
||||
ariaLabel={ariaLabel}
|
||||
// className={clsx(
|
||||
// isLoading && "base-spinner cursor-not-allowed",
|
||||
// className,
|
||||
// "focus:border-accent-300 inline-flex items-center space-x-2 rounded-md border border-border px-3 py-2 text-sm font-medium shadow-2xs focus:outline-hidden focus:ring-2",
|
||||
// disabled ? "cursor-not-allowed bg-secondary/90 opacity-75" : "bg-background",
|
||||
// !destructive && "text-accent-700",
|
||||
// destructive && "text-red-700",
|
||||
// !disabled && !destructive && !className && "hover:border-accent-300 hover:text-accent-900 focus:ring-ring hover:bg-secondary",
|
||||
// !disabled && destructive && "hover:bg-red-50 focus:ring-red-500"
|
||||
// )}
|
||||
>
|
||||
{children}
|
||||
</LinkOrAhref>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
})()}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
import { Fragment, ReactNode } from "react";
|
||||
import { Popover, Transition } from "@headlessui/react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import ShareIcon from "../icons/ShareIcon";
|
||||
import { Button } from "../button";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
export default function ButtonFlyout({ className, disabled, children }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<Popover className="relative">
|
||||
{({ open }) => (
|
||||
<>
|
||||
<Popover.Button as={Button} type="button" variant="outline" disabled={disabled} className={className}>
|
||||
<span className="inline-flex items-center space-x-2">
|
||||
<span>{t("shared.share")}</span>
|
||||
<ShareIcon className={open ? "h-4 w-4 text-foreground/80" : "h-4 w-4 text-muted-foreground"} />
|
||||
</span>
|
||||
</Popover.Button>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-200"
|
||||
enterFrom="opacity-0 translate-y-1"
|
||||
enterTo="opacity-100 translate-y-0"
|
||||
leave="transition ease-in duration-150"
|
||||
leaveFrom="opacity-100 translate-y-0"
|
||||
leaveTo="opacity-0 translate-y-1"
|
||||
>
|
||||
<Popover.Panel className="absolute left-1/2 z-10 mt-3 w-screen max-w-xs -translate-x-1/2 transform px-2 sm:px-0">
|
||||
<div className="overflow-hidden rounded-lg shadow-lg ring-1 ring-black ring-opacity-5">
|
||||
<div className="bg-background relative grid gap-6 px-5 py-6 sm:gap-8 sm:p-8">{children}</div>
|
||||
</div>
|
||||
</Popover.Panel>
|
||||
</Transition>
|
||||
</>
|
||||
)}
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import { Fragment, ReactNode } from "react";
|
||||
import LinkOrAhref from "./LinkOrAhref";
|
||||
import ButtonEvent from "./ButtonEvent";
|
||||
import { useNavigation, useSearchParams, useSubmit } from "react-router";
|
||||
import clsx from "clsx";
|
||||
|
||||
interface Props {
|
||||
type?: "button" | "submit";
|
||||
to?: string | undefined;
|
||||
submits?: { action: string; values: { [key: string]: string } };
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
target?: undefined | "_blank";
|
||||
role?: string;
|
||||
rel?: string;
|
||||
event?: {
|
||||
action: string;
|
||||
category: string;
|
||||
label: string;
|
||||
value: string;
|
||||
};
|
||||
onClick?: () => void;
|
||||
sendEvent?: boolean;
|
||||
disabled?: boolean;
|
||||
}
|
||||
export default function ButtonSubmitForm({ submits, type, to, target, children, className, role, rel, event, onClick, sendEvent = true, disabled }: Props) {
|
||||
const submit = useSubmit();
|
||||
const navigation = useNavigation();
|
||||
const [searchParams] = useSearchParams();
|
||||
const isLoading = navigation.state === "submitting" && navigation.formData?.get("action") === submits?.action;
|
||||
|
||||
function onClicked() {
|
||||
if (!submits) {
|
||||
return;
|
||||
}
|
||||
const formData = new FormData();
|
||||
formData.append("action", submits.action ?? "");
|
||||
const values: { [key: string]: string } = submits?.values;
|
||||
for (const key in values) {
|
||||
formData.append(key, values[key]);
|
||||
}
|
||||
if (submits.action === "subscribe") {
|
||||
formData.set("coupon", searchParams.get("coupon")?.toString() ?? "");
|
||||
}
|
||||
submit(formData, {
|
||||
method: "post",
|
||||
});
|
||||
}
|
||||
return (
|
||||
<Fragment>
|
||||
{event ? (
|
||||
<ButtonEvent
|
||||
event={event}
|
||||
type={type}
|
||||
to={submits ? undefined : to}
|
||||
target={target}
|
||||
className={clsx(className, isLoading && "base-spinner")}
|
||||
role={role}
|
||||
rel={rel}
|
||||
onClick={onClicked}
|
||||
disabled={disabled}
|
||||
>
|
||||
{children}
|
||||
</ButtonEvent>
|
||||
) : (
|
||||
<LinkOrAhref
|
||||
type={type}
|
||||
to={submits ? undefined : to}
|
||||
target={target}
|
||||
className={clsx(className, isLoading && "base-spinner")}
|
||||
role={role}
|
||||
rel={rel}
|
||||
onClick={onClicked}
|
||||
disabled={disabled}
|
||||
>
|
||||
{children}
|
||||
</LinkOrAhref>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
+132
@@ -0,0 +1,132 @@
|
||||
import { MouseEventHandler, ReactNode, useRef } from "react";
|
||||
import clsx from "clsx";
|
||||
import LinkOrAhref from "./LinkOrAhref";
|
||||
import ConfirmModal, { RefConfirmModal } from "../modals/ConfirmModal";
|
||||
import { Button } from "../button";
|
||||
import { useLocation, useMatches } from "react-router";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
import AnalyticsHelper from "~/utils/helpers/AnalyticsHelper";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
type?: "button" | "submit" | "reset" | undefined;
|
||||
to?: string;
|
||||
target?: undefined | "_blank";
|
||||
rel?: string;
|
||||
disabled?: boolean;
|
||||
destructive?: boolean;
|
||||
children: ReactNode;
|
||||
onClick?: MouseEventHandler<HTMLButtonElement | HTMLAnchorElement>;
|
||||
reloadDocument?: boolean;
|
||||
prefetch?: "intent" | "render" | "none";
|
||||
confirmation?: {
|
||||
title: string;
|
||||
description: string;
|
||||
};
|
||||
event?: { action: string; category: string; label: string; value: string };
|
||||
sendEvent?: boolean;
|
||||
}
|
||||
|
||||
export default function ButtonTertiary({
|
||||
className = "",
|
||||
type = "button",
|
||||
onClick,
|
||||
disabled,
|
||||
destructive,
|
||||
to,
|
||||
target,
|
||||
rel,
|
||||
children,
|
||||
reloadDocument,
|
||||
prefetch,
|
||||
confirmation,
|
||||
event,
|
||||
sendEvent,
|
||||
}: Props) {
|
||||
const { t } = useTranslation();
|
||||
const refConfirm = useRef<RefConfirmModal>(null);
|
||||
let location = useLocation();
|
||||
const rootData = useRootData();
|
||||
const matches = useMatches();
|
||||
|
||||
function onClicked(e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) {
|
||||
if (onClick) {
|
||||
onClick(e);
|
||||
}
|
||||
if (!event || !sendEvent) {
|
||||
return;
|
||||
}
|
||||
const routeMatch = matches.find((m) => m.pathname == location.pathname);
|
||||
AnalyticsHelper.addEvent({
|
||||
url: location.pathname,
|
||||
route: routeMatch?.id,
|
||||
rootData,
|
||||
action: event.action,
|
||||
category: event.category,
|
||||
label: event.label,
|
||||
value: event.value,
|
||||
});
|
||||
}
|
||||
return (
|
||||
<span>
|
||||
{(() => {
|
||||
if (!to || disabled) {
|
||||
return (
|
||||
<Button
|
||||
variant={"ghost"}
|
||||
className={clsx(className, destructive && "text-red-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900 dark:hover:text-white")}
|
||||
onClick={
|
||||
confirmation
|
||||
? () => {
|
||||
refConfirm.current?.setDestructive(destructive || false);
|
||||
refConfirm.current?.show(confirmation.title, t("shared.confirm"), t("shared.cancel"), confirmation.description);
|
||||
}
|
||||
: onClicked
|
||||
}
|
||||
type={type}
|
||||
disabled={disabled}
|
||||
// className={clsx(
|
||||
// className,
|
||||
// "focus:ring-accent-300 mx-1 my-2 inline-flex items-center space-x-2 border-b border-transparent text-sm font-medium focus:rounded-md focus:outline-hidden focus:ring-2 focus:ring-offset-2",
|
||||
// disabled ? "cursor-not-allowed opacity-75" : "hover:border-dotted",
|
||||
// !destructive && "text-theme-700 border-b ",
|
||||
// destructive && "text-red-600",
|
||||
// !disabled && !destructive && !className && "hover:text-theme-800 focus:text-theme-900 ",
|
||||
// !disabled && destructive && "hover:border-red-300 hover:text-red-800 focus:text-red-900"
|
||||
// )}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<Button asChild variant={"ghost"} className={clsx(destructive && "text-red-500")}>
|
||||
<LinkOrAhref
|
||||
reloadDocument={reloadDocument}
|
||||
to={to}
|
||||
target={target}
|
||||
rel={rel}
|
||||
prefetch={prefetch}
|
||||
className={clsx(className)}
|
||||
// className={clsx(
|
||||
// className,
|
||||
// "focus:ring-accent-300 mx-1 my-2 inline-flex items-center space-x-2 border-b border-transparent text-sm font-medium focus:rounded-md focus:outline-hidden focus:ring-2 focus:ring-offset-2",
|
||||
// disabled ? "cursor-not-allowed opacity-75" : " hover:border-dotted",
|
||||
// !destructive && "text-theme-700 border-b ",
|
||||
// destructive && "text-red-600",
|
||||
// !disabled && !destructive && !className && "hover:text-theme-800 focus:text-theme-900 ",
|
||||
// !disabled && destructive && "hover:border-red-300 hover:text-red-800 focus:text-red-900"
|
||||
// )}
|
||||
>
|
||||
{children}
|
||||
</LinkOrAhref>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
})()}
|
||||
|
||||
<ConfirmModal ref={refConfirm} onYes={onClick} />
|
||||
</span>
|
||||
);
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
import { Link } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { Fragment, ReactNode, Ref, useEffect, useRef } from "react";
|
||||
import { Button } from "../button";
|
||||
|
||||
interface Props {
|
||||
type?: "button" | "submit";
|
||||
to: string | undefined;
|
||||
children: ReactNode;
|
||||
className?: string;
|
||||
target?: undefined | "_blank" | string;
|
||||
role?: string;
|
||||
ariaLabel?: string;
|
||||
rel?: string;
|
||||
onClick?: (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement>) => void;
|
||||
reloadDocument?: boolean;
|
||||
autoFocus?: boolean;
|
||||
prefetch?: "intent" | "render" | "none";
|
||||
disabled?: boolean;
|
||||
isLoading?: boolean;
|
||||
onMouseEnter?: (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement | HTMLDivElement>) => void;
|
||||
onMouseLeave?: (e: React.MouseEvent<HTMLButtonElement | HTMLAnchorElement | HTMLDivElement>) => void;
|
||||
}
|
||||
export default function LinkOrAhref({
|
||||
type = "button",
|
||||
to,
|
||||
target,
|
||||
children,
|
||||
className,
|
||||
role,
|
||||
ariaLabel,
|
||||
rel,
|
||||
onClick,
|
||||
reloadDocument,
|
||||
autoFocus,
|
||||
prefetch,
|
||||
disabled,
|
||||
isLoading,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
}: Props) {
|
||||
const focusRef = useRef<HTMLButtonElement | HTMLAnchorElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!autoFocus) {
|
||||
return;
|
||||
}
|
||||
const timeout = window.setTimeout(() => focusRef.current?.focus(), 0);
|
||||
return () => window.clearTimeout(timeout);
|
||||
}, [autoFocus]);
|
||||
|
||||
return (
|
||||
<Fragment>
|
||||
{(!to && !onClick) || (to && disabled) ? (
|
||||
<div className={className} role={role} aria-label={ariaLabel} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
|
||||
{children}
|
||||
</div>
|
||||
) : to == undefined ? (
|
||||
<Button
|
||||
ref={focusRef as Ref<HTMLButtonElement>}
|
||||
type={type}
|
||||
onClick={onClick}
|
||||
className={clsx(className, isLoading && "base-spinner cursor-not-allowed")}
|
||||
role={role}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
>
|
||||
{children}
|
||||
</Button>
|
||||
) : (
|
||||
<Link
|
||||
reloadDocument={reloadDocument}
|
||||
onClick={onClick}
|
||||
to={to}
|
||||
target={target}
|
||||
className={className}
|
||||
role={role}
|
||||
aria-label={ariaLabel}
|
||||
ref={focusRef as Ref<HTMLAnchorElement>}
|
||||
prefetch={prefetch}
|
||||
rel={rel}
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
import ButtonPrimary from "./ButtonPrimary";
|
||||
import { forwardRef, MouseEventHandler, ReactNode, Ref, useImperativeHandle, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { useNavigation } from "react-router";
|
||||
|
||||
export interface RefLoadingButton {
|
||||
start: () => void;
|
||||
stop: () => void;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
type?: "button" | "submit" | "reset" | undefined;
|
||||
disabled?: boolean;
|
||||
children: ReactNode;
|
||||
onClick?: MouseEventHandler<HTMLButtonElement>;
|
||||
to?: string;
|
||||
actionName?: string;
|
||||
isLoading?: boolean;
|
||||
dataUiId?: string;
|
||||
}
|
||||
|
||||
const LoadingButton = ({ className, type = "button", children, disabled, onClick, to, actionName, isLoading, dataUiId }: Props, ref: Ref<RefLoadingButton>) => {
|
||||
const navigation = useNavigation();
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useImperativeHandle(ref, () => ({
|
||||
start,
|
||||
stop,
|
||||
}));
|
||||
|
||||
function start() {
|
||||
setLoading(true);
|
||||
}
|
||||
function stop() {
|
||||
setLoading(false);
|
||||
}
|
||||
const submitting = navigation.state === "submitting";
|
||||
|
||||
function checkIsLoading() {
|
||||
if (isLoading !== undefined) {
|
||||
return isLoading;
|
||||
}
|
||||
const loadingOrSubmitting = loading || submitting;
|
||||
if (actionName) {
|
||||
return loadingOrSubmitting && navigation.state === "submitting" && navigation.formData?.get("action") === actionName;
|
||||
}
|
||||
return loadingOrSubmitting;
|
||||
}
|
||||
|
||||
return (
|
||||
<ButtonPrimary
|
||||
disabled={disabled || checkIsLoading()}
|
||||
className={clsx(className, "relative justify-center", checkIsLoading() && "base-spinner cursor-not-allowed")}
|
||||
type={type}
|
||||
onClick={onClick}
|
||||
to={to}
|
||||
dataUiId={dataUiId}
|
||||
>
|
||||
{/* {checkIsLoading() && <ReloadIcon className="mr-2 h-4 w-4 animate-spin" />} */}
|
||||
|
||||
{children}
|
||||
</ButtonPrimary>
|
||||
);
|
||||
};
|
||||
|
||||
export default forwardRef(LoadingButton);
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import ButtonPrimary from "./ButtonPrimary";
|
||||
import { t as i18nT } from "i18next";
|
||||
import ButtonSecondary from "./ButtonSecondary";
|
||||
import ButtonTertiary from "./ButtonTertiary";
|
||||
import LoadingButton, { RefLoadingButton } from "./LoadingButton";
|
||||
import { useRef } from "react";
|
||||
|
||||
export default function PreviewButtons() {
|
||||
const loadingButton = useRef<RefLoadingButton>(null);
|
||||
function startLoading() {
|
||||
if (loadingButton.current) {
|
||||
loadingButton.current?.start();
|
||||
setTimeout(() => {
|
||||
loadingButton.current?.stop();
|
||||
}, 2000);
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div id="buttons">
|
||||
<div className="border-muted-foreground overflow-hidden rounded-lg border-2 border-dashed p-6">
|
||||
<div id="buttons" className="w-full space-y-2">
|
||||
<div className="mx-auto flex max-w-3xl flex-col items-center justify-center space-y-4 sm:flex-row sm:items-end sm:justify-center sm:space-y-0 sm:space-x-4">
|
||||
<ButtonPrimary onClick={() => alert(i18nT("components.buttons.preview.clickedPrimary"))}>{i18nT("components.buttons.preview.primary")}</ButtonPrimary>
|
||||
<ButtonSecondary onClick={() => alert(i18nT("components.buttons.preview.clickedSecondary"))}>{i18nT("components.buttons.preview.secondary")}</ButtonSecondary>
|
||||
<ButtonTertiary onClick={() => alert(i18nT("components.buttons.preview.clickedTertiary"))}>{i18nT("components.buttons.preview.tertiary")}</ButtonTertiary>
|
||||
<LoadingButton ref={loadingButton} onClick={() => startLoading()}>
|
||||
{i18nT("components.buttons.preview.loading")}
|
||||
</LoadingButton>
|
||||
</div>
|
||||
<div className="mx-auto flex max-w-3xl flex-col items-center justify-center space-y-4 sm:flex-row sm:items-end sm:justify-center sm:space-y-0 sm:space-x-4">
|
||||
<ButtonPrimary disabled={true}>{i18nT("components.buttons.preview.primary")}</ButtonPrimary>
|
||||
<ButtonSecondary disabled={true}>{i18nT("components.buttons.preview.secondary")}</ButtonSecondary>
|
||||
<ButtonTertiary disabled={true}>{i18nT("components.buttons.preview.tertiary")}</ButtonTertiary>
|
||||
<LoadingButton disabled={true}>{i18nT("components.buttons.preview.loading")}</LoadingButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
import { useLocation } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import ButtonPrimary from "./ButtonPrimary";
|
||||
import ButtonSecondary from "./ButtonSecondary";
|
||||
import ButtonTertiary from "./ButtonTertiary";
|
||||
|
||||
export default function PreviewButtonsAsLinks() {
|
||||
const currentRoute = useLocation().pathname;
|
||||
return (
|
||||
<div id="buttons-as-links">
|
||||
<div className="not-prose border-border bg-background border border-dashed p-6">
|
||||
<div className="w-full space-y-2">
|
||||
<div className="mx-auto flex max-w-3xl flex-col items-center justify-center space-y-4 sm:flex-row sm:items-end sm:justify-center sm:space-y-0 sm:space-x-4">
|
||||
<ButtonPrimary to={currentRoute}>{i18nT("components.buttons.preview.primary")}</ButtonPrimary>
|
||||
<ButtonSecondary to={currentRoute}>{i18nT("components.buttons.preview.secondary")}</ButtonSecondary>
|
||||
<ButtonTertiary to={currentRoute}>{i18nT("components.buttons.preview.tertiary")}</ButtonTertiary>
|
||||
</div>
|
||||
<div className="mx-auto flex max-w-3xl flex-col items-center justify-center space-y-4 sm:flex-row sm:items-end sm:justify-center sm:space-y-0 sm:space-x-4">
|
||||
<ButtonPrimary disabled={true} to={currentRoute}>
|
||||
{i18nT("components.buttons.preview.primary")}
|
||||
</ButtonPrimary>
|
||||
<ButtonSecondary disabled={true} to={currentRoute}>
|
||||
{i18nT("components.buttons.preview.secondary")}
|
||||
</ButtonSecondary>
|
||||
<ButtonTertiary disabled={true} to={currentRoute}>
|
||||
{i18nT("components.buttons.preview.tertiary")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { t as i18nT } from "i18next";
|
||||
import ButtonPrimary from "./ButtonPrimary";
|
||||
import ButtonSecondary from "./ButtonSecondary";
|
||||
import ButtonTertiary from "./ButtonTertiary";
|
||||
|
||||
export default function PreviewButtonsDestructive() {
|
||||
return (
|
||||
<div id="buttons-as-links">
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<div className="w-full space-y-2">
|
||||
<div className="mx-auto flex max-w-3xl flex-col items-center justify-center space-y-4 sm:flex-row sm:items-end sm:justify-center sm:space-x-4 sm:space-y-0">
|
||||
<ButtonPrimary onClick={() => alert(i18nT("components.buttons.preview.clickedPrimaryDestructive"))} destructive={true}>
|
||||
{i18nT("components.buttons.preview.primary")}
|
||||
</ButtonPrimary>
|
||||
<ButtonSecondary onClick={() => alert(i18nT("components.buttons.preview.clickedSecondaryDestructive"))} destructive={true}>
|
||||
{i18nT("components.buttons.preview.secondary")}
|
||||
</ButtonSecondary>
|
||||
<ButtonTertiary onClick={() => alert(i18nT("components.buttons.preview.clickedTertiaryDestructive"))} destructive={true}>
|
||||
{i18nT("components.buttons.preview.tertiary")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
<div className="mx-auto flex max-w-3xl flex-col items-center justify-center space-y-4 sm:flex-row sm:items-end sm:justify-center sm:space-x-4 sm:space-y-0">
|
||||
<ButtonPrimary disabled={true} destructive={true}>
|
||||
{i18nT("components.buttons.preview.primary")}
|
||||
</ButtonPrimary>
|
||||
<ButtonSecondary disabled={true} destructive={true}>
|
||||
{i18nT("components.buttons.preview.secondary")}
|
||||
</ButtonSecondary>
|
||||
<ButtonTertiary disabled={true} destructive={true}>
|
||||
{i18nT("components.buttons.preview.tertiary")}
|
||||
</ButtonTertiary>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import * as React from "react";
|
||||
import { ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon } from "~/components/ui/icons/vendor";
|
||||
import { DayButton, getDefaultClassNames } from "react-day-picker";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
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";
|
||||
|
||||
// Subframe migration (strangler shim):
|
||||
// This file keeps the original shadcn `Calendar` API but renders the Subframe design-system
|
||||
// Calendar as the underlying view. Subframe's Calendar is a thin wrapper over the SAME
|
||||
// `react-day-picker` `DayPicker` (identical `DayPickerProps`), so all functionality the
|
||||
// call-sites rely on — `mode` single/range, controlled `selected`/`onSelect`,
|
||||
// `month`/`onMonthChange`, `fromYear`/`toYear`, `captionLayout="dropdown"`, `required`,
|
||||
// `disabled` — is preserved by passing the same props through.
|
||||
//
|
||||
// The shadcn-specific behavior NOT provided by Subframe is retained here:
|
||||
// - i18n locale default (via `useTranslation` + `getDateFnsLocale`) — call-sites don't
|
||||
// pass `locale`; they rely on it,
|
||||
// - localized month-dropdown formatter,
|
||||
// - the full `classNames` styling and `components` (incl. the `CalendarDayButton`),
|
||||
// - the `buttonVariant` prop and the `buttonVariants` consumer contract.
|
||||
//
|
||||
// Subframe's Calendar injects its own `Chevron` component and a wrapping `<div>`; our
|
||||
// `components.Chevron`/`components.Root` overrides win because Subframe spreads the caller's
|
||||
// props after its own, so `react-day-picker` receives our merged `components`.
|
||||
function Calendar({
|
||||
className,
|
||||
classNames,
|
||||
showOutsideDays = true,
|
||||
captionLayout = "label",
|
||||
buttonVariant = "ghost",
|
||||
locale: localeProp,
|
||||
formatters,
|
||||
components,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SubframeCalendar> & {
|
||||
buttonVariant?: React.ComponentProps<typeof Button>["variant"];
|
||||
}) {
|
||||
const defaultClassNames = getDefaultClassNames();
|
||||
const { i18n } = useTranslation();
|
||||
const language = i18n.language || undefined;
|
||||
const dateFnsLocale = localeProp ?? getDateFnsLocale(language);
|
||||
const monthDropdownFormatter = React.useMemo(() => new Intl.DateTimeFormat(language, { month: "short" }), [language]);
|
||||
|
||||
return (
|
||||
<SubframeCalendar
|
||||
locale={dateFnsLocale}
|
||||
showOutsideDays={showOutsideDays}
|
||||
className={cn(
|
||||
"bg-background group/calendar p-3 [--cell-size:--spacing(8)] [[data-slot=card-content]_&]:bg-transparent [[data-slot=popover-content]_&]:bg-transparent",
|
||||
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
|
||||
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
|
||||
className
|
||||
)}
|
||||
captionLayout={captionLayout}
|
||||
formatters={{
|
||||
formatMonthDropdown: (date) => monthDropdownFormatter.format(date),
|
||||
...formatters,
|
||||
}}
|
||||
classNames={{
|
||||
root: cn("w-fit", defaultClassNames.root),
|
||||
months: cn("flex gap-4 flex-col md:flex-row relative", defaultClassNames.months),
|
||||
month: cn("flex flex-col w-full gap-4", defaultClassNames.month),
|
||||
nav: cn("flex items-center gap-1 w-full absolute top-0 inset-x-0 justify-between", defaultClassNames.nav),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) aria-disabled:opacity-50 p-0 select-none",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn("flex items-center justify-center h-(--cell-size) w-full px-(--cell-size)", defaultClassNames.month_caption),
|
||||
dropdowns: cn("w-full flex items-center text-sm font-medium justify-center h-(--cell-size) gap-1.5", defaultClassNames.dropdowns),
|
||||
dropdown_root: cn(
|
||||
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn("absolute inset-0 opacity-0", defaultClassNames.dropdown),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label" ? "text-sm" : "rounded-md pl-2 pr-1 flex items-center gap-1 text-sm h-8 [&>svg]:text-muted-foreground [&>svg]:size-3.5",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn("text-muted-foreground rounded-md flex-1 font-normal text-[0.8rem] select-none", defaultClassNames.weekday),
|
||||
week: cn("flex w-full mt-2", defaultClassNames.week),
|
||||
week_number_header: cn("select-none w-(--cell-size)", defaultClassNames.week_number_header),
|
||||
week_number: cn("text-[0.8rem] select-none text-muted-foreground", defaultClassNames.week_number),
|
||||
day: cn(
|
||||
"relative w-full h-full p-0 text-center [&:first-child[data-selected=true]_button]:rounded-l-md [&:last-child[data-selected=true]_button]:rounded-r-md group/day aspect-square select-none",
|
||||
defaultClassNames.day
|
||||
),
|
||||
range_start: cn("rounded-l-md bg-accent", defaultClassNames.range_start),
|
||||
range_middle: cn("rounded-none", defaultClassNames.range_middle),
|
||||
range_end: cn("rounded-r-md bg-accent", defaultClassNames.range_end),
|
||||
today: cn("bg-accent text-accent-foreground rounded-md data-[selected=true]:rounded-none", defaultClassNames.today),
|
||||
outside: cn("text-muted-foreground aria-selected:text-muted-foreground", defaultClassNames.outside),
|
||||
disabled: cn("text-muted-foreground opacity-50", defaultClassNames.disabled),
|
||||
hidden: cn("invisible", defaultClassNames.hidden),
|
||||
...classNames,
|
||||
}}
|
||||
components={{
|
||||
Root: ({ className, rootRef, ...props }) => {
|
||||
return <div data-slot="calendar" ref={rootRef} className={cn(className)} {...props} />;
|
||||
},
|
||||
Chevron: ({ className, orientation, ...props }) => {
|
||||
if (orientation === "left") {
|
||||
return <ChevronLeftIcon className={cn("size-4", className)} {...props} />;
|
||||
}
|
||||
|
||||
if (orientation === "right") {
|
||||
return <ChevronRightIcon className={cn("size-4", className)} {...props} />;
|
||||
}
|
||||
|
||||
return <ChevronDownIcon className={cn("size-4", className)} {...props} />;
|
||||
},
|
||||
DayButton: CalendarDayButton,
|
||||
WeekNumber: ({ children, ...props }) => {
|
||||
return (
|
||||
<td {...props}>
|
||||
<div className="flex size-(--cell-size) items-center justify-center text-center">{children}</div>
|
||||
</td>
|
||||
);
|
||||
},
|
||||
...components,
|
||||
}}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CalendarDayButton({ className, day, modifiers, ...props }: React.ComponentProps<typeof DayButton>) {
|
||||
const defaultClassNames = getDefaultClassNames();
|
||||
|
||||
const ref = React.useRef<HTMLButtonElement>(null);
|
||||
React.useEffect(() => {
|
||||
if (modifiers.focused) ref.current?.focus();
|
||||
}, [modifiers.focused]);
|
||||
|
||||
return (
|
||||
<Button
|
||||
ref={ref}
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
data-day={day.date.toISOString()}
|
||||
data-selected-single={modifiers.selected && !modifiers.range_start && !modifiers.range_end && !modifiers.range_middle}
|
||||
data-range-start={modifiers.range_start}
|
||||
data-range-end={modifiers.range_end}
|
||||
data-range-middle={modifiers.range_middle}
|
||||
className={cn(
|
||||
"data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground data-[range-middle=true]:bg-accent data-[range-middle=true]:text-accent-foreground data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-ring/50 dark:hover:text-accent-foreground flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:ring-[3px] data-[range-end=true]:rounded-md data-[range-end=true]:rounded-r-md data-[range-middle=true]:rounded-none data-[range-start=true]:rounded-md data-[range-start=true]:rounded-l-md [&>span]:text-xs [&>span]:opacity-70",
|
||||
defaultClassNames.day,
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Calendar, CalendarDayButton };
|
||||
@@ -0,0 +1,95 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-surface-neutral-primary text-text-neutral-primary flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
// WCAG-2.2: focus-visible ring when the card itself is focusable
|
||||
// (e.g. used as a tabIndex={0} link wrapper or role=button).
|
||||
"focus-visible:outline-none focus-visible:shadow-focus",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-[data-slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-text-neutral-tertiary text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import useEmblaCarousel, {
|
||||
type UseEmblaCarouselType,
|
||||
} from "embla-carousel-react"
|
||||
import { cn } from "~/lib/utils"
|
||||
import { Button } from "~/components/ui/button"
|
||||
import { ArrowLeftIcon, ArrowRightIcon } from "~/components/ui/icons/vendor";
|
||||
import { useTranslation } from "react-i18next"
|
||||
|
||||
type CarouselApi = UseEmblaCarouselType[1]
|
||||
type UseCarouselParameters = Parameters<typeof useEmblaCarousel>
|
||||
type CarouselOptions = UseCarouselParameters[0]
|
||||
type CarouselPlugin = UseCarouselParameters[1]
|
||||
|
||||
type CarouselProps = {
|
||||
opts?: CarouselOptions
|
||||
plugins?: CarouselPlugin
|
||||
orientation?: "horizontal" | "vertical"
|
||||
setApi?: (api: CarouselApi) => void
|
||||
}
|
||||
|
||||
type CarouselContextProps = {
|
||||
carouselRef: ReturnType<typeof useEmblaCarousel>[0]
|
||||
api: ReturnType<typeof useEmblaCarousel>[1]
|
||||
scrollPrev: () => void
|
||||
scrollNext: () => void
|
||||
canScrollPrev: boolean
|
||||
canScrollNext: boolean
|
||||
} & CarouselProps
|
||||
|
||||
const CarouselContext = React.createContext<CarouselContextProps | null>(null)
|
||||
|
||||
function useCarousel() {
|
||||
const context = React.useContext(CarouselContext)
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useCarousel must be used within a <Carousel />")
|
||||
}
|
||||
|
||||
return context
|
||||
}
|
||||
|
||||
function Carousel({
|
||||
orientation = "horizontal",
|
||||
opts,
|
||||
setApi,
|
||||
plugins,
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & CarouselProps) {
|
||||
const [carouselRef, api] = useEmblaCarousel(
|
||||
{
|
||||
...opts,
|
||||
axis: orientation === "horizontal" ? "x" : "y",
|
||||
},
|
||||
plugins
|
||||
)
|
||||
const [canScrollPrev, setCanScrollPrev] = React.useState(false)
|
||||
const [canScrollNext, setCanScrollNext] = React.useState(false)
|
||||
|
||||
const onSelect = React.useCallback((api: CarouselApi) => {
|
||||
if (!api) return
|
||||
setCanScrollPrev(api.canScrollPrev())
|
||||
setCanScrollNext(api.canScrollNext())
|
||||
}, [])
|
||||
|
||||
const scrollPrev = React.useCallback(() => {
|
||||
api?.scrollPrev()
|
||||
}, [api])
|
||||
|
||||
const scrollNext = React.useCallback(() => {
|
||||
api?.scrollNext()
|
||||
}, [api])
|
||||
|
||||
const handleKeyDown = React.useCallback(
|
||||
(event: React.KeyboardEvent<HTMLDivElement>) => {
|
||||
if (event.key === "ArrowLeft") {
|
||||
event.preventDefault()
|
||||
scrollPrev()
|
||||
} else if (event.key === "ArrowRight") {
|
||||
event.preventDefault()
|
||||
scrollNext()
|
||||
}
|
||||
},
|
||||
[scrollPrev, scrollNext]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api || !setApi) return
|
||||
setApi(api)
|
||||
}, [api, setApi])
|
||||
|
||||
React.useEffect(() => {
|
||||
if (!api) return
|
||||
onSelect(api)
|
||||
api.on("reInit", onSelect)
|
||||
api.on("select", onSelect)
|
||||
|
||||
return () => {
|
||||
api?.off("select", onSelect)
|
||||
}
|
||||
}, [api, onSelect])
|
||||
|
||||
return (
|
||||
<CarouselContext.Provider
|
||||
value={{
|
||||
carouselRef,
|
||||
api: api,
|
||||
opts,
|
||||
orientation:
|
||||
orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
|
||||
scrollPrev,
|
||||
scrollNext,
|
||||
canScrollPrev,
|
||||
canScrollNext,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
onKeyDownCapture={handleKeyDown}
|
||||
className={cn("relative", className)}
|
||||
role="region"
|
||||
aria-roledescription="carousel"
|
||||
data-slot="carousel"
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
</CarouselContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { carouselRef, orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={carouselRef}
|
||||
className="overflow-hidden"
|
||||
data-slot="carousel-content"
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
"flex",
|
||||
orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselItem({ className, ...props }: React.ComponentProps<"div">) {
|
||||
const { orientation } = useCarousel()
|
||||
|
||||
return (
|
||||
<div
|
||||
role="group"
|
||||
aria-roledescription="slide"
|
||||
data-slot="carousel-item"
|
||||
className={cn(
|
||||
"min-w-0 shrink-0 grow-0 basis-full",
|
||||
orientation === "horizontal" ? "pl-4" : "pt-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselPrevious({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollPrev, canScrollPrev } = useCarousel()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-previous"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -left-12 -translate-y-1/2"
|
||||
: "-top-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollPrev}
|
||||
aria-label={t("shared.previous")}
|
||||
onClick={scrollPrev}
|
||||
{...props}
|
||||
>
|
||||
<ArrowLeftIcon aria-hidden="true" />
|
||||
<span className="sr-only">{t("shared.previous")}</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
function CarouselNext({
|
||||
className,
|
||||
variant = "outline",
|
||||
size = "icon",
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { orientation, scrollNext, canScrollNext } = useCarousel()
|
||||
const { t } = useTranslation()
|
||||
|
||||
return (
|
||||
<Button
|
||||
data-slot="carousel-next"
|
||||
variant={variant}
|
||||
size={size}
|
||||
className={cn(
|
||||
"absolute size-8 rounded-full",
|
||||
orientation === "horizontal"
|
||||
? "top-1/2 -right-12 -translate-y-1/2"
|
||||
: "-bottom-12 left-1/2 -translate-x-1/2 rotate-90",
|
||||
className
|
||||
)}
|
||||
disabled={!canScrollNext}
|
||||
aria-label={t("shared.next")}
|
||||
onClick={scrollNext}
|
||||
{...props}
|
||||
>
|
||||
<ArrowRightIcon aria-hidden="true" />
|
||||
<span className="sr-only">{t("shared.next")}</span>
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
type CarouselApi,
|
||||
Carousel,
|
||||
CarouselContent,
|
||||
CarouselItem,
|
||||
CarouselPrevious,
|
||||
CarouselNext,
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
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 };
|
||||
@@ -0,0 +1,58 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
|
||||
|
||||
import { Checkbox as SubframeCheckbox } from "~/ui/components/Checkbox"
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
// Subframe migration (strangler shim):
|
||||
// Keeps the original shadcn/Radix `Checkbox` API (`React.ComponentProps<typeof
|
||||
// CheckboxPrimitive.Root>`) but renders the Subframe design-system Checkbox behind it.
|
||||
//
|
||||
// Pitfalls handled here:
|
||||
// - Subframe's Checkbox is ALWAYS controlled (no uncontrolled/`defaultChecked` path), so
|
||||
// the shim owns the checked state with `useState` and only defers to the caller when
|
||||
// `checked` is supplied — preserving controlled + uncontrolled behavior.
|
||||
// - Radix `CheckedState` is `boolean | "indeterminate"`. Subframe splits this into separate
|
||||
// `checked` (boolean) + `indeterminate` (boolean) props, so the shim maps them apart and
|
||||
// re-assembles the `CheckedState` back into `onCheckedChange`.
|
||||
// - The bare checkbox renders just the box (no label), so Subframe's label slot is hidden by
|
||||
// default; a caller can still override `hideLabel`.
|
||||
function Checkbox({
|
||||
className,
|
||||
checked,
|
||||
defaultChecked,
|
||||
onCheckedChange,
|
||||
...props
|
||||
}: React.ComponentProps<typeof CheckboxPrimitive.Root>) {
|
||||
const isControlled = checked !== undefined
|
||||
const [internalChecked, setInternalChecked] = React.useState<CheckboxPrimitive.CheckedState>(
|
||||
defaultChecked ?? false
|
||||
)
|
||||
|
||||
const currentChecked = isControlled ? checked : internalChecked
|
||||
const indeterminate = currentChecked === "indeterminate"
|
||||
|
||||
const handleCheckedChange = (next: boolean) => {
|
||||
// When the box was indeterminate, a click resolves it to checked (Radix semantics).
|
||||
const resolved: CheckboxPrimitive.CheckedState = next
|
||||
if (!isControlled) {
|
||||
setInternalChecked(resolved)
|
||||
}
|
||||
onCheckedChange?.(resolved)
|
||||
}
|
||||
|
||||
return (
|
||||
<SubframeCheckbox
|
||||
hideLabel={true}
|
||||
{...props}
|
||||
checked={indeterminate ? false : Boolean(currentChecked)}
|
||||
indeterminate={indeterminate}
|
||||
onCheckedChange={handleCheckedChange}
|
||||
className={cn(className)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Checkbox }
|
||||
@@ -0,0 +1,72 @@
|
||||
// // "use client";
|
||||
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "~/components/ui/card";
|
||||
import { RadioGroupIndicator, RadioGroupItem, type RadioGroupItemProps } from "@radix-ui/react-radio-group";
|
||||
import { CircleIcon } from "~/components/ui/icons/vendor";
|
||||
import type { ComponentProps, HTMLAttributes } from "react";
|
||||
import { RadioGroup } from "~/components/ui/radio-group";
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
export type ChoiceboxProps = ComponentProps<typeof RadioGroup>;
|
||||
|
||||
export const Choicebox = ({ className, ...props }: ChoiceboxProps) => <RadioGroup className={cn("w-full", className)} {...props} />;
|
||||
|
||||
export type ChoiceboxItemProps = RadioGroupItemProps;
|
||||
|
||||
export const ChoiceboxItem = ({ className, children, ...props }: ChoiceboxItemProps) => (
|
||||
<RadioGroupItem
|
||||
className={cn(
|
||||
"text-left",
|
||||
'[&[data-state="checked"]]:border-foreground/30'
|
||||
// '[&[data-state="checked"]]:bg-primary-foreground'
|
||||
)}
|
||||
asChild
|
||||
{...props}
|
||||
>
|
||||
<Card className={cn("flex cursor-pointer flex-row items-center justify-between rounded-md p-4 shadow-none transition-all", className)}>{children}</Card>
|
||||
</RadioGroupItem>
|
||||
);
|
||||
|
||||
export type ChoiceboxItemHeaderProps = ComponentProps<typeof CardHeader>;
|
||||
|
||||
export const ChoiceboxItemHeader = ({ className, ...props }: ComponentProps<typeof CardHeader>) => (
|
||||
<CardHeader className={cn("flex-1 gap-0 p-0", className)} {...props} />
|
||||
);
|
||||
|
||||
export type ChoiceboxItemTitleProps = ComponentProps<typeof CardTitle>;
|
||||
|
||||
export const ChoiceboxItemTitle = ({ className, ...props }: ChoiceboxItemTitleProps) => (
|
||||
<CardTitle className={cn("flex items-center gap-2 text-sm font-medium [&[data-state='checked']]:font-bold", className)} {...props} />
|
||||
);
|
||||
|
||||
export type ChoiceboxItemSubtitleProps = HTMLAttributes<HTMLSpanElement>;
|
||||
|
||||
export const ChoiceboxItemSubtitle = ({ className, ...props }: ChoiceboxItemSubtitleProps) => (
|
||||
<span className={cn("text-text-neutral-tertiary text-xs font-normal", className)} {...props} />
|
||||
);
|
||||
|
||||
export type ChoiceboxItemDescriptionProps = ComponentProps<typeof CardDescription>;
|
||||
|
||||
export const ChoiceboxItemDescription = ({ className, ...props }: ChoiceboxItemDescriptionProps) => (
|
||||
<CardDescription className={cn("text-sm", className)} {...props} />
|
||||
);
|
||||
|
||||
export type ChoiceboxItemContentProps = ComponentProps<typeof CardContent>;
|
||||
|
||||
export const ChoiceboxItemContent = ({ className, ...props }: ChoiceboxItemContentProps) => (
|
||||
<CardContent
|
||||
className={cn(
|
||||
"border-border-strong text-primary focus-visible:border-brand-brand-border-solid-default focus-visible:shadow-focus aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:bg-input/30 dark:aria-invalid:ring-destructive/40 flex aspect-square size-4 shrink-0 items-center justify-center rounded-full border p-0 shadow-xs transition-[color,box-shadow] outline-none disabled:cursor-not-allowed disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
|
||||
export type ChoiceboxItemIndicatorProps = ComponentProps<typeof RadioGroupIndicator>;
|
||||
|
||||
export const ChoiceboxItemIndicator = ({ className, ...props }: ChoiceboxItemIndicatorProps) => (
|
||||
<RadioGroupIndicator asChild {...props}>
|
||||
<CircleIcon className={cn("fill-primary size-2", className)} />
|
||||
</RadioGroupIndicator>
|
||||
);
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"
|
||||
|
||||
function Collapsible({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
|
||||
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
|
||||
}
|
||||
|
||||
function CollapsibleTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleTrigger
|
||||
data-slot="collapsible-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CollapsibleContent({
|
||||
...props
|
||||
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
|
||||
return (
|
||||
<CollapsiblePrimitive.CollapsibleContent
|
||||
data-slot="collapsible-content"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Collapsible, CollapsibleTrigger, CollapsibleContent }
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
import { forwardRef, useMemo, useState } from "react";
|
||||
import { HexColorPicker } from "react-colorful";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "../popover";
|
||||
import { Button } from "../button";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Input } from "../input";
|
||||
import { Label } from "../label";
|
||||
|
||||
interface ColorPickerProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onBlur?: () => void;
|
||||
}
|
||||
|
||||
const ColorPicker = forwardRef<HTMLInputElement, Omit<React.ComponentProps<"button">, "value" | "onChange" | "onBlur"> & ColorPickerProps>(
|
||||
({ disabled, value, onChange, onBlur, name, className, ...props }, forwardedRef) => {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const parsedValue = useMemo(() => {
|
||||
return value || "#FFFFFF";
|
||||
}, [value]);
|
||||
|
||||
return (
|
||||
<Popover onOpenChange={setOpen} open={open}>
|
||||
<PopoverTrigger className="bg-surface-neutral-primary" asChild disabled={disabled} onBlur={onBlur}>
|
||||
<Button
|
||||
{...props}
|
||||
className={cn("block", className)}
|
||||
name={name}
|
||||
onClick={() => {
|
||||
setOpen(true);
|
||||
}}
|
||||
size="xs"
|
||||
style={{
|
||||
backgroundColor: parsedValue,
|
||||
}}
|
||||
variant="outline"
|
||||
>
|
||||
<div />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-full space-y-2">
|
||||
<Label className="text-sm">{props.title}</Label>
|
||||
<HexColorPicker color={parsedValue} onChange={onChange} />
|
||||
<Input
|
||||
// maxLength={7}
|
||||
onChange={(e) => {
|
||||
onChange(e?.currentTarget?.value);
|
||||
}}
|
||||
value={parsedValue}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
);
|
||||
ColorPicker.displayName = "ColorPicker";
|
||||
|
||||
export { ColorPicker };
|
||||
@@ -0,0 +1,107 @@
|
||||
import { t as i18nT } from "i18next";
|
||||
("use client");
|
||||
|
||||
import * as React from "react";
|
||||
import { Command as CommandPrimitive } from "cmdk";
|
||||
import { SearchIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "~/components/ui/dialog";
|
||||
|
||||
function Command({ className, ...props }: React.ComponentProps<typeof CommandPrimitive>) {
|
||||
return (
|
||||
<CommandPrimitive
|
||||
data-slot="command"
|
||||
className={cn("bg-surface-neutral-primary text-text-neutral-primary flex h-full w-full flex-col overflow-hidden rounded-md", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandDialog({
|
||||
title = i18nT("components.command.title"),
|
||||
description = i18nT("components.command.description"),
|
||||
children,
|
||||
dataUiId,
|
||||
onCloseAutoFocus,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Dialog> & {
|
||||
title?: string;
|
||||
description?: string;
|
||||
dataUiId?: string;
|
||||
onCloseAutoFocus?: (event: Event) => void;
|
||||
}) {
|
||||
return (
|
||||
<Dialog {...props}>
|
||||
<DialogHeader className="sr-only">
|
||||
<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">
|
||||
{children}
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandInput({ className, ...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" />
|
||||
<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",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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} />;
|
||||
}
|
||||
|
||||
function CommandEmpty({ ...props }: React.ComponentProps<typeof CommandPrimitive.Empty>) {
|
||||
return <CommandPrimitive.Empty data-slot="command-empty" className="py-6 text-center text-sm" {...props} />;
|
||||
}
|
||||
|
||||
function CommandGroup({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Group>) {
|
||||
return (
|
||||
<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",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandSeparator({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Separator>) {
|
||||
return <CommandPrimitive.Separator data-slot="command-separator" className={cn("bg-border-default -mx-1 h-px", className)} {...props} />;
|
||||
}
|
||||
|
||||
function CommandItem({ className, ...props }: React.ComponentProps<typeof CommandPrimitive.Item>) {
|
||||
return (
|
||||
<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",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function CommandShortcut({ className, ...props }: React.ComponentProps<"span">) {
|
||||
return <span data-slot="command-shortcut" className={cn("text-text-neutral-tertiary ml-auto text-xs tracking-widest", className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Command, CommandDialog, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem, CommandShortcut, CommandSeparator };
|
||||
+156
@@ -0,0 +1,156 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { fireEvent, render, screen, waitFor } 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 type { ScopedCommandAction } from "~/services/command-registry/commandRegistry";
|
||||
import CommandPalette from "./CommandPalette";
|
||||
|
||||
type CommandPaletteTestState = {
|
||||
navigate: ReturnType<typeof vi.fn>;
|
||||
getCommandRegistryActions: ReturnType<typeof vi.fn>;
|
||||
useAppOrAdminData: ReturnType<typeof vi.fn>;
|
||||
useRootData: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
|
||||
declare global {
|
||||
var __commandPaletteTest: CommandPaletteTestState;
|
||||
}
|
||||
|
||||
globalThis.__commandPaletteTest = {
|
||||
navigate: vi.fn(),
|
||||
getCommandRegistryActions: vi.fn(),
|
||||
useAppOrAdminData: vi.fn(),
|
||||
useRootData: vi.fn(),
|
||||
};
|
||||
|
||||
globalThis.ResizeObserver =
|
||||
globalThis.ResizeObserver ??
|
||||
class ResizeObserver {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
};
|
||||
HTMLElement.prototype.scrollIntoView = HTMLElement.prototype.scrollIntoView ?? vi.fn();
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({ t: (value: string) => value }),
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useFetcher: () => ({ submit: vi.fn() }),
|
||||
useNavigate: () => globalThis.__commandPaletteTest.navigate,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("~/utils/data/useAppOrAdminData", () => ({
|
||||
useAppOrAdminData: () => globalThis.__commandPaletteTest.useAppOrAdminData(),
|
||||
}));
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => globalThis.__commandPaletteTest.useRootData(),
|
||||
}));
|
||||
|
||||
vi.mock("~/services/command-registry/commandRegistry", () => ({
|
||||
getCommandRegistryActions: (...args: unknown[]) => globalThis.__commandPaletteTest.getCommandRegistryActions(...args),
|
||||
}));
|
||||
|
||||
const appData = { currentTenant: { slug: "acme" } };
|
||||
const rootData = { appConfiguration: { app: { features: {} } } };
|
||||
|
||||
function renderPalette(props?: Partial<React.ComponentProps<typeof CommandPalette>>) {
|
||||
return render(
|
||||
<CommandPalette layout="app" {...props}>
|
||||
<div>Palette child</div>
|
||||
</CommandPalette>
|
||||
);
|
||||
}
|
||||
|
||||
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");
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
const state = globalThis.__commandPaletteTest;
|
||||
state.navigate.mockReset();
|
||||
state.getCommandRegistryActions.mockReset();
|
||||
state.useAppOrAdminData.mockReset();
|
||||
state.useRootData.mockReset();
|
||||
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" } },
|
||||
]);
|
||||
});
|
||||
|
||||
function openPalette() {
|
||||
fireEvent.keyDown(document, { key: "k", metaKey: 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("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();
|
||||
openPalette();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(state.getCommandRegistryActions).toHaveBeenCalledWith(expect.objectContaining({ appData: undefined, rootData: undefined }));
|
||||
});
|
||||
expect(screen.getByText("Palette child")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders stable data-ui-id attributes for command palette surfaces and rows", async () => {
|
||||
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();
|
||||
});
|
||||
});
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
import { createContext, lazy, ReactNode, Suspense, useContext, useEffect, useMemo, useState } from "react";
|
||||
import type { ScopedCommandAction } from "~/services/command-registry/commandRegistry";
|
||||
|
||||
type CommandPaletteContextValue = {
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
toggle: () => void;
|
||||
};
|
||||
|
||||
const CommandPaletteContext = createContext<CommandPaletteContextValue | null>(null);
|
||||
const CommandPaletteDialog = lazy(() => import("./CommandPaletteDialog"));
|
||||
|
||||
export function useCommandPalette() {
|
||||
const context = useContext(CommandPaletteContext);
|
||||
return context ?? { open: false, setOpen: () => undefined, toggle: () => undefined };
|
||||
}
|
||||
|
||||
interface Props {
|
||||
layout?: "app" | "admin" | "docs";
|
||||
children: ReactNode;
|
||||
actions?: ScopedCommandAction[];
|
||||
}
|
||||
|
||||
export default function CommandPalette({ layout, children, actions }: Props) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
const contextValue = useMemo(
|
||||
() => ({
|
||||
open,
|
||||
setOpen,
|
||||
toggle: () => setOpen((value) => !value),
|
||||
}),
|
||||
[open]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
function onKeyDown(event: KeyboardEvent) {
|
||||
if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
|
||||
event.preventDefault();
|
||||
setOpen((value) => !value);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener("keydown", onKeyDown);
|
||||
return () => document.removeEventListener("keydown", onKeyDown);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<CommandPaletteContext.Provider value={contextValue}>
|
||||
{open ? (
|
||||
<Suspense fallback={null}>
|
||||
<CommandPaletteDialog actions={actions} layout={layout} open={open} setOpen={setOpen} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
{children}
|
||||
</CommandPaletteContext.Provider>
|
||||
);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
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 { getCommandRegistryActions, type CommandRegistryLayout, type ScopedCommandAction } from "~/services/command-registry/commandRegistry";
|
||||
import type { AppLoaderData } from "~/utils/data/useAppData";
|
||||
import { useAppOrAdminData } from "~/utils/data/useAppOrAdminData";
|
||||
import { useRootData } from "~/utils/data/useRootData";
|
||||
|
||||
export default function CommandPaletteDialog({
|
||||
actions,
|
||||
layout,
|
||||
open,
|
||||
setOpen,
|
||||
}: {
|
||||
actions?: ScopedCommandAction[];
|
||||
layout?: CommandRegistryLayout;
|
||||
open: boolean;
|
||||
setOpen: (open: boolean) => void;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const fetcher = useFetcher();
|
||||
const appData = useAppOrAdminData() as AppLoaderData | undefined;
|
||||
const rootData = useRootData();
|
||||
|
||||
const resolvedActions =
|
||||
actions ??
|
||||
(layout
|
||||
? getCommandRegistryActions({
|
||||
layout,
|
||||
t,
|
||||
i18n,
|
||||
navigate,
|
||||
submitLogout: () => {
|
||||
const form = new FormData();
|
||||
if (rootData?.csrf) {
|
||||
form.set("csrf", rootData.csrf);
|
||||
}
|
||||
fetcher.submit(form, { method: "post", action: "/logout" });
|
||||
},
|
||||
appData,
|
||||
rootData,
|
||||
})
|
||||
: []);
|
||||
|
||||
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;
|
||||
if (trigger) {
|
||||
event.preventDefault();
|
||||
trigger.focus();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<CommandInput data-ui-id={UI_SURFACE_IDS.commandPaletteSearch} />
|
||||
<CommandList data-ui-id={UI_SURFACE_IDS.commandPaletteResults}>
|
||||
<CommandEmpty>{t("app.commands.empty.title")}</CommandEmpty>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
function ContextMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {
|
||||
return <ContextMenuPrimitive.Root data-slot="context-menu" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Trigger data-slot="context-menu-trigger" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Group>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Group data-slot="context-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal data-slot="context-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Sub>) {
|
||||
return <ContextMenuPrimitive.Sub data-slot="context-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function ContextMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioGroup
|
||||
data-slot="context-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubTrigger
|
||||
data-slot="context-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
// Subframe DropdownItem layout: rounded-md px-2 py-2 (sub-menu has no Subframe flyout pendant)
|
||||
"focus:bg-surface-neutral-secondary focus:text-text-neutral-primary data-[state=open]:bg-surface-neutral-secondary data-[state=open]:text-text-neutral-primary flex cursor-default items-center rounded-md px-2 py-2 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto" />
|
||||
</ContextMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.SubContent
|
||||
data-slot="context-menu-sub-content"
|
||||
className={cn(
|
||||
// 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",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Content>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Portal>
|
||||
<ContextMenuPrimitive.Content
|
||||
data-slot="context-menu-content"
|
||||
className={cn(
|
||||
// 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",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</ContextMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Item
|
||||
data-slot="context-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
// Subframe DropdownItem layout: gap-2 rounded-md px-2 py-2
|
||||
"focus:bg-surface-neutral-secondary focus:text-text-neutral-primary data-[variant=destructive]:text-text-feedback-negative data-[variant=destructive]:focus:bg-surface-feedback-solid-negative-default/10 dark:data-[variant=destructive]:focus:bg-surface-feedback-solid-negative-default/20 data-[variant=destructive]:focus:text-text-feedback-negative data-[variant=destructive]:*:[svg]:!text-text-feedback-negative [&_svg:not([class*='text-'])]:text-text-neutral-tertiary relative flex cursor-default items-center gap-2 rounded-md px-2 py-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.CheckboxItem
|
||||
data-slot="context-menu-checkbox-item"
|
||||
className={cn(
|
||||
// Subframe DropdownItem layout: gap-2 rounded-md py-2 (pl-8 indicator slot kept from Radix; no Subframe pendant)
|
||||
"focus:bg-surface-neutral-secondary focus:text-text-neutral-primary relative flex cursor-default items-center gap-2 rounded-md py-2 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.RadioItem
|
||||
data-slot="context-menu-radio-item"
|
||||
className={cn(
|
||||
// Subframe DropdownItem layout: gap-2 rounded-md py-2 (pl-8 indicator slot kept from Radix; no Subframe pendant)
|
||||
"focus:bg-surface-neutral-secondary focus:text-text-neutral-primary relative flex cursor-default items-center gap-2 rounded-md py-2 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<ContextMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</ContextMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</ContextMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Label
|
||||
data-slot="context-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"text-text-neutral-primary px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<ContextMenuPrimitive.Separator
|
||||
data-slot="context-menu-separator"
|
||||
className={cn("bg-border-default -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function ContextMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="context-menu-shortcut"
|
||||
className={cn(
|
||||
"text-text-neutral-tertiary ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
ContextMenu,
|
||||
ContextMenuTrigger,
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuCheckboxItem,
|
||||
ContextMenuRadioItem,
|
||||
ContextMenuLabel,
|
||||
ContextMenuSeparator,
|
||||
ContextMenuShortcut,
|
||||
ContextMenuGroup,
|
||||
ContextMenuPortal,
|
||||
ContextMenuSub,
|
||||
ContextMenuSubContent,
|
||||
ContextMenuSubTrigger,
|
||||
ContextMenuRadioGroup,
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
import { render } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import DateCell from "./DateCell";
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
i18n: { language: "en" },
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("DateCell", () => {
|
||||
it("renders date with default displays", () => {
|
||||
const date = new Date(Date.now() - 60 * 60 * 1000);
|
||||
const { container } = render(<DateCell date={date} />);
|
||||
expect(container.querySelector("div")).not.toBeNull();
|
||||
expect(container.querySelector("div")?.getAttribute("title")).toBeTruthy();
|
||||
expect(container.textContent).toMatch(/ago|vor/i);
|
||||
});
|
||||
|
||||
it("renders date with specific displays", () => {
|
||||
const date = new Date(Date.now() - 60 * 60 * 1000);
|
||||
const { container } = render(<DateCell date={date} displays={["dm", "ago"]} />);
|
||||
expect(container.querySelector("div")).not.toBeNull();
|
||||
expect(container.querySelector("div")?.getAttribute("title")).toBeTruthy();
|
||||
expect(container.textContent).toMatch(/ago|vor/i);
|
||||
expect(container.textContent).not.toContain("ymd");
|
||||
});
|
||||
|
||||
it("renders empty when date is null", () => {
|
||||
const { container } = render(<DateCell date={null} />);
|
||||
expect(container.querySelector("div")).toBeNull();
|
||||
});
|
||||
});
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
import clsx from "clsx";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
import type { DateDisplay } from "~/utils/shared/DateUtils";
|
||||
|
||||
export default function DateCell({ date, displays = ["ymd", "ago"], className }: { date: Date | null; displays?: DateDisplay[]; className?: string }) {
|
||||
const fmt = useLocaleFormatters();
|
||||
return (
|
||||
<>
|
||||
{date && (
|
||||
<div title={fmt.dateTime(date)} className={cn("flex flex-col", className)}>
|
||||
{displays.includes("ymd") && <div>{fmt.date(date, { dateStyle: "medium" })}</div>}
|
||||
{displays.includes("dm") && <div>{fmt.date(date, { day: "numeric", month: "short" })}</div>}
|
||||
{displays.includes("mdy") && <div>{fmt.date(date, { dateStyle: "long" })}</div>}
|
||||
{displays.includes("hms") && <div>{fmt.date(date, { timeStyle: "medium" })}</div>}
|
||||
{displays.includes("ymdhms") && <div>{fmt.dateTime(date)}</div>}
|
||||
{displays.includes("ymdhmsms") && (
|
||||
<div>
|
||||
{fmt.date(date, {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
fractionalSecondDigits: 3,
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{displays.includes("ago") && <div className={clsx(displays.length > 1 && "text-xs")}>{fmt.relativeDate(date)}</div>}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createDateRangePresets, getDateKeyInTimezone } from "./DateRangeFilter";
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
describe("createDateRangePresets", () => {
|
||||
it("uses translated labels for short preset names", () => {
|
||||
const presets = createDateRangePresets("UTC", (key) => {
|
||||
const copy: Record<string, string> = {
|
||||
"shared.dateRange.today": "Heute",
|
||||
"shared.dateRange.yesterday": "Gestern",
|
||||
"shared.dateRange.last7Days": "Letzte 7 Tage",
|
||||
"shared.dateRange.last14Days": "Letzte 14 Tage",
|
||||
"shared.dateRange.last30Days": "Letzte 30 Tage",
|
||||
"shared.dateRange.thisWeek": "Diese Woche",
|
||||
"shared.dateRange.lastWeek": "Letzte Woche",
|
||||
"shared.dateRange.thisMonth": "Dieser Monat",
|
||||
"shared.dateRange.lastMonth": "Letzter Monat",
|
||||
"shared.dateRange.thisYear": "Dieses Jahr",
|
||||
"shared.dateRange.custom": "Benutzerdefiniert",
|
||||
};
|
||||
return copy[key] ?? key;
|
||||
});
|
||||
|
||||
expect(presets.find((preset) => preset.value === "today")?.label).toBe("Heute");
|
||||
expect(presets.find((preset) => preset.value === "yesterday")?.label).toBe("Gestern");
|
||||
expect(presets.find((preset) => preset.value === "last-7-days")?.label).toBe("Letzte 7 Tage");
|
||||
expect(presets.find((preset) => preset.value === "last-14-days")?.label).toBe("Letzte 14 Tage");
|
||||
expect(presets.find((preset) => preset.value === "last-30-days")?.label).toBe("Letzte 30 Tage");
|
||||
expect(presets.find((preset) => preset.value === "this-week")?.label).toBe("Diese Woche");
|
||||
expect(presets.find((preset) => preset.value === "last-week")?.label).toBe("Letzte Woche");
|
||||
expect(presets.find((preset) => preset.value === "this-month")?.label).toBe("Dieser Monat");
|
||||
expect(presets.find((preset) => preset.value === "last-month")?.label).toBe("Letzter Monat");
|
||||
expect(presets.find((preset) => preset.value === "this-year")?.label).toBe("Dieses Jahr");
|
||||
expect(presets.find((preset) => preset.value === "custom")?.label).toBe("Benutzerdefiniert");
|
||||
});
|
||||
|
||||
it("does not depend on autogenerated keys for preset labels", () => {
|
||||
const source = createDateRangePresets.toString();
|
||||
|
||||
expect(source).not.toContain("ui.autogenerated");
|
||||
});
|
||||
|
||||
it("uses the active locale week start for week presets", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-05-27T12:00:00Z"));
|
||||
|
||||
const germanWeek = createDateRangePresets("UTC", (key) => key, { weekStartsOn: 1 }).find((preset) => preset.value === "this-week")?.getRange();
|
||||
const englishWeek = createDateRangePresets("UTC", (key) => key, { weekStartsOn: 0 }).find((preset) => preset.value === "this-week")?.getRange();
|
||||
|
||||
expect(germanWeek).toBeDefined();
|
||||
expect(englishWeek).toBeDefined();
|
||||
expect(getDateKeyInTimezone(germanWeek!.from, "UTC")).toBe("2026-05-25");
|
||||
expect(getDateKeyInTimezone(germanWeek!.to, "UTC")).toBe("2026-05-31");
|
||||
expect(getDateKeyInTimezone(englishWeek!.from, "UTC")).toBe("2026-05-24");
|
||||
expect(getDateKeyInTimezone(englishWeek!.to, "UTC")).toBe("2026-05-30");
|
||||
});
|
||||
});
|
||||
+469
@@ -0,0 +1,469 @@
|
||||
import { useState, useEffect, useMemo } from "react";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { CalendarIcon } from "~/components/ui/icons/vendor";
|
||||
import { DateRange } from "react-day-picker";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { Button } from "~/components/ui/button";
|
||||
import { Calendar } from "~/components/ui/calendar";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "~/components/ui/popover";
|
||||
import { Separator } from "~/components/ui/separator";
|
||||
import { toZonedTime, formatInTimeZone } from "date-fns-tz";
|
||||
import { getLocaleWeekStartsOn } from "~/locale/date-fns";
|
||||
import { useLocaleFormatters } from "~/locale/format";
|
||||
|
||||
type DateRangeTranslator = (key: string) => string;
|
||||
|
||||
export type DateRangePreset = {
|
||||
value: string;
|
||||
label: string;
|
||||
getRange: () => { from: Date; to: Date };
|
||||
};
|
||||
|
||||
type DateRangePresetOptions = {
|
||||
weekStartsOn?: 0 | 1 | 2 | 3 | 4 | 5 | 6;
|
||||
};
|
||||
|
||||
export function getDateKeyInTimezone(date: Date, timezone: string): string {
|
||||
return formatInTimeZone(date, timezone, "yyyy-MM-dd");
|
||||
}
|
||||
|
||||
// Factory function to create timezone-aware presets
|
||||
export const createDateRangePresets = (
|
||||
timezone: string,
|
||||
t: DateRangeTranslator = (key) => String(i18nT(key)),
|
||||
options: DateRangePresetOptions = {}
|
||||
): DateRangePreset[] => {
|
||||
const weekStartsOn = options.weekStartsOn ?? 1;
|
||||
// Helper function to get start and end of day in a specific timezone
|
||||
const getDateRangeInTimezone = (date: Date, timezone: string) => {
|
||||
const zonedDate = toZonedTime(date, timezone);
|
||||
const year = zonedDate.getFullYear();
|
||||
const month = String(zonedDate.getMonth() + 1).padStart(2, "0");
|
||||
const day = String(zonedDate.getDate()).padStart(2, "0");
|
||||
|
||||
const startStr = `${year}-${month}-${day}T00:00:00`;
|
||||
const endStr = `${year}-${month}-${day}T23:59:59.999`;
|
||||
|
||||
const startOffset = formatInTimeZone(new Date(startStr), timezone, "xxx");
|
||||
const endOffset = formatInTimeZone(new Date(endStr), timezone, "xxx");
|
||||
|
||||
const startIsoString = `${startStr}${startOffset}`;
|
||||
const endIsoString = `${endStr}${endOffset}`;
|
||||
|
||||
return {
|
||||
from: new Date(startIsoString),
|
||||
to: new Date(endIsoString),
|
||||
};
|
||||
};
|
||||
|
||||
return [
|
||||
{
|
||||
value: "today",
|
||||
label: t("shared.dateRange.today"),
|
||||
getRange: () => {
|
||||
const now = new Date();
|
||||
return getDateRangeInTimezone(now, timezone);
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "yesterday",
|
||||
label: t("shared.dateRange.yesterday"),
|
||||
getRange: () => {
|
||||
const yesterday = new Date();
|
||||
yesterday.setDate(yesterday.getDate() - 1);
|
||||
return getDateRangeInTimezone(yesterday, timezone);
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "last-7-days",
|
||||
label: t("shared.dateRange.last7Days"),
|
||||
getRange: () => {
|
||||
const end = new Date();
|
||||
const endRange = getDateRangeInTimezone(end, timezone);
|
||||
const start = new Date();
|
||||
start.setDate(start.getDate() - 7);
|
||||
const startRange = getDateRangeInTimezone(start, timezone);
|
||||
return { from: startRange.from, to: endRange.to };
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "last-14-days",
|
||||
label: t("shared.dateRange.last14Days"),
|
||||
getRange: () => {
|
||||
const end = new Date();
|
||||
const endRange = getDateRangeInTimezone(end, timezone);
|
||||
const start = new Date();
|
||||
start.setDate(start.getDate() - 14);
|
||||
const startRange = getDateRangeInTimezone(start, timezone);
|
||||
return { from: startRange.from, to: endRange.to };
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "last-30-days",
|
||||
label: t("shared.dateRange.last30Days"),
|
||||
getRange: () => {
|
||||
const end = new Date();
|
||||
const endRange = getDateRangeInTimezone(end, timezone);
|
||||
const start = new Date();
|
||||
start.setDate(start.getDate() - 30);
|
||||
const startRange = getDateRangeInTimezone(start, timezone);
|
||||
return { from: startRange.from, to: endRange.to };
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "this-week",
|
||||
label: t("shared.dateRange.thisWeek"),
|
||||
getRange: () => {
|
||||
const now = new Date();
|
||||
const zonedNow = toZonedTime(now, timezone);
|
||||
const dayOfWeek = zonedNow.getDay();
|
||||
const daysSinceWeekStart = (dayOfWeek - weekStartsOn + 7) % 7;
|
||||
const start = new Date(zonedNow);
|
||||
start.setDate(zonedNow.getDate() - daysSinceWeekStart);
|
||||
const startRange = getDateRangeInTimezone(start, timezone);
|
||||
const end = new Date(start);
|
||||
end.setDate(start.getDate() + 6);
|
||||
const endRange = getDateRangeInTimezone(end, timezone);
|
||||
return { from: startRange.from, to: endRange.to };
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "last-week",
|
||||
label: t("shared.dateRange.lastWeek"),
|
||||
getRange: () => {
|
||||
const now = new Date();
|
||||
const zonedNow = toZonedTime(now, timezone);
|
||||
const dayOfWeek = zonedNow.getDay();
|
||||
const daysSinceWeekStart = (dayOfWeek - weekStartsOn + 7) % 7;
|
||||
const start = new Date(zonedNow);
|
||||
start.setDate(zonedNow.getDate() - daysSinceWeekStart - 7);
|
||||
const startRange = getDateRangeInTimezone(start, timezone);
|
||||
const end = new Date(start);
|
||||
end.setDate(start.getDate() + 6);
|
||||
const endRange = getDateRangeInTimezone(end, timezone);
|
||||
return { from: startRange.from, to: endRange.to };
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "this-month",
|
||||
label: t("shared.dateRange.thisMonth"),
|
||||
getRange: () => {
|
||||
const now = new Date();
|
||||
const zonedNow = toZonedTime(now, timezone);
|
||||
const start = new Date(zonedNow.getFullYear(), zonedNow.getMonth(), 1);
|
||||
const startRange = getDateRangeInTimezone(start, timezone);
|
||||
const end = new Date(zonedNow.getFullYear(), zonedNow.getMonth() + 1, 0);
|
||||
const endRange = getDateRangeInTimezone(end, timezone);
|
||||
return { from: startRange.from, to: endRange.to };
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "last-month",
|
||||
label: t("shared.dateRange.lastMonth"),
|
||||
getRange: () => {
|
||||
const now = new Date();
|
||||
const zonedNow = toZonedTime(now, timezone);
|
||||
const start = new Date(zonedNow.getFullYear(), zonedNow.getMonth() - 1, 1);
|
||||
const startRange = getDateRangeInTimezone(start, timezone);
|
||||
const end = new Date(zonedNow.getFullYear(), zonedNow.getMonth(), 0);
|
||||
const endRange = getDateRangeInTimezone(end, timezone);
|
||||
return { from: startRange.from, to: endRange.to };
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "this-year",
|
||||
label: t("shared.dateRange.thisYear"),
|
||||
getRange: () => {
|
||||
const now = new Date();
|
||||
const zonedNow = toZonedTime(now, timezone);
|
||||
const start = new Date(zonedNow.getFullYear(), 0, 1);
|
||||
const startRange = getDateRangeInTimezone(start, timezone);
|
||||
const end = new Date(zonedNow.getFullYear(), 11, 31);
|
||||
const endRange = getDateRangeInTimezone(end, timezone);
|
||||
return { from: startRange.from, to: endRange.to };
|
||||
},
|
||||
},
|
||||
{
|
||||
value: "custom",
|
||||
label: t("shared.dateRange.custom"),
|
||||
getRange: () => {
|
||||
return { from: new Date(), to: new Date() };
|
||||
},
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
// Default presets for backward compatibility
|
||||
export const dateRangePresets = createDateRangePresets("UTC");
|
||||
|
||||
interface DateRangeFilterProps {
|
||||
value?: DateRange;
|
||||
onChange: (range: DateRange | undefined) => void;
|
||||
placeholder?: string;
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
showPresets?: boolean;
|
||||
align?: "start" | "center" | "end";
|
||||
size?: "xs" | "default" | "sm" | "lg";
|
||||
childclass?: string;
|
||||
variant?: "default" | "full";
|
||||
}
|
||||
|
||||
export function DateRangeFilter({
|
||||
value,
|
||||
onChange,
|
||||
placeholder = i18nT("shared.dateRange.pickRange"),
|
||||
className,
|
||||
disabled = false,
|
||||
size = "default",
|
||||
childclass,
|
||||
variant = "default",
|
||||
}: DateRangeFilterProps) {
|
||||
const { t } = useTranslation();
|
||||
const formatters = useLocaleFormatters();
|
||||
const weekStartsOn = getLocaleWeekStartsOn(formatters.locale);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [tempDateRange, setTempDateRange] = useState<DateRange | undefined>(value);
|
||||
const [activePreset, setActivePreset] = useState<string | null>(null);
|
||||
const [showPresets, setShowPresets] = useState(value ? false : true);
|
||||
|
||||
// Get timezone from app data, fall back to UTC if not available
|
||||
let timezone = "UTC";
|
||||
// try {
|
||||
// const appData = useAppData();
|
||||
// timezone = appData?.timezone || "UTC";
|
||||
// } catch (error) {
|
||||
// // useAppData might not be available in all contexts, fall back to UTC
|
||||
// console.debug("DateRangeFilter: useAppData not available, using UTC timezone");
|
||||
// }
|
||||
|
||||
// Create timezone-aware presets
|
||||
const dateRangePresetsWithTimezone = useMemo(
|
||||
() => createDateRangePresets(timezone, (key) => String(t(key)), { weekStartsOn }),
|
||||
[t, timezone, weekStartsOn]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setTempDateRange(value);
|
||||
// Check if current value matches any preset
|
||||
if (value?.from && value?.to) {
|
||||
const valueFrom = value.from;
|
||||
const valueTo = value.to;
|
||||
const matchingPreset = dateRangePresetsWithTimezone.find((preset) => {
|
||||
const range = preset.getRange();
|
||||
return (
|
||||
getDateKeyInTimezone(range.from, timezone) === getDateKeyInTimezone(valueFrom, timezone) &&
|
||||
getDateKeyInTimezone(range.to, timezone) === getDateKeyInTimezone(valueTo, timezone)
|
||||
);
|
||||
});
|
||||
setActivePreset(matchingPreset?.value || null);
|
||||
} else {
|
||||
setActivePreset(null);
|
||||
}
|
||||
}, [dateRangePresetsWithTimezone, value, timezone]);
|
||||
|
||||
const handlePresetClick = (presetValue: string) => {
|
||||
const preset = dateRangePresetsWithTimezone.find((p) => p.value === presetValue);
|
||||
if (preset) {
|
||||
if (preset.value === "custom") {
|
||||
setShowPresets(false);
|
||||
} else {
|
||||
const range = preset.getRange();
|
||||
setTempDateRange(range);
|
||||
setActivePreset(presetValue);
|
||||
onChange(range);
|
||||
setOpen(false);
|
||||
setShowPresets(true);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDateRangeChange = (range: DateRange | undefined) => {
|
||||
setTempDateRange(range);
|
||||
setActivePreset(null);
|
||||
};
|
||||
|
||||
const handleApply = () => {
|
||||
// Adjust the date range to include the full day in the user's timezone
|
||||
if (tempDateRange?.from) {
|
||||
// Convert the selected dates to the user's timezone and get start/end of day
|
||||
const zonedFromDate = toZonedTime(tempDateRange.from, timezone);
|
||||
const fromYear = zonedFromDate.getFullYear();
|
||||
const fromMonth = String(zonedFromDate.getMonth() + 1).padStart(2, "0");
|
||||
const fromDay = String(zonedFromDate.getDate()).padStart(2, "0");
|
||||
|
||||
const fromStartStr = `${fromYear}-${fromMonth}-${fromDay}T00:00:00`;
|
||||
const fromOffset = formatInTimeZone(new Date(fromStartStr), timezone, "xxx");
|
||||
const fromIsoString = `${fromStartStr}${fromOffset}`;
|
||||
|
||||
const adjustedRange: DateRange = {
|
||||
from: new Date(fromIsoString),
|
||||
};
|
||||
|
||||
if (tempDateRange.to) {
|
||||
// Set the end date to the end of the day in the user's timezone
|
||||
const zonedToDate = toZonedTime(tempDateRange.to, timezone);
|
||||
const toYear = zonedToDate.getFullYear();
|
||||
const toMonth = String(zonedToDate.getMonth() + 1).padStart(2, "0");
|
||||
const toDay = String(zonedToDate.getDate()).padStart(2, "0");
|
||||
|
||||
const toEndStr = `${toYear}-${toMonth}-${toDay}T23:59:59.999`;
|
||||
const toOffset = formatInTimeZone(new Date(toEndStr), timezone, "xxx");
|
||||
const toIsoString = `${toEndStr}${toOffset}`;
|
||||
|
||||
adjustedRange.to = new Date(toIsoString);
|
||||
}
|
||||
|
||||
onChange(adjustedRange);
|
||||
} else {
|
||||
onChange(tempDateRange);
|
||||
}
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setTempDateRange(undefined);
|
||||
setActivePreset(null);
|
||||
onChange(undefined);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const formatDateRange = () => {
|
||||
const range = value;
|
||||
if (!range?.from) return placeholder;
|
||||
if (!range.to) return formatters.date(range.from, { dateStyle: "medium", timeZone: timezone });
|
||||
|
||||
// Check if the current range matches any preset
|
||||
for (const preset of dateRangePresetsWithTimezone) {
|
||||
const presetRange = preset.getRange();
|
||||
if (
|
||||
getDateKeyInTimezone(range.from, timezone) === getDateKeyInTimezone(presetRange.from, timezone) &&
|
||||
getDateKeyInTimezone(range.to, timezone) === getDateKeyInTimezone(presetRange.to, timezone)
|
||||
) {
|
||||
return preset.label;
|
||||
}
|
||||
}
|
||||
|
||||
return `${formatters.date(range.from, { dateStyle: "medium", timeZone: timezone })} - ${formatters.date(range.to, {
|
||||
dateStyle: "medium",
|
||||
timeZone: timezone,
|
||||
})}`;
|
||||
};
|
||||
|
||||
const hasValue = value?.from || value?.to;
|
||||
|
||||
return (
|
||||
<div className={cn("grid gap-2", className)}>
|
||||
<Popover modal={true} open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button id="date" variant="outline" size={size} className={cn("justify-start truncate pl-3 text-left font-normal", childclass)} disabled={disabled}>
|
||||
{variant === "full" && (
|
||||
<div className={cn("flex items-center gap-2 truncate", !hasValue && "text-text-neutral-tertiary")}>
|
||||
<CalendarIcon className="size-3.5" />
|
||||
<div className="truncate">{formatDateRange()}</div>
|
||||
</div>
|
||||
)}
|
||||
{variant === "default" && (
|
||||
<div className="flex items-center gap-2">
|
||||
<CalendarIcon className="size-3.5" />
|
||||
<div className="hidden 2xl:block">{formatDateRange()}</div>
|
||||
</div>
|
||||
)}
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="bg-surface-neutral-primary mb-4 overflow-y-auto p-3" side="bottom" sideOffset={4}>
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-between gap-2">
|
||||
<div className="flex flex-1 gap-2">
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleReset} disabled={!value && !tempDateRange}>
|
||||
{t("shared.reset")}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" size="sm" onClick={() => setShowPresets(!showPresets)}>
|
||||
{showPresets ? t("shared.dateRange.custom") : t("shared.dateRange.presets")}
|
||||
</Button>
|
||||
</div>
|
||||
<Button type="button" variant="outline" size="sm" onClick={handleApply} disabled={disabled}>
|
||||
{t("shared.apply")}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="max-h-[200px] space-y-3 overflow-y-auto pb-4 sm:max-h-[400px]">
|
||||
{showPresets && (
|
||||
<div className="grid grid-cols-2 gap-1">
|
||||
{dateRangePresetsWithTimezone.map((preset) => (
|
||||
<Button
|
||||
key={preset.value}
|
||||
variant={activePreset === preset.value ? "secondary" : "ghost"}
|
||||
size="sm"
|
||||
className="justify-start"
|
||||
onClick={() => handlePresetClick(preset.value)}
|
||||
>
|
||||
{preset.label}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{/* {showPresets && <Separator />} */}
|
||||
{!showPresets && (
|
||||
<div className="space-y-3">
|
||||
<Calendar
|
||||
mode="range"
|
||||
selected={tempDateRange}
|
||||
onSelect={handleDateRangeChange}
|
||||
defaultMonth={tempDateRange?.from}
|
||||
numberOfMonths={1}
|
||||
disabled={disabled}
|
||||
className="bg-surface-neutral-primary rounded-md border"
|
||||
/>
|
||||
{tempDateRange?.from && (
|
||||
<div className="text-text-neutral-tertiary text-center text-xs">
|
||||
{tempDateRange.from && !tempDateRange.to && t("shared.dateRange.selectEndDate")}
|
||||
{tempDateRange.from && tempDateRange.to && (
|
||||
<>
|
||||
{formatters.date(tempDateRange.from, { dateStyle: "medium" })} - {formatters.date(tempDateRange.to, { dateStyle: "medium" })}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Helper function to convert DateRange to query params
|
||||
export function dateRangeToParams(range: DateRange | undefined): { fromDate?: string; toDate?: string } {
|
||||
if (!range?.from) return {};
|
||||
|
||||
const params: { fromDate?: string; toDate?: string } = {
|
||||
fromDate: range.from.toISOString(),
|
||||
};
|
||||
|
||||
if (range.to) {
|
||||
params.toDate = range.to.toISOString();
|
||||
}
|
||||
|
||||
return params;
|
||||
}
|
||||
|
||||
// Helper function to convert query params to DateRange
|
||||
export function paramsToDateRange(fromDate?: string | null, toDate?: string | null): DateRange | undefined {
|
||||
if (!fromDate) return undefined;
|
||||
|
||||
const range: DateRange = {
|
||||
from: new Date(fromDate),
|
||||
};
|
||||
|
||||
if (toDate) {
|
||||
range.to = new Date(toDate);
|
||||
}
|
||||
|
||||
return range;
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { useSearchParams } from "react-router";
|
||||
import { DateRange } from "react-day-picker";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { FilterDto } from "~/components/ui/input/InputFilters";
|
||||
import { DateRangeFilter, dateRangeToParams, paramsToDateRange } from "./DateRangeFilter";
|
||||
|
||||
interface DateRangeInputFilterProps {
|
||||
name?: string;
|
||||
className?: string;
|
||||
placeholder?: string;
|
||||
onChange?: (range: DateRange | undefined) => void;
|
||||
childclass?: string;
|
||||
size?: "xs" | "default" | "sm" | "lg";
|
||||
variant?: "default" | "full";
|
||||
defaultRange?: DateRange;
|
||||
}
|
||||
|
||||
export function DateRangeInputFilter({
|
||||
name = "dateRange",
|
||||
className,
|
||||
placeholder,
|
||||
onChange,
|
||||
childclass,
|
||||
size,
|
||||
variant = "default",
|
||||
defaultRange,
|
||||
}: DateRangeInputFilterProps) {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [dateRange, setDateRange] = useState<DateRange | undefined>(defaultRange);
|
||||
|
||||
useEffect(() => {
|
||||
const fromDate = searchParams.get(`${name}From`);
|
||||
const toDate = searchParams.get(`${name}To`);
|
||||
if (!fromDate && !toDate) {
|
||||
setDateRange(defaultRange);
|
||||
} else {
|
||||
const range = paramsToDateRange(fromDate, toDate);
|
||||
setDateRange(range);
|
||||
}
|
||||
}, [searchParams, name]);
|
||||
|
||||
const handleDateRangeChange = (range: DateRange | undefined) => {
|
||||
setDateRange(range);
|
||||
|
||||
// Update search params
|
||||
const params = dateRangeToParams(range);
|
||||
|
||||
if (params.fromDate) {
|
||||
searchParams.set(`${name}From`, params.fromDate);
|
||||
} else {
|
||||
searchParams.delete(`${name}From`);
|
||||
}
|
||||
|
||||
if (params.toDate) {
|
||||
searchParams.set(`${name}To`, params.toDate);
|
||||
} else {
|
||||
searchParams.delete(`${name}To`);
|
||||
}
|
||||
|
||||
searchParams.delete("page"); // Reset pagination
|
||||
setSearchParams(searchParams);
|
||||
|
||||
// Call onChange callback if provided
|
||||
onChange?.(range);
|
||||
};
|
||||
|
||||
return (
|
||||
<DateRangeFilter
|
||||
variant={variant}
|
||||
value={dateRange}
|
||||
onChange={handleDateRangeChange}
|
||||
placeholder={placeholder}
|
||||
className={className}
|
||||
size={size}
|
||||
childclass={childclass}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Create a filter definition for InputFilters component
|
||||
export function createDateRangeFilter(options?: { name?: string; title?: string; fromParam?: string; toParam?: string }): FilterDto[] {
|
||||
const name = options?.name || "dateRange";
|
||||
const title = options?.title || i18nT("shared.dateRange.label");
|
||||
const fromParam = options?.fromParam || `${name}From`;
|
||||
const toParam = options?.toParam || `${name}To`;
|
||||
|
||||
return [
|
||||
{
|
||||
name: fromParam,
|
||||
title: i18nT("shared.dateRange.from", { title }),
|
||||
hideSearch: true,
|
||||
},
|
||||
{
|
||||
name: toParam,
|
||||
title: i18nT("shared.dateRange.to", { title }),
|
||||
hideSearch: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import * as React from "react";
|
||||
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { XIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
|
||||
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
|
||||
}
|
||||
|
||||
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
|
||||
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
|
||||
}
|
||||
|
||||
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
|
||||
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
|
||||
}
|
||||
|
||||
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
|
||||
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
|
||||
}
|
||||
|
||||
function DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Overlay>) {
|
||||
return (
|
||||
<DialogPrimitive.Overlay
|
||||
data-slot="dialog-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogContent({
|
||||
className,
|
||||
children,
|
||||
withCloseButton = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DialogPrimitive.Content> & { withCloseButton?: boolean }) {
|
||||
return (
|
||||
<DialogPortal data-slot="dialog-portal">
|
||||
<DialogOverlay />
|
||||
<DialogPrimitive.Content
|
||||
data-slot="dialog-content"
|
||||
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",
|
||||
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">
|
||||
<XIcon />
|
||||
<span className="sr-only">{i18nT("shared.close")}</span>
|
||||
</DialogPrimitive.Close>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
);
|
||||
}
|
||||
|
||||
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return <div data-slot="dialog-header" className={cn("flex flex-col gap-2 text-center sm:text-left", className)} {...props} />;
|
||||
}
|
||||
|
||||
function DialogFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return <div data-slot="dialog-footer" className={cn("flex gap-2 sm:flex-row sm:justify-end", className)} {...props} />;
|
||||
}
|
||||
|
||||
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
|
||||
return <DialogPrimitive.Title data-slot="dialog-title" className={cn("text-lg leading-none font-semibold", className)} {...props} />;
|
||||
}
|
||||
|
||||
function DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {
|
||||
return <DialogPrimitive.Description data-slot="dialog-description" className={cn("text-text-neutral-tertiary text-sm", className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger };
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
import { ReactNode } from "react";
|
||||
|
||||
interface Props {
|
||||
children: ReactNode;
|
||||
}
|
||||
export default function Divider({ children }: Props) {
|
||||
return (
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center" aria-hidden="true">
|
||||
<div className="border-border-default w-full border-t" />
|
||||
</div>
|
||||
<div className="relative flex justify-center">
|
||||
<span className="text-text-neutral-tertiary bg-surface-neutral-primary px-2 text-sm">{children}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
import { useTranslation } from "react-i18next";
|
||||
import BreadcrumbSimple from "~/components/ui/breadcrumbs/BreadcrumbSimple";
|
||||
|
||||
interface Props {
|
||||
items: { title: string; routePath: string }[];
|
||||
}
|
||||
|
||||
export default function DocBreadcrumb({ items }: Props) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return <BreadcrumbSimple menu={[{ title: t("docs.title"), routePath: "/docs" }, ...items]} />;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
import CustomCarousel from "../images/CustomCarousel";
|
||||
|
||||
interface Props {
|
||||
items: {
|
||||
type: string;
|
||||
title: string;
|
||||
src: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
export default function DocCarousel({ items }: Props) {
|
||||
return <CustomCarousel items={items} />;
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
import { t as i18nT } from "i18next";
|
||||
import CheckIcon from "../icons/CheckIcon";
|
||||
import XIcon from "../icons/XIcon";
|
||||
|
||||
interface Props {
|
||||
items: { route: string; c: boolean; r: boolean; u: boolean; d: boolean }[];
|
||||
}
|
||||
|
||||
export default function DocLifeCycle({ items }: Props) {
|
||||
return (
|
||||
<div className="not-prose flex flex-col">
|
||||
<div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
|
||||
<div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
|
||||
<div className="overflow-hidden shadow-xs ring-1 ring-black ring-opacity-5 md:rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-300">
|
||||
<thead className="bg-surface-neutral-secondary">
|
||||
<tr>
|
||||
<th scope="col" className="text-text-neutral-primary w-full px-2 py-1.5 text-left text-sm font-semibold sm:pl-6">
|
||||
{i18nT("components.docs.lifecycle.route")}
|
||||
</th>
|
||||
<th scope="col" className="text-text-neutral-primary px-2 py-1.5 text-center text-sm font-semibold">
|
||||
{i18nT("components.docs.lifecycle.create")}
|
||||
</th>
|
||||
<th scope="col" className="text-text-neutral-primary px-2 py-1.5 text-center text-sm font-semibold">
|
||||
{i18nT("components.docs.lifecycle.read")}
|
||||
</th>
|
||||
<th scope="col" className="text-text-neutral-primary px-2 py-1.5 text-center text-sm font-semibold">
|
||||
{i18nT("components.docs.lifecycle.update")}
|
||||
</th>
|
||||
<th scope="col" className="text-text-neutral-primary px-2 py-1.5 text-center text-sm font-semibold">
|
||||
{i18nT("components.docs.lifecycle.delete")}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-border bg-surface-neutral-primary divide-y">
|
||||
{items.map((item) => (
|
||||
<tr key={item.route}>
|
||||
<td className="text-text-neutral-primary whitespace-nowrap px-2 py-1.5 text-sm font-medium sm:pl-6">{item.route}</td>
|
||||
<td className="text-text-neutral-tertiary whitespace-nowrap px-2 py-1.5 text-center text-sm">
|
||||
{item.c ? <CheckIcon className="text-theme-500 mx-auto h-4 w-4" /> : <XIcon className="mx-auto h-4 w-4 text-gray-300" />}
|
||||
</td>
|
||||
<td className="text-text-neutral-tertiary whitespace-nowrap px-2 py-1.5 text-center text-sm">
|
||||
{item.r ? <CheckIcon className="text-theme-500 mx-auto h-4 w-4" /> : <XIcon className="mx-auto h-4 w-4 text-gray-300" />}
|
||||
</td>
|
||||
<td className="text-text-neutral-tertiary whitespace-nowrap px-2 py-1.5 text-center text-sm">
|
||||
{item.u ? <CheckIcon className="text-theme-500 mx-auto h-4 w-4" /> : <XIcon className="mx-auto h-4 w-4 text-gray-300" />}
|
||||
</td>
|
||||
<td className="text-text-neutral-tertiary whitespace-nowrap px-2 py-1.5 text-center text-sm">
|
||||
{item.d ? <CheckIcon className="text-theme-500 mx-auto h-4 w-4" /> : <XIcon className="mx-auto h-4 w-4 text-gray-300" />}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { t as i18nT } from "i18next";
|
||||
import { Link } from "react-router";
|
||||
|
||||
interface Props {
|
||||
items: { name: string; title: string; type?: ModelPropertyType; customType?: { name: string; route?: string }; description?: string; required: boolean }[];
|
||||
}
|
||||
export enum ModelPropertyType {
|
||||
String,
|
||||
DateTime,
|
||||
Int,
|
||||
Decimal,
|
||||
Boolean,
|
||||
UUID,
|
||||
Cuid,
|
||||
}
|
||||
|
||||
export default function DocPropertiesTable({ items }: Props) {
|
||||
return (
|
||||
<div className="not-prose flex flex-col">
|
||||
<div className="-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
|
||||
<div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
|
||||
<div className="overflow-hidden shadow-xs ring-1 ring-black ring-opacity-5 md:rounded-lg">
|
||||
<table className="min-w-full divide-y divide-gray-300">
|
||||
<thead className="bg-surface-neutral-secondary">
|
||||
<tr>
|
||||
<th scope="col" className="text-text-neutral-primary px-2 py-1.5 text-left text-sm font-semibold sm:pl-6">
|
||||
{i18nT("components.docs.properties.name")}
|
||||
</th>
|
||||
<th scope="col" className="text-text-neutral-primary px-2 py-1.5 text-left text-sm font-semibold">
|
||||
{i18nT("components.docs.properties.title")}
|
||||
</th>
|
||||
<th scope="col" className="text-text-neutral-primary px-2 py-1.5 text-left text-sm font-semibold">
|
||||
{i18nT("components.docs.properties.type")}
|
||||
</th>
|
||||
<th scope="col" className="text-text-neutral-primary w-full px-2 py-1.5 text-left text-sm font-semibold">
|
||||
{i18nT("components.docs.properties.description")}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-border bg-surface-neutral-primary divide-y">
|
||||
{items.map((item) => (
|
||||
<tr key={item.name}>
|
||||
<td className="text-text-neutral-primary whitespace-nowrap px-2 py-1.5 text-sm font-medium sm:pl-6">
|
||||
{item.name} {item.required && <span className="ml-1 text-red-500">*</span>}
|
||||
</td>
|
||||
<td className="text-text-neutral-tertiary whitespace-nowrap px-2 py-1.5 text-sm">{item.title}</td>
|
||||
<td className="text-text-neutral-tertiary whitespace-nowrap px-2 py-1.5 text-sm">
|
||||
{item.customType && (
|
||||
<span className="font-bold">
|
||||
{item.customType.route ? (
|
||||
<Link className="text-theme-600 underline" to={item.customType.route}>
|
||||
{item.customType.name}
|
||||
</Link>
|
||||
) : (
|
||||
item.customType.name
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
{item.type !== undefined && ModelPropertyType[item.type]}
|
||||
</td>
|
||||
<td className="text-text-neutral-tertiary whitespace-nowrap px-2 py-1.5 text-sm">{item.description}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
interface Props {
|
||||
alt: string;
|
||||
src: string;
|
||||
}
|
||||
|
||||
export default function DocTutorialImage({ alt, src }: Props) {
|
||||
return (
|
||||
<div className="border-border-default border-2 border-dashed">
|
||||
<img className="bg-surface-neutral-secondary/90 mx-auto rounded-lg object-cover shadow-2xl" alt={alt} src={src} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
interface Props {
|
||||
title: string;
|
||||
src: string;
|
||||
}
|
||||
|
||||
export default function DocVideo({ title, src }: Props) {
|
||||
return (
|
||||
<div className="border-border-default h-full border-2 border-dashed">
|
||||
<iframe
|
||||
src={src}
|
||||
title={title ?? ""}
|
||||
frameBorder="0"
|
||||
loading="lazy"
|
||||
className="min-h-full w-full object-cover"
|
||||
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
||||
></iframe>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { Fragment, useState } from "react";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { Sheet, SheetContent, SheetDescription, SheetHeader, SheetTitle, SheetTrigger } from "../sheet";
|
||||
import { Button } from "../button";
|
||||
import Logo from "~/components/brand/Logo";
|
||||
import { ScrollArea } from "../scroll-area";
|
||||
import { Link } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { SideBarItem } from "~/application/sidebar/SidebarItem";
|
||||
import { getUiIdAttributes, UI_ACTION_IDS } from "~/application/ui/uiRegistry";
|
||||
import { MenuIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
export function MobileNav({ items }: { items: SideBarItem[] }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
|
||||
return (
|
||||
<Sheet open={open} onOpenChange={setOpen}>
|
||||
<SheetTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
data-ui-id={`${UI_ACTION_IDS.sidebarTrigger}.docsMobile`}
|
||||
className="px-0 text-base hover:bg-transparent focus-visible:bg-transparent focus-visible:ring-0 focus-visible:ring-offset-0 md:hidden"
|
||||
>
|
||||
<MenuIcon className="text-text-neutral-tertiary h-6 w-6" />
|
||||
<span className="sr-only">{i18nT("components.docsMobileNav.toggleMenu")}</span>
|
||||
</Button>
|
||||
</SheetTrigger>
|
||||
<SheetContent side="left" className="pr-0">
|
||||
<SheetHeader className="sr-only">
|
||||
<SheetTitle>{i18nT("docs.mobileNav.title")}</SheetTitle>
|
||||
<SheetDescription>{i18nT("docs.mobileNav.description")}</SheetDescription>
|
||||
</SheetHeader>
|
||||
<Logo className="mr-2" />
|
||||
<ScrollArea className="my-4 h-[calc(100vh-100px)] pb-10 pl-3">
|
||||
<div className="flex flex-col space-y-2">
|
||||
{items.map((item, index) => (
|
||||
<div key={index} className="flex flex-col space-y-3 pt-4" {...(!item.path ? getUiIdAttributes(item) : {})}>
|
||||
{item.items && item.items.length > 0 ? (
|
||||
<button type="button" aria-expanded="true" className="text-left font-medium" {...getUiIdAttributes(item)}>
|
||||
{item.title}
|
||||
</button>
|
||||
) : item.path ? (
|
||||
<Link to={item.path} {...getUiIdAttributes(item)}>
|
||||
<h4 className="font-medium">{item.title}</h4>
|
||||
</Link>
|
||||
) : (
|
||||
<h4 className="font-medium">{item.title}</h4>
|
||||
)}
|
||||
{item.items?.map((item) => (
|
||||
<Fragment key={item.path}>
|
||||
{!item.disabled &&
|
||||
(item.path ? (
|
||||
<MobileLink href={item.path} onOpenChange={setOpen} className="text-text-neutral-tertiary" uiItem={item}>
|
||||
{item.title}
|
||||
{item.side && (
|
||||
<span className="ml-2 rounded-md bg-[#adfa1d] px-1.5 py-0.5 text-xs leading-none text-[#000000] no-underline group-hover:no-underline">
|
||||
{item.side}
|
||||
</span>
|
||||
)}
|
||||
</MobileLink>
|
||||
) : (
|
||||
item.title
|
||||
))}
|
||||
</Fragment>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</SheetContent>
|
||||
</Sheet>
|
||||
);
|
||||
}
|
||||
|
||||
function MobileLink({
|
||||
href,
|
||||
onOpenChange,
|
||||
className,
|
||||
children,
|
||||
uiItem,
|
||||
...props
|
||||
}: {
|
||||
href: string;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
className: string;
|
||||
children: React.ReactNode;
|
||||
uiItem?: SideBarItem;
|
||||
}) {
|
||||
return (
|
||||
<Link
|
||||
to={href}
|
||||
onClick={() => {
|
||||
onOpenChange?.(false);
|
||||
}}
|
||||
className={clsx(className)}
|
||||
{...(uiItem ? getUiIdAttributes(uiItem) : {})}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { resolveRepoPath } from "~/utils/testing/repoPaths";
|
||||
import { MobileNav } from "./DocsMobileNav";
|
||||
import { DocsSidebarNav } from "./DocsSidebarNav";
|
||||
|
||||
vi.mock("~/utils/data/useRootData", () => ({
|
||||
useRootData: () => ({
|
||||
appConfiguration: {
|
||||
branding: {},
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
describe("docs navigation", () => {
|
||||
it("renders parents with children as expand-only controls", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<DocsSidebarNav
|
||||
items={[
|
||||
{
|
||||
title: "Settings",
|
||||
path: "/settings",
|
||||
items: [{ title: "Overview", path: "/settings" }],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByRole("button", { name: "Settings" })).toHaveAttribute("aria-expanded", "true");
|
||||
expect(screen.getByRole("link", { name: "Overview" })).toHaveAttribute("href", "/settings");
|
||||
expect(screen.queryByRole("link", { name: "Settings" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("does not render disabled docs items as links", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<DocsSidebarNav
|
||||
items={[
|
||||
{
|
||||
title: "Settings",
|
||||
items: [{ title: "Disabled Plugin", path: "/settings/plugin", disabled: true }],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.queryByRole("link", { name: "Disabled Plugin" })).not.toBeInTheDocument();
|
||||
expect(screen.getByText("Disabled Plugin")).toHaveAttribute("aria-disabled", "true");
|
||||
});
|
||||
|
||||
it("renders an accessible mobile docs sheet title and description", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<MobileNav items={[]} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Toggle menu" }));
|
||||
|
||||
const dialog = screen.getByRole("dialog", { name: "Docs navigation" });
|
||||
const heading = screen.getByRole("heading", { name: "Docs navigation" });
|
||||
const description = screen.getByText("Displays the mobile docs navigation.");
|
||||
|
||||
expect(dialog).toHaveAccessibleDescription("Displays the mobile docs navigation.");
|
||||
expect(heading.closest('[data-slot="sheet-header"]')).toHaveClass("sr-only");
|
||||
expect(description.closest('[data-slot="sheet-header"]')).toHaveClass("sr-only");
|
||||
});
|
||||
|
||||
it("keeps mobile docs parents as non-link controls", () => {
|
||||
render(
|
||||
<MemoryRouter>
|
||||
<MobileNav
|
||||
items={[
|
||||
{
|
||||
title: "Settings",
|
||||
path: "/settings",
|
||||
items: [{ title: "Overview", path: "/settings" }],
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: "Toggle menu" }));
|
||||
|
||||
expect(screen.getByRole("button", { name: "Settings" })).toHaveAttribute("aria-expanded", "true");
|
||||
expect(screen.getByRole("link", { name: "Overview" })).toHaveAttribute("href", "/settings");
|
||||
expect(screen.queryByRole("link", { name: "Settings" })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("adds an explicit overview child for knowledge-base category paths", () => {
|
||||
const source = fs.readFileSync(resolveRepoPath(path.join("apps/web/app/modules/knowledgeBase/components/layouts/KbDocsLayout.tsx")), "utf8");
|
||||
|
||||
expect(source).toContain('items: [{ title: t("shared.overview"), path: category.href }]');
|
||||
});
|
||||
});
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
import { Link, useLocation } from "react-router";
|
||||
import clsx from "clsx";
|
||||
import { SideBarItem } from "~/application/sidebar/SidebarItem";
|
||||
import { getUiIdAttributes } from "~/application/ui/uiRegistry";
|
||||
|
||||
export function DocsSidebarNav({ items }: { items: SideBarItem[] }) {
|
||||
return (
|
||||
<div>
|
||||
{items.length > 0 ? (
|
||||
<div className="w-full">
|
||||
{items.map((item, index) => (
|
||||
<div key={index} className={clsx(item.items && item.items.length > 0 && "pb-4")} {...(!item.path ? getUiIdAttributes(item) : {})}>
|
||||
{item.items && item.items.length > 0 ? (
|
||||
<button type="button" aria-expanded="true" className="mb-1 rounded-md px-2 py-1 text-left font-semibold" {...getUiIdAttributes(item)}>
|
||||
{item.title}
|
||||
</button>
|
||||
) : item.path ? (
|
||||
<Link to={item.path} className="hover:underline" {...getUiIdAttributes(item)}>
|
||||
<h4 className="mb-1 rounded-md px-2 py-1 font-semibold">{item.title}</h4>
|
||||
</Link>
|
||||
) : (
|
||||
<h4 className="mb-1 rounded-md px-2 py-1 font-semibold">{item.title}</h4>
|
||||
)}
|
||||
{item.items && item.items.length > 0 && <DocsSidebarNavItems items={item.items} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function DocsSidebarNavItems({ items }: { items: SideBarItem[] }) {
|
||||
const location = useLocation();
|
||||
const pathname = location.pathname;
|
||||
return items?.length ? (
|
||||
<div className="grid grid-flow-row auto-rows-max">
|
||||
{items.map((item, index) =>
|
||||
item.path && !item.disabled ? (
|
||||
<Link
|
||||
key={index}
|
||||
to={item.path}
|
||||
className={clsx(
|
||||
"group flex w-full items-center rounded-md border border-transparent px-2 py-1 text-sm hover:underline",
|
||||
item.disabled && "cursor-not-allowed opacity-60",
|
||||
pathname === item.path ? "text-text-neutral-primary font-medium" : "text-text-neutral-tertiary"
|
||||
)}
|
||||
target={item.target}
|
||||
rel={item.target ? "noreferrer" : ""}
|
||||
{...getUiIdAttributes(item)}
|
||||
// preventScrollReset
|
||||
>
|
||||
{item.title}
|
||||
{item.side && (
|
||||
<span className="ml-2 rounded-md bg-[#adfa1d] px-1.5 py-0.5 text-xs leading-none text-[#000000] no-underline group-hover:no-underline">
|
||||
{item.side}
|
||||
</span>
|
||||
)}
|
||||
</Link>
|
||||
) : (
|
||||
<span
|
||||
key={index}
|
||||
aria-disabled={item.disabled ? "true" : undefined}
|
||||
className={clsx(
|
||||
"text-text-neutral-tertiary flex w-full items-center rounded-md p-2",
|
||||
!item.disabled && "hover:underline",
|
||||
item.disabled && "cursor-not-allowed opacity-60"
|
||||
)}
|
||||
{...getUiIdAttributes(item)}
|
||||
>
|
||||
{item.title}
|
||||
{item.side && (
|
||||
<span className="bg-surface-neutral-secondary text-text-neutral-tertiary ml-2 rounded-md px-1.5 py-0.5 text-xs leading-none no-underline group-hover:no-underline">
|
||||
{item.side}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
) : null;
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
import { ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { ScrollArea } from "~/components/ui/scroll-area";
|
||||
import { DashboardTableOfContents } from "./toc";
|
||||
import clsx from "clsx";
|
||||
|
||||
export type PreviewComponentProps = {
|
||||
title: string;
|
||||
description: string;
|
||||
variants:
|
||||
| {
|
||||
id: string;
|
||||
title: string;
|
||||
component: ReactNode;
|
||||
code?: string;
|
||||
description?: string;
|
||||
}[]
|
||||
| {
|
||||
id: string;
|
||||
title: string;
|
||||
iframe: string;
|
||||
code?: string;
|
||||
description?: string;
|
||||
}[];
|
||||
className?: string;
|
||||
withToc?: boolean;
|
||||
overflow?: "hidden" | "visible";
|
||||
};
|
||||
export default function PreviewComponent({ title, description, variants, className, withToc = true, overflow = "hidden" }: PreviewComponentProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<main className={clsx("relative pb-6 lg:gap-10 lg:pb-8", withToc && "xl:grid xl:grid-cols-[1fr_150px]")}>
|
||||
<div className="space-y-8 overflow-hidden">
|
||||
<div>
|
||||
<h1 className="scroll-m-20 text-4xl font-bold tracking-tight">{title}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-lg">{description}</p>
|
||||
</div>
|
||||
{variants.map((variant, index) => (
|
||||
<div key={index} className="space-y-2">
|
||||
<div className="space-y-1">
|
||||
<h3 id={variant.id} className="text-xl font-bold tracking-tight">
|
||||
{variant.title}
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">{variant.description}</p>
|
||||
</div>
|
||||
<div
|
||||
className={clsx(
|
||||
"border-muted-foreground flex justify-center rounded-lg border-2 border-dashed",
|
||||
className,
|
||||
overflow === "hidden" ? "overflow-hidden" : "overflow-visible",
|
||||
"component" in variant && "p-6"
|
||||
)}
|
||||
>
|
||||
{"iframe" in variant ? <iframe src={variant.iframe} title={title} className="h-96 w-full border-0" /> : variant.component}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{withToc && (
|
||||
<div className="hidden text-sm xl:block">
|
||||
<div className="sticky top-16 pt-4">
|
||||
<ScrollArea className="pb-10">
|
||||
<div className="sticky top-16 -mt-10 h-[calc(100vh-3.5rem)] py-12">
|
||||
<DashboardTableOfContents
|
||||
// title={`${title} - Variants`}
|
||||
title={t("docs.onThisPage")}
|
||||
toc={{
|
||||
items: variants
|
||||
.map((f) => f)
|
||||
.map((item) => ({
|
||||
title: item.title,
|
||||
url: `#${item.id}`,
|
||||
})),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import clsx from "clsx";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import ButtonEvent from "../buttons/ButtonEvent";
|
||||
|
||||
interface Item {
|
||||
title: string;
|
||||
url: string;
|
||||
items?: Item[];
|
||||
}
|
||||
|
||||
interface Items {
|
||||
items?: Item[];
|
||||
}
|
||||
|
||||
interface TocProps {
|
||||
title: string;
|
||||
toc: Items;
|
||||
}
|
||||
|
||||
export function DashboardTableOfContents({ title, toc }: TocProps) {
|
||||
const itemIds = useMemo(
|
||||
() =>
|
||||
toc.items
|
||||
? toc.items
|
||||
.flatMap((item) => [item.url, item?.items?.map((item) => item.url)])
|
||||
.flat()
|
||||
.filter(Boolean)
|
||||
.map((id) => id?.split("#")[1])
|
||||
: [],
|
||||
[toc]
|
||||
);
|
||||
const activeHeading = useActiveItem(itemIds.filter(Boolean) as string[]);
|
||||
const mounted = useMounted();
|
||||
|
||||
if (!toc?.items || !mounted) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<p className="font-medium">{title}</p>
|
||||
<Tree tree={toc} activeItem={activeHeading} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useActiveItem(itemIds: string[]) {
|
||||
const [activeId, setActiveId] = useState<undefined | string>(undefined);
|
||||
|
||||
useEffect(() => {
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
entries.forEach((entry) => {
|
||||
if (entry.isIntersecting) {
|
||||
setActiveId(entry.target.id ?? undefined);
|
||||
}
|
||||
});
|
||||
},
|
||||
{ rootMargin: `0% 0% -80% 0%` }
|
||||
);
|
||||
|
||||
itemIds?.forEach((id) => {
|
||||
const element = document.getElementById(id);
|
||||
if (element) {
|
||||
observer.observe(element);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
itemIds?.forEach((id) => {
|
||||
const element = document.getElementById(id);
|
||||
if (element) {
|
||||
observer.unobserve(element);
|
||||
}
|
||||
});
|
||||
};
|
||||
}, [itemIds]);
|
||||
|
||||
return activeId;
|
||||
}
|
||||
|
||||
interface TreeProps {
|
||||
tree: Items;
|
||||
level?: number;
|
||||
activeItem?: string;
|
||||
}
|
||||
|
||||
function Tree({ tree, level = 1, activeItem }: TreeProps) {
|
||||
return tree?.items?.length && level < 3 ? (
|
||||
<ul className={clsx("m-0 list-none", { "pl-4": level !== 1 })}>
|
||||
{tree.items.map((item, index) => {
|
||||
return (
|
||||
<li key={index} className={clsx("mt-0 pt-2")}>
|
||||
<ButtonEvent
|
||||
event={{ action: "click", category: "toc", label: item.title, value: item.url }}
|
||||
to={item.url}
|
||||
className={clsx(
|
||||
"hover:text-text-neutral-primary inline-block no-underline transition-colors",
|
||||
item.url === `#${activeItem}` ? "text-text-neutral-primary font-medium" : "text-text-neutral-tertiary"
|
||||
)}
|
||||
>
|
||||
{item.title}
|
||||
</ButtonEvent>
|
||||
{item.items?.length ? <Tree tree={item} level={level + 1} activeItem={activeItem} /> : null}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
) : null;
|
||||
}
|
||||
|
||||
function useMounted() {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setMounted(true);
|
||||
}, []);
|
||||
|
||||
return mounted;
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
import * as React from "react"
|
||||
import { Drawer as DrawerPrimitive } from "vaul"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
function Drawer({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Root>) {
|
||||
return <DrawerPrimitive.Root data-slot="drawer" {...props} />
|
||||
}
|
||||
|
||||
function DrawerTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Trigger>) {
|
||||
return <DrawerPrimitive.Trigger data-slot="drawer-trigger" {...props} />
|
||||
}
|
||||
|
||||
function DrawerPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Portal>) {
|
||||
return <DrawerPrimitive.Portal data-slot="drawer-portal" {...props} />
|
||||
}
|
||||
|
||||
function DrawerClose({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Close>) {
|
||||
return <DrawerPrimitive.Close data-slot="drawer-close" {...props} />
|
||||
}
|
||||
|
||||
function DrawerOverlay({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Overlay>) {
|
||||
return (
|
||||
<DrawerPrimitive.Overlay
|
||||
data-slot="drawer-overlay"
|
||||
className={cn(
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerContent({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Content>) {
|
||||
return (
|
||||
<DrawerPortal data-slot="drawer-portal">
|
||||
<DrawerOverlay />
|
||||
<DrawerPrimitive.Content
|
||||
data-slot="drawer-content"
|
||||
className={cn(
|
||||
// Subframe Drawer panel layout: gap-2 between panel sections, border-solid, min-w-[320px] on side panels.
|
||||
// Radix/vaul-only pieces kept: fixed positioning, h-auto, per-direction insets/rounding/borders/sizing.
|
||||
"group/drawer-content bg-surface-neutral-primary fixed z-50 flex h-auto flex-col gap-2 border-solid",
|
||||
"data-[vaul-drawer-direction=top]:inset-x-0 data-[vaul-drawer-direction=top]:top-0 data-[vaul-drawer-direction=top]:mb-24 data-[vaul-drawer-direction=top]:max-h-[80vh] data-[vaul-drawer-direction=top]:rounded-b-lg data-[vaul-drawer-direction=top]:border-b",
|
||||
"data-[vaul-drawer-direction=bottom]:inset-x-0 data-[vaul-drawer-direction=bottom]:bottom-0 data-[vaul-drawer-direction=bottom]:mt-24 data-[vaul-drawer-direction=bottom]:max-h-[80vh] data-[vaul-drawer-direction=bottom]:rounded-t-lg data-[vaul-drawer-direction=bottom]:border-t",
|
||||
"data-[vaul-drawer-direction=right]:inset-y-0 data-[vaul-drawer-direction=right]:right-0 data-[vaul-drawer-direction=right]:w-3/4 data-[vaul-drawer-direction=right]:min-w-[320px] data-[vaul-drawer-direction=right]:border-l data-[vaul-drawer-direction=right]:sm:max-w-sm",
|
||||
"data-[vaul-drawer-direction=left]:inset-y-0 data-[vaul-drawer-direction=left]:left-0 data-[vaul-drawer-direction=left]:w-3/4 data-[vaul-drawer-direction=left]:min-w-[320px] data-[vaul-drawer-direction=left]:border-r data-[vaul-drawer-direction=left]:sm:max-w-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<div className="bg-surface-neutral-secondary mx-auto mt-4 hidden h-2 w-[100px] shrink-0 rounded-full group-data-[vaul-drawer-direction=bottom]/drawer-content:block" />
|
||||
{children}
|
||||
</DrawerPrimitive.Content>
|
||||
</DrawerPortal>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-header"
|
||||
className={cn("flex flex-col gap-1.5 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="drawer-footer"
|
||||
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerTitle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Title>) {
|
||||
return (
|
||||
<DrawerPrimitive.Title
|
||||
data-slot="drawer-title"
|
||||
className={cn("text-text-neutral-primary font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DrawerDescription({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DrawerPrimitive.Description>) {
|
||||
return (
|
||||
<DrawerPrimitive.Description
|
||||
data-slot="drawer-description"
|
||||
className={cn("text-text-neutral-tertiary text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Drawer,
|
||||
DrawerPortal,
|
||||
DrawerOverlay,
|
||||
DrawerTrigger,
|
||||
DrawerClose,
|
||||
DrawerContent,
|
||||
DrawerHeader,
|
||||
DrawerFooter,
|
||||
DrawerTitle,
|
||||
DrawerDescription,
|
||||
}
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
// Subframe DropdownMenuRoot surface layout: min-w-[192px] rounded-md px-1 py-1 (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-dropdown-menu-content-available-height) min-w-[192px] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border border-border-default p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
// Subframe DropdownItem layout: gap-2 rounded-md px-2 py-2
|
||||
"focus:bg-surface-neutral-secondary focus:text-text-neutral-primary data-[variant=destructive]:text-text-feedback-negative data-[variant=destructive]:focus:bg-surface-feedback-solid-negative-default/10 dark:data-[variant=destructive]:focus:bg-surface-feedback-solid-negative-default/20 data-[variant=destructive]:focus:text-text-feedback-negative data-[variant=destructive]:*:[svg]:!text-text-feedback-negative [&_svg:not([class*='text-'])]:text-text-neutral-tertiary relative flex cursor-default items-center gap-2 rounded-md px-2 py-2 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
// Subframe DropdownItem layout: gap-2 rounded-md py-2 (pl-8 indicator slot kept from Radix; no Subframe pendant)
|
||||
"focus:bg-surface-neutral-secondary focus:text-text-neutral-primary relative flex cursor-default items-center gap-2 rounded-md py-2 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
// Subframe DropdownItem layout: gap-2 rounded-md py-2 (pl-8 indicator slot kept from Radix; no Subframe pendant)
|
||||
"focus:bg-surface-neutral-secondary focus:text-text-neutral-primary relative flex cursor-default items-center gap-2 rounded-md py-2 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border-default -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-text-neutral-tertiary ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
// Subframe DropdownItem layout: rounded-md px-2 py-2 (sub-menu has no Subframe flyout pendant)
|
||||
"focus:bg-surface-neutral-secondary focus:text-text-neutral-primary data-[state=open]:bg-surface-neutral-secondary data-[state=open]:text-text-neutral-primary flex cursor-default items-center rounded-md px-2 py-2 text-sm outline-hidden select-none data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
className={cn(
|
||||
// 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-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border border-border-default p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { Fragment, MouseEventHandler, ReactNode } from "react";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import { ChevronDownIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
right?: boolean;
|
||||
button?: ReactNode;
|
||||
options?: ReactNode;
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
btnClassName?: string;
|
||||
onClick?: MouseEventHandler<HTMLButtonElement>;
|
||||
disabled?: boolean;
|
||||
isLoading?: boolean;
|
||||
}
|
||||
|
||||
export default function Dropdown({ button, options, right, onClick, className, btnClassName, disabled, isLoading }: Props) {
|
||||
return (
|
||||
<Menu as="div" className={clsx(className, "relative inline-block text-left")}>
|
||||
<div>
|
||||
<Menu.Button
|
||||
disabled={disabled || isLoading}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (onClick) {
|
||||
onClick(e);
|
||||
}
|
||||
}}
|
||||
className={clsx(
|
||||
isLoading && "base-spinner cursor-not-allowed",
|
||||
btnClassName ?? "inline-flex w-full items-center justify-center rounded-md px-3 py-2 text-sm font-medium shadow-2xs",
|
||||
disabled || isLoading
|
||||
? "bg-surface-neutral-secondary/90 cursor-not-allowed"
|
||||
: clsx("bg-surface-neutral-primary", "shadow-focus focus:outline-hidden focus:ring-offset-2")
|
||||
)}
|
||||
>
|
||||
{button}
|
||||
{!btnClassName && <ChevronDownIcon className="text-text-neutral-tertiary -mr-1 ml-2 h-4 w-4" />}
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
className={clsx(
|
||||
"bg-surface-neutral-modal border-border-default absolute z-40 mt-2 w-48 overflow-hidden rounded-md border shadow-lg ring-1 ring-border-default focus:outline-hidden",
|
||||
right ? "left-0 origin-top-left" : "right-0 origin-top-right"
|
||||
)}
|
||||
>
|
||||
<div className="py-1">{options}</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
// @vitest-environment node
|
||||
import { readFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
const source = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "DropdownDots.tsx"), "utf8");
|
||||
|
||||
describe("DropdownDots disabled links", () => {
|
||||
test("disabled href items do not render navigable links", () => {
|
||||
expect(source).toContain("item.href && !item.disabled");
|
||||
expect(source).not.toContain('to={item.disabled ? "" : item.href}');
|
||||
expect(source).toContain("aria-disabled={item.disabled || undefined}");
|
||||
});
|
||||
});
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
import { MoreVerticalIcon } from "~/components/ui/icons/vendor";
|
||||
import { Button } from "../button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "../dropdown-menu";
|
||||
import { Link } from "react-router";
|
||||
import { Fragment } from "react/jsx-runtime";
|
||||
import { cn } from "~/lib/utils";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
interface Props {
|
||||
title?: string;
|
||||
items: {
|
||||
name: "separator" | React.ReactNode | (string & {});
|
||||
href?: string;
|
||||
target?: string;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
hidden?: boolean;
|
||||
}[];
|
||||
size?: "xs" | "sm" | "lg";
|
||||
children?: React.ReactNode;
|
||||
className?: string;
|
||||
classMenuContent?: string;
|
||||
variant?: "default" | "ghost" | "outline";
|
||||
ariaLabel?: string;
|
||||
}
|
||||
export default function DropdownDots({ title, items, size = "sm", children, className, classMenuContent, variant = "ghost", ariaLabel }: Props) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
asChild
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
>
|
||||
<Button type="button" variant={variant} size={size} className={className} aria-label={ariaLabel ?? (children ? undefined : t("shared.openMenu"))}>
|
||||
{children ? (
|
||||
children
|
||||
) : (
|
||||
<MoreVerticalIcon
|
||||
className="opacity-90"
|
||||
size={cn(
|
||||
size === "xs" && 12,
|
||||
size === "sm" && 16,
|
||||
size === "lg" && 20
|
||||
//
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent className={cn("max-w-44", classMenuContent)}>
|
||||
{title && (
|
||||
<Fragment>
|
||||
<DropdownMenuLabel>{title}</DropdownMenuLabel>
|
||||
<DropdownMenuSeparator />
|
||||
</Fragment>
|
||||
)}
|
||||
<DropdownMenuGroup>
|
||||
{items
|
||||
.filter((item) => !item.hidden)
|
||||
.map((item, idx) => (
|
||||
<Fragment key={idx}>
|
||||
{item.name === "separator" ? (
|
||||
<DropdownMenuSeparator />
|
||||
) : (
|
||||
<DropdownMenuItem key={idx} asChild>
|
||||
{item.href && !item.disabled ? (
|
||||
<Link
|
||||
to={item.href}
|
||||
className={item.className}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
}}
|
||||
target={item.target}
|
||||
>
|
||||
{item.name}
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className={cn("w-full", item.disabled && "cursor-not-allowed opacity-50", item.className)}
|
||||
disabled={item.disabled}
|
||||
aria-disabled={item.disabled || undefined}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (item.onClick) {
|
||||
item.onClick();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{item.name}
|
||||
</button>
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
</Fragment>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
{/* <DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="text-red-600" onClick={() => deleteItem(item.id)}>
|
||||
Delete
|
||||
</DropdownMenuItem> */}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
import { Fragment, ReactNode } from "react";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import OptionsIcon from "../icons/OptionsIcon";
|
||||
|
||||
interface Props {
|
||||
right?: boolean;
|
||||
options?: ReactNode;
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
button?: ReactNode;
|
||||
buttonDataUiId?: string;
|
||||
disabled?: boolean;
|
||||
width?: "w-48" | "w-56" | "w-64" | "w-72" | "w-80" | "w-96";
|
||||
}
|
||||
|
||||
export default function DropdownOptions({ options, right, className, button, buttonDataUiId, disabled, width = "w-48" }: Props) {
|
||||
return (
|
||||
<Menu as="div" className={clsx(className, "relative inline-block text-left")}>
|
||||
<div>
|
||||
<Menu.Button data-ui-id={buttonDataUiId} disabled={disabled}>
|
||||
{button ?? <OptionsIcon />}
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
className={clsx(
|
||||
"bg-surface-neutral-modal absolute z-40 mt-2 rounded-md shadow-lg ring-1 ring-border-default focus:outline-hidden",
|
||||
right ? "left-0 origin-top-left" : "right-0 origin-top-right",
|
||||
width
|
||||
)}
|
||||
>
|
||||
<div className="py-1">{options}</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
import { Fragment, ReactNode } from "react";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import OptionsIcon from "../icons/OptionsIcon";
|
||||
import { Link } from "react-router";
|
||||
|
||||
interface Props {
|
||||
items?: (
|
||||
| {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
}
|
||||
| {
|
||||
label: string;
|
||||
href: string;
|
||||
target?: "_blank" | string;
|
||||
}
|
||||
)[];
|
||||
button?: ReactNode;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
width?: "w-48" | "w-56" | "w-64" | "w-72" | "w-80" | "w-96";
|
||||
right?: boolean;
|
||||
}
|
||||
|
||||
export default function DropdownSimple({ items, button, disabled, className, right, width = "w-48" }: Props) {
|
||||
return (
|
||||
<Menu as="div" className={clsx(className, "relative inline-block text-left")}>
|
||||
<div>
|
||||
<Menu.Button disabled={disabled}>{button ?? <OptionsIcon />}</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
className={clsx(
|
||||
"bg-surface-neutral-modal absolute z-40 mt-2 rounded-md shadow-lg ring-1 ring-border-default focus:outline-hidden",
|
||||
right ? "left-0 origin-top-left" : "right-0 origin-top-right",
|
||||
width
|
||||
)}
|
||||
>
|
||||
<div className="py-1">
|
||||
{items?.map((item, i) => {
|
||||
return (
|
||||
<Menu.Item key={i}>
|
||||
{({ active, close }) => {
|
||||
return (
|
||||
<Fragment>
|
||||
{"href" in item ? (
|
||||
<Link
|
||||
to={item.href}
|
||||
target={item.target}
|
||||
className={clsx("w-full text-left", active ? "text-text-neutral-primary bg-surface-neutral-secondary" : "text-text-neutral-secondary", "block px-4 py-2 text-sm")}
|
||||
onClick={() => close()}
|
||||
>
|
||||
{item.label}
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
item.onClick();
|
||||
close();
|
||||
}}
|
||||
className={clsx("w-full text-left", active ? "text-text-neutral-primary bg-surface-neutral-secondary" : "text-text-neutral-secondary", "block px-4 py-2 text-sm")}
|
||||
>
|
||||
{item.label}
|
||||
</button>
|
||||
)}
|
||||
</Fragment>
|
||||
);
|
||||
}}
|
||||
</Menu.Item>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
import { Fragment, MouseEventHandler, ReactNode } from "react";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import { Link } from "react-router";
|
||||
import { ChevronDownIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
right?: boolean;
|
||||
title: string;
|
||||
options: {
|
||||
title: string;
|
||||
routePath?: string;
|
||||
onClick?: () => void;
|
||||
disabled?: boolean;
|
||||
}[];
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
btnClassName?: string;
|
||||
onClick?: MouseEventHandler<HTMLButtonElement>;
|
||||
}
|
||||
|
||||
export default function DropdownStyless({ title, options, right, onClick, className, btnClassName }: Props) {
|
||||
return (
|
||||
<Menu as="div" className={clsx(className, "relative inline-block text-left")}>
|
||||
<div>
|
||||
<Menu.Button
|
||||
onClick={onClick}
|
||||
className={
|
||||
btnClassName ??
|
||||
"hover:bg-surface-neutral-secondary shadow-focus bg-surface-neutral-primary text-text-neutral-secondary inline-flex w-full justify-center rounded-md text-sm font-medium focus:outline-hidden focus:ring-offset-2 focus:ring-offset-gray-100"
|
||||
}
|
||||
>
|
||||
{title}
|
||||
{!btnClassName && <ChevronDownIcon className="text-text-neutral-tertiary -mr-1 ml-2 h-5 w-5" />}
|
||||
</Menu.Button>
|
||||
</div>
|
||||
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
className={clsx(
|
||||
"bg-surface-neutral-modal absolute z-40 mt-2 w-48 rounded-md shadow-lg ring-1 ring-border-default focus:outline-hidden",
|
||||
right ? "left-0 origin-top-left" : "right-0 origin-top-right"
|
||||
)}
|
||||
>
|
||||
<div className="py-1">
|
||||
{options.map((item, idx) => {
|
||||
return (
|
||||
<Menu.Item key={idx}>
|
||||
{({ active, close }) => (
|
||||
<>
|
||||
{item.onClick && (
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(
|
||||
"hover:bg-surface-neutral-secondary w-full text-left",
|
||||
item.disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",
|
||||
active ? "text-text-neutral-primary bg-surface-neutral-secondary" : "text-text-neutral-secondary",
|
||||
"block px-4 py-2 text-sm"
|
||||
)}
|
||||
disabled={item.disabled}
|
||||
onClick={() => {
|
||||
if (item.onClick) {
|
||||
item.onClick();
|
||||
}
|
||||
close();
|
||||
}}
|
||||
>
|
||||
{item.title}
|
||||
</button>
|
||||
)}
|
||||
{item.routePath && (
|
||||
<Link
|
||||
to={item.routePath}
|
||||
className={clsx("w-full text-left", active ? "text-text-neutral-primary bg-surface-neutral-secondary" : "text-text-neutral-secondary", "block px-4 py-2 text-sm")}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Menu.Item>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
import { Fragment, MouseEventHandler, ReactNode } from "react";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import { Link } from "react-router";
|
||||
import { ChevronDownIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Props {
|
||||
right?: boolean;
|
||||
button?: ReactNode;
|
||||
to?: string;
|
||||
options?: ReactNode;
|
||||
children?: ReactNode;
|
||||
className?: string;
|
||||
onClick?: MouseEventHandler<HTMLButtonElement>;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export default function DropdownWithClick({ button, to, options, right, onClick, className, disabled }: Props) {
|
||||
return (
|
||||
<span className={clsx(className, "relative z-10 inline-flex rounded-md shadow-2xs")}>
|
||||
{to ? (
|
||||
<Link
|
||||
to={to}
|
||||
className={clsx(
|
||||
"focus:border-brand-brand-border-solid-default shadow-focus border-border-default bg-surface-neutral-primary text-text-neutral-secondary relative -mr-1 inline-flex items-center rounded-l-md border px-4 py-2 text-sm font-medium focus:z-10 focus:outline-hidden",
|
||||
disabled ? "cursor-not-allowed opacity-80" : "hover:bg-surface-neutral-secondary focus:bg-surface-neutral-secondary"
|
||||
)}
|
||||
>
|
||||
{button}
|
||||
</Link>
|
||||
) : (
|
||||
<button
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
type="button"
|
||||
className={clsx(
|
||||
"focus:border-brand-brand-border-solid-default shadow-focus border-border-default bg-surface-neutral-primary text-text-neutral-secondary relative -mr-1 inline-flex items-center rounded-l-md border px-4 py-2 text-sm font-medium focus:z-10 focus:outline-hidden",
|
||||
disabled ? "cursor-not-allowed opacity-80" : "hover:bg-surface-neutral-secondary focus:bg-surface-neutral-secondary"
|
||||
)}
|
||||
>
|
||||
{button}
|
||||
</button>
|
||||
)}
|
||||
<Menu as="span" className="relative -ml-px block">
|
||||
<Menu.Button className="hover:bg-surface-neutral-secondary focus:border-brand-brand-border-solid-default shadow-focus border-border-default text-text-neutral-tertiary bg-surface-neutral-primary relative inline-flex items-center rounded-r-md border px-2 py-2 text-sm font-medium focus:z-10 focus:outline-hidden">
|
||||
<ChevronDownIcon className="h-5 w-5" />
|
||||
</Menu.Button>
|
||||
<Transition
|
||||
as={Fragment}
|
||||
enter="transition ease-out duration-100"
|
||||
enterFrom="transform opacity-0 scale-95"
|
||||
enterTo="transform opacity-100 scale-100"
|
||||
leave="transition ease-in duration-75"
|
||||
leaveFrom="transform opacity-100 scale-100"
|
||||
leaveTo="transform opacity-0 scale-95"
|
||||
>
|
||||
<Menu.Items
|
||||
className={clsx(
|
||||
"bg-surface-neutral-modal absolute z-40 mt-2 w-48 rounded-md shadow-lg ring-1 ring-border-default focus:outline-hidden",
|
||||
right ? "left-0 origin-top-left" : "right-0 origin-top-right"
|
||||
)}
|
||||
>
|
||||
<div className="py-1">{options}</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</Menu>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import React, { MouseEventHandler, ReactNode } from "react";
|
||||
import { Menu, Transition } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import { usePopper } from "./use-popper";
|
||||
import { Link } from "react-router";
|
||||
|
||||
interface Props {
|
||||
button: ReactNode;
|
||||
options: {
|
||||
title?: string;
|
||||
routePath?: string;
|
||||
onClick?: () => void | undefined;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
render?: (active: boolean, close: () => void) => ReactNode;
|
||||
}[];
|
||||
size?: "sm" | "md" | "lg" | "xl";
|
||||
onClick?: MouseEventHandler<HTMLButtonElement>;
|
||||
className?: string;
|
||||
}
|
||||
export default function MenuWithPopper({ button, options, size = "sm", onClick, className }: Props) {
|
||||
let [trigger, container] = usePopper({
|
||||
strategy: "fixed",
|
||||
});
|
||||
|
||||
return (
|
||||
<Menu>
|
||||
<span>
|
||||
<Menu.Button ref={trigger} onClick={onClick} className={className}>
|
||||
{button}
|
||||
</Menu.Button>
|
||||
</span>
|
||||
|
||||
<div ref={container} className={clsx(size === "sm" && "w-56", size === "md" && "w-64", size === "lg" && "w-80", size === "xl" && "w-96")}>
|
||||
<Transition
|
||||
enter="transition duration-100 ease-out"
|
||||
enterFrom="transform scale-95 opacity-0"
|
||||
enterTo="transform scale-100 opacity-100"
|
||||
leave="transition duration-75 ease-out"
|
||||
leaveFrom="transform scale-100 opacity-100"
|
||||
leaveTo="transform scale-95 opacity-0"
|
||||
>
|
||||
<Menu.Items className="border-border-default bg-surface-neutral-modal divide-border-default divide-y rounded-md border shadow-lg outline-hidden">
|
||||
<div className="py-1">
|
||||
{options.map((item, idx) => {
|
||||
return (
|
||||
<Menu.Item key={idx}>
|
||||
{({ active, close }) => (
|
||||
<>
|
||||
{item.render && item.render(active, close)}
|
||||
{item.onClick && (
|
||||
<button
|
||||
type="button"
|
||||
className={clsx(
|
||||
item.className,
|
||||
"hover:bg-surface-neutral-secondary w-full text-left",
|
||||
item.disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",
|
||||
active ? "text-text-neutral-primary bg-surface-neutral-secondary" : "text-text-neutral-secondary",
|
||||
"block px-4 py-2 text-sm"
|
||||
)}
|
||||
disabled={item.disabled}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
if (item.onClick) {
|
||||
item.onClick();
|
||||
}
|
||||
close();
|
||||
}}
|
||||
>
|
||||
{item.title}
|
||||
</button>
|
||||
)}
|
||||
{item.routePath && (
|
||||
<Link
|
||||
to={item.routePath}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
close();
|
||||
}}
|
||||
className={clsx(
|
||||
item.className,
|
||||
"hover:bg-surface-neutral-secondary w-full text-left",
|
||||
item.disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer",
|
||||
active ? "text-text-neutral-primary bg-surface-neutral-secondary" : "text-text-neutral-secondary",
|
||||
"block px-4 py-2 text-sm"
|
||||
)}
|
||||
>
|
||||
{item.title}
|
||||
</Link>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Menu.Item>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</Menu.Items>
|
||||
</Transition>
|
||||
</div>
|
||||
</Menu>
|
||||
);
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
import PreviewDropdownsSimple from "./PreviewDropdownsSimple";
|
||||
import { t as i18nT } from "i18next";
|
||||
import PreviewDropdownsWithClick from "./PreviewDropdownsWithClick";
|
||||
|
||||
export default function PreviewDropdowns() {
|
||||
return (
|
||||
<div id="dropdowns">
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.dropdowns.preview.simple")}</h3>
|
||||
<div className="border-border bg-background space-x-2 border border-dashed p-6">
|
||||
<PreviewDropdownsSimple />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<h3 className="text-sm font-medium">{i18nT("components.dropdowns.preview.title")}</h3>
|
||||
<div className="border-border bg-background space-x-2 border border-dashed p-6">
|
||||
<PreviewDropdownsWithClick />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { Link, useLocation } from "react-router";
|
||||
import { Menu } from "@headlessui/react";
|
||||
import { t as i18nT } from "i18next";
|
||||
import clsx from "clsx";
|
||||
import Dropdown from "./Dropdown";
|
||||
|
||||
export default function PreviewDropdownsSimple() {
|
||||
const currentRoute = useLocation().pathname;
|
||||
return (
|
||||
<div className="not-prose border-border bg-background space-x-2 border border-dashed p-6">
|
||||
<div className="w-full space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<Dropdown
|
||||
right={true}
|
||||
onClick={() => alert(i18nT("components.dropdowns.preview.dropdownClick"))}
|
||||
button={<div>{i18nT("components.dropdowns.preview.dropdown")}</div>}
|
||||
options={
|
||||
<div>
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => alert(i18nT("components.dropdowns.preview.clicked"))}
|
||||
className={clsx("w-full text-left", active ? "text-foreground bg-secondary/90" : "text-foreground/80", "block px-4 py-2 text-sm")}
|
||||
>
|
||||
{i18nT("components.dropdowns.preview.button")}
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<Link
|
||||
to={currentRoute}
|
||||
className={clsx("w-full", active ? "text-foreground bg-secondary/90" : "text-foreground/80", "block px-4 py-2 text-sm")}
|
||||
>
|
||||
<div>{i18nT("components.dropdowns.preview.link")}</div>
|
||||
</Link>
|
||||
)}
|
||||
</Menu.Item>
|
||||
</div>
|
||||
}
|
||||
></Dropdown>
|
||||
<Dropdown
|
||||
onClick={() => alert(i18nT("components.dropdowns.preview.dropdownClick"))}
|
||||
button={<div>{i18nT("components.dropdowns.preview.dropdown")}</div>}
|
||||
options={
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
className="hover:bg-secondary text-foreground/80 block w-full px-4 py-2 text-left text-sm focus:outline-hidden"
|
||||
tabIndex={-1}
|
||||
onClick={() => alert(i18nT("components.dropdowns.preview.clicked"))}
|
||||
>
|
||||
<div>{i18nT("components.dropdowns.preview.button")}</div>
|
||||
</button>
|
||||
<Link
|
||||
to={currentRoute}
|
||||
className="hover:bg-secondary text-foreground/80 block w-full px-4 py-2 text-left text-sm focus:outline-hidden"
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div>{i18nT("components.dropdowns.preview.link")}</div>
|
||||
</Link>
|
||||
</div>
|
||||
}
|
||||
></Dropdown>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+70
@@ -0,0 +1,70 @@
|
||||
import { Link, useLocation } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import { Menu } from "@headlessui/react";
|
||||
import clsx from "clsx";
|
||||
import DropdownWithClick from "./DropdownWithClick";
|
||||
|
||||
export default function PreviewDropdownsWithClick() {
|
||||
const currentRoute = useLocation().pathname;
|
||||
return (
|
||||
<div className="not-prose border-border bg-background space-x-2 border border-dashed p-6">
|
||||
<div className="w-full space-y-2">
|
||||
<div className="flex justify-between">
|
||||
<DropdownWithClick
|
||||
right={true}
|
||||
onClick={() => alert(i18nT("components.dropdowns.preview.dropdownClick"))}
|
||||
button={<div>{i18nT("components.dropdowns.preview.withClick")}</div>}
|
||||
options={
|
||||
<div>
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => alert(i18nT("components.dropdowns.preview.clicked"))}
|
||||
className={clsx("w-full text-left", active ? "text-foreground bg-secondary/90" : "text-foreground/80", "block px-4 py-2 text-sm")}
|
||||
>
|
||||
{i18nT("components.dropdowns.preview.button")}
|
||||
</button>
|
||||
)}
|
||||
</Menu.Item>
|
||||
<Menu.Item>
|
||||
{({ active }) => (
|
||||
<Link
|
||||
to={currentRoute}
|
||||
className={clsx("w-full", active ? "text-foreground bg-secondary/90" : "text-foreground/80", "block px-4 py-2 text-sm")}
|
||||
>
|
||||
<div>{i18nT("components.dropdowns.preview.link")}</div>
|
||||
</Link>
|
||||
)}
|
||||
</Menu.Item>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<DropdownWithClick
|
||||
onClick={() => alert(i18nT("components.dropdowns.preview.dropdownClick"))}
|
||||
button={<div>{i18nT("components.dropdowns.preview.withClick")}</div>}
|
||||
options={
|
||||
<div>
|
||||
<button
|
||||
type="button"
|
||||
className="hover:bg-secondary text-foreground/80 block w-full px-4 py-2 text-left text-sm focus:outline-hidden"
|
||||
tabIndex={-1}
|
||||
onClick={() => alert(i18nT("components.dropdowns.preview.clicked"))}
|
||||
>
|
||||
<div>{i18nT("components.dropdowns.preview.button")}</div>
|
||||
</button>
|
||||
<Link
|
||||
to={currentRoute}
|
||||
className="hover:bg-secondary text-foreground/80 block w-full px-4 py-2 text-left text-sm focus:outline-hidden"
|
||||
tabIndex={-1}
|
||||
>
|
||||
<div>{i18nT("components.dropdowns.preview.link")}</div>
|
||||
</Link>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
import { RefCallback, useRef, useCallback, useMemo } from "react";
|
||||
import { createPopper, Options } from "@popperjs/core";
|
||||
|
||||
/**
|
||||
* Example implementation to use Popper: https://popper.js.org/
|
||||
*/
|
||||
export function usePopper(options?: Partial<Options>): [RefCallback<Element | null>, RefCallback<HTMLElement | null>] {
|
||||
let reference = useRef<Element>(null);
|
||||
let popper = useRef<HTMLElement>(null);
|
||||
|
||||
let cleanupCallback = useRef(() => {});
|
||||
|
||||
let instantiatePopper = useCallback(() => {
|
||||
if (!reference.current) return;
|
||||
if (!popper.current) return;
|
||||
|
||||
if (cleanupCallback.current) cleanupCallback.current();
|
||||
|
||||
cleanupCallback.current = createPopper(reference.current, popper.current, options).destroy;
|
||||
}, [reference, popper, cleanupCallback, options]);
|
||||
|
||||
return useMemo(
|
||||
() => [
|
||||
(referenceDomNode) => {
|
||||
// @ts-ignore
|
||||
reference.current = referenceDomNode;
|
||||
instantiatePopper();
|
||||
},
|
||||
(popperDomNode) => {
|
||||
// @ts-ignore
|
||||
popper.current = popperDomNode;
|
||||
instantiatePopper();
|
||||
},
|
||||
],
|
||||
[reference, popper, instantiatePopper]
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { cva, type VariantProps } from "class-variance-authority"
|
||||
|
||||
import { cn } from "~/lib/utils"
|
||||
|
||||
function Empty({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty"
|
||||
// Subframe EmptyState layout: centered column, gap-6 inner stack, px-4 py-8 padding
|
||||
className={cn(
|
||||
"flex min-w-0 flex-1 flex-col items-center justify-center gap-6 text-balance rounded-md border-dashed px-4 py-8 text-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-header"
|
||||
// Subframe EmptyState layout: centered text block, gap-4, max-w-[384px] (max-w-sm)
|
||||
className={cn(
|
||||
"flex max-w-sm flex-col items-center gap-4 text-center",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
const emptyMediaVariants = cva(
|
||||
"mb-2 flex shrink-0 items-center justify-center [&_svg]:pointer-events-none [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-transparent",
|
||||
// Subframe EmptyState icon size: 48px (h-12 w-12)
|
||||
icon: "bg-surface-neutral-secondary text-text-neutral-primary flex size-12 shrink-0 items-center justify-center rounded-md [&_svg:not([class*='size-'])]:size-6",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function EmptyMedia({
|
||||
className,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<"div"> & VariantProps<typeof emptyMediaVariants>) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-icon"
|
||||
data-variant={variant}
|
||||
className={cn(emptyMediaVariants({ variant, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-title"
|
||||
// Subframe EmptyState title typo: text-body-large-0 (20px / 500), centered
|
||||
className={cn("text-body-large-0 font-body-large-0", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyDescription({ className, ...props }: React.ComponentProps<"p">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-description"
|
||||
// Subframe EmptyState body typo: text-body-default-regular-150 (16px / 400 / lh 24px)
|
||||
className={cn(
|
||||
"text-text-neutral-secondary text-body-default-regular-150 font-body-default-regular-150 [&>a:hover]:text-brand-brand-surface-solid-default [&>a]:underline [&>a]:underline-offset-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function EmptyContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="empty-content"
|
||||
className={cn(
|
||||
"flex w-full min-w-0 max-w-sm flex-col items-center gap-4 text-balance text-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Empty,
|
||||
EmptyHeader,
|
||||
EmptyTitle,
|
||||
EmptyDescription,
|
||||
EmptyContent,
|
||||
EmptyMedia,
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
import ButtonSecondary from "../buttons/ButtonSecondary";
|
||||
import IconEmptyResults from "~/components/ui/icons/IconEmptyResults";
|
||||
import clsx from "clsx";
|
||||
import { PlusIcon, ReloadIcon } from "~/components/ui/icons/vendor";
|
||||
|
||||
interface Captions {
|
||||
description?: string;
|
||||
thereAreNo?: string;
|
||||
new?: string;
|
||||
}
|
||||
|
||||
interface Props {
|
||||
className?: string;
|
||||
captions: Captions;
|
||||
to?: string;
|
||||
icon?: string;
|
||||
onClick?: () => void;
|
||||
}
|
||||
|
||||
export default function EmptyState({ className, captions, to, icon, onClick }: Props) {
|
||||
return (
|
||||
// Subframe EmptyState layout: centered column, px-4 py-8, gap-6 stack, gap-4 text block, 48px icon, body-large title / body-default body
|
||||
<div className={clsx(className, "border-border-default flex flex-col items-center gap-6 rounded-md border-2 border-dashed px-4 py-8 text-center")}>
|
||||
<IconEmptyResults className="h-12 w-12" />
|
||||
<div className="flex max-w-[384px] flex-col items-center gap-4">
|
||||
<h3 className="text-body-large-0 font-body-large-0 text-text-neutral-primary">{captions.thereAreNo}</h3>
|
||||
{captions.description && (
|
||||
<p className="text-text-neutral-secondary text-body-default-regular-150 font-body-default-regular-150">{captions.description}</p>
|
||||
)}
|
||||
</div>
|
||||
{captions.new && (
|
||||
<div>
|
||||
{(() => {
|
||||
if (to) {
|
||||
return (
|
||||
<ButtonSecondary to={to}>
|
||||
{(() => {
|
||||
if (icon === "plus") {
|
||||
return <PlusIcon className="h-4 w-4" />;
|
||||
} else if (icon === "refresh") {
|
||||
return <ReloadIcon className="h-4 w-4" />;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
})()}
|
||||
<div>{captions.new}</div>
|
||||
</ButtonSecondary>
|
||||
);
|
||||
} else {
|
||||
return (
|
||||
<ButtonSecondary onClick={onClick} type="button">
|
||||
{icon === "plus" && <PlusIcon className="h-4 w-4" />}
|
||||
<div>{captions.new}</div>
|
||||
</ButtonSecondary>
|
||||
);
|
||||
}
|
||||
})()}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
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 }) {
|
||||
return (
|
||||
// Subframe EmptyState layout: centered, px-4 py-8, body-default typo
|
||||
<div className={cn("border-border-default bg-surface-neutral-primary w-full rounded-md border-2 border-dashed px-4 py-8 text-center", className)}>
|
||||
{/* <IconEmptyResults className="mx-auto w-10" /> */}
|
||||
<div className="text-text-neutral-secondary text-body-default-regular-150 font-body-default-regular-150">{children}</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
import { useLocation } from "react-router";
|
||||
import { t as i18nT } from "i18next";
|
||||
import EmptyState from "./EmptyState";
|
||||
|
||||
export default function PreviewEmptyStates() {
|
||||
const currentRoute = useLocation().pathname;
|
||||
return (
|
||||
<div id="empty-states" className="space-y-1">
|
||||
<div className="border-border bg-background border border-dashed p-6">
|
||||
<div className="w-full space-y-2">
|
||||
<EmptyState
|
||||
onClick={() => alert(i18nT("components.emptyState.preview.clicked"))}
|
||||
captions={{
|
||||
new: i18nT("components.emptyState.preview.button"),
|
||||
thereAreNo: i18nT("components.emptyState.preview.thereAreNo"),
|
||||
description: i18nT("components.emptyState.preview.description"),
|
||||
}}
|
||||
icon="plus"
|
||||
/>
|
||||
<EmptyState
|
||||
to={currentRoute}
|
||||
captions={{
|
||||
new: i18nT("components.emptyState.preview.link"),
|
||||
thereAreNo: i18nT("components.emptyState.preview.thereAreNo"),
|
||||
description: i18nT("components.emptyState.preview.description"),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, it, vi } from "vitest";
|
||||
import { ErrorPage, type ErrorStatus } from "./ErrorPage";
|
||||
import { expectNoA11yViolations } from "~/utils/test/a11y";
|
||||
|
||||
const translations = vi.hoisted<Record<string, string>>(() => ({
|
||||
"401.eyebrow": "Unauthorized",
|
||||
"401.title": "You're not authorized to see this page.",
|
||||
"401.description": "Contact your admin and verify your permissions.",
|
||||
"403.eyebrow": "Forbidden",
|
||||
"403.title": "You don't have permission to access this page.",
|
||||
"403.description": "If you think this is a mistake, contact your admin or request access.",
|
||||
"404.eyebrow": "404 error",
|
||||
"404.title": "Page not found.",
|
||||
"404.description": "Sorry, we couldn't find the page you're looking for.",
|
||||
"500.eyebrow": "500 error",
|
||||
"500.title": "Something went wrong.",
|
||||
"500.description": "We couldn't complete your request. Please try again or contact support if the issue continues.",
|
||||
"503.eyebrow": "503 error",
|
||||
"503.title": "Maintenance mode.",
|
||||
"503.description": "We're making improvements. Please try again shortly.",
|
||||
goBack: "Go back",
|
||||
"shared.logo": "Logo",
|
||||
}));
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => vi.fn(),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => translations[key] ?? key,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/brand/Logo", () => ({ default: () => <div data-testid="logo">Logo</div> }));
|
||||
vi.mock("~/components/public/PublicFooter", () => ({ default: () => <footer data-testid="public-footer">Footer</footer> }));
|
||||
|
||||
describe("ErrorPage a11y", () => {
|
||||
it.each([401, 403, 404, 500, 503] as ErrorStatus[])("status %s renders without a11y violations", async (status) => {
|
||||
await expectNoA11yViolations(
|
||||
<MemoryRouter>
|
||||
<ErrorPage status={status} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
});
|
||||
|
||||
it("custom back link variant has accessible link text", async () => {
|
||||
await expectNoA11yViolations(
|
||||
<MemoryRouter>
|
||||
<ErrorPage status={401} customBackButton={<a href="/dashboard">Return to dashboard</a>} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
});
|
||||
|
||||
it("with logo image fallback uses alt text", async () => {
|
||||
await expectNoA11yViolations(
|
||||
<MemoryRouter>
|
||||
<ErrorPage status={500} logo="/logo.png" />
|
||||
</MemoryRouter>
|
||||
);
|
||||
});
|
||||
});
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
import "@testing-library/jest-dom";
|
||||
import { fireEvent, render, screen } from "@testing-library/react";
|
||||
import { MemoryRouter } from "react-router";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ERROR_PAGE_PRESETS, ErrorPage, type ErrorStatus } from "./ErrorPage";
|
||||
|
||||
const navigate = vi.fn();
|
||||
const errorMessages = vi.hoisted<Record<string, string>>(() => ({
|
||||
"401.eyebrow": "Unauthorized",
|
||||
"401.title": "You're not authorized to see this page.",
|
||||
"401.description": "Contact your admin and verify your permissions.",
|
||||
"403.eyebrow": "Forbidden",
|
||||
"403.title": "You don't have permission to access this page.",
|
||||
"403.description": "If you think this is a mistake, contact your admin or request access.",
|
||||
"404.eyebrow": "404 error",
|
||||
"404.title": "Page not found.",
|
||||
"404.description": "Sorry, we couldn't find the page you're looking for.",
|
||||
"500.eyebrow": "500 error",
|
||||
"500.title": "Something went wrong.",
|
||||
"500.description": "We couldn't complete your request. Please try again or contact support if the issue continues.",
|
||||
"503.eyebrow": "503 error",
|
||||
"503.title": "Maintenance mode.",
|
||||
"503.description": "We're making improvements. Please try again shortly.",
|
||||
goBack: "Go back",
|
||||
"shared.logo": "Logo",
|
||||
}));
|
||||
|
||||
const expectedErrorCopy = Object.fromEntries(
|
||||
([401, 403, 404, 500, 503] as ErrorStatus[]).map((status) => [
|
||||
status,
|
||||
{
|
||||
eyebrow: errorMessages[ERROR_PAGE_PRESETS[status].eyebrowKey],
|
||||
title: errorMessages[ERROR_PAGE_PRESETS[status].titleKey],
|
||||
description: errorMessages[ERROR_PAGE_PRESETS[status].descriptionKey],
|
||||
},
|
||||
])
|
||||
) as Record<ErrorStatus, { eyebrow: string; title: string; description: string }>;
|
||||
|
||||
vi.mock("react-router", async () => {
|
||||
const actual = await vi.importActual<typeof import("react-router")>("react-router");
|
||||
return {
|
||||
...actual,
|
||||
useNavigate: () => navigate,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("react-i18next", () => ({
|
||||
useTranslation: () => ({
|
||||
t: (key: string) => errorMessages[key] ?? key,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("~/components/brand/Logo", () => ({ default: () => <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>> = {}) {
|
||||
return render(
|
||||
<MemoryRouter>
|
||||
<ErrorPage status={status} {...props} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
}
|
||||
|
||||
describe("ErrorPage", () => {
|
||||
it.each([401, 403, 404, 500, 503] as ErrorStatus[])("renders preset copy and markers for %s", (status) => {
|
||||
renderErrorPage(status);
|
||||
|
||||
const preset = ERROR_PAGE_PRESETS[status];
|
||||
const copy = expectedErrorCopy[status];
|
||||
const page = screen.getByTestId("error-page");
|
||||
expect(page).toHaveAttribute("data-error-status", String(status));
|
||||
expect(preset.eyebrowKey).toBe(`${status}.eyebrow`);
|
||||
expect(screen.getByText(copy.eyebrow)).toBeInTheDocument();
|
||||
expect(screen.getByRole("heading", { name: copy.title })).toBeInTheDocument();
|
||||
expect(screen.getByText(copy.description)).toBeInTheDocument();
|
||||
expect(screen.getByTestId("logo")).toBeInTheDocument();
|
||||
expect(screen.getByTestId("public-footer")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("omits footer and back controls when disabled", () => {
|
||||
renderErrorPage(404, { withFooter: false, withGoBack: false });
|
||||
|
||||
expect(screen.queryByTestId("public-footer")).not.toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /go back/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("renders a custom back action instead of the default navigation button", () => {
|
||||
renderErrorPage(401, { customBackButton: <a href="/dashboard">Return to dashboard</a> });
|
||||
|
||||
expect(screen.getByRole("link", { name: "Return to dashboard" })).toBeInTheDocument();
|
||||
expect(screen.queryByRole("button", { name: /go back/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("navigates back with the default back action", () => {
|
||||
renderErrorPage(403);
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /go back/i }));
|
||||
|
||||
expect(navigate).toHaveBeenCalledWith(-1);
|
||||
});
|
||||
|
||||
it("does not render diagnostics unless explicitly supplied", () => {
|
||||
const { rerender } = render(
|
||||
<MemoryRouter>
|
||||
<ErrorPage status={500} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.queryByText("stack trace details")).not.toBeInTheDocument();
|
||||
|
||||
rerender(
|
||||
<MemoryRouter>
|
||||
<ErrorPage status={500} diagnosticChildren={<pre>stack trace details</pre>} />
|
||||
</MemoryRouter>
|
||||
);
|
||||
|
||||
expect(screen.getByText("stack trace details")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
import { useNavigate } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import Logo from "~/components/brand/Logo";
|
||||
import PublicFooter from "~/components/public/PublicFooter";
|
||||
|
||||
export type ErrorStatus = 401 | 403 | 404 | 500 | 503;
|
||||
|
||||
export interface ErrorPagePreset {
|
||||
eyebrowKey: string;
|
||||
titleKey: string;
|
||||
descriptionKey: string;
|
||||
}
|
||||
|
||||
export const ERROR_PAGE_PRESETS: Record<ErrorStatus, ErrorPagePreset> = {
|
||||
401: {
|
||||
eyebrowKey: "401.eyebrow",
|
||||
titleKey: "401.title",
|
||||
descriptionKey: "401.description",
|
||||
},
|
||||
403: {
|
||||
eyebrowKey: "403.eyebrow",
|
||||
titleKey: "403.title",
|
||||
descriptionKey: "403.description",
|
||||
},
|
||||
404: {
|
||||
eyebrowKey: "404.eyebrow",
|
||||
titleKey: "404.title",
|
||||
descriptionKey: "404.description",
|
||||
},
|
||||
500: {
|
||||
eyebrowKey: "500.eyebrow",
|
||||
titleKey: "500.title",
|
||||
descriptionKey: "500.description",
|
||||
},
|
||||
503: {
|
||||
eyebrowKey: "503.eyebrow",
|
||||
titleKey: "503.title",
|
||||
descriptionKey: "503.description",
|
||||
},
|
||||
};
|
||||
|
||||
export interface ErrorPageProps {
|
||||
status: ErrorStatus;
|
||||
title?: string;
|
||||
description?: string;
|
||||
eyebrow?: string;
|
||||
withLogo?: boolean;
|
||||
withFooter?: boolean;
|
||||
withGoBack?: boolean;
|
||||
customBackButton?: React.ReactNode;
|
||||
logo?: string | undefined;
|
||||
actionSlot?: React.ReactNode;
|
||||
diagnosticChildren?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function ErrorPage({
|
||||
status,
|
||||
title,
|
||||
description,
|
||||
eyebrow,
|
||||
withLogo = true,
|
||||
withFooter = true,
|
||||
withGoBack = true,
|
||||
customBackButton,
|
||||
logo,
|
||||
actionSlot,
|
||||
diagnosticChildren,
|
||||
}: ErrorPageProps) {
|
||||
const navigate = useNavigate();
|
||||
const { t } = useTranslation("errors");
|
||||
const preset = ERROR_PAGE_PRESETS[status];
|
||||
const resolvedEyebrow = eyebrow ?? t(preset.eyebrowKey);
|
||||
const resolvedTitle = title ?? t(preset.titleKey);
|
||||
const resolvedDescription = description ?? t(preset.descriptionKey);
|
||||
|
||||
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>
|
||||
)}
|
||||
<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"> ←</span> {t("goBack")}
|
||||
</button>
|
||||
)}
|
||||
{actionSlot}
|
||||
</div>
|
||||
)}
|
||||
{diagnosticChildren && <div className="mt-6 text-left">{diagnosticChildren}</div>}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
{withFooter && <PublicFooter />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
Loaded 100 of 5885 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user