setup husky prettier eslint

This commit is contained in:
2026-03-18 19:39:52 +05:30
parent 42624cae94
commit b675dd857b
93 changed files with 11269 additions and 6011 deletions

7
.eslintignore Normal file
View File

@@ -0,0 +1,7 @@
.next
node_modules
dist
build
coverage
public
.env*

4
.husky/pre-commit Normal file
View File

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

9
.prettierignore Normal file
View File

@@ -0,0 +1,9 @@
node_modules
.next
dist
out
coverage
build
.public
public
.env*

9
.prettierrc Normal file
View File

@@ -0,0 +1,9 @@
{
"singleQuote": true,
"trailingComma": "all",
"printWidth": 100,
"useTabs": false,
"tabWidth": 2,
"semi": true,
"endOfLine": "auto"
}

View File

@@ -63,11 +63,13 @@ YOLOPOTHOLE/
## 📦 Prerequisites
### Backend
- Python 3.9+
- CUDA-compatible GPU (optional, recommended)
- FFmpeg
### Frontend
- Node.js 18+
- npm/yarn/pnpm
@@ -116,6 +118,7 @@ npm install @radix-ui/react-scroll-area
### Backend Configuration
**`app/core/storage.py`**
```python
from pathlib import Path
@@ -135,6 +138,7 @@ MODELS_DIR.mkdir(exist_ok=True)
```
**`main.py`**
```python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
@@ -166,6 +170,7 @@ if __name__ == "__main__":
### Frontend Configuration
**`.env.local`**
```bash
NEXT_PUBLIC_WS_URL=ws://localhost:8000/api/v1
```
@@ -173,6 +178,7 @@ NEXT_PUBLIC_WS_URL=ws://localhost:8000/api/v1
### Model Configuration
**Adaptive Parameters** (in `video_processor.py`):
```python
# Speed < 30 km/h: ROI 50%, Confidence 0.35
# Speed 30-60 km/h: ROI 65%, Confidence 0.28
@@ -223,6 +229,7 @@ npm start
### REST Endpoints
#### 1. Upload Video
```http
POST /api/v1/upload
Content-Type: multipart/form-data
@@ -241,6 +248,7 @@ Response:
```
#### 2. Get Processing Status
```http
GET /api/v1/status/{video_id}
@@ -253,6 +261,7 @@ Response:
```
#### 3. Get Detection Results
```http
GET /api/v1/results/{video_id}
@@ -260,6 +269,7 @@ Response: See "Sample Detection Results" below
```
#### 4. List All Videos
```http
GET /api/v1/videos
@@ -279,24 +289,26 @@ Response:
### Internal API Calls (Frontend)
**Upload Request**:
```typescript
const formData = new FormData()
formData.append("file", file)
formData.append("speed_kmh", "30")
const formData = new FormData();
formData.append('file', file);
formData.append('speed_kmh', '30');
const response = await fetch(`${API_URL}/upload`, {
method: "POST",
body: formData
})
method: 'POST',
body: formData,
});
const result = await response.json()
const result = await response.json();
// Returns: { video_id, filename, message, status }
```
**Results Request**:
```typescript
const response = await fetch(`${API_URL}/results/${videoId}`)
const detectionData: DetectionData = await response.json()
const response = await fetch(`${API_URL}/results/${videoId}`);
const detectionData: DetectionData = await response.json();
```
---
@@ -304,13 +316,15 @@ const detectionData: DetectionData = await response.json()
## 🔄 WebSocket Protocol
### Connection
```javascript
const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`);
```
### Message Types
#### 1. Status Update
```json
{
"type": "status",
@@ -321,6 +335,7 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
```
#### 2. Progress Update
```json
{
"type": "progress",
@@ -332,6 +347,7 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
```
#### 3. Completion
```json
{
"type": "complete",
@@ -348,6 +364,7 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
```
#### 4. Error
```json
{
"type": "error",
@@ -357,6 +374,7 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
```
#### 5. Heartbeat
```json
{
"type": "heartbeat"
@@ -469,28 +487,28 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
```typescript
type DetectionData = {
video_id: string
video_id: string;
video_info: {
fps: number // 30.0
width: number // 1920
height: number // 1080
total_frames: number // 1200
}
fps: number; // 30.0
width: number; // 1920
height: number; // 1080
total_frames: number; // 1200
};
summary: {
unique_potholes: number // 18
total_detections: number // 245
total_frames: number // 1200
detection_rate: number // 12.25
}
unique_potholes: number; // 18
total_detections: number; // 245
total_frames: number; // 1200
detection_rate: number; // 12.25
};
frames: Array<{
frame_id: number
frame_id: number;
potholes: Array<{
pothole_id: number
bbox: { x1: number; y1: number; x2: number; y2: number }
confidence: number
}>
}>
}
pothole_id: number;
bbox: { x1: number; y1: number; x2: number; y2: number };
confidence: number;
}>;
}>;
};
```
---
@@ -500,6 +518,7 @@ type DetectionData = {
### Backend Issues
**Model Not Loading**
```bash
# Check model path
ls models/pothole-detector.pt
@@ -509,6 +528,7 @@ python -c "from ultralytics import YOLO; print('OK')"
```
**CUDA/GPU Issues**
```bash
# Check CUDA availability
python -c "import torch; print(torch.cuda.is_available())"
@@ -518,6 +538,7 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
```
**WebSocket Connection Failed**
- Ensure CORS is properly configured
- Check firewall settings for port 8000
- Verify WebSocket URL matches backend
@@ -525,6 +546,7 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
### Frontend Issues
**Video Not Playing**
```typescript
// Check browser console for errors
// Ensure video MIME type is supported
@@ -532,6 +554,7 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
```
**Bounding Boxes Not Showing**
```typescript
// Check canvas dimensions match video
// Verify detection data structure
@@ -539,6 +562,7 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
```
**Progress Not Updating**
```typescript
// Check WebSocket connection status
// Verify video_id matches between upload and WS
@@ -548,12 +572,14 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
### Performance Optimization
**Slow Processing**
- Use GPU acceleration (CUDA)
- Reduce video resolution
- Lower frame rate
- Adjust confidence thresholds
**High Memory Usage**
```python
# Limit thread pool workers
executor = ThreadPoolExecutor(max_workers=2)
@@ -582,6 +608,4 @@ pothole_tracker = defaultdict(lambda: deque(maxlen=10))
- Add authentication for production deployments
- Use HTTPS/WSS in production
**Built with FastAPI, YOLO, React, and shadcn/ui**

36
eslint.config.js Normal file
View File

@@ -0,0 +1,36 @@
import nextConfig from 'eslint-config-next';
import prettierPlugin from 'eslint-plugin-prettier';
const prettierRules = {
'prettier/prettier': [
'error',
{
singleQuote: true,
trailingComma: 'all',
printWidth: 100,
endOfLine: 'auto',
},
],
};
const additionalRules = {
...prettierRules,
// Some React rules are intentionally relaxed for this project.
'react-hooks/set-state-in-effect': 'off',
'react-hooks/exhaustive-deps': 'warn',
'react-hooks/immutability': 'off',
'react-hooks/incompatible-library': 'off',
'react-hooks/purity': 'off',
'import/no-anonymous-default-export': 'off',
};
export default [
...nextConfig,
{
files: ['**/*.{js,jsx,ts,tsx}'],
plugins: {
prettier: prettierPlugin,
},
rules: additionalRules,
},
];

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.

5256
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,26 +3,33 @@
"version": "0.1.0",
"private": true,
"scripts": {
"prepare": "husky install",
"build": "next build",
"dev": "next dev",
"lint": "eslint .",
"lint": "eslint . --ext .js,.jsx,.ts,.tsx",
"lint:fix": "eslint . --ext .js,.jsx,.ts,.tsx --fix",
"format": "prettier --write .",
"start": "next start"
},
"lint-staged": {
"*.+(js|jsx|ts|tsx)": [
"npm run lint:fix"
],
"*.+(json|md|css|scss|html)": [
"npm run format"
]
},
"dependencies": {
"@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.1",
"@radix-ui/react-popover": "^1.1.4",
"@radix-ui/react-progress": "^1.1.1",
"@radix-ui/react-scroll-area": "^1.2.2",
"@radix-ui/react-select": "^2.1.4",
"@radix-ui/react-separator": "^1.1.7",
"@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tooltip": "^1.2.8",
"@tanstack/react-table": "^8.21.3",
"@vercel/analytics": "1.3.1",
"axios": "^1.13.6",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -37,8 +44,7 @@
"react-leaflet": "^5.0.0",
"recharts": "2.15.4",
"sonner": "^1.7.4",
"tailwind-merge": "^3.3.1",
"tailwindcss-animate": "^1.0.7"
"tailwind-merge": "^3.3.1"
},
"devDependencies": {
"@tailwindcss/postcss": "^4.1.9",
@@ -47,7 +53,14 @@
"@types/react": "^19",
"@types/react-dom": "^19",
"autoprefixer": "^10.4.20",
"eslint": "^9.39.4",
"eslint-config-next": "^16.1.7",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.5",
"husky": "^9.1.7",
"lint-staged": "^16.4.0",
"postcss": "^8.5",
"prettier": "^3.8.1",
"tailwindcss": "^4.1.9",
"tw-animate-css": "^1.4.0",
"typescript": "^5"

View File

@@ -1,5 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
plugins: ['@tailwindcss/postcss'],
};
export default config;

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,9 @@
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 React from "react";
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 React from 'react';
const ModulesLayout = ({
children,
@@ -31,5 +31,4 @@ const ModulesLayout = ({
);
};
export default ModulesLayout;

View File

@@ -1,59 +1,55 @@
"use client"
'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"
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 }
)
() => import('@/components/project-selection-section').then((mod) => mod.ProjectSelectionSection),
{ ssr: false },
);
export default function NewAnalysisPage() {
const router = useRouter()
const router = useRouter();
const handleSelectionComplete = (session: SessionContext) => {
// Save session to storage and navigate to upload page
sessionService.saveSession(session)
router.push(ROUTES.UPLOAD)
}
const handleSelectionComplete = (session: SessionContext) => {
// Save session to storage and navigate to upload page
sessionService.saveSession(session);
router.push(ROUTES.UPLOAD);
};
return (
<div className="min-h-screen">
{/* Main Content */}
<main className="min-h-screen">
return (
<div className="min-h-screen">
{/* Main Content */}
<main className="min-h-screen">
<div className="container mx-auto px-6 py-10 max-w-340">
{/* 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>
<div className="container mx-auto px-6 py-10 max-w-340">
{/* 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>
{/* Project Selection Section */}
<Reveal delay={0.2} direction="up">
<div>
<ProjectSelectionSection onSelectionComplete={handleSelectionComplete} />
</div>
</Reveal>
<Reveal delay={0.4}>
<PoweredBy />
</Reveal>
</div>
</main>
<Reveal delay={0.4}>
<PoweredBy />
</Reveal>
</div>
)
</main>
</div>
);
}

View File

@@ -1,470 +1,513 @@
"use client"
'use client';
import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Loader2, CheckCircle2, Package, FolderKanban, Globe } from "lucide-react"
import { DataTable } from "@/components/data-table"
import { PageHeader } from "@/components/page-header"
import { projectService, packageService } from "@/services/api"
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Project,
Package as PackageType,
PackageCreate,
PackageUpdate
} from "@/types"
import { ColumnDef } from "@tanstack/react-table"
import { toast } from "sonner"
import { Badge } from "@/components/ui/badge"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { PoweredBy } from "@/components/powered-by"
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Loader2, CheckCircle2, Package, FolderKanban, Globe } from 'lucide-react';
import { DataTable } from '@/components/data-table';
import { PageHeader } from '@/components/page-header';
import { projectService, packageService } from '@/services/api';
import { Project, Package as PackageType, PackageCreate, PackageUpdate } from '@/types';
import { ColumnDef } from '@tanstack/react-table';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { PoweredBy } from '@/components/powered-by';
export default function PackagePage() {
const [packages, setPackages] = useState<PackageType[]>([])
const [totalItems, setTotalItems] = useState(0)
const [projects, setProjects] = useState<Project[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isModalOpen, setIsModalOpen] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const [loadingProjects, setLoadingProjects] = useState(false)
const [packages, setPackages] = useState<PackageType[]>([]);
const [totalItems, setTotalItems] = useState(0);
const [projects, setProjects] = useState<Project[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
const [loadingProjects, setLoadingProjects] = useState(false);
// Pagination state
const [skip, setSkip] = useState(0)
const [limit, setLimit] = useState(10)
// Pagination state
const [skip, setSkip] = useState(0);
const [limit, setLimit] = useState(10);
// Editing state
const [isEditing, setIsEditing] = useState(false)
const [currentPackage, setCurrentPackage] = useState<PackageType | null>(null)
// Editing state
const [isEditing, setIsEditing] = useState(false);
const [currentPackage, setCurrentPackage] = useState<PackageType | null>(null);
// Form fields
const [selectedProjectId, setSelectedProjectId] = useState("")
const [name, setName] = useState("")
const [region, setRegion] = useState("")
const [chainageStartKm, setChainageStartKm] = useState<string>("")
const [chainageEndKm, setChainageEndKm] = useState<string>("")
// Form fields
const [selectedProjectId, setSelectedProjectId] = useState('');
const [name, setName] = useState('');
const [region, setRegion] = useState('');
const [chainageStartKm, setChainageStartKm] = useState<string>('');
const [chainageEndKm, setChainageEndKm] = useState<string>('');
// Load packages and projects
const loadPackages = async (currentSkip = skip, currentLimit = limit) => {
try {
setIsLoading(true)
setError(null)
const data = await packageService.getPackages({ skip: currentSkip, limit: currentLimit })
setPackages(data.items)
setTotalItems(data.totalItems)
} catch (err) {
setError("Failed to load packages. Please check if the backend is running.")
} finally {
// Add a small delay for animation stability
setTimeout(() => {
setIsLoading(false)
}, 800)
}
// Load packages and projects
const loadPackages = async (currentSkip = skip, currentLimit = limit) => {
try {
setIsLoading(true);
setError(null);
const data = await packageService.getPackages({ skip: currentSkip, limit: currentLimit });
setPackages(data.items);
setTotalItems(data.totalItems);
} catch (err) {
setError('Failed to load packages. Please check if the backend is running.');
} finally {
// Add a small delay for animation stability
setTimeout(() => {
setIsLoading(false);
}, 800);
}
};
const loadProjects = async () => {
try {
setLoadingProjects(true);
const data = await projectService.getProjects({ skip: 0, limit: 1000 }); // Load all projects for selector
setProjects(data.items);
} catch (err) {
setError('Failed to load projects.');
} finally {
setLoadingProjects(false);
}
};
useEffect(() => {
loadPackages(skip, limit);
loadProjects();
}, [skip, limit]);
const resetForm = () => {
setSelectedProjectId('');
setName('');
setRegion('');
setChainageStartKm('');
setChainageEndKm('');
setError(null);
setIsEditing(false);
setCurrentPackage(null);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!selectedProjectId) {
setError('Please select a project first');
return;
}
if (!name.trim()) {
setError('Package name is required');
return;
}
const loadProjects = async () => {
try {
setLoadingProjects(true)
const data = await projectService.getProjects({ skip: 0, limit: 1000 }) // Load all projects for selector
setProjects(data.items)
} catch (err) {
setError("Failed to load projects.")
} finally {
setLoadingProjects(false)
}
setIsSubmitting(true);
setError(null);
try {
if (isEditing && currentPackage) {
const data: PackageUpdate = {
name: name.trim(),
region: region.trim() || null,
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0,
};
await packageService.updatePackage(currentPackage.id, data);
toast.success('Package Updated', {
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
});
} else {
const data: PackageCreate = {
project_id: selectedProjectId,
name: name.trim(),
region: region.trim() || null,
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0,
};
await packageService.createPackage(data);
toast.success('Package Created', {
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
});
}
// Refresh packages list
await loadPackages();
// Close modal and reset form immediately
setIsModalOpen(false);
resetForm();
} catch (err) {
const message =
err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} package`;
setError(message);
toast.error('Operation Failed', {
description: message,
});
} finally {
setIsSubmitting(false);
}
};
useEffect(() => {
loadPackages(skip, limit)
loadProjects()
}, [skip, limit])
const handleEdit = (pkg: PackageType) => {
setIsEditing(true);
setCurrentPackage(pkg);
setSelectedProjectId(pkg.project_id);
setName(pkg.name || '');
setRegion(pkg.region || '');
setChainageStartKm(pkg.chainage_start_km?.toString() || '0');
setChainageEndKm(pkg.chainage_end_km?.toString() || '0');
setIsModalOpen(true);
};
const resetForm = () => {
setSelectedProjectId("")
setName("")
setRegion("")
setChainageStartKm("")
setChainageEndKm("")
setError(null)
setIsEditing(false)
setCurrentPackage(null)
const handleDelete = async (pkg: PackageType) => {
if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) return;
try {
setIsLoading(true);
await packageService.deletePackage(pkg.id);
toast.success('Package Deleted', {
description: `${pkg.name} has been removed from the system.`,
});
await loadPackages();
} catch (err) {
setError('Failed to delete package');
toast.error('Deletion Failed', {
description: 'The package could not be removed. Please try again.',
});
} finally {
setIsLoading(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!selectedProjectId) {
setError("Please select a project first")
return
}
if (!name.trim()) {
setError("Package name is required")
return
}
const getProjectName = (projectId: string) => {
return projects.find((p) => p.id === projectId)?.name || projectId;
};
setIsSubmitting(true)
setError(null)
const columns: ColumnDef<PackageType>[] = [
{
accessorKey: 'name',
header: 'Package Name',
cell: ({ row }) => (
<div className="font-semibold text-gray-900 dark:text-gray-100">{row.original.name}</div>
),
},
{
accessorKey: 'project_id',
header: 'Project',
cell: ({ row }) => getProjectName(row.original.project_id),
},
{
accessorKey: 'project_state',
header: 'Project State',
cell: ({ row }) => {
const pkg = row.original;
const project = projects.find((p) => p.id === pkg.project_id);
if (!project?.state) return <span className="text-gray-400"></span>;
try {
if (isEditing && currentPackage) {
const data: PackageUpdate = {
name: name.trim(),
region: region.trim() || null,
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0,
}
await packageService.updatePackage(currentPackage.id, data)
toast.success("Package Updated", {
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
})
} else {
const data: PackageCreate = {
project_id: selectedProjectId,
name: name.trim(),
region: region.trim() || null,
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0,
}
await packageService.createPackage(data)
toast.success("Package Created", {
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
})
const states = project.state
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (states.length === 0) return <span className="text-gray-400"></span>;
const firstState = states[0];
const remainingStates = states.slice(1);
return (
<div className="flex items-center gap-1.5">
<Badge variant="secondary">{firstState}</Badge>
{remainingStates.length > 0 && (
<Popover>
<PopoverTrigger asChild>
<button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
+{remainingStates.length}
</button>
</PopoverTrigger>
<PopoverContent className="w-auto p-2" align="start">
<div className="flex flex-col gap-1.5">
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
Other States
</p>
{remainingStates.map((item, idx) => (
<Badge key={idx} variant="secondary">
{item}
</Badge>
))}
</div>
</PopoverContent>
</Popover>
)}
</div>
);
},
},
{
accessorKey: 'region',
header: 'Region',
},
{
accessorKey: 'chainage_start_km',
header: 'Start (km)',
cell: ({ row }) => row.original.chainage_start_km?.toFixed(2) ?? '0.00',
},
{
accessorKey: 'chainage_end_km',
header: 'End (km)',
cell: ({ row }) => row.original.chainage_end_km?.toFixed(2) ?? '0.00',
},
];
return (
<>
<main className="relative z-10">
{/* Refined Header */}
<div className="mb-8">
<PageHeader
title="Package Management"
description="Manage project packages"
icon={Package}
actions={
<Button
onClick={() => {
setIsEditing(false);
setIsModalOpen(true);
}}
>
<Package className="mr-2 h-4 w-4" />
Add New Package
</Button>
}
/>
</div>
// Refresh packages list
await loadPackages()
{/* Data Table */}
<div>
<DataTable
title="Packages"
data={packages}
columns={columns}
onEdit={handleEdit}
onDelete={handleDelete}
isLoading={isLoading}
pagination={{
skip,
limit,
totalItems,
onPageChange: setSkip,
onLimitChange: (newLimit) => {
setLimit(newLimit);
setSkip(0); // Reset skip when limit changes
},
}}
/>
</div>
// Close modal and reset form immediately
setIsModalOpen(false)
resetForm()
} catch (err) {
const message = err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} package`
setError(message)
toast.error("Operation Failed", {
description: message,
})
} finally {
setIsSubmitting(false)
}
}
<PoweredBy />
</main>
const handleEdit = (pkg: PackageType) => {
setIsEditing(true)
setCurrentPackage(pkg)
setSelectedProjectId(pkg.project_id)
setName(pkg.name || "")
setRegion(pkg.region || "")
setChainageStartKm(pkg.chainage_start_km?.toString() || "0")
setChainageEndKm(pkg.chainage_end_km?.toString() || "0")
setIsModalOpen(true)
}
{/* Modal Dialog */}
<Dialog
open={isModalOpen}
onOpenChange={(open) => {
if (!open) {
setIsModalOpen(false);
resetForm();
} else {
setIsModalOpen(true);
}
}}
>
<DialogContent className="max-w-2xl" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader className="gap-2">
<DialogTitle className="flex items-center gap-3 text-xl">
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
<Package className="h-5 w-5" />
</div>
{isEditing ? 'Edit Package Details' : 'Create New Package'}
</DialogTitle>
<DialogDescription className="text-sm">
{isEditing
? 'Update the technical specifications for your road infrastructure package.'
: 'Select a project and provide the essential data to establish a new package.'}
</DialogDescription>
</DialogHeader>
const handleDelete = async (pkg: PackageType) => {
if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) return
<form onSubmit={handleSubmit} className="space-y-8">
{/* Step 1: Select Project */}
{!isEditing && (
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="w-6 h-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase">
01
</div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
Select Parent Project
</p>
</div>
<Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
<SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
{loadingProjects ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
<span className="text-muted-foreground text-sm">Loading...</span>
</div>
) : (
<SelectValue placeholder="Choose a project..." />
)}
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id} className="py-3">
<span className="font-semibold">{project.name}</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
try {
setIsLoading(true)
await packageService.deletePackage(pkg.id)
toast.success("Package Deleted", {
description: `${pkg.name} has been removed from the system.`,
})
await loadPackages()
} catch (err) {
setError("Failed to delete package")
toast.error("Deletion Failed", {
description: "The package could not be removed. Please try again.",
})
} finally {
setIsLoading(false)
}
}
{/* Step 2: Package Info */}
<div
className={`space-y-4 ${selectedProjectId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
>
{!isEditing && (
<div className="flex items-center gap-2.5">
<div
className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedProjectId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
>
02
</div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
Package Information
</p>
</div>
)}
const getProjectName = (projectId: string) => {
return projects.find(p => p.id === projectId)?.name || projectId
}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
<div className="space-y-2">
<Label
htmlFor="pkg-name"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Package Name <span className="text-destructive">*</span>
</Label>
<Input
id="pkg-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Package 01"
className="h-11 bg-muted/20 border-border/60"
required
/>
</div>
const columns: ColumnDef<PackageType>[] = [
{
accessorKey: "name",
header: "Package Name",
cell: ({ row }) => (
<div className="font-semibold text-gray-900 dark:text-gray-100">{row.original.name}</div>
)
},
{
accessorKey: "project_id",
header: "Project",
cell: ({ row }) => getProjectName(row.original.project_id)
},
{
accessorKey: "project_state",
header: "Project State",
cell: ({ row }) => {
const pkg = row.original
const project = projects.find(p => p.id === pkg.project_id)
if (!project?.state) return <span className="text-gray-400"></span>
<div className="space-y-2">
<Label
htmlFor="region"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2"
>
<Globe className="h-3.5 w-3.5 opacity-60" />
Region{' '}
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label>
<Input
id="region"
value={region}
onChange={(e) => setRegion(e.target.value)}
placeholder="e.g. North Zone"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
const states = project.state.split(',').map(s => s.trim()).filter(Boolean)
if (states.length === 0) return <span className="text-gray-400"></span>
<div className="space-y-2">
<Label
htmlFor="chainage-start"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Chainage Start (km)
</Label>
<Input
id="chainage-start"
type="number"
step="0.01"
value={chainageStartKm}
onChange={(e) => setChainageStartKm(e.target.value)}
placeholder="0.00"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
const firstState = states[0]
const remainingStates = states.slice(1)
<div className="space-y-2">
<Label
htmlFor="chainage-end"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Chainage End (km)
</Label>
<Input
id="chainage-end"
type="number"
step="0.01"
value={chainageEndKm}
onChange={(e) => setChainageEndKm(e.target.value)}
placeholder="0.00"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
</div>
</div>
return (
<div className="flex items-center gap-1.5">
<Badge variant="secondary">
{firstState}
</Badge>
{remainingStates.length > 0 && (
<Popover>
<PopoverTrigger asChild>
<button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
+{remainingStates.length}
</button>
</PopoverTrigger>
<PopoverContent className="w-auto p-2" align="start">
<div className="flex flex-col gap-1.5">
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">Other States</p>
{remainingStates.map((item, idx) => (
<Badge key={idx} variant="secondary">
{item}
</Badge>
))}
</div>
</PopoverContent>
</Popover>
)}
</div>
)
}
},
{
accessorKey: "region",
header: "Region",
},
{
accessorKey: "chainage_start_km",
header: "Start (km)",
cell: ({ row }) => row.original.chainage_start_km?.toFixed(2) ?? "0.00"
},
{
accessorKey: "chainage_end_km",
header: "End (km)",
cell: ({ row }) => row.original.chainage_end_km?.toFixed(2) ?? "0.00"
},
]
return (
<>
<main className="relative z-10">
{/* Refined Header */}
<div className="mb-8">
<PageHeader
title="Package Management"
description="Manage project packages"
icon={Package}
actions={
<Button
onClick={() => { setIsEditing(false); setIsModalOpen(true); }}
>
<Package className="mr-2 h-4 w-4" />
Add New Package
</Button>
}
/>
</div>
{/* Data Table */}
<div>
<DataTable
title="Packages"
data={packages}
columns={columns}
onEdit={handleEdit}
onDelete={handleDelete}
isLoading={isLoading}
pagination={{
skip,
limit,
totalItems,
onPageChange: setSkip,
onLimitChange: (newLimit) => {
setLimit(newLimit);
setSkip(0); // Reset skip when limit changes
}
}}
/>
</div>
<PoweredBy />
</main>
{/* Modal Dialog */}
<Dialog open={isModalOpen} onOpenChange={(open) => { if (!open) { setIsModalOpen(false); resetForm(); } else { setIsModalOpen(true); } }}>
<DialogContent
className="max-w-2xl"
onOpenAutoFocus={(e) => e.preventDefault()}
>
<DialogHeader className="gap-2">
<DialogTitle className="flex items-center gap-3 text-xl">
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
<Package className="h-5 w-5" />
</div>
{isEditing ? 'Edit Package Details' : 'Create New Package'}
</DialogTitle>
<DialogDescription className="text-sm">
{isEditing ? 'Update the technical specifications for your road infrastructure package.' : 'Select a project and provide the essential data to establish a new package.'}
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit} className="space-y-8">
{/* Step 1: Select Project */}
{!isEditing && (
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="w-6 h-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase">
01
</div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">Select Parent Project</p>
</div>
<Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
<SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
{loadingProjects ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
<span className="text-muted-foreground text-sm">Loading...</span>
</div>
) : (
<SelectValue placeholder="Choose a project..." />
)}
</SelectTrigger>
<SelectContent>
{projects.map(project => (
<SelectItem key={project.id} value={project.id} className="py-3">
<span className="font-semibold">{project.name}</span>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Step 2: Package Info */}
<div className={`space-y-4 ${selectedProjectId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}>
{!isEditing && (
<div className="flex items-center gap-2.5">
<div className={`w-6 h-6 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedProjectId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}>
02
</div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">Package Information</p>
</div>
)}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
<div className="space-y-2">
<Label htmlFor="pkg-name" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">
Package Name <span className="text-destructive">*</span>
</Label>
<Input
id="pkg-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="e.g. Package 01"
className="h-11 bg-muted/20 border-border/60"
required
/>
</div>
<div className="space-y-2">
<Label htmlFor="region" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2">
<Globe className="h-3.5 w-3.5 opacity-60" />
Region <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label>
<Input
id="region"
value={region}
onChange={(e) => setRegion(e.target.value)}
placeholder="e.g. North Zone"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
<div className="space-y-2">
<Label htmlFor="chainage-start" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">
Chainage Start (km)
</Label>
<Input
id="chainage-start"
type="number"
step="0.01"
value={chainageStartKm}
onChange={(e) => setChainageStartKm(e.target.value)}
placeholder="0.00"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
<div className="space-y-2">
<Label htmlFor="chainage-end" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">
Chainage End (km)
</Label>
<Input
id="chainage-end"
type="number"
step="0.01"
value={chainageEndKm}
onChange={(e) => setChainageEndKm(e.target.value)}
placeholder="0.00"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
</div>
</div>
{/* Submit Button */}
<div className="flex gap-4 pt-4">
<Button
type="button"
variant="outline"
onClick={() => {
setIsModalOpen(false)
resetForm()
}}
disabled={isSubmitting}
className="flex-1"
>
Cancel
</Button>
<Button
type="submit"
disabled={isSubmitting || !name.trim() || !selectedProjectId}
className="flex-1"
>
{isSubmitting ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>{isEditing ? 'Updating...' : 'Creating...'}</span>
</div>
) : (
<div className="flex items-center gap-2">
{isEditing ? <CheckCircle2 className="h-4 w-4" /> : <Package className="h-4 w-4" />}
<span>{isEditing ? 'Update Package' : 'Create Package'}</span>
</div>
)}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</>
)
{/* Submit Button */}
<div className="flex gap-4 pt-4">
<Button
type="button"
variant="outline"
onClick={() => {
setIsModalOpen(false);
resetForm();
}}
disabled={isSubmitting}
className="flex-1"
>
Cancel
</Button>
<Button
type="submit"
disabled={isSubmitting || !name.trim() || !selectedProjectId}
className="flex-1"
>
{isSubmitting ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>{isEditing ? 'Updating...' : 'Creating...'}</span>
</div>
) : (
<div className="flex items-center gap-2">
{isEditing ? (
<CheckCircle2 className="h-4 w-4" />
) : (
<Package className="h-4 w-4" />
)}
<span>{isEditing ? 'Update Package' : 'Create Package'}</span>
</div>
)}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -1,6 +1,6 @@
import { redirect } from "next/navigation"
import { ROUTES } from "@/utils/routes"
import { redirect } from 'next/navigation';
import { ROUTES } from '@/utils/routes';
export default function HomePage() {
redirect(ROUTES.DASHBOARD)
redirect(ROUTES.DASHBOARD);
}

View File

@@ -1,452 +1,497 @@
"use client"
'use client';
import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Loader2, CheckCircle2, Layers, MapPin, Building2, Route, X } from "lucide-react"
import { DataTable } from "@/components/data-table"
import { PageHeader } from "@/components/page-header"
import { projectService } from "@/services/api"
import { ProjectCreate, Project, ProjectUpdate } from "@/types"
import { ColumnDef } from "@tanstack/react-table"
import { toast } from "sonner"
import { Badge } from "@/components/ui/badge"
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover"
import { PoweredBy } from "@/components/powered-by"
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Loader2, CheckCircle2, Layers, MapPin, Building2, Route, X } from 'lucide-react';
import { DataTable } from '@/components/data-table';
import { PageHeader } from '@/components/page-header';
import { projectService } from '@/services/api';
import { ProjectCreate, Project, ProjectUpdate } from '@/types';
import { ColumnDef } from '@tanstack/react-table';
import { toast } from 'sonner';
import { Badge } from '@/components/ui/badge';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { PoweredBy } from '@/components/powered-by';
export default function ProjectPage() {
const [projects, setProjects] = useState<Project[]>([])
const [totalItems, setTotalItems] = useState(0)
const [isLoading, setIsLoading] = useState(true)
const [isModalOpen, setIsModalOpen] = useState(false)
const [isSubmitting, setIsSubmitting] = useState(false)
const [error, setError] = useState<string | null>(null)
const [projects, setProjects] = useState<Project[]>([]);
const [totalItems, setTotalItems] = useState(0);
const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null);
// Pagination state
const [skip, setSkip] = useState(0)
const [limit, setLimit] = useState(10)
// Pagination state
const [skip, setSkip] = useState(0);
const [limit, setLimit] = useState(10);
// Editing state
const [isEditing, setIsEditing] = useState(false)
const [currentProject, setCurrentProject] = useState<Project | null>(null)
// Editing state
const [isEditing, setIsEditing] = useState(false);
const [currentProject, setCurrentProject] = useState<Project | null>(null);
// Form fields
const [name, setName] = useState("")
const [state, setState] = useState("")
const [corridorName, setCorridorName] = useState("")
const [startLat, setStartLat] = useState("")
const [startLng, setStartLng] = useState("")
const [endLat, setEndLat] = useState("")
const [endLng, setEndLng] = useState("")
// Form fields
const [name, setName] = useState('');
const [state, setState] = useState('');
const [corridorName, setCorridorName] = useState('');
const [startLat, setStartLat] = useState('');
const [startLng, setStartLng] = useState('');
const [endLat, setEndLat] = useState('');
const [endLng, setEndLng] = useState('');
// Load projects
const loadProjects = async (currentSkip = skip, currentLimit = limit) => {
try {
setIsLoading(true)
setError(null)
const data = await projectService.getProjects({ skip: currentSkip, limit: currentLimit })
setProjects(data.items)
setTotalItems(data.totalItems)
} catch (err) {
setError("Failed to load projects. Please check if the backend is running.")
} finally {
// Add a small delay for animation stability
setTimeout(() => {
setIsLoading(false)
}, 800)
}
// Load projects
const loadProjects = async (currentSkip = skip, currentLimit = limit) => {
try {
setIsLoading(true);
setError(null);
const data = await projectService.getProjects({ skip: currentSkip, limit: currentLimit });
setProjects(data.items);
setTotalItems(data.totalItems);
} catch (err) {
setError('Failed to load projects. Please check if the backend is running.');
} finally {
// Add a small delay for animation stability
setTimeout(() => {
setIsLoading(false);
}, 800);
}
};
useEffect(() => {
loadProjects(skip, limit);
}, [skip, limit]);
const resetForm = () => {
setName('');
setState('');
setCorridorName('');
setStartLat('');
setStartLng('');
setEndLat('');
setEndLng('');
setError(null);
setIsEditing(false);
setCurrentProject(null);
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!name.trim()) {
setError('Project name is required');
return;
}
useEffect(() => {
loadProjects(skip, limit)
}, [skip, limit])
setIsSubmitting(true);
setError(null);
const resetForm = () => {
setName("")
setState("")
setCorridorName("")
setStartLat("")
setStartLng("")
setEndLat("")
setEndLng("")
setError(null)
setIsEditing(false)
setCurrentProject(null)
try {
if (isEditing && currentProject) {
const data: ProjectUpdate = {
name: name.trim(),
state: state.trim() || null,
corridor_name: corridorName.trim() || null,
start_lat: startLat ? parseFloat(startLat) : null,
start_lng: startLng ? parseFloat(startLng) : null,
end_lat: endLat ? parseFloat(endLat) : null,
end_lng: endLng ? parseFloat(endLng) : null,
};
await projectService.updateProject(currentProject.id, data);
toast.success('Project Updated', {
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
});
} else {
const data: ProjectCreate = {
name: name.trim(),
state: state.trim() || null,
corridor_name: corridorName.trim() || null,
start_lat: startLat ? parseFloat(startLat) : null,
start_lng: startLng ? parseFloat(startLng) : null,
end_lat: endLat ? parseFloat(endLat) : null,
end_lng: endLng ? parseFloat(endLng) : null,
};
await projectService.createProject(data);
toast.success('Project Created', {
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
});
}
// Refresh projects list
await loadProjects();
// Close modal and reset form immediately
setIsModalOpen(false);
resetForm();
} catch (err) {
const message =
err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} project`;
setError(message);
toast.error('Operation Failed', {
description: message,
});
} finally {
setIsSubmitting(false);
}
};
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!name.trim()) {
setError("Project name is required")
return
}
const handleEdit = (project: Project) => {
setIsEditing(true);
setCurrentProject(project);
setName(project.name || '');
setState(project.state || '');
setCorridorName(project.corridor_name || '');
setStartLat(project.start_lat?.toString() || '');
setStartLng(project.start_lng?.toString() || '');
setEndLat(project.end_lat?.toString() || '');
setEndLng(project.end_lng?.toString() || '');
setIsModalOpen(true);
};
setIsSubmitting(true)
setError(null)
const handleDelete = async (project: Project) => {
if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) return;
try {
if (isEditing && currentProject) {
const data: ProjectUpdate = {
name: name.trim(),
state: state.trim() || null,
corridor_name: corridorName.trim() || null,
start_lat: startLat ? parseFloat(startLat) : null,
start_lng: startLng ? parseFloat(startLng) : null,
end_lat: endLat ? parseFloat(endLat) : null,
end_lng: endLng ? parseFloat(endLng) : null,
}
await projectService.updateProject(currentProject.id, data)
toast.success("Project Updated", {
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
})
} else {
const data: ProjectCreate = {
name: name.trim(),
state: state.trim() || null,
corridor_name: corridorName.trim() || null,
start_lat: startLat ? parseFloat(startLat) : null,
start_lng: startLng ? parseFloat(startLng) : null,
end_lat: endLat ? parseFloat(endLat) : null,
end_lng: endLng ? parseFloat(endLng) : null,
}
await projectService.createProject(data)
toast.success("Project Created", {
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
})
try {
setIsLoading(true);
await projectService.deleteProject(project.id);
toast.success('Project Deleted', {
description: `${project.name} has been removed from the system.`,
});
await loadProjects();
} catch (err) {
setError('Failed to delete project');
toast.error('Deletion Failed', {
description:
'The project could not be removed. Please try again or check your permissions.',
});
} finally {
setIsLoading(false);
}
};
const columns: ColumnDef<Project>[] = [
{
accessorKey: 'name',
header: 'Project Name',
cell: ({ row }) => <div className="font-semibold">{row.original.name}</div>,
},
{
accessorKey: 'state',
header: 'State',
cell: ({ row }) => {
const project = row.original;
if (!project.state) return <span></span>;
const states = project.state
.split(',')
.map((s) => s.trim())
.filter(Boolean);
if (states.length === 0) return <span></span>;
const firstState = states[0];
const remainingStates = states.slice(1);
return (
<div className="flex items-center gap-1.5">
<Badge variant="secondary">{firstState}</Badge>
{remainingStates.length > 0 && (
<Popover>
<PopoverTrigger asChild>
<button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
+{remainingStates.length}
</button>
</PopoverTrigger>
<PopoverContent className="w-auto p-2" align="start">
<div className="flex flex-col gap-1.5">
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
Other States
</p>
{remainingStates.map((item, idx) => (
<Badge key={idx} variant="secondary">
{item}
</Badge>
))}
</div>
</PopoverContent>
</Popover>
)}
</div>
);
},
},
{
accessorKey: 'corridor_name',
header: 'Corridor',
},
];
return (
<>
<main className="relative z-10">
{/* Refined Header */}
<div className="mb-8">
<PageHeader
title="Project Management"
description="Manage road infrastructure projects"
icon={Layers}
actions={
<Button
onClick={() => {
setIsEditing(false);
setIsModalOpen(true);
}}
>
<Layers className="mr-2 h-5 w-5" />
Add New Project
</Button>
}
/>
</div>
// Refresh projects list
await loadProjects()
{/* Data Table */}
<div>
<DataTable
title="Projects"
data={projects}
columns={columns}
onEdit={handleEdit}
onDelete={handleDelete}
isLoading={isLoading}
pagination={{
skip,
limit,
totalItems,
onPageChange: setSkip,
onLimitChange: (newLimit) => {
setLimit(newLimit);
setSkip(0); // Reset skip when limit changes
},
}}
/>
</div>
// Close modal and reset form immediately
setIsModalOpen(false)
resetForm()
} catch (err) {
const message = err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} project`
setError(message)
toast.error("Operation Failed", {
description: message,
})
} finally {
setIsSubmitting(false)
}
}
<PoweredBy />
</main>
const handleEdit = (project: Project) => {
setIsEditing(true)
setCurrentProject(project)
setName(project.name || "")
setState(project.state || "")
setCorridorName(project.corridor_name || "")
setStartLat(project.start_lat?.toString() || "")
setStartLng(project.start_lng?.toString() || "")
setEndLat(project.end_lat?.toString() || "")
setEndLng(project.end_lng?.toString() || "")
setIsModalOpen(true)
}
{/* Modal Dialog */}
<Dialog
open={isModalOpen}
onOpenChange={(open) => {
if (!open) {
setIsModalOpen(false);
resetForm();
} else {
setIsModalOpen(true);
}
}}
>
<DialogContent className="max-w-2xl" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader className="gap-2">
<DialogTitle className="flex items-center gap-3 text-xl">
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
<Layers className="h-5 w-5" />
</div>
{isEditing ? 'Edit Project Details' : 'Create New Project'}
</DialogTitle>
<DialogDescription className="text-sm">
{isEditing
? 'Update the technical specifications for your road infrastructure project.'
: 'Provide the essential road data to establish a new analysis project.'}
</DialogDescription>
</DialogHeader>
const handleDelete = async (project: Project) => {
if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) return
<form onSubmit={handleSubmit} className="space-y-6">
{/* Project Name */}
<div className="space-y-2">
<Label
htmlFor="name"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Project Name <span className="text-destructive">*</span>
</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter a descriptive project name..."
className="h-11 bg-muted/20 border-border/60"
required
/>
</div>
try {
setIsLoading(true)
await projectService.deleteProject(project.id)
toast.success("Project Deleted", {
description: `${project.name} has been removed from the system.`,
})
await loadProjects()
} catch (err) {
setError("Failed to delete project")
toast.error("Deletion Failed", {
description: "The project could not be removed. Please try again or check your permissions.",
})
} finally {
setIsLoading(false)
}
}
const columns: ColumnDef<Project>[] = [
{
accessorKey: "name",
header: "Project Name",
cell: ({ row }) => (
<div className="font-semibold">{row.original.name}</div>
)
},
{
accessorKey: "state",
header: "State",
cell: ({ row }) => {
const project = row.original
if (!project.state) return <span></span>
const states = project.state.split(',').map(s => s.trim()).filter(Boolean)
if (states.length === 0) return <span></span>
const firstState = states[0]
const remainingStates = states.slice(1)
return (
<div className="flex items-center gap-1.5">
<Badge
variant="secondary"
>
{firstState}
</Badge>
{remainingStates.length > 0 && (
<Popover>
<PopoverTrigger asChild>
<button className="flex items-center justify-center rounded-full bg-muted/50 hover:bg-muted px-1.5 py-0.5 text-[10px] font-bold text-muted-foreground transition-colors border border-border/40">
+{remainingStates.length}
</button>
</PopoverTrigger>
<PopoverContent className="w-auto p-2" align="start">
<div className="flex flex-col gap-1.5">
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">Other States</p>
{remainingStates.map((item, idx) => (
<Badge
key={idx}
variant="secondary"
>
{item}
</Badge>
))}
</div>
</PopoverContent>
</Popover>
)}
</div>
)
}
},
{
accessorKey: "corridor_name",
header: "Corridor",
},
]
return (
<>
<main className="relative z-10">
{/* Refined Header */}
<div className="mb-8">
<PageHeader
title="Project Management"
description="Manage road infrastructure projects"
icon={Layers}
actions={
<Button
onClick={() => { setIsEditing(false); setIsModalOpen(true); }}
>
<Layers className="mr-2 h-5 w-5" />
Add New Project
</Button>
}
/>
</div>
{/* Data Table */}
<div>
<DataTable
title="Projects"
data={projects}
columns={columns}
onEdit={handleEdit}
onDelete={handleDelete}
isLoading={isLoading}
pagination={{
skip,
limit,
totalItems,
onPageChange: setSkip,
onLimitChange: (newLimit) => {
setLimit(newLimit);
setSkip(0); // Reset skip when limit changes
}
}}
/>
</div>
<PoweredBy />
</main>
{/* Modal Dialog */}
<Dialog open={isModalOpen} onOpenChange={(open) => { if (!open) { setIsModalOpen(false); resetForm(); } else { setIsModalOpen(true); } }}>
<DialogContent
className="max-w-2xl"
onOpenAutoFocus={(e) => e.preventDefault()}
{/* State & Corridor Row */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
<div className="space-y-2">
<Label
htmlFor="state"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
<DialogHeader className="gap-2">
<DialogTitle className="flex items-center gap-3 text-xl">
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
<Layers className="h-5 w-5" />
</div>
{isEditing ? 'Edit Project Details' : 'Create New Project'}
</DialogTitle>
<DialogDescription className="text-sm">
{isEditing ? 'Update the technical specifications for your road infrastructure project.' : 'Provide the essential road data to establish a new analysis project.'}
</DialogDescription>
</DialogHeader>
State{' '}
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label>
<Input
id="state"
value={state}
onChange={(e) => setState(e.target.value)}
placeholder="e.g. Maharashtra"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
<div className="space-y-2">
<Label
htmlFor="corridor"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2"
>
<Route className="h-3.5 w-3.5 opacity-60" />
Corridor Name{' '}
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label>
<Input
id="corridor"
value={corridorName}
onChange={(e) => setCorridorName(e.target.value)}
placeholder="e.g. Mumbai-Goa Highway"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
</div>
{/* GPS Coordinates Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-2">
{/* Start Point */}
<div className="space-y-4">
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
<MapPin className="h-3.5 w-3.5 opacity-60" /> START POINT
</p>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label
htmlFor="start-lat"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
>
Lat
</Label>
<Input
id="start-lat"
type="number"
step="any"
value={startLat}
onChange={(e) => setStartLat(e.target.value)}
placeholder="0.0000"
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
/>
</div>
<div className="space-y-2">
<Label
htmlFor="start-lng"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
>
Lng
</Label>
<Input
id="start-lng"
type="number"
step="any"
value={startLng}
onChange={(e) => setStartLng(e.target.value)}
placeholder="0.0000"
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
/>
</div>
</div>
</div>
{/* End Point */}
<div className="space-y-4">
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
<MapPin className="h-3.5 w-3.5 opacity-60" /> END POINT
</p>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label
htmlFor="end-lat"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
>
Lat
</Label>
<Input
id="end-lat"
type="number"
step="any"
value={endLat}
onChange={(e) => setEndLat(e.target.value)}
placeholder="0.0000"
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
/>
</div>
<div className="space-y-2">
<Label
htmlFor="end-lng"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
>
Lng
</Label>
<Input
id="end-lng"
type="number"
step="any"
value={endLng}
onChange={(e) => setEndLng(e.target.value)}
placeholder="0.0000"
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
/>
</div>
</div>
</div>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
{/* Project Name */}
<div className="space-y-2">
<Label htmlFor="name" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">
Project Name <span className="text-destructive">*</span>
</Label>
<Input
id="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Enter a descriptive project name..."
className="h-11 bg-muted/20 border-border/60"
required
/>
</div>
{/* State & Corridor Row */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5">
<div className="space-y-2">
<Label htmlFor="state" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">
State <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label>
<Input
id="state"
value={state}
onChange={(e) => setState(e.target.value)}
placeholder="e.g. Maharashtra"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
<div className="space-y-2">
<Label htmlFor="corridor" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2">
<Route className="h-3.5 w-3.5 opacity-60" />
Corridor Name <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label>
<Input
id="corridor"
value={corridorName}
onChange={(e) => setCorridorName(e.target.value)}
placeholder="e.g. Mumbai-Goa Highway"
className="h-11 bg-muted/20 border-border/60"
/>
</div>
</div>
{/* GPS Coordinates Grid */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-8 pt-2">
{/* Start Point */}
<div className="space-y-4">
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
<MapPin className="h-3.5 w-3.5 opacity-60" /> START POINT
</p>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="start-lat" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70">Lat</Label>
<Input
id="start-lat"
type="number"
step="any"
value={startLat}
onChange={(e) => setStartLat(e.target.value)}
placeholder="0.0000"
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
/>
</div>
<div className="space-y-2">
<Label htmlFor="start-lng" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70">Lng</Label>
<Input
id="start-lng"
type="number"
step="any"
value={startLng}
onChange={(e) => setStartLng(e.target.value)}
placeholder="0.0000"
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
/>
</div>
</div>
</div>
{/* End Point */}
<div className="space-y-4">
<p className="text-[11px] font-black text-muted-foreground tracking-widest flex items-center gap-2">
<MapPin className="h-3.5 w-3.5 opacity-60" /> END POINT
</p>
<div className="grid grid-cols-2 gap-4">
<div className="space-y-2">
<Label htmlFor="end-lat" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70">Lat</Label>
<Input
id="end-lat"
type="number"
step="any"
value={endLat}
onChange={(e) => setEndLat(e.target.value)}
placeholder="0.0000"
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
/>
</div>
<div className="space-y-2">
<Label htmlFor="end-lng" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70">Lng</Label>
<Input
id="end-lng"
type="number"
step="any"
value={endLng}
onChange={(e) => setEndLng(e.target.value)}
placeholder="0.0000"
className="h-10 bg-muted/10 border-border/40 text-xs font-mono"
/>
</div>
</div>
</div>
</div>
{/* Submit Button */}
<div className="flex gap-4 pt-2">
<Button
type="button"
variant="outline"
onClick={() => {
setIsModalOpen(false)
resetForm()
}}
disabled={isSubmitting}
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs border-border/80 hover:bg-muted/50"
>
Cancel
</Button>
<Button
type="submit"
disabled={isSubmitting || !name.trim()}
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs shadow-lg shadow-primary/20"
>
{isSubmitting ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>{isEditing ? 'Updating...' : 'Creating...'}</span>
</div>
) : (
<div className="flex items-center gap-2">
{isEditing ? <CheckCircle2 className="h-4 w-4" /> : <Layers className="h-4 w-4" />}
<span>{isEditing ? 'Update Project' : 'Create Project'}</span>
</div>
)}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</>
)
{/* Submit Button */}
<div className="flex gap-4 pt-2">
<Button
type="button"
variant="outline"
onClick={() => {
setIsModalOpen(false);
resetForm();
}}
disabled={isSubmitting}
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs border-border/80 hover:bg-muted/50"
>
Cancel
</Button>
<Button
type="submit"
disabled={isSubmitting || !name.trim()}
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs shadow-lg shadow-primary/20"
>
{isSubmitting ? (
<div className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
<span>{isEditing ? 'Updating...' : 'Creating...'}</span>
</div>
) : (
<div className="flex items-center gap-2">
{isEditing ? (
<CheckCircle2 className="h-4 w-4" />
) : (
<Layers className="h-4 w-4" />
)}
<span>{isEditing ? 'Update Project' : 'Create Project'}</span>
</div>
)}
</Button>
</div>
</form>
</DialogContent>
</Dialog>
</>
);
}

