Compare commits
4 Commits
23186ffd29
...
a376558b2f
| Author | SHA1 | Date | |
|---|---|---|---|
| a376558b2f | |||
| 4fe93460d9 | |||
| cbfb6e040b | |||
| 7a82e17bbb |
27
src/app/(modules)/_components/module-shell-header.tsx
Normal file
27
src/app/(modules)/_components/module-shell-header.tsx
Normal 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 items-center justify-between gap-4 border-b border-border bg-background/95 px-6 py-3 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>
|
||||
);
|
||||
}
|
||||
@@ -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">
|
||||
<main className="flex flex-1 h-screen w-full flex-col overflow-hidden">
|
||||
<div className="scroll-stable flex-1 overflow-auto">
|
||||
<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>
|
||||
<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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -184,9 +184,9 @@ export function TicketClassDetectionPreview({
|
||||
size="sm"
|
||||
onClick={() => setCurrentIndex((index) => Math.max(index - 1, 0))}
|
||||
disabled={isPreviousDisabled}
|
||||
aria-label="Previous detection"
|
||||
>
|
||||
<ChevronLeft className="size-4" />
|
||||
Previous
|
||||
</Button>
|
||||
<div className="min-w-16 text-center text-sm font-medium text-foreground">
|
||||
{detectionCount === 0
|
||||
@@ -199,8 +199,8 @@ export function TicketClassDetectionPreview({
|
||||
size="sm"
|
||||
onClick={() => setCurrentIndex((index) => index + 1)}
|
||||
disabled={isNextDisabled}
|
||||
aria-label="Next detection"
|
||||
>
|
||||
Next
|
||||
<ChevronRight className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import {
|
||||
Activity,
|
||||
ArrowRight,
|
||||
CalendarDays,
|
||||
Clock3,
|
||||
Gauge,
|
||||
@@ -10,7 +9,7 @@ import {
|
||||
Monitor,
|
||||
UserRound,
|
||||
} from 'lucide-react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
|
||||
import {
|
||||
Card,
|
||||
@@ -20,12 +19,20 @@ import {
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
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';
|
||||
|
||||
type IconComponent = React.ComponentType<{ className?: string }>;
|
||||
|
||||
@@ -105,7 +112,7 @@ export function TicketOverviewCard({
|
||||
}: {
|
||||
ticket: TicketOverviewDetail;
|
||||
}) {
|
||||
const router = useRouter();
|
||||
const [isAnalysisOpen, setIsAnalysisOpen] = useState(false);
|
||||
const videoMetadata = ticket.video_metadata;
|
||||
const duration =
|
||||
typeof videoMetadata?.duration_seconds === 'number'
|
||||
@@ -125,11 +132,9 @@ export function TicketOverviewCard({
|
||||
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(
|
||||
videoName ||
|
||||
videoMetadata?.fps ||
|
||||
duration ||
|
||||
videoMetadata?.resolution?.label,
|
||||
videoMetadata?.fps || duration || videoMetadata?.resolution?.label,
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -178,10 +183,9 @@ export function TicketOverviewCard({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="text-primary hover:bg-primary/10 hover:text-primary"
|
||||
onClick={() => router.push(`/results/${analysisVideoId}`)}
|
||||
onClick={() => setIsAnalysisOpen(true)}
|
||||
>
|
||||
View Analysis
|
||||
<ArrowRight className="size-3.5" />
|
||||
View Video
|
||||
</Button>
|
||||
</PermissionGuard>
|
||||
</CardAction>
|
||||
@@ -210,9 +214,6 @@ export function TicketOverviewCard({
|
||||
</div>
|
||||
{hasVideoMetrics ? (
|
||||
<div className="grid gap-3 rounded-lg bg-muted/35 px-4 py-3 text-sm sm:grid-cols-3">
|
||||
{videoName ? (
|
||||
<VideoMetric icon={Monitor} label={videoName} />
|
||||
) : null}
|
||||
{videoMetadata?.fps ? (
|
||||
<VideoMetric icon={Gauge} label={`${videoMetadata.fps} FPS`} />
|
||||
) : null}
|
||||
@@ -229,6 +230,20 @@ export function TicketOverviewCard({
|
||||
) : null}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Dialog open={isAnalysisOpen} onOpenChange={setIsAnalysisOpen}>
|
||||
<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">
|
||||
{analysisTitle}
|
||||
</DialogTitle>
|
||||
<DialogDescription className="truncate text-xs">
|
||||
Video analysis with annotation overlay
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<TicketInlineAnalysisVideo ticket={ticket} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
'use client';
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useMemo, useState } from 'react';
|
||||
import { Users, Mail, Phone, Send, ShieldCheck } 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';
|
||||
@@ -21,6 +21,15 @@ export function AssignTicketAction({ ticket }: { ticket: TicketDetail }) {
|
||||
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() + 5, 11),
|
||||
[today],
|
||||
);
|
||||
|
||||
return (
|
||||
<TicketActionCard icon={Users} title="Assign to Contractor">
|
||||
@@ -56,13 +65,20 @@ export function AssignTicketAction({ ticket }: { ticket: TicketDetail }) {
|
||||
</div>
|
||||
) : null}
|
||||
<div className="space-y-2">
|
||||
<Label>Due Date *</Label>
|
||||
<DatePicker
|
||||
<Label htmlFor="assign-due-date">
|
||||
Due Date <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<DatePickerSimple
|
||||
id="assign-due-date"
|
||||
value={dueDate}
|
||||
onChange={setDueDate}
|
||||
showTimeZone={false}
|
||||
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">
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { getDefectVisual } from '@/constants/defectVisualConfig';
|
||||
import type { DetectionResultItem } from '@/types';
|
||||
import type { BoundingBoxOverlayItem } from '@/types';
|
||||
|
||||
interface BoundingBoxOverlayProps {
|
||||
detections: DetectionResultItem[];
|
||||
detections: BoundingBoxOverlayItem[];
|
||||
videoWidth: number;
|
||||
videoHeight: number;
|
||||
}
|
||||
@@ -23,7 +23,7 @@ export default function BoundingBoxOverlay({
|
||||
viewBox={`0 0 ${videoWidth} ${videoHeight}`}
|
||||
preserveAspectRatio="xMidYMid meet"
|
||||
>
|
||||
{detections.map(({ id, detection }) => {
|
||||
{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)}%`;
|
||||
@@ -31,7 +31,7 @@ export default function BoundingBoxOverlay({
|
||||
const labelWidth = Math.max(150, label.length * 17);
|
||||
|
||||
return (
|
||||
<g key={id}>
|
||||
<g key={detection.id}>
|
||||
<rect
|
||||
x={box.x1}
|
||||
y={box.y1}
|
||||
|
||||
@@ -18,16 +18,17 @@ import {
|
||||
Sidebar,
|
||||
SidebarContent,
|
||||
SidebarFooter,
|
||||
SidebarGroup,
|
||||
SidebarHeader,
|
||||
SidebarRail,
|
||||
SidebarMenu,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuButton,
|
||||
SidebarMenuItem,
|
||||
SidebarMenuSub,
|
||||
SidebarMenuSubButton,
|
||||
SidebarMenuSubItem,
|
||||
SidebarGroup,
|
||||
SidebarGroupLabel,
|
||||
SidebarRail,
|
||||
SidebarTrigger,
|
||||
useSidebar,
|
||||
} from '@/components/ui/sidebar';
|
||||
import Link from 'next/link';
|
||||
import { usePathname } from 'next/navigation';
|
||||
@@ -41,6 +42,7 @@ function isRouteActive(pathname: string, path?: string) {
|
||||
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 = {
|
||||
@@ -53,17 +55,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
|
||||
@@ -75,7 +81,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 />
|
||||
@@ -83,6 +89,23 @@ 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"
|
||||
/>
|
||||
<SidebarTrigger
|
||||
tooltip="Open sidebar"
|
||||
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'}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SidebarNavItem({
|
||||
item,
|
||||
pathname,
|
||||
@@ -159,4 +182,3 @@ function SidebarNavItem({
|
||||
</SidebarMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
129
src/components/form/DatePickerSimple.tsx
Normal file
129
src/components/form/DatePickerSimple.tsx
Normal 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>
|
||||
);
|
||||
}
|
||||
@@ -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';
|
||||
|
||||
537
src/components/ui/calendar-grid-picker.tsx
Normal file
537
src/components/ui/calendar-grid-picker.tsx
Normal 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-md 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-sm 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-sm 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-sm 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 };
|
||||
@@ -256,29 +256,56 @@ function Sidebar({
|
||||
function SidebarTrigger({
|
||||
className,
|
||||
onClick,
|
||||
tooltip,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Button>) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
}: React.ComponentProps<typeof Button> & {
|
||||
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
|
||||
}) {
|
||||
const { isMobile, toggleSidebar } = useSidebar();
|
||||
|
||||
return (
|
||||
const button = (
|
||||
<Button
|
||||
data-sidebar="trigger"
|
||||
data-slot="sidebar-trigger"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className={cn('size-7', className)}
|
||||
size="icon-sm"
|
||||
className={cn(
|
||||
'rounded-md text-muted-foreground transition-colors hover:bg-accent hover:text-foreground',
|
||||
className,
|
||||
)}
|
||||
onClick={(event) => {
|
||||
onClick?.(event);
|
||||
toggleSidebar();
|
||||
}}
|
||||
{...props}
|
||||
>
|
||||
<PanelLeftIcon />
|
||||
<PanelLeftIcon className="size-4" />
|
||||
<span className="sr-only">Toggle Sidebar</span>
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (!tooltip) {
|
||||
return button;
|
||||
}
|
||||
|
||||
if (typeof tooltip === 'string') {
|
||||
tooltip = {
|
||||
children: tooltip,
|
||||
};
|
||||
}
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>{button}</TooltipTrigger>
|
||||
<TooltipContent
|
||||
side="right"
|
||||
align="center"
|
||||
hidden={isMobile}
|
||||
{...tooltip}
|
||||
/>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
function SidebarRail({ className, ...props }: React.ComponentProps<'button'>) {
|
||||
const { toggleSidebar } = useSidebar();
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { AlertTriangle, ImageIcon, Loader2 } from 'lucide-react';
|
||||
import Image from 'next/image';
|
||||
|
||||
import { useProtectedMediaObjectUrl } from '@/hooks/useProtectedMedia';
|
||||
import type { DetectionResultItem } from '@/types';
|
||||
import type { BoundingBoxOverlayItem, DetectionResultItem } from '@/types';
|
||||
|
||||
import BoundingBoxOverlay from '@/components/annotation/boundingBoxOverlay';
|
||||
|
||||
@@ -22,6 +22,17 @@ export default function AnnotatedDetectionImage({
|
||||
const { objectUrl, isLoading, isError } = useProtectedMediaObjectUrl(
|
||||
detection?.detection.context_image_url,
|
||||
);
|
||||
const overlayDetections: BoundingBoxOverlayItem[] = detection
|
||||
? [
|
||||
{
|
||||
id: detection.id,
|
||||
class_name: detection.detection.class_name,
|
||||
display_name: detection.detection.display_name,
|
||||
confidence: detection.detection.confidence,
|
||||
bounding_box: detection.detection.bounding_box,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
|
||||
const aspectRatio =
|
||||
videoWidth > 0 && videoHeight > 0
|
||||
@@ -58,7 +69,7 @@ export default function AnnotatedDetectionImage({
|
||||
className="object-contain"
|
||||
/>
|
||||
<BoundingBoxOverlay
|
||||
detections={[detection]}
|
||||
detections={overlayDetections}
|
||||
videoWidth={videoWidth}
|
||||
videoHeight={videoHeight}
|
||||
/>
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
|
||||
import { RefObject, useEffect } from 'react';
|
||||
import { AlertTriangle, Loader2 } from 'lucide-react';
|
||||
import type { DetectionResultLog } from '@/types';
|
||||
import type {
|
||||
DetectionResultLog,
|
||||
VideoAnnotationFrameDetection,
|
||||
} from '@/types';
|
||||
import { useDetectionThumbnails } from './useDetectionThumbnails';
|
||||
import BoundingBoxOverlay from '@/components/annotation/boundingBoxOverlay';
|
||||
import {
|
||||
@@ -21,7 +24,7 @@ import {
|
||||
interface AnnotatedVideoPlayerProps {
|
||||
videoRef: RefObject<MediaPlayerInstance | null>;
|
||||
logs: DetectionResultLog[];
|
||||
visibleLogs: DetectionResultLog[];
|
||||
visibleDetections: VideoAnnotationFrameDetection[];
|
||||
videoWidth: number;
|
||||
videoHeight: number;
|
||||
videoUrl: string | null;
|
||||
@@ -60,7 +63,7 @@ function VideoFrameSync({
|
||||
export default function AnnotatedVideoPlayer({
|
||||
videoRef,
|
||||
logs,
|
||||
visibleLogs,
|
||||
visibleDetections,
|
||||
videoWidth,
|
||||
videoHeight,
|
||||
videoUrl,
|
||||
@@ -92,7 +95,7 @@ export default function AnnotatedVideoPlayer({
|
||||
</MediaProvider>
|
||||
<VideoFrameSync onVideoFrame={onVideoFrame} />
|
||||
<BoundingBoxOverlay
|
||||
detections={visibleLogs}
|
||||
detections={visibleDetections}
|
||||
videoWidth={videoWidth}
|
||||
videoHeight={videoHeight}
|
||||
/>
|
||||
|
||||
242
src/components/video/useVideoAnnotationPlayback.ts
Normal file
242
src/components/video/useVideoAnnotationPlayback.ts
Normal file
@@ -0,0 +1,242 @@
|
||||
'use client';
|
||||
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
RefObject,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
} from 'react';
|
||||
import type { MediaPlayerInstance } from '@vidstack/react';
|
||||
|
||||
import { useVideoAnnotationFramesQuery } from '@/app/(modules)/results/hooks/useVideoResults';
|
||||
import { videoKeys } from '@/app/(modules)/results/queries/videoKeys';
|
||||
import { videoService } from '@/services/api';
|
||||
import type {
|
||||
DetectionResultLog,
|
||||
VideoAnnotationFrameDetection,
|
||||
VideoAnnotationFramesParams,
|
||||
VideoAnnotationFramesResponse,
|
||||
} from '@/types';
|
||||
|
||||
const ANNOTATION_WINDOW_MS = 30000;
|
||||
const ANNOTATION_PREFETCH_THRESHOLD_MS = 5000;
|
||||
|
||||
const buildWindowParams = (
|
||||
startTimeMs: number,
|
||||
): VideoAnnotationFramesParams => ({
|
||||
start_time_ms: startTimeMs,
|
||||
end_time_ms: startTimeMs + ANNOTATION_WINDOW_MS,
|
||||
});
|
||||
|
||||
const getWindowStartMs = (currentTimeMs: number) =>
|
||||
Math.floor(Math.max(currentTimeMs, 0) / ANNOTATION_WINDOW_MS) *
|
||||
ANNOTATION_WINDOW_MS;
|
||||
|
||||
interface UseVideoAnnotationPlaybackParams {
|
||||
videoId: string | undefined;
|
||||
logs: DetectionResultLog[];
|
||||
fps: number;
|
||||
videoRef: RefObject<MediaPlayerInstance | null>;
|
||||
}
|
||||
|
||||
export function useVideoAnnotationPlayback({
|
||||
videoId,
|
||||
logs,
|
||||
fps,
|
||||
videoRef,
|
||||
}: UseVideoAnnotationPlaybackParams) {
|
||||
const queryClient = useQueryClient();
|
||||
const shouldPauseAfterSeekRef = useRef(false);
|
||||
const visibleDetectionIdsRef = useRef('');
|
||||
const [currentWindowStartMs, setCurrentWindowStartMs] = useState(0);
|
||||
const [activeLog, setActiveLog] = useState<DetectionResultLog | undefined>();
|
||||
const [visibleDetections, setVisibleDetections] = useState<
|
||||
VideoAnnotationFrameDetection[]
|
||||
>([]);
|
||||
|
||||
const sortedLogs = useMemo(
|
||||
() =>
|
||||
[...logs].sort(
|
||||
(a, b) => a.frame.timestamp_seconds - b.frame.timestamp_seconds,
|
||||
),
|
||||
[logs],
|
||||
);
|
||||
const currentWindowParams = useMemo(
|
||||
() => buildWindowParams(currentWindowStartMs),
|
||||
[currentWindowStartMs],
|
||||
);
|
||||
const annotationFramesQuery = useVideoAnnotationFramesQuery(
|
||||
videoId,
|
||||
currentWindowParams,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setActiveLog((current) => {
|
||||
if (current && sortedLogs.some((log) => log.id === current.id)) {
|
||||
return current;
|
||||
}
|
||||
|
||||
return sortedLogs[0];
|
||||
});
|
||||
}, [sortedLogs]);
|
||||
|
||||
const prefetchWindow = useCallback(
|
||||
(startTimeMs: number) => {
|
||||
if (!videoId || startTimeMs < 0) return;
|
||||
|
||||
const params = buildWindowParams(startTimeMs);
|
||||
|
||||
void queryClient.prefetchQuery({
|
||||
queryKey: videoKeys.annotationFrames(videoId, params),
|
||||
queryFn: () => videoService.getVideoAnnotationFrames(videoId, params),
|
||||
staleTime: 1000 * 60 * 5,
|
||||
gcTime: 1000 * 60 * 30,
|
||||
});
|
||||
},
|
||||
[queryClient, videoId],
|
||||
);
|
||||
|
||||
const getWindowData = useCallback(
|
||||
(startTimeMs: number) => {
|
||||
if (!videoId) return undefined;
|
||||
|
||||
const params = buildWindowParams(startTimeMs);
|
||||
|
||||
return (
|
||||
queryClient.getQueryData<VideoAnnotationFramesResponse>(
|
||||
videoKeys.annotationFrames(videoId, params),
|
||||
) ??
|
||||
(startTimeMs === currentWindowStartMs
|
||||
? annotationFramesQuery.data
|
||||
: undefined)
|
||||
);
|
||||
},
|
||||
[annotationFramesQuery.data, currentWindowStartMs, queryClient, videoId],
|
||||
);
|
||||
|
||||
const updateActiveLog = useCallback(
|
||||
(currentTimeSeconds: number) => {
|
||||
if (sortedLogs.length === 0) {
|
||||
setActiveLog(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentLog = sortedLogs.findLast(
|
||||
(log) => log.frame.timestamp_seconds <= currentTimeSeconds,
|
||||
);
|
||||
const nextActiveLog = currentLog ?? sortedLogs[0];
|
||||
|
||||
setActiveLog((previous) =>
|
||||
previous?.id === nextActiveLog.id ? previous : nextActiveLog,
|
||||
);
|
||||
},
|
||||
[sortedLogs],
|
||||
);
|
||||
|
||||
const getVisibleDetections = useCallback(
|
||||
(currentTimeSeconds: number) => {
|
||||
const currentTimeMs = currentTimeSeconds * 1000;
|
||||
const targetWindowStartMs = getWindowStartMs(currentTimeMs);
|
||||
|
||||
if (targetWindowStartMs !== currentWindowStartMs) {
|
||||
setCurrentWindowStartMs(targetWindowStartMs);
|
||||
}
|
||||
|
||||
const windowData = getWindowData(targetWindowStartMs);
|
||||
|
||||
if (!windowData) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (
|
||||
windowData.window.has_more_after &&
|
||||
currentTimeMs >=
|
||||
windowData.window.end_time_ms - ANNOTATION_PREFETCH_THRESHOLD_MS
|
||||
) {
|
||||
prefetchWindow(windowData.window.end_time_ms);
|
||||
}
|
||||
|
||||
const frameDurationMs = fps > 0 ? 1000 / fps : 0;
|
||||
const currentFrame = windowData.frames.find((frame) => {
|
||||
const frameEndMs =
|
||||
frame.end_timestamp_ms ?? frame.timestamp_ms + frameDurationMs;
|
||||
|
||||
return (
|
||||
currentTimeMs >= frame.timestamp_ms && currentTimeMs < frameEndMs
|
||||
);
|
||||
});
|
||||
|
||||
return currentFrame?.detections ?? [];
|
||||
},
|
||||
[currentWindowStartMs, fps, getWindowData, prefetchWindow],
|
||||
);
|
||||
|
||||
const updateVisibleDetections = useCallback(
|
||||
(currentTimeSeconds: number) => {
|
||||
const nextDetections = getVisibleDetections(currentTimeSeconds);
|
||||
const nextIds = nextDetections.map((detection) => detection.id).join('|');
|
||||
|
||||
if (nextIds === visibleDetectionIdsRef.current) return;
|
||||
|
||||
visibleDetectionIdsRef.current = nextIds;
|
||||
setVisibleDetections(nextDetections);
|
||||
},
|
||||
[getVisibleDetections],
|
||||
);
|
||||
|
||||
const handleSeek = useCallback(
|
||||
(log: DetectionResultLog) => {
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
|
||||
const targetTimeSeconds = log.frame.timestamp_seconds;
|
||||
const targetWindowStartMs = getWindowStartMs(targetTimeSeconds * 1000);
|
||||
|
||||
prefetchWindow(targetWindowStartMs);
|
||||
setCurrentWindowStartMs(targetWindowStartMs);
|
||||
shouldPauseAfterSeekRef.current = true;
|
||||
video.pause();
|
||||
video.currentTime = targetTimeSeconds;
|
||||
setActiveLog(log);
|
||||
updateVisibleDetections(targetTimeSeconds);
|
||||
},
|
||||
[prefetchWindow, updateVisibleDetections, videoRef],
|
||||
);
|
||||
|
||||
const handleSeeked = useCallback(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video || !shouldPauseAfterSeekRef.current) return;
|
||||
|
||||
shouldPauseAfterSeekRef.current = false;
|
||||
video.pause();
|
||||
}, [videoRef]);
|
||||
|
||||
const handleTimeUpdate = useCallback(() => {
|
||||
const video = videoRef.current;
|
||||
if (!video) return;
|
||||
|
||||
updateActiveLog(video.currentTime);
|
||||
}, [updateActiveLog, videoRef]);
|
||||
|
||||
const handleVideoFrame = useCallback(
|
||||
(mediaTime: number) => {
|
||||
updateActiveLog(mediaTime);
|
||||
updateVisibleDetections(mediaTime);
|
||||
},
|
||||
[updateActiveLog, updateVisibleDetections],
|
||||
);
|
||||
|
||||
return {
|
||||
activeLog,
|
||||
annotationFramesQuery,
|
||||
handleSeek,
|
||||
handleSeeked,
|
||||
handleTimeUpdate,
|
||||
handleVideoFrame,
|
||||
sortedLogs,
|
||||
visibleDetections,
|
||||
};
|
||||
}
|
||||
@@ -1,36 +1,60 @@
|
||||
'use client';
|
||||
|
||||
import { useMemo, useState } from 'react';
|
||||
import { ImageIcon } from 'lucide-react';
|
||||
import { useRef } from 'react';
|
||||
import type { MediaPlayerInstance } from '@vidstack/react';
|
||||
import { Film } from 'lucide-react';
|
||||
|
||||
import { useProtectedVideoQuery } from '@/app/(modules)/results/hooks/useVideoResults';
|
||||
import type { CompletedVideoResult } from '@/types';
|
||||
|
||||
import DetectionLocationMap from './map/detectionLocationMap';
|
||||
import {
|
||||
Card,
|
||||
CardContent,
|
||||
CardDescription,
|
||||
CardHeader,
|
||||
CardTitle,
|
||||
} from '@/components/ui/card';
|
||||
import { CompletedVideoResult } from '@/types';
|
||||
import DetectionLocationMap from './map/detectionLocationMap';
|
||||
} from './ui/card';
|
||||
import AnnotatedDetectionImage from './video/annotatedDetectionImage';
|
||||
import AnnotatedVideoPlayer from './video/annotatedVideoPlayer';
|
||||
import CurrentDetectionBar from './video/currentDetectionBar';
|
||||
import DetectionLogs from './video/detectionLogs';
|
||||
import ResultStatsGrid from './video/resultStatsGrid';
|
||||
import { useVideoAnnotationPlayback } from './video/useVideoAnnotationPlayback';
|
||||
|
||||
type VideoPlayerSectionProps = {
|
||||
data: CompletedVideoResult;
|
||||
};
|
||||
|
||||
export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) {
|
||||
const sortedLogs = useMemo(
|
||||
() =>
|
||||
[...data.logs].sort(
|
||||
(a, b) => a.frame.timestamp_seconds - b.frame.timestamp_seconds,
|
||||
),
|
||||
[data.logs],
|
||||
);
|
||||
const [selectedLogId, setSelectedLogId] = useState(sortedLogs[0]?.id);
|
||||
const activeLog =
|
||||
sortedLogs.find((log) => log.id === selectedLogId) ?? sortedLogs[0];
|
||||
const videoRef = useRef<MediaPlayerInstance | null>(null);
|
||||
const {
|
||||
activeLog,
|
||||
handleSeek,
|
||||
handleSeeked,
|
||||
handleTimeUpdate,
|
||||
handleVideoFrame,
|
||||
sortedLogs,
|
||||
visibleDetections,
|
||||
} = useVideoAnnotationPlayback({
|
||||
videoId: data.video_id,
|
||||
logs: data.logs,
|
||||
fps: data.summary.fps,
|
||||
videoRef,
|
||||
});
|
||||
const {
|
||||
videoUrl,
|
||||
isLoading: isVideoLoading,
|
||||
isError: isVideoError,
|
||||
refetch: refetchVideo,
|
||||
} = useProtectedVideoQuery(data.raw_video_url);
|
||||
const mediaAspectRatio =
|
||||
data.summary.video_width > 0 && data.summary.video_height > 0
|
||||
? `${data.summary.video_width} / ${data.summary.video_height}`
|
||||
: '16 / 9';
|
||||
const activeMapLabel = activeLog
|
||||
? `${activeLog.detection.display_name} - Frame ${activeLog.frame.number}`
|
||||
: 'Detection';
|
||||
|
||||
return (
|
||||
<div className="space-y-6">
|
||||
@@ -38,14 +62,15 @@ export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) {
|
||||
<CardHeader className="border-b pb-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="rounded bg-secondary p-2">
|
||||
<ImageIcon className="h-5 w-5 text-primary" />
|
||||
<Film className="h-5 w-5 text-primary" />
|
||||
</div>
|
||||
<div>
|
||||
<CardTitle className="text-lg font-bold">
|
||||
Detection Preview
|
||||
Detection Playback
|
||||
</CardTitle>
|
||||
<CardDescription className="text-xs">
|
||||
Selected detection image with its bounding box
|
||||
Raw video with frontend annotation overlay and selected
|
||||
detection location
|
||||
</CardDescription>
|
||||
</div>
|
||||
</div>
|
||||
@@ -53,17 +78,48 @@ export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) {
|
||||
<CardContent className="pt-6">
|
||||
<div className="grid grid-cols-1 gap-6 lg:grid-cols-3">
|
||||
<div className="space-y-6 lg:col-span-2">
|
||||
<AnnotatedDetectionImage
|
||||
detection={activeLog}
|
||||
videoWidth={data.summary.video_width}
|
||||
videoHeight={data.summary.video_height}
|
||||
/>
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground">
|
||||
Detection Video
|
||||
</p>
|
||||
<AnnotatedVideoPlayer
|
||||
videoRef={videoRef}
|
||||
logs={sortedLogs}
|
||||
visibleDetections={visibleDetections}
|
||||
videoWidth={data.summary.video_width}
|
||||
videoHeight={data.summary.video_height}
|
||||
videoUrl={videoUrl}
|
||||
isLoading={isVideoLoading}
|
||||
isError={isVideoError}
|
||||
onRetry={() => void refetchVideo()}
|
||||
onTimeUpdate={handleTimeUpdate}
|
||||
onVideoFrame={handleVideoFrame}
|
||||
onSeeked={handleSeeked}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DetectionLocationMap
|
||||
latitude={activeLog?.location.latitude ?? null}
|
||||
longitude={activeLog?.location.longitude ?? null}
|
||||
label={activeLog?.detection.display_name ?? 'Detection'}
|
||||
/>
|
||||
<div className="grid gap-4 xl:grid-cols-[minmax(0,1.65fr)_minmax(280px,1fr)]">
|
||||
<div className="space-y-2">
|
||||
<p className="text-xs font-medium text-muted-foreground">
|
||||
Annotated Image
|
||||
</p>
|
||||
<AnnotatedDetectionImage
|
||||
detection={activeLog}
|
||||
videoWidth={data.summary.video_width}
|
||||
videoHeight={data.summary.video_height}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<DetectionLocationMap
|
||||
latitude={activeLog?.location.latitude ?? null}
|
||||
longitude={activeLog?.location.longitude ?? null}
|
||||
label={activeMapLabel}
|
||||
title="Location on Map"
|
||||
variant="plain"
|
||||
aspectRatio={mediaAspectRatio}
|
||||
showCoordinates={false}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<CurrentDetectionBar activeLog={activeLog} data={data} />
|
||||
</div>
|
||||
@@ -71,7 +127,7 @@ export default function VideoPlayerSection({ data }: VideoPlayerSectionProps) {
|
||||
<DetectionLogs
|
||||
logs={sortedLogs}
|
||||
activeLogId={activeLog?.id}
|
||||
onSelect={(log) => setSelectedLogId(log.id)}
|
||||
onSelect={handleSeek}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -54,6 +54,8 @@ export const API_ROUTES = {
|
||||
UPLOAD_EVENTS: (token: string) =>
|
||||
`/biz/api/v1/uploads/events?sse_token=${encodeURIComponent(token)}`,
|
||||
RESULTS: (id: string) => `/biz/api/v1/results/${id}/completed`,
|
||||
ANNOTATION_FRAMES: (id: string) =>
|
||||
`/biz/api/v1/results/${id}/annotation-frames`,
|
||||
DETECTIONS: (id: string) => `/biz/api/v1/results/${id}/detections`,
|
||||
},
|
||||
TICKETS: {
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
PaginationParams,
|
||||
SseTokenResponse,
|
||||
UploadListResponse,
|
||||
VideoAnnotationFramesParams,
|
||||
VideoAnnotationFramesResponse,
|
||||
VideoDetectionsParams,
|
||||
VideoDetectionsResponse,
|
||||
} from '@/types';
|
||||
@@ -81,15 +83,28 @@ export const videoService = {
|
||||
return response.data;
|
||||
},
|
||||
|
||||
getVideoAnnotationFrames: async (
|
||||
videoId: string,
|
||||
params: VideoAnnotationFramesParams,
|
||||
): Promise<VideoAnnotationFramesResponse> => {
|
||||
const response = await axiosClient.get<VideoAnnotationFramesResponse>(
|
||||
API_ROUTES.VIDEOS.ANNOTATION_FRAMES(videoId),
|
||||
{
|
||||
params,
|
||||
},
|
||||
);
|
||||
return response.data;
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch the annotated video as a blob through the authenticated axios client.
|
||||
* Fetch a protected video as a blob through the authenticated axios client.
|
||||
*
|
||||
* The browser's native `<video src>` request cannot carry the Bearer token,
|
||||
* which makes the protected media endpoint respond with 401. Proxying the
|
||||
* download through axios attaches the auth header (and benefits from the
|
||||
* refresh-on-401 interceptor) so the bytes can be played back locally.
|
||||
*/
|
||||
getAnnotatedVideo: async (url: string): Promise<Blob> => {
|
||||
getProtectedVideo: async (url: string): Promise<Blob> => {
|
||||
const response = await axiosClient.get<Blob>(url, {
|
||||
responseType: 'blob',
|
||||
});
|
||||
|
||||
@@ -14,6 +14,14 @@ export type DetectionBoundingBox = {
|
||||
height: number;
|
||||
};
|
||||
|
||||
export type BoundingBoxOverlayItem = {
|
||||
id: string | number;
|
||||
class_name: string;
|
||||
display_name: string;
|
||||
confidence: number;
|
||||
bounding_box: DetectionBoundingBox;
|
||||
};
|
||||
|
||||
export type DetectionResultItem = {
|
||||
id: string;
|
||||
detection: {
|
||||
@@ -66,3 +74,45 @@ export type VideoDetectionsResponse = {
|
||||
sort: string;
|
||||
items: DetectionResultItem[];
|
||||
};
|
||||
|
||||
export type VideoAnnotationFramesParams = {
|
||||
start_time_ms: number;
|
||||
end_time_ms: number;
|
||||
};
|
||||
|
||||
export type VideoAnnotationFrameDetection = BoundingBoxOverlayItem & {
|
||||
location: {
|
||||
latitude: number | null;
|
||||
longitude: number | null;
|
||||
};
|
||||
};
|
||||
|
||||
export type VideoAnnotationFrame = {
|
||||
frame_number: number;
|
||||
timestamp_ms: number;
|
||||
timestamp_seconds: number;
|
||||
end_timestamp_ms?: number;
|
||||
detections: VideoAnnotationFrameDetection[];
|
||||
};
|
||||
|
||||
export type VideoAnnotationFramesResponse = {
|
||||
video_id: string;
|
||||
raw_video_url: string;
|
||||
video: {
|
||||
width: number;
|
||||
height: number;
|
||||
fps: number;
|
||||
duration_seconds: number;
|
||||
total_frames: number;
|
||||
};
|
||||
coordinate_format: 'xyxy_pixel' | string;
|
||||
window: {
|
||||
start_time_ms: number;
|
||||
end_time_ms: number;
|
||||
has_more_before: boolean;
|
||||
has_more_after: boolean;
|
||||
};
|
||||
frame_count_in_window: number;
|
||||
detection_count_in_window: number;
|
||||
frames: VideoAnnotationFrame[];
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user