Skip to content

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

47.0 KB
Raw Blame
import React, { useEffect, useRef, useState, useCallback } from 'react';
import {
  ZoomIn,
  ZoomOut,
  Maximize,
  RotateCcw,
  RotateCw,
  FlipHorizontal,
  FlipVertical,
  Compass,
  Contrast,
  Columns2,
} from 'lucide-react';
import { CanvasDimensions, LayerItem } from '../types/editor';
import { ThemePreset } from '../types/settings';
import { NavigatorPreviewMode } from '../types/workspace';
import {
  isNativeCanvasActive,
  renderNativeNavigatorPreview,
  subscribeNativeCanvasActive,
  subscribeNativeHistory,
  subscribeNativeStrokeCommitted,
} from '../utils/nativeEngineBridge';
import { recoveryService } from '../services/recoveryService';
import { formatRotationDegrees } from '../utils/canvasUtils';
import {
  applyPerceptualGrayscaleToImageData,
  clampNavigatorSplitRatio,
  DEFAULT_NAVIGATOR_SPLIT_RATIO,
} from '../utils/valueCheck';
import {
  documentStoreActions,
  useDocumentStore,
  useWorkspaceStore,
  workspaceStoreActions,
} from '../stores';
import {
  CameraTransformState,
  CanvasNavigationHandle,
  MAX_ZOOM,
  MIN_ZOOM,
  formatZoomPercent,
} from '../hooks/useCanvasNavigation';
import { IconButton, ScrubSlider, SegmentedControl, type ScrubSliderHandle } from './ui';
import { useI18n } from '../i18n';

export const NAVIGATOR_PREVIEW_THROTTLE_MS = 200;
const PREVIEW_PADDING = 8;
const MAX_PREVIEW_LONG_EDGE = 256;
const SLIDER_MAX = 1000;

export interface DocPoint {
  x: number;
  y: number;
}

export interface PreviewBoxMetrics {
  stageW: number;
  stageH: number;
  offsetX: number;
  offsetY: number;
  drawW: number;
  drawH: number;
  scale: number;
}

/** Logarithmic zoom <-> slider [0..1000] mapping for CSP-like smooth zoom control. */
export function zoomToSliderPos(zoom: number): number {
  const clamped = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, Number.isFinite(zoom) ? zoom : 1));
  const minLog = Math.log(MIN_ZOOM);
  const maxLog = Math.log(MAX_ZOOM);
  return Math.round(((Math.log(clamped) - minLog) / (maxLog - minLog)) * SLIDER_MAX);
}

export function sliderPosToZoom(pos: number): number {
  const clamped = Math.max(0, Math.min(SLIDER_MAX, Number.isFinite(pos) ? pos : 0));
  const minLog = Math.log(MIN_ZOOM);
  const maxLog = Math.log(MAX_ZOOM);
  return Math.exp(minLog + (clamped / SLIDER_MAX) * (maxLog - minLog));
}

/**
 * Unprojects a viewport-local point `(vx, vy)` into document coordinates,
 * matching `screenToCanvas` with rotation and `flipX`/`flipY`.
 */
export function viewportPointToDoc(
  vx: number,
  vy: number,
  cam: CameraTransformState,
  dimensions: CanvasDimensions
): DocPoint {
  const safeZoom = Math.max(0.0001, Number.isFinite(cam?.zoom) ? cam.zoom : 1);
  const panX = Number.isFinite(cam?.pan?.x) ? cam.pan.x : 0;
  const panY = Number.isFinite(cam?.pan?.y) ? cam.pan.y : 0;
  const rot = Number.isFinite(cam?.rotation) ? cam.rotation : 0;
  const docW = Number.isFinite(dimensions?.width) ? dimensions.width : 1920;
  const docH = Number.isFinite(dimensions?.height) ? dimensions.height : 1080;
  const rx = vx - panX;
  const ry = vy - panY;
  const rad = (rot * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const unrotX = rx * cos + ry * sin;
  const unrotY = -rx * sin + ry * cos;
  const fx = cam?.flipX ? -1 : 1;
  const fy = cam?.flipY ? -1 : 1;
  return {
    x: docW / 2 + (fx * unrotX) / safeZoom,
    y: docH / 2 + (fy * unrotY) / safeZoom,
  };
}

/**
 * Returns the 4 corners [TL, TR, BR, BL] of the visible main viewport in document space.
 */
export function computeViewportQuadInDoc(
  viewportW: number,
  viewportH: number,
  cam: CameraTransformState,
  dimensions: CanvasDimensions
): [DocPoint, DocPoint, DocPoint, DocPoint] {
  return [
    viewportPointToDoc(0, 0, cam, dimensions),
    viewportPointToDoc(viewportW, 0, cam, dimensions),
    viewportPointToDoc(viewportW, viewportH, cam, dimensions),
    viewportPointToDoc(0, viewportH, cam, dimensions),
  ];
}

/**
 * Computes the exact `pan` that places `targetDoc` at the center of `(viewportW, viewportH)`
 * under the current zoom, rotation, flipX, and flipY.
 */
export function computePanForDocCenter(
  targetDoc: DocPoint,
  viewportW: number,
  viewportH: number,
  cam: Pick<CameraTransformState, 'zoom' | 'rotation' | 'flipX' | 'flipY'>,
  dimensions: CanvasDimensions
): { x: number; y: number } {
  const fx = cam.flipX ? -1 : 1;
  const fy = cam.flipY ? -1 : 1;
  const dx = (targetDoc.x - dimensions.width / 2) * fx;
  const dy = (targetDoc.y - dimensions.height / 2) * fy;
  const rad = (cam.rotation * Math.PI) / 180;
  const cos = Math.cos(rad);
  const sin = Math.sin(rad);
  const rx = cam.zoom * (dx * cos - dy * sin);
  const ry = cam.zoom * (dx * sin + dy * cos);
  return {
    x: viewportW / 2 - rx,
    y: viewportH / 2 - ry,
  };
}

/** Point-in-convex-quad test (orientation invariant to handle mirrored flipX/flipY quads). */
export function isPointInConvexQuad(
  pt: DocPoint,
  quad: [DocPoint, DocPoint, DocPoint, DocPoint]
): boolean {
  if (!pt || !Array.isArray(quad) || quad.length < 4) return false;
  let sign = 0;
  for (let i = 0; i < 4; i++) {
    const a = quad[i];
    const b = quad[(i + 1) % 4];
    if (!a || !b) return false;
    const cross = (b.x - a.x) * (pt.y - a.y) - (b.y - a.y) * (pt.x - a.x);
    if (Math.abs(cross) < 1e-6) continue;
    const s = cross > 0 ? 1 : -1;
    if (sign === 0) sign = s;
    else if (sign !== s) return false;
  }
  return true;
}

export function computePreviewBoxMetrics(
  stageW: number,
  stageH: number,
  dimensions: CanvasDimensions
): PreviewBoxMetrics {
  const safeW = Math.max(24, stageW);
  const safeH = Math.max(24, stageH);
  const docW = Math.max(1, dimensions.width);
  const docH = Math.max(1, dimensions.height);
  const availW = Math.max(12, safeW - PREVIEW_PADDING * 2);
  const availH = Math.max(12, safeH - PREVIEW_PADDING * 2);
  const scale = Math.min(availW / docW, availH / docH);
  const drawW = Math.max(1, docW * scale);
  const drawH = Math.max(1, docH * scale);
  return {
    stageW: safeW,
    stageH: safeH,
    offsetX: (safeW - drawW) / 2,
    offsetY: (safeH - drawH) / 2,
    drawW,
    drawH,
    scale,
  };
}

/**
 * Maps a pointer's clientX inside the Navigator preview stage to a clamped [0.05..0.95]
 * Color | B/W split ratio relative to the document thumbnail rectangle.
 */
export function computeNavigatorSplitRatioFromClientX(
  clientX: number,
  stageLeft: number,
  metrics: PreviewBoxMetrics
): number {
  const localX = clientX - stageLeft;
  const rel = (localX - metrics.offsetX) / Math.max(1, metrics.drawW);
  return clampNavigatorSplitRatio(rel);
}

export interface NavigatorPanelProps {
  viewportRef: React.RefObject<HTMLDivElement | null>;
  navigation: CanvasNavigationHandle;
  dimensions: CanvasDimensions;
  layers: LayerItem[];
  showCheckerboard: boolean;
  zoom: number;
  rotation: number;
  flipX: boolean;
  flipY: boolean;
  onZoomIn: () => void;
  onZoomOut: () => void;
  onFitToScreen: () => void;
  onZoomActualSize: () => void;
  onRotateLeft: () => void;
  onRotateRight: () => void;
  onResetRotation: () => void;
  onToggleFlipHorizontal: () => void;
  onToggleFlipVertical: () => void;
  activeLayerId?: string;
  previewMode?: NavigatorPreviewMode;
  onChangePreviewMode?: (mode: NavigatorPreviewMode) => void;
  splitRatio?: number;
  onChangeSplitRatio?: (ratio: number, persist?: boolean) => void;
  valueCheckEnabled?: boolean;
  onToggleValueCheck?: () => void;
  themePreset?: ThemePreset;
  throttleMs?: number;
}

export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(
  ({
    viewportRef,
    navigation,
    dimensions,
    layers,
    showCheckerboard,
    zoom,
    rotation,
    flipX,
    flipY,
    onZoomIn,
    onZoomOut,
    onFitToScreen,
    onZoomActualSize,
    onRotateLeft,
    onRotateRight,
    onResetRotation,
    onToggleFlipHorizontal,
    onToggleFlipVertical,
    activeLayerId,
    previewMode: previewModeProp,
    onChangePreviewMode,
    splitRatio: splitRatioProp,
    onChangeSplitRatio,
    valueCheckEnabled: valueCheckProp,
    onToggleValueCheck,
    themePreset = 'modern',
    throttleMs = NAVIGATOR_PREVIEW_THROTTLE_MS,
  }) => {
    const { t } = useI18n();
    const storePreviewMode = useWorkspaceStore((s) => s.navigatorPreviewMode);
    const storeSplitRatio = useWorkspaceStore((s) => s.navigatorSplitRatio);
    const storeValueCheckEnabled = useDocumentStore((s) => s.valueCheckEnabled);

    const activePreviewMode: NavigatorPreviewMode = previewModeProp ?? storePreviewMode;
    const activeSplitRatio = clampNavigatorSplitRatio(splitRatioProp ?? storeSplitRatio);
    const isValueCheckEnabled = valueCheckProp ?? storeValueCheckEnabled;

    const handleSelectPreviewMode = useCallback(
      (mode: NavigatorPreviewMode) => {
        if (onChangePreviewMode) {
          onChangePreviewMode(mode);
        } else {
          workspaceStoreActions.setNavigatorPreviewMode(mode);
        }
      },
      [onChangePreviewMode]
    );

    const handleUpdateSplitRatio = useCallback(
      (ratio: number, persist = true) => {
        const clamped = clampNavigatorSplitRatio(ratio);
        if (onChangeSplitRatio) {
          onChangeSplitRatio(clamped, persist);
        } else {
          workspaceStoreActions.setNavigatorSplitRatio(clamped, persist);
        }
      },
      [onChangeSplitRatio]
    );

    const handleToggleValueCheck = useCallback(() => {
      if (onToggleValueCheck) {
        onToggleValueCheck();
      } else {
        documentStoreActions.toggleValueCheck();
      }
    }, [onToggleValueCheck]);

    const stageRef = useRef<HTMLDivElement | null>(null);
    const previewCanvasRef = useRef<HTMLCanvasElement | null>(null);
    const colorBufferCanvasRef = useRef<HTMLCanvasElement | null>(null);
    const bwBufferCanvasRef = useRef<HTMLCanvasElement | null>(null);
    const colorGenRef = useRef<number>(0);
    const bwGenRef = useRef<number>(-1);
    const overlayCanvasRef = useRef<HTMLCanvasElement | null>(null);
    const zoomSliderRef = useRef<ScrubSliderHandle | null>(null);
    const zoomLabelRef = useRef<HTMLSpanElement | null>(null);
    const angleLabelRef = useRef<HTMLSpanElement | null>(null);

    const [stageSize, setStageSize] = useState<{ width: number; height: number }>({
      width: 200,
      height: 120,
    });
    const [isDraggingFrame, setIsDraggingFrame] = useState(false);
    const [isDraggingSplit, setIsDraggingSplit] = useState(false);

    const metricsRef = useRef<PreviewBoxMetrics>(
      computePreviewBoxMetrics(200, 120, dimensions)
    );
    metricsRef.current = computePreviewBoxMetrics(stageSize.width, stageSize.height, dimensions);

    const latestSceneRef = useRef({
      layers,
      dimensions,
      showCheckerboard,
      activeLayerId,
      previewMode: activePreviewMode,
      splitRatio: activeSplitRatio,
    });
    latestSceneRef.current = {
      layers,
      dimensions,
      showCheckerboard,
      activeLayerId,
      previewMode: activePreviewMode,
      splitRatio: activeSplitRatio,
    };

    const splitDragRef = useRef<{
      active: boolean;
      pointerId: number | null;
      latestRatio: number;
    }>({
      active: false,
      pointerId: null,
      latestRatio: activeSplitRatio,
    });

    const dragStateRef = useRef<{
      active: boolean;
      pointerId: number | null;
      grabOffsetDoc: DocPoint;
    }>({
      active: false,
      pointerId: null,
      grabOffsetDoc: { x: 0, y: 0 },
    });

    const getMainViewportSize = useCallback((): { vw: number; vh: number } => {
      const vp = viewportRef.current;
      const vw = vp && vp.clientWidth > 0 ? vp.clientWidth : 800;
      const vh = vp && vp.clientHeight > 0 ? vp.clientHeight : 600;
      return { vw, vh };
    }, [viewportRef]);

    // Draw ONLY the red viewport frame overlay (60-240Hz via navigation.subscribeCamera, zero React re-renders)
    const drawViewportOverlay = useCallback(
      (cam?: CameraTransformState) => {
        const overlay = overlayCanvasRef.current;
        if (!overlay) return;
        const ctx = overlay.getContext('2d');
        if (!ctx) return;

        const m = metricsRef.current;
        const dpr = typeof window !== 'undefined' ? Math.min(2, window.devicePixelRatio || 1) : 1;
        const targetW = Math.max(1, Math.round(m.stageW * dpr));
        const targetH = Math.max(1, Math.round(m.stageH * dpr));
        if (overlay.width !== targetW || overlay.height !== targetH) {
          overlay.width = targetW;
          overlay.height = targetH;
        }

        ctx.save();
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        ctx.clearRect(0, 0, m.stageW, m.stageH);

        // Subtle document outline border
        ctx.strokeStyle = 'rgba(255, 255, 255, 0.16)';
        ctx.lineWidth = 1;
        ctx.strokeRect(
          Math.floor(m.offsetX) + 0.5,
          Math.floor(m.offsetY) + 0.5,
          Math.max(1, Math.round(m.drawW)),
          Math.max(1, Math.round(m.drawH))
        );

        const activeCam = cam ?? navigation.getCameraState();
        const sceneDims = latestSceneRef.current?.dimensions;
        if (!activeCam || !activeCam.pan || !sceneDims) {
          ctx.restore();
          return;
        }
        const { vw, vh } = getMainViewportSize();
        const quad = computeViewportQuadInDoc(vw, vh, activeCam, sceneDims);

        const pts = Array.isArray(quad)
          ? quad.map((p) => ({
              x: m.offsetX + p.x * m.scale,
              y: m.offsetY + p.y * m.scale,
            }))
          : [];

        if (
          pts.length < 4 ||
          pts.some((p) => !p || !Number.isFinite(p.x) || !Number.isFinite(p.y))
        ) {
          ctx.restore();
          return;
        }

        // Red viewport frame polygon
        ctx.beginPath();
        ctx.moveTo(pts[0].x, pts[0].y);
        ctx.lineTo(pts[1].x, pts[1].y);
        ctx.lineTo(pts[2].x, pts[2].y);
        ctx.lineTo(pts[3].x, pts[3].y);
        ctx.closePath();

        ctx.fillStyle = 'rgba(239, 68, 68, 0.08)';
        ctx.fill();
        ctx.strokeStyle = '#ef4444';
        ctx.lineWidth = 1.5;
        ctx.stroke();

        // Top-edge orientation indicator tick (makes rotation & flipY immediately readable)
        const topMidX = (pts[0].x + pts[1].x) * 0.5;
        const topMidY = (pts[0].y + pts[1].y) * 0.5;
        const cx = (pts[0].x + pts[2].x) * 0.5;
        const cy = (pts[0].y + pts[2].y) * 0.5;
        const vx = topMidX - cx;
        const vy = topMidY - cy;
        const len = Math.hypot(vx, vy);
        if (len > 4) {
          const ux = vx / len;
          const uy = vy / len;
          ctx.beginPath();
          ctx.moveTo(topMidX, topMidY);
          ctx.lineTo(topMidX + ux * 4, topMidY + uy * 4);
          ctx.strokeStyle = '#f87171';
          ctx.lineWidth = 1.5;
          ctx.stroke();
        }

        ctx.restore();

        // Live DOM sync for zoom slider/readout and angle without React re-render
        if (zoomSliderRef.current) {
          zoomSliderRef.current.setLiveValue(activeCam.zoom * 100);
        }
        if (zoomLabelRef.current) {
          zoomLabelRef.current.textContent = formatZoomPercent(activeCam.zoom);
        }
        if (angleLabelRef.current) {
          angleLabelRef.current.textContent = formatRotationDegrees(activeCam.rotation);
        }
      },
      [getMainViewportSize, navigation]
    );

    // Throttled low-LOD preview composite (<= 1 render per throttleMs during rapid brush strokes)
    const lastPreviewTsRef = useRef<number>(0);
    const previewTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);

    const ensureBwBufferSynced = useCallback(
      (colorCanvas: HTMLCanvasElement, targetW: number, targetH: number): HTMLCanvasElement | null => {
        if (typeof document === 'undefined') return null;
        if (!bwBufferCanvasRef.current) {
          bwBufferCanvasRef.current = document.createElement('canvas');
        }
        const bwCanvas = bwBufferCanvasRef.current;
        if (bwCanvas.width !== targetW) bwCanvas.width = targetW;
        if (bwCanvas.height !== targetH) bwCanvas.height = targetH;

        if (bwGenRef.current === colorGenRef.current) {
          return bwCanvas;
        }

        const bwCtx = bwCanvas.getContext('2d', { willReadFrequently: true });
        if (!bwCtx) return null;

        bwCtx.clearRect(0, 0, targetW, targetH);
        bwCtx.drawImage(colorCanvas, 0, 0);
        try {
          const imgData = bwCtx.getImageData(0, 0, targetW, targetH);
          applyPerceptualGrayscaleToImageData(imgData);
          bwCtx.putImageData(imgData, 0, 0);
        } catch {
          // Ignore in headless/mock contexts without getImageData
        }
        bwGenRef.current = colorGenRef.current;
        return bwCanvas;
      },
      []
    );

    const presentPreviewToDisplay = useCallback(
      (overrideMode?: NavigatorPreviewMode, overrideSplitRatio?: number) => {
        const displayCanvas = previewCanvasRef.current;
        const colorCanvas = colorBufferCanvasRef.current;
        if (!displayCanvas || !colorCanvas) return;
        const w = Math.max(1, colorCanvas.width);
        const h = Math.max(1, colorCanvas.height);
        if (displayCanvas.width !== w) displayCanvas.width = w;
        if (displayCanvas.height !== h) displayCanvas.height = h;

        const displayCtx = displayCanvas.getContext('2d');
        if (!displayCtx) return;

        const mode = overrideMode ?? latestSceneRef.current.previewMode;
        const ratio = clampNavigatorSplitRatio(
          overrideSplitRatio ?? latestSceneRef.current.splitRatio
        );

        displayCtx.save();
        displayCtx.setTransform(1, 0, 0, 1, 0, 0);
        displayCtx.clearRect(0, 0, w, h);

        if (mode === 'color') {
          displayCtx.drawImage(colorCanvas, 0, 0);
        } else {
          const bwCanvas = ensureBwBufferSynced(colorCanvas, w, h);
          if (mode === 'bw') {
            displayCtx.drawImage(bwCanvas ?? colorCanvas, 0, 0);
          } else {
            // Split View: Left = Color, Right = Live perceptual B/W tones
            const splitPx = Math.max(0, Math.min(w, Math.round(w * ratio)));
            if (splitPx > 0) {
              displayCtx.drawImage(colorCanvas, 0, 0, splitPx, h, 0, 0, splitPx, h);
            }
            if (splitPx < w) {
              displayCtx.drawImage(
                bwCanvas ?? colorCanvas,
                splitPx,
                0,
                w - splitPx,
                h,
                splitPx,
                0,
                w - splitPx,
                h
              );
            }
          }
        }

        displayCtx.restore();
      },
      [ensureBwBufferSynced]
    );

    const nativePreviewReqRef = useRef<number>(0);

    const renderPreviewNow = useCallback(() => {
      const displayCanvas = previewCanvasRef.current;
      if (!displayCanvas || typeof document === 'undefined') return;
      const {
        dimensions: curDims,
        showCheckerboard: curCheck,
      } = latestSceneRef.current;
      const docW = Math.max(1, curDims.width);
      const docH = Math.max(1, curDims.height);
      const scale = Math.min(1, MAX_PREVIEW_LONG_EDGE / Math.max(docW, docH));
      const targetW = Math.max(1, Math.round(docW * scale));
      const targetH = Math.max(1, Math.round(docH * scale));

      if (!colorBufferCanvasRef.current) {
        colorBufferCanvasRef.current = document.createElement('canvas');
      }
      const colorCanvas = colorBufferCanvasRef.current;
      if (colorCanvas.width !== targetW) colorCanvas.width = targetW;
      if (colorCanvas.height !== targetH) colorCanvas.height = targetH;

      lastPreviewTsRef.current = Date.now();

      if (isNativeCanvasActive()) {
        const reqId = ++nativePreviewReqRef.current;
        const activeDocId = useDocumentStore.getState().activeDocumentId;
        void renderNativeNavigatorPreview({
          docId: activeDocId,
          maxDim: MAX_PREVIEW_LONG_EDGE,
          showCheckerboard: curCheck,
        }).then((img) => {
          if (reqId !== nativePreviewReqRef.current || !img) return;
          const buf = colorBufferCanvasRef.current;
          if (!buf) return;
          if (buf.width !== img.width) buf.width = img.width;
          if (buf.height !== img.height) buf.height = img.height;
          const bCtx = buf.getContext('2d');
          if (!bCtx) return;
          if (typeof ImageData !== 'undefined') {
            bCtx.putImageData(new ImageData(img.rgba, img.width, img.height), 0, 0);
          } else if (typeof bCtx.createImageData === 'function') {
            const imgData = bCtx.createImageData(img.width, img.height);
            imgData.data.set(img.rgba);
            bCtx.putImageData(imgData, 0, 0);
          }
          colorGenRef.current += 1;
          presentPreviewToDisplay();
        });
        return;
      }

      // Headless / Vitest fallback: draw clean backdrop so Navigator preview stays defined
      const bCtx = colorCanvas.getContext('2d');
      if (bCtx) {
        bCtx.save();
        bCtx.setTransform(1, 0, 0, 1, 0, 0);
        bCtx.fillStyle = curCheck ? '#242424' : '#ffffff';
        bCtx.fillRect(0, 0, targetW, targetH);
        bCtx.restore();
      }
      colorGenRef.current += 1;
      presentPreviewToDisplay();
    }, [presentPreviewToDisplay]);

    const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
    const palettesHiddenRef = useRef(palettesHidden);
    palettesHiddenRef.current = palettesHidden;
    const hasRenderedInitialRef = useRef(false);
    const pendingRefreshRef = useRef(false);
    const wasStageZeroRef = useRef(false);

    const isNavigatorHidden = useCallback((): boolean => {
      if (palettesHiddenRef.current) return true;
      if (typeof document !== 'undefined' && document.hidden) return true;
      const stage = stageRef.current;
      if (stage && typeof stage.getBoundingClientRect === 'function') {
        const rect = stage.getBoundingClientRect();
        if (rect.width <= 0 || rect.height <= 0) return true;
      }
      return false;
    }, []);

    // Compact structural visual signature for layers — intentionally EXCLUDES `thumbnailUrl`
    // and `maskThumbnailUrl` so async thumbnail updates NEVER trigger redundant Navigator readbacks.
    const layersVisualSig = Array.isArray(layers)
      ? layers
          .map(
            (l) =>
              `${l.id}:${l.visible ? 1 : 0}:${l.opacity}:${l.blendMode}:${l.clipped ? 1 : 0}:${l.maskEnabled ? 1 : 0}:${l.maskLinked ? 1 : 0}:${l.parentId ?? ''}:${l.type}`
          )
          .join('|')
      : '';

    const scheduleThrottledPreview = useCallback(
      (deferSync: boolean = true, effectiveThrottleOverride?: number) => {
        const waitMs = effectiveThrottleOverride ?? throttleMs;

        // Skip GPU readbacks while actively drawing or while the Navigator panel is collapsed/hidden;
        // remember that a refresh is needed so it flushes once drawing stops or panel becomes visible.
        if (recoveryService.getIsDrawingActive() || isNavigatorHidden()) {
          pendingRefreshRef.current = true;
          if (previewTimerRef.current !== null) {
            clearTimeout(previewTimerRef.current);
            previewTimerRef.current = null;
          }
          return;
        }

        if (!deferSync && waitMs <= 0) {
          if (previewTimerRef.current !== null) {
            clearTimeout(previewTimerRef.current);
            previewTimerRef.current = null;
          }
          pendingRefreshRef.current = false;
          hasRenderedInitialRef.current = true;
          renderPreviewNow();
          return;
        }

        // True trailing debounce: reset timer on every burst event so rapid StrokeCommitted +
        // HistoryChanged + layer mutations coalesce into AT MOST ONE GPU readback!
        if (previewTimerRef.current !== null) {
          clearTimeout(previewTimerRef.current);
        }
        previewTimerRef.current = setTimeout(() => {
          previewTimerRef.current = null;
          if (recoveryService.getIsDrawingActive() || isNavigatorHidden()) {
            pendingRefreshRef.current = true;
            return;
          }
          pendingRefreshRef.current = false;
          hasRenderedInitialRef.current = true;
          renderPreviewNow();
        }, Math.max(16, waitMs));
      },
      [isNavigatorHidden, renderPreviewNow, throttleMs]
    );

    // Track Navigator preview stage size via ResizeObserver
    useEffect(() => {
      const el = stageRef.current;
      if (!el) return;
      const syncSize = () => {
        const rect = el.getBoundingClientRect();
        if (rect.width > 0 && rect.height > 0) {
          const becameVisible = wasStageZeroRef.current;
          wasStageZeroRef.current = false;
          setStageSize((prev) =>
            Math.abs(prev.width - rect.width) < 1 && Math.abs(prev.height - rect.height) < 1
              ? prev
              : { width: Math.round(rect.width), height: Math.round(rect.height) }
          );
          if (becameVisible && pendingRefreshRef.current) {
            scheduleThrottledPreview(true);
          }
        } else {
          wasStageZeroRef.current = true;
        }
      };
      syncSize();
      const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(syncSize) : null;
      ro?.observe(el);
      return () => ro?.disconnect();
    }, [scheduleThrottledPreview]);

    // Trigger initial render once on mount, and debounced composite only on structural visual changes
    useEffect(() => {
      if (!hasRenderedInitialRef.current) {
        scheduleThrottledPreview(false, 0);
      } else {
        scheduleThrottledPreview(true);
      }
    }, [layersVisualSig, dimensions.width, dimensions.height, showCheckerboard, scheduleThrottledPreview]);

    // Flush any skipped preview once palettes are unhidden
    useEffect(() => {
      if (!palettesHidden && pendingRefreshRef.current) {
        scheduleThrottledPreview(true);
      }
    }, [palettesHidden, scheduleThrottledPreview]);

    // Re-present instantly (0 recomposite!) when switching Color / Split / B&W or scrubbing split
    useEffect(() => {
      presentPreviewToDisplay(activePreviewMode, activeSplitRatio);
    }, [activePreviewMode, activeSplitRatio, presentPreviewToDisplay]);

    // Subscribe to native Rust stroke commits & history mutations (excluding redundant thumbnail
    // events), coalesced through a single trailing debounce and paused while actively sketching.
    useEffect(() => {
      const triggerRefresh = () => {
        scheduleThrottledPreview(true);
      };
      const unsubStroke = subscribeNativeStrokeCommitted(triggerRefresh);
      const unsubHistory = subscribeNativeHistory(triggerRefresh);
      const unsubDrawing = recoveryService.subscribeDrawingActive((active) => {
        if (!active && pendingRefreshRef.current) {
          scheduleThrottledPreview(true);
        }
      });
      const unsubNativeActive = subscribeNativeCanvasActive((active) => {
        if (active) {
          scheduleThrottledPreview(false, 0);
        }
      });
      return () => {
        unsubStroke();
        unsubHistory();
        unsubDrawing();
        unsubNativeActive();
        if (previewTimerRef.current !== null) {
          clearTimeout(previewTimerRef.current);
          previewTimerRef.current = null;
        }
      };
    }, [scheduleThrottledPreview]);

    // Direct rAF camera subscription for zero-rerender red viewport frame updates
    useEffect(() => {
      drawViewportOverlay(navigation.getCameraState());
      const unsub = navigation.subscribeCamera((cam) => {
        drawViewportOverlay(cam);
      });
      return unsub;
    }, [navigation, drawViewportOverlay, stageSize, dimensions]);

    // Re-sync overlay when main canvas viewport resizes
    useEffect(() => {
      const vp = viewportRef.current;
      if (!vp || typeof ResizeObserver === 'undefined') return;
      const ro = new ResizeObserver(() => drawViewportOverlay(navigation.getCameraState()));
      ro.observe(vp);
      return () => ro.disconnect();
    }, [viewportRef, navigation, drawViewportOverlay]);

    const pointerEventToDoc = useCallback((clientX: number, clientY: number): DocPoint | null => {
      const stage = stageRef.current;
      if (!stage) return null;
      const rect = stage.getBoundingClientRect();
      const m = metricsRef.current;
      const localX = clientX - rect.left;
      const localY = clientY - rect.top;
      return {
        x: (localX - m.offsetX) / Math.max(1e-5, m.scale),
        y: (localY - m.offsetY) / Math.max(1e-5, m.scale),
      };
    }, []);

    const applyPanForTargetDoc = useCallback(
      (targetDoc: DocPoint, commit: boolean) => {
        const cam = navigation.getCameraState();
        const { vw, vh } = getMainViewportSize();
        const nextPan = computePanForDocCenter(
          targetDoc,
          vw,
          vh,
          cam,
          latestSceneRef.current.dimensions
        );
        if (navigation.setPanLive) {
          navigation.setPanLive(nextPan, commit);
        } else {
          navigation.panRef.current = nextPan;
        }
      },
      [getMainViewportSize, navigation]
    );

    const handleStagePointerDown = useCallback(
      (e: React.PointerEvent<HTMLDivElement>) => {
        if (e.button !== 0) return;
        e.preventDefault();
        const ptDoc = pointerEventToDoc(e.clientX, e.clientY);
        if (!ptDoc) return;

        const cam = navigation.getCameraState();
        const { vw, vh } = getMainViewportSize();
        const dims = latestSceneRef.current.dimensions;
        const quad = computeViewportQuadInDoc(vw, vh, cam, dims);

        let grabOffsetDoc: DocPoint = { x: 0, y: 0 };
        if (isPointInConvexQuad(ptDoc, quad)) {
          const centerDoc = viewportPointToDoc(vw / 2, vh / 2, cam, dims);
          grabOffsetDoc = {
            x: centerDoc.x - ptDoc.x,
            y: centerDoc.y - ptDoc.y,
          };
        } else {
          applyPanForTargetDoc(ptDoc, false);
        }

        dragStateRef.current = {
          active: true,
          pointerId: e.pointerId,
          grabOffsetDoc,
        };
        setIsDraggingFrame(true);
        try {
          e.currentTarget.setPointerCapture?.(e.pointerId);
        } catch {
          // Ignore in synthetic pointer events
        }
      },
      [applyPanForTargetDoc, getMainViewportSize, navigation, pointerEventToDoc]
    );

    const handleStagePointerMove = useCallback(
      (e: React.PointerEvent<HTMLDivElement>) => {
        if (!dragStateRef.current.active) return;
        const ptDoc = pointerEventToDoc(e.clientX, e.clientY);
        if (!ptDoc) return;
        const targetDoc = {
          x: ptDoc.x + dragStateRef.current.grabOffsetDoc.x,
          y: ptDoc.y + dragStateRef.current.grabOffsetDoc.y,
        };
        applyPanForTargetDoc(targetDoc, false);
      },
      [applyPanForTargetDoc, pointerEventToDoc]
    );

    const finishStageDrag = useCallback(
      (e?: React.PointerEvent<HTMLDivElement>) => {
        if (!dragStateRef.current.active) return;
        const pid = dragStateRef.current.pointerId;
        dragStateRef.current.active = false;
        dragStateRef.current.pointerId = null;
        setIsDraggingFrame(false);
        if (e && pid !== null) {
          try {
            e.currentTarget.releasePointerCapture?.(pid);
          } catch {
            // Ignore in synthetic pointer events
          }
        }
        navigation.commitCameraState?.();
      },
      [navigation]
    );

    const handleZoomSliderChange = useCallback(
      (zoomPct: number) => {
        const nextZoom = Math.max(MIN_ZOOM, Math.min(MAX_ZOOM, zoomPct / 100));
        if (navigation.setZoomLive) {
          navigation.setZoomLive(nextZoom, false);
        }
      },
      [navigation]
    );

    const handleZoomSliderCommit = useCallback(() => {
      navigation.commitCameraState?.();
    }, [navigation]);

    const handleSplitPointerDown = useCallback(
      (e: React.PointerEvent<HTMLDivElement>) => {
        if (e.button !== 0) return;
        e.stopPropagation();
        e.preventDefault();
        const stage = stageRef.current;
        if (!stage) return;
        const rect = stage.getBoundingClientRect();
        const nextRatio = computeNavigatorSplitRatioFromClientX(
          e.clientX,
          rect.left,
          metricsRef.current
        );
        splitDragRef.current = {
          active: true,
          pointerId: e.pointerId,
          latestRatio: nextRatio,
        };
        setIsDraggingSplit(true);
        presentPreviewToDisplay('split', nextRatio);
        handleUpdateSplitRatio(nextRatio, false);
        try {
          e.currentTarget.setPointerCapture?.(e.pointerId);
        } catch {
          // Ignore in synthetic pointer events
        }
      },
      [handleUpdateSplitRatio, presentPreviewToDisplay]
    );

    const handleSplitPointerMove = useCallback(
      (e: React.PointerEvent<HTMLDivElement>) => {
        if (!splitDragRef.current.active) return;
        e.stopPropagation();
        const stage = stageRef.current;
        if (!stage) return;
        const rect = stage.getBoundingClientRect();
        const nextRatio = computeNavigatorSplitRatioFromClientX(
          e.clientX,
          rect.left,
          metricsRef.current
        );
        splitDragRef.current.latestRatio = nextRatio;
        presentPreviewToDisplay('split', nextRatio);
        handleUpdateSplitRatio(nextRatio, false);
      },
      [handleUpdateSplitRatio, presentPreviewToDisplay]
    );

    const finishSplitDrag = useCallback(
      (e?: React.PointerEvent<HTMLDivElement>) => {
        if (!splitDragRef.current.active) return;
        e?.stopPropagation();
        const pid = splitDragRef.current.pointerId;
        const finalRatio = splitDragRef.current.latestRatio;
        splitDragRef.current.active = false;
        splitDragRef.current.pointerId = null;
        setIsDraggingSplit(false);
        if (e && pid !== null) {
          try {
            e.currentTarget.releasePointerCapture?.(pid);
          } catch {
            // Ignore in synthetic pointer events
          }
        }
        handleUpdateSplitRatio(finalRatio, true);
      },
      [handleUpdateSplitRatio]
    );

    const handleSplitDoubleClick = useCallback(
      (e: React.MouseEvent<HTMLDivElement>) => {
        e.stopPropagation();
        handleUpdateSplitRatio(DEFAULT_NAVIGATOR_SPLIT_RATIO, true);
      },
      [handleUpdateSplitRatio]
    );

    const handleSplitKeyDown = useCallback(
      (e: React.KeyboardEvent<HTMLDivElement>) => {
        if (e.key === 'ArrowLeft') {
          e.preventDefault();
          handleUpdateSplitRatio(activeSplitRatio - 0.05, true);
        } else if (e.key === 'ArrowRight') {
          e.preventDefault();
          handleUpdateSplitRatio(activeSplitRatio + 0.05, true);
        } else if (e.key === 'Home') {
          e.preventDefault();
          handleUpdateSplitRatio(0.05, true);
        } else if (e.key === 'End') {
          e.preventDefault();
          handleUpdateSplitRatio(0.95, true);
        } else if (e.key === '0' || e.key === 'Enter') {
          e.preventDefault();
          handleUpdateSplitRatio(DEFAULT_NAVIGATOR_SPLIT_RATIO, true);
        }
      },
      [activeSplitRatio, handleUpdateSplitRatio]
    );

    const m = metricsRef.current;
    const splitLineLeft = m.offsetX + m.drawW * activeSplitRatio;
    const splitLeftWidth = m.drawW * activeSplitRatio;
    const splitRightWidth = m.drawW * (1 - activeSplitRatio);

    return (
      <div
        data-testid="navigator-panel"
        data-theme-preset={themePreset}
        data-preview-mode={activePreviewMode}
        className="flex flex-col h-full min-h-0 select-none bg-ui-panel text-ui-primary"
      >
        {/* Interactive Canvas Preview Stage */}
        <div
          ref={stageRef}
          data-testid="navigator-preview-stage"
          onPointerDown={handleStagePointerDown}
          onPointerMove={handleStagePointerMove}
          onPointerUp={finishStageDrag}
          onPointerCancel={finishStageDrag}
          className={`relative flex-1 min-h-[76px] overflow-hidden bg-ui-void ${
            isDraggingSplit
              ? 'cursor-ew-resize'
              : isDraggingFrame
              ? 'cursor-grabbing'
              : 'cursor-grab'
          }`}
          title={t('Click or drag red viewport frame to pan canvas')}
        >
          <canvas
            ref={previewCanvasRef}
            data-testid="navigator-preview-canvas"
            style={{
              position: 'absolute',
              left: `${m.offsetX}px`,
              top: `${m.offsetY}px`,
              width: `${m.drawW}px`,
              height: `${m.drawH}px`,
              imageRendering: m.scale > 1.5 ? 'pixelated' : 'auto',
            }}
            className="pointer-events-none shadow-sm"
          />
          <canvas
            ref={overlayCanvasRef}
            data-testid="navigator-overlay-canvas"
            className="absolute inset-0 w-full h-full pointer-events-none"
          />

          {/* Live B/W Mode Corner Badge */}
          {activePreviewMode === 'bw' && (
            <span
              data-testid="nav-bw-badge"
              className="pointer-events-none absolute top-1.5 left-1.5 z-10 px-1.5 py-0.5 rounded-ui-xs bg-ui-floating border border-ui-default shadow-ui-floating text-[9px] font-ui-mono uppercase tracking-wider text-ui-primary"
            >
              {t('B/W Tone')}
            </span>
          )}

          {/* Split View (Color | B/W) Interactive Divider & Micro-Labels */}
          {activePreviewMode === 'split' && (
            <>
              {splitLeftWidth >= 28 && (
                <span
                  data-testid="nav-split-color-label"
                  style={{
                    left: `${m.offsetX + 4}px`,
                    top: `${m.offsetY + 4}px`,
                  }}
                  className="pointer-events-none absolute z-10 px-1 py-[1px] rounded-ui-xs bg-ui-floating border border-ui-default text-[8px] font-ui-mono uppercase tracking-wider text-ui-primary"
                >
                  {t('CLR')}
                </span>
              )}
              {splitRightWidth >= 28 && (
                <span
                  data-testid="nav-split-bw-label"
                  style={{
                    right: `${Math.max(4, m.stageW - (m.offsetX + m.drawW) + 4)}px`,
                    top: `${m.offsetY + 4}px`,
                  }}
                  className="pointer-events-none absolute z-10 px-1 py-[1px] rounded-ui-xs bg-ui-floating border border-ui-default text-[8px] font-ui-mono uppercase tracking-wider text-ui-primary"
                >
                  {t('B/W')}
                </span>
              )}
              <div
                role="slider"
                tabIndex={0}
                data-testid="nav-split-handle"
                aria-label={t('Color and B/W Split Position')}
                aria-valuemin={5}
                aria-valuemax={95}
                aria-valuenow={Math.round(activeSplitRatio * 100)}
                onPointerDown={handleSplitPointerDown}
                onPointerMove={handleSplitPointerMove}
                onPointerUp={finishSplitDrag}
                onPointerCancel={finishSplitDrag}
                onDoubleClick={handleSplitDoubleClick}
                onKeyDown={handleSplitKeyDown}
                title={t('Drag to compare Color | B/W tones (Double-click to center 50%)')}
                style={{
                  left: `${splitLineLeft}px`,
                  top: `${m.offsetY}px`,
                  height: `${m.drawH}px`,
                }}
                className="absolute z-20 w-3 -ml-1.5 flex items-center justify-center cursor-ew-resize group focus:outline-none"
              >
                <div className="w-[1.5px] h-full bg-white/85 shadow-[0_0_2px_rgba(0,0,0,0.85)] group-hover:bg-ui-accent transition-colors" />
                <div
                  className={`absolute w-3.5 h-3.5 rounded-full flex items-center justify-center border shadow-ui-floating transition-transform ${
                    isDraggingSplit
                      ? 'bg-ui-accent border-ui-accent-contrast scale-110'
                      : 'bg-ui-floating border-ui-strong group-hover:border-ui-accent group-hover:scale-105'
                  }`}
                >
                  <span
                    className={`w-[1px] h-1.5 mr-[1.5px] ${
                      isDraggingSplit ? 'bg-ui-accent-contrast' : 'bg-ui-primary/80'
                    }`}
                  />
                  <span
                    className={`w-[1px] h-1.5 ${
                      isDraggingSplit ? 'bg-ui-accent-contrast' : 'bg-ui-primary/80'
                    }`}
                  />
                </div>
              </div>
            </>
          )}

          {/* Main Canvas Value Check Active Pill */}
          {isValueCheckEnabled && (
            <button
              type="button"
              data-testid="nav-canvas-value-badge"
              onPointerDown={(e) => e.stopPropagation()}
              onClick={handleToggleValueCheck}
              title={t('Main Canvas Value Check (Live B/W) is ON — Click to return main canvas to Color')}
              className="absolute top-1.5 right-1.5 z-20 px-1.5 py-0.5 rounded-ui-xs bg-ui-floating hover:bg-ui-elevated border border-ui-accent-border shadow-ui-floating text-[9px] font-ui-mono uppercase tracking-wider text-ui-accent cursor-pointer transition-colors"
            >
              {t('Canvas B/W')}
            </button>
          )}
        </div>

        {/* Compact Control Bar */}
        <div className="shrink-0 px-1.5 py-1 flex flex-col gap-1 border-t bg-ui-header border-ui-subtle">
          {/* Row 1: Zoom Controls */}
          <div className="flex items-center gap-1">
            <IconButton
              size="xs"
              data-testid="nav-zoom-out"
              onClick={onZoomOut}
              title={t('Zoom Out')}
              icon={<ZoomOut className="w-3 h-3" />}
            />
            <ScrubSlider
              liveRef={zoomSliderRef}
              data-testid="nav-zoom-slider"
              aria-label={t('Zoom')}
              min={MIN_ZOOM * 100}
              max={MAX_ZOOM * 100}
              step={1}
              defaultValue={100}
              unit="%"
              logarithmic
              hideLabel
              hideValue
              size="xs"
              value={Math.round(zoom * 100)}
              onChange={handleZoomSliderChange}
              onCommit={handleZoomSliderCommit}
              className="flex-1 min-w-0"
            />
            <IconButton
              size="xs"
              data-testid="nav-zoom-in"
              onClick={onZoomIn}
              title={t('Zoom In')}
              icon={<ZoomIn className="w-3 h-3" />}
            />
            <span
              ref={zoomLabelRef}
              data-testid="nav-zoom-readout"
              className="text-[10px] font-ui-mono tabular-nums text-ui-secondary w-10 text-right shrink-0"
            >
              {formatZoomPercent(zoom)}
            </span>
          </div>

          {/* Row 2: Fit / 100% / Rotate / Reset Angle / Flip H & V */}
          <div className="flex items-center justify-between gap-0.5 flex-wrap">
            <div className="flex items-center gap-0.5">
              <IconButton
                size="xs"
                data-testid="nav-fit-screen"
                onClick={onFitToScreen}
                title={t('Fit to Screen (Ctrl+0)')}
                icon={<Maximize className="w-3 h-3" />}
              />
              <IconButton
                size="xs"
                data-testid="nav-zoom-100"
                onClick={onZoomActualSize}
                title={t('Reset Zoom to 100% (Ctrl+1)')}
                label="100%"
                className="px-1 font-ui-mono tabular-nums"
              />
            </div>

            <div className="flex items-center gap-0.5">
              <IconButton
                size="xs"
                data-testid="nav-rotate-left"
                onClick={onRotateLeft}
                title={t('Rotate Left (-15°)')}
                icon={<RotateCcw className="w-3 h-3" />}
              />
              <IconButton
                size="xs"
                data-testid="nav-reset-rotation"
                onClick={onResetRotation}
                title={t('Reset Canvas Angle (0°)')}
                icon={<Compass className="w-2.5 h-2.5 opacity-70" />}
                label={
                  <span ref={angleLabelRef} data-testid="nav-angle-readout">
                    {formatRotationDegrees(rotation)}
                  </span>
                }
                className="px-1 font-ui-mono tabular-nums"
              />
              <IconButton
                size="xs"
                data-testid="nav-rotate-right"
                onClick={onRotateRight}
                title={t('Rotate Right (+15°)')}
                icon={<RotateCw className="w-3 h-3" />}
              />
            </div>

            <div className="flex items-center gap-0.5">
              <IconButton
                size="xs"
                data-testid="nav-flip-h"
                active={flipX}
                onClick={onToggleFlipHorizontal}
                title={t('Flip Horizontal View (Shift+H)')}
                icon={<FlipHorizontal className="w-3 h-3" />}
              />
              <IconButton
                size="xs"
                data-testid="nav-flip-v"
                active={flipY}
                onClick={onToggleFlipVertical}
                title={t('Flip Vertical View (Shift+V)')}
                icon={<FlipVertical className="w-3 h-3" />}
              />
            </div>
          </div>

          {/* Row 3: Navigator Tone Preview Mode (Color / Split / B/W) + 1-Click Main Canvas Value Check */}
          <div className="flex items-center justify-between gap-1 pt-0.5 border-t border-ui-subtle">
            <SegmentedControl<NavigatorPreviewMode>
              size="xs"
              selectionRole="button"
              aria-label={t('Navigator Preview Mode')}
              value={activePreviewMode}
              onChange={handleSelectPreviewMode}
              options={[
                {
                  value: 'color',
                  label: t('Color'),
                  title: t('Color Navigator Preview'),
                  'data-testid': 'nav-mode-color',
                },
                {
                  value: 'split',
                  label: t('Split'),
                  icon: <Columns2 className="w-2.5 h-2.5" />,
                  title: t('Split View — Compare Color & Live B/W Tones in Navigator (Alt+Shift+Y)'),
                  accentOnActive: true,
                  'data-testid': 'nav-mode-split',
                },
                {
                  value: 'bw',
                  label: t('B/W'),
                  title: t(
                    'Live B/W Preview in Navigator — Paint in color on main canvas while monitoring B/W values in real time'
                  ),
                  accentOnActive: true,
                  className: 'font-ui-mono',
                  'data-testid': 'nav-mode-bw',
                },
              ]}
            />

            <IconButton
              size="xs"
              variant="subtle"
              data-testid="nav-value-check"
              active={isValueCheckEnabled}
              onClick={handleToggleValueCheck}
              title={t('1-Click Value Check — Toggle Live B/W Tone Check on Main Canvas (Shift+Y)')}
              icon={<Contrast className="w-3 h-3" />}
              label={t('Value')}
              className="font-medium"
            />
          </div>
        </div>
      </div>
    );
  }
);

NavigatorPanel.displayName = 'NavigatorPanel';