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.

5254
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;

View File

@@ -1,167 +1,184 @@
"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, MapPin, Navigation, Milestone, ArrowUpCircle, ArrowDownCircle } from "lucide-react"
import { DataTable } from "@/components/data-table"
import { PageHeader } from "@/components/page-header"
import { PoweredBy } from "@/components/powered-by"
import { projectService, packageService, chainageService } from "@/services/api"
import { import {
Project, Select,
Package as PackageType, SelectContent,
Chainage, SelectItem,
ChainageCreate, SelectTrigger,
ChainageUpdate SelectValue,
} from "@/types" } from '@/components/ui/select';
import { ColumnDef } from "@tanstack/react-table" import {
import { toast } from "sonner" Dialog,
import { Badge } from "@/components/ui/badge" DialogContent,
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" DialogDescription,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Loader2,
CheckCircle2,
MapPin,
Navigation,
Milestone,
ArrowUpCircle,
ArrowDownCircle,
} from 'lucide-react';
import { DataTable } from '@/components/data-table';
import { PageHeader } from '@/components/page-header';
import { PoweredBy } from '@/components/powered-by';
import { projectService, packageService, chainageService } from '@/services/api';
import { Project, Package as PackageType, Chainage, ChainageCreate, ChainageUpdate } 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';
export default function ChainagePage() { export default function ChainagePage() {
const [chainages, setChainages] = useState<Chainage[]>([]) const [chainages, setChainages] = useState<Chainage[]>([]);
const [totalItems, setTotalItems] = useState(0) const [totalItems, setTotalItems] = useState(0);
const [projects, setProjects] = useState<Project[]>([]) const [projects, setProjects] = useState<Project[]>([]);
const [packages, setPackages] = useState<PackageType[]>([]) const [packages, setPackages] = useState<PackageType[]>([]);
const [allPackages, setAllPackages] = useState<PackageType[]>([]) const [allPackages, setAllPackages] = useState<PackageType[]>([]);
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);
const [loadingPackages, setLoadingPackages] = useState(false) const [loadingPackages, setLoadingPackages] = 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 [currentChainage, setCurrentChainage] = useState<Chainage | null>(null) const [currentChainage, setCurrentChainage] = useState<Chainage | null>(null);
// Form fields // Form fields
const [selectedProjectId, setSelectedProjectId] = useState("") const [selectedProjectId, setSelectedProjectId] = useState('');
const [selectedPackageId, setSelectedPackageId] = useState("") const [selectedPackageId, setSelectedPackageId] = useState('');
const [segmentName, setSegmentName] = useState("") const [segmentName, setSegmentName] = useState('');
const [chainageStartKm, setChainageStartKm] = useState("") const [chainageStartKm, setChainageStartKm] = useState('');
const [chainageEndKm, setChainageEndKm] = useState("") const [chainageEndKm, setChainageEndKm] = 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('');
const [direction, setDirection] = useState<'UP' | 'DOWN'>("UP") const [direction, setDirection] = useState<'UP' | 'DOWN'>('UP');
// Load chainages and projects // Load chainages and projects
const loadChainages = async (currentSkip = skip, currentLimit = limit) => { const loadChainages = async (currentSkip = skip, currentLimit = limit) => {
try { try {
setIsLoading(true) setIsLoading(true);
setError(null) setError(null);
const data = await chainageService.getChainages({ skip: currentSkip, limit: currentLimit }) const data = await chainageService.getChainages({ skip: currentSkip, limit: currentLimit });
setChainages(data.items) setChainages(data.items);
setTotalItems(data.totalItems) setTotalItems(data.totalItems);
} catch (err) { } catch (err) {
setError("Failed to load chainages. Please check if the backend is running.") setError('Failed to load chainages. 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 () => { const loadProjects = async () => {
try { try {
setLoadingProjects(true) setLoadingProjects(true);
const data = await projectService.getProjects({ skip: 0, limit: 1000 }) const data = await projectService.getProjects({ skip: 0, limit: 1000 });
setProjects(data.items) setProjects(data.items);
} catch (err) { } catch (err) {
setError("Failed to load projects.") setError('Failed to load projects.');
} finally { } finally {
setLoadingProjects(false) setLoadingProjects(false);
}
} }
};
const loadAllPackages = async () => { const loadAllPackages = async () => {
try { try {
const data = await packageService.getPackages({ skip: 0, limit: 1000 }) const data = await packageService.getPackages({ skip: 0, limit: 1000 });
setAllPackages(data.items) setAllPackages(data.items);
} catch (err) { } catch (err) {
console.error("Failed to load all packages") console.error('Failed to load all packages');
}
} }
};
useEffect(() => { useEffect(() => {
loadChainages(skip, limit) loadChainages(skip, limit);
loadProjects() loadProjects();
loadAllPackages() loadAllPackages();
}, [skip, limit]) }, [skip, limit]);
// Load packages when project changes // Load packages when project changes
useEffect(() => { useEffect(() => {
if (!selectedProjectId) { if (!selectedProjectId) {
setPackages([]) setPackages([]);
if (!isEditing) setSelectedPackageId("") if (!isEditing) setSelectedPackageId('');
return return;
} }
const loadPackagesForProject = async () => { const loadPackagesForProject = async () => {
try { try {
setLoadingPackages(true) setLoadingPackages(true);
if (!isEditing) setSelectedPackageId("") if (!isEditing) setSelectedPackageId('');
const data = await packageService.getPackagesByProject(selectedProjectId, { skip: 0, limit: 1000 }) const data = await packageService.getPackagesByProject(selectedProjectId, {
setPackages(data.items) skip: 0,
limit: 1000,
});
setPackages(data.items);
} catch (err) { } catch (err) {
setError("Failed to load packages for the selected project.") setError('Failed to load packages for the selected project.');
} finally { } finally {
setLoadingPackages(false) setLoadingPackages(false);
} }
} };
loadPackagesForProject() loadPackagesForProject();
}, [selectedProjectId, isEditing]) }, [selectedProjectId, isEditing]);
const resetForm = () => { const resetForm = () => {
setSelectedProjectId("") setSelectedProjectId('');
setSelectedPackageId("") setSelectedPackageId('');
setSegmentName("") setSegmentName('');
setChainageStartKm("") setChainageStartKm('');
setChainageEndKm("") setChainageEndKm('');
setStartLat("") setStartLat('');
setStartLng("") setStartLng('');
setEndLat("") setEndLat('');
setEndLng("") setEndLng('');
setDirection("UP") setDirection('UP');
setError(null) setError(null);
setIsEditing(false) setIsEditing(false);
setCurrentChainage(null) setCurrentChainage(null);
} };
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault() e.preventDefault();
if (!selectedPackageId && !isEditing) { if (!selectedPackageId && !isEditing) {
setError("Please select a project and package first") setError('Please select a project and package first');
return return;
} }
if (!segmentName.trim()) { if (!segmentName.trim()) {
setError("Segment name is required") setError('Segment name is required');
return return;
} }
if (!startLat || !startLng || !endLat || !endLng) { if (!startLat || !startLng || !endLat || !endLng) {
setError("All GPS coordinates are required for chainages") setError('All GPS coordinates are required for chainages');
return return;
} }
if (!chainageStartKm || !chainageEndKm) { if (!chainageStartKm || !chainageEndKm) {
setError("Chainage start and end values are required") setError('Chainage start and end values are required');
return return;
} }
setIsSubmitting(true) setIsSubmitting(true);
setError(null) setError(null);
try { try {
if (isEditing && currentChainage) { if (isEditing && currentChainage) {
@@ -174,11 +191,11 @@ export default function ChainagePage() {
end_lat: parseFloat(endLat), end_lat: parseFloat(endLat),
end_lng: parseFloat(endLng), end_lng: parseFloat(endLng),
direction: direction as 'UP' | 'DOWN', direction: direction as 'UP' | 'DOWN',
} };
await chainageService.updateChainage(currentChainage.id, data) await chainageService.updateChainage(currentChainage.id, data);
toast.success("Chainage Updated", { toast.success('Chainage Updated', {
description: `${segmentName} has been updated successfully at ${new Date().toLocaleTimeString()}`, description: `${segmentName} has been updated successfully at ${new Date().toLocaleTimeString()}`,
}) });
} else { } else {
const data: ChainageCreate = { const data: ChainageCreate = {
package_id: selectedPackageId, package_id: selectedPackageId,
@@ -190,121 +207,131 @@ export default function ChainagePage() {
end_lat: parseFloat(endLat), end_lat: parseFloat(endLat),
end_lng: parseFloat(endLng), end_lng: parseFloat(endLng),
direction: direction, direction: direction,
} };
await chainageService.createChainage(data) await chainageService.createChainage(data);
toast.success("Chainage Created", { toast.success('Chainage Created', {
description: `${segmentName} has been established successfully at ${new Date().toLocaleTimeString()}`, description: `${segmentName} has been established successfully at ${new Date().toLocaleTimeString()}`,
}) });
} }
// Refresh chainages list // Refresh chainages list
await loadChainages() await loadChainages();
// Close modal and reset form immediately // Close modal and reset form immediately
setIsModalOpen(false) setIsModalOpen(false);
resetForm() resetForm();
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} chainage` const message =
setError(message) err instanceof Error
toast.error("Operation Failed", { ? err.message
: `Failed to ${isEditing ? 'update' : 'create'} chainage`;
setError(message);
toast.error('Operation Failed', {
description: message, description: message,
}) });
} finally { } finally {
setIsSubmitting(false) setIsSubmitting(false);
}
} }
};
const handleEdit = (chainage: Chainage) => { const handleEdit = (chainage: Chainage) => {
setIsEditing(true) setIsEditing(true);
setCurrentChainage(chainage) setCurrentChainage(chainage);
// Find project for this package // Find project for this package
const pkg = allPackages.find(p => p.id === chainage.package_id) const pkg = allPackages.find((p) => p.id === chainage.package_id);
if (pkg) { if (pkg) {
setSelectedProjectId(pkg.project_id) setSelectedProjectId(pkg.project_id);
setSelectedPackageId(chainage.package_id) setSelectedPackageId(chainage.package_id);
} }
setSegmentName(chainage.segment_name || "") setSegmentName(chainage.segment_name || '');
setChainageStartKm(chainage.chainage_start_km?.toString() || "") setChainageStartKm(chainage.chainage_start_km?.toString() || '');
setChainageEndKm(chainage.chainage_end_km?.toString() || "") setChainageEndKm(chainage.chainage_end_km?.toString() || '');
setStartLat(chainage.start_lat.toString()) setStartLat(chainage.start_lat.toString());
setStartLng(chainage.start_lng.toString()) setStartLng(chainage.start_lng.toString());
setEndLat(chainage.end_lat.toString()) setEndLat(chainage.end_lat.toString());
setEndLng(chainage.end_lng.toString()) setEndLng(chainage.end_lng.toString());
setDirection(chainage.direction) setDirection(chainage.direction);
setIsModalOpen(true) setIsModalOpen(true);
} };
const handleDelete = async (chainage: Chainage) => { const handleDelete = async (chainage: Chainage) => {
if (!confirm(`Are you sure you want to delete chainage "${chainage.segment_name}"?`)) return if (!confirm(`Are you sure you want to delete chainage "${chainage.segment_name}"?`)) return;
try { try {
setIsLoading(true) setIsLoading(true);
await chainageService.deleteChainage(chainage.id) await chainageService.deleteChainage(chainage.id);
toast.success("Chainage Deleted", { toast.success('Chainage Deleted', {
description: `${chainage.segment_name} has been removed from the system.`, description: `${chainage.segment_name} has been removed from the system.`,
}) });
await loadChainages() await loadChainages();
} catch (err) { } catch (err) {
setError("Failed to delete chainage") setError('Failed to delete chainage');
toast.error("Deletion Failed", { toast.error('Deletion Failed', {
description: "The chainage could not be removed. Please try again.", description: 'The chainage could not be removed. Please try again.',
}) });
} finally { } finally {
setIsLoading(false) setIsLoading(false);
}
} }
};
const getPackageName = (packageId: string) => { const getPackageName = (packageId: string) => {
return allPackages.find(p => p.id === packageId)?.name || packageId return allPackages.find((p) => p.id === packageId)?.name || packageId;
} };
const isFormComplete = selectedPackageId && segmentName.trim() && startLat && startLng && endLat && endLng && chainageStartKm && chainageEndKm const isFormComplete =
selectedPackageId &&
segmentName.trim() &&
startLat &&
startLng &&
endLat &&
endLng &&
chainageStartKm &&
chainageEndKm;
const columns: ColumnDef<Chainage>[] = [ const columns: ColumnDef<Chainage>[] = [
{ {
accessorKey: "segment_name", accessorKey: 'segment_name',
header: "Segment Name", header: 'Segment Name',
cell: ({ row }) => ( cell: ({ row }) => <div className="font-semibold">{row.original.segment_name}</div>,
<div className="font-semibold">{row.original.segment_name}</div>
)
}, },
{ {
accessorKey: "package_id", accessorKey: 'package_id',
header: "Package", header: 'Package',
cell: ({ row }) => getPackageName(row.original.package_id) cell: ({ row }) => getPackageName(row.original.package_id),
}, },
{ {
accessorKey: "project", accessorKey: 'project',
header: "Project", header: 'Project',
cell: ({ row }) => { cell: ({ row }) => {
const chainage = row.original const chainage = row.original;
const pkg = allPackages.find(p => p.id === chainage.package_id) const pkg = allPackages.find((p) => p.id === chainage.package_id);
const project = projects.find(p => p.id === pkg?.project_id) const project = projects.find((p) => p.id === pkg?.project_id);
return project?.name || "—" return project?.name || '—';
} },
}, },
{ {
id: "project_state", id: 'project_state',
header: "Project State", header: 'Project State',
cell: ({ row }) => { cell: ({ row }) => {
const chainage = row.original const chainage = row.original;
const pkg = allPackages.find(p => p.id === chainage.package_id) const pkg = allPackages.find((p) => p.id === chainage.package_id);
const project = projects.find(p => p.id === pkg?.project_id) const project = projects.find((p) => p.id === pkg?.project_id);
if (!project?.state) return <span className=""></span> if (!project?.state) return <span className=""></span>;
const states = project.state.split(',').map(s => s.trim()).filter(Boolean) const states = project.state
if (states.length === 0) return <span className=""></span> .split(',')
.map((s) => s.trim())
.filter(Boolean);
if (states.length === 0) return <span className=""></span>;
const firstState = states[0] const firstState = states[0];
const remainingStates = states.slice(1) const remainingStates = states.slice(1);
return ( return (
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<Badge variant="secondary"> <Badge variant="secondary">{firstState}</Badge>
{firstState}
</Badge>
{remainingStates.length > 0 && ( {remainingStates.length > 0 && (
<Popover> <Popover>
@@ -315,7 +342,9 @@ export default function ChainagePage() {
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-auto p-2" align="start"> <PopoverContent className="w-auto p-2" align="start">
<div className="flex flex-col gap-1.5"> <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> <p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
Other States
</p>
{remainingStates.map((item, idx) => ( {remainingStates.map((item, idx) => (
<Badge key={idx} variant="secondary"> <Badge key={idx} variant="secondary">
{item} {item}
@@ -326,24 +355,25 @@ export default function ChainagePage() {
</Popover> </Popover>
)} )}
</div> </div>
) );
} },
}, },
{ {
accessorKey: "chainage", accessorKey: 'chainage',
header: "Chainage (km)", header: 'Chainage (km)',
cell: ({ row }) => { cell: ({ row }) => {
const chainage = row.original const chainage = row.original;
return ( return (
<div className="flex flex-row gap-2"> <div className="flex flex-row gap-2">
<Badge variant="outline" className="flex items-center gap-1.5 border-amber-500/50 text-amber-500 font-bold whitespace-nowrap"> <Badge
variant="outline"
className="flex items-center gap-1.5 border-amber-500/50 text-amber-500 font-bold whitespace-nowrap"
>
<Milestone className="h-3 w-3" /> <Milestone className="h-3 w-3" />
{chainage.chainage_start_km} - {chainage.chainage_end_km} {chainage.chainage_start_km} - {chainage.chainage_end_km}
</Badge> </Badge>
<Badge <Badge variant="secondary">
variant="secondary" {chainage.direction === 'UP' ? (
>
{chainage.direction === "UP" ? (
<ArrowUpCircle className="h-3 w-3" /> <ArrowUpCircle className="h-3 w-3" />
) : ( ) : (
<ArrowDownCircle className="h-3 w-3" /> <ArrowDownCircle className="h-3 w-3" />
@@ -351,30 +381,36 @@ export default function ChainagePage() {
{chainage.direction} {chainage.direction}
</Badge> </Badge>
</div> </div>
) );
} },
}, },
{ {
accessorKey: "start_gps", accessorKey: 'start_gps',
header: "Start GPS", header: 'Start GPS',
cell: ({ row }) => ( cell: ({ row }) => (
<Badge variant="outline" className="flex items-center gap-1.5 border-blue-500/50 text-blue-500 font-bold whitespace-nowrap"> <Badge
variant="outline"
className="flex items-center gap-1.5 border-blue-500/50 text-blue-500 font-bold whitespace-nowrap"
>
<MapPin className="h-3 w-3" /> <MapPin className="h-3 w-3" />
{row.original.start_lat.toFixed(4)}, {row.original.start_lng.toFixed(4)} {row.original.start_lat.toFixed(4)}, {row.original.start_lng.toFixed(4)}
</Badge> </Badge>
) ),
}, },
{ {
accessorKey: "end_gps", accessorKey: 'end_gps',
header: "End GPS", header: 'End GPS',
cell: ({ row }) => ( cell: ({ row }) => (
<Badge variant="outline" className="flex items-center gap-1.5 border-blue-500/50 text-blue-500 font-bold whitespace-nowrap"> <Badge
variant="outline"
className="flex items-center gap-1.5 border-blue-500/50 text-blue-500 font-bold whitespace-nowrap"
>
<MapPin className="h-3 w-3" /> <MapPin className="h-3 w-3" />
{row.original.end_lat.toFixed(4)}, {row.original.end_lng.toFixed(4)} {row.original.end_lat.toFixed(4)}, {row.original.end_lng.toFixed(4)}
</Badge> </Badge>
) ),
}, },
] ];
return ( return (
<> <>
@@ -387,7 +423,10 @@ export default function ChainagePage() {
icon={Milestone} icon={Milestone}
actions={ actions={
<Button <Button
onClick={() => { setIsEditing(false); setIsModalOpen(true); }} onClick={() => {
setIsEditing(false);
setIsModalOpen(true);
}}
> >
<Milestone className="mr-2 h-4 w-4" /> <Milestone className="mr-2 h-4 w-4" />
Add New Chainage Add New Chainage
@@ -396,7 +435,6 @@ export default function ChainagePage() {
/> />
</div> </div>
{/* Data Table */} {/* Data Table */}
<div> <div>
<DataTable <DataTable
@@ -414,7 +452,7 @@ export default function ChainagePage() {
onLimitChange: (newLimit) => { onLimitChange: (newLimit) => {
setLimit(newLimit); setLimit(newLimit);
setSkip(0); // Reset skip when limit changes setSkip(0); // Reset skip when limit changes
} },
}} }}
/> />
</div> </div>
@@ -423,10 +461,18 @@ export default function ChainagePage() {
</main> </main>
{/* Modal Dialog */} {/* Modal Dialog */}
<Dialog open={isModalOpen} onOpenChange={(open) => { if (!open) { setIsModalOpen(false); resetForm(); } else { setIsModalOpen(true); } }}> <Dialog
<DialogContent open={isModalOpen}
onOpenAutoFocus={(e) => e.preventDefault()} onOpenChange={(open) => {
if (!open) {
setIsModalOpen(false);
resetForm();
} else {
setIsModalOpen(true);
}
}}
> >
<DialogContent onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader className="gap-2"> <DialogHeader className="gap-2">
<DialogTitle className="flex items-center gap-3 text-xl"> <DialogTitle className="flex items-center gap-3 text-xl">
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm"> <div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
@@ -435,12 +481,12 @@ export default function ChainagePage() {
{isEditing ? 'Edit Chainage Details' : 'Create New Chainage'} {isEditing ? 'Edit Chainage Details' : 'Create New Chainage'}
</DialogTitle> </DialogTitle>
<DialogDescription className="text-sm"> <DialogDescription className="text-sm">
{isEditing ? 'Update the technical specifications for your road segment chainage.' : 'Select a project & package, then provide the essential chainage data.'} {isEditing
? 'Update the technical specifications for your road segment chainage.'
: 'Select a project & package, then provide the essential chainage data.'}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6"> <form onSubmit={handleSubmit} className="space-y-6">
{!isEditing && ( {!isEditing && (
<div className="grid grid-cols-1 md:grid-cols-2 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
@@ -450,7 +496,9 @@ export default function ChainagePage() {
<div className="w-5 h-5 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase"> <div className="w-5 h-5 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase">
01 01
</div> </div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">Select Project</p> <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
Select Project
</p>
</div> </div>
<Select value={selectedProjectId} onValueChange={setSelectedProjectId}> <Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
<SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20"> <SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
@@ -464,7 +512,7 @@ export default function ChainagePage() {
)} )}
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{projects.map(project => ( {projects.map((project) => (
<SelectItem key={project.id} value={project.id} className="py-2.5"> <SelectItem key={project.id} value={project.id} className="py-2.5">
<span className="font-semibold">{project.name}</span> <span className="font-semibold">{project.name}</span>
</SelectItem> </SelectItem>
@@ -474,14 +522,24 @@ export default function ChainagePage() {
</div> </div>
{/* Step 2: Select Package */} {/* Step 2: Select Package */}
<div className={`space-y-3 ${selectedProjectId ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}> <div
className={`space-y-3 ${selectedProjectId ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
>
<div className="flex items-center gap-2.5"> <div className="flex items-center gap-2.5">
<div className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedProjectId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}> <div
className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedProjectId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
>
02 02
</div> </div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">Select Package</p> <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
Select Package
</p>
</div> </div>
<Select value={selectedPackageId} onValueChange={setSelectedPackageId} disabled={!selectedProjectId}> <Select
value={selectedPackageId}
onValueChange={setSelectedPackageId}
disabled={!selectedProjectId}
>
<SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20"> <SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
{loadingPackages ? ( {loadingPackages ? (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
@@ -489,11 +547,15 @@ export default function ChainagePage() {
<span className="text-muted-foreground text-xs">Loading...</span> <span className="text-muted-foreground text-xs">Loading...</span>
</div> </div>
) : ( ) : (
<SelectValue placeholder={selectedProjectId ? "Choose a package..." : "Select project first"} /> <SelectValue
placeholder={
selectedProjectId ? 'Choose a package...' : 'Select project first'
}
/>
)} )}
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{packages.map(pkg => ( {packages.map((pkg) => (
<SelectItem key={pkg.id} value={pkg.id} className="py-2.5"> <SelectItem key={pkg.id} value={pkg.id} className="py-2.5">
<span className="font-semibold">{pkg.name}</span> <span className="font-semibold">{pkg.name}</span>
</SelectItem> </SelectItem>
@@ -505,20 +567,29 @@ export default function ChainagePage() {
)} )}
{/* Step 3: Chainage Details */} {/* Step 3: Chainage Details */}
<div className={`space-y-4 ${selectedPackageId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}> <div
className={`space-y-4 ${selectedPackageId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
>
{!isEditing && ( {!isEditing && (
<div className="flex items-center gap-2.5"> <div className="flex items-center gap-2.5">
<div className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedPackageId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}> <div
className={`w-5 h-5 rounded-full flex items-center justify-center text-[10px] font-bold uppercase ${selectedPackageId ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'}`}
>
03 03
</div> </div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">Chainage Information</p> <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
Chainage Information
</p>
</div> </div>
)} )}
{/* Segment Name & Chainage Row */} {/* Segment Name & Chainage Row */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5"> <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="segment" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
htmlFor="segment"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Segment Name <span className="text-destructive">*</span> Segment Name <span className="text-destructive">*</span>
</Label> </Label>
<Input <Input
@@ -532,7 +603,10 @@ export default function ChainagePage() {
</div> </div>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="ch-start" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
htmlFor="ch-start"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Start (km) <span className="text-destructive">*</span> Start (km) <span className="text-destructive">*</span>
</Label> </Label>
<Input <Input
@@ -548,7 +622,10 @@ export default function ChainagePage() {
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="ch-end" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
htmlFor="ch-end"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
End (km) <span className="text-destructive">*</span> End (km) <span className="text-destructive">*</span>
</Label> </Label>
<Input <Input
@@ -568,7 +645,10 @@ export default function ChainagePage() {
{/* Direction Row */} {/* Direction Row */}
<div className="space-y-3"> <div className="space-y-3">
<Label htmlFor="direction" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
htmlFor="direction"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Direction <span className="text-destructive">*</span> Direction <span className="text-destructive">*</span>
</Label> </Label>
<Select value={direction} onValueChange={(val: 'UP' | 'DOWN') => setDirection(val)}> <Select value={direction} onValueChange={(val: 'UP' | 'DOWN') => setDirection(val)}>
@@ -595,7 +675,12 @@ export default function ChainagePage() {
</p> </p>
<div className="grid grid-cols-1 gap-3"> <div className="grid grid-cols-1 gap-3">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Label htmlFor="s-lat" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70 w-8">Lat</Label> <Label
htmlFor="s-lat"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70 w-8"
>
Lat
</Label>
<Input <Input
id="s-lat" id="s-lat"
type="number" type="number"
@@ -608,7 +693,12 @@ export default function ChainagePage() {
/> />
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Label htmlFor="s-lng" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70 w-8">Lng</Label> <Label
htmlFor="s-lng"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70 w-8"
>
Lng
</Label>
<Input <Input
id="s-lng" id="s-lng"
type="number" type="number"
@@ -630,7 +720,12 @@ export default function ChainagePage() {
</p> </p>
<div className="grid grid-cols-1 gap-3"> <div className="grid grid-cols-1 gap-3">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Label htmlFor="e-lat" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70 w-8">Lat</Label> <Label
htmlFor="e-lat"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70 w-8"
>
Lat
</Label>
<Input <Input
id="e-lat" id="e-lat"
type="number" type="number"
@@ -643,7 +738,12 @@ export default function ChainagePage() {
/> />
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Label htmlFor="e-lng" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70 w-8">Lng</Label> <Label
htmlFor="e-lng"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70 w-8"
>
Lng
</Label>
<Input <Input
id="e-lng" id="e-lng"
type="number" type="number"
@@ -667,18 +767,14 @@ export default function ChainagePage() {
type="button" type="button"
variant="outline" variant="outline"
onClick={() => { onClick={() => {
setIsModalOpen(false) setIsModalOpen(false);
resetForm() resetForm();
}} }}
disabled={isSubmitting} disabled={isSubmitting}
> >
Cancel Cancel
</Button> </Button>
<Button <Button type="submit" disabled={isSubmitting || !isFormComplete} className="flex-1">
type="submit"
disabled={isSubmitting || !isFormComplete}
className="flex-1"
>
{isSubmitting ? ( {isSubmitting ? (
<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" />
@@ -686,7 +782,11 @@ export default function ChainagePage() {
</div> </div>
) : ( ) : (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{isEditing ? <CheckCircle2 className="h-4 w-4" /> : <Milestone className="h-4 w-4" />} {isEditing ? (
<CheckCircle2 className="h-4 w-4" />
) : (
<Milestone className="h-4 w-4" />
)}
<span>{isEditing ? 'Update Chainage' : 'Create Chainage'}</span> <span>{isEditing ? 'Update Chainage' : 'Create Chainage'}</span>
</div> </div>
)} )}
@@ -696,5 +796,5 @@ export default function ChainagePage() {
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</> </>
) );
} }

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,35 +1,33 @@
"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"> <div className="container mx-auto px-6 py-10 max-w-340">
{/* Refined Left-Aligned Header */} {/* Refined Left-Aligned Header */}
<div className="mb-8"> <div className="mb-8">
@@ -47,13 +45,11 @@ export default function NewAnalysisPage() {
</div> </div>
</Reveal> </Reveal>
<Reveal delay={0.4}> <Reveal delay={0.4}>
<PoweredBy /> <PoweredBy />
</Reveal> </Reveal>
</div> </div>
</main> </main>
</div> </div>
) );
} }

View File

@@ -1,112 +1,119 @@
"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 () => { const loadProjects = async () => {
try { try {
setLoadingProjects(true) setLoadingProjects(true);
const data = await projectService.getProjects({ skip: 0, limit: 1000 }) // Load all projects for selector const data = await projectService.getProjects({ skip: 0, limit: 1000 }); // Load all projects for selector
setProjects(data.items) setProjects(data.items);
} catch (err) { } catch (err) {
setError("Failed to load projects.") setError('Failed to load projects.');
} finally { } finally {
setLoadingProjects(false) setLoadingProjects(false);
}
} }
};
useEffect(() => { useEffect(() => {
loadPackages(skip, limit) loadPackages(skip, limit);
loadProjects() loadProjects();
}, [skip, limit]) }, [skip, limit]);
const resetForm = () => { const resetForm = () => {
setSelectedProjectId("") setSelectedProjectId('');
setName("") setName('');
setRegion("") setRegion('');
setChainageStartKm("") setChainageStartKm('');
setChainageEndKm("") setChainageEndKm('');
setError(null) setError(null);
setIsEditing(false) setIsEditing(false);
setCurrentPackage(null) setCurrentPackage(null);
} };
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault() e.preventDefault();
if (!selectedProjectId) { if (!selectedProjectId) {
setError("Please select a project first") setError('Please select a project first');
return return;
} }
if (!name.trim()) { if (!name.trim()) {
setError("Package name is required") setError('Package name is required');
return return;
} }
setIsSubmitting(true) setIsSubmitting(true);
setError(null) setError(null);
try { try {
if (isEditing && currentPackage) { if (isEditing && currentPackage) {
@@ -115,11 +122,11 @@ export default function PackagePage() {
region: region.trim() || null, region: region.trim() || null,
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0, chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0, chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0,
} };
await packageService.updatePackage(currentPackage.id, data) await packageService.updatePackage(currentPackage.id, data);
toast.success("Package Updated", { toast.success('Package Updated', {
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`, description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
}) });
} else { } else {
const data: PackageCreate = { const data: PackageCreate = {
project_id: selectedProjectId, project_id: selectedProjectId,
@@ -127,97 +134,99 @@ export default function PackagePage() {
region: region.trim() || null, region: region.trim() || null,
chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0, chainage_start_km: chainageStartKm ? parseFloat(chainageStartKm) : 0,
chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0, chainage_end_km: chainageEndKm ? parseFloat(chainageEndKm) : 0,
} };
await packageService.createPackage(data) await packageService.createPackage(data);
toast.success("Package Created", { toast.success('Package Created', {
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`, description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
}) });
} }
// Refresh packages list // Refresh packages list
await loadPackages() await loadPackages();
// Close modal and reset form immediately // Close modal and reset form immediately
setIsModalOpen(false) setIsModalOpen(false);
resetForm() resetForm();
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} package` const message =
setError(message) err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} package`;
toast.error("Operation Failed", { setError(message);
toast.error('Operation Failed', {
description: message, description: message,
}) });
} finally { } finally {
setIsSubmitting(false) setIsSubmitting(false);
}
} }
};
const handleEdit = (pkg: PackageType) => { const handleEdit = (pkg: PackageType) => {
setIsEditing(true) setIsEditing(true);
setCurrentPackage(pkg) setCurrentPackage(pkg);
setSelectedProjectId(pkg.project_id) setSelectedProjectId(pkg.project_id);
setName(pkg.name || "") setName(pkg.name || '');
setRegion(pkg.region || "") setRegion(pkg.region || '');
setChainageStartKm(pkg.chainage_start_km?.toString() || "0") setChainageStartKm(pkg.chainage_start_km?.toString() || '0');
setChainageEndKm(pkg.chainage_end_km?.toString() || "0") setChainageEndKm(pkg.chainage_end_km?.toString() || '0');
setIsModalOpen(true) setIsModalOpen(true);
} };
const handleDelete = async (pkg: PackageType) => { const handleDelete = async (pkg: PackageType) => {
if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) return if (!confirm(`Are you sure you want to delete package "${pkg.name}"?`)) return;
try { try {
setIsLoading(true) setIsLoading(true);
await packageService.deletePackage(pkg.id) await packageService.deletePackage(pkg.id);
toast.success("Package Deleted", { toast.success('Package Deleted', {
description: `${pkg.name} has been removed from the system.`, description: `${pkg.name} has been removed from the system.`,
}) });
await loadPackages() await loadPackages();
} catch (err) { } catch (err) {
setError("Failed to delete package") setError('Failed to delete package');
toast.error("Deletion Failed", { toast.error('Deletion Failed', {
description: "The package could not be removed. Please try again.", description: 'The package could not be removed. Please try again.',
}) });
} finally { } finally {
setIsLoading(false) setIsLoading(false);
}
} }
};
const getProjectName = (projectId: string) => { const getProjectName = (projectId: string) => {
return projects.find(p => p.id === projectId)?.name || projectId return projects.find((p) => p.id === projectId)?.name || projectId;
} };
const columns: ColumnDef<PackageType>[] = [ const columns: ColumnDef<PackageType>[] = [
{ {
accessorKey: "name", accessorKey: 'name',
header: "Package Name", header: 'Package Name',
cell: ({ row }) => ( cell: ({ row }) => (
<div className="font-semibold text-gray-900 dark:text-gray-100">{row.original.name}</div> <div className="font-semibold text-gray-900 dark:text-gray-100">{row.original.name}</div>
) ),
}, },
{ {
accessorKey: "project_id", accessorKey: 'project_id',
header: "Project", header: 'Project',
cell: ({ row }) => getProjectName(row.original.project_id) cell: ({ row }) => getProjectName(row.original.project_id),
}, },
{ {
accessorKey: "project_state", accessorKey: 'project_state',
header: "Project State", header: 'Project State',
cell: ({ row }) => { cell: ({ row }) => {
const pkg = row.original const pkg = row.original;
const project = projects.find(p => p.id === pkg.project_id) const project = projects.find((p) => p.id === pkg.project_id);
if (!project?.state) return <span className="text-gray-400"></span> if (!project?.state) return <span className="text-gray-400"></span>;
const states = project.state.split(',').map(s => s.trim()).filter(Boolean) const states = project.state
if (states.length === 0) return <span className="text-gray-400"></span> .split(',')
.map((s) => s.trim())
.filter(Boolean);
if (states.length === 0) return <span className="text-gray-400"></span>;
const firstState = states[0] const firstState = states[0];
const remainingStates = states.slice(1) const remainingStates = states.slice(1);
return ( return (
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<Badge variant="secondary"> <Badge variant="secondary">{firstState}</Badge>
{firstState}
</Badge>
{remainingStates.length > 0 && ( {remainingStates.length > 0 && (
<Popover> <Popover>
@@ -228,7 +237,9 @@ export default function PackagePage() {
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-auto p-2" align="start"> <PopoverContent className="w-auto p-2" align="start">
<div className="flex flex-col gap-1.5"> <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> <p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
Other States
</p>
{remainingStates.map((item, idx) => ( {remainingStates.map((item, idx) => (
<Badge key={idx} variant="secondary"> <Badge key={idx} variant="secondary">
{item} {item}
@@ -239,28 +250,27 @@ export default function PackagePage() {
</Popover> </Popover>
)} )}
</div> </div>
) );
} },
}, },
{ {
accessorKey: "region", accessorKey: 'region',
header: "Region", header: 'Region',
}, },
{ {
accessorKey: "chainage_start_km", accessorKey: 'chainage_start_km',
header: "Start (km)", header: 'Start (km)',
cell: ({ row }) => row.original.chainage_start_km?.toFixed(2) ?? "0.00" cell: ({ row }) => row.original.chainage_start_km?.toFixed(2) ?? '0.00',
}, },
{ {
accessorKey: "chainage_end_km", accessorKey: 'chainage_end_km',
header: "End (km)", header: 'End (km)',
cell: ({ row }) => row.original.chainage_end_km?.toFixed(2) ?? "0.00" cell: ({ row }) => row.original.chainage_end_km?.toFixed(2) ?? '0.00',
}, },
] ];
return ( return (
<> <>
<main className="relative z-10"> <main className="relative z-10">
{/* Refined Header */} {/* Refined Header */}
<div className="mb-8"> <div className="mb-8">
@@ -270,7 +280,10 @@ export default function PackagePage() {
icon={Package} icon={Package}
actions={ actions={
<Button <Button
onClick={() => { setIsEditing(false); setIsModalOpen(true); }} onClick={() => {
setIsEditing(false);
setIsModalOpen(true);
}}
> >
<Package className="mr-2 h-4 w-4" /> <Package className="mr-2 h-4 w-4" />
Add New Package Add New Package
@@ -279,7 +292,6 @@ export default function PackagePage() {
/> />
</div> </div>
{/* Data Table */} {/* Data Table */}
<div> <div>
<DataTable <DataTable
@@ -297,7 +309,7 @@ export default function PackagePage() {
onLimitChange: (newLimit) => { onLimitChange: (newLimit) => {
setLimit(newLimit); setLimit(newLimit);
setSkip(0); // Reset skip when limit changes setSkip(0); // Reset skip when limit changes
} },
}} }}
/> />
</div> </div>
@@ -306,11 +318,18 @@ export default function PackagePage() {
</main> </main>
{/* Modal Dialog */} {/* Modal Dialog */}
<Dialog open={isModalOpen} onOpenChange={(open) => { if (!open) { setIsModalOpen(false); resetForm(); } else { setIsModalOpen(true); } }}> <Dialog
<DialogContent open={isModalOpen}
className="max-w-2xl" onOpenChange={(open) => {
onOpenAutoFocus={(e) => e.preventDefault()} if (!open) {
setIsModalOpen(false);
resetForm();
} else {
setIsModalOpen(true);
}
}}
> >
<DialogContent className="max-w-2xl" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader className="gap-2"> <DialogHeader className="gap-2">
<DialogTitle className="flex items-center gap-3 text-xl"> <DialogTitle className="flex items-center gap-3 text-xl">
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm"> <div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
@@ -319,12 +338,12 @@ export default function PackagePage() {
{isEditing ? 'Edit Package Details' : 'Create New Package'} {isEditing ? 'Edit Package Details' : 'Create New Package'}
</DialogTitle> </DialogTitle>
<DialogDescription className="text-sm"> <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.'} {isEditing
? 'Update the technical specifications for your road infrastructure package.'
: 'Select a project and provide the essential data to establish a new package.'}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<form onSubmit={handleSubmit} className="space-y-8"> <form onSubmit={handleSubmit} className="space-y-8">
{/* Step 1: Select Project */} {/* Step 1: Select Project */}
{!isEditing && ( {!isEditing && (
@@ -333,7 +352,9 @@ export default function PackagePage() {
<div className="w-6 h-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase"> <div className="w-6 h-6 rounded-full bg-primary/10 text-primary flex items-center justify-center text-[10px] font-bold uppercase">
01 01
</div> </div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">Select Parent Project</p> <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
Select Parent Project
</p>
</div> </div>
<Select value={selectedProjectId} onValueChange={setSelectedProjectId}> <Select value={selectedProjectId} onValueChange={setSelectedProjectId}>
<SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20"> <SelectTrigger className="h-11 bg-muted/10 border-border/40 focus:ring-primary/20">
@@ -347,7 +368,7 @@ export default function PackagePage() {
)} )}
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
{projects.map(project => ( {projects.map((project) => (
<SelectItem key={project.id} value={project.id} className="py-3"> <SelectItem key={project.id} value={project.id} className="py-3">
<span className="font-semibold">{project.name}</span> <span className="font-semibold">{project.name}</span>
</SelectItem> </SelectItem>
@@ -357,21 +378,29 @@ export default function PackagePage() {
</div> </div>
)} )}
{/* Step 2: Package Info */} {/* Step 2: Package Info */}
<div className={`space-y-4 ${selectedProjectId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}> <div
className={`space-y-4 ${selectedProjectId || isEditing ? 'opacity-100' : 'opacity-40 pointer-events-none'}`}
>
{!isEditing && ( {!isEditing && (
<div className="flex items-center gap-2.5"> <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'}`}> <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 02
</div> </div>
<p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">Package Information</p> <p className="text-[11px] font-black text-muted-foreground uppercase tracking-widest">
Package Information
</p>
</div> </div>
)} )}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5"> <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="pkg-name" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
htmlFor="pkg-name"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Package Name <span className="text-destructive">*</span> Package Name <span className="text-destructive">*</span>
</Label> </Label>
<Input <Input
@@ -385,9 +414,13 @@ export default function PackagePage() {
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="region" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-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" /> <Globe className="h-3.5 w-3.5 opacity-60" />
Region <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span> Region{' '}
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label> </Label>
<Input <Input
id="region" id="region"
@@ -399,7 +432,10 @@ export default function PackagePage() {
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="chainage-start" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
htmlFor="chainage-start"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Chainage Start (km) Chainage Start (km)
</Label> </Label>
<Input <Input
@@ -414,7 +450,10 @@ export default function PackagePage() {
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="chainage-end" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
htmlFor="chainage-end"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Chainage End (km) Chainage End (km)
</Label> </Label>
<Input <Input
@@ -436,8 +475,8 @@ export default function PackagePage() {
type="button" type="button"
variant="outline" variant="outline"
onClick={() => { onClick={() => {
setIsModalOpen(false) setIsModalOpen(false);
resetForm() resetForm();
}} }}
disabled={isSubmitting} disabled={isSubmitting}
className="flex-1" className="flex-1"
@@ -456,7 +495,11 @@ export default function PackagePage() {
</div> </div>
) : ( ) : (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{isEditing ? <CheckCircle2 className="h-4 w-4" /> : <Package className="h-4 w-4" />} {isEditing ? (
<CheckCircle2 className="h-4 w-4" />
) : (
<Package className="h-4 w-4" />
)}
<span>{isEditing ? 'Update Package' : 'Create Package'}</span> <span>{isEditing ? 'Update Package' : 'Create Package'}</span>
</div> </div>
)} )}
@@ -466,5 +509,5 @@ export default function PackagePage() {
</DialogContent> </DialogContent>
</Dialog> </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,91 +1,97 @@
"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(() => { useEffect(() => {
loadProjects(skip, limit) loadProjects(skip, limit);
}, [skip, limit]) }, [skip, limit]);
const resetForm = () => { const resetForm = () => {
setName("") setName('');
setState("") setState('');
setCorridorName("") setCorridorName('');
setStartLat("") setStartLat('');
setStartLng("") setStartLng('');
setEndLat("") setEndLat('');
setEndLng("") setEndLng('');
setError(null) setError(null);
setIsEditing(false) setIsEditing(false);
setCurrentProject(null) setCurrentProject(null);
} };
const handleSubmit = async (e: React.FormEvent) => { const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault() e.preventDefault();
if (!name.trim()) { if (!name.trim()) {
setError("Project name is required") setError('Project name is required');
return return;
} }
setIsSubmitting(true) setIsSubmitting(true);
setError(null) setError(null);
try { try {
if (isEditing && currentProject) { if (isEditing && currentProject) {
@@ -97,11 +103,11 @@ export default function ProjectPage() {
start_lng: startLng ? parseFloat(startLng) : null, start_lng: startLng ? parseFloat(startLng) : null,
end_lat: endLat ? parseFloat(endLat) : null, end_lat: endLat ? parseFloat(endLat) : null,
end_lng: endLng ? parseFloat(endLng) : null, end_lng: endLng ? parseFloat(endLng) : null,
} };
await projectService.updateProject(currentProject.id, data) await projectService.updateProject(currentProject.id, data);
toast.success("Project Updated", { toast.success('Project Updated', {
description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`, description: `${name} has been updated successfully at ${new Date().toLocaleTimeString()}`,
}) });
} else { } else {
const data: ProjectCreate = { const data: ProjectCreate = {
name: name.trim(), name: name.trim(),
@@ -111,92 +117,90 @@ export default function ProjectPage() {
start_lng: startLng ? parseFloat(startLng) : null, start_lng: startLng ? parseFloat(startLng) : null,
end_lat: endLat ? parseFloat(endLat) : null, end_lat: endLat ? parseFloat(endLat) : null,
end_lng: endLng ? parseFloat(endLng) : null, end_lng: endLng ? parseFloat(endLng) : null,
} };
await projectService.createProject(data) await projectService.createProject(data);
toast.success("Project Created", { toast.success('Project Created', {
description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`, description: `${name} has been established successfully at ${new Date().toLocaleTimeString()}`,
}) });
} }
// Refresh projects list // Refresh projects list
await loadProjects() await loadProjects();
// Close modal and reset form immediately // Close modal and reset form immediately
setIsModalOpen(false) setIsModalOpen(false);
resetForm() resetForm();
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} project` const message =
setError(message) err instanceof Error ? err.message : `Failed to ${isEditing ? 'update' : 'create'} project`;
toast.error("Operation Failed", { setError(message);
toast.error('Operation Failed', {
description: message, description: message,
}) });
} finally { } finally {
setIsSubmitting(false) setIsSubmitting(false);
}
} }
};
const handleEdit = (project: Project) => { const handleEdit = (project: Project) => {
setIsEditing(true) setIsEditing(true);
setCurrentProject(project) setCurrentProject(project);
setName(project.name || "") setName(project.name || '');
setState(project.state || "") setState(project.state || '');
setCorridorName(project.corridor_name || "") setCorridorName(project.corridor_name || '');
setStartLat(project.start_lat?.toString() || "") setStartLat(project.start_lat?.toString() || '');
setStartLng(project.start_lng?.toString() || "") setStartLng(project.start_lng?.toString() || '');
setEndLat(project.end_lat?.toString() || "") setEndLat(project.end_lat?.toString() || '');
setEndLng(project.end_lng?.toString() || "") setEndLng(project.end_lng?.toString() || '');
setIsModalOpen(true) setIsModalOpen(true);
} };
const handleDelete = async (project: Project) => { const handleDelete = async (project: Project) => {
if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) return if (!confirm(`Are you sure you want to delete project "${project.name}"?`)) return;
try { try {
setIsLoading(true) setIsLoading(true);
await projectService.deleteProject(project.id) await projectService.deleteProject(project.id);
toast.success("Project Deleted", { toast.success('Project Deleted', {
description: `${project.name} has been removed from the system.`, description: `${project.name} has been removed from the system.`,
}) });
await loadProjects() await loadProjects();
} catch (err) { } catch (err) {
setError("Failed to delete project") setError('Failed to delete project');
toast.error("Deletion Failed", { toast.error('Deletion Failed', {
description: "The project could not be removed. Please try again or check your permissions.", description:
}) 'The project could not be removed. Please try again or check your permissions.',
});
} finally { } finally {
setIsLoading(false) setIsLoading(false);
}
} }
};
const columns: ColumnDef<Project>[] = [ const columns: ColumnDef<Project>[] = [
{ {
accessorKey: "name", accessorKey: 'name',
header: "Project Name", header: 'Project Name',
cell: ({ row }) => ( cell: ({ row }) => <div className="font-semibold">{row.original.name}</div>,
<div className="font-semibold">{row.original.name}</div>
)
}, },
{ {
accessorKey: "state", accessorKey: 'state',
header: "State", header: 'State',
cell: ({ row }) => { cell: ({ row }) => {
const project = row.original const project = row.original;
if (!project.state) return <span></span> if (!project.state) return <span></span>;
const states = project.state.split(',').map(s => s.trim()).filter(Boolean) const states = project.state
if (states.length === 0) return <span></span> .split(',')
.map((s) => s.trim())
.filter(Boolean);
if (states.length === 0) return <span></span>;
const firstState = states[0] const firstState = states[0];
const remainingStates = states.slice(1) const remainingStates = states.slice(1);
return ( return (
<div className="flex items-center gap-1.5"> <div className="flex items-center gap-1.5">
<Badge <Badge variant="secondary">{firstState}</Badge>
variant="secondary"
>
{firstState}
</Badge>
{remainingStates.length > 0 && ( {remainingStates.length > 0 && (
<Popover> <Popover>
@@ -207,12 +211,11 @@ export default function ProjectPage() {
</PopoverTrigger> </PopoverTrigger>
<PopoverContent className="w-auto p-2" align="start"> <PopoverContent className="w-auto p-2" align="start">
<div className="flex flex-col gap-1.5"> <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> <p className="text-[10px] font-bold text-muted-foreground uppercase tracking-wider mb-0.5 px-1">
Other States
</p>
{remainingStates.map((item, idx) => ( {remainingStates.map((item, idx) => (
<Badge <Badge key={idx} variant="secondary">
key={idx}
variant="secondary"
>
{item} {item}
</Badge> </Badge>
))} ))}
@@ -221,18 +224,17 @@ export default function ProjectPage() {
</Popover> </Popover>
)} )}
</div> </div>
) );
} },
}, },
{ {
accessorKey: "corridor_name", accessorKey: 'corridor_name',
header: "Corridor", header: 'Corridor',
}, },
] ];
return ( return (
<> <>
<main className="relative z-10"> <main className="relative z-10">
{/* Refined Header */} {/* Refined Header */}
<div className="mb-8"> <div className="mb-8">
@@ -242,7 +244,10 @@ export default function ProjectPage() {
icon={Layers} icon={Layers}
actions={ actions={
<Button <Button
onClick={() => { setIsEditing(false); setIsModalOpen(true); }} onClick={() => {
setIsEditing(false);
setIsModalOpen(true);
}}
> >
<Layers className="mr-2 h-5 w-5" /> <Layers className="mr-2 h-5 w-5" />
Add New Project Add New Project
@@ -251,7 +256,6 @@ export default function ProjectPage() {
/> />
</div> </div>
{/* Data Table */} {/* Data Table */}
<div> <div>
<DataTable <DataTable
@@ -269,7 +273,7 @@ export default function ProjectPage() {
onLimitChange: (newLimit) => { onLimitChange: (newLimit) => {
setLimit(newLimit); setLimit(newLimit);
setSkip(0); // Reset skip when limit changes setSkip(0); // Reset skip when limit changes
} },
}} }}
/> />
</div> </div>
@@ -277,13 +281,19 @@ export default function ProjectPage() {
<PoweredBy /> <PoweredBy />
</main> </main>
{/* Modal Dialog */} {/* Modal Dialog */}
<Dialog open={isModalOpen} onOpenChange={(open) => { if (!open) { setIsModalOpen(false); resetForm(); } else { setIsModalOpen(true); } }}> <Dialog
<DialogContent open={isModalOpen}
className="max-w-2xl" onOpenChange={(open) => {
onOpenAutoFocus={(e) => e.preventDefault()} if (!open) {
setIsModalOpen(false);
resetForm();
} else {
setIsModalOpen(true);
}
}}
> >
<DialogContent className="max-w-2xl" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogHeader className="gap-2"> <DialogHeader className="gap-2">
<DialogTitle className="flex items-center gap-3 text-xl"> <DialogTitle className="flex items-center gap-3 text-xl">
<div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm"> <div className="p-2 rounded-lg bg-primary text-primary-foreground shadow-sm">
@@ -292,16 +302,19 @@ export default function ProjectPage() {
{isEditing ? 'Edit Project Details' : 'Create New Project'} {isEditing ? 'Edit Project Details' : 'Create New Project'}
</DialogTitle> </DialogTitle>
<DialogDescription className="text-sm"> <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.'} {isEditing
? 'Update the technical specifications for your road infrastructure project.'
: 'Provide the essential road data to establish a new analysis project.'}
</DialogDescription> </DialogDescription>
</DialogHeader> </DialogHeader>
<form onSubmit={handleSubmit} className="space-y-6"> <form onSubmit={handleSubmit} className="space-y-6">
{/* Project Name */} {/* Project Name */}
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="name" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
htmlFor="name"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
Project Name <span className="text-destructive">*</span> Project Name <span className="text-destructive">*</span>
</Label> </Label>
<Input <Input
@@ -317,8 +330,12 @@ export default function ProjectPage() {
{/* State & Corridor Row */} {/* State & Corridor Row */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-5"> <div className="grid grid-cols-1 md:grid-cols-2 gap-5">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="state" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"> <Label
State <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span> htmlFor="state"
className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider"
>
State{' '}
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label> </Label>
<Input <Input
id="state" id="state"
@@ -329,9 +346,13 @@ export default function ProjectPage() {
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="corridor" className="text-[11px] font-bold text-muted-foreground uppercase tracking-wider flex items-center gap-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" /> <Route className="h-3.5 w-3.5 opacity-60" />
Corridor Name <span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span> Corridor Name{' '}
<span className="text-[10px] lowercase font-normal opacity-70">(Optional)</span>
</Label> </Label>
<Input <Input
id="corridor" id="corridor"
@@ -352,7 +373,12 @@ export default function ProjectPage() {
</p> </p>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="start-lat" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70">Lat</Label> <Label
htmlFor="start-lat"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
>
Lat
</Label>
<Input <Input
id="start-lat" id="start-lat"
type="number" type="number"
@@ -364,7 +390,12 @@ export default function ProjectPage() {
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="start-lng" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70">Lng</Label> <Label
htmlFor="start-lng"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
>
Lng
</Label>
<Input <Input
id="start-lng" id="start-lng"
type="number" type="number"
@@ -385,7 +416,12 @@ export default function ProjectPage() {
</p> </p>
<div className="grid grid-cols-2 gap-4"> <div className="grid grid-cols-2 gap-4">
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="end-lat" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70">Lat</Label> <Label
htmlFor="end-lat"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
>
Lat
</Label>
<Input <Input
id="end-lat" id="end-lat"
type="number" type="number"
@@ -397,7 +433,12 @@ export default function ProjectPage() {
/> />
</div> </div>
<div className="space-y-2"> <div className="space-y-2">
<Label htmlFor="end-lng" className="text-[10px] font-bold text-muted-foreground uppercase opacity-70">Lng</Label> <Label
htmlFor="end-lng"
className="text-[10px] font-bold text-muted-foreground uppercase opacity-70"
>
Lng
</Label>
<Input <Input
id="end-lng" id="end-lng"
type="number" type="number"
@@ -418,8 +459,8 @@ export default function ProjectPage() {
type="button" type="button"
variant="outline" variant="outline"
onClick={() => { onClick={() => {
setIsModalOpen(false) setIsModalOpen(false);
resetForm() resetForm();
}} }}
disabled={isSubmitting} disabled={isSubmitting}
className="flex-1 h-12 font-bold uppercase tracking-wider text-xs border-border/80 hover:bg-muted/50" className="flex-1 h-12 font-bold uppercase tracking-wider text-xs border-border/80 hover:bg-muted/50"
@@ -438,7 +479,11 @@ export default function ProjectPage() {
</div> </div>
) : ( ) : (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{isEditing ? <CheckCircle2 className="h-4 w-4" /> : <Layers className="h-4 w-4" />} {isEditing ? (
<CheckCircle2 className="h-4 w-4" />
) : (
<Layers className="h-4 w-4" />
)}
<span>{isEditing ? 'Update Project' : 'Create Project'}</span> <span>{isEditing ? 'Update Project' : 'Create Project'}</span>
</div> </div>
)} )}
@@ -448,5 +493,5 @@ export default function ProjectPage() {
</DialogContent> </DialogContent>
</Dialog> </Dialog>
</> </>
) );
} }

View File

@@ -1,81 +1,84 @@
"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
) {
setDetectionType('pothole-detection');
} }
// Retrieve video file from IndexedDB // Retrieve video file from IndexedDB
const storedVideoFile = await getVideoFile(videoId) const storedVideoFile = await getVideoFile(videoId);
if (storedVideoFile) { if (storedVideoFile) {
setVideoFile(storedVideoFile) setVideoFile(storedVideoFile);
} }
} catch (err) { } catch (err) {
setError(err instanceof Error ? err.message : "Failed to load results") setError(err instanceof Error ? err.message : 'Failed to load results');
} finally { } finally {
setIsLoading(false) setIsLoading(false);
}
} }
};
if (videoId) { if (videoId) {
fetchResults() fetchResults();
} }
}, [videoId]) }, [videoId]);
const handleNewAnalysis = async () => { const handleNewAnalysis = async () => {
if (videoId) { if (videoId) {
try { try {
await clearVideoFile(videoId) await clearVideoFile(videoId);
} catch (err) { } catch (err) {
console.error("Failed to clear video file:", err) console.error('Failed to clear video file:', err);
} }
} }
sessionService.clearSession() sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS) router.push(ROUTES.NEW_ANALYSIS);
} };
const getTitle = () => { const getTitle = () => {
if (detectionType === "pothole-detection") return "Pothole Detection Results" if (detectionType === 'pothole-detection') return 'Pothole Detection Results';
if (detectionType === "sign-board-detection") return "Signboard Detection Results" if (detectionType === 'sign-board-detection') return 'Signboard Detection Results';
return "Pothole & Signboard Detection Results" return 'Pothole & Signboard Detection Results';
} };
if (isLoading) { if (isLoading) {
return ( return (
@@ -85,7 +88,7 @@ export default function VideoResultsPage() {
<p className="text-sm text-muted-foreground">Loading detection results...</p> <p className="text-sm text-muted-foreground">Loading detection results...</p>
</Card> </Card>
</div> </div>
) );
} }
if (error) { if (error) {
@@ -94,12 +97,14 @@ export default function VideoResultsPage() {
<Card className="flex flex-col items-center gap-6 p-8 text-center max-w-md"> <Card className="flex flex-col items-center gap-6 p-8 text-center max-w-md">
<p className="text-destructive font-medium">{error}</p> <p className="text-destructive font-medium">{error}</p>
<div className="flex gap-4"> <div className="flex gap-4">
<Button onClick={() => router.push(ROUTES.UPLOAD)} variant="outline">Back to Upload</Button> <Button onClick={() => router.push(ROUTES.UPLOAD)} variant="outline">
Back to Upload
</Button>
<Button onClick={handleNewAnalysis}>New Analysis</Button> <Button onClick={handleNewAnalysis}>New Analysis</Button>
</div> </div>
</Card> </Card>
</div> </div>
) );
} }
return ( return (
@@ -107,11 +112,7 @@ export default function VideoResultsPage() {
<main className="min-h-screen"> <main className="min-h-screen">
<div className="container mx-auto px-6 py-10 max-w-[1600px]"> <div className="container mx-auto px-6 py-10 max-w-[1600px]">
<div className="mb-8"> <div className="mb-8">
<PageHeader <PageHeader title={getTitle()} description={`Video ID: ${videoId}`} icon={TrendingUp} />
title={getTitle()}
description={`Video ID: ${videoId}`}
icon={TrendingUp}
/>
</div> </div>
{session && ( {session && (
@@ -120,25 +121,36 @@ export default function VideoResultsPage() {
<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-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-wrap items-center gap-x-12 gap-y-4">
<div className="flex flex-col"> <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-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight"> <span className="text-base font-bold leading-tight">
{session.projectName} {session.projectName}
</span> </span>
</div> </div>
<div className="flex flex-col border-l pl-12 border-border/60"> <div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span> <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName} {session.packageName}
</span> </span>
</div> </div>
<div className="flex flex-col border-l pl-12 border-border/60"> <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-[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"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName} {session.chainageName}
</span> </span>
</div> </div>
</div> </div>
<Button onClick={handleNewAnalysis} variant="outline" size="sm" className="font-semibold px-6 shrink-0 h-9"> <Button
onClick={handleNewAnalysis}
variant="outline"
size="sm"
className="font-semibold px-6 shrink-0 h-9"
>
Start New Analysis Start New Analysis
</Button> </Button>
</div> </div>
@@ -159,5 +171,5 @@ export default function VideoResultsPage() {
</div> </div>
</main> </main>
</div> </div>
) );
} }

View File

@@ -1,65 +1,65 @@
"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 we have a videoId, redirect to the dynamic results page
if (videoData.videoId) { if (videoData.videoId) {
router.replace(`${ROUTES.RESULTS}/${videoData.videoId}`) router.replace(`${ROUTES.RESULTS}/${videoData.videoId}`);
return return;
} }
setSession(storedSession) setSession(storedSession);
}, [router]) }, [router]);
const handleNewAnalysis = async () => { const handleNewAnalysis = async () => {
// Clear video from IndexedDB // Clear video from IndexedDB
if (videoId) { if (videoId) {
try { try {
await clearVideoFile(videoId) await clearVideoFile(videoId);
} catch (err) { } catch (err) {
console.error("Failed to clear video file:", err) console.error('Failed to clear video file:', err);
} }
} }
sessionService.clearSession() sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS) router.push(ROUTES.NEW_ANALYSIS);
} };
const getTitle = () => { const getTitle = () => {
if (detectionType === "pothole-detection") return "Pothole Detection Results" if (detectionType === 'pothole-detection') return 'Pothole Detection Results';
if (detectionType === "sign-board-detection") return "Signboard Detection Results" if (detectionType === 'sign-board-detection') return 'Signboard Detection Results';
return "Pothole & Signboard Detection Results" return 'Pothole & Signboard Detection Results';
} };
if (isLoading) { if (isLoading) {
return ( return (
@@ -69,7 +69,7 @@ export default function ResultsPage() {
<p className="text-sm text-muted-foreground">Loading results...</p> <p className="text-sm text-muted-foreground">Loading results...</p>
</Card> </Card>
</div> </div>
) );
} }
if (error) { if (error) {
@@ -80,7 +80,7 @@ export default function ResultsPage() {
<Button onClick={handleNewAnalysis}>Start New Analysis</Button> <Button onClick={handleNewAnalysis}>Start New Analysis</Button>
</Card> </Card>
</div> </div>
) );
} }
return ( return (
@@ -101,25 +101,36 @@ export default function ResultsPage() {
<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-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-wrap items-center gap-x-12 gap-y-4">
<div className="flex flex-col"> <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-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight"> <span className="text-base font-bold leading-tight">
{session.projectName} {session.projectName}
</span> </span>
</div> </div>
<div className="flex flex-col border-l pl-12 border-border/60"> <div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span> <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName} {session.packageName}
</span> </span>
</div> </div>
<div className="flex flex-col border-l pl-12 border-border/60"> <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-[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"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName} {session.chainageName}
</span> </span>
</div> </div>
</div> </div>
<Button onClick={handleNewAnalysis} variant="outline" size="sm" className="font-semibold px-6 shrink-0 h-9"> <Button
onClick={handleNewAnalysis}
variant="outline"
size="sm"
className="font-semibold px-6 shrink-0 h-9"
>
Start New Analysis Start New Analysis
</Button> </Button>
</div> </div>
@@ -140,5 +151,5 @@ export default function ResultsPage() {
</div> </div>
</main> </main>
</div> </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,106 +1,108 @@
"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") { if (data.type === 'complete' || data.status === 'completed') {
setStatusMessage("Processing completed! Finalizing...") setStatusMessage('Processing completed! Finalizing...');
ws.close() ws.close();
// Navigate to results // Navigate to results
setTimeout(() => router.push(`/results/${vid}`), 1000) setTimeout(() => router.push(`/results/${vid}`), 1000);
} }
if (data.type === "error") { if (data.type === 'error') {
setError("Error: " + data.message) setError('Error: ' + data.message);
setStatusMessage("") setStatusMessage('');
ws.close() ws.close();
}
} }
};
ws.onerror = () => { ws.onerror = () => {
setStatusMessage("Connection lost. Reconnecting...") setStatusMessage('Connection lost. Reconnecting...');
setTimeout(() => connectWebSocket(vid), 3000) setTimeout(() => connectWebSocket(vid), 3000);
} };
return ws return ws;
}, [router]) },
[router],
);
useEffect(() => { useEffect(() => {
const storedSession = sessionService.loadSession() const storedSession = sessionService.loadSession();
setSession(storedSession) setSession(storedSession);
const checkStatus = async () => { const checkStatus = async () => {
try { try {
const statusData = await videoService.getVideoStatus(videoId); const statusData = await videoService.getVideoStatus(videoId);
if (statusData.status === "completed") { if (statusData.status === 'completed') {
router.replace(`/results/${videoId}`) router.replace(`/results/${videoId}`);
return return;
} }
if (statusData.status === "error") { if (statusData.status === 'error') {
setError(statusData.message || "An error occurred during processing.") setError(statusData.message || 'An error occurred during processing.');
setIsLoading(false) setIsLoading(false);
return return;
} }
// If processing, start WebSocket // If processing, start WebSocket
setProgress(statusData.progress || 0) setProgress(statusData.progress || 0);
setStatusMessage(statusData.message || "Resuming processing...") setStatusMessage(statusData.message || 'Resuming processing...');
connectWebSocket(videoId) connectWebSocket(videoId);
setIsLoading(false) setIsLoading(false);
} catch (err) { } catch (err) {
console.error("Status check failed:", err) console.error('Status check failed:', err);
setError("Failed to connect to server.") setError('Failed to connect to server.');
setIsLoading(false) setIsLoading(false);
}
} }
};
if (videoId) { if (videoId) {
checkStatus() checkStatus();
} }
}, [videoId, router, connectWebSocket]) }, [videoId, router, connectWebSocket]);
if (isLoading) { if (isLoading) {
return ( return (
@@ -109,7 +111,7 @@ export default function VideoProcessingPage() {
<Loader2 className="h-8 w-8 animate-spin text-primary" /> <Loader2 className="h-8 w-8 animate-spin text-primary" />
</Card> </Card>
</div> </div>
) );
} }
return ( return (
@@ -130,19 +132,25 @@ export default function VideoProcessingPage() {
<div className="flex flex-col md:flex-row md:items-center py-4 px-6 gap-6 bg-card"> <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-wrap items-center gap-x-12 gap-y-4 flex-1">
<div className="flex flex-col"> <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-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight"> <span className="text-base font-bold leading-tight">
{session.projectName} {session.projectName}
</span> </span>
</div> </div>
<div className="flex flex-col border-l pl-12 border-border/60"> <div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span> <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName} {session.packageName}
</span> </span>
</div> </div>
<div className="flex flex-col border-l pl-12 border-border/60"> <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-[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"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName} {session.chainageName}
</span> </span>
@@ -156,9 +164,7 @@ export default function VideoProcessingPage() {
<Card className="flex-1 flex flex-col items-center justify-center py-12 px-8 min-h-[450px]"> <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="flex flex-col items-center justify-center w-full max-w-2xl space-y-10">
<div className="text-center space-y-4"> <div className="text-center space-y-4">
<h2 className="text-3xl font-bold tracking-tight"> <h2 className="text-3xl font-bold tracking-tight">Processing Analysis</h2>
Processing Analysis
</h2>
<p className="text-sm font-mono text-muted-foreground tracking-widest"> <p className="text-sm font-mono text-muted-foreground tracking-widest">
ID: {videoId} ID: {videoId}
</p> </p>
@@ -166,7 +172,9 @@ export default function VideoProcessingPage() {
<div className="w-full space-y-4"> <div className="w-full space-y-4">
<div className="flex items-center justify-between text-sm"> <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-muted-foreground text-xs uppercase tracking-widest">
Progress
</span>
<span className="font-bold text-primary text-lg">{progress}%</span> <span className="font-bold text-primary text-lg">{progress}%</span>
</div> </div>
<div className="h-4 rounded-full bg-secondary overflow-hidden border"> <div className="h-4 rounded-full bg-secondary overflow-hidden border">
@@ -178,9 +186,7 @@ export default function VideoProcessingPage() {
<div className="text-center pt-2"> <div className="text-center pt-2">
<div className="inline-flex items-center gap-3 px-4 py-2 rounded-full border bg-secondary/30"> <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" /> <Loader2 className="h-4 w-4 animate-spin text-primary" />
<p className="text-sm font-semibold"> <p className="text-sm font-semibold">{statusMessage}</p>
{statusMessage}
</p>
</div> </div>
</div> </div>
</div> </div>
@@ -188,11 +194,7 @@ export default function VideoProcessingPage() {
{error && ( {error && (
<div className="w-full p-6 rounded-md bg-destructive/10 border border-destructive/20 text-center space-y-3"> <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> <p className="text-destructive font-medium">{error}</p>
<Button <Button variant="outline" size="sm" onClick={() => window.location.reload()}>
variant="outline"
size="sm"
onClick={() => window.location.reload()}
>
Retry Connection Retry Connection
</Button> </Button>
</div> </div>
@@ -204,5 +206,5 @@ export default function VideoProcessingPage() {
</div> </div>
</main> </main>
</div> </div>
) );
} }

View File

@@ -1,87 +1,93 @@
"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 { try {
const result = await videoService.uploadVideo(formData); const result = await videoService.uploadVideo(formData);
@@ -89,41 +95,40 @@ export default function UploadPage() {
// Store file locally for potential recovery/results display // Store file locally for potential recovery/results display
if (file) { if (file) {
try { try {
await storeVideoFile(result.video_id, file) await storeVideoFile(result.video_id, file);
} catch (err) { } catch (err) {
console.error("Failed to store video file:", err) console.error('Failed to store video file:', err);
} }
} }
sessionService.saveVideoData({ videoId: result.video_id, detectionType }) sessionService.saveVideoData({ videoId: result.video_id, detectionType });
// Redirect to the dynamic processing page // Redirect to the dynamic processing page
router.push(`/upload/${result.video_id}`) router.push(`/upload/${result.video_id}`);
} catch (err) { } catch (err) {
let errorMessage = "Upload failed" let errorMessage = 'Upload failed';
if (err instanceof TypeError && err.message === "Failed to fetch") { if (err instanceof TypeError && err.message === 'Failed to fetch') {
errorMessage = "Cannot connect to server. Please check if backend is running." errorMessage = 'Cannot connect to server. Please check if backend is running.';
} else if (err instanceof Error) { } else if (err instanceof Error) {
errorMessage = err.message errorMessage = err.message;
}
setError(errorMessage)
setStatusMessage("")
setUploading(false)
setProgress(0)
} }
setError(errorMessage);
setStatusMessage('');
setUploading(false);
setProgress(0);
} }
};
const handleBackToSelection = () => { const handleBackToSelection = () => {
sessionService.clearSession() sessionService.clearSession();
router.push(ROUTES.NEW_ANALYSIS) router.push(ROUTES.NEW_ANALYSIS);
} };
const getTitle = () => { const getTitle = () => {
if (detectionType === "pothole-detection") return "Pothole Detection" if (detectionType === 'pothole-detection') return 'Pothole Detection';
if (detectionType === "sign-board-detection") return "Signboard Detection" if (detectionType === 'sign-board-detection') return 'Signboard Detection';
return "Pothole & Signboard Detection" return 'Pothole & Signboard Detection';
} };
if (isLoading) { if (isLoading) {
return ( return (
@@ -132,7 +137,7 @@ export default function UploadPage() {
<Loader2 className="h-8 w-8 animate-spin text-primary" /> <Loader2 className="h-8 w-8 animate-spin text-primary" />
</Card> </Card>
</div> </div>
) );
} }
return ( return (
@@ -156,19 +161,25 @@ export default function UploadPage() {
<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-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-wrap items-center gap-x-12 gap-y-4">
<div className="flex flex-col"> <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-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Project
</span>
<span className="text-base font-bold leading-tight"> <span className="text-base font-bold leading-tight">
{session.projectName} {session.projectName}
</span> </span>
</div> </div>
<div className="flex flex-col border-l pl-12 border-border/60"> <div className="flex flex-col border-l pl-12 border-border/60">
<span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">Package</span> <span className="text-[10px] font-bold uppercase tracking-widest text-muted-foreground mb-1.5">
Package
</span>
<span className="text-sm font-semibold text-muted-foreground leading-tight"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.packageName} {session.packageName}
</span> </span>
</div> </div>
<div className="flex flex-col border-l pl-12 border-border/60"> <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-[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"> <span className="text-sm font-semibold text-muted-foreground leading-tight">
{session.chainageName} {session.chainageName}
</span> </span>
@@ -190,9 +201,7 @@ export default function UploadPage() {
{/* Upload Card */} {/* Upload Card */}
<Card className="flex-1"> <Card className="flex-1">
<CardHeader className="pb-4"> <CardHeader className="pb-4">
<CardTitle className="text-xl font-bold"> <CardTitle className="text-xl font-bold">Upload Video</CardTitle>
Upload Video
</CardTitle>
<CardDescription className="text-sm"> <CardDescription className="text-sm">
Select video file, detection type, vehicle speed, and method for analysis Select video file, detection type, vehicle speed, and method for analysis
</CardDescription> </CardDescription>
@@ -209,8 +218,8 @@ export default function UploadPage() {
type="file" type="file"
accept="video/*" accept="video/*"
onChange={(e) => { onChange={(e) => {
setFile(e.target.files?.[0] || null) setFile(e.target.files?.[0] || null);
setError(null) setError(null);
}} }}
disabled={uploading} 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" 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"
@@ -227,8 +236,8 @@ export default function UploadPage() {
type="file" type="file"
accept=".json,application/json" accept=".json,application/json"
onChange={(e) => { onChange={(e) => {
setJsonFile(e.target.files?.[0] || null) setJsonFile(e.target.files?.[0] || null);
setError(null) setError(null);
}} }}
disabled={uploading} 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" 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"
@@ -283,11 +292,7 @@ export default function UploadPage() {
<Label htmlFor="select-method" className="text-sm font-semibold"> <Label htmlFor="select-method" className="text-sm font-semibold">
Select Method Select Method
</Label> </Label>
<Select <Select value={selectMethod} onValueChange={setSelectMethod} disabled={uploading}>
value={selectMethod}
onValueChange={setSelectMethod}
disabled={uploading}
>
<SelectTrigger id="select-method" className="h-11"> <SelectTrigger id="select-method" className="h-11">
<SelectValue placeholder="Select method" /> <SelectValue placeholder="Select method" />
</SelectTrigger> </SelectTrigger>
@@ -322,7 +327,7 @@ export default function UploadPage() {
<span>Processing...</span> <span>Processing...</span>
</div> </div>
) : ( ) : (
"Upload and Process" 'Upload and Process'
)} )}
</Button> </Button>
</CardContent> </CardContent>
@@ -332,5 +337,5 @@ export default function UploadPage() {
</div> </div>
</main> </main>
</div> </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"

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,26 +1,26 @@
"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) {
@@ -29,49 +29,52 @@ export default function DashboardMapContent({ detections }: DashboardMapContentP
<div className="h-full w-full flex items-center justify-center bg-muted/20"> <div className="h-full w-full flex items-center justify-center bg-muted/20">
<p className="text-muted-foreground">No detections to display</p> <p className="text-muted-foreground">No detections to display</p>
</div> </div>
) );
} }
// Calculate bounds to fit all markers // Calculate bounds to fit all markers
const firstDetection = detections[0] const firstDetection = detections[0];
const bounds = new LatLngBounds( const bounds = new LatLngBounds(
new LatLng(firstDetection.latitude!, firstDetection.longitude!), new LatLng(firstDetection.latitude!, firstDetection.longitude!),
new LatLng(firstDetection.latitude!, firstDetection.longitude!) new LatLng(firstDetection.latitude!, firstDetection.longitude!),
) );
detections.forEach(d => { detections.forEach((d) => {
if (d.latitude && d.longitude) { if (d.latitude && d.longitude) {
bounds.extend(new LatLng(d.latitude, d.longitude)) bounds.extend(new LatLng(d.latitude, d.longitude));
} }
}) });
// Center point // Center point
const center: [number, number] = [ const center: [number, number] = [
(bounds.getNorth() + bounds.getSouth()) / 2, (bounds.getNorth() + bounds.getSouth()) / 2,
(bounds.getEast() + bounds.getWest()) / 2 (bounds.getEast() + bounds.getWest()) / 2,
] ];
// Get marker color based on detection type // Get marker color based on detection type
const getMarkerColor = (type: string) => { const getMarkerColor = (type: string) => {
const t = type.toLowerCase() const t = type.toLowerCase();
if (t === "pothole") { if (t === 'pothole') {
return { fill: "#ef4444", stroke: "#b91c1c" } // Red return { fill: '#ef4444', stroke: '#b91c1c' }; // Red
} else if (t === "defected_sign_board") { } else if (t === 'defected_sign_board') {
return { fill: "#3b82f6", stroke: "#1d4ed8" } // Blue return { fill: '#3b82f6', stroke: '#1d4ed8' }; // Blue
} else if (t === "road_crack") { } else if (t === 'road_crack') {
return { fill: "#f59e0b", stroke: "#b45309" } // Orange return { fill: '#f59e0b', stroke: '#b45309' }; // Orange
} else if (t === "damaged_road_marking") { } else if (t === 'damaged_road_marking') {
return { fill: "#6366f1", stroke: "#4338ca" } // Indigo return { fill: '#6366f1', stroke: '#4338ca' }; // Indigo
} else if (t === "good_sign_board") { } else if (t === 'good_sign_board') {
return { fill: "#10b981", stroke: "#047857" } // Emerald return { fill: '#10b981', stroke: '#047857' }; // Emerald
}
return { fill: "#64748b", stroke: "#475569" } // Default Slate
} }
return { fill: '#64748b', stroke: '#475569' }; // Default Slate
};
// Get display name for detection type // Get display name for detection type
const getTypeName = (type: string) => { const getTypeName = (type: string) => {
return type.split('_').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ') return type
} .split('_')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
};
return ( return (
<MapContainer <MapContainer
@@ -88,8 +91,8 @@ export default function DashboardMapContent({ detections }: DashboardMapContentP
{/* Detection markers */} {/* Detection markers */}
{detections.map((detection, idx) => { {detections.map((detection, idx) => {
const colors = getMarkerColor(detection.type) const colors = getMarkerColor(detection.type);
const typeName = getTypeName(detection.type) const typeName = getTypeName(detection.type);
return ( return (
<CircleMarker <CircleMarker
@@ -104,13 +107,11 @@ export default function DashboardMapContent({ detections }: DashboardMapContentP
> >
<Popup> <Popup>
<div className="text-sm space-y-2 min-w-[180px]"> <div className="text-sm space-y-2 min-w-[180px]">
<div className="font-bold text-base border-b pb-1"> <div className="font-bold text-base border-b pb-1">{typeName}</div>
{typeName}
</div>
<div className="space-y-1"> <div className="space-y-1">
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-muted-foreground">Class:</span> <span className="text-muted-foreground">Class:</span>
<span className="font-medium">{detection.class.replace(/_/g, " ")}</span> <span className="font-medium">{detection.class.replace(/_/g, ' ')}</span>
</div> </div>
<div className="flex justify-between"> <div className="flex justify-between">
<span className="text-muted-foreground">Confidence:</span> <span className="text-muted-foreground">Confidence:</span>
@@ -127,11 +128,11 @@ export default function DashboardMapContent({ detections }: DashboardMapContentP
</div> </div>
</Popup> </Popup>
</CircleMarker> </CircleMarker>
) );
})} })}
{/* Auto-fit bounds */} {/* Auto-fit bounds */}
<FitBounds bounds={bounds} /> <FitBounds bounds={bounds} />
</MapContainer> </MapContainer>
) );
} }

View File

@@ -1,30 +1,27 @@
"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, ssr: false,
loading: () => ( loading: () => (
<div className="h-full w-full flex items-center justify-center"> <div className="h-full w-full flex items-center justify-center">
<Loader2 className="h-8 w-8 text-primary" /> <Loader2 className="h-8 w-8 text-primary" />
</div> </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({
@@ -32,61 +29,68 @@ export function DashboardMap({
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 { try {
setIsLoading(true) setIsLoading(true);
setError(null) setError(null);
const filteredDetections: Detection[] = [] const filteredDetections: Detection[] = [];
const packagesToProcess = selectedPackageId && selectedPackageId !== "all" const packagesToProcess =
selectedPackageId && selectedPackageId !== 'all'
? { [selectedPackageId]: projectSummary.packages[selectedPackageId] } ? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
: projectSummary.packages || {} : 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 && selectedChainageId !== 'all'
? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] } ? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
: (pkg as any).chainages || {} : (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 || [];
filteredDetections.push(...chainageDetections) filteredDetections.push(...chainageDetections);
} }
} }
setDetections(filteredDetections) setDetections(filteredDetections);
} catch (err) { } catch (err) {
console.error("Failed to extract detections:", err) console.error('Failed to extract detections:', err);
setError("Failed to load detection data") setError('Failed to load detection data');
} finally { } finally {
setIsLoading(false) setIsLoading(false);
} }
}, [projectSummary, selectedPackageId, selectedChainageId]) }, [projectSummary, selectedPackageId, selectedChainageId]);
// Filter detections with valid GPS coordinates // Filter detections with valid GPS coordinates
const validDetections = detections.filter(d => d.latitude && d.longitude) const validDetections = detections.filter((d) => d.latitude && d.longitude);
// Count detections by category // Count detections by category
const counts = { const counts = {
defected_sign_board: validDetections.filter(d => d.type?.toLowerCase() === "defected_sign_board").length, defected_sign_board: validDetections.filter(
pothole: validDetections.filter(d => d.type?.toLowerCase() === "pothole").length, (d) => d.type?.toLowerCase() === 'defected_sign_board',
road_crack: validDetections.filter(d => d.type?.toLowerCase() === "road_crack").length, ).length,
damaged_road_marking: validDetections.filter(d => d.type?.toLowerCase() === "damaged_road_marking").length, pothole: validDetections.filter((d) => d.type?.toLowerCase() === 'pothole').length,
good_sign_board: validDetections.filter(d => d.type?.toLowerCase() === "good_sign_board").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 ( return (
<Card className={`overflow-hidden ${className}`}> <Card className={`overflow-hidden ${className}`}>
@@ -97,11 +101,11 @@ export function DashboardMap({
<Milestone className="h-5 w-5" /> <Milestone className="h-5 w-5" />
</div> </div>
<div> <div>
<CardTitle className="text-base font-bold"> <CardTitle className="text-base font-bold">Detection Map</CardTitle>
Detection Map
</CardTitle>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
{isLoading ? "Loading..." : `${validDetections.length} detections with GPS coordinates`} {isLoading
? 'Loading...'
: `${validDetections.length} detections with GPS coordinates`}
</p> </p>
</div> </div>
</div> </div>
@@ -114,19 +118,27 @@ export function DashboardMap({
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-blue-500" /> <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> <span className="text-muted-foreground font-medium">
Defected Signs ({counts.defected_sign_board})
</span>
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-amber-500" /> <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> <span className="text-muted-foreground font-medium">
Cracks ({counts.road_crack})
</span>
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-indigo-500" /> <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> <span className="text-muted-foreground font-medium">
Markings ({counts.damaged_road_marking})
</span>
</div> </div>
<div className="flex items-center gap-1"> <div className="flex items-center gap-1">
<div className="w-2.5 h-2.5 rounded-full bg-emerald-500" /> <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> <span className="text-muted-foreground font-medium">
Good Signs ({counts.good_sign_board})
</span>
</div> </div>
</div> </div>
</div> </div>
@@ -145,7 +157,9 @@ export function DashboardMap({
<div className="h-full w-full flex items-center justify-center bg-muted/50"> <div className="h-full w-full flex items-center justify-center bg-muted/50">
<div className="text-center"> <div className="text-center">
<p className="text-muted-foreground">No detections with GPS coordinates found</p> <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> <p className="text-sm text-muted-foreground mt-1 opacity-70">
Process some videos to see detections on the map
</p>
</div> </div>
</div> </div>
) : ( ) : (
@@ -154,5 +168,5 @@ export function DashboardMap({
</div> </div>
</CardContent> </CardContent>
</Card> </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 (
@@ -55,5 +55,5 @@ export function DashboardSkeleton() {
</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,4 +1,4 @@
"use client" 'use client';
import { import {
Select, Select,
@@ -6,21 +6,21 @@ import {
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({
@@ -33,7 +33,7 @@ export function FilterSelector({
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">
@@ -43,10 +43,12 @@ export function FilterSelector({
<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]">
Project
</span>
</div> </div>
<Select <Select
value={selectedProjectId || ""} value={selectedProjectId || ''}
onValueChange={onProjectChange} onValueChange={onProjectChange}
disabled={isLoading || projects.length === 0} disabled={isLoading || projects.length === 0}
> >
@@ -70,10 +72,12 @@ export function FilterSelector({
<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">
<Package className="h-4 w-4" /> <Package className="h-4 w-4" />
</div> </div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">Package</span> <span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">
Package
</span>
</div> </div>
<Select <Select
value={selectedPackageId || "all"} value={selectedPackageId || 'all'}
onValueChange={onPackageChange} onValueChange={onPackageChange}
disabled={isLoading} disabled={isLoading}
> >
@@ -93,16 +97,18 @@ export function FilterSelector({
)} )}
{/* Chainage Dropdown */} {/* Chainage Dropdown */}
{selectedPackageId && selectedPackageId !== "all" && ( {selectedPackageId && selectedPackageId !== 'all' && (
<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">
<Milestone className="h-4 w-4" /> <Milestone className="h-4 w-4" />
</div> </div>
<span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">Chainage</span> <span className="text-[11px] font-black text-muted-foreground uppercase tracking-[0.15em]">
Chainage
</span>
</div> </div>
<Select <Select
value={selectedChainageId || "all"} value={selectedChainageId || 'all'}
onValueChange={onChainageChange} onValueChange={onChainageChange}
disabled={isLoading} disabled={isLoading}
> >

View File

@@ -1,15 +1,15 @@
"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({
@@ -17,12 +17,12 @@ export function StatsCard({
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">
@@ -36,13 +36,9 @@ export function StatsCard({
<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}
</p>
{subtitle && ( {subtitle && (
<p className="text-xs text-muted-foreground mt-1 line-clamp-1"> <p className="text-xs text-muted-foreground mt-1 line-clamp-1">{subtitle}</p>
{subtitle}
</p>
)} )}
</> </>
)} )}
@@ -55,6 +51,5 @@ export function StatsCard({
</CardContent> </CardContent>
</Card> </Card>
</motion.div> </motion.div>
) );
} }

View File

@@ -1,21 +1,23 @@
"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">
Rows per page
</p>
<Select <Select
value={`${table.getState().pagination.pageSize}`} value={`${table.getState().pagination.pageSize}`}
onValueChange={(value) => { onValueChange={(value) => {

View File

@@ -1,6 +1,6 @@
"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 (

View File

@@ -1,9 +1,9 @@
"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;
@@ -12,13 +12,13 @@ interface TopHeaderProps {
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>

View File

@@ -1,12 +1,8 @@
"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 (
@@ -15,15 +11,13 @@ const TableHeader = <TData, _>({ table }: { table: Table<TData> }) => {
<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"
: ( >
{header.isPlaceholder ? null : (
<div className="flex items-center gap-2 group cursor-pointer select-none"> <div className="flex items-center gap-2 group cursor-pointer select-none">
{flexRender( {flexRender(header.column.columnDef.header, header.getContext())}
header.column.columnDef.header,
header.getContext()
)}
</div> </div>
)} )}
</TableHead> </TableHead>

View File

@@ -1,5 +1,5 @@
"use client"; 'use client';
import React from "react"; import React from 'react';
import { import {
ColumnDef, ColumnDef,
SortingState, SortingState,
@@ -8,17 +8,17 @@ import {
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>[];
@@ -53,13 +53,11 @@ export function DataTable<TData, TValue>({
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;
@@ -108,10 +106,12 @@ export function DataTable<TData, TValue>({
state: { state: {
rowSelection, rowSelection,
sorting, sorting,
pagination: pagination ? { pagination: pagination
? {
pageIndex: Math.floor(pagination.skip / pagination.limit), pageIndex: Math.floor(pagination.skip / pagination.limit),
pageSize: pagination.limit, pageSize: pagination.limit,
} : undefined, }
: undefined,
}, },
onPaginationChange: (updater) => { onPaginationChange: (updater) => {
if (typeof updater === 'function' && pagination) { if (typeof updater === 'function' && pagination) {
@@ -136,12 +136,18 @@ export function DataTable<TData, TValue>({
/> />
<div className="px-6 py-2"> <div className="px-6 py-2">
<Table containerClassName="max-h-[calc(100vh-300px)] overflow-y-auto scrollbar-thin" className="border-separate border-spacing-0"> <Table
containerClassName="max-h-[calc(100vh-300px)] overflow-y-auto scrollbar-thin"
className="border-separate border-spacing-0"
>
<TableHeader table={table} /> <TableHeader table={table} />
<TableBody> <TableBody>
{isLoading ? ( {isLoading ? (
Array.from({ length: 5 }).map((_, idx) => ( Array.from({ length: 5 }).map((_, idx) => (
<TableRow key={idx} className="border-b border-border/30 last:border-0 hover:bg-muted/5"> <TableRow
key={idx}
className="border-b border-border/30 last:border-0 hover:bg-muted/5"
>
{columns.map((_, colIdx) => ( {columns.map((_, colIdx) => (
<TableCell key={colIdx} className="px-6 py-6 border-b border-border/30"> <TableCell key={colIdx} className="px-6 py-6 border-b border-border/30">
<Skeleton className="h-4 w-full max-w-[140px] opacity-20" /> <Skeleton className="h-4 w-full max-w-[140px] opacity-20" />
@@ -153,28 +159,27 @@ export function DataTable<TData, TValue>({
table.getRowModel().rows.map((row) => ( table.getRowModel().rows.map((row) => (
<TableRow <TableRow
key={row.id} key={row.id}
data-state={row.getIsSelected() && "selected"} data-state={row.getIsSelected() && 'selected'}
className="group hover:bg-muted/10 transition-colors" className="group hover:bg-muted/10 transition-colors"
> >
{row.getVisibleCells().map((cell) => ( {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"> <TableCell
{flexRender( key={cell.id}
cell.column.columnDef.cell, className="px-4 py-3 border-b border-border/50 align-middle text-muted-foreground text-sm font-medium group-hover:text-foreground"
cell.getContext() >
)} {flexRender(cell.column.columnDef.cell, cell.getContext())}
</TableCell> </TableCell>
))} ))}
</TableRow> </TableRow>
)) ))
) : ( ) : (
<TableRow> <TableRow>
<TableCell <TableCell colSpan={columns.length} className="h-48 text-center">
colSpan={columns.length}
className="h-48 text-center"
>
<div className="flex flex-col items-center justify-center text-muted-foreground gap-1"> <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="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> <p className="text-xs opacity-60 font-medium">
Try adjusting your filters or search terms.
</p>
</div> </div>
</TableCell> </TableCell>
</TableRow> </TableRow>

View File

@@ -1,52 +1,52 @@
"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) { if (validDetections.length === 0) {
return ( return (
@@ -60,23 +60,32 @@ export default function MapModal({ open, onClose, detections, detectionType }: M
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </Dialog>
) );
} }
const routeCoordinates: [number, number][] = validDetections.map(d => [d.latitude, d.longitude]) const routeCoordinates: [number, number][] = validDetections.map((d) => [
const bounds = new LatLngBounds(new LatLng(routeCoordinates[0][0], routeCoordinates[0][1]), new LatLng(routeCoordinates[0][0], routeCoordinates[0][1])) d.latitude,
routeCoordinates.forEach(coord => bounds.extend(new LatLng(coord[0], coord[1]))) d.longitude,
const center: [number, number] = [(bounds.getNorth() + bounds.getSouth()) / 2, (bounds.getEast() + bounds.getWest()) / 2] ]);
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 isCombined = detectionType === 'pot-sign-detection';
const isPothole = detectionType === "pothole-detection" const isPothole = detectionType === 'pothole-detection';
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-6xl h-[85vh] p-0 flex flex-col overflow-hidden border-none shadow-2xl">
<DialogHeader className="px-6 py-4 border-b shrink-0"> <DialogHeader className="px-6 py-4 border-b shrink-0">
<DialogTitle className="text-xl font-bold"> <DialogTitle className="text-xl font-bold">
{isCombined ? "Combined" : isPothole ? "Pothole" : "Signboard"} Detection Map {isCombined ? 'Combined' : isPothole ? 'Pothole' : 'Signboard'} Detection Map
</DialogTitle> </DialogTitle>
<p className="text-xs text-muted-foreground font-medium"> <p className="text-xs text-muted-foreground font-medium">
{validDetections.length} points of interest identified with GPS data {validDetections.length} points of interest identified with GPS data
@@ -84,34 +93,24 @@ export default function MapModal({ open, onClose, detections, detectionType }: M
</DialogHeader> </DialogHeader>
<div className="flex-1 w-full relative bg-muted/20"> <div className="flex-1 w-full relative bg-muted/20">
<MapContainer <MapContainer center={center} zoom={13} className="h-full w-full" scrollWheelZoom={true}>
center={center}
zoom={13}
className="h-full w-full"
scrollWheelZoom={true}
>
<TileLayer <TileLayer
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors' attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/> />
<Polyline <Polyline positions={routeCoordinates} color="#3b82f6" weight={4} opacity={0.6} />
positions={routeCoordinates}
color="#3b82f6"
weight={4}
opacity={0.6}
/>
{validDetections.map((detection, idx) => { {validDetections.map((detection, idx) => {
const type = (detection.type || "").toLowerCase() const type = (detection.type || '').toLowerCase();
const colors: Record<string, { fill: string, stroke: string }> = { const colors: Record<string, { fill: string; stroke: string }> = {
'pothole': { fill: '#ef4444', stroke: '#b91c1c' }, pothole: { fill: '#ef4444', stroke: '#b91c1c' },
'defected_sign_board': { fill: '#3b82f6', stroke: '#1d4ed8' }, defected_sign_board: { fill: '#3b82f6', stroke: '#1d4ed8' },
'road_crack': { fill: '#f59e0b', stroke: '#b45309' }, road_crack: { fill: '#f59e0b', stroke: '#b45309' },
'damaged_road_marking': { fill: '#6366f1', stroke: '#4338ca' }, damaged_road_marking: { fill: '#6366f1', stroke: '#4338ca' },
'good_sign_board': { fill: '#10b981', stroke: '#047857' } good_sign_board: { fill: '#10b981', stroke: '#047857' },
} };
const color = colors[type] || { fill: '#64748b', stroke: '#475569' } const color = colors[type] || { fill: '#64748b', stroke: '#475569' };
return ( return (
<CircleMarker <CircleMarker
@@ -127,13 +126,15 @@ export default function MapModal({ open, onClose, detections, detectionType }: M
<Popup> <Popup>
<div className="text-[11px] space-y-2 p-1"> <div className="text-[11px] space-y-2 p-1">
<div className="font-bold border-b pb-1 capitalize"> <div className="font-bold border-b pb-1 capitalize">
{(detection.type || "").replace(/_/g, " ")} #{detection.id} {(detection.type || '').replace(/_/g, ' ')} #{detection.id}
</div> </div>
<div className="grid grid-cols-2 gap-x-4 gap-y-1"> <div className="grid grid-cols-2 gap-x-4 gap-y-1">
<span className="text-muted-foreground">Frame:</span> <span className="text-muted-foreground">Frame:</span>
<span className="font-semibold text-right">{detection.frame_number}</span> <span className="font-semibold text-right">{detection.frame_number}</span>
<span className="text-muted-foreground">Confidence:</span> <span className="text-muted-foreground">Confidence:</span>
<span className="font-semibold text-right">{(detection.confidence * 100).toFixed(0)}%</span> <span className="font-semibold text-right">
{(detection.confidence * 100).toFixed(0)}%
</span>
</div> </div>
<div className="font-mono bg-muted p-1.5 rounded border text-center text-[9px]"> <div className="font-mono bg-muted p-1.5 rounded border text-center text-[9px]">
{detection.latitude.toFixed(6)}, {detection.longitude.toFixed(6)} {detection.latitude.toFixed(6)}, {detection.longitude.toFixed(6)}
@@ -141,12 +142,12 @@ export default function MapModal({ open, onClose, detections, detectionType }: M
</div> </div>
</Popup> </Popup>
</CircleMarker> </CircleMarker>
) );
})} })}
<FitBounds bounds={bounds} /> <FitBounds bounds={bounds} />
</MapContainer> </MapContainer>
</div> </div>
</DialogContent> </DialogContent>
</Dialog> </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,14 +1,14 @@
"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) {
@@ -21,21 +21,14 @@ export function PageHeader({ title, description, icon: Icon, children, actions }
{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}
</h1>
<p className="text-muted-foreground mt-1 text-sm font-semibold tracking-wide opacity-80"> <p className="text-muted-foreground mt-1 text-sm font-semibold tracking-wide opacity-80">
{description} {description}
</p> </p>
</div> </div>
</div> </div>
{actions && ( {actions && <div className="flex items-center gap-4">{actions}</div>}
<div className="flex items-center gap-4">
{actions}
</div>
)}
</div> </div>
</Reveal> </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>
<Image
src="/sg.svg"
alt="Sentient Geeks"
width={130}
height={20}
/>
</div> </div>
) );
} }

View File

@@ -1,127 +1,128 @@
"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 () => { const loadPackages = async () => {
try { try {
setLoadingPackages(true) setLoadingPackages(true);
setError(null) setError(null);
setSelectedPackage(null) setSelectedPackage(null);
setSelectedChainage(null) setSelectedChainage(null);
setChainages([]) setChainages([]);
const data = await packageService.getPackagesByProject(selectedProject.id) const data = await packageService.getPackagesByProject(selectedProject.id);
setPackages(data.items) setPackages(data.items);
} catch (err) { } catch (err) {
console.error("Failed to load packages:", err) console.error('Failed to load packages:', err);
setError("Failed to load packages for the selected project.") setError('Failed to load packages for the selected project.');
} finally { } finally {
setLoadingPackages(false) setLoadingPackages(false);
} }
} };
loadPackages() loadPackages();
}, [selectedProject]) }, [selectedProject]);
// Load chainages when package changes // Load chainages when package changes
useEffect(() => { useEffect(() => {
if (!selectedPackage) { if (!selectedPackage) {
setChainages([]) setChainages([]);
setSelectedChainage(null) setSelectedChainage(null);
return return;
} }
const loadChainages = async () => { const loadChainages = async () => {
try { try {
setLoadingChainages(true) setLoadingChainages(true);
setError(null) setError(null);
setSelectedChainage(null) setSelectedChainage(null);
const data = await chainageService.getChainagesByPackage(selectedPackage.id) const data = await chainageService.getChainagesByPackage(selectedPackage.id);
setChainages(data.items) setChainages(data.items);
} catch (err) { } catch (err) {
console.error("Failed to load chainages:", err) console.error('Failed to load chainages:', err);
setError("Failed to load chainages for the selected package.") setError('Failed to load chainages for the selected package.');
} finally { } finally {
setLoadingChainages(false) setLoadingChainages(false);
} }
} };
loadChainages() loadChainages();
}, [selectedPackage]) }, [selectedPackage]);
const handleProjectChange = (projectId: string) => { const handleProjectChange = (projectId: string) => {
const project = projects.find(p => p.id === projectId) || null const project = projects.find((p) => p.id === projectId) || null;
setSelectedProject(project) setSelectedProject(project);
} };
const handlePackageChange = (packageId: string) => { const handlePackageChange = (packageId: string) => {
const pkg = packages.find(p => p.id === packageId) || null const pkg = packages.find((p) => p.id === packageId) || null;
setSelectedPackage(pkg) setSelectedPackage(pkg);
} };
const handleChainageChange = (chainageId: string) => { const handleChainageChange = (chainageId: string) => {
const chainage = chainages.find(chn => chn.id === chainageId) || null const chainage = chainages.find((chn) => chn.id === chainageId) || null;
setSelectedChainage(chainage) setSelectedChainage(chainage);
} };
const handleProceed = () => { const handleProceed = () => {
if (selectedProject && selectedPackage && selectedChainage) { if (selectedProject && selectedPackage && selectedChainage) {
@@ -131,20 +132,20 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
packageId: selectedPackage.id, packageId: selectedPackage.id,
packageName: selectedPackage.name, packageName: selectedPackage.name,
chainageId: selectedChainage.id, chainageId: selectedChainage.id,
chainageName: selectedChainage.segment_name chainageName: selectedChainage.segment_name,
}) });
}
} }
};
const isComplete = selectedProject && selectedPackage && selectedChainage const isComplete = selectedProject && selectedPackage && selectedChainage;
// Step status helpers // Step status helpers
const getStepStatus = (step: number) => { const getStepStatus = (step: number) => {
if (step === 1) return selectedProject ? 'completed' : 'active' if (step === 1) return selectedProject ? 'completed' : 'active';
if (step === 2) return selectedPackage ? 'completed' : selectedProject ? 'active' : 'pending' if (step === 2) return selectedPackage ? 'completed' : selectedProject ? 'active' : 'pending';
if (step === 3) return selectedChainage ? 'completed' : selectedPackage ? 'active' : 'pending' if (step === 3) return selectedChainage ? 'completed' : selectedPackage ? 'active' : 'pending';
return 'pending' return 'pending';
} };
return ( return (
<Card className="overflow-hidden"> <Card className="overflow-hidden">
@@ -160,36 +161,42 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
{/* Step Progress Indicator */} {/* Step Progress Indicator */}
<div className="flex items-center justify-center pt-2"> <div className="flex items-center justify-center pt-2">
{[1, 2, 3].map((step, index) => { {[1, 2, 3].map((step, index) => {
const status = getStepStatus(step) const status = getStepStatus(step);
const labels = ['Project', 'Package', 'Chainage'] const labels = ['Project', 'Package', 'Chainage'];
return ( return (
<div key={step} className="flex items-center"> <div key={step} className="flex items-center">
<div className="flex flex-col items-center"> <div className="flex flex-col items-center">
<div <div
className={cn( className={cn(
"w-10 h-10 rounded-full flex items-center justify-center text-sm font-semibold transition-all", '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 === 'completed'
status === 'active' ? "bg-primary text-primary-foreground ring-4 ring-primary/10" : ? 'bg-primary text-primary-foreground'
"bg-muted text-muted-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} {status === 'completed' ? <Check className="h-5 w-5" /> : step}
</div> </div>
<span className={cn( <span
"text-xs mt-2 font-medium", className={cn(
status === 'pending' ? "text-muted-foreground/60" : "text-foreground" 'text-xs mt-2 font-medium',
)}> status === 'pending' ? 'text-muted-foreground/60' : 'text-foreground',
)}
>
{labels[index]} {labels[index]}
</span> </span>
</div> </div>
{index < 2 && ( {index < 2 && (
<div className={cn( <div
"w-16 h-0.5 mx-2 mb-6 rounded-full", className={cn(
getStepStatus(step + 1) !== 'pending' ? "bg-primary" : "bg-border" 'w-16 h-0.5 mx-2 mb-6 rounded-full',
)} /> getStepStatus(step + 1) !== 'pending' ? 'bg-primary' : 'bg-border',
)}
/>
)} )}
</div> </div>
) );
})} })}
</div> </div>
</div> </div>
@@ -210,7 +217,7 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
Project Project
</Label> </Label>
<Select <Select
value={selectedProject?.id || ""} value={selectedProject?.id || ''}
onValueChange={handleProjectChange} onValueChange={handleProjectChange}
disabled={loadingProjects} disabled={loadingProjects}
> >
@@ -240,7 +247,7 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
Package Package
</Label> </Label>
<Select <Select
value={selectedPackage?.id || ""} value={selectedPackage?.id || ''}
onValueChange={handlePackageChange} onValueChange={handlePackageChange}
disabled={!selectedProject || loadingPackages} disabled={!selectedProject || loadingPackages}
> >
@@ -251,7 +258,9 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
<span>Loading...</span> <span>Loading...</span>
</div> </div>
) : ( ) : (
<SelectValue placeholder={selectedProject ? "Select package" : "Select project first"} /> <SelectValue
placeholder={selectedProject ? 'Select package' : 'Select project first'}
/>
)} )}
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -270,7 +279,7 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
Chainage Chainage
</Label> </Label>
<Select <Select
value={selectedChainage?.id || ""} value={selectedChainage?.id || ''}
onValueChange={handleChainageChange} onValueChange={handleChainageChange}
disabled={!selectedPackage || loadingChainages} disabled={!selectedPackage || loadingChainages}
> >
@@ -281,7 +290,9 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
<span>Loading...</span> <span>Loading...</span>
</div> </div>
) : ( ) : (
<SelectValue placeholder={selectedPackage ? "Select chainage" : "Select package first"} /> <SelectValue
placeholder={selectedPackage ? 'Select chainage' : 'Select package first'}
/>
)} )}
</SelectTrigger> </SelectTrigger>
<SelectContent> <SelectContent>
@@ -321,9 +332,9 @@ export function ProjectSelectionSection({ onSelectionComplete }: ProjectSelectio
className="w-full h-12 text-base font-bold uppercase tracking-wide" className="w-full h-12 text-base font-bold uppercase tracking-wide"
size="lg" size="lg"
> >
{isComplete ? "Proceed to Upload" : "Select all fields to proceed"} {isComplete ? 'Proceed to Upload' : 'Select all fields to proceed'}
</Button> </Button>
</CardContent> </CardContent>
</Card> </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,8 +1,11 @@
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
@@ -15,7 +18,7 @@ export const chainageService = {
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;
}, },
@@ -23,11 +26,14 @@ export const chainageService = {
/** /**
* Fetch chainages filtered by package ID * Fetch chainages filtered by package ID
*/ */
getChainagesByPackage: async (packageId: string, params?: PaginationParams): Promise<PaginatedResponse<Chainage>> => { getChainagesByPackage: async (
packageId: string,
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: { package_id: packageId, skip, limit } params: { package_id: packageId, skip, limit },
}); });
return response.data; return response.data;
}, },
@@ -36,7 +42,7 @@ export const chainageService = {
* 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;
}, },
@@ -54,5 +60,5 @@ export const chainageService = {
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,6 +1,6 @@
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
@@ -17,7 +17,7 @@ export const detectionService = {
const projects = projectsResponse.items; const projects = projectsResponse.items;
// Then fetch detections for each project // Then fetch detections for each project
const allDetections: Detection[] = [] const allDetections: Detection[] = [];
for (const project of projects) { for (const project of projects) {
try { try {
@@ -26,11 +26,11 @@ export const detectionService = {
[key: string]: { [key: string]: {
chainages: { chainages: {
[key: string]: { [key: string]: {
detections: Detection[] detections: Detection[];
} };
} };
} };
} };
}>(`/summary/projects/${project.id}`); }>(`/summary/projects/${project.id}`);
const summary = response.data; const summary = response.data;
@@ -38,19 +38,19 @@ export const detectionService = {
// Extract detections from the nested structure // Extract detections from the nested structure
for (const pkg of Object.values(summary.packages || {})) { for (const pkg of Object.values(summary.packages || {})) {
for (const loc of Object.values(pkg.chainages || {})) { for (const loc of Object.values(pkg.chainages || {})) {
allDetections.push(...(loc.detections || [])) allDetections.push(...(loc.detections || []));
} }
} }
} catch (e) { } catch (e) {
// Skip projects that fail to load // Skip projects that fail to load
console.warn(`Failed to load detections for project ${project.id}:`, e) console.warn(`Failed to load detections for project ${project.id}:`, e);
} }
} }
return allDetections; return allDetections;
} catch (e) { } catch (e) {
console.error("Failed to fetch all detections:", e) console.error('Failed to fetch all detections:', e);
return [] 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,8 +1,11 @@
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
@@ -15,7 +18,7 @@ export const packageService = {
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;
}, },
@@ -23,11 +26,14 @@ export const packageService = {
/** /**
* Fetch packages filtered by project ID * Fetch packages filtered by project ID
*/ */
getPackagesByProject: async (projectId: string, params?: PaginationParams): Promise<PaginatedResponse<Package>> => { getPackagesByProject: async (
projectId: string,
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: { project_id: projectId, skip, limit } params: { project_id: projectId, skip, limit },
}); });
return response.data; return response.data;
}, },
@@ -36,7 +42,7 @@ export const packageService = {
* 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;
}, },
@@ -54,5 +60,5 @@ export const packageService = {
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,8 +1,11 @@
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
@@ -15,7 +18,7 @@ export const projectService = {
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;
}, },
@@ -24,7 +27,7 @@ export const projectService = {
* 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;
}, },
@@ -57,10 +60,10 @@ export const projectService = {
*/ */
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;
} },
}; };
/** /**
@@ -74,27 +77,29 @@ export const projectDataService = {
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 && selectedPackageId !== 'all'
? { [selectedPackageId]: projectSummary.packages[selectedPackageId] } ? { [selectedPackageId]: projectSummary.packages[selectedPackageId] }
: projectSummary.packages || {} : 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 && selectedChainageId !== 'all'
? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] } ? { [selectedChainageId]: (pkg as any).chainages[selectedChainageId] }
: (pkg as any).chainages || {} : (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,9 +1,9 @@
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
@@ -13,8 +13,8 @@ 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));
} }
}, },
@@ -22,10 +22,10 @@ export const sessionService = {
* Load session from localStorage * Load session from localStorage
*/ */
loadSession: (): SessionContext => { loadSession: (): SessionContext => {
if (typeof window !== "undefined") { if (typeof window !== 'undefined') {
const stored = localStorage.getItem(SESSION_KEY) const stored = localStorage.getItem(SESSION_KEY);
if (stored) { if (stored) {
return JSON.parse(stored) return JSON.parse(stored);
} }
} }
return emptySessionContext; return emptySessionContext;
@@ -35,10 +35,10 @@ export const sessionService = {
* Clear all session data * Clear all session data
*/ */
clearSession: (): void => { clearSession: (): void => {
if (typeof window !== "undefined") { if (typeof window !== 'undefined') {
localStorage.removeItem(SESSION_KEY) localStorage.removeItem(SESSION_KEY);
localStorage.removeItem(VIDEO_DATA_KEY) localStorage.removeItem(VIDEO_DATA_KEY);
localStorage.removeItem(DETECTION_TYPE_KEY) localStorage.removeItem(DETECTION_TYPE_KEY);
} }
}, },
@@ -46,8 +46,8 @@ export const sessionService = {
* Save video result data * Save video result data
*/ */
saveVideoData: (data: VideoResultData): void => { saveVideoData: (data: VideoResultData): void => {
if (typeof window !== "undefined") { if (typeof window !== 'undefined') {
localStorage.setItem(VIDEO_DATA_KEY, JSON.stringify(data)) localStorage.setItem(VIDEO_DATA_KEY, JSON.stringify(data));
} }
}, },
@@ -55,10 +55,10 @@ export const sessionService = {
* Load video result data * Load video result data
*/ */
loadVideoData: (): VideoResultData | null => { loadVideoData: (): VideoResultData | null => {
if (typeof window !== "undefined") { if (typeof window !== 'undefined') {
const stored = localStorage.getItem(VIDEO_DATA_KEY) const stored = localStorage.getItem(VIDEO_DATA_KEY);
if (stored) { if (stored) {
return JSON.parse(stored) return JSON.parse(stored);
} }
} }
return null; return null;
@@ -68,6 +68,6 @@ export const sessionService = {
* Check if session is complete * Check if session is complete
*/ */
isSessionValid: (session: SessionContext): boolean => { isSessionValid: (session: SessionContext): boolean => {
return !!(session.projectId && session.packageId && session.chainageId) return !!(session.projectId && session.packageId && session.chainageId);
} },
}; };

View File

@@ -1,5 +1,5 @@
import axiosClient from "../axios/axios"; import axiosClient from '../axios/axios';
import { Video, PaginationParams } from "@/types"; import { Video, PaginationParams } from '@/types';
/** /**
* Video Service * Video Service
@@ -28,15 +28,15 @@ export const videoService = {
}; };
}>; }>;
}>(`/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,
@@ -45,7 +45,7 @@ export const videoService = {
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(),
})); }));
}, },
@@ -53,10 +53,10 @@ export const videoService = {
* 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;
}, },
@@ -75,5 +75,5 @@ export const videoService = {
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"
]
} }