View File

@@ -1,163 +1,175 @@
"use client"
'use client';
import { useState, useEffect } from "react"
import { useRouter, useParams } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Loader2, TrendingUp } from "lucide-react"
import VideoPlayerSection from "@/components/video-player-section"
import { PageHeader } from "@/components/page-header"
import { PoweredBy } from "@/components/powered-by"
import { sessionService, videoService } from "@/services/api"
import { SessionContext, DetectionData, DetectionType } from "@/types"
import { getVideoFile, clearVideoFile } from "@/lib/video-storage"
import { ROUTES } from "@/utils/routes"
import { Card } from "@/components/ui/card"
import { useState, useEffect } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Loader2, TrendingUp } from 'lucide-react';
import VideoPlayerSection from '@/components/video-player-section';
import { PageHeader } from '@/components/page-header';
import { PoweredBy } from '@/components/powered-by';
import { sessionService, videoService } from '@/services/api';
import { SessionContext, DetectionData, DetectionType } from '@/types';
import { getVideoFile, clearVideoFile } from '@/lib/video-storage';
import { ROUTES } from '@/utils/routes';
import { Card } from '@/components/ui/card';
const API_URL = process.env.NEXT_PUBLIC_API_URL
const API_URL = process.env.NEXT_PUBLIC_API_URL;
export default function VideoResultsPage() {
const router = useRouter()
const { videoId } = useParams() as { videoId: string }
const [session, setSession] = useState<SessionContext | null>(null)
const [detectionData, setDetectionData] = useState<DetectionData | null>(null)
const [detectionType, setDetectionType] = useState<DetectionType>("pothole-detection")
const [videoFile, setVideoFile] = useState<File | null>(null)
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const router = useRouter();
const { videoId } = useParams() as { videoId: string };
const [session, setSession] = useState<SessionContext | null>(null);
const [detectionData, setDetectionData] = useState<DetectionData | null>(null);
const [detectionType, setDetectionType] = useState<DetectionType>('pothole-detection');
const [videoFile, setVideoFile] = useState<File | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const storedSession = sessionService.loadSession()
setSession(storedSession)
useEffect(() => {
const storedSession = sessionService.loadSession();
setSession(storedSession);
const fetchResults = async () => {
try {
// Fetch detection data from backend
const data = await videoService.getVideoResults(videoId);
setDetectionData(data as any)
const fetchResults = async () => {
try {
// Fetch detection data from backend
const data = await videoService.getVideoResults(videoId);
setDetectionData(data as any);
// Try to infer detection type from results if possible
if (data.summary?.unique_signboards !== undefined && data.summary?.unique_signboards > 0) {
setDetectionType("sign-board-detection")
} else if (data.summary?.unique_potholes !== undefined && data.summary?.unique_potholes > 0) {
setDetectionType("pothole-detection")
}
// Retrieve video file from IndexedDB
const storedVideoFile = await getVideoFile(videoId)
if (storedVideoFile) {
setVideoFile(storedVideoFile)
}
} catch (err) {
setError(err instanceof Error ? err.message : "Failed to load results")
} finally {
setIsLoading(false)
}
// Try to infer detection type from results if possible
if (data.summary?.unique_signboards !== undefined && data.summary?.unique_signboards > 0) {
setDetectionType('sign-board-detection');
} else if (
data.summary?.unique_potholes !== undefined &&
data.summary?.unique_potholes > 0
) {
setDetectionType('pothole-detection');
}
if (videoId) {
fetchResults()
// Retrieve video file from IndexedDB
const storedVideoFile = await getVideoFile(videoId);
if (storedVideoFile) {
setVideoFile(storedVideoFile);
}
}, [videoId])
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load results');
} finally {
setIsLoading(false);
}
};
const handleNewAnalysis = async () => {
if (videoId) {
try {
await clearVideoFile(videoId)
} catch (err) {
console.error("Failed to clear video file:", err)
}
}
sessionService.clearSession()
router.push(ROUTES.NEW_ANALYSIS)
if (videoId) {
fetchResults();
}
}, [videoId]);
const getTitle = () => {
if (detectionType === "pothole-detection") return "Pothole Detection Results"
if (detectionType === "sign-board-detection") return "Signboard Detection Results"
return "Pothole & Signboard Detection Results"
const handleNewAnalysis = async () => {
if (videoId) {
try {
await clearVideoFile(videoId);
} catch (err) {
console.error('Failed to clear video file:', err);
}
}
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
};
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-4 p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Loading detection results...</p>
</Card>
</div>
)
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-6 p-8 text-center max-w-md">
<p className="text-destructive font-medium">{error}</p>
<div className="flex gap-4">
<Button onClick={() => router.push(ROUTES.UPLOAD)} variant="outline">Back to Upload</Button>
<Button onClick={handleNewAnalysis}>New Analysis</Button>
</div>
</Card>
</div>
)
}
const getTitle = () => {
if (detectionType === 'pothole-detection') return 'Pothole Detection Results';
if (detectionType === 'sign-board-detection') return 'Signboard Detection Results';
return 'Pothole & Signboard Detection Results';
};
if (isLoading) {
return (
<div className="min-h-screen">
<main className="min-h-screen">
<div className="container mx-auto px-6 py-10 max-w-[1600px]">
<div className="mb-8">
<PageHeader
title={getTitle()}
description={`Video ID: ${videoId}`}
icon={TrendingUp}
/>
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-4 p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Loading detection results...</p>
</Card>
</div>
);
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-6 p-8 text-center max-w-md">
<p className="text-destructive font-medium">{error}</p>
<div className="flex gap-4">
<Button onClick={() => router.push(ROUTES.UPLOAD)} variant="outline">
Back to Upload
</Button>
<Button onClick={handleNewAnalysis}>New Analysis</Button>
</div>
</Card>
</div>
);
}
return (
<div className="min-h-screen">
<main className="min-h-screen">
<div className="container mx-auto px-6 py-10 max-w-[1600px]">
<div className="mb-8">
<PageHeader title={getTitle()} description={`Video ID: ${videoId}`} icon={TrendingUp} />
</div>
{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">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
{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">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Project</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Chainage</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName}
</span>
</div>
</div>
<Button onClick={handleNewAnalysis} variant="outline" size="sm" className="font-semibold px-6 shrink-0 h-9">
Start New Analysis
</Button>
</div>
</Card>
</div>
)}
{detectionData && (
<VideoPlayerSection
data={detectionData}
videoId={videoId}
videoFile={videoFile}
detectionType={detectionType}
projectId={session?.projectId || undefined}
/>
)}
<PoweredBy />
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Chainage
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName}
</span>
</div>
</div>
<Button
onClick={handleNewAnalysis}
variant="outline"
size="sm"
className="font-semibold px-6 shrink-0 h-9"
>
Start New Analysis
</Button>
</div>
</main>
</Card>
</div>
)}
{detectionData && (
<VideoPlayerSection
data={detectionData}
videoId={videoId}
videoFile={videoFile}
detectionType={detectionType}
projectId={session?.projectId || undefined}
/>
)}
<PoweredBy />
</div>
)
</main>
</div>
);
}

View File

@@ -1,144 +1,155 @@
"use client"
'use client';
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Button } from "@/components/ui/button"
import { Loader2, TrendingUp } from "lucide-react"
import VideoPlayerSection from "@/components/video-player-section"
import { PageHeader } from "@/components/page-header"
import { PoweredBy } from "@/components/powered-by"
import { sessionService } from "@/services/api"
import { SessionContext, DetectionData, DetectionType } from "@/types"
import { clearVideoFile } from "@/lib/video-storage"
import { ROUTES } from "@/utils/routes"
import { Card } from "@/components/ui/card"
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Button } from '@/components/ui/button';
import { Loader2, TrendingUp } from 'lucide-react';
import VideoPlayerSection from '@/components/video-player-section';
import { PageHeader } from '@/components/page-header';
import { PoweredBy } from '@/components/powered-by';
import { sessionService } from '@/services/api';
import { SessionContext, DetectionData, DetectionType } from '@/types';
import { clearVideoFile } from '@/lib/video-storage';
import { ROUTES } from '@/utils/routes';
import { Card } from '@/components/ui/card';
export default function ResultsPage() {
const router = useRouter()
const [session, setSession] = useState<SessionContext | null>(null)
const [detectionData] = useState<DetectionData | null>(null)
const [detectionType] = useState<DetectionType>("pothole-detection")
const [videoId] = useState<string | null>(null)
const [videoFile] = useState<File | null>(null)
const [isLoading] = useState(true)
const [error] = useState<string | null>(null)
const router = useRouter();
const [session, setSession] = useState<SessionContext | null>(null);
const [detectionData] = useState<DetectionData | null>(null);
const [detectionType] = useState<DetectionType>('pothole-detection');
const [videoId] = useState<string | null>(null);
const [videoFile] = useState<File | null>(null);
const [isLoading] = useState(true);
const [error] = useState<string | null>(null);
// Load session and video data on mount
useEffect(() => {
const storedSession = sessionService.loadSession()
const videoData = sessionService.loadVideoData()
// Load session and video data on mount
useEffect(() => {
const storedSession = sessionService.loadSession();
const videoData = sessionService.loadVideoData();
if (!sessionService.isSessionValid(storedSession) || !videoData) {
router.replace(ROUTES.NEW_ANALYSIS)
return
}
// If we have a videoId, redirect to the dynamic results page
if (videoData.videoId) {
router.replace(`${ROUTES.RESULTS}/${videoData.videoId}`)
return
}
setSession(storedSession)
}, [router])
const handleNewAnalysis = async () => {
// Clear video from IndexedDB
if (videoId) {
try {
await clearVideoFile(videoId)
} catch (err) {
console.error("Failed to clear video file:", err)
}
}
sessionService.clearSession()
router.push(ROUTES.NEW_ANALYSIS)
if (!sessionService.isSessionValid(storedSession) || !videoData) {
router.replace(ROUTES.NEW_ANALYSIS);
return;
}
const getTitle = () => {
if (detectionType === "pothole-detection") return "Pothole Detection Results"
if (detectionType === "sign-board-detection") return "Signboard Detection Results"
return "Pothole & Signboard Detection Results"
// If we have a videoId, redirect to the dynamic results page
if (videoData.videoId) {
router.replace(`${ROUTES.RESULTS}/${videoData.videoId}`);
return;
}
if (isLoading) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-4 p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Loading results...</p>
</Card>
</div>
)
}
setSession(storedSession);
}, [router]);
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-6 p-8 text-center max-w-md">
<p className="text-destructive font-medium">{error}</p>
<Button onClick={handleNewAnalysis}>Start New Analysis</Button>
</Card>
</div>
)
const handleNewAnalysis = async () => {
// Clear video from IndexedDB
if (videoId) {
try {
await clearVideoFile(videoId);
} catch (err) {
console.error('Failed to clear video file:', err);
}
}
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
};
const getTitle = () => {
if (detectionType === 'pothole-detection') return 'Pothole Detection Results';
if (detectionType === 'sign-board-detection') return 'Signboard Detection Results';
return 'Pothole & Signboard Detection Results';
};
if (isLoading) {
return (
<div className="min-h-screen">
<main className="min-h-screen">
<div className="container mx-auto px-6 py-10 max-w-[1600px]">
<div className="mb-8">
<PageHeader
title={getTitle()}
description="View your AI-powered road analysis results"
icon={TrendingUp}
/>
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-4 p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground">Loading results...</p>
</Card>
</div>
);
}
if (error) {
return (
<div className="min-h-screen flex items-center justify-center">
<Card className="flex flex-col items-center gap-6 p-8 text-center max-w-md">
<p className="text-destructive font-medium">{error}</p>
<Button onClick={handleNewAnalysis}>Start New Analysis</Button>
</Card>
</div>
);
}
return (
<div className="min-h-screen">
<main className="min-h-screen">
<div className="container mx-auto px-6 py-10 max-w-[1600px]">
<div className="mb-8">
<PageHeader
title={getTitle()}
description="View your AI-powered road analysis results"
icon={TrendingUp}
/>
</div>
{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">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
{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">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Project</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Chainage</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName}
</span>
</div>
</div>
<Button onClick={handleNewAnalysis} variant="outline" size="sm" className="font-semibold px-6 shrink-0 h-9">
Start New Analysis
</Button>
</div>
</Card>
</div>
)}
{detectionData && videoId && (
<VideoPlayerSection
data={detectionData}
videoId={videoId}
videoFile={videoFile}
detectionType={detectionType}
projectId={session?.projectId || undefined}
/>
)}
<PoweredBy />
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Chainage
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName}
</span>
</div>
</div>
<Button
onClick={handleNewAnalysis}
variant="outline"
size="sm"
className="font-semibold px-6 shrink-0 h-9"
>
Start New Analysis
</Button>
</div>
</main>
</Card>
</div>
)}
{detectionData && videoId && (
<VideoPlayerSection
data={detectionData}
videoId={videoId}
videoFile={videoFile}
detectionType={detectionType}
projectId={session?.projectId || undefined}
/>
)}
<PoweredBy />
</div>
)
</main>
</div>
);
}

View File

@@ -1,7 +1,7 @@
"use client";
'use client';
import { motion } from "motion/react";
import React from "react";
import { motion } from 'motion/react';
import React from 'react';
export default function Template({ children }: { children: React.ReactNode }) {
return (

View File

@@ -1,208 +1,210 @@
"use client"
'use client';
import { useState, useEffect, useCallback } from "react"
import { useRouter, useParams } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Loader2, TrendingUp } 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 { Button } from "@/components/ui/button"
import { useState, useEffect, useCallback } from 'react';
import { useRouter, useParams } from 'next/navigation';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, TrendingUp } 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 { Button } from '@/components/ui/button';
const API_URL = process.env.NEXT_PUBLIC_API_URL
const WS_URL = API_URL?.replace(/^https:\/\//, "wss://").replace(/^http:\/\//, "ws://")
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const WS_URL = API_URL?.replace(/^https:\/\//, 'wss://').replace(/^http:\/\//, 'ws://');
export default function VideoProcessingPage() {
const router = useRouter()
const { videoId } = useParams() as { videoId: string }
const [session, setSession] = useState<SessionContext | null>(null)
const [isLoading, setIsLoading] = useState(true)
const router = useRouter();
const { videoId } = useParams() as { videoId: string };
const [session, setSession] = useState<SessionContext | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Processing states
const [progress, setProgress] = useState(0)
const [statusMessage, setStatusMessage] = useState("Initializing...")
const [error, setError] = useState<string | null>(null)
// Processing states
const [progress, setProgress] = useState(0);
const [statusMessage, setStatusMessage] = useState('Initializing...');
const [error, setError] = useState<string | null>(null);
const connectWebSocket = useCallback((vid: string) => {
const ws = new WebSocket(`${WS_URL}/ws/${vid}`)
const connectWebSocket = useCallback(
(vid: string) => {
const ws = new WebSocket(`${WS_URL}/ws/${vid}`);
ws.onmessage = async (event) => {
const data = JSON.parse(event.data)
ws.onmessage = async (event) => {
const data = JSON.parse(event.data);
if (data.type === "progress" || data.progress !== undefined) {
setProgress(data.progress || 0)
let message = data.message || "Processing..."
if (data.unique_potholes !== undefined) {
message += ` | Unique: ${data.unique_potholes} | Total: ${data.total_detections || 0}`
} else if (data.unique_signboards !== undefined) {
message += ` | Unique: ${data.unique_signboards} | Total: ${data.total_detections || 0}`
}
setStatusMessage(message)
}
if (data.type === "complete" || data.status === "completed") {
setStatusMessage("Processing completed! Finalizing...")
ws.close()
// Navigate to results
setTimeout(() => router.push(`/results/${vid}`), 1000)
}
if (data.type === "error") {
setError("Error: " + data.message)
setStatusMessage("")
ws.close()
}
if (data.type === 'progress' || data.progress !== undefined) {
setProgress(data.progress || 0);
let message = data.message || 'Processing...';
if (data.unique_potholes !== undefined) {
message += ` | Unique: ${data.unique_potholes} | Total: ${data.total_detections || 0}`;
} else if (data.unique_signboards !== undefined) {
message += ` | Unique: ${data.unique_signboards} | Total: ${data.total_detections || 0}`;
}
setStatusMessage(message);
}
ws.onerror = () => {
setStatusMessage("Connection lost. Reconnecting...")
setTimeout(() => connectWebSocket(vid), 3000)
if (data.type === 'complete' || data.status === 'completed') {
setStatusMessage('Processing completed! Finalizing...');
ws.close();
// Navigate to results
setTimeout(() => router.push(`/results/${vid}`), 1000);
}
return ws
}, [router])
if (data.type === 'error') {
setError('Error: ' + data.message);
setStatusMessage('');
ws.close();
}
};
useEffect(() => {
const storedSession = sessionService.loadSession()
setSession(storedSession)
ws.onerror = () => {
setStatusMessage('Connection lost. Reconnecting...');
setTimeout(() => connectWebSocket(vid), 3000);
};
const checkStatus = async () => {
try {
const statusData = await videoService.getVideoStatus(videoId);
return ws;
},
[router],
);
if (statusData.status === "completed") {
router.replace(`/results/${videoId}`)
return
}
useEffect(() => {
const storedSession = sessionService.loadSession();
setSession(storedSession);
if (statusData.status === "error") {
setError(statusData.message || "An error occurred during processing.")
setIsLoading(false)
return
}
const checkStatus = async () => {
try {
const statusData = await videoService.getVideoStatus(videoId);
// If processing, start WebSocket
setProgress(statusData.progress || 0)
setStatusMessage(statusData.message || "Resuming processing...")
connectWebSocket(videoId)
setIsLoading(false)
} catch (err) {
console.error("Status check failed:", err)
setError("Failed to connect to server.")
setIsLoading(false)
}
if (statusData.status === 'completed') {
router.replace(`/results/${videoId}`);
return;
}
if (videoId) {
checkStatus()
if (statusData.status === 'error') {
setError(statusData.message || 'An error occurred during processing.');
setIsLoading(false);
return;
}
}, [videoId, router, connectWebSocket])
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>
</div>
)
// If processing, start WebSocket
setProgress(statusData.progress || 0);
setStatusMessage(statusData.message || 'Resuming processing...');
connectWebSocket(videoId);
setIsLoading(false);
} catch (err) {
console.error('Status check failed:', err);
setError('Failed to connect to server.');
setIsLoading(false);
}
};
if (videoId) {
checkStatus();
}
}, [videoId, router, connectWebSocket]);
if (isLoading) {
return (
<div className="min-h-screen">
<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">
<div className="mb-6">
<PageHeader
title="Processing Analysis"
description={`Real-time analysis progress for video ID: ${videoId}`}
icon={TrendingUp}
/>
<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>
</div>
);
}
return (
<div className="min-h-screen">
<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">
<div className="mb-6">
<PageHeader
title="Processing Analysis"
description={`Real-time analysis progress for video ID: ${videoId}`}
icon={TrendingUp}
/>
</div>
{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 py-4 px-6 gap-6 bg-card">
<div className="flex flex-wrap items-center gap-x-12 gap-y-4 flex-1">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
{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 py-4 px-6 gap-6 bg-card">
<div className="flex flex-wrap items-center gap-x-12 gap-y-4 flex-1">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Project</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Chainage</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName}
</span>
</div>
</div>
</div>
</Card>
</div>
)}
<Card className="flex-1 flex flex-col items-center justify-center py-12 px-8 min-h-[450px]">
<div className="flex flex-col items-center justify-center w-full max-w-2xl space-y-10">
<div className="text-center space-y-4">
<h2 className="text-3xl font-bold tracking-tight">
Processing Analysis
</h2>
<p className="text-sm font-mono text-muted-foreground tracking-widest">
ID: {videoId}
</p>
</div>
<div className="w-full space-y-4">
<div className="flex items-center justify-between text-sm">
<span className="font-bold text-muted-foreground text-xs uppercase tracking-widest">Progress</span>
<span className="font-bold text-primary text-lg">{progress}%</span>
</div>
<div className="h-4 rounded-full bg-secondary overflow-hidden border">
<div
className="h-full bg-primary transition-all duration-1000 ease-in-out"
style={{ width: `${progress}%` }}
/>
</div>
<div className="text-center pt-2">
<div className="inline-flex items-center gap-3 px-4 py-2 rounded-full border bg-secondary/30">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
<p className="text-sm font-semibold">
{statusMessage}
</p>
</div>
</div>
</div>
{error && (
<div className="w-full p-6 rounded-md bg-destructive/10 border border-destructive/20 text-center space-y-3">
<p className="text-destructive font-medium">{error}</p>
<Button
variant="outline"
size="sm"
onClick={() => window.location.reload()}
>
Retry Connection
</Button>
</div>
)}
</div>
</Card>
<PoweredBy />
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Chainage
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName}
</span>
</div>
</div>
</div>
</main>
</Card>
</div>
)}
<Card className="flex-1 flex flex-col items-center justify-center py-12 px-8 min-h-[450px]">
<div className="flex flex-col items-center justify-center w-full max-w-2xl space-y-10">
<div className="text-center space-y-4">
<h2 className="text-3xl font-bold tracking-tight">Processing Analysis</h2>
<p className="text-sm font-mono text-muted-foreground tracking-widest">
ID: {videoId}
</p>
</div>
<div className="w-full space-y-4">
<div className="flex items-center justify-between text-sm">
<span className="font-bold text-muted-foreground text-xs uppercase tracking-widest">
Progress
</span>
<span className="font-bold text-primary text-lg">{progress}%</span>
</div>
<div className="h-4 rounded-full bg-secondary overflow-hidden border">
<div
className="h-full bg-primary transition-all duration-1000 ease-in-out"
style={{ width: `${progress}%` }}
/>
</div>
<div className="text-center pt-2">
<div className="inline-flex items-center gap-3 px-4 py-2 rounded-full border bg-secondary/30">
<Loader2 className="h-4 w-4 animate-spin text-primary" />
<p className="text-sm font-semibold">{statusMessage}</p>
</div>
</div>
</div>
{error && (
<div className="w-full p-6 rounded-md bg-destructive/10 border border-destructive/20 text-center space-y-3">
<p className="text-destructive font-medium">{error}</p>
<Button variant="outline" size="sm" onClick={() => window.location.reload()}>
Retry Connection
</Button>
</div>
)}
</div>
</Card>
<PoweredBy />
</div>
)
</main>
</div>
);
}

View File

@@ -1,336 +1,341 @@
"use client"
'use client';
import { useState, useEffect } from "react"
import { useRouter } from "next/navigation"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Loader2, TrendingUp } 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 { cn } from "@/lib/utils"
import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Loader2, TrendingUp } 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 { cn } from '@/lib/utils';
const API_URL = process.env.NEXT_PUBLIC_API_URL
const API_URL = process.env.NEXT_PUBLIC_API_URL;
const DETECTION_TYPES = [
{ value: "pothole-detection", label: "Pothole Detection" },
{ value: "sign-board-detection", label: "Signboard Detection" },
{ value: "pot-sign-detection", label: "Pothole & Signboard Detection" },
] as const
{ value: 'pothole-detection', label: 'Pothole Detection' },
{ value: 'sign-board-detection', label: 'Signboard Detection' },
{ value: 'pot-sign-detection', label: 'Pothole & Signboard Detection' },
] as const;
const DETECTION_METHODS = [
{ value: "yolo", label: "YOLO Detection Model" },
{ value: "yolo_vl", label: "YOLO with Vision-Language Model" },
{ value: "sam3", label: "OpenAI SAM 3 Segmentation Model" },
{ value: "yoloe", label: "YOLOE Open-Vocabulary Detection" },
{ value: "yoloe_trained_vl", label: "YOLOE With Vision Language Model" },
] as const
{ value: 'yolo', label: 'YOLO Detection Model' },
{ value: 'yolo_vl', label: 'YOLO with Vision-Language Model' },
{ value: 'sam3', label: 'OpenAI SAM 3 Segmentation Model' },
{ value: 'yoloe', label: 'YOLOE Open-Vocabulary Detection' },
{ value: 'yoloe_trained_vl', label: 'YOLOE With Vision Language Model' },
] as const;
type DetectionType = "pothole-detection" | "sign-board-detection" | "pot-sign-detection"
type DetectionType = 'pothole-detection' | 'sign-board-detection' | 'pot-sign-detection';
export default function UploadPage() {
const router = useRouter()
const [session, setSession] = useState<SessionContext | null>(null)
const [isLoading, setIsLoading] = useState(true)
const router = useRouter();
const [session, setSession] = useState<SessionContext | null>(null);
const [isLoading, setIsLoading] = useState(true);
// Form states
const [file, setFile] = useState<File | null>(null)
const [jsonFile, setJsonFile] = useState<File | null>(null)
const [speed, setSpeed] = useState(30)
const [detectionType, setDetectionType] = useState<DetectionType>("pothole-detection")
const [selectMethod, setSelectMethod] = useState("yolo_vl")
// Form states
const [file, setFile] = useState<File | null>(null);
const [jsonFile, setJsonFile] = useState<File | null>(null);
const [speed, setSpeed] = useState(30);
const [detectionType, setDetectionType] = useState<DetectionType>('pothole-detection');
const [selectMethod, setSelectMethod] = useState('yolo_vl');
// Upload states
const [uploading, setUploading] = useState(false)
const [progress, setProgress] = useState(0)
const [statusMessage, setStatusMessage] = useState("")
const [error, setError] = useState<string | null>(null)
// 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)
setIsLoading(false)
}, [router])
// Load session on mount
useEffect(() => {
const storedSession = sessionService.loadSession();
if (!sessionService.isSessionValid(storedSession)) {
router.replace(ROUTES.NEW_ANALYSIS);
return;
}
setSession(storedSession);
setIsLoading(false);
}, [router]);
const handleUpload = async () => {
if (!file) {
setError("Please select a video file")
return
}
const handleUpload = async () => {
if (!file) {
setError('Please select a video file');
return;
}
const formData = new FormData()
formData.append("file", file)
formData.append("detection_type", detectionType)
formData.append("speed_kmh", speed.toString())
formData.append("detection_mode", selectMethod)
if (jsonFile) {
formData.append("json_file", jsonFile)
}
const formData = new FormData();
formData.append('file', file);
formData.append('detection_type', detectionType);
formData.append('speed_kmh', speed.toString());
formData.append('detection_mode', selectMethod);
if (jsonFile) {
formData.append('json_file', jsonFile);
}
setUploading(true)
setProgress(0)
setStatusMessage("Uploading...")
setError(null)
setUploading(true);
setProgress(0);
setStatusMessage('Uploading...');
setError(null);
try {
const result = await videoService.uploadVideo(formData);
// Store file locally for potential recovery/results display
if (file) {
try {
const result = await videoService.uploadVideo(formData);
// Store file locally for potential recovery/results display
if (file) {
try {
await storeVideoFile(result.video_id, file)
} catch (err) {
console.error("Failed to store video file:", err)
}
}
sessionService.saveVideoData({ videoId: result.video_id, detectionType })
// Redirect to the dynamic processing page
router.push(`/upload/${result.video_id}`)
await storeVideoFile(result.video_id, file);
} catch (err) {
let errorMessage = "Upload failed"
if (err instanceof TypeError && err.message === "Failed to fetch") {
errorMessage = "Cannot connect to server. Please check if backend is running."
} else if (err instanceof Error) {
errorMessage = err.message
}
setError(errorMessage)
setStatusMessage("")
setUploading(false)
setProgress(0)
console.error('Failed to store video file:', err);
}
}
}
const handleBackToSelection = () => {
sessionService.clearSession()
router.push(ROUTES.NEW_ANALYSIS)
}
sessionService.saveVideoData({ videoId: result.video_id, detectionType });
const getTitle = () => {
if (detectionType === "pothole-detection") return "Pothole Detection"
if (detectionType === "sign-board-detection") return "Signboard Detection"
return "Pothole & Signboard Detection"
// Redirect to the dynamic processing page
router.push(`/upload/${result.video_id}`);
} catch (err) {
let errorMessage = 'Upload failed';
if (err instanceof TypeError && err.message === 'Failed to fetch') {
errorMessage = 'Cannot connect to server. Please check if backend is running.';
} else if (err instanceof Error) {
errorMessage = err.message;
}
setError(errorMessage);
setStatusMessage('');
setUploading(false);
setProgress(0);
}
};
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>
</div>
)
}
const handleBackToSelection = () => {
sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS);
};
const getTitle = () => {
if (detectionType === 'pothole-detection') return 'Pothole Detection';
if (detectionType === 'sign-board-detection') return 'Signboard Detection';
return 'Pothole & Signboard Detection';
};
if (isLoading) {
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 className="min-h-screen flex items-center justify-center">
<Card className="p-8">
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</Card>
</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>
{/* 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">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
{/* 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">
<div className="flex flex-col">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Project</span>
<span className="text-base font-bold leading-tight">
{session.projectName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Chainage</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName}
</span>
</div>
</div>
<Button
variant="outline"
size="sm"
onClick={handleBackToSelection}
className="font-semibold px-6 shrink-0 h-9"
>
Change Selection
</Button>
</div>
</Card>
</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, detection type, vehicle speed, and method for analysis
</CardDescription>
</CardHeader>
<CardContent className="pt-4 space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-4">
{/* Video File Input */}
<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 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>
</div>
{/* Detection, Speed, and Method Row */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{/* Detection Type */}
<div className="space-y-2">
<Label htmlFor="detection-type" className="text-sm font-semibold">
Detection Type
</Label>
<Select
value={detectionType}
onValueChange={(v) => setDetectionType(v as DetectionType)}
disabled={uploading}
>
<SelectTrigger id="detection-type" className="h-11">
<SelectValue placeholder="Select detection type" />
</SelectTrigger>
<SelectContent>
{DETECTION_TYPES.map((type) => (
<SelectItem key={type.value} value={type.value}>
{type.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Speed Input */}
<div className="space-y-2">
<Label htmlFor="speed" className="text-sm font-semibold">
Vehicle Speed (km/h)
</Label>
<Input
id="speed"
type="number"
min={1}
max={200}
value={speed}
onChange={(e) => setSpeed(Number(e.target.value))}
disabled={uploading}
className="h-11"
/>
</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>
{/* 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="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName}
</span>
</div>
<div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Chainage
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName}
</span>
</div>
</div>
<Button
variant="outline"
size="sm"
onClick={handleBackToSelection}
className="font-semibold px-6 shrink-0 h-9"
>
Change Selection
</Button>
</div>
</main>
</Card>
</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, detection type, vehicle speed, and method for analysis
</CardDescription>
</CardHeader>
<CardContent className="pt-4 space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-4">
{/* Video File Input */}
<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 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>
</div>
{/* Detection, Speed, and Method Row */}
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
{/* Detection Type */}
<div className="space-y-2">
<Label htmlFor="detection-type" className="text-sm font-semibold">
Detection Type
</Label>
<Select
value={detectionType}
onValueChange={(v) => setDetectionType(v as DetectionType)}
disabled={uploading}
>
<SelectTrigger id="detection-type" className="h-11">
<SelectValue placeholder="Select detection type" />
</SelectTrigger>
<SelectContent>
{DETECTION_TYPES.map((type) => (
<SelectItem key={type.value} value={type.value}>
{type.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Speed Input */}
<div className="space-y-2">
<Label htmlFor="speed" className="text-sm font-semibold">
Vehicle Speed (km/h)
</Label>
<Input
id="speed"
type="number"
min={1}
max={200}
value={speed}
onChange={(e) => setSpeed(Number(e.target.value))}
disabled={uploading}
className="h-11"
/>
</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>
{/* 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>
)
</main>
</div>
);
}

View File

@@ -1,5 +1,5 @@
@import "tailwindcss";
@import "tw-animate-css";
@import 'tailwindcss';
@import 'tw-animate-css';
@custom-variant dark (&:is(.dark *));
@@ -72,10 +72,9 @@
--sidebar-ring: oklch(0.38 0.189 293.745);
}
@theme inline {
--font-sans: "Geist", "Geist Fallback", system-ui, sans-serif;
--font-mono: "Geist Mono", "Geist Mono Fallback", monospace;
--font-sans: 'Geist', 'Geist Fallback', system-ui, sans-serif;
--font-mono: 'Geist Mono', 'Geist Mono Fallback', monospace;
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
@@ -148,4 +147,3 @@
scrollbar-color: var(--muted-foreground) transparent;
}
}

View File

@@ -1,23 +1,23 @@
import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google";
import "./globals.css";
import { ThemeProvider } from "@/components/theme-provider";
import { Toaster } from "@/components/ui/sonner"
import { BackgroundGradient } from "@/components/background-gradient";
import type { Metadata } from 'next';
import { Geist, Geist_Mono } from 'next/font/google';
import './globals.css';
import { ThemeProvider } from '@/components/theme-provider';
import { Toaster } from '@/components/ui/sonner';
import { BackgroundGradient } from '@/components/background-gradient';
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
variable: '--font-geist-sans',
subsets: ['latin'],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
variable: '--font-geist-mono',
subsets: ['latin'],
});
export const metadata: Metadata = {
title: "Create Next App",
description: "Generated by create next app",
title: 'Create Next App',
description: 'Generated by create next app',
};
export default function RootLayout({
@@ -27,9 +27,7 @@ export default function RootLayout({
}>) {
return (
<html lang="en" suppressHydrationWarning>
<body
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
>
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<ThemeProvider
attribute="class"
defaultTheme="system"
@@ -40,7 +38,7 @@ export default function RootLayout({
<BackgroundGradient />
{children}
</div>
<Toaster position="top-center" />
<Toaster position="top-center" />
</ThemeProvider>
</body>
</html>

View File

@@ -1,7 +1,7 @@
"use client";
'use client';
import React from "react";
import { usePathname } from "next/navigation";
import React from 'react';
import { usePathname } from 'next/navigation';
import {
Breadcrumb,
BreadcrumbItem,
@@ -9,18 +9,18 @@ import {
BreadcrumbList,
BreadcrumbPage,
BreadcrumbSeparator,
} from "@/components/ui/breadcrumb";
} from '@/components/ui/breadcrumb';
export function BreadcrumbBasic() {
const pathname = usePathname();
const segments = pathname.split("/").filter((segment) => segment !== "");
const segments = pathname.split('/').filter((segment) => segment !== '');
// Helper to format segment (e.g., "new-analysis" -> "New Analysis")
const formatSegment = (segment: string) => {
return segment
.split("-")
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" ");
.join(' ');
};
return (
@@ -32,7 +32,7 @@ export function BreadcrumbBasic() {
{segments.length > 0 && <BreadcrumbSeparator />}
{segments.map((segment, index) => {
const href = `/${segments.slice(0, index + 1).join("/")}`;
const href = `/${segments.slice(0, index + 1).join('/')}`;
const isLast = index === segments.length - 1;
// Skip segments that represent module groups or generic IDs if needed

View File

@@ -1,8 +1,11 @@
import React from 'react'
import React from 'react';
export function BackgroundGradient() {
return (
<div className="fixed inset-0 -z-10 h-full w-full overflow-hidden pointer-events-none" aria-hidden="true">
<div
className="fixed inset-0 -z-10 h-full w-full overflow-hidden pointer-events-none"
aria-hidden="true"
>
{/* Top Gradient */}
<div className="absolute inset-x-0 top-0 transform-gpu overflow-hidden blur-3xl">
<div
@@ -25,7 +28,7 @@ export function BackgroundGradient() {
/>
</div>
</div>
)
);
}
export function BackgroundGradientBottom() {

View File

@@ -1,48 +1,48 @@
"use client"
'use client';
import * as React from "react"
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from "recharts"
import { Loader2 } from "lucide-react"
import * as React from 'react';
import { Bar, BarChart, CartesianGrid, XAxis, YAxis } from 'recharts';
import { Loader2 } from 'lucide-react';
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig,
} from "@/components/ui/chart"
} from '@/components/ui/chart';
interface ChainageData {
name: string
defected_sign_board: number
pothole: number
road_crack: number
damaged_road_marking: number
total: number
name: string;
defected_sign_board: number;
pothole: number;
road_crack: number;
damaged_road_marking: number;
total: number;
}
interface ChainageBarChartProps {
data: ChainageData[]
isLoading?: boolean
data: ChainageData[];
isLoading?: boolean;
}
const chartConfig = {
pothole: {
label: "Potholes",
color: "var(--chart-1)",
label: 'Potholes',
color: 'var(--chart-1)',
},
defected_sign_board: {
label: "Defected Signboards",
color: "var(--chart-2)",
label: 'Defected Signboards',
color: 'var(--chart-2)',
},
road_crack: {
label: "Road Cracks",
color: "var(--chart-3)",
label: 'Road Cracks',
color: 'var(--chart-3)',
},
damaged_road_marking: {
label: "Damaged Markings",
color: "var(--chart-4)",
label: 'Damaged Markings',
color: 'var(--chart-4)',
},
} satisfies ChartConfig
} satisfies ChartConfig;
export function ChainageBarChart({ data, isLoading = false }: ChainageBarChartProps) {
if (isLoading) {
@@ -50,7 +50,7 @@ export function ChainageBarChart({ data, isLoading = false }: ChainageBarChartPr
<div className="h-[250px] flex items-center justify-center">
<Loader2 className="h-8 w-8 text-primary/50 animate-spin" />
</div>
)
);
}
if (data.length === 0) {
@@ -59,17 +59,17 @@ export function ChainageBarChart({ data, isLoading = false }: ChainageBarChartPr
<p className="text-sm">No chainage data available</p>
<p className="text-xs mt-1">Process videos to see detections by chainage</p>
</div>
)
);
}
// Filter out good signboards for a more "damage-focused" standard chart as per multiple bar example
const chartData = data.map(item => ({
const chartData = data.map((item) => ({
name: item.name,
pothole: item.pothole,
defected_sign_board: item.defected_sign_board,
road_crack: item.road_crack,
damaged_road_marking: item.damaged_road_marking,
}))
}));
return (
<div className="h-[250px] w-full">
@@ -81,19 +81,11 @@ export function ChainageBarChart({ data, isLoading = false }: ChainageBarChartPr
tickLine={false}
tickMargin={10}
axisLine={false}
tickFormatter={(value) => value.length > 8 ? `${value.slice(0, 8)}...` : value}
tickFormatter={(value) => (value.length > 8 ? `${value.slice(0, 8)}...` : value)}
fontSize={12}
/>
<YAxis
tickLine={false}
axisLine={false}
fontSize={12}
tickMargin={10}
/>
<ChartTooltip
cursor={false}
content={<ChartTooltipContent indicator="dashed" />}
/>
<YAxis tickLine={false} axisLine={false} fontSize={12} tickMargin={10} />
<ChartTooltip cursor={false} content={<ChartTooltipContent indicator="dashed" />} />
<Bar dataKey="pothole" fill="var(--color-pothole)" radius={4} />
<Bar dataKey="defected_sign_board" fill="var(--color-defected_sign_board)" radius={4} />
<Bar dataKey="road_crack" fill="var(--color-road_crack)" radius={4} />
@@ -101,5 +93,5 @@ export function ChainageBarChart({ data, isLoading = false }: ChainageBarChartPr
</BarChart>
</ChartContainer>
</div>
)
);
}

View File

@@ -1,137 +1,138 @@
"use client"
'use client';
import { useEffect } from "react"
import { MapContainer, TileLayer, CircleMarker, Popup, useMap } from "react-leaflet"
import { LatLngBounds, LatLng } from "leaflet"
import "leaflet/dist/leaflet.css"
import { Detection } from "@/types"
import { useEffect } from 'react';
import { MapContainer, TileLayer, CircleMarker, Popup, useMap } from 'react-leaflet';
import { LatLngBounds, LatLng } from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { Detection } from '@/types';
interface DashboardMapContentProps {
detections: Detection[]
detections: Detection[];
}
// Component to auto-fit map bounds to show all markers
function FitBounds({ bounds }: { bounds: LatLngBounds }) {
const map = useMap()
const map = useMap();
useEffect(() => {
if (bounds.isValid()) {
map.fitBounds(bounds, { padding: [50, 50] })
}
}, [bounds, map])
useEffect(() => {
if (bounds.isValid()) {
map.fitBounds(bounds, { padding: [50, 50] });
}
}, [bounds, map]);
return null
return null;
}
export default function DashboardMapContent({ detections }: DashboardMapContentProps) {
if (detections.length === 0) {
return (
<div className="h-full w-full flex items-center justify-center bg-muted/20">
<p className="text-muted-foreground">No detections to display</p>
</div>
)
}
// Calculate bounds to fit all markers
const firstDetection = detections[0]
const bounds = new LatLngBounds(
new LatLng(firstDetection.latitude!, firstDetection.longitude!),
new LatLng(firstDetection.latitude!, firstDetection.longitude!)
)
detections.forEach(d => {
if (d.latitude && d.longitude) {
bounds.extend(new LatLng(d.latitude, d.longitude))
}
})
// Center point
const center: [number, number] = [
(bounds.getNorth() + bounds.getSouth()) / 2,
(bounds.getEast() + bounds.getWest()) / 2
]
// Get marker color based on detection type
const getMarkerColor = (type: string) => {
const t = type.toLowerCase()
if (t === "pothole") {
return { fill: "#ef4444", stroke: "#b91c1c" } // Red
} else if (t === "defected_sign_board") {
return { fill: "#3b82f6", stroke: "#1d4ed8" } // Blue
} else if (t === "road_crack") {
return { fill: "#f59e0b", stroke: "#b45309" } // Orange
} else if (t === "damaged_road_marking") {
return { fill: "#6366f1", stroke: "#4338ca" } // Indigo
} else if (t === "good_sign_board") {
return { fill: "#10b981", stroke: "#047857" } // Emerald
}
return { fill: "#64748b", stroke: "#475569" } // Default Slate
}
// Get display name for detection type
const getTypeName = (type: string) => {
return type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
}
if (detections.length === 0) {
return (
<MapContainer
center={center}
zoom={13}
className="h-full w-full"
scrollWheelZoom={true}
zoomAnimation={false}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<div className="h-full w-full flex items-center justify-center bg-muted/20">
<p className="text-muted-foreground">No detections to display</p>
</div>
);
}
{/* Detection markers */}
{detections.map((detection, idx) => {
const colors = getMarkerColor(detection.type)
const typeName = getTypeName(detection.type)
// Calculate bounds to fit all markers
const firstDetection = detections[0];
const bounds = new LatLngBounds(
new LatLng(firstDetection.latitude!, firstDetection.longitude!),
new LatLng(firstDetection.latitude!, firstDetection.longitude!),
);
return (
<CircleMarker
key={`${detection.id}-${idx}`}
center={[detection.latitude!, detection.longitude!]}
radius={10}
fillColor={colors.fill}
color={colors.stroke}
weight={2}
opacity={1}
fillOpacity={0.8}
>
<Popup>
<div className="text-sm space-y-2 min-w-[180px]">
<div className="font-bold text-base border-b pb-1">
{typeName}
</div>
<div className="space-y-1">
<div className="flex justify-between">
<span className="text-muted-foreground">Class:</span>
<span className="font-medium">{detection.class.replace(/_/g, " ")}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Confidence:</span>
<span className="font-medium">{(detection.confidence * 100).toFixed(1)}%</span>
</div>
</div>
<div className="pt-2 border-t">
<div className="text-xs text-muted-foreground mb-1">Coordinates</div>
<div className="font-mono text-xs bg-muted/30 p-2 rounded">
<div>Lat: {detection.latitude!.toFixed(6)}</div>
<div>Lng: {detection.longitude!.toFixed(6)}</div>
</div>
</div>
</div>
</Popup>
</CircleMarker>
)
})}
detections.forEach((d) => {
if (d.latitude && d.longitude) {
bounds.extend(new LatLng(d.latitude, d.longitude));
}
});
{/* Auto-fit bounds */}
<FitBounds bounds={bounds} />
</MapContainer>
)
// Center point
const center: [number, number] = [
(bounds.getNorth() + bounds.getSouth()) / 2,
(bounds.getEast() + bounds.getWest()) / 2,
];
// Get marker color based on detection type
const getMarkerColor = (type: string) => {
const t = type.toLowerCase();
if (t === 'pothole') {
return { fill: '#ef4444', stroke: '#b91c1c' }; // Red
} else if (t === 'defected_sign_board') {
return { fill: '#3b82f6', stroke: '#1d4ed8' }; // Blue
} else if (t === 'road_crack') {
return { fill: '#f59e0b', stroke: '#b45309' }; // Orange
} else if (t === 'damaged_road_marking') {
return { fill: '#6366f1', stroke: '#4338ca' }; // Indigo
} else if (t === 'good_sign_board') {
return { fill: '#10b981', stroke: '#047857' }; // Emerald
}
return { fill: '#64748b', stroke: '#475569' }; // Default Slate
};
// Get display name for detection type
const getTypeName = (type: string) => {
return type
.split('_')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
return (
<MapContainer
center={center}
zoom={13}
className="h-full w-full"
scrollWheelZoom={true}
zoomAnimation={false}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
{/* Detection markers */}
{detections.map((detection, idx) => {
const colors = getMarkerColor(detection.type);
const typeName = getTypeName(detection.type);
return (
<CircleMarker
key={`${detection.id}-${idx}`}
center={[detection.latitude!, detection.longitude!]}
radius={10}
fillColor={colors.fill}
color={colors.stroke}
weight={2}
opacity={1}
fillOpacity={0.8}
>
<Popup>
<div className="text-sm space-y-2 min-w-[180px]">
<div className="font-bold text-base border-b pb-1">{typeName}</div>
<div className="space-y-1">
<div className="flex justify-between">
<span className="text-muted-foreground">Class:</span>
<span className="font-medium">{detection.class.replace(/_/g, ' ')}</span>
</div>
<div className="flex justify-between">
<span className="text-muted-foreground">Confidence:</span>
<span className="font-medium">{(detection.confidence * 100).toFixed(1)}%</span>
</div>
</div>
<div className="pt-2 border-t">
<div className="text-xs text-muted-foreground mb-1">Coordinates</div>
<div className="font-mono text-xs bg-muted/30 p-2 rounded">
<div>Lat: {detection.latitude!.toFixed(6)}</div>
<div>Lng: {detection.longitude!.toFixed(6)}</div>
</div>
</div>
</div>
</Popup>
</CircleMarker>
);
})}
{/* Auto-fit bounds */}
<FitBounds bounds={bounds} />
</MapContainer>
);
}

View File

@@ -1,158 +1,172 @@
"use client"
'use client';
import { useEffect, useState } from "react"
import dynamic from "next/dynamic"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Loader2, Milestone } from "lucide-react"
import { Detection } from "@/types"
import { useEffect, useState } from 'react';
import dynamic from 'next/dynamic';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, Milestone } from 'lucide-react';
import { Detection } from '@/types';
// Dynamically import the map to avoid SSR issues with Leaflet
const DashboardMapContent = dynamic(
() => import("./dashboard-map-content"),
{
ssr: false,
loading: () => (
<div className="h-full w-full flex items-center justify-center">
<Loader2 className="h-8 w-8 text-primary" />
</div>
)
}
)
const DashboardMapContent = dynamic(() => import('./dashboard-map-content'), {
ssr: false,
loading: () => (
<div className="h-full w-full flex items-center justify-center">
<Loader2 className="h-8 w-8 text-primary" />
</div>
),
});
interface DashboardMapProps {
className?: string
selectedProjectId?: string | null
selectedPackageId?: string | null
selectedChainageId?: string | null
projectSummary?: any
className?: string;
selectedProjectId?: string | null;
selectedPackageId?: string | null;
selectedChainageId?: string | null;
projectSummary?: any;
}
export function DashboardMap({
className,
selectedProjectId,
selectedPackageId,
selectedChainageId,
projectSummary
className,
selectedProjectId,
selectedPackageId,
selectedChainageId,
projectSummary,
}: DashboardMapProps) {
const [detections, setDetections] = useState<Detection[]>([])
const [isLoading, setIsLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
const [detections, setDetections] = useState<Detection[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!projectSummary) {
setDetections([])
setIsLoading(false)
return
}
try {
setIsLoading(true)
setError(null)
const filteredDetections: Detection[] = []
const packagesToProcess = selectedPackageId && selectedPackageId !== "all"
? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
: projectSummary.packages || {}
for (const [pkgName, pkg] of Object.entries(packagesToProcess)) {
const chainagesToProcess = selectedChainageId && selectedChainageId !== "all"
? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
: (pkg as any).chainages || {}
for (const [chnName, chn] of Object.entries(chainagesToProcess)) {
if (!chn) continue
const chainageDetections = (chn as any).detections || []
filteredDetections.push(...chainageDetections)
}
}
setDetections(filteredDetections)
} catch (err) {
console.error("Failed to extract detections:", err)
setError("Failed to load detection data")
} finally {
setIsLoading(false)
}
}, [projectSummary, selectedPackageId, selectedChainageId])
// Filter detections with valid GPS coordinates
const validDetections = detections.filter(d => d.latitude && d.longitude)
// Count detections by category
const counts = {
defected_sign_board: validDetections.filter(d => d.type?.toLowerCase() === "defected_sign_board").length,
pothole: validDetections.filter(d => d.type?.toLowerCase() === "pothole").length,
road_crack: validDetections.filter(d => d.type?.toLowerCase() === "road_crack").length,
damaged_road_marking: validDetections.filter(d => d.type?.toLowerCase() === "damaged_road_marking").length,
good_sign_board: validDetections.filter(d => d.type?.toLowerCase() === "good_sign_board").length
useEffect(() => {
if (!projectSummary) {
setDetections([]);
setIsLoading(false);
return;
}
return (
<Card className={`overflow-hidden ${className}`}>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="p-2 rounded-md bg-secondary text-secondary-foreground flex items-center justify-center">
<Milestone className="h-5 w-5" />
</div>
<div>
<CardTitle className="text-base font-bold">
Detection Map
</CardTitle>
<p className="text-xs text-muted-foreground">
{isLoading ? "Loading..." : `${validDetections.length} detections with GPS coordinates`}
</p>
</div>
</div>
try {
setIsLoading(true);
setError(null);
{/* Compact Color Legend */}
<div className="flex flex-wrap items-center justify-end gap-x-4 gap-y-1 text-[10px] max-w-[60%]">
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-red-500" />
<span className="text-muted-foreground font-medium">Potholes ({counts.pothole})</span>
</div>
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-blue-500" />
<span className="text-muted-foreground font-medium">Defected Signs ({counts.defected_sign_board})</span>
</div>
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-amber-500" />
<span className="text-muted-foreground font-medium">Cracks ({counts.road_crack})</span>
</div>
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-indigo-500" />
<span className="text-muted-foreground font-medium">Markings ({counts.damaged_road_marking})</span>
</div>
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-emerald-500" />
<span className="text-muted-foreground font-medium">Good Signs ({counts.good_sign_board})</span>
</div>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[500px] p-2 w-full relative">
{isLoading ? (
<div className="h-full w-full flex items-center justify-center bg-muted/50">
<Loader2 className="h-8 w-8 text-primary animate-spin" />
</div>
) : error ? (
<div className="h-full w-full flex items-center justify-center bg-muted/50">
<p className="text-muted-foreground">{error}</p>
</div>
) : validDetections.length === 0 ? (
<div className="h-full w-full flex items-center justify-center bg-muted/50">
<div className="text-center">
<p className="text-muted-foreground">No detections with GPS coordinates found</p>
<p className="text-sm text-muted-foreground mt-1 opacity-70">Process some videos to see detections on the map</p>
</div>
</div>
) : (
<DashboardMapContent detections={validDetections} />
)}
</div>
</CardContent>
</Card>
)
const filteredDetections: Detection[] = [];
const packagesToProcess =
selectedPackageId && selectedPackageId !== 'all'
? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
: projectSummary.packages || {};
for (const [pkgName, pkg] of Object.entries(packagesToProcess)) {
const chainagesToProcess =
selectedChainageId && selectedChainageId !== 'all'
? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
: (pkg as any).chainages || {};
for (const [chnName, chn] of Object.entries(chainagesToProcess)) {
if (!chn) continue;
const chainageDetections = (chn as any).detections || [];
filteredDetections.push(...chainageDetections);
}
}
setDetections(filteredDetections);
} catch (err) {
console.error('Failed to extract detections:', err);
setError('Failed to load detection data');
} finally {
setIsLoading(false);
}
}, [projectSummary, selectedPackageId, selectedChainageId]);
// Filter detections with valid GPS coordinates
const validDetections = detections.filter((d) => d.latitude && d.longitude);
// Count detections by category
const counts = {
defected_sign_board: validDetections.filter(
(d) => d.type?.toLowerCase() === 'defected_sign_board',
).length,
pothole: validDetections.filter((d) => d.type?.toLowerCase() === 'pothole').length,
road_crack: validDetections.filter((d) => d.type?.toLowerCase() === 'road_crack').length,
damaged_road_marking: validDetections.filter(
(d) => d.type?.toLowerCase() === 'damaged_road_marking',
).length,
good_sign_board: validDetections.filter((d) => d.type?.toLowerCase() === 'good_sign_board')
.length,
};
return (
<Card className={`overflow-hidden ${className}`}>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div className="p-2 rounded-md bg-secondary text-secondary-foreground flex items-center justify-center">
<Milestone className="h-5 w-5" />
</div>
<div>
<CardTitle className="text-base font-bold">Detection Map</CardTitle>
<p className="text-xs text-muted-foreground">
{isLoading
? 'Loading...'
: `${validDetections.length} detections with GPS coordinates`}
</p>
</div>
</div>
{/* Compact Color Legend */}
<div className="flex flex-wrap items-center justify-end gap-x-4 gap-y-1 text-[10px] max-w-[60%]">
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-red-500" />
<span className="text-muted-foreground font-medium">Potholes ({counts.pothole})</span>
</div>
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-blue-500" />
<span className="text-muted-foreground font-medium">
Defected Signs ({counts.defected_sign_board})
</span>
</div>
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-amber-500" />
<span className="text-muted-foreground font-medium">
Cracks ({counts.road_crack})
</span>
</div>
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-indigo-500" />
<span className="text-muted-foreground font-medium">
Markings ({counts.damaged_road_marking})
</span>
</div>
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-emerald-500" />
<span className="text-muted-foreground font-medium">
Good Signs ({counts.good_sign_board})
</span>
</div>
</div>
</div>
</CardHeader>
<CardContent className="p-0">
<div className="h-[500px] p-2 w-full relative">
{isLoading ? (
<div className="h-full w-full flex items-center justify-center bg-muted/50">
<Loader2 className="h-8 w-8 text-primary animate-spin" />
</div>
) : error ? (
<div className="h-full w-full flex items-center justify-center bg-muted/50">
<p className="text-muted-foreground">{error}</p>
</div>
) : validDetections.length === 0 ? (
<div className="h-full w-full flex items-center justify-center bg-muted/50">
<div className="text-center">
<p className="text-muted-foreground">No detections with GPS coordinates found</p>
<p className="text-sm text-muted-foreground mt-1 opacity-70">
Process some videos to see detections on the map
</p>
</div>
</div>
) : (
<DashboardMapContent detections={validDetections} />
)}
</div>
</CardContent>
</Card>
);
}

View File

@@ -1,7 +1,7 @@
"use client"
'use client';
import { Skeleton } from "@/components/ui/skeleton"
import { Card, CardContent, CardHeader } from "@/components/ui/card"
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
export function DashboardSkeleton() {
return (
@@ -42,18 +42,18 @@ export function DashboardSkeleton() {
{/* Map Skeleton */}
<Card>
<CardHeader className="pb-2">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Skeleton className="w-10 h-10 rounded-md" />
<Skeleton className="h-6 w-48" />
</div>
<Skeleton className="h-8 w-32 rounded-full" />
</div>
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<Skeleton className="w-10 h-10 rounded-md" />
<Skeleton className="h-6 w-48" />
</div>
<Skeleton className="h-8 w-32 rounded-full" />
</div>
</CardHeader>
<CardContent className="p-2">
<Skeleton className="h-[500px] w-full rounded-md" />
</CardContent>
</Card>
</div>
)
);
}

View File

@@ -1,47 +1,47 @@
"use client"
'use client';
import * as React from "react"
import { Loader2 } from "lucide-react"
import { Label, Pie, PieChart } from "recharts"
import * as React from 'react';
import { Loader2 } from 'lucide-react';
import { Label, Pie, PieChart } from 'recharts';
import {
ChartContainer,
ChartTooltip,
ChartTooltipContent,
type ChartConfig,
} from "@/components/ui/chart"
} from '@/components/ui/chart';
interface DetectionDonutChartProps {
defectedSignboard: number
pothole: number
roadCrack: number
damagedRoadMarking: number
goodSignboard: number
isLoading?: boolean
defectedSignboard: number;
pothole: number;
roadCrack: number;
damagedRoadMarking: number;
goodSignboard: number;
isLoading?: boolean;
}
const chartConfig = {
pothole: {
label: "Potholes",
color: "var(--chart-1)",
label: 'Potholes',
color: 'var(--chart-1)',
},
defectedSignboard: {
label: "Defected Signboards",
color: "var(--chart-2)",
label: 'Defected Signboards',
color: 'var(--chart-2)',
},
roadCrack: {
label: "Road Cracks",
color: "var(--chart-3)",
label: 'Road Cracks',
color: 'var(--chart-3)',
},
damagedRoadMarking: {
label: "Damaged Markings",
color: "var(--chart-4)",
label: 'Damaged Markings',
color: 'var(--chart-4)',
},
goodSignboard: {
label: "Good Signboards",
color: "var(--chart-5)",
label: 'Good Signboards',
color: 'var(--chart-5)',
},
} satisfies ChartConfig
} satisfies ChartConfig;
export function DetectionDonutChart({
defectedSignboard,
@@ -54,43 +54,37 @@ export function DetectionDonutChart({
const chartData = React.useMemo(
() =>
[
{ type: "pothole", count: pothole, fill: "var(--color-pothole)" },
{ type: 'pothole', count: pothole, fill: 'var(--color-pothole)' },
{
type: "defectedSignboard",
type: 'defectedSignboard',
count: defectedSignboard,
fill: "var(--color-defectedSignboard)",
fill: 'var(--color-defectedSignboard)',
},
{ type: "roadCrack", count: roadCrack, fill: "var(--color-roadCrack)" },
{ type: 'roadCrack', count: roadCrack, fill: 'var(--color-roadCrack)' },
{
type: "damagedRoadMarking",
type: 'damagedRoadMarking',
count: damagedRoadMarking,
fill: "var(--color-damagedRoadMarking)",
fill: 'var(--color-damagedRoadMarking)',
},
{
type: "goodSignboard",
type: 'goodSignboard',
count: goodSignboard,
fill: "var(--color-goodSignboard)",
fill: 'var(--color-goodSignboard)',
},
].filter((item) => item.count > 0),
[
pothole,
defectedSignboard,
roadCrack,
damagedRoadMarking,
goodSignboard,
]
)
[pothole, defectedSignboard, roadCrack, damagedRoadMarking, goodSignboard],
);
const totalDetections = React.useMemo(() => {
return chartData.reduce((acc, curr) => acc + curr.count, 0)
}, [chartData])
return chartData.reduce((acc, curr) => acc + curr.count, 0);
}, [chartData]);
if (isLoading) {
return (
<div className="h-[250px] flex items-center justify-center">
<Loader2 className="h-8 w-8 text-primary/50 animate-spin" />
</div>
)
);
}
if (totalDetections === 0) {
@@ -99,36 +93,19 @@ export function DetectionDonutChart({
<p className="text-sm">No detections found</p>
<p className="text-xs mt-1">Process videos to see data</p>
</div>
)
);
}
return (
<ChartContainer
config={chartConfig}
className="mx-auto aspect-square max-h-[250px]"
>
<ChartContainer config={chartConfig} className="mx-auto aspect-square max-h-[250px]">
<PieChart>
<ChartTooltip
cursor={false}
content={<ChartTooltipContent hideLabel />}
/>
<Pie
data={chartData}
dataKey="count"
nameKey="type"
innerRadius={60}
strokeWidth={5}
>
<ChartTooltip cursor={false} content={<ChartTooltipContent hideLabel />} />
<Pie data={chartData} dataKey="count" nameKey="type" innerRadius={60} strokeWidth={5}>
<Label
content={({ viewBox }) => {
if (viewBox && "cx" in viewBox && "cy" in viewBox) {
if (viewBox && 'cx' in viewBox && 'cy' in viewBox) {
return (
<text
x={viewBox.cx}
y={viewBox.cy}
textAnchor="middle"
dominantBaseline="middle"
>
<text x={viewBox.cx} y={viewBox.cy} textAnchor="middle" dominantBaseline="middle">
<tspan
x={viewBox.cx}
y={viewBox.cy}
@@ -144,13 +121,12 @@ export function DetectionDonutChart({
Total
</tspan>
</text>
)
);
}
}}
/>
</Pie>
</PieChart>
</ChartContainer>
)
);
}

