Connect annotator to real API: JWT login, services real-mode, Konva canvas, autosave, paginated images, tracing

This commit is contained in:
hailt 2026-11-12 15:13:07 +07:00
parent 59fc3efca6
commit e010bb5558
38 changed files with 1880 additions and 529 deletions

42
package-lock.json generated
View file

@ -1036,9 +1036,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1194,9 +1191,6 @@
"arm" "arm"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1211,9 +1205,6 @@
"arm" "arm"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1228,9 +1219,6 @@
"arm64" "arm64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1245,9 +1233,6 @@
"arm64" "arm64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1262,9 +1247,6 @@
"loong64" "loong64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1279,9 +1261,6 @@
"loong64" "loong64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1296,9 +1275,6 @@
"ppc64" "ppc64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1313,9 +1289,6 @@
"ppc64" "ppc64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1330,9 +1303,6 @@
"riscv64" "riscv64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1347,9 +1317,6 @@
"riscv64" "riscv64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1364,9 +1331,6 @@
"s390x" "s390x"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1381,9 +1345,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"glibc"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [
@ -1398,9 +1359,6 @@
"x64" "x64"
], ],
"dev": true, "dev": true,
"libc": [
"musl"
],
"license": "MIT", "license": "MIT",
"optional": true, "optional": true,
"os": [ "os": [

8
restart_web.sh Normal file
View file

@ -0,0 +1,8 @@
#!/bin/bash
# Restart danable web dev server (pattern lives here, never in caller cmdline).
pkill -f 'vite --host 0\.0\.0\.0 --port 5173' 2>/dev/null
sleep 2
cd /home/hailt/danagble/anotation-frontend
setsid -f ./node_modules/.bin/vite --host 0.0.0.0 --port 5173 </dev/null >>/tmp/danable-web.log 2>&1
sleep 5
curl -s -o /dev/null -w "web=%{http_code}\n" localhost:5173/

View file

@ -4,6 +4,15 @@ import { useAuthStore } from '@/stores/authStore'
import { LoginRequest, UserRole } from '@/types' import { LoginRequest, UserRole } from '@/types'
import { canApproveLabels, canCreateProject, canManageUsers } from '@/utils/permissions' import { canApproveLabels, canCreateProject, canManageUsers } from '@/utils/permissions'
// Prefer the server's message (e.g. FastAPI `detail`) over axios' generic text.
function readServerMessage(err: unknown): string | null {
if (typeof err === 'object' && err !== null && 'response' in err) {
const detail = (err as { response?: { data?: { detail?: unknown } } }).response?.data?.detail
if (typeof detail === 'string' && detail.trim() !== '') return detail
}
return err instanceof Error ? err.message : null
}
export function useAuth() { export function useAuth() {
const { user, isAuthenticated, login: storeLogin, logout: storeLogout, setUser, setRole } = useAuthStore() const { user, isAuthenticated, login: storeLogin, logout: storeLogout, setUser, setRole } = useAuthStore()
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
@ -17,9 +26,9 @@ export function useAuth() {
storeLogin(response.user, response.accessToken) storeLogin(response.user, response.accessToken)
return response return response
} catch (err) { } catch (err) {
const message = err instanceof Error ? err.message : 'Đăng nhập thất bại' const message = readServerMessage(err) ?? 'Đăng nhập thất bại'
setError(message) setError(message)
throw err throw new Error(message)
} finally { } finally {
setIsLoading(false) setIsLoading(false)
} }

View file

@ -1,13 +1,33 @@
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { Link, useLocation } from 'react-router-dom' import { Link, useLocation } from 'react-router-dom'
import clsx from 'clsx' import clsx from 'clsx'
import { Project } from '@/types'
import { USE_MOCK_DATA } from '@/app/constants'
import { getProjects as getApiProjects } from '@/services/projectService'
import { getProjects, subscribeProjectsStore } from '@/pages/projects/projectData' import { getProjects, subscribeProjectsStore } from '@/pages/projects/projectData'
export const RecentProjects: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => { export const RecentProjects: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => {
const location = useLocation() const location = useLocation()
const [recentProjects, setRecentProjects] = useState(() => getProjects().slice(0, 3)) const [recentProjects, setRecentProjects] = useState<Project[]>(() =>
USE_MOCK_DATA ? getProjects().slice(0, 3) : []
)
useEffect(() => subscribeProjectsStore(() => setRecentProjects(getProjects().slice(0, 3))), []) useEffect(() => {
if (USE_MOCK_DATA) {
return subscribeProjectsStore(() => setRecentProjects(getProjects().slice(0, 3)))
}
let cancelled = false
getApiProjects()
.then((list) => {
if (!cancelled) setRecentProjects(list.slice(0, 3))
})
.catch(() => {
if (!cancelled) setRecentProjects([])
})
return () => {
cancelled = true
}
}, [])
return ( return (
<div> <div>

View file

@ -1,6 +1,9 @@
import React from 'react' import React, { useEffect, useState } from 'react'
import { NavLink, useLocation } from 'react-router-dom' import { NavLink, useLocation } from 'react-router-dom'
import clsx from 'clsx' import clsx from 'clsx'
import { USE_MOCK_DATA } from '@/app/constants'
import { getProjects } from '@/services/projectService'
import { getMembers } from '@/services/userService'
interface NavItem { interface NavItem {
to: string to: string
@ -12,19 +15,35 @@ interface NavItem {
export const SidebarNav: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => { export const SidebarNav: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => {
const location = useLocation() const location = useLocation()
const [realCounts, setRealCounts] = useState<{ projects: number; users: number } | null>(null)
useEffect(() => {
if (USE_MOCK_DATA) return
let cancelled = false
Promise.all([getProjects(), getMembers()])
.then(([projects, members]) => {
if (!cancelled) setRealCounts({ projects: projects.length, users: members.length })
})
.catch(() => {
if (!cancelled) setRealCounts(null)
})
return () => {
cancelled = true
}
}, [])
const navItems: NavItem[] = [ const navItems: NavItem[] = [
{ {
to: '/projects', to: '/projects',
label: 'Dự án', label: 'Dự án',
badge: 3, badge: realCounts?.projects ?? 3,
matchPrefix: '/projects', matchPrefix: '/projects',
icon: '/assets/projects-ui/layout-grid.svg', icon: '/assets/projects-ui/layout-grid.svg',
}, },
{ {
to: '/users', to: '/users',
label: 'Người dùng', label: 'Người dùng',
badge: 8, badge: realCounts?.users ?? 8,
matchPrefix: '/users', matchPrefix: '/users',
icon: '/assets/projects-ui/users.svg', icon: '/assets/projects-ui/users.svg',
}, },

View file

@ -1,6 +1,7 @@
import React, { useEffect } from 'react' import React, { useEffect } from 'react'
import { useParams } from 'react-router-dom' import { useParams } from 'react-router-dom'
import toast from 'react-hot-toast' import toast from 'react-hot-toast'
import { USE_MOCK_DATA } from '@/app/constants'
import { useAnnotatorStore } from './annotatorStore' import { useAnnotatorStore } from './annotatorStore'
import { AnnotatorHeader } from './components/header/AnnotatorHeader' import { AnnotatorHeader } from './components/header/AnnotatorHeader'
import { ImageInfo } from './components/header/ImageInfo' import { ImageInfo } from './components/header/ImageInfo'
@ -16,12 +17,19 @@ export const AnnotatorPage: React.FC = () => {
const { id } = useParams<{ id: string }>() const { id } = useParams<{ id: string }>()
const project = useAnnotatorStore((s) => s.project) const project = useAnnotatorStore((s) => s.project)
const isLoading = useAnnotatorStore((s) => s.isLoading)
const loadError = useAnnotatorStore((s) => s.loadError)
const images = useAnnotatorStore((s) => s.images)
const initProject = useAnnotatorStore((s) => s.initProject) const initProject = useAnnotatorStore((s) => s.initProject)
useEffect(() => { useEffect(() => {
initProject(id ?? 'urban_vehicles_v2') initProject(id ?? 'urban_vehicles_v2')
}, [id, initProject]) }, [id, initProject])
// Real mode: never paint the mock fallback — wait for the API project.
// (Flag only; the gate renders at the single return below so hook order stays stable.)
const showGate = !USE_MOCK_DATA && (isLoading || images.length === 0)
// Global keyboard shortcuts for fast annotation // Global keyboard shortcuts for fast annotation
useEffect(() => { useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => { const handleKeyDown = (e: KeyboardEvent) => {
@ -115,10 +123,12 @@ export const AnnotatorPage: React.FC = () => {
return return
} }
// Left / Right arrow keys: navigate images // Arrow keys: navigate images (Up/Left = previous, Down/Right = next)
if (e.key === 'ArrowLeft') { if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
e.preventDefault()
state.prevImage() state.prevImage()
} else if (e.key === 'ArrowRight') { } else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
e.preventDefault()
state.nextImage() state.nextImage()
} }
} }
@ -127,6 +137,31 @@ export const AnnotatorPage: React.FC = () => {
return () => window.removeEventListener('keydown', handleKeyDown) return () => window.removeEventListener('keydown', handleKeyDown)
}, []) }, [])
if (showGate) {
return (
<div className="flex min-h-[480px] flex-col items-center justify-center gap-3">
{loadError ? (
<>
<p className="text-sm font-medium text-slate-700">Không tải được dự án</p>
<p className="max-w-md text-center text-xs text-slate-500">{loadError}</p>
<button
type="button"
onClick={() => initProject(id ?? '')}
className="mt-1 rounded-lg bg-[#C95C3C] px-4 py-2 text-xs font-semibold text-white"
>
Thử lại
</button>
</>
) : (
<>
<div className="h-8 w-8 animate-spin rounded-full border-2 border-slate-200 border-t-[#C95C3C]" />
<span className="text-xs font-medium text-slate-500">Đang tải dự án...</span>
</>
)}
</div>
)
}
return ( return (
<div className="min-h-full space-y-4 p-6"> <div className="min-h-full space-y-4 p-6">
{/* Top Project Title & Action Buttons */} {/* Top Project Title & Action Buttons */}

View file

@ -1,3 +1,4 @@
import toast from 'react-hot-toast'
import { create } from 'zustand' import { create } from 'zustand'
import { import {
AnnotationShape, AnnotationShape,
@ -10,6 +11,10 @@ import {
Project, Project,
TaskType, TaskType,
} from '@/types' } from '@/types'
import { USE_MOCK_DATA } from '@/app/constants'
import { getAnnotation, saveAnnotation } from '@/services/annotationService'
import { getProjectImages, updateImageStatus as persistImageStatus } from '@/services/imageService'
import { getProjectById } from '@/services/projectService'
import { getAnnotatorImageUrl } from './annotatorTheme' import { getAnnotatorImageUrl } from './annotatorTheme'
import { normalizeBBox } from '@/utils/canvas' import { normalizeBBox } from '@/utils/canvas'
@ -458,6 +463,9 @@ interface HistorySnapshot {
export interface AnnotatorState { export interface AnnotatorState {
project: Project project: Project
images: ImageItem[] images: ImageItem[]
isLoading: boolean
loadError: string | null
isSaving: boolean
currentImageIndex: number currentImageIndex: number
displayImageCounter: number displayImageCounter: number
activeTool: AnnotationTool activeTool: AnnotationTool
@ -473,6 +481,7 @@ export interface AnnotatorState {
vertexEditEnabled: boolean vertexEditEnabled: boolean
activeGroupId: number activeGroupId: number
zoom: number zoom: number
pan: { x: number; y: number }
lastSavedAt: string lastSavedAt: string
draftPolygonPoints: Point2D[] draftPolygonPoints: Point2D[]
historyPast: HistorySnapshot[] historyPast: HistorySnapshot[]
@ -512,10 +521,11 @@ export interface AnnotatorState {
zoomIn: () => void zoomIn: () => void
zoomOut: () => void zoomOut: () => void
resetZoom: () => void resetZoom: () => void
setPan: (pan: { x: number; y: number }) => void
undo: () => void undo: () => void
redo: () => void redo: () => void
saveCurrentAnnotation: () => void saveCurrentAnnotation: () => void
saveAndNext: () => void scheduleAutosave: () => void
updateImageStatus: (status: ImageAnnotationStatus) => void updateImageStatus: (status: ImageAnnotationStatus) => void
} }
@ -571,6 +581,8 @@ function createInitialAnnotationState(project: Project) {
return { return {
project, project,
images, images,
isLoading: false,
loadError: null,
currentImageIndex: 0, currentImageIndex: 0,
displayImageCounter, displayImageCounter,
activeTool: defaultTool, activeTool: defaultTool,
@ -586,6 +598,8 @@ function createInitialAnnotationState(project: Project) {
vertexEditEnabled: true, vertexEditEnabled: true,
activeGroupId: 2, activeGroupId: 2,
zoom: 75, zoom: 75,
pan: { x: 0, y: 0 },
isSaving: false,
lastSavedAt: '09:42', lastSavedAt: '09:42',
draftPolygonPoints: [] as Point2D[], draftPolygonPoints: [] as Point2D[],
historyPast: [] as HistorySnapshot[], historyPast: [] as HistorySnapshot[],
@ -593,18 +607,143 @@ function createInitialAnnotationState(project: Project) {
} }
} }
async function ensureAnnotationLoaded(projectId: string, imageId: string): Promise<void> {
const state = useAnnotatorStore.getState()
if (USE_MOCK_DATA || imageId in state.shapesByImageId) return
try {
const ann = await getAnnotation(projectId, imageId)
useAnnotatorStore.setState((s) => ({
shapesByImageId: { ...s.shapesByImageId, [imageId]: ann.shapes },
classificationByImageId: {
...s.classificationByImageId,
[imageId]: ann.classificationLabelId ?? s.project.classes[0]?.id ?? '',
},
flagsByImageId: {
...s.flagsByImageId,
[imageId]: {
blurryOrUncertain: Boolean(ann.flags?.blurryOrUncertain),
needsRecheck: Boolean(ann.flags?.needsRecheck),
},
},
}))
} catch {
// Keep an empty canvas; the save path will surface errors.
useAnnotatorStore.setState((s) => ({
shapesByImageId: { ...s.shapesByImageId, [imageId]: [] },
}))
}
}
function buildRealState(
project: Project,
images: ImageItem[]
): ReturnType<typeof createInitialAnnotationState> {
const defaultTool: AnnotationTool =
project.taskType === 'classification'
? 'select'
: project.taskType === 'object_detection'
? 'bbox'
: 'polygon'
const fallbackClass = project.classes[0]?.id ?? ''
const classificationByImageId: Record<string, string> = {}
const flagsByImageId: Record<string, { blurryOrUncertain: boolean; needsRecheck: boolean }> = {}
const statusByImageId: Record<string, ImageAnnotationStatus> = {}
for (const img of images) {
classificationByImageId[img.id] = img.classificationLabelId ?? fallbackClass
flagsByImageId[img.id] = {
blurryOrUncertain: Boolean(img.flags?.blurryOrUncertain),
needsRecheck: Boolean(img.flags?.needsRecheck),
}
statusByImageId[img.id] = img.status
}
return {
project,
images,
isLoading: false,
loadError: null,
currentImageIndex: 0,
displayImageCounter: project.taskType === 'classification' ? 124 : 321,
activeTool: defaultTool,
selectedClassId: fallbackClass,
selectedShapeId: null,
shapesByImageId: {},
classificationByImageId,
flagsByImageId,
statusByImageId,
showBoxes: true,
showMasks: true,
maskOpacity: 35,
vertexEditEnabled: true,
activeGroupId: 2,
zoom: 75,
pan: { x: 0, y: 0 },
isSaving: false,
lastSavedAt: '',
draftPolygonPoints: [],
historyPast: [],
historyFuture: [],
}
}
const EMPTY_PROJECT: Project = {
id: '',
name: '',
slug: '',
description: '',
taskType: 'object_detection',
status: 'annotating',
thumbnailUrl: '',
updatedAt: '',
classes: [],
stats: {
totalImages: 0,
unassigned: 0,
inProgress: 0,
pendingReview: 0,
completed: 0,
totalObjects: 0,
},
members: [],
}
// Autosave: mutating actions reschedule; the timer fires saveCurrentAnnotation
// 1.2s after the last edit. Navigation flushes pending saves first.
let autosaveTimer: ReturnType<typeof setTimeout> | null = null
export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
...createInitialAnnotationState(ANNOTATOR_PROJECTS_BY_ID.urban_vehicles_v2!), ...(USE_MOCK_DATA
? createInitialAnnotationState(ANNOTATOR_PROJECTS_BY_ID.urban_vehicles_v2!)
: { ...buildRealState(EMPTY_PROJECT, []), isLoading: true }),
initProject: (projectId) => { initProject: (projectId) => {
if (USE_MOCK_DATA) {
const selectedProject = const selectedProject =
ANNOTATOR_PROJECTS_BY_ID[projectId] ?? ANNOTATOR_PROJECTS_BY_ID.urban_vehicles_v2! ANNOTATOR_PROJECTS_BY_ID[projectId] ?? ANNOTATOR_PROJECTS_BY_ID.urban_vehicles_v2!
set(createInitialAnnotationState(selectedProject)) set(createInitialAnnotationState(selectedProject))
return
}
set({ isLoading: true, loadError: null })
void (async () => {
try {
const project = await getProjectById(projectId)
const images = await getProjectImages(project.id)
set(buildRealState(project, images))
if (images[0]) {
await ensureAnnotationLoaded(project.id, images[0].id)
}
} catch (err) {
const message = err instanceof Error ? err.message : 'Không tải được dự án'
set({ isLoading: false, loadError: message })
toast.error(message)
}
})()
}, },
selectImageByIndex: (index) => { selectImageByIndex: (index) => {
const { images, project } = get() const { images, project } = get()
if (index < 0 || index >= images.length) return if (index < 0 || index >= images.length) return
// Flush pending edits of the current image before leaving it.
get().saveCurrentAnnotation()
const baseNum = project.taskType === 'classification' ? 124 : 321 const baseNum = project.taskType === 'classification' ? 124 : 321
const img = images[index] const img = images[index]
const shapes = img ? get().shapesByImageId[img.id] ?? [] : [] const shapes = img ? get().shapesByImageId[img.id] ?? [] : []
@ -615,7 +754,25 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
draftPolygonPoints: [], draftPolygonPoints: [],
historyPast: [], historyPast: [],
historyFuture: [], historyFuture: [],
pan: { x: 0, y: 0 },
}) })
if (img && !USE_MOCK_DATA) {
// Preload neighbour full images into the browser cache so arrow-key
// navigation never waits on R2. Same presigned URL within the session.
for (const neighbour of [images[index - 1], images[index + 1]]) {
if (neighbour) {
const pre = new Image()
pre.src = neighbour.url
}
}
void ensureAnnotationLoaded(project.id, img.id).then(() => {
const fresh = useAnnotatorStore.getState()
const loaded = fresh.shapesByImageId[img.id] ?? []
if (fresh.images[fresh.currentImageIndex]?.id === img.id) {
useAnnotatorStore.setState({ selectedShapeId: loaded[0]?.id ?? null })
}
})
}
}, },
nextImage: () => { nextImage: () => {
@ -679,6 +836,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
], ],
historyFuture: [], historyFuture: [],
}) })
get().scheduleAutosave();
}, },
toggleFlag: (flag) => { toggleFlag: (flag) => {
@ -698,6 +856,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
}, },
}, },
}) })
get().scheduleAutosave();
}, },
setShowBoxes: (show) => set({ showBoxes: show }), setShowBoxes: (show) => set({ showBoxes: show }),
@ -735,6 +894,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
[currentImage.id]: updated, [currentImage.id]: updated,
}, },
}) })
get().scheduleAutosave();
}, },
updateSelectedShapeGroup: (groupId) => { updateSelectedShapeGroup: (groupId) => {
@ -751,6 +911,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
[currentImage.id]: updated, [currentImage.id]: updated,
}, },
}) })
get().scheduleAutosave();
}, },
addBoundingBox: (bbox) => { addBoundingBox: (bbox) => {
@ -792,6 +953,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
], ],
historyFuture: [], historyFuture: [],
}) })
get().scheduleAutosave();
}, },
updateBoundingBox: (shapeId, bbox) => { updateBoundingBox: (shapeId, bbox) => {
@ -868,6 +1030,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
], ],
historyFuture: [], historyFuture: [],
}) })
get().scheduleAutosave();
}, },
cancelDraftPolygon: () => set({ draftPolygonPoints: [] }), cancelDraftPolygon: () => set({ draftPolygonPoints: [] }),
@ -917,6 +1080,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
], ],
historyFuture: [], historyFuture: [],
}) })
get().scheduleAutosave();
}, },
deletePolygonVertex: (shapeId, vertexIndex) => { deletePolygonVertex: (shapeId, vertexIndex) => {
@ -940,6 +1104,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
[currentImage.id]: updated, [currentImage.id]: updated,
}, },
}) })
get().scheduleAutosave();
}, },
addPointShape: (pt) => { addPointShape: (pt) => {
@ -977,6 +1142,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
], ],
historyFuture: [], historyFuture: [],
}) })
get().scheduleAutosave();
}, },
updatePointShape: (shapeId, pt) => { updatePointShape: (shapeId, pt) => {
@ -1009,6 +1175,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
[currentImage.id]: updated, [currentImage.id]: updated,
}, },
}) })
get().scheduleAutosave();
}, },
toggleAllShapesVisibility: () => { toggleAllShapesVisibility: () => {
@ -1024,6 +1191,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
[currentImage.id]: updated, [currentImage.id]: updated,
}, },
}) })
get().scheduleAutosave();
}, },
deleteShape: (shapeId) => { deleteShape: (shapeId) => {
@ -1050,12 +1218,14 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
], ],
historyFuture: [], historyFuture: [],
}) })
get().scheduleAutosave();
}, },
setZoom: (zoom) => set({ zoom: Math.max(25, Math.min(200, zoom)) }), setZoom: (zoom) => set({ zoom: Math.max(25, Math.min(200, zoom)) }),
zoomIn: () => set((s) => ({ zoom: Math.min(200, s.zoom + 15) })), zoomIn: () => set((s) => ({ zoom: Math.min(200, s.zoom + 15) })),
zoomOut: () => set((s) => ({ zoom: Math.max(40, s.zoom - 15) })), zoomOut: () => set((s) => ({ zoom: Math.max(40, s.zoom - 15) })),
resetZoom: () => set({ zoom: 75 }), resetZoom: () => set({ zoom: 75, pan: { x: 0, y: 0 } }),
setPan: (pan) => set({ pan }),
undo: () => { undo: () => {
const state = get() const state = get()
@ -1078,6 +1248,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
historyPast: state.historyPast.slice(0, -1), historyPast: state.historyPast.slice(0, -1),
historyFuture: [currentSnapshot, ...state.historyFuture], historyFuture: [currentSnapshot, ...state.historyFuture],
}) })
get().scheduleAutosave();
}, },
redo: () => { redo: () => {
@ -1101,15 +1272,48 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
historyPast: [...state.historyPast, currentSnapshot], historyPast: [...state.historyPast, currentSnapshot],
historyFuture: state.historyFuture.slice(1), historyFuture: state.historyFuture.slice(1),
}) })
get().scheduleAutosave();
}, },
saveCurrentAnnotation: () => { saveCurrentAnnotation: () => {
const state = get()
const currentImage = state.images[state.currentImageIndex]
if (!currentImage) return
if (USE_MOCK_DATA) {
set({ lastSavedAt: getCurrentTimeHHMM() }) set({ lastSavedAt: getCurrentTimeHHMM() })
return
}
if (autosaveTimer) {
clearTimeout(autosaveTimer)
autosaveTimer = null
}
set({ isSaving: true })
void (async () => {
try {
await saveAnnotation(state.project.id, currentImage.id, {
classificationLabelId: state.classificationByImageId[currentImage.id],
flags: state.flagsByImageId[currentImage.id] ?? {
blurryOrUncertain: false,
needsRecheck: false,
},
shapes: state.shapesByImageId[currentImage.id] ?? [],
})
useAnnotatorStore.setState({ lastSavedAt: getCurrentTimeHHMM() })
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Lưu nhãn thất bại')
} finally {
useAnnotatorStore.setState({ isSaving: false })
}
})()
}, },
saveAndNext: () => { scheduleAutosave: () => {
set({ lastSavedAt: getCurrentTimeHHMM() }) if (USE_MOCK_DATA) return
get().nextImage() if (autosaveTimer) clearTimeout(autosaveTimer)
autosaveTimer = setTimeout(() => {
autosaveTimer = null
useAnnotatorStore.getState().saveCurrentAnnotation()
}, 1200)
}, },
updateImageStatus: (status) => { updateImageStatus: (status) => {
@ -1123,5 +1327,10 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
}, },
lastSavedAt: getCurrentTimeHHMM(), lastSavedAt: getCurrentTimeHHMM(),
}) })
if (!USE_MOCK_DATA) {
void persistImageStatus(state.project.id, currentImage.id, status).catch((err: unknown) => {
toast.error(err instanceof Error ? err.message : 'Đổi trạng thái thất bại')
})
}
}, },
})) }))

