Connect annotator to real API: JWT login, services real-mode, Konva canvas, autosave, paginated images, tracing
This commit is contained in:
parent
59fc3efca6
commit
e010bb5558
38 changed files with 1880 additions and 529 deletions
|
|
@ -4,6 +4,15 @@ import { useAuthStore } from '@/stores/authStore'
|
|||
import { LoginRequest, UserRole } from '@/types'
|
||||
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() {
|
||||
const { user, isAuthenticated, login: storeLogin, logout: storeLogout, setUser, setRole } = useAuthStore()
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
|
@ -17,9 +26,9 @@ export function useAuth() {
|
|||
storeLogin(response.user, response.accessToken)
|
||||
return response
|
||||
} 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)
|
||||
throw err
|
||||
throw new Error(message)
|
||||
} finally {
|
||||
setIsLoading(false)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,33 @@
|
|||
import React, { useEffect, useState } from 'react'
|
||||
import { Link, useLocation } from 'react-router-dom'
|
||||
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'
|
||||
|
||||
export const RecentProjects: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => {
|
||||
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 (
|
||||
<div>
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import React from 'react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { NavLink, useLocation } from 'react-router-dom'
|
||||
import clsx from 'clsx'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { getProjects } from '@/services/projectService'
|
||||
import { getMembers } from '@/services/userService'
|
||||
|
||||
interface NavItem {
|
||||
to: string
|
||||
|
|
@ -12,19 +15,35 @@ interface NavItem {
|
|||
|
||||
export const SidebarNav: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => {
|
||||
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[] = [
|
||||
{
|
||||
to: '/projects',
|
||||
label: 'Dự án',
|
||||
badge: 3,
|
||||
badge: realCounts?.projects ?? 3,
|
||||
matchPrefix: '/projects',
|
||||
icon: '/assets/projects-ui/layout-grid.svg',
|
||||
},
|
||||
{
|
||||
to: '/users',
|
||||
label: 'Người dùng',
|
||||
badge: 8,
|
||||
badge: realCounts?.users ?? 8,
|
||||
matchPrefix: '/users',
|
||||
icon: '/assets/projects-ui/users.svg',
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import React, { useEffect } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import toast from 'react-hot-toast'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { useAnnotatorStore } from './annotatorStore'
|
||||
import { AnnotatorHeader } from './components/header/AnnotatorHeader'
|
||||
import { ImageInfo } from './components/header/ImageInfo'
|
||||
|
|
@ -16,12 +17,19 @@ export const AnnotatorPage: React.FC = () => {
|
|||
const { id } = useParams<{ id: string }>()
|
||||
|
||||
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)
|
||||
|
||||
useEffect(() => {
|
||||
initProject(id ?? 'urban_vehicles_v2')
|
||||
}, [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
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
|
|
@ -115,10 +123,12 @@ export const AnnotatorPage: React.FC = () => {
|
|||
return
|
||||
}
|
||||
|
||||
// Left / Right arrow keys: navigate images
|
||||
if (e.key === 'ArrowLeft') {
|
||||
// Arrow keys: navigate images (Up/Left = previous, Down/Right = next)
|
||||
if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
|
||||
e.preventDefault()
|
||||
state.prevImage()
|
||||
} else if (e.key === 'ArrowRight') {
|
||||
} else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
|
||||
e.preventDefault()
|
||||
state.nextImage()
|
||||
}
|
||||
}
|
||||
|
|
@ -127,6 +137,31 @@ export const AnnotatorPage: React.FC = () => {
|
|||
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 (
|
||||
<div className="min-h-full space-y-4 p-6">
|
||||
{/* Top Project Title & Action Buttons */}
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import toast from 'react-hot-toast'
|
||||
import { create } from 'zustand'
|
||||
import {
|
||||
AnnotationShape,
|
||||
|
|
@ -10,6 +11,10 @@ import {
|
|||
Project,
|
||||
TaskType,
|
||||
} 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 { normalizeBBox } from '@/utils/canvas'
|
||||
|
||||
|
|
@ -458,6 +463,9 @@ interface HistorySnapshot {
|
|||
export interface AnnotatorState {
|
||||
project: Project
|
||||
images: ImageItem[]
|
||||
isLoading: boolean
|
||||
loadError: string | null
|
||||
isSaving: boolean
|
||||
currentImageIndex: number
|
||||
displayImageCounter: number
|
||||
activeTool: AnnotationTool
|
||||
|
|
@ -473,6 +481,7 @@ export interface AnnotatorState {
|
|||
vertexEditEnabled: boolean
|
||||
activeGroupId: number
|
||||
zoom: number
|
||||
pan: { x: number; y: number }
|
||||
lastSavedAt: string
|
||||
draftPolygonPoints: Point2D[]
|
||||
historyPast: HistorySnapshot[]
|
||||
|
|
@ -512,10 +521,11 @@ export interface AnnotatorState {
|
|||
zoomIn: () => void
|
||||
zoomOut: () => void
|
||||
resetZoom: () => void
|
||||
setPan: (pan: { x: number; y: number }) => void
|
||||
undo: () => void
|
||||
redo: () => void
|
||||
saveCurrentAnnotation: () => void
|
||||
saveAndNext: () => void
|
||||
scheduleAutosave: () => void
|
||||
updateImageStatus: (status: ImageAnnotationStatus) => void
|
||||
}
|
||||
|
||||
|
|
@ -571,6 +581,8 @@ function createInitialAnnotationState(project: Project) {
|
|||
return {
|
||||
project,
|
||||
images,
|
||||
isLoading: false,
|
||||
loadError: null,
|
||||
currentImageIndex: 0,
|
||||
displayImageCounter,
|
||||
activeTool: defaultTool,
|
||||
|
|
@ -586,6 +598,8 @@ function createInitialAnnotationState(project: Project) {
|
|||
vertexEditEnabled: true,
|
||||
activeGroupId: 2,
|
||||
zoom: 75,
|
||||
pan: { x: 0, y: 0 },
|
||||
isSaving: false,
|
||||
lastSavedAt: '09:42',
|
||||
draftPolygonPoints: [] as Point2D[],
|
||||
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) => ({
|
||||
...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) => {
|
||||
const selectedProject =
|
||||
ANNOTATOR_PROJECTS_BY_ID[projectId] ?? ANNOTATOR_PROJECTS_BY_ID.urban_vehicles_v2!
|
||||
set(createInitialAnnotationState(selectedProject))
|
||||
if (USE_MOCK_DATA) {
|
||||
const selectedProject =
|
||||
ANNOTATOR_PROJECTS_BY_ID[projectId] ?? ANNOTATOR_PROJECTS_BY_ID.urban_vehicles_v2!
|
||||
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) => {
|
||||
const { images, project } = get()
|
||||
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 img = images[index]
|
||||
const shapes = img ? get().shapesByImageId[img.id] ?? [] : []
|
||||
|
|
@ -615,7 +754,25 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
draftPolygonPoints: [],
|
||||
historyPast: [],
|
||||
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: () => {
|
||||
|
|
@ -679,6 +836,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
],
|
||||
historyFuture: [],
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
toggleFlag: (flag) => {
|
||||
|
|
@ -698,6 +856,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
},
|
||||
},
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
setShowBoxes: (show) => set({ showBoxes: show }),
|
||||
|
|
@ -735,6 +894,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
[currentImage.id]: updated,
|
||||
},
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
updateSelectedShapeGroup: (groupId) => {
|
||||
|
|
@ -751,6 +911,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
[currentImage.id]: updated,
|
||||
},
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
addBoundingBox: (bbox) => {
|
||||
|
|
@ -792,6 +953,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
],
|
||||
historyFuture: [],
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
updateBoundingBox: (shapeId, bbox) => {
|
||||
|
|
@ -868,6 +1030,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
],
|
||||
historyFuture: [],
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
cancelDraftPolygon: () => set({ draftPolygonPoints: [] }),
|
||||
|
|
@ -917,6 +1080,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
],
|
||||
historyFuture: [],
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
deletePolygonVertex: (shapeId, vertexIndex) => {
|
||||
|
|
@ -940,6 +1104,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
[currentImage.id]: updated,
|
||||
},
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
addPointShape: (pt) => {
|
||||
|
|
@ -977,6 +1142,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
],
|
||||
historyFuture: [],
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
updatePointShape: (shapeId, pt) => {
|
||||
|
|
@ -1009,6 +1175,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
[currentImage.id]: updated,
|
||||
},
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
toggleAllShapesVisibility: () => {
|
||||
|
|
@ -1024,6 +1191,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
[currentImage.id]: updated,
|
||||
},
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
deleteShape: (shapeId) => {
|
||||
|
|
@ -1050,12 +1218,14 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
],
|
||||
historyFuture: [],
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
setZoom: (zoom) => set({ zoom: Math.max(25, Math.min(200, zoom)) }),
|
||||
zoomIn: () => set((s) => ({ zoom: Math.min(200, 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: () => {
|
||||
const state = get()
|
||||
|
|
@ -1078,6 +1248,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
historyPast: state.historyPast.slice(0, -1),
|
||||
historyFuture: [currentSnapshot, ...state.historyFuture],
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
redo: () => {
|
||||
|
|
@ -1101,15 +1272,48 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
historyPast: [...state.historyPast, currentSnapshot],
|
||||
historyFuture: state.historyFuture.slice(1),
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
saveCurrentAnnotation: () => {
|
||||
set({ lastSavedAt: getCurrentTimeHHMM() })
|
||||
const state = get()
|
||||
const currentImage = state.images[state.currentImageIndex]
|
||||
if (!currentImage) return
|
||||
if (USE_MOCK_DATA) {
|
||||
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: () => {
|
||||
set({ lastSavedAt: getCurrentTimeHHMM() })
|
||||
get().nextImage()
|
||||
scheduleAutosave: () => {
|
||||
if (USE_MOCK_DATA) return
|
||||
if (autosaveTimer) clearTimeout(autosaveTimer)
|
||||
autosaveTimer = setTimeout(() => {
|
||||
autosaveTimer = null
|
||||
useAnnotatorStore.getState().saveCurrentAnnotation()
|
||||
}, 1200)
|
||||
},
|
||||
|
||||
updateImageStatus: (status) => {
|
||||
|
|
@ -1123,5 +1327,10 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
},
|
||||
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')
|
||||
})
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
|
|
|||
|
|
@ -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 { normalizeBBox } from '@/utils/canvas'
|
||||
import { useAnnotatorStore } from '../../annotatorStore'
|
||||
|
|
@ -20,9 +23,30 @@ type DragInteraction =
|
|||
initialBox: BoundingBox
|
||||
}
|
||||
| { 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 = () => {
|
||||
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 currentImage = useAnnotatorStore((s) => s.images[s.currentImageIndex])
|
||||
|
|
@ -35,6 +59,7 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
const maskOpacity = useAnnotatorStore((s) => s.maskOpacity)
|
||||
const vertexEditEnabled = useAnnotatorStore((s) => s.vertexEditEnabled)
|
||||
const zoom = useAnnotatorStore((s) => s.zoom)
|
||||
const pan = useAnnotatorStore((s) => s.pan)
|
||||
const draftPolygonPoints = useAnnotatorStore((s) => s.draftPolygonPoints)
|
||||
|
||||
const setSelectedShapeId = useAnnotatorStore((s) => s.setSelectedShapeId)
|
||||
|
|
@ -48,31 +73,132 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
|
||||
const [interaction, setInteraction] = useState<DragInteraction | 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
|
||||
|
||||
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 selectedShape = shapes.find((s) => s.id === selectedShapeId)
|
||||
const activeClass =
|
||||
project.classes.find((c) => c.id === selectedClassId) ?? project.classes[0]!
|
||||
|
||||
// Convert client mouse position to 1920x1080 SVG coordinate space
|
||||
const getSvgPoint = (e: React.MouseEvent): Point2D => {
|
||||
const svg = svgRef.current
|
||||
if (!svg) return { x: 0, y: 0 }
|
||||
const rect = svg.getBoundingClientRect()
|
||||
if (rect.width === 0 || rect.height === 0) return { x: 0, y: 0 }
|
||||
const scaleX = currentImage.width / rect.width
|
||||
const scaleY = currentImage.height / rect.height
|
||||
// Exact pointer -> image coords through the live Stage transform.
|
||||
const getImagePoint = (e: KonvaEventObject<MouseEvent>): Point2D => {
|
||||
const stage = e.target.getStage() ?? stageRef.current
|
||||
if (!stage) return { x: 0, y: 0 }
|
||||
const pos = stage.getPointerPosition()
|
||||
if (!pos) return { x: 0, y: 0 }
|
||||
const st = useAnnotatorStore.getState()
|
||||
const s = displayScaleOf(stage)
|
||||
return {
|
||||
x: Math.max(0, Math.min(currentImage.width, (e.clientX - rect.left) * scaleX)),
|
||||
y: Math.max(0, Math.min(currentImage.height, (e.clientY - rect.top) * scaleY)),
|
||||
x: Math.max(0, Math.min(currentImage.width, (pos.x - st.pan.x) / s)),
|
||||
y: Math.max(0, Math.min(currentImage.height, (pos.y - st.pan.y) / s)),
|
||||
}
|
||||
}
|
||||
|
||||
const handleCanvasMouseDown = (e: React.MouseEvent) => {
|
||||
if (e.button !== 0) return
|
||||
const pt = getSvgPoint(e)
|
||||
const handleWheel = (e: KonvaEventObject<WheelEvent>) => {
|
||||
e.evt.preventDefault()
|
||||
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') {
|
||||
setInteraction({ type: 'draw-bbox', start: pt, current: pt })
|
||||
|
|
@ -89,18 +215,39 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
return
|
||||
}
|
||||
|
||||
if (activeTool === 'select') {
|
||||
if (activeTool === 'select' && stage && e.target === stage) {
|
||||
setSelectedShapeId(null)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCanvasMouseMove = (e: React.MouseEvent) => {
|
||||
const pt = getSvgPoint(e)
|
||||
const handleMouseMove = (e: KonvaEventObject<MouseEvent>) => {
|
||||
if (draftPolygonPoints.length > 0) {
|
||||
setCursorPoint(pt)
|
||||
setCursorPoint(getImagePoint(e))
|
||||
}
|
||||
|
||||
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') {
|
||||
setInteraction({ ...interaction, current: pt })
|
||||
|
|
@ -163,7 +310,7 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
}
|
||||
}
|
||||
|
||||
const handleCanvasMouseUp = () => {
|
||||
const handleMouseUp = () => {
|
||||
if (!interaction) return
|
||||
if (interaction.type === 'draw-bbox') {
|
||||
const rawBox: BoundingBox = {
|
||||
|
|
@ -173,6 +320,9 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
height: interaction.current.y - interaction.start.y,
|
||||
}
|
||||
addBoundingBox(rawBox)
|
||||
} else if (interaction.type !== 'pan-stage') {
|
||||
// Continuous ops (move/resize/vertex) already wrote state per mousemove.
|
||||
useAnnotatorStore.getState().scheduleAutosave()
|
||||
}
|
||||
setInteraction(null)
|
||||
}
|
||||
|
|
@ -197,103 +347,121 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
)
|
||||
: null
|
||||
|
||||
const scaleFactor = zoom / 75
|
||||
|
||||
return (
|
||||
<div className="px-4 py-3">
|
||||
<div className="relative overflow-hidden rounded-xl border border-slate-200/80 bg-slate-900">
|
||||
<div
|
||||
className="w-full origin-center transition-transform duration-150"
|
||||
style={{
|
||||
transform: scaleFactor !== 1 ? `scale(${scaleFactor})` : undefined,
|
||||
}}
|
||||
>
|
||||
<svg
|
||||
ref={svgRef}
|
||||
viewBox={`0 0 ${currentImage.width} ${currentImage.height}`}
|
||||
className="block aspect-[1.925] w-full select-none"
|
||||
style={{
|
||||
cursor:
|
||||
activeTool === 'bbox' || activeTool === 'polygon' || activeTool === 'point'
|
||||
? 'crosshair'
|
||||
: 'default',
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="relative overflow-hidden rounded-xl border border-slate-200/80 bg-slate-900"
|
||||
>
|
||||
{stageW > 0 && stageH > 0 && (
|
||||
<Stage
|
||||
ref={(node) => {
|
||||
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={{
|
||||
cursor: spaceDown
|
||||
? 'grab'
|
||||
: activeTool === 'bbox' ||
|
||||
activeTool === 'polygon' ||
|
||||
activeTool === 'point'
|
||||
? 'crosshair'
|
||||
: 'default',
|
||||
}}
|
||||
onMouseDown={handleCanvasMouseDown}
|
||||
onMouseMove={handleCanvasMouseMove}
|
||||
onMouseUp={handleCanvasMouseUp}
|
||||
onDoubleClick={handleDoubleClick}
|
||||
>
|
||||
<ImageViewer
|
||||
url={currentImage.url}
|
||||
width={currentImage.width}
|
||||
height={currentImage.height}
|
||||
/>
|
||||
<Layer>
|
||||
<ImageViewer
|
||||
url={currentImage.url}
|
||||
thumbUrl={currentImage.thumbnailSmallUrl ?? currentImage.thumbnailUrl}
|
||||
width={currentImage.width}
|
||||
height={currentImage.height}
|
||||
/>
|
||||
|
||||
{project.taskType === 'object_detection' && (
|
||||
<BoundingBoxTool
|
||||
{project.taskType === 'object_detection' && (
|
||||
<BoundingBoxTool
|
||||
shapes={shapes}
|
||||
selectedShapeId={selectedShapeId}
|
||||
showBoxes={showBoxes}
|
||||
draftBox={draftBox}
|
||||
activeClassColor={activeClass.color}
|
||||
activeClassName={activeClass.name}
|
||||
onSelectShape={setSelectedShapeId}
|
||||
onStartMoveBox={(pt, shape) => {
|
||||
if (!shape.bbox) return
|
||||
setInteraction({
|
||||
type: 'move-bbox',
|
||||
shapeId: shape.id,
|
||||
startMouse: pt,
|
||||
initialBox: { ...shape.bbox },
|
||||
})
|
||||
}}
|
||||
onStartResizeBox={(pt, shape, corner) => {
|
||||
if (!shape.bbox) return
|
||||
setInteraction({
|
||||
type: 'resize-bbox',
|
||||
shapeId: shape.id,
|
||||
corner,
|
||||
startMouse: pt,
|
||||
initialBox: { ...shape.bbox },
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{project.taskType === 'segmentation' && (
|
||||
<PolygonTool
|
||||
shapes={shapes}
|
||||
selectedShapeId={selectedShapeId}
|
||||
showMasks={showMasks}
|
||||
maskOpacity={maskOpacity}
|
||||
vertexEditEnabled={vertexEditEnabled}
|
||||
draftPolygonPoints={draftPolygonPoints}
|
||||
cursorPoint={cursorPoint}
|
||||
activeClassColor={activeClass.color}
|
||||
onSelectShape={setSelectedShapeId}
|
||||
onStartDragVertex={(shapeId, vertexIndex) => {
|
||||
setInteraction({
|
||||
type: 'drag-vertex',
|
||||
shapeId,
|
||||
vertexIndex,
|
||||
})
|
||||
}}
|
||||
onInsertVertexOnEdge={(shapeId, afterIndex) => {
|
||||
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}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PointTool
|
||||
shapes={shapes}
|
||||
selectedShapeId={selectedShapeId}
|
||||
showBoxes={showBoxes}
|
||||
draftBox={draftBox}
|
||||
activeClassColor={activeClass.color}
|
||||
activeClassName={activeClass.name}
|
||||
onSelectShape={setSelectedShapeId}
|
||||
onStartMoveBox={(e, shape) => {
|
||||
if (!shape.bbox) return
|
||||
setInteraction({
|
||||
type: 'move-bbox',
|
||||
shapeId: shape.id,
|
||||
startMouse: getSvgPoint(e),
|
||||
initialBox: { ...shape.bbox },
|
||||
})
|
||||
}}
|
||||
onStartResizeBox={(e, shape, corner) => {
|
||||
if (!shape.bbox) return
|
||||
setInteraction({
|
||||
type: 'resize-bbox',
|
||||
shapeId: shape.id,
|
||||
corner,
|
||||
startMouse: getSvgPoint(e),
|
||||
initialBox: { ...shape.bbox },
|
||||
})
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
|
||||
{project.taskType === 'segmentation' && (
|
||||
<PolygonTool
|
||||
shapes={shapes}
|
||||
selectedShapeId={selectedShapeId}
|
||||
showMasks={showMasks}
|
||||
maskOpacity={maskOpacity}
|
||||
vertexEditEnabled={vertexEditEnabled}
|
||||
draftPolygonPoints={draftPolygonPoints}
|
||||
cursorPoint={cursorPoint}
|
||||
activeClassColor={activeClass.color}
|
||||
onSelectShape={setSelectedShapeId}
|
||||
onStartDragVertex={(_e, shapeId, vertexIndex) => {
|
||||
setInteraction({
|
||||
type: 'drag-vertex',
|
||||
shapeId,
|
||||
vertexIndex,
|
||||
})
|
||||
}}
|
||||
onInsertVertexOnEdge={(shapeId, afterIndex, pt) => {
|
||||
insertPolygonVertex(shapeId, afterIndex, pt)
|
||||
}}
|
||||
onCloseDraftPolygon={closeDraftPolygon}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PointTool
|
||||
shapes={shapes}
|
||||
selectedShapeId={selectedShapeId}
|
||||
onSelectShape={setSelectedShapeId}
|
||||
/>
|
||||
|
||||
<SelectTool selectedShape={selectedShape} />
|
||||
</svg>
|
||||
</div>
|
||||
<SelectTool selectedShape={selectedShape} />
|
||||
</Layer>
|
||||
</Stage>
|
||||
)}
|
||||
|
||||
{/* Bottom-left dark translucent pill overlay */}
|
||||
<CanvasOverlay />
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
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'
|
||||
|
||||
|
|
@ -11,9 +12,9 @@ export interface BoundingBoxToolProps {
|
|||
activeClassColor: string
|
||||
activeClassName: string
|
||||
onSelectShape: (shapeId: string) => void
|
||||
onStartMoveBox: (e: React.MouseEvent, shape: AnnotationShape) => void
|
||||
onStartMoveBox: (pt: Point2D, shape: AnnotationShape) => void
|
||||
onStartResizeBox: (
|
||||
e: React.MouseEvent,
|
||||
pt: Point2D,
|
||||
shape: AnnotationShape,
|
||||
corner: ResizeHandleCorner
|
||||
) => void
|
||||
|
|
@ -34,8 +35,21 @@ export const BoundingBoxTool: React.FC<BoundingBoxToolProps> = ({
|
|||
|
||||
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 (
|
||||
<g>
|
||||
<Group>
|
||||
{bboxShapes.map((shape) => {
|
||||
const box = shape.bbox!
|
||||
const isSelected = shape.id === selectedShapeId
|
||||
|
|
@ -51,113 +65,137 @@ export const BoundingBoxTool: React.FC<BoundingBoxToolProps> = ({
|
|||
]
|
||||
|
||||
return (
|
||||
<g key={shape.id}>
|
||||
{/* Main Bounding Box Rectangle */}
|
||||
<rect
|
||||
<Group key={shape.id}>
|
||||
{/* Light interior tint (separate node: border below stays crisp) */}
|
||||
<Rect
|
||||
x={box.x}
|
||||
y={box.y}
|
||||
width={box.width}
|
||||
height={box.height}
|
||||
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}
|
||||
strokeWidth={isSelected ? 4 : 3}
|
||||
className="cursor-move"
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation()
|
||||
e.cancelBubble = true
|
||||
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 */}
|
||||
<g
|
||||
className="cursor-pointer"
|
||||
<Group
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation()
|
||||
e.cancelBubble = true
|
||||
onSelectShape(shape.id)
|
||||
}}
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
<rect
|
||||
<Rect
|
||||
x={box.x}
|
||||
y={pillY}
|
||||
width={pillWidth}
|
||||
height={32}
|
||||
rx={8}
|
||||
cornerRadius={8}
|
||||
fill={shape.color}
|
||||
fillOpacity={0.92}
|
||||
/>
|
||||
<text
|
||||
x={box.x + pillWidth / 2}
|
||||
y={pillY + 21}
|
||||
<Text
|
||||
x={box.x}
|
||||
y={pillY + 6}
|
||||
width={pillWidth}
|
||||
height={32}
|
||||
align="center"
|
||||
fill={isLightTag ? '#0F172A' : '#FFFFFF'}
|
||||
fontSize={17}
|
||||
fontWeight="bold"
|
||||
textAnchor="middle"
|
||||
className="select-none"
|
||||
>
|
||||
{shape.labelName}
|
||||
</text>
|
||||
</g>
|
||||
fontStyle="bold"
|
||||
text={shape.labelName}
|
||||
/>
|
||||
</Group>
|
||||
|
||||
{/* Corner Resize Handles when Selected */}
|
||||
{isSelected &&
|
||||
corners.map((corner) => (
|
||||
<rect
|
||||
<Rect
|
||||
key={corner.id}
|
||||
x={corner.cx - 8}
|
||||
y={corner.cy - 8}
|
||||
width={16}
|
||||
height={16}
|
||||
rx={3}
|
||||
cornerRadius={3}
|
||||
fill="#FFFFFF"
|
||||
stroke={shape.color}
|
||||
strokeWidth={3.5}
|
||||
style={{ cursor: corner.cursor }}
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation()
|
||||
onStartResizeBox(e, shape, corner.id)
|
||||
e.cancelBubble = true
|
||||
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 */}
|
||||
{draftBox && draftBox.width > 4 && draftBox.height > 4 && (
|
||||
<g className="pointer-events-none">
|
||||
<rect
|
||||
<Group listening={false}>
|
||||
<Rect
|
||||
x={draftBox.x}
|
||||
y={draftBox.y}
|
||||
width={draftBox.width}
|
||||
height={draftBox.height}
|
||||
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}
|
||||
strokeWidth={3.5}
|
||||
strokeDasharray="8 6"
|
||||
dash={[8, 6]}
|
||||
/>
|
||||
<rect
|
||||
<Rect
|
||||
x={draftBox.x}
|
||||
y={Math.max(4, draftBox.y - 34)}
|
||||
width={110}
|
||||
height={28}
|
||||
rx={6}
|
||||
cornerRadius={6}
|
||||
fill={activeClassColor}
|
||||
/>
|
||||
<text
|
||||
x={draftBox.x + 55}
|
||||
y={Math.max(4, draftBox.y - 34) + 19}
|
||||
<Text
|
||||
x={draftBox.x}
|
||||
y={Math.max(4, draftBox.y - 34) + 5}
|
||||
width={110}
|
||||
align="center"
|
||||
fill="#FFFFFF"
|
||||
fontSize={15}
|
||||
fontWeight="bold"
|
||||
textAnchor="middle"
|
||||
>
|
||||
{activeClassName}
|
||||
</text>
|
||||
</g>
|
||||
fontStyle="bold"
|
||||
text={activeClassName}
|
||||
/>
|
||||
</Group>
|
||||
)}
|
||||
</g>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,21 +1,51 @@
|
|||
import React from 'react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { Image as KonvaImage } from 'react-konva'
|
||||
|
||||
export interface ImageViewerProps {
|
||||
url: string
|
||||
thumbUrl?: string
|
||||
width: number
|
||||
height: number
|
||||
}
|
||||
|
||||
export const ImageViewer: React.FC<ImageViewerProps> = ({ url, width, height }) => {
|
||||
return (
|
||||
<image
|
||||
href={url}
|
||||
x={0}
|
||||
y={0}
|
||||
width={width}
|
||||
height={height}
|
||||
preserveAspectRatio="none"
|
||||
className="select-none pointer-events-none"
|
||||
/>
|
||||
)
|
||||
// Blur-up: paint the (usually already cached) thumbnail first, swap to the
|
||||
// full image the moment it arrives. The canvas never stares blank waiting
|
||||
// on R2, and the swap is pixel-exact since both share the same dimensions.
|
||||
export const ImageViewer: React.FC<ImageViewerProps> = ({ url, thumbUrl, width, height }) => {
|
||||
const [current, setCurrent] = useState<HTMLImageElement | null>(null)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setCurrent(null)
|
||||
|
||||
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} />
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import React from 'react'
|
||||
import { Circle, Group, Rect, Text } from 'react-konva'
|
||||
import { AnnotationShape } from '@/types'
|
||||
|
||||
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)
|
||||
|
||||
return (
|
||||
<g>
|
||||
<Group>
|
||||
{pointShapes.map((shape) => {
|
||||
const pt = shape.point!
|
||||
const isSelected = shape.id === selectedShapeId
|
||||
return (
|
||||
<g
|
||||
<Group
|
||||
key={shape.id}
|
||||
className="cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
e.cancelBubble = true
|
||||
onSelectShape(shape.id)
|
||||
}}
|
||||
style={{ cursor: 'pointer' }}
|
||||
>
|
||||
<circle
|
||||
cx={pt.x}
|
||||
cy={pt.y}
|
||||
r={isSelected ? 12 : 9}
|
||||
<Circle
|
||||
x={pt.x}
|
||||
y={pt.y}
|
||||
radius={isSelected ? 12 : 9}
|
||||
fill={shape.color}
|
||||
fillOpacity={0.35}
|
||||
opacity={0.35}
|
||||
stroke="#FFFFFF"
|
||||
strokeWidth={3}
|
||||
/>
|
||||
<circle cx={pt.x} cy={pt.y} r={5} fill={shape.color} />
|
||||
<rect
|
||||
<Circle x={pt.x} y={pt.y} radius={5} fill={shape.color} />
|
||||
<Rect x={pt.x - 36} y={pt.y - 38} width={72} height={24} cornerRadius={6} fill={shape.color} />
|
||||
<Text
|
||||
x={pt.x - 36}
|
||||
y={pt.y - 38}
|
||||
y={pt.y - 33}
|
||||
width={72}
|
||||
height={24}
|
||||
rx={6}
|
||||
fill={shape.color}
|
||||
/>
|
||||
<text
|
||||
x={pt.x}
|
||||
y={pt.y - 22}
|
||||
align="center"
|
||||
fill="#FFFFFF"
|
||||
fontSize={14}
|
||||
fontWeight="bold"
|
||||
textAnchor="middle"
|
||||
>
|
||||
{shape.labelName}
|
||||
</text>
|
||||
</g>
|
||||
fontStyle="bold"
|
||||
text={shape.labelName}
|
||||
/>
|
||||
</Group>
|
||||
)
|
||||
})}
|
||||
</g>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import React from 'react'
|
||||
import { Circle, Group, Line, Rect, Text } from 'react-konva'
|
||||
import { AnnotationShape, Point2D } from '@/types'
|
||||
|
||||
export interface PolygonToolProps {
|
||||
|
|
@ -11,16 +12,8 @@ export interface PolygonToolProps {
|
|||
cursorPoint: Point2D | null
|
||||
activeClassColor: string
|
||||
onSelectShape: (shapeId: string) => void
|
||||
onStartDragVertex: (
|
||||
e: React.MouseEvent,
|
||||
shapeId: string,
|
||||
vertexIndex: number
|
||||
) => void
|
||||
onInsertVertexOnEdge: (
|
||||
shapeId: string,
|
||||
afterIndex: number,
|
||||
pt: Point2D
|
||||
) => void
|
||||
onStartDragVertex: (shapeId: string, vertexIndex: number) => void
|
||||
onInsertVertexOnEdge: (shapeId: string, afterIndex: number) => void
|
||||
onCloseDraftPolygon: () => void
|
||||
}
|
||||
|
||||
|
|
@ -45,11 +38,11 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
|
|||
)
|
||||
|
||||
return (
|
||||
<g>
|
||||
<Group>
|
||||
{polygonShapes.map((shape) => {
|
||||
const pts = shape.points!
|
||||
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
|
||||
const topPoint = pts.reduce(
|
||||
|
|
@ -65,20 +58,28 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
|
|||
const tagY = Math.max(8, topPoint.y - 46)
|
||||
|
||||
return (
|
||||
<g key={shape.id}>
|
||||
{/* Polygon Filled Mask */}
|
||||
<polygon
|
||||
points={pointsAttr}
|
||||
<Group key={shape.id}>
|
||||
{/* Polygon Filled Mask: tint and border split (see BoundingBoxTool) */}
|
||||
<Line
|
||||
points={flatPoints}
|
||||
closed
|
||||
fill={shape.color}
|
||||
fillOpacity={maskOpacity / 100}
|
||||
stroke={shape.color}
|
||||
strokeWidth={isSelected ? 4 : 3}
|
||||
strokeLinejoin="round"
|
||||
className="cursor-pointer transition-opacity"
|
||||
opacity={maskOpacity / 100}
|
||||
strokeEnabled={false}
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation()
|
||||
e.cancelBubble = true
|
||||
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 */}
|
||||
|
|
@ -87,115 +88,110 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
|
|||
pts.map((pt, idx) => {
|
||||
const nextPt = pts[(idx + 1) % pts.length]!
|
||||
return (
|
||||
<line
|
||||
<Line
|
||||
key={`edge-${idx}`}
|
||||
x1={pt.x}
|
||||
y1={pt.y}
|
||||
x2={nextPt.x}
|
||||
y2={nextPt.y}
|
||||
stroke="transparent"
|
||||
points={[pt.x, pt.y, nextPt.x, nextPt.y]}
|
||||
stroke="rgba(0,0,0,0)"
|
||||
strokeWidth={14}
|
||||
className="cursor-copy"
|
||||
onDoubleClick={(e) => {
|
||||
e.stopPropagation()
|
||||
const midX = (pt.x + nextPt.x) / 2
|
||||
const midY = (pt.y + nextPt.y) / 2
|
||||
onInsertVertexOnEdge(shape.id, idx, { x: midX, y: midY })
|
||||
hitStrokeWidth={14}
|
||||
onDblClick={(e) => {
|
||||
e.cancelBubble = true
|
||||
onInsertVertexOnEdge(shape.id, idx)
|
||||
}}
|
||||
style={{ cursor: 'copy' }}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
|
||||
{/* Label Pill above Selected Polygon (e.g., "Xe buýt · group 2") */}
|
||||
{isSelected && (
|
||||
<g className="pointer-events-none">
|
||||
<rect
|
||||
<Group listening={false}>
|
||||
<Rect
|
||||
x={tagX}
|
||||
y={tagY}
|
||||
width={tagWidth}
|
||||
height={34}
|
||||
rx={8}
|
||||
cornerRadius={8}
|
||||
fill={shape.color}
|
||||
fillOpacity={0.88}
|
||||
/>
|
||||
<text
|
||||
x={tagX + tagWidth / 2}
|
||||
y={tagY + 22}
|
||||
<Text
|
||||
x={tagX}
|
||||
y={tagY + 7}
|
||||
width={tagWidth}
|
||||
align="center"
|
||||
fill="#0F172A"
|
||||
fontSize={16}
|
||||
fontWeight="bold"
|
||||
textAnchor="middle"
|
||||
className="select-none"
|
||||
>
|
||||
{tagText}
|
||||
</text>
|
||||
</g>
|
||||
fontStyle="bold"
|
||||
text={tagText}
|
||||
/>
|
||||
</Group>
|
||||
)}
|
||||
|
||||
{/* Draggable Vertex Handles on Selected Polygon */}
|
||||
{isSelected &&
|
||||
pts.map((pt, idx) => (
|
||||
<circle
|
||||
<Circle
|
||||
key={`vertex-${idx}`}
|
||||
cx={pt.x}
|
||||
cy={pt.y}
|
||||
r={vertexEditEnabled ? 7.5 : 5.5}
|
||||
x={pt.x}
|
||||
y={pt.y}
|
||||
radius={vertexEditEnabled ? 7.5 : 5.5}
|
||||
fill="#FFFFFF"
|
||||
stroke={shape.color}
|
||||
strokeWidth={3.5}
|
||||
className={
|
||||
vertexEditEnabled ? 'cursor-grab active:cursor-grabbing' : 'cursor-pointer'
|
||||
}
|
||||
onMouseDown={(e) => {
|
||||
e.stopPropagation()
|
||||
e.cancelBubble = true
|
||||
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 */}
|
||||
{draftPolygonPoints.length > 0 && (
|
||||
<g>
|
||||
<polyline
|
||||
<Group>
|
||||
<Line
|
||||
points={[
|
||||
...draftPolygonPoints.map((p) => `${p.x},${p.y}`),
|
||||
...(cursorPoint ? [`${cursorPoint.x},${cursorPoint.y}`] : []),
|
||||
].join(' ')}
|
||||
...draftPolygonPoints.flatMap((p) => [p.x, p.y]),
|
||||
...(cursorPoint ? [cursorPoint.x, cursorPoint.y] : []),
|
||||
]}
|
||||
fill={activeClassColor}
|
||||
fillOpacity={0.18}
|
||||
stroke={activeClassColor}
|
||||
strokeWidth={3.5}
|
||||
strokeDasharray="8 5"
|
||||
className="pointer-events-none"
|
||||
dash={[8, 5]}
|
||||
listening={false}
|
||||
/>
|
||||
{draftPolygonPoints.map((pt, idx) => {
|
||||
const isFirst = idx === 0
|
||||
return (
|
||||
<circle
|
||||
<Circle
|
||||
key={`draft-pt-${idx}`}
|
||||
cx={pt.x}
|
||||
cy={pt.y}
|
||||
r={isFirst ? 10 : 7}
|
||||
x={pt.x}
|
||||
y={pt.y}
|
||||
radius={isFirst ? 10 : 7}
|
||||
fill={isFirst ? activeClassColor : '#FFFFFF'}
|
||||
stroke="#FFFFFF"
|
||||
strokeWidth={3}
|
||||
className="cursor-pointer"
|
||||
onClick={(e) => {
|
||||
if (isFirst && draftPolygonPoints.length >= 3) {
|
||||
e.stopPropagation()
|
||||
e.cancelBubble = true
|
||||
onCloseDraftPolygon()
|
||||
}
|
||||
}}
|
||||
style={{ cursor: 'pointer' }}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</g>
|
||||
</Group>
|
||||
)}
|
||||
</g>
|
||||
</Group>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,6 @@ import { TASK_TYPE_LABELS } from '@/app/constants'
|
|||
import { formatNumber } from '@/utils/format'
|
||||
import { useAnnotatorStore } from '../../annotatorStore'
|
||||
import { SaveButton } from './SaveButton'
|
||||
import { SaveAndNextButton } from './SaveAndNextButton'
|
||||
|
||||
export const AnnotatorHeader: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
|
|
@ -32,7 +31,6 @@ export const AnnotatorHeader: React.FC = () => {
|
|||
<span>Về tổng quan</span>
|
||||
</button>
|
||||
<SaveButton />
|
||||
<SaveAndNextButton />
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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 & ảnh tiếp</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
|
@ -9,6 +9,7 @@ export const SaveStatus: React.FC = () => {
|
|||
const currentImage = useAnnotatorStore((s) => s.images[s.currentImageIndex])
|
||||
const shapesByImageId = useAnnotatorStore((s) => s.shapesByImageId)
|
||||
const lastSavedAt = useAnnotatorStore((s) => s.lastSavedAt)
|
||||
const isSaving = useAnnotatorStore((s) => s.isSaving)
|
||||
|
||||
const shapes = currentImage ? shapesByImageId[currentImage.id] ?? [] : []
|
||||
|
||||
|
|
@ -33,10 +34,17 @@ export const SaveStatus: React.FC = () => {
|
|||
|
||||
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 items-center gap-1.5 font-medium text-[#15803D]">
|
||||
<span>✓</span>
|
||||
<span>Đã lưu lúc {lastSavedAt}</span>
|
||||
</div>
|
||||
{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]">
|
||||
<span>✓</span>
|
||||
<span>Đã lưu lúc {lastSavedAt}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{project.taskType === 'segmentation' && (
|
||||
<div className="flex items-center gap-5">
|
||||
|
|
|
|||
|
|
@ -3,14 +3,22 @@ import clsx from 'clsx'
|
|||
import { useAnnotatorStore } from '../../annotatorStore'
|
||||
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 = () => {
|
||||
const images = useAnnotatorStore((s) => s.images)
|
||||
const currentImageIndex = useAnnotatorStore((s) => s.currentImageIndex)
|
||||
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 (
|
||||
<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
|
||||
// Shorten "urban_00124.jpg" -> "..00124.jpg" matching wireframe
|
||||
const shortName = img.fileName.replace(/^[a-z]+_/, '..')
|
||||
|
|
@ -32,8 +40,10 @@ export const ThumbnailStrip: React.FC = () => {
|
|||
style={isActive ? { borderColor: ANNOTATOR_COLORS.selection } : undefined}
|
||||
>
|
||||
<img
|
||||
src={img.thumbnailUrl}
|
||||
src={img.thumbnailSmallUrl ?? img.thumbnailUrl}
|
||||
alt={img.fileName}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -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 { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { LoginRequest } from '@/types'
|
||||
import { LOGIN_COLORS } from '@/styles/theme'
|
||||
import { HeroSection } from './components/HeroSection'
|
||||
|
|
@ -13,23 +16,30 @@ const FOOTER_LINKS = [
|
|||
|
||||
export const LoginPage: React.FC = () => {
|
||||
const navigate = useNavigate()
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [contactModalOpen, setContactModalOpen] = useState(false)
|
||||
const { login, loginWithSSO, error: authError, isLoading } = useAuth()
|
||||
const [contactModalOpen, setContactModalOpen] = React.useState(false)
|
||||
|
||||
const handleLogin = (_credentials: LoginRequest) => {
|
||||
setIsLoading(true)
|
||||
setTimeout(() => {
|
||||
setIsLoading(false)
|
||||
const handleLogin = async (credentials: LoginRequest) => {
|
||||
try {
|
||||
await login(credentials)
|
||||
navigate('/projects')
|
||||
}, 250)
|
||||
} catch {
|
||||
// useAuth already stores the message; shown below the form.
|
||||
}
|
||||
}
|
||||
|
||||
const handleSSOLogin = () => {
|
||||
setIsLoading(true)
|
||||
setTimeout(() => {
|
||||
setIsLoading(false)
|
||||
const handleSSOLogin = async () => {
|
||||
if (!USE_MOCK_DATA) {
|
||||
// No SSO provider is configured; a mock token would only 401 back here.
|
||||
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')
|
||||
}, 250)
|
||||
} catch {
|
||||
// shown via authError
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
@ -67,9 +77,10 @@ export const LoginPage: React.FC = () => {
|
|||
|
||||
{/* Biểu mẫu đăng nhập trung tâm */}
|
||||
<LoginForm
|
||||
onSubmit={handleLogin}
|
||||
onSSOLogin={handleSSOLogin}
|
||||
onSubmit={(data) => void handleLogin(data)}
|
||||
onSSOLogin={() => void handleSSOLogin()}
|
||||
isLoading={isLoading}
|
||||
serverError={authError}
|
||||
/>
|
||||
|
||||
{/* Liên kết điều khoản & ngôn ngữ cuối trang */}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import React, { useState } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { LoginRequest } from '@/types'
|
||||
import { LOGIN_COLORS, createInsetOutlineStyle } from '@/styles/theme'
|
||||
import { SSOButton } from './SSOButton'
|
||||
|
|
@ -8,15 +9,17 @@ export interface LoginFormProps {
|
|||
onSubmit: (data: LoginRequest) => void
|
||||
onSSOLogin?: () => void
|
||||
isLoading?: boolean
|
||||
serverError?: string | null
|
||||
}
|
||||
|
||||
export const LoginForm: React.FC<LoginFormProps> = ({
|
||||
onSubmit,
|
||||
onSSOLogin,
|
||||
isLoading = false,
|
||||
serverError = null,
|
||||
}) => {
|
||||
const [email, setEmail] = useState<string>('minhanh@visionlab.vn')
|
||||
const [password, setPassword] = useState<string>('••••••••••••')
|
||||
const [email, setEmail] = useState<string>(USE_MOCK_DATA ? 'minhanh@visionlab.vn' : '')
|
||||
const [password, setPassword] = useState<string>(USE_MOCK_DATA ? '••••••••••••' : '')
|
||||
const [rememberMe, setRememberMe] = useState<boolean>(true)
|
||||
const [showPassword, setShowPassword] = useState<boolean>(false)
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null)
|
||||
|
|
@ -94,9 +97,9 @@ export const LoginForm: React.FC<LoginFormProps> = ({
|
|||
</div>
|
||||
|
||||
{/* 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">
|
||||
{errorMessage}
|
||||
{errorMessage ?? serverError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 { 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 {
|
||||
OverviewTab,
|
||||
DataTab,
|
||||
|
|
@ -9,13 +15,12 @@ import {
|
|||
SettingsTab,
|
||||
} from './components'
|
||||
import {
|
||||
getProjectById,
|
||||
getProjectImages,
|
||||
getProjectById as getMockProjectById,
|
||||
addUploadedImagesToProject,
|
||||
updateProjectClasses,
|
||||
updateProjectMembers,
|
||||
updateProject,
|
||||
deleteProjectById,
|
||||
updateProject as updateMockProject,
|
||||
deleteProjectById as deleteMockProjectById,
|
||||
subscribeProjectsStore,
|
||||
} from './projectData'
|
||||
|
||||
|
|
@ -41,27 +46,165 @@ export const ProjectDetailPage: React.FC = () => {
|
|||
const fileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
|
||||
const [activeTab, setActiveTab] = useState<DetailTabKey>('overview')
|
||||
const [project, setProject] = useState(() => getProjectById(id))
|
||||
const [images, setImages] = useState(() => getProjectImages(project.id))
|
||||
const [project, setProject] = useState<Project | null>(null)
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const current = getProjectById(id)
|
||||
setProject(current)
|
||||
setImages(getProjectImages(current.id))
|
||||
const reload = useCallback(async () => {
|
||||
if (!id) return
|
||||
if (USE_MOCK_DATA) {
|
||||
setProject(getMockProjectById(id))
|
||||
return
|
||||
}
|
||||
setProject(await getProjectById(id))
|
||||
}, [id])
|
||||
|
||||
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(() => {
|
||||
const current = getProjectById(id)
|
||||
setProject(current)
|
||||
setImages(getProjectImages(current.id))
|
||||
setProject(getMockProjectById(id))
|
||||
})
|
||||
}, [id])
|
||||
|
||||
const handleUploadFiles = (fileList: FileList | null) => {
|
||||
if (!fileList || fileList.length === 0) return
|
||||
const names = Array.from(fileList).map((f) => f.name)
|
||||
addUploadedImagesToProject(project.id, names)
|
||||
const handleUploadFiles = async (fileList: FileList | null) => {
|
||||
if (!fileList || fileList.length === 0 || !project) return
|
||||
if (USE_MOCK_DATA) {
|
||||
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 (
|
||||
|
|
@ -73,7 +216,7 @@ export const ProjectDetailPage: React.FC = () => {
|
|||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => handleUploadFiles(e.target.files)}
|
||||
onChange={(e) => void handleUploadFiles(e.target.files)}
|
||||
/>
|
||||
|
||||
{/* Top Header matching MVP · Project dashboard.png */}
|
||||
|
|
@ -97,7 +240,8 @@ export const ProjectDetailPage: React.FC = () => {
|
|||
<button
|
||||
type="button"
|
||||
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
|
||||
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"
|
||||
/>
|
||||
</svg>
|
||||
<span>Tải ảnh lên</span>
|
||||
<span>{isUploading ? 'Đang tải...' : 'Tải ảnh lên'}</span>
|
||||
</button>
|
||||
|
||||
<button
|
||||
|
|
@ -156,7 +300,6 @@ export const ProjectDetailPage: React.FC = () => {
|
|||
{activeTab === 'overview' && (
|
||||
<OverviewTab
|
||||
project={project}
|
||||
images={images}
|
||||
onSwitchTab={(tab) => setActiveTab(tab)}
|
||||
/>
|
||||
)}
|
||||
|
|
@ -164,39 +307,30 @@ export const ProjectDetailPage: React.FC = () => {
|
|||
{activeTab === 'data' && (
|
||||
<DataTab
|
||||
project={project}
|
||||
images={images}
|
||||
onUploadImages={(names) => addUploadedImagesToProject(project.id, names)}
|
||||
onUploadImages={(_names, files) => void handleUploadFiles(files ? toFileList(files) : null)}
|
||||
hideSampleUpload={!USE_MOCK_DATA}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'labels' && (
|
||||
<LabelsTab
|
||||
classes={project.classes}
|
||||
onUpdateClasses={(classes) => updateProjectClasses(project.id, classes)}
|
||||
onUpdateClasses={(classes) => void handleUpdateClasses(classes)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'members' && (
|
||||
<MembersTab
|
||||
members={project.members}
|
||||
onUpdateMembers={(members) => updateProjectMembers(project.id, members)}
|
||||
onUpdateMembers={(members) => void handleUpdateMembers(members)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{activeTab === 'settings' && (
|
||||
<SettingsTab
|
||||
project={project}
|
||||
onSaveSettings={(updates) =>
|
||||
updateProject(project.id, (p) => ({
|
||||
...p,
|
||||
name: updates.name,
|
||||
slug: updates.slug,
|
||||
description: updates.description,
|
||||
taskType: updates.taskType,
|
||||
updatedAt: 'Vừa cập nhật',
|
||||
}))
|
||||
}
|
||||
onDeleteProject={() => deleteProjectById(project.id)}
|
||||
onSaveSettings={(updates) => void handleSaveSettings(updates)}
|
||||
onDeleteProject={() => void handleDeleteProject()}
|
||||
/>
|
||||
)}
|
||||
</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
|
||||
|
|
|
|||
|
|
@ -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 { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { useProjects } from '@/hooks/useProjects'
|
||||
import {
|
||||
ProjectStatsCards,
|
||||
ProjectFilters,
|
||||
|
|
@ -8,16 +11,22 @@ import {
|
|||
CreateProjectModal,
|
||||
} from './components'
|
||||
import {
|
||||
getProjects,
|
||||
getActivities,
|
||||
addProject,
|
||||
deleteProjectById,
|
||||
getProjects as getMockProjects,
|
||||
getActivities as getMockActivities,
|
||||
addProject as addMockProject,
|
||||
deleteProjectById as deleteMockProjectById,
|
||||
subscribeProjectsStore,
|
||||
} from './projectData'
|
||||
|
||||
export const ProjectListPage: React.FC = () => {
|
||||
const [projects, setProjects] = useState(() => getProjects())
|
||||
const [activities, setActivities] = useState(() => getActivities())
|
||||
const {
|
||||
projects: apiProjects,
|
||||
activities: apiActivities,
|
||||
isLoading: apiLoading,
|
||||
createProject: apiCreate,
|
||||
deleteProject: apiDelete,
|
||||
} = useProjects()
|
||||
const [mockTick, setMockTick] = useState(0)
|
||||
const [isCreateModalOpen, setIsCreateModalOpen] = useState(false)
|
||||
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
|
|
@ -26,13 +35,23 @@ export const ProjectListPage: React.FC = () => {
|
|||
const [sortBy, setSortBy] = useState<'updated' | 'name' | 'progress'>('updated')
|
||||
const [viewMode, setViewMode] = useState<'grid' | 'list'>('grid')
|
||||
|
||||
useEffect(() => {
|
||||
return subscribeProjectsStore(() => {
|
||||
setProjects(getProjects())
|
||||
setActivities(getActivities())
|
||||
})
|
||||
React.useEffect(() => {
|
||||
if (USE_MOCK_DATA) {
|
||||
return subscribeProjectsStore(() => setMockTick((t) => t + 1))
|
||||
}
|
||||
}, [])
|
||||
|
||||
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 list = projects.filter((proj) => {
|
||||
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'))
|
||||
}
|
||||
if (sortBy === 'progress') {
|
||||
return [...list].sort((a, b) => {
|
||||
const progA =
|
||||
a.stats.totalImages > 0
|
||||
? (a.stats.completed + a.stats.pendingReview) / a.stats.totalImages
|
||||
: 0
|
||||
const progB =
|
||||
b.stats.totalImages > 0
|
||||
? (b.stats.completed + b.stats.pendingReview) / b.stats.totalImages
|
||||
: 0
|
||||
return progB - progA
|
||||
})
|
||||
const progressOf = (p: (typeof list)[number]) =>
|
||||
p.stats.totalImages > 0
|
||||
? (p.stats.completed + p.stats.pendingReview) / p.stats.totalImages
|
||||
: 0
|
||||
return [...list].sort((x, y) => progressOf(y) - progressOf(x))
|
||||
}
|
||||
return list
|
||||
}, [projects, searchQuery, selectedTaskType, selectedStatus, sortBy])
|
||||
|
||||
const handleCreateProject = (input: CreateProjectInput) => {
|
||||
addProject(input)
|
||||
const handleCreateProject = async (input: CreateProjectInput) => {
|
||||
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) => {
|
||||
deleteProjectById(projectId)
|
||||
const handleDeleteProject = async (projectId: string) => {
|
||||
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 (
|
||||
|
|
@ -100,7 +132,7 @@ export const ProjectListPage: React.FC = () => {
|
|||
</div>
|
||||
|
||||
{/* 4 Summary Cards */}
|
||||
<ProjectStatsCards projects={projects} />
|
||||
<ProjectStatsCards projects={filteredProjects} />
|
||||
|
||||
{/* Filter Bar */}
|
||||
<ProjectFilters
|
||||
|
|
@ -117,7 +149,14 @@ export const ProjectListPage: React.FC = () => {
|
|||
/>
|
||||
|
||||
{/* 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">
|
||||
<p className="text-sm font-semibold text-slate-700">
|
||||
Không tìm thấy dự án phù hợp
|
||||
|
|
@ -138,7 +177,7 @@ export const ProjectListPage: React.FC = () => {
|
|||
<ProjectCard
|
||||
key={project.id}
|
||||
project={project}
|
||||
onDelete={handleDeleteProject}
|
||||
onDelete={(pid) => void handleDeleteProject(pid)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
|
@ -155,7 +194,7 @@ export const ProjectListPage: React.FC = () => {
|
|||
<CreateProjectModal
|
||||
isOpen={isCreateModalOpen}
|
||||
onClose={() => setIsCreateModalOpen(false)}
|
||||
onCreate={handleCreateProject}
|
||||
onCreate={(input) => void handleCreateProject(input)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -76,6 +76,8 @@ export const ProjectCard: React.FC<ProjectCardProps> = ({ project, onDelete }) =
|
|||
<img
|
||||
src={project.thumbnailUrl}
|
||||
alt={project.name}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
className="h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.02]"
|
||||
/>
|
||||
|
||||
|
|
|
|||
|
|
@ -1,11 +1,11 @@
|
|||
import React, { useState, useRef } from 'react'
|
||||
import { ImageItem, Project } from '@/types'
|
||||
import { Project } from '@/types'
|
||||
import { ImageTable } from './ImageTable'
|
||||
|
||||
interface DataTabProps {
|
||||
project: Project
|
||||
images: ImageItem[]
|
||||
onUploadImages: (fileNames: string[]) => void
|
||||
onUploadImages: (fileNames: string[], files?: File[]) => void
|
||||
hideSampleUpload?: boolean
|
||||
}
|
||||
|
||||
interface DatasetBatch {
|
||||
|
|
@ -19,9 +19,10 @@ interface DatasetBatch {
|
|||
|
||||
export const DataTab: React.FC<DataTabProps> = ({
|
||||
project,
|
||||
images,
|
||||
onUploadImages,
|
||||
hideSampleUpload = false,
|
||||
}) => {
|
||||
const imageCount = project.stats.totalImages
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [batches, setBatches] = useState<DatasetBatch[]>([
|
||||
|
|
@ -53,15 +54,18 @@ export const DataTab: React.FC<DataTabProps> = ({
|
|||
|
||||
const handleFilesSelected = (files: FileList | null) => {
|
||||
if (!files || files.length === 0) return
|
||||
const names = Array.from(files).map((f) => f.name)
|
||||
onUploadImages(names)
|
||||
const list = Array.from(files)
|
||||
onUploadImages(
|
||||
list.map((f) => f.name),
|
||||
list
|
||||
)
|
||||
setBatches((prev) => [
|
||||
{
|
||||
id: `batch-${Date.now()}`,
|
||||
batchName: `upload_batch_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}`,
|
||||
uploadedBy: 'Minh Anh',
|
||||
uploadedAt: 'Vừa tải lên',
|
||||
imageCount: names.length,
|
||||
imageCount: list.length,
|
||||
status: 'Đã phân công',
|
||||
},
|
||||
...prev,
|
||||
|
|
@ -70,9 +74,9 @@ export const DataTab: React.FC<DataTabProps> = ({
|
|||
|
||||
const handleSimulatedSampleUpload = () => {
|
||||
const sampleNames = [
|
||||
`traffic_${String(327 + images.length).padStart(5, '0')}.jpg`,
|
||||
`traffic_${String(328 + images.length).padStart(5, '0')}.jpg`,
|
||||
`traffic_${String(329 + images.length).padStart(5, '0')}.jpg`,
|
||||
`traffic_${String(327 + imageCount).padStart(5, '0')}.jpg`,
|
||||
`traffic_${String(328 + imageCount).padStart(5, '0')}.jpg`,
|
||||
`traffic_${String(329 + imageCount).padStart(5, '0')}.jpg`,
|
||||
]
|
||||
onUploadImages(sampleNames)
|
||||
setBatches((prev) => [
|
||||
|
|
@ -146,13 +150,15 @@ export const DataTab: React.FC<DataTabProps> = ({
|
|||
>
|
||||
Chọn tệp từ máy tính
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSimulatedSampleUpload}
|
||||
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-xs font-semibold text-slate-700 transition hover:bg-slate-50"
|
||||
>
|
||||
+ Nhập nhanh 3 ảnh mẫu
|
||||
</button>
|
||||
{!hideSampleUpload && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleSimulatedSampleUpload}
|
||||
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-xs font-semibold text-slate-700 transition hover:bg-slate-50"
|
||||
>
|
||||
+ Nhập nhanh 3 ảnh mẫu
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -203,13 +209,13 @@ export const DataTab: React.FC<DataTabProps> = ({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Full Image Table */}
|
||||
{/* Full Image Table (self-paginated) */}
|
||||
<ImageTable
|
||||
projectId={project.id}
|
||||
projectSlug={project.slug}
|
||||
images={images}
|
||||
stats={project.stats}
|
||||
classes={project.classes}
|
||||
memberNames={project.members.map((m) => m.name)}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,20 +1,48 @@
|
|||
import React, { useState } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
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 {
|
||||
projectId?: string
|
||||
projectSlug?: string
|
||||
images?: ImageItem[]
|
||||
classes?: LabelClass[]
|
||||
}
|
||||
|
||||
const FORMAT_MAP = { coco: 'coco_json', yolo: 'yolo_txt', json: 'labelme_json' } as const
|
||||
|
||||
export const ExportButton: React.FC<ExportButtonProps> = ({
|
||||
projectId,
|
||||
projectSlug = 'traffic_camera_v2',
|
||||
images = [],
|
||||
classes = [],
|
||||
}) => {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [isExporting, setIsExporting] = useState(false)
|
||||
|
||||
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 = {
|
||||
dataset: projectSlug,
|
||||
exportFormat: format.toUpperCase(),
|
||||
|
|
@ -49,6 +77,7 @@ export const ExportButton: React.FC<ExportButtonProps> = ({
|
|||
<div className="relative">
|
||||
<button
|
||||
type="button"
|
||||
disabled={isExporting}
|
||||
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"
|
||||
>
|
||||
|
|
|
|||
|
|
@ -1,14 +1,17 @@
|
|||
import React, { useState, useMemo } from 'react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
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'
|
||||
|
||||
interface ImageTableProps {
|
||||
projectId: string
|
||||
projectSlug: string
|
||||
images: ImageItem[]
|
||||
stats: ProjectStats
|
||||
classes: LabelClass[]
|
||||
memberNames: string[]
|
||||
}
|
||||
|
||||
const STATUS_BADGE_MAP: Record<
|
||||
|
|
@ -41,40 +44,93 @@ const STATUS_BADGE_MAP: Record<
|
|||
},
|
||||
}
|
||||
|
||||
const PAGE_SIZE = 50
|
||||
|
||||
export const ImageTable: React.FC<ImageTableProps> = ({
|
||||
projectId,
|
||||
projectSlug,
|
||||
images,
|
||||
stats,
|
||||
classes,
|
||||
memberNames,
|
||||
}) => {
|
||||
const navigate = useNavigate()
|
||||
const [searchQuery, setSearchQuery] = useState('')
|
||||
const [selectedStatus, setSelectedStatus] = useState<'all' | ImageAnnotationStatus>('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 set = new Set<string>()
|
||||
images.forEach((img) => set.add(img.assignedTo.name))
|
||||
return Array.from(set)
|
||||
}, [images])
|
||||
const debouncedSearch = useDebounce(searchQuery, 400)
|
||||
|
||||
const filteredImages = useMemo(() => {
|
||||
return images.filter((img) => {
|
||||
const matchSearch =
|
||||
!searchQuery.trim() ||
|
||||
img.fileName.toLowerCase().includes(searchQuery.trim().toLowerCase())
|
||||
const matchStatus = selectedStatus === 'all' || img.status === selectedStatus
|
||||
const matchMember = selectedMember === 'all' || img.assignedTo.name === selectedMember
|
||||
return matchSearch && matchStatus && matchMember
|
||||
})
|
||||
}, [images, searchQuery, selectedStatus, selectedMember])
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
setIsLoading(true)
|
||||
const load = async () => {
|
||||
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 matchMember = selectedMember === 'all' || img.assignedTo.name === selectedMember
|
||||
return matchSearch && matchStatus && matchMember
|
||||
})
|
||||
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 =
|
||||
stats.totalObjects ??
|
||||
classes.reduce((sum, cls) => sum + cls.count, 0)
|
||||
|
||||
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 (
|
||||
<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
|
||||
searchQuery={searchQuery}
|
||||
onSearchChange={setSearchQuery}
|
||||
onSearchChange={resetPage(setSearchQuery)}
|
||||
selectedStatus={selectedStatus}
|
||||
onStatusChange={setSelectedStatus}
|
||||
onStatusChange={resetPage(setSelectedStatus as (v: string) => void)}
|
||||
selectedMember={selectedMember}
|
||||
onMemberChange={setSelectedMember}
|
||||
onMemberChange={resetPage(setSelectedMember)}
|
||||
memberNames={memberNames}
|
||||
projectId={projectId}
|
||||
projectSlug={projectSlug}
|
||||
images={images}
|
||||
images={shownImages}
|
||||
classes={classes}
|
||||
/>
|
||||
</div>
|
||||
|
|
@ -114,14 +171,20 @@ export const ImageTable: React.FC<ImageTableProps> = ({
|
|||
</tr>
|
||||
</thead>
|
||||
<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>
|
||||
<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.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredImages.map((image) => {
|
||||
rows.map((image) => {
|
||||
const badge = STATUS_BADGE_MAP[image.status]
|
||||
return (
|
||||
<tr
|
||||
|
|
@ -134,9 +197,14 @@ export const ImageTable: React.FC<ImageTableProps> = ({
|
|||
<td className="py-3.5 pl-5 pr-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<img
|
||||
src={image.thumbnailUrl}
|
||||
src={image.thumbnailSmallUrl ?? image.thumbnailUrl}
|
||||
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>
|
||||
<p className="font-mono text-[11px] text-[var(--project-heading)]">
|
||||
|
|
@ -185,6 +253,34 @@ export const ImageTable: React.FC<ImageTableProps> = ({
|
|||
</tbody>
|
||||
</table>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ interface ImageTableFiltersProps {
|
|||
selectedMember: string
|
||||
onMemberChange: (val: string) => void
|
||||
memberNames: string[]
|
||||
projectId?: string
|
||||
projectSlug?: string
|
||||
images?: ImageItem[]
|
||||
classes?: LabelClass[]
|
||||
|
|
@ -23,6 +24,7 @@ export const ImageTableFilters: React.FC<ImageTableFiltersProps> = ({
|
|||
selectedMember,
|
||||
onMemberChange,
|
||||
memberNames,
|
||||
projectId,
|
||||
projectSlug,
|
||||
images,
|
||||
classes,
|
||||
|
|
@ -104,7 +106,7 @@ export const ImageTableFilters: React.FC<ImageTableFiltersProps> = ({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
<ExportButton projectSlug={projectSlug} images={images} classes={classes} />
|
||||
<ExportButton projectId={projectId} projectSlug={projectSlug} images={images} classes={classes} />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import React from 'react'
|
||||
import { ImageItem, Project } from '@/types'
|
||||
import { Project } from '@/types'
|
||||
import { StatusCards } from './StatusCards'
|
||||
import { LabelDistribution } from './LabelDistribution'
|
||||
import { MemberAssignment } from './MemberAssignment'
|
||||
|
|
@ -7,13 +7,11 @@ import { ImageTable } from './ImageTable'
|
|||
|
||||
interface OverviewTabProps {
|
||||
project: Project
|
||||
images: ImageItem[]
|
||||
onSwitchTab: (tab: 'overview' | 'data' | 'labels' | 'members' | 'settings') => void
|
||||
}
|
||||
|
||||
export const OverviewTab: React.FC<OverviewTabProps> = ({
|
||||
project,
|
||||
images,
|
||||
onSwitchTab,
|
||||
}) => {
|
||||
return (
|
||||
|
|
@ -38,13 +36,13 @@ export const OverviewTab: React.FC<OverviewTabProps> = ({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image Table */}
|
||||
{/* Image Table (self-paginated; never the whole dataset) */}
|
||||
<ImageTable
|
||||
projectId={project.id}
|
||||
projectSlug={project.slug}
|
||||
images={images}
|
||||
stats={project.stats}
|
||||
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)]">
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
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 { getMockDb, saveMockDb } from './mockData'
|
||||
|
||||
|
|
@ -16,6 +17,17 @@ export async function getAnnotation(
|
|||
projectId: string,
|
||||
imageId: string
|
||||
): 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)
|
||||
const db = getMockDb()
|
||||
const key = `${projectId}:${imageId}`
|
||||
|
|
@ -52,6 +64,24 @@ export async function saveAnnotation(
|
|||
imageId: string,
|
||||
data: SaveAnnotationInput
|
||||
): 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)
|
||||
const db = getMockDb()
|
||||
const key = `${projectId}:${imageId}`
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios'
|
||||
import { API_BASE_URL, STORAGE_KEYS } from '@/app/constants'
|
||||
import { getSessionId } from '@/utils/session'
|
||||
import { getStorageItem, removeStorageItem } from '@/utils/storage'
|
||||
|
||||
export const api = axios.create({
|
||||
|
|
@ -16,6 +17,10 @@ api.interceptors.request.use(
|
|||
if (token && config.headers) {
|
||||
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
|
||||
},
|
||||
(error: AxiosError) => Promise.reject(error)
|
||||
|
|
@ -27,6 +32,9 @@ api.interceptors.response.use(
|
|||
if (error.response?.status === 401) {
|
||||
removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN)
|
||||
removeStorageItem(STORAGE_KEYS.REFRESH_TOKEN)
|
||||
if (typeof window !== 'undefined' && !window.location.pathname.startsWith('/login')) {
|
||||
window.location.href = '/login'
|
||||
}
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 { getStorageItem, removeStorageItem, setStorageItem } from '@/utils/storage'
|
||||
import { delay } from './api'
|
||||
import { api, delay } from './api'
|
||||
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> {
|
||||
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)
|
||||
const db = getMockDb()
|
||||
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()}`,
|
||||
}
|
||||
|
||||
setStorageItem(STORAGE_KEYS.ACCESS_TOKEN, response.accessToken)
|
||||
setStorageItem(STORAGE_KEYS.REFRESH_TOKEN, response.refreshToken)
|
||||
setStorageItem(STORAGE_KEYS.CURRENT_USER, user)
|
||||
|
||||
persistSession(response)
|
||||
return response
|
||||
}
|
||||
|
||||
|
|
@ -60,14 +71,17 @@ export async function loginWithSSO(provider: 'google' | 'microsoft' | 'sso' = 's
|
|||
refreshToken: `mock-sso-refresh-${provider}-${Date.now()}`,
|
||||
}
|
||||
|
||||
setStorageItem(STORAGE_KEYS.ACCESS_TOKEN, response.accessToken)
|
||||
setStorageItem(STORAGE_KEYS.REFRESH_TOKEN, response.refreshToken)
|
||||
setStorageItem(STORAGE_KEYS.CURRENT_USER, user)
|
||||
|
||||
persistSession(response)
|
||||
return response
|
||||
}
|
||||
|
||||
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)
|
||||
removeStorageItem(STORAGE_KEYS.ACCESS_TOKEN)
|
||||
removeStorageItem(STORAGE_KEYS.REFRESH_TOKEN)
|
||||
|
|
@ -75,6 +89,17 @@ export async function logout(): Promise<void> {
|
|||
}
|
||||
|
||||
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)
|
||||
const storedUser = getStorageItem<User | null>(STORAGE_KEYS.CURRENT_USER, null)
|
||||
if (storedUser) return storedUser
|
||||
|
|
|
|||
40
src/services/eventService.ts
Normal file
40
src/services/eventService.ts
Normal 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)
|
||||
}
|
||||
}
|
||||
|
|
@ -1,8 +1,12 @@
|
|||
import { AnnotationShape, ImageItem } from '@/types'
|
||||
import { exportToLabelMeJSON, LabelMeJSON } from '@/utils/labelme'
|
||||
import { exportSegmentationMaskPNG } from '@/utils/mask'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { getAnnotation } from './annotationService'
|
||||
import { delay } from './api'
|
||||
import { getProjectImages } from './imageService'
|
||||
import { getMockDb } from './mockData'
|
||||
import { getProjectById } from './projectService'
|
||||
|
||||
export type ExportFormat = 'labelme_json' | 'coco_json' | 'yolo_txt' | 'mask_png'
|
||||
|
||||
|
|
@ -10,6 +14,33 @@ export async function exportProjectLabels(
|
|||
projectId: string,
|
||||
format: ExportFormat = 'coco_json'
|
||||
): 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)
|
||||
const db = getMockDb()
|
||||
const project = db.projects.find((p) => p.id === projectId || p.slug === projectId) ?? db.projects[0]
|
||||
|
|
@ -46,13 +77,7 @@ export async function exportProjectLabels(
|
|||
type: 'application/json;charset=utf-8',
|
||||
})
|
||||
const url = URL.createObjectURL(blob)
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = fileName
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
URL.revokeObjectURL(url)
|
||||
triggerDownload(url, fileName)
|
||||
}
|
||||
|
||||
return {
|
||||
|
|
@ -61,6 +86,17 @@ export async function exportProjectLabels(
|
|||
}
|
||||
}
|
||||
|
||||
function triggerDownload(url: string, fileName: string): void {
|
||||
if (typeof document === 'undefined') return
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = fileName
|
||||
document.body.appendChild(link)
|
||||
link.click()
|
||||
document.body.removeChild(link)
|
||||
URL.revokeObjectURL(url)
|
||||
}
|
||||
|
||||
export function downloadImageLabelMeJSON(
|
||||
image: ImageItem,
|
||||
shapes: AnnotationShape[]
|
||||
|
|
|
|||
|
|
@ -1,7 +1,52 @@
|
|||
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'
|
||||
|
||||
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 {
|
||||
status?: ImageAnnotationStatus | 'all'
|
||||
assigneeId?: string | 'all'
|
||||
|
|
@ -9,10 +54,63 @@ export interface ImageFilterParams {
|
|||
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(
|
||||
projectId: string,
|
||||
filters?: ImageFilterParams
|
||||
): 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)
|
||||
const db = getMockDb()
|
||||
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> {
|
||||
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)
|
||||
const db = getMockDb()
|
||||
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(
|
||||
projectId: string,
|
||||
files: { fileName: string; url?: string; width?: number; height?: number }[]
|
||||
files: UploadFileItem[]
|
||||
): 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)
|
||||
const db = getMockDb()
|
||||
const created: ImageItem[] = []
|
||||
|
|
@ -122,6 +269,10 @@ export async function updateImageStatus(
|
|||
imageId: string,
|
||||
status: ImageAnnotationStatus
|
||||
): Promise<ImageItem> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
await api.patch(`/projects/${projectId}/images/${imageId}`, null, { params: { status } })
|
||||
return getImageById(projectId, imageId)
|
||||
}
|
||||
await delay(120)
|
||||
const db = getMockDb()
|
||||
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 prevStatus = current.status
|
||||
track('image.status', {
|
||||
project_id: projectId,
|
||||
image_id: imageId,
|
||||
payload: { from: prevStatus, to: status },
|
||||
})
|
||||
const updated: ImageItem = {
|
||||
...current,
|
||||
status,
|
||||
|
|
|
|||
|
|
@ -1,19 +1,52 @@
|
|||
import { LabelClass } from '@/types'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { getColorForClass } from '@/utils/colors'
|
||||
import { delay } from './api'
|
||||
import { api, delay } from './api'
|
||||
import { getMockDb, saveMockDb } from './mockData'
|
||||
import { getProjectById } from './projectService'
|
||||
|
||||
export async function getLabels(projectId: string): Promise<LabelClass[]> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
const project = await getProjectById(projectId)
|
||||
return project.classes
|
||||
}
|
||||
await delay(80)
|
||||
const db = getMockDb()
|
||||
const project = db.projects.find((p) => p.id === projectId || p.slug === projectId)
|
||||
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(
|
||||
projectId: string,
|
||||
input: { name: string; color?: string }
|
||||
): 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)
|
||||
const db = getMockDb()
|
||||
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> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
const existing = await getLabels(projectId)
|
||||
await replaceLabels(
|
||||
projectId,
|
||||
existing.filter((c) => c.id !== labelId)
|
||||
)
|
||||
return
|
||||
}
|
||||
await delay(120)
|
||||
const db = getMockDb()
|
||||
const project = db.projects.find((p) => p.id === projectId || p.slug === projectId)
|
||||
|
|
|
|||
|
|
@ -529,7 +529,7 @@ const INITIAL_ACTIVITIES: ActivityLog[] = [
|
|||
},
|
||||
]
|
||||
|
||||
const INITIAL_ROLE_PERMISSIONS: RolePermissionItem[] = [
|
||||
export const INITIAL_ROLE_PERMISSIONS: RolePermissionItem[] = [
|
||||
{
|
||||
role: 'admin',
|
||||
title: 'Admin (Quản trị viên)',
|
||||
|
|
|
|||
|
|
@ -1,7 +1,49 @@
|
|||
import { ActivityLog, CreateProjectInput, Project, ProjectStatus, TaskType } from '@/types'
|
||||
import { delay } from './api'
|
||||
import { ActivityLog, CreateProjectInput, LabelClass, Project, ProjectStatus, TaskType } from '@/types'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { api, delay } from './api'
|
||||
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 {
|
||||
search?: string
|
||||
taskType?: TaskType | 'all'
|
||||
|
|
@ -9,6 +51,10 @@ export interface ProjectFilterParams {
|
|||
}
|
||||
|
||||
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)
|
||||
const db = getMockDb()
|
||||
let list = [...db.projects]
|
||||
|
|
@ -35,6 +81,10 @@ export async function getProjects(params?: ProjectFilterParams): 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)
|
||||
const db = getMockDb()
|
||||
const found =
|
||||
|
|
@ -45,7 +95,38 @@ export async function getProjectById(projectId: string): Promise<Project> {
|
|||
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> {
|
||||
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)
|
||||
const db = getMockDb()
|
||||
|
||||
|
|
@ -185,6 +266,16 @@ export async function updateProject(
|
|||
projectId: string,
|
||||
updates: Partial<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)
|
||||
const db = getMockDb()
|
||||
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> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
await api.delete(`/projects/${projectId}`)
|
||||
return
|
||||
}
|
||||
await delay(180)
|
||||
const db = getMockDb()
|
||||
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[]> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
const { data } = await api.get<ActivityLog[]>('/activities', { params: { limit: 30 } })
|
||||
return data
|
||||
}
|
||||
await delay(100)
|
||||
const db = getMockDb()
|
||||
return db.activities
|
||||
|
|
|
|||
|
|
@ -1,8 +1,44 @@
|
|||
import { InviteMemberInput, RolePermissionItem, UserRole, UserStatus, WorkspaceMember } from '@/types'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
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'
|
||||
|
||||
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 {
|
||||
search?: string
|
||||
role?: UserRole | 'all'
|
||||
|
|
@ -10,6 +46,21 @@ export interface MemberFilterParams {
|
|||
}
|
||||
|
||||
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)
|
||||
const db = getMockDb()
|
||||
let list = [...db.members]
|
||||
|
|
@ -33,6 +84,14 @@ export async function getMembers(params?: MemberFilterParams): Promise<Workspace
|
|||
}
|
||||
|
||||
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)
|
||||
const db = getMockDb()
|
||||
|
||||
|
|
@ -88,6 +147,10 @@ export async function updateMemberRole(
|
|||
memberId: string,
|
||||
role: UserRole
|
||||
): Promise<WorkspaceMember> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
const { data } = await api.patch<any>(`/users/${memberId}`, { role })
|
||||
return mapMember(data, 0)
|
||||
}
|
||||
await delay(140)
|
||||
const db = getMockDb()
|
||||
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> {
|
||||
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)
|
||||
const db = getMockDb()
|
||||
const idx = db.members.findIndex((m) => m.id === memberId)
|
||||
|
|
@ -134,7 +204,32 @@ export async function toggleMemberStatus(memberId: string): Promise<WorkspaceMem
|
|||
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[]> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
// Static reference data, same for every workspace.
|
||||
return INITIAL_ROLE_PERMISSIONS
|
||||
}
|
||||
await delay(80)
|
||||
const db = getMockDb()
|
||||
return db.rolePermissions
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ export interface ImageItem {
|
|||
fileName: string
|
||||
url: string
|
||||
thumbnailUrl: string
|
||||
thumbnailSmallUrl?: string
|
||||
width: number
|
||||
height: number
|
||||
status: ImageAnnotationStatus
|
||||
|
|
|
|||
23
src/utils/session.ts
Normal file
23
src/utils/session.ts
Normal 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()
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue