Template
1
0

feat: update payment views

This commit is contained in:
2025-12-06 20:42:10 +01:00
parent ce4d5ba013
commit 37164b560f
49 changed files with 1826 additions and 624 deletions

View File

@@ -0,0 +1,34 @@
import { GalleryVerticalEnd } from "lucide-react";
import { Controller } from "@/lib/controller.tsx";
import { User } from "@/services/user.ts";
type Tenant = {
name: string;
logo: React.ElementType;
domain: string;
};
export class AppSiderbarController extends Controller<{
tenant: Tenant;
}> {
async onInit() {
const user = await User.resolve();
if (user === undefined) {
return {
tenant: {
name: "Zitadel",
logo: GalleryVerticalEnd,
domain: "iam.valkyrjs.com",
},
};
}
return {
tenant: {
name: user.tenant.name,
logo: GalleryVerticalEnd,
domain: user.tenant.domain,
},
};
}
}

View File

@@ -1,26 +1,7 @@
import * as React from "react"
import {
IconCamera,
IconChartBar,
IconDashboard,
IconDatabase,
IconFileAi,
IconFileDescription,
IconFileWord,
IconFolder,
IconHelp,
IconInnerShadowTop,
IconListDetails,
IconReport,
IconSearch,
IconSettings,
IconUsers,
} from "@tabler/icons-react"
import { Link } from "@tanstack/react-router";
import { GalleryVerticalEnd } from "lucide-react";
import { NavDocuments } from "@/components/nav-documents"
import { NavMain } from "@/components/nav-main"
import { NavSecondary } from "@/components/nav-secondary"
import { NavUser } from "@/components/nav-user"
import { NavUser } from "@/components/nav-user";
import {
Sidebar,
SidebarContent,
@@ -29,151 +10,38 @@ import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar"
} from "@/components/ui/sidebar";
const data = {
user: {
name: "shadcn",
email: "m@example.com",
avatar: "/avatars/shadcn.jpg",
},
navMain: [
{
title: "Dashboard",
url: "#",
icon: IconDashboard,
},
{
title: "Lifecycle",
url: "#",
icon: IconListDetails,
},
{
title: "Analytics",
url: "#",
icon: IconChartBar,
},
{
title: "Projects",
url: "#",
icon: IconFolder,
},
{
title: "Team",
url: "#",
icon: IconUsers,
},
],
navClouds: [
{
title: "Capture",
icon: IconCamera,
isActive: true,
url: "#",
items: [
{
title: "Active Proposals",
url: "#",
},
{
title: "Archived",
url: "#",
},
],
},
{
title: "Proposal",
icon: IconFileDescription,
url: "#",
items: [
{
title: "Active Proposals",
url: "#",
},
{
title: "Archived",
url: "#",
},
],
},
{
title: "Prompts",
icon: IconFileAi,
url: "#",
items: [
{
title: "Active Proposals",
url: "#",
},
{
title: "Archived",
url: "#",
},
],
},
],
navSecondary: [
{
title: "Settings",
url: "#",
icon: IconSettings,
},
{
title: "Get Help",
url: "#",
icon: IconHelp,
},
{
title: "Search",
url: "#",
icon: IconSearch,
},
],
documents: [
{
name: "Data Library",
url: "#",
icon: IconDatabase,
},
{
name: "Reports",
url: "#",
icon: IconReport,
},
{
name: "Word Assistant",
url: "#",
icon: IconFileWord,
},
],
}
import { makeControllerComponent } from "../lib/controller.tsx";
import { AppSiderbarController } from "./app-sidebar.controller.ts";
import { NavPayment } from "./nav-payment.tsx";
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
export const AppSidebar = makeControllerComponent(AppSiderbarController, ({ tenant }) => {
return (
<Sidebar collapsible="offcanvas" {...props}>
<Sidebar collapsible="offcanvas">
<SidebarHeader>
<SidebarMenu>
<SidebarMenuItem>
<SidebarMenuButton
asChild
className="data-[slot=sidebar-menu-button]:!p-1.5"
>
<a href="#">
<IconInnerShadowTop className="!size-5" />
<span className="text-base font-semibold">Acme Inc.</span>
</a>
<SidebarMenuButton size="lg" asChild>
<Link to="/">
<div className="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
<GalleryVerticalEnd className="size-4" />
</div>
<div className="flex flex-col gap-0.5 leading-none">
<span className="font-medium">{tenant.name}</span>
<span className="">{tenant.domain}</span>
</div>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
</SidebarMenu>
</SidebarHeader>
<SidebarContent>
<NavMain items={data.navMain} />
<NavDocuments items={data.documents} />
<NavSecondary items={data.navSecondary} className="mt-auto" />
<NavPayment />
</SidebarContent>
<SidebarFooter>
<NavUser user={data.user} />
<NavUser />
</SidebarFooter>
</Sidebar>
)
}
);
});

View File

@@ -1,56 +0,0 @@
import { IconCirclePlusFilled, IconMail, type Icon } from "@tabler/icons-react"
import { Button } from "@/components/ui/button"
import {
SidebarGroup,
SidebarGroupContent,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
} from "@/components/ui/sidebar"
export function NavMain({
items,
}: {
items: {
title: string
url: string
icon?: Icon
}[]
}) {
return (
<SidebarGroup>
<SidebarGroupContent className="flex flex-col gap-2">
<SidebarMenu>
<SidebarMenuItem className="flex items-center gap-2">
<SidebarMenuButton
tooltip="Quick Create"
className="bg-primary text-primary-foreground hover:bg-primary/90 hover:text-primary-foreground active:bg-primary/90 active:text-primary-foreground min-w-8 duration-200 ease-linear"
>
<IconCirclePlusFilled />
<span>Quick Create</span>
</SidebarMenuButton>
<Button
size="icon"
className="size-8 group-data-[collapsible=icon]:opacity-0"
variant="outline"
>
<IconMail />
<span className="sr-only">Inbox</span>
</Button>
</SidebarMenuItem>
</SidebarMenu>
<SidebarMenu>
{items.map((item) => (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton tooltip={item.title}>
{item.icon && <item.icon />}
<span>{item.title}</span>
</SidebarMenuButton>
</SidebarMenuItem>
))}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
)
}

View File

@@ -0,0 +1,85 @@
import type { Beneficiary } from "@module/payment/client";
import { Book, CirclePlusIcon, type LucideIcon, SquareTerminal } from "lucide-react";
import type { FunctionComponent } from "react";
import { loadBeneficiaries, payment } from "@/database/payment.ts";
import { Controller } from "@/lib/controller.tsx";
import { User } from "@/services/user.ts";
import { DialogCreateBeneficiary } from "./payment/create-beneficiary.tsx";
export class NavPaymentController extends Controller<{
items: MenuItem[];
}> {
#subscriptions: any[] = [];
async onInit() {
await this.#subscribe();
return {
items: [
{
title: "Dashboard",
url: "/payment",
icon: SquareTerminal,
},
],
};
}
async #subscribe() {
await loadBeneficiaries();
this.#subscriptions.push(
await payment
.collection("beneficiary")
.subscribe({ tenantId: await User.getTenantId() }, { sort: { label: 1 } }, (beneficiaries) => {
this.setState("items", this.#getMenuItems(beneficiaries));
}),
);
}
#getMenuItems(beneficiaries: Beneficiary[]): MenuItem[] {
return [
{
title: "Dashboard",
url: "/payment",
icon: SquareTerminal,
},
{
title: "Beneficiaries",
url: "#",
icon: Book,
isActive: true,
items: [
{
title: "Create Beneficiary",
icon: CirclePlusIcon,
component: DialogCreateBeneficiary,
},
...beneficiaries.map((beneficiary) => ({
title: beneficiary.label ?? "Unlabeled",
url: `/payment/${beneficiary._id}`,
})),
],
},
];
}
}
type MenuItem = {
title: string;
url: string;
icon?: LucideIcon;
isActive?: boolean;
items?: SubMenuItem[];
};
type SubMenuItem =
| {
title: string;
url: string;
}
| {
title: string;
icon: LucideIcon;
component: FunctionComponent<{ title: string; icon: LucideIcon }>;
};

