diff --git a/package-lock.json b/package-lock.json index 8fbb7f5..1d399d8 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1036,9 +1036,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1194,9 +1191,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1211,9 +1205,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1228,9 +1219,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1245,9 +1233,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1262,9 +1247,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1279,9 +1261,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1296,9 +1275,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1313,9 +1289,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1330,9 +1303,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1347,9 +1317,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1364,9 +1331,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1381,9 +1345,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1398,9 +1359,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ diff --git a/restart_web.sh b/restart_web.sh new file mode 100644 index 0000000..a46dfe0 --- /dev/null +++ b/restart_web.sh @@ -0,0 +1,8 @@ +#!/bin/bash +# Restart danable web dev server (pattern lives here, never in caller cmdline). +pkill -f 'vite --host 0\.0\.0\.0 --port 5173' 2>/dev/null +sleep 2 +cd /home/hailt/danagble/anotation-frontend +setsid -f ./node_modules/.bin/vite --host 0.0.0.0 --port 5173 >/tmp/danable-web.log 2>&1 +sleep 5 +curl -s -o /dev/null -w "web=%{http_code}\n" localhost:5173/ diff --git a/src/hooks/useAuth.ts b/src/hooks/useAuth.ts index ac0bcf2..6d98785 100644 --- a/src/hooks/useAuth.ts +++ b/src/hooks/useAuth.ts @@ -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) } diff --git a/src/layouts/components/Sidebar/RecentProjects.tsx b/src/layouts/components/Sidebar/RecentProjects.tsx index aed48c1..cd43434 100644 --- a/src/layouts/components/Sidebar/RecentProjects.tsx +++ b/src/layouts/components/Sidebar/RecentProjects.tsx @@ -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(() => + 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 (
diff --git a/src/layouts/components/Sidebar/SidebarNav.tsx b/src/layouts/components/Sidebar/SidebarNav.tsx index 2f481d5..09837f7 100644 --- a/src/layouts/components/Sidebar/SidebarNav.tsx +++ b/src/layouts/components/Sidebar/SidebarNav.tsx @@ -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', }, diff --git a/src/pages/annotator/AnnotatorPage.tsx b/src/pages/annotator/AnnotatorPage.tsx index 05f8e83..b0f8ab8 100644 --- a/src/pages/annotator/AnnotatorPage.tsx +++ b/src/pages/annotator/AnnotatorPage.tsx @@ -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 ( +
+ {loadError ? ( + <> +

Không tải được dự án

+

{loadError}

+ + + ) : ( + <> +
+ Đang tải dự án... + + )} +
+ ) + } + return (
{/* Top Project Title & Action Buttons */} diff --git a/src/pages/annotator/annotatorStore.ts b/src/pages/annotator/annotatorStore.ts index 1be2c49..5fc84f1 100644 --- a/src/pages/annotator/annotatorStore.ts +++ b/src/pages/annotator/annotatorStore.ts @@ -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 { + 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 { + const defaultTool: AnnotationTool = + project.taskType === 'classification' + ? 'select' + : project.taskType === 'object_detection' + ? 'bbox' + : 'polygon' + const fallbackClass = project.classes[0]?.id ?? '' + const classificationByImageId: Record = {} + const flagsByImageId: Record = {} + const statusByImageId: Record = {} + 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 | null = null + export const useAnnotatorStore = create((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((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((set, get) => ({ ], historyFuture: [], }) + get().scheduleAutosave(); }, toggleFlag: (flag) => { @@ -698,6 +856,7 @@ export const useAnnotatorStore = create((set, get) => ({ }, }, }) + get().scheduleAutosave(); }, setShowBoxes: (show) => set({ showBoxes: show }), @@ -735,6 +894,7 @@ export const useAnnotatorStore = create((set, get) => ({ [currentImage.id]: updated, }, }) + get().scheduleAutosave(); }, updateSelectedShapeGroup: (groupId) => { @@ -751,6 +911,7 @@ export const useAnnotatorStore = create((set, get) => ({ [currentImage.id]: updated, }, }) + get().scheduleAutosave(); }, addBoundingBox: (bbox) => { @@ -792,6 +953,7 @@ export const useAnnotatorStore = create((set, get) => ({ ], historyFuture: [], }) + get().scheduleAutosave(); }, updateBoundingBox: (shapeId, bbox) => { @@ -868,6 +1030,7 @@ export const useAnnotatorStore = create((set, get) => ({ ], historyFuture: [], }) + get().scheduleAutosave(); }, cancelDraftPolygon: () => set({ draftPolygonPoints: [] }), @@ -917,6 +1080,7 @@ export const useAnnotatorStore = create((set, get) => ({ ], historyFuture: [], }) + get().scheduleAutosave(); }, deletePolygonVertex: (shapeId, vertexIndex) => { @@ -940,6 +1104,7 @@ export const useAnnotatorStore = create((set, get) => ({ [currentImage.id]: updated, }, }) + get().scheduleAutosave(); }, addPointShape: (pt) => { @@ -977,6 +1142,7 @@ export const useAnnotatorStore = create((set, get) => ({ ], historyFuture: [], }) + get().scheduleAutosave(); }, updatePointShape: (shapeId, pt) => { @@ -1009,6 +1175,7 @@ export const useAnnotatorStore = create((set, get) => ({ [currentImage.id]: updated, }, }) + get().scheduleAutosave(); }, toggleAllShapesVisibility: () => { @@ -1024,6 +1191,7 @@ export const useAnnotatorStore = create((set, get) => ({ [currentImage.id]: updated, }, }) + get().scheduleAutosave(); }, deleteShape: (shapeId) => { @@ -1050,12 +1218,14 @@ export const useAnnotatorStore = create((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((set, get) => ({ historyPast: state.historyPast.slice(0, -1), historyFuture: [currentSnapshot, ...state.historyFuture], }) + get().scheduleAutosave(); }, redo: () => { @@ -1101,15 +1272,48 @@ export const useAnnotatorStore = create((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((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') + }) + } }, })) diff --git a/src/pages/annotator/components/canvas/AnnotationCanvas.tsx b/src/pages/annotator/components/canvas/AnnotationCanvas.tsx index a870197..3396027 100644 --- a/src/pages/annotator/components/canvas/AnnotationCanvas.tsx +++ b/src/pages/annotator/components/canvas/AnnotationCanvas.tsx @@ -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(null) + const stageRef = useRef(null) + const containerRef = useRef(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(null) const [cursorPoint, setCursorPoint] = useState(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): 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) => { + 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) => { + 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) => { 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 (
-
-
- + {stageW > 0 && stageH > 0 && ( + { + 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} > - + + - {project.taskType === 'object_detection' && ( - { + 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' && ( + { + 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} + /> + )} + + { - 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' && ( - { - setInteraction({ - type: 'drag-vertex', - shapeId, - vertexIndex, - }) - }} - onInsertVertexOnEdge={(shapeId, afterIndex, pt) => { - insertPolygonVertex(shapeId, afterIndex, pt) - }} - onCloseDraftPolygon={closeDraftPolygon} - /> - )} - - - - - -
+ + + + )} {/* Bottom-left dark translucent pill overlay */} diff --git a/src/pages/annotator/components/canvas/BoundingBoxTool.tsx b/src/pages/annotator/components/canvas/BoundingBoxTool.tsx index abb36ab..486ab43 100644 --- a/src/pages/annotator/components/canvas/BoundingBoxTool.tsx +++ b/src/pages/annotator/components/canvas/BoundingBoxTool.tsx @@ -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 = ({ 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 ( - + {bboxShapes.map((shape) => { const box = shape.bbox! const isSelected = shape.id === selectedShapeId @@ -51,113 +65,137 @@ export const BoundingBoxTool: React.FC = ({ ] return ( - - {/* Main Bounding Box Rectangle */} - + {/* Light interior tint (separate node: border below stays crisp) */} + { + 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 */} + { - 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 */} - { - e.stopPropagation() + e.cancelBubble = true onSelectShape(shape.id) }} + style={{ cursor: 'pointer' }} > - - - {shape.labelName} - - + fontStyle="bold" + text={shape.labelName} + /> + {/* Corner Resize Handles when Selected */} {isSelected && corners.map((corner) => ( - { - 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 }} /> ))} - + ) })} {/* Active Draft Bounding Box while user drags */} {draftBox && draftBox.width > 4 && draftBox.height > 4 && ( - - + + - - - {activeClassName} - - + fontStyle="bold" + text={activeClassName} + /> + )} - + ) } diff --git a/src/pages/annotator/components/canvas/ImageViewer.tsx b/src/pages/annotator/components/canvas/ImageViewer.tsx index beb74e2..068182a 100644 --- a/src/pages/annotator/components/canvas/ImageViewer.tsx +++ b/src/pages/annotator/components/canvas/ImageViewer.tsx @@ -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 = ({ url, width, height }) => { - return ( - - ) +// 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 = ({ url, thumbUrl, width, height }) => { + const [current, setCurrent] = useState(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 } diff --git a/src/pages/annotator/components/canvas/PointTool.tsx b/src/pages/annotator/components/canvas/PointTool.tsx index 44f9e0d..c41c1b0 100644 --- a/src/pages/annotator/components/canvas/PointTool.tsx +++ b/src/pages/annotator/components/canvas/PointTool.tsx @@ -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 = ({ const pointShapes = shapes.filter((s) => s.type === 'point' && s.visible && s.point) return ( - + {pointShapes.map((shape) => { const pt = shape.point! const isSelected = shape.id === selectedShapeId return ( - { - e.stopPropagation() + e.cancelBubble = true onSelectShape(shape.id) }} + style={{ cursor: 'pointer' }} > - - - + + - - {shape.labelName} - - + fontStyle="bold" + text={shape.labelName} + /> + ) })} - + ) } diff --git a/src/pages/annotator/components/canvas/PolygonTool.tsx b/src/pages/annotator/components/canvas/PolygonTool.tsx index 513ec1a..fc06e32 100644 --- a/src/pages/annotator/components/canvas/PolygonTool.tsx +++ b/src/pages/annotator/components/canvas/PolygonTool.tsx @@ -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 = ({ ) return ( - + {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 = ({ const tagY = Math.max(8, topPoint.y - 46) return ( - - {/* Polygon Filled Mask */} - + {/* Polygon Filled Mask: tint and border split (see BoundingBoxTool) */} + { - e.stopPropagation() + e.cancelBubble = true onSelectShape(shape.id) }} + style={{ cursor: 'pointer' }} + /> + {/* Clickable/Double-clickable Edges for inserting a new vertex */} @@ -87,115 +88,110 @@ export const PolygonTool: React.FC = ({ pts.map((pt, idx) => { const nextPt = pts[(idx + 1) % pts.length]! return ( - { - 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 && ( - - + - - {tagText} - - + fontStyle="bold" + text={tagText} + /> + )} {/* Draggable Vertex Handles on Selected Polygon */} {isSelected && pts.map((pt, idx) => ( - { - e.stopPropagation() + e.cancelBubble = true if (vertexEditEnabled) { - onStartDragVertex(e, shape.id, idx) + onStartDragVertex(shape.id, idx) } }} + style={{ + cursor: vertexEditEnabled ? 'grab' : 'pointer', + }} /> ))} - + ) })} {/* In-progress Draft Polygon while clicking points */} {draftPolygonPoints.length > 0 && ( - - + `${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 ( - { if (isFirst && draftPolygonPoints.length >= 3) { - e.stopPropagation() + e.cancelBubble = true onCloseDraftPolygon() } }} + style={{ cursor: 'pointer' }} /> ) })} - + )} - + ) } diff --git a/src/pages/annotator/components/header/AnnotatorHeader.tsx b/src/pages/annotator/components/header/AnnotatorHeader.tsx index 9e81d52..34d316b 100644 --- a/src/pages/annotator/components/header/AnnotatorHeader.tsx +++ b/src/pages/annotator/components/header/AnnotatorHeader.tsx @@ -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 = () => { Về tổng quan -
) diff --git a/src/pages/annotator/components/header/SaveAndNextButton.tsx b/src/pages/annotator/components/header/SaveAndNextButton.tsx deleted file mode 100644 index 5b526cf..0000000 --- a/src/pages/annotator/components/header/SaveAndNextButton.tsx +++ /dev/null @@ -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 ( - - ) -} diff --git a/src/pages/annotator/components/navigator/SaveStatus.tsx b/src/pages/annotator/components/navigator/SaveStatus.tsx index b8226cc..c6a222d 100644 --- a/src/pages/annotator/components/navigator/SaveStatus.tsx +++ b/src/pages/annotator/components/navigator/SaveStatus.tsx @@ -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 (
-
- ✓ - Đã lưu lúc {lastSavedAt} -
+ {isSaving ? ( +
+ + Đang lưu… +
+ ) : ( +
+ ✓ + Đã lưu lúc {lastSavedAt} +
+ )} {project.taskType === 'segmentation' && (
diff --git a/src/pages/annotator/components/navigator/ThumbnailStrip.tsx b/src/pages/annotator/components/navigator/ThumbnailStrip.tsx index 6e44446..cdb7987 100644 --- a/src/pages/annotator/components/navigator/ThumbnailStrip.tsx +++ b/src/pages/annotator/components/navigator/ThumbnailStrip.tsx @@ -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 (
- {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.fileName}
diff --git a/src/pages/auth/LoginPage.tsx b/src/pages/auth/LoginPage.tsx index b185a7d..601cddf 100644 --- a/src/pages/auth/LoginPage.tsx +++ b/src/pages/auth/LoginPage.tsx @@ -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 */} void handleLogin(data)} + onSSOLogin={() => void handleSSOLogin()} isLoading={isLoading} + serverError={authError} /> {/* Liên kết điều khoản & ngôn ngữ cuối trang */} diff --git a/src/pages/auth/components/LoginForm.tsx b/src/pages/auth/components/LoginForm.tsx index f31e4fd..1394904 100644 --- a/src/pages/auth/components/LoginForm.tsx +++ b/src/pages/auth/components/LoginForm.tsx @@ -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 = ({ onSubmit, onSSOLogin, isLoading = false, + serverError = null, }) => { - const [email, setEmail] = useState('minhanh@visionlab.vn') - const [password, setPassword] = useState('••••••••••••') + const [email, setEmail] = useState(USE_MOCK_DATA ? 'minhanh@visionlab.vn' : '') + const [password, setPassword] = useState(USE_MOCK_DATA ? '••••••••••••' : '') const [rememberMe, setRememberMe] = useState(true) const [showPassword, setShowPassword] = useState(false) const [errorMessage, setErrorMessage] = useState(null) @@ -94,9 +97,9 @@ export const LoginForm: React.FC = ({
{/* Thông báo lỗi nếu có */} - {errorMessage && ( + {(errorMessage || serverError) && (
- {errorMessage} + {errorMessage ?? serverError}
)} diff --git a/src/pages/projects/ProjectDetailPage.tsx b/src/pages/projects/ProjectDetailPage.tsx index 928964f..3f793fe 100644 --- a/src/pages/projects/ProjectDetailPage.tsx +++ b/src/pages/projects/ProjectDetailPage.tsx @@ -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(null) const [activeTab, setActiveTab] = useState('overview') - const [project, setProject] = useState(() => getProjectById(id)) - const [images, setImages] = useState(() => getProjectImages(project.id)) + const [project, setProject] = useState(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 ( +
+
+
+ Đang tải dự án... +
+
+ ) } 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 = () => {
@@ -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 diff --git a/src/pages/projects/ProjectListPage.tsx b/src/pages/projects/ProjectListPage.tsx index cbb63c8..4759a30 100644 --- a/src/pages/projects/ProjectListPage.tsx +++ b/src/pages/projects/ProjectListPage.tsx @@ -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 = () => {
{/* 4 Summary Cards */} - + {/* Filter Bar */} { /> {/* Project Cards Grid / List */} - {filteredProjects.length === 0 ? ( + {!USE_MOCK_DATA && apiLoading && projects.length === 0 ? ( +
+
+
+ Đang tải dự án... +
+
+ ) : filteredProjects.length === 0 ? (

Không tìm thấy dự án phù hợp @@ -138,7 +177,7 @@ export const ProjectListPage: React.FC = () => { void handleDeleteProject(pid)} /> ))}

@@ -155,7 +194,7 @@ export const ProjectListPage: React.FC = () => { setIsCreateModalOpen(false)} - onCreate={handleCreateProject} + onCreate={(input) => void handleCreateProject(input)} />
) diff --git a/src/pages/projects/components/ProjectCard.tsx b/src/pages/projects/components/ProjectCard.tsx index c6a8997..7a3056a 100644 --- a/src/pages/projects/components/ProjectCard.tsx +++ b/src/pages/projects/components/ProjectCard.tsx @@ -76,6 +76,8 @@ export const ProjectCard: React.FC = ({ project, onDelete }) = {project.name} diff --git a/src/pages/projects/components/detail/DataTab.tsx b/src/pages/projects/components/detail/DataTab.tsx index 5c3d9a5..42609b6 100644 --- a/src/pages/projects/components/detail/DataTab.tsx +++ b/src/pages/projects/components/detail/DataTab.tsx @@ -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 = ({ project, - images, onUploadImages, + hideSampleUpload = false, }) => { + const imageCount = project.stats.totalImages const fileInputRef = useRef(null) const [isDragging, setIsDragging] = useState(false) const [batches, setBatches] = useState([ @@ -53,15 +54,18 @@ export const DataTab: React.FC = ({ 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 = ({ 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 = ({ > Chọn tệp từ máy tính - + {!hideSampleUpload && ( + + )}
@@ -203,13 +209,13 @@ export const DataTab: React.FC = ({
- {/* Full Image Table */} + {/* Full Image Table (self-paginated) */} m.name)} /> ) diff --git a/src/pages/projects/components/detail/ExportButton.tsx b/src/pages/projects/components/detail/ExportButton.tsx index 516b723..7baaccb 100644 --- a/src/pages/projects/components/detail/ExportButton.tsx +++ b/src/pages/projects/components/detail/ExportButton.tsx @@ -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 = ({ + 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 = ({
+ + Trang {page + 1} / {formatNum(pageCount)} + + +
+ ) } diff --git a/src/pages/projects/components/detail/ImageTableFilters.tsx b/src/pages/projects/components/detail/ImageTableFilters.tsx index 9762ad8..6bbcca2 100644 --- a/src/pages/projects/components/detail/ImageTableFilters.tsx +++ b/src/pages/projects/components/detail/ImageTableFilters.tsx @@ -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 = ({ selectedMember, onMemberChange, memberNames, + projectId, projectSlug, images, classes, @@ -104,7 +106,7 @@ export const ImageTableFilters: React.FC = ({ - + ) } diff --git a/src/pages/projects/components/detail/OverviewTab.tsx b/src/pages/projects/components/detail/OverviewTab.tsx index 9f07fa1..0b1c867 100644 --- a/src/pages/projects/components/detail/OverviewTab.tsx +++ b/src/pages/projects/components/detail/OverviewTab.tsx @@ -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 = ({ project, - images, onSwitchTab, }) => { return ( @@ -38,13 +36,13 @@ export const OverviewTab: React.FC = ({ - {/* Image Table */} + {/* Image Table (self-paginated; never the whole dataset) */} m.name)} />
diff --git a/src/services/annotationService.ts b/src/services/annotationService.ts index 7905009..9a4affd 100644 --- a/src/services/annotationService.ts +++ b/src/services/annotationService.ts @@ -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 { + if (!USE_MOCK_DATA) { + const { data } = await api.get(`/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 { + 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}` diff --git a/src/services/api.ts b/src/services/api.ts index 4873512..06c44d1 100644 --- a/src/services/api.ts +++ b/src/services/api.ts @@ -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) } diff --git a/src/services/authService.ts b/src/services/authService.ts index 1bf911e..f6d843e 100644 --- a/src/services/authService.ts +++ b/src/services/authService.ts @@ -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 { + if (!USE_MOCK_DATA) { + const { data } = await api.post('/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 { 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 { + 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 { } export async function getCurrentUser(): Promise { + if (!USE_MOCK_DATA) { + try { + const { data } = await api.get('/auth/me') + setStorageItem(STORAGE_KEYS.CURRENT_USER, data) + return data + } catch { + const stored = getStorageItem(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(STORAGE_KEYS.CURRENT_USER, null) if (storedUser) return storedUser diff --git a/src/services/eventService.ts b/src/services/eventService.ts new file mode 100644 index 0000000..5085e87 --- /dev/null +++ b/src/services/eventService.ts @@ -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 +} + +const buffer: TrackedEvent[] = [] +let timer: ReturnType | null = null + +async function flush(): Promise { + 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 = {} +): void { + buffer.push({ action, ...opts }) + if (buffer.length >= 20) { + void flush() + return + } + if (timer === null) { + timer = setTimeout(() => void flush(), 3000) + } +} diff --git a/src/services/exportService.ts b/src/services/exportService.ts index 3c259f8..1badebf 100644 --- a/src/services/exportService.ts +++ b/src/services/exportService.ts @@ -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[] diff --git a/src/services/imageService.ts b/src/services/imageService.ts index b8d30fc..8e0f66c 100644 --- a/src/services/imageService.ts +++ b/src/services/imageService.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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, diff --git a/src/services/labelService.ts b/src/services/labelService.ts index 0dcb93a..040f606 100644 --- a/src/services/labelService.ts +++ b/src/services/labelService.ts @@ -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 { + 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 { + const { data } = await api.put(`/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 { + 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 { + 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) diff --git a/src/services/mockData.ts b/src/services/mockData.ts index 62562ba..077d224 100644 --- a/src/services/mockData.ts +++ b/src/services/mockData.ts @@ -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)', diff --git a/src/services/projectService.ts b/src/services/projectService.ts index 00d540f..067edef 100644 --- a/src/services/projectService.ts +++ b/src/services/projectService.ts @@ -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 { + if (!USE_MOCK_DATA) { + const { data } = await api.get('/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 { + if (!USE_MOCK_DATA) { + const { data } = await api.get(`/projects/${projectId}`) + return mapProject(data) + } await delay(120) const db = getMockDb() const found = @@ -45,7 +95,38 @@ export async function getProjectById(projectId: string): Promise { 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 { + if (!USE_MOCK_DATA) { + const { data } = await api.post('/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 ): Promise { + if (!USE_MOCK_DATA) { + const { data } = await api.patch(`/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 { + 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 { } export async function getRecentActivities(): Promise { + if (!USE_MOCK_DATA) { + const { data } = await api.get('/activities', { params: { limit: 30 } }) + return data + } await delay(100) const db = getMockDb() return db.activities diff --git a/src/services/userService.ts b/src/services/userService.ts index 6a86a7d..848526a 100644 --- a/src/services/userService.ts +++ b/src/services/userService.ts @@ -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 = { + 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 { + if (!USE_MOCK_DATA) { + const { data } = await api.get('/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 { + if (!USE_MOCK_DATA) { + const { data } = await api.post('/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 { + if (!USE_MOCK_DATA) { + const { data } = await api.patch(`/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 { + 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(`/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 { + if (!USE_MOCK_DATA) { + const { data } = await api.patch(`/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 { + if (!USE_MOCK_DATA) { + // Static reference data, same for every workspace. + return INITIAL_ROLE_PERMISSIONS + } await delay(80) const db = getMockDb() return db.rolePermissions diff --git a/src/types/image.ts b/src/types/image.ts index 511fe31..21359d7 100644 --- a/src/types/image.ts +++ b/src/types/image.ts @@ -6,6 +6,7 @@ export interface ImageItem { fileName: string url: string thumbnailUrl: string + thumbnailSmallUrl?: string width: number height: number status: ImageAnnotationStatus diff --git a/src/utils/session.ts b/src/utils/session.ts new file mode 100644 index 0000000..2932ab2 --- /dev/null +++ b/src/utils/session.ts @@ -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() + } +}