33 Commits

Author SHA1 Message Date
9d7f956c3b feat(ticket): show assigned contractor details on in-progress tickets 2026-07-10 18:27:26 +05:30
0026824f84 Assign to Contractor // here in due date also change the year to 20 2026-07-10 16:17:53 +05:30
a18eb64dac feat(ticket): enable circular detection preview navigation 2026-07-10 16:12:30 +05:30
6c71d8f8a7 fix(ticket): widen extension due date picker range 2026-07-10 15:56:00 +05:30
0e2172366b refactor(ui): replace theme dropdown with toggle button 2026-07-10 13:38:17 +05:30
56180f8d18 style(ui): use pointer cursor for dropdown menu items 2026-07-10 13:25:28 +05:30
5269b29aac feat(ticket): use grid picker for extension due date 2026-07-10 12:24:44 +05:30
9fe7109faf style: widen plan and role sheet panels 2026-07-10 11:31:36 +05:30
9720546455 refactor(ticket): update ticket detail skeleton loaders 2026-07-10 10:42:40 +05:30
8727963c54 style: refine shared UI primitives and management flows 2026-07-09 23:06:25 +05:30
0e8108b875 feat: modify table design 2026-07-09 17:14:37 +05:30
87dde1c8d1 feat: sync codebase with latest radix pattern 2026-07-09 17:07:11 +05:30
a376558b2f refactor(layout): improve module header and sidebar toggle UX 2026-07-09 11:54:16 +05:30
4fe93460d9 feat(ui): use grid calendar picker for modern ui look 2026-07-09 10:31:36 +05:30
cbfb6e040b refactor(ticket): rename View Analysis button to View Video 2026-07-08 17:51:42 +05:30
7a82e17bbb feat(results): add live annotation overlay on raw video playback 2026-07-08 17:24:20 +05:30
23186ffd29 feat(ticket): add paginated class detection preview with image and map 2026-07-08 10:48:03 +05:30
fb9a654aea feat(results): replace video playback with detection image preview and map 2026-07-07 15:36:27 +05:30
d88978a830 chore: class location change 2026-07-07 12:02:29 +05:30
ba9731de86 refactor: refactor report proff section 2026-07-06 17:04:05 +05:30
c0f3a718ef feat(upload): display no-defects analysis result 2026-07-06 14:17:32 +05:30
14220445ad chore: ignore auto-generated next-env.d.ts 2026-07-04 00:57:42 +05:30
79272c7abc feat(ticket): add extension requests and improve repair proof upload UI 2026-07-04 00:56:08 +05:30
26e15360f7 feat(ticket): add due date picker and contractor details to assign flow 2026-07-03 16:07:08 +05:30
b6a0f04f1e Merge branch 'videoplayer' of https://git.convexsol.co/santasri.pachhal/visionRoad-ui into feat/mod 2026-07-03 10:36:32 +05:30
9cf4f0e795 feat(ticket): redesign overview with AI summary, location, and shared defect visuals 2026-07-03 10:30:59 +05:30
fdcfc3a8db feat: add action to open ticket action in upload 2026-07-02 15:44:26 +05:30
278b9591d7 feat: added sse for upload section 2026-07-02 14:28:28 +05:30
02adbb4c10 feat: introduce custom video player for video analysis 2026-07-02 14:23:00 +05:30
53fe4e11fe feat: change interface of analysis video log 2026-07-02 13:57:18 +05:30
2eb58856af feat(ticket): add section icons, theme-aware system timeline, and nested sidebar active routes 2026-07-02 11:33:53 +05:30
c73ba0a01f feat(ticket): redesign audit timeline with structured history events 2026-07-01 22:23:49 +05:30
1a94ff80e6 fix: scrollbar gutter shifting issue 2026-07-01 17:28:25 +05:30
148 changed files with 10579 additions and 2830 deletions

1
.gitignore vendored
View File

@@ -44,6 +44,7 @@ Thumbs.db
# TypeScript
*.tsbuildinfo
next-env.d.ts
# Test / coverage
coverage/

View File

@@ -1,16 +1,17 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"style": "radix-vega",
"rsc": true,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/app/globals.css",
"baseColor": "slate",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"rtl": false,
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
@@ -18,5 +19,7 @@
"lib": "@/lib",
"hooks": "@/hooks"
},
"menuColor": "default",
"menuAccent": "subtle",
"registries": {}
}

6
next-env.d.ts vendored
View File

@@ -1,6 +0,0 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.

3467
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -27,26 +27,35 @@
"@tanstack/react-query-devtools": "^5.101.0",
"@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.14.3",
"@vidstack/react": "^1.15.6",
"axios": "^1.13.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"date-fns": "^4.4.0",
"leaflet": "^1.9.4",
"libphonenumber-js": "^1.13.7",
"lightgallery": "^2.9.0",
"lucide-react": "^0.548.0",
"motion": "^12.38.0",
"next": "16.0.10",
"next-themes": "^0.4.6",
"radix-ui": "^1.6.0",
"react": "19.2.0",
"react-day-picker": "^10.0.1",
"react-dom": "19.2.0",
"react-hook-form": "^7.79.0",
"recharts": "2.15.4",
"react-leaflet": "^5.0.0",
"recharts": "^3.8.0",
"shadcn": "^4.13.0",
"sonner": "^1.7.4",
"tailwind-merge": "^3.3.1",
"vaul": "^1.1.2",
"zod": "^4.4.3",
"zustand": "^5.0.14"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.9",
"@types/leaflet": "^1.9.21",
"@types/node": "^22",
"@types/react": "^19",
"@types/react-dom": "^19",

View File

