first commit

This commit is contained in:
Michael Dong
2026-02-05 11:24:40 +08:00
commit a98e12f286
144 changed files with 26459 additions and 0 deletions

View File

@@ -0,0 +1,55 @@
"use client";
import type { ReactNode } from "react";
import { Button } from "@/components/ui/button";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import AppSidebar from "@/components/AppSidebar";
import LanguageSwitcher from "@/components/LanguageSwitcher";
import { clearToken } from "@/lib/auth";
import { useTranslation } from "@/lib/i18n";
import { NotificationProvider } from "@/lib/notification-context";
import { UserProvider } from "@/lib/user-context";
const AppShellContent = ({ children }: { children: ReactNode }) => {
const t = useTranslation();
return (
<SidebarProvider defaultOpen>
<div className="flex min-h-screen bg-slate-100 p-6">
<AppSidebar />
<SidebarInset>
<div className="mx-auto flex w-full max-w-6xl flex-col gap-6 px-6">
<div className="rounded-xl bg-white p-4 shadow-sm">
<div className="flex flex-wrap items-center justify-between gap-4">
<div>
<h1 className="text-xl font-semibold leading-tight text-slate-900">Notify</h1>
<p className="text-sm text-slate-500">{t("appDesc")}</p>
</div>
<div className="flex items-center gap-3">
<LanguageSwitcher />
<Button variant="outline" onClick={() => clearToken()}>
{t("logout")}
</Button>
</div>
</div>
</div>
<div className="grid gap-5">{children}</div>
</div>
</SidebarInset>
</div>
</SidebarProvider>
);
};
const AppShell = ({ children }: { children: ReactNode }) => {
return (
<UserProvider>
<NotificationProvider>
<AppShellContent>{children}</AppShellContent>
</NotificationProvider>
</UserProvider>
);
};
export default AppShell;

View File

@@ -0,0 +1,105 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { Bell, BellDot, ListTodo, Settings, UserPlus } from "lucide-react";
import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupContent,
SidebarGroupLabel,
SidebarHeader,
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
SidebarSeparator,
} from "@/components/ui/sidebar";
import Avatar from "@/components/ui/avatar";
import { useTranslation, type TranslationKey } from "@/lib/i18n";
import { useNotification } from "@/lib/notification-context";
import { useUser } from "@/lib/user-context";
const navItems: { href: string; labelKey: TranslationKey; icon: typeof ListTodo }[] = [
{ href: "/todos", labelKey: "navTodo", icon: ListTodo },
{ href: "/reminders", labelKey: "navReminder", icon: Bell },
{ href: "/invites", labelKey: "navInvites", icon: UserPlus },
{ href: "/settings", labelKey: "navSettings", icon: Settings },
{ href: "/notifications", labelKey: "navNotifications", icon: BellDot },
];
const AppSidebar = () => {
const pathname = usePathname();
const { unreadCount } = useNotification();
const { user } = useUser();
const t = useTranslation();
return (
<Sidebar variant="inset" className="h-[calc(100vh-3rem)] self-start bg-white">
<SidebarHeader className="gap-2 px-3 py-4">
<div className="flex items-center gap-2">
<span className="flex h-8 w-8 items-center justify-center rounded-full bg-blue-500/10 text-blue-600">
<span className="text-base font-semibold"></span>
</span>
<span className="text-base font-semibold group-data-[state=collapsed]/sidebar:hidden">
notify
</span>
</div>
</SidebarHeader>
<SidebarContent>
<SidebarGroup>
<SidebarGroupLabel className="group-data-[state=collapsed]/sidebar:hidden">
{t("navigation")}
</SidebarGroupLabel>
<SidebarGroupContent>
<SidebarMenu>
{navItems.map((item) => {
const isActive = pathname?.startsWith(item.href);
const isNotifications = item.href === "/notifications";
return (
<SidebarMenuItem key={item.href}>
<SidebarMenuButton
asChild
isActive={isActive}
className="group-data-[state=collapsed]/sidebar:justify-center group-data-[state=collapsed]/sidebar:px-2"
>
<Link href={item.href}>
<span className="relative">
<item.icon className="h-4 w-4" />
{isNotifications && unreadCount > 0 && (
<span className="absolute -right-1 -top-1 hidden h-2 w-2 rounded-full bg-red-500 group-data-[state=collapsed]/sidebar:inline-flex" />
)}
</span>
<span className="group-data-[state=collapsed]/sidebar:hidden">
{t(item.labelKey)}
</span>
{isNotifications && unreadCount > 0 && (
<span className="ml-auto rounded-full bg-red-500 px-2 py-0.5 text-xs font-semibold text-white group-data-[state=collapsed]/sidebar:hidden">
{unreadCount}
</span>
)}
</Link>
</SidebarMenuButton>
</SidebarMenuItem>
);
})}
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
</SidebarContent>
<SidebarSeparator />
<SidebarFooter className="px-3 py-4">
<div className="flex items-center gap-2 group-data-[state=collapsed]/sidebar:justify-center">
<Avatar username={user?.username} src={user?.avatar} size="sm" />
<span className="text-sm font-medium text-slate-700 group-data-[state=collapsed]/sidebar:hidden">
{user?.username}
</span>
</div>
</SidebarFooter>
</Sidebar>
);
};
export default AppSidebar;

View File

@@ -0,0 +1,57 @@
"use client";
import { useState } from "react";
import { Globe } from "lucide-react";
import { Button } from "@/components/ui/button";
import {
Popover,
PopoverContent,
PopoverTrigger,
} from "@/components/ui/popover";
import { useI18n, type Locale } from "@/lib/i18n";
const languages: { value: Locale; label: string }[] = [
{ value: "zh", label: "中文" },
{ value: "en", label: "English" },
];
const LanguageSwitcher = () => {
const { locale, setLocale, t } = useI18n();
const [open, setOpen] = useState(false);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button variant="outline" size="sm" className="gap-2">
<Globe className="h-4 w-4" />
<span className="hidden sm:inline">
{languages.find((l) => l.value === locale)?.label}
</span>
</Button>
</PopoverTrigger>
<PopoverContent className="w-32 p-1" align="end">
<div className="flex flex-col gap-1">
{languages.map((lang) => (
<button
key={lang.value}
className={`w-full rounded-md px-3 py-2 text-left text-sm transition-colors hover:bg-slate-100 ${
locale === lang.value
? "bg-slate-100 font-medium text-slate-900"
: "text-slate-600"
}`}
onClick={() => {
setLocale(lang.value);
setOpen(false);
}}
>
{lang.label}
</button>
))}
</div>
</PopoverContent>
</Popover>
);
};
export default LanguageSwitcher;

View File

