Skip to content

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

sub view & navigator

sora6fba000bd7f5
diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsx
index 6ccc414..fab4dd7 100644
--- a/src/components/AppShell.tsx
+++ b/src/components/AppShell.tsx
@@ -507,6 +507,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
const modernAccent = useUiStore((s) => s.appSettings.modernAccent || 'neutral');
const modernCustomColor = useUiStore((s) => s.appSettings.modernCustomColor);
const themePreset = useUiStore((s) => s.appSettings.themePreset);
+ const showCheckerboard = useUiStore((s) => s.appSettings.showCheckerboard);
const userName = useUiStore((s) => s.appSettings.userName);
const showStatusBar = useWorkspaceStore((s) => s.showStatusBar);
const showDocumentTabs = useWorkspaceStore((s) => s.showDocumentTabs);
@@ -647,6 +648,63 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
]
);
+ const handleZoomActualSize = useCallback(() => {
+ canvasProps.navigation.setZoomLive?.(1.0, true);
+ }, [canvasProps.navigation]);
+
+ const handleRotateLeft = useCallback(() => {
+ canvasProps.navigation.rotateBy?.(-15);
+ }, [canvasProps.navigation]);
+
+ const handleRotateRight = useCallback(() => {
+ canvasProps.navigation.rotateBy?.(15);
+ }, [canvasProps.navigation]);
+
+ const navigatorProps = useMemo(
+ () => ({
+ viewportRef: canvasProps.viewportRef,
+ navigation: canvasProps.navigation,
+ dimensions,
+ layers: canvasProps.layers,
+ tileGrid: canvasProps.tileGrid,
+ showCheckerboard,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ onZoomIn: zoomIn,
+ onZoomOut: zoomOut,
+ onFitToScreen: resetZoomAndCenter,
+ onZoomActualSize: handleZoomActualSize,
+ onRotateLeft: handleRotateLeft,
+ onRotateRight: handleRotateRight,
+ onResetRotation: resetRotation,
+ onToggleFlipHorizontal: toggleFlipHorizontal,
+ onToggleFlipVertical: toggleFlipVertical,
+ }),
+ [
+ canvasProps.viewportRef,
+ canvasProps.navigation,
+ canvasProps.layers,
+ canvasProps.tileGrid,
+ dimensions,
+ showCheckerboard,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ zoomIn,
+ zoomOut,
+ resetZoomAndCenter,
+ handleZoomActualSize,
+ handleRotateLeft,
+ handleRotateRight,
+ resetRotation,
+ toggleFlipHorizontal,
+ toggleFlipVertical,
+ ]
+ );
+
const layerSidebarProps = useMemo(
() => ({
hasOpenDocument,
@@ -857,6 +915,7 @@ export const AppShell: React.FC<AppShellProps> = React.memo(
onInvertSelection={canvasProps.onInvertSelection}
onToggleTransparentColor={handleToggleTransparentColor}
layerSidebarProps={layerSidebarProps}
+ navigatorProps={navigatorProps}
>
{showDocumentTabs && (
<DocumentTabBar
diff --git a/src/components/DockWorkspace.tsx b/src/components/DockWorkspace.tsx
index fc11f26..f20e639 100644
--- a/src/components/DockWorkspace.tsx
+++ b/src/components/DockWorkspace.tsx
@@ -17,6 +17,8 @@ import {
PanelLeft,
PanelRight,
Eye,
+ Compass,
+ Images,
} from 'lucide-react';
import { CanvasColorMode, CspBrush } from '../types/editor';
import { ThemePreset } from '../types/settings';
@@ -51,6 +53,8 @@ import { ToolPropertyInspector } from './ToolPropertyInspector';
import { BrushSizePalette } from './BrushSizePalette';
import { RightSidebar, RightSidebarColorSection, RightSidebarProps } from './RightSidebar';
import { QuickAccessPanel } from './QuickAccessPanel';
+import { NavigatorPanel, NavigatorPanelProps } from './NavigatorPanel';
+import { SubViewPanel } from './SubViewPanel';
import { WorkspaceCommandHandlers } from './CommandBar';
const DND_PANEL_MIME = 'application/x-inkstudio-panel';
@@ -65,6 +69,10 @@ export function renderPanelIcon(panelId: DockPanelId, className = 'w-3.5 h-3.5')
return <Sliders className={className} />;
case 'brush-size':
return <CircleDot className={className} />;
+ case 'navigator':
+ return <Compass className={className} />;
+ case 'sub-view':
+ return <Images className={className} />;
case 'color':
return <Palette className={className} />;
case 'layers':
@@ -163,6 +171,8 @@ export interface DockWorkspaceProps {
onToggleTransparentColor?: () => void;
// Layer & history props forwarded cleanly to RightSidebar docked panels
layerSidebarProps: Omit<RightSidebarProps, 'width' | 'onWidthChange' | 'hideColorPanel' | 'dockedMode'>;
+ // Navigator palette props
+ navigatorProps?: Omit<NavigatorPanelProps, 'themePreset'>;
// Center canvas area (DocumentTabBar + CanvasArea + StatusBar)
children: React.ReactNode;
}
@@ -760,6 +770,7 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({
onInvertSelection,
onToggleTransparentColor,
layerSidebarProps,
+ navigatorProps,
children,
}) => {
const layout = useWorkspaceStore((s) => s.layout);
@@ -845,6 +856,12 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({
);
case 'brush-size':
return <BrushSizeDockedContent themePreset={themePreset} />;
+ case 'navigator':
+ return navigatorProps ? (
+ <NavigatorPanel {...navigatorProps} themePreset={themePreset} />
+ ) : null;
+ case 'sub-view':
+ return <SubViewPanel colorMode={colorMode} themePreset={themePreset} />;
case 'color':
return (
<RightSidebarColorSection
@@ -883,6 +900,7 @@ export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({
commandHandlers,
customBrushes,
layerSidebarProps,
+ navigatorProps,
onContractSelection,
onDeselect,
onExpandSelection,
diff --git a/src/components/NavigatorPanel.tsx b/src/components/NavigatorPanel.tsx
new file mode 100644
index 0000000..019128b
--- /dev/null
+++ b/src/components/NavigatorPanel.tsx
@@ -0,0 +1,758 @@
+import React, { useEffect, useRef, useState, useCallback } from 'react';
+import {
+ ZoomIn,
+ ZoomOut,
+ Maximize,
+ RotateCcw,
+ RotateCw,
+ FlipHorizontal,
+ FlipVertical,
+ Compass,
+} from 'lucide-react';
+import { CanvasDimensions, LayerItem } from '../types/editor';
+import { ThemePreset } from '../types/settings';
+import { SparseTileGrid } from '../utils/tileEngine';
+import { ViewportCompositor } from '../utils/compositor';
+import { formatRotationDegrees } from '../utils/canvasUtils';
+import {
+ CameraTransformState,
+ CanvasNavigationHandle,
+ MAX_ZOOM,
+ MIN_ZOOM,
+ formatZoomPercent,
+} from '../hooks/useCanvasNavigation';
+
+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, cam.zoom);
+ const rx = vx - cam.pan.x;
+ const ry = vy - cam.pan.y;
+ const rad = (cam.rotation * 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: dimensions.width / 2 + (fx * unrotX) / safeZoom,
+ y: dimensions.height / 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 {
+ let sign = 0;
+ for (let i = 0; i < 4; i++) {
+ const a = quad[i];
+ const b = quad[(i + 1) % 4];
+ 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,
+ };
+}
+
+export interface NavigatorPanelProps {
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ navigation: CanvasNavigationHandle;
+ dimensions: CanvasDimensions;
+ layers: LayerItem[];
+ tileGrid: SparseTileGrid;
+ 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;
+ themePreset?: ThemePreset;
+ throttleMs?: number;
+}
+
+export const NavigatorPanel: React.FC<NavigatorPanelProps> = React.memo(
+ ({
+ viewportRef,
+ navigation,
+ dimensions,
+ layers,
+ tileGrid,
+ showCheckerboard,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ onZoomIn,
+ onZoomOut,
+ onFitToScreen,
+ onZoomActualSize,
+ onRotateLeft,
+ onRotateRight,
+ onResetRotation,
+ onToggleFlipHorizontal,
+ onToggleFlipVertical,
+ themePreset = 'modern',
+ throttleMs = NAVIGATOR_PREVIEW_THROTTLE_MS,
+ }) => {
+ const isVintage = themePreset === 'vintage-manga';
+
+ const stageRef = useRef<HTMLDivElement | null>(null);
+ const previewCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const overlayCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const zoomSliderRef = useRef<HTMLInputElement | 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 metricsRef = useRef<PreviewBoxMetrics>(
+ computePreviewBoxMetrics(200, 120, dimensions)
+ );
+ metricsRef.current = computePreviewBoxMetrics(stageSize.width, stageSize.height, dimensions);
+
+ const latestSceneRef = useRef({
+ layers,
+ dimensions,
+ tileGrid,
+ showCheckerboard,
+ });
+ latestSceneRef.current = { layers, dimensions, tileGrid, showCheckerboard };
+
+ 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 { vw, vh } = getMainViewportSize();
+ const quad = computeViewportQuadInDoc(vw, vh, activeCam, latestSceneRef.current.dimensions);
+
+ const pts = quad.map((p) => ({
+ x: m.offsetX + p.x * m.scale,
+ y: m.offsetY + p.y * m.scale,
+ }));
+
+ // 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.value = String(zoomToSliderPos(activeCam.zoom));
+ }
+ 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 ~200ms during rapid brush strokes)
+ const lastPreviewTsRef = useRef<number>(0);
+ const previewTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const renderPreviewNow = useCallback(() => {
+ const canvas = previewCanvasRef.current;
+ if (!canvas) return;
+ const { layers: curLayers, dimensions: curDims, tileGrid: curGrid, 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 (canvas.width !== targetW) canvas.width = targetW;
+ if (canvas.height !== targetH) canvas.height = targetH;
+
+ ViewportCompositor.renderLowResPreview(canvas, curLayers, curDims, curGrid, {
+ showCheckerboard: curCheck,
+ });
+ lastPreviewTsRef.current = Date.now();
+ }, []);
+
+ const scheduleThrottledPreview = useCallback(() => {
+ const now = Date.now();
+ const elapsed = now - lastPreviewTsRef.current;
+ if (elapsed >= throttleMs) {
+ if (previewTimerRef.current !== null) {
+ clearTimeout(previewTimerRef.current);
+ previewTimerRef.current = null;
+ }
+ renderPreviewNow();
+ return;
+ }
+ if (previewTimerRef.current !== null) return;
+ const remaining = Math.max(16, throttleMs - elapsed);
+ previewTimerRef.current = setTimeout(() => {
+ previewTimerRef.current = null;
+ renderPreviewNow();
+ }, remaining);
+ }, [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) {
+ 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) }
+ );
+ }
+ };
+ syncSize();
+ const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(syncSize) : null;
+ ro?.observe(el);
+ return () => ro?.disconnect();
+ }, []);
+
+ // Trigger throttled composite on layer/dimension/background changes
+ useEffect(() => {
+ scheduleThrottledPreview();
+ }, [layers, dimensions, showCheckerboard, tileGrid, scheduleThrottledPreview]);
+
+ // Subscribe to SparseTileGrid changes with 200ms throttle to avoid stroke overhead
+ useEffect(() => {
+ const unsub = tileGrid.subscribe(() => {
+ scheduleThrottledPreview();
+ });
+ return () => {
+ unsub();
+ if (previewTimerRef.current !== null) {
+ clearTimeout(previewTimerRef.current);
+ previewTimerRef.current = null;
+ }
+ };
+ }, [tileGrid, 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 handleZoomSliderInput = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const pos = Number(e.target.value);
+ const nextZoom = sliderPosToZoom(pos);
+ if (navigation.setZoomLive) {
+ navigation.setZoomLive(nextZoom, false);
+ }
+ },
+ [navigation]
+ );
+
+ const handleZoomSliderCommit = useCallback(() => {
+ navigation.commitCameraState?.();
+ }, [navigation]);
+
+ const m = metricsRef.current;
+
+ const btnBase = isVintage
+ ? 'h-5 px-1 rounded text-[10px] flex items-center justify-center text-[#d0d0d5] hover:text-white hover:bg-[#4e4e52] transition-colors cursor-pointer'
+ : 'h-5 px-1 rounded text-[10px] flex items-center justify-center text-[#a3a3a3] hover:text-[#f5f5f5] hover:bg-[#2c2c2c] transition-colors cursor-pointer';
+
+ const btnActive = isVintage
+ ? 'bg-[#337bb5] text-white'
+ : 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-inset ring-[var(--accent-border)]';
+
+ return (
+ <div
+ data-testid="navigator-panel"
+ data-theme-preset={themePreset}
+ className={`flex flex-col h-full min-h-0 select-none ${
+ isVintage ? 'bg-[#363638] text-[#e5e5e5]' : 'bg-[#202020] text-[#e5e5e5]'
+ }`}
+ >
+ {/* 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 ${
+ isDraggingFrame ? 'cursor-grabbing' : 'cursor-grab'
+ } ${isVintage ? 'bg-[#252527]' : 'bg-[#141414]'}`}
+ title="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"
+ />
+ </div>
+
+ {/* Compact Control Bar */}
+ <div
+ className={`shrink-0 px-1.5 py-1 flex flex-col gap-1 border-t ${
+ isVintage
+ ? 'bg-[#313134] border-[#232325]'
+ : 'bg-[#1b1b1b] border-white/[0.06]'
+ }`}
+ >
+ {/* Row 1: Zoom Controls */}
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ data-testid="nav-zoom-out"
+ onClick={onZoomOut}
+ title="Zoom Out"
+ className={`${btnBase} w-5 shrink-0`}
+ >
+ <ZoomOut className="w-3 h-3" />
+ </button>
+ <input
+ ref={zoomSliderRef}
+ type="range"
+ data-testid="nav-zoom-slider"
+ min={0}
+ max={SLIDER_MAX}
+ defaultValue={zoomToSliderPos(zoom)}
+ onChange={handleZoomSliderInput}
+ onPointerUp={handleZoomSliderCommit}
+ onKeyUp={handleZoomSliderCommit}
+ aria-label="Zoom"
+ className="flex-1 min-w-0 h-1 accent-[var(--accent)] cursor-pointer"
+ />
+ <button
+ type="button"
+ data-testid="nav-zoom-in"
+ onClick={onZoomIn}
+ title="Zoom In"
+ className={`${btnBase} w-5 shrink-0`}
+ >
+ <ZoomIn className="w-3 h-3" />
+ </button>
+ <span
+ ref={zoomLabelRef}
+ data-testid="nav-zoom-readout"
+ className="text-[10px] font-mono tabular-nums text-[#b5b5b5] 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">
+ <button
+ type="button"
+ data-testid="nav-fit-screen"
+ onClick={onFitToScreen}
+ title="Fit to Screen (Ctrl+0)"
+ className={btnBase}
+ >
+ <Maximize className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="nav-zoom-100"
+ onClick={onZoomActualSize}
+ title="Actual Pixels (100%)"
+ className={`${btnBase} px-1 font-mono`}
+ >
+ 100%
+ </button>
+ </div>
+
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ data-testid="nav-rotate-left"
+ onClick={onRotateLeft}
+ title="Rotate Left (-15°)"
+ className={`${btnBase} w-5`}
+ >
+ <RotateCcw className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="nav-reset-rotation"
+ onClick={onResetRotation}
+ title="Reset Canvas Angle (0°)"
+ className={`${btnBase} gap-0.5 px-1 font-mono tabular-nums`}
+ >
+ <Compass className="w-2.5 h-2.5 opacity-70" />
+ <span ref={angleLabelRef} data-testid="nav-angle-readout">
+ {formatRotationDegrees(rotation)}
+ </span>
+ </button>
+ <button
+ type="button"
+ data-testid="nav-rotate-right"
+ onClick={onRotateRight}
+ title="Rotate Right (+15°)"
+ className={`${btnBase} w-5`}
+ >
+ <RotateCw className="w-3 h-3" />
+ </button>
+ </div>
+
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ data-testid="nav-flip-h"
+ onClick={onToggleFlipHorizontal}
+ aria-pressed={flipX}
+ title="Flip Horizontal View (Shift+H)"
+ className={`${btnBase} w-5 ${flipX ? btnActive : ''}`}
+ >
+ <FlipHorizontal className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="nav-flip-v"
+ onClick={onToggleFlipVertical}
+ aria-pressed={flipY}
+ title="Flip Vertical View (Shift+V)"
+ className={`${btnBase} w-5 ${flipY ? btnActive : ''}`}
+ >
+ <FlipVertical className="w-3 h-3" />
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+ }
+);
+
+NavigatorPanel.displayName = 'NavigatorPanel';
diff --git a/src/components/SubViewPanel.tsx b/src/components/SubViewPanel.tsx
new file mode 100644
index 0000000..78fc73a
--- /dev/null
+++ b/src/components/SubViewPanel.tsx
@@ -0,0 +1,1013 @@
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import {
+ Plus,
+ ChevronLeft,
+ ChevronRight,
+ Trash2,
+ ZoomIn,
+ ZoomOut,
+ Maximize,
+ RotateCcw,
+ RotateCw,
+ FlipHorizontal,
+ Pipette,
+ Hand,
+ List,
+ ImagePlus,
+ RefreshCw,
+} from 'lucide-react';
+import { CanvasColorMode } from '../types/editor';
+import { ThemePreset } from '../types/settings';
+import {
+ SUB_VIEW_MAX_ZOOM,
+ SUB_VIEW_MIN_ZOOM,
+ SubViewImageItem,
+ SubViewTransform,
+ subViewStoreActions,
+ useSubViewStore,
+} from '../stores/useSubViewStore';
+import { toolStoreActions } from '../stores/useToolStore';
+
+const DND_PANEL_MIME = 'application/x-inkstudio-panel';
+const VALID_IMAGE_EXT_RE = /\.(png|jpe?g|webp|gif|bmp|avif|ico|svg)$/i;
+
+export interface PixelCoord {
+ x: number;
+ y: number;
+}
+
+/**
+ * Inverse-maps a point `(localX, localY)` inside the Sub View stage into
+ * integer source image pixel coordinates `(x, y)` accounting for pan, zoom, rotation, and flipX.
+ * Returns `null` if the point lies outside the image bounds.
+ */
+export function subViewPointToImagePixel(
+ localX: number,
+ localY: number,
+ stageW: number,
+ stageH: number,
+ imgW: number,
+ imgH: number,
+ transform: SubViewTransform
+): PixelCoord | null {
+ if (imgW <= 0 || imgH <= 0 || stageW <= 0 || stageH <= 0) return null;
+ const safeZoom = Math.max(1e-4, transform.zoom);
+ const dx = localX - (stageW / 2 + transform.pan.x);
+ const dy = localY - (stageH / 2 + transform.pan.y);
+
+ const rad = (transform.rotation * Math.PI) / 180;
+ const cos = Math.cos(rad);
+ const sin = Math.sin(rad);
+
+ const unrotX = dx * cos + dy * sin;
+ const unrotY = -dx * sin + dy * cos;
+ const fx = transform.flipX ? -1 : 1;
+
+ const px = Math.floor(imgW / 2 + (fx * unrotX) / safeZoom);
+ const py = Math.floor(imgH / 2 + unrotY / safeZoom);
+
+ if (px < 0 || py < 0 || px >= imgW || py >= imgH) return null;
+ return { x: px, y: py };
+}
+
+/**
+ * Safely samples a `#rrggbb` hex color at `(px, py)` from an owned offscreen 2D canvas.
+ * Catches CORS/SecurityError exceptions cleanly and ignores fully transparent pixels.
+ */
+export function samplePixelHexFromCanvas(
+ canvas: HTMLCanvasElement | null,
+ px: number,
+ py: number
+): string | null {
+ if (!canvas || px < 0 || py < 0 || px >= canvas.width || py >= canvas.height) {
+ return null;
+ }
+ try {
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ if (!ctx) return null;
+ const data = ctx.getImageData(px, py, 1, 1).data;
+ const alpha = data[3];
+ if (alpha === 0) return null;
+ const r = data[0].toString(16).padStart(2, '0');
+ const g = data[1].toString(16).padStart(2, '0');
+ const b = data[2].toString(16).padStart(2, '0');
+ return `#${r}${g}${b}`;
+ } catch {
+ // Guard against tainted canvas / SecurityError
+ return null;
+ }
+}
+
+export function computeSubViewFitZoom(
+ stageW: number,
+ stageH: number,
+ imgW: number,
+ imgH: number,
+ padding = 12
+): number {
+ if (imgW <= 0 || imgH <= 0 || stageW <= 0 || stageH <= 0) return 1;
+ const availW = Math.max(16, stageW - padding * 2);
+ const availH = Math.max(16, stageH - padding * 2);
+ const fit = Math.min(availW / imgW, availH / imgH);
+ return Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, fit));
+}
+
+function isImageFile(file: File): boolean {
+ if (file.type && file.type.startsWith('image/')) return true;
+ return VALID_IMAGE_EXT_RE.test(file.name);
+}
+
+function readLocalImageFile(file: File): Promise<{ name: string; src: string; width: number; height: number }> {
+ return new Promise((resolve, reject) => {
+ const reader = new FileReader();
+ reader.onerror = () => reject(new Error(`Failed to read ${file.name}`));
+ reader.onload = () => {
+ const dataUrl = typeof reader.result === 'string' ? reader.result : '';
+ if (!dataUrl) {
+ reject(new Error(`Empty image data for ${file.name}`));
+ return;
+ }
+ const img = new Image();
+ img.onload = () => {
+ resolve({
+ name: file.name || 'Reference',
+ src: dataUrl,
+ width: img.naturalWidth || img.width || 1,
+ height: img.naturalHeight || img.height || 1,
+ });
+ };
+ img.onerror = () => reject(new Error(`Unsupported image format: ${file.name}`));
+ img.src = dataUrl;
+ };
+ reader.readAsDataURL(file);
+ });
+}
+
+export interface SubViewPanelProps {
+ colorMode?: CanvasColorMode;
+ themePreset?: ThemePreset;
+}
+
+export const SubViewPanel: React.FC<SubViewPanelProps> = React.memo(
+ ({ colorMode = 'color', themePreset = 'modern' }) => {
+ const isVintage = themePreset === 'vintage-manga';
+
+ const items = useSubViewStore((s) => s.items);
+ const activeId = useSubViewStore((s) => s.activeId);
+ const autoEyedropper = useSubViewStore((s) => s.autoEyedropper);
+ const manualEyedropper = useSubViewStore((s) => s.manualEyedropper);
+ const showList = useSubViewStore((s) => s.showList);
+
+ const activeIndex = useMemo(
+ () => Math.max(0, items.findIndex((i) => i.id === activeId)),
+ [items, activeId]
+ );
+ const activeItem: SubViewImageItem | null = items.length > 0 ? items[activeIndex] ?? items[0] : null;
+
+ const stageRef = useRef<HTMLDivElement | null>(null);
+ const displayCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const sourceCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const fileInputRef = useRef<HTMLInputElement | null>(null);
+ const reloadInputRef = useRef<HTMLInputElement | null>(null);
+
+ const [stageSize, setStageSize] = useState<{ width: number; height: number }>({
+ width: 200,
+ height: 140,
+ });
+ const [sourceVersion, setSourceVersion] = useState(0);
+ const [isDragOverFiles, setIsDragOverFiles] = useState(false);
+ const [isHoveringStage, setIsHoveringStage] = useState(false);
+ const [isSpaceHeld, setIsSpaceHeld] = useState(false);
+ const [isAltHeld, setIsAltHeld] = useState(false);
+ const [sampledHex, setSampledHex] = useState<string | null>(null);
+ const [loadError, setLoadError] = useState<string | null>(null);
+
+ // Live mutable transform during drag/pan/wheel so Sub View stays silky-smooth
+ const liveTransformRef = useRef<SubViewTransform>({
+ zoom: 1,
+ pan: { x: 0, y: 0 },
+ rotation: 0,
+ flipX: false,
+ });
+
+ const interactionRef = useRef<{
+ mode: 'none' | 'pan' | 'eyedrop';
+ pointerId: number | null;
+ startClientX: number;
+ startClientY: number;
+ startPanX: number;
+ startPanY: number;
+ }>({
+ mode: 'none',
+ pointerId: null,
+ startClientX: 0,
+ startClientY: 0,
+ startPanX: 0,
+ startPanY: 0,
+ });
+
+ const activeItemRef = useRef<SubViewImageItem | null>(activeItem);
+ activeItemRef.current = activeItem;
+
+ const stageSizeRef = useRef(stageSize);
+ stageSizeRef.current = stageSize;
+
+ // Sync live transform ref whenever active item changes
+ useEffect(() => {
+ if (!activeItem) return;
+ liveTransformRef.current = {
+ zoom: activeItem.zoom,
+ pan: { x: activeItem.pan.x, y: activeItem.pan.y },
+ rotation: activeItem.rotation,
+ flipX: activeItem.flipX,
+ };
+ }, [activeItem]);
+
+ // Track stage dimensions via ResizeObserver
+ useEffect(() => {
+ const el = stageRef.current;
+ if (!el) return;
+ const sync = () => {
+ const rect = el.getBoundingClientRect();
+ if (rect.width > 0 && rect.height > 0) {
+ 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) }
+ );
+ }
+ };
+ sync();
+ const ro = typeof ResizeObserver !== 'undefined' ? new ResizeObserver(sync) : null;
+ ro?.observe(el);
+ return () => ro?.disconnect();
+ }, []);
+
+ // Track Space / Alt while hovering Sub View for quick pan/eyedropper override
+ useEffect(() => {
+ if (!isHoveringStage) {
+ setIsSpaceHeld(false);
+ setIsAltHeld(false);
+ return;
+ }
+ const onKeyDown = (e: KeyboardEvent) => {
+ if (e.code === 'Space') setIsSpaceHeld(true);
+ if (e.key === 'Alt') setIsAltHeld(true);
+ };
+ const onKeyUp = (e: KeyboardEvent) => {
+ if (e.code === 'Space') setIsSpaceHeld(false);
+ if (e.key === 'Alt') setIsAltHeld(false);
+ };
+ window.addEventListener('keydown', onKeyDown);
+ window.addEventListener('keyup', onKeyUp);
+ return () => {
+ window.removeEventListener('keydown', onKeyDown);
+ window.removeEventListener('keyup', onKeyUp);
+ };
+ }, [isHoveringStage]);
+
+ // Decode active reference into an owned offscreen 2D canvas for CORS-safe pixel sampling
+ useEffect(() => {
+ let cancelled = false;
+ setLoadError(null);
+
+ if (!activeItem || !activeItem.src) {
+ sourceCanvasRef.current = null;
+ setSourceVersion((v) => v + 1);
+ return;
+ }
+
+ const img = new Image();
+ img.crossOrigin = 'anonymous';
+ img.onload = () => {
+ if (cancelled) return;
+ const w = Math.max(1, img.naturalWidth || img.width || activeItem.width || 1);
+ const h = Math.max(1, img.naturalHeight || img.height || activeItem.height || 1);
+ const off = document.createElement('canvas');
+ off.width = w;
+ off.height = h;
+ const ctx = off.getContext('2d', { willReadFrequently: true });
+ if (ctx) {
+ ctx.clearRect(0, 0, w, h);
+ ctx.drawImage(img, 0, 0, w, h);
+ }
+ sourceCanvasRef.current = off;
+ setSourceVersion((v) => v + 1);
+
+ if (activeItem.needsInitialFit) {
+ const { width: sw, height: sh } = stageSizeRef.current;
+ const fitZoom = computeSubViewFitZoom(sw, sh, w, h);
+ liveTransformRef.current = { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false };
+ subViewStoreActions.updateImageTransform(
+ activeItem.id,
+ { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },
+ true
+ );
+ }
+ };
+ img.onerror = () => {
+ if (cancelled) return;
+ sourceCanvasRef.current = null;
+ setLoadError('Failed to decode image');
+ setSourceVersion((v) => v + 1);
+ };
+ img.src = activeItem.src;
+
+ return () => {
+ cancelled = true;
+ };
+ }, [activeItem?.id, activeItem?.src]);
+
+ // Render Sub View display canvas from owned offscreen source canvas
+ const renderDisplayCanvas = useCallback(
+ (overrideTransform?: SubViewTransform) => {
+ const display = displayCanvasRef.current;
+ if (!display) return;
+ const ctx = display.getContext('2d');
+ if (!ctx) return;
+
+ const { width: sw, height: sh } = stageSizeRef.current;
+ const dpr = typeof window !== 'undefined' ? Math.min(2, window.devicePixelRatio || 1) : 1;
+ const targetW = Math.max(1, Math.round(sw * dpr));
+ const targetH = Math.max(1, Math.round(sh * dpr));
+ if (display.width !== targetW || display.height !== targetH) {
+ display.width = targetW;
+ display.height = targetH;
+ }
+
+ ctx.save();
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ ctx.clearRect(0, 0, sw, sh);
+
+ const src = sourceCanvasRef.current;
+ if (!src) {
+ ctx.restore();
+ return;
+ }
+
+ const t = overrideTransform ?? liveTransformRef.current;
+ ctx.translate(sw / 2 + t.pan.x, sh / 2 + t.pan.y);
+ ctx.rotate((t.rotation * Math.PI) / 180);
+ ctx.scale(t.flipX ? -t.zoom : t.zoom, t.zoom);
+ ctx.imageSmoothingEnabled = t.zoom < 2;
+ ctx.drawImage(src, -src.width / 2, -src.height / 2);
+ ctx.restore();
+ },
+ []
+ );
+
+ useEffect(() => {
+ renderDisplayCanvas();
+ }, [activeItem, stageSize, sourceVersion, renderDisplayCanvas]);
+
+ // Determine effective interaction mode on hover/click
+ const isEyedropperActive = useMemo(() => {
+ if (isSpaceHeld) return false;
+ if (isAltHeld) return true;
+ return autoEyedropper || manualEyedropper;
+ }, [autoEyedropper, manualEyedropper, isSpaceHeld, isAltHeld]);
+
+ const sampleColorAtClientPos = useCallback(
+ (clientX: number, clientY: number, commit: boolean): string | null => {
+ const stage = stageRef.current;
+ const src = sourceCanvasRef.current;
+ if (!stage || !src) return null;
+ const rect = stage.getBoundingClientRect();
+ const localX = clientX - rect.left;
+ const localY = clientY - rect.top;
+ const pxCoord = subViewPointToImagePixel(
+ localX,
+ localY,
+ rect.width || stageSizeRef.current.width,
+ rect.height || stageSizeRef.current.height,
+ src.width,
+ src.height,
+ liveTransformRef.current
+ );
+ if (!pxCoord) return null;
+ const hex = samplePixelHexFromCanvas(src, pxCoord.x, pxCoord.y);
+ if (!hex) return null;
+ setSampledHex(hex);
+ toolStoreActions.setPrimaryColor(hex, commit, colorMode);
+ return hex;
+ },
+ [colorMode]
+ );
+
+ const handleFilesSelected = useCallback(async (fileList: FileList | File[]) => {
+ const files = Array.from(fileList).filter(isImageFile);
+ if (files.length === 0) return;
+ setLoadError(null);
+ const loaded: Array<{ name: string; src: string; width: number; height: number }> = [];
+ for (const file of files) {
+ try {
+ loaded.push(await readLocalImageFile(file));
+ } catch {
+ setLoadError(`Could not load "${file.name}"`);
+ }
+ }
+ if (loaded.length > 0) {
+ subViewStoreActions.addImages(loaded);
+ }
+ }, []);
+
+ const handleReloadActiveFile = useCallback(async (file: File | undefined) => {
+ const item = activeItemRef.current;
+ if (!file || !item || !isImageFile(file)) return;
+ try {
+ const loaded = await readLocalImageFile(file);
+ subViewStoreActions.replaceImageSrc(item.id, loaded.src, loaded.width, loaded.height);
+ } catch {
+ setLoadError(`Could not load "${file.name}"`);
+ }
+ }, []);
+
+ const handleStagePointerDown = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ const item = activeItemRef.current;
+ if (!item || !item.src) return;
+ e.preventDefault();
+ e.stopPropagation();
+
+ // Middle mouse button or Space forces pan
+ const forcePan = e.button === 1 || isSpaceHeld;
+ const shouldEyedrop = !forcePan && e.button === 0 && (isEyedropperActive || e.altKey);
+
+ if (shouldEyedrop) {
+ interactionRef.current = {
+ mode: 'eyedrop',
+ pointerId: e.pointerId,
+ startClientX: e.clientX,
+ startClientY: e.clientY,
+ startPanX: 0,
+ startPanY: 0,
+ };
+ sampleColorAtClientPos(e.clientX, e.clientY, true);
+ } else if (e.button === 0 || e.button === 1) {
+ interactionRef.current = {
+ mode: 'pan',
+ pointerId: e.pointerId,
+ startClientX: e.clientX,
+ startClientY: e.clientY,
+ startPanX: liveTransformRef.current.pan.x,
+ startPanY: liveTransformRef.current.pan.y,
+ };
+ }
+
+ try {
+ e.currentTarget.setPointerCapture?.(e.pointerId);
+ } catch {
+ // Ignore in synthetic events
+ }
+ },
+ [isEyedropperActive, isSpaceHeld, sampleColorAtClientPos]
+ );
+
+ const handleStagePointerMove = useCallback(
+ (e: React.PointerEvent<HTMLDivElement>) => {
+ const state = interactionRef.current;
+ if (state.mode === 'none') return;
+
+ if (state.mode === 'eyedrop') {
+ sampleColorAtClientPos(e.clientX, e.clientY, false);
+ return;
+ }
+
+ if (state.mode === 'pan') {
+ const dx = e.clientX - state.startClientX;
+ const dy = e.clientY - state.startClientY;
+ const next: SubViewTransform = {
+ ...liveTransformRef.current,
+ pan: { x: state.startPanX + dx, y: state.startPanY + dy },
+ };
+ liveTransformRef.current = next;
+ renderDisplayCanvas(next);
+ }
+ },
+ [renderDisplayCanvas, sampleColorAtClientPos]
+ );
+
+ const finishStageInteraction = useCallback(
+ (e?: React.PointerEvent<HTMLDivElement>) => {
+ const state = interactionRef.current;
+ if (state.mode === 'none') return;
+ const prevMode = state.mode;
+ const pid = state.pointerId;
+ interactionRef.current.mode = 'none';
+ interactionRef.current.pointerId = null;
+
+ if (e && pid !== null) {
+ try {
+ e.currentTarget.releasePointerCapture?.(pid);
+ } catch {
+ // Ignore in synthetic events
+ }
+ }
+
+ const item = activeItemRef.current;
+ if (prevMode === 'pan' && item) {
+ subViewStoreActions.updateImageTransform(
+ item.id,
+ { pan: liveTransformRef.current.pan, needsInitialFit: false },
+ true
+ );
+ } else if (prevMode === 'eyedrop' && e) {
+ sampleColorAtClientPos(e.clientX, e.clientY, true);
+ }
+ },
+ [sampleColorAtClientPos]
+ );
+
+ // Independent mouse wheel zoom strictly inside Sub View
+ useEffect(() => {
+ const el = stageRef.current;
+ if (!el) return;
+ const handleWheel = (e: WheelEvent) => {
+ const item = activeItemRef.current;
+ if (!item || !item.src) return;
+ e.preventDefault();
+ e.stopPropagation();
+
+ const rect = el.getBoundingClientRect();
+ const localX = e.clientX - rect.left;
+ const localY = e.clientY - rect.top;
+ const cx = (rect.width || stageSizeRef.current.width) / 2;
+ const cy = (rect.height || stageSizeRef.current.height) / 2;
+
+ const factor = Math.exp(-e.deltaY * 0.002);
+ const cur = liveTransformRef.current;
+ const nextZoom = Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, cur.zoom * factor));
+ const ratio = nextZoom / cur.zoom;
+
+ const nextPanX = localX - cx - (localX - cx - cur.pan.x) * ratio;
+ const nextPanY = localY - cy - (localY - cy - cur.pan.y) * ratio;
+
+ const next: SubViewTransform = {
+ ...cur,
+ zoom: nextZoom,
+ pan: { x: nextPanX, y: nextPanY },
+ };
+ liveTransformRef.current = next;
+ renderDisplayCanvas(next);
+ subViewStoreActions.updateImageTransform(
+ item.id,
+ { zoom: nextZoom, pan: next.pan, needsInitialFit: false },
+ true
+ );
+ };
+ el.addEventListener('wheel', handleWheel, { passive: false });
+ return () => el.removeEventListener('wheel', handleWheel);
+ }, [renderDisplayCanvas]);
+
+ // Independent Sub View control actions (strictly local to active Sub View image)
+ const handleSubZoomBy = useCallback((factor: number) => {
+ const item = activeItemRef.current;
+ if (!item) return;
+ const nextZoom = Math.max(
+ SUB_VIEW_MIN_ZOOM,
+ Math.min(SUB_VIEW_MAX_ZOOM, liveTransformRef.current.zoom * factor)
+ );
+ subViewStoreActions.updateImageTransform(item.id, { zoom: nextZoom, needsInitialFit: false }, true);
+ }, []);
+
+ const handleSubFit = useCallback(() => {
+ const item = activeItemRef.current;
+ if (!item) return;
+ const src = sourceCanvasRef.current;
+ const w = src?.width || item.width || 1;
+ const h = src?.height || item.height || 1;
+ const { width: sw, height: sh } = stageSizeRef.current;
+ const fitZoom = computeSubViewFitZoom(sw, sh, w, h);
+ subViewStoreActions.updateImageTransform(
+ item.id,
+ { zoom: fitZoom, pan: { x: 0, y: 0 }, rotation: 0, flipX: false, needsInitialFit: false },
+ true
+ );
+ }, []);
+
+ const handleSubRotateBy = useCallback((deltaDeg: number) => {
+ const item = activeItemRef.current;
+ if (!item) return;
+ subViewStoreActions.updateImageTransform(
+ item.id,
+ { rotation: liveTransformRef.current.rotation + deltaDeg },
+ true
+ );
+ }, []);
+
+ const handleSubResetRotation = useCallback(() => {
+ const item = activeItemRef.current;
+ if (!item) return;
+ subViewStoreActions.updateImageTransform(item.id, { rotation: 0 }, true);
+ }, []);
+
+ const handleSubToggleFlipX = useCallback(() => {
+ const item = activeItemRef.current;
+ if (!item) return;
+ subViewStoreActions.updateImageTransform(
+ item.id,
+ { flipX: !liveTransformRef.current.flipX },
+ true
+ );
+ }, []);
+
+ const handleDragOver = (e: React.DragEvent<HTMLDivElement>) => {
+ // Ignore internal dock tab drag operations
+ if (e.dataTransfer.types.includes(DND_PANEL_MIME)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ e.dataTransfer.dropEffect = 'copy';
+ setIsDragOverFiles(true);
+ };
+
+ const handleDragLeave = () => {
+ setIsDragOverFiles(false);
+ };
+
+ const handleDrop = (e: React.DragEvent<HTMLDivElement>) => {
+ if (e.dataTransfer.types.includes(DND_PANEL_MIME)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragOverFiles(false);
+ if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
+ void handleFilesSelected(e.dataTransfer.files);
+ }
+ };
+
+ const btnBase = isVintage
+ ? 'h-5 px-1 rounded text-[10px] flex items-center justify-center text-[#d0d0d5] hover:text-white hover:bg-[#4e4e52] disabled:opacity-35 disabled:pointer-events-none transition-colors cursor-pointer'
+ : 'h-5 px-1 rounded text-[10px] flex items-center justify-center text-[#a3a3a3] hover:text-[#f5f5f5] hover:bg-[#2c2c2c] disabled:opacity-35 disabled:pointer-events-none transition-colors cursor-pointer';
+
+ const btnActive = isVintage
+ ? 'bg-[#337bb5] text-white'
+ : 'bg-[var(--accent-subtle)] text-[var(--accent)] ring-1 ring-inset ring-[var(--accent-border)]';
+
+ const stageCursorClass = !activeItem?.src
+ ? 'cursor-default'
+ : isEyedropperActive
+ ? 'cursor-crosshair'
+ : interactionRef.current.mode === 'pan'
+ ? 'cursor-grabbing'
+ : 'cursor-grab';
+
+ return (
+ <div
+ data-testid="sub-view-panel"
+ data-theme-preset={themePreset}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ onDrop={handleDrop}
+ className={`flex flex-col h-full min-h-0 select-none relative ${
+ isVintage ? 'bg-[#363638] text-[#e5e5e5]' : 'bg-[#202020] text-[#e5e5e5]'
+ }`}
+ >
+ {/* Hidden Local Image Inputs */}
+ <input
+ ref={fileInputRef}
+ data-testid="subview-file-input"
+ type="file"
+ accept="image/*"
+ multiple
+ className="hidden"
+ onChange={(e) => {
+ if (e.target.files && e.target.files.length > 0) {
+ void handleFilesSelected(e.target.files);
+ }
+ e.target.value = '';
+ }}
+ />
+ <input
+ ref={reloadInputRef}
+ type="file"
+ accept="image/*"
+ className="hidden"
+ onChange={(e) => {
+ void handleReloadActiveFile(e.target.files?.[0]);
+ e.target.value = '';
+ }}
+ />
+
+ {/* Top Bar: Reference Management (+, < >, index, list toggle, delete) */}
+ <div
+ className={`h-6 px-1 flex items-center justify-between gap-1 shrink-0 border-b ${
+ isVintage
+ ? 'bg-[#313134] border-[#232325]'
+ : 'bg-[#1b1b1b] border-white/[0.06]'
+ }`}
+ >
+ <div className="flex items-center gap-0.5 min-w-0">
+ <button
+ type="button"
+ data-testid="subview-add-btn"
+ onClick={() => fileInputRef.current?.click()}
+ title="Import Reference Image(s)"
+ className={`${btnBase} w-5 shrink-0`}
+ >
+ <Plus className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="subview-prev-btn"
+ disabled={items.length <= 1}
+ onClick={() => subViewStoreActions.stepActive(-1)}
+ title="Previous Reference"
+ className={`${btnBase} w-5 shrink-0`}
+ >
+ <ChevronLeft className="w-3 h-3" />
+ </button>
+ <span
+ data-testid="subview-counter"
+ className="text-[10px] font-mono tabular-nums text-[#a8a8a8] px-0.5 shrink-0"
+ >
+ {items.length > 0 ? `${activeIndex + 1}/${items.length}` : '0/0'}
+ </span>
+ <button
+ type="button"
+ data-testid="subview-next-btn"
+ disabled={items.length <= 1}
+ onClick={() => subViewStoreActions.stepActive(1)}
+ title="Next Reference"
+ className={`${btnBase} w-5 shrink-0`}
+ >
+ <ChevronRight className="w-3 h-3" />
+ </button>
+ </div>
+
+ <span
+ data-testid="subview-active-name"
+ title={activeItem?.name || ''}
+ className="text-[10px] text-[#9e9e9e] truncate flex-1 text-center px-1"
+ >
+ {activeItem?.name || 'No reference'}
+ </span>
+
+ <div className="flex items-center gap-0.5 shrink-0">
+ <button
+ type="button"
+ data-testid="subview-list-toggle"
+ disabled={items.length === 0}
+ onClick={() => subViewStoreActions.toggleShowList()}
+ aria-pressed={showList}
+ title="Reference List"
+ className={`${btnBase} w-5 ${showList && items.length > 0 ? btnActive : ''}`}
+ >
+ <List className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="subview-delete-btn"
+ disabled={!activeItem}
+ onClick={() => activeItem && subViewStoreActions.removeImage(activeItem.id)}
+ title="Remove Current Reference"
+ className={`${btnBase} w-5 hover:text-rose-400`}
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ </div>
+ </div>
+
+ {/* Optional Reference List Strip */}
+ {showList && items.length > 0 && (
+ <div
+ data-testid="subview-list-drawer"
+ className={`max-h-24 overflow-y-auto shrink-0 border-b px-1 py-0.5 flex flex-col gap-0.5 ${
+ isVintage
+ ? 'bg-[#2b2b2e] border-[#232325]'
+ : 'bg-[#181818] border-white/[0.06]'
+ }`}
+ >
+ {items.map((item, idx) => {
+ const isSelected = item.id === activeItem?.id;
+ return (
+ <div
+ key={item.id}
+ data-testid={`subview-list-item-${item.id}`}
+ onClick={() => subViewStoreActions.selectImage(item.id)}
+ className={`flex items-center gap-1.5 px-1 py-0.5 rounded text-[10px] cursor-pointer ${
+ isSelected
+ ? isVintage
+ ? 'bg-[#337bb5] text-white'
+ : 'bg-[#2c2c2c] text-[#f5f5f5]'
+ : 'text-[#a3a3a3] hover:bg-[#242424]'
+ }`}
+ >
+ {item.src ? (
+ <img
+ src={item.src}
+ alt=""
+ className="w-4 h-4 object-cover rounded-sm shrink-0 bg-[#111]"
+ />
+ ) : (
+ <div className="w-4 h-4 rounded-sm shrink-0 bg-[#2a2a2a] flex items-center justify-center text-[8px]">
+ {idx + 1}
+ </div>
+ )}
+ <span className="truncate flex-1">{item.name}</span>
+ <span className="text-[9px] opacity-60 font-mono shrink-0">
+ {item.width}x{item.height}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Reference Viewport Stage */}
+ <div
+ ref={stageRef}
+ data-testid="subview-stage"
+ onPointerEnter={() => setIsHoveringStage(true)}
+ onPointerLeave={() => {
+ setIsHoveringStage(false);
+ setSampledHex(null);
+ }}
+ onPointerDown={handleStagePointerDown}
+ onPointerMove={handleStagePointerMove}
+ onPointerUp={finishStageInteraction}
+ onPointerCancel={finishStageInteraction}
+ className={`relative flex-1 min-h-[76px] overflow-hidden flex items-center justify-center ${stageCursorClass} ${
+ isDragOverFiles
+ ? 'ring-2 ring-inset ring-[var(--accent)] bg-[var(--accent-subtle)]'
+ : isVintage
+ ? 'bg-[#252527]'
+ : 'bg-[#141414]'
+ }`}
+ >
+ <canvas
+ ref={displayCanvasRef}
+ data-testid="subview-canvas"
+ className="absolute inset-0 w-full h-full pointer-events-none"
+ />
+
+ {/* Empty State / Drop Target */}
+ {!activeItem && (
+ <button
+ type="button"
+ data-testid="subview-empty-dropzone"
+ onClick={() => fileInputRef.current?.click()}
+ className="z-10 flex flex-col items-center gap-1 px-3 py-2 rounded border border-dashed border-white/[0.15] hover:border-[var(--accent)] text-[#8a8a8a] hover:text-[#e5e5e5] transition-colors cursor-pointer"
+ >
+ <ImagePlus className="w-4 h-4 opacity-75" />
+ <span className="text-[10px]">Drop images or click +</span>
+ </button>
+ )}
+
+ {/* Persisted Metadata-Only Slot (image exceeded localStorage budget) */}
+ {activeItem && !activeItem.src && (
+ <div className="z-10 flex flex-col items-center gap-1 px-2 text-center">
+ <span className="text-[10px] text-[#9e9e9e]">
+ {activeItem.name} (reload file)
+ </span>
+ <button
+ type="button"
+ onClick={() => reloadInputRef.current?.click()}
+ className="h-5 px-2 rounded bg-[#2c2c2c] hover:bg-[#383838] text-[10px] text-[#e5e5e5] flex items-center gap-1 cursor-pointer"
+ >
+ <RefreshCw className="w-3 h-3" />
+ <span>Re-open</span>
+ </button>
+ </div>
+ )}
+
+ {/* Error Pill */}
+ {loadError && (
+ <div className="absolute bottom-1 left-1 right-1 z-20 px-1.5 py-0.5 rounded bg-rose-950/90 border border-rose-500/40 text-[9px] text-rose-200 truncate">
+ {loadError}
+ </div>
+ )}
+
+ {/* Live Sampled Color Swatch Pill */}
+ {sampledHex && (
+ <div
+ data-testid="subview-sampled-pill"
+ className="absolute top-1 right-1 z-20 px-1.5 py-0.5 rounded bg-[#161616]/90 border border-white/15 flex items-center gap-1 pointer-events-none shadow"
+ >
+ <span
+ className="w-2.5 h-2.5 rounded-sm border border-white/30 shrink-0"
+ style={{ backgroundColor: sampledHex }}
+ />
+ <span className="text-[9px] font-mono text-[#e5e5e5] uppercase">{sampledHex}</span>
+ </div>
+ )}
+ </div>
+
+ {/* Bottom Compact Control Bar (Strictly Local Sub View Transforms + Eyedropper Mode) */}
+ <div
+ className={`shrink-0 px-1.5 py-1 flex items-center justify-between gap-0.5 flex-wrap border-t ${
+ isVintage
+ ? 'bg-[#313134] border-[#232325]'
+ : 'bg-[#1b1b1b] border-white/[0.06]'
+ }`}
+ >
+ {/* Zoom + Fit */}
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ data-testid="subview-zoom-out"
+ disabled={!activeItem}
+ onClick={() => handleSubZoomBy(1 / 1.25)}
+ title="Sub View Zoom Out"
+ className={`${btnBase} w-5`}
+ >
+ <ZoomOut className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="subview-zoom-in"
+ disabled={!activeItem}
+ onClick={() => handleSubZoomBy(1.25)}
+ title="Sub View Zoom In"
+ className={`${btnBase} w-5`}
+ >
+ <ZoomIn className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="subview-fit"
+ disabled={!activeItem}
+ onClick={handleSubFit}
+ title="Reset Sub View (Fit, 0°, Unflip)"
+ className={`${btnBase} w-5`}
+ >
+ <Maximize className="w-3 h-3" />
+ </button>
+ </div>
+
+ {/* Rotate + Flip H */}
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ data-testid="subview-rotate-left"
+ disabled={!activeItem}
+ onClick={() => handleSubRotateBy(-15)}
+ title="Sub View Rotate Left (-15°)"
+ className={`${btnBase} w-5`}
+ >
+ <RotateCcw className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="subview-reset-rotation"
+ disabled={!activeItem}
+ onClick={handleSubResetRotation}
+ title="Reset Sub View Rotation (0°)"
+ className={`${btnBase} px-1 font-mono tabular-nums`}
+ >
+ {`${Math.round(activeItem?.rotation ?? 0)}°`}
+ </button>
+ <button
+ type="button"
+ data-testid="subview-rotate-right"
+ disabled={!activeItem}
+ onClick={() => handleSubRotateBy(15)}
+ title="Sub View Rotate Right (+15°)"
+ className={`${btnBase} w-5`}
+ >
+ <RotateCw className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ data-testid="subview-flip-h"
+ disabled={!activeItem}
+ aria-pressed={Boolean(activeItem?.flipX)}
+ onClick={handleSubToggleFlipX}
+ title="Sub View Flip Horizontal"
+ className={`${btnBase} w-5 ${activeItem?.flipX ? btnActive : ''}`}
+ >
+ <FlipHorizontal className="w-3 h-3" />
+ </button>
+ </div>
+
+ {/* Eyedropper / Pan Mode Controls */}
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ data-testid="subview-auto-eyedropper"
+ aria-pressed={autoEyedropper}
+ onClick={() => subViewStoreActions.toggleAutoEyedropper()}
+ title="Switch to Eyedropper Automatically on Hover/Click (CSP mode)"
+ className={`${btnBase} gap-0.5 px-1 ${autoEyedropper ? btnActive : ''}`}
+ >
+ <Pipette className="w-3 h-3" />
+ <span>Auto</span>
+ </button>
+ {!autoEyedropper && (
+ <button
+ type="button"
+ data-testid="subview-mode-toggle"
+ aria-pressed={manualEyedropper}
+ onClick={() => subViewStoreActions.setManualEyedropper(!manualEyedropper)}
+ title={manualEyedropper ? 'Eyedropper Active (click for Pan)' : 'Pan Active (click for Eyedropper)'}
+ className={`${btnBase} w-5 ${manualEyedropper ? btnActive : ''}`}
+ >
+ {manualEyedropper ? <Pipette className="w-3 h-3" /> : <Hand className="w-3 h-3" />}
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+ }
+);
+
+SubViewPanel.displayName = 'SubViewPanel';
diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.ts
index 8172ccc..bb2d382 100644
--- a/src/hooks/useCanvasNavigation.ts
+++ b/src/hooks/useCanvasNavigation.ts
@@ -31,6 +31,10 @@ export interface CanvasNavigationHandle {
flipYRef: React.MutableRefObject<boolean>;
getCameraState: () => CameraTransformState;
subscribeCamera: (listener: CameraSubscriber) => () => void;
+ setPanLive?: (pan: { x: number; y: number }, commit?: boolean) => void;
+ setZoomLive?: (targetZoom: number, commit?: boolean) => void;
+ rotateBy?: (deltaDeg: number) => void;
+ commitCameraState?: () => void;
}
export const ZOOM_PRESETS = [
@@ -315,6 +319,21 @@ export function useCanvasNavigation({
[broadcastCameraImmediate]
);
+ /** Zero-React-rerender live pan update for smooth 60-240Hz Navigator drag. */
+ const setPanLive = useCallback(
+ (nextPan: { x: number; y: number }, commit = false) => {
+ if (!Number.isFinite(nextPan.x) || !Number.isFinite(nextPan.y)) return;
+ panRef.current = { x: nextPan.x, y: nextPan.y };
+ if (commit) {
+ broadcastCameraImmediate();
+ commitNavStateImmediate();
+ } else {
+ scheduleCameraBroadcast();
+ }
+ },
+ [broadcastCameraImmediate, commitNavStateImmediate, scheduleCameraBroadcast]
+ );
+
const setRotation = useCallback(
(newRotationOrFn: number | ((prev: number) => number)) => {
const next = typeof newRotationOrFn === 'function' ? newRotationOrFn(rotationRef.current) : newRotationOrFn;
@@ -325,6 +344,36 @@ export function useCanvasNavigation({
[broadcastCameraImmediate]
);
+ /** Rotates canvas around the viewport center by `deltaDeg` degrees. */
+ const rotateBy = useCallback(
+ (deltaDeg: number) => {
+ if (!Number.isFinite(deltaDeg) || Math.abs(deltaDeg) < 0.0001) return;
+ const viewport = viewportRef.current;
+ const nextRotation = rotationRef.current + deltaDeg;
+ if (!viewport || viewport.clientWidth <= 0 || viewport.clientHeight <= 0) {
+ rotationRef.current = nextRotation;
+ setRotationState(nextRotation);
+ broadcastCameraImmediate();
+ return;
+ }
+ const vc = {
+ x: viewport.clientWidth / 2,
+ y: viewport.clientHeight / 2,
+ };
+ const dRad = (deltaDeg * Math.PI) / 180;
+ const rx = panRef.current.x - vc.x;
+ const ry = panRef.current.y - vc.y;
+ const newPanX = vc.x + rx * Math.cos(dRad) - ry * Math.sin(dRad);
+ const newPanY = vc.y + rx * Math.sin(dRad) + ry * Math.cos(dRad);
+ rotationRef.current = nextRotation;
+ panRef.current = { x: newPanX, y: newPanY };
+ setRotationState(nextRotation);
+ setPanState({ x: newPanX, y: newPanY });
+ broadcastCameraImmediate();
+ },
+ [broadcastCameraImmediate]
+ );
+
const centerCanvas = useCallback(
(targetZoom: number = zoomRef.current) => {
const viewport = viewportRef.current;
@@ -515,6 +564,33 @@ export function useCanvasNavigation({
[broadcastCameraImmediate]
);
+ /** Zero-React-rerender live zoom around viewport center (for Navigator slider scrubbing). */
+ const setZoomLive = useCallback(
+ (targetZoom: number, commit = false) => {
+ if (!Number.isFinite(targetZoom)) return;
+ const currentZoom = zoomRef.current;
+ const clampedZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, targetZoom));
+ const viewport = viewportRef.current;
+ if (viewport && viewport.clientWidth > 0 && viewport.clientHeight > 0 && Math.abs(clampedZoom - currentZoom) >= 0.00001) {
+ const centerX = viewport.clientWidth / 2;
+ const centerY = viewport.clientHeight / 2;
+ const ratio = clampedZoom / currentZoom;
+ panRef.current = {
+ x: centerX - (centerX - panRef.current.x) * ratio,
+ y: centerY - (centerY - panRef.current.y) * ratio,
+ };
+ }
+ zoomRef.current = clampedZoom;
+ if (commit) {
+ broadcastCameraImmediate();
+ commitNavStateImmediate();
+ } else {
+ scheduleCameraBroadcast();
+ }
+ },
+ [broadcastCameraImmediate, commitNavStateImmediate, scheduleCameraBroadcast]
+ );
+
const zoomIn = useCallback(() => {
const current = zoomRef.current;
let target = ZOOM_PRESETS.find((p) => p > current * 1.01);
@@ -980,8 +1056,12 @@ export function useCanvasNavigation({
flipYRef,
getCameraState,
subscribeCamera,
+ setPanLive,
+ setZoomLive,
+ rotateBy,
+ commitCameraState: commitNavStateImmediate,
}),
- [getCameraState, subscribeCamera]
+ [getCameraState, subscribeCamera, setPanLive, setZoomLive, rotateBy, commitNavStateImmediate]
);
const activeHeldModifierAction = resolveHeldKeyModifierAction(
@@ -1018,13 +1098,18 @@ export function useCanvasNavigation({
startZoomDrag,
zoomIn,
zoomOut,
+ zoomToViewportCenter,
resetZoomAndCenter,
resetRotation,
+ rotateBy,
toggleFlipHorizontal,
toggleFlipVertical,
resetViewFlip,
setZoom,
setPan,
+ setPanLive,
+ setZoomLive,
+ commitCameraState: commitNavStateImmediate,
setRotation,
centerCanvas,
};
diff --git a/src/stores/index.ts b/src/stores/index.ts
index c517bcd..3040e60 100644
--- a/src/stores/index.ts
+++ b/src/stores/index.ts
@@ -22,3 +22,6 @@ export type {
export { useWorkspaceStore, workspaceStoreActions } from './useWorkspaceStore';
export type { WorkspaceStoreState } from './useWorkspaceStore';
+
+export { useSubViewStore, subViewStoreActions } from './useSubViewStore';
+export type { SubViewStoreState, SubViewImageItem, SubViewTransform } from './useSubViewStore';
diff --git a/src/stores/useSubViewStore.ts b/src/stores/useSubViewStore.ts
new file mode 100644
index 0000000..2cc7c6a
--- /dev/null
+++ b/src/stores/useSubViewStore.ts
@@ -0,0 +1,323 @@
+import { createStore } from './createStore';
+
+export const SUB_VIEW_STORAGE_KEY = 'ink_studio_subview_v1';
+const MAX_PERSISTED_SRC_CHARS = 380_000;
+const MAX_TOTAL_PERSISTED_CHARS = 1_500_000;
+
+export interface SubViewTransform {
+ zoom: number;
+ pan: { x: number; y: number };
+ rotation: number; // degrees
+ flipX: boolean;
+}
+
+export interface SubViewImageItem {
+ id: string;
+ name: string;
+ src: string; // data: URL or safe same-origin URL (may be empty if evicted from storage on reload)
+ width: number;
+ height: number;
+ zoom: number;
+ pan: { x: number; y: number };
+ rotation: number;
+ flipX: boolean;
+ /** True until first fit-to-container calculation is performed for this item */
+ needsInitialFit?: boolean;
+}
+
+export interface SubViewStoreState {
+ items: SubViewImageItem[];
+ activeId: string | null;
+ autoEyedropper: boolean;
+ manualEyedropper: boolean;
+ showList: boolean;
+}
+
+interface PersistedSubViewPayload {
+ version: 1;
+ activeId: string | null;
+ autoEyedropper: boolean;
+ showList: boolean;
+ items: Array<{
+ id: string;
+ name: string;
+ src?: string;
+ width: number;
+ height: number;
+ zoom: number;
+ pan: { x: number; y: number };
+ rotation: number;
+ flipX: boolean;
+ needsInitialFit?: boolean;
+ }>;
+}
+
+export const SUB_VIEW_MIN_ZOOM = 0.05;
+export const SUB_VIEW_MAX_ZOOM = 16.0;
+
+function clampZoom(z: number): number {
+ if (!Number.isFinite(z)) return 1;
+ return Math.max(SUB_VIEW_MIN_ZOOM, Math.min(SUB_VIEW_MAX_ZOOM, z));
+}
+
+function isSafeImageSrc(src: unknown): src is string {
+ if (typeof src !== 'string' || !src) return false;
+ // Allow data:image/* (never data:image/svg+xml script vectors when loading raw strings unless standard)
+ // and safe local/blob/https URLs
+ if (src.startsWith('data:image/')) return true;
+ if (src.startsWith('blob:')) return false; // blob URLs do not survive reload
+ return false;
+}
+
+export function loadSubViewState(): SubViewStoreState {
+ const fallback: SubViewStoreState = {
+ items: [],
+ activeId: null,
+ autoEyedropper: true,
+ manualEyedropper: false,
+ showList: false,
+ };
+
+ try {
+ if (typeof localStorage === 'undefined') return fallback;
+ const raw = localStorage.getItem(SUB_VIEW_STORAGE_KEY);
+ if (!raw) return fallback;
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
+ if (!parsed || typeof parsed !== 'object') return fallback;
+
+ const rawItems = Array.isArray(parsed.items) ? parsed.items : [];
+ const items: SubViewImageItem[] = [];
+ const seen = new Set<string>();
+
+ for (const entry of rawItems) {
+ if (!entry || typeof entry !== 'object') continue;
+ const r = entry as Record<string, unknown>;
+ const id = typeof r.id === 'string' && r.id.trim() ? r.id : '';
+ if (!id || seen.has(id)) continue;
+ seen.add(id);
+
+ const name = typeof r.name === 'string' && r.name.trim() ? r.name.slice(0, 120) : 'Reference';
+ const src = isSafeImageSrc(r.src) ? r.src : '';
+ const width = typeof r.width === 'number' && Number.isFinite(r.width) && r.width > 0 ? Math.round(r.width) : 0;
+ const height = typeof r.height === 'number' && Number.isFinite(r.height) && r.height > 0 ? Math.round(r.height) : 0;
+ const zoom = clampZoom(typeof r.zoom === 'number' ? r.zoom : 1);
+ const panRec = r.pan && typeof r.pan === 'object' ? (r.pan as Record<string, unknown>) : null;
+ const panX = panRec && typeof panRec.x === 'number' && Number.isFinite(panRec.x) ? panRec.x : 0;
+ const panY = panRec && typeof panRec.y === 'number' && Number.isFinite(panRec.y) ? panRec.y : 0;
+ const rotation = typeof r.rotation === 'number' && Number.isFinite(r.rotation) ? r.rotation : 0;
+ const flipX = Boolean(r.flipX);
+
+ items.push({
+ id,
+ name,
+ src,
+ width,
+ height,
+ zoom,
+ pan: { x: panX, y: panY },
+ rotation,
+ flipX,
+ needsInitialFit: typeof r.needsInitialFit === 'boolean' ? r.needsInitialFit : !panX && !panY && zoom === 1,
+ });
+ }
+
+ const activeId =
+ typeof parsed.activeId === 'string' && items.some((i) => i.id === parsed.activeId)
+ ? parsed.activeId
+ : items[0]?.id ?? null;
+
+ return {
+ items,
+ activeId,
+ autoEyedropper: typeof parsed.autoEyedropper === 'boolean' ? parsed.autoEyedropper : true,
+ manualEyedropper: false,
+ showList: typeof parsed.showList === 'boolean' ? parsed.showList : false,
+ };
+ } catch {
+ return fallback;
+ }
+}
+
+export function saveSubViewState(state: SubViewStoreState): void {
+ try {
+ if (typeof localStorage === 'undefined') return;
+
+ let budget = MAX_TOTAL_PERSISTED_CHARS;
+ const serializedItems = state.items.map((item) => {
+ let persistedSrc: string | undefined;
+ if (
+ item.src.startsWith('data:image/') &&
+ item.src.length <= MAX_PERSISTED_SRC_CHARS &&
+ item.src.length <= budget
+ ) {
+ persistedSrc = item.src;
+ budget -= item.src.length;
+ }
+ return {
+ id: item.id,
+ name: item.name,
+ ...(persistedSrc ? { src: persistedSrc } : {}),
+ width: item.width,
+ height: item.height,
+ zoom: item.zoom,
+ pan: item.pan,
+ rotation: item.rotation,
+ flipX: item.flipX,
+ needsInitialFit: item.needsInitialFit,
+ };
+ });
+
+ const payload: PersistedSubViewPayload = {
+ version: 1,
+ activeId: state.activeId,
+ autoEyedropper: state.autoEyedropper,
+ showList: state.showList,
+ items: serializedItems,
+ };
+
+ try {
+ localStorage.setItem(SUB_VIEW_STORAGE_KEY, JSON.stringify(payload));
+ } catch {
+ // QuotaExceeded fallback: persist metadata without inline image payloads
+ const metadataOnly: PersistedSubViewPayload = {
+ ...payload,
+ items: payload.items.map(({ src: _omit, ...rest }) => rest),
+ };
+ localStorage.setItem(SUB_VIEW_STORAGE_KEY, JSON.stringify(metadataOnly));
+ }
+ } catch {
+ // Ignore storage access errors
+ }
+}
+
+export const useSubViewStore = createStore<SubViewStoreState>(loadSubViewState);
+
+let subViewIdSeq = 1;
+export function createSubViewItemId(): string {
+ subViewIdSeq += 1;
+ return `sv-${Date.now().toString(36)}-${subViewIdSeq}`;
+}
+
+function persist(): void {
+ saveSubViewState(useSubViewStore.getState());
+}
+
+export const subViewStoreActions = {
+ addImages(newItems: Array<{ name: string; src: string; width: number; height: number; id?: string }>): void {
+ if (newItems.length === 0) return;
+ const prepared: SubViewImageItem[] = newItems.map((item) => ({
+ id: item.id || createSubViewItemId(),
+ name: item.name.slice(0, 120) || 'Reference',
+ src: item.src,
+ width: Math.max(1, Math.round(item.width)),
+ height: Math.max(1, Math.round(item.height)),
+ zoom: 1,
+ pan: { x: 0, y: 0 },
+ rotation: 0,
+ flipX: false,
+ needsInitialFit: true,
+ }));
+
+ useSubViewStore.setState((prev) => ({
+ items: [...prev.items, ...prepared],
+ activeId: prepared[prepared.length - 1].id,
+ }));
+ persist();
+ },
+
+ removeImage(id: string): void {
+ useSubViewStore.setState((prev) => {
+ const idx = prev.items.findIndex((i) => i.id === id);
+ if (idx < 0) return prev;
+ const nextItems = prev.items.filter((i) => i.id !== id);
+ let nextActive = prev.activeId;
+ if (prev.activeId === id) {
+ const fallbackIdx = Math.min(idx, nextItems.length - 1);
+ nextActive = fallbackIdx >= 0 ? nextItems[fallbackIdx].id : null;
+ }
+ return { items: nextItems, activeId: nextActive };
+ });
+ persist();
+ },
+
+ clearAll(): void {
+ useSubViewStore.setState({ items: [], activeId: null });
+ persist();
+ },
+
+ selectImage(id: string): void {
+ useSubViewStore.setState((prev) => {
+ if (!prev.items.some((i) => i.id === id) || prev.activeId === id) return prev;
+ return { activeId: id };
+ });
+ persist();
+ },
+
+ stepActive(delta: -1 | 1): void {
+ useSubViewStore.setState((prev) => {
+ if (prev.items.length <= 1) return prev;
+ const idx = prev.items.findIndex((i) => i.id === prev.activeId);
+ const safeIdx = idx < 0 ? 0 : idx;
+ const nextIdx = (safeIdx + delta + prev.items.length) % prev.items.length;
+ return { activeId: prev.items[nextIdx].id };
+ });
+ persist();
+ },
+
+ updateImageTransform(
+ id: string,
+ patch: Partial<SubViewTransform> & { needsInitialFit?: boolean },
+ shouldPersist = true
+ ): void {
+ useSubViewStore.setState((prev) => ({
+ items: prev.items.map((item) => {
+ if (item.id !== id) return item;
+ return {
+ ...item,
+ zoom: patch.zoom !== undefined ? clampZoom(patch.zoom) : item.zoom,
+ pan: patch.pan !== undefined ? { x: patch.pan.x, y: patch.pan.y } : item.pan,
+ rotation: patch.rotation !== undefined && Number.isFinite(patch.rotation) ? patch.rotation : item.rotation,
+ flipX: patch.flipX !== undefined ? patch.flipX : item.flipX,
+ needsInitialFit: patch.needsInitialFit !== undefined ? patch.needsInitialFit : item.needsInitialFit,
+ };
+ }),
+ }));
+ if (shouldPersist) persist();
+ },
+
+ replaceImageSrc(id: string, src: string, width: number, height: number): void {
+ useSubViewStore.setState((prev) => ({
+ items: prev.items.map((item) =>
+ item.id === id
+ ? {
+ ...item,
+ src,
+ width: Math.max(1, Math.round(width)),
+ height: Math.max(1, Math.round(height)),
+ needsInitialFit: true,
+ }
+ : item
+ ),
+ }));
+ persist();
+ },
+
+ setAutoEyedropper(enabled: boolean): void {
+ useSubViewStore.setState({ autoEyedropper: enabled });
+ persist();
+ },
+
+ toggleAutoEyedropper(): void {
+ useSubViewStore.setState((prev) => ({ autoEyedropper: !prev.autoEyedropper }));
+ persist();
+ },
+
+ setManualEyedropper(enabled: boolean): void {
+ useSubViewStore.setState({ manualEyedropper: enabled });
+ },
+
+ toggleShowList(): void {
+ useSubViewStore.setState((prev) => ({ showList: !prev.showList }));
+ persist();
+ },
+};
diff --git a/src/types/workspace.ts b/src/types/workspace.ts
index bbf4936..e1f7fe7 100644
--- a/src/types/workspace.ts
+++ b/src/types/workspace.ts
@@ -5,6 +5,8 @@ export type DockPanelId =
| 'subtool'
| 'tool-property'
| 'brush-size'
+ | 'navigator'
+ | 'sub-view'
| 'color'
| 'layers'
| 'history'
@@ -98,6 +100,8 @@ export const ALL_DOCK_PANEL_IDS: DockPanelId[] = [
'subtool',
'tool-property',
'brush-size',
+ 'navigator',
+ 'sub-view',
'color',
'layers',
'history',
@@ -141,6 +145,24 @@ export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {
minWidth: 148,
maxWidth: 340,
},
+ navigator: {
+ id: 'navigator',
+ title: 'Navigator',
+ shortTitle: 'Nav',
+ defaultSide: 'right',
+ defaultWidth: 224,
+ minWidth: 176,
+ maxWidth: 380,
+ },
+ 'sub-view': {
+ id: 'sub-view',
+ title: 'Sub View',
+ shortTitle: 'SubView',
+ defaultSide: 'right',
+ defaultWidth: 224,
+ minWidth: 176,
+ maxWidth: 400,
+ },
color: {
id: 'color',
title: 'Color Wheel',
diff --git a/src/utils/__tests__/navigatorAndSubView.test.tsx b/src/utils/__tests__/navigatorAndSubView.test.tsx
new file mode 100644
index 0000000..aa54417
--- /dev/null
+++ b/src/utils/__tests__/navigatorAndSubView.test.tsx
@@ -0,0 +1,828 @@
+import { act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { ALL_DOCK_PANEL_IDS, DOCK_PANEL_META } from '../../types/workspace';
+import {
+ findPanelLocation,
+ getPresetLayout,
+} from '../workspacePresets';
+import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';
+import {
+ SUB_VIEW_STORAGE_KEY,
+ subViewStoreActions,
+ useSubViewStore,
+} from '../../stores/useSubViewStore';
+import { useToolStore } from '../../stores/useToolStore';
+import { SparseTileGrid } from '../tileEngine';
+import { ViewportCompositor } from '../compositor';
+import {
+ NavigatorPanel,
+ computePanForDocCenter,
+ computeViewportQuadInDoc,
+ isPointInConvexQuad,
+ sliderPosToZoom,
+ viewportPointToDoc,
+ zoomToSliderPos,
+} from '../../components/NavigatorPanel';
+import {
+ SubViewPanel,
+ samplePixelHexFromCanvas,
+ subViewPointToImagePixel,
+} from '../../components/SubViewPanel';
+import { CameraSubscriber, CameraTransformState, CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
+import { CanvasDimensions, LayerItem } from '../../types/editor';
+
+function createMemoryStorage(): Storage {
+ const store = new Map<string, string>();
+ return {
+ get length() {
+ return store.size;
+ },
+ clear() {
+ store.clear();
+ },
+ getItem(key: string) {
+ return store.has(key) ? store.get(key)! : null;
+ },
+ key(index: number) {
+ return Array.from(store.keys())[index] ?? null;
+ },
+ removeItem(key: string) {
+ store.delete(key);
+ },
+ setItem(key: string, value: string) {
+ store.set(key, String(value));
+ },
+ };
+}
+
+class MiniText {
+ nodeType = 3;
+ nodeName = '#text';
+ parentNode: MiniEl | null = null;
+ constructor(public nodeValue: string, public ownerDocument: MiniDoc) {}
+}
+
+class MiniComment {
+ nodeType = 8;
+ nodeName = '#comment';
+ parentNode: MiniEl | null = null;
+ constructor(public nodeValue: string, public ownerDocument: MiniDoc) {}
+}
+
+function createMock2DContext(pixelColor: [number, number, number, number] = [255, 64, 32, 255]) {
+ return {
+ save: vi.fn(),
+ restore: vi.fn(),
+ setTransform: vi.fn(),
+ clearRect: vi.fn(),
+ fillRect: vi.fn(),
+ strokeRect: vi.fn(),
+ beginPath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ closePath: vi.fn(),
+ fill: vi.fn(),
+ stroke: vi.fn(),
+ translate: vi.fn(),
+ rotate: vi.fn(),
+ scale: vi.fn(),
+ drawImage: vi.fn(),
+ createImageData: (w: number, h: number) => ({ data: new Uint8ClampedArray(w * h * 4), width: w, height: h }),
+ putImageData: vi.fn(),
+ getImageData: vi.fn((_x: number, _y: number, w: number, h: number) => {
+ const data = new Uint8ClampedArray(w * h * 4);
+ for (let i = 0; i < data.length; i += 4) {
+ data[i] = pixelColor[0];
+ data[i + 1] = pixelColor[1];
+ data[i + 2] = pixelColor[2];
+ data[i + 3] = pixelColor[3];
+ }
+ return { data, width: w, height: h };
+ }),
+ imageSmoothingEnabled: true,
+ fillStyle: '',
+ strokeStyle: '',
+ lineWidth: 1,
+ globalAlpha: 1,
+ globalCompositeOperation: 'source-over',
+ };
+}
+
+class MiniEl extends EventTarget {
+ nodeType = 1;
+ nodeName: string;
+ tagName: string;
+ namespaceURI = 'http://www.w3.org/1999/xhtml';
+ parentNode: MiniEl | null = null;
+ childNodes: Array<MiniEl | MiniText | MiniComment> = [];
+ style: Record<string, string> = {};
+ className = '';
+ disabled = false;
+ value = '';
+ width = 200;
+ height = 120;
+ clientWidth = 200;
+ clientHeight = 120;
+ attrs = new Map<string, string>();
+ private mockCtx: ReturnType<typeof createMock2DContext> | null = null;
+
+ constructor(tag: string, public ownerDocument: MiniDoc) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = tag.toUpperCase();
+ }
+
+ get firstChild() {
+ return this.childNodes[0] ?? null;
+ }
+
+ get textContent(): string {
+ return this.childNodes
+ .map((c) => (c instanceof MiniText ? c.nodeValue : c instanceof MiniEl ? c.textContent : ''))
+ .join('');
+ }
+
+ set textContent(val: string) {
+ this.childNodes = val ? [new MiniText(val, this.ownerDocument)] : [];
+ }
+
+ getBoundingClientRect() {
+ return {
+ left: 0,
+ top: 0,
+ width: this.clientWidth,
+ height: this.clientHeight,
+ right: this.clientWidth,
+ bottom: this.clientHeight,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ };
+ }
+
+ setPointerCapture() {}
+ releasePointerCapture() {}
+
+ override dispatchEvent(event: Event): boolean {
+ if (!event.target) {
+ Object.defineProperty(event, 'target', { value: this, configurable: true });
+ }
+ let cur: MiniEl | null = this;
+ while (cur) {
+ EventTarget.prototype.dispatchEvent.call(cur, event);
+ if (!event.bubbles) break;
+ cur = cur.parentNode;
+ }
+ return !event.defaultPrevented;
+ }
+
+ getContext(type: string) {
+ if (type === '2d') {
+ if (!this.mockCtx) this.mockCtx = createMock2DContext(this.ownerDocument.mockSampleColor);
+ return this.mockCtx;
+ }
+ return null;
+ }
+
+ appendChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
+ if (child.parentNode) child.parentNode.removeChild(child);
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+
+ removeChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
+ const idx = this.childNodes.indexOf(child);
+ if (idx >= 0) {
+ this.childNodes.splice(idx, 1);
+ child.parentNode = null;
+ }
+ return child;
+ }
+
+ insertBefore<T extends MiniEl | MiniText | MiniComment>(
+ node: T,
+ ref: MiniEl | MiniText | MiniComment | null
+ ): T {
+ if (node.parentNode) node.parentNode.removeChild(node);
+ node.parentNode = this;
+ const idx = ref ? this.childNodes.indexOf(ref) : -1;
+ if (idx >= 0) this.childNodes.splice(idx, 0, node);
+ else this.childNodes.push(node);
+ return node;
+ }
+
+ setAttribute(k: string, v: string) {
+ this.attrs.set(k, String(v));
+ }
+
+ getAttribute(k: string): string | null {
+ return this.attrs.get(k) ?? null;
+ }
+
+ removeAttribute(k: string) {
+ this.attrs.delete(k);
+ }
+
+ contains(target: unknown): boolean {
+ if (target === this) return true;
+ for (const c of this.childNodes) {
+ if (c === target) return true;
+ if (c instanceof MiniEl && c.contains(target)) return true;
+ }
+ return false;
+ }
+
+ findByAttr(attr: string, value: string): MiniEl | null {
+ if (this.getAttribute(attr) === value) return this;
+ for (const c of this.childNodes) {
+ if (c instanceof MiniEl) {
+ const found = c.findByAttr(attr, value);
+ if (found) return found;
+ }
+ }
+ return null;
+ }
+}
+
+interface MiniDoc {
+ nodeType: number;
+ nodeName: string;
+ documentElement: MiniEl;
+ body: MiniEl;
+ activeElement: MiniEl;
+ defaultView: Record<string, unknown>;
+ mockSampleColor: [number, number, number, number];
+ createElement: (tag: string) => MiniEl;
+ createElementNS: (_ns: string, tag: string) => MiniEl;
+ createTextNode: (text: string) => MiniText;
+ createComment: (text: string) => MiniComment;
+ addEventListener: EventTarget['addEventListener'];
+ removeEventListener: EventTarget['removeEventListener'];
+ dispatchEvent: EventTarget['dispatchEvent'];
+}
+
+function installMiniDom(sampleColor: [number, number, number, number] = [52, 168, 83, 255]) {
+ const g = globalThis as unknown as Record<string, unknown>;
+ const saved: Record<string, unknown> = {
+ window: g.window,
+ document: g.document,
+ HTMLElement: g.HTMLElement,
+ Node: g.Node,
+ Element: g.Element,
+ Image: g.Image,
+ requestAnimationFrame: g.requestAnimationFrame,
+ cancelAnimationFrame: g.cancelAnimationFrame,
+ IS_REACT_ACT_ENVIRONMENT: g.IS_REACT_ACT_ENVIRONMENT,
+ };
+ g.IS_REACT_ACT_ENVIRONMENT = true;
+
+ const winTarget = new EventTarget();
+ const docTarget = new EventTarget();
+
+ const mockDoc: MiniDoc = {
+ nodeType: 9,
+ nodeName: '#document',
+ documentElement: null as unknown as MiniEl,
+ body: null as unknown as MiniEl,
+ activeElement: null as unknown as MiniEl,
+ defaultView: null as unknown as Record<string, unknown>,
+ mockSampleColor: sampleColor,
+ createElement: (tag: string) => new MiniEl(tag, mockDoc),
+ createElementNS: (_ns: string, tag: string) => new MiniEl(tag, mockDoc),
+ createTextNode: (text: string) => new MiniText(text, mockDoc),
+ createComment: (text: string) => new MiniComment(text, mockDoc),
+ addEventListener: docTarget.addEventListener.bind(docTarget),
+ removeEventListener: docTarget.removeEventListener.bind(docTarget),
+ dispatchEvent: docTarget.dispatchEvent.bind(docTarget),
+ };
+
+ mockDoc.documentElement = new MiniEl('html', mockDoc);
+ mockDoc.body = new MiniEl('body', mockDoc);
+ mockDoc.documentElement.appendChild(mockDoc.body);
+ mockDoc.activeElement = mockDoc.body;
+
+ class MockImage {
+ naturalWidth = 100;
+ naturalHeight = 100;
+ width = 100;
+ height = 100;
+ crossOrigin = '';
+ onload: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ private _src = '';
+ get src() {
+ return this._src;
+ }
+ set src(val: string) {
+ this._src = val;
+ if (val && this.onload) {
+ this.onload();
+ }
+ }
+ }
+
+ class MockIFrame extends MiniEl {}
+
+ const rafMock = (cb: FrameRequestCallback) => {
+ cb(16);
+ return 1;
+ };
+ const cancelRafMock = () => {};
+
+ const mockWin: Record<string, unknown> = {
+ innerWidth: 1440,
+ innerHeight: 900,
+ devicePixelRatio: 1,
+ document: mockDoc,
+ Node: MiniEl,
+ Element: MiniEl,
+ HTMLElement: MiniEl,
+ SVGElement: MiniEl,
+ HTMLIFrameElement: MockIFrame,
+ Event,
+ CustomEvent,
+ addEventListener: winTarget.addEventListener.bind(winTarget),
+ removeEventListener: winTarget.removeEventListener.bind(winTarget),
+ dispatchEvent: winTarget.dispatchEvent.bind(winTarget),
+ requestAnimationFrame: rafMock,
+ cancelAnimationFrame: cancelRafMock,
+ };
+ mockDoc.defaultView = mockWin;
+
+ g.window = mockWin;
+ g.document = mockDoc;
+ g.HTMLElement = MiniEl;
+ g.Node = MiniEl;
+ g.Element = MiniEl;
+ g.Image = MockImage;
+ g.requestAnimationFrame = rafMock;
+ g.cancelAnimationFrame = cancelRafMock;
+
+ const container = new MiniEl('div', mockDoc);
+ mockDoc.body.appendChild(container);
+
+ return {
+ container,
+ mockDoc,
+ cleanup: () => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete g[k];
+ else g[k] = v;
+ }
+ },
+ };
+}
+
+function createMockNavigation(initial?: Partial<CameraTransformState>) {
+ const subs = new Set<CameraSubscriber>();
+ const state: CameraTransformState = {
+ pan: initial?.pan ?? { x: 400, y: 300 },
+ zoom: initial?.zoom ?? 1,
+ rotation: initial?.rotation ?? 0,
+ flipX: initial?.flipX ?? false,
+ flipY: initial?.flipY ?? false,
+ };
+
+ const panRef = { current: { ...state.pan } };
+ const zoomRef = { current: state.zoom };
+ const rotationRef = { current: state.rotation };
+ const flipXRef = { current: state.flipX };
+ const flipYRef = { current: state.flipY };
+
+ const emit = () => {
+ const cam: CameraTransformState = {
+ pan: { ...panRef.current },
+ zoom: zoomRef.current,
+ rotation: rotationRef.current,
+ flipX: flipXRef.current,
+ flipY: flipYRef.current,
+ };
+ subs.forEach((fn) => fn(cam));
+ };
+
+ const setPanLive = vi.fn((next: { x: number; y: number }, _commit?: boolean) => {
+ panRef.current = { ...next };
+ emit();
+ });
+ const setZoomLive = vi.fn((z: number, _commit?: boolean) => {
+ zoomRef.current = z;
+ emit();
+ });
+ const rotateBy = vi.fn((delta: number) => {
+ rotationRef.current += delta;
+ emit();
+ });
+ const commitCameraState = vi.fn();
+
+ const handle: CanvasNavigationHandle = {
+ panRef,
+ zoomRef,
+ rotationRef,
+ flipXRef,
+ flipYRef,
+ getCameraState: () => ({
+ pan: { ...panRef.current },
+ zoom: zoomRef.current,
+ rotation: rotationRef.current,
+ flipX: flipXRef.current,
+ flipY: flipYRef.current,
+ }),
+ subscribeCamera: (fn) => {
+ subs.add(fn);
+ return () => subs.delete(fn);
+ },
+ setPanLive,
+ setZoomLive,
+ rotateBy,
+ commitCameraState,
+ };
+
+ return { handle, setPanLive, setZoomLive, rotateBy, commitCameraState, emit };
+}
+
+describe('Navigator & Sub View Dock Integration and Presets', () => {
+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;
+
+ beforeEach(() => {
+ Object.defineProperty(globalThis, 'localStorage', {
+ value: createMemoryStorage(),
+ configurable: true,
+ writable: true,
+ });
+ useWorkspaceStore.reset();
+ useSubViewStore.reset();
+ });
+
+ afterEach(() => {
+ if (prevStorage === undefined) {
+ delete (globalThis as unknown as Record<string, unknown>).localStorage;
+ } else {
+ Object.defineProperty(globalThis, 'localStorage', {
+ value: prevStorage,
+ configurable: true,
+ writable: true,
+ });
+ }
+ });
+
+ it('registers navigator and sub-view in dock metadata and all three workspace presets', () => {
+ expect(ALL_DOCK_PANEL_IDS).toContain('navigator');
+ expect(ALL_DOCK_PANEL_IDS).toContain('sub-view');
+ expect(DOCK_PANEL_META.navigator.title).toBe('Navigator');
+ expect(DOCK_PANEL_META['sub-view'].title).toBe('Sub View');
+
+ for (const preset of ['default-illustration', 'manga-studio', 'minimalist-tablet'] as const) {
+ const layout = getPresetLayout(preset);
+ expect(findPanelLocation(layout, 'navigator')).not.toBeNull();
+ expect(findPanelLocation(layout, 'sub-view')).not.toBeNull();
+ }
+ });
+
+ it('supports docking, moving, hiding, and persisting navigator and sub-view across reload', () => {
+ workspaceStoreActions.movePanel('navigator', { side: 'left' });
+ workspaceStoreActions.movePanel('sub-view', { side: 'left' });
+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'navigator')?.side).toBe('left');
+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'sub-view')?.side).toBe('left');
+
+ useWorkspaceStore.reset();
+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'navigator')?.side).toBe('left');
+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'sub-view')?.side).toBe('left');
+ });
+});
+
+describe('NavigatorPanel Geometry, Throttled Preview & Smooth Pan', () => {
+ const dims: CanvasDimensions = { width: 1000, height: 800, dpi: 300 };
+
+ it('computes exact viewport quad and inverse pan under rotation, flipX, and flipY', () => {
+ const cases: CameraTransformState[] = [
+ { pan: { x: 400, y: 300 }, zoom: 1, rotation: 0, flipX: false, flipY: false },
+ { pan: { x: 250, y: 180 }, zoom: 2.5, rotation: 37, flipX: false, flipY: false },
+ { pan: { x: 520, y: 310 }, zoom: 1.5, rotation: -45, flipX: true, flipY: false },
+ { pan: { x: 310, y: 420 }, zoom: 0.75, rotation: 120, flipX: true, flipY: true },
+ ];
+
+ for (const cam of cases) {
+ const quad = computeViewportQuadInDoc(800, 600, cam, dims);
+ const centerDoc = viewportPointToDoc(400, 300, cam, dims);
+ expect(isPointInConvexQuad(centerDoc, quad)).toBe(true);
+
+ // Inverse pan: asking to center on targetDoc=(200, 150) must map (400, 300) back to (200, 150)
+ const targetDoc = { x: 200, y: 150 };
+ const nextPan = computePanForDocCenter(targetDoc, 800, 600, cam, dims);
+ const verify = viewportPointToDoc(400, 300, { ...cam, pan: nextPan }, dims);
+ expect(verify.x).toBeCloseTo(targetDoc.x, 4);
+ expect(verify.y).toBeCloseTo(targetDoc.y, 4);
+ }
+
+ // Zoom slider roundtrip
+ expect(sliderPosToZoom(zoomToSliderPos(1.0))).toBeCloseTo(1.0, 2);
+ expect(sliderPosToZoom(zoomToSliderPos(4.0))).toBeCloseTo(4.0, 1);
+ });
+
+ it('throttles low-LOD preview composites (~200ms) and pans main canvas via setPanLive on drag', () => {
+ vi.useFakeTimers();
+ const dom = installMiniDom();
+ let root: Root | null = null;
+ const renderPreviewSpy = vi
+ .spyOn(ViewportCompositor, 'renderLowResPreview')
+ .mockImplementation(() => {});
+
+ try {
+ const grid = new SparseTileGrid();
+ const nav = createMockNavigation({ pan: { x: 400, y: 300 }, zoom: 2, rotation: 0 });
+ const viewportEl = { clientWidth: 800, clientHeight: 600 } as HTMLDivElement;
+ const viewportRef = { current: viewportEl };
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-1',
+ name: 'Ink',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ alphaLocked: false,
+ clipped: false,
+ parentId: null,
+ },
+ ];
+
+ const onFit = vi.fn();
+ const onZoom100 = vi.fn();
+ const onFlipH = vi.fn();
+ const onFlipV = vi.fn();
+
+ act(() => {
+ root = createRoot(dom.container as unknown as Element);
+ root.render(
+ <NavigatorPanel
+ viewportRef={viewportRef}
+ navigation={nav.handle}
+ dimensions={dims}
+ layers={layers}
+ tileGrid={grid}
+ showCheckerboard={false}
+ zoom={2}
+ rotation={0}
+ flipX={false}
+ flipY={false}
+ onZoomIn={vi.fn()}
+ onZoomOut={vi.fn()}
+ onFitToScreen={onFit}
+ onZoomActualSize={onZoom100}
+ onRotateLeft={vi.fn()}
+ onRotateRight={vi.fn()}
+ onResetRotation={vi.fn()}
+ onToggleFlipHorizontal={onFlipH}
+ onToggleFlipVertical={onFlipV}
+ throttleMs={200}
+ />
+ );
+ });
+
+ // Initial render happened once
+ expect(renderPreviewSpy).toHaveBeenCalledTimes(1);
+
+ // Burst 15 rapid tile updates during fast strokes -> must be coalesced by 200ms throttle
+ act(() => {
+ for (let i = 0; i < 15; i++) {
+ grid.notifyChange(false);
+ }
+ });
+ expect(renderPreviewSpy).toHaveBeenCalledTimes(1);
+
+ act(() => {
+ vi.advanceTimersByTime(220);
+ });
+ expect(renderPreviewSpy).toHaveBeenCalledTimes(2);
+
+ // Drag on Navigator stage to pan main canvas smoothly via setPanLive
+ const stage = dom.container.findByAttr('data-testid', 'navigator-preview-stage');
+ expect(stage).not.toBeNull();
+
+ act(() => {
+ stage!.dispatchEvent(
+ Object.assign(new Event('pointerdown', { bubbles: true }), {
+ button: 0,
+ pointerId: 1,
+ clientX: 30,
+ clientY: 30,
+ })
+ );
+ stage!.dispatchEvent(
+ Object.assign(new Event('pointermove', { bubbles: true }), {
+ button: 0,
+ pointerId: 1,
+ clientX: 140,
+ clientY: 85,
+ })
+ );
+ stage!.dispatchEvent(
+ Object.assign(new Event('pointerup', { bubbles: true }), {
+ button: 0,
+ pointerId: 1,
+ clientX: 140,
+ clientY: 85,
+ })
+ );
+ });
+
+ expect(nav.setPanLive).toHaveBeenCalled();
+ expect(nav.commitCameraState).toHaveBeenCalledTimes(1);
+
+ // Verify compact control bar buttons
+ const fitBtn = dom.container.findByAttr('data-testid', 'nav-fit-screen');
+ const z100Btn = dom.container.findByAttr('data-testid', 'nav-zoom-100');
+ const flipHBtn = dom.container.findByAttr('data-testid', 'nav-flip-h');
+ const flipVBtn = dom.container.findByAttr('data-testid', 'nav-flip-v');
+ act(() => {
+ fitBtn!.dispatchEvent(new Event('click', { bubbles: true }));
+ z100Btn!.dispatchEvent(new Event('click', { bubbles: true }));
+ flipHBtn!.dispatchEvent(new Event('click', { bubbles: true }));
+ flipVBtn!.dispatchEvent(new Event('click', { bubbles: true }));
+ });
+ expect(onFit).toHaveBeenCalledTimes(1);
+ expect(onZoom100).toHaveBeenCalledTimes(1);
+ expect(onFlipH).toHaveBeenCalledTimes(1);
+ expect(onFlipV).toHaveBeenCalledTimes(1);
+ } finally {
+ renderPreviewSpy.mockRestore();
+ if (root) {
+ act(() => {
+ root?.unmount();
+ });
+ }
+ dom.cleanup();
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('SubViewPanel Reference Management, Transforms & CORS-Safe Eyedropper', () => {
+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;
+
+ beforeEach(() => {
+ Object.defineProperty(globalThis, 'localStorage', {
+ value: createMemoryStorage(),
+ configurable: true,
+ writable: true,
+ });
+ useSubViewStore.reset();
+ useToolStore.reset();
+ });
+
+ afterEach(() => {
+ if (prevStorage === undefined) {
+ delete (globalThis as unknown as Record<string, unknown>).localStorage;
+ } else {
+ Object.defineProperty(globalThis, 'localStorage', {
+ value: prevStorage,
+ configurable: true,
+ writable: true,
+ });
+ }
+ });
+
+ it('inverse-maps Sub View pointer coordinates accurately under pan, zoom, rotation, and flipX', () => {
+ // Center of stage (100, 70) maps to center pixel (50, 50) of a 100x100 image
+ expect(
+ subViewPointToImagePixel(100, 70, 200, 140, 100, 100, {
+ zoom: 1,
+ pan: { x: 0, y: 0 },
+ rotation: 0,
+ flipX: false,
+ })
+ ).toEqual({ x: 50, y: 50 });
+
+ // With flipX=true, +10px right of center maps to -10px in image X (40, 50)
+ expect(
+ subViewPointToImagePixel(110, 70, 200, 140, 100, 100, {
+ zoom: 1,
+ pan: { x: 0, y: 0 },
+ rotation: 0,
+ flipX: true,
+ })
+ ).toEqual({ x: 40, y: 50 });
+
+ // Outside bounds returns null
+ expect(
+ subViewPointToImagePixel(0, 0, 200, 140, 20, 20, {
+ zoom: 1,
+ pan: { x: 0, y: 0 },
+ rotation: 0,
+ flipX: false,
+ })
+ ).toBeNull();
+ });
+
+ it('samples hex color cleanly and catches CORS SecurityError without throwing', () => {
+ const okCanvas = {
+ width: 10,
+ height: 10,
+ getContext: () => ({
+ getImageData: () => ({ data: new Uint8ClampedArray([18, 52, 86, 255]) }),
+ }),
+ } as unknown as HTMLCanvasElement;
+ expect(samplePixelHexFromCanvas(okCanvas, 2, 2)).toBe('#123456');
+
+ const transparentCanvas = {
+ width: 10,
+ height: 10,
+ getContext: () => ({
+ getImageData: () => ({ data: new Uint8ClampedArray([255, 0, 0, 0]) }),
+ }),
+ } as unknown as HTMLCanvasElement;
+ expect(samplePixelHexFromCanvas(transparentCanvas, 2, 2)).toBeNull();
+
+ const taintedCanvas = {
+ width: 10,
+ height: 10,
+ getContext: () => ({
+ getImageData: () => {
+ throw new Error('SecurityError: tainted canvas');
+ },
+ }),
+ } as unknown as HTMLCanvasElement;
+ expect(samplePixelHexFromCanvas(taintedCanvas, 2, 2)).toBeNull();
+ });
+
+ it('loads multiple references, persists session metadata, transforms independently, and sets primaryColor on eyedropper click', () => {
+ const dom = installMiniDom([52, 168, 83, 255]); // #34a853
+ let root: Root | null = null;
+
+ try {
+ subViewStoreActions.addImages([
+ { id: 'ref-1', name: 'character_sheet.png', src: 'data:image/png;base64,AAA', width: 100, height: 100 },
+ { id: 'ref-2', name: 'palette_study.png', src: 'data:image/png;base64,BBB', width: 100, height: 100 },
+ ]);
+
+ expect(useSubViewStore.getState().items.length).toBe(2);
+ expect(useSubViewStore.getState().activeId).toBe('ref-2');
+
+ act(() => {
+ root = createRoot(dom.container as unknown as Element);
+ root.render(<SubViewPanel colorMode="color" themePreset="modern" />);
+ });
+
+ expect(dom.container.findByAttr('data-testid', 'subview-counter')?.textContent).toBe('2/2');
+
+ // Navigate to previous reference (<)
+ act(() => {
+ dom.container
+ .findByAttr('data-testid', 'subview-prev-btn')!
+ .dispatchEvent(new Event('click', { bubbles: true }));
+ });
+ expect(useSubViewStore.getState().activeId).toBe('ref-1');
+ expect(dom.container.findByAttr('data-testid', 'subview-counter')?.textContent).toBe('1/2');
+
+ // Independent transform controls: rotate + flipH
+ act(() => {
+ dom.container
+ .findByAttr('data-testid', 'subview-rotate-right')!
+ .dispatchEvent(new Event('click', { bubbles: true }));
+ dom.container
+ .findByAttr('data-testid', 'subview-flip-h')!
+ .dispatchEvent(new Event('click', { bubbles: true }));
+ });
+ const activeAfterTransform = useSubViewStore.getState().items.find((i) => i.id === 'ref-1')!;
+ expect(activeAfterTransform.rotation).toBe(15);
+ expect(activeAfterTransform.flipX).toBe(true);
+
+ // Clicking reference image in Auto Eyedropper mode immediately updates active brush primaryColor
+ expect(useToolStore.getState().primaryColor).toBe('#000000');
+ const stage = dom.container.findByAttr('data-testid', 'subview-stage');
+ expect(stage).not.toBeNull();
+ act(() => {
+ stage!.dispatchEvent(
+ Object.assign(new Event('pointerdown', { bubbles: true }), {
+ button: 0,
+ pointerId: 1,
+ clientX: 100,
+ clientY: 60,
+ })
+ );
+ });
+ expect(useToolStore.getState().primaryColor).toBe('#34a853');
+ expect(useToolStore.getState().brushSettings.color).toBe('#34a853');
+
+ // Persist across reload
+ expect(localStorage.getItem(SUB_VIEW_STORAGE_KEY)).toBeTruthy();
+ act(() => {
+ useSubViewStore.reset();
+ });
+ expect(useSubViewStore.getState().items.length).toBe(2);
+ expect(useSubViewStore.getState().activeId).toBe('ref-1');
+ expect(useSubViewStore.getState().items[0].flipX).toBe(true);
+ expect(useSubViewStore.getState().items[0].rotation).toBe(15);
+ } finally {
+ if (root) {
+ act(() => {
+ root?.unmount();
+ });
+ }
+ dom.cleanup();
+ }
+ });
+});
diff --git a/src/utils/compositor.ts b/src/utils/compositor.ts
index 93144c3..87addb5 100644
--- a/src/utils/compositor.ts
+++ b/src/utils/compositor.ts
@@ -5045,6 +5045,188 @@ export class ViewportCompositor {
ctx.restore();
}
+ private static previewTileCanvas: HTMLCanvasElement | null = null;
+ private static previewScratchCanvas: HTMLCanvasElement | null = null;
+
+ /**
+ * Lightweight low-LOD composite preview renderer for Navigator & thumbnails.
+ * Reads directly from SparseTileGrid mipmap LOD tiles (no WebGL context creation, no GPU readPixels stall).
+ */
+ public static renderLowResPreview(
+ targetCanvas: HTMLCanvasElement,
+ layers: LayerItem[],
+ dimensions: CanvasDimensions,
+ grid: SparseTileGrid = globalTileGrid,
+ options: { showCheckerboard?: boolean } = {}
+ ): void {
+ if (typeof document === 'undefined') return;
+ const ctx = targetCanvas.getContext('2d');
+ if (!ctx) return;
+
+ const outW = Math.max(1, Math.floor(targetCanvas.width));
+ const outH = Math.max(1, Math.floor(targetCanvas.height));
+ const docW = Math.max(1, dimensions.width);
+ const docH = Math.max(1, dimensions.height);
+
+ // Choose lowest sufficient LOD based on downscale ratio (avoids reading full-res tiles on 4K+ canvases)
+ const ratio = Math.max(docW / outW, docH / outH);
+ const targetLod = ratio >= 7 ? 3 : ratio >= 3.5 ? 2 : ratio >= 1.8 ? 1 : 0;
+ const lodDocSize = TILE_SIZE << targetLod;
+ const scaleX = outW / docW;
+ const scaleY = outH / docH;
+
+ // 1. Background
+ ctx.save();
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.globalAlpha = 1;
+ if (options.showCheckerboard) {
+ const cell = 6;
+ ctx.fillStyle = '#202020';
+ ctx.fillRect(0, 0, outW, outH);
+ ctx.fillStyle = '#2a2a2a';
+ for (let y = 0; y < outH; y += cell) {
+ const offset = ((y / cell) & 1) * cell;
+ for (let x = offset; x < outW; x += cell * 2) {
+ ctx.fillRect(x, y, cell, cell);
+ }
+ }
+ } else {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, outW, outH);
+ }
+
+ if (!ViewportCompositor.previewTileCanvas) {
+ ViewportCompositor.previewTileCanvas = document.createElement('canvas');
+ ViewportCompositor.previewTileCanvas.width = TILE_SIZE;
+ ViewportCompositor.previewTileCanvas.height = TILE_SIZE;
+ }
+ const tileCanvas = ViewportCompositor.previewTileCanvas;
+ const tileCtx = tileCanvas.getContext('2d', { willReadFrequently: true });
+ if (!tileCtx) {
+ ctx.restore();
+ return;
+ }
+
+ const drawSingleLayer = (
+ dstCtx: CanvasRenderingContext2D,
+ layer: LayerItem,
+ opacityMul: number,
+ compositeOverride?: GlobalCompositeOperation
+ ) => {
+ const alpha = Math.max(0, Math.min(1, layer.opacity * opacityMul));
+ if (alpha <= 0.001) return;
+
+ const tiles = grid.getOrBuildLodTiles(layer.id, targetLod);
+ if (tiles.length === 0) return;
+
+ dstCtx.save();
+ dstCtx.globalAlpha = alpha;
+ dstCtx.globalCompositeOperation = compositeOverride ?? getCanvasCompositeOperation(layer.blendMode);
+ dstCtx.imageSmoothingEnabled = true;
+
+ for (const tile of tiles) {
+ const rgba = grid.getTileAsRGBA(tile);
+ const imgData = tileCtx.createImageData(TILE_SIZE, TILE_SIZE);
+ imgData.data.set(rgba);
+ tileCtx.putImageData(imgData, 0, 0);
+
+ const dx = tile.tileX * lodDocSize * scaleX;
+ const dy = tile.tileY * lodDocSize * scaleY;
+ const dw = lodDocSize * scaleX;
+ const dh = lodDocSize * scaleY;
+ dstCtx.drawImage(tileCanvas, dx, dy, dw, dh);
+ }
+
+ dstCtx.restore();
+ };
+
+ const renderNodes = (
+ dstCtx: CanvasRenderingContext2D,
+ nodes: LayerTreeNode[],
+ opacityMul: number
+ ) => {
+ const renderOrder = nodes.slice().reverse();
+ const groups = groupTreeNodesForCompositing(renderOrder);
+
+ for (const group of groups) {
+ const baseNode = group.baseNode;
+ const baseLayer = baseNode.layer;
+ if (!baseLayer.visible || baseLayer.opacity <= 0.001) continue;
+
+ if (baseLayer.type === 'folder') {
+ const folderOpacity = opacityMul * baseLayer.opacity;
+ if (baseLayer.blendMode === 'pass-through') {
+ if (baseNode.children.length > 0) {
+ renderNodes(dstCtx, baseNode.children, folderOpacity);
+ }
+ } else {
+ const tmp = document.createElement('canvas');
+ tmp.width = outW;
+ tmp.height = outH;
+ const tmpCtx = tmp.getContext('2d');
+ if (tmpCtx) {
+ if (baseNode.children.length > 0) {
+ renderNodes(tmpCtx, baseNode.children, 1.0);
+ }
+ dstCtx.save();
+ dstCtx.globalAlpha = Math.max(0, Math.min(1, folderOpacity));
+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ dstCtx.drawImage(tmp, 0, 0);
+ dstCtx.restore();
+ }
+ }
+ continue;
+ }
+
+ if (baseLayer.type === 'adjustment' && baseLayer.adjustmentData) {
+ try {
+ const imgData = dstCtx.getImageData(0, 0, outW, outH);
+ applyAdjustment(imgData, baseLayer.adjustmentData, undefined, baseLayer.opacity * opacityMul);
+ dstCtx.putImageData(imgData, 0, 0);
+ } catch {
+ // Ignore in headless/mock contexts without getImageData
+ }
+ continue;
+ }
+
+ const activeClipped = group.clippedNodes.filter(
+ (cn) => cn.layer.visible && cn.layer.opacity > 0.001 && cn.layer.type !== 'folder'
+ );
+
+ if (activeClipped.length === 0) {
+ drawSingleLayer(dstCtx, baseLayer, opacityMul);
+ } else {
+ if (!ViewportCompositor.previewScratchCanvas) {
+ ViewportCompositor.previewScratchCanvas = document.createElement('canvas');
+ }
+ const grpCanvas = ViewportCompositor.previewScratchCanvas;
+ if (grpCanvas.width !== outW) grpCanvas.width = outW;
+ if (grpCanvas.height !== outH) grpCanvas.height = outH;
+ const grpCtx = grpCanvas.getContext('2d');
+ if (!grpCtx) {
+ drawSingleLayer(dstCtx, baseLayer, opacityMul);
+ continue;
+ }
+ grpCtx.clearRect(0, 0, outW, outH);
+ drawSingleLayer(grpCtx, baseLayer, 1.0, 'source-over');
+ for (const cn of activeClipped) {
+ drawSingleLayer(grpCtx, cn.layer, 1.0, 'source-atop');
+ }
+ dstCtx.save();
+ dstCtx.globalAlpha = Math.max(0, Math.min(1, opacityMul));
+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(baseLayer.blendMode);
+ dstCtx.drawImage(grpCanvas, 0, 0);
+ dstCtx.restore();
+ }
+ }
+ };
+
+ const tree = buildLayerTree(layers);
+ renderNodes(ctx, tree, 1.0);
+ ctx.restore();
+ }
+
/**
* Clear all allocated WebGL textures, FBOs, buffers, and programs.
*/
diff --git a/src/utils/tileEngine.ts b/src/utils/tileEngine.ts
index b95d903..89baabb 100644
--- a/src/utils/tileEngine.ts
+++ b/src/utils/tileEngine.ts
@@ -1545,33 +1545,38 @@ export class SparseTileGrid {
}
/**
- * Ensures LOD 3 mipmap tiles exist and are up-to-date for all populated regions of `layerId`.
+ * Ensures mipmap tiles at `targetLod` (0..3) exist and are up-to-date for all populated regions of `layerId`.
*/
- public getOrBuildLod3Tiles(layerId: string): TileBuffer[] {
- const lod3Coords = new Map<string, { tx: number; ty: number }>();
+ public getOrBuildLodTiles(layerId: string, targetLod: number): TileBuffer[] {
+ const lod = Math.max(0, Math.min(3, Math.floor(targetLod)));
+ if (lod === 0) {
+ return this.getLayerTiles(layerId);
+ }
+
+ const lodCoords = new Map<string, { tx: number; ty: number }>();
for (const tile of this.tiles.values()) {
if (tile.layerId !== layerId) continue;
if ((tile.lod ?? 0) === 0) {
- const l3x = tile.tileX >> 3;
- const l3y = tile.tileY >> 3;
- const k = `${l3x}:${l3y}`;
- if (!lod3Coords.has(k)) {
- lod3Coords.set(k, { tx: l3x, ty: l3y });
+ const ltx = tile.tileX >> lod;
+ const lty = tile.tileY >> lod;
+ const k = `${ltx}:${lty}`;
+ if (!lodCoords.has(k)) {
+ lodCoords.set(k, { tx: ltx, ty: lty });
}
- } else if (tile.lod === 3) {
+ } else if (tile.lod === lod) {
const k = `${tile.tileX}:${tile.tileY}`;
- if (!lod3Coords.has(k)) {
- lod3Coords.set(k, { tx: tile.tileX, ty: tile.tileY });
+ if (!lodCoords.has(k)) {
+ lodCoords.set(k, { tx: tile.tileX, ty: tile.tileY });
}
}
}
const result: TileBuffer[] = [];
- for (const { tx, ty } of lod3Coords.values()) {
- let tile = this.getTile(layerId, tx, ty, 3);
- if (!tile || tile.data === null || this.isLodTileDirty(layerId, tx, ty, 3)) {
- tile = this.generateLodTile(layerId, tx, ty, 3);
+ for (const { tx, ty } of lodCoords.values()) {
+ let tile = this.getTile(layerId, tx, ty, lod);
+ if (!tile || tile.data === null || this.isLodTileDirty(layerId, tx, ty, lod)) {
+ tile = this.generateLodTile(layerId, tx, ty, lod);
}
if (tile && tile.data !== null) {
result.push(tile);
@@ -1580,6 +1585,13 @@ export class SparseTileGrid {
return result;
}
+ /**
+ * Ensures LOD 3 mipmap tiles exist and are up-to-date for all populated regions of `layerId`.
+ */
+ public getOrBuildLod3Tiles(layerId: string): TileBuffer[] {
+ return this.getOrBuildLodTiles(layerId, 3);
+ }
+
/**
* Generates a layer thumbnail directly from LOD 3 mipmap tiles (1/8 resolution: 2048px per tile).
* Completely bypasses full-size canvas allocation and full-resolution pixel reads.
diff --git a/src/utils/workspacePresets.ts b/src/utils/workspacePresets.ts
index c9c98fe..5e12ee9 100644
--- a/src/utils/workspacePresets.ts
+++ b/src/utils/workspacePresets.ts
@@ -79,17 +79,23 @@ export const DEFAULT_ILLUSTRATION_LAYOUT: WorkspaceLayout = {
width: 224,
collapsed: false,
groups: [
+ {
+ id: 'grp-navigator-subview',
+ panelIds: ['navigator', 'sub-view'],
+ activePanelId: 'navigator',
+ heightRatio: 0.26,
+ },
{
id: 'grp-color',
panelIds: ['color'],
activePanelId: 'color',
- heightRatio: 0.3,
+ heightRatio: 0.26,
},
{
id: 'grp-layers-history',
panelIds: ['layers', 'history'],
activePanelId: 'layers',
- heightRatio: 0.7,
+ heightRatio: 0.48,
},
],
},
@@ -169,17 +175,23 @@ export const MANGA_STUDIO_LAYOUT: WorkspaceLayout = {
width: 232,
collapsed: false,
groups: [
+ {
+ id: 'grp-manga-nav-subview',
+ panelIds: ['navigator', 'sub-view'],
+ activePanelId: 'navigator',
+ heightRatio: 0.26,
+ },
{
id: 'grp-manga-layers',
panelIds: ['layers'],
activePanelId: 'layers',
- heightRatio: 0.72,
+ heightRatio: 0.5,
},
{
id: 'grp-manga-history',
panelIds: ['history'],
activePanelId: 'history',
- heightRatio: 0.28,
+ heightRatio: 0.24,
},
],
},
@@ -223,7 +235,7 @@ export const MINIMALIST_TABLET_LAYOUT: WorkspaceLayout = {
groups: [
{
id: 'grp-tablet-layers',
- panelIds: ['layers', 'history', 'quick-access'],
+ panelIds: ['navigator', 'sub-view', 'layers', 'history', 'quick-access'],
activePanelId: 'layers',
heightRatio: 1,
},