Initial release
This commit is contained in:
commit
721217a8e3
130 files changed
+7099
No files matched your search
@@ -0,0 +1,37 @@
|
||||
import React from "react"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "../ui/card"
|
||||
|
||||
interface CustomCardProps {
|
||||
title?: string
|
||||
description?: string
|
||||
footer?: string | React.ReactNode
|
||||
children: React.ReactNode
|
||||
[key: string]: any
|
||||
}
|
||||
|
||||
export function CustomCard({
|
||||
title,
|
||||
description,
|
||||
footer,
|
||||
children,
|
||||
...props
|
||||
}: CustomCardProps) {
|
||||
const { className } = props
|
||||
return (
|
||||
<Card className={`w-full ${className}`}>
|
||||
<CardHeader className="space-y-2">
|
||||
<CardTitle className="text-2xl">{title}</CardTitle>
|
||||
<CardDescription>{description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>{children}</CardContent>
|
||||
<CardFooter className="flex justify-center">{footer}</CardFooter>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "./custom.card"
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Link } from "react-router"
|
||||
import { ThemeToggle, UserMenu } from "@/components/layout"
|
||||
|
||||
export function Header() {
|
||||
return (
|
||||
<header className="border-border border-b bg-card">
|
||||
<div className="mx-auto flex max-w-6xl items-center justify-between px-6 py-4">
|
||||
<h1 className="font-semibold text-xl">
|
||||
<Link to="/">URL Shortener</Link>
|
||||
</h1>
|
||||
<div className="flex items-center gap-2">
|
||||
<ThemeToggle />
|
||||
<UserMenu />
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { Header } from "./header"
|
||||
export { ThemeToggle } from "./theme.toggle"
|
||||
export { UserMenu } from "./user.menu"
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Moon, Sun } from "lucide-react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { useTheme } from "@/context/theme.provider"
|
||||
|
||||
export function ThemeToggle() {
|
||||
const { theme, setTheme } = useTheme()
|
||||
|
||||
const toggleTheme = () => {
|
||||
setTheme(theme === "light" ? "dark" : "light")
|
||||
}
|
||||
|
||||
return (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={toggleTheme}
|
||||
title={`Switch to ${theme === "light" ? "dark" : "light"} mode`}
|
||||
>
|
||||
{theme === "light" ? (
|
||||
<Moon className="h-5 w-5" />
|
||||
) : (
|
||||
<Sun className="h-5 w-5" />
|
||||
)}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { CircleUserIcon, LogOut, User2Icon } from "lucide-react"
|
||||
import { Link } from "react-router"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu"
|
||||
|
||||
const handleLogout = () => {
|
||||
localStorage.removeItem("accessToken")
|
||||
window.location.href = "/login"
|
||||
}
|
||||
|
||||
export function UserMenu() {
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="outline">
|
||||
<CircleUserIcon />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent side="bottom" align="end" className="w-36">
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem asChild>
|
||||
<Link to={"/profile"} className="flex cursor-pointer items-center">
|
||||
<User2Icon className="mr-2" />
|
||||
Profile
|
||||
</Link>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="flex items-center">
|
||||
<button onClick={handleLogout} className="flex items-center">
|
||||
<LogOut className="mr-4" />
|
||||
Logout
|
||||
</button>
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./protected.route"
|
||||
export * from "./public.route"
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Navigate, Outlet, useLocation } from "react-router"
|
||||
import { useAuth } from "@/context/auth.context"
|
||||
import { LoaderCircle } from "lucide-react"
|
||||
|
||||
export const ProtectedRoute = () => {
|
||||
const { isAuthenticated, isLoading } = useAuth()
|
||||
const location = useLocation()
|
||||
|
||||
if (isLoading) {
|
||||
return <div className="loading-screen">
|
||||
<LoaderCircle className="loading-screen-icon" />
|
||||
</div>
|
||||
}
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return <Navigate to="/login" state={{ from: location }} replace />
|
||||
}
|
||||
|
||||
return <Outlet />
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Navigate, Outlet } from "react-router"
|
||||
import { useAuth } from "@/context/auth.context"
|
||||
import { LoaderCircle } from "lucide-react"
|
||||
|
||||
export const PublicRoute = () => {
|
||||
const { isAuthenticated, isLoading } = useAuth()
|
||||
|
||||
if (isLoading) return <div className="loading-screen">
|
||||
<LoaderCircle className="loading-screen-icon" />
|
||||
</div>
|
||||
|
||||
if (isAuthenticated) {
|
||||
return <Navigate to="/" replace />
|
||||
}
|
||||
|
||||
return <Outlet />
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
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-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground hover:bg-primary/90",
|
||||
destructive:
|
||||
"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",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-9 px-4 py-2 has-[>svg]:px-3",
|
||||
sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",
|
||||
lg: "h-10 rounded-md px-6 has-[>svg]:px-4",
|
||||
icon: "size-9",
|
||||
"icon-sm": "size-8",
|
||||
"icon-lg": "size-10",
|
||||
},
|
||||
},
|
||||
defaultVariants: {
|
||||
variant: "default",
|
||||
size: "default",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> &
|
||||
VariantProps<typeof buttonVariants> & {
|
||||
asChild?: boolean
|
||||
}) {
|
||||
const Comp = asChild ? Slot : "button"
|
||||
|
||||
return (
|
||||
<Comp
|
||||
data-slot="button"
|
||||
className={cn(buttonVariants({ variant, size, className }))}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Button, buttonVariants }
|
||||
@@ -0,0 +1,92 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Card({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card"
|
||||
className={cn(
|
||||
"bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-header"
|
||||
className={cn(
|
||||
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-title"
|
||||
className={cn("leading-none font-semibold", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-description"
|
||||
className={cn("text-muted-foreground text-sm", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-action"
|
||||
className={cn(
|
||||
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-content"
|
||||
className={cn("px-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div
|
||||
data-slot="card-footer"
|
||||
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
Card,
|
||||
CardHeader,
|
||||
CardFooter,
|
||||
CardTitle,
|
||||
CardAction,
|
||||
CardDescription,
|
||||
CardContent,
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
import * as React from "react"
|
||||
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function DropdownMenu({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
|
||||
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuPortal({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuTrigger({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Trigger
|
||||
data-slot="dropdown-menu-trigger"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuContent({
|
||||
className,
|
||||
sideOffset = 4,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Content>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Portal>
|
||||
<DropdownMenuPrimitive.Content
|
||||
data-slot="dropdown-menu-content"
|
||||
sideOffset={sideOffset}
|
||||
className={cn(
|
||||
"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 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
</DropdownMenuPrimitive.Portal>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuItem({
|
||||
className,
|
||||
inset,
|
||||
variant = "default",
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
|
||||
inset?: boolean
|
||||
variant?: "default" | "destructive"
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Item
|
||||
data-slot="dropdown-menu-item"
|
||||
data-inset={inset}
|
||||
data-variant={variant}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_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]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuCheckboxItem({
|
||||
className,
|
||||
children,
|
||||
checked,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.CheckboxItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.CheckboxItem
|
||||
data-slot="dropdown-menu-checkbox-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
checked={checked}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CheckIcon className="size-4" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.CheckboxItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioGroup({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioGroup
|
||||
data-slot="dropdown-menu-radio-group"
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuRadioItem({
|
||||
className,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioItem>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.RadioItem
|
||||
data-slot="dropdown-menu-radio-item"
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
<span className="pointer-events-none absolute left-2 flex size-3.5 items-center justify-center">
|
||||
<DropdownMenuPrimitive.ItemIndicator>
|
||||
<CircleIcon className="size-2 fill-current" />
|
||||
</DropdownMenuPrimitive.ItemIndicator>
|
||||
</span>
|
||||
{children}
|
||||
</DropdownMenuPrimitive.RadioItem>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuLabel({
|
||||
className,
|
||||
inset,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Label> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Label
|
||||
data-slot="dropdown-menu-label"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSeparator({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Separator>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.Separator
|
||||
data-slot="dropdown-menu-separator"
|
||||
className={cn("bg-border -mx-1 my-1 h-px", className)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuShortcut({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<"span">) {
|
||||
return (
|
||||
<span
|
||||
data-slot="dropdown-menu-shortcut"
|
||||
className={cn(
|
||||
"text-muted-foreground ml-auto text-xs tracking-widest",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSub({
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
|
||||
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />
|
||||
}
|
||||
|
||||
function DropdownMenuSubTrigger({
|
||||
className,
|
||||
inset,
|
||||
children,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubTrigger> & {
|
||||
inset?: boolean
|
||||
}) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubTrigger
|
||||
data-slot="dropdown-menu-sub-trigger"
|
||||
data-inset={inset}
|
||||
className={cn(
|
||||
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
<ChevronRightIcon className="ml-auto size-4" />
|
||||
</DropdownMenuPrimitive.SubTrigger>
|
||||
)
|
||||
}
|
||||
|
||||
function DropdownMenuSubContent({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof DropdownMenuPrimitive.SubContent>) {
|
||||
return (
|
||||
<DropdownMenuPrimitive.SubContent
|
||||
data-slot="dropdown-menu-sub-content"
|
||||
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 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export {
|
||||
DropdownMenu,
|
||||
DropdownMenuPortal,
|
||||
DropdownMenuTrigger,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuGroup,
|
||||
DropdownMenuLabel,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuCheckboxItem,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuShortcut,
|
||||
DropdownMenuSub,
|
||||
DropdownMenuSubTrigger,
|
||||
DropdownMenuSubContent,
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
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 flex w-full gap-3 data-[invalid=true]:text-destructive",
|
||||
{
|
||||
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]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px",
|
||||
],
|
||||
responsive: [
|
||||
"flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]: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 leading-snug font-medium 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 leading-normal font-normal group-has-[[data-orientation=horizontal]]/field:text-balance",
|
||||
"last:mt-0 nth-last-2:-mt-1 [[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?.length) {
|
||||
return null
|
||||
}
|
||||
|
||||
const uniqueErrors = [
|
||||
...new Map(errors.map((error) => [error?.message, error])).values(),
|
||||
]
|
||||
|
||||
if (uniqueErrors?.length == 1) {
|
||||
return uniqueErrors[0]?.message
|
||||
}
|
||||
|
||||
return (
|
||||
<ul className="ml-4 flex list-disc flex-col gap-1">
|
||||
{uniqueErrors.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,
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as React from "react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<input
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
|
||||
"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",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
@@ -0,0 +1,22 @@
|
||||
import * as React from "react"
|
||||
import * as LabelPrimitive from "@radix-ui/react-label"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Label({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
|
||||
return (
|
||||
<LabelPrimitive.Root
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
@@ -0,0 +1,28 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
data-slot="separator"
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Separator }
|
||||
@@ -0,0 +1,38 @@
|
||||
import {
|
||||
CircleCheckIcon,
|
||||
InfoIcon,
|
||||
Loader2Icon,
|
||||
OctagonXIcon,
|
||||
TriangleAlertIcon,
|
||||
} from "lucide-react"
|
||||
import { useTheme } from "next-themes"
|
||||
import { Toaster as Sonner, type ToasterProps } from "sonner"
|
||||
|
||||
const Toaster = ({ ...props }: ToasterProps) => {
|
||||
const { theme = "system" } = useTheme()
|
||||
|
||||
return (
|
||||
<Sonner
|
||||
theme={theme as ToasterProps["theme"]}
|
||||
className="toaster group"
|
||||
icons={{
|
||||
success: <CircleCheckIcon className="size-4" />,
|
||||
info: <InfoIcon className="size-4" />,
|
||||
warning: <TriangleAlertIcon className="size-4" />,
|
||||
error: <OctagonXIcon className="size-4" />,
|
||||
loading: <Loader2Icon className="size-4 animate-spin" />,
|
||||
}}
|
||||
style={
|
||||
{
|
||||
"--normal-bg": "var(--popover)",
|
||||
"--normal-text": "var(--popover-foreground)",
|
||||
"--normal-border": "var(--border)",
|
||||
"--border-radius": "var(--radius)",
|
||||
} as React.CSSProperties
|
||||
}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Toaster }
|
||||
@@ -0,0 +1,7 @@
|
||||
export const DOMAIN =
|
||||
import.meta.env.VITE_DOMAIN || "http://localhost:5173"
|
||||
|
||||
export const API_BASE_URL =
|
||||
import.meta.env.VITE_API_BASE_URL || "http://localhost:3000/api"
|
||||
|
||||
export const SIGNUP_ENABLED = import.meta.env.VITE_SIGNUP_ENABLED === "true"
|
||||
@@ -0,0 +1,61 @@
|
||||
import React, { createContext, useContext, useEffect, useState } from "react"
|
||||
import { loginService } from "@/features/auth/auth.api"
|
||||
import { isTokenExpired } from "@/lib/auth.utils"
|
||||
|
||||
interface AuthContextType {
|
||||
login: (creds: any) => Promise<void>
|
||||
logout: () => void
|
||||
isAuthenticated: boolean
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | null>(null)
|
||||
|
||||
export const AuthProvider = ({ children }: { children: React.ReactNode }) => {
|
||||
const [isAuthenticated, setIsAuthenticated] = useState(() => {
|
||||
const token = localStorage.getItem("accessToken")
|
||||
return token != null && !isTokenExpired(token)
|
||||
})
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem("accessToken")
|
||||
|
||||
if (token) {
|
||||
if (isTokenExpired(token)) {
|
||||
localStorage.removeItem("accessToken")
|
||||
setIsAuthenticated(false)
|
||||
} else {
|
||||
setIsAuthenticated(true)
|
||||
}
|
||||
}
|
||||
setIsLoading(false)
|
||||
}, [])
|
||||
|
||||
const login = async (credentials: any) => {
|
||||
const data = await loginService(credentials)
|
||||
|
||||
if (data.accessToken) {
|
||||
localStorage.setItem("accessToken", data.accessToken)
|
||||
} else {
|
||||
throw new Error("No access token received")
|
||||
}
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem("accessToken")
|
||||
window.location.href = "/login"
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ login, logout, isAuthenticated, isLoading }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext)
|
||||
if (!context) throw new Error("useAuth must be used within an AuthProvider")
|
||||
return context
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./auth.context"
|
||||
export * from "./theme.provider"
|
||||
@@ -0,0 +1,63 @@
|
||||
import { createContext, useContext, useEffect, useState } from "react"
|
||||
|
||||
type Theme = "dark" | "light"
|
||||
|
||||
type ThemeProviderProps = {
|
||||
children: React.ReactNode
|
||||
defaultTheme?: Theme
|
||||
storageKey?: string
|
||||
}
|
||||
|
||||
type ThemeProviderState = {
|
||||
theme: Theme
|
||||
setTheme: (theme: Theme) => void
|
||||
}
|
||||
|
||||
const initialState: ThemeProviderState = {
|
||||
theme: "light",
|
||||
setTheme: () => null,
|
||||
}
|
||||
|
||||
const ThemeProviderContext = createContext<ThemeProviderState>(initialState)
|
||||
|
||||
export function ThemeProvider({
|
||||
children,
|
||||
defaultTheme = "light",
|
||||
storageKey = "theme",
|
||||
...props
|
||||
}: ThemeProviderProps) {
|
||||
const [theme, setTheme] = useState<Theme>(
|
||||
() => (localStorage.getItem(storageKey) as Theme) || defaultTheme,
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const root = window.document.documentElement
|
||||
|
||||
root.classList.remove("light", "dark")
|
||||
|
||||
root.classList.add(theme)
|
||||
}, [theme])
|
||||
|
||||
const value = {
|
||||
theme,
|
||||
setTheme: (theme: Theme) => {
|
||||
localStorage.setItem(storageKey, theme)
|
||||
setTheme(theme)
|
||||
},
|
||||
}
|
||||
|
||||
return (
|
||||
<ThemeProviderContext.Provider {...props} value={value}>
|
||||
{children}
|
||||
</ThemeProviderContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeProviderContext)
|
||||
|
||||
if (context === undefined)
|
||||
throw new Error("useTheme must be used within a ThemeProvider")
|
||||
|
||||
return context
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { apiClient } from "@/lib/api.client"
|
||||
|
||||
export const signupService = async (data: {
|
||||
name: string
|
||||
email: string
|
||||
password: string
|
||||
}) => {
|
||||
const newUser = await apiClient("/auth/signup", {
|
||||
method: "POST",
|
||||
body: data,
|
||||
})
|
||||
if (newUser) {
|
||||
return { ok: true }
|
||||
} else {
|
||||
return { ok: false, message: "Registration failed" }
|
||||
}
|
||||
}
|
||||
|
||||
export const loginService = async (data: {
|
||||
email: string
|
||||
password: string
|
||||
}) => {
|
||||
return await apiClient("/auth/login", {
|
||||
method: "POST",
|
||||
body: data,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import React from "react"
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardFooter,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from "../../../components/ui/card"
|
||||
|
||||
interface CustomCardProps {
|
||||
title?: string
|
||||
description?: string
|
||||
footer?: string | React.ReactNode
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export function AuthCard({
|
||||
title,
|
||||
description,
|
||||
footer,
|
||||
children,
|
||||
}: CustomCardProps) {
|
||||
return (
|
||||
<Card className="w-full max-w-md">
|
||||
<CardHeader className="space-y-2 text-center">
|
||||
<CardTitle className="text-2xl">{title}</CardTitle>
|
||||
<CardDescription>{description}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>{children}</CardContent>
|
||||
<CardFooter className="flex justify-center">{footer}</CardFooter>
|
||||
</Card>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./auth.card"
|
||||
export * from "./login.form"
|
||||
export * from "./signup.form"
|
||||
@@ -0,0 +1,102 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { type SubmitHandler, useForm } from "react-hook-form"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldSet,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { loginService } from "../auth.api"
|
||||
import { type LoginInputs, loginSchema } from "../schemas"
|
||||
|
||||
export function LoginForm() {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
setError,
|
||||
} = useForm<LoginInputs>({
|
||||
resolver: zodResolver(loginSchema),
|
||||
defaultValues: {
|
||||
email: "",
|
||||
password: "",
|
||||
},
|
||||
})
|
||||
const onSubmit: SubmitHandler<LoginInputs> = async (data) => {
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const response = await loginService(data)
|
||||
|
||||
localStorage.setItem("accessToken", response.accessToken)
|
||||
|
||||
location.replace("/")
|
||||
} catch (error) {
|
||||
setError("root", {
|
||||
type: "manual",
|
||||
message: error instanceof Error ? error.message : "Login failed",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FieldSet>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
type="text"
|
||||
placeholder="admin@example.com"
|
||||
className="w-full"
|
||||
{...register("email", { required: true })}
|
||||
/>
|
||||
</Field>
|
||||
{errors.email && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.email.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
{...register("password", { required: true })}
|
||||
className="w-full"
|
||||
/>
|
||||
</Field>
|
||||
{errors.password && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.password.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
className={`w-full ${isLoading ? "loading" : ""}`}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Sign In {isLoading ? "..." : ""}
|
||||
</Button>
|
||||
<div className="text-center">
|
||||
{errors.root && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.root.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
</div>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { type SubmitHandler, useForm } from "react-hook-form"
|
||||
import { useNavigate } from "react-router"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldSet,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { signupService } from "../auth.api"
|
||||
import { type RegisterInputs, registerSchema } from "../schemas"
|
||||
|
||||
export function SignupForm() {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
setError,
|
||||
} = useForm<RegisterInputs>({
|
||||
resolver: zodResolver(registerSchema),
|
||||
defaultValues: {
|
||||
email: "",
|
||||
name: "",
|
||||
password: "",
|
||||
},
|
||||
})
|
||||
const onSubmit: SubmitHandler<RegisterInputs> = async (data) => {
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const response = await signupService(data)
|
||||
|
||||
if (response.ok) {
|
||||
alert("Signup successful! Please login.")
|
||||
navigate("/login")
|
||||
} else {
|
||||
throw new Error(response.message || "Signup failed")
|
||||
}
|
||||
} catch (error) {
|
||||
setError("root", {
|
||||
type: "manual",
|
||||
message: error instanceof Error ? error.message : "Signup failed",
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FieldSet>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email">Email</FieldLabel>
|
||||
<Input
|
||||
id="email"
|
||||
type="text"
|
||||
placeholder="admin@example.com"
|
||||
className="w-full"
|
||||
{...register("email", { required: true })}
|
||||
/>
|
||||
</Field>
|
||||
{errors.email && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.email.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
<Field>
|
||||
<FieldLabel htmlFor="name">Name</FieldLabel>
|
||||
<Input
|
||||
id="name"
|
||||
type="text"
|
||||
placeholder="Admin User"
|
||||
className="w-full"
|
||||
{...register("name", { required: true })}
|
||||
/>
|
||||
</Field>
|
||||
{errors.name && (
|
||||
<FieldDescription>{errors.name.message}</FieldDescription>
|
||||
)}
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password">Password</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
placeholder="••••••••"
|
||||
{...register("password", { required: true })}
|
||||
className="w-full"
|
||||
/>
|
||||
</Field>
|
||||
{errors.password && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.password.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
<Button
|
||||
type="submit"
|
||||
className={`w-full ${isLoading ? "loading" : ""}`}
|
||||
disabled={isLoading}
|
||||
>
|
||||
Sign Up {isLoading ? "..." : ""}
|
||||
</Button>
|
||||
<div className="text-center">
|
||||
{errors.root && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.root.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
</div>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const emailSchema = z.email("Invalid email address")
|
||||
|
||||
export const passwordSchema = z
|
||||
.string()
|
||||
.min(6, "Password must be at least 6 characters")
|
||||
@@ -0,0 +1,3 @@
|
||||
export * from "./auth.common.schemas"
|
||||
export * from "./login.schemas"
|
||||
export * from "./signup.schemas"
|
||||
@@ -0,0 +1,9 @@
|
||||
import { z } from "zod"
|
||||
import { emailSchema, passwordSchema } from "./auth.common.schemas"
|
||||
|
||||
export const loginSchema = z.object({
|
||||
email: emailSchema,
|
||||
password: passwordSchema,
|
||||
})
|
||||
|
||||
export type LoginInputs = z.infer<typeof loginSchema>
|
||||
@@ -0,0 +1,10 @@
|
||||
import { z } from "zod"
|
||||
import { emailSchema, passwordSchema } from "./auth.common.schemas"
|
||||
|
||||
export const registerSchema = z.object({
|
||||
email: emailSchema,
|
||||
name: z.string().min(2, "Name must be at least 2 characters"),
|
||||
password: passwordSchema,
|
||||
})
|
||||
|
||||
export type RegisterInputs = z.infer<typeof registerSchema>
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./password.form"
|
||||
export * from "./profile.form"
|
||||
@@ -0,0 +1,104 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldSet,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { type ChangePasswordInputs, changePasswordSchema } from "../schemas"
|
||||
import { changePassword } from "../user.api"
|
||||
|
||||
export function ChangePasswordCard() {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
setError,
|
||||
formState: { errors, isDirty, isSubmitting },
|
||||
} = useForm<ChangePasswordInputs>({
|
||||
resolver: zodResolver(changePasswordSchema),
|
||||
defaultValues: {
|
||||
password: "",
|
||||
confirmPassword: "",
|
||||
},
|
||||
mode: "onChange",
|
||||
})
|
||||
|
||||
const onSubmit = async (data: ChangePasswordInputs) => {
|
||||
try {
|
||||
await changePassword({ password: data.password })
|
||||
|
||||
reset()
|
||||
toast.success("Password updated successfully")
|
||||
} catch (error) {
|
||||
setError("root", {
|
||||
type: "server",
|
||||
message: (error as Error).message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FieldSet>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="password" className="font-medium text-sm">
|
||||
New Password
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
{...register("password")}
|
||||
/>
|
||||
{errors.password && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.password.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel
|
||||
htmlFor="confirmPassword"
|
||||
className="font-medium text-sm"
|
||||
>
|
||||
Confirm Password
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="confirmPassword"
|
||||
type="password"
|
||||
autoComplete="new-password"
|
||||
{...register("confirmPassword")}
|
||||
/>
|
||||
{errors.confirmPassword && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.confirmPassword.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
{errors.root && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.root.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting || !isDirty}
|
||||
>
|
||||
{isSubmitting ? "Updating..." : "Update Password"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useForm } from "react-hook-form"
|
||||
import { toast } from "sonner"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldSet,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { getUser } from "../user.api"
|
||||
import { type UpdateUserInputs, updateUserSchema } from "../schemas"
|
||||
import { updateUser } from "../user.api"
|
||||
import { useEffect } from "react"
|
||||
|
||||
export function ProfileForm() {
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
reset,
|
||||
setError,
|
||||
formState: { errors, isDirty, isSubmitting },
|
||||
} = useForm<UpdateUserInputs>({
|
||||
resolver: zodResolver(updateUserSchema),
|
||||
defaultValues: async () => {
|
||||
return await getUser()
|
||||
},
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchUser() {
|
||||
const user = await getUser()
|
||||
reset(user)
|
||||
}
|
||||
fetchUser()
|
||||
}, [reset])
|
||||
|
||||
const onSubmit = async (data: UpdateUserInputs) => {
|
||||
try {
|
||||
await updateUser(data)
|
||||
reset(data)
|
||||
toast.success("Profile updated successfully")
|
||||
} catch (error) {
|
||||
setError("root", {
|
||||
type: "server",
|
||||
message: (error as Error).message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FieldSet>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="name" className="font-medium text-sm">
|
||||
Name
|
||||
</FieldLabel>
|
||||
<Input id="name" {...register("name")} />
|
||||
{errors.name && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.name.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="email" className="font-medium text-sm">
|
||||
Email
|
||||
</FieldLabel>
|
||||
<Input id="email" {...register("email")} />
|
||||
{errors.email && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.email.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
{errors.root && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.root.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting || !isDirty}
|
||||
>
|
||||
{isSubmitting ? "Updating..." : "Update Profile"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./password.schemas"
|
||||
export * from "./profile.schemas"
|
||||
@@ -0,0 +1,14 @@
|
||||
import { z } from "zod"
|
||||
import { passwordSchema } from "@/features/auth/schemas"
|
||||
|
||||
export const changePasswordSchema = z
|
||||
.object({
|
||||
password: passwordSchema,
|
||||
confirmPassword: z.string(),
|
||||
})
|
||||
.refine((data) => data.password === data.confirmPassword, {
|
||||
message: "Passwords do not match",
|
||||
path: ["confirmPassword"],
|
||||
})
|
||||
|
||||
export type ChangePasswordInputs = z.infer<typeof changePasswordSchema>
|
||||
@@ -0,0 +1,8 @@
|
||||
import { z } from "zod"
|
||||
|
||||
export const updateUserSchema = z.object({
|
||||
name: z.string().min(2, "Name must be at least 2 characters long"),
|
||||
email: z.email().optional(),
|
||||
})
|
||||
|
||||
export type UpdateUserInputs = z.infer<typeof updateUserSchema>
|
||||
@@ -0,0 +1,19 @@
|
||||
import { apiClient } from "@/lib/api.client"
|
||||
|
||||
export const getUser = async () => {
|
||||
return await apiClient("/user", { method: "GET" })
|
||||
}
|
||||
|
||||
export const updateUser = async (data: { name: string; email?: string }) => {
|
||||
return await apiClient("/user", {
|
||||
method: "PATCH",
|
||||
body: data,
|
||||
})
|
||||
}
|
||||
|
||||
export const changePassword = async (data: { password: string }) => {
|
||||
return await apiClient("/user/password", {
|
||||
method: "PATCH",
|
||||
body: { password: data.password },
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./url.form"
|
||||
export * from "./url.list"
|
||||
@@ -0,0 +1,108 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod"
|
||||
import { useState } from "react"
|
||||
import { type SubmitHandler, useForm } from "react-hook-form"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Field,
|
||||
FieldDescription,
|
||||
FieldGroup,
|
||||
FieldLabel,
|
||||
FieldSet,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { createUrl } from "../url.api"
|
||||
import { type ShortenUrlInputs, shortenUrlSchema } from "../schemas/url.schema"
|
||||
import type { UrlFormProps } from "../types/url.types"
|
||||
|
||||
export function UrlForm({ onAddUrl }: UrlFormProps) {
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
const {
|
||||
register,
|
||||
handleSubmit,
|
||||
formState: { errors },
|
||||
setError,
|
||||
clearErrors,
|
||||
reset,
|
||||
} = useForm<ShortenUrlInputs>({
|
||||
resolver: zodResolver(shortenUrlSchema),
|
||||
defaultValues: {
|
||||
url: "",
|
||||
alias: null,
|
||||
},
|
||||
})
|
||||
|
||||
const onSubmit: SubmitHandler<ShortenUrlInputs> = async (data) => {
|
||||
setIsLoading(true)
|
||||
|
||||
try {
|
||||
const response = await createUrl(data)
|
||||
|
||||
onAddUrl(response)
|
||||
|
||||
reset()
|
||||
} catch (error) {
|
||||
setError("root", {
|
||||
type: "server",
|
||||
message: (error as Error).message,
|
||||
})
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||
<FieldSet>
|
||||
<FieldGroup>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="url" className="font-medium text-sm">
|
||||
URL
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="url"
|
||||
type="text"
|
||||
placeholder="https://example.com/very/long/url"
|
||||
{...register("url")}
|
||||
onChange={() => {
|
||||
clearErrors("url")
|
||||
}}
|
||||
/>
|
||||
{errors.url && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.url.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
</Field>
|
||||
|
||||
<Field>
|
||||
<FieldLabel htmlFor="alias" className="font-medium text-sm">
|
||||
Custom Alias{" "}
|
||||
<span className="text-muted-foreground">(optional)</span>
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="alias"
|
||||
type="text"
|
||||
placeholder="alias"
|
||||
required={false}
|
||||
{...register("alias", { required: false })}
|
||||
/>
|
||||
{errors.alias && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.alias.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
</Field>
|
||||
{errors.root && (
|
||||
<FieldDescription className="text-destructive text-sm">
|
||||
{errors.root.message}
|
||||
</FieldDescription>
|
||||
)}
|
||||
|
||||
<Button type="submit" className="w-full" disabled={isLoading}>
|
||||
{isLoading ? "Creating..." : "Shorten URL"}
|
||||
</Button>
|
||||
</FieldGroup>
|
||||
</FieldSet>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { Check, Copy, Edit2, Trash2 } from "lucide-react"
|
||||
import { useState } from "react"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { DOMAIN } from "@/config"
|
||||
import type { Url, UrlListProps } from "../types/url.types"
|
||||
|
||||
export function UrlsList({ urls, onDelete, onUpdate }: UrlListProps) {
|
||||
const [editingId, setEditingId] = useState<string | null>(null)
|
||||
const [editValue, setEditValue] = useState("")
|
||||
const [copiedId, setCopiedId] = useState<string | null>(null)
|
||||
|
||||
const handleEdit = ({ id, alias }: Url) => {
|
||||
setEditingId(id)
|
||||
if (alias) setEditValue(alias)
|
||||
}
|
||||
|
||||
const handleSaveEdit = (id: string) => {
|
||||
if (editValue.trim()) {
|
||||
onUpdate(id, editValue)
|
||||
setEditingId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCopy = (text: string, id: string) => {
|
||||
navigator.clipboard.writeText(`${DOMAIN}/${text}`)
|
||||
setCopiedId(id)
|
||||
setTimeout(() => setCopiedId(null), 2000)
|
||||
}
|
||||
|
||||
const formatDate = (dateString: string) => {
|
||||
return new Date(dateString).toLocaleDateString("en-US", {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{urls.length === 0 ? (
|
||||
<div className="py-8 text-center text-muted-foreground">
|
||||
No shortened URLs yet. Create one to get started.
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-3">
|
||||
{urls.map((url: Url) => (
|
||||
<div
|
||||
key={url.id}
|
||||
className="flex items-center gap-3 rounded-lg border border-border p-4 transition-colors hover:bg-muted/50"
|
||||
>
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="mb-2 flex items-center gap-2">
|
||||
{editingId === url.id ? (
|
||||
<div className="flex flex-1 gap-2">
|
||||
<Input
|
||||
value={editValue}
|
||||
onChange={(e) => setEditValue(e.target.value)}
|
||||
className="flex-1"
|
||||
autoFocus
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={() => handleSaveEdit(url.id)}
|
||||
>
|
||||
Save
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onClick={() => setEditingId(null)}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<code className="rounded bg-muted px-2 py-1 font-mono text-sm">
|
||||
{url.alias ?? url.shortId}
|
||||
</code>
|
||||
<button
|
||||
onClick={() =>
|
||||
handleCopy(url.alias ?? url.shortId, url.id)
|
||||
}
|
||||
className="rounded p-1 transition-colors hover:bg-muted"
|
||||
title="Copy short ID"
|
||||
>
|
||||
{copiedId === url.id ? (
|
||||
<Check className="h-4 w-4 text-green-600" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
<span>Clicks {url.clicks}</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<a
|
||||
href={url.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="block truncate text-primary text-sm hover:underline"
|
||||
title={url.url}
|
||||
>
|
||||
{url.url}
|
||||
</a>
|
||||
<p className="mt-1 text-muted-foreground text-xs">
|
||||
{formatDate(url.createdAt)}
|
||||
</p>
|
||||
</div>
|
||||
{editingId !== url.id && (
|
||||
<div className="flex gap-2">
|
||||
{url.alias && (
|
||||
<button
|
||||
onClick={() => handleEdit(url)}
|
||||
className="rounded p-2 transition-colors hover:bg-muted"
|
||||
title="Edit"
|
||||
>
|
||||
<Edit2 className="h-4 w-4 text-muted-foreground" />
|
||||
</button>
|
||||
)}
|
||||
<button
|
||||
onClick={() => onDelete(url.id)}
|
||||
className="rounded p-2 transition-colors hover:bg-destructive/10"
|
||||
title="Delete"
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from "zod"
|
||||
|
||||
const urlSchema = z.url({
|
||||
protocol: /^https?$/,
|
||||
hostname: z.regexes.domain,
|
||||
})
|
||||
|
||||
const aliasSchema = z
|
||||
.string()
|
||||
.max(30)
|
||||
.transform((val) => (val === "" ? null : val))
|
||||
.nullable()
|
||||
.optional()
|
||||
.refine((val) => {
|
||||
if (val === null || val === undefined) return true
|
||||
return /^[a-zA-Z0-9]+$/.test(val)
|
||||
}, "Alias can only contain alphanumeric characters")
|
||||
|
||||
export const shortenUrlSchema = z.object({
|
||||
url: urlSchema,
|
||||
alias: aliasSchema,
|
||||
})
|
||||
|
||||
export type ShortenUrlInputs = z.infer<typeof shortenUrlSchema>
|
||||
@@ -0,0 +1,21 @@
|
||||
export interface Url {
|
||||
id: string
|
||||
url: string
|
||||
shortId: string
|
||||
alias: string | null
|
||||
clicks: number
|
||||
createdAt: string
|
||||
}
|
||||
|
||||
export interface UrlList {
|
||||
urls: Url[]
|
||||
}
|
||||
|
||||
export interface UrlListProps extends UrlList {
|
||||
onDelete: (id: string) => void
|
||||
onUpdate: (id: string, alias: string) => void
|
||||
}
|
||||
|
||||
export interface UrlFormProps {
|
||||
onAddUrl: (newUrl: Url) => void
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import { apiClient } from "@/lib/api.client"
|
||||
import type { ShortenUrlInputs } from "./schemas/url.schema"
|
||||
import type { Url } from "./types/url.types"
|
||||
|
||||
export const getUrls = async (): Promise<Url[]> => {
|
||||
const data = await apiClient("/url", { method: "GET" })
|
||||
return data
|
||||
}
|
||||
|
||||
export const createUrl = async (data: ShortenUrlInputs) => {
|
||||
return await apiClient("/url/shorten", {
|
||||
method: "POST",
|
||||
body: data,
|
||||
})
|
||||
}
|
||||
|
||||
export const updateUrl = async (id: string, alias: string) => {
|
||||
return await apiClient(`/url/${id}`, {
|
||||
method: "PATCH",
|
||||
body: { alias },
|
||||
})
|
||||
}
|
||||
|
||||
export const deleteUrl = async (id: string) => {
|
||||
return await apiClient(`/url/${id}`, { method: "DELETE" })
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { useEffect } from "react";
|
||||
|
||||
export default function useTitle(title: string) {
|
||||
useEffect(() => {
|
||||
document.title = `URL Shortener - ${title}`;
|
||||
}, [title]);
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
@import url("https://fonts.googleapis.com/css2?family=Geist:wght@100..900&display=swap");
|
||||
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
@theme {
|
||||
--font-roboto: "Geist", sans-serif;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--color-chart-1: var(--chart-1);
|
||||
--color-chart-2: var(--chart-2);
|
||||
--color-chart-3: var(--chart-3);
|
||||
--color-chart-4: var(--chart-4);
|
||||
--color-chart-5: var(--chart-5);
|
||||
--color-sidebar: var(--sidebar);
|
||||
--color-sidebar-foreground: var(--sidebar-foreground);
|
||||
--color-sidebar-primary: var(--sidebar-primary);
|
||||
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
|
||||
--color-sidebar-accent: var(--sidebar-accent);
|
||||
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
|
||||
--color-sidebar-border: var(--sidebar-border);
|
||||
--color-sidebar-ring: var(--sidebar-ring);
|
||||
}
|
||||
|
||||
:root {
|
||||
--radius: 0.625rem;
|
||||
--background: oklch(1 0 0);
|
||||
--foreground: oklch(0.145 0 0);
|
||||
--card: oklch(1 0 0);
|
||||
--card-foreground: oklch(0.145 0 0);
|
||||
--popover: oklch(1 0 0);
|
||||
--popover-foreground: oklch(0.145 0 0);
|
||||
--primary: oklch(0.205 0 0);
|
||||
--primary-foreground: oklch(0.985 0 0);
|
||||
--secondary: oklch(0.97 0 0);
|
||||
--secondary-foreground: oklch(0.205 0 0);
|
||||
--muted: oklch(0.97 0 0);
|
||||
--muted-foreground: oklch(0.556 0 0);
|
||||
--accent: oklch(0.97 0 0);
|
||||
--accent-foreground: oklch(0.205 0 0);
|
||||
--destructive: oklch(0.577 0.245 27.325);
|
||||
--border: oklch(0.922 0 0);
|
||||
--input: oklch(0.922 0 0);
|
||||
--ring: oklch(0.708 0 0);
|
||||
--chart-1: oklch(0.646 0.222 41.116);
|
||||
--chart-2: oklch(0.6 0.118 184.704);
|
||||
--chart-3: oklch(0.398 0.07 227.392);
|
||||
--chart-4: oklch(0.828 0.189 84.429);
|
||||
--chart-5: oklch(0.769 0.188 70.08);
|
||||
--sidebar: oklch(0.985 0 0);
|
||||
--sidebar-foreground: oklch(0.145 0 0);
|
||||
--sidebar-primary: oklch(0.205 0 0);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.97 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.205 0 0);
|
||||
--sidebar-border: oklch(0.922 0 0);
|
||||
--sidebar-ring: oklch(0.708 0 0);
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: oklch(0.145 0 0);
|
||||
--foreground: oklch(0.985 0 0);
|
||||
--card: oklch(0.205 0 0);
|
||||
--card-foreground: oklch(0.985 0 0);
|
||||
--popover: oklch(0.205 0 0);
|
||||
--popover-foreground: oklch(0.985 0 0);
|
||||
--primary: oklch(0.922 0 0);
|
||||
--primary-foreground: oklch(0.205 0 0);
|
||||
--secondary: oklch(0.269 0 0);
|
||||
--secondary-foreground: oklch(0.985 0 0);
|
||||
--muted: oklch(0.269 0 0);
|
||||
--muted-foreground: oklch(0.708 0 0);
|
||||
--accent: oklch(0.269 0 0);
|
||||
--accent-foreground: oklch(0.985 0 0);
|
||||
--destructive: oklch(0.704 0.191 22.216);
|
||||
--border: oklch(1 0 0 / 10%);
|
||||
--input: oklch(1 0 0 / 15%);
|
||||
--ring: oklch(0.556 0 0);
|
||||
--chart-1: oklch(0.488 0.243 264.376);
|
||||
--chart-2: oklch(0.696 0.17 162.48);
|
||||
--chart-3: oklch(0.769 0.188 70.08);
|
||||
--chart-4: oklch(0.627 0.265 303.9);
|
||||
--chart-5: oklch(0.645 0.246 16.439);
|
||||
--sidebar: oklch(0.205 0 0);
|
||||
--sidebar-foreground: oklch(0.985 0 0);
|
||||
--sidebar-primary: oklch(0.488 0.243 264.376);
|
||||
--sidebar-primary-foreground: oklch(0.985 0 0);
|
||||
--sidebar-accent: oklch(0.269 0 0);
|
||||
--sidebar-accent-foreground: oklch(0.985 0 0);
|
||||
--sidebar-border: oklch(1 0 0 / 10%);
|
||||
--sidebar-ring: oklch(0.556 0 0);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
}
|
||||
}
|
||||
|
||||
button {
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { Outlet } from "react-router"
|
||||
import { Header } from "@/components/layout"
|
||||
import { Toaster } from "@/components/ui/sonner"
|
||||
|
||||
export function AppLayout() {
|
||||
return (
|
||||
<main
|
||||
className={`min-h-screen bg-background font-sans text-foreground antialiased`}
|
||||
>
|
||||
<Header />
|
||||
<Outlet />
|
||||
<Toaster />
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import { Outlet } from "react-router"
|
||||
|
||||
export function AuthLayout() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center px-4">
|
||||
<Outlet />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "@/layouts/app.layout"
|
||||
export * from "@/layouts/auth.layout"
|
||||
@@ -0,0 +1,65 @@
|
||||
import { API_BASE_URL } from "@/config"
|
||||
|
||||
interface FetchOptions extends Omit<RequestInit, "body"> {
|
||||
body?: any
|
||||
}
|
||||
|
||||
export const apiClient = async (
|
||||
endpoint: string = "",
|
||||
options: FetchOptions = {},
|
||||
) => {
|
||||
const token = localStorage.getItem("accessToken")
|
||||
|
||||
// @ts-ignore: Ignore headers type for simplicity
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
...options.headers,
|
||||
}
|
||||
|
||||
if (token) {
|
||||
headers["Authorization"] = `Bearer ${token}`
|
||||
}
|
||||
|
||||
let body: BodyInit | null | undefined
|
||||
|
||||
if (options.body) {
|
||||
if (
|
||||
typeof options.body === "object" &&
|
||||
!(options.body instanceof FormData) &&
|
||||
!(options.body instanceof URLSearchParams)
|
||||
) {
|
||||
body = JSON.stringify(options.body)
|
||||
} else {
|
||||
body = options.body as BodyInit
|
||||
}
|
||||
}
|
||||
|
||||
const config: RequestInit = {
|
||||
...options,
|
||||
headers,
|
||||
body,
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||||
...config,
|
||||
})
|
||||
|
||||
if (response.status === 401) {
|
||||
if (window.location.pathname !== "/login") {
|
||||
window.location.href = "/login"
|
||||
}
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const errorBody = await response.json().catch(() => ({}))
|
||||
throw new Error(errorBody.message || `HTTP Error: ${response.status}`)
|
||||
}
|
||||
|
||||
if (response.status === 204) return null
|
||||
|
||||
return response.json()
|
||||
} catch (error) {
|
||||
throw new Error((error as Error).message || "Network Error")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { jwtDecode } from "jwt-decode"
|
||||
|
||||
export const isTokenExpired = (token: string): boolean => {
|
||||
if (!token) return true
|
||||
try {
|
||||
const decoded = jwtDecode(token)
|
||||
const currentTime = Date.now() / 1000
|
||||
// @ts-ignore
|
||||
return decoded.exp < currentTime + 10
|
||||
} catch (_error) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { type ClassValue, clsx } from "clsx"
|
||||
import { twMerge } from "tailwind-merge"
|
||||
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs))
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { StrictMode } from "react"
|
||||
import { createRoot } from "react-dom/client"
|
||||
import { RouterProvider } from "react-router"
|
||||
import "./index.css"
|
||||
import { AuthProvider, ThemeProvider } from "@/context"
|
||||
import { router } from "@/routes"
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<AuthProvider>
|
||||
<ThemeProvider>
|
||||
<RouterProvider router={router} />
|
||||
</ThemeProvider>
|
||||
</AuthProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
export * from "./urls.page.tsx"
|
||||
export * from "./login.page.tsx"
|
||||
export * from "./notFound.page.tsx"
|
||||
export * from "./profile.page.tsx"
|
||||
export * from "./signup.page.tsx"
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Link } from "react-router"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { SIGNUP_ENABLED } from "@/config"
|
||||
import { AuthCard, LoginForm } from "@/features/auth/components"
|
||||
import useTitle from "@/hooks/useTitle"
|
||||
|
||||
const LoginFooter = () => {
|
||||
return (
|
||||
<>
|
||||
{SIGNUP_ENABLED === true && (
|
||||
<p className="text-center text-muted-foreground text-sm">
|
||||
Don't have an account?{" "}
|
||||
<Link to="/signup">
|
||||
<Button variant="link" size="sm" className="p-0">
|
||||
Sign up
|
||||
</Button>
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function LoginPage() {
|
||||
useTitle("Login");
|
||||
return (
|
||||
<AuthCard
|
||||
title="URL Shortener"
|
||||
description="Login to your Account"
|
||||
footer={<LoginFooter />}
|
||||
>
|
||||
<LoginForm />
|
||||
</AuthCard>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import useTitle from "@/hooks/useTitle";
|
||||
import { Undo2 } from "lucide-react"
|
||||
import { Link } from "react-router"
|
||||
|
||||
export function NotFoundPage() {
|
||||
useTitle("404 Not Found");
|
||||
return (
|
||||
<div className="flex min-h-screen items-center px-4 py-12 sm:px-6 md:px-8 lg:px-12 xl:px-16">
|
||||
<div className="w-full space-y-6 text-center">
|
||||
<div className="space-y-3">
|
||||
<h1 className="font-bold text-4xl tracking-tighter transition-transform hover:scale-110 sm:text-5xl">
|
||||
404
|
||||
</h1>
|
||||
<p className="text-gray-500">
|
||||
Looks like you've ventured into the unknown digital realm.
|
||||
</p>
|
||||
</div>
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-flex h-10 items-center rounded-md bg-gray-900 px-8 font-medium text-gray-50 text-sm shadow transition-colors hover:bg-gray-900/90 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-gray-950 disabled:pointer-events-none disabled:opacity-50 dark:bg-gray-50 dark:text-gray-900 dark:focus-visible:ring-gray-300 dark:hover:bg-gray-50/90"
|
||||
>
|
||||
<Undo2 className="mr-2 h-4 w-4" />
|
||||
Return Home
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { CustomCard } from "@/components/common"
|
||||
import { ChangePasswordCard, ProfileForm } from "@/features/profile/components"
|
||||
import useTitle from "@/hooks/useTitle";
|
||||
|
||||
export function ProfilePage() {
|
||||
useTitle("Profile Settings");
|
||||
return (
|
||||
<div className="mx-auto max-w-6xl px-6 py-8">
|
||||
<div className="grid gap-8 lg:grid-cols-4">
|
||||
<div className="lg:col-span-2">
|
||||
<CustomCard
|
||||
title="Profile Settings"
|
||||
description="Update your profile information"
|
||||
>
|
||||
<ProfileForm />
|
||||
</CustomCard>
|
||||
</div>
|
||||
<div className="lg:col-span-2">
|
||||
<CustomCard
|
||||
title="Change Password"
|
||||
description="Update your account password"
|
||||
>
|
||||
<ChangePasswordCard />
|
||||
</CustomCard>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Link } from "react-router"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { SIGNUP_ENABLED } from "@/config"
|
||||
import { AuthCard, SignupForm } from "@/features/auth/components"
|
||||
import useTitle from "@/hooks/useTitle"
|
||||
|
||||
const SignupFooter = () => {
|
||||
return (
|
||||
<>
|
||||
{SIGNUP_ENABLED === true && (
|
||||
<p className="text-center text-muted-foreground text-sm">
|
||||
Do you have an account?{" "}
|
||||
<Link to="/login">
|
||||
<Button variant="link" size="sm" className="p-0">
|
||||
Login
|
||||
</Button>
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
export function SignupPage() {
|
||||
useTitle("Sign Up");
|
||||
return (
|
||||
<AuthCard
|
||||
title="URL Shortener"
|
||||
description="Sign Up for an Account"
|
||||
footer={<SignupFooter />}
|
||||
>
|
||||
<SignupForm />
|
||||
</AuthCard>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useEffect, useState } from "react"
|
||||
import { toast } from "sonner"
|
||||
import { CustomCard } from "@/components/common"
|
||||
import { UrlForm, UrlsList } from "@/features/url/components"
|
||||
import { deleteUrl, getUrls, updateUrl } from "@/features/url/url.api"
|
||||
import { type Url } from "@/features/url/types/url.types"
|
||||
import useTitle from "@/hooks/useTitle"
|
||||
|
||||
export function UrlsPage() {
|
||||
useTitle("Dashboard");
|
||||
const [urls, setUrls] = useState<Url[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
const fetchData = async () => {
|
||||
const data = await getUrls()
|
||||
setUrls(data)
|
||||
}
|
||||
fetchData()
|
||||
}, [])
|
||||
|
||||
const handleAddUrl = (newUrl: Url) => {
|
||||
setUrls((prevUrls) => [newUrl, ...prevUrls])
|
||||
toast.success("URL shortened successfully")
|
||||
}
|
||||
|
||||
const handleDeleteUrl = async (id: string) => {
|
||||
await deleteUrl(id)
|
||||
setUrls((prevUrls) => prevUrls.filter((url) => url.id !== id))
|
||||
toast.success("URL deleted successfully")
|
||||
}
|
||||
|
||||
const handleUpdateUrl = async (id: string, alias: string) => {
|
||||
await updateUrl(id, alias)
|
||||
setUrls((prevUrls) =>
|
||||
prevUrls.map((url) => (url.id === id ? { ...url, alias } : url)),
|
||||
)
|
||||
toast.success("URL updated successfully")
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-6xl px-6 py-8">
|
||||
<div className="grid gap-8 lg:grid-cols-3">
|
||||
<div className="lg:col-span-1">
|
||||
<CustomCard
|
||||
title="Create Short URL"
|
||||
description="Generate a new shortened URL"
|
||||
>
|
||||
<UrlForm onAddUrl={handleAddUrl} />
|
||||
</CustomCard>
|
||||
</div>
|
||||
|
||||
<div className="lg:col-span-2">
|
||||
<CustomCard
|
||||
title="Your Shortened URLs"
|
||||
description="Manage all your shortened URLs"
|
||||
>
|
||||
<UrlsList
|
||||
urls={urls}
|
||||
onDelete={handleDeleteUrl}
|
||||
onUpdate={handleUpdateUrl}
|
||||
/>
|
||||
</CustomCard>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { createBrowserRouter } from "react-router"
|
||||
import { ProtectedRoute, PublicRoute } from "./components/routes"
|
||||
import { AppLayout, AuthLayout } from "./layouts"
|
||||
import {
|
||||
UrlsPage,
|
||||
LoginPage,
|
||||
NotFoundPage,
|
||||
ProfilePage,
|
||||
SignupPage,
|
||||
} from "./pages"
|
||||
import { SIGNUP_ENABLED } from "@/config"
|
||||
|
||||
export const router = createBrowserRouter([
|
||||
{
|
||||
element: <ProtectedRoute />,
|
||||
children: [
|
||||
{
|
||||
path: "/",
|
||||
element: <AppLayout />,
|
||||
children: [
|
||||
{
|
||||
index: true,
|
||||
element: <UrlsPage />,
|
||||
},
|
||||
{
|
||||
path: "profile",
|
||||
element: <ProfilePage />,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
element: <PublicRoute />,
|
||||
children: [
|
||||
{
|
||||
element: <AuthLayout />,
|
||||
children: [
|
||||
{
|
||||
path: "login",
|
||||
element: <LoginPage />,
|
||||
},
|
||||
...(SIGNUP_ENABLED === true
|
||||
? [
|
||||
{
|
||||
path: "signup",
|
||||
element: <SignupPage />,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
path: "*",
|
||||
element: <NotFoundPage />,
|
||||
},
|
||||
])
|
||||
Reference in new issue
Block a user