@@ -0,0 +1,204 @@
"use client";
import { useEffect, useState, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import Avatar from "@/components/ui/avatar";
import { api } from "@/lib/api";
import { useTranslation } from "@/lib/i18n";
import { useUser } from "@/lib/user-context";
type Me = {
username?: string;
avatar?: string | null;
timezone: string;
barkUrl?: string | null;
inappEnabled: boolean;
barkEnabled: boolean;
};
const SettingsPanel = () => {
const t = useTranslation();
const { refreshUser } = useUser();
const fileInputRef = useRef<HTMLInputElement>(null);
const [form, setForm] = useState<Me>({
timezone: "Asia/Shanghai",
barkUrl: "",
avatar: null,
inappEnabled: true,
barkEnabled: false,
});
const [saved, setSaved] = useState(false);
const [uploading, setUploading] = useState(false);
useEffect(() => {
api
.getMe()
.then((data) => setForm(data as Me))
.catch(() => null);
}, []);
const save = async () => {
await api.updateSettings({
avatar: form.avatar || null,
timezone: form.timezone,
barkUrl: form.barkUrl || null,
inappEnabled: form.inappEnabled,
barkEnabled: form.barkEnabled,
});
await refreshUser();
setSaved(true);
setTimeout(() => setSaved(false), 1500);
};
const handleFileChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (!file) return;
// 验证文件类型
const allowedTypes = ["image/jpeg", "image/png", "image/gif", "image/webp"];
if (!allowedTypes.includes(file.type)) {
alert("不支持的文件格式,请上传 jpg、png、gif 或 webp 格式的图片");
return;
}
// 验证文件大小 (5MB)
if (file.size > 5 * 1024 * 1024) {
alert("文件大小不能超过 5MB");
return;
}
try {
setUploading(true);
const result = await api.uploadAvatar(file);
setForm({ ...form, avatar: result.avatarUrl });
await refreshUser();
} catch (error) {
console.error("上传头像失败:", error);
alert("上传头像失败,请重试");
} finally {
setUploading(false);
}
};
const handleRemoveAvatar = () => {
setForm({ ...form, avatar: null });
if (fileInputRef.current) {
fileInputRef.current.value = "";
}
};
return (
<Card className="bg-white">
<CardHeader>
<CardTitle>{t("settings")}</CardTitle>
<CardDescription>{t("settingsDesc")}</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
{/* Avatar Section */}
<div className="space-y-2">
<Label>{t("avatar")}</Label>
<div className="flex items-center gap-4">
<Avatar username={form.username} src={form.avatar} size="lg" />
<div className="flex flex-col gap-2">
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleFileChange}
className="hidden"
id="avatar-upload"
/>
<Button
variant="outline"
size="sm"
onClick={() => fileInputRef.current?.click()}
disabled={uploading}
>
{uploading ? t("uploading") : t("uploadAvatar")}
</Button>
{form.avatar && (
<Button
variant="outline"
size="sm"
onClick={handleRemoveAvatar}
>
{t("removeAvatar")}
</Button>
)}
<p className="text-xs text-slate-500">{t("avatarHint")}</p>
</div>
</div>
</div>
<div className="space-y-2">
<Label htmlFor="barkUrl">{t("barkPushUrl")}</Label>
<Input
id="barkUrl"
value={form.barkUrl ?? ""}
onChange={(event) => setForm({ ...form, barkUrl: event.target.value })}
placeholder="https://your.bark.server"
/>
</div>
<div className="space-y-2">
<Label htmlFor="timezone">{t("timezone")}</Label>
<Input
id="timezone"
value={form.timezone}
onChange={(event) => setForm({ ...form, timezone: event.target.value })}
placeholder="Asia/Shanghai"
/>
</div>
<div className="space-y-2">
<Label>{t("notificationChannels")}</Label>
<div className="rounded-lg bg-slate-50/80">
<div className="flex items-center justify-between px-4 py-3">
<div>
<div className="text-sm font-medium text-slate-800">{t("webNotifications")}</div>
<div className="text-xs text-slate-500">{t("webNotificationsDesc")}</div>
</div>
<Checkbox
id="inapp"
checked={form.inappEnabled}
onCheckedChange={(checked) =>
setForm({ ...form, inappEnabled: checked === true })
}
/>
</div>
<div className="mx-4 h-px bg-slate-200/50" />
<div className="flex items-center justify-between px-4 py-3">
<div>
<div className="text-sm font-medium text-slate-800">{t("barkAlerts")}</div>
<div className="text-xs text-slate-500">{t("barkAlertsDesc")}</div>
</div>
<Checkbox
id="bark"
checked={form.barkEnabled}
onCheckedChange={(checked) =>
setForm({ ...form, barkEnabled: checked === true })
}
/>
</div>
</div>
</div>
<div className="flex items-center gap-3">
<Button variant="outline" onClick={save}>
{t("save")}
</Button>
<Button variant="outline" type="button">
{t("cancel")}
</Button>
{saved && <div className="text-sm text-primary">{t("saved")}</div>}
</div>
</div>
</CardContent>
</Card>
);
};
export default SettingsPanel;

View File

@@ -0,0 +1,117 @@
"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";
const AlertDialog = AlertDialogPrimitive.Root;
const AlertDialogTrigger = AlertDialogPrimitive.Trigger;
const AlertDialogPortal = AlertDialogPrimitive.Portal;
const AlertDialogOverlay = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Overlay
className={cn(
"fixed inset-0 z-50 bg-black/50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
ref={ref}
/>
));
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName;
const AlertDialogContent = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Content>
>(({ className, ...props }, ref) => (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 bg-white p-6 shadow-xl duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-xl",
className
)}
{...props}
/>
</AlertDialogPortal>
));
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName;
const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-2 text-center sm:text-left", className)} {...props} />
);
AlertDialogHeader.displayName = "AlertDialogHeader";
const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
{...props}
/>
);
AlertDialogFooter.displayName = "AlertDialogFooter";
const AlertDialogTitle = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold text-slate-900", className)}
{...props}
/>
));
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName;
const AlertDialogDescription = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Description
ref={ref}
className={cn("text-sm text-slate-500", className)}
{...props}
/>
));
AlertDialogDescription.displayName = AlertDialogPrimitive.Description.displayName;
const AlertDialogAction = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Action>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Action>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
));
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName;
const AlertDialogCancel = React.forwardRef<
React.ElementRef<typeof AlertDialogPrimitive.Cancel>,
React.ComponentPropsWithoutRef<typeof AlertDialogPrimitive.Cancel>
>(({ className, ...props }, ref) => (
<AlertDialogPrimitive.Cancel
ref={ref}
className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
{...props}
/>
));
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName;
export {
AlertDialog,
AlertDialogPortal,
AlertDialogOverlay,
AlertDialogTrigger,
AlertDialogContent,
AlertDialogHeader,
AlertDialogFooter,
AlertDialogTitle,
AlertDialogDescription,
AlertDialogAction,
AlertDialogCancel,
};

View File

