| 10 | import { getPointerPositionRelativeToStage } from "./getPointerPosition"; |
| 11 | |
| 12 | export function useFreeDrawingTool() { |
| 13 | const tool = useStateStore((state) => state.selectedTool); |
| 14 | |
| 15 | const penProperties = useToolPropertiesStore( |
| 16 | (state) => state.properties.pen ?? defaultPenProperties |
| 17 | ); |
| 18 | const eraserProperties = useToolPropertiesStore( |
| 19 | (state) => state.properties.eraser ?? defaultEraserProperties |
| 20 | ); |
| 21 | |
| 22 | const lines = useHistoryStore((state) => state.current.freeDrawingLines); |
| 23 | const addLine = useHistoryStore((state) => state.addFreeDrawingLine); |
| 24 | const updateLastLine = useHistoryStore( |
| 25 | (state) => state.updateLastFreeDrawingLine |
| 26 | ); |
| 27 | const saveToHistory = useHistoryStore((state) => state.saveToHistory); |
| 28 | |
| 29 | const isDrawing = useRef(false); |
| 30 | |
| 31 | const handlePointerDown = (e: KonvaEventObject<MouseEvent | TouchEvent>) => { |
| 32 | if (tool !== "pen" && tool !== "eraser") return; |
| 33 | |
| 34 | // Save current state before starting new drawing |
| 35 | saveToHistory(); |
| 36 | |
| 37 | isDrawing.current = true; |
| 38 | const stage = e.target.getStage(); |
| 39 | const pos = stage ? getPointerPositionRelativeToStage(stage) : null; |
| 40 | |
| 41 | if (!pos) return; |
| 42 | const lineProps = |
| 43 | tool === "pen" |
| 44 | ? { |
| 45 | stroke: penProperties.stroke, |
| 46 | strokeWidth: penProperties.strokeWidth, |
| 47 | opacity: penProperties.opacity, |
| 48 | } |
| 49 | : { |
| 50 | strokeWidth: eraserProperties.strokeWidth, |
| 51 | opacity: eraserProperties.opacity, |
| 52 | }; |
| 53 | |
| 54 | addLine({ |
| 55 | id: createShapeId(), |
| 56 | tool, |
| 57 | points: [pos.x, pos.y], |
| 58 | ...lineProps, |
| 59 | }); |
| 60 | }; |
| 61 | |
| 62 | const handlePointerUp = () => { |
| 63 | isDrawing.current = false; |
| 64 | }; |
| 65 | |
| 66 | const handlePointerMove = (e: KonvaEventObject<MouseEvent | TouchEvent>) => { |
| 67 | if (tool !== "pen" && tool !== "eraser") return; |
| 68 | |
| 69 | if (!isDrawing.current) return; |