add konva js to project + create some components with ai

This commit is contained in:
hamid zarghami
2025-11-16 16:33:54 +03:30
parent c1c6b0ebf7
commit 1a0c869101
38 changed files with 1855 additions and 42 deletions
@@ -0,0 +1,97 @@
import { useState, useRef, useEffect } from "react";
import Konva from "konva";
import { useEditorStore, type EditorObject } from "../../store/editorStore";
import { createDrawingObject } from "./drawingUtils";
export const useDrawingHandlers = () => {
const [isDrawing, setIsDrawing] = useState(false);
const [startPos, setStartPos] = useState({ x: 0, y: 0 });
const [tempObject, setTempObject] = useState<EditorObject | null>(null);
const transformerRef = useRef<Konva.Transformer>(null);
const { tool, addObject, updateObject, setSelectedObjectId } = useEditorStore();
useEffect(() => {
setTempObject(null);
setIsDrawing(false);
}, [tool]);
const handleStageMouseDown = (e: Konva.KonvaEventObject<MouseEvent>) => {
const stage = e.target.getStage();
if (!stage) return;
const pointerPos = stage.getPointerPosition();
if (!pointerPos) return;
if (tool === "select") {
const clickedOnEmpty = e.target === stage;
if (clickedOnEmpty) {
setSelectedObjectId(null);
if (transformerRef.current) {
transformerRef.current.nodes([]);
}
}
return;
}
setIsDrawing(true);
setStartPos(pointerPos);
if (tool === "text") {
const newText: EditorObject = {
id: `text-${Date.now()}`,
type: "text",
x: pointerPos.x,
y: pointerPos.y,
text: "متن جدید",
fontSize: 24,
fill: "#000000",
};
addObject(newText);
setSelectedObjectId(newText.id);
}
};
const handleStageMouseMove = (e: Konva.KonvaEventObject<MouseEvent>) => {
if (!isDrawing || tool === "select" || tool === "text") return;
const stage = e.target.getStage();
if (!stage) return;
const pointerPos = stage.getPointerPosition();
if (!pointerPos) return;
const newObject = createDrawingObject({ tool, startPos, pointerPos, tempObject });
if (!newObject) return;
if (!tempObject) {
addObject(newObject);
setTempObject(newObject);
} else {
const updates: Partial<EditorObject> =
tool === "circle"
? { width: newObject.width, height: newObject.height }
: {
x: newObject.x,
y: newObject.y,
width: newObject.width,
height: newObject.height,
};
updateObject(tempObject.id, updates);
}
};
const handleStageMouseUp = () => {
setIsDrawing(false);
setTempObject(null);
};
return {
isDrawing,
transformerRef,
handleStageMouseDown,
handleStageMouseMove,
handleStageMouseUp,
};
};