@@ -0,0 +1,81 @@
"use client";
import { useMemo } from "react";
import { cn } from "@/lib/utils";
type AvatarProps = {
username?: string | null;
src?: string | null;
size?: "sm" | "md" | "lg";
className?: string;
};
const sizeClasses = {
sm: "h-8 w-8 text-sm",
md: "h-10 w-10 text-base",
lg: "h-12 w-12 text-lg",
};
// Generate a consistent color based on username
const getAvatarColor = (username: string): string => {
const colors = [
"bg-blue-500",
"bg-green-500",
"bg-purple-500",
"bg-orange-500",
"bg-pink-500",
"bg-teal-500",
"bg-indigo-500",
"bg-cyan-500",
];
let hash = 0;
for (let i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + ((hash << 5) - hash);
}
return colors[Math.abs(hash) % colors.length];
};
const Avatar = ({ username, src, size = "md", className }: AvatarProps) => {
const initial = useMemo(() => {
if (!username) return "?";
// Get the first character, handling unicode properly
const firstChar = [...username][0];
return firstChar?.toUpperCase() || "?";
}, [username]);
const bgColor = useMemo(() => {
return username ? getAvatarColor(username) : "bg-slate-400";
}, [username]);
if (src) {
return (
<img
src={src}
alt={username || "Avatar"}
className={cn(
"rounded-full object-cover",
sizeClasses[size],
className
)}
/>
);
}
return (
<div
className={cn(
"flex items-center justify-center rounded-full font-semibold text-white",
sizeClasses[size],
bgColor,
className
)}
title={username || undefined}
>
{initial}
</div>
);
};
export default Avatar;

View File

@@ -0,0 +1,57 @@
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 buttonVariants = cva(
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
{
variants: {
variant: {
default:
"bg-primary text-primary-foreground shadow hover:bg-primary/90",
destructive:
"bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
outline:
"border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
secondary:
"bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
ghost: "hover:bg-accent hover:text-accent-foreground",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: "h-9 px-4 py-2",
sm: "h-8 rounded-md px-3 text-xs",
lg: "h-10 rounded-md px-8",
icon: "h-9 w-9",
},
},
defaultVariants: {
variant: "default",
size: "default",
},
}
)
export interface ButtonProps
extends React.ButtonHTMLAttributes<HTMLButtonElement>,
VariantProps<typeof buttonVariants> {
asChild?: boolean
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
({ className, variant, size, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button"
return (
<Comp
className={cn(buttonVariants({ variant, size, className }))}
ref={ref}
{...props}
/>
)
}
)
Button.displayName = "Button"
export { Button, buttonVariants }

View File

@@ -0,0 +1,89 @@
"use client";
import * as React from "react";
import { ChevronLeft, ChevronRight } from "lucide-react";
import { DayPicker } from "react-day-picker";
import { cn } from "@/lib/utils";
export type CalendarProps = React.ComponentProps<typeof DayPicker>;
function Calendar({
className,
classNames,
showOutsideDays = true,
...props
}: CalendarProps) {
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn("p-3", className)}
classNames={{
months: "flex flex-col sm:flex-row gap-2",
month: "flex flex-col gap-4",
month_caption: "flex justify-center pt-1 relative items-center w-full",
caption_label: "text-sm font-medium",
nav: "flex items-center gap-1",
button_previous: cn(
"absolute left-1 top-0 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100 inline-flex items-center justify-center rounded-md hover:bg-slate-100"
),
button_next: cn(
"absolute right-1 top-0 h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100 inline-flex items-center justify-center rounded-md hover:bg-slate-100"
),
month_grid: "w-full border-collapse space-y-1",
weekdays: "flex",
weekday:
"text-slate-500 rounded-md w-8 font-normal text-[0.8rem]",
week: "flex w-full mt-2",
day: cn(
"relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-slate-100 [&:has([aria-selected].day-range-end)]:rounded-r-md [&:has([aria-selected].day-outside)]:bg-slate-100/50",
props.mode === "range"
? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
: "[&:has([aria-selected])]:rounded-md"
),
day_button: cn(
"h-8 w-8 p-0 font-normal rounded-md text-sm transition-colors hover:bg-slate-100 hover:text-slate-900 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-slate-950 aria-selected:opacity-100"
),
range_start: "day-range-start",
range_end: "day-range-end",
selected:
"bg-slate-900 text-white rounded-md hover:bg-slate-800 hover:text-white focus:bg-slate-900 focus:text-white",
today: "bg-slate-100 text-slate-900",
outside:
"day-outside text-slate-500 aria-selected:bg-slate-100/50 aria-selected:text-slate-500",
disabled: "text-slate-500 opacity-50",
range_middle:
"aria-selected:bg-slate-100 aria-selected:text-slate-900",
hidden: "invisible",
...classNames,
}}
components={{
Chevron: ({ orientation }) => {
const Icon = orientation === "left" ? ChevronLeft : ChevronRight;
return <Icon className="h-4 w-4" />;
},
DayButton: ({ day, modifiers, className, ...buttonProps }) => (
<button
type="button"
className={className}
{...buttonProps}
/>
),
PreviousMonthButton: ({ className, ...buttonProps }) => (
<button type="button" className={className} {...buttonProps}>
<ChevronLeft className="h-4 w-4" />
</button>
),
NextMonthButton: ({ className, ...buttonProps }) => (
<button type="button" className={className} {...buttonProps}>
<ChevronRight className="h-4 w-4" />
</button>
),
}}
{...props}
/>
);
}
Calendar.displayName = "Calendar";
export { Calendar };

View File

@@ -0,0 +1,52 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("rounded-xl bg-card text-card-foreground shadow-sm", className)}
{...props}
/>
)
);
Card.displayName = "Card";
const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
)
);
CardHeader.displayName = "CardHeader";
const CardTitle = React.forwardRef<HTMLParagraphElement, React.HTMLAttributes<HTMLHeadingElement>>(
({ className, ...props }, ref) => (
<h3 ref={ref} className={cn("text-lg font-semibold leading-none tracking-tight", className)} {...props} />
)
);
CardTitle.displayName = "CardTitle";
const CardDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => (
<p ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
));
CardDescription.displayName = "CardDescription";
const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
)
);
CardContent.displayName = "CardContent";
const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
)
);
CardFooter.displayName = "CardFooter";
export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter };

View File

@@ -0,0 +1,26 @@
import * as React from "react";
import * as CheckboxPrimitive from "@radix-ui/react-checkbox";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
>
<CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
<Check className="h-3.5 w-3.5" />
</CheckboxPrimitive.Indicator>
</CheckboxPrimitive.Root>
));
Checkbox.displayName = CheckboxPrimitive.Root.displayName;
export { Checkbox };

View File

@@ -0,0 +1,161 @@
"use client";
import * as React from "react";
import { CalendarIcon } from "lucide-react";
import { format, parse, isValid } from "date-fns";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Calendar } from "@/components/ui/calendar";
import { Input } from "@/components/ui/input";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
interface DateTimePickerProps {
value?: Date;
onChange?: (date: Date | undefined) => void;
placeholder?: string;
disabled?: boolean;
className?: string;
}
function DateTimePicker({
value,
onChange,
placeholder = "选择日期和时间",
disabled = false,
className,
}: DateTimePickerProps) {
const [open, setOpen] = React.useState(false);
// 获取初始默认时间
const getDefaultDate = React.useCallback(() => {
const now = new Date();
now.setSeconds(0);
now.setMilliseconds(0);
return now;
}, []);
const [selectedDate, setSelectedDate] = React.useState<Date | undefined>(() => {
return value ?? getDefaultDate();
});
const [inputValue, setInputValue] = React.useState(() => {
return format(value ?? getDefaultDate(), "yyyy-MM-dd HH:mm");
});
// 组件挂载时,如果没有外部值,设置当前时间为默认值
const initialized = React.useRef(false);
React.useEffect(() => {
if (!initialized.current && !value && onChange) {
initialized.current = true;
const defaultDate = getDefaultDate();
onChange(defaultDate);
}
}, [value, onChange, getDefaultDate]);
// Sync with external value
React.useEffect(() => {
if (value) {
setSelectedDate(value);
setInputValue(format(value, "yyyy-MM-dd HH:mm"));
}
}, [value]);
const handleDateSelect = (date: Date | undefined) => {
setSelectedDate(date);
if (date && onChange) {
const newDate = new Date(date);
// 如果已有时间值,保留原来的时分;否则使用当前时间
if (value) {
newDate.setHours(value.getHours());
newDate.setMinutes(value.getMinutes());
} else {
const now = new Date();
newDate.setHours(now.getHours());
newDate.setMinutes(now.getMinutes());
}
newDate.setSeconds(0);
newDate.setMilliseconds(0);
onChange(newDate);
}
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
setInputValue(newValue);
};
const handleInputBlur = () => {
if (!inputValue.trim()) {
onChange?.(undefined);
setSelectedDate(undefined);
return;
}
// Try to parse the input value with time
const parsed = parse(inputValue, "yyyy-MM-dd HH:mm", new Date());
if (isValid(parsed)) {
setSelectedDate(parsed);
parsed.setSeconds(0);
parsed.setMilliseconds(0);
onChange?.(parsed);
} else {
// If invalid, reset to the current value
if (value) {
setInputValue(format(value, "yyyy-MM-dd HH:mm"));
} else {
setInputValue("");
}
}
};
return (
<div className={cn("relative flex items-center", className)}>
<Input
type="text"
value={inputValue}
onChange={handleInputChange}
onBlur={handleInputBlur}
placeholder={placeholder}
disabled={disabled}
className="pr-10"
/>
<Popover open={open} onOpenChange={setOpen} modal={true}>
<PopoverTrigger asChild>
<Button
type="button"
variant="ghost"
size="icon"
disabled={disabled}
className="absolute right-0 h-full px-3 hover:bg-transparent"
>
<CalendarIcon className="h-4 w-4 text-slate-500" />
</Button>
</PopoverTrigger>
<PopoverContent
className="w-auto p-0"
align="end"
onOpenAutoFocus={(e) => e.preventDefault()}
onCloseAutoFocus={(e) => e.preventDefault()}
>
<div
onClick={(e) => {
// 阻止点击事件冒泡到 Dialog
e.stopPropagation();
}}
onPointerDown={(e) => {
// 阻止指针按下事件冒泡
e.stopPropagation();
}}
>
<Calendar
mode="single"
selected={selectedDate}
onSelect={handleDateSelect}
/>
</div>
</PopoverContent>
</Popover>
</div>
);
}
export { DateTimePicker };

View File

@@ -0,0 +1,104 @@
"use client";
import * as React from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";
const Dialog = DialogPrimitive.Root;
const DialogTrigger = DialogPrimitive.Trigger;
const DialogPortal = DialogPrimitive.Portal;
const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Overlay>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Overlay
ref={ref}
className={cn(
"fixed inset-0 z-50 bg-black/50 backdrop-blur-sm data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
className
)}
{...props}
/>
));
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
<DialogPortal>
<DialogOverlay />
<DialogPrimitive.Content
ref={ref}
className={cn(
"fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 bg-white p-6 shadow-xl duration-200 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-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-xl",
className
)}
{...props}
>
{children}
<DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-slate-950 focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-slate-100 data-[state=open]:text-slate-500">
<X className="h-4 w-4" />
<span className="sr-only">Close</span>
</DialogPrimitive.Close>
</DialogPrimitive.Content>
</DialogPortal>
));
DialogContent.displayName = DialogPrimitive.Content.displayName;
const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)} {...props} />
);
DialogHeader.displayName = "DialogHeader";
const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
<div
className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
{...props}
/>
);
DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Title>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Title
ref={ref}
className={cn("text-lg font-semibold leading-none tracking-tight text-slate-900", className)}
{...props}
/>
));
DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
React.ElementRef<typeof DialogPrimitive.Description>,
React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
<DialogPrimitive.Description
ref={ref}
className={cn("text-sm text-slate-500", className)}
{...props}
/>
));
DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
Dialog,
DialogPortal,
DialogOverlay,
DialogTrigger,
DialogClose,
DialogContent,
DialogHeader,
DialogFooter,
DialogTitle,
DialogDescription,
};

View File

@@ -0,0 +1,244 @@
"use client"
import { useMemo } from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
import { Separator } from "@/components/ui/separator"
function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) {
return (
<fieldset
data-slot="field-set"
className={cn(
"flex flex-col gap-6",
"has-[>[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3",
className
)}
{...props}
/>
)
}
function FieldLegend({
className,
variant = "legend",
...props
}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) {
return (
<legend
data-slot="field-legend"
data-variant={variant}
className={cn(
"mb-3 font-medium",
"data-[variant=legend]:text-base",
"data-[variant=label]:text-sm",
className
)}
{...props}
/>
)
}
function FieldGroup({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-group"
className={cn(
"group/field-group @container/field-group flex w-full flex-col gap-7 data-[slot=checkbox-group]:gap-3 [&>[data-slot=field-group]]:gap-4",
className
)}
{...props}
/>
)
}
const fieldVariants = cva(
"group/field data-[invalid=true]:text-destructive flex w-full gap-3",
{
variants: {
orientation: {
vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"],
horizontal: [
"flex-row items-center",
"[&>[data-slot=field-label]]:flex-auto",
"has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px has-[>[data-slot=field-content]]:items-start",
],
responsive: [
"@md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto flex-col [&>*]:w-full [&>.sr-only]:w-auto",
"@md/field-group:[&>[data-slot=field-label]]:flex-auto",
"@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
],
},
},
defaultVariants: {
orientation: "vertical",
},
}
)
function Field({
className,
orientation = "vertical",
...props
}: React.ComponentProps<"div"> & VariantProps<typeof fieldVariants>) {
return (
<div
role="group"
data-slot="field"
data-orientation={orientation}
className={cn(fieldVariants({ orientation }), className)}
{...props}
/>
)
}
function FieldContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-content"
className={cn(
"group/field-content flex flex-1 flex-col gap-1.5 leading-snug",
className
)}
{...props}
/>
)
}
function FieldLabel({
className,
...props
}: React.ComponentProps<typeof Label>) {
return (
<Label
data-slot="field-label"
className={cn(
"group/field-label peer/field-label flex w-fit gap-2 leading-snug group-data-[disabled=true]/field:opacity-50",
"has-[>[data-slot=field]]:w-full has-[>[data-slot=field]]:flex-col has-[>[data-slot=field]]:rounded-md has-[>[data-slot=field]]:border [&>[data-slot=field]]:p-4",
"has-data-[state=checked]:bg-primary/5 has-data-[state=checked]:border-primary dark:has-data-[state=checked]:bg-primary/10",
className
)}
{...props}
/>
)
}
function FieldTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="field-label"
className={cn(
"flex w-fit items-center gap-2 text-sm font-medium leading-snug group-data-[disabled=true]/field:opacity-50",
className
)}
{...props}
/>
)
}
function FieldDescription({ className, ...props }: React.ComponentProps<"p">) {
return (
<p
data-slot="field-description"
className={cn(
"text-muted-foreground text-sm font-normal leading-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
"nth-last-2:-mt-1 last:mt-0 [[data-variant=legend]+&]:-mt-1.5",
"[&>a:hover]:text-primary [&>a]:underline [&>a]:underline-offset-4",
className
)}
{...props}
/>
)
}
function FieldSeparator({
children,
className,
...props
}: React.ComponentProps<"div"> & {
children?: React.ReactNode
}) {
return (
<div
data-slot="field-separator"
data-content={!!children}
className={cn(
"relative -my-2 h-5 text-sm group-data-[variant=outline]/field-group:-mb-2",
className
)}
{...props}
>
<Separator className="absolute inset-0 top-1/2" />
{children && (
<span
className="bg-background text-muted-foreground relative mx-auto block w-fit px-2"
data-slot="field-separator-content"
>
{children}
</span>
)}
</div>
)
}
function FieldError({
className,
children,
errors,
...props
}: React.ComponentProps<"div"> & {
errors?: Array<{ message?: string } | undefined>
}) {
const content = useMemo(() => {
if (children) {
return children
}
if (!errors) {
return null
}
if (errors?.length === 1 && errors[0]?.message) {
return errors[0].message
}
return (
<ul className="ml-4 flex list-disc flex-col gap-1">
{errors.map(
(error, index) =>
error?.message && <li key={index}>{error.message}</li>
)}
</ul>
)
}, [children, errors])
if (!content) {
return null
}
return (
<div
role="alert"
data-slot="field-error"
className={cn("text-destructive text-sm font-normal", className)}
{...props}
>
{content}
</div>
)
}
export {
Field,
FieldLabel,
FieldDescription,
FieldError,
FieldGroup,
FieldLegend,
FieldSeparator,
FieldSet,
FieldContent,
FieldTitle,
}

View File

@@ -0,0 +1,178 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { Slot } from "@radix-ui/react-slot"
import {
Controller,
FormProvider,
useFormContext,
type ControllerProps,
type FieldPath,
type FieldValues,
} from "react-hook-form"
import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"
const Form = FormProvider
type FormFieldContextValue<
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
> = {
name: TName
}
const FormFieldContext = React.createContext<FormFieldContextValue | null>(null)
const FormField = <
TFieldValues extends FieldValues = FieldValues,
TName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>
>({
...props
}: ControllerProps<TFieldValues, TName>) => {
return (
<FormFieldContext.Provider value={{ name: props.name }}>
<Controller {...props} />
</FormFieldContext.Provider>
)
}
const useFormField = () => {
const fieldContext = React.useContext(FormFieldContext)
const itemContext = React.useContext(FormItemContext)
const { getFieldState, formState } = useFormContext()
if (!fieldContext) {
throw new Error("useFormField should be used within <FormField>")
}
if (!itemContext) {
throw new Error("useFormField should be used within <FormItem>")
}
const fieldState = getFieldState(fieldContext.name, formState)
const { id } = itemContext
return {
id,
name: fieldContext.name,
formItemId: `${id}-form-item`,
formDescriptionId: `${id}-form-item-description`,
formMessageId: `${id}-form-item-message`,
...fieldState,
}
}
type FormItemContextValue = {
id: string
}
const FormItemContext = React.createContext<FormItemContextValue | null>(null)
const FormItem = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement>
>(({ className, ...props }, ref) => {
const id = React.useId()
return (
<FormItemContext.Provider value={{ id }}>
<div ref={ref} className={cn("space-y-2", className)} {...props} />
</FormItemContext.Provider>
)
})
FormItem.displayName = "FormItem"
const FormLabel = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root>
>(({ className, ...props }, ref) => {
const { error, formItemId } = useFormField()
return (
<Label
ref={ref}
className={cn(error && "text-destructive", className)}
htmlFor={formItemId}
{...props}
/>
)
})
FormLabel.displayName = "FormLabel"
const FormControl = React.forwardRef<
React.ElementRef<typeof Slot>,
React.ComponentPropsWithoutRef<typeof Slot>
>(({ ...props }, ref) => {
const { error, formItemId, formDescriptionId, formMessageId } = useFormField()
return (
<Slot
ref={ref}
id={formItemId}
aria-describedby={
!error
? `${formDescriptionId}`
: `${formDescriptionId} ${formMessageId}`
}
aria-invalid={!!error}
{...props}
/>
)
})
FormControl.displayName = "FormControl"
const FormDescription = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, ...props }, ref) => {
const { formDescriptionId } = useFormField()
return (
<p
ref={ref}
id={formDescriptionId}
className={cn("text-[0.8rem] text-muted-foreground", className)}
{...props}
/>
)
})
FormDescription.displayName = "FormDescription"
const FormMessage = React.forwardRef<
HTMLParagraphElement,
React.HTMLAttributes<HTMLParagraphElement>
>(({ className, children, ...props }, ref) => {
const { error, formMessageId } = useFormField()
const body = error ? String(error?.message ?? "") : children
if (!body) {
return null
}
return (
<p
ref={ref}
id={formMessageId}
className={cn("text-[0.8rem] font-medium text-destructive", className)}
{...props}
>
{body}
</p>
)
})
FormMessage.displayName = "FormMessage"
export {
useFormField,
Form,
FormItem,
FormLabel,
FormControl,
FormDescription,
FormMessage,
FormField,
}

View File

@@ -0,0 +1,22 @@
import * as React from "react";
import { cn } from "@/lib/utils";
const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, type, ...props }, ref) => {
return (
<input
type={type}
className={cn(
"flex h-10 w-full rounded-lg border border-input/60 bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/30 disabled:cursor-not-allowed disabled:opacity-50",
className
)}
ref={ref}
{...props}
/>
);
}
);
Input.displayName = "Input";
export { Input };

View File

@@ -0,0 +1,26 @@
"use client"
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva, type VariantProps } from "class-variance-authority"
import { cn } from "@/lib/utils"
const labelVariants = cva(
"text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)
const Label = React.forwardRef<
React.ElementRef<typeof LabelPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof LabelPrimitive.Root> &
VariantProps<typeof labelVariants>
>(({ className, ...props }, ref) => (
<LabelPrimitive.Root
ref={ref}
className={cn(labelVariants(), className)}
{...props}
/>
))
Label.displayName = LabelPrimitive.Root.displayName
export { Label }

View File

@@ -0,0 +1,33 @@
"use client"
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"
import { cn } from "@/lib/utils"
const Popover = PopoverPrimitive.Root
const PopoverTrigger = PopoverPrimitive.Trigger
const PopoverAnchor = PopoverPrimitive.Anchor
const PopoverContent = React.forwardRef<
React.ElementRef<typeof PopoverPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof PopoverPrimitive.Content>
>(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
<PopoverPrimitive.Portal>
<PopoverPrimitive.Content
ref={ref}
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none 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 origin-[--radix-popover-content-transform-origin]",
className
)}
{...props}
/>
</PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName
export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