View File

@@ -0,0 +1,78 @@
"use client";
import { Link } from "@tanstack/react-router";
import { ChevronRight } from "lucide-react";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
} from "@/components/ui/sidebar";
import { makeControllerComponent } from "../lib/controller.tsx";
import { NavPaymentController } from "./nav-payment.controller.ts";
export const NavPayment = makeControllerComponent(NavPaymentController, ({ items }) => {
return (
<SidebarGroup>
<SidebarGroupLabel>Payment</SidebarGroupLabel>
<SidebarMenu>
{items.map((item) => {
if (item.items !== undefined) {
return (
<Collapsible key={item.title} asChild defaultOpen={item.isActive} className="group/collapsible">
<SidebarMenuItem>
<CollapsibleTrigger asChild>
<SidebarMenuButton tooltip={item.title}>
{item.icon && <item.icon />}
<span>{item.title}</span>
<ChevronRight className="ml-auto transition-transform duration-200 group-data-[state=open]/collapsible:rotate-90" />
</SidebarMenuButton>
</CollapsibleTrigger>
<CollapsibleContent>
<SidebarMenuSub>
{item.items?.map((subItem) => {
if ("component" in subItem) {
return (
<SidebarMenuSubItem key={subItem.title}>
<subItem.component title={subItem.title} icon={subItem.icon} />
</SidebarMenuSubItem>
);
}
return (
<SidebarMenuSubItem key={subItem.title}>
<SidebarMenuSubButton asChild>
<Link to={subItem.url}>
<span>{subItem.title}</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
);
})}
</SidebarMenuSub>
</CollapsibleContent>
</SidebarMenuItem>
</Collapsible>
);
}
return (
<SidebarMenuItem key={item.title}>
<SidebarMenuButton tooltip={item.title} asChild>
<Link to={item.url}>
{item.icon && <item.icon />}
<span>{item.title}</span>
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroup>
);
});

View File

@@ -1,5 +1,6 @@
import { Controller } from "@/lib/controller.tsx";
import { type User as ZitadelUser, zitadel } from "@/services/zitadel.ts";
import { User } from "@/services/user.ts";
import { zitadel } from "@/services/zitadel.ts";
export class NavUserController extends Controller<{
user: User;
@@ -11,38 +12,14 @@ export class NavUserController extends Controller<{
}
async #getAuthenticatedUser(): Promise<User> {
const user = await zitadel.userManager.getUser();
if (user === null) {
const user = await User.resolve();
if (user === undefined) {
throw new Error("Failed to resolve user session");
}
return getUserProfile(user);
return user;
}
signout() {
zitadel.signout();
}
}
function getUserProfile({ profile }: ZitadelUser): User {
const user: User = { name: "Unknown", email: "unknown@acme.none", avatar: "" };
if (profile.name) {
user.name = profile.name;
} else if (profile.given_name && profile.family_name) {
user.name = `${profile.given_name} ${profile.family_name}`;
} else if (profile.given_name) {
user.name = profile.given_name;
}
if (profile.email) {
user.email = profile.email;
}
if (profile.picture !== undefined) {
user.avatar = profile.picture;
}
return user;
}
type User = {
name: string;
email: string;
avatar: string;
};

View File

@@ -0,0 +1,41 @@
import type { LucideIcon } from "lucide-react";
import { payment } from "@/database/payment.ts";
import { Controller } from "@/lib/controller.tsx";
import { api, getSuccessResponse } from "@/services/api.ts";
import { User } from "@/services/user.ts";
export class CreateBeneficiaryController extends Controller<
{
isSubmitting: boolean;
},
{ title: string; icon: LucideIcon }
> {
#label?: string;
async onInit() {
return {
isSubmitting: false,
};
}
setLabel(label: string) {
this.#label = label;
}
async submit() {
this.setState("isSubmitting", true);
const res = await api.payment.benficiaries.create({
body: {
tenantId: await User.getTenantId(),
label: this.#label,
},
});
if ("data" in res) {
await payment
.collection("beneficiary")
.insertOne(await getSuccessResponse(api.payment.benficiaries.id({ params: { id: res.data } })));
}
this.setState("isSubmitting", false);
}
}

View File

@@ -0,0 +1,58 @@
import { useId } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { LoadingSwap } from "@/components/ui/loading-swap";
import { SidebarMenuSubButton } from "@/components/ui/sidebar.tsx";
import { makeControllerComponent } from "../../lib/controller.tsx";
import { CreateBeneficiaryController } from "./create-beneficiary.controller.ts";
export const DialogCreateBeneficiary = makeControllerComponent(
CreateBeneficiaryController,
({ title, setLabel, submit, isSubmitting, ...props }) => {
const labelId = useId();
return (
<Dialog>
<form>
<DialogTrigger asChild>
<SidebarMenuSubButton className="cursor-pointer bg-secondary hover:bg-secondary/70">
<props.icon /> <span>{title}</span>
</SidebarMenuSubButton>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Create beneficiary</DialogTitle>
<DialogDescription>Create a payment ledger and its supported currencies</DialogDescription>
</DialogHeader>
<div className="grid gap-4">
<div className="grid gap-3">
<Label htmlFor={labelId}>Label</Label>
<Input id={labelId} name="label" onChange={({ target: { value } }) => setLabel(value)} />
</div>
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">Cancel</Button>
</DialogClose>
<Button type="submit" onClick={submit}>
<LoadingSwap isLoading={isSubmitting}>Create</LoadingSwap>
</Button>
</DialogFooter>
</DialogContent>
</form>
</Dialog>
);
},
);

View File

@@ -0,0 +1,43 @@
import { CurrencySchema } from "@module/payment/client";
import type { LucideIcon } from "lucide-react";
import { api } from "@/services/api.ts";
import { Controller } from "../../lib/controller.tsx";
export class CreateLedgerController extends Controller<
{
isSubmitting: boolean;
},
{ title: string; icon: LucideIcon }
> {
#label?: string;
#currencies: string[] = [];
async onInit() {
return {
isSubmitting: false,
};
}
setLabel(label: string) {
this.#label = label;
}
setCurrencies(currencies: string[]) {
this.#currencies = currencies;
}
async submit() {
this.setState("isSubmitting", true);
const result = await api.payment.ledger.create({
body: {
beneficiaryId: crypto.randomUUID(),
label: this.#label,
currencies: this.#currencies.map((currency) => CurrencySchema.parse(currency)),
},
});
console.log(result);
this.setState("isSubmitting", false);
}
}

View File

@@ -0,0 +1,84 @@
import { currencies } from "@module/payment/client";
import { useId } from "react";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
DialogTrigger,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { LoadingSwap } from "@/components/ui/loading-swap";
import {
MultiSelect,
MultiSelectContent,
MultiSelectGroup,
MultiSelectItem,
MultiSelectTrigger,
MultiSelectValue,
} from "@/components/ui/multi-select";
import { SidebarMenuSubButton } from "@/components/ui/sidebar.tsx";
import { makeControllerComponent } from "../../lib/controller.tsx";
import { CreateLedgerController } from "./create-ledger.controller.ts";
export const DialogCreateLedger = makeControllerComponent(
CreateLedgerController,
({ title, setLabel, setCurrencies, submit, isSubmitting, ...props }) => {
const labelId = useId();
return (
<Dialog>
<form>
<DialogTrigger asChild>
<SidebarMenuSubButton className="cursor-pointer bg-secondary hover:bg-secondary/70">
<props.icon /> <span>{title}</span>
</SidebarMenuSubButton>
</DialogTrigger>
<DialogContent className="sm:max-w-[425px]">
<DialogHeader>
<DialogTitle>Create ledger</DialogTitle>
<DialogDescription>Create a payment ledger and its supported currencies</DialogDescription>
</DialogHeader>
<div className="grid gap-4">
<div className="grid gap-3">
<Label htmlFor={labelId}>Label</Label>
<Input id={labelId} name="label" onChange={({ target: { value } }) => setLabel(value)} />
</div>
<div className="grid gap-3">
<Label>Currencies</Label>
<MultiSelect onValuesChange={setCurrencies}>
<MultiSelectTrigger className="w-full max-w-[400px]">
<MultiSelectValue placeholder="Select frameworks..." />
</MultiSelectTrigger>
<MultiSelectContent>
<MultiSelectGroup>
{currencies.map((currency) => (
<MultiSelectItem key={currency} value={currency}>
{currency}
</MultiSelectItem>
))}
</MultiSelectGroup>
</MultiSelectContent>
</MultiSelect>
</div>
</div>
<DialogFooter>
<DialogClose asChild>
<Button variant="outline">Cancel</Button>
</DialogClose>
<Button type="submit" onClick={submit}>
<LoadingSwap isLoading={isSubmitting}>Create</LoadingSwap>
</Button>
</DialogFooter>
</DialogContent>
</form>
</Dialog>
);
},
);

View File

@@ -0,0 +1,45 @@
import { AudioWaveform, Command, GalleryVerticalEnd } from "lucide-react";
import { Controller } from "@/lib/controller.tsx";
type Tenant = {
name: string;
logo: React.ElementType;
plan: string;
};
export class TenantSwitcherController extends Controller<{
activeTenant?: Tenant;
tenants: Tenant[];
}> {
async onInit() {
return {
activeTenant: {
name: "Acme Inc",
logo: GalleryVerticalEnd,
plan: "Enterprise",
},
tenants: [
{
name: "Acme Inc",
logo: GalleryVerticalEnd,
plan: "Enterprise",
},
{
name: "Acme Corp.",
logo: AudioWaveform,
plan: "Startup",
},
{
name: "Evil Corp.",
logo: Command,
plan: "Free",
},
],
};
}
setActiveTenant(tenant: Tenant) {
this.setState("activeTenant", tenant);
}
}

View File

@@ -0,0 +1,74 @@
"use client";
import { ChevronsUpDown, Plus } from "lucide-react";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuShortcut,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { SidebarMenu, SidebarMenuButton, SidebarMenuItem, useSidebar } from "@/components/ui/sidebar";
import { makeControllerComponent } from "../lib/controller.tsx";
import { TenantSwitcherController } from "./tenant-switcher.controller.ts";
export const TenantSwitcher = makeControllerComponent(
TenantSwitcherController,
({ tenants, activeTenant, setActiveTenant }) => {
const { isMobile } = useSidebar();
if (activeTenant === undefined) {
return null;
}
return (
<SidebarMenu>
<SidebarMenuItem>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<SidebarMenuButton
size="lg"
className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground"
>
<div className="bg-sidebar-primary text-sidebar-primary-foreground flex aspect-square size-8 items-center justify-center rounded-lg">
<activeTenant.logo className="size-4" />
</div>
<div className="grid flex-1 text-left text-sm leading-tight">
<span className="truncate font-medium">{activeTenant.name}</span>
<span className="truncate text-xs">{activeTenant.plan}</span>
</div>
<ChevronsUpDown className="ml-auto" />
</SidebarMenuButton>
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-(--radix-dropdown-menu-trigger-width) min-w-56 rounded-lg"
align="start"
side={isMobile ? "bottom" : "right"}
sideOffset={4}
>
<DropdownMenuLabel className="text-muted-foreground text-xs">Teams</DropdownMenuLabel>
{tenants.map((tenant, index) => (
<DropdownMenuItem key={tenant.name} onClick={() => setActiveTenant(tenant)} className="gap-2 p-2">
<div className="flex size-6 items-center justify-center rounded-md border">
<tenant.logo className="size-3.5 shrink-0" />
</div>
{tenant.name}
<DropdownMenuShortcut>{index + 1}</DropdownMenuShortcut>
</DropdownMenuItem>
))}
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-2 p-2">
<div className="flex size-6 items-center justify-center rounded-md border bg-transparent">
<Plus className="size-4" />
</div>
<div className="text-muted-foreground font-medium">Add team</div>
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</SidebarMenuItem>
</SidebarMenu>
);
},
);

View File

@@ -1,8 +1,8 @@
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "@radix-ui/react-slot";
import { cva, type VariantProps } from "class-variance-authority";
import type * as React from "react";
import { cn } from "@/lib/utils"
import { cn } from "@/lib/utils";
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",
@@ -14,10 +14,8 @@ const buttonVariants = cva(
"bg-destructive text-white 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 hover:bg-secondary/80",
ghost:
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
secondary: "bg-secondary text-secondary-foreground 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: {
@@ -33,8 +31,8 @@ const buttonVariants = cva(
variant: "default",
size: "default",
},
}
)
},
);
function Button({
className,
@@ -44,17 +42,11 @@ function Button({
...props
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean
asChild?: boolean;
}) {
const Comp = asChild ? Slot : "button"
const Comp = asChild ? Slot : "button";
return (
<Comp
data-slot="button"
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
)
return <Comp data-slot="button" className={cn(buttonVariants({ variant, size, className }))} {...props} />;
}
export { Button, buttonVariants }
export { Button, buttonVariants };

View File

@@ -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 }

View File

@@ -0,0 +1,182 @@
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { SearchIcon } from "lucide-react"
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-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",
className
)}
{...props}
/>
)
}
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
children,
className,
showCloseButton = true,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
className?: string
showCloseButton?: boolean
}) {
return (
<Dialog {...props}>
<DialogHeader className="sr-only">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent
className={cn("overflow-hidden p-0", className)}
showCloseButton={showCloseButton}
>
<Command className="[&_[cmdk-group-heading]]:text-muted-foreground **: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 px-3"
>
<SearchIcon className="size-4 shrink-0 opacity-50" />
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
"placeholder:text-muted-foreground 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-foreground [&_[cmdk-group-heading]]:text-muted-foreground 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 -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-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground 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-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props}
/>
)
}
export {
Command,
CommandDialog,
CommandInput,
CommandList,
CommandEmpty,
CommandGroup,
CommandItem,
CommandShortcut,
CommandSeparator,
}

View File

@@ -0,0 +1,141 @@
import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
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,
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
}) {
return (
<DialogPortal data-slot="dialog-portal">
<DialogOverlay />
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"bg-background 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 w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg",
className
)}
{...props}
>
{children}
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
>
<XIcon />
<span className="sr-only">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 flex-col-reverse 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-muted-foreground text-sm", className)}
{...props}
/>
)
}
export {
Dialog,
DialogClose,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogOverlay,
DialogPortal,
DialogTitle,
DialogTrigger,
}

View File

@@ -0,0 +1,33 @@
import { Loader2Icon } from "lucide-react";
import type { ReactNode } from "react";
import { cn } from "@/lib/utils";
export function LoadingSwap({
isLoading,
children,
className,
}: {
isLoading: boolean;
children: ReactNode;
className?: string;
}) {
return (
<div className="grid grid-cols-1 items-center justify-items-center">
<div
className={cn(
"col-start-1 col-end-2 row-start-1 row-end-2 w-full",
isLoading ? "invisible" : "visible",
className,
)}
>
{children}
</div>
<div
className={cn("col-start-1 col-end-2 row-start-1 row-end-2", isLoading ? "visible" : "invisible", className)}
>
<Loader2Icon className="animate-spin" />
</div>
</div>
);
}

