refactor: modify upload section

This commit is contained in:
2026-03-19 12:32:55 +05:30
parent 37d7a664e0
commit 8510bd9f32
11 changed files with 531 additions and 436 deletions

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env sh
. "$(dirname "$0")/_/husky.sh"
# . "$(dirname "$0")/_/husky.sh"
npx lint-staged
# npx lint-staged

2
next-env.d.ts vendored
View File

@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import './.next/dev/types/routes.d.ts';
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.

View File

@@ -1,55 +0,0 @@
'use client';
import { useRouter } from 'next/navigation';
import dynamic from 'next/dynamic';
import { sessionService } from '@/services/api';
import { SessionContext } from '@/types';
import { PowerCircle, TrendingUp } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import { PoweredBy } from '@/components/powered-by';
import { ROUTES } from '@/utils/routes';
import { Reveal } from '@/components/ui/reveal';
const ProjectSelectionSection = dynamic(
() => import('@/components/project-selection-section').then((mod) => mod.ProjectSelectionSection),
{ ssr: false },
);
export default function NewAnalysisPage() {
const router = useRouter();
const handleSelectionComplete = (session: SessionContext) => {
// Save session to storage and navigate to upload page
sessionService.saveSession(session);
router.push(ROUTES.UPLOAD);
};
return (
<>
{/* Main Content */}
<main>
<div>
{/* Refined Left-Aligned Header */}
<div className="mb-8">
<PageHeader
title="VisionRoad Detection System"
description="Select project details to begin your AI-powered road infrastructure analysis"
icon={TrendingUp}
/>
</div>
{/* Project Selection Section */}
<Reveal delay={0.2} direction="up">
<div>
<ProjectSelectionSection onSelectionComplete={handleSelectionComplete} />
</div>
</Reveal>
<Reveal delay={0.4}>
<PoweredBy />
</Reveal>
</div>
</main>
</>
);
}

View File