View File

@@ -1,125 +1,131 @@
"use client"
'use client';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select"
import { FolderOpen, Package, Milestone } from "lucide-react"
import { Project } from "@/types"
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { FolderOpen, Package, Milestone } from 'lucide-react';
import { Project } from '@/types';
interface FilterSelectorProps {
projects: Project[]
selectedProjectId: string | null
selectedPackageId: string | null
selectedChainageId: string | null
onProjectChange: (projectId: string) => void
onPackageChange: (packageId: string) => void
onChainageChange: (chainageId: string) => void
packages: Array<{ id: string; name: string }>
chainages: Array<{ id: string; name: string }>
isLoading?: boolean
projects: Project[];
selectedProjectId: string | null;
selectedPackageId: string | null;
selectedChainageId: string | null;
onProjectChange: (projectId: string) => void;
onPackageChange: (packageId: string) => void;
onChainageChange: (chainageId: string) => void;
packages: Array<{ id: string; name: string }>;
chainages: Array<{ id: string; name: string }>;
isLoading?: boolean;
}
export function FilterSelector({
projects,
selectedProjectId,
selectedPackageId,
selectedChainageId,
onProjectChange,
onPackageChange,
onChainageChange,
packages,
chainages,
isLoading = false
projects,
selectedProjectId,
selectedPackageId,
selectedChainageId,
onProjectChange,
onPackageChange,
onChainageChange,
packages,
chainages,
isLoading = false,
}: FilterSelectorProps) {
return (
<div className="flex flex-col gap-5 p-5">
{/* Project Dropdown */}
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-gray-900 dark:bg-gray-100 text-gray-100 dark:text-gray-900 shadow-sm">
<FolderOpen className="h-4 w-4" />
</div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">Project</span>
</div>
<Select
value={selectedProjectId || ""}
onValueChange={onProjectChange}
disabled={isLoading || projects.length === 0}
>
<SelectTrigger className="h-10 text-sm w-full bg-background border-border/60 shadow-xs">
<SelectValue placeholder="Select project" />
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Package Dropdown */}
{selectedProjectId && (
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-gray-900 dark:bg-gray-100 text-gray-100 dark:text-gray-900 shadow-sm">
<Package className="h-4 w-4" />
</div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">Package</span>
</div>
<Select
value={selectedPackageId || "all"}
onValueChange={onPackageChange}
disabled={isLoading}
>
<SelectTrigger className="h-10 text-sm w-full bg-background border-border/60 shadow-xs">
<SelectValue placeholder="All packages" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Packages</SelectItem>
{packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id}>
{pkg.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Chainage Dropdown */}
{selectedPackageId && selectedPackageId !== "all" && (
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-gray-900 dark:bg-gray-100 text-gray-100 dark:text-gray-900 shadow-sm">
<Milestone className="h-4 w-4" />
</div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">Chainage</span>
</div>
<Select
value={selectedChainageId || "all"}
onValueChange={onChainageChange}
disabled={isLoading}
>
<SelectTrigger className="h-10 text-sm w-full bg-background border-border/60 shadow-xs">
<SelectValue placeholder="All chainages" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Chainages</SelectItem>
{chainages.map((chn) => (
<SelectItem key={chn.id} value={chn.id}>
{chn.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
return (
<div className="flex flex-col gap-5 p-5">
{/* Project Dropdown */}
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-gray-900 dark:bg-gray-100 text-gray-100 dark:text-gray-900 shadow-sm">
<FolderOpen className="h-4 w-4" />
</div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">
Project
</span>
</div>
);
<Select
value={selectedProjectId || ''}
onValueChange={onProjectChange}
disabled={isLoading || projects.length === 0}
>
<SelectTrigger className="h-10 text-sm w-full bg-background border-border/60 shadow-xs">
<SelectValue placeholder="Select project" />
</SelectTrigger>
<SelectContent>
{projects.map((project) => (
<SelectItem key={project.id} value={project.id}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Package Dropdown */}
{selectedProjectId && (
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-gray-900 dark:bg-gray-100 text-gray-100 dark:text-gray-900 shadow-sm">
<Package className="h-4 w-4" />
</div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">
Package
</span>
</div>
<Select
value={selectedPackageId || 'all'}
onValueChange={onPackageChange}
disabled={isLoading}
>
<SelectTrigger className="h-10 text-sm w-full bg-background border-border/60 shadow-xs">
<SelectValue placeholder="All packages" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Packages</SelectItem>
{packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id}>
{pkg.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
{/* Chainage Dropdown */}
{selectedPackageId && selectedPackageId !== 'all' && (
<div className="space-y-3">
<div className="flex items-center gap-2.5">
<div className="p-2 rounded-lg bg-gray-900 dark:bg-gray-100 text-gray-100 dark:text-gray-900 shadow-sm">
<Milestone className="h-4 w-4" />
</div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">
Chainage
</span>
</div>
<Select
value={selectedChainageId || 'all'}
onValueChange={onChainageChange}
disabled={isLoading}
>
<SelectTrigger className="h-10 text-sm w-full bg-background border-border/60 shadow-xs">
<SelectValue placeholder="All chainages" />
</SelectTrigger>
<SelectContent>
<SelectItem value="all">All Chainages</SelectItem>
{chainages.map((chn) => (
<SelectItem key={chn.id} value={chn.id}>
{chn.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
)}
</div>
);
}

View File

@@ -1,60 +1,55 @@
"use client"
'use client';
import { Card, CardContent } from "@/components/ui/card"
import { LucideIcon } from "lucide-react"
import { motion } from "motion/react"
import { Card, CardContent } from '@/components/ui/card';
import { LucideIcon } from 'lucide-react';
import { motion } from 'motion/react';
interface StatsCardProps {
title: string
subtitle?: string
value: number | string
icon: LucideIcon
isLoading?: boolean
title: string;
subtitle?: string;
value: number | string;
icon: LucideIcon;
isLoading?: boolean;
}
export function StatsCard({
title,
subtitle,
value,
icon: Icon,
isLoading = false
title,
subtitle,
value,
icon: Icon,
isLoading = false,
}: StatsCardProps) {
return (
<motion.div
whileHover={{ y: -4, scale: 1.02 }}
transition={{ type: "spring", stiffness: 400, damping: 17 }}
className="h-full"
>
<Card className="h-full py-6 px-4 transition-colors cursor-pointer">
<CardContent className="p-0 flex items-center justify-between gap-6">
<div className="flex flex-col gap-1 min-w-0">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
{title}
</h3>
<div className="flex flex-col">
{isLoading ? (
<div className="h-10 w-24 bg-muted rounded-md mt-2 animate-pulse" />
) : (
<>
<p className="text-3xl font-bold tracking-tight">
{value}
</p>
{subtitle && (
<p className="text-xs text-muted-foreground mt-1 line-clamp-1">
{subtitle}
</p>
)}
</>
)}
</div>
</div>
return (
<motion.div
whileHover={{ y: -4, scale: 1.02 }}
transition={{ type: 'spring', stiffness: 400, damping: 17 }}
className="h-full"
>
<Card className="h-full py-6 px-4 transition-colors cursor-pointer">
<CardContent className="p-0 flex items-center justify-between gap-6">
<div className="flex flex-col gap-1 min-w-0">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
{title}
</h3>
<div className="flex flex-col">
{isLoading ? (
<div className="h-10 w-24 bg-muted rounded-md mt-2 animate-pulse" />
) : (
<>
<p className="text-3xl font-bold tracking-tight">{value}</p>
{subtitle && (
<p className="text-xs text-muted-foreground mt-1 line-clamp-1">{subtitle}</p>
)}
</>
)}
</div>
</div>
<div className="p-3 rounded-xl bg-primary/10 text-primary shrink-0 group-hover:bg-primary group-hover:text-primary-foreground transition-colors">
<Icon className="h-6 w-6" />
</div>
</CardContent>
</Card>
</motion.div>
)
<div className="p-3 rounded-xl bg-primary/10 text-primary shrink-0 group-hover:bg-primary group-hover:text-primary-foreground transition-colors">
<Icon className="h-6 w-6" />
</div>
</CardContent>
</Card>
</motion.div>
);
}

View File

@@ -1,69 +1,71 @@
"use client";
import { Table } from "@tanstack/react-table";
'use client';
import { Table } from '@tanstack/react-table';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import { Button } from "@/components/ui/button";
import { ChevronLeft, ChevronRight } from "lucide-react";
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Button } from '@/components/ui/button';
import { ChevronLeft, ChevronRight } from 'lucide-react';
export function TableFooter<TData>({ table }: { table: Table<TData> }) {
return (
<div className="flex items-center justify-between px-6 py-4 border-t border-border/40 bg-muted/5">
<div className="flex items-center gap-6">
<div className="flex items-center space-x-2">
<p className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">Rows per page</p>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger className="h-8 w-[70px] bg-transparent border-border/40 text-xs font-semibold">
<SelectValue placeholder={table.getState().pagination.pageSize} />
</SelectTrigger>
<SelectContent side="top" className="min-w-[70px]">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`} className="text-xs">
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
<div className="flex items-center gap-8">
<div className="flex items-center text-[11px] font-bold text-muted-foreground uppercase tracking-widest gap-1">
<span className="text-foreground">Page {table.getState().pagination.pageIndex + 1}</span>
<span className="opacity-40">/</span>
<span>{table.getPageCount() || 1}</span>
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="h-8 w-8 p-0 border-border/40 bg-transparent hover:bg-muted/50 transition-colors"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<ChevronLeft className="h-4 w-4 opacity-70" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0 border-border/40 bg-transparent hover:bg-muted/50 transition-colors"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<ChevronRight className="h-4 w-4 opacity-70" />
</Button>
</div>
</div>
return (
<div className="flex items-center justify-between px-6 py-4 border-t border-border/40 bg-muted/5">
<div className="flex items-center gap-6">
<div className="flex items-center space-x-2">
<p className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">
Rows per page
</p>
<Select
value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => {
table.setPageSize(Number(value));
}}
>
<SelectTrigger className="h-8 w-[70px] bg-transparent border-border/40 text-xs font-semibold">
<SelectValue placeholder={table.getState().pagination.pageSize} />
</SelectTrigger>
<SelectContent side="top" className="min-w-[70px]">
{[10, 20, 30, 40, 50].map((pageSize) => (
<SelectItem key={pageSize} value={`${pageSize}`} className="text-xs">
{pageSize}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
);
</div>
<div className="flex items-center gap-8">
<div className="flex items-center text-[11px] font-bold text-muted-foreground uppercase tracking-widest gap-1">
<span className="text-foreground">Page {table.getState().pagination.pageIndex + 1}</span>
<span className="opacity-40">/</span>
<span>{table.getPageCount() || 1}</span>
</div>
<div className="flex items-center space-x-2">
<Button
variant="outline"
className="h-8 w-8 p-0 border-border/40 bg-transparent hover:bg-muted/50 transition-colors"
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
>
<span className="sr-only">Go to previous page</span>
<ChevronLeft className="h-4 w-4 opacity-70" />
</Button>
<Button
variant="outline"
className="h-8 w-8 p-0 border-border/40 bg-transparent hover:bg-muted/50 transition-colors"
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
>
<span className="sr-only">Go to next page</span>
<ChevronRight className="h-4 w-4 opacity-70" />
</Button>
</div>
</div>
</div>
);
}

View File

@@ -1,17 +1,17 @@
"use client";
import { SearchIcon } from "lucide-react";
import { Input } from "@/components/ui/input";
'use client';
import { SearchIcon } from 'lucide-react';
import { Input } from '@/components/ui/input';
const SearchBar = () => {
return (
<div className="relative w-full">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground/70" />
<Input
placeholder="Search resources..."
className="pl-9 h-10 text-sm bg-muted/20 border-border/40 focus:bg-background transition-all"
/>
</div>
);
return (
<div className="relative w-full">
<SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground/70" />
<Input
placeholder="Search resources..."
className="pl-9 h-10 text-sm bg-muted/20 border-border/40 focus:bg-background transition-all"
/>
</div>
);
};
export default SearchBar;

View File

@@ -1,36 +1,36 @@
"use client";
import React from "react";
import { Button } from "@/components/ui/button";
import SearchBar from "./SearchBar";
import { FolderPlus, Settings2, SlidersHorizontal } from "lucide-react";
import { Badge } from "@/components/ui/badge";
'use client';
import React from 'react';
import { Button } from '@/components/ui/button';
import SearchBar from './SearchBar';
import { FolderPlus, Settings2, SlidersHorizontal } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
interface TopHeaderProps {
title?: string;
itemCount?: number;
onAddNew?: () => void;
addButtonText?: string;
title?: string;
itemCount?: number;
onAddNew?: () => void;
addButtonText?: string;
}
const TopHeader = ({ title, itemCount, onAddNew, addButtonText = "Add New" }: TopHeaderProps) => {
return (
<div className="flex flex-col gap-1 p-3 w-full">
{/* Connected Summary Block */}
<div className="w-full bg-muted/10 border border-border/50 rounded-lg p-4 flex items-center">
<div className="flex items-center gap-2 text-muted-foreground font-semibold tracking-tight">
<span className="text-base text-foreground/80">Total {title || "Items"} :</span>
<span className="text-primary font-bold text-lg">{itemCount || 0}</span>
</div>
</div>
const TopHeader = ({ title, itemCount, onAddNew, addButtonText = 'Add New' }: TopHeaderProps) => {
return (
<div className="flex flex-col gap-1 p-3 w-full">
{/* Connected Summary Block */}
<div className="w-full bg-muted/10 border border-border/50 rounded-lg p-4 flex items-center">
<div className="flex items-center gap-2 text-muted-foreground font-semibold tracking-tight">
<span className="text-base text-foreground/80">Total {title || 'Items'} :</span>
<span className="text-primary font-bold text-lg">{itemCount || 0}</span>
</div>
</div>
<div className="flex items-center justify-between gap-4">
{/* Search Bar Hidden for now as per requirement */}
{/* <div className="flex w-full max-w-sm">
<div className="flex items-center justify-between gap-4">
{/* Search Bar Hidden for now as per requirement */}
{/* <div className="flex w-full max-w-sm">
<SearchBar />
</div> */}
{/* Add New Button moved to PageHeader */}
{/* {onAddNew && (
{/* Add New Button moved to PageHeader */}
{/* {onAddNew && (
<Button
onClick={onAddNew}
className="h-11 px-6 rounded-xl bg-primary hover:bg-primary/90 text-primary-foreground font-bold text-sm shadow-md shadow-primary/20 transition-all hover:-translate-y-0.5"
@@ -39,9 +39,9 @@ const TopHeader = ({ title, itemCount, onAddNew, addButtonText = "Add New" }: To
{addButtonText}
</Button>
)} */}
</div>
</div>
);
</div>
</div>
);
};
export default TopHeader;

View File

@@ -1,38 +1,32 @@
"use client";
import { flexRender } from "@tanstack/react-table";
import {
TableHead,
TableHeader as ShadTableHeader,
TableRow,
} from "@/components/ui/table";
import { Table } from "@tanstack/react-table";
import { ChevronDown, ChevronsUpDown } from "lucide-react";
'use client';
import { flexRender } from '@tanstack/react-table';
import { TableHead, TableHeader as ShadTableHeader, TableRow } from '@/components/ui/table';
import { Table } from '@tanstack/react-table';
import { ChevronDown, ChevronsUpDown } from 'lucide-react';
const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
return (
<ShadTableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent border-b border-border/30">
{headerGroup.headers.map((header) => {
return (
<TableHead key={header.id} className="h-14 px-6 text-muted-foreground border-b border-border/30 font-medium text-sm">
{header.isPlaceholder
? null
: (
<div className="flex items-center gap-2 group cursor-pointer select-none">
{flexRender(
header.column.columnDef.header,
header.getContext()
)}
</div>
)}
</TableHead>
);
})}
</TableRow>
))}
</ShadTableHeader>
);
return (
<ShadTableHeader>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id} className="hover:bg-transparent border-b border-border/30">
{headerGroup.headers.map((header) => {
return (
<TableHead
key={header.id}
className="h-14 px-6 text-muted-foreground border-b border-border/30 font-medium text-sm"
>
{header.isPlaceholder ? null : (
<div className="flex items-center gap-2 group cursor-pointer select-none">
{flexRender(header.column.columnDef.header, header.getContext())}
</div>
)}
</TableHead>
);
})}
</TableRow>
))}
</ShadTableHeader>
);
};
export default TableHeader;

View File

@@ -1,189 +1,194 @@
"use client";
import React from "react";
'use client';
import React from 'react';
import {
ColumnDef,
SortingState,
flexRender,
getCoreRowModel,
useReactTable,
getSortedRowModel,
getPaginationRowModel,
} from "@tanstack/react-table";
ColumnDef,
SortingState,
flexRender,
getCoreRowModel,
useReactTable,
getSortedRowModel,
getPaginationRowModel,
} from '@tanstack/react-table';
import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table";
import { Skeleton } from "@/components/ui/skeleton";
import { Button } from "@/components/ui/button";
import { Edit3, MoreHorizontal, Trash2 } from "lucide-react";
import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
import { Skeleton } from '@/components/ui/skeleton';
import { Button } from '@/components/ui/button';
import { Edit3, MoreHorizontal, Trash2 } from 'lucide-react';
import TopHeader from "./Header";
import TableHeader from "./TableHeader";
import { TableFooter } from "./Footer";
import { cn } from "@/lib/utils";
import TopHeader from './Header';
import TableHeader from './TableHeader';
import { TableFooter } from './Footer';
import { cn } from '@/lib/utils';
export interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[];
data: TData[];
title?: string;
onAddNew?: () => void;
addButtonText?: string;
isLoading?: boolean;
onEdit?: (item: TData) => void;
onDelete?: (item: TData) => void;
pagination?: {
skip: number;
limit: number;
totalItems?: number;
onPageChange: (newSkip: number) => void;
onLimitChange: (newLimit: number) => void;
};
columns: ColumnDef<TData, TValue>[];
data: TData[];
title?: string;
onAddNew?: () => void;
addButtonText?: string;
isLoading?: boolean;
onEdit?: (item: TData) => void;
onDelete?: (item: TData) => void;
pagination?: {
skip: number;
limit: number;
totalItems?: number;
onPageChange: (newSkip: number) => void;
onLimitChange: (newLimit: number) => void;
};
}
export function DataTable<TData, TValue>({
columns: initialColumns,
data,
title,
onAddNew,
addButtonText,
isLoading = false,
onEdit,
onDelete,
pagination,
columns: initialColumns,
data,
title,
onAddNew,
addButtonText,
isLoading = false,
onEdit,
onDelete,
pagination,
}: DataTableProps<TData, TValue>) {
const [rowSelection, setRowSelection] = React.useState({});
const [sorting, setSorting] = React.useState<SortingState>([]);
const [rowSelection, setRowSelection] = React.useState({});
const [sorting, setSorting] = React.useState<SortingState>([]);
const columns = React.useMemo(() => {
const cols: ColumnDef<TData, TValue>[] = [
...initialColumns,
];
const columns = React.useMemo(() => {
const cols: ColumnDef<TData, TValue>[] = [...initialColumns];
if (onEdit || onDelete) {
cols.push({
id: "actions",
header: () => <div className="text-right px-4">Action</div>,
cell: ({ row }) => {
const item = row.original;
return (
<div className="flex justify-end gap-3 px-4">
{onEdit && (
<button
onClick={(e) => {
e.stopPropagation();
onEdit(item);
}}
className="flex items-center justify-center h-8 w-8 rounded-md text-primary hover:bg-foreground/10 transition-all duration-200"
>
<Edit3 className="h-4.5 w-4.5" />
</button>
)}
{onDelete && (
<button
onClick={(e) => {
e.stopPropagation();
onDelete(item);
}}
className="flex items-center justify-center h-8 w-8 rounded-md text-red-500 hover:bg-foreground/10 transition-all duration-200"
>
<Trash2 className="h-4.5 w-4.5" />
</button>
)}
</div>
);
},
});
}
return cols;
}, [initialColumns, onEdit, onDelete]);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
manualPagination: !!pagination,
pageCount: pagination?.totalItems ? Math.ceil(pagination.totalItems / pagination.limit) : -1,
state: {
rowSelection,
sorting,
pagination: pagination ? {
pageIndex: Math.floor(pagination.skip / pagination.limit),
pageSize: pagination.limit,
} : undefined,
},
onPaginationChange: (updater) => {
if (typeof updater === 'function' && pagination) {
const newState = updater({
pageIndex: Math.floor(pagination.skip / pagination.limit),
pageSize: pagination.limit,
});
pagination.onLimitChange(newState.pageSize);
pagination.onPageChange(newState.pageIndex * newState.pageSize);
}
},
});
return (
<div className="rounded-xl border border-border/50 bg-muted/10 p-1 space-y-6">
<div className="bg-background/40 dark:bg-background/60 backdrop-blur-xl rounded-xl border border-border/50 overflow-hidden transition-all duration-300">
<TopHeader
title={title}
itemCount={data.length}
onAddNew={onAddNew}
addButtonText={addButtonText}
/>
<div className="px-6 py-2">
<Table containerClassName="max-h-[calc(100vh-300px)] overflow-y-auto scrollbar-thin" className="border-separate border-spacing-0">
<TableHeader table={table} />
<TableBody>
{isLoading ? (
Array.from({ length: 5 }).map((_, idx) => (
<TableRow key={idx} className="border-b border-border/30 last:border-0 hover:bg-muted/5">
{columns.map((_, colIdx) => (
<TableCell key={colIdx} className="px-6 py-6 border-b border-border/30">
<Skeleton className="h-4 w-full max-w-[140px] opacity-20" />
</TableCell>
))}
</TableRow>
))
) : table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && "selected"}
className="group hover:bg-muted/10 transition-colors"
>
{row.getVisibleCells().map((cell) => (
<TableCell key={cell.id} className="px-4 py-3 border-b border-border/50 align-middle text-muted-foreground text-sm font-medium group-hover:text-foreground">
{flexRender(
cell.column.columnDef.cell,
cell.getContext()
)}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell
colSpan={columns.length}
className="h-48 text-center"
>
<div className="flex flex-col items-center justify-center text-muted-foreground gap-1">
<p className="font-bold text-sm tracking-tight">No results found.</p>
<p className="text-xs opacity-60 font-medium">Try adjusting your filters or search terms.</p>
</div>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
<TableFooter table={table} />
if (onEdit || onDelete) {
cols.push({
id: 'actions',
header: () => <div className="text-right px-4">Action</div>,
cell: ({ row }) => {
const item = row.original;
return (
<div className="flex justify-end gap-3 px-4">
{onEdit && (
<button
onClick={(e) => {
e.stopPropagation();
onEdit(item);
}}
className="flex items-center justify-center h-8 w-8 rounded-md text-primary hover:bg-foreground/10 transition-all duration-200"
>
<Edit3 className="h-4.5 w-4.5" />
</button>
)}
{onDelete && (
<button
onClick={(e) => {
e.stopPropagation();
onDelete(item);
}}
className="flex items-center justify-center h-8 w-8 rounded-md text-red-500 hover:bg-foreground/10 transition-all duration-200"
>
<Trash2 className="h-4.5 w-4.5" />
</button>
)}
</div>
);
},
});
}
return cols;
}, [initialColumns, onEdit, onDelete]);
const table = useReactTable({
data,
columns,
getCoreRowModel: getCoreRowModel(),
onRowSelectionChange: setRowSelection,
onSortingChange: setSorting,
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
manualPagination: !!pagination,
pageCount: pagination?.totalItems ? Math.ceil(pagination.totalItems / pagination.limit) : -1,
state: {
rowSelection,
sorting,
pagination: pagination
? {
pageIndex: Math.floor(pagination.skip / pagination.limit),
pageSize: pagination.limit,
}
: undefined,
},
onPaginationChange: (updater) => {
if (typeof updater === 'function' && pagination) {
const newState = updater({
pageIndex: Math.floor(pagination.skip / pagination.limit),
pageSize: pagination.limit,
});
pagination.onLimitChange(newState.pageSize);
pagination.onPageChange(newState.pageIndex * newState.pageSize);
}
},
});
return (
<div className="rounded-xl border border-border/50 bg-muted/10 p-1 space-y-6">
<div className="bg-background/40 dark:bg-background/60 backdrop-blur-xl rounded-xl border border-border/50 overflow-hidden transition-all duration-300">
<TopHeader
title={title}
itemCount={data.length}
onAddNew={onAddNew}
addButtonText={addButtonText}
/>
<div className="px-6 py-2">
<Table
containerClassName="max-h-[calc(100vh-300px)] overflow-y-auto scrollbar-thin"
className="border-separate border-spacing-0"
>
<TableHeader table={table} />
<TableBody>
{isLoading ? (
Array.from({ length: 5 }).map((_, idx) => (
<TableRow
key={idx}
className="border-b border-border/30 last:border-0 hover:bg-muted/5"
>
{columns.map((_, colIdx) => (
<TableCell key={colIdx} className="px-6 py-6 border-b border-border/30">
<Skeleton className="h-4 w-full max-w-[140px] opacity-20" />
</TableCell>
))}
</TableRow>
))
) : table.getRowModel().rows?.length ? (
table.getRowModel().rows.map((row) => (
<TableRow
key={row.id}
data-state={row.getIsSelected() && 'selected'}
className="group hover:bg-muted/10 transition-colors"
>
{row.getVisibleCells().map((cell) => (
<TableCell
key={cell.id}
className="px-4 py-3 border-b border-border/50 align-middle text-muted-foreground text-sm font-medium group-hover:text-foreground"
>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell>
))}
</TableRow>
))
) : (
<TableRow>
<TableCell colSpan={columns.length} className="h-48 text-center">
<div className="flex flex-col items-center justify-center text-muted-foreground gap-1">
<p className="font-bold text-sm tracking-tight">No results found.</p>
<p className="text-xs opacity-60 font-medium">
Try adjusting your filters or search terms.
</p>
</div>
</TableCell>
</TableRow>
)}
</TableBody>
</Table>
</div>
);
<TableFooter table={table} />
</div>
</div>
);
}

View File

@@ -1,152 +1,153 @@
"use client"
'use client';
import { useEffect } from "react"
import { MapContainer, TileLayer, Polyline, CircleMarker, Popup, useMap } from "react-leaflet"
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { LatLngBounds, LatLng } from "leaflet"
import "leaflet/dist/leaflet.css"
import { useEffect } from 'react';
import { MapContainer, TileLayer, Polyline, CircleMarker, Popup, useMap } from 'react-leaflet';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { LatLngBounds, LatLng } from 'leaflet';
import 'leaflet/dist/leaflet.css';
type Detection = {
id: number
type: string
class: string
confidence: number
latitude: number
longitude: number
frame_number: number
}
id: number;
type: string;
class: string;
confidence: number;
latitude: number;
longitude: number;
frame_number: number;
};
type MapModalProps = {
open: boolean
onClose: () => void
detections: Detection[]
detectionType: "pothole-detection" | "sign-board-detection" | "pot-sign-detection"
}
open: boolean;
onClose: () => void;
detections: Detection[];
detectionType: 'pothole-detection' | 'sign-board-detection' | 'pot-sign-detection';
};
// Component to auto-fit map bounds to show all markers
function FitBounds({ bounds }: { bounds: LatLngBounds }) {
const map = useMap()
const map = useMap();
useEffect(() => {
if (!map || !bounds.isValid()) return
useEffect(() => {
if (!map || !bounds.isValid()) return;
const timer = setTimeout(() => {
map.invalidateSize()
map.fitBounds(bounds, {
padding: [50, 50],
maxZoom: 16,
animate: true
})
}, 200)
const timer = setTimeout(() => {
map.invalidateSize();
map.fitBounds(bounds, {
padding: [50, 50],
maxZoom: 16,
animate: true,
});
}, 200);
return () => clearTimeout(timer)
}, [bounds, map])
return () => clearTimeout(timer);
}, [bounds, map]);
return null
return null;
}
export default function MapModal({ open, onClose, detections, detectionType }: MapModalProps) {
const validDetections = detections.filter(d => d.latitude && d.longitude)
if (validDetections.length === 0) {
return (
<Dialog open={open} onOpenChange={onClose}>
<DialogContent className="max-w-4xl h-[600px]">
<DialogHeader>
<DialogTitle>Detection Map</DialogTitle>
</DialogHeader>
<div className="flex items-center justify-center h-full text-muted-foreground text-sm font-medium">
No GPS data available for detections.
</div>
</DialogContent>
</Dialog>
)
}
const routeCoordinates: [number, number][] = validDetections.map(d => [d.latitude, d.longitude])
const bounds = new LatLngBounds(new LatLng(routeCoordinates[0][0], routeCoordinates[0][1]), new LatLng(routeCoordinates[0][0], routeCoordinates[0][1]))
routeCoordinates.forEach(coord => bounds.extend(new LatLng(coord[0], coord[1])))
const center: [number, number] = [(bounds.getNorth() + bounds.getSouth()) / 2, (bounds.getEast() + bounds.getWest()) / 2]
const isCombined = detectionType === "pot-sign-detection"
const isPothole = detectionType === "pothole-detection"
const validDetections = detections.filter((d) => d.latitude && d.longitude);
if (validDetections.length === 0) {
return (
<Dialog open={open} onOpenChange={onClose}>
<DialogContent className="max-w-6xl h-[85vh] p-0 flex flex-col overflow-hidden border-none shadow-2xl">
<DialogHeader className="px-6 py-4 border-b shrink-0">
<DialogTitle className="text-xl font-bold">
{isCombined ? "Combined" : isPothole ? "Pothole" : "Signboard"} Detection Map
</DialogTitle>
<p className="text-xs text-muted-foreground font-medium">
{validDetections.length} points of interest identified with GPS data
</p>
</DialogHeader>
<Dialog open={open} onOpenChange={onClose}>
<DialogContent className="max-w-4xl h-[600px]">
<DialogHeader>
<DialogTitle>Detection Map</DialogTitle>
</DialogHeader>
<div className="flex items-center justify-center h-full text-muted-foreground text-sm font-medium">
No GPS data available for detections.
</div>
</DialogContent>
</Dialog>
);
}
<div className="flex-1 w-full relative bg-muted/20">
<MapContainer
center={center}
zoom={13}
className="h-full w-full"
scrollWheelZoom={true}
>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
const routeCoordinates: [number, number][] = validDetections.map((d) => [
d.latitude,
d.longitude,
]);
const bounds = new LatLngBounds(
new LatLng(routeCoordinates[0][0], routeCoordinates[0][1]),
new LatLng(routeCoordinates[0][0], routeCoordinates[0][1]),
);
routeCoordinates.forEach((coord) => bounds.extend(new LatLng(coord[0], coord[1])));
const center: [number, number] = [
(bounds.getNorth() + bounds.getSouth()) / 2,
(bounds.getEast() + bounds.getWest()) / 2,
];
<Polyline
positions={routeCoordinates}
color="#3b82f6"
weight={4}
opacity={0.6}
/>
const isCombined = detectionType === 'pot-sign-detection';
const isPothole = detectionType === 'pothole-detection';
{validDetections.map((detection, idx) => {
const type = (detection.type || "").toLowerCase()
const colors: Record<string, { fill: string, stroke: string }> = {
'pothole': { fill: '#ef4444', stroke: '#b91c1c' },
'defected_sign_board': { fill: '#3b82f6', stroke: '#1d4ed8' },
'road_crack': { fill: '#f59e0b', stroke: '#b45309' },
'damaged_road_marking': { fill: '#6366f1', stroke: '#4338ca' },
'good_sign_board': { fill: '#10b981', stroke: '#047857' }
}
const color = colors[type] || { fill: '#64748b', stroke: '#475569' }
return (
<Dialog open={open} onOpenChange={onClose}>
<DialogContent className="max-w-6xl h-[85vh] p-0 flex flex-col overflow-hidden border-none shadow-2xl">
<DialogHeader className="px-6 py-4 border-b shrink-0">
<DialogTitle className="text-xl font-bold">
{isCombined ? 'Combined' : isPothole ? 'Pothole' : 'Signboard'} Detection Map
</DialogTitle>
<p className="text-xs text-muted-foreground font-medium">
{validDetections.length} points of interest identified with GPS data
</p>
</DialogHeader>
return (
<CircleMarker
key={`${detection.id}-${idx}`}
center={[detection.latitude, detection.longitude]}
radius={7}
fillColor={color.fill}
color={color.stroke}
weight={2}
opacity={1}
fillOpacity={0.9}
>
<Popup>
<div className="text-[11px] space-y-2 p-1">
<div className="font-bold border-b pb-1 capitalize">
{(detection.type || "").replace(/_/g, " ")} #{detection.id}
</div>
<div className="grid grid-cols-2 gap-x-4 gap-y-1">
<span className="text-muted-foreground">Frame:</span>
<span className="font-semibold text-right">{detection.frame_number}</span>
<span className="text-muted-foreground">Confidence:</span>
<span className="font-semibold text-right">{(detection.confidence * 100).toFixed(0)}%</span>
</div>
<div className="font-mono bg-muted p-1.5 rounded border text-center text-[9px]">
{detection.latitude.toFixed(6)}, {detection.longitude.toFixed(6)}
</div>
</div>
</Popup>
</CircleMarker>
)
})}
<FitBounds bounds={bounds} />
</MapContainer>
</div>
</DialogContent>
</Dialog>
)
<div className="flex-1 w-full relative bg-muted/20">
<MapContainer center={center} zoom={13} className="h-full w-full" scrollWheelZoom={true}>
<TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Polyline positions={routeCoordinates} color="#3b82f6" weight={4} opacity={0.6} />
{validDetections.map((detection, idx) => {
const type = (detection.type || '').toLowerCase();
const colors: Record<string, { fill: string; stroke: string }> = {
pothole: { fill: '#ef4444', stroke: '#b91c1c' },
defected_sign_board: { fill: '#3b82f6', stroke: '#1d4ed8' },
road_crack: { fill: '#f59e0b', stroke: '#b45309' },
damaged_road_marking: { fill: '#6366f1', stroke: '#4338ca' },
good_sign_board: { fill: '#10b981', stroke: '#047857' },
};
const color = colors[type] || { fill: '#64748b', stroke: '#475569' };
return (
<CircleMarker
key={`${detection.id}-${idx}`}
center={[detection.latitude, detection.longitude]}
radius={7}
fillColor={color.fill}
color={color.stroke}
weight={2}
opacity={1}
fillOpacity={0.9}
>
<Popup>
<div className="text-[11px] space-y-2 p-1">
<div className="font-bold border-b pb-1 capitalize">
{(detection.type || '').replace(/_/g, ' ')} #{detection.id}
</div>
<div className="grid grid-cols-2 gap-x-4 gap-y-1">
<span className="text-muted-foreground">Frame:</span>
<span className="font-semibold text-right">{detection.frame_number}</span>
<span className="text-muted-foreground">Confidence:</span>
<span className="font-semibold text-right">
{(detection.confidence * 100).toFixed(0)}%
</span>
</div>
<div className="font-mono bg-muted p-1.5 rounded border text-center text-[9px]">
{detection.latitude.toFixed(6)}, {detection.longitude.toFixed(6)}
</div>
</div>
</Popup>
</CircleMarker>
);
})}
<FitBounds bounds={bounds} />
</MapContainer>
</div>
</DialogContent>
</Dialog>
);
}

View File

@@ -1,16 +1,16 @@
"use client";
'use client';
import * as React from "react";
import { Moon, Sun } from "lucide-react";
import { useTheme } from "next-themes";
import * as React from 'react';
import { Moon, Sun } from 'lucide-react';
import { useTheme } from 'next-themes';
import { Button } from "@/components/ui/button";
import { Button } from '@/components/ui/button';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
} from '@/components/ui/dropdown-menu';
export function ModeToggle() {
const { setTheme } = useTheme();
@@ -25,15 +25,9 @@ export function ModeToggle() {
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem onClick={() => setTheme("light")}>
Light
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("dark")}>
Dark
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme("system")}>
System
</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('light')}>Light</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('dark')}>Dark</DropdownMenuItem>
<DropdownMenuItem onClick={() => setTheme('system')}>System</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);

View File

@@ -1,19 +1,8 @@
"use client"
'use client';
import {
BadgeCheck,
Bell,
ChevronsUpDown,
CreditCard,
LogOut,
Sparkles,
} from "lucide-react"
import { BadgeCheck, Bell, ChevronsUpDown, CreditCard, LogOut, Sparkles } from 'lucide-react';
import {
Avatar,
AvatarFallback,
AvatarImage,
} from "@/components/ui/avatar"
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
DropdownMenu,
DropdownMenuContent,
@@ -22,24 +11,24 @@ import {
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
} from '@/components/ui/dropdown-menu';
import {
SidebarMenu,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
} from "@/components/ui/sidebar"
} from '@/components/ui/sidebar';
export function NavUser({
user,
}: {
user: {
name: string
email: string
avatar: string
}
name: string;
email: string;
avatar: string;
};
}) {
const { isMobile } = useSidebar()
const { isMobile } = useSidebar();
return (
<SidebarMenu>
@@ -63,7 +52,7 @@ export function NavUser({
</DropdownMenuTrigger>
<DropdownMenuContent
className="w-[--radix-dropdown-menu-trigger-width] min-w-56 rounded-lg"
side={isMobile ? "bottom" : "right"}
side={isMobile ? 'bottom' : 'right'}
align="end"
sideOffset={4}
>
@@ -110,5 +99,5 @@ export function NavUser({
</DropdownMenu>
</SidebarMenuItem>
</SidebarMenu>
)
);
}

View File

@@ -1,41 +1,34 @@
"use client"
'use client';
import { LucideIcon } from "lucide-react"
import { Reveal } from "@/components/ui/reveal"
import { LucideIcon } from 'lucide-react';
import { Reveal } from '@/components/ui/reveal';
interface PageHeaderProps {
title: string
description: string
icon?: LucideIcon
children?: React.ReactNode
actions?: React.ReactNode
title: string;
description: string;
icon?: LucideIcon;
children?: React.ReactNode;
actions?: React.ReactNode;
}
export function PageHeader({ title, description, icon: Icon, children, actions }: PageHeaderProps) {
return (
<Reveal direction="down" className="w-full">
<div className="flex items-center justify-between w-full">
<div className="flex items-center gap-6">
{/* <div className="p-3.5 rounded-xl bg-primary text-primary-foreground flex items-center justify-center shadow-lg shadow-primary/5 ring-1 ring-white/10">
return (
<Reveal direction="down" className="w-full">
<div className="flex items-center justify-between w-full">
<div className="flex items-center gap-6">
{/* <div className="p-3.5 rounded-xl bg-primary text-primary-foreground flex items-center justify-center shadow-lg shadow-primary/5 ring-1 ring-white/10">
{Icon && <Icon className="h-7 w-7" />}
{children}
</div> */}
<div className="flex flex-col">
<h1 className="text-3xl font-extrabold tracking-tight ">
{title}
</h1>
<p className="text-muted-foreground mt-1 text-sm font-semibold tracking-wide opacity-80">
{description}
</p>
</div>
</div>
{actions && (
<div className="flex items-center gap-4">
{actions}
</div>
)}
</div>
</Reveal>
)
<div className="flex flex-col">
<h1 className="text-3xl font-extrabold tracking-tight ">{title}</h1>
<p className="text-muted-foreground mt-1 text-sm font-semibold tracking-wide opacity-80">
{description}
</p>
</div>
</div>
{actions && <div className="flex items-center gap-4">{actions}</div>}
</div>
</Reveal>
);
}

View File

@@ -1,17 +1,10 @@
import Image from "next/image"
import Image from 'next/image';
export function PoweredBy() {
return (
<div className="flex items-center justify-center gap-2 mt-3 transition-opacity duration-300">
<span className="font-medium text-muted-foreground">
Powered by
</span>
<Image
src="/sg.svg"
alt="Sentient Geeks"
width={130}
height={20}
/>
</div>
)
return (
<div className="flex items-center justify-center gap-2 mt-3 transition-opacity duration-300">
<span className="font-medium text-muted-foreground">Powered by</span>
<Image src="/sg.svg" alt="Sentient Geeks" width={130} height={20} />
</div>
);
}

View File

@@ -1,329 +1,340 @@
"use client"
'use client';
import { useState, useEffect } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Label } from "@/components/ui/label"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Loader2, Check } from "lucide-react"
import { projectService, packageService, chainageService } from "@/services/api"
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import {
Project,
Package as PackageType,
Chainage,
SessionContext
} from "@/types"
import { cn } from "@/lib/utils"
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Loader2, Check } from 'lucide-react';
import { projectService, packageService, chainageService } from '@/services/api';
import { Project, Package as PackageType, Chainage, SessionContext } from '@/types';
import { cn } from '@/lib/utils';
type ProjectSelectionSectionProps = {
onSelectionComplete: (session: SessionContext) => void
}
onSelectionComplete: (session: SessionContext) => void;
};
export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectionSectionProps) {
// Data states
const [projects, setProjects] = useState<Project[]>([])
const [packages, setPackages] = useState<PackageType[]>([])
const [chainages, setChainages] = useState<Chainage[]>([])
// Data states
const [projects, setProjects] = useState<Project[]>([]);
const [packages, setPackages] = useState<PackageType[]>([]);
const [chainages, setChainages] = useState<Chainage[]>([]);
// Selection states
const [selectedProject, setSelectedProject] = useState<Project | null>(null)
const [selectedPackage, setSelectedPackage] = useState<PackageType | null>(null)
const [selectedChainage, setSelectedChainage] = useState<Chainage | null>(null)
// Selection states
const [selectedProject, setSelectedProject] = useState<Project | null>(null);
const [selectedPackage, setSelectedPackage] = useState<PackageType | null>(null);
const [selectedChainage, setSelectedChainage] = useState<Chainage | null>(null);
// Loading states
const [loadingProjects, setLoadingProjects] = useState(true)
const [loadingPackages, setLoadingPackages] = useState(false)
const [loadingChainages, setLoadingChainages] = useState(false)
// Loading states
const [loadingProjects, setLoadingProjects] = useState(true);
const [loadingPackages, setLoadingPackages] = useState(false);
const [loadingChainages, setLoadingChainages] = useState(false);
// Error state
const [error, setError] = useState<string | null>(null)
// Error state
const [error, setError] = useState<string | null>(null);
// Load projects on mount
useEffect(() => {
const loadProjects = async () => {
try {
setLoadingProjects(true)
setError(null)
const data = await projectService.getProjects()
setProjects(data.items)
} catch (err) {
console.error("Failed to load projects:", err)
setError("Failed to load projects. Please check if the backend is running.")
} finally {
setLoadingProjects(false)
}
}
loadProjects()
}, [])
// Load projects on mount
useEffect(() => {
const loadProjects = async () => {
try {
setLoadingProjects(true);
setError(null);
const data = await projectService.getProjects();
setProjects(data.items);
} catch (err) {
console.error('Failed to load projects:', err);
setError('Failed to load projects. Please check if the backend is running.');
} finally {
setLoadingProjects(false);
}
};
loadProjects();
}, []);
// Load packages when project changes
useEffect(() => {
if (!selectedProject) {
setPackages([])
setSelectedPackage(null)
return
}
const loadPackages = async () => {
try {
setLoadingPackages(true)
setError(null)
setSelectedPackage(null)
setSelectedChainage(null)
setChainages([])
const data = await packageService.getPackagesByProject(selectedProject.id)
setPackages(data.items)
} catch (err) {
console.error("Failed to load packages:", err)
setError("Failed to load packages for the selected project.")
} finally {
setLoadingPackages(false)
}
}
loadPackages()
}, [selectedProject])
// Load chainages when package changes
useEffect(() => {
if (!selectedPackage) {
setChainages([])
setSelectedChainage(null)
return
}
const loadChainages = async () => {
try {
setLoadingChainages(true)
setError(null)
setSelectedChainage(null)
const data = await chainageService.getChainagesByPackage(selectedPackage.id)
setChainages(data.items)
} catch (err) {
console.error("Failed to load chainages:", err)
setError("Failed to load chainages for the selected package.")
} finally {
setLoadingChainages(false)
}
}
loadChainages()
}, [selectedPackage])
const handleProjectChange = (projectId: string) => {
const project = projects.find(p => p.id === projectId) || null
setSelectedProject(project)
// Load packages when project changes
useEffect(() => {
if (!selectedProject) {
setPackages([]);
setSelectedPackage(null);
return;
}
const handlePackageChange = (packageId: string) => {
const pkg = packages.find(p => p.id === packageId) || null
setSelectedPackage(pkg)
const loadPackages = async () => {
try {
setLoadingPackages(true);
setError(null);
setSelectedPackage(null);
setSelectedChainage(null);
setChainages([]);
const data = await packageService.getPackagesByProject(selectedProject.id);
setPackages(data.items);
} catch (err) {
console.error('Failed to load packages:', err);
setError('Failed to load packages for the selected project.');
} finally {
setLoadingPackages(false);
}
};
loadPackages();
}, [selectedProject]);
// Load chainages when package changes
useEffect(() => {
if (!selectedPackage) {
setChainages([]);
setSelectedChainage(null);
return;
}
const handleChainageChange = (chainageId: string) => {
const chainage = chainages.find(chn => chn.id === chainageId) || null
setSelectedChainage(chainage)
const loadChainages = async () => {
try {
setLoadingChainages(true);
setError(null);
setSelectedChainage(null);
const data = await chainageService.getChainagesByPackage(selectedPackage.id);
setChainages(data.items);
} catch (err) {
console.error('Failed to load chainages:', err);
setError('Failed to load chainages for the selected package.');
} finally {
setLoadingChainages(false);
}
};
loadChainages();
}, [selectedPackage]);
const handleProjectChange = (projectId: string) => {
const project = projects.find((p) => p.id === projectId) || null;
setSelectedProject(project);
};
const handlePackageChange = (packageId: string) => {
const pkg = packages.find((p) => p.id === packageId) || null;
setSelectedPackage(pkg);
};
const handleChainageChange = (chainageId: string) => {
const chainage = chainages.find((chn) => chn.id === chainageId) || null;
setSelectedChainage(chainage);
};
const handleProceed = () => {
if (selectedProject && selectedPackage && selectedChainage) {
onSelectionComplete({
projectId: selectedProject.id,
projectName: selectedProject.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: selectedChainage.id,
chainageName: selectedChainage.segment_name,
});
}
};
const handleProceed = () => {
if (selectedProject && selectedPackage && selectedChainage) {
onSelectionComplete({
projectId: selectedProject.id,
projectName: selectedProject.name,
packageId: selectedPackage.id,
packageName: selectedPackage.name,
chainageId: selectedChainage.id,
chainageName: selectedChainage.segment_name
})
}
}
const isComplete = selectedProject && selectedPackage && selectedChainage;
const isComplete = selectedProject && selectedPackage && selectedChainage
// Step status helpers
const getStepStatus = (step: number) => {
if (step === 1) return selectedProject ? 'completed' : 'active';
if (step === 2) return selectedPackage ? 'completed' : selectedProject ? 'active' : 'pending';
if (step === 3) return selectedChainage ? 'completed' : selectedPackage ? 'active' : 'pending';
return 'pending';
};
// Step status helpers
const getStepStatus = (step: number) => {
if (step === 1) return selectedProject ? 'completed' : 'active'
if (step === 2) return selectedPackage ? 'completed' : selectedProject ? 'active' : 'pending'
if (step === 3) return selectedChainage ? 'completed' : selectedPackage ? 'active' : 'pending'
return 'pending'
}
return (
<Card className="overflow-hidden">
<CardHeader className="pb-6">
<div className="flex flex-col gap-6">
<div>
<CardTitle className="text-2xl font-bold">Select Project Chainage</CardTitle>
<CardDescription className="mt-2 text-base">
Select Project, Package & Chainage to begin intelligent road analysis.
</CardDescription>
</div>
return (
<Card className="overflow-hidden">
<CardHeader className="pb-6">
<div className="flex flex-col gap-6">
<div>
<CardTitle className="text-2xl font-bold">Select Project Chainage</CardTitle>
<CardDescription className="mt-2 text-base">
Select Project, Package & Chainage to begin intelligent road analysis.
</CardDescription>
</div>
{/* Step Progress Indicator */}
<div className="flex items-center justify-center pt-2">
{[1, 2, 3].map((step, index) => {
const status = getStepStatus(step)
const labels = ['Project', 'Package', 'Chainage']
return (
<div key={step} className="flex items-center">
<div className="flex flex-col items-center">
<div
className={cn(
"w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all",
status === 'completed' ? "bg-primary text-primary-foreground" :
status === 'active' ? "bg-primary text-primary-foreground ring-4 ring-primary/10" :
"bg-muted text-muted-foreground"
)}
>
{status === 'completed' ? <Check className="h-5 w-5" /> : step}
</div>
<span className={cn(
"text-xs mt-2 font-medium",
status === 'pending' ? "text-muted-foreground/60" : "text-foreground"
)}>
{labels[index]}
</span>
</div>
{index < 2 && (
<div className={cn(
"w-16 h-0.5 mx-2 mb-6 rounded-full",
getStepStatus(step + 1) !== 'pending' ? "bg-primary" : "bg-border"
)} />
)}
</div>
)
})}
{/* Step Progress Indicator */}
<div className="flex items-center justify-center pt-2">
{[1, 2, 3].map((step, index) => {
const status = getStepStatus(step);
const labels = ['Project', 'Package', 'Chainage'];
return (
<div key={step} className="flex items-center">
<div className="flex flex-col items-center">
<div
className={cn(
'w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all',
status === 'completed'
? 'bg-primary text-primary-foreground'
: status === 'active'
? 'bg-primary text-primary-foreground ring-4 ring-primary/10'
: 'bg-muted text-muted-foreground',
)}
>
{status === 'completed' ? <Check className="h-5 w-5" /> : step}
</div>
<span
className={cn(
'text-xs mt-2 font-medium',
status === 'pending' ? 'text-muted-foreground/60' : 'text-foreground',
)}
>
{labels[index]}
</span>
</div>
{index < 2 && (
<div
className={cn(
'w-16 h-0.5 mx-2 mb-6 rounded-full',
getStepStatus(step + 1) !== 'pending' ? 'bg-primary' : 'bg-border',
)}
/>
)}
</div>
</CardHeader>
);
})}
</div>
</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>
<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>
<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">
<span>{chn.segment_name}</span>
<span className="text-[10px] text-muted-foreground">
{chn.chainage_start_km}-{chn.chainage_end_km} km | {chn.direction}
</span>
</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">{selectedChainage?.segment_name}</span>
</div>
</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>
{/* 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>
</Card>
)
{/* 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">
<span>{chn.segment_name}</span>
<span className="text-[10px] text-muted-foreground">
{chn.chainage_start_km}-{chn.chainage_end_km} km | {chn.direction}
</span>
</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">{selectedChainage?.segment_name}</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>
</Card>
);
}

View File

@@ -1,11 +1,11 @@
"use client"
'use client';
import * as React from "react"
import { ThemeProvider as NextThemesProvider } from "next-themes"
import * as React from 'react';
import { ThemeProvider as NextThemesProvider } from 'next-themes';
export function ThemeProvider({
children,
...props
}: React.ComponentProps<typeof NextThemesProvider>) {
return <NextThemesProvider {...props}>{children}</NextThemesProvider>
return <NextThemesProvider {...props}>{children}</NextThemesProvider>;
}

View File

@@ -1,37 +1,28 @@
"use client"
'use client';
import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"
import * as React from 'react';
import * as AvatarPrimitive from '@radix-ui/react-avatar';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Avatar({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return (
<AvatarPrimitive.Root
data-slot="avatar"
className={cn(
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
className={cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', className)}
{...props}
/>
)
);
}
function AvatarImage({
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return (
<AvatarPrimitive.Image
data-slot="avatar-image"
className={cn("aspect-square size-full", className)}
className={cn('aspect-square size-full', className)}
{...props}
/>
)
);
}
function AvatarFallback({
@@ -41,13 +32,10 @@ function AvatarFallback({
return (
<AvatarPrimitive.Fallback
data-slot="avatar-fallback"
className={cn(
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
className={cn('bg-muted flex size-full items-center justify-center rounded-full', className)}
{...props}
/>
)
);
}
export { Avatar, AvatarImage, AvatarFallback }
export { Avatar, AvatarImage, AvatarFallback };

View File

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

View File

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

View File

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

View File

@@ -1,92 +1,75 @@
import * as React from "react"
import * as React from 'react';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Card({ className, ...props }: React.ComponentProps<"div">) {
function Card({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card"
className={cn(
"flex flex-col gap-6 rounded-xl border bg-card backdrop-blur-xl py-6 text-card-foreground",
className
'flex flex-col gap-6 rounded-xl border bg-card backdrop-blur-xl py-6 text-card-foreground',
className,
)}
{...props}
/>
)
);
}
function CardHeader({ className, ...props }: React.ComponentProps<"div">) {
function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-header"
className={cn(
"@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",
className
'@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6',
className,
)}
{...props}
/>
)
);
}
function CardTitle({ className, ...props }: React.ComponentProps<"div">) {
function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-title"
className={cn("leading-none font-semibold", className)}
className={cn('leading-none font-semibold', className)}
{...props}
/>
)
);
}
function CardDescription({ className, ...props }: React.ComponentProps<"div">) {
function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
)
);
}
function CardAction({ className, ...props }: React.ComponentProps<"div">) {
function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-action"
className={cn(
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
{...props}
/>
)
);
}
function CardContent({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
data-slot="card-content"
className={cn("px-6", className)}
{...props}
/>
)
function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
return <div data-slot="card-content" className={cn('px-6', className)} {...props} />;
}
function CardFooter({ className, ...props }: React.ComponentProps<"div">) {
function CardFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="card-footer"
className={cn("flex items-center px-6 [.border-t]:pt-6", className)}
className={cn('flex items-center px-6 [.border-t]:pt-6', className)}
{...props}
/>
)
);
}
export {
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}
export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };

View File

@@ -1,37 +1,37 @@
'use client'
'use client';
import * as React from 'react'
import * as RechartsPrimitive from 'recharts'
import * as React from 'react';
import * as RechartsPrimitive from 'recharts';
import { cn } from '@/lib/utils'
import { cn } from '@/lib/utils';
// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: '', dark: '.dark' } as const
const THEMES = { light: '', dark: '.dark' } as const;
export type ChartConfig = {
[k in string]: {
label?: React.ReactNode
icon?: React.ComponentType
label?: React.ReactNode;
icon?: React.ComponentType;
} & (
| { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> }
)
}
);
};
type ChartContextProps = {
config: ChartConfig
}
config: ChartConfig;
};
const ChartContext = React.createContext<ChartContextProps | null>(null)
const ChartContext = React.createContext<ChartContextProps | null>(null);
function useChart() {
const context = React.useContext(ChartContext)
const context = React.useContext(ChartContext);
if (!context) {
throw new Error('useChart must be used within a <ChartContainer />')
throw new Error('useChart must be used within a <ChartContainer />');
}
return context
return context;
}
function ChartContainer({
@@ -41,13 +41,11 @@ function ChartContainer({
config,
...props
}: React.ComponentProps<'div'> & {
config: ChartConfig
children: React.ComponentProps<
typeof RechartsPrimitive.ResponsiveContainer
>['children']
config: ChartConfig;
children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>['children'];
}) {
const uniqueId = React.useId()
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`
const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`;
return (
<ChartContext.Provider value={{ config }}>
@@ -61,21 +59,17 @@ function ChartContainer({
{...props}
>
<ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
<RechartsPrimitive.ResponsiveContainer>{children}</RechartsPrimitive.ResponsiveContainer>
</div>
</ChartContext.Provider>
)
);
}
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter(
([, config]) => config.theme || config.color,
)
const colorConfig = Object.entries(config).filter(([, config]) => config.theme || config.color);
if (!colorConfig.length) {
return null
return null;
}
return (
@@ -87,10 +81,8 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] ||
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.color;
return color ? ` --color-${key}: ${color};` : null;
})
.join('\n')}
}
@@ -99,10 +91,10 @@ ${colorConfig
.join('\n'),
}}
/>
)
}
);
};
const ChartTooltip = RechartsPrimitive.Tooltip
const ChartTooltip = RechartsPrimitive.Tooltip;
function ChartTooltipContent({
active,
@@ -120,55 +112,45 @@ function ChartTooltipContent({
labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<'div'> & {
hideLabel?: boolean
hideIndicator?: boolean
indicator?: 'line' | 'dot' | 'dashed'
nameKey?: string
labelKey?: string
hideLabel?: boolean;
hideIndicator?: boolean;
indicator?: 'line' | 'dot' | 'dashed';
nameKey?: string;
labelKey?: string;
}) {
const { config } = useChart()
const { config } = useChart();
const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) {
return null
return null;
}
const [item] = payload
const key = `${labelKey || item?.dataKey || item?.name || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const [item] = payload;
const key = `${labelKey || item?.dataKey || item?.name || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value =
!labelKey && typeof label === 'string'
? config[label as keyof typeof config]?.label || label
: itemConfig?.label
: itemConfig?.label;
if (labelFormatter) {
return (
<div className={cn('font-medium', labelClassName)}>
{labelFormatter(value, payload)}
</div>
)
<div className={cn('font-medium', labelClassName)}>{labelFormatter(value, payload)}</div>
);
}
if (!value) {
return null
return null;
}
return <div className={cn('font-medium', labelClassName)}>{value}</div>
}, [
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
return <div className={cn('font-medium', labelClassName)}>{value}</div>;
}, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey]);
if (!active || !payload?.length) {
return null
return null;
}
const nestLabel = payload.length === 1 && indicator !== 'dot'
const nestLabel = payload.length === 1 && indicator !== 'dot';
return (
<div
@@ -180,9 +162,9 @@ function ChartTooltipContent({
{!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5">
{payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const indicatorColor = color || item.payload.fill || item.color
const key = `${nameKey || item.name || item.dataKey || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color || item.payload.fill || item.color;
return (
<div
@@ -241,14 +223,14 @@ function ChartTooltipContent({
</>
)}
</div>
)
);
})}
</div>
</div>
)
);
}
const ChartLegend = RechartsPrimitive.Legend
const ChartLegend = RechartsPrimitive.Legend;
function ChartLegendContent({
className,
@@ -258,13 +240,13 @@ function ChartLegendContent({
nameKey,
}: React.ComponentProps<'div'> &
Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & {
hideIcon?: boolean
nameKey?: string
hideIcon?: boolean;
nameKey?: string;
}) {
const { config } = useChart()
const { config } = useChart();
if (!payload?.length) {
return null
return null;
}
return (
@@ -276,8 +258,8 @@ function ChartLegendContent({
)}
>
{payload.map((item) => {
const key = `${nameKey || item.dataKey || 'value'}`
const itemConfig = getPayloadConfigFromPayload(config, item, key)
const key = `${nameKey || item.dataKey || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key);
return (
<div
@@ -298,49 +280,36 @@ function ChartLegendContent({
)}
{itemConfig?.label}
</div>
)
);
})}
</div>
)
);
}
// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
config: ChartConfig,
payload: unknown,
key: string,
) {
function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
if (typeof payload !== 'object' || payload === null) {
return undefined
return undefined;
}
const payloadPayload =
'payload' in payload &&
typeof payload.payload === 'object' &&
payload.payload !== null
'payload' in payload && typeof payload.payload === 'object' && payload.payload !== null
? payload.payload
: undefined
: undefined;
let configLabelKey: string = key
let configLabelKey: string = key;
if (
key in payload &&
typeof payload[key as keyof typeof payload] === 'string'
) {
configLabelKey = payload[key as keyof typeof payload] as string
if (key in payload && typeof payload[key as keyof typeof payload] === 'string') {
configLabelKey = payload[key as keyof typeof payload] as string;
} else if (
payloadPayload &&
key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
) {
configLabelKey = payloadPayload[
key as keyof typeof payloadPayload
] as string
configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string;
}
return configLabelKey in config
? config[configLabelKey]
: config[key as keyof typeof config]
return configLabelKey in config ? config[configLabelKey] : config[key as keyof typeof config];
}
export {
@@ -350,4 +319,4 @@ export {
ChartLegend,
ChartLegendContent,
ChartStyle,
}
};

View File

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

View File

@@ -1,34 +1,26 @@
"use client"
'use client';
import * as React from "react"
import { XIcon } from "lucide-react"
import { Dialog as DialogPrimitive } from "radix-ui"
import * as React from 'react';
import { XIcon } from 'lucide-react';
import { Dialog as DialogPrimitive } from 'radix-ui';
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
function Dialog({
...props
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}
function DialogTrigger({
...props
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}
function DialogPortal({
...props
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}
function DialogClose({
...props
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}
function DialogOverlay({
@@ -39,12 +31,12 @@ function DialogOverlay({
<DialogPrimitive.Overlay
data-slot="dialog-overlay"
className={cn(
"fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0",
className
'fixed inset-0 z-50 bg-black/50 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:animate-in data-[state=open]:fade-in-0',
className,
)}
{...props}
/>
)
);
}
function DialogContent({
@@ -53,7 +45,7 @@ function DialogContent({
showCloseButton = true,
...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean
showCloseButton?: boolean;
}) {
return (
<DialogPortal data-slot="dialog-portal">
@@ -61,8 +53,8 @@ function DialogContent({
<DialogPrimitive.Content
data-slot="dialog-content"
className={cn(
"fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg",
className
'fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border bg-background p-6 shadow-lg duration-200 outline-none data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95 sm:max-w-lg',
className,
)}
{...props}
>
@@ -78,17 +70,17 @@ function DialogContent({
)}
</DialogPrimitive.Content>
</DialogPortal>
)
);
}
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) {
function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="dialog-header"
className={cn("flex flex-col gap-2 text-center sm:text-left", className)}
className={cn('flex flex-col gap-2 text-center sm:text-left', className)}
{...props}
/>
)
);
}
function DialogFooter({
@@ -96,16 +88,13 @@ function DialogFooter({
showCloseButton = false,
children,
...props
}: React.ComponentProps<"div"> & {
showCloseButton?: boolean
}: React.ComponentProps<'div'> & {
showCloseButton?: boolean;
}) {
return (
<div
data-slot="dialog-footer"
className={cn(
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
{...props}
>
{children}
@@ -115,20 +104,17 @@ function DialogFooter({
</DialogPrimitive.Close>
)}
</div>
)
);
}
function DialogTitle({
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
return (
<DialogPrimitive.Title
data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)}
className={cn('text-lg leading-none font-semibold', className)}
{...props}
/>
)
);
}
function DialogDescription({
@@ -138,10 +124,10 @@ function DialogDescription({
return (
<DialogPrimitive.Description
data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)}
className={cn('text-sm text-muted-foreground', className)}
{...props}
/>
)
);
}
export {
@@ -155,4 +141,4 @@ export {
DialogPortal,
DialogTitle,
DialogTrigger,
}
};

View File

@@ -1,34 +1,25 @@
"use client";
'use client';
import * as React from "react";
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react";
import * as React from 'react';
import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';
import { cn } from "@/lib/utils";
import { cn } from '@/lib/utils';
function DropdownMenu({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
}
function DropdownMenuPortal({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return (
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
);
return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
}
function DropdownMenuTrigger({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return (
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
);
return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
}
function DropdownMenuContent({
@@ -42,8 +33,8 @@ function DropdownMenuContent({
data-slot="dropdown-menu-content"
sideOffset={sideOffset}
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md",
className
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 max-h-(--radix-dropdown-menu-content-available-height) min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border p-1 shadow-md',
className,
)}
{...props}
/>
@@ -51,22 +42,18 @@ function DropdownMenuContent({
);
}
function DropdownMenuGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
);
function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
}
function DropdownMenuItem({
className,
inset,
variant = "default",
variant = 'default',
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean;
variant?: "default" | "destructive";
variant?: 'default' | 'destructive';
}) {
return (
<DropdownMenuPrimitive.Item
@@ -75,7 +62,7 @@ function DropdownMenuItem({
data-variant={variant}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[variant=destructive]:text-destructive data-[variant=destructive]:focus:bg-destructive/10 dark:data-[variant=destructive]:focus:bg-destructive/20 data-[variant=destructive]:focus:text-destructive data-[variant=destructive]:*:[svg]:!text-destructive [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
/>
@@ -93,7 +80,7 @@ function DropdownMenuCheckboxItem({
data-slot="dropdown-menu-checkbox-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
checked={checked}
{...props}
@@ -111,12 +98,7 @@ function DropdownMenuCheckboxItem({
function DropdownMenuRadioGroup({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return (
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
);
return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
}
function DropdownMenuRadioItem({
@@ -129,7 +111,7 @@ function DropdownMenuRadioItem({
data-slot="dropdown-menu-radio-item"
className={cn(
"focus:bg-accent focus:text-accent-foreground relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
@@ -154,10 +136,7 @@ function DropdownMenuLabel({
<DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label"
data-inset={inset}
className={cn(
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}
{...props}
/>
);
@@ -170,31 +149,23 @@ function DropdownMenuSeparator({
return (
<DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-separator"
className={cn("bg-border -mx-1 my-1 h-px", className)}
className={cn('bg-border -mx-1 my-1 h-px', className)}
{...props}
/>
);
}
function DropdownMenuShortcut({
className,
...props
}: React.ComponentProps<"span">) {
function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
data-slot="dropdown-menu-shortcut"
className={cn(
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
{...props}
/>
);
}
function DropdownMenuSub({
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
}
@@ -212,7 +183,7 @@ function DropdownMenuSubTrigger({
data-inset={inset}
className={cn(
"focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",
className
className,
)}
{...props}
>
@@ -230,8 +201,8 @@ function DropdownMenuSubContent({
<DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content"
className={cn(
"bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg",
className
'bg-popover text-popover-foreground data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 min-w-[8rem] origin-(--radix-dropdown-menu-content-transform-origin) overflow-hidden rounded-md border p-1 shadow-lg',
className,
)}
{...props}
/>

View File

@@ -1,21 +1,21 @@
import * as React from "react"
import * as React from 'react';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
function Input({ className, type, ...props }: React.ComponentProps<'input'>) {
return (
<input
type={type}
data-slot="input"
className={cn(
"file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
"focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]",
"aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",
className
'file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground dark:bg-input/30 border-input h-9 w-full min-w-0 rounded-md border bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm',
'focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]',
'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive',
className,
)}
{...props}
/>
)
);
}
export { Input }
export { Input };

View File

@@ -1,14 +1,11 @@
'use client'
'use client';
import * as React from 'react'
import * as LabelPrimitive from '@radix-ui/react-label'
import * as React from 'react';
import * as LabelPrimitive from '@radix-ui/react-label';
import { cn } from '@/lib/utils'
import { cn } from '@/lib/utils';
function Label({
className,
...props
}: React.ComponentProps<typeof LabelPrimitive.Root>) {
function Label({ className, ...props }: React.ComponentProps<typeof LabelPrimitive.Root>) {
return (
<LabelPrimitive.Root
data-slot="label"
@@ -18,7 +15,7 @@ function Label({
)}
{...props}
/>
)
);
}
export { Label }
export { Label };

View File

@@ -1,12 +1,8 @@
import * as React from 'react'
import {
ChevronLeftIcon,
ChevronRightIcon,
MoreHorizontalIcon,
} from 'lucide-react'
import * as React from 'react';
import { ChevronLeftIcon, ChevronRightIcon, MoreHorizontalIcon } from 'lucide-react';
import { cn } from '@/lib/utils'
import { Button, buttonVariants } from '@/components/ui/button'
import { cn } from '@/lib/utils';
import { Button, buttonVariants } from '@/components/ui/button';
function Pagination({ className, ...props }: React.ComponentProps<'nav'>) {
return (
@@ -17,37 +13,29 @@ function Pagination({ className, ...props }: React.ComponentProps<'nav'>) {
className={cn('mx-auto flex w-full justify-center', className)}
{...props}
/>
)
);
}
function PaginationContent({
className,
...props
}: React.ComponentProps<'ul'>) {
function PaginationContent({ className, ...props }: React.ComponentProps<'ul'>) {
return (
<ul
data-slot="pagination-content"
className={cn('flex flex-row items-center gap-1', className)}
{...props}
/>
)
);
}
function PaginationItem({ ...props }: React.ComponentProps<'li'>) {
return <li data-slot="pagination-item" {...props} />
return <li data-slot="pagination-item" {...props} />;
}
type PaginationLinkProps = {
isActive?: boolean
isActive?: boolean;
} & Pick<React.ComponentProps<typeof Button>, 'size'> &
React.ComponentProps<'a'>
React.ComponentProps<'a'>;
function PaginationLink({
className,
isActive,
size = 'icon',
...props
}: PaginationLinkProps) {
function PaginationLink({ className, isActive, size = 'icon', ...props }: PaginationLinkProps) {
return (
<a
aria-current={isActive ? 'page' : undefined}
@@ -62,13 +50,10 @@ function PaginationLink({
)}
{...props}
/>
)
);
}
function PaginationPrevious({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
function PaginationPrevious({ className, ...props }: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to previous page"
@@ -79,13 +64,10 @@ function PaginationPrevious({
<ChevronLeftIcon />
<span className="hidden sm:block">Previous</span>
</PaginationLink>
)
);
}
function PaginationNext({
className,
...props
}: React.ComponentProps<typeof PaginationLink>) {
function PaginationNext({ className, ...props }: React.ComponentProps<typeof PaginationLink>) {
return (
<PaginationLink
aria-label="Go to next page"
@@ -96,13 +78,10 @@ function PaginationNext({
<span className="hidden sm:block">Next</span>
<ChevronRightIcon />
</PaginationLink>
)
);
}
function PaginationEllipsis({
className,
...props
}: React.ComponentProps<'span'>) {
function PaginationEllipsis({ className, ...props }: React.ComponentProps<'span'>) {
return (
<span
aria-hidden
@@ -113,7 +92,7 @@ function PaginationEllipsis({
<MoreHorizontalIcon className="size-4" />
<span className="sr-only">More pages</span>
</span>
)
);
}
export {
@@ -124,4 +103,4 @@ export {
PaginationPrevious,
PaginationNext,
PaginationEllipsis,
}
};

View File

@@ -1,25 +1,21 @@
"use client"
'use client';
import * as React from "react"
import { Popover as PopoverPrimitive } from "radix-ui"
import * as React from 'react';
import { Popover as PopoverPrimitive } from 'radix-ui';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Popover({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}
function PopoverTrigger({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverContent({
className,
align = "center",
align = 'center',
sideOffset = 4,
...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) {
@@ -30,52 +26,41 @@ function PopoverContent({
align={align}
sideOffset={sideOffset}
className={cn(
"z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
className
'z-50 w-72 origin-(--radix-popover-content-transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
className,
)}
{...props}
/>
</PopoverPrimitive.Portal>
)
);
}
function PopoverAnchor({
...props
}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
}
function PopoverHeader({ className, ...props }: React.ComponentProps<"div">) {
function PopoverHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="popover-header"
className={cn("flex flex-col gap-1 text-sm", className)}
className={cn('flex flex-col gap-1 text-sm', className)}
{...props}
/>
)
);
}
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) {
return (
<div
data-slot="popover-title"
className={cn("font-medium", className)}
{...props}
/>
)
function PopoverTitle({ className, ...props }: React.ComponentProps<'h2'>) {
return <div data-slot="popover-title" className={cn('font-medium', className)} {...props} />;
}
function PopoverDescription({
className,
...props
}: React.ComponentProps<"p">) {
function PopoverDescription({ className, ...props }: React.ComponentProps<'p'>) {
return (
<p
data-slot="popover-description"
className={cn("text-muted-foreground", className)}
className={cn('text-muted-foreground', className)}
{...props}
/>
)
);
}
export {
@@ -86,4 +71,4 @@ export {
PopoverHeader,
PopoverTitle,
PopoverDescription,
}
};

View File

@@ -1,9 +1,9 @@
'use client'
'use client';
import * as React from 'react'
import * as ProgressPrimitive from '@radix-ui/react-progress'
import * as React from 'react';
import * as ProgressPrimitive from '@radix-ui/react-progress';
import { cn } from '@/lib/utils'
import { cn } from '@/lib/utils';
function Progress({
className,
@@ -13,10 +13,7 @@ function Progress({
return (
<ProgressPrimitive.Root
data-slot="progress"
className={cn(
'bg-primary/20 relative h-2 w-full overflow-hidden rounded-full',
className,
)}
className={cn('bg-primary/20 relative h-2 w-full overflow-hidden rounded-full', className)}
{...props}
>
<ProgressPrimitive.Indicator
@@ -25,7 +22,7 @@ function Progress({
style={{ transform: `translateX(-${100 - (value || 0)}%)` }}
/>
</ProgressPrimitive.Root>
)
);
}
export { Progress }
export { Progress };

View File

@@ -1,12 +1,12 @@
"use client";
'use client';
import { motion, type HTMLMotionProps } from "motion/react";
import React from "react";
import { motion, type HTMLMotionProps } from 'motion/react';
import React from 'react';
interface RevealProps extends HTMLMotionProps<"div"> {
interface RevealProps extends HTMLMotionProps<'div'> {
children: React.ReactNode;
delay?: number;
direction?: "up" | "down" | "left" | "right" | "none";
direction?: 'up' | 'down' | 'left' | 'right' | 'none';
duration?: number;
distance?: number;
}
@@ -14,7 +14,7 @@ interface RevealProps extends HTMLMotionProps<"div"> {
export function Reveal({
children,
delay = 0,
direction = "up",
direction = 'up',
duration = 0.5,
distance = 20,
className,
@@ -32,10 +32,10 @@ export function Reveal({
<motion.div
initial={{
opacity: 0,
...(direction !== "none" ? offsets[direction] : {})
...(direction !== 'none' ? offsets[direction] : {}),
}}
whileInView={{ opacity: 1, x: 0, y: 0 }}
viewport={{ once: true, margin: "-50px" }}
viewport={{ once: true, margin: '-50px' }}
transition={{
duration,
delay,
@@ -49,7 +49,7 @@ export function Reveal({
);
}
interface StaggerContainerProps extends HTMLMotionProps<"div"> {
interface StaggerContainerProps extends HTMLMotionProps<'div'> {
children: React.ReactNode;
staggerChildren?: number;
delayChildren?: number;
@@ -66,7 +66,7 @@ export function StaggerContainer({
<motion.div
initial="hidden"
whileInView="show"
viewport={{ once: true, margin: "-50px" }}
viewport={{ once: true, margin: '-50px' }}
variants={{
hidden: { opacity: 0 },
show: {
@@ -87,7 +87,7 @@ export function StaggerContainer({
export function StaggerItem({
children,
direction = "up",
direction = 'up',
distance = 20,
className,
...props
@@ -105,7 +105,7 @@ export function StaggerItem({
variants={{
hidden: {
opacity: 0,
...(direction !== "none" ? offsets[direction] : {})
...(direction !== 'none' ? offsets[direction] : {}),
},
show: { opacity: 1, x: 0, y: 0 },
}}

View File

@@ -1,9 +1,9 @@
"use client"
'use client';
import * as React from "react"
import { ScrollArea as ScrollAreaPrimitive } from "radix-ui"
import * as React from 'react';
import { ScrollArea as ScrollAreaPrimitive } from 'radix-ui';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function ScrollArea({
className,
@@ -13,7 +13,7 @@ function ScrollArea({
return (
<ScrollAreaPrimitive.Root
data-slot="scroll-area"
className={cn("relative", className)}
className={cn('relative', className)}
{...props}
>
<ScrollAreaPrimitive.Viewport
@@ -25,12 +25,12 @@ function ScrollArea({
<ScrollBar />
<ScrollAreaPrimitive.Corner />
</ScrollAreaPrimitive.Root>
)
);
}
function ScrollBar({
className,
orientation = "vertical",
orientation = 'vertical',
...props
}: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
return (
@@ -38,12 +38,10 @@ function ScrollBar({
data-slot="scroll-area-scrollbar"
orientation={orientation}
className={cn(
"flex touch-none p-px transition-colors select-none",
orientation === "vertical" &&
"h-full w-2.5 border-l border-l-transparent",
orientation === "horizontal" &&
"h-2.5 flex-col border-t border-t-transparent",
className
'flex touch-none p-px transition-colors select-none',
orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent',
orientation === 'horizontal' && 'h-2.5 flex-col border-t border-t-transparent',
className,
)}
{...props}
>
@@ -52,7 +50,7 @@ function ScrollBar({
className="relative flex-1 rounded-full bg-border"
/>
</ScrollAreaPrimitive.ScrollAreaScrollbar>
)
);
}
export { ScrollArea, ScrollBar }
export { ScrollArea, ScrollBar };

View File

@@ -1,36 +1,30 @@
"use client"
'use client';
import * as React from "react"
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
import { Select as SelectPrimitive } from "radix-ui"
import * as React from 'react';
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
import { Select as SelectPrimitive } from 'radix-ui';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Select({
...props
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />;
}
function SelectGroup({
...props
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />;
}
function SelectValue({
...props
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}
function SelectTrigger({
className,
size = "default",
size = 'default',
children,
...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default"
size?: 'sm' | 'default';
}) {
return (
<SelectPrimitive.Trigger
@@ -38,7 +32,7 @@ function SelectTrigger({
data-size={size}
className={cn(
"flex h-9 w-full min-w-0 items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground",
className
className,
)}
{...props}
>
@@ -47,14 +41,14 @@ function SelectTrigger({
<ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon>
</SelectPrimitive.Trigger>
)
);
}
function SelectContent({
className,
children,
position = "item-aligned",
align = "center",
position = 'item-aligned',
align = 'center',
...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) {
return (
@@ -62,10 +56,10 @@ function SelectContent({
<SelectPrimitive.Content
data-slot="select-content"
className={cn(
"relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95",
position === "popper" &&
"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
className
'relative z-50 max-h-(--radix-select-content-available-height) min-w-[8rem] origin-(--radix-select-content-transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[state=open]:animate-in data-[state=open]:fade-in-0 data-[state=open]:zoom-in-95',
position === 'popper' &&
'data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1',
className,
)}
position={position}
align={align}
@@ -74,9 +68,9 @@ function SelectContent({
<SelectScrollUpButton />
<SelectPrimitive.Viewport
className={cn(
"p-1",
position === "popper" &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1"
'p-1',
position === 'popper' &&
'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1',
)}
>
{children}
@@ -84,20 +78,17 @@ function SelectContent({
<SelectScrollDownButton />
</SelectPrimitive.Content>
</SelectPrimitive.Portal>
)
);
}
function SelectLabel({
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
return (
<SelectPrimitive.Label
data-slot="select-label"
className={cn("px-2 py-1.5 text-xs text-muted-foreground", className)}
className={cn('px-2 py-1.5 text-xs text-muted-foreground', className)}
{...props}
/>
)
);
}
function SelectItem({
@@ -110,7 +101,7 @@ function SelectItem({
data-slot="select-item"
className={cn(
"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2",
className
className,
)}
{...props}
>
@@ -124,7 +115,7 @@ function SelectItem({
</span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item>
)
);
}
function SelectSeparator({
@@ -134,10 +125,10 @@ function SelectSeparator({
return (
<SelectPrimitive.Separator
data-slot="select-separator"
className={cn("pointer-events-none -mx-1 my-1 h-px bg-border", className)}
className={cn('pointer-events-none -mx-1 my-1 h-px bg-border', className)}
{...props}
/>
)
);
}
function SelectScrollUpButton({
@@ -147,15 +138,12 @@ function SelectScrollUpButton({
return (
<SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton>
)
);
}
function SelectScrollDownButton({
@@ -165,15 +153,12 @@ function SelectScrollDownButton({
return (
<SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button"
className={cn(
"flex cursor-default items-center justify-center py-1",
className
)}
className={cn('flex cursor-default items-center justify-center py-1', className)}
{...props}
>
<ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton>
)
);
}
export {
@@ -187,4 +172,4 @@ export {
SelectSeparator,
SelectTrigger,
SelectValue,
}
};

View File

@@ -1,13 +1,13 @@
"use client"
'use client';
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"
import * as React from 'react';
import * as SeparatorPrimitive from '@radix-ui/react-separator';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Separator({
className,
orientation = "horizontal",
orientation = 'horizontal',
decorative = true,
...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
@@ -17,12 +17,12 @@ function Separator({
decorative={decorative}
orientation={orientation}
className={cn(
"bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px",
className
'bg-border shrink-0 data-[orientation=horizontal]:h-px data-[orientation=horizontal]:w-full data-[orientation=vertical]:h-full data-[orientation=vertical]:w-px',
className,
)}
{...props}
/>
)
);
}
export { Separator }
export { Separator };

View File

@@ -1,31 +1,25 @@
"use client"
'use client';
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { XIcon } from "lucide-react"
import * as React from 'react';
import * as SheetPrimitive from '@radix-ui/react-dialog';
import { XIcon } from 'lucide-react';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} />
return <SheetPrimitive.Root data-slot="sheet" {...props} />;
}
function SheetTrigger({
...props
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}
function SheetClose({
...props
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}
function SheetPortal({
...props
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}
function SheetOverlay({
@@ -36,21 +30,21 @@ function SheetOverlay({
<SheetPrimitive.Overlay
data-slot="sheet-overlay"
className={cn(
"data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50",
className
'data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/50',
className,
)}
{...props}
/>
)
);
}
function SheetContent({
className,
children,
side = "right",
side = 'right',
...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left"
side?: 'top' | 'right' | 'bottom' | 'left';
}) {
return (
<SheetPortal>
@@ -58,16 +52,16 @@ function SheetContent({
<SheetPrimitive.Content
data-slot="sheet-content"
className={cn(
"bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500",
side === "right" &&
"data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm",
side === "left" &&
"data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm",
side === "top" &&
"data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b",
side === "bottom" &&
"data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t",
className
'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out fixed z-50 flex flex-col gap-4 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500',
side === 'right' &&
'data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right inset-y-0 right-0 h-full w-3/4 border-l sm:max-w-sm',
side === 'left' &&
'data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left inset-y-0 left-0 h-full w-3/4 border-r sm:max-w-sm',
side === 'top' &&
'data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top inset-x-0 top-0 h-auto border-b',
side === 'bottom' &&
'data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t',
className,
)}
{...props}
>
@@ -78,40 +72,37 @@ function SheetContent({
</SheetPrimitive.Close>
</SheetPrimitive.Content>
</SheetPortal>
)
);
}
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) {
function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-header"
className={cn("flex flex-col gap-1.5 p-4", className)}
className={cn('flex flex-col gap-1.5 p-4', className)}
{...props}
/>
)
);
}
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) {
function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sheet-footer"
className={cn("mt-auto flex flex-col gap-2 p-4", className)}
className={cn('mt-auto flex flex-col gap-2 p-4', className)}
{...props}
/>
)
);
}
function SheetTitle({
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
return (
<SheetPrimitive.Title
data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)}
className={cn('text-foreground font-semibold', className)}
{...props}
/>
)
);
}
function SheetDescription({
@@ -121,10 +112,10 @@ function SheetDescription({
return (
<SheetPrimitive.Description
data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)}
className={cn('text-muted-foreground text-sm', className)}
{...props}
/>
)
);
}
export {
@@ -136,4 +127,4 @@ export {
SheetFooter,
SheetTitle,
SheetDescription,
}
};

View File

@@ -1,56 +1,51 @@
"use client"
'use client';
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"
import { PanelLeftIcon } from "lucide-react"
import * as React from 'react';
import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from 'class-variance-authority';
import { PanelLeftIcon } from 'lucide-react';
import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import { useIsMobile } from '@/hooks/use-mobile';
import { cn } from '@/lib/utils';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Separator } from '@/components/ui/separator';
import {
Sheet,
SheetContent,
SheetDescription,
SheetHeader,
SheetTitle,
} from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from "@/components/ui/tooltip"
} from '@/components/ui/sheet';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"
const SIDEBAR_COOKIE_NAME = 'sidebar_state';
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7;
const SIDEBAR_WIDTH = '16rem';
const SIDEBAR_WIDTH_MOBILE = '18rem';
const SIDEBAR_WIDTH_ICON = '3rem';
const SIDEBAR_KEYBOARD_SHORTCUT = 'b';
type SidebarContextProps = {
state: "expanded" | "collapsed"
open: boolean
setOpen: (open: boolean) => void
openMobile: boolean
setOpenMobile: (open: boolean) => void
isMobile: boolean
toggleSidebar: () => void
}
state: 'expanded' | 'collapsed';
open: boolean;
setOpen: (open: boolean) => void;
openMobile: boolean;
setOpenMobile: (open: boolean) => void;
isMobile: boolean;
toggleSidebar: () => void;
};
const SidebarContext = React.createContext<SidebarContextProps | null>(null)
const SidebarContext = React.createContext<SidebarContextProps | null>(null);
function useSidebar() {
const context = React.useContext(SidebarContext)
const context = React.useContext(SidebarContext);
if (!context) {
throw new Error("useSidebar must be used within a SidebarProvider.")
throw new Error('useSidebar must be used within a SidebarProvider.');
}
return context
return context;
}
function SidebarProvider({
@@ -61,57 +56,54 @@ function SidebarProvider({
style,
children,
...props
}: React.ComponentProps<"div"> & {
defaultOpen?: boolean
open?: boolean
onOpenChange?: (open: boolean) => void
}: React.ComponentProps<'div'> & {
defaultOpen?: boolean;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
const isMobile = useIsMobile()
const [openMobile, setOpenMobile] = React.useState(false)
const isMobile = useIsMobile();
const [openMobile, setOpenMobile] = React.useState(false);
// This is the internal state of the sidebar.
// We use openProp and setOpenProp for control from outside the component.
const [_open, _setOpen] = React.useState(defaultOpen)
const open = openProp ?? _open
const [_open, _setOpen] = React.useState(defaultOpen);
const open = openProp ?? _open;
const setOpen = React.useCallback(
(value: boolean | ((value: boolean) => boolean)) => {
const openState = typeof value === "function" ? value(open) : value
const openState = typeof value === 'function' ? value(open) : value;
if (setOpenProp) {
setOpenProp(openState)
setOpenProp(openState);
} else {
_setOpen(openState)
_setOpen(openState);
}
// This sets the cookie to keep the sidebar state.
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`;
},
[setOpenProp, open]
)
[setOpenProp, open],
);
// Helper to toggle the sidebar.
const toggleSidebar = React.useCallback(() => {
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open)
}, [isMobile, setOpen, setOpenMobile])
return isMobile ? setOpenMobile((open) => !open) : setOpen((open) => !open);
}, [isMobile, setOpen, setOpenMobile]);
// Adds a keyboard shortcut to toggle the sidebar.
React.useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (
event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
(event.metaKey || event.ctrlKey)
) {
event.preventDefault()
toggleSidebar()
if (event.key === SIDEBAR_KEYBOARD_SHORTCUT && (event.metaKey || event.ctrlKey)) {
event.preventDefault();
toggleSidebar();
}
}
};
window.addEventListener("keydown", handleKeyDown)
return () => window.removeEventListener("keydown", handleKeyDown)
}, [toggleSidebar])
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, [toggleSidebar]);
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? "expanded" : "collapsed"
const state = open ? 'expanded' : 'collapsed';
const contextValue = React.useMemo<SidebarContextProps>(
() => ({
@@ -123,8 +115,8 @@ function SidebarProvider({
setOpenMobile,
toggleSidebar,
}),
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar]
)
[state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar],
);
return (
<SidebarContext.Provider value={contextValue}>
@@ -133,14 +125,14 @@ function SidebarProvider({
data-slot="sidebar-wrapper"
style={
{
"--sidebar-width": SIDEBAR_WIDTH,
"--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
'--sidebar-width': SIDEBAR_WIDTH,
'--sidebar-width-icon': SIDEBAR_WIDTH_ICON,
...style,
} as React.CSSProperties
}
className={cn(
"group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full",
className
'group/sidebar-wrapper has-data-[variant=inset]:bg-sidebar flex min-h-svh w-full',
className,
)}
{...props}
>
@@ -148,36 +140,36 @@ function SidebarProvider({
</div>
</TooltipProvider>
</SidebarContext.Provider>
)
);
}
function Sidebar({
side = "left",
variant = "sidebar",
collapsible = "offcanvas",
side = 'left',
variant = 'sidebar',
collapsible = 'offcanvas',
className,
children,
...props
}: React.ComponentProps<"div"> & {
side?: "left" | "right"
variant?: "sidebar" | "floating" | "inset"
collapsible?: "offcanvas" | "icon" | "none"
}: React.ComponentProps<'div'> & {
side?: 'left' | 'right';
variant?: 'sidebar' | 'floating' | 'inset';
collapsible?: 'offcanvas' | 'icon' | 'none';
}) {
const { isMobile, state, openMobile, setOpenMobile } = useSidebar()
const { isMobile, state, openMobile, setOpenMobile } = useSidebar();
if (collapsible === "none") {
if (collapsible === 'none') {
return (
<div
data-slot="sidebar"
className={cn(
"bg-sidebar backdrop-blur-xl text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col",
className
'bg-sidebar backdrop-blur-xl text-sidebar-foreground flex h-full w-(--sidebar-width) flex-col',
className,
)}
{...props}
>
{children}
</div>
)
);
}
if (isMobile) {
@@ -190,7 +182,7 @@ function Sidebar({
className="bg-sidebar backdrop-blur-xl text-sidebar-foreground w-(--sidebar-width) p-0 [&>button]:hidden"
style={
{
"--sidebar-width": SIDEBAR_WIDTH_MOBILE,
'--sidebar-width': SIDEBAR_WIDTH_MOBILE,
} as React.CSSProperties
}
side={side}
@@ -202,14 +194,14 @@ function Sidebar({
<div className="flex h-full w-full flex-col">{children}</div>
</SheetContent>
</Sheet>
)
);
}
return (
<div
className="group peer text-sidebar-foreground hidden md:block"
data-state={state}
data-collapsible={state === "collapsed" ? collapsible : ""}
data-collapsible={state === 'collapsed' ? collapsible : ''}
data-variant={variant}
data-side={side}
data-slot="sidebar"
@@ -218,26 +210,26 @@ function Sidebar({
<div
data-slot="sidebar-gap"
className={cn(
"relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",
"group-data-[collapsible=offcanvas]:w-0",
"group-data-[side=right]:rotate-180",
variant === "floating" || variant === "inset"
? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon)"
'relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear',
'group-data-[collapsible=offcanvas]:w-0',
'group-data-[side=right]:rotate-180',
variant === 'floating' || variant === 'inset'
? 'group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4)))]'
: 'group-data-[collapsible=icon]:w-(--sidebar-width-icon)',
)}
/>
<div
data-slot="sidebar-container"
className={cn(
"fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",
side === "left"
? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
: "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
'fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex',
side === 'left'
? 'left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]'
: 'right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]',
// Adjust the padding for floating and inset variants.
variant === "floating" || variant === "inset"
? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]"
: "group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l",
className
variant === 'floating' || variant === 'inset'
? 'p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)+(--spacing(4))+2px)]'
: 'group-data-[collapsible=icon]:w-(--sidebar-width-icon) group-data-[side=left]:border-r group-data-[side=right]:border-l',
className,
)}
{...props}
>
@@ -250,15 +242,11 @@ function Sidebar({
</div>
</div>
</div>
)
);
}
function SidebarTrigger({
className,
onClick,
...props
}: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar()
function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<typeof Button>) {
const { toggleSidebar } = useSidebar();
return (
<Button
@@ -266,21 +254,21 @@ function SidebarTrigger({
data-slot="sidebar-trigger"
variant="ghost"
size="icon"
className={cn("size-7", className)}
className={cn('size-7', className)}
onClick={(event) => {
onClick?.(event)
toggleSidebar()
onClick?.(event);
toggleSidebar();
}}
{...props}
>
<PanelLeftIcon />
<span className="sr-only">Toggle Sidebar</span>
</Button>
)
);
}
function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
const { toggleSidebar } = useSidebar()
function SidebarRail({ className, ...props }: React.ComponentProps<'button'>) {
const { toggleSidebar } = useSidebar();
return (
<button
@@ -291,225 +279,216 @@ function SidebarRail({ className, ...props }: React.ComponentProps<"button">) {
onClick={toggleSidebar}
title="Toggle Sidebar"
className={cn(
"hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex",
"in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize",
"[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
"hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full",
"[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
"[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
className
'hover:after:bg-sidebar-border absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear group-data-[side=left]:-right-4 group-data-[side=right]:left-0 after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] sm:flex',
'in-data-[side=left]:cursor-w-resize in-data-[side=right]:cursor-e-resize',
'[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize',
'hover:group-data-[collapsible=offcanvas]:bg-sidebar group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full',
'[[data-side=left][data-collapsible=offcanvas]_&]:-right-2',
'[[data-side=right][data-collapsible=offcanvas]_&]:-left-2',
className,
)}
{...props}
/>
)
);
}
function SidebarInset({ className, ...props }: React.ComponentProps<"main">) {
function SidebarInset({ className, ...props }: React.ComponentProps<'main'>) {
return (
<main
data-slot="sidebar-inset"
className={cn(
"bg-background relative flex w-full flex-1 flex-col",
"md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2",
className
'bg-background relative flex w-full flex-1 flex-col',
'md:peer-data-[variant=inset]:m-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow-sm md:peer-data-[variant=inset]:peer-data-[state=collapsed]:ml-2',
className,
)}
{...props}
/>
)
);
}
function SidebarInput({
className,
...props
}: React.ComponentProps<typeof Input>) {
function SidebarInput({ className, ...props }: React.ComponentProps<typeof Input>) {
return (
<Input
data-slot="sidebar-input"
data-sidebar="input"
className={cn("bg-background h-8 w-full shadow-none", className)}
className={cn('bg-background h-8 w-full shadow-none', className)}
{...props}
/>
)
);
}
function SidebarHeader({ className, ...props }: React.ComponentProps<"div">) {
function SidebarHeader({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-header"
data-sidebar="header"
className={cn("flex flex-col gap-2 p-2", className)}
className={cn('flex flex-col gap-2 p-2', className)}
{...props}
/>
)
);
}
function SidebarFooter({ className, ...props }: React.ComponentProps<"div">) {
function SidebarFooter({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-footer"
data-sidebar="footer"
className={cn("flex flex-col gap-2 p-2", className)}
className={cn('flex flex-col gap-2 p-2', className)}
{...props}
/>
)
);
}
function SidebarSeparator({
className,
...props
}: React.ComponentProps<typeof Separator>) {
function SidebarSeparator({ className, ...props }: React.ComponentProps<typeof Separator>) {
return (
<Separator
data-slot="sidebar-separator"
data-sidebar="separator"
className={cn("bg-sidebar-border mx-2 w-auto", className)}
className={cn('bg-sidebar-border mx-2 w-auto', className)}
{...props}
/>
)
);
}
function SidebarContent({ className, ...props }: React.ComponentProps<"div">) {
function SidebarContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-content"
data-sidebar="content"
className={cn(
"flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
className
'flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden',
className,
)}
{...props}
/>
)
);
}
function SidebarGroup({ className, ...props }: React.ComponentProps<"div">) {
function SidebarGroup({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-group"
data-sidebar="group"
className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
className={cn('relative flex w-full min-w-0 flex-col p-2', className)}
{...props}
/>
)
);
}
function SidebarGroupLabel({
className,
asChild = false,
...props
}: React.ComponentProps<"div"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "div"
}: React.ComponentProps<'div'> & { asChild?: boolean }) {
const Comp = asChild ? Slot : 'div';
return (
<Comp
data-slot="sidebar-group-label"
data-sidebar="group-label"
className={cn(
"text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
"group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
className
'text-sidebar-foreground/70 ring-sidebar-ring flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium outline-hidden transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',
'group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0',
className,
)}
{...props}
/>
)
);
}
function SidebarGroupAction({
className,
asChild = false,
...props
}: React.ComponentProps<"button"> & { asChild?: boolean }) {
const Comp = asChild ? Slot : "button"
}: React.ComponentProps<'button'> & { asChild?: boolean }) {
const Comp = asChild ? Slot : 'button';
return (
<Comp
data-slot="sidebar-group-action"
data-sidebar="group-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground absolute top-3.5 right-3 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"group-data-[collapsible=icon]:hidden",
className
'after:absolute after:-inset-2 md:after:hidden',
'group-data-[collapsible=icon]:hidden',
className,
)}
{...props}
/>
)
);
}
function SidebarGroupContent({
className,
...props
}: React.ComponentProps<"div">) {
function SidebarGroupContent({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-group-content"
data-sidebar="group-content"
className={cn("w-full text-sm", className)}
className={cn('w-full text-sm', className)}
{...props}
/>
)
);
}
function SidebarMenu({ className, ...props }: React.ComponentProps<"ul">) {
function SidebarMenu({ className, ...props }: React.ComponentProps<'ul'>) {
return (
<ul
data-slot="sidebar-menu"
data-sidebar="menu"
className={cn("flex w-full min-w-0 flex-col gap-1", className)}
className={cn('flex w-full min-w-0 flex-col gap-1', className)}
{...props}
/>
)
);
}
function SidebarMenuItem({ className, ...props }: React.ComponentProps<"li">) {
function SidebarMenuItem({ className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="sidebar-menu-item"
data-sidebar="menu-item"
className={cn("group/menu-item relative", className)}
className={cn('group/menu-item relative', className)}
{...props}
/>
)
);
}
const sidebarMenuButtonVariants = cva(
"peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
'peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-hidden ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-data-[sidebar=menu-action]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-2! [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0',
{
variants: {
variant: {
default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
default: 'hover:bg-sidebar-accent hover:text-sidebar-accent-foreground',
outline:
"bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
'bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]',
},
size: {
default: "h-8 text-sm",
sm: "h-7 text-xs",
lg: "h-12 text-sm group-data-[collapsible=icon]:p-0!",
default: 'h-8 text-sm',
sm: 'h-7 text-xs',
lg: 'h-12 text-sm group-data-[collapsible=icon]:p-0!',
},
},
defaultVariants: {
variant: "default",
size: "default",
variant: 'default',
size: 'default',
},
}
)
},
);
function SidebarMenuButton({
asChild = false,
isActive = false,
variant = "default",
size = "default",
variant = 'default',
size = 'default',
tooltip,
className,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
isActive?: boolean
tooltip?: string | React.ComponentProps<typeof TooltipContent>
}: React.ComponentProps<'button'> & {
asChild?: boolean;
isActive?: boolean;
tooltip?: string | React.ComponentProps<typeof TooltipContent>;
} & VariantProps<typeof sidebarMenuButtonVariants>) {
const Comp = asChild ? Slot : "button"
const { isMobile, state } = useSidebar()
const Comp = asChild ? Slot : 'button';
const { isMobile, state } = useSidebar();
const button = (
<Comp
@@ -520,16 +499,16 @@ function SidebarMenuButton({
className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
{...props}
/>
)
);
if (!tooltip) {
return button
return button;
}
if (typeof tooltip === "string") {
if (typeof tooltip === 'string') {
tooltip = {
children: tooltip,
}
};
}
return (
@@ -538,11 +517,11 @@ function SidebarMenuButton({
<TooltipContent
side="right"
align="center"
hidden={state !== "collapsed" || isMobile}
hidden={state !== 'collapsed' || isMobile}
{...tooltip}
/>
</Tooltip>
)
);
}
function SidebarMenuAction({
@@ -550,134 +529,123 @@ function SidebarMenuAction({
asChild = false,
showOnHover = false,
...props
}: React.ComponentProps<"button"> & {
asChild?: boolean
showOnHover?: boolean
}: React.ComponentProps<'button'> & {
asChild?: boolean;
showOnHover?: boolean;
}) {
const Comp = asChild ? Slot : "button"
const Comp = asChild ? Slot : 'button';
return (
<Comp
data-slot="sidebar-menu-action"
data-sidebar="menu-action"
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground peer-hover/menu-button:text-sidebar-accent-foreground absolute top-1.5 right-1 flex aspect-square w-5 items-center justify-center rounded-md p-0 outline-hidden transition-transform focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0',
// Increases the hit area of the button on mobile.
"after:absolute after:-inset-2 md:after:hidden",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
'after:absolute after:-inset-2 md:after:hidden',
'peer-data-[size=sm]/menu-button:top-1',
'peer-data-[size=default]/menu-button:top-1.5',
'peer-data-[size=lg]/menu-button:top-2.5',
'group-data-[collapsible=icon]:hidden',
showOnHover &&
"peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0",
className
'peer-data-[active=true]/menu-button:text-sidebar-accent-foreground group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 md:opacity-0',
className,
)}
{...props}
/>
)
);
}
function SidebarMenuBadge({
className,
...props
}: React.ComponentProps<"div">) {
function SidebarMenuBadge({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="sidebar-menu-badge"
data-sidebar="menu-badge"
className={cn(
"text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none",
"peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
"peer-data-[size=sm]/menu-button:top-1",
"peer-data-[size=default]/menu-button:top-1.5",
"peer-data-[size=lg]/menu-button:top-2.5",
"group-data-[collapsible=icon]:hidden",
className
'text-sidebar-foreground pointer-events-none absolute right-1 flex h-5 min-w-5 items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums select-none',
'peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground',
'peer-data-[size=sm]/menu-button:top-1',
'peer-data-[size=default]/menu-button:top-1.5',
'peer-data-[size=lg]/menu-button:top-2.5',
'group-data-[collapsible=icon]:hidden',
className,
)}
{...props}
/>
)
);
}
function SidebarMenuSkeleton({
className,
showIcon = false,
...props
}: React.ComponentProps<"div"> & {
showIcon?: boolean
}: React.ComponentProps<'div'> & {
showIcon?: boolean;
}) {
// Random width between 50 to 90%.
const width = React.useMemo(() => {
return `${Math.floor(Math.random() * 40) + 50}%`
}, [])
return `${Math.floor(Math.random() * 40) + 50}%`;
}, []);
return (
<div
data-slot="sidebar-menu-skeleton"
data-sidebar="menu-skeleton"
className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
className={cn('flex h-8 items-center gap-2 rounded-md px-2', className)}
{...props}
>
{showIcon && (
<Skeleton
className="size-4 rounded-md"
data-sidebar="menu-skeleton-icon"
/>
)}
{showIcon && <Skeleton className="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />}
<Skeleton
className="h-4 max-w-(--skeleton-width) flex-1"
data-sidebar="menu-skeleton-text"
style={
{
"--skeleton-width": width,
'--skeleton-width': width,
} as React.CSSProperties
}
/>
</div>
)
);
}
function SidebarMenuSub({ className, ...props }: React.ComponentProps<"ul">) {
function SidebarMenuSub({ className, ...props }: React.ComponentProps<'ul'>) {
return (
<ul
data-slot="sidebar-menu-sub"
data-sidebar="menu-sub"
className={cn(
"border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5",
"group-data-[collapsible=icon]:hidden",
className
'border-sidebar-border mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l px-2.5 py-0.5',
'group-data-[collapsible=icon]:hidden',
className,
)}
{...props}
/>
)
);
}
function SidebarMenuSubItem({
className,
...props
}: React.ComponentProps<"li">) {
function SidebarMenuSubItem({ className, ...props }: React.ComponentProps<'li'>) {
return (
<li
data-slot="sidebar-menu-sub-item"
data-sidebar="menu-sub-item"
className={cn("group/menu-sub-item relative", className)}
className={cn('group/menu-sub-item relative', className)}
{...props}
/>
)
);
}
function SidebarMenuSubButton({
asChild = false,
size = "md",
size = 'md',
isActive = false,
className,
...props
}: React.ComponentProps<"a"> & {
asChild?: boolean
size?: "sm" | "md"
isActive?: boolean
}: React.ComponentProps<'a'> & {
asChild?: boolean;
size?: 'sm' | 'md';
isActive?: boolean;
}) {
const Comp = asChild ? Slot : "a"
const Comp = asChild ? Slot : 'a';
return (
<Comp
@@ -686,16 +654,16 @@ function SidebarMenuSubButton({
data-size={size}
data-active={isActive}
className={cn(
"text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
"data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
size === "sm" && "text-xs",
size === "md" && "text-sm",
"group-data-[collapsible=icon]:hidden",
className
'text-sidebar-foreground ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground active:bg-sidebar-accent active:text-sidebar-accent-foreground [&>svg]:text-sidebar-accent-foreground flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 outline-hidden focus-visible:ring-2 disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0',
'data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground',
size === 'sm' && 'text-xs',
size === 'md' && 'text-sm',
'group-data-[collapsible=icon]:hidden',
className,
)}
{...props}
/>
)
);
}
export {
@@ -723,4 +691,4 @@ export {
SidebarSeparator,
SidebarTrigger,
useSidebar,
}
};

View File

@@ -1,13 +1,13 @@
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
function Skeleton({ className, ...props }: React.ComponentProps<'div'>) {
return (
<div
data-slot="skeleton"
className={cn("animate-pulse rounded-md bg-accent", className)}
className={cn('animate-pulse rounded-md bg-accent', className)}
{...props}
/>
)
);
}
export { Skeleton }
export { Skeleton };

View File

@@ -1,10 +1,10 @@
'use client'
'use client';
import { useTheme } from 'next-themes'
import { Toaster as Sonner, ToasterProps } from 'sonner'
import { useTheme } from 'next-themes';
import { Toaster as Sonner, ToasterProps } from 'sonner';
const Toaster = ({ ...props }: ToasterProps) => {
const { theme = 'system' } = useTheme()
const { theme = 'system' } = useTheme();
return (
<Sonner
@@ -19,7 +19,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
}
{...props}
/>
)
}
);
};
export { Toaster }
export { Toaster };

View File

@@ -1,120 +1,99 @@
"use client"
'use client';
import * as React from "react"
import * as React from 'react';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function Table({
className,
containerClassName,
...props
}: React.ComponentProps<"table"> & { containerClassName?: string }) {
}: React.ComponentProps<'table'> & { containerClassName?: string }) {
return (
<div
data-slot="table-container"
className={cn("relative w-full overflow-x-auto", containerClassName)}
className={cn('relative w-full overflow-x-auto', containerClassName)}
>
<table
data-slot="table"
className={cn("w-full caption-bottom text-sm", className)}
className={cn('w-full caption-bottom text-sm', className)}
{...props}
/>
</div>
)
);
}
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) {
return (
<thead
data-slot="table-header"
className={cn("[&_tr]:border-b", className)}
{...props}
/>
)
function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
return <thead data-slot="table-header" className={cn('[&_tr]:border-b', className)} {...props} />;
}
function TableBody({ className, ...props }: React.ComponentProps<"tbody">) {
function TableBody({ className, ...props }: React.ComponentProps<'tbody'>) {
return (
<tbody
data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)}
className={cn('[&_tr:last-child]:border-0', className)}
{...props}
/>
)
);
}
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) {
function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
return (
<tfoot
data-slot="table-footer"
className={cn(
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
{...props}
/>
)
);
}
function TableRow({ className, ...props }: React.ComponentProps<"tr">) {
function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
return (
<tr
data-slot="table-row"
className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
className
'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',
className,
)}
{...props}
/>
)
);
}
function TableHead({ className, ...props }: React.ComponentProps<"th">) {
function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
return (
<th
data-slot="table-head"
className={cn(
"h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
'h-10 px-2 text-left align-middle font-medium whitespace-nowrap text-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',
className,
)}
{...props}
/>
)
);
}
function TableCell({ className, ...props }: React.ComponentProps<"td">) {
function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
return (
<td
data-slot="table-cell"
className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
className
'p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',
className,
)}
{...props}
/>
)
);
}
function TableCaption({
className,
...props
}: React.ComponentProps<"caption">) {
function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {
return (
<caption
data-slot="table-caption"
className={cn("mt-4 text-sm text-muted-foreground", className)}
className={cn('mt-4 text-sm text-muted-foreground', className)}
{...props}
/>
)
);
}
export {
Table,
TableHeader,
TableBody,
TableFooter,
TableHead,
TableRow,
TableCell,
TableCaption,
}
export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };

View File

@@ -1,9 +1,9 @@
"use client"
'use client';
import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"
import * as React from 'react';
import * as TooltipPrimitive from '@radix-ui/react-tooltip';
import { cn } from "@/lib/utils"
import { cn } from '@/lib/utils';
function TooltipProvider({
delayDuration = 0,
@@ -15,23 +15,19 @@ function TooltipProvider({
delayDuration={delayDuration}
{...props}
/>
)
);
}
function Tooltip({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return (
<TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider>
)
);
}
function TooltipTrigger({
...props
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}
function TooltipContent({
@@ -46,8 +42,8 @@ function TooltipContent({
data-slot="tooltip-content"
sideOffset={sideOffset}
className={cn(
"bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance",
className
'bg-foreground text-background animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 z-50 w-fit origin-(--radix-tooltip-content-transform-origin) rounded-md px-3 py-1.5 text-xs text-balance',
className,
)}
{...props}
>
@@ -55,7 +51,7 @@ function TooltipContent({
<TooltipPrimitive.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content>
</TooltipPrimitive.Portal>
)
);
}
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }
export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };

File diff suppressed because it is too large Load Diff

View File

@@ -1,19 +1,19 @@
import * as React from 'react'
import * as React from 'react';
const MOBILE_BREAKPOINT = 768
const MOBILE_BREAKPOINT = 768;
export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
}
mql.addEventListener('change', onChange)
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
return () => mql.removeEventListener('change', onChange)
}, [])
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
};
mql.addEventListener('change', onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener('change', onChange);
}, []);
return !!isMobile
return !!isMobile;
}

