Skip to content

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

14.1 KB
Raw Blame
import React from 'react';
import { RotateCw } from 'lucide-react';
import type {
  CanvasDimensions,
  GradientDragPreview,
  GradientMeshState,
} from '../types/editor';
import {
  getGradientMeshBounds,
  getGradientMeshCentroid,
  getSelectedMeshNodeIndices,
} from '../utils/toolConfigs';
import { useI18n } from '../i18n';

export interface GradientOverlayProps {
  dimensions: CanvasDimensions;
  zoom: number;
  flipX: boolean;
  flipY: boolean;
  dragPreview: GradientDragPreview | null;
  mesh: GradientMeshState | null;
  marqueeRect?: { x: number; y: number; width: number; height: number } | null;
  isRotatingMesh?: boolean;
  opacity: number;
  onApplyMesh?: () => void;
  onCancelMesh?: () => void;
  onStartRotateMesh?: (e: React.PointerEvent<HTMLElement>) => void;
}

export const GradientOverlay: React.FC<GradientOverlayProps> = React.memo(
  ({
    dimensions,
    zoom,
    flipX,
    flipY,
    dragPreview,
    mesh,
    marqueeRect = null,
    isRotatingMesh = false,
    opacity: _opacity,
    onApplyMesh,
    onCancelMesh,
    onStartRotateMesh,
  }) => {
    const { t } = useI18n();
    const invZoom = 1 / Math.max(0.05, zoom);

    if (!dragPreview && !mesh) return null;

    return (
      <>
        {dragPreview && (() => {
          const { start, end, type } = dragPreview;
          const dx = end.x - start.x;
          const dy = end.y - start.y;
          const dist = Math.hypot(dx, dy);
          const angleDeg = ((Math.atan2(dy, dx) * 180) / Math.PI + 360) % 360;
          return (
            <>
              <svg
                className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"
                viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}
              >
                {type === 'radial' && dist > 1 && (
                  <circle
                    cx={start.x}
                    cy={start.y}
                    r={dist}
                    fill="none"
                    stroke="#ffffff"
                    strokeOpacity={0.75}
                    strokeWidth={1.5 * invZoom}
                    strokeDasharray={`${6 * invZoom} ${4 * invZoom}`}
                  />
                )}
                <line
                  x1={start.x}
                  y1={start.y}
                  x2={end.x}
                  y2={end.y}
                  stroke="#000000"
                  strokeOpacity={0.7}
                  strokeWidth={3 * invZoom}
                />
                <line
                  x1={start.x}
                  y1={start.y}
                  x2={end.x}
                  y2={end.y}
                  stroke="#ffffff"
                  strokeWidth={1.5 * invZoom}
                />
                <circle
                  cx={start.x}
                  cy={start.y}
                  r={5 * invZoom}
                  fill="#ffffff"
                  stroke="#000000"
                  strokeWidth={1.5 * invZoom}
                />
                <circle
                  cx={end.x}
                  cy={end.y}
                  r={5 * invZoom}
                  fill="var(--ui-accent, #38bdf8)"
                  stroke="#000000"
                  strokeWidth={1.5 * invZoom}
                />
              </svg>
              <div
                className="absolute pointer-events-none z-35 px-1.5 py-0.5 rounded-ui-xs bg-ui-floating border border-ui-default text-ui-primary shadow-ui-floating font-ui-mono tabular-nums text-[10px] whitespace-nowrap"
                style={{
                  left: `${end.x}px`,
                  top: `${end.y}px`,
                  transform: `translate(${10 * invZoom}px, ${10 * invZoom}px) scale(${
                    (flipX ? -1 : 1) * invZoom
                  }, ${(flipY ? -1 : 1) * invZoom})`,
                  transformOrigin: 'top left',
                }}
              >
                {Math.round(dist)}px · {Math.round(angleDeg)}°
              </div>
            </>
          );
        })()}

        {mesh && (() => {
          const selectedIndices = getSelectedMeshNodeIndices(mesh);
          const selectedSet = new Set(selectedIndices);
          const bounds = getGradientMeshBounds(mesh);
          const centroid = getGradientMeshCentroid(mesh);
          const rotationDeg = Math.round(mesh.rotationDeg ?? 0);
          const handleX = centroid.x;
          const handleY = bounds.minY - 28 * invZoom;
          const barTop = Math.max(8, bounds.minY - 66 * invZoom);

          return (
            <>
              <svg
                className="absolute inset-0 w-full h-full pointer-events-none z-35 overflow-visible"
                viewBox={`0 0 ${dimensions.width} ${dimensions.height}`}
              >
                {/* Horizontal mesh wires */}
                {Array.from({ length: mesh.rows }).map((_, r) =>
                  Array.from({ length: mesh.cols - 1 }).map((__, c) => {
                    const a = mesh.nodes[r * mesh.cols + c];
                    const b = mesh.nodes[r * mesh.cols + c + 1];
                    if (!a || !b) return null;
                    return (
                      <line
                        key={`mh-${r}-${c}`}
                        x1={a.x}
                        y1={a.y}
                        x2={b.x}
                        y2={b.y}
                        stroke="#ffffff"
                        strokeOpacity={0.75}
                        strokeWidth={1.25 * invZoom}
                        strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}
                      />
                    );
                  })
                )}
                {/* Vertical mesh wires */}
                {Array.from({ length: mesh.rows - 1 }).map((_, r) =>
                  Array.from({ length: mesh.cols }).map((__, c) => {
                    const a = mesh.nodes[r * mesh.cols + c];
                    const b = mesh.nodes[(r + 1) * mesh.cols + c];
                    if (!a || !b) return null;
                    return (
                      <line
                        key={`mv-${r}-${c}`}
                        x1={a.x}
                        y1={a.y}
                        x2={b.x}
                        y2={b.y}
                        stroke="#ffffff"
                        strokeOpacity={0.75}
                        strokeWidth={1.25 * invZoom}
                        strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}
                      />
                    );
                  })
                )}

                {/* Rotation stem & center pivot crosshair */}
                {mesh.nodes.length > 0 && (
                  <g>
                    <line
                      x1={centroid.x}
                      y1={bounds.minY}
                      x2={handleX}
                      y2={handleY}
                      stroke="#000000"
                      strokeOpacity={0.6}
                      strokeWidth={2.5 * invZoom}
                    />
                    <line
                      x1={centroid.x}
                      y1={bounds.minY}
                      x2={handleX}
                      y2={handleY}
                      stroke="#38bdf8"
                      strokeWidth={1.25 * invZoom}
                    />
                    <circle
                      cx={centroid.x}
                      cy={centroid.y}
                      r={(isRotatingMesh ? 5 : 3.5) * invZoom}
                      fill="none"
                      stroke="#38bdf8"
                      strokeOpacity={isRotatingMesh ? 0.95 : 0.6}
                      strokeWidth={1.25 * invZoom}
                    />
                    <line
                      x1={centroid.x - 6 * invZoom}
                      y1={centroid.y}
                      x2={centroid.x + 6 * invZoom}
                      y2={centroid.y}
                      stroke="#38bdf8"
                      strokeOpacity={isRotatingMesh ? 0.95 : 0.6}
                      strokeWidth={1.1 * invZoom}
                    />
                    <line
                      x1={centroid.x}
                      y1={centroid.y - 6 * invZoom}
                      x2={centroid.x}
                      y2={centroid.y + 6 * invZoom}
                      stroke="#38bdf8"
                      strokeOpacity={isRotatingMesh ? 0.95 : 0.6}
                      strokeWidth={1.1 * invZoom}
                    />
                  </g>
                )}

                {/* Marquee multi-selection rectangle */}
                {marqueeRect && (marqueeRect.width > 1 || marqueeRect.height > 1) && (
                  <rect
                    x={marqueeRect.x}
                    y={marqueeRect.y}
                    width={marqueeRect.width}
                    height={marqueeRect.height}
                    fill="rgba(56, 189, 248, 0.14)"
                    stroke="#38bdf8"
                    strokeWidth={1.25 * invZoom}
                    strokeDasharray={`${4 * invZoom} ${3 * invZoom}`}
                  />
                )}

                {/* Draggable control nodes */}
                {mesh.nodes.map((node, idx) => {
                  const isSelected = selectedSet.has(idx);
                  const isPrimary = mesh.selectedNodeIndex === idx;
                  return (
                    <g key={`mn-${idx}`}>
                      {isSelected && (
                        <circle
                          cx={node.x}
                          cy={node.y}
                          r={11.5 * invZoom}
                          fill="none"
                          stroke={isPrimary ? '#38bdf8' : '#7dd3fc'}
                          strokeOpacity={0.75}
                          strokeWidth={1.5 * invZoom}
                        />
                      )}
                      <circle
                        cx={node.x}
                        cy={node.y}
                        r={(isSelected ? (isPrimary ? 8.5 : 7.5) : 6) * invZoom}
                        fill={node.color}
                        stroke={isSelected ? (isPrimary ? '#38bdf8' : '#e0f2fe') : '#ffffff'}
                        strokeWidth={(isSelected ? 2.5 : 1.75) * invZoom}
                      />
                    </g>
                  );
                })}
              </svg>

              {/* Interactive On-Canvas Rotation Handle (rotates all vertices simultaneously) */}
              {mesh.nodes.length > 0 && onStartRotateMesh && (
                <button
                  type="button"
                  title={t('Drag to rotate all mesh vertices (Shift: 15° snap)')}
                  onPointerDown={(e) => {
                    e.stopPropagation();
                    onStartRotateMesh(e);
                  }}
                  className={`absolute z-36 pointer-events-auto w-6 h-6 rounded-full flex items-center justify-center bg-ui-floating border text-ui-accent shadow-ui-floating transition-colors ${
                    isRotatingMesh
                      ? 'border-ui-accent bg-ui-accent-subtle cursor-grabbing'
                      : 'border-ui-default hover:border-ui-accent hover:bg-ui-control-hover cursor-grab'
                  }`}
                  style={{
                    left: `${handleX}px`,
                    top: `${handleY}px`,
                    transform: `translate(-50%, -50%) scale(${(flipX ? -1 : 1) * invZoom}, ${
                      (flipY ? -1 : 1) * invZoom
                    })`,
                    transformOrigin: 'center center',
                  }}
                >
                  <RotateCw className="w-3.5 h-3.5" />
                </button>
              )}

              {/* Live Rotation Angle Badge while dragging rotation handle */}
              {isRotatingMesh && (
                <div
                  className="absolute pointer-events-none z-40 px-1.5 py-0.5 rounded-ui-xs bg-ui-floating border border-ui-accent-border text-ui-primary font-ui-mono tabular-nums text-[10px] whitespace-nowrap shadow-ui-floating"
                  style={{
                    left: `${handleX}px`,
                    top: `${handleY - 20 * invZoom}px`,
                    transform: `translate(-50%, -50%) scale(${(flipX ? -1 : 1) * invZoom}, ${
                      (flipY ? -1 : 1) * invZoom
                    })`,
                    transformOrigin: 'center center',
                  }}
                >
                  {rotationDeg}°
                </div>
              )}

              {/* Floating Mesh Commit / Cancel Action Bar */}
              {mesh.nodes.length > 0 && (
                <div
                  onPointerDown={(e) => e.stopPropagation()}
                  className="absolute z-40 pointer-events-auto flex items-center gap-1 px-1.5 py-1 rounded-ui-sm bg-ui-floating border border-ui-default shadow-ui-floating text-ui-primary"
                  style={{
                    left: `${bounds.minX}px`,
                    top: `${barTop}px`,
                    transform: `scale(${(flipX ? -1 : 1) * invZoom}, ${(flipY ? -1 : 1) * invZoom})`,
                    transformOrigin: 'top left',
                  }}
                >
                  <span className="text-[10px] font-ui-mono tabular-nums text-ui-muted px-1 whitespace-nowrap">
                    {t('Mesh ({cols}×{rows})', { cols: mesh.cols, rows: mesh.rows })}
                    {selectedIndices.length > 0
                      ? t(' · {count} sel', { count: selectedIndices.length })
                      : ''}
                    {rotationDeg !== 0 ? ` · ${rotationDeg}°` : ''}
                  </span>
                  <button
                    type="button"
                    onClick={onApplyMesh}
                    className="px-2 py-0.5 rounded-ui-xs bg-ui-accent text-ui-accent-contrast hover:opacity-90 text-[10px] font-medium transition-opacity cursor-pointer"
                  >
                    {t('Apply')}
                  </button>
                  <button
                    type="button"
                    onClick={onCancelMesh}
                    className="px-2 py-0.5 rounded-ui-xs bg-ui-control hover:bg-ui-control-hover border border-ui-subtle text-ui-primary text-[10px] transition-colors cursor-pointer"
                  >
                    {t('Cancel')}
                  </button>
                </div>
              )}
            </>
          );
        })()}
      </>
    );
  }
);

GradientOverlay.displayName = 'GradientOverlay';