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