View file

@ -1,4 +1,7 @@
import React, { useRef, useState } from 'react' import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { Layer, Stage } from 'react-konva'
import type { KonvaEventObject } from 'konva/lib/Node'
import type Konva from 'konva'
import { BoundingBox, Point2D } from '@/types' import { BoundingBox, Point2D } from '@/types'
import { normalizeBBox } from '@/utils/canvas' import { normalizeBBox } from '@/utils/canvas'
import { useAnnotatorStore } from '../../annotatorStore' import { useAnnotatorStore } from '../../annotatorStore'
@ -20,9 +23,30 @@ type DragInteraction =
initialBox: BoundingBox initialBox: BoundingBox
} }
| { type: 'drag-vertex'; shapeId: string; vertexIndex: number } | { type: 'drag-vertex'; shapeId: string; vertexIndex: number }
| { type: 'pan-stage'; last: Point2D }
function clampPan(
pan: { x: number; y: number },
scale: number,
imgW: number,
imgH: number,
stageW: number,
stageH: number
): { x: number; y: number } {
const minX = Math.min(0, stageW - imgW * scale)
const maxX = Math.max(0, stageW - imgW * scale)
const minY = Math.min(0, stageH - imgH * scale)
const maxY = Math.max(0, stageH - imgH * scale)
return {
x: Math.max(minX, Math.min(maxX, pan.x)),
y: Math.max(minY, Math.min(maxY, pan.y)),
}
}
export const AnnotationCanvas: React.FC = () => { export const AnnotationCanvas: React.FC = () => {
const svgRef = useRef<SVGSVGElement | null>(null) const stageRef = useRef<Konva.Stage | null>(null)
const containerRef = useRef<HTMLDivElement | null>(null)
const [stageW, setStageW] = useState(0)
const project = useAnnotatorStore((s) => s.project) const project = useAnnotatorStore((s) => s.project)
const currentImage = useAnnotatorStore((s) => s.images[s.currentImageIndex]) const currentImage = useAnnotatorStore((s) => s.images[s.currentImageIndex])
@ -35,6 +59,7 @@ export const AnnotationCanvas: React.FC = () => {
const maskOpacity = useAnnotatorStore((s) => s.maskOpacity) const maskOpacity = useAnnotatorStore((s) => s.maskOpacity)
const vertexEditEnabled = useAnnotatorStore((s) => s.vertexEditEnabled) const vertexEditEnabled = useAnnotatorStore((s) => s.vertexEditEnabled)
const zoom = useAnnotatorStore((s) => s.zoom) const zoom = useAnnotatorStore((s) => s.zoom)
const pan = useAnnotatorStore((s) => s.pan)
const draftPolygonPoints = useAnnotatorStore((s) => s.draftPolygonPoints) const draftPolygonPoints = useAnnotatorStore((s) => s.draftPolygonPoints)
const setSelectedShapeId = useAnnotatorStore((s) => s.setSelectedShapeId) const setSelectedShapeId = useAnnotatorStore((s) => s.setSelectedShapeId)
@ -48,31 +73,132 @@ export const AnnotationCanvas: React.FC = () => {
const [interaction, setInteraction] = useState<DragInteraction | null>(null) const [interaction, setInteraction] = useState<DragInteraction | null>(null)
const [cursorPoint, setCursorPoint] = useState<Point2D | null>(null) const [cursorPoint, setCursorPoint] = useState<Point2D | null>(null)
const [spaceDown, setSpaceDown] = useState(false)
// Track container width; stage height follows image aspect. A ResizeObserver
// (not a one-shot measure) is required: on hard reload the container can
// still be 0px when effects first run, before stylesheets/fonts settle.
// Re-run when content appears: on first mount there is no image yet, the
// component renders null and the ref is unattached — without this dep the
// observer would never be installed after the image loads.
const hasImage = currentImage !== undefined
useLayoutEffect(() => {
const el = containerRef.current
if (!el) return
const measure = () => {
const w = el.clientWidth
setStageW((prev) => (prev === w ? prev : w))
}
measure()
const ro = new ResizeObserver(measure)
ro.observe(el)
window.addEventListener('resize', measure)
return () => {
ro.disconnect()
window.removeEventListener('resize', measure)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hasImage])
// Space-held panning (ignored while typing).
useEffect(() => {
const isTypingTarget = (t: EventTarget | null) =>
t instanceof HTMLElement &&
(t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.tagName === 'SELECT')
const down = (e: KeyboardEvent) => {
if (e.code === 'Space' && !isTypingTarget(e.target)) {
e.preventDefault()
setSpaceDown(true)
}
}
const up = (e: KeyboardEvent) => {
if (e.code === 'Space') setSpaceDown(false)
}
const blur = () => setSpaceDown(false)
window.addEventListener('keydown', down)
window.addEventListener('keyup', up)
window.addEventListener('blur', blur)
return () => {
window.removeEventListener('keydown', down)
window.removeEventListener('keyup', up)
window.removeEventListener('blur', blur)
}
}, [])
if (!currentImage) return null if (!currentImage) return null
const stageH = stageW > 0 ? Math.round((stageW * currentImage.height) / currentImage.width) : 0
// Base fit: whole image visible at zoom=75; zoom % scales around it.
const fitScale = stageW > 0 ? stageW / currentImage.width : 1
const scale = fitScale * (zoom / 75)
// Full display scale from a live Stage (fit * zoom), for event handlers.
const displayScaleOf = (stage: Konva.Stage | null): number => {
if (!stage || stage.width() === 0) return fitScale
return (stage.width() / currentImage.width) * (useAnnotatorStore.getState().zoom / 75)
}
const shapes = shapesByImageId[currentImage.id] ?? [] const shapes = shapesByImageId[currentImage.id] ?? []
const selectedShape = shapes.find((s) => s.id === selectedShapeId) const selectedShape = shapes.find((s) => s.id === selectedShapeId)
const activeClass = const activeClass =
project.classes.find((c) => c.id === selectedClassId) ?? project.classes[0]! project.classes.find((c) => c.id === selectedClassId) ?? project.classes[0]!
// Convert client mouse position to 1920x1080 SVG coordinate space // Exact pointer -> image coords through the live Stage transform.
const getSvgPoint = (e: React.MouseEvent): Point2D => { const getImagePoint = (e: KonvaEventObject<MouseEvent>): Point2D => {
const svg = svgRef.current const stage = e.target.getStage() ?? stageRef.current
if (!svg) return { x: 0, y: 0 } if (!stage) return { x: 0, y: 0 }
const rect = svg.getBoundingClientRect() const pos = stage.getPointerPosition()
if (rect.width === 0 || rect.height === 0) return { x: 0, y: 0 } if (!pos) return { x: 0, y: 0 }
const scaleX = currentImage.width / rect.width const st = useAnnotatorStore.getState()
const scaleY = currentImage.height / rect.height const s = displayScaleOf(stage)
return { return {
x: Math.max(0, Math.min(currentImage.width, (e.clientX - rect.left) * scaleX)), x: Math.max(0, Math.min(currentImage.width, (pos.x - st.pan.x) / s)),
y: Math.max(0, Math.min(currentImage.height, (e.clientY - rect.top) * scaleY)), y: Math.max(0, Math.min(currentImage.height, (pos.y - st.pan.y) / s)),
} }
} }
const handleCanvasMouseDown = (e: React.MouseEvent) => { const handleWheel = (e: KonvaEventObject<WheelEvent>) => {
if (e.button !== 0) return e.evt.preventDefault()
const pt = getSvgPoint(e) const stage = stageRef.current
if (!stage) return
const st = useAnnotatorStore.getState()
const fit = stage.width() / currentImage.width
const oldScale = fit * (st.zoom / 75)
const nextZoom = Math.round(
Math.max(25, Math.min(200, st.zoom * (e.evt.deltaY < 0 ? 1.15 : 1 / 1.15)))
)
if (nextZoom === st.zoom) return
const newScale = fit * (nextZoom / 75)
const pointer = stage.getPointerPosition()
if (!pointer) return
const mouseTo = {
x: (pointer.x - st.pan.x) / oldScale,
y: (pointer.y - st.pan.y) / oldScale,
}
const nextPan = clampPan(
{
x: pointer.x - mouseTo.x * newScale,
y: pointer.y - mouseTo.y * newScale,
},
newScale,
currentImage.width,
currentImage.height,
stage.width(),
stage.height()
)
st.setZoom(nextZoom)
st.setPan(nextPan)
}
const handleMouseDown = (e: KonvaEventObject<MouseEvent>) => {
const stage = e.target.getStage()
// Middle-button drag or Space+drag pans the viewport.
if (e.evt.button === 1 || (spaceDown && e.evt.button === 0)) {
setInteraction({ type: 'pan-stage', last: { x: e.evt.clientX, y: e.evt.clientY } })
return
}
if (e.evt.button !== 0) return
const pt = getImagePoint(e)
if (project.taskType === 'object_detection' && activeTool === 'bbox') { if (project.taskType === 'object_detection' && activeTool === 'bbox') {
setInteraction({ type: 'draw-bbox', start: pt, current: pt }) setInteraction({ type: 'draw-bbox', start: pt, current: pt })
@ -89,18 +215,39 @@ export const AnnotationCanvas: React.FC = () => {
return return
} }
if (activeTool === 'select') { if (activeTool === 'select' && stage && e.target === stage) {
setSelectedShapeId(null) setSelectedShapeId(null)
} }
} }
const handleCanvasMouseMove = (e: React.MouseEvent) => { const handleMouseMove = (e: KonvaEventObject<MouseEvent>) => {
const pt = getSvgPoint(e)
if (draftPolygonPoints.length > 0) { if (draftPolygonPoints.length > 0) {
setCursorPoint(pt) setCursorPoint(getImagePoint(e))
} }
if (!interaction) return if (!interaction) return
const st = useAnnotatorStore.getState()
if (interaction.type === 'pan-stage') {
const dx = e.evt.clientX - interaction.last.x
const dy = e.evt.clientY - interaction.last.y
const stage = stageRef.current
const s = displayScaleOf(stage)
st.setPan(
clampPan(
{ x: st.pan.x + dx, y: st.pan.y + dy },
s,
currentImage.width,
currentImage.height,
stage?.width() ?? 0,
stage?.height() ?? 0
)
)
setInteraction({ type: 'pan-stage', last: { x: e.evt.clientX, y: e.evt.clientY } })
return
}
const pt = getImagePoint(e)
if (interaction.type === 'draw-bbox') { if (interaction.type === 'draw-bbox') {
setInteraction({ ...interaction, current: pt }) setInteraction({ ...interaction, current: pt })
@ -163,7 +310,7 @@ export const AnnotationCanvas: React.FC = () => {
} }
} }
const handleCanvasMouseUp = () => { const handleMouseUp = () => {
if (!interaction) return if (!interaction) return
if (interaction.type === 'draw-bbox') { if (interaction.type === 'draw-bbox') {
const rawBox: BoundingBox = { const rawBox: BoundingBox = {
@ -173,6 +320,9 @@ export const AnnotationCanvas: React.FC = () => {
height: interaction.current.y - interaction.start.y, height: interaction.current.y - interaction.start.y,
} }
addBoundingBox(rawBox) addBoundingBox(rawBox)
} else if (interaction.type !== 'pan-stage') {
// Continuous ops (move/resize/vertex) already wrote state per mousemove.
useAnnotatorStore.getState().scheduleAutosave()
} }
setInteraction(null) setInteraction(null)
} }
@ -197,34 +347,43 @@ export const AnnotationCanvas: React.FC = () => {
) )
: null : null
const scaleFactor = zoom / 75
return ( return (
<div className="px-4 py-3"> <div className="px-4 py-3">
<div className="relative overflow-hidden rounded-xl border border-slate-200/80 bg-slate-900">
<div <div
className="w-full origin-center transition-transform duration-150" ref={containerRef}
style={{ className="relative overflow-hidden rounded-xl border border-slate-200/80 bg-slate-900"
transform: scaleFactor !== 1 ? `scale(${scaleFactor})` : undefined,
}}
> >
<svg {stageW > 0 && stageH > 0 && (
ref={svgRef} <Stage
viewBox={`0 0 ${currentImage.width} ${currentImage.height}`} ref={(node) => {
className="block aspect-[1.925] w-full select-none" stageRef.current = node
}}
width={stageW}
height={stageH}
scaleX={scale}
scaleY={scale}
x={pan.x}
y={pan.y}
onMouseDown={handleMouseDown}
onMouseMove={handleMouseMove}
onMouseUp={handleMouseUp}
onMouseLeave={handleMouseUp}
onWheel={handleWheel}
onDblClick={handleDoubleClick}
style={{ style={{
cursor: cursor: spaceDown
activeTool === 'bbox' || activeTool === 'polygon' || activeTool === 'point' ? 'grab'
: activeTool === 'bbox' ||
activeTool === 'polygon' ||
activeTool === 'point'
? 'crosshair' ? 'crosshair'
: 'default', : 'default',
}} }}
onMouseDown={handleCanvasMouseDown}
onMouseMove={handleCanvasMouseMove}
onMouseUp={handleCanvasMouseUp}
onDoubleClick={handleDoubleClick}
> >
<Layer>
<ImageViewer <ImageViewer
url={currentImage.url} url={currentImage.url}
thumbUrl={currentImage.thumbnailSmallUrl ?? currentImage.thumbnailUrl}
width={currentImage.width} width={currentImage.width}
height={currentImage.height} height={currentImage.height}
/> />
@ -238,22 +397,22 @@ export const AnnotationCanvas: React.FC = () => {
activeClassColor={activeClass.color} activeClassColor={activeClass.color}
activeClassName={activeClass.name} activeClassName={activeClass.name}
onSelectShape={setSelectedShapeId} onSelectShape={setSelectedShapeId}
onStartMoveBox={(e, shape) => { onStartMoveBox={(pt, shape) => {
if (!shape.bbox) return if (!shape.bbox) return
setInteraction({ setInteraction({
type: 'move-bbox', type: 'move-bbox',
shapeId: shape.id, shapeId: shape.id,
startMouse: getSvgPoint(e), startMouse: pt,
initialBox: { ...shape.bbox }, initialBox: { ...shape.bbox },
}) })
}} }}
onStartResizeBox={(e, shape, corner) => { onStartResizeBox={(pt, shape, corner) => {
if (!shape.bbox) return if (!shape.bbox) return
setInteraction({ setInteraction({
type: 'resize-bbox', type: 'resize-bbox',
shapeId: shape.id, shapeId: shape.id,
corner, corner,
startMouse: getSvgPoint(e), startMouse: pt,
initialBox: { ...shape.bbox }, initialBox: { ...shape.bbox },
}) })
}} }}
@ -271,15 +430,23 @@ export const AnnotationCanvas: React.FC = () => {
cursorPoint={cursorPoint} cursorPoint={cursorPoint}
activeClassColor={activeClass.color} activeClassColor={activeClass.color}
onSelectShape={setSelectedShapeId} onSelectShape={setSelectedShapeId}
onStartDragVertex={(_e, shapeId, vertexIndex) => { onStartDragVertex={(shapeId, vertexIndex) => {
setInteraction({ setInteraction({
type: 'drag-vertex', type: 'drag-vertex',
shapeId, shapeId,
vertexIndex, vertexIndex,
}) })
}} }}
onInsertVertexOnEdge={(shapeId, afterIndex, pt) => { onInsertVertexOnEdge={(shapeId, afterIndex) => {
insertPolygonVertex(shapeId, afterIndex, pt) const target = shapes.find((s) => s.id === shapeId)
const pts = target?.points
if (!pts || pts.length === 0) return
const a = pts[afterIndex % pts.length]!
const b = pts[(afterIndex + 1) % pts.length]!
insertPolygonVertex(shapeId, afterIndex, {
x: (a.x + b.x) / 2,
y: (a.y + b.y) / 2,
})
}} }}
onCloseDraftPolygon={closeDraftPolygon} onCloseDraftPolygon={closeDraftPolygon}
/> />
@ -292,8 +459,9 @@ export const AnnotationCanvas: React.FC = () => {
/> />
<SelectTool selectedShape={selectedShape} /> <SelectTool selectedShape={selectedShape} />
</svg> </Layer>
</div> </Stage>
)}
{/* Bottom-left dark translucent pill overlay */} {/* Bottom-left dark translucent pill overlay */}
<CanvasOverlay /> <CanvasOverlay />

View file

@ -1,5 +1,6 @@
import React from 'react' import React from 'react'
import { AnnotationShape, BoundingBox } from '@/types' import { Group, Rect, Text } from 'react-konva'
import { AnnotationShape, BoundingBox, Point2D } from '@/types'
export type ResizeHandleCorner = 'nw' | 'ne' | 'sw' | 'se' export type ResizeHandleCorner = 'nw' | 'ne' | 'sw' | 'se'
@ -11,9 +12,9 @@ export interface BoundingBoxToolProps {
activeClassColor: string activeClassColor: string
activeClassName: string activeClassName: string
onSelectShape: (shapeId: string) => void onSelectShape: (shapeId: string) => void
onStartMoveBox: (e: React.MouseEvent, shape: AnnotationShape) => void onStartMoveBox: (pt: Point2D, shape: AnnotationShape) => void
onStartResizeBox: ( onStartResizeBox: (
e: React.MouseEvent, pt: Point2D,
shape: AnnotationShape, shape: AnnotationShape,
corner: ResizeHandleCorner corner: ResizeHandleCorner
) => void ) => void
@ -34,8 +35,21 @@ export const BoundingBoxTool: React.FC<BoundingBoxToolProps> = ({
const bboxShapes = shapes.filter((s) => s.type === 'bbox' && s.visible && s.bbox) const bboxShapes = shapes.filter((s) => s.type === 'bbox' && s.visible && s.bbox)
// Image-space point of a Konva pointer event, via the live Stage transform.
const toImagePoint = (target: { getStage: () => any }): Point2D | null => {
const stage = target.getStage()
if (!stage) return null
const pos = stage.getPointerPosition()
if (!pos) return null
const scale = stage.scaleX() || 1
return {
x: (pos.x - stage.x()) / scale,
y: (pos.y - stage.y()) / scale,
}
}
return ( return (
<g> <Group>
{bboxShapes.map((shape) => { {bboxShapes.map((shape) => {
const box = shape.bbox! const box = shape.bbox!
const isSelected = shape.id === selectedShapeId const isSelected = shape.id === selectedShapeId
@ -51,113 +65,137 @@ export const BoundingBoxTool: React.FC<BoundingBoxToolProps> = ({
] ]
return ( return (
<g key={shape.id}> <Group key={shape.id}>
{/* Main Bounding Box Rectangle */} {/* Light interior tint (separate node: border below stays crisp) */}
<rect <Rect
x={box.x} x={box.x}
y={box.y} y={box.y}
width={box.width} width={box.width}
height={box.height} height={box.height}
fill={shape.color} fill={shape.color}
fillOpacity={isSelected ? 0.14 : 0.05} opacity={isSelected ? 0.12 : 0.05}
onMouseDown={(e) => {
e.cancelBubble = true
onSelectShape(shape.id)
const pt = toImagePoint(e.target)
if (pt) onStartMoveBox(pt, shape)
}}
style={{ cursor: 'move' }}
/>
{/* Main Bounding Box Rectangle: border only, owns all mouse input */}
<Rect
x={box.x}
y={box.y}
width={box.width}
height={box.height}
fillEnabled={false}
stroke={shape.color} stroke={shape.color}
strokeWidth={isSelected ? 4 : 3} strokeWidth={isSelected ? 4 : 3}
className="cursor-move"
onMouseDown={(e) => { onMouseDown={(e) => {
e.stopPropagation() e.cancelBubble = true
onSelectShape(shape.id) onSelectShape(shape.id)
onStartMoveBox(e, shape) const pt = toImagePoint(e.target)
if (pt) onStartMoveBox(pt, shape)
}} }}
style={{ cursor: 'move' }}
/> />
{/* Top-left Label Pill matching wireframe */} {/* Top-left Label Pill matching wireframe */}
<g <Group
className="cursor-pointer"
onMouseDown={(e) => { onMouseDown={(e) => {
e.stopPropagation() e.cancelBubble = true
onSelectShape(shape.id) onSelectShape(shape.id)
}} }}
style={{ cursor: 'pointer' }}
> >
<rect <Rect
x={box.x} x={box.x}
y={pillY} y={pillY}
width={pillWidth} width={pillWidth}
height={32} height={32}
rx={8} cornerRadius={8}
fill={shape.color} fill={shape.color}
fillOpacity={0.92} fillOpacity={0.92}
/> />
<text <Text
x={box.x + pillWidth / 2} x={box.x}
y={pillY + 21} y={pillY + 6}
width={pillWidth}
height={32}
align="center"
fill={isLightTag ? '#0F172A' : '#FFFFFF'} fill={isLightTag ? '#0F172A' : '#FFFFFF'}
fontSize={17} fontSize={17}
fontWeight="bold" fontStyle="bold"
textAnchor="middle" text={shape.labelName}
className="select-none" />
> </Group>
{shape.labelName}
</text>
</g>
{/* Corner Resize Handles when Selected */} {/* Corner Resize Handles when Selected */}
{isSelected && {isSelected &&
corners.map((corner) => ( corners.map((corner) => (
<rect <Rect
key={corner.id} key={corner.id}
x={corner.cx - 8} x={corner.cx - 8}
y={corner.cy - 8} y={corner.cy - 8}
width={16} width={16}
height={16} height={16}
rx={3} cornerRadius={3}
fill="#FFFFFF" fill="#FFFFFF"
stroke={shape.color} stroke={shape.color}
strokeWidth={3.5} strokeWidth={3.5}
style={{ cursor: corner.cursor }}
onMouseDown={(e) => { onMouseDown={(e) => {
e.stopPropagation() e.cancelBubble = true
onStartResizeBox(e, shape, corner.id) const pt = toImagePoint(e.target)
if (pt) onStartResizeBox(pt, shape, corner.id)
}} }}
style={{ cursor: corner.cursor }}
/> />
))} ))}
</g> </Group>
) )
})} })}
{/* Active Draft Bounding Box while user drags */} {/* Active Draft Bounding Box while user drags */}
{draftBox && draftBox.width > 4 && draftBox.height > 4 && ( {draftBox && draftBox.width > 4 && draftBox.height > 4 && (
<g className="pointer-events-none"> <Group listening={false}>
<rect <Rect
x={draftBox.x} x={draftBox.x}
y={draftBox.y} y={draftBox.y}
width={draftBox.width} width={draftBox.width}
height={draftBox.height} height={draftBox.height}
fill={activeClassColor} fill={activeClassColor}
fillOpacity={0.18} opacity={0.18}
/>
<Rect
x={draftBox.x}
y={draftBox.y}
width={draftBox.width}
height={draftBox.height}
fillEnabled={false}
stroke={activeClassColor} stroke={activeClassColor}
strokeWidth={3.5} strokeWidth={3.5}
strokeDasharray="8 6" dash={[8, 6]}
/> />
<rect <Rect
x={draftBox.x} x={draftBox.x}
y={Math.max(4, draftBox.y - 34)} y={Math.max(4, draftBox.y - 34)}
width={110} width={110}
height={28} height={28}
rx={6} cornerRadius={6}
fill={activeClassColor} fill={activeClassColor}
/> />
<text <Text
x={draftBox.x + 55} x={draftBox.x}
y={Math.max(4, draftBox.y - 34) + 19} y={Math.max(4, draftBox.y - 34) + 5}
width={110}
align="center"
fill="#FFFFFF" fill="#FFFFFF"
fontSize={15} fontSize={15}
fontWeight="bold" fontStyle="bold"
textAnchor="middle" text={activeClassName}
> />
{activeClassName} </Group>
</text>
</g>
)} )}
</g> </Group>
) )
} }

View file

@ -1,21 +1,51 @@
import React from 'react' import React, { useEffect, useState } from 'react'
import { Image as KonvaImage } from 'react-konva'
export interface ImageViewerProps { export interface ImageViewerProps {
url: string url: string
thumbUrl?: string
width: number width: number
height: number height: number
} }
export const ImageViewer: React.FC<ImageViewerProps> = ({ url, width, height }) => { // Blur-up: paint the (usually already cached) thumbnail first, swap to the
return ( // full image the moment it arrives. The canvas never stares blank waiting
<image // on R2, and the swap is pixel-exact since both share the same dimensions.
href={url} export const ImageViewer: React.FC<ImageViewerProps> = ({ url, thumbUrl, width, height }) => {
x={0} const [current, setCurrent] = useState<HTMLImageElement | null>(null)
y={0}
width={width} useEffect(() => {
height={height} let cancelled = false
preserveAspectRatio="none" setCurrent(null)
className="select-none pointer-events-none"
/> const showThumb = thumbUrl && thumbUrl !== url
) const paint = (src: string, done: (el: HTMLImageElement) => void) => {
const el = new window.Image()
el.onload = () => {
if (!cancelled) done(el)
}
el.src = src
}
if (showThumb) {
paint(thumbUrl, (thumb) => {
if (cancelled) return
setCurrent(thumb)
paint(url, (full) => {
if (!cancelled) setCurrent(full)
})
})
} else {
paint(url, (full) => {
if (!cancelled) setCurrent(full)
})
}
return () => {
cancelled = true
}
}, [url, thumbUrl])
if (!current) return null
return <KonvaImage image={current} x={0} y={0} width={width} height={height} listening={false} />
} }

View file

@ -1,4 +1,5 @@
import React from 'react' import React from 'react'
import { Circle, Group, Rect, Text } from 'react-konva'
import { AnnotationShape } from '@/types' import { AnnotationShape } from '@/types'
export interface PointToolProps { export interface PointToolProps {
@ -15,50 +16,43 @@ export const PointTool: React.FC<PointToolProps> = ({
const pointShapes = shapes.filter((s) => s.type === 'point' && s.visible && s.point) const pointShapes = shapes.filter((s) => s.type === 'point' && s.visible && s.point)
return ( return (
<g> <Group>
{pointShapes.map((shape) => { {pointShapes.map((shape) => {
const pt = shape.point! const pt = shape.point!
const isSelected = shape.id === selectedShapeId const isSelected = shape.id === selectedShapeId
return ( return (
<g <Group
key={shape.id} key={shape.id}
className="cursor-pointer"
onClick={(e) => { onClick={(e) => {
e.stopPropagation() e.cancelBubble = true
onSelectShape(shape.id) onSelectShape(shape.id)
}} }}
style={{ cursor: 'pointer' }}
> >
<circle <Circle
cx={pt.x} x={pt.x}
cy={pt.y} y={pt.y}
r={isSelected ? 12 : 9} radius={isSelected ? 12 : 9}
fill={shape.color} fill={shape.color}
fillOpacity={0.35} opacity={0.35}
stroke="#FFFFFF" stroke="#FFFFFF"
strokeWidth={3} strokeWidth={3}
/> />
<circle cx={pt.x} cy={pt.y} r={5} fill={shape.color} /> <Circle x={pt.x} y={pt.y} radius={5} fill={shape.color} />
<rect <Rect x={pt.x - 36} y={pt.y - 38} width={72} height={24} cornerRadius={6} fill={shape.color} />
<Text
x={pt.x - 36} x={pt.x - 36}
y={pt.y - 38} y={pt.y - 33}
width={72} width={72}
height={24} align="center"
rx={6}
fill={shape.color}
/>
<text
x={pt.x}
y={pt.y - 22}
fill="#FFFFFF" fill="#FFFFFF"
fontSize={14} fontSize={14}
fontWeight="bold" fontStyle="bold"
textAnchor="middle" text={shape.labelName}
> />
{shape.labelName} </Group>
</text>
</g>
) )
})} })}
</g> </Group>
) )
} }

View file

@ -1,4 +1,5 @@
import React from 'react' import React from 'react'
import { Circle, Group, Line, Rect, Text } from 'react-konva'
import { AnnotationShape, Point2D } from '@/types' import { AnnotationShape, Point2D } from '@/types'
export interface PolygonToolProps { export interface PolygonToolProps {
@ -11,16 +12,8 @@ export interface PolygonToolProps {
cursorPoint: Point2D | null cursorPoint: Point2D | null
activeClassColor: string activeClassColor: string
onSelectShape: (shapeId: string) => void onSelectShape: (shapeId: string) => void
onStartDragVertex: ( onStartDragVertex: (shapeId: string, vertexIndex: number) => void
e: React.MouseEvent, onInsertVertexOnEdge: (shapeId: string, afterIndex: number) => void
shapeId: string,
vertexIndex: number
) => void
onInsertVertexOnEdge: (
shapeId: string,
afterIndex: number,
pt: Point2D
) => void
onCloseDraftPolygon: () => void onCloseDraftPolygon: () => void
} }
@ -45,11 +38,11 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
) )
return ( return (
<g> <Group>
{polygonShapes.map((shape) => { {polygonShapes.map((shape) => {
const pts = shape.points! const pts = shape.points!
const isSelected = shape.id === selectedShapeId const isSelected = shape.id === selectedShapeId
const pointsAttr = pts.map((p) => `${p.x},${p.y}`).join(' ') const flatPoints = pts.flatMap((p) => [p.x, p.y])
// Find top-most vertex to place the label tag cleanly above the shape // Find top-most vertex to place the label tag cleanly above the shape
const topPoint = pts.reduce( const topPoint = pts.reduce(
@ -65,20 +58,28 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
const tagY = Math.max(8, topPoint.y - 46) const tagY = Math.max(8, topPoint.y - 46)
return ( return (
<g key={shape.id}> <Group key={shape.id}>
{/* Polygon Filled Mask */} {/* Polygon Filled Mask: tint and border split (see BoundingBoxTool) */}
<polygon <Line
points={pointsAttr} points={flatPoints}
closed
fill={shape.color} fill={shape.color}
fillOpacity={maskOpacity / 100} opacity={maskOpacity / 100}
stroke={shape.color} strokeEnabled={false}
strokeWidth={isSelected ? 4 : 3}
strokeLinejoin="round"
className="cursor-pointer transition-opacity"
onMouseDown={(e) => { onMouseDown={(e) => {
e.stopPropagation() e.cancelBubble = true
onSelectShape(shape.id) onSelectShape(shape.id)
}} }}
style={{ cursor: 'pointer' }}
/>
<Line
points={flatPoints}
closed
fillEnabled={false}
stroke={shape.color}
strokeWidth={isSelected ? 4 : 3}
lineJoin="round"
listening={false}
/> />
{/* Clickable/Double-clickable Edges for inserting a new vertex */} {/* Clickable/Double-clickable Edges for inserting a new vertex */}
@ -87,115 +88,110 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
pts.map((pt, idx) => { pts.map((pt, idx) => {
const nextPt = pts[(idx + 1) % pts.length]! const nextPt = pts[(idx + 1) % pts.length]!
return ( return (
<line <Line
key={`edge-${idx}`} key={`edge-${idx}`}
x1={pt.x} points={[pt.x, pt.y, nextPt.x, nextPt.y]}
y1={pt.y} stroke="rgba(0,0,0,0)"
x2={nextPt.x}
y2={nextPt.y}
stroke="transparent"
strokeWidth={14} strokeWidth={14}
className="cursor-copy" hitStrokeWidth={14}
onDoubleClick={(e) => { onDblClick={(e) => {
e.stopPropagation() e.cancelBubble = true
const midX = (pt.x + nextPt.x) / 2 onInsertVertexOnEdge(shape.id, idx)
const midY = (pt.y + nextPt.y) / 2
onInsertVertexOnEdge(shape.id, idx, { x: midX, y: midY })
}} }}
style={{ cursor: 'copy' }}
/> />
) )
})} })}
{/* Label Pill above Selected Polygon (e.g., "Xe buýt · group 2") */} {/* Label Pill above Selected Polygon (e.g., "Xe buýt · group 2") */}
{isSelected && ( {isSelected && (
<g className="pointer-events-none"> <Group listening={false}>
<rect <Rect
x={tagX} x={tagX}
y={tagY} y={tagY}
width={tagWidth} width={tagWidth}
height={34} height={34}
rx={8} cornerRadius={8}
fill={shape.color} fill={shape.color}
fillOpacity={0.88} fillOpacity={0.88}
/> />
<text <Text
x={tagX + tagWidth / 2} x={tagX}
y={tagY + 22} y={tagY + 7}
width={tagWidth}
align="center"
fill="#0F172A" fill="#0F172A"
fontSize={16} fontSize={16}
fontWeight="bold" fontStyle="bold"
textAnchor="middle" text={tagText}
className="select-none" />
> </Group>
{tagText}
</text>
</g>
)} )}
{/* Draggable Vertex Handles on Selected Polygon */} {/* Draggable Vertex Handles on Selected Polygon */}
{isSelected && {isSelected &&
pts.map((pt, idx) => ( pts.map((pt, idx) => (
<circle <Circle
key={`vertex-${idx}`} key={`vertex-${idx}`}
cx={pt.x} x={pt.x}
cy={pt.y} y={pt.y}
r={vertexEditEnabled ? 7.5 : 5.5} radius={vertexEditEnabled ? 7.5 : 5.5}
fill="#FFFFFF" fill="#FFFFFF"
stroke={shape.color} stroke={shape.color}
strokeWidth={3.5} strokeWidth={3.5}
className={
vertexEditEnabled ? 'cursor-grab active:cursor-grabbing' : 'cursor-pointer'
}
onMouseDown={(e) => { onMouseDown={(e) => {
e.stopPropagation() e.cancelBubble = true
if (vertexEditEnabled) { if (vertexEditEnabled) {
onStartDragVertex(e, shape.id, idx) onStartDragVertex(shape.id, idx)
} }
}} }}
style={{
cursor: vertexEditEnabled ? 'grab' : 'pointer',
}}
/> />
))} ))}
</g> </Group>
) )
})} })}
{/* In-progress Draft Polygon while clicking points */} {/* In-progress Draft Polygon while clicking points */}
{draftPolygonPoints.length > 0 && ( {draftPolygonPoints.length > 0 && (
<g> <Group>
<polyline <Line
points={[ points={[
...draftPolygonPoints.map((p) => `${p.x},${p.y}`), ...draftPolygonPoints.flatMap((p) => [p.x, p.y]),
...(cursorPoint ? [`${cursorPoint.x},${cursorPoint.y}`] : []), ...(cursorPoint ? [cursorPoint.x, cursorPoint.y] : []),
].join(' ')} ]}
fill={activeClassColor} fill={activeClassColor}
fillOpacity={0.18} fillOpacity={0.18}
stroke={activeClassColor} stroke={activeClassColor}
strokeWidth={3.5} strokeWidth={3.5}
strokeDasharray="8 5" dash={[8, 5]}
className="pointer-events-none" listening={false}
/> />
{draftPolygonPoints.map((pt, idx) => { {draftPolygonPoints.map((pt, idx) => {
const isFirst = idx === 0 const isFirst = idx === 0
return ( return (
<circle <Circle
key={`draft-pt-${idx}`} key={`draft-pt-${idx}`}
cx={pt.x} x={pt.x}
cy={pt.y} y={pt.y}
r={isFirst ? 10 : 7} radius={isFirst ? 10 : 7}
fill={isFirst ? activeClassColor : '#FFFFFF'} fill={isFirst ? activeClassColor : '#FFFFFF'}
stroke="#FFFFFF" stroke="#FFFFFF"
strokeWidth={3} strokeWidth={3}
className="cursor-pointer"
onClick={(e) => { onClick={(e) => {
if (isFirst && draftPolygonPoints.length >= 3) { if (isFirst && draftPolygonPoints.length >= 3) {
e.stopPropagation() e.cancelBubble = true
onCloseDraftPolygon() onCloseDraftPolygon()
} }
}} }}
style={{ cursor: 'pointer' }}
/> />
) )
})} })}
</g> </Group>
)} )}
</g> </Group>
) )
} }

View file

@ -4,7 +4,6 @@ import { TASK_TYPE_LABELS } from '@/app/constants'
import { formatNumber } from '@/utils/format' import { formatNumber } from '@/utils/format'
import { useAnnotatorStore } from '../../annotatorStore' import { useAnnotatorStore } from '../../annotatorStore'
import { SaveButton } from './SaveButton' import { SaveButton } from './SaveButton'
import { SaveAndNextButton } from './SaveAndNextButton'
export const AnnotatorHeader: React.FC = () => { export const AnnotatorHeader: React.FC = () => {
const navigate = useNavigate() const navigate = useNavigate()
@ -32,7 +31,6 @@ export const AnnotatorHeader: React.FC = () => {
<span>Về tổng quan</span> <span>Về tổng quan</span>
</button> </button>
<SaveButton /> <SaveButton />
<SaveAndNextButton />
</div> </div>
</section> </section>
) )

View file

@ -1,29 +0,0 @@
import React from 'react'
import toast from 'react-hot-toast'
import { useAnnotatorStore } from '../../annotatorStore'
import { ANNOTATOR_COLORS } from '../../annotatorTheme'
export const SaveAndNextButton: React.FC = () => {
const saveAndNext = useAnnotatorStore((s) => s.saveAndNext)
const currentImage = useAnnotatorStore((s) => s.images[s.currentImageIndex])
const handleSaveAndNext = () => {
const fileName = currentImage?.fileName ?? 'ảnh'
saveAndNext()
toast.success(`Đã lưu ${fileName} và chuyển sang ảnh tiếp theo`)
}
return (
<button
type="button"
onClick={handleSaveAndNext}
className="inline-flex h-10 items-center gap-2 rounded-lg bg-[#c75c4a] px-4 text-[13px] font-semibold text-white transition-colors hover:bg-[#b94f3e] focus:outline-none focus:ring-2 focus:ring-[#c75c4a]/30"
style={{ backgroundColor: ANNOTATOR_COLORS.brand }}
onMouseEnter={(event) => { event.currentTarget.style.backgroundColor = ANNOTATOR_COLORS.brandHover }}
onMouseLeave={(event) => { event.currentTarget.style.backgroundColor = ANNOTATOR_COLORS.brand }}
>
<span>→</span>
<span>Lưu &amp; ảnh tiếp</span>
</button>
)
}

View file

@ -9,6 +9,7 @@ export const SaveStatus: React.FC = () => {
const currentImage = useAnnotatorStore((s) => s.images[s.currentImageIndex]) const currentImage = useAnnotatorStore((s) => s.images[s.currentImageIndex])
const shapesByImageId = useAnnotatorStore((s) => s.shapesByImageId) const shapesByImageId = useAnnotatorStore((s) => s.shapesByImageId)
const lastSavedAt = useAnnotatorStore((s) => s.lastSavedAt) const lastSavedAt = useAnnotatorStore((s) => s.lastSavedAt)
const isSaving = useAnnotatorStore((s) => s.isSaving)
const shapes = currentImage ? shapesByImageId[currentImage.id] ?? [] : [] const shapes = currentImage ? shapesByImageId[currentImage.id] ?? [] : []
@ -33,10 +34,17 @@ export const SaveStatus: React.FC = () => {
return ( return (
<div className="flex flex-wrap items-center justify-between border-t border-slate-100 px-4 py-2.5 text-xs"> <div className="flex flex-wrap items-center justify-between border-t border-slate-100 px-4 py-2.5 text-xs">
{isSaving ? (
<div className="flex items-center gap-1.5 font-medium text-amber-600">
<span className="inline-block h-3 w-3 animate-spin rounded-full border-2 border-amber-200 border-t-amber-600" />
<span>Đang lưu…</span>
</div>
) : (
<div className="flex items-center gap-1.5 font-medium text-[#15803D]"> <div className="flex items-center gap-1.5 font-medium text-[#15803D]">
<span>✓</span> <span>✓</span>
<span>Đã lưu lúc {lastSavedAt}</span> <span>Đã lưu lúc {lastSavedAt}</span>
</div> </div>
)}
{project.taskType === 'segmentation' && ( {project.taskType === 'segmentation' && (
<div className="flex items-center gap-5"> <div className="flex items-center gap-5">

View file

@ -3,14 +3,22 @@ import clsx from 'clsx'
import { useAnnotatorStore } from '../../annotatorStore' import { useAnnotatorStore } from '../../annotatorStore'
import { ANNOTATOR_COLORS } from '../../annotatorTheme' import { ANNOTATOR_COLORS } from '../../annotatorTheme'
// Sliding window: with 1k+ images, rendering every thumb would issue
// a thousand R2 GETs and DOM nodes. Only neighbours of the cursor load.
const STRIP_RADIUS = 30
export const ThumbnailStrip: React.FC = () => { export const ThumbnailStrip: React.FC = () => {
const images = useAnnotatorStore((s) => s.images) const images = useAnnotatorStore((s) => s.images)
const currentImageIndex = useAnnotatorStore((s) => s.currentImageIndex) const currentImageIndex = useAnnotatorStore((s) => s.currentImageIndex)
const selectImageByIndex = useAnnotatorStore((s) => s.selectImageByIndex) const selectImageByIndex = useAnnotatorStore((s) => s.selectImageByIndex)
const lo = Math.max(0, currentImageIndex - STRIP_RADIUS)
const hi = Math.min(images.length, currentImageIndex + STRIP_RADIUS + 1)
return ( return (
<div className="grid grid-cols-6 gap-2.5 px-4 py-2.5"> <div className="grid grid-cols-6 gap-2.5 px-4 py-2.5">
{images.map((img, index) => { {images.slice(lo, hi).map((img, i) => {
const index = lo + i
const isActive = index === currentImageIndex const isActive = index === currentImageIndex
// Shorten "urban_00124.jpg" -> "..00124.jpg" matching wireframe // Shorten "urban_00124.jpg" -> "..00124.jpg" matching wireframe
const shortName = img.fileName.replace(/^[a-z]+_/, '..') const shortName = img.fileName.replace(/^[a-z]+_/, '..')
@ -32,8 +40,10 @@ export const ThumbnailStrip: React.FC = () => {
style={isActive ? { borderColor: ANNOTATOR_COLORS.selection } : undefined} style={isActive ? { borderColor: ANNOTATOR_COLORS.selection } : undefined}
> >
<img <img
src={img.thumbnailUrl} src={img.thumbnailSmallUrl ?? img.thumbnailUrl}
alt={img.fileName} alt={img.fileName}
loading="lazy"
decoding="async"
className="h-full w-full object-cover" className="h-full w-full object-cover"
/> />
</div> </div>

View file

@ -1,5 +1,8 @@
import React, { useState } from 'react' import React from 'react'
import toast from 'react-hot-toast'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { USE_MOCK_DATA } from '@/app/constants'
import { useAuth } from '@/hooks/useAuth'
import { LoginRequest } from '@/types' import { LoginRequest } from '@/types'
import { LOGIN_COLORS } from '@/styles/theme' import { LOGIN_COLORS } from '@/styles/theme'
import { HeroSection } from './components/HeroSection' import { HeroSection } from './components/HeroSection'
@ -13,23 +16,30 @@ const FOOTER_LINKS = [
export const LoginPage: React.FC = () => { export const LoginPage: React.FC = () => {
const navigate = useNavigate() const navigate = useNavigate()
const [isLoading, setIsLoading] = useState(false) const { login, loginWithSSO, error: authError, isLoading } = useAuth()
const [contactModalOpen, setContactModalOpen] = useState(false) const [contactModalOpen, setContactModalOpen] = React.useState(false)
const handleLogin = (_credentials: LoginRequest) => { const handleLogin = async (credentials: LoginRequest) => {
setIsLoading(true) try {
setTimeout(() => { await login(credentials)
setIsLoading(false)
navigate('/projects') navigate('/projects')
}, 250) } catch {
// useAuth already stores the message; shown below the form.
}
} }
const handleSSOLogin = () => { const handleSSOLogin = async () => {
setIsLoading(true) if (!USE_MOCK_DATA) {
setTimeout(() => { // No SSO provider is configured; a mock token would only 401 back here.
setIsLoading(false) toast.error('SSO chưa được cấu hình, hãy đăng nhập bằng email')
return
}
try {
await loginWithSSO('sso')
navigate('/projects') navigate('/projects')
}, 250) } catch {
// shown via authError
}
} }
return ( return (
@ -67,9 +77,10 @@ export const LoginPage: React.FC = () => {
{/* Biểu mẫu đăng nhập trung tâm */} {/* Biểu mẫu đăng nhập trung tâm */}
<LoginForm <LoginForm
onSubmit={handleLogin} onSubmit={(data) => void handleLogin(data)}
onSSOLogin={handleSSOLogin} onSSOLogin={() => void handleSSOLogin()}
isLoading={isLoading} isLoading={isLoading}
serverError={authError}
/> />
{/* Liên kết điều khoản & ngôn ngữ cuối trang */} {/* Liên kết điều khoản & ngôn ngữ cuối trang */}

View file

@ -1,5 +1,6 @@
import React, { useState } from 'react' import React, { useState } from 'react'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { USE_MOCK_DATA } from '@/app/constants'
import { LoginRequest } from '@/types' import { LoginRequest } from '@/types'
import { LOGIN_COLORS, createInsetOutlineStyle } from '@/styles/theme' import { LOGIN_COLORS, createInsetOutlineStyle } from '@/styles/theme'
import { SSOButton } from './SSOButton' import { SSOButton } from './SSOButton'
@ -8,15 +9,17 @@ export interface LoginFormProps {
onSubmit: (data: LoginRequest) => void onSubmit: (data: LoginRequest) => void
onSSOLogin?: () => void onSSOLogin?: () => void
isLoading?: boolean isLoading?: boolean
serverError?: string | null
} }
export const LoginForm: React.FC<LoginFormProps> = ({ export const LoginForm: React.FC<LoginFormProps> = ({
onSubmit, onSubmit,
onSSOLogin, onSSOLogin,
isLoading = false, isLoading = false,
serverError = null,
}) => { }) => {
const [email, setEmail] = useState<string>('minhanh@visionlab.vn') const [email, setEmail] = useState<string>(USE_MOCK_DATA ? 'minhanh@visionlab.vn' : '')
const [password, setPassword] = useState<string>('••••••••••••') const [password, setPassword] = useState<string>(USE_MOCK_DATA ? '••••••••••••' : '')
const [rememberMe, setRememberMe] = useState<boolean>(true) const [rememberMe, setRememberMe] = useState<boolean>(true)
const [showPassword, setShowPassword] = useState<boolean>(false) const [showPassword, setShowPassword] = useState<boolean>(false)
const [errorMessage, setErrorMessage] = useState<string | null>(null) const [errorMessage, setErrorMessage] = useState<string | null>(null)
@ -94,9 +97,9 @@ export const LoginForm: React.FC<LoginFormProps> = ({
</div> </div>
{/* Thông báo lỗi nếu có */} {/* Thông báo lỗi nếu có */}
{errorMessage && ( {(errorMessage || serverError) && (
<div className="self-stretch px-3.5 py-2.5 rounded-[8px] bg-red-50 border border-red-200 text-xs text-red-700"> <div className="self-stretch px-3.5 py-2.5 rounded-[8px] bg-red-50 border border-red-200 text-xs text-red-700">
{errorMessage} {errorMessage ?? serverError}
</div> </div>
)} )}

View file

@ -1,6 +1,12 @@
import React, { useState, useEffect, useRef } from 'react' import React, { useState, useEffect, useRef, useCallback } from 'react'
import toast from 'react-hot-toast'
import { useParams, useNavigate } from 'react-router-dom' import { useParams, useNavigate } from 'react-router-dom'
import { TaskType } from '@/types' import { Project, ProjectMemberSummary, TaskType } from '@/types'
import { USE_MOCK_DATA } from '@/app/constants'
import { getProjectById, updateProject, deleteProject } from '@/services/projectService'
import { uploadImages } from '@/services/imageService'
import { replaceLabels } from '@/services/labelService'
import { updateMemberProjects, updateMemberRole } from '@/services/userService'
import { import {
OverviewTab, OverviewTab,
DataTab, DataTab,
@ -9,13 +15,12 @@ import {
SettingsTab, SettingsTab,
} from './components' } from './components'
import { import {
getProjectById, getProjectById as getMockProjectById,
getProjectImages,
addUploadedImagesToProject, addUploadedImagesToProject,
updateProjectClasses, updateProjectClasses,
updateProjectMembers, updateProjectMembers,
updateProject, updateProject as updateMockProject,
deleteProjectById, deleteProjectById as deleteMockProjectById,
subscribeProjectsStore, subscribeProjectsStore,
} from './projectData' } from './projectData'
@ -41,27 +46,165 @@ export const ProjectDetailPage: React.FC = () => {
const fileInputRef = useRef<HTMLInputElement | null>(null) const fileInputRef = useRef<HTMLInputElement | null>(null)
const [activeTab, setActiveTab] = useState<DetailTabKey>('overview') const [activeTab, setActiveTab] = useState<DetailTabKey>('overview')
const [project, setProject] = useState(() => getProjectById(id)) const [project, setProject] = useState<Project | null>(null)
const [images, setImages] = useState(() => getProjectImages(project.id)) const [isUploading, setIsUploading] = useState(false)
useEffect(() => { const reload = useCallback(async () => {
const current = getProjectById(id) if (!id) return
setProject(current) if (USE_MOCK_DATA) {
setImages(getProjectImages(current.id)) setProject(getMockProjectById(id))
return
}
setProject(await getProjectById(id))
}, [id]) }, [id])
useEffect(() => { useEffect(() => {
if (USE_MOCK_DATA) {
setProject(getMockProjectById(id))
return
}
reload().catch((err: unknown) => {
toast.error(err instanceof Error ? err.message : 'Không tải được dự án')
})
}, [id, reload])
useEffect(() => {
if (!USE_MOCK_DATA || !id) return
return subscribeProjectsStore(() => { return subscribeProjectsStore(() => {
const current = getProjectById(id) setProject(getMockProjectById(id))
setProject(current)
setImages(getProjectImages(current.id))
}) })
}, [id]) }, [id])
const handleUploadFiles = (fileList: FileList | null) => { const handleUploadFiles = async (fileList: FileList | null) => {
if (!fileList || fileList.length === 0) return if (!fileList || fileList.length === 0 || !project) return
const names = Array.from(fileList).map((f) => f.name) if (USE_MOCK_DATA) {
addUploadedImagesToProject(project.id, names) addUploadedImagesToProject(project.id, Array.from(fileList).map((f) => f.name))
return
}
setIsUploading(true)
try {
const files = Array.from(fileList)
await uploadImages(
project.id,
files.map((file) => ({ fileName: file.name, file }))
)
toast.success(`Đã tải lên ${files.length} ảnh`)
await reload()
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Tải ảnh thất bại')
} finally {
setIsUploading(false)
}
}
const handleUpdateClasses = async (classes: Project['classes']) => {
if (!project) return
if (USE_MOCK_DATA) {
updateProjectClasses(project.id, classes)
return
}
try {
const replaced = await replaceLabels(project.id, classes)
setProject({ ...project, classes: replaced })
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Cập nhật lớp nhãn thất bại')
}
}
const handleUpdateMembers = async (members: ProjectMemberSummary[]) => {
if (!project) return
if (USE_MOCK_DATA) {
updateProjectMembers(project.id, members)
return
}
const prev = project.members
try {
// Diff against current list: role change / unassign sync to backend.
// Brand-new local entries (mem-*) need an email invite -> use Users page.
for (const m of members) {
const old = prev.find((p) => p.id === m.id)
if (!old) {
if (String(m.id).startsWith('mem-')) {
toast.error(`"${m.name}" chưa có tài khoản — mời qua trang Users bằng email trước`)
continue
}
await updateMemberProjects(m.id, [project.id])
continue
}
if (old.role !== m.role) {
await updateMemberRole(m.id, m.role)
}
}
for (const old of prev) {
if (!members.some((m) => m.id === old.id)) {
const { getMembers } = await import('@/services/userService')
const all = await getMembers()
const full = all.find((u) => u.id === old.id)
if (full) {
await updateMemberProjects(
old.id,
full.assignedProjectIds.filter((pid) => pid !== project.id)
)
}
}
}
await reload()
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Cập nhật thành viên thất bại')
}
}
const handleSaveSettings = async (updates: {
name: string
slug: string
description: string
taskType: TaskType
}) => {
if (!project) return
if (USE_MOCK_DATA) {
updateMockProject(project.id, (p) => ({
...p,
name: updates.name,
slug: updates.slug,
description: updates.description,
taskType: updates.taskType,
updatedAt: 'Vừa cập nhật',
}))
return
}
try {
const updated = await updateProject(project.id, updates)
setProject(updated)
toast.success('Đã lưu cài đặt')
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Lưu cài đặt thất bại')
}
}
const handleDeleteProject = async () => {
if (!project) return
if (USE_MOCK_DATA) {
deleteMockProjectById(project.id)
navigate('/projects')
return
}
try {
await deleteProject(project.id)
navigate('/projects')
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Xóa dự án thất bại')
}
}
if (!project) {
return (
<div className="flex min-h-[360px] items-center justify-center">
<div className="flex flex-col items-center gap-3">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-slate-200 border-t-[#C95C3C]" />
<span className="text-xs font-medium text-slate-500">Đang tải dự án...</span>
</div>
</div>
)
} }
return ( return (
@ -73,7 +216,7 @@ export const ProjectDetailPage: React.FC = () => {
accept="image/*" accept="image/*"
multiple multiple
className="hidden" className="hidden"
onChange={(e) => handleUploadFiles(e.target.files)} onChange={(e) => void handleUploadFiles(e.target.files)}
/> />
{/* Top Header matching MVP · Project dashboard.png */} {/* Top Header matching MVP · Project dashboard.png */}
@ -97,7 +240,8 @@ export const ProjectDetailPage: React.FC = () => {
<button <button
type="button" type="button"
onClick={() => fileInputRef.current?.click()} onClick={() => fileInputRef.current?.click()}
className="inline-flex h-10 items-center gap-2 rounded-lg border border-[var(--project-border)] bg-white px-4 text-[13px] font-semibold text-[var(--project-heading)] transition hover:bg-[var(--project-canvas)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--project-accent)]/30" disabled={isUploading}
className="inline-flex h-10 items-center gap-2 rounded-lg border border-[var(--project-border)] bg-white px-4 text-[13px] font-semibold text-[var(--project-heading)] transition hover:bg-[var(--project-canvas)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--project-accent)]/30 disabled:opacity-60"
> >
<svg <svg
className="h-4 w-4 text-[var(--project-heading)]" className="h-4 w-4 text-[var(--project-heading)]"
@ -112,7 +256,7 @@ export const ProjectDetailPage: React.FC = () => {
d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M16 8l-4-4m0 0L8 8m4-4v12" d="M4 16v2a2 2 0 002 2h12a2 2 0 002-2v-2M16 8l-4-4m0 0L8 8m4-4v12"
/> />
</svg> </svg>
<span>Tải ảnh lên</span> <span>{isUploading ? 'Đang tải...' : 'Tải ảnh lên'}</span>
</button> </button>
<button <button
@ -156,7 +300,6 @@ export const ProjectDetailPage: React.FC = () => {
{activeTab === 'overview' && ( {activeTab === 'overview' && (
<OverviewTab <OverviewTab
project={project} project={project}
images={images}
onSwitchTab={(tab) => setActiveTab(tab)} onSwitchTab={(tab) => setActiveTab(tab)}
/> />
)} )}
@ -164,39 +307,30 @@ export const ProjectDetailPage: React.FC = () => {
{activeTab === 'data' && ( {activeTab === 'data' && (
<DataTab <DataTab
project={project} project={project}
images={images} onUploadImages={(_names, files) => void handleUploadFiles(files ? toFileList(files) : null)}
onUploadImages={(names) => addUploadedImagesToProject(project.id, names)} hideSampleUpload={!USE_MOCK_DATA}
/> />
)} )}
{activeTab === 'labels' && ( {activeTab === 'labels' && (
<LabelsTab <LabelsTab
classes={project.classes} classes={project.classes}
onUpdateClasses={(classes) => updateProjectClasses(project.id, classes)} onUpdateClasses={(classes) => void handleUpdateClasses(classes)}
/> />
)} )}
{activeTab === 'members' && ( {activeTab === 'members' && (
<MembersTab <MembersTab
members={project.members} members={project.members}
onUpdateMembers={(members) => updateProjectMembers(project.id, members)} onUpdateMembers={(members) => void handleUpdateMembers(members)}
/> />
)} )}
{activeTab === 'settings' && ( {activeTab === 'settings' && (
<SettingsTab <SettingsTab
project={project} project={project}
onSaveSettings={(updates) => onSaveSettings={(updates) => void handleSaveSettings(updates)}
updateProject(project.id, (p) => ({ onDeleteProject={() => void handleDeleteProject()}
...p,
name: updates.name,
slug: updates.slug,
description: updates.description,
taskType: updates.taskType,
updatedAt: 'Vừa cập nhật',
}))
}
onDeleteProject={() => deleteProjectById(project.id)}
/> />
)} )}
</div> </div>
@ -204,4 +338,10 @@ export const ProjectDetailPage: React.FC = () => {
) )
} }
function toFileList(files: File[]): FileList | null {
const dt = new DataTransfer()
for (const f of files) dt.items.add(f)
return dt.files.length > 0 ? dt.files : null
}
export default ProjectDetailPage export default ProjectDetailPage

View file

@ -1,5 +1,8 @@
import React, { useState, useEffect, useMemo } from 'react' import React, { useState, useMemo } from 'react'
import toast from 'react-hot-toast'
import { CreateProjectInput, ProjectStatus, TaskType } from '@/types' import { CreateProjectInput, ProjectStatus, TaskType } from '@/types'
import { USE_MOCK_DATA } from '@/app/constants'
import { useProjects } from '@/hooks/useProjects'
import { import {
ProjectStatsCards, ProjectStatsCards,
ProjectFilters, ProjectFilters,
@ -8,16 +11,22 @@ import {
CreateProjectModal, CreateProjectModal,
} from './components' } from './components'
import { import {
getProjects, getProjects as getMockProjects,
getActivities, getActivities as getMockActivities,
addProject, addProject as addMockProject,
deleteProjectById, deleteProjectById as deleteMockProjectById,
subscribeProjectsStore, subscribeProjectsStore,
} from './projectData' } from './projectData'
export const ProjectListPage: React.FC = () => { export const ProjectListPage: React.FC = () => {
const [projects, setProjects] = useState(() => getProjects()) const {
const [activities, setActivities] = useState(() => getActivities()) projects: apiProjects,
activities: apiActivities,
isLoading: apiLoading,
createProject: apiCreate,
deleteProject: apiDelete,
} = useProjects()
const [mockTick, setMockTick] = useState(0)
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false) const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
const [searchQuery, setSearchQuery] = useState('') const [searchQuery, setSearchQuery] = useState('')
@ -26,13 +35,23 @@ export const ProjectListPage: React.FC = () => {
const [sortBy, setSortBy] = useState<'updated' | 'name' | 'progress'>('updated') const [sortBy, setSortBy] = useState<'updated' | 'name' | 'progress'>('updated')
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid') const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
useEffect(() => { React.useEffect(() => {
return subscribeProjectsStore(() => { if (USE_MOCK_DATA) {
setProjects(getProjects()) return subscribeProjectsStore(() => setMockTick((t) => t + 1))
setActivities(getActivities()) }
})
}, []) }, [])
const projects = useMemo(
() => (USE_MOCK_DATA ? getMockProjects() : apiProjects),
// eslint-disable-next-line react-hooks/exhaustive-deps
[mockTick, apiProjects]
)
const activities = useMemo(
() => (USE_MOCK_DATA ? getMockActivities() : apiActivities),
// eslint-disable-next-line react-hooks/exhaustive-deps
[mockTick, apiActivities]
)
const filteredProjects = useMemo(() => { const filteredProjects = useMemo(() => {
const list = projects.filter((proj) => { const list = projects.filter((proj) => {
const q = searchQuery.trim().toLowerCase() const q = searchQuery.trim().toLowerCase()
@ -53,27 +72,40 @@ export const ProjectListPage: React.FC = () => {
return [...list].sort((a, b) => a.name.localeCompare(b.name, 'vi')) return [...list].sort((a, b) => a.name.localeCompare(b.name, 'vi'))
} }
if (sortBy === 'progress') { if (sortBy === 'progress') {
return [...list].sort((a, b) => { const progressOf = (p: (typeof list)[number]) =>
const progA = p.stats.totalImages > 0
a.stats.totalImages > 0 ? (p.stats.completed + p.stats.pendingReview) / p.stats.totalImages
? (a.stats.completed + a.stats.pendingReview) / a.stats.totalImages
: 0 : 0
const progB = return [...list].sort((x, y) => progressOf(y) - progressOf(x))
b.stats.totalImages > 0
? (b.stats.completed + b.stats.pendingReview) / b.stats.totalImages
: 0
return progB - progA
})
} }
return list return list
}, [projects, searchQuery, selectedTaskType, selectedStatus, sortBy]) }, [projects, searchQuery, selectedTaskType, selectedStatus, sortBy])
const handleCreateProject = (input: CreateProjectInput) => { const handleCreateProject = async (input: CreateProjectInput) => {
addProject(input) if (USE_MOCK_DATA) {
addMockProject(input)
return
}
try {
await apiCreate(input)
setIsCreateModalOpen(false)
toast.success('Đã tạo dự án')
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Tạo dự án thất bại')
}
} }
const handleDeleteProject = (projectId: string) => { const handleDeleteProject = async (projectId: string) => {
deleteProjectById(projectId) if (USE_MOCK_DATA) {
deleteMockProjectById(projectId)
return
}
try {
await apiDelete(projectId)
toast.success('Đã xóa dự án')
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Xóa dự án thất bại')
}
} }
return ( return (
@ -100,7 +132,7 @@ export const ProjectListPage: React.FC = () => {
</div> </div>
{/* 4 Summary Cards */} {/* 4 Summary Cards */}
<ProjectStatsCards projects={projects} /> <ProjectStatsCards projects={filteredProjects} />
{/* Filter Bar */} {/* Filter Bar */}
<ProjectFilters <ProjectFilters
@ -117,7 +149,14 @@ export const ProjectListPage: React.FC = () => {
/> />
{/* Project Cards Grid / List */} {/* Project Cards Grid / List */}
{filteredProjects.length === 0 ? ( {!USE_MOCK_DATA && apiLoading && projects.length === 0 ? (
<div className="flex min-h-[240px] items-center justify-center">
<div className="flex flex-col items-center gap-3">
<div className="h-8 w-8 animate-spin rounded-full border-2 border-slate-200 border-t-[#C95C3C]" />
<span className="text-xs font-medium text-slate-500">Đang tải dự án...</span>
</div>
</div>
) : filteredProjects.length === 0 ? (
<div className="rounded-2xl border border-slate-200/80 bg-white py-14 text-center"> <div className="rounded-2xl border border-slate-200/80 bg-white py-14 text-center">
<p className="text-sm font-semibold text-slate-700"> <p className="text-sm font-semibold text-slate-700">
Không tìm thấy dự án phù hợp Không tìm thấy dự án phù hợp
@ -138,7 +177,7 @@ export const ProjectListPage: React.FC = () => {
<ProjectCard <ProjectCard
key={project.id} key={project.id}
project={project} project={project}
onDelete={handleDeleteProject} onDelete={(pid) => void handleDeleteProject(pid)}
/> />
))} ))}
</div> </div>
@ -155,7 +194,7 @@ export const ProjectListPage: React.FC = () => {
<CreateProjectModal <CreateProjectModal
isOpen={isCreateModalOpen} isOpen={isCreateModalOpen}
onClose={() => setIsCreateModalOpen(false)} onClose={() => setIsCreateModalOpen(false)}
onCreate={handleCreateProject} onCreate={(input) => void handleCreateProject(input)}
/> />
</div> </div>
) )

View file

@ -76,6 +76,8 @@ export const ProjectCard: React.FC<ProjectCardProps> = ({ project, onDelete }) =
<img <img
src={project.thumbnailUrl} src={project.thumbnailUrl}
alt={project.name} alt={project.name}
loading="lazy"
decoding="async"
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.02]" className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.02]"
/> />

View file

@ -1,11 +1,11 @@
import React, { useState, useRef } from 'react' import React, { useState, useRef } from 'react'
import { ImageItem, Project } from '@/types' import { Project } from '@/types'
import { ImageTable } from './ImageTable' import { ImageTable } from './ImageTable'
interface DataTabProps { interface DataTabProps {
project: Project project: Project
images: ImageItem[] onUploadImages: (fileNames: string[], files?: File[]) => void
onUploadImages: (fileNames: string[]) => void hideSampleUpload?: boolean
} }
interface DatasetBatch { interface DatasetBatch {
@ -19,9 +19,10 @@ interface DatasetBatch {
export const DataTab: React.FC<DataTabProps> = ({ export const DataTab: React.FC<DataTabProps> = ({
project, project,
images,
onUploadImages, onUploadImages,
hideSampleUpload = false,
}) => { }) => {
const imageCount = project.stats.totalImages
const fileInputRef = useRef<HTMLInputElement | null>(null) const fileInputRef = useRef<HTMLInputElement | null>(null)
const [isDragging, setIsDragging] = useState(false) const [isDragging, setIsDragging] = useState(false)
const [batches, setBatches] = useState<DatasetBatch[]>([ const [batches, setBatches] = useState<DatasetBatch[]>([
@ -53,15 +54,18 @@ export const DataTab: React.FC<DataTabProps> = ({
const handleFilesSelected = (files: FileList | null) => { const handleFilesSelected = (files: FileList | null) => {
if (!files || files.length === 0) return if (!files || files.length === 0) return
const names = Array.from(files).map((f) => f.name) const list = Array.from(files)
onUploadImages(names) onUploadImages(
list.map((f) => f.name),
list
)
setBatches((prev) => [ setBatches((prev) => [
{ {
id: `batch-${Date.now()}`, id: `batch-${Date.now()}`,
batchName: `upload_batch_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}`, batchName: `upload_batch_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}`,
uploadedBy: 'Minh Anh', uploadedBy: 'Minh Anh',
uploadedAt: 'Vừa tải lên', uploadedAt: 'Vừa tải lên',
imageCount: names.length, imageCount: list.length,
status: 'Đã phân công', status: 'Đã phân công',
}, },
...prev, ...prev,
@ -70,9 +74,9 @@ export const DataTab: React.FC<DataTabProps> = ({
const handleSimulatedSampleUpload = () => { const handleSimulatedSampleUpload = () => {
const sampleNames = [ const sampleNames = [
`traffic_${String(327 + images.length).padStart(5, '0')}.jpg`, `traffic_${String(327 + imageCount).padStart(5, '0')}.jpg`,
`traffic_${String(328 + images.length).padStart(5, '0')}.jpg`, `traffic_${String(328 + imageCount).padStart(5, '0')}.jpg`,
`traffic_${String(329 + images.length).padStart(5, '0')}.jpg`, `traffic_${String(329 + imageCount).padStart(5, '0')}.jpg`,
] ]
onUploadImages(sampleNames) onUploadImages(sampleNames)
setBatches((prev) => [ setBatches((prev) => [
@ -146,6 +150,7 @@ export const DataTab: React.FC<DataTabProps> = ({
> >
Chọn tệp từ máy tính Chọn tệp từ máy tính
</button> </button>
{!hideSampleUpload && (
<button <button
type="button" type="button"
onClick={handleSimulatedSampleUpload} onClick={handleSimulatedSampleUpload}
@ -153,6 +158,7 @@ export const DataTab: React.FC<DataTabProps> = ({
> >
+ Nhập nhanh 3 ảnh mẫu + Nhập nhanh 3 ảnh mẫu
</button> </button>
)}
</div> </div>
</div> </div>
@ -203,13 +209,13 @@ export const DataTab: React.FC<DataTabProps> = ({
</div> </div>
</div> </div>
{/* Full Image Table */} {/* Full Image Table (self-paginated) */}
<ImageTable <ImageTable
projectId={project.id} projectId={project.id}
projectSlug={project.slug} projectSlug={project.slug}
images={images}
stats={project.stats} stats={project.stats}
classes={project.classes} classes={project.classes}
memberNames={project.members.map((m) => m.name)}
/> />
</div> </div>
) )

View file

@ -1,20 +1,48 @@
import React, { useState } from 'react' import React, { useState } from 'react'
import toast from 'react-hot-toast'
import { ImageItem, LabelClass } from '@/types' import { ImageItem, LabelClass } from '@/types'
import { USE_MOCK_DATA } from '@/app/constants'
import { exportProjectLabels, type ExportFormat } from '@/services/exportService'
import { track } from '@/services/eventService'
interface ExportButtonProps { interface ExportButtonProps {
projectId?: string
projectSlug?: string projectSlug?: string
images?: ImageItem[] images?: ImageItem[]
classes?: LabelClass[] classes?: LabelClass[]
} }
const FORMAT_MAP = { coco: 'coco_json', yolo: 'yolo_txt', json: 'labelme_json' } as const
export const ExportButton: React.FC<ExportButtonProps> = ({ export const ExportButton: React.FC<ExportButtonProps> = ({
projectId,
projectSlug = 'traffic_camera_v2', projectSlug = 'traffic_camera_v2',
images = [], images = [],
classes = [], classes = [],
}) => { }) => {
const [open, setOpen] = useState(false) const [open, setOpen] = useState(false)
const [isExporting, setIsExporting] = useState(false)
const triggerDownload = (format: 'coco' | 'yolo' | 'json') => { const triggerDownload = (format: 'coco' | 'yolo' | 'json') => {
// Real mode: export the whole filtered dataset server-side, not just this page.
if (!USE_MOCK_DATA && projectId) {
const exportFormat: ExportFormat = FORMAT_MAP[format]
setOpen(false)
setIsExporting(true)
exportProjectLabels(projectId, exportFormat)
.then(({ fileName, recordCount }) => {
track('dataset.export', {
project_id: projectId,
payload: { format: exportFormat, recordCount },
})
toast.success(`Đã xuất ${recordCount} ảnh (${fileName})`)
})
.catch((err: unknown) => {
toast.error(err instanceof Error ? err.message : 'Xuất dataset thất bại')
})
.finally(() => setIsExporting(false))
return
}
const payload = { const payload = {
dataset: projectSlug, dataset: projectSlug,
exportFormat: format.toUpperCase(), exportFormat: format.toUpperCase(),
@ -49,6 +77,7 @@ export const ExportButton: React.FC<ExportButtonProps> = ({
<div className="relative"> <div className="relative">
<button <button
type="button" type="button"
disabled={isExporting}
onClick={() => setOpen((prev) => !prev)} onClick={() => setOpen((prev) => !prev)}
className="inline-flex h-10 items-center gap-2 rounded-lg border border-[var(--project-border)] bg-white px-4 text-xs font-semibold text-[var(--project-heading)] transition hover:bg-[var(--project-canvas)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--project-accent)]/30" className="inline-flex h-10 items-center gap-2 rounded-lg border border-[var(--project-border)] bg-white px-4 text-xs font-semibold text-[var(--project-heading)] transition hover:bg-[var(--project-canvas)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--project-accent)]/30"
> >

View file

@ -1,14 +1,17 @@
import React, { useState, useMemo } from 'react' import React, { useEffect, useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { ImageAnnotationStatus, ImageItem, LabelClass, ProjectStats } from '@/types' import { ImageAnnotationStatus, ImageItem, LabelClass, ProjectStats } from '@/types'
import { USE_MOCK_DATA } from '@/app/constants'
import { useDebounce } from '@/hooks/useDebounce'
import { getProjectImages, getProjectImagesPage } from '@/services/imageService'
import { ImageTableFilters } from './ImageTableFilters' import { ImageTableFilters } from './ImageTableFilters'
interface ImageTableProps { interface ImageTableProps {
projectId: string projectId: string
projectSlug: string projectSlug: string
images: ImageItem[]
stats: ProjectStats stats: ProjectStats
classes: LabelClass[] classes: LabelClass[]
memberNames: string[]
} }
const STATUS_BADGE_MAP: Record< const STATUS_BADGE_MAP: Record<
@ -41,40 +44,93 @@ const STATUS_BADGE_MAP: Record<
}, },
} }
const PAGE_SIZE = 50
export const ImageTable: React.FC<ImageTableProps> = ({ export const ImageTable: React.FC<ImageTableProps> = ({
projectId, projectId,
projectSlug, projectSlug,
images,
stats, stats,
classes, classes,
memberNames,
}) => { }) => {
const navigate = useNavigate() const navigate = useNavigate()
const [searchQuery, setSearchQuery] = useState('') const [searchQuery, setSearchQuery] = useState('')
const [selectedStatus, setSelectedStatus] = useState<'all' | ImageAnnotationStatus>('all') const [selectedStatus, setSelectedStatus] = useState<'all' | ImageAnnotationStatus>('all')
const [selectedMember, setSelectedMember] = useState('all') const [selectedMember, setSelectedMember] = useState('all')
const [page, setPage] = useState(0)
const [rows, setRows] = useState<ImageItem[]>([])
const [total, setTotal] = useState(0)
const [isLoading, setIsLoading] = useState(false)
const [mockExportRows, setMockExportRows] = useState<ImageItem[]>([])
const memberNames = useMemo(() => { const debouncedSearch = useDebounce(searchQuery, 400)
const set = new Set<string>()
images.forEach((img) => set.add(img.assignedTo.name))
return Array.from(set)
}, [images])
const filteredImages = useMemo(() => { useEffect(() => {
return images.filter((img) => { let cancelled = false
const matchSearch = setIsLoading(true)
!searchQuery.trim() || const load = async () => {
img.fileName.toLowerCase().includes(searchQuery.trim().toLowerCase()) if (USE_MOCK_DATA) {
const all = await getProjectImages(projectId)
const q = debouncedSearch.trim().toLowerCase()
const filtered = all.filter((img) => {
const matchSearch = !q || img.fileName.toLowerCase().includes(q)
const matchStatus = selectedStatus === 'all' || img.status === selectedStatus const matchStatus = selectedStatus === 'all' || img.status === selectedStatus
const matchMember = selectedMember === 'all' || img.assignedTo.name === selectedMember const matchMember = selectedMember === 'all' || img.assignedTo.name === selectedMember
return matchSearch && matchStatus && matchMember return matchSearch && matchStatus && matchMember
}) })
}, [images, searchQuery, selectedStatus, selectedMember]) if (!cancelled) {
setTotal(filtered.length)
setRows(filtered.slice(page * PAGE_SIZE, page * PAGE_SIZE + PAGE_SIZE))
setMockExportRows(filtered)
setIsLoading(false)
}
return
}
try {
const data = await getProjectImagesPage(projectId, {
status: selectedStatus,
search: debouncedSearch,
assignee: selectedMember,
limit: PAGE_SIZE,
offset: page * PAGE_SIZE,
})
if (!cancelled) {
setRows(data.items)
setTotal(data.total)
setIsLoading(false)
}
} catch {
if (!cancelled) {
setRows([])
setTotal(0)
setIsLoading(false)
}
}
}
void load()
return () => {
cancelled = true
}
}, [projectId, debouncedSearch, selectedStatus, selectedMember, page])
const resetPage = (fn: (v: string) => void) => (v: string) => {
setPage(0)
fn(v)
}
const totalObjects = const totalObjects =
stats.totalObjects ?? stats.totalObjects ??
classes.reduce((sum, cls) => sum + cls.count, 0) classes.reduce((sum, cls) => sum + cls.count, 0)
const formatNum = (n: number) => n.toLocaleString('vi-VN') const formatNum = (n: number) => n.toLocaleString('vi-VN')
const pageCount = Math.max(1, Math.ceil(total / PAGE_SIZE))
const from = total === 0 ? 0 : page * PAGE_SIZE + 1
const to = Math.min(total, page * PAGE_SIZE + rows.length)
const shownImages = useMemo(
() => (USE_MOCK_DATA ? mockExportRows : rows),
[mockExportRows, rows]
)
return ( return (
<div className="overflow-hidden rounded-xl border border-[var(--project-border)] bg-[var(--project-surface)]"> <div className="overflow-hidden rounded-xl border border-[var(--project-border)] bg-[var(--project-surface)]">
@ -89,14 +145,15 @@ export const ImageTable: React.FC<ImageTableProps> = ({
<ImageTableFilters <ImageTableFilters
searchQuery={searchQuery} searchQuery={searchQuery}
onSearchChange={setSearchQuery} onSearchChange={resetPage(setSearchQuery)}
selectedStatus={selectedStatus} selectedStatus={selectedStatus}
onStatusChange={setSelectedStatus} onStatusChange={resetPage(setSelectedStatus as (v: string) => void)}
selectedMember={selectedMember} selectedMember={selectedMember}
onMemberChange={setSelectedMember} onMemberChange={resetPage(setSelectedMember)}
memberNames={memberNames} memberNames={memberNames}
projectId={projectId}
projectSlug={projectSlug} projectSlug={projectSlug}
images={images} images={shownImages}
classes={classes} classes={classes}
/> />
</div> </div>
@ -114,14 +171,20 @@ export const ImageTable: React.FC<ImageTableProps> = ({
</tr> </tr>
</thead> </thead>
<tbody className="divide-y divide-[var(--project-border)] text-xs"> <tbody className="divide-y divide-[var(--project-border)] text-xs">
{filteredImages.length === 0 ? ( {isLoading && rows.length === 0 ? (
<tr>
<td colSpan={5} className="py-10 text-center text-[var(--project-body)]">
Đang tải ảnh...
</td>
</tr>
) : rows.length === 0 ? (
<tr> <tr>
<td colSpan={5} className="py-10 text-center text-[var(--project-body)]"> <td colSpan={5} className="py-10 text-center text-[var(--project-body)]">
Không tìm thấy ảnh phù hợp với bộ lọc hiện tại. Không tìm thấy ảnh phù hợp với bộ lọc hiện tại.
</td> </td>
</tr> </tr>
) : ( ) : (
filteredImages.map((image) => { rows.map((image) => {
const badge = STATUS_BADGE_MAP[image.status] const badge = STATUS_BADGE_MAP[image.status]
return ( return (
<tr <tr
@ -134,9 +197,14 @@ export const ImageTable: React.FC<ImageTableProps> = ({
<td className="py-3.5 pl-5 pr-4"> <td className="py-3.5 pl-5 pr-4">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<img <img
src={image.thumbnailUrl} src={image.thumbnailSmallUrl ?? image.thumbnailUrl}
alt={image.fileName} alt={image.fileName}
className="h-9 w-[54px] shrink-0 rounded object-cover" loading="lazy"
decoding="async"
onError={(e) => {
e.currentTarget.style.display = 'none'
}}
className="h-9 w-[54px] shrink-0 rounded bg-slate-100 object-cover"
/> />
<div> <div>
<p className="font-mono text-[11px] text-[var(--project-heading)]"> <p className="font-mono text-[11px] text-[var(--project-heading)]">
@ -185,6 +253,34 @@ export const ImageTable: React.FC<ImageTableProps> = ({
</tbody> </tbody>
</table> </table>
</div> </div>
{/* Pagination: one screenful per request, never the whole dataset */}
<div className="flex items-center justify-between border-t border-[var(--project-border)] px-5 py-3 text-[11px] text-[var(--project-body)]">
<span>
Hiển thị {formatNum(from)}–{formatNum(to)} / {formatNum(total)} ảnh
</span>
<div className="flex items-center gap-2">
<button
type="button"
disabled={page === 0}
onClick={() => setPage((p) => Math.max(0, p - 1))}
className="rounded-lg border border-[var(--project-border)] px-3 py-1.5 font-medium transition hover:bg-[var(--project-canvas)] disabled:opacity-40"
>
← Trước
</button>
<span className="tabular-nums">
Trang {page + 1} / {formatNum(pageCount)}
</span>
<button
type="button"
disabled={page + 1 >= pageCount}
onClick={() => setPage((p) => p + 1)}
className="rounded-lg border border-[var(--project-border)] px-3 py-1.5 font-medium transition hover:bg-[var(--project-canvas)] disabled:opacity-40"
>
Tiếp →
</button>
</div>
</div>
</div> </div>
) )
} }

View file

@ -10,6 +10,7 @@ interface ImageTableFiltersProps {
selectedMember: string selectedMember: string
onMemberChange: (val: string) => void onMemberChange: (val: string) => void
memberNames: string[] memberNames: string[]
projectId?: string
projectSlug?: string projectSlug?: string
images?: ImageItem[] images?: ImageItem[]
classes?: LabelClass[] classes?: LabelClass[]
@ -23,6 +24,7 @@ export const ImageTableFilters: React.FC<ImageTableFiltersProps> = ({
selectedMember, selectedMember,
onMemberChange, onMemberChange,
memberNames, memberNames,
projectId,
projectSlug, projectSlug,
images, images,
classes, classes,
@ -104,7 +106,7 @@ export const ImageTableFilters: React.FC<ImageTableFiltersProps> = ({
</div> </div>
</div> </div>
<ExportButton projectSlug={projectSlug} images={images} classes={classes} /> <ExportButton projectId={projectId} projectSlug={projectSlug} images={images} classes={classes} />
</div> </div>
) )
} }

View file

@ -1,5 +1,5 @@
import React from 'react' import React from 'react'
import { ImageItem, Project } from '@/types' import { Project } from '@/types'
import { StatusCards } from './StatusCards' import { StatusCards } from './StatusCards'
import { LabelDistribution } from './LabelDistribution' import { LabelDistribution } from './LabelDistribution'
import { MemberAssignment } from './MemberAssignment' import { MemberAssignment } from './MemberAssignment'
@ -7,13 +7,11 @@ import { ImageTable } from './ImageTable'
interface OverviewTabProps { interface OverviewTabProps {
project: Project project: Project
images: ImageItem[]
onSwitchTab: (tab: 'overview' | 'data' | 'labels' | 'members' | 'settings') => void onSwitchTab: (tab: 'overview' | 'data' | 'labels' | 'members' | 'settings') => void
} }
export const OverviewTab: React.FC<OverviewTabProps> = ({ export const OverviewTab: React.FC<OverviewTabProps> = ({
project, project,
images,
onSwitchTab, onSwitchTab,
}) => { }) => {
return ( return (
@ -38,13 +36,13 @@ export const OverviewTab: React.FC<OverviewTabProps> = ({
</div> </div>
</div> </div>
{/* Image Table */} {/* Image Table (self-paginated; never the whole dataset) */}
<ImageTable <ImageTable
projectId={project.id} projectId={project.id}
projectSlug={project.slug} projectSlug={project.slug}
images={images}
stats={project.stats} stats={project.stats}
classes={project.classes} classes={project.classes}
memberNames={project.members.map((m) => m.name)}
/> />
<section className="overflow-hidden rounded-xl border border-[var(--project-border)] bg-[var(--project-surface)]"> <section className="overflow-hidden rounded-xl border border-[var(--project-border)] bg-[var(--project-surface)]">

View file

@ -1,5 +1,6 @@
import { AnnotationShape, ImageAnnotationData, ImageItem } from '@/types' import { AnnotationShape, ImageAnnotationData, ImageItem } from '@/types'
import { delay } from './api' import { USE_MOCK_DATA } from '@/app/constants'
import { api, delay } from './api'
import { updateImageStatus } from './imageService' import { updateImageStatus } from './imageService'
import { getMockDb, saveMockDb } from './mockData' import { getMockDb, saveMockDb } from './mockData'
@ -16,6 +17,17 @@ export async function getAnnotation(
projectId: string, projectId: string,
imageId: string imageId: string
): Promise<ImageAnnotationData> { ): Promise<ImageAnnotationData> {
if (!USE_MOCK_DATA) {
const { data } = await api.get<any>(`/projects/${projectId}/images/${imageId}/annotation`)
return {
imageId: data.imageId,
projectId: data.projectId,
classificationLabelId: data.classificationLabelId,
flags: data.flags,
shapes: data.shapes ?? [],
updatedAt: 'Vừa đồng bộ',
}
}
await delay(90) await delay(90)
const db = getMockDb() const db = getMockDb()
const key = `${projectId}:${imageId}` const key = `${projectId}:${imageId}`
@ -52,6 +64,24 @@ export async function saveAnnotation(
imageId: string, imageId: string,
data: SaveAnnotationInput data: SaveAnnotationInput
): Promise<ImageAnnotationData> { ): Promise<ImageAnnotationData> {
if (!USE_MOCK_DATA) {
await api.put(`/projects/${projectId}/images/${imageId}/annotation`, {
classificationLabelId: data.classificationLabelId,
flags: data.flags,
shapes: data.shapes.map((shape, idx) => ({ ...shape, index: idx + 1 })),
})
return {
imageId,
projectId,
classificationLabelId: data.classificationLabelId,
flags: {
blurryOrUncertain: Boolean(data.flags.blurryOrUncertain),
needsRecheck: Boolean(data.flags.needsRecheck),
},
shapes: data.shapes.map((shape, idx) => ({ ...shape, index: idx + 1 })),
updatedAt: 'Vừa lưu',
}
}
await delay(100) await delay(100)
const db = getMockDb() const db = getMockDb()
const key = `${projectId}:${imageId}` const key = `${projectId}:${imageId}`

View file

@ -1,5 +1,6 @@
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios' import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios'
import { API_BASE_URL, STORAGE_KEYS } from '@/app/constants' import { API_BASE_URL, STORAGE_KEYS } from '@/app/constants'
import { getSessionId } from '@/utils/session'
import { getStorageItem, removeStorageItem } from '@/utils/storage' import { getStorageItem, removeStorageItem } from '@/utils/storage'
export const api = axios.create({ export const api = axios.create({
@ -16,6 +17,10 @@ api.interceptors.request.use(
if (token && config.headers) { if (token && config.headers) {
config.headers.Authorization = `Bearer ${token}` config.headers.Authorization = `Bearer ${token}`
} }
if (config.headers) {
// One session per visit: backend groups every operation by this ID.
config.headers['X-Session-ID'] = getSessionId()
}
return config return config
}, },
(error: AxiosError) => Promise.reject(error) (error: AxiosError) => Promise.reject(error)
@ -27,6 +32,9 @@ api.interceptors.response.use(
if (error.response?.status === 401) { if (error.response?.status === 401) {
removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN) removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN)
removeStorageItem(STORAGE_KEYS.REFRESH_TOKEN) removeStorageItem(STORAGE_KEYS.REFRESH_TOKEN)
if (typeof window !== 'undefined' && !window.location.pathname.startsWith('/login')) {
window.location.href = '/login'
}
} }
return Promise.reject(error) return Promise.reject(error)
} }

View file

@ -1,10 +1,24 @@
import { STORAGE_KEYS } from '@/app/constants' import { STORAGE_KEYS, USE_MOCK_DATA } from '@/app/constants'
import { LoginRequest, LoginResponse, User, UserRole } from '@/types' import { LoginRequest, LoginResponse, User, UserRole } from '@/types'
import { getStorageItem, removeStorageItem, setStorageItem } from '@/utils/storage' import { getStorageItem, removeStorageItem, setStorageItem } from '@/utils/storage'
import { delay } from './api' import { api, delay } from './api'
import { DEFAULT_USER, getMockDb, saveMockDb } from './mockData' import { DEFAULT_USER, getMockDb, saveMockDb } from './mockData'
function persistSession(response: LoginResponse): void {
setStorageItem(STORAGE_KEYS.ACCESS_TOKEN, response.accessToken)
setStorageItem(STORAGE_KEYS.REFRESH_TOKEN, response.refreshToken)
setStorageItem(STORAGE_KEYS.CURRENT_USER, response.user)
}
export async function login(payload: LoginRequest): Promise<LoginResponse> { export async function login(payload: LoginRequest): Promise<LoginResponse> {
if (!USE_MOCK_DATA) {
const { data } = await api.post<LoginResponse>('/auth/login', {
email: payload.email,
password: payload.password ?? '',
})
persistSession(data)
return data
}
await delay(250) await delay(250)
const db = getMockDb() const db = getMockDb()
const matchedMember = db.members.find( const matchedMember = db.members.find(
@ -37,10 +51,7 @@ export async function login(payload: LoginRequest): Promise<LoginResponse> {
refreshToken: `mock-refresh-token-${user.id}-${Date.now()}`, refreshToken: `mock-refresh-token-${user.id}-${Date.now()}`,
} }
setStorageItem(STORAGE_KEYS.ACCESS_TOKEN, response.accessToken) persistSession(response)
setStorageItem(STORAGE_KEYS.REFRESH_TOKEN, response.refreshToken)
setStorageItem(STORAGE_KEYS.CURRENT_USER, user)
return response return response
} }
@ -60,14 +71,17 @@ export async function loginWithSSO(provider: 'google' | 'microsoft' | 'sso' = 's
refreshToken: `mock-sso-refresh-${provider}-${Date.now()}`, refreshToken: `mock-sso-refresh-${provider}-${Date.now()}`,
} }
setStorageItem(STORAGE_KEYS.ACCESS_TOKEN, response.accessToken) persistSession(response)
setStorageItem(STORAGE_KEYS.REFRESH_TOKEN, response.refreshToken)
setStorageItem(STORAGE_KEYS.CURRENT_USER, user)
return response return response
} }
export async function logout(): Promise<void> { export async function logout(): Promise<void> {
if (!USE_MOCK_DATA) {
removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN)
removeStorageItem(STORAGE_KEYS.REFRESH_TOKEN)
removeStorageItem(STORAGE_KEYS.CURRENT_USER)
return
}
await delay(100) await delay(100)
removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN) removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN)
removeStorageItem(STORAGE_KEYS.REFRESH_TOKEN) removeStorageItem(STORAGE_KEYS.REFRESH_TOKEN)
@ -75,6 +89,17 @@ export async function logout(): Promise<void> {
} }
export async function getCurrentUser(): Promise<User> { export async function getCurrentUser(): Promise<User> {
if (!USE_MOCK_DATA) {
try {
const { data } = await api.get<User>('/auth/me')
setStorageItem(STORAGE_KEYS.CURRENT_USER, data)
return data
} catch {
const stored = getStorageItem<User | null>(STORAGE_KEYS.CURRENT_USER, null)
if (stored) return stored
throw new Error('Phiên đăng nhập đã hết hạn, vui lòng đăng nhập lại')
}
}
await delay(80) await delay(80)
const storedUser = getStorageItem<User | null>(STORAGE_KEYS.CURRENT_USER, null) const storedUser = getStorageItem<User | null>(STORAGE_KEYS.CURRENT_USER, null)
if (storedUser) return storedUser if (storedUser) return storedUser

View file

@ -0,0 +1,40 @@
// Fire-and-forget client action log. The backend already logs server-side
// operations; this covers UI-only thao tác (status changes, exports) so the
// session timeline is complete for replay. Never throws, never blocks UI.
import { api } from './api'
import { getSessionId } from '@/utils/session'
interface TrackedEvent {
action: string
project_id?: string
image_id?: string
payload?: Record<string, unknown>
}
const buffer: TrackedEvent[] = []
let timer: ReturnType<typeof setTimeout> | null = null
async function flush(): Promise<void> {
timer = null
if (buffer.length === 0) return
const events = buffer.splice(0, buffer.length)
try {
await api.post('/events', { session_id: getSessionId(), events })
} catch {
// Backend down or mock mode: drop, UI keeps working.
}
}
export function track(
action: TrackedEvent['action'],
opts: Omit<TrackedEvent, 'action'> = {}
): void {
buffer.push({ action, ...opts })
if (buffer.length >= 20) {
void flush()
return
}
if (timer === null) {
timer = setTimeout(() => void flush(), 3000)
}
}

View file

@ -1,8 +1,12 @@
import { AnnotationShape, ImageItem } from '@/types' import { AnnotationShape, ImageItem } from '@/types'
import { exportToLabelMeJSON, LabelMeJSON } from '@/utils/labelme' import { exportToLabelMeJSON, LabelMeJSON } from '@/utils/labelme'
import { exportSegmentationMaskPNG } from '@/utils/mask' import { exportSegmentationMaskPNG } from '@/utils/mask'
import { USE_MOCK_DATA } from '@/app/constants'
import { getAnnotation } from './annotationService'
import { delay } from './api' import { delay } from './api'
import { getProjectImages } from './imageService'
import { getMockDb } from './mockData' import { getMockDb } from './mockData'
import { getProjectById } from './projectService'
export type ExportFormat = 'labelme_json' | 'coco_json' | 'yolo_txt' | 'mask_png' export type ExportFormat = 'labelme_json' | 'coco_json' | 'yolo_txt' | 'mask_png'
@ -10,6 +14,33 @@ export async function exportProjectLabels(
projectId: string, projectId: string,
format: ExportFormat = 'coco_json' format: ExportFormat = 'coco_json'
): Promise<{ fileName: string; recordCount: number }> { ): Promise<{ fileName: string; recordCount: number }> {
if (!USE_MOCK_DATA) {
const project = await getProjectById(projectId)
const images = await getProjectImages(project.id)
const rows = await Promise.all(
images.map(async (img) => {
const ann = await getAnnotation(project.id, img.id)
return {
id: img.id,
fileName: img.fileName,
width: img.width,
height: img.height,
status: img.status,
classificationLabelId: ann.classificationLabelId ?? img.classificationLabelId,
shapes: ann.shapes,
}
})
)
const fileName = `${project.slug || 'dataset'}_${format}.json`
const blob = new Blob(
[JSON.stringify({ project: { id: project.id, slug: project.slug, format }, images: rows }, null, 2)],
{ type: 'application/json;charset=utf-8' }
)
triggerDownload(URL.createObjectURL(blob), fileName)
return { fileName, recordCount: images.length }
}
await delay(250) await delay(250)
const db = getMockDb() const db = getMockDb()
const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) ?? db.projects[0] const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) ?? db.projects[0]
@ -46,6 +77,17 @@ export async function exportProjectLabels(
type: 'application/json;charset=utf-8', type: 'application/json;charset=utf-8',
}) })
const url = URL.createObjectURL(blob) const url = URL.createObjectURL(blob)
triggerDownload(url, fileName)
}
return {
fileName,
recordCount: images.length,
}
}
function triggerDownload(url: string, fileName: string): void {
if (typeof document === 'undefined') return
const link = document.createElement('a') const link = document.createElement('a')
link.href = url link.href = url
link.download = fileName link.download = fileName
@ -55,12 +97,6 @@ export async function exportProjectLabels(
URL.revokeObjectURL(url) URL.revokeObjectURL(url)
} }
return {
fileName,
recordCount: images.length,
}
}
export function downloadImageLabelMeJSON( export function downloadImageLabelMeJSON(
image: ImageItem, image: ImageItem,
shapes: AnnotationShape[] shapes: AnnotationShape[]

View file

@ -1,7 +1,52 @@
import { ImageAnnotationStatus, ImageItem } from '@/types' import { ImageAnnotationStatus, ImageItem } from '@/types'
import { delay } from './api' import { USE_MOCK_DATA } from '@/app/constants'
import { api, delay } from './api'
import { track } from './eventService'
import { getMockDb, getRandomStreetPhoto, saveMockDb } from './mockData' import { getMockDb, getRandomStreetPhoto, saveMockDb } from './mockData'
export interface UploadFileItem {
fileName: string
url?: string
width?: number
height?: number
file?: File
}
export function mapImage(raw: any): ImageItem {
return {
id: raw.id,
projectId: raw.projectId,
fileName: raw.fileName,
url: raw.url,
thumbnailUrl: raw.thumbnailUrl ?? raw.url,
thumbnailSmallUrl: raw.thumbnailSmallUrl ?? raw.thumbnailUrl ?? raw.url,
width: raw.width ?? 0,
height: raw.height ?? 0,
status: raw.status,
objectCount: raw.objectCount ?? 0,
classificationLabelId: raw.classificationLabelId,
flags: raw.flags ?? {},
assignedTo: {
id: raw.assignedTo ?? 'unassigned',
name: raw.assignedToName || 'Chưa gán',
role: 'annotator',
},
reviewerName: raw.reviewerName,
savedAt: 'Vừa đồng bộ',
}
}
async function readDimensions(file: File): Promise<{ width: number; height: number }> {
try {
const bmp = await createImageBitmap(file)
const dims = { width: bmp.width, height: bmp.height }
bmp.close()
return dims
} catch {
return { width: 0, height: 0 }
}
}
export interface ImageFilterParams { export interface ImageFilterParams {
status?: ImageAnnotationStatus | 'all' status?: ImageAnnotationStatus | 'all'
assigneeId?: string | 'all' assigneeId?: string | 'all'
@ -9,10 +54,63 @@ export interface ImageFilterParams {
search?: string search?: string
} }
export interface ImagePage {
items: ImageItem[]
total: number
}
export async function getProjectImagesPage(
projectId: string,
params: {
status?: ImageAnnotationStatus | 'all'
search?: string
assignee?: string
limit?: number
offset?: number
} = {}
): Promise<ImagePage> {
const { data } = await api.get<{ items: any[]; total: number }>(
`/projects/${projectId}/images`,
{
params: {
status: params.status ?? 'all',
search: params.search || undefined,
assignee: params.assignee && params.assignee !== 'all' ? params.assignee : undefined,
limit: params.limit ?? 50,
offset: params.offset ?? 0,
},
}
)
return { items: data.items.map(mapImage), total: data.total }
}
export async function getProjectImages( export async function getProjectImages(
projectId: string, projectId: string,
filters?: ImageFilterParams filters?: ImageFilterParams
): Promise<ImageItem[]> { ): Promise<ImageItem[]> {
if (!USE_MOCK_DATA) {
// Full-list consumers (annotator navigation, export): walk all pages.
// Metadata only (~200 rows/call); bytes still load per-image on demand.
const items: ImageItem[] = []
const limit = 200
let offset = 0
for (;;) {
const page = await getProjectImagesPage(projectId, {
status: filters?.status ?? 'all',
search: filters?.search,
limit,
offset,
})
items.push(...page.items)
if (items.length >= page.total || page.items.length === 0) break
offset += limit
}
// assigneeId here is a user id; the page API filters by name instead.
if (filters?.assigneeId && filters.assigneeId !== 'all') {
return items.filter((img) => img.assignedTo.id === filters.assigneeId)
}
return items
}
await delay(120) await delay(120)
const db = getMockDb() const db = getMockDb()
let items = db.images.filter((img) => img.projectId === projectId) let items = db.images.filter((img) => img.projectId === projectId)
@ -42,6 +140,15 @@ export async function getProjectImages(
} }
export async function getImageById(projectId: string, imageId: string): Promise<ImageItem> { export async function getImageById(projectId: string, imageId: string): Promise<ImageItem> {
if (!USE_MOCK_DATA) {
const items = await getProjectImages(projectId)
const found =
items.find((img) => img.id === imageId || img.fileName === imageId) ?? items[0]
if (!found) {
throw new Error(`Không tìm thấy ảnh: ${imageId}`)
}
return found
}
await delay(80) await delay(80)
const db = getMockDb() const db = getMockDb()
const projectImages = db.images.filter((img) => img.projectId === projectId) const projectImages = db.images.filter((img) => img.projectId === projectId)
@ -59,8 +166,48 @@ export async function getImageById(projectId: string, imageId: string): Promise<
export async function uploadImages( export async function uploadImages(
projectId: string, projectId: string,
files: { fileName: string; url?: string; width?: number; height?: number }[] files: UploadFileItem[]
): Promise<ImageItem[]> { ): Promise<ImageItem[]> {
if (!USE_MOCK_DATA) {
// Real flow: presign -> PUT bytes straight to R2 -> confirm metadata.
const created: ImageItem[] = []
for (const f of files) {
if (!f.file) {
throw new Error(`Thiếu dữ liệu file cho "${f.fileName}": hãy tải lên từ thiết bị`)
}
const dims = await readDimensions(f.file)
const { data: presigned } = await api.post<{ putUrl: string; r2Key: string }>(
`/projects/${projectId}/images/presign`,
{ fileName: f.fileName, contentType: f.file.type || 'image/jpeg' }
)
const putRes = await fetch(presigned.putUrl, {
method: 'PUT',
headers: { 'Content-Type': f.file.type || 'image/jpeg' },
body: f.file,
})
if (!putRes.ok) {
throw new Error(`Tải "${f.fileName}" lên kho lưu trữ thất bại (${putRes.status})`)
}
const { data: confirmed } = await api.post<{ id: string; r2Key: string; url: string }>(
`/projects/${projectId}/images`,
{ fileName: f.fileName, r2Key: presigned.r2Key, width: dims.width, height: dims.height }
)
created.push(
mapImage({
id: confirmed.id,
projectId,
fileName: f.fileName,
url: confirmed.url,
width: dims.width,
height: dims.height,
status: 'in_progress',
objectCount: 0,
flags: {},
})
)
}
return created
}
await delay(300) await delay(300)
const db = getMockDb() const db = getMockDb()
const created: ImageItem[] = [] const created: ImageItem[] = []
@ -122,6 +269,10 @@ export async function updateImageStatus(
imageId: string, imageId: string,
status: ImageAnnotationStatus status: ImageAnnotationStatus
): Promise<ImageItem> { ): Promise<ImageItem> {
if (!USE_MOCK_DATA) {
await api.patch(`/projects/${projectId}/images/${imageId}`, null, { params: { status } })
return getImageById(projectId, imageId)
}
await delay(120) await delay(120)
const db = getMockDb() const db = getMockDb()
const idx = db.images.findIndex((img) => img.projectId === projectId && img.id === imageId) const idx = db.images.findIndex((img) => img.projectId === projectId && img.id === imageId)
@ -133,6 +284,11 @@ export async function updateImageStatus(
const current = db.images[targetIdx]! const current = db.images[targetIdx]!
const prevStatus = current.status const prevStatus = current.status
track('image.status', {
project_id: projectId,
image_id: imageId,
payload: { from: prevStatus, to: status },
})
const updated: ImageItem = { const updated: ImageItem = {
...current, ...current,
status, status,

View file

@ -1,19 +1,52 @@
import { LabelClass } from '@/types' import { LabelClass } from '@/types'
import { USE_MOCK_DATA } from '@/app/constants'
import { getColorForClass } from '@/utils/colors' import { getColorForClass } from '@/utils/colors'
import { delay } from './api' import { api, delay } from './api'
import { getMockDb, saveMockDb } from './mockData' import { getMockDb, saveMockDb } from './mockData'
import { getProjectById } from './projectService'
export async function getLabels(projectId: string): Promise<LabelClass[]> { export async function getLabels(projectId: string): Promise<LabelClass[]> {
if (!USE_MOCK_DATA) {
const project = await getProjectById(projectId)
return project.classes
}
await delay(80) await delay(80)
const db = getMockDb() const db = getMockDb()
const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) const project = db.projects.find((p) => p.id === projectId || p.slug === projectId)
return project ? project.classes : db.projects[0]?.classes ?? [] return project ? project.classes : db.projects[0]?.classes ?? []
} }
export async function replaceLabels(
projectId: string,
classes: LabelClass[]
): Promise<LabelClass[]> {
const { data } = await api.put<any[]>(`/projects/${projectId}/classes`, classes)
return data.map((c: any, i: number) => ({
id: c.id,
name: c.name,
color: c.color,
count: 0,
shortcutKey: String(i + 1),
}))
}
export async function createLabel( export async function createLabel(
projectId: string, projectId: string,
input: { name: string; color?: string } input: { name: string; color?: string }
): Promise<LabelClass> { ): Promise<LabelClass> {
if (!USE_MOCK_DATA) {
const existing = await getLabels(projectId)
const next: LabelClass = {
id: `cls-new-${Date.now()}`,
name: input.name.trim(),
color: input.color || getColorForClass(existing.length),
count: 0,
shortcutKey: String(existing.length + 1),
}
const replaced = await replaceLabels(projectId, [...existing, next])
const created = replaced.find((c) => c.name === next.name) ?? replaced[replaced.length - 1]!
return created
}
await delay(140) await delay(140)
const db = getMockDb() const db = getMockDb()
const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) const project = db.projects.find((p) => p.id === projectId || p.slug === projectId)
@ -36,6 +69,14 @@ export async function createLabel(
} }
export async function deleteLabel(projectId: string, labelId: string): Promise<void> { export async function deleteLabel(projectId: string, labelId: string): Promise<void> {
if (!USE_MOCK_DATA) {
const existing = await getLabels(projectId)
await replaceLabels(
projectId,
existing.filter((c) => c.id !== labelId)
)
return
}
await delay(120) await delay(120)
const db = getMockDb() const db = getMockDb()
const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) const project = db.projects.find((p) => p.id === projectId || p.slug === projectId)

View file

@ -529,7 +529,7 @@ const INITIAL_ACTIVITIES: ActivityLog[] = [
}, },
] ]
const INITIAL_ROLE_PERMISSIONS: RolePermissionItem[] = [ export const INITIAL_ROLE_PERMISSIONS: RolePermissionItem[] = [
{ {
role: 'admin', role: 'admin',
title: 'Admin (Quản trị viên)', title: 'Admin (Quản trị viên)',

View file

@ -1,7 +1,49 @@
import { ActivityLog, CreateProjectInput, Project, ProjectStatus, TaskType } from '@/types' import { ActivityLog, CreateProjectInput, LabelClass, Project, ProjectStatus, TaskType } from '@/types'
import { delay } from './api' import { USE_MOCK_DATA } from '@/app/constants'
import { api, delay } from './api'
import { getMockDb, getRandomStreetPhoto, saveMockDb } from './mockData' import { getMockDb, getRandomStreetPhoto, saveMockDb } from './mockData'
export function mapProject(raw: any): Project {
return {
id: raw.id,
name: raw.name,
slug: raw.slug,
description: raw.description ?? '',
taskType: raw.taskType,
status: raw.status,
thumbnailUrl: raw.thumbnailUrl ?? '',
updatedAt: raw.updatedAt ?? '',
classes: (raw.classes ?? []).map((c: any, i: number) => ({
id: c.id,
name: c.name,
color: c.color,
count: c.count ?? 0,
shortcutKey: String(i + 1),
})) as LabelClass[],
stats: raw.stats ?? {
totalImages: 0,
unassigned: 0,
inProgress: 0,
pendingReview: 0,
completed: 0,
totalObjects: 0,
},
members: raw.members ?? [],
}
}
export function slugifyProjectName(name: string): string {
return (
name
.toLowerCase()
.normalize('NFD')
.replace(/[\u0300-\u036f]/g, '')
.replace(/đ/g, 'd')
.replace(/[^a-z0-9]+/g, '_')
.replace(/^_|_$/g, '') + '_v1'
)
}
export interface ProjectFilterParams { export interface ProjectFilterParams {
search?: string search?: string
taskType?: TaskType | 'all' taskType?: TaskType | 'all'
@ -9,6 +51,10 @@ export interface ProjectFilterParams {
} }
export async function getProjects(params?: ProjectFilterParams): Promise<Project[]> { export async function getProjects(params?: ProjectFilterParams): Promise<Project[]> {
if (!USE_MOCK_DATA) {
const { data } = await api.get<any[]>('/projects')
return applyFilters(data.map(mapProject), params)
}
await delay(150) await delay(150)
const db = getMockDb() const db = getMockDb()
let list = [...db.projects] let list = [...db.projects]
@ -35,6 +81,10 @@ export async function getProjects(params?: ProjectFilterParams): Promise<Project
} }
export async function getProjectById(projectId: string): Promise<Project> { export async function getProjectById(projectId: string): Promise<Project> {
if (!USE_MOCK_DATA) {
const { data } = await api.get<any>(`/projects/${projectId}`)
return mapProject(data)
}
await delay(120) await delay(120)
const db = getMockDb() const db = getMockDb()
const found = const found =
@ -45,7 +95,38 @@ export async function getProjectById(projectId: string): Promise<Project> {
return found return found
} }
function applyFilters(list: Project[], params?: ProjectFilterParams): Project[] {
if (params?.search && params.search.trim() !== '') {
const q = params.search.trim().toLowerCase()
list = list.filter(
(p) =>
p.name.toLowerCase().includes(q) ||
p.slug.toLowerCase().includes(q) ||
p.description.toLowerCase().includes(q)
)
}
if (params?.taskType && params.taskType !== 'all') {
list = list.filter((p) => p.taskType === params.taskType)
}
if (params?.status && params.status !== 'all') {
list = list.filter((p) => p.status === params.status)
}
return list
}
export async function createProject(input: CreateProjectInput): Promise<Project> { export async function createProject(input: CreateProjectInput): Promise<Project> {
if (!USE_MOCK_DATA) {
const { data } = await api.post<any>('/projects', {
name: input.name.trim(),
slug: slugifyProjectName(input.name),
description: input.description.trim(),
taskType: input.taskType,
})
return mapProject(data)
}
await delay(250) await delay(250)
const db = getMockDb() const db = getMockDb()
@ -185,6 +266,16 @@ export async function updateProject(
projectId: string, projectId: string,
updates: Partial<Project> updates: Partial<Project>
): Promise<Project> { ): Promise<Project> {
if (!USE_MOCK_DATA) {
const { data } = await api.patch<any>(`/projects/${projectId}`, {
name: updates.name,
slug: updates.slug,
description: updates.description,
task_type: updates.taskType,
status: updates.status,
})
return mapProject(data)
}
await delay(180) await delay(180)
const db = getMockDb() const db = getMockDb()
const idx = db.projects.findIndex((p) => p.id === projectId) const idx = db.projects.findIndex((p) => p.id === projectId)
@ -203,6 +294,10 @@ export async function updateProject(
} }
export async function deleteProject(projectId: string): Promise<void> { export async function deleteProject(projectId: string): Promise<void> {
if (!USE_MOCK_DATA) {
await api.delete(`/projects/${projectId}`)
return
}
await delay(180) await delay(180)
const db = getMockDb() const db = getMockDb()
db.projects = db.projects.filter((p) => p.id !== projectId) db.projects = db.projects.filter((p) => p.id !== projectId)
@ -211,6 +306,10 @@ export async function deleteProject(projectId: string): Promise<void> {
} }
export async function getRecentActivities(): Promise<ActivityLog[]> { export async function getRecentActivities(): Promise<ActivityLog[]> {
if (!USE_MOCK_DATA) {
const { data } = await api.get<ActivityLog[]>('/activities', { params: { limit: 30 } })
return data
}
await delay(100) await delay(100)
const db = getMockDb() const db = getMockDb()
return db.activities return db.activities

View file

@ -1,8 +1,44 @@
import { InviteMemberInput, RolePermissionItem, UserRole, UserStatus, WorkspaceMember } from '@/types' import { InviteMemberInput, RolePermissionItem, UserRole, UserStatus, WorkspaceMember } from '@/types'
import { USE_MOCK_DATA } from '@/app/constants'
import { getColorForClass } from '@/utils/colors' import { getColorForClass } from '@/utils/colors'
import { delay } from './api' import { INITIAL_ROLE_PERMISSIONS } from './mockData'
import { api, delay } from './api'
import { getMockDb, saveMockDb } from './mockData' import { getMockDb, saveMockDb } from './mockData'
const ACCESS_SUMMARY: Record<UserRole, string> = {
admin: 'Toàn quyền hệ thống',
manager: 'Tạo dự án · Gán việc · Duyệt nhãn',
reviewer: 'Kiểm duyệt · Phê duyệt / Từ chối',
annotator: 'Vẽ BBox, Polygon · Nộp duyệt',
}
function initialsOf(name: string): string {
const parts = name.trim().split(/\s+/)
if (parts.length >= 2) {
return `${parts[0]?.[0] ?? ''}${parts[parts.length - 1]?.[0] ?? ''}`.toUpperCase()
}
return (name.trim().slice(0, 2) || 'TV').toUpperCase()
}
function mapMember(raw: any, index: number): WorkspaceMember {
const projectIds: string[] = raw.assignedProjectIds ?? []
return {
id: raw.id,
name: raw.name,
email: raw.email,
initials: initialsOf(raw.name),
avatarColor: getColorForClass(index),
role: raw.role,
status: raw.status,
assignedProjectsText:
projectIds.length > 0 ? `${projectIds.length} dự án` : 'Chưa gán dự án',
assignedProjectIds: projectIds,
accessSummary: ACCESS_SUMMARY[raw.role as UserRole] ?? '',
activityStatusText: raw.status === 'invited' ? 'Đã gửi lời mời' : 'Đang hoạt động',
isOnline: false,
}
}
export interface MemberFilterParams { export interface MemberFilterParams {
search?: string search?: string
role?: UserRole | 'all' role?: UserRole | 'all'
@ -10,6 +46,21 @@ export interface MemberFilterParams {
} }
export async function getMembers(params?: MemberFilterParams): Promise<WorkspaceMember[]> { export async function getMembers(params?: MemberFilterParams): Promise<WorkspaceMember[]> {
if (!USE_MOCK_DATA) {
const { data } = await api.get<any[]>('/users')
let list = data.map(mapMember)
if (params?.search && params.search.trim() !== '') {
const q = params.search.trim().toLowerCase()
list = list.filter((m) => m.name.toLowerCase().includes(q) || m.email.toLowerCase().includes(q))
}
if (params?.role && params.role !== 'all') {
list = list.filter((m) => m.role === params.role)
}
if (params?.status && params.status !== 'all') {
list = list.filter((m) => m.status === params.status)
}
return list
}
await delay(120) await delay(120)
const db = getMockDb() const db = getMockDb()
let list = [...db.members] let list = [...db.members]
@ -33,6 +84,14 @@ export async function getMembers(params?: MemberFilterParams): Promise<Workspace
} }
export async function inviteMember(input: InviteMemberInput): Promise<WorkspaceMember> { export async function inviteMember(input: InviteMemberInput): Promise<WorkspaceMember> {
if (!USE_MOCK_DATA) {
const { data } = await api.post<any>('/users', {
email: input.email,
role: input.role,
projectIds: input.projectIds,
})
return mapMember(data, 0)
}
await delay(220) await delay(220)
const db = getMockDb() const db = getMockDb()
@ -88,6 +147,10 @@ export async function updateMemberRole(
memberId: string, memberId: string,
role: UserRole role: UserRole
): Promise<WorkspaceMember> { ): Promise<WorkspaceMember> {
if (!USE_MOCK_DATA) {
const { data } = await api.patch<any>(`/users/${memberId}`, { role })
return mapMember(data, 0)
}
await delay(140) await delay(140)
const db = getMockDb() const db = getMockDb()
const idx = db.members.findIndex((m) => m.id === memberId) const idx = db.members.findIndex((m) => m.id === memberId)
@ -114,6 +177,13 @@ export async function updateMemberRole(
} }
export async function toggleMemberStatus(memberId: string): Promise<WorkspaceMember> { export async function toggleMemberStatus(memberId: string): Promise<WorkspaceMember> {
if (!USE_MOCK_DATA) {
const members = await getMembers()
const current = members.find((m) => m.id === memberId)
const nextStatus: UserStatus = current?.status === 'suspended' ? 'active' : 'suspended'
const { data } = await api.patch<any>(`/users/${memberId}`, { status: nextStatus })
return mapMember(data, 0)
}
await delay(140) await delay(140)
const db = getMockDb() const db = getMockDb()
const idx = db.members.findIndex((m) => m.id === memberId) const idx = db.members.findIndex((m) => m.id === memberId)
@ -134,7 +204,32 @@ export async function toggleMemberStatus(memberId: string): Promise<WorkspaceMem
return updated return updated
} }
export async function updateMemberProjects(
memberId: string,
projectIds: string[]
): Promise<WorkspaceMember> {
if (!USE_MOCK_DATA) {
const { data } = await api.patch<any>(`/users/${memberId}`, { projectIds })
return mapMember(data, 0)
}
await delay(120)
const db = getMockDb()
const idx = db.members.findIndex((m) => m.id === memberId)
if (idx === -1) {
throw new Error(`Không tìm thấy thành viên: ${memberId}`)
}
const existing = db.members[idx]!
const updated: WorkspaceMember = { ...existing, assignedProjectIds: projectIds }
db.members[idx] = updated
saveMockDb(db)
return updated
}
export async function getRolePermissions(): Promise<RolePermissionItem[]> { export async function getRolePermissions(): Promise<RolePermissionItem[]> {
if (!USE_MOCK_DATA) {
// Static reference data, same for every workspace.
return INITIAL_ROLE_PERMISSIONS
}
await delay(80) await delay(80)
const db = getMockDb() const db = getMockDb()
return db.rolePermissions return db.rolePermissions

View file

@ -6,6 +6,7 @@ export interface ImageItem {
fileName: string fileName: string
url: string url: string
thumbnailUrl: string thumbnailUrl: string
thumbnailSmallUrl?: string
width: number width: number
height: number height: number
status: ImageAnnotationStatus status: ImageAnnotationStatus

23
src/utils/session.ts Normal file
View file

@ -0,0 +1,23 @@
// One ID per browser visit. Sent as X-Session-ID on every API call so the
// backend tracelog can group all operations of this visit for replay.
const KEY = 'danable_session_id'
function randomId(): string {
if (typeof crypto !== 'undefined' && 'randomUUID' in crypto) {
return crypto.randomUUID()
}
return `sess-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
}
export function getSessionId(): string {
try {
let sid = sessionStorage.getItem(KEY)
if (!sid) {
sid = randomId()
sessionStorage.setItem(KEY, sid)
}
return sid
} catch {
return randomId()
}
}