@@ -77,7 +77,7 @@ export default function VideoResultsPage() {
}
}
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
router.push(ROUTES.UPLOAD);
};
const getTitle = () => {

View File

@@ -29,7 +29,7 @@ export default function ResultsPage() {
const videoData = sessionService.loadVideoData();
if (!sessionService.isSessionValid(storedSession) || !videoData) {
router.replace(ROUTES.NEW_ANALYSIS);
router.replace(ROUTES.UPLOAD);
return;
}
@@ -52,7 +52,7 @@ export default function ResultsPage() {
}
}
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
router.push(ROUTES.UPLOAD);
};
const getTitle = () => {

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, TrendingUp, ArrowUp, ArrowDown } from 'lucide-react';
@@ -25,9 +25,14 @@ export default function VideoProcessingPage() {
const [statusMessage, setStatusMessage] = useState('Initializing...');
const [error, setError] = useState<string | null>(null);
const wsRef = useRef<WebSocket | null>(null);
const connectWebSocket = useCallback(
(vid: string) => {
if (wsRef.current) return wsRef.current;
const ws = new WebSocket(`${WS_URL}/ws/${vid}`);
wsRef.current = ws;
ws.onmessage = async (event) => {
const data = JSON.parse(event.data);
@@ -60,9 +65,14 @@ export default function VideoProcessingPage() {
ws.onerror = () => {
setStatusMessage('Connection lost. Reconnecting...');
wsRef.current = null;
setTimeout(() => connectWebSocket(vid), 3000);
};
ws.onclose = () => {
wsRef.current = null;
};
return ws;
},
[router],
@@ -72,10 +82,14 @@ export default function VideoProcessingPage() {
const storedSession = sessionService.loadSession();
setSession(storedSession);
let isMounted = true;
const checkStatus = async () => {
try {
const statusData = await videoService.getVideoStatus(videoId);
if (!isMounted) return;
if (statusData.status === 'completed') {
router.replace(`/results/${videoId}`);
return;
@@ -94,14 +108,24 @@ export default function VideoProcessingPage() {
setIsLoading(false);
} catch (err) {
console.error('Status check failed:', err);
setError('Failed to connect to server.');
setIsLoading(false);
if (isMounted) {
setError('Failed to connect to server.');
setIsLoading(false);
}
}
};
if (videoId) {
checkStatus();
}
return () => {
isMounted = false;
if (wsRef.current) {
wsRef.current.close();
wsRef.current = null;
}
};
}, [videoId, router, connectWebSocket]);
if (isLoading) {

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -13,17 +13,16 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Loader2, TrendingUp, ArrowUp, ArrowDown } from 'lucide-react';
import { Loader2, TrendingUp, ChevronRight } from 'lucide-react';
import { PageHeader } from '@/components/page-header';
import { PoweredBy } from '@/components/powered-by';
import { sessionService, videoService } from '@/services/api';
import { SessionContext } from '@/types';
import { ROUTES } from '@/utils/routes';
import { storeVideoFile } from '@/lib/video-storage';
import { ProjectSelectionSection } from '@/components/project-selection-section';
import { Reveal } from '@/components/ui/reveal';
import { cn } from '@/lib/utils';
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const DETECTION_METHODS = [
{ value: 'yolo', label: 'YOLO Detection Model' },
{ value: 'yolo_vl', label: 'YOLO with Vision-Language Model' },
@@ -45,20 +44,21 @@ export default function UploadPage() {
// Upload states
const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0);
const [statusMessage, setStatusMessage] = useState('');
const [error, setError] = useState<string | null>(null);
// Load session on mount
useEffect(() => {
const storedSession = sessionService.loadSession();
if (!sessionService.isSessionValid(storedSession)) {
router.replace(ROUTES.NEW_ANALYSIS);
return;
}
setSession(storedSession);
// We don't load session on mount for the upload page to ensure
// project details are filled manually as requested.
setIsLoading(false);
}, [router]);
}, []);
const handleSelectionChange = useCallback((selectedSession: SessionContext | null) => {
setSession(selectedSession);
if (selectedSession) {
sessionService.saveSession(selectedSession);
}
}, []);
const handleUpload = async () => {
if (!file) {
@@ -66,27 +66,27 @@ export default function UploadPage() {
return;
}
if (!session) {
setError('Please complete the project selection first');
return;
}
const formData = new FormData();
formData.append('file', file);
formData.append('detection_mode', selectMethod);
if (session?.chainageId) {
formData.append('chainage_id', session.chainageId);
}
formData.append('chainage_id', session.chainageId as string);
if (jsonFile) {
formData.append('json_file', jsonFile);
}
setUploading(true);
setProgress(0);
setStatusMessage('Uploading...');
setError(null);
try {
const result = await videoService.uploadVideo(formData);
// Store file locally for potential recovery/results display
// Store file locally
if (file) {
try {
await storeVideoFile(result.video_id, file);
@@ -96,8 +96,6 @@ export default function UploadPage() {
}
sessionService.saveVideoData({ videoId: result.video_id });
// Redirect to the dynamic processing page
router.push(`/upload/${result.video_id}`);
} catch (err) {
let errorMessage = 'Upload failed';
@@ -107,200 +105,166 @@ export default function UploadPage() {
errorMessage = err.message;
}
setError(errorMessage);
setStatusMessage('');
setUploading(false);
setProgress(0);
}
};
const handleBackToSelection = () => {
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
};
const getTitle = () => 'Road Analysis';
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</Card>
<Loader2 className="h-10 w-10 animate-spin text-primary" />
</div>
);
}
return (
<div className="min-h-screen">
{/* Main Content */}
<main className="min-h-screen flex flex-col">
<div className="flex-1 container mx-auto px-6 py-6 max-w-340 flex flex-col">
{/* Header */}
<div className="mb-6">
<PageHeader
title={getTitle()}
description="Upload video file and fill in required details to start the road analysis"
icon={TrendingUp}
/>
</div>
const isSessionComplete = !!(session && sessionService.isSessionValid(session));
const isFormValid = isSessionComplete && file;
{/* Compact Session Info Bar */}
{session && (
<div className="mb-6">
<Card className="p-0 border shadow-sm overflow-hidden">
<div className="flex flex-col md:flex-row md:items-center justify-between py-4 px-6 gap-6 bg-card">
<div className="flex flex-wrap items-center gap-x-12 gap-y-4">
{[
{ label: 'Project', value: session.projectName, primary: true },
{ label: 'Package', value: session.packageName },
{ label: 'Chainage', value: session.chainageName },
].map((item, idx) => (
<div
key={item.label}
className={cn(
'flex flex-col',
idx !== 0 && 'border-l pl-12 border-border/60',
)}
>
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
{item.label}
</span>
<span
className={cn(
'leading-tight flex items-center gap-1.5',
item.primary
? 'text-base font-bold'
: 'text-sm font-semibold text-muted-foreground',
)}
>
{item.value}
{item.label === 'Chainage' && session.chainageDirection && (
<span className="flex items-center gap-1 px-1 py-0.5 rounded bg-muted text-[10px] font-bold uppercase border ml-1">
{session.chainageDirection === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{session.chainageDirection}
</span>
)}
</span>
</div>
))}
return (
<div className="min-h-screen pb-12">
<main>
{/* Header */}
<div className="mb-10">
<PageHeader
title="Intelligent Road Asset AI Analysis"
description="High-precision detection for potholes, signboards, and culverts from video data"
icon={TrendingUp}
/>
</div>
<div className="space-y-8 mt-8">
{/* Module 1: Project Selection */}
<Reveal direction="up" delay={0.1}>
<Card className="border">
<CardHeader>
<CardTitle className="text-xl font-bold">1. Project Details</CardTitle>
<CardDescription>
Select the target project, package, and chainage segment.
</CardDescription>
</CardHeader>
<CardContent>
<ProjectSelectionSection
onSelectionChange={handleSelectionChange}
asStep={true}
hideButton={true}
/>
</CardContent>
</Card>
</Reveal>
{/* Module 2: Upload Data */}
<Reveal direction="up" delay={0.2}>
<Card className={cn("border transition-all duration-300", !isSessionComplete && "opacity-60 pointer-events-none grayscale-[0.5]")}>
<CardHeader>
<CardTitle className="text-xl font-bold flex items-center gap-2">
2. Upload Video Data
</CardTitle>
<CardDescription>
Provide the video file and optional GPS telemetry for processing.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
<div className="grid grid-cols-1 gap-6 text-sm">
{/* Video File Input */}
<div className="space-y-2">
<Label htmlFor="video-file" className="text-sm font-semibold">
Video File <span className="text-destructive">*</span>
</Label>
<div className="relative group">
<Input
id="video-file"
type="file"
accept="video/*"
onChange={(e) => {
setFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading || !isSessionComplete}
className="h-12 bg-muted/30 border-dashed border-2 group-hover:border-primary/50 transition-colors cursor-pointer file:mr-4 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary file:text-primary-foreground file:font-semibold file:text-xs"
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* JSON File Input */}
<div className="space-y-2">
<Label htmlFor="json-file" className="text-sm font-semibold">
GPS JSON File (Optional)
</Label>
<Input
id="json-file"
type="file"
accept=".json,application/json"
onChange={(e) => {
setJsonFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading || !isSessionComplete}
className="h-11 bg-muted/20 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary/10 file:text-primary file:font-medium file:text-xs"
/>
</div>
{/* Select Method */}
<div className="space-y-2">
<Label htmlFor="select-method" className="text-sm font-semibold">
Analysis Method
</Label>
<Select
value={selectMethod}
onValueChange={setSelectMethod}
disabled={uploading || !isSessionComplete}
>
<SelectTrigger id="select-method" className="h-11 bg-muted/20">
<SelectValue placeholder="Select method" />
</SelectTrigger>
<SelectContent>
{DETECTION_METHODS.map((method) => (
<SelectItem key={method.value} value={method.value}>
{method.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/5 border border-destructive/20 text-destructive text-sm font-medium animate-in fade-in slide-in-from-top-1">
{error}
</div>
)}
{/* Primary Action Button */}
<div className="pt-2">
<Button
variant="outline"
size="sm"
onClick={handleBackToSelection}
className="font-semibold px-6 shrink-0 h-9"
onClick={handleUpload}
disabled={!isFormValid || uploading}
className="w-full h-14 font-extrabold uppercase tracking-wider"
>
Change Selection
{uploading ? (
<div className="flex items-center gap-3">
<Loader2 className="h-5 w-5 animate-spin" />
<span>Processing Upload...</span>
</div>
) : (
<div className="flex items-center gap-2">
<span>Upload & Process Analysis</span>
<ChevronRight className="h-5 w-5" />
</div>
)}
</Button>
</div>
</Card>
</div>
)}
</CardContent>
</Card>
</Reveal>
</div>
{/* Upload Card */}
<Card className="flex-1">
<CardHeader className="pb-4">
<CardTitle className="text-xl font-bold">Upload Video</CardTitle>
<CardDescription className="text-sm">
Select video file, GPS JSON file, and method for analysis
</CardDescription>
</CardHeader>
<CardContent className="pt-4 space-y-6">
<div className="space-y-6">
{/* Video File Input - Full Width */}
<div className="space-y-2">
<Label htmlFor="video-file" className="text-sm font-semibold">
Video File
</Label>
<Input
id="video-file"
type="file"
accept="video/*"
onChange={(e) => {
setFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading}
className="h-11 bg-muted/20 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary/10 file:text-primary file:font-medium file:text-xs hover:file:bg-primary/20"
/>
</div>
{/* JSON File and Method - Both in one line */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* JSON File Input */}
<div className="space-y-2">
<Label htmlFor="json-file" className="text-sm font-semibold">
GPS JSON File
</Label>
<Input
id="json-file"
type="file"
accept=".json,application/json"
onChange={(e) => {
setJsonFile(e.target.files?.[0] || null);
setError(null);
}}
disabled={uploading}
className="h-11 bg-muted/20 file:mr-3 file:py-1.5 file:px-3 file:rounded-md file:border-0 file:bg-primary/10 file:text-primary file:font-medium file:text-xs hover:file:bg-primary/20"
/>
</div>
{/* Select Method */}
<div className="space-y-2">
<Label htmlFor="select-method" className="text-sm font-semibold">
Select Method
</Label>
<Select
value={selectMethod}
onValueChange={setSelectMethod}
disabled={uploading}
>
<SelectTrigger id="select-method" className="h-11">
<SelectValue placeholder="Select method" />
</SelectTrigger>
<SelectContent>
{DETECTION_METHODS.map((method) => (
<SelectItem key={method.value} value={method.value}>
{method.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm leading-relaxed whitespace-pre-line">
{error}
</div>
)}
{/* Upload Button */}
<Button
onClick={handleUpload}
disabled={!file || uploading}
className="w-full h-14 text-base font-bold uppercase tracking-wide"
size="lg"
>
{uploading ? (
<div className="flex items-center gap-2">
<Loader2 className="h-5 w-5 animate-spin" />
<span>Processing...</span>
</div>
) : (
'Upload and Process'
)}
</Button>
</CardContent>
</Card>
<PoweredBy />
<div className="mt-12">
<Reveal delay={0.4}>
<PoweredBy />
</Reveal>
</div>
</main>
</div>

View File

@@ -33,7 +33,7 @@ const data = {
},
{
title: 'New Analysis',
url: ROUTES.NEW_ANALYSIS,
url: ROUTES.UPLOAD,
icon: Plus,
},
{

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect } from 'react';
import { useState, useEffect, useRef } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
@@ -17,12 +17,23 @@ import { Project, Package as PackageType, Chainage, SessionContext } from '@/typ
import { cn } from '@/lib/utils';
type ProjectSelectionSectionProps = {
onSelectionComplete: (session: SessionContext) => void;
onSelectionComplete?: (session: SessionContext) => void;
onSelectionChange?: (session: SessionContext | null) => void;
asStep?: boolean;
hideButton?: boolean;
};
export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectionSectionProps) {
let globalProjectsCache: Project[] | null = null;
let projectsPromise: Promise<Project[]> | null = null;
export function ProjectSelectionSection({
onSelectionComplete,
onSelectionChange,
asStep = false,
hideButton = false
}: ProjectSelectionSectionProps) {
// Data states
const [projects, setProjects] = useState<Project[]>([]);
const [projects, setProjects] = useState<Project[]>(globalProjectsCache || []);
const [packages, setPackages] = useState<PackageType[]>([]);
const [chainages, setChainages] = useState<Chainage[]>([]);
@@ -32,7 +43,7 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
const [selectedChainage, setSelectedChainage] = useState<Chainage | null>(null);
// Loading states
const [loadingProjects, setLoadingProjects] = useState(true);
const [loadingProjects, setLoadingProjects] = useState(!globalProjectsCache);
const [loadingPackages, setLoadingPackages] = useState(false);
const [loadingChainages, setLoadingChainages] = useState(false);
@@ -41,20 +52,48 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
// Load projects on mount
useEffect(() => {
let isMounted = true;
const loadProjects = async () => {
// Use cache if we already have it
if (globalProjectsCache) {
if (isMounted) {
setProjects(globalProjectsCache);
setLoadingProjects(false);
}
return;
}
// If a fetch is already in flight, reuse that promise
if (!projectsPromise) {
projectsPromise = projectService.getProjects().then(data => {
globalProjectsCache = data.items;
return data.items;
}).catch(err => {
projectsPromise = null; // Reset on error to allow retry
throw err;
});
}
try {
setLoadingProjects(true);
setError(null);
const data = await projectService.getProjects();
setProjects(data.items);
const data = await projectsPromise;
if (isMounted) {
setProjects(data);
}
} catch (err) {
console.error('Failed to load projects:', err);
setError('Failed to load projects. Please check if the backend is running.');
if (isMounted) {
setError('Failed to load projects. Please check connection.');
}
} finally {
setLoadingProjects(false);
if (isMounted) {
setLoadingProjects(false);
}
}
};
loadProjects();
return () => { isMounted = false; };
}, []);
// Load packages when project changes
@@ -65,6 +104,7 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
return;
}
let isMounted = true;
const loadPackages = async () => {
try {
setLoadingPackages(true);
@@ -73,15 +113,22 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
setSelectedChainage(null);
setChainages([]);
const data = await packageService.getPackagesByProject(selectedProject.id);
setPackages(data.items);
if (isMounted) {
setPackages(data.items);
}
} catch (err) {
console.error('Failed to load packages:', err);
setError('Failed to load packages for the selected project.');
if (isMounted) {
console.error('Failed to load packages:', err);
setError('Failed to load packages for the selected project.');
}
} finally {
setLoadingPackages(false);
if (isMounted) {
setLoadingPackages(false);
}
}
};
loadPackages();
return () => { isMounted = false; };
}, [selectedProject]);
// Load chainages when package changes
@@ -92,21 +139,29 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
return;
}
let isMounted = true;
const loadChainages = async () => {
try {
setLoadingChainages(true);
setError(null);
setSelectedChainage(null);
const data = await chainageService.getChainagesByPackage(selectedPackage.id);
setChainages(data.items);
if (isMounted) {
setChainages(data.items);
}
} catch (err) {
console.error('Failed to load chainages:', err);
setError('Failed to load chainages for the selected package.');
if (isMounted) {
console.error('Failed to load chainages:', err);
setError('Failed to load chainages for the selected package.');
}
} finally {
setLoadingChainages(false);
if (isMounted) {
setLoadingChainages(false);
}
}
};
loadChainages();
return () => { isMounted = false; };
}, [selectedPackage]);
const handleProjectChange = (projectId: string) => {
@@ -124,8 +179,38 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
setSelectedChainage(chainage);
};
// Cache the last reported state to prevent infinite loops
const lastReportedIdRef = useRef<string | null>(null);
// Handle change reporting
useEffect(() => {
if (onSelectionChange) {
const currentIds = selectedProject && selectedPackage && selectedChainage
? `${selectedProject.id}-${selectedPackage.id}-${selectedChainage.id}`
: null;
if (currentIds !== lastReportedIdRef.current) {
lastReportedIdRef.current = currentIds;
if (selectedProject && selectedPackage && selectedChainage) {
onSelectionChange({
projectId: selectedProject.id,
projectName: selectedProject.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: selectedChainage.id,
chainageName: selectedChainage.segment_name,
chainageDirection: selectedChainage.direction,
});
} else {
onSelectionChange(null);
}
}
}
}, [selectedProject, selectedPackage, selectedChainage, onSelectionChange]);
const handleProceed = () => {
if (selectedProject && selectedPackage && selectedChainage) {
if (selectedProject && selectedPackage && selectedChainage && onSelectionComplete) {
onSelectionComplete({
projectId: selectedProject.id,
projectName: selectedProject.name,
@@ -148,6 +233,167 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
return 'pending';
};
const content = (
<>
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm mb-6">
{error}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
{/* Project Dropdown */}
<div className="space-y-2">
<Label htmlFor="project" className="text-sm font-semibold">
Project
</Label>
<Select
value={selectedProject?.id || ''}
onValueChange={handleProjectChange}
disabled={loadingProjects}
>
<SelectTrigger id="project" className="h-11">
{loadingProjects ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue placeholder="Select project" />
)}
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Package Dropdown */}
<div className="space-y-2">
<Label htmlFor="package" className="text-sm font-semibold">
Package
</Label>
<Select
value={selectedPackage?.id || ''}
onValueChange={handlePackageChange}
disabled={!selectedProject || loadingPackages}
>
<SelectTrigger id="package" className="h-11">
{loadingPackages ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue
placeholder={selectedProject ? 'Select package' : 'Select project first'}
/>
)}
</SelectTrigger>
<SelectContent>
{packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id}>
{pkg.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Chainage Dropdown */}
<div className="space-y-2">
<Label htmlFor="chainage" className="text-sm font-semibold">
Chainage
</Label>
<Select
value={selectedChainage?.id || ''}
onValueChange={handleChainageChange}
disabled={!selectedPackage || loadingChainages}
>
<SelectTrigger id="chainage" className="h-11">
{loadingChainages ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue
placeholder={selectedPackage ? 'Select chainage' : 'Select package first'}
/>
)}
</SelectTrigger>
<SelectContent>
{chainages.map((chn) => (
<SelectItem key={chn.id} value={chn.id}>
<div className="flex flex-col gap-0.5 py-0.5">
<span className="font-semibold text-sm">{chn.segment_name}</span>
<div className="flex items-center gap-2 text-[10px] text-muted-foreground font-medium">
<span>{chn.chainage_start_km}-{chn.chainage_end_km} km</span>
<span className="h-2.5 w-px bg-border" />
<span className="flex items-center gap-1 uppercase">
{chn.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{chn.direction}
</span>
</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Selected Summary - Only if not asStep or if specifically desired */}
{!asStep && isComplete && (
<div className="px-4 py-3 rounded-md bg-secondary/50 border text-sm mb-8">
<div className="flex items-center gap-2 flex-wrap text-muted-foreground">
<span className="font-semibold text-foreground">Selection:</span>
<span className="text-foreground">{selectedProject?.name}</span>
<span>/</span>
<span className="text-foreground">{selectedPackage?.name}</span>
<span>/</span>
<span className="text-foreground flex items-center gap-1.5">
{selectedChainage?.segment_name}
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-muted text-[10px] font-bold uppercase border">
{selectedChainage?.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{selectedChainage?.direction}
</span>
</span>
</div>
</div>
)}
{/* Proceed Button */}
{!hideButton && (
<Button
onClick={handleProceed}
disabled={!isComplete}
className="w-full h-14 text-base font-bold uppercase tracking-wider"
size="lg"
>
{isComplete ? 'Proceed to Upload' : 'Select all fields to proceed'}
</Button>
)}
</>
);
if (asStep) {
return content;
}
return (
<Card className="overflow-hidden">
<CardHeader className="pb-6">
@@ -203,157 +449,8 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
</div>
</CardHeader>
<CardContent className="space-y-8">
{/* Error Display */}
{error && (
<div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm">
{error}
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{/* Project Dropdown */}
<div className="space-y-2">
<Label htmlFor="project" className="text-sm font-semibold">
Project
</Label>
<Select
value={selectedProject?.id || ''}
onValueChange={handleProjectChange}
disabled={loadingProjects}
>
<SelectTrigger id="project" className="h-11">
{loadingProjects ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue placeholder="Select project" />
)}
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Package Dropdown */}
<div className="space-y-2">
<Label htmlFor="package" className="text-sm font-semibold">
Package
</Label>
<Select
value={selectedPackage?.id || ''}
onValueChange={handlePackageChange}
disabled={!selectedProject || loadingPackages}
>
<SelectTrigger id="package" className="h-11">
{loadingPackages ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue
placeholder={selectedProject ? 'Select package' : 'Select project first'}
/>
)}
</SelectTrigger>
<SelectContent>
{packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id}>
{pkg.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Chainage Dropdown */}
<div className="space-y-2">
<Label htmlFor="chainage" className="text-sm font-semibold">
Chainage
</Label>
<Select
value={selectedChainage?.id || ''}
onValueChange={handleChainageChange}
disabled={!selectedPackage || loadingChainages}
>
<SelectTrigger id="chainage" className="h-11">
{loadingChainages ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>Loading...</span>
</div>
) : (
<SelectValue
placeholder={selectedPackage ? 'Select chainage' : 'Select package first'}
/>
)}
</SelectTrigger>
<SelectContent>
{chainages.map((chn) => (
<SelectItem key={chn.id} value={chn.id}>
<div className="flex flex-col gap-0.5 py-0.5">
<span className="font-semibold text-sm">{chn.segment_name}</span>
<div className="flex items-center gap-2 text-[10px] text-muted-foreground font-medium">
<span>{chn.chainage_start_km}-{chn.chainage_end_km} km</span>
<span className="h-2.5 w-px bg-border" />
<span className="flex items-center gap-1 uppercase">
{chn.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{chn.direction}
</span>
</div>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
{/* Selected Summary */}
{isComplete && (
<div className="px-4 py-3 rounded-md bg-secondary/50 border text-sm">
<div className="flex items-center gap-2 flex-wrap text-muted-foreground">
<span className="font-semibold text-foreground">Selection:</span>
<span className="text-foreground">{selectedProject?.name}</span>
<span>/</span>
<span className="text-foreground">{selectedPackage?.name}</span>
<span>/</span>
<span className="text-foreground flex items-center gap-1.5">
{selectedChainage?.segment_name}
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-muted text-[10px] font-bold uppercase border">
{selectedChainage?.direction === 'UP' ? (
<ArrowUp className="h-2.5 w-2.5" />
) : (
<ArrowDown className="h-2.5 w-2.5" />
)}
{selectedChainage?.direction}
</span>
</span>
</div>
</div>
)}
{/* Proceed Button */}
<Button
onClick={handleProceed}
disabled={!isComplete}
className="w-full h-12 text-base font-bold uppercase tracking-wide"
size="lg"
>
{isComplete ? 'Proceed to Upload' : 'Select all fields to proceed'}
</Button>
<CardContent className="pt-0">
{content}
</CardContent>
</Card>
);

View File

@@ -0,0 +1,66 @@
import * as React from 'react';
import { Check } from 'lucide-react';
import { cn } from '@/lib/utils';
interface StepperProps {
steps: {
title: string;
description?: string;
}[];
activeStep: number;
className?: string;
}
export function Stepper({ steps, activeStep, className }: StepperProps) {
return (
<div className={cn('w-full', className)}>
<div className="relative flex justify-between">
{/* Connection Lines */}
<div className="absolute top-5 left-0 right-0 h-0.5 bg-muted -z-10" />
<div
className="absolute top-5 left-0 h-0.5 bg-primary transition-all duration-500 -z-10"
style={{ width: `${(activeStep / (steps.length - 1)) * 100}%` }}
/>
{steps.map((step, index) => {
const isActive = index === activeStep;
const isCompleted = index < activeStep;
const isPending = index > activeStep;
return (
<div key={step.title} className="flex flex-col items-center flex-1">
<div
className={cn(
'w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all duration-300 border-2',
isActive
? 'bg-primary border-primary text-primary-foreground ring-4 ring-primary/10 scale-110'
: isCompleted
? 'bg-primary border-primary text-primary-foreground'
: 'bg-background border-muted text-muted-foreground',
)}
>
{isCompleted ? <Check className="h-5 w-5" /> : <span>{index + 1}</span>}
</div>
<div className="mt-4 text-center px-2">
<p
className={cn(
'text-sm font-bold transition-colors',
isActive ? 'text-foreground' : 'text-muted-foreground',
)}
>
{step.title}
</p>
{step.description && (
<p className="text-[11px] text-muted-foreground mt-1 line-clamp-1 max-w-[120px] mx-auto hidden md:block">
{step.description}
</p>
)}
</div>
</div>
);
})}
</div>
</div>
);
}

View File

@@ -4,7 +4,6 @@ export const ROUTES = {
PACKAGE: '/package',
CHAINAGE: '/chainage',
ACCOUNT: '/account',
NEW_ANALYSIS: '/new-analysis',
UPLOAD: '/upload',
RESULTS: '/results',
} as const;