View File

@@ -1,191 +0,0 @@
'use client'
// Inspired by react-hot-toast library
import * as React from 'react'
import type { ToastActionElement, ToastProps } from '@/components/ui/toast'
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: 'ADD_TOAST',
UPDATE_TOAST: 'UPDATE_TOAST',
DISMISS_TOAST: 'DISMISS_TOAST',
REMOVE_TOAST: 'REMOVE_TOAST',
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType['ADD_TOAST']
toast: ToasterToast
}
| {
type: ActionType['UPDATE_TOAST']
toast: Partial<ToasterToast>
}
| {
type: ActionType['DISMISS_TOAST']
toastId?: ToasterToast['id']
}
| {
type: ActionType['REMOVE_TOAST']
toastId?: ToasterToast['id']
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: 'REMOVE_TOAST',
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case 'ADD_TOAST':
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case 'UPDATE_TOAST':
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t,
),
}
case 'DISMISS_TOAST': {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t,
),
}
}
case 'REMOVE_TOAST':
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, 'id'>
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: 'UPDATE_TOAST',
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: 'DISMISS_TOAST', toastId: id })
dispatch({
type: 'ADD_TOAST',
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: 'DISMISS_TOAST', toastId }),
}
}
export { useToast, toast }

View File

@@ -1,6 +1,6 @@
import { clsx, type ClassValue } from 'clsx'
import { twMerge } from 'tailwind-merge'
import { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
return twMerge(clsx(inputs));
}

