UNPKG

@saran-ign/video-annotation-tool

Version:

[![npm version](https://img.shields.io/npm/v/@saran-ign/video-annotation-tool.svg)](https://www.npmjs.com/package/@saran-ign/video-annotation-tool) [![npm downloads](https://img.shields.io/npm/dm/@saran-ign/video-annotation-tool.svg)](https://www.npmjs.co

69 lines (68 loc) 2.64 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, useCallback, useContext, useState } from "react"; const CanvasContext = createContext(undefined); export const CanvasProvider = ({ children, shapes, setShapes }) => { // GENERAL STATES const [isDrawing, setIsDrawing] = useState(false); const [newShape, setNewShape] = useState(null); const [selectedShapeId, setSelectedShapeId] = useState(null); const [rectPosititon, setRectPosition] = useState({ x: null, y: null }); const [videoRefVal, setVideoRefVal] = useState(null); const [dimensions, setDimensions] = useState({ width: 500, height: 300, }); // STACK STATES const [history, setHistory] = useState([]); const [redoStack, setRedoStack] = useState([]); /** * Handle UNDO. */ const undo = useCallback(() => { if (history.length > 0) { const lastState = history[history.length - 1]; setRedoStack((prevRedoStack) => [shapes, ...prevRedoStack]); setShapes(lastState); setHistory((prevHistory) => prevHistory.slice(0, -1)); } }, [history, shapes, setShapes]); /** * Handle REDO. */ const redo = useCallback(() => { if (redoStack.length > 0) { const nextState = redoStack[0]; setHistory((prevHistory) => [...prevHistory, shapes]); setShapes(nextState); setRedoStack((prevRedoStack) => prevRedoStack.slice(1)); } }, [redoStack, shapes, setShapes]); /** * Handle shape deletion by filtering out the shape with the given ID. */ const deleteShape = useCallback(() => { setHistory((prevHistory) => [...prevHistory, shapes]); setRedoStack([]); setShapes((prevShapes) => prevShapes.filter((shape) => shape.id !== selectedShapeId)); setSelectedShapeId(null); }, [selectedShapeId, shapes, setShapes]); return (_jsx(CanvasContext.Provider, { value: { shapes, setShapes, isDrawing, setIsDrawing, newShape, setNewShape, selectedShapeId, setSelectedShapeId, rectPosititon, setRectPosition, videoRefVal, setVideoRefVal, dimensions, setDimensions, history, setHistory, redoStack, setRedoStack, deleteShape, undo, redo }, children: children })); }; export const useCanvas = () => { const context = useContext(CanvasContext); if (context === undefined) { throw new Error('useCanvas must be used within a CanvasProvider'); } return context; };