View File

@@ -0,0 +1,318 @@
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
import { useI18n, type TranslationKey } from "@/lib/i18n";
export type RecurrenceMode = "daily" | "weekly" | "biweekly" | "monthly" | "yearly";
export type RecurrenceRule = {
type: "hourly" | "daily" | "weekly" | "monthly" | "yearly";
interval?: number;
byWeekday?: number;
byMonthday?: number;
};
interface RecurrencePickerProps {
value?: RecurrenceRule;
onChange?: (rule: RecurrenceRule) => void;
dueDate?: Date;
className?: string;
}
const WEEKDAYS = [
{ value: 0, labelKey: "sun" },
{ value: 1, labelKey: "mon" },
{ value: 2, labelKey: "tue" },
{ value: 3, labelKey: "wed" },
{ value: 4, labelKey: "thu" },
{ value: 5, labelKey: "fri" },
{ value: 6, labelKey: "sat" },
] as const;
const MONTHS = [
{ value: 1, labelKey: "jan" },
{ value: 2, labelKey: "feb" },
{ value: 3, labelKey: "mar" },
{ value: 4, labelKey: "apr" },
{ value: 5, labelKey: "may" },
{ value: 6, labelKey: "jun" },
{ value: 7, labelKey: "jul" },
{ value: 8, labelKey: "aug" },
{ value: 9, labelKey: "sep" },
{ value: 10, labelKey: "oct" },
{ value: 11, labelKey: "nov" },
{ value: 12, labelKey: "dec" },
] as const;
export function RecurrencePicker({
value,
onChange,
dueDate,
className,
}: RecurrencePickerProps) {
const { t } = useI18n();
// Derive mode from value
const getMode = (): RecurrenceMode => {
if (!value) return "daily";
if (value.type === "weekly" && value.interval === 2) return "biweekly";
if (value.type === "weekly") return "weekly";
if (value.type === "monthly") return "monthly";
if (value.type === "yearly") return "yearly";
return "daily";
};
const [mode, setMode] = React.useState<RecurrenceMode>(getMode);
const [selectedWeekday, setSelectedWeekday] = React.useState<number>(
value?.byWeekday ?? (dueDate ? dueDate.getDay() : new Date().getDay())
);
const [selectedMonthday, setSelectedMonthday] = React.useState<number>(
value?.byMonthday ?? (dueDate ? dueDate.getDate() : new Date().getDate())
);
const [selectedMonth, setSelectedMonth] = React.useState<number>(
dueDate ? dueDate.getMonth() + 1 : new Date().getMonth() + 1
);
const [selectedYearDay, setSelectedYearDay] = React.useState<number>(
dueDate ? dueDate.getDate() : new Date().getDate()
);
// Sync internal state when value changes from parent
React.useEffect(() => {
setMode(getMode());
if (value?.byWeekday !== undefined) {
setSelectedWeekday(value.byWeekday);
}
if (value?.byMonthday !== undefined) {
setSelectedMonthday(value.byMonthday);
setSelectedYearDay(value.byMonthday);
}
}, [value]);
// Build rule and call onChange
const buildRule = React.useCallback((
newMode: RecurrenceMode,
weekday: number,
monthday: number,
month: number,
yearDay: number
): RecurrenceRule => {
switch (newMode) {
case "daily":
return { type: "daily", interval: 1 };
case "weekly":
return { type: "weekly", interval: 1, byWeekday: weekday };
case "biweekly":
return { type: "weekly", interval: 2, byWeekday: weekday };
case "monthly":
return { type: "monthly", interval: 1, byMonthday: monthday };
case "yearly":
// For yearly, we store the day in byMonthday
// The month is derived from the dueDate which user sets separately
return { type: "yearly", interval: 1, byMonthday: yearDay };
default:
return { type: "daily", interval: 1 };
}
}, []);
const handleModeChange = (newMode: RecurrenceMode) => {
setMode(newMode);
onChange?.(buildRule(newMode, selectedWeekday, selectedMonthday, selectedMonth, selectedYearDay));
};
const handleWeekdayChange = (weekday: number) => {
setSelectedWeekday(weekday);
onChange?.(buildRule(mode, weekday, selectedMonthday, selectedMonth, selectedYearDay));
};
const handleMonthdayChange = (day: number) => {
setSelectedMonthday(day);
onChange?.(buildRule(mode, selectedWeekday, day, selectedMonth, selectedYearDay));
};
const handleYearDayChange = (day: number) => {
setSelectedYearDay(day);
onChange?.(buildRule(mode, selectedWeekday, selectedMonthday, selectedMonth, day));
};
const handleMonthChange = (month: number) => {
setSelectedMonth(month);
// When month changes, also update yearDay if it exceeds the month's days
const maxDays = getDaysInMonth(month);
const newDay = Math.min(selectedYearDay, maxDays);
setSelectedYearDay(newDay);
onChange?.(buildRule(mode, selectedWeekday, selectedMonthday, month, newDay));
};
// Get days in a specific month (for year 2024 as reference)
const getDaysInMonth = (month: number): number => {
const daysInMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return daysInMonth[month - 1] || 31;
};
// Generate preview text
const getPreviewText = (): string => {
const time = dueDate
? `${dueDate.getHours().toString().padStart(2, "0")}:${dueDate.getMinutes().toString().padStart(2, "0")}`
: "";
switch (mode) {
case "daily":
return t("recurrencePreviewDaily" as TranslationKey, { time });
case "weekly":
return t("recurrencePreviewWeekly" as TranslationKey, {
weekday: t(WEEKDAYS[selectedWeekday].labelKey as TranslationKey),
time
});
case "biweekly":
return t("recurrencePreviewBiweekly" as TranslationKey, {
weekday: t(WEEKDAYS[selectedWeekday].labelKey as TranslationKey),
time
});
case "monthly":
return t("recurrencePreviewMonthly" as TranslationKey, { day: selectedMonthday, time });
case "yearly":
return t("recurrencePreviewYearly" as TranslationKey, {
month: t(MONTHS[selectedMonth - 1].labelKey as TranslationKey),
day: selectedYearDay,
time
});
default:
return "";
}
};
const modes: { value: RecurrenceMode; labelKey: string }[] = [
{ value: "daily", labelKey: "modeDaily" },
{ value: "weekly", labelKey: "modeWeekly" },
{ value: "biweekly", labelKey: "modeBiweekly" },
{ value: "monthly", labelKey: "modeMonthly" },
{ value: "yearly", labelKey: "modeYearly" },
];
return (
<div className={cn("space-y-4", className)}>
{/* Mode Selector - Segmented Control */}
<div className="flex rounded-lg bg-slate-100/80 p-1">
{modes.map((m) => (
<button
key={m.value}
type="button"
onClick={() => handleModeChange(m.value)}
className={cn(
"flex-1 rounded-md px-2 py-1.5 text-xs font-medium transition-all",
mode === m.value
? "bg-white text-slate-900 shadow-sm"
: "text-slate-600 hover:text-slate-900"
)}
>
{t(m.labelKey as TranslationKey)}
</button>
))}
</div>
{/* Mode-specific Options */}
<div className="min-h-[60px]">
{/* Weekly / Biweekly - Weekday Selector */}
{(mode === "weekly" || mode === "biweekly") && (
<div className="space-y-2">
<label className="text-xs font-medium text-slate-500">
{t("selectWeekday")}
</label>
<div className="flex gap-1.5">
{WEEKDAYS.map((day) => (
<button
key={day.value}
type="button"
onClick={() => handleWeekdayChange(day.value)}
className={cn(
"flex h-8 w-8 items-center justify-center rounded-full text-xs font-medium transition-all",
selectedWeekday === day.value
? "bg-blue-500 text-white shadow-sm"
: "bg-slate-100 text-slate-600 hover:bg-slate-200"
)}
>
{t(day.labelKey as TranslationKey)}
</button>
))}
</div>
</div>
)}
{/* Monthly - Day of Month Selector */}
{mode === "monthly" && (
<div className="space-y-2">
<label className="text-xs font-medium text-slate-500">
{t("selectMonthday")}
</label>
<div className="flex items-center gap-2">
<span className="text-sm text-slate-600">{t("everyMonth")}</span>
<select
value={selectedMonthday}
onChange={(e) => handleMonthdayChange(Number(e.target.value))}
className="h-9 rounded-lg border border-slate-200/60 bg-white px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
>
{Array.from({ length: 31 }, (_, i) => i + 1).map((day) => (
<option key={day} value={day}>
{day}
</option>
))}
</select>
<span className="text-sm text-slate-600">{t("dayUnit")}</span>
</div>
</div>
)}
{/* Yearly - Month and Day Selector */}
{mode === "yearly" && (
<div className="space-y-2">
<label className="text-xs font-medium text-slate-500">
{t("selectYearlyDate")}
</label>
<div className="flex items-center gap-2">
<span className="text-sm text-slate-600">{t("everyYear")}</span>
<select
value={selectedMonth}
onChange={(e) => handleMonthChange(Number(e.target.value))}
className="h-9 rounded-lg border border-slate-200/60 bg-white px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
>
{MONTHS.map((month) => (
<option key={month.value} value={month.value}>
{t(month.labelKey as TranslationKey)}
</option>
))}
</select>
<select
value={selectedYearDay}
onChange={(e) => handleYearDayChange(Number(e.target.value))}
className="h-9 rounded-lg border border-slate-200/60 bg-white px-3 text-sm focus:outline-none focus:ring-2 focus:ring-primary/30"
>
{Array.from({ length: getDaysInMonth(selectedMonth) }, (_, i) => i + 1).map((day) => (
<option key={day} value={day}>
{day}
</option>
))}
</select>
<span className="text-sm text-slate-600">{t("dayUnit")}</span>
</div>
</div>
)}
{/* Daily - No additional options needed */}
{mode === "daily" && (
<div className="flex items-center justify-center py-2 text-sm text-slate-500">
{t("dailyNoOptions")}
</div>
)}
</div>
{/* Preview */}
<div className="rounded-lg bg-blue-50 px-3 py-2">
<div className="flex items-center gap-2">
<span className="text-xs font-medium text-blue-600/70">{t("willRepeat")}</span>
<span className="text-sm font-medium text-blue-600">{getPreviewText()}</span>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,48 @@
"use client"
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"
import { cn } from "@/lib/utils"
const ScrollArea = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.Root>
>(({ className, children, ...props }, ref) => (
<ScrollAreaPrimitive.Root
ref={ref}
className={cn("relative overflow-hidden", className)}
{...props}
>
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
{children}
</ScrollAreaPrimitive.Viewport>
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName
const ScrollBar = React.forwardRef<
React.ElementRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>,
React.ComponentPropsWithoutRef<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>
>(({ className, orientation = "vertical", ...props }, ref) => (
<ScrollAreaPrimitive.ScrollAreaScrollbar
ref={ref}
orientation={orientation}
className={cn(
"flex touch-none select-none transition-colors",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent p-[1px]",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent p-[1px]",
className
)}
{...props}
>
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
</ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName
export { ScrollArea, ScrollBar }

View File

@@ -0,0 +1,159 @@
"use client";
import * as React from "react";
import * as SelectPrimitive from "@radix-ui/react-select";
import { Check, ChevronDown, ChevronUp } from "lucide-react";
import { cn } from "@/lib/utils";
const Select = SelectPrimitive.Root;
const SelectGroup = SelectPrimitive.Group;
const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Trigger>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-9 w-full items-center justify-between whitespace-nowrap rounded-lg border border-slate-200/60 bg-transparent px-3 py-2 text-sm ring-offset-white placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-primary/30 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
>
{children}
<SelectPrimitive.Icon asChild>
<ChevronDown className="h-4 w-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
));
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollUpButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronUp className="h-4 w-4" />
</SelectPrimitive.ScrollUpButton>
));
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
<SelectPrimitive.ScrollDownButton
ref={ref}
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
{...props}
>
<ChevronDown className="h-4 w-4" />
</SelectPrimitive.ScrollDownButton>
));
SelectScrollDownButton.displayName =
SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Content>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
<SelectPrimitive.Portal>
<SelectPrimitive.Content
ref={ref}
className={cn(
"relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-lg bg-white text-slate-950 shadow-lg 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",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
)}
position={position}
{...props}
>
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
)}
>
{children}
</SelectPrimitive.Viewport>
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
));
SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Label>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Label
ref={ref}
className={cn("px-2 py-1.5 text-sm font-semibold", className)}
{...props}
/>
));
SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Item>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
<SelectPrimitive.Item
ref={ref}
className={cn(
"relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-slate-100 focus:text-slate-900 data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
className
)}
{...props}
>
<span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
<SelectPrimitive.ItemIndicator>
<Check className="h-4 w-4" />
</SelectPrimitive.ItemIndicator>
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
));
SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
React.ElementRef<typeof SelectPrimitive.Separator>,
React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
className={cn("-mx-1 my-1 h-px bg-slate-100", className)}
{...props}
/>
));
SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
Select,
SelectGroup,
SelectValue,
SelectTrigger,
SelectContent,
SelectLabel,
SelectItem,
SelectSeparator,
SelectScrollUpButton,
SelectScrollDownButton,
};

View File

@@ -0,0 +1,31 @@
"use client"
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import { cn } from "@/lib/utils"
const Separator = React.forwardRef<
React.ElementRef<typeof SeparatorPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
>(
(
{ className, orientation = "horizontal", decorative = true, ...props },
ref
) => (
<SeparatorPrimitive.Root
ref={ref}
decorative={decorative}
orientation={orientation}
className={cn(
"shrink-0 bg-border",
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
className
)}
{...props}
/>
)
)
Separator.displayName = SeparatorPrimitive.Root.displayName
export { Separator }

View File

@@ -0,0 +1,222 @@
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";
type SidebarContextValue = {
open: boolean;
setOpen: (value: boolean) => void;
toggle: () => void;
};
const SidebarContext = React.createContext<SidebarContextValue | null>(null);
const useSidebar = () => {
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.");
}
return context;
};
const SidebarProvider = ({
children,
defaultOpen = true,
}: {
children: React.ReactNode;
defaultOpen?: boolean;
}) => {
const [open, setOpen] = React.useState(defaultOpen);
const toggle = React.useCallback(() => setOpen((prev) => !prev), []);
return (
<SidebarContext.Provider value={{ open, setOpen, toggle }}>
{children}
</SidebarContext.Provider>
);
};
const sidebarVariants = cva(
"group/sidebar relative flex h-full flex-col bg-sidebar text-sidebar-foreground transition-all duration-200",
{
variants: {
variant: {
sidebar: "w-[--sidebar-width] data-[state=collapsed]:w-[--sidebar-width-collapsed]",
inset:
"w-[--sidebar-width] rounded-2xl shadow-sm data-[state=collapsed]:w-[--sidebar-width-collapsed]",
floating:
"w-[--sidebar-width] rounded-2xl shadow-md data-[state=collapsed]:w-[--sidebar-width-collapsed]",
},
},
defaultVariants: {
variant: "sidebar",
},
}
);
const Sidebar = React.forwardRef<
HTMLDivElement,
React.HTMLAttributes<HTMLDivElement> & VariantProps<typeof sidebarVariants>
>(({ className, variant, style, ...props }, ref) => {
const { open } = useSidebar();
return (
<div
ref={ref}
className={cn(sidebarVariants({ variant }), className)}
data-state={open ? "expanded" : "collapsed"}
style={
{
"--sidebar-width": "16rem",
"--sidebar-width-collapsed": "4.25rem",
...style,
} as React.CSSProperties
}
{...props}
/>
);
});
Sidebar.displayName = "Sidebar";
const SidebarInset = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("min-h-screen flex-1", className)} {...props} />
)
);
SidebarInset.displayName = "SidebarInset";
const SidebarHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex h-14 items-center px-4", className)} {...props} />
)
);
SidebarHeader.displayName = "SidebarHeader";
const SidebarContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("flex-1 overflow-auto p-2", className)} {...props} />
)
);
SidebarContent.displayName = "SidebarContent";
const SidebarFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("p-2", className)} {...props} />
)
);
SidebarFooter.displayName = "SidebarFooter";
const SidebarGroup = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("space-y-2 px-2 py-2", className)} {...props} />
)
);
SidebarGroup.displayName = "SidebarGroup";
const SidebarGroupLabel = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div
ref={ref}
className={cn("px-2 text-xs font-medium uppercase text-sidebar-foreground/60", className)}
{...props}
/>
)
);
SidebarGroupLabel.displayName = "SidebarGroupLabel";
const SidebarGroupContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("space-y-1", className)} {...props} />
)
);
SidebarGroupContent.displayName = "SidebarGroupContent";
const SidebarMenu = React.forwardRef<HTMLUListElement, React.HTMLAttributes<HTMLUListElement>>(
({ className, ...props }, ref) => (
<ul ref={ref} className={cn("space-y-1", className)} {...props} />
)
);
SidebarMenu.displayName = "SidebarMenu";
const SidebarMenuItem = React.forwardRef<HTMLLIElement, React.HTMLAttributes<HTMLLIElement>>(
({ className, ...props }, ref) => (
<li ref={ref} className={cn("list-none", className)} {...props} />
)
);
SidebarMenuItem.displayName = "SidebarMenuItem";
const sidebarMenuButtonVariants = cva(
"flex w-full items-center gap-2 rounded-lg px-3 py-2 text-sm font-medium text-sidebar-foreground transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
{
variants: {
isActive: {
true: "bg-sidebar-accent text-sidebar-primary font-semibold",
false: "",
},
},
defaultVariants: {
isActive: false,
},
}
);
const SidebarMenuButton = React.forwardRef<
HTMLButtonElement,
React.ButtonHTMLAttributes<HTMLButtonElement> &
VariantProps<typeof sidebarMenuButtonVariants> & { asChild?: boolean }
>(({ className, isActive, asChild = false, ...props }, ref) => {
const Comp = asChild ? Slot : "button";
return (
<Comp
ref={ref}
className={cn(sidebarMenuButtonVariants({ isActive }), className)}
{...props}
/>
);
});
SidebarMenuButton.displayName = "SidebarMenuButton";
const SidebarSeparator = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => (
<div ref={ref} className={cn("mx-3 my-2 h-px bg-sidebar-border/50", className)} {...props} />
)
);
SidebarSeparator.displayName = "SidebarSeparator";
const SidebarTrigger = React.forwardRef<HTMLButtonElement, React.HTMLAttributes<HTMLButtonElement>>(
({ className, children, ...props }, ref) => {
const { toggle } = useSidebar();
return (
<button
ref={ref}
type="button"
className={cn(
"inline-flex h-10 w-10 items-center justify-center rounded-md border bg-background text-foreground shadow-sm transition-colors hover:bg-accent",
className
)}
onClick={toggle}
{...props}
>
{children}
</button>
);
}
);
SidebarTrigger.displayName = "SidebarTrigger";
export {
SidebarProvider,
Sidebar,
SidebarInset,
SidebarHeader,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarGroupLabel,
SidebarGroupContent,
SidebarMenu,
SidebarMenuItem,
SidebarMenuButton,
SidebarSeparator,
SidebarTrigger,
useSidebar,
};