View File

@@ -0,0 +1,325 @@
"use client";
import { CheckIcon, ChevronsUpDownIcon, XIcon } from "lucide-react";
import {
type ComponentPropsWithoutRef,
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from "@/components/ui/command";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
type MultiSelectContextType = {
open: boolean;
setOpen: (open: boolean) => void;
selectedValues: Set<string>;
toggleValue: (value: string) => void;
items: Map<string, ReactNode>;
onItemAdded: (value: string, label: ReactNode) => void;
};
const MultiSelectContext = createContext<MultiSelectContextType | null>(null);
export function MultiSelect({
children,
values,
defaultValues,
onValuesChange,
}: {
children: ReactNode;
values?: string[];
defaultValues?: string[];
onValuesChange?: (values: string[]) => void;
}) {
const [open, setOpen] = useState(false);
const [internalValues, setInternalValues] = useState(new Set<string>(values ?? defaultValues));
const selectedValues = values ? new Set(values) : internalValues;
const [items, setItems] = useState<Map<string, ReactNode>>(new Map());
function toggleValue(value: string) {
const getNewSet = (prev: Set<string>) => {
const newSet = new Set(prev);
if (newSet.has(value)) {
newSet.delete(value);
} else {
newSet.add(value);
}
return newSet;
};
setInternalValues(getNewSet);
onValuesChange?.([...getNewSet(selectedValues)]);
}
const onItemAdded = useCallback((value: string, label: ReactNode) => {
setItems((prev) => {
if (prev.get(value) === label) return prev;
return new Map(prev).set(value, label);
});
}, []);
return (
<MultiSelectContext
value={{
open,
setOpen,
selectedValues,
toggleValue,
items,
onItemAdded,
}}
>
<Popover open={open} onOpenChange={setOpen} modal={true}>
{children}
</Popover>
</MultiSelectContext>
);
}
export function MultiSelectTrigger({
className,
children,
...props
}: {
className?: string;
children?: ReactNode;
} & ComponentPropsWithoutRef<typeof Button>) {
const { open } = useMultiSelectContext();
return (
<PopoverTrigger asChild>
<Button
{...props}
variant={props.variant ?? "outline"}
role={props.role ?? "combobox"}
aria-expanded={props["aria-expanded"] ?? open}
className={cn(
"flex h-auto min-h-9 w-fit items-center justify-between gap-2 overflow-hidden rounded-md border border-input bg-transparent px-3 py-1.5 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-[placeholder]:text-muted-foreground dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className,
)}
>
{children}
<ChevronsUpDownIcon className="size-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
);
}
export function MultiSelectValue({
placeholder,
clickToRemove = true,
className,
overflowBehavior = "wrap-when-open",
...props
}: {
placeholder?: string;
clickToRemove?: boolean;
overflowBehavior?: "wrap" | "wrap-when-open" | "cutoff";
} & Omit<ComponentPropsWithoutRef<"div">, "children">) {
const { selectedValues, toggleValue, items, open } = useMultiSelectContext();
const [overflowAmount, setOverflowAmount] = useState(0);
const valueRef = useRef<HTMLDivElement>(null);
const overflowRef = useRef<HTMLDivElement>(null);
const shouldWrap = overflowBehavior === "wrap" || (overflowBehavior === "wrap-when-open" && open);
const checkOverflow = useCallback(() => {
if (valueRef.current == null) {
return;
}
const containerElement = valueRef.current;
const overflowElement = overflowRef.current;
const items = containerElement.querySelectorAll<HTMLElement>("[data-selected-item]");
if (overflowElement != null) {
overflowElement.style.display = "none";
}
for (const child of items) {
child.style.removeProperty("display");
}
let amount = 0;
for (let i = items.length - 1; i >= 0; i--) {
const child = items[i];
if (containerElement.scrollWidth <= containerElement.clientWidth) {
break;
}
amount = items.length - i;
child.style.display = "none";
overflowElement?.style.removeProperty("display");
}
setOverflowAmount(amount);
}, []);
const handleResize = useCallback(
(node: HTMLDivElement) => {
valueRef.current = node;
const mutationObserver = new MutationObserver(checkOverflow);
const observer = new ResizeObserver(debounce(checkOverflow, 100));
mutationObserver.observe(node, {
childList: true,
attributes: true,
attributeFilter: ["class", "style"],
});
observer.observe(node);
return () => {
observer.disconnect();
mutationObserver.disconnect();
valueRef.current = null;
};
},
[checkOverflow],
);
if (selectedValues.size === 0 && placeholder) {
return <span className="min-w-0 overflow-hidden font-normal text-muted-foreground">{placeholder}</span>;
}
return (
<div
{...props}
ref={handleResize}
className={cn("flex w-full gap-1.5 overflow-hidden", shouldWrap && "h-full flex-wrap", className)}
>
{[...selectedValues]
.filter((value) => items.has(value))
.map((value) => (
<Badge
variant="outline"
data-selected-item
className="group flex items-center gap-1"
key={value}
onClick={
clickToRemove
? (e) => {
e.stopPropagation();
toggleValue(value);
}
: undefined
}
>
{items.get(value)}
{clickToRemove && <XIcon className="size-2 text-muted-foreground group-hover:text-destructive" />}
</Badge>
))}
<Badge
style={{
display: overflowAmount > 0 && !shouldWrap ? "block" : "none",
}}
variant="outline"
ref={overflowRef}
>
+{overflowAmount}
</Badge>
</div>
);
}
export function MultiSelectContent({
search = true,
children,
...props
}: {
search?: boolean | { placeholder?: string; emptyMessage?: string };
children: ReactNode;
} & Omit<ComponentPropsWithoutRef<typeof Command>, "children">) {
const canSearch = typeof search === "object" ? true : search;
return (
<>
<div style={{ display: "none" }}>
<Command>
<CommandList>{children}</CommandList>
</Command>
</div>
<PopoverContent className="min-w-[var(--radix-popover-trigger-width)] p-0">
<Command {...props}>
{canSearch ? (
<CommandInput placeholder={typeof search === "object" ? search.placeholder : undefined} />
) : (
<button type="button" className="sr-only" />
)}
<CommandList>
{canSearch && <CommandEmpty>{typeof search === "object" ? search.emptyMessage : undefined}</CommandEmpty>}
{children}
</CommandList>
</Command>
</PopoverContent>
</>
);
}
export function MultiSelectItem({
value,
children,
badgeLabel,
onSelect,
...props
}: {
badgeLabel?: ReactNode;
value: string;
} & Omit<ComponentPropsWithoutRef<typeof CommandItem>, "value">) {
const { toggleValue, selectedValues, onItemAdded } = useMultiSelectContext();
const isSelected = selectedValues.has(value);
useEffect(() => {
onItemAdded(value, badgeLabel ?? children);
}, [value, children, onItemAdded, badgeLabel]);
return (
<CommandItem
{...props}
onSelect={() => {
toggleValue(value);
onSelect?.(value);
}}
>
<CheckIcon className={cn("mr-2 size-4", isSelected ? "opacity-100" : "opacity-0")} />
{children}
</CommandItem>
);
}
export function MultiSelectGroup(props: ComponentPropsWithoutRef<typeof CommandGroup>) {
return <CommandGroup {...props} />;
}
export function MultiSelectSeparator(props: ComponentPropsWithoutRef<typeof CommandSeparator>) {
return <CommandSeparator {...props} />;
}
function useMultiSelectContext() {
const context = useContext(MultiSelectContext);
if (context == null) {
throw new Error("useMultiSelectContext must be used within a MultiSelectContext");
}
return context;
}
function debounce<T extends (...args: never[]) => void>(func: T, wait: number): (...args: Parameters<T>) => void {
let timeout: ReturnType<typeof setTimeout> | null = null;
return function (this: unknown, ...args: Parameters<T>) {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), wait);
};
}

View File

@@ -0,0 +1,46 @@
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
}
function PopoverContent({
className,
align = "center",
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
return (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
data-slot="popover-content"
align={align}
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground 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 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border p-4 shadow-md outline-hidden",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
}
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }