feat: add dataset import and upload flow
This commit is contained in:
parent
e010bb5558
commit
7352228c60
33 changed files with 2161 additions and 252 deletions
|
|
@ -1,7 +1,21 @@
|
|||
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import * as projectService from '@/services/projectService'
|
||||
import { useProjectStore } from '@/stores/projectStore'
|
||||
import { CreateProjectInput, Project } from '@/types'
|
||||
import { ActivityLog, CreateProjectInput, Project } from '@/types'
|
||||
|
||||
// Shared activity feed: one cache key for the page, the bell and mutations.
|
||||
// NOTE: the empty fallback is a module-level constant — a fresh [] literal
|
||||
// here would change identity every render and loop any effect watching it.
|
||||
const EMPTY_ACTIVITIES: ActivityLog[] = []
|
||||
|
||||
export function useActivities() {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['activities'],
|
||||
queryFn: () => projectService.getRecentActivities(),
|
||||
staleTime: 60 * 1000,
|
||||
})
|
||||
return data ?? EMPTY_ACTIVITIES
|
||||
}
|
||||
|
||||
export function useProjects() {
|
||||
const queryClient = useQueryClient()
|
||||
|
|
@ -25,17 +39,16 @@ export function useProjects() {
|
|||
taskType: taskTypeFilter,
|
||||
status: statusFilter,
|
||||
}),
|
||||
staleTime: 60 * 1000,
|
||||
})
|
||||
|
||||
const allProjectsQuery = useQuery({
|
||||
queryKey: ['projects', 'all'],
|
||||
queryFn: () => projectService.getProjects(),
|
||||
staleTime: 60 * 1000,
|
||||
})
|
||||
|
||||
const activitiesQuery = useQuery({
|
||||
queryKey: ['activities'],
|
||||
queryFn: () => projectService.getRecentActivities(),
|
||||
})
|
||||
const activities = useActivities()
|
||||
|
||||
const createProjectMutation = useMutation({
|
||||
mutationFn: (input: CreateProjectInput) => projectService.createProject(input),
|
||||
|
|
@ -71,7 +84,7 @@ export function useProjects() {
|
|||
return {
|
||||
projects,
|
||||
allProjects,
|
||||
activities: activitiesQuery.data ?? [],
|
||||
activities,
|
||||
isLoading: projectsQuery.isLoading,
|
||||
isError: projectsQuery.isError,
|
||||
searchQuery,
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ export function useUsers() {
|
|||
|
||||
const membersQuery = useQuery({
|
||||
queryKey: ['members', { search, role: roleFilter, status: statusFilter }],
|
||||
staleTime: 60 * 1000,
|
||||
queryFn: () =>
|
||||
userService.getMembers({
|
||||
search,
|
||||
|
|
@ -21,6 +22,7 @@ export function useUsers() {
|
|||
|
||||
const allMembersQuery = useQuery({
|
||||
queryKey: ['members', 'all'],
|
||||
staleTime: 60 * 1000,
|
||||
queryFn: () => userService.getMembers(),
|
||||
})
|
||||
|
||||
|
|
@ -51,6 +53,13 @@ export function useUsers() {
|
|||
},
|
||||
})
|
||||
|
||||
const deleteMemberMutation = useMutation({
|
||||
mutationFn: (memberId: string) => userService.deleteMember(memberId),
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['members'] })
|
||||
},
|
||||
})
|
||||
|
||||
const allMembers = allMembersQuery.data ?? []
|
||||
|
||||
return {
|
||||
|
|
@ -68,6 +77,7 @@ export function useUsers() {
|
|||
isInviting: inviteMutation.isPending,
|
||||
updateMemberRole: updateRoleMutation.mutateAsync,
|
||||
toggleMemberStatus: toggleStatusMutation.mutateAsync,
|
||||
deleteMember: deleteMemberMutation.mutateAsync,
|
||||
counts: {
|
||||
total: allMembers.length,
|
||||
admins: allMembers.filter((m) => m.role === 'admin').length,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
import React from 'react'
|
||||
import { Link, useLocation } from 'react-router-dom'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { getProjectById } from '@/services/projectService'
|
||||
|
||||
export interface BreadcrumbItem {
|
||||
label: string
|
||||
|
|
@ -10,6 +13,7 @@ export interface BreadcrumbProps {
|
|||
items?: BreadcrumbItem[]
|
||||
}
|
||||
|
||||
// Mock-mode fallback names (real mode resolves from the API below).
|
||||
const PROJECT_NAMES: Record<string, string> = {
|
||||
urban_vehicles_v2: 'Phương tiện đô thị',
|
||||
traffic_camera_v2: 'Giao thông đô thị',
|
||||
|
|
@ -23,6 +27,15 @@ export const Breadcrumb: React.FC<BreadcrumbProps> = ({ items }) => {
|
|||
const location = useLocation()
|
||||
const isProjectWorkspaceScreen = /^\/projects(?:\/[^/]+)?$/.test(location.pathname)
|
||||
|
||||
const parts = location.pathname.split('/').filter(Boolean)
|
||||
const routeProjectId = parts[0] === 'projects' ? parts[1] : undefined
|
||||
const { data: crumbProject } = useQuery({
|
||||
queryKey: ['project', routeProjectId, 'crumb'],
|
||||
queryFn: () => getProjectById(routeProjectId!),
|
||||
enabled: !USE_MOCK_DATA && Boolean(routeProjectId),
|
||||
staleTime: 5 * 60 * 1000,
|
||||
})
|
||||
|
||||
const resolvedItems: BreadcrumbItem[] = React.useMemo(() => {
|
||||
if (items && items.length > 0) return items
|
||||
|
||||
|
|
@ -35,11 +48,12 @@ export const Breadcrumb: React.FC<BreadcrumbProps> = ({ items }) => {
|
|||
]
|
||||
}
|
||||
|
||||
const parts = path.split('/').filter(Boolean)
|
||||
if (parts[0] === 'projects') {
|
||||
const list: BreadcrumbItem[] = [{ label: 'Dự án', to: '/projects' }]
|
||||
if (parts[1]) {
|
||||
const projName = PROJECT_NAMES[parts[1]] || 'Giao thông đô thị'
|
||||
const projName = USE_MOCK_DATA
|
||||
? (PROJECT_NAMES[parts[1]] ?? parts[1])
|
||||
: (crumbProject?.name ?? '…')
|
||||
list.push({ label: projName, to: `/projects/${parts[1]}` })
|
||||
if (parts[2] === 'annotate') {
|
||||
list.push({ label: 'Người gán nhãn' })
|
||||
|
|
@ -53,7 +67,8 @@ export const Breadcrumb: React.FC<BreadcrumbProps> = ({ items }) => {
|
|||
}
|
||||
|
||||
return [{ label: 'Dự án', to: '/projects' }, { label: 'Tổng quan' }]
|
||||
}, [items, location.pathname])
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [items, location.pathname, crumbProject?.name])
|
||||
|
||||
return (
|
||||
<nav className="flex items-center gap-2 text-xs text-slate-500">
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import React, { useState, useRef, useEffect } from 'react'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { useActivities } from '@/hooks/useProjects'
|
||||
|
||||
interface NotificationItem {
|
||||
id: string
|
||||
|
|
@ -33,6 +35,20 @@ export const NotificationBell: React.FC<{ isProjectWorkspace?: boolean }> = ({ i
|
|||
const [notifications, setNotifications] = useState(MOCK_NOTIFICATIONS)
|
||||
const ref = useRef<HTMLDivElement>(null)
|
||||
|
||||
// Real mode: the bell mirrors the shared activity cache, not mock people.
|
||||
const activities = useActivities()
|
||||
useEffect(() => {
|
||||
if (USE_MOCK_DATA) return
|
||||
setNotifications(
|
||||
activities.slice(0, 6).map((a) => ({
|
||||
id: a.id,
|
||||
title: a.actionText,
|
||||
time: a.timestamp,
|
||||
unread: false,
|
||||
}))
|
||||
)
|
||||
}, [activities])
|
||||
|
||||
useEffect(() => {
|
||||
const handleClickOutside = (event: MouseEvent) => {
|
||||
if (ref.current && !ref.current.contains(event.target as Node)) {
|
||||
|
|
|
|||
|
|
@ -1,23 +1,35 @@
|
|||
import React from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useAuthStore } from '@/stores/authStore'
|
||||
import { Dropdown } from '../../../components/ui/Dropdown'
|
||||
import { showToast } from '../../../components/feedback/Toast'
|
||||
|
||||
export const UserMenu: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => {
|
||||
const navigate = useNavigate()
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const storeLogout = useAuthStore((s) => s.logout)
|
||||
|
||||
const displayName = user?.name ?? 'Người dùng'
|
||||
const initials = displayName
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.map((w) => w[0] ?? '')
|
||||
.join('')
|
||||
.slice(0, 2)
|
||||
.toUpperCase()
|
||||
|
||||
return (
|
||||
<Dropdown
|
||||
align="right"
|
||||
trigger={
|
||||
<div className={`flex h-[30px] w-[30px] items-center justify-center rounded-full text-[11px] font-semibold text-[var(--project-accent)] transition-all ${isProjectWorkspace ? 'bg-[var(--project-avatar-background)]' : 'bg-orange-100 text-slate-800 hover:ring-2 hover:ring-orange-200'}`}>
|
||||
MA
|
||||
{initials}
|
||||
</div>
|
||||
}
|
||||
items={[
|
||||
{
|
||||
label: 'Hồ sơ cá nhân (Minh Anh)',
|
||||
onClick: () => showToast.info('Đang mở hồ sơ Quản trị viên Minh Anh'),
|
||||
label: `Hồ sơ cá nhân (${displayName})`,
|
||||
onClick: () => showToast.info(`Đang mở hồ sơ ${displayName}`),
|
||||
},
|
||||
{
|
||||
label: 'Quản lý người dùng',
|
||||
|
|
@ -27,6 +39,7 @@ export const UserMenu: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProject
|
|||
label: 'Đăng xuất',
|
||||
danger: true,
|
||||
onClick: () => {
|
||||
storeLogout()
|
||||
showToast.success('Đã đăng xuất thành công')
|
||||
navigate('/login')
|
||||
},
|
||||
|
|
|
|||
|
|
@ -3,29 +3,20 @@ 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 { useProjects } from '@/hooks/useProjects'
|
||||
import { getProjects, subscribeProjectsStore } from '@/pages/projects/projectData'
|
||||
|
||||
export const RecentProjects: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => {
|
||||
const location = useLocation()
|
||||
const [recentProjects, setRecentProjects] = useState<Project[]>(() =>
|
||||
const [mockProjects, setMockProjects] = useState<Project[]>(() =>
|
||||
USE_MOCK_DATA ? getProjects().slice(0, 3) : []
|
||||
)
|
||||
const { allProjects } = useProjects()
|
||||
const recentProjects = USE_MOCK_DATA ? mockProjects : allProjects.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 subscribeProjectsStore(() => setMockProjects(getProjects().slice(0, 3)))
|
||||
}
|
||||
}, [])
|
||||
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
import React, { useEffect, useState } from 'react'
|
||||
import React 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'
|
||||
import { useProjects } from '@/hooks/useProjects'
|
||||
import { useUsers } from '@/hooks/useUsers'
|
||||
|
||||
interface NavItem {
|
||||
to: string
|
||||
|
|
@ -15,22 +15,13 @@ 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
|
||||
}
|
||||
}, [])
|
||||
// Shared react-query caches: no direct fetches, so mounting the sidebar
|
||||
// never duplicates the page queries (StrictMode remounts share them too).
|
||||
const { allProjects } = useProjects()
|
||||
const { allMembers } = useUsers()
|
||||
const realCounts = USE_MOCK_DATA
|
||||
? null
|
||||
: { projects: allProjects.length, users: allMembers.length }
|
||||
|
||||
const navItems: NavItem[] = [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,20 +1,51 @@
|
|||
import React from 'react'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { api } from '@/services/api'
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes <= 0) return '0 B'
|
||||
const units = ['B', 'KB', 'MB', 'GB', 'TB']
|
||||
const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)))
|
||||
const v = bytes / 1024 ** i
|
||||
return `${v >= 100 ? Math.round(v) : v.toFixed(1)} ${units[i]}`
|
||||
}
|
||||
|
||||
export const StorageUsage: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['storage-usage'],
|
||||
queryFn: async () => {
|
||||
const res = await api.get<{ bytes: number; objects: number; quota_bytes: number }>(
|
||||
'/storage/usage'
|
||||
)
|
||||
return res.data
|
||||
},
|
||||
enabled: !USE_MOCK_DATA,
|
||||
staleTime: 10 * 60 * 1000,
|
||||
})
|
||||
|
||||
// Mock mode keeps the design placeholder; real mode shows measured R2 bytes.
|
||||
const pct = data && data.quota_bytes > 0
|
||||
? Math.min(100, Math.round((data.bytes / data.quota_bytes) * 100))
|
||||
: 24
|
||||
const caption = data
|
||||
? `${formatBytes(data.bytes)} / ${formatBytes(data.quota_bytes)} đã sử dụng`
|
||||
: '12 GB / 50 GB đã sử dụng'
|
||||
|
||||
return (
|
||||
<div className={`rounded-[8px] p-3 ${isProjectWorkspace ? 'bg-[#f1f3fe]' : 'rounded-xl border border-slate-200/60 bg-slate-100/80 p-3.5'}`}>
|
||||
<div className={`mb-2 flex items-center justify-between font-medium text-slate-700 ${isProjectWorkspace ? 'text-[10px] text-[#332926]' : 'text-xs'}`}>
|
||||
<span>Dung lượng dữ liệu</span>
|
||||
<span className="font-semibold text-slate-900">24%</span>
|
||||
<span className="font-semibold text-slate-900">{pct}%</span>
|
||||
</div>
|
||||
<div className="h-1 w-full overflow-hidden rounded-full bg-[#e5e8ed]">
|
||||
<div
|
||||
className={`h-full rounded-full ${isProjectWorkspace ? 'bg-[#8a87f4]' : 'bg-[#3B5BDB]'}`}
|
||||
style={{ width: '24%' }}
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
<div className={`mt-2 text-slate-500 ${isProjectWorkspace ? 'text-[9px] text-[#332926]' : 'text-[11px]'}`}>
|
||||
12 GB / 50 GB đã sử dụng
|
||||
{caption}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,11 +1,33 @@
|
|||
import React from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { useAuthStore } from '@/stores/authStore'
|
||||
import { showToast } from '../../../components/feedback/Toast'
|
||||
|
||||
const ROLE_LABELS: Record<string, string> = {
|
||||
admin: 'Quản trị viên',
|
||||
manager: 'Quản lý dự án',
|
||||
reviewer: 'Người kiểm duyệt',
|
||||
annotator: 'Người gán nhãn',
|
||||
}
|
||||
|
||||
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) || '??').toUpperCase()
|
||||
}
|
||||
|
||||
export const UserInfo: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProjectWorkspace = false }) => {
|
||||
const navigate = useNavigate()
|
||||
const user = useAuthStore((s) => s.user)
|
||||
const storeLogout = useAuthStore((s) => s.logout)
|
||||
|
||||
const displayName = user?.name ?? 'Người dùng'
|
||||
const displayRole = (user?.role && ROLE_LABELS[user.role]) || 'Thành viên'
|
||||
|
||||
const handleLogout = () => {
|
||||
storeLogout()
|
||||
showToast.success('Đã đăng xuất khỏi phiên làm việc')
|
||||
navigate('/login')
|
||||
}
|
||||
|
|
@ -36,14 +58,14 @@ export const UserInfo: React.FC<{ isProjectWorkspace?: boolean }> = ({ isProject
|
|||
<div className={`flex items-center justify-between ${isProjectWorkspace ? 'border-t border-[#2d374d] pt-[18px]' : 'border-t border-slate-200 pt-3'}`}>
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
<div className={`flex shrink-0 items-center justify-center rounded-full font-semibold ${isProjectWorkspace ? 'h-[34px] w-[34px] bg-[#f5ded6] text-[11px] text-[#332926]' : 'h-8 w-8 bg-orange-100 text-xs text-slate-800'}`}>
|
||||
MA
|
||||
{initialsOf(displayName)}
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<div className={`truncate font-semibold ${isProjectWorkspace ? 'text-[12px] text-[#332926]' : 'text-xs text-slate-900'}`}>
|
||||
Minh Anh
|
||||
{displayName}
|
||||
</div>
|
||||
<div className={`truncate ${isProjectWorkspace ? 'text-[10px] text-[#332926]' : 'text-[11px] text-slate-500'}`}>
|
||||
Quản trị viên
|
||||
{displayRole}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import React, { useEffect } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { useParams, useSearchParams } from 'react-router-dom'
|
||||
import toast from 'react-hot-toast'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { useAnnotatorStore } from './annotatorStore'
|
||||
|
|
@ -19,16 +19,19 @@ export const AnnotatorPage: React.FC = () => {
|
|||
const project = useAnnotatorStore((s) => s.project)
|
||||
const isLoading = useAnnotatorStore((s) => s.isLoading)
|
||||
const loadError = useAnnotatorStore((s) => s.loadError)
|
||||
const images = useAnnotatorStore((s) => s.images)
|
||||
const initProject = useAnnotatorStore((s) => s.initProject)
|
||||
const [searchParams] = useSearchParams()
|
||||
|
||||
useEffect(() => {
|
||||
initProject(id ?? 'urban_vehicles_v2')
|
||||
initProject(id ?? 'urban_vehicles_v2', searchParams.get('imageId') ?? undefined)
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [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)
|
||||
// Per-image loads use the inline canvas spinner; an empty dataset (total 0)
|
||||
// falls through to the workspace empty state, not this gate.
|
||||
const showGate = !USE_MOCK_DATA && (isLoading || loadError !== null)
|
||||
|
||||
// Global keyboard shortcuts for fast annotation
|
||||
useEffect(() => {
|
||||
|
|
@ -85,6 +88,9 @@ export const AnnotatorPage: React.FC = () => {
|
|||
state.setActiveTool('bbox')
|
||||
return
|
||||
}
|
||||
if (keyLower === 'b' && state.project.taskType === 'segmentation') {
|
||||
state.setActiveTool('brush')
|
||||
}
|
||||
if (keyLower === 'p' && state.project.taskType === 'segmentation') {
|
||||
state.setActiveTool('polygon')
|
||||
return
|
||||
|
|
|
|||
|
|
@ -13,7 +13,11 @@ import {
|
|||
} from '@/types'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { getAnnotation, saveAnnotation } from '@/services/annotationService'
|
||||
import { getProjectImages, updateImageStatus as persistImageStatus } from '@/services/imageService'
|
||||
import {
|
||||
getImageOffset,
|
||||
getProjectImagesPage,
|
||||
updateImageStatus as persistImageStatus,
|
||||
} from '@/services/imageService'
|
||||
import { getProjectById } from '@/services/projectService'
|
||||
import { getAnnotatorImageUrl } from './annotatorTheme'
|
||||
import { normalizeBBox } from '@/utils/canvas'
|
||||
|
|
@ -462,10 +466,13 @@ interface HistorySnapshot {
|
|||
|
||||
export interface AnnotatorState {
|
||||
project: Project
|
||||
images: ImageItem[]
|
||||
// Sparse cursor over the dataset: index i holds metadata only after its
|
||||
// page is fetched. length === server total. Never the whole 12k at once.
|
||||
images: (ImageItem | undefined)[]
|
||||
isLoading: boolean
|
||||
loadError: string | null
|
||||
isSaving: boolean
|
||||
loadingImage: boolean
|
||||
currentImageIndex: number
|
||||
displayImageCounter: number
|
||||
activeTool: AnnotationTool
|
||||
|
|
@ -478,6 +485,7 @@ export interface AnnotatorState {
|
|||
showBoxes: boolean
|
||||
showMasks: boolean
|
||||
maskOpacity: number
|
||||
brushSize: number
|
||||
vertexEditEnabled: boolean
|
||||
activeGroupId: number
|
||||
zoom: number
|
||||
|
|
@ -488,8 +496,11 @@ export interface AnnotatorState {
|
|||
historyFuture: HistorySnapshot[]
|
||||
|
||||
// Actions
|
||||
initProject: (projectId: string) => void
|
||||
initProject: (projectId: string, initialImageId?: string) => void
|
||||
selectImageByIndex: (index: number) => void
|
||||
loadImage: (index: number) => Promise<void>
|
||||
openImageById: (imageId: string) => void
|
||||
ensureWindow: (lo: number, hi: number) => void
|
||||
nextImage: () => void
|
||||
prevImage: () => void
|
||||
setActiveTool: (tool: AnnotationTool) => void
|
||||
|
|
@ -509,6 +520,8 @@ export interface AnnotatorState {
|
|||
addDraftPolygonPoint: (pt: Point2D) => void
|
||||
closeDraftPolygon: () => void
|
||||
cancelDraftPolygon: () => void
|
||||
addTracedPolygons: (polygons: Point2D[][]) => void
|
||||
setBrushSize: (size: number) => void
|
||||
updatePolygonVertex: (shapeId: string, vertexIndex: number, pt: Point2D) => void
|
||||
insertPolygonVertex: (shapeId: string, afterIndex: number, pt: Point2D) => void
|
||||
deletePolygonVertex: (shapeId: string, vertexIndex: number) => void
|
||||
|
|
@ -595,11 +608,13 @@ function createInitialAnnotationState(project: Project) {
|
|||
showBoxes: true,
|
||||
showMasks: true,
|
||||
maskOpacity: 35,
|
||||
brushSize: 24,
|
||||
vertexEditEnabled: true,
|
||||
activeGroupId: 2,
|
||||
zoom: 75,
|
||||
pan: { x: 0, y: 0 },
|
||||
isSaving: false,
|
||||
loadingImage: false,
|
||||
lastSavedAt: '09:42',
|
||||
draftPolygonPoints: [] as Point2D[],
|
||||
historyPast: [] as HistorySnapshot[],
|
||||
|
|
@ -662,7 +677,7 @@ function buildRealState(
|
|||
isLoading: false,
|
||||
loadError: null,
|
||||
currentImageIndex: 0,
|
||||
displayImageCounter: project.taskType === 'classification' ? 124 : 321,
|
||||
displayImageCounter: 1,
|
||||
activeTool: defaultTool,
|
||||
selectedClassId: fallbackClass,
|
||||
selectedShapeId: null,
|
||||
|
|
@ -673,11 +688,13 @@ function buildRealState(
|
|||
showBoxes: true,
|
||||
showMasks: true,
|
||||
maskOpacity: 35,
|
||||
brushSize: 24,
|
||||
vertexEditEnabled: true,
|
||||
activeGroupId: 2,
|
||||
zoom: 75,
|
||||
pan: { x: 0, y: 0 },
|
||||
isSaving: false,
|
||||
loadingImage: false,
|
||||
lastSavedAt: '',
|
||||
draftPolygonPoints: [],
|
||||
historyPast: [],
|
||||
|
|
@ -715,7 +732,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
? createInitialAnnotationState(ANNOTATOR_PROJECTS_BY_ID.urban_vehicles_v2!)
|
||||
: { ...buildRealState(EMPTY_PROJECT, []), isLoading: true }),
|
||||
|
||||
initProject: (projectId) => {
|
||||
initProject: (projectId, initialImageId) => {
|
||||
if (USE_MOCK_DATA) {
|
||||
const selectedProject =
|
||||
ANNOTATOR_PROJECTS_BY_ID[projectId] ?? ANNOTATOR_PROJECTS_BY_ID.urban_vehicles_v2!
|
||||
|
|
@ -726,10 +743,13 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
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)
|
||||
// Total only: metadata arrives page-by-page as the user navigates.
|
||||
const { total } = await getProjectImagesPage(project.id, { limit: 1 })
|
||||
set({ ...buildRealState(project, []), images: new Array(total) })
|
||||
if (initialImageId) {
|
||||
await useAnnotatorStore.getState().openImageById(initialImageId)
|
||||
} else {
|
||||
await useAnnotatorStore.getState().loadImage(0)
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : 'Không tải được dự án'
|
||||
|
|
@ -739,14 +759,112 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
})()
|
||||
},
|
||||
|
||||
loadImage: async (index) => {
|
||||
const st = get()
|
||||
if (USE_MOCK_DATA) {
|
||||
if (index < 0 || index >= st.images.length) return
|
||||
set({ currentImageIndex: index, loadingImage: false })
|
||||
return
|
||||
}
|
||||
if (index < 0 || index >= st.images.length) return
|
||||
const cached = st.images[index]
|
||||
const baseNum = USE_MOCK_DATA ? (st.project.taskType === 'classification' ? 124 : 321) : 1
|
||||
if (cached) {
|
||||
set({
|
||||
currentImageIndex: index,
|
||||
displayImageCounter: baseNum + index,
|
||||
loadingImage: false,
|
||||
})
|
||||
} else {
|
||||
set({ currentImageIndex: index, loadingImage: true })
|
||||
try {
|
||||
const lo = Math.max(0, index - 25)
|
||||
const page = await getProjectImagesPage(st.project.id, { limit: 51, offset: lo })
|
||||
set((s) => {
|
||||
const arr = s.images.slice()
|
||||
page.items.forEach((im, k) => {
|
||||
arr[lo + k] = im
|
||||
})
|
||||
return {
|
||||
images: arr,
|
||||
currentImageIndex: index,
|
||||
displayImageCounter: baseNum + index,
|
||||
loadingImage: false,
|
||||
}
|
||||
})
|
||||
} catch (err) {
|
||||
set({ loadingImage: false })
|
||||
toast.error(err instanceof Error ? err.message : 'Không tải được ảnh')
|
||||
return
|
||||
}
|
||||
}
|
||||
const img = useAnnotatorStore.getState().images[index]
|
||||
if (!img) return
|
||||
for (const neighbour of [
|
||||
useAnnotatorStore.getState().images[index - 1],
|
||||
useAnnotatorStore.getState().images[index + 1],
|
||||
]) {
|
||||
if (neighbour) {
|
||||
const pre = new Image()
|
||||
pre.src = neighbour.url
|
||||
}
|
||||
}
|
||||
await ensureAnnotationLoaded(st.project.id, img.id)
|
||||
},
|
||||
|
||||
openImageById: (imageId) => {
|
||||
const st = get()
|
||||
if (USE_MOCK_DATA) {
|
||||
const idx = st.images.findIndex((img) => img?.id === imageId)
|
||||
if (idx !== -1) st.selectImageByIndex(idx)
|
||||
return
|
||||
}
|
||||
void (async () => {
|
||||
try {
|
||||
const { offset } = await getImageOffset(st.project.id, imageId)
|
||||
await useAnnotatorStore.getState().loadImage(offset)
|
||||
} catch {
|
||||
await useAnnotatorStore.getState().loadImage(0)
|
||||
}
|
||||
})()
|
||||
},
|
||||
|
||||
ensureWindow: (lo, hi) => {
|
||||
const st = get()
|
||||
if (USE_MOCK_DATA) return
|
||||
const start = Math.max(0, lo)
|
||||
const missing: number[] = []
|
||||
for (let i = start; i < Math.min(hi, st.images.length); i++) {
|
||||
if (!st.images[i]) missing.push(i)
|
||||
}
|
||||
if (missing.length === 0) return
|
||||
const from = missing[0]!
|
||||
void getProjectImagesPage(st.project.id, {
|
||||
limit: Math.min(61, missing[missing.length - 1]! - from + 1),
|
||||
offset: from,
|
||||
})
|
||||
.then((page) => {
|
||||
useAnnotatorStore.setState((s) => {
|
||||
const arr = s.images.slice()
|
||||
page.items.forEach((im, k) => {
|
||||
arr[from + k] = im
|
||||
})
|
||||
return { images: arr }
|
||||
})
|
||||
})
|
||||
.catch(() => {
|
||||
// Strip shows skeletons; a later navigation refetches.
|
||||
})
|
||||
},
|
||||
|
||||
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] ?? [] : []
|
||||
const baseNum = USE_MOCK_DATA ? (project.taskType === 'classification' ? 124 : 321) : 1
|
||||
const cached = images[index]
|
||||
const shapes = cached ? get().shapesByImageId[cached.id] ?? [] : []
|
||||
set({
|
||||
currentImageIndex: index,
|
||||
displayImageCounter: baseNum + index,
|
||||
|
|
@ -756,23 +874,7 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
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 })
|
||||
}
|
||||
})
|
||||
}
|
||||
void get().loadImage(index)
|
||||
},
|
||||
|
||||
nextImage: () => {
|
||||
|
|
@ -862,6 +964,8 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
setShowBoxes: (show) => set({ showBoxes: show }),
|
||||
setShowMasks: (show) => set({ showMasks: show }),
|
||||
setMaskOpacity: (opacity) => set({ maskOpacity: opacity }),
|
||||
setBrushSize: (size) =>
|
||||
set({ brushSize: Math.max(4, Math.min(160, Math.round(size))) }),
|
||||
toggleVertexEdit: () => set((s) => ({ vertexEditEnabled: !s.vertexEditEnabled })),
|
||||
|
||||
setActiveGroupId: (groupId) => {
|
||||
|
|
@ -923,7 +1027,8 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
|
||||
const cls =
|
||||
state.project.classes.find((c) => c.id === state.selectedClassId) ??
|
||||
state.project.classes[0]!
|
||||
state.project.classes[0]
|
||||
if (!cls) return
|
||||
const currentShapes = state.shapesByImageId[currentImage.id] ?? []
|
||||
const nextIndex = currentShapes.length + 1
|
||||
const newShape: AnnotationShape = {
|
||||
|
|
@ -999,7 +1104,8 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
}
|
||||
const cls =
|
||||
state.project.classes.find((c) => c.id === state.selectedClassId) ??
|
||||
state.project.classes[0]!
|
||||
state.project.classes[0]
|
||||
if (!cls) return
|
||||
const currentShapes = state.shapesByImageId[currentImage.id] ?? []
|
||||
const nextIndex = currentShapes.length + 1
|
||||
const newShape: AnnotationShape = {
|
||||
|
|
@ -1035,6 +1141,44 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
|
||||
cancelDraftPolygon: () => set({ draftPolygonPoints: [] }),
|
||||
|
||||
addTracedPolygons: (polygons) => {
|
||||
const state = get()
|
||||
const currentImage = state.images[state.currentImageIndex]
|
||||
if (!currentImage || polygons.length === 0) return
|
||||
const cls =
|
||||
state.project.classes.find((c) => c.id === state.selectedClassId) ??
|
||||
state.project.classes[0]
|
||||
if (!cls) return
|
||||
const currentShapes = state.shapesByImageId[currentImage.id] ?? []
|
||||
const made = polygons.map((points, i) => ({
|
||||
id: `brush-${Date.now()}-${i}`,
|
||||
index: currentShapes.length + i + 1,
|
||||
type: 'polygon' as const,
|
||||
labelId: cls.id,
|
||||
labelName: cls.name,
|
||||
color: cls.color,
|
||||
visible: true,
|
||||
groupId: state.activeGroupId,
|
||||
points: points.map((p) => ({ x: Math.round(p.x), y: Math.round(p.y) })),
|
||||
}))
|
||||
set({
|
||||
shapesByImageId: {
|
||||
...state.shapesByImageId,
|
||||
[currentImage.id]: [...currentShapes, ...made],
|
||||
},
|
||||
selectedShapeId: made[made.length - 1]!.id,
|
||||
historyPast: [
|
||||
...state.historyPast,
|
||||
{
|
||||
shapes: currentShapes,
|
||||
classificationLabelId: state.classificationByImageId[currentImage.id] ?? 'cls-car',
|
||||
},
|
||||
],
|
||||
historyFuture: [],
|
||||
})
|
||||
get().scheduleAutosave();
|
||||
},
|
||||
|
||||
updatePolygonVertex: (shapeId, vertexIndex, pt) => {
|
||||
const state = get()
|
||||
const currentImage = state.images[state.currentImageIndex]
|
||||
|
|
@ -1113,7 +1257,8 @@ export const useAnnotatorStore = create<AnnotatorState>((set, get) => ({
|
|||
if (!currentImage) return
|
||||
const cls =
|
||||
state.project.classes.find((c) => c.id === state.selectedClassId) ??
|
||||
state.project.classes[0]!
|
||||
state.project.classes[0]
|
||||
if (!cls) return
|
||||
const currentShapes = state.shapesByImageId[currentImage.id] ?? []
|
||||
const nextIndex = currentShapes.length + 1
|
||||
const newShape: AnnotationShape = {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,15 @@
|
|||
import React, { useEffect, useLayoutEffect, useRef, useState } from 'react'
|
||||
import { Layer, Stage } from 'react-konva'
|
||||
import { Circle, Image as KonvaImageView, 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 { traceMask } from '@/utils/maskTrace'
|
||||
import { useAnnotatorStore } from '../../annotatorStore'
|
||||
|
||||
// Offscreen raster cap: brush strokes paint here at full image resolution
|
||||
// (downscaled past this), then trace to polygons on release.
|
||||
const MASK_MAX_SIDE = 2048
|
||||
import { ImageViewer } from './ImageViewer'
|
||||
import { BoundingBoxTool, ResizeHandleCorner } from './BoundingBoxTool'
|
||||
import { PolygonTool } from './PolygonTool'
|
||||
|
|
@ -23,6 +28,7 @@ type DragInteraction =
|
|||
initialBox: BoundingBox
|
||||
}
|
||||
| { type: 'drag-vertex'; shapeId: string; vertexIndex: number }
|
||||
| { type: 'brush-stroke' }
|
||||
| { type: 'pan-stage'; last: Point2D }
|
||||
|
||||
function clampPan(
|
||||
|
|
@ -74,6 +80,65 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
const [interaction, setInteraction] = useState<DragInteraction | null>(null)
|
||||
const [cursorPoint, setCursorPoint] = useState<Point2D | null>(null)
|
||||
const [spaceDown, setSpaceDown] = useState(false)
|
||||
const [brokenImageId, setBrokenImageId] = useState<string | null>(null)
|
||||
const [brushPainting, setBrushPainting] = useState(false)
|
||||
const loadingImage = useAnnotatorStore((s) => s.loadingImage)
|
||||
const nextImage = useAnnotatorStore((s) => s.nextImage)
|
||||
const brushSize = useAnnotatorStore((s) => s.brushSize)
|
||||
const maskCanvasRef = useRef<HTMLCanvasElement | null>(null)
|
||||
const maskScaleRef = useRef(1)
|
||||
const lastBrushPt = useRef<Point2D | null>(null)
|
||||
const brushPreviewRef = useRef<Konva.Image>(null)
|
||||
|
||||
const ensureMaskCanvas = (imgW: number, imgH: number): HTMLCanvasElement | null => {
|
||||
const scale = Math.min(1, MASK_MAX_SIDE / Math.max(imgW, imgH))
|
||||
const cv = maskCanvasRef.current
|
||||
if (
|
||||
cv &&
|
||||
cv.width === Math.round(imgW * scale) &&
|
||||
cv.height === Math.round(imgH * scale)
|
||||
) {
|
||||
maskScaleRef.current = scale
|
||||
return cv
|
||||
}
|
||||
const next = document.createElement('canvas')
|
||||
next.width = Math.round(imgW * scale)
|
||||
next.height = Math.round(imgH * scale)
|
||||
maskCanvasRef.current = next
|
||||
maskScaleRef.current = scale
|
||||
return next
|
||||
}
|
||||
|
||||
const clearBrushMask = () => {
|
||||
const cv = maskCanvasRef.current
|
||||
if (cv) {
|
||||
cv.getContext('2d')?.clearRect(0, 0, cv.width, cv.height)
|
||||
}
|
||||
lastBrushPt.current = null
|
||||
setBrushPainting(false)
|
||||
}
|
||||
|
||||
const stampBrush = (from: Point2D, to: Point2D, color: string) => {
|
||||
const cv = maskCanvasRef.current
|
||||
const ctx = cv?.getContext('2d')
|
||||
if (!cv || !ctx) return
|
||||
const st = useAnnotatorStore.getState()
|
||||
const s = maskScaleRef.current
|
||||
ctx.strokeStyle = color
|
||||
ctx.fillStyle = color
|
||||
ctx.lineWidth = Math.max(1, st.brushSize * s)
|
||||
ctx.lineCap = 'round'
|
||||
ctx.lineJoin = 'round'
|
||||
ctx.beginPath()
|
||||
ctx.moveTo(from.x * s, from.y * s)
|
||||
ctx.lineTo(to.x * s, to.y * s)
|
||||
ctx.stroke()
|
||||
ctx.beginPath()
|
||||
ctx.arc(to.x * s, to.y * s, Math.max(0.5, (st.brushSize * s) / 2), 0, Math.PI * 2)
|
||||
ctx.fill()
|
||||
// Konva caches the raster: changed pixels need an explicit redraw.
|
||||
brushPreviewRef.current?.getLayer()?.batchDraw()
|
||||
}
|
||||
|
||||
// Track container width; stage height follows image aspect. A ResizeObserver
|
||||
// (not a one-shot measure) is required: on hard reload the container can
|
||||
|
|
@ -100,6 +165,12 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [hasImage])
|
||||
|
||||
// A fresh raster per tool/image: stale strokes never leak across contexts.
|
||||
useEffect(() => {
|
||||
clearBrushMask()
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [activeTool, currentImage?.id])
|
||||
|
||||
// Space-held panning (ignored while typing).
|
||||
useEffect(() => {
|
||||
const isTypingTarget = (t: EventTarget | null) =>
|
||||
|
|
@ -125,7 +196,47 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
}
|
||||
}, [])
|
||||
|
||||
if (!currentImage) return null
|
||||
if (!currentImage) {
|
||||
// Per-image loads (arrow-key navigation across 12k rows) resolve here.
|
||||
return (
|
||||
<div className="px-4 py-3">
|
||||
<div className="flex min-h-[420px] items-center justify-center rounded-xl border border-slate-200/80 bg-slate-900">
|
||||
{loadingImage ? (
|
||||
<div className="flex flex-col items-center gap-3">
|
||||
<div className="h-8 w-8 animate-spin rounded-full border-2 border-slate-600 border-t-white" />
|
||||
<span className="text-xs font-medium text-slate-300">Đang tải ảnh...</span>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// One corrupt file must never strand the session: show the fault inline
|
||||
// with a way forward instead of a blank canvas.
|
||||
if (brokenImageId === currentImage.id) {
|
||||
return (
|
||||
<div className="px-4 py-3">
|
||||
<div className="flex min-h-[420px] flex-col items-center justify-center gap-3 rounded-xl border border-red-200 bg-red-50/60 px-6 text-center">
|
||||
<p className="text-sm font-semibold text-red-800">Ảnh này bị lỗi, không hiển thị được</p>
|
||||
<p className="max-w-md font-mono text-[11px] text-red-500">{currentImage.fileName}</p>
|
||||
<p className="text-xs text-slate-500">
|
||||
Nhãn đã lưu (nếu có) vẫn còn. Các ảnh khác không ảnh hưởng.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setBrokenImageId(null)
|
||||
nextImage()
|
||||
}}
|
||||
className="mt-1 rounded-lg bg-[#C95C3C] px-4 py-2 text-xs font-semibold text-white"
|
||||
>
|
||||
Qua ảnh kế →
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
const stageH = stageW > 0 ? Math.round((stageW * currentImage.height) / currentImage.width) : 0
|
||||
// Base fit: whole image visible at zoom=75; zoom % scales around it.
|
||||
|
|
@ -141,7 +252,11 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
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]!
|
||||
project.classes.find((c) => c.id === selectedClassId) ?? project.classes[0]
|
||||
|
||||
// No label classes yet: drawing is disabled but the image still shows,
|
||||
// so existing labels stay viewable and nothing dead-ends.
|
||||
const canDraw = activeClass !== undefined
|
||||
|
||||
// Exact pointer -> image coords through the live Stage transform.
|
||||
const getImagePoint = (e: KonvaEventObject<MouseEvent>): Point2D => {
|
||||
|
|
@ -198,6 +313,7 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
return
|
||||
}
|
||||
if (e.evt.button !== 0) return
|
||||
if (!canDraw) return
|
||||
const pt = getImagePoint(e)
|
||||
|
||||
if (project.taskType === 'object_detection' && activeTool === 'bbox') {
|
||||
|
|
@ -210,6 +326,20 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
return
|
||||
}
|
||||
|
||||
if (project.taskType === 'segmentation' && activeTool === 'brush') {
|
||||
const st = useAnnotatorStore.getState()
|
||||
const cls =
|
||||
project.classes.find((c) => c.id === st.selectedClassId) ?? project.classes[0]
|
||||
if (!cls) return
|
||||
ensureMaskCanvas(currentImage.width, currentImage.height)
|
||||
stampBrush(pt, pt, cls.color)
|
||||
lastBrushPt.current = pt
|
||||
setCursorPoint(pt)
|
||||
setBrushPainting(true)
|
||||
setInteraction({ type: 'brush-stroke' })
|
||||
return
|
||||
}
|
||||
|
||||
if (activeTool === 'point' && project.taskType !== 'classification') {
|
||||
addPointShape(pt)
|
||||
return
|
||||
|
|
@ -221,13 +351,24 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
}
|
||||
|
||||
const handleMouseMove = (e: KonvaEventObject<MouseEvent>) => {
|
||||
if (draftPolygonPoints.length > 0) {
|
||||
if (draftPolygonPoints.length > 0 || activeTool === 'brush') {
|
||||
setCursorPoint(getImagePoint(e))
|
||||
}
|
||||
|
||||
if (!interaction) return
|
||||
const st = useAnnotatorStore.getState()
|
||||
|
||||
if (interaction.type === 'brush-stroke') {
|
||||
const pt = getImagePoint(e)
|
||||
const last = lastBrushPt.current ?? pt
|
||||
const cls =
|
||||
project.classes.find((c) => c.id === st.selectedClassId) ?? project.classes[0]
|
||||
if (cls) stampBrush(last, pt, cls.color)
|
||||
lastBrushPt.current = pt
|
||||
setCursorPoint(pt)
|
||||
return
|
||||
}
|
||||
|
||||
if (interaction.type === 'pan-stage') {
|
||||
const dx = e.evt.clientX - interaction.last.x
|
||||
const dy = e.evt.clientY - interaction.last.y
|
||||
|
|
@ -312,6 +453,26 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
|
||||
const handleMouseUp = () => {
|
||||
if (!interaction) return
|
||||
if (interaction.type === 'brush-stroke') {
|
||||
// Release: vectorize the painted raster into polygon shapes.
|
||||
const cv = maskCanvasRef.current
|
||||
const s = maskScaleRef.current
|
||||
if (cv) {
|
||||
const ctx = cv.getContext('2d')
|
||||
const pixels = ctx?.getImageData(0, 0, cv.width, cv.height).data
|
||||
if (pixels) {
|
||||
const blobs = traceMask(pixels, cv.width, cv.height).map((poly) =>
|
||||
poly.map((p) => ({ x: p.x / s, y: p.y / s }))
|
||||
)
|
||||
if (blobs.length > 0) {
|
||||
useAnnotatorStore.getState().addTracedPolygons(blobs)
|
||||
}
|
||||
}
|
||||
}
|
||||
clearBrushMask()
|
||||
setInteraction(null)
|
||||
return
|
||||
}
|
||||
if (interaction.type === 'draw-bbox') {
|
||||
const rawBox: BoundingBox = {
|
||||
x: interaction.start.x,
|
||||
|
|
@ -349,6 +510,19 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
|
||||
return (
|
||||
<div className="px-4 py-3">
|
||||
{!canDraw && (
|
||||
<div className="mb-2 flex items-center justify-between gap-3 rounded-xl border border-amber-200 bg-amber-50 px-4 py-2.5">
|
||||
<p className="text-xs text-amber-900">
|
||||
Dự án chưa có lớp nhãn nào — bạn vẫn xem được ảnh, hãy tạo lớp ở tab Lớp nhãn để bắt đầu vẽ.
|
||||
</p>
|
||||
<a
|
||||
href={`/projects/${project.id}`}
|
||||
className="shrink-0 rounded-lg bg-[#C95C3C] px-3 py-1.5 text-[11px] font-semibold text-white"
|
||||
>
|
||||
Mở tab Lớp nhãn
|
||||
</a>
|
||||
</div>
|
||||
)}
|
||||
<div
|
||||
ref={containerRef}
|
||||
className="relative overflow-hidden rounded-xl border border-slate-200/80 bg-slate-900"
|
||||
|
|
@ -375,7 +549,8 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
? 'grab'
|
||||
: activeTool === 'bbox' ||
|
||||
activeTool === 'polygon' ||
|
||||
activeTool === 'point'
|
||||
activeTool === 'point' ||
|
||||
activeTool === 'brush'
|
||||
? 'crosshair'
|
||||
: 'default',
|
||||
}}
|
||||
|
|
@ -386,6 +561,7 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
thumbUrl={currentImage.thumbnailSmallUrl ?? currentImage.thumbnailUrl}
|
||||
width={currentImage.width}
|
||||
height={currentImage.height}
|
||||
onError={() => setBrokenImageId(currentImage.id)}
|
||||
/>
|
||||
|
||||
{project.taskType === 'object_detection' && (
|
||||
|
|
@ -394,8 +570,8 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
selectedShapeId={selectedShapeId}
|
||||
showBoxes={showBoxes}
|
||||
draftBox={draftBox}
|
||||
activeClassColor={activeClass.color}
|
||||
activeClassName={activeClass.name}
|
||||
activeClassColor={activeClass?.color ?? '#888888'}
|
||||
activeClassName={activeClass?.name ?? ''}
|
||||
onSelectShape={setSelectedShapeId}
|
||||
onStartMoveBox={(pt, shape) => {
|
||||
if (!shape.bbox) return
|
||||
|
|
@ -428,7 +604,7 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
vertexEditEnabled={vertexEditEnabled}
|
||||
draftPolygonPoints={draftPolygonPoints}
|
||||
cursorPoint={cursorPoint}
|
||||
activeClassColor={activeClass.color}
|
||||
activeClassColor={activeClass?.color ?? '#888888'}
|
||||
onSelectShape={setSelectedShapeId}
|
||||
onStartDragVertex={(shapeId, vertexIndex) => {
|
||||
setInteraction({
|
||||
|
|
@ -452,6 +628,38 @@ export const AnnotationCanvas: React.FC = () => {
|
|||
/>
|
||||
)}
|
||||
|
||||
{/* Live brush preview: the raster being painted, tinted like a mask */}
|
||||
{project.taskType === 'segmentation' &&
|
||||
brushPainting &&
|
||||
maskCanvasRef.current && (
|
||||
<KonvaImageView
|
||||
image={maskCanvasRef.current}
|
||||
ref={brushPreviewRef}
|
||||
x={0}
|
||||
y={0}
|
||||
width={currentImage.width}
|
||||
height={currentImage.height}
|
||||
opacity={maskOpacity / 100}
|
||||
listening={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Brush cursor ring (constant on-screen width) */}
|
||||
{project.taskType === 'segmentation' &&
|
||||
activeTool === 'brush' &&
|
||||
cursorPoint &&
|
||||
!interaction && (
|
||||
<Circle
|
||||
x={cursorPoint.x}
|
||||
y={cursorPoint.y}
|
||||
radius={brushSize / 2}
|
||||
stroke="#525252"
|
||||
strokeWidth={1.5 / scale}
|
||||
dash={[6 / scale, 4 / scale]}
|
||||
listening={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PointTool
|
||||
shapes={shapes}
|
||||
selectedShapeId={selectedShapeId}
|
||||
|
|
|
|||
|
|
@ -6,46 +6,94 @@ export interface ImageViewerProps {
|
|||
thumbUrl?: string
|
||||
width: number
|
||||
height: number
|
||||
onError?: () => void
|
||||
}
|
||||
|
||||
// Blur-up: paint the (usually already cached) thumbnail first, swap to the
|
||||
// full image the moment it arrives. The canvas never stares blank waiting
|
||||
// on R2, and the swap is pixel-exact since both share the same dimensions.
|
||||
export const ImageViewer: React.FC<ImageViewerProps> = ({ url, thumbUrl, width, height }) => {
|
||||
export const ImageViewer: React.FC<ImageViewerProps> = ({ url, thumbUrl, width, height, onError }) => {
|
||||
const [current, setCurrent] = useState<HTMLImageElement | null>(null)
|
||||
const [failed, setFailed] = useState(false)
|
||||
const failedRef = React.useRef(false)
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
failedRef.current = false
|
||||
setFailed(false)
|
||||
setCurrent(null)
|
||||
|
||||
const showThumb = thumbUrl && thumbUrl !== url
|
||||
const paint = (src: string, done: (el: HTMLImageElement) => void) => {
|
||||
const paint = (
|
||||
src: string,
|
||||
done: (el: HTMLImageElement) => void,
|
||||
fail: () => void
|
||||
) => {
|
||||
const el = new window.Image()
|
||||
el.onload = () => {
|
||||
if (!cancelled) done(el)
|
||||
}
|
||||
el.onerror = () => {
|
||||
if (!cancelled) fail()
|
||||
}
|
||||
el.src = src
|
||||
}
|
||||
|
||||
if (showThumb) {
|
||||
paint(thumbUrl, (thumb) => {
|
||||
if (cancelled) return
|
||||
setCurrent(thumb)
|
||||
paint(url, (full) => {
|
||||
if (!cancelled) setCurrent(full)
|
||||
})
|
||||
})
|
||||
// Thumb failure is not fatal: the full image may still load.
|
||||
paint(
|
||||
thumbUrl,
|
||||
(thumb) => {
|
||||
if (cancelled) return
|
||||
setCurrent(thumb)
|
||||
paint(
|
||||
url,
|
||||
(full) => {
|
||||
if (!cancelled) setCurrent(full)
|
||||
},
|
||||
() => {
|
||||
// Full failed but thumb shows: keep thumb, no error.
|
||||
}
|
||||
)
|
||||
},
|
||||
() => {
|
||||
paint(
|
||||
url,
|
||||
(full) => {
|
||||
if (!cancelled) setCurrent(full)
|
||||
},
|
||||
() => {
|
||||
if (!cancelled && !failedRef.current) {
|
||||
failedRef.current = true
|
||||
setFailed(true)
|
||||
onError?.()
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
)
|
||||
} else {
|
||||
paint(url, (full) => {
|
||||
if (!cancelled) setCurrent(full)
|
||||
})
|
||||
paint(
|
||||
url,
|
||||
(full) => {
|
||||
if (!cancelled) setCurrent(full)
|
||||
},
|
||||
() => {
|
||||
if (!cancelled && !failedRef.current) {
|
||||
failedRef.current = true
|
||||
setFailed(true)
|
||||
onError?.()
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [url, thumbUrl])
|
||||
|
||||
if (!current) return null
|
||||
if (failed || !current) return null
|
||||
return <KonvaImage image={current} x={0} y={0} width={width} height={height} listening={false} />
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import React from 'react'
|
||||
import { Circle, Group, Line, Rect, Text } from 'react-konva'
|
||||
import { AnnotationShape, Point2D } from '@/types'
|
||||
import { useAnnotatorStore } from '../../annotatorStore'
|
||||
|
||||
export interface PolygonToolProps {
|
||||
shapes: AnnotationShape[]
|
||||
|
|
@ -31,6 +32,9 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
|
|||
onInsertVertexOnEdge,
|
||||
onCloseDraftPolygon,
|
||||
}) => {
|
||||
// Brush strokes must reach the canvas even when they start on an existing
|
||||
// mask: while brushing, shapes stay visible but don't swallow mousedown.
|
||||
const brushActive = useAnnotatorStore((s) => s.activeTool) === 'brush'
|
||||
if (!showMasks) return null
|
||||
|
||||
const polygonShapes = shapes.filter(
|
||||
|
|
@ -67,6 +71,7 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
|
|||
opacity={maskOpacity / 100}
|
||||
strokeEnabled={false}
|
||||
onMouseDown={(e) => {
|
||||
if (brushActive) return
|
||||
e.cancelBubble = true
|
||||
onSelectShape(shape.id)
|
||||
}}
|
||||
|
|
@ -140,6 +145,7 @@ export const PolygonTool: React.FC<PolygonToolProps> = ({
|
|||
stroke={shape.color}
|
||||
strokeWidth={3.5}
|
||||
onMouseDown={(e) => {
|
||||
if (brushActive) return
|
||||
e.cancelBubble = true
|
||||
if (vertexEditEnabled) {
|
||||
onStartDragVertex(shape.id, idx)
|
||||
|
|
|
|||
|
|
@ -52,6 +52,19 @@ export const ToolBar: React.FC = () => {
|
|||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'brush',
|
||||
label: 'Cọ',
|
||||
shortcut: 'B',
|
||||
enabled: taskType === 'segmentation',
|
||||
icon: (
|
||||
<svg className="h-3.5 w-3.5" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||
<path d="m14.5 12.5 5-5a2.12 2.12 0 0 0-3-3l-5 5" />
|
||||
<path d="m13.5 11.5-7.5 7.5a1.5 1.5 0 0 0 2.12 2.12l7.5-7.5" />
|
||||
<path d="m14.5 12.5 2 2L20 11l-2-2" />
|
||||
</svg>
|
||||
),
|
||||
},
|
||||
{
|
||||
id: 'point',
|
||||
label: 'Điểm',
|
||||
|
|
|
|||
|
|
@ -5,12 +5,15 @@ import { SaveStatus } from './SaveStatus'
|
|||
|
||||
export const ImageNavigator: React.FC = () => {
|
||||
const taskType = useAnnotatorStore((s) => s.project.taskType)
|
||||
const activeTool = useAnnotatorStore((s) => s.activeTool)
|
||||
|
||||
const leftHint =
|
||||
taskType === 'classification'
|
||||
? 'Chọn lớp ở bảng bên phải · Không tạo shape'
|
||||
: taskType === 'object_detection'
|
||||
? 'Kéo để tạo box · Kéo góc để chỉnh kích thước'
|
||||
: activeTool === 'brush'
|
||||
? 'Tô lên ảnh · Thả chuột để thành polygon'
|
||||
: 'Click để thêm đỉnh · Enter để đóng polygon'
|
||||
|
||||
const rightShortcut =
|
||||
|
|
@ -18,6 +21,8 @@ export const ImageNavigator: React.FC = () => {
|
|||
? 'Chọn [V]'
|
||||
: taskType === 'object_detection'
|
||||
? 'Hộp [B]'
|
||||
: activeTool === 'brush'
|
||||
? 'Cọ [B]'
|
||||
: 'Polygon [P]'
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -1,67 +1,90 @@
|
|||
import React from 'react'
|
||||
import React, { useEffect } from 'react'
|
||||
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.
|
||||
// Sliding window over the dataset cursor: only ~61 thumbs exist in DOM/R2
|
||||
// traffic at once, no matter if the project holds 12k images. Missing slots
|
||||
// render skeletons while ensureWindow backfills them.
|
||||
const STRIP_RADIUS = 30
|
||||
|
||||
export const ThumbnailStrip: React.FC = () => {
|
||||
const images = useAnnotatorStore((s) => s.images)
|
||||
const total = useAnnotatorStore((s) => s.images.length)
|
||||
const currentImageIndex = useAnnotatorStore((s) => s.currentImageIndex)
|
||||
const selectImageByIndex = useAnnotatorStore((s) => s.selectImageByIndex)
|
||||
const ensureWindow = useAnnotatorStore((s) => s.ensureWindow)
|
||||
const images = useAnnotatorStore((s) => s.images)
|
||||
|
||||
const lo = Math.max(0, currentImageIndex - STRIP_RADIUS)
|
||||
const hi = Math.min(images.length, currentImageIndex + STRIP_RADIUS + 1)
|
||||
const hi = Math.min(total, currentImageIndex + STRIP_RADIUS + 1)
|
||||
|
||||
useEffect(() => {
|
||||
ensureWindow(lo, hi)
|
||||
}, [ensureWindow, lo, hi])
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-6 gap-2.5 px-4 py-2.5">
|
||||
{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]+_/, '..')
|
||||
<div>
|
||||
{total > STRIP_RADIUS * 2 + 1 && (
|
||||
<div className="px-4 pb-1 text-[10px] tabular-nums text-slate-400">
|
||||
Hiển thị {lo + 1}–{hi} / {total} ảnh
|
||||
</div>
|
||||
)}
|
||||
<div className="grid grid-cols-6 gap-2.5 px-4 py-2.5">
|
||||
{Array.from({ length: Math.max(0, hi - lo) }, (_, k) => {
|
||||
const index = lo + k
|
||||
const img = images[index]
|
||||
const isActive = index === currentImageIndex
|
||||
if (!img) {
|
||||
return (
|
||||
<div key={`skeleton-${index}`} className="flex flex-col items-center gap-1">
|
||||
<div className="aspect-video w-full animate-pulse rounded-lg bg-slate-200" />
|
||||
<span className="font-mono text-[10px] text-slate-300">…</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
// Shorten "urban_00124.jpg" -> "..00124.jpg" matching wireframe
|
||||
const shortName = img.fileName.replace(/^[a-z]+_/, '..')
|
||||
|
||||
return (
|
||||
<button
|
||||
key={img.id}
|
||||
type="button"
|
||||
onClick={() => selectImageByIndex(index)}
|
||||
className="group flex flex-col items-center gap-1 focus:outline-none"
|
||||
>
|
||||
<div
|
||||
className={clsx(
|
||||
'relative aspect-video w-full overflow-hidden rounded-lg border-2 transition-all',
|
||||
isActive
|
||||
? 'shadow-xs'
|
||||
: 'border-transparent opacity-85 hover:opacity-100'
|
||||
)}
|
||||
style={isActive ? { borderColor: ANNOTATOR_COLORS.selection } : undefined}
|
||||
return (
|
||||
<button
|
||||
key={img.id}
|
||||
type="button"
|
||||
onClick={() => selectImageByIndex(index)}
|
||||
className="group flex flex-col items-center gap-1 focus:outline-none"
|
||||
>
|
||||
<img
|
||||
src={img.thumbnailSmallUrl ?? img.thumbnailUrl}
|
||||
alt={img.fileName}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
<div
|
||||
className={clsx(
|
||||
'relative aspect-video w-full overflow-hidden rounded-lg border-2 transition-all',
|
||||
isActive
|
||||
? 'shadow-xs'
|
||||
: 'border-transparent opacity-85 hover:opacity-100'
|
||||
)}
|
||||
style={isActive ? { borderColor: ANNOTATOR_COLORS.selection } : undefined}
|
||||
>
|
||||
<img
|
||||
src={img.thumbnailSmallUrl ?? img.thumbnailUrl}
|
||||
alt={img.fileName}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<span
|
||||
className={clsx(
|
||||
'font-mono text-[10px] transition-colors',
|
||||
isActive
|
||||
? 'font-semibold'
|
||||
: 'text-slate-400 group-hover:text-slate-600'
|
||||
)}
|
||||
style={isActive ? { color: ANNOTATOR_COLORS.selection } : undefined}
|
||||
>
|
||||
{shortName}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
<span
|
||||
className={clsx(
|
||||
'font-mono text-[10px] transition-colors',
|
||||
isActive
|
||||
? 'font-semibold'
|
||||
: 'text-slate-400 group-hover:text-slate-600'
|
||||
)}
|
||||
style={isActive ? { color: ANNOTATOR_COLORS.selection } : undefined}
|
||||
>
|
||||
{shortName}
|
||||
</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -80,12 +80,18 @@ export const ClassificationPanel: React.FC = () => {
|
|||
|
||||
{/* Reviewer Info Box */}
|
||||
<div className="rounded-xl bg-slate-50 p-3.5">
|
||||
<p className="text-xs font-semibold text-slate-800">
|
||||
{currentImage.submittedBy ?? 'Hà Linh'} đã gửi nhãn {activeClass?.name ?? 'Ô tô'}
|
||||
</p>
|
||||
{currentImage.submittedBy ? (
|
||||
<p className="text-xs font-semibold text-slate-800">
|
||||
{currentImage.submittedBy} đã gửi nhãn {activeClass?.name ?? 'Ô tô'}
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs font-semibold text-slate-800">
|
||||
Nhãn {activeClass?.name ?? 'Ô tô'}
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-1 text-[11px] text-slate-500">
|
||||
{currentImage.submittedAt ?? 'Hôm nay, 09:42'} · Người duyệt:{' '}
|
||||
{currentImage.reviewerName ?? 'Thu Hà'}
|
||||
{currentImage.submittedAt ?? 'Chưa gửi duyệt'} · Người duyệt:{' '}
|
||||
{currentImage.reviewerName ?? 'Chưa phân công'}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -13,10 +13,12 @@ export const SegmentationPanel: React.FC = () => {
|
|||
const selectedShapeId = useAnnotatorStore((s) => s.selectedShapeId)
|
||||
const showMasks = useAnnotatorStore((s) => s.showMasks)
|
||||
const maskOpacity = useAnnotatorStore((s) => s.maskOpacity)
|
||||
const brushSize = useAnnotatorStore((s) => s.brushSize)
|
||||
const vertexEditEnabled = useAnnotatorStore((s) => s.vertexEditEnabled)
|
||||
|
||||
const setShowMasks = useAnnotatorStore((s) => s.setShowMasks)
|
||||
const setMaskOpacity = useAnnotatorStore((s) => s.setMaskOpacity)
|
||||
const setBrushSize = useAnnotatorStore((s) => s.setBrushSize)
|
||||
const toggleVertexEdit = useAnnotatorStore((s) => s.toggleVertexEdit)
|
||||
const setSelectedShapeId = useAnnotatorStore((s) => s.setSelectedShapeId)
|
||||
const toggleShapeVisibility = useAnnotatorStore((s) => s.toggleShapeVisibility)
|
||||
|
|
@ -78,6 +80,23 @@ export const SegmentationPanel: React.FC = () => {
|
|||
/>
|
||||
</div>
|
||||
|
||||
{/* Brush Size Slider */}
|
||||
<div className="space-y-1.5">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="text-slate-500">Cỡ cọ (px ảnh gốc)</span>
|
||||
<span className="font-semibold text-[#4F46E5]">{brushSize}px</span>
|
||||
</div>
|
||||
<input
|
||||
type="range"
|
||||
min={4}
|
||||
max={160}
|
||||
step={2}
|
||||
value={brushSize}
|
||||
onChange={(e) => setBrushSize(Number(e.target.value))}
|
||||
className="h-1.5 w-full cursor-pointer appearance-none rounded-lg bg-slate-200 accent-[#C95C3C]"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Polygon Objects List */}
|
||||
<div className="max-h-[240px] space-y-2 overflow-y-auto pr-0.5">
|
||||
{shapes.map((shape) => (
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { useParams, useNavigate } from 'react-router-dom'
|
|||
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 { uploadFilesBatch } from '@/services/uploadQueue'
|
||||
import { replaceLabels } from '@/services/labelService'
|
||||
import { updateMemberProjects, updateMemberRole } from '@/services/userService'
|
||||
import {
|
||||
|
|
@ -83,13 +83,15 @@ export const ProjectDetailPage: React.FC = () => {
|
|||
}
|
||||
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()
|
||||
const result = await uploadFilesBatch(project.id, Array.from(fileList))
|
||||
const skippedMsg =
|
||||
result.skipped.length > 0 ? `, bỏ qua ${result.skipped.length} tên trùng` : ''
|
||||
if (result.failed.length === 0) {
|
||||
toast.success(`Đã tải lên ${result.done.length} ảnh${skippedMsg}`)
|
||||
} else {
|
||||
toast.error(`Xong ${result.done.length} ảnh, lỗi ${result.failed.length}${skippedMsg}`)
|
||||
}
|
||||
if (result.done.length > 0) await reload()
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Tải ảnh thất bại')
|
||||
} finally {
|
||||
|
|
@ -307,7 +309,7 @@ export const ProjectDetailPage: React.FC = () => {
|
|||
{activeTab === 'data' && (
|
||||
<DataTab
|
||||
project={project}
|
||||
onUploadImages={(_names, files) => void handleUploadFiles(files ? toFileList(files) : null)}
|
||||
onUploadComplete={() => void reload()}
|
||||
hideSampleUpload={!USE_MOCK_DATA}
|
||||
/>
|
||||
)}
|
||||
|
|
@ -338,10 +340,4 @@ export const ProjectDetailPage: React.FC = () => {
|
|||
)
|
||||
}
|
||||
|
||||
function toFileList(files: File[]): FileList | null {
|
||||
const dt = new DataTransfer()
|
||||
for (const f of files) dt.items.add(f)
|
||||
return dt.files.length > 0 ? dt.files : null
|
||||
}
|
||||
|
||||
export default ProjectDetailPage
|
||||
|
|
|
|||
|
|
@ -1,13 +1,36 @@
|
|||
import React, { useState, useRef } from 'react'
|
||||
import toast from 'react-hot-toast'
|
||||
import { Project } from '@/types'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import {
|
||||
collectDroppedFiles,
|
||||
uploadFilesBatch,
|
||||
uploadFileMultipart,
|
||||
type UploadTask,
|
||||
} from '@/services/uploadQueue'
|
||||
import { api } from '@/services/api'
|
||||
import {
|
||||
importCocoFile,
|
||||
importYoloFiles,
|
||||
type DatasetImportSummary,
|
||||
} from '@/services/datasetImportService'
|
||||
import { addUploadedImagesToProject } from '../../projectData'
|
||||
import { ImageTable } from './ImageTable'
|
||||
|
||||
interface DataTabProps {
|
||||
project: Project
|
||||
onUploadImages: (fileNames: string[], files?: File[]) => void
|
||||
onUploadComplete: () => void
|
||||
hideSampleUpload?: boolean
|
||||
}
|
||||
|
||||
const IMAGE_EXTS = ['.jpg', '.jpeg', '.png', '.webp', '.bmp']
|
||||
const ZIP_LIMIT_BYTES = 400 * 1024 * 1024
|
||||
|
||||
function isImageName(name: string): boolean {
|
||||
const lower = name.toLowerCase()
|
||||
return IMAGE_EXTS.some((ext) => lower.endsWith(ext))
|
||||
}
|
||||
|
||||
interface DatasetBatch {
|
||||
id: string
|
||||
batchName: string
|
||||
|
|
@ -19,77 +42,250 @@ interface DatasetBatch {
|
|||
|
||||
export const DataTab: React.FC<DataTabProps> = ({
|
||||
project,
|
||||
onUploadImages,
|
||||
onUploadComplete,
|
||||
hideSampleUpload = false,
|
||||
}) => {
|
||||
const imageCount = project.stats.totalImages
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const folderInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const zipInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const cocoInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const yoloInputRef = useRef<HTMLInputElement | null>(null)
|
||||
const [isImporting, setIsImporting] = useState(false)
|
||||
const [isDragging, setIsDragging] = useState(false)
|
||||
const [batches, setBatches] = useState<DatasetBatch[]>([
|
||||
{
|
||||
id: 'batch-03',
|
||||
batchName: 'batch_2026_10_morning_cam04',
|
||||
uploadedBy: 'Minh Anh',
|
||||
uploadedAt: 'Hôm nay, 08:30',
|
||||
imageCount: 320,
|
||||
status: 'Đang gán nhãn',
|
||||
},
|
||||
{
|
||||
id: 'batch-02',
|
||||
batchName: 'batch_2026_10_intersection_02',
|
||||
uploadedBy: 'Minh Anh',
|
||||
uploadedAt: 'Hôm qua, 16:15',
|
||||
imageCount: 480,
|
||||
status: 'Đang gán nhãn',
|
||||
},
|
||||
{
|
||||
id: 'batch-01',
|
||||
batchName: 'batch_2026_09_initial_seed',
|
||||
uploadedBy: 'Thu Hà',
|
||||
uploadedAt: '5 ngày trước',
|
||||
imageCount: 480,
|
||||
status: 'Hoàn thành',
|
||||
},
|
||||
])
|
||||
|
||||
const handleFilesSelected = (files: FileList | null) => {
|
||||
if (!files || files.length === 0) return
|
||||
const list = Array.from(files)
|
||||
onUploadImages(
|
||||
list.map((f) => f.name),
|
||||
list
|
||||
)
|
||||
const [tasks, setTasks] = useState<UploadTask[]>([])
|
||||
const [isUploading, setIsUploading] = useState(false)
|
||||
const fileBlobs = useRef(new Map<string, File>())
|
||||
const [batches, setBatches] = useState<DatasetBatch[]>(() =>
|
||||
USE_MOCK_DATA
|
||||
? [
|
||||
{
|
||||
id: 'batch-03',
|
||||
batchName: 'batch_2026_10_morning_cam04',
|
||||
uploadedBy: 'Minh Anh',
|
||||
uploadedAt: 'Hôm nay, 08:30',
|
||||
imageCount: 320,
|
||||
status: 'Đang gán nhãn',
|
||||
},
|
||||
{
|
||||
id: 'batch-02',
|
||||
batchName: 'batch_2026_10_intersection_02',
|
||||
uploadedBy: 'Minh Anh',
|
||||
uploadedAt: 'Hôm qua, 16:15',
|
||||
imageCount: 480,
|
||||
status: 'Đang gán nhãn',
|
||||
},
|
||||
{
|
||||
id: 'batch-01',
|
||||
batchName: 'batch_2026_09_initial_seed',
|
||||
uploadedBy: 'Thu Hà',
|
||||
uploadedAt: '5 ngày trước',
|
||||
imageCount: 480,
|
||||
status: 'Hoàn thành',
|
||||
},
|
||||
]
|
||||
: []
|
||||
)
|
||||
const pushBatchRow = (count: number, batchName: string) => {
|
||||
setBatches((prev) => [
|
||||
{
|
||||
id: `batch-${Date.now()}`,
|
||||
batchName: `upload_batch_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}`,
|
||||
uploadedBy: 'Minh Anh',
|
||||
batchName,
|
||||
uploadedBy: 'Bạn',
|
||||
uploadedAt: 'Vừa tải lên',
|
||||
imageCount: list.length,
|
||||
imageCount: count,
|
||||
status: 'Đã phân công',
|
||||
},
|
||||
...prev,
|
||||
])
|
||||
}
|
||||
|
||||
const runUpload = async (files: File[], batchName: string) => {
|
||||
if (USE_MOCK_DATA) {
|
||||
addUploadedImagesToProject(
|
||||
project.id,
|
||||
files.map((f) => f.name)
|
||||
)
|
||||
pushBatchRow(files.length, batchName)
|
||||
onUploadComplete()
|
||||
return
|
||||
}
|
||||
const images = files.filter((f) => isImageName(f.name))
|
||||
if (images.length === 0) {
|
||||
toast.error('Không tìm thấy ảnh hợp lệ (jpg, png, webp, bmp)')
|
||||
return
|
||||
}
|
||||
images.forEach((f) => fileBlobs.current.set(f.name, f))
|
||||
setIsUploading(true)
|
||||
try {
|
||||
const result = await uploadFilesBatch(project.id, images, setTasks)
|
||||
pushBatchRow(result.done.length, batchName)
|
||||
const skippedMsg =
|
||||
result.skipped.length > 0 ? `, bỏ qua ${result.skipped.length} tên trùng` : ''
|
||||
if (result.failed.length === 0) {
|
||||
toast.success(`Đã tải lên ${result.done.length} ảnh${skippedMsg}`)
|
||||
} else {
|
||||
toast.error(
|
||||
`Xong ${result.done.length}/${images.length} ảnh, lỗi ${result.failed.length}${skippedMsg} — bấm Thử lại`
|
||||
)
|
||||
}
|
||||
if (result.done.length > 0) onUploadComplete()
|
||||
} finally {
|
||||
setIsUploading(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleFilesSelected = (files: FileList | null) => {
|
||||
if (!files || files.length === 0) return
|
||||
void runUpload(
|
||||
Array.from(files),
|
||||
`upload_batch_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}`
|
||||
)
|
||||
}
|
||||
|
||||
const handleDrop = async (dt: DataTransfer) => {
|
||||
const files = await collectDroppedFiles(dt)
|
||||
if (files.length === 0) {
|
||||
toast.error('Thư mục trống hoặc không đọc được')
|
||||
return
|
||||
}
|
||||
await runUpload(files, `drop_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}`)
|
||||
}
|
||||
|
||||
const [serverImport, setServerImport] = useState<string | null>(null)
|
||||
|
||||
const pollServerImport = (jobId: string) => {
|
||||
// Poll the server job until done/error; cheap (one tiny request per 10s).
|
||||
const timer = window.setInterval(async () => {
|
||||
try {
|
||||
const { data } = await api.get<{ status: string; done_files: number; total_files: number; error?: string }>(
|
||||
`/projects/${project.id}/imports/${jobId}`
|
||||
)
|
||||
if (data.status === 'done') {
|
||||
window.clearInterval(timer)
|
||||
setServerImport(null)
|
||||
toast.success(`Nhập xong ${data.done_files} ảnh từ zip`)
|
||||
onUploadComplete()
|
||||
} else if (data.status === 'error') {
|
||||
window.clearInterval(timer)
|
||||
setServerImport(null)
|
||||
toast.error(`Nhập zip thất bại: ${data.error ?? 'lỗi server'}`)
|
||||
} else {
|
||||
setServerImport(`Server đang nhập ${data.done_files}/${data.total_files} ảnh…`)
|
||||
}
|
||||
} catch {
|
||||
window.clearInterval(timer)
|
||||
setServerImport(null)
|
||||
}
|
||||
}, 10000)
|
||||
}
|
||||
|
||||
const handleZipSelected = async (files: FileList | null) => {
|
||||
const zipFile = files?.[0]
|
||||
if (!zipFile) return
|
||||
if (zipFile.size > ZIP_LIMIT_BYTES) {
|
||||
// GB-scale: multipart upload straight to R2, then the server imports
|
||||
// from the R2 key (streamed, bounded RAM) — never through the browser.
|
||||
try {
|
||||
setServerImport(`Đang đẩy ${(zipFile.size / 1024 / 1024 / 1024).toFixed(1)}GB lên kho… 0%`)
|
||||
const { r2Key } = await uploadFileMultipart(project.id, zipFile, (ratio) => {
|
||||
setServerImport(
|
||||
`Đang đẩy ${(zipFile.size / 1024 / 1024 / 1024).toFixed(1)}GB lên kho… ${Math.round(ratio * 100)}%`
|
||||
)
|
||||
})
|
||||
const { data: job } = await api.post<{ id: string }>(
|
||||
`/projects/${project.id}/imports/r2-zip`,
|
||||
{ r2_key: r2Key }
|
||||
)
|
||||
toast.success('Zip đã lên kho, server bắt đầu nhập — bạn cứ làm việc tiếp')
|
||||
pollServerImport(job.id)
|
||||
} catch (err) {
|
||||
setServerImport(null)
|
||||
toast.error(err instanceof Error ? err.message : 'Đẩy zip thất bại')
|
||||
}
|
||||
return
|
||||
}
|
||||
try {
|
||||
const { default: JSZip } = await import('jszip')
|
||||
const zip = await JSZip.loadAsync(zipFile)
|
||||
const out: File[] = []
|
||||
const entries = Object.values(zip.files).filter(
|
||||
(e) => !e.dir && !e.name.startsWith('__MACOSX/') && isImageName(e.name)
|
||||
)
|
||||
for (const entry of entries) {
|
||||
const blob = await entry.async('blob')
|
||||
const base = entry.name.split('/').pop() ?? entry.name
|
||||
out.push(new File([blob], base, { type: 'image/jpeg' }))
|
||||
}
|
||||
if (out.length === 0) {
|
||||
toast.error('Zip không chứa ảnh hợp lệ')
|
||||
return
|
||||
}
|
||||
await runUpload(out, zipFile.name.replace(/\.[^/.]+$/, ''))
|
||||
} catch {
|
||||
toast.error('Không đọc được file zip')
|
||||
}
|
||||
}
|
||||
|
||||
const failedTasks = tasks.filter((t) => t.status === 'error')
|
||||
|
||||
const summarizeImport = (summary: DatasetImportSummary, kind: string) => {
|
||||
const parts = [`${kind}: lưu ${summary.saved} ảnh`]
|
||||
if (summary.createdClasses.length > 0) {
|
||||
parts.push(`tạo ${summary.createdClasses.length} lớp mới (${summary.createdClasses.join(', ')})`)
|
||||
}
|
||||
if (summary.missingFiles.length > 0) {
|
||||
parts.push(`${summary.missingFiles.length} file không khớp tên ảnh`)
|
||||
}
|
||||
summary.warnings.slice(0, 2).forEach((w) => parts.push(w))
|
||||
toast.success(parts.join(' · '))
|
||||
if (summary.saved > 0) onUploadComplete()
|
||||
}
|
||||
|
||||
const handleCocoSelected = async (files: FileList | null) => {
|
||||
const file = files?.[0]
|
||||
if (!file) return
|
||||
setIsImporting(true)
|
||||
try {
|
||||
summarizeImport(await importCocoFile(project.id, file), 'COCO')
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Nhập COCO thất bại')
|
||||
} finally {
|
||||
setIsImporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const handleYoloSelected = async (files: FileList | null) => {
|
||||
if (!files || files.length === 0) return
|
||||
setIsImporting(true)
|
||||
try {
|
||||
summarizeImport(await importYoloFiles(project.id, Array.from(files)), 'YOLO')
|
||||
} catch (err) {
|
||||
toast.error(err instanceof Error ? err.message : 'Nhập YOLO thất bại')
|
||||
} finally {
|
||||
setIsImporting(false)
|
||||
}
|
||||
}
|
||||
|
||||
const retryFailed = async () => {
|
||||
const files = failedTasks
|
||||
.map((t) => fileBlobs.current.get(t.fileName))
|
||||
.filter((f): f is File => f !== undefined)
|
||||
if (files.length === 0) return
|
||||
await runUpload(files, `retry_${new Date().toISOString().slice(0, 10).replace(/-/g, '_')}`)
|
||||
}
|
||||
|
||||
const handleSimulatedSampleUpload = () => {
|
||||
if (!USE_MOCK_DATA) return
|
||||
const sampleNames = [
|
||||
`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) => [
|
||||
{
|
||||
id: `batch-${Date.now()}`,
|
||||
batchName: `camera_import_${batches.length + 1}`,
|
||||
uploadedBy: 'Minh Anh',
|
||||
uploadedAt: 'Vừa tải lên',
|
||||
imageCount: sampleNames.length,
|
||||
status: 'Đã phân công',
|
||||
},
|
||||
...prev,
|
||||
])
|
||||
pushBatchRow(
|
||||
sampleNames.length,
|
||||
`camera_import_${batches.length + 1}`
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
|
|
@ -104,7 +300,7 @@ export const DataTab: React.FC<DataTabProps> = ({
|
|||
onDrop={(e) => {
|
||||
e.preventDefault()
|
||||
setIsDragging(false)
|
||||
handleFilesSelected(e.dataTransfer.files)
|
||||
void handleDrop(e.dataTransfer)
|
||||
}}
|
||||
className={`flex flex-col items-center justify-center rounded-2xl border-2 border-dashed p-8 text-center transition ${
|
||||
isDragging
|
||||
|
|
@ -118,7 +314,52 @@ export const DataTab: React.FC<DataTabProps> = ({
|
|||
accept="image/*"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => handleFilesSelected(e.target.files)}
|
||||
onChange={(e) => {
|
||||
handleFilesSelected(e.target.files)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
ref={folderInputRef}
|
||||
type="file"
|
||||
// @ts-expect-error webkitdirectory is valid but missing from React types
|
||||
webkitdirectory=""
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
handleFilesSelected(e.target.files)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
ref={zipInputRef}
|
||||
type="file"
|
||||
accept=".zip,application/zip"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
void handleZipSelected(e.target.files)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
ref={cocoInputRef}
|
||||
type="file"
|
||||
accept=".json,application/json"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
void handleCocoSelected(e.target.files)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<input
|
||||
ref={yoloInputRef}
|
||||
type="file"
|
||||
accept=".txt,.yaml,.yml"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
void handleYoloSelected(e.target.files)
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-2xl bg-[#FDF4F1] text-[#C95C3C]">
|
||||
<svg
|
||||
|
|
@ -146,10 +387,45 @@ export const DataTab: React.FC<DataTabProps> = ({
|
|||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
className="rounded-xl bg-[#C95C3C] px-4 py-2 text-xs font-semibold text-white shadow-sm transition hover:bg-[#B5492B]"
|
||||
disabled={isUploading}
|
||||
className="rounded-xl bg-[#C95C3C] px-4 py-2 text-xs font-semibold text-white shadow-sm transition hover:bg-[#B5492B] disabled:opacity-60"
|
||||
>
|
||||
Chọn tệp từ máy tính
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => folderInputRef.current?.click()}
|
||||
disabled={isUploading}
|
||||
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-xs font-semibold text-slate-700 transition hover:bg-slate-50 disabled:opacity-60"
|
||||
>
|
||||
Chọn cả thư mục
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => zipInputRef.current?.click()}
|
||||
disabled={isUploading}
|
||||
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-xs font-semibold text-slate-700 transition hover:bg-slate-50 disabled:opacity-60"
|
||||
>
|
||||
Nhập file ZIP
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => cocoInputRef.current?.click()}
|
||||
disabled={isUploading || isImporting}
|
||||
title="Nhập annotation COCO JSON (ảnh phải tải lên trước, khớp theo tên file)"
|
||||
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-xs font-semibold text-slate-700 transition hover:bg-slate-50 disabled:opacity-60"
|
||||
>
|
||||
{isImporting ? 'Đang nhập…' : 'Nhập COCO'}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => yoloInputRef.current?.click()}
|
||||
disabled={isUploading || isImporting}
|
||||
title="Nhập nhãn YOLO (.txt + classes.txt hoặc dataset.yaml)"
|
||||
className="rounded-xl border border-slate-200 bg-white px-4 py-2 text-xs font-semibold text-slate-700 transition hover:bg-slate-50 disabled:opacity-60"
|
||||
>
|
||||
{isImporting ? 'Đang nhập…' : 'Nhập YOLO'}
|
||||
</button>
|
||||
{!hideSampleUpload && (
|
||||
<button
|
||||
type="button"
|
||||
|
|
@ -160,6 +436,63 @@ export const DataTab: React.FC<DataTabProps> = ({
|
|||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Batch progress: overall bar + failed rows with retry */}
|
||||
{serverImport && (
|
||||
<div className="mx-auto mt-5 w-full max-w-xl rounded-xl border border-indigo-200 bg-indigo-50/60 p-4 text-left">
|
||||
<div className="flex items-center gap-2 text-xs font-semibold text-indigo-900">
|
||||
<span className="inline-block h-3 w-3 animate-spin rounded-full border-2 border-indigo-200 border-t-indigo-700" />
|
||||
<span>{serverImport}</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{tasks.length > 0 && (
|
||||
<div className="mx-auto mt-5 w-full max-w-xl rounded-xl border border-slate-200 bg-white p-4 text-left">
|
||||
{(() => {
|
||||
const done = tasks.filter((t) => t.status === 'done').length
|
||||
const pct = Math.round((done / Math.max(1, tasks.length)) * 100)
|
||||
return (
|
||||
<>
|
||||
<div className="flex items-center justify-between text-xs font-semibold text-slate-700">
|
||||
<span>
|
||||
Đang tải {done}/{tasks.length} ảnh
|
||||
{isUploading ? '…' : ' — xong'}
|
||||
</span>
|
||||
<span className="tabular-nums">{pct}%</span>
|
||||
</div>
|
||||
<div className="mt-2 h-2 overflow-hidden rounded-full bg-slate-100">
|
||||
<div
|
||||
className="h-full rounded-full bg-[#C95C3C] transition-all"
|
||||
style={{ width: `${pct}%` }}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
})()}
|
||||
{failedTasks.length > 0 && (
|
||||
<div className="mt-3 space-y-1.5">
|
||||
{failedTasks.slice(0, 5).map((t) => (
|
||||
<p key={t.fileName} className="truncate text-[11px] text-red-600">
|
||||
{t.fileName}: {t.error ?? 'lỗi'}
|
||||
</p>
|
||||
))}
|
||||
{failedTasks.length > 5 && (
|
||||
<p className="text-[11px] text-slate-400">
|
||||
…và {failedTasks.length - 5} file lỗi khác
|
||||
</p>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => void retryFailed()}
|
||||
disabled={isUploading}
|
||||
className="mt-1 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] font-semibold text-slate-700 hover:bg-slate-50 disabled:opacity-60"
|
||||
>
|
||||
Thử lại {failedTasks.length} file lỗi
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Dataset Batches Table */}
|
||||
|
|
|
|||
|
|
@ -5,6 +5,9 @@ import {
|
|||
UserStatus,
|
||||
InviteMemberInput,
|
||||
} from '../../types'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { useProjects } from '@/hooks/useProjects'
|
||||
import { useUsers } from '@/hooks/useUsers'
|
||||
import { UserStatsCards } from './components/UserStatsCards'
|
||||
import { UserTableFilters } from './components/UserTableFilters'
|
||||
import { UserTable } from './components/UserTable'
|
||||
|
|
@ -130,7 +133,22 @@ const INITIAL_MEMBERS: WorkspaceMember[] = [
|
|||
]
|
||||
|
||||
export const UserManagementPage: React.FC = () => {
|
||||
const [members, setMembers] = useState<WorkspaceMember[]>(INITIAL_MEMBERS)
|
||||
const [mockMembers, setMockMembers] = useState<WorkspaceMember[]>(INITIAL_MEMBERS)
|
||||
const usersApi = useUsers()
|
||||
const { allProjects } = useProjects()
|
||||
// Real mode: single source of truth is the API (starts with just the admin;
|
||||
// more members arrive via invite). Mock mode keeps the local fixture.
|
||||
const members = USE_MOCK_DATA ? mockMembers : usersApi.allMembers
|
||||
const setMembers = (updater: (prev: WorkspaceMember[]) => WorkspaceMember[]) => {
|
||||
if (USE_MOCK_DATA) setMockMembers(updater)
|
||||
}
|
||||
const projectOptions = USE_MOCK_DATA
|
||||
? [
|
||||
{ id: 'proj-1', name: 'Phương tiện đô thị' },
|
||||
{ id: 'proj-2', name: 'Giao thông đô thị' },
|
||||
{ id: 'proj-3', name: 'Phân vùng đường phố' },
|
||||
]
|
||||
: allProjects.map((p) => ({ id: p.id, name: p.name }))
|
||||
const [activeTab, setActiveTab] = useState<'members' | 'invites' | 'roles'>(
|
||||
'members'
|
||||
)
|
||||
|
|
@ -197,6 +215,15 @@ export const UserManagementPage: React.FC = () => {
|
|||
)
|
||||
|
||||
const handleChangeRole = (memberId: string, newRole: UserRole) => {
|
||||
if (!USE_MOCK_DATA) {
|
||||
usersApi
|
||||
.updateMemberRole({ memberId, role: newRole })
|
||||
.then(() => showToast('Đã cập nhật vai trò thành viên.'))
|
||||
.catch(() =>
|
||||
showToast('Cập nhật vai trò thất bại.')
|
||||
)
|
||||
return
|
||||
}
|
||||
setMembers((prev) =>
|
||||
prev.map((m) =>
|
||||
m.id === memberId
|
||||
|
|
@ -212,6 +239,19 @@ export const UserManagementPage: React.FC = () => {
|
|||
}
|
||||
|
||||
const handleToggleStatus = (memberId: string) => {
|
||||
if (!USE_MOCK_DATA) {
|
||||
usersApi
|
||||
.toggleMemberStatus(memberId)
|
||||
.then((updated) =>
|
||||
showToast(
|
||||
updated.status === 'suspended'
|
||||
? `Đã tạm khóa tài khoản ${updated.name}.`
|
||||
: `Đã mở khóa tài khoản ${updated.name}.`
|
||||
)
|
||||
)
|
||||
.catch(() => showToast('Cập nhật trạng thái thất bại.'))
|
||||
return
|
||||
}
|
||||
setMembers((prev) =>
|
||||
prev.map((m) => {
|
||||
if (m.id !== memberId) return m
|
||||
|
|
@ -231,6 +271,18 @@ export const UserManagementPage: React.FC = () => {
|
|||
}
|
||||
|
||||
const handleInviteMember = (input: InviteMemberInput) => {
|
||||
if (!USE_MOCK_DATA) {
|
||||
usersApi
|
||||
.inviteMember(input)
|
||||
.then(() => {
|
||||
setInviteModalOpen(false)
|
||||
showToast(`Đã gửi lời mời đến ${input.email}`)
|
||||
})
|
||||
.catch(() =>
|
||||
showToast('Mời thành viên thất bại.')
|
||||
)
|
||||
return
|
||||
}
|
||||
const emailPrefix = input.email.split('@')[0] || 'Thành viên'
|
||||
const formattedName = emailPrefix
|
||||
.replace(/[._-]/g, ' ')
|
||||
|
|
@ -276,6 +328,13 @@ export const UserManagementPage: React.FC = () => {
|
|||
}
|
||||
|
||||
const handleCancelInvite = (id: string) => {
|
||||
if (!USE_MOCK_DATA) {
|
||||
usersApi
|
||||
.deleteMember(id)
|
||||
.then(() => showToast('Đã hủy lời mời.'))
|
||||
.catch(() => showToast('Hủy lời mời thất bại.'))
|
||||
return
|
||||
}
|
||||
setMembers((prev) => prev.filter((m) => m.id !== id))
|
||||
showToast('Đã hủy lời mời.')
|
||||
}
|
||||
|
|
@ -396,6 +455,7 @@ export const UserManagementPage: React.FC = () => {
|
|||
onStatusFilterChange={setStatusFilter}
|
||||
projectFilter={projectFilter}
|
||||
onProjectFilterChange={setProjectFilter}
|
||||
projectOptions={projectOptions}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
|
@ -423,6 +483,7 @@ export const UserManagementPage: React.FC = () => {
|
|||
isOpen={inviteModalOpen}
|
||||
onClose={() => setInviteModalOpen(false)}
|
||||
onInvite={handleInviteMember}
|
||||
projects={projectOptions}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ export interface InviteUserModalProps {
|
|||
isOpen: boolean
|
||||
onClose: () => void
|
||||
onInvite: (input: InviteMemberInput) => void
|
||||
projects?: { id: string; name: string }[]
|
||||
}
|
||||
|
||||
const AVAILABLE_PROJECTS = [
|
||||
|
|
@ -17,14 +18,15 @@ export const InviteUserModal: React.FC<InviteUserModalProps> = ({
|
|||
isOpen,
|
||||
onClose,
|
||||
onInvite,
|
||||
projects,
|
||||
}) => {
|
||||
const projectList: { id: string; name: string; count?: string }[] =
|
||||
projects ?? AVAILABLE_PROJECTS
|
||||
const [email, setEmail] = useState('')
|
||||
const [role, setRole] = useState<UserRole>('annotator')
|
||||
const [selectedProjects, setSelectedProjects] = useState<string[]>([
|
||||
'proj-1',
|
||||
'proj-2',
|
||||
'proj-3',
|
||||
])
|
||||
const [selectedProjects, setSelectedProjects] = useState<string[]>(() =>
|
||||
projectList.map((p) => p.id)
|
||||
)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
|
||||
if (!isOpen) return null
|
||||
|
|
@ -151,7 +153,7 @@ export const InviteUserModal: React.FC<InviteUserModalProps> = ({
|
|||
Dự án được phân công
|
||||
</label>
|
||||
<div className="space-y-2 rounded-xl border border-slate-200 p-3 bg-slate-50/50">
|
||||
{AVAILABLE_PROJECTS.map((proj) => {
|
||||
{projectList.map((proj) => {
|
||||
const checked = selectedProjects.includes(proj.id)
|
||||
return (
|
||||
<label
|
||||
|
|
@ -167,7 +169,7 @@ export const InviteUserModal: React.FC<InviteUserModalProps> = ({
|
|||
/>
|
||||
<span>{proj.name}</span>
|
||||
</span>
|
||||
<span className="text-slate-400">{proj.count}</span>
|
||||
<span className="text-slate-400">{proj.count ?? ''}</span>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ export interface UserTableFiltersProps {
|
|||
onStatusFilterChange: (value: UserStatus | 'all') => void
|
||||
projectFilter: string
|
||||
onProjectFilterChange: (value: string) => void
|
||||
projectOptions?: { id: string; name: string }[]
|
||||
}
|
||||
|
||||
export const UserTableFilters: React.FC<UserTableFiltersProps> = ({
|
||||
|
|
@ -21,6 +22,11 @@ export const UserTableFilters: React.FC<UserTableFiltersProps> = ({
|
|||
onStatusFilterChange,
|
||||
projectFilter,
|
||||
onProjectFilterChange,
|
||||
projectOptions = [
|
||||
{ id: 'proj-1', name: 'Phương tiện đô thị' },
|
||||
{ id: 'proj-2', name: 'Giao thông đô thị' },
|
||||
{ id: 'proj-3', name: 'Phân vùng đường phố' },
|
||||
],
|
||||
}) => {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-2.5">
|
||||
|
|
@ -112,9 +118,11 @@ export const UserTableFilters: React.FC<UserTableFiltersProps> = ({
|
|||
className="appearance-none pl-3.5 pr-8 py-2 rounded-xl border border-slate-200 bg-white text-xs sm:text-[13px] font-medium text-slate-700 hover:border-slate-300 focus:outline-none focus:border-indigo-500 cursor-pointer"
|
||||
>
|
||||
<option value="all">Tất cả dự án</option>
|
||||
<option value="proj-1">Phương tiện đô thị</option>
|
||||
<option value="proj-2">Giao thông đô thị</option>
|
||||
<option value="proj-3">Phân vùng đường phố</option>
|
||||
{projectOptions.map((p) => (
|
||||
<option key={p.id} value={p.id}>
|
||||
{p.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<span className="pointer-events-none absolute inset-y-0 right-0 pr-2.5 flex items-center text-slate-500">
|
||||
<svg
|
||||
|
|
|
|||
141
src/services/datasetImportService.ts
Normal file
141
src/services/datasetImportService.ts
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
import { AnnotationShape } from '@/types'
|
||||
import { USE_MOCK_DATA } from '@/app/constants'
|
||||
import { api } from './api'
|
||||
import { getProjectById } from './projectService'
|
||||
import { getProjectImages } from './imageService'
|
||||
import { replaceLabels } from './labelService'
|
||||
import { stem, type ImportShape, type ParsedDataset } from '@/utils/datasetImport'
|
||||
|
||||
export interface DatasetImportSummary {
|
||||
saved: number
|
||||
missingFiles: string[]
|
||||
skippedRle: number
|
||||
createdClasses: string[]
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
function toShapes(
|
||||
shapes: ImportShape[],
|
||||
classOf: (label: string) => { id: string; name: string; color: string }
|
||||
): AnnotationShape[] {
|
||||
return shapes.map((s, i) => {
|
||||
const cls = classOf(s.label)
|
||||
const base = {
|
||||
id: `imp-${Date.now()}-${i}`,
|
||||
index: i + 1,
|
||||
labelId: cls.id,
|
||||
labelName: cls.name,
|
||||
color: cls.color,
|
||||
visible: true,
|
||||
}
|
||||
if (s.polygon) {
|
||||
return { ...base, type: 'polygon' as const, points: s.polygon }
|
||||
}
|
||||
const b = s.bbox ?? { x: 0, y: 0, width: 10, height: 10 }
|
||||
return { ...base, type: 'bbox' as const, bbox: b }
|
||||
})
|
||||
}
|
||||
|
||||
export async function importParsedDataset(
|
||||
projectId: string,
|
||||
parsed: ParsedDataset
|
||||
): Promise<DatasetImportSummary> {
|
||||
if (USE_MOCK_DATA) {
|
||||
throw new Error('Nhập dataset annotation chỉ khả dụng ở chế độ API thật')
|
||||
}
|
||||
const project = await getProjectById(projectId)
|
||||
const images = await getProjectImages(project.id)
|
||||
const byStem = new Map(images.map((img) => [stem(img.fileName), img]))
|
||||
|
||||
// Match categories to project classes (case-insensitive); create missing ones.
|
||||
const classOf = new Map<string, { id: string; name: string; color: string }>()
|
||||
project.classes.forEach((c) => classOf.set(c.name.toLowerCase(), c))
|
||||
const createdClasses: string[] = []
|
||||
for (const name of parsed.categories) {
|
||||
if (!classOf.has(name.toLowerCase())) {
|
||||
createdClasses.push(name)
|
||||
}
|
||||
}
|
||||
let classes = project.classes
|
||||
if (createdClasses.length > 0) {
|
||||
const palette = ['#3B82F6', '#10B981', '#F59E0B', '#A855F7', '#EF4444', '#06B6D4']
|
||||
const additions = createdClasses.map((name, i) => ({
|
||||
id: `cls-imp-${Date.now()}-${i}`,
|
||||
name,
|
||||
color: palette[(classes.length + i) % palette.length]!,
|
||||
count: 0,
|
||||
shortcutKey: undefined,
|
||||
}))
|
||||
classes = await replaceLabels(project.id, [...classes, ...additions])
|
||||
classes.forEach((c) => classOf.set(c.name.toLowerCase(), c))
|
||||
}
|
||||
const resolve = (label: string) =>
|
||||
classOf.get(label.toLowerCase()) ?? {
|
||||
id: classes[0]?.id ?? '',
|
||||
name: classes[0]?.name ?? label,
|
||||
color: classes[0]?.color ?? '#888888',
|
||||
};
|
||||
|
||||
const payload: Record<
|
||||
string,
|
||||
{ classificationLabelId?: string; flags: { blurryOrUncertain: boolean; needsRecheck: boolean }; shapes: AnnotationShape[] }
|
||||
> = {}
|
||||
const missingFiles: string[] = []
|
||||
for (const item of parsed.items) {
|
||||
const img = byStem.get(stem(item.fileName))
|
||||
if (!img) {
|
||||
missingFiles.push(item.fileName)
|
||||
continue
|
||||
}
|
||||
const shapes = toShapes(item.shapes, resolve)
|
||||
const firstLabel = item.shapes[0]?.label
|
||||
payload[img.id] = {
|
||||
classificationLabelId:
|
||||
project.taskType === 'classification' && firstLabel
|
||||
? resolve(firstLabel).id
|
||||
: undefined,
|
||||
flags: { blurryOrUncertain: false, needsRecheck: false },
|
||||
shapes,
|
||||
}
|
||||
}
|
||||
// Bulk upsert in 500-image chunks (server limit per call).
|
||||
const entries = Object.entries(payload)
|
||||
let saved = 0
|
||||
const missing: string[] = []
|
||||
for (let i = 0; i < entries.length; i += 500) {
|
||||
const chunk = Object.fromEntries(entries.slice(i, i + 500))
|
||||
const { data } = await api.put<{ saved: number; missing: string[] }>(
|
||||
`/projects/${project.id}/annotations/batch`,
|
||||
chunk
|
||||
)
|
||||
saved += data.saved
|
||||
missing.push(...data.missing)
|
||||
}
|
||||
return {
|
||||
saved,
|
||||
missingFiles: [...missingFiles, ...missing],
|
||||
skippedRle: parsed.warnings.filter((w) => w.includes('RLE')).length,
|
||||
createdClasses,
|
||||
warnings: parsed.warnings,
|
||||
}
|
||||
}
|
||||
|
||||
export async function importCocoFile(projectId: string, file: File): Promise<DatasetImportSummary> {
|
||||
const { parseCocoDataset } = await import('@/utils/datasetImport')
|
||||
const parsed = parseCocoDataset(JSON.parse(await file.text()))
|
||||
return importParsedDataset(projectId, parsed)
|
||||
}
|
||||
|
||||
export async function importYoloFiles(
|
||||
projectId: string,
|
||||
txtFiles: File[]
|
||||
): Promise<DatasetImportSummary> {
|
||||
const { parseYoloFiles } = await import('@/utils/datasetImport')
|
||||
const project = await getProjectById(projectId)
|
||||
const images = await getProjectImages(project.id)
|
||||
const dims = new Map(
|
||||
images.map((img) => [stem(img.fileName), { width: img.width, height: img.height }])
|
||||
)
|
||||
const parsed = await parseYoloFiles(txtFiles, dims)
|
||||
return importParsedDataset(projectId, parsed)
|
||||
}
|
||||
|
|
@ -139,6 +139,16 @@ export async function getProjectImages(
|
|||
return items
|
||||
}
|
||||
|
||||
export async function getImageOffset(
|
||||
projectId: string,
|
||||
imageId: string
|
||||
): Promise<{ offset: number; total: number }> {
|
||||
const { data } = await api.get<{ offset: number; total: number }>(
|
||||
`/projects/${projectId}/images/by-id/${imageId}`
|
||||
)
|
||||
return data
|
||||
}
|
||||
|
||||
export async function getImageById(projectId: string, imageId: string): Promise<ImageItem> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
const items = await getProjectImages(projectId)
|
||||
|
|
|
|||
311
src/services/uploadQueue.ts
Normal file
311
src/services/uploadQueue.ts
Normal file
|
|
@ -0,0 +1,311 @@
|
|||
import { api } from './api'
|
||||
|
||||
export type UploadTaskStatus = 'pending' | 'uploading' | 'done' | 'error' | 'skipped'
|
||||
|
||||
export interface UploadTask {
|
||||
fileName: string
|
||||
status: UploadTaskStatus
|
||||
progress: number
|
||||
error?: string
|
||||
imageId?: string
|
||||
}
|
||||
|
||||
export interface BatchUploadResult {
|
||||
done: { fileName: string; imageId: string }[]
|
||||
failed: { fileName: string; error: string }[]
|
||||
skipped: string[]
|
||||
}
|
||||
|
||||
interface PresignSlot {
|
||||
fileName: string
|
||||
putUrl: string
|
||||
r2Key: string
|
||||
}
|
||||
|
||||
const CONCURRENCY = 4
|
||||
const MAX_RETRIES = 2
|
||||
|
||||
function putWithProgress(
|
||||
url: string,
|
||||
file: File,
|
||||
contentType: string,
|
||||
onProgress: (ratio: number) => void
|
||||
): Promise<void> {
|
||||
// fetch has no upload progress; XHR is used for this single call only.
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest()
|
||||
xhr.open('PUT', url)
|
||||
xhr.setRequestHeader('Content-Type', contentType)
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) onProgress(e.loaded / e.total)
|
||||
}
|
||||
xhr.onload = () =>
|
||||
xhr.status >= 200 && xhr.status < 300
|
||||
? resolve()
|
||||
: reject(new Error(`Tải lên kho lưu trữ thất bại (${xhr.status})`))
|
||||
xhr.onerror = () => reject(new Error('Lỗi mạng khi tải lên'))
|
||||
xhr.send(file)
|
||||
})
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively collect files from a drop (files and/or folders) preserving names.
|
||||
export async function collectDroppedFiles(dt: DataTransfer): Promise<File[]> {
|
||||
const items = Array.from(dt.items).filter((i) => i.kind === 'file')
|
||||
const entries = items
|
||||
.map((i) => (typeof i.webkitGetAsEntry === 'function' ? i.webkitGetAsEntry() : null))
|
||||
.filter((e): e is FileSystemEntry => e !== null)
|
||||
if (entries.length === 0 || entries.every((e) => e.isFile)) {
|
||||
return Array.from(dt.files)
|
||||
}
|
||||
const out: File[] = []
|
||||
const walk = async (entry: FileSystemEntry, prefix: string): Promise<void> => {
|
||||
if (entry.isFile) {
|
||||
const blob = await new Promise<File>((resolve, reject) =>
|
||||
(entry as FileSystemFileEntry).file(resolve, reject)
|
||||
)
|
||||
out.push(new File([blob], prefix + blob.name, { type: blob.type }))
|
||||
return
|
||||
}
|
||||
if (entry.isDirectory) {
|
||||
const reader = (entry as FileSystemDirectoryEntry).createReader()
|
||||
for (;;) {
|
||||
const batch: FileSystemEntry[] = await new Promise((resolve, reject) =>
|
||||
reader.readEntries(resolve, reject)
|
||||
)
|
||||
if (batch.length === 0) break
|
||||
for (const child of batch) await walk(child, `${prefix}${entry.name}/`)
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const entry of entries) await walk(entry, '')
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- Resumable multipart upload for single big files (100MB..GBs) ----
|
||||
// Parts go straight to R2 in parallel with per-part retry; ETags persist in
|
||||
// localStorage so a dropped network resumes instead of restarting.
|
||||
const MP_PART_SIZE = 8 * 1024 * 1024
|
||||
const MP_CONCURRENCY = 4
|
||||
const MP_RETRIES = 2
|
||||
const MP_RESUME_PREFIX = 'danable:mp:'
|
||||
|
||||
interface MpResume {
|
||||
key: string
|
||||
uploadId: string
|
||||
etags: Record<number, string>
|
||||
totalParts: number
|
||||
}
|
||||
|
||||
function mpFingerprint(file: File): string {
|
||||
return `${MP_RESUME_PREFIX}${file.name}-${file.size}-${file.lastModified}`
|
||||
}
|
||||
|
||||
function putPart(
|
||||
url: string,
|
||||
blob: Blob,
|
||||
onProgress: (loaded: number) => void
|
||||
): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest()
|
||||
xhr.open('PUT', url)
|
||||
xhr.upload.onprogress = (e) => {
|
||||
if (e.lengthComputable) onProgress(e.loaded)
|
||||
}
|
||||
xhr.onload = () => {
|
||||
if (xhr.status >= 200 && xhr.status < 300) {
|
||||
resolve(xhr.getResponseHeader('ETag') ?? '')
|
||||
} else {
|
||||
reject(new Error(`Part thất bại (${xhr.status})`))
|
||||
}
|
||||
}
|
||||
xhr.onerror = () => reject(new Error('Lỗi mạng khi tải part'))
|
||||
xhr.send(blob)
|
||||
})
|
||||
}
|
||||
|
||||
export async function uploadFileMultipart(
|
||||
projectId: string,
|
||||
file: File,
|
||||
onProgress?: (ratio: number, uploadedBytes: number) => void
|
||||
): Promise<{ r2Key: string }> {
|
||||
const totalParts = Math.max(1, Math.ceil(file.size / MP_PART_SIZE))
|
||||
const saved = (() => {
|
||||
try {
|
||||
const raw = localStorage.getItem(mpFingerprint(file))
|
||||
return raw ? (JSON.parse(raw) as MpResume) : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
})()
|
||||
|
||||
let key: string
|
||||
let uploadId: string
|
||||
const etags: Record<number, string> = { ...(saved?.etags ?? {}) }
|
||||
if (saved && saved.totalParts === totalParts) {
|
||||
// Resume: reuse key + uploadId, skip parts that already have ETags.
|
||||
key = saved.key
|
||||
uploadId = saved.uploadId
|
||||
} else {
|
||||
const { data } = await api.post<{ key: string; uploadId: string }>(
|
||||
`/projects/${projectId}/uploads/multipart`,
|
||||
{ fileName: file.name, contentType: file.type || 'application/octet-stream' }
|
||||
)
|
||||
key = data.key
|
||||
uploadId = data.uploadId
|
||||
}
|
||||
const persist = () => {
|
||||
try {
|
||||
localStorage.setItem(
|
||||
mpFingerprint(file),
|
||||
JSON.stringify({ key, uploadId, etags, totalParts })
|
||||
)
|
||||
} catch {
|
||||
// Private mode: resume simply unavailable.
|
||||
}
|
||||
}
|
||||
persist()
|
||||
|
||||
const { data: partUrls } = await api.post<{ urls: Record<number, string> }>(
|
||||
`/projects/${projectId}/uploads/multipart/parts`,
|
||||
{ key, uploadId, numbers: Array.from({ length: totalParts }, (_, i) => i + 1) }
|
||||
)
|
||||
|
||||
const loaded = new Array<number>(totalParts).fill(0)
|
||||
const report = () => {
|
||||
const sum = loaded.reduce((a, b) => a + b, 0)
|
||||
onProgress?.(sum / Math.max(1, file.size), sum)
|
||||
}
|
||||
let cursor = 0
|
||||
const numbers = Array.from({ length: totalParts }, (_, i) => i + 1)
|
||||
const worker = async (): Promise<void> => {
|
||||
for (;;) {
|
||||
const n = numbers[cursor++]
|
||||
if (n === undefined) return
|
||||
if (etags[n]) continue
|
||||
const start = (n - 1) * MP_PART_SIZE
|
||||
const blob = file.slice(start, start + MP_PART_SIZE)
|
||||
let done = false
|
||||
for (let attempt = 0; attempt <= MP_RETRIES && !done; attempt++) {
|
||||
try {
|
||||
etags[n] = await putPart(partUrls.urls[n]!, blob, (ld) => {
|
||||
loaded[n - 1] = ld
|
||||
report()
|
||||
})
|
||||
loaded[n - 1] = blob.size
|
||||
report()
|
||||
persist()
|
||||
done = true
|
||||
} catch (err) {
|
||||
if (attempt === MP_RETRIES) throw err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(MP_CONCURRENCY, totalParts) }, worker))
|
||||
|
||||
await api.post(`/projects/${projectId}/uploads/multipart/complete`, {
|
||||
key,
|
||||
uploadId,
|
||||
parts: Object.entries(etags).map(([num, ETag]) => ({ ETag, PartNumber: Number(num) })),
|
||||
})
|
||||
try {
|
||||
localStorage.removeItem(mpFingerprint(file))
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
onProgress?.(1, file.size)
|
||||
return { r2Key: key }
|
||||
}
|
||||
|
||||
export async function uploadFilesBatch(
|
||||
projectId: string,
|
||||
files: File[],
|
||||
onUpdate?: (tasks: UploadTask[]) => void
|
||||
): Promise<BatchUploadResult> {
|
||||
const seen = new Set<string>()
|
||||
const tasks: UploadTask[] = files.map((f) => {
|
||||
if (seen.has(f.name)) {
|
||||
return { fileName: f.name, status: 'skipped', progress: 0 }
|
||||
}
|
||||
seen.add(f.name)
|
||||
return { fileName: f.name, status: 'pending', progress: 0 }
|
||||
})
|
||||
const emit = () => onUpdate?.(tasks.map((t) => ({ ...t })))
|
||||
emit()
|
||||
|
||||
// One presign call per 100 files instead of one per file.
|
||||
const slots = new Map<string, PresignSlot>()
|
||||
const pending = files.filter((f) => tasks.find((t) => t.fileName === f.name)?.status === 'pending')
|
||||
for (let i = 0; i < pending.length; i += 100) {
|
||||
const chunk = pending.slice(i, i + 100)
|
||||
const { data } = await api.post<PresignSlot[]>(`/projects/${projectId}/images/batch-presign`,
|
||||
chunk.map((f) => ({ fileName: f.name, contentType: f.type || 'image/jpeg' }))
|
||||
)
|
||||
data.forEach((s) => slots.set(s.fileName, s))
|
||||
}
|
||||
|
||||
const result: BatchUploadResult = { done: [], failed: [], skipped: [] }
|
||||
tasks.forEach((t) => {
|
||||
if (t.status === 'skipped') result.skipped.push(t.fileName)
|
||||
})
|
||||
|
||||
let cursor = 0
|
||||
const queue = pending.slice()
|
||||
const worker = async (): Promise<void> => {
|
||||
for (;;) {
|
||||
const file = queue[cursor++]
|
||||
if (!file) return
|
||||
const task = tasks.find((t) => t.fileName === file.name)!
|
||||
const slot = slots.get(file.name)
|
||||
if (!slot) {
|
||||
task.status = 'error'
|
||||
task.error = 'Không lấy được URL tải lên'
|
||||
result.failed.push({ fileName: file.name, error: task.error })
|
||||
emit()
|
||||
continue
|
||||
}
|
||||
task.status = 'uploading'
|
||||
emit()
|
||||
let ok = false
|
||||
for (let attempt = 0; attempt <= MAX_RETRIES && !ok; attempt++) {
|
||||
try {
|
||||
const dims = await readDimensions(file)
|
||||
await putWithProgress(slot.putUrl, file, file.type || 'image/jpeg', (r) => {
|
||||
task.progress = r
|
||||
emit()
|
||||
})
|
||||
const { data: confirmed } = await api.post<{ id: string }>(
|
||||
`/projects/${projectId}/images`,
|
||||
{ fileName: file.name, r2Key: slot.r2Key, width: dims.width, height: dims.height }
|
||||
)
|
||||
task.status = 'done'
|
||||
task.progress = 1
|
||||
task.imageId = confirmed.id
|
||||
result.done.push({ fileName: file.name, imageId: confirmed.id })
|
||||
ok = true
|
||||
} catch (err) {
|
||||
task.error = err instanceof Error ? err.message : 'Tải lên thất bại'
|
||||
if (attempt === MAX_RETRIES) {
|
||||
task.status = 'error'
|
||||
result.failed.push({ fileName: file.name, error: task.error })
|
||||
}
|
||||
} finally {
|
||||
emit()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
await Promise.all(Array.from({ length: Math.min(CONCURRENCY, queue.length) }, worker))
|
||||
return result
|
||||
}
|
||||
|
|
@ -225,6 +225,17 @@ export async function updateMemberProjects(
|
|||
return updated
|
||||
}
|
||||
|
||||
export async function deleteMember(memberId: string): Promise<void> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
await api.delete(`/users/${memberId}`)
|
||||
return
|
||||
}
|
||||
await delay(120)
|
||||
const db = getMockDb()
|
||||
db.members = db.members.filter((m) => m.id !== memberId)
|
||||
saveMockDb(db)
|
||||
}
|
||||
|
||||
export async function getRolePermissions(): Promise<RolePermissionItem[]> {
|
||||
if (!USE_MOCK_DATA) {
|
||||
// Static reference data, same for every workspace.
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
export type AnnotationTool = 'select' | 'bbox' | 'polygon' | 'point'
|
||||
export type AnnotationTool = 'select' | 'bbox' | 'polygon' | 'point' | 'brush'
|
||||
|
||||
export interface BoundingBox {
|
||||
x: number
|
||||
|
|
|
|||
216
src/utils/datasetImport.ts
Normal file
216
src/utils/datasetImport.ts
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
// Pure parsers: COCO JSON / YOLO txt (+classes) -> normalized import items.
|
||||
// No API calls here; orchestration lives in datasetImportService.
|
||||
export interface ImportShape {
|
||||
label: string
|
||||
bbox?: { x: number; y: number; width: number; height: number }
|
||||
polygon?: { x: number; y: number }[]
|
||||
}
|
||||
|
||||
export interface ImportItem {
|
||||
fileName: string
|
||||
width?: number
|
||||
height?: number
|
||||
shapes: ImportShape[]
|
||||
}
|
||||
|
||||
export interface ParsedDataset {
|
||||
items: ImportItem[]
|
||||
categories: string[]
|
||||
warnings: string[]
|
||||
}
|
||||
|
||||
export function stem(name: string): string {
|
||||
const base = name.split('/').pop() ?? name
|
||||
return base.replace(/\.[^/.]+$/, '').toLowerCase()
|
||||
}
|
||||
|
||||
function roundBox(b: { x: number; y: number; width: number; height: number }) {
|
||||
return {
|
||||
x: Math.round(b.x),
|
||||
y: Math.round(b.y),
|
||||
width: Math.round(b.width),
|
||||
height: Math.round(b.height),
|
||||
}
|
||||
}
|
||||
|
||||
export function parseCocoDataset(json: unknown): ParsedDataset {
|
||||
const warnings: string[] = []
|
||||
if (typeof json !== 'object' || json === null) {
|
||||
throw new Error('File COCO không đúng định dạng JSON')
|
||||
}
|
||||
const root = json as {
|
||||
images?: { id?: number | string; file_name?: string; width?: number; height?: number }[]
|
||||
annotations?: {
|
||||
image_id?: number | string
|
||||
category_id?: number | string
|
||||
bbox?: [number, number, number, number]
|
||||
segmentation?: number[][] | { counts?: unknown } | unknown
|
||||
iscrowd?: number
|
||||
}[]
|
||||
categories?: { id?: number | string; name?: string }[]
|
||||
}
|
||||
if (!Array.isArray(root.images) || !Array.isArray(root.annotations) || !Array.isArray(root.categories)) {
|
||||
throw new Error('Thiếu images / annotations / categories trong COCO JSON')
|
||||
}
|
||||
const catName = new Map<string, string>()
|
||||
root.categories.forEach((c) => {
|
||||
if (c.id !== undefined && c.name) catName.set(String(c.id), c.name)
|
||||
})
|
||||
const byImage = new Map<string, ImportShape[]>()
|
||||
let skippedRle = 0
|
||||
for (const ann of root.annotations) {
|
||||
const key = String(ann.image_id ?? '')
|
||||
const label = catName.get(String(ann.category_id ?? '')) ?? `class_${ann.category_id}`
|
||||
const list = byImage.get(key) ?? []
|
||||
const shape: ImportShape = { label }
|
||||
if (Array.isArray(ann.bbox) && ann.bbox.length === 4) {
|
||||
const [x, y, w, h] = ann.bbox
|
||||
shape.bbox = roundBox({ x, y, width: w, height: h })
|
||||
}
|
||||
const seg = ann.segmentation as number[][] | { counts?: unknown } | undefined
|
||||
if (Array.isArray(seg) && seg.length > 0 && Array.isArray(seg[0]) && (seg[0] as number[]).length >= 6) {
|
||||
const ring = seg[0] as number[]
|
||||
const pts: { x: number; y: number }[] = []
|
||||
for (let i = 0; i + 1 < ring.length; i += 2) {
|
||||
pts.push({ x: Math.round(ring[i]!), y: Math.round(ring[i + 1]!) })
|
||||
}
|
||||
shape.polygon = pts
|
||||
} else if (seg !== undefined && (!Array.isArray(seg) || (Array.isArray(seg) && seg.length > 0))) {
|
||||
// RLE / crowd masks cannot become vector shapes: keep bbox if present.
|
||||
if (!shape.bbox) {
|
||||
skippedRle += 1
|
||||
continue
|
||||
}
|
||||
}
|
||||
if (!shape.bbox && !shape.polygon) continue
|
||||
list.push(shape)
|
||||
byImage.set(key, list)
|
||||
}
|
||||
if (skippedRle > 0) {
|
||||
warnings.push(`${skippedRle} mask RLE/crowd không chuyển được sang polygon, đã bỏ qua`)
|
||||
}
|
||||
const idToFile = new Map<string, { fileName: string; width?: number; height?: number }>()
|
||||
root.images.forEach((img) => {
|
||||
if (img.id !== undefined && img.file_name) {
|
||||
idToFile.set(String(img.id), {
|
||||
fileName: img.file_name.split('/').pop() ?? img.file_name,
|
||||
width: img.width,
|
||||
height: img.height,
|
||||
})
|
||||
}
|
||||
})
|
||||
const items: ImportItem[] = []
|
||||
byImage.forEach((shapes, imageId) => {
|
||||
const meta = idToFile.get(imageId)
|
||||
if (!meta) {
|
||||
warnings.push(`annotation tham chiếu image_id không tồn tại: ${imageId}`)
|
||||
return
|
||||
}
|
||||
items.push({ ...meta, shapes })
|
||||
})
|
||||
return { items, categories: [...catName.values()], warnings }
|
||||
}
|
||||
|
||||
function parseYoloClasses(text: string, fileName: string): string[] | null {
|
||||
if (/classes\.txt$/i.test(fileName)) {
|
||||
return text
|
||||
.split('\n')
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l !== '')
|
||||
}
|
||||
if (/\.ya?ml$/i.test(fileName)) {
|
||||
// Minimal parse: supports `names: [a, b]` and block `- a` / `0: a` forms.
|
||||
const inline = text.match(/names\s*:\s*\[([^\]]*)\]/)
|
||||
if (inline?.[1] !== undefined) {
|
||||
return inline[1].split(',').map((s) => s.trim().replace(/^['"]|['"]$/g, '')).filter(Boolean)
|
||||
}
|
||||
const names: string[] = []
|
||||
const map: Record<number, string> = {}
|
||||
let inNames = false
|
||||
for (const line of text.split('\n')) {
|
||||
if (/^\s*names\s*:\s*$/.test(line)) {
|
||||
inNames = true
|
||||
continue
|
||||
}
|
||||
if (inNames) {
|
||||
const dash = line.match(/^\s*-\s*(.+)\s*$/)
|
||||
if (dash?.[1]) {
|
||||
names.push(dash[1].trim().replace(/^['"]|['"]$/g, ''))
|
||||
continue
|
||||
}
|
||||
const kv = line.match(/^\s*(\d+)\s*:\s*(.+)\s*$/)
|
||||
if (kv?.[1] !== undefined && kv?.[2]) {
|
||||
map[Number(kv[1])] = kv[2].trim().replace(/^['"]|['"]$/g, '')
|
||||
continue
|
||||
}
|
||||
if (/^\s*\S+\s*:\s*\S/.test(line) && !/^\s/.test(line)) break
|
||||
}
|
||||
}
|
||||
const fromMap = Object.keys(map)
|
||||
.map(Number)
|
||||
.sort((a, b) => a - b)
|
||||
.map((k) => map[k]!)
|
||||
const out = names.length > 0 ? names : fromMap
|
||||
return out.length > 0 ? out : null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export async function parseYoloFiles(
|
||||
txtFiles: File[],
|
||||
imageDims: Map<string, { width: number; height: number }>
|
||||
): Promise<ParsedDataset> {
|
||||
const warnings: string[] = []
|
||||
const classes: string[] = []
|
||||
const labelFiles: File[] = []
|
||||
for (const f of txtFiles) {
|
||||
const text = await f.text()
|
||||
const parsed = parseYoloClasses(text, f.name)
|
||||
if (parsed) {
|
||||
if (classes.length === 0) classes.push(...parsed)
|
||||
} else if (/\.txt$/i.test(f.name)) {
|
||||
labelFiles.push(f)
|
||||
}
|
||||
}
|
||||
if (classes.length === 0) {
|
||||
throw new Error('Thiếu classes.txt hoặc dataset.yaml kèm theo file .txt nhãn')
|
||||
}
|
||||
const items: ImportItem[] = []
|
||||
for (const f of labelFiles) {
|
||||
const dims = imageDims.get(stem(f.name))
|
||||
if (!dims || dims.width <= 0) {
|
||||
warnings.push(`Bỏ qua ${f.name}: không tìm thấy ảnh cùng tên trong dự án`)
|
||||
continue
|
||||
}
|
||||
const text = await f.text()
|
||||
const shapes: ImportShape[] = []
|
||||
text.split('\n').forEach((line, idx) => {
|
||||
const parts = line.trim().split(/\s+/)
|
||||
if (parts.length < 5) {
|
||||
if (line.trim() !== '') warnings.push(`${f.name}:${idx + 1} dòng sai định dạng, bỏ qua`)
|
||||
return
|
||||
}
|
||||
const [clsRaw, xcRaw, ycRaw, wRaw, hRaw] = parts
|
||||
const cls = Number(clsRaw)
|
||||
const vals = [xcRaw, ycRaw, wRaw, hRaw].map(Number)
|
||||
if (!Number.isInteger(cls) || vals.some((v) => !Number.isFinite(v))) {
|
||||
warnings.push(`${f.name}:${idx + 1} dòng sai định dạng, bỏ qua`)
|
||||
return
|
||||
}
|
||||
const [xc, yc, w, h] = vals as [number, number, number, number]
|
||||
shapes.push({
|
||||
label: classes[cls] ?? `class_${cls}`,
|
||||
bbox: roundBox({
|
||||
x: (xc - w / 2) * dims.width,
|
||||
y: (yc - h / 2) * dims.height,
|
||||
width: w * dims.width,
|
||||
height: h * dims.height,
|
||||
}),
|
||||
})
|
||||
})
|
||||
if (shapes.length > 0) {
|
||||
items.push({ fileName: `${stem(f.name)}.jpg`, width: dims.width, height: dims.height, shapes })
|
||||
}
|
||||
}
|
||||
return { items, categories: classes, warnings }
|
||||
}
|
||||
145
src/utils/maskTrace.ts
Normal file
145
src/utils/maskTrace.ts
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
import { Point2D } from '@/types'
|
||||
|
||||
// Raster mask -> vector polygons: connected components, one ordered contour
|
||||
// each, simplified. Lets the brush tool store plain polygon shapes, so
|
||||
// rendering, editing, export and the backend all keep working unchanged.
|
||||
export function traceMask(
|
||||
data: Uint8ClampedArray,
|
||||
width: number,
|
||||
height: number,
|
||||
minArea = 64,
|
||||
epsilon = 1.5
|
||||
): Point2D[][] {
|
||||
const mask = new Uint8Array(width * height)
|
||||
for (let i = 0; i < mask.length; i++) {
|
||||
mask[i] = data[i * 4 + 3]! > 127 ? 1 : 0
|
||||
}
|
||||
|
||||
const seen = new Uint8Array(width * height)
|
||||
const stack: number[] = []
|
||||
const out: Point2D[][] = []
|
||||
for (let s = 0; s < mask.length; s++) {
|
||||
if (!mask[s] || seen[s]) continue
|
||||
// Flood-fill one 8-connected blob, collecting its boundary pixels
|
||||
// (foreground with at least one background 8-neighbour).
|
||||
const boundary = new Map<number, Point2D>()
|
||||
stack.push(s)
|
||||
seen[s] = 1
|
||||
while (stack.length > 0) {
|
||||
const cur = stack.pop()!
|
||||
const cx = cur % width
|
||||
const cy = Math.floor(cur / width)
|
||||
let isEdge = false
|
||||
for (let dy = -1; dy <= 1; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
if (dx === 0 && dy === 0) continue
|
||||
const nx = cx + dx
|
||||
const ny = cy + dy
|
||||
const inside =
|
||||
nx >= 0 && ny >= 0 && nx < width && ny < height && mask[ny * width + nx] === 1
|
||||
if (!inside) {
|
||||
isEdge = true
|
||||
} else {
|
||||
const ni = ny * width + nx
|
||||
if (!seen[ni]) {
|
||||
seen[ni] = 1
|
||||
stack.push(ni)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isEdge) boundary.set(cur, { x: cx, y: cy })
|
||||
}
|
||||
if (boundary.size < 3) continue
|
||||
const ordered = walkBoundary(boundary)
|
||||
if (ordered.length >= 3 && Math.abs(shoelace(ordered)) >= minArea) {
|
||||
const simplified = simplify(ordered, epsilon)
|
||||
if (simplified.length >= 3) out.push(simplified)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Greedy perimeter walk: from the topmost-leftmost boundary pixel, always
|
||||
// step to the nearest unused 8-neighbour (jump only when disconnected).
|
||||
function walkBoundary(cells: Map<number, Point2D>): Point2D[] {
|
||||
let startKey = -1
|
||||
let startPt: Point2D | null = null
|
||||
for (const [key, pt] of Array.from(cells.entries())) {
|
||||
if (
|
||||
startPt === null ||
|
||||
pt.y < startPt.y ||
|
||||
(pt.y === startPt.y && pt.x < startPt.x)
|
||||
) {
|
||||
startKey = key
|
||||
startPt = pt
|
||||
}
|
||||
}
|
||||
if (startPt === null) return []
|
||||
const unused = new Map(cells)
|
||||
unused.delete(startKey)
|
||||
const path: Point2D[] = [startPt]
|
||||
let cur = startPt
|
||||
const dist2 = (a: Point2D, b: Point2D) => (a.x - b.x) ** 2 + (a.y - b.y) ** 2
|
||||
while (unused.size > 0) {
|
||||
let bestKey = -1
|
||||
let best: Point2D | null = null
|
||||
let bestD = Infinity
|
||||
let adjacentFound = false
|
||||
for (const [key, pt] of Array.from(unused.entries())) {
|
||||
const d = dist2(cur, pt)
|
||||
const adjacent = Math.abs(pt.x - cur.x) <= 1 && Math.abs(pt.y - cur.y) <= 1
|
||||
if (adjacent && (!adjacentFound || d < bestD)) {
|
||||
adjacentFound = true
|
||||
bestKey = key
|
||||
best = pt
|
||||
bestD = d
|
||||
} else if (!adjacentFound && d < bestD) {
|
||||
bestKey = key
|
||||
best = pt
|
||||
bestD = d
|
||||
}
|
||||
}
|
||||
if (best === null) break
|
||||
path.push(best)
|
||||
unused.delete(bestKey)
|
||||
cur = best
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
function shoelace(points: Point2D[]): number {
|
||||
let sum = 0
|
||||
for (let i = 0; i < points.length; i++) {
|
||||
const a = points[i]!
|
||||
const b = points[(i + 1) % points.length]!
|
||||
sum += a.x * b.y - b.x * a.y
|
||||
}
|
||||
return sum / 2
|
||||
}
|
||||
|
||||
function perpendicularDistance(p: Point2D, a: Point2D, b: Point2D): number {
|
||||
const dx = b.x - a.x
|
||||
const dy = b.y - a.y
|
||||
if (dx === 0 && dy === 0) return Math.hypot(p.x - a.x, p.y - a.y)
|
||||
return Math.abs(dy * p.x - dx * p.y + b.x * a.y - b.y * a.x) / Math.hypot(dx, dy)
|
||||
}
|
||||
|
||||
function simplify(points: Point2D[], epsilon: number): Point2D[] {
|
||||
if (points.length <= 2) return points
|
||||
let maxDist = 0
|
||||
let index = 0
|
||||
for (let i = 1; i < points.length - 1; i++) {
|
||||
const d = perpendicularDistance(points[i]!, points[0]!, points[points.length - 1]!)
|
||||
if (d > maxDist) {
|
||||
maxDist = d
|
||||
index = i
|
||||
}
|
||||
}
|
||||
if (maxDist > epsilon) {
|
||||
const left = simplify(points.slice(0, index + 1), epsilon)
|
||||
const right = simplify(points.slice(index), epsilon)
|
||||
return [...left.slice(0, -1), ...right]
|
||||
}
|
||||
return [points[0]!, points[points.length - 1]!]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue