Skip to content

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

25.5 KB
Raw Blame
import { CanvasDimensions } from '../types/editor';
import { AnchorPosition, ResizeCanvasOptions } from '../types/settings';

export const MIN_CANVAS_DIM = 1;
export const MAX_CANVAS_DIM = 16384;

export type CropHandleId = 'nw' | 'n' | 'ne' | 'e' | 'se' | 's' | 'sw' | 'w' | 'move';
export type CropResizeHandleId = Exclude<CropHandleId, 'move'>;
export type CropGridMode = 'thirds' | 'golden' | 'none';

export interface CropRect {
  /** Left edge of the new canvas in current document pixel coordinates (negative expands left). */
  x: number;
  /** Top edge of the new canvas in current document pixel coordinates (negative expands top). */
  y: number;
  /** Width of the new canvas in pixels. */
  width: number;
  /** Height of the new canvas in pixels. */
  height: number;
}

export interface SnapTargets {
  x: number[];
  y: number[];
  threshold: number;
}

export interface SnapGuides {
  x?: number;
  y?: number;
}

export interface CanvasResizeDraft {
  originWidth: number;
  originHeight: number;
  cropX: number;
  cropY: number;
  width: number;
  height: number;
  dpi: number;
  scaleContent: boolean;
  /** Active anchor preset, or null when manually cropped/offset. */
  anchor: AnchorPosition | null;
  lockRatio: boolean;
  ratioX: number;
  ratioY: number;
  gridMode: CropGridMode;
}

export interface RatioPreset {
  label: string;
  x: number;
  y: number;
}

export const RATIO_PRESETS: RatioPreset[] = [
  { label: '16:9', x: 16, y: 9 },
  { label: '1:1', x: 1, y: 1 },
  { label: '4:3', x: 4, y: 3 },
  { label: '3:2', x: 3, y: 2 },
  { label: '9:16', x: 9, y: 16 },
  { label: '2:3', x: 2, y: 3 },
  { label: '21:9', x: 21, y: 9 },
];

export function clampCanvasDimension(value: number, min = MIN_CANVAS_DIM, max = MAX_CANVAS_DIM): number {
  if (!Number.isFinite(value)) return min;
  return Math.max(min, Math.min(max, Math.round(value)));
}

export function clampCropCoordinate(value: number): number {
  if (!Number.isFinite(value)) return 0;
  return Math.max(-MAX_CANVAS_DIM, Math.min(MAX_CANVAS_DIM, Math.round(value))) || 0;
}

/**
 * Computes the crop rectangle origin (cropX, cropY) in current document coordinates
 * corresponding to a standard 3x3 anchor alignment.
 *
 * Since ResizeCanvas shifts existing pixels by (offsetX, offsetY) into the new canvas,
 * the new canvas's (0, 0) lies at (-offsetX, -offsetY) in the old document coordinate system.
 */
export function computeCropOriginForAnchor(
  originWidth: number,
  originHeight: number,
  targetWidth: number,
  targetHeight: number,
  anchor: AnchorPosition
): { cropX: number; cropY: number } {
  let offsetX: number;
  if (anchor === 'top-left' || anchor === 'left' || anchor === 'bottom-left') {
    offsetX = 0;
  } else if (anchor === 'top-right' || anchor === 'right' || anchor === 'bottom-right') {
    offsetX = targetWidth - originWidth;
  } else {
    offsetX = Math.round((targetWidth - originWidth) / 2);
  }

  let offsetY: number;
  if (anchor === 'top-left' || anchor === 'top' || anchor === 'top-right') {
    offsetY = 0;
  } else if (anchor === 'bottom-left' || anchor === 'bottom' || anchor === 'bottom-right') {
    offsetY = targetHeight - originHeight;
  } else {
    offsetY = Math.round((targetHeight - originHeight) / 2);
  }

  return {
    cropX: -offsetX || 0,
    cropY: -offsetY || 0,
  };
}

export function createInitialCanvasResizeDraft(dimensions: CanvasDimensions): CanvasResizeDraft {
  const w = clampCanvasDimension(dimensions.width || 1920);
  const h = clampCanvasDimension(dimensions.height || 1080);
  const dpi = Math.max(1, Math.min(4800, Math.round(dimensions.dpi || 300)));
  return {
    originWidth: w,
    originHeight: h,
    cropX: 0,
    cropY: 0,
    width: w,
    height: h,
    dpi,
    scaleContent: false,
    anchor: 'center',
    lockRatio: false,
    ratioX: w,
    ratioY: h,
    gridMode: 'thirds',
  };
}

export function isCropModified(draft: CanvasResizeDraft): boolean {
  return (
    Math.round(draft.cropX) !== 0 ||
    Math.round(draft.cropY) !== 0 ||
    Math.round(draft.width) !== Math.round(draft.originWidth) ||
    Math.round(draft.height) !== Math.round(draft.originHeight)
  );
}

export function draftToResizeCanvasOptions(draft: CanvasResizeDraft): ResizeCanvasOptions {
  const width = clampCanvasDimension(draft.width);
  const height = clampCanvasDimension(draft.height);
  const dpi = Math.max(1, Math.min(4800, Math.round(draft.dpi || 300)));

  if (draft.scaleContent) {
    return {
      width,
      height,
      dpi,
      scaleContent: true,
      anchor: draft.anchor ?? 'center',
    };
  }

  return {
    width,
    height,
    dpi,
    scaleContent: false,
    anchor: draft.anchor ?? 'center',
    offsetX: -clampCropCoordinate(draft.cropX) || 0,
    offsetY: -clampCropCoordinate(draft.cropY) || 0,
  };
}

export function applyWidthToDraft(draft: CanvasResizeDraft, rawWidth: number): CanvasResizeDraft {
  const newW = clampCanvasDimension(rawWidth);
  let newH = draft.height;
  if (draft.lockRatio && draft.ratioX > 0 && draft.ratioY > 0) {
    newH = clampCanvasDimension((newW * draft.ratioY) / draft.ratioX);
  }
  const origin = draft.anchor
    ? computeCropOriginForAnchor(draft.originWidth, draft.originHeight, newW, newH, draft.anchor)
    : { cropX: draft.cropX, cropY: draft.cropY };
  return {
    ...draft,
    width: newW,
    height: newH,
    cropX: origin.cropX,
    cropY: origin.cropY,
    ratioX: draft.lockRatio ? draft.ratioX : newW,
    ratioY: draft.lockRatio ? draft.ratioY : newH,
  };
}

export function applyHeightToDraft(draft: CanvasResizeDraft, rawHeight: number): CanvasResizeDraft {
  const newH = clampCanvasDimension(rawHeight);
  let newW = draft.width;
  if (draft.lockRatio && draft.ratioX > 0 && draft.ratioY > 0) {
    newW = clampCanvasDimension((newH * draft.ratioX) / draft.ratioY);
  }
  const origin = draft.anchor
    ? computeCropOriginForAnchor(draft.originWidth, draft.originHeight, newW, newH, draft.anchor)
    : { cropX: draft.cropX, cropY: draft.cropY };
  return {
    ...draft,
    width: newW,
    height: newH,
    cropX: origin.cropX,
    cropY: origin.cropY,
    ratioX: draft.lockRatio ? draft.ratioX : newW,
    ratioY: draft.lockRatio ? draft.ratioY : newH,
  };
}

export function applyCropXToDraft(draft: CanvasResizeDraft, rawCropX: number): CanvasResizeDraft {
  return {
    ...draft,
    cropX: clampCropCoordinate(rawCropX),
    anchor: null,
  };
}

export function applyCropYToDraft(draft: CanvasResizeDraft, rawCropY: number): CanvasResizeDraft {
  return {
    ...draft,
    cropY: clampCropCoordinate(rawCropY),
    anchor: null,
  };
}

export function applyAnchorToDraft(
  draft: CanvasResizeDraft,
  anchor: AnchorPosition
): CanvasResizeDraft {
  const { cropX, cropY } = computeCropOriginForAnchor(
    draft.originWidth,
    draft.originHeight,
    draft.width,
    draft.height,
    anchor
  );
  return {
    ...draft,
    anchor,
    cropX,
    cropY,
  };
}

export function applyLockRatioToggleToDraft(
  draft: CanvasResizeDraft,
  lockRatio: boolean
): CanvasResizeDraft {
  return {
    ...draft,
    lockRatio,
    ratioX: lockRatio ? Math.max(1, draft.width) : draft.ratioX,
    ratioY: lockRatio ? Math.max(1, draft.height) : draft.ratioY,
  };
}

export function applyRatioPresetToDraft(
  draft: CanvasResizeDraft,
  ratioX: number,
  ratioY: number
): CanvasResizeDraft {
  if (ratioX <= 0 || ratioY <= 0) return draft;
  const prevCx = draft.cropX + draft.width / 2;
  const prevCy = draft.cropY + draft.height / 2;

  let newW = draft.width;
  let newH = Math.round((newW * ratioY) / ratioX);
  if (newH > MAX_CANVAS_DIM) {
    newH = MAX_CANVAS_DIM;
    newW = clampCanvasDimension((newH * ratioX) / ratioY);
  } else {
    newH = clampCanvasDimension(newH);
  }

  const origin = draft.anchor
    ? computeCropOriginForAnchor(draft.originWidth, draft.originHeight, newW, newH, draft.anchor)
    : {
        cropX: clampCropCoordinate(prevCx - newW / 2),
        cropY: clampCropCoordinate(prevCy - newH / 2),
      };

  return {
    ...draft,
    width: newW,
    height: newH,
    cropX: origin.cropX,
    cropY: origin.cropY,
    lockRatio: true,
    ratioX,
    ratioY,
  };
}

export function applySwapDimensionsToDraft(draft: CanvasResizeDraft): CanvasResizeDraft {
  const prevCx = draft.cropX + draft.width / 2;
  const prevCy = draft.cropY + draft.height / 2;
  const newW = draft.height;
  const newH = draft.width;

  const origin = draft.anchor
    ? computeCropOriginForAnchor(draft.originWidth, draft.originHeight, newW, newH, draft.anchor)
    : {
        cropX: clampCropCoordinate(prevCx - newW / 2),
        cropY: clampCropCoordinate(prevCy - newH / 2),
      };

  return {
    ...draft,
    width: newW,
    height: newH,
    cropX: origin.cropX,
    cropY: origin.cropY,
    ratioX: draft.ratioY,
    ratioY: draft.ratioX,
  };
}

export function applyResetCropToDraft(draft: CanvasResizeDraft): CanvasResizeDraft {
  return {
    ...draft,
    cropX: 0,
    cropY: 0,
    width: draft.originWidth,
    height: draft.originHeight,
    anchor: 'center',
    lockRatio: false,
    ratioX: draft.originWidth,
    ratioY: draft.originHeight,
  };
}

export function applyFitBoundsToDraft(
  draft: CanvasResizeDraft,
  bounds: { x: number; y: number; width: number; height: number }
): CanvasResizeDraft {
  const x = clampCropCoordinate(bounds.x);
  const y = clampCropCoordinate(bounds.y);
  const width = clampCanvasDimension(bounds.width);
  const height = clampCanvasDimension(bounds.height);
  return {
    ...draft,
    scaleContent: false,
    cropX: x,
    cropY: y,
    width,
    height,
    anchor: null,
    lockRatio: false,
    ratioX: width,
    ratioY: height,
  };
}

export function applyCropRectToDraft(
  draft: CanvasResizeDraft,
  rect: CropRect
): CanvasResizeDraft {
  const width = clampCanvasDimension(rect.width);
  const height = clampCanvasDimension(rect.height);
  const cropX = clampCropCoordinate(rect.x);
  const cropY = clampCropCoordinate(rect.y);
  return {
    ...draft,
    cropX,
    cropY,
    width,
    height,
    anchor: null,
    ratioX: draft.lockRatio ? draft.ratioX : width,
    ratioY: draft.lockRatio ? draft.ratioY : height,
  };
}

export function applyScaleContentToggleToDraft(
  draft: CanvasResizeDraft,
  scaleContent: boolean,
  autoLockRatioForResample = false
): CanvasResizeDraft {
  if (scaleContent === draft.scaleContent) return draft;
  if (scaleContent) {
    return {
      ...draft,
      scaleContent: true,
      lockRatio: autoLockRatioForResample ? true : draft.lockRatio,
      ratioX: autoLockRatioForResample ? draft.width : draft.ratioX,
      ratioY: autoLockRatioForResample ? draft.height : draft.ratioY,
    };
  }
  return {
    ...draft,
    scaleContent: false,
  };
}

export function nudgeCropDraft(
  draft: CanvasResizeDraft,
  dx: number,
  dy: number
): CanvasResizeDraft {
  if (draft.scaleContent) return draft;
  return {
    ...draft,
    cropX: clampCropCoordinate(draft.cropX + dx),
    cropY: clampCropCoordinate(draft.cropY + dy),
    anchor: null,
  };
}

export function cycleCropGridMode(current: CropGridMode): CropGridMode {
  if (current === 'thirds') return 'golden';
  if (current === 'golden') return 'none';
  return 'thirds';
}

function findClosestSnap(
  value: number,
  targets: number[],
  threshold: number
): { snapped: number; target?: number } {
  let bestTarget: number | undefined;
  let bestDist = threshold;
  for (let i = 0; i < targets.length; i++) {
    const d = Math.abs(value - targets[i]);
    if (d <= bestDist) {
      bestDist = d;
      bestTarget = targets[i];
    }
  }
  if (bestTarget !== undefined) {
    return { snapped: bestTarget, target: bestTarget };
  }
  return { snapped: value };
}

export interface HandleResizeOptions {
  lockAspect?: boolean;
  aspectRatio?: number;
  fromCenter?: boolean;
  minSize?: number;
  maxSize?: number;
  snapTargets?: SnapTargets | null;
}

/**
 * Resizes a CropRect by dragging one of the 8 corner or edge handles.
 * Supports free resize, aspect-locked resize (corners & edges), symmetric Alt-from-center,
 * clamping to [minSize, maxSize], and magnetic edge/center snapping.
 */
export function resizeCropRectByHandle(
  startRect: CropRect,
  handle: CropResizeHandleId,
  dx: number,
  dy: number,
  options: HandleResizeOptions = {}
): { rect: CropRect; snapGuides: SnapGuides } {
  const minSize = options.minSize ?? MIN_CANVAS_DIM;
  const maxSize = options.maxSize ?? MAX_CANVAS_DIM;
  const lockAspect = Boolean(options.lockAspect);
  const fromCenter = Boolean(options.fromCenter);
  const snapTargets = options.snapTargets ?? null;
  const snapGuides: SnapGuides = {};

  const startLeft = Math.round(startRect.x);
  const startTop = Math.round(startRect.y);
  const startW = clampCanvasDimension(startRect.width, minSize, maxSize);
  const startH = clampCanvasDimension(startRect.height, minSize, maxSize);
  const startRight = startLeft + startW;
  const startBottom = startTop + startH;
  const cx = startLeft + startW / 2;
  const cy = startTop + startH / 2;

  const hasW = handle.includes('w');
  const hasE = handle.includes('e');
  const hasN = handle.includes('n');
  const hasS = handle.includes('s');

  if (!lockAspect) {
    let x = startLeft;
    let y = startTop;
    let width = startW;
    let height = startH;

    if (fromCenter) {
      if (hasW || hasE) {
        const rawHalf = Math.max(minSize / 2, startW / 2 + (hasE ? dx : -dx));
        let targetW = rawHalf * 2;
        if (snapTargets) {
          const edgePos = hasE ? cx + rawHalf : cx - rawHalf;
          const snap = findClosestSnap(edgePos, snapTargets.x, snapTargets.threshold);
          if (snap.target !== undefined) {
            targetW = Math.abs(snap.snapped - cx) * 2;
            snapGuides.x = snap.target;
          }
        }
        width = clampCanvasDimension(targetW, minSize, maxSize);
        x = Math.round(cx - width / 2);
      }
      if (hasN || hasS) {
        const rawHalf = Math.max(minSize / 2, startH / 2 + (hasS ? dy : -dy));
        let targetH = rawHalf * 2;
        if (snapTargets) {
          const edgePos = hasS ? cy + rawHalf : cy - rawHalf;
          const snap = findClosestSnap(edgePos, snapTargets.y, snapTargets.threshold);
          if (snap.target !== undefined) {
            targetH = Math.abs(snap.snapped - cy) * 2;
            snapGuides.y = snap.target;
          }
        }
        height = clampCanvasDimension(targetH, minSize, maxSize);
        y = Math.round(cy - height / 2);
      }
    } else {
      if (hasW) {
        let nextLeft = startLeft + dx;
        if (snapTargets) {
          const snap = findClosestSnap(nextLeft, snapTargets.x, snapTargets.threshold);
          if (snap.target !== undefined) {
            nextLeft = snap.snapped;
            snapGuides.x = snap.target;
          }
        }
        width = clampCanvasDimension(startRight - nextLeft, minSize, maxSize);
        x = startRight - width;
      } else if (hasE) {
        let nextRight = startRight + dx;
        if (snapTargets) {
          const snap = findClosestSnap(nextRight, snapTargets.x, snapTargets.threshold);
          if (snap.target !== undefined) {
            nextRight = snap.snapped;
            snapGuides.x = snap.target;
          }
        }
        width = clampCanvasDimension(nextRight - startLeft, minSize, maxSize);
        x = startLeft;
      }

      if (hasN) {
        let nextTop = startTop + dy;
        if (snapTargets) {
          const snap = findClosestSnap(nextTop, snapTargets.y, snapTargets.threshold);
          if (snap.target !== undefined) {
            nextTop = snap.snapped;
            snapGuides.y = snap.target;
          }
        }
        height = clampCanvasDimension(startBottom - nextTop, minSize, maxSize);
        y = startBottom - height;
      } else if (hasS) {
        let nextBottom = startBottom + dy;
        if (snapTargets) {
          const snap = findClosestSnap(nextBottom, snapTargets.y, snapTargets.threshold);
          if (snap.target !== undefined) {
            nextBottom = snap.snapped;
            snapGuides.y = snap.target;
          }
        }
        height = clampCanvasDimension(nextBottom - startTop, minSize, maxSize);
        y = startTop;
      }
    }

    return {
      rect: {
        x: clampCropCoordinate(x),
        y: clampCropCoordinate(y),
        width,
        height,
      },
      snapGuides,
    };
  }

  // Aspect-locked resize
  const rawRatio = options.aspectRatio;
  const r =
    typeof rawRatio === 'number' && Number.isFinite(rawRatio) && rawRatio > 0
      ? rawRatio
      : startW / Math.max(1, startH);

  const minW = Math.min(maxSize, Math.max(minSize, Math.ceil(minSize * r)));
  const maxW = Math.max(minW, Math.min(maxSize, Math.floor(maxSize * r)));
  const minH = Math.min(maxSize, Math.max(minSize, Math.ceil(minSize / r)));
  const maxH = Math.max(minH, Math.min(maxSize, Math.floor(maxSize / r)));

  const isCorner = (hasW || hasE) && (hasN || hasS);
  let width = startW;
  let height = startH;

  if (isCorner) {
    let rawW = fromCenter
      ? startW + 2 * (hasE ? dx : -dx)
      : startW + (hasE ? dx : -dx);
    let rawH = fromCenter
      ? startH + 2 * (hasS ? dy : -dy)
      : startH + (hasS ? dy : -dy);

    // Optional edge snap before aspect projection
    if (snapTargets && !fromCenter) {
      const candX = hasE ? startLeft + rawW : startRight - rawW;
      const snapX = findClosestSnap(candX, snapTargets.x, snapTargets.threshold);
      const candY = hasS ? startTop + rawH : startBottom - rawH;
      const snapY = findClosestSnap(candY, snapTargets.y, snapTargets.threshold);
      if (snapX.target !== undefined) {
        rawW = hasE ? snapX.snapped - startLeft : startRight - snapX.snapped;
        rawH = rawW / r;
        snapGuides.x = snapX.target;
      } else if (snapY.target !== undefined) {
        rawH = hasS ? snapY.snapped - startTop : startBottom - snapY.snapped;
        rawW = rawH * r;
        snapGuides.y = snapY.target;
      }
    }

    // Smooth orthogonal projection onto aspect line (w = h * r)
    const projH = (rawW * r + rawH) / (r * r + 1);
    const projW = projH * r;
    width = clampCanvasDimension(projW, minW, maxW);
    height = clampCanvasDimension(width / r, minSize, maxSize);

    const x = fromCenter
      ? Math.round(cx - width / 2)
      : hasW
        ? startRight - width
        : startLeft;
    const y = fromCenter
      ? Math.round(cy - height / 2)
      : hasN
        ? startBottom - height
        : startTop;

    return {
      rect: { x: clampCropCoordinate(x), y: clampCropCoordinate(y), width, height },
      snapGuides,
    };
  }

  // Horizontal edge handle (e or w) with locked aspect
  if (hasW || hasE) {
    let rawW = fromCenter
      ? startW + 2 * (hasE ? dx : -dx)
      : startW + (hasE ? dx : -dx);
    if (snapTargets && !fromCenter) {
      const candX = hasE ? startLeft + rawW : startRight - rawW;
      const snapX = findClosestSnap(candX, snapTargets.x, snapTargets.threshold);
      if (snapX.target !== undefined) {
        rawW = hasE ? snapX.snapped - startLeft : startRight - snapX.snapped;
        snapGuides.x = snapX.target;
      }
    }
    width = clampCanvasDimension(rawW, minW, maxW);
    height = clampCanvasDimension(width / r, minSize, maxSize);
    const x = fromCenter
      ? Math.round(cx - width / 2)
      : hasW
        ? startRight - width
        : startLeft;
    const y = Math.round(cy - height / 2);
    return {
      rect: { x: clampCropCoordinate(x), y: clampCropCoordinate(y), width, height },
      snapGuides,
    };
  }

  // Vertical edge handle (n or s) with locked aspect
  let rawH = fromCenter
    ? startH + 2 * (hasS ? dy : -dy)
    : startH + (hasS ? dy : -dy);
  if (snapTargets && !fromCenter) {
    const candY = hasS ? startTop + rawH : startBottom - rawH;
    const snapY = findClosestSnap(candY, snapTargets.y, snapTargets.threshold);
    if (snapY.target !== undefined) {
      rawH = hasS ? snapY.snapped - startTop : startBottom - snapY.snapped;
      snapGuides.y = snapY.target;
    }
  }
  height = clampCanvasDimension(rawH, minH, maxH);
  width = clampCanvasDimension(height * r, minSize, maxSize);
  const x = Math.round(cx - width / 2);
  const y = fromCenter
    ? Math.round(cy - height / 2)
    : hasN
      ? startBottom - height
      : startTop;
  return {
    rect: { x: clampCropCoordinate(x), y: clampCropCoordinate(y), width, height },
    snapGuides,
  };
}

export interface MoveCropOptions {
  constrainAxis?: boolean;
  snapTargets?: SnapTargets | null;
}

/**
 * Moves a CropRect by (dx, dy) in document pixel space with optional Shift axis locking
 * and magnetic snapping of left/center/right and top/middle/bottom edges.
 */
export function moveCropRect(
  startRect: CropRect,
  dx: number,
  dy: number,
  options: MoveCropOptions = {}
): { rect: CropRect; snapGuides: SnapGuides } {
  let effDx = dx;
  let effDy = dy;
  if (options.constrainAxis) {
    if (Math.abs(effDx) >= Math.abs(effDy)) {
      effDy = 0;
    } else {
      effDx = 0;
    }
  }

  let nextX = Math.round(startRect.x + effDx);
  let nextY = Math.round(startRect.y + effDy);
  const width = clampCanvasDimension(startRect.width);
  const height = clampCanvasDimension(startRect.height);
  const snapGuides: SnapGuides = {};

  const snapTargets = options.snapTargets;
  if (snapTargets) {
    // Check left, right, center X
    let bestDx = Infinity;
    let bestTargetX: number | undefined;
    const xEdges = [nextX, nextX + width, nextX + width / 2];
    for (const edge of xEdges) {
      for (const t of snapTargets.x) {
        const dist = Math.abs(edge - t);
        if (dist <= snapTargets.threshold && dist < Math.abs(bestDx)) {
          bestDx = t - edge;
          bestTargetX = t;
        }
      }
    }
    if (bestTargetX !== undefined) {
      nextX = Math.round(nextX + bestDx);
      snapGuides.x = bestTargetX;
    }

    // Check top, bottom, center Y
    let bestDy = Infinity;
    let bestTargetY: number | undefined;
    const yEdges = [nextY, nextY + height, nextY + height / 2];
    for (const edge of yEdges) {
      for (const t of snapTargets.y) {
        const dist = Math.abs(edge - t);
        if (dist <= snapTargets.threshold && dist < Math.abs(bestDy)) {
          bestDy = t - edge;
          bestTargetY = t;
        }
      }
    }
    if (bestTargetY !== undefined) {
      nextY = Math.round(nextY + bestDy);
      snapGuides.y = bestTargetY;
    }
  }

  return {
    rect: {
      x: clampCropCoordinate(nextX),
      y: clampCropCoordinate(nextY),
      width,
      height,
    },
    snapGuides,
  };
}

export interface MarqueeCropOptions {
  lockAspect?: boolean;
  aspectRatio?: number;
  fromCenter?: boolean;
  minSize?: number;
  maxSize?: number;
  snapTargets?: SnapTargets | null;
}

/**
 * Creates a brand-new CropRect by click-dragging on the canvas outside the current crop box.
 */
export function createCropRectFromDrag(
  startPt: { x: number; y: number },
  curPt: { x: number; y: number },
  options: MarqueeCropOptions = {}
): { rect: CropRect; snapGuides: SnapGuides } {
  const minSize = options.minSize ?? MIN_CANVAS_DIM;
  const maxSize = options.maxSize ?? MAX_CANVAS_DIM;
  const lockAspect = Boolean(options.lockAspect);
  const fromCenter = Boolean(options.fromCenter);
  const snapTargets = options.snapTargets ?? null;
  const snapGuides: SnapGuides = {};

  let sx = Math.round(startPt.x);
  let sy = Math.round(startPt.y);
  let ex = Math.round(curPt.x);
  let ey = Math.round(curPt.y);

  if (snapTargets) {
    const snapEx = findClosestSnap(ex, snapTargets.x, snapTargets.threshold);
    if (snapEx.target !== undefined) {
      ex = Math.round(snapEx.snapped);
      snapGuides.x = snapEx.target;
    }
    const snapEy = findClosestSnap(ey, snapTargets.y, snapTargets.threshold);
    if (snapEy.target !== undefined) {
      ey = Math.round(snapEy.snapped);
      snapGuides.y = snapEy.target;
    }
  }

  let rawDx = ex - sx;
  let rawDy = ey - sy;
  const signX = rawDx >= 0 ? 1 : -1;
  const signY = rawDy >= 0 ? 1 : -1;
  let absW = Math.abs(rawDx) * (fromCenter ? 2 : 1);
  let absH = Math.abs(rawDy) * (fromCenter ? 2 : 1);

  if (lockAspect) {
    const r =
      typeof options.aspectRatio === 'number' &&
      Number.isFinite(options.aspectRatio) &&
      options.aspectRatio > 0
        ? options.aspectRatio
        : 1;
    if (absW / r >= absH) {
      absH = absW / r;
    } else {
      absW = absH * r;
    }
  }

  const width = clampCanvasDimension(absW, minSize, maxSize);
  const height = clampCanvasDimension(absH, minSize, maxSize);

  let x: number;
  let y: number;
  if (fromCenter) {
    x = Math.round(sx - width / 2);
    y = Math.round(sy - height / 2);
  } else {
    x = signX >= 0 ? sx : sx - width;
    y = signY >= 0 ? sy : sy - height;
  }

  return {
    rect: {
      x: clampCropCoordinate(x),
      y: clampCropCoordinate(y),
      width,
      height,
    },
    snapGuides,
  };
}

const HANDLE_NORMALS: Record<CropResizeHandleId, [number, number]> = {
  e: [1, 0],
  se: [1, 1],
  s: [0, 1],
  sw: [-1, 1],
  w: [-1, 0],
  nw: [-1, -1],
  n: [0, -1],
  ne: [1, -1],
};

/**
 * Computes the true screen-space CSS resize cursor for a crop handle,
 * compensating for arbitrary viewport rotation, flipX, and flipY.
 */
export function getRotatedResizeCursor(
  handle: CropHandleId,
  rotationDeg: number,
  flipX = false,
  flipY = false
): string {
  if (handle === 'move') return 'move';
  const [nx, ny] = HANDLE_NORMALS[handle];
  const fx = flipX ? -nx : nx;
  const fy = flipY ? -ny : ny;
  const rad = (rotationDeg * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const sx = fx * cos - fy * sin;
  const sy = fx * sin + fy * cos;

  let deg = (Math.atan2(sy, sx) * 180) / Math.PI;
  deg = ((deg % 180) + 180) % 180;

  if (deg < 22.5 || deg >= 157.5) return 'ew-resize';
  if (deg < 67.5) return 'nwse-resize';
  if (deg < 112.5) return 'ns-resize';
  return 'nesw-resize';
}