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 ## 📦 Prerequisites
### Backend ### Backend
- Python 3.9+ - Python 3.9+
- CUDA-compatible GPU (optional, recommended) - CUDA-compatible GPU (optional, recommended)
- FFmpeg - FFmpeg
### Frontend ### Frontend
- Node.js 18+ - Node.js 18+
- npm/yarn/pnpm - npm/yarn/pnpm
@@ -116,6 +118,7 @@ npm install @radix-ui/react-scroll-area
### Backend Configuration ### Backend Configuration
**`app/core/storage.py`** **`app/core/storage.py`**
```python ```python
from pathlib import Path from pathlib import Path
@@ -135,6 +138,7 @@ MODELS_DIR.mkdir(exist_ok=True)
``` ```
**`main.py`** **`main.py`**
```python ```python
from fastapi import FastAPI from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
@@ -166,6 +170,7 @@ if __name__ == "__main__":
### Frontend Configuration ### Frontend Configuration
**`.env.local`** **`.env.local`**
```bash ```bash
NEXT_PUBLIC_WS_URL=ws://localhost:8000/api/v1 NEXT_PUBLIC_WS_URL=ws://localhost:8000/api/v1
``` ```
@@ -173,6 +178,7 @@ NEXT_PUBLIC_WS_URL=ws://localhost:8000/api/v1
### Model Configuration ### Model Configuration
**Adaptive Parameters** (in `video_processor.py`): **Adaptive Parameters** (in `video_processor.py`):
```python ```python
# Speed < 30 km/h: ROI 50%, Confidence 0.35 # Speed < 30 km/h: ROI 50%, Confidence 0.35
# Speed 30-60 km/h: ROI 65%, Confidence 0.28 # Speed 30-60 km/h: ROI 65%, Confidence 0.28
@@ -223,6 +229,7 @@ npm start
### REST Endpoints ### REST Endpoints
#### 1. Upload Video #### 1. Upload Video
```http ```http
POST /api/v1/upload POST /api/v1/upload
Content-Type: multipart/form-data Content-Type: multipart/form-data
@@ -241,6 +248,7 @@ Response:
``` ```
#### 2. Get Processing Status #### 2. Get Processing Status
```http ```http
GET /api/v1/status/{video_id} GET /api/v1/status/{video_id}
@@ -253,6 +261,7 @@ Response:
``` ```
#### 3. Get Detection Results #### 3. Get Detection Results
```http ```http
GET /api/v1/results/{video_id} GET /api/v1/results/{video_id}
@@ -260,6 +269,7 @@ Response: See "Sample Detection Results" below
``` ```
#### 4. List All Videos #### 4. List All Videos
```http ```http
GET /api/v1/videos GET /api/v1/videos
@@ -279,24 +289,26 @@ Response:
### Internal API Calls (Frontend) ### Internal API Calls (Frontend)
**Upload Request**: **Upload Request**:
```typescript ```typescript
const formData = new FormData() const formData = new FormData();
formData.append("file", file) formData.append('file', file);
formData.append("speed_kmh", "30") formData.append('speed_kmh', '30');
const response = await fetch(`${API_URL}/upload`, { const response = await fetch(`${API_URL}/upload`, {
method: "POST", method: 'POST',
body: formData body: formData,
}) });
const result = await response.json() const result = await response.json();
// Returns: { video_id, filename, message, status } // Returns: { video_id, filename, message, status }
``` ```
**Results Request**: **Results Request**:
```typescript ```typescript
const response = await fetch(`${API_URL}/results/${videoId}`) const response = await fetch(`${API_URL}/results/${videoId}`);
const detectionData: DetectionData = await response.json() const detectionData: DetectionData = await response.json();
``` ```
--- ---
@@ -304,13 +316,15 @@ const detectionData: DetectionData = await response.json()
## 🔄 WebSocket Protocol ## 🔄 WebSocket Protocol
### Connection ### Connection
```javascript ```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 ### Message Types
#### 1. Status Update #### 1. Status Update
```json ```json
{ {
"type": "status", "type": "status",
@@ -321,6 +335,7 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
``` ```
#### 2. Progress Update #### 2. Progress Update
```json ```json
{ {
"type": "progress", "type": "progress",
@@ -332,6 +347,7 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
``` ```
#### 3. Completion #### 3. Completion
```json ```json
{ {
"type": "complete", "type": "complete",
@@ -348,6 +364,7 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
``` ```
#### 4. Error #### 4. Error
```json ```json
{ {
"type": "error", "type": "error",
@@ -357,6 +374,7 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
``` ```
#### 5. Heartbeat #### 5. Heartbeat
```json ```json
{ {
"type": "heartbeat" "type": "heartbeat"
@@ -469,28 +487,28 @@ const ws = new WebSocket(`ws://localhost:8000/api/v1/ws/${videoId}`)
```typescript ```typescript
type DetectionData = { type DetectionData = {
video_id: string video_id: string;
video_info: { video_info: {
fps: number // 30.0 fps: number; // 30.0
width: number // 1920 width: number; // 1920
height: number // 1080 height: number; // 1080
total_frames: number // 1200 total_frames: number; // 1200
} };
summary: { summary: {
unique_potholes: number // 18 unique_potholes: number; // 18
total_detections: number // 245 total_detections: number; // 245
total_frames: number // 1200 total_frames: number; // 1200
detection_rate: number // 12.25 detection_rate: number; // 12.25
} };
frames: Array<{ frames: Array<{
frame_id: number frame_id: number;
potholes: Array<{ potholes: Array<{
pothole_id: number pothole_id: number;
bbox: { x1: number; y1: number; x2: number; y2: number } bbox: { x1: number; y1: number; x2: number; y2: number };
confidence: number confidence: number;
}> }>;
}> }>;
} };
``` ```
--- ---
@@ -500,6 +518,7 @@ type DetectionData = {
### Backend Issues ### Backend Issues
**Model Not Loading** **Model Not Loading**
```bash ```bash
# Check model path # Check model path
ls models/pothole-detector.pt ls models/pothole-detector.pt
@@ -509,6 +528,7 @@ python -c "from ultralytics import YOLO; print('OK')"
``` ```
**CUDA/GPU Issues** **CUDA/GPU Issues**
```bash ```bash
# Check CUDA availability # Check CUDA availability
python -c "import torch; print(torch.cuda.is_available())" 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** **WebSocket Connection Failed**
- Ensure CORS is properly configured - Ensure CORS is properly configured
- Check firewall settings for port 8000 - Check firewall settings for port 8000
- Verify WebSocket URL matches backend - Verify WebSocket URL matches backend
@@ -525,6 +546,7 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
### Frontend Issues ### Frontend Issues
**Video Not Playing** **Video Not Playing**
```typescript ```typescript
// Check browser console for errors // Check browser console for errors
// Ensure video MIME type is supported // Ensure video MIME type is supported
@@ -532,6 +554,7 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
``` ```
**Bounding Boxes Not Showing** **Bounding Boxes Not Showing**
```typescript ```typescript
// Check canvas dimensions match video // Check canvas dimensions match video
// Verify detection data structure // Verify detection data structure
@@ -539,6 +562,7 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
``` ```
**Progress Not Updating** **Progress Not Updating**
```typescript ```typescript
// Check WebSocket connection status // Check WebSocket connection status
// Verify video_id matches between upload and WS // Verify video_id matches between upload and WS
@@ -548,12 +572,14 @@ self.pothole_model = YOLO("models/pothole-detector.pt", device='cpu')
### Performance Optimization ### Performance Optimization
**Slow Processing** **Slow Processing**
- Use GPU acceleration (CUDA) - Use GPU acceleration (CUDA)
- Reduce video resolution - Reduce video resolution
- Lower frame rate - Lower frame rate
- Adjust confidence thresholds - Adjust confidence thresholds
**High Memory Usage** **High Memory Usage**
```python ```python
# Limit thread pool workers # Limit thread pool workers
executor = ThreadPoolExecutor(max_workers=2) executor = ThreadPoolExecutor(max_workers=2)
@@ -582,6 +608,4 @@ pothole_tracker = defaultdict(lambda: deque(maxlen=10))
- Add authentication for production deployments - Add authentication for production deployments
- Use HTTPS/WSS in production - Use HTTPS/WSS in production
**Built with FastAPI, YOLO, React, and shadcn/ui** **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" />
/// <reference types="next/image-types/global" /> /// <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 // NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information. // 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", "version": "0.1.0",
"private": true, "private": true,
"scripts": { "scripts": {
"prepare": "husky install",
"build": "next build", "build": "next build",
"dev": "next dev", "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" "start": "next start"
}, },
"lint-staged": {
"*.+(js|jsx|ts|tsx)": [
"npm run lint:fix"
],
"*.+(json|md|css|scss|html)": [
"npm run format"
]
},
"dependencies": { "dependencies": {
"@radix-ui/react-avatar": "^1.1.10", "@radix-ui/react-avatar": "^1.1.10",
"@radix-ui/react-collapsible": "^1.1.12", "@radix-ui/react-collapsible": "^1.1.12",
"@radix-ui/react-dialog": "^1.1.15", "@radix-ui/react-dialog": "^1.1.15",
"@radix-ui/react-dropdown-menu": "^2.1.16", "@radix-ui/react-dropdown-menu": "^2.1.16",
"@radix-ui/react-label": "^2.1.1", "@radix-ui/react-label": "^2.1.1",
"@radix-ui/react-popover": "^1.1.4",
"@radix-ui/react-progress": "^1.1.1", "@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-separator": "^1.1.7",
"@radix-ui/react-slot": "^1.2.3", "@radix-ui/react-slot": "^1.2.3",
"@radix-ui/react-tooltip": "^1.2.8", "@radix-ui/react-tooltip": "^1.2.8",
"@tanstack/react-table": "^8.21.3", "@tanstack/react-table": "^8.21.3",
"@vercel/analytics": "1.3.1",
"axios": "^1.13.6", "axios": "^1.13.6",
"class-variance-authority": "^0.7.1", "class-variance-authority": "^0.7.1",
"clsx": "^2.1.1", "clsx": "^2.1.1",
@@ -37,8 +44,7 @@
"react-leaflet": "^5.0.0", "react-leaflet": "^5.0.0",
"recharts": "2.15.4", "recharts": "2.15.4",
"sonner": "^1.7.4", "sonner": "^1.7.4",
"tailwind-merge": "^3.3.1", "tailwind-merge": "^3.3.1"
"tailwindcss-animate": "^1.0.7"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/postcss": "^4.1.9", "@tailwindcss/postcss": "^4.1.9",
@@ -47,7 +53,14 @@
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"autoprefixer": "^10.4.20", "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", "postcss": "^8.5",
"prettier": "^3.8.1",
"tailwindcss": "^4.1.9", "tailwindcss": "^4.1.9",
"tw-animate-css": "^1.4.0", "tw-animate-css": "^1.4.0",
"typescript": "^5" "typescript": "^5"

View File

@@ -1,5 +1,5 @@
const config = { const config = {
plugins: ["@tailwindcss/postcss"], plugins: ['@tailwindcss/postcss'],
}; };
export default config; 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 { BreadcrumbBasic } from '@/components/app-breadcrumb';
import { AppSidebar } from "@/components/app-sidebar"; import { AppSidebar } from '@/components/app-sidebar';
import { ModeToggle } from "@/components/mode-toogle"; import { ModeToggle } from '@/components/mode-toogle';
import { SidebarProvider, SidebarTrigger } from "@/components/ui/sidebar"; import { SidebarProvider, SidebarTrigger } from '@/components/ui/sidebar';
import { Separator } from "@/components/ui/separator"; import { Separator } from '@/components/ui/separator';
import React from "react"; import React from 'react';
const ModulesLayout = ({ const ModulesLayout = ({
children, children,
@@ -31,5 +31,4 @@ const ModulesLayout = ({
); );
}; };
export default ModulesLayout; export default ModulesLayout;

View File

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

View File

@@ -1,470 +1,513 @@
"use client" 'use client';
import { useState, useEffect } from "react" import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from "@/components/ui/button" import { Button } from '@/components/ui/button';
import { Input } from "@/components/ui/input" import { Input } from '@/components/ui/input';
import { Label } from "@/components/ui/label" 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 { import {
Project, Select,
Package as PackageType, SelectContent,
PackageCreate, SelectItem,
PackageUpdate SelectTrigger,
} from "@/types" SelectValue,
import { ColumnDef } from "@tanstack/react-table" } from '@/components/ui/select';
import { toast } from "sonner" import {
import { Badge } from "@/components/ui/badge" Dialog,
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" DialogContent,
import { PoweredBy } from "@/components/powered-by" 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() { export default function PackagePage() {
const [packages, setPackages] = useState<PackageType[]>([]) const [packages, setPackages] = useState<PackageType[]>([]);
const [totalItems, setTotalItems] = useState(0) const [totalItems, setTotalItems] = useState(0);
const [projects, setProjects] = useState<Project[]>([]) const [projects, setProjects] = useState<Project[]>([]);
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false) const [isModalOpen, setIsModalOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null);
const [loadingProjects, setLoadingProjects] = useState(false) const [loadingProjects, setLoadingProjects] = useState(false);
// Pagination state // Pagination state
const [skip, setSkip] = useState(0) const [skip, setSkip] = useState(0);
const [limit, setLimit] = useState(10) const [limit, setLimit] = useState(10);
// Editing state // Editing state
const [isEditing, setIsEditing] = useState(false) const [isEditing, setIsEditing] = useState(false);
const [currentPackage, setCurrentPackage] = useState<PackageType | null>(null) const [currentPackage, setCurrentPackage] = useState<PackageType | null>(null);
// Form fields // Form fields
const [selectedProjectId, setSelectedProjectId] = useState("") const [selectedProjectId, setSelectedProjectId] = useState('');
const [name, setName] = useState("") const [name, setName] = useState('');
const [region, setRegion] = useState("") const [region, setRegion] = useState('');
const [chainageStartKm, setChainageStartKm] = useState<string>("") const [chainageStartKm, setChainageStartKm] = useState<string>('');
const [chainageEndKm, setChainageEndKm] = useState<string>("") const [chainageEndKm, setChainageEndKm] = useState<string>('');
// Load packages and projects // Load packages and projects
const loadPackages = async (currentSkip = skip, currentLimit = limit) => { const loadPackages = async (currentSkip = skip, currentLimit = limit) => {
try { try {
setIsLoading(true) setIsLoading(true);
setError(null) setError(null);
const data = await packageService.getPackages({ skip: currentSkip, limit: currentLimit }) const data = await packageService.getPackages({ skip: currentSkip, limit: currentLimit });
setPackages(data.items) setPackages(data.items);
setTotalItems(data.totalItems) setTotalItems(data.totalItems);
} catch (err) { } catch (err) {
setError("Failed to load packages. Please check if the backend is running.") setError('Failed to load packages. Please check if the backend is running.');
} finally { } finally {
// Add a small delay for animation stability // Add a small delay for animation stability
setTimeout(() => { setTimeout(() => {
setIsLoading(false) setIsLoading(false);
}, 800) }, 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 () => { setIsSubmitting(true);
try { setError(null);
setLoadingProjects(true)
const data = await projectService.getProjects({ skip: 0, limit: 1000 }) // Load all projects for selector try {
setProjects(data.items) if (isEditing && currentPackage) {
} catch (err) { const data: PackageUpdate = {
setError("Failed to load projects.") name: name.trim(),
} finally { region: region.trim() || null,
setLoadingProjects(false) 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(() => { const handleEdit = (pkg: PackageType) => {
loadPackages(skip, limit) setIsEditing(true);
loadProjects() setCurrentPackage(pkg);
}, [skip, limit]) 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 = () => { const handleDelete = async (pkg: PackageType) => {
setSelectedProjectId("") if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) return;
setName("")
setRegion("") try {
setChainageStartKm("") setIsLoading(true);
setChainageEndKm("") await packageService.deletePackage(pkg.id);
setError(null) toast.success('Package Deleted', {
setIsEditing(false) description: `${pkg.name} has been removed from the system.`,
setCurrentPackage(null) });
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) => { const getProjectName = (projectId: string) => {
e.preventDefault() return projects.find((p) => p.id === projectId)?.name || projectId;
if (!selectedProjectId) { };
setError("Please select a project first")
return
}
if (!name.trim()) {
setError("Package name is required")
return
}
setIsSubmitting(true) const columns: ColumnDef<PackageType>[] = [
setError(null) {
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 { const states = project.state
if (isEditing && currentPackage) { .split(',')
const data: PackageUpdate = { .map((s) => s.trim())
name: name.trim(), .filter(Boolean);
region: region.trim() || null, if (states.length === 0) return <span className="text-gray-400"></span>;
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0, const firstState = states[0];
} const remainingStates = states.slice(1);
await packageService.updatePackage(currentPackage.id, data)
toast.success("Package Updated", { return (
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`, <div className="flex items-center gap-1.5">
}) <Badge variant="secondary">{firstState}</Badge>
} else {
const data: PackageCreate = { {remainingStates.length > 0 && (
project_id: selectedProjectId, <Popover>
name: name.trim(), <PopoverTrigger asChild>
region: region.trim() || null, <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">
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0, +{remainingStates.length}
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0, </button>
} </PopoverTrigger>
await packageService.createPackage(data) <PopoverContent className="w-auto p-2" align="start">
toast.success("Package Created", { <div className="flex flex-col gap-1.5">
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`, <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 {/* Data Table */}
await loadPackages() <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 <PoweredBy />
setIsModalOpen(false) </main>
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)
}
}
const handleEdit = (pkg: PackageType) => { {/* Modal Dialog */}
setIsEditing(true) <Dialog
setCurrentPackage(pkg) open={isModalOpen}
setSelectedProjectId(pkg.project_id) onOpenChange={(open) => {
setName(pkg.name || "") if (!open) {
setRegion(pkg.region || "") setIsModalOpen(false);
setChainageStartKm(pkg.chainage_start_km?.toString() || "0") resetForm();
setChainageEndKm(pkg.chainage_end_km?.toString() || "0") } else {
setIsModalOpen(true) 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) => { <form onSubmit={handleSubmit} className="space-y-8">
if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) return {/* 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 { {/* Step 2: Package Info */}
setIsLoading(true) <div
await packageService.deletePackage(pkg.id) className={`space-y-4 ${selectedProjectId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
toast.success("Package Deleted", { >
description: `${pkg.name} has been removed from the system.`, {!isEditing && (
}) <div className="flex items-center gap-2.5">
await loadPackages() <div
} catch (err) { 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'}`}
setError("Failed to delete package") >
toast.error("Deletion Failed", { 02
description: "The package could not be removed. Please try again.", </div>
}) <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
} finally { Package Information
setIsLoading(false) </p>
} </div>
} )}
const getProjectName = (projectId: string) => { <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
return projects.find(p => p.id === projectId)?.name || projectId <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>[] = [ <div className="space-y-2">
{ <Label
accessorKey: "name", htmlFor="region"
header: "Package Name", className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2"
cell: ({ row }) => ( >
<div className="font-semibold text-gray-900 dark:text-gray-100">{row.original.name}</div> <Globe className="h-3.5 w-3.5 opacity-60" />
) Region{' '}
}, <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
{ </Label>
accessorKey: "project_id", <Input
header: "Project", id="region"
cell: ({ row }) => getProjectName(row.original.project_id) value={region}
}, onChange={(e) => setRegion(e.target.value)}
{ placeholder="e.g. North Zone"
accessorKey: "project_state", className="h-11 bg-muted/20 border-border/60"
header: "Project State", />
cell: ({ row }) => { </div>
const pkg = row.original
const project = projects.find(p => p.id === pkg.project_id)
if (!project?.state) return <span className="text-gray-400"></span>
const states = project.state.split(',').map(s => s.trim()).filter(Boolean) <div className="space-y-2">
if (states.length === 0) return <span className="text-gray-400"></span> <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] <div className="space-y-2">
const remainingStates = states.slice(1) <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 ( {/* Submit Button */}
<div className="flex items-center gap-1.5"> <div className="flex gap-4 pt-4">
<Badge variant="secondary"> <Button
{firstState} type="button"
</Badge> variant="outline"
onClick={() => {
{remainingStates.length > 0 && ( setIsModalOpen(false);
<Popover> resetForm();
<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"> disabled={isSubmitting}
+{remainingStates.length} className="flex-1"
</button> >
</PopoverTrigger> Cancel
<PopoverContent className="w-auto p-2" align="start"> </Button>
<div className="flex flex-col gap-1.5"> <Button
<p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">Other States</p> type="submit"
{remainingStates.map((item, idx) => ( disabled={isSubmitting || !name.trim() || !selectedProjectId}
<Badge key={idx} variant="secondary"> className="flex-1"
{item} >
</Badge> {isSubmitting ? (
))} <div className="flex items-center gap-2">
</div> <Loader2 className="h-4 w-4 animate-spin" />
</PopoverContent> <span>{isEditing ? 'Updating...' : 'Creating...'}</span>
</Popover> </div>
)} ) : (
</div> <div className="flex items-center gap-2">
) {isEditing ? (
} <CheckCircle2 className="h-4 w-4" />
}, ) : (
{ <Package className="h-4 w-4" />
accessorKey: "region", )}
header: "Region", <span>{isEditing ? 'Update Package' : 'Create Package'}</span>
}, </div>
{ )}
accessorKey: "chainage_start_km", </Button>
header: "Start (km)", </div>
cell: ({ row }) => row.original.chainage_start_km?.toFixed(2) ?? "0.00" </form>
}, </DialogContent>
{ </Dialog>
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>
</>
)
} }

View File

@@ -1,6 +1,6 @@
import { redirect } from "next/navigation" import { redirect } from 'next/navigation';
import { ROUTES } from "@/utils/routes" import { ROUTES } from '@/utils/routes';
export default function HomePage() { 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 { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from "@/components/ui/button" import { Button } from '@/components/ui/button';
import { Input } from "@/components/ui/input" import { Input } from '@/components/ui/input';
import { Label } from "@/components/ui/label" import { Label } from '@/components/ui/label';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog" import {
import { Loader2, CheckCircle2, Layers, MapPin, Building2, Route, X } from "lucide-react" Dialog,
import { DataTable } from "@/components/data-table" DialogContent,
import { PageHeader } from "@/components/page-header" DialogDescription,
import { projectService } from "@/services/api" DialogHeader,
import { ProjectCreate, Project, ProjectUpdate } from "@/types" DialogTitle,
import { ColumnDef } from "@tanstack/react-table" } from '@/components/ui/dialog';
import { toast } from "sonner" import { Loader2, CheckCircle2, Layers, MapPin, Building2, Route, X } from 'lucide-react';
import { Badge } from "@/components/ui/badge" import { DataTable } from '@/components/data-table';
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" import { PageHeader } from '@/components/page-header';
import { PoweredBy } from "@/components/powered-by" 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() { export default function ProjectPage() {
const [projects, setProjects] = useState<Project[]>([]) const [projects, setProjects] = useState<Project[]>([]);
const [totalItems, setTotalItems] = useState(0) const [totalItems, setTotalItems] = useState(0);
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true);
const [isModalOpen, setIsModalOpen] = useState(false) const [isModalOpen, setIsModalOpen] = useState(false);
const [isSubmitting, setIsSubmitting] = useState(false) const [isSubmitting, setIsSubmitting] = useState(false);
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null);
// Pagination state // Pagination state
const [skip, setSkip] = useState(0) const [skip, setSkip] = useState(0);
const [limit, setLimit] = useState(10) const [limit, setLimit] = useState(10);
// Editing state // Editing state
const [isEditing, setIsEditing] = useState(false) const [isEditing, setIsEditing] = useState(false);
const [currentProject, setCurrentProject] = useState<Project | null>(null) const [currentProject, setCurrentProject] = useState<Project | null>(null);
// Form fields // Form fields
const [name, setName] = useState("") const [name, setName] = useState('');
const [state, setState] = useState("") const [state, setState] = useState('');
const [corridorName, setCorridorName] = useState("") const [corridorName, setCorridorName] = useState('');
const [startLat, setStartLat] = useState("") const [startLat, setStartLat] = useState('');
const [startLng, setStartLng] = useState("") const [startLng, setStartLng] = useState('');
const [endLat, setEndLat] = useState("") const [endLat, setEndLat] = useState('');
const [endLng, setEndLng] = useState("") const [endLng, setEndLng] = useState('');
// Load projects // Load projects
const loadProjects = async (currentSkip = skip, currentLimit = limit) => { const loadProjects = async (currentSkip = skip, currentLimit = limit) => {
try { try {
setIsLoading(true) setIsLoading(true);
setError(null) setError(null);
const data = await projectService.getProjects({ skip: currentSkip, limit: currentLimit }) const data = await projectService.getProjects({ skip: currentSkip, limit: currentLimit });
setProjects(data.items) setProjects(data.items);
setTotalItems(data.totalItems) setTotalItems(data.totalItems);
} catch (err) { } catch (err) {
setError("Failed to load projects. Please check if the backend is running.") setError('Failed to load projects. Please check if the backend is running.');
} finally { } finally {
// Add a small delay for animation stability // Add a small delay for animation stability
setTimeout(() => { setTimeout(() => {
setIsLoading(false) setIsLoading(false);
}, 800) }, 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(() => { setIsSubmitting(true);
loadProjects(skip, limit) setError(null);
}, [skip, limit])
const resetForm = () => { try {
setName("") if (isEditing && currentProject) {
setState("") const data: ProjectUpdate = {
setCorridorName("") name: name.trim(),
setStartLat("") state: state.trim() || null,
setStartLng("") corridor_name: corridorName.trim() || null,
setEndLat("") start_lat: startLat ? parseFloat(startLat) : null,
setEndLng("") start_lng: startLng ? parseFloat(startLng) : null,
setError(null) end_lat: endLat ? parseFloat(endLat) : null,
setIsEditing(false) end_lng: endLng ? parseFloat(endLng) : null,
setCurrentProject(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) => { const handleEdit = (project: Project) => {
e.preventDefault() setIsEditing(true);
if (!name.trim()) { setCurrentProject(project);
setError("Project name is required") setName(project.name || '');
return 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) const handleDelete = async (project: Project) => {
setError(null) if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) return;
try { try {
if (isEditing && currentProject) { setIsLoading(true);
const data: ProjectUpdate = { await projectService.deleteProject(project.id);
name: name.trim(), toast.success('Project Deleted', {
state: state.trim() || null, description: `${project.name} has been removed from the system.`,
corridor_name: corridorName.trim() || null, });
start_lat: startLat ? parseFloat(startLat) : null, await loadProjects();
start_lng: startLng ? parseFloat(startLng) : null, } catch (err) {
end_lat: endLat ? parseFloat(endLat) : null, setError('Failed to delete project');
end_lng: endLng ? parseFloat(endLng) : null, toast.error('Deletion Failed', {
} description:
await projectService.updateProject(currentProject.id, data) 'The project could not be removed. Please try again or check your permissions.',
toast.success("Project Updated", { });
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`, } finally {
}) setIsLoading(false);
} else { }
const data: ProjectCreate = { };
name: name.trim(),
state: state.trim() || null, const columns: ColumnDef<Project>[] = [
corridor_name: corridorName.trim() || null, {
start_lat: startLat ? parseFloat(startLat) : null, accessorKey: 'name',
start_lng: startLng ? parseFloat(startLng) : null, header: 'Project Name',
end_lat: endLat ? parseFloat(endLat) : null, cell: ({ row }) => <div className="font-semibold">{row.original.name}</div>,
end_lng: endLng ? parseFloat(endLng) : null, },
} {
await projectService.createProject(data) accessorKey: 'state',
toast.success("Project Created", { header: 'State',
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`, 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 {/* Data Table */}
await loadProjects() <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 <PoweredBy />
setIsModalOpen(false) </main>
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 handleEdit = (project: Project) => { {/* Modal Dialog */}
setIsEditing(true) <Dialog
setCurrentProject(project) open={isModalOpen}
setName(project.name || "") onOpenChange={(open) => {
setState(project.state || "") if (!open) {
setCorridorName(project.corridor_name || "") setIsModalOpen(false);
setStartLat(project.start_lat?.toString() || "") resetForm();
setStartLng(project.start_lng?.toString() || "") } else {
setEndLat(project.end_lat?.toString() || "") setIsModalOpen(true);
setEndLng(project.end_lng?.toString() || "") }
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) => { <form onSubmit={handleSubmit} className="space-y-6">
if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) return {/* 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 { {/* State & Corridor Row */}
setIsLoading(true) <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
await projectService.deleteProject(project.id) <div className="space-y-2">
toast.success("Project Deleted", { <Label
description: `${project.name} has been removed from the system.`, htmlFor="state"
}) className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
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()}
> >
<DialogHeader className="gap-2"> State{' '}
<DialogTitle className="flex items-center gap-3 text-xl"> <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm"> </Label>
<Layers className="h-5 w-5" /> <Input
</div> id="state"
{isEditing ? 'Edit Project Details' : 'Create New Project'} value={state}
</DialogTitle> onChange={(e) => setState(e.target.value)}
<DialogDescription className="text-sm"> placeholder="e.g. Maharashtra"
{isEditing ? 'Update the technical specifications for your road infrastructure project.' : 'Provide the essential road data to establish a new analysis project.'} className="h-11 bg-muted/20 border-border/60"
</DialogDescription> />
</DialogHeader> </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"> {/* Submit Button */}
{/* Project Name */} <div className="flex gap-4 pt-2">
<div className="space-y-2"> <Button
<Label htmlFor="name" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> type="button"
Project Name <span className="text-destructive">*</span> variant="outline"
</Label> onClick={() => {
<Input setIsModalOpen(false);
id="name" resetForm();
value={name} }}
onChange={(e) => setName(e.target.value)} disabled={isSubmitting}
placeholder="Enter a descriptive project name..." className="flex-1 h-12 font-bold uppercase tracking-wider text-xs border-border/80 hover:bg-muted/50"
className="h-11 bg-muted/20 border-border/60" >
required Cancel
/> </Button>
</div> <Button
type="submit"
{/* State & Corridor Row */} disabled={isSubmitting || !name.trim()}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5"> className="flex-1 h-12 font-bold uppercase tracking-wider text-xs shadow-lg shadow-primary/20"
<div className="space-y-2"> >
<Label htmlFor="state" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> {isSubmitting ? (
State <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span> <div className="flex items-center gap-2">
</Label> <Loader2 className="h-4 w-4 animate-spin" />
<Input <span>{isEditing ? 'Updating...' : 'Creating...'}</span>
id="state" </div>
value={state} ) : (
onChange={(e) => setState(e.target.value)} <div className="flex items-center gap-2">
placeholder="e.g. Maharashtra" {isEditing ? (
className="h-11 bg-muted/20 border-border/60" <CheckCircle2 className="h-4 w-4" />
/> ) : (
</div> <Layers className="h-4 w-4" />
<div className="space-y-2"> )}
<Label htmlFor="corridor" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-2"> <span>{isEditing ? 'Update Project' : 'Create Project'}</span>
<Route className="h-3.5 w-3.5 opacity-60" /> </div>
Corridor Name <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span> )}
</Label> </Button>
<Input </div>
id="corridor" </form>
value={corridorName} </DialogContent>
onChange={(e) => setCorridorName(e.target.value)} </Dialog>
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>
</>
)
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,336 +1,341 @@
"use client" 'use client';
import { useState, useEffect } from "react" import { useState, useEffect } from 'react';
import { useRouter } from "next/navigation" import { useRouter } from 'next/navigation';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from "@/components/ui/button" import { Button } from '@/components/ui/button';
import { Input } from "@/components/ui/input" import { Input } from '@/components/ui/input';
import { Label } from "@/components/ui/label" import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import {
import { Loader2, TrendingUp } from "lucide-react" Select,
import { PageHeader } from "@/components/page-header" SelectContent,
import { PoweredBy } from "@/components/powered-by" SelectItem,
import { sessionService, videoService } from "@/services/api" SelectTrigger,
import { SessionContext } from "@/types" SelectValue,
import { ROUTES } from "@/utils/routes" } from '@/components/ui/select';
import { storeVideoFile } from "@/lib/video-storage" import { Loader2, TrendingUp } from 'lucide-react';
import { cn } from "@/lib/utils" 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 = [ const DETECTION_TYPES = [
{ value: "pothole-detection", label: "Pothole Detection" }, { value: 'pothole-detection', label: 'Pothole Detection' },
{ value: "sign-board-detection", label: "Signboard Detection" }, { value: 'sign-board-detection', label: 'Signboard Detection' },
{ value: "pot-sign-detection", label: "Pothole & Signboard Detection" }, { value: 'pot-sign-detection', label: 'Pothole & Signboard Detection' },
] as const ] as const;
const DETECTION_METHODS = [ const DETECTION_METHODS = [
{ value: "yolo", label: "YOLO Detection Model" }, { value: 'yolo', label: 'YOLO Detection Model' },
{ value: "yolo_vl", label: "YOLO with Vision-Language Model" }, { value: 'yolo_vl', label: 'YOLO with Vision-Language Model' },
{ value: "sam3", label: "OpenAI SAM 3 Segmentation Model" }, { value: 'sam3', label: 'OpenAI SAM 3 Segmentation Model' },
{ value: "yoloe", label: "YOLOE Open-Vocabulary Detection" }, { value: 'yoloe', label: 'YOLOE Open-Vocabulary Detection' },
{ value: "yoloe_trained_vl", label: "YOLOE With Vision Language Model" }, { value: 'yoloe_trained_vl', label: 'YOLOE With Vision Language Model' },
] as const ] 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() { export default function UploadPage() {
const router = useRouter() const router = useRouter();
const [session, setSession] = useState<SessionContext | null>(null) const [session, setSession] = useState<SessionContext | null>(null);
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true);
// Form states // Form states
const [file, setFile] = useState<File | null>(null) const [file, setFile] = useState<File | null>(null);
const [jsonFile, setJsonFile] = useState<File | null>(null) const [jsonFile, setJsonFile] = useState<File | null>(null);
const [speed, setSpeed] = useState(30) const [speed, setSpeed] = useState(30);
const [detectionType, setDetectionType] = useState<DetectionType>("pothole-detection") const [detectionType, setDetectionType] = useState<DetectionType>('pothole-detection');
const [selectMethod, setSelectMethod] = useState("yolo_vl") const [selectMethod, setSelectMethod] = useState('yolo_vl');
// Upload states // Upload states
const [uploading, setUploading] = useState(false) const [uploading, setUploading] = useState(false);
const [progress, setProgress] = useState(0) const [progress, setProgress] = useState(0);
const [statusMessage, setStatusMessage] = useState("") const [statusMessage, setStatusMessage] = useState('');
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null);
// Load session on mount // Load session on mount
useEffect(() => { useEffect(() => {
const storedSession = sessionService.loadSession() const storedSession = sessionService.loadSession();
if (!sessionService.isSessionValid(storedSession)) { if (!sessionService.isSessionValid(storedSession)) {
router.replace(ROUTES.NEW_ANALYSIS) router.replace(ROUTES.NEW_ANALYSIS);
return return;
} }
setSession(storedSession) setSession(storedSession);
setIsLoading(false) setIsLoading(false);
}, [router]) }, [router]);
const handleUpload = async () => { const handleUpload = async () => {
if (!file) { if (!file) {
setError("Please select a video file") setError('Please select a video file');
return return;
} }
const formData = new FormData() const formData = new FormData();
formData.append("file", file) formData.append('file', file);
formData.append("detection_type", detectionType) formData.append('detection_type', detectionType);
formData.append("speed_kmh", speed.toString()) formData.append('speed_kmh', speed.toString());
formData.append("detection_mode", selectMethod) formData.append('detection_mode', selectMethod);
if (jsonFile) { if (jsonFile) {
formData.append("json_file", jsonFile) formData.append('json_file', jsonFile);
} }
setUploading(true) setUploading(true);
setProgress(0) setProgress(0);
setStatusMessage("Uploading...") setStatusMessage('Uploading...');
setError(null) setError(null);
try {
const result = await videoService.uploadVideo(formData);
// Store file locally for potential recovery/results display
if (file) {
try { try {
const result = await videoService.uploadVideo(formData); await storeVideoFile(result.video_id, file);
// 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}`)
} catch (err) { } catch (err) {
let errorMessage = "Upload failed" console.error('Failed to store video file:', err);
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)
} }
} }
const handleBackToSelection = () => { sessionService.saveVideoData({ videoId: result.video_id, detectionType });
sessionService.clearSession()
router.push(ROUTES.NEW_ANALYSIS)
}
const getTitle = () => { // Redirect to the dynamic processing page
if (detectionType === "pothole-detection") return "Pothole Detection" router.push(`/upload/${result.video_id}`);
if (detectionType === "sign-board-detection") return "Signboard Detection" } catch (err) {
return "Pothole & Signboard Detection" 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) { const handleBackToSelection = () => {
return ( sessionService.clearSession();
<div className="min-h-screen flex items-center justify-center"> router.push(ROUTES.NEW_ANALYSIS);
<Card className="p-8"> };
<Loader2 className="h-8 w-8 animate-spin text-primary" />
</Card>
</div>
)
}
const getTitle = () => {
if (detectionType === 'pothole-detection') return 'Pothole Detection';
if (detectionType === 'sign-board-detection') return 'Signboard Detection';
return 'Pothole & Signboard Detection';
};
if (isLoading) {
return ( return (
<div className="min-h-screen"> <div className="min-h-screen flex items-center justify-center">
{/* Main Content */} <Card className="p-8">
<main className="min-h-screen flex flex-col"> <Loader2 className="h-8 w-8 animate-spin text-primary" />
<div className="flex-1 container mx-auto px-6 py-6 max-w-340 flex flex-col"> </Card>
{/* Header */} </div>
<div className="mb-6"> );
<PageHeader }
title={getTitle()}
description="Upload video file and fill in required details to start the road analysis" return (
icon={TrendingUp} <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> </div>
<div className="flex flex-col border-l pl-12 border-border/60">
{/* Compact Session Info Bar */} <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
{session && ( Package
<div className="mb-6"> </span>
<Card className="p-0 border shadow-sm overflow-hidden"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
<div className="flex flex-col md:flex-row md:items-center justify-between py-4 px-6 gap-6 bg-card"> {session.packageName}
<div className="flex flex-wrap items-center gap-x-12 gap-y-4"> </span>
<div className="flex flex-col"> </div>
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Project</span> <div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-base font-bold leading-tight"> <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
{session.projectName} Chainage
</span> </span>
</div> <span className="text-sm font-semibold text-muted-foreground leading-tight">
<div className="flex flex-col border-l pl-12 border-border/60"> {session.chainageName}
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span> </span>
<span className="text-sm font-semibold text-muted-foreground leading-tight"> </div>
{session.packageName} </div>
</span> <Button
</div> variant="outline"
<div className="flex flex-col border-l pl-12 border-border/60"> size="sm"
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Chainage</span> onClick={handleBackToSelection}
<span className="text-sm font-semibold text-muted-foreground leading-tight"> className="font-semibold px-6 shrink-0 h-9"
{session.chainageName} >
</span> Change Selection
</div> </Button>
</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> </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> </div>
) </main>
</div>
);
} }

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
"use client"; 'use client';
import React from "react"; import React from 'react';
import { usePathname } from "next/navigation"; import { usePathname } from 'next/navigation';
import { import {
Breadcrumb, Breadcrumb,
BreadcrumbItem, BreadcrumbItem,
@@ -9,18 +9,18 @@ import {
BreadcrumbList, BreadcrumbList,
BreadcrumbPage, BreadcrumbPage,
BreadcrumbSeparator, BreadcrumbSeparator,
} from "@/components/ui/breadcrumb"; } from '@/components/ui/breadcrumb';
export function BreadcrumbBasic() { export function BreadcrumbBasic() {
const pathname = usePathname(); 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") // Helper to format segment (e.g., "new-analysis" -> "New Analysis")
const formatSegment = (segment: string) => { const formatSegment = (segment: string) => {
return segment return segment
.split("-") .split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1)) .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(" "); .join(' ');
}; };
return ( return (
@@ -32,7 +32,7 @@ export function BreadcrumbBasic() {
{segments.length > 0 && <BreadcrumbSeparator />} {segments.length > 0 && <BreadcrumbSeparator />}
{segments.map((segment, index) => { {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; const isLast = index === segments.length - 1;
// Skip segments that represent module groups or generic IDs if needed // 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() { export function BackgroundGradient() {
return ( 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 */} {/* Top Gradient */}
<div className="absolute inset-x-0 top-0 transform-gpu overflow-hidden blur-3xl"> <div className="absolute inset-x-0 top-0 transform-gpu overflow-hidden blur-3xl">
<div <div
@@ -25,7 +28,7 @@ export function BackgroundGradient() {
/> />
</div> </div>
</div> </div>
) );
} }
export function BackgroundGradientBottom() { export function BackgroundGradientBottom() {

View File

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

View File

@@ -1,137 +1,138 @@
"use client" 'use client';
import { useEffect } from "react" import { useEffect } from 'react';
import { MapContainer, TileLayer, CircleMarker, Popup, useMap } from "react-leaflet" import { MapContainer, TileLayer, CircleMarker, Popup, useMap } from 'react-leaflet';
import { LatLngBounds, LatLng } from "leaflet" import { LatLngBounds, LatLng } from 'leaflet';
import "leaflet/dist/leaflet.css" import 'leaflet/dist/leaflet.css';
import { Detection } from "@/types" import { Detection } from '@/types';
interface DashboardMapContentProps { interface DashboardMapContentProps {
detections: Detection[] detections: Detection[];
} }
// Component to auto-fit map bounds to show all markers // Component to auto-fit map bounds to show all markers
function FitBounds({ bounds }: { bounds: LatLngBounds }) { function FitBounds({ bounds }: { bounds: LatLngBounds }) {
const map = useMap() const map = useMap();
useEffect(() => { useEffect(() => {
if (bounds.isValid()) { if (bounds.isValid()) {
map.fitBounds(bounds, { padding: [50, 50] }) map.fitBounds(bounds, { padding: [50, 50] });
} }
}, [bounds, map]) }, [bounds, map]);
return null return null;
} }
export default function DashboardMapContent({ detections }: DashboardMapContentProps) { export default function DashboardMapContent({ detections }: DashboardMapContentProps) {
if (detections.length === 0) { 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(' ')
}
return ( return (
<MapContainer <div className="h-full w-full flex items-center justify-center bg-muted/20">
center={center} <p className="text-muted-foreground">No detections to display</p>
zoom={13} </div>
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 */} // Calculate bounds to fit all markers
{detections.map((detection, idx) => { const firstDetection = detections[0];
const colors = getMarkerColor(detection.type) const bounds = new LatLngBounds(
const typeName = getTypeName(detection.type) new LatLng(firstDetection.latitude!, firstDetection.longitude!),
new LatLng(firstDetection.latitude!, firstDetection.longitude!),
);
return ( detections.forEach((d) => {
<CircleMarker if (d.latitude && d.longitude) {
key={`${detection.id}-${idx}`} bounds.extend(new LatLng(d.latitude, d.longitude));
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 */} // Center point
<FitBounds bounds={bounds} /> const center: [number, number] = [
</MapContainer> (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 { useEffect, useState } from 'react';
import dynamic from "next/dynamic" import dynamic from 'next/dynamic';
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card" import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, Milestone } from "lucide-react" import { Loader2, Milestone } from 'lucide-react';
import { Detection } from "@/types" import { Detection } from '@/types';
// Dynamically import the map to avoid SSR issues with Leaflet // Dynamically import the map to avoid SSR issues with Leaflet
const DashboardMapContent = dynamic( const DashboardMapContent = dynamic(() => import('./dashboard-map-content'), {
() => import("./dashboard-map-content"), ssr: false,
{ loading: () => (
ssr: false, <div className="h-full w-full flex items-center justify-center">
loading: () => ( <Loader2 className="h-8 w-8 text-primary" />
<div className="h-full w-full flex items-center justify-center"> </div>
<Loader2 className="h-8 w-8 text-primary" /> ),
</div> });
)
}
)
interface DashboardMapProps { interface DashboardMapProps {
className?: string className?: string;
selectedProjectId?: string | null selectedProjectId?: string | null;
selectedPackageId?: string | null selectedPackageId?: string | null;
selectedChainageId?: string | null selectedChainageId?: string | null;
projectSummary?: any projectSummary?: any;
} }
export function DashboardMap({ export function DashboardMap({
className, className,
selectedProjectId, selectedProjectId,
selectedPackageId, selectedPackageId,
selectedChainageId, selectedChainageId,
projectSummary projectSummary,
}: DashboardMapProps) { }: DashboardMapProps) {
const [detections, setDetections] = useState<Detection[]>([]) const [detections, setDetections] = useState<Detection[]>([]);
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null);
useEffect(() => { useEffect(() => {
if (!projectSummary) { if (!projectSummary) {
setDetections([]) setDetections([]);
setIsLoading(false) setIsLoading(false);
return 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
} }
return ( try {
<Card className={`overflow-hidden ${className}`}> setIsLoading(true);
<CardHeader className="pb-2"> setError(null);
<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 */} const filteredDetections: Detection[] = [];
<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"> const packagesToProcess =
<div className="w-2.5 h-2.5 rounded-full bg-red-500" /> selectedPackageId && selectedPackageId !== 'all'
<span className="text-muted-foreground font-medium">Potholes ({counts.pothole})</span> ? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
</div> : projectSummary.packages || {};
<div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-blue-500" /> for (const [pkgName, pkg] of Object.entries(packagesToProcess)) {
<span className="text-muted-foreground font-medium">Defected Signs ({counts.defected_sign_board})</span> const chainagesToProcess =
</div> selectedChainageId && selectedChainageId !== 'all'
<div className="flex items-center gap-1"> ? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
<div className="w-2.5 h-2.5 rounded-full bg-amber-500" /> : (pkg as any).chainages || {};
<span className="text-muted-foreground font-medium">Cracks ({counts.road_crack})</span>
</div> for (const [chnName, chn] of Object.entries(chainagesToProcess)) {
<div className="flex items-center gap-1"> if (!chn) continue;
<div className="w-2.5 h-2.5 rounded-full bg-indigo-500" /> const chainageDetections = (chn as any).detections || [];
<span className="text-muted-foreground font-medium">Markings ({counts.damaged_road_marking})</span> filteredDetections.push(...chainageDetections);
</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> setDetections(filteredDetections);
</div> } catch (err) {
</div> console.error('Failed to extract detections:', err);
</div> setError('Failed to load detection data');
</CardHeader> } finally {
<CardContent className="p-0"> setIsLoading(false);
<div className="h-[500px] p-2 w-full relative"> }
{isLoading ? ( }, [projectSummary, selectedPackageId, selectedChainageId]);
<div className="h-full w-full flex items-center justify-center bg-muted/50">
<Loader2 className="h-8 w-8 text-primary animate-spin" /> // Filter detections with valid GPS coordinates
</div> const validDetections = detections.filter((d) => d.latitude && d.longitude);
) : error ? (
<div className="h-full w-full flex items-center justify-center bg-muted/50"> // Count detections by category
<p className="text-muted-foreground">{error}</p> const counts = {
</div> defected_sign_board: validDetections.filter(
) : validDetections.length === 0 ? ( (d) => d.type?.toLowerCase() === 'defected_sign_board',
<div className="h-full w-full flex items-center justify-center bg-muted/50"> ).length,
<div className="text-center"> pothole: validDetections.filter((d) => d.type?.toLowerCase() === 'pothole').length,
<p className="text-muted-foreground">No detections with GPS coordinates found</p> road_crack: validDetections.filter((d) => d.type?.toLowerCase() === 'road_crack').length,
<p className="text-sm text-muted-foreground mt-1 opacity-70">Process some videos to see detections on the map</p> damaged_road_marking: validDetections.filter(
</div> (d) => d.type?.toLowerCase() === 'damaged_road_marking',
</div> ).length,
) : ( good_sign_board: validDetections.filter((d) => d.type?.toLowerCase() === 'good_sign_board')
<DashboardMapContent detections={validDetections} /> .length,
)} };
</div>
</CardContent> return (
</Card> <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 { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent, CardHeader } from "@/components/ui/card" import { Card, CardContent, CardHeader } from '@/components/ui/card';
export function DashboardSkeleton() { export function DashboardSkeleton() {
return ( return (
@@ -42,18 +42,18 @@ export function DashboardSkeleton() {
{/* Map Skeleton */} {/* Map Skeleton */}
<Card> <Card>
<CardHeader className="pb-2"> <CardHeader className="pb-2">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Skeleton className="w-10 h-10 rounded-md" /> <Skeleton className="w-10 h-10 rounded-md" />
<Skeleton className="h-6 w-48" /> <Skeleton className="h-6 w-48" />
</div> </div>
<Skeleton className="h-8 w-32 rounded-full" /> <Skeleton className="h-8 w-32 rounded-full" />
</div> </div>
</CardHeader> </CardHeader>
<CardContent className="p-2"> <CardContent className="p-2">
<Skeleton className="h-[500px] w-full rounded-md" /> <Skeleton className="h-[500px] w-full rounded-md" />
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
) );
} }

View File

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

View File

@@ -1,125 +1,131 @@
"use client" 'use client';
import { import {
Select, Select,
SelectContent, SelectContent,
SelectItem, SelectItem,
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select" } from '@/components/ui/select';
import { FolderOpen, Package, Milestone } from "lucide-react" import { FolderOpen, Package, Milestone } from 'lucide-react';
import { Project } from "@/types" import { Project } from '@/types';
interface FilterSelectorProps { interface FilterSelectorProps {
projects: Project[] projects: Project[];
selectedProjectId: string | null selectedProjectId: string | null;
selectedPackageId: string | null selectedPackageId: string | null;
selectedChainageId: string | null selectedChainageId: string | null;
onProjectChange: (projectId: string) => void onProjectChange: (projectId: string) => void;
onPackageChange: (packageId: string) => void onPackageChange: (packageId: string) => void;
onChainageChange: (chainageId: string) => void onChainageChange: (chainageId: string) => void;
packages: Array<{ id: string; name: string }> packages: Array<{ id: string; name: string }>;
chainages: Array<{ id: string; name: string }> chainages: Array<{ id: string; name: string }>;
isLoading?: boolean isLoading?: boolean;
} }
export function FilterSelector({ export function FilterSelector({
projects, projects,
selectedProjectId, selectedProjectId,
selectedPackageId, selectedPackageId,
selectedChainageId, selectedChainageId,
onProjectChange, onProjectChange,
onPackageChange, onPackageChange,
onChainageChange, onChainageChange,
packages, packages,
chainages, chainages,
isLoading = false isLoading = false,
}: FilterSelectorProps) { }: FilterSelectorProps) {
return ( return (
<div className="flex flex-col gap-5 p-5"> <div className="flex flex-col gap-5 p-5">
{/* Project Dropdown */} {/* Project Dropdown */}
<div className="space-y-3"> <div className="space-y-3">
<div className="flex items-center gap-2.5"> <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"> <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" /> <FolderOpen className="h-4 w-4" />
</div> </div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">Project</span> <span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">
</div> Project
<Select </span>
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> </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 { Card, CardContent } from '@/components/ui/card';
import { LucideIcon } from "lucide-react" import { LucideIcon } from 'lucide-react';
import { motion } from "motion/react" import { motion } from 'motion/react';
interface StatsCardProps { interface StatsCardProps {
title: string title: string;
subtitle?: string subtitle?: string;
value: number | string value: number | string;
icon: LucideIcon icon: LucideIcon;
isLoading?: boolean isLoading?: boolean;
} }
export function StatsCard({ export function StatsCard({
title, title,
subtitle, subtitle,
value, value,
icon: Icon, icon: Icon,
isLoading = false isLoading = false,
}: StatsCardProps) { }: StatsCardProps) {
return ( return (
<motion.div <motion.div
whileHover={{ y: -4, scale: 1.02 }} whileHover={{ y: -4, scale: 1.02 }}
transition={{ type: "spring", stiffness: 400, damping: 17 }} transition={{ type: 'spring', stiffness: 400, damping: 17 }}
className="h-full" className="h-full"
> >
<Card className="h-full py-6 px-4 transition-colors cursor-pointer"> <Card className="h-full py-6 px-4 transition-colors cursor-pointer">
<CardContent className="p-0 flex items-center justify-between gap-6"> <CardContent className="p-0 flex items-center justify-between gap-6">
<div className="flex flex-col gap-1 min-w-0"> <div className="flex flex-col gap-1 min-w-0">
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider"> <h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wider">
{title} {title}
</h3> </h3>
<div className="flex flex-col"> <div className="flex flex-col">
{isLoading ? ( {isLoading ? (
<div className="h-10 w-24 bg-muted rounded-md mt-2 animate-pulse" /> <div className="h-10 w-24 bg-muted rounded-md mt-2 animate-pulse" />
) : ( ) : (
<> <>
<p className="text-3xl font-bold tracking-tight"> <p className="text-3xl font-bold tracking-tight">{value}</p>
{value} {subtitle && (
</p> <p className="text-xs text-muted-foreground mt-1 line-clamp-1">{subtitle}</p>
{subtitle && ( )}
<p className="text-xs text-muted-foreground mt-1 line-clamp-1"> </>
{subtitle} )}
</p> </div>
)} </div>
</>
)}
</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"> <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" /> <Icon className="h-6 w-6" />
</div> </div>
</CardContent> </CardContent>
</Card> </Card>
</motion.div> </motion.div>
) );
} }

View File

@@ -1,69 +1,71 @@
"use client"; 'use client';
import { Table } from "@tanstack/react-table"; import { Table } from '@tanstack/react-table';
import { import {
Select, Select,
SelectContent, SelectContent,
SelectItem, SelectItem,
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} from "@/components/ui/select"; } from '@/components/ui/select';
import { Button } from "@/components/ui/button"; import { Button } from '@/components/ui/button';
import { ChevronLeft, ChevronRight } from "lucide-react"; import { ChevronLeft, ChevronRight } from 'lucide-react';
export function TableFooter<TData>({ table }: { table: Table<TData> }) { export function TableFooter<TData>({ table }: { table: Table<TData> }) {
return ( 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 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 gap-6">
<div className="flex items-center space-x-2"> <div className="flex items-center space-x-2">
<p className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">Rows per page</p> <p className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider">
<Select Rows per page
value={`${table.getState().pagination.pageSize}`} </p>
onValueChange={(value) => { <Select
table.setPageSize(Number(value)); 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> <SelectTrigger className="h-8 w-[70px] bg-transparent border-border/40 text-xs font-semibold">
<SelectContent side="top" className="min-w-[70px]"> <SelectValue placeholder={table.getState().pagination.pageSize} />
{[10, 20, 30, 40, 50].map((pageSize) => ( </SelectTrigger>
<SelectItem key={pageSize} value={`${pageSize}`} className="text-xs"> <SelectContent side="top" className="min-w-[70px]">
{pageSize} {[10, 20, 30, 40, 50].map((pageSize) => (
</SelectItem> <SelectItem key={pageSize} value={`${pageSize}`} className="text-xs">
))} {pageSize}
</SelectContent> </SelectItem>
</Select> ))}
</div> </SelectContent>
</div> </Select>
<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> </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"; 'use client';
import { SearchIcon } from "lucide-react"; import { SearchIcon } from 'lucide-react';
import { Input } from "@/components/ui/input"; import { Input } from '@/components/ui/input';
const SearchBar = () => { const SearchBar = () => {
return ( return (
<div className="relative w-full"> <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" /> <SearchIcon className="absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground/70" />
<Input <Input
placeholder="Search resources..." placeholder="Search resources..."
className="pl-9 h-10 text-sm bg-muted/20 border-border/40 focus:bg-background transition-all" className="pl-9 h-10 text-sm bg-muted/20 border-border/40 focus:bg-background transition-all"
/> />
</div> </div>
); );
}; };
export default SearchBar; export default SearchBar;

View File

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

View File

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

View File

@@ -1,189 +1,194 @@
"use client"; 'use client';
import React from "react"; import React from 'react';
import { import {
ColumnDef, ColumnDef,
SortingState, SortingState,
flexRender, flexRender,
getCoreRowModel, getCoreRowModel,
useReactTable, useReactTable,
getSortedRowModel, getSortedRowModel,
getPaginationRowModel, getPaginationRowModel,
} from "@tanstack/react-table"; } from '@tanstack/react-table';
import { Table, TableBody, TableCell, TableRow } from "@/components/ui/table"; import { Table, TableBody, TableCell, TableRow } from '@/components/ui/table';
import { Skeleton } from "@/components/ui/skeleton"; import { Skeleton } from '@/components/ui/skeleton';
import { Button } from "@/components/ui/button"; import { Button } from '@/components/ui/button';
import { Edit3, MoreHorizontal, Trash2 } from "lucide-react"; import { Edit3, MoreHorizontal, Trash2 } from 'lucide-react';
import TopHeader from "./Header"; import TopHeader from './Header';
import TableHeader from "./TableHeader"; import TableHeader from './TableHeader';
import { TableFooter } from "./Footer"; import { TableFooter } from './Footer';
import { cn } from "@/lib/utils"; import { cn } from '@/lib/utils';
export interface DataTableProps<TData, TValue> { export interface DataTableProps<TData, TValue> {
columns: ColumnDef<TData, TValue>[]; columns: ColumnDef<TData, TValue>[];
data: TData[]; data: TData[];
title?: string; title?: string;
onAddNew?: () => void; onAddNew?: () => void;
addButtonText?: string; addButtonText?: string;
isLoading?: boolean; isLoading?: boolean;
onEdit?: (item: TData) => void; onEdit?: (item: TData) => void;
onDelete?: (item: TData) => void; onDelete?: (item: TData) => void;
pagination?: { pagination?: {
skip: number; skip: number;
limit: number; limit: number;
totalItems?: number; totalItems?: number;
onPageChange: (newSkip: number) => void; onPageChange: (newSkip: number) => void;
onLimitChange: (newLimit: number) => void; onLimitChange: (newLimit: number) => void;
}; };
} }
export function DataTable<TData, TValue>({ export function DataTable<TData, TValue>({
columns: initialColumns, columns: initialColumns,
data, data,
title, title,
onAddNew, onAddNew,
addButtonText, addButtonText,
isLoading = false, isLoading = false,
onEdit, onEdit,
onDelete, onDelete,
pagination, pagination,
}: DataTableProps<TData, TValue>) { }: DataTableProps<TData, TValue>) {
const [rowSelection, setRowSelection] = React.useState({}); const [rowSelection, setRowSelection] = React.useState({});
const [sorting, setSorting] = React.useState<SortingState>([]); const [sorting, setSorting] = React.useState<SortingState>([]);
const columns = React.useMemo(() => { const columns = React.useMemo(() => {
const cols: ColumnDef<TData, TValue>[] = [ const cols: ColumnDef<TData, TValue>[] = [...initialColumns];
...initialColumns,
];
if (onEdit || onDelete) { if (onEdit || onDelete) {
cols.push({ cols.push({
id: "actions", id: 'actions',
header: () => <div className="text-right px-4">Action</div>, header: () => <div className="text-right px-4">Action</div>,
cell: ({ row }) => { cell: ({ row }) => {
const item = row.original; const item = row.original;
return ( return (
<div className="flex justify-end gap-3 px-4"> <div className="flex justify-end gap-3 px-4">
{onEdit && ( {onEdit && (
<button <button
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
onEdit(item); onEdit(item);
}} }}
className="flex items-center justify-center h-8 w-8 rounded-md text-primary hover:bg-foreground/10 transition-all duration-200" 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" /> <Edit3 className="h-4.5 w-4.5" />
</button> </button>
)} )}
{onDelete && ( {onDelete && (
<button <button
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
onDelete(item); 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" 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" /> <Trash2 className="h-4.5 w-4.5" />
</button> </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>
);
},
});
}
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> </div>
); <TableFooter table={table} />
</div>
</div>
);
} }

View File

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

View File

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

View File

@@ -1,41 +1,34 @@
"use client" 'use client';
import { LucideIcon } from "lucide-react" import { LucideIcon } from 'lucide-react';
import { Reveal } from "@/components/ui/reveal" import { Reveal } from '@/components/ui/reveal';
interface PageHeaderProps { interface PageHeaderProps {
title: string title: string;
description: string description: string;
icon?: LucideIcon icon?: LucideIcon;
children?: React.ReactNode children?: React.ReactNode;
actions?: React.ReactNode actions?: React.ReactNode;
} }
export function PageHeader({ title, description, icon: Icon, children, actions }: PageHeaderProps) { export function PageHeader({ title, description, icon: Icon, children, actions }: PageHeaderProps) {
return ( return (
<Reveal direction="down" className="w-full"> <Reveal direction="down" className="w-full">
<div className="flex items-center justify-between w-full"> <div className="flex items-center justify-between w-full">
<div className="flex items-center gap-6"> <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"> {/* <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" />} {Icon && <Icon className="h-7 w-7" />}
{children} {children}
</div> */} </div> */}
<div className="flex flex-col"> <div className="flex flex-col">
<h1 className="text-3xl font-extrabold tracking-tight "> <h1 className="text-3xl font-extrabold tracking-tight ">{title}</h1>
{title} <p className="text-muted-foreground mt-1 text-sm font-semibold tracking-wide opacity-80">
</h1> {description}
<p className="text-muted-foreground mt-1 text-sm font-semibold tracking-wide opacity-80"> </p>
{description} </div>
</p> </div>
</div> {actions && <div className="flex items-center gap-4">{actions}</div>}
</div> </div>
{actions && ( </Reveal>
<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() { export function PoweredBy() {
return ( return (
<div className="flex items-center justify-center gap-2 mt-3 transition-opacity duration-300"> <div className="flex items-center justify-center gap-2 mt-3 transition-opacity duration-300">
<span className="font-medium text-muted-foreground"> <span className="font-medium text-muted-foreground">Powered by</span>
Powered by <Image src="/sg.svg" alt="Sentient Geeks" width={130} height={20} />
</span> </div>
<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 { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from "@/components/ui/button" import { Button } from '@/components/ui/button';
import { Label } from "@/components/ui/label" 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 { import {
Project, Select,
Package as PackageType, SelectContent,
Chainage, SelectItem,
SessionContext SelectTrigger,
} from "@/types" SelectValue,
import { cn } from "@/lib/utils" } 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 = { type ProjectSelectionSectionProps = {
onSelectionComplete: (session: SessionContext) => void onSelectionComplete: (session: SessionContext) => void;
} };
export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectionSectionProps) { export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectionSectionProps) {
// Data states // Data states
const [projects, setProjects] = useState<Project[]>([]) const [projects, setProjects] = useState<Project[]>([]);
const [packages, setPackages] = useState<PackageType[]>([]) const [packages, setPackages] = useState<PackageType[]>([]);
const [chainages, setChainages] = useState<Chainage[]>([]) const [chainages, setChainages] = useState<Chainage[]>([]);
// Selection states // Selection states
const [selectedProject, setSelectedProject] = useState<Project | null>(null) const [selectedProject, setSelectedProject] = useState<Project | null>(null);
const [selectedPackage, setSelectedPackage] = useState<PackageType | null>(null) const [selectedPackage, setSelectedPackage] = useState<PackageType | null>(null);
const [selectedChainage, setSelectedChainage] = useState<Chainage | null>(null) const [selectedChainage, setSelectedChainage] = useState<Chainage | null>(null);
// Loading states // Loading states
const [loadingProjects, setLoadingProjects] = useState(true) const [loadingProjects, setLoadingProjects] = useState(true);
const [loadingPackages, setLoadingPackages] = useState(false) const [loadingPackages, setLoadingPackages] = useState(false);
const [loadingChainages, setLoadingChainages] = useState(false) const [loadingChainages, setLoadingChainages] = useState(false);
// Error state // Error state
const [error, setError] = useState<string | null>(null) const [error, setError] = useState<string | null>(null);
// Load projects on mount // Load projects on mount
useEffect(() => { useEffect(() => {
const loadProjects = async () => { const loadProjects = async () => {
try { try {
setLoadingProjects(true) setLoadingProjects(true);
setError(null) setError(null);
const data = await projectService.getProjects() const data = await projectService.getProjects();
setProjects(data.items) setProjects(data.items);
} catch (err) { } catch (err) {
console.error("Failed to load projects:", err) console.error('Failed to load projects:', err);
setError("Failed to load projects. Please check if the backend is running.") setError('Failed to load projects. Please check if the backend is running.');
} finally { } finally {
setLoadingProjects(false) setLoadingProjects(false);
} }
} };
loadProjects() loadProjects();
}, []) }, []);
// Load packages when project changes // Load packages when project changes
useEffect(() => { useEffect(() => {
if (!selectedProject) { if (!selectedProject) {
setPackages([]) setPackages([]);
setSelectedPackage(null) setSelectedPackage(null);
return 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)
} }
const handlePackageChange = (packageId: string) => { const loadPackages = async () => {
const pkg = packages.find(p => p.id === packageId) || null try {
setSelectedPackage(pkg) 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 loadChainages = async () => {
const chainage = chainages.find(chn => chn.id === chainageId) || null try {
setSelectedChainage(chainage) 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 = () => { const isComplete = selectedProject && selectedPackage && selectedChainage;
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 // 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 return (
const getStepStatus = (step: number) => { <Card className="overflow-hidden">
if (step === 1) return selectedProject ? 'completed' : 'active' <CardHeader className="pb-6">
if (step === 2) return selectedPackage ? 'completed' : selectedProject ? 'active' : 'pending' <div className="flex flex-col gap-6">
if (step === 3) return selectedChainage ? 'completed' : selectedPackage ? 'active' : 'pending' <div>
return 'pending' <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 ( {/* Step Progress Indicator */}
<Card className="overflow-hidden"> <div className="flex items-center justify-center pt-2">
<CardHeader className="pb-6"> {[1, 2, 3].map((step, index) => {
<div className="flex flex-col gap-6"> const status = getStepStatus(step);
<div> const labels = ['Project', 'Package', 'Chainage'];
<CardTitle className="text-2xl font-bold">Select Project Chainage</CardTitle> return (
<CardDescription className="mt-2 text-base"> <div key={step} className="flex items-center">
Select Project, Package & Chainage to begin intelligent road analysis. <div className="flex flex-col items-center">
</CardDescription> <div
</div> className={cn(
'w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all',
{/* Step Progress Indicator */} status === 'completed'
<div className="flex items-center justify-center pt-2"> ? 'bg-primary text-primary-foreground'
{[1, 2, 3].map((step, index) => { : status === 'active'
const status = getStepStatus(step) ? 'bg-primary text-primary-foreground ring-4 ring-primary/10'
const labels = ['Project', 'Package', 'Chainage'] : 'bg-muted text-muted-foreground',
return ( )}
<div key={step} className="flex items-center"> >
<div className="flex flex-col items-center"> {status === 'completed' ? <Check className="h-5 w-5" /> : step}
<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>
)
})}
</div> </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> </div>
</CardHeader> );
})}
</div>
</div>
</CardHeader>
<CardContent className="space-y-8"> <CardContent className="space-y-8">
{/* Error Display */} {/* Error Display */}
{error && ( {error && (
<div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm"> <div className="p-4 rounded-md bg-destructive/10 border border-destructive/20 text-destructive text-sm">
{error} {error}
</div> </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"> {/* Package Dropdown */}
{/* Project Dropdown */} <div className="space-y-2">
<div className="space-y-2"> <Label htmlFor="package" className="text-sm font-semibold">
<Label htmlFor="project" className="text-sm font-semibold"> Package
Project </Label>
</Label> <Select
<Select value={selectedPackage?.id || ''}
value={selectedProject?.id || ""} onValueChange={handlePackageChange}
onValueChange={handleProjectChange} disabled={!selectedProject || loadingPackages}
disabled={loadingProjects} >
> <SelectTrigger id="package" className="h-11">
<SelectTrigger id="project" className="h-11"> {loadingPackages ? (
{loadingProjects ? ( <div className="flex items-center gap-2">
<div className="flex items-center gap-2"> <Loader2 className="h-4 w-4 animate-spin" />
<Loader2 className="h-4 w-4 animate-spin" /> <span>Loading...</span>
<span>Loading...</span> </div>
</div> ) : (
) : ( <SelectValue
<SelectValue placeholder="Select project" /> placeholder={selectedProject ? 'Select package' : 'Select project first'}
)} />
</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>
)} )}
</SelectTrigger>
<SelectContent>
{packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id}>
{pkg.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{/* Proceed Button */} {/* Chainage Dropdown */}
<Button <div className="space-y-2">
onClick={handleProceed} <Label htmlFor="chainage" className="text-sm font-semibold">
disabled={!isComplete} Chainage
className="w-full h-12 text-base font-bold uppercase tracking-wide" </Label>
size="lg" <Select
> value={selectedChainage?.id || ''}
{isComplete ? "Proceed to Upload" : "Select all fields to proceed"} onValueChange={handleChainageChange}
</Button> disabled={!selectedPackage || loadingChainages}
</CardContent> >
</Card> <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 * as React from 'react';
import { ThemeProvider as NextThemesProvider } from "next-themes" import { ThemeProvider as NextThemesProvider } from 'next-themes';
export function ThemeProvider({ export function ThemeProvider({
children, children,
...props ...props
}: React.ComponentProps<typeof NextThemesProvider>) { }: 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 React from 'react';
import * as AvatarPrimitive from "@radix-ui/react-avatar" import * as AvatarPrimitive from '@radix-ui/react-avatar';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
function Avatar({ function Avatar({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Root>) {
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Root>) {
return ( return (
<AvatarPrimitive.Root <AvatarPrimitive.Root
data-slot="avatar" data-slot="avatar"
className={cn( className={cn('relative flex size-8 shrink-0 overflow-hidden rounded-full', className)}
"relative flex size-8 shrink-0 overflow-hidden rounded-full",
className
)}
{...props} {...props}
/> />
) );
} }
function AvatarImage({ function AvatarImage({ className, ...props }: React.ComponentProps<typeof AvatarPrimitive.Image>) {
className,
...props
}: React.ComponentProps<typeof AvatarPrimitive.Image>) {
return ( return (
<AvatarPrimitive.Image <AvatarPrimitive.Image
data-slot="avatar-image" data-slot="avatar-image"
className={cn("aspect-square size-full", className)} className={cn('aspect-square size-full', className)}
{...props} {...props}
/> />
) );
} }
function AvatarFallback({ function AvatarFallback({
@@ -41,13 +32,10 @@ function AvatarFallback({
return ( return (
<AvatarPrimitive.Fallback <AvatarPrimitive.Fallback
data-slot="avatar-fallback" data-slot="avatar-fallback"
className={cn( className={cn('bg-muted flex size-full items-center justify-center rounded-full', className)}
"bg-muted flex size-full items-center justify-center rounded-full",
className
)}
{...props} {...props}
/> />
) );
} }
export { Avatar, AvatarImage, AvatarFallback } export { Avatar, AvatarImage, AvatarFallback };

View File

@@ -1,39 +1,37 @@
import * as React from "react" import * as React from 'react';
import { cva, type VariantProps } from "class-variance-authority" import { cva, type VariantProps } from 'class-variance-authority';
import { Slot } from "radix-ui" import { Slot } from 'radix-ui';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
const badgeVariants = cva( 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: { variants: {
variant: { variant: {
default: "bg-primary text-primary-foreground [a&]:hover:bg-primary/90", default: 'bg-primary text-primary-foreground [a&]:hover:bg-primary/90',
secondary: secondary: 'bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90',
"bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
destructive: 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: outline:
"border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground", 'border-border text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground',
ghost: "[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", link: 'text-primary underline-offset-4 [a&]:hover:underline',
}, },
}, },
defaultVariants: { defaultVariants: {
variant: "default", variant: 'default',
}, },
} },
) );
function Badge({ function Badge({
className, className,
variant = "default", variant = 'default',
asChild = false, asChild = false,
...props ...props
}: React.ComponentProps<"span"> & }: React.ComponentProps<'span'> & VariantProps<typeof badgeVariants> & { asChild?: boolean }) {
VariantProps<typeof badgeVariants> & { asChild?: boolean }) { const Comp = asChild ? Slot.Root : 'span';
const Comp = asChild ? Slot.Root : "span"
return ( return (
<Comp <Comp
@@ -42,7 +40,7 @@ function Badge({
className={cn(badgeVariants({ variant }), className)} className={cn(badgeVariants({ variant }), className)}
{...props} {...props}
/> />
) );
} }
export { Badge, badgeVariants } export { Badge, badgeVariants };

View File

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

View File

@@ -1,40 +1,38 @@
import * as React from "react" import * as React from 'react';
import { Slot } from "@radix-ui/react-slot" import { Slot } from '@radix-ui/react-slot';
import { cva, type VariantProps } from "class-variance-authority" import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
const buttonVariants = cva( 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", "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: { variants: {
variant: { variant: {
default: "bg-primary text-primary-foreground hover:bg-primary/90", default: 'bg-primary text-primary-foreground hover:bg-primary/90',
destructive: 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: 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", '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: secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',
"bg-secondary text-secondary-foreground hover:bg-secondary/80", ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',
ghost: link: 'text-primary underline-offset-4 hover:underline',
"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",
link: "text-primary underline-offset-4 hover:underline",
}, },
size: { size: {
default: "h-9 px-4 py-2 has-[>svg]:px-3", 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", 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", lg: 'h-10 rounded-md px-6 has-[>svg]:px-4',
icon: "size-9", icon: 'size-9',
"icon-sm": "size-8", 'icon-sm': 'size-8',
"icon-lg": "size-10", 'icon-lg': 'size-10',
}, },
}, },
defaultVariants: { defaultVariants: {
variant: "default", variant: 'default',
size: "default", size: 'default',
}, },
} },
) );
function Button({ function Button({
className, className,
@@ -42,11 +40,11 @@ function Button({
size, size,
asChild = false, asChild = false,
...props ...props
}: React.ComponentProps<"button"> & }: React.ComponentProps<'button'> &
VariantProps<typeof buttonVariants> & { VariantProps<typeof buttonVariants> & {
asChild?: boolean asChild?: boolean;
}) { }) {
const Comp = asChild ? Slot : "button" const Comp = asChild ? Slot : 'button';
return ( return (
<Comp <Comp
@@ -54,7 +52,7 @@ function Button({
className={cn(buttonVariants({ variant, size, className }))} className={cn(buttonVariants({ variant, size, className }))}
{...props} {...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 ( return (
<div <div
data-slot="card" data-slot="card"
className={cn( className={cn(
"flex flex-col gap-6 rounded-xl border bg-card backdrop-blur-xl py-6 text-card-foreground", 'flex flex-col gap-6 rounded-xl border bg-card backdrop-blur-xl py-6 text-card-foreground',
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function CardHeader({ className, ...props }: React.ComponentProps<"div">) { function CardHeader({ className, ...props }: React.ComponentProps<'div'>) {
return ( return (
<div <div
data-slot="card-header" data-slot="card-header"
className={cn( 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", '@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 className,
)} )}
{...props} {...props}
/> />
) );
} }
function CardTitle({ className, ...props }: React.ComponentProps<"div">) { function CardTitle({ className, ...props }: React.ComponentProps<'div'>) {
return ( return (
<div <div
data-slot="card-title" data-slot="card-title"
className={cn("leading-none font-semibold", className)} className={cn('leading-none font-semibold', className)}
{...props} {...props}
/> />
) );
} }
function CardDescription({ className, ...props }: React.ComponentProps<"div">) { function CardDescription({ className, ...props }: React.ComponentProps<'div'>) {
return ( return (
<div <div
data-slot="card-description" data-slot="card-description"
className={cn("text-sm text-muted-foreground", className)} className={cn('text-sm text-muted-foreground', className)}
{...props} {...props}
/> />
) );
} }
function CardAction({ className, ...props }: React.ComponentProps<"div">) { function CardAction({ className, ...props }: React.ComponentProps<'div'>) {
return ( return (
<div <div
data-slot="card-action" data-slot="card-action"
className={cn( className={cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', className)}
"col-start-2 row-span-2 row-start-1 self-start justify-self-end",
className
)}
{...props} {...props}
/> />
) );
} }
function CardContent({ className, ...props }: React.ComponentProps<"div">) { function CardContent({ className, ...props }: React.ComponentProps<'div'>) {
return ( return <div data-slot="card-content" className={cn('px-6', className)} {...props} />;
<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 ( return (
<div <div
data-slot="card-footer" 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} {...props}
/> />
) );
} }
export { export { Card, CardHeader, CardFooter, CardTitle, CardAction, CardDescription, CardContent };
Card,
CardHeader,
CardFooter,
CardTitle,
CardAction,
CardDescription,
CardContent,
}

View File

@@ -1,37 +1,37 @@
'use client' 'use client';
import * as React from 'react' import * as React from 'react';
import * as RechartsPrimitive from 'recharts' import * as RechartsPrimitive from 'recharts';
import { cn } from '@/lib/utils' import { cn } from '@/lib/utils';
// Format: { THEME_NAME: CSS_SELECTOR } // Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = { light: '', dark: '.dark' } as const const THEMES = { light: '', dark: '.dark' } as const;
export type ChartConfig = { export type ChartConfig = {
[k in string]: { [k in string]: {
label?: React.ReactNode label?: React.ReactNode;
icon?: React.ComponentType icon?: React.ComponentType;
} & ( } & (
| { color?: string; theme?: never } | { color?: string; theme?: never }
| { color?: never; theme: Record<keyof typeof THEMES, string> } | { color?: never; theme: Record<keyof typeof THEMES, string> }
) );
} };
type ChartContextProps = { type ChartContextProps = {
config: ChartConfig config: ChartConfig;
} };
const ChartContext = React.createContext<ChartContextProps | null>(null) const ChartContext = React.createContext<ChartContextProps | null>(null);
function useChart() { function useChart() {
const context = React.useContext(ChartContext) const context = React.useContext(ChartContext);
if (!context) { 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({ function ChartContainer({
@@ -41,13 +41,11 @@ function ChartContainer({
config, config,
...props ...props
}: React.ComponentProps<'div'> & { }: React.ComponentProps<'div'> & {
config: ChartConfig config: ChartConfig;
children: React.ComponentProps< children: React.ComponentProps<typeof RechartsPrimitive.ResponsiveContainer>['children'];
typeof RechartsPrimitive.ResponsiveContainer
>['children']
}) { }) {
const uniqueId = React.useId() const uniqueId = React.useId();
const chartId = `chart-${id || uniqueId.replace(/:/g, '')}` const chartId = `chart-${id || uniqueId.replace(/:/g, '')}`;
return ( return (
<ChartContext.Provider value={{ config }}> <ChartContext.Provider value={{ config }}>
@@ -61,21 +59,17 @@ function ChartContainer({
{...props} {...props}
> >
<ChartStyle id={chartId} config={config} /> <ChartStyle id={chartId} config={config} />
<RechartsPrimitive.ResponsiveContainer> <RechartsPrimitive.ResponsiveContainer>{children}</RechartsPrimitive.ResponsiveContainer>
{children}
</RechartsPrimitive.ResponsiveContainer>
</div> </div>
</ChartContext.Provider> </ChartContext.Provider>
) );
} }
const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => { const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
const colorConfig = Object.entries(config).filter( const colorConfig = Object.entries(config).filter(([, config]) => config.theme || config.color);
([, config]) => config.theme || config.color,
)
if (!colorConfig.length) { if (!colorConfig.length) {
return null return null;
} }
return ( return (
@@ -87,10 +81,8 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {
${prefix} [data-chart=${id}] { ${prefix} [data-chart=${id}] {
${colorConfig ${colorConfig
.map(([key, itemConfig]) => { .map(([key, itemConfig]) => {
const color = const color = itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || itemConfig.color;
itemConfig.theme?.[theme as keyof typeof itemConfig.theme] || return color ? ` --color-${key}: ${color};` : null;
itemConfig.color
return color ? ` --color-${key}: ${color};` : null
}) })
.join('\n')} .join('\n')}
} }
@@ -99,10 +91,10 @@ ${colorConfig
.join('\n'), .join('\n'),
}} }}
/> />
) );
} };
const ChartTooltip = RechartsPrimitive.Tooltip const ChartTooltip = RechartsPrimitive.Tooltip;
function ChartTooltipContent({ function ChartTooltipContent({
active, active,
@@ -120,55 +112,45 @@ function ChartTooltipContent({
labelKey, labelKey,
}: React.ComponentProps<typeof RechartsPrimitive.Tooltip> & }: React.ComponentProps<typeof RechartsPrimitive.Tooltip> &
React.ComponentProps<'div'> & { React.ComponentProps<'div'> & {
hideLabel?: boolean hideLabel?: boolean;
hideIndicator?: boolean hideIndicator?: boolean;
indicator?: 'line' | 'dot' | 'dashed' indicator?: 'line' | 'dot' | 'dashed';
nameKey?: string nameKey?: string;
labelKey?: string labelKey?: string;
}) { }) {
const { config } = useChart() const { config } = useChart();
const tooltipLabel = React.useMemo(() => { const tooltipLabel = React.useMemo(() => {
if (hideLabel || !payload?.length) { if (hideLabel || !payload?.length) {
return null return null;
} }
const [item] = payload const [item] = payload;
const key = `${labelKey || item?.dataKey || item?.name || 'value'}` const key = `${labelKey || item?.dataKey || item?.name || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key) const itemConfig = getPayloadConfigFromPayload(config, item, key);
const value = const value =
!labelKey && typeof label === 'string' !labelKey && typeof label === 'string'
? config[label as keyof typeof config]?.label || label ? config[label as keyof typeof config]?.label || label
: itemConfig?.label : itemConfig?.label;
if (labelFormatter) { if (labelFormatter) {
return ( return (
<div className={cn('font-medium', labelClassName)}> <div className={cn('font-medium', labelClassName)}>{labelFormatter(value, payload)}</div>
{labelFormatter(value, payload)} );
</div>
)
} }
if (!value) { if (!value) {
return null return null;
} }
return <div className={cn('font-medium', labelClassName)}>{value}</div> return <div className={cn('font-medium', labelClassName)}>{value}</div>;
}, [ }, [label, labelFormatter, payload, hideLabel, labelClassName, config, labelKey]);
label,
labelFormatter,
payload,
hideLabel,
labelClassName,
config,
labelKey,
])
if (!active || !payload?.length) { if (!active || !payload?.length) {
return null return null;
} }
const nestLabel = payload.length === 1 && indicator !== 'dot' const nestLabel = payload.length === 1 && indicator !== 'dot';
return ( return (
<div <div
@@ -180,9 +162,9 @@ function ChartTooltipContent({
{!nestLabel ? tooltipLabel : null} {!nestLabel ? tooltipLabel : null}
<div className="grid gap-1.5"> <div className="grid gap-1.5">
{payload.map((item, index) => { {payload.map((item, index) => {
const key = `${nameKey || item.name || item.dataKey || 'value'}` const key = `${nameKey || item.name || item.dataKey || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key) const itemConfig = getPayloadConfigFromPayload(config, item, key);
const indicatorColor = color || item.payload.fill || item.color const indicatorColor = color || item.payload.fill || item.color;
return ( return (
<div <div
@@ -241,14 +223,14 @@ function ChartTooltipContent({
</> </>
)} )}
</div> </div>
) );
})} })}
</div> </div>
</div> </div>
) );
} }
const ChartLegend = RechartsPrimitive.Legend const ChartLegend = RechartsPrimitive.Legend;
function ChartLegendContent({ function ChartLegendContent({
className, className,
@@ -258,13 +240,13 @@ function ChartLegendContent({
nameKey, nameKey,
}: React.ComponentProps<'div'> & }: React.ComponentProps<'div'> &
Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & { Pick<RechartsPrimitive.LegendProps, 'payload' | 'verticalAlign'> & {
hideIcon?: boolean hideIcon?: boolean;
nameKey?: string nameKey?: string;
}) { }) {
const { config } = useChart() const { config } = useChart();
if (!payload?.length) { if (!payload?.length) {
return null return null;
} }
return ( return (
@@ -276,8 +258,8 @@ function ChartLegendContent({
)} )}
> >
{payload.map((item) => { {payload.map((item) => {
const key = `${nameKey || item.dataKey || 'value'}` const key = `${nameKey || item.dataKey || 'value'}`;
const itemConfig = getPayloadConfigFromPayload(config, item, key) const itemConfig = getPayloadConfigFromPayload(config, item, key);
return ( return (
<div <div
@@ -298,49 +280,36 @@ function ChartLegendContent({
)} )}
{itemConfig?.label} {itemConfig?.label}
</div> </div>
) );
})} })}
</div> </div>
) );
} }
// Helper to extract item config from a payload. // Helper to extract item config from a payload.
function getPayloadConfigFromPayload( function getPayloadConfigFromPayload(config: ChartConfig, payload: unknown, key: string) {
config: ChartConfig,
payload: unknown,
key: string,
) {
if (typeof payload !== 'object' || payload === null) { if (typeof payload !== 'object' || payload === null) {
return undefined return undefined;
} }
const payloadPayload = const payloadPayload =
'payload' in payload && 'payload' in payload && typeof payload.payload === 'object' && payload.payload !== null
typeof payload.payload === 'object' &&
payload.payload !== null
? payload.payload ? payload.payload
: undefined : undefined;
let configLabelKey: string = key let configLabelKey: string = key;
if ( if (key in payload && typeof payload[key as keyof typeof payload] === 'string') {
key in payload && configLabelKey = payload[key as keyof typeof payload] as string;
typeof payload[key as keyof typeof payload] === 'string'
) {
configLabelKey = payload[key as keyof typeof payload] as string
} else if ( } else if (
payloadPayload && payloadPayload &&
key in payloadPayload && key in payloadPayload &&
typeof payloadPayload[key as keyof typeof payloadPayload] === 'string' typeof payloadPayload[key as keyof typeof payloadPayload] === 'string'
) { ) {
configLabelKey = payloadPayload[ configLabelKey = payloadPayload[key as keyof typeof payloadPayload] as string;
key as keyof typeof payloadPayload
] as string
} }
return configLabelKey in config return configLabelKey in config ? config[configLabelKey] : config[key as keyof typeof config];
? config[configLabelKey]
: config[key as keyof typeof config]
} }
export { export {
@@ -350,4 +319,4 @@ export {
ChartLegend, ChartLegend,
ChartLegendContent, ChartLegendContent,
ChartStyle, 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({ function Collapsible({ ...props }: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
...props return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />;
}: React.ComponentProps<typeof CollapsiblePrimitive.Root>) {
return <CollapsiblePrimitive.Root data-slot="collapsible" {...props} />
} }
function CollapsibleTrigger({ function CollapsibleTrigger({
...props ...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) { }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleTrigger>) {
return ( return <CollapsiblePrimitive.CollapsibleTrigger data-slot="collapsible-trigger" {...props} />;
<CollapsiblePrimitive.CollapsibleTrigger
data-slot="collapsible-trigger"
{...props}
/>
)
} }
function CollapsibleContent({ function CollapsibleContent({
...props ...props
}: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) { }: React.ComponentProps<typeof CollapsiblePrimitive.CollapsibleContent>) {
return ( return <CollapsiblePrimitive.CollapsibleContent data-slot="collapsible-content" {...props} />;
<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 * as React from 'react';
import { XIcon } from "lucide-react" import { XIcon } from 'lucide-react';
import { Dialog as DialogPrimitive } from "radix-ui" import { Dialog as DialogPrimitive } from 'radix-ui';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
import { Button } from "@/components/ui/button" import { Button } from '@/components/ui/button';
function Dialog({ function Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {
...props return <DialogPrimitive.Root data-slot="dialog" {...props} />;
}: React.ComponentProps<typeof DialogPrimitive.Root>) {
return <DialogPrimitive.Root data-slot="dialog" {...props} />
} }
function DialogTrigger({ function DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
...props return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />;
}: React.ComponentProps<typeof DialogPrimitive.Trigger>) {
return <DialogPrimitive.Trigger data-slot="dialog-trigger" {...props} />
} }
function DialogPortal({ function DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {
...props return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />;
}: React.ComponentProps<typeof DialogPrimitive.Portal>) {
return <DialogPrimitive.Portal data-slot="dialog-portal" {...props} />
} }
function DialogClose({ function DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {
...props return <DialogPrimitive.Close data-slot="dialog-close" {...props} />;
}: React.ComponentProps<typeof DialogPrimitive.Close>) {
return <DialogPrimitive.Close data-slot="dialog-close" {...props} />
} }
function DialogOverlay({ function DialogOverlay({
@@ -39,12 +31,12 @@ function DialogOverlay({
<DialogPrimitive.Overlay <DialogPrimitive.Overlay
data-slot="dialog-overlay" data-slot="dialog-overlay"
className={cn( 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", '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 className,
)} )}
{...props} {...props}
/> />
) );
} }
function DialogContent({ function DialogContent({
@@ -53,7 +45,7 @@ function DialogContent({
showCloseButton = true, showCloseButton = true,
...props ...props
}: React.ComponentProps<typeof DialogPrimitive.Content> & { }: React.ComponentProps<typeof DialogPrimitive.Content> & {
showCloseButton?: boolean showCloseButton?: boolean;
}) { }) {
return ( return (
<DialogPortal data-slot="dialog-portal"> <DialogPortal data-slot="dialog-portal">
@@ -61,8 +53,8 @@ function DialogContent({
<DialogPrimitive.Content <DialogPrimitive.Content
data-slot="dialog-content" data-slot="dialog-content"
className={cn( 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", '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 className,
)} )}
{...props} {...props}
> >
@@ -78,17 +70,17 @@ function DialogContent({
)} )}
</DialogPrimitive.Content> </DialogPrimitive.Content>
</DialogPortal> </DialogPortal>
) );
} }
function DialogHeader({ className, ...props }: React.ComponentProps<"div">) { function DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {
return ( return (
<div <div
data-slot="dialog-header" 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} {...props}
/> />
) );
} }
function DialogFooter({ function DialogFooter({
@@ -96,16 +88,13 @@ function DialogFooter({
showCloseButton = false, showCloseButton = false,
children, children,
...props ...props
}: React.ComponentProps<"div"> & { }: React.ComponentProps<'div'> & {
showCloseButton?: boolean showCloseButton?: boolean;
}) { }) {
return ( return (
<div <div
data-slot="dialog-footer" data-slot="dialog-footer"
className={cn( className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}
"flex flex-col-reverse gap-2 sm:flex-row sm:justify-end",
className
)}
{...props} {...props}
> >
{children} {children}
@@ -115,20 +104,17 @@ function DialogFooter({
</DialogPrimitive.Close> </DialogPrimitive.Close>
)} )}
</div> </div>
) );
} }
function DialogTitle({ function DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {
className,
...props
}: React.ComponentProps<typeof DialogPrimitive.Title>) {
return ( return (
<DialogPrimitive.Title <DialogPrimitive.Title
data-slot="dialog-title" data-slot="dialog-title"
className={cn("text-lg leading-none font-semibold", className)} className={cn('text-lg leading-none font-semibold', className)}
{...props} {...props}
/> />
) );
} }
function DialogDescription({ function DialogDescription({
@@ -138,10 +124,10 @@ function DialogDescription({
return ( return (
<DialogPrimitive.Description <DialogPrimitive.Description
data-slot="dialog-description" data-slot="dialog-description"
className={cn("text-sm text-muted-foreground", className)} className={cn('text-sm text-muted-foreground', className)}
{...props} {...props}
/> />
) );
} }
export { export {
@@ -155,4 +141,4 @@ export {
DialogPortal, DialogPortal,
DialogTitle, DialogTitle,
DialogTrigger, DialogTrigger,
} };

View File

@@ -1,34 +1,25 @@
"use client"; 'use client';
import * as React from "react"; import * as React from 'react';
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"; import * as DropdownMenuPrimitive from '@radix-ui/react-dropdown-menu';
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"; import { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';
import { cn } from "@/lib/utils"; import { cn } from '@/lib/utils';
function DropdownMenu({ function DropdownMenu({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Root>) {
return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />; return <DropdownMenuPrimitive.Root data-slot="dropdown-menu" {...props} />;
} }
function DropdownMenuPortal({ function DropdownMenuPortal({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Portal>) {
return ( return <DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />;
<DropdownMenuPrimitive.Portal data-slot="dropdown-menu-portal" {...props} />
);
} }
function DropdownMenuTrigger({ function DropdownMenuTrigger({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.Trigger>) {
return ( return <DropdownMenuPrimitive.Trigger data-slot="dropdown-menu-trigger" {...props} />;
<DropdownMenuPrimitive.Trigger
data-slot="dropdown-menu-trigger"
{...props}
/>
);
} }
function DropdownMenuContent({ function DropdownMenuContent({
@@ -42,8 +33,8 @@ function DropdownMenuContent({
data-slot="dropdown-menu-content" data-slot="dropdown-menu-content"
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( 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", '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 className,
)} )}
{...props} {...props}
/> />
@@ -51,22 +42,18 @@ function DropdownMenuContent({
); );
} }
function DropdownMenuGroup({ function DropdownMenuGroup({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
...props return <DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />;
}: React.ComponentProps<typeof DropdownMenuPrimitive.Group>) {
return (
<DropdownMenuPrimitive.Group data-slot="dropdown-menu-group" {...props} />
);
} }
function DropdownMenuItem({ function DropdownMenuItem({
className, className,
inset, inset,
variant = "default", variant = 'default',
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & { }: React.ComponentProps<typeof DropdownMenuPrimitive.Item> & {
inset?: boolean; inset?: boolean;
variant?: "default" | "destructive"; variant?: 'default' | 'destructive';
}) { }) {
return ( return (
<DropdownMenuPrimitive.Item <DropdownMenuPrimitive.Item
@@ -75,7 +62,7 @@ function DropdownMenuItem({
data-variant={variant} data-variant={variant}
className={cn( 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", "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} {...props}
/> />
@@ -93,7 +80,7 @@ function DropdownMenuCheckboxItem({
data-slot="dropdown-menu-checkbox-item" data-slot="dropdown-menu-checkbox-item"
className={cn( 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", "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} checked={checked}
{...props} {...props}
@@ -111,12 +98,7 @@ function DropdownMenuCheckboxItem({
function DropdownMenuRadioGroup({ function DropdownMenuRadioGroup({
...props ...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) { }: React.ComponentProps<typeof DropdownMenuPrimitive.RadioGroup>) {
return ( return <DropdownMenuPrimitive.RadioGroup data-slot="dropdown-menu-radio-group" {...props} />;
<DropdownMenuPrimitive.RadioGroup
data-slot="dropdown-menu-radio-group"
{...props}
/>
);
} }
function DropdownMenuRadioItem({ function DropdownMenuRadioItem({
@@ -129,7 +111,7 @@ function DropdownMenuRadioItem({
data-slot="dropdown-menu-radio-item" data-slot="dropdown-menu-radio-item"
className={cn( 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", "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} {...props}
> >
@@ -154,10 +136,7 @@ function DropdownMenuLabel({
<DropdownMenuPrimitive.Label <DropdownMenuPrimitive.Label
data-slot="dropdown-menu-label" data-slot="dropdown-menu-label"
data-inset={inset} data-inset={inset}
className={cn( className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}
"px-2 py-1.5 text-sm font-medium data-[inset]:pl-8",
className
)}
{...props} {...props}
/> />
); );
@@ -170,31 +149,23 @@ function DropdownMenuSeparator({
return ( return (
<DropdownMenuPrimitive.Separator <DropdownMenuPrimitive.Separator
data-slot="dropdown-menu-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} {...props}
/> />
); );
} }
function DropdownMenuShortcut({ function DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {
className,
...props
}: React.ComponentProps<"span">) {
return ( return (
<span <span
data-slot="dropdown-menu-shortcut" data-slot="dropdown-menu-shortcut"
className={cn( className={cn('text-muted-foreground ml-auto text-xs tracking-widest', className)}
"text-muted-foreground ml-auto text-xs tracking-widest",
className
)}
{...props} {...props}
/> />
); );
} }
function DropdownMenuSub({ function DropdownMenuSub({ ...props }: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
...props
}: React.ComponentProps<typeof DropdownMenuPrimitive.Sub>) {
return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />; return <DropdownMenuPrimitive.Sub data-slot="dropdown-menu-sub" {...props} />;
} }
@@ -212,7 +183,7 @@ function DropdownMenuSubTrigger({
data-inset={inset} data-inset={inset}
className={cn( 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", "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} {...props}
> >
@@ -230,8 +201,8 @@ function DropdownMenuSubContent({
<DropdownMenuPrimitive.SubContent <DropdownMenuPrimitive.SubContent
data-slot="dropdown-menu-sub-content" data-slot="dropdown-menu-sub-content"
className={cn( 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", '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 className,
)} )}
{...props} {...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 ( return (
<input <input
type={type} type={type}
data-slot="input" data-slot="input"
className={cn( 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", '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]", '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", 'aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive',
className className,
)} )}
{...props} {...props}
/> />
) );
} }
export { Input } export { Input };

View File

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

View File

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

View File

@@ -1,25 +1,21 @@
"use client" 'use client';
import * as React from "react" import * as React from 'react';
import { Popover as PopoverPrimitive } from "radix-ui" import { Popover as PopoverPrimitive } from 'radix-ui';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
function Popover({ function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {
...props return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
return <PopoverPrimitive.Root data-slot="popover" {...props} />
} }
function PopoverTrigger({ function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
...props return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
} }
function PopoverContent({ function PopoverContent({
className, className,
align = "center", align = 'center',
sideOffset = 4, sideOffset = 4,
...props ...props
}: React.ComponentProps<typeof PopoverPrimitive.Content>) { }: React.ComponentProps<typeof PopoverPrimitive.Content>) {
@@ -30,52 +26,41 @@ function PopoverContent({
align={align} align={align}
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( 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", '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 className,
)} )}
{...props} {...props}
/> />
</PopoverPrimitive.Portal> </PopoverPrimitive.Portal>
) );
} }
function PopoverAnchor({ function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
...props return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...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 ( return (
<div <div
data-slot="popover-header" 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} {...props}
/> />
) );
} }
function PopoverTitle({ className, ...props }: React.ComponentProps<"h2">) { function PopoverTitle({ className, ...props }: React.ComponentProps<'h2'>) {
return ( return <div data-slot="popover-title" className={cn('font-medium', className)} {...props} />;
<div
data-slot="popover-title"
className={cn("font-medium", className)}
{...props}
/>
)
} }
function PopoverDescription({ function PopoverDescription({ className, ...props }: React.ComponentProps<'p'>) {
className,
...props
}: React.ComponentProps<"p">) {
return ( return (
<p <p
data-slot="popover-description" data-slot="popover-description"
className={cn("text-muted-foreground", className)} className={cn('text-muted-foreground', className)}
{...props} {...props}
/> />
) );
} }
export { export {
@@ -86,4 +71,4 @@ export {
PopoverHeader, PopoverHeader,
PopoverTitle, PopoverTitle,
PopoverDescription, PopoverDescription,
} };

View File

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

View File

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

View File

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

View File

@@ -1,36 +1,30 @@
"use client" 'use client';
import * as React from "react" import * as React from 'react';
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react" import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
import { Select as SelectPrimitive } from "radix-ui" import { Select as SelectPrimitive } from 'radix-ui';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
function Select({ function Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {
...props return <SelectPrimitive.Root data-slot="select" {...props} />;
}: React.ComponentProps<typeof SelectPrimitive.Root>) {
return <SelectPrimitive.Root data-slot="select" {...props} />
} }
function SelectGroup({ function SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {
...props return <SelectPrimitive.Group data-slot="select-group" {...props} />;
}: React.ComponentProps<typeof SelectPrimitive.Group>) {
return <SelectPrimitive.Group data-slot="select-group" {...props} />
} }
function SelectValue({ function SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {
...props return <SelectPrimitive.Value data-slot="select-value" {...props} />;
}: React.ComponentProps<typeof SelectPrimitive.Value>) {
return <SelectPrimitive.Value data-slot="select-value" {...props} />
} }
function SelectTrigger({ function SelectTrigger({
className, className,
size = "default", size = 'default',
children, children,
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Trigger> & { }: React.ComponentProps<typeof SelectPrimitive.Trigger> & {
size?: "sm" | "default" size?: 'sm' | 'default';
}) { }) {
return ( return (
<SelectPrimitive.Trigger <SelectPrimitive.Trigger
@@ -38,7 +32,7 @@ function SelectTrigger({
data-size={size} data-size={size}
className={cn( 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", "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} {...props}
> >
@@ -47,14 +41,14 @@ function SelectTrigger({
<ChevronDownIcon className="size-4 opacity-50" /> <ChevronDownIcon className="size-4 opacity-50" />
</SelectPrimitive.Icon> </SelectPrimitive.Icon>
</SelectPrimitive.Trigger> </SelectPrimitive.Trigger>
) );
} }
function SelectContent({ function SelectContent({
className, className,
children, children,
position = "item-aligned", position = 'item-aligned',
align = "center", align = 'center',
...props ...props
}: React.ComponentProps<typeof SelectPrimitive.Content>) { }: React.ComponentProps<typeof SelectPrimitive.Content>) {
return ( return (
@@ -62,10 +56,10 @@ function SelectContent({
<SelectPrimitive.Content <SelectPrimitive.Content
data-slot="select-content" data-slot="select-content"
className={cn( 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", '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" && 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", '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 className,
)} )}
position={position} position={position}
align={align} align={align}
@@ -74,9 +68,9 @@ function SelectContent({
<SelectScrollUpButton /> <SelectScrollUpButton />
<SelectPrimitive.Viewport <SelectPrimitive.Viewport
className={cn( className={cn(
"p-1", 'p-1',
position === "popper" && position === 'popper' &&
"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1" 'h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)] scroll-my-1',
)} )}
> >
{children} {children}
@@ -84,20 +78,17 @@ function SelectContent({
<SelectScrollDownButton /> <SelectScrollDownButton />
</SelectPrimitive.Content> </SelectPrimitive.Content>
</SelectPrimitive.Portal> </SelectPrimitive.Portal>
) );
} }
function SelectLabel({ function SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Label>) {
className,
...props
}: React.ComponentProps<typeof SelectPrimitive.Label>) {
return ( return (
<SelectPrimitive.Label <SelectPrimitive.Label
data-slot="select-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} {...props}
/> />
) );
} }
function SelectItem({ function SelectItem({
@@ -110,7 +101,7 @@ function SelectItem({
data-slot="select-item" data-slot="select-item"
className={cn( 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", "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} {...props}
> >
@@ -124,7 +115,7 @@ function SelectItem({
</span> </span>
<SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText> <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
</SelectPrimitive.Item> </SelectPrimitive.Item>
) );
} }
function SelectSeparator({ function SelectSeparator({
@@ -134,10 +125,10 @@ function SelectSeparator({
return ( return (
<SelectPrimitive.Separator <SelectPrimitive.Separator
data-slot="select-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} {...props}
/> />
) );
} }
function SelectScrollUpButton({ function SelectScrollUpButton({
@@ -147,15 +138,12 @@ function SelectScrollUpButton({
return ( return (
<SelectPrimitive.ScrollUpButton <SelectPrimitive.ScrollUpButton
data-slot="select-scroll-up-button" data-slot="select-scroll-up-button"
className={cn( className={cn('flex cursor-default items-center justify-center py-1', className)}
"flex cursor-default items-center justify-center py-1",
className
)}
{...props} {...props}
> >
<ChevronUpIcon className="size-4" /> <ChevronUpIcon className="size-4" />
</SelectPrimitive.ScrollUpButton> </SelectPrimitive.ScrollUpButton>
) );
} }
function SelectScrollDownButton({ function SelectScrollDownButton({
@@ -165,15 +153,12 @@ function SelectScrollDownButton({
return ( return (
<SelectPrimitive.ScrollDownButton <SelectPrimitive.ScrollDownButton
data-slot="select-scroll-down-button" data-slot="select-scroll-down-button"
className={cn( className={cn('flex cursor-default items-center justify-center py-1', className)}
"flex cursor-default items-center justify-center py-1",
className
)}
{...props} {...props}
> >
<ChevronDownIcon className="size-4" /> <ChevronDownIcon className="size-4" />
</SelectPrimitive.ScrollDownButton> </SelectPrimitive.ScrollDownButton>
) );
} }
export { export {
@@ -187,4 +172,4 @@ export {
SelectSeparator, SelectSeparator,
SelectTrigger, SelectTrigger,
SelectValue, SelectValue,
} };

View File

@@ -1,13 +1,13 @@
"use client" 'use client';
import * as React from "react" import * as React from 'react';
import * as SeparatorPrimitive from "@radix-ui/react-separator" import * as SeparatorPrimitive from '@radix-ui/react-separator';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
function Separator({ function Separator({
className, className,
orientation = "horizontal", orientation = 'horizontal',
decorative = true, decorative = true,
...props ...props
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) { }: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
@@ -17,12 +17,12 @@ function Separator({
decorative={decorative} decorative={decorative}
orientation={orientation} orientation={orientation}
className={cn( 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", '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 className,
)} )}
{...props} {...props}
/> />
) );
} }
export { Separator } export { Separator };

View File

@@ -1,31 +1,25 @@
"use client" 'use client';
import * as React from "react" import * as React from 'react';
import * as SheetPrimitive from "@radix-ui/react-dialog" import * as SheetPrimitive from '@radix-ui/react-dialog';
import { XIcon } from "lucide-react" import { XIcon } from 'lucide-react';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) { function Sheet({ ...props }: React.ComponentProps<typeof SheetPrimitive.Root>) {
return <SheetPrimitive.Root data-slot="sheet" {...props} /> return <SheetPrimitive.Root data-slot="sheet" {...props} />;
} }
function SheetTrigger({ function SheetTrigger({ ...props }: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
...props return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />;
}: React.ComponentProps<typeof SheetPrimitive.Trigger>) {
return <SheetPrimitive.Trigger data-slot="sheet-trigger" {...props} />
} }
function SheetClose({ function SheetClose({ ...props }: React.ComponentProps<typeof SheetPrimitive.Close>) {
...props return <SheetPrimitive.Close data-slot="sheet-close" {...props} />;
}: React.ComponentProps<typeof SheetPrimitive.Close>) {
return <SheetPrimitive.Close data-slot="sheet-close" {...props} />
} }
function SheetPortal({ function SheetPortal({ ...props }: React.ComponentProps<typeof SheetPrimitive.Portal>) {
...props return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />;
}: React.ComponentProps<typeof SheetPrimitive.Portal>) {
return <SheetPrimitive.Portal data-slot="sheet-portal" {...props} />
} }
function SheetOverlay({ function SheetOverlay({
@@ -36,21 +30,21 @@ function SheetOverlay({
<SheetPrimitive.Overlay <SheetPrimitive.Overlay
data-slot="sheet-overlay" data-slot="sheet-overlay"
className={cn( 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", '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 className,
)} )}
{...props} {...props}
/> />
) );
} }
function SheetContent({ function SheetContent({
className, className,
children, children,
side = "right", side = 'right',
...props ...props
}: React.ComponentProps<typeof SheetPrimitive.Content> & { }: React.ComponentProps<typeof SheetPrimitive.Content> & {
side?: "top" | "right" | "bottom" | "left" side?: 'top' | 'right' | 'bottom' | 'left';
}) { }) {
return ( return (
<SheetPortal> <SheetPortal>
@@ -58,16 +52,16 @@ function SheetContent({
<SheetPrimitive.Content <SheetPrimitive.Content
data-slot="sheet-content" data-slot="sheet-content"
className={cn( 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", '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" && 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", '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" && 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", '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" && 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", '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" && 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", 'data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom inset-x-0 bottom-0 h-auto border-t',
className className,
)} )}
{...props} {...props}
> >
@@ -78,40 +72,37 @@ function SheetContent({
</SheetPrimitive.Close> </SheetPrimitive.Close>
</SheetPrimitive.Content> </SheetPrimitive.Content>
</SheetPortal> </SheetPortal>
) );
} }
function SheetHeader({ className, ...props }: React.ComponentProps<"div">) { function SheetHeader({ className, ...props }: React.ComponentProps<'div'>) {
return ( return (
<div <div
data-slot="sheet-header" 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} {...props}
/> />
) );
} }
function SheetFooter({ className, ...props }: React.ComponentProps<"div">) { function SheetFooter({ className, ...props }: React.ComponentProps<'div'>) {
return ( return (
<div <div
data-slot="sheet-footer" 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} {...props}
/> />
) );
} }
function SheetTitle({ function SheetTitle({ className, ...props }: React.ComponentProps<typeof SheetPrimitive.Title>) {
className,
...props
}: React.ComponentProps<typeof SheetPrimitive.Title>) {
return ( return (
<SheetPrimitive.Title <SheetPrimitive.Title
data-slot="sheet-title" data-slot="sheet-title"
className={cn("text-foreground font-semibold", className)} className={cn('text-foreground font-semibold', className)}
{...props} {...props}
/> />
) );
} }
function SheetDescription({ function SheetDescription({
@@ -121,10 +112,10 @@ function SheetDescription({
return ( return (
<SheetPrimitive.Description <SheetPrimitive.Description
data-slot="sheet-description" data-slot="sheet-description"
className={cn("text-muted-foreground text-sm", className)} className={cn('text-muted-foreground text-sm', className)}
{...props} {...props}
/> />
) );
} }
export { export {
@@ -136,4 +127,4 @@ export {
SheetFooter, SheetFooter,
SheetTitle, SheetTitle,
SheetDescription, SheetDescription,
} };

View File

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

View File

@@ -1,10 +1,10 @@
'use client' 'use client';
import { useTheme } from 'next-themes' import { useTheme } from 'next-themes';
import { Toaster as Sonner, ToasterProps } from 'sonner' import { Toaster as Sonner, ToasterProps } from 'sonner';
const Toaster = ({ ...props }: ToasterProps) => { const Toaster = ({ ...props }: ToasterProps) => {
const { theme = 'system' } = useTheme() const { theme = 'system' } = useTheme();
return ( return (
<Sonner <Sonner
@@ -19,7 +19,7 @@ const Toaster = ({ ...props }: ToasterProps) => {
} }
{...props} {...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({ function Table({
className, className,
containerClassName, containerClassName,
...props ...props
}: React.ComponentProps<"table"> & { containerClassName?: string }) { }: React.ComponentProps<'table'> & { containerClassName?: string }) {
return ( return (
<div <div
data-slot="table-container" data-slot="table-container"
className={cn("relative w-full overflow-x-auto", containerClassName)} className={cn('relative w-full overflow-x-auto', containerClassName)}
> >
<table <table
data-slot="table" data-slot="table"
className={cn("w-full caption-bottom text-sm", className)} className={cn('w-full caption-bottom text-sm', className)}
{...props} {...props}
/> />
</div> </div>
) );
} }
function TableHeader({ className, ...props }: React.ComponentProps<"thead">) { function TableHeader({ className, ...props }: React.ComponentProps<'thead'>) {
return ( return <thead data-slot="table-header" className={cn('[&_tr]:border-b', className)} {...props} />;
<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 ( return (
<tbody <tbody
data-slot="table-body" data-slot="table-body"
className={cn("[&_tr:last-child]:border-0", className)} className={cn('[&_tr:last-child]:border-0', className)}
{...props} {...props}
/> />
) );
} }
function TableFooter({ className, ...props }: React.ComponentProps<"tfoot">) { function TableFooter({ className, ...props }: React.ComponentProps<'tfoot'>) {
return ( return (
<tfoot <tfoot
data-slot="table-footer" data-slot="table-footer"
className={cn( className={cn('border-t bg-muted/50 font-medium [&>tr]:last:border-b-0', className)}
"border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",
className
)}
{...props} {...props}
/> />
) );
} }
function TableRow({ className, ...props }: React.ComponentProps<"tr">) { function TableRow({ className, ...props }: React.ComponentProps<'tr'>) {
return ( return (
<tr <tr
data-slot="table-row" data-slot="table-row"
className={cn( className={cn(
"border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted", 'border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted',
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function TableHead({ className, ...props }: React.ComponentProps<"th">) { function TableHead({ className, ...props }: React.ComponentProps<'th'>) {
return ( return (
<th <th
data-slot="table-head" data-slot="table-head"
className={cn( 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]", '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 className,
)} )}
{...props} {...props}
/> />
) );
} }
function TableCell({ className, ...props }: React.ComponentProps<"td">) { function TableCell({ className, ...props }: React.ComponentProps<'td'>) {
return ( return (
<td <td
data-slot="table-cell" data-slot="table-cell"
className={cn( className={cn(
"p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]", 'p-2 align-middle whitespace-nowrap [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]',
className className,
)} )}
{...props} {...props}
/> />
) );
} }
function TableCaption({ function TableCaption({ className, ...props }: React.ComponentProps<'caption'>) {
className,
...props
}: React.ComponentProps<"caption">) {
return ( return (
<caption <caption
data-slot="table-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} {...props}
/> />
) );
} }
export { export { Table, TableHeader, TableBody, TableFooter, TableHead, TableRow, TableCell, TableCaption };
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 React from 'react';
import * as TooltipPrimitive from "@radix-ui/react-tooltip" import * as TooltipPrimitive from '@radix-ui/react-tooltip';
import { cn } from "@/lib/utils" import { cn } from '@/lib/utils';
function TooltipProvider({ function TooltipProvider({
delayDuration = 0, delayDuration = 0,
@@ -15,23 +15,19 @@ function TooltipProvider({
delayDuration={delayDuration} delayDuration={delayDuration}
{...props} {...props}
/> />
) );
} }
function Tooltip({ function Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {
...props
}: React.ComponentProps<typeof TooltipPrimitive.Root>) {
return ( return (
<TooltipProvider> <TooltipProvider>
<TooltipPrimitive.Root data-slot="tooltip" {...props} /> <TooltipPrimitive.Root data-slot="tooltip" {...props} />
</TooltipProvider> </TooltipProvider>
) );
} }
function TooltipTrigger({ function TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
...props return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />;
}: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {
return <TooltipPrimitive.Trigger data-slot="tooltip-trigger" {...props} />
} }
function TooltipContent({ function TooltipContent({
@@ -46,8 +42,8 @@ function TooltipContent({
data-slot="tooltip-content" data-slot="tooltip-content"
sideOffset={sideOffset} sideOffset={sideOffset}
className={cn( 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", '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 className,
)} )}
{...props} {...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.Arrow className="bg-foreground fill-foreground z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px]" />
</TooltipPrimitive.Content> </TooltipPrimitive.Content>
</TooltipPrimitive.Portal> </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() { export function useIsMobile() {
const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined) const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined);
React.useEffect(() => { React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`) const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
const onChange = () => { const onChange = () => {
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
} };
mql.addEventListener('change', onChange) mql.addEventListener('change', onChange);
setIsMobile(window.innerWidth < MOBILE_BREAKPOINT) setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
return () => mql.removeEventListener('change', onChange) 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 { clsx, type ClassValue } from 'clsx';
import { twMerge } from 'tailwind-merge' import { twMerge } from 'tailwind-merge';
export function cn(...inputs: ClassValue[]) { 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 * Used to persist video files across page navigations
*/ */
const DB_NAME = 'visionroad_db' const DB_NAME = 'visionroad_db';
const DB_VERSION = 1 const DB_VERSION = 1;
const VIDEO_STORE = 'videos' const VIDEO_STORE = 'videos';
let db: IDBDatabase | null = null let db: IDBDatabase | null = null;
/** /**
* Open the IndexedDB database * Open the IndexedDB database
*/ */
async function openDB(): Promise<IDBDatabase> { async function openDB(): Promise<IDBDatabase> {
if (db) return db if (db) return db;
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION) const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error) request.onerror = () => reject(request.error);
request.onsuccess = () => { request.onsuccess = () => {
db = request.result db = request.result;
resolve(db) resolve(db);
} };
request.onupgradeneeded = (event) => { request.onupgradeneeded = (event) => {
const database = (event.target as IDBOpenDBRequest).result const database = (event.target as IDBOpenDBRequest).result;
if (!database.objectStoreNames.contains(VIDEO_STORE)) { if (!database.objectStoreNames.contains(VIDEO_STORE)) {
database.createObjectStore(VIDEO_STORE, { keyPath: 'id' }) database.createObjectStore(VIDEO_STORE, { keyPath: 'id' });
} }
} };
}) });
} }
/** /**
* Store a video file in IndexedDB * Store a video file in IndexedDB
*/ */
export async function storeVideoFile(videoId: string, file: File): Promise<void> { export async function storeVideoFile(videoId: string, file: File): Promise<void> {
const database = await openDB() const database = await openDB();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite') const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE) const store = transaction.objectStore(VIDEO_STORE);
const request = store.put({ const request = store.put({
id: videoId, id: videoId,
file: file, file: file,
timestamp: Date.now() timestamp: Date.now(),
}) });
request.onerror = () => reject(request.error) request.onerror = () => reject(request.error);
request.onsuccess = () => resolve() request.onsuccess = () => resolve();
}) });
} }
/** /**
* Retrieve a video file from IndexedDB * Retrieve a video file from IndexedDB
*/ */
export async function getVideoFile(videoId: string): Promise<File | null> { export async function getVideoFile(videoId: string): Promise<File | null> {
const database = await openDB() const database = await openDB();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readonly') const transaction = database.transaction([VIDEO_STORE], 'readonly');
const store = transaction.objectStore(VIDEO_STORE) const store = transaction.objectStore(VIDEO_STORE);
const request = store.get(videoId) const request = store.get(videoId);
request.onerror = () => reject(request.error) request.onerror = () => reject(request.error);
request.onsuccess = () => { request.onsuccess = () => {
const result = request.result const result = request.result;
resolve(result ? result.file : null) resolve(result ? result.file : null);
} };
}) });
} }
/** /**
* Clear a video file from IndexedDB * Clear a video file from IndexedDB
*/ */
export async function clearVideoFile(videoId: string): Promise<void> { export async function clearVideoFile(videoId: string): Promise<void> {
const database = await openDB() const database = await openDB();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite') const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE) const store = transaction.objectStore(VIDEO_STORE);
const request = store.delete(videoId) const request = store.delete(videoId);
request.onerror = () => reject(request.error) request.onerror = () => reject(request.error);
request.onsuccess = () => resolve() request.onsuccess = () => resolve();
}) });
} }
/** /**
* Clear all video files from IndexedDB * Clear all video files from IndexedDB
*/ */
export async function clearAllVideos(): Promise<void> { export async function clearAllVideos(): Promise<void> {
const database = await openDB() const database = await openDB();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const transaction = database.transaction([VIDEO_STORE], 'readwrite') const transaction = database.transaction([VIDEO_STORE], 'readwrite');
const store = transaction.objectStore(VIDEO_STORE) const store = transaction.objectStore(VIDEO_STORE);
const request = store.clear() const request = store.clear();
request.onerror = () => reject(request.error) request.onerror = () => reject(request.error);
request.onsuccess = () => resolve() request.onsuccess = () => resolve();
}) });
} }

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,73 +1,73 @@
import { SessionContext, VideoResultData, emptySessionContext } from "@/types"; import { SessionContext, VideoResultData, emptySessionContext } from '@/types';
// Session Storage Keys // Session Storage Keys
const SESSION_KEY = "visionroad_session"; const SESSION_KEY = 'visionroad_session';
const VIDEO_DATA_KEY = "visionroad_video_data"; const VIDEO_DATA_KEY = 'visionroad_video_data';
const DETECTION_TYPE_KEY = "visionroad_detection_type"; const DETECTION_TYPE_KEY = 'visionroad_detection_type';
/** /**
* Session Service * Session Service
*/ */
export const sessionService = { export const sessionService = {
/** /**
* Save session to localStorage * Save session to localStorage
*/ */
saveSession: (session: SessionContext): void => { saveSession: (session: SessionContext): void => {
if (typeof window !== "undefined") { if (typeof window !== 'undefined') {
localStorage.setItem(SESSION_KEY, JSON.stringify(session)) 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)
} }
},
/**
* 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 axiosClient from '../axios/axios';
import { Video, PaginationParams } from "@/types"; import { Video, PaginationParams } from '@/types';
/** /**
* Video Service * Video Service
*/ */
export const videoService = { export const videoService = {
/** /**
* Fetch all videos and transform them to match the Video interface * Fetch all videos and transform them to match the Video interface
*/ */
getVideos: async (params?: PaginationParams): Promise<Video[]> => { getVideos: async (params?: PaginationParams): Promise<Video[]> => {
const skip = params?.skip ?? 0; const skip = params?.skip ?? 0;
const limit = params?.limit ?? 100; const limit = params?.limit ?? 100;
const response = await axiosClient.get<{ const response = await axiosClient.get<{
videos: Array<{ videos: Array<{
video_id: string; video_id: string;
status: string; status: string;
progress: number; progress: number;
summary?: { summary?: {
unique_defected_sign_board?: number; unique_defected_sign_board?: number;
unique_pothole?: number; unique_pothole?: number;
unique_road_crack?: number; unique_road_crack?: number;
unique_damaged_road_marking?: number; unique_damaged_road_marking?: number;
unique_good_sign_board?: number; unique_good_sign_board?: number;
total_road_damage?: number; total_road_damage?: number;
total_detections?: number; total_detections?: number;
}; };
}>; }>;
}>(`/videos`, { }>(`/videos`, {
params: { skip, limit } params: { skip, limit },
}); });
// Transform the response to match our Video interface // Transform the response to match our Video interface
return response.data.videos.map(v => ({ return response.data.videos.map((v) => ({
id: v.video_id, id: v.video_id,
filename: v.video_id, filename: v.video_id,
detection_type: "pot-sign-detection" as const, detection_type: 'pot-sign-detection' as const,
status: v.status as Video["status"], status: v.status as Video['status'],
unique_defected_sign_board: v.summary?.unique_defected_sign_board, unique_defected_sign_board: v.summary?.unique_defected_sign_board,
unique_pothole: v.summary?.unique_pothole, unique_pothole: v.summary?.unique_pothole,
unique_road_crack: v.summary?.unique_road_crack, unique_road_crack: v.summary?.unique_road_crack,
unique_damaged_road_marking: v.summary?.unique_damaged_road_marking, unique_damaged_road_marking: v.summary?.unique_damaged_road_marking,
unique_good_sign_board: v.summary?.unique_good_sign_board, unique_good_sign_board: v.summary?.unique_good_sign_board,
total_road_damage: v.summary?.total_road_damage, total_road_damage: v.summary?.total_road_damage,
total_detections: v.summary?.total_detections, total_detections: v.summary?.total_detections,
created_at: new Date().toISOString(), created_at: new Date().toISOString(),
updated_at: new Date().toISOString() updated_at: new Date().toISOString(),
})); }));
}, },
/** /**
* Upload a video for processing * Upload a video for processing
*/ */
uploadVideo: async (formData: FormData): Promise<any> => { uploadVideo: async (formData: FormData): Promise<any> => {
const response = await axiosClient.post("/upload", formData, { const response = await axiosClient.post('/upload', formData, {
headers: { headers: {
"Content-Type": "multipart/form-data" 'Content-Type': 'multipart/form-data',
} },
}); });
return response.data; return response.data;
}, },
/** /**
* Get processing status of a video * Get processing status of a video
*/ */
getVideoStatus: async (videoId: string): Promise<any> => { getVideoStatus: async (videoId: string): Promise<any> => {
const response = await axiosClient.get(`/status/${videoId}`); const response = await axiosClient.get(`/status/${videoId}`);
return response.data; return response.data;
}, },
/** /**
* Get analysis results for a video * Get analysis results for a video
*/ */
getVideoResults: async (videoId: string): Promise<any> => { getVideoResults: async (videoId: string): Promise<any> => {
const response = await axiosClient.get(`/results/${videoId}`); const response = await axiosClient.get(`/results/${videoId}`);
return response.data; return response.data;
} },
}; };

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,28 +2,28 @@
* Detection types for map and display * Detection types for map and display
*/ */
export interface Detection { export interface Detection {
id: number id: number;
video_id: string video_id: string;
type: string type: string;
class: string class: string;
confidence: number confidence: number;
latitude: number | null latitude: number | null;
longitude: number | null longitude: number | null;
frame_number: number frame_number: number;
timestamp_ms: 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 { export interface DetectionListItem {
detection_id?: number detection_id?: number;
pothole_id?: number pothole_id?: number;
signboard_id?: number signboard_id?: number;
type: string type: string;
first_detected_frame: number first_detected_frame: number;
first_detected_time: number first_detected_time: number;
confidence: number confidence: number;
bbox?: { x1: number; y1: number; x2: number; y2: number } bbox?: { x1: number; y1: number; x2: number; y2: number };
lat?: number lat?: number;
lng?: number lng?: number;
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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