View File

@@ -3,107 +3,107 @@
* Used to persist video files across page navigations
*/
const DB_NAME = 'visionroad_db'
const DB_VERSION = 1
const VIDEO_STORE = 'videos'
const DB_NAME = 'visionroad_db';
const DB_VERSION = 1;
const VIDEO_STORE = 'videos';
let db: IDBDatabase | null = null
let db: IDBDatabase | null = null;
/**
* Open the IndexedDB database
*/
async function openDB(): Promise<IDBDatabase> {
if (db) return db
if (db) return db;
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION)
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error)
request.onsuccess = () => {
db = request.result
resolve(db)
}
request.onerror = () => reject(request.error);
request.onsuccess = () => {
db = request.result;
resolve(db);
};
request.onupgradeneeded = (event) => {
const database = (event.target as IDBOpenDBRequest).result
if (!database.objectStoreNames.contains(VIDEO_STORE)) {
database.createObjectStore(VIDEO_STORE, { keyPath: 'id' })
}
}
})
request.onupgradeneeded = (event) => {
const database = (event.target as IDBOpenDBRequest).result;
if (!database.objectStoreNames.contains(VIDEO_STORE)) {
database.createObjectStore(VIDEO_STORE, { keyPath: 'id' });
}
};
});
}
/**
* Store a video file in IndexedDB
*/
export async function storeVideoFile(videoId: string, file: File): Promise<void> {
const database = await openDB()
const database = await openDB();
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite')
const store = transaction.objectStore(VIDEO_STORE)
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE);
const request = store.put({
id: videoId,
file: file,
timestamp: Date.now()
})
const request = store.put({
id: videoId,
file: file,
timestamp: Date.now(),
});
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve()
})
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}
/**
* Retrieve a video file from IndexedDB
*/
export async function getVideoFile(videoId: string): Promise<File | null> {
const database = await openDB()
const database = await openDB();
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readonly')
const store = transaction.objectStore(VIDEO_STORE)
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readonly');
const store = transaction.objectStore(VIDEO_STORE);
const request = store.get(videoId)
const request = store.get(videoId);
request.onerror = () => reject(request.error)
request.onsuccess = () => {
const result = request.result
resolve(result ? result.file : null)
}
})
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const result = request.result;
resolve(result ? result.file : null);
};
});
}
/**
* Clear a video file from IndexedDB
*/
export async function clearVideoFile(videoId: string): Promise<void> {
const database = await openDB()
const database = await openDB();
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite')
const store = transaction.objectStore(VIDEO_STORE)
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE);
const request = store.delete(videoId)
const request = store.delete(videoId);
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve()
})
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}
/**
* Clear all video files from IndexedDB
*/
export async function clearAllVideos(): Promise<void> {
const database = await openDB()
const database = await openDB();
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite')
const store = transaction.objectStore(VIDEO_STORE)
return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE);
const request = store.clear()
const request = store.clear();
request.onerror = () => reject(request.error)
request.onsuccess = () => resolve()
})
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve();
});
}

View File

@@ -1,58 +1,64 @@
import axiosClient from "../axios/axios";
import axiosClient from '../axios/axios';
import {
Chainage, ChainageCreate, ChainageUpdate,
PaginatedResponse, PaginationParams
} from "@/types";
Chainage,
ChainageCreate,
ChainageUpdate,
PaginatedResponse,
PaginationParams,
} from '@/types';
/**
* Chainage Service
*/
export const chainageService = {
/**
* Fetch all chainages
*/
getChainages: async (params?: PaginationParams): Promise<PaginatedResponse<Chainage>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Chainage>>(`/chainages/`, {
params: { skip, limit }
});
return response.data;
},
/**
* Fetch all chainages
*/
getChainages: async (params?: PaginationParams): Promise<PaginatedResponse<Chainage>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Chainage>>(`/chainages/`, {
params: { skip, limit },
});
return response.data;
},
/**
* Fetch chainages filtered by package ID
*/
getChainagesByPackage: async (packageId: string, params?: PaginationParams): Promise<PaginatedResponse<Chainage>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Chainage>>(`/chainages/`, {
params: { package_id: packageId, skip, limit }
});
return response.data;
},
/**
* Fetch chainages filtered by package ID
*/
getChainagesByPackage: async (
packageId: string,
params?: PaginationParams,
): Promise<PaginatedResponse<Chainage>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Chainage>>(`/chainages/`, {
params: { package_id: packageId, skip, limit },
});
return response.data;
},
/**
* Create a new chainage
*/
createChainage: async (data: ChainageCreate): Promise<Chainage> => {
const response = await axiosClient.post<Chainage>("/chainages/", data);
return response.data;
},
/**
* Create a new chainage
*/
createChainage: async (data: ChainageCreate): Promise<Chainage> => {
const response = await axiosClient.post<Chainage>('/chainages/', data);
return response.data;
},
/**
* Update an existing chainage
*/
updateChainage: async (chainageId: string, data: ChainageUpdate): Promise<Chainage> => {
const response = await axiosClient.put<Chainage>(`/chainages/${chainageId}`, data);
return response.data;
},
/**
* Update an existing chainage
*/
updateChainage: async (chainageId: string, data: ChainageUpdate): Promise<Chainage> => {
const response = await axiosClient.put<Chainage>(`/chainages/${chainageId}`, data);
return response.data;
},
/**
* Delete a chainage
*/
deleteChainage: async (chainageId: string): Promise<{ message: string }> => {
const response = await axiosClient.delete<{ message: string }>(`/chainages/${chainageId}`);
return response.data;
}
/**
* Delete a chainage
*/
deleteChainage: async (chainageId: string): Promise<{ message: string }> => {
const response = await axiosClient.delete<{ message: string }>(`/chainages/${chainageId}`);
return response.data;
},
};

View File

@@ -1,56 +1,56 @@
import axiosClient from "../axios/axios";
import { Detection } from "@/types";
import { projectService } from "./project.service";
import axiosClient from '../axios/axios';
import { Detection } from '@/types';
import { projectService } from './project.service';
/**
* Detection Service
*/
export const detectionService = {
/**
* Fetch all detections from completed videos
* Uses the summary endpoint to get detections for each project
*/
getAllDetections: async (): Promise<Detection[]> => {
/**
* Fetch all detections from completed videos
* Uses the summary endpoint to get detections for each project
*/
getAllDetections: async (): Promise<Detection[]> => {
try {
// First get all projects
const projectsResponse = await projectService.getProjects();
const projects = projectsResponse.items;
// Then fetch detections for each project
const allDetections: Detection[] = [];
for (const project of projects) {
try {
// First get all projects
const projectsResponse = await projectService.getProjects();
const projects = projectsResponse.items;
const response = await axiosClient.get<{
packages: {
[key: string]: {
chainages: {
[key: string]: {
detections: Detection[];
};
};
};
};
}>(`/summary/projects/${project.id}`);
// Then fetch detections for each project
const allDetections: Detection[] = []
const summary = response.data;
for (const project of projects) {
try {
const response = await axiosClient.get<{
packages: {
[key: string]: {
chainages: {
[key: string]: {
detections: Detection[]
}
}
}
}
}>(`/summary/projects/${project.id}`);
const summary = response.data;
// Extract detections from the nested structure
for (const pkg of Object.values(summary.packages || {})) {
for (const loc of Object.values(pkg.chainages || {})) {
allDetections.push(...(loc.detections || []))
}
}
} catch (e) {
// Skip projects that fail to load
console.warn(`Failed to load detections for project ${project.id}:`, e)
}
// Extract detections from the nested structure
for (const pkg of Object.values(summary.packages || {})) {
for (const loc of Object.values(pkg.chainages || {})) {
allDetections.push(...(loc.detections || []));
}
return allDetections;
}
} catch (e) {
console.error("Failed to fetch all detections:", e)
return []
// Skip projects that fail to load
console.warn(`Failed to load detections for project ${project.id}:`, e);
}
}
return allDetections;
} catch (e) {
console.error('Failed to fetch all detections:', e);
return [];
}
},
};

View File

@@ -1,7 +1,7 @@
export * from "./project.service";
export * from "./package.service";
export { chainageService } from "./chainage.service";
export * from "./video.service";
export * from "./detection.service";
export * from "./session.service";
export { projectDataService } from "./project.service";
export * from './project.service';
export * from './package.service';
export { chainageService } from './chainage.service';
export * from './video.service';
export * from './detection.service';
export * from './session.service';
export { projectDataService } from './project.service';

View File

@@ -1,58 +1,64 @@
import axiosClient from "../axios/axios";
import axiosClient from '../axios/axios';
import {
Package, PackageCreate, PackageUpdate,
PaginatedResponse, PaginationParams
} from "@/types";
Package,
PackageCreate,
PackageUpdate,
PaginatedResponse,
PaginationParams,
} from '@/types';
/**
* Package Service
*/
export const packageService = {
/**
* Fetch all packages
*/
getPackages: async (params?: PaginationParams): Promise<PaginatedResponse<Package>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Package>>(`/packages/`, {
params: { skip, limit }
});
return response.data;
},
/**
* Fetch all packages
*/
getPackages: async (params?: PaginationParams): Promise<PaginatedResponse<Package>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Package>>(`/packages/`, {
params: { skip, limit },
});
return response.data;
},
/**
* Fetch packages filtered by project ID
*/
getPackagesByProject: async (projectId: string, params?: PaginationParams): Promise<PaginatedResponse<Package>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Package>>(`/packages/`, {
params: { project_id: projectId, skip, limit }
});
return response.data;
},
/**
* Fetch packages filtered by project ID
*/
getPackagesByProject: async (
projectId: string,
params?: PaginationParams,
): Promise<PaginatedResponse<Package>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Package>>(`/packages/`, {
params: { project_id: projectId, skip, limit },
});
return response.data;
},
/**
* Create a new package
*/
createPackage: async (data: PackageCreate): Promise<Package> => {
const response = await axiosClient.post<Package>("/packages/", data);
return response.data;
},
/**
* Create a new package
*/
createPackage: async (data: PackageCreate): Promise<Package> => {
const response = await axiosClient.post<Package>('/packages/', data);
return response.data;
},
/**
* Update an existing package
*/
updatePackage: async (packageId: string, data: PackageUpdate): Promise<Package> => {
const response = await axiosClient.put<Package>(`/packages/${packageId}`, data);
return response.data;
},
/**
* Update an existing package
*/
updatePackage: async (packageId: string, data: PackageUpdate): Promise<Package> => {
const response = await axiosClient.put<Package>(`/packages/${packageId}`, data);
return response.data;
},
/**
* Delete a package
*/
deletePackage: async (packageId: string): Promise<{ message: string }> => {
const response = await axiosClient.delete<{ message: string }>(`/packages/${packageId}`);
return response.data;
}
/**
* Delete a package
*/
deletePackage: async (packageId: string): Promise<{ message: string }> => {
const response = await axiosClient.delete<{ message: string }>(`/packages/${packageId}`);
return response.data;
},
};

View File

@@ -1,66 +1,69 @@
import axiosClient from "../axios/axios";
import axiosClient from '../axios/axios';
import {
Project, ProjectCreate, ProjectUpdate,
PaginatedResponse, PaginationParams
} from "@/types";
Project,
ProjectCreate,
ProjectUpdate,
PaginatedResponse,
PaginationParams,
} from '@/types';
/**
* Project Service
*/
export const projectService = {
/**
* Fetch all projects
*/
getProjects: async (params?: PaginationParams): Promise<PaginatedResponse<Project>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Project>>(`/projects/`, {
params: { skip, limit }
});
return response.data;
},
/**
* Fetch all projects
*/
getProjects: async (params?: PaginationParams): Promise<PaginatedResponse<Project>> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<PaginatedResponse<Project>>(`/projects/`, {
params: { skip, limit },
});
return response.data;
},
/**
* Create a new project
*/
createProject: async (data: ProjectCreate): Promise<Project> => {
const response = await axiosClient.post<Project>("/projects/", data);
return response.data;
},
/**
* Create a new project
*/
createProject: async (data: ProjectCreate): Promise<Project> => {
const response = await axiosClient.post<Project>('/projects/', data);
return response.data;
},
/**
* Update an existing project
*/
updateProject: async (projectId: string, data: ProjectUpdate): Promise<Project> => {
const response = await axiosClient.put<Project>(`/projects/${projectId}`, data);
return response.data;
},
/**
* Update an existing project
*/
updateProject: async (projectId: string, data: ProjectUpdate): Promise<Project> => {
const response = await axiosClient.put<Project>(`/projects/${projectId}`, data);
return response.data;
},
/**
* Delete a project
*/
deleteProject: async (projectId: string): Promise<{ message: string }> => {
const response = await axiosClient.delete<{ message: string }>(`/projects/${projectId}`);
return response.data;
},
/**
* Delete a project
*/
deleteProject: async (projectId: string): Promise<{ message: string }> => {
const response = await axiosClient.delete<{ message: string }>(`/projects/${projectId}`);
return response.data;
},
/**
* Fetch project summary (detections across packages and chainages)
*/
getProjectSummary: async (projectId: string): Promise<any> => {
const response = await axiosClient.get(`/summary/projects/${projectId}`);
return response.data;
},
/**
* Fetch project summary (detections across packages and chainages)
*/
getProjectSummary: async (projectId: string): Promise<any> => {
const response = await axiosClient.get(`/summary/projects/${projectId}`);
return response.data;
},
/**
* Fetch project summary filtered by video ID
*/
getProjectSummaryByVideo: async (projectId: string, videoId: string): Promise<any> => {
const response = await axiosClient.get(`/summary/projects/${projectId}`, {
params: { video_id: videoId }
});
return response.data;
}
/**
* Fetch project summary filtered by video ID
*/
getProjectSummaryByVideo: async (projectId: string, videoId: string): Promise<any> => {
const response = await axiosClient.get(`/summary/projects/${projectId}`, {
params: { video_id: videoId },
});
return response.data;
},
};
/**
@@ -68,33 +71,35 @@ export const projectService = {
* Moved from legacy project-service.ts
*/
export const projectDataService = {
/**
* Extracts all detections from a project summary, optionally filtered by package and chainage
*/
extractDetections(
projectSummary: any,
selectedPackageId?: string | null,
selectedChainageId?: string | null
): any[] {
if (!projectSummary) return []
/**
* Extracts all detections from a project summary, optionally filtered by package and chainage
*/
extractDetections(
projectSummary: any,
selectedPackageId?: string | null,
selectedChainageId?: string | null,
): any[] {
if (!projectSummary) return [];
const detections: any[] = []
const packagesToProcess = selectedPackageId && selectedPackageId !== "all"
? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
: projectSummary.packages || {}
const detections: any[] = [];
const packagesToProcess =
selectedPackageId && selectedPackageId !== 'all'
? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
: projectSummary.packages || {};
for (const [pkgName, pkg] of Object.entries(packagesToProcess)) {
const chainagesToProcess = selectedChainageId && selectedChainageId !== "all"
? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
: (pkg as any).chainages || {}
for (const [pkgName, pkg] of Object.entries(packagesToProcess)) {
const chainagesToProcess =
selectedChainageId && selectedChainageId !== 'all'
? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
: (pkg as any).chainages || {};
for (const [chnName, chn] of Object.entries(chainagesToProcess)) {
if (!chn) continue
const chainageDetections = (chn as any).detections || []
detections.push(...chainageDetections)
}
}
return detections
for (const [chnName, chn] of Object.entries(chainagesToProcess)) {
if (!chn) continue;
const chainageDetections = (chn as any).detections || [];
detections.push(...chainageDetections);
}
}
return detections;
},
};

View File

@@ -1,73 +1,73 @@
import { SessionContext, VideoResultData, emptySessionContext } from "@/types";
import { SessionContext, VideoResultData, emptySessionContext } from '@/types';
// Session Storage Keys
const SESSION_KEY = "visionroad_session";
const VIDEO_DATA_KEY = "visionroad_video_data";
const DETECTION_TYPE_KEY = "visionroad_detection_type";
const SESSION_KEY = 'visionroad_session';
const VIDEO_DATA_KEY = 'visionroad_video_data';
const DETECTION_TYPE_KEY = 'visionroad_detection_type';
/**
* Session Service
*/
export const sessionService = {
/**
* Save session to localStorage
*/
saveSession: (session: SessionContext): void => {
if (typeof window !== "undefined") {
localStorage.setItem(SESSION_KEY, JSON.stringify(session))
}
},
/**
* Load session from localStorage
*/
loadSession: (): SessionContext => {
if (typeof window !== "undefined") {
const stored = localStorage.getItem(SESSION_KEY)
if (stored) {
return JSON.parse(stored)
}
}
return emptySessionContext;
},
/**
* Clear all session data
*/
clearSession: (): void => {
if (typeof window !== "undefined") {
localStorage.removeItem(SESSION_KEY)
localStorage.removeItem(VIDEO_DATA_KEY)
localStorage.removeItem(DETECTION_TYPE_KEY)
}
},
/**
* Save video result data
*/
saveVideoData: (data: VideoResultData): void => {
if (typeof window !== "undefined") {
localStorage.setItem(VIDEO_DATA_KEY, JSON.stringify(data))
}
},
/**
* Load video result data
*/
loadVideoData: (): VideoResultData | null => {
if (typeof window !== "undefined") {
const stored = localStorage.getItem(VIDEO_DATA_KEY)
if (stored) {
return JSON.parse(stored)
}
}
return null;
},
/**
* Check if session is complete
*/
isSessionValid: (session: SessionContext): boolean => {
return !!(session.projectId && session.packageId && session.chainageId)
/**
* Save session to localStorage
*/
saveSession: (session: SessionContext): void => {
if (typeof window !== 'undefined') {
localStorage.setItem(SESSION_KEY, JSON.stringify(session));
}
},
/**
* Load session from localStorage
*/
loadSession: (): SessionContext => {
if (typeof window !== 'undefined') {
const stored = localStorage.getItem(SESSION_KEY);
if (stored) {
return JSON.parse(stored);
}
}
return emptySessionContext;
},
/**
* Clear all session data
*/
clearSession: (): void => {
if (typeof window !== 'undefined') {
localStorage.removeItem(SESSION_KEY);
localStorage.removeItem(VIDEO_DATA_KEY);
localStorage.removeItem(DETECTION_TYPE_KEY);
}
},
/**
* Save video result data
*/
saveVideoData: (data: VideoResultData): void => {
if (typeof window !== 'undefined') {
localStorage.setItem(VIDEO_DATA_KEY, JSON.stringify(data));
}
},
/**
* Load video result data
*/
loadVideoData: (): VideoResultData | null => {
if (typeof window !== 'undefined') {
const stored = localStorage.getItem(VIDEO_DATA_KEY);
if (stored) {
return JSON.parse(stored);
}
}
return null;
},
/**
* Check if session is complete
*/
isSessionValid: (session: SessionContext): boolean => {
return !!(session.projectId && session.packageId && session.chainageId);
},
};

View File

@@ -1,79 +1,79 @@
import axiosClient from "../axios/axios";
import { Video, PaginationParams } from "@/types";
import axiosClient from '../axios/axios';
import { Video, PaginationParams } from '@/types';
/**
* Video Service
*/
export const videoService = {
/**
* Fetch all videos and transform them to match the Video interface
*/
getVideos: async (params?: PaginationParams): Promise<Video[]> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
/**
* Fetch all videos and transform them to match the Video interface
*/
getVideos: async (params?: PaginationParams): Promise<Video[]> => {
const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100;
const response = await axiosClient.get<{
videos: Array<{
video_id: string;
status: string;
progress: number;
summary?: {
unique_defected_sign_board?: number;
unique_pothole?: number;
unique_road_crack?: number;
unique_damaged_road_marking?: number;
unique_good_sign_board?: number;
total_road_damage?: number;
total_detections?: number;
};
}>;
}>(`/videos`, {
params: { skip, limit }
});
const response = await axiosClient.get<{
videos: Array<{
video_id: string;
status: string;
progress: number;
summary?: {
unique_defected_sign_board?: number;
unique_pothole?: number;
unique_road_crack?: number;
unique_damaged_road_marking?: number;
unique_good_sign_board?: number;
total_road_damage?: number;
total_detections?: number;
};
}>;
}>(`/videos`, {
params: { skip, limit },
});
// Transform the response to match our Video interface
return response.data.videos.map(v => ({
id: v.video_id,
filename: v.video_id,
detection_type: "pot-sign-detection" as const,
status: v.status as Video["status"],
unique_defected_sign_board: v.summary?.unique_defected_sign_board,
unique_pothole: v.summary?.unique_pothole,
unique_road_crack: v.summary?.unique_road_crack,
unique_damaged_road_marking: v.summary?.unique_damaged_road_marking,
unique_good_sign_board: v.summary?.unique_good_sign_board,
total_road_damage: v.summary?.total_road_damage,
total_detections: v.summary?.total_detections,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString()
}));
},
// Transform the response to match our Video interface
return response.data.videos.map((v) => ({
id: v.video_id,
filename: v.video_id,
detection_type: 'pot-sign-detection' as const,
status: v.status as Video['status'],
unique_defected_sign_board: v.summary?.unique_defected_sign_board,
unique_pothole: v.summary?.unique_pothole,
unique_road_crack: v.summary?.unique_road_crack,
unique_damaged_road_marking: v.summary?.unique_damaged_road_marking,
unique_good_sign_board: v.summary?.unique_good_sign_board,
total_road_damage: v.summary?.total_road_damage,
total_detections: v.summary?.total_detections,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}));
},
/**
* Upload a video for processing
*/
uploadVideo: async (formData: FormData): Promise<any> => {
const response = await axiosClient.post("/upload", formData, {
headers: {
"Content-Type": "multipart/form-data"
}
});
return response.data;
},
/**
* Upload a video for processing
*/
uploadVideo: async (formData: FormData): Promise<any> => {
const response = await axiosClient.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
return response.data;
},
/**
* Get processing status of a video
*/
getVideoStatus: async (videoId: string): Promise<any> => {
const response = await axiosClient.get(`/status/${videoId}`);
return response.data;
},
/**
* Get processing status of a video
*/
getVideoStatus: async (videoId: string): Promise<any> => {
const response = await axiosClient.get(`/status/${videoId}`);
return response.data;
},
/**
* Get analysis results for a video
*/
getVideoResults: async (videoId: string): Promise<any> => {
const response = await axiosClient.get(`/results/${videoId}`);
return response.data;
}
/**
* Get analysis results for a video
*/
getVideoResults: async (videoId: string): Promise<any> => {
const response = await axiosClient.get(`/results/${videoId}`);
return response.data;
},
};

View File

@@ -1,5 +1,5 @@
import { ENV_CONSTANT } from "@/constants/secrect.constant";
import axios from "axios";
import { ENV_CONSTANT } from '@/constants/secrect.constant';
import axios from 'axios';
const BASE_URL = ENV_CONSTANT.BASE_API_URL;
@@ -7,24 +7,24 @@ const axiosClient = axios.create({
baseURL: BASE_URL,
headers: {
// "Content-Type": "application/json",
"ngrok-skip-browser-warning": "true"
'ngrok-skip-browser-warning': 'true',
},
});
// Add request interceptor to inject access token
axiosClient.interceptors.request.use(
(config) => {
if (typeof window !== "undefined") {
const token = localStorage.getItem("token");
if (typeof window !== 'undefined') {
const token = localStorage.getItem('token');
if (token && config.headers) {
config.headers["Authorization"] = `Bearer ${token}`;
config.headers['Authorization'] = `Bearer ${token}`;
}
}
return config;
},
(error) => {
return Promise.reject(error);
}
},
);
// Basic response interceptor
@@ -33,12 +33,12 @@ axiosClient.interceptors.response.use(
(error) => {
// Standard error handling can be added here later
return Promise.reject(error);
}
},
);
export const axiosAuth = axios.create({
baseURL: BASE_URL,
headers: { "Content-Type": "application/json" },
headers: { 'Content-Type': 'application/json' },
});
export default axiosClient;

View File

@@ -1,65 +1,65 @@
import { DetectionListItem } from "./detection"
import { DetectionListItem } from './detection';
/**
* Analysis result types
*/
export type DetectionData = {
video_id: string
detection_type?: string
output_video_path?: string
video_id: string;
detection_type?: string;
output_video_path?: string;
video_info: {
fps: number
width: number
height: number
total_frames: number
}
fps: number;
width: number;
height: number;
total_frames: number;
};
summary: {
unique_defected_sign_board?: number
unique_pothole?: number
unique_road_crack?: number
unique_damaged_road_marking?: number
unique_good_sign_board?: number
total_road_damage?: number
total_detections: number
total_frames: number
detection_rate: number
}
pothole_list?: Array<DetectionListItem>
defected_sign_board_list?: Array<DetectionListItem>
road_crack_list?: Array<DetectionListItem>
damaged_road_marking_list?: Array<DetectionListItem>
good_sign_board_list?: Array<DetectionListItem>
signboard_list?: Array<DetectionListItem> // Keeping for backward compatibility
unique_defected_sign_board?: number;
unique_pothole?: number;
unique_road_crack?: number;
unique_damaged_road_marking?: number;
unique_good_sign_board?: number;
total_road_damage?: number;
total_detections: number;
total_frames: number;
detection_rate: number;
};
pothole_list?: Array<DetectionListItem>;
defected_sign_board_list?: Array<DetectionListItem>;
road_crack_list?: Array<DetectionListItem>;
damaged_road_marking_list?: Array<DetectionListItem>;
good_sign_board_list?: Array<DetectionListItem>;
signboard_list?: Array<DetectionListItem>; // Keeping for backward compatibility
frames: Array<{
frame_id: number
frame_id: number;
// Legacy format: separate arrays
potholes?: Array<{
pothole_id: number
bbox: { x1: number; y1: number; x2: number; y2: number }
confidence: number
}>
pothole_id: number;
bbox: { x1: number; y1: number; x2: number; y2: number };
confidence: number;
}>;
signboards?: Array<{
signboard_id: number
type: string
bbox: { x1: number; y1: number; x2: number; y2: number }
confidence: number
}>
signboard_id: number;
type: string;
bbox: { x1: number; y1: number; x2: number; y2: number };
confidence: number;
}>;
// Flat format (pot-sign-detection): unified detections array
detections?: Array<{
frame_id: number
detection_id: number
type: string
confidence: number
bbox: { x1: number; y1: number; x2: number; y2: number }
center?: { x: number; y: number }
area?: number
frame_id: number;
detection_id: number;
type: string;
confidence: number;
bbox: { x1: number; y1: number; x2: number; y2: number };
center?: { x: number; y: number };
area?: number;
count?: {
defected_sign_board: number
pothole: number
road_crack: number
damaged_road_marking: number
good_sign_board: number
}
}>
}>
}
defected_sign_board: number;
pothole: number;
road_crack: number;
damaged_road_marking: number;
good_sign_board: number;
};
}>;
}>;
};

View File

@@ -2,39 +2,39 @@
* Chainage related types
*/
export interface Chainage {
id: string
package_id: string
segment_name: string
chainage_start_km: number
chainage_end_km: number
start_lat: number
start_lng: number
end_lat: number
end_lng: number
direction: 'UP' | 'DOWN'
created_at: string
updated_at: string
id: string;
package_id: string;
segment_name: string;
chainage_start_km: number;
chainage_end_km: number;
start_lat: number;
start_lng: number;
end_lat: number;
end_lng: number;
direction: 'UP' | 'DOWN';
created_at: string;
updated_at: string;
}
export interface ChainageCreate {
package_id: string
segment_name: string
chainage_start_km: number
chainage_end_km: number
start_lat: number
start_lng: number
end_lat: number
end_lng: number
direction: 'UP' | 'DOWN'
package_id: string;
segment_name: string;
chainage_start_km: number;
chainage_end_km: number;
start_lat: number;
start_lng: number;
end_lat: number;
end_lng: number;
direction: 'UP' | 'DOWN';
}
export interface ChainageUpdate {
segment_name?: string
chainage_start_km?: number
chainage_end_km?: number
start_lat?: number
start_lng?: number
end_lat?: number
end_lng?: number
direction?: 'UP' | 'DOWN'
segment_name?: string;
chainage_start_km?: number;
chainage_end_km?: number;
start_lat?: number;
start_lng?: number;
end_lat?: number;
end_lng?: number;
direction?: 'UP' | 'DOWN';
}

View File

@@ -2,8 +2,8 @@
* Common API pagination types
*/
export interface PaginatedResponse<T> {
items: T[]
totalItems: number
items: T[];
totalItems: number;
}
export interface PaginationParams {

View File

@@ -2,28 +2,28 @@
* Detection types for map and display
*/
export interface Detection {
id: number
video_id: string
type: string
class: string
confidence: number
latitude: number | null
longitude: number | null
frame_number: number
timestamp_ms: number
id: number;
video_id: string;
type: string;
class: string;
confidence: number;
latitude: number | null;
longitude: number | null;
frame_number: number;
timestamp_ms: number;
}
export type DetectionType = "pothole-detection" | "sign-board-detection" | "pot-sign-detection"
export type DetectionType = 'pothole-detection' | 'sign-board-detection' | 'pot-sign-detection';
export interface DetectionListItem {
detection_id?: number
pothole_id?: number
signboard_id?: number
type: string
first_detected_frame: number
first_detected_time: number
confidence: number
bbox?: { x1: number; y1: number; x2: number; y2: number }
lat?: number
lng?: number
detection_id?: number;
pothole_id?: number;
signboard_id?: number;
type: string;
first_detected_frame: number;
first_detected_time: number;
confidence: number;
bbox?: { x1: number; y1: number; x2: number; y2: number };
lat?: number;
lng?: number;
}

View File

@@ -1,8 +1,8 @@
export * from "./common"
export * from "./project"
export * from "./package"
export * from "./chainage"
export * from "./video"
export * from "./detection"
export * from "./analysis"
export * from "./session"
export * from './common';
export * from './project';
export * from './package';
export * from './chainage';
export * from './video';
export * from './detection';
export * from './analysis';
export * from './session';

View File

@@ -2,27 +2,27 @@
* Package related types
*/
export interface Package {
id: string
project_id: string
name: string
region: string | null
chainage_start_km: number
chainage_end_km: number
created_at: string
updated_at: string
id: string;
project_id: string;
name: string;
region: string | null;
chainage_start_km: number;
chainage_end_km: number;
created_at: string;
updated_at: string;
}
export interface PackageCreate {
project_id: string
name: string
region?: string | null
chainage_start_km?: number
chainage_end_km?: number
project_id: string;
name: string;
region?: string | null;
chainage_start_km?: number;
chainage_end_km?: number;
}
export interface PackageUpdate {
name?: string
region?: string | null
chainage_start_km?: number
chainage_end_km?: number
name?: string;
region?: string | null;
chainage_start_km?: number;
chainage_end_km?: number;
}

View File

@@ -2,34 +2,34 @@
* Project related types
*/
export interface Project {
id: string
name: string
state: string | null
corridor_name: string | null
start_lat: number | null
start_lng: number | null
end_lat: number | null
end_lng: number | null
created_at: string
updated_at: string
id: string;
name: string;
state: string | null;
corridor_name: string | null;
start_lat: number | null;
start_lng: number | null;
end_lat: number | null;
end_lng: number | null;
created_at: string;
updated_at: string;
}
export interface ProjectCreate {
name: string
state?: string | null
corridor_name?: string | null
start_lat?: number | null
start_lng?: number | null
end_lat?: number | null
end_lng?: number | null
name: string;
state?: string | null;
corridor_name?: string | null;
start_lat?: number | null;
start_lng?: number | null;
end_lat?: number | null;
end_lng?: number | null;
}
export interface ProjectUpdate {
name?: string
state?: string | null
corridor_name?: string | null
start_lat?: number | null
start_lng?: number | null
end_lat?: number | null
end_lng?: number | null
name?: string;
state?: string | null;
corridor_name?: string | null;
start_lat?: number | null;
start_lng?: number | null;
end_lat?: number | null;
end_lng?: number | null;
}

View File

@@ -2,12 +2,12 @@
* Session related types for storing user selections
*/
export interface SessionContext {
projectId: string | null
projectName: string | null
packageId: string | null
packageName: string | null
chainageId: string | null
chainageName: string | null
projectId: string | null;
projectName: string | null;
packageId: string | null;
packageName: string | null;
chainageId: string | null;
chainageName: string | null;
}
export const emptySessionContext: SessionContext = {
@@ -16,5 +16,5 @@ export const emptySessionContext: SessionContext = {
packageId: null,
packageName: null,
chainageId: null,
chainageName: null
}
chainageName: null,
};

View File

@@ -2,22 +2,22 @@
* Video related types
*/
export interface Video {
id: string
filename: string
detection_type: "pothole-detection" | "sign-board-detection" | "pot-sign-detection"
status: "pending" | "processing" | "completed" | "failed"
unique_defected_sign_board?: number
unique_pothole?: number
unique_road_crack?: number
unique_damaged_road_marking?: number
unique_good_sign_board?: number
total_road_damage?: number
total_detections?: number
created_at: string
updated_at: string
id: string;
filename: string;
detection_type: 'pothole-detection' | 'sign-board-detection' | 'pot-sign-detection';
status: 'pending' | 'processing' | 'completed' | 'failed';
unique_defected_sign_board?: number;
unique_pothole?: number;
unique_road_crack?: number;
unique_damaged_road_marking?: number;
unique_good_sign_board?: number;
total_road_damage?: number;
total_detections?: number;
created_at: string;
updated_at: string;
}
export interface VideoResultData {
videoId: string
detectionType: string
videoId: string;
detectionType: string;
}

View File

@@ -1,10 +1,10 @@
export const ROUTES = {
DASHBOARD: "/dashboard",
PROJECT: "/project",
PACKAGE: "/package",
CHAINAGE: "/chainage",
ACCOUNT: "/account",
NEW_ANALYSIS: "/new-analysis",
UPLOAD: "/upload",
RESULTS: "/results",
DASHBOARD: '/dashboard',
PROJECT: '/project',
PACKAGE: '/package',
CHAINAGE: '/chainage',
ACCOUNT: '/account',
NEW_ANALYSIS: '/new-analysis',
UPLOAD: '/upload',
RESULTS: '/results',
} as const;

View File

@@ -1,11 +1,7 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
@@ -23,9 +19,7 @@
}
],
"paths": {
"@/*": [
"./src/*"
]
"@/*": ["./src/*"]
}
},
"include": [
@@ -35,7 +29,5 @@
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"
]
"exclude": ["node_modules"]
}