guide line and magnet

This commit is contained in:
hamid zarghami
2026-04-26 10:50:22 +03:30
parent e2b7e964cd
commit 4feccbf1f9
5 changed files with 335 additions and 17 deletions
+206 -3
View File
@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import { Stage, Layer, Rect } from "react-konva";
import Konva from "konva";
import { useEditorStore } from "../store/editorStore";
@@ -10,6 +10,8 @@ import { useTransformHandlers } from "./canvas/useTransformHandlers";
import { useObjectHandlers } from "./canvas/useObjectHandlers";
import { useMaskGroupState } from "./canvas/useMaskGroupState";
import ObjectsLayer from "./canvas/ObjectsLayer";
import GuidesLayer from "./canvas/GuidesLayer";
import { getSnappedPosition, type Guide } from "./canvas/useSnap";
import CellEditor from "@/components/CellEditor";
import ZoomControls from "./ZoomControls";
@@ -20,6 +22,8 @@ type EditorCanvasProps = {
const EditorCanvas = ({ catalogSize }: EditorCanvasProps) => {
const stageRef = useRef<Konva.Stage>(null);
const layerRef = useRef<Konva.Layer>(null);
const activeGuideIdsRef = useRef<string[]>([]);
const stageWrapRef = useRef<HTMLDivElement>(null);
const {
tool,
@@ -45,6 +49,14 @@ const EditorCanvas = ({ catalogSize }: EditorCanvasProps) => {
useTransformHandlers(transformerRef, layerRef);
const [guides, setGuides] = useState<Guide[]>([]);
const [activeGuideIds, setActiveGuideIds] = useState<string[]>([]);
const [selectedGuideId, setSelectedGuideId] = useState<string | null>(null);
const [draftGuide, setDraftGuide] = useState<{
orientation: Guide["orientation"];
position: number;
} | null>(null);
useEffect(() => {
if (stageRef.current) {
setStageRef(stageRef);
@@ -56,19 +68,198 @@ const EditorCanvas = ({ catalogSize }: EditorCanvasProps) => {
const finalScale = stageSize.scale * zoom;
const updateActiveGuides = (nextActiveGuideIds: string[]) => {
const prev = activeGuideIdsRef.current;
const changed =
prev.length !== nextActiveGuideIds.length ||
prev.some((id, index) => id !== nextActiveGuideIds[index]);
if (changed) {
activeGuideIdsRef.current = nextActiveGuideIds;
setActiveGuideIds(nextActiveGuideIds);
}
};
const handleGuidePositionChange = (id: string, position: number) => {
setGuides((prev) =>
prev.map((guide) =>
guide.id === id
? {
...guide,
position,
}
: guide,
),
);
};
const addGuide = (orientation: Guide["orientation"], position: number) => {
const id = `guide-${orientation}-${crypto.randomUUID()}`;
setGuides((prev) => [...prev, { id, orientation, position }]);
setSelectedGuideId(id);
};
const removeGuide = (id: string) => {
setGuides((prev) => prev.filter((guide) => guide.id !== id));
setActiveGuideIds((prev) => prev.filter((activeId) => activeId !== id));
setSelectedGuideId((prev) => (prev === id ? null : prev));
};
const handleGuideDragEnd = (id: string, position: number, shouldRemove: boolean) => {
if (shouldRemove) {
removeGuide(id);
return;
}
handleGuidePositionChange(id, position);
};
useEffect(() => {
const handleDeleteGuide = (e: KeyboardEvent) => {
if (!selectedGuideId) return;
const target = e.target as HTMLElement;
if (
target?.tagName === "INPUT" ||
target?.tagName === "TEXTAREA" ||
target?.isContentEditable
) {
return;
}
if (e.key === "Delete" || e.key === "Backspace") {
e.preventDefault();
removeGuide(selectedGuideId);
}
};
window.addEventListener("keydown", handleDeleteGuide);
return () => {
window.removeEventListener("keydown", handleDeleteGuide);
};
}, [selectedGuideId]);
const startRulerGuideDrag = (orientation: Guide["orientation"]) => {
const updateFromPointer = (event: MouseEvent) => {
const rect = stageWrapRef.current?.getBoundingClientRect();
if (!rect) return null;
const rawPos =
orientation === "vertical"
? (event.clientX - rect.left) / finalScale
: (event.clientY - rect.top) / finalScale;
return rawPos;
};
const updateDraft = (event: MouseEvent) => {
const pointerPos = updateFromPointer(event);
if (pointerPos === null) return;
const boundedPos =
orientation === "vertical"
? Math.max(0, Math.min(stageSize.width, pointerPos))
: Math.max(0, Math.min(stageSize.height, pointerPos));
setDraftGuide({ orientation, position: boundedPos });
};
const handleMouseMove = (event: MouseEvent) => {
updateDraft(event);
};
const handleMouseUp = (event: MouseEvent) => {
const rect = stageWrapRef.current?.getBoundingClientRect();
if (!rect) {
setDraftGuide(null);
return;
}
const isInside =
event.clientX >= rect.left &&
event.clientX <= rect.right &&
event.clientY >= rect.top &&
event.clientY <= rect.bottom;
if (isInside) {
const pointerPos = updateFromPointer(event);
if (pointerPos !== null) {
const boundedPos = orientation === "vertical"
? Math.max(0, Math.min(stageSize.width, pointerPos))
: Math.max(0, Math.min(stageSize.height, pointerPos));
addGuide(orientation, boundedPos);
}
}
setDraftGuide(null);
window.removeEventListener("mousemove", handleMouseMove);
window.removeEventListener("mouseup", handleMouseUp);
};
window.addEventListener("mousemove", handleMouseMove);
window.addEventListener("mouseup", handleMouseUp, { once: true });
};
const handleDragMove = (e: Konva.KonvaEventObject<DragEvent>) => {
const node = e.target;
if (!node || node.name() === "guide-line") return;
const snapped = getSnappedPosition({ x: node.x(), y: node.y() }, guides);
if (node.x() !== snapped.position.x || node.y() !== snapped.position.y) {
node.position(snapped.position);
node.getLayer()?.batchDraw();
}
updateActiveGuides(snapped.activeGuideIds);
};
const handleDragEnd = () => {
updateActiveGuides([]);
};
const handleStageMouseDownWithGuideReset = (e: Konva.KonvaEventObject<MouseEvent>) => {
if (e.target?.name() !== "guide-line") {
setSelectedGuideId(null);
}
handleStageMouseDown(e);
};
return (
<div className="flex-1 flex items-center justify-center pb-8 overflow-auto relative">
<div className="shadow-lg mt-8">
<div className="mt-8">
<div
className="relative select-none"
style={{
width: stageSize.width * finalScale,
height: stageSize.height * finalScale,
}}
>
<div
className="absolute -top-6 left-0 h-6 bg-slate-100 border-b border-slate-300 cursor-col-resize"
style={{ width: stageSize.width * finalScale }}
onMouseDown={(e) => {
e.preventDefault();
startRulerGuideDrag("vertical");
}}
title="Drag to create vertical guide"
/>
<div
className="absolute top-0 -left-6 w-6 bg-slate-100 border-r border-slate-300 cursor-row-resize"
style={{ height: stageSize.height * finalScale }}
onMouseDown={(e) => {
e.preventDefault();
startRulerGuideDrag("horizontal");
}}
title="Drag to create horizontal guide"
/>
<div className="absolute -top-6 -left-6 w-6 h-6 bg-slate-200 border border-slate-300" />
<div ref={stageWrapRef} className="shadow-lg">
<Stage
ref={stageRef}
width={stageSize.width * finalScale}
height={stageSize.height * finalScale}
scaleX={finalScale}
scaleY={finalScale}
onMouseDown={handleStageMouseDown}
onMouseDown={handleStageMouseDownWithGuideReset}
onMouseMove={handleStageMouseMove}
onMouseUp={handleStageMouseUp}
onDragMove={handleDragMove}
onDragEnd={handleDragEnd}
>
<Layer listening={false}>
<Rect
@@ -100,7 +291,19 @@ const EditorCanvas = ({ catalogSize }: EditorCanvasProps) => {
onGroup={handleGroupWithMask}
onUngroup={handleUngroupFromMask}
/>
<GuidesLayer
guides={guides}
stageWidth={stageSize.width}
stageHeight={stageSize.height}
activeGuideIds={activeGuideIds}
selectedGuideId={selectedGuideId}
draftGuide={draftGuide}
onGuideSelect={setSelectedGuideId}
onGuideDragEnd={handleGuideDragEnd}
/>
</Stage>
</div>
</div>
</div>
{editingCell && (
<CellEditor