Skip to content

A lightweight Clip Studio Paint alternative with real-time multiplayer collaborative drawing. Built with Tauri and React.

34.1 KB
Raw Blame
import React, { useEffect, useRef, useState, useCallback, useId } from 'react';
import { createPortal } from 'react-dom';
import {
  Check,
  X,
  RotateCcw,
  Grid3X3,
  ArrowLeftRight,
  SlidersHorizontal,
  Lock,
} from 'lucide-react';
import { CanvasDimensions } from '../types/editor';
import { ResizeCanvasOptions } from '../types/settings';
import { CanvasNavigationHandle, CameraTransformState } from '../hooks/useCanvasNavigation';
import { screenToCanvas } from '../utils/canvasUtils';
import { resolvePointerModifierAction } from '../utils/shortcutManager';
import { uiStoreActions, useUiStore } from '../stores';
import { useI18n } from '../i18n';
import {
  CropGridMode,
  CropHandleId,
  CropRect,
  CropResizeHandleId,
  SnapGuides,
  applyCropRectToDraft,
  applyResetCropToDraft,
  applySwapDimensionsToDraft,
  createCropRectFromDrag,
  cycleCropGridMode,
  draftToResizeCanvasOptions,
  getRotatedResizeCursor,
  isCropModified,
  moveCropRect,
  resizeCropRectByHandle,
} from '../utils/canvasResizeCrop';

export interface CanvasResizeOverlayProps {
  dimensions: CanvasDimensions;
  viewportRef: React.RefObject<HTMLDivElement | null>;
  navigation?: CanvasNavigationHandle;
  pan: { x: number; y: number };
  zoom: number;
  rotation: number;
  flipX?: boolean;
  flipY?: boolean;
  isNavigationActive?: boolean;
  onApply?: (options: ResizeCanvasOptions) => void;
  onCancel?: () => void;
}

const CORNER_HANDLES: CropResizeHandleId[] = ['nw', 'ne', 'se', 'sw'];
const EDGE_HANDLES: CropResizeHandleId[] = ['n', 'e', 's', 'w'];
const SNAP_THRESHOLD_SCREEN_PX = 6;
const MARQUEE_DRAG_THRESHOLD_PX = 4;

function isNavigationPointerDown(e: React.PointerEvent, isSpaceDown: boolean): boolean {
  if (e.button !== 0 || isSpaceDown) return true;
  const modSettings = useUiStore.getState().appSettings.modifierKeys;
  const resolved = resolvePointerModifierAction(
    {
      button: e.button,
      pointerType: e.pointerType,
      ctrlKey: e.ctrlKey,
      metaKey: e.metaKey,
      shiftKey: e.shiftKey,
      altKey: e.altKey,
      isSpaceDown,
    },
    modSettings
  );
  return (
    resolved?.action === 'pan' ||
    resolved?.action === 'rotate' ||
    resolved?.action === 'zoom-drag'
  );
}

function getGridLabel(mode: CropGridMode): string {
  if (mode === 'thirds') return 'Rule of Thirds';
  if (mode === 'golden') return 'Golden Ratio';
  return 'No Grid';
}

function getGridFractions(mode: CropGridMode): [number, number] | null {
  if (mode === 'thirds') return [1 / 3, 2 / 3];
  if (mode === 'golden') return [0.381966, 0.618034];
  return null;
}

/**
 * Full-viewport capture backdrop (mounted between canvas interaction surface and artboard overlays)
 * allowing the user to click-drag outside the existing crop rectangle to draw a brand-new crop box,
 * just like Photoshop's Crop tool. Navigation modifiers & non-primary buttons pass through.
 */
export const CanvasResizeMarqueeBackdrop: React.FC<{
  dimensions: CanvasDimensions;
  viewportRef: React.RefObject<HTMLDivElement | null>;
  navigation?: CanvasNavigationHandle;
  pan: { x: number; y: number };
  zoom: number;
  rotation: number;
  flipX?: boolean;
  flipY?: boolean;
  isSpaceDown?: boolean;
  isNavigationActive?: boolean;
}> = ({
  dimensions,
  viewportRef,
  navigation,
  pan,
  zoom,
  rotation,
  flipX = false,
  flipY = false,
  isSpaceDown = false,
  isNavigationActive = false,
}) => {
  const isOpen = useUiStore((s) => s.isResizeCanvasModalOpen);
  const scaleContent = useUiStore((s) => s.canvasResizeDraft?.scaleContent ?? false);
  const cleanupRef = useRef<(() => void) | null>(null);

  useEffect(() => {
    return () => {
      cleanupRef.current?.();
      cleanupRef.current = null;
    };
  }, []);

  if (!isOpen || scaleContent || isNavigationActive) return null;

  const handlePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
    if (isNavigationPointerDown(e, isSpaceDown)) {
      return;
    }
    const draft = useUiStore.getState().canvasResizeDraft;
    if (!draft || draft.scaleContent) return;

    e.preventDefault();
    e.stopPropagation();

    cleanupRef.current?.();

    const startClientX = e.clientX;
    const startClientY = e.clientY;

    const getCam = (): CameraTransformState =>
      navigation ? navigation.getCameraState() : { pan, zoom, rotation, flipX, flipY };
    const getRect = (): DOMRect =>
      viewportRef.current?.getBoundingClientRect() ?? new DOMRect(0, 0, 0, 0);

    const startCam = getCam();
    const startViewportRect = getRect();
    const startDoc = screenToCanvas(
      startClientX,
      startClientY,
      startViewportRect,
      startCam.pan,
      startCam.zoom,
      startCam.rotation,
      dimensions,
      startCam.flipX,
      startCam.flipY
    );

    let hasStartedDrag = false;

    const handleMove = (ev: PointerEvent) => {
      const dist = Math.hypot(ev.clientX - startClientX, ev.clientY - startClientY);
      if (!hasStartedDrag) {
        if (dist < MARQUEE_DRAG_THRESHOLD_PX) return;
        hasStartedDrag = true;
      }

      const curDraft = useUiStore.getState().canvasResizeDraft;
      if (!curDraft || curDraft.scaleContent) return;

      const cam = getCam();
      const vpRect = getRect();
      const curDoc = screenToCanvas(
        ev.clientX,
        ev.clientY,
        vpRect,
        cam.pan,
        cam.zoom,
        cam.rotation,
        dimensions,
        cam.flipX,
        cam.flipY
      );

      const snapThreshold = SNAP_THRESHOLD_SCREEN_PX / Math.max(0.05, cam.zoom);
      const snapTargets =
        ev.ctrlKey || ev.metaKey
          ? null
          : {
              x: [0, dimensions.width / 2, dimensions.width],
              y: [0, dimensions.height / 2, dimensions.height],
              threshold: snapThreshold,
            };

      const lockAspect = curDraft.lockRatio || ev.shiftKey;
      const aspectRatio = curDraft.lockRatio
        ? curDraft.ratioX / Math.max(1, curDraft.ratioY)
        : 1;

      const { rect } = createCropRectFromDrag(startDoc, curDoc, {
        lockAspect,
        aspectRatio,
        fromCenter: ev.altKey,
        snapTargets,
      });

      uiStoreActions.updateCanvasResizeDraft((prev) => applyCropRectToDraft(prev, rect));
    };

    const handleUp = () => {
      window.removeEventListener('pointermove', handleMove);
      window.removeEventListener('pointerup', handleUp);
      window.removeEventListener('pointercancel', handleUp);
      cleanupRef.current = null;
    };

    cleanupRef.current = handleUp;
    window.addEventListener('pointermove', handleMove);
    window.addEventListener('pointerup', handleUp);
    window.addEventListener('pointercancel', handleUp);
  };

  return (
    <div
      data-testid="canvas-crop-marquee-backdrop"
      onPointerDown={handlePointerDown}
      className="absolute inset-0 z-[18] cursor-crosshair"
    />
  );
};

export const CanvasResizeOverlay: React.FC<CanvasResizeOverlayProps> = ({
  dimensions,
  viewportRef,
  navigation,
  pan,
  zoom,
  rotation,
  flipX = false,
  flipY = false,
  isNavigationActive = false,
  onApply,
  onCancel,
}) => {
  const { t, td } = useI18n();
  const isOpen = useUiStore((s) => s.isResizeCanvasModalOpen);
  const draft = useUiStore((s) => s.canvasResizeDraft);
  const isInspectorCollapsed = useUiStore((s) => s.isResizeInspectorCollapsed);
  const patternId = useId();

  const [activeHandle, setActiveHandle] = useState<CropHandleId | null>(null);
  const [hoveredHandle, setHoveredHandle] = useState<CropHandleId | null>(null);
  const [snapGuides, setSnapGuides] = useState<SnapGuides>({});
  const dragCleanupRef = useRef<(() => void) | null>(null);

  useEffect(() => {
    return () => {
      dragCleanupRef.current?.();
      dragCleanupRef.current = null;
    };
  }, []);

  useEffect(() => {
    if (!isOpen) {
      dragCleanupRef.current?.();
      dragCleanupRef.current = null;
      setActiveHandle(null);
      setHoveredHandle(null);
      setSnapGuides({});
    }
  }, [isOpen]);

  const handleConfirm = useCallback(() => {
    const current = useUiStore.getState().canvasResizeDraft;
    if (!current) return;
    const options = draftToResizeCanvasOptions(current);
    onApply?.(options);
    uiStoreActions.setResizeCanvasModalOpen(false);
  }, [onApply]);

  const handleCancel = useCallback(() => {
    if (onCancel) {
      onCancel();
    } else {
      uiStoreActions.setResizeCanvasModalOpen(false);
    }
  }, [onCancel]);

  const startHandleDrag = useCallback(
    (handle: CropHandleId, e: React.PointerEvent) => {
      if (isNavigationPointerDown(e, isNavigationActive)) {
        return;
      }
      const curDraft = useUiStore.getState().canvasResizeDraft;
      if (!curDraft || curDraft.scaleContent) return;

      e.preventDefault();
      e.stopPropagation();

      dragCleanupRef.current?.();

      const startRect: CropRect = {
        x: curDraft.cropX,
        y: curDraft.cropY,
        width: curDraft.width,
        height: curDraft.height,
      };
      const startAspect = curDraft.lockRatio
        ? curDraft.ratioX / Math.max(1, curDraft.ratioY)
        : startRect.width / Math.max(1, startRect.height);

      const getCam = (): CameraTransformState =>
        navigation ? navigation.getCameraState() : { pan, zoom, rotation, flipX, flipY };
      const getRect = (): DOMRect =>
        viewportRef.current?.getBoundingClientRect() ?? new DOMRect(0, 0, 0, 0);

      const startCam = getCam();
      const startVpRect = getRect();
      const startDoc = screenToCanvas(
        e.clientX,
        e.clientY,
        startVpRect,
        startCam.pan,
        startCam.zoom,
        startCam.rotation,
        dimensions,
        startCam.flipX,
        startCam.flipY
      );

      setActiveHandle(handle);

      const handleMove = (ev: PointerEvent) => {
        const latestDraft = useUiStore.getState().canvasResizeDraft;
        if (!latestDraft || latestDraft.scaleContent) return;

        const cam = getCam();
        const vpRect = getRect();
        const curDoc = screenToCanvas(
          ev.clientX,
          ev.clientY,
          vpRect,
          cam.pan,
          cam.zoom,
          cam.rotation,
          dimensions,
          cam.flipX,
          cam.flipY
        );

        const dx = curDoc.x - startDoc.x;
        const dy = curDoc.y - startDoc.y;

        const snapThreshold = SNAP_THRESHOLD_SCREEN_PX / Math.max(0.05, cam.zoom);
        const snapTargets =
          ev.ctrlKey || ev.metaKey
            ? null
            : {
                x: [0, dimensions.width / 2, dimensions.width],
                y: [0, dimensions.height / 2, dimensions.height],
                threshold: snapThreshold,
              };

        if (handle === 'move') {
          const { rect, snapGuides: nextGuides } = moveCropRect(startRect, dx, dy, {
            constrainAxis: ev.shiftKey,
            snapTargets,
          });
          setSnapGuides(nextGuides);
          uiStoreActions.updateCanvasResizeDraft((prev) => applyCropRectToDraft(prev, rect));
          return;
        }

        const lockAspect = latestDraft.lockRatio || ev.shiftKey;
        const aspectRatio = latestDraft.lockRatio
          ? latestDraft.ratioX / Math.max(1, latestDraft.ratioY)
          : startAspect;

        const { rect, snapGuides: nextGuides } = resizeCropRectByHandle(
          startRect,
          handle,
          dx,
          dy,
          {
            lockAspect,
            aspectRatio,
            fromCenter: ev.altKey,
            snapTargets,
          }
        );
        setSnapGuides(nextGuides);
        uiStoreActions.updateCanvasResizeDraft((prev) => applyCropRectToDraft(prev, rect));
      };

      const handleUp = () => {
        window.removeEventListener('pointermove', handleMove);
        window.removeEventListener('pointerup', handleUp);
        window.removeEventListener('pointercancel', handleUp);
        dragCleanupRef.current = null;
        setActiveHandle(null);
        setSnapGuides({});
      };

      dragCleanupRef.current = handleUp;
      window.addEventListener('pointermove', handleMove);
      window.addEventListener('pointerup', handleUp);
      window.addEventListener('pointercancel', handleUp);
    },
    [dimensions, flipX, flipY, isNavigationActive, navigation, pan, rotation, viewportRef, zoom]
  );

  if (!isOpen || !draft) return null;

  const invZoom = 1 / Math.max(0.05, zoom);
  const origW = dimensions.width;
  const origH = dimensions.height;
  const cropX = draft.cropX;
  const cropY = draft.cropY;
  const cropW = draft.width;
  const cropH = draft.height;
  const modified = isCropModified(draft);
  const isDragging = activeHandle !== null;
  const pointerClass = isNavigationActive ? 'pointer-events-none' : 'pointer-events-auto';

  // Compute intersection of crop rect and original canvas for evenodd masks
  const ix0 = Math.max(0, cropX);
  const iy0 = Math.max(0, cropY);
  const ix1 = Math.min(origW, cropX + cropW);
  const iy1 = Math.min(origH, cropY + cropH);
  const hasIntersection = ix1 > ix0 && iy1 > iy0;

  // Dimmed mask covering cropped-away portion of the original canvas
  const croppedScrimPath = hasIntersection
    ? `M 0 0 H ${origW} V ${origH} H 0 Z M ${ix0} ${iy0} H ${ix1} V ${iy1} H ${ix0} Z`
    : `M 0 0 H ${origW} V ${origH} H 0 Z`;

  // Expanded region outside the original canvas bounds
  const hasExpansion =
    cropX < 0 || cropY < 0 || cropX + cropW > origW || cropY + cropH > origH;
  const expansionAreaPath = hasExpansion
    ? hasIntersection
      ? `M ${cropX} ${cropY} H ${cropX + cropW} V ${cropY + cropH} H ${cropX} Z M ${ix0} ${iy0} H ${ix1} V ${iy1} H ${ix0} Z`
      : `M ${cropX} ${cropY} H ${cropX + cropW} V ${cropY + cropH} H ${cropX} Z`
    : '';

  const gridFractions = getGridFractions(draft.gridMode);
  const patSize = Math.max(4, 14 * invZoom);
  const halfPat = patSize / 2;

  // Handle sizing in document pixels (constant screen size)
  const cornerHitSize = 24 * invZoom;
  const edgeHitThick = 16 * invZoom;
  const cornerArmLen = Math.min(18 * invZoom, Math.max(4 * invZoom, Math.min(cropW, cropH) * 0.32));
  const cornerArmThick = 3.5 * invZoom;
  const edgePillLen = Math.min(26 * invZoom, Math.max(6 * invZoom, Math.min(cropW, cropH) * 0.35));
  const edgePillThick = 4.5 * invZoom;

  // Counter-transform for upright readable badges
  const uprightBadgeTransform = `scale(${invZoom}) scale(${flipX ? -1 : 1}, ${flipY ? -1 : 1}) rotate(${-rotation}deg)`;

  const getCornerBracketPath = (corner: CropResizeHandleId): string => {
    const t = cornerArmThick;
    const len = cornerArmLen;
    switch (corner) {
      case 'nw':
        return `M ${cropX - t * 0.5} ${cropY - t * 0.5} h ${len} v ${t} h ${-(len - t)} v ${len - t} h ${-t} Z`;
      case 'ne':
        return `M ${cropX + cropW + t * 0.5} ${cropY - t * 0.5} h ${-len} v ${t} h ${len - t} v ${len - t} h ${t} Z`;
      case 'se':
        return `M ${cropX + cropW + t * 0.5} ${cropY + cropH + t * 0.5} h ${-len} v ${-t} h ${len - t} v ${-(len - t)} h ${t} Z`;
      case 'sw':
        return `M ${cropX - t * 0.5} ${cropY + cropH + t * 0.5} h ${len} v ${-t} h ${-(len - t)} v ${-(len - t)} h ${-t} Z`;
      default:
        return '';
    }
  };

  const getCornerHitPos = (corner: CropResizeHandleId): { left: number; top: number } => {
    const half = cornerHitSize / 2;
    switch (corner) {
      case 'nw':
        return { left: cropX - half, top: cropY - half };
      case 'ne':
        return { left: cropX + cropW - half, top: cropY - half };
      case 'se':
        return { left: cropX + cropW - half, top: cropY + cropH - half };
      case 'sw':
      default:
        return { left: cropX - half, top: cropY + cropH - half };
    }
  };

  const getEdgeHitStyle = (edge: CropResizeHandleId): React.CSSProperties => {
    const cornerInset = Math.min(cornerHitSize * 0.5, Math.min(cropW, cropH) * 0.25);
    const halfT = edgeHitThick / 2;
    switch (edge) {
      case 'n':
        return {
          left: `${cropX + cornerInset}px`,
          top: `${cropY - halfT}px`,
          width: `${Math.max(2 * invZoom, cropW - cornerInset * 2)}px`,
          height: `${edgeHitThick}px`,
        };
      case 's':
        return {
          left: `${cropX + cornerInset}px`,
          top: `${cropY + cropH - halfT}px`,
          width: `${Math.max(2 * invZoom, cropW - cornerInset * 2)}px`,
          height: `${edgeHitThick}px`,
        };
      case 'w':
        return {
          left: `${cropX - halfT}px`,
          top: `${cropY + cornerInset}px`,
          width: `${edgeHitThick}px`,
          height: `${Math.max(2 * invZoom, cropH - cornerInset * 2)}px`,
        };
      case 'e':
      default:
        return {
          left: `${cropX + cropW - halfT}px`,
          top: `${cropY + cornerInset}px`,
          width: `${edgeHitThick}px`,
          height: `${Math.max(2 * invZoom, cropH - cornerInset * 2)}px`,
        };
    }
  };

  const getEdgePillRect = (edge: CropResizeHandleId) => {
    const cx = cropX + cropW / 2;
    const cy = cropY + cropH / 2;
    if (edge === 'n') {
      return {
        x: cx - edgePillLen / 2,
        y: cropY - edgePillThick / 2,
        width: edgePillLen,
        height: edgePillThick,
      };
    }
    if (edge === 's') {
      return {
        x: cx - edgePillLen / 2,
        y: cropY + cropH - edgePillThick / 2,
        width: edgePillLen,
        height: edgePillThick,
      };
    }
    if (edge === 'w') {
      return {
        x: cropX - edgePillThick / 2,
        y: cy - edgePillLen / 2,
        width: edgePillThick,
        height: edgePillLen,
      };
    }
    return {
      x: cropX + cropW - edgePillThick / 2,
      y: cy - edgePillLen / 2,
      width: edgePillThick,
      height: edgePillLen,
    };
  };

  const snapGuideMinY = Math.min(0, cropY) - 36 * invZoom;
  const snapGuideMaxY = Math.max(origH, cropY + cropH) + 36 * invZoom;
  const snapGuideMinX = Math.min(0, cropX) - 36 * invZoom;
  const snapGuideMaxX = Math.max(origW, cropX + cropW) + 36 * invZoom;

  const percentW = Math.round((cropW / Math.max(1, origW)) * 100);
  const percentH = Math.round((cropH / Math.max(1, origH)) * 100);

  return (
    <>
      {draft.scaleContent ? (
        /* Scale Content (Resample) Non-Cropping Reference Frame */
        <div
          data-testid="canvas-resize-scale-preview"
          className="absolute inset-0 pointer-events-none z-35"
        >
          <svg
            className="absolute inset-0 w-full h-full overflow-visible pointer-events-none"
            viewBox={`0 0 ${origW} ${origH}`}
          >
            <rect
              x={0}
              y={0}
              width={origW}
              height={origH}
              fill="none"
              stroke="var(--ui-accent)"
              strokeWidth={1.75 * invZoom}
              strokeDasharray={`${6 * invZoom} ${4 * invZoom}`}
            />
          </svg>
          <div
            className="absolute pointer-events-none px-2 py-0.5 rounded-ui-xs bg-ui-floating/95 border border-ui-default text-ui-primary shadow-ui-floating font-ui-mono tabular-nums text-[10px] whitespace-nowrap flex items-center gap-1.5"
            style={{
              left: `${origW / 2}px`,
              top: `${-16 * invZoom}px`,
              transform: `translate(-50%, -100%) ${uprightBadgeTransform}`,
              transformOrigin: 'center bottom',
            }}
          >
            <span className="text-ui-accent font-medium">{t('Resample')}</span>
            <span>
              {cropW} × {cropH} px
            </span>
            <span className="text-ui-muted">
              ({percentW}% × {percentH}%)
            </span>
          </div>
        </div>
      ) : (
        /* Interactive Crop & Resize Canvas Bounds Overlay */
        <div
          data-testid="canvas-resize-crop-overlay"
          className="absolute inset-0 pointer-events-none z-35"
        >
          {/* 1. SVG Scrim, Expanded Preview, Guides, Frame Border & Handle Visuals */}
          <svg
            className="absolute inset-0 w-full h-full overflow-visible pointer-events-none"
            viewBox={`0 0 ${origW} ${origH}`}
          >
            <defs>
              <pattern
                id={`crop-expand-checker-${patternId}`}
                width={patSize}
                height={patSize}
                patternUnits="userSpaceOnUse"
              >
                <rect width={patSize} height={patSize} fill="rgba(255,255,255,0.12)" />
                <rect width={halfPat} height={halfPat} fill="rgba(255,255,255,0.22)" />
                <rect
                  x={halfPat}
                  y={halfPat}
                  width={halfPat}
                  height={halfPat}
                  fill="rgba(255,255,255,0.22)"
                />
              </pattern>
            </defs>

            {/* Darkened scrim over cropped-out areas of the original canvas */}
            <path
              data-testid="canvas-crop-scrim"
              d={croppedScrimPath}
              fillRule="evenodd"
              fill={isDragging ? 'rgba(0, 0, 0, 0.64)' : 'rgba(0, 0, 0, 0.52)'}
            />

            {/* Expanded canvas area preview outside the original canvas */}
            {hasExpansion && expansionAreaPath && (
              <path
                data-testid="canvas-crop-expansion-area"
                d={expansionAreaPath}
                fillRule="evenodd"
                fill={`url(#crop-expand-checker-${patternId})`}
              />
            )}

            {/* Original canvas reference outline when modified */}
            {modified && (
              <>
                <rect
                  x={0}
                  y={0}
                  width={origW}
                  height={origH}
                  fill="none"
                  stroke="rgba(0, 0, 0, 0.45)"
                  strokeWidth={1.6 * invZoom}
                  strokeDasharray={`${5 * invZoom} ${4 * invZoom}`}
                />
                <rect
                  x={0}
                  y={0}
                  width={origW}
                  height={origH}
                  fill="none"
                  stroke="rgba(255, 255, 255, 0.55)"
                  strokeWidth={1 * invZoom}
                  strokeDasharray={`${5 * invZoom} ${4 * invZoom}`}
                />
              </>
            )}

            {/* Composition Grid (Rule of Thirds / Golden Ratio) */}
            {gridFractions && (
              <g opacity={isDragging ? 0.72 : 0.34}>
                {gridFractions.map((f, idx) => {
                  const gx = cropX + cropW * f;
                  const gy = cropY + cropH * f;
                  return (
                    <React.Fragment key={idx}>
                      <line
                        x1={gx}
                        y1={cropY}
                        x2={gx}
                        y2={cropY + cropH}
                        stroke="rgba(0, 0, 0, 0.45)"
                        strokeWidth={1.8 * invZoom}
                      />
                      <line
                        x1={gx}
                        y1={cropY}
                        x2={gx}
                        y2={cropY + cropH}
                        stroke="#ffffff"
                        strokeWidth={0.9 * invZoom}
                      />
                      <line
                        x1={cropX}
                        y1={gy}
                        x2={cropX + cropW}
                        y2={gy}
                        stroke="rgba(0, 0, 0, 0.45)"
                        strokeWidth={1.8 * invZoom}
                      />
                      <line
                        x1={cropX}
                        y1={gy}
                        x2={cropX + cropW}
                        y2={gy}
                        stroke="#ffffff"
                        strokeWidth={0.9 * invZoom}
                      />
                    </React.Fragment>
                  );
                })}
              </g>
            )}

            {/* Magnetic Snap Guide Lines */}
            {snapGuides.x !== undefined && (
              <line
                x1={snapGuides.x}
                y1={snapGuideMinY}
                x2={snapGuides.x}
                y2={snapGuideMaxY}
                stroke="var(--ui-accent)"
                strokeWidth={1.4 * invZoom}
                strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}
              />
            )}
            {snapGuides.y !== undefined && (
              <line
                x1={snapGuideMinX}
                y1={snapGuides.y}
                x2={snapGuideMaxX}
                y2={snapGuides.y}
                stroke="var(--ui-accent)"
                strokeWidth={1.4 * invZoom}
                strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}
              />
            )}

            {/* Crop Frame Double-Contrast Border */}
            <rect
              data-testid="canvas-crop-frame-rect"
              x={cropX}
              y={cropY}
              width={cropW}
              height={cropH}
              fill="none"
              stroke="rgba(0, 0, 0, 0.72)"
              strokeWidth={2.6 * invZoom}
            />
            <rect
              x={cropX}
              y={cropY}
              width={cropW}
              height={cropH}
              fill="none"
              stroke={isDragging ? 'var(--ui-accent)' : '#ffffff'}
              strokeWidth={1.35 * invZoom}
            />

            {/* 4 Edge Pill Handle Visuals */}
            {EDGE_HANDLES.map((edge) => {
              const r = getEdgePillRect(edge);
              const isHot = activeHandle === edge || hoveredHandle === edge;
              return (
                <rect
                  key={edge}
                  x={r.x}
                  y={r.y}
                  width={r.width}
                  height={r.height}
                  rx={edgePillThick * 0.45}
                  ry={edgePillThick * 0.45}
                  fill={isHot ? 'var(--ui-accent)' : '#ffffff'}
                  stroke="rgba(0, 0, 0, 0.78)"
                  strokeWidth={1.1 * invZoom}
                />
              );
            })}

            {/* 4 Corner L-Bracket Visuals */}
            {CORNER_HANDLES.map((corner) => {
              const isHot = activeHandle === corner || hoveredHandle === corner;
              return (
                <path
                  key={corner}
                  d={getCornerBracketPath(corner)}
                  fill={isHot ? 'var(--ui-accent)' : '#ffffff'}
                  stroke="rgba(0, 0, 0, 0.8)"
                  strokeWidth={1.1 * invZoom}
                  strokeLinejoin="miter"
                />
              );
            })}
          </svg>

          {/* 2. Interactive Interior Drag-to-Move Region */}
          <div
            data-testid="canvas-crop-move-area"
            onPointerDown={(e) => startHandleDrag('move', e)}
            onDoubleClick={(e) => {
              e.stopPropagation();
              handleConfirm();
            }}
            onPointerEnter={() => setHoveredHandle('move')}
            onPointerLeave={() => setHoveredHandle((prev) => (prev === 'move' ? null : prev))}
            className={`absolute ${pointerClass}`}
            style={{
              left: `${cropX}px`,
              top: `${cropY}px`,
              width: `${cropW}px`,
              height: `${cropH}px`,
              cursor: activeHandle === 'move' ? 'grabbing' : 'move',
            }}
            title={t('Drag to reposition canvas frame · Double-click to apply')}
          />

          {/* 3. Interactive Edge Hit Strips */}
          {EDGE_HANDLES.map((edge) => (
            <div
              key={edge}
              data-testid={`canvas-crop-handle-${edge}`}
              onPointerDown={(e) => startHandleDrag(edge, e)}
              onPointerEnter={() => setHoveredHandle(edge)}
              onPointerLeave={() => setHoveredHandle((prev) => (prev === edge ? null : prev))}
              className={`absolute ${pointerClass}`}
              style={{
                ...getEdgeHitStyle(edge),
                cursor: getRotatedResizeCursor(edge, rotation, flipX, flipY),
              }}
            />
          ))}

          {/* 4. Interactive Corner Hit Targets */}
          {CORNER_HANDLES.map((corner) => {
            const pos = getCornerHitPos(corner);
            return (
              <div
                key={corner}
                data-testid={`canvas-crop-handle-${corner}`}
                onPointerDown={(e) => startHandleDrag(corner, e)}
                onPointerEnter={() => setHoveredHandle(corner)}
                onPointerLeave={() => setHoveredHandle((prev) => (prev === corner ? null : prev))}
                className={`absolute ${pointerClass}`}
                style={{
                  left: `${pos.left}px`,
                  top: `${pos.top}px`,
                  width: `${cornerHitSize}px`,
                  height: `${cornerHitSize}px`,
                  cursor: getRotatedResizeCursor(corner, rotation, flipX, flipY),
                }}
              />
            );
          })}

          {/* 5. Upright Live Dimension Readout Badge */}
          <div
            data-testid="canvas-crop-dimension-badge"
            className="absolute pointer-events-none px-2 py-0.5 rounded-ui-xs bg-ui-floating/95 border border-ui-default text-ui-primary shadow-ui-floating font-ui-mono tabular-nums text-[10px] whitespace-nowrap flex items-center gap-1.5"
            style={{
              left: `${cropX + cropW / 2}px`,
              top: `${cropY - 12 * invZoom}px`,
              transform: `translate(-50%, -100%) ${uprightBadgeTransform}`,
              transformOrigin: 'center bottom',
            }}
          >
            {draft.lockRatio && <Lock className="w-2.5 h-2.5 text-ui-accent shrink-0" />}
            <span className="font-medium">
              {cropW} × {cropH} px
            </span>
            {(cropX !== 0 || cropY !== 0) && (
              <span className="text-ui-muted">
                · X {cropX}, Y {cropY}
              </span>
            )}
          </div>
        </div>
      )}

      {/* Viewport-Anchored Bottom Crop / Resize Action Bar */}
      {typeof document !== 'undefined' &&
        createPortal(
          <div
            data-testid="canvas-crop-action-bar"
            data-native-occluder="true"
            className="fixed bottom-9 left-1/2 -translate-x-1/2 z-[48] max-w-[95vw] bg-ui-floating border border-ui-default rounded-ui-md shadow-ui-floating px-2 py-1 flex flex-wrap items-center justify-center gap-1 select-none text-[11px] text-ui-primary"
            onPointerDown={(e) => e.stopPropagation()}
          >
            {!draft.scaleContent && (
              <>
                <button
                  type="button"
                  onClick={() =>
                    uiStoreActions.updateCanvasResizeDraft((prev) => ({
                      ...prev,
                      gridMode: cycleCropGridMode(prev.gridMode),
                    }))
                  }
                  title={t('Crop guide: {mode} (click to cycle)', {
                    mode: td(getGridLabel(draft.gridMode)),
                  })}
                  className="px-2 py-1 rounded-ui-xs text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover flex items-center gap-1.5 transition-colors cursor-pointer"
                >
                  <Grid3X3 className="w-3.5 h-3.5" />
                  <span className="hidden sm:inline">{td(getGridLabel(draft.gridMode))}</span>
                </button>

                <button
                  type="button"
                  disabled={!modified}
                  onClick={() =>
                    uiStoreActions.updateCanvasResizeDraft((prev) => applyResetCropToDraft(prev))
                  }
                  title={t('Reset crop frame to original canvas')}
                  className={`px-2 py-1 rounded-ui-xs flex items-center gap-1 transition-colors ${
                    modified
                      ? 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover cursor-pointer'
                      : 'text-ui-disabled cursor-default opacity-50'
                  }`}
                >
                  <RotateCcw className="w-3.5 h-3.5" />
                  <span>{t('Reset')}</span>
                </button>
              </>
            )}

            <button
              type="button"
              onClick={() =>
                uiStoreActions.updateCanvasResizeDraft((prev) => applySwapDimensionsToDraft(prev))
              }
              title={t('Swap Width and Height')}
              className="px-1.5 py-1 rounded-ui-xs text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover flex items-center gap-1 transition-colors cursor-pointer"
            >
              <ArrowLeftRight className="w-3.5 h-3.5" />
            </button>

            <button
              type="button"
              onClick={() => uiStoreActions.setResizeInspectorCollapsed(!isInspectorCollapsed)}
              title={
                isInspectorCollapsed
                  ? t('Show Resize Canvas settings panel')
                  : t('Hide Resize Canvas settings panel')
              }
              className={`px-2 py-1 rounded-ui-xs flex items-center gap-1 transition-colors cursor-pointer ${
                !isInspectorCollapsed
                  ? 'bg-ui-accent-subtle text-ui-accent border border-ui-accent-border'
                  : 'text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover border border-transparent'
              }`}
            >
              <SlidersHorizontal className="w-3.5 h-3.5" />
              <span className="hidden sm:inline">
                {isInspectorCollapsed ? t('Show Panel') : t('Panel')}
              </span>
            </button>

            <div className="w-px h-4 bg-ui-subtle mx-0.5" />

            <button
              type="button"
              onClick={handleCancel}
              title={t('Cancel (Esc)')}
              className="px-2 py-1 rounded-ui-xs text-ui-secondary hover:text-ui-primary hover:bg-ui-control-hover flex items-center gap-1 transition-colors cursor-pointer"
            >
              <X className="w-3.5 h-3.5" />
              <span>{t('Cancel')}</span>
            </button>

            <button
              type="button"
              onClick={handleConfirm}
              title={t('Apply Resize / Crop (Enter)')}
              className="px-2.5 py-1 rounded-ui-xs bg-ui-accent text-ui-accent-contrast hover:opacity-90 font-medium flex items-center gap-1 transition-opacity cursor-pointer"
            >
              <Check className="w-3.5 h-3.5" />
              <span>{draft.scaleContent ? t('Resize') : t('Apply')}</span>
            </button>
          </div>,
          document.body
        )}
    </>
  );
};