Untitled

Anonymous
Plain Text
09/09/2025 12:31 PM
27.0 KB
18
Indexable
Never
import React, { useState, useRef, useCallback, useEffect } from "react";
import {
  CanvasObject,
  RectangleObject,
  CircleObject,
  TextObject,
  StickyObject,
  PathObject,
  LineObject,
  TableObject,
  ToolType,
  ShapeType,
  LineType,
  Point,
  CanvasState,
} from "@/types/canvas";
import { CanvasObjectComponent } from "./CanvasObject";
import { Toolbar } from "./Toolbar";
import { Navbar } from "./Navbar";
import { ZoomToolbar } from "./ZoomToolbar";
import { AccessibilityInstructions } from "./AccessibilityInstructions";
import { TextFormattingToolbar } from "./TextFormattingToolbar";

// Screen-based coordinate system: 1 SVG unit = 1 screen pixel at 100% zoom
const getInitialViewBox = () => {
  const width = typeof window !== "undefined" ? window.innerWidth : 1920;
  const height =
    typeof window !== "undefined" ? window.innerHeight - 104 : 1080; // Account for navbar/toolbar
  return { x: 0, y: 0, width, height };
};

const INITIAL_STATE: CanvasState = {
  objects: [],
  selectedObjectIds: [],
  viewBox: getInitialViewBox(),
  zoom: 1,
  tool: "select",
  currentShape: "rectangle",
  currentLineType: "line",
  currentColor: "#8B5CF6",
  currentStickyColor: "yellow",
  isDrawing: false,
  currentPath: undefined,
  isPanning: false,
  lastPanPoint: undefined,
};

export function Canvas() {
  const [state, setState] = useState<CanvasState>(INITIAL_STATE);
  const [isTextEditing, setIsTextEditing] = useState(false);
  const [history, setHistory] = useState<CanvasState[]>([INITIAL_STATE]);
  const [historyIndex, setHistoryIndex] = useState(0);
  const [isDrawingLine, setIsDrawingLine] = useState(false);
  const [lineStartPoint, setLineStartPoint] = useState<Point | null>(null);
  const [currentMousePos, setCurrentMousePos] = useState<Point | null>(null);
  const svgRef = useRef<SVGSVGElement>(null);

  const updateState = useCallback((updates: Partial<CanvasState>) => {
    setState((prev) => ({ ...prev, ...updates }));
  }, []);

  const saveToHistory = useCallback(
    (newState: CanvasState) => {
      setHistory((prev) => {
        // Remove any history after current index (when we're not at the latest state)
        const newHistory = prev.slice(0, historyIndex + 1);
        // Add the new state
        newHistory.push(newState);
        // Limit history to 50 states to prevent memory issues
        if (newHistory.length > 50) {
          newHistory.shift();
          setHistoryIndex((prevIndex) => Math.max(0, prevIndex));
          return newHistory;
        }
        setHistoryIndex(newHistory.length - 1);
        return newHistory;
      });
    },
    [historyIndex]
  );

  const updateStateWithHistory = useCallback(
    (updates: Partial<CanvasState>) => {
      setState((prev) => {
        const newState = { ...prev, ...updates };
        // Only save to history if objects or selectedObjectIds changed
        if (
          updates.objects !== undefined ||
          updates.selectedObjectIds !== undefined
        ) {
          saveToHistory(newState);
        }
        return newState;
      });
    },
    [saveToHistory]
  );

  const undo = useCallback(() => {
    if (historyIndex > 0) {
      const newIndex = historyIndex - 1;
      const previousState = history[newIndex];
      setHistoryIndex(newIndex);
      setState(previousState);
    }
  }, [history, historyIndex]);

  const redo = useCallback(() => {
    if (historyIndex < history.length - 1) {
      const newIndex = historyIndex + 1;
      const nextState = history[newIndex];
      setHistoryIndex(newIndex);
      setState(nextState);
    }
  }, [history, historyIndex]);

  const addObject = useCallback(
    (objectData: any) => {
      const newObject = {
        ...objectData,
        id: `obj-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
      } as CanvasObject;

      updateStateWithHistory({
        objects: [...state.objects, newObject],
        selectedObjectIds: [newObject.id],
      });

      return newObject.id;
    },
    [state.objects, updateStateWithHistory]
  );

  const updateObject = useCallback(
    (id: string, updates: any) => {
      updateStateWithHistory({
        objects: state.objects.map((obj) =>
          obj.id === id ? ({ ...obj, ...updates } as CanvasObject) : obj
        ),
      });
    },
    [state.objects, updateStateWithHistory]
  );

  const deleteSelectedObjects = useCallback(() => {
    updateStateWithHistory({
      objects: state.objects.filter(
        (obj) => !state.selectedObjectIds.includes(obj.id)
      ),
      selectedObjectIds: [],
    });
  }, [state.objects, state.selectedObjectIds, updateStateWithHistory]);

  const deleteObject = useCallback(
    (id: string) => {
      updateStateWithHistory({
        objects: state.objects.filter((obj) => obj.id !== id),
        selectedObjectIds: state.selectedObjectIds.filter(
          (objId) => objId !== id
        ),
      });
    },
    [state.objects, state.selectedObjectIds, updateStateWithHistory]
  );

  const selectObject = useCallback(
    (id: string) => {
      updateStateWithHistory({
        selectedObjectIds: [id],
      });
    },
    [updateStateWithHistory]
  );

  const moveObject = useCallback(
    (id: string, newPosition: Point) => {
      const object = state.objects.find((obj) => obj.id === id);
      if (!object) return;

      if (object.type === "line") {
        // For lines, calculate the delta and move both start and end points
        const deltaX = newPosition.x - object.position.x;
        const deltaY = newPosition.y - object.position.y;

        updateObject(id, {
          position: newPosition,
          startPoint: {
            x: object.startPoint.x + deltaX,
            y: object.startPoint.y + deltaY,
          },
          endPoint: {
            x: object.endPoint.x + deltaX,
            y: object.endPoint.y + deltaY,
          },
        });
      } else {
        updateObject(id, { position: newPosition });
      }
    },
    [updateObject, state.objects]
  );

  const editObjectText = useCallback(
    (id: string, newText: string) => {
      updateStateWithHistory({
        objects: state.objects.map((obj) => {
          if (obj.id === id) {
            if (obj.type === "text" || obj.type === "sticky") {
              return { ...obj, text: newText } as CanvasObject;
            } else if (obj.type === "table") {
              // Handle table cell updates
              try {
                const cellUpdate = JSON.parse(newText);
                const newCellData = [...obj.cellData];
                newCellData[cellUpdate.rowIndex][cellUpdate.colIndex] =
                  cellUpdate.text;
                return { ...obj, cellData: newCellData } as CanvasObject;
              } catch {
                // If parsing fails, treat as regular text update (shouldn't happen)
                return obj;
              }
            }
          }
          return obj;
        }),
      });
    },
    [state.objects, updateStateWithHistory]
  );

  const updateTextStyle = useCallback(
    (style: "h1" | "h2" | "h3" | "h4" | "paragraph") => {
      const selectedTextObjects = state.objects.filter(
        (obj): obj is TextObject =>
          obj.type === "text" && state.selectedObjectIds.includes(obj.id)
      );

      if (selectedTextObjects.length === 0) return;

      const count = selectedTextObjects.length;
      const semanticLabel = style === "h1" ? "heading level 1" 
        : style === "h2" ? "heading level 2"
        : style === "h3" ? "heading level 3" 
        : style === "h4" ? "heading level 4"
        : "normal paragraph";
      
      // VoiceOver-optimized announcement with assertive priority
      const announcement = count === 1 
        ? `Text converted to ${semanticLabel}`
        : `${count} text objects converted to ${semanticLabel}`;
      
      // Create temporary element for VoiceOver announcement
      const announcer = document.createElement("div");
      announcer.setAttribute("aria-live", "assertive");
      announcer.setAttribute("aria-atomic", "true");
      announcer.setAttribute("role", "status");
      announcer.style.position = "absolute";
      announcer.style.left = "-10000px";
      announcer.style.width = "1px";
      announcer.style.height = "1px";
      announcer.style.overflow = "hidden";
      document.body.appendChild(announcer);
      
      // Immediate announcement for VoiceOver
      setTimeout(() => {
        announcer.textContent = announcement;
        // Keep announcer for longer to ensure VoiceOver reads it
        setTimeout(() => {
          if (document.body.contains(announcer)) {
            document.body.removeChild(announcer);
          }
        }, 2000);
      }, 50);

      updateStateWithHistory({
        objects: state.objects.map((obj) => {
          if (obj.type === "text" && state.selectedObjectIds.includes(obj.id)) {
            const fontSize = style === "h1" ? 32 
              : style === "h2" ? 28
              : style === "h3" ? 24
              : style === "h4" ? 20
              : 16;
            return {
              ...obj,
              semanticRole: style,
              fontSize,
            } as TextObject;
          }
          return obj;
        }),
      });
    },
    [state.objects, state.selectedObjectIds, updateStateWithHistory]
  );

  // Get current text style for selected objects
  const getSelectedTextStyle = useCallback((): "h1" | "h2" | "h3" | "h4" | "paragraph" => {
    const selectedTextObjects = state.objects.filter(
      (obj): obj is TextObject =>
        obj.type === "text" && state.selectedObjectIds.includes(obj.id)
    );

    if (selectedTextObjects.length === 0) return "paragraph";
    
    // If all selected text objects have the same semantic role, return that
    const firstStyle = selectedTextObjects[0].semanticRole || "paragraph";
    const allSameStyle = selectedTextObjects.every(
      (obj) => (obj.semanticRole || "paragraph") === firstStyle
    );
    
    return allSameStyle ? firstStyle : "paragraph";
  }, [state.objects, state.selectedObjectIds]);

  const hasSelectedTextObjects = useCallback((): boolean => {
    return state.objects.some(
      (obj) => obj.type === "text" && state.selectedObjectIds.includes(obj.id)
    );
  }, [state.objects, state.selectedObjectIds]);

  // Get position for text formatting toolbar - KORRIGIERT
  const getTextToolbarPosition = useCallback((): { x: number; y: number } | null => {
    const selectedTextObjects = state.objects.filter(
      (obj): obj is TextObject =>
        obj.type === "text" && state.selectedObjectIds.includes(obj.id)
    );

    if (selectedTextObjects.length === 0 || !svgRef.current) return null;

    // Use the first selected text object's position
    const textObj = selectedTextObjects[0];
    const svgRect = svgRef.current.getBoundingClientRect();
    
    // Calculate CENTER of text object in SVG coordinates (not top-left corner)
    const textCenterX = textObj.position.x + (textObj.width || 200) / 2;
    const textTopY = textObj.position.y;
    
    // Convert SVG coordinates to screen coordinates
    const screenCenterX = ((textCenterX - state.viewBox.x) / state.viewBox.width) * svgRect.width + svgRect.left;
    const screenY = ((textTopY - state.viewBox.y) / state.viewBox.height) * svgRect.height + svgRect.top;

    // Toolbar dimensions
    const toolbarWidth = 600; // estimated toolbar width
    const toolbarHeight = 50; // estimated toolbar height
    
    // Center toolbar horizontally on text center (no need to subtract half width here since transform will center it)
    let adjustedX = screenCenterX;
    let adjustedY = screenY - toolbarHeight - 10; // Position above text with margin

    // Keep toolbar within screen bounds
    adjustedX = Math.max(toolbarWidth / 2 + 10, Math.min(adjustedX, window.innerWidth - toolbarWidth / 2 - 10));
    adjustedY = Math.max(10, adjustedY);

    return { x: adjustedX, y: adjustedY };
  }, [state.objects, state.selectedObjectIds, state.viewBox]);

  const getMousePosition = useCallback(
    (e: React.MouseEvent): Point => {
      if (!svgRef.current) return { x: 0, y: 0 };

      const rect = svgRef.current.getBoundingClientRect();
      const x =
        ((e.clientX - rect.left) / rect.width) * state.viewBox.width +
        state.viewBox.x;
      const y =
        ((e.clientY - rect.top) / rect.height) * state.viewBox.height +
        state.viewBox.y;

      return { x, y };
    },
    [state.viewBox]
  );

  const handleCanvasClick = useCallback(
    (e: React.MouseEvent) => {
      const position = getMousePosition(e);

      switch (state.tool) {
        case "shape":
          if (state.currentShape === "rectangle") {
            addObject({
              type: "rectangle",
              position,
              width: 120,
              height: 80,
              fill: state.currentColor,
            });
          } else if (state.currentShape === "circle") {
            addObject({
              type: "circle",
              position,
              radius: 60,
              fill: state.currentColor,
            });
          }
          // Switch to select tool after creating shape
          updateState({ tool: "select" });
          break;

        case "text":
          addObject({
            type: "text",
            position,
            text: "Double-click to edit",
            fontSize: 16,
            color: state.currentColor,
            width: 200,
            height: 50,
            semanticRole: "paragraph",
          });
          // Switch to select tool after creating text
          updateState({ tool: "select" });
          break;

        case "sticky":
          addObject({
            type: "sticky",
            position,
            text: "",
            width: 200,
            height: 200,
            color: state.currentStickyColor,
          });
          // Switch to select tool after creating sticky
          updateState({ tool: "select" });
          break;

        case "table":
          // Create a 3x3 table with empty cells
          const emptyCells = Array(3)
            .fill(null)
            .map(() => Array(3).fill(""));
          addObject({
            type: "table",
            position,
            width: 300,
            height: 180,
            rows: 3,
            columns: 3,
            cellData: emptyCells,
            borderColor: "#000000",
            backgroundColor: "#ffffff",
          });
          // Switch to select tool after creating table
          updateState({ tool: "select" });
          break;

        case "line":
          if (!isDrawingLine) {
            // Start drawing line
            setIsDrawingLine(true);
            setLineStartPoint(position);
          } else {
            // Finish drawing line
            if (lineStartPoint) {
              addObject({
                type: "line",
                position: lineStartPoint,
                startPoint: lineStartPoint,
                endPoint: position,
                lineType: state.currentLineType,
                stroke: state.currentColor,
                strokeWidth: 2,
              });
              // Switch to select tool after completing line
              updateState({ tool: "select" });
            }
            setIsDrawingLine(false);
            setLineStartPoint(null);
          }
          break;

        case "select":
          updateStateWithHistory({ selectedObjectIds: [] });
          break;
      }
    },
    [
      state.tool,
      state.currentShape,
      state.currentLineType,
      state.currentColor,
      state.currentStickyColor,
      isDrawingLine,
      lineStartPoint,
      getMousePosition,
      addObject,
      updateStateWithHistory,
    ]
  );

  const handleMouseDown = useCallback(
    (e: React.MouseEvent) => {
      const position = getMousePosition(e);

      if (state.tool === "draw" || state.tool === "highlight") {
        setState((prev) => ({
          ...prev,
          isDrawing: true,
          currentPath: [position],
        }));
      } else if (state.tool === "hand") {
        setState((prev) => ({
          ...prev,
          isPanning: true,
          lastPanPoint: { x: e.clientX, y: e.clientY },
        }));
      }
    },
    [state.tool, getMousePosition]
  );

  const handleMouseMove = useCallback(
    (e: React.MouseEvent) => {
      const position = getMousePosition(e);

      // Update current mouse position for line preview
      if (isDrawingLine && state.tool === "line") {
        setCurrentMousePos(position);
      }

      if (
        state.isDrawing &&
        state.currentPath &&
        (state.tool === "draw" || state.tool === "highlight")
      ) {
        setState((prev) => ({
          ...prev,
          currentPath: [...(prev.currentPath || []), position],
        }));
      } else if (
        state.isPanning &&
        state.lastPanPoint &&
        state.tool === "hand"
      ) {
        const deltaX = e.clientX - state.lastPanPoint.x;
        const deltaY = e.clientY - state.lastPanPoint.y;

        // Convert screen delta to SVG coordinate delta
        const svgRect = svgRef.current?.getBoundingClientRect();
        if (svgRect) {
          const scaleX = state.viewBox.width / svgRect.width;
          const scaleY = state.viewBox.height / svgRect.height;

          setState((prev) => ({
            ...prev,
            viewBox: {
              ...prev.viewBox,
              x: prev.viewBox.x - deltaX * scaleX,
              y: prev.viewBox.y - deltaY * scaleY,
            },
            lastPanPoint: { x: e.clientX, y: e.clientY },
          }));
        }
      }
    },
    [
      state.isDrawing,
      state.currentPath,
      state.tool,
      state.isPanning,
      state.lastPanPoint,
      isDrawingLine,
      getMousePosition,
    ]
  );

  const handleMouseUp = useCallback(() => {
    if (state.isDrawing && state.currentPath && state.currentPath.length > 1) {
      const pathString = state.currentPath
        .map(
          (point, index) => `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`
        )
        .join(" ");

      addObject({
        type: "path",
        position: state.currentPath[0],
        path: pathString,
        stroke: state.currentColor,
        strokeWidth: state.tool === "highlight" ? 12 : 3,
      });

      // Switch to select tool after completing drawing/highlighting
      if (state.tool === "draw" || state.tool === "highlight") {
        updateState({ tool: "select" });
      }
    }

    setState((prev) => ({
      ...prev,
      isDrawing: false,
      currentPath: undefined,
      isPanning: false,
      lastPanPoint: undefined,
    }));
  }, [
    state.isDrawing,
    state.currentPath,
    state.currentColor,
    state.tool,
    addObject,
    updateState,
  ]);

  const handleZoomIn = useCallback(() => {
    setState((prev) => {
      const newZoom = Math.min(prev.zoom * 1.2, 5);
      const zoomFactor = newZoom / prev.zoom;

      // Scale viewBox to zoom in (smaller viewBox = more zoomed in)
      const newWidth = prev.viewBox.width / zoomFactor;
      const newHeight = prev.viewBox.height / zoomFactor;

      // Keep center point the same
      const centerX = prev.viewBox.x + prev.viewBox.width / 2;
      const centerY = prev.viewBox.y + prev.viewBox.height / 2;

      return {
        ...prev,
        zoom: newZoom,
        viewBox: {
          x: centerX - newWidth / 2,
          y: centerY - newHeight / 2,
          width: newWidth,
          height: newHeight,
        },
      };
    });
  }, []);

  const handleZoomOut = useCallback(() => {
    setState((prev) => {
      const newZoom = Math.max(prev.zoom / 1.2, 0.1);
      const zoomFactor = newZoom / prev.zoom;

      // Scale viewBox to zoom out (larger viewBox = more zoomed out)
      const newWidth = prev.viewBox.width / zoomFactor;
      const newHeight = prev.viewBox.height / zoomFactor;

      // Keep center point the same
      const centerX = prev.viewBox.x + prev.viewBox.width / 2;
      const centerY = prev.viewBox.y + prev.viewBox.height / 2;

      return {
        ...prev,
        zoom: newZoom,
        viewBox: {
          x: centerX - newWidth / 2,
          y: centerY - newHeight / 2,
          width: newWidth,
          height: newHeight,
        },
      };
    });
  }, []);

  const handleReset = useCallback(() => {
    const initialViewBox = getInitialViewBox();
    setState((prev) => ({
      ...prev,
      viewBox: initialViewBox,
      zoom: 1,
      selectedObjectIds: [],
    }));
  }, []);

  // Keyboard shortcuts
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Don't trigger shortcuts when text is being edited
      if (isTextEditing) {
        return;
      }

      if (e.key === "Delete" || e.key === "Backspace") {
        if (state.selectedObjectIds.length > 0) {
          deleteSelectedObjects();
        }
      }

      if (e.key === "Escape") {
        updateStateWithHistory({ selectedObjectIds: [] });
        updateState({ tool: "select" });
      }

      // Undo/Redo shortcuts
      if ((e.ctrlKey || e.metaKey) && e.key === "z" && !e.shiftKey) {
        e.preventDefault();
        undo();
      }
      if (
        (e.ctrlKey || e.metaKey) &&
        (e.key === "y" || (e.key === "z" && e.shiftKey))
      ) {
        e.preventDefault();
        redo();
      }

      // Tool shortcuts
      if (e.key >= "1" && e.key <= "7") {
        const tools: ToolType[] = [
          "hand",
          "select",
          "draw",
          "eraser",
          "shape",
          "text",
          "sticky",
        ];
        const toolIndex = parseInt(e.key) - 1;
        if (tools[toolIndex]) {
          setState((prev) => ({ ...prev, tool: tools[toolIndex] }));
        }
      }

      // Text style shortcuts
      if ((e.ctrlKey || e.metaKey) && e.altKey) {
        if (e.key === "1") {
          e.preventDefault();
          updateTextStyle("h1");
        } else if (e.key === "0") {
          e.preventDefault();
          updateTextStyle("paragraph");
        }
      }

      // Shape shortcuts when shape tool is active
      if (state.tool === "shape") {
        if (e.key === "r" || e.key === "R") {
          setState((prev) => ({ ...prev, currentShape: "rectangle" }));
        } else if (e.key === "c" || e.key === "C") {
          setState((prev) => ({ ...prev, currentShape: "circle" }));
        }
      }
    };

    document.addEventListener("keydown", handleKeyDown);
    return () => document.removeEventListener("keydown", handleKeyDown);
  }, [
    state.selectedObjectIds,
    state.tool,
    isTextEditing,
    deleteSelectedObjects,
    updateStateWithHistory,
    updateState,
    updateTextStyle,
    undo,
    redo,
  ]);

  return (
    <div className="canvas-container h-screen">
      <AccessibilityInstructions />
      <Navbar />
      <Toolbar
        activeTool={state.tool}
        onToolChange={(tool) => updateState({ tool })}
        currentShape={state.currentShape}
        onShapeChange={(shape) => updateState({ currentShape: shape })}
        currentLineType={state.currentLineType}
        onLineTypeChange={(lineType) =>
          updateState({ currentLineType: lineType })
        }
        currentColor={state.currentColor}
        onColorChange={(color) => updateState({ currentColor: color })}
        currentStickyColor={state.currentStickyColor}
        onStickyColorChange={(color) =>
          updateState({ currentStickyColor: color })
        }
        selectedTextStyle={getSelectedTextStyle()}
        onTextStyleChange={updateTextStyle}
        hasSelectedText={hasSelectedTextObjects()}
        onUndo={historyIndex > 0 ? undo : undefined}
        onRedo={historyIndex < history.length - 1 ? redo : undefined}
      />

      <ZoomToolbar
        onZoomIn={handleZoomIn}
        onZoomOut={handleZoomOut}
        onReset={handleReset}
        zoom={state.zoom}
      />

      {/* Text Formatting Toolbar */}
      <TextFormattingToolbar
        isVisible={hasSelectedTextObjects() || isTextEditing}
        position={getTextToolbarPosition()}
        currentStyle={getSelectedTextStyle()}
        onStyleChange={updateTextStyle}
      />

      <div className="absolute inset-0 top-[128px]">
        <svg
          ref={svgRef}
          className={`w-full h-full canvas-grid ${
            state.tool === "hand"
              ? state.isPanning
                ? "cursor-grabbing"
                : "cursor-grab"
              : ""
          }`}
          viewBox={`${state.viewBox.x} ${state.viewBox.y} ${state.viewBox.width} ${state.viewBox.height}`}
          onClick={handleCanvasClick}
          onMouseDown={handleMouseDown}
          onMouseMove={handleMouseMove}
          onMouseUp={handleMouseUp}
        >
          {/* Grid pattern - screen-appropriate size */}
          <defs>
            <pattern
              id="grid"
              width="50"
              height="50"
              patternUnits="userSpaceOnUse"
            >
              <rect width="50" height="50" fill="none" />
              <path
                d="M 50 0 L 0 0 0 50"
                fill="none"
                stroke="white"
                strokeWidth="3"
                opacity="1"
              />
            </pattern>
          </defs>

          {/* Canvas background - unlimited size */}
          <rect
            x={state.viewBox.x - state.viewBox.width}
            y={state.viewBox.y - state.viewBox.height}
            width={state.viewBox.width * 3}
            height={state.viewBox.height * 3}
            fill="#f5f5f5"
          />

          {/* Grid overlay - unlimited size */}
          <rect
            x={state.viewBox.x - state.viewBox.width}
            y={state.viewBox.y - state.viewBox.height}
            width={state.viewBox.width * 3}
            height={state.viewBox.height * 3}
            fill="url(#grid)"
          />

          {/* Render all objects */}
          {state.objects.map((object) => (
            <CanvasObjectComponent
              key={object.id}
              object={{
                ...object,
                selected: state.selectedObjectIds.includes(object.id),
              }}
              onSelect={selectObject}
              onMove={moveObject}
              onTextEdit={editObjectText}
              onTextEditingChange={setIsTextEditing}
              onDelete={deleteObject}
              currentTool={state.tool}
            />
          ))}

          {/* Current drawing path */}
          {state.isDrawing &&
            state.currentPath &&
            state.currentPath.length > 1 && (
              <path
                d={state.currentPath
                  .map(
                    (point, index) =>
                      `${index === 0 ? "M" : "L"} ${point.x} ${point.y}`
                  )
                  .join(" ")}
                stroke={state.currentColor}
                strokeWidth={state.tool === "highlight" ? "12" : "3"}
                fill="none"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            )}

          {/* Line preview when drawing */}
          {isDrawingLine && lineStartPoint && currentMousePos && (
            <g>
              <line
                x1={lineStartPoint.x}
                y1={lineStartPoint.y}
                x2={currentMousePos.x}
                y2={currentMousePos.y}
                stroke={state.currentColor}
                strokeWidth="2"
                strokeDasharray="5,5"
                opacity="0.7"
              />
            </g>
          )}
        </svg>
      </div>
    </div>
  );
}
Editor is loading...
Leave a Comment