@@ -33,7 +33,7 @@ function ResetPasswordContent() {
</header>
{!hasToken ? (
<div className="rounded-md border border-destructive/30 bg-destructive/5 p-4 text-destructive">
<div className="rounded-lg border border-destructive/30 bg-destructive/5 p-4 text-destructive">
Password reset token is missing.
</div>
) : (

View File

@@ -0,0 +1,27 @@
'use client';
import { BreadcrumbBasic } from '@/components/app-breadcrumb';
import { ModeToggle } from '@/components/mode-toogle';
import { Separator } from '@/components/ui/separator';
import { SidebarTrigger, useSidebar } from '@/components/ui/sidebar';
export function ModuleShellHeader() {
const { isMobile } = useSidebar();
return (
<div className="sticky top-0 z-50 flex h-14 items-center justify-between gap-4 border-b border-border bg-background/95 px-6 backdrop-blur supports-backdrop-filter:bg-background/80">
<div className="flex min-w-0 items-center gap-3">
{isMobile ? (
<>
<SidebarTrigger className="shrink-0 bg-background/80 text-muted-foreground shadow-xs backdrop-blur-sm" />
<Separator orientation="vertical" className="h-4 shrink-0" />
</>
) : null}
<div className="min-w-0">
<BreadcrumbBasic />
</div>
</div>
<ModeToggle />
</div>
);
}

View File

@@ -13,6 +13,7 @@ import { FormField, PhoneInput } from '@/components/form';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
@@ -71,12 +72,12 @@ export function ClientSheet({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-3xl">
<DialogHeader className="shrink-0 border-b px-6 py-4 pr-12">
<DialogTitle className="text-lg leading-none font-semibold tracking-tight">
<DialogContent className="sm:max-w-3xl">
<DialogHeader>
<DialogTitle>
{clientId ? 'Edit Client' : 'Create Client'}
</DialogTitle>
<DialogDescription className="text-sm">
<DialogDescription>
Manage company and primary contact details.
</DialogDescription>
</DialogHeader>
@@ -86,7 +87,7 @@ export function ClientSheet({
onSubmit={onSubmit}
className="flex min-h-0 flex-1 flex-col"
>
<div className="max-h-[58vh] space-y-5 overflow-y-auto px-6 py-4">
<DialogBody className="space-y-5">
<div className="grid gap-4 md:grid-cols-2">
<FormField
id="client-first-name"
@@ -240,9 +241,9 @@ export function ClientSheet({
/>
</FormField>
</div>
</div>
</DialogBody>
<DialogFooter className="shrink-0 border-t px-6 py-4">
<DialogFooter>
<Button
type="button"
variant="outline"

View File

@@ -1,10 +1,8 @@
import { BreadcrumbBasic } from '@/components/app-breadcrumb';
import { AppSidebar } from '@/components/app-sidebar';
import { ModeToggle } from '@/components/mode-toogle';
import { SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar';
import { Separator } from '@/components/ui/separator';
import { SidebarProvider } from '@/components/ui/sidebar';
import { AuthGuard } from '@/guards';
import React from 'react';
import { ModuleShellHeader } from './_components/module-shell-header';
const ModulesLayout = ({
children,
@@ -15,16 +13,11 @@ const ModulesLayout = ({
<AuthGuard>
<SidebarProvider>
<AppSidebar />
<main className="flex flex-1 flex-col w-full h-screen overflow-hidden">
<div className="flex-1 overflow-auto [scrollbar-gutter:stable]">
<div className="max-w-380 mx-auto w-full flex flex-col min-h-full">
<div className="flex gap-3 items-center sticky top-0 bg-background z-50 py-3 px-6 border-b border-border">
<SidebarTrigger />
<ModeToggle />
<Separator orientation="vertical" className="mx-2 h-4" />
<BreadcrumbBasic />
</div>
<div className="p-6 flex-1">{children}</div>
<main className="flex flex-1 h-screen w-full flex-col overflow-hidden">
<div className="scroll-stable flex-1 overflow-auto">
<div className="mx-auto flex min-h-full w-full max-w-380 flex-col">
<ModuleShellHeader />
<div className="flex-1 p-6">{children}</div>
</div>
</div>
</main>

View File

@@ -10,6 +10,7 @@ import { ProjectSelect } from '@/components/lookups/ProjectSelect';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
@@ -62,14 +63,14 @@ export function PackageDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-2xl"
className="sm:max-w-2xl"
onOpenAutoFocus={(event) => event.preventDefault()}
>
<DialogHeader className="shrink-0 border-b px-6 py-4 pr-12">
<DialogTitle className="text-lg leading-none font-semibold tracking-tight">
<DialogHeader>
<DialogTitle>
{packageId ? 'Edit Package' : 'Create Package'}
</DialogTitle>
<DialogDescription className="text-sm">
<DialogDescription>
Manage package details and optional chainage range.
</DialogDescription>
</DialogHeader>
@@ -79,7 +80,7 @@ export function PackageDialog({
onSubmit={onSubmit}
className="flex min-h-0 flex-1 flex-col"
>
<div className="max-h-[58vh] space-y-6 overflow-y-auto px-6 py-4">
<DialogBody className="space-y-6">
<section className="space-y-4">
<div className="space-y-1">
<h3 className="text-sm font-semibold">Basic details</h3>
@@ -173,9 +174,9 @@ export function PackageDialog({
</FormField>
</div>
</section>
</div>
</DialogBody>
<DialogFooter className="shrink-0 border-t px-6 py-4">
<DialogFooter>
<Button
type="button"
variant="outline"

View File

@@ -4,6 +4,16 @@ import { useCallback, useState } from 'react';
import { Package as PackageIcon, Plus } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import type { Package } from '@/types';
@@ -20,6 +30,7 @@ import {
export default function PackagePage() {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [packageToDelete, setPackageToDelete] = useState<Package | null>(null);
const { skip, setSkip, limit, setLimit } = usePackageFilters();
const packagesQuery = usePackagesQuery({ skip, limit });
const projectsQuery = useProjectOptionsQuery();
@@ -67,14 +78,25 @@ export default function PackagePage() {
const deletePackage = useCallback(
(pkg: Package) => {
if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) {
return;
}
deletePackageMutation.mutate(pkg);
setPackageToDelete(pkg);
},
[deletePackageMutation],
[],
);
const handleDeleteDialogOpenChange = useCallback((open: boolean) => {
if (!open) {
setPackageToDelete(null);
}
}, []);
const confirmDeletePackage = useCallback(() => {
if (!packageToDelete) return;
deletePackageMutation.mutate(packageToDelete, {
onSettled: () => setPackageToDelete(null),
});
}, [deletePackageMutation, packageToDelete]);
const projects = projectsQuery.data?.items ?? [];
const packages = packagesQuery.data?.items ?? [];
const total = packagesQuery.data?.totalItems ?? 0;
@@ -122,6 +144,36 @@ export default function PackagePage() {
canSubmit={canSubmit}
isSaving={isSaving}
/>
<AlertDialog
open={Boolean(packageToDelete)}
onOpenChange={handleDeleteDialogOpenChange}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete package?</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete{' '}
<span className="font-medium text-foreground">
{packageToDelete?.name}
</span>
. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deletePackageMutation.isPending}>
Cancel
</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
disabled={deletePackageMutation.isPending}
onClick={confirmDeletePackage}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}

View File

@@ -67,7 +67,7 @@ export function PlanSheet({
return (
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent className="w-full gap-0 p-0 sm:max-w-3xl">
<SheetContent className="w-full! gap-0 p-0 sm:max-w-3xl! lg:max-w-4xl!">
<SheetHeader className="shrink-0 border-b px-6 py-4 pr-12">
<SheetTitle className="text-lg leading-none font-semibold tracking-tight">
{planId ? 'Edit Plan' : 'Create Plan'}
@@ -77,7 +77,11 @@ export function PlanSheet({
</SheetDescription>
</SheetHeader>
<form noValidate onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
<form
noValidate
onSubmit={onSubmit}
className="flex min-h-0 flex-1 flex-col"
>
<div className="flex-1 space-y-5 overflow-y-auto px-6 py-4">
<div className="grid gap-4 md:grid-cols-2">
<FormField
@@ -242,7 +246,7 @@ export function PlanSheet({
<label className="flex items-center gap-2">
<input
type="checkbox"
className="size-4 rounded border-border accent-primary"
className="size-4 rounded-lg border-border accent-primary"
{...register('is_active')}
/>
Active
@@ -250,7 +254,7 @@ export function PlanSheet({
<label className="flex items-center gap-2">
<input
type="checkbox"
className="size-4 rounded border-border accent-primary"
className="size-4 rounded-lg border-border accent-primary"
{...register('is_custom')}
/>
Custom plan
@@ -269,7 +273,7 @@ export function PlanSheet({
}
>
{isPermissionsLoading ? (
<div className="rounded-md border p-6 text-muted-foreground">
<div className="rounded-lg border p-6 text-muted-foreground">
Loading permissions...
</div>
) : (

View File

@@ -8,6 +8,7 @@ import { FormField } from '@/components/form';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
@@ -54,14 +55,14 @@ export function ProjectDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-2xl"
className="sm:max-w-2xl"
onOpenAutoFocus={(event) => event.preventDefault()}
>
<DialogHeader className="shrink-0 border-b px-6 py-4 pr-12">
<DialogTitle className="text-lg leading-none font-semibold tracking-tight">
<DialogHeader>
<DialogTitle>
{projectId ? 'Edit Project' : 'Create Project'}
</DialogTitle>
<DialogDescription className="text-sm">
<DialogDescription>
Manage road project identity and optional coordinate boundaries.
</DialogDescription>
</DialogHeader>
@@ -71,7 +72,7 @@ export function ProjectDialog({
onSubmit={onSubmit}
className="flex min-h-0 flex-1 flex-col"
>
<div className="max-h-[58vh] space-y-6 overflow-y-auto px-6 py-4">
<DialogBody className="space-y-6">
<section className="space-y-4">
<div className="space-y-1">
<h3 className="text-sm font-semibold">Basic details</h3>
@@ -192,9 +193,9 @@ export function ProjectDialog({
</div>
</div>
</section>
</div>
</DialogBody>
<DialogFooter className="shrink-0 border-t px-6 py-4">
<DialogFooter>
<Button
type="button"
variant="outline"

View File

@@ -4,6 +4,16 @@ import { useCallback, useState } from 'react';
import { Layers, Plus } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import type { Project } from '@/types';
@@ -19,6 +29,7 @@ import {
export default function ProjectPage() {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [projectToDelete, setProjectToDelete] = useState<Project | null>(null);
const { skip, setSkip, limit, setLimit } = useProjectFilters();
const projectsQuery = useProjectsQuery({ skip, limit });
const deleteProjectMutation = useDeleteProjectMutation();
@@ -63,16 +74,25 @@ export default function ProjectPage() {
const deleteProject = useCallback(
(project: Project) => {
if (
!confirm(`Are you sure you want to delete project "${project.name}"?`)
) {
return;
}
deleteProjectMutation.mutate(project);
setProjectToDelete(project);
},
[deleteProjectMutation],
[],
);
const handleDeleteDialogOpenChange = useCallback((open: boolean) => {
if (!open) {
setProjectToDelete(null);
}
}, []);
const confirmDeleteProject = useCallback(() => {
if (!projectToDelete) return;
deleteProjectMutation.mutate(projectToDelete, {
onSettled: () => setProjectToDelete(null),
});
}, [deleteProjectMutation, projectToDelete]);
const columns = useProjectColumns();
const projects = projectsQuery.data?.items ?? [];
const total = projectsQuery.data?.totalItems ?? 0;
@@ -117,6 +137,36 @@ export default function ProjectPage() {
canSubmit={canSubmit}
isSaving={isSaving}
/>
<AlertDialog
open={Boolean(projectToDelete)}
onOpenChange={handleDeleteDialogOpenChange}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete project?</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete{' '}
<span className="font-medium text-foreground">
{projectToDelete?.name}
</span>
. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteProjectMutation.isPending}>
Cancel
</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
disabled={deleteProjectMutation.isPending}
onClick={confirmDeleteProject}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}

View File

@@ -5,7 +5,7 @@ import { Skeleton } from '@/components/ui/skeleton';
function StatSkeleton() {
return (
<div className="flex flex-col items-center rounded-lg border border-muted bg-muted/30 p-4 text-center">
<Skeleton className="mb-2 size-9 rounded-md" />
<Skeleton className="mb-2 size-9 rounded-lg" />
<Skeleton className="h-6 w-12" />
<Skeleton className="mt-2 h-3 w-20" />
</div>
@@ -14,10 +14,13 @@ function StatSkeleton() {
function DetectionLogSkeleton() {
return (
<div className="rounded-md border bg-card p-4">
<div className="mb-3 flex items-start justify-between gap-4">
<div className="rounded-lg border bg-card p-3">
<div className="flex gap-3">
<Skeleton className="size-20 shrink-0 rounded-lg" />
<div className="min-w-0 flex-1 space-y-2">
<div className="flex items-start justify-between gap-3">
<div className="space-y-2">
<Skeleton className="h-4 w-36" />
<Skeleton className="h-5 w-28" />
<Skeleton className="h-3 w-20" />
</div>
<div className="space-y-2">
@@ -25,11 +28,11 @@ function DetectionLogSkeleton() {
<Skeleton className="h-3 w-10" />
</div>
</div>
<div className="space-y-2">
<Skeleton className="h-3 w-32" />
<Skeleton className="h-3 w-44" />
</div>
</div>
</div>
);
}
@@ -38,7 +41,7 @@ export function VideoResultsSkeleton() {
<div className="space-y-8">
<div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 items-start gap-3">
<Skeleton className="size-10 rounded-md" />
<Skeleton className="size-10 rounded-lg" />
<div className="min-w-0 space-y-2">
<Skeleton className="h-7 w-60 max-w-full" />
<Skeleton className="h-3 w-80 max-w-full" />
@@ -47,10 +50,10 @@ export function VideoResultsSkeleton() {
<Skeleton className="h-8 w-20" />
</div>
<section className="overflow-hidden rounded-xl border bg-card">
<section className="overflow-hidden rounded-lg border bg-card">
<div className="border-b p-6 pb-4">
<div className="flex items-center gap-3">
<Skeleton className="size-10 rounded" />
<Skeleton className="size-10 rounded-lg" />
<div className="space-y-2">
<Skeleton className="h-5 w-44" />
<Skeleton className="h-3 w-64" />
@@ -73,7 +76,7 @@ export function VideoResultsSkeleton() {
</div>
<div className="grid grid-cols-1 gap-2 p-3 sm:grid-cols-3">
{Array.from({ length: 3 }).map((_, index) => (
<Skeleton key={index} className="h-16 w-full rounded-md" />
<Skeleton key={index} className="h-16 w-full rounded-lg" />
))}
</div>
</section>

View File

@@ -4,6 +4,7 @@ import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { videoService } from '@/services/api';
import type { VideoAnnotationFramesParams } from '@/types';
import { videoKeys } from '../queries/videoKeys';
@@ -18,6 +19,20 @@ export function useVideoResultsQuery(videoId: string | undefined) {
});
}
export function useVideoAnnotationFramesQuery(
videoId: string | undefined,
params: VideoAnnotationFramesParams,
) {
return useQuery({
queryKey: videoKeys.annotationFrames(videoId ?? '', params),
queryFn: () =>
videoService.getVideoAnnotationFrames(videoId as string, params),
enabled: Boolean(videoId),
staleTime: 1000 * 60 * 5,
gcTime: 1000 * 60 * 30,
});
}
/**
* Download the annotated video through the authenticated axios client and
* expose a local object URL that the native `<video>` element can play.
@@ -26,10 +41,10 @@ export function useVideoResultsQuery(videoId: string | undefined) {
* directly is what fixes the 401. The browser cannot attach the Bearer token to
* a media request, but axios can.
*/
export function useAnnotatedVideoQuery(url: string | undefined) {
export function useProtectedVideoQuery(url: string | undefined) {
const query = useQuery({
queryKey: videoKeys.annotatedVideo(url ?? ''),
queryFn: () => videoService.getAnnotatedVideo(url as string),
queryFn: () => videoService.getProtectedVideo(url as string),
enabled: Boolean(url),
staleTime: Infinity,
gcTime: 1000 * 60 * 30,
@@ -59,3 +74,5 @@ export function useAnnotatedVideoQuery(url: string | undefined) {
refetch: query.refetch,
};
}
export const useAnnotatedVideoQuery = useProtectedVideoQuery;

View File

@@ -2,6 +2,10 @@ export const videoKeys = {
all: ['videos'] as const,
results: () => [...videoKeys.all, 'results'] as const,
result: (videoId: string) => [...videoKeys.results(), videoId] as const,
annotationFrames: (
videoId: string,
params: { start_time_ms: number; end_time_ms: number },
) => [...videoKeys.result(videoId), 'annotation-frames', params] as const,
annotatedVideos: () => [...videoKeys.all, 'annotated'] as const,
annotatedVideo: (url: string) =>
[...videoKeys.annotatedVideos(), url] as const,

View File

@@ -62,7 +62,7 @@ export function RoleSheet({
<Sheet open={open} onOpenChange={onOpenChange}>
<SheetContent
side="right"
className="flex h-full flex-col gap-0 p-0 sm:max-w-3xl lg:max-w-2xl"
className="flex h-full w-full! flex-col gap-0 p-0 sm:max-w-3xl!"
>
<SheetHeader className="shrink-0 border-b px-6 py-4 pr-12">
<SheetTitle className="text-lg leading-none font-semibold tracking-tight">
@@ -73,7 +73,11 @@ export function RoleSheet({
</SheetDescription>
</SheetHeader>
<form noValidate onSubmit={onSubmit} className="flex min-h-0 flex-1 flex-col">
<form
noValidate
onSubmit={onSubmit}
className="flex min-h-0 flex-1 flex-col"
>
<div className="flex-1 space-y-5 overflow-y-auto px-6 py-4">
<div className="grid gap-4 md:grid-cols-2">
<FormField
@@ -125,7 +129,7 @@ export function RoleSheet({
}
>
{isPermissionsLoading ? (
<div className="rounded-md border p-6 text-muted-foreground">
<div className="rounded-lg border p-6 text-muted-foreground">
Loading permissions...
</div>
) : (

View File

@@ -11,6 +11,7 @@ import { ProjectSelect } from '@/components/lookups/ProjectSelect';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
@@ -71,14 +72,14 @@ export function SegmentDialog({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent
className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-2xl"
className="sm:max-w-2xl"
onOpenAutoFocus={(event) => event.preventDefault()}
>
<DialogHeader className="shrink-0 border-b px-6 py-4 pr-12">
<DialogTitle className="text-lg leading-none font-semibold tracking-tight">
<DialogHeader>
<DialogTitle>
{segmentId ? 'Edit Segment' : 'Create Segment'}
</DialogTitle>
<DialogDescription className="text-sm">
<DialogDescription>
Manage segment binding, chainage values, direction, and coordinates.
</DialogDescription>
</DialogHeader>
@@ -88,7 +89,7 @@ export function SegmentDialog({
onSubmit={onSubmit}
className="flex min-h-0 flex-1 flex-col"
>
<div className="max-h-[58vh] space-y-6 overflow-y-auto px-6 py-4">
<DialogBody className="space-y-6">
<section className="space-y-4">
<div className="space-y-1">
<h3 className="text-sm font-semibold">Basic details</h3>
@@ -300,9 +301,9 @@ export function SegmentDialog({
</div>
</div>
</section>
</div>
</DialogBody>
<DialogFooter className="shrink-0 border-t px-6 py-4">
<DialogFooter>
<Button
type="button"
variant="outline"

View File

@@ -4,6 +4,16 @@ import { useCallback, useState } from 'react';
import { Milestone, Plus } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Button } from '@/components/ui/button';
import type { Chainage } from '@/types';
@@ -21,6 +31,7 @@ import {
export default function SegmentPage() {
const [isDialogOpen, setIsDialogOpen] = useState(false);
const [segmentToDelete, setSegmentToDelete] = useState<Chainage | null>(null);
const { skip, setSkip, limit, setLimit } = useSegmentFilters();
const segmentsQuery = useSegmentsQuery({ skip, limit });
const projectsQuery = useProjectOptionsQuery();
@@ -75,18 +86,25 @@ export default function SegmentPage() {
const deleteSegment = useCallback(
(segment: Chainage) => {
if (
!confirm(
`Are you sure you want to delete segment "${segment.segment_name}"?`,
)
) {
return;
}
deleteSegmentMutation.mutate(segment);
setSegmentToDelete(segment);
},
[deleteSegmentMutation],
[],
);
const handleDeleteDialogOpenChange = useCallback((open: boolean) => {
if (!open) {
setSegmentToDelete(null);
}
}, []);
const confirmDeleteSegment = useCallback(() => {
if (!segmentToDelete) return;
deleteSegmentMutation.mutate(segmentToDelete, {
onSettled: () => setSegmentToDelete(null),
});
}, [deleteSegmentMutation, segmentToDelete]);
const projects = projectsQuery.data?.items ?? [];
const allPackages = allPackagesQuery.data?.items ?? [];
const segments = segmentsQuery.data?.items ?? [];
@@ -139,6 +157,36 @@ export default function SegmentPage() {
canSubmit={canSubmit}
isSaving={isSaving}
/>
<AlertDialog
open={Boolean(segmentToDelete)}
onOpenChange={handleDeleteDialogOpenChange}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete segment?</AlertDialogTitle>
<AlertDialogDescription>
This will permanently delete{' '}
<span className="font-medium text-foreground">
{segmentToDelete?.segment_name}
</span>
. This action cannot be undone.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={deleteSegmentMutation.isPending}>
Cancel
</AlertDialogCancel>
<AlertDialogAction
variant="destructive"
disabled={deleteSegmentMutation.isPending}
onClick={confirmDeleteSegment}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}

View File

@@ -13,6 +13,7 @@ import { FormField, PhoneInput, SelectPopover } from '@/components/form';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
@@ -98,12 +99,12 @@ export function TenantSheet({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-3xl">
<DialogHeader className="shrink-0 border-b px-6 py-4 pr-12">
<DialogTitle className="text-lg leading-none font-semibold tracking-tight">
<DialogContent className="sm:max-w-3xl">
<DialogHeader>
<DialogTitle>
{tenantId ? 'Edit Tenant' : 'Create Tenant'}
</DialogTitle>
<DialogDescription className="text-sm">
<DialogDescription>
Bind a client and subscription plan, then invite the tenant
administrator.
</DialogDescription>
@@ -114,7 +115,7 @@ export function TenantSheet({
onSubmit={onSubmit}
className="flex min-h-0 flex-1 flex-col"
>
<div className="max-h-[50vh] space-y-5 overflow-y-auto px-6 py-4">
<DialogBody className="space-y-5">
<div className="space-y-1">
<p>Basic Information</p>
<p className="text-muted-foreground">
@@ -227,7 +228,7 @@ export function TenantSheet({
id="tenant-description"
placeholder="North zone operations"
{...register('description')}
className="min-h-20 w-full rounded-md border border-input bg-background px-3 py-2 outline-none focus-visible:border-ring"
className="min-h-20 w-full rounded-lg border border-input bg-background px-3 py-2 outline-none focus-visible:border-ring"
/>
</FormField>
</div>
@@ -314,7 +315,7 @@ export function TenantSheet({
</div>
</>
) : adminEmail ? (
<div className="rounded-md border bg-muted/40 p-4 text-muted-foreground">
<div className="rounded-lg border bg-muted/40 p-4 text-muted-foreground">
Admin invitation details cannot be changed after tenant
creation.
<p className="mt-1 text-foreground">
@@ -322,9 +323,9 @@ export function TenantSheet({
</p>
</div>
) : null}
</div>
</DialogBody>
<DialogFooter className="shrink-0 border-t px-6 py-4">
<DialogFooter>
<Button
type="button"
variant="outline"

View File

@@ -1,82 +1,71 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Timeline, TimelineItem } from '@/components/ui/timeline';
function TimelineEntrySkeleton({
index,
isLast,
}: {
index: number;
isLast: boolean;
}) {
return (
<TimelineItem
layout="left"
isLast={isLast}
opposite={
<div className="space-y-2">
<Skeleton className="ml-auto h-4 w-16" />
<Skeleton className="ml-auto h-3 w-12" />
</div>
}
marker={<Skeleton className="size-4 rounded-full" />}
>
<div
className={
index === 0
? 'rounded-lg border border-dashed border-primary/25 bg-primary/5 px-4 py-3.5'
: 'rounded-lg border bg-card p-4'
}
>
{index === 0 ? <Skeleton className="h-5 w-28 rounded-lg" /> : null}
<Skeleton className={index === 0 ? 'mt-3 h-4 w-44' : 'h-4 w-44'} />
{index === 0 ? (
<Skeleton className="mt-2 h-3 w-full max-w-md" />
) : (
<>
<div className="mt-3 flex items-center gap-3">
<Skeleton className="size-9 rounded-full" />
<div className="min-w-0 flex-1 space-y-2">
<Skeleton className="h-4 w-36" />
<Skeleton className="h-3 w-48 max-w-full" />
</div>
</div>
<Skeleton className="mt-3 h-16 w-full rounded-lg" />
</>
)}
</div>
</TimelineItem>
);
}
export function TicketClassContentSkeleton() {
return (
<div className="space-y-5" aria-label="Loading defect class details">
<Card>
<CardHeader className="sm:grid-cols-[1fr_auto]">
<Skeleton className="h-5 w-36" />
<Skeleton className="h-3 w-32 sm:col-start-2 sm:row-start-1" />
</CardHeader>
<CardContent className="space-y-5">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
{Array.from({ length: 2 }).map((_, index) => (
<div key={index} className="space-y-1">
<Skeleton className="h-3 w-20" />
<Skeleton className="h-4 w-36" />
<div className="space-y-4" aria-label="Loading defect class details">
<div className="flex items-center gap-2">
<Skeleton className="size-5 rounded-lg" />
<Skeleton className="h-5 w-56 max-w-full" />
</div>
))}
</div>
<div className="space-y-2">
<Skeleton className="h-3 w-24" />
<div className="rounded-lg border bg-muted/15 px-4 py-3">
<Skeleton className="h-4 w-full" />
<Skeleton className="mt-2 h-4 w-3/4" />
</div>
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<Skeleton className="h-5 w-40" />
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<Skeleton className="aspect-video w-full rounded-md" />
<Skeleton className="aspect-video w-full rounded-md" />
</CardContent>
</Card>
<Card>
<CardHeader>
<Skeleton className="h-5 w-32" />
</CardHeader>
<CardContent>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-5">
{Array.from({ length: 5 }).map((_, index) => (
<div key={index} className="space-y-2 rounded-lg border p-2">
<Skeleton className="aspect-4/3 w-full rounded-lg" />
<Skeleton className="h-3 w-16" />
</div>
))}
</div>
</CardContent>
</Card>
<Card>
<CardHeader>
<Skeleton className="h-5 w-56" />
</CardHeader>
<CardContent className="pl-5.5">
<Timeline>
{Array.from({ length: 3 }).map((_, index) => (
<div key={index} className="relative flex gap-4 pb-8 last:pb-0">
{index < 2 ? (
<span className="absolute top-6 left-2.75 h-[calc(100%-10px)] w-px bg-border" />
) : null}
<Skeleton className="relative z-10 mt-0.5 size-6 shrink-0 rounded-full" />
<div className="min-w-0 flex-1 space-y-3">
<div className="flex flex-wrap items-center gap-3">
<Skeleton className="h-4 w-44" />
<Skeleton className="h-3 w-28" />
</div>
<Skeleton className="h-3 w-56" />
<Skeleton className="h-12 w-full" />
</div>
</div>
<TimelineEntrySkeleton
key={index}
index={index}
isLast={index === 2}
/>
))}
</CardContent>
</Card>
</Timeline>
</div>
);
}
@@ -86,7 +75,7 @@ export function TicketClassActionsSkeleton() {
<Card aria-label="Loading defect class actions">
<CardHeader>
<div className="flex items-center gap-2">
<Skeleton className="size-4 rounded" />
<Skeleton className="size-4 rounded-lg" />
<Skeleton className="h-5 w-32" />
</div>
</CardHeader>

View File

@@ -0,0 +1,281 @@
'use client';
import { useEffect, useMemo, useState } from 'react';
import { AlertTriangle, ChevronLeft, ChevronRight } from 'lucide-react';
import DetectionLocationMap from '@/components/map/detectionLocationMap';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import AnnotatedDetectionImage from '@/components/video/annotatedDetectionImage';
import { getDefectVisual } from '@/constants/defectVisualConfig';
import { cn } from '@/lib/utils';
import { useTicketClassDetectionsQuery } from '../../hooks/useTicketQueries';
interface TicketClassDetectionPreviewProps {
videoId?: string | null;
defectClassName: string;
displayName: string;
totalCount?: number;
}
function DetectionMetadataBar({
items,
}: {
items: { label: string; value: string | number }[];
}) {
return (
<div className="rounded-lg bg-muted/40 px-4 py-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 sm:divide-x sm:divide-border/70">
{items.map((item, index) => (
<div
key={item.label}
className={cn(
'space-y-1',
index === 0 && 'sm:pr-4',
index === 1 && 'sm:px-4',
index === 2 && 'sm:pl-4',
)}
>
<p className="text-xs text-muted-foreground">{item.label}</p>
<div className="text-sm font-semibold text-foreground">
{item.value}
</div>
</div>
))}
</div>
</div>
);
}
function TicketClassDetectionPreviewSkeleton() {
return (
<>
<div className="grid grid-cols-1 gap-4 xl:grid-cols-2">
<div className="min-w-0 space-y-2">
<Skeleton className="h-3 w-24" />
<Skeleton className="aspect-video w-full rounded-lg" />
</div>
<div className="min-w-0 space-y-2">
<Skeleton className="h-3 w-28" />
<Skeleton
className="w-full rounded-lg"
style={{ aspectRatio: '16 / 9' }}
/>
</div>
</div>
<div className="rounded-lg bg-muted/40 px-4 py-4">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-3 sm:divide-x sm:divide-border/70">
{Array.from({ length: 3 }).map((_, index) => (
<div
key={index}
className={cn(
'space-y-1',
index === 0 && 'sm:pr-4',
index === 1 && 'sm:px-4',
index === 2 && 'sm:pl-4',
)}
>
<Skeleton className="h-3 w-16" />
<Skeleton className="h-4 w-20" />
</div>
))}
</div>
</div>
</>
);
}
export function TicketClassDetectionPreview({
videoId,
defectClassName,
displayName,
totalCount,
}: TicketClassDetectionPreviewProps) {
const [currentIndex, setCurrentIndex] = useState(0);
const visual = getDefectVisual(defectClassName);
const IssueIcon = visual.icon;
useEffect(() => {
setCurrentIndex(0);
}, [defectClassName]);
const queryParams = useMemo(
() => ({
class_name: defectClassName,
skip: currentIndex,
limit: 1,
sort: 'timestamp_asc',
}),
[currentIndex, defectClassName],
);
const detectionsQuery = useTicketClassDetectionsQuery(
videoId ?? undefined,
queryParams,
);
const detectionResult = detectionsQuery.data;
const activeDetection = detectionResult?.items[0];
const detectionCount = detectionResult?.total ?? totalCount ?? 0;
const mediaAspectRatio =
detectionResult &&
detectionResult.video_width > 0 &&
detectionResult.video_height > 0
? `${detectionResult.video_width} / ${detectionResult.video_height}`
: '16 / 9';
useEffect(() => {
if (detectionCount === 0 && currentIndex !== 0) {
setCurrentIndex(0);
return;
}
if (detectionCount > 0 && currentIndex > detectionCount - 1) {
setCurrentIndex(detectionCount - 1);
}
}, [currentIndex, detectionCount]);
const isNavigationDisabled =
detectionCount === 0 || detectionsQuery.isLoading;
return (
<div className="space-y-4">
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 items-center gap-3">
<span
className={cn(
'flex size-10 shrink-0 self-start items-center justify-center rounded-lg',
visual.cardClassName,
)}
>
<IssueIcon className={cn('size-5', visual.colorClassName)} />
</span>
<div className="min-w-0 space-y-1">
<div className="flex min-w-0 flex-wrap items-center gap-2">
<h3>{displayName}</h3>
<Badge
variant="secondary"
className={cn(
'rounded-lg',
visual.cardClassName,
visual.colorClassName,
)}
>
{detectionCount} Detections
</Badge>
</div>
<p className="text-muted-foreground">
Review detections in ascending timestamp order.
</p>
</div>
</div>
<div className="flex items-center gap-2 self-start sm:self-auto">
<Button
type="button"
variant="secondary"
onClick={() =>
setCurrentIndex((index) =>
detectionCount === 0
? 0
: (index - 1 + detectionCount) % detectionCount,
)
}
disabled={isNavigationDisabled}
aria-label="Previous detection"
>
<ChevronLeft className="size-4" />
</Button>
<div className="min-w-16 text-center text-sm font-medium text-foreground">
{detectionCount === 0
? '0 of 0'
: `${currentIndex + 1} of ${detectionCount}`}
</div>
<Button
type="button"
variant="secondary"
onClick={() =>
setCurrentIndex((index) =>
detectionCount === 0 ? 0 : (index + 1) % detectionCount,
)
}
disabled={isNavigationDisabled}
aria-label="Next detection"
>
<ChevronRight className="size-4" />
</Button>
</div>
</div>
{detectionsQuery.isLoading && !detectionsQuery.data ? (
<TicketClassDetectionPreviewSkeleton />
) : detectionsQuery.isError ? (
<div className="rounded-lg border border-dashed border-destructive/40 bg-destructive/5 px-4 py-8 text-center">
<div className="flex flex-col items-center gap-2">
<AlertTriangle className="size-6 text-destructive" />
<p className="text-sm font-medium text-destructive">
Failed to load detection preview.
</p>
<Button
type="button"
variant="outline"
size="sm"
onClick={() => void detectionsQuery.refetch()}
>
Retry
</Button>
</div>
</div>
) : !activeDetection || !detectionResult ? (
<div className="rounded-lg border border-dashed bg-muted/20 px-4 py-10 text-center text-sm text-muted-foreground">
No detections are available for this issue.
</div>
) : (
<>
<div className="grid grid-cols-1 items-start gap-4 xl:grid-cols-2">
<div className="min-w-0 space-y-2">
<p className="text-muted-foreground">Detection Image</p>
<div className="overflow-hidden rounded-lg">
<AnnotatedDetectionImage
detection={activeDetection}
videoWidth={detectionResult.video_width}
videoHeight={detectionResult.video_height}
/>
</div>
</div>
<DetectionLocationMap
className="min-w-0"
latitude={activeDetection.location.latitude}
longitude={activeDetection.location.longitude}
label={`${displayName} - Frame ${activeDetection.frame.number}`}
title="Location on Map"
variant="plain"
aspectRatio={mediaAspectRatio}
showCoordinates={false}
/>
</div>
<DetectionMetadataBar
items={[
{
label: 'Confidence',
value: `${Math.round(activeDetection.detection.confidence * 100)}%`,
},
{
label: 'Frame',
value: activeDetection.frame.number,
},
{
label: 'Timestamp',
value: `${activeDetection.frame.timestamp_seconds}s`,
},
]}
/>
</>
)}
</div>
);
}

View File

@@ -2,22 +2,26 @@
import { useEffect, useMemo, useState } from 'react';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { Component } from 'lucide-react';
import { Component, ListChecks } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { DEFECT_CLASS_STATUS_CONFIG } from '@/constants/defectClassStatus';
import { cn } from '@/lib/utils';
import type { TicketOverviewDetail } from '@/types';
import { useTicketDefectClassesQuery } from '../../hooks/useTicketQueries';
import { TicketClassDetectionPreview } from './TicketClassDetectionPreview';
interface TicketDefectClassTabsProps {
ticketId: string;
ticket?: TicketOverviewDetail;
}
export function TicketDefectClassTabs({
ticketId,
ticket,
}: TicketDefectClassTabsProps) {
const router = useRouter();
const pathname = usePathname();
@@ -56,20 +60,32 @@ export function TicketDefectClassTabs({
setSelectedClass(className);
router.replace(`${pathname}?${nextParams.toString()}`, { scroll: false });
};
const selectedIssue = ticket?.ai_result.detections_by_class.find(
(item) => item.class_name === selectedClass,
);
const selectedClassItem = defectClasses.find(
(item) => item.class_name === selectedClass,
);
const previewDisplayName =
selectedIssue?.display_name ??
selectedClassItem?.display_name ??
selectedClass ??
'Detection';
const previewVideoId = ticket?.video_id ?? defectClassesQuery.data?.video_id;
if (defectClassesQuery.isLoading) {
return (
<Card className="w-full">
<CardHeader>
<div className="h-5 w-24 animate-pulse rounded bg-muted" />
</CardHeader>
<CardContent className="flex flex-col gap-2">
<Card className="w-full rounded-lg">
<CardContent className="space-y-4 p-5">
<div className="h-5 w-24 animate-pulse rounded-lg bg-muted" />
<div className="flex flex-col gap-2">
{Array.from({ length: 3 }).map((_, index) => (
<div
key={index}
className="h-11 w-full animate-pulse rounded-lg bg-muted"
/>
))}
</div>
</CardContent>
</Card>
);
@@ -87,18 +103,19 @@ export function TicketDefectClassTabs({
className="w-full"
>
<Card className="w-full">
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<span>Issues</span>
<CardContent className="grid gap-0 p-0 lg:grid-cols-[minmax(220px,280px)_1fr] lg:divide-x lg:divide-border">
<div className="space-y-4 px-5">
<div className="flex items-center gap-2">
<ListChecks className="size-5 shrink-0 text-primary" />
<h2 className="text-base font-semibold">Detected Issues</h2>
<Badge
variant="secondary"
className="min-w-5 min-h-5 justify-center rounded-full"
>
{defectClasses.length}
</Badge>
</CardTitle>
</CardHeader>
<CardContent>
</div>
<TabsList className="flex h-auto w-full flex-col items-stretch gap-2 bg-transparent p-0">
{defectClasses.map((item) => {
const statusConfig =
@@ -109,7 +126,7 @@ export function TicketDefectClassTabs({
key={item.class_name}
value={item.class_name}
className={cn(
'group h-auto w-full flex-none items-center justify-between! gap-2 rounded-lg border border-border bg-muted/30 px-3 py-2.5 text-sm text-muted-foreground shadow-none after:hidden',
'group h-auto w-full flex-none items-center justify-between! gap-2 rounded-lg border bg-muted/30 px-3 py-2.5 text-sm text-muted-foreground shadow-none after:hidden',
'data-[state=active]:bg-muted data-[state=active]:text-foreground',
)}
>
@@ -118,7 +135,7 @@ export function TicketDefectClassTabs({
</span>
<Badge
className={cn(
'shrink-0 gap-1.5 rounded-full border-0 px-2.5 py-1 text-xs font-medium',
'shrink-0 rounded-full',
statusConfig.badgeClassName,
)}
>
@@ -129,6 +146,16 @@ export function TicketDefectClassTabs({
);
})}
</TabsList>
</div>
<div className="min-w-0 px-5">
<TicketClassDetectionPreview
videoId={previewVideoId}
defectClassName={selectedClass}
displayName={previewDisplayName}
totalCount={selectedIssue?.count}
/>
</div>
</CardContent>
</Card>
</Tabs>

View File

@@ -4,9 +4,6 @@ import { ArrowLeft } from 'lucide-react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { SparkleButton } from '@/components/ui/sparkle-button';
import { PERMISSIONS } from '@/constants/permissions';
import { PermissionGuard } from '@/guards';
import type { TicketOverviewDetail } from '@/types';
export function TicketDetailHeader({
@@ -15,7 +12,7 @@ export function TicketDetailHeader({
ticket: TicketOverviewDetail;
}) {
const router = useRouter();
const ticketLabel = ticket.ticket_name;
const ticketLabel = ticket.ticket_name || ticket.id;
return (
<div className="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
@@ -25,20 +22,8 @@ export function TicketDetailHeader({
</div>
<div className="flex shrink-0 items-center gap-2">
{ticket.video_id ? (
<PermissionGuard permissions={PERMISSIONS.TICKET.ASSIGN}>
<SparkleButton
className="h-10 min-w-36 px-5"
onClick={() => router.push(`/results/${ticket.video_id}`)}
>
View Analysis
</SparkleButton>
</PermissionGuard>
) : null}
<Button
variant="outline"
size="sm"
variant="secondary"
onClick={() => router.push('/ticket')}
>
<ArrowLeft className="size-4" />

View File

@@ -2,87 +2,84 @@
import { History, MessageSquareText } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { PersonInfo } from '@/components/person-avatar';
import { Badge } from '@/components/ui/badge';
import { Timeline, TimelineItem } from '@/components/ui/timeline';
import { cn } from '@/lib/utils';
import type { TicketDetail, TicketHistoryItem, TicketStatus } from '@/types';
import { formatDate } from '@/utils/date';
import type { TicketDetail, TicketHistoryItem, TicketHistorySource } from '@/types';
import { formatTimelineDateTime } from '@/utils/date';
import { getPersonLabel } from '@/utils/person';
function getActorLabel(item: TicketHistoryItem) {
return item.actor?.name || item.actor?.email || 'System';
}
function getLifecycleTitle(status: TicketStatus) {
const titles: Record<TicketStatus, string> = {
unassigned: 'Awaiting Assignment',
assigned: 'Dispatched to Maintenance',
under_review: 'Maintenance Finalized',
closed: 'Ticket Closed',
};
return titles[status];
}
function HistoryEntry({
item,
isLast,
}: {
item: TicketHistoryItem;
isLast: boolean;
}) {
const isClosed = item.to_status === 'closed';
function TimelineDate({ value }: { value: string }) {
const { date, time } = formatTimelineDateTime(value);
return (
<div className="relative flex gap-4 pb-8 last:pb-0">
{!isLast ? (
<span
aria-hidden
className="absolute top-6 left-2.75 h-[calc(100%-10px)] w-px bg-border"
/>
) : null}
<span
aria-hidden
className={cn(
'relative z-10 mt-0.5 flex size-6 shrink-0 items-center justify-center rounded-full border-2 bg-background',
isClosed
? 'border-primary bg-primary text-primary-foreground'
: 'border-primary/60',
)}
>
<span
className={cn(
'size-2 rounded-full bg-primary',
isClosed &&
'h-1.5 w-2.5 -rotate-45 rounded-none border-b-2 border-l-2 border-current bg-transparent',
)}
/>
</span>
<div className="min-w-0 flex-1 space-y-2">
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-1">
<h3 className="text-sm font-semibold text-foreground">
{getLifecycleTitle(item.to_status)}
</h3>
<time
dateTime={item.created_at}
className="text-xs font-semibold text-muted-foreground tabular-nums"
>
{formatDate(item.created_at)}
<time dateTime={value} className="block tabular-nums">
<span className="block text-sm font-semibold text-foreground">{date}</span>
<span className="block text-xs text-muted-foreground">{time}</span>
</time>
</div>
);
}
<p className="text-xs font-medium text-muted-foreground">
Updated By{' '}
<span className="text-foreground/90">{getActorLabel(item)}</span>
function HistoryNote({ item }: { item: TicketHistoryItem }) {
const noteText = item.note?.text?.trim();
if (!noteText) return null;
return (
<div className="mt-3 rounded-lg border border-amber-300/80 bg-amber-50/90 px-3 py-2.5 dark:border-amber-500/30 dark:bg-amber-500/10">
<div className="flex items-center gap-1.5 text-xs font-medium text-amber-900 dark:text-amber-200">
<MessageSquareText className="size-3.5 shrink-0 text-amber-700 dark:text-amber-300" />
<span>
Note by {getPersonLabel(item.note?.author ?? item.actor)}
</span>
</div>
<p className="mt-1.5 text-sm leading-relaxed text-amber-950/80 dark:text-amber-100/90">
{noteText}
</p>
{item.note ? (
<div className="flex gap-2 rounded-md border border-border bg-background px-3 py-2 text-sm leading-relaxed text-foreground">
<MessageSquareText className="mt-0.5 size-4 shrink-0 text-primary" />
<p>{item.note}</p>
</div>
);
}
function getSourceLabel(source: TicketHistorySource) {
return source === 'system' ? 'System Generated' : 'User Action';
}
function SystemHistoryEntry({ item }: { item: TicketHistoryItem }) {
const noteText = item.note?.text?.trim();
return (
<div className="rounded-lg border border-dashed border-primary/25 bg-primary/5 px-4 py-3.5">
<Badge
className="rounded-lg px-2.5 py-0.5 text-[10px] font-semibold tracking-wider uppercase"
>
{getSourceLabel(item.source)}
</Badge>
<h3 className="mt-2 text-sm font-semibold text-foreground">{item.title}</h3>
{noteText ? (
<p className="mt-1 text-sm leading-relaxed text-muted-foreground">
{noteText}
</p>
) : null}
</div>
);
}
function UserHistoryEntry({ item }: { item: TicketHistoryItem }) {
const noteText = item.note?.text?.trim();
const isAssigned = item.event_type === 'assigned';
return (
<div className="rounded-lg border bg-card p-4">
<h3 className="mb-3 text-sm font-semibold text-foreground">{item.title}</h3>
<PersonInfo person={item.actor} />
{isAssigned && item.target_user ? (
<div className="mt-3 space-y-1">
<p className="text-xs text-muted-foreground">Assigned to</p>
<PersonInfo person={item.target_user} />
</div>
) : null}
{noteText ? <HistoryNote item={item} /> : null}
</div>
);
}
@@ -91,25 +88,41 @@ export function TicketHistoryCard({ ticket }: { ticket: TicketDetail }) {
const history = ticket.history ?? [];
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<div className="space-y-4">
<div className="flex items-center gap-2">
<History className="size-5 text-primary" />
Audit & Lifecycle Timeline
</CardTitle>
</CardHeader>
<CardContent>
{history.length ? (
<div className="pl-0.5">
{history.map((item, index) => (
<HistoryEntry
key={item.id}
item={item}
isLast={index === history.length - 1}
/>
))}
<h2 className="text-base font-semibold">Audit & Lifecycle Timeline</h2>
</div>
{history.length ? (
<Timeline>
{history.map((item, index) => (
<TimelineItem
key={item.id}
layout="left"
isLast={index === history.length - 1}
opposite={<TimelineDate value={item.created_at} />}
marker={
<span className="flex size-4 items-center justify-center rounded-full border bg-background shadow-xs">
<span
className={cn(
'size-1.5 rounded-full',
item.source === 'system'
? 'bg-muted-foreground'
: 'bg-primary',
)}
/>
</span>
}
>
{item.source === 'system' ? (
<SystemHistoryEntry item={item} />
) : (
<UserHistoryEntry item={item} />
)}
</TimelineItem>
))}
</Timeline>
) : (
<div className="rounded-lg border border-dashed border-border/80 bg-muted/10 px-4 py-8 text-center">
<p className="text-sm font-medium text-muted-foreground">
@@ -117,7 +130,6 @@ export function TicketHistoryCard({ ticket }: { ticket: TicketDetail }) {
</p>
</div>
)}
</CardContent>
</Card>
</div>
);
}

View File

@@ -0,0 +1,68 @@
'use client';
import { useRef } from 'react';
import type { MediaPlayerInstance } from '@vidstack/react';
import { useProtectedVideoQuery } from '@/app/(modules)/results/hooks/useVideoResults';
import AnnotatedVideoPlayer from '@/components/video/annotatedVideoPlayer';
import { useVideoAnnotationPlayback } from '@/components/video/useVideoAnnotationPlayback';
import type { TicketOverviewDetail } from '@/types';
type TicketInlineAnalysisVideoProps = {
ticket: TicketOverviewDetail;
};
export function TicketInlineAnalysisVideo({
ticket,
}: TicketInlineAnalysisVideoProps) {
const videoRef = useRef<MediaPlayerInstance | null>(null);
const videoId = ticket.video_id ?? ticket.video?.id ?? undefined;
const sourceUrl = ticket.video?.url ?? undefined;
const fps = ticket.video_metadata?.fps ?? 0;
const videoWidth = ticket.video_metadata?.resolution.width ?? 0;
const videoHeight = ticket.video_metadata?.resolution.height ?? 0;
const {
visibleDetections,
handleSeeked,
handleTimeUpdate,
handleVideoFrame,
} = useVideoAnnotationPlayback({
videoId,
logs: [],
fps,
videoRef,
});
const {
videoUrl,
isLoading: isVideoLoading,
isError: isVideoError,
refetch: refetchVideo,
} = useProtectedVideoQuery(sourceUrl);
if (!videoId || !sourceUrl) {
return (
<div className="rounded-lg border border-dashed bg-muted/20 px-4 py-8 text-sm text-muted-foreground">
Analysis video is unavailable for this ticket.
</div>
);
}
return (
<div className="space-y-2">
<AnnotatedVideoPlayer
videoRef={videoRef}
logs={[]}
visibleDetections={visibleDetections}
videoWidth={videoWidth}
videoHeight={videoHeight}
videoUrl={videoUrl}
isLoading={isVideoLoading}
isError={isVideoError}
onRetry={() => void refetchVideo()}
onTimeUpdate={handleTimeUpdate}
onVideoFrame={handleVideoFrame}
onSeeked={handleSeeked}
/>
</div>
);
}

View File

@@ -1,28 +1,42 @@
'use client';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketActor, TicketOverviewDetail } from '@/types';
import {
Activity,
CalendarDays,
Clock3,
Gauge,
MapPin,
Monitor,
UserRound,
Play
} from 'lucide-react';
import { useState } from 'react';
function formatCreatedDate(value: string | null | undefined) {
if (!value) return '-';
return new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium' }).format(
new Date(value),
);
}
import {
Card,
CardAction,
CardContent,
CardHeader,
CardTitle,
} from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { getDefectVisual } from '@/constants/defectVisualConfig';
import { PERMISSIONS } from '@/constants/permissions';
import { PermissionGuard } from '@/guards';
import { cn } from '@/lib/utils';
import type { TicketOverviewDetail } from '@/types';
import { formatDate } from '@/utils/date';
import { TicketInlineAnalysisVideo } from './TicketInlineAnalysisVideo';
function getInitials(person: TicketActor | null | undefined) {
const source = person?.name || person?.email || '?';
return source
.split(/[\s@._-]+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part.charAt(0).toUpperCase())
.join('');
}
function getPersonLabel(person: TicketActor | null | undefined) {
return person?.name || person?.email || '-';
}
type IconComponent = React.ComponentType<{ className?: string }>;
function MetaLabel({ children }: { children: React.ReactNode }) {
return (
@@ -36,29 +50,6 @@ function MetaValue({ children }: { children: React.ReactNode }) {
return <p className="text-sm font-semibold text-foreground">{children}</p>;
}
function PersonMetaValue({
person,
accentClassName = 'bg-primary/15 text-primary',
}: {
person: TicketActor | null | undefined;
accentClassName?: string;
}) {
if (!person) {
return <MetaValue>-</MetaValue>;
}
return (
<div className="flex min-w-0 items-center gap-2">
<span
className={`flex size-5 shrink-0 items-center justify-center rounded-full text-[10px] font-bold ${accentClassName}`}
>
{getInitials(person)}
</span>
<p className="truncate text-sm font-medium">{getPersonLabel(person)}</p>
</div>
);
}
function OverviewField({
label,
children,
@@ -67,43 +58,193 @@ function OverviewField({
children: React.ReactNode;
}) {
return (
<div className="space-y-1">
<div className="min-w-0 space-y-1">
<MetaLabel>{label}</MetaLabel>
{children}
</div>
);
}
function SummaryCard({
label,
value,
colorClassName,
cardClassName,
}: {
label: string;
value: number;
colorClassName: string;
cardClassName: string;
}) {
return (
<div
className={cn(
'rounded-lg bg-muted/40 p-4 hover:scale-105 transition-transform ease-in-out',
cardClassName,
)}
>
<p className={cn('text-2xl font-bold tracking-tight', colorClassName)}>
{value}
</p>
<p className="mt-2 truncate text-xs font-semibold text-foreground">
{label}
</p>
<p className="mt-0.5 text-[11px] text-muted-foreground">Detected</p>
</div>
);
}
function VideoMetric({
icon: Icon,
label,
}: {
icon: IconComponent;
label: string;
}) {
return (
<div className="flex items-center justify-center gap-2 font-medium">
<Icon className="size-4 text-muted-foreground" />
<span>{label}</span>
</div>
);
}
export function TicketOverviewCard({
ticket,
}: {
ticket: TicketOverviewDetail;
}) {
const [isAnalysisOpen, setIsAnalysisOpen] = useState(false);
const videoMetadata = ticket.video_metadata;
const duration =
typeof videoMetadata?.duration_seconds === 'number'
? `${Math.floor(videoMetadata.duration_seconds / 60)}:${Math.floor(
videoMetadata.duration_seconds % 60,
)
.toString()
.padStart(2, '0')}`
: null;
const chainageName =
ticket.location?.chainage?.name || ticket.chainage_name || null;
const packageName = ticket.location?.package?.name || null;
const locationLabel =
[chainageName, packageName].filter(Boolean).join(', ') || null;
const uploadedOn =
ticket.timestamps?.created_at || ticket.ai_result.completed_at || null;
const uploaderName = ticket.uploader?.name || null;
const analysisVideoId = ticket.video_id || ticket.video?.id || null;
const videoName = ticket.video?.name || null;
const analysisTitle = videoName || ticket.ticket_name || 'Analysis Video';
const hasVideoMetrics = Boolean(
videoMetadata?.fps || duration || videoMetadata?.resolution?.label,
);
return (
<div className="space-y-5">
{uploadedOn || uploaderName || locationLabel ? (
<Card>
<CardHeader>
<CardTitle>Overview</CardTitle>
</CardHeader>
<CardContent className="grid grid-cols-2 gap-x-4 gap-y-6 md:grid-cols-4">
<OverviewField label="Detection Count">
<MetaValue>{ticket.ai_result.detection_count} Occurrences</MetaValue>
<CardContent className="grid gap-4 py-4 sm:grid-cols-3 sm:divide-x">
{uploadedOn ? (
<div className="flex items-center gap-3 sm:pr-4">
<CalendarDays className="size-5 shrink-0 text-muted-foreground" />
<OverviewField label="Uploaded On">
<MetaValue>{formatDate(uploadedOn)}</MetaValue>
</OverviewField>
<OverviewField label="Chainage">
<MetaValue>{ticket.chainage_name}</MetaValue>
</OverviewField>
</div>
) : null}
{uploaderName ? (
<div className="flex items-center gap-3 sm:px-4">
<UserRound className="size-5 shrink-0 text-muted-foreground" />
<OverviewField label="Uploaded By">
<PersonMetaValue person={ticket.uploader} />
<MetaValue>{uploaderName}</MetaValue>
</OverviewField>
<OverviewField label="Created Date">
<MetaValue>
{formatCreatedDate(ticket.timestamps.created_at)}
</MetaValue>
</div>
) : null}
{locationLabel ? (
<div className="flex items-center gap-3 sm:pl-4">
<MapPin className="size-5 shrink-0 text-muted-foreground" />
<OverviewField label="Location">
<MetaValue>{locationLabel}</MetaValue>
</OverviewField>
</div>
) : null}
</CardContent>
</Card>
) : null}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Activity className="size-5 text-primary" />
AI Detection Summary
</CardTitle>
{analysisVideoId ? (
<CardAction>
<PermissionGuard permissions={PERMISSIONS.TICKET.ASSIGN}>
<Button
variant="secondary"
onClick={() => setIsAnalysisOpen(true)}
>
<Play className="mr-2 size-4" />
View Video
</Button>
</PermissionGuard>
</CardAction>
) : null}
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-6">
<SummaryCard
label="Total Detections"
value={ticket.ai_result.detection_count}
colorClassName="text-violet-600"
cardClassName="bg-violet-500/8"
/>
{ticket.ai_result.detections_by_class.map((item) => {
const visual = getDefectVisual(item.class_name);
return (
<SummaryCard
key={item.class_name}
label={item.display_name}
value={item.count}
colorClassName={visual.colorClassName}
cardClassName={visual.cardClassName}
/>
);
})}
</div>
{hasVideoMetrics ? (
<div className="grid gap-3 rounded-lg bg-muted/35 px-4 py-3 text-sm sm:grid-cols-3">
{videoMetadata?.fps ? (
<VideoMetric icon={Gauge} label={`${videoMetadata.fps} FPS`} />
) : null}
{duration ? (
<VideoMetric icon={Clock3} label={`${duration} Duration`} />
) : null}
{videoMetadata?.resolution?.label ? (
<VideoMetric
icon={Monitor}
label={`${videoMetadata.resolution.label} Resolution`}
/>
) : null}
</div>
) : null}
</CardContent>
</Card>
<Dialog open={isAnalysisOpen} onOpenChange={setIsAnalysisOpen}>
<DialogContent className="sm:max-w-5xl">
<DialogHeader>
<DialogTitle>{analysisTitle}</DialogTitle>
<DialogDescription>
Video analysis with annotation overlay
</DialogDescription>
</DialogHeader>
<DialogBody>
<TicketInlineAnalysisVideo ticket={ticket} />
</DialogBody>
</DialogContent>
</Dialog>
</div>
);
}

View File

@@ -1,11 +1,29 @@
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import {
Card,
CardAction,
CardContent,
CardHeader,
} from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
function OverviewSkeletonField() {
function OverviewMetaSkeletonField({ className }: { className?: string }) {
return (
<div className="space-y-2">
<div className={`flex items-center gap-3 ${className ?? ''}`}>
<Skeleton className="size-5 shrink-0 rounded-lg" />
<div className="min-w-0 space-y-2">
<Skeleton className="h-3 w-24" />
<Skeleton className="h-4 w-32" />
<Skeleton className="h-4 w-32 max-w-full" />
</div>
</div>
);
}
function SummarySkeletonCard() {
return (
<div className="rounded-lg bg-muted/40 p-4">
<Skeleton className="h-7 w-10" />
<Skeleton className="mt-3 h-3 w-24 max-w-full" />
<Skeleton className="mt-2 h-3 w-16" />
</div>
);
}
@@ -27,15 +45,45 @@ export function TicketOverviewHeaderSkeleton() {
export function TicketOverviewCardSkeleton() {
return (
<Card aria-label="Loading ticket overview">
<CardHeader>
<Skeleton className="h-4 w-20" />
</CardHeader>
<CardContent className="grid grid-cols-2 gap-x-4 gap-y-6 md:grid-cols-4">
{Array.from({ length: 4 }).map((_, index) => (
<OverviewSkeletonField key={index} />
))}
<div className="space-y-5" aria-label="Loading ticket overview">
<Card>
<CardContent className="grid gap-4 py-4 sm:grid-cols-3 sm:divide-x">
<OverviewMetaSkeletonField className="sm:pr-4" />
<OverviewMetaSkeletonField className="sm:px-4" />
<OverviewMetaSkeletonField className="sm:pl-4" />
</CardContent>
</Card>
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Skeleton className="size-5 rounded-lg" />
<Skeleton className="h-5 w-40" />
</div>
<CardAction>
<Skeleton className="h-9 w-28" />
</CardAction>
</CardHeader>
<CardContent className="space-y-4">
<div className="grid grid-cols-2 gap-3 lg:grid-cols-3 xl:grid-cols-6">
{Array.from({ length: 6 }).map((_, index) => (
<SummarySkeletonCard key={index} />
))}
</div>
<div className="grid gap-3 rounded-lg bg-muted/35 px-4 py-3 sm:grid-cols-3">
{Array.from({ length: 3 }).map((_, index) => (
<div
key={index}
className="flex items-center justify-center gap-2"
>
<Skeleton className="size-4 rounded-lg" />
<Skeleton className="h-4 w-24" />
</div>
))}
</div>
</CardContent>
</Card>
</div>
);
}

View File

@@ -1,42 +0,0 @@
'use client';
import { ImageIcon } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketDetail } from '@/types';
import { RepairProofImagesGrid } from './repair-report/RepairProofImagesGrid';
import { RepairReportPanel } from './repair-report/RepairReportPanel';
import { RepairVideoComparison } from './repair-report/RepairVideoComparison';
export function TicketRepairReportCard({ ticket }: { ticket: TicketDetail }) {
const repair = ticket.repair;
if (!repair) {
return null;
}
return (
<section className="space-y-5">
<RepairReportPanel ticket={ticket} />
<RepairVideoComparison ticket={ticket} />
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ImageIcon className="size-5 text-primary" />
Repair Images
</CardTitle>
</CardHeader>
<CardContent>
<RepairProofImagesGrid
imageUrls={repair?.proof_image_urls ?? []}
submittedAt={repair?.submitted_at ?? null}
/>
</CardContent>
</Card>
</section>
);
}

View File

@@ -4,10 +4,13 @@ import { PERMISSIONS } from '@/constants/permissions';
import { PermissionGuard } from '@/guards';
import type { TicketDetail } from '@/types';
import { AssignedContractorAction } from './actions/AssignedContractorAction';
import { AssignTicketAction } from './actions/AssignTicketAction';
import { ClosedTicketAction } from './actions/ClosedTicketAction';
import { NoTicketAction } from './actions/NoTicketAction';
import { ReviewExtensionRequestAction } from './actions/ReviewExtensionRequestAction';
import { ReviewRepairAction } from './actions/ReviewRepairAction';
import { SubmittedRepairProofAction } from './actions/SubmittedRepairProofAction';
import { SubmitRepairAction } from './actions/SubmitRepairAction';
interface TicketStatusActionsProps {
@@ -28,12 +31,22 @@ function getTicketAction(ticket: TicketDetail) {
if (ticket.assignment_status === 'assigned') {
return (
<PermissionGuard
permissions={PERMISSIONS.TICKET.ASSIGN}
fallback={
<PermissionGuard
permissions={PERMISSIONS.TICKET.WORK}
fallback={<NoTicketAction />}
>
<SubmitRepairAction ticket={ticket} />
</PermissionGuard>
}
>
<>
<AssignedContractorAction ticket={ticket} />
<ReviewExtensionRequestAction ticket={ticket} />
</>
</PermissionGuard>
);
}
@@ -59,5 +72,15 @@ function getTicketAction(ticket: TicketDetail) {
}
export function TicketStatusActions({ ticket }: TicketStatusActionsProps) {
return getTicketAction(ticket);
const action = getTicketAction(ticket);
const submittedProof = ticket.repair?.submitted_at ? (
<SubmittedRepairProofAction ticket={ticket} />
) : null;
return (
<div className="space-y-3">
{submittedProof}
{action}
</div>
);
}

View File

@@ -1,56 +1,109 @@
'use client';
import { useState } from 'react';
import { Send, UserPlus } from 'lucide-react';
import { useMemo, useState } from 'react';
import { Users, Mail, Phone, Send, ShieldCheck } from 'lucide-react';
import { DatePickerSimple } from '@/components/form/DatePickerSimple';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { AssignableWorkerSelect } from '@/components/lookups/AssignableWorkerSelect';
import type { TicketDetail } from '@/types';
import type { AssignableTicketUser, TicketDetail } from '@/types';
import { useAssignTicketMutation } from '../../../hooks/useTicketQueries';
import { TicketActionCard } from './TicketActionCard';
export function AssignTicketAction({ ticket }: { ticket: TicketDetail }) {
const [selectedUserId, setSelectedUserId] = useState('');
const [selectedContractor, setSelectedContractor] =
useState<AssignableTicketUser | null>(null);
const [dueDate, setDueDate] = useState<Date>();
const [assignNote, setAssignNote] = useState('');
const assignMutation = useAssignTicketMutation(ticket.id);
const today = useMemo(() => {
const date = new Date();
date.setHours(0, 0, 0, 0);
return date;
}, []);
const maxDueMonth = useMemo(
() => new Date(today.getFullYear() + 20, 11),
[today],
);
return (
<TicketActionCard icon={UserPlus} title="Assign Ticket">
<TicketActionCard icon={Users} title="Assign to Contractor">
<div className="space-y-4">
<div className="space-y-2">
<Label>Contractor</Label>
<Label>Contractor *</Label>
<AssignableWorkerSelect
value={selectedUserId}
onValueChange={setSelectedUserId}
onValueChange={(userId, user) => {
setSelectedUserId(userId);
setSelectedContractor(user);
}}
disabled={assignMutation.isPending}
/>
</div>
{selectedContractor ? (
<div className="space-y-2 rounded-lg border bg-muted/30 p-3">
<p className="text-sm font-medium">Contractor Details</p>
{selectedContractor.phone_number ? (
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Phone className="size-4 shrink-0" />
{selectedContractor.phone_number}
</p>
) : null}
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<Mail className="size-4 shrink-0" />
<span className="truncate">{selectedContractor.email}</span>
</p>
<p className="flex items-center gap-2 text-sm text-muted-foreground">
<ShieldCheck className="size-4 shrink-0" />
{selectedContractor.role.name}
</p>
</div>
) : null}
<div className="space-y-2">
<Label>Note</Label>
<Label htmlFor="assign-due-date">
Due Date <span className="text-destructive">*</span>
</Label>
<DatePickerSimple
id="assign-due-date"
value={dueDate}
onChange={setDueDate}
showLabel={false}
placeholder="Select due date"
disabled={assignMutation.isPending}
className="w-full"
startMonth={today}
endMonth={maxDueMonth}
disabledDates={{ before: today }}
/>
</div>
<div className="space-y-2">
<Label>Assignment Note (Optional)</Label>
<Textarea
value={assignNote}
onChange={(event) => setAssignNote(event.target.value)}
placeholder="Please inspect and repair"
placeholder="Add any instructions or notes for the contractor..."
/>
</div>
<Button
disabled={!selectedUserId || assignMutation.isPending}
disabled={!selectedUserId || !dueDate || assignMutation.isPending}
onClick={() => {
if (!selectedUserId) return;
if (!selectedUserId || !dueDate) return;
assignMutation.mutate({
assigned_to_user_id: Number(selectedUserId),
defect_class: ticket.defect_class,
due_at: dueDate.toISOString(),
note: assignNote || undefined,
});
}}
className="w-full"
>
<Send />
Assign
Assign Ticket
</Button>
</div>
</TicketActionCard>

View File

@@ -0,0 +1,61 @@
'use client';
import { CalendarClock, UserCheck } from 'lucide-react';
import { PersonInfo } from '@/components/person-avatar';
import { Badge } from '@/components/ui/badge';
import type { TicketDetail } from '@/types';
import { formatDate } from '@/utils/date';
import { TicketActionCard } from './TicketActionCard';
function AssignmentField({ label, value }: { label: string; value: string }) {
return (
<div className="min-w-0 space-y-1">
<p className="text-xs text-muted-foreground">{label}</p>
<p className="truncate text-sm font-medium text-foreground">{value}</p>
</div>
);
}
export function AssignedContractorAction({ ticket }: { ticket: TicketDetail }) {
const worker = ticket.worker;
return (
<TicketActionCard icon={UserCheck} title="Assigned Contractor">
{worker ? (
<div className="space-y-5">
<div className="flex items-center justify-between gap-3">
<PersonInfo person={worker} size="lg" />
<Badge>
Assigned
</Badge>
</div>
<div className="grid grid-cols-2 gap-x-4 gap-y-5 border-t pt-4">
<AssignmentField label="Role" value={worker.role?.name ?? '-'} />
<AssignmentField
label="Assigned By"
value={worker.assigned_by_name ?? '-'}
/>
<AssignmentField
label="Assigned On"
value={formatDate(worker.assigned_at)}
/>
<div className="min-w-0 space-y-1">
<p className="text-xs text-muted-foreground">Due Date</p>
<p className="flex items-center gap-1.5 text-sm font-medium text-foreground">
<CalendarClock className="size-4 shrink-0 text-muted-foreground" />
<span className="truncate">{formatDate(worker.due_at)}</span>
</p>
</div>
</div>
</div>
) : (
<p className="text-sm text-muted-foreground">
Assignment details are not available.
</p>
)}
</TicketActionCard>
);
}

View File

@@ -3,7 +3,7 @@
import type { ReactNode } from 'react';
import { Lock, MessageSquare } from 'lucide-react';
import { Avatar, AvatarFallback } from '@/components/ui/avatar';
import { PersonInfo } from '@/components/person-avatar';
import { Button } from '@/components/ui/button';
import {
Card,
@@ -14,34 +14,18 @@ import {
} from '@/components/ui/card';
import { cn } from '@/lib/utils';
import type { TicketDetail } from '@/types';
function getInitials(name?: string | null, email?: string | null) {
const source = name || email || '?';
return source
.split(/[\s@._-]+/)
.filter(Boolean)
.slice(0, 2)
.map((part) => part.charAt(0).toUpperCase())
.join('');
}
function getPersonLabel(person: TicketDetail['reviewer']) {
return person?.name || person?.email || 'Unknown';
}
function formatReviewDate(value: string | null | undefined) {
if (!value) return '-';
return new Intl.DateTimeFormat('en-IN', { dateStyle: 'medium' }).format(
new Date(value),
);
}
import { formatDateOnly } from '@/utils/date';
function getClosedAt(ticket: TicketDetail) {
const closedEntry = ticket.history?.find(
(item) => item.to_status === 'closed',
const approvedEntry = [...(ticket.history ?? [])]
.reverse()
.find(
(item) =>
item.event_type === 'repair_approved' ||
item.to_class_status === 'approved',
);
return (
closedEntry?.created_at ??
approvedEntry?.created_at ??
ticket.reviewer?.reviewed_at ??
ticket.timestamps.updated_at
);
@@ -101,35 +85,19 @@ export function ClosedTicketAction({ ticket }: { ticket: TicketDetail }) {
<Card>
<CardHeader>
<CardTitle className="text-lg">Resolution Details</CardTitle>
<CardDescription>Review record for {ticket.id}</CardDescription>
<CardDescription>Review record for {ticket.ticket_name}</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<div className="space-y-4 rounded-xl border bg-muted/20 p-4">
<div className="space-y-4 rounded-lg border bg-muted/20 p-4">
<MetaField
label="Reviewed By"
value={
<div className="flex min-w-0 items-center gap-3">
<Avatar className="size-10 border border-primary/30">
<AvatarFallback className="bg-primary/15 text-sm text-primary">
{getInitials(reviewer?.name, reviewer?.email)}
</AvatarFallback>
</Avatar>
<div className="min-w-0">
<p className="truncate">{getPersonLabel(reviewer)}</p>
{reviewer?.email ? (
<p className="mt-0.5 truncate text-xs font-medium text-muted-foreground">
{reviewer.email}
</p>
) : null}
</div>
</div>
}
value={<PersonInfo person={reviewer} size="lg" />}
/>
<MetaField
label="Reviewed Date"
value={formatReviewDate(reviewedAt)}
value={formatDateOnly(reviewedAt)}
/>
</div>

View File

@@ -1,7 +1,16 @@
'use client';
import { useEffect, useRef, useState, type ReactNode } from 'react';
import { ImageIcon, Loader2, Send, Video, X } from 'lucide-react';
import {
Camera,
ImageIcon,
Loader2,
Play,
Plus,
Send,
Video,
X,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
@@ -10,89 +19,119 @@ import { cn } from '@/lib/utils';
import { useSubmitRepairUploadMutation } from '../../../hooks/useTicketQueries';
const MAX_IMAGES = 5;
const MAX_IMAGES = 30;
const MAX_NOTES = 500;
function RequiredMark() {
return <span className="text-destructive">*</span>;
}
interface MediaDropzoneProps {
function formatVideoDuration(seconds: number) {
const totalSeconds = Math.floor(seconds);
const minutes = Math.floor(totalSeconds / 60);
const remainingSeconds = totalSeconds % 60;
return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
}
interface MediaSectionHeaderProps {
icon: ReactNode;
label: string;
accept: string;
file: File | null;
onFileChange: (file: File | null) => void;
title: string;
addLabel: string;
onAdd: () => void;
disabled?: boolean;
}
function MediaDropzone({
function MediaSectionHeader({
icon,
label,
accept,
file,
onFileChange,
title,
addLabel,
onAdd,
disabled = false,
}: MediaDropzoneProps) {
const inputRef = useRef<HTMLInputElement | null>(null);
}: MediaSectionHeaderProps) {
return (
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-2">
<span className="text-primary">{icon}</span>
<span className="text-sm font-semibold">{title}</span>
</div>
<Button
type="button"
variant="secondary"
size="sm"
disabled={disabled}
onClick={onAdd}
className="shrink-0"
>
<Plus className="size-3.5" />
{addLabel}
</Button>
</div>
);
}
function MediaHint({ children }: { children: ReactNode }) {
return (
<p className="rounded-lg bg-muted/50 px-3 py-2 text-xs text-muted-foreground">
{children}
</p>
);
}
interface EmptyMediaPlaceholderProps {
icon: ReactNode;
title: string;
description: string;
className?: string;
disabled?: boolean;
onClick: () => void;
}
function EmptyMediaPlaceholder({
icon,
title,
description,
className,
disabled = false,
onClick,
}: EmptyMediaPlaceholderProps) {
return (
<button
type="button"
disabled={disabled}
onClick={() => inputRef.current?.click()}
onClick={onClick}
className={cn(
'flex w-full items-center cursor-pointer gap-3 rounded-lg border border-dashed px-4 py-3 text-left transition-colors',
'hover:border-primary/50 hover:bg-muted/30',
disabled && 'pointer-events-none opacity-60',
file && 'border-primary/40 bg-muted/20',
'flex w-full min-w-0 cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-dashed border-border/80 bg-muted/15 px-4 py-6 text-center transition-colors',
'hover:border-primary/40 hover:bg-primary/5',
disabled && 'cursor-not-allowed opacity-60',
className,
)}
>
<input
ref={inputRef}
type="file"
accept={accept}
className="hidden"
disabled={disabled}
onChange={(event) => {
onFileChange(event.target.files?.[0] ?? null);
event.target.value = '';
}}
/>
<span className="flex size-9 shrink-0 items-center justify-center rounded-md bg-primary/10 text-primary">
<span className="flex size-10 items-center justify-center rounded-full bg-primary/10 text-primary">
{icon}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium">
{file ? file.name : label}
</span>
{file ? (
<span className="text-xs text-muted-foreground">
Click to replace
</span>
) : null}
<span className="text-sm font-medium text-foreground">{title}</span>
<span className="max-w-xs text-xs text-muted-foreground">
{description}
</span>
</button>
);
}
interface ImageSlotProps {
file: File | null;
previewUrl: string | null;
interface ImageThumbnailProps {
file: File;
previewUrl: string;
disabled?: boolean;
onAdd: () => void;
onRemove: () => void;
}
function ImageSlot({
function ImageThumbnail({
file,
previewUrl,
disabled = false,
onAdd,
onRemove,
}: ImageSlotProps) {
if (file && previewUrl) {
}: ImageThumbnailProps) {
return (
<div className="group relative aspect-square overflow-hidden rounded-lg border bg-muted/30">
<div className="group relative size-20 shrink-0 overflow-hidden rounded-lg border bg-muted/30">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={previewUrl}
@@ -103,7 +142,7 @@ function ImageSlot({
type="button"
disabled={disabled}
onClick={onRemove}
className="absolute top-1 right-1 flex size-5 cursor-pointer items-center justify-center rounded-full bg-background/90 text-foreground opacity-0 shadow-sm transition-opacity group-hover:opacity-100 disabled:cursor-not-allowed disabled:opacity-50"
className="absolute top-1 right-1 flex size-5 cursor-pointer items-center justify-center rounded-full bg-foreground/80 text-background shadow-sm transition-opacity disabled:cursor-not-allowed disabled:opacity-50"
aria-label={`Remove ${file.name}`}
>
<X className="size-3" />
@@ -112,20 +151,51 @@ function ImageSlot({
);
}
interface VideoThumbnailProps {
file: File;
previewUrl: string;
duration: string | null;
disabled?: boolean;
onRemove: () => void;
}
function VideoThumbnail({
file,
previewUrl,
duration,
disabled = false,
onRemove,
}: VideoThumbnailProps) {
return (
<div className="group relative h-20 w-36 shrink-0 overflow-hidden rounded-lg border bg-muted/30">
<video
src={previewUrl}
className="size-full object-cover"
muted
playsInline
preload="metadata"
aria-label={file.name}
/>
<div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-black/20">
<span className="flex size-8 items-center justify-center rounded-full bg-background/90 text-foreground shadow-sm">
<Play className="size-3.5 fill-current" />
</span>
</div>
{duration ? (
<span className="pointer-events-none absolute bottom-1.5 right-1.5 rounded-lg bg-black/75 px-1.5 py-0.5 text-[10px] font-medium text-white">
{duration}
</span>
) : null}
<button
type="button"
disabled={disabled}
onClick={onAdd}
className={cn(
'flex aspect-square cursor-pointer items-center justify-center rounded-lg border border-dashed bg-muted/20 text-muted-foreground transition-colors',
'hover:border-primary/50 hover:bg-muted/40 hover:text-primary',
disabled && 'cursor-not-allowed opacity-60',
)}
aria-label="Add image"
onClick={onRemove}
className="absolute top-1 right-1 flex size-5 cursor-pointer items-center justify-center rounded-full bg-foreground/80 text-background shadow-sm transition-opacity disabled:cursor-not-allowed disabled:opacity-50"
aria-label={`Remove ${file.name}`}
>
<ImageIcon className="size-4" />
<X className="size-3" />
</button>
</div>
);
}
@@ -139,14 +209,18 @@ export function RepairEvidenceForm({
defectClass,
}: RepairEvidenceFormProps) {
const imageInputRef = useRef<HTMLInputElement | null>(null);
const videoInputRef = useRef<HTMLInputElement | null>(null);
const [notes, setNotes] = useState('');
const [videoFile, setVideoFile] = useState<File | null>(null);
const [videoPreview, setVideoPreview] = useState<string | null>(null);
const [videoDuration, setVideoDuration] = useState<string | null>(null);
const [imageFiles, setImageFiles] = useState<File[]>([]);
const [imagePreviews, setImagePreviews] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
const submitRepairUploadMutation = useSubmitRepairUploadMutation(ticketId);
const isSubmitting = submitRepairUploadMutation.isPending;
const canSubmit = Boolean(notes.trim() && videoFile);
const canAddMoreImages = imageFiles.length < MAX_IMAGES;
useEffect(() => {
const urls = imageFiles.map((file) => URL.createObjectURL(file));
@@ -156,6 +230,32 @@ export function RepairEvidenceForm({
};
}, [imageFiles]);
useEffect(() => {
if (!videoFile) {
setVideoPreview(null);
setVideoDuration(null);
return;
}
const url = URL.createObjectURL(videoFile);
setVideoPreview(url);
setVideoDuration(null);
let cancelled = false;
const video = document.createElement('video');
video.preload = 'metadata';
video.onloadedmetadata = () => {
if (cancelled || !Number.isFinite(video.duration)) return;
setVideoDuration(formatVideoDuration(video.duration));
};
video.src = url;
return () => {
cancelled = true;
URL.revokeObjectURL(url);
};
}, [videoFile]);
const addImages = (files: FileList | null) => {
if (!files?.length) return;
@@ -177,6 +277,16 @@ export function RepairEvidenceForm({
);
};
const selectVideo = (files: FileList | null) => {
setVideoFile(files?.[0] ?? null);
setError(null);
};
const removeVideo = () => {
setVideoFile(null);
setError(null);
};
const removeImage = (index: number) => {
setImageFiles((current) =>
current.filter((_, itemIndex) => itemIndex !== index),
@@ -186,7 +296,7 @@ export function RepairEvidenceForm({
const handleSubmit = async () => {
if (!notes.trim() || !videoFile) {
setError('Repair notes and video are required.');
setError('Repair notes and a video are required.');
return;
}
@@ -206,86 +316,148 @@ export function RepairEvidenceForm({
}
};
const imageSlots = Array.from({ length: MAX_IMAGES }, (_, index) => ({
file: imageFiles[index] ?? null,
previewUrl: imagePreviews[index] ?? null,
}));
const openImagePicker = () => {
if (!isSubmitting && canAddMoreImages) {
imageInputRef.current?.click();
}
};
const openVideoPicker = () => {
if (!isSubmitting) {
videoInputRef.current?.click();
}
};
return (
<div className="space-y-5">
<div className="space-y-2">
<Label htmlFor="repair-notes">
Repair Notes <RequiredMark />
</Label>
<Textarea
id="repair-notes"
value={notes}
onChange={(event) => {
setNotes(event.target.value);
setError(null);
}}
placeholder="Describe the repair work performed..."
disabled={isSubmitting}
className="min-h-24 resize-none"
/>
<div className="flex gap-3 rounded-lg border border-primary/15 bg-primary/5 p-4">
<Camera className="mt-0.5 size-5 shrink-0 text-primary" />
<div className="space-y-1">
<p className="text-sm font-semibold">Instructions</p>
<p className="text-sm text-muted-foreground">
Upload clear photos and one video of the repaired area and provide
relevant details.
</p>
</div>
</div>
<div className="space-y-3">
<Label className="text-muted-foreground">Media Upload</Label>
<div className="space-y-2">
<Label className="text-sm font-normal">
Repair Video <RequiredMark />
</Label>
<MediaDropzone
icon={<Video className="size-4" />}
label="Upload Repair Video (MP4, max 50MB)"
accept="video/mp4,video/*"
file={videoFile}
onFileChange={(file) => {
setVideoFile(file);
setError(null);
}}
disabled={isSubmitting}
/>
</div>
<div className="space-y-2">
<Label className="text-sm font-normal">
Upload Images (Max {MAX_IMAGES})
</Label>
<input
ref={imageInputRef}
type="file"
accept="image/*"
accept="image/jpeg,image/png,image/*"
multiple
className="hidden"
disabled={isSubmitting || imageFiles.length >= MAX_IMAGES}
disabled={isSubmitting || !canAddMoreImages}
onChange={(event) => {
addImages(event.target.files);
event.target.value = '';
}}
/>
<div className="grid grid-cols-5 gap-2">
{imageSlots.map((slot, index) => (
<ImageSlot
key={index}
file={slot.file}
previewUrl={slot.previewUrl}
disabled={
isSubmitting ||
(!slot.file && imageFiles.length >= MAX_IMAGES)
}
onAdd={() => imageInputRef.current?.click()}
<input
ref={videoInputRef}
type="file"
accept="video/mp4,video/quicktime,video/x-msvideo,video/*"
className="hidden"
disabled={isSubmitting}
onChange={(event) => {
selectVideo(event.target.files);
event.target.value = '';
}}
/>
<section className="space-y-3">
<MediaSectionHeader
icon={<Camera className="size-4" />}
title="Photos"
addLabel="Add Photos"
onAdd={openImagePicker}
disabled={isSubmitting || !canAddMoreImages}
/>
<div className="overflow-x-auto pb-1 [-ms-overflow-style:none] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{imageFiles.length === 0 ? (
<EmptyMediaPlaceholder
icon={<ImageIcon className="size-5" />}
title="No photos added yet"
description="Tap to upload repair photos"
disabled={isSubmitting}
onClick={openImagePicker}
className="min-h-26"
/>
) : (
<div className="flex min-w-min gap-3">
{imageFiles.map((file, index) => (
<ImageThumbnail
key={`${file.name}-${file.lastModified}-${index}`}
file={file}
previewUrl={imagePreviews[index]}
disabled={isSubmitting}
onRemove={() => removeImage(index)}
/>
))}
</div>
)}
</div>
<MediaHint>
You can upload up to {MAX_IMAGES} images (JPG, PNG)
</MediaHint>
</section>
<section className="space-y-3">
<div className="flex items-center gap-2">
<Video className="size-4 text-primary" />
<span className="text-sm font-semibold">Video</span>
</div>
<div>
{!videoFile || !videoPreview ? (
<EmptyMediaPlaceholder
icon={<Video className="size-5" />}
title="No video added yet"
description="Tap to upload a repair video"
disabled={isSubmitting}
onClick={openVideoPicker}
className="min-h-[104px]"
/>
) : (
<VideoThumbnail
file={videoFile}
previewUrl={videoPreview}
duration={videoDuration}
disabled={isSubmitting}
onRemove={removeVideo}
/>
)}
</div>
<MediaHint>You can upload one video (MP4, MOV, AVI)</MediaHint>
</section>
<div className="space-y-2">
<Label htmlFor="repair-notes">
Repair Notes <RequiredMark />
</Label>
<div className="relative">
<Textarea
id="repair-notes"
value={notes}
onChange={(event) => {
setNotes(event.target.value.slice(0, MAX_NOTES));
setError(null);
}}
placeholder="Describe the repair work completed, materials used, and any additional observations."
disabled={isSubmitting}
className="min-h-28 resize-none pb-8"
/>
<span className="pointer-events-none absolute bottom-2 right-3 text-xs text-muted-foreground">
{notes.length} / {MAX_NOTES}
</span>
</div>
</div>
{error ? (
<div className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
<div className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</div>
) : null}

View File

@@ -0,0 +1,157 @@
'use client';
import { useMemo, useState } from 'react';
import { Clock3, Loader2, Send } from 'lucide-react';
import { DatePicker } from '@/components/form/DatePicker';
import { DatePickerSimple } from '@/components/form/DatePickerSimple';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import type { TicketDetail } from '@/types';
import { useRequestTicketExtensionMutation } from '../../../hooks/useTicketQueries';
const MAX_REASON_LENGTH = 300;
interface RequestExtensionFormProps {
ticket: TicketDetail;
onCancel: () => void;
}
export function RequestExtensionForm({
ticket,
onCancel,
}: RequestExtensionFormProps) {
const currentDueAt = ticket.worker?.due_at;
const currentDueDate = useMemo(
() => (currentDueAt ? new Date(currentDueAt) : undefined),
[currentDueAt],
);
const earliestRequestedDate = useMemo(() => {
const date = currentDueDate ? new Date(currentDueDate) : new Date();
date.setHours(0, 0, 0, 0);
if (currentDueDate) date.setDate(date.getDate() + 1);
return date;
}, [currentDueDate]);
const latestRequestedMonth = useMemo(
() => new Date(earliestRequestedDate.getFullYear() + 20, 11),
[earliestRequestedDate],
);
const [requestedDueDate, setRequestedDueDate] = useState<Date>();
const [reason, setReason] = useState('');
const assignmentId = ticket.worker?.assignment_id;
const requestExtensionMutation = useRequestTicketExtensionMutation(
ticket.id,
assignmentId,
ticket.defect_class,
);
const isPending = requestExtensionMutation.isPending;
const isRequestedDateValid = Boolean(
requestedDueDate &&
(!currentDueDate || requestedDueDate.getTime() > currentDueDate.getTime()),
);
const canSubmit =
Boolean(assignmentId) &&
isRequestedDateValid &&
Boolean(reason.trim()) &&
!isPending;
const handleSubmit = async () => {
if (!requestedDueDate || !canSubmit) return;
await requestExtensionMutation.mutateAsync({
requested_due_at: requestedDueDate.toISOString(),
reason: reason.trim(),
});
setRequestedDueDate(undefined);
setReason('');
onCancel();
};
return (
<div className="space-y-5">
<div className="flex gap-3 rounded-lg border border-primary/15 bg-primary/5 p-4">
<Clock3 className="mt-0.5 size-5 shrink-0 text-primary" />
<p className="text-sm text-muted-foreground">
Request more time to complete the repair. Your manager will review the
request.
</p>
</div>
<div className="space-y-2">
<Label>Current Due Date</Label>
<DatePicker
value={currentDueDate}
showTimeZone={false}
placeholder="No due date available"
disabled
className="w-full"
/>
</div>
<div className="space-y-2">
<Label>
Requested Due Date <span className="text-destructive">*</span>
</Label>
<DatePickerSimple
id="requested-due-date"
value={requestedDueDate}
onChange={setRequestedDueDate}
showLabel={false}
placeholder="Select requested due date"
disabled={isPending}
className="w-full"
startMonth={earliestRequestedDate}
endMonth={latestRequestedMonth}
disabledDates={{ before: earliestRequestedDate }}
/>
{requestedDueDate && !isRequestedDateValid ? (
<p className="text-xs text-destructive">
Requested date must be after the current due date.
</p>
) : null}
</div>
<div className="space-y-2">
<Label htmlFor="extension-reason">
Reason for Extension <span className="text-destructive">*</span>
</Label>
<div className="relative">
<Textarea
id="extension-reason"
value={reason}
onChange={(event) =>
setReason(event.target.value.slice(0, MAX_REASON_LENGTH))
}
placeholder="Explain why additional time is required to complete the repair."
disabled={isPending}
className="min-h-28 resize-none pb-8"
/>
<span className="pointer-events-none absolute right-3 bottom-2 text-xs text-muted-foreground">
{reason.length} / {MAX_REASON_LENGTH}
</span>
</div>
</div>
<p className="text-xs text-muted-foreground">
This request will be sent to your manager for approval.
</p>
<div className="grid grid-cols-2 gap-3">
<Button
type="button"
variant="outline"
disabled={isPending}
onClick={onCancel}
>
Cancel
</Button>
<Button type="button" disabled={!canSubmit} onClick={handleSubmit}>
{isPending ? <Loader2 className="animate-spin" /> : <Send />}
{isPending ? 'Submitting...' : 'Submit Request'}
</Button>
</div>
</div>
);
}

View File

@@ -0,0 +1,231 @@
'use client';
import { useState } from 'react';
import {
ArrowRight,
CalendarClock,
Check,
Clock3,
Loader2,
X,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import type {
TicketDetail,
TicketExtensionRequest,
TicketExtensionRequestsResponse,
} from '@/types';
import { formatDate } from '@/utils/date';
import {
useReviewTicketExtensionMutation,
useTicketExtensionRequestQuery,
} from '../../../hooks/useTicketQueries';
import { TicketActionCard } from './TicketActionCard';
const MAX_NOTE_LENGTH = 300;
function getPendingRequest(response: TicketExtensionRequestsResponse) {
return response.items
.filter((request) => request.status === 'pending')
.reduce<TicketExtensionRequest | null>((latest, request) => {
if (!latest) return request;
return new Date(request.requested_at) > new Date(latest.requested_at)
? request
: latest;
}, null);
}
function getExtensionDays(request: TicketExtensionRequest) {
const difference =
new Date(request.requested_due_at).getTime() -
new Date(request.current_due_at).getTime();
return Math.max(0, Math.ceil(difference / (24 * 60 * 60 * 1000)));
}
function Requester({ request }: { request: TicketExtensionRequest }) {
const name = request.requested_by?.name ?? 'Assigned worker';
const initials = name
.split(/\s+/)
.slice(0, 2)
.map((part) => part[0]?.toUpperCase())
.join('');
return (
<div className="grid grid-cols-2 gap-3 rounded-lg bg-muted/40 p-3">
<div className="flex items-center gap-2">
<span className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/15 text-xs font-semibold text-primary">
{initials || 'W'}
</span>
<div className="min-w-0">
<p className="text-[11px] text-muted-foreground">Requested By</p>
<p className="truncate text-sm font-medium">{name}</p>
</div>
</div>
<div>
<p className="text-[11px] text-muted-foreground">Requested On</p>
<p className="text-sm font-medium">
{formatDate(request.requested_at)}
</p>
</div>
</div>
);
}
function ExtensionReviewForm({
ticket,
request,
}: {
ticket: TicketDetail;
request: TicketExtensionRequest;
}) {
const [note, setNote] = useState('');
const [selectedAction, setSelectedAction] = useState<
'approve' | 'reject' | null
>(null);
const assignmentId = ticket.worker?.assignment_id as number;
const reviewMutation = useReviewTicketExtensionMutation(
ticket.id,
assignmentId,
ticket.defect_class,
);
const extensionDays = getExtensionDays(request);
const submitDecision = async (action: 'approve' | 'reject') => {
setSelectedAction(action);
try {
await reviewMutation.mutateAsync({ action, note: note.trim() });
} finally {
setSelectedAction(null);
}
};
return (
<TicketActionCard icon={CalendarClock} title="Extension Request Details">
<div className="space-y-4">
<Requester request={request} />
<section className="space-y-2">
<p className="text-xs font-semibold">Request Summary</p>
<div className="grid grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-start gap-3 rounded-lg border p-3">
<div>
<p className="text-[11px] text-muted-foreground">
Current Due Date
</p>
<p className="text-xs font-medium">
{formatDate(request.current_due_at)}
</p>
</div>
<ArrowRight className="mt-6 size-4 text-muted-foreground" />
<div>
<p className="text-[11px] text-muted-foreground">
Requested Due Date
</p>
<p className="text-xs font-medium">
{formatDate(request.requested_due_at)}
</p>
{extensionDays > 0 ? (
<span className="mt-1 inline-flex rounded-full bg-emerald-100 px-2 py-0.5 text-[10px] font-semibold text-emerald-700 dark:bg-emerald-950/50 dark:text-emerald-300">
+{extensionDays} {extensionDays === 1 ? 'Day' : 'Days'}
</span>
) : null}
</div>
</div>
<div className="rounded-lg border p-3">
<p className="text-[11px] text-muted-foreground">Reason</p>
<p className="mt-1 text-sm leading-relaxed">{request.reason}</p>
</div>
</section>
<div className="space-y-2">
<Label htmlFor="extension-manager-note">
Add Manager Comments{' '}
<span className="text-muted-foreground">(Optional)</span>
</Label>
<div className="relative">
<Textarea
id="extension-manager-note"
value={note}
onChange={(event) =>
setNote(event.target.value.slice(0, MAX_NOTE_LENGTH))
}
placeholder="Add a note explaining your decision..."
disabled={reviewMutation.isPending}
className="min-h-24 resize-none pb-8"
/>
<span className="pointer-events-none absolute right-3 bottom-2 text-xs text-muted-foreground">
{note.length} / {MAX_NOTE_LENGTH}
</span>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<Button
type="button"
variant="outline"
className="border-destructive/40 text-destructive hover:bg-destructive/5 hover:text-destructive"
disabled={reviewMutation.isPending}
onClick={() => submitDecision('reject')}
>
{selectedAction === 'reject' ? (
<Loader2 className="animate-spin" />
) : (
<X />
)}
Reject Request
</Button>
<Button
type="button"
disabled={reviewMutation.isPending}
onClick={() => submitDecision('approve')}
>
{selectedAction === 'approve' ? (
<Loader2 className="animate-spin" />
) : (
<Check />
)}
Approve Extension
</Button>
</div>
</div>
</TicketActionCard>
);
}
export function ReviewExtensionRequestAction({
ticket,
}: {
ticket: TicketDetail;
}) {
const assignmentId = ticket.worker?.assignment_id;
const extensionRequestQuery = useTicketExtensionRequestQuery(
ticket.id,
assignmentId,
);
if (!assignmentId || extensionRequestQuery.isError) {
return null;
}
if (extensionRequestQuery.isLoading) {
return (
<TicketActionCard icon={Clock3} title="Extension Request">
<div className="flex items-center justify-center py-8 text-muted-foreground">
<Loader2 className="mr-2 size-4 animate-spin" />
<span className="text-sm">Checking for requests...</span>
</div>
</TicketActionCard>
);
}
const pendingRequest = extensionRequestQuery.data
? getPendingRequest(extensionRequestQuery.data)
: null;
if (!pendingRequest) return null;
return <ExtensionReviewForm ticket={ticket} request={pendingRequest} />;
}

View File

@@ -32,6 +32,7 @@ export function ReviewRepairAction({ ticket }: { ticket: TicketDetail }) {
</div>
<div className="grid grid-cols-2 gap-2">
<Button
variant={'secondary'}
disabled={!reviewComment || reviewRepairMutation.isPending}
onClick={() =>
reviewRepairMutation.mutate({

View File

@@ -1,19 +1,52 @@
'use client';
import { useState } from 'react';
import { Wrench } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import type { TicketDetail } from '@/types';
import { RepairEvidenceForm } from './RepairEvidenceForm';
import { TicketExtensionRequestPanel } from './TicketExtensionRequestPanel';
import { TicketActionCard } from './TicketActionCard';
type RepairActionTab = 'repair-proof' | 'request-extension';
export function SubmitRepairAction({ ticket }: { ticket: TicketDetail }) {
const [activeTab, setActiveTab] = useState<RepairActionTab>('repair-proof');
if (ticket.repair?.submitted_at) {
return null;
}
return (
<TicketActionCard icon={Wrench} title="Submit Repair Evidence">
<TicketActionCard icon={Wrench} title="Repair Proof">
<Tabs
value={activeTab}
onValueChange={(value) => setActiveTab(value as RepairActionTab)}
className="gap-5"
>
<TabsList variant="line" className="grid h-auto w-full grid-cols-2 p-0">
<TabsTrigger value="repair-proof" className="pb-3">
Upload Repair Proof
</TabsTrigger>
<TabsTrigger value="request-extension" className="pb-3">
Request Extension
</TabsTrigger>
</TabsList>
<TabsContent value="repair-proof">
<RepairEvidenceForm
ticketId={ticket.id}
defectClass={ticket.defect_class}
/>
</TabsContent>
<TabsContent value="request-extension">
<TicketExtensionRequestPanel
ticket={ticket}
onCancelRequest={() => setActiveTab('repair-proof')}
/>
</TabsContent>
</Tabs>
</TicketActionCard>
);
}

View File

@@ -0,0 +1 @@
export { RepairProofSummary as SubmittedRepairProofAction } from '../repair/RepairProofSummary';

View File

@@ -22,7 +22,7 @@ export function TicketActionCard({
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<Icon className={cn('size-4 text-primary', iconClassName)} />
<Icon className={cn('text-primary', iconClassName)} />
{title}
</CardTitle>
</CardHeader>

View File

@@ -0,0 +1,248 @@
'use client';
import {
AlertCircle,
CalendarDays,
CheckCircle2,
Clock3,
History,
Loader2,
RotateCcw,
XCircle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
import type {
TicketDetail,
TicketExtensionRequest,
TicketExtensionRequestsResponse,
} from '@/types';
import { formatDate } from '@/utils/date';
import { useTicketExtensionRequestQuery } from '../../../hooks/useTicketQueries';
import { RequestExtensionForm } from './RequestExtensionForm';
interface TicketExtensionRequestPanelProps {
ticket: TicketDetail;
onCancelRequest: () => void;
}
interface DetailRowProps {
label: string;
value: string;
children?: React.ReactNode;
className?: string;
}
function DetailRow({ label, value, children, className }: DetailRowProps) {
return (
<div className={cn('space-y-1 px-3 py-2.5', className)}>
<p className="text-[11px] font-medium text-muted-foreground">{label}</p>
<div className="flex items-center justify-between gap-3">
<p className="text-sm font-medium">{value}</p>
{children}
</div>
</div>
);
}
const statusConfig = {
pending: {
title: 'Request Pending',
description: 'Your extension request is waiting for manager approval.',
icon: Clock3,
className:
'border-amber-200 bg-amber-50 text-amber-700 dark:border-amber-900/60 dark:bg-amber-950/30 dark:text-amber-300',
},
approved: {
title: 'Request Approved',
description: 'Your extension request has been approved by the manager.',
icon: CheckCircle2,
className:
'border-emerald-200 bg-emerald-50 text-emerald-700 dark:border-emerald-900/60 dark:bg-emerald-950/30 dark:text-emerald-300',
},
rejected: {
title: 'Request Rejected',
description: 'Your extension request has been rejected by the manager.',
icon: AlertCircle,
className:
'border-red-200 bg-red-50 text-red-700 dark:border-red-900/60 dark:bg-red-950/30 dark:text-red-300',
},
cancelled: {
title: 'Request Cancelled',
description: 'This extension request was cancelled.',
icon: XCircle,
className: 'border-border bg-muted/50 text-muted-foreground',
},
} satisfies Record<
TicketExtensionRequest['status'],
{
title: string;
description: string;
icon: typeof Clock3;
className: string;
}
>;
function getLatestRequest(response: TicketExtensionRequestsResponse) {
return response.items.reduce<TicketExtensionRequest | null>(
(latest, item) => {
if (!latest) return item;
return new Date(item.requested_at) > new Date(latest.requested_at)
? item
: latest;
},
null,
);
}
function getExtensionDays(request: TicketExtensionRequest) {
const difference =
new Date(request.requested_due_at).getTime() -
new Date(request.current_due_at).getTime();
return Math.max(0, Math.ceil(difference / (24 * 60 * 60 * 1000)));
}
function ExtensionRequestDetails({
request,
}: {
request: TicketExtensionRequest;
}) {
const config = statusConfig[request.status];
const StatusIcon = config.icon;
const extensionDays = getExtensionDays(request);
return (
<div className="space-y-4">
<div className={cn('flex gap-3 rounded-lg border p-4', config.className)}>
<StatusIcon className="mt-0.5 size-5 shrink-0" />
<div className="space-y-1">
<p className="text-sm font-semibold">{config.title}</p>
<p className="text-xs leading-relaxed">{config.description}</p>
</div>
</div>
<section className="space-y-2">
<p className="text-xs font-semibold">Request Details</p>
<div className="divide-y overflow-hidden rounded-lg border">
<DetailRow
label="Requested On"
value={formatDate(request.requested_at)}
/>
<DetailRow
label="Requested Due Date"
value={formatDate(request.requested_due_at)}
>
{extensionDays > 0 ? (
<span className="shrink-0 rounded-full bg-primary/10 px-2 py-0.5 text-[10px] font-semibold text-primary">
+{extensionDays} {extensionDays === 1 ? 'Day' : 'Days'}
</span>
) : null}
</DetailRow>
<DetailRow label="Reason for Extension" value={request.reason} />
</div>
</section>
{request.resolved_at || request.resolved_by ? (
<section className="space-y-2">
<p className="text-xs font-semibold">Manager Response</p>
<div className="divide-y overflow-hidden rounded-lg border">
{request.resolved_at ? (
<DetailRow
label="Responded On"
value={formatDate(request.resolved_at)}
/>
) : null}
{request.resolved_by ? (
<DetailRow
label="Resolved By"
value={`${request.resolved_by.name} · ${request.resolved_by.role.name}`}
/>
) : null}
{request.status === 'approved' ? (
<DetailRow
label="Approved Due Date"
value={formatDate(request.requested_due_at)}
/>
) : null}
</div>
</section>
) : null}
<section className="space-y-2">
<p className="text-xs font-semibold">Original Due Date</p>
<div className="rounded-lg border">
<DetailRow
label="Original schedule"
value={formatDate(request.current_due_at)}
>
<CalendarDays className="size-4 text-muted-foreground" />
</DetailRow>
</div>
</section>
<Button type="button" variant="outline" className="w-full">
<History />
View Approval History
</Button>
</div>
);
}
export function TicketExtensionRequestPanel({
ticket,
onCancelRequest,
}: TicketExtensionRequestPanelProps) {
const assignmentId = ticket.worker?.assignment_id;
const extensionRequestQuery = useTicketExtensionRequestQuery(
ticket.id,
assignmentId,
);
if (!assignmentId) {
return (
<div className="rounded-lg border border-dashed p-4 text-sm text-muted-foreground">
No active assignment is available for this ticket.
</div>
);
}
if (extensionRequestQuery.isLoading) {
return (
<div className="flex min-h-40 items-center justify-center text-muted-foreground">
<Loader2 className="size-5 animate-spin" />
<span className="ml-2 text-sm">Loading extension request...</span>
</div>
);
}
if (extensionRequestQuery.isError) {
return (
<div className="space-y-3 rounded-lg border border-destructive/30 bg-destructive/5 p-4">
<p className="text-sm text-destructive">
Extension request details could not be loaded.
</p>
<Button
type="button"
size="sm"
variant="outline"
onClick={() => extensionRequestQuery.refetch()}
>
<RotateCcw />
Try Again
</Button>
</div>
);
}
const latestRequest = extensionRequestQuery.data
? getLatestRequest(extensionRequestQuery.data)
: null;
if (!latestRequest) {
return <RequestExtensionForm ticket={ticket} onCancel={onCancelRequest} />;
}
return <ExtensionRequestDetails request={latestRequest} />;
}

View File

@@ -1,121 +0,0 @@
'use client';
import { ImageIcon } from 'lucide-react';
import { Skeleton } from '@/components/ui/skeleton';
import { useProtectedMediaObjectUrl } from '@/hooks/useProtectedMedia';
import { cn } from '@/lib/utils';
import { formatRepairDate, ReportSurface } from './repairReportUtils';
const MAX_MEDIA_SLOTS = 5;
const imageBadgeStyles = [
'bg-primary/90 text-primary-foreground',
'bg-secondary text-secondary-foreground',
'bg-accent text-accent-foreground',
'bg-muted text-muted-foreground',
'bg-primary/70 text-primary-foreground',
] as const;
export function RepairProofImagesGrid({
imageUrls,
submittedAt,
layout = 'row',
}: {
imageUrls: string[];
submittedAt: string | null;
layout?: 'row' | 'sidebar';
}) {
const imageSlots = Array.from(
{ length: MAX_MEDIA_SLOTS },
(_, index) => imageUrls[index] ?? null,
);
return (
<div
className={cn(
'grid gap-3',
layout === 'sidebar'
? 'grid-cols-2 auto-rows-fr'
: 'grid-cols-2 sm:grid-cols-3 lg:grid-cols-5',
)}
>
{imageSlots.map((url, index) => (
<RepairProofImageSlot
key={index}
url={url}
index={index}
submittedAt={submittedAt}
/>
))}
</div>
);
}
function RepairProofImageSlot({
url,
index,
submittedAt,
}: {
url: string | null;
index: number;
submittedAt: string | null;
}) {
const { objectUrl, isLoading, isError } = useProtectedMediaObjectUrl(url);
if (!url) {
return (
<ReportSurface className="space-y-2 p-2">
<div className="flex aspect-4/3 items-center justify-center rounded-lg border border-dashed border-border/70 bg-muted/10 text-muted-foreground/70">
<ImageIcon className="size-4" />
</div>
<p className="truncate px-1 text-[11px] text-muted-foreground/70">
No image added
</p>
</ReportSurface>
);
}
if (isLoading) {
return (
<ReportSurface className="space-y-2 p-2">
<Skeleton className="aspect-4/3 w-full rounded-lg" />
<Skeleton className="h-3 w-16" />
</ReportSurface>
);
}
if (isError || !objectUrl) {
return (
<ReportSurface className="space-y-2 p-2">
<div className="flex aspect-4/3 items-center justify-center rounded-lg border border-dashed bg-muted/10 text-xs text-muted-foreground">
Unavailable
</div>
<p className="truncate px-1 text-[11px] text-muted-foreground">
Image {index + 1}
</p>
</ReportSurface>
);
}
return (
<ReportSurface className="space-y-2 p-2">
<a
href={objectUrl}
target="_blank"
rel="noreferrer"
className="group relative block overflow-hidden rounded-lg border bg-muted/20"
>
<img
src={objectUrl}
alt={`Repair proof ${index + 1}`}
className="aspect-4/3 w-full object-cover transition-transform group-hover:scale-[1.02]"
/>
</a>
<p className="truncate px-1 text-[11px] text-muted-foreground">
{submittedAt ? formatRepairDate(submittedAt) : `Image ${index + 1}`}
</p>
</ReportSurface>
);
}

View File

@@ -1,108 +0,0 @@
'use client';
import { FileText, MessageSquareQuote } from 'lucide-react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketDetail } from '@/types';
import {
EmptyPanel,
formatRepairDate,
getPersonLabel,
} from './repairReportUtils';
function MetaLabel({ children }: { children: React.ReactNode }) {
return (
<p className="text-xs font-medium tracking-wide text-muted-foreground">
{children}
</p>
);
}
function ReportField({
label,
value,
}: {
label: string;
value: string | null | undefined;
}) {
return (
<div className="space-y-1">
<MetaLabel>{label}</MetaLabel>
<p className="text-sm font-semibold text-foreground">{value || '-'}</p>
</div>
);
}
export function RepairReportPanel({ ticket }: { ticket: TicketDetail }) {
const repair = ticket.repair;
if (!repair) {
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<FileText className="size-5 text-primary" />
Repair Report
</CardTitle>
</CardHeader>
<CardContent>
<EmptyPanel
icon={MessageSquareQuote}
title="No repair report submitted yet"
description="Repair details will appear here once the assigned worker submits evidence."
className="py-10"
/>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader className="sm:grid-cols-[1fr_auto]">
<CardTitle className="flex items-center gap-2">
<FileText className="size-5 text-primary" />
Repair Report
</CardTitle>
{repair.submitted_at ? (
<span className="text-xs text-muted-foreground italic sm:col-start-2 sm:row-start-1">
Completed {formatRepairDate(repair.submitted_at)}
</span>
) : null}
</CardHeader>
<CardContent className="space-y-5">
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2">
<ReportField
label="Technician"
value={getPersonLabel(ticket.worker)}
/>
<ReportField
label="Submitted At"
value={
repair.submitted_at ? formatRepairDate(repair.submitted_at) : null
}
/>
</div>
<div className="space-y-2">
<MetaLabel>Repair Summary</MetaLabel>
{repair.notes?.trim() ? (
<div className="rounded-lg border bg-muted/15 px-4 py-3">
<p className="text-sm leading-relaxed text-foreground/90">
{repair.notes}
</p>
</div>
) : (
<EmptyPanel
icon={MessageSquareQuote}
title="No repair notes added yet"
className="py-6"
/>
)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,78 +0,0 @@
'use client';
import { ShieldCheck } from 'lucide-react';
import { ProtectedVideoPlayer } from '@/components/media/ProtectedVideoPlayer';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketDetail } from '@/types';
export function RepairVideoComparison({ ticket }: { ticket: TicketDetail }) {
const originalVideoUrl = ticket.video?.url ?? null;
const repairVideoUrl = ticket.repair?.proof_video_url ?? null;
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<ShieldCheck className="size-5 text-primary" />
Repair Verification
</CardTitle>
</CardHeader>
<CardContent className="grid grid-cols-1 gap-4 lg:grid-cols-2">
<ComparisonVideoItem
tooltip={ticket.video?.name ?? 'Original inspection video'}
videoLabel="Before"
videoUrl={originalVideoUrl}
meta="AI detection video"
emptyTitle="No original video available"
emptyDescription="The source inspection video is not attached to this ticket."
/>
<ComparisonVideoItem
tooltip="Contractor repair evidence video"
videoLabel="After"
videoUrl={repairVideoUrl}
meta="Contractor evidence video"
emptyTitle={
ticket.repair
? 'No repair video uploaded'
: 'No evidence submitted yet'
}
emptyDescription={
ticket.repair
? 'The assigned worker has not uploaded a repair video yet.'
: 'Repair video will appear here once evidence is submitted.'
}
/>
</CardContent>
</Card>
);
}
function ComparisonVideoItem({
tooltip,
videoLabel,
videoUrl,
meta,
emptyTitle,
emptyDescription,
}: {
tooltip: string;
videoLabel: string;
videoUrl: string | null;
meta: string;
emptyTitle: string;
emptyDescription: string;
}) {
return (
<div title={tooltip}>
<ProtectedVideoPlayer
url={videoUrl}
label={videoLabel}
meta={meta}
emptyTitle={emptyTitle}
emptyDescription={emptyDescription}
/>
</div>
);
}

View File

@@ -1,69 +0,0 @@
'use client';
import type { LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { TicketActor } from '@/types';
export function formatRepairDate(value: string | null | undefined) {
if (!value) return '-';
return new Intl.DateTimeFormat('en-IN', {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(value));
}
export function getPersonLabel(person: TicketActor | null | undefined) {
return person?.name || person?.email || 'Unknown';
}
export function SectionLabel({ children }: { children: React.ReactNode }) {
return (
<p className="text-[11px] font-semibold tracking-[0.12em] text-foreground uppercase">
{children}
</p>
);
}
export function ReportSurface({
children,
className,
}: {
children: React.ReactNode;
className?: string;
}) {
return (
<div className={cn('rounded-lg border bg-muted/15 p-3', className)}>
{children}
</div>
);
}
export function EmptyPanel({
icon: Icon,
title,
description,
className,
}: {
icon: LucideIcon;
title: string;
description?: string;
className?: string;
}) {
return (
<div
className={cn(
'flex flex-col items-center justify-center rounded-lg border border-dashed border-border/80 bg-muted/10 px-4 py-8 text-center',
className,
)}
>
<Icon className="mb-3 size-6 text-muted-foreground" />
<p className="text-sm font-medium text-muted-foreground">{title}</p>
{description ? (
<p className="mt-1 max-w-xs text-xs text-muted-foreground/80">
{description}
</p>
) : null}
</div>
);
}

View File

@@ -0,0 +1,114 @@
'use client';
import { useEffect, useMemo } from 'react';
import { useQueries } from '@tanstack/react-query';
import LightGallery from 'lightgallery/react';
import lgThumbnail from 'lightgallery/plugins/thumbnail';
import lgZoom from 'lightgallery/plugins/zoom';
import { Skeleton } from '@/components/ui/skeleton';
import { protectedMediaService } from '@/services/api';
interface RepairProofGalleryProps {
imageUrls: string[];
}
const MAX_VISIBLE_IMAGES = 8;
export function RepairProofGallery({ imageUrls }: RepairProofGalleryProps) {
const queries = useQueries({
queries: imageUrls.map((url) => ({
queryKey: ['protected-media', 'v2', url],
queryFn: () => protectedMediaService.getBlob(url),
staleTime: Infinity,
gcTime: 1000 * 60 * 30,
})),
});
const blobs = queries.map((query) => query.data);
const objectUrls = useMemo(
() => blobs.map((blob) => (blob ? URL.createObjectURL(blob) : null)),
// eslint-disable-next-line react-hooks/exhaustive-deps
[...blobs],
);
useEffect(
() => () => {
objectUrls.forEach((url) => {
if (url) URL.revokeObjectURL(url);
});
},
[objectUrls],
);
if (queries.some((query) => query.isLoading)) {
return (
<div className="grid grid-cols-4 gap-1 overflow-hidden rounded-lg">
{imageUrls.slice(0, MAX_VISIBLE_IMAGES).map((url, index) => (
<Skeleton
key={`${url}-${index}`}
className="aspect-square rounded-lg"
/>
))}
</div>
);
}
const images = objectUrls.flatMap((url, index) =>
url ? [{ url, originalIndex: index }] : [],
);
const visibleCount = Math.min(MAX_VISIBLE_IMAGES, images.length);
const overflowCount = images.length - visibleCount;
if (images.length === 0) {
return (
<div className="rounded-lg border border-dashed py-8 text-center text-sm text-muted-foreground">
Repair images are unavailable.
</div>
);
}
return (
<LightGallery
elementClassNames="grid grid-cols-4 gap-1 overflow-hidden rounded-lg"
mode="lg-fade"
speed={400}
plugins={[lgThumbnail, lgZoom]}
thumbnail
download={false}
mobileSettings={{ controls: true, showCloseIcon: true, download: false }}
>
{images.map(({ url, originalIndex }, index) => {
const isVisible = index < visibleCount;
const isOverflowTile = overflowCount > 0 && index === visibleCount - 1;
return (
<a
key={imageUrls[originalIndex]}
data-src={url}
data-sub-html={`<p>Repair evidence ${originalIndex + 1}</p>`}
className={isVisible ? 'group relative aspect-square' : 'hidden'}
aria-label={
isOverflowTile
? `View all ${images.length} repair images`
: `View repair image ${originalIndex + 1} of ${images.length}`
}
>
{/* Blob URLs cannot be handled by next/image. */}
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={url}
alt={`Repair evidence ${originalIndex + 1}`}
className="size-full object-cover transition duration-300 group-hover:scale-[1.03] group-hover:brightness-90"
/>
{isOverflowTile ? (
<span className="absolute inset-0 flex items-center justify-center bg-black/55 text-xl font-semibold text-white transition-colors group-hover:bg-black/65">
+{overflowCount}
</span>
) : null}
</a>
);
})}
</LightGallery>
);
}

View File

@@ -0,0 +1,103 @@
import { CheckCircle2, HardHat, Wrench, ToolCase } from 'lucide-react';
import { ProtectedVideoPlayer } from '@/components/media/ProtectedVideoPlayer';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import type { TicketDetail } from '@/types';
import { formatDate } from '@/utils/date';
import { RepairProofGallery } from './RepairProofGallery';
function SubmittedBanner({
submittedAt,
submitterName,
}: {
submittedAt: string;
submitterName: string;
}) {
return (
<div className="flex items-start gap-3 rounded-lg border border-emerald-200 bg-emerald-50 px-3 py-3 dark:border-emerald-900/60 dark:bg-emerald-950/30">
<CheckCircle2 className="mt-0.5 size-5 shrink-0 text-emerald-600 dark:text-emerald-400" />
<div className="min-w-0 space-y-0.5">
<p className="text-sm font-semibold text-emerald-800 dark:text-emerald-200">
Repair Submitted
</p>
<p className="text-xs text-emerald-700/80 dark:text-emerald-300/80">
{formatDate(submittedAt)} by {submitterName}
</p>
</div>
</div>
);
}
function ImageGallery({
imageUrls,
hasVideo,
}: {
imageUrls: string[];
hasVideo: boolean;
}) {
if (imageUrls.length === 0) {
return hasVideo ? null : (
<div className="flex items-center gap-2 rounded-lg border border-dashed px-3 py-4 text-sm text-muted-foreground">
<HardHat className="size-4 shrink-0" />
No media attached
</div>
);
}
return <RepairProofGallery imageUrls={imageUrls} />;
}
function Notes({ notes }: { notes: string | null | undefined }) {
return (
<div className="space-y-1.5">
<p className="text-xs font-semibold text-foreground">Repair Notes</p>
<p className="text-sm leading-relaxed text-muted-foreground">
{notes?.trim() || 'No repair notes provided.'}
</p>
</div>
);
}
export function RepairProofSummary({ ticket }: { ticket: TicketDetail }) {
const repair = ticket.repair;
if (!repair?.submitted_at) {
return null;
}
const submitterName = ticket.worker?.name?.trim() || 'Assigned worker';
return (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2 text-base">
<ToolCase className="text-primary" />
Repair Proof
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<SubmittedBanner
submittedAt={repair.submitted_at}
submitterName={submitterName}
/>
<ProtectedVideoPlayer
url={repair.proof_video_url}
meta="Contractor evidence video"
emptyTitle="No repair video uploaded"
emptyDescription="The assigned worker has not uploaded a repair video."
className="rounded-lg"
/>
<ImageGallery
imageUrls={repair.proof_image_urls}
hasVideo={Boolean(repair.proof_video_url)}
/>
<Notes notes={repair.notes} />
</CardContent>
</Card>
);
}

View File

@@ -17,7 +17,6 @@ import {
import { TicketHistoryCard } from './components/TicketHistoryCard';
import { TicketOverviewCard } from './components/TicketOverviewCard';
import { TicketRepairReportCard } from './components/TicketRepairReportCard';
import { TicketStatusActions } from './components/TicketStatusActions';
import { TicketDefectClassTabs } from './components/TicketDefectClassTabs';
import { useTicketDetailEvents } from '../hooks/useTicketDetailEvents';
@@ -73,17 +72,14 @@ export default function TicketDetailPage() {
) : (
<TicketOverviewCardSkeleton />
)}
<TicketDefectClassTabs ticketId={ticketId} ticket={overview} />
{isClassDetailLoading ? <TicketClassContentSkeleton /> : null}
{!isClassDetailLoading && classDetail ? (
<>
<TicketRepairReportCard ticket={classDetail} />
<TicketHistoryCard ticket={classDetail} />
</>
) : null}
</div>
<div className="space-y-3 self-start">
<TicketDefectClassTabs ticketId={ticketId} />
{isClassDetailLoading ? <TicketClassActionsSkeleton /> : null}
{!isClassDetailLoading && classDetail ? (
<TicketStatusActions ticket={classDetail} />

View File

@@ -4,15 +4,18 @@ import { useMemo } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';
import { ticketService } from '@/services/api';
import { ticketService, videoService } from '@/services/api';
import type {
AssignTicketPayload,
CloseTicketPayload,
RequestTicketExtensionPayload,
ReviewTicketExtensionPayload,
ReviewRepairPayload,
SubmitRepairPayload,
SubmitRepairUploadPayload,
TicketDetail,
TicketListParams,
VideoDetectionsParams,
} from '@/types';
import { ticketKeys } from '../queries/ticketKeys';
@@ -83,6 +86,52 @@ export function useTicketDefectClassesQuery(ticketId: string | undefined) {
});
}
export function useTicketClassDetectionsQuery(
videoId: string | undefined,
params: VideoDetectionsParams,
) {
const queryParams = useMemo(
() => ({
skip: params.skip ?? 0,
limit: params.limit ?? 1,
class_name: params.class_name,
min_confidence: params.min_confidence,
sort: params.sort ?? 'timestamp_asc',
search: params.search,
}),
[
params.class_name,
params.limit,
params.min_confidence,
params.search,
params.skip,
params.sort,
],
);
return useQuery({
queryKey: ticketKeys.classDetections(videoId ?? '', queryParams),
queryFn: () =>
videoService.getVideoDetections(videoId as string, queryParams),
enabled: Boolean(videoId && queryParams.class_name),
});
}
export function useTicketExtensionRequestQuery(
ticketId: string | undefined,
assignmentId: number | undefined,
) {
return useQuery({
queryKey: ticketKeys.extensionRequest(ticketId ?? '', assignmentId),
queryFn: () =>
ticketService.getTicketExtensionRequest(
ticketId as string,
assignmentId as number,
),
enabled: Boolean(ticketId && assignmentId),
});
}
export function useAssignableTicketUsersQuery(enabled: boolean) {
return useQuery({
queryKey: ticketKeys.assignableUsers(),
@@ -158,6 +207,64 @@ export function useSubmitRepairUploadMutation(ticketId: string) {
});
}
export function useRequestTicketExtensionMutation(
ticketId: string,
assignmentId: number | undefined,
defectClass: string,
) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: RequestTicketExtensionPayload) => {
if (assignmentId === undefined) {
throw new Error('No active assignment is available for this ticket.');
}
return ticketService.requestTicketExtension(
ticketId,
assignmentId,
payload,
);
},
onSuccess: () => {
toast.success('Extension request submitted');
queryClient.invalidateQueries({
queryKey: ticketKeys.extensionRequest(ticketId, assignmentId),
});
queryClient.invalidateQueries({
queryKey: ticketKeys.classDetail(ticketId, defectClass),
});
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
},
onError: () => toast.error('Failed to request an extension'),
});
}
export function useReviewTicketExtensionMutation(
ticketId: string,
assignmentId: number,
defectClass: string,
) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (payload: ReviewTicketExtensionPayload) =>
ticketService.reviewTicketExtension(ticketId, assignmentId, payload),
onSuccess: (_response, payload) => {
toast.success(
payload.action === 'approve'
? 'Extension request approved'
: 'Extension request rejected',
);
queryClient.invalidateQueries({
queryKey: ticketKeys.extensionRequest(ticketId, assignmentId),
});
queryClient.invalidateQueries({
queryKey: ticketKeys.classDetail(ticketId, defectClass),
});
queryClient.invalidateQueries({ queryKey: ticketKeys.lists() });
},
onError: () => toast.error('Failed to review extension request'),
});
}
export function useReviewRepairMutation(ticketId: string) {
const queryClient = useQueryClient();

View File

@@ -1,4 +1,4 @@
import type { TicketListParams } from '@/types';
import type { TicketListParams, VideoDetectionsParams } from '@/types';
export const ticketKeys = {
all: ['tickets'] as const,
@@ -9,7 +9,17 @@ export const ticketKeys = {
[...ticketKeys.details(), ticketId, 'overview'] as const,
classDetail: (ticketId: string, defectClass: string) =>
[...ticketKeys.details(), ticketId, 'class', defectClass] as const,
classDetections: (videoId: string, params: VideoDetectionsParams) =>
[...ticketKeys.details(), 'video', videoId, 'detections', params] as const,
defectClasses: (ticketId: string) =>
[...ticketKeys.details(), ticketId, 'defect-classes'] as const,
extensionRequest: (ticketId: string, assignmentId: number | undefined) =>
[
...ticketKeys.details(),
ticketId,
'assignments',
assignmentId,
'extension-request',
] as const,
assignableUsers: () => [...ticketKeys.all, 'assignable-users'] as const,
};

View File

@@ -6,6 +6,7 @@ import { Loader2, Play } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
@@ -89,19 +90,17 @@ export function CreateUploadDialog({
return (
<Dialog open={open} onOpenChange={handleOpenChange}>
<DialogContent
className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-5xl"
className="sm:max-w-5xl"
onOpenAutoFocus={(event) => event.preventDefault()}
>
<DialogHeader className="shrink-0 border-b px-6 py-4 pr-12">
<DialogTitle className="text-lg leading-none font-semibold tracking-tight">
Upload Video
</DialogTitle>
<DialogHeader>
<DialogTitle>Upload Video</DialogTitle>
<DialogDescription>
Configure location and upload road inspection data.
</DialogDescription>
</DialogHeader>
<div className="min-h-0 flex-1 space-y-5 overflow-y-auto px-6 py-4">
<DialogBody className="space-y-5">
<LocationSection
value={session}
onChange={setSession}
@@ -130,13 +129,13 @@ export function CreateUploadDialog({
portalContainer={dropdownPortalRef}
/>
{error ? (
<div className="rounded-md border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
<div className="rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-2 text-sm text-destructive">
{error}
</div>
) : null}
</div>
</DialogBody>
<DialogFooter className="shrink-0 border-t px-6 py-4">
<DialogFooter>
<Button
type="button"
variant="outline"

View File

@@ -1,5 +1,6 @@
'use client';
import { useRouter } from 'next/navigation';
import {
Download,
Eye,
@@ -29,6 +30,8 @@ export function UploadActionsMenu({
upload,
onViewVideo,
}: UploadActionsMenuProps) {
const router = useRouter();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -61,7 +64,15 @@ export function UploadActionsMenu({
<DropdownMenuItem>
<RotateCcw /> Retry Analysis
</DropdownMenuItem>
<DropdownMenuItem disabled={!upload.ticket_id}>
<DropdownMenuItem
disabled={!upload.ticket_id}
onClick={(event) => {
event.stopPropagation();
if (upload.ticket_id) {
router.push(`/ticket/${upload.ticket_id}`);
}
}}
>
<Ticket /> Open Ticket
</DropdownMenuItem>
<DropdownMenuSeparator />

View File

@@ -56,7 +56,7 @@ export function UploadFileDropzone({
handleFiles(event.dataTransfer.files);
}}
className={cn(
'group flex min-h-32 cursor-pointer flex-col justify-between rounded-md border border-dashed bg-card/60 p-4 transition-colors',
'group flex min-h-32 cursor-pointer flex-col justify-between rounded-lg border border-dashed bg-card/60 p-4 transition-colors',
'hover:border-primary/60 hover:bg-secondary/40',
isDragging && 'border-primary bg-secondary/60',
disabled && 'pointer-events-none cursor-not-allowed opacity-60',
@@ -72,7 +72,7 @@ export function UploadFileDropzone({
/>
<div className="space-y-3">
<div className="flex size-9 items-center justify-center rounded-md border bg-background">
<div className="flex size-9 items-center justify-center rounded-lg border bg-background">
<UploadCloud className="size-4 text-muted-foreground" />
</div>
<div>

View File

@@ -39,18 +39,14 @@ export function useUploadListColumns(
return (
<div
className="flex aspect-video w-20 items-center justify-center overflow-hidden rounded-md border bg-muted bg-cover bg-center"
className="flex aspect-video w-20 items-center justify-center overflow-hidden rounded-lg border bg-muted bg-cover bg-center"
style={
thumbnail
? { backgroundImage: `url("${thumbnail}")` }
: undefined
}
role={thumbnail ? 'img' : undefined}
aria-label={
thumbnail
? `Thumbnail for ${row.original.video_name}`
: undefined
}
aria-label={thumbnail ? 'Upload thumbnail' : undefined}
>
{!thumbnail ? (
<Video className="size-5 text-muted-foreground" />
@@ -59,14 +55,6 @@ export function useUploadListColumns(
);
},
},
{
accessorKey: 'video_name',
header: 'Video Name',
size: 150,
cell: ({ row }) => (
<span className="font-medium">{row.original.video_name}</span>
),
},
{
id: 'uploaded_by',
header: 'Uploader',

View File

@@ -1,4 +1,4 @@
import { CircleX, TicketCheck } from 'lucide-react';
import { CircleMinus, CircleX, TicketCheck } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import type { UploadListItem } from '@/types';
@@ -10,7 +10,9 @@ export function UploadResultCell({ item }: { item: UploadListItem }) {
<Badge className="bg-violet-500/15 text-violet-600 dark:text-violet-400">
<TicketCheck /> Ticket Created
</Badge>
<p className="text-xs font-medium">{item.ticket_id}</p>
<p className="text-xs font-medium">
{item.ticket_name ?? item.ticket_id}
</p>
</div>
);
}
@@ -28,5 +30,17 @@ export function UploadResultCell({ item }: { item: UploadListItem }) {
);
}
if (item.result === 'no_defects_found') {
return (
<div className="space-y-1">
<div className="flex items-center gap-1.5 text-xs font-medium text-amber-500">
<CircleMinus className="size-3.5" /> No Defects Found
</div>
<p className="text-xs text-muted-foreground">
{item.total_detections ?? 0} issues detected
</p>
</div>
);
}
return <span className="text-muted-foreground"></span>;
}

View File

@@ -1,44 +0,0 @@
'use client';
import { ProtectedVideoPlayer } from '@/components/media/ProtectedVideoPlayer';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import type { UploadListItem } from '@/types';
interface UploadVideoDialogProps {
upload: UploadListItem | null;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function UploadVideoDialog({
upload,
open,
onOpenChange,
}: UploadVideoDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="gap-3 p-3 sm:max-w-5xl sm:p-4">
<DialogHeader className="min-w-0 pr-8">
<DialogTitle className="truncate text-left text-base">
Video Preview
</DialogTitle>
<DialogDescription className="truncate text-xs">
{upload?.video_name ?? 'Uploaded video'}
</DialogDescription>
</DialogHeader>
<ProtectedVideoPlayer
url={open ? upload?.raw_video_url : undefined}
className="rounded-lg"
unavailableTitle="Video preview unavailable"
/>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,41 @@
'use client';
import { ProtectedVideoPlayer } from '@/components/media/ProtectedVideoPlayer';
import {
Dialog,
DialogBody,
DialogContent,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import type { UploadListItem } from '@/types';
interface VideoPreviewDialogProps {
upload: UploadListItem | null;
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function VideoPreviewDialog({
upload,
open,
onOpenChange,
}: VideoPreviewDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-5xl">
<DialogHeader>
<DialogTitle>Video Preview</DialogTitle>
</DialogHeader>
<DialogBody>
<ProtectedVideoPlayer
url={open ? upload?.raw_video_url : undefined}
className="rounded-lg"
unavailableTitle="Video preview unavailable"
/>
</DialogBody>
</DialogContent>
</Dialog>
);
}

View File

@@ -0,0 +1,112 @@
'use client';
import { useCallback, useMemo, useRef } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { API_ROUTES } from '@/constants/apiRoutes';
import { useSseWithToken } from '@/hooks/sse/useSseWithToken';
import { videoService } from '@/services/api';
import type {
PaginationParams,
UploadListResponse,
UploadStatusEvent,
} from '@/types';
import { uploadKeys } from './useUploadQueries';
function getUploadListParams(queryKey: readonly unknown[]) {
const params = queryKey[2];
if (!params || typeof params !== 'object' || Array.isArray(params)) {
return undefined;
}
return params as PaginationParams;
}
function patchUploadList(
current: UploadListResponse | undefined,
event: UploadStatusEvent,
params?: PaginationParams,
) {
if (!current) return current;
const existingIndex = current.items.findIndex(
(upload) => upload.id === event.item.id,
);
if (existingIndex >= 0) {
return {
...current,
items: current.items.map((upload) =>
upload.id === event.item.id ? event.item : upload,
),
};
}
if (event.kind !== 'created') return current;
const nextTotal = current.total + 1;
if ((params?.skip ?? 0) !== 0) {
return { ...current, total: nextTotal };
}
const pageLimit = params?.limit ?? current.items.length + 1;
return {
items: [event.item, ...current.items].slice(0, pageLimit),
total: nextTotal,
};
}
export function useUploadListEvents(enabled = true) {
const queryClient = useQueryClient();
const hasInvalidatedAfterConnectionErrorRef = useRef(false);
const events = useMemo(
() => ({
upload_status: (event: UploadStatusEvent) => {
queryClient
.getQueryCache()
.findAll({ queryKey: uploadKeys.lists() })
.forEach((query) => {
queryClient.setQueryData<UploadListResponse>(
query.queryKey,
(current) =>
patchUploadList(
current,
event,
getUploadListParams(query.queryKey),
),
);
});
},
heartbeat: () => undefined,
}),
[queryClient],
);
const getPath = useCallback(
(token: string) => API_ROUTES.VIDEOS.UPLOAD_EVENTS(token),
[],
);
const onConnectionError = useCallback(() => {
if (hasInvalidatedAfterConnectionErrorRef.current) return;
hasInvalidatedAfterConnectionErrorRef.current = true;
queryClient.invalidateQueries({ queryKey: uploadKeys.lists() });
}, [queryClient]);
const onConnectionOpen = useCallback(() => {
hasInvalidatedAfterConnectionErrorRef.current = false;
}, []);
useSseWithToken({
enabled,
getToken: videoService.createUploadEventsToken,
getPath,
events,
onConnectionError,
onConnectionOpen,
});
}

View File

@@ -10,13 +10,15 @@ import type { UploadListItem } from '@/types';
import { CreateUploadDialog } from './components/CreateUploadDialog';
import { useUploadListColumns } from './components/UploadListColumns';
import { UploadTable } from './components/UploadTable';
import { UploadVideoDialog } from './components/UploadVideoDialog';
import { VideoPreviewDialog } from './components/VideoPreviewDialog';
import { useUploadFilters } from './hooks/useUploadFilters';
import { useUploadListEvents } from './hooks/useUploadListEvents';
import { useUploadsQuery } from './hooks/useUploadQueries';
export default function UploadPage() {
const { skip, setSkip, limit, setLimit } = useUploadFilters();
const uploadsQuery = useUploadsQuery({ skip, limit });
useUploadListEvents();
const [isCreateOpen, setIsCreateOpen] = useState(false);
const [videoUpload, setVideoUpload] = useState<UploadListItem | null>(null);
@@ -54,7 +56,7 @@ export default function UploadPage() {
</main>
<CreateUploadDialog open={isCreateOpen} onOpenChange={setIsCreateOpen} />
<UploadVideoDialog
<VideoPreviewDialog
upload={videoUpload}
open={Boolean(videoUpload)}
onOpenChange={(open) => {

View File

@@ -14,6 +14,7 @@ import { RoleSelect } from '@/components/lookups/RoleSelect';
import { Button } from '@/components/ui/button';
import {
Dialog,
DialogBody,
DialogContent,
DialogDescription,
DialogFooter,
@@ -67,13 +68,13 @@ export function UserSheet({
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="flex max-h-[calc(100vh-2rem)] flex-col gap-0 p-0 sm:max-w-xl">
<DialogHeader className="shrink-0 border-b px-6 py-4 pr-12">
<DialogTitle className="text-lg leading-none font-semibold tracking-tight">
<DialogContent className="sm:max-w-xl">
<DialogHeader>
<DialogTitle>
{userId ? 'Edit User' : 'Create User'}
</DialogTitle>
<DialogDescription className="text-sm">
<DialogDescription>
Assign user details and a role.
</DialogDescription>
</DialogHeader>
@@ -83,7 +84,7 @@ export function UserSheet({
onSubmit={onSubmit}
className="flex min-h-0 flex-1 flex-col"
>
<div className="max-h-[50vh] space-y-5 overflow-y-auto px-6 py-4">
<DialogBody className="space-y-5">
<div className="grid gap-4 md:grid-cols-2">
<FormField
id="first-name"
@@ -172,9 +173,9 @@ export function UserSheet({
readOnly
/>
</FormField>
</div>
</DialogBody>
<DialogFooter className="shrink-0 border-t px-6 py-4">
<DialogFooter>
<Button
type="button"
variant="outline"

View File

@@ -1,84 +1,86 @@
@import 'tailwindcss';
@import 'tw-animate-css';
@import './typography.css';
@import "tw-animate-css";
@import "shadcn/tailwind.css";
@custom-variant dark (&:is(.dark *));
:root {
--radius: 0.65rem;
--background: oklch(1 0 0);
--foreground: oklch(0.141 0.005 285.823);
--radius: 0.225rem;
--card: oklch(1 0 0);
--card-foreground: oklch(0.141 0.005 285.823);
--card-foreground: oklch(0.145 0 0);
--popover: oklch(1 0 0);
--popover-foreground: oklch(0.141 0.005 285.823);
--primary: oklch(0.541 0.281 293.009);
--primary-foreground: oklch(0.969 0.016 293.756);
--popover-foreground: oklch(0.145 0 0);
--primary: oklch(0.457 0.24 277.023);
--primary-foreground: oklch(0.962 0.018 272.314);
--secondary: oklch(0.967 0.001 286.375);
--secondary-foreground: oklch(0.21 0.006 285.885);
--muted: oklch(0.967 0.001 286.375);
--muted-foreground: oklch(0.552 0.016 285.938);
--accent: oklch(0.967 0.001 286.375);
--accent-foreground: oklch(0.21 0.006 285.885);
--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.92 0.004 286.32);
--input: oklch(0.92 0.004 286.32);
--ring: oklch(0.702 0.183 293.541);
--chart-1: oklch(0.65 0.18 25); /* Soft Red/Rose - High Priority */
--chart-2: oklch(0.78 0.12 75); /* Warm Amber - Distinct */
--chart-3: oklch(0.68 0.12 245); /* Azure Blue - Cool Professional */
--chart-4: oklch(0.75 0.1 165); /* Mint Teal - Balanced */
--chart-5: oklch(0.85 0.08 195); /* Soft Cyan - Subdued */
--border: oklch(0.922 0 0);
--input: oklch(0.922 0 0);
--ring: oklch(0.708 0 0);
--chart-1: oklch(0.785 0.115 274.713); /* Soft Red/Rose - High Priority */
--chart-2: oklch(0.585 0.233 277.117); /* Warm Amber - Distinct */
--chart-3: oklch(0.511 0.262 276.966); /* Azure Blue - Cool Professional */
--chart-4: oklch(0.457 0.24 277.023); /* Mint Teal - Balanced */
--chart-5: oklch(0.398 0.195 277.366); /* Soft Cyan - Subdued */
--chart-6: oklch(0.62 0.22 295); /* Deep Violet - Theme Primary */
--chart-8: oklch(0.58 0.2 335); /* Cool Magenta - Distant Accent */
--sidebar: oklch(0.985 0 0);
--sidebar-foreground: oklch(0.141 0.005 285.823);
--sidebar-primary: oklch(0.541 0.281 293.009);
--sidebar-primary-foreground: oklch(0.969 0.016 293.756);
--sidebar-accent: oklch(0.967 0.001 286.375);
--sidebar-accent-foreground: oklch(0.21 0.006 285.885);
--sidebar-border: oklch(0.92 0.004 286.32);
--sidebar-ring: oklch(0.702 0.183 293.541);
--sidebar-foreground: oklch(0.145 0 0);
--sidebar-primary: oklch(0.511 0.262 276.966);
--sidebar-primary-foreground: oklch(0.962 0.018 272.314);
--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);
--background: oklch(1 0 0);
--foreground: oklch(0.145 0 0);
}
.dark {
--background: oklch(0.141 0.005 285.823);
--background: oklch(0.145 0 0);
--foreground: oklch(0.985 0 0);
--card: oklch(0.21 0.006 285.885);
--card: oklch(0.205 0 0);
--card-foreground: oklch(0.985 0 0);
--popover: oklch(0.21 0.006 285.885);
--popover: oklch(0.205 0 0);
--popover-foreground: oklch(0.985 0 0);
--primary: oklch(0.606 0.25 292.717);
--primary-foreground: oklch(0.969 0.016 293.756);
--primary: oklch(0.398 0.195 277.366);
--primary-foreground: oklch(0.962 0.018 272.314);
--secondary: oklch(0.274 0.006 286.033);
--secondary-foreground: oklch(0.985 0 0);
--muted: oklch(0.274 0.006 286.033);
--muted-foreground: oklch(0.705 0.015 286.067);
--accent: oklch(0.274 0.006 286.033);
--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.38 0.189 293.745);
--chart-1: oklch(0.7 0.16 25);
--chart-2: oklch(0.82 0.14 75);
--chart-3: oklch(0.72 0.14 245);
--chart-4: oklch(0.78 0.12 165);
--chart-5: oklch(0.88 0.1 195);
--ring: oklch(0.556 0 0);
--chart-1: oklch(0.785 0.115 274.713);
--chart-2: oklch(0.585 0.233 277.117);
--chart-3: oklch(0.511 0.262 276.966);
--chart-4: oklch(0.457 0.24 277.023);
--chart-5: oklch(0.398 0.195 277.366);
--chart-6: oklch(0.65 0.24 295);
--chart-8: oklch(0.62 0.22 335);
--sidebar: oklch(0.21 0.006 285.885);
--sidebar: oklch(0.205 0 0);
--sidebar-foreground: oklch(0.985 0 0);
--sidebar-primary: oklch(0.606 0.25 292.717);
--sidebar-primary-foreground: oklch(0.969 0.016 293.756);
--sidebar-accent: oklch(0.274 0.006 286.033);
--sidebar-primary: oklch(0.585 0.233 277.117);
--sidebar-primary-foreground: oklch(0.962 0.018 272.314);
--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.38 0.189 293.745);
--sidebar-ring: oklch(0.556 0 0);
}
@theme inline {
--font-sans: 'Poppins', 'Poppins Fallback', system-ui, sans-serif;
--font-sans: var(--font-sans);
--font-mono: 'Geist Mono', 'Geist Mono Fallback', monospace;
--color-background: var(--background);
--color-foreground: var(--foreground);
@@ -119,28 +121,47 @@
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--font-heading: var(--font-sans);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
@layer base {
html {
scrollbar-gutter: stable;
}
html:has(body[data-scroll-locked]) {
scrollbar-gutter: auto;
}
@supports not (scrollbar-gutter: stable) {
html {
.scroll-stable {
overflow-y: scroll;
}
}
* {
@apply border-border outline-none;
@apply outline-none border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
.scroll-stable {
scrollbar-gutter: stable;
}
html {
@apply font-sans;
}
button:not(:disabled), [role="button"]:not(:disabled) {
cursor: pointer;
}
}
.detection-video-player .vds-slider-preview {
display: none;
}
.detection-video-player
.vds-slider-preview:has(.vds-slider-thumbnail img[src^='blob:']) {
display: flex;
}

View File

@@ -1,10 +1,20 @@
import type { Metadata } from 'next';
import { Geist_Mono, Poppins } from 'next/font/google';
import { Geist_Mono, Poppins, Inter } from 'next/font/google';
import '@vidstack/react/player/styles/default/theme.css';
import '@vidstack/react/player/styles/default/layouts/video.css';
import 'leaflet/dist/leaflet.css';
import 'lightgallery/css/lightgallery.css';
import 'lightgallery/css/lg-thumbnail.css';
import 'lightgallery/css/lg-zoom.css';
import './globals.css';
import { ThemeProvider } from '@/providers/ThemeProvider';
import AppInitializer from '@/providers/AppInitializer';
import QueryProvider from '@/providers/QueryProvider';
import { Toaster } from '@/components/ui/sonner';
import { TooltipProvider } from '@/components/ui/tooltip';
import { cn } from '@/lib/utils';
const inter = Inter({subsets:['latin'],variable:'--font-sans'});
const poppins = Poppins({
variable: '--font-poppins',
@@ -31,7 +41,11 @@ export default function RootLayout({
children: React.ReactNode;
}>) {
return (
<html lang="en" suppressHydrationWarning>
<html
lang="en"
suppressHydrationWarning
className={cn('font-sans', "font-sans", inter.variable)}
>
<head>
<link rel="stylesheet" href="/flags/flags.css" />
</head>
@@ -44,8 +58,10 @@ export default function RootLayout({
>
<QueryProvider>
<AppInitializer>
<TooltipProvider delayDuration={0}>
{children}
<Toaster position="top-center" />
</TooltipProvider>
</AppInitializer>
</QueryProvider>
</ThemeProvider>

View File

@@ -3,8 +3,8 @@ import Image from 'next/image';
import { cn } from '@/lib/utils';
const sizeClasses = {
sm: 'size-8 rounded-md border-2 p-0.5',
md: 'size-12 rounded-md border-2 p-1.5',
sm: 'size-8 rounded-lg border-2 p-0.5',
md: 'size-12 rounded-lg border-2 p-1.5',
lg: 'size-28 rounded-lg border-[5px] p-3',
} as const;

View File

@@ -0,0 +1,66 @@
import { getDefectVisual } from '@/constants/defectVisualConfig';
import type { BoundingBoxOverlayItem } from '@/types';
interface BoundingBoxOverlayProps {
detections: BoundingBoxOverlayItem[];
videoWidth: number;
videoHeight: number;
}
export default function BoundingBoxOverlay({
detections,
videoWidth,
videoHeight,
}: BoundingBoxOverlayProps) {
if (videoWidth <= 0 || videoHeight <= 0 || detections.length === 0) {
return null;
}
return (
<svg
aria-hidden="true"
className="pointer-events-none absolute inset-0 z-[2] size-full"
viewBox={`0 0 ${videoWidth} ${videoHeight}`}
preserveAspectRatio="xMidYMid meet"
>
{detections.map((detection) => {
const { bounding_box: box } = detection;
const color = getDefectVisual(detection.class_name).boundingBoxColor;
const label = `${detection.display_name} ${(detection.confidence * 100).toFixed(0)}%`;
const labelY = Math.max(box.y1 - 34, 0);
const labelWidth = Math.max(150, label.length * 17);
return (
<g key={detection.id}>
<rect
x={box.x1}
y={box.y1}
width={box.x2 - box.x1}
height={box.y2 - box.y1}
fill="none"
stroke={color}
strokeWidth="4"
vectorEffect="non-scaling-stroke"
/>
<rect
x={box.x1}
y={labelY}
width={labelWidth}
height="34"
fill={color}
/>
<text
x={box.x1 + 8}
y={labelY + 23}
fill="white"
fontSize="20"
fontWeight="600"
>
{label}
</text>
</g>
);
})}
</svg>
);
}

View File

@@ -1,6 +1,7 @@
'use client';
import React from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import {
Breadcrumb,
@@ -27,7 +28,9 @@ export function BreadcrumbBasic() {
<Breadcrumb>
<BreadcrumbList>
<BreadcrumbItem>
<BreadcrumbLink href="/">Home</BreadcrumbLink>
<BreadcrumbLink asChild>
<Link href="/">Home</Link>
</BreadcrumbLink>
</BreadcrumbItem>
{segments.length > 0 && <BreadcrumbSeparator />}
@@ -44,8 +47,8 @@ export function BreadcrumbBasic() {
{isLast ? (
<BreadcrumbPage>{formatSegment(segment)}</BreadcrumbPage>
) : (
<BreadcrumbLink href={href}>
{formatSegment(segment)}
<BreadcrumbLink asChild>
<Link href={href}>{formatSegment(segment)}</Link>
</BreadcrumbLink>
)}
</BreadcrumbItem>

View File

@@ -18,24 +18,36 @@ import {
Sidebar,
SidebarContent,
SidebarFooter,
SidebarGroup,
SidebarHeader,
SidebarRail,
SidebarMenu,
SidebarMenuItem,
SidebarMenuButton,
SidebarMenuItem,
SidebarMenuSub,
SidebarMenuSubButton,
SidebarMenuSubItem,
SidebarGroup,
SidebarGroupLabel,
SidebarRail,
SidebarTrigger,
useSidebar,
} from '@/components/ui/sidebar';
import {
Tooltip,
TooltipContent,
TooltipTrigger,
} from '@/components/ui/tooltip';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useAppStore } from '@/store/app.store';
function isRouteActive(pathname: string, path?: string) {
if (!path) return false;
return pathname === path || pathname.startsWith(`${path}/`);
}
export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const pathname = usePathname();
const { hasPermission } = usePermissions();
const { isMobile } = useSidebar();
const authUser = useAppStore((state) => state.user);
const navItems = filterMenuItems(menuItems, hasPermission);
const user = {
@@ -48,17 +60,21 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
return (
<Sidebar collapsible="icon" {...props}>
<SidebarHeader>
<div className="flex items-center gap-2 py-2">
<LogoWrapper size="sm" variant="sidebar" />
<SidebarHeader className="border-b border-sidebar-border px-3 py-3 group-data-[collapsible=icon]:items-center group-data-[collapsible=icon]:border-b-0 group-data-[collapsible=icon]:px-2">
<div className="flex h-8 w-full items-center gap-3 group-data-[collapsible=icon]:w-8 group-data-[collapsible=icon]:justify-center">
<SidebarBrandControl isMobile={isMobile} />
<div className="grid flex-1 text-left text-sm leading-tight group-data-[collapsible=icon]:hidden">
<span className="truncate font-semibold">RoadMonitor</span>
<span className="truncate text-xs">Road Intelligence</span>
</div>
<SidebarTrigger
className="ml-auto shrink-0 bg-sidebar/80 text-sidebar-foreground/80 hover:bg-sidebar-accent hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:hidden"
aria-label={isMobile ? 'Close menu' : 'Hide menu'}
/>
</div>
</SidebarHeader>
<SidebarContent>
<SidebarGroup>
<SidebarContent className="px-2 py-3">
<SidebarGroup className="p-0">
<SidebarMenu>
{navItems.map((item) => (
<SidebarNavItem
@@ -70,7 +86,7 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
</SidebarMenu>
</SidebarGroup>
</SidebarContent>
<SidebarFooter>
<SidebarFooter className="border-t border-sidebar-border px-3 py-3">
<NavUser user={user} />
</SidebarFooter>
<SidebarRail />
@@ -78,6 +94,27 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
);
}
function SidebarBrandControl({ isMobile }: { isMobile: boolean }) {
return (
<div className="group/sidebar-brand relative flex size-8 shrink-0 items-center justify-center">
<LogoWrapper
size="sm"
variant="sidebar"
className="transition-opacity duration-150 group-data-[collapsible=icon]:group-hover/sidebar-brand:opacity-0 group-data-[collapsible=icon]:group-focus-within/sidebar-brand:opacity-0"
/>
<Tooltip>
<TooltipTrigger asChild>
<SidebarTrigger
className="pointer-events-none absolute inset-0 bg-sidebar text-sidebar-foreground/80 opacity-0 shadow-none hover:bg-sidebar-accent hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:pointer-events-auto group-data-[collapsible=icon]:group-hover/sidebar-brand:opacity-100 group-data-[collapsible=icon]:group-focus-within/sidebar-brand:opacity-100"
aria-label={isMobile ? 'Close menu' : 'Open menu'}
/>
</TooltipTrigger>
<TooltipContent side="right">Open menu</TooltipContent>
</Tooltip>
</div>
);
}
function SidebarNavItem({
item,
pathname,
@@ -85,16 +122,23 @@ function SidebarNavItem({
item: MenuItem;
pathname: string;
}) {
const isActive = item.path ? pathname === item.path : false;
const isActive = isRouteActive(pathname, item.path);
const isChildActive =
item.children?.some((child) => child.path === pathname) ?? false;
item.children?.some((child) => isRouteActive(pathname, child.path)) ??
false;
const hasChildren = Boolean(item.children?.length);
const [open, setOpen] = React.useState(isChildActive);
React.useEffect(() => {
if (isChildActive) setOpen(true);
}, [isChildActive]);
if (hasChildren) {
return (
<Collapsible
asChild
defaultOpen={isChildActive}
open={open}
onOpenChange={setOpen}
className="group/collapsible"
>
<SidebarMenuItem>
@@ -112,7 +156,7 @@ function SidebarNavItem({
{child.path ? (
<SidebarMenuSubButton
asChild
isActive={pathname === child.path}
isActive={isRouteActive(pathname, child.path)}
>
<Link href={child.path}>
<child.icon />
@@ -147,4 +191,3 @@ function SidebarNavItem({
</SidebarMenuItem>
);
}

View File

@@ -14,11 +14,9 @@ import {
ComboboxTrigger,
ComboboxValue,
} from '@/components/ui/combobox';
import { cn } from '@/lib/utils';
import type {
AsyncSelectOption,
AsyncSelectProps,
} from './AsyncSelect.types';
import type { AsyncSelectOption, AsyncSelectProps } from './AsyncSelect.types';
import { VirtualSelectList } from './VirtualSelectList';
type VirtualizerHandle = Virtualizer<HTMLDivElement, Element>;
@@ -30,6 +28,8 @@ export function AsyncSelect({
searchPlaceholder = 'Search...',
emptyMessage = 'No items found.',
disabled = false,
triggerClassName,
renderSelectedOption,
portalContainer,
}: AsyncSelectProps) {
const [open, setOpen] = useState(false);
@@ -125,7 +125,10 @@ export function AsyncSelect({
<Button
type="button"
variant="outline"
className="w-full justify-between font-normal"
className={cn(
'w-full justify-between font-normal',
triggerClassName,
)}
disabled={isDisabled}
>
{isLoading && !selectedOption ? (
@@ -133,15 +136,21 @@ export function AsyncSelect({
<Loader2 className="size-4 animate-spin" />
Loading...
</span>
) : (
<>
{selectedOption && renderSelectedOption ? (
renderSelectedOption(selectedOption)
) : (
<ComboboxValue placeholder={triggerPlaceholder} />
)}
</>
)}
</Button>
}
/>
<ComboboxContent
container={portalContainer}
className="min-w-[var(--anchor-width)]"
className="min-w-(--anchor-width)"
>
<div className="border-b p-2">
<ComboboxInput

View File

@@ -1,8 +1,9 @@
import type { RefObject } from 'react';
import type { ReactNode, RefObject } from 'react';
export type AsyncSelectOption = {
value: string;
label: string;
data?: unknown;
};
export type PaginatedResult<T> = {
@@ -47,5 +48,7 @@ export interface AsyncSelectProps {
searchPlaceholder?: string;
emptyMessage?: string;
disabled?: boolean;
triggerClassName?: string;
renderSelectedOption?: (option: AsyncSelectOption) => ReactNode;
portalContainer?: RefObject<HTMLDivElement | null>;
}

View File

@@ -86,7 +86,7 @@ export function AuthBackground({ className }: AuthBackgroundProps) {
<div className="mb-9 inline-flex items-center gap-5 text-left">
<LogoWrapper
alt=""
className="size-28 rounded-2xl border-[5px] p-4"
className="size-28 rounded-lg border-[5px] p-4"
priority
variant="glass"
/>

View File

@@ -1,7 +1,12 @@
'use client';
import { Table } from '@tanstack/react-table';
import { ChevronLeft, ChevronRight } from 'lucide-react';
import {
ChevronLeft,
ChevronRight,
ChevronsLeft,
ChevronsRight,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
@@ -25,26 +30,33 @@ export function TableFooter<TData>({
pageSize?: number;
onPageSizeChange?: (pageSize: number) => void;
}) {
const rows = table.getRowModel().rows.length;
const currentPageSize = pageSize ?? table.getState().pagination.pageSize;
const selectedRowCount = Object.keys(table.getState().rowSelection).length;
const pageIndex = table.getState().pagination.pageIndex;
const rawPageCount = table.getPageCount();
const pageCount = Math.max(
1,
Number.isFinite(rawPageCount) && rawPageCount > 0 ? rawPageCount : 1,
);
return (
<div className="flex flex-col gap-3 text-sm text-muted-foreground sm:flex-row sm:items-center sm:justify-between">
<div className="flex flex-wrap items-center gap-3">
<span>
Showing {rows} of {totalItems}
</span>
<div className="flex flex-col gap-3 px-4 text-sm text-muted-foreground sm:flex-row sm:items-center sm:justify-between">
<div>
{selectedRowCount} of {totalItems} row(s) selected.
</div>
<div className="flex flex-wrap items-center gap-4 sm:justify-end">
{onPageSizeChange ? (
<div className="flex items-center gap-2">
<span>Rows per page</span>
<div className="flex items-center gap-2 text-foreground">
<span className="font-medium">Rows per page</span>
<Select
value={String(currentPageSize)}
onValueChange={(value) => onPageSizeChange(Number(value))}
onValueChange={(value) => table.setPageSize(Number(value))}
>
<SelectTrigger className="h-8 w-18 bg-background">
<SelectTrigger className="h-8 w-20 border-border bg-background shadow-none">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectContent align="end">
{PAGE_SIZE_OPTIONS.map((size) => (
<SelectItem key={size} value={String(size)}>
{size}
@@ -54,26 +66,57 @@ export function TableFooter<TData>({
</Select>
</div>
) : null}
<div className="min-w-24 text-foreground font-medium">
Page {pageIndex + 1} of {pageCount}
</div>
<div className="flex gap-2">
<div className="flex items-center gap-2">
<Button
type="button"
variant="outline"
size="sm"
size="icon-sm"
className="size-8 shadow-none"
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
aria-label="Go to first page"
>
<ChevronsLeft className="size-4" />
</Button>
<Button
type="button"
variant="outline"
size="icon-sm"
className="size-8 shadow-none"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
aria-label="Go to previous page"
>
<ChevronLeft className="size-4" />
Previous
</Button>
<Button
type="button"
variant="outline"
size="sm"
size="icon-sm"
className="size-8 shadow-none"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
aria-label="Go to next page"
>
Next
<ChevronRight className="size-4" />
</Button>
<Button
type="button"
variant="outline"
size="icon-sm"
className="size-8 shadow-none"
onClick={() => table.setPageIndex(pageCount - 1)}
disabled={!table.getCanNextPage()}
aria-label="Go to last page"
>
<ChevronsRight className="size-4" />
</Button>
</div>
</div>
</div>
);

View File

@@ -21,26 +21,35 @@ const TopHeader = ({
tableTools,
}: TopHeaderProps) => {
return (
<div className="space-y-4">
<div className="space-y-3">
{(title || onAddNew) && (
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div>
{title ? <h2>{title}</h2> : null}
<p className="text-muted-foreground">Total {itemCount ?? 0}</p>
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div className="min-w-0">
{title ? <h2 className="text-lg font-semibold">{title}</h2> : null}
<p className="text-sm text-muted-foreground">
Total {itemCount ?? 0}
</p>
</div>
{onAddNew ? (
<Button onClick={onAddNew}>
<Plus className="mr-2 size-4" />
<Button onClick={onAddNew} size="sm" className="w-fit">
<Plus className="size-4" />
{addButtonText}
</Button>
) : null}
</div>
)}
{(toolbar || tableTools) && (
<div className="flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
<div className="min-w-0 flex-1">{toolbar}</div>
{toolbar ? (
<div className="min-w-0 flex-1 **:data-[slot=input-group]:border-border [&_[data-slot=input-group]]:bg-background [&_[data-slot=input-group]]:shadow-none [&_[data-slot=select-trigger]]:border-border [&_[data-slot=select-trigger]]:bg-background [&_[data-slot=select-trigger]]:shadow-none">
{toolbar}
</div>
) : null}
{tableTools ? (
<div className="flex shrink-0 justify-end">{tableTools}</div>
<div className="flex shrink-0 justify-end **:data-[slot=button]:shadow-none">
{tableTools}
</div>
) : null}
</div>
)}

View File

@@ -16,7 +16,7 @@ import { getPinnedColumnStyles } from './columnStyles';
const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
return (
<ShadTableHeader className="sticky top-0 z-20 bg-card">
<ShadTableHeader className="sticky top-0 z-20 bg-muted/70 backdrop-blur supports-backdrop-filter:bg-muted/60">
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => {
@@ -39,9 +39,9 @@ const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
canSort ? header.column.getToggleSortingHandler() : undefined
}
className={cn(
'h-10 max-w-0 overflow-hidden border-b border-border bg-card px-2 text-foreground transition-colors',
canSort && 'cursor-pointer select-none hover:bg-muted/60',
sortDirection && 'bg-muted/70',
'h-11 max-w-0 overflow-hidden border-b border-border bg-muted/70 px-4 text-sm font-semibold text-foreground transition-colors',
canSort && 'cursor-pointer select-none hover:bg-muted',
sortDirection && 'bg-muted',
)}
>
{header.isPlaceholder ? null : (
@@ -70,7 +70,7 @@ const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
className={cn(
'absolute -right-2 top-0 h-full w-1 cursor-col-resize touch-none select-none rounded bg-border opacity-0 transition-opacity hover:opacity-100',
'absolute -right-2 top-0 h-full w-1 cursor-col-resize touch-none select-none rounded-lg bg-border opacity-0 transition-opacity hover:opacity-100',
header.column.getIsResizing() && 'opacity-100',
)}
/>

View File

@@ -23,14 +23,20 @@ export function TableSearchInput({
className,
}: TableSearchInputProps) {
return (
<InputGroup className={cn('md:max-w-xs', className)}>
<InputGroup
className={cn(
'h-9 border-border bg-background shadow-none md:max-w-xs',
className,
)}
>
<InputGroupAddon>
<Search />
<Search className="size-4" />
</InputGroupAddon>
<InputGroupInput
value={value}
onChange={(event) => onChange(event.target.value)}
placeholder={placeholder}
className="placeholder:text-muted-foreground/70"
/>
</InputGroup>
);

View File

@@ -15,7 +15,6 @@ import {
import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
import { Skeleton } from '@/components/ui/skeleton';
import { TooltipProvider } from '@/components/ui/tooltip';
import type { PermissionInput } from '@/hooks/usePermissions';
import { PermissionGuard } from '@/guards';
@@ -211,8 +210,8 @@ function DataTableContent<TData, TValue>({
},
manualPagination: !!pagination,
manualSorting: isManualSorting,
pageCount: pagination?.totalItems
? Math.ceil(pagination.totalItems / pagination.limit)
pageCount: pagination
? Math.ceil((pagination.totalItems ?? data.length) / pagination.limit)
: -1,
state: {
rowSelection,
@@ -247,8 +246,8 @@ function DataTableContent<TData, TValue>({
});
return (
<TooltipProvider delayDuration={0}>
<section className="space-y-4 rounded-lg border bg-card p-4">
<>
<section className="space-y-3">
<TopHeader
title={onAddNew ? title : undefined}
itemCount={pagination?.totalItems ?? data.length}
@@ -260,9 +259,9 @@ function DataTableContent<TData, TValue>({
}
/>
<div>
<div className="overflow-hidden rounded-lg border bg-background">
<Table
containerClassName="max-h-[calc(100vh-350px)] overflow-y-auto"
containerClassName="max-h-[calc(100vh-350px)] overflow-auto"
className="table-fixed border-separate border-spacing-0"
style={{ width: '100%', minWidth: table.getTotalSize() }}
>
@@ -274,7 +273,7 @@ function DataTableContent<TData, TValue>({
{columns.map((_, colIdx) => (
<TableCell
key={colIdx}
className="border-b border-border"
className="h-13 border-b border-border px-4 py-3"
>
<Skeleton className="h-4 w-full max-w-35" />
</TableCell>
@@ -291,7 +290,9 @@ function DataTableContent<TData, TValue>({
const truncate = shouldTruncateCell(cell.column);
const pinned = cell.column.getIsPinned();
const isActionsCell = cell.column.id === 'actions';
const isRowClickable = Boolean(onRowClick && !isActionsCell);
const isRowClickable = Boolean(
onRowClick && !isActionsCell,
);
const content = flexRender(
cell.column.columnDef.cell,
cell.getContext(),
@@ -307,8 +308,8 @@ function DataTableContent<TData, TValue>({
: undefined
}
className={cn(
'max-w-0 overflow-hidden border-b border-border',
pinned && 'bg-card',
'h-13 max-w-0 overflow-hidden border-b border-border px-4 py-3 text-sm',
pinned && 'bg-background',
isRowClickable && 'cursor-pointer',
isActionsCell && 'cursor-default',
)}
@@ -346,6 +347,6 @@ function DataTableContent<TData, TValue>({
onPageSizeChange={pagination?.onLimitChange}
/>
</section>
</TooltipProvider>
</>
);
}

View File

@@ -0,0 +1,171 @@
'use client';
import * as React from 'react';
import { CalendarDays, ChevronDownIcon, Globe2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Calendar } from '@/components/ui/calendar';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { cn } from '@/lib/utils';
const DEFAULT_TIME_ZONES = [
'UTC',
'Asia/Kolkata',
'Asia/Dubai',
'Asia/Singapore',
'Asia/Tokyo',
'Europe/London',
'America/New_York',
'America/Los_Angeles',
'Australia/Sydney',
] as const;
export interface DatePickerProps {
value?: Date;
defaultValue?: Date;
onChange?: (date: Date | undefined) => void;
timeZone?: string;
defaultTimeZone?: string;
onTimeZoneChange?: (timeZone: string) => void;
timeZones?: readonly string[];
showTimeZone?: boolean;
placeholder?: string;
disabled?: boolean;
className?: string;
}
function getBrowserTimeZone() {
return Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
}
function formatDate(date: Date, timeZone: string) {
return new Intl.DateTimeFormat(undefined, {
dateStyle: 'long',
timeZone,
}).format(date);
}
function getTimeZoneLabel(timeZone: string) {
return timeZone.replaceAll('_', ' ');
}
export function DatePicker(props: DatePickerProps) {
const {
value,
defaultValue,
onChange,
timeZone,
defaultTimeZone,
onTimeZoneChange,
timeZones = DEFAULT_TIME_ZONES,
showTimeZone = true,
placeholder = 'Pick a date',
disabled = false,
className,
} = props;
const isDateControlled = Object.hasOwn(props, 'value');
const isTimeZoneControlled = Object.hasOwn(props, 'timeZone');
const [internalDate, setInternalDate] = React.useState(defaultValue);
const [internalTimeZone, setInternalTimeZone] = React.useState(
defaultTimeZone ?? 'UTC',
);
React.useEffect(() => {
if (!isTimeZoneControlled && !defaultTimeZone) {
setInternalTimeZone(getBrowserTimeZone());
}
}, [defaultTimeZone, isTimeZoneControlled]);
const selectedDate = isDateControlled ? value : internalDate;
const selectedTimeZone = timeZone ?? internalTimeZone;
const availableTimeZones = React.useMemo(
() => Array.from(new Set([selectedTimeZone, ...timeZones])).filter(Boolean),
[selectedTimeZone, timeZones],
);
const handleDateChange = (nextDate: Date | undefined) => {
if (!isDateControlled) setInternalDate(nextDate);
onChange?.(nextDate);
};
const handleTimeZoneChange = (nextTimeZone: string | null) => {
if (!nextTimeZone) return;
if (!isTimeZoneControlled) setInternalTimeZone(nextTimeZone);
onTimeZoneChange?.(nextTimeZone);
};
return (
<Popover>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
disabled={disabled}
data-empty={!selectedDate}
className={cn(
'w-64 justify-between text-left font-normal data-[empty=true]:text-muted-foreground',
className,
)}
>
<span className="flex min-w-0 items-center gap-2">
<CalendarDays className="size-4 shrink-0" />
<span className="truncate">
{selectedDate
? formatDate(selectedDate, selectedTimeZone)
: placeholder}
</span>
</span>
<ChevronDownIcon className="size-4 shrink-0 text-muted-foreground" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={selectedDate}
onSelect={handleDateChange}
defaultMonth={selectedDate}
timeZone={selectedTimeZone}
/>
{showTimeZone ? (
<div className="flex items-center gap-2 border-t p-3">
<Globe2 className="size-4 shrink-0 text-muted-foreground" />
<Select
value={selectedTimeZone}
onValueChange={handleTimeZoneChange}
>
<SelectTrigger
size="sm"
className="min-w-0 flex-1"
aria-label="Time zone"
>
<SelectValue />
</SelectTrigger>
<SelectContent position="popper">
{availableTimeZones.map((zone) => (
<SelectItem key={zone} value={zone}>
{getTimeZoneLabel(zone)}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
) : null}
</PopoverContent>
</Popover>
);
}
export { DEFAULT_TIME_ZONES };

View File

@@ -0,0 +1,129 @@
'use client';
import * as React from 'react';
import type { Matcher } from 'react-day-picker';
import { Button } from '@/components/ui/button';
import { CalendarGridPicker } from '@/components/ui/calendar-grid-picker';
import { FormField } from '@/components/form/FormField';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
export interface DatePickerSimpleProps {
value?: Date;
defaultValue?: Date;
onChange?: (date: Date | undefined) => void;
label?: string;
placeholder?: string;
disabled?: boolean;
className?: string;
id?: string;
showLabel?: boolean;
startMonth?: Date;
endMonth?: Date;
disabledDates?: Matcher | Matcher[];
}
function startOfDay(date: Date) {
const next = new Date(date);
next.setHours(0, 0, 0, 0);
return next;
}
function clampDateToRange(date: Date, min: Date, max: Date) {
if (date < min) return min;
if (date > max) return max;
return date;
}
export function DatePickerSimple(props: DatePickerSimpleProps) {
const {
value,
defaultValue,
onChange,
label = 'Date of birth',
placeholder = 'Select date',
disabled = false,
className,
id = 'date',
showLabel = true,
startMonth,
endMonth,
disabledDates,
} = props;
const isControlled = Object.hasOwn(props, 'value');
const [open, setOpen] = React.useState(false);
const [internalDate, setInternalDate] = React.useState<Date | undefined>(
defaultValue,
);
const selectedDate = isControlled ? value : internalDate;
const today = React.useMemo(() => startOfDay(new Date()), []);
const resolvedStartMonth = React.useMemo(
() => startMonth ?? new Date(today.getFullYear() - 100, 0),
[startMonth, today],
);
const resolvedEndMonth = React.useMemo(
() => endMonth ?? today,
[endMonth, today],
);
const initialMonth = selectedDate
? startOfDay(selectedDate)
: clampDateToRange(today, resolvedStartMonth, resolvedEndMonth);
const handleSelect = (date: Date | undefined) => {
if (!isControlled) setInternalDate(date);
onChange?.(date);
setOpen(false);
};
const picker = (
<Popover
open={open}
onOpenChange={(nextOpen) => {
setOpen(nextOpen);
}}
>
<PopoverTrigger asChild>
<Button
type="button"
variant="outline"
id={id}
disabled={disabled}
data-empty={!selectedDate}
className="w-full justify-start font-normal data-[empty=true]:text-muted-foreground"
>
{selectedDate
? selectedDate.toLocaleDateString(undefined, { dateStyle: 'long' })
: placeholder}
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto overflow-hidden p-0" align="start">
<CalendarGridPicker
key={open ? 'open' : 'closed'}
mode="single"
selected={selectedDate}
defaultMonth={initialMonth}
startMonth={resolvedStartMonth}
endMonth={resolvedEndMonth}
disabled={disabledDates}
onSelect={handleSelect}
/>
</PopoverContent>
</Popover>
);
if (!showLabel) {
return <div className={cn('w-full', className)}>{picker}</div>;
}
return (
<FormField id={id} label={label} className={className ?? 'mx-auto w-44'}>
{picker}
</FormField>
);
}

View File

@@ -32,7 +32,7 @@ interface MultiSelectPopoverProps {
function checkboxClass(checked: boolean) {
return cn(
'flex size-4 shrink-0 items-center justify-center rounded border',
'flex size-4 shrink-0 items-center justify-center rounded-lg border',
checked && 'border-primary bg-primary text-primary-foreground',
);
}
@@ -106,7 +106,7 @@ export function MultiSelectPopover({
type="button"
onClick={toggleAll}
aria-label={`Toggle all ${label}`}
className="shrink-0 cursor-pointer rounded-md p-0.5 hover:bg-muted"
className="shrink-0 cursor-pointer rounded-lg p-0.5 hover:bg-muted"
>
<span className={checkboxClass(areAllSelected)}>
{areAllSelected ? <Check className="size-3" /> : null}
@@ -128,7 +128,7 @@ export function MultiSelectPopover({
return (
<div
key={option.value}
className="flex items-center gap-2 rounded-md px-2 py-1.5 hover:bg-muted"
className="flex items-center gap-2 rounded-lg px-2 py-1.5 hover:bg-muted"
>
<button
type="button"

View File

@@ -101,7 +101,7 @@ export function SelectPopover({
setOpen(false);
}}
className={cn(
'flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-sm hover:bg-muted',
'flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-left text-sm hover:bg-muted',
option.disabled && 'cursor-not-allowed opacity-60',
)}
>

View File

@@ -5,3 +5,5 @@ export { PhoneInput } from './phone-input/PhoneInput';
export { SelectPopover } from './SelectPopover';
export type { SelectPopoverOption } from './SelectPopover';
export { PasswordField } from './PasswordField';
export { DatePickerSimple } from './DatePickerSimple';
export type { DatePickerSimpleProps } from './DatePickerSimple';

View File

@@ -109,7 +109,7 @@ export function CountryCombobox({
type="button"
variant="ghost"
disabled={disabled}
className="h-9 shrink-0 gap-1 rounded-none border-r px-2.5 shadow-none hover:bg-transparent"
className="h-9 shrink-0 gap-1 rounded-lg border-r px-2.5 shadow-none hover:bg-transparent"
>
<CountryFlag country={value} />
</Button>

View File

@@ -7,7 +7,7 @@ export function CountryFlag({ country }: { country: CountryCode }) {
<div
aria-hidden
className={cn(
'flag inline-block h-3.75 w-5.5 shrink-0 rounded-[2px] bg-size-[100%_auto]',
'flag inline-block h-3.75 w-5.5 shrink-0 rounded-lg bg-size-[100%_auto]',
`flag-${country.toLowerCase()}`,
)}
/>

View File

@@ -59,7 +59,7 @@ export function PhoneInput({
return (
<div
className={cn(
'flex h-9 w-full min-w-0 rounded-md border border-input bg-transparent shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 dark:bg-input/30',
'flex h-9 w-full min-w-0 rounded-lg border border-input bg-transparent shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-[3px] focus-within:ring-ring/50 dark:bg-input/30',
ariaInvalid &&
'border-destructive focus-within:border-destructive focus-within:ring-destructive/20',
disabled && 'cursor-not-allowed opacity-50',
@@ -80,7 +80,7 @@ export function PhoneInput({
disabled={disabled}
aria-invalid={ariaInvalid}
placeholder={placeholder}
className="h-9 flex-1 rounded-none border-0 bg-transparent px-3 py-1 shadow-none focus-visible:ring-0"
className="h-9 flex-1 rounded-lg border-0 bg-transparent px-3 py-1 shadow-none focus-visible:ring-0"
/>
</div>
);

View File

@@ -1,5 +1,7 @@
'use client';
import { UserRound } from 'lucide-react';
import { AsyncSelect, usePaginatedSelect } from '@/components/async-select';
import type { AsyncSelectOption } from '@/components/async-select';
import { ticketKeys } from '@/app/(modules)/ticket/queries/ticketKeys';
@@ -14,6 +16,7 @@ function mapWorkerOption(user: AssignableTicketUser): AsyncSelectOption {
return {
value: String(user.id),
label: user.name || user.email || user.username,
data: user,
};
}
@@ -58,14 +61,40 @@ export function AssignableWorkerSelect({
[...ticketKeys.assignableUsers(), 'selected', workerId] as const,
});
const handleValueChange = (workerId: string) => {
const option = lookup.options.find((item) => item.value === workerId);
const user = option?.data as AssignableTicketUser | undefined;
if (user) onValueChange(workerId, user);
};
const selectedUser = lookup.selectedOption?.data as
| AssignableTicketUser
| undefined;
return (
<AsyncSelect
lookup={lookup}
onValueChange={onValueChange}
onValueChange={handleValueChange}
disabled={disabled}
placeholder="Select contractor"
searchPlaceholder="Search contractors"
emptyMessage="No assignable contractors found."
triggerClassName="h-auto min-h-14 py-2"
renderSelectedOption={(option) => (
<span className="flex min-w-0 items-center gap-2.5">
<span className="flex size-9 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
<UserRound className="size-5" aria-hidden />
</span>
<span className="min-w-0 text-left">
<span className="block truncate font-medium text-foreground">
{option.label}
</span>
<span className="block truncate text-xs text-muted-foreground">
{selectedUser?.role.name}
</span>
</span>
</span>
)}
/>
);
}

View File

@@ -1,5 +1,7 @@
import type { AssignableTicketUser } from '@/types';
export interface AssignableWorkerSelectProps {
value: string;
onValueChange: (value: string) => void;
onValueChange: (value: string, user: AssignableTicketUser) => void;
disabled?: boolean;
}

View File

@@ -0,0 +1,142 @@
'use client';
import dynamic from 'next/dynamic';
import { MapPin } from 'lucide-react';
import { cn } from '@/lib/utils';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '@/components/ui/card';
type DetectionLocationMapProps = {
latitude: number | null;
longitude: number | null;
label: string;
title?: string;
description?: string;
aspectRatio?: string;
showCoordinates?: boolean;
variant?: 'card' | 'plain';
className?: string;
};
type ClientDetectionLocationMapProps = {
latitude: number;
longitude: number;
label: string;
};
const ClientDetectionLocationMap = dynamic<ClientDetectionLocationMapProps>(
async () => {
const { CircleMarker, MapContainer, Popup, TileLayer } =
await import('react-leaflet');
return function ClientDetectionLocationMapInner({
latitude,
longitude,
label,
}: ClientDetectionLocationMapProps) {
return (
<MapContainer
key={`${latitude}:${longitude}`}
center={[latitude, longitude]}
zoom={17}
scrollWheelZoom={false}
className="h-full w-full"
>
<TileLayer
attribution="&copy; OpenStreetMap contributors"
url="https://tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<CircleMarker
center={[latitude, longitude]}
radius={10}
pathOptions={{
color: '#dc2626',
fillColor: '#dc2626',
fillOpacity: 0.75,
weight: 2,
}}
>
<Popup>{label}</Popup>
</CircleMarker>
</MapContainer>
);
};
},
{
ssr: false,
loading: () => <div className="h-full w-full animate-pulse bg-muted" />,
},
);
export default function DetectionLocationMap({
latitude,
longitude,
label,
title = 'Detection Location',
description = 'Selected log GPS coordinates',
aspectRatio = '16 / 9',
showCoordinates = true,
variant = 'card',
className,
}: DetectionLocationMapProps) {
const mapContent =
latitude == null || longitude == null ? (
<div
className="flex items-center justify-center rounded-lg border border-dashed bg-muted/30 px-4 py-8 text-sm text-muted-foreground"
style={{ aspectRatio }}
>
Coordinates are unavailable for the selected log.
</div>
) : (
<>
{showCoordinates ? (
<div className="text-sm text-muted-foreground">
{latitude.toFixed(6)}, {longitude.toFixed(6)}
</div>
) : null}
<div
className="overflow-hidden rounded-lg border bg-muted"
style={{ aspectRatio }}
>
<ClientDetectionLocationMap
latitude={latitude}
longitude={longitude}
label={label}
/>
</div>
</>
);
if (variant === 'plain') {
return (
<div className={cn('space-y-2', className)}>
{title ? (
<p className="text-muted-foreground">{title}</p>
) : null}
{mapContent}
</div>
);
}
return (
<Card className={cn('overflow-hidden', className)}>
<CardHeader className="border-b pb-4">
<div className="flex items-center gap-3">
<div className="rounded-lg bg-secondary p-2">
<MapPin className="h-5 w-5 text-primary" />
</div>
<div>
<CardTitle className="text-base font-semibold">{title}</CardTitle>
<CardDescription className="text-xs">{description}</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4 pt-6">{mapContent}</CardContent>
</Card>
);
}

View File

@@ -24,7 +24,8 @@ export function ProtectedVideoPlayer({
unavailableTitle = 'Video unavailable',
className,
}: ProtectedVideoPlayerProps) {
const { objectUrl, isLoading, isError } = useProtectedMediaObjectUrl(url);
const { objectUrl, mediaType, isLoading, isError } =
useProtectedMediaObjectUrl(url);
if (!url) {
return (
@@ -40,7 +41,7 @@ export function ProtectedVideoPlayer({
return (
<div
className={cn(
'flex aspect-video w-full flex-col items-center justify-center gap-3 rounded-md border bg-muted/30 text-foreground',
'flex aspect-video w-full flex-col items-center justify-center gap-3 rounded-lg border bg-muted/30 text-foreground',
className,
)}
>
@@ -68,25 +69,28 @@ export function ProtectedVideoPlayer({
return (
<div
className={cn(
'group relative overflow-hidden rounded-md border bg-black/90',
'group relative overflow-hidden rounded-lg border bg-black/90',
className,
)}
>
<video
src={objectUrl}
className="aspect-video w-full object-cover"
key={objectUrl}
className="aspect-video w-full bg-black object-contain"
controls
playsInline
/>
preload="metadata"
>
<source src={objectUrl} type={mediaType ?? 'video/mp4'} />
</video>
{label ? (
<span className="absolute top-3 left-3 rounded bg-black/65 px-2.5 py-1 text-[11px] font-semibold text-white backdrop-blur-sm">
<span className="absolute top-3 left-3 rounded-lg bg-black/65 px-2.5 py-1 text-[11px] font-semibold text-white backdrop-blur-sm">
{label}
</span>
) : null}
{meta ? (
<span className="pointer-events-none absolute top-3 right-3 max-w-[55%] truncate text-xs font-medium">
<span className="pointer-events-none absolute top-3 right-3 max-w-[55%] truncate text-xs font-medium text-white/90">
{meta}
</span>
) : null}
@@ -106,7 +110,7 @@ function VideoState({
return (
<div
className={cn(
'flex aspect-video flex-col items-center justify-center rounded-md border border-dashed border-border/80 bg-muted/10 px-4 py-8 text-center',
'flex aspect-video flex-col items-center justify-center rounded-lg border border-dashed border-border/80 bg-muted/10 px-4 py-8 text-center',
className,
)}
>

View File

@@ -1,40 +1,21 @@
'use client';
import * as React from 'react';
import { Moon, Sun } from 'lucide-react';
import { useTheme } from 'next-themes';
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
export function ModeToggle() {
const { setTheme } = useTheme();
const { resolvedTheme, setTheme } = useTheme();
const toggleTheme = () => {
setTheme(resolvedTheme === 'dark' ? 'light' : 'dark');
};
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="outline" size="icon">
<Button variant="outline" size="icon" onClick={toggleTheme}>
<Sun className="h-[1.2rem] w-[1.2rem] rotate-0 scale-100 transition-all dark:-rotate-90 dark:scale-0" />
<Moon className="absolute h-[1.2rem] w-[1.2rem] rotate-90 scale-0 transition-all dark:rotate-0 dark:scale-100" />
<span className="sr-only">Toggle theme</span>
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme('light')}>
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('dark')}>
Dark
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('system')}>
System
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}

View File

@@ -0,0 +1,72 @@
'use client';
import { UserRound } from 'lucide-react';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { cn } from '@/lib/utils';
import type { TicketActor } from '@/types';
import { getPersonLabel } from '@/utils/person';
type PersonAvatarProps = {
person: TicketActor | null | undefined;
size?: 'default' | 'sm' | 'lg';
className?: string;
};
export function PersonAvatar({
person,
size = 'default',
className,
}: PersonAvatarProps) {
const avatarUrl = person?.avatar_url?.trim();
return (
<Avatar size={size} className={className}>
{avatarUrl ? (
<AvatarImage src={avatarUrl} alt={getPersonLabel(person)} />
) : null}
<AvatarFallback className="bg-muted text-muted-foreground">
<UserRound
className={cn(
'shrink-0',
size === 'sm' ? 'size-3.5' : size === 'lg' ? 'size-5' : 'size-4',
)}
aria-hidden
/>
</AvatarFallback>
</Avatar>
);
}
type PersonInfoProps = {
person: TicketActor | null | undefined;
size?: 'default' | 'sm' | 'lg';
className?: string;
};
export function PersonInfo({
person,
size = 'sm',
className,
}: PersonInfoProps) {
if (!person) {
return <p className="text-sm text-muted-foreground">-</p>;
}
const name = person.name?.trim();
const email = person.email?.trim();
return (
<div className={cn('flex min-w-0 items-center gap-2.5', className)}>
<PersonAvatar person={person} size={size} />
<div className="min-w-0">
<p className="truncate text-sm text-foreground">
{name || email || 'Unknown'}
</p>
{name && email ? (
<p className="truncate text-xs text-muted-foreground">{email}</p>
) : null}
</div>
</div>
);
}

View File

@@ -0,0 +1,199 @@
"use client"
import * as React from "react"
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
function AlertDialog({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {
return <AlertDialogPrimitive.Root data-slot="alert-dialog" {...props} />
}
function AlertDialogTrigger({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {
return (
<AlertDialogPrimitive.Trigger data-slot="alert-dialog-trigger" {...props} />
)
}
function AlertDialogPortal({
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {
return (
<AlertDialogPrimitive.Portal data-slot="alert-dialog-portal" {...props} />
)
}
function AlertDialogOverlay({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Overlay>) {
return (
<AlertDialogPrimitive.Overlay
data-slot="alert-dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/10 duration-100 supports-backdrop-filter:backdrop-blur-xs data-open:animate-in data-open:fade-in-0 data-closed:animate-out data-closed:fade-out-0",
className
)}
{...props}
/>
)
}
function AlertDialogContent({
className,
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Content> & {
size?: "default" | "sm"
}) {
return (
<AlertDialogPortal>
<AlertDialogOverlay />
<AlertDialogPrimitive.Content
data-slot="alert-dialog-content"
data-size={size}
className={cn(
"group/alert-dialog-content fixed top-1/2 left-1/2 z-50 grid w-full -translate-x-1/2 -translate-y-1/2 gap-6 rounded-lg bg-popover p-6 text-popover-foreground ring-1 ring-foreground/10 duration-100 outline-none data-[size=default]:max-w-xs data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95",
className
)}
{...props}
/>
</AlertDialogPortal>
)
}
function AlertDialogHeader({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-header"
className={cn(
"grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]",
className
)}
{...props}
/>
)
}
function AlertDialogFooter({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end",
className
)}
{...props}
/>
)
}
function AlertDialogMedia({
className,
...props
}: React.ComponentProps<"div">) {
return (
<div
data-slot="alert-dialog-media"
className={cn(
"mb-2 inline-flex size-16 items-center justify-center rounded-lg bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8",
className
)}
{...props}
/>
)
}
function AlertDialogTitle({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {
return (
<AlertDialogPrimitive.Title
data-slot="alert-dialog-title"
className={cn(
"font-heading text-lg font-medium sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2",
className
)}
{...props}
/>
)
}
function AlertDialogDescription({
className,
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {
return (
<AlertDialogPrimitive.Description
data-slot="alert-dialog-description"
className={cn(
"text-sm text-balance text-muted-foreground md:text-pretty *:[a]:underline *:[a]:underline-offset-3 *:[a]:hover:text-foreground",
className
)}
{...props}
/>
)
}
function AlertDialogAction({
className,
variant = "default",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Action> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Action
data-slot="alert-dialog-action"
className={cn(className)}
{...props}
/>
</Button>
)
}
function AlertDialogCancel({
className,
variant = "outline",
size = "default",
...props
}: React.ComponentProps<typeof AlertDialogPrimitive.Cancel> &
Pick<React.ComponentProps<typeof Button>, "variant" | "size">) {
return (
<Button variant={variant} size={size} asChild>
<AlertDialogPrimitive.Cancel
data-slot="alert-dialog-cancel"
className={cn(className)}
{...props}
/>
</Button>
)
}
export {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogMedia,
AlertDialogOverlay,
AlertDialogPortal,
AlertDialogTitle,
AlertDialogTrigger,
}

View File

@@ -17,7 +17,7 @@ function Avatar({
data-slot="avatar"
data-size={size}
className={cn(
"group/avatar relative flex size-8 shrink-0 overflow-hidden rounded-full select-none data-[size=lg]:size-10 data-[size=sm]:size-6",
"group/avatar relative flex size-8 shrink-0 rounded-full select-none after:absolute after:inset-0 after:rounded-full after:border after:border-border after:mix-blend-darken data-[size=lg]:size-10 data-[size=sm]:size-6 dark:after:mix-blend-lighten",
className
)}
{...props}
@@ -32,7 +32,10 @@ function AvatarImage({
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
className={cn(
"aspect-square size-full rounded-full object-cover",
className
)}
{...props}
/>
)
@@ -59,7 +62,7 @@ function AvatarBadge({ className, ...props }: React.ComponentProps<"span">) {
<span
data-slot="avatar-badge"
className={cn(
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground ring-2 ring-background select-none",
"absolute right-0 bottom-0 z-10 inline-flex items-center justify-center rounded-full bg-primary text-primary-foreground bg-blend-color ring-2 ring-background select-none",
"group-data-[size=sm]/avatar:size-2 group-data-[size=sm]/avatar:[&>svg]:hidden",
"group-data-[size=default]/avatar:size-2.5 group-data-[size=default]/avatar:[&>svg]:size-2",
"group-data-[size=lg]/avatar:size-3 group-data-[size=lg]/avatar:[&>svg]:size-2",
@@ -103,7 +106,7 @@ export {
Avatar,
AvatarImage,
AvatarFallback,
AvatarBadge,
AvatarGroup,
AvatarGroupCount,
AvatarBadge,
}

View File

@@ -1,39 +1,40 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { Slot } from 'radix-ui';
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from '@/lib/utils';
import { cn } from "@/lib/utils"
const badgeVariants = cva(
'inline-flex w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-full border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-[color,box-shadow] outline-none aria-invalid:border-destructive [&>svg]:pointer-events-none [&>svg]:size-3',
"group/badge inline-flex h-5 w-fit shrink-0 items-center justify-center gap-1 overflow-hidden rounded-lg border border-transparent px-2 py-0.5 text-xs font-medium whitespace-nowrap transition-all focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&>svg]:pointer-events-none [&>svg]:size-3!",
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground [a&]:hover:bg-primary/90',
default: "bg-primary text-primary-foreground [a]:hover:bg-primary/80",
secondary:
'bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90',
"bg-secondary text-secondary-foreground [a]:hover:bg-secondary/80",
destructive:
'bg-destructive text-white dark:bg-destructive/60 [a&]:hover:bg-destructive/90',
"bg-destructive/10 text-destructive focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:focus-visible:ring-destructive/40 [a]:hover:bg-destructive/20",
outline:
'border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
ghost: '[a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
link: 'text-primary underline-offset-4 [a&]:hover:underline',
"border-border text-foreground [a]:hover:bg-muted [a]:hover:text-muted-foreground",
ghost:
"hover:bg-muted hover:text-muted-foreground dark:hover:bg-muted/50",
link: "text-primary underline-offset-4 hover:underline",
},
},
defaultVariants: {
variant: 'default',
variant: "default",
},
},
);
}
)
function Badge({
className,
variant = 'default',
variant = "default",
asChild = false,
...props
}: React.ComponentProps<'span'> &
}: React.ComponentProps<"span"> &
VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
const Comp = asChild ? Slot.Root : 'span';
const Comp = asChild ? Slot.Root : "span"
return (
<Comp
@@ -42,7 +43,7 @@ function Badge({
className={cn(badgeVariants({ variant }), className)}
{...props}
/>
);
)
}
export { Badge, badgeVariants };
export { Badge, badgeVariants }

View File

@@ -1,95 +1,114 @@
import * as React from 'react';
import Link from 'next/link';
import { ChevronRight, MoreHorizontal } from 'lucide-react';
import * as React from "react"
import { Slot } from "radix-ui"
import { cn } from '@/lib/utils';
import { cn } from "@/lib/utils"
import { ChevronRightIcon, MoreHorizontalIcon } from "lucide-react"
function Breadcrumb({ ...props }: React.ComponentProps<'nav'>) {
return <nav aria-label="breadcrumb" data-slot="breadcrumb" {...props} />;
function Breadcrumb({ className, ...props }: React.ComponentProps<"nav">) {
return (
<nav
aria-label="breadcrumb"
data-slot="breadcrumb"
className={cn(className)}
{...props}
/>
)
}
function BreadcrumbList({ className, ...props }: React.ComponentProps<'ol'>) {
function BreadcrumbList({ className, ...props }: React.ComponentProps<"ol">) {
return (
<ol
data-slot="breadcrumb-list"
className={cn(
'flex flex-wrap items-center gap-1.5 text-sm wrap-break-word text-muted-foreground sm:gap-2.5',
className,
"flex flex-wrap items-center gap-1.5 text-sm wrap-break-word text-muted-foreground sm:gap-2.5",
className
)}
{...props}
/>
);
)
}
function BreadcrumbItem({ className, ...props }: React.ComponentProps<'li'>) {
function BreadcrumbItem({ className, ...props }: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-item"
className={cn('inline-flex items-center gap-1.5', className)}
className={cn("inline-flex items-center gap-1.5", className)}
{...props}
/>
);
)
}
type BreadcrumbLinkProps = React.ComponentProps<typeof Link>;
function BreadcrumbLink({
asChild,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : "a"
function BreadcrumbLink({ className, ...props }: BreadcrumbLinkProps) {
return (
<Link
<Comp
data-slot="breadcrumb-link"
className={cn('transition-colors hover:text-foreground', className)}
className={cn("transition-colors hover:text-foreground", className)}
{...props}
/>
);
)
}
function BreadcrumbPage({ className, ...props }: React.ComponentProps<'span'>) {
function BreadcrumbPage({ className, ...props }: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-page"
role="link"
aria-disabled="true"
aria-current="page"
className={cn('font-normal text-foreground', className)}
className={cn("font-normal text-foreground", className)}
{...props}
/>
);
)
}
function BreadcrumbSeparator({
children,
className,
...props
}: React.ComponentProps<'li'>) {
}: React.ComponentProps<"li">) {
return (
<li
data-slot="breadcrumb-separator"
role="presentation"
aria-hidden="true"
className={cn('[&>svg]:size-3.5', className)}
className={cn("[&>svg]:size-3.5", className)}
{...props}
>
{children ?? <ChevronRight />}
{children ?? (
<ChevronRightIcon />
)}
</li>
);
)
}
function BreadcrumbEllipsis({
className,
...props
}: React.ComponentProps<'span'>) {
}: React.ComponentProps<"span">) {
return (
<span
data-slot="breadcrumb-ellipsis"
role="presentation"
aria-hidden="true"
className={cn('flex size-9 items-center justify-center', className)}
className={cn(
"flex size-5 items-center justify-center [&>svg]:size-4",
className
)}
{...props}
>
<MoreHorizontal className="size-4" />
<MoreHorizontalIcon
/>
<span className="sr-only">More</span>
</span>
);
)
}
export {
@@ -100,4 +119,4 @@ export {
BreadcrumbPage,
BreadcrumbSeparator,
BreadcrumbEllipsis,
};
}

View File

@@ -1,54 +1,57 @@
import * as React from 'react';
import { cva, type VariantProps } from 'class-variance-authority';
import { Slot } from 'radix-ui';
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"
import { cn } from '@/lib/utils';
import { cn } from "@/lib/utils"
const buttonVariants = cva(
"inline-flex cursor-pointer shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50 aria-invalid:border-destructive [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
"group/button inline-flex shrink-0 items-center justify-center rounded-lg border border-transparent bg-clip-padding text-sm font-medium whitespace-nowrap transition-all outline-none select-none focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 active:not-aria-[haspopup]:translate-y-px disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
{
variants: {
variant: {
default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive:
'bg-destructive text-white hover:bg-destructive/90 dark:bg-destructive/60',
default: "bg-primary text-primary-foreground hover:bg-primary/80",
outline:
'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground focus-visible:border-ring dark:border-input dark:bg-input/30 dark:hover:bg-input/50',
"border-border bg-background shadow-xs hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50",
secondary:
'bg-secondary text-secondary-foreground hover:bg-secondary/80',
"bg-secondary text-secondary-foreground hover:bg-[color-mix(in_oklch,var(--secondary),var(--foreground)_5%)] aria-expanded:bg-secondary aria-expanded:text-secondary-foreground",
ghost:
'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
link: 'text-primary underline-offset-4 hover:underline',
"hover:bg-muted hover:text-foreground aria-expanded:bg-muted aria-expanded:text-foreground dark:hover:bg-muted/50",
destructive:
"bg-destructive/10 text-destructive hover:bg-destructive/20 focus-visible:border-destructive/40 focus-visible:ring-destructive/20 dark:bg-destructive/20 dark:hover:bg-destructive/30 dark:focus-visible:ring-destructive/40",
link: "text-primary underline-offset-4 hover:underline",
},
size: {
default: 'h-9 px-4 py-2 has-[>svg]:px-3',
xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: 'h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5',
lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',
icon: 'size-9',
'icon-xs': "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3",
'icon-sm': 'size-8',
'icon-lg': 'size-10',
default:
"h-9 gap-1.5 px-2.5 in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
xs: "h-6 gap-1 rounded-lg px-2 text-xs in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5 [&_svg:not([class*='size-'])]:size-3",
sm: "h-8 gap-1 rounded-lg px-2.5 in-data-[slot=button-group]:rounded-lg has-data-[icon=inline-end]:pr-1.5 has-data-[icon=inline-start]:pl-1.5",
lg: "h-10 gap-1.5 px-2.5 has-data-[icon=inline-end]:pr-2 has-data-[icon=inline-start]:pl-2",
icon: "size-9",
"icon-xs":
"size-6 rounded-lg in-data-[slot=button-group]:rounded-lg [&_svg:not([class*='size-'])]:size-3",
"icon-sm":
"size-8 rounded-lg in-data-[slot=button-group]:rounded-lg",
"icon-lg": "size-10",
},
},
defaultVariants: {
variant: 'default',
size: 'default',
variant: "default",
size: "default",
},
},
);
}
)
function Button({
className,
variant = 'default',
size = 'default',
variant = "default",
size = "default",
asChild = false,
...props
}: React.ComponentProps<'button'> &
}: React.ComponentProps<"button"> &
VariantProps<typeof buttonVariants> & {
asChild?: boolean;
asChild?: boolean
}) {
const Comp = asChild ? Slot.Root : 'button';
const Comp = asChild ? Slot.Root : "button"
return (
<Comp
@@ -58,7 +61,7 @@ function Button({
className={cn(buttonVariants({ variant, size, className }))}
{...props}
/>
);
)
}
export { Button, buttonVariants };
export { Button, buttonVariants }

View File

@@ -0,0 +1,537 @@
'use client';
import * as React from 'react';
import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';
import { useDayPicker, type MonthCaptionProps } from 'react-day-picker';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Calendar, CalendarDayButton } from '@/components/ui/calendar';
type CalendarView = 'days' | 'months' | 'years';
const MONTH_LABELS = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
] as const;
const PICKER_WIDTH = 'w-[280px]';
const PICKER_SHELL_CLASS =
'group/calendar p-3 text-popover-foreground [--cell-size:--spacing(8)]';
const PICKER_HEADER_CLASS =
'grid min-h-8 grid-cols-[2rem_1fr_2rem] items-center gap-1 border-b border-border pb-2';
const PICKER_NAV_BUTTON_CLASS = 'size-8 shrink-0 p-0';
const GRID_BUTTON_CLASS =
'h-9 w-full rounded-lg font-medium text-foreground hover:bg-accent/60 hover:text-accent-foreground';
const GRID_BUTTON_ACTIVE_CLASS =
'bg-muted text-foreground hover:bg-muted hover:text-foreground';
const GRID_BUTTON_DISABLED_CLASS =
'text-muted-foreground opacity-50 hover:bg-transparent hover:text-muted-foreground';
function getMonthIndex(date: Date) {
return date.getFullYear() * 12 + date.getMonth();
}
function isYearOutsideRange(year: number, startMonth?: Date, endMonth?: Date) {
if (startMonth && year < startMonth.getFullYear()) return true;
if (endMonth && year > endMonth.getFullYear()) return true;
return false;
}
function isMonthOutsideRange(
year: number,
month: number,
startMonth?: Date,
endMonth?: Date,
) {
const monthIndex = year * 12 + month;
if (startMonth && monthIndex < getMonthIndex(startMonth)) return true;
if (endMonth && monthIndex > getMonthIndex(endMonth)) return true;
return false;
}
function clampMonthToRange(
year: number,
month: number,
startMonth?: Date,
endMonth?: Date,
) {
let nextMonth = month;
if (startMonth && year === startMonth.getFullYear()) {
nextMonth = Math.max(nextMonth, startMonth.getMonth());
}
if (endMonth && year === endMonth.getFullYear()) {
nextMonth = Math.min(nextMonth, endMonth.getMonth());
}
return Math.min(11, Math.max(0, nextMonth));
}
type CalendarGridPickerContextValue = {
view: CalendarView;
setView: (view: CalendarView) => void;
pickerYear: number;
setPickerYear: React.Dispatch<React.SetStateAction<number>>;
decadeStart: number;
setDecadeStart: React.Dispatch<React.SetStateAction<number>>;
};
const CalendarGridPickerContext =
React.createContext<CalendarGridPickerContextValue | null>(null);
function useCalendarGridPicker() {
const context = React.useContext(CalendarGridPickerContext);
if (!context) {
throw new Error(
'useCalendarGridPicker must be used within CalendarGridPicker',
);
}
return context;
}
function PickerNav({
label,
onPrevious,
onNext,
onLabelClick,
disablePrevious = false,
disableNext = false,
}: {
label: string;
onPrevious: () => void;
onNext: () => void;
onLabelClick?: () => void;
disablePrevious?: boolean;
disableNext?: boolean;
}) {
return (
<div className={PICKER_HEADER_CLASS}>
<Button
type="button"
variant="ghost"
size="icon-sm"
className={cn(PICKER_NAV_BUTTON_CLASS, 'justify-self-start')}
onClick={onPrevious}
disabled={disablePrevious}
aria-label="Previous"
>
<ChevronLeftIcon className="size-4" />
</Button>
{onLabelClick ? (
<button
type="button"
className="rounded-lg px-2 text-center text-sm font-semibold text-foreground hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={onLabelClick}
>
{label}
</button>
) : (
<span className="px-2 text-center text-sm font-semibold text-foreground">
{label}
</span>
)}
<Button
type="button"
variant="ghost"
size="icon-sm"
className={cn(PICKER_NAV_BUTTON_CLASS, 'justify-self-end')}
onClick={onNext}
disabled={disableNext}
aria-label="Next"
>
<ChevronRightIcon className="size-4" />
</Button>
</div>
);
}
function MonthGrid({
year,
activeMonth,
onSelect,
startMonth,
endMonth,
}: {
year: number;
activeMonth: number;
onSelect: (month: number) => void;
startMonth?: Date;
endMonth?: Date;
}) {
return (
<div className="grid grid-cols-3 gap-x-2 gap-y-1.5 pt-2">
{MONTH_LABELS.map((label, month) => {
const isDisabled = isMonthOutsideRange(
year,
month,
startMonth,
endMonth,
);
return (
<Button
key={label}
type="button"
variant="ghost"
disabled={isDisabled}
className={cn(
GRID_BUTTON_CLASS,
isDisabled && GRID_BUTTON_DISABLED_CLASS,
activeMonth === month && !isDisabled && GRID_BUTTON_ACTIVE_CLASS,
)}
onClick={() => onSelect(month)}
>
{label}
</Button>
);
})}
</div>
);
}
function YearGrid({
decadeStart,
activeYear,
onSelect,
startMonth,
endMonth,
}: {
decadeStart: number;
activeYear: number;
onSelect: (year: number) => void;
startMonth?: Date;
endMonth?: Date;
}) {
const years = React.useMemo(
() => Array.from({ length: 10 }, (_, index) => decadeStart + index),
[decadeStart],
);
return (
<div className="grid grid-cols-2 gap-x-3 gap-y-1.5 pt-2">
{years.map((year) => {
const isDisabled = isYearOutsideRange(year, startMonth, endMonth);
return (
<Button
key={year}
type="button"
variant="ghost"
disabled={isDisabled}
className={cn(
GRID_BUTTON_CLASS,
isDisabled && GRID_BUTTON_DISABLED_CLASS,
activeYear === year && !isDisabled && GRID_BUTTON_ACTIVE_CLASS,
)}
onClick={() => onSelect(year)}
>
{year}
</Button>
);
})}
</div>
);
}
function CalendarMonthCaption({
calendarMonth,
className,
children: _children,
displayIndex: _displayIndex,
...props
}: MonthCaptionProps) {
const { goToMonth, previousMonth, nextMonth } = useDayPicker();
const { setView, setPickerYear, setDecadeStart } = useCalendarGridPicker();
const date = calendarMonth.date;
const monthName = date.toLocaleString('default', { month: 'long' });
const year = date.getFullYear();
return (
<div className={cn(PICKER_HEADER_CLASS, className)} {...props}>
<Button
type="button"
variant="ghost"
size="icon-sm"
className={cn(PICKER_NAV_BUTTON_CLASS, 'justify-self-start')}
disabled={!previousMonth}
aria-label="Previous month"
onClick={() => previousMonth && goToMonth(previousMonth)}
>
<ChevronLeftIcon className="size-4" />
</Button>
<div className="flex items-center justify-center gap-1 text-sm font-semibold">
<button
type="button"
className="rounded-lg px-1 text-center text-sm font-semibold text-foreground hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => {
setPickerYear(year);
setView('months');
}}
>
{monthName}
</button>
<button
type="button"
className="rounded-lg px-1 text-center text-sm font-semibold text-foreground hover:text-accent-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => {
setDecadeStart(Math.floor(year / 10) * 10);
setPickerYear(year);
setView('years');
}}
>
{year}
</button>
</div>
<Button
type="button"
variant="ghost"
size="icon-sm"
className={cn(PICKER_NAV_BUTTON_CLASS, 'justify-self-end')}
disabled={!nextMonth}
aria-label="Next month"
onClick={() => nextMonth && goToMonth(nextMonth)}
>
<ChevronRightIcon className="size-4" />
</Button>
</div>
);
}
function CalendarGridPickerPanel({
month,
onMonthChange,
startMonth,
endMonth,
}: {
month: Date;
onMonthChange: (month: Date) => void;
startMonth?: Date;
endMonth?: Date;
}) {
const {
view,
setView,
pickerYear,
setPickerYear,
decadeStart,
setDecadeStart,
} = useCalendarGridPicker();
const minYear = startMonth?.getFullYear();
const maxYear = endMonth?.getFullYear();
const activeMonth = clampMonthToRange(
pickerYear,
month.getMonth(),
startMonth,
endMonth,
);
if (view === 'months') {
return (
<div className="w-full">
<PickerNav
label={String(pickerYear)}
onPrevious={() => setPickerYear((year) => year - 1)}
onNext={() => setPickerYear((year) => year + 1)}
onLabelClick={() => {
setDecadeStart(Math.floor(pickerYear / 10) * 10);
setView('years');
}}
disablePrevious={minYear !== undefined && pickerYear <= minYear}
disableNext={maxYear !== undefined && pickerYear >= maxYear}
/>
<MonthGrid
year={pickerYear}
activeMonth={activeMonth}
startMonth={startMonth}
endMonth={endMonth}
onSelect={(nextMonth) => {
onMonthChange(new Date(pickerYear, nextMonth, 1));
setView('days');
}}
/>
</div>
);
}
if (view === 'years') {
return (
<div className="w-full">
<PickerNav
label={`${decadeStart} - ${decadeStart + 9}`}
onPrevious={() => setDecadeStart((start) => start - 10)}
onNext={() => setDecadeStart((start) => start + 10)}
disablePrevious={minYear !== undefined && decadeStart <= minYear}
disableNext={maxYear !== undefined && decadeStart + 10 > maxYear}
/>
<YearGrid
decadeStart={decadeStart}
activeYear={pickerYear}
startMonth={startMonth}
endMonth={endMonth}
onSelect={(year) => {
const nextMonth = clampMonthToRange(
year,
activeMonth,
startMonth,
endMonth,
);
setPickerYear(year);
onMonthChange(new Date(year, nextMonth, 1));
setView('months');
}}
/>
</div>
);
}
return null;
}
export type CalendarGridPickerProps = Omit<
Extract<React.ComponentProps<typeof Calendar>, { mode: 'single' }>,
'captionLayout' | 'navLayout' | 'hideNavigation'
> & {
onViewChange?: (view: CalendarView) => void;
};
function CalendarGridPicker({
className,
classNames,
components,
formatters,
month,
defaultMonth,
onMonthChange,
onViewChange,
startMonth,
endMonth,
...props
}: CalendarGridPickerProps) {
const initialMonth = month ?? defaultMonth ?? new Date();
const [view, setView] = React.useState<CalendarView>('days');
const [pickerYear, setPickerYear] = React.useState(
initialMonth.getFullYear(),
);
const [decadeStart, setDecadeStart] = React.useState(
Math.floor(initialMonth.getFullYear() / 10) * 10,
);
const [internalMonth, setInternalMonth] = React.useState(initialMonth);
const currentMonth = month ?? internalMonth;
React.useEffect(() => {
if (month) {
setPickerYear(month.getFullYear());
setDecadeStart(Math.floor(month.getFullYear() / 10) * 10);
}
}, [month]);
const handleViewChange = React.useCallback(
(nextView: CalendarView) => {
setView(nextView);
onViewChange?.(nextView);
},
[onViewChange],
);
const handleMonthChange = React.useCallback(
(nextMonth: Date) => {
if (!month) setInternalMonth(nextMonth);
setPickerYear(nextMonth.getFullYear());
setDecadeStart(Math.floor(nextMonth.getFullYear() / 10) * 10);
onMonthChange?.(nextMonth);
},
[month, onMonthChange],
);
const contextValue = React.useMemo(
() => ({
view,
setView: handleViewChange,
pickerYear,
setPickerYear,
decadeStart,
setDecadeStart,
}),
[view, handleViewChange, pickerYear, decadeStart],
);
if (view !== 'days') {
return (
<CalendarGridPickerContext.Provider value={contextValue}>
<div className={cn(PICKER_SHELL_CLASS, PICKER_WIDTH, className)}>
<CalendarGridPickerPanel
month={currentMonth}
onMonthChange={handleMonthChange}
startMonth={startMonth}
endMonth={endMonth}
/>
</div>
</CalendarGridPickerContext.Provider>
);
}
return (
<CalendarGridPickerContext.Provider value={contextValue}>
<Calendar
hideNavigation
className={cn(PICKER_SHELL_CLASS, PICKER_WIDTH, className)}
month={currentMonth}
onMonthChange={handleMonthChange}
startMonth={startMonth}
endMonth={endMonth}
formatters={{
formatWeekdayName: (date) =>
date.toLocaleString('en-US', { weekday: 'short' }).slice(0, 2),
...formatters,
}}
classNames={{
month: 'flex w-full flex-col gap-2',
month_caption: 'p-0',
weekdays: 'flex w-full',
weekday:
'flex-1 text-center text-[0.8rem] font-medium text-muted-foreground select-none',
week: 'mt-1 flex w-full',
...classNames,
}}
components={{
MonthCaption: CalendarMonthCaption,
DayButton: (dayButtonProps) => (
<CalendarDayButton
{...dayButtonProps}
className={cn(
dayButtonProps.className,
'data-[selected-single=true]:rounded-full data-[selected-single=true]:bg-muted data-[selected-single=true]:text-foreground',
)}
/>
),
...components,
}}
{...(props as Extract<
React.ComponentProps<typeof Calendar>,
{ mode: 'single' }
>)}
/>
</CalendarGridPickerContext.Provider>
);
}
export { CalendarGridPicker, type CalendarView };

View File

@@ -0,0 +1,222 @@
"use client"
import * as React from "react"
import {
DayPicker,
getDefaultClassNames,
type DayButton,
type Locale,
} from "react-day-picker"
import { cn } from "@/lib/utils"
import { Button, buttonVariants } from "@/components/ui/button"
import { ChevronLeftIcon, ChevronRightIcon, ChevronDownIcon } from "lucide-react"
function Calendar({
className,
classNames,
showOutsideDays = true,
captionLayout = "label",
buttonVariant = "ghost",
locale,
formatters,
components,
...props
}: React.ComponentProps<typeof DayPicker> & {
buttonVariant?: React.ComponentProps<typeof Button>["variant"]
}) {
const defaultClassNames = getDefaultClassNames()
return (
<DayPicker
showOutsideDays={showOutsideDays}
className={cn(
"group/calendar bg-background p-3 [--cell-radius:var(--radius-md)] [--cell-size:--spacing(8)] in-data-[slot=card-content]:bg-transparent in-data-[slot=popover-content]:bg-transparent",
String.raw`rtl:**:[.rdp-button\_next>svg]:rotate-180`,
String.raw`rtl:**:[.rdp-button\_previous>svg]:rotate-180`,
className
)}
captionLayout={captionLayout}
locale={locale}
formatters={{
formatMonthDropdown: (date) =>
date.toLocaleString(locale?.code, { month: "short" }),
...formatters,
}}
classNames={{
root: cn("w-fit", defaultClassNames.root),
months: cn(
"relative flex flex-col gap-4 md:flex-row",
defaultClassNames.months
),
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
nav: cn(
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
defaultClassNames.nav
),
button_previous: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
defaultClassNames.button_previous
),
button_next: cn(
buttonVariants({ variant: buttonVariant }),
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
defaultClassNames.button_next
),
month_caption: cn(
"flex h-(--cell-size) w-full items-center justify-center px-(--cell-size)",
defaultClassNames.month_caption
),
dropdowns: cn(
"flex h-(--cell-size) w-full items-center justify-center gap-1.5 text-sm font-medium",
defaultClassNames.dropdowns
),
dropdown_root: cn(
"relative rounded-lg",
defaultClassNames.dropdown_root
),
dropdown: cn(
"absolute inset-0 bg-popover opacity-0",
defaultClassNames.dropdown
),
caption_label: cn(
"font-medium select-none",
captionLayout === "label"
? "text-sm"
: "flex items-center gap-1 rounded-lg text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
defaultClassNames.caption_label
),
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
weekdays: cn("flex", defaultClassNames.weekdays),
weekday: cn(
"flex-1 rounded-lg text-[0.8rem] font-normal text-muted-foreground select-none",
defaultClassNames.weekday
),
week: cn("mt-2 flex w-full", defaultClassNames.week),
week_number_header: cn(
"w-(--cell-size) select-none",
defaultClassNames.week_number_header
),
week_number: cn(
"text-[0.8rem] text-muted-foreground select-none",
defaultClassNames.week_number
),
day: cn(
"group/day relative aspect-square h-full w-full rounded-lg p-0 text-center select-none [&:last-child[data-selected=true]_button]:rounded-lg",
props.showWeekNumber
? "[&:nth-child(2)[data-selected=true]_button]:rounded-lg"
: "[&:first-child[data-selected=true]_button]:rounded-lg",
defaultClassNames.day
),
range_start: cn(
"relative isolate z-0 rounded-lg bg-muted after:absolute after:inset-y-0 after:right-0 after:w-4 after:bg-muted",
defaultClassNames.range_start
),
range_middle: cn("rounded-lg", defaultClassNames.range_middle),
range_end: cn(
"relative isolate z-0 rounded-lg bg-muted after:absolute after:inset-y-0 after:left-0 after:w-4 after:bg-muted",
defaultClassNames.range_end
),
today: cn(
"rounded-lg bg-muted text-foreground data-[selected=true]:rounded-lg",
defaultClassNames.today
),
outside: cn(
"text-muted-foreground aria-selected:text-muted-foreground",
defaultClassNames.outside
),
disabled: cn(
"text-muted-foreground opacity-50",
defaultClassNames.disabled
),
hidden: cn("invisible", defaultClassNames.hidden),
...classNames,
}}
components={{
Root: ({ className, rootRef, ...props }) => {
return (
<div
data-slot="calendar"
ref={rootRef}
className={cn(className)}
{...props}
/>
)
},
Chevron: ({ className, orientation, ...props }) => {
if (orientation === "left") {
return (
<ChevronLeftIcon className={cn("size-4", className)} {...props} />
)
}
if (orientation === "right") {
return (
<ChevronRightIcon className={cn("size-4", className)} {...props} />
)
}
return (
<ChevronDownIcon className={cn("size-4", className)} {...props} />
)
},
DayButton: ({ ...props }) => (
<CalendarDayButton locale={locale} {...props} />
),
WeekNumber: ({ children, ...props }) => {
return (
<td {...props}>
<div className="flex size-(--cell-size) items-center justify-center text-center">
{children}
</div>
</td>
)
},
...components,
}}
{...props}
/>
)
}
function CalendarDayButton({
className,
day,
modifiers,
locale,
...props
}: React.ComponentProps<typeof DayButton> & { locale?: Partial<Locale> }) {
const defaultClassNames = getDefaultClassNames()
const ref = React.useRef<HTMLButtonElement>(null)
React.useEffect(() => {
if (modifiers.focused) ref.current?.focus()
}, [modifiers.focused])
return (
<Button
ref={ref}
variant="ghost"
size="icon"
data-day={day.date.toLocaleDateString(locale?.code)}
data-selected-single={
modifiers.selected &&
!modifiers.range_start &&
!modifiers.range_end &&
!modifiers.range_middle
}
data-range-start={modifiers.range_start}
data-range-end={modifiers.range_end}
data-range-middle={modifiers.range_middle}
className={cn(
"relative isolate z-10 flex aspect-square size-auto w-full min-w-(--cell-size) flex-col gap-1 border-0 leading-none font-normal group-data-[focused=true]/day:relative group-data-[focused=true]/day:z-10 group-data-[focused=true]/day:border-ring group-data-[focused=true]/day:ring-[3px] group-data-[focused=true]/day:ring-ring/50 data-[range-end=true]:rounded-lg data-[range-end=true]:rounded-lg data-[range-end=true]:bg-primary data-[range-end=true]:text-primary-foreground data-[range-middle=true]:rounded-lg data-[range-middle=true]:bg-muted data-[range-middle=true]:text-foreground data-[range-start=true]:rounded-lg data-[range-start=true]:rounded-lg data-[range-start=true]:bg-primary data-[range-start=true]:text-primary-foreground data-[selected-single=true]:bg-primary data-[selected-single=true]:text-primary-foreground dark:hover:text-foreground [&>span]:text-xs [&>span]:opacity-70",
defaultClassNames.day,
className
)}
{...props}
/>
)
}
export { Calendar, CalendarDayButton }

View File

@@ -1,84 +1,95 @@
import * as React from 'react';
import * as React from "react"
import { cn } from '@/lib/utils';
import { cn } from "@/lib/utils"
function Card({ className, ...props }: React.ComponentProps<'div'>) {
function Card({
className,
size = "default",
...props
}: React.ComponentProps<"div"> & { size?: "default" | "sm" }) {
return (
<div
data-slot="card"
data-size={size}
className={cn(
'flex flex-col overflow-hidden rounded-xl border bg-card text-card-foreground',
className,
"group/card flex flex-col gap-(--card-spacing) overflow-hidden rounded-lg bg-card py-(--card-spacing) text-sm text-card-foreground shadow-xs ring-1 ring-foreground/10 [--card-spacing:--spacing(6)] has-[>img:first-child]:pt-0 data-[size=sm]:[--card-spacing:--spacing(4)] *:[img:first-child]:rounded-lg *:[img:last-child]:rounded-lg",
className
)}
{...props}
/>
);
)
}
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
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 border-b px-5 py-4 has-data-[slot=card-action]:grid-cols-[1fr_auto]',
className,
"group/card-header @container/card-header grid auto-rows-min items-start gap-1 rounded-lg px-(--card-spacing) has-data-[slot=card-action]:grid-cols-[1fr_auto] has-data-[slot=card-description]:grid-rows-[auto_auto] [.border-b]:pb-(--card-spacing)",
className
)}
{...props}
/>
);
)
}
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-title"
className={cn('text-base leading-none font-semibold', className)}
className={cn(
"font-heading text-base leading-normal font-medium group-data-[size=sm]/card:text-sm",
className
)}
{...props}
/>
);
)
}
function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-description"
className={cn('text-sm text-muted-foreground', className)}
className={cn("text-sm text-muted-foreground", className)}
{...props}
/>
);
)
}
function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
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,
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props}
/>
);
)
}
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn('px-5 py-5', className)}
className={cn("px-(--card-spacing)", className)}
{...props}
/>
);
)
}
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-footer"
className={cn('flex items-center border-t px-5 py-4', className)}
className={cn(
"flex items-center rounded-lg px-(--card-spacing) [.border-t]:pt-(--card-spacing)",
className
)}
{...props}
/>
);
)
}
export {
@@ -89,4 +100,4 @@ export {
CardAction,
CardDescription,
CardContent,
};
}

View File

@@ -1,37 +1,42 @@
'use client';
"use client"
import * as React from 'react';
import * as RechartsPrimitive from 'recharts';
import * as React from "react"
import * as RechartsPrimitive from "recharts"
import type { TooltipValueType } from "recharts"
import { cn } from '@/lib/utils';
import { cn } from "@/lib/utils"
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: '', dark: '.dark' } as const;
const THEMES = { light: "", dark: ".dark" } as const
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode;
icon?: React.ComponentType;
const INITIAL_DIMENSION = { width: 320, height: 200 } as const
type TooltipNameType = number | string
export type ChartConfig = Record<
string,
{
label?: React.ReactNode
icon?: React.ComponentType
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
);
};
)
>
type ChartContextProps = {
config: ChartConfig;
};
const ChartContext = React.createContext<ChartContextProps | null>(null);
function useChart() {
const context = React.useContext(ChartContext);
if (!context) {
throw new Error('useChart must be used within a <ChartContainer />');
config: ChartConfig
}
return context;
const ChartContext = React.createContext<ChartContextProps | null>(null)
function useChart() {
const context = React.useContext(ChartContext)
if (!context) {
throw new Error("useChart must be used within a <ChartContainer />")
}
return context
}
function ChartContainer({
@@ -39,15 +44,20 @@ function ChartContainer({
className,
children,
config,
initialDimension = INITIAL_DIMENSION,
...props
}: React.ComponentProps<'div'> & {
config: ChartConfig;
}: React.ComponentProps<"div"> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>['children'];
>["children"]
initialDimension?: {
width: number
height: number
}
}) {
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`;
const uniqueId = React.useId()
const chartId = `chart-${id ?? uniqueId.replace(/:/g, "")}`
return (
<ChartContext.Provider value={{ config }}>
@@ -55,27 +65,29 @@ function ChartContainer({
data-slot="chart"
data-chart={chartId}
className={cn(
"[&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border flex aspect-video justify-center text-xs [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className,
"flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='#ccc']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='#fff']]:stroke-transparent [&_.recharts-layer]:outline-hidden [&_.recharts-polar-grid_[stroke='#ccc']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='#ccc']]:stroke-border [&_.recharts-sector]:outline-hidden [&_.recharts-sector[stroke='#fff']]:stroke-transparent [&_.recharts-surface]:outline-hidden",
className
)}
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
<RechartsPrimitive.ResponsiveContainer
initialDimension={initialDimension}
>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
);
)
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color,
);
([, config]) => config.theme ?? config.color
)
if (!colorConfig.length) {
return null;
return null
}
return (
@@ -88,27 +100,27 @@ ${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color;
return color ? ` --color-${key}: ${color};` : null;
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ??
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
})
.join('\n')}
.join("\n")}
}
`,
`
)
.join('\n'),
.join("\n"),
}}
/>
);
};
)
}
const ChartTooltip = RechartsPrimitive.Tooltip;
const ChartTooltip = RechartsPrimitive.Tooltip
function ChartTooltipContent({
active,
payload,
className,
indicator = 'dot',
indicator = "dot",
hideLabel = false,
hideIndicator = false,
label,
@@ -119,41 +131,47 @@ function ChartTooltipContent({
nameKey,
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<'div'> & {
hideLabel?: boolean;
hideIndicator?: boolean;
indicator?: 'line' | 'dot' | 'dashed';
nameKey?: string;
labelKey?: string;
}) {
const { config } = useChart();
React.ComponentProps<"div"> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: "line" | "dot" | "dashed"
nameKey?: string
labelKey?: string
} & Omit<
RechartsPrimitive.DefaultTooltipContentProps<
TooltipValueType,
TooltipNameType
>,
"accessibilityLayer"
>) {
const { config } = useChart()
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null;
return null
}
const [item] = payload;
const key = `${labelKey || item?.dataKey || item?.name || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const [item] = payload
const key = `${labelKey ?? item?.dataKey ?? item?.name ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const value =
!labelKey && typeof label === 'string'
? config[label as keyof typeof config]?.label || label
: itemConfig?.label;
!labelKey && typeof label === "string"
? (config[label]?.label ?? label)
: itemConfig?.label
if (labelFormatter) {
return (
<div className={cn('font-medium', labelClassName)}>
<div className={cn("font-medium", labelClassName)}>
{labelFormatter(value, payload)}
</div>
);
)
}
if (!value) {
return null;
return null
}
return <div className={cn('font-medium', labelClassName)}>{value}</div>;
return <div className={cn("font-medium", labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
@@ -162,34 +180,36 @@ function ChartTooltipContent({
labelClassName,
config,
labelKey,
]);
])
if (!active || !payload?.length) {
return null;
return null
}
const nestLabel = payload.length === 1 && indicator !== 'dot';
const nestLabel = payload.length === 1 && indicator !== "dot"
return (
<div
className={cn(
'border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl',
className,
"grid min-w-32 items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
className
)}
>
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color || item.payload.fill || item.color;
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.name ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color ?? item.payload?.fill ?? item.color
return (
<div
key={item.dataKey}
key={index}
className={cn(
'[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5',
indicator === 'dot' && 'items-center',
"flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
indicator === "dot" && "items-center"
)}
>
{formatter && item?.value !== undefined && item.name ? (
@@ -202,19 +222,19 @@ function ChartTooltipContent({
!hideIndicator && (
<div
className={cn(
'shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)',
"shrink-0 rounded-lg border-(--color-border) bg-(--color-bg)",
{
'h-2.5 w-2.5': indicator === 'dot',
'w-1': indicator === 'line',
'w-0 border-[1.5px] border-dashed bg-transparent':
indicator === 'dashed',
'my-0.5': nestLabel && indicator === 'dashed',
},
"h-2.5 w-2.5": indicator === "dot",
"w-1": indicator === "line",
"w-0 border-[1.5px] border-dashed bg-transparent":
indicator === "dashed",
"my-0.5": nestLabel && indicator === "dashed",
}
)}
style={
{
'--color-bg': indicatorColor,
'--color-border': indicatorColor,
"--color-bg": indicatorColor,
"--color-border": indicatorColor,
} as React.CSSProperties
}
/>
@@ -222,75 +242,78 @@ function ChartTooltipContent({
)}
<div
className={cn(
'flex flex-1 justify-between leading-none',
nestLabel ? 'items-end' : 'items-center',
"flex flex-1 justify-between leading-none",
nestLabel ? "items-end" : "items-center"
)}
>
<div className="grid gap-1.5">
{nestLabel ? tooltipLabel : null}
<span className="text-muted-foreground">
{itemConfig?.label || item.name}
{itemConfig?.label ?? item.name}
</span>
</div>
{item.value && (
<span className="text-foreground font-mono font-medium tabular-nums">
{item.value.toLocaleString()}
{item.value != null && (
<span className="font-mono font-medium text-foreground tabular-nums">
{typeof item.value === "number"
? item.value.toLocaleString()
: String(item.value)}
</span>
)}
</div>
</>
)}
</div>
);
)
})}
</div>
</div>
);
)
}
const ChartLegend = RechartsPrimitive.Legend;
const ChartLegend = RechartsPrimitive.Legend
function ChartLegendContent({
className,
hideIcon = false,
payload,
verticalAlign = 'bottom',
verticalAlign = "bottom",
nameKey,
}: React.ComponentProps<'div'> &
Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & {
hideIcon?: boolean;
nameKey?: string;
}) {
const { config } = useChart();
}: React.ComponentProps<"div"> & {
hideIcon?: boolean
nameKey?: string
} & RechartsPrimitive.DefaultLegendContentProps) {
const { config } = useChart()
if (!payload?.length) {
return null;
return null
}
return (
<div
className={cn(
'flex items-center justify-center gap-4',
verticalAlign === 'top' ? 'pb-3' : 'pt-3',
className,
"flex items-center justify-center gap-4",
verticalAlign === "top" ? "pb-3" : "pt-3",
className
)}
>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
{payload
.filter((item) => item.type !== "none")
.map((item, index) => {
const key = `${nameKey ?? item.dataKey ?? "value"}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
return (
<div
key={item.value}
className={
'[&>svg]:text-muted-foreground flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3'
}
key={index}
className={cn(
"flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
)}
>
{itemConfig?.icon && !hideIcon ? (
<itemConfig.icon />
) : (
<div
className="h-2 w-2 shrink-0 rounded-[2px]"
className="h-2 w-2 shrink-0 rounded-lg"
style={{
backgroundColor: item.color,
}}
@@ -298,49 +321,46 @@ function ChartLegendContent({
)}
{itemConfig?.label}
</div>
);
)
})}
</div>
);
)
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string,
key: string
) {
if (typeof payload !== 'object' || payload === null) {
return undefined;
if (typeof payload !== "object" || payload === null) {
return undefined
}
const payloadPayload =
'payload' in payload &&
typeof payload.payload === 'object' &&
"payload" in payload &&
typeof payload.payload === "object" &&
payload.payload !== null
? payload.payload
: undefined;
: undefined
let configLabelKey: string = key;
let configLabelKey: string = key
if (
key in payload &&
typeof payload[key as keyof typeof payload] === 'string'
typeof payload[key as keyof typeof payload] === "string"
) {
configLabelKey = payload[key as keyof typeof payload] as string;
configLabelKey = payload[key as keyof typeof payload] as string
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
typeof payloadPayload[key as keyof typeof payloadPayload] === "string"
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string;
] as string
}
return configLabelKey in config
? config[configLabelKey]
: config[key as keyof typeof config];
return configLabelKey in config ? config[configLabelKey] : config[key]
}
export {
@@ -350,4 +370,4 @@ export {
ChartLegend,
ChartLegendContent,
ChartStyle,
};
}

View File

@@ -1,11 +1,11 @@
'use client';
"use client"
import * as CollapsiblePrimitive from '@radix-ui/react-collapsible';
import { Collapsible as CollapsiblePrimitive } from "radix-ui"
function Collapsible({
...props
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
}
function CollapsibleTrigger({
@@ -16,7 +16,7 @@ function CollapsibleTrigger({
data-slot="collapsible-trigger"
{...props}
/>
);
)
}
function CollapsibleContent({
@@ -27,7 +27,7 @@ function CollapsibleContent({
data-slot="collapsible-content"
{...props}
/>
);
)
}
export { Collapsible, CollapsibleTrigger, CollapsibleContent };
export { Collapsible, CollapsibleTrigger, CollapsibleContent }

View File

@@ -1,63 +1,39 @@
'use client';
"use client"
import * as React from 'react';
import { Combobox as ComboboxPrimitive } from '@base-ui/react';
import { CheckIcon, ChevronDownIcon, XIcon } from 'lucide-react';
import * as React from "react"
import { Combobox as ComboboxPrimitive } from "@base-ui/react"
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import {
InputGroup,
InputGroupAddon,
InputGroupButton,
InputGroupInput,
} from '@/components/ui/input-group';
} from "@/components/ui/input-group"
import { ChevronDownIcon, XIcon, CheckIcon } from "lucide-react"
const Combobox = ComboboxPrimitive.Root;
const Combobox = ComboboxPrimitive.Root
function ComboboxValue({ ...props }: ComboboxPrimitive.Value.Props) {
return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />;
return <ComboboxPrimitive.Value data-slot="combobox-value" {...props} />
}
function ComboboxTrigger({
className,
children,
render,
...props
}: ComboboxPrimitive.Trigger.Props) {
const icon = (
<ChevronDownIcon
data-slot="combobox-trigger-icon"
className="pointer-events-none size-4 text-muted-foreground"
/>
);
const triggerRender = React.isValidElement<{ children?: React.ReactNode }>(
render,
)
? React.cloneElement(render, {
children: (
<>
{render.props.children}
{icon}
</>
),
})
: render;
return (
<ComboboxPrimitive.Trigger
data-slot="combobox-trigger"
className={cn(
"cursor-pointer disabled:cursor-not-allowed [&_svg:not([class*='size-'])]:size-4",
className,
)}
render={triggerRender}
className={cn("[&_svg:not([class*='size-'])]:size-4", className)}
{...props}
>
{children}
{render ? null : icon}
<ChevronDownIcon className="pointer-events-none size-4 text-muted-foreground" />
</ComboboxPrimitive.Trigger>
);
)
}
function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
@@ -70,7 +46,7 @@ function ComboboxClear({ className, ...props }: ComboboxPrimitive.Clear.Props) {
>
<XIcon className="pointer-events-none" />
</ComboboxPrimitive.Clear>
);
)
}
function ComboboxInput({
@@ -81,11 +57,11 @@ function ComboboxInput({
showClear = false,
...props
}: ComboboxPrimitive.Input.Props & {
showTrigger?: boolean;
showClear?: boolean;
showTrigger?: boolean
showClear?: boolean
}) {
return (
<InputGroup className={cn('w-auto', className)}>
<InputGroup className={cn("w-auto", className)}>
<ComboboxPrimitive.Input
render={<InputGroupInput disabled={disabled} />}
{...props}
@@ -107,14 +83,14 @@ function ComboboxInput({
</InputGroupAddon>
{children}
</InputGroup>
);
)
}
function ComboboxContent({
className,
side = 'bottom',
side = "bottom",
sideOffset = 6,
align = 'start',
align = "start",
alignOffset = 0,
anchor,
container,
@@ -122,9 +98,9 @@ function ComboboxContent({
}: ComboboxPrimitive.Popup.Props &
Pick<
ComboboxPrimitive.Positioner.Props,
'side' | 'align' | 'sideOffset' | 'alignOffset' | 'anchor'
"side" | "align" | "sideOffset" | "alignOffset" | "anchor"
> & {
container?: ComboboxPrimitive.Portal.Props['container'];
container?: ComboboxPrimitive.Portal.Props["container"]
}) {
return (
<ComboboxPrimitive.Portal container={container}>
@@ -139,15 +115,12 @@ function ComboboxContent({
<ComboboxPrimitive.Popup
data-slot="combobox-content"
data-chips={!!anchor}
className={cn(
'group/combobox-content relative max-h-96 w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+1.75rem)] origin-(--transform-origin) overflow-hidden rounded-md bg-popover text-popover-foreground ring-1 ring-foreground/10 duration-100 data-[chips=true]:min-w-(--anchor-width) 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 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95',
className,
)}
className={cn("group/combobox-content relative max-h-(--available-height) w-(--anchor-width) max-w-(--available-width) min-w-[calc(var(--anchor-width)+--spacing(7))] origin-(--transform-origin) overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10 duration-100 data-[chips=true]:min-w-(--anchor-width) data-[side=bottom]:slide-in-from-top-2 data-[side=inline-end]:slide-in-from-left-2 data-[side=inline-start]:slide-in-from-right-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 *:data-[slot=input-group]:m-1 *:data-[slot=input-group]:mb-0 *:data-[slot=input-group]:h-8 *:data-[slot=input-group]:border-input/30 *:data-[slot=input-group]:bg-input/30 *:data-[slot=input-group]:shadow-none data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95 data-closed:animate-out data-closed:fade-out-0 data-closed:zoom-out-95", className )}
{...props}
/>
</ComboboxPrimitive.Positioner>
</ComboboxPrimitive.Portal>
);
)
}
function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
@@ -155,12 +128,12 @@ function ComboboxList({ className, ...props }: ComboboxPrimitive.List.Props) {
<ComboboxPrimitive.List
data-slot="combobox-list"
className={cn(
'max-h-[min(21.75rem,calc(var(--available-height)-2.25rem))] scroll-py-1 overflow-y-auto p-1 data-empty:p-0',
className,
"no-scrollbar max-h-[min(calc(--spacing(72)---spacing(9)),calc(var(--available-height)---spacing(9)))] scroll-py-1 overflow-y-auto overscroll-contain p-1 data-empty:p-0",
className
)}
{...props}
/>
);
)
}
function ComboboxItem({
@@ -172,22 +145,21 @@ function ComboboxItem({
<ComboboxPrimitive.Item
data-slot="combobox-item"
className={cn(
"relative flex w-full cursor-pointer items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className,
"relative flex w-full cursor-default items-center gap-2 rounded-lg py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground not-data-[variant=destructive]:data-highlighted:**:text-accent-foreground data-disabled:pointer-events-none data-disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
)}
{...props}
>
{children}
<ComboboxPrimitive.ItemIndicator
data-slot="combobox-item-indicator"
render={
<span className="pointer-events-none absolute right-2 flex size-4 items-center justify-center" />
}
>
<CheckIcon className="pointer-events-none size-4 pointer-coarse:size-5" />
<CheckIcon className="pointer-events-none" />
</ComboboxPrimitive.ItemIndicator>
</ComboboxPrimitive.Item>
);
)
}
function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
@@ -197,7 +169,7 @@ function ComboboxGroup({ className, ...props }: ComboboxPrimitive.Group.Props) {
className={cn(className)}
{...props}
/>
);
)
}
function ComboboxLabel({
@@ -207,19 +179,16 @@ function ComboboxLabel({
return (
<ComboboxPrimitive.GroupLabel
data-slot="combobox-label"
className={cn(
'px-2 py-1.5 text-xs text-muted-foreground pointer-coarse:px-3 pointer-coarse:py-2 pointer-coarse:text-sm',
className,
)}
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
{...props}
/>
);
)
}
function ComboboxCollection({ ...props }: ComboboxPrimitive.Collection.Props) {
return (
<ComboboxPrimitive.Collection data-slot="combobox-collection" {...props} />
);
)
}
function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
@@ -227,12 +196,12 @@ function ComboboxEmpty({ className, ...props }: ComboboxPrimitive.Empty.Props) {
<ComboboxPrimitive.Empty
data-slot="combobox-empty"
className={cn(
'hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex',
className,
"hidden w-full justify-center py-2 text-center text-sm text-muted-foreground group-data-empty/combobox-content:flex",
className
)}
{...props}
/>
);
)
}
function ComboboxSeparator({
@@ -242,10 +211,10 @@ function ComboboxSeparator({
return (
<ComboboxPrimitive.Separator
data-slot="combobox-separator"
className={cn('-mx-1 my-1 h-px bg-border', className)}
className={cn("-mx-1 my-1 h-px bg-border", className)}
{...props}
/>
);
)
}
function ComboboxChips({
@@ -257,12 +226,12 @@ function ComboboxChips({
<ComboboxPrimitive.Chips
data-slot="combobox-chips"
className={cn(
'flex min-h-9 flex-wrap items-center gap-1.5 rounded-md border border-input bg-transparent bg-clip-padding px-2.5 py-1.5 text-sm transition-[color,box-shadow] focus-within:border-ring has-aria-invalid:border-destructive has-data-[slot=combobox-chip]:px-1.5 dark:bg-input/30 dark:has-aria-invalid:border-destructive',
className,
"flex min-h-9 flex-wrap items-center gap-1.5 rounded-lg border border-input bg-transparent bg-clip-padding px-2.5 py-1.5 text-sm shadow-xs transition-[color,box-shadow] focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 has-aria-invalid:border-destructive has-aria-invalid:ring-3 has-aria-invalid:ring-destructive/20 has-data-[slot=combobox-chip]:px-1.5 dark:bg-input/30 dark:has-aria-invalid:border-destructive/50 dark:has-aria-invalid:ring-destructive/40",
className
)}
{...props}
/>
);
)
}
function ComboboxChip({
@@ -271,14 +240,14 @@ function ComboboxChip({
showRemove = true,
...props
}: ComboboxPrimitive.Chip.Props & {
showRemove?: boolean;
showRemove?: boolean
}) {
return (
<ComboboxPrimitive.Chip
data-slot="combobox-chip"
className={cn(
'flex h-[calc(--spacing(5.5))] w-fit items-center justify-center gap-1 rounded-sm bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-0',
className,
"flex h-[calc(--spacing(5.5))] w-fit items-center justify-center gap-1 rounded-lg bg-muted px-1.5 text-xs font-medium whitespace-nowrap text-foreground has-disabled:pointer-events-none has-disabled:cursor-not-allowed has-disabled:opacity-50 has-data-[slot=combobox-chip-remove]:pr-0",
className
)}
{...props}
>
@@ -293,25 +262,24 @@ function ComboboxChip({
</ComboboxPrimitive.ChipRemove>
)}
</ComboboxPrimitive.Chip>
);
)
}
function ComboboxChipsInput({
className,
children,
...props
}: ComboboxPrimitive.Input.Props) {
return (
<ComboboxPrimitive.Input
data-slot="combobox-chip-input"
className={cn('min-w-16 flex-1 outline-none', className)}
className={cn("min-w-16 flex-1 outline-none", className)}
{...props}
/>
);
)
}
function useComboboxAnchor() {
return React.useRef<HTMLDivElement | null>(null);
return React.useRef<HTMLDivElement | null>(null)
}
export {
@@ -331,4 +299,4 @@ export {
ComboboxTrigger,
ComboboxValue,
useComboboxAnchor,
};
}

Some files were not shown because too many files have changed in this diff Show More