Feat: 토스트 추가, 프로젝트 카테고리 설정 추가

This commit is contained in:
jhynsoo 2024-09-27 15:02:30 +09:00
parent 465b3385f8
commit ade83e966f
16 changed files with 489 additions and 44 deletions

View File

@ -17,6 +17,7 @@
"@radix-ui/react-select": "^2.1.1",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
"@radix-ui/react-toast": "^1.2.1",
"@radix-ui/react-tooltip": "^1.1.2",
"@tanstack/react-query": "^5.52.1",
"axios": "^1.7.5",
@ -4581,6 +4582,40 @@
}
}
},
"node_modules/@radix-ui/react-toast": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@radix-ui/react-toast/-/react-toast-1.2.1.tgz",
"integrity": "sha512-5trl7piMXcZiCq7MW6r8YYmu0bK5qDpTWz+FdEPdKyft2UixkspheYbjbrLXVN5NGKHFbOP7lm8eD0biiSqZqg==",
"license": "MIT",
"dependencies": {
"@radix-ui/primitive": "1.1.0",
"@radix-ui/react-collection": "1.1.0",
"@radix-ui/react-compose-refs": "1.1.0",
"@radix-ui/react-context": "1.1.0",
"@radix-ui/react-dismissable-layer": "1.1.0",
"@radix-ui/react-portal": "1.1.1",
"@radix-ui/react-presence": "1.1.0",
"@radix-ui/react-primitive": "2.0.0",
"@radix-ui/react-use-callback-ref": "1.1.0",
"@radix-ui/react-use-controllable-state": "1.1.0",
"@radix-ui/react-use-layout-effect": "1.1.0",
"@radix-ui/react-visually-hidden": "1.1.0"
},
"peerDependencies": {
"@types/react": "*",
"@types/react-dom": "*",
"react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc",
"react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc"
},
"peerDependenciesMeta": {
"@types/react": {
"optional": true
},
"@types/react-dom": {
"optional": true
}
}
},
"node_modules/@radix-ui/react-tooltip": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-tooltip/-/react-tooltip-1.1.2.tgz",

View File

@ -23,6 +23,7 @@
"@radix-ui/react-select": "^2.1.1",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
"@radix-ui/react-toast": "^1.2.1",
"@radix-ui/react-tooltip": "^1.1.2",
"@tanstack/react-query": "^5.52.1",
"axios": "^1.7.5",

View File

@ -1,6 +1,7 @@
import { RouterProvider } from 'react-router-dom';
import router from './router';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from './components/ui/toaster';
const queryClient = new QueryClient();
@ -8,6 +9,7 @@ function App() {
return (
<QueryClientProvider client={queryClient}>
<RouterProvider router={router} />
<Toaster />
</QueryClientProvider>
);
}

View File

@ -13,6 +13,7 @@ import useProjectStore from '@/stores/useProjectStore';
import { LABEL_CATEGORY } from '@/constants';
import { useQueryClient } from '@tanstack/react-query';
import useSaveImageLabelsQuery from '@/queries/projects/useSaveImageLabelsQuery';
import { useToast } from '@/hooks/use-toast';
export default function ImageCanvas() {
const { project, folderId } = useProjectStore();
@ -31,6 +32,7 @@ export default function ImageCanvas() {
const [polygonPoints, setPolygonPoints] = useState<[number, number][]>([]);
const saveImageLabelsMutation = useSaveImageLabelsQuery();
const queryClient = useQueryClient();
const { toast } = useToast();
useEffect(() => {
setLabels(
@ -73,9 +75,14 @@ export default function ImageCanvas() {
{
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['folder', project!.id.toString(), folderId] });
toast({
title: '저장 성공',
});
},
onError: () => {
alert('레이블 데이터 저장 실패');
toast({
title: '저장 실패',
});
},
}
);

View File

@ -5,12 +5,17 @@ import { Form, FormControl, FormField, FormItem, FormLabel, FormMessage } from '
import { Input } from '../ui/input';
import { Button } from '../ui/button';
import { RadioGroup, RadioGroupItem } from '../ui/radio-group';
import { useRef, useState } from 'react';
import { X } from 'lucide-react';
const formSchema = z.object({
projectName: z.string().max(50).min(1, {
message: '이름을 입력해주세요.',
}),
labelType: z.enum(['Classification', 'Detection', 'Segmentation']),
categories: z.array(z.string()).min(1, {
message: '카테고리를 하나 이상 입력해주세요.',
}),
});
export type ProjectCreateFormValues = z.infer<typeof formSchema>;
@ -21,16 +26,32 @@ const defaultValues: Partial<ProjectCreateFormValues> = {
};
export default function ProjectCreateForm({ onSubmit }: { onSubmit: (data: ProjectCreateFormValues) => void }) {
const [categories, setCategories] = useState<string[]>([]);
const form = useForm<ProjectCreateFormValues>({
resolver: zodResolver(formSchema),
defaultValues,
defaultValues: { ...defaultValues, categories },
});
const categoryRef = useRef<HTMLInputElement>(null);
const handleAddCategory = (event: React.MouseEvent<HTMLButtonElement>, onChange: (value: string[]) => void) => {
event.preventDefault();
const category = categoryRef.current?.value;
if (!category) return;
const newCategories = [...categories, category];
if (!categories.includes(category)) {
onChange(newCategories);
setCategories(newCategories);
}
categoryRef.current!.value = '';
};
return (
<Form {...form}>
<form
onSubmit={form.handleSubmit(onSubmit)}
className="flex flex-col gap-5"
className="flex flex-col gap-5 overflow-x-auto"
>
<FormField
name="projectName"
@ -80,6 +101,50 @@ export default function ProjectCreateForm({ onSubmit }: { onSubmit: (data: Proje
</FormItem>
)}
/>
<FormField
name="categories"
render={({ field }) => (
<>
<div className="body-strong"></div>
<div className="flex gap-2">
<FormControl>
<Input
ref={categoryRef}
placeholder="카테고리를 추가해주세요."
/>
</FormControl>
<Button
variant="outline"
onClick={(event) => handleAddCategory(event, field.onChange)}
>
</Button>
</div>
{categories.length > 0 && (
<ul className="body-small box-border flex grow-0 gap-2 overflow-x-auto">
{categories.map((category: string, index: number) => (
<div
key={index}
className="flex items-center gap-1 rounded-full border border-gray-700 px-2 py-1 text-gray-900"
>
<span>{category}</span>
<X
size={16}
className="cursor-pointer"
onClick={() => {
const newCategories = categories.filter((_, i) => i !== index);
field.onChange(newCategories);
setCategories(newCategories);
}}
/>
</div>
))}
</ul>
)}
<FormMessage />
</>
)}
/>
<Button
type="submit"
variant="outlinePrimary"

View File

@ -37,6 +37,7 @@ export default function ProjectCreateModal({ onSubmit, buttonClass = '' }: Proje
const formattedData: ProjectRequest = {
title: data.projectName,
projectType: data.labelType.toLowerCase() as ProjectRequest['projectType'],
categories: data.categories,
};
onSubmit(formattedData);
handleClose();

View File

@ -1,18 +1,15 @@
import * as React from 'react';
import WorkSpaceCreateForm, { WorkSpaceCreateFormValues } from './WorkSpaceCreateForm';
import { Dialog, DialogContent, DialogHeader, DialogTrigger } from '../ui/dialogCustom';
import { Plus } from 'lucide-react';
import { WorkspaceRequest } from '@/types';
import { useState } from 'react';
interface WorkSpaceCreateModalProps {
onSubmit: (data: WorkspaceRequest) => void;
}
export default function WorkSpaceCreateModal({ onSubmit }: WorkSpaceCreateModalProps) {
const [isOpen, setIsOpen] = React.useState(false);
const handleOpen = () => setIsOpen(true);
const handleClose = () => setIsOpen(false);
const [isOpen, setIsOpen] = useState(false);
const handleFormSubmit = (data: WorkSpaceCreateFormValues) => {
const formattedData: WorkspaceRequest = {
@ -20,7 +17,7 @@ export default function WorkSpaceCreateModal({ onSubmit }: WorkSpaceCreateModalP
content: data.workspaceDescription || '',
};
onSubmit(formattedData);
handleClose();
setIsOpen(false);
};
return (
@ -31,7 +28,7 @@ export default function WorkSpaceCreateModal({ onSubmit }: WorkSpaceCreateModalP
<DialogTrigger asChild>
<button
className="flex items-center justify-center p-2"
onClick={handleOpen}
onClick={() => setIsOpen(true)}
>
<Plus size={20} />
</button>

View File

@ -1,5 +1,5 @@
import { LABEL_CATEGORY } from '@/constants';
import useCanvasStore from '@/stores/useCanvasStore';
import useProjectStore from '@/stores/useProjectStore';
import { Label } from '@/types';
import { Trash2 } from 'lucide-react';
import { MouseEventHandler } from 'react';
@ -12,13 +12,12 @@ export default function LabelButton({
setSelectedLabelId,
}: Label & { selected: boolean; setSelectedLabelId: (id: number) => void }) {
const { labels, setLabels } = useCanvasStore();
const { categories } = useProjectStore();
const handleClick: MouseEventHandler = () => {
console.log(`LabelButton ${id} clicked`);
setSelectedLabelId(id);
};
const handleDelete: MouseEventHandler = (event) => {
event.stopPropagation();
console.log(`Delete LabelButton ${id}`);
setLabels(labels.filter((label) => label.id !== id));
};
@ -27,33 +26,33 @@ export default function LabelButton({
className={`flex items-center rounded-lg transition-colors ${selected ? 'bg-gray-200' : 'bg-gray-50 hover:bg-gray-100'}`}
>
<div
className="flex grow cursor-pointer items-center gap-2.5 p-2.5 text-left"
className="flex grow cursor-pointer items-center gap-2.5 p-2.5 pr-1 text-left"
onClick={handleClick}
>
<div
className="h-3 w-3 rounded-full"
style={{
backgroundColor: color,
}}
className="h-3 w-3 shrink-0 rounded-full"
style={{ backgroundColor: color }}
/>
<div className="flex">
<select
className="body-small w-[97.2px] cursor-pointer rounded bg-transparent"
className="body-small w-full cursor-pointer rounded bg-transparent"
value={categoryId.toString()}
onChange={(event) => {
const newCategoryId = Number(event.target.value);
setLabels(labels.map((label) => (label.id === id ? { ...label, categoryId: newCategoryId } : label)));
}}
>
{LABEL_CATEGORY.map((category, index) => (
{categories.map(({ id, labelName }) => (
<option
value={index.toString()}
key={index}
value={id.toString()}
key={id}
>
{category}
{labelName}
</option>
))}
</select>
</div>
</div>
<button
className="p-2.5"
onClick={handleDelete}

View File

@ -10,13 +10,21 @@ import WorkspaceDropdownMenu from '../WorkspaceDropdownMenu';
import useAutoLabelQuery from '@/queries/projects/useAutoLabelQuery';
import useProjectStore from '@/stores/useProjectStore';
import { useQueryClient } from '@tanstack/react-query';
import { useToast } from '@/hooks/use-toast';
import useProjectCategoriesQuery from '@/queries/category/useProjectCategoriesQuery';
export default function ProjectStructure({ project }: { project: Project }) {
const setProject = useProjectStore((state) => state.setProject);
const { setProject, setCategories } = useProjectStore();
const { data: categories } = useProjectCategoriesQuery(project.id);
const image = useCanvasStore((state) => state.image);
const { data: folderData, refetch } = useFolderQuery(project.id.toString(), 0);
const queryClient = useQueryClient();
const requestAutoLabel = useAutoLabelQuery();
const { toast } = useToast();
useEffect(() => {
setCategories(categories);
}, [categories, setCategories]);
useEffect(() => {
setProject(project);
@ -71,12 +79,15 @@ export default function ProjectStructure({ project }: { project: Project }) {
{
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['folder', project!.id.toString()] });
setTimeout(() => {
alert('레이블링 성공!');
}, 100);
queryClient.invalidateQueries({ queryKey: ['labelJson'] });
toast({
title: '레이블링 성공',
});
},
onError: () => {
alert('자동 레이블링을 요청하는 중 오류가 발생했습니다.');
toast({
title: '레이블링 중 오류가 발생했습니다.',
});
},
}
);

View File

@ -0,0 +1,105 @@
import * as React from 'react';
import * as ToastPrimitives from '@radix-ui/react-toast';
import { cva, type VariantProps } from 'class-variance-authority';
import { cn } from '@/lib/utils';
const ToastProvider = ToastPrimitives.Provider;
const ToastViewport = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Viewport>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Viewport>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Viewport
ref={ref}
className={cn(
'fixed left-1/2 top-16 z-[100] flex max-h-screen -translate-x-1/2 flex-col-reverse items-center justify-center p-4',
className
)}
{...props}
/>
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;
const toastVariants = cva(
'group pointer-events-auto relative flex items-center justify-between space-x-4 overflow-hidden rounded-md border border-gray-200 px-5 py-3 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out data-[state=closed]:zoom-out-110 data-[state=open]:slide-in-from-top-5 data-[state=open]:fade-in dark:border-gray-800 rounded-full ease-out data-[state=open]:duration-300',
{
variants: {
variant: {
default: 'border bg-white text-gray-950 dark:bg-gray-950 dark:text-gray-50',
destructive:
'destructive group border-red-500 bg-red-500 text-gray-50 dark:border-red-900 dark:bg-red-900 dark:text-gray-50',
},
},
defaultVariants: {
variant: 'default',
},
}
);
const Toast = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Root>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> & VariantProps<typeof toastVariants>
>(({ className, variant, ...props }, ref) => {
return (
<ToastPrimitives.Root
ref={ref}
className={cn(toastVariants({ variant }), className)}
{...props}
/>
);
});
Toast.displayName = ToastPrimitives.Root.displayName;
const ToastAction = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Action>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Action>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Action
ref={ref}
className={cn(
'inline-flex h-8 shrink-0 items-center justify-center rounded-md border border-gray-200 bg-transparent px-3 text-sm font-medium ring-offset-white transition-colors hover:bg-gray-100 focus:outline-none focus:ring-2 focus:ring-gray-950 focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-gray-100/40 group-[.destructive]:hover:border-red-500/30 group-[.destructive]:hover:bg-red-500 group-[.destructive]:hover:text-gray-50 group-[.destructive]:focus:ring-red-500 dark:border-gray-800 dark:ring-offset-gray-950 dark:hover:bg-gray-800 dark:focus:ring-gray-300 dark:group-[.destructive]:border-gray-800/40 dark:group-[.destructive]:hover:border-red-900/30 dark:group-[.destructive]:hover:bg-red-900 dark:group-[.destructive]:hover:text-gray-50 dark:group-[.destructive]:focus:ring-red-900',
className
)}
{...props}
/>
));
ToastAction.displayName = ToastPrimitives.Action.displayName;
const ToastTitle = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Title>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Title>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Title
ref={ref}
className={cn('text-sm font-semibold', className)}
{...props}
/>
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;
const ToastDescription = React.forwardRef<
React.ElementRef<typeof ToastPrimitives.Description>,
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Description>
>(({ className, ...props }, ref) => (
<ToastPrimitives.Description
ref={ref}
className={cn('text-sm opacity-90', className)}
{...props}
/>
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;
type ToastProps = React.ComponentPropsWithoutRef<typeof Toast>;
type ToastActionElement = React.ReactElement<typeof ToastAction>;
export {
type ToastProps,
type ToastActionElement,
ToastProvider,
ToastViewport,
Toast,
ToastTitle,
ToastDescription,
ToastAction,
};

View File

@ -0,0 +1,26 @@
import { useToast } from '@/hooks/use-toast';
import { Toast, ToastDescription, ToastProvider, ToastTitle, ToastViewport } from '@/components/ui/toast';
export function Toaster() {
const { toasts } = useToast();
return (
<ToastProvider>
{toasts.map(function ({ id, title, description, action, ...props }) {
return (
<Toast
key={id}
{...props}
>
<div className="grid gap-1">
{title && <ToastTitle>{title}</ToastTitle>}
{description && <ToastDescription>{description}</ToastDescription>}
</div>
{action}
</Toast>
);
})}
<ToastViewport />
</ToastProvider>
);
}

View File

@ -0,0 +1,191 @@
import * as React from "react"
import type {
ToastActionElement,
ToastProps,
} from "@/components/ui/toast"
const TOAST_LIMIT = 1
const TOAST_REMOVE_DELAY = 1000000
type ToasterToast = ToastProps & {
id: string
title?: React.ReactNode
description?: React.ReactNode
action?: ToastActionElement
}
const actionTypes = {
ADD_TOAST: "ADD_TOAST",
UPDATE_TOAST: "UPDATE_TOAST",
DISMISS_TOAST: "DISMISS_TOAST",
REMOVE_TOAST: "REMOVE_TOAST",
} as const
let count = 0
function genId() {
count = (count + 1) % Number.MAX_SAFE_INTEGER
return count.toString()
}
type ActionType = typeof actionTypes
type Action =
| {
type: ActionType["ADD_TOAST"]
toast: ToasterToast
}
| {
type: ActionType["UPDATE_TOAST"]
toast: Partial<ToasterToast>
}
| {
type: ActionType["DISMISS_TOAST"]
toastId?: ToasterToast["id"]
}
| {
type: ActionType["REMOVE_TOAST"]
toastId?: ToasterToast["id"]
}
interface State {
toasts: ToasterToast[]
}
const toastTimeouts = new Map<string, ReturnType<typeof setTimeout>>()
const addToRemoveQueue = (toastId: string) => {
if (toastTimeouts.has(toastId)) {
return
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId)
dispatch({
type: "REMOVE_TOAST",
toastId: toastId,
})
}, TOAST_REMOVE_DELAY)
toastTimeouts.set(toastId, timeout)
}
export const reducer = (state: State, action: Action): State => {
switch (action.type) {
case "ADD_TOAST":
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
}
case "UPDATE_TOAST":
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
}
case "DISMISS_TOAST": {
const { toastId } = action
// ! Side effects ! - This could be extracted into a dismissToast() action,
// but I'll keep it here for simplicity
if (toastId) {
addToRemoveQueue(toastId)
} else {
state.toasts.forEach((toast) => {
addToRemoveQueue(toast.id)
})
}
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
open: false,
}
: t
),
}
}
case "REMOVE_TOAST":
if (action.toastId === undefined) {
return {
...state,
toasts: [],
}
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
}
}
}
const listeners: Array<(state: State) => void> = []
let memoryState: State = { toasts: [] }
function dispatch(action: Action) {
memoryState = reducer(memoryState, action)
listeners.forEach((listener) => {
listener(memoryState)
})
}
type Toast = Omit<ToasterToast, "id">
function toast({ ...props }: Toast) {
const id = genId()
const update = (props: ToasterToast) =>
dispatch({
type: "UPDATE_TOAST",
toast: { ...props, id },
})
const dismiss = () => dispatch({ type: "DISMISS_TOAST", toastId: id })
dispatch({
type: "ADD_TOAST",
toast: {
...props,
id,
open: true,
onOpenChange: (open) => {
if (!open) dismiss()
},
},
})
return {
id: id,
dismiss,
update,
}
}
function useToast() {
const [state, setState] = React.useState<State>(memoryState)
React.useEffect(() => {
listeners.push(setState)
return () => {
const index = listeners.indexOf(setState)
if (index > -1) {
listeners.splice(index, 1)
}
}
}, [state])
return {
...state,
toast,
dismiss: (toastId?: string) => dispatch({ type: "DISMISS_TOAST", toastId }),
}
}
export { useToast, toast }

View File

@ -49,7 +49,7 @@ const router = createBrowserRouter([
{
path: webPath.browse(),
element: (
<Suspense fallback={<PageLayout />}>
<Suspense fallback={<div></div>}>
<WorkspaceBrowseLayout />
</Suspense>
),

View File

@ -11,7 +11,7 @@ interface AuthState {
}
const useAuthStore = create<AuthState>()(
persist(
persist<AuthState>(
(set) => ({
accessToken: '',
profile: null,

View File

@ -1,11 +1,13 @@
import { create } from 'zustand';
import { Project } from '@/types';
import { LabelCategoryResponse, Project } from '@/types';
interface ProjectState {
project: Project | null;
setProject: (project: Project | null) => void;
folderId: number;
setFolderId: (folderId: number) => void;
categories: LabelCategoryResponse[];
setCategories: (categories: LabelCategoryResponse[]) => void;
}
const useProjectStore = create<ProjectState>((set) => ({
@ -13,6 +15,8 @@ const useProjectStore = create<ProjectState>((set) => ({
setProject: (project) => set({ project }),
folderId: 0,
setFolderId: (folderId) => set({ folderId }),
categories: [],
setCategories: (categories) => set({ categories }),
}));
export default useProjectStore;

View File

@ -122,6 +122,7 @@ export interface WorkspaceListResponse {
export interface ProjectRequest {
title: string;
projectType: 'classification' | 'detection' | 'segmentation';
categories: string[];
}
export type ProjectResponse = {
@ -281,7 +282,7 @@ export interface ImageFolderRequest {
}
export interface LabelCategoryResponse {
id: number;
name: string;
labelName: string;
}
// 카테고리 요청 DTO
export interface LabelCategoryRequest {