View File

@@ -0,0 +1,31 @@
"use client"
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"
type ToasterProps = React.ComponentProps<typeof Sonner>
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = "system" } = useTheme()
return (
<Sonner
theme={theme as ToasterProps["theme"]}
className="toaster group"
toastOptions={{
classNames: {
toast:
"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
description: "group-[.toast]:text-muted-foreground",
actionButton:
"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
cancelButton:
"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
},
}}
{...props}
/>
)
}
export { Toaster }

View File

@@ -0,0 +1,64 @@
"use client";
import { useEffect, useState } from "react";
import AppShell from "@/components/AppShell";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { api } from "@/lib/api";
type User = { id: string; username: string };
const UsersPage = () => {
const [users, setUsers] = useState<User[]>([]);
const [query, setQuery] = useState("");
const search = async () => {
const data = (await api.getUsers(query)) as User[];
setUsers(data);
};
useEffect(() => {
search().catch(() => null);
}, []);
return (
<AppShell>
<Card className="border-slate-200/80 shadow-sm">
<CardHeader className="gap-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<CardTitle></CardTitle>
<CardDescription></CardDescription>
</div>
<div className="flex w-full flex-col gap-2 sm:w-auto sm:flex-row">
<Input
placeholder="搜索用户名"
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
<Button onClick={search}></Button>
</div>
</CardHeader>
<CardContent>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{users.map((user) => (
<Card key={user.id} className="border-slate-200/70 bg-white/70 shadow-sm">
<CardContent className="p-4 font-medium text-slate-700">
{user.username}
</CardContent>
</Card>
))}
{users.length === 0 && (
<div className="rounded-xl border border-dashed border-slate-200 bg-white/60 p-6 text-center text-sm text-slate-500">
</div>
)}
</div>
</CardContent>
</Card>
</AppShell>
);
};
export default UsersPage;