Skip to content

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

dock, window editor, workspaces etc

sora916db507c422
diff --git a/src/App.tsx b/src/App.tsx
index 47573d9..82ec482 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,744 +1,85 @@
-import { useState, useCallback, useEffect, useRef, useMemo } from 'react';
-import {
- ToolType,
- BrushSettings,
- CanvasDimensions,
- CanvasColorMode,
- MenuSection,
- NewCanvasOptions,
- DocumentTab,
- LayerItem,
- CanvasSelection,
- TransformSession,
- FillSettings,
- TextSettings,
- FrameSettings,
- ExpressionColor,
- LiquifySettings,
- WandSettings,
- AdjustmentLayerData,
- FilterType,
- BalloonSettings,
- VectorEditSettings,
- SpeechBalloon,
- AnimationTimeline,
- CmykStandard,
- SoftProofSettings,
- DEFAULT_SOFT_PROOF_SETTINGS,
-} from './types/editor';
+import React, { useCallback, useEffect, useMemo, useRef } from 'react';
+import { AnimationTimeline, LayerItem } from './types/editor';
import {
createDefaultAnimationTimeline,
- setFrameCel,
removeFrameCel,
+ setFrameCel,
} from './utils/animationEngine';
-import { applyLiquifyStep, createLiquifySelectionMask, DirtyRect } from './utils/liquifyEngine';
-import { PerspectiveRuler, ConstraintAxis } from './types/perspective';
-import { createDefaultPerspectiveRuler, applyWormsEyePreset } from './utils/perspectiveMath';
-import { executeFloodFill, compositeVisibleLayers, compositeReferenceLayers, executeLassoFill } from './utils/floodFill';
-import {
- isPointInSelection,
- liftSelectionToFloating,
- commitFloatingSelection,
- computePolygonBounds,
- getCanvasContentBounds,
- floodSelectWand,
- expandSelection,
- contractSelection,
- featherSelection,
- invertSelection,
- selectionToMask,
- maskToBounds,
- maskToSvgPath,
-} from './utils/selectionUtils';
-import {
- renderPerspectiveQuad,
- renderMeshWarp,
- createDefaultPerspectiveQuad,
- createDefaultMeshPoints,
-} from './utils/transformEngine';
-import { applyScreentone } from './utils/screentoneEngine';
-import { applyLayerEffects } from './utils/layerEffectsEngine';
-import { useCanvasDrawing } from './hooks/useCanvasDrawing';
-import { useCanvasNavigation } from './hooks/useCanvasNavigation';
-import { useLayerManager } from './hooks/useLayerManager';
-import { enforceColorMode } from './utils/colorUtils';
-import { openFile } from './utils/imageLoader';
-import {
- promptSaveAs,
- saveToExistingHandle,
- promptExportPngImage,
- compositeCanvas,
- SaveDocumentData,
- SavedFileInfo,
-} from './utils/saveManager';
-import { Header } from './components/Header';
-import { LeftPanel } from './components/LeftPanel';
-import { CanvasArea } from './components/CanvasArea';
-import { RightSidebar } from './components/RightSidebar';
-import { NewCanvasModal } from './components/NewCanvasModal';
-import { ResizeCanvasModal } from './components/ResizeCanvasModal';
-import { SettingsModal } from './components/SettingsModal';
-import { useMultiplayer } from './hooks/useMultiplayer';
-import { multiplayerService } from './services/multiplayerService';
-import { HostModal } from './components/HostModal';
-import { ClipboardInviteToast } from './components/ClipboardInviteToast';
-import { WebLandingModal } from './components/WebLandingModal';
-import { WelcomeScreen } from './components/WelcomeScreen';
-import { AdjustmentModal } from './components/AdjustmentModal';
-import { LayerStylesModal } from './components/LayerStylesModal';
-import { recoveryService, CrashedSessionInfo } from './services/recoveryService';
-import { CrashRecoveryModal } from './components/CrashRecoveryModal';
-import { applyFilter } from './utils/filterEngine';
-import { saveRecentDocument, RecentDocument } from './utils/recentDocumentsManager';
-import {
- renderCompleteStroke,
- drawDot,
- drawSmoothBezierSegment,
- getMidPoint,
- get2DContext,
- getReusableBakeCanvas,
- screenToCanvas,
- sampleCompositedColor,
-} from './utils/canvasUtils';
+import { screenToCanvas } from './utils/canvasUtils';
import { globalTileGrid } from './utils/tileEngine';
import { documentStore } from './utils/documentStore';
-import { getNextCollabLayerName } from './hooks/useLayerManager';
-import { drawPencilDot, drawPencilBezierSegment, PencilGrade } from './utils/pencilEngine';
-import { Point } from './types/editor';
-import {
- StrokeStartMessage,
- StrokeChunkMessage,
- StrokeFinishMessage,
- MultiplayerMessage,
-} from './types/multiplayer';
-import {
- renderVectorStroke,
- renderVectorLayer,
- pinchVectorStroke,
- modifyStrokeWidth,
- simplifyVectorStroke,
-} from './utils/vectorEngine';
-import { renderMangaTextToCanvas } from './utils/mangaTextEngine';
-import { createDefaultSpeechBalloon, renderSpeechBalloon } from './utils/balloonEngine';
-import {
- renderSaturatedLines,
- renderStreamLines,
- SaturatedLinesOptions,
- StreamLinesOptions,
-} from './utils/mangaEffectsEngine';
-import { MangaEffectsModal } from './components/MangaEffectsModal';
-import { WebtoonExportModal } from './components/WebtoonExportModal';
-
-import {
- AppSettings,
- loadAppSettings,
- saveAppSettings,
- ResizeCanvasOptions,
- resolveModernAccentColor,
- getAccentContrastColor,
- hexToRgb,
-} from './types/settings';
-import {
- FilePlus,
- FolderOpen,
- Save,
- Download,
- Trash2,
- Film,
- Layers,
- Undo2,
- Redo2,
- ZoomIn,
- ZoomOut,
- RotateCcw,
- FlipHorizontal,
- FlipVertical,
- Plus,
- Loader2,
- Info as InfoIcon,
- CheckCircle2,
- Copy,
- ClipboardPaste,
- ImagePlus,
- Scaling,
- Settings,
- FolderDown,
- PaintBucket,
- SlidersHorizontal,
- Compass,
- Eye,
- EyeOff,
- Magnet,
- Lock,
- Unlock,
- Box,
- Maximize2,
- Minimize2,
- Feather,
- BoxSelect,
- X,
- Smartphone,
- Archive,
- Sparkles,
- MessageSquare,
- Spline,
-} from 'lucide-react';
-import { parseSutFile } from './utils/sutParser';
+import { multiplayerService } from './services/multiplayerService';
+import { useCanvasDrawing } from './hooks/useCanvasDrawing';
import {
- saveCustomBrush,
- prepareBrushSettingsForCsp,
- deleteCustomBrush,
- loadCustomBrushes,
-} from './utils/brushStorage';
+ PushHistoryStepFn,
+ useSelectionTools,
+ useShapeAndFillTools,
+ useVectorDrawing,
+} from './hooks/drawing';
+import { useCanvasNavigation } from './hooks/useCanvasNavigation';
+import { useLayerManager } from './hooks/useLayerManager';
+import { useCollabSync } from './hooks/useCollabSync';
+import { useTonalAndFilterActions } from './hooks/useTonalAndFilterActions';
+import { useAppMenuSections } from './hooks/useAppMenuSections';
import {
- saveBrushSettingsDebounced,
- flushPendingBrushSettingsSave,
- stepBrushSizePreset,
- getEffectiveBrushSettings,
- getActivePresetId,
- saveActivePresetId,
- ERASER_PRESET_ID,
- DEFAULT_BRUSH_PRESET_ID,
-} from './utils/brushPresetManager';
-import { TonalCorrectionModal } from './components/TonalCorrectionModal';
-import { SimpleToneModal, SimpleToneSettings } from './components/SimpleToneModal';
+ documentStoreActions,
+ selectHasOpenDocument,
+ uiStoreActions,
+ useDocumentStore,
+ useToolStore,
+ useUiStore,
+} from './stores';
import {
- TonalCorrectionType,
- applyTonalFilter,
- applyReverseGradient,
- createSelectionMask,
- getProcessingBounds,
- ProcessingBounds,
-} from './utils/tonalEngine';
-
-const INITIAL_DIMENSIONS: CanvasDimensions = {
- width: 1440,
- height: 900,
- dpi: 300,
-};
+ DocumentLifecycleManager,
+ useDocumentLifecycle,
+} from './components/DocumentLifecycleManager';
+import { GlobalShortcutListener } from './components/GlobalShortcutListener';
+import { ModalHost } from './components/ModalHost';
+import { AppShell } from './components/AppShell';
export function App() {
- const [tool, setTool] = useState<ToolType>('brush');
- const toolRef = useRef<ToolType>(tool);
- useEffect(() => {
- toolRef.current = tool;
- }, [tool]);
-
- const previousToolBeforeAltRef = useRef<ToolType | null>(null);
- const isAltActiveRef = useRef<boolean>(false);
- const isPipetteSamplingRef = useRef<boolean>(false);
-
- // Selection state
- const [selection, setSelection] = useState<CanvasSelection | null>(null);
-
- // Free Transform session state
- const [transformSession, setTransformSession] = useState<TransformSession | null>(null);
-
- // Magic Wand tool settings
- const [wandSettings, setWandSettings] = useState<WandSettings>({
- tolerance: 32,
- contiguous: true,
- antiAlias: true,
- referMode: 'active',
- });
- const selectionMaskCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const selectionPenDrawingRef = useRef<{
- isDrawing: boolean;
- lastPt: { x: number; y: number };
- maskCanvas: HTMLCanvasElement;
- ctx: CanvasRenderingContext2D;
- } | null>(null);
-
- // Fill tool settings
- const [fillSettings, setFillSettings] = useState<FillSettings>({
- method: 'refer-all',
- tolerance: 32,
- });
-
- // Text tool settings & active text placement session
- const [textSettings, setTextSettings] = useState<TextSettings>({
- text: '',
- fontFamily: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",
- fontSize: 28,
- bold: false,
- italic: false,
- align: 'center',
- outline: true,
- outlineColor: '#ffffff',
- outlineWidth: 3,
- color: '#000000',
- });
- const [textSession, setTextSession] = useState<{ x: number; y: number; settings: TextSettings } | null>(null);
- const [is3DLayerOpen, setIs3DLayerOpen] = useState<boolean>(false);
-
- // Frame Border tool settings
- const [frameSettings, setFrameSettings] = useState<FrameSettings>({
- thickness: 4,
- fillBackground: true,
- fillColor: '#ffffff',
- });
-
- // Speech Balloon tool settings & active placement session
- const [balloonSettings, setBalloonSettings] = useState<BalloonSettings>({
- shape: 'ellipse',
- fillColor: '#ffffff',
- strokeColor: '#000000',
- strokeWidth: 3,
- text: '',
- fontFamily: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",
- fontSize: 22,
- vertical: false,
- });
- const [activeBalloon, setActiveBalloon] = useState<SpeechBalloon | null>(null);
-
- // Vector "Correct Line" tool settings
- const [vectorEditSettings, setVectorEditSettings] = useState<VectorEditSettings>({
- mode: 'pinch',
- radius: 35,
- pinchStrength: 1.0,
- widthFactor: 1.5,
- simplifyTolerance: 2.0,
- });
-
- // Webtoon Studio Mode state
- const [isWebtoonMode, setIsWebtoonMode] = useState<boolean>(false);
- const [isWebtoonExportModalOpen, setIsWebtoonExportModalOpen] = useState<boolean>(false);
-
- // Manga Effect Lines Modal state
- const [isMangaEffectsModalOpen, setIsMangaEffectsModalOpen] = useState<boolean>(false);
-
- // Liquify tool settings
- const [liquifySettings, setLiquifySettings] = useState<LiquifySettings>(() => {
- try {
- const saved = localStorage.getItem('sora_paint_liquify_settings');
- if (saved) return JSON.parse(saved);
- } catch {}
- return {
- mode: 'push',
- size: 80,
- strength: 50,
- hardness: 50,
- usePressure: true,
- };
- });
- const liquifySettingsRef = useRef<LiquifySettings>(liquifySettings);
- useEffect(() => {
- liquifySettingsRef.current = liquifySettings;
- }, [liquifySettings]);
-
- const handleUpdateLiquifySettings = useCallback((newSettings: Partial<LiquifySettings>) => {
- setLiquifySettings((prev) => {
- const next = { ...prev, ...newSettings };
- try {
- localStorage.setItem('sora_paint_liquify_settings', JSON.stringify(next));
- } catch {}
- return next;
- });
- }, []);
-
- const isLiquifyingRef = useRef<boolean>(false);
- const prevLiquifyPointRef = useRef<{ x: number; y: number } | null>(null);
- const liquifyBeforeImageDataRef = useRef<ImageData | null>(null);
- const liquifyInitialImageDataRef = useRef<ImageData | null>(null);
-
- const isVectorEditingRef = useRef<boolean>(false);
- const lastVectorEditPtRef = useRef<{ x: number; y: number } | null>(null);
- const vectorEditBeforeStrokesRef = useRef<any[] | null>(null);
- const liquifyDirtyRectRef = useRef<DirtyRect | null>(null);
- const liquifyRafIdRef = useRef<number | null>(null);
- const liquifyLastPointerPosRef = useRef<{ pt: { x: number; y: number }; pressure: number } | null>(null);
- const liquifySelectionMaskRef = useRef<Uint8Array | null>(null);
-
- // Tool interaction tracking refs
- const selectionDragRef = useRef<{
- isDragging: boolean;
- startX: number;
- startY: number;
- origFloatingX: number;
- origFloatingY: number;
- origBoundsX: number;
- origBoundsY: number;
- } | null>(null);
- const selectRectStartRef = useRef<{ x: number; y: number } | null>(null);
- const lassoPointsRef = useRef<Array<{ x: number; y: number }>>([]);
- const lassoFillPointsRef = useRef<Array<{ x: number; y: number }>>([]);
- const frameStartRef = useRef<{ x: number; y: number } | null>(null);
- const [dimensions, setDimensions] = useState<CanvasDimensions>(INITIAL_DIMENSIONS);
- const [colorMode, setColorMode] = useState<CanvasColorMode>('color');
- const [documentName, setDocumentName] = useState<string>('');
-
- // CMYK Soft Proofing & Gamut Warning
- const [softProofSettings, setSoftProofSettings] = useState<SoftProofSettings>(DEFAULT_SOFT_PROOF_SETTINGS);
-
- const toggleSoftProof = useCallback(() => {
- setSoftProofSettings((prev) => ({
- ...prev,
- enabled: !prev.enabled,
- }));
- }, []);
-
- const toggleGamutWarning = useCallback(() => {
- setSoftProofSettings((prev) => ({
- ...prev,
- gamutWarning: !prev.gamutWarning,
- }));
- }, []);
-
- const setProofStandard = useCallback((standard: CmykStandard) => {
- setSoftProofSettings((prev) => ({
- ...prev,
- standard,
- }));
- }, []);
-
- // Multi-document tab management (starts empty by default)
- const [documents, setDocuments] = useState<DocumentTab[]>([]);
- const [activeDocumentId, setActiveDocumentId] = useState<string | null>(null);
- const hasOpenDocument = Boolean(activeDocumentId && documents.some((d) => d.id === activeDocumentId));
- const [appView, setAppView] = useState<'home' | 'workspace'>('workspace');
-
- // Panels width & visibility (compact defaults dedicating >80% viewport to canvas)
- const [leftPanelWidth, setLeftPanelWidth] = useState<number>(() => {
- const s = localStorage.getItem('ink_left_panel_width_v3');
- return s ? Number(s) : 118;
- });
- const [isLeftPanelHidden, setIsLeftPanelHidden] = useState<boolean>(false);
- const [isRightSidebarHidden, setIsRightSidebarHidden] = useState<boolean>(false);
- const [rightSidebarWidth, setRightSidebarWidth] = useState<number>(() => {
- const s = localStorage.getItem('ink_right_sidebar_width_v3');
- return s ? Number(s) : 162;
- });
-
- const handleLeftPanelWidthChange = useCallback((w: number) => {
- setLeftPanelWidth(w);
- localStorage.setItem('ink_left_panel_width_v3', String(w));
- }, []);
-
- const handleRightSidebarWidthChange = useCallback((w: number) => {
- setRightSidebarWidth(w);
- localStorage.setItem('ink_right_sidebar_width_v3', String(w));
- }, []);
+ const dimensions = useDocumentStore((s) => s.dimensions);
+ const colorMode = useDocumentStore((s) => s.colorMode);
+ const documents = useDocumentStore((s) => s.documents);
+ const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
+ const hasOpenDocument = useDocumentStore(selectHasOpenDocument);
+ const softProofSettings = useDocumentStore((s) => s.softProofSettings);
+ const perspectiveRuler = useDocumentStore((s) => s.perspectiveRuler);
+ const activeEditTarget = useDocumentStore((s) => s.activeEditTarget);
+ const animationTimeline = useDocumentStore((s) => s.animationTimeline);
+ const isWebtoonMode = useUiStore((s) => s.isWebtoonMode);
const draftCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const strokeCanvasRef = draftCanvasRef; // Backwards-compatible alias
-
- const [savedFileInfo, setSavedFileInfo] = useState<SavedFileInfo | null>(null);
- const [toastMessage, setToastMessage] = useState<string | null>(null);
- const toastTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
-
- const [appSettings, setAppSettings] = useState<AppSettings>(loadAppSettings);
-
- useEffect(() => {
- const accent = appSettings.modernAccent || 'neutral';
- const hex = resolveModernAccentColor(accent, appSettings.modernCustomColor);
- const rgb = hexToRgb(hex) || { r: 229, g: 229, b: 229 };
- const contrast = getAccentContrastColor(hex);
-
- const root = document.documentElement;
- root.setAttribute('data-theme', 'modern');
- root.setAttribute('data-accent', accent);
- root.style.setProperty('--accent', hex);
- root.style.setProperty('--accent-rgb', `${rgb.r}, ${rgb.g}, ${rgb.b}`);
- root.style.setProperty('--accent-contrast', contrast);
- root.style.setProperty('--accent-subtle', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.14)`);
- root.style.setProperty('--accent-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.32)`);
- root.style.setProperty('--modern-accent', hex);
- root.style.setProperty('--modern-accent-rgb', `${rgb.r}, ${rgb.g}, ${rgb.b}`);
- root.style.setProperty('--modern-accent-subtle', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.14)`);
- root.style.setProperty('--modern-accent-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.32)`);
- root.style.setProperty('--modern-accent-hover', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`);
- }, [appSettings.modernAccent, appSettings.modernCustomColor]);
-
- const [isNewCanvasModalOpen, setIsNewCanvasModalOpen] = useState<boolean>(false);
- const [isResizeCanvasModalOpen, setIsResizeCanvasModalOpen] = useState<boolean>(false);
- const [isSettingsModalOpen, setIsSettingsModalOpen] = useState<boolean>(false);
- const [isToneModalOpen, setIsToneModalOpen] = useState<boolean>(false);
- const [tonalModalState, setTonalModalState] = useState<{
- isOpen: boolean;
- type: TonalCorrectionType;
- targetLayerId: string;
- beforeImageData: ImageData | null;
- selectionMask: Uint8Array | null;
- bounds: ProcessingBounds;
- }>({
- isOpen: false,
- type: 'brightness-contrast',
- targetLayerId: '',
- beforeImageData: null,
- selectionMask: null,
- bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
- });
- const tonalModalStateRef = useRef(tonalModalState);
- useEffect(() => {
- tonalModalStateRef.current = tonalModalState;
- }, [tonalModalState]);
- const [isLoadingFile, setIsLoadingFile] = useState<boolean>(false);
- const [loadingStatus, setLoadingStatus] = useState<string>('');
-
- // Fault-Tolerant Crash Recovery (WAL Architecture) State
- const [crashedSessions, setCrashedSessions] = useState<CrashedSessionInfo[]>([]);
- const [isRecoveryModalOpen, setIsRecoveryModalOpen] = useState<boolean>(false);
-
- // Crash Recovery: detect unfinalized crashed sessions on startup
- useEffect(() => {
- recoveryService
- .checkForCrashedSessions()
- .then((sessions) => {
- if (sessions && sessions.length > 0) {
- setCrashedSessions(sessions);
- setIsRecoveryModalOpen(true);
- }
- })
- .catch((err) => {
- console.warn('[Recovery] Error scanning for crashed sessions:', err);
- });
- }, []);
-
-
- const fileInputRef = useRef<HTMLInputElement>(null);
- const pasteFileInputRef = useRef<HTMLInputElement>(null);
- const import3DFileInputRef = useRef<HTMLInputElement>(null);
- const [initial3DFile, setInitial3DFile] = useState<File | null>(null);
-
- const [perspectiveRuler, setPerspectiveRuler] = useState<PerspectiveRuler | null>(null);
- const [activeLockedAxis, setActiveLockedAxis] = useState<ConstraintAxis | null>(null);
-
- const handleActiveConstraintAxisChange = useCallback((newAxis: ConstraintAxis | null) => {
- setActiveLockedAxis((prev) => {
- if (prev === newAxis) return prev;
- if (
- prev &&
- newAxis &&
- prev.type === newAxis.type &&
- prev.origin.x === newAxis.origin.x &&
- prev.origin.y === newAxis.origin.y &&
- prev.dir.x === newAxis.dir.x &&
- prev.dir.y === newAxis.dir.y
- ) {
- return prev;
- }
- return newAxis;
- });
- }, []);
-
- const updatePerspectiveRuler = useCallback(
- (
- updater:
- | PerspectiveRuler
- | null
- | ((prev: PerspectiveRuler | null) => PerspectiveRuler | null)
- ) => {
- setPerspectiveRuler((prev) => {
- const next = typeof updater === 'function' ? updater(prev) : updater;
- if (activeDocumentId) {
- setDocuments((docs) =>
- docs.map((d) => (d.id === activeDocumentId ? { ...d, perspectiveRuler: next } : d))
- );
- }
- return next;
- });
- },
- [activeDocumentId]
- );
-
- const showToast = useCallback((msg: string) => {
- if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current);
- setToastMessage(msg);
- toastTimeoutRef.current = setTimeout(() => setToastMessage(null), 3200);
- }, []);
-
- const [primaryColor, setPrimaryColor] = useState<string>('#000000');
- const [secondaryColor, setSecondaryColor] = useState<string>('#ffffff');
- const [recentColors, setRecentColors] = useState<string[]>([
- '#000000',
- '#3b82f6',
- '#ef4444',
- '#10b981',
- '#f59e0b',
- '#ffffff',
- ]);
-
- const [brushSettings, setBrushSettings] = useState<BrushSettings>(() => {
- const activePreset = getActivePresetId();
- const effective = getEffectiveBrushSettings(activePreset);
- return {
- preset: activePreset,
- size: effective.size ?? 3.5,
- minSizeFactor: effective.minSizeFactor ?? 0.25,
- color: '#000000',
- secondaryColor: '#ffffff',
- opacity: effective.opacity ?? 1.0,
- flow: effective.flow ?? 0.74,
- spacing: effective.spacing ?? 0.08,
- grain: effective.grain ?? 0.95,
- usePressure: effective.usePressure ?? true,
- smoothing: effective.smoothing ?? true,
- stabilization: effective.stabilization ?? 15,
- hardness: effective.hardness ?? 0.8,
- ...effective,
- } as BrushSettings;
- });
+ const strokeCanvasRef = draftCanvasRef;
+ const selectiveUndoRef = useRef<(peerId?: string | number) => void>(() => {});
+ const pushHistoryStepRef = useRef<PushHistoryStepFn | null>(null);
+ const getActiveCanvasRef = useRef<() => HTMLCanvasElement | null>(() => null);
+ const showToast = uiStoreActions.showToast;
- // Active document's isolated SparseTileGrid (instant O(1) switch across tabs)
const activeTileGrid = useMemo(
- () => (activeDocumentId ? documentStore.getOrCreateSession(activeDocumentId).tileGrid : globalTileGrid),
+ () =>
+ activeDocumentId
+ ? documentStore.getOrCreateSession(activeDocumentId).tileGrid
+ : globalTileGrid,
[activeDocumentId]
);
// Layer Management System
- const {
- layers,
- setLayers,
- activeLayerId,
- setActiveLayerId,
- selectedLayerIds,
- toggleLayerSelection,
- deleteSelectedLayers,
- groupSelectedLayers,
- activeLayer,
- layerCanvasesRef,
- materializeLayerCanvas,
- releaseLayerCanvas,
- registerLayerCanvas,
- updateLayerThumbnail,
- addLayer,
- addRemoteLayer,
- deleteRemoteLayer,
- syncRemoteDocument,
- duplicateLayer,
- deleteLayer,
- copyLayer,
- pasteLayer,
- pasteLayerFromCanvas,
- pasteLayerFromFile,
- resizeCanvas,
- toggleVisibility,
- setOpacity,
- setBlendMode,
- toggleLock,
- toggleCollapse,
- renameLayer,
- moveLayer,
- moveLayerToFolder,
- reorderLayers,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- clearActiveLayer,
- resetToNewCanvas,
- setDefaultToneFrequency,
- clearDocument,
- loadDocument,
- switchDocumentSession,
- layerSourceCanvasesRef,
- toggleTone,
- setToneFrequency,
- setToneAngle,
- setToneDotShape,
- setToneDensity,
- setToneDensityType,
- toggleLayerColor,
- setLayerColor,
- setLayerSubColor,
- setLayerExpressionColor,
- setLayerMonoThreshold,
- setLayerMonoExpressMode,
- applyExpressionColorOfPreview,
- applyLayerColorPermanently,
- toggleClipping,
- toggleAlphaLock,
- convertLayer,
- fillScreentoneSelection,
- addLayerMask,
- removeLayerMask,
- toggleLayerMask,
- toggleMaskLinked,
- updateMaskThumbnail,
- addAdjustmentLayer,
- updateAdjustmentData,
- updateLayerStyles,
- } = useLayerManager({ dimensions, activeSessionId: activeDocumentId, tileGrid: activeTileGrid });
-
- // Synchronize active document recovery session and WAL periodic checkpointing
- const recoveryStateRef = useRef({
- documents,
- documentName,
+ const layerMgr = useLayerManager({
dimensions,
- colorMode,
- layers,
- activeLayerId,
+ activeSessionId: activeDocumentId,
+ tileGrid: activeTileGrid,
});
- recoveryStateRef.current = {
- documents,
- documentName,
- dimensions,
- colorMode,
- layers,
- activeLayerId,
- };
-
- useEffect(() => {
- if (!activeDocumentId) return;
- const st = recoveryStateRef.current;
- const initDoc = st.documents.find((d) => d.id === activeDocumentId);
- if (!initDoc) return;
-
- recoveryService.initSession(
- activeDocumentId,
- () => {
- const cur = recoveryStateRef.current;
- const doc = cur.documents.find((d) => d.id === activeDocumentId);
- return {
- sessionId: activeDocumentId,
- documentName: doc?.name || cur.documentName || 'Untitled Document',
- width: doc?.dimensions.width || cur.dimensions.width,
- height: doc?.dimensions.height || cur.dimensions.height,
- dpi: doc?.dimensions.dpi || cur.dimensions.dpi || 600,
- colorMode: doc?.colorMode || cur.colorMode || 'color',
- layers: doc?.layers || cur.layers,
- activeLayerId: doc?.activeLayerId || cur.activeLayerId,
- timestamp: Date.now(),
- };
- },
- async () => {
- const cur = recoveryStateRef.current;
- const doc = cur.documents.find((d) => d.id === activeDocumentId);
- const targetLayerId = doc?.activeLayerId || cur.activeLayerId;
- const dims = doc?.dimensions || cur.dimensions;
- if (!targetLayerId || dims.width <= 0 || dims.height <= 0) return null;
- try {
- const thumbW = 120;
- const thumbH = Math.max(68, Math.round((dims.height / Math.max(1, dims.width)) * thumbW));
- const dataUrl = documentStore.getActiveTileGrid().generateThumbnail(targetLayerId, thumbW, thumbH, dims);
- const commaIdx = dataUrl.indexOf(',');
- if (commaIdx < 0) return null;
- const b64 = dataUrl.slice(commaIdx + 1);
- const binStr = atob(b64);
- const bytes = new Uint8Array(binStr.length);
- for (let i = 0; i < binStr.length; i++) {
- bytes[i] = binStr.charCodeAt(i);
- }
- return bytes;
- } catch {
- return null;
- }
- }
- );
- }, [activeDocumentId, layerCanvasesRef]);
-
- // Active edit target for painting/erasing ('layer' content vs 'mask')
- const [activeEditTarget, setActiveEditTarget] = useState<'layer' | 'mask'>('layer');
-
- // 2D Frame-by-Frame Animation Timeline State
- const [animationTimeline, setAnimationTimeline] = useState<AnimationTimeline | null>(null);
const activeDoc = documents.find((d) => d.id === activeDocumentId);
- const activeAnimationTimeline = activeDoc?.animation !== undefined ? activeDoc.animation : animationTimeline;
+ const activeAnimationTimeline =
+ activeDoc?.animation !== undefined ? activeDoc.animation : animationTimeline;
const handleUpdateAnimationTimeline = useCallback(
(timeline: AnimationTimeline | null) => {
- setAnimationTimeline(timeline);
+ documentStoreActions.setAnimationTimeline(timeline);
if (activeDocumentId) {
- setDocuments((docs) =>
+ documentStoreActions.setDocuments((docs) =>
docs.map((d) => (d.id === activeDocumentId ? { ...d, animation: timeline } : d))
);
}
@@ -760,6393 +101,743 @@ export function App() {
collapsed: false,
parentId: null,
};
-
const canvas = document.createElement('canvas');
canvas.width = dimensions.width;
canvas.height = dimensions.height;
- registerLayerCanvas(newLayerId, canvas);
+ layerMgr.registerLayerCanvas(newLayerId, canvas);
- setLayers((prev) => [newCelLayer, ...prev]);
- setActiveLayerId(newLayerId);
+ layerMgr.setLayers((prev) => [newCelLayer, ...prev]);
+ layerMgr.setActiveLayerId(newLayerId);
- const currentTl = activeAnimationTimeline || createDefaultAnimationTimeline(layers);
- const updatedTl = setFrameCel(currentTl, frameIndex, newLayerId);
- handleUpdateAnimationTimeline(updatedTl);
+ const currentTl = activeAnimationTimeline || createDefaultAnimationTimeline(layerMgr.layers);
+ handleUpdateAnimationTimeline(setFrameCel(currentTl, frameIndex, newLayerId));
showToast(`Cel added for frame ${frameIndex + 1}`);
},
- [activeAnimationTimeline, dimensions, handleUpdateAnimationTimeline, layers, registerLayerCanvas, setActiveLayerId, setLayers, showToast]
+ [activeAnimationTimeline, dimensions, handleUpdateAnimationTimeline, layerMgr, showToast]
);
const handleDeleteAnimationCel = useCallback(
(frameIndex: number) => {
if (!activeAnimationTimeline) return;
- const updatedTl = removeFrameCel(activeAnimationTimeline, frameIndex);
- handleUpdateAnimationTimeline(updatedTl);
+ handleUpdateAnimationTimeline(removeFrameCel(activeAnimationTimeline, frameIndex));
showToast(`Cel removed from frame ${frameIndex + 1}`);
},
[activeAnimationTimeline, handleUpdateAnimationTimeline, showToast]
);
- // Adjustment Layer Modal state
- const [adjustmentModalState, setAdjustmentModalState] = useState<{
- isOpen: boolean;
- layerId?: string | null;
- initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance';
- }>({
- isOpen: false,
+ // Canvas Navigation
+ const nav = useCanvasNavigation({
+ dimensions,
+ isWebtoonMode,
+ activeDocumentId,
});
- const handleOpenAdjustmentModal = useCallback(
- (layerId?: string, initialType: 'curves' | 'gradient-map' | 'levels' | 'color-balance' = 'curves') => {
- setAdjustmentModalState({
- isOpen: true,
- layerId: layerId || null,
- initialType,
- });
- },
- []
- );
+ // Multiplayer & Collaborative Layer Sync
+ const collab = useCollabSync({
+ hasOpenDocument,
+ dimensions,
+ colorMode,
+ layers: layerMgr.layers,
+ activeLayerId: layerMgr.activeLayerId,
+ selectedLayerIds: layerMgr.selectedLayerIds,
+ layerCanvasesRef: layerMgr.layerCanvasesRef,
+ selectiveUndoRef,
+ setActiveLayerId: layerMgr.setActiveLayerId,
+ addLayer: layerMgr.addLayer,
+ addRemoteLayer: layerMgr.addRemoteLayer,
+ deleteLayer: layerMgr.deleteLayer,
+ deleteRemoteLayer: layerMgr.deleteRemoteLayer,
+ deleteSelectedLayers: layerMgr.deleteSelectedLayers,
+ groupSelectedLayers: layerMgr.groupSelectedLayers,
+ syncRemoteDocument: layerMgr.syncRemoteDocument,
+ renameLayer: layerMgr.renameLayer,
+ toggleVisibility: layerMgr.toggleVisibility,
+ setOpacity: layerMgr.setOpacity,
+ clearActiveLayer: layerMgr.clearActiveLayer,
+ updateLayerThumbnail: layerMgr.updateLayerThumbnail,
+ showToast,
+ });
- const handleApplyAdjustment = useCallback(
- (type: 'curves' | 'gradient-map' | 'levels' | 'color-balance', data: AdjustmentLayerData) => {
- if (adjustmentModalState.layerId) {
- updateAdjustmentData(adjustmentModalState.layerId, data);
- showToast(`Updated ${data.type} adjustment layer`);
- } else {
- addAdjustmentLayer(type, data);
- showToast(`Created new ${data.type} adjustment layer`);
- }
- setAdjustmentModalState({ isOpen: false });
+ const stableGetActiveCanvas = useCallback(() => getActiveCanvasRef.current(), []);
+ const stablePushHistoryStep = useCallback<PushHistoryStepFn>(
+ (...args) => {
+ pushHistoryStepRef.current?.(...args);
},
- [adjustmentModalState.layerId, updateAdjustmentData, addAdjustmentLayer, showToast]
+ []
);
- // Non-Destructive GPU Layer Styles Modal State (Stroke, Drop Shadow, Outer Glow)
- const [layerStylesModalState, setLayerStylesModalState] = useState<{
- isOpen: boolean;
- layerId?: string | null;
- }>({
- isOpen: false,
+ // Modular Selection & Transform Tools (mounted before useCanvasDrawing so selection is always synchronous)
+ const selectionTools = useSelectionTools({
+ dimensions,
+ colorMode,
+ layers: layerMgr.layers,
+ activeLayer: layerMgr.activeLayer,
+ activeLayerId: layerMgr.activeLayerId,
+ selectedLayerIds: layerMgr.selectedLayerIds,
+ layerCanvasesRef: layerMgr.layerCanvasesRef,
+ layerSourceCanvasesRef: layerMgr.layerSourceCanvasesRef,
+ getActiveCanvas: stableGetActiveCanvas,
+ updateLayerThumbnail: layerMgr.updateLayerThumbnail,
+ pushHistoryStep: stablePushHistoryStep,
+ showToast,
});
- const handleOpenLayerStylesModal = useCallback(
- (layerId?: string) => {
- const targetId = layerId || activeLayerId;
- if (targetId) {
- setLayerStylesModalState({
- isOpen: true,
- layerId: targetId,
- });
+ const handleCollabStrokeStart = useCallback(
+ (
+ strokeId: string,
+ layerId: string,
+ bs: import('./types/editor').BrushSettings,
+ t: import('./types/editor').ToolType,
+ startPt: import('./types/editor').Point
+ ) => {
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendStrokeStart(strokeId, layerId, bs, t, startPt);
}
},
- [activeLayerId]
+ []
);
- const handleApplyLayerStyles = useCallback(
- (styles: any) => {
- if (layerStylesModalState.layerId) {
- updateLayerStyles(layerStylesModalState.layerId, styles);
- showToast('Updated Layer Styles');
+ const handleCollabStrokeChunk = useCallback(
+ (strokeId: string, pts: import('./types/editor').Point[]) => {
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendStrokeChunk(strokeId, pts);
}
- setLayerStylesModalState({ isOpen: false });
},
- [layerStylesModalState.layerId, updateLayerStyles, showToast]
+ []
);
- const pushHistoryStepRef = useRef<any>(null);
-
- const handleApplyFilter = useCallback(
- (type: FilterType, params?: any) => {
- if (!hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked) {
- showToast('Select an unlocked raster layer to apply filter');
- return;
+ const handleCollabStrokeFinish = useCallback(
+ (
+ strokeId: string,
+ layerId: string,
+ endPt: import('./types/editor').Point,
+ dirty?: import('./types/editor').DirtyRect,
+ vectorStroke?: import('./types/editor').VectorStroke
+ ) => {
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendStrokeFinish(strokeId, layerId, endPt, dirty, vectorStroke);
}
- const grid = documentStore.getActiveTileGrid();
- const isTone = Boolean(activeLayer.toneEnabled && layerSourceCanvasesRef.current?.get(activeLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- const displayCanvas = layerCanvasesRef.current.get(activeLayerId);
-
- const width = dimensions.width;
- const height = dimensions.height;
- if (width <= 0 || height <= 0) return;
+ },
+ []
+ );
- let beforeImageData: ImageData;
- if (isTone && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (!sCtx) return;
- beforeImageData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- const raw = grid.readImageData(activeLayerId, 0, 0, width, height);
- beforeImageData = new ImageData(new Uint8ClampedArray(raw.data), width, height);
+ const handleCollabCursorMove = useCallback(
+ (x: number, y: number, isDrawing: boolean, t: import('./types/editor').ToolType) => {
+ if (multiplayerService.isConnected()) {
+ multiplayerService.sendCursor(x, y, isDrawing, t);
}
+ },
+ []
+ );
- const rawFiltered = applyFilter(
- new ImageData(new Uint8ClampedArray(beforeImageData.data), beforeImageData.width, beforeImageData.height),
- type,
- params
- );
-
- let finalImageData = rawFiltered;
- if (selection) {
- const selMask = createSelectionMask(selection, width, height);
- if (selMask) {
- finalImageData = new ImageData(new Uint8ClampedArray(beforeImageData.data), width, height);
- const src = beforeImageData.data;
- const flt = rawFiltered.data;
- const dst = finalImageData.data;
- for (let i = 0; i < selMask.length; i++) {
- const m = selMask[i];
- if (m === 0) continue;
- const p = i * 4;
- if (m === 255) {
- dst[p] = flt[p];
- dst[p + 1] = flt[p + 1];
- dst[p + 2] = flt[p + 2];
- dst[p + 3] = flt[p + 3];
- } else {
- const a = m / 255;
- const inv = 1 - a;
- dst[p] = Math.round(src[p] * inv + flt[p] * a);
- dst[p + 1] = Math.round(src[p + 1] * inv + flt[p + 1] * a);
- dst[p + 2] = Math.round(src[p + 2] * inv + flt[p + 2] * a);
- dst[p + 3] = Math.round(src[p + 3] * inv + flt[p + 3] * a);
- }
- }
- }
- }
+ // Thin Canvas Drawing Dispatcher (reads tool & brushSettings from useToolStore without subscribing!)
+ const drawing = useCanvasDrawing({
+ dimensions,
+ colorMode,
+ disabled: !hasOpenDocument || nav.isSpaceDown || nav.isPanning || nav.isRotating,
+ viewportRef: nav.viewportRef,
+ pan: nav.pan,
+ zoom: nav.zoom,
+ rotation: nav.rotation,
+ flipX: nav.flipX,
+ flipY: nav.flipY,
+ navigation: nav.navigation,
+ activeLayerId: layerMgr.activeLayerId,
+ activeSessionId: activeDocumentId,
+ tileGrid: activeTileGrid,
+ materializeLayerCanvas: layerMgr.materializeLayerCanvas,
+ activeLayerLocked: layerMgr.activeLayer?.locked ?? false,
+ activeLayerVisible: layerMgr.activeLayer
+ ? layerMgr.isLayerEffectivelyVisible(layerMgr.activeLayer)
+ : true,
+ layerCanvasesRef: layerMgr.layerCanvasesRef,
+ layerSourceCanvasesRef: layerMgr.layerSourceCanvasesRef,
+ layers: hasOpenDocument ? layerMgr.layers : [],
+ onUpdateLayerThumbnail: layerMgr.updateLayerThumbnail,
+ isMaskMode: activeEditTarget === 'mask',
+ onUpdateMaskThumbnail: layerMgr.updateMaskThumbnail,
+ draftCanvasRef,
+ strokeCanvasRef,
+ onCollabStrokeStart: handleCollabStrokeStart,
+ onCollabStrokeChunk: handleCollabStrokeChunk,
+ onCollabStrokeFinish: handleCollabStrokeFinish,
+ onCollabCursorMove: handleCollabCursorMove,
+ perspectiveRuler: hasOpenDocument ? perspectiveRuler : null,
+ onActiveConstraintAxisChange: documentStoreActions.setActiveLockedAxis,
+ selection: hasOpenDocument ? selectionTools.selection : null,
+ });
- const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+ selectiveUndoRef.current = drawing.selectiveUndo;
+ pushHistoryStepRef.current = drawing.pushHistoryStep;
+ getActiveCanvasRef.current = drawing.getActiveCanvas;
- if (isTone && sourceCanvas) {
- get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
- const effDisplay = displayCanvas || materializeLayerCanvas(activeLayerId);
- if (effDisplay) {
- applyLayerEffects(sourceCanvas, effDisplay, activeLayer, dimensions.dpi ?? 600);
- grid.ingestCanvas(activeLayerId, effDisplay, targetFormat);
- }
- } else {
- grid.writeImageData(activeLayerId, finalImageData, 0, 0, targetFormat);
- if (displayCanvas) {
- get2DContext(displayCanvas)?.putImageData(finalImageData, 0, 0);
- releaseLayerCanvas(activeLayerId);
- }
- if (sourceCanvas) {
- get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
- }
- }
+ const handleUndo = useCallback(() => {
+ if (collab.isConnected && collab.myPeer.id) {
+ drawing.selectiveUndo(collab.myPeer.id);
+ multiplayerService.sendSelectiveUndo(collab.myPeer.id.toString());
+ } else {
+ drawing.undo();
+ }
+ }, [collab.isConnected, collab.myPeer.id, drawing]);
- pushHistoryStepRef.current?.(
- 'filter',
- `Filter: ${type.replace('-', ' ')}`,
- beforeImageData,
- finalImageData,
- activeLayerId
+ const getCanvasCoords = useCallback(
+ (e: React.PointerEvent<HTMLElement> | PointerEvent) => {
+ if (!nav.viewportRef.current) return { x: 0, y: 0 };
+ const vRect = nav.viewportRef.current.getBoundingClientRect();
+ return screenToCanvas(
+ e.clientX,
+ e.clientY,
+ vRect,
+ nav.navigation.panRef.current,
+ nav.navigation.zoomRef.current,
+ nav.navigation.rotationRef.current,
+ dimensions,
+ nav.navigation.flipXRef.current,
+ nav.navigation.flipYRef.current
);
- grid.notifyChange(true);
- updateLayerThumbnail(activeLayerId, true);
- showToast(`Filter applied: ${type.replace('-', ' ')}`);
},
- [hasOpenDocument, activeLayer, activeLayerId, selection, dimensions.width, dimensions.height, dimensions.dpi, layerCanvasesRef, layerSourceCanvasesRef, materializeLayerCanvas, releaseLayerCanvas, colorMode, updateLayerThumbnail, showToast]
+ [nav.viewportRef, nav.navigation, dimensions]
);
- const {
- viewportRef,
- navigation,
- zoom,
- pan,
- rotation,
- flipX,
- flipY,
- isSpaceDown,
- isShiftDown,
- isRotateModifier,
- isPanning,
- isRotating,
- startPan,
- startRotate,
- zoomIn,
- zoomOut,
- resetZoomAndCenter,
- resetRotation,
- toggleFlipHorizontal,
- toggleFlipVertical,
- resetViewFlip,
- } = useCanvasNavigation({
+ // Modular Shape, Fill, Eyedropper, Text, Balloon & Liquify Tools
+ const shapeFillTools = useShapeAndFillTools({
dimensions,
- isWebtoonMode,
- activeDocumentId,
+ colorMode,
+ layers: layerMgr.layers,
+ activeLayer: layerMgr.activeLayer,
+ activeLayerId: layerMgr.activeLayerId,
+ selection: selectionTools.selection,
+ layerCanvasesRef: layerMgr.layerCanvasesRef,
+ layerSourceCanvasesRef: layerMgr.layerSourceCanvasesRef,
+ isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
+ getEffectiveOpacity: layerMgr.getEffectiveOpacity,
+ getActiveCanvas: drawing.getActiveCanvas,
+ getCanvasCoords,
+ updateLayerThumbnail: layerMgr.updateLayerThumbnail,
+ pushHistoryStep: drawing.pushHistoryStep,
});
- // Remote multiplayer draft overlays and stroke states
- const remoteDraftCanvasesRef = useRef<Map<string | number, HTMLCanvasElement>>(new Map());
- const remoteStrokeStatesRef = useRef<
- Map<
- string,
- {
- brushSettings: BrushSettings;
- tool: ToolType;
- points: Point[];
- layerId: string;
- peerId: string | number;
- }
- >
- >(new Map());
-
- const handleRemoteStrokeStart = useCallback((msg: StrokeStartMessage) => {
- remoteStrokeStatesRef.current.set(msg.strokeId, {
- brushSettings: msg.brushSettings,
- tool: msg.tool,
- points: [msg.startPoint],
- layerId: msg.layerId,
- peerId: msg.peerId,
- });
+ // Modular Vector Edit Tool
+ const vectorTools = useVectorDrawing({
+ activeLayer: layerMgr.activeLayer,
+ activeLayerId: layerMgr.activeLayerId,
+ colorMode,
+ getActiveCanvas: drawing.getActiveCanvas,
+ getCanvasCoords,
+ updateLayerThumbnail: layerMgr.updateLayerThumbnail,
+ pushHistoryStep: drawing.pushHistoryStep,
+ showToast,
+ });
- const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
- if (!draftCanvas) return;
- const ctx = get2DContext(draftCanvas);
- if (!ctx) return;
+ // Tonal, Filter, Adjustment, Styles, Screentone & Expression Color Actions
+ const tonalActions = useTonalAndFilterActions({
+ hasOpenDocument,
+ dimensions,
+ colorMode,
+ layers: layerMgr.layers,
+ activeLayer: layerMgr.activeLayer,
+ activeLayerId: layerMgr.activeLayerId,
+ selection: selectionTools.selection,
+ layerCanvasesRef: layerMgr.layerCanvasesRef,
+ layerSourceCanvasesRef: layerMgr.layerSourceCanvasesRef,
+ materializeLayerCanvas: layerMgr.materializeLayerCanvas,
+ releaseLayerCanvas: layerMgr.releaseLayerCanvas,
+ setActiveLayerId: layerMgr.setActiveLayerId,
+ getActiveCanvas: drawing.getActiveCanvas,
+ updateLayerThumbnail: layerMgr.updateLayerThumbnail,
+ handleCommitFloatingSelection: selectionTools.handleCommitFloatingSelection,
+ pushHistoryStepRef,
+ addLayer: layerMgr.addLayer,
+ pasteLayerFromCanvas: layerMgr.pasteLayerFromCanvas,
+ addAdjustmentLayer: layerMgr.addAdjustmentLayer,
+ updateAdjustmentData: layerMgr.updateAdjustmentData,
+ updateLayerStyles: layerMgr.updateLayerStyles,
+ fillScreentoneSelection: layerMgr.fillScreentoneSelection,
+ applyExpressionColorOfPreview: layerMgr.applyExpressionColorOfPreview,
+ applyLayerColorPermanently: layerMgr.applyLayerColorPermanently,
+ convertLayer: layerMgr.convertLayer,
+ showToast,
+ });
- ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
- const bs = msg.brushSettings;
- const isEraser = msg.tool === 'eraser';
- const isBgEraser = isEraser && (msg.layerId === 'layer-bg' || msg.layerId.startsWith('layer-bg'));
- const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
+ // Document Lifecycle Operations
+ const docLifecycle = useDocumentLifecycle({
+ layers: layerMgr.layers,
+ activeLayer: layerMgr.activeLayer,
+ activeLayerId: layerMgr.activeLayerId,
+ layerCanvasesRef: layerMgr.layerCanvasesRef,
+ getEffectiveOpacity: layerMgr.getEffectiveOpacity,
+ isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
+ setActiveLayerId: layerMgr.setActiveLayerId,
+ resetToNewCanvas: layerMgr.resetToNewCanvas,
+ setDefaultToneFrequency: layerMgr.setDefaultToneFrequency,
+ clearDocument: layerMgr.clearDocument,
+ loadDocument: layerMgr.loadDocument,
+ switchDocumentSession: layerMgr.switchDocumentSession,
+ resizeCanvas: layerMgr.resizeCanvas,
+ copyLayer: layerMgr.copyLayer,
+ pasteLayer: layerMgr.pasteLayer,
+ deleteLayer: layerMgr.deleteLayer,
+ pasteLayerFromFile: layerMgr.pasteLayerFromFile,
+ resetZoomAndCenter: nav.resetZoomAndCenter,
+ resetHistory: drawing.resetHistory,
+ pushHistoryStep: drawing.pushHistoryStep,
+ showToast,
+ });
- if (isPencil) {
- drawPencilDot(
- ctx,
- msg.startPoint,
- strokeColor,
- (bs.preset as PencilGrade) || 'pencil-2b',
- bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- bs.hardness
+ const handleToggleReferenceLayer = useCallback(
+ (layerId: string) => {
+ layerMgr.setLayers((prev) =>
+ prev.map((l) => (l.id === layerId ? { ...l, isReference: !l.isReference } : l))
);
+ },
+ [layerMgr.setLayers]
+ );
+
+ const handleMergeDown = useCallback(() => {
+ const res = layerMgr.mergeDown();
+ if (res) {
+ documentStoreActions.markDocumentDirty(activeDocumentId, true);
+ showToast('Merged layer down');
} else {
- drawDot(
- ctx,
- msg.startPoint,
- strokeColor,
- isEraser && !isBgEraser,
- colorMode === 'monochrome' ? 1.0 : (bs.hardness ?? 1.0),
- bs.flow ?? 1.0
- );
+ showToast('Cannot merge down: need an unlocked raster layer below');
}
- }, [colorMode]);
-
- const handleRemoteStrokeChunk = useCallback((msg: StrokeChunkMessage) => {
- const strokeState = remoteStrokeStatesRef.current.get(msg.strokeId);
- if (!strokeState) return;
-
- const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
- if (!draftCanvas) return;
- const ctx = get2DContext(draftCanvas);
- if (!ctx) return;
+ }, [layerMgr.mergeDown, activeDocumentId, showToast]);
- const bs = strokeState.brushSettings;
- const isEraser = strokeState.tool === 'eraser';
- const isBgEraser = isEraser && (strokeState.layerId === 'layer-bg' || strokeState.layerId.startsWith('layer-bg'));
- const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
- const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
- const pts = strokeState.points;
-
- for (let i = 0; i < msg.points.length; i++) {
- const pt = msg.points[i];
- pts.push(pt);
+ // Mark active document dirty whenever a new history step is committed on the same document
+ const lastHistoryMetaRef = useRef<{ docId: string | null; itemId: string | null }>({
+ docId: null,
+ itemId: null,
+ });
+ useEffect(() => {
+ const currentItem = drawing.historyList[drawing.historyIndex];
+ const currentItemId = currentItem?.id ?? null;
+ const prev = lastHistoryMetaRef.current;
+ if (
+ activeDocumentId &&
+ prev.docId === activeDocumentId &&
+ currentItemId &&
+ currentItemId !== prev.itemId &&
+ drawing.historyIndex > 0
+ ) {
+ documentStoreActions.markDocumentDirty(activeDocumentId, true);
+ }
+ lastHistoryMetaRef.current = { docId: activeDocumentId, itemId: currentItemId };
+ }, [activeDocumentId, drawing.historyList, drawing.historyIndex]);
+
+ // Unified Pointer Dispatcher reading tool imperatively from useToolStore
+ const handlePointerDown = useCallback(
+ (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => {
+ if (!hasOpenDocument || e.button !== 0) return;
+ const tool = useToolStore.getState().tool;
+ const pt = getCanvasCoords(e);
- if (isPencil) {
- if (pts.length >= 3) {
- const p0 = pts[pts.length - 3];
- const p1 = pts[pts.length - 2];
- const p2 = pts[pts.length - 1];
- drawPencilBezierSegment(
- ctx,
- getMidPoint(p0, p1),
- p1,
- getMidPoint(p1, p2),
- strokeColor,
- (bs.preset as PencilGrade) || 'pencil-2b',
- bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- bs.hardness
- );
- } else if (pts.length === 2) {
- drawPencilBezierSegment(
- ctx,
- pts[0],
- pts[0],
- getMidPoint(pts[0], pts[1]),
- strokeColor,
- (bs.preset as PencilGrade) || 'pencil-2b',
- bs.flow ?? 0.74,
- bs.grain ?? 1.0,
- bs.hardness
- );
- }
- } else if (bs.smoothing) {
- if (pts.length >= 3) {
- const p0 = pts[pts.length - 3];
- const p1 = pts[pts.length - 2];
- const p2 = pts[pts.length - 1];
- drawSmoothBezierSegment(
- ctx,
- getMidPoint(p0, p1),
- p1,
- getMidPoint(p1, p2),
- strokeColor,
- isEraser && !isBgEraser,
- colorMode === 'monochrome' ? 1.0 : (bs.hardness ?? 1.0),
- bs.flow ?? 1.0,
- bs.spacing ?? 0.1
- );
- } else if (pts.length === 2) {
- drawSmoothBezierSegment(
- ctx,
- pts[0],
- pts[0],
- getMidPoint(pts[0], pts[1]),
- strokeColor,
- isEraser && !isBgEraser,
- colorMode === 'monochrome' ? 1.0 : (bs.hardness ?? 1.0),
- bs.flow ?? 1.0,
- bs.spacing ?? 0.1
- );
- }
- } else {
- if (pts.length >= 2) {
- const pPrev = pts[pts.length - 2];
- const pCurr = pts[pts.length - 1];
- ctx.save();
- ctx.lineCap = 'round';
- ctx.lineJoin = 'round';
- if ((bs.flow ?? 1.0) < 0.999) {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.flow ?? 1.0));
- }
- if (isBgEraser) {
- ctx.globalCompositeOperation = 'source-over';
- ctx.strokeStyle = '#ffffff';
- } else if (isEraser) {
- ctx.globalCompositeOperation = 'destination-out';
- ctx.strokeStyle = 'rgba(0, 0, 0, 1)';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- ctx.strokeStyle = strokeColor;
- }
- ctx.lineWidth = (pPrev.width + pCurr.width) / 2;
- ctx.beginPath();
- ctx.moveTo(pPrev.x, pPrev.y);
- ctx.lineTo(pCurr.x, pCurr.y);
- ctx.stroke();
- ctx.restore();
+ if (tool === 'brush' || tool === 'eraser') {
+ if (selectionTools.selection?.floating) {
+ selectionTools.handleCommitFloatingSelection();
}
+ drawing.handlePointerDown(e, coalescedEvents);
+ return;
}
- }
- }, [colorMode]);
- const layersRef = useRef(layers);
- useEffect(() => {
- layersRef.current = layers;
- }, [layers]);
-
- const handleRemoteStrokeFinish = useCallback((msg: StrokeFinishMessage) => {
- const strokeState = remoteStrokeStatesRef.current.get(msg.strokeId);
- if (!strokeState) return;
-
- if (msg.endPoint) {
- strokeState.points.push(msg.endPoint);
- }
+ if (tool === 'vector-edit') {
+ vectorTools.handleVectorEditPointerDown(e, pt);
+ return;
+ }
- // Resolve target layer canvas with robust fallback so remote strokes never disappear
- let targetCanvas = layerCanvasesRef.current.get(msg.layerId);
- let targetLayerId = msg.layerId;
+ if (selectionTools.handleSelectionPointerDown(e, pt)) return;
+ shapeFillTools.handleShapeFillPointerDown(e, pt);
+ },
+ [hasOpenDocument, getCanvasCoords, selectionTools, drawing, vectorTools, shapeFillTools]
+ );
- if (!targetCanvas) {
- // 1. Try finding by peer id in layer id
- const byPeerId = layersRef.current.find(
- (l) => l.type === 'raster' && l.id.includes(String(msg.peerId))
- );
- if (byPeerId) {
- targetCanvas = layerCanvasesRef.current.get(byPeerId.id);
- targetLayerId = byPeerId.id;
+ const handlePointerMove = useCallback(
+ (
+ e: React.PointerEvent<HTMLElement>,
+ coalescedEvents?: PointerEvent[],
+ predictedEvents?: PointerEvent[]
+ ) => {
+ const tool = useToolStore.getState().tool;
+ if (tool === 'brush' || tool === 'eraser') {
+ drawing.handlePointerMove(e, coalescedEvents, predictedEvents);
+ return;
}
- }
-
- if (!targetCanvas) {
- // 2. Fallback to active layer or top raster layer
- const fallback =
- layersRef.current.find(
- (l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
- ) || layersRef.current.find((l) => l.type === 'raster');
- if (fallback) {
- targetCanvas = layerCanvasesRef.current.get(fallback.id);
- targetLayerId = fallback.id;
+ if (tool === 'vector-edit') {
+ vectorTools.handleVectorEditPointerMove(e);
+ return;
}
- }
-
- if (targetCanvas && strokeState.points.length > 0) {
- const targetLayer = layersRef.current.find((l) => l.id === targetLayerId);
- const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (msg.vectorStroke && targetLayer?.type === 'vector') {
- targetLayer.vectorStrokes = [...(targetLayer.vectorStrokes || []), msg.vectorStroke];
- const ctx = get2DContext(targetCanvas);
- if (ctx) {
- renderVectorStroke(ctx, msg.vectorStroke);
- const fullData = ctx.getImageData(0, 0, targetCanvas.width, targetCanvas.height);
- documentStore.getActiveTileGrid().writeImageData(targetLayerId, fullData, 0, 0, targetFormat);
- }
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(targetLayerId, true);
- } else {
- const ctx = get2DContext(targetCanvas);
- if (ctx) {
- const isEraser = strokeState.tool === 'eraser';
- const isBgEraser = isEraser && (targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg'));
- const bs = strokeState.brushSettings;
- const isTranslucentBrush = !isEraser && (bs.opacity ?? 1.0) < 0.999;
- const isAlphaLocked = Boolean(targetLayer?.alphaLocked);
- const isTransparentInk = Boolean(bs.isTransparentInk);
-
- if (isTranslucentBrush || isTransparentInk || isAlphaLocked) {
- const bakeCanvas = getReusableBakeCanvas(targetCanvas.width, targetCanvas.height);
- const bCtx = get2DContext(bakeCanvas);
- if (bCtx) {
- bCtx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
- renderCompleteStroke(
- bCtx,
- strokeState.points,
- { ...bs, opacity: 1.0, isTransparentInk: false },
- strokeState.tool,
- colorMode,
- isBgEraser,
- targetCanvas,
- false
- );
- ctx.save();
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if (isTransparentInk) {
- ctx.globalCompositeOperation = 'destination-out';
- } else if (isAlphaLocked) {
- ctx.globalCompositeOperation = 'source-atop';
- } else {
- ctx.globalCompositeOperation = 'source-over';
- }
- ctx.drawImage(bakeCanvas, 0, 0);
- ctx.restore();
- }
- } else {
- renderCompleteStroke(
- ctx,
- strokeState.points,
- bs,
- strokeState.tool,
- colorMode,
- isBgEraser,
- targetCanvas,
- isAlphaLocked
- );
- }
-
- const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5));
- let dirtyX = 0;
- let dirtyY = 0;
- let dirtyW = targetCanvas.width;
- let dirtyH = targetCanvas.height;
-
- if (msg.dirtyRect) {
- dirtyX = Math.max(0, Math.floor(msg.dirtyRect.x));
- dirtyY = Math.max(0, Math.floor(msg.dirtyRect.y));
- dirtyW = Math.min(targetCanvas.width - dirtyX, Math.ceil(msg.dirtyRect.width));
- dirtyH = Math.min(targetCanvas.height - dirtyY, Math.ceil(msg.dirtyRect.height));
- } else if (strokeState.points.length > 0) {
- let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
- for (const pt of strokeState.points) {
- if (pt.x < minX) minX = pt.x;
- if (pt.y < minY) minY = pt.y;
- if (pt.x > maxX) maxX = pt.x;
- if (pt.y > maxY) maxY = pt.y;
- }
- dirtyX = Math.max(0, Math.floor(minX - pad));
- dirtyY = Math.max(0, Math.floor(minY - pad));
- dirtyW = Math.min(targetCanvas.width - dirtyX, Math.ceil(maxX + pad) - dirtyX);
- dirtyH = Math.min(targetCanvas.height - dirtyY, Math.ceil(maxY + pad) - dirtyY);
- }
-
- if (dirtyW > 0 && dirtyH > 0) {
- const afterData = ctx.getImageData(dirtyX, dirtyY, dirtyW, dirtyH);
- documentStore.getActiveTileGrid().writeImageData(targetLayerId, afterData, dirtyX, dirtyY, targetFormat);
- }
+ if (shapeFillTools.handleShapeFillPointerMove(e)) return;
+ selectionTools.handleSelectionPointerMove(getCanvasCoords(e));
+ },
+ [drawing, vectorTools, shapeFillTools, selectionTools, getCanvasCoords]
+ );
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(targetLayerId, true);
- }
+ const handlePointerUp = useCallback(
+ (e: React.PointerEvent<HTMLElement>) => {
+ const tool = useToolStore.getState().tool;
+ if (tool === 'brush' || tool === 'eraser') {
+ drawing.handlePointerUp(e);
+ return;
}
- }
-
- // Clear remote draft canvas
- const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
- if (draftCanvas) {
- const ctx = get2DContext(draftCanvas);
- if (ctx) {
- ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ if (tool === 'vector-edit') {
+ vectorTools.handleVectorEditPointerUp();
+ return;
}
- }
+ const pt = getCanvasCoords(e);
+ if (selectionTools.handleSelectionPointerUp(pt)) return;
+ shapeFillTools.handleShapeFillPointerUp(e, pt);
+ },
+ [drawing, vectorTools, getCanvasCoords, selectionTools, shapeFillTools]
+ );
- remoteStrokeStatesRef.current.delete(msg.strokeId);
- }, [colorMode, layerCanvasesRef, updateLayerThumbnail]);
+ // Memoized Top Menu Bar Sections (independent of brush size & color)
+ const menuSections = useAppMenuSections({
+ hasOpenDocument,
+ dimensions,
+ layers: layerMgr.layers,
+ activeLayer: layerMgr.activeLayer,
+ activeLayerId: layerMgr.activeLayerId,
+ selection: selectionTools.selection,
+ canUndo: drawing.canUndo,
+ canRedo: drawing.canRedo,
+ flipX: nav.flipX,
+ flipY: nav.flipY,
+ isWebtoonMode,
+ perspectiveRuler,
+ softProofSettings,
+ activeAnimationTimeline,
+ clearCanvas: drawing.clearCanvas,
+ handleUndo,
+ redo: drawing.redo,
+ handleTriggerOpenFile: docLifecycle.handleTriggerOpenFile,
+ handleTriggerImport3DFile: docLifecycle.handleTriggerImport3DFile,
+ handleSave: docLifecycle.handleSave,
+ handleSaveAs: docLifecycle.handleSaveAs,
+ handleExportImage: docLifecycle.handleExportImage,
+ handleCopySelectedLayer: docLifecycle.handleCopySelectedLayer,
+ handlePasteSelectedLayer: docLifecycle.handlePasteSelectedLayer,
+ handleTriggerPasteFromFile: docLifecycle.handleTriggerPasteFromFile,
+ handleDeleteSelectedLayer: docLifecycle.handleDeleteSelectedLayer,
+ handleClearActiveLayer: collab.handleClearActiveLayer,
+ handleStartTransform: selectionTools.handleStartTransform,
+ handleDeselect: selectionTools.handleDeselect,
+ handleFillSelectionColor: selectionTools.handleFillSelectionColor,
+ handleOpenTonalModal: tonalActions.handleOpenTonalModal,
+ handleApplyReverseGradient: tonalActions.handleApplyReverseGradient,
+ handleSelectAll: selectionTools.handleSelectAll,
+ handleInvertSelection: selectionTools.handleInvertSelection,
+ handleExpandSelection: selectionTools.handleExpandSelection,
+ handleContractSelection: selectionTools.handleContractSelection,
+ handleFeatherSelection: selectionTools.handleFeatherSelection,
+ handleAddLayer: collab.handleAddLayer,
+ handleOpenAdjustmentModal: tonalActions.handleOpenAdjustmentModal,
+ addLayerMask: layerMgr.addLayerMask,
+ removeLayerMask: layerMgr.removeLayerMask,
+ toggleLayerMask: layerMgr.toggleLayerMask,
+ toggleMaskLinked: layerMgr.toggleMaskLinked,
+ duplicateLayer: layerMgr.duplicateLayer,
+ handleMergeDown,
+ handleOpenLayerStylesModal: tonalActions.handleOpenLayerStylesModal,
+ toggleLayerColor: layerMgr.toggleLayerColor,
+ handleConvertLayer: tonalActions.handleConvertLayer,
+ deleteLayer: layerMgr.deleteLayer,
+ handleApplyFilter: tonalActions.handleApplyFilter,
+ zoomIn: nav.zoomIn,
+ zoomOut: nav.zoomOut,
+ resetZoomAndCenter: nav.resetZoomAndCenter,
+ resetRotation: nav.resetRotation,
+ toggleFlipHorizontal: nav.toggleFlipHorizontal,
+ toggleFlipVertical: nav.toggleFlipVertical,
+ resetViewFlip: nav.resetViewFlip,
+ handleUpdateAnimationTimeline,
+ handleAddAnimationCel,
+ showToast,
+ });
- const handleRemoteDocSync = useCallback((
- syncDims: CanvasDimensions,
- syncMode: CanvasColorMode,
- syncLayers: LayerItem[],
- syncDataUrls: Record<string, string>
- ) => {
- setDimensions(syncDims);
- setColorMode(syncMode);
- syncRemoteDocument(syncLayers, syncDataUrls);
- const newDocId = `doc-collab-${Date.now()}`;
- const newDoc: DocumentTab = {
- id: newDocId,
- name: 'Collab Session',
- dimensions: syncDims,
- colorMode: syncMode,
- layers: syncLayers,
- activeLayerId: syncLayers[0]?.id || 'layer-1',
- perspectiveRuler: null,
- };
- setPerspectiveRuler(null);
- setDocuments([newDoc]);
- setActiveDocumentId(newDocId);
- setDocumentName('Collab Session');
- }, [syncRemoteDocument]);
-
- const handleRemoteAssignedLayer = useCallback((layerId: string) => {
- setActiveLayerId(layerId);
- }, [setActiveLayerId]);
-
- const handleRemoteJoinRequest = useCallback((peer: import('./types/multiplayer').CollabPeer) => {
- // Automatically allocate a dedicated layer for the joining peer without hijacking host's active layer
- const layerName = getNextCollabLayerName(peer.name, layersRef.current);
- const layerId = `layer-${peer.id}-1`;
- const newLayer = addLayer('raster', null, layerName, layerId, false);
- multiplayerService.sendLayerAdd(newLayer);
- const updated = layersRef.current.some((l) => l.id === newLayer.id)
- ? layersRef.current
- : [newLayer, ...layersRef.current];
- return {
- assignedLayerId: layerId,
- updatedLayers: updated,
- };
- }, [addLayer]);
-
- const handleRemoteLayerAction = useCallback((msg: MultiplayerMessage) => {
- if (msg.type === 'LAYER_ADD') {
- const layerItem = (msg as any).layerItem as LayerItem;
- const imageDataUrl = (msg as any).imageDataUrl as string | undefined;
- if (layerItem) {
- addRemoteLayer(layerItem, imageDataUrl);
- }
- } else if (msg.type === 'LAYER_DELETE') {
- const layerId = (msg as any).layerId;
- if (layerId) {
- deleteRemoteLayer(layerId);
- }
- } else if (msg.type === 'LAYER_CLEAR') {
- const layerId = (msg as any).layerId;
- const targetCanvas = layerCanvasesRef.current.get(layerId);
- if (targetCanvas) {
- const ctx = get2DContext(targetCanvas);
- if (ctx) {
- const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
- if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, targetCanvas.width, targetCanvas.height);
- documentStore.getActiveTileGrid().ingestCanvas(layerId, targetCanvas, 'color-32bit');
- } else {
- ctx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
- documentStore.getActiveTileGrid().clearLayer(layerId);
- }
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(layerId, true);
- }
- }
- } else if (msg.type === 'LAYER_RENAME') {
- const layerId = (msg as any).layerId;
- const newName = (msg as any).newName;
- if (layerId && newName) {
- renameLayer(layerId, newName);
- }
- } else if (msg.type === 'LAYER_VISIBILITY') {
- const layerId = (msg as any).layerId;
- const visible = (msg as any).visible;
- if (layerId && visible !== undefined) {
- const l = layersRef.current.find((item) => item.id === layerId);
- if (l && l.visible !== visible) {
- toggleVisibility(layerId);
- }
- }
- } else if (msg.type === 'LAYER_OPACITY') {
- const layerId = (msg as any).layerId;
- const opacity = (msg as any).opacity;
- if (layerId && opacity !== undefined) {
- setOpacity(layerId, opacity);
- }
- }
- }, [addRemoteLayer, deleteRemoteLayer, layerCanvasesRef, updateLayerThumbnail, renameLayer, toggleVisibility, setOpacity]);
-
- const selectiveUndoRef = useRef<(peerId?: string | number) => void>(() => {});
-
- const {
- isConnected: isCollabConnected,
- isHost: isCollabHost,
- hostInfo: collabHostInfo,
- peers: collabPeers,
- myPeer: collabMyPeer,
- activePings: collabActivePings,
- clipboardInvite,
- setClipboardInvite,
- webLandingInvite,
- setWebLandingInvite,
- isHostModalOpen,
- setIsHostModalOpen,
- startHosting,
- stopHosting,
- joinRoom,
- leaveRoom: _leaveRoom,
- updateMyName,
- sendPing: _sendPing,
- } = useMultiplayer({
- dimensions,
- colorMode,
- layers,
- layerCanvasesRef,
- onRemoteStrokeStart: handleRemoteStrokeStart,
- onRemoteStrokeChunk: handleRemoteStrokeChunk,
- onRemoteStrokeFinish: handleRemoteStrokeFinish,
- onRemoteDocSync: handleRemoteDocSync,
- onRemoteJoinRequest: handleRemoteJoinRequest,
- onRemoteAssignedLayer: handleRemoteAssignedLayer,
- onRemoteLayerAction: handleRemoteLayerAction,
- onRemoteSelectiveUndo: (_strokeId, peerId) => {
- selectiveUndoRef.current(peerId);
- },
- showToast,
- });
-
- // When hosting starts, ensure host's primary drawing layer has the host's nickname
- const handleStartHosting = useCallback(
- async (roomName: string, port: number, hostNickname?: string, isGlobal?: boolean) => {
- if (!hasOpenDocument) {
- showToast('Please create or open a canvas before hosting a session.');
- return false;
- }
- const finalHostName = (hostNickname || collabMyPeer.name || 'Sora').trim();
- const defaultLayer =
- layersRef.current.find((l) => l.id === activeLayerId) ||
- layersRef.current.find((l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg'));
- if (
- defaultLayer &&
- (defaultLayer.name === 'Layer 1' ||
- !defaultLayer.name.toLowerCase().startsWith(finalHostName.toLowerCase()))
- ) {
- const hostLayerName = getNextCollabLayerName(
- finalHostName,
- layersRef.current.filter((l) => l.id !== defaultLayer.id)
- );
- renameLayer(defaultLayer.id, hostLayerName);
- }
- return await startHosting(roomName, port, finalHostName, isGlobal);
- },
- [hasOpenDocument, showToast, collabMyPeer.name, activeLayerId, renameLayer, startHosting]
- );
-
- // Collaborative-aware Layer Operations
- const handleAddLayer = useCallback(
- (type: 'raster' | 'folder' = 'raster') => {
- if (isCollabConnected && type === 'raster') {
- const name = getNextCollabLayerName(collabMyPeer.name, layersRef.current);
- const newLayer = addLayer('raster', null, name);
- if (newLayer) {
- multiplayerService.sendLayerAdd(newLayer);
- }
- } else {
- addLayer(type);
- }
- },
- [isCollabConnected, collabMyPeer.name, addLayer]
- );
-
- const handleDeleteLayer = useCallback(
- (id: string) => {
- deleteLayer(id);
- if (isCollabConnected) {
- multiplayerService.sendLayerDelete(id);
- }
- },
- [deleteLayer, isCollabConnected]
- );
-
- const handleDeleteSelectedLayers = useCallback(() => {
- if (selectedLayerIds && selectedLayerIds.length > 1) {
- deleteSelectedLayers();
- showToast(`Deleted ${selectedLayerIds.length} layers`);
- } else {
- handleDeleteLayer(activeLayerId);
- }
- }, [selectedLayerIds, deleteSelectedLayers, handleDeleteLayer, activeLayerId, showToast]);
-
- const handleGroupSelectedLayers = useCallback(() => {
- groupSelectedLayers();
- showToast('Grouped layers into folder');
- }, [groupSelectedLayers, showToast]);
-
- const handleToggleVisibility = useCallback(
- (id: string) => {
- const l = layersRef.current.find((item) => item.id === id);
- toggleVisibility(id);
- if (isCollabConnected && l) {
- multiplayerService.sendLayerVisibility(id, !l.visible);
- }
- },
- [toggleVisibility, isCollabConnected]
- );
-
- const handleSetOpacity = useCallback(
- (id: string, opacity: number) => {
- setOpacity(id, opacity);
- if (isCollabConnected) {
- multiplayerService.sendLayerOpacity(id, opacity);
- }
- },
- [setOpacity, isCollabConnected]
- );
-
- const handleRenameLayer = useCallback(
- (id: string, newName: string) => {
- renameLayer(id, newName);
- if (isCollabConnected) {
- multiplayerService.sendLayerRename(id, newName);
- }
- },
- [renameLayer, isCollabConnected]
- );
-
- const handleClearActiveLayer = useCallback(() => {
- clearActiveLayer();
- if (isCollabConnected) {
- multiplayerService.sendLayerClear(activeLayerId);
- }
- }, [clearActiveLayer, isCollabConnected, activeLayerId]);
-
- const {
- interactionRef,
- isDrawingRef,
- getActiveCanvas,
- pushHistoryStep,
- handlePointerDown: handleCanvasDrawingPointerDown,
- handlePointerMove: handleCanvasDrawingPointerMove,
- handlePointerUp: handleCanvasDrawingPointerUp,
- handlePointerEnter,
- handlePointerLeave,
- undo,
- redo,
- canUndo,
- canRedo,
- historyList,
- historyIndex,
- jumpToHistoryIndex,
- clearCanvas,
- resetHistory,
- selectiveUndo,
- cursorPos,
- isHovering,
- } = useCanvasDrawing({
- tool,
- brushSettings,
- dimensions,
- colorMode,
- disabled: !hasOpenDocument || isSpaceDown || isPanning || isRotating,
- viewportRef,
- pan,
- zoom,
- rotation,
- flipX,
- flipY,
- navigation,
- activeLayerId,
- activeSessionId: activeDocumentId,
- tileGrid: activeTileGrid,
- materializeLayerCanvas,
- activeLayerLocked: activeLayer?.locked ?? false,
- activeLayerVisible: activeLayer ? isLayerEffectivelyVisible(activeLayer) : true,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- layers: hasOpenDocument ? layers : [],
- onUpdateLayerThumbnail: updateLayerThumbnail,
- isMaskMode: activeEditTarget === 'mask',
- onUpdateMaskThumbnail: updateMaskThumbnail,
- draftCanvasRef,
- strokeCanvasRef,
- onCollabStrokeStart: (strokeId, layerId, bs, t, startPt) => {
- if (multiplayerService.isConnected()) {
- multiplayerService.sendStrokeStart(strokeId, layerId, bs, t, startPt);
- }
- },
- onCollabStrokeChunk: (strokeId, pts) => {
- if (multiplayerService.isConnected()) {
- multiplayerService.sendStrokeChunk(strokeId, pts);
- }
- },
- onCollabStrokeFinish: (strokeId, layerId, endPt, dirty, vectorStroke) => {
- if (multiplayerService.isConnected()) {
- multiplayerService.sendStrokeFinish(strokeId, layerId, endPt, dirty, vectorStroke);
- }
- },
- onCollabCursorMove: (x, y, isDrawing, t) => {
- if (multiplayerService.isConnected()) {
- multiplayerService.sendCursor(x, y, isDrawing, t);
- }
- },
- perspectiveRuler: hasOpenDocument ? perspectiveRuler : null,
- onActiveConstraintAxisChange: handleActiveConstraintAxisChange,
- selection: hasOpenDocument ? selection : null,
- });
-
- selectiveUndoRef.current = selectiveUndo;
- pushHistoryStepRef.current = pushHistoryStep;
-
- const handleUndo = useCallback(() => {
- if (isCollabConnected && collabMyPeer.id) {
- selectiveUndo(collabMyPeer.id);
- multiplayerService.sendSelectiveUndo(collabMyPeer.id.toString());
- } else {
- undo();
- }
- }, [isCollabConnected, collabMyPeer.id, selectiveUndo, undo]);
-
-
- const handleSelectTool = useCallback((newTool: ToolType) => {
- const prevTool = toolRef.current;
- if (prevTool === newTool) return;
-
- if (newTool === 'eraser') {
- const eraserSettings = getEffectiveBrushSettings(ERASER_PRESET_ID);
- setBrushSettings((prev) => ({
- ...prev,
- ...eraserSettings,
- color: prev.color,
- }));
- } else if (prevTool === 'eraser' && newTool === 'brush') {
- const activePreset = brushSettings.preset || getActivePresetId();
- const brushCfg = getEffectiveBrushSettings(activePreset);
- setBrushSettings((prev) => ({
- ...prev,
- ...brushCfg,
- color: prev.color,
- }));
- }
-
- setTool(newTool);
- }, [brushSettings.preset]);
-
- const updateBrushSettings = useCallback((newSettings: Partial<BrushSettings>) => {
- setBrushSettings((prev) => {
- const next = { ...prev, ...newSettings };
- const targetPresetId = toolRef.current === 'eraser'
- ? ERASER_PRESET_ID
- : (next.preset || prev.preset || DEFAULT_BRUSH_PRESET_ID);
-
- saveBrushSettingsDebounced(targetPresetId, next);
- if (next.preset && toolRef.current === 'brush') {
- saveActivePresetId(next.preset);
- }
- return next;
- });
- }, []);
-
- useEffect(() => {
- const handleBeforeUnload = () => flushPendingBrushSettingsSave();
- window.addEventListener('beforeunload', handleBeforeUnload);
- return () => {
- flushPendingBrushSettingsSave();
- window.removeEventListener('beforeunload', handleBeforeUnload);
- };
- }, []);
-
-
- const addRecentColor = useCallback((color: string) => {
- setRecentColors((prev) => {
- const filtered = prev.filter((c) => c.toLowerCase() !== color.toLowerCase());
- return [color, ...filtered].slice(0, 14);
- });
- }, []);
-
- const [isTransparentColor, setIsTransparentColor] = useState<boolean>(false);
-
- const toggleTransparentColor = useCallback(() => {
- setIsTransparentColor((prev) => {
- const next = !prev;
- updateBrushSettings({ isTransparentInk: next });
- showToast(next ? 'Transparent ink mode active' : 'Color ink mode active');
- return next;
- });
- }, [updateBrushSettings, showToast]);
-
- const handlePrimaryColorChange = useCallback(
- (color: string, commit = true) => {
- const effective = enforceColorMode(color, colorMode);
- setPrimaryColor(effective);
- setIsTransparentColor(false);
- updateBrushSettings({ color: effective, isTransparentInk: false });
- if (commit) {
- addRecentColor(effective);
- }
- if (toolRef.current === 'eraser') {
- handleSelectTool('brush');
- }
- },
- [addRecentColor, colorMode, handleSelectTool, updateBrushSettings]
- );
-
- const handleSecondaryColorChange = useCallback(
- (color: string, commit = true) => {
- const effective = enforceColorMode(color, colorMode);
- setSecondaryColor(effective);
- updateBrushSettings({ secondaryColor: effective });
- if (commit) {
- addRecentColor(effective);
- }
- },
- [addRecentColor, colorMode, updateBrushSettings]
- );
-
- const handleSwapColors = useCallback(() => {
- setIsTransparentColor(false);
- setPrimaryColor((prevPrim) => {
- setSecondaryColor(prevPrim);
- const effective = enforceColorMode(secondaryColor, colorMode);
- updateBrushSettings({ color: effective, secondaryColor: prevPrim, isTransparentInk: false });
- addRecentColor(effective);
- return effective;
- });
- if (toolRef.current === 'eraser') {
- handleSelectTool('brush');
- }
- }, [addRecentColor, colorMode, handleSelectTool, secondaryColor, updateBrushSettings]);
-
- const getCanvasCoords = useCallback(
- (e: React.PointerEvent<HTMLElement> | PointerEvent) => {
- if (!viewportRef.current) return { x: 0, y: 0 };
- const vRect = viewportRef.current.getBoundingClientRect();
- return screenToCanvas(
- e.clientX,
- e.clientY,
- vRect,
- navigation.panRef.current,
- navigation.zoomRef.current,
- navigation.rotationRef.current,
- dimensions,
- navigation.flipXRef.current,
- navigation.flipYRef.current
- );
- },
- [viewportRef, navigation, dimensions]
- );
-
- const handleSampleColor = useCallback(
- (pt: { x: number; y: number }) => {
- const sampled = sampleCompositedColor(
- layers,
- layerCanvasesRef.current,
- pt.x,
- pt.y,
- isLayerEffectivelyVisible,
- getEffectiveOpacity,
- dimensions.width,
- dimensions.height,
- selection?.floating
- );
- if (sampled) {
- handlePrimaryColorChange(sampled, true);
- }
- },
- [
- layers,
- layerCanvasesRef,
- isLayerEffectivelyVisible,
- getEffectiveOpacity,
- dimensions.width,
- dimensions.height,
- selection?.floating,
- handlePrimaryColorChange,
- ]
- );
-
- const handleCommitFloatingSelection = useCallback(() => {
- if (!selection?.floating) return;
- const targetLayerId = selection.floating.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
- if (!canvas) return;
-
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- commitFloatingSelection(canvas, selection.floating, sourceCanvas);
-
- const ctx = get2DContext(canvas);
- if (ctx) {
- const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- if (selection.floating.beforeImageData) {
- pushHistoryStep(
- 'selection-move',
- 'Move Selection',
- selection.floating.beforeImageData,
- afterData,
- targetLayerId
- );
- } else {
- const lyr = layers.find((l) => l.id === targetLayerId);
- const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().writeImageData(targetLayerId, afterData, 0, 0, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- documentStore.getActiveTileGrid().notifyChange(true);
- }
-
- updateLayerThumbnail(targetLayerId, true);
- setSelection((prev) => (prev ? { ...prev, floating: null } : null));
- }, [selection, activeLayerId, layers, colorMode, layerCanvasesRef, getActiveCanvas, layerSourceCanvasesRef, pushHistoryStep, updateLayerThumbnail]);
-
- const handleDeselect = useCallback(() => {
- if (selection?.floating) {
- handleCommitFloatingSelection();
- }
- setSelection(null);
- }, [selection, handleCommitFloatingSelection]);
-
- const handleClearSelection = useCallback(() => {
- if (!selection) return;
- if (selection.floating) {
- const targetLayerId = selection.floating.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
- if (canvas && selection.floating.beforeImageData) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- pushHistoryStep(
- 'clear',
- 'Clear Selection',
- selection.floating.beforeImageData,
- afterData,
- targetLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- }
- }
- setSelection(null);
- return;
- }
-
- const canvas = getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
-
- const clearOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- c.save();
- if (selection.mask && selection.maskWidth && selection.maskHeight) {
- const maskCanvas = document.createElement('canvas');
- maskCanvas.width = target.width;
- maskCanvas.height = target.height;
- const mCtx = maskCanvas.getContext('2d');
- if (mCtx) {
- const mImg = mCtx.createImageData(target.width, target.height);
- for (let i = 0; i < selection.mask.length; i++) {
- if (isBg) {
- mImg.data[i * 4] = 255;
- mImg.data[i * 4 + 1] = 255;
- mImg.data[i * 4 + 2] = 255;
- }
- mImg.data[i * 4 + 3] = selection.mask[i];
- }
- mCtx.putImageData(mImg, 0, 0);
- c.globalCompositeOperation = isBg ? 'source-over' : 'destination-out';
- c.drawImage(maskCanvas, 0, 0);
- }
- } else if (selection.type === 'rect') {
- if (isBg) {
- c.fillStyle = '#ffffff';
- c.fillRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
- } else {
- c.clearRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
- }
- } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
- c.beginPath();
- c.moveTo(selection.polygon[0].x, selection.polygon[0].y);
- for (let i = 1; i < selection.polygon.length; i++) {
- c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
- }
- c.closePath();
- if (isBg) {
- c.fillStyle = '#ffffff';
- c.fill();
- } else {
- c.globalCompositeOperation = 'destination-out';
- c.fillStyle = 'rgba(0, 0, 0, 1)';
- c.fill();
- }
- }
- c.restore();
- };
-
- clearOn(canvas);
- if (sourceCanvas) clearOn(sourceCanvas);
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep(
- 'clear',
- 'Clear Selection',
- beforeImageData,
- afterImageData,
- activeLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- }, [selection, getActiveCanvas, activeLayerId, layerCanvasesRef, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
-
- const handleFillSelectionColor = useCallback(() => {
- if (!selection) return;
- const canvas = getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- const fillOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- c.save();
- if (selection.mask && selection.maskWidth && selection.maskHeight) {
- const maskCanvas = document.createElement('canvas');
- maskCanvas.width = target.width;
- maskCanvas.height = target.height;
- const mCtx = maskCanvas.getContext('2d');
- if (mCtx) {
- mCtx.fillStyle = primaryColor;
- mCtx.fillRect(0, 0, target.width, target.height);
- const mImg = mCtx.getImageData(0, 0, target.width, target.height);
- for (let i = 0; i < selection.mask.length; i++) {
- mImg.data[i * 4 + 3] = Math.round((mImg.data[i * 4 + 3] * selection.mask[i]) / 255);
- }
- mCtx.putImageData(mImg, 0, 0);
- c.drawImage(maskCanvas, 0, 0);
- }
- } else {
- c.fillStyle = primaryColor;
- if (selection.type === 'rect') {
- c.fillRect(selection.bounds.x, selection.bounds.y, selection.bounds.width, selection.bounds.height);
- } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
- c.beginPath();
- c.moveTo(selection.polygon[0].x, selection.polygon[0].y);
- for (let i = 1; i < selection.polygon.length; i++) {
- c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
- }
- c.closePath();
- c.fill();
- }
- }
- c.restore();
- };
-
- fillOn(canvas);
- if (sourceCanvas) {
- fillOn(sourceCanvas);
- if (activeLayer?.toneEnabled) {
- applyLayerEffects(sourceCanvas, canvas, activeLayer, dimensions.dpi ?? 600, selection.bounds);
- }
- }
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep(
- 'fill',
- 'Fill Selection',
- beforeImageData,
- afterImageData,
- activeLayerId
- );
- }, [selection, getActiveCanvas, primaryColor, activeLayerId, activeLayer, layerSourceCanvasesRef, dimensions.dpi, updateLayerThumbnail, pushHistoryStep]);
-
- const handleExpandSelection = useCallback(
- (pixels = 5) => {
- if (!selection) return;
- const w = dimensions.width;
- const h = dimensions.height;
- const currentMask = selectionToMask(selection, w, h);
- const expanded = expandSelection(currentMask, w, h, pixels);
- const b = maskToBounds(expanded, w, h);
- if (!b) {
- setSelection(null);
- return;
- }
- const svg = maskToSvgPath(expanded, w, h);
- setSelection({
- type: 'mask',
- bounds: b,
- mask: expanded,
- maskWidth: w,
- maskHeight: h,
- svgPath: svg,
- });
- showToast(`Expanded Selection (+${pixels}px)`);
- },
- [selection, dimensions, showToast]
- );
-
- const handleContractSelection = useCallback(
- (pixels = 5) => {
- if (!selection) return;
- const w = dimensions.width;
- const h = dimensions.height;
- const currentMask = selectionToMask(selection, w, h);
- const contracted = contractSelection(currentMask, w, h, pixels);
- const b = maskToBounds(contracted, w, h);
- if (!b) {
- setSelection(null);
- showToast('Selection contracted to empty');
- return;
- }
- const svg = maskToSvgPath(contracted, w, h);
- setSelection({
- type: 'mask',
- bounds: b,
- mask: contracted,
- maskWidth: w,
- maskHeight: h,
- svgPath: svg,
- });
- showToast(`Contracted Selection (-${pixels}px)`);
- },
- [selection, dimensions, showToast]
- );
-
- const handleFeatherSelection = useCallback(
- (radius = 5) => {
- if (!selection) return;
- const w = dimensions.width;
- const h = dimensions.height;
- const currentMask = selectionToMask(selection, w, h);
- const feathered = featherSelection(currentMask, w, h, radius);
- const b = maskToBounds(feathered, w, h);
- if (!b) {
- setSelection(null);
- return;
- }
- const svg = maskToSvgPath(feathered, w, h);
- setSelection({
- type: 'mask',
- bounds: b,
- mask: feathered,
- maskWidth: w,
- maskHeight: h,
- svgPath: svg,
- });
- showToast(`Feathered Selection (${radius}px)`);
- },
- [selection, dimensions, showToast]
- );
-
- const handleInvertSelection = useCallback(() => {
- const w = dimensions.width;
- const h = dimensions.height;
- const currentMask = selection ? selectionToMask(selection, w, h) : new Uint8Array(w * h);
- const inverted = invertSelection(currentMask, w, h);
- const b = maskToBounds(inverted, w, h);
- if (!b) {
- setSelection(null);
- showToast('Inverted Selection (Empty)');
- return;
- }
- const svg = maskToSvgPath(inverted, w, h);
- setSelection({
- type: 'mask',
- bounds: b,
- mask: inverted,
- maskWidth: w,
- maskHeight: h,
- svgPath: svg,
- });
- showToast('Inverted Selection');
- }, [selection, dimensions, showToast]);
-
- const handleSelectAll = useCallback(() => {
- const w = dimensions.width;
- const h = dimensions.height;
- const mask = new Uint8Array(w * h);
- mask.fill(255);
- const svg = `M 0 0 H ${w} V ${h} H 0 Z`;
- setSelection({
- type: 'rect',
- bounds: { x: 0, y: 0, width: w, height: h },
- mask,
- maskWidth: w,
- maskHeight: h,
- svgPath: svg,
- });
- showToast('Selected All (Ctrl+A)');
- }, [dimensions, showToast]);
-
- const handleToggleReferenceLayer = useCallback((layerId: string) => {
- setLayers((prev) =>
- prev.map((l) => (l.id === layerId ? { ...l, isReference: !l.isReference } : l))
- );
- }, [setLayers]);
-
- const getTonalLabel = useCallback((type: TonalCorrectionType) => {
- switch (type) {
- case 'brightness-contrast':
- return 'Brightness/Contrast';
- case 'binarization':
- return 'Binarization';
- case 'hue-saturation':
- return 'Hue/Saturation/Luminosity';
- case 'posterization':
- return 'Posterization';
- case 'level-correction':
- return 'Level Correction';
- case 'reverse-gradient':
- return 'Reverse Gradient';
- default:
- return 'Tonal Correction';
- }
- }, []);
-
- const handleOpenTonalModal = useCallback(
- (type: TonalCorrectionType) => {
- if (!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster') return;
- if (selection?.floating) {
- handleCommitFloatingSelection();
- }
-
- const grid = documentStore.getActiveTileGrid();
- let targetLayerId = activeLayerId;
- let targetLayer = layers.find((l) => l.id === targetLayerId);
- let hasPixels = grid.hasLayerTiles(targetLayerId);
-
- if (!hasPixels) {
- const candidate = layers.find(
- (l) => l.id !== targetLayerId && l.type === 'raster' && l.visible && grid.hasLayerTiles(l.id)
- );
- if (candidate) {
- targetLayerId = candidate.id;
- targetLayer = candidate;
- setActiveLayerId(candidate.id);
- showToast(`Switched to "${candidate.name}" (active layer had no pixels)`);
- hasPixels = true;
- } else {
- showToast('Selected layer is empty. Draw or open an image first.');
- return;
- }
- }
-
- const displayCanvas = materializeLayerCanvas(targetLayerId);
-
- const isTone = Boolean(targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
-
- if (!canvas) {
- showToast('Canvas not available for active layer.');
- return;
- }
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const selectionMask = createSelectionMask(selection, canvas.width, canvas.height);
- const bounds = getProcessingBounds(selection, canvas.width, canvas.height);
-
- const newState = {
- isOpen: true,
- type,
- targetLayerId,
- beforeImageData,
- selectionMask,
- bounds,
- };
- tonalModalStateRef.current = newState;
- setTonalModalState(newState);
- },
- [
- hasOpenDocument,
- activeLayer,
- activeLayerId,
- layers,
- selection,
- handleCommitFloatingSelection,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- setActiveLayerId,
- showToast,
- ]
- );
-
- const handleTonalPreviewChange = useCallback(
- (type: TonalCorrectionType, params: any, enabled: boolean) => {
- const state = tonalModalStateRef.current;
- if (!state.isOpen || !state.beforeImageData) return;
- const targetLayerId = state.targetLayerId;
- const targetLayer = layers.find((l) => l.id === targetLayerId);
- const isTone = Boolean(targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- if (enabled) {
- const previewData = ctx.createImageData(canvas.width, canvas.height);
- applyTonalFilter(
- state.beforeImageData,
- previewData,
- type,
- params,
- state.selectionMask,
- state.bounds
- );
- ctx.putImageData(previewData, 0, 0);
- } else {
- ctx.putImageData(state.beforeImageData, 0, 0);
- }
-
- if (isTone && sourceCanvas && displayCanvas) {
- applyScreentone(sourceCanvas, displayCanvas, {
- frequency: targetLayer?.toneFrequency ?? 60,
- angle: targetLayer?.toneAngle ?? 45,
- dotShape: targetLayer?.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
-
- if (displayCanvas) {
- const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- documentStore.getActiveTileGrid().notifyChange(true);
- }
- },
- [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]
- );
-
- const handleTonalApply = useCallback(
- (type: TonalCorrectionType, params: any) => {
- const state = tonalModalStateRef.current;
- if (!state.isOpen || !state.beforeImageData) return;
- const targetLayerId = state.targetLayerId;
- const targetLayer = layers.find((l) => l.id === targetLayerId);
- const isTone = Boolean(targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const finalData = ctx.createImageData(canvas.width, canvas.height);
- applyTonalFilter(
- state.beforeImageData,
- finalData,
- type,
- params,
- state.selectionMask,
- state.bounds
- );
- ctx.putImageData(finalData, 0, 0);
-
- if (isTone && sourceCanvas && displayCanvas) {
- applyScreentone(sourceCanvas, displayCanvas, {
- frequency: targetLayer?.toneFrequency ?? 60,
- angle: targetLayer?.toneAngle ?? 45,
- dotShape: targetLayer?.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
-
- updateLayerThumbnail(targetLayerId, true);
- const label = getTonalLabel(type);
- pushHistoryStep(
- 'tonal-correction',
- label,
- state.beforeImageData,
- finalData,
- targetLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- if (!isTone) {
- releaseLayerCanvas(targetLayerId);
- }
-
- const resetState = {
- isOpen: false,
- type,
- targetLayerId: '',
- beforeImageData: null,
- selectionMask: null,
- bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
- };
- tonalModalStateRef.current = resetState;
- setTonalModalState(resetState);
- showToast(`Applied ${label}`);
- },
- [
- layers,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- dimensions.dpi,
- updateLayerThumbnail,
- getTonalLabel,
- pushHistoryStep,
- releaseLayerCanvas,
- showToast,
- ]
- );
-
- const handleTonalCancel = useCallback(() => {
- const state = tonalModalStateRef.current;
- if (!state.isOpen) return;
- if (state.beforeImageData) {
- const targetLayerId = state.targetLayerId;
- const targetLayer = layers.find((l) => l.id === targetLayerId);
- const isTone = Boolean(targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
- if (canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.putImageData(state.beforeImageData, 0, 0);
- if (isTone && sourceCanvas && displayCanvas) {
- applyScreentone(sourceCanvas, displayCanvas, {
- frequency: targetLayer?.toneFrequency ?? 60,
- angle: targetLayer?.toneAngle ?? 45,
- dotShape: targetLayer?.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
- if (displayCanvas) {
- const isMono = colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- documentStore.getActiveTileGrid().notifyChange(true);
- if (!isTone) {
- releaseLayerCanvas(targetLayerId);
- }
- }
- }
- }
- }
-
- const resetState = {
- isOpen: false,
- type: state.type,
- targetLayerId: '',
- beforeImageData: null,
- selectionMask: null,
- bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
- };
- tonalModalStateRef.current = resetState;
- setTonalModalState(resetState);
- }, [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi, releaseLayerCanvas]);
-
- const handleApplyReverseGradient = useCallback(() => {
- if (!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster') return;
- if (selection?.floating) {
- handleCommitFloatingSelection();
- }
-
- let targetLayerId = activeLayerId;
- let targetLayer = layers.find((l) => l.id === targetLayerId);
- let displayCanvas = layerCanvasesRef.current.get(targetLayerId);
-
- // Verify if target layer has pixels
- let hasPixels = false;
- if (displayCanvas) {
- const dCtx = get2DContext(displayCanvas);
- if (dCtx) {
- const dData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height).data;
- for (let i = 3; i < dData.length; i += 4) {
- if (dData[i] > 0) {
- hasPixels = true;
- break;
- }
- }
- }
- }
-
- if (!hasPixels) {
- const candidate = layers.find((l) => {
- if (l.id === targetLayerId || l.type !== 'raster' || !l.visible) return false;
- const c = layerCanvasesRef.current.get(l.id);
- if (!c) return false;
- const cCtx = get2DContext(c);
- if (!cCtx) return false;
- const cData = cCtx.getImageData(0, 0, c.width, c.height).data;
- for (let j = 3; j < cData.length; j += 4) {
- if (cData[j] > 0) return true;
- }
- return false;
- });
-
- if (candidate) {
- targetLayerId = candidate.id;
- targetLayer = candidate;
- displayCanvas = layerCanvasesRef.current.get(candidate.id);
- setActiveLayerId(candidate.id);
- showToast(`Switched to "${candidate.name}" (active layer had no pixels)`);
- } else {
- showToast('Selected layer is empty. Draw or open an image first.');
- return;
- }
- }
-
- const isTone = Boolean(targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const afterImageData = ctx.createImageData(canvas.width, canvas.height);
- afterImageData.data.set(beforeImageData.data);
-
- const mask = createSelectionMask(selection, canvas.width, canvas.height);
- const bounds = getProcessingBounds(selection, canvas.width, canvas.height);
-
- applyReverseGradient(beforeImageData, afterImageData, mask, bounds);
- ctx.putImageData(afterImageData, 0, 0);
-
- if (isTone && sourceCanvas && displayCanvas) {
- applyScreentone(sourceCanvas, displayCanvas, {
- frequency: targetLayer?.toneFrequency ?? 60,
- angle: targetLayer?.toneAngle ?? 45,
- dotShape: targetLayer?.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
-
- updateLayerThumbnail(targetLayerId, true);
- pushHistoryStep(
- 'tonal-correction',
- 'Reverse Gradient',
- beforeImageData,
- afterImageData,
- targetLayerId
- );
- showToast('Inverted colors (Reverse Gradient)');
- }, [
- hasOpenDocument,
- activeLayer,
- activeLayerId,
- layers,
- selection,
- handleCommitFloatingSelection,
- layerCanvasesRef,
- layerSourceCanvasesRef,
- dimensions.dpi,
- updateLayerThumbnail,
- pushHistoryStep,
- setActiveLayerId,
- showToast,
- ]);
-
- const handleStartTransform = useCallback(() => {
- if (transformSession?.active) return;
- const canvas = layerCanvasesRef.current.get(activeLayerId) || getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
-
- if (selection) {
- let floatCanvas = selection.floating?.canvas;
- let floatX = selection.floating?.x ?? selection.bounds.x;
- let floatY = selection.floating?.y ?? selection.bounds.y;
- let beforeData = selection.floating?.beforeImageData;
-
- if (!floatCanvas) {
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- const lifted = liftSelectionToFloating(canvas, selection, sourceCanvas, isBg);
- if (!lifted) return;
- floatCanvas = lifted.floatingCanvas;
- beforeData = lifted.beforeImageData;
- const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(activeLayerId, true);
- }
-
- const quad = createDefaultPerspectiveQuad(floatX, floatY, floatCanvas.width, floatCanvas.height, 0);
- setTransformSession({
- active: true,
- layerId: activeLayerId,
- sourceCanvas: floatCanvas,
- beforeImageData: beforeData || ctx.getImageData(0, 0, canvas.width, canvas.height),
- bounds: { x: floatX, y: floatY, width: floatCanvas.width, height: floatCanvas.height },
- x: floatX,
- y: floatY,
- width: floatCanvas.width,
- height: floatCanvas.height,
- rotation: 0,
- flipH: false,
- flipV: false,
- isSelection: true,
- mode: 'affine',
- perspectiveQuad: quad,
- meshCols: 4,
- meshRows: 4,
- meshPoints: createDefaultMeshPoints(quad, 4, 4),
- });
- setSelection(null);
- } else {
- const isMultiLayer = !selection && selectedLayerIds && selectedLayerIds.length > 1;
- const multiTargetLayers = isMultiLayer
- ? layers.filter((l) => selectedLayerIds.includes(l.id) && l.type === 'raster')
- : [];
-
- if (isMultiLayer && multiTargetLayers.length > 1) {
- // Multi-Layer Batch Transform
- const layerBeforeImages = new Map<string, ImageData>();
- const layerSourceCanvases = new Map<string, HTMLCanvasElement>();
-
- let minX = Infinity;
- let minY = Infinity;
- let maxX = -Infinity;
- let maxY = -Infinity;
-
- for (const lyr of multiTargetLayers) {
- const c = layerCanvasesRef.current.get(lyr.id);
- if (!c) continue;
- const cCtx = get2DContext(c);
- if (!cCtx) continue;
- const bData = cCtx.getImageData(0, 0, c.width, c.height);
- layerBeforeImages.set(lyr.id, bData);
-
- const cb = getCanvasContentBounds(c, lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg'));
- if (cb) {
- minX = Math.min(minX, cb.x);
- minY = Math.min(minY, cb.y);
- maxX = Math.max(maxX, cb.x + cb.width);
- maxY = Math.max(maxY, cb.y + cb.height);
- }
- }
-
- if (!isFinite(minX) || !isFinite(minY) || maxX <= minX || maxY <= minY) {
- showToast('Selected layers are empty');
- return;
- }
-
- const b = {
- x: Math.max(0, minX),
- y: Math.max(0, minY),
- width: Math.max(1, maxX - minX),
- height: Math.max(1, maxY - minY),
- };
-
- const compositeCanvas = document.createElement('canvas');
- compositeCanvas.width = b.width;
- compositeCanvas.height = b.height;
- const compCtx = get2DContext(compositeCanvas);
-
- const orderedLayers = multiTargetLayers.slice().reverse();
- for (const lyr of orderedLayers) {
- const c = layerCanvasesRef.current.get(lyr.id);
- if (!c) continue;
- const cCtx = get2DContext(c);
- if (!cCtx) continue;
-
- const sCanvas = document.createElement('canvas');
- sCanvas.width = b.width;
- sCanvas.height = b.height;
- const sCtx = get2DContext(sCanvas);
- if (sCtx) {
- sCtx.drawImage(c, -b.x, -b.y);
- layerSourceCanvases.set(lyr.id, sCanvas);
- }
-
- if (compCtx) {
- compCtx.save();
- compCtx.globalAlpha = lyr.opacity;
- compCtx.drawImage(sCanvas, 0, 0);
- compCtx.restore();
- }
-
- const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');
- if (isLayerBg) {
- cCtx.fillStyle = '#ffffff';
- cCtx.fillRect(b.x, b.y, b.width, b.height);
- } else {
- cCtx.clearRect(b.x, b.y, b.width, b.height);
- }
-
- const existingSrc = layerSourceCanvasesRef.current?.get(lyr.id);
- if (existingSrc) {
- const escCtx = get2DContext(existingSrc);
- if (escCtx) {
- if (isLayerBg) {
- escCtx.fillStyle = '#ffffff';
- escCtx.fillRect(b.x, b.y, b.width, b.height);
- } else {
- escCtx.clearRect(b.x, b.y, b.width, b.height);
- }
- }
- }
- const isMono = colorMode === 'monochrome' || lyr.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(lyr.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- updateLayerThumbnail(lyr.id, true);
- }
- documentStore.getActiveTileGrid().notifyChange(true);
-
- const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
- setTransformSession({
- active: true,
- layerId: activeLayerId,
- layerIds: multiTargetLayers.map((l) => l.id),
- layerSourceCanvases,
- layerBeforeImages,
- sourceCanvas: compositeCanvas,
- beforeImageData: layerBeforeImages.get(activeLayerId) || Array.from(layerBeforeImages.values())[0],
- bounds: { x: b.x, y: b.y, width: b.width, height: b.height },
- x: b.x,
- y: b.y,
- width: b.width,
- height: b.height,
- rotation: 0,
- flipH: false,
- flipV: false,
- isSelection: false,
- mode: 'affine',
- perspectiveQuad: quad,
- meshCols: 4,
- meshRows: 4,
- meshPoints: createDefaultMeshPoints(quad, 4, 4),
- });
- setTool('transform');
- return;
- }
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const contentBounds = getCanvasContentBounds(canvas, isBg);
- let b = contentBounds;
- if (!b) {
- if (isBg) {
- b = { x: 0, y: 0, width: canvas.width, height: canvas.height };
- } else {
- showToast('Active layer is empty');
- return;
- }
- }
-
- const sourceCanvas = document.createElement('canvas');
- sourceCanvas.width = b.width;
- sourceCanvas.height = b.height;
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- const sliceData = ctx.getImageData(b.x, b.y, b.width, b.height);
- sCtx.putImageData(sliceData, 0, 0);
- }
-
- if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(b.x, b.y, b.width, b.height);
- } else {
- ctx.clearRect(b.x, b.y, b.width, b.height);
- }
-
- const existingSourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- if (existingSourceCanvas) {
- const escCtx = get2DContext(existingSourceCanvas);
- if (escCtx) {
- if (isBg) {
- escCtx.fillStyle = '#ffffff';
- escCtx.fillRect(b.x, b.y, b.width, b.height);
- } else {
- escCtx.clearRect(b.x, b.y, b.width, b.height);
- }
- }
- }
-
- const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(activeLayerId, true);
-
- const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
- setTransformSession({
- active: true,
- layerId: activeLayerId,
- sourceCanvas,
- beforeImageData,
- bounds: { x: b.x, y: b.y, width: b.width, height: b.height },
- x: b.x,
- y: b.y,
- width: b.width,
- height: b.height,
- rotation: 0,
- flipH: false,
- flipV: false,
- isSelection: false,
- mode: 'affine',
- perspectiveQuad: quad,
- meshCols: 4,
- meshRows: 4,
- meshPoints: createDefaultMeshPoints(quad, 4, 4),
- });
- }
- setTool('transform');
- }, [transformSession, getActiveCanvas, selection, activeLayerId, selectedLayerIds, layers, layerSourceCanvasesRef, updateLayerThumbnail, showToast]);
-
- const handleApplyTransform = useCallback(() => {
- if (!transformSession) return;
-
- if (transformSession.layerIds && transformSession.layerIds.length > 1 && transformSession.layerSourceCanvases) {
- for (const lId of transformSession.layerIds) {
- const c = layerCanvasesRef.current.get(lId);
- const sCanvas = transformSession.layerSourceCanvases.get(lId);
- if (!c || !sCanvas) continue;
- const cCtx = get2DContext(c);
- if (!cCtx) continue;
-
- const drawLayerTransformed = (targetCtx: CanvasRenderingContext2D) => {
- targetCtx.save();
- if (transformSession.mode === 'perspective' && transformSession.perspectiveQuad) {
- renderPerspectiveQuad(targetCtx, sCanvas, transformSession.perspectiveQuad, 24);
- } else if (transformSession.mode === 'mesh' && transformSession.meshPoints) {
- renderMeshWarp(targetCtx, sCanvas, transformSession.meshPoints, 6);
- } else {
- const cx = transformSession.x + transformSession.width / 2;
- const cy = transformSession.y + transformSession.height / 2;
- targetCtx.translate(cx, cy);
- targetCtx.rotate((transformSession.rotation * Math.PI) / 180);
- targetCtx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
- targetCtx.drawImage(
- sCanvas,
- -transformSession.width / 2,
- -transformSession.height / 2,
- transformSession.width,
- transformSession.height
- );
- }
- targetCtx.restore();
- };
-
- drawLayerTransformed(cCtx);
-
- const existingSrc = layerSourceCanvasesRef.current?.get(lId);
- if (existingSrc) {
- const sCtx = get2DContext(existingSrc);
- if (sCtx) drawLayerTransformed(sCtx);
- }
-
- const lyr = layers.find((l) => l.id === lId);
- if (lyr?.toneEnabled && existingSrc) {
- applyScreentone(existingSrc, c, {
- frequency: lyr.toneFrequency ?? 60,
- angle: lyr.toneAngle ?? 45,
- dotShape: lyr.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
-
- const beforeDataForLayer = transformSession.layerBeforeImages?.get(lId);
- const afterDataForLayer = cCtx.getImageData(0, 0, c.width, c.height);
- const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- if (beforeDataForLayer) {
- pushHistoryStep(
- 'transform',
- 'Batch Free Transform',
- beforeDataForLayer,
- afterDataForLayer,
- lId
- );
- }
- updateLayerThumbnail(lId, true);
- }
-
- documentStore.getActiveTileGrid().notifyChange(true);
- setTransformSession(null);
- setTool('brush');
- return;
- }
-
- const canvas = layerCanvasesRef.current.get(transformSession.layerId) || getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const sourceCanvas = layerSourceCanvasesRef.current?.get(transformSession.layerId);
-
- const drawTransformed = (targetCtx: CanvasRenderingContext2D) => {
- targetCtx.save();
- if (transformSession.mode === 'perspective' && transformSession.perspectiveQuad) {
- renderPerspectiveQuad(targetCtx, transformSession.sourceCanvas, transformSession.perspectiveQuad, 24);
- } else if (transformSession.mode === 'mesh' && transformSession.meshPoints) {
- renderMeshWarp(targetCtx, transformSession.sourceCanvas, transformSession.meshPoints, 6);
- } else {
- const cx = transformSession.x + transformSession.width / 2;
- const cy = transformSession.y + transformSession.height / 2;
- targetCtx.translate(cx, cy);
- targetCtx.rotate((transformSession.rotation * Math.PI) / 180);
- targetCtx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
- targetCtx.drawImage(
- transformSession.sourceCanvas,
- -transformSession.width / 2,
- -transformSession.height / 2,
- transformSession.width,
- transformSession.height
- );
- }
- targetCtx.restore();
- };
-
- drawTransformed(ctx);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) drawTransformed(sCtx);
- }
-
- const layer = layers.find((l) => l.id === transformSession.layerId);
- if (layer?.toneEnabled && sourceCanvas) {
- applyScreentone(
- sourceCanvas,
- canvas,
- {
- frequency: layer.toneFrequency ?? 60,
- angle: layer.toneAngle ?? 45,
- dotShape: layer.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- }
- );
- }
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- pushHistoryStep(
- 'transform',
- 'Free Transform',
- transformSession.beforeImageData,
- afterImageData,
- transformSession.layerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
-
- updateLayerThumbnail(transformSession.layerId, true);
- setTransformSession(null);
- setTool('brush');
- }, [
- transformSession,
- colorMode,
- layerCanvasesRef,
- getActiveCanvas,
- layers,
- layerSourceCanvasesRef,
- dimensions.dpi,
- pushHistoryStep,
- updateLayerThumbnail,
- ]);
-
- const handleCancelTransform = useCallback(() => {
- if (!transformSession) return;
-
- if (transformSession.layerBeforeImages && transformSession.layerBeforeImages.size > 0) {
- for (const [lId, beforeData] of transformSession.layerBeforeImages.entries()) {
- const c = layerCanvasesRef.current.get(lId);
- if (c && beforeData) {
- const ctx = get2DContext(c);
- ctx?.putImageData(beforeData, 0, 0);
-
- const lyr = layers.find((l) => l.id === lId);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(lId);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.putImageData(beforeData, 0, 0);
-
- if (lyr?.toneEnabled) {
- applyScreentone(sourceCanvas, c, {
- frequency: lyr.toneFrequency ?? 60,
- angle: lyr.toneAngle ?? 45,
- dotShape: lyr.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- });
- }
- }
- const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
- updateLayerThumbnail(lId, true);
- }
- }
- documentStore.getActiveTileGrid().notifyChange(true);
- setTransformSession(null);
- setTool('brush');
- return;
- }
-
- const canvas = layerCanvasesRef.current.get(transformSession.layerId) || getActiveCanvas();
- if (canvas && transformSession.beforeImageData) {
- const ctx = get2DContext(canvas);
- ctx?.putImageData(transformSession.beforeImageData, 0, 0);
-
- const layer = layers.find((l) => l.id === transformSession.layerId);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(transformSession.layerId);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.putImageData(transformSession.beforeImageData, 0, 0);
-
- if (layer?.toneEnabled) {
- applyScreentone(
- sourceCanvas,
- canvas,
- {
- frequency: layer.toneFrequency ?? 60,
- angle: layer.toneAngle ?? 45,
- dotShape: layer.toneDotShape ?? 'circle',
- dpi: dimensions.dpi ?? 600,
- }
- );
- }
- }
- const isMono = colorMode === 'monochrome' || layer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(transformSession.layerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(transformSession.layerId, true);
- }
- setTransformSession(null);
- setTool('brush');
- }, [
- transformSession,
- colorMode,
- layerCanvasesRef,
- getActiveCanvas,
- layers,
- layerSourceCanvasesRef,
- dimensions.dpi,
- updateLayerThumbnail,
- ]);
-
- const handleConfirmText = useCallback(() => {
- if (!textSession || !textSession.settings.text.trim()) {
- setTextSession(null);
- return;
- }
- const canvas = getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- const renderTextOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- const s = textSession.settings;
- renderMangaTextToCanvas(c, s.text, textSession.x, textSession.y, {
- fontSize: s.fontSize,
- fontFamily: s.fontFamily,
- writingMode: s.writingMode || 'horizontal-tb',
- bold: s.bold,
- italic: s.italic,
- align: s.align,
- color: s.color,
- outline: s.outline,
- outlineColor: s.outlineColor,
- outlineWidth: s.outlineWidth,
- anchorTopLeft: true,
- });
- };
-
- renderTextOn(canvas);
- if (sourceCanvas) renderTextOn(sourceCanvas);
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep(
- 'text',
- 'Manga Text',
- beforeImageData,
- afterImageData,
- activeLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
-
- setTextSession(null);
- }, [textSession, getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
-
- const handleCancelText = useCallback(() => {
- setTextSession(null);
- }, []);
-
- const handleConfirmBalloon = useCallback(() => {
- if (!activeBalloon) return;
- const canvas = getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- const drawOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- renderSpeechBalloon(c, activeBalloon);
- };
-
- drawOn(canvas);
- if (sourceCanvas) drawOn(sourceCanvas);
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep(
- 'frame',
- 'Speech Balloon',
- beforeImageData,
- afterImageData,
- activeLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
-
- setActiveBalloon(null);
- }, [activeBalloon, getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep]);
-
- const handleDeleteBalloon = useCallback(() => {
- setActiveBalloon(null);
- }, []);
-
- const handleApplyMangaEffects = useCallback(
- (type: 'saturated' | 'stream', options: SaturatedLinesOptions | StreamLinesOptions) => {
- const canvas = getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- const renderOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- if (type === 'saturated') {
- renderSaturatedLines(c, canvas.width, canvas.height, options as SaturatedLinesOptions);
- } else {
- renderStreamLines(c, canvas.width, canvas.height, options as StreamLinesOptions);
- }
- };
-
- renderOn(canvas);
- if (sourceCanvas) renderOn(sourceCanvas);
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep('brush', `Manga Effect (${type})`, beforeImageData, afterImageData, activeLayerId);
- documentStore.getActiveTileGrid().notifyChange(true);
- showToast(`Applied manga ${type} lines`);
- },
- [getActiveCanvas, activeLayerId, layerSourceCanvasesRef, updateLayerThumbnail, pushHistoryStep, showToast]
- );
-
- const handleInsert3DRasterLayer = useCallback(
- (layer: LayerItem, canvas: HTMLCanvasElement) => {
- if (layer.type === 'folder') {
- addLayer('folder', layer.parentId, layer.name, layer.id);
- } else {
- pasteLayerFromCanvas(canvas, layer.name, layer.blendMode, layer.opacity, layer.id, layer);
- }
- showToast(`Added 3D layer "${layer.name}".`);
- },
- [addLayer, pasteLayerFromCanvas, showToast]
- );
-
- const handleFillScreentone = useCallback(() => {
- setIsToneModalOpen(true);
- }, []);
-
- const handleConfirmTone = useCallback(
- (settings: SimpleToneSettings) => {
- setIsToneModalOpen(false);
- const { id, canvas } = fillScreentoneSelection(
- selection,
- settings.density,
- settings.frequency,
- settings.angle,
- settings.dotShape,
- settings.densityType
- );
- const ctx = get2DContext(canvas);
- if (ctx) {
- const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- pushHistoryStep(
- 'screentone',
- `Screentone (${settings.density}%)`,
- null,
- afterData,
- id
- );
- }
- showToast(`Created Screentone Layer (${settings.density}%)`);
- },
- [selection, fillScreentoneSelection, pushHistoryStep, showToast]
- );
-
- // Apply previewed Expression Color permanently to layer with Undo history
- const handleApplyExpressionColor = useCallback(
- (layerId: string) => {
- const result = applyExpressionColorOfPreview(layerId);
- if (result && result.beforeImageData && result.afterImageData) {
- pushHistoryStep(
- 'expression-color',
- 'Apply Expression Color',
- result.beforeImageData,
- result.afterImageData,
- layerId
- );
- showToast('Applied expression color to layer');
- }
- },
- [applyExpressionColorOfPreview, pushHistoryStep, showToast]
- );
-
- // Apply Layer Color Tint permanently to layer with Undo history
- const handleApplyLayerColor = useCallback(
- (layerId: string) => {
- const result = applyLayerColorPermanently(layerId);
- if (result && result.beforeImageData && result.afterImageData) {
- pushHistoryStep(
- 'layer-color',
- 'Apply Layer Color Tint',
- result.beforeImageData,
- result.afterImageData,
- layerId
- );
- showToast('Applied tint to layer permanently');
- }
- },
- [applyLayerColorPermanently, pushHistoryStep, showToast]
- );
-
- // Direct conversion of layer to Color, Gray, or Monochrome with Undo history
- const handleConvertLayer = useCallback(
- (
- layerId: string,
- targetMode: ExpressionColor,
- options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
- ) => {
- const result = convertLayer(layerId, targetMode, options);
- if (result && result.beforeImageData && result.afterImageData) {
- pushHistoryStep(
- 'layer-convert',
- `Convert to ${targetMode.toUpperCase()}`,
- result.beforeImageData,
- result.afterImageData,
- layerId
- );
- showToast(`Converted layer to ${targetMode}`);
- }
- },
- [convertLayer, pushHistoryStep, showToast]
- );
-
- const startLiquifyLoop = useCallback(
- (canvas: HTMLCanvasElement, sourceCanvas: HTMLCanvasElement | undefined, isTone: boolean) => {
- if (liquifyRafIdRef.current) cancelAnimationFrame(liquifyRafIdRef.current);
-
- const tick = () => {
- if (!isLiquifyingRef.current || !liquifyLastPointerPosRef.current) {
- liquifyRafIdRef.current = null;
- return;
- }
- const { pt, pressure } = liquifyLastPointerPosRef.current;
- const dirty = applyLiquifyStep({
- canvas,
- sourceCanvas: isTone ? sourceCanvas : undefined,
- cx: pt.x,
- cy: pt.y,
- prevX: pt.x,
- prevY: pt.y,
- settings: liquifySettingsRef.current,
- pressure,
- initialImageData: liquifyInitialImageDataRef.current,
- selectionMask: liquifySelectionMaskRef.current,
- });
-
- if (dirty) {
- if (activeLayer?.toneEnabled && sourceCanvas) {
- const displayCanvas = layerCanvasesRef.current.get(activeLayerId);
- if (displayCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, activeLayer, dimensions.dpi ?? 600, dirty);
- }
- } else {
- const dCtx = get2DContext(canvas);
- if (dCtx && dirty.width > 0 && dirty.height > 0) {
- const subData = dCtx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
- const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().writeImageData(activeLayerId, subData, dirty.x, dirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- }
- documentStore.getActiveTileGrid().notifyChange(true);
- }
-
- liquifyRafIdRef.current = requestAnimationFrame(tick);
- };
-
- liquifyRafIdRef.current = requestAnimationFrame(tick);
- },
- [activeLayer, activeLayerId, colorMode, dimensions.dpi, layerCanvasesRef]
- );
-
- const handlePointerDown = useCallback(
- (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => {
- if (!hasOpenDocument || e.button !== 0) return;
-
- const pt = getCanvasCoords(e);
-
- if (tool === 'pipette') {
- e.preventDefault();
- try {
- (e.target as HTMLElement).setPointerCapture(e.pointerId);
- } catch {}
- isPipetteSamplingRef.current = true;
- handleSampleColor(pt);
- return;
- }
-
- if (tool === 'liquify') {
- e.preventDefault();
- if (!activeLayer || activeLayer.locked || (activeLayer && !isLayerEffectivelyVisible(activeLayer))) return;
- const targetLayerId = activeLayerId;
- const isTone = Boolean(activeLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
- if (!canvas) return;
-
- const ctx = get2DContext(canvas);
- if (!ctx) return;
-
- isLiquifyingRef.current = true;
- prevLiquifyPointRef.current = pt;
- liquifyBeforeImageDataRef.current = ctx.getImageData(0, 0, canvas.width, canvas.height);
- liquifyInitialImageDataRef.current = liquifyBeforeImageDataRef.current;
- liquifySelectionMaskRef.current = createLiquifySelectionMask(selection, canvas.width, canvas.height);
- liquifyDirtyRectRef.current = null;
- liquifyLastPointerPosRef.current = { pt, pressure: e.pressure || 1.0 };
-
- try {
- (e.target as HTMLElement).setPointerCapture(e.pointerId);
- } catch {}
-
- const mode = liquifySettingsRef.current.mode;
- if (mode === 'expand' || mode === 'pinch' || mode === 'twirl-cw' || mode === 'twirl-ccw' || mode === 'reconstruct') {
- const dirty = applyLiquifyStep({
- canvas,
- sourceCanvas: isTone ? sourceCanvas : undefined,
- cx: pt.x,
- cy: pt.y,
- prevX: pt.x,
- prevY: pt.y,
- settings: liquifySettingsRef.current,
- pressure: e.pressure || 1.0,
- initialImageData: liquifyInitialImageDataRef.current,
- selectionMask: liquifySelectionMaskRef.current,
- });
- if (dirty) {
- liquifyDirtyRectRef.current = dirty;
- if (activeLayer?.toneEnabled && sourceCanvas && displayCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, activeLayer, dimensions.dpi ?? 600, dirty);
- } else if (dirty.width > 0 && dirty.height > 0) {
- const subData = ctx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
- const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().writeImageData(targetLayerId, subData, dirty.x, dirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- documentStore.getActiveTileGrid().notifyChange(true);
- }
- startLiquifyLoop(canvas, sourceCanvas, isTone);
- }
- return;
- }
-
- if (tool === 'brush' || tool === 'eraser') {
- if (selection?.floating) {
- handleCommitFloatingSelection();
- }
- handleCanvasDrawingPointerDown(e, coalescedEvents);
- return;
- }
-
- if (tool === 'select-wand') {
- e.preventDefault();
- if (selection?.floating) {
- handleCommitFloatingSelection();
- }
-
- const px = Math.floor(pt.x);
- const py = Math.floor(pt.y);
- if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return;
-
- let sampleCanvas: HTMLCanvasElement | null = null;
- if (wandSettings.referMode === 'all') {
- sampleCanvas = compositeVisibleLayers(layers, layerCanvasesRef.current, dimensions);
- } else if (wandSettings.referMode === 'reference') {
- const refLayer = layers.find((l) => l.isReference && l.visible);
- if (refLayer) {
- sampleCanvas = layerCanvasesRef.current.get(refLayer.id) || null;
- } else {
- sampleCanvas = layerCanvasesRef.current.get(activeLayerId) || getActiveCanvas();
- }
- } else {
- sampleCanvas = layerCanvasesRef.current.get(activeLayerId) || getActiveCanvas();
- }
-
- if (!sampleCanvas) return;
- const sCtx = get2DContext(sampleCanvas);
- if (!sCtx) return;
-
- const w = dimensions.width;
- const h = dimensions.height;
- const sampleImageData = sCtx.getImageData(0, 0, w, h);
- const { mask, bounds } = floodSelectWand(
- sampleImageData,
- w,
- h,
- px,
- py,
- wandSettings
- );
-
- if (!bounds || bounds.width === 0 || bounds.height === 0) {
- setSelection(null);
- return;
- }
-
- const svgPath = maskToSvgPath(mask, w, h);
- setSelection({
- type: 'wand',
- bounds,
- mask,
- maskWidth: w,
- maskHeight: h,
- svgPath,
- });
- return;
- }
-
- if (tool === 'select-pen' || tool === 'select-eraser') {
- e.preventDefault();
- if (selection?.floating) {
- handleCommitFloatingSelection();
- }
-
- const w = dimensions.width;
- const h = dimensions.height;
- let maskCanvas = selectionMaskCanvasRef.current;
- if (!maskCanvas || maskCanvas.width !== w || maskCanvas.height !== h) {
- maskCanvas = document.createElement('canvas');
- maskCanvas.width = w;
- maskCanvas.height = h;
- selectionMaskCanvasRef.current = maskCanvas;
- }
-
- const mCtx = get2DContext(maskCanvas);
- if (!mCtx) return;
-
- mCtx.clearRect(0, 0, w, h);
- if (selection) {
- const currentMask = selectionToMask(selection, w, h);
- const imgData = mCtx.createImageData(w, h);
- for (let i = 0; i < currentMask.length; i++) {
- const val = currentMask[i];
- const idx = i * 4;
- imgData.data[idx] = val;
- imgData.data[idx + 1] = val;
- imgData.data[idx + 2] = val;
- imgData.data[idx + 3] = val > 0 ? 255 : 0;
- }
- mCtx.putImageData(imgData, 0, 0);
- }
-
- const brushSize = brushSettings.size;
- mCtx.save();
- mCtx.lineCap = 'round';
- mCtx.lineJoin = 'round';
- mCtx.lineWidth = brushSize;
- if (tool === 'select-pen') {
- mCtx.globalCompositeOperation = 'source-over';
- mCtx.fillStyle = '#ffffff';
- mCtx.strokeStyle = '#ffffff';
- } else {
- mCtx.globalCompositeOperation = 'destination-out';
- mCtx.fillStyle = '#000000';
- mCtx.strokeStyle = '#000000';
- }
-
- mCtx.beginPath();
- mCtx.arc(pt.x, pt.y, brushSize / 2, 0, Math.PI * 2);
- mCtx.fill();
- mCtx.restore();
-
- selectionPenDrawingRef.current = {
- isDrawing: true,
- lastPt: pt,
- maskCanvas,
- ctx: mCtx,
- };
-
- const mImgData = mCtx.getImageData(0, 0, w, h);
- const newMask = new Uint8Array(w * h);
- for (let i = 0; i < newMask.length; i++) {
- newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;
- }
- const b = maskToBounds(newMask, w, h);
- if (b) {
- const svg = maskToSvgPath(newMask, w, h);
- setSelection({
- type: 'mask',
- bounds: b,
- mask: newMask,
- maskWidth: w,
- maskHeight: h,
- svgPath: svg,
- });
- } else {
- setSelection(null);
- }
- return;
- }
-
- if (tool === 'select-rect' || tool === 'select-lasso') {
- e.preventDefault();
- if (selection && isPointInSelection(pt.x, pt.y, selection)) {
- const canvas = getActiveCanvas();
- if (!canvas) return;
-
- if (!selection.floating) {
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
- const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
- const lifted = liftSelectionToFloating(canvas, selection, sourceCanvas, isBg);
- if (lifted) {
- const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(activeLayerId, true);
- const floatingObj = {
- canvas: lifted.floatingCanvas,
- x: selection.bounds.x,
- y: selection.bounds.y,
- origX: selection.bounds.x,
- origY: selection.bounds.y,
- layerId: activeLayerId,
- beforeImageData: lifted.beforeImageData,
- };
- setSelection({
- ...selection,
- floating: floatingObj,
- });
- selectionDragRef.current = {
- isDragging: true,
- startX: pt.x,
- startY: pt.y,
- origFloatingX: selection.bounds.x,
- origFloatingY: selection.bounds.y,
- origBoundsX: selection.bounds.x,
- origBoundsY: selection.bounds.y,
- };
- }
- } else {
- selectionDragRef.current = {
- isDragging: true,
- startX: pt.x,
- startY: pt.y,
- origFloatingX: selection.floating.x,
- origFloatingY: selection.floating.y,
- origBoundsX: selection.bounds.x,
- origBoundsY: selection.bounds.y,
- };
- }
- return;
- }
-
- if (selection?.floating) {
- handleCommitFloatingSelection();
- }
-
- if (tool === 'select-rect') {
- selectRectStartRef.current = pt;
- setSelection({
- type: 'rect',
- bounds: { x: pt.x, y: pt.y, width: 0, height: 0 },
- });
- } else {
- lassoPointsRef.current = [pt];
- setSelection({
- type: 'lasso',
- bounds: { x: pt.x, y: pt.y, width: 0, height: 0 },
- polygon: [pt],
- });
- }
- return;
- }
-
- if (tool === 'fill') {
- e.preventDefault();
- if (fillSettings.method === 'lasso') {
- lassoFillPointsRef.current = [pt];
- return;
- }
-
- const px = Math.floor(pt.x);
- const py = Math.floor(pt.y);
- if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return;
-
- const canvas = getActiveCanvas();
- if (!canvas || activeLayer?.locked || (activeLayer && !isLayerEffectivelyVisible(activeLayer))) return;
-
- const ctx = get2DContext(canvas);
- if (!ctx) return;
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- let refCanvas: HTMLCanvasElement;
- if (fillSettings.method === 'refer-all') {
- refCanvas = compositeVisibleLayers(layers, layerCanvasesRef.current, dimensions);
- } else if (fillSettings.method === 'refer-reference') {
- refCanvas = compositeReferenceLayers(layers, layerCanvasesRef.current, dimensions);
- } else {
- refCanvas = canvas;
- }
-
- const selMask = selection ? createSelectionMask(selection, canvas.width, canvas.height) : null;
- const fillRes = executeFloodFill(
- canvas,
- refCanvas,
- px,
- py,
- primaryColor,
- fillSettings.tolerance,
- sourceCanvas,
- {
- closeGap: fillSettings.closeGap ?? 0,
- areaScale: fillSettings.areaScale ?? 0,
- antiAlias: fillSettings.antiAlias ?? true,
- selectionMask: selMask,
- }
- );
- if (activeLayer?.toneEnabled && sourceCanvas) {
- applyLayerEffects(sourceCanvas, canvas, activeLayer, dimensions.dpi ?? 600, fillRes.dirtyRect ?? undefined);
- }
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep(
- 'fill',
- 'Bucket Fill',
- beforeImageData,
- afterImageData,
- activeLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- return;
- }
-
- if (tool === 'frame') {
- e.preventDefault();
- frameStartRef.current = pt;
- return;
- }
-
- if (tool === 'text') {
- e.preventDefault();
- setTextSession({
- x: Math.round(pt.x),
- y: Math.round(pt.y),
- settings: { ...textSettings },
- });
- return;
- }
-
- if (tool === 'balloon') {
- e.preventDefault();
- const newBalloon = createDefaultSpeechBalloon(
- Math.round(pt.x - 100),
- Math.round(pt.y - 70),
- 200,
- 140,
- balloonSettings.shape
- );
- newBalloon.strokeWidth = balloonSettings.strokeWidth;
- newBalloon.strokeColor = primaryColor || '#000000';
- newBalloon.fillColor = balloonSettings.fillColor || '#ffffff';
- newBalloon.vertical = balloonSettings.vertical;
- setActiveBalloon(newBalloon);
- return;
- }
-
- if (tool === 'vector-edit') {
- e.preventDefault();
- if (!activeLayer || activeLayer.type !== 'vector' || !activeLayer.vectorStrokes) {
- showToast('Select a Vector Layer to use Correct Line tools');
- return;
- }
- isVectorEditingRef.current = true;
- lastVectorEditPtRef.current = pt;
- vectorEditBeforeStrokesRef.current = JSON.parse(JSON.stringify(activeLayer.vectorStrokes));
- return;
- }
- },
- [
- hasOpenDocument,
- getCanvasCoords,
- tool,
- selection,
- handleCommitFloatingSelection,
- handleCanvasDrawingPointerDown,
- getActiveCanvas,
- layerSourceCanvasesRef,
- activeLayerId,
- updateLayerThumbnail,
- fillSettings,
- dimensions.width,
- dimensions.height,
- activeLayer,
- isLayerEffectivelyVisible,
- layers,
- layerCanvasesRef,
- primaryColor,
- pushHistoryStep,
- textSettings,
- handleSampleColor,
- wandSettings,
- brushSettings.size,
- dimensions,
- ]
- );
-
- const handlePointerMove = useCallback(
- (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[], predictedEvents?: PointerEvent[]) => {
- if (tool === 'pipette') {
- if (isPipetteSamplingRef.current) {
- const pt = getCanvasCoords(e);
- handleSampleColor(pt);
- }
- return;
- }
-
- if (tool === 'brush' || tool === 'eraser') {
- handleCanvasDrawingPointerMove(e, coalescedEvents, predictedEvents);
- return;
- }
-
- if (tool === 'vector-edit') {
- if (!isVectorEditingRef.current || !activeLayer?.vectorStrokes) return;
- const pt = getCanvasCoords(e);
- const lastPt = lastVectorEditPtRef.current || pt;
- const delta = { x: pt.x - lastPt.x, y: pt.y - lastPt.y };
- lastVectorEditPtRef.current = pt;
-
- const radius = vectorEditSettings.radius || 35;
- let updated = false;
-
- const newStrokes = activeLayer.vectorStrokes.map((stroke) => {
- if (stroke.deleted) return stroke;
- if (
- pt.x < stroke.bounds.minX - radius ||
- pt.x > stroke.bounds.maxX + radius ||
- pt.y < stroke.bounds.minY - radius ||
- pt.y > stroke.bounds.maxY + radius
- ) {
- return stroke;
- }
-
- if (vectorEditSettings.mode === 'pinch') {
- if (Math.hypot(delta.x, delta.y) > 0.05) {
- updated = true;
- return pinchVectorStroke(stroke, pt, radius, delta);
- }
- } else if (vectorEditSettings.mode === 'width') {
- updated = true;
- return modifyStrokeWidth(stroke, pt, radius, vectorEditSettings.widthFactor);
- } else if (vectorEditSettings.mode === 'simplify') {
- updated = true;
- return simplifyVectorStroke(stroke, vectorEditSettings.simplifyTolerance);
- }
- return stroke;
- });
-
- if (updated) {
- activeLayer.vectorStrokes = newStrokes;
- const canvas = getActiveCanvas();
- if (canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- renderVectorLayer(ctx, newStrokes);
- const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(activeLayerId, true);
- }
- }
- }
- return;
- }
-
- if (tool === 'liquify') {
- if (!isLiquifyingRef.current) return;
- const pt = getCanvasCoords(e);
- const pressure = e.pressure || 1.0;
- liquifyLastPointerPosRef.current = { pt, pressure };
-
- const targetLayerId = activeLayerId;
- const isTone = Boolean(activeLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
- if (!canvas) return;
-
- const prev = prevLiquifyPointRef.current || pt;
- const dist = Math.hypot(pt.x - prev.x, pt.y - prev.y);
- const stepDist = Math.max(2, (liquifySettingsRef.current.size / 2) * 0.25);
- const numSteps = Math.max(1, Math.ceil(dist / stepDist));
-
- let overallDirty: DirtyRect | null = null;
- for (let i = 1; i <= numSteps; i++) {
- const t = i / numSteps;
- const cx = prev.x + (pt.x - prev.x) * t;
- const cy = prev.y + (pt.y - prev.y) * t;
- const px = prev.x + (pt.x - prev.x) * ((i - 1) / numSteps);
- const py = prev.y + (pt.y - prev.y) * ((i - 1) / numSteps);
-
- const dirty = applyLiquifyStep({
- canvas,
- sourceCanvas: isTone ? sourceCanvas : undefined,
- cx,
- cy,
- prevX: px,
- prevY: py,
- settings: liquifySettingsRef.current,
- pressure,
- initialImageData: liquifyInitialImageDataRef.current,
- selectionMask: liquifySelectionMaskRef.current,
- });
-
- if (dirty) {
- if (!overallDirty) {
- overallDirty = { ...dirty };
- } else {
- const minX = Math.min(overallDirty.x, dirty.x);
- const minY = Math.min(overallDirty.y, dirty.y);
- const maxX = Math.max(overallDirty.x + overallDirty.width, dirty.x + dirty.width);
- const maxY = Math.max(overallDirty.y + overallDirty.height, dirty.y + dirty.height);
- overallDirty = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
- }
- }
- }
-
- prevLiquifyPointRef.current = pt;
-
- if (overallDirty) {
- if (activeLayer?.toneEnabled && sourceCanvas && displayCanvas) {
- applyLayerEffects(sourceCanvas, displayCanvas, activeLayer, dimensions.dpi ?? 600, overallDirty);
- } else if (overallDirty.width > 0 && overallDirty.height > 0) {
- const cCtx = get2DContext(canvas);
- if (cCtx) {
- const subData = cCtx.getImageData(overallDirty.x, overallDirty.y, overallDirty.width, overallDirty.height);
- const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
- documentStore.getActiveTileGrid().writeImageData(targetLayerId, subData, overallDirty.x, overallDirty.y, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- }
- documentStore.getActiveTileGrid().notifyChange(true);
- if (!liquifyDirtyRectRef.current) {
- liquifyDirtyRectRef.current = overallDirty;
- } else {
- const cur = liquifyDirtyRectRef.current;
- const minX = Math.min(cur.x, overallDirty.x);
- const minY = Math.min(cur.y, overallDirty.y);
- const maxX = Math.max(cur.x + cur.width, overallDirty.x + overallDirty.width);
- const maxY = Math.max(cur.y + cur.height, overallDirty.y + overallDirty.height);
- liquifyDirtyRectRef.current = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
- }
- }
- return;
- }
-
- const pt = getCanvasCoords(e);
-
- if ((tool === 'select-pen' || tool === 'select-eraser') && selectionPenDrawingRef.current?.isDrawing) {
- const { ctx: mCtx, lastPt } = selectionPenDrawingRef.current;
- const brushSize = brushSettings.size;
- mCtx.save();
- mCtx.lineCap = 'round';
- mCtx.lineJoin = 'round';
- mCtx.lineWidth = brushSize;
- if (tool === 'select-pen') {
- mCtx.globalCompositeOperation = 'source-over';
- mCtx.strokeStyle = '#ffffff';
- } else {
- mCtx.globalCompositeOperation = 'destination-out';
- mCtx.strokeStyle = '#000000';
- }
-
- mCtx.beginPath();
- mCtx.moveTo(lastPt.x, lastPt.y);
- mCtx.lineTo(pt.x, pt.y);
- mCtx.stroke();
- mCtx.restore();
-
- selectionPenDrawingRef.current.lastPt = pt;
- return;
- }
-
- if (selectionDragRef.current?.isDragging) {
- const dx = pt.x - selectionDragRef.current.startX;
- const dy = pt.y - selectionDragRef.current.startY;
- setSelection((prev) => {
- if (!prev || !prev.floating) return prev;
- const newX = Math.round(selectionDragRef.current!.origFloatingX + dx);
- const newY = Math.round(selectionDragRef.current!.origFloatingY + dy);
- const boundsX = Math.round(selectionDragRef.current!.origBoundsX + dx);
- const boundsY = Math.round(selectionDragRef.current!.origBoundsY + dy);
- let updatedPoly = prev.polygon;
- if (prev.type === 'lasso' && prev.polygon) {
- const shiftX = boundsX - prev.bounds.x;
- const shiftY = boundsY - prev.bounds.y;
- updatedPoly = prev.polygon.map((p) => ({ x: p.x + shiftX, y: p.y + shiftY }));
- }
- return {
- ...prev,
- bounds: { ...prev.bounds, x: boundsX, y: boundsY },
- polygon: updatedPoly,
- floating: {
- ...prev.floating,
- x: newX,
- y: newY,
- },
- };
- });
- return;
- }
-
- if (selectRectStartRef.current) {
- const s = selectRectStartRef.current;
- const minX = Math.floor(Math.min(s.x, pt.x));
- const minY = Math.floor(Math.min(s.y, pt.y));
- const w = Math.ceil(Math.abs(pt.x - s.x));
- const h = Math.ceil(Math.abs(pt.y - s.y));
- setSelection({
- type: 'rect',
- bounds: { x: minX, y: minY, width: w, height: h },
- });
- return;
- }
-
- if (lassoPointsRef.current.length > 0) {
- const pts = lassoPointsRef.current;
- const last = pts[pts.length - 1];
- if (Math.hypot(pt.x - last.x, pt.y - last.y) >= 2) {
- pts.push(pt);
- const b = computePolygonBounds(pts);
- setSelection({
- type: 'lasso',
- bounds: b,
- polygon: [...pts],
- });
- }
- return;
- }
-
- if (tool === 'fill' && fillSettings.method === 'lasso' && lassoFillPointsRef.current.length > 0) {
- lassoFillPointsRef.current.push(pt);
- return;
- }
- },
- [
- tool,
- activeLayer,
- activeLayerId,
- colorMode,
- vectorEditSettings,
- getActiveCanvas,
- updateLayerThumbnail,
- layerSourceCanvasesRef,
- layerCanvasesRef,
- handleCanvasDrawingPointerMove,
- getCanvasCoords,
- fillSettings.method,
- handleSampleColor,
- brushSettings.size,
- dimensions,
- ]
- );
-
- const handlePointerUp = useCallback(
- (e: React.PointerEvent<HTMLElement>) => {
- if (tool === 'pipette') {
- try {
- (e.target as HTMLElement).releasePointerCapture(e.pointerId);
- } catch {}
- if (isPipetteSamplingRef.current) {
- isPipetteSamplingRef.current = false;
- const pt = getCanvasCoords(e);
- handleSampleColor(pt);
- }
- return;
- }
-
- if (tool === 'brush' || tool === 'eraser') {
- handleCanvasDrawingPointerUp(e);
- return;
- }
-
- if (tool === 'liquify') {
- try {
- (e.target as HTMLElement).releasePointerCapture(e.pointerId);
- } catch {}
-
- if (liquifyRafIdRef.current) {
- cancelAnimationFrame(liquifyRafIdRef.current);
- liquifyRafIdRef.current = null;
- }
-
- if (isLiquifyingRef.current) {
- isLiquifyingRef.current = false;
- const targetLayerId = activeLayerId;
- const isTone = Boolean(activeLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId));
- const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
- const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
- const canvas = (isTone && sourceCanvas) ? sourceCanvas : displayCanvas;
-
- if (canvas && liquifyBeforeImageDataRef.current) {
- const ctx = get2DContext(canvas);
- const afterImageData = ctx?.getImageData(0, 0, canvas.width, canvas.height);
- if (afterImageData) {
- const modeLabel = liquifySettingsRef.current.mode.charAt(0).toUpperCase() + liquifySettingsRef.current.mode.slice(1);
- pushHistoryStep(
- 'liquify',
- `Liquify: ${modeLabel}`,
- liquifyBeforeImageDataRef.current,
- afterImageData,
- targetLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- updateLayerThumbnail(targetLayerId, true);
- }
- }
-
- liquifyBeforeImageDataRef.current = null;
- liquifyInitialImageDataRef.current = null;
- liquifySelectionMaskRef.current = null;
- liquifyDirtyRectRef.current = null;
- prevLiquifyPointRef.current = null;
- liquifyLastPointerPosRef.current = null;
- }
- return;
- }
-
- const pt = getCanvasCoords(e);
-
- if ((tool === 'select-pen' || tool === 'select-eraser') && selectionPenDrawingRef.current?.isDrawing) {
- const { ctx: mCtx } = selectionPenDrawingRef.current;
- selectionPenDrawingRef.current = null;
- const w = dimensions.width;
- const h = dimensions.height;
- const mImgData = mCtx.getImageData(0, 0, w, h);
- const newMask = new Uint8Array(w * h);
- for (let i = 0; i < newMask.length; i++) {
- newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;
- }
- const b = maskToBounds(newMask, w, h);
- if (b) {
- const svg = maskToSvgPath(newMask, w, h);
- setSelection({
- type: 'mask',
- bounds: b,
- mask: newMask,
- maskWidth: w,
- maskHeight: h,
- svgPath: svg,
- });
- } else {
- setSelection(null);
- }
- return;
- }
-
- if (selectionDragRef.current?.isDragging) {
- selectionDragRef.current = null;
- return;
- }
-
- if (selectRectStartRef.current) {
- const s = selectRectStartRef.current;
- selectRectStartRef.current = null;
- const minX = Math.floor(Math.min(s.x, pt.x));
- const minY = Math.floor(Math.min(s.y, pt.y));
- const w = Math.ceil(Math.abs(pt.x - s.x));
- const h = Math.ceil(Math.abs(pt.y - s.y));
- if (w < 4 || h < 4) {
- setSelection(null);
- } else {
- setSelection({
- type: 'rect',
- bounds: { x: minX, y: minY, width: w, height: h },
- });
- }
- return;
- }
-
- if (lassoPointsRef.current.length > 0) {
- if (lassoPointsRef.current.length < 3) {
- setSelection(null);
- } else {
- const b = computePolygonBounds(lassoPointsRef.current);
- setSelection({
- type: 'lasso',
- bounds: b,
- polygon: [...lassoPointsRef.current],
- });
- }
- lassoPointsRef.current = [];
- return;
- }
-
- if (tool === 'fill' && fillSettings.method === 'lasso' && lassoFillPointsRef.current.length >= 3) {
- const pts = [...lassoFillPointsRef.current];
- lassoFillPointsRef.current = [];
- const canvas = getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- executeLassoFill(canvas, pts, primaryColor, sourceCanvas);
- if (activeLayer?.toneEnabled && sourceCanvas) {
- applyLayerEffects(sourceCanvas, canvas, activeLayer, dimensions.dpi ?? 600);
- }
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep(
- 'fill',
- 'Lasso Fill',
- beforeImageData,
- afterImageData,
- activeLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- return;
- }
-
- if (tool === 'frame' && frameStartRef.current) {
- const s = frameStartRef.current;
- frameStartRef.current = null;
- const minX = Math.floor(Math.min(s.x, pt.x));
- const minY = Math.floor(Math.min(s.y, pt.y));
- const w = Math.ceil(Math.abs(pt.x - s.x));
- const h = Math.ceil(Math.abs(pt.y - s.y));
-
- if (w >= 4 && h >= 4) {
- const canvas = getActiveCanvas();
- if (!canvas) return;
- const ctx = get2DContext(canvas);
- if (!ctx) return;
- const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
-
- const drawFrameOn = (target: HTMLCanvasElement) => {
- const c = get2DContext(target);
- if (!c) return;
- c.save();
- if (frameSettings.fillBackground) {
- c.fillStyle = frameSettings.fillColor || '#ffffff';
- c.fillRect(minX, minY, w, h);
- }
- c.strokeStyle = primaryColor || '#000000';
- c.lineWidth = frameSettings.thickness;
- c.lineJoin = 'miter';
- c.strokeRect(minX, minY, w, h);
- c.restore();
- };
-
- drawFrameOn(canvas);
- if (sourceCanvas) drawFrameOn(sourceCanvas);
-
- const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
- updateLayerThumbnail(activeLayerId, true);
- pushHistoryStep(
- 'frame',
- 'Frame Border',
- beforeImageData,
- afterImageData,
- activeLayerId
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- }
- return;
- }
-
- if (tool === 'vector-edit' && isVectorEditingRef.current) {
- isVectorEditingRef.current = false;
- if (activeLayer?.vectorStrokes && vectorEditBeforeStrokesRef.current) {
- pushHistoryStep(
- 'brush',
- `Correct Line (${vectorEditSettings.mode})`,
- null,
- null,
- activeLayerId,
- undefined,
- undefined,
- { before: vectorEditBeforeStrokesRef.current, after: [...activeLayer.vectorStrokes] }
- );
- documentStore.getActiveTileGrid().notifyChange(true);
- }
- return;
- }
- },
- [
- tool,
- activeLayer,
- activeLayerId,
- vectorEditSettings,
- layerCanvasesRef,
- handleCanvasDrawingPointerUp,
- getCanvasCoords,
- selection,
- fillSettings.method,
- getActiveCanvas,
- layerSourceCanvasesRef,
- primaryColor,
- updateLayerThumbnail,
- pushHistoryStep,
- frameSettings,
- handleSampleColor,
- dimensions,
- ]
- );
-
- const needsAdaptiveFitRef = useRef<boolean>(true);
- const pendingFitDimsRef = useRef<CanvasDimensions | null>(null);
-
- const handleViewportReady = useCallback(
- (_viewport: HTMLDivElement) => {
- if (needsAdaptiveFitRef.current) {
- if (_viewport.clientWidth <= 0 || _viewport.clientHeight <= 0) {
- return;
- }
- needsAdaptiveFitRef.current = false;
- const targetDims = pendingFitDimsRef.current || dimensions;
- pendingFitDimsRef.current = null;
- resetZoomAndCenter(targetDims);
- }
- },
- [dimensions, resetZoomAndCenter]
- );
-
- // Create New Canvas handler
- const handleCreateNewCanvas = useCallback(
- (options: NewCanvasOptions) => {
- const newDims: CanvasDimensions = {
- width: options.width,
- height: options.height,
- dpi: options.dpi,
- };
- setDimensions(newDims);
- setColorMode(options.colorMode);
- let name = (options.name || 'Untitled').trim();
- if (!/\.[a-zA-Z0-9]+$/.test(name) && !name.endsWith('*')) {
- name = `${name}*`;
- }
- setDocumentName(name);
- setSavedFileInfo(null); // Reset saved file state on new canvas
-
- // Snap brush color if switching to monochrome or grayscale
- if (options.colorMode === 'monochrome') {
- const snapPrimary = enforceColorMode(primaryColor, 'monochrome');
- setPrimaryColor(snapPrimary);
- updateBrushSettings({ color: snapPrimary, hardness: 1.0 });
- } else if (options.colorMode === 'grayscale') {
- const snapPrimary = enforceColorMode(primaryColor, 'grayscale');
- setPrimaryColor(snapPrimary);
- updateBrushSettings({ color: snapPrimary });
- }
-
- const defaultFreq = options.defaultFrequency ?? 60;
- const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
- const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
- newDims,
- options.backgroundColor,
- options.colorMode,
- defaultFreq,
- newDocId
- );
- needsAdaptiveFitRef.current = true;
- pendingFitDimsRef.current = newDims;
- resetZoomAndCenter(newDims);
- resetHistory(newDocId);
-
- // Add to document tabs (empty perspective ruler by default)
- const newDoc: DocumentTab = {
- id: newDocId,
- name,
- dimensions: newDims,
- colorMode: options.colorMode,
- layers: initialLayers,
- activeLayerId: topId,
- perspectiveRuler: null,
- defaultFrequency: defaultFreq,
- };
-
- setPerspectiveRuler(null);
- setDocuments((prev) => [...prev, newDoc]);
- setActiveDocumentId(newDocId);
- setAppView('workspace');
-
- showToast(`Created ${name}`);
- },
- [primaryColor, resetHistory, resetToNewCanvas, resetZoomAndCenter, showToast, updateBrushSettings]
- );
-
- // Initialize a default white canvas on launch so >80% of the viewport is immediately dedicated to drawing
- const hasAutoCreatedInitialDocRef = useRef(false);
- useEffect(() => {
- if (hasAutoCreatedInitialDocRef.current || documents.length > 0) return;
- hasAutoCreatedInitialDocRef.current = true;
- const initDims: CanvasDimensions = {
- width: appSettings.defaultWidth || 1920,
- height: appSettings.defaultHeight || 1080,
- dpi: appSettings.defaultDpi || 300,
- };
- const initColorMode = appSettings.defaultColorMode || 'color';
- const initBg = appSettings.defaultBgColor || '#ffffff';
- const initName = 'Untitled*';
- const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
- setDimensions(initDims);
- setColorMode(initColorMode);
- setDocumentName(initName);
- const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
- initDims,
- initBg,
- initColorMode,
- 60,
- newDocId
- );
- needsAdaptiveFitRef.current = true;
- pendingFitDimsRef.current = initDims;
- resetZoomAndCenter(initDims);
- resetHistory(newDocId);
- setDocuments([
- {
- id: newDocId,
- name: initName,
- dimensions: initDims,
- colorMode: initColorMode,
- layers: initialLayers,
- activeLayerId: topId,
- perspectiveRuler: null,
- defaultFrequency: 60,
- },
- ]);
- setActiveDocumentId(newDocId);
- setAppView('workspace');
- }, [
- appSettings.defaultBgColor,
- appSettings.defaultColorMode,
- appSettings.defaultDpi,
- appSettings.defaultHeight,
- appSettings.defaultWidth,
- documents.length,
- resetHistory,
- resetToNewCanvas,
- resetZoomAndCenter,
- ]);
-
- // Copy selected layer
- const handleCopySelectedLayer = useCallback(() => {
- if (!activeLayer) return;
- const copied = copyLayer(activeLayerId);
- if (copied) {
- showToast(`Copied layer "${copied.name}"`);
- }
- }, [activeLayer, activeLayerId, copyLayer, showToast]);
-
- // Paste layer
- const handlePasteSelectedLayer = useCallback(async () => {
- const res = await pasteLayer();
- if (res.success && res.layerName) {
- showToast(`Pasted layer "${res.layerName}"`);
- } else {
- showToast('Clipboard is empty');
- }
- }, [pasteLayer, showToast]);
-
- // Delete selected layer
- const handleDeleteSelectedLayer = useCallback(() => {
- const rasterCount = layers.filter((l) => l.type === 'raster').length;
- if (rasterCount <= 1) {
- showToast('Cannot delete the only raster layer');
- return;
- }
- const layerName = activeLayer?.name || 'layer';
- deleteLayer(activeLayerId);
- showToast(`Deleted layer "${layerName}"`);
- }, [activeLayer, activeLayerId, deleteLayer, layers, showToast]);
-
- // Paste from file
- const handleTriggerPasteFromFile = useCallback(() => {
- pasteFileInputRef.current?.click();
- }, []);
-
- const handlePasteFileInputChange = useCallback(
- async (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (file) {
- try {
- const layerName = await pasteLayerFromFile(file);
- showToast(`Pasted "${layerName}" from file`);
- } catch (err: unknown) {
- console.error('Failed to paste from file:', err);
- const errMsg = err instanceof Error ? err.message : String(err);
- alert(`Failed to paste image from file: ${errMsg}`);
- } finally {
- if (pasteFileInputRef.current) {
- pasteFileInputRef.current.value = '';
- }
- }
- }
- },
- [pasteLayerFromFile, showToast]
- );
-
- // Import 3D Model File (.glb, .gltf, .obj)
- const handleTriggerImport3DFile = useCallback(() => {
- import3DFileInputRef.current?.click();
- }, []);
-
- const handleImport3DFileInputChange = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (file) {
- setInitial3DFile(file);
- setIs3DLayerOpen(true);
- showToast(`Importing 3D model "${file.name}" into local ghost layer...`);
- if (import3DFileInputRef.current) {
- import3DFileInputRef.current.value = '';
- }
- }
- },
- [showToast]
- );
-
- // Resize canvas
- const handleResizeCanvas = useCallback(
- (options: ResizeCanvasOptions) => {
- const newDims: CanvasDimensions = {
- width: options.width,
- height: options.height,
- dpi: options.dpi || dimensions.dpi,
- };
-
- resizeCanvas(newDims, options);
- setDimensions(newDims);
- pendingFitDimsRef.current = newDims;
- needsAdaptiveFitRef.current = true;
- resetZoomAndCenter(newDims);
- resetHistory();
- showToast(`Canvas resized to ${newDims.width} × ${newDims.height} px`);
- },
- [dimensions.dpi, resetHistory, resetZoomAndCenter, resizeCanvas, showToast]
- );
-
- // Settings update handler
- const handleUpdateSettings = useCallback((newSettings: AppSettings) => {
- setAppSettings(newSettings);
- saveAppSettings(newSettings);
- documentStore.setTileBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
- setBrushSettings((prev) => ({
- ...prev,
- stabilization: newSettings.defaultStabilization,
- usePressure: newSettings.usePressureByDefault,
- smoothing: newSettings.smoothingEnabled,
- }));
- }, []);
-
- // Synchronize initial tile memory budget (shared across all open documents)
- useEffect(() => {
- documentStore.setTileBudgetMb(appSettings.tileMemoryBudgetMb || 1024);
- }, [appSettings.tileMemoryBudgetMb]);
-
- // File loading handler
- const handleProcessFile = useCallback(
- async (file: File) => {
- if (file.name.toLowerCase().endsWith('.sut')) {
- try {
- setIsLoadingFile(true);
- setLoadingStatus(`Importing CSP Brush: ${file.name}...`);
- const buffer = await file.arrayBuffer();
- const parsedBrush = await parseSutFile(buffer, file.name);
- const existing = (await loadCustomBrushes()).filter(
- (b) => b.name.toLowerCase() === parsedBrush.name.toLowerCase() || b.id === parsedBrush.id
- );
- for (const old of existing) {
- await deleteCustomBrush(old.id).catch(() => {});
- }
- await saveCustomBrush(parsedBrush);
- setTool('brush');
- const fullSettings = await prepareBrushSettingsForCsp(parsedBrush);
- updateBrushSettings(fullSettings);
- showToast(`Imported CSP brush "${parsedBrush.name}" successfully!`);
- } catch (err: any) {
- showToast(err.message || 'Failed to import .sut brush.');
- } finally {
- setIsLoadingFile(false);
- setLoadingStatus('');
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- }
- return;
- }
-
- try {
- setIsLoadingFile(true);
- setLoadingStatus(`Loading ${file.name}...`);
-
- const doc = await openFile(file);
- const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
- setDimensions(doc.dimensions);
- setColorMode(doc.colorMode);
- setDocumentName(doc.name);
- setSavedFileInfo(null); // Reset handle on new import
-
- loadDocument(doc, newDocId);
- needsAdaptiveFitRef.current = true;
- pendingFitDimsRef.current = doc.dimensions;
- resetZoomAndCenter(doc.dimensions);
- resetHistory(newDocId);
-
- // Create document tab (pixel storage lives in DocumentStore's isolated SparseTileGrid)
- const newDoc: DocumentTab = {
- id: newDocId,
- name: doc.name,
- dimensions: doc.dimensions,
- colorMode: doc.colorMode,
- layers: doc.layers,
- activeLayerId: doc.layers[0]?.id || 'layer-1',
- perspectiveRuler: null,
- };
-
- setPerspectiveRuler(null);
- setDocuments((prev) => [...prev, newDoc]);
- setActiveDocumentId(newDocId);
-
- // Track in recent documents
- saveRecentDocument({
- id: newDocId,
- title: file.name,
- path: (file as any).path || `C:\\Users\\Artist\\Documents\\InkStudio\\${file.name}`,
- size: file.size || 1048576,
- coverUrl: doc.layers[0]?.thumbnailUrl,
- isStarred: false,
- fileType: file.name.slice(file.name.lastIndexOf('.')),
- isSaved: true,
- }).catch(console.warn);
-
- showToast(`Opened ${file.name}`);
- } catch (err: unknown) {
- console.error('Failed to open file:', err);
- const errMsg = err instanceof Error ? err.message : String(err);
- alert(`Could not open "${file.name}":\n${errMsg || 'Unsupported or corrupted file.'}`);
- } finally {
- setIsLoadingFile(false);
- setLoadingStatus('');
- if (fileInputRef.current) {
- fileInputRef.current.value = '';
- }
- }
- },
- [loadDocument, resetHistory, resetZoomAndCenter, showToast]
- );
-
- // Keep active document tab's metadata in sync (without copying full HTMLCanvasElements into state)
- useEffect(() => {
- if (!activeDocumentId) return;
- setDocuments((prev) => {
- const curr = prev.find((d) => d.id === activeDocumentId);
- if (!curr) return prev;
- if (curr.layers === layers && curr.activeLayerId === activeLayerId) {
- return prev;
- }
- return prev.map((d) =>
- d.id === activeDocumentId
- ? {
- ...d,
- layers,
- activeLayerId,
- }
- : d
- );
- });
- }, [layers, activeLayerId, activeDocumentId]);
-
- // Tab selection, close, and rename handlers — O(1) SparseTileGrid switch without clearing or re-slicing
- const handleSelectDocument = useCallback(
- (id: string) => {
- if (id === activeDocumentId) {
- setAppView('workspace');
- return;
- }
- const doc = documents.find((d) => d.id === id);
- if (!doc) return;
- setAppView('workspace');
- setDimensions(doc.dimensions);
- setColorMode(doc.colorMode);
- setDocumentName(doc.name);
- if (doc.defaultFrequency) {
- setDefaultToneFrequency(doc.defaultFrequency);
- }
- if (doc.savedFileInfo && doc.savedFileInfo.extension) {
- setSavedFileInfo({
- name: doc.savedFileInfo.name,
- handle: doc.savedFileInfo.handle,
- extension: doc.savedFileInfo.extension,
- });
- } else {
- setSavedFileInfo(null);
- }
- switchDocumentSession(id, doc.layers || [], doc.activeLayerId || '', doc.dimensions);
- setActiveDocumentId(id);
- setPerspectiveRuler(doc.perspectiveRuler ?? null);
- needsAdaptiveFitRef.current = true;
- pendingFitDimsRef.current = doc.dimensions;
- resetZoomAndCenter(doc.dimensions);
- },
- [activeDocumentId, documents, resetZoomAndCenter, setDefaultToneFrequency, switchDocumentSession]
- );
-
- const handleCloseDocument = useCallback(
- (id: string) => {
- setDocuments((prev) => {
- const next = prev.filter((d) => d.id !== id);
- if (id === activeDocumentId) {
- if (next.length > 0) {
- const nextActive = next[next.length - 1];
- setDimensions(nextActive.dimensions);
- setColorMode(nextActive.colorMode);
- setDocumentName(nextActive.name);
- setPerspectiveRuler(nextActive.perspectiveRuler ?? null);
- if (nextActive.savedFileInfo && nextActive.savedFileInfo.extension) {
- setSavedFileInfo({
- name: nextActive.savedFileInfo.name,
- handle: nextActive.savedFileInfo.handle,
- extension: nextActive.savedFileInfo.extension,
- });
- } else {
- setSavedFileInfo(null);
- }
- if (nextActive.layers && nextActive.layers.length > 0) {
- switchDocumentSession(
- nextActive.id,
- nextActive.layers,
- nextActive.activeLayerId || '',
- nextActive.dimensions
- );
- setActiveDocumentId(nextActive.id);
- needsAdaptiveFitRef.current = true;
- pendingFitDimsRef.current = nextActive.dimensions;
- resetZoomAndCenter(nextActive.dimensions);
- } else {
- setActiveDocumentId(nextActive.id);
- clearDocument();
- }
- } else {
- documentStore.setActiveDocument(null);
- setActiveDocumentId(null);
- setDocumentName('');
- setSavedFileInfo(null);
- clearDocument();
- setPerspectiveRuler(null);
- setAppView('home');
- }
- }
- return next;
- });
- if (id) {
- // Dispose isolated SparseTileGrid, scratch disk tiles, Undo cache, and temporary buffers
- documentStore.closeSession(id).catch(console.warn);
- recoveryService.closeSession(id).catch(console.warn);
- }
- },
- [activeDocumentId, clearDocument, resetZoomAndCenter, switchDocumentSession]
- );
-
- // Fault-Tolerant Crash Recovery Restore Handler
- const handleRestoreCrashedSession = useCallback(
- async (session: CrashedSessionInfo) => {
- try {
- const replayData = await recoveryService.loadSessionData(session.session_id);
- const restoredSession = documentStore.getOrCreateSession(session.session_id);
- const { manifest, replayedStrokesCount, replayedMutationsCount } =
- recoveryService.replaySessionData(replayData, restoredSession.tileGrid);
-
- const restoredDims: CanvasDimensions = {
- width: manifest.width,
- height: manifest.height,
- dpi: manifest.dpi,
- };
-
- // Bind document directly to the replayed SparseTileGrid (zero full-canvas reconstruction!)
- loadDocument(
- {
- name: manifest.documentName,
- dimensions: restoredDims,
- colorMode: manifest.colorMode,
- layers: manifest.layers,
- },
- session.session_id,
- true
- );
- if (manifest.activeLayerId) {
- setActiveLayerId(manifest.activeLayerId);
- }
-
- // Set dimensions & color mode
- setDimensions(restoredDims);
- setColorMode(manifest.colorMode);
- setDocumentName(manifest.documentName);
-
- const restoredDoc: DocumentTab = {
- id: session.session_id,
- name: manifest.documentName,
- dimensions: restoredDims,
- colorMode: manifest.colorMode,
- layers: manifest.layers,
- activeLayerId: manifest.activeLayerId || manifest.layers[0]?.id || '',
- };
-
- setDocuments((prev) => {
- const filtered = prev.filter((d) => d.id !== session.session_id);
- return [restoredDoc, ...filtered];
- });
- setActiveDocumentId(session.session_id);
- setAppView('workspace');
-
- needsAdaptiveFitRef.current = true;
- pendingFitDimsRef.current = restoredDims;
- resetZoomAndCenter(restoredDims);
- resetHistory(session.session_id);
-
- // Push undo history entry
- pushHistoryStep(
- 'initial',
- 'Session restored from crash',
- null,
- null,
- manifest.activeLayerId || manifest.layers[0]?.id || ''
- );
-
- // Invalidate GPU textures & trigger compositor
- restoredSession.tileGrid.notifyChange(true);
-
- setIsRecoveryModalOpen(false);
- setCrashedSessions((prev) => prev.filter((s) => s.session_id !== session.session_id));
- showToast(
- `Restored "${manifest.documentName}" (${replayedStrokesCount} strokes, ${replayedMutationsCount} mutations recovered)`
- );
- } catch (err: any) {
- console.error('[Recovery] Restore error:', err);
- alert('Failed to restore crashed session: ' + err.message);
- }
- },
- [loadDocument, resetHistory, resetZoomAndCenter, showToast, pushHistoryStep, setActiveLayerId]
- );
-
- const handleDiscardCrashedSession = useCallback(
- async (session: CrashedSessionInfo) => {
- try {
- await recoveryService.discardCrashedSession(session.session_id);
- setCrashedSessions((prev) => {
- const next = prev.filter((s) => s.session_id !== session.session_id);
- if (next.length === 0) {
- setIsRecoveryModalOpen(false);
- }
- return next;
- });
- showToast('Crashed session discarded');
- } catch (err: any) {
- console.warn('[Recovery] Discard error:', err);
- }
- },
- [showToast]
- );
-
- const handleRenameDocument = useCallback(
- (id: string, newName: string) => {
- setDocuments((prev) =>
- prev.map((d) => (d.id === id ? { ...d, name: newName } : d))
- );
- if (id === activeDocumentId) {
- setDocumentName(newName);
- }
- },
- [activeDocumentId]
- );
-
- const handleTriggerOpenFile = useCallback(() => {
- fileInputRef.current?.click();
- }, []);
-
- const handleFileInputChange = useCallback(
- (e: React.ChangeEvent<HTMLInputElement>) => {
- const file = e.target.files?.[0];
- if (file) {
- handleProcessFile(file);
- }
- },
- [handleProcessFile]
- );
-
- // 1. Save (Ctrl+S) - Prompts if not saved yet; otherwise saves directly
- const handleSave = useCallback(async () => {
- const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
- const docData: SaveDocumentData = {
- name: cleanNameForSave,
- dimensions,
- colorMode,
- layers,
- layerCanvasesMap: layerCanvasesRef.current,
- tileGrid: documentStore.getActiveTileGrid(),
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- tabId: activeDocumentId || undefined,
- };
-
- // If haven't saved the file yet, prompt to select a path and file extension
- if (!savedFileInfo?.handle) {
- try {
- const info = await promptSaveAs(docData, savedFileInfo?.extension || '.sora');
- setSavedFileInfo(info);
- // info.name includes the extension (e.g. art.sora or Untitled.sora)
- setDocumentName(info.name);
- setDocuments((prev) =>
- prev.map((d) => (d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info } : d))
- );
- saveRecentDocument({
- id: activeDocumentId || `doc-${Date.now()}`,
- title: info.name,
- path: `InkStudio\\${info.name}`,
- size: 1572864,
- coverUrl: layers[0]?.thumbnailUrl,
- isStarred: false,
- fileType: info.extension,
- isSaved: true,
- }).catch(console.warn);
- showToast(`Saved to ${info.name}`);
- } catch (err: any) {
- if (err.message !== 'Save canceled') {
- alert('Failed to save file: ' + err.message);
- }
- }
- } else {
- // File has already been saved before: directly write without prompting!
- try {
- await saveToExistingHandle(docData, savedFileInfo);
- setDocumentName(savedFileInfo.name);
- setDocuments((prev) =>
- prev.map((d) => (d.id === activeDocumentId ? { ...d, name: savedFileInfo.name } : d))
- );
- saveRecentDocument({
- id: activeDocumentId || `doc-${Date.now()}`,
- title: savedFileInfo.name,
- path: `InkStudio\\${savedFileInfo.name}`,
- size: 1572864,
- coverUrl: layers[0]?.thumbnailUrl,
- isStarred: false,
- fileType: savedFileInfo.extension,
- isSaved: true,
- }).catch(console.warn);
- showToast(`Saved to ${savedFileInfo.name}`);
- } catch (err: any) {
- console.warn('Direct handle save failed, prompting with Save As:', err);
- try {
- const info = await promptSaveAs(docData, savedFileInfo.extension || '.sora');
- setSavedFileInfo(info);
- setDocumentName(info.name);
- setDocuments((prev) =>
- prev.map((d) => (d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info } : d))
- );
- saveRecentDocument({
- id: activeDocumentId || `doc-${Date.now()}`,
- title: info.name,
- path: `InkStudio\\${info.name}`,
- size: 1572864,
- coverUrl: layers[0]?.thumbnailUrl,
- isStarred: false,
- fileType: info.extension,
- isSaved: true,
- }).catch(console.warn);
- showToast(`Saved to ${info.name}`);
- } catch (e: any) {
- if (e.message !== 'Save canceled') {
- alert('Failed to save file: ' + e.message);
- }
- }
- }
- }
- }, [
- activeDocumentId,
- colorMode,
- dimensions,
- documentName,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- layerCanvasesRef,
- layers,
- savedFileInfo,
- showToast,
- ]);
-
- // 2. Save As (Ctrl+Shift+S) - Always prompts to select path and extension
- const handleSaveAs = useCallback(async () => {
- const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
- const docData: SaveDocumentData = {
- name: cleanNameForSave,
- dimensions,
- colorMode,
- layers,
- layerCanvasesMap: layerCanvasesRef.current,
- tileGrid: documentStore.getActiveTileGrid(),
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- tabId: activeDocumentId || undefined,
- };
-
- try {
- const defaultExt = savedFileInfo?.extension || '.sora';
- const info = await promptSaveAs(docData, defaultExt);
- setSavedFileInfo(info);
- setDocumentName(info.name);
- setDocuments((prev) =>
- prev.map((d) => (d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info } : d))
- );
- saveRecentDocument({
- id: activeDocumentId || `doc-${Date.now()}`,
- title: info.name,
- path: `InkStudio\\${info.name}`,
- size: 1572864,
- coverUrl: layers[0]?.thumbnailUrl,
- isStarred: false,
- fileType: info.extension,
- isSaved: true,
- }).catch(console.warn);
- showToast(`Saved as ${info.name}`);
- } catch (err: any) {
- if (err.message !== 'Save canceled') {
- alert('Failed to save file: ' + err.message);
- }
- }
- }, [
- activeDocumentId,
- colorMode,
- dimensions,
- documentName,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- layerCanvasesRef,
- layers,
- savedFileInfo,
- showToast,
- ]);
-
- // 3. Export Image - Export as .png; always prompts for a download path within a folder
- const handleExportImage = useCallback(async () => {
- const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
- const docData: SaveDocumentData = {
- name: cleanNameForSave,
- dimensions,
- colorMode,
- layers,
- layerCanvasesMap: layerCanvasesRef.current,
- tileGrid: documentStore.getActiveTileGrid(),
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- };
-
- try {
- const exportedName = await promptExportPngImage(docData, cleanNameForSave);
- showToast(`Exported image to ${exportedName}`);
- } catch (err: any) {
- if (err.message !== 'Export canceled') {
- alert('Failed to export image: ' + err.message);
- }
- }
- }, [
- colorMode,
- dimensions,
- documentName,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- layerCanvasesRef,
- layers,
- showToast,
- ]);
-
- const isAnyModalOpen =
- isRecoveryModalOpen ||
- isNewCanvasModalOpen ||
- isResizeCanvasModalOpen ||
- isSettingsModalOpen ||
- tonalModalState.isOpen ||
- adjustmentModalState.isOpen ||
- layerStylesModalState.isOpen ||
- isToneModalOpen ||
- isHostModalOpen ||
- isMangaEffectsModalOpen ||
- isWebtoonExportModalOpen ||
- isLoadingFile;
-
- const isAnyModalOpenRef = useRef<boolean>(isAnyModalOpen);
- isAnyModalOpenRef.current = isAnyModalOpen;
-
- const tempToolHoldRef = useRef<{
- code: string;
- prevTool: ToolType;
- targetTool: ToolType;
- downAt: number;
- usedWhileHeld: boolean;
- } | null>(null);
-
- const handleResetDefaultColors = useCallback(() => {
- setIsTransparentColor(false);
- const prim = enforceColorMode('#000000', colorMode);
- const sec = enforceColorMode('#ffffff', colorMode);
- setPrimaryColor(prim);
- setSecondaryColor(sec);
- updateBrushSettings({ color: prim, secondaryColor: sec, isTransparentInk: false });
- }, [colorMode, updateBrushSettings]);
-
- // Global Keyboard Shortcuts (Layout-Independent e.code + CSP Hold-and-Release Temporary Tools)
- useEffect(() => {
- const isEditableTarget = (target: EventTarget | null): boolean => {
- if (!(target instanceof HTMLElement)) return false;
- const tag = target.tagName;
- return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
- };
-
- const CODE_TO_TOOL: Record<string, ToolType> = {
- KeyB: 'brush',
- KeyE: 'eraser',
- KeyI: 'pipette',
- KeyJ: 'liquify',
- KeyM: 'select-rect',
- KeyL: 'select-lasso',
- KeyW: 'select-wand',
- KeyG: 'fill',
- KeyT: 'text',
- KeyF: 'frame',
- KeyO: 'balloon',
- KeyY: 'vector-edit',
- };
-
- const handleKeyDown = (e: KeyboardEvent) => {
- if (isAnyModalOpenRef.current || isEditableTarget(e.target)) {
- return;
- }
-
- const key = e.key.toLowerCase();
- const code = e.code;
-
- // Ctrl / Cmd shortcuts
- if (e.ctrlKey || e.metaKey) {
- // Toggle Animation Timeline: Ctrl+Alt+A
- if (e.altKey && !e.shiftKey && (code === 'KeyA' || key === 'a')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- if (activeAnimationTimeline) {
- handleUpdateAnimationTimeline(null);
- } else {
- handleUpdateAnimationTimeline(createDefaultAnimationTimeline(layers));
- }
- return;
- }
-
- // Soft Proof Colors: Ctrl+Alt+Y
- if (e.altKey && !e.shiftKey && (code === 'KeyY' || key === 'y')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- toggleSoftProof();
- return;
- }
-
- // Ignore other Ctrl+Alt combinations (reserved for Ctrl+Alt+Drag resize & Ctrl+Alt+0 reset rotation)
- if (e.altKey) return;
-
- // Undo: Ctrl+Z (Cmd+Z)
- if (!e.shiftKey && (code === 'KeyZ' || key === 'z')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleUndo();
- return;
- }
- // Redo: Ctrl+Shift+Z or Ctrl+Y
- if (
- (e.shiftKey && (code === 'KeyZ' || key === 'z')) ||
- (!e.shiftKey && (code === 'KeyY' || key === 'y'))
- ) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- redo();
- return;
- }
- // Gamut Warning: Ctrl+Shift+Y
- if (e.shiftKey && (code === 'KeyY' || key === 'y')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- toggleGamutWarning();
- return;
- }
- // New Raster Layer: Ctrl+Shift+N
- if (e.shiftKey && (code === 'KeyN' || key === 'n')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleAddLayer('raster');
- return;
- }
- // New Canvas: Ctrl+N
- if (!e.shiftKey && (code === 'KeyN' || key === 'n')) {
- e.preventDefault();
- setIsNewCanvasModalOpen(true);
- return;
- }
- // Open File: Ctrl+O
- if (!e.shiftKey && (code === 'KeyO' || key === 'o')) {
- e.preventDefault();
- handleTriggerOpenFile();
- return;
- }
- // Save As: Ctrl+Shift+S
- if (e.shiftKey && (code === 'KeyS' || key === 's')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleSaveAs();
- return;
- }
- // Save: Ctrl+S
- if (!e.shiftKey && (code === 'KeyS' || key === 's')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleSave();
- return;
- }
- // Duplicate Layer: Ctrl+J
- if (!e.shiftKey && (code === 'KeyJ' || key === 'j')) {
- if (!hasOpenDocument || !activeLayer) return;
- e.preventDefault();
- duplicateLayer(activeLayerId);
- return;
- }
- // Copy Layer: Ctrl+C (only when no text is selected)
- if (!e.shiftKey && (code === 'KeyC' || key === 'c')) {
- if (!hasOpenDocument) return;
- const textSel = window.getSelection()?.toString();
- if (!textSel || textSel.length === 0) {
- e.preventDefault();
- handleCopySelectedLayer();
- return;
- }
- }
- // Paste Layer: Ctrl+V
- if (!e.shiftKey && (code === 'KeyV' || key === 'v')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handlePasteSelectedLayer();
- return;
- }
- // Group Layers: Ctrl+G
- if (!e.shiftKey && (code === 'KeyG' || key === 'g')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleGroupSelectedLayers();
- return;
- }
- // Transform: Ctrl+T
- if (!e.shiftKey && (code === 'KeyT' || key === 't')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleStartTransform();
- return;
- }
- // Select All: Ctrl+A
- if (!e.shiftKey && (code === 'KeyA' || key === 'a')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleSelectAll();
- return;
- }
- // Deselect: Ctrl+D
- if (!e.shiftKey && (code === 'KeyD' || key === 'd')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleDeselect();
- return;
- }
- // Invert Selection: Ctrl+Shift+I
- if (e.shiftKey && (code === 'KeyI' || key === 'i')) {
- if (!hasOpenDocument) return;
- e.preventDefault();
- handleInvertSelection();
- return;
- }
- // Reverse Gradient (Invert Colors): Ctrl+I
- if (!e.shiftKey && (code === 'KeyI' || key === 'i')) {
- if (!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster') return;
- e.preventDefault();
- handleApplyReverseGradient();
- return;
- }
- // Hue / Saturation / Luminosity: Ctrl+U
- if (!e.shiftKey && (code === 'KeyU' || key === 'u')) {
- if (!hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster') return;
- e.preventDefault();
- handleOpenTonalModal('hue-saturation');
- return;
- }
- // Settings: Ctrl+,
- if (!e.shiftKey && (code === 'Comma' || key === ',' || key === '<')) {
- e.preventDefault();
- setIsSettingsModalOpen(true);
- return;
- }
- // Toggle Perspective Ruler: Ctrl+Shift+R
- if (e.shiftKey && (code === 'KeyR' || key === 'r')) {
- e.preventDefault();
- updatePerspectiveRuler((prev) => {
- if (!prev) {
- const next = createDefaultPerspectiveRuler('2-point', dimensions);
- showToast('2-Point Perspective Ruler added to canvas');
- return next;
- }
- const next = { ...prev, enabled: !prev.enabled };
- showToast(next.enabled ? 'Perspective Ruler: Shown' : 'Perspective Ruler: Hidden');
- return next;
- });
- return;
- }
- // Toggle Perspective Snapping: Ctrl+Shift+P
- if (e.shiftKey && (code === 'KeyP' || key === 'p')) {
- e.preventDefault();
- updatePerspectiveRuler((prev) => {
- if (!prev) return null;
- const next = { ...prev, snapEnabled: !prev.snapEnabled };
- showToast(next.snapEnabled ? 'Perspective Snapping: ON' : 'Perspective Snapping: OFF');
- return next;
- });
- return;
- }
- return;
- }
-
- // Alt-only shortcuts: Alt+C -> Add Animation Cel
- if (e.altKey && !e.ctrlKey && !e.metaKey) {
- if (!e.shiftKey && (code === 'KeyC' || key === 'c')) {
- if (!hasOpenDocument || !activeAnimationTimeline) return;
- e.preventDefault();
- // Revert temporary Alt pipette if it activated on Alt down
- if (isAltActiveRef.current && previousToolBeforeAltRef.current !== null) {
- setTool(previousToolBeforeAltRef.current);
- previousToolBeforeAltRef.current = null;
- isAltActiveRef.current = false;
- }
- handleAddAnimationCel(activeAnimationTimeline.currentFrame);
- }
- return;
- }
-
- // Tab / Shift+Tab: Toggle UI Panels (CSP workspace hide)
- if (code === 'Tab' && !textSession) {
- e.preventDefault();
- if (e.shiftKey) {
- setIsLeftPanelHidden((prev) => !prev);
- } else {
- const hideBoth = !(isLeftPanelHidden && isRightSidebarHidden);
- setIsLeftPanelHidden(hideBoth);
- setIsRightSidebarHidden(hideBoth);
- }
- return;
- }
-
- // Brush Size Stepper: [ and ] (BracketLeft / BracketRight, supports key-repeat)
- if (!e.shiftKey && (code === 'BracketLeft' || code === 'BracketRight')) {
- e.preventDefault();
- const dir: -1 | 1 = code === 'BracketLeft' ? -1 : 1;
- if (toolRef.current === 'liquify') {
- const nextSize = Math.max(4, Math.min(500, Math.round(stepBrushSizePreset(liquifySettings.size, dir))));
- handleUpdateLiquifySettings({ size: nextSize });
- } else {
- const nextSize = stepBrushSizePreset(brushSettings.size, dir);
- updateBrushSettings({ size: nextSize });
- }
- return;
- }
-
- // Non-destructive View Flip shortcuts: Shift+H (Horizontal), Shift+V (Vertical)
- if (e.shiftKey && !isSpaceDown) {
- if (code === 'KeyH' || key === 'h') {
- if (!hasOpenDocument || e.repeat) return;
- e.preventDefault();
- toggleFlipHorizontal();
- return;
- }
- if (code === 'KeyV' || key === 'v') {
- if (!hasOpenDocument || e.repeat) return;
- e.preventDefault();
- toggleFlipVertical();
- return;
- }
- }
-
- // Single-key tool & color shortcuts (no modifiers)
- if (!e.shiftKey) {
- const mappedTool = CODE_TO_TOOL[code];
- if (mappedTool) {
- if (e.repeat) return;
- const prev = toolRef.current;
- if (prev !== mappedTool) {
- tempToolHoldRef.current = {
- code,
- prevTool: prev,
- targetTool: mappedTool,
- downAt: performance.now(),
- usedWhileHeld: false,
- };
- handleSelectTool(mappedTool);
- }
- return;
- }
-
- if (code === 'KeyX' || key === 'x') {
- if (!e.repeat) handleSwapColors();
- return;
- }
- if (code === 'KeyD' || key === 'd') {
- if (!e.repeat) handleResetDefaultColors();
- return;
- }
- if (code === 'KeyC' || key === 'c') {
- if (!e.repeat) toggleTransparentColor();
- return;
- }
- }
-
- if (key === 'delete' || key === 'backspace') {
- if (!hasOpenDocument) return;
- e.preventDefault();
- if (selection) {
- handleClearSelection();
- } else {
- handleDeleteSelectedLayer();
- }
- } else if (key === 'escape') {
- if (transformSession?.active) {
- e.preventDefault();
- handleCancelTransform();
- } else if (textSession) {
- e.preventDefault();
- handleCancelText();
- } else if (selection) {
- e.preventDefault();
- handleDeselect();
- }
- } else if (key === 'enter') {
- if (transformSession?.active) {
- e.preventDefault();
- handleApplyTransform();
- }
- }
- };
-
- const handleKeyUp = (e: KeyboardEvent) => {
- const hold = tempToolHoldRef.current;
- if (hold && e.code === hold.code) {
- const heldMs = performance.now() - hold.downAt;
- tempToolHoldRef.current = null;
- if ((heldMs >= 220 || hold.usedWhileHeld) && toolRef.current === hold.targetTool) {
- handleSelectTool(hold.prevTool);
- }
- }
- };
-
- const handlePointerDownMarkUsed = () => {
- if (tempToolHoldRef.current) {
- tempToolHoldRef.current.usedWhileHeld = true;
- }
- };
-
- const handleWindowBlur = () => {
- tempToolHoldRef.current = null;
- };
-
- window.addEventListener('keydown', handleKeyDown);
- window.addEventListener('keyup', handleKeyUp);
- window.addEventListener('pointerdown', handlePointerDownMarkUsed, true);
- window.addEventListener('blur', handleWindowBlur);
- return () => {
- window.removeEventListener('keydown', handleKeyDown);
- window.removeEventListener('keyup', handleKeyUp);
- window.removeEventListener('pointerdown', handlePointerDownMarkUsed, true);
- window.removeEventListener('blur', handleWindowBlur);
- };
- }, [
- activeAnimationTimeline,
- activeLayer,
- activeLayerId,
- brushSettings.size,
- dimensions,
- duplicateLayer,
- handleAddAnimationCel,
- handleAddLayer,
- handleApplyReverseGradient,
- handleApplyTransform,
- handleCancelText,
- handleCancelTransform,
- handleClearSelection,
- handleCopySelectedLayer,
- handleDeleteSelectedLayer,
- handleDeselect,
- handleGroupSelectedLayers,
- handleInvertSelection,
- handleOpenTonalModal,
- handlePasteSelectedLayer,
- handleResetDefaultColors,
- handleSave,
- handleSaveAs,
- handleSelectAll,
- handleSelectTool,
- handleStartTransform,
- handleSwapColors,
- handleTriggerOpenFile,
- handleUndo,
- handleUpdateAnimationTimeline,
- handleUpdateLiquifySettings,
- hasOpenDocument,
- isLeftPanelHidden,
- isRightSidebarHidden,
- layers,
- liquifySettings.size,
- redo,
- selection,
- showToast,
- textSession,
- toggleGamutWarning,
- toggleSoftProof,
- toggleTransparentColor,
- transformSession,
- updateBrushSettings,
- updatePerspectiveRuler,
- ]);
-
- // Pipette tool: hold Alt to activate, release Alt to switch back to previous tool
- useEffect(() => {
- const handleKeyDown = (e: KeyboardEvent) => {
- const target = e.target as HTMLElement | null;
- if (
- isAnyModalOpenRef.current ||
- (target && (['INPUT', 'TEXTAREA', 'SELECT'].includes(target.tagName) || target.isContentEditable))
- ) {
- return;
- }
-
- if (e.key === 'Alt') {
- if (
- !e.ctrlKey &&
- !e.metaKey &&
- !isDrawingRef.current &&
- !selectionPenDrawingRef.current?.isDrawing
- ) {
- e.preventDefault();
- if (!isAltActiveRef.current && !e.repeat) {
- isAltActiveRef.current = true;
- if (toolRef.current !== 'pipette') {
- previousToolBeforeAltRef.current = toolRef.current;
- setTool('pipette');
- }
- }
- }
- return;
- }
-
- // If user presses Ctrl or Space while Alt is active (Ctrl+Alt resize or Alt+Space play), revert pipette
- if (((e.ctrlKey || e.metaKey) || e.code === 'Space') && isAltActiveRef.current) {
- if (previousToolBeforeAltRef.current !== null) {
- setTool(previousToolBeforeAltRef.current);
- previousToolBeforeAltRef.current = null;
- }
- isAltActiveRef.current = false;
- isPipetteSamplingRef.current = false;
- }
- };
-
- const handleKeyUp = (e: KeyboardEvent) => {
- if (e.key === 'Alt' || (!e.altKey && isAltActiveRef.current)) {
- if (isAltActiveRef.current) {
- e.preventDefault();
- isAltActiveRef.current = false;
- }
- isPipetteSamplingRef.current = false;
- if (previousToolBeforeAltRef.current !== null) {
- setTool(previousToolBeforeAltRef.current);
- previousToolBeforeAltRef.current = null;
- }
- }
- };
-
- const handleBlur = () => {
- isAltActiveRef.current = false;
- isPipetteSamplingRef.current = false;
- if (previousToolBeforeAltRef.current !== null) {
- setTool(previousToolBeforeAltRef.current);
- previousToolBeforeAltRef.current = null;
- }
- };
-
- window.addEventListener('keydown', handleKeyDown);
- window.addEventListener('keyup', handleKeyUp);
- window.addEventListener('blur', handleBlur);
- return () => {
- window.removeEventListener('keydown', handleKeyDown);
- window.removeEventListener('keyup', handleKeyUp);
- window.removeEventListener('blur', handleBlur);
- };
- }, [isDrawingRef]);
-
- // Drag and drop onto application window
- useEffect(() => {
- const handleDragOver = (e: DragEvent) => {
- e.preventDefault();
- };
-
- const handleDrop = async (e: DragEvent) => {
- e.preventDefault();
- if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
- const file = e.dataTransfer.files[0];
- if (file.name.toLowerCase().endsWith('.sut')) {
- try {
- setIsLoadingFile(true);
- setLoadingStatus(`Importing CSP Brush: ${file.name}...`);
- const buffer = await file.arrayBuffer();
- const parsedBrush = await parseSutFile(buffer, file.name);
- const existing = (await loadCustomBrushes()).filter(
- (b) => b.name.toLowerCase() === parsedBrush.name.toLowerCase() || b.id === parsedBrush.id
- );
- for (const old of existing) {
- await deleteCustomBrush(old.id).catch(() => {});
- }
- await saveCustomBrush(parsedBrush);
- setTool('brush');
- const fullSettings = await prepareBrushSettingsForCsp(parsedBrush);
- updateBrushSettings(fullSettings);
- showToast(`Imported CSP brush "${parsedBrush.name}" successfully!`);
- } catch (err: any) {
- console.error('Failed to import CSP brush:', err);
- showToast(err.message || 'Failed to import .sut brush.');
- } finally {
- setIsLoadingFile(false);
- }
- return;
- }
- handleProcessFile(file);
- }
- };
-
- window.addEventListener('dragover', handleDragOver);
- window.addEventListener('drop', handleDrop);
- return () => {
- window.removeEventListener('dragover', handleDragOver);
- window.removeEventListener('drop', handleDrop);
- };
- }, [handleProcessFile, showToast, updateBrushSettings]);
-
- // Application Menu Bar Sections (Memoized to prevent 240Hz navigation re-allocations)
- const menuSections: MenuSection[] = useMemo(() => [
- {
- id: 'file',
- label: 'File',
- items: [
- // Category 1: Creation & Opening
- {
- id: 'file-new',
- label: 'New...',
- shortcut: 'Ctrl+N',
- icon: <FilePlus className="w-3.5 h-3.5 text-sky-400" />,
- onClick: () => setIsNewCanvasModalOpen(true),
- },
- {
- id: 'file-open',
- label: 'Open...',
- shortcut: 'Ctrl+O',
- icon: <FolderOpen className="w-3.5 h-3.5 text-amber-400" />,
- onClick: handleTriggerOpenFile,
- },
- {
- id: 'file-import-sut',
- label: 'Import CSP Brush (.sut)...',
- icon: <FolderDown className="w-3.5 h-3.5 text-cyan-400" />,
- onClick: () => {
- const input = document.createElement('input');
- input.type = 'file';
- input.accept = '.sut';
- input.onchange = async () => {
- const file = input.files?.[0];
- if (file) {
- try {
- setIsLoadingFile(true);
- setLoadingStatus(`Importing CSP Brush: ${file.name}...`);
- const buffer = await file.arrayBuffer();
- const parsedBrush = await parseSutFile(buffer, file.name);
- const existing = (await loadCustomBrushes()).filter(
- (b) => b.name.toLowerCase() === parsedBrush.name.toLowerCase() || b.id === parsedBrush.id
- );
- for (const old of existing) {
- await deleteCustomBrush(old.id).catch(() => {});
- }
- await saveCustomBrush(parsedBrush);
- setTool('brush');
- const fullSettings = await prepareBrushSettingsForCsp(parsedBrush);
- updateBrushSettings(fullSettings);
- showToast(`Imported CSP brush "${parsedBrush.name}" successfully!`);
- } catch (err: any) {
- showToast(err.message || 'Failed to import .sut brush.');
- } finally {
- setIsLoadingFile(false);
- }
- }
- };
- input.click();
- },
- },
- {
- id: 'file-import-3d',
- label: 'Import 3D Model (.glb, .obj)...',
- icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
- disabled: !hasOpenDocument,
- onClick: handleTriggerImport3DFile,
- },
- {
- id: 'file-div-1',
- label: '',
- divider: true,
- },
- // Category 2: Saving & Exporting
- {
- id: 'file-save',
- label: 'Save',
- shortcut: 'Ctrl+S',
- icon: <Save className="w-3.5 h-3.5 text-blue-400" />,
- disabled: !hasOpenDocument,
- onClick: handleSave,
- },
- {
- id: 'file-save-as',
- label: 'Save As...',
- shortcut: 'Ctrl+Shift+S',
- icon: <Save className="w-3.5 h-3.5 text-indigo-400" />,
- disabled: !hasOpenDocument,
- onClick: handleSaveAs,
- },
- {
- id: 'file-export-image',
- label: 'Export Image...',
- icon: <Download className="w-3.5 h-3.5 text-emerald-400" />,
- disabled: !hasOpenDocument,
- onClick: handleExportImage,
- },
- {
- id: 'file-export-webtoon',
- label: 'Export Webtoon Chapter Slices (.zip)...',
- icon: <Archive className="w-3.5 h-3.5 text-cyan-400" />,
- disabled: !hasOpenDocument,
- onClick: () => setIsWebtoonExportModalOpen(true),
- },
- {
- id: 'file-div-2',
- label: '',
- divider: true,
- },
- // Category 3: Canvas Actions
- {
- id: 'file-clear',
- label: 'Clear Canvas',
- icon: <Trash2 className="w-3.5 h-3.5 text-rose-400" />,
- danger: true,
- disabled: !hasOpenDocument,
- onClick: clearCanvas,
- },
- ],
- },
- {
- id: 'edit',
- label: 'Edit',
- items: [
- {
- id: 'edit-undo',
- label: 'Undo',
- shortcut: 'Ctrl+Z',
- icon: <Undo2 className="w-3.5 h-3.5" />,
- disabled: !hasOpenDocument || !canUndo,
- onClick: handleUndo,
- },
- {
- id: 'edit-redo',
- label: 'Redo',
- shortcut: 'Ctrl+Y',
- icon: <Redo2 className="w-3.5 h-3.5" />,
- disabled: !hasOpenDocument || !canRedo,
- onClick: redo,
- },
- {
- id: 'edit-div-1',
- label: '',
- divider: true,
- },
- {
- id: 'edit-copy',
- label: 'Copy',
- shortcut: 'Ctrl+C',
- icon: <Copy className="w-3.5 h-3.5 text-sky-400" />,
- disabled: !hasOpenDocument || !activeLayer,
- onClick: handleCopySelectedLayer,
- },
- {
- id: 'edit-paste',
- label: 'Paste',
- shortcut: 'Ctrl+V',
- icon: <ClipboardPaste className="w-3.5 h-3.5 text-amber-400" />,
- disabled: !hasOpenDocument,
- onClick: handlePasteSelectedLayer,
- },
- {
- id: 'edit-paste-file',
- label: 'Paste from file...',
- icon: <ImagePlus className="w-3.5 h-3.5 text-emerald-400" />,
- disabled: !hasOpenDocument,
- onClick: handleTriggerPasteFromFile,
- },
- {
- id: 'edit-import-3d',
- label: 'Import 3D File (.glb, .obj)...',
- icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
- disabled: !hasOpenDocument,
- onClick: handleTriggerImport3DFile,
- },
- {
- id: 'edit-delete',
- label: 'Delete',
- shortcut: 'Del',
- icon: <Trash2 className="w-3.5 h-3.5 text-rose-400" />,
- danger: true,
- disabled: !hasOpenDocument || layers.filter((l) => l.type === 'raster').length <= 1,
- onClick: handleDeleteSelectedLayer,
- },
- {
- id: 'edit-clear-layer',
- label: 'Clear Active Layer',
- disabled: !hasOpenDocument || !activeLayer,
- onClick: handleClearActiveLayer,
- },
- {
- id: 'edit-transform',
- label: 'Free Transform',
- shortcut: 'Ctrl+T',
- icon: <Scaling className="w-3.5 h-3.5 text-cyan-400" />,
- disabled: !hasOpenDocument,
- onClick: handleStartTransform,
- },
- {
- id: 'edit-deselect',
- label: 'Deselect',
- shortcut: 'Ctrl+D',
- disabled: !hasOpenDocument || !selection,
- onClick: handleDeselect,
- },
- {
- id: 'edit-fill-sel',
- label: 'Fill Selection',
- icon: <PaintBucket className="w-3.5 h-3.5 text-amber-400" />,
- disabled: !hasOpenDocument || !selection,
- onClick: handleFillSelectionColor,
- },
- {
- id: 'edit-tonal-correction',
- label: 'Tonal Correction',
- icon: <SlidersHorizontal className="w-3.5 h-3.5 text-violet-400" />,
- disabled: !hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
- submenu: [
- {
- id: 'edit-tonal-brightness-contrast',
- label: 'Brightness/Contrast...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
- onClick: () => handleOpenTonalModal('brightness-contrast'),
- },
- {
- id: 'edit-tonal-hue-saturation',
- label: 'Hue/Saturation/Luminosity...',
- shortcut: 'Ctrl+U',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
- onClick: () => handleOpenTonalModal('hue-saturation'),
- },
- {
- id: 'edit-tonal-posterization',
- label: 'Posterization...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
- onClick: () => handleOpenTonalModal('posterization'),
- },
- {
- id: 'edit-tonal-reverse-gradient',
- label: 'Reverse Gradient',
- shortcut: 'Ctrl+I',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
- onClick: handleApplyReverseGradient,
- },
- {
- id: 'edit-tonal-level-correction',
- label: 'Level Correction...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
- onClick: () => handleOpenTonalModal('level-correction'),
- },
- {
- id: 'edit-tonal-binarization',
- label: 'Binarization...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
- onClick: () => handleOpenTonalModal('binarization'),
- },
- ],
- },
- {
- id: 'edit-div-2',
- label: '',
- divider: true,
- },
- {
- id: 'edit-resize-canvas',
- label: 'Resize Canvas...',
- icon: <Scaling className="w-3.5 h-3.5 text-indigo-400" />,
- disabled: !hasOpenDocument,
- onClick: () => setIsResizeCanvasModalOpen(true),
- },
- {
- id: 'edit-div-3',
- label: '',
- divider: true,
- },
- {
- id: 'edit-settings',
- label: 'Settings...',
- shortcut: 'Ctrl+,',
- icon: <Settings className="w-3.5 h-3.5 text-slate-300" />,
- onClick: () => setIsSettingsModalOpen(true),
- },
- ],
- },
- {
- id: 'select',
- label: 'Select',
- items: [
- {
- id: 'select-all',
- label: 'Select All',
- shortcut: 'Ctrl+A',
- icon: <BoxSelect className="w-3.5 h-3.5 text-sky-400" />,
- disabled: !hasOpenDocument,
- onClick: handleSelectAll,
- },
- {
- id: 'select-deselect',
- label: 'Deselect',
- shortcut: 'Ctrl+D',
- icon: <X className="w-3.5 h-3.5 text-rose-400" />,
- disabled: !hasOpenDocument || !selection,
- onClick: handleDeselect,
- },
- {
- id: 'select-invert',
- label: 'Invert Selection',
- shortcut: 'Ctrl+Shift+I',
- icon: <RotateCcw className="w-3.5 h-3.5 text-amber-400" />,
- disabled: !hasOpenDocument,
- onClick: handleInvertSelection,
- },
- {
- id: 'select-div-1',
- label: '',
- divider: true,
- },
- {
- id: 'select-expand',
- label: 'Expand (+5px)...',
- icon: <Maximize2 className="w-3.5 h-3.5 text-indigo-400" />,
- disabled: !hasOpenDocument || !selection,
- onClick: () => handleExpandSelection(5),
- },
- {
- id: 'select-contract',
- label: 'Contract (-5px)...',
- icon: <Minimize2 className="w-3.5 h-3.5 text-emerald-400" />,
- disabled: !hasOpenDocument || !selection,
- onClick: () => handleContractSelection(5),
- },
- {
- id: 'select-feather',
- label: 'Feather (5px)...',
- icon: <Feather className="w-3.5 h-3.5 text-purple-400" />,
- disabled: !hasOpenDocument || !selection,
- onClick: () => handleFeatherSelection(5),
- },
- {
- id: 'select-div-2',
- label: '',
- divider: true,
- },
- {
- id: 'select-transform',
- label: 'Transform Selection',
- shortcut: 'Ctrl+T',
- icon: <Scaling className="w-3.5 h-3.5 text-cyan-400" />,
- disabled: !hasOpenDocument || !selection,
- onClick: handleStartTransform,
- },
- ],
- },
- {
- id: 'layer',
- label: 'Layer',
- items: [
- {
- id: 'layer-new-raster',
- label: 'New Raster Layer',
- shortcut: 'Ctrl+Shift+N',
- icon: <Plus className="w-3.5 h-3.5" />,
- disabled: !hasOpenDocument,
- onClick: () => handleAddLayer('raster'),
- },
- {
- id: 'layer-new-folder',
- label: 'New Folder',
- disabled: !hasOpenDocument,
- onClick: () => handleAddLayer('folder'),
- },
- {
- id: 'layer-new-3d',
- label: 'New 3D Reference Layer...',
- icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
- disabled: !hasOpenDocument,
- onClick: () => setIs3DLayerOpen(true),
- },
- {
- id: 'layer-new-adjustment',
- label: 'New Adjustment Layer',
- disabled: !hasOpenDocument,
- submenu: [
- {
- id: 'layer-adj-curves',
- label: 'Tone Curves...',
- onClick: () => handleOpenAdjustmentModal(undefined, 'curves'),
- },
- {
- id: 'layer-adj-gradient-map',
- label: 'Gradient Map...',
- onClick: () => handleOpenAdjustmentModal(undefined, 'gradient-map'),
- },
- {
- id: 'layer-adj-levels',
- label: 'Levels...',
- onClick: () => handleOpenAdjustmentModal(undefined, 'levels'),
- },
- {
- id: 'layer-adj-color-balance',
- label: 'Color Balance...',
- onClick: () => handleOpenAdjustmentModal(undefined, 'color-balance'),
- },
- ],
- },
- {
- id: 'layer-mask-submenu',
- label: 'Layer Mask',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.type === 'folder',
- submenu: [
- {
- id: 'layer-mask-add',
- label: activeLayer?.maskCanvas ? 'Mask Already Present' : 'Add Layer Mask (Reveal All)',
- disabled: Boolean(activeLayer?.maskCanvas),
- onClick: () => addLayerMask(activeLayerId),
- },
- {
- id: 'layer-mask-delete',
- label: 'Delete Layer Mask',
- danger: true,
- disabled: !activeLayer?.maskCanvas,
- onClick: () => removeLayerMask(activeLayerId),
- },
- {
- id: 'layer-mask-toggle',
- label: activeLayer?.maskEnabled === false ? 'Enable Layer Mask' : 'Disable Layer Mask',
- disabled: !activeLayer?.maskCanvas,
- onClick: () => toggleLayerMask(activeLayerId),
- },
- {
- id: 'layer-mask-link',
- label: activeLayer?.maskLinked === false ? 'Link Mask to Layer' : 'Unlink Mask from Layer',
- disabled: !activeLayer?.maskCanvas,
- onClick: () => toggleMaskLinked(activeLayerId),
- },
- ],
- },
- {
- id: 'layer-duplicate',
- label: 'Duplicate Layer',
- shortcut: 'Ctrl+J',
- disabled: !hasOpenDocument || !activeLayer,
- onClick: () => duplicateLayer(activeLayerId),
- },
- {
- id: 'layer-div-effects',
- label: '',
- divider: true,
- },
- {
- id: 'layer-styles',
- label: 'Layer Style (Stroke, Shadow, Glow)...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.type === 'folder' || activeLayer.type === 'adjustment',
- onClick: () => handleOpenLayerStylesModal(activeLayerId),
- },
- {
- id: 'layer-toggle-tint',
- label: activeLayer?.layerColorEnabled ? 'Disable Layer Color (Tint)' : 'Enable Layer Color (Tint)',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.type === 'folder',
- onClick: () => toggleLayerColor(activeLayerId),
- },
- {
- id: 'layer-convert-submenu',
- label: 'Convert Expression Color',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.type === 'folder',
- submenu: [
- {
- id: 'layer-convert-color',
- label: 'Color (RGB)',
- onClick: () => handleConvertLayer(activeLayerId, 'color'),
- },
- {
- id: 'layer-convert-gray',
- label: 'Gray (Grayscale)',
- onClick: () => handleConvertLayer(activeLayerId, 'gray'),
- },
- {
- id: 'layer-convert-monochrome',
- label: 'Monochrome (1-bit B&W)',
- onClick: () => handleConvertLayer(activeLayerId, 'monochrome'),
- },
- ],
- },
- {
- id: 'layer-div-ruler',
- label: '',
- divider: true,
- },
- {
- id: 'layer-perspective-ruler',
- label: 'Perspective Ruler',
- disabled: !hasOpenDocument,
- submenu: !perspectiveRuler
- ? [
- {
- id: 'layer-add-ruler-1p',
- label: 'Add 1-Point Perspective Ruler',
- onClick: () => {
- const next = createDefaultPerspectiveRuler('1-point', dimensions);
- updatePerspectiveRuler(next);
- showToast('1-Point Perspective Ruler added to canvas');
- },
- },
- {
- id: 'layer-add-ruler-2p',
- label: 'Add 2-Point Perspective Ruler',
- onClick: () => {
- const next = createDefaultPerspectiveRuler('2-point', dimensions);
- updatePerspectiveRuler(next);
- showToast('2-Point Perspective Ruler added to canvas');
- },
- },
- {
- id: 'layer-add-ruler-3p-birds',
- label: "Add 3-Point Perspective Ruler (Bird's-Eye)",
- onClick: () => {
- const next = createDefaultPerspectiveRuler('3-point', dimensions);
- updatePerspectiveRuler(next);
- showToast("3-Point Perspective Ruler (Bird's-Eye) added to canvas");
- },
- },
- {
- id: 'layer-add-ruler-3p-worms',
- label: "Add 3-Point Perspective Ruler (Worm's-Eye)",
- onClick: () => {
- const base = createDefaultPerspectiveRuler('3-point', dimensions);
- const next = applyWormsEyePreset(base, dimensions);
- updatePerspectiveRuler(next);
- showToast("3-Point Perspective Ruler (Worm's-Eye) added to canvas");
- },
- },
- ]
- : [
- {
- id: 'layer-remove-ruler',
- label: 'Remove Perspective Ruler from Canvas',
- danger: true,
- onClick: () => {
- updatePerspectiveRuler(null);
- showToast('Removed perspective ruler from canvas');
- },
- },
- ],
- },
- {
- id: 'layer-div-delete',
- label: '',
- divider: true,
- },
- {
- id: 'layer-delete',
- label: 'Delete Layer',
- danger: true,
- disabled: !hasOpenDocument || layers.length <= 1,
- onClick: () => deleteLayer(activeLayerId),
- },
- ],
- },
- {
- id: 'filter',
- label: 'Filter',
- items: [
- {
- id: 'filter-gaussian-blur',
- label: 'Gaussian Blur...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
- onClick: () => {
- const r = window.prompt('Gaussian Blur Radius (px, 1-100):', '5');
- if (r !== null) {
- const radius = Math.max(1, Math.min(100, parseFloat(r) || 5));
- handleApplyFilter('gaussian-blur', { radius });
- }
- },
- },
- {
- id: 'filter-motion-blur',
- label: 'Motion Blur...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
- onClick: () => {
- const d = window.prompt('Motion Blur Distance (px, 1-100):', '15');
- const a = d !== null ? window.prompt('Motion Blur Angle (degrees, 0-360):', '0') : null;
- if (d !== null && a !== null) {
- const distance = Math.max(1, Math.min(100, parseFloat(d) || 15));
- const angle = Math.max(0, Math.min(360, parseFloat(a) || 0));
- handleApplyFilter('motion-blur', { distance, angle });
- }
- },
- },
- {
- id: 'filter-unsharp-mask',
- label: 'Unsharp Mask...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
- onClick: () => {
- const r = window.prompt('Unsharp Mask Radius (px, 0.5-20):', '2');
- const a = r !== null ? window.prompt('Amount factor (0.1-5.0):', '1.5') : null;
- if (r !== null && a !== null) {
- const radius = Math.max(0.5, Math.min(20, parseFloat(r) || 2));
- const amount = Math.max(0.1, Math.min(5, parseFloat(a) || 1.5));
- handleApplyFilter('unsharp-mask', { radius, amount, threshold: 0 });
- }
- },
- },
- {
- id: 'filter-film-grain',
- label: 'Film Grain...',
- disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
- onClick: () => {
- const i = window.prompt('Film Grain Intensity (% 1-100):', '25');
- if (i !== null) {
- const intensity = Math.max(1, Math.min(100, parseFloat(i) || 25));
- handleApplyFilter('film-grain', { intensity, size: 1, monochromatic: true });
- }
- },
- },
- ],
- },
- {
- id: 'ruler',
- label: 'Ruler',
- items: [
- ...(!perspectiveRuler
- ? [
- {
- id: 'ruler-add-1p',
- label: 'Add 1-Point Perspective Ruler',
- icon: <Compass className="w-3.5 h-3.5 text-cyan-400" />,
- disabled: !hasOpenDocument,
- onClick: () => {
- const next = createDefaultPerspectiveRuler('1-point', dimensions);
- updatePerspectiveRuler(next);
- showToast('1-Point Perspective Ruler added to canvas');
- },
- },
- {
- id: 'ruler-add-2p',
- label: 'Add 2-Point Perspective Ruler',
- icon: <Compass className="w-3.5 h-3.5 text-purple-400" />,
- disabled: !hasOpenDocument,
- onClick: () => {
- const next = createDefaultPerspectiveRuler('2-point', dimensions);
- updatePerspectiveRuler(next);
- showToast('2-Point Perspective Ruler added to canvas');
- },
- },
- {
- id: 'ruler-add-3p-birds',
- label: "Add 3-Point Perspective Ruler (Bird's-Eye)",
- icon: <Compass className="w-3.5 h-3.5 text-emerald-400" />,
- disabled: !hasOpenDocument,
- onClick: () => {
- const next = createDefaultPerspectiveRuler('3-point', dimensions);
- updatePerspectiveRuler(next);
- showToast("3-Point Perspective Ruler (Bird's-Eye) added to canvas");
- },
- },
- {
- id: 'ruler-add-3p-worms',
- label: "Add 3-Point Perspective Ruler (Worm's-Eye)",
- icon: <Compass className="w-3.5 h-3.5 text-amber-400" />,
- disabled: !hasOpenDocument,
- onClick: () => {
- const base = createDefaultPerspectiveRuler('3-point', dimensions);
- const next = applyWormsEyePreset(base, dimensions);
- updatePerspectiveRuler(next);
- showToast("3-Point Perspective Ruler (Worm's-Eye) added to canvas");
- },
- },
- ]
- : [
- {
- id: 'ruler-toggle-visibility',
- label: perspectiveRuler.enabled
- ? 'Hide Perspective Ruler'
- : 'Show Perspective Ruler',
- shortcut: 'Ctrl+Shift+R',
- icon: perspectiveRuler.enabled ? (
- <EyeOff className="w-3.5 h-3.5 text-sky-400" />
- ) : (
- <Eye className="w-3.5 h-3.5 text-sky-400" />
- ),
- disabled: !hasOpenDocument,
- onClick: () =>
- updatePerspectiveRuler((prev) =>
- prev ? { ...prev, enabled: !prev.enabled } : null
- ),
- },
- {
- id: 'ruler-toggle-snap',
- label: perspectiveRuler.snapEnabled
- ? 'Disable Snapping'
- : 'Enable Snapping',
- shortcut: 'Ctrl+Shift+P',
- icon: <Magnet className="w-3.5 h-3.5 text-emerald-400" />,
- disabled: !hasOpenDocument,
- onClick: () =>
- updatePerspectiveRuler((prev) =>
- prev ? { ...prev, snapEnabled: !prev.snapEnabled } : null
- ),
- },
- {
- id: 'ruler-toggle-lock',
- label: perspectiveRuler.locked
- ? 'Unlock Handles (Edit Mode)'
- : 'Lock Handles (Freeze for Inking)',
- icon: perspectiveRuler.locked ? (
- <Unlock className="w-3.5 h-3.5 text-amber-400" />
- ) : (
- <Lock className="w-3.5 h-3.5 text-amber-400" />
- ),
- disabled: !hasOpenDocument,
- onClick: () =>
- updatePerspectiveRuler((prev) =>
- prev ? { ...prev, locked: !prev.locked } : null
- ),
- },
- {
- id: 'ruler-line-count',
- label: `Guide Rays (${perspectiveRuler.guideRayCount || 6} lines)`,
- disabled: !hasOpenDocument,
- submenu: [2, 4, 6, 8, 12, 16].map((count) => ({
- id: `ruler-rays-${count}`,
- label: `${count} Rays per VP`,
- checked: (perspectiveRuler.guideRayCount || 6) === count,
- onClick: () =>
- updatePerspectiveRuler((prev) =>
- prev ? { ...prev, guideRayCount: count } : null
- ),
- })),
- },
- {
- id: 'ruler-presets',
- label: 'Change Perspective Preset',
- disabled: !hasOpenDocument,
- submenu: [
- {
- id: 'ruler-preset-1p',
- label: '1-Point Perspective (Center)',
- onClick: () => {
- const next = createDefaultPerspectiveRuler('1-point', dimensions);
- next.snapEnabled = perspectiveRuler.snapEnabled;
- next.locked = perspectiveRuler.locked;
- next.guideRayCount = perspectiveRuler.guideRayCount;
- updatePerspectiveRuler(next);
- },
- },
- {
- id: 'ruler-preset-2p',
- label: '2-Point Perspective (Wide Street)',
- onClick: () => {
- const next = createDefaultPerspectiveRuler('2-point', dimensions);
- next.snapEnabled = perspectiveRuler.snapEnabled;
- next.locked = perspectiveRuler.locked;
- next.guideRayCount = perspectiveRuler.guideRayCount;
- updatePerspectiveRuler(next);
- },
- },
- {
- id: 'ruler-preset-3p-birds',
- label: "3-Point Perspective (Bird's-Eye)",
- onClick: () => {
- const next = createDefaultPerspectiveRuler('3-point', dimensions);
- next.snapEnabled = perspectiveRuler.snapEnabled;
- next.locked = perspectiveRuler.locked;
- next.guideRayCount = perspectiveRuler.guideRayCount;
- updatePerspectiveRuler(next);
- },
- },
- {
- id: 'ruler-preset-3p-worms',
- label: "3-Point Perspective (Worm's-Eye)",
- onClick: () => {
- const base = createDefaultPerspectiveRuler('3-point', dimensions);
- base.guideRayCount = perspectiveRuler.guideRayCount;
- const next = applyWormsEyePreset(base, dimensions);
- updatePerspectiveRuler(next);
- },
- },
- ],
- },
- {
- id: 'ruler-div-remove',
- label: '',
- divider: true,
- },
- {
- id: 'ruler-remove',
- label: 'Remove Perspective Ruler from Canvas',
- danger: true,
- icon: <Trash2 className="w-3.5 h-3.5 text-red-400" />,
- disabled: !hasOpenDocument,
- onClick: () => {
- updatePerspectiveRuler(null);
- showToast('Removed perspective ruler from canvas');
- },
- },
- ]),
- ],
- },
- {
- id: 'view',
- label: 'View',
- items: [
- {
- id: 'view-zoom-in',
- label: 'Zoom In',
- shortcut: 'Ctrl++',
- icon: <ZoomIn className="w-3.5 h-3.5" />,
- disabled: !hasOpenDocument,
- onClick: zoomIn,
- },
- {
- id: 'view-zoom-out',
- label: 'Zoom Out',
- shortcut: 'Ctrl+-',
- icon: <ZoomOut className="w-3.5 h-3.5" />,
- disabled: !hasOpenDocument,
- onClick: zoomOut,
- },
- {
- id: 'view-reset-zoom',
- label: 'Reset Zoom & Center',
- shortcut: 'Ctrl+0',
- disabled: !hasOpenDocument,
- onClick: resetZoomAndCenter,
- },
- {
- id: 'view-reset-rotation',
- label: 'Reset Rotation',
- shortcut: 'Ctrl+Alt+0',
- icon: <RotateCcw className="w-3.5 h-3.5" />,
- disabled: !hasOpenDocument,
- onClick: resetRotation,
- },
- {
- id: 'view-div-flip',
- label: '',
- divider: true,
- },
- {
- id: 'view-flip-horizontal',
- label: 'Flip View Horizontal',
- shortcut: 'Shift+H',
- icon: <FlipHorizontal className="w-3.5 h-3.5" />,
- checked: flipX,
- disabled: !hasOpenDocument,
- onClick: toggleFlipHorizontal,
- },
- {
- id: 'view-flip-vertical',
- label: 'Flip View Vertical',
- shortcut: 'Shift+V',
- icon: <FlipVertical className="w-3.5 h-3.5" />,
- checked: flipY,
- disabled: !hasOpenDocument,
- onClick: toggleFlipVertical,
- },
- {
- id: 'view-reset-flip',
- label: 'Reset View Flip',
- disabled: !hasOpenDocument || (!flipX && !flipY),
- onClick: resetViewFlip,
- },
- {
- id: 'view-div-ruler',
- label: '',
- divider: true,
- },
- {
- id: 'view-toggle-ruler',
- label: perspectiveRuler?.enabled ? 'Hide Perspective Ruler' : 'Show Perspective Ruler',
- shortcut: 'Ctrl+Shift+R',
- disabled: !hasOpenDocument || !perspectiveRuler,
- onClick: () =>
- updatePerspectiveRuler((prev) =>
- prev ? { ...prev, enabled: !prev.enabled } : null
- ),
- },
- {
- id: 'view-toggle-snap',
- label: perspectiveRuler?.snapEnabled
- ? 'Disable Perspective Snapping'
- : 'Enable Perspective Snapping',
- shortcut: 'Ctrl+Shift+P',
- disabled: !hasOpenDocument || !perspectiveRuler,
- onClick: () =>
- updatePerspectiveRuler((prev) =>
- prev ? { ...prev, snapEnabled: !prev.snapEnabled } : null
- ),
- },
- {
- id: 'view-div-webtoon',
- label: '',
- divider: true,
- },
- {
- id: 'view-webtoon-mode',
- label: isWebtoonMode ? 'Exit Webtoon Studio Mode' : 'Webtoon Studio Mode (9:16 Mockup)',
- icon: <Smartphone className="w-3.5 h-3.5 text-emerald-400" />,
- disabled: !hasOpenDocument,
- onClick: () => setIsWebtoonMode((prev) => !prev),
- },
- {
- id: 'view-div-soft-proof',
- label: '',
- divider: true,
- },
- {
- id: 'view-proof-setup',
- label: 'Proof Setup',
- disabled: !hasOpenDocument,
- submenu: [
- {
- id: 'proof-setup-us-web',
- label: 'Working CMYK - U.S. Web Coated (SWOP) v2',
- checked: softProofSettings.standard === 'us-web-coated-swop',
- onClick: () => setProofStandard('us-web-coated-swop'),
- },
- {
- id: 'proof-setup-japan',
- label: 'Japan Color 2001 Coated',
- checked: softProofSettings.standard === 'japan-color-2001',
- onClick: () => setProofStandard('japan-color-2001'),
- },
- {
- id: 'proof-setup-iso',
- label: 'ISO Coated v2 (ECI)',
- checked: softProofSettings.standard === 'iso-coated-v2',
- onClick: () => setProofStandard('iso-coated-v2'),
- },
- ],
- },
- {
- id: 'view-proof-colors',
- label: 'Proof Colors',
- shortcut: 'Ctrl+Alt+Y',
- checked: softProofSettings.enabled,
- disabled: !hasOpenDocument,
- onClick: toggleSoftProof,
- },
- {
- id: 'view-gamut-warning',
- label: 'Gamut Warning',
- shortcut: 'Ctrl+Shift+Y',
- checked: softProofSettings.gamutWarning,
- disabled: !hasOpenDocument,
- onClick: toggleGamutWarning,
- },
- ],
- },
- {
- id: 'manga',
- label: 'Manga',
- items: [
- {
- id: 'manga-effects-generator',
- label: 'Manga Effect Lines Generator...',
- icon: <Sparkles className="w-3.5 h-3.5 text-amber-400" />,
- disabled: !hasOpenDocument,
- onClick: () => setIsMangaEffectsModalOpen(true),
- },
- {
- id: 'manga-balloon-tool',
- label: 'Parametric Speech Balloon Tool',
- icon: <MessageSquare className="w-3.5 h-3.5 text-cyan-400" />,
- disabled: !hasOpenDocument,
- onClick: () => handleSelectTool('balloon'),
- },
- {
- id: 'manga-correct-line',
- label: 'Correct Line (Vector Pinch/Width/Simplify)',
- icon: <Spline className="w-3.5 h-3.5 text-indigo-400" />,
- disabled: !hasOpenDocument,
- onClick: () => handleSelectTool('vector-edit'),
- },
- {
- id: 'manga-div-webtoon',
- label: '',
- divider: true,
- },
- {
- id: 'manga-webtoon-toggle',
- label: isWebtoonMode ? 'Exit Webtoon Studio Mode' : 'Webtoon Studio Mode (9:16 Simulator)',
- icon: <Smartphone className="w-3.5 h-3.5 text-emerald-400" />,
- disabled: !hasOpenDocument,
- onClick: () => setIsWebtoonMode((prev) => !prev),
- },
- {
- id: 'manga-webtoon-export',
- label: 'Export Webtoon Chapter Slices (.zip)...',
- icon: <Archive className="w-3.5 h-3.5 text-sky-400" />,
- disabled: !hasOpenDocument,
- onClick: () => setIsWebtoonExportModalOpen(true),
- },
- ],
- },
- {
- id: 'animation',
- label: 'Animation',
- items: [
- {
- id: 'anim-toggle-timeline',
- label: activeAnimationTimeline ? 'Hide Animation Timeline' : 'Show Animation Timeline',
- shortcut: 'Ctrl+Alt+A',
- icon: <Film className="w-3.5 h-3.5 text-emerald-400" />,
- disabled: !hasOpenDocument,
- onClick: () => {
- if (activeAnimationTimeline) {
- handleUpdateAnimationTimeline(null);
- } else {
- const tl = createDefaultAnimationTimeline(layers);
- handleUpdateAnimationTimeline(tl);
- }
- },
- },
- {
- id: 'anim-new-cel',
- label: 'Add Cel to Current Frame',
- shortcut: 'Alt+C',
- icon: <Plus className="w-3.5 h-3.5" />,
- disabled: !hasOpenDocument || !activeAnimationTimeline,
- onClick: () => {
- if (activeAnimationTimeline) {
- handleAddAnimationCel(activeAnimationTimeline.currentFrame);
- }
- },
- },
- {
- id: 'anim-toggle-onion',
- label: activeAnimationTimeline?.onionSkin.enabled
- ? 'Disable Onion Skinning'
- : 'Enable Onion Skinning',
- icon: <Layers className="w-3.5 h-3.5 text-purple-400" />,
- disabled: !hasOpenDocument || !activeAnimationTimeline,
- onClick: () => {
- if (activeAnimationTimeline) {
- handleUpdateAnimationTimeline({
- ...activeAnimationTimeline,
- onionSkin: {
- ...activeAnimationTimeline.onionSkin,
- enabled: !activeAnimationTimeline.onionSkin.enabled,
- },
- });
- }
- },
- },
- ],
- },
- {
- id: 'help',
- label: 'Help',
- items: [
- {
- id: 'help-about',
- label: 'About Ink Studio',
- icon: <InfoIcon className="w-3.5 h-3.5 text-[#93c5fd]" />,
- onClick: () => {
- alert(
- 'Ink Studio - Professional Digital Painting & Manga Studio\n\n' +
- '- Full Layer Management with 17 Blend Modes\n' +
- '- Supports Opening PSD (Photoshop) & CSP (Clip Studio Paint) with layers\n' +
- '- Supports Common Images: PNG, JPG, WEBP, GIF, BMP, SVG\n' +
- '- Save & Save As: PSD (layered), Ink Studio Project (.sora / .ink), PNG, JPG, WebP\n' +
- '- Export Image: High-resolution PNG\n' +
- '- Color Modes: Full Color (RGB), Grayscale, and 1-bit Manga Monochrome\n' +
- '- CSP Sub-Tool Engine, Tablet Pressure, Tilt & Inking Stabilization'
- );
- },
- },
- ],
- },
- ], [
- activeAnimationTimeline,
- activeLayer,
- activeLayerId,
- addLayerMask,
- canRedo,
- canUndo,
- clearCanvas,
- deleteLayer,
- dimensions,
- duplicateLayer,
- handleAddAnimationCel,
- handleAddLayer,
- handleApplyFilter,
- handleApplyReverseGradient,
- handleClearActiveLayer,
- handleContractSelection,
- handleConvertLayer,
- handleCopySelectedLayer,
- handleDeleteSelectedLayer,
- handleDeselect,
- handleExpandSelection,
- handleExportImage,
- handleFeatherSelection,
- handleFillSelectionColor,
- handleInvertSelection,
- handleOpenAdjustmentModal,
- handleOpenLayerStylesModal,
- handleOpenTonalModal,
- handlePasteSelectedLayer,
- handleSave,
- handleSaveAs,
- handleSelectAll,
- handleSelectTool,
- handleStartTransform,
- handleTriggerImport3DFile,
- handleTriggerOpenFile,
- handleTriggerPasteFromFile,
- handleUndo,
- handleUpdateAnimationTimeline,
- hasOpenDocument,
- isWebtoonMode,
- layers,
- perspectiveRuler,
- redo,
- removeLayerMask,
- resetRotation,
- resetZoomAndCenter,
- selection,
- setProofStandard,
- showToast,
- softProofSettings.enabled,
- softProofSettings.gamutWarning,
- softProofSettings.standard,
- toggleGamutWarning,
- toggleLayerColor,
- toggleLayerMask,
- toggleMaskLinked,
- toggleSoftProof,
- updateBrushSettings,
- updatePerspectiveRuler,
- zoomIn,
- zoomOut,
- ]);
-
- const handleSelectWelcomeDocument = useCallback(
- async (doc: RecentDocument) => {
- // 1. If running in Tauri, attempt to read directly from PC disk
- if (typeof window !== 'undefined' && (window as any).__TAURI_INTERNALS__) {
- try {
- const { invoke } = await import('@tauri-apps/api/core');
- const bytes = await invoke<number[]>('read_file_from_disk', { path: doc.path });
- if (bytes && bytes.length > 0) {
- const uint8 = new Uint8Array(bytes);
- const file = new File([uint8], doc.title, { type: 'application/octet-stream' });
- await handleProcessFile(file);
- setAppView('workspace');
- return;
- }
- } catch (err) {
- console.warn('Direct disk read via Tauri failed, fallback:', err);
- }
- }
-
- // 2. Fallback: Initialize new canvas with the document title and standard dimensions
- handleCreateNewCanvas({
- width: 1920,
- height: 1080,
- dpi: 300,
- colorMode: 'color',
- name: doc.title,
- backgroundColor: '#ffffff',
- aspectRatioPreset: '16:9',
- aspectRatioX: 16,
- aspectRatioY: 9,
- lockAspectRatio: true,
- });
- showToast(`Loaded workspace for "${doc.title}"`);
- },
- [handleCreateNewCanvas, handleProcessFile, showToast]
- );
-
- const modernAccent = appSettings.modernAccent || 'neutral';
- const modernAccentHex = resolveModernAccentColor(modernAccent, appSettings.modernCustomColor);
- const modernAccentRgb = hexToRgb(modernAccentHex) || { r: 229, g: 229, b: 229 };
- const modernAccentContrast = getAccentContrastColor(modernAccentHex);
-
- const modernStyleVars = useMemo(
- () =>
- ({
- '--accent': modernAccentHex,
- '--accent-rgb': `${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}`,
- '--accent-contrast': modernAccentContrast,
- '--accent-subtle': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.14)`,
- '--accent-border': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.32)`,
- '--modern-accent': modernAccentHex,
- '--modern-accent-rgb': `${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}`,
- '--modern-accent-subtle': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.14)`,
- '--modern-accent-border': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.32)`,
- '--modern-accent-hover': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.2)`,
- }) as React.CSSProperties,
- [modernAccentHex, modernAccentRgb.r, modernAccentRgb.g, modernAccentRgb.b, modernAccentContrast]
+ const handleOpenCollabModal = useCallback(() => {
+ collab.setIsHostModalOpen(true);
+ }, [collab.setIsHostModalOpen]);
+
+ const canvasProps = useMemo(
+ () => ({
+ viewportRef: nav.viewportRef,
+ onViewportReady: docLifecycle.handleViewportReady,
+ zoom: nav.zoom,
+ pan: nav.pan,
+ rotation: nav.rotation,
+ flipX: nav.flipX,
+ flipY: nav.flipY,
+ navigation: nav.navigation,
+ isSpaceDown: nav.isSpaceDown,
+ isShiftDown: nav.isShiftDown,
+ isRotateModifier: nav.isRotateModifier,
+ isPanning: nav.isPanning,
+ isRotating: nav.isRotating,
+ startPan: nav.startPan,
+ startRotate: nav.startRotate,
+ isHovering: drawing.isHovering,
+ cursorPos: drawing.cursorPos,
+ onPointerDown: handlePointerDown,
+ onPointerMove: handlePointerMove,
+ onPointerUp: handlePointerUp,
+ onPointerEnter: drawing.handlePointerEnter,
+ onPointerLeave: drawing.handlePointerLeave,
+ layers: layerMgr.layers,
+ activeLayerId: layerMgr.activeLayerId,
+ tileGrid: activeTileGrid,
+ layerCanvasesRef: layerMgr.layerCanvasesRef,
+ registerLayerCanvas: layerMgr.registerLayerCanvas,
+ getEffectiveOpacity: layerMgr.getEffectiveOpacity,
+ isLayerEffectivelyVisible: layerMgr.isLayerEffectivelyVisible,
+ interactionRef: drawing.interactionRef,
+ draftCanvasRef,
+ strokeCanvasRef,
+ peers: collab.peers,
+ activePings: collab.activePings,
+ remoteDraftCanvasesRef: collab.remoteDraftCanvasesRef,
+ selection: selectionTools.selection,
+ onDeselect: selectionTools.handleDeselect,
+ onTransformSelection: selectionTools.handleStartTransform,
+ onFillScreentone: tonalActions.handleFillScreentone,
+ onFillColor: selectionTools.handleFillSelectionColor,
+ onClearSelection: selectionTools.handleClearSelection,
+ onInvertSelection: selectionTools.handleInvertSelection,
+ onExpandSelection: selectionTools.handleExpandSelection,
+ onContractSelection: selectionTools.handleContractSelection,
+ onFeatherSelection: selectionTools.handleFeatherSelection,
+ transformSession: selectionTools.transformSession,
+ setTransformSession: selectionTools.setTransformSession,
+ onApplyTransform: selectionTools.handleApplyTransform,
+ onCancelTransform: selectionTools.handleCancelTransform,
+ textSession: shapeFillTools.textSession,
+ setTextSession: shapeFillTools.setTextSession,
+ onConfirmText: shapeFillTools.handleConfirmText,
+ onCancelText: shapeFillTools.handleCancelText,
+ onInsertRasterLayer: tonalActions.handleInsert3DRasterLayer,
+ activeBalloon: shapeFillTools.activeBalloon,
+ setActiveBalloon: shapeFillTools.setActiveBalloon,
+ onConfirmBalloon: shapeFillTools.handleConfirmBalloon,
+ onDeleteBalloon: shapeFillTools.handleDeleteBalloon,
+ animationTimeline: activeAnimationTimeline,
+ onUpdateAnimationTimeline: handleUpdateAnimationTimeline,
+ onAddAnimationCel: handleAddAnimationCel,
+ onDeleteAnimationCel: handleDeleteAnimationCel,
+ onSelectCelLayer: layerMgr.setActiveLayerId,
+ }),
+ [
+ nav,
+ docLifecycle.handleViewportReady,
+ drawing.isHovering,
+ drawing.cursorPos,
+ drawing.handlePointerEnter,
+ drawing.handlePointerLeave,
+ drawing.interactionRef,
+ handlePointerDown,
+ handlePointerMove,
+ handlePointerUp,
+ layerMgr.layers,
+ layerMgr.activeLayerId,
+ layerMgr.layerCanvasesRef,
+ layerMgr.registerLayerCanvas,
+ layerMgr.getEffectiveOpacity,
+ layerMgr.isLayerEffectivelyVisible,
+ layerMgr.setActiveLayerId,
+ activeTileGrid,
+ collab.peers,
+ collab.activePings,
+ collab.remoteDraftCanvasesRef,
+ selectionTools,
+ tonalActions.handleFillScreentone,
+ tonalActions.handleInsert3DRasterLayer,
+ shapeFillTools.textSession,
+ shapeFillTools.setTextSession,
+ shapeFillTools.handleConfirmText,
+ shapeFillTools.handleCancelText,
+ shapeFillTools.activeBalloon,
+ shapeFillTools.setActiveBalloon,
+ shapeFillTools.handleConfirmBalloon,
+ shapeFillTools.handleDeleteBalloon,
+ activeAnimationTimeline,
+ handleUpdateAnimationTimeline,
+ handleAddAnimationCel,
+ handleDeleteAnimationCel,
+ ]
);
return (
- <div
- className="flex flex-col w-screen h-screen overflow-hidden bg-[#161616] text-[#e5e5e5] font-sans gap-px app-root-container"
- data-theme="modern"
- data-accent={modernAccent}
- style={modernStyleVars}
+ <AppShell
+ fileInputRef={docLifecycle.fileInputRef}
+ pasteFileInputRef={docLifecycle.pasteFileInputRef}
+ import3DFileInputRef={docLifecycle.import3DFileInputRef}
+ handleFileInputChange={docLifecycle.handleFileInputChange}
+ handlePasteFileInputChange={docLifecycle.handlePasteFileInputChange}
+ handleImport3DFileInputChange={docLifecycle.handleImport3DFileInputChange}
+ canUndo={drawing.canUndo}
+ canRedo={drawing.canRedo}
+ handleUndo={handleUndo}
+ redo={drawing.redo}
+ zoom={nav.zoom}
+ zoomIn={nav.zoomIn}
+ zoomOut={nav.zoomOut}
+ resetZoomAndCenter={nav.resetZoomAndCenter}
+ rotation={nav.rotation}
+ resetRotation={nav.resetRotation}
+ flipX={nav.flipX}
+ flipY={nav.flipY}
+ toggleFlipHorizontal={nav.toggleFlipHorizontal}
+ toggleFlipVertical={nav.toggleFlipVertical}
+ resetViewFlip={nav.resetViewFlip}
+ menuSections={menuSections}
+ handleSelectDocument={docLifecycle.handleSelectDocument}
+ handleCloseDocument={docLifecycle.handleCloseDocument}
+ handleRenameDocument={docLifecycle.handleRenameDocument}
+ handleSave={docLifecycle.handleSave}
+ handleSaveAs={docLifecycle.handleSaveAs}
+ handleClearActiveLayer={collab.handleClearActiveLayer}
+ handleMergeDown={handleMergeDown}
+ isCollabConnected={collab.isConnected}
+ collabPeerCount={collab.peers.length + 1}
+ onOpenCollabModal={handleOpenCollabModal}
+ handleTriggerOpenFile={docLifecycle.handleTriggerOpenFile}
+ handleSelectWelcomeDocument={docLifecycle.handleSelectWelcomeDocument}
+ showToast={showToast}
+ canvasProps={canvasProps}
+ historyList={drawing.historyList}
+ historyIndex={drawing.historyIndex}
+ jumpToHistoryIndex={drawing.jumpToHistoryIndex}
+ layers={layerMgr.layers}
+ activeLayerId={layerMgr.activeLayerId}
+ selectedLayerIds={layerMgr.selectedLayerIds}
+ setActiveLayerId={layerMgr.setActiveLayerId}
+ toggleLayerSelection={layerMgr.toggleLayerSelection}
+ handleGroupSelectedLayers={collab.handleGroupSelectedLayers}
+ handleDeleteSelectedLayers={collab.handleDeleteSelectedLayers}
+ handleAddLayer={collab.handleAddLayer}
+ duplicateLayer={layerMgr.duplicateLayer}
+ handleDeleteLayer={collab.handleDeleteLayer}
+ handleToggleVisibility={collab.handleToggleVisibility}
+ handleSetOpacity={collab.handleSetOpacity}
+ setBlendMode={layerMgr.setBlendMode}
+ toggleLock={layerMgr.toggleLock}
+ toggleAlphaLock={layerMgr.toggleAlphaLock}
+ toggleClipping={layerMgr.toggleClipping}
+ toggleCollapse={layerMgr.toggleCollapse}
+ handleRenameLayer={collab.handleRenameLayer}
+ moveLayer={layerMgr.moveLayer}
+ moveLayerToFolder={layerMgr.moveLayerToFolder}
+ reorderLayers={layerMgr.reorderLayers}
+ handleToggleReferenceLayer={handleToggleReferenceLayer}
+ toggleTone={layerMgr.toggleTone}
+ setToneFrequency={layerMgr.setToneFrequency}
+ setToneAngle={layerMgr.setToneAngle}
+ setToneDotShape={layerMgr.setToneDotShape}
+ setToneDensity={layerMgr.setToneDensity}
+ setToneDensityType={layerMgr.setToneDensityType}
+ toggleLayerColor={layerMgr.toggleLayerColor}
+ setLayerColor={layerMgr.setLayerColor}
+ setLayerSubColor={layerMgr.setLayerSubColor}
+ setLayerExpressionColor={layerMgr.setLayerExpressionColor}
+ setLayerMonoThreshold={layerMgr.setLayerMonoThreshold}
+ setLayerMonoExpressMode={layerMgr.setLayerMonoExpressMode}
+ handleApplyExpressionColor={tonalActions.handleApplyExpressionColor}
+ handleApplyLayerColor={tonalActions.handleApplyLayerColor}
+ addLayerMask={layerMgr.addLayerMask}
+ removeLayerMask={layerMgr.removeLayerMask}
+ toggleLayerMask={layerMgr.toggleLayerMask}
+ toggleMaskLinked={layerMgr.toggleMaskLinked}
+ handleOpenAdjustmentModal={tonalActions.handleOpenAdjustmentModal}
+ handleOpenLayerStylesModal={tonalActions.handleOpenLayerStylesModal}
>
- {/* Hidden File Input for Native File Picker */}
- <input
- ref={fileInputRef}
- type="file"
- accept=".png,.jpg,.jpeg,.webp,.bmp,.gif,.svg,.psd,.psb,.clip,.csp,.sora,.ink,.sut"
- onChange={handleFileInputChange}
- className="hidden"
- />
-
- {/* Hidden File Input for Paste Photo From File */}
- <input
- ref={pasteFileInputRef}
- type="file"
- accept=".png,.jpg,.jpeg,.webp,.bmp,.gif,.svg,.ico,image/*"
- onChange={handlePasteFileInputChange}
- className="hidden"
- />
-
- {/* Hidden File Input for 3D Model Import */}
- <input
- ref={import3DFileInputRef}
- type="file"
- accept=".glb,.gltf,.obj"
- onChange={handleImport3DFileInputChange}
- className="hidden"
+ <DocumentLifecycleManager
+ layers={layerMgr.layers}
+ activeLayerId={layerMgr.activeLayerId}
+ layerCanvasesRef={layerMgr.layerCanvasesRef}
+ needsAdaptiveFitRef={docLifecycle.needsAdaptiveFitRef}
+ pendingFitDimsRef={docLifecycle.pendingFitDimsRef}
+ resetToNewCanvas={layerMgr.resetToNewCanvas}
+ resetZoomAndCenter={nav.resetZoomAndCenter}
+ resetHistory={drawing.resetHistory}
/>
- {/* Consolidated Single Slim 36px Header Bar */}
- <Header
- canUndo={hasOpenDocument && canUndo}
- canRedo={hasOpenDocument && canRedo}
- onUndo={handleUndo}
- onRedo={redo}
- zoom={zoom}
- onZoomIn={zoomIn}
- onZoomOut={zoomOut}
- onResetZoom={resetZoomAndCenter}
- rotation={rotation}
- onResetRotation={resetRotation}
- flipX={flipX}
- flipY={flipY}
- onToggleFlipHorizontal={toggleFlipHorizontal}
- onToggleFlipVertical={toggleFlipVertical}
- onResetViewFlip={resetViewFlip}
- dimensions={dimensions}
- colorMode={colorMode}
- menuSections={menuSections}
+ <GlobalShortcutListener
hasOpenDocument={hasOpenDocument}
- documents={documents}
- activeDocumentId={activeDocumentId}
- onSelectDocument={handleSelectDocument}
- onCloseDocument={handleCloseDocument}
- onNewDocument={() => setIsNewCanvasModalOpen(true)}
- onRenameDocument={handleRenameDocument}
- isCollabConnected={isCollabConnected}
- collabPeerCount={collabPeers.length + 1}
- onOpenCollabModal={() => setIsHostModalOpen(true)}
- onOpenSettings={() => setIsSettingsModalOpen(true)}
- themePreset={appSettings.themePreset}
- softProofSettings={softProofSettings}
- appView={appView}
- onSelectAppView={(view) => {
- if (view === 'workspace' && !hasOpenDocument) {
- setIsNewCanvasModalOpen(true);
- } else {
- setAppView(view);
- }
- }}
- />
-
- {/* Main Workspace */}
- <div className="flex flex-1 overflow-hidden relative gap-px bg-[#161616]">
- {!hasOpenDocument || appView === 'home' ? (
- <WelcomeScreen
- userName={appSettings.userName}
- onNewDocument={() => setIsNewCanvasModalOpen(true)}
- onOpenFile={handleTriggerOpenFile}
- onSelectRecentDocument={handleSelectWelcomeDocument}
- showToast={showToast}
- themePreset={appSettings.themePreset}
- />
- ) : (
- <>
- <LeftPanel
- currentTool={tool}
- onSelectTool={handleSelectTool}
- brushSettings={brushSettings}
- onUpdateBrushSettings={updateBrushSettings}
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- isTransparentColor={isTransparentColor}
- onToggleTransparentColor={toggleTransparentColor}
- onPrimaryColorChange={handlePrimaryColorChange}
- onSecondaryColorChange={handleSecondaryColorChange}
- onSwapColors={handleSwapColors}
- recentColors={recentColors}
- width={leftPanelWidth}
- onWidthChange={handleLeftPanelWidthChange}
- isHidden={isLeftPanelHidden}
- onToggleHidden={() => setIsLeftPanelHidden((prev) => !prev)}
- fillSettings={fillSettings}
- onUpdateFillSettings={(newSettings) => setFillSettings((prev) => ({ ...prev, ...newSettings }))}
- textSettings={textSettings}
- onUpdateTextSettings={(newSettings) => setTextSettings((prev) => ({ ...prev, ...newSettings }))}
- frameSettings={frameSettings}
- onUpdateFrameSettings={(newSettings) => setFrameSettings((prev) => ({ ...prev, ...newSettings }))}
- hasSelection={Boolean(selection)}
- onDeselect={handleDeselect}
- onTransformSelection={handleStartTransform}
- onFillScreentone={handleFillScreentone}
- liquifySettings={liquifySettings}
- onUpdateLiquifySettings={handleUpdateLiquifySettings}
- balloonSettings={balloonSettings}
- onUpdateBalloonSettings={(newSettings) => setBalloonSettings((prev) => ({ ...prev, ...newSettings }))}
- vectorEditSettings={vectorEditSettings}
- onUpdateVectorEditSettings={(newSettings) => setVectorEditSettings((prev) => ({ ...prev, ...newSettings }))}
- onOpenMangaEffects={() => setIsMangaEffectsModalOpen(true)}
- wandSettings={wandSettings}
- onUpdateWandSettings={(newSettings) => setWandSettings((prev) => ({ ...prev, ...newSettings }))}
- onExpandSelection={handleExpandSelection}
- onContractSelection={handleContractSelection}
- onFeatherSelection={handleFeatherSelection}
- onInvertSelection={handleInvertSelection}
- />
-
- {/* Center Workspace: >80% Viewport Dedicated to Drawing Canvas */}
- <div className="flex flex-col flex-1 min-w-0 overflow-hidden relative">
- <CanvasArea
- viewportRef={viewportRef}
- onViewportReady={handleViewportReady}
- dimensions={dimensions}
- brushSettings={brushSettings}
- onUpdateBrushSettings={updateBrushSettings}
- zoom={zoom}
- pan={pan}
- rotation={rotation}
- flipX={flipX}
- flipY={flipY}
- navigation={navigation}
- isSpaceDown={isSpaceDown}
- isShiftDown={isShiftDown}
- isRotateModifier={isRotateModifier}
- isPanning={isPanning}
- isRotating={isRotating}
- onStartPan={startPan}
- onStartRotate={startRotate}
- isHovering={isHovering}
- cursorPos={cursorPos}
- onPointerDown={handlePointerDown}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerEnter={handlePointerEnter}
- onPointerLeave={handlePointerLeave}
- layers={layers}
- activeLayerId={activeLayerId}
- colorMode={colorMode}
- tileGrid={activeTileGrid}
- layerCanvasesRef={layerCanvasesRef}
- registerLayerCanvas={registerLayerCanvas}
- getEffectiveOpacity={getEffectiveOpacity}
- isLayerEffectivelyVisible={isLayerEffectivelyVisible}
- interactionRef={interactionRef}
- showCheckerboard={appSettings.showCheckerboard}
- showCursorCoordinates={appSettings.showCursorCoordinates}
- showPressureInStatusBar={appSettings.showPressureInStatusBar}
- hasOpenDocument={hasOpenDocument}
- draftCanvasRef={draftCanvasRef}
- strokeCanvasRef={strokeCanvasRef}
- peers={collabPeers}
- activePings={collabActivePings}
- remoteDraftCanvasesRef={remoteDraftCanvasesRef}
- tool={tool}
- liquifySettings={liquifySettings}
- onUpdateLiquifySettings={handleUpdateLiquifySettings}
- primaryColor={primaryColor}
- onSwapColors={handleSwapColors}
- selection={selection}
- onDeselect={handleDeselect}
- onTransformSelection={handleStartTransform}
- onFillScreentone={handleFillScreentone}
- onFillColor={handleFillSelectionColor}
- onClearSelection={handleClearSelection}
- onInvertSelection={handleInvertSelection}
- onExpandSelection={handleExpandSelection}
- onContractSelection={handleContractSelection}
- onFeatherSelection={handleFeatherSelection}
- transformSession={transformSession}
- onUpdateTransformSession={(updater) =>
- setTransformSession((prev) => (prev ? updater(prev) : null))
- }
- onApplyTransform={handleApplyTransform}
- onCancelTransform={handleCancelTransform}
- textSession={textSession}
- onUpdateTextSettings={(updater) =>
- setTextSession((prev) => (prev ? { ...prev, settings: updater(prev.settings) } : null))
- }
- onMoveTextSession={(newX, newY) =>
- setTextSession((prev) => (prev ? { ...prev, x: newX, y: newY } : null))
- }
- onConfirmText={handleConfirmText}
- onCancelText={handleCancelText}
- perspectiveRuler={hasOpenDocument ? perspectiveRuler : null}
- onUpdatePerspectiveRuler={updatePerspectiveRuler}
- activeLockedAxis={activeLockedAxis}
- is3DLayerOpen={is3DLayerOpen}
- initial3DFile={initial3DFile}
- onClose3DLayer={() => {
- setIs3DLayerOpen(false);
- setInitial3DFile(null);
- }}
- onInsertRasterLayer={handleInsert3DRasterLayer}
- isWebtoonMode={isWebtoonMode}
- onToggleWebtoonMode={() => setIsWebtoonMode((prev) => !prev)}
- onOpenWebtoonExport={() => setIsWebtoonExportModalOpen(true)}
- activeBalloon={activeBalloon}
- onUpdateBalloon={(updater) => setActiveBalloon((prev) => (prev ? updater(prev) : null))}
- onConfirmBalloon={handleConfirmBalloon}
- onDeleteBalloon={handleDeleteBalloon}
- animationTimeline={activeAnimationTimeline}
- onUpdateAnimationTimeline={handleUpdateAnimationTimeline}
- onAddAnimationCel={handleAddAnimationCel}
- onDeleteAnimationCel={handleDeleteAnimationCel}
- onSelectCelLayer={setActiveLayerId}
- softProofSettings={softProofSettings}
- />
- </div>
-
- {!isRightSidebarHidden && (
- <RightSidebar
- hasOpenDocument={hasOpenDocument}
- onNewCanvas={() => setIsNewCanvasModalOpen(true)}
- onOpenFile={handleTriggerOpenFile}
- primaryColor={primaryColor}
- secondaryColor={secondaryColor}
- onPrimaryColorChange={handlePrimaryColorChange}
- onSecondaryColorChange={handleSecondaryColorChange}
- onSwapColors={handleSwapColors}
- recentColors={recentColors}
- currentTool={tool}
- onSelectTool={handleSelectTool}
- colorMode={colorMode}
- historyList={hasOpenDocument ? historyList : []}
- historyIndex={hasOpenDocument ? historyIndex : -1}
- onJumpToHistory={jumpToHistoryIndex}
- canUndo={hasOpenDocument && canUndo}
- canRedo={hasOpenDocument && canRedo}
- onUndo={handleUndo}
- onRedo={redo}
- layers={hasOpenDocument ? layers : []}
- activeLayerId={hasOpenDocument ? activeLayerId : ''}
- selectedLayerIds={hasOpenDocument ? selectedLayerIds : []}
- onSelectLayer={setActiveLayerId}
- onToggleLayerSelection={toggleLayerSelection}
- onGroupSelectedLayers={handleGroupSelectedLayers}
- onDeleteSelectedLayers={handleDeleteSelectedLayers}
- onAddLayer={handleAddLayer}
- onOpen3DLayer={hasOpenDocument ? () => setIs3DLayerOpen(true) : undefined}
- onDuplicateLayer={duplicateLayer}
- onDeleteLayer={handleDeleteLayer}
- onToggleVisibility={handleToggleVisibility}
- onSetOpacity={handleSetOpacity}
- onSetBlendMode={setBlendMode}
- onToggleLock={toggleLock}
- onToggleAlphaLock={toggleAlphaLock}
- onToggleClipping={toggleClipping}
- onToggleCollapse={toggleCollapse}
- onRenameLayer={handleRenameLayer}
- onMoveLayer={moveLayer}
- onMoveLayerToFolder={moveLayerToFolder}
- onReorderLayers={reorderLayers}
- onToggleReferenceLayer={handleToggleReferenceLayer}
- onToggleTone={toggleTone}
- onSetToneFrequency={setToneFrequency}
- onSetToneAngle={setToneAngle}
- onSetToneDotShape={setToneDotShape}
- onSetToneDensity={setToneDensity}
- onSetToneDensityType={setToneDensityType}
- onToggleLayerColor={toggleLayerColor}
- onSetLayerColor={setLayerColor}
- onSetLayerSubColor={setLayerSubColor}
- onSetLayerExpressionColor={setLayerExpressionColor}
- onSetLayerMonoThreshold={setLayerMonoThreshold}
- onSetLayerMonoExpressMode={setLayerMonoExpressMode}
- onApplyExpressionColor={handleApplyExpressionColor}
- onApplyLayerColor={handleApplyLayerColor}
- activeEditTarget={activeEditTarget}
- onSelectEditTarget={setActiveEditTarget}
- onAddLayerMask={addLayerMask}
- onRemoveLayerMask={removeLayerMask}
- onToggleLayerMask={toggleLayerMask}
- onToggleMaskLinked={toggleMaskLinked}
- onOpenAdjustmentModal={handleOpenAdjustmentModal}
- onOpenLayerStylesModal={handleOpenLayerStylesModal}
- width={rightSidebarWidth}
- onWidthChange={handleRightSidebarWidthChange}
- />
- )}
- </>
- )}
- </div>
-
- {/* Fault-Tolerant Crash Recovery Modal */}
- <CrashRecoveryModal
- isOpen={isRecoveryModalOpen}
- sessions={crashedSessions}
- onRestore={handleRestoreCrashedSession}
- onDiscard={handleDiscardCrashedSession}
- onClose={() => setIsRecoveryModalOpen(false)}
- />
-
- {/* New Canvas Modal Dialog */}
- <NewCanvasModal
- isOpen={isNewCanvasModalOpen}
- onClose={() => setIsNewCanvasModalOpen(false)}
- onCreate={handleCreateNewCanvas}
- initialWidth={dimensions.width}
- initialHeight={dimensions.height}
- initialDpi={dimensions.dpi || 300}
- initialName="Untitled*"
- />
-
- {/* Resize Canvas Modal Dialog */}
- <ResizeCanvasModal
- isOpen={isResizeCanvasModalOpen}
- onClose={() => setIsResizeCanvasModalOpen(false)}
- currentDimensions={dimensions}
- onResize={handleResizeCanvas}
- />
-
- {/* Settings Modal Dialog */}
- <SettingsModal
- isOpen={isSettingsModalOpen}
- onClose={() => setIsSettingsModalOpen(false)}
- settings={appSettings}
- onUpdateSettings={handleUpdateSettings}
- onShowToast={showToast}
- />
-
- {/* Tonal Correction Modal Dialog */}
- <TonalCorrectionModal
- isOpen={tonalModalState.isOpen}
- type={tonalModalState.type}
- beforeImageData={tonalModalState.beforeImageData}
- selectionMask={tonalModalState.selectionMask}
- onClose={handleTonalCancel}
- onApply={handleTonalApply}
- onPreviewChange={handleTonalPreviewChange}
- />
-
- {/* Non-destructive Adjustment Layer Modal (Curves, Gradient Map, Levels, Color Balance) */}
- {adjustmentModalState.isOpen && (
- <AdjustmentModal
- isOpen={adjustmentModalState.isOpen}
- initialType={adjustmentModalState.initialType || 'curves'}
- initialData={
- adjustmentModalState.layerId
- ? layers.find((l) => l.id === adjustmentModalState.layerId)?.adjustmentData
- : undefined
- }
- editingLayerId={adjustmentModalState.layerId}
- onApply={handleApplyAdjustment}
- onClose={() => setAdjustmentModalState({ isOpen: false })}
- />
- )}
-
- {/* Non-destructive GPU Layer Styles Modal (Stroke, Drop Shadow, Outer Glow) */}
- {layerStylesModalState.isOpen && (
- <LayerStylesModal
- isOpen={layerStylesModalState.isOpen}
- layerName={layers.find((l) => l.id === layerStylesModalState.layerId)?.name || 'Layer'}
- initialStyles={layers.find((l) => l.id === layerStylesModalState.layerId)?.styles}
- onClose={() => setLayerStylesModalState({ isOpen: false })}
- onApply={handleApplyLayerStyles}
- />
- )}
-
- {/* Clip Studio Paint Simple Tone Settings Modal */}
- <SimpleToneModal
- isOpen={isToneModalOpen}
- onClose={() => setIsToneModalOpen(false)}
- onConfirm={handleConfirmTone}
- initialFrequency={activeLayer?.toneFrequency || documents.find((d) => d.id === activeDocumentId)?.defaultFrequency || 60}
- initialDensity={activeLayer?.toneDensity || 40}
- dpi={dimensions.dpi ?? 600}
- />
-
- {/* Multiplayer Collaboration Modals & Overlays */}
- <HostModal
- isOpen={isHostModalOpen}
- onClose={() => setIsHostModalOpen(false)}
- isHost={isCollabHost}
- isConnected={isCollabConnected}
- hostInfo={collabHostInfo}
- peers={collabPeers}
- myPeer={collabMyPeer}
- onUpdateMyName={updateMyName}
- onStartHosting={handleStartHosting}
- onStopHosting={stopHosting}
+ dimensions={dimensions}
+ layers={layerMgr.layers}
+ activeLayer={layerMgr.activeLayer}
+ activeLayerId={layerMgr.activeLayerId}
+ selection={selectionTools.selection}
+ transformSession={selectionTools.transformSession}
+ textSession={shapeFillTools.textSession}
+ activeAnimationTimeline={activeAnimationTimeline}
+ isSpaceDown={nav.isSpaceDown}
+ isHostModalOpen={collab.isHostModalOpen}
+ isDrawingRef={drawing.isDrawingRef}
+ isSelectionPenDrawingRef={selectionTools.isSelectionPenDrawingRef}
+ isPipetteSamplingRef={shapeFillTools.isPipetteSamplingRef}
+ handleUndo={handleUndo}
+ redo={drawing.redo}
+ handleAddLayer={collab.handleAddLayer}
+ handleTriggerOpenFile={docLifecycle.handleTriggerOpenFile}
+ handleSave={docLifecycle.handleSave}
+ handleSaveAs={docLifecycle.handleSaveAs}
+ duplicateLayer={layerMgr.duplicateLayer}
+ handleCopySelectedLayer={docLifecycle.handleCopySelectedLayer}
+ handlePasteSelectedLayer={docLifecycle.handlePasteSelectedLayer}
+ handleGroupSelectedLayers={collab.handleGroupSelectedLayers}
+ handleStartTransform={selectionTools.handleStartTransform}
+ handleSelectAll={selectionTools.handleSelectAll}
+ handleDeselect={selectionTools.handleDeselect}
+ handleInvertSelection={selectionTools.handleInvertSelection}
+ handleApplyReverseGradient={tonalActions.handleApplyReverseGradient}
+ handleOpenTonalModal={tonalActions.handleOpenTonalModal}
+ handleUpdateAnimationTimeline={handleUpdateAnimationTimeline}
+ handleAddAnimationCel={handleAddAnimationCel}
+ toggleFlipHorizontal={nav.toggleFlipHorizontal}
+ toggleFlipVertical={nav.toggleFlipVertical}
+ handleClearSelection={selectionTools.handleClearSelection}
+ handleDeleteSelectedLayer={docLifecycle.handleDeleteSelectedLayer}
+ handleCancelTransform={selectionTools.handleCancelTransform}
+ handleCancelText={shapeFillTools.handleCancelText}
+ handleApplyTransform={selectionTools.handleApplyTransform}
+ handleProcessFile={docLifecycle.handleProcessFile}
showToast={showToast}
/>
- <ClipboardInviteToast
- invite={clipboardInvite}
- onJoin={(h, p, r) => joinRoom(h, p, r, collabMyPeer.name)}
- onDismiss={() => setClipboardInvite(null)}
- />
-
- <WebLandingModal
- invite={webLandingInvite}
- onJoinInBrowser={(name, h, p, r) => {
- updateMyName(name);
- joinRoom(h, p, r, name);
- }}
- onDismiss={() => setWebLandingInvite(null)}
- />
-
-
- {/* Loading Modal when parsing large PSD or CSP files */}
- {isLoadingFile && (
- <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 select-none">
- <div className="bg-[#202020] rounded-md shadow-[0_16px_48px_rgba(0,0,0,0.75)] px-5 py-3.5 flex items-center gap-3 text-xs text-[#e5e5e5]">
- <Loader2 className="w-4 h-4 text-[var(--accent)] animate-spin" />
- <div className="flex flex-col">
- <span className="font-medium text-xs">{loadingStatus || 'Opening Document...'}</span>
- <span className="text-[#8a8a8a] text-[10px]">Extracting layers and pixel data</span>
- </div>
- </div>
- </div>
- )}
-
- {/* Toast Notification */}
- {toastMessage && (
- <div className="fixed bottom-5 right-5 z-50 bg-[#202020] text-[#e5e5e5] px-3.5 py-2 rounded-md shadow-[0_12px_32px_rgba(0,0,0,0.65)] flex items-center gap-2 text-xs">
- <CheckCircle2 className="w-3.5 h-3.5 text-[var(--accent)]" />
- <span className="font-medium">{toastMessage}</span>
- </div>
- )}
-
- {/* Manga Effect Lines Generator Modal */}
- <MangaEffectsModal
- isOpen={isMangaEffectsModalOpen}
- onClose={() => setIsMangaEffectsModalOpen(false)}
- canvasWidth={dimensions.width}
- canvasHeight={dimensions.height}
- onApply={handleApplyMangaEffects}
- />
-
- {/* Webtoon Chapter Slicer & Zip Exporter Modal */}
- <WebtoonExportModal
- isOpen={isWebtoonExportModalOpen}
- onClose={() => setIsWebtoonExportModalOpen(false)}
- getActiveCanvas={() =>
- compositeCanvas(
- dimensions,
- layers,
- layerCanvasesRef.current,
- getEffectiveOpacity,
- isLayerEffectivelyVisible,
- false,
- documentStore.getActiveTileGrid()
- )
- }
- canvasWidth={dimensions.width}
- canvasHeight={dimensions.height}
- documentTitle={documents.find((d) => d.id === activeDocumentId)?.name || 'webtoon_chapter'}
+ <ModalHost
+ layers={layerMgr.layers}
+ activeLayer={layerMgr.activeLayer}
+ layerCanvasesRef={layerMgr.layerCanvasesRef}
+ getEffectiveOpacity={layerMgr.getEffectiveOpacity}
+ isLayerEffectivelyVisible={layerMgr.isLayerEffectivelyVisible}
+ handleCreateNewCanvas={docLifecycle.handleCreateNewCanvas}
+ handleResizeCanvas={docLifecycle.handleResizeCanvas}
+ handleUpdateSettings={docLifecycle.handleUpdateSettings}
+ handleRestoreCrashedSession={docLifecycle.handleRestoreCrashedSession}
+ handleDiscardCrashedSession={docLifecycle.handleDiscardCrashedSession}
+ handleTonalCancel={tonalActions.handleTonalCancel}
+ handleTonalApply={tonalActions.handleTonalApply}
+ handleTonalPreviewChange={tonalActions.handleTonalPreviewChange}
+ handleApplyAdjustment={tonalActions.handleApplyAdjustment}
+ handleApplyLayerStyles={tonalActions.handleApplyLayerStyles}
+ handleConfirmTone={tonalActions.handleConfirmTone}
+ handleApplyMangaEffects={tonalActions.handleApplyMangaEffects}
+ isHostModalOpen={collab.isHostModalOpen}
+ setIsHostModalOpen={collab.setIsHostModalOpen}
+ isCollabHost={collab.isHost}
+ isCollabConnected={collab.isConnected}
+ collabHostInfo={collab.hostInfo}
+ collabPeers={collab.peers}
+ collabMyPeer={collab.myPeer}
+ updateMyName={collab.updateMyName}
+ handleStartHosting={collab.handleStartHosting}
+ stopHosting={collab.stopHosting}
+ clipboardInvite={collab.clipboardInvite}
+ setClipboardInvite={collab.setClipboardInvite}
+ webLandingInvite={collab.webLandingInvite}
+ setWebLandingInvite={collab.setWebLandingInvite}
+ joinRoom={collab.joinRoom}
+ showToast={showToast}
/>
- </div>
+ </AppShell>
);
}
diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsx
new file mode 100644
index 0000000..4affa70
--- /dev/null
+++ b/src/components/AppShell.tsx
@@ -0,0 +1,882 @@
+import React, { useMemo, useCallback, useEffect } from 'react';
+import {
+ AnimationTimeline,
+ BlendMode,
+ CanvasSelection,
+ ExpressionColor,
+ HistoryItemMeta,
+ LayerItem,
+ MenuSection,
+ SpeechBalloon,
+ TransformSession,
+} from '../types/editor';
+import { CollabPeer } from '../types/multiplayer';
+import { SparseTileGrid } from '../utils/tileEngine';
+import { RecentDocument } from '../utils/recentDocumentsManager';
+import {
+ getAccentContrastColor,
+ hexToRgb,
+ resolveModernAccentColor,
+} from '../types/settings';
+import { CanvasNavigationHandle } from '../hooks/useCanvasNavigation';
+import { TextPlacementSession } from '../hooks/drawing/useShapeAndFillTools';
+import {
+ documentStoreActions,
+ selectHasOpenDocument,
+ toolStoreActions,
+ uiStoreActions,
+ useDocumentStore,
+ useToolStore,
+ useUiStore,
+ useWorkspaceStore,
+} from '../stores';
+import { Header } from './Header';
+import { WelcomeScreen } from './WelcomeScreen';
+import { CanvasArea } from './CanvasArea';
+import { DocumentTabBar } from './DocumentTabBar';
+import { StatusBar } from './StatusBar';
+import { DockWorkspace } from './DockWorkspace';
+import { WorkspaceCommandHandlers } from './CommandBar';
+
+interface CanvasAreaContainerProps {
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ onViewportReady: (viewport: HTMLDivElement) => void;
+ zoom: number;
+ pan: { x: number; y: number };
+ rotation: number;
+ flipX: boolean;
+ flipY: boolean;
+ navigation: CanvasNavigationHandle;
+ isSpaceDown: boolean;
+ isShiftDown: boolean;
+ isRotateModifier: boolean;
+ isPanning: boolean;
+ isRotating: boolean;
+ startPan: (e: React.PointerEvent) => void;
+ startRotate: (e: React.PointerEvent) => void;
+ isHovering: boolean;
+ cursorPos: { x: number; y: number } | null;
+ onPointerDown: (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => void;
+ onPointerMove: (
+ e: React.PointerEvent<HTMLElement>,
+ coalescedEvents?: PointerEvent[],
+ predictedEvents?: PointerEvent[]
+ ) => void;
+ onPointerUp: (e: React.PointerEvent<HTMLElement>) => void;
+ onPointerEnter: () => void;
+ onPointerLeave: () => void;
+ layers: LayerItem[];
+ activeLayerId: string;
+ tileGrid: SparseTileGrid;
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ registerLayerCanvas: (id: string, canvas: HTMLCanvasElement | null) => void;
+ getEffectiveOpacity: (layer: LayerItem) => number;
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
+ interactionRef: React.RefObject<HTMLDivElement | null>;
+ draftCanvasRef: React.RefObject<HTMLCanvasElement | null>;
+ strokeCanvasRef: React.RefObject<HTMLCanvasElement | null>;
+ peers: CollabPeer[];
+ activePings: Array<{ id: string; x: number; y: number; color: string; name: string }>;
+ remoteDraftCanvasesRef: React.MutableRefObject<Map<string | number, HTMLCanvasElement>>;
+ selection: CanvasSelection | null;
+ onDeselect: () => void;
+ onTransformSelection: () => void;
+ onFillScreentone: () => void;
+ onFillColor: () => void;
+ onClearSelection: () => void;
+ onInvertSelection: () => void;
+ onExpandSelection: (pixels?: number) => void;
+ onContractSelection: (pixels?: number) => void;
+ onFeatherSelection: (radius?: number) => void;
+ transformSession: TransformSession | null;
+ setTransformSession: React.Dispatch<React.SetStateAction<TransformSession | null>>;
+ onApplyTransform: () => void;
+ onCancelTransform: () => void;
+ textSession: TextPlacementSession | null;
+ setTextSession: React.Dispatch<React.SetStateAction<TextPlacementSession | null>>;
+ onConfirmText: () => void;
+ onCancelText: () => void;
+ onInsertRasterLayer: (layer: LayerItem, canvas: HTMLCanvasElement) => void;
+ activeBalloon: SpeechBalloon | null;
+ setActiveBalloon: React.Dispatch<React.SetStateAction<SpeechBalloon | null>>;
+ onConfirmBalloon: () => void;
+ onDeleteBalloon: () => void;
+ animationTimeline: AnimationTimeline | null;
+ onUpdateAnimationTimeline: (timeline: AnimationTimeline | null) => void;
+ onAddAnimationCel: (frameIndex: number) => void;
+ onDeleteAnimationCel: (frameIndex: number) => void;
+ onSelectCelLayer: (layerId: string) => void;
+}
+
+/**
+ * Isolated store-connected CanvasArea wrapper so tool/brush/color changes only
+ * re-render CanvasArea without re-rendering AppShell, Header, or RightSidebar.
+ */
+const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((props) => {
+ const tool = useToolStore((s) => s.tool);
+ const brushSettings = useToolStore((s) => s.brushSettings);
+ const liquifySettings = useToolStore((s) => s.liquifySettings);
+ const primaryColor = useToolStore((s) => s.primaryColor);
+
+ const dimensions = useDocumentStore((s) => s.dimensions);
+ const colorMode = useDocumentStore((s) => s.colorMode);
+ const hasOpenDocument = useDocumentStore(selectHasOpenDocument);
+ const perspectiveRuler = useDocumentStore((s) => s.perspectiveRuler);
+ const activeLockedAxis = useDocumentStore((s) => s.activeLockedAxis);
+ const softProofSettings = useDocumentStore((s) => s.softProofSettings);
+
+ const showCheckerboard = useUiStore((s) => s.appSettings.showCheckerboard);
+ const showCursorCoordinates = useUiStore((s) => s.appSettings.showCursorCoordinates);
+ const showPressureInStatusBar = useUiStore((s) => s.appSettings.showPressureInStatusBar);
+ const is3DLayerOpen = useUiStore((s) => s.is3DLayerOpen);
+ const initial3DFile = useUiStore((s) => s.initial3DFile);
+ const isWebtoonMode = useUiStore((s) => s.isWebtoonMode);
+
+ const handleClose3DLayer = useCallback(() => {
+ uiStoreActions.set3DLayerOpen(false, null);
+ }, []);
+
+ const handleToggleWebtoon = useCallback(() => {
+ uiStoreActions.toggleWebtoonMode();
+ }, []);
+
+ const handleOpenWebtoonExport = useCallback(() => {
+ uiStoreActions.setWebtoonExportModalOpen(true);
+ }, []);
+
+ const handleUpdateTransformSession = useCallback(
+ (updater: (prev: TransformSession) => TransformSession) => {
+ props.setTransformSession((prev) => (prev ? updater(prev) : null));
+ },
+ [props.setTransformSession]
+ );
+
+ const handleUpdateTextSettings = useCallback(
+ (updater: (prev: TextPlacementSession['settings']) => TextPlacementSession['settings']) => {
+ props.setTextSession((prev) => (prev ? { ...prev, settings: updater(prev.settings) } : null));
+ },
+ [props.setTextSession]
+ );
+
+ const handleMoveTextSession = useCallback(
+ (newX: number, newY: number) => {
+ props.setTextSession((prev) => (prev ? { ...prev, x: newX, y: newY } : null));
+ },
+ [props.setTextSession]
+ );
+
+ const handleUpdateBalloon = useCallback(
+ (updater: (prev: SpeechBalloon) => SpeechBalloon) => {
+ props.setActiveBalloon((prev) => (prev ? updater(prev) : null));
+ },
+ [props.setActiveBalloon]
+ );
+
+ return (
+ <CanvasArea
+ viewportRef={props.viewportRef}
+ onViewportReady={props.onViewportReady}
+ dimensions={dimensions}
+ brushSettings={brushSettings}
+ onUpdateBrushSettings={toolStoreActions.updateBrushSettings}
+ zoom={props.zoom}
+ pan={props.pan}
+ rotation={props.rotation}
+ flipX={props.flipX}
+ flipY={props.flipY}
+ navigation={props.navigation}
+ isSpaceDown={props.isSpaceDown}
+ isShiftDown={props.isShiftDown}
+ isRotateModifier={props.isRotateModifier}
+ isPanning={props.isPanning}
+ isRotating={props.isRotating}
+ onStartPan={props.startPan}
+ onStartRotate={props.startRotate}
+ isHovering={props.isHovering}
+ cursorPos={props.cursorPos}
+ onPointerDown={props.onPointerDown}
+ onPointerMove={props.onPointerMove}
+ onPointerUp={props.onPointerUp}
+ onPointerEnter={props.onPointerEnter}
+ onPointerLeave={props.onPointerLeave}
+ layers={props.layers}
+ activeLayerId={props.activeLayerId}
+ colorMode={colorMode}
+ tileGrid={props.tileGrid}
+ layerCanvasesRef={props.layerCanvasesRef}
+ registerLayerCanvas={props.registerLayerCanvas}
+ getEffectiveOpacity={props.getEffectiveOpacity}
+ isLayerEffectivelyVisible={props.isLayerEffectivelyVisible}
+ interactionRef={props.interactionRef}
+ showCheckerboard={showCheckerboard}
+ showCursorCoordinates={showCursorCoordinates}
+ showPressureInStatusBar={showPressureInStatusBar}
+ hasOpenDocument={hasOpenDocument}
+ draftCanvasRef={props.draftCanvasRef}
+ strokeCanvasRef={props.strokeCanvasRef}
+ peers={props.peers}
+ activePings={props.activePings}
+ remoteDraftCanvasesRef={props.remoteDraftCanvasesRef}
+ tool={tool}
+ liquifySettings={liquifySettings}
+ onUpdateLiquifySettings={toolStoreActions.updateLiquifySettings}
+ primaryColor={primaryColor}
+ onSwapColors={toolStoreActions.swapColors}
+ selection={props.selection}
+ onDeselect={props.onDeselect}
+ onTransformSelection={props.onTransformSelection}
+ onFillScreentone={props.onFillScreentone}
+ onFillColor={props.onFillColor}
+ onClearSelection={props.onClearSelection}
+ onInvertSelection={props.onInvertSelection}
+ onExpandSelection={props.onExpandSelection}
+ onContractSelection={props.onContractSelection}
+ onFeatherSelection={props.onFeatherSelection}
+ transformSession={props.transformSession}
+ onUpdateTransformSession={handleUpdateTransformSession}
+ onApplyTransform={props.onApplyTransform}
+ onCancelTransform={props.onCancelTransform}
+ textSession={props.textSession}
+ onUpdateTextSettings={handleUpdateTextSettings}
+ onMoveTextSession={handleMoveTextSession}
+ onConfirmText={props.onConfirmText}
+ onCancelText={props.onCancelText}
+ perspectiveRuler={hasOpenDocument ? perspectiveRuler : null}
+ onUpdatePerspectiveRuler={documentStoreActions.setPerspectiveRuler}
+ activeLockedAxis={activeLockedAxis}
+ is3DLayerOpen={is3DLayerOpen}
+ initial3DFile={initial3DFile}
+ onClose3DLayer={handleClose3DLayer}
+ onInsertRasterLayer={props.onInsertRasterLayer}
+ isWebtoonMode={isWebtoonMode}
+ onToggleWebtoonMode={handleToggleWebtoon}
+ onOpenWebtoonExport={handleOpenWebtoonExport}
+ activeBalloon={props.activeBalloon}
+ onUpdateBalloon={handleUpdateBalloon}
+ onConfirmBalloon={props.onConfirmBalloon}
+ onDeleteBalloon={props.onDeleteBalloon}
+ animationTimeline={props.animationTimeline}
+ onUpdateAnimationTimeline={props.onUpdateAnimationTimeline}
+ onAddAnimationCel={props.onAddAnimationCel}
+ onDeleteAnimationCel={props.onDeleteAnimationCel}
+ onSelectCelLayer={props.onSelectCelLayer}
+ softProofSettings={softProofSettings}
+ />
+ );
+});
+CanvasAreaContainer.displayName = 'CanvasAreaContainer';
+
+interface StatusBarContainerProps {
+ zoom: number;
+ rotation: number;
+ onResetRotation: () => void;
+}
+
+/**
+ * Isolated store-connected StatusBar wrapper so brush/tool changes only
+ * re-render StatusBar without re-rendering AppShell, Header, or Layers.
+ */
+const StatusBarContainer: React.FC<StatusBarContainerProps> = React.memo(
+ ({ zoom, rotation, onResetRotation }) => {
+ const tool = useToolStore((s) => s.tool);
+ const brushSettings = useToolStore((s) => s.brushSettings);
+ const colorMode = useDocumentStore((s) => s.colorMode);
+ const hasOpenDocument = useDocumentStore(selectHasOpenDocument);
+ const softProofSettings = useDocumentStore((s) => s.softProofSettings);
+ const showCursorCoordinates = useUiStore((s) => s.appSettings.showCursorCoordinates);
+ const showPressureInStatusBar = useUiStore((s) => s.appSettings.showPressureInStatusBar);
+ const themePreset = useUiStore((s) => s.appSettings.themePreset);
+
+ return (
+ <StatusBar
+ tool={tool}
+ brushSettings={brushSettings}
+ zoom={zoom}
+ rotation={rotation}
+ onResetRotation={onResetRotation}
+ colorMode={colorMode}
+ showCursorCoordinates={showCursorCoordinates}
+ showPressureInStatusBar={showPressureInStatusBar}
+ hasOpenDocument={hasOpenDocument}
+ themePreset={themePreset}
+ softProofSettings={softProofSettings}
+ />
+ );
+ }
+);
+StatusBarContainer.displayName = 'StatusBarContainer';
+
+export interface AppShellProps {
+ fileInputRef: React.RefObject<HTMLInputElement | null>;
+ pasteFileInputRef: React.RefObject<HTMLInputElement | null>;
+ import3DFileInputRef: React.RefObject<HTMLInputElement | null>;
+ handleFileInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ handlePasteFileInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ handleImport3DFileInputChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ // Header props
+ canUndo: boolean;
+ canRedo: boolean;
+ handleUndo: () => void;
+ redo: () => void;
+ zoom: number;
+ zoomIn: () => void;
+ zoomOut: () => void;
+ resetZoomAndCenter: () => void;
+ rotation: number;
+ resetRotation: () => void;
+ flipX: boolean;
+ flipY: boolean;
+ toggleFlipHorizontal: () => void;
+ toggleFlipVertical: () => void;
+ resetViewFlip: () => void;
+ menuSections: MenuSection[];
+ handleSelectDocument: (id: string) => void;
+ handleCloseDocument: (id: string) => void;
+ handleRenameDocument: (id: string, newName: string) => void;
+ handleSave: () => void;
+ handleSaveAs: () => void;
+ handleClearActiveLayer: () => void;
+ handleMergeDown: () => void;
+ isCollabConnected: boolean;
+ collabPeerCount: number;
+ onOpenCollabModal: () => void;
+ // Welcome props
+ handleTriggerOpenFile: () => void;
+ handleSelectWelcomeDocument: (doc: RecentDocument) => void;
+ showToast: (msg: string) => void;
+ // Canvas & Drawing props
+ canvasProps: CanvasAreaContainerProps;
+ // RightSidebar props
+ historyList: HistoryItemMeta[];
+ historyIndex: number;
+ jumpToHistoryIndex: (index: number) => void;
+ layers: LayerItem[];
+ activeLayerId: string;
+ selectedLayerIds: string[];
+ setActiveLayerId: (id: string) => void;
+ toggleLayerSelection: (id: string, isShift: boolean, isCtrl: boolean) => void;
+ handleGroupSelectedLayers: () => void;
+ handleDeleteSelectedLayers: () => void;
+ handleAddLayer: (type?: 'raster' | 'folder') => void;
+ duplicateLayer: (id: string) => void;
+ handleDeleteLayer: (id: string) => void;
+ handleToggleVisibility: (id: string) => void;
+ handleSetOpacity: (id: string, opacity: number) => void;
+ setBlendMode: (id: string, blendMode: BlendMode) => void;
+ toggleLock: (id: string) => void;
+ toggleAlphaLock: (id: string) => void;
+ toggleClipping: (id: string) => void;
+ toggleCollapse: (id: string) => void;
+ handleRenameLayer: (id: string, name: string) => void;
+ moveLayer: (id: string, direction: 'up' | 'down') => void;
+ moveLayerToFolder: (id: string, targetFolderId: string | null) => void;
+ reorderLayers: (draggedId: string, targetId: string, position: 'above' | 'below' | 'inside') => void;
+ handleToggleReferenceLayer: (id: string) => void;
+ toggleTone: (id: string) => void;
+ setToneFrequency: (id: string, frequency: number) => void;
+ setToneAngle: (id: string, angle: number) => void;
+ setToneDotShape: (id: string, dotShape: 'circle' | 'euclidean') => void;
+ setToneDensity: (id: string, density: number) => void;
+ setToneDensityType: (id: string, densityType: 'specified' | 'image') => void;
+ toggleLayerColor: (id: string) => void;
+ setLayerColor: (id: string, color: string) => void;
+ setLayerSubColor: (id: string, color: string) => void;
+ setLayerExpressionColor: (id: string, mode: ExpressionColor) => void;
+ setLayerMonoThreshold: (id: string, threshold: number) => void;
+ setLayerMonoExpressMode: (id: string, expressBlack: boolean, expressWhite: boolean) => void;
+ handleApplyExpressionColor: (id: string) => void;
+ handleApplyLayerColor: (id: string) => void;
+ addLayerMask: (layerId: string) => void;
+ removeLayerMask: (layerId: string, apply?: boolean) => void;
+ toggleLayerMask: (layerId: string) => void;
+ toggleMaskLinked: (layerId: string) => void;
+ handleOpenAdjustmentModal: (
+ layerId?: string,
+ initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance'
+ ) => void;
+ handleOpenLayerStylesModal: (layerId?: string) => void;
+ children?: React.ReactNode;
+}
+
+export const AppShell: React.FC<AppShellProps> = React.memo(
+ ({
+ fileInputRef,
+ pasteFileInputRef,
+ import3DFileInputRef,
+ handleFileInputChange,
+ handlePasteFileInputChange,
+ handleImport3DFileInputChange,
+ canUndo,
+ canRedo,
+ handleUndo,
+ redo,
+ zoom,
+ zoomIn,
+ zoomOut,
+ resetZoomAndCenter,
+ rotation,
+ resetRotation,
+ flipX,
+ flipY,
+ toggleFlipHorizontal,
+ toggleFlipVertical,
+ resetViewFlip,
+ menuSections,
+ handleSelectDocument,
+ handleCloseDocument,
+ handleRenameDocument,
+ handleSave,
+ handleSaveAs,
+ handleClearActiveLayer,
+ handleMergeDown,
+ isCollabConnected,
+ collabPeerCount,
+ onOpenCollabModal,
+ handleTriggerOpenFile,
+ handleSelectWelcomeDocument,
+ showToast,
+ canvasProps,
+ historyList,
+ historyIndex,
+ jumpToHistoryIndex,
+ layers,
+ activeLayerId,
+ selectedLayerIds,
+ setActiveLayerId,
+ toggleLayerSelection,
+ handleGroupSelectedLayers,
+ handleDeleteSelectedLayers,
+ handleAddLayer,
+ duplicateLayer,
+ handleDeleteLayer,
+ handleToggleVisibility,
+ handleSetOpacity,
+ setBlendMode,
+ toggleLock,
+ toggleAlphaLock,
+ toggleClipping,
+ toggleCollapse,
+ handleRenameLayer,
+ moveLayer,
+ moveLayerToFolder,
+ reorderLayers,
+ handleToggleReferenceLayer,
+ toggleTone,
+ setToneFrequency,
+ setToneAngle,
+ setToneDotShape,
+ setToneDensity,
+ setToneDensityType,
+ toggleLayerColor,
+ setLayerColor,
+ setLayerSubColor,
+ setLayerExpressionColor,
+ setLayerMonoThreshold,
+ setLayerMonoExpressMode,
+ handleApplyExpressionColor,
+ handleApplyLayerColor,
+ addLayerMask,
+ removeLayerMask,
+ toggleLayerMask,
+ toggleMaskLinked,
+ handleOpenAdjustmentModal,
+ handleOpenLayerStylesModal,
+ children,
+ }) => {
+ const dimensions = useDocumentStore((s) => s.dimensions);
+ const colorMode = useDocumentStore((s) => s.colorMode);
+ const documents = useDocumentStore((s) => s.documents);
+ const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
+ const hasOpenDocument = useDocumentStore(selectHasOpenDocument);
+ const softProofSettings = useDocumentStore((s) => s.softProofSettings);
+ const activeEditTarget = useDocumentStore((s) => s.activeEditTarget);
+
+ const appView = useUiStore((s) => s.appView);
+ const modernAccent = useUiStore((s) => s.appSettings.modernAccent || 'neutral');
+ const modernCustomColor = useUiStore((s) => s.appSettings.modernCustomColor);
+ const themePreset = useUiStore((s) => s.appSettings.themePreset);
+ const userName = useUiStore((s) => s.appSettings.userName);
+ const showStatusBar = useWorkspaceStore((s) => s.showStatusBar);
+ const showDocumentTabs = useWorkspaceStore((s) => s.showDocumentTabs);
+
+ useEffect(() => {
+ const hex = resolveModernAccentColor(modernAccent, modernCustomColor);
+ const rgb = hexToRgb(hex) || { r: 229, g: 229, b: 229 };
+ const contrast = getAccentContrastColor(hex);
+
+ const root = document.documentElement;
+ root.setAttribute('data-theme', themePreset);
+ root.setAttribute('data-accent', modernAccent);
+ root.style.setProperty('--accent', hex);
+ root.style.setProperty('--accent-rgb', `${rgb.r}, ${rgb.g}, ${rgb.b}`);
+ root.style.setProperty('--accent-contrast', contrast);
+ root.style.setProperty('--accent-subtle', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.14)`);
+ root.style.setProperty('--accent-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.32)`);
+ root.style.setProperty('--modern-accent', hex);
+ root.style.setProperty('--modern-accent-rgb', `${rgb.r}, ${rgb.g}, ${rgb.b}`);
+ root.style.setProperty('--modern-accent-subtle', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.14)`);
+ root.style.setProperty('--modern-accent-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.32)`);
+ root.style.setProperty('--modern-accent-hover', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.2)`);
+ }, [modernAccent, modernCustomColor, themePreset]);
+
+ const modernAccentHex = resolveModernAccentColor(modernAccent, modernCustomColor);
+ const modernAccentRgb = hexToRgb(modernAccentHex) || { r: 229, g: 229, b: 229 };
+ const modernAccentContrast = getAccentContrastColor(modernAccentHex);
+
+ const modernStyleVars = useMemo(
+ () =>
+ ({
+ '--accent': modernAccentHex,
+ '--accent-rgb': `${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}`,
+ '--accent-contrast': modernAccentContrast,
+ '--accent-subtle': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.14)`,
+ '--accent-border': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.32)`,
+ '--modern-accent': modernAccentHex,
+ '--modern-accent-rgb': `${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}`,
+ '--modern-accent-subtle': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.14)`,
+ '--modern-accent-border': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.32)`,
+ '--modern-accent-hover': `rgba(${modernAccentRgb.r}, ${modernAccentRgb.g}, ${modernAccentRgb.b}, 0.2)`,
+ }) as React.CSSProperties,
+ [
+ modernAccentHex,
+ modernAccentRgb.r,
+ modernAccentRgb.g,
+ modernAccentRgb.b,
+ modernAccentContrast,
+ ]
+ );
+
+ const handleOpenNewCanvas = useCallback(() => {
+ uiStoreActions.setNewCanvasModalOpen(true);
+ }, []);
+
+ const handleOpenSettings = useCallback(() => {
+ uiStoreActions.setSettingsModalOpen(true);
+ }, []);
+
+ const handleOpen3DLayer = useCallback(() => {
+ uiStoreActions.set3DLayerOpen(true);
+ }, []);
+
+ const handleSelectAppView = useCallback(
+ (view: 'home' | 'workspace') => {
+ if (view === 'workspace' && !hasOpenDocument) {
+ uiStoreActions.setNewCanvasModalOpen(true);
+ } else {
+ uiStoreActions.setAppView(view);
+ }
+ },
+ [hasOpenDocument]
+ );
+
+ const handleToggleTransparentColor = useCallback(() => {
+ const next = toolStoreActions.toggleTransparentColor();
+ showToast(next ? 'Transparent ink mode active' : 'Color ink mode active');
+ }, [showToast]);
+
+ const handleSwapColors = useCallback(() => {
+ toolStoreActions.swapColors(colorMode);
+ }, [colorMode]);
+
+ const handleNewRasterLayer = useCallback(() => {
+ handleAddLayer('raster');
+ }, [handleAddLayer]);
+
+ const handleDuplicateActiveLayer = useCallback(() => {
+ if (activeLayerId) duplicateLayer(activeLayerId);
+ }, [activeLayerId, duplicateLayer]);
+
+ const commandHandlers = useMemo<WorkspaceCommandHandlers>(
+ () => ({
+ canUndo: hasOpenDocument && canUndo,
+ canRedo: hasOpenDocument && canRedo,
+ onUndo: handleUndo,
+ onRedo: redo,
+ onSave: handleSave,
+ onSaveAs: handleSaveAs,
+ onNewLayer: handleNewRasterLayer,
+ onDuplicateLayer: handleDuplicateActiveLayer,
+ onClearLayer: handleClearActiveLayer,
+ onMergeDown: handleMergeDown,
+ onFlipHorizontal: toggleFlipHorizontal,
+ onFlipVertical: toggleFlipVertical,
+ flipX,
+ flipY,
+ onResetZoom: resetZoomAndCenter,
+ onResetRotation: resetRotation,
+ onTransform: canvasProps.onTransformSelection,
+ onDeselect: canvasProps.onDeselect,
+ onSwapColors: handleSwapColors,
+ onToggleTransparentColor: handleToggleTransparentColor,
+ hasOpenDocument,
+ }),
+ [
+ hasOpenDocument,
+ canUndo,
+ canRedo,
+ handleUndo,
+ redo,
+ handleSave,
+ handleSaveAs,
+ handleNewRasterLayer,
+ handleDuplicateActiveLayer,
+ handleClearActiveLayer,
+ handleMergeDown,
+ toggleFlipHorizontal,
+ toggleFlipVertical,
+ flipX,
+ flipY,
+ resetZoomAndCenter,
+ resetRotation,
+ canvasProps.onTransformSelection,
+ canvasProps.onDeselect,
+ handleSwapColors,
+ handleToggleTransparentColor,
+ ]
+ );
+
+ const layerSidebarProps = useMemo(
+ () => ({
+ hasOpenDocument,
+ onNewCanvas: handleOpenNewCanvas,
+ onOpenFile: handleTriggerOpenFile,
+ colorMode,
+ historyList: hasOpenDocument ? historyList : [],
+ historyIndex: hasOpenDocument ? historyIndex : -1,
+ onJumpToHistory: jumpToHistoryIndex,
+ canUndo: hasOpenDocument && canUndo,
+ canRedo: hasOpenDocument && canRedo,
+ onUndo: handleUndo,
+ onRedo: redo,
+ layers: hasOpenDocument ? layers : [],
+ activeLayerId: hasOpenDocument ? activeLayerId : '',
+ selectedLayerIds: hasOpenDocument ? selectedLayerIds : [],
+ onSelectLayer: setActiveLayerId,
+ onToggleLayerSelection: toggleLayerSelection,
+ onGroupSelectedLayers: handleGroupSelectedLayers,
+ onDeleteSelectedLayers: handleDeleteSelectedLayers,
+ onAddLayer: handleAddLayer,
+ onOpen3DLayer: hasOpenDocument ? handleOpen3DLayer : undefined,
+ onDuplicateLayer: duplicateLayer,
+ onDeleteLayer: handleDeleteLayer,
+ onToggleVisibility: handleToggleVisibility,
+ onSetOpacity: handleSetOpacity,
+ onSetBlendMode: setBlendMode,
+ onToggleLock: toggleLock,
+ onToggleAlphaLock: toggleAlphaLock,
+ onToggleClipping: toggleClipping,
+ onToggleCollapse: toggleCollapse,
+ onRenameLayer: handleRenameLayer,
+ onMoveLayer: moveLayer,
+ onMoveLayerToFolder: moveLayerToFolder,
+ onReorderLayers: reorderLayers,
+ onToggleReferenceLayer: handleToggleReferenceLayer,
+ onToggleTone: toggleTone,
+ onSetToneFrequency: setToneFrequency,
+ onSetToneAngle: setToneAngle,
+ onSetToneDotShape: setToneDotShape,
+ onSetToneDensity: setToneDensity,
+ onSetToneDensityType: setToneDensityType,
+ onToggleLayerColor: toggleLayerColor,
+ onSetLayerColor: setLayerColor,
+ onSetLayerSubColor: setLayerSubColor,
+ onSetLayerExpressionColor: setLayerExpressionColor,
+ onSetLayerMonoThreshold: setLayerMonoThreshold,
+ onSetLayerMonoExpressMode: setLayerMonoExpressMode,
+ onApplyExpressionColor: handleApplyExpressionColor,
+ onApplyLayerColor: handleApplyLayerColor,
+ activeEditTarget,
+ onSelectEditTarget: documentStoreActions.setActiveEditTarget,
+ onAddLayerMask: addLayerMask,
+ onRemoveLayerMask: removeLayerMask,
+ onToggleLayerMask: toggleLayerMask,
+ onToggleMaskLinked: toggleMaskLinked,
+ onOpenAdjustmentModal: handleOpenAdjustmentModal,
+ onOpenLayerStylesModal: handleOpenLayerStylesModal,
+ }),
+ [
+ hasOpenDocument,
+ handleOpenNewCanvas,
+ handleTriggerOpenFile,
+ colorMode,
+ historyList,
+ historyIndex,
+ jumpToHistoryIndex,
+ canUndo,
+ canRedo,
+ handleUndo,
+ redo,
+ layers,
+ activeLayerId,
+ selectedLayerIds,
+ setActiveLayerId,
+ toggleLayerSelection,
+ handleGroupSelectedLayers,
+ handleDeleteSelectedLayers,
+ handleAddLayer,
+ handleOpen3DLayer,
+ duplicateLayer,
+ handleDeleteLayer,
+ handleToggleVisibility,
+ handleSetOpacity,
+ setBlendMode,
+ toggleLock,
+ toggleAlphaLock,
+ toggleClipping,
+ toggleCollapse,
+ handleRenameLayer,
+ moveLayer,
+ moveLayerToFolder,
+ reorderLayers,
+ handleToggleReferenceLayer,
+ toggleTone,
+ setToneFrequency,
+ setToneAngle,
+ setToneDotShape,
+ setToneDensity,
+ setToneDensityType,
+ toggleLayerColor,
+ setLayerColor,
+ setLayerSubColor,
+ setLayerExpressionColor,
+ setLayerMonoThreshold,
+ setLayerMonoExpressMode,
+ handleApplyExpressionColor,
+ handleApplyLayerColor,
+ activeEditTarget,
+ addLayerMask,
+ removeLayerMask,
+ toggleLayerMask,
+ toggleMaskLinked,
+ handleOpenAdjustmentModal,
+ handleOpenLayerStylesModal,
+ ]
+ );
+
+ return (
+ <div
+ className="flex flex-col w-screen h-screen overflow-hidden bg-[#161616] text-[#e5e5e5] font-sans gap-px app-root-container"
+ data-theme={themePreset}
+ data-accent={modernAccent}
+ style={modernStyleVars}
+ >
+ {/* Hidden File Inputs */}
+ <input
+ ref={fileInputRef}
+ type="file"
+ accept=".png,.jpg,.jpeg,.webp,.bmp,.gif,.svg,.psd,.psb,.clip,.csp,.sora,.ink,.sut"
+ onChange={handleFileInputChange}
+ className="hidden"
+ />
+ <input
+ ref={pasteFileInputRef}
+ type="file"
+ accept=".png,.jpg,.jpeg,.webp,.bmp,.gif,.svg,.ico,image/*"
+ onChange={handlePasteFileInputChange}
+ className="hidden"
+ />
+ <input
+ ref={import3DFileInputRef}
+ type="file"
+ accept=".glb,.gltf,.obj"
+ onChange={handleImport3DFileInputChange}
+ className="hidden"
+ />
+
+ {/* Consolidated Single Slim 36px Header Bar */}
+ <Header
+ canUndo={hasOpenDocument && canUndo}
+ canRedo={hasOpenDocument && canRedo}
+ onUndo={handleUndo}
+ onRedo={redo}
+ zoom={zoom}
+ onZoomIn={zoomIn}
+ onZoomOut={zoomOut}
+ onResetZoom={resetZoomAndCenter}
+ rotation={rotation}
+ onResetRotation={resetRotation}
+ flipX={flipX}
+ flipY={flipY}
+ onToggleFlipHorizontal={toggleFlipHorizontal}
+ onToggleFlipVertical={toggleFlipVertical}
+ onResetViewFlip={resetViewFlip}
+ dimensions={dimensions}
+ colorMode={colorMode}
+ menuSections={menuSections}
+ hasOpenDocument={hasOpenDocument}
+ documents={documents}
+ activeDocumentId={activeDocumentId}
+ onSelectDocument={handleSelectDocument}
+ onCloseDocument={handleCloseDocument}
+ onNewDocument={handleOpenNewCanvas}
+ onRenameDocument={handleRenameDocument}
+ commandHandlers={commandHandlers}
+ isCollabConnected={isCollabConnected}
+ collabPeerCount={collabPeerCount}
+ onOpenCollabModal={onOpenCollabModal}
+ onOpenSettings={handleOpenSettings}
+ themePreset={themePreset}
+ softProofSettings={softProofSettings}
+ appView={appView}
+ onSelectAppView={handleSelectAppView}
+ />
+
+ {/* Main Workspace */}
+ <div className="flex flex-1 min-h-0 overflow-hidden relative gap-px bg-[#161616]">
+ {!hasOpenDocument || appView === 'home' ? (
+ <WelcomeScreen
+ userName={userName}
+ onNewDocument={handleOpenNewCanvas}
+ onOpenFile={handleTriggerOpenFile}
+ onSelectRecentDocument={handleSelectWelcomeDocument}
+ showToast={showToast}
+ themePreset={themePreset}
+ />
+ ) : (
+ <DockWorkspace
+ themePreset={themePreset}
+ colorMode={colorMode}
+ commandHandlers={commandHandlers}
+ onDeselect={canvasProps.onDeselect}
+ onTransformSelection={canvasProps.onTransformSelection}
+ onExpandSelection={canvasProps.onExpandSelection}
+ onContractSelection={canvasProps.onContractSelection}
+ onFeatherSelection={canvasProps.onFeatherSelection}
+ onInvertSelection={canvasProps.onInvertSelection}
+ onToggleTransparentColor={handleToggleTransparentColor}
+ layerSidebarProps={layerSidebarProps}
+ >
+ {showDocumentTabs && (
+ <DocumentTabBar
+ documents={documents}
+ activeDocumentId={activeDocumentId}
+ onSelectDocument={handleSelectDocument}
+ onCloseDocument={handleCloseDocument}
+ onNewDocument={handleOpenNewCanvas}
+ onRenameDocument={handleRenameDocument}
+ themePreset={themePreset}
+ />
+ )}
+
+ <div className="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden relative">
+ <CanvasAreaContainer {...canvasProps} />
+ </div>
+
+ {showStatusBar && (
+ <StatusBarContainer
+ zoom={zoom}
+ rotation={rotation}
+ onResetRotation={resetRotation}
+ />
+ )}
+ </DockWorkspace>
+ )}
+ </div>
+
+ {children}
+ </div>
+ );
+ }
+);
+
+AppShell.displayName = 'AppShell';
diff --git a/src/components/BrushSizePalette.tsx b/src/components/BrushSizePalette.tsx
index 2a60f61..ec2a1c8 100644
--- a/src/components/BrushSizePalette.tsx
+++ b/src/components/BrushSizePalette.tsx
@@ -9,9 +9,10 @@ import {
Sparkles,
} from 'lucide-react';
import { ToolType } from '../types/editor';
+import { ThemePreset } from '../types/settings';
import { BRUSH_SIZE_PRESETS } from '../utils/brushPresetManager';
-interface BrushSizePaletteProps {
+export interface BrushSizePaletteProps {
currentSize: number;
onSelectSize: (size: number) => void;
activeBrushName: string;
@@ -21,9 +22,10 @@ interface BrushSizePaletteProps {
onResetAllSettings?: () => void;
className?: string;
hideHeader?: boolean;
+ themePreset?: ThemePreset;
}
-export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
+export const BrushSizePalette: React.FC<BrushSizePaletteProps> = React.memo(({
currentSize,
onSelectSize,
activeBrushName,
@@ -33,9 +35,11 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
onResetAllSettings,
className = '',
hideHeader = false,
+ themePreset = 'modern',
}) => {
const [showMenu, setShowMenu] = useState(false);
const menuRef = useRef<HTMLDivElement>(null);
+ const isVintage = themePreset === 'vintage-manga';
useEffect(() => {
if (!showMenu) return;
@@ -48,7 +52,6 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
return () => window.removeEventListener('mousedown', handleOutsideClick);
}, [showMenu]);
- // Determine tool icon matching the active tool/preset
const renderToolIcon = () => {
if (tool === 'eraser') {
return <Eraser className="w-3.5 h-3.5 text-rose-400 shrink-0" />;
@@ -60,84 +63,75 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
return <Square className="w-3.5 h-3.5 text-teal-400 shrink-0" />;
}
if (presetId?.startsWith('csp-')) {
- return <Sparkles className="w-3.5 h-3.5 text-[#5ce1e6] shrink-0" />;
+ return (
+ <Sparkles
+ className={`w-3.5 h-3.5 shrink-0 ${
+ isVintage ? 'text-[#5ce1e6]' : 'text-[var(--accent)]'
+ }`}
+ />
+ );
}
- return <Paintbrush className="w-3.5 h-3.5 text-[#5ce1e6] shrink-0" />;
+ return (
+ <Paintbrush
+ className={`w-3.5 h-3.5 shrink-0 ${
+ isVintage ? 'text-[#5ce1e6]' : 'text-[var(--accent)]'
+ }`}
+ />
+ );
};
- // Renders the Clip Studio Paint style circle preview inside each cell
const renderSizeCircle = (size: number) => {
- if (size <= 0.7) {
- return <div className="w-[1.5px] h-[1.5px] rounded-full bg-white" />;
- }
- if (size <= 1) {
- return <div className="w-[2px] h-[2px] rounded-full bg-white" />;
- }
- if (size <= 1.5) {
- return <div className="w-[2.5px] h-[2.5px] rounded-full bg-white" />;
- }
- if (size <= 2) {
- return <div className="w-[3px] h-[3px] rounded-full bg-white" />;
- }
- if (size <= 2.5) {
- return <div className="w-[3.5px] h-[3.5px] rounded-full bg-white" />;
- }
- if (size <= 3) {
- return <div className="w-[4px] h-[4px] rounded-full bg-white" />;
- }
- if (size <= 4) {
- return <div className="w-[5px] h-[5px] rounded-full bg-white" />;
- }
- if (size <= 5) {
- return <div className="w-[6px] h-[6px] rounded-full bg-white" />;
- }
- if (size <= 6) {
- return <div className="w-[7px] h-[7px] rounded-full bg-white" />;
- }
- if (size <= 7) {
- return <div className="w-[8px] h-[8px] rounded-full bg-white" />;
- }
- if (size <= 8) {
- return <div className="w-[9.5px] h-[9.5px] rounded-full bg-white" />;
- }
- if (size <= 10) {
- return <div className="w-[11.5px] h-[11.5px] rounded-full bg-white" />;
- }
- if (size <= 12) {
- return <div className="w-[13.5px] h-[13.5px] rounded-full bg-white" />;
- }
- if (size <= 15) {
- return <div className="w-[15.5px] h-[15.5px] rounded-full bg-white" />;
- }
- if (size <= 17) {
- return <div className="w-[17.5px] h-[17.5px] rounded-full bg-white" />;
- }
- if (size <= 20) {
- return <div className="w-[19.5px] h-[19.5px] rounded-full bg-white" />;
- }
- if (size <= 25) {
- return (
- <div className="w-[22px] h-[16px] overflow-hidden flex items-end justify-center relative">
- <div className="w-[22px] h-[22px] rounded-full bg-white relative top-[3px]" />
- <div className="absolute bottom-0 w-full h-[1px] bg-[#666666]/60" />
- </div>
- );
+ const dotClass = isVintage ? 'bg-[#f0f0f4]' : 'bg-[#e5e5e5]';
+ const smallMap: Array<[number, number]> = [
+ [0.7, 1.5],
+ [1, 2],
+ [1.5, 2.5],
+ [2, 3],
+ [2.5, 3.5],
+ [3, 4],
+ [4, 5],
+ [5, 6],
+ [6, 7],
+ [7, 8],
+ [8, 9.5],
+ [10, 11.5],
+ [12, 13.5],
+ [15, 15.5],
+ [17, 17.5],
+ [20, 19.5],
+ ];
+ for (const [maxSize, px] of smallMap) {
+ if (size <= maxSize) {
+ return (
+ <div
+ className={`rounded-full ${dotClass}`}
+ style={{ width: `${px}px`, height: `${px}px` }}
+ />
+ );
+ }
}
if (size <= 30) {
+ const d = size <= 25 ? 22 : 24;
+ const top = size <= 25 ? 3 : 4;
return (
- <div className="w-[24px] h-[16px] overflow-hidden flex items-end justify-center relative">
- <div className="w-[24px] h-[24px] rounded-full bg-white relative top-[4px]" />
+ <div
+ className="h-[16px] overflow-hidden flex items-end justify-center relative"
+ style={{ width: `${d}px` }}
+ >
+ <div
+ className={`rounded-full ${dotClass} relative`}
+ style={{ width: `${d}px`, height: `${d}px`, top: `${top}px` }}
+ />
<div className="absolute bottom-0 w-full h-[1px] bg-[#666666]/60" />
</div>
);
}
- // Sizes >= 40: large dome filled white with flat bottom edge (CSP signature style)
- const domeDiameter = Math.min(32, 24 + Math.min(8, Math.log10(size / 30) * 4));
+ const domeDiameter = Math.min(30, 22 + Math.min(8, Math.log10(size / 30) * 4));
return (
- <div className="w-[28px] h-[16px] overflow-hidden flex items-end justify-center relative">
+ <div className="w-[26px] h-[16px] overflow-hidden flex items-end justify-center relative">
<div
- className="rounded-full bg-white relative"
+ className={`rounded-full ${dotClass} relative`}
style={{
width: `${domeDiameter}px`,
height: `${domeDiameter}px`,
@@ -150,24 +144,44 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
};
return (
- <div className={`flex flex-col select-none bg-[#1e2023] ${className}`}>
- {/* Header Bar matching Clip Studio Paint screenshot */}
+ <div
+ data-testid="brush-size-palette"
+ data-theme-preset={themePreset}
+ className={`flex flex-col h-full min-h-0 select-none ${
+ isVintage ? 'bg-[#363638] text-[#e5e5e5]' : 'bg-[#202020] text-[#e5e5e5]'
+ } ${className}`}
+ >
{!hideHeader && (
- <div className="h-8 px-2.5 flex items-center justify-between border-b border-[#2b2d31] bg-[#1a1b1e] shrink-0 text-white relative">
- <div className="flex items-center space-x-2 min-w-0">
- {/* Menu icon (≡) */}
+ <div
+ className={`h-7 px-2 flex items-center justify-between shrink-0 relative ${
+ isVintage
+ ? 'bg-gradient-to-b from-[#464649] to-[#363638] border-b border-[#232325] text-[#f0f0f4]'
+ : 'bg-[#1a1a1a] border-b border-white/[0.06] text-[#e5e5e5]'
+ }`}
+ >
+ <div className="flex items-center space-x-1.5 min-w-0">
<div className="relative" ref={menuRef}>
<button
type="button"
onClick={() => setShowMenu((prev) => !prev)}
title="Brush Size Options"
- className="p-1 text-[#8c9099] hover:text-white hover:bg-[#282a2e] rounded transition-colors cursor-pointer"
+ className={`p-1 rounded transition-colors cursor-pointer ${
+ isVintage
+ ? 'text-[#b0b0b6] hover:text-white hover:bg-[#4e4e52]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
>
<Menu className="w-3.5 h-3.5" />
</button>
{showMenu && (
- <div className="absolute top-7 left-0 w-48 bg-[#18191b] border border-[#33363e] rounded shadow-xl py-1 z-50 text-[11px] text-[#cccccc]">
+ <div
+ className={`absolute top-6 left-0 w-44 rounded shadow-xl py-1 z-50 text-[11px] ${
+ isVintage
+ ? 'bg-[#2b2b2e] border border-[#202022] text-[#e0e0e4]'
+ : 'bg-[#1a1a1a] border border-white/[0.1] text-[#cccccc]'
+ }`}
+ >
{onResetSizeToDefault && (
<button
type="button"
@@ -175,9 +189,9 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
onResetSizeToDefault();
setShowMenu(false);
}}
- className="w-full px-3 py-1.5 text-left hover:bg-[#26282e] hover:text-white flex items-center space-x-2 cursor-pointer"
+ className="w-full px-3 py-1.5 text-left hover:bg-[#2c2c2c] hover:text-white flex items-center space-x-2 cursor-pointer"
>
- <RotateCcw className="w-3 h-3 text-[#5ce1e6]" />
+ <RotateCcw className="w-3 h-3 text-[var(--accent)]" />
<span>Reset Size to Default</span>
</button>
)}
@@ -188,41 +202,50 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
onResetAllSettings();
setShowMenu(false);
}}
- className="w-full px-3 py-1.5 text-left hover:bg-[#26282e] hover:text-rose-400 flex items-center space-x-2 cursor-pointer"
+ className="w-full px-3 py-1.5 text-left hover:bg-[#2c2c2c] hover:text-rose-400 flex items-center space-x-2 cursor-pointer"
>
<RotateCcw className="w-3 h-3 text-rose-400" />
<span>Reset All Brush Settings</span>
</button>
)}
- <div className="px-3 py-1 text-[10px] text-[#717682] border-t border-[#26282e] mt-1">
+ <div className="px-3 py-1 text-[10px] text-[#8a8a8a] border-t border-white/[0.06] mt-1">
Current: {currentSize} px
</div>
</div>
)}
</div>
- {/* Tool Icon */}
{renderToolIcon()}
- {/* Brush Size Label */}
<span
- className="text-xs font-semibold tracking-tight text-[#e0e3ea] truncate"
+ className="text-[11px] font-medium tracking-tight truncate"
title={`Brush size [${activeBrushName || 'Brush'}]`}
>
- Brush size [{activeBrushName || 'Brush'}]
+ {activeBrushName || 'Brush'}
</span>
</div>
- {/* Current Size Badge */}
- <span className="text-[10px] font-mono px-1.5 py-0.5 rounded bg-[#141517] border border-[#2b2d31] text-[#5ce1e6] shrink-0">
- {currentSize} px
+ <span
+ className={`text-[10px] font-mono px-1.5 py-0.5 rounded shrink-0 ${
+ isVintage
+ ? 'bg-[#2b2b2e] border border-[#202022] text-[#38bdf8]'
+ : 'bg-[#161616] text-[var(--accent)]'
+ }`}
+ >
+ {currentSize}px
</span>
</div>
)}
- {/* 6-Column Grid of 40 Presets matching screenshot */}
- <div className="p-1 overflow-y-auto">
- <div className="grid grid-cols-6 border-t border-l border-[#2d3036] bg-[#141518]">
+ {/* Responsive CSP-style grid of brush size presets */}
+ <div className="p-1 flex-1 min-h-0 overflow-y-auto">
+ <div
+ className={`grid grid-cols-[repeat(auto-fill,minmax(32px,1fr))] border-t border-l ${
+ isVintage
+ ? 'border-[#252528] bg-[#2a2a2d]'
+ : 'border-[#2a2a2a] bg-[#161616]'
+ }`}
+ >
{BRUSH_SIZE_PRESETS.map((preset) => {
const isSelected = Math.abs(currentSize - preset) < 0.05;
@@ -232,19 +255,22 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
type="button"
onClick={() => onSelectSize(preset)}
title={`${preset} px`}
- className={`h-11 flex flex-col items-center justify-between py-1 px-0.5 border-r border-b transition-colors cursor-pointer relative group ${
+ aria-pressed={isSelected}
+ className={`h-10 flex flex-col items-center justify-between py-1 px-0.5 border-r border-b transition-colors cursor-pointer relative ${
isSelected
- ? 'bg-[#37485e] border-[#4e6a88] text-white shadow-inner font-semibold z-10'
- : 'bg-[#1b1c1f]/80 hover:bg-[#282b31] border-[#292b30] text-[#a8acb6] hover:text-white'
+ ? isVintage
+ ? 'bg-[#337bb5] border-[#4e95cf] text-white font-semibold z-10'
+ : 'bg-[var(--accent-subtle)] border-[var(--accent-border)] text-[var(--accent)] font-semibold z-10'
+ : isVintage
+ ? 'bg-[#343437] hover:bg-[#444448] border-[#252528] text-[#b8b8be] hover:text-white'
+ : 'bg-[#202020] hover:bg-[#2c2c2c] border-[#2a2a2a] text-[#8a8a8a] hover:text-[#e5e5e5]'
}`}
>
- {/* Visual circle preview */}
- <div className="w-full h-5 flex items-center justify-center overflow-hidden">
+ <div className="w-full h-4 flex items-center justify-center overflow-hidden">
{renderSizeCircle(preset)}
</div>
- {/* Preset size numeric label */}
- <span className="text-[10px] font-mono tracking-tight leading-none text-center">
+ <span className="text-[9px] font-mono tracking-tight leading-none text-center">
{preset}
</span>
</button>
@@ -254,4 +280,6 @@ export const BrushSizePalette: React.FC<BrushSizePaletteProps> = ({
</div>
</div>
);
-};
+});
+
+BrushSizePalette.displayName = 'BrushSizePalette';
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index d97f187..b6bc757 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -1619,8 +1619,8 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
</div>
)}
- {/* Subtle Zero-Height Canvas Coordinate / Pressure Readout */}
- {(showCursorCoordinates || showPressureInStatusBar) && (
+ {/* Subtle Zero-Height Canvas Coordinate / Pressure Readout (only shown if bottom StatusBar is hidden) */}
+ {false && (showCursorCoordinates || showPressureInStatusBar) && (
<div
ref={pointerStatRef}
className="pointer-events-none absolute bottom-2 right-3 z-30 text-[10px] font-mono text-[#8a8a8a]/70 select-none"
diff --git a/src/components/CommandBar.tsx b/src/components/CommandBar.tsx
new file mode 100644
index 0000000..17fa207
--- /dev/null
+++ b/src/components/CommandBar.tsx
@@ -0,0 +1,499 @@
+import React, { useState, useRef, useEffect } from 'react';
+import {
+ Save,
+ Undo2,
+ Redo2,
+ FlipHorizontal,
+ FlipVertical,
+ Eraser,
+ Layers,
+ Plus,
+ Copy,
+ Scaling,
+ X,
+ Maximize2,
+ RotateCcw,
+ ArrowLeftRight,
+ EyeOff,
+ Eye,
+ SlidersHorizontal,
+ LayoutGrid,
+ ChevronDown,
+ ChevronUp,
+ Check,
+ Sparkles,
+} from 'lucide-react';
+import {
+ COMMAND_CATALOG,
+ CommandActionId,
+ WORKSPACE_PRESET_LABELS,
+ WorkspacePresetId,
+} from '../types/workspace';
+import { ThemePreset } from '../types/settings';
+import { useWorkspaceStore, workspaceStoreActions } from '../stores';
+
+export interface WorkspaceCommandHandlers {
+ onUndo: () => void;
+ onRedo: () => void;
+ canUndo: boolean;
+ canRedo: boolean;
+ onSave?: () => void;
+ onSaveAs?: () => void;
+ onNewLayer?: () => void;
+ onDuplicateLayer?: () => void;
+ onClearLayer?: () => void;
+ onMergeDown?: () => void;
+ onFlipHorizontal?: () => void;
+ onFlipVertical?: () => void;
+ flipX?: boolean;
+ flipY?: boolean;
+ onResetZoom?: () => void;
+ onResetRotation?: () => void;
+ onTransform?: () => void;
+ onDeselect?: () => void;
+ onSwapColors?: () => void;
+ onToggleTransparentColor?: () => void;
+ hasOpenDocument: boolean;
+}
+
+export function renderCommandIcon(id: CommandActionId, palettesHidden = false): React.ReactNode {
+ const cls = 'w-3.5 h-3.5 shrink-0';
+ switch (id) {
+ case 'save':
+ case 'save-as':
+ return <Save className={cls} />;
+ case 'undo':
+ return <Undo2 className={cls} />;
+ case 'redo':
+ return <Redo2 className={cls} />;
+ case 'flip-h':
+ return <FlipHorizontal className={cls} />;
+ case 'flip-v':
+ return <FlipVertical className={cls} />;
+ case 'clear-layer':
+ return <Eraser className={cls} />;
+ case 'merge-down':
+ return <Layers className={cls} />;
+ case 'new-layer':
+ return <Plus className={cls} />;
+ case 'duplicate-layer':
+ return <Copy className={cls} />;
+ case 'transform':
+ return <Scaling className={cls} />;
+ case 'deselect':
+ return <X className={cls} />;
+ case 'reset-zoom':
+ return <Maximize2 className={cls} />;
+ case 'reset-rotation':
+ return <RotateCcw className={cls} />;
+ case 'swap-colors':
+ return <ArrowLeftRight className={cls} />;
+ case 'transparent-ink':
+ return <Sparkles className={cls} />;
+ case 'toggle-palettes':
+ return palettesHidden ? <Eye className={cls} /> : <EyeOff className={cls} />;
+ default:
+ return <Sparkles className={cls} />;
+ }
+}
+
+export function executeWorkspaceCommand(
+ id: CommandActionId,
+ handlers: WorkspaceCommandHandlers
+): void {
+ switch (id) {
+ case 'undo':
+ if (handlers.canUndo) handlers.onUndo();
+ break;
+ case 'redo':
+ if (handlers.canRedo) handlers.onRedo();
+ break;
+ case 'save':
+ handlers.onSave?.();
+ break;
+ case 'save-as':
+ handlers.onSaveAs?.();
+ break;
+ case 'new-layer':
+ handlers.onNewLayer?.();
+ break;
+ case 'duplicate-layer':
+ handlers.onDuplicateLayer?.();
+ break;
+ case 'clear-layer':
+ handlers.onClearLayer?.();
+ break;
+ case 'merge-down':
+ handlers.onMergeDown?.();
+ break;
+ case 'flip-h':
+ handlers.onFlipHorizontal?.();
+ break;
+ case 'flip-v':
+ handlers.onFlipVertical?.();
+ break;
+ case 'reset-zoom':
+ handlers.onResetZoom?.();
+ break;
+ case 'reset-rotation':
+ handlers.onResetRotation?.();
+ break;
+ case 'transform':
+ handlers.onTransform?.();
+ break;
+ case 'deselect':
+ handlers.onDeselect?.();
+ break;
+ case 'swap-colors':
+ handlers.onSwapColors?.();
+ break;
+ case 'transparent-ink':
+ handlers.onToggleTransparentColor?.();
+ break;
+ case 'toggle-palettes':
+ workspaceStoreActions.togglePalettesHidden();
+ break;
+ }
+}
+
+export function isCommandDisabled(
+ id: CommandActionId,
+ handlers: WorkspaceCommandHandlers
+): boolean {
+ if (id === 'toggle-palettes' || id === 'swap-colors' || id === 'transparent-ink') return false;
+ if (!handlers.hasOpenDocument) return true;
+ if (id === 'undo') return !handlers.canUndo;
+ if (id === 'redo') return !handlers.canRedo;
+ return false;
+}
+
+export function isCommandActive(
+ id: CommandActionId,
+ handlers: WorkspaceCommandHandlers,
+ palettesHidden: boolean
+): boolean {
+ if (id === 'flip-h') return Boolean(handlers.flipX);
+ if (id === 'flip-v') return Boolean(handlers.flipY);
+ if (id === 'toggle-palettes') return palettesHidden;
+ return false;
+}
+
+interface CommandBarProps {
+ handlers: WorkspaceCommandHandlers;
+ themePreset?: ThemePreset;
+}
+
+export const CommandBar: React.FC<CommandBarProps> = React.memo(({
+ handlers,
+ themePreset = 'modern',
+}) => {
+ const commandBarIds = useWorkspaceStore((s) => s.commandBarIds);
+ const showCommandBar = useWorkspaceStore((s) => s.showCommandBar);
+ const activePreset = useWorkspaceStore((s) => s.activePreset);
+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
+
+ const [isCustomizeOpen, setIsCustomizeOpen] = useState(false);
+ const [isPresetMenuOpen, setIsPresetMenuOpen] = useState(false);
+ const customizeRef = useRef<HTMLDivElement>(null);
+ const presetRef = useRef<HTMLDivElement>(null);
+
+ const isVintage = themePreset === 'vintage-manga';
+
+ useEffect(() => {
+ if (!isCustomizeOpen && !isPresetMenuOpen) return;
+ const handlePointerDown = (e: MouseEvent) => {
+ const target = e.target as Node;
+ if (isCustomizeOpen && customizeRef.current && !customizeRef.current.contains(target)) {
+ setIsCustomizeOpen(false);
+ }
+ if (isPresetMenuOpen && presetRef.current && !presetRef.current.contains(target)) {
+ setIsPresetMenuOpen(false);
+ }
+ };
+ const handleKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ setIsCustomizeOpen(false);
+ setIsPresetMenuOpen(false);
+ }
+ };
+ window.addEventListener('mousedown', handlePointerDown);
+ window.addEventListener('keydown', handleKey);
+ return () => {
+ window.removeEventListener('mousedown', handlePointerDown);
+ window.removeEventListener('keydown', handleKey);
+ };
+ }, [isCustomizeOpen, isPresetMenuOpen]);
+
+ const catalogById = React.useMemo(() => {
+ const map = new Map(COMMAND_CATALOG.map((c) => [c.id, c]));
+ return map;
+ }, []);
+
+ const presets: WorkspacePresetId[] = [
+ 'default-illustration',
+ 'manga-studio',
+ 'minimalist-tablet',
+ 'custom',
+ ];
+
+ return (
+ <div
+ data-testid="command-bar"
+ className="flex items-center gap-1 min-w-0"
+ style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
+ >
+ {/* Customizable Command Buttons */}
+ {showCommandBar && (
+ <div
+ className={`flex items-center gap-0.5 px-1 h-6 rounded overflow-x-auto no-scrollbar ${
+ isVintage
+ ? 'bg-[#2b2b2e] border border-[#202022] shadow-[inset_1px_1px_2px_rgba(0,0,0,0.45)]'
+ : 'bg-[#161616]'
+ }`}
+ >
+ {commandBarIds.map((cmdId) => {
+ const entry = catalogById.get(cmdId);
+ if (!entry) return null;
+ const disabled = isCommandDisabled(cmdId, handlers);
+ const active = isCommandActive(cmdId, handlers, palettesHidden);
+
+ return (
+ <button
+ key={cmdId}
+ type="button"
+ disabled={disabled}
+ onClick={() => executeWorkspaceCommand(cmdId, handlers)}
+ title={`${entry.label}${entry.shortcut ? ` (${entry.shortcut})` : ''}`}
+ aria-label={entry.label}
+ aria-pressed={active || undefined}
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors shrink-0 ${
+ disabled
+ ? 'opacity-30 cursor-not-allowed text-[#8a8a8a]'
+ : active
+ ? isVintage
+ ? 'bg-[#337bb5] text-white cursor-pointer'
+ : 'bg-[#2c2c2c] text-[var(--accent)] cursor-pointer'
+ : isVintage
+ ? 'text-[#c0c0c6] hover:text-white hover:bg-[#444448] cursor-pointer'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
+ }`}
+ >
+ {renderCommandIcon(cmdId, palettesHidden)}
+ </button>
+ );
+ })}
+
+ {/* Customize Command Bar Button */}
+ <div className="relative" ref={customizeRef}>
+ <button
+ type="button"
+ onClick={() => {
+ setIsPresetMenuOpen(false);
+ setIsCustomizeOpen((v) => !v);
+ }}
+ title="Customize Command Bar"
+ aria-label="Customize Command Bar"
+ className={`w-5 h-5 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ isCustomizeOpen
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <SlidersHorizontal className="w-3 h-3" />
+ </button>
+
+ {isCustomizeOpen && (
+ <div
+ className={`fixed top-9 left-1/2 -translate-x-1/2 w-64 rounded-md shadow-2xl p-2 z-50 text-[11px] ${
+ isVintage
+ ? 'bg-[#333336] border border-[#202022] text-[#e5e5e5]'
+ : 'bg-[#202020] border border-white/[0.1] text-[#e5e5e5]'
+ }`}
+ >
+ <div className="flex items-center justify-between pb-1.5 mb-1.5 border-b border-white/[0.08]">
+ <span className="font-medium text-xs">Command Bar</span>
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.resetCommandBar()}
+ className="text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
+ >
+ Reset
+ </button>
+ </div>
+
+ {/* Active order */}
+ {commandBarIds.length > 0 && (
+ <div className="mb-2 space-y-0.5 max-h-32 overflow-y-auto">
+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a] px-1 mb-0.5">
+ Pinned ({commandBarIds.length})
+ </div>
+ {commandBarIds.map((cid, idx) => {
+ const entry = catalogById.get(cid);
+ if (!entry) return null;
+ return (
+ <div
+ key={cid}
+ className="flex items-center justify-between gap-1 px-1.5 py-0.5 rounded bg-[#161616]"
+ >
+ <div className="flex items-center gap-1.5 min-w-0">
+ {renderCommandIcon(cid)}
+ <span className="truncate">{entry.label}</span>
+ </div>
+ <div className="flex items-center gap-0.5 shrink-0">
+ <button
+ type="button"
+ disabled={idx === 0}
+ onClick={() => workspaceStoreActions.moveCommandBarItem(cid, -1)}
+ className="p-0.5 text-[#8a8a8a] hover:text-white disabled:opacity-25 cursor-pointer"
+ title="Move left"
+ >
+ <ChevronUp className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ disabled={idx === commandBarIds.length - 1}
+ onClick={() => workspaceStoreActions.moveCommandBarItem(cid, 1)}
+ className="p-0.5 text-[#8a8a8a] hover:text-white disabled:opacity-25 cursor-pointer"
+ title="Move right"
+ >
+ <ChevronDown className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.toggleCommandBarItem(cid)}
+ className="p-0.5 text-[#8a8a8a] hover:text-rose-400 cursor-pointer"
+ title="Remove"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Toggle all catalog commands */}
+ <div className="text-[10px] uppercase tracking-wider text-[#8a8a8a] px-1 mb-0.5">
+ Available Commands
+ </div>
+ <div className="max-h-44 overflow-y-auto space-y-0.5">
+ {COMMAND_CATALOG.map((entry) => {
+ const pinned = commandBarIds.includes(entry.id);
+ return (
+ <button
+ key={entry.id}
+ type="button"
+ onClick={() => workspaceStoreActions.toggleCommandBarItem(entry.id)}
+ className={`w-full flex items-center justify-between gap-2 px-1.5 py-1 rounded text-left transition-colors cursor-pointer ${
+ pinned
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ <span className="flex items-center gap-1.5 min-w-0">
+ {renderCommandIcon(entry.id)}
+ <span className="truncate">{entry.label}</span>
+ </span>
+ {pinned && <Check className="w-3 h-3 text-[var(--accent)] shrink-0" />}
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
+ {/* Workspace Preset Selector */}
+ <div className="relative shrink-0" ref={presetRef}>
+ <button
+ type="button"
+ onClick={() => {
+ setIsCustomizeOpen(false);
+ setIsPresetMenuOpen((v) => !v);
+ }}
+ data-testid="workspace-preset-trigger"
+ title="Workspace Presets & Layout"
+ className={`h-6 px-2 rounded flex items-center gap-1 text-[11px] transition-colors cursor-pointer ${
+ isVintage
+ ? 'bg-gradient-to-b from-[#4e4e52] to-[#3a3a3d] border border-[#242426] text-[#e5e5e5] hover:brightness-110'
+ : 'bg-[#161616] hover:bg-[#2c2c2c] text-[#cccccc] hover:text-white'
+ }`}
+ >
+ <LayoutGrid className="w-3 h-3 text-[var(--accent)]" />
+ <span className="hidden xl:inline max-w-[116px] truncate">
+ {WORKSPACE_PRESET_LABELS[activePreset]}
+ </span>
+ <ChevronDown className="w-3 h-3 text-[#8a8a8a]" />
+ </button>
+
+ {isPresetMenuOpen && (
+ <div
+ data-testid="workspace-preset-menu"
+ className={`absolute top-7 right-0 w-52 rounded-md shadow-2xl p-1 z-50 text-[11px] ${
+ isVintage
+ ? 'bg-[#333336] border border-[#202022] text-[#e5e5e5]'
+ : 'bg-[#202020] border border-white/[0.1] text-[#e5e5e5]'
+ }`}
+ >
+ <div className="px-2 py-1 text-[10px] uppercase tracking-wider text-[#8a8a8a]">
+ Workspace Presets
+ </div>
+ {presets.map((preset) => {
+ const selected = activePreset === preset;
+ return (
+ <button
+ key={preset}
+ type="button"
+ onClick={() => {
+ workspaceStoreActions.applyPreset(preset);
+ setIsPresetMenuOpen(false);
+ }}
+ className={`w-full flex items-center justify-between px-2 py-1.5 rounded text-left transition-colors cursor-pointer ${
+ selected
+ ? 'bg-[#2c2c2c] text-white font-medium'
+ : 'text-[#cccccc] hover:bg-[#2c2c2c]/60 hover:text-white'
+ }`}
+ >
+ <span>{WORKSPACE_PRESET_LABELS[preset]}</span>
+ {selected && <Check className="w-3 h-3 text-[var(--accent)]" />}
+ </button>
+ );
+ })}
+
+ <div className="my-1 h-px bg-white/[0.08]" />
+
+ <button
+ type="button"
+ onClick={() => {
+ workspaceStoreActions.togglePalettesHidden();
+ setIsPresetMenuOpen(false);
+ }}
+ className="w-full flex items-center justify-between px-2 py-1.5 rounded text-left text-[#cccccc] hover:bg-[#2c2c2c]/60 hover:text-white cursor-pointer"
+ >
+ <span>{palettesHidden ? 'Show Palettes' : 'Hide Palettes'}</span>
+ <span className="text-[10px] font-mono text-[#8a8a8a]">Tab</span>
+ </button>
+
+ <button
+ type="button"
+ onClick={() => {
+ workspaceStoreActions.resetWorkspace();
+ setIsPresetMenuOpen(false);
+ }}
+ data-testid="reset-workspace-btn"
+ className="w-full flex items-center gap-1.5 px-2 py-1.5 rounded text-left text-amber-300 hover:bg-[#2c2c2c]/60 cursor-pointer"
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span>Reset Workspace</span>
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+});
+
+CommandBar.displayName = 'CommandBar';
diff --git a/src/components/DockWorkspace.tsx b/src/components/DockWorkspace.tsx
new file mode 100644
index 0000000..fc11f26
--- /dev/null
+++ b/src/components/DockWorkspace.tsx
@@ -0,0 +1,1012 @@
+import React, { useState, useRef, useEffect, useCallback } from 'react';
+import {
+ ChevronsLeft,
+ ChevronsRight,
+ Paintbrush,
+ Sliders,
+ CircleDot,
+ Palette,
+ Layers,
+ History,
+ Zap,
+ Wrench,
+ MoreHorizontal,
+ ArrowLeftToLine,
+ ArrowRightToLine,
+ X,
+ PanelLeft,
+ PanelRight,
+ Eye,
+} from 'lucide-react';
+import { CanvasColorMode, CspBrush } from '../types/editor';
+import { ThemePreset } from '../types/settings';
+import {
+ DOCK_PANEL_META,
+ DockColumn,
+ DockGroup,
+ DockPanelId,
+ DockSide,
+} from '../types/workspace';
+import {
+ CUSTOM_BRUSHES_CHANGED_EVENT,
+ getCachedCustomBrushes,
+ loadCustomBrushes,
+ preloadTipImage,
+} from '../utils/brushStorage';
+import {
+ DEFAULT_BRUSH_PRESET_ID,
+ ERASER_PRESET_ID,
+ getEffectiveBrushSettings,
+ resetBrushSettingsToDefault,
+} from '../utils/brushPresetManager';
+import {
+ toolStoreActions,
+ useToolStore,
+ useWorkspaceStore,
+ workspaceStoreActions,
+} from '../stores';
+import { ToolStrip } from './ToolStrip';
+import { SubToolList } from './SubToolList';
+import { ToolPropertyInspector } from './ToolPropertyInspector';
+import { BrushSizePalette } from './BrushSizePalette';
+import { RightSidebar, RightSidebarColorSection, RightSidebarProps } from './RightSidebar';
+import { QuickAccessPanel } from './QuickAccessPanel';
+import { WorkspaceCommandHandlers } from './CommandBar';
+
+const DND_PANEL_MIME = 'application/x-inkstudio-panel';
+
+export function renderPanelIcon(panelId: DockPanelId, className = 'w-3.5 h-3.5'): React.ReactNode {
+ switch (panelId) {
+ case 'tools':
+ return <Wrench className={className} />;
+ case 'subtool':
+ return <Paintbrush className={className} />;
+ case 'tool-property':
+ return <Sliders className={className} />;
+ case 'brush-size':
+ return <CircleDot className={className} />;
+ case 'color':
+ return <Palette className={className} />;
+ case 'layers':
+ return <Layers className={className} />;
+ case 'history':
+ return <History className={className} />;
+ case 'quick-access':
+ return <Zap className={className} />;
+ }
+}
+
+function useSharedCustomBrushes(): [CspBrush[], React.Dispatch<React.SetStateAction<CspBrush[]>>] {
+ const [customBrushes, setCustomBrushes] = useState<CspBrush[]>(() => getCachedCustomBrushes());
+
+ useEffect(() => {
+ let active = true;
+ loadCustomBrushes().then((brushes) => {
+ if (!active) return;
+ setCustomBrushes(brushes);
+ for (const b of brushes) {
+ if (b.tipDataUrl) preloadTipImage(b.tipDataUrl).catch(() => {});
+ if (b.secondaryTipDataUrl) preloadTipImage(b.secondaryTipDataUrl).catch(() => {});
+ if (b.subTips) {
+ for (const st of b.subTips) {
+ if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
+ }
+ }
+ if (b.paperTexture) preloadTipImage(b.paperTexture).catch(() => {});
+ }
+ });
+ const handleChanged = () => setCustomBrushes([...getCachedCustomBrushes()]);
+ window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
+ return () => {
+ active = false;
+ window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
+ };
+ }, []);
+
+ return [customBrushes, setCustomBrushes];
+}
+
+/** Isolated BrushSizePalette wrapper so brush size changes never re-render dock chrome or layers */
+const BrushSizeDockedContent: React.FC<{ themePreset: ThemePreset }> = React.memo(
+ ({ themePreset }) => {
+ const size = useToolStore((s) => s.brushSettings.size);
+ const brushName = useToolStore((s) => s.brushSettings.brushName);
+ const preset = useToolStore((s) => s.brushSettings.preset);
+ const tool = useToolStore((s) => s.tool);
+
+ const activePresetId =
+ tool === 'eraser' ? ERASER_PRESET_ID : preset || DEFAULT_BRUSH_PRESET_ID;
+
+ const handleSelectSize = useCallback((nextSize: number) => {
+ toolStoreActions.updateBrushSettings({ size: nextSize });
+ }, []);
+
+ const handleResetSize = useCallback(() => {
+ const defaults = getEffectiveBrushSettings(activePresetId);
+ if (defaults.size !== undefined) {
+ toolStoreActions.updateBrushSettings({ size: defaults.size });
+ }
+ }, [activePresetId]);
+
+ const handleResetAll = useCallback(() => {
+ const restored = resetBrushSettingsToDefault(activePresetId, getCachedCustomBrushes());
+ toolStoreActions.updateBrushSettings(restored);
+ }, [activePresetId]);
+
+ return (
+ <BrushSizePalette
+ currentSize={size}
+ onSelectSize={handleSelectSize}
+ activeBrushName={brushName || (tool === 'eraser' ? 'Eraser' : String(preset || 'Brush'))}
+ tool={tool}
+ presetId={activePresetId}
+ onResetSizeToDefault={handleResetSize}
+ onResetAllSettings={handleResetAll}
+ themePreset={themePreset}
+ />
+ );
+ }
+);
+BrushSizeDockedContent.displayName = 'BrushSizeDockedContent';
+
+export interface DockWorkspaceProps {
+ themePreset: ThemePreset;
+ colorMode: CanvasColorMode;
+ commandHandlers: WorkspaceCommandHandlers;
+ // Tool / selection callbacks
+ onDeselect?: () => void;
+ onTransformSelection?: () => void;
+ onExpandSelection?: (pixels: number) => void;
+ onContractSelection?: (pixels: number) => void;
+ onFeatherSelection?: (radius: number) => void;
+ onInvertSelection?: () => void;
+ onToggleTransparentColor?: () => void;
+ // Layer & history props forwarded cleanly to RightSidebar docked panels
+ layerSidebarProps: Omit<RightSidebarProps, 'width' | 'onWidthChange' | 'hideColorPanel' | 'dockedMode'>;
+ // Center canvas area (DocumentTabBar + CanvasArea + StatusBar)
+ children: React.ReactNode;
+}
+
+interface DockGroupViewProps {
+ side: DockSide;
+ col: DockColumn;
+ group: DockGroup;
+ themePreset: ThemePreset;
+ draggingPanelId: DockPanelId | null;
+ onStartDragPanel: (panelId: DockPanelId) => void;
+ onEndDragPanel: () => void;
+ renderPanelBody: (panelId: DockPanelId, containerWidth: number) => React.ReactNode;
+}
+
+const DockGroupView: React.FC<DockGroupViewProps> = React.memo(({
+ side,
+ col,
+ group,
+ themePreset,
+ draggingPanelId,
+ onStartDragPanel,
+ onEndDragPanel,
+ renderPanelBody,
+}) => {
+ const [menuOpen, setMenuOpen] = useState(false);
+ const [isDragOverTab, setIsDragOverTab] = useState(false);
+ const menuRef = useRef<HTMLDivElement>(null);
+ const isVintage = themePreset === 'vintage-manga';
+
+ useEffect(() => {
+ if (!menuOpen) return;
+ const handleOutside = (e: MouseEvent) => {
+ if (menuRef.current && !menuRef.current.contains(e.target as Node)) {
+ setMenuOpen(false);
+ }
+ };
+ window.addEventListener('mousedown', handleOutside);
+ return () => window.removeEventListener('mousedown', handleOutside);
+ }, [menuOpen]);
+
+ const activePanelId = group.panelIds.includes(group.activePanelId)
+ ? group.activePanelId
+ : group.panelIds[0];
+
+ const isCompactToolOnly =
+ col.width <= 64 && group.panelIds.length === 1 && group.panelIds[0] === 'tools';
+
+ const handleDropOnTabs = (e: React.DragEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setIsDragOverTab(false);
+ const rawId =
+ (e.dataTransfer.getData(DND_PANEL_MIME) as DockPanelId) ||
+ (e.dataTransfer.getData('text/plain') as DockPanelId) ||
+ draggingPanelId;
+ if (rawId && DOCK_PANEL_META[rawId]) {
+ workspaceStoreActions.movePanel(rawId, {
+ side,
+ targetColId: col.id,
+ targetGroupId: group.id,
+ });
+ }
+ onEndDragPanel();
+ };
+
+ return (
+ <div
+ data-testid={`dock-group-${group.id}`}
+ style={{ flexGrow: group.heightRatio, flexBasis: 0 }}
+ className={`flex flex-col min-h-[72px] overflow-hidden ${
+ isVintage ? 'bg-[#363638]' : 'bg-[#202020]'
+ }`}
+ >
+ {/* Palette Tab Header Bar (Draggable!) */}
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ e.dataTransfer.dropEffect = 'move';
+ setIsDragOverTab(true);
+ }}
+ onDragLeave={() => setIsDragOverTab(false)}
+ onDrop={handleDropOnTabs}
+ className={`h-6 flex items-center justify-between px-1 shrink-0 select-none relative transition-colors ${
+ isDragOverTab
+ ? 'bg-[var(--accent-subtle)] ring-1 ring-inset ring-[var(--accent)]'
+ : isVintage
+ ? 'bg-gradient-to-b from-[#49494d] to-[#3a3a3d] border-b border-[#232325]'
+ : 'bg-[#1a1a1a] border-b border-white/[0.06]'
+ }`}
+ >
+ <div className="flex items-center gap-0.5 min-w-0 overflow-x-auto no-scrollbar h-full">
+ {group.panelIds.map((pid) => {
+ const meta = DOCK_PANEL_META[pid];
+ const isActive = pid === activePanelId;
+ return (
+ <button
+ key={pid}
+ type="button"
+ draggable
+ onDragStart={(e) => {
+ e.dataTransfer.setData(DND_PANEL_MIME, pid);
+ e.dataTransfer.setData('text/plain', pid);
+ e.dataTransfer.effectAllowed = 'move';
+ onStartDragPanel(pid);
+ }}
+ onDragEnd={onEndDragPanel}
+ onClick={() => workspaceStoreActions.setGroupActivePanel(col.id, group.id, pid)}
+ data-testid={`dock-tab-${pid}`}
+ title={`${meta.title} — Drag tab to move palette`}
+ className={`h-5 px-1.5 rounded-sm flex items-center gap-1 text-[10px] transition-colors shrink-0 cursor-grab active:cursor-grabbing ${
+ isActive
+ ? isVintage
+ ? 'bg-[#337bb5] text-white font-medium'
+ : 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : isVintage
+ ? 'text-[#b0b0b6] hover:text-white hover:bg-[#4e4e52]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#262626]'
+ }`}
+ >
+ {renderPanelIcon(pid, 'w-3 h-3 shrink-0')}
+ {!isCompactToolOnly && (
+ <span className="truncate max-w-[84px]">
+ {group.panelIds.length > 1 ? meta.shortTitle : meta.title}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Palette Options Menu (1-click Move Left/Right, New Column, Collapse, Hide) */}
+ {!isCompactToolOnly && (
+ <div className="relative shrink-0" ref={menuRef}>
+ <button
+ type="button"
+ onClick={() => setMenuOpen((v) => !v)}
+ data-testid={`dock-menu-btn-${activePanelId}`}
+ title="Palette Dock Options"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <MoreHorizontal className="w-3 h-3" />
+ </button>
+
+ {menuOpen && (
+ <div
+ className={`absolute top-6 ${
+ side === 'left' ? 'left-0' : 'right-0'
+ } w-44 rounded-md shadow-2xl p-1 z-50 text-[11px] ${
+ isVintage
+ ? 'bg-[#333336] border border-[#202022] text-[#e5e5e5]'
+ : 'bg-[#202020] border border-white/[0.1] text-[#e5e5e5]'
+ }`}
+ >
+ <div className="px-2 py-0.5 text-[10px] text-[#8a8a8a] truncate">
+ {DOCK_PANEL_META[activePanelId].title}
+ </div>
+ <div className="my-0.5 h-px bg-white/[0.08]" />
+
+ {side === 'right' ? (
+ <button
+ type="button"
+ data-testid={`move-to-left-${activePanelId}`}
+ onClick={() => {
+ workspaceStoreActions.movePanel(activePanelId, { side: 'left' });
+ setMenuOpen(false);
+ }}
+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"
+ >
+ <ArrowLeftToLine className="w-3 h-3 text-[var(--accent)]" />
+ <span>Move to Left Dock</span>
+ </button>
+ ) : (
+ <button
+ type="button"
+ data-testid={`move-to-right-${activePanelId}`}
+ onClick={() => {
+ workspaceStoreActions.movePanel(activePanelId, { side: 'right' });
+ setMenuOpen(false);
+ }}
+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"
+ >
+ <ArrowRightToLine className="w-3 h-3 text-[var(--accent)]" />
+ <span>Move to Right Dock</span>
+ </button>
+ )}
+
+ <button
+ type="button"
+ onClick={() => {
+ workspaceStoreActions.movePanel(activePanelId, { side });
+ setMenuOpen(false);
+ }}
+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"
+ >
+ {side === 'left' ? (
+ <PanelLeft className="w-3 h-3 text-[#8a8a8a]" />
+ ) : (
+ <PanelRight className="w-3 h-3 text-[#8a8a8a]" />
+ )}
+ <span>Move to New Column</span>
+ </button>
+
+ <button
+ type="button"
+ onClick={() => {
+ workspaceStoreActions.toggleColumnCollapsed(col.id, true);
+ setMenuOpen(false);
+ }}
+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] cursor-pointer text-left"
+ >
+ {side === 'left' ? (
+ <ChevronsLeft className="w-3 h-3 text-[#8a8a8a]" />
+ ) : (
+ <ChevronsRight className="w-3 h-3 text-[#8a8a8a]" />
+ )}
+ <span>Collapse Dock Strip</span>
+ </button>
+
+ <div className="my-0.5 h-px bg-white/[0.08]" />
+
+ <button
+ type="button"
+ onClick={() => {
+ workspaceStoreActions.togglePanelVisibility(activePanelId);
+ setMenuOpen(false);
+ }}
+ className="w-full flex items-center gap-1.5 px-2 py-1 rounded hover:bg-[#2c2c2c] text-rose-400 cursor-pointer text-left"
+ >
+ <X className="w-3 h-3" />
+ <span>Close Palette</span>
+ </button>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* Active Panel Content */}
+ <div className="flex-1 min-h-0 overflow-hidden flex flex-col">
+ {renderPanelBody(activePanelId, col.width)}
+ </div>
+ </div>
+ );
+});
+DockGroupView.displayName = 'DockGroupView';
+
+interface DockColumnViewProps {
+ side: DockSide;
+ col: DockColumn;
+ themePreset: ThemePreset;
+ draggingPanelId: DockPanelId | null;
+ onStartDragPanel: (panelId: DockPanelId) => void;
+ onEndDragPanel: () => void;
+ renderPanelBody: (panelId: DockPanelId, containerWidth: number) => React.ReactNode;
+}
+
+const DockColumnView: React.FC<DockColumnViewProps> = React.memo(({
+ side,
+ col,
+ themePreset,
+ draggingPanelId,
+ onStartDragPanel,
+ onEndDragPanel,
+ renderPanelBody,
+}) => {
+ const openPopover = useWorkspaceStore((s) => s.openPopover);
+ const colRef = useRef<HTMLDivElement>(null);
+ const [dragOverSplitIdx, setDragOverSplitIdx] = useState<number | null>(null);
+ const isVintage = themePreset === 'vintage-manga';
+
+ const activePopoverPanelId =
+ col.collapsed && openPopover?.colId === col.id ? openPopover.panelId : null;
+
+ const handleStartColumnResize = (e: React.PointerEvent) => {
+ e.preventDefault();
+ const startX = e.clientX;
+ const startWidth = col.width;
+ const handleMove = (ev: PointerEvent) => {
+ const delta = side === 'left' ? ev.clientX - startX : startX - ev.clientX;
+ workspaceStoreActions.resizeColumn(col.id, startWidth + delta);
+ };
+ const handleUp = () => {
+ window.removeEventListener('pointermove', handleMove);
+ window.removeEventListener('pointerup', handleUp);
+ };
+ window.addEventListener('pointermove', handleMove);
+ window.addEventListener('pointerup', handleUp);
+ };
+
+ const handleStartGroupSplitResize = (
+ e: React.PointerEvent,
+ topGroup: DockGroup,
+ bottomGroup: DockGroup
+ ) => {
+ e.preventDefault();
+ const colEl = colRef.current;
+ if (!colEl) return;
+ const totalHeight = Math.max(120, colEl.getBoundingClientRect().height);
+ const totalRatioSum = col.groups.reduce((acc, g) => acc + g.heightRatio, 0) || 1;
+ const pairSum = topGroup.heightRatio + bottomGroup.heightRatio;
+ const startY = e.clientY;
+ const startTopRatio = topGroup.heightRatio;
+
+ const handleMove = (ev: PointerEvent) => {
+ const deltaRatio = ((ev.clientY - startY) / totalHeight) * totalRatioSum;
+ const minRatio = Math.min(0.15 * totalRatioSum, pairSum * 0.25);
+ const nextTop = Math.max(minRatio, Math.min(pairSum - minRatio, startTopRatio + deltaRatio));
+ const nextBottom = pairSum - nextTop;
+ workspaceStoreActions.resizeGroupSplit(
+ col.id,
+ topGroup.id,
+ bottomGroup.id,
+ nextTop,
+ nextBottom
+ );
+ };
+ const handleUp = () => {
+ window.removeEventListener('pointermove', handleMove);
+ window.removeEventListener('pointerup', handleUp);
+ };
+ window.addEventListener('pointermove', handleMove);
+ window.addEventListener('pointerup', handleUp);
+ };
+
+ const handleDropNewGroup = (e: React.DragEvent, insertIndex: number) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDragOverSplitIdx(null);
+ const rawId =
+ (e.dataTransfer.getData(DND_PANEL_MIME) as DockPanelId) ||
+ (e.dataTransfer.getData('text/plain') as DockPanelId) ||
+ draggingPanelId;
+ if (rawId && DOCK_PANEL_META[rawId]) {
+ workspaceStoreActions.movePanel(rawId, {
+ side,
+ targetColId: col.id,
+ insertGroupIndex: insertIndex,
+ });
+ }
+ onEndDragPanel();
+ };
+
+ // Collapsed CSP Tab Strip mode
+ if (col.collapsed) {
+ const allPanelIds = col.groups.flatMap((g) => g.panelIds);
+ const popoverWidth = Math.max(204, col.width);
+
+ return (
+ <div
+ data-testid={`dock-column-${col.id}`}
+ data-collapsed="true"
+ className={`relative w-[30px] h-full flex flex-col items-center py-1 gap-1 shrink-0 select-none z-20 ${
+ isVintage
+ ? 'bg-[#333336] border-x border-[#232325]'
+ : 'bg-[#1c1c1c] border-x border-white/[0.04]'
+ }`}
+ >
+ {/* Expand Column Button */}
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.toggleColumnCollapsed(col.id, false)}
+ data-testid={`dock-expand-${col.id}`}
+ title="Expand Dock Column"
+ className="w-6 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer shrink-0"
+ >
+ {side === 'left' ? (
+ <ChevronsRight className="w-3.5 h-3.5" />
+ ) : (
+ <ChevronsLeft className="w-3.5 h-3.5" />
+ )}
+ </button>
+
+ <div className="w-4 h-px bg-white/[0.08] shrink-0" />
+
+ {/* Vertical Icon Tab Strip */}
+ <div className="flex flex-col items-center gap-1 flex-1 overflow-y-auto no-scrollbar w-full px-0.5">
+ {allPanelIds.map((pid) => {
+ const meta = DOCK_PANEL_META[pid];
+ const isOpen = activePopoverPanelId === pid;
+ return (
+ <button
+ key={pid}
+ type="button"
+ draggable
+ onDragStart={(e) => {
+ e.dataTransfer.setData(DND_PANEL_MIME, pid);
+ e.dataTransfer.setData('text/plain', pid);
+ onStartDragPanel(pid);
+ }}
+ onDragEnd={onEndDragPanel}
+ onClick={() => workspaceStoreActions.togglePopover(col.id, pid)}
+ data-testid={`collapsed-tab-${pid}`}
+ title={`${meta.title} (Click to pop out)`}
+ aria-pressed={isOpen}
+ className={`relative w-6 h-7 rounded flex items-center justify-center transition-colors cursor-pointer shrink-0 ${
+ isOpen
+ ? isVintage
+ ? 'bg-[#337bb5] text-white'
+ : 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ {isOpen && (
+ <span
+ className={`absolute top-1 bottom-1 w-[2px] rounded-full ${
+ side === 'left' ? 'left-0' : 'right-0'
+ }`}
+ style={{ backgroundColor: isVintage ? '#38bdf8' : 'var(--accent)' }}
+ />
+ )}
+ {renderPanelIcon(pid, 'w-3.5 h-3.5')}
+ </button>
+ );
+ })}
+ </div>
+
+ {/* CSP Pop-out Floating Palette Popover */}
+ {activePopoverPanelId && (
+ <div
+ data-testid={`dock-popover-${activePopoverPanelId}`}
+ style={{ width: popoverWidth }}
+ className={`absolute top-1 bottom-1 z-40 flex flex-col rounded-md shadow-[0_12px_36px_rgba(0,0,0,0.75)] overflow-hidden ${
+ side === 'left' ? 'left-[32px]' : 'right-[32px]'
+ } ${
+ isVintage
+ ? 'bg-[#363638] border border-[#202022]'
+ : 'bg-[#202020] border border-white/[0.12]'
+ }`}
+ >
+ <div
+ className={`h-7 px-2 flex items-center justify-between shrink-0 ${
+ isVintage
+ ? 'bg-gradient-to-b from-[#49494d] to-[#3a3a3d] border-b border-[#232325]'
+ : 'bg-[#1a1a1a] border-b border-white/[0.08]'
+ }`}
+ >
+ <div className="flex items-center gap-1.5 min-w-0">
+ {renderPanelIcon(activePopoverPanelId, 'w-3.5 h-3.5 text-[var(--accent)]')}
+ <span className="text-[11px] font-medium text-[#e5e5e5] truncate">
+ {DOCK_PANEL_META[activePopoverPanelId].title}
+ </span>
+ </div>
+ <div className="flex items-center gap-0.5 shrink-0">
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.toggleColumnCollapsed(col.id, false)}
+ title="Expand & Pin Column"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-white hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ {side === 'left' ? (
+ <ChevronsRight className="w-3 h-3" />
+ ) : (
+ <ChevronsLeft className="w-3 h-3" />
+ )}
+ </button>
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.closePopover()}
+ title="Dismiss Popover (Esc)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-white hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ </div>
+ </div>
+ <div className="flex-1 min-h-0 overflow-hidden flex flex-col">
+ {renderPanelBody(activePopoverPanelId, popoverWidth)}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ // Expanded Dock Column mode
+ return (
+ <div
+ ref={colRef}
+ data-testid={`dock-column-${col.id}`}
+ data-collapsed="false"
+ style={{ width: col.width }}
+ className={`relative h-full flex flex-col shrink-0 overflow-hidden z-10 ${
+ isVintage ? 'bg-[#262628]' : 'bg-[#161616]'
+ }`}
+ >
+ {/* Slim CSP Column Collapse Bar */}
+ <div
+ className={`h-4 px-1 flex items-center shrink-0 ${
+ side === 'left' ? 'justify-end' : 'justify-start'
+ } ${
+ isVintage
+ ? 'bg-[#2e2e31] border-b border-[#202022]'
+ : 'bg-[#181818] border-b border-white/[0.04]'
+ }`}
+ >
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.toggleColumnCollapsed(col.id, true)}
+ data-testid={`dock-collapse-${col.id}`}
+ title="Collapse Dock Column to Icon Strip"
+ className="h-3.5 px-1 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ {side === 'left' ? (
+ <ChevronsLeft className="w-3 h-3" />
+ ) : (
+ <ChevronsRight className="w-3 h-3" />
+ )}
+ </button>
+ </div>
+
+ {/* Stacked Palette Groups with Horizontal Splitters */}
+ <div className="flex-1 min-h-0 flex flex-col overflow-hidden">
+ {col.groups.map((grp, idx) => (
+ <React.Fragment key={grp.id}>
+ {draggingPanelId && (
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setDragOverSplitIdx(idx);
+ }}
+ onDragLeave={() => setDragOverSplitIdx(null)}
+ onDrop={(e) => handleDropNewGroup(e, idx)}
+ className={`h-1.5 shrink-0 transition-all ${
+ dragOverSplitIdx === idx ? 'h-3 bg-[var(--accent)]/40' : 'bg-transparent'
+ }`}
+ />
+ )}
+
+ <DockGroupView
+ side={side}
+ col={col}
+ group={grp}
+ themePreset={themePreset}
+ draggingPanelId={draggingPanelId}
+ onStartDragPanel={onStartDragPanel}
+ onEndDragPanel={onEndDragPanel}
+ renderPanelBody={renderPanelBody}
+ />
+
+ {idx < col.groups.length - 1 && (
+ <div
+ onPointerDown={(e) => handleStartGroupSplitResize(e, grp, col.groups[idx + 1])}
+ title="Drag to resize stacked palettes"
+ className={`h-1 shrink-0 cursor-row-resize transition-colors ${
+ isVintage
+ ? 'bg-[#232325] hover:bg-[#38bdf8]/60'
+ : 'bg-[#161616] hover:bg-[var(--accent)]/50'
+ }`}
+ />
+ )}
+ </React.Fragment>
+ ))}
+
+ {/* Bottom drop zone for stacking a dragged palette at the bottom of this column */}
+ {draggingPanelId && (
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setDragOverSplitIdx(col.groups.length);
+ }}
+ onDragLeave={() => setDragOverSplitIdx(null)}
+ onDrop={(e) => handleDropNewGroup(e, col.groups.length)}
+ className={`h-2 shrink-0 transition-all ${
+ dragOverSplitIdx === col.groups.length
+ ? 'h-5 bg-[var(--accent)]/40 border-t border-[var(--accent)]'
+ : 'bg-transparent'
+ }`}
+ />
+ )}
+ </div>
+
+ {/* Vertical Column Resize Splitter */}
+ <div
+ onPointerDown={handleStartColumnResize}
+ title="Drag to resize dock column"
+ className={`absolute top-0 bottom-0 w-1 cursor-col-resize transition-colors z-30 ${
+ side === 'left' ? 'right-0' : 'left-0'
+ } hover:bg-[var(--accent)]/50`}
+ />
+ </div>
+ );
+});
+DockColumnView.displayName = 'DockColumnView';
+
+export const DockWorkspace: React.FC<DockWorkspaceProps> = React.memo(({
+ themePreset,
+ colorMode,
+ commandHandlers,
+ onDeselect,
+ onTransformSelection,
+ onExpandSelection,
+ onContractSelection,
+ onFeatherSelection,
+ onInvertSelection,
+ onToggleTransparentColor,
+ layerSidebarProps,
+ children,
+}) => {
+ const layout = useWorkspaceStore((s) => s.layout);
+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
+ const openPopover = useWorkspaceStore((s) => s.openPopover);
+
+ const [customBrushes, setCustomBrushes] = useSharedCustomBrushes();
+ const [draggingPanelId, setDraggingPanelId] = useState<DockPanelId | null>(null);
+ const [edgeDropSide, setEdgeDropSide] = useState<DockSide | null>(null);
+ const workspaceRef = useRef<HTMLDivElement>(null);
+
+ const isVintage = themePreset === 'vintage-manga';
+
+ // Close collapsed-strip popover on Escape or outside click on canvas
+ useEffect(() => {
+ if (!openPopover) return;
+ const handleKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') workspaceStoreActions.closePopover();
+ };
+ window.addEventListener('keydown', handleKey);
+ return () => window.removeEventListener('keydown', handleKey);
+ }, [openPopover]);
+
+ const handleStartDragPanel = useCallback((panelId: DockPanelId) => {
+ setDraggingPanelId(panelId);
+ }, []);
+
+ const handleEndDragPanel = useCallback(() => {
+ setDraggingPanelId(null);
+ setEdgeDropSide(null);
+ }, []);
+
+ const handleDropEdge = (e: React.DragEvent, side: DockSide) => {
+ e.preventDefault();
+ const rawId =
+ (e.dataTransfer.getData(DND_PANEL_MIME) as DockPanelId) ||
+ (e.dataTransfer.getData('text/plain') as DockPanelId) ||
+ draggingPanelId;
+ if (rawId && DOCK_PANEL_META[rawId]) {
+ workspaceStoreActions.movePanel(rawId, {
+ side,
+ insertColumnIndex: side === 'left' ? layout.leftDocks.length : 0,
+ });
+ }
+ handleEndDragPanel();
+ };
+
+ const renderPanelBody = useCallback(
+ (panelId: DockPanelId, containerWidth: number): React.ReactNode => {
+ switch (panelId) {
+ case 'tools':
+ return (
+ <ToolStrip
+ fluid
+ onTransformSelection={onTransformSelection}
+ onToggleTransparentColor={onToggleTransparentColor}
+ />
+ );
+ case 'subtool':
+ return (
+ <div className="flex flex-col h-full min-h-0 overflow-hidden bg-[#202020]">
+ <SubToolList
+ customBrushes={customBrushes}
+ setCustomBrushes={setCustomBrushes}
+ />
+ </div>
+ );
+ case 'tool-property':
+ return (
+ <div className="flex flex-col h-full min-h-0 overflow-hidden bg-[#202020]">
+ <ToolPropertyInspector
+ width={containerWidth}
+ customBrushes={customBrushes}
+ setCustomBrushes={setCustomBrushes}
+ onDeselect={onDeselect}
+ onTransformSelection={onTransformSelection}
+ onExpandSelection={onExpandSelection}
+ onContractSelection={onContractSelection}
+ onFeatherSelection={onFeatherSelection}
+ onInvertSelection={onInvertSelection}
+ />
+ </div>
+ );
+ case 'brush-size':
+ return <BrushSizeDockedContent themePreset={themePreset} />;
+ case 'color':
+ return (
+ <RightSidebarColorSection
+ colorMode={colorMode}
+ containerWidth={containerWidth}
+ fullHeight
+ />
+ );
+ case 'layers':
+ return (
+ <RightSidebar
+ {...layerSidebarProps}
+ hideColorPanel
+ dockedMode="layers"
+ />
+ );
+ case 'history':
+ return (
+ <RightSidebar
+ {...layerSidebarProps}
+ hideColorPanel
+ dockedMode="history"
+ />
+ );
+ case 'quick-access':
+ return (
+ <QuickAccessPanel
+ handlers={commandHandlers}
+ themePreset={themePreset}
+ />
+ );
+ }
+ },
+ [
+ colorMode,
+ commandHandlers,
+ customBrushes,
+ layerSidebarProps,
+ onContractSelection,
+ onDeselect,
+ onExpandSelection,
+ onFeatherSelection,
+ onInvertSelection,
+ onToggleTransparentColor,
+ onTransformSelection,
+ setCustomBrushes,
+ themePreset,
+ ]
+ );
+
+ return (
+ <div
+ ref={workspaceRef}
+ data-testid="dock-workspace"
+ data-palettes-hidden={String(palettesHidden)}
+ className={`flex flex-1 min-h-0 overflow-hidden relative gap-px ${
+ isVintage ? 'bg-[#232325]' : 'bg-[#161616]'
+ }`}
+ >
+ {/* Left Dock Zone */}
+ {!palettesHidden && (
+ <div
+ data-testid="left-dock-zone"
+ className="flex h-full shrink-0 gap-px relative z-20"
+ >
+ {layout.leftDocks.map((col) => (
+ <DockColumnView
+ key={col.id}
+ side="left"
+ col={col}
+ themePreset={themePreset}
+ draggingPanelId={draggingPanelId}
+ onStartDragPanel={handleStartDragPanel}
+ onEndDragPanel={handleEndDragPanel}
+ renderPanelBody={renderPanelBody}
+ />
+ ))}
+
+ {/* Left-side New Column Drop Zone while dragging */}
+ {draggingPanelId && (
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setEdgeDropSide('left');
+ }}
+ onDragLeave={() => setEdgeDropSide(null)}
+ onDrop={(e) => handleDropEdge(e, 'left')}
+ className={`w-4 h-full transition-all flex items-center justify-center ${
+ edgeDropSide === 'left'
+ ? 'w-8 bg-[var(--accent-subtle)] border-2 border-dashed border-[var(--accent)]'
+ : 'bg-[var(--accent-subtle)]/30'
+ }`}
+ title="Drop to create new Left Dock column"
+ />
+ )}
+ </div>
+ )}
+
+ {/* Center Canvas Column (DocumentTabBar + CanvasArea + StatusBar) */}
+ <div
+ className="flex flex-col flex-1 min-w-0 min-h-0 overflow-hidden relative"
+ onMouseDown={() => {
+ if (openPopover) workspaceStoreActions.closePopover();
+ }}
+ >
+ {children}
+
+ {/* Unobtrusive Restore Palettes Pill when hidden via Tab */}
+ {palettesHidden && (
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.setPalettesHidden(false)}
+ data-testid="restore-palettes-pill"
+ title="Show Palettes (Tab)"
+ className="absolute top-2 right-2 z-30 h-6 px-2 rounded-full bg-[#202020]/90 hover:bg-[#2c2c2c] border border-white/[0.12] text-[10px] text-[#cccccc] hover:text-white flex items-center gap-1 shadow-lg cursor-pointer"
+ >
+ <Eye className="w-3 h-3 text-[var(--accent)]" />
+ <span>Show Palettes (Tab)</span>
+ </button>
+ )}
+ </div>
+
+ {/* Right Dock Zone */}
+ {!palettesHidden && (
+ <div
+ data-testid="right-dock-zone"
+ className="flex h-full shrink-0 gap-px relative z-20"
+ >
+ {/* Right-side New Column Drop Zone while dragging */}
+ {draggingPanelId && (
+ <div
+ onDragOver={(e) => {
+ e.preventDefault();
+ setEdgeDropSide('right');
+ }}
+ onDragLeave={() => setEdgeDropSide(null)}
+ onDrop={(e) => handleDropEdge(e, 'right')}
+ className={`w-4 h-full transition-all flex items-center justify-center ${
+ edgeDropSide === 'right'
+ ? 'w-8 bg-[var(--accent-subtle)] border-2 border-dashed border-[var(--accent)]'
+ : 'bg-[var(--accent-subtle)]/30'
+ }`}
+ title="Drop to create new Right Dock column"
+ />
+ )}
+
+ {layout.rightDocks.map((col) => (
+ <DockColumnView
+ key={col.id}
+ side="right"
+ col={col}
+ themePreset={themePreset}
+ draggingPanelId={draggingPanelId}
+ onStartDragPanel={handleStartDragPanel}
+ onEndDragPanel={handleEndDragPanel}
+ renderPanelBody={renderPanelBody}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+});
+
+DockWorkspace.displayName = 'DockWorkspace';
diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsx
new file mode 100644
index 0000000..1f64232
--- /dev/null
+++ b/src/components/DocumentLifecycleManager.tsx
@@ -0,0 +1,1071 @@
+import React, { useRef, useEffect, useCallback } from 'react';
+import {
+ CanvasColorMode,
+ CanvasDimensions,
+ DocumentTab,
+ LayerItem,
+ LoadedDocument,
+ NewCanvasOptions,
+} from '../types/editor';
+import { AppSettings, ResizeCanvasOptions } from '../types/settings';
+import { openFile } from '../utils/imageLoader';
+import {
+ promptExportPngImage,
+ promptSaveAs,
+ SaveDocumentData,
+ saveToExistingHandle,
+} from '../utils/saveManager';
+import { saveRecentDocument, RecentDocument } from '../utils/recentDocumentsManager';
+import { enforceColorMode } from '../utils/colorUtils';
+import { parseSutFile } from '../utils/sutParser';
+import {
+ deleteCustomBrush,
+ loadCustomBrushes,
+ prepareBrushSettingsForCsp,
+ saveCustomBrush,
+} from '../utils/brushStorage';
+import { documentStore } from '../utils/documentStore';
+import { recoveryService, CrashedSessionInfo } from '../services/recoveryService';
+import {
+ documentStoreActions,
+ toolStoreActions,
+ uiStoreActions,
+ useDocumentStore,
+ useToolStore,
+ useUiStore,
+} from '../stores';
+import { PushHistoryStepFn } from '../hooks/drawing';
+
+interface FileWithOptionalPath extends File {
+ path?: string;
+}
+
+interface TauriWindow extends Window {
+ __TAURI_INTERNALS__?: unknown;
+}
+
+export interface UseDocumentLifecycleParams {
+ layers: LayerItem[];
+ activeLayer: LayerItem | undefined;
+ activeLayerId: string;
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ getEffectiveOpacity: (layer: LayerItem) => number;
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
+ setActiveLayerId: (id: string) => void;
+ resetToNewCanvas: (
+ dims: CanvasDimensions,
+ bgColor: string,
+ mode: CanvasColorMode,
+ defaultFreq: number,
+ docId: string
+ ) => { layers: LayerItem[]; activeLayerId: string };
+ setDefaultToneFrequency: (freq: number) => void;
+ clearDocument: () => void;
+ loadDocument: (
+ doc: Pick<LoadedDocument, 'name' | 'dimensions' | 'colorMode' | 'layers'>,
+ sessionId?: string,
+ alreadyInGrid?: boolean
+ ) => void;
+ switchDocumentSession: (
+ docId: string,
+ layers: LayerItem[],
+ activeLayerId: string,
+ dimensions: CanvasDimensions
+ ) => void;
+ resizeCanvas: (newDims: CanvasDimensions, options: ResizeCanvasOptions) => void;
+ copyLayer: (id: string) => LayerItem | null;
+ pasteLayer: () => Promise<{ success: boolean; layerName?: string }>;
+ deleteLayer: (id: string) => void;
+ pasteLayerFromFile: (file: File) => Promise<string>;
+ resetZoomAndCenter: (dims?: CanvasDimensions) => void;
+ resetHistory: (targetDocumentId?: string) => void;
+ pushHistoryStep: PushHistoryStepFn;
+ showToast: (msg: string) => void;
+}
+
+export function useDocumentLifecycle({
+ layers,
+ activeLayer,
+ activeLayerId,
+ layerCanvasesRef,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ setActiveLayerId,
+ resetToNewCanvas,
+ setDefaultToneFrequency,
+ clearDocument,
+ loadDocument,
+ switchDocumentSession,
+ resizeCanvas,
+ copyLayer,
+ pasteLayer,
+ deleteLayer,
+ pasteLayerFromFile,
+ resetZoomAndCenter,
+ resetHistory,
+ pushHistoryStep,
+ showToast,
+}: UseDocumentLifecycleParams) {
+ const documents = useDocumentStore((s) => s.documents);
+ const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
+ const dimensions = useDocumentStore((s) => s.dimensions);
+ const colorMode = useDocumentStore((s) => s.colorMode);
+ const documentName = useDocumentStore((s) => s.documentName);
+ const savedFileInfo = useDocumentStore((s) => s.savedFileInfo);
+
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const pasteFileInputRef = useRef<HTMLInputElement>(null);
+ const import3DFileInputRef = useRef<HTMLInputElement>(null);
+ const needsAdaptiveFitRef = useRef<boolean>(true);
+ const pendingFitDimsRef = useRef<CanvasDimensions | null>(null);
+
+ const handleViewportReady = useCallback(
+ (viewport: HTMLDivElement) => {
+ if (needsAdaptiveFitRef.current) {
+ if (viewport.clientWidth <= 0 || viewport.clientHeight <= 0) {
+ return;
+ }
+ needsAdaptiveFitRef.current = false;
+ const targetDims = pendingFitDimsRef.current || useDocumentStore.getState().dimensions;
+ pendingFitDimsRef.current = null;
+ resetZoomAndCenter(targetDims);
+ }
+ },
+ [resetZoomAndCenter]
+ );
+
+ const handleCreateNewCanvas = useCallback(
+ (options: NewCanvasOptions) => {
+ const newDims: CanvasDimensions = {
+ width: options.width,
+ height: options.height,
+ dpi: options.dpi,
+ };
+ documentStoreActions.setDimensions(newDims);
+ documentStoreActions.setColorMode(options.colorMode);
+ let name = (options.name || 'Untitled').trim();
+ if (!/\.[a-zA-Z0-9]+$/.test(name) && !name.endsWith('*')) {
+ name = `${name}*`;
+ }
+ documentStoreActions.setDocumentName(name);
+ documentStoreActions.setSavedFileInfo(null);
+
+ const primaryColor = useToolStore.getState().primaryColor;
+ if (options.colorMode === 'monochrome') {
+ const snapPrimary = enforceColorMode(primaryColor, 'monochrome');
+ toolStoreActions.setPrimaryColor(snapPrimary, false, 'monochrome');
+ toolStoreActions.updateBrushSettings({ color: snapPrimary, hardness: 1.0 });
+ } else if (options.colorMode === 'grayscale') {
+ const snapPrimary = enforceColorMode(primaryColor, 'grayscale');
+ toolStoreActions.setPrimaryColor(snapPrimary, false, 'grayscale');
+ toolStoreActions.updateBrushSettings({ color: snapPrimary });
+ }
+
+ const defaultFreq = options.defaultFrequency ?? 60;
+ const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+ const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
+ newDims,
+ options.backgroundColor,
+ options.colorMode,
+ defaultFreq,
+ newDocId
+ );
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = newDims;
+ resetZoomAndCenter(newDims);
+ resetHistory(newDocId);
+
+ const newDoc: DocumentTab = {
+ id: newDocId,
+ name,
+ dimensions: newDims,
+ colorMode: options.colorMode,
+ layers: initialLayers,
+ activeLayerId: topId,
+ perspectiveRuler: null,
+ defaultFrequency: defaultFreq,
+ };
+
+ documentStoreActions.setPerspectiveRuler(null);
+ documentStoreActions.setDocuments((prev) => [...prev, newDoc]);
+ documentStoreActions.setActiveDocumentId(newDocId);
+ uiStoreActions.setAppView('workspace');
+ showToast(`Created ${name}`);
+ },
+ [resetHistory, resetToNewCanvas, resetZoomAndCenter, showToast]
+ );
+
+ const handleCopySelectedLayer = useCallback(() => {
+ if (!activeLayer) return;
+ const copied = copyLayer(activeLayerId);
+ if (copied) {
+ showToast(`Copied layer "${copied.name}"`);
+ }
+ }, [activeLayer, activeLayerId, copyLayer, showToast]);
+
+ const handlePasteSelectedLayer = useCallback(async () => {
+ const res = await pasteLayer();
+ if (res.success && res.layerName) {
+ showToast(`Pasted layer "${res.layerName}"`);
+ } else {
+ showToast('Clipboard is empty');
+ }
+ }, [pasteLayer, showToast]);
+
+ const handleDeleteSelectedLayer = useCallback(() => {
+ const rasterCount = layers.filter((l) => l.type === 'raster').length;
+ if (rasterCount <= 1) {
+ showToast('Cannot delete the only raster layer');
+ return;
+ }
+ const layerName = activeLayer?.name || 'layer';
+ deleteLayer(activeLayerId);
+ showToast(`Deleted layer "${layerName}"`);
+ }, [activeLayer, activeLayerId, deleteLayer, layers, showToast]);
+
+ const handleTriggerPasteFromFile = useCallback(() => {
+ pasteFileInputRef.current?.click();
+ }, []);
+
+ const handlePasteFileInputChange = useCallback(
+ async (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (file) {
+ try {
+ const layerName = await pasteLayerFromFile(file);
+ showToast(`Pasted "${layerName}" from file`);
+ } catch (err: unknown) {
+ console.error('Failed to paste from file:', err);
+ const errMsg = err instanceof Error ? err.message : String(err);
+ alert(`Failed to paste image from file: ${errMsg}`);
+ } finally {
+ if (pasteFileInputRef.current) {
+ pasteFileInputRef.current.value = '';
+ }
+ }
+ }
+ },
+ [pasteLayerFromFile, showToast]
+ );
+
+ const handleTriggerImport3DFile = useCallback(() => {
+ import3DFileInputRef.current?.click();
+ }, []);
+
+ const handleImport3DFileInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (file) {
+ uiStoreActions.set3DLayerOpen(true, file);
+ showToast(`Importing 3D model "${file.name}" into local ghost layer...`);
+ if (import3DFileInputRef.current) {
+ import3DFileInputRef.current.value = '';
+ }
+ }
+ },
+ [showToast]
+ );
+
+ const handleResizeCanvas = useCallback(
+ (options: ResizeCanvasOptions) => {
+ const curDims = useDocumentStore.getState().dimensions;
+ const newDims: CanvasDimensions = {
+ width: options.width,
+ height: options.height,
+ dpi: options.dpi || curDims.dpi,
+ };
+
+ resizeCanvas(newDims, options);
+ documentStoreActions.setDimensions(newDims);
+ pendingFitDimsRef.current = newDims;
+ needsAdaptiveFitRef.current = true;
+ resetZoomAndCenter(newDims);
+ resetHistory();
+ showToast(`Canvas resized to ${newDims.width} × ${newDims.height} px`);
+ },
+ [resetHistory, resetZoomAndCenter, resizeCanvas, showToast]
+ );
+
+ const handleUpdateSettings = useCallback((newSettings: AppSettings) => {
+ uiStoreActions.updateAppSettings(newSettings);
+ documentStore.setTileBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
+ toolStoreActions.updateBrushSettings({
+ stabilization: newSettings.defaultStabilization,
+ usePressure: newSettings.usePressureByDefault,
+ smoothing: newSettings.smoothingEnabled,
+ });
+ }, []);
+
+ const handleProcessFile = useCallback(
+ async (file: File) => {
+ if (file.name.toLowerCase().endsWith('.sut')) {
+ try {
+ uiStoreActions.setLoading(true, `Importing CSP Brush: ${file.name}...`);
+ const buffer = await file.arrayBuffer();
+ const parsedBrush = await parseSutFile(buffer, file.name);
+ const existing = (await loadCustomBrushes()).filter(
+ (b) =>
+ b.name.toLowerCase() === parsedBrush.name.toLowerCase() || b.id === parsedBrush.id
+ );
+ for (const old of existing) {
+ await deleteCustomBrush(old.id).catch(() => {});
+ }
+ await saveCustomBrush(parsedBrush);
+ toolStoreActions.setToolRaw('brush');
+ const fullSettings = await prepareBrushSettingsForCsp(parsedBrush);
+ toolStoreActions.updateBrushSettings(fullSettings);
+ showToast(`Imported CSP brush "${parsedBrush.name}" successfully!`);
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : 'Failed to import .sut brush.';
+ showToast(msg);
+ } finally {
+ uiStoreActions.setLoading(false, '');
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ }
+ }
+ return;
+ }
+
+ try {
+ uiStoreActions.setLoading(true, `Loading ${file.name}...`);
+
+ const doc = await openFile(file);
+ const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+ documentStoreActions.setDimensions(doc.dimensions);
+ documentStoreActions.setColorMode(doc.colorMode);
+ documentStoreActions.setDocumentName(doc.name);
+ documentStoreActions.setSavedFileInfo(null);
+
+ loadDocument(doc, newDocId);
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = doc.dimensions;
+ resetZoomAndCenter(doc.dimensions);
+ resetHistory(newDocId);
+
+ const newDoc: DocumentTab = {
+ id: newDocId,
+ name: doc.name,
+ dimensions: doc.dimensions,
+ colorMode: doc.colorMode,
+ layers: doc.layers,
+ activeLayerId: doc.layers[0]?.id || 'layer-1',
+ perspectiveRuler: null,
+ };
+
+ documentStoreActions.setPerspectiveRuler(null);
+ documentStoreActions.setDocuments((prev) => [...prev, newDoc]);
+ documentStoreActions.setActiveDocumentId(newDocId);
+
+ const fileWithPath = file as FileWithOptionalPath;
+ saveRecentDocument({
+ id: newDocId,
+ title: file.name,
+ path: fileWithPath.path || `C:\\Users\\Artist\\Documents\\InkStudio\\${file.name}`,
+ size: file.size || 1048576,
+ coverUrl: doc.layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: file.name.slice(file.name.lastIndexOf('.')),
+ isSaved: true,
+ }).catch(console.warn);
+
+ showToast(`Opened ${file.name}`);
+ } catch (err: unknown) {
+ console.error('Failed to open file:', err);
+ const errMsg = err instanceof Error ? err.message : String(err);
+ alert(`Could not open "${file.name}":\n${errMsg || 'Unsupported or corrupted file.'}`);
+ } finally {
+ uiStoreActions.setLoading(false, '');
+ if (fileInputRef.current) {
+ fileInputRef.current.value = '';
+ }
+ }
+ },
+ [loadDocument, resetHistory, resetZoomAndCenter, showToast]
+ );
+
+ const handleSelectDocument = useCallback(
+ (id: string) => {
+ if (id === activeDocumentId) {
+ uiStoreActions.setAppView('workspace');
+ return;
+ }
+ const doc = documents.find((d) => d.id === id);
+ if (!doc) return;
+ uiStoreActions.setAppView('workspace');
+ documentStoreActions.setDimensions(doc.dimensions);
+ documentStoreActions.setColorMode(doc.colorMode);
+ documentStoreActions.setDocumentName(doc.name);
+ if (doc.defaultFrequency) {
+ setDefaultToneFrequency(doc.defaultFrequency);
+ }
+ if (doc.savedFileInfo && doc.savedFileInfo.extension) {
+ documentStoreActions.setSavedFileInfo({
+ name: doc.savedFileInfo.name,
+ handle: doc.savedFileInfo.handle,
+ extension: doc.savedFileInfo.extension,
+ });
+ } else {
+ documentStoreActions.setSavedFileInfo(null);
+ }
+ switchDocumentSession(id, doc.layers || [], doc.activeLayerId || '', doc.dimensions);
+ documentStoreActions.setActiveDocumentId(id);
+ documentStoreActions.setPerspectiveRuler(doc.perspectiveRuler ?? null);
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = doc.dimensions;
+ resetZoomAndCenter(doc.dimensions);
+ },
+ [activeDocumentId, documents, resetZoomAndCenter, setDefaultToneFrequency, switchDocumentSession]
+ );
+
+ const handleCloseDocument = useCallback(
+ (id: string) => {
+ documentStoreActions.setDocuments((prev) => {
+ const next = prev.filter((d) => d.id !== id);
+ if (id === activeDocumentId) {
+ if (next.length > 0) {
+ const nextActive = next[next.length - 1];
+ documentStoreActions.setDimensions(nextActive.dimensions);
+ documentStoreActions.setColorMode(nextActive.colorMode);
+ documentStoreActions.setDocumentName(nextActive.name);
+ documentStoreActions.setPerspectiveRuler(nextActive.perspectiveRuler ?? null);
+ if (nextActive.savedFileInfo && nextActive.savedFileInfo.extension) {
+ documentStoreActions.setSavedFileInfo({
+ name: nextActive.savedFileInfo.name,
+ handle: nextActive.savedFileInfo.handle,
+ extension: nextActive.savedFileInfo.extension,
+ });
+ } else {
+ documentStoreActions.setSavedFileInfo(null);
+ }
+ if (nextActive.layers && nextActive.layers.length > 0) {
+ switchDocumentSession(
+ nextActive.id,
+ nextActive.layers,
+ nextActive.activeLayerId || '',
+ nextActive.dimensions
+ );
+ documentStoreActions.setActiveDocumentId(nextActive.id);
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = nextActive.dimensions;
+ resetZoomAndCenter(nextActive.dimensions);
+ } else {
+ documentStoreActions.setActiveDocumentId(nextActive.id);
+ clearDocument();
+ }
+ } else {
+ documentStore.setActiveDocument(null);
+ documentStoreActions.setActiveDocumentId(null);
+ documentStoreActions.setDocumentName('');
+ documentStoreActions.setSavedFileInfo(null);
+ clearDocument();
+ documentStoreActions.setPerspectiveRuler(null);
+ uiStoreActions.setAppView('home');
+ }
+ }
+ return next;
+ });
+ if (id) {
+ documentStore.closeSession(id).catch(console.warn);
+ recoveryService.closeSession(id).catch(console.warn);
+ }
+ },
+ [activeDocumentId, clearDocument, resetZoomAndCenter, switchDocumentSession]
+ );
+
+ const handleRestoreCrashedSession = useCallback(
+ async (session: CrashedSessionInfo) => {
+ try {
+ const replayData = await recoveryService.loadSessionData(session.session_id);
+ const restoredSession = documentStore.getOrCreateSession(session.session_id);
+ const { manifest, replayedStrokesCount, replayedMutationsCount } =
+ recoveryService.replaySessionData(replayData, restoredSession.tileGrid);
+
+ const restoredDims: CanvasDimensions = {
+ width: manifest.width,
+ height: manifest.height,
+ dpi: manifest.dpi,
+ };
+
+ loadDocument(
+ {
+ name: manifest.documentName,
+ dimensions: restoredDims,
+ colorMode: manifest.colorMode,
+ layers: manifest.layers,
+ },
+ session.session_id,
+ true
+ );
+ if (manifest.activeLayerId) {
+ setActiveLayerId(manifest.activeLayerId);
+ }
+
+ documentStoreActions.setDimensions(restoredDims);
+ documentStoreActions.setColorMode(manifest.colorMode);
+ documentStoreActions.setDocumentName(manifest.documentName);
+
+ const restoredDoc: DocumentTab = {
+ id: session.session_id,
+ name: manifest.documentName,
+ dimensions: restoredDims,
+ colorMode: manifest.colorMode,
+ layers: manifest.layers,
+ activeLayerId: manifest.activeLayerId || manifest.layers[0]?.id || '',
+ };
+
+ documentStoreActions.setDocuments((prev) => {
+ const filtered = prev.filter((d) => d.id !== session.session_id);
+ return [restoredDoc, ...filtered];
+ });
+ documentStoreActions.setActiveDocumentId(session.session_id);
+ uiStoreActions.setAppView('workspace');
+
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = restoredDims;
+ resetZoomAndCenter(restoredDims);
+ resetHistory(session.session_id);
+
+ pushHistoryStep(
+ 'initial',
+ 'Session restored from crash',
+ null,
+ null,
+ manifest.activeLayerId || manifest.layers[0]?.id || ''
+ );
+
+ restoredSession.tileGrid.notifyChange(true);
+
+ uiStoreActions.setRecoveryModal(false);
+ uiStoreActions.setCrashedSessions((prev) =>
+ prev.filter((s) => s.session_id !== session.session_id)
+ );
+ showToast(
+ `Restored "${manifest.documentName}" (${replayedStrokesCount} strokes, ${replayedMutationsCount} mutations recovered)`
+ );
+ } catch (err: unknown) {
+ console.error('[Recovery] Restore error:', err);
+ const msg = err instanceof Error ? err.message : String(err);
+ alert('Failed to restore crashed session: ' + msg);
+ }
+ },
+ [loadDocument, resetHistory, resetZoomAndCenter, showToast, pushHistoryStep, setActiveLayerId]
+ );
+
+ const handleDiscardCrashedSession = useCallback(
+ async (session: CrashedSessionInfo) => {
+ try {
+ await recoveryService.discardCrashedSession(session.session_id);
+ uiStoreActions.setCrashedSessions((prev) => {
+ const next = prev.filter((s) => s.session_id !== session.session_id);
+ if (next.length === 0) {
+ uiStoreActions.setRecoveryModal(false);
+ }
+ return next;
+ });
+ showToast('Crashed session discarded');
+ } catch (err: unknown) {
+ console.warn('[Recovery] Discard error:', err);
+ }
+ },
+ [showToast]
+ );
+
+ const handleRenameDocument = useCallback(
+ (id: string, newName: string) => {
+ documentStoreActions.setDocuments((prev) =>
+ prev.map((d) => (d.id === id ? { ...d, name: newName } : d))
+ );
+ if (id === activeDocumentId) {
+ documentStoreActions.setDocumentName(newName);
+ }
+ },
+ [activeDocumentId]
+ );
+
+ const handleTriggerOpenFile = useCallback(() => {
+ fileInputRef.current?.click();
+ }, []);
+
+ const handleFileInputChange = useCallback(
+ (e: React.ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files?.[0];
+ if (file) {
+ handleProcessFile(file);
+ }
+ },
+ [handleProcessFile]
+ );
+
+ const handleSave = useCallback(async () => {
+ const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
+ const docData: SaveDocumentData = {
+ name: cleanNameForSave,
+ dimensions,
+ colorMode,
+ layers,
+ layerCanvasesMap: layerCanvasesRef.current,
+ tileGrid: documentStore.getActiveTileGrid(),
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ tabId: activeDocumentId || undefined,
+ };
+
+ if (!savedFileInfo?.handle) {
+ try {
+ const info = await promptSaveAs(docData, savedFileInfo?.extension || '.sora');
+ documentStoreActions.setSavedFileInfo(info);
+ documentStoreActions.setDocumentName(info.name);
+ documentStoreActions.setDocuments((prev) =>
+ prev.map((d) =>
+ d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info, isDirty: false } : d
+ )
+ );
+ saveRecentDocument({
+ id: activeDocumentId || `doc-${Date.now()}`,
+ title: info.name,
+ path: `InkStudio\\${info.name}`,
+ size: 1572864,
+ coverUrl: layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: info.extension,
+ isSaved: true,
+ }).catch(console.warn);
+ showToast(`Saved to ${info.name}`);
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg !== 'Save canceled') {
+ alert('Failed to save file: ' + msg);
+ }
+ }
+ } else {
+ try {
+ await saveToExistingHandle(docData, savedFileInfo);
+ documentStoreActions.setDocumentName(savedFileInfo.name);
+ documentStoreActions.setDocuments((prev) =>
+ prev.map((d) =>
+ d.id === activeDocumentId ? { ...d, name: savedFileInfo.name, isDirty: false } : d
+ )
+ );
+ saveRecentDocument({
+ id: activeDocumentId || `doc-${Date.now()}`,
+ title: savedFileInfo.name,
+ path: `InkStudio\\${savedFileInfo.name}`,
+ size: 1572864,
+ coverUrl: layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: savedFileInfo.extension,
+ isSaved: true,
+ }).catch(console.warn);
+ showToast(`Saved to ${savedFileInfo.name}`);
+ } catch (err: unknown) {
+ console.warn('Direct handle save failed, prompting with Save As:', err);
+ try {
+ const info = await promptSaveAs(docData, savedFileInfo.extension || '.sora');
+ documentStoreActions.setSavedFileInfo(info);
+ documentStoreActions.setDocumentName(info.name);
+ documentStoreActions.setDocuments((prev) =>
+ prev.map((d) =>
+ d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info, isDirty: false } : d
+ )
+ );
+ saveRecentDocument({
+ id: activeDocumentId || `doc-${Date.now()}`,
+ title: info.name,
+ path: `InkStudio\\${info.name}`,
+ size: 1572864,
+ coverUrl: layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: info.extension,
+ isSaved: true,
+ }).catch(console.warn);
+ showToast(`Saved to ${info.name}`);
+ } catch (e: unknown) {
+ const msg = e instanceof Error ? e.message : String(e);
+ if (msg !== 'Save canceled') {
+ alert('Failed to save file: ' + msg);
+ }
+ }
+ }
+ }
+ }, [
+ activeDocumentId,
+ colorMode,
+ dimensions,
+ documentName,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ layerCanvasesRef,
+ layers,
+ savedFileInfo,
+ showToast,
+ ]);
+
+ const handleSaveAs = useCallback(async () => {
+ const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
+ const docData: SaveDocumentData = {
+ name: cleanNameForSave,
+ dimensions,
+ colorMode,
+ layers,
+ layerCanvasesMap: layerCanvasesRef.current,
+ tileGrid: documentStore.getActiveTileGrid(),
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ tabId: activeDocumentId || undefined,
+ };
+
+ try {
+ const defaultExt = savedFileInfo?.extension || '.sora';
+ const info = await promptSaveAs(docData, defaultExt);
+ documentStoreActions.setSavedFileInfo(info);
+ documentStoreActions.setDocumentName(info.name);
+ documentStoreActions.setDocuments((prev) =>
+ prev.map((d) =>
+ d.id === activeDocumentId ? { ...d, name: info.name, savedFileInfo: info, isDirty: false } : d
+ )
+ );
+ saveRecentDocument({
+ id: activeDocumentId || `doc-${Date.now()}`,
+ title: info.name,
+ path: `InkStudio\\${info.name}`,
+ size: 1572864,
+ coverUrl: layers[0]?.thumbnailUrl,
+ isStarred: false,
+ fileType: info.extension,
+ isSaved: true,
+ }).catch(console.warn);
+ showToast(`Saved as ${info.name}`);
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg !== 'Save canceled') {
+ alert('Failed to save file: ' + msg);
+ }
+ }
+ }, [
+ activeDocumentId,
+ colorMode,
+ dimensions,
+ documentName,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ layerCanvasesRef,
+ layers,
+ savedFileInfo,
+ showToast,
+ ]);
+
+ const handleExportImage = useCallback(async () => {
+ const cleanNameForSave = documentName.replace(/\*+$/, '') || 'Untitled';
+ const docData: SaveDocumentData = {
+ name: cleanNameForSave,
+ dimensions,
+ colorMode,
+ layers,
+ layerCanvasesMap: layerCanvasesRef.current,
+ tileGrid: documentStore.getActiveTileGrid(),
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ };
+
+ try {
+ const exportedName = await promptExportPngImage(docData, cleanNameForSave);
+ showToast(`Exported image to ${exportedName}`);
+ } catch (err: unknown) {
+ const msg = err instanceof Error ? err.message : String(err);
+ if (msg !== 'Export canceled') {
+ alert('Failed to export image: ' + msg);
+ }
+ }
+ }, [
+ colorMode,
+ dimensions,
+ documentName,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ layerCanvasesRef,
+ layers,
+ showToast,
+ ]);
+
+ const handleSelectWelcomeDocument = useCallback(
+ async (doc: RecentDocument) => {
+ if (typeof window !== 'undefined' && (window as TauriWindow).__TAURI_INTERNALS__) {
+ try {
+ const { invoke } = await import('@tauri-apps/api/core');
+ const bytes = await invoke<number[]>('read_file_from_disk', { path: doc.path });
+ if (bytes && bytes.length > 0) {
+ const uint8 = new Uint8Array(bytes);
+ const file = new File([uint8], doc.title, { type: 'application/octet-stream' });
+ await handleProcessFile(file);
+ uiStoreActions.setAppView('workspace');
+ return;
+ }
+ } catch (err) {
+ console.warn('Direct disk read via Tauri failed, fallback:', err);
+ }
+ }
+
+ handleCreateNewCanvas({
+ width: 1920,
+ height: 1080,
+ dpi: 300,
+ colorMode: 'color',
+ name: doc.title,
+ backgroundColor: '#ffffff',
+ aspectRatioPreset: '16:9',
+ aspectRatioX: 16,
+ aspectRatioY: 9,
+ lockAspectRatio: true,
+ });
+ showToast(`Loaded workspace for "${doc.title}"`);
+ },
+ [handleCreateNewCanvas, handleProcessFile, showToast]
+ );
+
+ return {
+ fileInputRef,
+ pasteFileInputRef,
+ import3DFileInputRef,
+ needsAdaptiveFitRef,
+ pendingFitDimsRef,
+ handleViewportReady,
+ handleCreateNewCanvas,
+ handleCopySelectedLayer,
+ handlePasteSelectedLayer,
+ handleDeleteSelectedLayer,
+ handleTriggerPasteFromFile,
+ handlePasteFileInputChange,
+ handleTriggerImport3DFile,
+ handleImport3DFileInputChange,
+ handleResizeCanvas,
+ handleUpdateSettings,
+ handleProcessFile,
+ handleSelectDocument,
+ handleCloseDocument,
+ handleRestoreCrashedSession,
+ handleDiscardCrashedSession,
+ handleRenameDocument,
+ handleTriggerOpenFile,
+ handleFileInputChange,
+ handleSave,
+ handleSaveAs,
+ handleExportImage,
+ handleSelectWelcomeDocument,
+ };
+}
+
+export interface DocumentLifecycleManagerProps {
+ layers: LayerItem[];
+ activeLayerId: string;
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ needsAdaptiveFitRef: React.MutableRefObject<boolean>;
+ pendingFitDimsRef: React.MutableRefObject<CanvasDimensions | null>;
+ resetToNewCanvas: (
+ dims: CanvasDimensions,
+ bgColor: string,
+ mode: CanvasColorMode,
+ defaultFreq: number,
+ docId: string
+ ) => { layers: LayerItem[]; activeLayerId: string };
+ resetZoomAndCenter: (dims?: CanvasDimensions) => void;
+ resetHistory: (targetDocumentId?: string) => void;
+}
+
+/**
+ * Headless lifecycle coordinator: handles startup crash recovery detection,
+ * initial canvas creation, WAL checkpointing, tile memory budget sync,
+ * and active document tab metadata synchronization.
+ */
+export const DocumentLifecycleManager: React.FC<DocumentLifecycleManagerProps> = React.memo(
+ ({
+ layers,
+ activeLayerId,
+ layerCanvasesRef,
+ needsAdaptiveFitRef,
+ pendingFitDimsRef,
+ resetToNewCanvas,
+ resetZoomAndCenter,
+ resetHistory,
+ }) => {
+ const documents = useDocumentStore((s) => s.documents);
+ const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
+ const dimensions = useDocumentStore((s) => s.dimensions);
+ const colorMode = useDocumentStore((s) => s.colorMode);
+ const documentName = useDocumentStore((s) => s.documentName);
+ const appSettings = useUiStore((s) => s.appSettings);
+
+ // 1. Scan for unfinalized crashed WAL sessions on launch
+ useEffect(() => {
+ recoveryService
+ .checkForCrashedSessions()
+ .then((sessions) => {
+ if (sessions && sessions.length > 0) {
+ uiStoreActions.setRecoveryModal(true, sessions);
+ }
+ })
+ .catch((err) => {
+ console.warn('[Recovery] Error scanning for crashed sessions:', err);
+ });
+ }, []);
+
+ // 2. Synchronize tile memory budget across all open documents
+ useEffect(() => {
+ documentStore.setTileBudgetMb(appSettings.tileMemoryBudgetMb || 1024);
+ }, [appSettings.tileMemoryBudgetMb]);
+
+ // 3. Auto-create initial white canvas on launch
+ const hasAutoCreatedInitialDocRef = useRef(false);
+ useEffect(() => {
+ if (hasAutoCreatedInitialDocRef.current || documents.length > 0) return;
+ hasAutoCreatedInitialDocRef.current = true;
+ const initDims: CanvasDimensions = {
+ width: appSettings.defaultWidth || 1920,
+ height: appSettings.defaultHeight || 1080,
+ dpi: appSettings.defaultDpi || 300,
+ };
+ const initColorMode = appSettings.defaultColorMode || 'color';
+ const initBg = appSettings.defaultBgColor || '#ffffff';
+ const initName = 'Untitled*';
+ const newDocId = `doc-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
+ documentStoreActions.setDimensions(initDims);
+ documentStoreActions.setColorMode(initColorMode);
+ documentStoreActions.setDocumentName(initName);
+ const { layers: initialLayers, activeLayerId: topId } = resetToNewCanvas(
+ initDims,
+ initBg,
+ initColorMode,
+ 60,
+ newDocId
+ );
+ needsAdaptiveFitRef.current = true;
+ pendingFitDimsRef.current = initDims;
+ resetZoomAndCenter(initDims);
+ resetHistory(newDocId);
+ documentStoreActions.setDocuments([
+ {
+ id: newDocId,
+ name: initName,
+ dimensions: initDims,
+ colorMode: initColorMode,
+ layers: initialLayers,
+ activeLayerId: topId,
+ perspectiveRuler: null,
+ defaultFrequency: 60,
+ },
+ ]);
+ documentStoreActions.setActiveDocumentId(newDocId);
+ uiStoreActions.setAppView('workspace');
+ }, [
+ appSettings.defaultBgColor,
+ appSettings.defaultColorMode,
+ appSettings.defaultDpi,
+ appSettings.defaultHeight,
+ appSettings.defaultWidth,
+ documents.length,
+ needsAdaptiveFitRef,
+ pendingFitDimsRef,
+ resetHistory,
+ resetToNewCanvas,
+ resetZoomAndCenter,
+ ]);
+
+ // 4. Sync active document recovery session & WAL periodic checkpointing
+ const recoveryStateRef = useRef({
+ documents,
+ documentName,
+ dimensions,
+ colorMode,
+ layers,
+ activeLayerId,
+ });
+ recoveryStateRef.current = {
+ documents,
+ documentName,
+ dimensions,
+ colorMode,
+ layers,
+ activeLayerId,
+ };
+
+ useEffect(() => {
+ if (!activeDocumentId) return;
+ const st = recoveryStateRef.current;
+ const initDoc = st.documents.find((d) => d.id === activeDocumentId);
+ if (!initDoc) return;
+
+ recoveryService.initSession(
+ activeDocumentId,
+ () => {
+ const cur = recoveryStateRef.current;
+ const doc = cur.documents.find((d) => d.id === activeDocumentId);
+ return {
+ sessionId: activeDocumentId,
+ documentName: doc?.name || cur.documentName || 'Untitled Document',
+ width: doc?.dimensions.width || cur.dimensions.width,
+ height: doc?.dimensions.height || cur.dimensions.height,
+ dpi: doc?.dimensions.dpi || cur.dimensions.dpi || 600,
+ colorMode: doc?.colorMode || cur.colorMode || 'color',
+ layers: doc?.layers || cur.layers,
+ activeLayerId: doc?.activeLayerId || cur.activeLayerId,
+ timestamp: Date.now(),
+ };
+ },
+ async () => {
+ const cur = recoveryStateRef.current;
+ const doc = cur.documents.find((d) => d.id === activeDocumentId);
+ const targetLayerId = doc?.activeLayerId || cur.activeLayerId;
+ const dims = doc?.dimensions || cur.dimensions;
+ if (!targetLayerId || dims.width <= 0 || dims.height <= 0) return null;
+ try {
+ const thumbW = 120;
+ const thumbH = Math.max(
+ 68,
+ Math.round((dims.height / Math.max(1, dims.width)) * thumbW)
+ );
+ const dataUrl = documentStore
+ .getActiveTileGrid()
+ .generateThumbnail(targetLayerId, thumbW, thumbH, dims);
+ const commaIdx = dataUrl.indexOf(',');
+ if (commaIdx < 0) return null;
+ const b64 = dataUrl.slice(commaIdx + 1);
+ const binStr = atob(b64);
+ const bytes = new Uint8Array(binStr.length);
+ for (let i = 0; i < binStr.length; i++) {
+ bytes[i] = binStr.charCodeAt(i);
+ }
+ return bytes;
+ } catch {
+ return null;
+ }
+ }
+ );
+ }, [activeDocumentId, layerCanvasesRef]);
+
+ // 5. Keep active document tab's metadata in sync
+ useEffect(() => {
+ if (!activeDocumentId) return;
+ documentStoreActions.setActiveLayerId(activeLayerId);
+ documentStoreActions.setDocuments((prev) => {
+ const curr = prev.find((d) => d.id === activeDocumentId);
+ if (!curr) return prev;
+ if (curr.layers === layers && curr.activeLayerId === activeLayerId) {
+ return prev;
+ }
+ return prev.map((d) =>
+ d.id === activeDocumentId
+ ? {
+ ...d,
+ layers,
+ activeLayerId,
+ }
+ : d
+ );
+ });
+ }, [layers, activeLayerId, activeDocumentId]);
+
+ return null;
+ }
+);
+
+DocumentLifecycleManager.displayName = 'DocumentLifecycleManager';
diff --git a/src/components/DocumentTabBar.tsx b/src/components/DocumentTabBar.tsx
index 6f8e05b..93f0629 100644
--- a/src/components/DocumentTabBar.tsx
+++ b/src/components/DocumentTabBar.tsx
@@ -3,7 +3,7 @@ import { X, Plus, File } from 'lucide-react';
import { DocumentTab } from '../types/editor';
import { ThemePreset } from '../types/settings';
-interface DocumentTabBarProps {
+export interface DocumentTabBarProps {
documents: DocumentTab[];
activeDocumentId: string | null;
onSelectDocument: (id: string) => void;
@@ -20,7 +20,7 @@ export const DocumentTabBar: React.FC<DocumentTabBarProps> = React.memo(({
onCloseDocument,
onNewDocument,
onRenameDocument,
- themePreset: _themePreset = 'vintage-manga',
+ themePreset = 'modern',
}) => {
const [editingId, setEditingId] = useState<string | null>(null);
const [editingName, setEditingName] = useState<string>('');
@@ -38,30 +38,36 @@ export const DocumentTabBar: React.FC<DocumentTabBarProps> = React.memo(({
setEditingId(null);
};
- if (_themePreset === 'modern') {
+ if (themePreset === 'modern') {
return (
- <div className="h-8 flex items-center px-2 select-none z-20 shrink-0 overflow-x-auto no-scrollbar bg-[#0f1015] border-b border-white/[0.08]">
- {/* List of Document Tabs */}
- <div className="flex items-center space-x-1.5 h-full py-1">
+ <div
+ data-testid="document-tab-bar"
+ data-theme-preset="modern"
+ className="h-7 flex items-center px-1.5 select-none z-20 shrink-0 overflow-x-auto no-scrollbar bg-[#1a1a1a] border-b border-white/[0.06]"
+ >
+ <div className="flex items-center space-x-1 h-full py-0.5">
{documents.map((doc) => {
const isActive = doc.id === activeDocumentId;
+ const isDirty = Boolean(doc.isDirty);
return (
<div
key={doc.id}
onClick={() => onSelectDocument(doc.id)}
onDoubleClick={(e) => handleStartRename(e, doc)}
- title={`${doc.name} (${doc.dimensions.width}×${doc.dimensions.height}px)`}
- className={`group relative h-full flex items-center space-x-2 px-2.5 rounded-md text-xs cursor-pointer transition-all ${
+ title={`${doc.name}${isDirty ? ' *' : ''} (${doc.dimensions.width}×${doc.dimensions.height}px)`}
+ className={`group relative h-full flex items-center space-x-1.5 px-2.5 rounded text-[11px] cursor-pointer transition-colors ${
isActive
- ? 'bg-[#181920] text-white font-medium border border-white/[0.1] shadow-xs'
- : 'text-white/60 hover:text-white/90 hover:bg-white/[0.04] border border-transparent'
+ ? 'bg-[#262626] text-[#e5e5e5] font-medium border border-white/[0.08]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 border border-transparent'
}`}
>
- {/* Document Icon */}
- <File className={`w-3.5 h-3.5 shrink-0 ${isActive ? 'text-[var(--modern-accent)]' : 'text-white/40'}`} />
+ <File
+ className={`w-3 h-3 shrink-0 ${
+ isActive ? 'text-[var(--accent)]' : 'text-[#666666]'
+ }`}
+ />
- {/* Document Name / Inline Rename Input */}
{editingId === doc.id ? (
<input
type="text"
@@ -74,42 +80,54 @@ export const DocumentTabBar: React.FC<DocumentTabBarProps> = React.memo(({
}}
autoFocus
onClick={(e) => e.stopPropagation()}
- className="bg-[#101116] text-white text-xs px-1.5 py-0.5 rounded-sm outline-none border border-[var(--modern-accent)] w-28"
+ className="bg-[#161616] text-[#e5e5e5] text-[11px] px-1 py-0.5 rounded-sm outline-none border border-[var(--accent)] w-28"
/>
) : (
- <span className="truncate max-w-[160px] tracking-normal">{doc.name}</span>
+ <span className="truncate max-w-[160px] tracking-normal">
+ {doc.name}
+ {isDirty && (
+ <span
+ data-testid={`dirty-indicator-${doc.id}`}
+ className="ml-0.5 text-[var(--accent)] font-bold"
+ title="Unsaved changes"
+ >
+ *
+ </span>
+ )}
+ </span>
)}
- {/* Close Button */}
<button
+ type="button"
onClick={(e) => {
e.stopPropagation();
onCloseDocument(doc.id);
}}
+ aria-label={`Close ${doc.name}`}
title="Close file"
- className={`p-0.5 rounded transition-colors ${
+ className={`p-0.5 rounded transition-colors cursor-pointer ${
isActive
- ? 'text-white/50 hover:text-white hover:bg-white/10'
- : 'text-transparent group-hover:text-white/40 hover:!text-white hover:bg-white/10'
+ ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-white/10'
+ : 'text-transparent group-hover:text-[#8a8a8a] hover:!text-[#e5e5e5] hover:bg-white/10'
}`}
>
<X className="w-3 h-3" />
</button>
- {/* Active Tab Accent Underline */}
{isActive && (
- <div className="absolute bottom-0 left-2 right-2 h-[2px] bg-[var(--modern-accent)] rounded-full" />
+ <div className="absolute bottom-0 left-2 right-2 h-[2px] bg-[var(--accent)] rounded-full" />
)}
</div>
);
})}
</div>
- {/* New File (+) Button */}
<button
+ type="button"
onClick={onNewDocument}
+ aria-label="New Document"
title="Create New File (Ctrl+N)"
- className="ml-1 p-1 rounded-md transition-colors flex items-center justify-center shrink-0 cursor-pointer text-white/50 hover:text-white hover:bg-white/[0.08]"
+ className="ml-1 p-1 rounded transition-colors flex items-center justify-center shrink-0 cursor-pointer text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]"
>
<Plus className="w-3.5 h-3.5" />
</button>
@@ -118,28 +136,32 @@ export const DocumentTabBar: React.FC<DocumentTabBarProps> = React.memo(({
}
return (
- <div className="h-8 flex items-center px-2 select-none z-20 shrink-0 overflow-x-auto no-scrollbar transition-colors bg-[#333336] border-b border-[#232325]">
- {/* List of Document Tabs */}
+ <div
+ data-testid="document-tab-bar"
+ data-theme-preset="vintage-manga"
+ className="h-7 flex items-center px-2 select-none z-20 shrink-0 overflow-x-auto no-scrollbar transition-colors bg-[#333336] border-b border-[#232325]"
+ >
<div className="flex items-center space-x-1 h-full">
{documents.map((doc) => {
const isActive = doc.id === activeDocumentId;
+ const isDirty = Boolean(doc.isDirty);
return (
<div
key={doc.id}
onClick={() => onSelectDocument(doc.id)}
onDoubleClick={(e) => handleStartRename(e, doc)}
- title={`${doc.name} (${doc.dimensions.width}×${doc.dimensions.height}px)`}
- className={`group relative h-full flex items-center space-x-2 px-3 text-xs cursor-pointer transition-colors ${
+ title={`${doc.name}${isDirty ? ' *' : ''} (${doc.dimensions.width}×${doc.dimensions.height}px)`}
+ className={`group relative h-full flex items-center space-x-1.5 px-2.5 text-[11px] cursor-pointer transition-colors ${
isActive
? 'bg-gradient-to-b from-[#56565a] to-[#464649] text-white font-medium border-t border-l border-r border-[#242426] shadow-[inset_0_1px_0_rgba(255,255,255,0.22)]'
: 'bg-gradient-to-b from-[#424245] to-[#363638] text-[#aaaaae] hover:text-[#d0d0d5] border border-[#272729]'
}`}
>
- {/* Document Icon */}
- <File className={`w-3.5 h-3.5 shrink-0 ${isActive ? 'text-[#38bdf8]' : 'text-[#77777d]'}`} />
+ <File
+ className={`w-3 h-3 shrink-0 ${isActive ? 'text-[#38bdf8]' : 'text-[#77777d]'}`}
+ />
- {/* Document Name / Inline Rename Input */}
{editingId === doc.id ? (
<input
type="text"
@@ -152,20 +174,32 @@ export const DocumentTabBar: React.FC<DocumentTabBarProps> = React.memo(({
}}
autoFocus
onClick={(e) => e.stopPropagation()}
- className="bg-[#242426] text-white text-xs px-1.5 py-0.5 rounded-none outline-none border border-[#38bdf8] w-28"
+ className="bg-[#242426] text-white text-[11px] px-1.5 py-0.5 rounded-none outline-none border border-[#38bdf8] w-28"
/>
) : (
- <span className="truncate max-w-[160px] tracking-wide">{doc.name}</span>
+ <span className="truncate max-w-[160px] tracking-wide">
+ {doc.name}
+ {isDirty && (
+ <span
+ data-testid={`dirty-indicator-${doc.id}`}
+ className="ml-0.5 text-amber-300 font-bold"
+ title="Unsaved changes"
+ >
+ *
+ </span>
+ )}
+ </span>
)}
- {/* Close Button */}
<button
+ type="button"
onClick={(e) => {
e.stopPropagation();
onCloseDocument(doc.id);
}}
+ aria-label={`Close ${doc.name}`}
title="Close file"
- className={`p-0.5 rounded-xs transition-colors ${
+ className={`p-0.5 rounded-xs transition-colors cursor-pointer ${
isActive
? 'text-[#aaaaae] hover:text-white hover:bg-[#343438]'
: 'text-transparent group-hover:text-[#aaaaae] hover:!text-white hover:bg-[#2c2c30]'
@@ -174,7 +208,6 @@ export const DocumentTabBar: React.FC<DocumentTabBarProps> = React.memo(({
<X className="w-3 h-3" />
</button>
- {/* Active Tab Accent Underline */}
{isActive && (
<div className="absolute bottom-0 left-0 right-0 h-[2px] bg-[#337bb5]" />
)}
@@ -183,13 +216,14 @@ export const DocumentTabBar: React.FC<DocumentTabBarProps> = React.memo(({
})}
</div>
- {/* New File (+) Button */}
<button
+ type="button"
onClick={onNewDocument}
+ aria-label="New Document"
title="Create New File (Ctrl+N)"
className="ml-1.5 p-1 rounded-[2px] transition-colors flex items-center justify-center shrink-0 cursor-pointer bg-gradient-to-b from-[#4e4e52] to-[#3a3a3d] border border-[#272729] text-[#aaaaae] hover:text-white shadow-[inset_0_1px_0_rgba(255,255,255,0.18)] active:brightness-90"
>
- <Plus className="w-3.5 h-3.5" />
+ <Plus className="w-3 h-3" />
</button>
</div>
);
diff --git a/src/components/GlobalShortcutListener.tsx b/src/components/GlobalShortcutListener.tsx
new file mode 100644
index 0000000..138eccc
--- /dev/null
+++ b/src/components/GlobalShortcutListener.tsx
@@ -0,0 +1,638 @@
+import React, { useEffect, useRef } from 'react';
+import {
+ AnimationTimeline,
+ CanvasDimensions,
+ CanvasSelection,
+ LayerItem,
+ ToolType,
+ TransformSession,
+} from '../types/editor';
+import { createDefaultAnimationTimeline } from '../utils/animationEngine';
+import { createDefaultPerspectiveRuler } from '../utils/perspectiveMath';
+import {
+ flushPendingBrushSettingsSave,
+ stepBrushSizePreset,
+} from '../utils/brushPresetManager';
+import { parseSutFile } from '../utils/sutParser';
+import {
+ deleteCustomBrush,
+ loadCustomBrushes,
+ prepareBrushSettingsForCsp,
+ saveCustomBrush,
+} from '../utils/brushStorage';
+import { TonalCorrectionType } from '../utils/tonalEngine';
+import {
+ documentStoreActions,
+ selectIsAnyModalOpen,
+ toolStoreActions,
+ uiStoreActions,
+ useToolStore,
+ useUiStore,
+ workspaceStoreActions,
+} from '../stores';
+import { TextPlacementSession } from '../hooks/drawing/useShapeAndFillTools';
+
+export interface GlobalShortcutListenerProps {
+ hasOpenDocument: boolean;
+ dimensions: CanvasDimensions;
+ layers: LayerItem[];
+ activeLayer: LayerItem | undefined;
+ activeLayerId: string;
+ selection: CanvasSelection | null;
+ transformSession: TransformSession | null;
+ textSession: TextPlacementSession | null;
+ activeAnimationTimeline: AnimationTimeline | null;
+ isSpaceDown: boolean;
+ isHostModalOpen: boolean;
+ isDrawingRef: React.MutableRefObject<boolean>;
+ isSelectionPenDrawingRef: React.MutableRefObject<boolean>;
+ isPipetteSamplingRef: React.MutableRefObject<boolean>;
+ handleUndo: () => void;
+ redo: () => void;
+ handleAddLayer: (type?: 'raster' | 'folder') => void;
+ handleTriggerOpenFile: () => void;
+ handleSave: () => void;
+ handleSaveAs: () => void;
+ duplicateLayer: (layerId: string) => void;
+ handleCopySelectedLayer: () => void;
+ handlePasteSelectedLayer: () => void;
+ handleGroupSelectedLayers: () => void;
+ handleStartTransform: () => void;
+ handleSelectAll: () => void;
+ handleDeselect: () => void;
+ handleInvertSelection: () => void;
+ handleApplyReverseGradient: () => void;
+ handleOpenTonalModal: (type: TonalCorrectionType) => void;
+ handleUpdateAnimationTimeline: (timeline: AnimationTimeline | null) => void;
+ handleAddAnimationCel: (frameIndex: number) => void;
+ toggleFlipHorizontal: () => void;
+ toggleFlipVertical: () => void;
+ handleClearSelection: () => void;
+ handleDeleteSelectedLayer: () => void;
+ handleCancelTransform: () => void;
+ handleCancelText: () => void;
+ handleApplyTransform: () => void;
+ handleProcessFile: (file: File) => void;
+ showToast: (msg: string) => void;
+}
+
+const CODE_TO_TOOL: Record<string, ToolType> = {
+ KeyB: 'brush',
+ KeyE: 'eraser',
+ KeyI: 'pipette',
+ KeyJ: 'liquify',
+ KeyM: 'select-rect',
+ KeyL: 'select-lasso',
+ KeyW: 'select-wand',
+ KeyG: 'fill',
+ KeyT: 'text',
+ KeyF: 'frame',
+ KeyO: 'balloon',
+ KeyY: 'vector-edit',
+};
+
+function isEditableTarget(target: EventTarget | null): boolean {
+ if (!(target instanceof HTMLElement)) return false;
+ const tag = target.tagName;
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
+}
+
+/**
+ * Headless listener for global hotkeys, temporary tool holds, Alt eyedropper hold,
+ * drag-and-drop file import, and beforeunload brush settings persistence.
+ * Reads tool/UI/document stores imperatively to avoid re-renders on brush/color edits.
+ */
+export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = React.memo(
+ (props) => {
+ const propsRef = useRef(props);
+ propsRef.current = props;
+
+ const previousToolBeforeAltRef = useRef<ToolType | null>(null);
+ const isAltActiveRef = useRef<boolean>(false);
+ const tempToolHoldRef = useRef<{
+ code: string;
+ prevTool: ToolType;
+ targetTool: ToolType;
+ downAt: number;
+ usedWhileHeld: boolean;
+ } | null>(null);
+
+ // Flush debounced brush settings on window close/unmount
+ useEffect(() => {
+ const handleBeforeUnload = () => flushPendingBrushSettingsSave();
+ window.addEventListener('beforeunload', handleBeforeUnload);
+ return () => {
+ flushPendingBrushSettingsSave();
+ window.removeEventListener('beforeunload', handleBeforeUnload);
+ };
+ }, []);
+
+ // Global Keyboard Shortcuts (Layout-Independent e.code + CSP Hold-and-Release Temporary Tools)
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ const p = propsRef.current;
+ const uiState = useUiStore.getState();
+ const isModalOpen = selectIsAnyModalOpen(uiState, p.isHostModalOpen) || uiState.isLoadingFile;
+ if (isModalOpen || isEditableTarget(e.target)) {
+ return;
+ }
+
+ const key = e.key.toLowerCase();
+ const code = e.code;
+
+ // Ctrl / Cmd shortcuts
+ if (e.ctrlKey || e.metaKey) {
+ if (e.altKey && !e.shiftKey && (code === 'KeyA' || key === 'a')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ if (p.activeAnimationTimeline) {
+ p.handleUpdateAnimationTimeline(null);
+ } else {
+ p.handleUpdateAnimationTimeline(createDefaultAnimationTimeline(p.layers));
+ }
+ return;
+ }
+
+ if (e.altKey && !e.shiftKey && (code === 'KeyY' || key === 'y')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ documentStoreActions.toggleSoftProof();
+ return;
+ }
+
+ if (e.altKey) return;
+
+ if (!e.shiftKey && (code === 'KeyZ' || key === 'z')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleUndo();
+ return;
+ }
+
+ if (
+ (e.shiftKey && (code === 'KeyZ' || key === 'z')) ||
+ (!e.shiftKey && (code === 'KeyY' || key === 'y'))
+ ) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.redo();
+ return;
+ }
+
+ if (e.shiftKey && (code === 'KeyY' || key === 'y')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ documentStoreActions.toggleGamutWarning();
+ return;
+ }
+
+ if (e.shiftKey && (code === 'KeyN' || key === 'n')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleAddLayer('raster');
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyN' || key === 'n')) {
+ e.preventDefault();
+ uiStoreActions.setNewCanvasModalOpen(true);
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyO' || key === 'o')) {
+ e.preventDefault();
+ p.handleTriggerOpenFile();
+ return;
+ }
+
+ if (e.shiftKey && (code === 'KeyS' || key === 's')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleSaveAs();
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyS' || key === 's')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleSave();
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyJ' || key === 'j')) {
+ if (!p.hasOpenDocument || !p.activeLayer) return;
+ e.preventDefault();
+ p.duplicateLayer(p.activeLayerId);
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyC' || key === 'c')) {
+ if (!p.hasOpenDocument) return;
+ const textSel = window.getSelection()?.toString();
+ if (!textSel || textSel.length === 0) {
+ e.preventDefault();
+ p.handleCopySelectedLayer();
+ return;
+ }
+ }
+
+ if (!e.shiftKey && (code === 'KeyV' || key === 'v')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handlePasteSelectedLayer();
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyG' || key === 'g')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleGroupSelectedLayers();
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyT' || key === 't')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleStartTransform();
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyA' || key === 'a')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleSelectAll();
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyD' || key === 'd')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleDeselect();
+ return;
+ }
+
+ if (e.shiftKey && (code === 'KeyI' || key === 'i')) {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ p.handleInvertSelection();
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyI' || key === 'i')) {
+ if (
+ !p.hasOpenDocument ||
+ !p.activeLayer ||
+ p.activeLayer.locked ||
+ p.activeLayer.type !== 'raster'
+ ) {
+ return;
+ }
+ e.preventDefault();
+ p.handleApplyReverseGradient();
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'KeyU' || key === 'u')) {
+ if (
+ !p.hasOpenDocument ||
+ !p.activeLayer ||
+ p.activeLayer.locked ||
+ p.activeLayer.type !== 'raster'
+ ) {
+ return;
+ }
+ e.preventDefault();
+ p.handleOpenTonalModal('hue-saturation');
+ return;
+ }
+
+ if (!e.shiftKey && (code === 'Comma' || key === ',' || key === '<')) {
+ e.preventDefault();
+ uiStoreActions.setSettingsModalOpen(true);
+ return;
+ }
+
+ if (e.shiftKey && (code === 'KeyR' || key === 'r')) {
+ e.preventDefault();
+ documentStoreActions.setPerspectiveRuler((prev) => {
+ if (!prev) {
+ const next = createDefaultPerspectiveRuler('2-point', p.dimensions);
+ p.showToast('2-Point Perspective Ruler added to canvas');
+ return next;
+ }
+ const next = { ...prev, enabled: !prev.enabled };
+ p.showToast(next.enabled ? 'Perspective Ruler: Shown' : 'Perspective Ruler: Hidden');
+ return next;
+ });
+ return;
+ }
+
+ if (e.shiftKey && (code === 'KeyP' || key === 'p')) {
+ e.preventDefault();
+ documentStoreActions.setPerspectiveRuler((prev) => {
+ if (!prev) return null;
+ const next = { ...prev, snapEnabled: !prev.snapEnabled };
+ p.showToast(
+ next.snapEnabled ? 'Perspective Snapping: ON' : 'Perspective Snapping: OFF'
+ );
+ return next;
+ });
+ return;
+ }
+ return;
+ }
+
+ // Alt-only shortcuts: Alt+C -> Add Animation Cel
+ if (e.altKey && !e.ctrlKey && !e.metaKey) {
+ if (!e.shiftKey && (code === 'KeyC' || key === 'c')) {
+ if (!p.hasOpenDocument || !p.activeAnimationTimeline) return;
+ e.preventDefault();
+ if (isAltActiveRef.current && previousToolBeforeAltRef.current !== null) {
+ toolStoreActions.setToolRaw(previousToolBeforeAltRef.current);
+ previousToolBeforeAltRef.current = null;
+ isAltActiveRef.current = false;
+ toolStoreActions.setQuickModifiers({ isAltActive: false });
+ }
+ p.handleAddAnimationCel(p.activeAnimationTimeline.currentFrame);
+ }
+ return;
+ }
+
+ // Tab / Shift+Tab: Toggle UI Panels (CSP Hide/Show Palettes)
+ if (code === 'Tab' && !p.textSession) {
+ e.preventDefault();
+ if (e.shiftKey) {
+ uiStoreActions.toggleLeftPanelHidden();
+ } else {
+ workspaceStoreActions.togglePalettesHidden();
+ }
+ return;
+ }
+
+ // Brush Size Stepper: [ and ]
+ if (!e.shiftKey && (code === 'BracketLeft' || code === 'BracketRight')) {
+ e.preventDefault();
+ const dir: -1 | 1 = code === 'BracketLeft' ? -1 : 1;
+ const toolState = useToolStore.getState();
+ if (toolState.tool === 'liquify') {
+ const nextSize = Math.max(
+ 4,
+ Math.min(500, Math.round(stepBrushSizePreset(toolState.liquifySettings.size, dir)))
+ );
+ toolStoreActions.updateLiquifySettings({ size: nextSize });
+ } else {
+ const nextSize = stepBrushSizePreset(toolState.brushSettings.size, dir);
+ toolStoreActions.updateBrushSettings({ size: nextSize });
+ }
+ return;
+ }
+
+ // Non-destructive View Flip shortcuts
+ if (e.shiftKey && !p.isSpaceDown) {
+ if (code === 'KeyH' || key === 'h') {
+ if (!p.hasOpenDocument || e.repeat) return;
+ e.preventDefault();
+ p.toggleFlipHorizontal();
+ return;
+ }
+ if (code === 'KeyV' || key === 'v') {
+ if (!p.hasOpenDocument || e.repeat) return;
+ e.preventDefault();
+ p.toggleFlipVertical();
+ return;
+ }
+ }
+
+ // Single-key tool & color shortcuts
+ if (!e.shiftKey) {
+ const mappedTool = CODE_TO_TOOL[code];
+ if (mappedTool) {
+ if (e.repeat) return;
+ const prev = useToolStore.getState().tool;
+ if (prev !== mappedTool) {
+ tempToolHoldRef.current = {
+ code,
+ prevTool: prev,
+ targetTool: mappedTool,
+ downAt: performance.now(),
+ usedWhileHeld: false,
+ };
+ toolStoreActions.selectTool(mappedTool);
+ }
+ return;
+ }
+
+ if (code === 'KeyX' || key === 'x') {
+ if (!e.repeat) toolStoreActions.swapColors();
+ return;
+ }
+ if (code === 'KeyD' || key === 'd') {
+ if (!e.repeat) toolStoreActions.resetDefaultColors();
+ return;
+ }
+ if (code === 'KeyC' || key === 'c') {
+ if (!e.repeat) {
+ const next = toolStoreActions.toggleTransparentColor();
+ p.showToast(next ? 'Transparent ink mode active' : 'Color ink mode active');
+ }
+ return;
+ }
+ }
+
+ if (key === 'delete' || key === 'backspace') {
+ if (!p.hasOpenDocument) return;
+ e.preventDefault();
+ if (p.selection) {
+ p.handleClearSelection();
+ } else {
+ p.handleDeleteSelectedLayer();
+ }
+ } else if (key === 'escape') {
+ if (p.transformSession?.active) {
+ e.preventDefault();
+ p.handleCancelTransform();
+ } else if (p.textSession) {
+ e.preventDefault();
+ p.handleCancelText();
+ } else if (p.selection) {
+ e.preventDefault();
+ p.handleDeselect();
+ }
+ } else if (key === 'enter') {
+ if (p.transformSession?.active) {
+ e.preventDefault();
+ p.handleApplyTransform();
+ }
+ }
+ };
+
+ const handleKeyUp = (e: KeyboardEvent) => {
+ const hold = tempToolHoldRef.current;
+ if (hold && e.code === hold.code) {
+ const heldMs = performance.now() - hold.downAt;
+ tempToolHoldRef.current = null;
+ if (
+ (heldMs >= 220 || hold.usedWhileHeld) &&
+ useToolStore.getState().tool === hold.targetTool
+ ) {
+ toolStoreActions.selectTool(hold.prevTool);
+ }
+ }
+ };
+
+ const handlePointerDownMarkUsed = () => {
+ if (tempToolHoldRef.current) {
+ tempToolHoldRef.current.usedWhileHeld = true;
+ }
+ };
+
+ const handleWindowBlur = () => {
+ tempToolHoldRef.current = null;
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ window.addEventListener('keyup', handleKeyUp);
+ window.addEventListener('pointerdown', handlePointerDownMarkUsed, true);
+ window.addEventListener('blur', handleWindowBlur);
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('keyup', handleKeyUp);
+ window.removeEventListener('pointerdown', handlePointerDownMarkUsed, true);
+ window.removeEventListener('blur', handleWindowBlur);
+ };
+ }, []);
+
+ // Alt-hold temporary pipette
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ const p = propsRef.current;
+ const uiState = useUiStore.getState();
+ const isModalOpen = selectIsAnyModalOpen(uiState, p.isHostModalOpen) || uiState.isLoadingFile;
+ if (isModalOpen || isEditableTarget(e.target)) {
+ return;
+ }
+
+ if (e.key === 'Alt') {
+ if (
+ !e.ctrlKey &&
+ !e.metaKey &&
+ !p.isDrawingRef.current &&
+ !p.isSelectionPenDrawingRef.current
+ ) {
+ e.preventDefault();
+ if (!isAltActiveRef.current && !e.repeat) {
+ isAltActiveRef.current = true;
+ toolStoreActions.setQuickModifiers({ isAltActive: true });
+ const currentTool = useToolStore.getState().tool;
+ if (currentTool !== 'pipette') {
+ previousToolBeforeAltRef.current = currentTool;
+ toolStoreActions.setToolRaw('pipette');
+ }
+ }
+ }
+ return;
+ }
+
+ if ((e.ctrlKey || e.metaKey || e.code === 'Space') && isAltActiveRef.current) {
+ if (previousToolBeforeAltRef.current !== null) {
+ toolStoreActions.setToolRaw(previousToolBeforeAltRef.current);
+ previousToolBeforeAltRef.current = null;
+ }
+ isAltActiveRef.current = false;
+ p.isPipetteSamplingRef.current = false;
+ toolStoreActions.setQuickModifiers({ isAltActive: false });
+ }
+ };
+
+ const handleKeyUp = (e: KeyboardEvent) => {
+ const p = propsRef.current;
+ if (e.key === 'Alt' || (!e.altKey && isAltActiveRef.current)) {
+ if (isAltActiveRef.current) {
+ e.preventDefault();
+ isAltActiveRef.current = false;
+ toolStoreActions.setQuickModifiers({ isAltActive: false });
+ }
+ p.isPipetteSamplingRef.current = false;
+ if (previousToolBeforeAltRef.current !== null) {
+ toolStoreActions.setToolRaw(previousToolBeforeAltRef.current);
+ previousToolBeforeAltRef.current = null;
+ }
+ }
+ };
+
+ const handleBlur = () => {
+ const p = propsRef.current;
+ isAltActiveRef.current = false;
+ p.isPipetteSamplingRef.current = false;
+ toolStoreActions.setQuickModifiers({ isAltActive: false });
+ if (previousToolBeforeAltRef.current !== null) {
+ toolStoreActions.setToolRaw(previousToolBeforeAltRef.current);
+ previousToolBeforeAltRef.current = null;
+ }
+ };
+
+ window.addEventListener('keydown', handleKeyDown);
+ window.addEventListener('keyup', handleKeyUp);
+ window.addEventListener('blur', handleBlur);
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown);
+ window.removeEventListener('keyup', handleKeyUp);
+ window.removeEventListener('blur', handleBlur);
+ };
+ }, []);
+
+ // Drag and drop onto application window
+ useEffect(() => {
+ const handleDragOver = (e: DragEvent) => {
+ e.preventDefault();
+ };
+
+ const handleDrop = async (e: DragEvent) => {
+ e.preventDefault();
+ const p = propsRef.current;
+ if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
+ const file = e.dataTransfer.files[0];
+ if (file.name.toLowerCase().endsWith('.sut')) {
+ try {
+ uiStoreActions.setLoading(true, `Importing CSP Brush: ${file.name}...`);
+ const buffer = await file.arrayBuffer();
+ const parsedBrush = await parseSutFile(buffer, file.name);
+ const existing = (await loadCustomBrushes()).filter(
+ (b) =>
+ b.name.toLowerCase() === parsedBrush.name.toLowerCase() ||
+ b.id === parsedBrush.id
+ );
+ for (const old of existing) {
+ await deleteCustomBrush(old.id).catch(() => {});
+ }
+ await saveCustomBrush(parsedBrush);
+ toolStoreActions.setToolRaw('brush');
+ const fullSettings = await prepareBrushSettingsForCsp(parsedBrush);
+ toolStoreActions.updateBrushSettings(fullSettings);
+ p.showToast(`Imported CSP brush "${parsedBrush.name}" successfully!`);
+ } catch (err: unknown) {
+ console.error('Failed to import CSP brush:', err);
+ const msg = err instanceof Error ? err.message : 'Failed to import .sut brush.';
+ p.showToast(msg);
+ } finally {
+ uiStoreActions.setLoading(false, '');
+ }
+ return;
+ }
+ p.handleProcessFile(file);
+ }
+ };
+
+ window.addEventListener('dragover', handleDragOver);
+ window.addEventListener('drop', handleDrop);
+ return () => {
+ window.removeEventListener('dragover', handleDragOver);
+ window.removeEventListener('drop', handleDrop);
+ };
+ }, []);
+
+ return null;
+ }
+);
+
+GlobalShortcutListener.displayName = 'GlobalShortcutListener';
diff --git a/src/components/Header.tsx b/src/components/Header.tsx
index 33b699f..19e70a0 100644
--- a/src/components/Header.tsx
+++ b/src/components/Header.tsx
@@ -1,10 +1,7 @@
-import React, { useState } from 'react';
+import React, { useMemo } from 'react';
import {
- Undo2,
- Redo2,
Minus,
Plus,
- X,
Users,
Settings,
RotateCcw,
@@ -23,8 +20,9 @@ import { formatZoomPercent } from '../hooks/useCanvasNavigation';
import { formatRotationDegrees } from '../utils/canvasUtils';
import { MenuBar } from './MenuBar';
import { WindowControls } from './WindowControls';
+import { CommandBar, WorkspaceCommandHandlers } from './CommandBar';
-interface HeaderProps {
+export interface HeaderProps {
canUndo: boolean;
canRedo: boolean;
onUndo: () => void;
@@ -50,6 +48,7 @@ interface HeaderProps {
onCloseDocument?: (id: string) => void;
onNewDocument?: () => void;
onRenameDocument?: (id: string, newName: string) => void;
+ commandHandlers?: WorkspaceCommandHandlers;
isCollabConnected?: boolean;
collabPeerCount?: number;
onOpenCollabModal?: () => void;
@@ -79,43 +78,59 @@ export const Header: React.FC<HeaderProps> = React.memo(({
colorMode = 'color',
menuSections,
hasOpenDocument = true,
- documents = [],
- activeDocumentId = null,
- onSelectDocument,
- onCloseDocument,
- onNewDocument,
- onRenameDocument,
+ commandHandlers,
isCollabConnected = false,
collabPeerCount = 1,
onOpenCollabModal,
onOpenSettings,
- themePreset,
+ themePreset = 'modern',
softProofSettings,
appView = 'workspace',
onSelectAppView,
}) => {
- const [editingId, setEditingId] = useState<string | null>(null);
- const [editingName, setEditingName] = useState<string>('');
-
- const handleStartRename = (e: React.MouseEvent, doc: DocumentTab) => {
- e.stopPropagation();
- setEditingId(doc.id);
- setEditingName(doc.name);
- };
-
- const handleFinishRename = (id: string) => {
- if (editingName.trim() && onRenameDocument) {
- onRenameDocument(id, editingName.trim());
- }
- setEditingId(null);
- };
-
const isRotated = Math.abs(rotation % 360) > 0.05;
+ const isVintage = themePreset === 'vintage-manga';
+
+ const resolvedHandlers = useMemo<WorkspaceCommandHandlers>(
+ () =>
+ commandHandlers ?? {
+ canUndo,
+ canRedo,
+ onUndo,
+ onRedo,
+ onFlipHorizontal: onToggleFlipHorizontal,
+ onFlipVertical: onToggleFlipVertical,
+ flipX,
+ flipY,
+ onResetZoom,
+ onResetRotation,
+ hasOpenDocument,
+ },
+ [
+ commandHandlers,
+ canUndo,
+ canRedo,
+ onUndo,
+ onRedo,
+ onToggleFlipHorizontal,
+ onToggleFlipVertical,
+ flipX,
+ flipY,
+ onResetZoom,
+ onResetRotation,
+ hasOpenDocument,
+ ]
+ );
return (
<header
data-tauri-drag-region
- className="h-[36px] px-2 flex items-center justify-between gap-2 bg-[#202020] text-[#e5e5e5] select-none z-40 shrink-0"
+ data-theme-preset={themePreset}
+ className={`h-[36px] px-2 flex items-center justify-between gap-2 select-none z-40 shrink-0 ${
+ isVintage
+ ? 'bg-gradient-to-b from-[#49494d] to-[#363638] border-b border-[#232325] text-[#f0f0f4]'
+ : 'bg-[#202020] text-[#e5e5e5]'
+ }`}
>
{/* Left: App Icon (Home Toggle) + Menu Bar */}
<div
@@ -142,84 +157,14 @@ export const Header: React.FC<HeaderProps> = React.memo(({
<MenuBar sections={menuSections} />
</div>
- {/* Center: Consolidated Compact Document Tabs */}
- <div
- className="flex-1 min-w-0 flex items-center gap-1 overflow-x-auto no-scrollbar px-1"
- style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
- >
- {documents.map((doc) => {
- const isActive = doc.id === activeDocumentId && appView === 'workspace';
- return (
- <div
- key={doc.id}
- onClick={() => onSelectDocument?.(doc.id)}
- onDoubleClick={(e) => handleStartRename(e, doc)}
- title={`${doc.name} (${doc.dimensions.width}×${doc.dimensions.height}px)`}
- className={`group relative h-6 flex items-center gap-1.5 pl-2.5 pr-1.5 rounded text-[11px] cursor-pointer shrink-0 transition-colors ${
- isActive
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- {isActive && (
- <span
- className="w-1.5 h-1.5 rounded-full shrink-0"
- style={{ backgroundColor: 'var(--accent)' }}
- />
- )}
-
- {editingId === doc.id ? (
- <input
- type="text"
- value={editingName}
- onChange={(e) => setEditingName(e.target.value)}
- onBlur={() => handleFinishRename(doc.id)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') handleFinishRename(doc.id);
- if (e.key === 'Escape') setEditingId(null);
- }}
- autoFocus
- onClick={(e) => e.stopPropagation()}
- className="bg-[#161616] text-[#e5e5e5] text-[11px] px-1 py-0.5 rounded w-24"
- />
- ) : (
- <span className="truncate max-w-[130px]">{doc.name}</span>
- )}
-
- {onCloseDocument && (
- <button
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- onCloseDocument(doc.id);
- }}
- title="Close tab"
- className={`w-4 h-4 rounded flex items-center justify-center transition-colors cursor-pointer ${
- isActive
- ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#161616]/50'
- : 'opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- <X className="w-2.5 h-2.5" />
- </button>
- )}
- </div>
- );
- })}
-
- {onNewDocument && (
- <button
- type="button"
- onClick={onNewDocument}
- title="New Canvas (Ctrl+N)"
- className="w-6 h-6 rounded flex items-center justify-center shrink-0 text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
- >
- <Plus className="w-3.5 h-3.5" />
- </button>
+ {/* Center: Customizable CSP Command Bar + Workspace Preset Selector */}
+ <div className="flex-1 min-w-0 flex items-center justify-center px-1">
+ {appView === 'workspace' && (
+ <CommandBar handlers={resolvedHandlers} themePreset={themePreset} />
)}
</div>
- {/* Right: Mode Badges, Undo/Redo, Zoom Level, Settings & Window Controls */}
+ {/* Right: Mode Badges, Zoom Level, View Flip, Collab, Settings & Window Controls */}
<div
className="flex items-center gap-1.5 shrink-0"
style={{ WebkitAppRegion: 'no-drag' } as React.CSSProperties}
@@ -262,41 +207,13 @@ export const Header: React.FC<HeaderProps> = React.memo(({
</button>
)}
- {/* Undo / Redo */}
- <div className="flex items-center gap-0.5">
- <button
- type="button"
- onClick={onUndo}
- disabled={!canUndo}
- title="Undo (Ctrl+Z)"
- className={`w-6 h-6 rounded flex items-center justify-center transition-colors ${
- canUndo
- ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
- : 'text-[#8a8a8a]/25 cursor-not-allowed'
- }`}
- >
- <Undo2 className="w-3.5 h-3.5" />
- </button>
- <button
- type="button"
- onClick={onRedo}
- disabled={!canRedo}
- title="Redo (Ctrl+Y)"
- className={`w-6 h-6 rounded flex items-center justify-center transition-colors ${
- canRedo
- ? 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer'
- : 'text-[#8a8a8a]/25 cursor-not-allowed'
- }`}
- >
- <Redo2 className="w-3.5 h-3.5" />
- </button>
- </div>
-
{/* Compact Zoom Control */}
<div
- className={`h-6 flex items-center bg-[#161616] rounded px-0.5 ${
- !hasOpenDocument ? 'opacity-40 pointer-events-none' : ''
- }`}
+ className={`h-6 flex items-center rounded px-0.5 ${
+ isVintage
+ ? 'bg-[#2b2b2e] border border-[#202022]'
+ : 'bg-[#161616]'
+ } ${!hasOpenDocument ? 'opacity-40 pointer-events-none' : ''}`}
>
<button
type="button"
@@ -327,9 +244,9 @@ export const Header: React.FC<HeaderProps> = React.memo(({
{/* Non-Destructive View Flip Controls (CSP-style Mirror View) */}
{(onToggleFlipHorizontal || onToggleFlipVertical) && (
<div
- className={`h-6 flex items-center bg-[#161616] rounded px-0.5 gap-0.5 ${
- !hasOpenDocument ? 'opacity-40 pointer-events-none' : ''
- }`}
+ className={`h-6 flex items-center rounded px-0.5 gap-0.5 ${
+ isVintage ? 'bg-[#2b2b2e] border border-[#202022]' : 'bg-[#161616]'
+ } ${!hasOpenDocument ? 'opacity-40 pointer-events-none' : ''}`}
>
{onToggleFlipHorizontal && (
<button
diff --git a/src/components/LeftPanel.tsx b/src/components/LeftPanel.tsx
index 2a78928..519a168 100644
--- a/src/components/LeftPanel.tsx
+++ b/src/components/LeftPanel.tsx
@@ -1,2066 +1,140 @@
import React, { useState, useRef, useEffect, useCallback } from 'react';
-import {
- Paintbrush,
- Pencil,
- Eraser,
- PanelLeftClose,
- PanelLeftOpen,
- ArrowLeftRight,
- ChevronDown,
- ChevronRight,
- Plus,
- Trash2,
- Loader2,
- FolderDown,
- Palette,
- Square,
- BoxSelect,
- Lasso,
- PaintBucket,
- Type,
- Frame,
- Scaling,
- Pipette,
- Maximize2,
- Minimize2,
- RotateCcw,
- Wand2,
- PenTool,
- Feather,
- MessageSquare,
- Spline,
- Sparkles,
-} from 'lucide-react';
-import {
- ToolType,
- BrushSettings,
- BrushPresetId,
- CspBrush,
- BrushDynamics,
- DEFAULT_BRUSH_DYNAMICS,
- FillSettings,
- TextSettings,
- FrameSettings,
- LiquifySettings,
- LiquifyMode,
- WandSettings,
- BalloonSettings,
- VectorEditSettings,
- CspAngleDynamicsMode,
- CspBlendTipsMode,
- CspPaperTextureMode,
- CspTipFlipMode,
- CspTaperSettings,
- CspSpraySettings,
-} from '../types/editor';
-import { LiquifyIcon } from './LiquifyIcon';
-import { parseSutFile } from '../utils/sutParser';
+import { CspBrush } from '../types/editor';
import {
loadCustomBrushes,
getCachedCustomBrushes,
- saveCustomBrush,
- saveCustomBrushDebounced,
- deleteCustomBrush,
preloadTipImage,
- prepareBrushSettingsForCsp,
CUSTOM_BRUSHES_CHANGED_EVENT,
} from '../utils/brushStorage';
-import { resolveBrushTipImage } from '../utils/brushOutline';
-import { BUILTIN_BRUSHES, BrushCategory } from '../utils/presetBrushes';
-import {
- getEffectiveBrushSettings,
- getSavedBrushSettings,
- resetBrushSettingsToDefault,
- saveActivePresetId,
- ERASER_PRESET_ID,
-} from '../utils/brushPresetManager';
-import { renderBrushStrokePreview } from '../utils/brushPreview';
-import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/CspBrushEngine';
+import { useToolStore, useUiStore, uiStoreActions } from '../stores';
+import { ToolStrip } from './ToolStrip';
+import { SubToolList } from './SubToolList';
+import { ToolPropertyInspector } from './ToolPropertyInspector';
-interface LeftPanelProps {
- currentTool: ToolType;
- onSelectTool: (tool: ToolType) => void;
- brushSettings: BrushSettings;
- onUpdateBrushSettings: (newSettings: Partial<BrushSettings>) => void;
- primaryColor: string;
- secondaryColor: string;
- onPrimaryColorChange?: (color: string) => void;
- onSecondaryColorChange?: (color: string) => void;
- onSwapColors: () => void;
- isTransparentColor?: boolean;
- onToggleTransparentColor?: () => void;
- recentColors?: string[];
- width: number;
- onWidthChange: (newWidth: number) => void;
- isHidden: boolean;
- onToggleHidden: () => void;
- fillSettings?: FillSettings;
- onUpdateFillSettings?: (newSettings: Partial<FillSettings>) => void;
- textSettings?: TextSettings;
- onUpdateTextSettings?: (newSettings: Partial<TextSettings>) => void;
- frameSettings?: FrameSettings;
- onUpdateFrameSettings?: (newSettings: Partial<FrameSettings>) => void;
- hasSelection?: boolean;
+export interface LeftPanelProps {
onDeselect?: () => void;
onTransformSelection?: () => void;
- onFillScreentone?: () => void;
- liquifySettings?: LiquifySettings;
- onUpdateLiquifySettings?: (newSettings: Partial<LiquifySettings>) => void;
- balloonSettings?: BalloonSettings;
- onUpdateBalloonSettings?: (newSettings: Partial<BalloonSettings>) => void;
- vectorEditSettings?: VectorEditSettings;
- onUpdateVectorEditSettings?: (newSettings: Partial<VectorEditSettings>) => void;
- onOpenMangaEffects?: () => void;
- wandSettings?: WandSettings;
- onUpdateWandSettings?: (newSettings: Partial<WandSettings>) => void;
onExpandSelection?: (pixels: number) => void;
onContractSelection?: (pixels: number) => void;
onFeatherSelection?: (radius: number) => void;
onInvertSelection?: () => void;
+ onToggleTransparentColor?: () => void;
}
-interface CompactSliderProps {
- label: string;
- valueLabel: string;
- min: number;
- max: number;
- step?: number;
- value: number;
- onChange: (val: number) => void;
-}
-
-const CompactSlider: React.FC<CompactSliderProps> = ({
- label,
- valueLabel,
- min,
- max,
- step = 1,
- value,
- onChange,
-}) => (
- <div className="space-y-1">
- <div className="flex items-center justify-between text-[11px]">
- <span className="text-[#8a8a8a] truncate">{label}</span>
- <span className="font-mono text-[10px] text-[#e5e5e5] ml-1 shrink-0">{valueLabel}</span>
- </div>
- <input
- type="range"
- min={min}
- max={max}
- step={step}
- value={value}
- onChange={(e) => onChange(Number(e.target.value))}
- className="w-full"
- />
- </div>
-);
-
-const LIQUIFY_MODES: Array<{ id: LiquifyMode; label: string }> = [
- { id: 'push', label: 'Push' },
- { id: 'expand', label: 'Expand' },
- { id: 'pinch', label: 'Pinch' },
- { id: 'push-left', label: 'Push Left' },
- { id: 'push-right', label: 'Push Right' },
- { id: 'twirl-cw', label: 'Twirl CW' },
- { id: 'twirl-ccw', label: 'Twirl CCW' },
- { id: 'reconstruct', label: 'Reconstruct' },
-];
-
-type InspectorAccordionId = 'ink' | 'tip' | 'stroke' | 'mixing' | 'texture' | 'dynamics';
-
-const DEFAULT_TAPER: CspTaperSettings = {
- useIn: false,
- inLength: 24,
- inRatio: 0.9,
- useOut: false,
- outLength: 32,
- outRatio: 0.9,
- startingSharpness: 0.85,
- endingSharpness: 0.85,
- affectSize: true,
-};
-
-const DEFAULT_SPRAY: CspSpraySettings = {
- enabled: false,
- size: 4,
- density: 12,
- bias: 0.5,
-};
-
-export const LeftPanel: React.FC<LeftPanelProps> = React.memo(({
- currentTool,
- onSelectTool,
- brushSettings,
- onUpdateBrushSettings,
- primaryColor,
- secondaryColor,
- onSwapColors,
- isTransparentColor = false,
- onToggleTransparentColor,
- width,
- onWidthChange,
- isHidden,
- onToggleHidden,
- fillSettings,
- onUpdateFillSettings,
- textSettings,
- onUpdateTextSettings,
- frameSettings,
- onUpdateFrameSettings,
- onDeselect,
- onTransformSelection,
- liquifySettings,
- onUpdateLiquifySettings,
- balloonSettings,
- onUpdateBalloonSettings,
- vectorEditSettings,
- onUpdateVectorEditSettings,
- onOpenMangaEffects,
- wandSettings,
- onUpdateWandSettings,
- onExpandSelection,
- onContractSelection,
- onFeatherSelection,
- onInvertSelection,
-}) => {
- const [openAccordion, setOpenAccordion] = useState<InspectorAccordionId | null>(null);
- const [customBrushes, setCustomBrushes] = useState<CspBrush[]>(() => getCachedCustomBrushes());
- const [isImportingSut, setIsImportingSut] = useState(false);
- const [isDraggingFileOver, setIsDraggingFileOver] = useState(false);
- const [selectedCategory, setSelectedCategory] = useState<'all' | BrushCategory | 'csp'>('all');
- const sutInputRef = useRef<HTMLInputElement>(null);
- const previewCanvasRef = useRef<HTMLCanvasElement>(null);
-
- const [isDraggingWidth, setIsDraggingWidth] = useState(false);
- const dragStartXRef = useRef(0);
- const dragStartWidthRef = useRef(width);
-
- const syncCustomBrushes = useCallback(() => {
- loadCustomBrushes().then((brushes) => {
- setCustomBrushes(brushes);
- for (const b of brushes) {
- if (b.tipDataUrl) preloadTipImage(b.tipDataUrl).catch(() => {});
- if (b.secondaryTipDataUrl) preloadTipImage(b.secondaryTipDataUrl).catch(() => {});
- if (b.subTips) {
- for (const st of b.subTips) {
- if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
+export const LeftPanel: React.FC<LeftPanelProps> = React.memo(
+ ({
+ onDeselect,
+ onTransformSelection,
+ onExpandSelection,
+ onContractSelection,
+ onFeatherSelection,
+ onInvertSelection,
+ onToggleTransparentColor,
+ }) => {
+ const currentTool = useToolStore((s) => s.tool);
+ const width = useUiStore((s) => s.leftPanelWidth);
+ const isHidden = useUiStore((s) => s.isLeftPanelHidden);
+
+ const [customBrushes, setCustomBrushes] = useState<CspBrush[]>(() =>
+ getCachedCustomBrushes()
+ );
+ const [isDraggingWidth, setIsDraggingWidth] = useState(false);
+ const dragStartXRef = useRef(0);
+ const dragStartWidthRef = useRef(width);
+
+ const syncCustomBrushes = useCallback(() => {
+ loadCustomBrushes().then((brushes) => {
+ setCustomBrushes(brushes);
+ for (const b of brushes) {
+ if (b.tipDataUrl) preloadTipImage(b.tipDataUrl).catch(() => {});
+ if (b.secondaryTipDataUrl) preloadTipImage(b.secondaryTipDataUrl).catch(() => {});
+ if (b.subTips) {
+ for (const st of b.subTips) {
+ if (st.dataUrl) preloadTipImage(st.dataUrl).catch(() => {});
+ }
}
+ if (b.paperTexture) preloadTipImage(b.paperTexture).catch(() => {});
}
- if (b.paperTexture) preloadTipImage(b.paperTexture).catch(() => {});
- }
- });
- }, []);
-
- useEffect(() => {
- syncCustomBrushes();
- const handleChanged = () => {
- setCustomBrushes([...getCachedCustomBrushes()]);
- };
- window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
- return () => window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
- }, [syncCustomBrushes]);
-
- useEffect(() => {
- if (!isDraggingWidth) return;
- const handlePointerMove = (e: PointerEvent) => {
- const delta = e.clientX - dragStartXRef.current;
- const newWidth = Math.max(128, Math.min(300, Math.round(dragStartWidthRef.current + delta)));
- onWidthChange(newWidth);
- };
- const handlePointerUp = () => setIsDraggingWidth(false);
- window.addEventListener('pointermove', handlePointerMove);
- window.addEventListener('pointerup', handlePointerUp);
- return () => {
- window.removeEventListener('pointermove', handlePointerMove);
- window.removeEventListener('pointerup', handlePointerUp);
- };
- }, [isDraggingWidth, onWidthChange]);
+ });
+ }, []);
- const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
-
- // Coalesce live S-curve stroke preview redraws to a single animation frame
- useEffect(() => {
- if (isHidden || !isBrushOrEraser) return;
- const canvas = previewCanvasRef.current;
- if (!canvas) return;
- const cssWidth = Math.max(96, width - 16);
- const cssHeight = 32;
- const rafId = requestAnimationFrame(() => {
- const resolvedTip = resolveBrushTipImage(brushSettings);
- renderBrushStrokePreview(
- canvas,
- cssWidth,
- cssHeight,
- {
- preset: brushSettings.preset,
- size: brushSettings.size,
- flow: brushSettings.flow,
- opacity: brushSettings.opacity,
- grain: brushSettings.grain,
- hardness: brushSettings.hardness,
- spacing: brushSettings.spacing,
- minSizeFactor: brushSettings.minSizeFactor,
- usePressure: brushSettings.usePressure,
- color: currentTool === 'eraser' ? '#e5e5e5' : '#ececec',
- backgroundColor: '#161616',
- tool: currentTool === 'eraser' ? 'eraser' : 'brush',
- customTipImage: resolvedTip,
- customTipAngle: brushSettings.customTipAngle,
- thickness: brushSettings.thickness,
- thicknessVertical: brushSettings.thicknessVertical,
- flipH: brushSettings.flipH,
- flipV: brushSettings.flipV,
- blendTipsMode: brushSettings.blendTipsMode,
- adjustDensityByGap: brushSettings.adjustDensityByGap,
- antiAlias: brushSettings.antiAlias,
- pressureCurve: brushSettings.pressureCurve,
- spray: brushSettings.spray,
- colorMixing: brushSettings.colorMixing,
- amountOfPaint: brushSettings.amountOfPaint,
- densityOfPaint: brushSettings.densityOfPaint,
- colorStretch: brushSettings.colorStretch,
- wetEdge: brushSettings.wetEdge,
- },
- true
- );
- });
- return () => cancelAnimationFrame(rafId);
- }, [isHidden, isBrushOrEraser, width, currentTool, brushSettings]);
-
- const activePreset: BrushPresetId = brushSettings.preset || 'pencil-2b';
- const activeBuiltinBrush = BUILTIN_BRUSHES.find((b) => b.id === activePreset);
- const isCustomBrushActive =
- currentTool === 'brush' &&
- (activePreset.startsWith('csp-') || (Boolean(brushSettings.customTipDataUrl) && !activeBuiltinBrush));
- const activeCustomBrush = isCustomBrushActive
- ? customBrushes.find((b) => b.id === activePreset)
- : null;
-
- const handleUpdateBrushSettings = (newSettings: Partial<BrushSettings>) => {
- onUpdateBrushSettings(newSettings);
- if (isCustomBrushActive && activeCustomBrush) {
- const updatedBrush: CspBrush = {
- ...activeCustomBrush,
- size: newSettings.size ?? activeCustomBrush.size,
- opacity: newSettings.opacity ?? activeCustomBrush.opacity,
- flow: newSettings.flow ?? activeCustomBrush.flow,
- brushDensity: newSettings.brushDensity ?? newSettings.flow ?? activeCustomBrush.brushDensity,
- adjustDensityByGap: newSettings.adjustDensityByGap ?? activeCustomBrush.adjustDensityByGap,
- blendTipsMode: newSettings.blendTipsMode ?? activeCustomBrush.blendTipsMode,
- spacing: newSettings.spacing ?? activeCustomBrush.spacing,
- hardness: newSettings.hardness ?? activeCustomBrush.hardness,
- thickness: newSettings.thickness ?? activeCustomBrush.thickness,
- thicknessVertical: newSettings.thicknessVertical ?? activeCustomBrush.thicknessVertical,
- antiAlias: newSettings.antiAlias ?? activeCustomBrush.antiAlias,
- stabilization: newSettings.stabilization ?? activeCustomBrush.stabilization,
- postCorrection: newSettings.postCorrection ?? activeCustomBrush.postCorrection,
- sharpCorners: newSettings.sharpCorners ?? activeCustomBrush.sharpCorners,
- angle: newSettings.customTipAngle ?? activeCustomBrush.angle,
- angleDynamics: newSettings.customTipAngleDynamics ?? activeCustomBrush.angleDynamics,
- flipH: newSettings.flipH ?? activeCustomBrush.flipH,
- flipV: newSettings.flipV ?? activeCustomBrush.flipV,
- isRibbon: newSettings.isRibbon ?? activeCustomBrush.isRibbon,
- usePressure: newSettings.usePressure ?? activeCustomBrush.usePressure,
- useTilt: newSettings.useTilt ?? activeCustomBrush.useTilt,
- useVelocity: newSettings.useVelocity ?? activeCustomBrush.useVelocity,
- pressureCurve: newSettings.pressureCurve ?? activeCustomBrush.pressureCurve,
- taper: newSettings.taper ?? activeCustomBrush.taper,
- spray: newSettings.spray ?? activeCustomBrush.spray,
- colorMixing: newSettings.colorMixing ?? activeCustomBrush.colorMixing,
- mixingMode: newSettings.mixingMode ?? activeCustomBrush.mixingMode,
- amountOfPaint: newSettings.amountOfPaint ?? activeCustomBrush.amountOfPaint,
- densityOfPaint: newSettings.densityOfPaint ?? activeCustomBrush.densityOfPaint,
- colorStretch: newSettings.colorStretch ?? activeCustomBrush.colorStretch,
- wetEdge: newSettings.wetEdge ?? activeCustomBrush.wetEdge,
- wetEdgeRadius: newSettings.wetEdgeRadius ?? activeCustomBrush.wetEdgeRadius,
- textureDensity: newSettings.grain ?? activeCustomBrush.textureDensity,
- paperTextureMode: newSettings.paperTextureMode ?? activeCustomBrush.paperTextureMode,
- paperTextureScale: newSettings.paperTextureScale ?? activeCustomBrush.paperTextureScale,
- paperTextureInverted: newSettings.paperTextureInverted ?? activeCustomBrush.paperTextureInverted,
- dynamics: newSettings.dynamics ?? activeCustomBrush.dynamics,
+ useEffect(() => {
+ syncCustomBrushes();
+ const handleChanged = () => {
+ setCustomBrushes([...getCachedCustomBrushes()]);
};
- setCustomBrushes((prev) => prev.map((b) => (b.id === updatedBrush.id ? updatedBrush : b)));
- saveCustomBrushDebounced(updatedBrush);
- }
- };
-
- const handleUpdateDynamics = (patch: Partial<BrushDynamics>) => {
- const cur = brushSettings.dynamics || DEFAULT_BRUSH_DYNAMICS;
- handleUpdateBrushSettings({ dynamics: { ...cur, ...patch } });
- };
-
- const handleUpdateTaper = (patch: Partial<CspTaperSettings>) => {
- const cur = brushSettings.taper || DEFAULT_TAPER;
- handleUpdateBrushSettings({ taper: { ...cur, ...patch } });
- };
-
- const handleUpdateSpray = (patch: Partial<CspSpraySettings>) => {
- const cur = brushSettings.spray || DEFAULT_SPRAY;
- handleUpdateBrushSettings({ spray: { ...cur, ...patch } });
- };
-
- const handleSelectBrushPreset = (presetId: BrushPresetId) => {
- onSelectTool('brush');
- saveActivePresetId(presetId);
- const effective = getEffectiveBrushSettings(presetId, customBrushes);
- onUpdateBrushSettings({
- customTipDataUrl: undefined,
- customTipImage: undefined,
- customTipAngle: 0,
- customTipAngleDynamics: 'none',
- flipH: 'none',
- flipV: 'none',
- isRibbon: false,
- colorMixing: false,
- wetEdge: 0,
- grain: 0,
- spray: undefined,
- taper: undefined,
- ...effective,
- preset: presetId,
- });
- };
-
- const handleSelectCustomBrush = async (brush: CspBrush) => {
- onSelectTool('brush');
- saveActivePresetId(brush.id);
- const prepared = await prepareBrushSettingsForCsp(brush);
- const saved = getSavedBrushSettings(brush.id);
- onUpdateBrushSettings({
- ...prepared,
- ...saved,
- preset: brush.id,
- });
- };
-
- const handleImportSut = async (file: File) => {
- setIsImportingSut(true);
- try {
- const buffer = await file.arrayBuffer();
- const parsedBrush = await parseSutFile(buffer, file.name);
- const existing = customBrushes.filter(
- (b) => b.name.toLowerCase() === parsedBrush.name.toLowerCase() || b.id === parsedBrush.id
- );
- for (const old of existing) {
- await deleteCustomBrush(old.id).catch(() => {});
- }
- await saveCustomBrush(parsedBrush);
- setCustomBrushes((prev) => [
- parsedBrush,
- ...prev.filter(
- (b) => b.name.toLowerCase() !== parsedBrush.name.toLowerCase() && b.id !== parsedBrush.id
- ),
- ]);
- await handleSelectCustomBrush(parsedBrush);
- } catch (err: any) {
- alert(err.message || 'Failed to import Clip Studio Paint brush file.');
- } finally {
- setIsImportingSut(false);
- }
- };
-
- const handleDeleteCustomBrush = async (e: React.MouseEvent, brushId: string) => {
- e.stopPropagation();
- if (window.confirm('Delete this imported brush?')) {
- await deleteCustomBrush(brushId);
- setCustomBrushes((prev) => prev.filter((b) => b.id !== brushId));
- if (brushSettings.preset === brushId) {
- handleSelectBrushPreset('pencil-2b');
- }
- }
- };
-
- const toggleAccordion = (id: InspectorAccordionId) => {
- setOpenAccordion((prev) => (prev === id ? null : id));
- };
-
- const toolItems: Array<{
- id: ToolType;
- label: string;
- icon: React.ReactNode;
- dividerAfter?: boolean;
- onClick?: () => void;
- }> = [
- {
- id: 'brush',
- label: 'Brush (B)',
- icon: <Paintbrush className="w-3.5 h-3.5" />,
- onClick: () => {
- onSelectTool('brush');
- if (isHidden) onToggleHidden();
- },
- },
- { id: 'eraser', label: 'Eraser (E)', icon: <Eraser className="w-3.5 h-3.5" /> },
- { id: 'pipette', label: 'Eyedropper (I)', icon: <Pipette className="w-3.5 h-3.5" /> },
- {
- id: 'liquify',
- label: 'Liquify (J)',
- icon: <LiquifyIcon className="w-3.5 h-3.5" />,
- dividerAfter: true,
- },
- {
- id: 'transform',
- label: 'Transform (Ctrl+T)',
- icon: <Scaling className="w-3.5 h-3.5" />,
- onClick: () => {
- onSelectTool('transform');
- onTransformSelection?.();
- },
- },
- { id: 'select-rect', label: 'Marquee (M)', icon: <BoxSelect className="w-3.5 h-3.5" /> },
- { id: 'select-lasso', label: 'Lasso (L)', icon: <Lasso className="w-3.5 h-3.5" /> },
- { id: 'select-wand', label: 'Magic Wand (W)', icon: <Wand2 className="w-3.5 h-3.5" /> },
- {
- id: 'select-pen',
- label: 'Selection Pen',
- icon: <PenTool className="w-3.5 h-3.5" />,
- dividerAfter: true,
- },
- { id: 'fill', label: 'Fill (G)', icon: <PaintBucket className="w-3.5 h-3.5" /> },
- { id: 'text', label: 'Text (T)', icon: <Type className="w-3.5 h-3.5" /> },
- { id: 'frame', label: 'Frame Border (F)', icon: <Frame className="w-3.5 h-3.5" /> },
- { id: 'balloon', label: 'Speech Balloon', icon: <MessageSquare className="w-3.5 h-3.5" /> },
- { id: 'vector-edit', label: 'Correct Line', icon: <Spline className="w-3.5 h-3.5" /> },
- ];
-
- const renderContextualToolPanel = () => {
- if (currentTool === 'fill') {
- const method = fillSettings?.method ?? 'refer-all';
- return (
- <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
- <div className="text-[11px] font-medium text-[#e5e5e5]">Fill</div>
- <div className="space-y-1">
- {(
- [
- { id: 'refer-all', label: 'All Visible' },
- { id: 'refer-active', label: 'Active Layer' },
- { id: 'refer-reference', label: 'Reference Layer' },
- { id: 'lasso', label: 'Lasso Fill' },
- ] as const
- ).map((m) => (
- <button
- key={m.id}
- type="button"
- onClick={() => onUpdateFillSettings?.({ method: m.id })}
- className={`w-full px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${
- method === m.id
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- {m.label}
- </button>
- ))}
- </div>
- {method !== 'lasso' && (
- <>
- <CompactSlider
- label="Tolerance"
- valueLabel={`${fillSettings?.tolerance ?? 32}`}
- min={0}
- max={100}
- value={fillSettings?.tolerance ?? 32}
- onChange={(v) => onUpdateFillSettings?.({ tolerance: v })}
- />
- <CompactSlider
- label="Close Gap"
- valueLabel={`${fillSettings?.closeGap ?? 0}px`}
- min={0}
- max={20}
- value={fillSettings?.closeGap ?? 0}
- onChange={(v) => onUpdateFillSettings?.({ closeGap: v })}
- />
- <CompactSlider
- label="Area Scaling"
- valueLabel={`${(fillSettings?.areaScale ?? 0) > 0 ? '+' : ''}${fillSettings?.areaScale ?? 0}px`}
- min={-20}
- max={20}
- value={fillSettings?.areaScale ?? 0}
- onChange={(v) => onUpdateFillSettings?.({ areaScale: v })}
- />
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Anti-Alias</span>
- <input
- type="checkbox"
- checked={fillSettings?.antiAlias ?? true}
- onChange={(e) => onUpdateFillSettings?.({ antiAlias: e.target.checked })}
- />
- </label>
- </>
- )}
- </div>
- );
- }
-
- if (currentTool === 'liquify') {
- const activeMode = liquifySettings?.mode ?? 'push';
- return (
- <div className="p-2 space-y-3 overflow-y-auto flex-1">
- <div className="px-0.5 text-[11px] font-medium text-[#e5e5e5]">Liquify</div>
- <div className="space-y-0.5">
- {LIQUIFY_MODES.map((sub) => (
- <button
- key={sub.id}
- type="button"
- onClick={() => onUpdateLiquifySettings?.({ mode: sub.id })}
- className={`w-full px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${
- activeMode === sub.id
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- {sub.label}
- </button>
- ))}
- </div>
- <CompactSlider
- label="Size"
- valueLabel={`${liquifySettings?.size ?? 80}px`}
- min={4}
- max={500}
- value={liquifySettings?.size ?? 80}
- onChange={(v) => onUpdateLiquifySettings?.({ size: v })}
- />
- <CompactSlider
- label="Strength"
- valueLabel={`${liquifySettings?.strength ?? 50}%`}
- min={1}
- max={100}
- value={liquifySettings?.strength ?? 50}
- onChange={(v) => onUpdateLiquifySettings?.({ strength: v })}
- />
- <CompactSlider
- label="Hardness"
- valueLabel={`${liquifySettings?.hardness ?? 50}%`}
- min={0}
- max={100}
- value={liquifySettings?.hardness ?? 50}
- onChange={(v) => onUpdateLiquifySettings?.({ hardness: v })}
- />
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Pressure</span>
- <input
- type="checkbox"
- checked={liquifySettings?.usePressure ?? true}
- onChange={(e) => onUpdateLiquifySettings?.({ usePressure: e.target.checked })}
- />
- </label>
- </div>
- );
- }
-
- if (
- currentTool === 'select-rect' ||
- currentTool === 'select-lasso' ||
- currentTool === 'select-wand' ||
- currentTool === 'select-pen' ||
- currentTool === 'select-eraser'
- ) {
- const activeWand = wandSettings || {
- tolerance: 32,
- contiguous: true,
- antiAlias: true,
- referMode: 'active' as const,
+ window.addEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
+ return () => window.removeEventListener(CUSTOM_BRUSHES_CHANGED_EVENT, handleChanged);
+ }, [syncCustomBrushes]);
+
+ useEffect(() => {
+ if (!isDraggingWidth) return;
+ const handlePointerMove = (e: PointerEvent) => {
+ const delta = e.clientX - dragStartXRef.current;
+ const newWidth = Math.max(
+ 128,
+ Math.min(300, Math.round(dragStartWidthRef.current + delta))
+ );
+ uiStoreActions.setLeftPanelWidth(newWidth);
};
- return (
- <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
- <div className="text-[11px] font-medium text-[#e5e5e5]">Selection</div>
- <div className="grid grid-cols-2 gap-1">
- {(
- [
- { id: 'select-rect', label: 'Rect' },
- { id: 'select-lasso', label: 'Lasso' },
- { id: 'select-wand', label: 'Wand' },
- { id: 'select-pen', label: 'Pen' },
- { id: 'select-eraser', label: 'Erase' },
- ] as const
- ).map((s) => (
- <button
- key={s.id}
- type="button"
- onClick={() => onSelectTool(s.id)}
- className={`py-1 px-1.5 rounded text-[11px] transition-colors cursor-pointer ${
- currentTool === s.id
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- {s.label}
- </button>
- ))}
- </div>
-
- {(currentTool === 'select-pen' || currentTool === 'select-eraser') && (
- <CompactSlider
- label="Brush Size"
- valueLabel={`${brushSettings.size}px`}
- min={1}
- max={250}
- value={Math.round(brushSettings.size)}
- onChange={(v) => onUpdateBrushSettings({ size: v })}
- />
- )}
-
- {currentTool === 'select-wand' && (
- <div className="space-y-2.5 pt-1">
- <CompactSlider
- label="Tolerance"
- valueLabel={`${activeWand.tolerance}`}
- min={0}
- max={255}
- value={activeWand.tolerance}
- onChange={(v) => onUpdateWandSettings?.({ tolerance: v })}
- />
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Contiguous</span>
- <input
- type="checkbox"
- checked={activeWand.contiguous}
- onChange={(e) => onUpdateWandSettings?.({ contiguous: e.target.checked })}
- />
- </label>
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Anti-Alias</span>
- <input
- type="checkbox"
- checked={activeWand.antiAlias}
- onChange={(e) => onUpdateWandSettings?.({ antiAlias: e.target.checked })}
- />
- </label>
- <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
- {(['active', 'all', 'reference'] as const).map((mode) => (
- <button
- key={mode}
- type="button"
- onClick={() => onUpdateWandSettings?.({ referMode: mode })}
- className={`py-0.5 rounded text-[10px] capitalize cursor-pointer ${
- activeWand.referMode === mode
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- {mode === 'reference' ? 'Ref' : mode}
- </button>
- ))}
- </div>
- </div>
- )}
+ const handlePointerUp = () => setIsDraggingWidth(false);
+ window.addEventListener('pointermove', handlePointerMove);
+ window.addEventListener('pointerup', handlePointerUp);
+ return () => {
+ window.removeEventListener('pointermove', handlePointerMove);
+ window.removeEventListener('pointerup', handlePointerUp);
+ };
+ }, [isDraggingWidth]);
- <div className="space-y-1 pt-1">
- <div className="grid grid-cols-3 gap-1">
- <button
- type="button"
- onClick={() => onExpandSelection?.(5)}
- title="Expand 5px"
- className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
- >
- <Maximize2 className="w-3 h-3" />
- </button>
- <button
- type="button"
- onClick={() => onContractSelection?.(5)}
- title="Contract 5px"
- className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
- >
- <Minimize2 className="w-3 h-3" />
- </button>
- <button
- type="button"
- onClick={() => onFeatherSelection?.(5)}
- title="Feather 5px"
- className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
- >
- <Feather className="w-3 h-3" />
- </button>
- </div>
- <button
- type="button"
- onClick={onInvertSelection}
- className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center gap-1.5 cursor-pointer"
- >
- <RotateCcw className="w-3 h-3" />
- <span>Invert</span>
- </button>
- <button
- type="button"
- onClick={onTransformSelection}
- className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center gap-1.5 cursor-pointer"
- >
- <Scaling className="w-3 h-3" />
- <span>Transform</span>
- </button>
- <button
- type="button"
- onClick={onDeselect}
- className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer text-left"
- >
- Deselect
- </button>
- </div>
- </div>
- );
- }
+ const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
- if (currentTool === 'text') {
- return (
- <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
- <div className="text-[11px] font-medium text-[#e5e5e5]">Text</div>
- <select
- value={textSettings?.fontFamily}
- onChange={(e) => onUpdateTextSettings?.({ fontFamily: e.target.value })}
- className="w-full px-2 py-1 text-[11px]"
+ return (
+ <div className="flex h-full select-none z-10 shrink-0 gap-px bg-[#161616]">
+ <ToolStrip
+ onTransformSelection={onTransformSelection}
+ onToggleTransparentColor={onToggleTransparentColor}
+ />
+
+ {!isHidden && (
+ <aside
+ style={{ width }}
+ className="relative bg-[#202020] flex flex-col text-[#e5e5e5] text-xs shrink-0 overflow-hidden"
>
- <option value="'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif">Manga / Anime</option>
- <option value="'Anime Ace', 'Comic Sans MS', sans-serif">Anime Ace</option>
- <option value="Arial, sans-serif">Arial</option>
- <option value="Impact, sans-serif">Impact</option>
- <option value="Georgia, serif">Georgia</option>
- </select>
- <div className="grid grid-cols-2 gap-1 bg-[#161616] p-0.5 rounded">
- <button
- type="button"
- onClick={() => onUpdateTextSettings?.({ writingMode: 'horizontal-tb' })}
- className={`py-1 rounded text-[10px] cursor-pointer ${
- textSettings?.writingMode !== 'vertical-rl'
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- Horiz
- </button>
- <button
- type="button"
- onClick={() => onUpdateTextSettings?.({ writingMode: 'vertical-rl' })}
- className={`py-1 rounded text-[10px] cursor-pointer ${
- textSettings?.writingMode === 'vertical-rl'
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- Vert
- </button>
- </div>
- <CompactSlider
- label="Font Size"
- valueLabel={`${textSettings?.fontSize ?? 28}px`}
- min={12}
- max={160}
- value={textSettings?.fontSize ?? 28}
- onChange={(v) => onUpdateTextSettings?.({ fontSize: v })}
- />
- </div>
- );
- }
-
- if (currentTool === 'frame') {
- return (
- <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
- <div className="text-[11px] font-medium text-[#e5e5e5]">Frame Border</div>
- <CompactSlider
- label="Thickness"
- valueLabel={`${frameSettings?.thickness ?? 4}px`}
- min={1}
- max={100}
- value={frameSettings?.thickness ?? 4}
- onChange={(v) => onUpdateFrameSettings?.({ thickness: v })}
- />
- <div className="grid grid-cols-2 gap-1 bg-[#161616] p-0.5 rounded">
- <button
- type="button"
- onClick={() => onUpdateFrameSettings?.({ fillBackground: true })}
- className={`py-1 rounded text-[10px] cursor-pointer ${
- frameSettings?.fillBackground
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- White
- </button>
- <button
- type="button"
- onClick={() => onUpdateFrameSettings?.({ fillBackground: false })}
- className={`py-1 rounded text-[10px] cursor-pointer ${
- !frameSettings?.fillBackground
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- Empty
- </button>
- </div>
- </div>
- );
- }
-
- if (currentTool === 'balloon') {
- return (
- <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
- <div className="text-[11px] font-medium text-[#e5e5e5]">Balloon</div>
- <div className="space-y-0.5">
- {(['ellipse', 'rounded-rect', 'jagged-flash', 'thought'] as const).map((shape) => (
- <button
- key={shape}
- type="button"
- onClick={() => onUpdateBalloonSettings?.({ shape })}
- className={`w-full px-2 py-1 rounded text-left text-[11px] capitalize cursor-pointer ${
- balloonSettings?.shape === shape
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- {shape.replace('-', ' ')}
- </button>
- ))}
- </div>
- <CompactSlider
- label="Border"
- valueLabel={`${balloonSettings?.strokeWidth ?? 3}px`}
- min={1}
- max={15}
- value={balloonSettings?.strokeWidth ?? 3}
- onChange={(v) => onUpdateBalloonSettings?.({ strokeWidth: v })}
- />
- </div>
- );
- }
-
- if (currentTool === 'vector-edit') {
- const activeMode = vectorEditSettings?.mode || 'pinch';
- return (
- <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
- <div className="text-[11px] font-medium text-[#e5e5e5]">Correct Line</div>
- <div className="space-y-0.5">
- {(['pinch', 'width', 'simplify'] as const).map((m) => (
- <button
- key={m}
- type="button"
- onClick={() => onUpdateVectorEditSettings?.({ mode: m })}
- className={`w-full px-2 py-1 rounded text-left text-[11px] capitalize cursor-pointer ${
- activeMode === m
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- {m}
- </button>
- ))}
- </div>
- <CompactSlider
- label="Radius"
- valueLabel={`${vectorEditSettings?.radius ?? 30}px`}
- min={5}
- max={150}
- value={vectorEditSettings?.radius ?? 30}
- onChange={(v) => onUpdateVectorEditSettings?.({ radius: v })}
- />
- {activeMode === 'pinch' && (
- <CompactSlider
- label="Pinch Level"
- valueLabel={`${Math.round((vectorEditSettings?.pinchStrength ?? 0.65) * 100)}%`}
- min={10}
- max={100}
- value={Math.round((vectorEditSettings?.pinchStrength ?? 0.65) * 100)}
- onChange={(v) => onUpdateVectorEditSettings?.({ pinchStrength: v / 100 })}
- />
- )}
- {activeMode === 'width' && (
- <CompactSlider
- label="Adjust Width"
- valueLabel={`${(vectorEditSettings?.widthFactor ?? 1.2) >= 1 ? '+' : ''}${Math.round(((vectorEditSettings?.widthFactor ?? 1.2) - 1) * 100)}%`}
- min={50}
- max={200}
- value={Math.round((vectorEditSettings?.widthFactor ?? 1.2) * 100)}
- onChange={(v) => onUpdateVectorEditSettings?.({ widthFactor: v / 100 })}
- />
- )}
- {activeMode === 'simplify' && (
- <CompactSlider
- label="Simplify"
- valueLabel={`${(vectorEditSettings?.simplifyTolerance ?? 2.0).toFixed(1)}px`}
- min={0.5}
- max={12}
- step={0.5}
- value={vectorEditSettings?.simplifyTolerance ?? 2.0}
- onChange={(v) => onUpdateVectorEditSettings?.({ simplifyTolerance: v })}
+ {isBrushOrEraser && (
+ <SubToolList
+ customBrushes={customBrushes}
+ setCustomBrushes={setCustomBrushes}
+ />
+ )}
+
+ <ToolPropertyInspector
+ width={width}
+ customBrushes={customBrushes}
+ setCustomBrushes={setCustomBrushes}
+ onDeselect={onDeselect}
+ onTransformSelection={onTransformSelection}
+ onExpandSelection={onExpandSelection}
+ onContractSelection={onContractSelection}
+ onFeatherSelection={onFeatherSelection}
+ onInvertSelection={onInvertSelection}
/>
- )}
- {onOpenMangaEffects && (
- <button
- type="button"
- onClick={onOpenMangaEffects}
- className="w-full py-1.5 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#e5e5e5] cursor-pointer"
- >
- Effect Lines...
- </button>
- )}
- </div>
- );
- }
-
- return (
- <div className="p-2.5 text-[11px] text-[#8a8a8a]">
- <div className="text-[#e5e5e5] font-medium capitalize mb-1">{currentTool}</div>
- <p className="leading-relaxed">Click or drag directly on the canvas.</p>
- </div>
- );
- };
- const visibleBuiltinBrushes = BUILTIN_BRUSHES.filter((b) => {
- if (selectedCategory === 'all') return true;
- if (selectedCategory === 'csp') return false;
- return b.category === selectedCategory;
- });
-
- const showCspBrushes = selectedCategory === 'all' || selectedCategory === 'csp';
- const currentAntiAlias = brushSettings.antiAlias ?? 2;
-
- return (
- <div className="flex h-full select-none z-10 shrink-0 gap-px bg-[#161616]">
- {/* 1. Narrow 44px Tool Strip */}
- <aside className="w-[44px] bg-[#202020] flex flex-col items-center py-1.5 z-20 shrink-0">
- <div className="flex flex-col items-center gap-0.5 w-full px-1">
- {toolItems.map((item) => {
- const isActive = currentTool === item.id;
- return (
- <React.Fragment key={item.id}>
- <button
- type="button"
- onClick={() => (item.onClick ? item.onClick() : onSelectTool(item.id))}
- title={item.label}
- className={`relative w-8 h-7 rounded flex items-center justify-center transition-colors cursor-pointer ${
- isActive
- ? 'bg-[#2c2c2c] text-[var(--accent)]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
- }`}
- >
- {isActive && (
- <span
- className="absolute left-0 top-1.5 bottom-1.5 w-[2px] rounded-full"
- style={{ backgroundColor: 'var(--accent)' }}
- />
- )}
- {item.icon}
- </button>
- {item.dividerAfter && <div className="w-4 h-px bg-[#2c2c2c] my-1" />}
- </React.Fragment>
- );
- })}
- </div>
-
- {/* Bottom Color Swatches & Collapse Toggle */}
- <div className="mt-auto flex flex-col items-center gap-1.5 pt-2 pb-1 w-full">
- <div className="relative w-6 h-6">
+ {/* Subtle Drag Handle on Right Edge */}
<div
- onClick={onSwapColors}
- title={`Secondary: ${secondaryColor} (X to swap, D to reset)`}
- className="absolute bottom-0 right-0 w-4 h-4 rounded-sm cursor-pointer shadow-[0_0_0_1px_rgba(255,255,255,0.18)]"
- style={{ backgroundColor: secondaryColor }}
- />
- <div
- onClick={() => {
- if (isTransparentColor) onToggleTransparentColor?.();
- else onSwapColors();
+ onMouseDown={(e) => {
+ e.preventDefault();
+ setIsDraggingWidth(true);
+ dragStartXRef.current = e.clientX;
+ dragStartWidthRef.current = width;
}}
- title={`Primary: ${primaryColor}`}
- className={`absolute top-0 left-0 w-4 h-4 rounded-sm cursor-pointer z-10 ${
- !isTransparentColor
- ? 'shadow-[0_0_0_1.5px_var(--accent)]'
- : 'opacity-70 shadow-[0_0_0_1px_rgba(255,255,255,0.2)]'
- }`}
- style={{ backgroundColor: primaryColor }}
+ title="Resize brush panel"
+ className="absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-[var(--accent)]/40 transition-colors z-30"
/>
- </div>
-
- <div
- onClick={onToggleTransparentColor}
- title="Transparent Ink (C)"
- className={`w-6 h-2.5 rounded-xs cursor-pointer transition-all ${
- isTransparentColor ? 'shadow-[0_0_0_1.5px_var(--accent)]' : 'opacity-65 hover:opacity-100'
- }`}
- style={{
- backgroundImage: 'repeating-conic-gradient(#777 0% 25%, #ccc 0% 50%)',
- backgroundSize: '4px 4px',
- }}
- />
-
- <button
- type="button"
- onClick={onSwapColors}
- title="Swap Colors (X)"
- className="w-7 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
- >
- <ArrowLeftRight className="w-3 h-3" />
- </button>
-
- <button
- type="button"
- onClick={onToggleHidden}
- title={isHidden ? 'Show Panel (Shift+Tab)' : 'Hide Panel (Shift+Tab)'}
- className="w-7 h-7 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
- >
- {isHidden ? <PanelLeftOpen className="w-3.5 h-3.5" /> : <PanelLeftClose className="w-3.5 h-3.5" />}
- </button>
- </div>
- </aside>
-
- {/* 2. CSP Sub-Tool List + Sub-Tool Detail Inspector */}
- {!isHidden && (
- <aside
- style={{ width }}
- className="relative bg-[#202020] flex flex-col text-[#e5e5e5] text-xs shrink-0 overflow-hidden"
- >
- {isBrushOrEraser ? (
- <>
- {/* Category Filter Strip + Import .sut */}
- <div className="px-1.5 py-1.5 flex items-center gap-1 shrink-0">
- <select
- value={selectedCategory}
- onChange={(e) => setSelectedCategory(e.target.value as 'all' | BrushCategory | 'csp')}
- aria-label="Brush Category"
- className="flex-1 min-w-0 h-5 bg-[#161616] text-[#e5e5e5] text-[11px] px-1.5 rounded cursor-pointer"
- >
- <option value="all" className="bg-[#202020]">All Brushes</option>
- <option value="pencil-line" className="bg-[#202020]">Pencil &amp; Ink</option>
- <option value="color-paint" className="bg-[#202020]">Color &amp; Paint</option>
- <option value="csp" className="bg-[#202020]">CSP Imported</option>
- </select>
-
- <button
- type="button"
- onClick={() => sutInputRef.current?.click()}
- title="Import CSP Brush (.sut)"
- className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"
- >
- <Plus className="w-3 h-3" />
- </button>
- </div>
-
- <input
- type="file"
- ref={sutInputRef}
- accept=".sut"
- className="hidden"
- onChange={(e) => {
- const file = e.target.files?.[0];
- if (file) handleImportSut(file);
- e.target.value = '';
- }}
- />
-
- {/* Compact High-Density Sub-Tool List */}
- <div
- onDragOver={(e) => {
- if (e.dataTransfer.types.includes('Files')) {
- e.preventDefault();
- setIsDraggingFileOver(true);
- }
- }}
- onDragLeave={() => setIsDraggingFileOver(false)}
- onDrop={(e) => {
- e.preventDefault();
- setIsDraggingFileOver(false);
- const files = Array.from(e.dataTransfer.files).filter((f) =>
- f.name.toLowerCase().endsWith('.sut')
- );
- for (const f of files) handleImportSut(f);
- }}
- className="flex-1 overflow-y-auto px-1.5 py-0.5 space-y-0.5 relative min-h-[84px]"
- >
- {isDraggingFileOver && (
- <div className="absolute inset-1 bg-[#161616]/95 rounded flex flex-col items-center justify-center p-2 text-center z-30 pointer-events-none">
- <FolderDown className="w-4 h-4 text-[var(--accent)] mb-1" />
- <span className="text-[10px] text-[#e5e5e5]">Drop .sut</span>
- </div>
- )}
-
- {isImportingSut && (
- <div className="px-2 py-1 rounded bg-[#2c2c2c] text-[10px] text-[#e5e5e5] flex items-center gap-1.5">
- <Loader2 className="w-3 h-3 animate-spin" />
- <span className="truncate">Importing...</span>
- </div>
- )}
-
- {visibleBuiltinBrushes.map((item) => {
- const isSelected =
- currentTool === 'brush' &&
- (brushSettings.preset === item.id || (!brushSettings.preset && item.id === 'pencil-2b'));
-
- return (
- <button
- key={item.id}
- type="button"
- onClick={() => handleSelectBrushPreset(item.id)}
- title={`${item.name} - ${item.desc}`}
- className={`w-full flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors cursor-pointer ${
- isSelected
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- {item.icon === 'pencil' ? (
- <Pencil className="w-3 h-3 shrink-0 opacity-80" />
- ) : item.icon === 'palette' ? (
- <Palette className="w-3 h-3 shrink-0 opacity-80" />
- ) : item.icon === 'square' ? (
- <Square className="w-3 h-3 shrink-0 opacity-80" />
- ) : (
- <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />
- )}
- <span className="text-[11px] truncate leading-tight flex-1">{item.name}</span>
- </button>
- );
- })}
-
- {showCspBrushes &&
- customBrushes.map((brush) => {
- const isSelected = currentTool === 'brush' && brushSettings.preset === brush.id;
- return (
- <div
- key={brush.id}
- onClick={() => handleSelectCustomBrush(brush)}
- title={brush.name}
- className={`group flex items-center justify-between gap-1 px-2 py-1 rounded cursor-pointer transition-colors ${
- isSelected
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
- }`}
- >
- <div className="flex items-center gap-1.5 min-w-0">
- {brush.tipDataUrl ? (
- <img
- src={brush.tipDataUrl}
- alt=""
- className="w-3 h-3 object-contain shrink-0 brightness-125"
- />
- ) : (
- <Sparkles className="w-3 h-3 shrink-0 opacity-80" />
- )}
- <span className="text-[11px] truncate leading-tight">{brush.name}</span>
- </div>
- <button
- type="button"
- onClick={(e) => handleDeleteCustomBrush(e, brush.id)}
- title="Delete brush"
- className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-red-400 shrink-0 cursor-pointer"
- >
- <Trash2 className="w-2.5 h-2.5" />
- </button>
- </div>
- );
- })}
-
- {selectedCategory === 'csp' && customBrushes.length === 0 && (
- <div className="py-4 px-2 text-center space-y-2">
- <p className="text-[10px] text-[#8a8a8a]">Drop .sut brush file</p>
- <button
- type="button"
- onClick={() => sutInputRef.current?.click()}
- className="px-2 py-1 rounded bg-[#2c2c2c] text-[10px] text-[#e5e5e5] cursor-pointer"
- >
- Import .sut
- </button>
- </div>
- )}
- </div>
-
- {/* Live S-Curve Stroke Preview + Quick Size/Opacity Bar */}
- <div className="shrink-0 bg-[#1b1b1b] border-t border-[#2a2a2a] px-2 py-1.5 space-y-1.5">
- <canvas
- ref={previewCanvasRef}
- className="w-full h-8 rounded bg-[#161616] block"
- />
- <CompactSlider
- label="Brush Size ([ / ])"
- valueLabel={`${brushSettings.size < 10 ? brushSettings.size.toFixed(1) : Math.round(brushSettings.size)}px`}
- min={0.5}
- max={500}
- step={0.5}
- value={brushSettings.size}
- onChange={(v) => handleUpdateBrushSettings({ size: v })}
- />
- <CompactSlider
- label="Opacity"
- valueLabel={`${Math.round((brushSettings.opacity ?? 1.0) * 100)}%`}
- min={1}
- max={100}
- value={Math.round((brushSettings.opacity ?? 1.0) * 100)}
- onChange={(v) => handleUpdateBrushSettings({ opacity: v / 100 })}
- />
- </div>
-
- {/* CSP Sub-Tool Detail Accordions */}
- <div className="shrink-0 bg-[#161616] pt-px space-y-px max-h-[50%] overflow-y-auto">
- {/* 1. Ink (Brush Density, Gap Compensation, Blend Tips, 4-stage Anti-Alias) */}
- <div className="bg-[#202020]">
- <button
- type="button"
- onClick={() => toggleAccordion('ink')}
- className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
- >
- <span>Ink</span>
- <div className="flex items-center gap-1">
- <span className="font-mono text-[10px] text-[#e5e5e5]">
- {Math.round((brushSettings.flow ?? 0.85) * 100)}%
- </span>
- {openAccordion === 'ink' ? (
- <ChevronDown className="w-3 h-3" />
- ) : (
- <ChevronRight className="w-3 h-3" />
- )}
- </div>
- </button>
-
- {openAccordion === 'ink' && (
- <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
- <CompactSlider
- label="Brush Density"
- valueLabel={`${Math.round((brushSettings.flow ?? 0.85) * 100)}%`}
- min={1}
- max={100}
- value={Math.round((brushSettings.flow ?? 0.85) * 100)}
- onChange={(v) =>
- handleUpdateBrushSettings({ flow: v / 100, brushDensity: v / 100 })
- }
- />
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Adjust by Gap</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.adjustDensityByGap)}
- onChange={(e) =>
- handleUpdateBrushSettings({ adjustDensityByGap: e.target.checked })
- }
- />
- </label>
- <div className="space-y-1">
- <span className="text-[11px] text-[#8a8a8a]">Blend Tips</span>
- <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
- {(
- [
- { id: 'normal', label: 'Normal' },
- { id: 'darken', label: 'Darken' },
- { id: 'compare', label: 'Compare' },
- ] as Array<{ id: CspBlendTipsMode; label: string }>
- ).map((mode) => (
- <button
- key={mode.id}
- type="button"
- onClick={() => handleUpdateBrushSettings({ blendTipsMode: mode.id })}
- className={`py-0.5 rounded text-[10px] cursor-pointer ${
- (brushSettings.blendTipsMode ?? 'normal') === mode.id
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- {mode.label}
- </button>
- ))}
- </div>
- </div>
- <div className="space-y-1">
- <span className="text-[11px] text-[#8a8a8a]">Anti-Aliasing</span>
- <div className="grid grid-cols-4 gap-0.5 bg-[#161616] p-0.5 rounded">
- {(
- [
- { val: 0, label: 'None' },
- { val: 1, label: 'Weak' },
- { val: 2, label: 'Med' },
- { val: 3, label: 'Strong' },
- ] as const
- ).map((aa) => (
- <button
- key={aa.val}
- type="button"
- onClick={() => handleUpdateBrushSettings({ antiAlias: aa.val })}
- className={`py-0.5 rounded text-[10px] cursor-pointer ${
- currentAntiAlias === aa.val
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- {aa.label}
- </button>
- ))}
- </div>
- </div>
- </div>
- )}
- </div>
-
- {/* 2. Brush Tip (Hardness, Spacing, Thickness H/V, Angle + Dynamics, Flip H/V, Ribbon) */}
- <div className="bg-[#202020]">
- <button
- type="button"
- onClick={() => toggleAccordion('tip')}
- className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
- >
- <span>Brush Tip</span>
- {openAccordion === 'tip' ? (
- <ChevronDown className="w-3 h-3" />
- ) : (
- <ChevronRight className="w-3 h-3" />
- )}
- </button>
-
- {openAccordion === 'tip' && (
- <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
- <CompactSlider
- label="Hardness"
- valueLabel={`${Math.round((brushSettings.hardness ?? 1.0) * 100)}%`}
- min={5}
- max={100}
- value={Math.round((brushSettings.hardness ?? 1.0) * 100)}
- onChange={(v) => handleUpdateBrushSettings({ hardness: v / 100 })}
- />
- <CompactSlider
- label="Gap (Spacing)"
- valueLabel={`${Math.round((brushSettings.spacing ?? 0.1) * 100)}%`}
- min={1}
- max={100}
- value={Math.round((brushSettings.spacing ?? 0.1) * 100)}
- onChange={(v) => handleUpdateBrushSettings({ spacing: v / 100 })}
- />
- <CompactSlider
- label="Thickness"
- valueLabel={`${Math.round((brushSettings.thickness ?? 1.0) * 100)}%`}
- min={5}
- max={100}
- value={Math.round((brushSettings.thickness ?? 1.0) * 100)}
- onChange={(v) => handleUpdateBrushSettings({ thickness: v / 100 })}
- />
- <div className="grid grid-cols-2 gap-0.5 bg-[#161616] p-0.5 rounded">
- <button
- type="button"
- onClick={() => handleUpdateBrushSettings({ thicknessVertical: false })}
- className={`py-0.5 rounded text-[10px] cursor-pointer ${
- !brushSettings.thicknessVertical
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a]'
- }`}
- >
- Horizontal
- </button>
- <button
- type="button"
- onClick={() => handleUpdateBrushSettings({ thicknessVertical: true })}
- className={`py-0.5 rounded text-[10px] cursor-pointer ${
- brushSettings.thicknessVertical
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a]'
- }`}
- >
- Vertical
- </button>
- </div>
- <CompactSlider
- label="Angle"
- valueLabel={`${Math.round(brushSettings.customTipAngle ?? 0)}deg`}
- min={0}
- max={360}
- value={Math.round(brushSettings.customTipAngle ?? 0)}
- onChange={(v) => handleUpdateBrushSettings({ customTipAngle: v })}
- />
- <div className="space-y-1">
- <span className="text-[11px] text-[#8a8a8a]">Angle Dynamics</span>
- <select
- value={brushSettings.customTipAngleDynamics ?? 'none'}
- onChange={(e) =>
- handleUpdateBrushSettings({
- customTipAngleDynamics: e.target.value as CspAngleDynamicsMode,
- })
- }
- className="w-full h-6 bg-[#161616] text-[#e5e5e5] text-[10px] px-1.5 rounded cursor-pointer"
- >
- <option value="none">None</option>
- <option value="direction">Direction of Line</option>
- <option value="tilt">Pen Tilt</option>
- <option value="twist">Barrel Twist</option>
- <option value="random">Random</option>
- <option value="direction-random">Direction + Random</option>
- </select>
- </div>
- <div className="grid grid-cols-2 gap-1.5">
- <div className="space-y-0.5">
- <span className="text-[10px] text-[#8a8a8a]">Flip H</span>
- <select
- value={brushSettings.flipH ?? 'none'}
- onChange={(e) =>
- handleUpdateBrushSettings({ flipH: e.target.value as CspTipFlipMode })
- }
- className="w-full h-5 bg-[#161616] text-[#e5e5e5] text-[10px] px-1 rounded cursor-pointer"
- >
- <option value="none">None</option>
- <option value="random">Random</option>
- <option value="alternate">Alternate</option>
- </select>
- </div>
- <div className="space-y-0.5">
- <span className="text-[10px] text-[#8a8a8a]">Flip V</span>
- <select
- value={brushSettings.flipV ?? 'none'}
- onChange={(e) =>
- handleUpdateBrushSettings({ flipV: e.target.value as CspTipFlipMode })
- }
- className="w-full h-5 bg-[#161616] text-[#e5e5e5] text-[10px] px-1 rounded cursor-pointer"
- >
- <option value="none">None</option>
- <option value="random">Random</option>
- <option value="alternate">Alternate</option>
- </select>
- </div>
- </div>
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Ribbon</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.isRibbon)}
- onChange={(e) => handleUpdateBrushSettings({ isRibbon: e.target.checked })}
- />
- </label>
- </div>
- )}
- </div>
-
- {/* 3. Stroke & Stabilization */}
- <div className="bg-[#202020]">
- <button
- type="button"
- onClick={() => toggleAccordion('stroke')}
- className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
- >
- <span>Stabilization &amp; Stroke</span>
- <div className="flex items-center gap-1">
- <span className="font-mono text-[10px] text-[#e5e5e5]">
- {brushSettings.stabilization ?? 15}
- </span>
- {openAccordion === 'stroke' ? (
- <ChevronDown className="w-3 h-3" />
- ) : (
- <ChevronRight className="w-3 h-3" />
- )}
- </div>
- </button>
-
- {openAccordion === 'stroke' && (
- <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
- <CompactSlider
- label="Stabilization"
- valueLabel={`${brushSettings.stabilization ?? 15}`}
- min={0}
- max={50}
- value={brushSettings.stabilization ?? 15}
- onChange={(v) => handleUpdateBrushSettings({ stabilization: v })}
- />
- <CompactSlider
- label="Post-Correction"
- valueLabel={`${brushSettings.postCorrection ?? 0}`}
- min={0}
- max={5}
- value={brushSettings.postCorrection ?? 0}
- onChange={(v) => handleUpdateBrushSettings({ postCorrection: v })}
- />
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Sharp Angles</span>
- <input
- type="checkbox"
- checked={brushSettings.sharpCorners ?? true}
- onChange={(e) =>
- handleUpdateBrushSettings({ sharpCorners: e.target.checked })
- }
- />
- </label>
-
- <div className="grid grid-cols-2 gap-1.5">
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Taper In</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.taper?.useIn)}
- onChange={(e) => handleUpdateTaper({ useIn: e.target.checked })}
- />
- </label>
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Taper Out</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.taper?.useOut)}
- onChange={(e) => handleUpdateTaper({ useOut: e.target.checked })}
- />
- </label>
- </div>
- {(brushSettings.taper?.useIn || brushSettings.taper?.useOut) && (
- <CompactSlider
- label="Taper Length"
- valueLabel={`${Math.round(brushSettings.taper?.outLength ?? 32)}px`}
- min={4}
- max={200}
- value={Math.round(brushSettings.taper?.outLength ?? 32)}
- onChange={(v) =>
- handleUpdateTaper({ inLength: v, outLength: v })
- }
- />
- )}
-
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Pen Pressure</span>
- <input
- type="checkbox"
- checked={brushSettings.usePressure}
- onChange={(e) =>
- handleUpdateBrushSettings({ usePressure: e.target.checked })
- }
- />
- </label>
- {brushSettings.usePressure && (
- <>
- <CompactSlider
- label="Min Width"
- valueLabel={`${Math.round(brushSettings.minSizeFactor * 100)}%`}
- min={0}
- max={95}
- value={Math.round(brushSettings.minSizeFactor * 100)}
- onChange={(v) => handleUpdateBrushSettings({ minSizeFactor: v / 100 })}
- />
- <div className="space-y-1">
- <span className="text-[10px] text-[#8a8a8a]">Pressure Curve</span>
- <div className="grid grid-cols-5 gap-0.5 bg-[#161616] p-0.5 rounded">
- {(
- [
- { id: 'linear', short: 'Lin' },
- { id: 'g-pen', short: 'G' },
- { id: 'soft', short: 'Soft' },
- { id: 'firm', short: 'Firm' },
- { id: 'chisel', short: 'Hard' },
- ] as const
- ).map((p) => (
- <button
- key={p.id}
- type="button"
- title={CSP_PRESSURE_CURVE_PRESETS[p.id]?.label}
- onClick={() =>
- handleUpdateBrushSettings({
- pressureCurve: CSP_PRESSURE_CURVE_PRESETS[p.id]?.points,
- })
- }
- className="py-0.5 rounded text-[9px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
- >
- {p.short}
- </button>
- ))}
- </div>
- </div>
- </>
- )}
-
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Stylus Tilt</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.useTilt)}
- onChange={(e) => handleUpdateBrushSettings({ useTilt: e.target.checked })}
- />
- </label>
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Velocity Dynamics</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.useVelocity)}
- onChange={(e) =>
- handleUpdateBrushSettings({ useVelocity: e.target.checked })
- }
- />
- </label>
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Bezier Smoothing</span>
- <input
- type="checkbox"
- checked={brushSettings.smoothing}
- onChange={(e) =>
- handleUpdateBrushSettings({ smoothing: e.target.checked })
- }
- />
- </label>
- <button
- type="button"
- onClick={() => {
- const def = resetBrushSettingsToDefault(
- currentTool === 'eraser'
- ? ERASER_PRESET_ID
- : brushSettings.preset || 'pencil-2b',
- customBrushes
- );
- handleUpdateBrushSettings(def);
- }}
- className="w-full py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
- >
- Reset Brush to Default
- </button>
- </div>
- )}
- </div>
-
- {/* 4. Color Mixing & Watercolor Edge */}
- <div className="bg-[#202020]">
- <button
- type="button"
- onClick={() => toggleAccordion('mixing')}
- className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
- >
- <span>Color Mixing &amp; Edge</span>
- {openAccordion === 'mixing' ? (
- <ChevronDown className="w-3 h-3" />
- ) : (
- <ChevronRight className="w-3 h-3" />
- )}
- </button>
-
- {openAccordion === 'mixing' && (
- <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Color Mixing</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.colorMixing)}
- onChange={(e) =>
- handleUpdateBrushSettings({ colorMixing: e.target.checked })
- }
- />
- </label>
- {brushSettings.colorMixing && (
- <>
- <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
- {(
- [
- { id: 'blend', label: 'Blend' },
- { id: 'running_color', label: 'Running' },
- { id: 'smear', label: 'Smear' },
- ] as const
- ).map((m) => (
- <button
- key={m.id}
- type="button"
- onClick={() => handleUpdateBrushSettings({ mixingMode: m.id })}
- className={`py-0.5 rounded text-[10px] cursor-pointer ${
- (brushSettings.mixingMode || 'blend') === m.id
- ? 'bg-[#2c2c2c] text-[#e5e5e5]'
- : 'text-[#8a8a8a]'
- }`}
- >
- {m.label}
- </button>
- ))}
- </div>
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Perceptual (OKLab)</span>
- <input
- type="checkbox"
- checked={brushSettings.perceptualMixing ?? true}
- onChange={(e) =>
- handleUpdateBrushSettings({ perceptualMixing: e.target.checked })
- }
- />
- </label>
- <CompactSlider
- label="Amount of Paint"
- valueLabel={`${Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}
- onChange={(v) => handleUpdateBrushSettings({ amountOfPaint: v / 100 })}
- />
- <CompactSlider
- label="Density of Paint"
- valueLabel={`${Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}%`}
- min={1}
- max={100}
- value={Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}
- onChange={(v) => handleUpdateBrushSettings({ densityOfPaint: v / 100 })}
- />
- <CompactSlider
- label="Color Stretch"
- valueLabel={`${Math.round((brushSettings.colorStretch ?? 0.6) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.colorStretch ?? 0.6) * 100)}
- onChange={(v) => handleUpdateBrushSettings({ colorStretch: v / 100 })}
- />
- </>
- )}
- <CompactSlider
- label="Watercolor Edge"
- valueLabel={`${Math.round((brushSettings.wetEdge ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.wetEdge ?? 0) * 100)}
- onChange={(v) => handleUpdateBrushSettings({ wetEdge: v / 100 })}
- />
- {(brushSettings.wetEdge ?? 0) > 0.01 && (
- <CompactSlider
- label="Edge Width"
- valueLabel={`${brushSettings.wetEdgeRadius ?? 4}px`}
- min={1}
- max={20}
- value={Math.round(brushSettings.wetEdgeRadius ?? 4)}
- onChange={(v) => handleUpdateBrushSettings({ wetEdgeRadius: v })}
- />
- )}
- </div>
- )}
- </div>
-
- {/* 5. Texture & Spraying Effect */}
- <div className="bg-[#202020]">
- <button
- type="button"
- onClick={() => toggleAccordion('texture')}
- className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
- >
- <span>Texture &amp; Spray</span>
- {openAccordion === 'texture' ? (
- <ChevronDown className="w-3 h-3" />
- ) : (
- <ChevronRight className="w-3 h-3" />
- )}
- </button>
-
- {openAccordion === 'texture' && (
- <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
- <CompactSlider
- label="Texture Density"
- valueLabel={`${Math.round((brushSettings.grain ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.grain ?? 0) * 100)}
- onChange={(v) =>
- handleUpdateBrushSettings({ grain: v / 100, textureDensity: v / 100 })
- }
- />
- {(brushSettings.grain ?? 0) > 0.005 && (
- <>
- <div className="space-y-1">
- <span className="text-[11px] text-[#8a8a8a]">Texture Mode</span>
- <select
- value={brushSettings.paperTextureMode ?? 'subtract'}
- onChange={(e) =>
- handleUpdateBrushSettings({
- paperTextureMode: e.target.value as CspPaperTextureMode,
- })
- }
- className="w-full h-6 bg-[#161616] text-[#e5e5e5] text-[10px] px-1.5 rounded cursor-pointer"
- >
- <option value="subtract">Subtract (Valley Fill)</option>
- <option value="multiply">Multiply</option>
- <option value="compare">Compare Density</option>
- <option value="overlay">Overlay</option>
- <option value="outline">Outline</option>
- </select>
- </div>
- <CompactSlider
- label="Texture Scale"
- valueLabel={`${Math.round((brushSettings.paperTextureScale ?? 1.0) * 100)}%`}
- min={10}
- max={400}
- step={5}
- value={Math.round((brushSettings.paperTextureScale ?? 1.0) * 100)}
- onChange={(v) =>
- handleUpdateBrushSettings({ paperTextureScale: v / 100 })
- }
- />
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Invert Texture</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.paperTextureInverted)}
- onChange={(e) =>
- handleUpdateBrushSettings({
- paperTextureInverted: e.target.checked,
- })
- }
- />
- </label>
- </>
- )}
-
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer pt-1">
- <span>Spraying Effect</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.spray?.enabled)}
- onChange={(e) => handleUpdateSpray({ enabled: e.target.checked })}
- />
- </label>
- {brushSettings.spray?.enabled && (
- <>
- <CompactSlider
- label="Particle Size"
- valueLabel={`${brushSettings.spray.size ?? 4}px`}
- min={1}
- max={80}
- value={Math.round(brushSettings.spray.size ?? 4)}
- onChange={(v) => handleUpdateSpray({ size: v })}
- />
- <CompactSlider
- label="Spray Density"
- valueLabel={`${brushSettings.spray.density ?? 12}`}
- min={1}
- max={64}
- value={Math.round(brushSettings.spray.density ?? 12)}
- onChange={(v) => handleUpdateSpray({ density: v })}
- />
- </>
- )}
- </div>
- )}
- </div>
-
- {/* 6. Dynamics & Jitter */}
- <div className="bg-[#202020]">
- <button
- type="button"
- onClick={() => toggleAccordion('dynamics')}
- className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
- >
- <span>Dynamics &amp; Jitter</span>
- {openAccordion === 'dynamics' ? (
- <ChevronDown className="w-3 h-3" />
- ) : (
- <ChevronRight className="w-3 h-3" />
- )}
- </button>
-
- {openAccordion === 'dynamics' && (
- <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
- <CompactSlider
- label="Size Jitter"
- valueLabel={`${Math.round((brushSettings.dynamics?.sizeJitter ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.dynamics?.sizeJitter ?? 0) * 100)}
- onChange={(v) => handleUpdateDynamics({ sizeJitter: v / 100 })}
- />
- <CompactSlider
- label="Angle Jitter"
- valueLabel={`${Math.round((brushSettings.dynamics?.angleJitter ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.dynamics?.angleJitter ?? 0) * 100)}
- onChange={(v) => handleUpdateDynamics({ angleJitter: v / 100 })}
- />
- <CompactSlider
- label="Roundness Jitter"
- valueLabel={`${Math.round((brushSettings.dynamics?.roundnessJitter ?? 0) * 100)}%`}
- min={0}
- max={95}
- value={Math.round((brushSettings.dynamics?.roundnessJitter ?? 0) * 100)}
- onChange={(v) => handleUpdateDynamics({ roundnessJitter: v / 100 })}
- />
- <CompactSlider
- label="Scatter"
- valueLabel={`${(brushSettings.dynamics?.scatter ?? 0).toFixed(1)}x`}
- min={0}
- max={5}
- step={0.1}
- value={brushSettings.dynamics?.scatter ?? 0}
- onChange={(v) => handleUpdateDynamics({ scatter: v })}
- />
- {(brushSettings.dynamics?.scatter ?? 0) > 0 && (
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Scatter Both Axes</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.dynamics?.scatterBothAxes)}
- onChange={(e) =>
- handleUpdateDynamics({ scatterBothAxes: e.target.checked })
- }
- />
- </label>
- )}
- <CompactSlider
- label="Count"
- valueLabel={`${brushSettings.dynamics?.count ?? 1}`}
- min={1}
- max={10}
- value={brushSettings.dynamics?.count ?? 1}
- onChange={(v) => handleUpdateDynamics({ count: v })}
- />
- <CompactSlider
- label="Flow Jitter"
- valueLabel={`${Math.round((brushSettings.dynamics?.flowJitter ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.dynamics?.flowJitter ?? 0) * 100)}
- onChange={(v) => handleUpdateDynamics({ flowJitter: v / 100 })}
- />
- <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
- <span>Color Jitter</span>
- <input
- type="checkbox"
- checked={Boolean(brushSettings.dynamics?.colorJitterEnabled)}
- onChange={(e) =>
- handleUpdateDynamics({ colorJitterEnabled: e.target.checked })
- }
- />
- </label>
- {brushSettings.dynamics?.colorJitterEnabled && (
- <>
- <CompactSlider
- label="Hue"
- valueLabel={`${Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}
- onChange={(v) => handleUpdateDynamics({ hueJitter: v / 100 })}
- />
- <CompactSlider
- label="Saturation"
- valueLabel={`${Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}
- onChange={(v) => handleUpdateDynamics({ saturationJitter: v / 100 })}
- />
- <CompactSlider
- label="Brightness"
- valueLabel={`${Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}
- onChange={(v) => handleUpdateDynamics({ brightnessJitter: v / 100 })}
- />
- <CompactSlider
- label="FG / BG Mix"
- valueLabel={`${Math.round((brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100)}%`}
- min={0}
- max={100}
- value={Math.round((brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100)}
- onChange={(v) => handleUpdateDynamics({ foregroundBackgroundJitter: v / 100 })}
- />
- </>
- )}
- </div>
- )}
- </div>
- </div>
- </>
- ) : (
- renderContextualToolPanel()
- )}
-
- {/* Subtle Drag Handle on Right Edge */}
- <div
- onMouseDown={(e) => {
- e.preventDefault();
- setIsDraggingWidth(true);
- dragStartXRef.current = e.clientX;
- dragStartWidthRef.current = width;
- }}
- title="Resize brush panel"
- className="absolute right-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-[var(--accent)]/40 transition-colors z-30"
- />
- </aside>
- )}
- </div>
- );
-});
+ </aside>
+ )}
+ </div>
+ );
+ }
+);
LeftPanel.displayName = 'LeftPanel';
diff --git a/src/components/ModalHost.tsx b/src/components/ModalHost.tsx
new file mode 100644
index 0000000..4bcd3e2
--- /dev/null
+++ b/src/components/ModalHost.tsx
@@ -0,0 +1,317 @@
+import React, { useCallback } from 'react';
+import { CheckCircle2, Loader2 } from 'lucide-react';
+import {
+ AdjustmentLayerData,
+ LayerItem,
+ LayerStyles,
+ NewCanvasOptions,
+} from '../types/editor';
+import { AppSettings, ResizeCanvasOptions } from '../types/settings';
+import { CollabPeer, SessionHostInfo } from '../types/multiplayer';
+import { CrashedSessionInfo } from '../services/recoveryService';
+import { TonalCorrectionType } from '../utils/tonalEngine';
+import { AnyTonalParams } from '../hooks/useTonalAndFilterActions';
+import { SaturatedLinesOptions, StreamLinesOptions } from '../utils/mangaEffectsEngine';
+import { compositeCanvas } from '../utils/saveManager';
+import { documentStore } from '../utils/documentStore';
+import { useDocumentStore, useUiStore, uiStoreActions } from '../stores';
+import { CrashRecoveryModal } from './CrashRecoveryModal';
+import { NewCanvasModal } from './NewCanvasModal';
+import { ResizeCanvasModal } from './ResizeCanvasModal';
+import { SettingsModal } from './SettingsModal';
+import { TonalCorrectionModal } from './TonalCorrectionModal';
+import { AdjustmentModal } from './AdjustmentModal';
+import { LayerStylesModal } from './LayerStylesModal';
+import { SimpleToneModal, SimpleToneSettings } from './SimpleToneModal';
+import { HostModal } from './HostModal';
+import { ClipboardInviteToast } from './ClipboardInviteToast';
+import { WebLandingModal } from './WebLandingModal';
+import { MangaEffectsModal } from './MangaEffectsModal';
+import { WebtoonExportModal } from './WebtoonExportModal';
+
+export interface InviteLinkPayload {
+ roomName: string;
+ host: string;
+ port: number;
+ url: string;
+}
+
+export interface ModalHostProps {
+ layers: LayerItem[];
+ activeLayer: LayerItem | undefined;
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ getEffectiveOpacity: (layer: LayerItem) => number;
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
+ handleCreateNewCanvas: (options: NewCanvasOptions) => void;
+ handleResizeCanvas: (options: ResizeCanvasOptions) => void;
+ handleUpdateSettings: (newSettings: AppSettings) => void;
+ handleRestoreCrashedSession: (session: CrashedSessionInfo) => Promise<void>;
+ handleDiscardCrashedSession: (session: CrashedSessionInfo) => Promise<void>;
+ handleTonalCancel: () => void;
+ handleTonalApply: (type: TonalCorrectionType, params: AnyTonalParams) => void;
+ handleTonalPreviewChange: (
+ type: TonalCorrectionType,
+ params: AnyTonalParams,
+ enabled: boolean
+ ) => void;
+ handleApplyAdjustment: (
+ type: 'curves' | 'gradient-map' | 'levels' | 'color-balance',
+ data: AdjustmentLayerData
+ ) => void;
+ handleApplyLayerStyles: (styles: LayerStyles) => void;
+ handleConfirmTone: (settings: SimpleToneSettings) => void;
+ handleApplyMangaEffects: (
+ type: 'saturated' | 'stream',
+ options: SaturatedLinesOptions | StreamLinesOptions
+ ) => void;
+ // Multiplayer modal props
+ isHostModalOpen: boolean;
+ setIsHostModalOpen: (open: boolean) => void;
+ isCollabHost: boolean;
+ isCollabConnected: boolean;
+ collabHostInfo: SessionHostInfo | null;
+ collabPeers: CollabPeer[];
+ collabMyPeer: CollabPeer;
+ updateMyName: (name: string) => void;
+ handleStartHosting: (
+ roomName: string,
+ port: number,
+ hostNickname?: string,
+ isGlobal?: boolean
+ ) => Promise<boolean | SessionHostInfo>;
+ stopHosting: () => void;
+ clipboardInvite: InviteLinkPayload | null;
+ setClipboardInvite: (invite: InviteLinkPayload | null) => void;
+ webLandingInvite: InviteLinkPayload | null;
+ setWebLandingInvite: (invite: InviteLinkPayload | null) => void;
+ joinRoom: (host: string, port: number, roomName: string, name: string) => void;
+ showToast: (msg: string) => void;
+}
+
+export const ModalHost: React.FC<ModalHostProps> = React.memo(
+ ({
+ layers,
+ activeLayer,
+ layerCanvasesRef,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ handleCreateNewCanvas,
+ handleResizeCanvas,
+ handleUpdateSettings,
+ handleRestoreCrashedSession,
+ handleDiscardCrashedSession,
+ handleTonalCancel,
+ handleTonalApply,
+ handleTonalPreviewChange,
+ handleApplyAdjustment,
+ handleApplyLayerStyles,
+ handleConfirmTone,
+ handleApplyMangaEffects,
+ isHostModalOpen,
+ setIsHostModalOpen,
+ isCollabHost,
+ isCollabConnected,
+ collabHostInfo,
+ collabPeers,
+ collabMyPeer,
+ updateMyName,
+ handleStartHosting,
+ stopHosting,
+ clipboardInvite,
+ setClipboardInvite,
+ webLandingInvite,
+ setWebLandingInvite,
+ joinRoom,
+ showToast,
+ }) => {
+ const dimensions = useDocumentStore((s) => s.dimensions);
+ const documents = useDocumentStore((s) => s.documents);
+ const activeDocumentId = useDocumentStore((s) => s.activeDocumentId);
+
+ const isRecoveryModalOpen = useUiStore((s) => s.isRecoveryModalOpen);
+ const crashedSessions = useUiStore((s) => s.crashedSessions);
+ const isNewCanvasModalOpen = useUiStore((s) => s.isNewCanvasModalOpen);
+ const isResizeCanvasModalOpen = useUiStore((s) => s.isResizeCanvasModalOpen);
+ const isSettingsModalOpen = useUiStore((s) => s.isSettingsModalOpen);
+ const appSettings = useUiStore((s) => s.appSettings);
+ const tonalModalState = useUiStore((s) => s.tonalModalState);
+ const adjustmentModalState = useUiStore((s) => s.adjustmentModalState);
+ const layerStylesModalState = useUiStore((s) => s.layerStylesModalState);
+ const isToneModalOpen = useUiStore((s) => s.isToneModalOpen);
+ const isMangaEffectsModalOpen = useUiStore((s) => s.isMangaEffectsModalOpen);
+ const isWebtoonExportModalOpen = useUiStore((s) => s.isWebtoonExportModalOpen);
+ const isLoadingFile = useUiStore((s) => s.isLoadingFile);
+ const loadingStatus = useUiStore((s) => s.loadingStatus);
+ const toastMessage = useUiStore((s) => s.toastMessage);
+
+ const getWebtoonActiveCanvas = useCallback(
+ () =>
+ compositeCanvas(
+ dimensions,
+ layers,
+ layerCanvasesRef.current,
+ getEffectiveOpacity,
+ isLayerEffectivelyVisible,
+ false,
+ documentStore.getActiveTileGrid()
+ ),
+ [dimensions, layers, layerCanvasesRef, getEffectiveOpacity, isLayerEffectivelyVisible]
+ );
+
+ const activeDoc = documents.find((d) => d.id === activeDocumentId);
+
+ return (
+ <>
+ <CrashRecoveryModal
+ isOpen={isRecoveryModalOpen}
+ sessions={crashedSessions}
+ onRestore={handleRestoreCrashedSession}
+ onDiscard={handleDiscardCrashedSession}
+ onClose={() => uiStoreActions.setRecoveryModal(false)}
+ />
+
+ <NewCanvasModal
+ isOpen={isNewCanvasModalOpen}
+ onClose={() => uiStoreActions.setNewCanvasModalOpen(false)}
+ onCreate={handleCreateNewCanvas}
+ initialWidth={dimensions.width}
+ initialHeight={dimensions.height}
+ initialDpi={dimensions.dpi || 300}
+ initialName="Untitled*"
+ />
+
+ <ResizeCanvasModal
+ isOpen={isResizeCanvasModalOpen}
+ onClose={() => uiStoreActions.setResizeCanvasModalOpen(false)}
+ currentDimensions={dimensions}
+ onResize={handleResizeCanvas}
+ />
+
+ <SettingsModal
+ isOpen={isSettingsModalOpen}
+ onClose={() => uiStoreActions.setSettingsModalOpen(false)}
+ settings={appSettings}
+ onUpdateSettings={handleUpdateSettings}
+ onShowToast={showToast}
+ />
+
+ <TonalCorrectionModal
+ isOpen={tonalModalState.isOpen}
+ type={tonalModalState.type}
+ beforeImageData={tonalModalState.beforeImageData}
+ selectionMask={tonalModalState.selectionMask}
+ onClose={handleTonalCancel}
+ onApply={handleTonalApply}
+ onPreviewChange={handleTonalPreviewChange}
+ />
+
+ {adjustmentModalState.isOpen && (
+ <AdjustmentModal
+ isOpen={adjustmentModalState.isOpen}
+ initialType={adjustmentModalState.initialType || 'curves'}
+ initialData={
+ adjustmentModalState.layerId
+ ? layers.find((l) => l.id === adjustmentModalState.layerId)?.adjustmentData
+ : undefined
+ }
+ editingLayerId={adjustmentModalState.layerId}
+ onApply={handleApplyAdjustment}
+ onClose={() => uiStoreActions.setAdjustmentModalState({ isOpen: false })}
+ />
+ )}
+
+ {layerStylesModalState.isOpen && (
+ <LayerStylesModal
+ isOpen={layerStylesModalState.isOpen}
+ layerName={
+ layers.find((l) => l.id === layerStylesModalState.layerId)?.name || 'Layer'
+ }
+ initialStyles={layers.find((l) => l.id === layerStylesModalState.layerId)?.styles}
+ onClose={() => uiStoreActions.setLayerStylesModalState({ isOpen: false })}
+ onApply={handleApplyLayerStyles}
+ />
+ )}
+
+ <SimpleToneModal
+ isOpen={isToneModalOpen}
+ onClose={() => uiStoreActions.setToneModalOpen(false)}
+ onConfirm={handleConfirmTone}
+ initialFrequency={activeLayer?.toneFrequency || activeDoc?.defaultFrequency || 60}
+ initialDensity={activeLayer?.toneDensity || 40}
+ dpi={dimensions.dpi ?? 600}
+ />
+
+ <HostModal
+ isOpen={isHostModalOpen}
+ onClose={() => setIsHostModalOpen(false)}
+ isHost={isCollabHost}
+ isConnected={isCollabConnected}
+ hostInfo={collabHostInfo}
+ peers={collabPeers}
+ myPeer={collabMyPeer}
+ onUpdateMyName={updateMyName}
+ onStartHosting={handleStartHosting}
+ onStopHosting={stopHosting}
+ showToast={showToast}
+ />
+
+ <ClipboardInviteToast
+ invite={clipboardInvite}
+ onJoin={(h, p, r) => joinRoom(h, p, r, collabMyPeer.name)}
+ onDismiss={() => setClipboardInvite(null)}
+ />
+
+ <WebLandingModal
+ invite={webLandingInvite}
+ onJoinInBrowser={(name, h, p, r) => {
+ updateMyName(name);
+ joinRoom(h, p, r, name);
+ }}
+ onDismiss={() => setWebLandingInvite(null)}
+ />
+
+ {isLoadingFile && (
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/70 select-none">
+ <div className="bg-[#202020] rounded-md shadow-[0_16px_48px_rgba(0,0,0,0.75)] px-5 py-3.5 flex items-center gap-3 text-xs text-[#e5e5e5]">
+ <Loader2 className="w-4 h-4 text-[var(--accent)] animate-spin" />
+ <div className="flex flex-col">
+ <span className="font-medium text-xs">
+ {loadingStatus || 'Opening Document...'}
+ </span>
+ <span className="text-[#8a8a8a] text-[10px]">
+ Extracting layers and pixel data
+ </span>
+ </div>
+ </div>
+ </div>
+ )}
+
+ {toastMessage && (
+ <div className="fixed bottom-5 right-5 z-50 bg-[#202020] text-[#e5e5e5] px-3.5 py-2 rounded-md shadow-[0_12px_32px_rgba(0,0,0,0.65)] flex items-center gap-2 text-xs">
+ <CheckCircle2 className="w-3.5 h-3.5 text-[var(--accent)]" />
+ <span className="font-medium">{toastMessage}</span>
+ </div>
+ )}
+
+ <MangaEffectsModal
+ isOpen={isMangaEffectsModalOpen}
+ onClose={() => uiStoreActions.setMangaEffectsModalOpen(false)}
+ canvasWidth={dimensions.width}
+ canvasHeight={dimensions.height}
+ onApply={handleApplyMangaEffects}
+ />
+
+ <WebtoonExportModal
+ isOpen={isWebtoonExportModalOpen}
+ onClose={() => uiStoreActions.setWebtoonExportModalOpen(false)}
+ getActiveCanvas={getWebtoonActiveCanvas}
+ canvasWidth={dimensions.width}
+ canvasHeight={dimensions.height}
+ documentTitle={activeDoc?.name || 'webtoon_chapter'}
+ />
+ </>
+ );
+ }
+);
+
+ModalHost.displayName = 'ModalHost';
diff --git a/src/components/QuickAccessPanel.tsx b/src/components/QuickAccessPanel.tsx
new file mode 100644
index 0000000..049034b
--- /dev/null
+++ b/src/components/QuickAccessPanel.tsx
@@ -0,0 +1,507 @@
+import React, { useState } from 'react';
+import {
+ LayoutGrid,
+ List,
+ Plus,
+ Trash2,
+ ChevronUp,
+ ChevronDown,
+ RotateCcw,
+ Paintbrush,
+ Eraser,
+ Pipette,
+ PaintBucket,
+ BoxSelect,
+ Lasso,
+ Wand2,
+ Type,
+ Frame,
+ MessageSquare,
+ Spline,
+ Scaling,
+ SlidersHorizontal,
+ Palette,
+ PenTool,
+} from 'lucide-react';
+import { ToolType } from '../types/editor';
+import { ThemePreset } from '../types/settings';
+import { COMMAND_CATALOG, CommandActionId, QuickAccessItem } from '../types/workspace';
+import { BUILTIN_BRUSHES } from '../utils/presetBrushes';
+import { getEffectiveBrushSettings, saveActivePresetId } from '../utils/brushPresetManager';
+import {
+ toolStoreActions,
+ useToolStore,
+ useWorkspaceStore,
+ workspaceStoreActions,
+} from '../stores';
+import {
+ WorkspaceCommandHandlers,
+ executeWorkspaceCommand,
+ isCommandActive,
+ isCommandDisabled,
+ renderCommandIcon,
+} from './CommandBar';
+import { LiquifyIcon } from './LiquifyIcon';
+
+const QUICK_TOOL_CATALOG: Array<{ id: ToolType; label: string }> = [
+ { id: 'brush', label: 'Brush' },
+ { id: 'eraser', label: 'Eraser' },
+ { id: 'pipette', label: 'Eyedropper' },
+ { id: 'liquify', label: 'Liquify' },
+ { id: 'fill', label: 'Fill Bucket' },
+ { id: 'select-rect', label: 'Marquee' },
+ { id: 'select-lasso', label: 'Lasso' },
+ { id: 'select-wand', label: 'Magic Wand' },
+ { id: 'select-pen', label: 'Selection Pen' },
+ { id: 'transform', label: 'Transform' },
+ { id: 'text', label: 'Text' },
+ { id: 'frame', label: 'Frame Border' },
+ { id: 'balloon', label: 'Speech Balloon' },
+ { id: 'vector-edit', label: 'Correct Line' },
+];
+
+function renderToolIcon(tool: ToolType): React.ReactNode {
+ const cls = 'w-3.5 h-3.5 shrink-0';
+ switch (tool) {
+ case 'brush':
+ return <Paintbrush className={cls} />;
+ case 'eraser':
+ return <Eraser className={cls} />;
+ case 'pipette':
+ return <Pipette className={cls} />;
+ case 'liquify':
+ return <LiquifyIcon className={cls} />;
+ case 'fill':
+ return <PaintBucket className={cls} />;
+ case 'select-rect':
+ return <BoxSelect className={cls} />;
+ case 'select-lasso':
+ return <Lasso className={cls} />;
+ case 'select-wand':
+ return <Wand2 className={cls} />;
+ case 'select-pen':
+ case 'select-eraser':
+ return <PenTool className={cls} />;
+ case 'transform':
+ return <Scaling className={cls} />;
+ case 'text':
+ return <Type className={cls} />;
+ case 'frame':
+ return <Frame className={cls} />;
+ case 'balloon':
+ return <MessageSquare className={cls} />;
+ case 'vector-edit':
+ return <Spline className={cls} />;
+ default:
+ return <Paintbrush className={cls} />;
+ }
+}
+
+export interface QuickAccessPanelProps {
+ handlers: WorkspaceCommandHandlers;
+ themePreset?: ThemePreset;
+}
+
+export const QuickAccessPanel: React.FC<QuickAccessPanelProps> = React.memo(({
+ handlers,
+ themePreset = 'modern',
+}) => {
+ const items = useWorkspaceStore((s) => s.quickAccessItems);
+ const viewMode = useWorkspaceStore((s) => s.quickAccessViewMode);
+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
+
+ const activeTool = useToolStore((s) => s.tool);
+ const primaryColor = useToolStore((s) => s.primaryColor);
+ const activePresetId = useToolStore((s) => s.activePresetId);
+ const activeBrushName = useToolStore((s) => s.brushSettings.brushName);
+
+ const [isEditing, setIsEditing] = useState(false);
+ const [addTab, setAddTab] = useState<'command' | 'tool' | 'brush'>('command');
+ const isVintage = themePreset === 'vintage-manga';
+
+ const handleActivateItem = (item: QuickAccessItem) => {
+ if (item.kind === 'command' && item.commandId) {
+ executeWorkspaceCommand(item.commandId, handlers);
+ return;
+ }
+ if (item.kind === 'tool' && item.toolId) {
+ toolStoreActions.selectTool(item.toolId);
+ if (item.toolId === 'transform') handlers.onTransform?.();
+ return;
+ }
+ if (item.kind === 'color' && item.color) {
+ toolStoreActions.setPrimaryColor(item.color, true);
+ return;
+ }
+ if (item.kind === 'brush' && item.brushPresetId) {
+ toolStoreActions.selectTool('brush');
+ saveActivePresetId(item.brushPresetId);
+ const effective = getEffectiveBrushSettings(item.brushPresetId);
+ toolStoreActions.updateBrushSettings({ ...effective, preset: item.brushPresetId });
+ }
+ };
+
+ const handleAddCurrentColor = () => {
+ workspaceStoreActions.addQuickAccessItem({
+ id: `qa-color-${Date.now().toString(36)}`,
+ kind: 'color',
+ label: primaryColor.toUpperCase(),
+ color: primaryColor,
+ });
+ };
+
+ const handleAddCurrentBrush = () => {
+ const label = activeBrushName || activePresetId || 'Brush';
+ workspaceStoreActions.addQuickAccessItem({
+ id: `qa-brush-${Date.now().toString(36)}`,
+ kind: 'brush',
+ label,
+ brushPresetId: activePresetId,
+ });
+ };
+
+ const handleAddCommand = (commandId: CommandActionId, label: string) => {
+ workspaceStoreActions.addQuickAccessItem({
+ id: `qa-cmd-${commandId}-${Date.now().toString(36)}`,
+ kind: 'command',
+ label,
+ commandId,
+ });
+ };
+
+ const handleAddTool = (toolId: ToolType, label: string) => {
+ workspaceStoreActions.addQuickAccessItem({
+ id: `qa-tool-${toolId}-${Date.now().toString(36)}`,
+ kind: 'tool',
+ label,
+ toolId,
+ });
+ };
+
+ return (
+ <div
+ data-testid="quick-access-panel"
+ data-theme-preset={themePreset}
+ className={`flex flex-col h-full min-h-0 select-none text-xs ${
+ isVintage ? 'bg-[#363638] text-[#e5e5e5]' : 'bg-[#202020] text-[#e5e5e5]'
+ }`}
+ >
+ {/* Toolbar: Grid/List + Edit Mode */}
+ <div
+ className={`h-7 px-1.5 flex items-center justify-between shrink-0 ${
+ isVintage
+ ? 'bg-[#2e2e31] border-b border-[#232325]'
+ : 'bg-[#1a1a1a] border-b border-white/[0.06]'
+ }`}
+ >
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.setQuickAccessViewMode('grid')}
+ title="Grid View"
+ className={`w-5 h-5 rounded flex items-center justify-center cursor-pointer ${
+ viewMode === 'grid'
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ <LayoutGrid className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.setQuickAccessViewMode('list')}
+ title="List View"
+ className={`w-5 h-5 rounded flex items-center justify-center cursor-pointer ${
+ viewMode === 'list'
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ <List className="w-3 h-3" />
+ </button>
+ </div>
+
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ onClick={handleAddCurrentColor}
+ title={`Pin Primary Color (${primaryColor})`}
+ className="h-5 px-1 rounded flex items-center gap-1 text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <span
+ className="w-2.5 h-2.5 rounded-xs border border-white/25"
+ style={{ backgroundColor: primaryColor }}
+ />
+ <Plus className="w-2.5 h-2.5" />
+ </button>
+
+ <button
+ type="button"
+ onClick={() => setIsEditing((v) => !v)}
+ title="Customize Quick Access"
+ className={`h-5 px-1.5 rounded flex items-center gap-1 text-[10px] transition-colors cursor-pointer ${
+ isEditing
+ ? 'bg-[var(--accent-subtle)] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ <SlidersHorizontal className="w-3 h-3" />
+ <span>{isEditing ? 'Done' : 'Edit'}</span>
+ </button>
+ </div>
+ </div>
+
+ {/* Main Items Area */}
+ <div className="flex-1 min-h-0 overflow-y-auto p-1.5">
+ {items.length === 0 ? (
+ <div className="p-3 text-center text-[11px] text-[#8a8a8a]">
+ No shortcuts. Click Edit to add tools, commands, brushes, or colors.
+ </div>
+ ) : viewMode === 'grid' && !isEditing ? (
+ <div className="grid grid-cols-[repeat(auto-fill,minmax(46px,1fr))] gap-1">
+ {items.map((item) => {
+ const disabled =
+ item.kind === 'command' && item.commandId
+ ? isCommandDisabled(item.commandId, handlers)
+ : false;
+ const active =
+ (item.kind === 'command' &&
+ item.commandId &&
+ isCommandActive(item.commandId, handlers, palettesHidden)) ||
+ (item.kind === 'tool' && item.toolId === activeTool) ||
+ (item.kind === 'brush' && item.brushPresetId === activePresetId && activeTool === 'brush') ||
+ (item.kind === 'color' && item.color?.toLowerCase() === primaryColor.toLowerCase());
+
+ return (
+ <button
+ key={item.id}
+ type="button"
+ disabled={disabled}
+ onClick={() => handleActivateItem(item)}
+ title={item.label}
+ className={`h-11 px-1 rounded flex flex-col items-center justify-center gap-1 transition-colors ${
+ disabled
+ ? 'opacity-30 cursor-not-allowed bg-[#161616] text-[#8a8a8a]'
+ : active
+ ? isVintage
+ ? 'bg-[#337bb5] text-white border border-[#4e95cf] cursor-pointer'
+ : 'bg-[var(--accent-subtle)] text-[var(--accent)] border border-[var(--accent-border)] cursor-pointer'
+ : isVintage
+ ? 'bg-[#2c2c2f] hover:bg-[#444448] text-[#d0d0d5] border border-[#232325] cursor-pointer'
+ : 'bg-[#161616] hover:bg-[#2c2c2c] text-[#cccccc] hover:text-white border border-transparent cursor-pointer'
+ }`}
+ >
+ {item.kind === 'command' && item.commandId && renderCommandIcon(item.commandId, palettesHidden)}
+ {item.kind === 'tool' && item.toolId && renderToolIcon(item.toolId)}
+ {item.kind === 'color' && (
+ <span
+ className="w-4 h-4 rounded-sm border border-white/25"
+ style={{ backgroundColor: item.color }}
+ />
+ )}
+ {item.kind === 'brush' && <Paintbrush className="w-3.5 h-3.5 shrink-0" />}
+ <span className="text-[9px] leading-tight truncate max-w-full">
+ {item.label}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="space-y-0.5">
+ {items.map((item, idx) => {
+ const disabled =
+ !isEditing && item.kind === 'command' && item.commandId
+ ? isCommandDisabled(item.commandId, handlers)
+ : false;
+ const active =
+ !isEditing &&
+ ((item.kind === 'command' &&
+ item.commandId &&
+ isCommandActive(item.commandId, handlers, palettesHidden)) ||
+ (item.kind === 'tool' && item.toolId === activeTool) ||
+ (item.kind === 'brush' && item.brushPresetId === activePresetId && activeTool === 'brush') ||
+ (item.kind === 'color' && item.color?.toLowerCase() === primaryColor.toLowerCase()));
+
+ return (
+ <div
+ key={item.id}
+ className={`flex items-center gap-1 rounded px-1.5 py-1 transition-colors ${
+ active
+ ? isVintage
+ ? 'bg-[#337bb5] text-white'
+ : 'bg-[var(--accent-subtle)] text-[var(--accent)]'
+ : isVintage
+ ? 'bg-[#2c2c2f] hover:bg-[#444448] text-[#d0d0d5]'
+ : 'bg-[#161616] hover:bg-[#2c2c2c] text-[#cccccc]'
+ }`}
+ >
+ <button
+ type="button"
+ disabled={disabled}
+ onClick={() => !isEditing && handleActivateItem(item)}
+ className={`flex-1 min-w-0 flex items-center gap-2 text-left text-[11px] ${
+ disabled ? 'opacity-30 cursor-not-allowed' : 'cursor-pointer'
+ }`}
+ >
+ {item.kind === 'command' && item.commandId && renderCommandIcon(item.commandId, palettesHidden)}
+ {item.kind === 'tool' && item.toolId && renderToolIcon(item.toolId)}
+ {item.kind === 'color' && (
+ <span
+ className="w-3.5 h-3.5 rounded-xs border border-white/25 shrink-0"
+ style={{ backgroundColor: item.color }}
+ />
+ )}
+ {item.kind === 'brush' && <Paintbrush className="w-3.5 h-3.5 shrink-0" />}
+ <span className="truncate">{item.label}</span>
+ </button>
+
+ {isEditing && (
+ <div className="flex items-center gap-0.5 shrink-0">
+ <button
+ type="button"
+ disabled={idx === 0}
+ onClick={() => workspaceStoreActions.moveQuickAccessItem(item.id, -1)}
+ title="Move Up"
+ className="p-0.5 text-[#8a8a8a] hover:text-white disabled:opacity-25 cursor-pointer"
+ >
+ <ChevronUp className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ disabled={idx === items.length - 1}
+ onClick={() => workspaceStoreActions.moveQuickAccessItem(item.id, 1)}
+ title="Move Down"
+ className="p-0.5 text-[#8a8a8a] hover:text-white disabled:opacity-25 cursor-pointer"
+ >
+ <ChevronDown className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.removeQuickAccessItem(item.id)}
+ title="Remove"
+ className="p-0.5 text-[#8a8a8a] hover:text-rose-400 cursor-pointer"
+ >
+ <Trash2 className="w-3 h-3" />
+ </button>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ {/* Add-Item Drawer when Editing */}
+ {isEditing && (
+ <div className="shrink-0 border-t border-white/[0.08] bg-[#161616] p-1.5 space-y-1.5">
+ <div className="flex items-center justify-between gap-1">
+ <div className="flex items-center gap-0.5">
+ {(['command', 'tool', 'brush'] as const).map((tab) => (
+ <button
+ key={tab}
+ type="button"
+ onClick={() => setAddTab(tab)}
+ className={`px-1.5 py-0.5 rounded text-[10px] capitalize cursor-pointer ${
+ addTab === tab
+ ? 'bg-[#2c2c2c] text-white font-medium'
+ : 'text-[#8a8a8a] hover:text-white'
+ }`}
+ >
+ {tab}s
+ </button>
+ ))}
+ </div>
+ <button
+ type="button"
+ onClick={() => workspaceStoreActions.resetQuickAccessItems()}
+ title="Reset Quick Access to defaults"
+ className="p-1 rounded text-[#8a8a8a] hover:text-amber-300 hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ <RotateCcw className="w-3 h-3" />
+ </button>
+ </div>
+
+ <div className="flex items-center gap-1">
+ <button
+ type="button"
+ onClick={handleAddCurrentColor}
+ className="flex-1 py-1 px-1.5 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#cccccc] flex items-center justify-center gap-1 cursor-pointer"
+ >
+ <Palette className="w-3 h-3" />
+ <span>+ Color</span>
+ </button>
+ <button
+ type="button"
+ onClick={handleAddCurrentBrush}
+ className="flex-1 py-1 px-1.5 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#cccccc] flex items-center justify-center gap-1 cursor-pointer"
+ >
+ <Paintbrush className="w-3 h-3" />
+ <span>+ Brush</span>
+ </button>
+ </div>
+
+ <div className="max-h-28 overflow-y-auto space-y-0.5">
+ {addTab === 'command' &&
+ COMMAND_CATALOG.map((cmd) => (
+ <button
+ key={cmd.id}
+ type="button"
+ onClick={() => handleAddCommand(cmd.id, cmd.label)}
+ className="w-full flex items-center justify-between px-1.5 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#cccccc] hover:text-white cursor-pointer"
+ >
+ <span className="flex items-center gap-1.5 truncate">
+ {renderCommandIcon(cmd.id)}
+ <span className="truncate">{cmd.label}</span>
+ </span>
+ <Plus className="w-3 h-3 text-[#8a8a8a] shrink-0" />
+ </button>
+ ))}
+
+ {addTab === 'tool' &&
+ QUICK_TOOL_CATALOG.map((t) => (
+ <button
+ key={t.id}
+ type="button"
+ onClick={() => handleAddTool(t.id, t.label)}
+ className="w-full flex items-center justify-between px-1.5 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#cccccc] hover:text-white cursor-pointer"
+ >
+ <span className="flex items-center gap-1.5 truncate">
+ {renderToolIcon(t.id)}
+ <span className="truncate">{t.label}</span>
+ </span>
+ <Plus className="w-3 h-3 text-[#8a8a8a] shrink-0" />
+ </button>
+ ))}
+
+ {addTab === 'brush' &&
+ BUILTIN_BRUSHES.map((b) => (
+ <button
+ key={b.id}
+ type="button"
+ onClick={() =>
+ workspaceStoreActions.addQuickAccessItem({
+ id: `qa-brush-${b.id}-${Date.now().toString(36)}`,
+ kind: 'brush',
+ label: b.name,
+ brushPresetId: b.id,
+ })
+ }
+ className="w-full flex items-center justify-between px-1.5 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#cccccc] hover:text-white cursor-pointer"
+ >
+ <span className="flex items-center gap-1.5 truncate">
+ <Paintbrush className="w-3 h-3 shrink-0" />
+ <span className="truncate">{b.name}</span>
+ </span>
+ <Plus className="w-3 h-3 text-[#8a8a8a] shrink-0" />
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+ </div>
+ );
+});
+
+QuickAccessPanel.displayName = 'QuickAccessPanel';
diff --git a/src/components/RightSidebar.tsx b/src/components/RightSidebar.tsx
index cfe6cce..dff00a1 100644
--- a/src/components/RightSidebar.tsx
+++ b/src/components/RightSidebar.tsx
@@ -30,14 +30,80 @@ import {
} from '../types/editor';
import { BLEND_MODES } from '../utils/canvasUtils';
import { ColorPanel } from './ColorPanel';
+import { useToolStore, toolStoreActions } from '../stores';
+
+interface RightSidebarColorSectionProps {
+ colorMode: CanvasColorMode;
+ containerWidth: number;
+ fullHeight?: boolean;
+ primaryColor?: string;
+ secondaryColor?: string;
+ onPrimaryColorChange?: (color: string, commit?: boolean) => void;
+ onSecondaryColorChange?: (color: string, commit?: boolean) => void;
+ onSwapColors?: () => void;
+ recentColors?: string[];
+ currentTool?: ToolType;
+ onSelectTool?: (tool: ToolType) => void;
+}
-interface RightSidebarProps {
- primaryColor: string;
- secondaryColor: string;
- onPrimaryColorChange: (color: string, commit?: boolean) => void;
- onSecondaryColorChange: (color: string, commit?: boolean) => void;
- onSwapColors: () => void;
- recentColors: string[];
+export const RightSidebarColorSection: React.FC<RightSidebarColorSectionProps> = React.memo(
+ ({
+ colorMode,
+ containerWidth,
+ fullHeight = false,
+ primaryColor: primaryProp,
+ secondaryColor: secondaryProp,
+ onPrimaryColorChange,
+ onSecondaryColorChange,
+ onSwapColors,
+ recentColors: recentProp,
+ currentTool: toolProp,
+ onSelectTool,
+ }) => {
+ const storePrimary = useToolStore((s) => s.primaryColor);
+ const storeSecondary = useToolStore((s) => s.secondaryColor);
+ const storeRecent = useToolStore((s) => s.recentColors);
+ const storeTool = useToolStore((s) => s.tool);
+
+ return (
+ <section
+ className={
+ fullHeight
+ ? 'h-full w-full overflow-hidden bg-[#202020]'
+ : 'h-[28%] max-h-[30%] shrink-0 overflow-hidden bg-[#202020]'
+ }
+ >
+ <ColorPanel
+ primaryColor={primaryProp ?? storePrimary}
+ secondaryColor={secondaryProp ?? storeSecondary}
+ onPrimaryColorChange={
+ onPrimaryColorChange ??
+ ((color, commit) => toolStoreActions.setPrimaryColor(color, commit, colorMode))
+ }
+ onSecondaryColorChange={
+ onSecondaryColorChange ??
+ ((color, commit) => toolStoreActions.setSecondaryColor(color, commit, colorMode))
+ }
+ onSwapColors={onSwapColors ?? (() => toolStoreActions.swapColors(colorMode))}
+ colorMode={colorMode}
+ currentTool={toolProp ?? storeTool}
+ onSelectTool={onSelectTool ?? ((t) => toolStoreActions.selectTool(t))}
+ recentColors={recentProp ?? storeRecent}
+ containerWidth={containerWidth}
+ />
+ </section>
+ );
+ }
+);
+RightSidebarColorSection.displayName = 'RightSidebarColorSection';
+
+export interface RightSidebarProps {
+ primaryColor?: string;
+ secondaryColor?: string;
+ onPrimaryColorChange?: (color: string, commit?: boolean) => void;
+ onSecondaryColorChange?: (color: string, commit?: boolean) => void;
+ onSwapColors?: () => void;
+ recentColors?: string[];
historyList: HistoryItemMeta[];
historyIndex: number;
onJumpToHistory: (index: number) => void;
@@ -101,6 +167,8 @@ interface RightSidebarProps {
hasOpenDocument?: boolean;
onNewCanvas?: () => void;
onOpenFile?: () => void;
+ hideColorPanel?: boolean;
+ dockedMode?: 'full' | 'layers' | 'history';
}
const ClipToLayerIcon: React.FC<{ className?: string }> = ({ className = 'w-3 h-3' }) => (
@@ -127,7 +195,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
onSwapColors,
recentColors,
colorMode = 'color',
- currentTool = 'brush',
+ currentTool,
onSelectTool,
historyList,
historyIndex,
@@ -184,8 +252,15 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
hasOpenDocument = true,
onNewCanvas,
onOpenFile,
+ hideColorPanel = false,
+ dockedMode = 'full',
}) => {
- const [bottomTab, setBottomTab] = useState<'layers' | 'history'>('layers');
+ const [bottomTab, setBottomTab] = useState<'layers' | 'history'>(
+ dockedMode === 'history' ? 'history' : 'layers'
+ );
+ const effectiveTab: 'layers' | 'history' =
+ dockedMode === 'layers' ? 'layers' : dockedMode === 'history' ? 'history' : bottomTab;
+ const isDockedSingle = dockedMode !== 'full';
const [editingLayerId, setEditingLayerId] = useState<string | null>(null);
const [editingName, setEditingName] = useState<string>('');
const [draggedLayerId, setDraggedLayerId] = useState<string | null>(null);
@@ -412,67 +487,79 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
return (
<aside
- style={{ width }}
- className="relative bg-[#161616] flex flex-col gap-px text-[#e5e5e5] text-xs select-none z-10 shrink-0 overflow-hidden"
+ style={isDockedSingle ? undefined : { width }}
+ className={
+ isDockedSingle
+ ? 'relative w-full h-full bg-[#202020] flex flex-col text-[#e5e5e5] text-xs select-none overflow-hidden min-h-0'
+ : 'relative bg-[#161616] flex flex-col gap-px text-[#e5e5e5] text-xs select-none z-10 shrink-0 overflow-hidden'
+ }
>
{/* Left Resize Seam */}
- <div
- onMouseDown={(e) => {
- e.preventDefault();
- setIsResizing(true);
- startXRef.current = e.clientX;
- startWidthRef.current = width;
- }}
- title="Resize sidebar"
- className="absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-[var(--accent)]/40 transition-colors z-30"
- />
-
- {/* 1. Compact Color Wheel (<= 30% of sidebar height) */}
- <section className="h-[28%] max-h-[30%] shrink-0 overflow-hidden bg-[#202020]">
- <ColorPanel
+ {!isDockedSingle && (
+ <div
+ onMouseDown={(e) => {
+ e.preventDefault();
+ setIsResizing(true);
+ startXRef.current = e.clientX;
+ startWidthRef.current = width;
+ }}
+ title="Resize sidebar"
+ className="absolute left-0 top-0 bottom-0 w-1 cursor-col-resize hover:bg-[var(--accent)]/40 transition-colors z-30"
+ />
+ )}
+
+ {/* 1. Compact Color Wheel (<= 30% of sidebar height) - isolated store subscriber */}
+ {!hideColorPanel && !isDockedSingle && (
+ <RightSidebarColorSection
+ colorMode={colorMode}
+ containerWidth={width}
primaryColor={primaryColor}
secondaryColor={secondaryColor}
onPrimaryColorChange={onPrimaryColorChange}
onSecondaryColorChange={onSecondaryColorChange}
onSwapColors={onSwapColors}
- colorMode={colorMode}
+ recentColors={recentColors}
currentTool={currentTool}
onSelectTool={onSelectTool}
- recentColors={recentColors}
- containerWidth={width}
/>
- </section>
+ )}
- {/* 2. Spacious Layers Panel (>= 70% of sidebar height) */}
- <section className="flex-1 min-h-[70%] flex flex-col bg-[#202020] overflow-hidden">
+ {/* 2. Spacious Layers / History Panel */}
+ <section className={`flex-1 ${isDockedSingle ? 'min-h-0' : 'min-h-[70%]'} flex flex-col bg-[#202020] overflow-hidden`}>
{/* Header Bar: Layers / History Switch + Quick Layer Actions */}
<div className="h-7 px-1.5 flex items-center justify-between shrink-0">
- <div className="flex items-center gap-0.5">
- <button
- type="button"
- onClick={() => setBottomTab('layers')}
- className={`px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${
- bottomTab === 'layers'
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- Layers
- </button>
- <button
- type="button"
- onClick={() => setBottomTab('history')}
- className={`px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${
- bottomTab === 'history'
- ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
- : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
- }`}
- >
- History
- </button>
- </div>
+ {isDockedSingle ? (
+ <span className="text-[10px] uppercase tracking-wider text-[#8a8a8a] font-medium px-1">
+ {effectiveTab === 'layers' ? `${layers.length} Layers` : `${historyList.length} Steps`}
+ </span>
+ ) : (
+ <div className="flex items-center gap-0.5">
+ <button
+ type="button"
+ onClick={() => setBottomTab('layers')}
+ className={`px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${
+ effectiveTab === 'layers'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Layers
+ </button>
+ <button
+ type="button"
+ onClick={() => setBottomTab('history')}
+ className={`px-1.5 py-0.5 rounded text-[11px] transition-colors cursor-pointer ${
+ effectiveTab === 'history'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ History
+ </button>
+ </div>
+ )}
- {bottomTab === 'layers' && hasOpenDocument && (
+ {effectiveTab === 'layers' && hasOpenDocument && (
<div className="flex items-center gap-0.5">
<button
type="button"
@@ -513,7 +600,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</div>
)}
- {bottomTab === 'history' && (
+ {effectiveTab === 'history' && (
<div className="flex items-center gap-0.5">
<button
type="button"
@@ -546,7 +633,7 @@ export const RightSidebar: React.FC<RightSidebarProps> = React.memo(({
</div>
{/* Layers Content */}
- {bottomTab === 'layers' ? (
+ {effectiveTab === 'layers' ? (
<div className="flex-1 flex flex-col overflow-hidden min-h-0">
{!hasOpenDocument ? (
<div className="flex-1 flex flex-col items-center justify-center p-4 text-center text-[#8a8a8a]">
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 624f44d..03fe330 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -175,6 +175,41 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
<div className="flex-1 p-5 overflow-y-auto bg-[#202020] space-y-5">
{activeTab === 'appearance' && (
<>
+ {/* Visual Theme Preset */}
+ <section className="space-y-2.5">
+ <div>
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Interface Theme</h3>
+ <p className="text-[11px] text-[#8a8a8a]">
+ Switch between Modern dark chrome and Vintage Manga Studio beveled UI
+ </p>
+ </div>
+ <div className="grid grid-cols-2 gap-1.5">
+ {(
+ [
+ { id: 'modern', label: 'Modern Studio', desc: 'Flat dark + accent' },
+ { id: 'vintage-manga', label: 'Vintage Manga', desc: 'Classic CSP bevel' },
+ ] as const
+ ).map((opt) => {
+ const isSelected = localSettings.themePreset === opt.id;
+ return (
+ <button
+ key={opt.id}
+ type="button"
+ onClick={() => handleChange('themePreset', opt.id)}
+ className={`flex flex-col items-start px-3 py-2 rounded text-left transition-colors cursor-pointer ${
+ isSelected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ <span className="text-xs font-medium">{opt.label}</span>
+ <span className="text-[10px] text-[#8a8a8a]">{opt.desc}</span>
+ </button>
+ );
+ })}
+ </div>
+ </section>
+
{/* Accent Color Customization */}
<section className="space-y-2.5">
<div className="flex items-center justify-between">
diff --git a/src/components/StatusBar.tsx b/src/components/StatusBar.tsx
index e7f8df9..b3ccaef 100644
--- a/src/components/StatusBar.tsx
+++ b/src/components/StatusBar.tsx
@@ -76,7 +76,11 @@ export const StatusBar: React.FC<StatusBarProps> = React.memo(({
if (_themePreset === 'modern') {
return (
- <footer className="h-7 bg-[#0f1015] border-t border-white/[0.08] px-3 text-white/70 flex items-center justify-between text-xs select-none z-20 shrink-0">
+ <footer
+ data-testid="status-bar"
+ data-theme-preset="modern"
+ className="h-7 bg-[#1a1a1a] border-t border-white/[0.06] px-3 text-white/70 flex items-center justify-between text-xs select-none z-20 shrink-0"
+ >
{/* Tool & Smoothing Status */}
<div className="flex items-center space-x-2">
<div className="bg-white/[0.04] border border-white/[0.06] px-2 py-0.5 rounded-md flex items-center space-x-2">
@@ -176,7 +180,11 @@ export const StatusBar: React.FC<StatusBarProps> = React.memo(({
}
return (
- <footer className="h-7 bg-gradient-to-b from-[#464649] to-[#363638] border-t border-[#232325] px-2.5 text-[#b0b0b6] flex items-center justify-between text-xs select-none z-20 shrink-0 transition-colors">
+ <footer
+ data-testid="status-bar"
+ data-theme-preset="vintage-manga"
+ className="h-7 bg-gradient-to-b from-[#464649] to-[#363638] border-t border-[#232325] px-2.5 text-[#b0b0b6] flex items-center justify-between text-xs select-none z-20 shrink-0 transition-colors"
+ >
{/* Tool & Smoothing Status */}
<div className="flex items-center space-x-2">
<div className="bg-[#2b2b2e] border border-[#202022] shadow-[inset_1px_1px_2px_rgba(0,0,0,0.5),0_1px_0_rgba(255,255,255,0.08)] px-2 py-0.5 rounded-[2px] flex items-center space-x-2">
diff --git a/src/components/SubToolList.tsx b/src/components/SubToolList.tsx
new file mode 100644
index 0000000..0a94bab
--- /dev/null
+++ b/src/components/SubToolList.tsx
@@ -0,0 +1,293 @@
+import React, { useState, useRef } from 'react';
+import {
+ Paintbrush,
+ Pencil,
+ Plus,
+ Trash2,
+ Loader2,
+ FolderDown,
+ Palette,
+ Square,
+ Sparkles,
+} from 'lucide-react';
+import { BrushPresetId, CspBrush } from '../types/editor';
+import { parseSutFile } from '../utils/sutParser';
+import {
+ saveCustomBrush,
+ deleteCustomBrush,
+ prepareBrushSettingsForCsp,
+} from '../utils/brushStorage';
+import { BUILTIN_BRUSHES, BrushCategory } from '../utils/presetBrushes';
+import {
+ getEffectiveBrushSettings,
+ getSavedBrushSettings,
+ saveActivePresetId,
+} from '../utils/brushPresetManager';
+import { useToolStore, toolStoreActions } from '../stores';
+
+export interface SubToolListProps {
+ customBrushes: CspBrush[];
+ setCustomBrushes: React.Dispatch<React.SetStateAction<CspBrush[]>>;
+}
+
+export const SubToolList: React.FC<SubToolListProps> = React.memo(
+ ({ customBrushes, setCustomBrushes }) => {
+ const currentTool = useToolStore((s) => s.tool);
+ const activePreset = useToolStore((s) => s.brushSettings.preset);
+
+ const [isImportingSut, setIsImportingSut] = useState(false);
+ const [isDraggingFileOver, setIsDraggingFileOver] = useState(false);
+ const [selectedCategory, setSelectedCategory] = useState<'all' | BrushCategory | 'csp'>('all');
+ const sutInputRef = useRef<HTMLInputElement>(null);
+
+ const handleSelectBrushPreset = (presetId: BrushPresetId) => {
+ toolStoreActions.selectTool('brush');
+ saveActivePresetId(presetId);
+ const effective = getEffectiveBrushSettings(presetId, customBrushes);
+ toolStoreActions.updateBrushSettings({
+ customTipDataUrl: undefined,
+ customTipImage: undefined,
+ customTipAngle: 0,
+ customTipAngleDynamics: 'none',
+ flipH: 'none',
+ flipV: 'none',
+ isRibbon: false,
+ colorMixing: false,
+ wetEdge: 0,
+ grain: 0,
+ spray: undefined,
+ taper: undefined,
+ ...effective,
+ preset: presetId,
+ });
+ };
+
+ const handleSelectCustomBrush = async (brush: CspBrush) => {
+ toolStoreActions.selectTool('brush');
+ saveActivePresetId(brush.id);
+ const prepared = await prepareBrushSettingsForCsp(brush);
+ const saved = getSavedBrushSettings(brush.id);
+ toolStoreActions.updateBrushSettings({
+ ...prepared,
+ ...saved,
+ preset: brush.id,
+ });
+ };
+
+ const handleImportSut = async (file: File) => {
+ setIsImportingSut(true);
+ try {
+ const buffer = await file.arrayBuffer();
+ const parsedBrush = await parseSutFile(buffer, file.name);
+ const existing = customBrushes.filter(
+ (b) => b.name.toLowerCase() === parsedBrush.name.toLowerCase() || b.id === parsedBrush.id
+ );
+ for (const old of existing) {
+ await deleteCustomBrush(old.id).catch(() => {});
+ }
+ await saveCustomBrush(parsedBrush);
+ setCustomBrushes((prev) => [
+ parsedBrush,
+ ...prev.filter(
+ (b) =>
+ b.name.toLowerCase() !== parsedBrush.name.toLowerCase() && b.id !== parsedBrush.id
+ ),
+ ]);
+ await handleSelectCustomBrush(parsedBrush);
+ } catch (err: unknown) {
+ const msg =
+ err instanceof Error ? err.message : 'Failed to import Clip Studio Paint brush file.';
+ alert(msg);
+ } finally {
+ setIsImportingSut(false);
+ }
+ };
+
+ const handleDeleteCustomBrush = async (e: React.MouseEvent, brushId: string) => {
+ e.stopPropagation();
+ if (window.confirm('Delete this imported brush?')) {
+ await deleteCustomBrush(brushId);
+ setCustomBrushes((prev) => prev.filter((b) => b.id !== brushId));
+ if (activePreset === brushId) {
+ handleSelectBrushPreset('pencil-2b');
+ }
+ }
+ };
+
+ const visibleBuiltinBrushes = BUILTIN_BRUSHES.filter((b) => {
+ if (selectedCategory === 'all') return true;
+ if (selectedCategory === 'csp') return false;
+ return b.category === selectedCategory;
+ });
+
+ const showCspBrushes = selectedCategory === 'all' || selectedCategory === 'csp';
+
+ return (
+ <>
+ {/* Category Filter Strip + Import .sut */}
+ <div className="px-1.5 py-1.5 flex items-center gap-1 shrink-0">
+ <select
+ value={selectedCategory}
+ onChange={(e) =>
+ setSelectedCategory(e.target.value as 'all' | BrushCategory | 'csp')
+ }
+ aria-label="Brush Category"
+ className="flex-1 min-w-0 h-5 bg-[#161616] text-[#e5e5e5] text-[11px] px-1.5 rounded cursor-pointer"
+ >
+ <option value="all" className="bg-[#202020]">
+ All Brushes
+ </option>
+ <option value="pencil-line" className="bg-[#202020]">
+ Pencil &amp; Ink
+ </option>
+ <option value="color-paint" className="bg-[#202020]">
+ Color &amp; Paint
+ </option>
+ <option value="csp" className="bg-[#202020]">
+ CSP Imported
+ </option>
+ </select>
+
+ <button
+ type="button"
+ onClick={() => sutInputRef.current?.click()}
+ title="Import CSP Brush (.sut)"
+ className="w-5 h-5 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] shrink-0 cursor-pointer"
+ >
+ <Plus className="w-3 h-3" />
+ </button>
+ </div>
+
+ <input
+ type="file"
+ ref={sutInputRef}
+ accept=".sut"
+ className="hidden"
+ onChange={(e) => {
+ const file = e.target.files?.[0];
+ if (file) handleImportSut(file);
+ e.target.value = '';
+ }}
+ />
+
+ {/* Compact High-Density Sub-Tool List */}
+ <div
+ onDragOver={(e) => {
+ if (e.dataTransfer.types.includes('Files')) {
+ e.preventDefault();
+ setIsDraggingFileOver(true);
+ }
+ }}
+ onDragLeave={() => setIsDraggingFileOver(false)}
+ onDrop={(e) => {
+ e.preventDefault();
+ setIsDraggingFileOver(false);
+ const files = Array.from(e.dataTransfer.files).filter((f) =>
+ f.name.toLowerCase().endsWith('.sut')
+ );
+ for (const f of files) handleImportSut(f);
+ }}
+ className="flex-1 overflow-y-auto px-1.5 py-0.5 space-y-0.5 relative min-h-[84px]"
+ >
+ {isDraggingFileOver && (
+ <div className="absolute inset-1 bg-[#161616]/95 rounded flex flex-col items-center justify-center p-2 text-center z-30 pointer-events-none">
+ <FolderDown className="w-4 h-4 text-[var(--accent)] mb-1" />
+ <span className="text-[10px] text-[#e5e5e5]">Drop .sut</span>
+ </div>
+ )}
+
+ {isImportingSut && (
+ <div className="px-2 py-1 rounded bg-[#2c2c2c] text-[10px] text-[#e5e5e5] flex items-center gap-1.5">
+ <Loader2 className="w-3 h-3 animate-spin" />
+ <span className="truncate">Importing...</span>
+ </div>
+ )}
+
+ {visibleBuiltinBrushes.map((item) => {
+ const isSelected =
+ currentTool === 'brush' &&
+ (activePreset === item.id || (!activePreset && item.id === 'pencil-2b'));
+
+ return (
+ <button
+ key={item.id}
+ type="button"
+ onClick={() => handleSelectBrushPreset(item.id)}
+ title={`${item.name} - ${item.desc}`}
+ className={`w-full flex items-center gap-1.5 px-2 py-1 rounded text-left transition-colors cursor-pointer ${
+ isSelected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {item.icon === 'pencil' ? (
+ <Pencil className="w-3 h-3 shrink-0 opacity-80" />
+ ) : item.icon === 'palette' ? (
+ <Palette className="w-3 h-3 shrink-0 opacity-80" />
+ ) : item.icon === 'square' ? (
+ <Square className="w-3 h-3 shrink-0 opacity-80" />
+ ) : (
+ <Paintbrush className="w-3 h-3 shrink-0 opacity-80" />
+ )}
+ <span className="text-[11px] truncate leading-tight flex-1">{item.name}</span>
+ </button>
+ );
+ })}
+
+ {showCspBrushes &&
+ customBrushes.map((brush) => {
+ const isSelected = currentTool === 'brush' && activePreset === brush.id;
+ return (
+ <div
+ key={brush.id}
+ onClick={() => handleSelectCustomBrush(brush)}
+ title={brush.name}
+ className={`group flex items-center justify-between gap-1 px-2 py-1 rounded cursor-pointer transition-colors ${
+ isSelected
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ <div className="flex items-center gap-1.5 min-w-0">
+ {brush.tipDataUrl ? (
+ <img
+ src={brush.tipDataUrl}
+ alt=""
+ className="w-3 h-3 object-contain shrink-0 brightness-125"
+ />
+ ) : (
+ <Sparkles className="w-3 h-3 shrink-0 opacity-80" />
+ )}
+ <span className="text-[11px] truncate leading-tight">{brush.name}</span>
+ </div>
+ <button
+ type="button"
+ onClick={(e) => handleDeleteCustomBrush(e, brush.id)}
+ title="Delete brush"
+ className="opacity-0 group-hover:opacity-100 text-[#8a8a8a] hover:text-red-400 shrink-0 cursor-pointer"
+ >
+ <Trash2 className="w-2.5 h-2.5" />
+ </button>
+ </div>
+ );
+ })}
+
+ {selectedCategory === 'csp' && customBrushes.length === 0 && (
+ <div className="py-4 px-2 text-center space-y-2">
+ <p className="text-[10px] text-[#8a8a8a]">Drop .sut brush file</p>
+ <button
+ type="button"
+ onClick={() => sutInputRef.current?.click()}
+ className="px-2 py-1 rounded bg-[#2c2c2c] text-[10px] text-[#e5e5e5] cursor-pointer"
+ >
+ Import .sut
+ </button>
+ </div>
+ )}
+ </div>
+ </>
+ );
+ }
+);
+
+SubToolList.displayName = 'SubToolList';
diff --git a/src/components/ToolPropertyInspector.tsx b/src/components/ToolPropertyInspector.tsx
new file mode 100644
index 0000000..d64ab12
--- /dev/null
+++ b/src/components/ToolPropertyInspector.tsx
@@ -0,0 +1,1546 @@
+import React, { useState, useRef, useEffect } from 'react';
+import {
+ ChevronDown,
+ ChevronRight,
+ Scaling,
+ Maximize2,
+ Minimize2,
+ RotateCcw,
+ Feather,
+} from 'lucide-react';
+import {
+ BrushSettings,
+ BrushPresetId,
+ CspBrush,
+ BrushDynamics,
+ DEFAULT_BRUSH_DYNAMICS,
+ LiquifyMode,
+ CspAngleDynamicsMode,
+ CspBlendTipsMode,
+ CspPaperTextureMode,
+ CspTipFlipMode,
+ CspTaperSettings,
+ CspSpraySettings,
+} from '../types/editor';
+import { saveCustomBrushDebounced } from '../utils/brushStorage';
+import { resolveBrushTipImage } from '../utils/brushOutline';
+import { BUILTIN_BRUSHES } from '../utils/presetBrushes';
+import { resetBrushSettingsToDefault, ERASER_PRESET_ID } from '../utils/brushPresetManager';
+import { renderBrushStrokePreview } from '../utils/brushPreview';
+import { CSP_PRESSURE_CURVE_PRESETS } from '../engine/CspBrushEngine';
+import { useToolStore, toolStoreActions, useUiStore, uiStoreActions } from '../stores';
+
+interface CompactSliderProps {
+ label: string;
+ valueLabel: string;
+ min: number;
+ max: number;
+ step?: number;
+ value: number;
+ onChange: (val: number) => void;
+}
+
+const CompactSlider: React.FC<CompactSliderProps> = ({
+ label,
+ valueLabel,
+ min,
+ max,
+ step = 1,
+ value,
+ onChange,
+}) => (
+ <div className="space-y-1">
+ <div className="flex items-center justify-between text-[11px]">
+ <span className="text-[#8a8a8a] truncate">{label}</span>
+ <span className="font-mono text-[10px] text-[#e5e5e5] ml-1 shrink-0">{valueLabel}</span>
+ </div>
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={step}
+ value={value}
+ onChange={(e) => onChange(Number(e.target.value))}
+ className="w-full"
+ />
+ </div>
+);
+
+const LIQUIFY_MODES: Array<{ id: LiquifyMode; label: string }> = [
+ { id: 'push', label: 'Push' },
+ { id: 'expand', label: 'Expand' },
+ { id: 'pinch', label: 'Pinch' },
+ { id: 'push-left', label: 'Push Left' },
+ { id: 'push-right', label: 'Push Right' },
+ { id: 'twirl-cw', label: 'Twirl CW' },
+ { id: 'twirl-ccw', label: 'Twirl CCW' },
+ { id: 'reconstruct', label: 'Reconstruct' },
+];
+
+type InspectorAccordionId = 'ink' | 'tip' | 'stroke' | 'mixing' | 'texture' | 'dynamics';
+
+const DEFAULT_TAPER: CspTaperSettings = {
+ useIn: false,
+ inLength: 24,
+ inRatio: 0.9,
+ useOut: false,
+ outLength: 32,
+ outRatio: 0.9,
+ startingSharpness: 0.85,
+ endingSharpness: 0.85,
+ affectSize: true,
+};
+
+const DEFAULT_SPRAY: CspSpraySettings = {
+ enabled: false,
+ size: 4,
+ density: 12,
+ bias: 0.5,
+};
+
+export interface ToolPropertyInspectorProps {
+ width: number;
+ customBrushes: CspBrush[];
+ setCustomBrushes: React.Dispatch<React.SetStateAction<CspBrush[]>>;
+ onDeselect?: () => void;
+ onTransformSelection?: () => void;
+ onExpandSelection?: (pixels: number) => void;
+ onContractSelection?: (pixels: number) => void;
+ onFeatherSelection?: (radius: number) => void;
+ onInvertSelection?: () => void;
+}
+
+export const ToolPropertyInspector: React.FC<ToolPropertyInspectorProps> = React.memo(
+ ({
+ width,
+ customBrushes,
+ setCustomBrushes,
+ onDeselect,
+ onTransformSelection,
+ onExpandSelection,
+ onContractSelection,
+ onFeatherSelection,
+ onInvertSelection,
+ }) => {
+ const currentTool = useToolStore((s) => s.tool);
+ const brushSettings = useToolStore((s) => s.brushSettings);
+ const fillSettings = useToolStore((s) => s.fillSettings);
+ const textSettings = useToolStore((s) => s.textSettings);
+ const frameSettings = useToolStore((s) => s.frameSettings);
+ const liquifySettings = useToolStore((s) => s.liquifySettings);
+ const balloonSettings = useToolStore((s) => s.balloonSettings);
+ const vectorEditSettings = useToolStore((s) => s.vectorEditSettings);
+ const wandSettings = useToolStore((s) => s.wandSettings);
+ const isHidden = useUiStore((s) => s.isLeftPanelHidden);
+
+ const [openAccordion, setOpenAccordion] = useState<InspectorAccordionId | null>(null);
+ const previewCanvasRef = useRef<HTMLCanvasElement>(null);
+
+ const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
+
+ useEffect(() => {
+ if (isHidden || !isBrushOrEraser) return;
+ const canvas = previewCanvasRef.current;
+ if (!canvas) return;
+ const cssWidth = Math.max(96, width - 16);
+ const cssHeight = 32;
+ const rafId = requestAnimationFrame(() => {
+ const resolvedTip = resolveBrushTipImage(brushSettings);
+ renderBrushStrokePreview(
+ canvas,
+ cssWidth,
+ cssHeight,
+ {
+ preset: brushSettings.preset,
+ size: brushSettings.size,
+ flow: brushSettings.flow,
+ opacity: brushSettings.opacity,
+ grain: brushSettings.grain,
+ hardness: brushSettings.hardness,
+ spacing: brushSettings.spacing,
+ minSizeFactor: brushSettings.minSizeFactor,
+ usePressure: brushSettings.usePressure,
+ color: currentTool === 'eraser' ? '#e5e5e5' : '#ececec',
+ backgroundColor: '#161616',
+ tool: currentTool === 'eraser' ? 'eraser' : 'brush',
+ customTipImage: resolvedTip,
+ customTipAngle: brushSettings.customTipAngle,
+ thickness: brushSettings.thickness,
+ thicknessVertical: brushSettings.thicknessVertical,
+ flipH: brushSettings.flipH,
+ flipV: brushSettings.flipV,
+ blendTipsMode: brushSettings.blendTipsMode,
+ adjustDensityByGap: brushSettings.adjustDensityByGap,
+ antiAlias: brushSettings.antiAlias,
+ pressureCurve: brushSettings.pressureCurve,
+ spray: brushSettings.spray,
+ colorMixing: brushSettings.colorMixing,
+ amountOfPaint: brushSettings.amountOfPaint,
+ densityOfPaint: brushSettings.densityOfPaint,
+ colorStretch: brushSettings.colorStretch,
+ wetEdge: brushSettings.wetEdge,
+ },
+ true
+ );
+ });
+ return () => cancelAnimationFrame(rafId);
+ }, [isHidden, isBrushOrEraser, width, currentTool, brushSettings]);
+
+ const activePreset: BrushPresetId = brushSettings.preset || 'pencil-2b';
+ const activeBuiltinBrush = BUILTIN_BRUSHES.find((b) => b.id === activePreset);
+ const isCustomBrushActive =
+ currentTool === 'brush' &&
+ (activePreset.startsWith('csp-') ||
+ (Boolean(brushSettings.customTipDataUrl) && !activeBuiltinBrush));
+ const activeCustomBrush = isCustomBrushActive
+ ? customBrushes.find((b) => b.id === activePreset)
+ : null;
+
+ const handleUpdateBrushSettings = (newSettings: Partial<BrushSettings>) => {
+ toolStoreActions.updateBrushSettings(newSettings);
+ if (isCustomBrushActive && activeCustomBrush) {
+ const updatedBrush: CspBrush = {
+ ...activeCustomBrush,
+ size: newSettings.size ?? activeCustomBrush.size,
+ opacity: newSettings.opacity ?? activeCustomBrush.opacity,
+ flow: newSettings.flow ?? activeCustomBrush.flow,
+ brushDensity:
+ newSettings.brushDensity ?? newSettings.flow ?? activeCustomBrush.brushDensity,
+ adjustDensityByGap:
+ newSettings.adjustDensityByGap ?? activeCustomBrush.adjustDensityByGap,
+ blendTipsMode: newSettings.blendTipsMode ?? activeCustomBrush.blendTipsMode,
+ spacing: newSettings.spacing ?? activeCustomBrush.spacing,
+ hardness: newSettings.hardness ?? activeCustomBrush.hardness,
+ thickness: newSettings.thickness ?? activeCustomBrush.thickness,
+ thicknessVertical:
+ newSettings.thicknessVertical ?? activeCustomBrush.thicknessVertical,
+ antiAlias: newSettings.antiAlias ?? activeCustomBrush.antiAlias,
+ stabilization: newSettings.stabilization ?? activeCustomBrush.stabilization,
+ postCorrection: newSettings.postCorrection ?? activeCustomBrush.postCorrection,
+ sharpCorners: newSettings.sharpCorners ?? activeCustomBrush.sharpCorners,
+ angle: newSettings.customTipAngle ?? activeCustomBrush.angle,
+ angleDynamics: newSettings.customTipAngleDynamics ?? activeCustomBrush.angleDynamics,
+ flipH: newSettings.flipH ?? activeCustomBrush.flipH,
+ flipV: newSettings.flipV ?? activeCustomBrush.flipV,
+ isRibbon: newSettings.isRibbon ?? activeCustomBrush.isRibbon,
+ usePressure: newSettings.usePressure ?? activeCustomBrush.usePressure,
+ useTilt: newSettings.useTilt ?? activeCustomBrush.useTilt,
+ useVelocity: newSettings.useVelocity ?? activeCustomBrush.useVelocity,
+ pressureCurve: newSettings.pressureCurve ?? activeCustomBrush.pressureCurve,
+ taper: newSettings.taper ?? activeCustomBrush.taper,
+ spray: newSettings.spray ?? activeCustomBrush.spray,
+ colorMixing: newSettings.colorMixing ?? activeCustomBrush.colorMixing,
+ mixingMode: newSettings.mixingMode ?? activeCustomBrush.mixingMode,
+ amountOfPaint: newSettings.amountOfPaint ?? activeCustomBrush.amountOfPaint,
+ densityOfPaint: newSettings.densityOfPaint ?? activeCustomBrush.densityOfPaint,
+ colorStretch: newSettings.colorStretch ?? activeCustomBrush.colorStretch,
+ wetEdge: newSettings.wetEdge ?? activeCustomBrush.wetEdge,
+ wetEdgeRadius: newSettings.wetEdgeRadius ?? activeCustomBrush.wetEdgeRadius,
+ textureDensity: newSettings.grain ?? activeCustomBrush.textureDensity,
+ paperTextureMode: newSettings.paperTextureMode ?? activeCustomBrush.paperTextureMode,
+ paperTextureScale: newSettings.paperTextureScale ?? activeCustomBrush.paperTextureScale,
+ paperTextureInverted:
+ newSettings.paperTextureInverted ?? activeCustomBrush.paperTextureInverted,
+ dynamics: newSettings.dynamics ?? activeCustomBrush.dynamics,
+ };
+ setCustomBrushes((prev) =>
+ prev.map((b) => (b.id === updatedBrush.id ? updatedBrush : b))
+ );
+ saveCustomBrushDebounced(updatedBrush);
+ }
+ };
+
+ const handleUpdateDynamics = (patch: Partial<BrushDynamics>) => {
+ const cur = brushSettings.dynamics || DEFAULT_BRUSH_DYNAMICS;
+ handleUpdateBrushSettings({ dynamics: { ...cur, ...patch } });
+ };
+
+ const handleUpdateTaper = (patch: Partial<CspTaperSettings>) => {
+ const cur = brushSettings.taper || DEFAULT_TAPER;
+ handleUpdateBrushSettings({ taper: { ...cur, ...patch } });
+ };
+
+ const handleUpdateSpray = (patch: Partial<CspSpraySettings>) => {
+ const cur = brushSettings.spray || DEFAULT_SPRAY;
+ handleUpdateBrushSettings({ spray: { ...cur, ...patch } });
+ };
+
+ const toggleAccordion = (id: InspectorAccordionId) => {
+ setOpenAccordion((prev) => (prev === id ? null : id));
+ };
+
+ if (!isBrushOrEraser) {
+ if (currentTool === 'fill') {
+ const method = fillSettings.method ?? 'refer-all';
+ return (
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Fill</div>
+ <div className="space-y-1">
+ {(
+ [
+ { id: 'refer-all', label: 'All Visible' },
+ { id: 'refer-active', label: 'Active Layer' },
+ { id: 'refer-reference', label: 'Reference Layer' },
+ { id: 'lasso', label: 'Lasso Fill' },
+ ] as const
+ ).map((m) => (
+ <button
+ key={m.id}
+ type="button"
+ onClick={() => toolStoreActions.updateFillSettings({ method: m.id })}
+ className={`w-full px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${
+ method === m.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {m.label}
+ </button>
+ ))}
+ </div>
+ {method !== 'lasso' && (
+ <>
+ <CompactSlider
+ label="Tolerance"
+ valueLabel={`${fillSettings.tolerance ?? 32}`}
+ min={0}
+ max={100}
+ value={fillSettings.tolerance ?? 32}
+ onChange={(v) => toolStoreActions.updateFillSettings({ tolerance: v })}
+ />
+ <CompactSlider
+ label="Close Gap"
+ valueLabel={`${fillSettings.closeGap ?? 0}px`}
+ min={0}
+ max={20}
+ value={fillSettings.closeGap ?? 0}
+ onChange={(v) => toolStoreActions.updateFillSettings({ closeGap: v })}
+ />
+ <CompactSlider
+ label="Area Scaling"
+ valueLabel={`${(fillSettings.areaScale ?? 0) > 0 ? '+' : ''}${fillSettings.areaScale ?? 0}px`}
+ min={-20}
+ max={20}
+ value={fillSettings.areaScale ?? 0}
+ onChange={(v) => toolStoreActions.updateFillSettings({ areaScale: v })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Anti-Alias</span>
+ <input
+ type="checkbox"
+ checked={fillSettings.antiAlias ?? true}
+ onChange={(e) =>
+ toolStoreActions.updateFillSettings({ antiAlias: e.target.checked })
+ }
+ />
+ </label>
+ </>
+ )}
+ </div>
+ );
+ }
+
+ if (currentTool === 'liquify') {
+ const activeMode = liquifySettings.mode ?? 'push';
+ return (
+ <div className="p-2 space-y-3 overflow-y-auto flex-1">
+ <div className="px-0.5 text-[11px] font-medium text-[#e5e5e5]">Liquify</div>
+ <div className="space-y-0.5">
+ {LIQUIFY_MODES.map((sub) => (
+ <button
+ key={sub.id}
+ type="button"
+ onClick={() => toolStoreActions.updateLiquifySettings({ mode: sub.id })}
+ className={`w-full px-2 py-1 rounded text-left text-[11px] transition-colors cursor-pointer ${
+ activeMode === sub.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {sub.label}
+ </button>
+ ))}
+ </div>
+ <CompactSlider
+ label="Size"
+ valueLabel={`${liquifySettings.size ?? 80}px`}
+ min={4}
+ max={500}
+ value={liquifySettings.size ?? 80}
+ onChange={(v) => toolStoreActions.updateLiquifySettings({ size: v })}
+ />
+ <CompactSlider
+ label="Strength"
+ valueLabel={`${liquifySettings.strength ?? 50}%`}
+ min={1}
+ max={100}
+ value={liquifySettings.strength ?? 50}
+ onChange={(v) => toolStoreActions.updateLiquifySettings({ strength: v })}
+ />
+ <CompactSlider
+ label="Hardness"
+ valueLabel={`${liquifySettings.hardness ?? 50}%`}
+ min={0}
+ max={100}
+ value={liquifySettings.hardness ?? 50}
+ onChange={(v) => toolStoreActions.updateLiquifySettings({ hardness: v })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Pressure</span>
+ <input
+ type="checkbox"
+ checked={liquifySettings.usePressure ?? true}
+ onChange={(e) =>
+ toolStoreActions.updateLiquifySettings({ usePressure: e.target.checked })
+ }
+ />
+ </label>
+ </div>
+ );
+ }
+
+ if (
+ currentTool === 'select-rect' ||
+ currentTool === 'select-lasso' ||
+ currentTool === 'select-wand' ||
+ currentTool === 'select-pen' ||
+ currentTool === 'select-eraser'
+ ) {
+ return (
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Selection</div>
+ <div className="grid grid-cols-2 gap-1">
+ {(
+ [
+ { id: 'select-rect', label: 'Rect' },
+ { id: 'select-lasso', label: 'Lasso' },
+ { id: 'select-wand', label: 'Wand' },
+ { id: 'select-pen', label: 'Pen' },
+ { id: 'select-eraser', label: 'Erase' },
+ ] as const
+ ).map((s) => (
+ <button
+ key={s.id}
+ type="button"
+ onClick={() => toolStoreActions.selectTool(s.id)}
+ className={`py-1 px-1.5 rounded text-[11px] transition-colors cursor-pointer ${
+ currentTool === s.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {s.label}
+ </button>
+ ))}
+ </div>
+
+ {(currentTool === 'select-pen' || currentTool === 'select-eraser') && (
+ <CompactSlider
+ label="Brush Size"
+ valueLabel={`${brushSettings.size}px`}
+ min={1}
+ max={250}
+ value={Math.round(brushSettings.size)}
+ onChange={(v) => toolStoreActions.updateBrushSettings({ size: v })}
+ />
+ )}
+
+ {currentTool === 'select-wand' && (
+ <div className="space-y-2.5 pt-1">
+ <CompactSlider
+ label="Tolerance"
+ valueLabel={`${wandSettings.tolerance}`}
+ min={0}
+ max={255}
+ value={wandSettings.tolerance}
+ onChange={(v) => toolStoreActions.updateWandSettings({ tolerance: v })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Contiguous</span>
+ <input
+ type="checkbox"
+ checked={wandSettings.contiguous}
+ onChange={(e) =>
+ toolStoreActions.updateWandSettings({ contiguous: e.target.checked })
+ }
+ />
+ </label>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Anti-Alias</span>
+ <input
+ type="checkbox"
+ checked={wandSettings.antiAlias}
+ onChange={(e) =>
+ toolStoreActions.updateWandSettings({ antiAlias: e.target.checked })
+ }
+ />
+ </label>
+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(['active', 'all', 'reference'] as const).map((mode) => (
+ <button
+ key={mode}
+ type="button"
+ onClick={() => toolStoreActions.updateWandSettings({ referMode: mode })}
+ className={`py-0.5 rounded text-[10px] capitalize cursor-pointer ${
+ wandSettings.referMode === mode
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {mode === 'reference' ? 'Ref' : mode}
+ </button>
+ ))}
+ </div>
+ </div>
+ )}
+
+ <div className="space-y-1 pt-1">
+ <div className="grid grid-cols-3 gap-1">
+ <button
+ type="button"
+ onClick={() => onExpandSelection?.(5)}
+ title="Expand 5px"
+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
+ >
+ <Maximize2 className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => onContractSelection?.(5)}
+ title="Contract 5px"
+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
+ >
+ <Minimize2 className="w-3 h-3" />
+ </button>
+ <button
+ type="button"
+ onClick={() => onFeatherSelection?.(5)}
+ title="Feather 5px"
+ className="py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center justify-center cursor-pointer"
+ >
+ <Feather className="w-3 h-3" />
+ </button>
+ </div>
+ <button
+ type="button"
+ onClick={onInvertSelection}
+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center gap-1.5 cursor-pointer"
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span>Invert</span>
+ </button>
+ <button
+ type="button"
+ onClick={onTransformSelection}
+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] flex items-center gap-1.5 cursor-pointer"
+ >
+ <Scaling className="w-3 h-3" />
+ <span>Transform</span>
+ </button>
+ <button
+ type="button"
+ onClick={onDeselect}
+ className="w-full py-1 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer text-left"
+ >
+ Deselect
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ if (currentTool === 'text') {
+ return (
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Text</div>
+ <select
+ value={textSettings.fontFamily}
+ onChange={(e) => toolStoreActions.updateTextSettings({ fontFamily: e.target.value })}
+ className="w-full px-2 py-1 text-[11px]"
+ >
+ <option value="'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif">
+ Manga / Anime
+ </option>
+ <option value="'Anime Ace', 'Comic Sans MS', sans-serif">Anime Ace</option>
+ <option value="Arial, sans-serif">Arial</option>
+ <option value="Impact, sans-serif">Impact</option>
+ <option value="Georgia, serif">Georgia</option>
+ </select>
+ <div className="grid grid-cols-2 gap-1 bg-[#161616] p-0.5 rounded">
+ <button
+ type="button"
+ onClick={() => toolStoreActions.updateTextSettings({ writingMode: 'horizontal-tb' })}
+ className={`py-1 rounded text-[10px] cursor-pointer ${
+ textSettings.writingMode !== 'vertical-rl'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Horiz
+ </button>
+ <button
+ type="button"
+ onClick={() => toolStoreActions.updateTextSettings({ writingMode: 'vertical-rl' })}
+ className={`py-1 rounded text-[10px] cursor-pointer ${
+ textSettings.writingMode === 'vertical-rl'
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Vert
+ </button>
+ </div>
+ <CompactSlider
+ label="Font Size"
+ valueLabel={`${textSettings.fontSize ?? 28}px`}
+ min={12}
+ max={160}
+ value={textSettings.fontSize ?? 28}
+ onChange={(v) => toolStoreActions.updateTextSettings({ fontSize: v })}
+ />
+ </div>
+ );
+ }
+
+ if (currentTool === 'frame') {
+ return (
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Frame Border</div>
+ <CompactSlider
+ label="Thickness"
+ valueLabel={`${frameSettings.thickness ?? 4}px`}
+ min={1}
+ max={100}
+ value={frameSettings.thickness ?? 4}
+ onChange={(v) => toolStoreActions.updateFrameSettings({ thickness: v })}
+ />
+ <div className="grid grid-cols-2 gap-1 bg-[#161616] p-0.5 rounded">
+ <button
+ type="button"
+ onClick={() => toolStoreActions.updateFrameSettings({ fillBackground: true })}
+ className={`py-1 rounded text-[10px] cursor-pointer ${
+ frameSettings.fillBackground
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ White
+ </button>
+ <button
+ type="button"
+ onClick={() => toolStoreActions.updateFrameSettings({ fillBackground: false })}
+ className={`py-1 rounded text-[10px] cursor-pointer ${
+ !frameSettings.fillBackground
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ Empty
+ </button>
+ </div>
+ </div>
+ );
+ }
+
+ if (currentTool === 'balloon') {
+ return (
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Balloon</div>
+ <div className="space-y-0.5">
+ {(['ellipse', 'rounded-rect', 'jagged-flash', 'thought'] as const).map((shape) => (
+ <button
+ key={shape}
+ type="button"
+ onClick={() => toolStoreActions.updateBalloonSettings({ shape })}
+ className={`w-full px-2 py-1 rounded text-left text-[11px] capitalize cursor-pointer ${
+ balloonSettings.shape === shape
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {shape.replace('-', ' ')}
+ </button>
+ ))}
+ </div>
+ <CompactSlider
+ label="Border"
+ valueLabel={`${balloonSettings.strokeWidth ?? 3}px`}
+ min={1}
+ max={15}
+ value={balloonSettings.strokeWidth ?? 3}
+ onChange={(v) => toolStoreActions.updateBalloonSettings({ strokeWidth: v })}
+ />
+ </div>
+ );
+ }
+
+ if (currentTool === 'vector-edit') {
+ const activeMode = vectorEditSettings.mode || 'pinch';
+ return (
+ <div className="p-2.5 space-y-3 overflow-y-auto flex-1">
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Correct Line</div>
+ <div className="space-y-0.5">
+ {(['pinch', 'width', 'simplify'] as const).map((m) => (
+ <button
+ key={m}
+ type="button"
+ onClick={() => toolStoreActions.updateVectorEditSettings({ mode: m })}
+ className={`w-full px-2 py-1 rounded text-left text-[11px] capitalize cursor-pointer ${
+ activeMode === m
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {m}
+ </button>
+ ))}
+ </div>
+ <CompactSlider
+ label="Radius"
+ valueLabel={`${vectorEditSettings.radius ?? 30}px`}
+ min={5}
+ max={150}
+ value={vectorEditSettings.radius ?? 30}
+ onChange={(v) => toolStoreActions.updateVectorEditSettings({ radius: v })}
+ />
+ {activeMode === 'pinch' && (
+ <CompactSlider
+ label="Pinch Level"
+ valueLabel={`${Math.round((vectorEditSettings.pinchStrength ?? 0.65) * 100)}%`}
+ min={10}
+ max={100}
+ value={Math.round((vectorEditSettings.pinchStrength ?? 0.65) * 100)}
+ onChange={(v) =>
+ toolStoreActions.updateVectorEditSettings({ pinchStrength: v / 100 })
+ }
+ />
+ )}
+ {activeMode === 'width' && (
+ <CompactSlider
+ label="Adjust Width"
+ valueLabel={`${(vectorEditSettings.widthFactor ?? 1.2) >= 1 ? '+' : ''}${Math.round(((vectorEditSettings.widthFactor ?? 1.2) - 1) * 100)}%`}
+ min={50}
+ max={200}
+ value={Math.round((vectorEditSettings.widthFactor ?? 1.2) * 100)}
+ onChange={(v) =>
+ toolStoreActions.updateVectorEditSettings({ widthFactor: v / 100 })
+ }
+ />
+ )}
+ {activeMode === 'simplify' && (
+ <CompactSlider
+ label="Simplify"
+ valueLabel={`${(vectorEditSettings.simplifyTolerance ?? 2.0).toFixed(1)}px`}
+ min={0.5}
+ max={12}
+ step={0.5}
+ value={vectorEditSettings.simplifyTolerance ?? 2.0}
+ onChange={(v) =>
+ toolStoreActions.updateVectorEditSettings({ simplifyTolerance: v })
+ }
+ />
+ )}
+ <button
+ type="button"
+ onClick={() => uiStoreActions.setMangaEffectsModalOpen(true)}
+ className="w-full py-1.5 px-2 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#e5e5e5] cursor-pointer"
+ >
+ Effect Lines...
+ </button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="p-2.5 text-[11px] text-[#8a8a8a]">
+ <div className="text-[#e5e5e5] font-medium capitalize mb-1">{currentTool}</div>
+ <p className="leading-relaxed">Click or drag directly on the canvas.</p>
+ </div>
+ );
+ }
+
+ const currentAntiAlias = brushSettings.antiAlias ?? 2;
+
+ return (
+ <>
+ {/* Live S-Curve Stroke Preview + Quick Size/Opacity Bar */}
+ <div className="shrink-0 bg-[#1b1b1b] border-t border-[#2a2a2a] px-2 py-1.5 space-y-1.5">
+ <canvas ref={previewCanvasRef} className="w-full h-8 rounded bg-[#161616] block" />
+ <CompactSlider
+ label="Brush Size ([ / ])"
+ valueLabel={`${brushSettings.size < 10 ? brushSettings.size.toFixed(1) : Math.round(brushSettings.size)}px`}
+ min={0.5}
+ max={500}
+ step={0.5}
+ value={brushSettings.size}
+ onChange={(v) => handleUpdateBrushSettings({ size: v })}
+ />
+ <CompactSlider
+ label="Opacity"
+ valueLabel={`${Math.round((brushSettings.opacity ?? 1.0) * 100)}%`}
+ min={1}
+ max={100}
+ value={Math.round((brushSettings.opacity ?? 1.0) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ opacity: v / 100 })}
+ />
+ </div>
+
+ {/* CSP Sub-Tool Detail Accordions */}
+ <div className="shrink-0 bg-[#161616] pt-px space-y-px max-h-[50%] overflow-y-auto">
+ {/* 1. Ink */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('ink')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Ink</span>
+ <div className="flex items-center gap-1">
+ <span className="font-mono text-[10px] text-[#e5e5e5]">
+ {Math.round((brushSettings.flow ?? 0.85) * 100)}%
+ </span>
+ {openAccordion === 'ink' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </div>
+ </button>
+
+ {openAccordion === 'ink' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Brush Density"
+ valueLabel={`${Math.round((brushSettings.flow ?? 0.85) * 100)}%`}
+ min={1}
+ max={100}
+ value={Math.round((brushSettings.flow ?? 0.85) * 100)}
+ onChange={(v) =>
+ handleUpdateBrushSettings({ flow: v / 100, brushDensity: v / 100 })
+ }
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Adjust by Gap</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.adjustDensityByGap)}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ adjustDensityByGap: e.target.checked })
+ }
+ />
+ </label>
+ <div className="space-y-1">
+ <span className="text-[11px] text-[#8a8a8a]">Blend Tips</span>
+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { id: 'normal', label: 'Normal' },
+ { id: 'darken', label: 'Darken' },
+ { id: 'compare', label: 'Compare' },
+ ] as Array<{ id: CspBlendTipsMode; label: string }>
+ ).map((mode) => (
+ <button
+ key={mode.id}
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ blendTipsMode: mode.id })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ (brushSettings.blendTipsMode ?? 'normal') === mode.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {mode.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ <div className="space-y-1">
+ <span className="text-[11px] text-[#8a8a8a]">Anti-Aliasing</span>
+ <div className="grid grid-cols-4 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { val: 0, label: 'None' },
+ { val: 1, label: 'Weak' },
+ { val: 2, label: 'Med' },
+ { val: 3, label: 'Strong' },
+ ] as const
+ ).map((aa) => (
+ <button
+ key={aa.val}
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ antiAlias: aa.val })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ currentAntiAlias === aa.val
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {aa.label}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>
+ )}
+ </div>
+
+ {/* 2. Brush Tip */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('tip')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Brush Tip</span>
+ {openAccordion === 'tip' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </button>
+
+ {openAccordion === 'tip' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Hardness"
+ valueLabel={`${Math.round((brushSettings.hardness ?? 1.0) * 100)}%`}
+ min={5}
+ max={100}
+ value={Math.round((brushSettings.hardness ?? 1.0) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ hardness: v / 100 })}
+ />
+ <CompactSlider
+ label="Gap (Spacing)"
+ valueLabel={`${Math.round((brushSettings.spacing ?? 0.1) * 100)}%`}
+ min={1}
+ max={100}
+ value={Math.round((brushSettings.spacing ?? 0.1) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ spacing: v / 100 })}
+ />
+ <CompactSlider
+ label="Thickness"
+ valueLabel={`${Math.round((brushSettings.thickness ?? 1.0) * 100)}%`}
+ min={5}
+ max={100}
+ value={Math.round((brushSettings.thickness ?? 1.0) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ thickness: v / 100 })}
+ />
+ <div className="grid grid-cols-2 gap-0.5 bg-[#161616] p-0.5 rounded">
+ <button
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ thicknessVertical: false })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ !brushSettings.thicknessVertical
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a]'
+ }`}
+ >
+ Horizontal
+ </button>
+ <button
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ thicknessVertical: true })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ brushSettings.thicknessVertical
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a]'
+ }`}
+ >
+ Vertical
+ </button>
+ </div>
+ <CompactSlider
+ label="Angle"
+ valueLabel={`${Math.round(brushSettings.customTipAngle ?? 0)}deg`}
+ min={0}
+ max={360}
+ value={Math.round(brushSettings.customTipAngle ?? 0)}
+ onChange={(v) => handleUpdateBrushSettings({ customTipAngle: v })}
+ />
+ <div className="space-y-1">
+ <span className="text-[11px] text-[#8a8a8a]">Angle Dynamics</span>
+ <select
+ value={brushSettings.customTipAngleDynamics ?? 'none'}
+ onChange={(e) =>
+ handleUpdateBrushSettings({
+ customTipAngleDynamics: e.target.value as CspAngleDynamicsMode,
+ })
+ }
+ className="w-full h-6 bg-[#161616] text-[#e5e5e5] text-[10px] px-1.5 rounded cursor-pointer"
+ >
+ <option value="none">None</option>
+ <option value="direction">Direction of Line</option>
+ <option value="tilt">Pen Tilt</option>
+ <option value="twist">Barrel Twist</option>
+ <option value="random">Random</option>
+ <option value="direction-random">Direction + Random</option>
+ </select>
+ </div>
+ <div className="grid grid-cols-2 gap-1.5">
+ <div className="space-y-0.5">
+ <span className="text-[10px] text-[#8a8a8a]">Flip H</span>
+ <select
+ value={brushSettings.flipH ?? 'none'}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ flipH: e.target.value as CspTipFlipMode })
+ }
+ className="w-full h-5 bg-[#161616] text-[#e5e5e5] text-[10px] px-1 rounded cursor-pointer"
+ >
+ <option value="none">None</option>
+ <option value="random">Random</option>
+ <option value="alternate">Alternate</option>
+ </select>
+ </div>
+ <div className="space-y-0.5">
+ <span className="text-[10px] text-[#8a8a8a]">Flip V</span>
+ <select
+ value={brushSettings.flipV ?? 'none'}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ flipV: e.target.value as CspTipFlipMode })
+ }
+ className="w-full h-5 bg-[#161616] text-[#e5e5e5] text-[10px] px-1 rounded cursor-pointer"
+ >
+ <option value="none">None</option>
+ <option value="random">Random</option>
+ <option value="alternate">Alternate</option>
+ </select>
+ </div>
+ </div>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Ribbon</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.isRibbon)}
+ onChange={(e) => handleUpdateBrushSettings({ isRibbon: e.target.checked })}
+ />
+ </label>
+ </div>
+ )}
+ </div>
+
+ {/* 3. Stroke & Stabilization */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('stroke')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Stabilization &amp; Stroke</span>
+ <div className="flex items-center gap-1">
+ <span className="font-mono text-[10px] text-[#e5e5e5]">
+ {brushSettings.stabilization ?? 15}
+ </span>
+ {openAccordion === 'stroke' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </div>
+ </button>
+
+ {openAccordion === 'stroke' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Stabilization"
+ valueLabel={`${brushSettings.stabilization ?? 15}`}
+ min={0}
+ max={50}
+ value={brushSettings.stabilization ?? 15}
+ onChange={(v) => handleUpdateBrushSettings({ stabilization: v })}
+ />
+ <CompactSlider
+ label="Post-Correction"
+ valueLabel={`${brushSettings.postCorrection ?? 0}`}
+ min={0}
+ max={5}
+ value={brushSettings.postCorrection ?? 0}
+ onChange={(v) => handleUpdateBrushSettings({ postCorrection: v })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Sharp Angles</span>
+ <input
+ type="checkbox"
+ checked={brushSettings.sharpCorners ?? true}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ sharpCorners: e.target.checked })
+ }
+ />
+ </label>
+
+ <div className="grid grid-cols-2 gap-1.5">
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Taper In</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.taper?.useIn)}
+ onChange={(e) => handleUpdateTaper({ useIn: e.target.checked })}
+ />
+ </label>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Taper Out</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.taper?.useOut)}
+ onChange={(e) => handleUpdateTaper({ useOut: e.target.checked })}
+ />
+ </label>
+ </div>
+ {(brushSettings.taper?.useIn || brushSettings.taper?.useOut) && (
+ <CompactSlider
+ label="Taper Length"
+ valueLabel={`${Math.round(brushSettings.taper?.outLength ?? 32)}px`}
+ min={4}
+ max={200}
+ value={Math.round(brushSettings.taper?.outLength ?? 32)}
+ onChange={(v) => handleUpdateTaper({ inLength: v, outLength: v })}
+ />
+ )}
+
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Pen Pressure</span>
+ <input
+ type="checkbox"
+ checked={brushSettings.usePressure}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ usePressure: e.target.checked })
+ }
+ />
+ </label>
+ {brushSettings.usePressure && (
+ <>
+ <CompactSlider
+ label="Min Width"
+ valueLabel={`${Math.round(brushSettings.minSizeFactor * 100)}%`}
+ min={0}
+ max={95}
+ value={Math.round(brushSettings.minSizeFactor * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ minSizeFactor: v / 100 })}
+ />
+ <div className="space-y-1">
+ <span className="text-[10px] text-[#8a8a8a]">Pressure Curve</span>
+ <div className="grid grid-cols-5 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { id: 'linear', short: 'Lin' },
+ { id: 'g-pen', short: 'G' },
+ { id: 'soft', short: 'Soft' },
+ { id: 'firm', short: 'Firm' },
+ { id: 'chisel', short: 'Hard' },
+ ] as const
+ ).map((p) => (
+ <button
+ key={p.id}
+ type="button"
+ title={CSP_PRESSURE_CURVE_PRESETS[p.id]?.label}
+ onClick={() =>
+ handleUpdateBrushSettings({
+ pressureCurve: CSP_PRESSURE_CURVE_PRESETS[p.id]?.points,
+ })
+ }
+ className="py-0.5 rounded text-[9px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ {p.short}
+ </button>
+ ))}
+ </div>
+ </div>
+ </>
+ )}
+
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Stylus Tilt</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.useTilt)}
+ onChange={(e) => handleUpdateBrushSettings({ useTilt: e.target.checked })}
+ />
+ </label>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Velocity Dynamics</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.useVelocity)}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ useVelocity: e.target.checked })
+ }
+ />
+ </label>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Bezier Smoothing</span>
+ <input
+ type="checkbox"
+ checked={brushSettings.smoothing}
+ onChange={(e) => handleUpdateBrushSettings({ smoothing: e.target.checked })}
+ />
+ </label>
+ <button
+ type="button"
+ onClick={() => {
+ const def = resetBrushSettingsToDefault(
+ currentTool === 'eraser'
+ ? ERASER_PRESET_ID
+ : brushSettings.preset || 'pencil-2b',
+ customBrushes
+ );
+ handleUpdateBrushSettings(def);
+ }}
+ className="w-full py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
+ >
+ Reset Brush to Default
+ </button>
+ </div>
+ )}
+ </div>
+
+ {/* 4. Color Mixing & Watercolor Edge */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('mixing')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Color Mixing &amp; Edge</span>
+ {openAccordion === 'mixing' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </button>
+
+ {openAccordion === 'mixing' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Color Mixing</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.colorMixing)}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ colorMixing: e.target.checked })
+ }
+ />
+ </label>
+ {brushSettings.colorMixing && (
+ <>
+ <div className="grid grid-cols-3 gap-0.5 bg-[#161616] p-0.5 rounded">
+ {(
+ [
+ { id: 'blend', label: 'Blend' },
+ { id: 'running_color', label: 'Running' },
+ { id: 'smear', label: 'Smear' },
+ ] as const
+ ).map((m) => (
+ <button
+ key={m.id}
+ type="button"
+ onClick={() => handleUpdateBrushSettings({ mixingMode: m.id })}
+ className={`py-0.5 rounded text-[10px] cursor-pointer ${
+ (brushSettings.mixingMode || 'blend') === m.id
+ ? 'bg-[#2c2c2c] text-[#e5e5e5]'
+ : 'text-[#8a8a8a]'
+ }`}
+ >
+ {m.label}
+ </button>
+ ))}
+ </div>
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Perceptual (OKLab)</span>
+ <input
+ type="checkbox"
+ checked={brushSettings.perceptualMixing ?? true}
+ onChange={(e) =>
+ handleUpdateBrushSettings({ perceptualMixing: e.target.checked })
+ }
+ />
+ </label>
+ <CompactSlider
+ label="Amount of Paint"
+ valueLabel={`${Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.amountOfPaint ?? 0.7) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ amountOfPaint: v / 100 })}
+ />
+ <CompactSlider
+ label="Density of Paint"
+ valueLabel={`${Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}%`}
+ min={1}
+ max={100}
+ value={Math.round((brushSettings.densityOfPaint ?? 0.8) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ densityOfPaint: v / 100 })}
+ />
+ <CompactSlider
+ label="Color Stretch"
+ valueLabel={`${Math.round((brushSettings.colorStretch ?? 0.6) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.colorStretch ?? 0.6) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ colorStretch: v / 100 })}
+ />
+ </>
+ )}
+ <CompactSlider
+ label="Watercolor Edge"
+ valueLabel={`${Math.round((brushSettings.wetEdge ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.wetEdge ?? 0) * 100)}
+ onChange={(v) => handleUpdateBrushSettings({ wetEdge: v / 100 })}
+ />
+ {(brushSettings.wetEdge ?? 0) > 0.01 && (
+ <CompactSlider
+ label="Edge Width"
+ valueLabel={`${brushSettings.wetEdgeRadius ?? 4}px`}
+ min={1}
+ max={20}
+ value={Math.round(brushSettings.wetEdgeRadius ?? 4)}
+ onChange={(v) => handleUpdateBrushSettings({ wetEdgeRadius: v })}
+ />
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* 5. Texture & Spraying Effect */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('texture')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Texture &amp; Spray</span>
+ {openAccordion === 'texture' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </button>
+
+ {openAccordion === 'texture' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Texture Density"
+ valueLabel={`${Math.round((brushSettings.grain ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.grain ?? 0) * 100)}
+ onChange={(v) =>
+ handleUpdateBrushSettings({ grain: v / 100, textureDensity: v / 100 })
+ }
+ />
+ {(brushSettings.grain ?? 0) > 0.005 && (
+ <>
+ <div className="space-y-1">
+ <span className="text-[11px] text-[#8a8a8a]">Texture Mode</span>
+ <select
+ value={brushSettings.paperTextureMode ?? 'subtract'}
+ onChange={(e) =>
+ handleUpdateBrushSettings({
+ paperTextureMode: e.target.value as CspPaperTextureMode,
+ })
+ }
+ className="w-full h-6 bg-[#161616] text-[#e5e5e5] text-[10px] px-1.5 rounded cursor-pointer"
+ >
+ <option value="subtract">Subtract (Valley Fill)</option>
+ <option value="multiply">Multiply</option>
+ <option value="compare">Compare Density</option>
+ <option value="overlay">Overlay</option>
+ <option value="outline">Outline</option>
+ </select>
+ </div>
+ <CompactSlider
+ label="Texture Scale"
+ valueLabel={`${Math.round((brushSettings.paperTextureScale ?? 1.0) * 100)}%`}
+ min={10}
+ max={400}
+ step={5}
+ value={Math.round((brushSettings.paperTextureScale ?? 1.0) * 100)}
+ onChange={(v) =>
+ handleUpdateBrushSettings({ paperTextureScale: v / 100 })
+ }
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Invert Texture</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.paperTextureInverted)}
+ onChange={(e) =>
+ handleUpdateBrushSettings({
+ paperTextureInverted: e.target.checked,
+ })
+ }
+ />
+ </label>
+ </>
+ )}
+
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer pt-1">
+ <span>Spraying Effect</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.spray?.enabled)}
+ onChange={(e) => handleUpdateSpray({ enabled: e.target.checked })}
+ />
+ </label>
+ {brushSettings.spray?.enabled && (
+ <>
+ <CompactSlider
+ label="Particle Size"
+ valueLabel={`${brushSettings.spray.size ?? 4}px`}
+ min={1}
+ max={80}
+ value={Math.round(brushSettings.spray.size ?? 4)}
+ onChange={(v) => handleUpdateSpray({ size: v })}
+ />
+ <CompactSlider
+ label="Spray Density"
+ valueLabel={`${brushSettings.spray.density ?? 12}`}
+ min={1}
+ max={64}
+ value={Math.round(brushSettings.spray.density ?? 12)}
+ onChange={(v) => handleUpdateSpray({ density: v })}
+ />
+ </>
+ )}
+ </div>
+ )}
+ </div>
+
+ {/* 6. Dynamics & Jitter */}
+ <div className="bg-[#202020]">
+ <button
+ type="button"
+ onClick={() => toggleAccordion('dynamics')}
+ className="w-full px-2 py-1.5 flex items-center justify-between text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60 transition-colors cursor-pointer"
+ >
+ <span>Dynamics &amp; Jitter</span>
+ {openAccordion === 'dynamics' ? (
+ <ChevronDown className="w-3 h-3" />
+ ) : (
+ <ChevronRight className="w-3 h-3" />
+ )}
+ </button>
+
+ {openAccordion === 'dynamics' && (
+ <div className="px-2.5 pb-2.5 pt-1 space-y-2.5">
+ <CompactSlider
+ label="Size Jitter"
+ valueLabel={`${Math.round((brushSettings.dynamics?.sizeJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.sizeJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ sizeJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="Angle Jitter"
+ valueLabel={`${Math.round((brushSettings.dynamics?.angleJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.angleJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ angleJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="Roundness Jitter"
+ valueLabel={`${Math.round((brushSettings.dynamics?.roundnessJitter ?? 0) * 100)}%`}
+ min={0}
+ max={95}
+ value={Math.round((brushSettings.dynamics?.roundnessJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ roundnessJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="Scatter"
+ valueLabel={`${(brushSettings.dynamics?.scatter ?? 0).toFixed(1)}x`}
+ min={0}
+ max={5}
+ step={0.1}
+ value={brushSettings.dynamics?.scatter ?? 0}
+ onChange={(v) => handleUpdateDynamics({ scatter: v })}
+ />
+ {(brushSettings.dynamics?.scatter ?? 0) > 0 && (
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Scatter Both Axes</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.dynamics?.scatterBothAxes)}
+ onChange={(e) =>
+ handleUpdateDynamics({ scatterBothAxes: e.target.checked })
+ }
+ />
+ </label>
+ )}
+ <CompactSlider
+ label="Count"
+ valueLabel={`${brushSettings.dynamics?.count ?? 1}`}
+ min={1}
+ max={10}
+ value={brushSettings.dynamics?.count ?? 1}
+ onChange={(v) => handleUpdateDynamics({ count: v })}
+ />
+ <CompactSlider
+ label="Flow Jitter"
+ valueLabel={`${Math.round((brushSettings.dynamics?.flowJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.flowJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ flowJitter: v / 100 })}
+ />
+ <label className="flex items-center justify-between text-[11px] text-[#8a8a8a] cursor-pointer">
+ <span>Color Jitter</span>
+ <input
+ type="checkbox"
+ checked={Boolean(brushSettings.dynamics?.colorJitterEnabled)}
+ onChange={(e) =>
+ handleUpdateDynamics({ colorJitterEnabled: e.target.checked })
+ }
+ />
+ </label>
+ {brushSettings.dynamics?.colorJitterEnabled && (
+ <>
+ <CompactSlider
+ label="Hue"
+ valueLabel={`${Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.hueJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ hueJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="Saturation"
+ valueLabel={`${Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.saturationJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ saturationJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="Brightness"
+ valueLabel={`${Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round((brushSettings.dynamics?.brightnessJitter ?? 0) * 100)}
+ onChange={(v) => handleUpdateDynamics({ brightnessJitter: v / 100 })}
+ />
+ <CompactSlider
+ label="FG / BG Mix"
+ valueLabel={`${Math.round((brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100)}%`}
+ min={0}
+ max={100}
+ value={Math.round(
+ (brushSettings.dynamics?.foregroundBackgroundJitter ?? 0) * 100
+ )}
+ onChange={(v) =>
+ handleUpdateDynamics({ foregroundBackgroundJitter: v / 100 })
+ }
+ />
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ </div>
+ </>
+ );
+ }
+);
+
+ToolPropertyInspector.displayName = 'ToolPropertyInspector';
diff --git a/src/components/ToolStrip.tsx b/src/components/ToolStrip.tsx
new file mode 100644
index 0000000..109a059
--- /dev/null
+++ b/src/components/ToolStrip.tsx
@@ -0,0 +1,212 @@
+import React from 'react';
+import {
+ Paintbrush,
+ Eraser,
+ PanelLeftClose,
+ PanelLeftOpen,
+ ArrowLeftRight,
+ BoxSelect,
+ Lasso,
+ PaintBucket,
+ Type,
+ Frame,
+ Scaling,
+ Pipette,
+ Wand2,
+ PenTool,
+ MessageSquare,
+ Spline,
+} from 'lucide-react';
+import { ToolType } from '../types/editor';
+import { LiquifyIcon } from './LiquifyIcon';
+import { useToolStore, toolStoreActions, useUiStore, uiStoreActions, workspaceStoreActions } from '../stores';
+
+export interface ToolStripProps {
+ onTransformSelection?: () => void;
+ onToggleTransparentColor?: () => void;
+ fluid?: boolean;
+}
+
+export const ToolStrip: React.FC<ToolStripProps> = React.memo(
+ ({ onTransformSelection, onToggleTransparentColor, fluid = false }) => {
+ const currentTool = useToolStore((s) => s.tool);
+ const primaryColor = useToolStore((s) => s.primaryColor);
+ const secondaryColor = useToolStore((s) => s.secondaryColor);
+ const isTransparentColor = useToolStore((s) => s.isTransparentColor);
+ const isHidden = useUiStore((s) => s.isLeftPanelHidden);
+
+ const handleToggleTransparent = () => {
+ if (onToggleTransparentColor) {
+ onToggleTransparentColor();
+ } else {
+ const next = toolStoreActions.toggleTransparentColor();
+ uiStoreActions.showToast(
+ next ? 'Transparent ink mode active' : 'Color ink mode active'
+ );
+ }
+ };
+
+ const toolItems: Array<{
+ id: ToolType;
+ label: string;
+ icon: React.ReactNode;
+ dividerAfter?: boolean;
+ onClick?: () => void;
+ }> = [
+ {
+ id: 'brush',
+ label: 'Brush (B)',
+ icon: <Paintbrush className="w-3.5 h-3.5" />,
+ onClick: () => {
+ toolStoreActions.selectTool('brush');
+ if (isHidden) uiStoreActions.toggleLeftPanelHidden();
+ },
+ },
+ { id: 'eraser', label: 'Eraser (E)', icon: <Eraser className="w-3.5 h-3.5" /> },
+ { id: 'pipette', label: 'Eyedropper (I)', icon: <Pipette className="w-3.5 h-3.5" /> },
+ {
+ id: 'liquify',
+ label: 'Liquify (J)',
+ icon: <LiquifyIcon className="w-3.5 h-3.5" />,
+ dividerAfter: true,
+ },
+ {
+ id: 'transform',
+ label: 'Transform (Ctrl+T)',
+ icon: <Scaling className="w-3.5 h-3.5" />,
+ onClick: () => {
+ toolStoreActions.selectTool('transform');
+ onTransformSelection?.();
+ },
+ },
+ { id: 'select-rect', label: 'Marquee (M)', icon: <BoxSelect className="w-3.5 h-3.5" /> },
+ { id: 'select-lasso', label: 'Lasso (L)', icon: <Lasso className="w-3.5 h-3.5" /> },
+ { id: 'select-wand', label: 'Magic Wand (W)', icon: <Wand2 className="w-3.5 h-3.5" /> },
+ {
+ id: 'select-pen',
+ label: 'Selection Pen',
+ icon: <PenTool className="w-3.5 h-3.5" />,
+ dividerAfter: true,
+ },
+ { id: 'fill', label: 'Fill (G)', icon: <PaintBucket className="w-3.5 h-3.5" /> },
+ { id: 'text', label: 'Text (T)', icon: <Type className="w-3.5 h-3.5" /> },
+ { id: 'frame', label: 'Frame Border (F)', icon: <Frame className="w-3.5 h-3.5" /> },
+ { id: 'balloon', label: 'Speech Balloon', icon: <MessageSquare className="w-3.5 h-3.5" /> },
+ { id: 'vector-edit', label: 'Correct Line', icon: <Spline className="w-3.5 h-3.5" /> },
+ ];
+
+ return (
+ <aside
+ className={
+ fluid
+ ? 'w-full h-full bg-[#202020] flex flex-col items-center py-1.5 overflow-y-auto no-scrollbar'
+ : 'w-[44px] bg-[#202020] flex flex-col items-center py-1.5 z-20 shrink-0'
+ }
+ >
+ <div
+ className={
+ fluid
+ ? 'flex flex-wrap items-center justify-center gap-0.5 w-full px-1'
+ : 'flex flex-col items-center gap-0.5 w-full px-1'
+ }
+ >
+ {toolItems.map((item) => {
+ const isActive = currentTool === item.id;
+ return (
+ <React.Fragment key={item.id}>
+ <button
+ type="button"
+ onClick={() =>
+ item.onClick ? item.onClick() : toolStoreActions.selectTool(item.id)
+ }
+ title={item.label}
+ className={`relative w-8 h-7 rounded flex items-center justify-center transition-colors cursor-pointer ${
+ isActive
+ ? 'bg-[#2c2c2c] text-[var(--accent)]'
+ : 'text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ }`}
+ >
+ {isActive && (
+ <span
+ className="absolute left-0 top-1.5 bottom-1.5 w-[2px] rounded-full"
+ style={{ backgroundColor: 'var(--accent)' }}
+ />
+ )}
+ {item.icon}
+ </button>
+ {item.dividerAfter && <div className="w-4 h-px bg-[#2c2c2c] my-1" />}
+ </React.Fragment>
+ );
+ })}
+ </div>
+
+ {/* Bottom Color Swatches & Collapse Toggle */}
+ <div className="mt-auto flex flex-col items-center gap-1.5 pt-2 pb-1 w-full">
+ <div className="relative w-6 h-6">
+ <div
+ onClick={() => toolStoreActions.swapColors()}
+ title={`Secondary: ${secondaryColor} (X to swap, D to reset)`}
+ className="absolute bottom-0 right-0 w-4 h-4 rounded-sm cursor-pointer shadow-[0_0_0_1px_rgba(255,255,255,0.18)]"
+ style={{ backgroundColor: secondaryColor }}
+ />
+ <div
+ onClick={() => {
+ if (isTransparentColor) handleToggleTransparent();
+ else toolStoreActions.swapColors();
+ }}
+ title={`Primary: ${primaryColor}`}
+ className={`absolute top-0 left-0 w-4 h-4 rounded-sm cursor-pointer z-10 ${
+ !isTransparentColor
+ ? 'shadow-[0_0_0_1.5px_var(--accent)]'
+ : 'opacity-70 shadow-[0_0_0_1px_rgba(255,255,255,0.2)]'
+ }`}
+ style={{ backgroundColor: primaryColor }}
+ />
+ </div>
+
+ <div
+ onClick={handleToggleTransparent}
+ title="Transparent Ink (C)"
+ className={`w-6 h-2.5 rounded-xs cursor-pointer transition-all ${
+ isTransparentColor
+ ? 'shadow-[0_0_0_1.5px_var(--accent)]'
+ : 'opacity-65 hover:opacity-100'
+ }`}
+ style={{
+ backgroundImage: 'repeating-conic-gradient(#777 0% 25%, #ccc 0% 50%)',
+ backgroundSize: '4px 4px',
+ }}
+ />
+
+ <button
+ type="button"
+ onClick={() => toolStoreActions.swapColors()}
+ title="Swap Colors (X)"
+ className="w-7 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
+ >
+ <ArrowLeftRight className="w-3 h-3" />
+ </button>
+
+ <button
+ type="button"
+ onClick={() =>
+ fluid
+ ? workspaceStoreActions.togglePalettesHidden()
+ : uiStoreActions.toggleLeftPanelHidden()
+ }
+ title={fluid ? 'Hide/Show Palettes (Tab)' : isHidden ? 'Show Panel (Shift+Tab)' : 'Hide Panel (Shift+Tab)'}
+ className="w-7 h-7 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
+ >
+ {isHidden ? (
+ <PanelLeftOpen className="w-3.5 h-3.5" />
+ ) : (
+ <PanelLeftClose className="w-3.5 h-3.5" />
+ )}
+ </button>
+ </div>
+ </aside>
+ );
+ }
+);
+
+ToolStrip.displayName = 'ToolStrip';
diff --git a/src/hooks/drawing/index.ts b/src/hooks/drawing/index.ts
new file mode 100644
index 0000000..0b4305e
--- /dev/null
+++ b/src/hooks/drawing/index.ts
@@ -0,0 +1,6 @@
+export * from './types';
+export { useDrawingHistory } from './useDrawingHistory';
+export { useBrushStrokeSession } from './useBrushStrokeSession';
+export { useVectorDrawing, commitVectorStrokeOrErase } from './useVectorDrawing';
+export { useSelectionTools } from './useSelectionTools';
+export { useShapeAndFillTools } from './useShapeAndFillTools';
diff --git a/src/hooks/drawing/types.ts b/src/hooks/drawing/types.ts
new file mode 100644
index 0000000..1f300e3
--- /dev/null
+++ b/src/hooks/drawing/types.ts
@@ -0,0 +1,190 @@
+import React from 'react';
+import {
+ ToolType,
+ BrushSettings,
+ Point,
+ CanvasDimensions,
+ CanvasSelection,
+ HistoryActionType,
+ CanvasColorMode,
+ DirtyRect,
+ LayerItem,
+ TileDelta,
+ VectorStroke,
+} from '../../types/editor';
+import { SparseTileGrid } from '../../utils/tileEngine';
+import { CanvasNavigationHandle } from '../useCanvasNavigation';
+import { PerspectiveRuler, ConstraintAxis } from '../../types/perspective';
+
+export interface DraftCanvasElement extends HTMLCanvasElement {
+ __draftHasContent?: boolean;
+ __draftCompositeOp?: GlobalCompositeOperation;
+ __draftSpace?: 'document' | 'viewport';
+ __draftDocRect?: { x: number; y: number; width: number; height: number };
+ __draftScale?: number;
+ __draftMonochrome?: boolean;
+ __draftVersion?: number;
+ __isBlank?: boolean;
+ __isSolidWhite?: boolean;
+}
+
+export interface ExtendedPointerEvent extends React.PointerEvent<HTMLElement> {
+ coalescedEvents?: PointerEvent[];
+ predictedEvents?: PointerEvent[];
+}
+
+export interface LastStrokeEndState {
+ x: number;
+ y: number;
+ pressure: number;
+ width: number;
+ layerId: string;
+}
+
+export type PushHistoryStepFn = (
+ actionType: HistoryActionType,
+ label: string,
+ beforeData: ImageData | null,
+ afterData: ImageData | null,
+ targetLayerId: string,
+ dirtyRect?: DirtyRect,
+ explicitTileDeltas?: TileDelta[],
+ vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },
+ peerId?: string | number,
+ strokeId?: string,
+ isMaskEdit?: boolean
+) => void;
+
+export interface UseCanvasDrawingProps {
+ tool?: ToolType;
+ brushSettings?: BrushSettings;
+ dimensions: CanvasDimensions;
+ selection?: CanvasSelection | null;
+ colorMode?: CanvasColorMode;
+ disabled?: boolean;
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ pan: { x: number; y: number };
+ zoom: number;
+ rotation: number;
+ flipX?: boolean;
+ flipY?: boolean;
+ navigation?: CanvasNavigationHandle;
+ activeLayerId: string;
+ activeLayerLocked?: boolean;
+ activeLayerVisible?: boolean;
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ layerSourceCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ layers?: LayerItem[];
+ onUpdateLayerThumbnail: (layerId: string) => void;
+ isMaskMode?: boolean;
+ onUpdateMaskThumbnail?: (layerId: string) => void;
+ draftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ strokeCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ predictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ onCollabStrokeStart?: (
+ strokeId: string,
+ layerId: string,
+ brushSettings: BrushSettings,
+ tool: ToolType,
+ startPoint: Point
+ ) => void;
+ onCollabStrokeChunk?: (strokeId: string, points: Point[]) => void;
+ onCollabStrokeFinish?: (
+ strokeId: string,
+ layerId: string,
+ endPoint: Point,
+ dirtyRect?: DirtyRect,
+ vectorStroke?: VectorStroke
+ ) => void;
+ onCollabCursorMove?: (x: number, y: number, isDrawing: boolean, tool: ToolType) => void;
+ perspectiveRuler?: PerspectiveRuler | null;
+ onActiveConstraintAxisChange?: (axis: ConstraintAxis | null) => void;
+ activeSessionId?: string | null;
+ tileGrid?: SparseTileGrid;
+ materializeLayerCanvas?: (layerId: string) => HTMLCanvasElement | null;
+}
+
+export function isBackgroundLayerId(id: string): boolean {
+ return id === 'layer-bg' || id.startsWith('layer-bg');
+}
+
+export function applySelectionCanvasClip(
+ ctx: CanvasRenderingContext2D,
+ sel: CanvasSelection | null | undefined
+): void {
+ if (!sel) return;
+ if (sel.type === 'rect') {
+ ctx.beginPath();
+ ctx.rect(sel.bounds.x, sel.bounds.y, sel.bounds.width, sel.bounds.height);
+ ctx.clip();
+ } else if (sel.type === 'lasso' && sel.polygon && sel.polygon.length >= 3) {
+ ctx.beginPath();
+ ctx.moveTo(sel.polygon[0].x, sel.polygon[0].y);
+ for (let i = 1; i < sel.polygon.length; i++) {
+ ctx.lineTo(sel.polygon[i].x, sel.polygon[i].y);
+ }
+ ctx.closePath();
+ ctx.clip();
+ } else if (sel.svgPath && typeof Path2D !== 'undefined') {
+ try {
+ ctx.clip(new Path2D(sel.svgPath), 'evenodd');
+ } catch {
+ ctx.beginPath();
+ ctx.rect(sel.bounds.x, sel.bounds.y, sel.bounds.width, sel.bounds.height);
+ ctx.clip();
+ }
+ }
+}
+
+export function applySelectionMaskToImageData(
+ beforeData: ImageData,
+ afterData: ImageData,
+ rx: number,
+ ry: number,
+ sel: CanvasSelection | null | undefined
+): void {
+ if (!sel || !sel.mask || !sel.maskWidth || !sel.maskHeight) return;
+ const mask = sel.mask;
+ const mw = sel.maskWidth;
+ const mh = sel.maskHeight;
+ const w = afterData.width;
+ const h = afterData.height;
+ const src = beforeData.data;
+ const dst = afterData.data;
+
+ for (let ly = 0; ly < h; ly++) {
+ const docY = ry + ly;
+ const inY = docY >= 0 && docY < mh;
+ const maskRow = docY * mw;
+ const imgRow = ly * w;
+ for (let lx = 0; lx < w; lx++) {
+ const docX = rx + lx;
+ const mAlpha = inY && docX >= 0 && docX < mw ? mask[maskRow + docX] : 0;
+ if (mAlpha === 255) continue;
+ const idx = (imgRow + lx) * 4;
+ if (mAlpha === 0) {
+ dst[idx] = src[idx];
+ dst[idx + 1] = src[idx + 1];
+ dst[idx + 2] = src[idx + 2];
+ dst[idx + 3] = src[idx + 3];
+ } else {
+ const wAfter = mAlpha / 255;
+ const wBefore = 1 - wAfter;
+ const aB = (src[idx + 3] / 255) * wBefore;
+ const aA = (dst[idx + 3] / 255) * wAfter;
+ const outA = aB + aA;
+ if (outA <= 0.0001) {
+ dst[idx] = 0;
+ dst[idx + 1] = 0;
+ dst[idx + 2] = 0;
+ dst[idx + 3] = 0;
+ } else {
+ dst[idx] = Math.round((src[idx] * aB + dst[idx] * aA) / outA);
+ dst[idx + 1] = Math.round((src[idx + 1] * aB + dst[idx + 1] * aA) / outA);
+ dst[idx + 2] = Math.round((src[idx + 2] * aB + dst[idx + 2] * aA) / outA);
+ dst[idx + 3] = Math.round(outA * 255);
+ }
+ }
+ }
+ }
+}
diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.ts
new file mode 100644
index 0000000..2983a8b
--- /dev/null
+++ b/src/hooks/drawing/useBrushStrokeSession.ts
@@ -0,0 +1,2849 @@
+import React, { useRef, useCallback, useEffect } from 'react';
+import {
+ ToolType,
+ BrushSettings,
+ Point,
+ CanvasDimensions,
+ CanvasSelection,
+ CanvasColorMode,
+ DirtyRect,
+ LayerItem,
+ VectorStroke,
+} from '../../types/editor';
+import { SparseTileGrid, TILE_SIZE, TileFormat, releaseTemporaryCanvas } from '../../utils/tileEngine';
+import {
+ calculateStrokeWidth,
+ drawSmoothCubicBezierSegment,
+ drawDot,
+ screenToCanvas,
+ screenToCanvasInto,
+ getCanvasToViewportMatrix,
+ getVisibleCanvasBounds,
+ get2DContext,
+ getReusableBakeCanvas,
+ renderCompleteStroke,
+ applyParametricTaper,
+} from '../../utils/canvasUtils';
+import {
+ StrokePipeline,
+ computeClampedBakeDirtyRect,
+ encodePointerType,
+} from '../../engine/StrokePipeline';
+import { CubicBezierSegment } from '../../engine/SplineGenerator';
+import { applyCspWatercolorEdge } from '../../engine/CspBrushEngine';
+import { enforceColorMode, binarizeImageDataBuffer } from '../../utils/colorUtils';
+import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from '../../utils/pencilEngine';
+import {
+ drawTexturedCubicBezierSegment,
+ drawTexturedDot,
+ TexturedBrushOptions,
+ RadialMixingOptions,
+ canUseWebGlForTexturedBrush,
+ canUseWebGlForRadialBrush,
+ flushTexturedGpuDabs,
+ flushRadialGpuDabs,
+} from '../../utils/stampEngine';
+import { GpuDab } from '../../utils/webglBrushEngine';
+import { PaintReservoir, LayerPixelSampler } from '../../utils/colorMixingEngine';
+import { applyLayerEffects } from '../../utils/layerEffectsEngine';
+import { PerspectiveRuler, ConstraintAxis } from '../../types/perspective';
+import { PerspectiveSnapSession } from '../../utils/perspectiveSnapping';
+import { useToolStore } from '../../stores';
+import {
+ DraftCanvasElement,
+ ExtendedPointerEvent,
+ LastStrokeEndState,
+ PushHistoryStepFn,
+ applySelectionCanvasClip,
+ applySelectionMaskToImageData,
+ isBackgroundLayerId,
+} from './types';
+import { commitVectorStrokeOrErase } from './useVectorDrawing';
+
+export interface UseBrushStrokeSessionParams {
+ disabled: boolean;
+ activeSessionId?: string | null;
+ viewportRef: React.RefObject<HTMLDivElement | null>;
+ interactionRef: React.MutableRefObject<HTMLDivElement | null>;
+ isDrawingRef: React.MutableRefObject<boolean>;
+ lastStrokeEndRef: React.MutableRefObject<LastStrokeEndState | null>;
+ panRef: React.MutableRefObject<{ x: number; y: number }>;
+ zoomRef: React.MutableRefObject<number>;
+ rotationRef: React.MutableRefObject<number>;
+ flipXRef: React.MutableRefObject<boolean>;
+ flipYRef: React.MutableRefObject<boolean>;
+ toolOverrideRef: React.MutableRefObject<ToolType | undefined>;
+ brushSettingsOverrideRef: React.MutableRefObject<BrushSettings | undefined>;
+ colorModeRef: React.MutableRefObject<CanvasColorMode>;
+ activeLayerIdRef: React.MutableRefObject<string>;
+ activeLayerLockedRef: React.MutableRefObject<boolean>;
+ activeLayerVisibleRef: React.MutableRefObject<boolean>;
+ dimensionsRef: React.MutableRefObject<CanvasDimensions>;
+ selectionRef: React.MutableRefObject<CanvasSelection | null>;
+ isMaskModeRef: React.MutableRefObject<boolean>;
+ layersRef: React.MutableRefObject<LayerItem[] | undefined>;
+ layerSourceCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ effectiveDraftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ predictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
+ activeTileGridRef: React.MutableRefObject<SparseTileGrid>;
+ rulerRef: React.MutableRefObject<PerspectiveRuler | null | undefined>;
+ onActiveConstraintAxisChangeRef: React.MutableRefObject<
+ ((axis: ConstraintAxis | null) => void) | undefined
+ >;
+ onUpdateLayerThumbnail: (layerId: string) => void;
+ onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;
+ onCollabStrokeStartRef: React.MutableRefObject<
+ | ((
+ strokeId: string,
+ layerId: string,
+ brushSettings: BrushSettings,
+ tool: ToolType,
+ startPoint: Point
+ ) => void)
+ | undefined
+ >;
+ onCollabStrokeChunkRef: React.MutableRefObject<
+ ((strokeId: string, points: Point[]) => void) | undefined
+ >;
+ onCollabStrokeFinishRef: React.MutableRefObject<
+ | ((
+ strokeId: string,
+ layerId: string,
+ endPoint: Point,
+ dirtyRect?: DirtyRect,
+ vectorStroke?: VectorStroke
+ ) => void)
+ | undefined
+ >;
+ onCollabCursorMoveRef: React.MutableRefObject<
+ ((x: number, y: number, isDrawing: boolean, tool: ToolType) => void) | undefined
+ >;
+ getCachedLayerCanvas: (layerId?: string) => HTMLCanvasElement | null;
+ pushHistoryStep: PushHistoryStepFn;
+ flushPendingHistoryTasks: () => void;
+ enqueueHistoryTask: (task: () => void) => void;
+}
+
+export interface UseBrushStrokeSessionResult {
+ abortActiveStroke: () => void;
+ handlePointerDown: (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => void;
+ handlePointerMove: (
+ e: React.PointerEvent<HTMLElement>,
+ coalescedEvents?: PointerEvent[],
+ predictedEvents?: PointerEvent[]
+ ) => void;
+ handlePointerUp: (e: React.PointerEvent<HTMLElement>) => void;
+ handlePointerEnter: () => void;
+ handlePointerLeave: () => void;
+}
+
+export function useBrushStrokeSession({
+ disabled,
+ activeSessionId,
+ viewportRef,
+ interactionRef,
+ isDrawingRef,
+ lastStrokeEndRef,
+ panRef,
+ zoomRef,
+ rotationRef,
+ flipXRef,
+ flipYRef,
+ toolOverrideRef,
+ brushSettingsOverrideRef,
+ colorModeRef,
+ activeLayerIdRef,
+ activeLayerLockedRef,
+ activeLayerVisibleRef,
+ dimensionsRef,
+ selectionRef,
+ isMaskModeRef,
+ layersRef,
+ layerSourceCanvasesRef,
+ effectiveDraftCanvasRef,
+ predictedCanvasRef,
+ activeTileGridRef,
+ rulerRef,
+ onActiveConstraintAxisChangeRef,
+ onUpdateLayerThumbnail,
+ onUpdateMaskThumbnailRef,
+ onCollabStrokeStartRef,
+ onCollabStrokeChunkRef,
+ onCollabStrokeFinishRef,
+ onCollabCursorMoveRef,
+ getCachedLayerCanvas,
+ pushHistoryStep,
+ flushPendingHistoryTasks,
+ enqueueHistoryTask,
+}: UseBrushStrokeSessionParams): UseBrushStrokeSessionResult {
+ const getTool = useCallback(
+ (): ToolType => toolOverrideRef.current ?? useToolStore.getState().tool,
+ [toolOverrideRef]
+ );
+ const getBrushSettings = useCallback(
+ (): BrushSettings =>
+ brushSettingsOverrideRef.current ?? useToolStore.getState().brushSettings,
+ [brushSettingsOverrideRef]
+ );
+
+ const currentStrokeIdRef = useRef<string | null>(null);
+ const isToneStrokeRef = useRef(false);
+ const activePointerIdRef = useRef<number | null>(null);
+
+ const isPredictedCanvasDirtyRef = useRef(false);
+ const latestPredictedRef = useRef<{ predEvents: PointerEvent[]; vRect: DOMRect } | null>(null);
+
+ const getPredictedCanvas = useCallback((): HTMLCanvasElement | null => {
+ if (predictedCanvasRef?.current) return predictedCanvasRef.current;
+ if (typeof document !== 'undefined') {
+ return document.getElementById('ink-predicted-canvas') as HTMLCanvasElement | null;
+ }
+ return null;
+ }, [predictedCanvasRef]);
+
+ const clearPredictedCanvas = useCallback(() => {
+ latestPredictedRef.current = null;
+ if (!isPredictedCanvasDirtyRef.current) return;
+ const pCanvas = getPredictedCanvas();
+ if (pCanvas) {
+ const pCtx = get2DContext(pCanvas);
+ if (pCtx) {
+ pCtx.resetTransform();
+ pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
+ }
+ }
+ isPredictedCanvasDirtyRef.current = false;
+ }, [getPredictedCanvas]);
+
+ const snapSessionRef = useRef(new PerspectiveSnapSession());
+ const lastEmittedAxisRef = useRef<ConstraintAxis | null>(null);
+ const emitConstraintAxisChange = useCallback(
+ (newAxis: ConstraintAxis | null) => {
+ const prev = lastEmittedAxisRef.current;
+ if (prev === newAxis) return;
+ if (
+ prev &&
+ newAxis &&
+ prev.type === newAxis.type &&
+ prev.origin.x === newAxis.origin.x &&
+ prev.origin.y === newAxis.origin.y &&
+ prev.dir.x === newAxis.dir.x &&
+ prev.dir.y === newAxis.dir.y
+ ) {
+ return;
+ }
+ lastEmittedAxisRef.current = newAxis;
+ onActiveConstraintAxisChangeRef.current?.(newAxis);
+ },
+ [onActiveConstraintAxisChangeRef]
+ );
+
+ const allStrokePointsRef = useRef<Point[]>([]);
+ const strokePipelineRef = useRef(new StrokePipeline());
+ const frameGpuDabsRef = useRef<GpuDab[]>([]);
+ const scratchDocCoordRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
+ const predCoordPoolRef = useRef<Array<{ x: number; y: number; pressure?: number }>>([
+ { x: 0, y: 0, pressure: 0.5 },
+ { x: 0, y: 0, pressure: 0.5 },
+ { x: 0, y: 0, pressure: 0.5 },
+ { x: 0, y: 0, pressure: 0.5 },
+ ]);
+ const predDocCoordsRef = useRef<Array<{ x: number; y: number; pressure?: number }>>([]);
+ const predDabCounterRef = useRef<{ count: number }>({ count: 0 });
+ const lastQueuedPressureRef = useRef<number>(0.5);
+ const stabilizedPointRef = useRef<Point | null>(null);
+ const stampRemainderDistRef = useRef<number>(0);
+ const liveDabCounterRef = useRef<{ count: number }>({ count: 0 });
+ const activeReservoirRef = useRef<PaintReservoir | null>(null);
+ const layerPixelSamplerRef = useRef<LayerPixelSampler | null>(null);
+ const isWetColorStrokeRef = useRef<boolean>(false);
+ const liveNeedsNotifyRef = useRef<boolean>(false);
+ const isShiftLineStrokeRef = useRef<boolean>(false);
+ const lastPointTimeRef = useRef<number>(0);
+ const recentPointsTrailRef = useRef<
+ { x: number; y: number; t: number; pressure: number; width: number }[]
+ >([]);
+ const strokeTotalDistanceRef = useRef<number>(0);
+ const dirtyRectRef = useRef<{
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+ } | null>(null);
+ const touchedTilesRef = useRef<Set<number>>(new Set());
+ const lastProcessedPointRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
+ const hasLastProcessedPointRef = useRef<boolean>(false);
+ const drawRafIdRef = useRef<number | null>(null);
+ const clearDraftRafRef = useRef<number | null>(null);
+
+ const markTouchedTiles = useCallback(
+ (minX: number, minY: number, maxX: number, maxY: number) => {
+ const dims = dimensionsRef.current;
+ const cx0 = Math.max(0, Math.floor(minX));
+ const cy0 = Math.max(0, Math.floor(minY));
+ const cx1 = Math.min(dims.width, Math.ceil(maxX));
+ const cy1 = Math.min(dims.height, Math.ceil(maxY));
+ if (cx1 <= cx0 || cy1 <= cy0) return;
+ const tx0 = Math.floor(cx0 / TILE_SIZE);
+ const ty0 = Math.floor(cy0 / TILE_SIZE);
+ const tx1 = Math.floor((cx1 - 1) / TILE_SIZE);
+ const ty1 = Math.floor((cy1 - 1) / TILE_SIZE);
+ const set = touchedTilesRef.current;
+ for (let ty = ty0; ty <= ty1; ty++) {
+ for (let tx = tx0; tx <= tx1; tx++) {
+ set.add(ty * 65536 + tx);
+ }
+ }
+ },
+ [dimensionsRef]
+ );
+
+ const statRafRef = useRef<number | null>(null);
+ const pendingStatRef = useRef<{ x: number | null; y: number | null; pressure: number } | null>(
+ null
+ );
+ const cachedViewportRectRef = useRef<DOMRect | null>(null);
+
+ const getViewportRect = useCallback((): DOMRect | null => {
+ if (!cachedViewportRectRef.current && viewportRef.current) {
+ cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
+ }
+ return cachedViewportRectRef.current;
+ }, [viewportRef]);
+
+ useEffect(() => {
+ const handleResize = () => {
+ cachedViewportRectRef.current = null;
+ };
+ window.addEventListener('resize', handleResize);
+ window.addEventListener('scroll', handleResize, true);
+ let ro: ResizeObserver | null = null;
+ if (typeof ResizeObserver !== 'undefined' && viewportRef.current) {
+ ro = new ResizeObserver(handleResize);
+ ro.observe(viewportRef.current);
+ }
+ return () => {
+ window.removeEventListener('resize', handleResize);
+ window.removeEventListener('scroll', handleResize, true);
+ ro?.disconnect();
+ if (clearDraftRafRef.current !== null) {
+ cancelAnimationFrame(clearDraftRafRef.current);
+ }
+ if (drawRafIdRef.current !== null) {
+ cancelAnimationFrame(drawRafIdRef.current);
+ }
+ };
+ }, [viewportRef, disabled, activeSessionId]);
+
+ const dispatchPointerStat = useCallback(
+ (x: number | null, y: number | null, pressure: number) => {
+ pendingStatRef.current = {
+ x: x !== null ? Math.round(x) : null,
+ y: y !== null ? Math.round(y) : null,
+ pressure,
+ };
+ if (statRafRef.current === null) {
+ statRafRef.current = requestAnimationFrame(() => {
+ statRafRef.current = null;
+ if (pendingStatRef.current) {
+ window.dispatchEvent(
+ new CustomEvent('canvas-pointer-stat', {
+ detail: {
+ ...pendingStatRef.current,
+ isHovering: pendingStatRef.current.x !== null,
+ },
+ })
+ );
+ }
+ });
+ }
+ },
+ []
+ );
+
+ const abortActiveStroke = useCallback(() => {
+ if (!isDrawingRef.current) return;
+ if (drawRafIdRef.current !== null) {
+ cancelAnimationFrame(drawRafIdRef.current);
+ drawRafIdRef.current = null;
+ }
+ const draftCanvas = effectiveDraftCanvasRef?.current as DraftCanvasElement | null | undefined;
+ let clearedActiveDraft = false;
+ if (draftCanvas) {
+ const dCtx = get2DContext(draftCanvas);
+ if (dCtx) {
+ try {
+ dCtx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ dCtx.resetTransform();
+ dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ }
+ if (draftCanvas.__draftHasContent) {
+ clearedActiveDraft = true;
+ }
+ draftCanvas.__draftHasContent = false;
+ draftCanvas.__draftCompositeOp = 'source-over';
+ draftCanvas.__draftMonochrome = false;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ }
+ clearPredictedCanvas();
+ if (clearedActiveDraft) {
+ activeTileGridRef.current.notifyChange(true);
+ }
+ strokePipelineRef.current.abortStroke();
+ frameGpuDabsRef.current.length = 0;
+ isDrawingRef.current = false;
+ activePointerIdRef.current = null;
+ allStrokePointsRef.current = [];
+ stabilizedPointRef.current = null;
+ hasLastProcessedPointRef.current = false;
+ dirtyRectRef.current = null;
+ touchedTilesRef.current.clear();
+ liveNeedsNotifyRef.current = false;
+ isShiftLineStrokeRef.current = false;
+ isToneStrokeRef.current = false;
+ layerPixelSamplerRef.current = null;
+ activeReservoirRef.current = null;
+ snapSessionRef.current.endStroke();
+ emitConstraintAxisChange(null);
+ }, [
+ activeTileGridRef,
+ clearPredictedCanvas,
+ effectiveDraftCanvasRef,
+ emitConstraintAxisChange,
+ isDrawingRef,
+ ]);
+
+ const getCanvasPoint = useCallback(
+ (e: React.PointerEvent<HTMLElement> | PointerEvent): Point => {
+ const vRect = getViewportRect();
+ const dims = dimensionsRef.current;
+ const bs = getBrushSettings();
+ if (!vRect) {
+ return { x: 0, y: 0, pressure: 0.5, width: bs.size, timestamp: e.timeStamp };
+ }
+
+ const { x, y } = screenToCanvas(
+ e.clientX,
+ e.clientY,
+ vRect,
+ panRef.current,
+ zoomRef.current,
+ rotationRef.current,
+ dims,
+ flipXRef.current,
+ flipYRef.current
+ );
+
+ let pressure = 0;
+ if (e.pointerType === 'mouse') {
+ pressure = e.buttons & 1 ? 0.5 : 0;
+ } else {
+ pressure =
+ e.pressure !== undefined ? Math.max(0, Math.min(1.0, e.pressure)) : 0;
+ }
+
+ const width = calculateStrokeWidth(
+ bs.size,
+ pressure,
+ bs.minSizeFactor,
+ bs.usePressure,
+ e.pointerType,
+ bs.pressureCurveGamma ?? 1.0,
+ 1.0,
+ bs.pressureCurve
+ );
+
+ return {
+ x,
+ y,
+ pressure,
+ width,
+ tiltX: e.tiltX ?? 0,
+ tiltY: e.tiltY ?? 0,
+ twist: e.twist ?? 0,
+ timestamp: e.timeStamp,
+ };
+ },
+ [dimensionsRef, flipXRef, flipYRef, getBrushSettings, getViewportRect, panRef, rotationRef, zoomRef]
+ );
+
+ const buildLiveTexturedOptions = useCallback(
+ (
+ bs: BrushSettings,
+ strokeFlow: number,
+ strokeSpacing: number,
+ strokeHardness: number,
+ isMonochrome: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isolatedPass: boolean = false
+ ): TexturedBrushOptions => ({
+ size: bs.size,
+ minSizeFactor: bs.minSizeFactor,
+ opacity: isolatedPass ? 1.0 : bs.opacity,
+ flow: strokeFlow,
+ adjustDensityByGap: bs.adjustDensityByGap,
+ blendTipsMode: bs.blendTipsMode,
+ spacing: strokeSpacing,
+ thickness: bs.thickness,
+ thicknessVertical: bs.thicknessVertical,
+ flipH: bs.flipH,
+ flipV: bs.flipV,
+ isColorTip: bs.isColorTip,
+ angle: bs.customTipAngle,
+ angleDynamics: bs.customTipAngleDynamics,
+ rotationRandomScale: bs.customTipRotationRandomScale,
+ hardness: strokeHardness,
+ antiAlias: isMonochrome ? 0 : bs.antiAlias,
+ pressureCurve: bs.pressureCurve,
+ velocityCurve: bs.velocityCurve,
+ usePressure: bs.usePressure,
+ useVelocity: bs.useVelocity,
+ useTilt: Boolean(bs.useTilt),
+ sizeSensor: bs.sizeSensor,
+ opacitySensor: bs.opacitySensor,
+ densitySensor: bs.densitySensor,
+ subTips: bs.subTips,
+ subTipOrder: bs.subTipOrder,
+ subTipImages: bs.subTipImages,
+ spray: bs.spray,
+ taper: bs.taper,
+ colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
+ amountOfPaint: bs.amountOfPaint,
+ densityOfPaint: bs.densityOfPaint,
+ colorStretch: bs.colorStretch,
+ mixingMode: bs.mixingMode,
+ wetEdge: 0,
+ grain: bs.grain ?? bs.textureDensity,
+ paperTextureMode: bs.paperTextureMode,
+ paperTextureBrightness: bs.paperTextureBrightness,
+ paperTextureContrast: bs.paperTextureContrast,
+ paperTextureInverted: bs.paperTextureInverted,
+ paperTextureImage: bs.paperTextureImage,
+ paperTextureScale: bs.paperTextureScale,
+ paperTextureRotate: bs.paperTextureRotate,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ useGpu: bs.useGpu !== false,
+ underlyingCanvas: canvas || undefined,
+ sampler: layerPixelSamplerRef.current || undefined,
+ reservoir: activeReservoirRef.current || undefined,
+ isEraser: isolatedPass ? false : isEraser && !isBgEraser,
+ isBgEraser: isolatedPass ? false : isBgEraser,
+ alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
+ currentStrokeDist: strokeTotalDistanceRef.current,
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ }),
+ []
+ );
+
+ const buildLiveRadialOptions = useCallback(
+ (
+ bs: BrushSettings,
+ isMonochrome: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ isolatedPass: boolean = false
+ ): RadialMixingOptions => ({
+ colorMixing: bs.colorMixing,
+ perceptualMixing: bs.perceptualMixing,
+ amountOfPaint: bs.amountOfPaint,
+ densityOfPaint: bs.densityOfPaint,
+ colorStretch: bs.colorStretch,
+ mixingMode: bs.mixingMode,
+ underlyingCanvas: canvas || undefined,
+ sampler: layerPixelSamplerRef.current || undefined,
+ reservoir: activeReservoirRef.current || undefined,
+ alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
+ isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ useGpu: bs.useGpu !== false,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ useTilt: Boolean(bs.useTilt),
+ thicknessVertical: bs.thicknessVertical,
+ flipH: bs.flipH,
+ flipV: bs.flipV,
+ antiAlias: isMonochrome ? 0 : bs.antiAlias,
+ angleDynamics: bs.customTipAngleDynamics,
+ rotationRandomScale: bs.customTipRotationRandomScale,
+ adjustDensityByGap: bs.adjustDensityByGap,
+ blendTipsMode: bs.blendTipsMode,
+ grain: bs.grain ?? bs.textureDensity,
+ paperTextureMode: bs.paperTextureMode,
+ paperTextureBrightness: bs.paperTextureBrightness,
+ paperTextureContrast: bs.paperTextureContrast,
+ paperTextureInverted: bs.paperTextureInverted,
+ paperTextureImage: bs.paperTextureImage,
+ paperTextureScale: bs.paperTextureScale,
+ paperTextureRotate: bs.paperTextureRotate,
+ sizeSensor: bs.sizeSensor,
+ opacitySensor: bs.opacitySensor,
+ densitySensor: bs.densitySensor,
+ taper: bs.taper,
+ }),
+ []
+ );
+
+ const resolveStrokeColor = useCallback(
+ (
+ bs: BrushSettings,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ isMonochrome: boolean,
+ mode: CanvasColorMode
+ ): string => {
+ if (isMaskModeRef.current) {
+ if (isEraser) return '#000000';
+ let clean = bs.color.replace('#', '');
+ if (clean.length === 3) {
+ clean = clean
+ .split('')
+ .map((c) => c + c)
+ .join('');
+ }
+ const r = parseInt(clean.slice(0, 2), 16) || 0;
+ const g = parseInt(clean.slice(2, 4), 16) || 0;
+ const b = parseInt(clean.slice(4, 6), 16) || 0;
+ const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
+ const hexVal = gray.toString(16).padStart(2, '0');
+ return `#${hexVal}${hexVal}${hexVal}`;
+ }
+ return isBgEraser
+ ? '#ffffff'
+ : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
+ },
+ [isMaskModeRef]
+ );
+
+ const emitLiveSegment = useCallback(
+ (
+ draftCtx: CanvasRenderingContext2D,
+ seg: CubicBezierSegment,
+ bs: BrushSettings,
+ strokeColor: string,
+ strokeHardness: number,
+ strokeFlow: number,
+ strokeSpacing: number,
+ isMonochrome: boolean,
+ isPencil: boolean,
+ isEraser: boolean,
+ isBgEraser: boolean,
+ useWireframeEraser: boolean,
+ canvas: HTMLCanvasElement | null,
+ activeLayer: LayerItem | undefined,
+ gpuBatch: GpuDab[] | undefined
+ ) => {
+ const sStart = seg.p0;
+ const c1Pt = seg.c1;
+ const c2Pt = seg.c2;
+ const sEnd = seg.p3;
+
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const segPad = Math.ceil(
+ Math.max(sStart.width, sEnd.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32
+ );
+ const segMinX = Math.min(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) - segPad;
+ const segMinY = Math.min(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) - segPad;
+ const segMaxX = Math.max(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) + segPad;
+ const segMaxY = Math.max(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) + segPad;
+ strokePipelineRef.current.expandDirtyRectBounds(segMinX, segMinY, segMaxX, segMaxY);
+ markTouchedTiles(segMinX, segMinY, segMaxX, segMaxY);
+
+ if (useWireframeEraser) {
+ draftCtx.save();
+ draftCtx.lineCap = 'round';
+ draftCtx.lineJoin = 'round';
+ draftCtx.setLineDash([4, 4]);
+ draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
+ draftCtx.lineWidth = Math.max(1, (sStart.width + sEnd.width) / 2);
+ draftCtx.beginPath();
+ draftCtx.moveTo(sStart.x, sStart.y);
+ draftCtx.bezierCurveTo(c1Pt.x, c1Pt.y, c2Pt.x, c2Pt.y, sEnd.x, sEnd.y);
+ draftCtx.stroke();
+ draftCtx.restore();
+ return;
+ }
+
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ const draftCanvas = effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ const draftScale = draftCanvas?.__draftScale ?? 1.0;
+ const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+
+ if (bs.customTipImage) {
+ const tipOptions = buildLiveTexturedOptions(
+ bs,
+ isMonochrome ? 1.0 : bs.flow ?? 1.0,
+ bs.spacing ?? 0.08,
+ strokeHardness,
+ downscaledBinary ? false : isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true
+ );
+ if (downscaledBinary && tipOptions.antiAlias === 0) {
+ tipOptions.antiAlias = 2;
+ }
+ stampRemainderDistRef.current = drawTexturedCubicBezierSegment(
+ draftCtx,
+ sStart,
+ c1Pt,
+ c2Pt,
+ sEnd,
+ liveColor,
+ bs.customTipImage,
+ tipOptions,
+ stampRemainderDistRef.current,
+ liveDabCounterRef.current,
+ gpuBatch
+ );
+ } else if (isPencil) {
+ const grade = (bs.preset as PencilGrade) || 'pencil-2b';
+ stampRemainderDistRef.current = drawPencilCubicBezierSegment(
+ draftCtx,
+ sStart,
+ c1Pt,
+ c2Pt,
+ sEnd,
+ liveColor,
+ grade,
+ isMonochrome ? 1.0 : bs.flow ?? 0.74,
+ bs.grain ?? 1.0,
+ strokeHardness,
+ stampRemainderDistRef.current,
+ false,
+ false,
+ bs.useTilt ?? true
+ );
+ } else {
+ const radialMixingOptions = buildLiveRadialOptions(
+ bs,
+ downscaledBinary ? false : isMonochrome,
+ canvas,
+ activeLayer,
+ true
+ );
+ if (downscaledBinary && radialMixingOptions.antiAlias === 0) {
+ radialMixingOptions.antiAlias = 2;
+ }
+ stampRemainderDistRef.current = drawSmoothCubicBezierSegment(
+ draftCtx,
+ sStart,
+ c1Pt,
+ c2Pt,
+ sEnd,
+ liveColor,
+ false,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ stampRemainderDistRef.current,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180,
+ radialMixingOptions,
+ gpuBatch
+ );
+ }
+ },
+ [
+ buildLiveRadialOptions,
+ buildLiveTexturedOptions,
+ effectiveDraftCanvasRef,
+ markTouchedTiles,
+ ]
+ );
+
+ const renderPredictedStroke = useCallback(
+ (predEvents: PointerEvent[], vRect: DOMRect) => {
+ clearPredictedCanvas();
+ const bs = getBrushSettings();
+ if (getTool() === 'eraser' || bs.isTransparentInk) return;
+ const pipeline = strokePipelineRef.current;
+ if (pipeline.getKnotCount() < 2) return;
+ const pCanvas = getPredictedCanvas();
+ if (!pCanvas) return;
+ const pCtx = get2DContext(pCanvas);
+ if (!pCtx) return;
+
+ const dims = dimensionsRef.current;
+ const mode = colorModeRef.current;
+ const currentLayerId = activeLayerIdRef.current;
+ const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const isPencil = !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
+ const strokeColor = resolveStrokeColor(bs, false, false, isMonochrome, mode);
+ const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
+ const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
+ const strokeSpacing = bs.spacing ?? 0.08;
+
+ const maxPredDist = Math.min(20, Math.max(4, (bs.size || 10) * 1.15));
+ const predCoords = predDocCoordsRef.current;
+ predCoords.length = 0;
+
+ if (predEvents && predEvents.length > 0) {
+ const scratch = scratchDocCoordRef.current;
+ const pool = predCoordPoolRef.current;
+ const limit = Math.min(predEvents.length, pool.length);
+ for (let i = 0; i < limit; i++) {
+ const ev = predEvents[i];
+ screenToCanvasInto(
+ ev.clientX,
+ ev.clientY,
+ vRect,
+ panRef.current,
+ zoomRef.current,
+ rotationRef.current,
+ dims,
+ scratch,
+ flipXRef.current,
+ flipYRef.current
+ );
+ const slot = pool[i];
+ slot.x = scratch.x;
+ slot.y = scratch.y;
+ slot.pressure = ev.pressure;
+ predCoords.push(slot);
+ }
+ }
+
+ const scaleX = pCanvas.width / Math.max(1, vRect.width);
+ const scaleY = pCanvas.height / Math.max(1, vRect.height);
+ const matrix = getCanvasToViewportMatrix(
+ panRef.current,
+ zoomRef.current,
+ rotationRef.current,
+ dims,
+ scaleX,
+ scaleY,
+ flipXRef.current,
+ flipYRef.current
+ );
+
+ pCtx.save();
+ pCtx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
+ pCtx.beginPath();
+ pCtx.rect(0, 0, dims.width, dims.height);
+ pCtx.clip();
+ applySelectionCanvasClip(pCtx, selectionRef.current);
+
+ let predRem = stampRemainderDistRef.current;
+ const predAA =
+ isMonochrome && zoomRef.current < 1.0 ? 2 : isMonochrome ? 0 : bs.antiAlias;
+ const predTipOpts: TexturedBrushOptions | null = bs.customTipImage
+ ? {
+ size: bs.size,
+ minSizeFactor: bs.minSizeFactor,
+ opacity: 1.0,
+ flow: strokeFlow,
+ spacing: strokeSpacing,
+ thickness: bs.thickness,
+ thicknessVertical: bs.thicknessVertical,
+ angle: bs.customTipAngle,
+ angleDynamics: bs.customTipAngleDynamics,
+ rotationRandomScale: bs.customTipRotationRandomScale,
+ hardness: strokeHardness,
+ antiAlias: predAA,
+ pressureCurve: bs.pressureCurve,
+ usePressure: bs.usePressure,
+ subTips: bs.subTips,
+ subTipOrder: bs.subTipOrder,
+ subTipImages: bs.subTipImages,
+ spray: bs.spray,
+ wetEdge: 0,
+ grain: bs.grain ?? bs.textureDensity,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ useGpu: bs.useGpu !== false,
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ }
+ : null;
+ const predRadialOpts: RadialMixingOptions = {
+ useGpu: bs.useGpu !== false,
+ antiAlias: predAA,
+ dynamics: bs.dynamics,
+ secondaryColor: bs.secondaryColor,
+ dualBrush: bs.dualBrush,
+ dualTipImage: bs.dualTipImage,
+ dualBrushCompositeMode: bs.dualBrushCompositeMode,
+ grain: bs.grain ?? bs.textureDensity,
+ };
+
+ const predGpuDabs = frameGpuDabsRef.current;
+ predGpuDabs.length = 0;
+ const useGpuPred = bs.customTipImage
+ ? Boolean(predTipOpts && canUseWebGlForTexturedBrush(predTipOpts))
+ : !isPencil && canUseWebGlForRadialBrush(predRadialOpts);
+
+ predDabCounterRef.current.count = liveDabCounterRef.current.count;
+ const minPredMonoWidth =
+ isMonochrome && zoomRef.current < 0.99
+ ? 1.35 / Math.max(0.01, zoomRef.current)
+ : 0;
+
+ const drew = pipeline.buildPredictedSegments(null, maxPredDist, (seg) => {
+ const p0 =
+ minPredMonoWidth > 0 && seg.p0.width < minPredMonoWidth
+ ? { ...seg.p0, width: minPredMonoWidth }
+ : seg.p0;
+ const p3 =
+ minPredMonoWidth > 0 && seg.p3.width < minPredMonoWidth
+ ? { ...seg.p3, width: minPredMonoWidth }
+ : seg.p3;
+ if (bs.customTipImage && predTipOpts) {
+ predRem = drawTexturedCubicBezierSegment(
+ pCtx,
+ p0,
+ seg.c1,
+ seg.c2,
+ p3,
+ strokeColor,
+ bs.customTipImage,
+ predTipOpts,
+ predRem,
+ predDabCounterRef.current,
+ useGpuPred ? predGpuDabs : undefined
+ );
+ } else if (isPencil) {
+ const grade = (bs.preset as PencilGrade) || 'pencil-2b';
+ predRem = drawPencilCubicBezierSegment(
+ pCtx,
+ p0,
+ seg.c1,
+ seg.c2,
+ p3,
+ strokeColor,
+ grade,
+ isMonochrome ? 1.0 : bs.flow ?? 0.74,
+ bs.grain ?? 1.0,
+ strokeHardness,
+ predRem,
+ false,
+ false
+ );
+ } else {
+ predRem = drawSmoothCubicBezierSegment(
+ pCtx,
+ p0,
+ seg.c1,
+ seg.c2,
+ p3,
+ strokeColor,
+ false,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ predRem,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180,
+ predRadialOpts,
+ useGpuPred ? predGpuDabs : undefined
+ );
+ }
+ });
+
+ if (useGpuPred && predGpuDabs.length > 0) {
+ if (bs.customTipImage && predTipOpts) {
+ flushTexturedGpuDabs(pCtx, predGpuDabs, bs.customTipImage, strokeColor, predTipOpts);
+ } else {
+ flushRadialGpuDabs(
+ pCtx,
+ predGpuDabs,
+ strokeColor,
+ strokeHardness,
+ false,
+ false,
+ predRadialOpts
+ );
+ }
+ predGpuDabs.length = 0;
+ }
+
+ pCtx.restore();
+ if (drew) {
+ isPredictedCanvasDirtyRef.current = true;
+ }
+ },
+ [
+ activeLayerIdRef,
+ clearPredictedCanvas,
+ colorModeRef,
+ dimensionsRef,
+ flipXRef,
+ flipYRef,
+ getBrushSettings,
+ getPredictedCanvas,
+ getTool,
+ layersRef,
+ panRef,
+ resolveStrokeColor,
+ rotationRef,
+ selectionRef,
+ zoomRef,
+ ]
+ );
+
+ const flushPendingPoints = useCallback(() => {
+ drawRafIdRef.current = null;
+ if (!isDrawingRef.current) return;
+
+ const pipeline = strokePipelineRef.current;
+ if (pipeline.getPendingCount() === 0) {
+ const predData = latestPredictedRef.current;
+ latestPredictedRef.current = null;
+ const vRect = getViewportRect();
+ if (vRect && allStrokePointsRef.current.length > 0) {
+ renderPredictedStroke(predData ? predData.predEvents : [], vRect);
+ } else if (isPredictedCanvasDirtyRef.current) {
+ clearPredictedCanvas();
+ }
+ return;
+ }
+
+ const draftCanvas = effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ if (!draftCanvas) return;
+ const draftCtx = get2DContext(draftCanvas);
+ if (!draftCtx) return;
+
+ const bs = getBrushSettings();
+ const mode = colorModeRef.current;
+ const isEraser = getTool() === 'eraser';
+ const currentLayerId = activeLayerIdRef.current;
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
+ const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
+ const isVectorOrToneOrMask =
+ activeLayer?.type === 'vector' || isToneStrokeRef.current || isMaskModeRef.current;
+ const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
+ const canvas = getCachedLayerCanvas();
+ const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
+ const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
+ const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
+ const strokeSpacing = bs.spacing ?? 0.08;
+ const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
+ const taperEngine = pipeline.getTaperEngine();
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const blurMargin = (1 - strokeHardness) * ((bs.size || 10) * 1.5);
+ const dirtyPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + blurMargin + 24);
+
+ const draftScale = draftCanvas.__draftScale ?? 1.0;
+ const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const liveTipOpts = bs.customTipImage
+ ? buildLiveTexturedOptions(
+ bs,
+ isMonochrome ? 1.0 : bs.flow ?? 1.0,
+ strokeSpacing,
+ strokeHardness,
+ downscaledBinary ? false : isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true
+ )
+ : null;
+ if (liveTipOpts && downscaledBinary && liveTipOpts.antiAlias === 0) {
+ liveTipOpts.antiAlias = 2;
+ }
+ const liveRadialOpts =
+ !bs.customTipImage && !isPencil
+ ? buildLiveRadialOptions(
+ bs,
+ downscaledBinary ? false : isMonochrome,
+ canvas,
+ activeLayer,
+ true
+ )
+ : null;
+ if (liveRadialOpts && downscaledBinary && liveRadialOpts.antiAlias === 0) {
+ liveRadialOpts.antiAlias = 2;
+ }
+ const useGpuBatch =
+ !useWireframeEraser &&
+ (bs.customTipImage
+ ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
+ : !isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts)));
+
+ const gpuBatch = frameGpuDabsRef.current;
+ gpuBatch.length = 0;
+
+ const collabActive = Boolean(currentStrokeIdRef.current && onCollabStrokeChunkRef.current);
+ const chunkPts: Point[] | null = collabActive ? [] : null;
+ let drewAnySegment = false;
+
+ pipeline.drain({
+ dirtyPadExtra,
+ resolvePoint: (rawX, rawY, rawPressure, stabPressure, pointerType, _vx, _vy, dtMs, out) => {
+ let velocityScale = 1.0;
+ if (bs.velocityDynamics && stabilizedPointRef.current) {
+ const dist = Math.hypot(
+ rawX - stabilizedPointRef.current.x,
+ rawY - stabilizedPointRef.current.y
+ );
+ const speed = dist / Math.max(1, dtMs);
+ velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
+ }
+
+ const baseP = bs.usePressure
+ ? hasCustomCurve
+ ? stabPressure
+ : taperEngine.mapPressure(stabPressure)
+ : rawPressure > 0
+ ? 1.0
+ : 0;
+ const mappedP = bs.usePressure ? taperEngine.smoothPressure(baseP) : baseP;
+ let width = calculateStrokeWidth(
+ bs.size,
+ mappedP,
+ bs.minSizeFactor,
+ bs.usePressure,
+ pointerType,
+ bs.pressureCurveGamma ?? 1.0,
+ velocityScale,
+ bs.pressureCurve
+ );
+ if (isMonochrome && width < 1.25) {
+ width = 1.25;
+ }
+ out.pressure = mappedP;
+ out.width = width;
+ },
+ onPoint: (sample) => {
+ const pt: Point = {
+ x: sample.x,
+ y: sample.y,
+ pressure: sample.pressure,
+ width: sample.width,
+ tiltX: sample.tiltX,
+ tiltY: sample.tiltY,
+ twist: sample.twist,
+ timestamp: sample.timestamp,
+ isCorner: sample.isCorner,
+ };
+ if (allStrokePointsRef.current.length > 0) {
+ const prev = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];
+ strokeTotalDistanceRef.current += Math.hypot(pt.x - prev.x, pt.y - prev.y);
+ }
+ stabilizedPointRef.current = pt;
+ lastPointTimeRef.current = sample.timestamp;
+ allStrokePointsRef.current.push(pt);
+ recentPointsTrailRef.current.push({
+ x: pt.x,
+ y: pt.y,
+ t: sample.timestamp || performance.now(),
+ pressure: pt.pressure,
+ width: pt.width,
+ });
+ if (recentPointsTrailRef.current.length > 16) {
+ recentPointsTrailRef.current.shift();
+ }
+ if (chunkPts) {
+ chunkPts.push(pt);
+ }
+ },
+ onSegment: (seg) => {
+ drewAnySegment = true;
+ emitLiveSegment(
+ draftCtx,
+ seg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isPencil,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ useGpuBatch ? gpuBatch : undefined
+ );
+ },
+ });
+
+ if (useGpuBatch && gpuBatch.length > 0) {
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ let flushed = false;
+ if (bs.customTipImage && liveTipOpts) {
+ flushed = flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, liveTipOpts);
+ } else if (liveRadialOpts) {
+ flushed = flushRadialGpuDabs(
+ draftCtx,
+ gpuBatch,
+ liveColor,
+ strokeHardness,
+ false,
+ false,
+ liveRadialOpts
+ );
+ }
+ if (!flushed) {
+ const pts = allStrokePointsRef.current;
+ if (pts.length >= 2) {
+ const pA = pts[pts.length - 2];
+ const pB = pts[pts.length - 1];
+ const fallbackSeg = pipeline.getSplineGenerator().generateCornerSegment(pA, pB);
+ emitLiveSegment(
+ draftCtx,
+ fallbackSeg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isPencil,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ undefined
+ );
+ }
+ }
+ gpuBatch.length = 0;
+ }
+
+ const pDirty = pipeline.dirtyRect;
+ if (Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)) {
+ const dims = dimensionsRef.current;
+ if (!dirtyRectRef.current) {
+ dirtyRectRef.current = {
+ minX: Math.max(0, pDirty.minX),
+ minY: Math.max(0, pDirty.minY),
+ maxX: Math.min(dims.width, pDirty.maxX),
+ maxY: Math.min(dims.height, pDirty.maxY),
+ };
+ } else {
+ dirtyRectRef.current.minX = Math.max(0, Math.min(dirtyRectRef.current.minX, pDirty.minX));
+ dirtyRectRef.current.minY = Math.max(0, Math.min(dirtyRectRef.current.minY, pDirty.minY));
+ dirtyRectRef.current.maxX = Math.min(dims.width, Math.max(dirtyRectRef.current.maxX, pDirty.maxX));
+ dirtyRectRef.current.maxY = Math.min(dims.height, Math.max(dirtyRectRef.current.maxY, pDirty.maxY));
+ }
+ }
+
+ if (drewAnySegment) {
+ draftCanvas.__draftHasContent = true;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ liveNeedsNotifyRef.current = true;
+ }
+
+ if (currentStrokeIdRef.current && chunkPts && chunkPts.length > 0) {
+ onCollabStrokeChunkRef.current?.(currentStrokeIdRef.current, chunkPts);
+ }
+
+ if (liveNeedsNotifyRef.current) {
+ liveNeedsNotifyRef.current = false;
+ activeTileGridRef.current.notifyChange();
+ }
+
+ const predData = latestPredictedRef.current;
+ latestPredictedRef.current = null;
+ const vRect = getViewportRect();
+ if (vRect && allStrokePointsRef.current.length > 0) {
+ renderPredictedStroke(predData ? predData.predEvents : [], vRect);
+ } else if (isPredictedCanvasDirtyRef.current) {
+ clearPredictedCanvas();
+ }
+ }, [
+ activeLayerIdRef,
+ activeTileGridRef,
+ buildLiveRadialOptions,
+ buildLiveTexturedOptions,
+ clearPredictedCanvas,
+ colorModeRef,
+ dimensionsRef,
+ effectiveDraftCanvasRef,
+ emitLiveSegment,
+ getBrushSettings,
+ getCachedLayerCanvas,
+ getTool,
+ getViewportRect,
+ isDrawingRef,
+ isMaskModeRef,
+ layersRef,
+ onCollabStrokeChunkRef,
+ renderPredictedStroke,
+ resolveStrokeColor,
+ ]);
+
+ const handlePointerDown = useCallback(
+ (e: React.PointerEvent<HTMLElement>, _coalescedEvents?: PointerEvent[]) => {
+ const currentTool = getTool();
+ const isBrushOrEraser = currentTool === 'brush' || currentTool === 'eraser';
+ if (
+ !isBrushOrEraser ||
+ disabled ||
+ e.button !== 0 ||
+ activeLayerLockedRef.current ||
+ !activeLayerVisibleRef.current
+ ) {
+ return;
+ }
+ e.preventDefault();
+ if (isDrawingRef.current) {
+ abortActiveStroke();
+ }
+ flushPendingHistoryTasks();
+
+ const dims = dimensionsRef.current;
+ const currentLayerIdCheck = activeLayerIdRef.current;
+ if (!currentLayerIdCheck || dims.width <= 0 || dims.height <= 0) return;
+
+ const canvas = getCachedLayerCanvas();
+ if (isMaskModeRef.current && !canvas) return;
+
+ if (viewportRef.current) {
+ cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
+ }
+ const vRect = getViewportRect();
+ if (!vRect) return;
+
+ const draftCanvas = effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ if (!draftCanvas) return;
+
+ if (clearDraftRafRef.current !== null) {
+ cancelAnimationFrame(clearDraftRafRef.current);
+ clearDraftRafRef.current = null;
+ }
+
+ const draftCtx = get2DContext(draftCanvas);
+ if (!draftCtx) return;
+
+ const isEraser = currentTool === 'eraser';
+ const currentLayerId = activeLayerIdRef.current;
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
+ const allLayers = layersRef.current || [];
+ const activeLayer = allLayers.find((l) => l.id === currentLayerId);
+ const bs = getBrushSettings();
+ const mode = colorModeRef.current;
+ const isPencil =
+ !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const isTone = Boolean(activeLayer?.toneEnabled);
+ const isVectorLayer = activeLayer?.type === 'vector';
+ const isVectorOrToneOrMask = isVectorLayer || isTone || isMaskModeRef.current;
+ const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
+ isToneStrokeRef.current = isTone;
+
+ const draftCompositeOp: GlobalCompositeOperation =
+ isVectorOrToneOrMask || isBgEraser
+ ? 'source-over'
+ : isEraser || bs.isTransparentInk
+ ? 'destination-out'
+ : activeLayer?.alphaLocked
+ ? 'source-atop'
+ : 'source-over';
+
+ const rawVis = getVisibleCanvasBounds(
+ vRect,
+ panRef.current,
+ zoomRef.current,
+ rotationRef.current,
+ dims,
+ 128,
+ flipXRef.current,
+ flipYRef.current
+ );
+ const visMinX = rawVis.maxX > rawVis.minX ? rawVis.minX : 0;
+ const visMinY = rawVis.maxY > rawVis.minY ? rawVis.minY : 0;
+ const visW = Math.max(1, rawVis.maxX > rawVis.minX ? rawVis.maxX - rawVis.minX : dims.width);
+ const visH = Math.max(1, rawVis.maxY > rawVis.minY ? rawVis.maxY - rawVis.minY : dims.height);
+ const MAX_DRAFT_DIM = 2048;
+ const draftScale = Math.min(1.0, MAX_DRAFT_DIM / Math.max(visW, visH));
+ const surfaceW = Math.max(1, Math.ceil(visW * draftScale));
+ const surfaceH = Math.max(1, Math.ceil(visH * draftScale));
+ if (draftCanvas.width !== surfaceW || draftCanvas.height !== surfaceH) {
+ draftCanvas.width = surfaceW;
+ draftCanvas.height = surfaceH;
+ }
+
+ draftCtx.resetTransform();
+ draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ draftCanvas.__draftHasContent = false;
+ draftCanvas.__draftCompositeOp = draftCompositeOp;
+ draftCanvas.__draftSpace = 'document';
+ draftCanvas.__draftDocRect = {
+ x: visMinX,
+ y: visMinY,
+ width: surfaceW / draftScale,
+ height: surfaceH / draftScale,
+ };
+ draftCanvas.__draftScale = draftScale;
+ draftCanvas.__draftMonochrome = isMonochrome;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+
+ draftCtx.setTransform(
+ draftScale,
+ 0,
+ 0,
+ draftScale,
+ -visMinX * draftScale,
+ -visMinY * draftScale
+ );
+ draftCtx.save();
+ draftCtx.beginPath();
+ draftCtx.rect(0, 0, dims.width, dims.height);
+ draftCtx.clip();
+ applySelectionCanvasClip(draftCtx, selectionRef.current);
+
+ clearPredictedCanvas();
+
+ if (isTone) {
+ let sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId) || null;
+ if (!sourceCanvas) {
+ sourceCanvas = document.createElement('canvas');
+ sourceCanvas.width = dims.width;
+ sourceCanvas.height = dims.height;
+ if (canvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ sCtx?.drawImage(canvas, 0, 0);
+ } else {
+ activeTileGridRef.current.renderLayerToCanvas(currentLayerId, sourceCanvas);
+ }
+ layerSourceCanvasesRef?.current?.set(currentLayerId, sourceCanvas);
+ }
+ }
+
+ if (interactionRef.current) {
+ try {
+ interactionRef.current.setPointerCapture(e.pointerId);
+ } catch {
+ // Ignore pointer capture errors
+ }
+ }
+ activePointerIdRef.current = e.pointerId;
+ isDrawingRef.current = true;
+
+ const firstEvent = e.nativeEvent;
+ const rawStartPoint = getCanvasPoint(firstEvent);
+ const isAltOverride = e.altKey;
+ const startPoint = snapSessionRef.current.snapPoint(
+ rawStartPoint,
+ rulerRef.current ?? null,
+ isAltOverride
+ );
+ emitConstraintAxisChange(snapSessionRef.current.getActiveAxis());
+
+ const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
+ const strokeHardness = isMonochrome ? 1.0 : bs.hardness ?? 1.0;
+ const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
+ const strokeSpacing = bs.spacing ?? 0.08;
+
+ const pipeline = strokePipelineRef.current;
+ pipeline.beginStroke({
+ stabilizerLevel: bs.stabilization ?? 0,
+ zoom: zoomRef.current || 1.0,
+ sharpCorners: bs.sharpCorners !== false,
+ brushSize: bs.size,
+ color: strokeColor,
+ pointerId: e.pointerId,
+ });
+
+ const startNow = startPoint.timestamp ?? performance.now();
+ lastPointTimeRef.current = startNow;
+ const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
+ const taperEngine = pipeline.getTaperEngine();
+ if (bs.usePressure) {
+ const baseStartP = hasCustomCurve
+ ? startPoint.pressure
+ : taperEngine.mapPressure(startPoint.pressure);
+ const smoothStartP = taperEngine.smoothPressure(baseStartP);
+ startPoint.pressure = smoothStartP;
+ startPoint.width = calculateStrokeWidth(
+ bs.size,
+ smoothStartP,
+ bs.minSizeFactor,
+ bs.usePressure,
+ firstEvent.pointerType,
+ bs.pressureCurveGamma ?? 1.0,
+ 1.0,
+ bs.pressureCurve
+ );
+ }
+ if (isMonochrome && startPoint.width < 1.25) {
+ startPoint.width = 1.25;
+ }
+
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const blurMargin = (1 - strokeHardness) * (startPoint.width * 1.5);
+ const r = Math.max(
+ 32,
+ Math.ceil(
+ Math.max(startPoint.width, bs.size || 10) * (2.8 + scatterFactor * 2) + blurMargin + 32
+ )
+ );
+
+ const prevStrokeEnd = lastStrokeEndRef.current;
+ const isShiftLine =
+ Boolean(e.shiftKey) &&
+ !isMaskModeRef.current &&
+ prevStrokeEnd !== null &&
+ prevStrokeEnd.layerId === currentLayerId;
+ isShiftLineStrokeRef.current = isShiftLine;
+
+ if (isShiftLine && prevStrokeEnd) {
+ const pLineStart: Point = {
+ x: prevStrokeEnd.x,
+ y: prevStrokeEnd.y,
+ pressure: startPoint.pressure,
+ width: startPoint.width,
+ tiltX: startPoint.tiltX,
+ tiltY: startPoint.tiltY,
+ twist: startPoint.twist,
+ timestamp: startNow - 16,
+ };
+ const pLineMid: Point = {
+ x: (pLineStart.x + startPoint.x) * 0.5,
+ y: (pLineStart.y + startPoint.y) * 0.5,
+ pressure: startPoint.pressure,
+ width: startPoint.width,
+ tiltX: startPoint.tiltX,
+ tiltY: startPoint.tiltY,
+ twist: startPoint.twist,
+ timestamp: startNow - 8,
+ };
+ allStrokePointsRef.current = [pLineStart, pLineMid, startPoint];
+ pipeline.seedKnot(
+ pLineStart.x,
+ pLineStart.y,
+ pLineStart.pressure,
+ pLineStart.width,
+ pLineStart.tiltX ?? 0,
+ pLineStart.tiltY ?? 0,
+ pLineStart.twist ?? 0,
+ pLineStart.timestamp ?? 0,
+ r
+ );
+ pipeline.seedKnot(
+ pLineMid.x,
+ pLineMid.y,
+ pLineMid.pressure,
+ pLineMid.width,
+ pLineMid.tiltX ?? 0,
+ pLineMid.tiltY ?? 0,
+ pLineMid.twist ?? 0,
+ pLineMid.timestamp ?? 0,
+ r
+ );
+ } else {
+ allStrokePointsRef.current = [startPoint];
+ pipeline.seedKnot(
+ startPoint.x,
+ startPoint.y,
+ startPoint.pressure,
+ startPoint.width,
+ startPoint.tiltX ?? 0,
+ startPoint.tiltY ?? 0,
+ startPoint.twist ?? 0,
+ startNow,
+ r
+ );
+ }
+
+ stabilizedPointRef.current = { ...startPoint };
+ lastProcessedPointRef.current.x = startPoint.x;
+ lastProcessedPointRef.current.y = startPoint.y;
+ hasLastProcessedPointRef.current = true;
+ lastQueuedPressureRef.current = startPoint.pressure;
+ recentPointsTrailRef.current = [
+ {
+ x: startPoint.x,
+ y: startPoint.y,
+ t: startNow,
+ pressure: startPoint.pressure,
+ width: startPoint.width,
+ },
+ ];
+ strokeTotalDistanceRef.current =
+ isShiftLine && prevStrokeEnd
+ ? Math.hypot(startPoint.x - prevStrokeEnd.x, startPoint.y - prevStrokeEnd.y)
+ : 0;
+
+ dispatchPointerStat(startPoint.x, startPoint.y, startPoint.pressure);
+
+ const minInitX =
+ isShiftLine && prevStrokeEnd ? Math.min(startPoint.x, prevStrokeEnd.x) : startPoint.x;
+ const minInitY =
+ isShiftLine && prevStrokeEnd ? Math.min(startPoint.y, prevStrokeEnd.y) : startPoint.y;
+ const maxInitX =
+ isShiftLine && prevStrokeEnd ? Math.max(startPoint.x, prevStrokeEnd.x) : startPoint.x;
+ const maxInitY =
+ isShiftLine && prevStrokeEnd ? Math.max(startPoint.y, prevStrokeEnd.y) : startPoint.y;
+ dirtyRectRef.current = {
+ minX: Math.max(0, Math.floor(minInitX - r)),
+ minY: Math.max(0, Math.floor(minInitY - r)),
+ maxX: Math.min(dims.width, Math.ceil(maxInitX + r)),
+ maxY: Math.min(dims.height, Math.ceil(maxInitY + r)),
+ };
+ pipeline.expandDirtyRectBounds(
+ dirtyRectRef.current.minX,
+ dirtyRectRef.current.minY,
+ dirtyRectRef.current.maxX,
+ dirtyRectRef.current.maxY
+ );
+ touchedTilesRef.current.clear();
+ markTouchedTiles(
+ dirtyRectRef.current.minX,
+ dirtyRectRef.current.minY,
+ dirtyRectRef.current.maxX,
+ dirtyRectRef.current.maxY
+ );
+
+ const isWetColor = !isEraser && Boolean(bs.colorMixing);
+ isWetColorStrokeRef.current = isWetColor;
+ liveNeedsNotifyRef.current = false;
+
+ if (isWetColor) {
+ layerPixelSamplerRef.current = new LayerPixelSampler(
+ canvas || dims,
+ currentLayerId,
+ activeTileGridRef.current
+ );
+ activeReservoirRef.current = new PaintReservoir(strokeColor);
+ } else {
+ layerPixelSamplerRef.current = null;
+ activeReservoirRef.current = null;
+ }
+
+ const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
+ currentStrokeIdRef.current = strokeId;
+ onCollabStrokeStartRef.current?.(strokeId, currentLayerId, bs, currentTool, startPoint);
+
+ liveDabCounterRef.current.count = 0;
+ stampRemainderDistRef.current = bs.customTipImage
+ ? Math.max(0.15, startPoint.width * (bs.spacing ?? 0.07))
+ : isPencil
+ ? Math.max(0.25, startPoint.width * (bs.spacing ?? 0.07))
+ : Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
+
+ const firstDotPoint = allStrokePointsRef.current[0];
+
+ if (useWireframeEraser) {
+ draftCtx.save();
+ draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
+ draftCtx.setLineDash([3, 3]);
+ draftCtx.lineWidth = Math.max(1, 1.5 / Math.max(0.05, zoomRef.current));
+ draftCtx.beginPath();
+ draftCtx.arc(
+ firstDotPoint.x,
+ firstDotPoint.y,
+ Math.max(1, firstDotPoint.width / 2),
+ 0,
+ Math.PI * 2
+ );
+ draftCtx.stroke();
+ draftCtx.restore();
+ } else {
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const gpuBatch = frameGpuDabsRef.current;
+ gpuBatch.length = 0;
+
+ if (bs.customTipImage) {
+ const tipOptions = buildLiveTexturedOptions(
+ bs,
+ isMonochrome ? 1.0 : bs.flow ?? 1.0,
+ strokeSpacing,
+ strokeHardness,
+ downscaledBinary ? false : isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true
+ );
+ if (downscaledBinary && tipOptions.antiAlias === 0) {
+ tipOptions.antiAlias = 2;
+ }
+ const useGpu = canUseWebGlForTexturedBrush(tipOptions);
+ drawTexturedDot(
+ draftCtx,
+ firstDotPoint,
+ liveColor,
+ bs.customTipImage,
+ tipOptions,
+ useGpu ? gpuBatch : undefined
+ );
+ if (useGpu && gpuBatch.length > 0) {
+ if (
+ !flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, tipOptions)
+ ) {
+ drawTexturedDot(draftCtx, firstDotPoint, liveColor, bs.customTipImage, tipOptions);
+ }
+ gpuBatch.length = 0;
+ }
+ } else if (isPencil) {
+ const grade = (bs.preset as PencilGrade) || 'pencil-2b';
+ drawPencilDot(
+ draftCtx,
+ firstDotPoint,
+ liveColor,
+ grade,
+ isMonochrome ? 1.0 : bs.flow ?? 0.74,
+ bs.grain ?? 1.0,
+ strokeHardness,
+ false,
+ false
+ );
+ } else {
+ const radialMixingOptions = buildLiveRadialOptions(
+ bs,
+ downscaledBinary ? false : isMonochrome,
+ canvas,
+ activeLayer,
+ true
+ );
+ if (downscaledBinary && radialMixingOptions.antiAlias === 0) {
+ radialMixingOptions.antiAlias = 2;
+ }
+ const useGpu = canUseWebGlForRadialBrush(radialMixingOptions);
+ drawDot(
+ draftCtx,
+ firstDotPoint,
+ liveColor,
+ false,
+ strokeHardness,
+ strokeFlow,
+ radialMixingOptions,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180,
+ useGpu ? gpuBatch : undefined
+ );
+ if (useGpu && gpuBatch.length > 0) {
+ if (
+ !flushRadialGpuDabs(
+ draftCtx,
+ gpuBatch,
+ liveColor,
+ strokeHardness,
+ false,
+ false,
+ radialMixingOptions
+ )
+ ) {
+ drawDot(
+ draftCtx,
+ firstDotPoint,
+ liveColor,
+ false,
+ strokeHardness,
+ strokeFlow,
+ radialMixingOptions,
+ bs.thickness ?? 1.0,
+ ((bs.customTipAngle ?? 0) * Math.PI) / 180
+ );
+ }
+ gpuBatch.length = 0;
+ }
+ }
+ }
+
+ if (isShiftLine && prevStrokeEnd) {
+ const lineSeg = pipeline
+ .getSplineGenerator()
+ .generateCornerSegment(allStrokePointsRef.current[0], startPoint);
+ const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
+ const liveTipOpts = bs.customTipImage
+ ? buildLiveTexturedOptions(
+ bs,
+ isMonochrome ? 1.0 : bs.flow ?? 1.0,
+ strokeSpacing,
+ strokeHardness,
+ downscaledBinary ? false : isMonochrome,
+ canvas,
+ activeLayer,
+ isEraser,
+ isBgEraser,
+ true
+ )
+ : null;
+ if (liveTipOpts && downscaledBinary && liveTipOpts.antiAlias === 0) {
+ liveTipOpts.antiAlias = 2;
+ }
+ const liveRadialOpts =
+ !bs.customTipImage && !isPencil
+ ? buildLiveRadialOptions(
+ bs,
+ downscaledBinary ? false : isMonochrome,
+ canvas,
+ activeLayer,
+ true
+ )
+ : null;
+ if (liveRadialOpts && downscaledBinary && liveRadialOpts.antiAlias === 0) {
+ liveRadialOpts.antiAlias = 2;
+ }
+ const useGpuLine =
+ !useWireframeEraser &&
+ (bs.customTipImage
+ ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
+ : !isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts)));
+ const gpuBatch = frameGpuDabsRef.current;
+ gpuBatch.length = 0;
+ emitLiveSegment(
+ draftCtx,
+ lineSeg,
+ bs,
+ strokeColor,
+ strokeHardness,
+ strokeFlow,
+ strokeSpacing,
+ isMonochrome,
+ isPencil,
+ isEraser,
+ isBgEraser,
+ useWireframeEraser,
+ canvas,
+ activeLayer,
+ useGpuLine ? gpuBatch : undefined
+ );
+ if (useGpuLine && gpuBatch.length > 0) {
+ const liveColor =
+ (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
+ if (bs.customTipImage && liveTipOpts) {
+ flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, liveTipOpts);
+ } else if (liveRadialOpts) {
+ flushRadialGpuDabs(
+ draftCtx,
+ gpuBatch,
+ liveColor,
+ strokeHardness,
+ false,
+ false,
+ liveRadialOpts
+ );
+ }
+ gpuBatch.length = 0;
+ }
+ pipeline.seedKnot(
+ startPoint.x,
+ startPoint.y,
+ startPoint.pressure,
+ startPoint.width,
+ startPoint.tiltX ?? 0,
+ startPoint.tiltY ?? 0,
+ startPoint.twist ?? 0,
+ startNow,
+ r
+ );
+ }
+
+ draftCanvas.__draftHasContent = true;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ activeTileGridRef.current.notifyChange();
+ liveNeedsNotifyRef.current = false;
+
+ if (pipeline.getPendingCount() > 0 && drawRafIdRef.current === null) {
+ drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
+ }
+ },
+ [
+ abortActiveStroke,
+ activeLayerIdRef,
+ activeLayerLockedRef,
+ activeLayerVisibleRef,
+ activeTileGridRef,
+ buildLiveRadialOptions,
+ buildLiveTexturedOptions,
+ clearPredictedCanvas,
+ colorModeRef,
+ dimensionsRef,
+ disabled,
+ dispatchPointerStat,
+ effectiveDraftCanvasRef,
+ emitConstraintAxisChange,
+ emitLiveSegment,
+ flipXRef,
+ flipYRef,
+ flushPendingHistoryTasks,
+ flushPendingPoints,
+ getBrushSettings,
+ getCachedLayerCanvas,
+ getCanvasPoint,
+ getTool,
+ getViewportRect,
+ interactionRef,
+ isDrawingRef,
+ isMaskModeRef,
+ lastStrokeEndRef,
+ layerSourceCanvasesRef,
+ layersRef,
+ markTouchedTiles,
+ onCollabStrokeStartRef,
+ panRef,
+ resolveStrokeColor,
+ rotationRef,
+ rulerRef,
+ selectionRef,
+ viewportRef,
+ zoomRef,
+ ]
+ );
+
+ const handlePointerMove = useCallback(
+ (
+ e: React.PointerEvent<HTMLElement>,
+ coalescedEvents?: PointerEvent[],
+ predictedEvents?: PointerEvent[]
+ ) => {
+ const extEvent = e as ExtendedPointerEvent;
+ if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
+ const point = getCanvasPoint(e);
+ dispatchPointerStat(point.x, point.y, point.pressure);
+ onCollabCursorMoveRef.current?.(point.x, point.y, false, getTool());
+ return;
+ }
+
+ e.preventDefault();
+
+ const vRect = getViewportRect();
+ if (!vRect) return;
+ const dims = dimensionsRef.current;
+
+ const candidateCoalesced: PointerEvent[] | readonly PointerEvent[] | null =
+ coalescedEvents ??
+ extEvent.coalescedEvents ??
+ (typeof e.nativeEvent?.getCoalescedEvents === 'function'
+ ? e.nativeEvent.getCoalescedEvents()
+ : null);
+ let rawCoalesced: PointerEvent[] | readonly PointerEvent[] | null = null;
+ if (candidateCoalesced && candidateCoalesced.length > 0) {
+ const lastC = candidateCoalesced[candidateCoalesced.length - 1];
+ const nativeEvt = e.nativeEvent;
+ if (
+ lastC &&
+ nativeEvt &&
+ Number.isFinite(lastC.clientX) &&
+ Number.isFinite(lastC.clientY) &&
+ Math.hypot(lastC.clientX - nativeEvt.clientX, lastC.clientY - nativeEvt.clientY) <= 1.5
+ ) {
+ rawCoalesced = candidateCoalesced;
+ }
+ }
+ const count = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced.length : 1;
+
+ const pipeline = strokePipelineRef.current;
+ const scratch = scratchDocCoordRef.current;
+ const lastProc = lastProcessedPointRef.current;
+ const minStepDoc = Math.min(0.25, 0.25 / Math.max(0.05, zoomRef.current));
+ const isAltOverride = e.altKey;
+ const isShiftKey = e.shiftKey;
+ const ruler = rulerRef.current ?? null;
+ const curPan = panRef.current;
+ const curZoom = zoomRef.current;
+ const curRot = rotationRef.current;
+ const curFlipX = flipXRef.current;
+ const curFlipY = flipYRef.current;
+
+ let lastQueuedX = 0;
+ let lastQueuedY = 0;
+ let lastQueuedPressure = lastQueuedPressureRef.current;
+ let hasQueued = false;
+
+ for (let i = 0; i < count; i++) {
+ const cEvent = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced[i] : e.nativeEvent;
+ screenToCanvasInto(
+ cEvent.clientX,
+ cEvent.clientY,
+ vRect,
+ curPan,
+ curZoom,
+ curRot,
+ dims,
+ scratch,
+ curFlipX,
+ curFlipY
+ );
+
+ const snapRes = snapSessionRef.current.processPoint(scratch, ruler, isAltOverride);
+ let cx = snapRes.x;
+ let cy = snapRes.y;
+ if (snapRes.axis) {
+ emitConstraintAxisChange(snapRes.axis);
+ } else if (
+ !isShiftLineStrokeRef.current &&
+ isShiftKey &&
+ !ruler?.enabled &&
+ allStrokePointsRef.current.length > 0
+ ) {
+ const originPt = allStrokePointsRef.current[0];
+ const dx = cx - originPt.x;
+ const dy = cy - originPt.y;
+ const dist = Math.hypot(dx, dy);
+ if (dist > 0.5) {
+ const snapAngle = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);
+ cx = originPt.x + Math.cos(snapAngle) * dist;
+ cy = originPt.y + Math.sin(snapAngle) * dist;
+ }
+ }
+
+ let cPressure = 0;
+ if (cEvent.pointerType === 'mouse') {
+ cPressure = cEvent.buttons & 1 ? 0.5 : 0;
+ } else {
+ cPressure =
+ cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;
+ }
+
+ if (
+ hasLastProcessedPointRef.current &&
+ Math.hypot(cx - lastProc.x, cy - lastProc.y) < minStepDoc &&
+ Math.abs(cPressure - lastQueuedPressure) <= 0.04
+ ) {
+ continue;
+ }
+
+ lastProc.x = cx;
+ lastProc.y = cy;
+ hasLastProcessedPointRef.current = true;
+
+ pipeline.enqueueSample(
+ cx,
+ cy,
+ cPressure,
+ cEvent.tiltX ?? 0,
+ cEvent.tiltY ?? 0,
+ cEvent.twist ?? 0,
+ cEvent.timeStamp,
+ encodePointerType(cEvent.pointerType)
+ );
+ lastQueuedX = cx;
+ lastQueuedY = cy;
+ lastQueuedPressure = cPressure;
+ hasQueued = true;
+ }
+
+ lastQueuedPressureRef.current = lastQueuedPressure;
+
+ const rawPredicted =
+ predictedEvents ??
+ extEvent.predictedEvents ??
+ (typeof e.nativeEvent?.getPredictedEvents === 'function'
+ ? e.nativeEvent.getPredictedEvents()
+ : null);
+
+ if (rawPredicted && rawPredicted.length > 0) {
+ latestPredictedRef.current = { predEvents: rawPredicted, vRect };
+ } else {
+ latestPredictedRef.current = null;
+ }
+
+ if (hasQueued) {
+ dispatchPointerStat(lastQueuedX, lastQueuedY, lastQueuedPressure);
+ onCollabCursorMoveRef.current?.(lastQueuedX, lastQueuedY, true, getTool());
+ }
+
+ if (
+ (pipeline.getPendingCount() > 0 || latestPredictedRef.current !== null) &&
+ drawRafIdRef.current === null
+ ) {
+ drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
+ }
+ },
+ [
+ dimensionsRef,
+ dispatchPointerStat,
+ emitConstraintAxisChange,
+ flipXRef,
+ flipYRef,
+ flushPendingPoints,
+ getCanvasPoint,
+ getTool,
+ getViewportRect,
+ isDrawingRef,
+ onCollabCursorMoveRef,
+ panRef,
+ rotationRef,
+ rulerRef,
+ zoomRef,
+ ]
+ );
+
+ const handlePointerUp = useCallback(
+ (e: React.PointerEvent<HTMLElement>) => {
+ if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
+ return;
+ }
+
+ e.preventDefault();
+ clearPredictedCanvas();
+
+ if (interactionRef.current && interactionRef.current.hasPointerCapture(e.pointerId)) {
+ try {
+ interactionRef.current.releasePointerCapture(e.pointerId);
+ } catch {
+ // Ignore release errors
+ }
+ }
+
+ if (drawRafIdRef.current !== null) {
+ cancelAnimationFrame(drawRafIdRef.current);
+ drawRafIdRef.current = null;
+ }
+ flushPendingPoints();
+
+ const bs = getBrushSettings();
+ const dims = dimensionsRef.current;
+ const grid = activeTileGridRef.current;
+ const endPoint = getCanvasPoint(e);
+ const draftCanvas = effectiveDraftCanvasRef?.current as
+ | DraftCanvasElement
+ | null
+ | undefined;
+ const canvas = getCachedLayerCanvas() as DraftCanvasElement | null;
+ if (canvas) {
+ canvas.__isBlank = false;
+ canvas.__isSolidWhite = false;
+ }
+
+ const currentTool = getTool();
+ const currentLayerId = activeLayerIdRef.current;
+ const isEraser = currentTool === 'eraser';
+ const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
+ const mode = colorModeRef.current;
+ const isPencil =
+ !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
+
+ const isTone = isToneStrokeRef.current;
+ const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
+ const isToneLayer = Boolean(activeLayer?.toneEnabled);
+ const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
+ const isMonochrome = mode === 'monochrome' || isMonoLayer;
+ const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;
+ const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
+
+ const pipeline = strokePipelineRef.current;
+ const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
+ const tailPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + 24);
+ const enableFlickTaper =
+ !isEraser &&
+ !isShiftLineStrokeRef.current &&
+ activeLayer?.type !== 'vector' &&
+ Boolean(bs.taper?.useOut);
+
+ let addedFlickPoints = false;
+ pipeline.finalizeStroke(e.timeStamp || performance.now(), {
+ enableFlickTaper,
+ dirtyPadExtra: tailPadExtra,
+ onPoint: (sample) => {
+ addedFlickPoints = true;
+ allStrokePointsRef.current.push({
+ x: sample.x,
+ y: sample.y,
+ pressure: sample.pressure,
+ width: sample.width,
+ tiltX: sample.tiltX,
+ tiltY: sample.tiltY,
+ twist: sample.twist,
+ timestamp: sample.timestamp,
+ isCorner: sample.isCorner,
+ });
+ },
+ onSegment: (seg) => {
+ const segPad = Math.ceil(
+ Math.max(seg.p0.width, seg.p3.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32
+ );
+ const tMinX = Math.min(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) - segPad;
+ const tMinY = Math.min(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) - segPad;
+ const tMaxX = Math.max(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) + segPad;
+ const tMaxY = Math.max(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) + segPad;
+ pipeline.expandDirtyRectBounds(tMinX, tMinY, tMaxX, tMaxY);
+ markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);
+ },
+ });
+
+ const pDirty = pipeline.dirtyRect;
+ const mergedDirty = dirtyRectRef.current
+ ? {
+ minX: Math.min(
+ dirtyRectRef.current.minX,
+ Number.isFinite(pDirty.minX) ? pDirty.minX : dirtyRectRef.current.minX
+ ),
+ minY: Math.min(
+ dirtyRectRef.current.minY,
+ Number.isFinite(pDirty.minY) ? pDirty.minY : dirtyRectRef.current.minY
+ ),
+ maxX: Math.max(
+ dirtyRectRef.current.maxX,
+ Number.isFinite(pDirty.maxX) ? pDirty.maxX : dirtyRectRef.current.maxX
+ ),
+ maxY: Math.max(
+ dirtyRectRef.current.maxY,
+ Number.isFinite(pDirty.maxY) ? pDirty.maxY : dirtyRectRef.current.maxY
+ ),
+ }
+ : Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)
+ ? { ...pDirty }
+ : null;
+
+ let exitSpeed = 0;
+ if (recentPointsTrailRef.current.length >= 2) {
+ const trail = recentPointsTrailRef.current;
+ const sampleIdx = Math.max(0, trail.length - 4);
+ const pA = trail[sampleIdx];
+ const pB = trail[trail.length - 1];
+ const dwellMs = Math.max(0, performance.now() - pB.t);
+ const dt = Math.max(1, pB.t - pA.t + dwellMs);
+ exitSpeed = Math.hypot(pB.x - pA.x, pB.y - pA.y) / dt;
+ }
+
+ const shouldTaper =
+ Boolean(bs.taper?.useIn) || (Boolean(bs.taper?.useOut) && !addedFlickPoints);
+ if (shouldTaper && allStrokePointsRef.current.length >= 3) {
+ applyParametricTaper(allStrokePointsRef.current, {
+ useIn: Boolean(bs.taper?.useIn),
+ useOut: Boolean(bs.taper?.useOut) && !addedFlickPoints,
+ minSizeFactor: bs.minSizeFactor,
+ exitSpeed,
+ });
+ }
+
+ const allPoints = allStrokePointsRef.current;
+ let createdVectorStroke: VectorStroke | undefined;
+
+ if (allPoints.length > 0 && !isMaskModeRef.current) {
+ const finalPt = allPoints[allPoints.length - 1];
+ lastStrokeEndRef.current = {
+ x: finalPt.x,
+ y: finalPt.y,
+ pressure: finalPt.pressure,
+ width: finalPt.width,
+ layerId: currentLayerId,
+ };
+ }
+
+ if (
+ activeLayer?.type === 'vector' &&
+ allPoints.length > 0 &&
+ dims.width > 0 &&
+ dims.height > 0
+ ) {
+ createdVectorStroke = commitVectorStrokeOrErase({
+ activeLayer,
+ currentLayerId,
+ allPoints,
+ bs,
+ isEraser,
+ isPencil,
+ isMonochrome,
+ strokeColor,
+ dims,
+ grid,
+ canvas,
+ mergedDirty,
+ strokeId: currentStrokeIdRef.current,
+ pushHistoryStep,
+ });
+ } else if (mergedDirty && allPoints.length > 0 && dims.width > 0 && dims.height > 0) {
+ const hasWetEdge =
+ !isMonochrome && !isEraser && !bs.isTransparentInk && (bs.wetEdge ?? 0) > 0.01;
+ const clampedBakeRect = computeClampedBakeDirtyRect(
+ mergedDirty,
+ dims.width,
+ dims.height,
+ bs.size || 10,
+ hasWetEdge ? bs.wetEdge ?? 0 : 0,
+ bs.wetEdgeRadius ?? 3.0
+ );
+
+ if (clampedBakeRect) {
+ const { x: sx, y: sy, width: dw, height: dh } = clampedBakeRect;
+ let label = 'Brush Stroke';
+ if (bs.isTransparentInk) {
+ label = 'Transparent Ink';
+ } else if (currentTool === 'eraser') {
+ label = 'Eraser';
+ } else if (bs.brushName) {
+ label = bs.brushName;
+ } else if (bs.preset === 'pencil-f') {
+ label = 'Pencil (F)';
+ } else if (bs.preset === 'pencil-2b') {
+ label = 'Pencil (2B)';
+ } else if (bs.preset === 'pencil-4b') {
+ label = 'Pencil (4B)';
+ } else if (bs.preset === 'pencil-hb') {
+ label = 'Pencil (HB)';
+ } else {
+ label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
+ }
+
+ const dirtyRect = clampedBakeRect;
+ const toolForHistory =
+ currentTool === 'eraser' ? 'eraser' : isPencil ? 'pencil' : 'brush';
+ const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
+ const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
+ const activeSelection = selectionRef.current;
+
+ if (isMaskModeRef.current && canvas) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ const beforeMaskData = ctx.getImageData(sx, sy, dw, dh);
+ const maskBs: BrushSettings = {
+ ...bs,
+ color: strokeColor,
+ isTransparentInk: false,
+ colorMixing: false,
+ };
+ const maskTool: ToolType = isEraser ? 'brush' : currentTool;
+
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(sx, sy, dw, dh);
+ ctx.clip();
+ applySelectionCanvasClip(ctx, activeSelection);
+
+ if ((bs.opacity ?? 1.0) >= 0.999) {
+ renderCompleteStroke(
+ ctx,
+ allPoints,
+ maskBs,
+ maskTool,
+ 'grayscale',
+ false,
+ canvas,
+ false
+ );
+ } else {
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ ctx.globalCompositeOperation = 'source-over';
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtx) {
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ { ...maskBs, opacity: 1.0 },
+ maskTool,
+ 'grayscale',
+ false,
+ canvas,
+ false
+ );
+ bCtx.restore();
+ ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ }
+ }
+ ctx.restore();
+
+ const afterMaskData = ctx.getImageData(sx, sy, dw, dh);
+ if (activeSelection?.mask) {
+ applySelectionMaskToImageData(
+ beforeMaskData,
+ afterMaskData,
+ sx,
+ sy,
+ activeSelection
+ );
+ ctx.putImageData(afterMaskData, sx, sy);
+ }
+ if (activeLayer) {
+ activeLayer.maskVersion = (activeLayer.maskVersion || 0) + 1;
+ }
+ enqueueHistoryTask(() => {
+ pushHistoryStep(
+ toolForHistory,
+ 'Layer Mask Stroke',
+ beforeMaskData,
+ afterMaskData,
+ currentLayerId,
+ dirtyRect,
+ undefined,
+ undefined,
+ undefined,
+ undefined,
+ true
+ );
+ });
+ }
+ } else if (isToneLayer && sourceCanvas) {
+ if (!grid.isLayerIngested(currentLayerId)) {
+ grid.ingestCanvas(currentLayerId, sourceCanvas, targetFormat);
+ }
+ const sCtx = get2DContext(sourceCanvas);
+ const beforeSelectionData =
+ activeSelection?.mask && sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
+ if (sCtx) {
+ sCtx.save();
+ sCtx.beginPath();
+ sCtx.rect(sx, sy, dw, dh);
+ sCtx.clip();
+ applySelectionCanvasClip(sCtx, activeSelection);
+
+ const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999;
+ if (!needsIsolatedBake) {
+ renderCompleteStroke(
+ sCtx,
+ allPoints,
+ bs,
+ currentTool,
+ effectiveMode,
+ isBgEraser,
+ sourceCanvas,
+ Boolean(activeLayer?.alphaLocked)
+ );
+ } else {
+ sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
+ sCtx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ sCtx.globalCompositeOperation = 'source-atop';
+ } else {
+ sCtx.globalCompositeOperation = 'source-over';
+ }
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
+ if (bCtxBake) {
+ bCtxBake.clearRect(0, 0, dw, dh);
+ bCtxBake.save();
+ bCtxBake.translate(-sx, -sy);
+ renderCompleteStroke(
+ bCtxBake,
+ allPoints,
+ {
+ ...bs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ color: isEraser && !isBgEraser ? '#000000' : bs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ sourceCanvas,
+ false
+ );
+ bCtxBake.restore();
+ sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ }
+ }
+ sCtx.restore();
+ }
+
+ const beforeSnapshot = grid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
+ if (afterData && beforeSelectionData && activeSelection?.mask && sCtx) {
+ applySelectionMaskToImageData(
+ beforeSelectionData,
+ afterData,
+ sx,
+ sy,
+ activeSelection
+ );
+ sCtx.putImageData(afterData, sx, sy);
+ }
+
+ if (activeLayer && canvas) {
+ const freq = activeLayer.toneFrequency ?? 60;
+ const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
+ const cellMargin = isEraser ? Math.ceil(cellSize * 2 + 32) : 0;
+ const fxX = Math.max(0, sx - cellMargin);
+ const fxY = Math.max(0, sy - cellMargin);
+ const fxW = Math.min(canvas.width, sx + dw + cellMargin) - fxX;
+ const fxH = Math.min(canvas.height, sy + dh + cellMargin) - fxY;
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ activeLayer,
+ dimensionsRef.current.dpi ?? 600,
+ { x: fxX, y: fxY, width: fxW, height: fxH }
+ );
+ }
+
+ if (afterData) {
+ grid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+ }
+ const tileDeltas = grid.computeDeltasFromSnapshot(
+ beforeSnapshot,
+ currentLayerId,
+ dirtyRect
+ );
+
+ enqueueHistoryTask(() => {
+ pushHistoryStep(
+ toolForHistory,
+ label,
+ null,
+ null,
+ currentLayerId,
+ dirtyRect,
+ tileDeltas
+ );
+ });
+ } else {
+ const regionCanvas = grid.createRegionCanvas(currentLayerId, dirtyRect);
+ const rCtx = regionCanvas ? get2DContext(regionCanvas) : null;
+ if (regionCanvas && rCtx) {
+ const beforeSelectionData = activeSelection?.mask
+ ? rCtx.getImageData(0, 0, dw, dh)
+ : null;
+
+ rCtx.save();
+ rCtx.translate(-sx, -sy);
+ rCtx.beginPath();
+ rCtx.rect(sx, sy, dw, dh);
+ rCtx.clip();
+ applySelectionCanvasClip(rCtx, activeSelection);
+
+ const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999 || hasWetEdge;
+
+ if (!needsIsolatedBake) {
+ renderCompleteStroke(
+ rCtx,
+ allPoints,
+ bs,
+ currentTool,
+ effectiveMode,
+ isBgEraser,
+ canvas || undefined,
+ Boolean(activeLayer?.alphaLocked)
+ );
+ } else {
+ rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
+ rCtx.globalCompositeOperation = 'destination-out';
+ } else if (activeLayer?.alphaLocked) {
+ rCtx.globalCompositeOperation = 'source-atop';
+ } else {
+ rCtx.globalCompositeOperation = 'source-over';
+ }
+ const bakeCanvas = getReusableBakeCanvas(dw, dh);
+ const bCtx = bakeCanvas.getContext('2d', {
+ alpha: true,
+ willReadFrequently: hasWetEdge,
+ });
+ if (bCtx) {
+ bCtx.clearRect(0, 0, dw, dh);
+ bCtx.save();
+ bCtx.translate(-sx, -sy);
+ renderCompleteStroke(
+ bCtx,
+ allPoints,
+ {
+ ...bs,
+ opacity: 1.0,
+ isTransparentInk: false,
+ wetEdge: 0,
+ color: isEraser && !isBgEraser ? '#000000' : bs.color,
+ },
+ isEraser && !isBgEraser ? 'brush' : currentTool,
+ effectiveMode,
+ isBgEraser,
+ canvas || undefined,
+ false
+ );
+ bCtx.restore();
+
+ if (hasWetEdge) {
+ const bakeImg = bCtx.getImageData(0, 0, dw, dh);
+ applyCspWatercolorEdge(
+ bakeImg,
+ bs.wetEdge ?? 0,
+ bs.wetEdgeRadius ?? 3.0,
+ bs.wetEdgeAlphaPower ?? 25,
+ bs.wetEdgeValuePower ?? 15
+ );
+ bCtx.putImageData(bakeImg, 0, 0);
+ }
+
+ rCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
+ }
+ }
+
+ rCtx.restore();
+
+ if (beforeSelectionData && activeSelection?.mask) {
+ const fullAfter = rCtx.getImageData(0, 0, dw, dh);
+ applySelectionMaskToImageData(
+ beforeSelectionData,
+ fullAfter,
+ sx,
+ sy,
+ activeSelection
+ );
+ rCtx.putImageData(fullAfter, 0, 0);
+ }
+
+ const useSparseTileSpans =
+ dw * dh > 512 * 512 && touchedTilesRef.current.size > 0;
+ if (useSparseTileSpans) {
+ const rows = new Map<number, number[]>();
+ for (const key of touchedTilesRef.current) {
+ const ty = Math.floor(key / 65536);
+ const tx = key % 65536;
+ let list = rows.get(ty);
+ if (!list) {
+ list = [];
+ rows.set(ty, list);
+ }
+ list.push(tx);
+ }
+
+ const spans: Array<{ x: number; y: number; width: number; height: number }> = [];
+ for (const [ty, txList] of rows) {
+ txList.sort((a, b) => a - b);
+ let spanStart = txList[0];
+ let spanEnd = txList[0];
+ const pushClampedSpan = (s0: number, s1: number) => {
+ const rx = Math.max(sx, s0 * TILE_SIZE);
+ const ry = Math.max(sy, ty * TILE_SIZE);
+ const rxEnd = Math.min(sx + dw, (s1 + 1) * TILE_SIZE);
+ const ryEnd = Math.min(sy + dh, (ty + 1) * TILE_SIZE);
+ const rw = rxEnd - rx;
+ const rh = ryEnd - ry;
+ if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
+ };
+ for (let i = 1; i < txList.length; i++) {
+ if (txList[i] <= spanEnd + 1) {
+ spanEnd = txList[i];
+ } else {
+ pushClampedSpan(spanStart, spanEnd);
+ spanStart = txList[i];
+ spanEnd = txList[i];
+ }
+ }
+ pushClampedSpan(spanStart, spanEnd);
+ }
+
+ const beforeSnapshot = new Map<
+ string,
+ { format: TileFormat; data: Uint8Array | null }
+ >();
+ for (let i = 0; i < spans.length; i++) {
+ const sp = spans[i];
+ const subSnap = grid.snapshotTilesInRect(currentLayerId, sp);
+ for (const [k, v] of subSnap) {
+ if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
+ }
+ const spanData = rCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
+ if (isMonochrome) {
+ binarizeImageDataBuffer(
+ spanData,
+ activeLayer?.monoThreshold ?? 128,
+ activeLayer?.monoExpressBlack ?? true,
+ activeLayer?.monoExpressWhite ?? true
+ );
+ }
+ grid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
+ enqueueHistoryTask(() => {
+ pushHistoryStep(
+ toolForHistory,
+ label,
+ null,
+ null,
+ currentLayerId,
+ dirtyRect,
+ tileDeltas
+ );
+ });
+ } else {
+ const beforeSnapshot = grid.snapshotTilesInRect(currentLayerId, dirtyRect);
+ const afterData = rCtx.getImageData(0, 0, dw, dh);
+ if (isMonochrome) {
+ binarizeImageDataBuffer(
+ afterData,
+ activeLayer?.monoThreshold ?? 128,
+ activeLayer?.monoExpressBlack ?? true,
+ activeLayer?.monoExpressWhite ?? true
+ );
+ }
+ grid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
+ const tileDeltas = grid.computeDeltasFromSnapshot(
+ beforeSnapshot,
+ currentLayerId,
+ dirtyRect
+ );
+
+ enqueueHistoryTask(() => {
+ pushHistoryStep(
+ toolForHistory,
+ label,
+ null,
+ null,
+ currentLayerId,
+ dirtyRect,
+ tileDeltas
+ );
+ });
+ }
+
+ releaseTemporaryCanvas(regionCanvas);
+
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
+ }
+ if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
+ const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
+ if (existingSource) {
+ grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (clearDraftRafRef.current !== null) {
+ cancelAnimationFrame(clearDraftRafRef.current);
+ clearDraftRafRef.current = null;
+ }
+ if (draftCanvas) {
+ const dCtx = get2DContext(draftCanvas);
+ if (dCtx) {
+ try {
+ dCtx.restore();
+ } catch {
+ // Ignore restore underflow
+ }
+ dCtx.resetTransform();
+ dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ }
+ draftCanvas.__draftHasContent = false;
+ draftCanvas.__draftCompositeOp = 'source-over';
+ draftCanvas.__draftMonochrome = false;
+ draftCanvas.__draftVersion = (draftCanvas.__draftVersion || 0) + 1;
+ }
+ clearPredictedCanvas();
+
+ grid.notifyChange(true);
+
+ if (currentStrokeIdRef.current) {
+ onCollabStrokeFinishRef.current?.(
+ currentStrokeIdRef.current,
+ currentLayerId,
+ endPoint,
+ mergedDirty
+ ? {
+ x: Math.max(0, Math.floor(mergedDirty.minX)),
+ y: Math.max(0, Math.floor(mergedDirty.minY)),
+ width: Math.max(
+ 1,
+ Math.ceil(mergedDirty.maxX) - Math.max(0, Math.floor(mergedDirty.minX))
+ ),
+ height: Math.max(
+ 1,
+ Math.ceil(mergedDirty.maxY) - Math.max(0, Math.floor(mergedDirty.minY))
+ ),
+ }
+ : undefined,
+ createdVectorStroke
+ );
+ currentStrokeIdRef.current = null;
+ }
+
+ strokePipelineRef.current.abortStroke();
+ frameGpuDabsRef.current.length = 0;
+ isDrawingRef.current = false;
+ activePointerIdRef.current = null;
+ allStrokePointsRef.current = [];
+ stabilizedPointRef.current = null;
+ hasLastProcessedPointRef.current = false;
+ dirtyRectRef.current = null;
+ touchedTilesRef.current.clear();
+ liveNeedsNotifyRef.current = false;
+ isShiftLineStrokeRef.current = false;
+ isToneStrokeRef.current = false;
+ layerPixelSamplerRef.current = null;
+ activeReservoirRef.current = null;
+ snapSessionRef.current.endStroke();
+ emitConstraintAxisChange(null);
+
+ if (isMaskModeRef.current) {
+ onUpdateMaskThumbnailRef.current?.(currentLayerId);
+ grid.notifyChange(true);
+ } else {
+ enqueueHistoryTask(() => {
+ onUpdateLayerThumbnail(currentLayerId);
+ });
+ }
+ },
+ [
+ activeLayerIdRef,
+ activeTileGridRef,
+ clearPredictedCanvas,
+ colorModeRef,
+ dimensionsRef,
+ effectiveDraftCanvasRef,
+ emitConstraintAxisChange,
+ enqueueHistoryTask,
+ flushPendingPoints,
+ getBrushSettings,
+ getCachedLayerCanvas,
+ getCanvasPoint,
+ getTool,
+ interactionRef,
+ isDrawingRef,
+ isMaskModeRef,
+ lastStrokeEndRef,
+ layerSourceCanvasesRef,
+ layersRef,
+ markTouchedTiles,
+ onCollabStrokeFinishRef,
+ onUpdateLayerThumbnail,
+ onUpdateMaskThumbnailRef,
+ pushHistoryStep,
+ resolveStrokeColor,
+ selectionRef,
+ ]
+ );
+
+ const handlePointerEnter = useCallback(() => {
+ if (viewportRef.current) {
+ cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
+ }
+ dispatchPointerStat(null, null, 0);
+ }, [dispatchPointerStat, viewportRef]);
+
+ const handlePointerLeave = useCallback(() => {
+ if (!isDrawingRef.current) {
+ dispatchPointerStat(null, null, 0);
+ }
+ }, [dispatchPointerStat, isDrawingRef]);
+
+ return {
+ abortActiveStroke,
+ handlePointerDown,
+ handlePointerMove,
+ handlePointerUp,
+ handlePointerEnter,
+ handlePointerLeave,
+ };
+}
diff --git a/src/hooks/drawing/useDrawingHistory.ts b/src/hooks/drawing/useDrawingHistory.ts
new file mode 100644
index 0000000..e8f361a
--- /dev/null
+++ b/src/hooks/drawing/useDrawingHistory.ts
@@ -0,0 +1,1032 @@
+import React, { useRef, useState, useCallback, useEffect } from 'react';
+import {
+ CanvasDimensions,
+ CanvasColorMode,
+ DirtyRect,
+ HistoryActionType,
+ HistoryItem,
+ HistoryItemMeta,
+ LayerItem,
+ TileDelta,
+ VectorStroke,
+} from '../../types/editor';
+import {
+ SparseTileGrid,
+ globalTileGrid,
+ releaseTemporaryCanvas,
+} from '../../utils/tileEngine';
+import { UndoCacheManager, globalUndoCache } from '../../utils/undoCache';
+import { documentStore } from '../../utils/documentStore';
+import { recoveryService } from '../../services/recoveryService';
+import { renderVectorLayer } from '../../utils/vectorEngine';
+import { createCanvasThumbnail, formatTime, get2DContext } from '../../utils/canvasUtils';
+import { applyLayerEffects } from '../../utils/layerEffectsEngine';
+import { isBackgroundLayerId, LastStrokeEndState, PushHistoryStepFn } from './types';
+
+type IdleCallbackWindow = Window & {
+ requestIdleCallback?: (cb: () => void, options?: { timeout: number }) => number;
+ cancelIdleCallback?: (id: number) => void;
+};
+
+export interface UseDrawingHistoryParams {
+ activeSessionId?: string | null;
+ tileGrid?: SparseTileGrid;
+ activeLayerId: string;
+ activeLayerLocked: boolean;
+ dimensions: CanvasDimensions;
+ dimensionsRef: React.MutableRefObject<CanvasDimensions>;
+ activeLayerIdRef: React.MutableRefObject<string>;
+ colorModeRef: React.MutableRefObject<CanvasColorMode>;
+ layersRef: React.MutableRefObject<LayerItem[] | undefined>;
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ layerSourceCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ onUpdateLayerThumbnail: (layerId: string) => void;
+ onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;
+ isDrawingRef: React.MutableRefObject<boolean>;
+ lastStrokeEndRef: React.MutableRefObject<LastStrokeEndState | null>;
+ abortActiveStrokeRef: React.MutableRefObject<() => void>;
+}
+
+export interface UseDrawingHistoryResult {
+ activeSessionIdRef: React.MutableRefObject<string | null>;
+ activeTileGridRef: React.MutableRefObject<SparseTileGrid>;
+ activeUndoCacheRef: React.MutableRefObject<UndoCacheManager>;
+ historyList: HistoryItemMeta[];
+ historyIndex: number;
+ canUndo: boolean;
+ canRedo: boolean;
+ pushHistoryStep: PushHistoryStepFn;
+ flushPendingHistoryTasks: () => void;
+ enqueueHistoryTask: (task: () => void) => void;
+ jumpToHistoryIndex: (targetIndex: number) => Promise<void>;
+ undo: () => void;
+ redo: () => void;
+ selectiveUndo: (peerIdToUndo?: string | number) => Promise<void>;
+ clearCanvas: () => void;
+ resetHistory: (targetDocumentId?: string) => void;
+}
+
+export function useDrawingHistory({
+ activeSessionId,
+ tileGrid,
+ activeLayerId,
+ activeLayerLocked,
+ dimensions,
+ dimensionsRef,
+ activeLayerIdRef,
+ colorModeRef,
+ layersRef,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ onUpdateLayerThumbnail,
+ onUpdateMaskThumbnailRef,
+ isDrawingRef,
+ lastStrokeEndRef,
+ abortActiveStrokeRef,
+}: UseDrawingHistoryParams): UseDrawingHistoryResult {
+ const activeSessionIdRef = useRef<string | null>(activeSessionId ?? null);
+ const activeTileGridRef = useRef<SparseTileGrid>(
+ tileGrid ??
+ (activeSessionId
+ ? documentStore.getOrCreateSession(activeSessionId).tileGrid
+ : globalTileGrid)
+ );
+ const activeUndoCacheRef = useRef<UndoCacheManager>(
+ activeSessionId
+ ? documentStore.getOrCreateSession(activeSessionId).undoCache
+ : globalUndoCache
+ );
+
+ const initialSession = activeSessionId
+ ? documentStore.getOrCreateSession(activeSessionId)
+ : null;
+ const historyRef = useRef<HistoryItem[]>(initialSession ? initialSession.history : []);
+ const historyIndexRef = useRef<number>(initialSession ? initialSession.historyIndex : -1);
+ const historyQueueRef = useRef<Promise<void>>(Promise.resolve());
+
+ const [historyList, setHistoryList] = useState<HistoryItemMeta[]>([]);
+ const [historyIndex, setHistoryIndex] = useState<number>(-1);
+ const [canUndo, setCanUndo] = useState(false);
+ const [canRedo, setCanRedo] = useState(false);
+
+ if (tileGrid) {
+ activeTileGridRef.current = tileGrid;
+ } else if (activeSessionId) {
+ const sess = documentStore.getOrCreateSession(activeSessionId);
+ activeTileGridRef.current = sess.tileGrid;
+ activeUndoCacheRef.current = sess.undoCache;
+ }
+
+ const persistSessionHistory = useCallback((docId?: string | null) => {
+ const targetDocId = docId !== undefined ? docId : activeSessionIdRef.current;
+ if (!targetDocId) return;
+ const sess = documentStore.getSession(targetDocId);
+ if (sess) {
+ sess.history = historyRef.current;
+ sess.historyIndex = historyIndexRef.current;
+ }
+ }, []);
+
+ const syncHistoryState = useCallback(() => {
+ const idx = historyIndexRef.current;
+ const len = historyRef.current.length;
+ setHistoryIndex(idx);
+ setCanUndo(idx > 0);
+ setCanRedo(idx >= 0 && idx < len - 1);
+ setHistoryList(
+ historyRef.current.map((item) => ({
+ id: item.id,
+ type: item.type,
+ label: item.label,
+ timestamp: item.timestamp,
+ timeFormatted: item.timeFormatted,
+ thumbnailUrl: item.thumbnailUrl,
+ layerId: item.layerId,
+ }))
+ );
+ }, []);
+
+ const ensureInitialHistory = useCallback(() => {
+ if (historyRef.current.length === 0) {
+ const now = Date.now();
+ const targetLayerId = activeLayerIdRef.current;
+ const dims = dimensionsRef.current;
+ const grid = activeTileGridRef.current;
+ const initialThumb = targetLayerId
+ ? createCanvasThumbnail(
+ { grid, layerId: targetLayerId, dimensions: dims },
+ !isBackgroundLayerId(targetLayerId)
+ )
+ : '';
+
+ const initialItem: HistoryItem = {
+ id: `hist-init-${now}`,
+ type: 'initial',
+ label: 'New Document',
+ timestamp: now,
+ timeFormatted: formatTime(now),
+ thumbnailUrl: initialThumb,
+ imageData: undefined,
+ beforeImageData: null,
+ afterImageData: null,
+ layerId: targetLayerId,
+ };
+
+ historyRef.current = [initialItem];
+ historyIndexRef.current = 0;
+ persistSessionHistory();
+ syncHistoryState();
+ }
+ }, [activeLayerIdRef, dimensionsRef, persistSessionHistory, syncHistoryState]);
+
+ const pushHistoryStep = useCallback<PushHistoryStepFn>(
+ (
+ actionType: HistoryActionType,
+ label: string,
+ beforeData: ImageData | null,
+ afterData: ImageData | null,
+ targetLayerId: string,
+ dirtyRect?: DirtyRect,
+ explicitTileDeltas?: TileDelta[],
+ vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },
+ peerId?: string | number,
+ strokeId?: string,
+ isMaskEdit?: boolean
+ ) => {
+ const now = Date.now();
+ const dims = dimensionsRef.current;
+ const grid = activeTileGridRef.current;
+ const docId = activeSessionIdRef.current;
+ const undoCache = activeUndoCacheRef.current;
+
+ let tileDeltas = explicitTileDeltas;
+
+ const effectiveDirtyRect =
+ dirtyRect ||
+ (dims.width > 0 && dims.height > 0
+ ? { x: 0, y: 0, width: dims.width, height: dims.height }
+ : undefined);
+
+ if (!isMaskEdit && !tileDeltas && effectiveDirtyRect && (beforeData || afterData)) {
+ const activeLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+ const isMono =
+ !isBackgroundLayerId(targetLayerId) &&
+ (colorModeRef.current === 'monochrome' ||
+ activeLayer?.expressionColor === 'monochrome');
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (beforeData) {
+ const bx =
+ beforeData.width === effectiveDirtyRect.width &&
+ beforeData.height === effectiveDirtyRect.height
+ ? effectiveDirtyRect.x
+ : 0;
+ const by =
+ beforeData.width === effectiveDirtyRect.width &&
+ beforeData.height === effectiveDirtyRect.height
+ ? effectiveDirtyRect.y
+ : 0;
+ grid.writeImageData(targetLayerId, beforeData, bx, by, targetFormat);
+ }
+
+ const beforeSnapshot = grid.snapshotTilesInRect(targetLayerId, effectiveDirtyRect);
+
+ if (afterData) {
+ const ax =
+ afterData.width === effectiveDirtyRect.width &&
+ afterData.height === effectiveDirtyRect.height
+ ? effectiveDirtyRect.x
+ : 0;
+ const ay =
+ afterData.width === effectiveDirtyRect.width &&
+ afterData.height === effectiveDirtyRect.height
+ ? effectiveDirtyRect.y
+ : 0;
+ grid.writeImageData(targetLayerId, afterData, ax, ay, targetFormat);
+ } else if (actionType === 'clear') {
+ grid.clearLayer(targetLayerId);
+ }
+
+ tileDeltas = grid.computeDeltasFromSnapshot(
+ beforeSnapshot,
+ targetLayerId,
+ effectiveDirtyRect
+ );
+ }
+
+ const hasDeltas = Boolean(tileDeltas && tileDeltas.length > 0);
+
+ const item: HistoryItem = {
+ id: `hist-${now}-${Math.random().toString(36).substring(2, 7)}`,
+ type: actionType,
+ label,
+ timestamp: now,
+ timeFormatted: formatTime(now),
+ thumbnailUrl: '',
+ layerId: targetLayerId,
+ beforeImageData: hasDeltas ? null : beforeData,
+ afterImageData: hasDeltas ? null : afterData,
+ imageData: hasDeltas ? undefined : afterData || undefined,
+ dirtyRect: effectiveDirtyRect,
+ tileDeltas: hasDeltas ? tileDeltas : undefined,
+ vectorStrokesDelta: vectorDelta,
+ peerId,
+ strokeId,
+ isMaskEdit,
+ };
+
+ const newHistory = historyRef.current.slice(0, historyIndexRef.current + 1);
+ newHistory.push(item);
+
+ if (newHistory.length > 50) {
+ newHistory.shift();
+ }
+
+ historyRef.current = newHistory;
+ historyIndexRef.current = newHistory.length - 1;
+ persistSessionHistory(docId);
+
+ if (dims.width > 0 && dims.height > 0) {
+ const isLarge = dims.width * dims.height > 1024 * 1024;
+ if (isLarge && hasDeltas) {
+ const existingLayerThumb =
+ layersRef.current?.find((l) => l.id === targetLayerId)?.thumbnailUrl || '';
+ item.thumbnailUrl = existingLayerThumb;
+ } else {
+ item.thumbnailUrl = createCanvasThumbnail(
+ { grid, layerId: targetLayerId, dimensions: dims },
+ !isBackgroundLayerId(targetLayerId)
+ );
+ }
+ }
+ syncHistoryState();
+
+ if (tileDeltas && tileDeltas.length > 0) {
+ const registerPromise = docId
+ ? documentStore.registerUndoStep(docId, item)
+ : undoCache.registerStep(item, historyRef.current);
+ registerPromise.catch((err) => {
+ console.warn('[History] LRU cache registration failed:', err);
+ });
+ }
+
+ if ((tileDeltas && tileDeltas.length > 0) || vectorDelta) {
+ const sessionKey = docId || recoveryService.getCurrentSessionId() || 'default-session';
+ recoveryService.logStrokeDelta(sessionKey, tileDeltas, vectorDelta, targetLayerId);
+ }
+ },
+ [colorModeRef, dimensionsRef, layersRef, persistSessionHistory, syncHistoryState]
+ );
+
+ const pendingHistoryTasksRef = useRef<Array<() => void>>([]);
+ const idleCallbackIdRef = useRef<number | ReturnType<typeof setTimeout> | null>(null);
+
+ const flushPendingHistoryTasks = useCallback(() => {
+ if (idleCallbackIdRef.current !== null) {
+ const win = typeof window !== 'undefined' ? (window as IdleCallbackWindow) : null;
+ if (win?.cancelIdleCallback && typeof idleCallbackIdRef.current === 'number') {
+ win.cancelIdleCallback(idleCallbackIdRef.current);
+ } else {
+ clearTimeout(idleCallbackIdRef.current as ReturnType<typeof setTimeout>);
+ }
+ idleCallbackIdRef.current = null;
+ }
+ const tasks = pendingHistoryTasksRef.current.splice(0);
+ for (const task of tasks) {
+ try {
+ task();
+ } catch (err) {
+ console.warn('[History] Error flushing pending history task:', err);
+ }
+ }
+ }, []);
+
+ const enqueueHistoryTask = useCallback(
+ (task: () => void) => {
+ pendingHistoryTasksRef.current.push(task);
+ if (idleCallbackIdRef.current === null) {
+ const win = typeof window !== 'undefined' ? (window as IdleCallbackWindow) : null;
+ const scheduleRun = () => {
+ if (win?.requestIdleCallback) {
+ idleCallbackIdRef.current = win.requestIdleCallback(runTasks, { timeout: 1200 });
+ } else {
+ idleCallbackIdRef.current = setTimeout(runTasks, 64);
+ }
+ };
+ const runTasks = () => {
+ idleCallbackIdRef.current = null;
+ if (isDrawingRef.current) {
+ scheduleRun();
+ return;
+ }
+ const tasks = pendingHistoryTasksRef.current.splice(0);
+ for (const t of tasks) {
+ try {
+ t();
+ } catch (err) {
+ console.warn('[History] Error running idle history task:', err);
+ }
+ }
+ };
+ scheduleRun();
+ }
+ },
+ [isDrawingRef]
+ );
+
+ const jumpToHistoryIndex = useCallback(
+ (targetIndex: number): Promise<void> => {
+ flushPendingHistoryTasks();
+ if (isDrawingRef.current) {
+ abortActiveStrokeRef.current();
+ }
+ const nextOp = historyQueueRef.current.then(async () => {
+ if (targetIndex < 0 || targetIndex >= historyRef.current.length) return;
+ const currentIndex = historyIndexRef.current;
+ if (targetIndex === currentIndex) return;
+
+ const grid = activeTileGridRef.current;
+ const undoCache = activeUndoCacheRef.current;
+ const dims = dimensionsRef.current;
+
+ if (targetIndex < currentIndex) {
+ for (let i = currentIndex; i > targetIndex; i--) {
+ const item = historyRef.current[i];
+ if (item) {
+ const targetLayerId = item.layerId || activeLayerId;
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
+ const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
+ const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+ const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
+ const deltas = await undoCache.resolveDeltas(item);
+
+ if (item.isMaskEdit && targetLayer?.maskCanvas) {
+ const mCtx = get2DContext(targetLayer.maskCanvas);
+ if (mCtx && item.beforeImageData) {
+ const mx =
+ item.dirtyRect && item.beforeImageData.width === item.dirtyRect.width
+ ? item.dirtyRect.x
+ : 0;
+ const my =
+ item.dirtyRect && item.beforeImageData.height === item.dirtyRect.height
+ ? item.dirtyRect.y
+ : 0;
+ mCtx.putImageData(item.beforeImageData, mx, my);
+ targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
+ onUpdateMaskThumbnailRef.current?.(targetLayerId);
+ }
+ } else if (item.vectorStrokesDelta && targetLayer) {
+ targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
+ const tempVec = canvas || document.createElement('canvas');
+ if (!canvas) {
+ tempVec.width = dims.width;
+ tempVec.height = dims.height;
+ }
+ const cCtx = get2DContext(tempVec);
+ if (cCtx) {
+ cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ grid.clearLayer(targetLayerId);
+ grid.ingestCanvas(
+ targetLayerId,
+ tempVec,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ if (!canvas) releaseTemporaryCanvas(tempVec);
+ } else if (deltas && deltas.length > 0) {
+ grid.applyTileDeltas(deltas, 'undo');
+
+ if (isToneStep && sourceCanvas) {
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ if (canvas && targetLayer) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ targetLayer,
+ dimensionsRef.current.dpi ?? 600,
+ item.dirtyRect
+ );
+ }
+ } else if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ if (sourceCanvas) {
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ }
+ }
+ } else if (isToneStep && sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) {
+ if (item.dirtyRect && item.beforeImageData) {
+ sCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
+ } else if (item.beforeImageData) {
+ sCtx.putImageData(item.beforeImageData, 0, 0);
+ } else if (item.type === 'initial') {
+ if (isBackgroundLayerId(targetLayerId)) {
+ sCtx.fillStyle = '#ffffff';
+ sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
+ } else {
+ sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
+ }
+ }
+ }
+
+ if (canvas && targetLayer) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ targetLayer,
+ dimensionsRef.current.dpi ?? 600,
+ item.dirtyRect
+ );
+ }
+ } else {
+ const isMono =
+ !isBackgroundLayerId(targetLayerId) &&
+ (targetLayer?.expressionColor === 'monochrome' ||
+ colorModeRef.current === 'monochrome');
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (item.beforeImageData) {
+ const bx =
+ item.dirtyRect &&
+ item.beforeImageData.width === item.dirtyRect.width &&
+ item.beforeImageData.height === item.dirtyRect.height
+ ? item.dirtyRect.x
+ : 0;
+ const by =
+ item.dirtyRect &&
+ item.beforeImageData.width === item.dirtyRect.width &&
+ item.beforeImageData.height === item.dirtyRect.height
+ ? item.dirtyRect.y
+ : 0;
+ grid.writeImageData(targetLayerId, item.beforeImageData, bx, by, targetFormat);
+ } else if (item.type === 'initial') {
+ if (isBackgroundLayerId(targetLayerId)) {
+ grid.fillLayerSolidWhite(
+ targetLayerId,
+ dims.width,
+ dims.height,
+ 'color-32bit'
+ );
+ } else {
+ grid.clearLayer(targetLayerId);
+ }
+ }
+
+ if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ }
+ if (sourceCanvas) {
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ }
+ }
+
+ onUpdateLayerThumbnail(targetLayerId);
+ }
+ }
+ } else {
+ for (let i = currentIndex + 1; i <= targetIndex; i++) {
+ const item = historyRef.current[i];
+ const dataToApply = item?.afterImageData || item?.imageData;
+ if (item) {
+ const targetLayerId = item.layerId || activeLayerId;
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
+ const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
+ const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+ const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
+ const deltas = await undoCache.resolveDeltas(item);
+
+ if (item.isMaskEdit && targetLayer?.maskCanvas) {
+ const mCtx = get2DContext(targetLayer.maskCanvas);
+ if (mCtx && dataToApply) {
+ const mx =
+ item.dirtyRect && dataToApply.width === item.dirtyRect.width
+ ? item.dirtyRect.x
+ : 0;
+ const my =
+ item.dirtyRect && dataToApply.height === item.dirtyRect.height
+ ? item.dirtyRect.y
+ : 0;
+ mCtx.putImageData(dataToApply, mx, my);
+ targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
+ onUpdateMaskThumbnailRef.current?.(targetLayerId);
+ }
+ } else if (item.vectorStrokesDelta && targetLayer) {
+ targetLayer.vectorStrokes = item.vectorStrokesDelta.after;
+ const tempVec = canvas || document.createElement('canvas');
+ if (!canvas) {
+ tempVec.width = dims.width;
+ tempVec.height = dims.height;
+ }
+ const cCtx = get2DContext(tempVec);
+ if (cCtx) {
+ cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ grid.clearLayer(targetLayerId);
+ grid.ingestCanvas(
+ targetLayerId,
+ tempVec,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ if (!canvas) releaseTemporaryCanvas(tempVec);
+ } else if (deltas && deltas.length > 0) {
+ grid.applyTileDeltas(deltas, 'redo');
+
+ if (isToneStep && sourceCanvas) {
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ if (canvas && targetLayer) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ targetLayer,
+ dimensionsRef.current.dpi ?? 600,
+ item.dirtyRect
+ );
+ }
+ } else if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ if (sourceCanvas) {
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ }
+ }
+ } else if (isToneStep && sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) {
+ if (item.dirtyRect && dataToApply) {
+ sCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);
+ } else if (dataToApply) {
+ sCtx.putImageData(dataToApply, 0, 0);
+ } else if (item.type === 'initial') {
+ if (isBackgroundLayerId(targetLayerId)) {
+ sCtx.fillStyle = '#ffffff';
+ sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
+ } else {
+ sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
+ }
+ }
+ }
+
+ if (canvas && targetLayer) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ targetLayer,
+ dimensionsRef.current.dpi ?? 600,
+ item.dirtyRect
+ );
+ }
+ } else {
+ const isMono =
+ !isBackgroundLayerId(targetLayerId) &&
+ (targetLayer?.expressionColor === 'monochrome' ||
+ colorModeRef.current === 'monochrome');
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (dataToApply) {
+ const ax =
+ item.dirtyRect &&
+ dataToApply.width === item.dirtyRect.width &&
+ dataToApply.height === item.dirtyRect.height
+ ? item.dirtyRect.x
+ : 0;
+ const ay =
+ item.dirtyRect &&
+ dataToApply.width === item.dirtyRect.width &&
+ dataToApply.height === item.dirtyRect.height
+ ? item.dirtyRect.y
+ : 0;
+ grid.writeImageData(targetLayerId, dataToApply, ax, ay, targetFormat);
+ } else if (item.type === 'initial') {
+ if (isBackgroundLayerId(targetLayerId)) {
+ grid.fillLayerSolidWhite(
+ targetLayerId,
+ dims.width,
+ dims.height,
+ 'color-32bit'
+ );
+ } else {
+ grid.clearLayer(targetLayerId);
+ }
+ }
+
+ if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ }
+ if (sourceCanvas) {
+ grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
+ }
+ }
+
+ onUpdateLayerThumbnail(targetLayerId);
+ }
+ }
+ }
+
+ historyIndexRef.current = targetIndex;
+ persistSessionHistory();
+ syncHistoryState();
+ grid.notifyChange(true);
+ });
+ historyQueueRef.current = nextOp.catch((err) => {
+ console.warn('[History] Error during jumpToHistoryIndex:', err);
+ });
+ return historyQueueRef.current;
+ },
+ [
+ abortActiveStrokeRef,
+ activeLayerId,
+ colorModeRef,
+ dimensionsRef,
+ flushPendingHistoryTasks,
+ isDrawingRef,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ layersRef,
+ onUpdateLayerThumbnail,
+ onUpdateMaskThumbnailRef,
+ persistSessionHistory,
+ syncHistoryState,
+ ]
+ );
+
+ const undo = useCallback(() => {
+ flushPendingHistoryTasks();
+ if (isDrawingRef.current) {
+ abortActiveStrokeRef.current();
+ }
+ if (historyIndexRef.current <= 0) return;
+ jumpToHistoryIndex(historyIndexRef.current - 1);
+ }, [abortActiveStrokeRef, flushPendingHistoryTasks, isDrawingRef, jumpToHistoryIndex]);
+
+ const redo = useCallback(() => {
+ flushPendingHistoryTasks();
+ if (isDrawingRef.current) {
+ abortActiveStrokeRef.current();
+ }
+ if (historyIndexRef.current >= historyRef.current.length - 1) return;
+ jumpToHistoryIndex(historyIndexRef.current + 1);
+ }, [abortActiveStrokeRef, flushPendingHistoryTasks, isDrawingRef, jumpToHistoryIndex]);
+
+ const selectiveUndo = useCallback(
+ async (peerIdToUndo?: string | number) => {
+ flushPendingHistoryTasks();
+ if (isDrawingRef.current) {
+ abortActiveStrokeRef.current();
+ }
+
+ const history = historyRef.current;
+ const currIdx = historyIndexRef.current;
+ if (currIdx < 0 || history.length === 0) return;
+
+ let targetItemIdx = -1;
+ for (let i = currIdx; i >= 0; i--) {
+ const item = history[i];
+ if (
+ !peerIdToUndo ||
+ item.peerId === peerIdToUndo ||
+ (peerIdToUndo === 'local' && !item.peerId)
+ ) {
+ targetItemIdx = i;
+ break;
+ }
+ }
+
+ if (targetItemIdx === -1) return;
+
+ const item = history[targetItemIdx];
+ const targetLayerId = item.layerId || activeLayerId;
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
+ const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
+ const grid = activeTileGridRef.current;
+ const undoCache = activeUndoCacheRef.current;
+ const dims = dimensionsRef.current;
+
+ if (item.vectorStrokesDelta && targetLayer) {
+ targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
+ const tempVec = canvas || document.createElement('canvas');
+ if (!canvas) {
+ tempVec.width = dims.width;
+ tempVec.height = dims.height;
+ }
+ const cCtx = get2DContext(tempVec);
+ if (cCtx) {
+ cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
+ renderVectorLayer(cCtx, targetLayer.vectorStrokes);
+ const isMono = targetLayer.expressionColor === 'monochrome';
+ grid.clearLayer(targetLayerId);
+ grid.ingestCanvas(targetLayerId, tempVec, isMono ? 'monochrome-1bit' : 'color-32bit');
+ }
+ if (!canvas) releaseTemporaryCanvas(tempVec);
+ } else {
+ const deltas = await undoCache.resolveDeltas(item);
+ if (deltas && deltas.length > 0) {
+ grid.applyTileDeltas(deltas, 'undo');
+ if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ }
+ } else if (item.beforeImageData) {
+ const isMono =
+ !isBackgroundLayerId(targetLayerId) &&
+ (targetLayer?.expressionColor === 'monochrome' ||
+ colorModeRef.current === 'monochrome');
+ const bx = item.dirtyRect ? item.dirtyRect.x : 0;
+ const by = item.dirtyRect ? item.dirtyRect.y : 0;
+ grid.writeImageData(
+ targetLayerId,
+ item.beforeImageData,
+ bx,
+ by,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ if (canvas) {
+ grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
+ }
+ }
+ }
+
+ historyRef.current.splice(targetItemIdx, 1);
+ historyIndexRef.current = Math.min(
+ historyIndexRef.current - 1,
+ historyRef.current.length - 1
+ );
+ persistSessionHistory();
+ syncHistoryState();
+
+ onUpdateLayerThumbnail(targetLayerId);
+ grid.notifyChange(true);
+ },
+ [
+ abortActiveStrokeRef,
+ activeLayerId,
+ colorModeRef,
+ dimensionsRef,
+ flushPendingHistoryTasks,
+ isDrawingRef,
+ layerCanvasesRef,
+ layersRef,
+ onUpdateLayerThumbnail,
+ persistSessionHistory,
+ syncHistoryState,
+ ]
+ );
+
+ const clearCanvas = useCallback(() => {
+ if (!activeLayerId || activeLayerLocked) return;
+ const dims = dimensionsRef.current;
+ if (dims.width <= 0 || dims.height <= 0) return;
+
+ const grid = activeTileGridRef.current;
+ const activeLayer = layersRef.current?.find((l) => l.id === activeLayerId);
+ const isBg = isBackgroundLayerId(activeLayerId);
+ const fullRect = { x: 0, y: 0, width: dims.width, height: dims.height };
+
+ const beforeSnapshot = isBg
+ ? grid.snapshotTilesInRect(activeLayerId, fullRect)
+ : grid.snapshotLayerTiles(activeLayerId);
+
+ let vectorDelta: { before: VectorStroke[]; after: VectorStroke[] } | undefined;
+ if (activeLayer?.type === 'vector') {
+ const beforeStrokes = [...(activeLayer.vectorStrokes || [])];
+ activeLayer.vectorStrokes = [];
+ vectorDelta = { before: beforeStrokes, after: [] };
+ }
+
+ if (isBg) {
+ grid.fillLayerSolidWhite(activeLayerId, dims.width, dims.height, 'color-32bit');
+ } else {
+ grid.clearLayer(activeLayerId);
+ grid.markLayerIngested(activeLayerId);
+ }
+
+ const tileDeltas = grid.computeDeltasFromSnapshot(
+ beforeSnapshot,
+ activeLayerId,
+ isBg ? fullRect : undefined
+ );
+
+ const canvas = layerCanvasesRef.current.get(activeLayerId);
+ if (canvas) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ if (isBg) {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ } else {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ }
+ }
+ }
+
+ const sourceCanvas = layerSourceCanvasesRef?.current?.get(activeLayerId);
+ if (sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) {
+ if (isBg) {
+ sCtx.fillStyle = '#ffffff';
+ sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
+ } else {
+ sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
+ }
+ }
+ }
+
+ onUpdateLayerThumbnail(activeLayerId);
+ pushHistoryStep(
+ 'clear',
+ 'Clear Layer',
+ null,
+ null,
+ activeLayerId,
+ fullRect,
+ tileDeltas,
+ vectorDelta
+ );
+ grid.notifyChange(true);
+ }, [
+ activeLayerId,
+ activeLayerLocked,
+ dimensionsRef,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ layersRef,
+ onUpdateLayerThumbnail,
+ pushHistoryStep,
+ ]);
+
+ const resetHistory = useCallback(
+ (targetDocumentId?: string) => {
+ flushPendingHistoryTasks();
+ const docId = targetDocumentId ?? activeSessionIdRef.current;
+ const sess = docId ? documentStore.getSession(docId) : null;
+ const targetCache = sess ? sess.undoCache : activeUndoCacheRef.current;
+ const targetGrid = sess ? sess.tileGrid : activeTileGridRef.current;
+
+ if (sess) {
+ sess.history = [];
+ sess.historyIndex = -1;
+ }
+
+ if (!targetDocumentId || targetDocumentId === activeSessionIdRef.current) {
+ historyRef.current = [];
+ historyIndexRef.current = -1;
+ lastStrokeEndRef.current = null;
+ setHistoryList([]);
+ setHistoryIndex(-1);
+ setCanUndo(false);
+ setCanRedo(false);
+ }
+
+ targetCache.clearCache().catch(() => {});
+
+ const now = Date.now();
+ const dims = dimensionsRef.current;
+ const layerId = activeLayerIdRef.current || activeLayerId;
+ if (layerId && dims.width > 0 && dims.height > 0) {
+ const thumbnail = createCanvasThumbnail(
+ { grid: targetGrid, layerId, dimensions: dims },
+ !isBackgroundLayerId(layerId)
+ );
+ const initialItem: HistoryItem = {
+ id: `hist-init-${now}`,
+ type: 'initial',
+ label: 'New Document',
+ timestamp: now,
+ timeFormatted: formatTime(now),
+ thumbnailUrl: thumbnail,
+ imageData: undefined,
+ beforeImageData: null,
+ afterImageData: null,
+ layerId,
+ };
+ if (sess) {
+ sess.history = [initialItem];
+ sess.historyIndex = 0;
+ }
+ if (!targetDocumentId || targetDocumentId === activeSessionIdRef.current) {
+ historyRef.current = [initialItem];
+ historyIndexRef.current = 0;
+ syncHistoryState();
+ }
+ }
+ },
+ [
+ activeLayerId,
+ activeLayerIdRef,
+ dimensionsRef,
+ flushPendingHistoryTasks,
+ lastStrokeEndRef,
+ syncHistoryState,
+ ]
+ );
+
+ // Swap per-document history & UndoCacheManager on activeSessionId change
+ useEffect(() => {
+ const prevDocId = activeSessionIdRef.current;
+ const nextDocId = activeSessionId ?? null;
+ if (prevDocId === nextDocId) return;
+
+ flushPendingHistoryTasks();
+ if (isDrawingRef.current) {
+ abortActiveStrokeRef.current();
+ }
+ if (prevDocId) {
+ persistSessionHistory(prevDocId);
+ }
+
+ activeSessionIdRef.current = nextDocId;
+ lastStrokeEndRef.current = null;
+
+ if (nextDocId) {
+ const sess = documentStore.getOrCreateSession(nextDocId);
+ activeTileGridRef.current = tileGrid ?? sess.tileGrid;
+ activeUndoCacheRef.current = sess.undoCache;
+ historyRef.current = sess.history;
+ historyIndexRef.current = sess.historyIndex;
+ } else {
+ activeTileGridRef.current = tileGrid ?? globalTileGrid;
+ activeUndoCacheRef.current = globalUndoCache;
+ historyRef.current = [];
+ historyIndexRef.current = -1;
+ }
+
+ syncHistoryState();
+ }, [
+ abortActiveStrokeRef,
+ activeSessionId,
+ flushPendingHistoryTasks,
+ isDrawingRef,
+ lastStrokeEndRef,
+ persistSessionHistory,
+ syncHistoryState,
+ tileGrid,
+ ]);
+
+ useEffect(() => {
+ if (historyRef.current.length > 0) return;
+ if (!activeLayerId || dimensions.width <= 0 || dimensions.height <= 0) return;
+ ensureInitialHistory();
+ }, [activeLayerId, activeSessionId, dimensions.width, dimensions.height, ensureInitialHistory]);
+
+ return {
+ activeSessionIdRef,
+ activeTileGridRef,
+ activeUndoCacheRef,
+ historyList,
+ historyIndex,
+ canUndo,
+ canRedo,
+ pushHistoryStep,
+ flushPendingHistoryTasks,
+ enqueueHistoryTask,
+ jumpToHistoryIndex,
+ undo,
+ redo,
+ selectiveUndo,
+ clearCanvas,
+ resetHistory,
+ };
+}
diff --git a/src/hooks/drawing/useSelectionTools.ts b/src/hooks/drawing/useSelectionTools.ts
new file mode 100644
index 0000000..afd3389
--- /dev/null
+++ b/src/hooks/drawing/useSelectionTools.ts
@@ -0,0 +1,1415 @@
+import React, { useState, useRef, useCallback } from 'react';
+import {
+ CanvasColorMode,
+ CanvasDimensions,
+ CanvasSelection,
+ LayerItem,
+ TransformSession,
+} from '../../types/editor';
+import { documentStore } from '../../utils/documentStore';
+import { compositeVisibleLayers } from '../../utils/floodFill';
+import {
+ isPointInSelection,
+ liftSelectionToFloating,
+ commitFloatingSelection,
+ computePolygonBounds,
+ getCanvasContentBounds,
+ floodSelectWand,
+ expandSelection,
+ contractSelection,
+ featherSelection,
+ invertSelection,
+ selectionToMask,
+ maskToBounds,
+ maskToSvgPath,
+} from '../../utils/selectionUtils';
+import {
+ renderPerspectiveQuad,
+ renderMeshWarp,
+ createDefaultPerspectiveQuad,
+ createDefaultMeshPoints,
+} from '../../utils/transformEngine';
+import { applyScreentone } from '../../utils/screentoneEngine';
+import { applyLayerEffects } from '../../utils/layerEffectsEngine';
+import { get2DContext } from '../../utils/canvasUtils';
+import { useToolStore, toolStoreActions } from '../../stores';
+import { PushHistoryStepFn } from './types';
+
+export interface UseSelectionToolsParams {
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ activeLayer: LayerItem | undefined;
+ activeLayerId: string;
+ selectedLayerIds: string[];
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ layerSourceCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ getActiveCanvas: () => HTMLCanvasElement | null;
+ updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
+ pushHistoryStep: PushHistoryStepFn;
+ showToast: (msg: string) => void;
+}
+
+export interface UseSelectionToolsResult {
+ selection: CanvasSelection | null;
+ setSelection: React.Dispatch<React.SetStateAction<CanvasSelection | null>>;
+ transformSession: TransformSession | null;
+ setTransformSession: React.Dispatch<React.SetStateAction<TransformSession | null>>;
+ isSelectionPenDrawingRef: React.MutableRefObject<boolean>;
+ handleCommitFloatingSelection: () => void;
+ handleDeselect: () => void;
+ handleClearSelection: () => void;
+ handleFillSelectionColor: () => void;
+ handleExpandSelection: (pixels?: number) => void;
+ handleContractSelection: (pixels?: number) => void;
+ handleFeatherSelection: (radius?: number) => void;
+ handleInvertSelection: () => void;
+ handleSelectAll: () => void;
+ handleStartTransform: () => void;
+ handleApplyTransform: () => void;
+ handleCancelTransform: () => void;
+ handleSelectionPointerDown: (
+ e: React.PointerEvent<HTMLElement>,
+ pt: { x: number; y: number }
+ ) => boolean;
+ handleSelectionPointerMove: (pt: { x: number; y: number }) => boolean;
+ handleSelectionPointerUp: (pt: { x: number; y: number }) => boolean;
+}
+
+export function useSelectionTools({
+ dimensions,
+ colorMode,
+ layers,
+ activeLayer,
+ activeLayerId,
+ selectedLayerIds,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ getActiveCanvas,
+ updateLayerThumbnail,
+ pushHistoryStep,
+ showToast,
+}: UseSelectionToolsParams): UseSelectionToolsResult {
+ const [selection, setSelection] = useState<CanvasSelection | null>(null);
+ const [transformSession, setTransformSession] = useState<TransformSession | null>(null);
+
+ const selectionMaskCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const isSelectionPenDrawingRef = useRef<boolean>(false);
+ const selectionPenDrawingRef = useRef<{
+ isDrawing: boolean;
+ lastPt: { x: number; y: number };
+ maskCanvas: HTMLCanvasElement;
+ ctx: CanvasRenderingContext2D;
+ } | null>(null);
+
+ const selectionDragRef = useRef<{
+ isDragging: boolean;
+ startX: number;
+ startY: number;
+ origFloatingX: number;
+ origFloatingY: number;
+ origBoundsX: number;
+ origBoundsY: number;
+ } | null>(null);
+
+ const selectRectStartRef = useRef<{ x: number; y: number } | null>(null);
+ const lassoPointsRef = useRef<Array<{ x: number; y: number }>>([]);
+
+ const handleCommitFloatingSelection = useCallback(() => {
+ if (!selection?.floating) return;
+ const targetLayerId = selection.floating.layerId || activeLayerId;
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
+ if (!canvas) return;
+
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ commitFloatingSelection(canvas, selection.floating, sourceCanvas);
+
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ if (selection.floating.beforeImageData) {
+ pushHistoryStep(
+ 'selection-move',
+ 'Move Selection',
+ selection.floating.beforeImageData,
+ afterData,
+ targetLayerId
+ );
+ } else {
+ const lyr = layers.find((l) => l.id === targetLayerId);
+ const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .writeImageData(
+ targetLayerId,
+ afterData,
+ 0,
+ 0,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ documentStore.getActiveTileGrid().notifyChange(true);
+ }
+
+ updateLayerThumbnail(targetLayerId, true);
+ setSelection((prev) => (prev ? { ...prev, floating: null } : null));
+ }, [
+ selection,
+ activeLayerId,
+ layers,
+ colorMode,
+ layerCanvasesRef,
+ getActiveCanvas,
+ layerSourceCanvasesRef,
+ pushHistoryStep,
+ updateLayerThumbnail,
+ ]);
+
+ const handleDeselect = useCallback(() => {
+ if (selection?.floating) {
+ handleCommitFloatingSelection();
+ }
+ setSelection(null);
+ }, [selection, handleCommitFloatingSelection]);
+
+ const handleClearSelection = useCallback(() => {
+ if (!selection) return;
+ if (selection.floating) {
+ const targetLayerId = selection.floating.layerId || activeLayerId;
+ const canvas = layerCanvasesRef.current.get(targetLayerId) || getActiveCanvas();
+ if (canvas && selection.floating.beforeImageData) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ pushHistoryStep(
+ 'clear',
+ 'Clear Selection',
+ selection.floating.beforeImageData,
+ afterData,
+ targetLayerId
+ );
+ documentStore.getActiveTileGrid().notifyChange(true);
+ }
+ }
+ setSelection(null);
+ return;
+ }
+
+ const canvas = getActiveCanvas();
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
+
+ const clearOn = (target: HTMLCanvasElement) => {
+ const c = get2DContext(target);
+ if (!c) return;
+ c.save();
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ const maskCanvas = document.createElement('canvas');
+ maskCanvas.width = target.width;
+ maskCanvas.height = target.height;
+ const mCtx = maskCanvas.getContext('2d');
+ if (mCtx) {
+ const mImg = mCtx.createImageData(target.width, target.height);
+ for (let i = 0; i < selection.mask.length; i++) {
+ if (isBg) {
+ mImg.data[i * 4] = 255;
+ mImg.data[i * 4 + 1] = 255;
+ mImg.data[i * 4 + 2] = 255;
+ }
+ mImg.data[i * 4 + 3] = selection.mask[i];
+ }
+ mCtx.putImageData(mImg, 0, 0);
+ c.globalCompositeOperation = isBg ? 'source-over' : 'destination-out';
+ c.drawImage(maskCanvas, 0, 0);
+ }
+ } else if (selection.type === 'rect') {
+ if (isBg) {
+ c.fillStyle = '#ffffff';
+ c.fillRect(
+ selection.bounds.x,
+ selection.bounds.y,
+ selection.bounds.width,
+ selection.bounds.height
+ );
+ } else {
+ c.clearRect(
+ selection.bounds.x,
+ selection.bounds.y,
+ selection.bounds.width,
+ selection.bounds.height
+ );
+ }
+ } else if (selection.type === 'lasso' && selection.polygon && selection.polygon.length >= 3) {
+ c.beginPath();
+ c.moveTo(selection.polygon[0].x, selection.polygon[0].y);
+ for (let i = 1; i < selection.polygon.length; i++) {
+ c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
+ }
+ c.closePath();
+ if (isBg) {
+ c.fillStyle = '#ffffff';
+ c.fill();
+ } else {
+ c.globalCompositeOperation = 'destination-out';
+ c.fillStyle = 'rgba(0, 0, 0, 1)';
+ c.fill();
+ }
+ }
+ c.restore();
+ };
+
+ clearOn(canvas);
+ if (sourceCanvas) clearOn(sourceCanvas);
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ updateLayerThumbnail(activeLayerId, true);
+ pushHistoryStep('clear', 'Clear Selection', beforeImageData, afterImageData, activeLayerId);
+ documentStore.getActiveTileGrid().notifyChange(true);
+ }, [
+ selection,
+ getActiveCanvas,
+ activeLayerId,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ updateLayerThumbnail,
+ pushHistoryStep,
+ ]);
+
+ const handleFillSelectionColor = useCallback(() => {
+ if (!selection) return;
+ const canvas = getActiveCanvas();
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const primaryColor = useToolStore.getState().primaryColor;
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+
+ const fillOn = (target: HTMLCanvasElement) => {
+ const c = get2DContext(target);
+ if (!c) return;
+ c.save();
+ if (selection.mask && selection.maskWidth && selection.maskHeight) {
+ const maskCanvas = document.createElement('canvas');
+ maskCanvas.width = target.width;
+ maskCanvas.height = target.height;
+ const mCtx = maskCanvas.getContext('2d');
+ if (mCtx) {
+ mCtx.fillStyle = primaryColor;
+ mCtx.fillRect(0, 0, target.width, target.height);
+ const mImg = mCtx.getImageData(0, 0, target.width, target.height);
+ for (let i = 0; i < selection.mask.length; i++) {
+ mImg.data[i * 4 + 3] = Math.round((mImg.data[i * 4 + 3] * selection.mask[i]) / 255);
+ }
+ mCtx.putImageData(mImg, 0, 0);
+ c.drawImage(maskCanvas, 0, 0);
+ }
+ } else {
+ c.fillStyle = primaryColor;
+ if (selection.type === 'rect') {
+ c.fillRect(
+ selection.bounds.x,
+ selection.bounds.y,
+ selection.bounds.width,
+ selection.bounds.height
+ );
+ } else if (
+ selection.type === 'lasso' &&
+ selection.polygon &&
+ selection.polygon.length >= 3
+ ) {
+ c.beginPath();
+ c.moveTo(selection.polygon[0].x, selection.polygon[0].y);
+ for (let i = 1; i < selection.polygon.length; i++) {
+ c.lineTo(selection.polygon[i].x, selection.polygon[i].y);
+ }
+ c.closePath();
+ c.fill();
+ }
+ }
+ c.restore();
+ };
+
+ fillOn(canvas);
+ if (sourceCanvas) {
+ fillOn(sourceCanvas);
+ if (activeLayer?.toneEnabled) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ activeLayer,
+ dimensions.dpi ?? 600,
+ selection.bounds
+ );
+ }
+ }
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ updateLayerThumbnail(activeLayerId, true);
+ pushHistoryStep('fill', 'Fill Selection', beforeImageData, afterImageData, activeLayerId);
+ }, [
+ selection,
+ getActiveCanvas,
+ activeLayerId,
+ activeLayer,
+ layerSourceCanvasesRef,
+ dimensions.dpi,
+ updateLayerThumbnail,
+ pushHistoryStep,
+ ]);
+
+ const handleExpandSelection = useCallback(
+ (pixels = 5) => {
+ if (!selection) return;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const currentMask = selectionToMask(selection, w, h);
+ const expanded = expandSelection(currentMask, w, h, pixels);
+ const b = maskToBounds(expanded, w, h);
+ if (!b) {
+ setSelection(null);
+ return;
+ }
+ const svg = maskToSvgPath(expanded, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: expanded,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast(`Expanded Selection (+${pixels}px)`);
+ },
+ [selection, dimensions, showToast]
+ );
+
+ const handleContractSelection = useCallback(
+ (pixels = 5) => {
+ if (!selection) return;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const currentMask = selectionToMask(selection, w, h);
+ const contracted = contractSelection(currentMask, w, h, pixels);
+ const b = maskToBounds(contracted, w, h);
+ if (!b) {
+ setSelection(null);
+ showToast('Selection contracted to empty');
+ return;
+ }
+ const svg = maskToSvgPath(contracted, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: contracted,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast(`Contracted Selection (-${pixels}px)`);
+ },
+ [selection, dimensions, showToast]
+ );
+
+ const handleFeatherSelection = useCallback(
+ (radius = 5) => {
+ if (!selection) return;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const currentMask = selectionToMask(selection, w, h);
+ const feathered = featherSelection(currentMask, w, h, radius);
+ const b = maskToBounds(feathered, w, h);
+ if (!b) {
+ setSelection(null);
+ return;
+ }
+ const svg = maskToSvgPath(feathered, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: feathered,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast(`Feathered Selection (${radius}px)`);
+ },
+ [selection, dimensions, showToast]
+ );
+
+ const handleInvertSelection = useCallback(() => {
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const currentMask = selection ? selectionToMask(selection, w, h) : new Uint8Array(w * h);
+ const inverted = invertSelection(currentMask, w, h);
+ const b = maskToBounds(inverted, w, h);
+ if (!b) {
+ setSelection(null);
+ showToast('Inverted Selection (Empty)');
+ return;
+ }
+ const svg = maskToSvgPath(inverted, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: inverted,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast('Inverted Selection');
+ }, [selection, dimensions, showToast]);
+
+ const handleSelectAll = useCallback(() => {
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const mask = new Uint8Array(w * h);
+ mask.fill(255);
+ const svg = `M 0 0 H ${w} V ${h} H 0 Z`;
+ setSelection({
+ type: 'rect',
+ bounds: { x: 0, y: 0, width: w, height: h },
+ mask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ showToast('Selected All (Ctrl+A)');
+ }, [dimensions, showToast]);
+
+ const handleStartTransform = useCallback(() => {
+ if (transformSession?.active) return;
+ const canvas = layerCanvasesRef.current.get(activeLayerId) || getActiveCanvas();
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
+
+ if (selection) {
+ let floatCanvas = selection.floating?.canvas;
+ const floatX = selection.floating?.x ?? selection.bounds.x;
+ const floatY = selection.floating?.y ?? selection.bounds.y;
+ let beforeData = selection.floating?.beforeImageData;
+
+ if (!floatCanvas) {
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+ const lifted = liftSelectionToFloating(canvas, selection, sourceCanvas, isBg);
+ if (!lifted) return;
+ floatCanvas = lifted.floatingCanvas;
+ beforeData = lifted.beforeImageData;
+ const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(activeLayerId, true);
+ }
+
+ const quad = createDefaultPerspectiveQuad(
+ floatX,
+ floatY,
+ floatCanvas.width,
+ floatCanvas.height,
+ 0
+ );
+ setTransformSession({
+ active: true,
+ layerId: activeLayerId,
+ sourceCanvas: floatCanvas,
+ beforeImageData: beforeData || ctx.getImageData(0, 0, canvas.width, canvas.height),
+ bounds: { x: floatX, y: floatY, width: floatCanvas.width, height: floatCanvas.height },
+ x: floatX,
+ y: floatY,
+ width: floatCanvas.width,
+ height: floatCanvas.height,
+ rotation: 0,
+ flipH: false,
+ flipV: false,
+ isSelection: true,
+ mode: 'affine',
+ perspectiveQuad: quad,
+ meshCols: 4,
+ meshRows: 4,
+ meshPoints: createDefaultMeshPoints(quad, 4, 4),
+ });
+ setSelection(null);
+ } else {
+ const isMultiLayer = selectedLayerIds && selectedLayerIds.length > 1;
+ const multiTargetLayers = isMultiLayer
+ ? layers.filter((l) => selectedLayerIds.includes(l.id) && l.type === 'raster')
+ : [];
+
+ if (isMultiLayer && multiTargetLayers.length > 1) {
+ const layerBeforeImages = new Map<string, ImageData>();
+ const layerSourceCanvases = new Map<string, HTMLCanvasElement>();
+
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+
+ for (const lyr of multiTargetLayers) {
+ const c = layerCanvasesRef.current.get(lyr.id);
+ if (!c) continue;
+ const cCtx = get2DContext(c);
+ if (!cCtx) continue;
+ const bData = cCtx.getImageData(0, 0, c.width, c.height);
+ layerBeforeImages.set(lyr.id, bData);
+
+ const cb = getCanvasContentBounds(
+ c,
+ lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg')
+ );
+ if (cb) {
+ minX = Math.min(minX, cb.x);
+ minY = Math.min(minY, cb.y);
+ maxX = Math.max(maxX, cb.x + cb.width);
+ maxY = Math.max(maxY, cb.y + cb.height);
+ }
+ }
+
+ if (!isFinite(minX) || !isFinite(minY) || maxX <= minX || maxY <= minY) {
+ showToast('Selected layers are empty');
+ return;
+ }
+
+ const b = {
+ x: Math.max(0, minX),
+ y: Math.max(0, minY),
+ width: Math.max(1, maxX - minX),
+ height: Math.max(1, maxY - minY),
+ };
+
+ const compositeCanvas = document.createElement('canvas');
+ compositeCanvas.width = b.width;
+ compositeCanvas.height = b.height;
+ const compCtx = get2DContext(compositeCanvas);
+
+ const orderedLayers = multiTargetLayers.slice().reverse();
+ for (const lyr of orderedLayers) {
+ const c = layerCanvasesRef.current.get(lyr.id);
+ if (!c) continue;
+ const cCtx = get2DContext(c);
+ if (!cCtx) continue;
+
+ const sCanvas = document.createElement('canvas');
+ sCanvas.width = b.width;
+ sCanvas.height = b.height;
+ const sCtx = get2DContext(sCanvas);
+ if (sCtx) {
+ sCtx.drawImage(c, -b.x, -b.y);
+ layerSourceCanvases.set(lyr.id, sCanvas);
+ }
+
+ if (compCtx) {
+ compCtx.save();
+ compCtx.globalAlpha = lyr.opacity;
+ compCtx.drawImage(sCanvas, 0, 0);
+ compCtx.restore();
+ }
+
+ const isLayerBg = lyr.id === 'layer-bg' || lyr.id.startsWith('layer-bg');
+ if (isLayerBg) {
+ cCtx.fillStyle = '#ffffff';
+ cCtx.fillRect(b.x, b.y, b.width, b.height);
+ } else {
+ cCtx.clearRect(b.x, b.y, b.width, b.height);
+ }
+
+ const existingSrc = layerSourceCanvasesRef.current?.get(lyr.id);
+ if (existingSrc) {
+ const escCtx = get2DContext(existingSrc);
+ if (escCtx) {
+ if (isLayerBg) {
+ escCtx.fillStyle = '#ffffff';
+ escCtx.fillRect(b.x, b.y, b.width, b.height);
+ } else {
+ escCtx.clearRect(b.x, b.y, b.width, b.height);
+ }
+ }
+ }
+ const isMono = colorMode === 'monochrome' || lyr.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(lyr.id, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ updateLayerThumbnail(lyr.id, true);
+ }
+ documentStore.getActiveTileGrid().notifyChange(true);
+
+ const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
+ setTransformSession({
+ active: true,
+ layerId: activeLayerId,
+ layerIds: multiTargetLayers.map((l) => l.id),
+ layerSourceCanvases,
+ layerBeforeImages,
+ sourceCanvas: compositeCanvas,
+ beforeImageData:
+ layerBeforeImages.get(activeLayerId) || Array.from(layerBeforeImages.values())[0],
+ bounds: { x: b.x, y: b.y, width: b.width, height: b.height },
+ x: b.x,
+ y: b.y,
+ width: b.width,
+ height: b.height,
+ rotation: 0,
+ flipH: false,
+ flipV: false,
+ isSelection: false,
+ mode: 'affine',
+ perspectiveQuad: quad,
+ meshCols: 4,
+ meshRows: 4,
+ meshPoints: createDefaultMeshPoints(quad, 4, 4),
+ });
+ toolStoreActions.setToolRaw('transform');
+ return;
+ }
+
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const contentBounds = getCanvasContentBounds(canvas, isBg);
+ let b = contentBounds;
+ if (!b) {
+ if (isBg) {
+ b = { x: 0, y: 0, width: canvas.width, height: canvas.height };
+ } else {
+ showToast('Active layer is empty');
+ return;
+ }
+ }
+
+ const sourceCanvas = document.createElement('canvas');
+ sourceCanvas.width = b.width;
+ sourceCanvas.height = b.height;
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) {
+ const sliceData = ctx.getImageData(b.x, b.y, b.width, b.height);
+ sCtx.putImageData(sliceData, 0, 0);
+ }
+
+ if (isBg) {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(b.x, b.y, b.width, b.height);
+ } else {
+ ctx.clearRect(b.x, b.y, b.width, b.height);
+ }
+
+ const existingSourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+ if (existingSourceCanvas) {
+ const escCtx = get2DContext(existingSourceCanvas);
+ if (escCtx) {
+ if (isBg) {
+ escCtx.fillStyle = '#ffffff';
+ escCtx.fillRect(b.x, b.y, b.width, b.height);
+ } else {
+ escCtx.clearRect(b.x, b.y, b.width, b.height);
+ }
+ }
+ }
+
+ const isMono = colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(activeLayerId, true);
+
+ const quad = createDefaultPerspectiveQuad(b.x, b.y, b.width, b.height, 0);
+ setTransformSession({
+ active: true,
+ layerId: activeLayerId,
+ sourceCanvas,
+ beforeImageData,
+ bounds: { x: b.x, y: b.y, width: b.width, height: b.height },
+ x: b.x,
+ y: b.y,
+ width: b.width,
+ height: b.height,
+ rotation: 0,
+ flipH: false,
+ flipV: false,
+ isSelection: false,
+ mode: 'affine',
+ perspectiveQuad: quad,
+ meshCols: 4,
+ meshRows: 4,
+ meshPoints: createDefaultMeshPoints(quad, 4, 4),
+ });
+ }
+ toolStoreActions.setToolRaw('transform');
+ }, [
+ transformSession,
+ getActiveCanvas,
+ selection,
+ activeLayerId,
+ activeLayer,
+ colorMode,
+ selectedLayerIds,
+ layers,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ updateLayerThumbnail,
+ showToast,
+ ]);
+
+ const handleApplyTransform = useCallback(() => {
+ if (!transformSession) return;
+
+ if (
+ transformSession.layerIds &&
+ transformSession.layerIds.length > 1 &&
+ transformSession.layerSourceCanvases
+ ) {
+ for (const lId of transformSession.layerIds) {
+ const c = layerCanvasesRef.current.get(lId);
+ const sCanvas = transformSession.layerSourceCanvases.get(lId);
+ if (!c || !sCanvas) continue;
+ const cCtx = get2DContext(c);
+ if (!cCtx) continue;
+
+ const drawLayerTransformed = (targetCtx: CanvasRenderingContext2D) => {
+ targetCtx.save();
+ if (transformSession.mode === 'perspective' && transformSession.perspectiveQuad) {
+ renderPerspectiveQuad(targetCtx, sCanvas, transformSession.perspectiveQuad, 24);
+ } else if (transformSession.mode === 'mesh' && transformSession.meshPoints) {
+ renderMeshWarp(targetCtx, sCanvas, transformSession.meshPoints, 6);
+ } else {
+ const cx = transformSession.x + transformSession.width / 2;
+ const cy = transformSession.y + transformSession.height / 2;
+ targetCtx.translate(cx, cy);
+ targetCtx.rotate((transformSession.rotation * Math.PI) / 180);
+ targetCtx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
+ targetCtx.drawImage(
+ sCanvas,
+ -transformSession.width / 2,
+ -transformSession.height / 2,
+ transformSession.width,
+ transformSession.height
+ );
+ }
+ targetCtx.restore();
+ };
+
+ drawLayerTransformed(cCtx);
+
+ const existingSrc = layerSourceCanvasesRef.current?.get(lId);
+ if (existingSrc) {
+ const sCtx = get2DContext(existingSrc);
+ if (sCtx) drawLayerTransformed(sCtx);
+ }
+
+ const lyr = layers.find((l) => l.id === lId);
+ if (lyr?.toneEnabled && existingSrc) {
+ applyScreentone(existingSrc, c, {
+ frequency: lyr.toneFrequency ?? 60,
+ angle: lyr.toneAngle ?? 45,
+ dotShape: lyr.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ });
+ }
+
+ const beforeDataForLayer = transformSession.layerBeforeImages?.get(lId);
+ const afterDataForLayer = cCtx.getImageData(0, 0, c.width, c.height);
+ const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ if (beforeDataForLayer) {
+ pushHistoryStep(
+ 'transform',
+ 'Batch Free Transform',
+ beforeDataForLayer,
+ afterDataForLayer,
+ lId
+ );
+ }
+ updateLayerThumbnail(lId, true);
+ }
+
+ documentStore.getActiveTileGrid().notifyChange(true);
+ setTransformSession(null);
+ toolStoreActions.setToolRaw('brush');
+ return;
+ }
+
+ const canvas = layerCanvasesRef.current.get(transformSession.layerId) || getActiveCanvas();
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(transformSession.layerId);
+
+ const drawTransformed = (targetCtx: CanvasRenderingContext2D) => {
+ targetCtx.save();
+ if (transformSession.mode === 'perspective' && transformSession.perspectiveQuad) {
+ renderPerspectiveQuad(
+ targetCtx,
+ transformSession.sourceCanvas,
+ transformSession.perspectiveQuad,
+ 24
+ );
+ } else if (transformSession.mode === 'mesh' && transformSession.meshPoints) {
+ renderMeshWarp(targetCtx, transformSession.sourceCanvas, transformSession.meshPoints, 6);
+ } else {
+ const cx = transformSession.x + transformSession.width / 2;
+ const cy = transformSession.y + transformSession.height / 2;
+ targetCtx.translate(cx, cy);
+ targetCtx.rotate((transformSession.rotation * Math.PI) / 180);
+ targetCtx.scale(transformSession.flipH ? -1 : 1, transformSession.flipV ? -1 : 1);
+ targetCtx.drawImage(
+ transformSession.sourceCanvas,
+ -transformSession.width / 2,
+ -transformSession.height / 2,
+ transformSession.width,
+ transformSession.height
+ );
+ }
+ targetCtx.restore();
+ };
+
+ drawTransformed(ctx);
+ if (sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (sCtx) drawTransformed(sCtx);
+ }
+
+ const layer = layers.find((l) => l.id === transformSession.layerId);
+ if (layer?.toneEnabled && sourceCanvas) {
+ applyScreentone(sourceCanvas, canvas, {
+ frequency: layer.toneFrequency ?? 60,
+ angle: layer.toneAngle ?? 45,
+ dotShape: layer.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ });
+ }
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ pushHistoryStep(
+ 'transform',
+ 'Free Transform',
+ transformSession.beforeImageData,
+ afterImageData,
+ transformSession.layerId
+ );
+ documentStore.getActiveTileGrid().notifyChange(true);
+
+ updateLayerThumbnail(transformSession.layerId, true);
+ setTransformSession(null);
+ toolStoreActions.setToolRaw('brush');
+ }, [
+ transformSession,
+ colorMode,
+ layerCanvasesRef,
+ getActiveCanvas,
+ layers,
+ layerSourceCanvasesRef,
+ dimensions.dpi,
+ pushHistoryStep,
+ updateLayerThumbnail,
+ ]);
+
+ const handleCancelTransform = useCallback(() => {
+ if (!transformSession) return;
+
+ if (transformSession.layerBeforeImages && transformSession.layerBeforeImages.size > 0) {
+ for (const [lId, beforeData] of transformSession.layerBeforeImages.entries()) {
+ const c = layerCanvasesRef.current.get(lId);
+ if (c && beforeData) {
+ const ctx = get2DContext(c);
+ ctx?.putImageData(beforeData, 0, 0);
+
+ const lyr = layers.find((l) => l.id === lId);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(lId);
+ if (sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ sCtx?.putImageData(beforeData, 0, 0);
+
+ if (lyr?.toneEnabled) {
+ applyScreentone(sourceCanvas, c, {
+ frequency: lyr.toneFrequency ?? 60,
+ angle: lyr.toneAngle ?? 45,
+ dotShape: lyr.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ });
+ }
+ }
+ const isMono = colorMode === 'monochrome' || lyr?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(lId, c, isMono ? 'monochrome-1bit' : 'color-32bit');
+ updateLayerThumbnail(lId, true);
+ }
+ }
+ documentStore.getActiveTileGrid().notifyChange(true);
+ setTransformSession(null);
+ toolStoreActions.setToolRaw('brush');
+ return;
+ }
+
+ const canvas = layerCanvasesRef.current.get(transformSession.layerId) || getActiveCanvas();
+ if (canvas && transformSession.beforeImageData) {
+ const ctx = get2DContext(canvas);
+ ctx?.putImageData(transformSession.beforeImageData, 0, 0);
+
+ const layer = layers.find((l) => l.id === transformSession.layerId);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(transformSession.layerId);
+ if (sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ sCtx?.putImageData(transformSession.beforeImageData, 0, 0);
+
+ if (layer?.toneEnabled) {
+ applyScreentone(sourceCanvas, canvas, {
+ frequency: layer.toneFrequency ?? 60,
+ angle: layer.toneAngle ?? 45,
+ dotShape: layer.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ });
+ }
+ }
+ const isMono = colorMode === 'monochrome' || layer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(transformSession.layerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(transformSession.layerId, true);
+ }
+ setTransformSession(null);
+ toolStoreActions.setToolRaw('brush');
+ }, [
+ transformSession,
+ colorMode,
+ layerCanvasesRef,
+ getActiveCanvas,
+ layers,
+ layerSourceCanvasesRef,
+ dimensions.dpi,
+ updateLayerThumbnail,
+ ]);
+
+ const handleSelectionPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
+ const { tool, wandSettings, brushSettings } = useToolStore.getState();
+
+ if (tool === 'select-wand') {
+ e.preventDefault();
+ if (selection?.floating) {
+ handleCommitFloatingSelection();
+ }
+
+ const px = Math.floor(pt.x);
+ const py = Math.floor(pt.y);
+ if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return true;
+
+ let sampleCanvas: HTMLCanvasElement | null = null;
+ if (wandSettings.referMode === 'all') {
+ sampleCanvas = compositeVisibleLayers(layers, layerCanvasesRef.current, dimensions);
+ } else if (wandSettings.referMode === 'reference') {
+ const refLayer = layers.find((l) => l.isReference && l.visible);
+ if (refLayer) {
+ sampleCanvas = layerCanvasesRef.current.get(refLayer.id) || null;
+ } else {
+ sampleCanvas = layerCanvasesRef.current.get(activeLayerId) || getActiveCanvas();
+ }
+ } else {
+ sampleCanvas = layerCanvasesRef.current.get(activeLayerId) || getActiveCanvas();
+ }
+
+ if (!sampleCanvas) return true;
+ const sCtx = get2DContext(sampleCanvas);
+ if (!sCtx) return true;
+
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const sampleImageData = sCtx.getImageData(0, 0, w, h);
+ const { mask, bounds } = floodSelectWand(sampleImageData, w, h, px, py, wandSettings);
+
+ if (!bounds || bounds.width === 0 || bounds.height === 0) {
+ setSelection(null);
+ return true;
+ }
+
+ const svgPath = maskToSvgPath(mask, w, h);
+ setSelection({
+ type: 'wand',
+ bounds,
+ mask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath,
+ });
+ return true;
+ }
+
+ if (tool === 'select-pen' || tool === 'select-eraser') {
+ e.preventDefault();
+ if (selection?.floating) {
+ handleCommitFloatingSelection();
+ }
+
+ const w = dimensions.width;
+ const h = dimensions.height;
+ let maskCanvas = selectionMaskCanvasRef.current;
+ if (!maskCanvas || maskCanvas.width !== w || maskCanvas.height !== h) {
+ maskCanvas = document.createElement('canvas');
+ maskCanvas.width = w;
+ maskCanvas.height = h;
+ selectionMaskCanvasRef.current = maskCanvas;
+ }
+
+ const mCtx = get2DContext(maskCanvas);
+ if (!mCtx) return true;
+
+ mCtx.clearRect(0, 0, w, h);
+ if (selection) {
+ const currentMask = selectionToMask(selection, w, h);
+ const imgData = mCtx.createImageData(w, h);
+ for (let i = 0; i < currentMask.length; i++) {
+ const val = currentMask[i];
+ const idx = i * 4;
+ imgData.data[idx] = val;
+ imgData.data[idx + 1] = val;
+ imgData.data[idx + 2] = val;
+ imgData.data[idx + 3] = val > 0 ? 255 : 0;
+ }
+ mCtx.putImageData(imgData, 0, 0);
+ }
+
+ const brushSize = brushSettings.size;
+ mCtx.save();
+ mCtx.lineCap = 'round';
+ mCtx.lineJoin = 'round';
+ mCtx.lineWidth = brushSize;
+ if (tool === 'select-pen') {
+ mCtx.globalCompositeOperation = 'source-over';
+ mCtx.fillStyle = '#ffffff';
+ mCtx.strokeStyle = '#ffffff';
+ } else {
+ mCtx.globalCompositeOperation = 'destination-out';
+ mCtx.fillStyle = '#000000';
+ mCtx.strokeStyle = '#000000';
+ }
+
+ mCtx.beginPath();
+ mCtx.arc(pt.x, pt.y, brushSize / 2, 0, Math.PI * 2);
+ mCtx.fill();
+ mCtx.restore();
+
+ isSelectionPenDrawingRef.current = true;
+ selectionPenDrawingRef.current = {
+ isDrawing: true,
+ lastPt: pt,
+ maskCanvas,
+ ctx: mCtx,
+ };
+
+ const mImgData = mCtx.getImageData(0, 0, w, h);
+ const newMask = new Uint8Array(w * h);
+ for (let i = 0; i < newMask.length; i++) {
+ newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;
+ }
+ const b = maskToBounds(newMask, w, h);
+ if (b) {
+ const svg = maskToSvgPath(newMask, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: newMask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ } else {
+ setSelection(null);
+ }
+ return true;
+ }
+
+ if (tool === 'select-rect' || tool === 'select-lasso') {
+ e.preventDefault();
+ if (selection && isPointInSelection(pt.x, pt.y, selection)) {
+ const canvas = getActiveCanvas();
+ if (!canvas) return true;
+
+ if (!selection.floating) {
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+ const isBg = activeLayerId === 'layer-bg' || activeLayerId.startsWith('layer-bg');
+ const lifted = liftSelectionToFloating(canvas, selection, sourceCanvas, isBg);
+ if (lifted) {
+ const isMono =
+ colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(activeLayerId, canvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(activeLayerId, true);
+ const floatingObj = {
+ canvas: lifted.floatingCanvas,
+ x: selection.bounds.x,
+ y: selection.bounds.y,
+ origX: selection.bounds.x,
+ origY: selection.bounds.y,
+ layerId: activeLayerId,
+ beforeImageData: lifted.beforeImageData,
+ };
+ setSelection({
+ ...selection,
+ floating: floatingObj,
+ });
+ selectionDragRef.current = {
+ isDragging: true,
+ startX: pt.x,
+ startY: pt.y,
+ origFloatingX: selection.bounds.x,
+ origFloatingY: selection.bounds.y,
+ origBoundsX: selection.bounds.x,
+ origBoundsY: selection.bounds.y,
+ };
+ }
+ } else {
+ selectionDragRef.current = {
+ isDragging: true,
+ startX: pt.x,
+ startY: pt.y,
+ origFloatingX: selection.floating.x,
+ origFloatingY: selection.floating.y,
+ origBoundsX: selection.bounds.x,
+ origBoundsY: selection.bounds.y,
+ };
+ }
+ return true;
+ }
+
+ if (selection?.floating) {
+ handleCommitFloatingSelection();
+ }
+
+ if (tool === 'select-rect') {
+ selectRectStartRef.current = pt;
+ setSelection({
+ type: 'rect',
+ bounds: { x: pt.x, y: pt.y, width: 0, height: 0 },
+ });
+ } else {
+ lassoPointsRef.current = [pt];
+ setSelection({
+ type: 'lasso',
+ bounds: { x: pt.x, y: pt.y, width: 0, height: 0 },
+ polygon: [pt],
+ });
+ }
+ return true;
+ }
+
+ return false;
+ },
+ [
+ selection,
+ handleCommitFloatingSelection,
+ dimensions,
+ layers,
+ layerCanvasesRef,
+ activeLayerId,
+ getActiveCanvas,
+ layerSourceCanvasesRef,
+ colorMode,
+ activeLayer,
+ updateLayerThumbnail,
+ ]
+ );
+
+ const handleSelectionPointerMove = useCallback((pt: { x: number; y: number }): boolean => {
+ const { tool, brushSettings } = useToolStore.getState();
+
+ if ((tool === 'select-pen' || tool === 'select-eraser') && selectionPenDrawingRef.current?.isDrawing) {
+ const { ctx: mCtx, lastPt } = selectionPenDrawingRef.current;
+ const brushSize = brushSettings.size;
+ mCtx.save();
+ mCtx.lineCap = 'round';
+ mCtx.lineJoin = 'round';
+ mCtx.lineWidth = brushSize;
+ if (tool === 'select-pen') {
+ mCtx.globalCompositeOperation = 'source-over';
+ mCtx.strokeStyle = '#ffffff';
+ } else {
+ mCtx.globalCompositeOperation = 'destination-out';
+ mCtx.strokeStyle = '#000000';
+ }
+
+ mCtx.beginPath();
+ mCtx.moveTo(lastPt.x, lastPt.y);
+ mCtx.lineTo(pt.x, pt.y);
+ mCtx.stroke();
+ mCtx.restore();
+
+ selectionPenDrawingRef.current.lastPt = pt;
+ return true;
+ }
+
+ if (selectionDragRef.current?.isDragging) {
+ const drag = selectionDragRef.current;
+ const dx = pt.x - drag.startX;
+ const dy = pt.y - drag.startY;
+ setSelection((prev) => {
+ if (!prev || !prev.floating) return prev;
+ const newX = Math.round(drag.origFloatingX + dx);
+ const newY = Math.round(drag.origFloatingY + dy);
+ const boundsX = Math.round(drag.origBoundsX + dx);
+ const boundsY = Math.round(drag.origBoundsY + dy);
+ let updatedPoly = prev.polygon;
+ if (prev.type === 'lasso' && prev.polygon) {
+ const shiftX = boundsX - prev.bounds.x;
+ const shiftY = boundsY - prev.bounds.y;
+ updatedPoly = prev.polygon.map((p) => ({ x: p.x + shiftX, y: p.y + shiftY }));
+ }
+ return {
+ ...prev,
+ bounds: { ...prev.bounds, x: boundsX, y: boundsY },
+ polygon: updatedPoly,
+ floating: {
+ ...prev.floating,
+ x: newX,
+ y: newY,
+ },
+ };
+ });
+ return true;
+ }
+
+ if (selectRectStartRef.current) {
+ const s = selectRectStartRef.current;
+ const minX = Math.floor(Math.min(s.x, pt.x));
+ const minY = Math.floor(Math.min(s.y, pt.y));
+ const w = Math.ceil(Math.abs(pt.x - s.x));
+ const h = Math.ceil(Math.abs(pt.y - s.y));
+ setSelection({
+ type: 'rect',
+ bounds: { x: minX, y: minY, width: w, height: h },
+ });
+ return true;
+ }
+
+ if (lassoPointsRef.current.length > 0) {
+ const pts = lassoPointsRef.current;
+ const last = pts[pts.length - 1];
+ if (Math.hypot(pt.x - last.x, pt.y - last.y) >= 2) {
+ pts.push(pt);
+ const b = computePolygonBounds(pts);
+ setSelection({
+ type: 'lasso',
+ bounds: b,
+ polygon: [...pts],
+ });
+ }
+ return true;
+ }
+
+ return false;
+ }, []);
+
+ const handleSelectionPointerUp = useCallback(
+ (pt: { x: number; y: number }): boolean => {
+ const { tool } = useToolStore.getState();
+
+ if (
+ (tool === 'select-pen' || tool === 'select-eraser') &&
+ selectionPenDrawingRef.current?.isDrawing
+ ) {
+ const { ctx: mCtx } = selectionPenDrawingRef.current;
+ selectionPenDrawingRef.current = null;
+ isSelectionPenDrawingRef.current = false;
+ const w = dimensions.width;
+ const h = dimensions.height;
+ const mImgData = mCtx.getImageData(0, 0, w, h);
+ const newMask = new Uint8Array(w * h);
+ for (let i = 0; i < newMask.length; i++) {
+ newMask[i] = mImgData.data[i * 4 + 3] > 0 ? 255 : 0;
+ }
+ const b = maskToBounds(newMask, w, h);
+ if (b) {
+ const svg = maskToSvgPath(newMask, w, h);
+ setSelection({
+ type: 'mask',
+ bounds: b,
+ mask: newMask,
+ maskWidth: w,
+ maskHeight: h,
+ svgPath: svg,
+ });
+ } else {
+ setSelection(null);
+ }
+ return true;
+ }
+
+ if (selectionDragRef.current?.isDragging) {
+ selectionDragRef.current = null;
+ return true;
+ }
+
+ if (selectRectStartRef.current) {
+ const s = selectRectStartRef.current;
+ selectRectStartRef.current = null;
+ const minX = Math.floor(Math.min(s.x, pt.x));
+ const minY = Math.floor(Math.min(s.y, pt.y));
+ const w = Math.ceil(Math.abs(pt.x - s.x));
+ const h = Math.ceil(Math.abs(pt.y - s.y));
+ if (w < 4 || h < 4) {
+ setSelection(null);
+ } else {
+ setSelection({
+ type: 'rect',
+ bounds: { x: minX, y: minY, width: w, height: h },
+ });
+ }
+ return true;
+ }
+
+ if (lassoPointsRef.current.length > 0) {
+ if (lassoPointsRef.current.length < 3) {
+ setSelection(null);
+ } else {
+ const b = computePolygonBounds(lassoPointsRef.current);
+ setSelection({
+ type: 'lasso',
+ bounds: b,
+ polygon: [...lassoPointsRef.current],
+ });
+ }
+ lassoPointsRef.current = [];
+ return true;
+ }
+
+ return false;
+ },
+ [dimensions.height, dimensions.width]
+ );
+
+ return {
+ selection,
+ setSelection,
+ transformSession,
+ setTransformSession,
+ isSelectionPenDrawingRef,
+ handleCommitFloatingSelection,
+ handleDeselect,
+ handleClearSelection,
+ handleFillSelectionColor,
+ handleExpandSelection,
+ handleContractSelection,
+ handleFeatherSelection,
+ handleInvertSelection,
+ handleSelectAll,
+ handleStartTransform,
+ handleApplyTransform,
+ handleCancelTransform,
+ handleSelectionPointerDown,
+ handleSelectionPointerMove,
+ handleSelectionPointerUp,
+ };
+}
diff --git a/src/hooks/drawing/useShapeAndFillTools.ts b/src/hooks/drawing/useShapeAndFillTools.ts
new file mode 100644
index 0000000..e059566
--- /dev/null
+++ b/src/hooks/drawing/useShapeAndFillTools.ts
@@ -0,0 +1,832 @@
+import React, { useState, useRef, useCallback } from 'react';
+import {
+ CanvasColorMode,
+ CanvasDimensions,
+ CanvasSelection,
+ LayerItem,
+ SpeechBalloon,
+ TextSettings,
+} from '../../types/editor';
+import { documentStore } from '../../utils/documentStore';
+import {
+ executeFloodFill,
+ compositeVisibleLayers,
+ compositeReferenceLayers,
+ executeLassoFill,
+} from '../../utils/floodFill';
+import { applyLiquifyStep, createLiquifySelectionMask, DirtyRect } from '../../utils/liquifyEngine';
+import { applyLayerEffects } from '../../utils/layerEffectsEngine';
+import { createSelectionMask } from '../../utils/tonalEngine';
+import { get2DContext, sampleCompositedColor } from '../../utils/canvasUtils';
+import { renderMangaTextToCanvas } from '../../utils/mangaTextEngine';
+import { createDefaultSpeechBalloon, renderSpeechBalloon } from '../../utils/balloonEngine';
+import { useToolStore, toolStoreActions } from '../../stores';
+import { PushHistoryStepFn } from './types';
+
+export interface TextPlacementSession {
+ x: number;
+ y: number;
+ settings: TextSettings;
+}
+
+export interface UseShapeAndFillToolsParams {
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ activeLayer: LayerItem | undefined;
+ activeLayerId: string;
+ selection: CanvasSelection | null;
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ layerSourceCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ isLayerEffectivelyVisible: (layer: LayerItem) => boolean;
+ getEffectiveOpacity: (layer: LayerItem) => number;
+ getActiveCanvas: () => HTMLCanvasElement | null;
+ getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => { x: number; y: number };
+ updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
+ pushHistoryStep: PushHistoryStepFn;
+}
+
+export interface UseShapeAndFillToolsResult {
+ textSession: TextPlacementSession | null;
+ setTextSession: React.Dispatch<React.SetStateAction<TextPlacementSession | null>>;
+ activeBalloon: SpeechBalloon | null;
+ setActiveBalloon: React.Dispatch<React.SetStateAction<SpeechBalloon | null>>;
+ isPipetteSamplingRef: React.MutableRefObject<boolean>;
+ handleSampleColor: (pt: { x: number; y: number }) => void;
+ handleConfirmText: () => void;
+ handleCancelText: () => void;
+ handleConfirmBalloon: () => void;
+ handleDeleteBalloon: () => void;
+ handleShapeFillPointerDown: (
+ e: React.PointerEvent<HTMLElement>,
+ pt: { x: number; y: number }
+ ) => boolean;
+ handleShapeFillPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;
+ handleShapeFillPointerUp: (
+ e: React.PointerEvent<HTMLElement>,
+ pt: { x: number; y: number }
+ ) => boolean;
+}
+
+export function useShapeAndFillTools({
+ dimensions,
+ colorMode,
+ layers,
+ activeLayer,
+ activeLayerId,
+ selection,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ isLayerEffectivelyVisible,
+ getEffectiveOpacity,
+ getActiveCanvas,
+ getCanvasCoords,
+ updateLayerThumbnail,
+ pushHistoryStep,
+}: UseShapeAndFillToolsParams): UseShapeAndFillToolsResult {
+ const [textSession, setTextSession] = useState<TextPlacementSession | null>(null);
+ const [activeBalloon, setActiveBalloon] = useState<SpeechBalloon | null>(null);
+
+ const isPipetteSamplingRef = useRef<boolean>(false);
+ const lassoFillPointsRef = useRef<Array<{ x: number; y: number }>>([]);
+ const frameStartRef = useRef<{ x: number; y: number } | null>(null);
+
+ const isLiquifyingRef = useRef<boolean>(false);
+ const prevLiquifyPointRef = useRef<{ x: number; y: number } | null>(null);
+ const liquifyBeforeImageDataRef = useRef<ImageData | null>(null);
+ const liquifyInitialImageDataRef = useRef<ImageData | null>(null);
+ const liquifyDirtyRectRef = useRef<DirtyRect | null>(null);
+ const liquifyRafIdRef = useRef<number | null>(null);
+ const liquifyLastPointerPosRef = useRef<{
+ pt: { x: number; y: number };
+ pressure: number;
+ } | null>(null);
+ const liquifySelectionMaskRef = useRef<Uint8Array | null>(null);
+
+ const handleSampleColor = useCallback(
+ (pt: { x: number; y: number }) => {
+ const sampled = sampleCompositedColor(
+ layers,
+ layerCanvasesRef.current,
+ pt.x,
+ pt.y,
+ isLayerEffectivelyVisible,
+ getEffectiveOpacity,
+ dimensions.width,
+ dimensions.height,
+ selection?.floating
+ );
+ if (sampled) {
+ toolStoreActions.setPrimaryColor(sampled, true, colorMode);
+ }
+ },
+ [
+ layers,
+ layerCanvasesRef,
+ isLayerEffectivelyVisible,
+ getEffectiveOpacity,
+ dimensions.width,
+ dimensions.height,
+ selection?.floating,
+ colorMode,
+ ]
+ );
+
+ const handleConfirmText = useCallback(() => {
+ if (!textSession || !textSession.settings.text.trim()) {
+ setTextSession(null);
+ return;
+ }
+ const canvas = getActiveCanvas();
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+
+ const renderTextOn = (target: HTMLCanvasElement) => {
+ const c = get2DContext(target);
+ if (!c) return;
+ const s = textSession.settings;
+ renderMangaTextToCanvas(c, s.text, textSession.x, textSession.y, {
+ fontSize: s.fontSize,
+ fontFamily: s.fontFamily,
+ writingMode: s.writingMode || 'horizontal-tb',
+ bold: s.bold,
+ italic: s.italic,
+ align: s.align,
+ color: s.color,
+ outline: s.outline,
+ outlineColor: s.outlineColor,
+ outlineWidth: s.outlineWidth,
+ anchorTopLeft: true,
+ });
+ };
+
+ renderTextOn(canvas);
+ if (sourceCanvas) renderTextOn(sourceCanvas);
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ updateLayerThumbnail(activeLayerId, true);
+ pushHistoryStep('text', 'Manga Text', beforeImageData, afterImageData, activeLayerId);
+ documentStore.getActiveTileGrid().notifyChange(true);
+ setTextSession(null);
+ }, [
+ textSession,
+ getActiveCanvas,
+ activeLayerId,
+ layerSourceCanvasesRef,
+ updateLayerThumbnail,
+ pushHistoryStep,
+ ]);
+
+ const handleCancelText = useCallback(() => {
+ setTextSession(null);
+ }, []);
+
+ const handleConfirmBalloon = useCallback(() => {
+ if (!activeBalloon) return;
+ const canvas = getActiveCanvas();
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+
+ const drawOn = (target: HTMLCanvasElement) => {
+ const c = get2DContext(target);
+ if (!c) return;
+ renderSpeechBalloon(c, activeBalloon);
+ };
+
+ drawOn(canvas);
+ if (sourceCanvas) drawOn(sourceCanvas);
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ updateLayerThumbnail(activeLayerId, true);
+ pushHistoryStep('frame', 'Speech Balloon', beforeImageData, afterImageData, activeLayerId);
+ documentStore.getActiveTileGrid().notifyChange(true);
+ setActiveBalloon(null);
+ }, [
+ activeBalloon,
+ getActiveCanvas,
+ activeLayerId,
+ layerSourceCanvasesRef,
+ updateLayerThumbnail,
+ pushHistoryStep,
+ ]);
+
+ const handleDeleteBalloon = useCallback(() => {
+ setActiveBalloon(null);
+ }, []);
+
+ const startLiquifyLoop = useCallback(
+ (canvas: HTMLCanvasElement, sourceCanvas: HTMLCanvasElement | undefined, isTone: boolean) => {
+ if (liquifyRafIdRef.current) cancelAnimationFrame(liquifyRafIdRef.current);
+
+ const tick = () => {
+ if (!isLiquifyingRef.current || !liquifyLastPointerPosRef.current) {
+ liquifyRafIdRef.current = null;
+ return;
+ }
+ const { pt, pressure } = liquifyLastPointerPosRef.current;
+ const liquifySettings = useToolStore.getState().liquifySettings;
+ const dirty = applyLiquifyStep({
+ canvas,
+ sourceCanvas: isTone ? sourceCanvas : undefined,
+ cx: pt.x,
+ cy: pt.y,
+ prevX: pt.x,
+ prevY: pt.y,
+ settings: liquifySettings,
+ pressure,
+ initialImageData: liquifyInitialImageDataRef.current,
+ selectionMask: liquifySelectionMaskRef.current,
+ });
+
+ if (dirty) {
+ if (activeLayer?.toneEnabled && sourceCanvas) {
+ const displayCanvas = layerCanvasesRef.current.get(activeLayerId);
+ if (displayCanvas) {
+ applyLayerEffects(
+ sourceCanvas,
+ displayCanvas,
+ activeLayer,
+ dimensions.dpi ?? 600,
+ dirty
+ );
+ }
+ } else {
+ const dCtx = get2DContext(canvas);
+ if (dCtx && dirty.width > 0 && dirty.height > 0) {
+ const subData = dCtx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
+ const isMono =
+ colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .writeImageData(
+ activeLayerId,
+ subData,
+ dirty.x,
+ dirty.y,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ }
+ documentStore.getActiveTileGrid().notifyChange(true);
+ }
+
+ liquifyRafIdRef.current = requestAnimationFrame(tick);
+ };
+
+ liquifyRafIdRef.current = requestAnimationFrame(tick);
+ },
+ [activeLayer, activeLayerId, colorMode, dimensions.dpi, layerCanvasesRef]
+ );
+
+ const handleShapeFillPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
+ const {
+ tool,
+ primaryColor,
+ fillSettings,
+ textSettings,
+ balloonSettings,
+ liquifySettings,
+ } = useToolStore.getState();
+
+ if (tool === 'pipette') {
+ e.preventDefault();
+ try {
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ } catch {
+ // Ignore pointer capture errors
+ }
+ isPipetteSamplingRef.current = true;
+ handleSampleColor(pt);
+ return true;
+ }
+
+ if (tool === 'liquify') {
+ e.preventDefault();
+ if (
+ !activeLayer ||
+ activeLayer.locked ||
+ (activeLayer && !isLayerEffectivelyVisible(activeLayer))
+ ) {
+ return true;
+ }
+ const targetLayerId = activeLayerId;
+ const isTone = Boolean(
+ activeLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
+ const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+ if (!canvas) return true;
+
+ const ctx = get2DContext(canvas);
+ if (!ctx) return true;
+
+ isLiquifyingRef.current = true;
+ prevLiquifyPointRef.current = pt;
+ liquifyBeforeImageDataRef.current = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ liquifyInitialImageDataRef.current = liquifyBeforeImageDataRef.current;
+ liquifySelectionMaskRef.current = createLiquifySelectionMask(
+ selection,
+ canvas.width,
+ canvas.height
+ );
+ liquifyDirtyRectRef.current = null;
+ liquifyLastPointerPosRef.current = { pt, pressure: e.pressure || 1.0 };
+
+ try {
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ } catch {
+ // Ignore pointer capture errors
+ }
+
+ const mode = liquifySettings.mode;
+ if (
+ mode === 'expand' ||
+ mode === 'pinch' ||
+ mode === 'twirl-cw' ||
+ mode === 'twirl-ccw' ||
+ mode === 'reconstruct'
+ ) {
+ const dirty = applyLiquifyStep({
+ canvas,
+ sourceCanvas: isTone ? sourceCanvas : undefined,
+ cx: pt.x,
+ cy: pt.y,
+ prevX: pt.x,
+ prevY: pt.y,
+ settings: liquifySettings,
+ pressure: e.pressure || 1.0,
+ initialImageData: liquifyInitialImageDataRef.current,
+ selectionMask: liquifySelectionMaskRef.current,
+ });
+ if (dirty) {
+ liquifyDirtyRectRef.current = dirty;
+ if (activeLayer?.toneEnabled && sourceCanvas && displayCanvas) {
+ applyLayerEffects(
+ sourceCanvas,
+ displayCanvas,
+ activeLayer,
+ dimensions.dpi ?? 600,
+ dirty
+ );
+ } else if (dirty.width > 0 && dirty.height > 0) {
+ const subData = ctx.getImageData(dirty.x, dirty.y, dirty.width, dirty.height);
+ const isMono =
+ colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .writeImageData(
+ targetLayerId,
+ subData,
+ dirty.x,
+ dirty.y,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ documentStore.getActiveTileGrid().notifyChange(true);
+ }
+ startLiquifyLoop(canvas, sourceCanvas, isTone);
+ }
+ return true;
+ }
+
+ if (tool === 'fill') {
+ e.preventDefault();
+ if (fillSettings.method === 'lasso') {
+ lassoFillPointsRef.current = [pt];
+ return true;
+ }
+
+ const px = Math.floor(pt.x);
+ const py = Math.floor(pt.y);
+ if (px < 0 || px >= dimensions.width || py < 0 || py >= dimensions.height) return true;
+
+ const canvas = getActiveCanvas();
+ if (
+ !canvas ||
+ activeLayer?.locked ||
+ (activeLayer && !isLayerEffectivelyVisible(activeLayer))
+ ) {
+ return true;
+ }
+
+ const ctx = get2DContext(canvas);
+ if (!ctx) return true;
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+
+ let refCanvas: HTMLCanvasElement;
+ if (fillSettings.method === 'refer-all') {
+ refCanvas = compositeVisibleLayers(layers, layerCanvasesRef.current, dimensions);
+ } else if (fillSettings.method === 'refer-reference') {
+ refCanvas = compositeReferenceLayers(layers, layerCanvasesRef.current, dimensions);
+ } else {
+ refCanvas = canvas;
+ }
+
+ const selMask = selection
+ ? createSelectionMask(selection, canvas.width, canvas.height)
+ : null;
+ const fillRes = executeFloodFill(
+ canvas,
+ refCanvas,
+ px,
+ py,
+ primaryColor,
+ fillSettings.tolerance,
+ sourceCanvas,
+ {
+ closeGap: fillSettings.closeGap ?? 0,
+ areaScale: fillSettings.areaScale ?? 0,
+ antiAlias: fillSettings.antiAlias ?? true,
+ selectionMask: selMask,
+ }
+ );
+ if (activeLayer?.toneEnabled && sourceCanvas) {
+ applyLayerEffects(
+ sourceCanvas,
+ canvas,
+ activeLayer,
+ dimensions.dpi ?? 600,
+ fillRes.dirtyRect ?? undefined
+ );
+ }
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ updateLayerThumbnail(activeLayerId, true);
+ pushHistoryStep('fill', 'Bucket Fill', beforeImageData, afterImageData, activeLayerId);
+ documentStore.getActiveTileGrid().notifyChange(true);
+ return true;
+ }
+
+ if (tool === 'frame') {
+ e.preventDefault();
+ frameStartRef.current = pt;
+ return true;
+ }
+
+ if (tool === 'text') {
+ e.preventDefault();
+ setTextSession({
+ x: Math.round(pt.x),
+ y: Math.round(pt.y),
+ settings: { ...textSettings },
+ });
+ return true;
+ }
+
+ if (tool === 'balloon') {
+ e.preventDefault();
+ const newBalloon = createDefaultSpeechBalloon(
+ Math.round(pt.x - 100),
+ Math.round(pt.y - 70),
+ 200,
+ 140,
+ balloonSettings.shape
+ );
+ newBalloon.strokeWidth = balloonSettings.strokeWidth;
+ newBalloon.strokeColor = primaryColor || '#000000';
+ newBalloon.fillColor = balloonSettings.fillColor || '#ffffff';
+ newBalloon.vertical = balloonSettings.vertical;
+ setActiveBalloon(newBalloon);
+ return true;
+ }
+
+ return false;
+ },
+ [
+ handleSampleColor,
+ activeLayer,
+ activeLayerId,
+ isLayerEffectivelyVisible,
+ layerSourceCanvasesRef,
+ layerCanvasesRef,
+ selection,
+ dimensions,
+ colorMode,
+ startLiquifyLoop,
+ getActiveCanvas,
+ layers,
+ updateLayerThumbnail,
+ pushHistoryStep,
+ ]
+ );
+
+ const handleShapeFillPointerMove = useCallback(
+ (e: React.PointerEvent<HTMLElement>): boolean => {
+ const { tool, fillSettings, liquifySettings } = useToolStore.getState();
+
+ if (tool === 'pipette') {
+ if (isPipetteSamplingRef.current) {
+ const pt = getCanvasCoords(e);
+ handleSampleColor(pt);
+ }
+ return true;
+ }
+
+ if (tool === 'liquify') {
+ if (!isLiquifyingRef.current) return true;
+ const pt = getCanvasCoords(e);
+ const pressure = e.pressure || 1.0;
+ liquifyLastPointerPosRef.current = { pt, pressure };
+
+ const targetLayerId = activeLayerId;
+ const isTone = Boolean(
+ activeLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
+ const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+ if (!canvas) return true;
+
+ const prev = prevLiquifyPointRef.current || pt;
+ const dist = Math.hypot(pt.x - prev.x, pt.y - prev.y);
+ const stepDist = Math.max(2, (liquifySettings.size / 2) * 0.25);
+ const numSteps = Math.max(1, Math.ceil(dist / stepDist));
+
+ let overallDirty: DirtyRect | null = null;
+ for (let i = 1; i <= numSteps; i++) {
+ const t = i / numSteps;
+ const cx = prev.x + (pt.x - prev.x) * t;
+ const cy = prev.y + (pt.y - prev.y) * t;
+ const px = prev.x + (pt.x - prev.x) * ((i - 1) / numSteps);
+ const py = prev.y + (pt.y - prev.y) * ((i - 1) / numSteps);
+
+ const dirty = applyLiquifyStep({
+ canvas,
+ sourceCanvas: isTone ? sourceCanvas : undefined,
+ cx,
+ cy,
+ prevX: px,
+ prevY: py,
+ settings: liquifySettings,
+ pressure,
+ initialImageData: liquifyInitialImageDataRef.current,
+ selectionMask: liquifySelectionMaskRef.current,
+ });
+
+ if (dirty) {
+ if (!overallDirty) {
+ overallDirty = { ...dirty };
+ } else {
+ const minX = Math.min(overallDirty.x, dirty.x);
+ const minY = Math.min(overallDirty.y, dirty.y);
+ const maxX = Math.max(overallDirty.x + overallDirty.width, dirty.x + dirty.width);
+ const maxY = Math.max(overallDirty.y + overallDirty.height, dirty.y + dirty.height);
+ overallDirty = { x: minX, y: minY, width: maxX - minX, height: maxY - minY };
+ }
+ }
+ }
+
+ prevLiquifyPointRef.current = pt;
+
+ if (overallDirty) {
+ if (activeLayer?.toneEnabled && sourceCanvas && displayCanvas) {
+ applyLayerEffects(
+ sourceCanvas,
+ displayCanvas,
+ activeLayer,
+ dimensions.dpi ?? 600,
+ overallDirty
+ );
+ } else if (overallDirty.width > 0 && overallDirty.height > 0) {
+ const cCtx = get2DContext(canvas);
+ if (cCtx) {
+ const subData = cCtx.getImageData(
+ overallDirty.x,
+ overallDirty.y,
+ overallDirty.width,
+ overallDirty.height
+ );
+ const isMono =
+ colorMode === 'monochrome' || activeLayer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .writeImageData(
+ targetLayerId,
+ subData,
+ overallDirty.x,
+ overallDirty.y,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ }
+ documentStore.getActiveTileGrid().notifyChange(true);
+ if (!liquifyDirtyRectRef.current) {
+ liquifyDirtyRectRef.current = overallDirty;
+ } else {
+ const cur = liquifyDirtyRectRef.current;
+ const minX = Math.min(cur.x, overallDirty.x);
+ const minY = Math.min(cur.y, overallDirty.y);
+ const maxX = Math.max(cur.x + cur.width, overallDirty.x + overallDirty.width);
+ const maxY = Math.max(cur.y + cur.height, overallDirty.y + overallDirty.height);
+ liquifyDirtyRectRef.current = {
+ x: minX,
+ y: minY,
+ width: maxX - minX,
+ height: maxY - minY,
+ };
+ }
+ }
+ return true;
+ }
+
+ if (
+ tool === 'fill' &&
+ fillSettings.method === 'lasso' &&
+ lassoFillPointsRef.current.length > 0
+ ) {
+ lassoFillPointsRef.current.push(getCanvasCoords(e));
+ return true;
+ }
+
+ return false;
+ },
+ [
+ getCanvasCoords,
+ handleSampleColor,
+ activeLayerId,
+ activeLayer,
+ layerSourceCanvasesRef,
+ layerCanvasesRef,
+ dimensions.dpi,
+ colorMode,
+ ]
+ );
+
+ const handleShapeFillPointerUp = useCallback(
+ (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
+ const { tool, primaryColor, fillSettings, frameSettings, liquifySettings } =
+ useToolStore.getState();
+
+ if (tool === 'pipette') {
+ try {
+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);
+ } catch {
+ // Ignore release errors
+ }
+ if (isPipetteSamplingRef.current) {
+ isPipetteSamplingRef.current = false;
+ handleSampleColor(pt);
+ }
+ return true;
+ }
+
+ if (tool === 'liquify') {
+ try {
+ (e.target as HTMLElement).releasePointerCapture(e.pointerId);
+ } catch {
+ // Ignore release errors
+ }
+
+ if (liquifyRafIdRef.current) {
+ cancelAnimationFrame(liquifyRafIdRef.current);
+ liquifyRafIdRef.current = null;
+ }
+
+ if (isLiquifyingRef.current) {
+ isLiquifyingRef.current = false;
+ const targetLayerId = activeLayerId;
+ const isTone = Boolean(
+ activeLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
+ const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+
+ if (canvas && liquifyBeforeImageDataRef.current) {
+ const ctx = get2DContext(canvas);
+ const afterImageData = ctx?.getImageData(0, 0, canvas.width, canvas.height);
+ if (afterImageData) {
+ const modeLabel =
+ liquifySettings.mode.charAt(0).toUpperCase() + liquifySettings.mode.slice(1);
+ pushHistoryStep(
+ 'liquify',
+ `Liquify: ${modeLabel}`,
+ liquifyBeforeImageDataRef.current,
+ afterImageData,
+ targetLayerId
+ );
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(targetLayerId, true);
+ }
+ }
+
+ liquifyBeforeImageDataRef.current = null;
+ liquifyInitialImageDataRef.current = null;
+ liquifySelectionMaskRef.current = null;
+ liquifyDirtyRectRef.current = null;
+ prevLiquifyPointRef.current = null;
+ liquifyLastPointerPosRef.current = null;
+ }
+ return true;
+ }
+
+ if (
+ tool === 'fill' &&
+ fillSettings.method === 'lasso' &&
+ lassoFillPointsRef.current.length >= 3
+ ) {
+ const pts = [...lassoFillPointsRef.current];
+ lassoFillPointsRef.current = [];
+ const canvas = getActiveCanvas();
+ if (!canvas) return true;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return true;
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+
+ executeLassoFill(canvas, pts, primaryColor, sourceCanvas);
+ if (activeLayer?.toneEnabled && sourceCanvas) {
+ applyLayerEffects(sourceCanvas, canvas, activeLayer, dimensions.dpi ?? 600);
+ }
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ updateLayerThumbnail(activeLayerId, true);
+ pushHistoryStep('fill', 'Lasso Fill', beforeImageData, afterImageData, activeLayerId);
+ documentStore.getActiveTileGrid().notifyChange(true);
+ return true;
+ }
+
+ if (tool === 'frame' && frameStartRef.current) {
+ const s = frameStartRef.current;
+ frameStartRef.current = null;
+ const minX = Math.floor(Math.min(s.x, pt.x));
+ const minY = Math.floor(Math.min(s.y, pt.y));
+ const w = Math.ceil(Math.abs(pt.x - s.x));
+ const h = Math.ceil(Math.abs(pt.y - s.y));
+
+ if (w >= 4 && h >= 4) {
+ const canvas = getActiveCanvas();
+ if (!canvas) return true;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return true;
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+
+ const drawFrameOn = (target: HTMLCanvasElement) => {
+ const c = get2DContext(target);
+ if (!c) return;
+ c.save();
+ if (frameSettings.fillBackground) {
+ c.fillStyle = frameSettings.fillColor || '#ffffff';
+ c.fillRect(minX, minY, w, h);
+ }
+ c.strokeStyle = primaryColor || '#000000';
+ c.lineWidth = frameSettings.thickness;
+ c.lineJoin = 'miter';
+ c.strokeRect(minX, minY, w, h);
+ c.restore();
+ };
+
+ drawFrameOn(canvas);
+ if (sourceCanvas) drawFrameOn(sourceCanvas);
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ updateLayerThumbnail(activeLayerId, true);
+ pushHistoryStep('frame', 'Frame Border', beforeImageData, afterImageData, activeLayerId);
+ documentStore.getActiveTileGrid().notifyChange(true);
+ }
+ return true;
+ }
+
+ return false;
+ },
+ [
+ handleSampleColor,
+ activeLayerId,
+ activeLayer,
+ layerSourceCanvasesRef,
+ layerCanvasesRef,
+ pushHistoryStep,
+ updateLayerThumbnail,
+ getActiveCanvas,
+ dimensions.dpi,
+ ]
+ );
+
+ return {
+ textSession,
+ setTextSession,
+ activeBalloon,
+ setActiveBalloon,
+ isPipetteSamplingRef,
+ handleSampleColor,
+ handleConfirmText,
+ handleCancelText,
+ handleConfirmBalloon,
+ handleDeleteBalloon,
+ handleShapeFillPointerDown,
+ handleShapeFillPointerMove,
+ handleShapeFillPointerUp,
+ };
+}
diff --git a/src/hooks/drawing/useVectorDrawing.ts b/src/hooks/drawing/useVectorDrawing.ts
new file mode 100644
index 0000000..67ef48a
--- /dev/null
+++ b/src/hooks/drawing/useVectorDrawing.ts
@@ -0,0 +1,371 @@
+import React, { useRef, useCallback } from 'react';
+import {
+ BrushSettings,
+ CanvasColorMode,
+ CanvasDimensions,
+ LayerItem,
+ Point,
+ VectorKnot,
+ VectorStroke,
+} from '../../types/editor';
+import { SparseTileGrid, releaseTemporaryCanvas } from '../../utils/tileEngine';
+import { documentStore } from '../../utils/documentStore';
+import {
+ applyVectorEraser,
+ computeStrokeBounds,
+ modifyStrokeWidth,
+ pinchVectorStroke,
+ renderVectorLayer,
+ renderVectorStroke,
+ simplifyPathPoints,
+ simplifyVectorStroke,
+} from '../../utils/vectorEngine';
+import { get2DContext } from '../../utils/canvasUtils';
+import { useToolStore } from '../../stores';
+import { PushHistoryStepFn } from './types';
+
+export interface CommitVectorStrokeArgs {
+ activeLayer: LayerItem;
+ currentLayerId: string;
+ allPoints: Point[];
+ bs: BrushSettings;
+ isEraser: boolean;
+ isPencil: boolean;
+ isMonochrome: boolean;
+ strokeColor: string;
+ dims: CanvasDimensions;
+ grid: SparseTileGrid;
+ canvas: HTMLCanvasElement | null;
+ mergedDirty: { minX: number; minY: number; maxX: number; maxY: number } | null;
+ strokeId: string | null;
+ pushHistoryStep: PushHistoryStepFn;
+}
+
+export function commitVectorStrokeOrErase({
+ activeLayer,
+ currentLayerId,
+ allPoints,
+ bs,
+ isEraser,
+ isPencil,
+ isMonochrome,
+ strokeColor,
+ dims,
+ grid,
+ canvas,
+ mergedDirty,
+ strokeId,
+ pushHistoryStep,
+}: CommitVectorStrokeArgs): VectorStroke | undefined {
+ const knots: VectorKnot[] = allPoints.map((pt, idx) => ({
+ x: pt.x,
+ y: pt.y,
+ pressure: pt.pressure,
+ width: pt.width || Math.max(0.5, (bs.size || 10) * pt.pressure),
+ timestamp: Date.now() + idx,
+ }));
+ const prevStrokes = [...(activeLayer.vectorStrokes || [])];
+
+ if (isEraser) {
+ const eraserRadius = Math.max(1, (bs.size || 10) * 0.5);
+ const eraserPath = allPoints.map((p) => ({ x: p.x, y: p.y }));
+ const eraserResult = applyVectorEraser(
+ eraserPath,
+ eraserRadius,
+ prevStrokes,
+ 'intersection'
+ );
+ const updatedStrokes = eraserResult.updatedStrokes;
+ activeLayer.vectorStrokes = updatedStrokes;
+
+ let minX = mergedDirty ? mergedDirty.minX : 0;
+ let minY = mergedDirty ? mergedDirty.minY : 0;
+ let maxX = mergedDirty ? mergedDirty.maxX : dims.width;
+ let maxY = mergedDirty ? mergedDirty.maxY : dims.height;
+ for (const st of prevStrokes) {
+ if (st.bounds) {
+ minX = Math.min(minX, st.bounds.minX);
+ minY = Math.min(minY, st.bounds.minY);
+ maxX = Math.max(maxX, st.bounds.maxX);
+ maxY = Math.max(maxY, st.bounds.maxY);
+ }
+ }
+ const vPad = Math.ceil(Math.max(16, bs.size || 10));
+ const vx = Math.max(0, Math.floor(minX - vPad));
+ const vy = Math.max(0, Math.floor(minY - vPad));
+ const vw = Math.max(0, Math.min(dims.width, Math.ceil(maxX + vPad)) - vx);
+ const vh = Math.max(0, Math.min(dims.height, Math.ceil(maxY + vPad)) - vy);
+
+ if (vw > 0 && vh > 0) {
+ const tempVec = document.createElement('canvas');
+ tempVec.width = vw;
+ tempVec.height = vh;
+ const vCtx = get2DContext(tempVec);
+ if (vCtx) {
+ vCtx.save();
+ vCtx.translate(-vx, -vy);
+ renderVectorLayer(vCtx, updatedStrokes);
+ vCtx.restore();
+ const subData = vCtx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(
+ currentLayerId,
+ subData,
+ vx,
+ vy,
+ isMonochrome ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ releaseTemporaryCanvas(tempVec);
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, {
+ x: vx,
+ y: vy,
+ width: vw,
+ height: vh,
+ });
+ }
+ }
+
+ pushHistoryStep(
+ 'eraser',
+ 'Vector Eraser',
+ null,
+ null,
+ currentLayerId,
+ vw > 0 && vh > 0
+ ? { x: vx, y: vy, width: vw, height: vh }
+ : { x: 0, y: 0, width: dims.width, height: dims.height },
+ undefined,
+ { before: prevStrokes, after: updatedStrokes },
+ undefined,
+ strokeId || undefined
+ );
+ return undefined;
+ }
+
+ const simplifiedKnots = simplifyPathPoints(knots, 0.5);
+ const strokeKnots = simplifiedKnots.length >= 2 ? simplifiedKnots : knots;
+ const bounds = computeStrokeBounds(strokeKnots);
+ const newStroke: VectorStroke = {
+ id: strokeId || `vec-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
+ layerId: currentLayerId,
+ tool: isPencil ? 'pencil' : 'brush',
+ knots: strokeKnots,
+ color: strokeColor,
+ baseWidth: bs.size || 10,
+ opacity: bs.opacity ?? 1.0,
+ bounds,
+ };
+
+ const updatedStrokes = [...prevStrokes, newStroke];
+ activeLayer.vectorStrokes = updatedStrokes;
+
+ const vPad = Math.ceil(Math.max(16, bs.size || 10));
+ const vx = Math.max(0, Math.floor(bounds.minX - vPad));
+ const vy = Math.max(0, Math.floor(bounds.minY - vPad));
+ const vw = Math.max(0, Math.min(dims.width, Math.ceil(bounds.maxX + vPad)) - vx);
+ const vh = Math.max(0, Math.min(dims.height, Math.ceil(bounds.maxY + vPad)) - vy);
+
+ if (vw > 0 && vh > 0) {
+ const tempVec = grid.createRegionCanvas(currentLayerId, {
+ x: vx,
+ y: vy,
+ width: vw,
+ height: vh,
+ });
+ const vCtx = tempVec ? get2DContext(tempVec) : null;
+ if (tempVec && vCtx) {
+ vCtx.save();
+ vCtx.translate(-vx, -vy);
+ renderVectorStroke(vCtx, newStroke);
+ vCtx.restore();
+ const subData = vCtx.getImageData(0, 0, vw, vh);
+ grid.writeImageData(
+ currentLayerId,
+ subData,
+ vx,
+ vy,
+ isMonochrome ? 'monochrome-1bit' : 'color-32bit'
+ );
+ }
+ releaseTemporaryCanvas(tempVec);
+ if (canvas) {
+ grid.renderLayerToCanvas(currentLayerId, canvas, {
+ x: vx,
+ y: vy,
+ width: vw,
+ height: vh,
+ });
+ }
+ }
+
+ pushHistoryStep(
+ isPencil ? 'pencil' : 'brush',
+ bs.brushName || (isPencil ? 'Vector Pencil' : 'Vector Pen'),
+ null,
+ null,
+ currentLayerId,
+ vw > 0 && vh > 0
+ ? { x: vx, y: vy, width: vw, height: vh }
+ : { x: 0, y: 0, width: dims.width, height: dims.height },
+ undefined,
+ { before: prevStrokes, after: updatedStrokes },
+ undefined,
+ strokeId || undefined
+ );
+
+ return newStroke;
+}
+
+export interface UseVectorDrawingParams {
+ activeLayer: LayerItem | undefined;
+ activeLayerId: string;
+ colorMode: CanvasColorMode;
+ getActiveCanvas: () => HTMLCanvasElement | null;
+ getCanvasCoords: (e: React.PointerEvent<HTMLElement> | PointerEvent) => { x: number; y: number };
+ updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
+ pushHistoryStep: PushHistoryStepFn;
+ showToast: (msg: string) => void;
+}
+
+export interface UseVectorDrawingResult {
+ commitVectorStrokeOrErase: typeof commitVectorStrokeOrErase;
+ handleVectorEditPointerDown: (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }) => boolean;
+ handleVectorEditPointerMove: (e: React.PointerEvent<HTMLElement>) => boolean;
+ handleVectorEditPointerUp: () => boolean;
+}
+
+export function useVectorDrawing({
+ activeLayer,
+ activeLayerId,
+ colorMode,
+ getActiveCanvas,
+ getCanvasCoords,
+ updateLayerThumbnail,
+ pushHistoryStep,
+ showToast,
+}: UseVectorDrawingParams): UseVectorDrawingResult {
+ const isVectorEditingRef = useRef<boolean>(false);
+ const lastVectorEditPtRef = useRef<{ x: number; y: number } | null>(null);
+ const vectorEditBeforeStrokesRef = useRef<VectorStroke[] | null>(null);
+
+ const handleVectorEditPointerDown = useCallback(
+ (e: React.PointerEvent<HTMLElement>, pt: { x: number; y: number }): boolean => {
+ e.preventDefault();
+ if (!activeLayer || activeLayer.type !== 'vector' || !activeLayer.vectorStrokes) {
+ showToast('Select a Vector Layer to use Correct Line tools');
+ return true;
+ }
+ isVectorEditingRef.current = true;
+ lastVectorEditPtRef.current = pt;
+ vectorEditBeforeStrokesRef.current = JSON.parse(
+ JSON.stringify(activeLayer.vectorStrokes)
+ ) as VectorStroke[];
+ return true;
+ },
+ [activeLayer, showToast]
+ );
+
+ const handleVectorEditPointerMove = useCallback(
+ (e: React.PointerEvent<HTMLElement>): boolean => {
+ if (!isVectorEditingRef.current || !activeLayer?.vectorStrokes) return true;
+ const pt = getCanvasCoords(e);
+ const lastPt = lastVectorEditPtRef.current || pt;
+ const delta = { x: pt.x - lastPt.x, y: pt.y - lastPt.y };
+ lastVectorEditPtRef.current = pt;
+
+ const vectorEditSettings = useToolStore.getState().vectorEditSettings;
+ const radius = vectorEditSettings.radius || 35;
+ let updated = false;
+
+ const newStrokes = activeLayer.vectorStrokes.map((stroke) => {
+ if (stroke.deleted) return stroke;
+ if (
+ pt.x < stroke.bounds.minX - radius ||
+ pt.x > stroke.bounds.maxX + radius ||
+ pt.y < stroke.bounds.minY - radius ||
+ pt.y > stroke.bounds.maxY + radius
+ ) {
+ return stroke;
+ }
+
+ if (vectorEditSettings.mode === 'pinch') {
+ if (Math.hypot(delta.x, delta.y) > 0.05) {
+ updated = true;
+ return pinchVectorStroke(stroke, pt, radius, delta);
+ }
+ } else if (vectorEditSettings.mode === 'width') {
+ updated = true;
+ return modifyStrokeWidth(stroke, pt, radius, vectorEditSettings.widthFactor);
+ } else if (vectorEditSettings.mode === 'simplify') {
+ updated = true;
+ return simplifyVectorStroke(stroke, vectorEditSettings.simplifyTolerance);
+ }
+ return stroke;
+ });
+
+ if (updated) {
+ activeLayer.vectorStrokes = newStrokes;
+ const canvas = getActiveCanvas();
+ if (canvas) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ renderVectorLayer(ctx, newStrokes);
+ const isMono =
+ colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(
+ activeLayerId,
+ canvas,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(activeLayerId, true);
+ }
+ }
+ }
+ return true;
+ },
+ [
+ activeLayer,
+ activeLayerId,
+ colorMode,
+ getActiveCanvas,
+ getCanvasCoords,
+ updateLayerThumbnail,
+ ]
+ );
+
+ const handleVectorEditPointerUp = useCallback((): boolean => {
+ if (!isVectorEditingRef.current) return false;
+ isVectorEditingRef.current = false;
+ const vectorEditSettings = useToolStore.getState().vectorEditSettings;
+ if (activeLayer?.vectorStrokes && vectorEditBeforeStrokesRef.current) {
+ pushHistoryStep(
+ 'brush',
+ `Correct Line (${vectorEditSettings.mode})`,
+ null,
+ null,
+ activeLayerId,
+ undefined,
+ undefined,
+ {
+ before: vectorEditBeforeStrokesRef.current,
+ after: [...activeLayer.vectorStrokes],
+ }
+ );
+ documentStore.getActiveTileGrid().notifyChange(true);
+ }
+ vectorEditBeforeStrokesRef.current = null;
+ return true;
+ }, [activeLayer, activeLayerId, pushHistoryStep]);
+
+ return {
+ commitVectorStrokeOrErase,
+ handleVectorEditPointerDown,
+ handleVectorEditPointerMove,
+ handleVectorEditPointerUp,
+ };
+}
diff --git a/src/hooks/useAppMenuSections.tsx b/src/hooks/useAppMenuSections.tsx
new file mode 100644
index 0000000..4f780f3
--- /dev/null
+++ b/src/hooks/useAppMenuSections.tsx
@@ -0,0 +1,1431 @@
+import { useMemo } from 'react';
+import {
+ FilePlus,
+ FolderOpen,
+ Save,
+ Download,
+ Trash2,
+ Film,
+ Layers,
+ Undo2,
+ Redo2,
+ ZoomIn,
+ ZoomOut,
+ RotateCcw,
+ FlipHorizontal,
+ FlipVertical,
+ Plus,
+ Info as InfoIcon,
+ Copy,
+ ClipboardPaste,
+ ImagePlus,
+ Scaling,
+ Settings,
+ FolderDown,
+ PaintBucket,
+ SlidersHorizontal,
+ Compass,
+ Eye,
+ EyeOff,
+ Magnet,
+ Lock,
+ Unlock,
+ Box,
+ Maximize2,
+ Minimize2,
+ Feather,
+ BoxSelect,
+ X,
+ Smartphone,
+ Archive,
+ Sparkles,
+ MessageSquare,
+ Spline,
+} from 'lucide-react';
+import {
+ AnimationTimeline,
+ CanvasDimensions,
+ CanvasSelection,
+ CmykStandard,
+ ExpressionColor,
+ FilterType,
+ LayerItem,
+ MenuSection,
+ SoftProofSettings,
+} from '../types/editor';
+import { PerspectiveRuler } from '../types/perspective';
+import { createDefaultAnimationTimeline } from '../utils/animationEngine';
+import { createDefaultPerspectiveRuler, applyWormsEyePreset } from '../utils/perspectiveMath';
+import { parseSutFile } from '../utils/sutParser';
+import {
+ deleteCustomBrush,
+ loadCustomBrushes,
+ prepareBrushSettingsForCsp,
+ saveCustomBrush,
+} from '../utils/brushStorage';
+import { TonalCorrectionType } from '../utils/tonalEngine';
+import { AnyFilterParams } from './useTonalAndFilterActions';
+import {
+ documentStoreActions,
+ toolStoreActions,
+ uiStoreActions,
+ useWorkspaceStore,
+ workspaceStoreActions,
+} from '../stores';
+import {
+ ALL_DOCK_PANEL_IDS,
+ DOCK_PANEL_META,
+ WORKSPACE_PRESET_LABELS,
+ WorkspacePresetId,
+} from '../types/workspace';
+import { listVisiblePanelIds } from '../utils/workspacePresets';
+
+export interface UseAppMenuSectionsParams {
+ hasOpenDocument: boolean;
+ dimensions: CanvasDimensions;
+ layers: LayerItem[];
+ activeLayer: LayerItem | undefined;
+ activeLayerId: string;
+ selection: CanvasSelection | null;
+ canUndo: boolean;
+ canRedo: boolean;
+ flipX: boolean;
+ flipY: boolean;
+ isWebtoonMode: boolean;
+ perspectiveRuler: PerspectiveRuler | null;
+ softProofSettings: SoftProofSettings;
+ activeAnimationTimeline: AnimationTimeline | null;
+ clearCanvas: () => void;
+ handleUndo: () => void;
+ redo: () => void;
+ handleTriggerOpenFile: () => void;
+ handleTriggerImport3DFile: () => void;
+ handleSave: () => void;
+ handleSaveAs: () => void;
+ handleExportImage: () => void;
+ handleCopySelectedLayer: () => void;
+ handlePasteSelectedLayer: () => void;
+ handleTriggerPasteFromFile: () => void;
+ handleDeleteSelectedLayer: () => void;
+ handleClearActiveLayer: () => void;
+ handleStartTransform: () => void;
+ handleDeselect: () => void;
+ handleFillSelectionColor: () => void;
+ handleOpenTonalModal: (type: TonalCorrectionType) => void;
+ handleApplyReverseGradient: () => void;
+ handleSelectAll: () => void;
+ handleInvertSelection: () => void;
+ handleExpandSelection: (pixels?: number) => void;
+ handleContractSelection: (pixels?: number) => void;
+ handleFeatherSelection: (radius?: number) => void;
+ handleAddLayer: (type?: 'raster' | 'folder') => void;
+ handleOpenAdjustmentModal: (
+ layerId?: string,
+ initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance'
+ ) => void;
+ addLayerMask: (layerId: string) => void;
+ removeLayerMask: (layerId: string) => void;
+ toggleLayerMask: (layerId: string) => void;
+ toggleMaskLinked: (layerId: string) => void;
+ duplicateLayer: (layerId: string) => void;
+ handleMergeDown: () => void;
+ handleOpenLayerStylesModal: (layerId?: string) => void;
+ toggleLayerColor: (layerId: string) => void;
+ handleConvertLayer: (layerId: string, mode: ExpressionColor) => void;
+ deleteLayer: (layerId: string) => void;
+ handleApplyFilter: (type: FilterType, params?: AnyFilterParams) => void;
+ zoomIn: () => void;
+ zoomOut: () => void;
+ resetZoomAndCenter: () => void;
+ resetRotation: () => void;
+ toggleFlipHorizontal: () => void;
+ toggleFlipVertical: () => void;
+ resetViewFlip: () => void;
+ handleUpdateAnimationTimeline: (timeline: AnimationTimeline | null) => void;
+ handleAddAnimationCel: (frameIndex: number) => void;
+ showToast: (msg: string) => void;
+}
+
+export function useAppMenuSections(params: UseAppMenuSectionsParams): MenuSection[] {
+ const {
+ hasOpenDocument,
+ dimensions,
+ layers,
+ activeLayer,
+ activeLayerId,
+ selection,
+ canUndo,
+ canRedo,
+ flipX,
+ flipY,
+ isWebtoonMode,
+ perspectiveRuler,
+ softProofSettings,
+ activeAnimationTimeline,
+ clearCanvas,
+ handleUndo,
+ redo,
+ handleTriggerOpenFile,
+ handleTriggerImport3DFile,
+ handleSave,
+ handleSaveAs,
+ handleExportImage,
+ handleCopySelectedLayer,
+ handlePasteSelectedLayer,
+ handleTriggerPasteFromFile,
+ handleDeleteSelectedLayer,
+ handleClearActiveLayer,
+ handleStartTransform,
+ handleDeselect,
+ handleFillSelectionColor,
+ handleOpenTonalModal,
+ handleApplyReverseGradient,
+ handleSelectAll,
+ handleInvertSelection,
+ handleExpandSelection,
+ handleContractSelection,
+ handleFeatherSelection,
+ handleAddLayer,
+ handleOpenAdjustmentModal,
+ addLayerMask,
+ removeLayerMask,
+ toggleLayerMask,
+ toggleMaskLinked,
+ duplicateLayer,
+ handleMergeDown,
+ handleOpenLayerStylesModal,
+ toggleLayerColor,
+ handleConvertLayer,
+ deleteLayer,
+ handleApplyFilter,
+ zoomIn,
+ zoomOut,
+ resetZoomAndCenter,
+ resetRotation,
+ toggleFlipHorizontal,
+ toggleFlipVertical,
+ resetViewFlip,
+ handleUpdateAnimationTimeline,
+ handleAddAnimationCel,
+ showToast,
+ } = params;
+
+ const activePreset = useWorkspaceStore((s) => s.activePreset);
+ const workspaceLayout = useWorkspaceStore((s) => s.layout);
+ const palettesHidden = useWorkspaceStore((s) => s.palettesHidden);
+ const showStatusBar = useWorkspaceStore((s) => s.showStatusBar);
+ const showDocumentTabs = useWorkspaceStore((s) => s.showDocumentTabs);
+ const showCommandBar = useWorkspaceStore((s) => s.showCommandBar);
+ const visiblePanels = useMemo(() => listVisiblePanelIds(workspaceLayout), [workspaceLayout]);
+
+ return useMemo(
+ () => [
+ {
+ id: 'file',
+ label: 'File',
+ items: [
+ {
+ id: 'file-new',
+ label: 'New...',
+ shortcut: 'Ctrl+N',
+ icon: <FilePlus className="w-3.5 h-3.5 text-sky-400" />,
+ onClick: () => uiStoreActions.setNewCanvasModalOpen(true),
+ },
+ {
+ id: 'file-open',
+ label: 'Open...',
+ shortcut: 'Ctrl+O',
+ icon: <FolderOpen className="w-3.5 h-3.5 text-amber-400" />,
+ onClick: handleTriggerOpenFile,
+ },
+ {
+ id: 'file-import-sut',
+ label: 'Import CSP Brush (.sut)...',
+ icon: <FolderDown className="w-3.5 h-3.5 text-cyan-400" />,
+ onClick: () => {
+ const input = document.createElement('input');
+ input.type = 'file';
+ input.accept = '.sut';
+ input.onchange = async () => {
+ const file = input.files?.[0];
+ if (file) {
+ try {
+ uiStoreActions.setLoading(true, `Importing CSP Brush: ${file.name}...`);
+ const buffer = await file.arrayBuffer();
+ const parsedBrush = await parseSutFile(buffer, file.name);
+ const existing = (await loadCustomBrushes()).filter(
+ (b) =>
+ b.name.toLowerCase() === parsedBrush.name.toLowerCase() ||
+ b.id === parsedBrush.id
+ );
+ for (const old of existing) {
+ await deleteCustomBrush(old.id).catch(() => {});
+ }
+ await saveCustomBrush(parsedBrush);
+ toolStoreActions.setToolRaw('brush');
+ const fullSettings = await prepareBrushSettingsForCsp(parsedBrush);
+ toolStoreActions.updateBrushSettings(fullSettings);
+ showToast(`Imported CSP brush "${parsedBrush.name}" successfully!`);
+ } catch (err: unknown) {
+ const msg =
+ err instanceof Error ? err.message : 'Failed to import .sut brush.';
+ showToast(msg);
+ } finally {
+ uiStoreActions.setLoading(false, '');
+ }
+ }
+ };
+ input.click();
+ },
+ },
+ {
+ id: 'file-import-3d',
+ label: 'Import 3D Model (.glb, .obj)...',
+ icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleTriggerImport3DFile,
+ },
+ { id: 'file-div-1', label: '', divider: true },
+ {
+ id: 'file-save',
+ label: 'Save',
+ shortcut: 'Ctrl+S',
+ icon: <Save className="w-3.5 h-3.5 text-blue-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleSave,
+ },
+ {
+ id: 'file-save-as',
+ label: 'Save As...',
+ shortcut: 'Ctrl+Shift+S',
+ icon: <Save className="w-3.5 h-3.5 text-indigo-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleSaveAs,
+ },
+ {
+ id: 'file-export-image',
+ label: 'Export Image...',
+ icon: <Download className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleExportImage,
+ },
+ {
+ id: 'file-export-webtoon',
+ label: 'Export Webtoon Chapter Slices (.zip)...',
+ icon: <Archive className="w-3.5 h-3.5 text-cyan-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => uiStoreActions.setWebtoonExportModalOpen(true),
+ },
+ { id: 'file-div-2', label: '', divider: true },
+ {
+ id: 'file-clear',
+ label: 'Clear Canvas',
+ icon: <Trash2 className="w-3.5 h-3.5 text-rose-400" />,
+ danger: true,
+ disabled: !hasOpenDocument,
+ onClick: clearCanvas,
+ },
+ ],
+ },
+ {
+ id: 'edit',
+ label: 'Edit',
+ items: [
+ {
+ id: 'edit-undo',
+ label: 'Undo',
+ shortcut: 'Ctrl+Z',
+ icon: <Undo2 className="w-3.5 h-3.5" />,
+ disabled: !hasOpenDocument || !canUndo,
+ onClick: handleUndo,
+ },
+ {
+ id: 'edit-redo',
+ label: 'Redo',
+ shortcut: 'Ctrl+Y',
+ icon: <Redo2 className="w-3.5 h-3.5" />,
+ disabled: !hasOpenDocument || !canRedo,
+ onClick: redo,
+ },
+ { id: 'edit-div-1', label: '', divider: true },
+ {
+ id: 'edit-copy',
+ label: 'Copy',
+ shortcut: 'Ctrl+C',
+ icon: <Copy className="w-3.5 h-3.5 text-sky-400" />,
+ disabled: !hasOpenDocument || !activeLayer,
+ onClick: handleCopySelectedLayer,
+ },
+ {
+ id: 'edit-paste',
+ label: 'Paste',
+ shortcut: 'Ctrl+V',
+ icon: <ClipboardPaste className="w-3.5 h-3.5 text-amber-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handlePasteSelectedLayer,
+ },
+ {
+ id: 'edit-paste-file',
+ label: 'Paste from file...',
+ icon: <ImagePlus className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleTriggerPasteFromFile,
+ },
+ {
+ id: 'edit-import-3d',
+ label: 'Import 3D File (.glb, .obj)...',
+ icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleTriggerImport3DFile,
+ },
+ {
+ id: 'edit-delete',
+ label: 'Delete',
+ shortcut: 'Del',
+ icon: <Trash2 className="w-3.5 h-3.5 text-rose-400" />,
+ danger: true,
+ disabled: !hasOpenDocument || layers.filter((l) => l.type === 'raster').length <= 1,
+ onClick: handleDeleteSelectedLayer,
+ },
+ {
+ id: 'edit-clear-layer',
+ label: 'Clear Active Layer',
+ disabled: !hasOpenDocument || !activeLayer,
+ onClick: handleClearActiveLayer,
+ },
+ {
+ id: 'edit-transform',
+ label: 'Free Transform',
+ shortcut: 'Ctrl+T',
+ icon: <Scaling className="w-3.5 h-3.5 text-cyan-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleStartTransform,
+ },
+ {
+ id: 'edit-deselect',
+ label: 'Deselect',
+ shortcut: 'Ctrl+D',
+ disabled: !hasOpenDocument || !selection,
+ onClick: handleDeselect,
+ },
+ {
+ id: 'edit-fill-sel',
+ label: 'Fill Selection',
+ icon: <PaintBucket className="w-3.5 h-3.5 text-amber-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: handleFillSelectionColor,
+ },
+ {
+ id: 'edit-tonal-correction',
+ label: 'Tonal Correction',
+ icon: <SlidersHorizontal className="w-3.5 h-3.5 text-violet-400" />,
+ disabled:
+ !hasOpenDocument || !activeLayer || activeLayer.locked || activeLayer.type !== 'raster',
+ submenu: [
+ {
+ id: 'edit-tonal-brightness-contrast',
+ label: 'Brightness/Contrast...',
+ disabled:
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.locked ||
+ activeLayer.type !== 'raster',
+ onClick: () => handleOpenTonalModal('brightness-contrast'),
+ },
+ {
+ id: 'edit-tonal-hue-saturation',
+ label: 'Hue/Saturation/Luminosity...',
+ shortcut: 'Ctrl+U',
+ disabled:
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.locked ||
+ activeLayer.type !== 'raster',
+ onClick: () => handleOpenTonalModal('hue-saturation'),
+ },
+ {
+ id: 'edit-tonal-posterization',
+ label: 'Posterization...',
+ disabled:
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.locked ||
+ activeLayer.type !== 'raster',
+ onClick: () => handleOpenTonalModal('posterization'),
+ },
+ {
+ id: 'edit-tonal-reverse-gradient',
+ label: 'Reverse Gradient',
+ shortcut: 'Ctrl+I',
+ disabled:
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.locked ||
+ activeLayer.type !== 'raster',
+ onClick: handleApplyReverseGradient,
+ },
+ {
+ id: 'edit-tonal-level-correction',
+ label: 'Level Correction...',
+ disabled:
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.locked ||
+ activeLayer.type !== 'raster',
+ onClick: () => handleOpenTonalModal('level-correction'),
+ },
+ {
+ id: 'edit-tonal-binarization',
+ label: 'Binarization...',
+ disabled:
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.locked ||
+ activeLayer.type !== 'raster',
+ onClick: () => handleOpenTonalModal('binarization'),
+ },
+ ],
+ },
+ { id: 'edit-div-2', label: '', divider: true },
+ {
+ id: 'edit-resize-canvas',
+ label: 'Resize Canvas...',
+ icon: <Scaling className="w-3.5 h-3.5 text-indigo-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => uiStoreActions.setResizeCanvasModalOpen(true),
+ },
+ { id: 'edit-div-3', label: '', divider: true },
+ {
+ id: 'edit-settings',
+ label: 'Settings...',
+ shortcut: 'Ctrl+,',
+ icon: <Settings className="w-3.5 h-3.5 text-slate-300" />,
+ onClick: () => uiStoreActions.setSettingsModalOpen(true),
+ },
+ ],
+ },
+ {
+ id: 'select',
+ label: 'Select',
+ items: [
+ {
+ id: 'select-all',
+ label: 'Select All',
+ shortcut: 'Ctrl+A',
+ icon: <BoxSelect className="w-3.5 h-3.5 text-sky-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleSelectAll,
+ },
+ {
+ id: 'select-deselect',
+ label: 'Deselect',
+ shortcut: 'Ctrl+D',
+ icon: <X className="w-3.5 h-3.5 text-rose-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: handleDeselect,
+ },
+ {
+ id: 'select-invert',
+ label: 'Invert Selection',
+ shortcut: 'Ctrl+Shift+I',
+ icon: <RotateCcw className="w-3.5 h-3.5 text-amber-400" />,
+ disabled: !hasOpenDocument,
+ onClick: handleInvertSelection,
+ },
+ { id: 'select-div-1', label: '', divider: true },
+ {
+ id: 'select-expand',
+ label: 'Expand (+5px)...',
+ icon: <Maximize2 className="w-3.5 h-3.5 text-indigo-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: () => handleExpandSelection(5),
+ },
+ {
+ id: 'select-contract',
+ label: 'Contract (-5px)...',
+ icon: <Minimize2 className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: () => handleContractSelection(5),
+ },
+ {
+ id: 'select-feather',
+ label: 'Feather (5px)...',
+ icon: <Feather className="w-3.5 h-3.5 text-purple-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: () => handleFeatherSelection(5),
+ },
+ { id: 'select-div-2', label: '', divider: true },
+ {
+ id: 'select-transform',
+ label: 'Transform Selection',
+ shortcut: 'Ctrl+T',
+ icon: <Scaling className="w-3.5 h-3.5 text-cyan-400" />,
+ disabled: !hasOpenDocument || !selection,
+ onClick: handleStartTransform,
+ },
+ ],
+ },
+ {
+ id: 'layer',
+ label: 'Layer',
+ items: [
+ {
+ id: 'layer-new-raster',
+ label: 'New Raster Layer',
+ shortcut: 'Ctrl+Shift+N',
+ icon: <Plus className="w-3.5 h-3.5" />,
+ disabled: !hasOpenDocument,
+ onClick: () => handleAddLayer('raster'),
+ },
+ {
+ id: 'layer-new-folder',
+ label: 'New Folder',
+ disabled: !hasOpenDocument,
+ onClick: () => handleAddLayer('folder'),
+ },
+ {
+ id: 'layer-new-3d',
+ label: 'New 3D Reference Layer...',
+ icon: <Box className="w-3.5 h-3.5 text-purple-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => uiStoreActions.set3DLayerOpen(true),
+ },
+ {
+ id: 'layer-new-adjustment',
+ label: 'New Adjustment Layer',
+ disabled: !hasOpenDocument,
+ submenu: [
+ {
+ id: 'layer-adj-curves',
+ label: 'Tone Curves...',
+ onClick: () => handleOpenAdjustmentModal(undefined, 'curves'),
+ },
+ {
+ id: 'layer-adj-gradient-map',
+ label: 'Gradient Map...',
+ onClick: () => handleOpenAdjustmentModal(undefined, 'gradient-map'),
+ },
+ {
+ id: 'layer-adj-levels',
+ label: 'Levels...',
+ onClick: () => handleOpenAdjustmentModal(undefined, 'levels'),
+ },
+ {
+ id: 'layer-adj-color-balance',
+ label: 'Color Balance...',
+ onClick: () => handleOpenAdjustmentModal(undefined, 'color-balance'),
+ },
+ ],
+ },
+ {
+ id: 'layer-mask-submenu',
+ label: 'Layer Mask',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type === 'folder',
+ submenu: [
+ {
+ id: 'layer-mask-add',
+ label: activeLayer?.maskCanvas
+ ? 'Mask Already Present'
+ : 'Add Layer Mask (Reveal All)',
+ disabled: Boolean(activeLayer?.maskCanvas),
+ onClick: () => addLayerMask(activeLayerId),
+ },
+ {
+ id: 'layer-mask-delete',
+ label: 'Delete Layer Mask',
+ danger: true,
+ disabled: !activeLayer?.maskCanvas,
+ onClick: () => removeLayerMask(activeLayerId),
+ },
+ {
+ id: 'layer-mask-toggle',
+ label:
+ activeLayer?.maskEnabled === false ? 'Enable Layer Mask' : 'Disable Layer Mask',
+ disabled: !activeLayer?.maskCanvas,
+ onClick: () => toggleLayerMask(activeLayerId),
+ },
+ {
+ id: 'layer-mask-link',
+ label:
+ activeLayer?.maskLinked === false
+ ? 'Link Mask to Layer'
+ : 'Unlink Mask from Layer',
+ disabled: !activeLayer?.maskCanvas,
+ onClick: () => toggleMaskLinked(activeLayerId),
+ },
+ ],
+ },
+ {
+ id: 'layer-duplicate',
+ label: 'Duplicate Layer',
+ shortcut: 'Ctrl+J',
+ disabled: !hasOpenDocument || !activeLayer,
+ onClick: () => duplicateLayer(activeLayerId),
+ },
+ {
+ id: 'layer-merge-down',
+ label: 'Merge with Layer Below',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || layers.length <= 1,
+ onClick: handleMergeDown,
+ },
+ { id: 'layer-div-effects', label: '', divider: true },
+ {
+ id: 'layer-styles',
+ label: 'Layer Style (Stroke, Shadow, Glow)...',
+ disabled:
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.type === 'folder' ||
+ activeLayer.type === 'adjustment',
+ onClick: () => handleOpenLayerStylesModal(activeLayerId),
+ },
+ {
+ id: 'layer-toggle-tint',
+ label: activeLayer?.layerColorEnabled
+ ? 'Disable Layer Color (Tint)'
+ : 'Enable Layer Color (Tint)',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type === 'folder',
+ onClick: () => toggleLayerColor(activeLayerId),
+ },
+ {
+ id: 'layer-convert-submenu',
+ label: 'Convert Expression Color',
+ disabled: !hasOpenDocument || !activeLayer || activeLayer.type === 'folder',
+ submenu: [
+ {
+ id: 'layer-convert-color',
+ label: 'Color (RGB)',
+ onClick: () => handleConvertLayer(activeLayerId, 'color'),
+ },
+ {
+ id: 'layer-convert-gray',
+ label: 'Gray (Grayscale)',
+ onClick: () => handleConvertLayer(activeLayerId, 'gray'),
+ },
+ {
+ id: 'layer-convert-monochrome',
+ label: 'Monochrome (1-bit B&W)',
+ onClick: () => handleConvertLayer(activeLayerId, 'monochrome'),
+ },
+ ],
+ },
+ { id: 'layer-div-ruler', label: '', divider: true },
+ {
+ id: 'layer-perspective-ruler',
+ label: 'Perspective Ruler',
+ disabled: !hasOpenDocument,
+ submenu: !perspectiveRuler
+ ? [
+ {
+ id: 'layer-add-ruler-1p',
+ label: 'Add 1-Point Perspective Ruler',
+ onClick: () => {
+ documentStoreActions.setPerspectiveRuler(
+ createDefaultPerspectiveRuler('1-point', dimensions)
+ );
+ showToast('1-Point Perspective Ruler added to canvas');
+ },
+ },
+ {
+ id: 'layer-add-ruler-2p',
+ label: 'Add 2-Point Perspective Ruler',
+ onClick: () => {
+ documentStoreActions.setPerspectiveRuler(
+ createDefaultPerspectiveRuler('2-point', dimensions)
+ );
+ showToast('2-Point Perspective Ruler added to canvas');
+ },
+ },
+ {
+ id: 'layer-add-ruler-3p-birds',
+ label: "Add 3-Point Perspective Ruler (Bird's-Eye)",
+ onClick: () => {
+ documentStoreActions.setPerspectiveRuler(
+ createDefaultPerspectiveRuler('3-point', dimensions)
+ );
+ showToast("3-Point Perspective Ruler (Bird's-Eye) added to canvas");
+ },
+ },
+ {
+ id: 'layer-add-ruler-3p-worms',
+ label: "Add 3-Point Perspective Ruler (Worm's-Eye)",
+ onClick: () => {
+ const base = createDefaultPerspectiveRuler('3-point', dimensions);
+ documentStoreActions.setPerspectiveRuler(
+ applyWormsEyePreset(base, dimensions)
+ );
+ showToast("3-Point Perspective Ruler (Worm's-Eye) added to canvas");
+ },
+ },
+ ]
+ : [
+ {
+ id: 'layer-remove-ruler',
+ label: 'Remove Perspective Ruler from Canvas',
+ danger: true,
+ onClick: () => {
+ documentStoreActions.setPerspectiveRuler(null);
+ showToast('Removed perspective ruler from canvas');
+ },
+ },
+ ],
+ },
+ { id: 'layer-div-delete', label: '', divider: true },
+ {
+ id: 'layer-delete',
+ label: 'Delete Layer',
+ danger: true,
+ disabled: !hasOpenDocument || layers.length <= 1,
+ onClick: () => deleteLayer(activeLayerId),
+ },
+ ],
+ },
+ {
+ id: 'filter',
+ label: 'Filter',
+ items: [
+ {
+ id: 'filter-gaussian-blur',
+ label: 'Gaussian Blur...',
+ disabled:
+ !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
+ onClick: () => {
+ const r = window.prompt('Gaussian Blur Radius (px, 1-100):', '5');
+ if (r !== null) {
+ const radius = Math.max(1, Math.min(100, parseFloat(r) || 5));
+ handleApplyFilter('gaussian-blur', { radius });
+ }
+ },
+ },
+ {
+ id: 'filter-motion-blur',
+ label: 'Motion Blur...',
+ disabled:
+ !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
+ onClick: () => {
+ const d = window.prompt('Motion Blur Distance (px, 1-100):', '15');
+ const a =
+ d !== null ? window.prompt('Motion Blur Angle (degrees, 0-360):', '0') : null;
+ if (d !== null && a !== null) {
+ const distance = Math.max(1, Math.min(100, parseFloat(d) || 15));
+ const angle = Math.max(0, Math.min(360, parseFloat(a) || 0));
+ handleApplyFilter('motion-blur', { distance, angle });
+ }
+ },
+ },
+ {
+ id: 'filter-unsharp-mask',
+ label: 'Unsharp Mask...',
+ disabled:
+ !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
+ onClick: () => {
+ const r = window.prompt('Unsharp Mask Radius (px, 0.5-20):', '2');
+ const a = r !== null ? window.prompt('Amount factor (0.1-5.0):', '1.5') : null;
+ if (r !== null && a !== null) {
+ const radius = Math.max(0.5, Math.min(20, parseFloat(r) || 2));
+ const amount = Math.max(0.1, Math.min(5, parseFloat(a) || 1.5));
+ handleApplyFilter('unsharp-mask', { radius, amount, threshold: 0 });
+ }
+ },
+ },
+ {
+ id: 'filter-film-grain',
+ label: 'Film Grain...',
+ disabled:
+ !hasOpenDocument || !activeLayer || activeLayer.type !== 'raster' || activeLayer.locked,
+ onClick: () => {
+ const i = window.prompt('Film Grain Intensity (% 1-100):', '25');
+ if (i !== null) {
+ const intensity = Math.max(1, Math.min(100, parseFloat(i) || 25));
+ handleApplyFilter('film-grain', { intensity, size: 1, monochromatic: true });
+ }
+ },
+ },
+ ],
+ },
+ {
+ id: 'ruler',
+ label: 'Ruler',
+ items: !perspectiveRuler
+ ? [
+ {
+ id: 'ruler-add-1p',
+ label: 'Add 1-Point Perspective Ruler',
+ icon: <Compass className="w-3.5 h-3.5 text-cyan-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => {
+ documentStoreActions.setPerspectiveRuler(
+ createDefaultPerspectiveRuler('1-point', dimensions)
+ );
+ showToast('1-Point Perspective Ruler added to canvas');
+ },
+ },
+ {
+ id: 'ruler-add-2p',
+ label: 'Add 2-Point Perspective Ruler',
+ icon: <Compass className="w-3.5 h-3.5 text-purple-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => {
+ documentStoreActions.setPerspectiveRuler(
+ createDefaultPerspectiveRuler('2-point', dimensions)
+ );
+ showToast('2-Point Perspective Ruler added to canvas');
+ },
+ },
+ {
+ id: 'ruler-add-3p-birds',
+ label: "Add 3-Point Perspective Ruler (Bird's-Eye)",
+ icon: <Compass className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => {
+ documentStoreActions.setPerspectiveRuler(
+ createDefaultPerspectiveRuler('3-point', dimensions)
+ );
+ showToast("3-Point Perspective Ruler (Bird's-Eye) added to canvas");
+ },
+ },
+ {
+ id: 'ruler-add-3p-worms',
+ label: "Add 3-Point Perspective Ruler (Worm's-Eye)",
+ icon: <Compass className="w-3.5 h-3.5 text-amber-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => {
+ const base = createDefaultPerspectiveRuler('3-point', dimensions);
+ documentStoreActions.setPerspectiveRuler(
+ applyWormsEyePreset(base, dimensions)
+ );
+ showToast("3-Point Perspective Ruler (Worm's-Eye) added to canvas");
+ },
+ },
+ ]
+ : [
+ {
+ id: 'ruler-toggle-visibility',
+ label: perspectiveRuler.enabled
+ ? 'Hide Perspective Ruler'
+ : 'Show Perspective Ruler',
+ shortcut: 'Ctrl+Shift+R',
+ icon: perspectiveRuler.enabled ? (
+ <EyeOff className="w-3.5 h-3.5 text-sky-400" />
+ ) : (
+ <Eye className="w-3.5 h-3.5 text-sky-400" />
+ ),
+ disabled: !hasOpenDocument,
+ onClick: () =>
+ documentStoreActions.setPerspectiveRuler((prev) =>
+ prev ? { ...prev, enabled: !prev.enabled } : null
+ ),
+ },
+ {
+ id: 'ruler-toggle-snap',
+ label: perspectiveRuler.snapEnabled ? 'Disable Snapping' : 'Enable Snapping',
+ shortcut: 'Ctrl+Shift+P',
+ icon: <Magnet className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () =>
+ documentStoreActions.setPerspectiveRuler((prev) =>
+ prev ? { ...prev, snapEnabled: !prev.snapEnabled } : null
+ ),
+ },
+ {
+ id: 'ruler-toggle-lock',
+ label: perspectiveRuler.locked
+ ? 'Unlock Handles (Edit Mode)'
+ : 'Lock Handles (Freeze for Inking)',
+ icon: perspectiveRuler.locked ? (
+ <Unlock className="w-3.5 h-3.5 text-amber-400" />
+ ) : (
+ <Lock className="w-3.5 h-3.5 text-amber-400" />
+ ),
+ disabled: !hasOpenDocument,
+ onClick: () =>
+ documentStoreActions.setPerspectiveRuler((prev) =>
+ prev ? { ...prev, locked: !prev.locked } : null
+ ),
+ },
+ {
+ id: 'ruler-line-count',
+ label: `Guide Rays (${perspectiveRuler.guideRayCount || 6} lines)`,
+ disabled: !hasOpenDocument,
+ submenu: [2, 4, 6, 8, 12, 16].map((count) => ({
+ id: `ruler-rays-${count}`,
+ label: `${count} Rays per VP`,
+ checked: (perspectiveRuler.guideRayCount || 6) === count,
+ onClick: () =>
+ documentStoreActions.setPerspectiveRuler((prev) =>
+ prev ? { ...prev, guideRayCount: count } : null
+ ),
+ })),
+ },
+ {
+ id: 'ruler-presets',
+ label: 'Change Perspective Preset',
+ disabled: !hasOpenDocument,
+ submenu: [
+ {
+ id: 'ruler-preset-1p',
+ label: '1-Point Perspective (Center)',
+ onClick: () => {
+ const next = createDefaultPerspectiveRuler('1-point', dimensions);
+ next.snapEnabled = perspectiveRuler.snapEnabled;
+ next.locked = perspectiveRuler.locked;
+ next.guideRayCount = perspectiveRuler.guideRayCount;
+ documentStoreActions.setPerspectiveRuler(next);
+ },
+ },
+ {
+ id: 'ruler-preset-2p',
+ label: '2-Point Perspective (Wide Street)',
+ onClick: () => {
+ const next = createDefaultPerspectiveRuler('2-point', dimensions);
+ next.snapEnabled = perspectiveRuler.snapEnabled;
+ next.locked = perspectiveRuler.locked;
+ next.guideRayCount = perspectiveRuler.guideRayCount;
+ documentStoreActions.setPerspectiveRuler(next);
+ },
+ },
+ {
+ id: 'ruler-preset-3p-birds',
+ label: "3-Point Perspective (Bird's-Eye)",
+ onClick: () => {
+ const next = createDefaultPerspectiveRuler('3-point', dimensions);
+ next.snapEnabled = perspectiveRuler.snapEnabled;
+ next.locked = perspectiveRuler.locked;
+ next.guideRayCount = perspectiveRuler.guideRayCount;
+ documentStoreActions.setPerspectiveRuler(next);
+ },
+ },
+ {
+ id: 'ruler-preset-3p-worms',
+ label: "3-Point Perspective (Worm's-Eye)",
+ onClick: () => {
+ const base = createDefaultPerspectiveRuler('3-point', dimensions);
+ base.guideRayCount = perspectiveRuler.guideRayCount;
+ documentStoreActions.setPerspectiveRuler(
+ applyWormsEyePreset(base, dimensions)
+ );
+ },
+ },
+ ],
+ },
+ { id: 'ruler-div-remove', label: '', divider: true },
+ {
+ id: 'ruler-remove',
+ label: 'Remove Perspective Ruler from Canvas',
+ danger: true,
+ icon: <Trash2 className="w-3.5 h-3.5 text-red-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => {
+ documentStoreActions.setPerspectiveRuler(null);
+ showToast('Removed perspective ruler from canvas');
+ },
+ },
+ ],
+ },
+ {
+ id: 'view',
+ label: 'View',
+ items: [
+ {
+ id: 'view-zoom-in',
+ label: 'Zoom In',
+ shortcut: 'Ctrl++',
+ icon: <ZoomIn className="w-3.5 h-3.5" />,
+ disabled: !hasOpenDocument,
+ onClick: zoomIn,
+ },
+ {
+ id: 'view-zoom-out',
+ label: 'Zoom Out',
+ shortcut: 'Ctrl+-',
+ icon: <ZoomOut className="w-3.5 h-3.5" />,
+ disabled: !hasOpenDocument,
+ onClick: zoomOut,
+ },
+ {
+ id: 'view-reset-zoom',
+ label: 'Reset Zoom & Center',
+ shortcut: 'Ctrl+0',
+ disabled: !hasOpenDocument,
+ onClick: resetZoomAndCenter,
+ },
+ {
+ id: 'view-reset-rotation',
+ label: 'Reset Rotation',
+ shortcut: 'Ctrl+Alt+0',
+ icon: <RotateCcw className="w-3.5 h-3.5" />,
+ disabled: !hasOpenDocument,
+ onClick: resetRotation,
+ },
+ { id: 'view-div-flip', label: '', divider: true },
+ {
+ id: 'view-flip-horizontal',
+ label: 'Flip View Horizontal',
+ shortcut: 'Shift+H',
+ icon: <FlipHorizontal className="w-3.5 h-3.5" />,
+ checked: flipX,
+ disabled: !hasOpenDocument,
+ onClick: toggleFlipHorizontal,
+ },
+ {
+ id: 'view-flip-vertical',
+ label: 'Flip View Vertical',
+ shortcut: 'Shift+V',
+ icon: <FlipVertical className="w-3.5 h-3.5" />,
+ checked: flipY,
+ disabled: !hasOpenDocument,
+ onClick: toggleFlipVertical,
+ },
+ {
+ id: 'view-reset-flip',
+ label: 'Reset View Flip',
+ disabled: !hasOpenDocument || (!flipX && !flipY),
+ onClick: resetViewFlip,
+ },
+ { id: 'view-div-ruler', label: '', divider: true },
+ {
+ id: 'view-toggle-ruler',
+ label: perspectiveRuler?.enabled
+ ? 'Hide Perspective Ruler'
+ : 'Show Perspective Ruler',
+ shortcut: 'Ctrl+Shift+R',
+ disabled: !hasOpenDocument || !perspectiveRuler,
+ onClick: () =>
+ documentStoreActions.setPerspectiveRuler((prev) =>
+ prev ? { ...prev, enabled: !prev.enabled } : null
+ ),
+ },
+ {
+ id: 'view-toggle-snap',
+ label: perspectiveRuler?.snapEnabled
+ ? 'Disable Perspective Snapping'
+ : 'Enable Perspective Snapping',
+ shortcut: 'Ctrl+Shift+P',
+ disabled: !hasOpenDocument || !perspectiveRuler,
+ onClick: () =>
+ documentStoreActions.setPerspectiveRuler((prev) =>
+ prev ? { ...prev, snapEnabled: !prev.snapEnabled } : null
+ ),
+ },
+ { id: 'view-div-webtoon', label: '', divider: true },
+ {
+ id: 'view-webtoon-mode',
+ label: isWebtoonMode
+ ? 'Exit Webtoon Studio Mode'
+ : 'Webtoon Studio Mode (9:16 Mockup)',
+ icon: <Smartphone className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => uiStoreActions.toggleWebtoonMode(),
+ },
+ { id: 'view-div-soft-proof', label: '', divider: true },
+ {
+ id: 'view-proof-setup',
+ label: 'Proof Setup',
+ disabled: !hasOpenDocument,
+ submenu: (
+ [
+ {
+ id: 'proof-setup-us-web',
+ label: 'Working CMYK - U.S. Web Coated (SWOP) v2',
+ standard: 'us-web-coated-swop' as CmykStandard,
+ },
+ {
+ id: 'proof-setup-japan',
+ label: 'Japan Color 2001 Coated',
+ standard: 'japan-color-2001' as CmykStandard,
+ },
+ {
+ id: 'proof-setup-iso',
+ label: 'ISO Coated v2 (ECI)',
+ standard: 'iso-coated-v2' as CmykStandard,
+ },
+ ] as const
+ ).map((opt) => ({
+ id: opt.id,
+ label: opt.label,
+ checked: softProofSettings.standard === opt.standard,
+ onClick: () => documentStoreActions.setProofStandard(opt.standard),
+ })),
+ },
+ {
+ id: 'view-proof-colors',
+ label: 'Proof Colors',
+ shortcut: 'Ctrl+Alt+Y',
+ checked: softProofSettings.enabled,
+ disabled: !hasOpenDocument,
+ onClick: () => documentStoreActions.toggleSoftProof(),
+ },
+ {
+ id: 'view-gamut-warning',
+ label: 'Gamut Warning',
+ shortcut: 'Ctrl+Shift+Y',
+ checked: softProofSettings.gamutWarning,
+ disabled: !hasOpenDocument,
+ onClick: () => documentStoreActions.toggleGamutWarning(),
+ },
+ ],
+ },
+ {
+ id: 'manga',
+ label: 'Manga',
+ items: [
+ {
+ id: 'manga-effects-generator',
+ label: 'Manga Effect Lines Generator...',
+ icon: <Sparkles className="w-3.5 h-3.5 text-amber-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => uiStoreActions.setMangaEffectsModalOpen(true),
+ },
+ {
+ id: 'manga-balloon-tool',
+ label: 'Parametric Speech Balloon Tool',
+ icon: <MessageSquare className="w-3.5 h-3.5 text-cyan-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => toolStoreActions.selectTool('balloon'),
+ },
+ {
+ id: 'manga-correct-line',
+ label: 'Correct Line (Vector Pinch/Width/Simplify)',
+ icon: <Spline className="w-3.5 h-3.5 text-indigo-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => toolStoreActions.selectTool('vector-edit'),
+ },
+ { id: 'manga-div-webtoon', label: '', divider: true },
+ {
+ id: 'manga-webtoon-toggle',
+ label: isWebtoonMode
+ ? 'Exit Webtoon Studio Mode'
+ : 'Webtoon Studio Mode (9:16 Simulator)',
+ icon: <Smartphone className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => uiStoreActions.toggleWebtoonMode(),
+ },
+ {
+ id: 'manga-webtoon-export',
+ label: 'Export Webtoon Chapter Slices (.zip)...',
+ icon: <Archive className="w-3.5 h-3.5 text-sky-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => uiStoreActions.setWebtoonExportModalOpen(true),
+ },
+ ],
+ },
+ {
+ id: 'animation',
+ label: 'Animation',
+ items: [
+ {
+ id: 'anim-toggle-timeline',
+ label: activeAnimationTimeline
+ ? 'Hide Animation Timeline'
+ : 'Show Animation Timeline',
+ shortcut: 'Ctrl+Alt+A',
+ icon: <Film className="w-3.5 h-3.5 text-emerald-400" />,
+ disabled: !hasOpenDocument,
+ onClick: () => {
+ if (activeAnimationTimeline) {
+ handleUpdateAnimationTimeline(null);
+ } else {
+ handleUpdateAnimationTimeline(createDefaultAnimationTimeline(layers));
+ }
+ },
+ },
+ {
+ id: 'anim-new-cel',
+ label: 'Add Cel to Current Frame',
+ shortcut: 'Alt+C',
+ icon: <Plus className="w-3.5 h-3.5" />,
+ disabled: !hasOpenDocument || !activeAnimationTimeline,
+ onClick: () => {
+ if (activeAnimationTimeline) {
+ handleAddAnimationCel(activeAnimationTimeline.currentFrame);
+ }
+ },
+ },
+ {
+ id: 'anim-toggle-onion',
+ label: activeAnimationTimeline?.onionSkin.enabled
+ ? 'Disable Onion Skinning'
+ : 'Enable Onion Skinning',
+ icon: <Layers className="w-3.5 h-3.5 text-purple-400" />,
+ disabled: !hasOpenDocument || !activeAnimationTimeline,
+ onClick: () => {
+ if (activeAnimationTimeline) {
+ handleUpdateAnimationTimeline({
+ ...activeAnimationTimeline,
+ onionSkin: {
+ ...activeAnimationTimeline.onionSkin,
+ enabled: !activeAnimationTimeline.onionSkin.enabled,
+ },
+ });
+ }
+ },
+ },
+ ],
+ },
+ {
+ id: 'window',
+ label: 'Window',
+ items: [
+ {
+ id: 'window-workspace',
+ label: 'Workspace',
+ submenu: [
+ ...(
+ ['default-illustration', 'manga-studio', 'minimalist-tablet', 'custom'] as WorkspacePresetId[]
+ ).map((preset) => ({
+ id: `window-preset-${preset}`,
+ label: WORKSPACE_PRESET_LABELS[preset],
+ checked: activePreset === preset,
+ onClick: () => workspaceStoreActions.applyPreset(preset),
+ })),
+ { id: 'window-ws-div-1', label: '', divider: true },
+ {
+ id: 'window-ws-save-custom',
+ label: 'Register Current Layout as Custom',
+ onClick: () => {
+ workspaceStoreActions.saveAsCustomPreset();
+ showToast('Workspace saved to Custom preset');
+ },
+ },
+ {
+ id: 'window-ws-reset',
+ label: 'Reset Workspace',
+ icon: <RotateCcw className="w-3.5 h-3.5 text-amber-400" />,
+ onClick: () => {
+ workspaceStoreActions.resetWorkspace();
+ showToast('Workspace reset to preset defaults');
+ },
+ },
+ ],
+ },
+ {
+ id: 'window-toggle-palettes',
+ label: palettesHidden ? 'Show Palettes' : 'Hide Palettes',
+ shortcut: 'Tab',
+ checked: !palettesHidden,
+ onClick: () => workspaceStoreActions.togglePalettesHidden(),
+ },
+ { id: 'window-div-palettes', label: '', divider: true },
+ ...ALL_DOCK_PANEL_IDS.map((pid) => ({
+ id: `window-panel-${pid}`,
+ label: DOCK_PANEL_META[pid].title,
+ checked: visiblePanels.has(pid),
+ onClick: () => workspaceStoreActions.togglePanelVisibility(pid),
+ })),
+ { id: 'window-div-bars', label: '', divider: true },
+ {
+ id: 'window-toggle-command-bar',
+ label: 'Command Bar',
+ checked: showCommandBar,
+ onClick: () => workspaceStoreActions.setShowCommandBar(!showCommandBar),
+ },
+ {
+ id: 'window-toggle-doc-tabs',
+ label: 'Document Tab Bar',
+ checked: showDocumentTabs,
+ onClick: () => workspaceStoreActions.setShowDocumentTabs(!showDocumentTabs),
+ },
+ {
+ id: 'window-toggle-status-bar',
+ label: 'Status Bar',
+ checked: showStatusBar,
+ onClick: () => workspaceStoreActions.setShowStatusBar(!showStatusBar),
+ },
+ ],
+ },
+ {
+ id: 'help',
+ label: 'Help',
+ items: [
+ {
+ id: 'help-about',
+ label: 'About Ink Studio',
+ icon: <InfoIcon className="w-3.5 h-3.5 text-[#93c5fd]" />,
+ onClick: () => {
+ alert(
+ 'Ink Studio - Professional Digital Painting & Manga Studio\n\n' +
+ '- Full Layer Management with 17 Blend Modes\n' +
+ '- Supports Opening PSD (Photoshop) & CSP (Clip Studio Paint) with layers\n' +
+ '- Supports Common Images: PNG, JPG, WEBP, GIF, BMP, SVG\n' +
+ '- Save & Save As: PSD (layered), Ink Studio Project (.sora / .ink), PNG, JPG, WebP\n' +
+ '- Export Image: High-resolution PNG\n' +
+ '- Color Modes: Full Color (RGB), Grayscale, and 1-bit Manga Monochrome\n' +
+ '- CSP Sub-Tool Engine, Tablet Pressure, Tilt & Inking Stabilization'
+ );
+ },
+ },
+ ],
+ },
+ ],
+ [
+ activeAnimationTimeline,
+ activeLayer,
+ activeLayerId,
+ activePreset,
+ addLayerMask,
+ canRedo,
+ canUndo,
+ clearCanvas,
+ deleteLayer,
+ dimensions,
+ duplicateLayer,
+ flipX,
+ flipY,
+ handleAddAnimationCel,
+ handleAddLayer,
+ handleApplyFilter,
+ handleApplyReverseGradient,
+ handleClearActiveLayer,
+ handleContractSelection,
+ handleConvertLayer,
+ handleCopySelectedLayer,
+ handleDeleteSelectedLayer,
+ handleDeselect,
+ handleExpandSelection,
+ handleExportImage,
+ handleFeatherSelection,
+ handleFillSelectionColor,
+ handleInvertSelection,
+ handleMergeDown,
+ handleOpenAdjustmentModal,
+ handleOpenLayerStylesModal,
+ handleOpenTonalModal,
+ handlePasteSelectedLayer,
+ handleSave,
+ handleSaveAs,
+ handleSelectAll,
+ handleStartTransform,
+ handleTriggerImport3DFile,
+ handleTriggerOpenFile,
+ handleTriggerPasteFromFile,
+ handleUndo,
+ handleUpdateAnimationTimeline,
+ hasOpenDocument,
+ isWebtoonMode,
+ layers,
+ palettesHidden,
+ perspectiveRuler,
+ redo,
+ removeLayerMask,
+ resetRotation,
+ resetViewFlip,
+ resetZoomAndCenter,
+ selection,
+ showCommandBar,
+ showDocumentTabs,
+ showStatusBar,
+ showToast,
+ softProofSettings.enabled,
+ softProofSettings.gamutWarning,
+ softProofSettings.standard,
+ toggleFlipHorizontal,
+ toggleFlipVertical,
+ toggleLayerColor,
+ toggleLayerMask,
+ toggleMaskLinked,
+ visiblePanels,
+ zoomIn,
+ zoomOut,
+ ]
+ );
+}
diff --git a/src/hooks/useCanvasDrawing.ts b/src/hooks/useCanvasDrawing.ts
index 7b1f503..cbbe9ea 100644
--- a/src/hooks/useCanvasDrawing.ts
+++ b/src/hooks/useCanvasDrawing.ts
@@ -1,195 +1,17 @@
-import { useRef, useEffect, useState, useCallback } from 'react';
+import { useRef, useEffect, useCallback } from 'react';
import {
- ToolType,
- BrushSettings,
- Point,
- CanvasDimensions,
- CanvasSelection,
- HistoryActionType,
- HistoryItem,
- HistoryItemMeta,
- CanvasColorMode,
- DirtyRect,
- LayerItem,
- TileDelta,
- VectorStroke,
- VectorKnot,
-} from '../types/editor';
-import { SparseTileGrid, globalTileGrid, TILE_SIZE, TileFormat, releaseTemporaryCanvas } from '../utils/tileEngine';
-import { UndoCacheManager, globalUndoCache } from '../utils/undoCache';
-import { documentStore } from '../utils/documentStore';
-import { recoveryService } from '../services/recoveryService';
-import {
- applyVectorEraser,
- renderVectorLayer,
- renderVectorStroke,
- computeStrokeBounds,
- simplifyPathPoints,
-} from '../utils/vectorEngine';
-import {
- calculateStrokeWidth,
- drawSmoothCubicBezierSegment,
- drawDot,
- screenToCanvas,
- screenToCanvasInto,
- getCanvasToViewportMatrix,
- getVisibleCanvasBounds,
- createCanvasThumbnail,
- formatTime,
- get2DContext,
- getReusableBakeCanvas,
- renderCompleteStroke,
- applyParametricTaper,
-} from '../utils/canvasUtils';
-import {
- StrokePipeline,
- computeClampedBakeDirtyRect,
- encodePointerType,
-} from '../engine/StrokePipeline';
-import { CubicBezierSegment } from '../engine/SplineGenerator';
-import { CanvasNavigationHandle } from './useCanvasNavigation';
-import { applyCspWatercolorEdge } from '../engine/CspBrushEngine';
-import { enforceColorMode, binarizeImageDataBuffer } from '../utils/colorUtils';
-import { drawPencilCubicBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';
-import {
- drawTexturedCubicBezierSegment,
- drawTexturedDot,
- TexturedBrushOptions,
- RadialMixingOptions,
- canUseWebGlForTexturedBrush,
- canUseWebGlForRadialBrush,
- flushTexturedGpuDabs,
- flushRadialGpuDabs,
-} from '../utils/stampEngine';
-import { GpuDab } from '../utils/webglBrushEngine';
-import { PaintReservoir, LayerPixelSampler } from '../utils/colorMixingEngine';
-import { applyLayerEffects } from '../utils/layerEffectsEngine';
-import { PerspectiveRuler, ConstraintAxis } from '../types/perspective';
-import { PerspectiveSnapSession } from '../utils/perspectiveSnapping';
-
-function isBackgroundLayerId(id: string): boolean {
- return id === 'layer-bg' || id.startsWith('layer-bg');
-}
-
-function applySelectionCanvasClip(
- ctx: CanvasRenderingContext2D,
- sel: CanvasSelection | null | undefined
-): void {
- if (!sel) return;
- if (sel.type === 'rect') {
- ctx.beginPath();
- ctx.rect(sel.bounds.x, sel.bounds.y, sel.bounds.width, sel.bounds.height);
- ctx.clip();
- } else if (sel.type === 'lasso' && sel.polygon && sel.polygon.length >= 3) {
- ctx.beginPath();
- ctx.moveTo(sel.polygon[0].x, sel.polygon[0].y);
- for (let i = 1; i < sel.polygon.length; i++) {
- ctx.lineTo(sel.polygon[i].x, sel.polygon[i].y);
- }
- ctx.closePath();
- ctx.clip();
- } else if (sel.svgPath && typeof Path2D !== 'undefined') {
- try {
- ctx.clip(new Path2D(sel.svgPath), 'evenodd');
- } catch {
- // Fallback to bounds clip if svgPath fails
- ctx.beginPath();
- ctx.rect(sel.bounds.x, sel.bounds.y, sel.bounds.width, sel.bounds.height);
- ctx.clip();
- }
- }
-}
-
-function applySelectionMaskToImageData(
- beforeData: ImageData,
- afterData: ImageData,
- rx: number,
- ry: number,
- sel: CanvasSelection | null | undefined
-): void {
- if (!sel || !sel.mask || !sel.maskWidth || !sel.maskHeight) return;
- const mask = sel.mask;
- const mw = sel.maskWidth;
- const mh = sel.maskHeight;
- const w = afterData.width;
- const h = afterData.height;
- const src = beforeData.data;
- const dst = afterData.data;
-
- for (let ly = 0; ly < h; ly++) {
- const docY = ry + ly;
- const inY = docY >= 0 && docY < mh;
- const maskRow = docY * mw;
- const imgRow = ly * w;
- for (let lx = 0; lx < w; lx++) {
- const docX = rx + lx;
- const mAlpha = inY && docX >= 0 && docX < mw ? mask[maskRow + docX] : 0;
- if (mAlpha === 255) continue;
- const idx = (imgRow + lx) * 4;
- if (mAlpha === 0) {
- dst[idx] = src[idx];
- dst[idx + 1] = src[idx + 1];
- dst[idx + 2] = src[idx + 2];
- dst[idx + 3] = src[idx + 3];
- } else {
- const wAfter = mAlpha / 255;
- const wBefore = 1 - wAfter;
- const aB = (src[idx + 3] / 255) * wBefore;
- const aA = (dst[idx + 3] / 255) * wAfter;
- const outA = aB + aA;
- if (outA <= 0.0001) {
- dst[idx] = 0;
- dst[idx + 1] = 0;
- dst[idx + 2] = 0;
- dst[idx + 3] = 0;
- } else {
- dst[idx] = Math.round((src[idx] * aB + dst[idx] * aA) / outA);
- dst[idx + 1] = Math.round((src[idx + 1] * aB + dst[idx + 1] * aA) / outA);
- dst[idx + 2] = Math.round((src[idx + 2] * aB + dst[idx + 2] * aA) / outA);
- dst[idx + 3] = Math.round(outA * 255);
- }
- }
- }
- }
-}
-
-interface UseCanvasDrawingProps {
- tool: ToolType;
- brushSettings: BrushSettings;
- dimensions: CanvasDimensions;
- selection?: CanvasSelection | null;
- colorMode?: CanvasColorMode;
- disabled?: boolean;
- viewportRef: React.RefObject<HTMLDivElement | null>;
- pan: { x: number; y: number };
- zoom: number;
- rotation: number;
- flipX?: boolean;
- flipY?: boolean;
- navigation?: CanvasNavigationHandle;
- activeLayerId: string;
- activeLayerLocked?: boolean;
- activeLayerVisible?: boolean;
- layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- layerSourceCanvasesRef?: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
- layers?: LayerItem[];
- onUpdateLayerThumbnail: (layerId: string) => void;
- isMaskMode?: boolean;
- onUpdateMaskThumbnail?: (layerId: string) => void;
- draftCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
- strokeCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
- predictedCanvasRef?: React.RefObject<HTMLCanvasElement | null>;
- onCollabStrokeStart?: (strokeId: string, layerId: string, brushSettings: BrushSettings, tool: ToolType, startPoint: Point) => void;
- onCollabStrokeChunk?: (strokeId: string, points: Point[]) => void;
- onCollabStrokeFinish?: (strokeId: string, layerId: string, endPoint: Point, dirtyRect?: DirtyRect, vectorStroke?: VectorStroke) => void;
- onCollabCursorMove?: (x: number, y: number, isDrawing: boolean, tool: ToolType) => void;
- perspectiveRuler?: PerspectiveRuler | null;
- onActiveConstraintAxisChange?: (axis: ConstraintAxis | null) => void;
- activeSessionId?: string | null;
- tileGrid?: SparseTileGrid;
- materializeLayerCanvas?: (layerId: string) => HTMLCanvasElement | null;
-}
-
+ LastStrokeEndState,
+ UseCanvasDrawingProps,
+ useBrushStrokeSession,
+ useDrawingHistory,
+} from './drawing';
+
+export type { UseCanvasDrawingProps, PushHistoryStepFn } from './drawing';
+
+/**
+ * Thin canvas drawing dispatcher coordinating history, raster/WebGL brush sessions,
+ * and vector stroke commit/erase via modular hooks in `src/hooks/drawing/`.
+ */
export function useCanvasDrawing({
tool,
brushSettings,
@@ -205,9 +27,6 @@ export function useCanvasDrawing({
flipY = false,
navigation,
activeLayerId,
- activeSessionId,
- tileGrid,
- materializeLayerCanvas,
activeLayerLocked = false,
activeLayerVisible = true,
layerCanvasesRef,
@@ -225,52 +44,17 @@ export function useCanvasDrawing({
onCollabCursorMove,
perspectiveRuler = null,
onActiveConstraintAxisChange,
+ activeSessionId = null,
+ tileGrid,
+ materializeLayerCanvas,
}: UseCanvasDrawingProps) {
- // Current active collaborative stroke ID
- const currentStrokeIdRef = useRef<string | null>(null);
-
- // Active stroke is on a screentone layer
- const isToneStrokeRef = useRef(false);
-
- // Synchronous reference to layers list
- const layersRef = useRef(layers);
- layersRef.current = layers;
-
- // Support both draftCanvasRef and legacy strokeCanvasRef prop
- const effectiveDraftCanvasRef = draftCanvasRef || strokeCanvasRef;
-
- const getPredictedCanvas = useCallback((): HTMLCanvasElement | null => {
- if (predictedCanvasRef?.current) return predictedCanvasRef.current;
- const draft = effectiveDraftCanvasRef?.current;
- if (draft?.parentElement) {
- return draft.parentElement.querySelector<HTMLCanvasElement>('canvas.predicted-overlay-canvas');
- }
- return null;
- }, [effectiveDraftCanvasRef, predictedCanvasRef]);
+ const effectiveDraftCanvasRef = draftCanvasRef ?? strokeCanvasRef;
- const isPredictedCanvasDirtyRef = useRef(false);
- const latestPredictedRef = useRef<{ predEvents: PointerEvent[]; vRect: DOMRect } | null>(null);
-
- const clearPredictedCanvas = useCallback(() => {
- if (!isPredictedCanvasDirtyRef.current) return;
- const pCanvas = getPredictedCanvas();
- if (pCanvas) {
- const pCtx = get2DContext(pCanvas);
- if (pCtx) {
- pCtx.resetTransform();
- pCtx.clearRect(0, 0, pCanvas.width, pCanvas.height);
- }
- }
- isPredictedCanvasDirtyRef.current = false;
- }, [getPredictedCanvas]);
-
- // Top overlay interaction reference for pointer capture and events
const interactionRef = useRef<HTMLDivElement | null>(null);
const isDrawingRef = useRef(false);
- const activePointerIdRef = useRef<number | null>(null);
+ const lastStrokeEndRef = useRef<LastStrokeEndState | null>(null);
+ const abortActiveStrokeRef = useRef<() => void>(() => {});
- // Keep navigation transforms and editor settings updated in synchronous refs
- // When `navigation` handle is provided, read directly from its live refs so strokes hit exact document pixels even before debounced React state commits
const fallbackPanRef = useRef(pan);
const fallbackZoomRef = useRef(zoom);
const fallbackRotationRef = useRef(rotation);
@@ -281,8 +65,9 @@ export function useCanvasDrawing({
const rotationRef = navigation?.rotationRef ?? fallbackRotationRef;
const flipXRef = navigation?.flipXRef ?? fallbackFlipXRef;
const flipYRef = navigation?.flipYRef ?? fallbackFlipYRef;
- const brushSettingsRef = useRef(brushSettings);
- const toolRef = useRef(tool);
+
+ const toolOverrideRef = useRef(tool);
+ const brushSettingsOverrideRef = useRef(brushSettings);
const colorModeRef = useRef(colorMode);
const activeLayerIdRef = useRef(activeLayerId);
const activeLayerLockedRef = useRef(activeLayerLocked);
@@ -290,177 +75,66 @@ export function useCanvasDrawing({
const dimensionsRef = useRef(dimensions);
const selectionRef = useRef(selection);
const isMaskModeRef = useRef(isMaskMode);
+ const layersRef = useRef(layers);
const onUpdateMaskThumbnailRef = useRef(onUpdateMaskThumbnail);
-
- // Synchronously keep fallback & editor refs fresh during render execution
- fallbackPanRef.current = pan;
- fallbackZoomRef.current = zoom;
- fallbackRotationRef.current = rotation;
- fallbackFlipXRef.current = flipX;
- fallbackFlipYRef.current = flipY;
- brushSettingsRef.current = brushSettings;
- toolRef.current = tool;
- colorModeRef.current = colorMode;
- activeLayerIdRef.current = activeLayerId;
- activeLayerLockedRef.current = activeLayerLocked;
- activeLayerVisibleRef.current = activeLayerVisible;
- dimensionsRef.current = dimensions;
- selectionRef.current = selection;
- layersRef.current = layers;
- isMaskModeRef.current = isMaskMode;
- onUpdateMaskThumbnailRef.current = onUpdateMaskThumbnail;
-
const onCollabStrokeStartRef = useRef(onCollabStrokeStart);
const onCollabStrokeChunkRef = useRef(onCollabStrokeChunk);
const onCollabStrokeFinishRef = useRef(onCollabStrokeFinish);
const onCollabCursorMoveRef = useRef(onCollabCursorMove);
-
const rulerRef = useRef(perspectiveRuler);
- rulerRef.current = perspectiveRuler;
const onActiveConstraintAxisChangeRef = useRef(onActiveConstraintAxisChange);
- onActiveConstraintAxisChangeRef.current = onActiveConstraintAxisChange;
- const snapSessionRef = useRef(new PerspectiveSnapSession());
-
- const lastEmittedAxisRef = useRef<ConstraintAxis | null>(null);
- const emitConstraintAxisChange = useCallback((newAxis: ConstraintAxis | null) => {
- const prev = lastEmittedAxisRef.current;
- if (prev === newAxis) return;
- if (
- prev &&
- newAxis &&
- prev.type === newAxis.type &&
- prev.origin.x === newAxis.origin.x &&
- prev.origin.y === newAxis.origin.y &&
- prev.dir.x === newAxis.dir.x &&
- prev.dir.y === newAxis.dir.y
- ) {
- return;
- }
- lastEmittedAxisRef.current = newAxis;
- onActiveConstraintAxisChangeRef.current?.(newAxis);
- }, []);
useEffect(() => {
- fallbackPanRef.current = pan;
- fallbackZoomRef.current = zoom;
- fallbackRotationRef.current = rotation;
- fallbackFlipXRef.current = flipX;
- fallbackFlipYRef.current = flipY;
- brushSettingsRef.current = brushSettings;
- toolRef.current = tool;
+ if (!navigation) {
+ fallbackPanRef.current = pan;
+ fallbackZoomRef.current = zoom;
+ fallbackRotationRef.current = rotation;
+ fallbackFlipXRef.current = flipX;
+ fallbackFlipYRef.current = flipY;
+ }
+ toolOverrideRef.current = tool;
+ brushSettingsOverrideRef.current = brushSettings;
colorModeRef.current = colorMode;
activeLayerIdRef.current = activeLayerId;
activeLayerLockedRef.current = activeLayerLocked;
activeLayerVisibleRef.current = activeLayerVisible;
dimensionsRef.current = dimensions;
- layersRef.current = layers;
+ selectionRef.current = selection;
isMaskModeRef.current = isMaskMode;
+ layersRef.current = layers;
onUpdateMaskThumbnailRef.current = onUpdateMaskThumbnail;
- rulerRef.current = perspectiveRuler;
- onActiveConstraintAxisChangeRef.current = onActiveConstraintAxisChange;
-
onCollabStrokeStartRef.current = onCollabStrokeStart;
onCollabStrokeChunkRef.current = onCollabStrokeChunk;
onCollabStrokeFinishRef.current = onCollabStrokeFinish;
onCollabCursorMoveRef.current = onCollabCursorMove;
- });
-
- // Full sequence of points for high-resolution baking on pointerup
- const allStrokePointsRef = useRef<Point[]>([]);
-
- // Zero-allocation input ring buffer, 1-Euro corner-snapping stabilizer, spline generator, and taper engine
- const strokePipelineRef = useRef(new StrokePipeline());
-
- // Reusable per-frame GPU dab batch (eliminates per-frame array allocation on hot path)
- const frameGpuDabsRef = useRef<GpuDab[]>([]);
-
- // Pre-allocated scratch coordinates for zero-GC pointermove ingestion & prediction
- const scratchDocCoordRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
- const predCoordPoolRef = useRef<Array<{ x: number; y: number; pressure?: number }>>([
- { x: 0, y: 0, pressure: 0.5 },
- { x: 0, y: 0, pressure: 0.5 },
- { x: 0, y: 0, pressure: 0.5 },
+ rulerRef.current = perspectiveRuler;
+ onActiveConstraintAxisChangeRef.current = onActiveConstraintAxisChange;
+ }, [
+ navigation,
+ pan,
+ zoom,
+ rotation,
+ flipX,
+ flipY,
+ tool,
+ brushSettings,
+ colorMode,
+ activeLayerId,
+ activeLayerLocked,
+ activeLayerVisible,
+ dimensions,
+ selection,
+ isMaskMode,
+ layers,
+ onUpdateMaskThumbnail,
+ onCollabStrokeStart,
+ onCollabStrokeChunk,
+ onCollabStrokeFinish,
+ onCollabCursorMove,
+ perspectiveRuler,
+ onActiveConstraintAxisChange,
]);
- const predDocCoordsRef = useRef<Array<{ x: number; y: number; pressure?: number }>>([]);
- const predDabCounterRef = useRef<{ count: number }>({ count: 0 });
- const lastQueuedPressureRef = useRef<number>(0.5);
-
- // Stabilizer tracking ref (previous stabilized point for velocity dynamics)
- const stabilizedPointRef = useRef<Point | null>(null);
-
- // Distance accumulator for textured brush dab stepping
- const stampRemainderDistRef = useRef<number>(0);
- const liveDabCounterRef = useRef<{ count: number }>({ count: 0 });
-
- // Active color mixing reservoir & lazy tile sampler (reads clean pre-stroke SparseTileGrid)
- const activeReservoirRef = useRef<PaintReservoir | null>(null);
- const layerPixelSamplerRef = useRef<LayerPixelSampler | null>(null);
-
- const isWetColorStrokeRef = useRef<boolean>(false);
- const liveNeedsNotifyRef = useRef<boolean>(false);
- const lastStrokeEndRef = useRef<{ x: number; y: number; pressure: number; width: number; layerId: string } | null>(null);
- const isShiftLineStrokeRef = useRef<boolean>(false);
- const historyQueueRef = useRef<Promise<void>>(Promise.resolve());
- const lastPointTimeRef = useRef<number>(0);
- const recentPointsTrailRef = useRef<{ x: number; y: number; t: number; pressure: number; width: number }[]>([]);
- const strokeTotalDistanceRef = useRef<number>(0);
- // Dirty bounding box for the active stroke (mirrored from StrokePipeline.dirtyRect)
- const dirtyRectRef = useRef<{ minX: number; minY: number; maxX: number; maxY: number } | null>(null);
- const touchedTilesRef = useRef<Set<number>>(new Set());
- const lastProcessedPointRef = useRef<{ x: number; y: number }>({ x: 0, y: 0 });
- const hasLastProcessedPointRef = useRef<boolean>(false);
-
- const markTouchedTiles = useCallback((minX: number, minY: number, maxX: number, maxY: number) => {
- const dims = dimensionsRef.current;
- const clampedMinX = Math.max(0, Math.floor(minX));
- const clampedMinY = Math.max(0, Math.floor(minY));
- const clampedMaxX = Math.min(dims.width, Math.ceil(maxX));
- const clampedMaxY = Math.min(dims.height, Math.ceil(maxY));
- if (clampedMaxX <= clampedMinX || clampedMaxY <= clampedMinY) return;
- const minTx = clampedMinX >> 8;
- const minTy = clampedMinY >> 8;
- const maxTx = (clampedMaxX - 1) >> 8;
- const maxTy = (clampedMaxY - 1) >> 8;
- for (let ty = minTy; ty <= maxTy; ty++) {
- for (let tx = minTx; tx <= maxTx; tx++) {
- touchedTilesRef.current.add(ty * 65536 + tx);
- }
- }
- }, []);
-
- const drawRafIdRef = useRef<number | null>(null);
- const clearDraftRafRef = useRef<number | null>(null);
-
-
- // Per-document isolated tile grid, undo cache, and history stack bound to activeSessionId
- const activeSessionIdRef = useRef<string | null>(activeSessionId ?? null);
- const activeTileGridRef = useRef<SparseTileGrid>(
- tileGrid ?? (activeSessionId ? documentStore.getOrCreateSession(activeSessionId).tileGrid : globalTileGrid)
- );
- const activeUndoCacheRef = useRef<UndoCacheManager>(
- activeSessionId ? documentStore.getOrCreateSession(activeSessionId).undoCache : globalUndoCache
- );
-
- // Undo / Redo history stack of rich history items (synchronized with active TileGridSession)
- const initialSession = activeSessionId ? documentStore.getOrCreateSession(activeSessionId) : null;
- const historyRef = useRef<HistoryItem[]>(initialSession ? initialSession.history : []);
- const historyIndexRef = useRef<number>(initialSession ? initialSession.historyIndex : -1);
- const [historyList, setHistoryList] = useState<HistoryItemMeta[]>([]);
- const [historyIndex, setHistoryIndex] = useState<number>(-1);
- const [canUndo, setCanUndo] = useState(false);
- const [canRedo, setCanRedo] = useState(false);
-
- // Keep tileGridRef fresh if caller passes an explicit grid
- if (tileGrid) {
- activeTileGridRef.current = tileGrid;
- } else if (activeSessionId) {
- const sess = documentStore.getOrCreateSession(activeSessionId);
- activeTileGridRef.current = sess.tileGrid;
- activeUndoCacheRef.current = sess.undoCache;
- }
-
- // Non-allocating lookup of an already-materialized canvas (or active mask canvas)
const getCachedLayerCanvas = useCallback(
(layerId?: string): HTMLCanvasElement | null => {
const targetId = layerId || activeLayerIdRef.current || activeLayerId;
@@ -475,7 +149,6 @@ export function useCanvasDrawing({
[activeLayerId, layerCanvasesRef]
);
- // Public getter used by legacy canvas-based tools in App.tsx (materializes on demand from SparseTileGrid)
const getActiveCanvas = useCallback(() => {
const targetId = activeLayerIdRef.current || activeLayerId;
if (isMaskModeRef.current) {
@@ -496,3013 +169,87 @@ export function useCanvasDrawing({
);
}, [activeLayerId, layerCanvasesRef, materializeLayerCanvas]);
- const persistSessionHistory = useCallback((docId?: string | null) => {
- const targetDocId = docId !== undefined ? docId : activeSessionIdRef.current;
- if (!targetDocId) return;
- const sess = documentStore.getSession(targetDocId);
- if (sess) {
- sess.history = historyRef.current;
- sess.historyIndex = historyIndexRef.current;
- }
- }, []);
-
- // Real-time hover / draw stats dispatched via lightweight custom events without triggering React re-renders
- const statRafRef = useRef<number | null>(null);
- const pendingStatRef = useRef<{ x: number | null; y: number | null; pressure: number } | null>(null);
-
- // Cached viewport bounds to eliminate forced layout reflow during pointer movement
- const cachedViewportRectRef = useRef<DOMRect | null>(null);
-
- const getViewportRect = useCallback((): DOMRect | null => {
- if (!cachedViewportRectRef.current && viewportRef.current) {
- cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
- }
- return cachedViewportRectRef.current;
- }, [viewportRef]);
-
- useEffect(() => {
- const handleResize = () => {
- cachedViewportRectRef.current = null;
- };
- window.addEventListener('resize', handleResize);
- window.addEventListener('scroll', handleResize, true);
- let ro: ResizeObserver | null = null;
- if (typeof ResizeObserver !== 'undefined' && viewportRef.current) {
- ro = new ResizeObserver(handleResize);
- ro.observe(viewportRef.current);
- }
- return () => {
- window.removeEventListener('resize', handleResize);
- window.removeEventListener('scroll', handleResize, true);
- ro?.disconnect();
- if (clearDraftRafRef.current !== null) {
- cancelAnimationFrame(clearDraftRafRef.current);
- }
- if (drawRafIdRef.current !== null) {
- cancelAnimationFrame(drawRafIdRef.current);
- }
- };
- }, [viewportRef, disabled, activeSessionId]);
-
- const dispatchPointerStat = useCallback((x: number | null, y: number | null, pressure: number) => {
- pendingStatRef.current = {
- x: x !== null ? Math.round(x) : null,
- y: y !== null ? Math.round(y) : null,
- pressure,
- };
- if (statRafRef.current === null) {
- statRafRef.current = requestAnimationFrame(() => {
- statRafRef.current = null;
- if (pendingStatRef.current) {
- window.dispatchEvent(
- new CustomEvent('canvas-pointer-stat', {
- detail: { ...pendingStatRef.current, isHovering: pendingStatRef.current.x !== null },
- })
- );
- }
- });
- }
- }, []);
-
- const syncHistoryState = useCallback(() => {
- const idx = historyIndexRef.current;
- const len = historyRef.current.length;
- setHistoryIndex(idx);
- setCanUndo(idx > 0);
- setCanRedo(idx >= 0 && idx < len - 1);
- setHistoryList(
- historyRef.current.map((item) => ({
- id: item.id,
- type: item.type,
- label: item.label,
- timestamp: item.timestamp,
- timeFormatted: item.timeFormatted,
- thumbnailUrl: item.thumbnailUrl,
- layerId: item.layerId,
- }))
- );
- }, []);
-
- const ensureInitialHistory = useCallback(() => {
- if (historyRef.current.length === 0) {
- const now = Date.now();
- const targetLayerId = activeLayerIdRef.current;
- const dims = dimensionsRef.current;
- const grid = activeTileGridRef.current;
- const initialThumb = targetLayerId
- ? createCanvasThumbnail({ grid, layerId: targetLayerId, dimensions: dims }, !isBackgroundLayerId(targetLayerId))
- : '';
-
- const initialItem: HistoryItem = {
- id: `hist-init-${now}`,
- type: 'initial',
- label: 'New Document',
- timestamp: now,
- timeFormatted: formatTime(now),
- thumbnailUrl: initialThumb,
- imageData: undefined,
- beforeImageData: null,
- afterImageData: null,
- layerId: targetLayerId,
- };
-
- historyRef.current = [initialItem];
- historyIndexRef.current = 0;
- persistSessionHistory();
- syncHistoryState();
- }
- }, [persistSessionHistory, syncHistoryState]);
-
- const pushHistoryStep = useCallback(
- (
- actionType: HistoryActionType,
- label: string,
- beforeData: ImageData | null,
- afterData: ImageData | null,
- targetLayerId: string,
- dirtyRect?: DirtyRect,
- explicitTileDeltas?: TileDelta[],
- vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },
- peerId?: string | number,
- strokeId?: string,
- isMaskEdit?: boolean
- ) => {
- const now = Date.now();
- const dims = dimensionsRef.current;
- const grid = activeTileGridRef.current;
- const docId = activeSessionIdRef.current;
- const undoCache = activeUndoCacheRef.current;
-
- let tileDeltas = explicitTileDeltas;
-
- const effectiveDirtyRect =
- dirtyRect || (dims.width > 0 && dims.height > 0 ? { x: 0, y: 0, width: dims.width, height: dims.height } : undefined);
-
- // Automatically convert ImageData change into minimal SparseTileGrid TileDeltas (skip for mask edits)
- if (!isMaskEdit && !tileDeltas && effectiveDirtyRect && (beforeData || afterData)) {
- const activeLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const isMono = !isBackgroundLayerId(targetLayerId) && (colorModeRef.current === 'monochrome' || activeLayer?.expressionColor === 'monochrome');
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (beforeData) {
- const bx = beforeData.width === effectiveDirtyRect.width && beforeData.height === effectiveDirtyRect.height ? effectiveDirtyRect.x : 0;
- const by = beforeData.width === effectiveDirtyRect.width && beforeData.height === effectiveDirtyRect.height ? effectiveDirtyRect.y : 0;
- grid.writeImageData(targetLayerId, beforeData, bx, by, targetFormat);
- }
-
- const beforeSnapshot = grid.snapshotTilesInRect(targetLayerId, effectiveDirtyRect);
-
- if (afterData) {
- const ax = afterData.width === effectiveDirtyRect.width && afterData.height === effectiveDirtyRect.height ? effectiveDirtyRect.x : 0;
- const ay = afterData.width === effectiveDirtyRect.width && afterData.height === effectiveDirtyRect.height ? effectiveDirtyRect.y : 0;
- grid.writeImageData(targetLayerId, afterData, ax, ay, targetFormat);
- } else if (actionType === 'clear') {
- grid.clearLayer(targetLayerId);
- }
-
- tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, targetLayerId, effectiveDirtyRect);
- }
-
- const hasDeltas = Boolean(tileDeltas && tileDeltas.length > 0);
-
- const item: HistoryItem = {
- id: `hist-${now}-${Math.random().toString(36).substring(2, 7)}`,
- type: actionType,
- label,
- timestamp: now,
- timeFormatted: formatTime(now),
- thumbnailUrl: '',
- layerId: targetLayerId,
- // Memory optimization for 600 DPI manga: eliminate large 35MP ImageData arrays in RAM when tile deltas exist
- beforeImageData: hasDeltas ? null : beforeData,
- afterImageData: hasDeltas ? null : afterData,
- imageData: hasDeltas ? undefined : (afterData || undefined),
- dirtyRect: effectiveDirtyRect,
- tileDeltas: hasDeltas ? tileDeltas : undefined,
- vectorStrokesDelta: vectorDelta,
- peerId,
- strokeId,
- isMaskEdit,
- };
-
- // Branching: truncate any future redo steps
- const newHistory = historyRef.current.slice(0, historyIndexRef.current + 1);
- newHistory.push(item);
-
- // Keep max 50 states to maintain smooth memory & performance
- if (newHistory.length > 50) {
- newHistory.shift();
- }
-
- historyRef.current = newHistory;
- historyIndexRef.current = newHistory.length - 1;
- persistSessionHistory(docId);
-
- if (dims.width > 0 && dims.height > 0) {
- const isLarge = dims.width * dims.height > 1024 * 1024;
- if (isLarge && hasDeltas) {
- const existingLayerThumb = layersRef.current?.find((l) => l.id === targetLayerId)?.thumbnailUrl || '';
- item.thumbnailUrl = existingLayerThumb;
- } else {
- item.thumbnailUrl = createCanvasThumbnail(
- { grid, layerId: targetLayerId, dimensions: dims },
- !isBackgroundLayerId(targetLayerId)
- );
- }
- }
- syncHistoryState();
-
- // Per-document LRU disk cache offloading with shared RAM budget across all open tabs
- if (tileDeltas && tileDeltas.length > 0) {
- const registerPromise = docId
- ? documentStore.registerUndoStep(docId, item)
- : undoCache.registerStep(item, historyRef.current);
- registerPromise.catch((err) => {
- console.warn('[History] LRU cache registration failed:', err);
- });
- }
-
- // Non-blocking WAL journaling for crash recovery
- if ((tileDeltas && tileDeltas.length > 0) || vectorDelta) {
- const sessionKey = docId || recoveryService.getCurrentSessionId() || 'default-session';
- recoveryService.logStrokeDelta(sessionKey, tileDeltas, vectorDelta, targetLayerId);
- }
- },
- [persistSessionHistory, syncHistoryState]
- );
-
- // Background history serialization queue to eliminate main-thread hitches on stroke lift-off
- const pendingHistoryTasksRef = useRef<Array<() => void>>([]);
- const idleCallbackIdRef = useRef<any>(null);
-
- const flushPendingHistoryTasks = useCallback(() => {
- if (idleCallbackIdRef.current !== null) {
- if (typeof window !== 'undefined' && 'cancelIdleCallback' in window) {
- (window as any).cancelIdleCallback(idleCallbackIdRef.current);
- } else {
- clearTimeout(idleCallbackIdRef.current);
- }
- idleCallbackIdRef.current = null;
- }
- const tasks = pendingHistoryTasksRef.current.splice(0);
- for (const task of tasks) {
- try {
- task();
- } catch (err) {
- console.warn('[History] Error flushing pending history task:', err);
- }
- }
- }, []);
-
- const enqueueHistoryTask = useCallback((task: () => void) => {
- pendingHistoryTasksRef.current.push(task);
- if (idleCallbackIdRef.current === null) {
- const scheduleRun = () => {
- if (typeof window !== 'undefined' && 'requestIdleCallback' in window) {
- idleCallbackIdRef.current = (window as any).requestIdleCallback(runTasks, { timeout: 1200 });
- } else {
- idleCallbackIdRef.current = setTimeout(runTasks, 64);
- }
- };
- const runTasks = () => {
- idleCallbackIdRef.current = null;
- if (isDrawingRef.current) {
- scheduleRun();
- return;
- }
- const tasks = pendingHistoryTasksRef.current.splice(0);
- for (const t of tasks) {
- try {
- t();
- } catch (err) {
- console.warn('[History] Error running idle history task:', err);
- }
- }
- };
- scheduleRun();
- }
- }, []);
-
- // Abort any in-progress stroke session immediately (zero base-layer mutation to undo!)
- const abortActiveStroke = useCallback(() => {
- if (!isDrawingRef.current) return;
- if (drawRafIdRef.current !== null) {
- cancelAnimationFrame(drawRafIdRef.current);
- drawRafIdRef.current = null;
- }
- const draftCanvas = effectiveDraftCanvasRef?.current;
- let clearedActiveDraft = false;
- if (draftCanvas) {
- const dCtx = get2DContext(draftCanvas);
- if (dCtx) {
- try {
- dCtx.restore();
- } catch (_) {}
- dCtx.resetTransform();
- dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
- }
- if ((draftCanvas as any).__draftHasContent) {
- clearedActiveDraft = true;
- }
- (draftCanvas as any).__draftHasContent = false;
- (draftCanvas as any).__draftCompositeOp = 'source-over';
- (draftCanvas as any).__draftMonochrome = false;
- (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
- }
- clearPredictedCanvas();
- if (clearedActiveDraft) {
- activeTileGridRef.current.notifyChange(true);
- }
- strokePipelineRef.current.abortStroke();
- frameGpuDabsRef.current.length = 0;
- isDrawingRef.current = false;
- activePointerIdRef.current = null;
- allStrokePointsRef.current = [];
- stabilizedPointRef.current = null;
- hasLastProcessedPointRef.current = false;
- dirtyRectRef.current = null;
- touchedTilesRef.current.clear();
- liveNeedsNotifyRef.current = false;
- isShiftLineStrokeRef.current = false;
- isToneStrokeRef.current = false;
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
- snapSessionRef.current.endStroke();
- emitConstraintAxisChange(null);
- }, [clearPredictedCanvas, effectiveDraftCanvasRef, emitConstraintAxisChange]);
-
- // Jump directly to any past or future history step (serialized via historyQueueRef to prevent async race on rapid Ctrl+Z)
- const jumpToHistoryIndex = useCallback(
- (targetIndex: number): Promise<void> => {
- flushPendingHistoryTasks();
- if (isDrawingRef.current) {
- abortActiveStroke();
- }
- const nextOp = historyQueueRef.current.then(async () => {
- if (targetIndex < 0 || targetIndex >= historyRef.current.length) return;
- const currentIndex = historyIndexRef.current;
- if (targetIndex === currentIndex) return;
-
- const grid = activeTileGridRef.current;
- const undoCache = activeUndoCacheRef.current;
- const dims = dimensionsRef.current;
-
- if (targetIndex < currentIndex) {
- // Rolling back (undoing) in reverse chronological order
- for (let i = currentIndex; i > targetIndex; i--) {
- const item = historyRef.current[i];
- if (item) {
- const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
- const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
- const deltas = await undoCache.resolveDeltas(item);
-
- // Restore mask canvas if mask edit
- if (item.isMaskEdit && targetLayer?.maskCanvas) {
- const mCtx = get2DContext(targetLayer.maskCanvas);
- if (mCtx && item.beforeImageData) {
- const mx = item.dirtyRect && item.beforeImageData.width === item.dirtyRect.width ? item.dirtyRect.x : 0;
- const my = item.dirtyRect && item.beforeImageData.height === item.dirtyRect.height ? item.dirtyRect.y : 0;
- mCtx.putImageData(item.beforeImageData, mx, my);
- targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
- onUpdateMaskThumbnailRef.current?.(targetLayerId);
- }
- } else if (item.vectorStrokesDelta && targetLayer) {
- targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
- const tempVec = canvas || document.createElement('canvas');
- if (!canvas) {
- tempVec.width = dims.width;
- tempVec.height = dims.height;
- }
- const cCtx = get2DContext(tempVec);
- if (cCtx) {
- cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
- renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const isMono = targetLayer.expressionColor === 'monochrome';
- grid.clearLayer(targetLayerId);
- grid.ingestCanvas(targetLayerId, tempVec, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- if (!canvas) releaseTemporaryCanvas(tempVec);
- } else if (deltas && deltas.length > 0) {
- grid.applyTileDeltas(deltas, 'undo');
-
- if (isToneStep && sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- if (canvas && targetLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- targetLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
- } else if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- if (sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- }
- }
- } else if (isToneStep && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- if (item.dirtyRect && item.beforeImageData) {
- sCtx.putImageData(item.beforeImageData, item.dirtyRect.x, item.dirtyRect.y);
- } else if (item.beforeImageData) {
- sCtx.putImageData(item.beforeImageData, 0, 0);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- }
- }
- }
-
- if (canvas && targetLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- targetLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
- } else {
- const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (item.beforeImageData) {
- const bx = item.dirtyRect && item.beforeImageData.width === item.dirtyRect.width && item.beforeImageData.height === item.dirtyRect.height ? item.dirtyRect.x : 0;
- const by = item.dirtyRect && item.beforeImageData.width === item.dirtyRect.width && item.beforeImageData.height === item.dirtyRect.height ? item.dirtyRect.y : 0;
- grid.writeImageData(targetLayerId, item.beforeImageData, bx, by, targetFormat);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- grid.fillLayerSolidWhite(targetLayerId, dims.width, dims.height, 'color-32bit');
- } else {
- grid.clearLayer(targetLayerId);
- }
- }
-
- if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- }
- if (sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- }
- }
-
- onUpdateLayerThumbnail(targetLayerId);
- }
- }
- } else {
- // Rolling forward (redoing) in forward chronological order
- for (let i = currentIndex + 1; i <= targetIndex; i++) {
- const item = historyRef.current[i];
- const dataToApply = item?.afterImageData || item?.imageData;
- if (item) {
- const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(targetLayerId);
- const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const isToneStep = Boolean(targetLayer?.toneEnabled && sourceCanvas);
- const deltas = await undoCache.resolveDeltas(item);
-
- // Restore mask canvas if mask edit
- if (item.isMaskEdit && targetLayer?.maskCanvas) {
- const mCtx = get2DContext(targetLayer.maskCanvas);
- if (mCtx && dataToApply) {
- const mx = item.dirtyRect && dataToApply.width === item.dirtyRect.width ? item.dirtyRect.x : 0;
- const my = item.dirtyRect && dataToApply.height === item.dirtyRect.height ? item.dirtyRect.y : 0;
- mCtx.putImageData(dataToApply, mx, my);
- targetLayer.maskVersion = (targetLayer.maskVersion || 0) + 1;
- onUpdateMaskThumbnailRef.current?.(targetLayerId);
- }
- } else if (item.vectorStrokesDelta && targetLayer) {
- targetLayer.vectorStrokes = item.vectorStrokesDelta.after;
- const tempVec = canvas || document.createElement('canvas');
- if (!canvas) {
- tempVec.width = dims.width;
- tempVec.height = dims.height;
- }
- const cCtx = get2DContext(tempVec);
- if (cCtx) {
- cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
- renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const isMono = targetLayer.expressionColor === 'monochrome';
- grid.clearLayer(targetLayerId);
- grid.ingestCanvas(targetLayerId, tempVec, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- if (!canvas) releaseTemporaryCanvas(tempVec);
- } else if (deltas && deltas.length > 0) {
- grid.applyTileDeltas(deltas, 'redo');
-
- if (isToneStep && sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- if (canvas && targetLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- targetLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
- } else if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- if (sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- }
- }
- } else if (isToneStep && sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- if (item.dirtyRect && dataToApply) {
- sCtx.putImageData(dataToApply, item.dirtyRect.x, item.dirtyRect.y);
- } else if (dataToApply) {
- sCtx.putImageData(dataToApply, 0, 0);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- }
- }
- }
-
- if (canvas && targetLayer) {
- applyLayerEffects(
- sourceCanvas,
- canvas,
- targetLayer,
- dimensionsRef.current.dpi ?? 600,
- item.dirtyRect
- );
- }
- } else {
- const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
- const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
-
- if (dataToApply) {
- const ax = item.dirtyRect && dataToApply.width === item.dirtyRect.width && dataToApply.height === item.dirtyRect.height ? item.dirtyRect.x : 0;
- const ay = item.dirtyRect && dataToApply.width === item.dirtyRect.width && dataToApply.height === item.dirtyRect.height ? item.dirtyRect.y : 0;
- grid.writeImageData(targetLayerId, dataToApply, ax, ay, targetFormat);
- } else if (item.type === 'initial') {
- if (isBackgroundLayerId(targetLayerId)) {
- grid.fillLayerSolidWhite(targetLayerId, dims.width, dims.height, 'color-32bit');
- } else {
- grid.clearLayer(targetLayerId);
- }
- }
-
- if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- }
- if (sourceCanvas) {
- grid.renderLayerToCanvas(targetLayerId, sourceCanvas, item.dirtyRect);
- }
- }
-
- onUpdateLayerThumbnail(targetLayerId);
- }
- }
- }
-
- historyIndexRef.current = targetIndex;
- persistSessionHistory();
- syncHistoryState();
- grid.notifyChange(true);
- });
- historyQueueRef.current = nextOp.catch((err) => {
- console.warn('[History] Error during jumpToHistoryIndex:', err);
- });
- return historyQueueRef.current;
- },
- [abortActiveStroke, activeLayerId, flushPendingHistoryTasks, layerCanvasesRef, layerSourceCanvasesRef, onUpdateLayerThumbnail, syncHistoryState]
- );
-
- // Undo action
- const undo = useCallback(() => {
- flushPendingHistoryTasks();
- if (isDrawingRef.current) {
- abortActiveStroke();
- }
- if (historyIndexRef.current <= 0) return;
- jumpToHistoryIndex(historyIndexRef.current - 1);
- }, [abortActiveStroke, flushPendingHistoryTasks, jumpToHistoryIndex]);
-
- // Redo action
- const redo = useCallback(() => {
- flushPendingHistoryTasks();
- if (isDrawingRef.current) {
- abortActiveStroke();
- }
- if (historyIndexRef.current >= historyRef.current.length - 1) return;
- jumpToHistoryIndex(historyIndexRef.current + 1);
- }, [abortActiveStroke, flushPendingHistoryTasks, jumpToHistoryIndex]);
-
- // Selective Undo per Peer
- const selectiveUndo = useCallback(
- async (peerIdToUndo?: string | number) => {
- flushPendingHistoryTasks();
- if (isDrawingRef.current) {
- abortActiveStroke();
- }
-
- const history = historyRef.current;
- const currIdx = historyIndexRef.current;
- if (currIdx < 0 || history.length === 0) return;
-
- // Find the most recent history item matching the requested peerId (or local)
- let targetItemIdx = -1;
- for (let i = currIdx; i >= 0; i--) {
- const item = history[i];
- if (!peerIdToUndo || item.peerId === peerIdToUndo || (peerIdToUndo === 'local' && !item.peerId)) {
- targetItemIdx = i;
- break;
- }
- }
-
- if (targetItemIdx === -1) return;
-
- const item = history[targetItemIdx];
- const targetLayerId = item.layerId || activeLayerId;
- const canvas = layerCanvasesRef.current.get(targetLayerId) || null;
- const targetLayer = layersRef.current?.find((l) => l.id === targetLayerId);
- const grid = activeTileGridRef.current;
- const undoCache = activeUndoCacheRef.current;
- const dims = dimensionsRef.current;
-
- // Revert vector strokes if vector delta exists
- if (item.vectorStrokesDelta && targetLayer) {
- targetLayer.vectorStrokes = item.vectorStrokesDelta.before;
- const tempVec = canvas || document.createElement('canvas');
- if (!canvas) {
- tempVec.width = dims.width;
- tempVec.height = dims.height;
- }
- const cCtx = get2DContext(tempVec);
- if (cCtx) {
- cCtx.clearRect(0, 0, tempVec.width, tempVec.height);
- renderVectorLayer(cCtx, targetLayer.vectorStrokes);
- const isMono = targetLayer.expressionColor === 'monochrome';
- grid.clearLayer(targetLayerId);
- grid.ingestCanvas(targetLayerId, tempVec, isMono ? 'monochrome-1bit' : 'color-32bit');
- }
- if (!canvas) releaseTemporaryCanvas(tempVec);
- } else {
- // Revert tile deltas or image data
- const deltas = await undoCache.resolveDeltas(item);
- if (deltas && deltas.length > 0) {
- grid.applyTileDeltas(deltas, 'undo');
- if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- }
- } else if (item.beforeImageData) {
- const isMono = !isBackgroundLayerId(targetLayerId) && (targetLayer?.expressionColor === 'monochrome' || colorModeRef.current === 'monochrome');
- const bx = item.dirtyRect ? item.dirtyRect.x : 0;
- const by = item.dirtyRect ? item.dirtyRect.y : 0;
- grid.writeImageData(targetLayerId, item.beforeImageData, bx, by, isMono ? 'monochrome-1bit' : 'color-32bit');
- if (canvas) {
- grid.renderLayerToCanvas(targetLayerId, canvas, item.dirtyRect);
- }
- }
- }
-
- // Remove the undone item from history
- historyRef.current.splice(targetItemIdx, 1);
- historyIndexRef.current = Math.min(historyIndexRef.current - 1, historyRef.current.length - 1);
- persistSessionHistory();
- syncHistoryState();
-
- onUpdateLayerThumbnail(targetLayerId);
- grid.notifyChange(true);
- },
- [abortActiveStroke, activeLayerId, flushPendingHistoryTasks, layerCanvasesRef, onUpdateLayerThumbnail, persistSessionHistory, syncHistoryState]
- );
-
- // Clear active layer action directly via SparseTileGrid (zero full-canvas getImageData)
- const clearCanvas = useCallback(() => {
- if (!activeLayerId || activeLayerLocked) return;
- const dims = dimensionsRef.current;
- if (dims.width <= 0 || dims.height <= 0) return;
-
- const grid = activeTileGridRef.current;
- const activeLayer = layersRef.current?.find((l) => l.id === activeLayerId);
- const isBg = isBackgroundLayerId(activeLayerId);
- const fullRect = { x: 0, y: 0, width: dims.width, height: dims.height };
-
- const beforeSnapshot = isBg
- ? grid.snapshotTilesInRect(activeLayerId, fullRect)
- : grid.snapshotLayerTiles(activeLayerId);
-
- let vectorDelta: { before: VectorStroke[]; after: VectorStroke[] } | undefined;
- if (activeLayer?.type === 'vector') {
- const beforeStrokes = [...(activeLayer.vectorStrokes || [])];
- activeLayer.vectorStrokes = [];
- vectorDelta = { before: beforeStrokes, after: [] };
- }
-
- if (isBg) {
- grid.fillLayerSolidWhite(activeLayerId, dims.width, dims.height, 'color-32bit');
- } else {
- grid.clearLayer(activeLayerId);
- grid.markLayerIngested(activeLayerId);
- }
-
- const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, activeLayerId, isBg ? fullRect : undefined);
-
- const canvas = layerCanvasesRef.current.get(activeLayerId);
- if (canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- if (isBg) {
- ctx.fillStyle = '#ffffff';
- ctx.fillRect(0, 0, canvas.width, canvas.height);
- } else {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- }
- }
- }
-
- const sourceCanvas = layerSourceCanvasesRef?.current?.get(activeLayerId);
- if (sourceCanvas) {
- const sCtx = get2DContext(sourceCanvas);
- if (sCtx) {
- if (isBg) {
- sCtx.fillStyle = '#ffffff';
- sCtx.fillRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- } else {
- sCtx.clearRect(0, 0, sourceCanvas.width, sourceCanvas.height);
- }
- }
- }
-
- onUpdateLayerThumbnail(activeLayerId);
- pushHistoryStep(
- 'clear',
- 'Clear Layer',
- null,
- null,
- activeLayerId,
- fullRect,
- tileDeltas,
- vectorDelta
- );
- grid.notifyChange(true);
- }, [activeLayerId, activeLayerLocked, layerCanvasesRef, layerSourceCanvasesRef, onUpdateLayerThumbnail, pushHistoryStep]);
-
- // Isolate and swap per-document history & UndoCacheManager when activeSessionId changes
- useEffect(() => {
- const prevDocId = activeSessionIdRef.current;
- const nextDocId = activeSessionId ?? null;
- if (prevDocId === nextDocId) return;
-
- // Flush any pending history tasks for the previous document BEFORE switching refs
- flushPendingHistoryTasks();
- if (isDrawingRef.current) {
- abortActiveStroke();
- }
- if (prevDocId) {
- persistSessionHistory(prevDocId);
- }
-
- activeSessionIdRef.current = nextDocId;
- lastStrokeEndRef.current = null;
-
- if (nextDocId) {
- const sess = documentStore.getOrCreateSession(nextDocId);
- activeTileGridRef.current = tileGrid ?? sess.tileGrid;
- activeUndoCacheRef.current = sess.undoCache;
- historyRef.current = sess.history;
- historyIndexRef.current = sess.historyIndex;
- } else {
- activeTileGridRef.current = tileGrid ?? globalTileGrid;
- activeUndoCacheRef.current = globalUndoCache;
- historyRef.current = [];
- historyIndexRef.current = -1;
- }
-
- syncHistoryState();
- }, [activeSessionId, tileGrid, abortActiveStroke, flushPendingHistoryTasks, persistSessionHistory, syncHistoryState]);
-
- // Initialize document's first history state as soon as an active layer exists (no full canvas needed)
- useEffect(() => {
- if (historyRef.current.length > 0) return;
- if (!activeLayerId || dimensions.width <= 0 || dimensions.height <= 0) return;
- ensureInitialHistory();
- }, [activeLayerId, activeSessionId, dimensions.width, dimensions.height, ensureInitialHistory]);
-
- // Convert client pointer event coordinates to canvas pixel space
- const getCanvasPoint = useCallback(
- (e: React.PointerEvent<HTMLElement> | PointerEvent): Point => {
- const vRect = getViewportRect();
- const dims = dimensionsRef.current;
- const bs = brushSettingsRef.current;
- if (!vRect) return { x: 0, y: 0, pressure: 0.5, width: bs.size, timestamp: e.timeStamp };
-
- const { x, y } = screenToCanvas(
- e.clientX,
- e.clientY,
- vRect,
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims,
- flipXRef.current,
- flipYRef.current
- );
-
- let pressure = 0;
- if (e.pointerType === 'mouse') {
- pressure = (e.buttons & 1) ? 0.5 : 0;
- } else {
- pressure = e.pressure !== undefined ? Math.max(0, Math.min(1.0, e.pressure)) : 0;
- }
-
- const width = calculateStrokeWidth(
- bs.size,
- pressure,
- bs.minSizeFactor,
- bs.usePressure,
- e.pointerType,
- bs.pressureCurveGamma ?? 1.0,
- 1.0,
- bs.pressureCurve
- );
-
- const tiltX = e.tiltX ?? 0;
- const tiltY = e.tiltY ?? 0;
- const twist = e.twist ?? 0;
-
- return { x, y, pressure, width, tiltX, tiltY, twist, timestamp: e.timeStamp };
- },
- [getViewportRect]
- );
-
- const buildLiveTexturedOptions = useCallback(
- (
- bs: BrushSettings,
- strokeFlow: number,
- strokeSpacing: number,
- strokeHardness: number,
- isMonochrome: boolean,
- canvas: HTMLCanvasElement | null,
- activeLayer: LayerItem | undefined,
- isEraser: boolean,
- isBgEraser: boolean,
- isolatedPass: boolean = false
- ): TexturedBrushOptions => ({
- size: bs.size,
- minSizeFactor: bs.minSizeFactor,
- opacity: isolatedPass ? 1.0 : bs.opacity,
- flow: strokeFlow,
- adjustDensityByGap: bs.adjustDensityByGap,
- blendTipsMode: bs.blendTipsMode,
- spacing: strokeSpacing,
- thickness: bs.thickness,
- thicknessVertical: bs.thicknessVertical,
- flipH: bs.flipH,
- flipV: bs.flipV,
- isColorTip: bs.isColorTip,
- angle: bs.customTipAngle,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: isMonochrome ? 0 : bs.antiAlias,
- pressureCurve: bs.pressureCurve,
- velocityCurve: bs.velocityCurve,
- usePressure: bs.usePressure,
- useVelocity: bs.useVelocity,
- useTilt: Boolean(bs.useTilt),
- sizeSensor: bs.sizeSensor,
- opacitySensor: bs.opacitySensor,
- densitySensor: bs.densitySensor,
- subTips: bs.subTips,
- subTipOrder: bs.subTipOrder,
- subTipImages: bs.subTipImages,
- spray: bs.spray,
- taper: bs.taper,
- colorMixing: bs.colorMixing,
- perceptualMixing: bs.perceptualMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- wetEdge: 0,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureMode: bs.paperTextureMode,
- paperTextureBrightness: bs.paperTextureBrightness,
- paperTextureContrast: bs.paperTextureContrast,
- paperTextureInverted: bs.paperTextureInverted,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useGpu: bs.useGpu !== false,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- isEraser: isolatedPass ? false : isEraser && !isBgEraser,
- isBgEraser: isolatedPass ? false : isBgEraser,
- alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
- isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
- currentStrokeDist: strokeTotalDistanceRef.current,
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- }),
- []
- );
-
- const buildLiveRadialOptions = useCallback(
- (
- bs: BrushSettings,
- isMonochrome: boolean,
- canvas: HTMLCanvasElement | null,
- activeLayer: LayerItem | undefined,
- isolatedPass: boolean = false
- ): RadialMixingOptions => ({
- colorMixing: bs.colorMixing,
- perceptualMixing: bs.perceptualMixing,
- amountOfPaint: bs.amountOfPaint,
- densityOfPaint: bs.densityOfPaint,
- colorStretch: bs.colorStretch,
- mixingMode: bs.mixingMode,
- underlyingCanvas: canvas || undefined,
- sampler: layerPixelSamplerRef.current || undefined,
- reservoir: activeReservoirRef.current || undefined,
- alphaLocked: isolatedPass ? false : Boolean(activeLayer?.alphaLocked),
- isTransparentInk: isolatedPass ? false : Boolean(bs.isTransparentInk),
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- useGpu: bs.useGpu !== false,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useTilt: Boolean(bs.useTilt),
- thicknessVertical: bs.thicknessVertical,
- flipH: bs.flipH,
- flipV: bs.flipV,
- antiAlias: isMonochrome ? 0 : bs.antiAlias,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- adjustDensityByGap: bs.adjustDensityByGap,
- blendTipsMode: bs.blendTipsMode,
- grain: bs.grain ?? bs.textureDensity,
- paperTextureMode: bs.paperTextureMode,
- paperTextureBrightness: bs.paperTextureBrightness,
- paperTextureContrast: bs.paperTextureContrast,
- paperTextureInverted: bs.paperTextureInverted,
- paperTextureImage: bs.paperTextureImage,
- paperTextureScale: bs.paperTextureScale,
- paperTextureRotate: bs.paperTextureRotate,
- sizeSensor: bs.sizeSensor,
- opacitySensor: bs.opacitySensor,
- densitySensor: bs.densitySensor,
- taper: bs.taper,
- }),
- []
- );
-
- // Helper: compute effective live stroke color for current mode/mask/bg-eraser
- const resolveStrokeColor = useCallback(
- (bs: BrushSettings, isEraser: boolean, isBgEraser: boolean, isMonochrome: boolean, mode: CanvasColorMode): string => {
- if (isMaskModeRef.current) {
- if (isEraser) return '#000000';
- let clean = bs.color.replace('#', '');
- if (clean.length === 3) clean = clean.split('').map((c) => c + c).join('');
- const r = parseInt(clean.slice(0, 2), 16) || 0;
- const g = parseInt(clean.slice(2, 4), 16) || 0;
- const b = parseInt(clean.slice(4, 6), 16) || 0;
- const gray = Math.round(0.299 * r + 0.587 * g + 0.114 * b);
- const hexVal = gray.toString(16).padStart(2, '0');
- return `#${hexVal}${hexVal}${hexVal}`;
- }
- return isBgEraser ? '#ffffff' : enforceColorMode(bs.color, isMonochrome ? 'monochrome' : mode);
- },
- []
- );
-
- // Renders a sealed CubicBezierSegment onto draftCtx (either pushing into GPU batch or Canvas 2D fallback)
- const emitLiveSegment = useCallback(
- (
- draftCtx: CanvasRenderingContext2D,
- seg: CubicBezierSegment,
- bs: BrushSettings,
- strokeColor: string,
- strokeHardness: number,
- strokeFlow: number,
- strokeSpacing: number,
- isMonochrome: boolean,
- isPencil: boolean,
- isEraser: boolean,
- isBgEraser: boolean,
- useWireframeEraser: boolean,
- canvas: HTMLCanvasElement | null,
- activeLayer: LayerItem | undefined,
- gpuBatch: GpuDab[] | undefined
- ) => {
- const sStart = seg.p0;
- const c1Pt = seg.c1;
- const c2Pt = seg.c2;
- const sEnd = seg.p3;
-
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const segPad = Math.ceil(Math.max(sStart.width, sEnd.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32);
- const segMinX = Math.min(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) - segPad;
- const segMinY = Math.min(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) - segPad;
- const segMaxX = Math.max(sStart.x, c1Pt.x, c2Pt.x, sEnd.x) + segPad;
- const segMaxY = Math.max(sStart.y, c1Pt.y, c2Pt.y, sEnd.y) + segPad;
- strokePipelineRef.current.expandDirtyRectBounds(segMinX, segMinY, segMaxX, segMaxY);
- markTouchedTiles(segMinX, segMinY, segMaxX, segMaxY);
-
- if (useWireframeEraser) {
- draftCtx.save();
- draftCtx.lineCap = 'round';
- draftCtx.lineJoin = 'round';
- draftCtx.setLineDash([4, 4]);
- draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- draftCtx.lineWidth = Math.max(1, (sStart.width + sEnd.width) / 2);
- draftCtx.beginPath();
- draftCtx.moveTo(sStart.x, sStart.y);
- draftCtx.bezierCurveTo(c1Pt.x, c1Pt.y, c2Pt.x, c2Pt.y, sEnd.x, sEnd.y);
- draftCtx.stroke();
- draftCtx.restore();
- return;
- }
-
- const liveColor = (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- const draftCanvas = effectiveDraftCanvasRef?.current;
- const draftScale = (draftCanvas as any)?.__draftScale ?? 1.0;
- const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
-
- if (bs.customTipImage) {
- const tipOptions = buildLiveTexturedOptions(
- bs,
- isMonochrome ? 1.0 : (bs.flow ?? 1.0),
- bs.spacing ?? 0.08,
- strokeHardness,
- downscaledBinary ? false : isMonochrome,
- canvas,
- activeLayer,
- isEraser,
- isBgEraser,
- true
- );
- if (downscaledBinary && tipOptions.antiAlias === 0) {
- tipOptions.antiAlias = 2;
- }
- stampRemainderDistRef.current = drawTexturedCubicBezierSegment(
- draftCtx,
- sStart,
- c1Pt,
- c2Pt,
- sEnd,
- liveColor,
- bs.customTipImage,
- tipOptions,
- stampRemainderDistRef.current,
- liveDabCounterRef.current,
- gpuBatch
- );
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- stampRemainderDistRef.current = drawPencilCubicBezierSegment(
- draftCtx,
- sStart,
- c1Pt,
- c2Pt,
- sEnd,
- liveColor,
- grade,
- isMonochrome ? 1.0 : (bs.flow ?? 0.74),
- bs.grain ?? 1.0,
- strokeHardness,
- stampRemainderDistRef.current,
- false,
- false,
- bs.useTilt ?? true
- );
- } else {
- const radialMixingOptions = buildLiveRadialOptions(
- bs,
- downscaledBinary ? false : isMonochrome,
- canvas,
- activeLayer,
- true
- );
- if (downscaledBinary && radialMixingOptions.antiAlias === 0) {
- radialMixingOptions.antiAlias = 2;
- }
- stampRemainderDistRef.current = drawSmoothCubicBezierSegment(
- draftCtx,
- sStart,
- c1Pt,
- c2Pt,
- sEnd,
- liveColor,
- false,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- stampRemainderDistRef.current,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- radialMixingOptions,
- gpuBatch
- );
- }
- },
- [buildLiveRadialOptions, buildLiveTexturedOptions, effectiveDraftCanvasRef, markTouchedTiles]
- );
-
- // Ephemeral predicted tail overlay rendered strictly onto effectivePredictedCanvasRef (never leaks into layer data)
- const renderPredictedStroke = useCallback(
- (predEvents: PointerEvent[], vRect: DOMRect) => {
- clearPredictedCanvas();
- const bs = brushSettingsRef.current;
- if (toolRef.current === 'eraser' || bs.isTransparentInk) return;
- const pipeline = strokePipelineRef.current;
- if (pipeline.getKnotCount() < 2) return;
- const pCanvas = getPredictedCanvas();
- if (!pCanvas) return;
- const pCtx = get2DContext(pCanvas);
- if (!pCtx) return;
-
- const dims = dimensionsRef.current;
- const mode = colorModeRef.current;
- const currentLayerId = activeLayerIdRef.current;
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isPencil = !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const strokeColor = resolveStrokeColor(bs, false, false, isMonochrome, mode);
- const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
- const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
- const strokeSpacing = bs.spacing ?? 0.08;
-
- const maxPredDist = Math.min(20, Math.max(4, (bs.size || 10) * 1.15));
- const predCoords = predDocCoordsRef.current;
- predCoords.length = 0;
-
- if (predEvents && predEvents.length > 0) {
- const scratch = scratchDocCoordRef.current;
- const pool = predCoordPoolRef.current;
- const limit = Math.min(predEvents.length, pool.length);
- for (let i = 0; i < limit; i++) {
- const ev = predEvents[i];
- screenToCanvasInto(
- ev.clientX,
- ev.clientY,
- vRect,
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims,
- scratch,
- flipXRef.current,
- flipYRef.current
- );
- const slot = pool[i];
- slot.x = scratch.x;
- slot.y = scratch.y;
- slot.pressure = ev.pressure;
- predCoords.push(slot);
- }
- }
-
- const scaleX = pCanvas.width / Math.max(1, vRect.width);
- const scaleY = pCanvas.height / Math.max(1, vRect.height);
- const matrix = getCanvasToViewportMatrix(
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims,
- scaleX,
- scaleY,
- flipXRef.current,
- flipYRef.current
- );
-
- pCtx.save();
- pCtx.setTransform(matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f);
- pCtx.beginPath();
- pCtx.rect(0, 0, dims.width, dims.height);
- pCtx.clip();
- applySelectionCanvasClip(pCtx, selectionRef.current);
-
- let predRem = stampRemainderDistRef.current;
- // On viewport-sized predictedCanvas when zoomed out in monochrome, use smooth AA=2 (thresholded by SVG filter) so pixels never drop
- const predAA = isMonochrome && zoomRef.current < 1.0 ? 2 : (isMonochrome ? 0 : bs.antiAlias);
- const predTipOpts: TexturedBrushOptions | null = bs.customTipImage
- ? {
- size: bs.size,
- minSizeFactor: bs.minSizeFactor,
- opacity: 1.0,
- flow: strokeFlow,
- spacing: strokeSpacing,
- thickness: bs.thickness,
- thicknessVertical: bs.thicknessVertical,
- angle: bs.customTipAngle,
- angleDynamics: bs.customTipAngleDynamics,
- rotationRandomScale: bs.customTipRotationRandomScale,
- hardness: strokeHardness,
- antiAlias: predAA,
- pressureCurve: bs.pressureCurve,
- usePressure: bs.usePressure,
- subTips: bs.subTips,
- subTipOrder: bs.subTipOrder,
- subTipImages: bs.subTipImages,
- spray: bs.spray,
- wetEdge: 0,
- grain: bs.grain ?? bs.textureDensity,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- useGpu: bs.useGpu !== false,
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- }
- : null;
- const predRadialOpts: RadialMixingOptions = {
- useGpu: bs.useGpu !== false,
- antiAlias: predAA,
- dynamics: bs.dynamics,
- secondaryColor: bs.secondaryColor,
- dualBrush: bs.dualBrush,
- dualTipImage: bs.dualTipImage,
- dualBrushCompositeMode: bs.dualBrushCompositeMode,
- grain: bs.grain ?? bs.textureDensity,
- };
-
- const predGpuDabs = frameGpuDabsRef.current;
- predGpuDabs.length = 0;
- const useGpuPred = bs.customTipImage
- ? Boolean(predTipOpts && canUseWebGlForTexturedBrush(predTipOpts))
- : (!isPencil && canUseWebGlForRadialBrush(predRadialOpts));
-
- predDabCounterRef.current.count = liveDabCounterRef.current.count;
- // In zoomed-out monochrome mode, committed LOD tiles (OR-downsampled) and mipmapped draftCanvas
- // preserve sub-pixel ink at ~1.35 CSS px; lift transient predicted-bridge widths to match.
- const minPredMonoWidth = isMonochrome && zoomRef.current < 0.99 ? 1.35 / Math.max(0.01, zoomRef.current) : 0;
- // Render ONLY the real unsealed Catmull-Rom bridge (knotP1 -> knotP2), avoiding speculative
- // ahead-of-cursor overshoot that snaps back / disappears upon pointerup.
- const drew = pipeline.buildPredictedSegments(
- null,
- maxPredDist,
- (seg) => {
- const p0 = minPredMonoWidth > 0 && seg.p0.width < minPredMonoWidth ? { ...seg.p0, width: minPredMonoWidth } : seg.p0;
- const p3 = minPredMonoWidth > 0 && seg.p3.width < minPredMonoWidth ? { ...seg.p3, width: minPredMonoWidth } : seg.p3;
- if (bs.customTipImage && predTipOpts) {
- predRem = drawTexturedCubicBezierSegment(
- pCtx,
- p0,
- seg.c1,
- seg.c2,
- p3,
- strokeColor,
- bs.customTipImage,
- predTipOpts,
- predRem,
- predDabCounterRef.current,
- useGpuPred ? predGpuDabs : undefined
- );
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- predRem = drawPencilCubicBezierSegment(
- pCtx,
- p0,
- seg.c1,
- seg.c2,
- p3,
- strokeColor,
- grade,
- isMonochrome ? 1.0 : (bs.flow ?? 0.74),
- bs.grain ?? 1.0,
- strokeHardness,
- predRem,
- false,
- false
- );
- } else {
- predRem = drawSmoothCubicBezierSegment(
- pCtx,
- p0,
- seg.c1,
- seg.c2,
- p3,
- strokeColor,
- false,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- predRem,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- predRadialOpts,
- useGpuPred ? predGpuDabs : undefined
- );
- }
- }
- );
-
- if (useGpuPred && predGpuDabs.length > 0) {
- if (bs.customTipImage && predTipOpts) {
- flushTexturedGpuDabs(pCtx, predGpuDabs, bs.customTipImage, strokeColor, predTipOpts);
- } else {
- flushRadialGpuDabs(pCtx, predGpuDabs, strokeColor, strokeHardness, false, false, predRadialOpts);
- }
- predGpuDabs.length = 0;
- }
-
- pCtx.restore();
- if (drew) {
- isPredictedCanvasDirtyRef.current = true;
- }
- },
- [clearPredictedCanvas, getPredictedCanvas, resolveStrokeColor]
- );
-
- // Flush batched points from StrokePipeline ring buffer on requestAnimationFrame (ZERO getImageData!)
- const flushPendingPoints = useCallback(() => {
- drawRafIdRef.current = null;
- if (!isDrawingRef.current) return;
-
- const pipeline = strokePipelineRef.current;
- if (pipeline.getPendingCount() === 0) {
- const predData = latestPredictedRef.current;
- latestPredictedRef.current = null;
- const vRect = getViewportRect();
- if (vRect && allStrokePointsRef.current.length > 0) {
- renderPredictedStroke(predData ? predData.predEvents : [], vRect);
- } else if (isPredictedCanvasDirtyRef.current) {
- clearPredictedCanvas();
- }
- return;
- }
-
- const draftCanvas = effectiveDraftCanvasRef?.current;
- if (!draftCanvas) return;
- const draftCtx = get2DContext(draftCanvas);
- if (!draftCtx) return;
-
- const bs = brushSettingsRef.current;
- const mode = colorModeRef.current;
- const isEraser = toolRef.current === 'eraser';
- const currentLayerId = activeLayerIdRef.current;
- const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const isVectorOrToneOrMask = activeLayer?.type === 'vector' || isToneStrokeRef.current || isMaskModeRef.current;
- const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
- const canvas = getCachedLayerCanvas();
- const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
- const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
- const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
- const strokeSpacing = bs.spacing ?? 0.08;
- const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
- const taperEngine = pipeline.getTaperEngine();
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const blurMargin = (1 - strokeHardness) * ((bs.size || 10) * 1.5);
- const dirtyPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + blurMargin + 24);
-
- // Check GPU instanced dab batch eligibility for this frame
- const draftScale = (draftCanvas as any).__draftScale ?? 1.0;
- const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
- const liveTipOpts = bs.customTipImage
- ? buildLiveTexturedOptions(bs, isMonochrome ? 1.0 : (bs.flow ?? 1.0), strokeSpacing, strokeHardness, downscaledBinary ? false : isMonochrome, canvas, activeLayer, isEraser, isBgEraser, true)
- : null;
- if (liveTipOpts && downscaledBinary && liveTipOpts.antiAlias === 0) {
- liveTipOpts.antiAlias = 2;
- }
- const liveRadialOpts = !bs.customTipImage && !isPencil
- ? buildLiveRadialOptions(bs, downscaledBinary ? false : isMonochrome, canvas, activeLayer, true)
- : null;
- if (liveRadialOpts && downscaledBinary && liveRadialOpts.antiAlias === 0) {
- liveRadialOpts.antiAlias = 2;
- }
- const useGpuBatch =
- !useWireframeEraser &&
- (bs.customTipImage
- ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
- : (!isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts))));
-
- const gpuBatch = frameGpuDabsRef.current;
- gpuBatch.length = 0;
-
- const collabActive = Boolean(currentStrokeIdRef.current && onCollabStrokeChunkRef.current);
- const chunkPts: Point[] | null = collabActive ? [] : null;
- let drewAnySegment = false;
-
- pipeline.drain({
- dirtyPadExtra,
- resolvePoint: (rawX, rawY, rawPressure, stabPressure, pointerType, _vx, _vy, dtMs, out) => {
- let velocityScale = 1.0;
- if (bs.velocityDynamics && stabilizedPointRef.current) {
- const dist = Math.hypot(rawX - stabilizedPointRef.current.x, rawY - stabilizedPointRef.current.y);
- const speed = dist / Math.max(1, dtMs);
- velocityScale = Math.max(0.65, Math.min(1.0, 1.0 - Math.max(0, speed - 0.5) * 0.12));
- }
-
- const baseP = bs.usePressure
- ? (hasCustomCurve ? stabPressure : taperEngine.mapPressure(stabPressure))
- : (rawPressure > 0 ? 1.0 : 0);
- const mappedP = bs.usePressure ? taperEngine.smoothPressure(baseP) : baseP;
- let width = calculateStrokeWidth(
- bs.size,
- mappedP,
- bs.minSizeFactor,
- bs.usePressure,
- pointerType,
- bs.pressureCurveGamma ?? 1.0,
- velocityScale,
- bs.pressureCurve
- );
- if (isMonochrome && width < 1.25) {
- width = 1.25;
- }
- out.pressure = mappedP;
- out.width = width;
- },
- onPoint: (sample) => {
- const pt: Point = {
- x: sample.x,
- y: sample.y,
- pressure: sample.pressure,
- width: sample.width,
- tiltX: sample.tiltX,
- tiltY: sample.tiltY,
- twist: sample.twist,
- timestamp: sample.timestamp,
- isCorner: sample.isCorner,
- };
- if (allStrokePointsRef.current.length > 0) {
- const prev = allStrokePointsRef.current[allStrokePointsRef.current.length - 1];
- strokeTotalDistanceRef.current += Math.hypot(pt.x - prev.x, pt.y - prev.y);
- }
- stabilizedPointRef.current = pt;
- lastPointTimeRef.current = sample.timestamp;
- allStrokePointsRef.current.push(pt);
- recentPointsTrailRef.current.push({
- x: pt.x,
- y: pt.y,
- t: sample.timestamp || performance.now(),
- pressure: pt.pressure,
- width: pt.width,
- });
- if (recentPointsTrailRef.current.length > 16) {
- recentPointsTrailRef.current.shift();
- }
- if (chunkPts) {
- chunkPts.push(pt);
- }
- },
- onSegment: (seg) => {
- drewAnySegment = true;
- emitLiveSegment(
- draftCtx,
- seg,
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isPencil,
- isEraser,
- isBgEraser,
- useWireframeEraser,
- canvas,
- activeLayer,
- useGpuBatch ? gpuBatch : undefined
- );
- },
- });
-
- // Flush the entire frame's GPU dab batch in a single WebGlBrushEngine FBO instanced draw call
- if (useGpuBatch && gpuBatch.length > 0) {
- const liveColor = (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- let flushed = false;
- if (bs.customTipImage && liveTipOpts) {
- flushed = flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, liveTipOpts);
- } else if (liveRadialOpts) {
- flushed = flushRadialGpuDabs(draftCtx, gpuBatch, liveColor, strokeHardness, false, false, liveRadialOpts);
- }
- if (!flushed) {
- // Rare context-lost fallback: draw recent points onto draftCtx via Canvas 2D
- const pts = allStrokePointsRef.current;
- if (pts.length >= 2) {
- const pA = pts[pts.length - 2];
- const pB = pts[pts.length - 1];
- const fallbackSeg = pipeline.getSplineGenerator().generateCornerSegment(pA, pB);
- emitLiveSegment(
- draftCtx,
- fallbackSeg,
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isPencil,
- isEraser,
- isBgEraser,
- useWireframeEraser,
- canvas,
- activeLayer,
- undefined
- );
- }
- }
- gpuBatch.length = 0;
- }
-
- // Mirror StrokePipeline dirtyRect bounds
- const pDirty = pipeline.dirtyRect;
- if (Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX)) {
- const dims = dimensionsRef.current;
- if (!dirtyRectRef.current) {
- dirtyRectRef.current = {
- minX: Math.max(0, pDirty.minX),
- minY: Math.max(0, pDirty.minY),
- maxX: Math.min(dims.width, pDirty.maxX),
- maxY: Math.min(dims.height, pDirty.maxY),
- };
- } else {
- dirtyRectRef.current.minX = Math.max(0, Math.min(dirtyRectRef.current.minX, pDirty.minX));
- dirtyRectRef.current.minY = Math.max(0, Math.min(dirtyRectRef.current.minY, pDirty.minY));
- dirtyRectRef.current.maxX = Math.min(dims.width, Math.max(dirtyRectRef.current.maxX, pDirty.maxX));
- dirtyRectRef.current.maxY = Math.min(dims.height, Math.max(dirtyRectRef.current.maxY, pDirty.maxY));
- }
- }
-
- if (drewAnySegment) {
- (draftCanvas as any).__draftHasContent = true;
- (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
- liveNeedsNotifyRef.current = true;
- }
-
- if (currentStrokeIdRef.current && chunkPts && chunkPts.length > 0) {
- onCollabStrokeChunkRef.current?.(currentStrokeIdRef.current, chunkPts);
- }
-
- if (liveNeedsNotifyRef.current) {
- liveNeedsNotifyRef.current = false;
- activeTileGridRef.current.notifyChange();
- }
+ const history = useDrawingHistory({
+ activeSessionId,
+ tileGrid,
+ activeLayerId,
+ activeLayerLocked,
+ dimensions,
+ dimensionsRef,
+ activeLayerIdRef,
+ colorModeRef,
+ layersRef,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ onUpdateLayerThumbnail,
+ onUpdateMaskThumbnailRef,
+ isDrawingRef,
+ lastStrokeEndRef,
+ abortActiveStrokeRef,
+ });
- // Update ephemeral predicted stroke overlay throttled to rAF
- const predData = latestPredictedRef.current;
- latestPredictedRef.current = null;
- const vRect = getViewportRect();
- if (vRect && allStrokePointsRef.current.length > 0) {
- renderPredictedStroke(predData ? predData.predEvents : [], vRect);
- } else if (isPredictedCanvasDirtyRef.current) {
- clearPredictedCanvas();
- }
- }, [
- buildLiveRadialOptions,
- buildLiveTexturedOptions,
- clearPredictedCanvas,
+ const brushSession = useBrushStrokeSession({
+ disabled,
+ activeSessionId,
+ viewportRef,
+ interactionRef,
+ isDrawingRef,
+ lastStrokeEndRef,
+ panRef,
+ zoomRef,
+ rotationRef,
+ flipXRef,
+ flipYRef,
+ toolOverrideRef,
+ brushSettingsOverrideRef,
+ colorModeRef,
+ activeLayerIdRef,
+ activeLayerLockedRef,
+ activeLayerVisibleRef,
+ dimensionsRef,
+ selectionRef,
+ isMaskModeRef,
+ layersRef,
+ layerSourceCanvasesRef,
effectiveDraftCanvasRef,
- emitLiveSegment,
+ predictedCanvasRef,
+ activeTileGridRef: history.activeTileGridRef,
+ rulerRef,
+ onActiveConstraintAxisChangeRef,
+ onUpdateLayerThumbnail,
+ onUpdateMaskThumbnailRef,
+ onCollabStrokeStartRef,
+ onCollabStrokeChunkRef,
+ onCollabStrokeFinishRef,
+ onCollabCursorMoveRef,
getCachedLayerCanvas,
- getViewportRect,
- renderPredictedStroke,
- resolveStrokeColor,
- ]);
-
- // Pointer Down handler: initialize lightweight draft surface & StrokePipeline without touching base canvas or getImageData
- const handlePointerDown = useCallback(
- (e: React.PointerEvent<HTMLElement>, _coalescedEvents?: PointerEvent[]) => {
- const isBrushOrEraser = toolRef.current === 'brush' || toolRef.current === 'eraser';
- if (!isBrushOrEraser || disabled || e.button !== 0 || activeLayerLockedRef.current || !activeLayerVisibleRef.current) return;
- e.preventDefault();
- if (isDrawingRef.current) {
- abortActiveStroke();
- }
- flushPendingHistoryTasks();
-
- const dims = dimensionsRef.current;
- const currentLayerIdCheck = activeLayerIdRef.current;
- if (!currentLayerIdCheck || dims.width <= 0 || dims.height <= 0) return;
-
- const canvas = getCachedLayerCanvas();
- if (isMaskModeRef.current && !canvas) return;
-
- if (viewportRef.current) {
- cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
- }
- const vRect = getViewportRect();
- if (!vRect) return;
-
- const draftCanvas = effectiveDraftCanvasRef?.current;
- if (!draftCanvas) return;
-
- if (clearDraftRafRef.current !== null) {
- cancelAnimationFrame(clearDraftRafRef.current);
- clearDraftRafRef.current = null;
- }
-
- const draftCtx = get2DContext(draftCanvas);
- if (!draftCtx) return;
-
- const isEraser = toolRef.current === 'eraser';
- const currentLayerId = activeLayerIdRef.current;
- const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
- const allLayers = layersRef.current || [];
- const activeLayer = allLayers.find((l) => l.id === currentLayerId);
- const bs = brushSettingsRef.current;
- const mode = colorModeRef.current;
- const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const isTone = Boolean(activeLayer?.toneEnabled);
- const isVectorLayer = activeLayer?.type === 'vector';
- const isVectorOrToneOrMask = isVectorLayer || isTone || isMaskModeRef.current;
- const useWireframeEraser = isVectorOrToneOrMask && isEraser && !isBgEraser;
- isToneStrokeRef.current = isTone;
-
- // Configure GPU in-stack draft composite mode for ViewportCompositor (zero getImageData!)
- const draftCompositeOp: GlobalCompositeOperation =
- isVectorOrToneOrMask || isBgEraser
- ? 'source-over'
- : isEraser || bs.isTransparentInk
- ? 'destination-out'
- : activeLayer?.alphaLocked
- ? 'source-atop'
- : 'source-over';
-
- // Size draftCanvas in document space covering the visible document region (1:1 document pixels up to 2048px)
- // Guarantees 100% live-vs-baked parity at any zoom level with zero getImageData!
- const rawVis = getVisibleCanvasBounds(
- vRect,
- panRef.current,
- zoomRef.current,
- rotationRef.current,
- dims,
- 128,
- flipXRef.current,
- flipYRef.current
- );
- const visMinX = rawVis.maxX > rawVis.minX ? rawVis.minX : 0;
- const visMinY = rawVis.maxY > rawVis.minY ? rawVis.minY : 0;
- const visW = Math.max(1, rawVis.maxX > rawVis.minX ? rawVis.maxX - rawVis.minX : dims.width);
- const visH = Math.max(1, rawVis.maxY > rawVis.minY ? rawVis.maxY - rawVis.minY : dims.height);
- const MAX_DRAFT_DIM = 2048;
- const draftScale = Math.min(1.0, MAX_DRAFT_DIM / Math.max(visW, visH));
- const surfaceW = Math.max(1, Math.ceil(visW * draftScale));
- const surfaceH = Math.max(1, Math.ceil(visH * draftScale));
- if (draftCanvas.width !== surfaceW || draftCanvas.height !== surfaceH) {
- draftCanvas.width = surfaceW;
- draftCanvas.height = surfaceH;
- }
-
- draftCtx.resetTransform();
- draftCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
- (draftCanvas as any).__draftHasContent = false;
- (draftCanvas as any).__draftCompositeOp = draftCompositeOp;
- (draftCanvas as any).__draftSpace = 'document';
- (draftCanvas as any).__draftDocRect = {
- x: visMinX,
- y: visMinY,
- width: surfaceW / draftScale,
- height: surfaceH / draftScale,
- };
- (draftCanvas as any).__draftScale = draftScale;
- (draftCanvas as any).__draftMonochrome = isMonochrome;
- (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
-
- draftCtx.setTransform(draftScale, 0, 0, draftScale, -visMinX * draftScale, -visMinY * draftScale);
- draftCtx.save();
- draftCtx.beginPath();
- draftCtx.rect(0, 0, dims.width, dims.height);
- draftCtx.clip();
- applySelectionCanvasClip(draftCtx, selectionRef.current);
-
- clearPredictedCanvas();
-
- if (isTone) {
- let sourceCanvas = layerSourceCanvasesRef?.current?.get(currentLayerId) || null;
- if (!sourceCanvas) {
- sourceCanvas = document.createElement('canvas');
- sourceCanvas.width = dims.width;
- sourceCanvas.height = dims.height;
- if (canvas) {
- const sCtx = get2DContext(sourceCanvas);
- sCtx?.drawImage(canvas, 0, 0);
- } else {
- activeTileGridRef.current.renderLayerToCanvas(currentLayerId, sourceCanvas);
- }
- layerSourceCanvasesRef?.current?.set(currentLayerId, sourceCanvas);
- }
- }
-
- if (interactionRef.current) {
- try {
- interactionRef.current.setPointerCapture(e.pointerId);
- } catch {}
- }
- activePointerIdRef.current = e.pointerId;
- isDrawingRef.current = true;
-
- // Always anchor pointerdown strictly to e.nativeEvent so the stroke begins at the
- // exact center of the brush cursor ring even if Windows/WebView2 stylus drivers emit
- // stale or DPI-offset coalesced packets on pointerdown.
- const firstEvent = e.nativeEvent;
- const rawStartPoint = getCanvasPoint(firstEvent);
- const isAltOverride = e.altKey;
- const startPoint = snapSessionRef.current.snapPoint(rawStartPoint, rulerRef.current, isAltOverride);
- emitConstraintAxisChange(snapSessionRef.current.getActiveAxis());
-
- const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
- const strokeHardness = isMonochrome ? 1.0 : (bs.hardness ?? 1.0);
- const strokeFlow = isMonochrome ? 1.0 : (bs.flow ?? 1.0);
- const strokeSpacing = bs.spacing ?? 0.08;
-
- const pipeline = strokePipelineRef.current;
- pipeline.beginStroke({
- stabilizerLevel: bs.stabilization ?? 0,
- zoom: zoomRef.current || 1.0,
- sharpCorners: bs.sharpCorners !== false,
- brushSize: bs.size,
- color: strokeColor,
- pointerId: e.pointerId,
- });
-
- const startNow = startPoint.timestamp ?? performance.now();
- lastPointTimeRef.current = startNow;
- const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
- const taperEngine = pipeline.getTaperEngine();
- if (bs.usePressure) {
- const baseStartP = hasCustomCurve ? startPoint.pressure : taperEngine.mapPressure(startPoint.pressure);
- const smoothStartP = taperEngine.smoothPressure(baseStartP);
- startPoint.pressure = smoothStartP;
- startPoint.width = calculateStrokeWidth(
- bs.size,
- smoothStartP,
- bs.minSizeFactor,
- bs.usePressure,
- firstEvent.pointerType,
- bs.pressureCurveGamma ?? 1.0,
- 1.0,
- bs.pressureCurve
- );
- }
- if (isMonochrome && startPoint.width < 1.25) {
- startPoint.width = 1.25;
- }
-
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const blurMargin = (1 - strokeHardness) * (startPoint.width * 1.5);
- const r = Math.max(
- 32,
- Math.ceil(Math.max(startPoint.width, bs.size || 10) * (2.8 + scatterFactor * 2) + blurMargin + 32)
- );
-
- // CSP Shift + Click Straight Line from previous stroke end on the same layer
- const prevStrokeEnd = lastStrokeEndRef.current;
- const isShiftLine =
- Boolean(e.shiftKey) &&
- !isMaskModeRef.current &&
- prevStrokeEnd !== null &&
- prevStrokeEnd.layerId === currentLayerId;
- isShiftLineStrokeRef.current = isShiftLine;
-
- if (isShiftLine && prevStrokeEnd) {
- const pLineStart: Point = {
- x: prevStrokeEnd.x,
- y: prevStrokeEnd.y,
- pressure: startPoint.pressure,
- width: startPoint.width,
- tiltX: startPoint.tiltX,
- tiltY: startPoint.tiltY,
- twist: startPoint.twist,
- timestamp: startNow - 16,
- };
- const pLineMid: Point = {
- x: (pLineStart.x + startPoint.x) * 0.5,
- y: (pLineStart.y + startPoint.y) * 0.5,
- pressure: startPoint.pressure,
- width: startPoint.width,
- tiltX: startPoint.tiltX,
- tiltY: startPoint.tiltY,
- twist: startPoint.twist,
- timestamp: startNow - 8,
- };
- allStrokePointsRef.current = [pLineStart, pLineMid, startPoint];
- pipeline.seedKnot(pLineStart.x, pLineStart.y, pLineStart.pressure, pLineStart.width, pLineStart.tiltX ?? 0, pLineStart.tiltY ?? 0, pLineStart.twist ?? 0, pLineStart.timestamp ?? 0, r);
- pipeline.seedKnot(pLineMid.x, pLineMid.y, pLineMid.pressure, pLineMid.width, pLineMid.tiltX ?? 0, pLineMid.tiltY ?? 0, pLineMid.twist ?? 0, pLineMid.timestamp ?? 0, r);
- } else {
- allStrokePointsRef.current = [startPoint];
- pipeline.seedKnot(startPoint.x, startPoint.y, startPoint.pressure, startPoint.width, startPoint.tiltX ?? 0, startPoint.tiltY ?? 0, startPoint.twist ?? 0, startNow, r);
- }
-
- stabilizedPointRef.current = { ...startPoint };
- lastProcessedPointRef.current.x = startPoint.x;
- lastProcessedPointRef.current.y = startPoint.y;
- hasLastProcessedPointRef.current = true;
- lastQueuedPressureRef.current = startPoint.pressure;
- recentPointsTrailRef.current = [{
- x: startPoint.x,
- y: startPoint.y,
- t: startNow,
- pressure: startPoint.pressure,
- width: startPoint.width,
- }];
- strokeTotalDistanceRef.current = isShiftLine && prevStrokeEnd
- ? Math.hypot(startPoint.x - prevStrokeEnd.x, startPoint.y - prevStrokeEnd.y)
- : 0;
-
- dispatchPointerStat(startPoint.x, startPoint.y, startPoint.pressure);
-
- const minInitX = isShiftLine && prevStrokeEnd ? Math.min(startPoint.x, prevStrokeEnd.x) : startPoint.x;
- const minInitY = isShiftLine && prevStrokeEnd ? Math.min(startPoint.y, prevStrokeEnd.y) : startPoint.y;
- const maxInitX = isShiftLine && prevStrokeEnd ? Math.max(startPoint.x, prevStrokeEnd.x) : startPoint.x;
- const maxInitY = isShiftLine && prevStrokeEnd ? Math.max(startPoint.y, prevStrokeEnd.y) : startPoint.y;
- dirtyRectRef.current = {
- minX: Math.max(0, Math.floor(minInitX - r)),
- minY: Math.max(0, Math.floor(minInitY - r)),
- maxX: Math.min(dims.width, Math.ceil(maxInitX + r)),
- maxY: Math.min(dims.height, Math.ceil(maxInitY + r)),
- };
- pipeline.expandDirtyRectBounds(
- dirtyRectRef.current.minX,
- dirtyRectRef.current.minY,
- dirtyRectRef.current.maxX,
- dirtyRectRef.current.maxY
- );
- touchedTilesRef.current.clear();
- markTouchedTiles(
- dirtyRectRef.current.minX,
- dirtyRectRef.current.minY,
- dirtyRectRef.current.maxX,
- dirtyRectRef.current.maxY
- );
-
- const isWetColor = !isEraser && Boolean(bs.colorMixing);
- isWetColorStrokeRef.current = isWetColor;
- liveNeedsNotifyRef.current = false;
-
- if (isWetColor) {
- layerPixelSamplerRef.current = new LayerPixelSampler(
- canvas || dims,
- currentLayerId,
- activeTileGridRef.current
- );
- activeReservoirRef.current = new PaintReservoir(strokeColor);
- } else {
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
- }
-
- const strokeId = `stroke-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`;
- currentStrokeIdRef.current = strokeId;
- onCollabStrokeStartRef.current?.(strokeId, currentLayerId, bs, toolRef.current, startPoint);
-
- liveDabCounterRef.current.count = 0;
- stampRemainderDistRef.current = bs.customTipImage
- ? Math.max(0.15, startPoint.width * (bs.spacing ?? 0.07))
- : isPencil
- ? Math.max(0.25, startPoint.width * (bs.spacing ?? 0.07))
- : Math.max(0.12, startPoint.width * (bs.spacing ?? 0.08));
-
- const firstDotPoint = allStrokePointsRef.current[0];
-
- // Draw initial dot strictly onto draftCanvas (GPU instanced batch or Canvas 2D fallback) — ZERO getImageData!
- if (useWireframeEraser) {
- draftCtx.save();
- draftCtx.strokeStyle = 'rgba(255, 80, 80, 0.75)';
- draftCtx.setLineDash([3, 3]);
- draftCtx.lineWidth = Math.max(1, 1.5 / Math.max(0.05, zoomRef.current));
- draftCtx.beginPath();
- draftCtx.arc(firstDotPoint.x, firstDotPoint.y, Math.max(1, firstDotPoint.width / 2), 0, Math.PI * 2);
- draftCtx.stroke();
- draftCtx.restore();
- } else {
- const liveColor = (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
- const gpuBatch = frameGpuDabsRef.current;
- gpuBatch.length = 0;
-
- if (bs.customTipImage) {
- const tipOptions = buildLiveTexturedOptions(
- bs,
- isMonochrome ? 1.0 : (bs.flow ?? 1.0),
- strokeSpacing,
- strokeHardness,
- downscaledBinary ? false : isMonochrome,
- canvas,
- activeLayer,
- isEraser,
- isBgEraser,
- true
- );
- if (downscaledBinary && tipOptions.antiAlias === 0) {
- tipOptions.antiAlias = 2;
- }
- const useGpu = canUseWebGlForTexturedBrush(tipOptions);
- drawTexturedDot(draftCtx, firstDotPoint, liveColor, bs.customTipImage, tipOptions, useGpu ? gpuBatch : undefined);
- if (useGpu && gpuBatch.length > 0) {
- if (!flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, tipOptions)) {
- drawTexturedDot(draftCtx, firstDotPoint, liveColor, bs.customTipImage, tipOptions);
- }
- gpuBatch.length = 0;
- }
- } else if (isPencil) {
- const grade = (bs.preset as PencilGrade) || 'pencil-2b';
- drawPencilDot(
- draftCtx,
- firstDotPoint,
- liveColor,
- grade,
- isMonochrome ? 1.0 : (bs.flow ?? 0.74),
- bs.grain ?? 1.0,
- strokeHardness,
- false,
- false
- );
- } else {
- const radialMixingOptions = buildLiveRadialOptions(bs, downscaledBinary ? false : isMonochrome, canvas, activeLayer, true);
- if (downscaledBinary && radialMixingOptions.antiAlias === 0) {
- radialMixingOptions.antiAlias = 2;
- }
- const useGpu = canUseWebGlForRadialBrush(radialMixingOptions);
- drawDot(
- draftCtx,
- firstDotPoint,
- liveColor,
- false,
- strokeHardness,
- strokeFlow,
- radialMixingOptions,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180,
- useGpu ? gpuBatch : undefined
- );
- if (useGpu && gpuBatch.length > 0) {
- if (!flushRadialGpuDabs(draftCtx, gpuBatch, liveColor, strokeHardness, false, false, radialMixingOptions)) {
- drawDot(
- draftCtx,
- firstDotPoint,
- liveColor,
- false,
- strokeHardness,
- strokeFlow,
- radialMixingOptions,
- bs.thickness ?? 1.0,
- ((bs.customTipAngle ?? 0) * Math.PI) / 180
- );
- }
- gpuBatch.length = 0;
- }
- }
- }
-
- if (isShiftLine && prevStrokeEnd) {
- const lineSeg = pipeline.getSplineGenerator().generateCornerSegment(allStrokePointsRef.current[0], startPoint);
- const downscaledBinary = (isMonochrome || bs.antiAlias === 0) && draftScale < 0.999;
- const liveTipOpts = bs.customTipImage
- ? buildLiveTexturedOptions(bs, isMonochrome ? 1.0 : (bs.flow ?? 1.0), strokeSpacing, strokeHardness, downscaledBinary ? false : isMonochrome, canvas, activeLayer, isEraser, isBgEraser, true)
- : null;
- if (liveTipOpts && downscaledBinary && liveTipOpts.antiAlias === 0) {
- liveTipOpts.antiAlias = 2;
- }
- const liveRadialOpts = !bs.customTipImage && !isPencil
- ? buildLiveRadialOptions(bs, downscaledBinary ? false : isMonochrome, canvas, activeLayer, true)
- : null;
- if (liveRadialOpts && downscaledBinary && liveRadialOpts.antiAlias === 0) {
- liveRadialOpts.antiAlias = 2;
- }
- const useGpuLine =
- !useWireframeEraser &&
- (bs.customTipImage
- ? Boolean(liveTipOpts && canUseWebGlForTexturedBrush(liveTipOpts))
- : (!isPencil && Boolean(liveRadialOpts && canUseWebGlForRadialBrush(liveRadialOpts))));
- const gpuBatch = frameGpuDabsRef.current;
- gpuBatch.length = 0;
- emitLiveSegment(
- draftCtx,
- lineSeg,
- bs,
- strokeColor,
- strokeHardness,
- strokeFlow,
- strokeSpacing,
- isMonochrome,
- isPencil,
- isEraser,
- isBgEraser,
- useWireframeEraser,
- canvas,
- activeLayer,
- useGpuLine ? gpuBatch : undefined
- );
- if (useGpuLine && gpuBatch.length > 0) {
- const liveColor = (isEraser && !isBgEraser) || bs.isTransparentInk ? '#000000' : strokeColor;
- if (bs.customTipImage && liveTipOpts) {
- flushTexturedGpuDabs(draftCtx, gpuBatch, bs.customTipImage, liveColor, liveTipOpts);
- } else if (liveRadialOpts) {
- flushRadialGpuDabs(draftCtx, gpuBatch, liveColor, strokeHardness, false, false, liveRadialOpts);
- }
- gpuBatch.length = 0;
- }
- pipeline.seedKnot(startPoint.x, startPoint.y, startPoint.pressure, startPoint.width, startPoint.tiltX ?? 0, startPoint.tiltY ?? 0, startPoint.twist ?? 0, startNow, r);
- }
-
- (draftCanvas as any).__draftHasContent = true;
- (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
- activeTileGridRef.current.notifyChange();
- liveNeedsNotifyRef.current = false;
-
- if (pipeline.getPendingCount() > 0 && drawRafIdRef.current === null) {
- drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
- }
- },
- [
- abortActiveStroke,
- buildLiveRadialOptions,
- buildLiveTexturedOptions,
- clearPredictedCanvas,
- disabled,
- dispatchPointerStat,
- effectiveDraftCanvasRef,
- emitConstraintAxisChange,
- emitLiveSegment,
- flushPendingHistoryTasks,
- flushPendingPoints,
- getCachedLayerCanvas,
- getCanvasPoint,
- getViewportRect,
- layerSourceCanvasesRef,
- markTouchedTiles,
- resolveStrokeColor,
- viewportRef,
- ]
- );
-
- // Pointer Move handler: zero-allocation ingestion of getCoalescedEvents() & getPredictedEvents() into StrokePipeline ring buffer
- const handlePointerMove = useCallback(
- (
- e: React.PointerEvent<HTMLElement>,
- coalescedEvents?: PointerEvent[],
- predictedEvents?: PointerEvent[]
- ) => {
- if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
- const point = getCanvasPoint(e);
- dispatchPointerStat(point.x, point.y, point.pressure);
- onCollabCursorMoveRef.current?.(point.x, point.y, false, toolRef.current);
- return;
- }
-
- e.preventDefault();
-
- const vRect = getViewportRect();
- if (!vRect) return;
- const dims = dimensionsRef.current;
-
- const candidateCoalesced: PointerEvent[] | readonly PointerEvent[] | null =
- coalescedEvents ??
- (e as any).coalescedEvents ??
- (typeof e.nativeEvent?.getCoalescedEvents === 'function' ? e.nativeEvent.getCoalescedEvents() : null);
- let rawCoalesced: PointerEvent[] | readonly PointerEvent[] | null = null;
- if (candidateCoalesced && candidateCoalesced.length > 0) {
- const lastC = candidateCoalesced[candidateCoalesced.length - 1];
- const nativeEvt = e.nativeEvent;
- if (
- lastC &&
- nativeEvt &&
- Number.isFinite(lastC.clientX) &&
- Number.isFinite(lastC.clientY) &&
- Math.hypot(lastC.clientX - nativeEvt.clientX, lastC.clientY - nativeEvt.clientY) <= 1.5
- ) {
- rawCoalesced = candidateCoalesced;
- }
- }
- const count = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced.length : 1;
-
- const pipeline = strokePipelineRef.current;
- const scratch = scratchDocCoordRef.current;
- const lastProc = lastProcessedPointRef.current;
- const minStepDoc = Math.min(0.25, 0.25 / Math.max(0.05, zoomRef.current));
- const isAltOverride = e.altKey;
- const isShiftKey = e.shiftKey;
- const ruler = rulerRef.current;
- const curPan = panRef.current;
- const curZoom = zoomRef.current;
- const curRot = rotationRef.current;
- const curFlipX = flipXRef.current;
- const curFlipY = flipYRef.current;
-
- let lastQueuedX = 0;
- let lastQueuedY = 0;
- let lastQueuedPressure = lastQueuedPressureRef.current;
- let hasQueued = false;
-
- for (let i = 0; i < count; i++) {
- const cEvent = rawCoalesced && rawCoalesced.length > 0 ? rawCoalesced[i] : e.nativeEvent;
- screenToCanvasInto(
- cEvent.clientX,
- cEvent.clientY,
- vRect,
- curPan,
- curZoom,
- curRot,
- dims,
- scratch,
- curFlipX,
- curFlipY
- );
-
- const snapRes = snapSessionRef.current.processPoint(scratch, ruler, isAltOverride);
- let cx = snapRes.x;
- let cy = snapRes.y;
- if (snapRes.axis) {
- emitConstraintAxisChange(snapRes.axis);
- } else if (
- !isShiftLineStrokeRef.current &&
- isShiftKey &&
- !ruler?.enabled &&
- allStrokePointsRef.current.length > 0
- ) {
- const originPt = allStrokePointsRef.current[0];
- const dx = cx - originPt.x;
- const dy = cy - originPt.y;
- const dist = Math.hypot(dx, dy);
- if (dist > 0.5) {
- const snapAngle = Math.round(Math.atan2(dy, dx) / (Math.PI / 4)) * (Math.PI / 4);
- cx = originPt.x + Math.cos(snapAngle) * dist;
- cy = originPt.y + Math.sin(snapAngle) * dist;
- }
- }
-
- let cPressure = 0;
- if (cEvent.pointerType === 'mouse') {
- cPressure = (cEvent.buttons & 1) ? 0.5 : 0;
- } else {
- cPressure = cEvent.pressure !== undefined ? Math.max(0, Math.min(1.0, cEvent.pressure)) : 0;
- }
-
- if (
- hasLastProcessedPointRef.current &&
- Math.hypot(cx - lastProc.x, cy - lastProc.y) < minStepDoc &&
- Math.abs(cPressure - lastQueuedPressure) <= 0.04
- ) {
- continue;
- }
-
- lastProc.x = cx;
- lastProc.y = cy;
- hasLastProcessedPointRef.current = true;
-
- pipeline.enqueueSample(
- cx,
- cy,
- cPressure,
- cEvent.tiltX ?? 0,
- cEvent.tiltY ?? 0,
- cEvent.twist ?? 0,
- cEvent.timeStamp,
- encodePointerType(cEvent.pointerType)
- );
- lastQueuedX = cx;
- lastQueuedY = cy;
- lastQueuedPressure = cPressure;
- hasQueued = true;
- }
-
- lastQueuedPressureRef.current = lastQueuedPressure;
-
- const rawPredicted =
- predictedEvents ??
- (e as any).predictedEvents ??
- (typeof e.nativeEvent?.getPredictedEvents === 'function' ? e.nativeEvent.getPredictedEvents() : null);
-
- if (rawPredicted && rawPredicted.length > 0) {
- latestPredictedRef.current = { predEvents: rawPredicted, vRect };
- } else {
- latestPredictedRef.current = null;
- }
-
- if (hasQueued) {
- dispatchPointerStat(lastQueuedX, lastQueuedY, lastQueuedPressure);
- onCollabCursorMoveRef.current?.(lastQueuedX, lastQueuedY, true, toolRef.current);
- }
-
- if ((pipeline.getPendingCount() > 0 || latestPredictedRef.current !== null) && drawRafIdRef.current === null) {
- drawRafIdRef.current = requestAnimationFrame(flushPendingPoints);
- }
- },
- [dispatchPointerStat, emitConstraintAxisChange, flushPendingPoints, getCanvasPoint, getViewportRect]
- );
-
- // Pointer Up / Cancel handler: finalize StrokePipeline, bake dirty rect ONCE into base layer + SparseTileGrid + Undo delta
- const handlePointerUp = useCallback(
- (e: React.PointerEvent<HTMLElement>) => {
- if (!isDrawingRef.current || e.pointerId !== activePointerIdRef.current) {
- return;
- }
-
- e.preventDefault();
- clearPredictedCanvas();
-
- if (interactionRef.current && interactionRef.current.hasPointerCapture(e.pointerId)) {
- try {
- interactionRef.current.releasePointerCapture(e.pointerId);
- } catch {}
- }
-
- // Cancel any pending rAF and flush remaining buffered points synchronously
- if (drawRafIdRef.current !== null) {
- cancelAnimationFrame(drawRafIdRef.current);
- drawRafIdRef.current = null;
- }
- flushPendingPoints();
-
- const bs = brushSettingsRef.current;
- const dims = dimensionsRef.current;
- const grid = activeTileGridRef.current;
- const endPoint = getCanvasPoint(e);
- const draftCanvas = effectiveDraftCanvasRef?.current;
- const canvas = getCachedLayerCanvas();
- if (canvas) {
- (canvas as any).__isBlank = false;
- (canvas as any).__isSolidWhite = false;
- }
-
- const currentTool = toolRef.current;
- const currentLayerId = activeLayerIdRef.current;
- const isEraser = currentTool === 'eraser';
- const isBgEraser = isEraser && isBackgroundLayerId(currentLayerId);
- const mode = colorModeRef.current;
- const isPencil = !isEraser && !bs.customTipImage && (bs.preset?.startsWith('pencil') ?? false);
-
- const isTone = isToneStrokeRef.current;
- const activeLayer = layersRef.current?.find((l) => l.id === currentLayerId);
- const isToneLayer = Boolean(activeLayer?.toneEnabled);
- const isMonoLayer = activeLayer?.expressionColor === 'monochrome';
- const isMonochrome = mode === 'monochrome' || isMonoLayer;
- const sourceCanvas = isTone ? layerSourceCanvasesRef?.current?.get(currentLayerId) : null;
- const strokeColor = resolveStrokeColor(bs, isEraser, isBgEraser, isMonochrome, mode);
-
- const pipeline = strokePipelineRef.current;
- const scatterFactor = Math.max(0, bs.dynamics?.scatter ?? 0);
- const tailPadExtra = Math.ceil((bs.size || 10) * (1.8 + scatterFactor * 2) + 24);
- const enableFlickTaper =
- !isEraser &&
- !isShiftLineStrokeRef.current &&
- activeLayer?.type !== 'vector' &&
- Boolean(bs.taper?.useOut);
-
- // Seal final Catmull-Rom segment & optional ballistic exit flick taper in StrokePipeline
- let addedFlickPoints = false;
- pipeline.finalizeStroke(e.timeStamp || performance.now(), {
- enableFlickTaper,
- dirtyPadExtra: tailPadExtra,
- onPoint: (sample) => {
- addedFlickPoints = true;
- allStrokePointsRef.current.push({
- x: sample.x,
- y: sample.y,
- pressure: sample.pressure,
- width: sample.width,
- tiltX: sample.tiltX,
- tiltY: sample.tiltY,
- twist: sample.twist,
- timestamp: sample.timestamp,
- isCorner: sample.isCorner,
- });
- },
- onSegment: (seg) => {
- const segPad = Math.ceil(Math.max(seg.p0.width, seg.p3.width, bs.size || 10) * (2.8 + scatterFactor * 2) + 32);
- const tMinX = Math.min(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) - segPad;
- const tMinY = Math.min(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) - segPad;
- const tMaxX = Math.max(seg.p0.x, seg.c1.x, seg.c2.x, seg.p3.x) + segPad;
- const tMaxY = Math.max(seg.p0.y, seg.c1.y, seg.c2.y, seg.p3.y) + segPad;
- pipeline.expandDirtyRectBounds(tMinX, tMinY, tMaxX, tMaxY);
- markTouchedTiles(tMinX, tMinY, tMaxX, tMaxY);
- },
- });
-
- // Merge pipeline dirtyRect with dirtyRectRef
- const pDirty = pipeline.dirtyRect;
- const mergedDirty = dirtyRectRef.current
- ? {
- minX: Math.min(dirtyRectRef.current.minX, Number.isFinite(pDirty.minX) ? pDirty.minX : dirtyRectRef.current.minX),
- minY: Math.min(dirtyRectRef.current.minY, Number.isFinite(pDirty.minY) ? pDirty.minY : dirtyRectRef.current.minY),
- maxX: Math.max(dirtyRectRef.current.maxX, Number.isFinite(pDirty.maxX) ? pDirty.maxX : dirtyRectRef.current.maxX),
- maxY: Math.max(dirtyRectRef.current.maxY, Number.isFinite(pDirty.maxY) ? pDirty.maxY : dirtyRectRef.current.maxY),
- }
- : (Number.isFinite(pDirty.minX) && Number.isFinite(pDirty.maxX) ? { ...pDirty } : null);
-
- let exitSpeed = 0;
- if (recentPointsTrailRef.current.length >= 2) {
- const trail = recentPointsTrailRef.current;
- const sampleIdx = Math.max(0, trail.length - 4);
- const pA = trail[sampleIdx];
- const pB = trail[trail.length - 1];
- const dwellMs = Math.max(0, performance.now() - pB.t);
- const dt = Math.max(1, (pB.t - pA.t) + dwellMs);
- exitSpeed = Math.hypot(pB.x - pA.x, pB.y - pA.y) / dt;
- }
-
- const shouldTaper = Boolean(bs.taper?.useIn) || (Boolean(bs.taper?.useOut) && !addedFlickPoints);
- if (shouldTaper && allStrokePointsRef.current.length >= 3) {
- applyParametricTaper(allStrokePointsRef.current, {
- useIn: Boolean(bs.taper?.useIn),
- useOut: Boolean(bs.taper?.useOut) && !addedFlickPoints,
- minSizeFactor: bs.minSizeFactor,
- exitSpeed,
- });
- }
-
- const allPoints = allStrokePointsRef.current;
- let createdVectorStroke: VectorStroke | undefined;
-
- // Track final stroke point for Shift + Click straight line continuation
- if (allPoints.length > 0 && !isMaskModeRef.current) {
- const finalPt = allPoints[allPoints.length - 1];
- lastStrokeEndRef.current = {
- x: finalPt.x,
- y: finalPt.y,
- pressure: finalPt.pressure,
- width: finalPt.width,
- layerId: currentLayerId,
- };
- }
-
- if (activeLayer?.type === 'vector' && allPoints.length > 0 && dims.width > 0 && dims.height > 0) {
- const knots: VectorKnot[] = allPoints.map((pt, idx) => ({
- x: pt.x,
- y: pt.y,
- pressure: pt.pressure,
- width: pt.width || Math.max(0.5, (bs.size || 10) * pt.pressure),
- timestamp: Date.now() + idx,
- }));
- const prevStrokes = [...(activeLayer.vectorStrokes || [])];
-
- if (isEraser) {
- const eraserRadius = Math.max(1, (bs.size || 10) * 0.5);
- const eraserPath = allPoints.map((p) => ({ x: p.x, y: p.y }));
- const eraserResult = applyVectorEraser(eraserPath, eraserRadius, prevStrokes, 'intersection');
- const updatedStrokes = eraserResult.updatedStrokes;
- activeLayer.vectorStrokes = updatedStrokes;
-
- let minX = mergedDirty ? mergedDirty.minX : 0;
- let minY = mergedDirty ? mergedDirty.minY : 0;
- let maxX = mergedDirty ? mergedDirty.maxX : dims.width;
- let maxY = mergedDirty ? mergedDirty.maxY : dims.height;
- for (const st of prevStrokes) {
- if (st.bounds) {
- minX = Math.min(minX, st.bounds.minX);
- minY = Math.min(minY, st.bounds.minY);
- maxX = Math.max(maxX, st.bounds.maxX);
- maxY = Math.max(maxY, st.bounds.maxY);
- }
- }
- const vPad = Math.ceil(Math.max(16, (bs.size || 10)));
- const vx = Math.max(0, Math.floor(minX - vPad));
- const vy = Math.max(0, Math.floor(minY - vPad));
- const vw = Math.max(0, Math.min(dims.width, Math.ceil(maxX + vPad)) - vx);
- const vh = Math.max(0, Math.min(dims.height, Math.ceil(maxY + vPad)) - vy);
-
- if (vw > 0 && vh > 0) {
- const tempVec = document.createElement('canvas');
- tempVec.width = vw;
- tempVec.height = vh;
- const vCtx = get2DContext(tempVec);
- if (vCtx) {
- vCtx.save();
- vCtx.translate(-vx, -vy);
- renderVectorLayer(vCtx, updatedStrokes);
- vCtx.restore();
- const subData = vCtx.getImageData(0, 0, vw, vh);
- grid.writeImageData(
- currentLayerId,
- subData,
- vx,
- vy,
- isMonochrome ? 'monochrome-1bit' : 'color-32bit'
- );
- }
- releaseTemporaryCanvas(tempVec);
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, { x: vx, y: vy, width: vw, height: vh });
- }
- }
-
- pushHistoryStep(
- 'eraser',
- 'Vector Eraser',
- null,
- null,
- currentLayerId,
- vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : { x: 0, y: 0, width: dims.width, height: dims.height },
- undefined,
- { before: prevStrokes, after: updatedStrokes },
- undefined,
- currentStrokeIdRef.current || undefined
- );
- } else {
- const simplifiedKnots = simplifyPathPoints(knots, 0.5);
- const strokeKnots = simplifiedKnots.length >= 2 ? simplifiedKnots : knots;
- const bounds = computeStrokeBounds(strokeKnots);
- const newStroke: VectorStroke = {
- id: currentStrokeIdRef.current || `vec-${Date.now()}-${Math.random().toString(36).substring(2, 7)}`,
- layerId: currentLayerId,
- tool: isPencil ? 'pencil' : 'brush',
- knots: strokeKnots,
- color: strokeColor,
- baseWidth: bs.size || 10,
- opacity: bs.opacity ?? 1.0,
- bounds,
- };
- createdVectorStroke = newStroke;
-
- const updatedStrokes = [...prevStrokes, newStroke];
- activeLayer.vectorStrokes = updatedStrokes;
-
- const vPad = Math.ceil(Math.max(16, (bs.size || 10)));
- const vx = Math.max(0, Math.floor(bounds.minX - vPad));
- const vy = Math.max(0, Math.floor(bounds.minY - vPad));
- const vw = Math.max(0, Math.min(dims.width, Math.ceil(bounds.maxX + vPad)) - vx);
- const vh = Math.max(0, Math.min(dims.height, Math.ceil(bounds.maxY + vPad)) - vy);
-
- if (vw > 0 && vh > 0) {
- const tempVec = grid.createRegionCanvas(currentLayerId, { x: vx, y: vy, width: vw, height: vh });
- const vCtx = tempVec ? get2DContext(tempVec) : null;
- if (tempVec && vCtx) {
- vCtx.save();
- vCtx.translate(-vx, -vy);
- renderVectorStroke(vCtx, newStroke);
- vCtx.restore();
- const subData = vCtx.getImageData(0, 0, vw, vh);
- grid.writeImageData(
- currentLayerId,
- subData,
- vx,
- vy,
- isMonochrome ? 'monochrome-1bit' : 'color-32bit'
- );
- }
- releaseTemporaryCanvas(tempVec);
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, { x: vx, y: vy, width: vw, height: vh });
- }
- }
-
- pushHistoryStep(
- isPencil ? 'pencil' : 'brush',
- bs.brushName || (isPencil ? 'Vector Pencil' : 'Vector Pen'),
- null,
- null,
- currentLayerId,
- vw > 0 && vh > 0 ? { x: vx, y: vy, width: vw, height: vh } : { x: 0, y: 0, width: dims.width, height: dims.height },
- undefined,
- { before: prevStrokes, after: updatedStrokes },
- undefined,
- currentStrokeIdRef.current || undefined
- );
- }
- } else if (mergedDirty && allPoints.length > 0 && dims.width > 0 && dims.height > 0) {
- const hasWetEdge =
- !isMonochrome &&
- !isEraser &&
- !bs.isTransparentInk &&
- (bs.wetEdge ?? 0) > 0.01;
- const clampedBakeRect = computeClampedBakeDirtyRect(
- mergedDirty,
- dims.width,
- dims.height,
- bs.size || 10,
- hasWetEdge ? (bs.wetEdge ?? 0) : 0,
- bs.wetEdgeRadius ?? 3.0
- );
-
- if (clampedBakeRect) {
- const { x: sx, y: sy, width: dw, height: dh } = clampedBakeRect;
- let label = 'Brush Stroke';
- if (bs.isTransparentInk) {
- label = 'Transparent Ink';
- } else if (currentTool === 'eraser') {
- label = 'Eraser';
- } else if (bs.brushName) {
- label = bs.brushName;
- } else if (bs.preset === 'pencil-f') {
- label = 'Pencil (F)';
- } else if (bs.preset === 'pencil-2b') {
- label = 'Pencil (2B)';
- } else if (bs.preset === 'pencil-4b') {
- label = 'Pencil (4B)';
- } else if (bs.preset === 'pencil-hb') {
- label = 'Pencil (HB)';
- } else {
- label = isMonochrome ? 'Monochrome Pen' : 'Round Brush';
- }
-
- const dirtyRect = clampedBakeRect;
- const toolForHistory = currentTool === 'eraser' ? 'eraser' : (isPencil ? 'pencil' : 'brush');
- const targetFormat = isMonochrome ? 'monochrome-1bit' : 'color-32bit';
- const effectiveMode: CanvasColorMode = isMonochrome ? 'monochrome' : mode;
- const activeSelection = selectionRef.current;
-
- if (isMaskModeRef.current && canvas) {
- const ctx = get2DContext(canvas);
- if (ctx) {
- const beforeMaskData = ctx.getImageData(sx, sy, dw, dh);
- const maskBs: BrushSettings = {
- ...bs,
- color: strokeColor,
- isTransparentInk: false,
- colorMixing: false,
- };
- const maskTool: ToolType = isEraser ? 'brush' : currentTool;
-
- ctx.save();
- ctx.beginPath();
- ctx.rect(sx, sy, dw, dh);
- ctx.clip();
- applySelectionCanvasClip(ctx, activeSelection);
-
- if ((bs.opacity ?? 1.0) >= 0.999) {
- renderCompleteStroke(ctx, allPoints, maskBs, maskTool, 'grayscale', false, canvas, false);
- } else {
- ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- ctx.globalCompositeOperation = 'source-over';
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtx) {
- bCtx.clearRect(0, 0, dw, dh);
- bCtx.save();
- bCtx.translate(-sx, -sy);
- renderCompleteStroke(bCtx, allPoints, { ...maskBs, opacity: 1.0 }, maskTool, 'grayscale', false, canvas, false);
- bCtx.restore();
- ctx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
- ctx.restore();
-
- const afterMaskData = ctx.getImageData(sx, sy, dw, dh);
- if (activeSelection?.mask) {
- applySelectionMaskToImageData(beforeMaskData, afterMaskData, sx, sy, activeSelection);
- ctx.putImageData(afterMaskData, sx, sy);
- }
- if (activeLayer) {
- activeLayer.maskVersion = (activeLayer.maskVersion || 0) + 1;
- }
- enqueueHistoryTask(() => {
- pushHistoryStep(
- toolForHistory,
- 'Layer Mask Stroke',
- beforeMaskData,
- afterMaskData,
- currentLayerId,
- dirtyRect,
- undefined,
- undefined,
- undefined,
- undefined,
- true
- );
- });
- }
- } else if (isToneLayer && sourceCanvas) {
- if (!grid.isLayerIngested(currentLayerId)) {
- grid.ingestCanvas(currentLayerId, sourceCanvas, targetFormat);
- }
- const sCtx = get2DContext(sourceCanvas);
- const beforeSelectionData =
- activeSelection?.mask && sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- if (sCtx) {
- sCtx.save();
- sCtx.beginPath();
- sCtx.rect(sx, sy, dw, dh);
- sCtx.clip();
- applySelectionCanvasClip(sCtx, activeSelection);
-
- const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999;
- if (!needsIsolatedBake) {
- renderCompleteStroke(sCtx, allPoints, bs, currentTool, effectiveMode, isBgEraser, sourceCanvas, Boolean(activeLayer?.alphaLocked));
- } else {
- sCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
- sCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- sCtx.globalCompositeOperation = 'source-atop';
- } else {
- sCtx.globalCompositeOperation = 'source-over';
- }
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtxBake = bakeCanvas.getContext('2d', { alpha: true });
- if (bCtxBake) {
- bCtxBake.clearRect(0, 0, dw, dh);
- bCtxBake.save();
- bCtxBake.translate(-sx, -sy);
- renderCompleteStroke(
- bCtxBake,
- allPoints,
- { ...bs, opacity: 1.0, isTransparentInk: false, color: isEraser && !isBgEraser ? '#000000' : bs.color },
- isEraser && !isBgEraser ? 'brush' : currentTool,
- effectiveMode,
- isBgEraser,
- sourceCanvas,
- false
- );
- bCtxBake.restore();
- sCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
- sCtx.restore();
- }
-
- const beforeSnapshot = grid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = sCtx ? sCtx.getImageData(sx, sy, dw, dh) : null;
- if (afterData && beforeSelectionData && activeSelection?.mask && sCtx) {
- applySelectionMaskToImageData(beforeSelectionData, afterData, sx, sy, activeSelection);
- sCtx.putImageData(afterData, sx, sy);
- }
-
- if (activeLayer && canvas) {
- const freq = activeLayer?.toneFrequency ?? 60;
- const cellSize = Math.max(3.5, (dimensionsRef.current.dpi ?? 600) / freq);
- const cellMargin = isEraser ? Math.ceil(cellSize * 2 + 32) : 0;
- const fxX = Math.max(0, sx - cellMargin);
- const fxY = Math.max(0, sy - cellMargin);
- const fxW = Math.min(canvas.width, sx + dw + cellMargin) - fxX;
- const fxH = Math.min(canvas.height, sy + dh + cellMargin) - fxY;
- applyLayerEffects(
- sourceCanvas,
- canvas,
- activeLayer,
- dimensionsRef.current.dpi ?? 600,
- { x: fxX, y: fxY, width: fxW, height: fxH }
- );
- }
-
- if (afterData) {
- grid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- }
- const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
-
- enqueueHistoryTask(() => {
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
- });
- } else {
- // Tile-native raster bake using a temporary dirtyRect-sized canvas (zero full-layer canvas!)
- const regionCanvas = grid.createRegionCanvas(currentLayerId, dirtyRect);
- const rCtx = regionCanvas ? get2DContext(regionCanvas) : null;
- if (regionCanvas && rCtx) {
- const beforeSelectionData =
- activeSelection?.mask ? rCtx.getImageData(0, 0, dw, dh) : null;
-
- rCtx.save();
- rCtx.translate(-sx, -sy);
- rCtx.beginPath();
- rCtx.rect(sx, sy, dw, dh);
- rCtx.clip();
- applySelectionCanvasClip(rCtx, activeSelection);
-
- const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999 || hasWetEdge;
-
- if (!needsIsolatedBake) {
- renderCompleteStroke(rCtx, allPoints, bs, currentTool, effectiveMode, isBgEraser, canvas || undefined, Boolean(activeLayer?.alphaLocked));
- } else {
- rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
- rCtx.globalCompositeOperation = 'destination-out';
- } else if (activeLayer?.alphaLocked) {
- rCtx.globalCompositeOperation = 'source-atop';
- } else {
- rCtx.globalCompositeOperation = 'source-over';
- }
- const bakeCanvas = getReusableBakeCanvas(dw, dh);
- const bCtx = bakeCanvas.getContext('2d', { alpha: true, willReadFrequently: hasWetEdge });
- if (bCtx) {
- bCtx.clearRect(0, 0, dw, dh);
- bCtx.save();
- bCtx.translate(-sx, -sy);
- renderCompleteStroke(
- bCtx,
- allPoints,
- {
- ...bs,
- opacity: 1.0,
- isTransparentInk: false,
- wetEdge: 0,
- color: isEraser && !isBgEraser ? '#000000' : bs.color,
- },
- isEraser && !isBgEraser ? 'brush' : currentTool,
- effectiveMode,
- isBgEraser,
- canvas || undefined,
- false
- );
- bCtx.restore();
-
- if (hasWetEdge) {
- const bakeImg = bCtx.getImageData(0, 0, dw, dh);
- applyCspWatercolorEdge(
- bakeImg,
- bs.wetEdge ?? 0,
- bs.wetEdgeRadius ?? 3.0,
- bs.wetEdgeAlphaPower ?? 25,
- bs.wetEdgeValuePower ?? 15
- );
- bCtx.putImageData(bakeImg, 0, 0);
- }
-
- rCtx.drawImage(bakeCanvas, 0, 0, dw, dh, sx, sy, dw, dh);
- }
- }
-
- rCtx.restore();
-
- if (beforeSelectionData && activeSelection?.mask) {
- const fullAfter = rCtx.getImageData(0, 0, dw, dh);
- applySelectionMaskToImageData(beforeSelectionData, fullAfter, sx, sy, activeSelection);
- rCtx.putImageData(fullAfter, 0, 0);
- }
-
- const useSparseTileSpans = dw * dh > 512 * 512 && touchedTilesRef.current.size > 0;
- if (useSparseTileSpans) {
- const rows = new Map<number, number[]>();
- for (const key of touchedTilesRef.current) {
- const ty = Math.floor(key / 65536);
- const tx = key % 65536;
- let list = rows.get(ty);
- if (!list) {
- list = [];
- rows.set(ty, list);
- }
- list.push(tx);
- }
-
- const spans: Array<{ x: number; y: number; width: number; height: number }> = [];
- for (const [ty, txList] of rows) {
- txList.sort((a, b) => a - b);
- let spanStart = txList[0];
- let spanEnd = txList[0];
- const pushClampedSpan = (s0: number, s1: number) => {
- const rx = Math.max(sx, s0 * TILE_SIZE);
- const ry = Math.max(sy, ty * TILE_SIZE);
- const rxEnd = Math.min(sx + dw, (s1 + 1) * TILE_SIZE);
- const ryEnd = Math.min(sy + dh, (ty + 1) * TILE_SIZE);
- const rw = rxEnd - rx;
- const rh = ryEnd - ry;
- if (rw > 0 && rh > 0) spans.push({ x: rx, y: ry, width: rw, height: rh });
- };
- for (let i = 1; i < txList.length; i++) {
- if (txList[i] <= spanEnd + 1) {
- spanEnd = txList[i];
- } else {
- pushClampedSpan(spanStart, spanEnd);
- spanStart = txList[i];
- spanEnd = txList[i];
- }
- }
- pushClampedSpan(spanStart, spanEnd);
- }
-
- const beforeSnapshot = new Map<string, { format: TileFormat; data: Uint8Array | null }>();
- for (let i = 0; i < spans.length; i++) {
- const sp = spans[i];
- const subSnap = grid.snapshotTilesInRect(currentLayerId, sp);
- for (const [k, v] of subSnap) {
- if (!beforeSnapshot.has(k)) beforeSnapshot.set(k, v);
- }
- const spanData = rCtx.getImageData(sp.x - sx, sp.y - sy, sp.width, sp.height);
- if (isMonochrome) {
- binarizeImageDataBuffer(
- spanData,
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
- }
- grid.writeImageData(currentLayerId, spanData, sp.x, sp.y, targetFormat, true);
- }
-
- const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId);
- enqueueHistoryTask(() => {
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
- });
- } else {
- const beforeSnapshot = grid.snapshotTilesInRect(currentLayerId, dirtyRect);
- const afterData = rCtx.getImageData(0, 0, dw, dh);
- if (isMonochrome) {
- binarizeImageDataBuffer(
- afterData,
- activeLayer?.monoThreshold ?? 128,
- activeLayer?.monoExpressBlack ?? true,
- activeLayer?.monoExpressWhite ?? true
- );
- }
- grid.writeImageData(currentLayerId, afterData, sx, sy, targetFormat);
- const tileDeltas = grid.computeDeltasFromSnapshot(beforeSnapshot, currentLayerId, dirtyRect);
-
- enqueueHistoryTask(() => {
- pushHistoryStep(toolForHistory, label, null, null, currentLayerId, dirtyRect, tileDeltas);
- });
- }
-
- // Release temporary dirtyRect canvas immediately
- releaseTemporaryCanvas(regionCanvas);
-
- // Synchronize any existing cached display/source canvases strictly within dirtyRect
- if (canvas) {
- grid.renderLayerToCanvas(currentLayerId, canvas, dirtyRect);
- }
- if (layerSourceCanvasesRef?.current?.has(currentLayerId)) {
- const existingSource = layerSourceCanvasesRef.current.get(currentLayerId);
- if (existingSource) {
- grid.renderLayerToCanvas(currentLayerId, existingSource, dirtyRect);
- }
- }
- }
- }
- }
- }
-
- // Clear draft overlay BEFORE synchronous tile grid notification so in-stack compositor
- // swaps from live draft to committed tiles in a single atomic frame (zero double-alpha flash!)
- if (clearDraftRafRef.current !== null) {
- cancelAnimationFrame(clearDraftRafRef.current);
- clearDraftRafRef.current = null;
- }
- if (draftCanvas) {
- const dCtx = get2DContext(draftCanvas);
- if (dCtx) {
- try {
- dCtx.restore();
- } catch (_) {}
- dCtx.resetTransform();
- dCtx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
- }
- (draftCanvas as any).__draftHasContent = false;
- (draftCanvas as any).__draftCompositeOp = 'source-over';
- (draftCanvas as any).__draftMonochrome = false;
- (draftCanvas as any).__draftVersion = ((draftCanvas as any).__draftVersion || 0) + 1;
- }
- clearPredictedCanvas();
-
- grid.notifyChange(true);
-
- if (currentStrokeIdRef.current) {
- onCollabStrokeFinishRef.current?.(
- currentStrokeIdRef.current,
- currentLayerId,
- endPoint,
- mergedDirty ? {
- x: Math.max(0, Math.floor(mergedDirty.minX)),
- y: Math.max(0, Math.floor(mergedDirty.minY)),
- width: Math.max(1, Math.ceil(mergedDirty.maxX) - Math.max(0, Math.floor(mergedDirty.minX))),
- height: Math.max(1, Math.ceil(mergedDirty.maxY) - Math.max(0, Math.floor(mergedDirty.minY))),
- } : undefined,
- createdVectorStroke
- );
- currentStrokeIdRef.current = null;
- }
-
- strokePipelineRef.current.abortStroke();
- frameGpuDabsRef.current.length = 0;
- isDrawingRef.current = false;
- activePointerIdRef.current = null;
- allStrokePointsRef.current = [];
- stabilizedPointRef.current = null;
- hasLastProcessedPointRef.current = false;
- dirtyRectRef.current = null;
- touchedTilesRef.current.clear();
- liveNeedsNotifyRef.current = false;
- isShiftLineStrokeRef.current = false;
- isToneStrokeRef.current = false;
- layerPixelSamplerRef.current = null;
- activeReservoirRef.current = null;
- snapSessionRef.current.endStroke();
- emitConstraintAxisChange(null);
-
- if (isMaskModeRef.current) {
- onUpdateMaskThumbnailRef.current?.(currentLayerId);
- grid.notifyChange(true);
- } else {
- enqueueHistoryTask(() => {
- onUpdateLayerThumbnail(currentLayerId);
- });
- }
- },
- [
- clearPredictedCanvas,
- effectiveDraftCanvasRef,
- emitConstraintAxisChange,
- enqueueHistoryTask,
- flushPendingPoints,
- getCachedLayerCanvas,
- getCanvasPoint,
- layerSourceCanvasesRef,
- markTouchedTiles,
- onUpdateLayerThumbnail,
- pushHistoryStep,
- resolveStrokeColor,
- ]
- );
-
- const handlePointerEnter = useCallback(() => {
- if (viewportRef.current) {
- cachedViewportRectRef.current = viewportRef.current.getBoundingClientRect();
- }
- dispatchPointerStat(null, null, 0);
- }, [dispatchPointerStat, viewportRef]);
-
- const handlePointerLeave = useCallback(() => {
- if (!isDrawingRef.current) {
- dispatchPointerStat(null, null, 0);
- }
- }, [dispatchPointerStat]);
-
- const resetHistory = useCallback((targetDocumentId?: string) => {
- flushPendingHistoryTasks();
- const docId = targetDocumentId ?? activeSessionIdRef.current;
- const sess = docId ? documentStore.getSession(docId) : null;
- const targetCache = sess ? sess.undoCache : activeUndoCacheRef.current;
- const targetGrid = sess ? sess.tileGrid : activeTileGridRef.current;
-
- if (sess) {
- sess.history = [];
- sess.historyIndex = -1;
- }
-
- if (!targetDocumentId || targetDocumentId === activeSessionIdRef.current) {
- historyRef.current = [];
- historyIndexRef.current = -1;
- lastStrokeEndRef.current = null;
- setHistoryList([]);
- setHistoryIndex(-1);
- setCanUndo(false);
- setCanRedo(false);
- }
-
- targetCache.clearCache().catch(() => {});
+ pushHistoryStep: history.pushHistoryStep,
+ flushPendingHistoryTasks: history.flushPendingHistoryTasks,
+ enqueueHistoryTask: history.enqueueHistoryTask,
+ });
- // Seed initial history state directly from SparseTileGrid LOD 3 (zero full canvas read)
- const now = Date.now();
- const dims = dimensionsRef.current;
- const layerId = activeLayerIdRef.current || activeLayerId;
- if (layerId && dims.width > 0 && dims.height > 0) {
- const thumbnail = createCanvasThumbnail(
- { grid: targetGrid, layerId, dimensions: dims },
- !isBackgroundLayerId(layerId)
- );
- const initialItem: HistoryItem = {
- id: `hist-init-${now}`,
- type: 'initial',
- label: 'New Document',
- timestamp: now,
- timeFormatted: formatTime(now),
- thumbnailUrl: thumbnail,
- imageData: undefined,
- beforeImageData: null,
- afterImageData: null,
- layerId,
- };
- if (sess) {
- sess.history = [initialItem];
- sess.historyIndex = 0;
- }
- if (!targetDocumentId || targetDocumentId === activeSessionIdRef.current) {
- historyRef.current = [initialItem];
- historyIndexRef.current = 0;
- syncHistoryState();
- }
- }
- }, [activeLayerId, flushPendingHistoryTasks, syncHistoryState]);
+ abortActiveStrokeRef.current = brushSession.abortActiveStroke;
return {
interactionRef,
isDrawingRef,
getActiveCanvas,
- pushHistoryStep,
- handlePointerDown,
- handlePointerMove,
- handlePointerUp,
- handlePointerEnter,
- handlePointerLeave,
- undo,
- redo,
- canUndo,
- canRedo,
- historyList,
- historyIndex,
- jumpToHistoryIndex,
- clearCanvas,
- resetHistory,
- selectiveUndo,
+ pushHistoryStep: history.pushHistoryStep,
+ handlePointerDown: brushSession.handlePointerDown,
+ handlePointerMove: brushSession.handlePointerMove,
+ handlePointerUp: brushSession.handlePointerUp,
+ handlePointerEnter: brushSession.handlePointerEnter,
+ handlePointerLeave: brushSession.handlePointerLeave,
+ undo: history.undo,
+ redo: history.redo,
+ canUndo: history.canUndo,
+ canRedo: history.canRedo,
+ historyList: history.historyList,
+ historyIndex: history.historyIndex,
+ jumpToHistoryIndex: history.jumpToHistoryIndex,
+ clearCanvas: history.clearCanvas,
+ resetHistory: history.resetHistory,
+ selectiveUndo: history.selectiveUndo,
cursorPos: null as { x: number; y: number } | null,
currentPressure: 0,
isHovering: false,
diff --git a/src/hooks/useCollabSync.ts b/src/hooks/useCollabSync.ts
new file mode 100644
index 0000000..aaeacac
--- /dev/null
+++ b/src/hooks/useCollabSync.ts
@@ -0,0 +1,680 @@
+import React, { useRef, useEffect, useCallback } from 'react';
+import {
+ BrushSettings,
+ CanvasColorMode,
+ CanvasDimensions,
+ DocumentTab,
+ LayerItem,
+ Point,
+ ToolType,
+} from '../types/editor';
+import {
+ CollabPeer,
+ MultiplayerMessage,
+ StrokeChunkMessage,
+ StrokeFinishMessage,
+ StrokeStartMessage,
+} from '../types/multiplayer';
+import { useMultiplayer } from './useMultiplayer';
+import { getNextCollabLayerName } from './useLayerManager';
+import { multiplayerService } from '../services/multiplayerService';
+import { enforceColorMode } from '../utils/colorUtils';
+import {
+ drawDot,
+ drawSmoothBezierSegment,
+ get2DContext,
+ getMidPoint,
+ getReusableBakeCanvas,
+ renderCompleteStroke,
+} from '../utils/canvasUtils';
+import { drawPencilBezierSegment, drawPencilDot, PencilGrade } from '../utils/pencilEngine';
+import { renderVectorStroke } from '../utils/vectorEngine';
+import { documentStore } from '../utils/documentStore';
+import { documentStoreActions } from '../stores';
+
+interface LayerActionMessageBase {
+ type: string;
+ layerItem?: LayerItem;
+ imageDataUrl?: string;
+ layerId?: string;
+ newName?: string;
+ visible?: boolean;
+ opacity?: number;
+}
+
+export interface UseCollabSyncParams {
+ hasOpenDocument: boolean;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ activeLayerId: string;
+ selectedLayerIds: string[];
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ selectiveUndoRef: React.MutableRefObject<(peerId?: string | number) => void>;
+ setActiveLayerId: (id: string) => void;
+ addLayer: (
+ type?: 'raster' | 'folder' | 'vector',
+ parentId?: string | null,
+ customName?: string,
+ customId?: string,
+ selectNew?: boolean
+ ) => LayerItem;
+ addRemoteLayer: (layerItem: LayerItem, imageDataUrl?: string) => void;
+ deleteLayer: (id: string) => void;
+ deleteRemoteLayer: (id: string) => void;
+ deleteSelectedLayers: () => void;
+ groupSelectedLayers: () => void;
+ syncRemoteDocument: (layers: LayerItem[], dataUrls: Record<string, string>) => void;
+ renameLayer: (id: string, newName: string) => void;
+ toggleVisibility: (id: string) => void;
+ setOpacity: (id: string, opacity: number) => void;
+ clearActiveLayer: () => void;
+ updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
+ showToast: (msg: string) => void;
+}
+
+export function useCollabSync({
+ hasOpenDocument,
+ dimensions,
+ colorMode,
+ layers,
+ activeLayerId,
+ selectedLayerIds,
+ layerCanvasesRef,
+ selectiveUndoRef,
+ setActiveLayerId,
+ addLayer,
+ addRemoteLayer,
+ deleteLayer,
+ deleteRemoteLayer,
+ deleteSelectedLayers,
+ groupSelectedLayers,
+ syncRemoteDocument,
+ renameLayer,
+ toggleVisibility,
+ setOpacity,
+ clearActiveLayer,
+ updateLayerThumbnail,
+ showToast,
+}: UseCollabSyncParams) {
+ const remoteDraftCanvasesRef = useRef<Map<string | number, HTMLCanvasElement>>(new Map());
+ const remoteStrokeStatesRef = useRef<
+ Map<
+ string,
+ {
+ brushSettings: BrushSettings;
+ tool: ToolType;
+ points: Point[];
+ layerId: string;
+ peerId: string | number;
+ }
+ >
+ >(new Map());
+
+ const layersRef = useRef(layers);
+ useEffect(() => {
+ layersRef.current = layers;
+ }, [layers]);
+
+ const handleRemoteStrokeStart = useCallback(
+ (msg: StrokeStartMessage) => {
+ remoteStrokeStatesRef.current.set(msg.strokeId, {
+ brushSettings: msg.brushSettings,
+ tool: msg.tool,
+ points: [msg.startPoint],
+ layerId: msg.layerId,
+ peerId: msg.peerId,
+ });
+
+ const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
+ if (!draftCanvas) return;
+ const ctx = get2DContext(draftCanvas);
+ if (!ctx) return;
+
+ ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ const bs = msg.brushSettings;
+ const isEraser = msg.tool === 'eraser';
+ const isBgEraser =
+ isEraser && (msg.layerId === 'layer-bg' || msg.layerId.startsWith('layer-bg'));
+ const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
+ const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
+
+ if (isPencil) {
+ drawPencilDot(
+ ctx,
+ msg.startPoint,
+ strokeColor,
+ (bs.preset as PencilGrade) || 'pencil-2b',
+ bs.flow ?? 0.74,
+ bs.grain ?? 1.0,
+ bs.hardness
+ );
+ } else {
+ drawDot(
+ ctx,
+ msg.startPoint,
+ strokeColor,
+ isEraser && !isBgEraser,
+ colorMode === 'monochrome' ? 1.0 : bs.hardness ?? 1.0,
+ bs.flow ?? 1.0
+ );
+ }
+ },
+ [colorMode]
+ );
+
+ const handleRemoteStrokeChunk = useCallback(
+ (msg: StrokeChunkMessage) => {
+ const strokeState = remoteStrokeStatesRef.current.get(msg.strokeId);
+ if (!strokeState) return;
+
+ const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
+ if (!draftCanvas) return;
+ const ctx = get2DContext(draftCanvas);
+ if (!ctx) return;
+
+ const bs = strokeState.brushSettings;
+ const isEraser = strokeState.tool === 'eraser';
+ const isBgEraser =
+ isEraser &&
+ (strokeState.layerId === 'layer-bg' || strokeState.layerId.startsWith('layer-bg'));
+ const isPencil = !isEraser && (bs.preset?.startsWith('pencil') ?? false);
+ const strokeColor = isBgEraser ? '#ffffff' : enforceColorMode(bs.color, colorMode);
+ const pts = strokeState.points;
+
+ for (let i = 0; i < msg.points.length; i++) {
+ const pt = msg.points[i];
+ pts.push(pt);
+
+ if (isPencil) {
+ if (pts.length >= 3) {
+ const p0 = pts[pts.length - 3];
+ const p1 = pts[pts.length - 2];
+ const p2 = pts[pts.length - 1];
+ drawPencilBezierSegment(
+ ctx,
+ getMidPoint(p0, p1),
+ p1,
+ getMidPoint(p1, p2),
+ strokeColor,
+ (bs.preset as PencilGrade) || 'pencil-2b',
+ bs.flow ?? 0.74,
+ bs.grain ?? 1.0,
+ bs.hardness
+ );
+ } else if (pts.length === 2) {
+ drawPencilBezierSegment(
+ ctx,
+ pts[0],
+ pts[0],
+ getMidPoint(pts[0], pts[1]),
+ strokeColor,
+ (bs.preset as PencilGrade) || 'pencil-2b',
+ bs.flow ?? 0.74,
+ bs.grain ?? 1.0,
+ bs.hardness
+ );
+ }
+ } else if (bs.smoothing) {
+ if (pts.length >= 3) {
+ const p0 = pts[pts.length - 3];
+ const p1 = pts[pts.length - 2];
+ const p2 = pts[pts.length - 1];
+ drawSmoothBezierSegment(
+ ctx,
+ getMidPoint(p0, p1),
+ p1,
+ getMidPoint(p1, p2),
+ strokeColor,
+ isEraser && !isBgEraser,
+ colorMode === 'monochrome' ? 1.0 : bs.hardness ?? 1.0,
+ bs.flow ?? 1.0,
+ bs.spacing ?? 0.1
+ );
+ } else if (pts.length === 2) {
+ drawSmoothBezierSegment(
+ ctx,
+ pts[0],
+ pts[0],
+ getMidPoint(pts[0], pts[1]),
+ strokeColor,
+ isEraser && !isBgEraser,
+ colorMode === 'monochrome' ? 1.0 : bs.hardness ?? 1.0,
+ bs.flow ?? 1.0,
+ bs.spacing ?? 0.1
+ );
+ }
+ } else if (pts.length >= 2) {
+ const pPrev = pts[pts.length - 2];
+ const pCurr = pts[pts.length - 1];
+ ctx.save();
+ ctx.lineCap = 'round';
+ ctx.lineJoin = 'round';
+ if ((bs.flow ?? 1.0) < 0.999) {
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.flow ?? 1.0));
+ }
+ if (isBgEraser) {
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.strokeStyle = '#ffffff';
+ } else if (isEraser) {
+ ctx.globalCompositeOperation = 'destination-out';
+ ctx.strokeStyle = 'rgba(0, 0, 0, 1)';
+ } else {
+ ctx.globalCompositeOperation = 'source-over';
+ ctx.strokeStyle = strokeColor;
+ }
+ ctx.lineWidth = (pPrev.width + pCurr.width) / 2;
+ ctx.beginPath();
+ ctx.moveTo(pPrev.x, pPrev.y);
+ ctx.lineTo(pCurr.x, pCurr.y);
+ ctx.stroke();
+ ctx.restore();
+ }
+ }
+ },
+ [colorMode]
+ );
+
+ const handleRemoteStrokeFinish = useCallback(
+ (msg: StrokeFinishMessage) => {
+ const strokeState = remoteStrokeStatesRef.current.get(msg.strokeId);
+ if (!strokeState) return;
+
+ if (msg.endPoint) {
+ strokeState.points.push(msg.endPoint);
+ }
+
+ let targetCanvas = layerCanvasesRef.current.get(msg.layerId);
+ let targetLayerId = msg.layerId;
+
+ if (!targetCanvas) {
+ const byPeerId = layersRef.current.find(
+ (l) => l.type === 'raster' && l.id.includes(String(msg.peerId))
+ );
+ if (byPeerId) {
+ targetCanvas = layerCanvasesRef.current.get(byPeerId.id);
+ targetLayerId = byPeerId.id;
+ }
+ }
+
+ if (!targetCanvas) {
+ const fallback =
+ layersRef.current.find(
+ (l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
+ ) || layersRef.current.find((l) => l.type === 'raster');
+ if (fallback) {
+ targetCanvas = layerCanvasesRef.current.get(fallback.id);
+ targetLayerId = fallback.id;
+ }
+ }
+
+ if (targetCanvas && strokeState.points.length > 0) {
+ const targetLayer = layersRef.current.find((l) => l.id === targetLayerId);
+ const isMono =
+ colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (msg.vectorStroke && targetLayer?.type === 'vector') {
+ targetLayer.vectorStrokes = [...(targetLayer.vectorStrokes || []), msg.vectorStroke];
+ const ctx = get2DContext(targetCanvas);
+ if (ctx) {
+ renderVectorStroke(ctx, msg.vectorStroke);
+ const fullData = ctx.getImageData(0, 0, targetCanvas.width, targetCanvas.height);
+ documentStore
+ .getActiveTileGrid()
+ .writeImageData(targetLayerId, fullData, 0, 0, targetFormat);
+ }
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(targetLayerId, true);
+ } else {
+ const ctx = get2DContext(targetCanvas);
+ if (ctx) {
+ const isEraser = strokeState.tool === 'eraser';
+ const isBgEraser =
+ isEraser && (targetLayerId === 'layer-bg' || targetLayerId.startsWith('layer-bg'));
+ const bs = strokeState.brushSettings;
+ const isTranslucentBrush = !isEraser && (bs.opacity ?? 1.0) < 0.999;
+ const isAlphaLocked = Boolean(targetLayer?.alphaLocked);
+ const isTransparentInk = Boolean(bs.isTransparentInk);
+
+ if (isTranslucentBrush || isTransparentInk || isAlphaLocked) {
+ const bakeCanvas = getReusableBakeCanvas(targetCanvas.width, targetCanvas.height);
+ const bCtx = get2DContext(bakeCanvas);
+ if (bCtx) {
+ bCtx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
+ renderCompleteStroke(
+ bCtx,
+ strokeState.points,
+ { ...bs, opacity: 1.0, isTransparentInk: false },
+ strokeState.tool,
+ colorMode,
+ isBgEraser,
+ targetCanvas,
+ false
+ );
+ ctx.save();
+ ctx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
+ if (isTransparentInk) {
+ ctx.globalCompositeOperation = 'destination-out';
+ } else if (isAlphaLocked) {
+ ctx.globalCompositeOperation = 'source-atop';
+ } else {
+ ctx.globalCompositeOperation = 'source-over';
+ }
+ ctx.drawImage(bakeCanvas, 0, 0);
+ ctx.restore();
+ }
+ } else {
+ renderCompleteStroke(
+ ctx,
+ strokeState.points,
+ bs,
+ strokeState.tool,
+ colorMode,
+ isBgEraser,
+ targetCanvas,
+ isAlphaLocked
+ );
+ }
+
+ const pad = Math.ceil(Math.max(32, (bs.size || 10) * 1.5));
+ let dirtyX = 0;
+ let dirtyY = 0;
+ let dirtyW = targetCanvas.width;
+ let dirtyH = targetCanvas.height;
+
+ if (msg.dirtyRect) {
+ dirtyX = Math.max(0, Math.floor(msg.dirtyRect.x));
+ dirtyY = Math.max(0, Math.floor(msg.dirtyRect.y));
+ dirtyW = Math.min(targetCanvas.width - dirtyX, Math.ceil(msg.dirtyRect.width));
+ dirtyH = Math.min(targetCanvas.height - dirtyY, Math.ceil(msg.dirtyRect.height));
+ } else if (strokeState.points.length > 0) {
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (const pt of strokeState.points) {
+ if (pt.x < minX) minX = pt.x;
+ if (pt.y < minY) minY = pt.y;
+ if (pt.x > maxX) maxX = pt.x;
+ if (pt.y > maxY) maxY = pt.y;
+ }
+ dirtyX = Math.max(0, Math.floor(minX - pad));
+ dirtyY = Math.max(0, Math.floor(minY - pad));
+ dirtyW = Math.min(targetCanvas.width - dirtyX, Math.ceil(maxX + pad) - dirtyX);
+ dirtyH = Math.min(targetCanvas.height - dirtyY, Math.ceil(maxY + pad) - dirtyY);
+ }
+
+ if (dirtyW > 0 && dirtyH > 0) {
+ const afterData = ctx.getImageData(dirtyX, dirtyY, dirtyW, dirtyH);
+ documentStore
+ .getActiveTileGrid()
+ .writeImageData(targetLayerId, afterData, dirtyX, dirtyY, targetFormat);
+ }
+
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(targetLayerId, true);
+ }
+ }
+ }
+
+ const draftCanvas = remoteDraftCanvasesRef.current.get(msg.peerId);
+ if (draftCanvas) {
+ const ctx = get2DContext(draftCanvas);
+ if (ctx) {
+ ctx.clearRect(0, 0, draftCanvas.width, draftCanvas.height);
+ }
+ }
+
+ remoteStrokeStatesRef.current.delete(msg.strokeId);
+ },
+ [colorMode, layerCanvasesRef, updateLayerThumbnail]
+ );
+
+ const handleRemoteDocSync = useCallback(
+ (
+ syncDims: CanvasDimensions,
+ syncMode: CanvasColorMode,
+ syncLayers: LayerItem[],
+ syncDataUrls: Record<string, string>
+ ) => {
+ documentStoreActions.setDimensions(syncDims);
+ documentStoreActions.setColorMode(syncMode);
+ syncRemoteDocument(syncLayers, syncDataUrls);
+ const newDocId = `doc-collab-${Date.now()}`;
+ const newDoc: DocumentTab = {
+ id: newDocId,
+ name: 'Collab Session',
+ dimensions: syncDims,
+ colorMode: syncMode,
+ layers: syncLayers,
+ activeLayerId: syncLayers[0]?.id || 'layer-1',
+ perspectiveRuler: null,
+ };
+ documentStoreActions.setPerspectiveRuler(null);
+ documentStoreActions.setDocuments([newDoc]);
+ documentStoreActions.setActiveDocumentId(newDocId);
+ documentStoreActions.setDocumentName('Collab Session');
+ },
+ [syncRemoteDocument]
+ );
+
+ const handleRemoteAssignedLayer = useCallback(
+ (layerId: string) => {
+ setActiveLayerId(layerId);
+ },
+ [setActiveLayerId]
+ );
+
+ const handleRemoteJoinRequest = useCallback(
+ (peer: CollabPeer) => {
+ const layerName = getNextCollabLayerName(peer.name, layersRef.current);
+ const layerId = `layer-${peer.id}-1`;
+ const newLayer = addLayer('raster', null, layerName, layerId, false);
+ multiplayerService.sendLayerAdd(newLayer);
+ const updated = layersRef.current.some((l) => l.id === newLayer.id)
+ ? layersRef.current
+ : [newLayer, ...layersRef.current];
+ return {
+ assignedLayerId: layerId,
+ updatedLayers: updated,
+ };
+ },
+ [addLayer]
+ );
+
+ const handleRemoteLayerAction = useCallback(
+ (msg: MultiplayerMessage) => {
+ const action = msg as unknown as LayerActionMessageBase;
+ if (action.type === 'LAYER_ADD') {
+ if (action.layerItem) {
+ addRemoteLayer(action.layerItem, action.imageDataUrl);
+ }
+ } else if (action.type === 'LAYER_DELETE') {
+ if (action.layerId) {
+ deleteRemoteLayer(action.layerId);
+ }
+ } else if (action.type === 'LAYER_CLEAR' && action.layerId) {
+ const layerId = action.layerId;
+ const targetCanvas = layerCanvasesRef.current.get(layerId);
+ if (targetCanvas) {
+ const ctx = get2DContext(targetCanvas);
+ if (ctx) {
+ const isBg = layerId === 'layer-bg' || layerId.startsWith('layer-bg');
+ if (isBg) {
+ ctx.fillStyle = '#ffffff';
+ ctx.fillRect(0, 0, targetCanvas.width, targetCanvas.height);
+ documentStore.getActiveTileGrid().ingestCanvas(layerId, targetCanvas, 'color-32bit');
+ } else {
+ ctx.clearRect(0, 0, targetCanvas.width, targetCanvas.height);
+ documentStore.getActiveTileGrid().clearLayer(layerId);
+ }
+ documentStore.getActiveTileGrid().notifyChange(true);
+ updateLayerThumbnail(layerId, true);
+ }
+ }
+ } else if (action.type === 'LAYER_RENAME') {
+ if (action.layerId && action.newName) {
+ renameLayer(action.layerId, action.newName);
+ }
+ } else if (action.type === 'LAYER_VISIBILITY') {
+ if (action.layerId && action.visible !== undefined) {
+ const l = layersRef.current.find((item) => item.id === action.layerId);
+ if (l && l.visible !== action.visible) {
+ toggleVisibility(action.layerId);
+ }
+ }
+ } else if (action.type === 'LAYER_OPACITY') {
+ if (action.layerId && action.opacity !== undefined) {
+ setOpacity(action.layerId, action.opacity);
+ }
+ }
+ },
+ [
+ addRemoteLayer,
+ deleteRemoteLayer,
+ layerCanvasesRef,
+ updateLayerThumbnail,
+ renameLayer,
+ toggleVisibility,
+ setOpacity,
+ ]
+ );
+
+ const mp = useMultiplayer({
+ dimensions,
+ colorMode,
+ layers,
+ layerCanvasesRef,
+ onRemoteStrokeStart: handleRemoteStrokeStart,
+ onRemoteStrokeChunk: handleRemoteStrokeChunk,
+ onRemoteStrokeFinish: handleRemoteStrokeFinish,
+ onRemoteDocSync: handleRemoteDocSync,
+ onRemoteJoinRequest: handleRemoteJoinRequest,
+ onRemoteAssignedLayer: handleRemoteAssignedLayer,
+ onRemoteLayerAction: handleRemoteLayerAction,
+ onRemoteSelectiveUndo: (_strokeId, peerId) => {
+ selectiveUndoRef.current(peerId);
+ },
+ showToast,
+ });
+
+ const handleStartHosting = useCallback(
+ async (roomName: string, port: number, hostNickname?: string, isGlobal?: boolean) => {
+ if (!hasOpenDocument) {
+ showToast('Please create or open a canvas before hosting a session.');
+ return false;
+ }
+ const finalHostName = (hostNickname || mp.myPeer.name || 'Sora').trim();
+ const defaultLayer =
+ layersRef.current.find((l) => l.id === activeLayerId) ||
+ layersRef.current.find(
+ (l) => l.type === 'raster' && l.id !== 'layer-bg' && !l.id.startsWith('layer-bg')
+ );
+ if (
+ defaultLayer &&
+ (defaultLayer.name === 'Layer 1' ||
+ !defaultLayer.name.toLowerCase().startsWith(finalHostName.toLowerCase()))
+ ) {
+ const hostLayerName = getNextCollabLayerName(
+ finalHostName,
+ layersRef.current.filter((l) => l.id !== defaultLayer.id)
+ );
+ renameLayer(defaultLayer.id, hostLayerName);
+ }
+ return await mp.startHosting(roomName, port, finalHostName, isGlobal);
+ },
+ [hasOpenDocument, showToast, mp.myPeer.name, activeLayerId, renameLayer, mp.startHosting]
+ );
+
+ const handleAddLayer = useCallback(
+ (type: 'raster' | 'folder' = 'raster') => {
+ if (mp.isConnected && type === 'raster') {
+ const name = getNextCollabLayerName(mp.myPeer.name, layersRef.current);
+ const newLayer = addLayer('raster', null, name);
+ if (newLayer) {
+ multiplayerService.sendLayerAdd(newLayer);
+ }
+ } else {
+ addLayer(type);
+ }
+ },
+ [mp.isConnected, mp.myPeer.name, addLayer]
+ );
+
+ const handleDeleteLayer = useCallback(
+ (id: string) => {
+ deleteLayer(id);
+ if (mp.isConnected) {
+ multiplayerService.sendLayerDelete(id);
+ }
+ },
+ [deleteLayer, mp.isConnected]
+ );
+
+ const handleDeleteSelectedLayers = useCallback(() => {
+ if (selectedLayerIds && selectedLayerIds.length > 1) {
+ deleteSelectedLayers();
+ showToast(`Deleted ${selectedLayerIds.length} layers`);
+ } else {
+ handleDeleteLayer(activeLayerId);
+ }
+ }, [selectedLayerIds, deleteSelectedLayers, handleDeleteLayer, activeLayerId, showToast]);
+
+ const handleGroupSelectedLayers = useCallback(() => {
+ groupSelectedLayers();
+ showToast('Grouped layers into folder');
+ }, [groupSelectedLayers, showToast]);
+
+ const handleToggleVisibility = useCallback(
+ (id: string) => {
+ const l = layersRef.current.find((item) => item.id === id);
+ toggleVisibility(id);
+ if (mp.isConnected && l) {
+ multiplayerService.sendLayerVisibility(id, !l.visible);
+ }
+ },
+ [toggleVisibility, mp.isConnected]
+ );
+
+ const handleSetOpacity = useCallback(
+ (id: string, opacity: number) => {
+ setOpacity(id, opacity);
+ if (mp.isConnected) {
+ multiplayerService.sendLayerOpacity(id, opacity);
+ }
+ },
+ [setOpacity, mp.isConnected]
+ );
+
+ const handleRenameLayer = useCallback(
+ (id: string, newName: string) => {
+ renameLayer(id, newName);
+ if (mp.isConnected) {
+ multiplayerService.sendLayerRename(id, newName);
+ }
+ },
+ [renameLayer, mp.isConnected]
+ );
+
+ const handleClearActiveLayer = useCallback(() => {
+ clearActiveLayer();
+ if (mp.isConnected) {
+ multiplayerService.sendLayerClear(activeLayerId);
+ }
+ }, [clearActiveLayer, mp.isConnected, activeLayerId]);
+
+ return {
+ ...mp,
+ remoteDraftCanvasesRef,
+ handleStartHosting,
+ handleAddLayer,
+ handleDeleteLayer,
+ handleDeleteSelectedLayers,
+ handleGroupSelectedLayers,
+ handleToggleVisibility,
+ handleSetOpacity,
+ handleRenameLayer,
+ handleClearActiveLayer,
+ };
+}
diff --git a/src/hooks/useLayerManager.ts b/src/hooks/useLayerManager.ts
index 1ac5d2e..1cc1f1a 100644
--- a/src/hooks/useLayerManager.ts
+++ b/src/hooks/useLayerManager.ts
@@ -1,7 +1,7 @@
import { useState, useRef, useCallback, useEffect } from 'react';
import { LayerItem, BlendMode, CanvasDimensions, CanvasColorMode, LoadedDocument, ExpressionColor, CanvasSelection, DirtyRect, AdjustmentLayerData, LayerStyles } from '../types/editor';
import { ResizeCanvasOptions } from '../types/settings';
-import { createCanvasThumbnail, get2DContext } from '../utils/canvasUtils';
+import { createCanvasThumbnail, get2DContext, getCanvasCompositeOperation } from '../utils/canvasUtils';
import { applyLayerEffects, applyExpressionColorToImageData } from '../utils/layerEffectsEngine';
import { HalftoneDotShape } from '../utils/screentoneEngine';
import { SparseTileGrid, globalTileGrid, releaseTemporaryCanvas } from '../utils/tileEngine';
@@ -1959,6 +1959,85 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
updateLayerThumbnail(activeLayerId);
}, [activeLayerId, updateLayerThumbnail]);
+ // Merge active raster layer down onto the raster layer directly below it
+ const mergeDown = useCallback(
+ (targetLayerId?: string): { targetId: string; removedId: string } | null => {
+ const currentLayers = layersRef.current;
+ const srcId = targetLayerId || activeLayerId;
+ const srcIdx = currentLayers.findIndex((l) => l.id === srcId);
+ if (srcIdx < 0) return null;
+
+ const srcLayer = currentLayers[srcIdx];
+ if (!srcLayer || srcLayer.type !== 'raster' || srcLayer.locked) return null;
+
+ // Find the next raster layer below (higher index in top-to-bottom stack)
+ let dstIdx = -1;
+ for (let i = srcIdx + 1; i < currentLayers.length; i++) {
+ if (currentLayers[i].type === 'raster') {
+ dstIdx = i;
+ break;
+ }
+ }
+ if (dstIdx < 0) return null;
+ const dstLayer = currentLayers[dstIdx];
+ if (dstLayer.locked) return null;
+
+ const srcCanvas = materializeLayerCanvas(srcLayer.id);
+ const dstCanvas = materializeLayerCanvas(dstLayer.id);
+ if (!srcCanvas || !dstCanvas) return null;
+
+ const dstCtx = get2DContext(dstCanvas);
+ if (!dstCtx) return null;
+
+ // Composite upper layer (respecting mask if present and enabled)
+ let drawSource: HTMLCanvasElement = srcCanvas;
+ let tempMasked: HTMLCanvasElement | null = null;
+ if (srcLayer.maskCanvas && srcLayer.maskEnabled !== false) {
+ tempMasked = document.createElement('canvas');
+ tempMasked.width = srcCanvas.width;
+ tempMasked.height = srcCanvas.height;
+ const tCtx = get2DContext(tempMasked);
+ if (tCtx) {
+ tCtx.drawImage(srcCanvas, 0, 0);
+ tCtx.globalCompositeOperation = 'destination-in';
+ tCtx.drawImage(srcLayer.maskCanvas, 0, 0);
+ drawSource = tempMasked;
+ }
+ }
+
+ dstCtx.save();
+ dstCtx.globalAlpha = srcLayer.visible ? Math.max(0, Math.min(1, srcLayer.opacity)) : 0;
+ dstCtx.globalCompositeOperation = getCanvasCompositeOperation(srcLayer.blendMode);
+ dstCtx.drawImage(drawSource, 0, 0);
+ dstCtx.restore();
+
+ if (tempMasked) {
+ releaseTemporaryCanvas(tempMasked);
+ }
+
+ // Sync destination canvas back into SparseTileGrid & remove source layer
+ const grid = activeTileGridRef.current;
+ const dstData = dstCtx.getImageData(0, 0, dstCanvas.width, dstCanvas.height);
+ grid.writeImageData(dstLayer.id, dstData, 0, 0, 'color-32bit');
+ grid.clearLayer(srcLayer.id);
+ layerCanvasesRef.current.delete(srcLayer.id);
+ layerSourceCanvasesRef.current.delete(srcLayer.id);
+ layerSourceCanvasesRef.current.delete(dstLayer.id);
+ (dstCanvas as unknown as { __isBlank?: boolean }).__isBlank = false;
+
+ const nextLayers = currentLayers.filter((l) => l.id !== srcLayer.id);
+ layersRef.current = nextLayers;
+ setLayers(nextLayers);
+ setActiveLayerId(dstLayer.id);
+ setSelectedLayerIds([dstLayer.id]);
+
+ grid.notifyChange(true);
+ updateLayerThumbnail(dstLayer.id);
+ return { targetId: dstLayer.id, removedId: srcLayer.id };
+ },
+ [activeLayerId, materializeLayerCanvas, setActiveLayerId, updateLayerThumbnail]
+ );
+
// Switch active document tab in O(1): binds session's SparseTileGrid without clearing or re-slicing
const switchDocumentSession = useCallback(
(documentId: string, nextLayers: LayerItem[], nextActiveLayerId: string, nextDims?: CanvasDimensions) => {
@@ -2784,6 +2863,7 @@ export function useLayerManager({ dimensions: _dimensions, activeSessionId, tile
getEffectiveOpacity,
isLayerEffectivelyVisible,
clearActiveLayer,
+ mergeDown,
resetToNewCanvas,
setDefaultToneFrequency: (freq: number) => {
defaultToneFrequencyRef.current = Math.max(20, Math.min(85, Math.round(freq || 60)));
diff --git a/src/hooks/useTonalAndFilterActions.ts b/src/hooks/useTonalAndFilterActions.ts
new file mode 100644
index 0000000..0367312
--- /dev/null
+++ b/src/hooks/useTonalAndFilterActions.ts
@@ -0,0 +1,870 @@
+import React, { useCallback } from 'react';
+import {
+ AdjustmentLayerData,
+ CanvasColorMode,
+ CanvasDimensions,
+ CanvasSelection,
+ ExpressionColor,
+ FilterType,
+ LayerItem,
+ LayerStyles,
+} from '../types/editor';
+import { documentStore } from '../utils/documentStore';
+import {
+ applyFilter,
+ FilmGrainParams,
+ GaussianBlurParams,
+ MotionBlurParams,
+ UnsharpMaskParams,
+} from '../utils/filterEngine';
+import { applyScreentone, HalftoneDotShape } from '../utils/screentoneEngine';
+import { applyLayerEffects } from '../utils/layerEffectsEngine';
+import { get2DContext } from '../utils/canvasUtils';
+import {
+ TonalCorrectionType,
+ BrightnessContrastParams,
+ BinarizationParams,
+ HueSaturationParams,
+ PosterizationParams,
+ LevelCorrectionParams,
+ applyTonalFilter,
+ applyReverseGradient,
+ createSelectionMask,
+ getProcessingBounds,
+} from '../utils/tonalEngine';
+
+export type AnyFilterParams =
+ | GaussianBlurParams
+ | MotionBlurParams
+ | UnsharpMaskParams
+ | FilmGrainParams;
+
+export type AnyTonalParams =
+ | BrightnessContrastParams
+ | BinarizationParams
+ | HueSaturationParams
+ | PosterizationParams
+ | LevelCorrectionParams
+ | Record<string, never>;
+import {
+ renderSaturatedLines,
+ renderStreamLines,
+ SaturatedLinesOptions,
+ StreamLinesOptions,
+} from '../utils/mangaEffectsEngine';
+import { SimpleToneSettings } from '../components/SimpleToneModal';
+import { useUiStore, uiStoreActions } from '../stores';
+import { PushHistoryStepFn } from './drawing';
+
+export interface UseTonalAndFilterActionsParams {
+ hasOpenDocument: boolean;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ layers: LayerItem[];
+ activeLayer: LayerItem | undefined;
+ activeLayerId: string;
+ selection: CanvasSelection | null;
+ layerCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ layerSourceCanvasesRef: React.MutableRefObject<Map<string, HTMLCanvasElement>>;
+ materializeLayerCanvas: (layerId: string) => HTMLCanvasElement | null;
+ releaseLayerCanvas: (layerId: string) => void;
+ setActiveLayerId: (id: string) => void;
+ getActiveCanvas: () => HTMLCanvasElement | null;
+ updateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
+ handleCommitFloatingSelection: () => void;
+ pushHistoryStepRef: React.MutableRefObject<PushHistoryStepFn | null>;
+ addLayer: (
+ type?: 'raster' | 'folder' | 'vector',
+ parentId?: string | null,
+ customName?: string,
+ customId?: string
+ ) => LayerItem;
+ pasteLayerFromCanvas: (
+ canvas: HTMLCanvasElement,
+ name?: string,
+ blendMode?: LayerItem['blendMode'],
+ opacity?: number,
+ customId?: string,
+ extraProps?: Partial<LayerItem>
+ ) => void;
+ addAdjustmentLayer: (
+ type: 'curves' | 'gradient-map' | 'levels' | 'color-balance',
+ data: AdjustmentLayerData
+ ) => void;
+ updateAdjustmentData: (layerId: string, data: AdjustmentLayerData) => void;
+ updateLayerStyles: (layerId: string, styles: LayerStyles) => void;
+ fillScreentoneSelection: (
+ selection: CanvasSelection | null,
+ density: number,
+ frequency: number,
+ angle: number,
+ dotShape: HalftoneDotShape,
+ densityType: 'specified' | 'image'
+ ) => { id: string; canvas: HTMLCanvasElement };
+ applyExpressionColorOfPreview: (
+ layerId: string
+ ) => { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null | undefined;
+ applyLayerColorPermanently: (
+ layerId: string
+ ) => { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null | undefined;
+ convertLayer: (
+ layerId: string,
+ targetMode: ExpressionColor,
+ options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
+ ) => { beforeImageData: ImageData | null; afterImageData: ImageData | null } | null | undefined;
+ showToast: (msg: string) => void;
+}
+
+export function useTonalAndFilterActions({
+ hasOpenDocument,
+ dimensions,
+ colorMode,
+ layers,
+ activeLayer,
+ activeLayerId,
+ selection,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ materializeLayerCanvas,
+ releaseLayerCanvas,
+ setActiveLayerId,
+ getActiveCanvas,
+ updateLayerThumbnail,
+ handleCommitFloatingSelection,
+ pushHistoryStepRef,
+ addLayer,
+ pasteLayerFromCanvas,
+ addAdjustmentLayer,
+ updateAdjustmentData,
+ updateLayerStyles,
+ fillScreentoneSelection,
+ applyExpressionColorOfPreview,
+ applyLayerColorPermanently,
+ convertLayer,
+ showToast,
+}: UseTonalAndFilterActionsParams) {
+ const handleOpenAdjustmentModal = useCallback(
+ (
+ layerId?: string,
+ initialType: 'curves' | 'gradient-map' | 'levels' | 'color-balance' = 'curves'
+ ) => {
+ uiStoreActions.setAdjustmentModalState({
+ isOpen: true,
+ layerId: layerId || undefined,
+ initialType,
+ });
+ },
+ []
+ );
+
+ const handleApplyAdjustment = useCallback(
+ (type: 'curves' | 'gradient-map' | 'levels' | 'color-balance', data: AdjustmentLayerData) => {
+ const targetId = useUiStore.getState().adjustmentModalState.layerId;
+ if (targetId) {
+ updateAdjustmentData(targetId, data);
+ showToast(`Updated ${data.type} adjustment layer`);
+ } else {
+ addAdjustmentLayer(type, data);
+ showToast(`Created new ${data.type} adjustment layer`);
+ }
+ uiStoreActions.setAdjustmentModalState({ isOpen: false });
+ },
+ [updateAdjustmentData, addAdjustmentLayer, showToast]
+ );
+
+ const handleOpenLayerStylesModal = useCallback(
+ (layerId?: string) => {
+ const targetId = layerId || activeLayerId;
+ if (targetId) {
+ uiStoreActions.setLayerStylesModalState({
+ isOpen: true,
+ layerId: targetId,
+ });
+ }
+ },
+ [activeLayerId]
+ );
+
+ const handleApplyLayerStyles = useCallback(
+ (styles: LayerStyles) => {
+ const targetId = useUiStore.getState().layerStylesModalState.layerId;
+ if (targetId) {
+ updateLayerStyles(targetId, styles);
+ showToast('Updated Layer Styles');
+ }
+ uiStoreActions.setLayerStylesModalState({ isOpen: false });
+ },
+ [updateLayerStyles, showToast]
+ );
+
+ const handleApplyFilter = useCallback(
+ (type: FilterType, params?: AnyFilterParams) => {
+ if (
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.type !== 'raster' ||
+ activeLayer.locked
+ ) {
+ showToast('Select an unlocked raster layer to apply filter');
+ return;
+ }
+ const grid = documentStore.getActiveTileGrid();
+ const isTone = Boolean(
+ activeLayer.toneEnabled && layerSourceCanvasesRef.current?.get(activeLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+ const displayCanvas = layerCanvasesRef.current.get(activeLayerId);
+
+ const width = dimensions.width;
+ const height = dimensions.height;
+ if (width <= 0 || height <= 0) return;
+
+ let beforeImageData: ImageData;
+ if (isTone && sourceCanvas) {
+ const sCtx = get2DContext(sourceCanvas);
+ if (!sCtx) return;
+ beforeImageData = sCtx.getImageData(0, 0, sourceCanvas.width, sourceCanvas.height);
+ } else {
+ const raw = grid.readImageData(activeLayerId, 0, 0, width, height);
+ beforeImageData = new ImageData(new Uint8ClampedArray(raw.data), width, height);
+ }
+
+ const rawFiltered = applyFilter(
+ new ImageData(
+ new Uint8ClampedArray(beforeImageData.data),
+ beforeImageData.width,
+ beforeImageData.height
+ ),
+ type,
+ params
+ );
+
+ let finalImageData = rawFiltered;
+ if (selection) {
+ const selMask = createSelectionMask(selection, width, height);
+ if (selMask) {
+ finalImageData = new ImageData(new Uint8ClampedArray(beforeImageData.data), width, height);
+ const src = beforeImageData.data;
+ const flt = rawFiltered.data;
+ const dst = finalImageData.data;
+ for (let i = 0; i < selMask.length; i++) {
+ const m = selMask[i];
+ if (m === 0) continue;
+ const p = i * 4;
+ if (m === 255) {
+ dst[p] = flt[p];
+ dst[p + 1] = flt[p + 1];
+ dst[p + 2] = flt[p + 2];
+ dst[p + 3] = flt[p + 3];
+ } else {
+ const a = m / 255;
+ const inv = 1 - a;
+ dst[p] = Math.round(src[p] * inv + flt[p] * a);
+ dst[p + 1] = Math.round(src[p + 1] * inv + flt[p + 1] * a);
+ dst[p + 2] = Math.round(src[p + 2] * inv + flt[p + 2] * a);
+ dst[p + 3] = Math.round(src[p + 3] * inv + flt[p + 3] * a);
+ }
+ }
+ }
+ }
+
+ const isMono = colorMode === 'monochrome' || activeLayer.expressionColor === 'monochrome';
+ const targetFormat = isMono ? 'monochrome-1bit' : 'color-32bit';
+
+ if (isTone && sourceCanvas) {
+ get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
+ const effDisplay = displayCanvas || materializeLayerCanvas(activeLayerId);
+ if (effDisplay) {
+ applyLayerEffects(sourceCanvas, effDisplay, activeLayer, dimensions.dpi ?? 600);
+ grid.ingestCanvas(activeLayerId, effDisplay, targetFormat);
+ }
+ } else {
+ grid.writeImageData(activeLayerId, finalImageData, 0, 0, targetFormat);
+ if (displayCanvas) {
+ get2DContext(displayCanvas)?.putImageData(finalImageData, 0, 0);
+ releaseLayerCanvas(activeLayerId);
+ }
+ if (sourceCanvas) {
+ get2DContext(sourceCanvas)?.putImageData(finalImageData, 0, 0);
+ }
+ }
+
+ pushHistoryStepRef.current?.(
+ 'filter',
+ `Filter: ${type.replace('-', ' ')}`,
+ beforeImageData,
+ finalImageData,
+ activeLayerId
+ );
+ grid.notifyChange(true);
+ updateLayerThumbnail(activeLayerId, true);
+ showToast(`Filter applied: ${type.replace('-', ' ')}`);
+ },
+ [
+ hasOpenDocument,
+ activeLayer,
+ activeLayerId,
+ selection,
+ dimensions.width,
+ dimensions.height,
+ dimensions.dpi,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ materializeLayerCanvas,
+ releaseLayerCanvas,
+ colorMode,
+ pushHistoryStepRef,
+ updateLayerThumbnail,
+ showToast,
+ ]
+ );
+
+ const getTonalLabel = useCallback((type: TonalCorrectionType) => {
+ switch (type) {
+ case 'brightness-contrast':
+ return 'Brightness/Contrast';
+ case 'binarization':
+ return 'Binarization';
+ case 'hue-saturation':
+ return 'Hue/Saturation/Luminosity';
+ case 'posterization':
+ return 'Posterization';
+ case 'level-correction':
+ return 'Level Correction';
+ case 'reverse-gradient':
+ return 'Reverse Gradient';
+ default:
+ return 'Tonal Correction';
+ }
+ }, []);
+
+ const handleOpenTonalModal = useCallback(
+ (type: TonalCorrectionType) => {
+ if (
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.locked ||
+ activeLayer.type !== 'raster'
+ ) {
+ return;
+ }
+ if (selection?.floating) {
+ handleCommitFloatingSelection();
+ }
+
+ const grid = documentStore.getActiveTileGrid();
+ let targetLayerId = activeLayerId;
+ let targetLayer = layers.find((l) => l.id === targetLayerId);
+ const hasPixels = grid.hasLayerTiles(targetLayerId);
+
+ if (!hasPixels) {
+ const candidate = layers.find(
+ (l) =>
+ l.id !== targetLayerId &&
+ l.type === 'raster' &&
+ l.visible &&
+ grid.hasLayerTiles(l.id)
+ );
+ if (candidate) {
+ targetLayerId = candidate.id;
+ targetLayer = candidate;
+ setActiveLayerId(candidate.id);
+ showToast(`Switched to "${candidate.name}" (active layer had no pixels)`);
+ } else {
+ showToast('Selected layer is empty. Draw or open an image first.');
+ return;
+ }
+ }
+
+ const displayCanvas = materializeLayerCanvas(targetLayerId);
+ const isTone = Boolean(
+ targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+
+ if (!canvas) {
+ showToast('Canvas not available for active layer.');
+ return;
+ }
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const selectionMask = createSelectionMask(selection, canvas.width, canvas.height);
+ const bounds = getProcessingBounds(selection, canvas.width, canvas.height);
+
+ uiStoreActions.setTonalModalState({
+ isOpen: true,
+ type,
+ targetLayerId,
+ beforeImageData,
+ selectionMask,
+ bounds,
+ });
+ },
+ [
+ hasOpenDocument,
+ activeLayer,
+ activeLayerId,
+ layers,
+ selection,
+ handleCommitFloatingSelection,
+ materializeLayerCanvas,
+ layerSourceCanvasesRef,
+ setActiveLayerId,
+ showToast,
+ ]
+ );
+
+ const handleTonalPreviewChange = useCallback(
+ (type: TonalCorrectionType, params: AnyTonalParams, enabled: boolean) => {
+ const state = useUiStore.getState().tonalModalState;
+ if (!state.isOpen || !state.beforeImageData) return;
+ const targetLayerId = state.targetLayerId;
+ const targetLayer = layers.find((l) => l.id === targetLayerId);
+ const isTone = Boolean(
+ targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
+ const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ if (enabled) {
+ const previewData = ctx.createImageData(canvas.width, canvas.height);
+ applyTonalFilter(
+ state.beforeImageData,
+ previewData,
+ type,
+ params,
+ state.selectionMask,
+ state.bounds
+ );
+ ctx.putImageData(previewData, 0, 0);
+ } else {
+ ctx.putImageData(state.beforeImageData, 0, 0);
+ }
+
+ if (isTone && sourceCanvas && displayCanvas) {
+ applyScreentone(sourceCanvas, displayCanvas, {
+ frequency: targetLayer?.toneFrequency ?? 60,
+ angle: targetLayer?.toneAngle ?? 45,
+ dotShape: targetLayer?.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ });
+ }
+
+ if (displayCanvas) {
+ const isMono =
+ colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(targetLayerId, displayCanvas, isMono ? 'monochrome-1bit' : 'color-32bit');
+ documentStore.getActiveTileGrid().notifyChange(true);
+ }
+ },
+ [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi]
+ );
+
+ const handleTonalApply = useCallback(
+ (type: TonalCorrectionType, params: AnyTonalParams) => {
+ const state = useUiStore.getState().tonalModalState;
+ if (!state.isOpen || !state.beforeImageData) return;
+ const targetLayerId = state.targetLayerId;
+ const targetLayer = layers.find((l) => l.id === targetLayerId);
+ const isTone = Boolean(
+ targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
+ const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const finalData = ctx.createImageData(canvas.width, canvas.height);
+ applyTonalFilter(
+ state.beforeImageData,
+ finalData,
+ type,
+ params,
+ state.selectionMask,
+ state.bounds
+ );
+ ctx.putImageData(finalData, 0, 0);
+
+ if (isTone && sourceCanvas && displayCanvas) {
+ applyScreentone(sourceCanvas, displayCanvas, {
+ frequency: targetLayer?.toneFrequency ?? 60,
+ angle: targetLayer?.toneAngle ?? 45,
+ dotShape: targetLayer?.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ });
+ }
+
+ updateLayerThumbnail(targetLayerId, true);
+ const label = getTonalLabel(type);
+ pushHistoryStepRef.current?.(
+ 'tonal-correction',
+ label,
+ state.beforeImageData,
+ finalData,
+ targetLayerId
+ );
+ documentStore.getActiveTileGrid().notifyChange(true);
+ if (!isTone) {
+ releaseLayerCanvas(targetLayerId);
+ }
+
+ uiStoreActions.setTonalModalState({
+ isOpen: false,
+ type,
+ targetLayerId: '',
+ beforeImageData: null,
+ selectionMask: null,
+ bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
+ });
+ showToast(`Applied ${label}`);
+ },
+ [
+ layers,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ dimensions.dpi,
+ updateLayerThumbnail,
+ getTonalLabel,
+ pushHistoryStepRef,
+ releaseLayerCanvas,
+ showToast,
+ ]
+ );
+
+ const handleTonalCancel = useCallback(() => {
+ const state = useUiStore.getState().tonalModalState;
+ if (!state.isOpen) return;
+ if (state.beforeImageData) {
+ const targetLayerId = state.targetLayerId;
+ const targetLayer = layers.find((l) => l.id === targetLayerId);
+ const isTone = Boolean(
+ targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ const displayCanvas = layerCanvasesRef.current.get(targetLayerId);
+ const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+ if (canvas) {
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ ctx.putImageData(state.beforeImageData, 0, 0);
+ if (isTone && sourceCanvas && displayCanvas) {
+ applyScreentone(sourceCanvas, displayCanvas, {
+ frequency: targetLayer?.toneFrequency ?? 60,
+ angle: targetLayer?.toneAngle ?? 45,
+ dotShape: targetLayer?.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ });
+ }
+ if (displayCanvas) {
+ const isMono =
+ colorMode === 'monochrome' || targetLayer?.expressionColor === 'monochrome';
+ documentStore
+ .getActiveTileGrid()
+ .ingestCanvas(
+ targetLayerId,
+ displayCanvas,
+ isMono ? 'monochrome-1bit' : 'color-32bit'
+ );
+ documentStore.getActiveTileGrid().notifyChange(true);
+ if (!isTone) {
+ releaseLayerCanvas(targetLayerId);
+ }
+ }
+ }
+ }
+ }
+
+ uiStoreActions.setTonalModalState({
+ isOpen: false,
+ type: state.type,
+ targetLayerId: '',
+ beforeImageData: null,
+ selectionMask: null,
+ bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
+ });
+ }, [layers, colorMode, layerCanvasesRef, layerSourceCanvasesRef, dimensions.dpi, releaseLayerCanvas]);
+
+ const handleApplyReverseGradient = useCallback(() => {
+ if (
+ !hasOpenDocument ||
+ !activeLayer ||
+ activeLayer.locked ||
+ activeLayer.type !== 'raster'
+ ) {
+ return;
+ }
+ if (selection?.floating) {
+ handleCommitFloatingSelection();
+ }
+
+ let targetLayerId = activeLayerId;
+ let targetLayer = layers.find((l) => l.id === targetLayerId);
+ let displayCanvas = layerCanvasesRef.current.get(targetLayerId);
+
+ let hasPixels = false;
+ if (displayCanvas) {
+ const dCtx = get2DContext(displayCanvas);
+ if (dCtx) {
+ const dData = dCtx.getImageData(0, 0, displayCanvas.width, displayCanvas.height).data;
+ for (let i = 3; i < dData.length; i += 4) {
+ if (dData[i] > 0) {
+ hasPixels = true;
+ break;
+ }
+ }
+ }
+ }
+
+ if (!hasPixels) {
+ const candidate = layers.find((l) => {
+ if (l.id === targetLayerId || l.type !== 'raster' || !l.visible) return false;
+ const c = layerCanvasesRef.current.get(l.id);
+ if (!c) return false;
+ const cCtx = get2DContext(c);
+ if (!cCtx) return false;
+ const cData = cCtx.getImageData(0, 0, c.width, c.height).data;
+ for (let j = 3; j < cData.length; j += 4) {
+ if (cData[j] > 0) return true;
+ }
+ return false;
+ });
+
+ if (candidate) {
+ targetLayerId = candidate.id;
+ targetLayer = candidate;
+ displayCanvas = layerCanvasesRef.current.get(candidate.id);
+ setActiveLayerId(candidate.id);
+ showToast(`Switched to "${candidate.name}" (active layer had no pixels)`);
+ } else {
+ showToast('Selected layer is empty. Draw or open an image first.');
+ return;
+ }
+ }
+
+ const isTone = Boolean(
+ targetLayer?.toneEnabled && layerSourceCanvasesRef.current?.get(targetLayerId)
+ );
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(targetLayerId);
+ const canvas = isTone && sourceCanvas ? sourceCanvas : displayCanvas;
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const afterImageData = ctx.createImageData(canvas.width, canvas.height);
+ afterImageData.data.set(beforeImageData.data);
+
+ const mask = createSelectionMask(selection, canvas.width, canvas.height);
+ const bounds = getProcessingBounds(selection, canvas.width, canvas.height);
+
+ applyReverseGradient(beforeImageData, afterImageData, mask, bounds);
+ ctx.putImageData(afterImageData, 0, 0);
+
+ if (isTone && sourceCanvas && displayCanvas) {
+ applyScreentone(sourceCanvas, displayCanvas, {
+ frequency: targetLayer?.toneFrequency ?? 60,
+ angle: targetLayer?.toneAngle ?? 45,
+ dotShape: targetLayer?.toneDotShape ?? 'circle',
+ dpi: dimensions.dpi ?? 600,
+ });
+ }
+
+ updateLayerThumbnail(targetLayerId, true);
+ pushHistoryStepRef.current?.(
+ 'tonal-correction',
+ 'Reverse Gradient',
+ beforeImageData,
+ afterImageData,
+ targetLayerId
+ );
+ showToast('Inverted colors (Reverse Gradient)');
+ }, [
+ hasOpenDocument,
+ activeLayer,
+ activeLayerId,
+ layers,
+ selection,
+ handleCommitFloatingSelection,
+ layerCanvasesRef,
+ layerSourceCanvasesRef,
+ dimensions.dpi,
+ updateLayerThumbnail,
+ pushHistoryStepRef,
+ setActiveLayerId,
+ showToast,
+ ]);
+
+ const handleApplyMangaEffects = useCallback(
+ (type: 'saturated' | 'stream', options: SaturatedLinesOptions | StreamLinesOptions) => {
+ const canvas = getActiveCanvas();
+ if (!canvas) return;
+ const ctx = get2DContext(canvas);
+ if (!ctx) return;
+
+ const beforeImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ const sourceCanvas = layerSourceCanvasesRef.current?.get(activeLayerId);
+
+ const renderOn = (target: HTMLCanvasElement) => {
+ const c = get2DContext(target);
+ if (!c) return;
+ if (type === 'saturated') {
+ renderSaturatedLines(c, canvas.width, canvas.height, options as SaturatedLinesOptions);
+ } else {
+ renderStreamLines(c, canvas.width, canvas.height, options as StreamLinesOptions);
+ }
+ };
+
+ renderOn(canvas);
+ if (sourceCanvas) renderOn(sourceCanvas);
+
+ const afterImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ updateLayerThumbnail(activeLayerId, true);
+ pushHistoryStepRef.current?.(
+ 'brush',
+ `Manga Effect (${type})`,
+ beforeImageData,
+ afterImageData,
+ activeLayerId
+ );
+ documentStore.getActiveTileGrid().notifyChange(true);
+ showToast(`Applied manga ${type} lines`);
+ },
+ [
+ getActiveCanvas,
+ activeLayerId,
+ layerSourceCanvasesRef,
+ updateLayerThumbnail,
+ pushHistoryStepRef,
+ showToast,
+ ]
+ );
+
+ const handleInsert3DRasterLayer = useCallback(
+ (layer: LayerItem, canvas: HTMLCanvasElement) => {
+ if (layer.type === 'folder') {
+ addLayer('folder', layer.parentId, layer.name, layer.id);
+ } else {
+ pasteLayerFromCanvas(canvas, layer.name, layer.blendMode, layer.opacity, layer.id, layer);
+ }
+ showToast(`Added 3D layer "${layer.name}".`);
+ },
+ [addLayer, pasteLayerFromCanvas, showToast]
+ );
+
+ const handleFillScreentone = useCallback(() => {
+ uiStoreActions.setToneModalOpen(true);
+ }, []);
+
+ const handleConfirmTone = useCallback(
+ (settings: SimpleToneSettings) => {
+ uiStoreActions.setToneModalOpen(false);
+ const { id, canvas } = fillScreentoneSelection(
+ selection,
+ settings.density,
+ settings.frequency,
+ settings.angle,
+ settings.dotShape,
+ settings.densityType
+ );
+ const ctx = get2DContext(canvas);
+ if (ctx) {
+ const afterData = ctx.getImageData(0, 0, canvas.width, canvas.height);
+ pushHistoryStepRef.current?.(
+ 'screentone',
+ `Screentone (${settings.density}%)`,
+ null,
+ afterData,
+ id
+ );
+ }
+ showToast(`Created Screentone Layer (${settings.density}%)`);
+ },
+ [selection, fillScreentoneSelection, pushHistoryStepRef, showToast]
+ );
+
+ const handleApplyExpressionColor = useCallback(
+ (layerId: string) => {
+ const result = applyExpressionColorOfPreview(layerId);
+ if (result && result.beforeImageData && result.afterImageData) {
+ pushHistoryStepRef.current?.(
+ 'expression-color',
+ 'Apply Expression Color',
+ result.beforeImageData,
+ result.afterImageData,
+ layerId
+ );
+ showToast('Applied expression color to layer');
+ }
+ },
+ [applyExpressionColorOfPreview, pushHistoryStepRef, showToast]
+ );
+
+ const handleApplyLayerColor = useCallback(
+ (layerId: string) => {
+ const result = applyLayerColorPermanently(layerId);
+ if (result && result.beforeImageData && result.afterImageData) {
+ pushHistoryStepRef.current?.(
+ 'layer-color',
+ 'Apply Layer Color Tint',
+ result.beforeImageData,
+ result.afterImageData,
+ layerId
+ );
+ showToast('Applied tint to layer permanently');
+ }
+ },
+ [applyLayerColorPermanently, pushHistoryStepRef, showToast]
+ );
+
+ const handleConvertLayer = useCallback(
+ (
+ layerId: string,
+ targetMode: ExpressionColor,
+ options?: { threshold?: number; expressBlack?: boolean; expressWhite?: boolean }
+ ) => {
+ const result = convertLayer(layerId, targetMode, options);
+ if (result && result.beforeImageData && result.afterImageData) {
+ pushHistoryStepRef.current?.(
+ 'layer-convert',
+ `Convert to ${targetMode.toUpperCase()}`,
+ result.beforeImageData,
+ result.afterImageData,
+ layerId
+ );
+ showToast(`Converted layer to ${targetMode}`);
+ }
+ },
+ [convertLayer, pushHistoryStepRef, showToast]
+ );
+
+ return {
+ handleOpenAdjustmentModal,
+ handleApplyAdjustment,
+ handleOpenLayerStylesModal,
+ handleApplyLayerStyles,
+ handleApplyFilter,
+ handleOpenTonalModal,
+ handleTonalPreviewChange,
+ handleTonalApply,
+ handleTonalCancel,
+ handleApplyReverseGradient,
+ handleApplyMangaEffects,
+ handleInsert3DRasterLayer,
+ handleFillScreentone,
+ handleConfirmTone,
+ handleApplyExpressionColor,
+ handleApplyLayerColor,
+ handleConvertLayer,
+ };
+}
diff --git a/src/stores/__tests__/storesAndRerenderIsolation.test.tsx b/src/stores/__tests__/storesAndRerenderIsolation.test.tsx
new file mode 100644
index 0000000..09742b0
--- /dev/null
+++ b/src/stores/__tests__/storesAndRerenderIsolation.test.tsx
@@ -0,0 +1,638 @@
+import React, { Profiler, act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ createStore,
+ shallowEqual,
+ useToolStore,
+ toolStoreActions,
+ useDocumentStore,
+ documentStoreActions,
+ selectHasOpenDocument,
+ useUiStore,
+ uiStoreActions,
+ selectIsAnyModalOpen,
+} from '../index';
+import { Header } from '../../components/Header';
+import { RightSidebar, RightSidebarColorSection } from '../../components/RightSidebar';
+import { ToolStrip } from '../../components/ToolStrip';
+import { LayerItem, MenuSection } from '../../types/editor';
+
+interface MiniNode {
+ nodeType: number;
+ nodeName: string;
+ parentNode: MiniElement | null;
+ ownerDocument: MiniDocument;
+}
+
+class MiniTextNode implements MiniNode {
+ public nodeType = 3;
+ public nodeName = '#text';
+ public nodeValue: string;
+ public parentNode: MiniElement | null = null;
+ public ownerDocument: MiniDocument;
+
+ constructor(text: string, ownerDocument: MiniDocument) {
+ this.nodeValue = text;
+ this.ownerDocument = ownerDocument;
+ }
+}
+
+class MiniCommentNode implements MiniNode {
+ public nodeType = 8;
+ public nodeName = '#comment';
+ public nodeValue: string;
+ public parentNode: MiniElement | null = null;
+ public ownerDocument: MiniDocument;
+
+ constructor(text: string, ownerDocument: MiniDocument) {
+ this.nodeValue = text;
+ this.ownerDocument = ownerDocument;
+ }
+}
+
+class MiniElement extends EventTarget implements MiniNode {
+ public nodeType = 1;
+ public nodeName: string;
+ public tagName: string;
+ public namespaceURI = 'http://www.w3.org/1999/xhtml';
+ public ownerDocument: MiniDocument;
+ public parentNode: MiniElement | null = null;
+ public childNodes: MiniNode[] = [];
+ public style: Record<string, string> = {};
+ public isContentEditable = false;
+ public clientWidth = 220;
+ public clientHeight = 600;
+ public width = 160;
+ public height = 160;
+ public value = '';
+ public checked = false;
+ public disabled = false;
+ public className = '';
+ public selected = false;
+ public defaultSelected = false;
+ private attrs = new Map<string, string>();
+
+ get options(): MiniElement[] {
+ const out: MiniElement[] = [];
+ const walk = (nodes: MiniNode[]) => {
+ for (const n of nodes) {
+ if (n instanceof MiniElement) {
+ if (n.tagName === 'OPTION') out.push(n);
+ walk(n.childNodes);
+ }
+ }
+ };
+ walk(this.childNodes);
+ return out;
+ }
+
+ constructor(tag: string, ownerDocument: MiniDocument) {
+ super();
+ this.nodeName = tag.toUpperCase();
+ this.tagName = tag.toUpperCase();
+ this.ownerDocument = ownerDocument;
+ }
+
+ get firstChild(): MiniNode | null {
+ return this.childNodes[0] ?? null;
+ }
+
+ appendChild<T extends MiniNode>(child: T): T {
+ if (child.parentNode) {
+ child.parentNode.removeChild(child);
+ }
+ child.parentNode = this;
+ this.childNodes.push(child);
+ return child;
+ }
+
+ removeChild<T extends MiniNode>(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 MiniNode>(newNode: T, refNode: MiniNode | null): T {
+ if (newNode.parentNode) {
+ newNode.parentNode.removeChild(newNode);
+ }
+ newNode.parentNode = this;
+ const idx = refNode ? this.childNodes.indexOf(refNode) : -1;
+ if (idx >= 0) {
+ this.childNodes.splice(idx, 0, newNode);
+ } else {
+ this.childNodes.push(newNode);
+ }
+ return newNode;
+ }
+
+ setAttribute(k: string, v: string): void {
+ this.attrs.set(k, String(v));
+ }
+
+ getAttribute(k: string): string | null {
+ return this.attrs.get(k) ?? null;
+ }
+
+ removeAttribute(k: string): void {
+ this.attrs.delete(k);
+ }
+
+ contains(target: MiniNode | null): boolean {
+ if (!target) return false;
+ if (target === this) return true;
+ for (const c of this.childNodes) {
+ if (c === target) return true;
+ if (c instanceof MiniElement && c.contains(target)) return true;
+ }
+ return false;
+ }
+
+ getBoundingClientRect(): DOMRect {
+ return {
+ left: 0,
+ top: 0,
+ width: this.clientWidth,
+ height: this.clientHeight,
+ right: this.clientWidth,
+ bottom: this.clientHeight,
+ x: 0,
+ y: 0,
+ toJSON: () => ({}),
+ } as DOMRect;
+ }
+
+ getContext(): Record<string, unknown> {
+ const noop = () => {};
+ return {
+ clearRect: noop,
+ fillRect: noop,
+ strokeRect: noop,
+ beginPath: noop,
+ closePath: noop,
+ moveTo: noop,
+ lineTo: noop,
+ arc: noop,
+ fill: noop,
+ stroke: noop,
+ save: noop,
+ restore: noop,
+ scale: noop,
+ translate: noop,
+ rotate: noop,
+ setTransform: noop,
+ resetTransform: noop,
+ drawImage: noop,
+ putImageData: noop,
+ createImageData: (w: number, h: number) => ({
+ width: w,
+ height: h,
+ data: new Uint8ClampedArray(w * h * 4),
+ }),
+ getImageData: (
+ _x: number,
+ _y: number,
+ w: number,
+ h: number
+ ) => ({
+ width: w,
+ height: h,
+ data: new Uint8ClampedArray(w * h * 4),
+ }),
+ createLinearGradient: () => ({ addColorStop: noop }),
+ createRadialGradient: () => ({ addColorStop: noop }),
+ createConicGradient: () => ({ addColorStop: noop }),
+ clip: noop,
+ rect: noop,
+ quadraticCurveTo: noop,
+ bezierCurveTo: noop,
+ setLineDash: noop,
+ fillText: noop,
+ strokeText: noop,
+ measureText: () => ({ width: 0 }),
+ };
+ }
+}
+
+interface MiniDocument {
+ nodeType: number;
+ nodeName: string;
+ documentElement: MiniElement;
+ body: MiniElement;
+ activeElement: MiniElement;
+ defaultView: Record<string, unknown>;
+ createElement: (tag: string) => MiniElement;
+ createElementNS: (_ns: string, tag: string) => MiniElement;
+ createTextNode: (text: string) => MiniTextNode;
+ createComment: (text: string) => MiniCommentNode;
+ querySelector: () => null;
+ addEventListener: EventTarget['addEventListener'];
+ removeEventListener: EventTarget['removeEventListener'];
+ dispatchEvent: EventTarget['dispatchEvent'];
+}
+
+function installMiniDom(): { container: MiniElement; cleanup: () => void } {
+ 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,
+ ResizeObserver: g.ResizeObserver,
+ 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 = {
+ nodeType: 9,
+ nodeName: '#document',
+ documentElement: null as unknown as MiniElement,
+ body: null as unknown as MiniElement,
+ activeElement: null as unknown as MiniElement,
+ defaultView: null as unknown as Record<string, unknown>,
+ createElement: (tag: string) => new MiniElement(tag, mockDoc),
+ createElementNS: (_ns: string, tag: string) => new MiniElement(tag, mockDoc),
+ createTextNode: (text: string) => new MiniTextNode(text, mockDoc),
+ createComment: (text: string) => new MiniCommentNode(text, mockDoc),
+ querySelector: () => null,
+ addEventListener: docTarget.addEventListener.bind(docTarget),
+ removeEventListener: docTarget.removeEventListener.bind(docTarget),
+ dispatchEvent: docTarget.dispatchEvent.bind(docTarget),
+ } as MiniDocument;
+
+ mockDoc.documentElement = new MiniElement('html', mockDoc);
+ mockDoc.body = new MiniElement('body', mockDoc);
+ mockDoc.documentElement.appendChild(mockDoc.body);
+ mockDoc.activeElement = mockDoc.body;
+
+ class MockHTMLIFrameElement extends MiniElement {}
+ class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ }
+
+ let rafSeq = 1;
+ const rafMock = (_cb: FrameRequestCallback) => rafSeq++;
+ const cancelRafMock = (_id: number) => {};
+
+ const mockWin: Record<string, unknown> = {
+ innerWidth: 1600,
+ innerHeight: 900,
+ devicePixelRatio: 1,
+ document: mockDoc,
+ Node: MiniElement,
+ Element: MiniElement,
+ HTMLElement: MiniElement,
+ SVGElement: MiniElement,
+ HTMLIFrameElement: MockHTMLIFrameElement,
+ Event,
+ CustomEvent,
+ addEventListener: winTarget.addEventListener.bind(winTarget),
+ removeEventListener: winTarget.removeEventListener.bind(winTarget),
+ dispatchEvent: winTarget.dispatchEvent.bind(winTarget),
+ requestAnimationFrame: rafMock,
+ cancelAnimationFrame: cancelRafMock,
+ setTimeout: globalThis.setTimeout.bind(globalThis),
+ clearTimeout: globalThis.clearTimeout.bind(globalThis),
+ };
+ mockDoc.defaultView = mockWin;
+
+ g.window = mockWin;
+ g.document = mockDoc;
+ g.HTMLElement = MiniElement;
+ g.Node = MiniElement;
+ g.Element = MiniElement;
+ g.ResizeObserver = MockResizeObserver;
+ g.requestAnimationFrame = rafMock;
+ g.cancelAnimationFrame = cancelRafMock;
+
+ const container = new MiniElement('div', mockDoc);
+ mockDoc.body.appendChild(container);
+
+ return {
+ container,
+ cleanup: () => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) {
+ delete g[k];
+ } else {
+ g[k] = v;
+ }
+ }
+ },
+ };
+}
+
+describe('External stores (useToolStore, useDocumentStore, useUiStore)', () => {
+ beforeEach(() => {
+ useToolStore.reset();
+ useDocumentStore.reset();
+ useUiStore.reset();
+ });
+
+ it('createStore notifies only when values actually change and shallowEqual compares objects', () => {
+ const store = createStore(() => ({ count: 0, name: 'init' }));
+ const spy = vi.fn();
+ const unsub = store.subscribe(spy);
+
+ store.setState({ count: 0 });
+ expect(spy).toHaveBeenCalledTimes(0);
+
+ store.setState({ count: 1 });
+ expect(spy).toHaveBeenCalledTimes(1);
+ expect(store.getState().count).toBe(1);
+
+ expect(shallowEqual({ a: 1, b: 'x' }, { a: 1, b: 'x' })).toBe(true);
+ expect(shallowEqual({ a: 1, b: 'x' }, { a: 2, b: 'x' })).toBe(false);
+ unsub();
+ });
+
+ it('useToolStore manages tool switching, brush updates, colors, and transparent ink', () => {
+ expect(useToolStore.getState().tool).toBe('brush');
+
+ toolStoreActions.updateBrushSettings({ size: 24, opacity: 0.75 });
+ expect(useToolStore.getState().brushSettings.size).toBe(24);
+ expect(useToolStore.getState().brushSettings.opacity).toBe(0.75);
+
+ toolStoreActions.setPrimaryColor('#ff0055');
+ expect(useToolStore.getState().primaryColor).toBe('#ff0055');
+ expect(useToolStore.getState().brushSettings.color).toBe('#ff0055');
+ expect(useToolStore.getState().recentColors[0]).toBe('#ff0055');
+
+ toolStoreActions.swapColors();
+ expect(useToolStore.getState().primaryColor).toBe('#ffffff');
+ expect(useToolStore.getState().secondaryColor).toBe('#ff0055');
+
+ const isTransparent = toolStoreActions.toggleTransparentColor();
+ expect(isTransparent).toBe(true);
+ expect(useToolStore.getState().isTransparentColor).toBe(true);
+ expect(useToolStore.getState().brushSettings.isTransparentInk).toBe(true);
+
+ // Switching to eraser and then picking a primary color returns to brush
+ toolStoreActions.selectTool('eraser');
+ expect(useToolStore.getState().tool).toBe('eraser');
+ toolStoreActions.setPrimaryColor('#112233');
+ expect(useToolStore.getState().tool).toBe('brush');
+ expect(useToolStore.getState().isTransparentColor).toBe(false);
+
+ // Monochrome mode enforcement
+ documentStoreActions.setColorMode('monochrome');
+ toolStoreActions.setPrimaryColor('#222222');
+ expect(useToolStore.getState().primaryColor).toBe('#000000');
+
+ // Quick modifiers
+ toolStoreActions.setQuickModifiers({ isAltActive: true });
+ expect(useToolStore.getState().quickModifiers.isAltActive).toBe(true);
+ });
+
+ it('useDocumentStore manages tabs, dimensions, active layer, and soft proof metadata', () => {
+ expect(selectHasOpenDocument(useDocumentStore.getState())).toBe(false);
+
+ documentStoreActions.setDocuments([
+ {
+ id: 'doc-1',
+ name: 'Manga Page 1',
+ dimensions: { width: 2480, height: 3508, dpi: 600 },
+ colorMode: 'monochrome',
+ layers: [],
+ activeLayerId: 'layer-1',
+ },
+ ]);
+ documentStoreActions.setActiveDocumentId('doc-1');
+ documentStoreActions.setDimensions({ width: 2480, height: 3508, dpi: 600 });
+ documentStoreActions.setActiveLayerId('layer-1');
+
+ expect(selectHasOpenDocument(useDocumentStore.getState())).toBe(true);
+ expect(useDocumentStore.getState().dimensions.dpi).toBe(600);
+ expect(useDocumentStore.getState().activeLayerId).toBe('layer-1');
+
+ documentStoreActions.toggleSoftProof();
+ documentStoreActions.toggleGamutWarning();
+ documentStoreActions.setProofStandard('japan-color-2001');
+ expect(useDocumentStore.getState().softProofSettings).toMatchObject({
+ enabled: true,
+ gamutWarning: true,
+ standard: 'japan-color-2001',
+ });
+ });
+
+ it('useUiStore manages modals, panel visibility, and toast lifecycle', () => {
+ expect(selectIsAnyModalOpen(useUiStore.getState())).toBe(false);
+
+ uiStoreActions.setSettingsModalOpen(true);
+ expect(selectIsAnyModalOpen(useUiStore.getState())).toBe(true);
+ uiStoreActions.setSettingsModalOpen(false);
+ expect(selectIsAnyModalOpen(useUiStore.getState())).toBe(false);
+
+ uiStoreActions.toggleAllPanels();
+ expect(useUiStore.getState().isLeftPanelHidden).toBe(true);
+ expect(useUiStore.getState().isRightSidebarHidden).toBe(true);
+
+ uiStoreActions.toggleAllPanels();
+ expect(useUiStore.getState().isLeftPanelHidden).toBe(false);
+ expect(useUiStore.getState().isRightSidebarHidden).toBe(false);
+
+ uiStoreActions.showToast('Saved');
+ expect(useUiStore.getState().toastMessage).toBe('Saved');
+ uiStoreActions.clearToast();
+ expect(useUiStore.getState().toastMessage).toBeNull();
+ });
+});
+
+describe('Zero-rerender isolation on brush size and color changes', () => {
+ let dom: { container: MiniElement; cleanup: () => void };
+ let root: Root | null = null;
+
+ beforeEach(() => {
+ useToolStore.reset();
+ useDocumentStore.reset();
+ useUiStore.reset();
+ dom = installMiniDom();
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => {
+ root?.unmount();
+ });
+ root = null;
+ }
+ dom.cleanup();
+ });
+
+ it('changing brush size or color triggers ZERO re-renders of Header (menu bar) or RightSidebar (layer list)', () => {
+ const noop = () => {};
+ const layers: LayerItem[] = [
+ {
+ id: 'layer-1',
+ name: 'Ink Layer',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ collapsed: false,
+ parentId: null,
+ },
+ {
+ id: 'layer-bg',
+ name: 'Paper',
+ type: 'raster',
+ visible: true,
+ opacity: 1,
+ blendMode: 'normal',
+ locked: false,
+ collapsed: false,
+ parentId: null,
+ },
+ ];
+ const menuSections: MenuSection[] = [
+ { id: 'file', label: 'File', items: [{ id: 'f-new', label: 'New', onClick: noop }] },
+ { id: 'edit', label: 'Edit', items: [{ id: 'e-undo', label: 'Undo', onClick: noop }] },
+ ];
+
+ let headerRenders = 0;
+ let layerListRenders = 0;
+ let colorPanelRenders = 0;
+ let brushObserverRenders = 0;
+ let lastObservedSize = 0;
+ let lastObservedColor = '';
+
+ const BrushSizeObserver: React.FC = () => {
+ brushObserverRenders += 1;
+ lastObservedSize = useToolStore((s) => s.brushSettings.size);
+ lastObservedColor = useToolStore((s) => s.primaryColor);
+ return React.createElement('span', null, `${lastObservedSize}:${lastObservedColor}`);
+ };
+
+ const TestShell: React.FC = () =>
+ React.createElement(
+ 'div',
+ null,
+ React.createElement(
+ Profiler,
+ {
+ id: 'Header',
+ onRender: () => {
+ headerRenders += 1;
+ },
+ },
+ React.createElement(Header, {
+ canUndo: true,
+ canRedo: false,
+ onUndo: noop,
+ onRedo: noop,
+ zoom: 1,
+ onZoomIn: noop,
+ onZoomOut: noop,
+ onResetZoom: noop,
+ rotation: 0,
+ onResetRotation: noop,
+ menuSections,
+ hasOpenDocument: true,
+ })
+ ),
+ React.createElement(ToolStrip, {}),
+ React.createElement(BrushSizeObserver, {}),
+ React.createElement(
+ Profiler,
+ {
+ id: 'ColorPanelSection',
+ onRender: () => {
+ colorPanelRenders += 1;
+ },
+ },
+ React.createElement(RightSidebarColorSection, {
+ colorMode: 'color',
+ containerWidth: 180,
+ })
+ ),
+ React.createElement(
+ Profiler,
+ {
+ id: 'RightSidebarLayerList',
+ onRender: () => {
+ layerListRenders += 1;
+ },
+ },
+ React.createElement(RightSidebar, {
+ hasOpenDocument: true,
+ hideColorPanel: true,
+ colorMode: 'color',
+ historyList: [],
+ historyIndex: -1,
+ onJumpToHistory: noop,
+ canUndo: false,
+ canRedo: false,
+ onUndo: noop,
+ onRedo: noop,
+ layers,
+ activeLayerId: 'layer-1',
+ selectedLayerIds: ['layer-1'],
+ onSelectLayer: noop,
+ onAddLayer: noop,
+ onDuplicateLayer: noop,
+ onDeleteLayer: noop,
+ onToggleVisibility: noop,
+ onSetOpacity: noop,
+ onSetBlendMode: noop,
+ onToggleLock: noop,
+ onToggleCollapse: noop,
+ onRenameLayer: noop,
+ onMoveLayerToFolder: noop,
+ width: 180,
+ })
+ )
+ );
+
+ act(() => {
+ root = createRoot(dom.container as unknown as Element);
+ root.render(React.createElement(TestShell));
+ });
+
+ expect(headerRenders).toBe(1);
+ expect(layerListRenders).toBe(1);
+ expect(colorPanelRenders).toBe(1);
+ expect(brushObserverRenders).toBe(1);
+
+ // Mutate brush size repeatedly -> neither Header, LayerList, nor ColorPanel should re-render
+ act(() => {
+ toolStoreActions.updateBrushSettings({ size: 12 });
+ toolStoreActions.updateBrushSettings({ size: 48 });
+ toolStoreActions.updateBrushSettings({ size: 96, opacity: 0.6 });
+ });
+
+ expect(headerRenders).toBe(1);
+ expect(layerListRenders).toBe(1);
+ expect(colorPanelRenders).toBe(1);
+
+ // Mutate primary color, secondary color, swap colors, toggle transparent ink
+ // -> ColorPanel updates, but Header (top menu bar) and LayerList still have ZERO re-renders
+ act(() => {
+ toolStoreActions.setPrimaryColor('#e11d48');
+ toolStoreActions.setSecondaryColor('#2563eb');
+ toolStoreActions.swapColors();
+ toolStoreActions.toggleTransparentColor();
+ });
+
+ expect(lastObservedSize).toBe(96);
+ expect(lastObservedColor).toBe('#2563eb');
+ expect(brushObserverRenders).toBeGreaterThan(1);
+ expect(colorPanelRenders).toBeGreaterThan(1);
+
+ // Critical acceptance check: Header (top menu bar) and RightSidebar (layer list) had ZERO re-renders!
+ expect(headerRenders).toBe(1);
+ expect(layerListRenders).toBe(1);
+ });
+});
diff --git a/src/stores/createStore.ts b/src/stores/createStore.ts
new file mode 100644
index 0000000..00baf04
--- /dev/null
+++ b/src/stores/createStore.ts
@@ -0,0 +1,118 @@
+import { useRef, useSyncExternalStore } from 'react';
+
+export type StoreListener = () => void;
+export type StateUpdater<T> = Partial<T> | ((prev: T) => Partial<T>);
+export type EqualityFn<U> = (a: U, b: U) => boolean;
+
+export interface StoreApi<T> {
+ getState: () => T;
+ setState: (partial: StateUpdater<T>) => void;
+ subscribe: (listener: StoreListener) => () => void;
+ reset: () => void;
+}
+
+export interface UseBoundStore<T> extends StoreApi<T> {
+ (): T;
+ <U>(selector: (state: T) => U, equalityFn?: EqualityFn<U>): U;
+}
+
+export function shallowEqual<T>(a: T, b: T): boolean {
+ if (Object.is(a, b)) return true;
+ if (typeof a !== 'object' || a === null || typeof b !== 'object' || b === null) {
+ return false;
+ }
+ const keysA = Object.keys(a as Record<string, unknown>);
+ const keysB = Object.keys(b as Record<string, unknown>);
+ if (keysA.length !== keysB.length) return false;
+ for (let i = 0; i < keysA.length; i++) {
+ const key = keysA[i];
+ if (
+ !Object.prototype.hasOwnProperty.call(b, key) ||
+ !Object.is((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])
+ ) {
+ return false;
+ }
+ }
+ return true;
+}
+
+export function createStore<T extends object>(initializer: () => T): UseBoundStore<T> {
+ let state: T = initializer();
+ const listeners = new Set<StoreListener>();
+
+ const getState = (): T => state;
+
+ const setState = (partial: StateUpdater<T>): void => {
+ const patch = typeof partial === 'function' ? partial(state) : partial;
+ if (!patch || Object.is(patch, state)) return;
+
+ let changed = false;
+ for (const key of Object.keys(patch) as Array<keyof T>) {
+ if (!Object.is(state[key], patch[key])) {
+ changed = true;
+ break;
+ }
+ }
+ if (!changed) return;
+
+ state = { ...state, ...patch };
+ listeners.forEach((listener) => listener());
+ };
+
+ const subscribe = (listener: StoreListener): (() => void) => {
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ };
+ };
+
+ const reset = (): void => {
+ state = initializer();
+ listeners.forEach((listener) => listener());
+ };
+
+ function useStore(): T;
+ function useStore<U>(selector: (state: T) => U, equalityFn?: EqualityFn<U>): U;
+ function useStore<U>(
+ selector?: (state: T) => U,
+ equalityFn: EqualityFn<U> = Object.is
+ ): T | U {
+ const selectorRef = useRef(selector);
+ selectorRef.current = selector;
+
+ const equalityRef = useRef(equalityFn);
+ equalityRef.current = equalityFn;
+
+ const snapshotRef = useRef<{ hasValue: boolean; value: T | U }>({
+ hasValue: false,
+ value: undefined as unknown as T,
+ });
+
+ const getSnapshot = (): T | U => {
+ const currentState = getState();
+ const sel = selectorRef.current;
+ const next = sel ? sel(currentState) : currentState;
+ if (snapshotRef.current.hasValue) {
+ const prev = snapshotRef.current.value;
+ if (sel) {
+ if (equalityRef.current(prev as U, next as U)) {
+ return prev;
+ }
+ } else if (Object.is(prev, next)) {
+ return prev;
+ }
+ }
+ snapshotRef.current = { hasValue: true, value: next };
+ return next;
+ };
+
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+ }
+
+ return Object.assign(useStore, {
+ getState,
+ setState,
+ subscribe,
+ reset,
+ });
+}
diff --git a/src/stores/index.ts b/src/stores/index.ts
new file mode 100644
index 0000000..c517bcd
--- /dev/null
+++ b/src/stores/index.ts
@@ -0,0 +1,24 @@
+export { createStore, shallowEqual } from './createStore';
+export type { StoreApi, UseBoundStore, StoreListener, StateUpdater, EqualityFn } from './createStore';
+
+export { useToolStore, toolStoreActions } from './useToolStore';
+export type { ToolStoreState, QuickModifiersState } from './useToolStore';
+
+export {
+ useDocumentStore,
+ documentStoreActions,
+ INITIAL_CANVAS_DIMENSIONS,
+ selectHasOpenDocument,
+} from './useDocumentStore';
+export type { DocumentStoreState } from './useDocumentStore';
+
+export { useUiStore, uiStoreActions, selectIsAnyModalOpen } from './useUiStore';
+export type {
+ UiStoreState,
+ TonalModalState,
+ AdjustmentModalState,
+ LayerStylesModalState,
+} from './useUiStore';
+
+export { useWorkspaceStore, workspaceStoreActions } from './useWorkspaceStore';
+export type { WorkspaceStoreState } from './useWorkspaceStore';
diff --git a/src/stores/useDocumentStore.ts b/src/stores/useDocumentStore.ts
new file mode 100644
index 0000000..cd89bc3
--- /dev/null
+++ b/src/stores/useDocumentStore.ts
@@ -0,0 +1,171 @@
+import {
+ CanvasDimensions,
+ CanvasColorMode,
+ DocumentTab,
+ SoftProofSettings,
+ DEFAULT_SOFT_PROOF_SETTINGS,
+ CmykStandard,
+ AnimationTimeline,
+} from '../types/editor';
+import { PerspectiveRuler, ConstraintAxis } from '../types/perspective';
+import { SavedFileInfo } from '../utils/saveManager';
+import { createStore } from './createStore';
+
+export const INITIAL_CANVAS_DIMENSIONS: CanvasDimensions = {
+ width: 1440,
+ height: 900,
+ dpi: 300,
+};
+
+export interface DocumentStoreState {
+ documents: DocumentTab[];
+ activeDocumentId: string | null;
+ dimensions: CanvasDimensions;
+ colorMode: CanvasColorMode;
+ documentName: string;
+ activeLayerId: string;
+ activeEditTarget: 'layer' | 'mask';
+ savedFileInfo: SavedFileInfo | null;
+ softProofSettings: SoftProofSettings;
+ animationTimeline: AnimationTimeline | null;
+ perspectiveRuler: PerspectiveRuler | null;
+ activeLockedAxis: ConstraintAxis | null;
+}
+
+const createInitialDocumentState = (): DocumentStoreState => ({
+ documents: [],
+ activeDocumentId: null,
+ dimensions: { ...INITIAL_CANVAS_DIMENSIONS },
+ colorMode: 'color',
+ documentName: '',
+ activeLayerId: '',
+ activeEditTarget: 'layer',
+ savedFileInfo: null,
+ softProofSettings: { ...DEFAULT_SOFT_PROOF_SETTINGS },
+ animationTimeline: null,
+ perspectiveRuler: null,
+ activeLockedAxis: null,
+});
+
+export const useDocumentStore = createStore<DocumentStoreState>(createInitialDocumentState);
+
+export const documentStoreActions = {
+ setDocuments(updater: DocumentTab[] | ((prev: DocumentTab[]) => DocumentTab[])): void {
+ useDocumentStore.setState((prev) => ({
+ documents: typeof updater === 'function' ? updater(prev.documents) : updater,
+ }));
+ },
+
+ setActiveDocumentId(id: string | null): void {
+ useDocumentStore.setState({ activeDocumentId: id });
+ },
+
+ markDocumentDirty(id: string | null, isDirty: boolean): void {
+ if (!id) return;
+ useDocumentStore.setState((prev) => {
+ const target = prev.documents.find((d) => d.id === id);
+ if (!target || Boolean(target.isDirty) === isDirty) return prev;
+ return {
+ documents: prev.documents.map((d) => (d.id === id ? { ...d, isDirty } : d)),
+ };
+ });
+ },
+
+ setDimensions(dimensions: CanvasDimensions): void {
+ useDocumentStore.setState({ dimensions });
+ },
+
+ setColorMode(colorMode: CanvasColorMode): void {
+ useDocumentStore.setState({ colorMode });
+ },
+
+ setDocumentName(documentName: string): void {
+ useDocumentStore.setState({ documentName });
+ },
+
+ setActiveLayerId(activeLayerId: string): void {
+ useDocumentStore.setState({ activeLayerId });
+ },
+
+ setActiveEditTarget(activeEditTarget: 'layer' | 'mask'): void {
+ useDocumentStore.setState({ activeEditTarget });
+ },
+
+ setSavedFileInfo(savedFileInfo: SavedFileInfo | null): void {
+ useDocumentStore.setState({ savedFileInfo });
+ },
+
+ toggleSoftProof(): void {
+ useDocumentStore.setState((prev) => ({
+ softProofSettings: {
+ ...prev.softProofSettings,
+ enabled: !prev.softProofSettings.enabled,
+ },
+ }));
+ },
+
+ toggleGamutWarning(): void {
+ useDocumentStore.setState((prev) => ({
+ softProofSettings: {
+ ...prev.softProofSettings,
+ gamutWarning: !prev.softProofSettings.gamutWarning,
+ },
+ }));
+ },
+
+ setProofStandard(standard: CmykStandard): void {
+ useDocumentStore.setState((prev) => ({
+ softProofSettings: {
+ ...prev.softProofSettings,
+ standard,
+ },
+ }));
+ },
+
+ setAnimationTimeline(animationTimeline: AnimationTimeline | null): void {
+ useDocumentStore.setState({ animationTimeline });
+ },
+
+ setPerspectiveRuler(
+ updater:
+ | PerspectiveRuler
+ | null
+ | ((prev: PerspectiveRuler | null) => PerspectiveRuler | null)
+ ): void {
+ useDocumentStore.setState((prev) => {
+ const next = typeof updater === 'function' ? updater(prev.perspectiveRuler) : updater;
+ if (prev.activeDocumentId) {
+ return {
+ perspectiveRuler: next,
+ documents: prev.documents.map((d) =>
+ d.id === prev.activeDocumentId ? { ...d, perspectiveRuler: next } : d
+ ),
+ };
+ }
+ return { perspectiveRuler: next };
+ });
+ },
+
+ setActiveLockedAxis(newAxis: ConstraintAxis | null): void {
+ const prev = useDocumentStore.getState().activeLockedAxis;
+ if (prev === newAxis) return;
+ if (
+ prev &&
+ newAxis &&
+ prev.type === newAxis.type &&
+ prev.origin.x === newAxis.origin.x &&
+ prev.origin.y === newAxis.origin.y &&
+ prev.dir.x === newAxis.dir.x &&
+ prev.dir.y === newAxis.dir.y
+ ) {
+ return;
+ }
+ useDocumentStore.setState({ activeLockedAxis: newAxis });
+ },
+};
+
+export function selectHasOpenDocument(state: DocumentStoreState): boolean {
+ return Boolean(
+ state.activeDocumentId && state.documents.some((d) => d.id === state.activeDocumentId)
+ );
+}
diff --git a/src/stores/useToolStore.ts b/src/stores/useToolStore.ts
new file mode 100644
index 0000000..59389a0
--- /dev/null
+++ b/src/stores/useToolStore.ts
@@ -0,0 +1,419 @@
+import {
+ ToolType,
+ BrushSettings,
+ BrushPresetId,
+ CanvasColorMode,
+ WandSettings,
+ FillSettings,
+ TextSettings,
+ FrameSettings,
+ BalloonSettings,
+ VectorEditSettings,
+ LiquifySettings,
+} from '../types/editor';
+import {
+ saveBrushSettingsDebounced,
+ getEffectiveBrushSettings,
+ getActivePresetId,
+ saveActivePresetId,
+ ERASER_PRESET_ID,
+ DEFAULT_BRUSH_PRESET_ID,
+} from '../utils/brushPresetManager';
+import { enforceColorMode } from '../utils/colorUtils';
+import { createStore } from './createStore';
+import { useDocumentStore } from './useDocumentStore';
+
+export interface QuickModifiersState {
+ isAltActive: boolean;
+ isSpaceDown: boolean;
+ isShiftDown: boolean;
+ isRotateModifier: boolean;
+}
+
+export interface ToolStoreState {
+ tool: ToolType;
+ activePresetId: BrushPresetId;
+ brushSettings: BrushSettings;
+ primaryColor: string;
+ secondaryColor: string;
+ isTransparentColor: boolean;
+ recentColors: string[];
+ quickModifiers: QuickModifiersState;
+ wandSettings: WandSettings;
+ fillSettings: FillSettings;
+ textSettings: TextSettings;
+ frameSettings: FrameSettings;
+ balloonSettings: BalloonSettings;
+ vectorEditSettings: VectorEditSettings;
+ liquifySettings: LiquifySettings;
+}
+
+const DEFAULT_RECENT_COLORS = [
+ '#000000',
+ '#3b82f6',
+ '#ef4444',
+ '#10b981',
+ '#f59e0b',
+ '#ffffff',
+];
+
+function createInitialBrushSettings(): { presetId: BrushPresetId; brushSettings: BrushSettings } {
+ const activePreset = getActivePresetId();
+ const effective = getEffectiveBrushSettings(activePreset);
+ return {
+ presetId: activePreset,
+ brushSettings: {
+ preset: activePreset,
+ size: effective.size ?? 3.5,
+ minSizeFactor: effective.minSizeFactor ?? 0.25,
+ color: '#000000',
+ secondaryColor: '#ffffff',
+ opacity: effective.opacity ?? 1.0,
+ flow: effective.flow ?? 0.74,
+ spacing: effective.spacing ?? 0.08,
+ grain: effective.grain ?? 0.95,
+ usePressure: effective.usePressure ?? true,
+ smoothing: effective.smoothing ?? true,
+ stabilization: effective.stabilization ?? 15,
+ hardness: effective.hardness ?? 0.8,
+ ...effective,
+ } as BrushSettings,
+ };
+}
+
+function loadInitialLiquifySettings(): LiquifySettings {
+ try {
+ if (typeof localStorage !== 'undefined') {
+ const saved = localStorage.getItem('sora_paint_liquify_settings');
+ if (saved) return JSON.parse(saved) as LiquifySettings;
+ }
+ } catch {
+ // Ignore storage errors
+ }
+ return {
+ mode: 'push',
+ size: 80,
+ strength: 50,
+ hardness: 50,
+ usePressure: true,
+ };
+}
+
+const createInitialToolState = (): ToolStoreState => {
+ const { presetId, brushSettings } = createInitialBrushSettings();
+ return {
+ tool: 'brush',
+ activePresetId: presetId,
+ brushSettings,
+ primaryColor: '#000000',
+ secondaryColor: '#ffffff',
+ isTransparentColor: false,
+ recentColors: [...DEFAULT_RECENT_COLORS],
+ quickModifiers: {
+ isAltActive: false,
+ isSpaceDown: false,
+ isShiftDown: false,
+ isRotateModifier: false,
+ },
+ wandSettings: {
+ tolerance: 32,
+ contiguous: true,
+ antiAlias: true,
+ referMode: 'active',
+ },
+ fillSettings: {
+ method: 'refer-all',
+ tolerance: 32,
+ },
+ textSettings: {
+ text: '',
+ fontFamily: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",
+ fontSize: 28,
+ bold: false,
+ italic: false,
+ align: 'center',
+ outline: true,
+ outlineColor: '#ffffff',
+ outlineWidth: 3,
+ color: '#000000',
+ },
+ frameSettings: {
+ thickness: 4,
+ fillBackground: true,
+ fillColor: '#ffffff',
+ },
+ balloonSettings: {
+ shape: 'ellipse',
+ fillColor: '#ffffff',
+ strokeColor: '#000000',
+ strokeWidth: 3,
+ text: '',
+ fontFamily: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",
+ fontSize: 22,
+ vertical: false,
+ },
+ vectorEditSettings: {
+ mode: 'pinch',
+ radius: 35,
+ pinchStrength: 1.0,
+ widthFactor: 1.5,
+ simplifyTolerance: 2.0,
+ },
+ liquifySettings: loadInitialLiquifySettings(),
+ };
+};
+
+export const useToolStore = createStore<ToolStoreState>(createInitialToolState);
+
+export const toolStoreActions = {
+ selectTool(newTool: ToolType): void {
+ const state = useToolStore.getState();
+ const prevTool = state.tool;
+ if (prevTool === newTool) return;
+
+ if (newTool === 'eraser') {
+ const eraserSettings = getEffectiveBrushSettings(ERASER_PRESET_ID);
+ useToolStore.setState({
+ tool: newTool,
+ brushSettings: {
+ ...state.brushSettings,
+ ...eraserSettings,
+ color: state.brushSettings.color,
+ },
+ });
+ return;
+ }
+
+ if (prevTool === 'eraser' && newTool === 'brush') {
+ const activePreset = state.brushSettings.preset || getActivePresetId();
+ const brushCfg = getEffectiveBrushSettings(activePreset);
+ useToolStore.setState({
+ tool: newTool,
+ activePresetId: activePreset,
+ brushSettings: {
+ ...state.brushSettings,
+ ...brushCfg,
+ color: state.brushSettings.color,
+ },
+ });
+ return;
+ }
+
+ useToolStore.setState({ tool: newTool });
+ },
+
+ setToolRaw(tool: ToolType): void {
+ useToolStore.setState({ tool });
+ },
+
+ updateBrushSettings(newSettings: Partial<BrushSettings>): void {
+ const state = useToolStore.getState();
+ const next: BrushSettings = { ...state.brushSettings, ...newSettings };
+ const targetPresetId =
+ state.tool === 'eraser'
+ ? ERASER_PRESET_ID
+ : next.preset || state.brushSettings.preset || DEFAULT_BRUSH_PRESET_ID;
+
+ saveBrushSettingsDebounced(targetPresetId, next);
+ if (next.preset && state.tool === 'brush') {
+ saveActivePresetId(next.preset);
+ }
+
+ useToolStore.setState({
+ brushSettings: next,
+ activePresetId:
+ next.preset && state.tool === 'brush' ? next.preset : state.activePresetId,
+ });
+ },
+
+ addRecentColor(color: string): void {
+ useToolStore.setState((prev) => {
+ const filtered = prev.recentColors.filter(
+ (c) => c.toLowerCase() !== color.toLowerCase()
+ );
+ return { recentColors: [color, ...filtered].slice(0, 14) };
+ });
+ },
+
+ setPrimaryColor(color: string, commit = true, colorModeOverride?: CanvasColorMode): void {
+ const mode = colorModeOverride ?? useDocumentStore.getState().colorMode;
+ const effective = enforceColorMode(color, mode);
+ const state = useToolStore.getState();
+
+ const nextBrush: BrushSettings = {
+ ...state.brushSettings,
+ color: effective,
+ isTransparentInk: false,
+ };
+ const targetPresetId =
+ state.tool === 'eraser'
+ ? ERASER_PRESET_ID
+ : nextBrush.preset || DEFAULT_BRUSH_PRESET_ID;
+ saveBrushSettingsDebounced(targetPresetId, nextBrush);
+
+ const nextRecent = commit
+ ? [
+ effective,
+ ...state.recentColors.filter((c) => c.toLowerCase() !== effective.toLowerCase()),
+ ].slice(0, 14)
+ : state.recentColors;
+
+ useToolStore.setState({
+ primaryColor: effective,
+ isTransparentColor: false,
+ brushSettings: nextBrush,
+ recentColors: nextRecent,
+ });
+
+ if (state.tool === 'eraser') {
+ toolStoreActions.selectTool('brush');
+ }
+ },
+
+ setSecondaryColor(color: string, commit = true, colorModeOverride?: CanvasColorMode): void {
+ const mode = colorModeOverride ?? useDocumentStore.getState().colorMode;
+ const effective = enforceColorMode(color, mode);
+ const state = useToolStore.getState();
+
+ const nextBrush: BrushSettings = {
+ ...state.brushSettings,
+ secondaryColor: effective,
+ };
+ const targetPresetId =
+ state.tool === 'eraser'
+ ? ERASER_PRESET_ID
+ : nextBrush.preset || DEFAULT_BRUSH_PRESET_ID;
+ saveBrushSettingsDebounced(targetPresetId, nextBrush);
+
+ const nextRecent = commit
+ ? [
+ effective,
+ ...state.recentColors.filter((c) => c.toLowerCase() !== effective.toLowerCase()),
+ ].slice(0, 14)
+ : state.recentColors;
+
+ useToolStore.setState({
+ secondaryColor: effective,
+ brushSettings: nextBrush,
+ recentColors: nextRecent,
+ });
+ },
+
+ swapColors(colorModeOverride?: CanvasColorMode): void {
+ const mode = colorModeOverride ?? useDocumentStore.getState().colorMode;
+ const state = useToolStore.getState();
+ const prevPrimary = state.primaryColor;
+ const effectivePrimary = enforceColorMode(state.secondaryColor, mode);
+ const nextBrush: BrushSettings = {
+ ...state.brushSettings,
+ color: effectivePrimary,
+ secondaryColor: prevPrimary,
+ isTransparentInk: false,
+ };
+ const targetPresetId =
+ state.tool === 'eraser'
+ ? ERASER_PRESET_ID
+ : nextBrush.preset || DEFAULT_BRUSH_PRESET_ID;
+ saveBrushSettingsDebounced(targetPresetId, nextBrush);
+
+ const nextRecent = [
+ effectivePrimary,
+ ...state.recentColors.filter(
+ (c) => c.toLowerCase() !== effectivePrimary.toLowerCase()
+ ),
+ ].slice(0, 14);
+
+ useToolStore.setState({
+ primaryColor: effectivePrimary,
+ secondaryColor: prevPrimary,
+ isTransparentColor: false,
+ brushSettings: nextBrush,
+ recentColors: nextRecent,
+ });
+
+ if (state.tool === 'eraser') {
+ toolStoreActions.selectTool('brush');
+ }
+ },
+
+ toggleTransparentColor(): boolean {
+ const state = useToolStore.getState();
+ const next = !state.isTransparentColor;
+ const nextBrush: BrushSettings = {
+ ...state.brushSettings,
+ isTransparentInk: next,
+ };
+ const targetPresetId =
+ state.tool === 'eraser'
+ ? ERASER_PRESET_ID
+ : nextBrush.preset || DEFAULT_BRUSH_PRESET_ID;
+ saveBrushSettingsDebounced(targetPresetId, nextBrush);
+
+ useToolStore.setState({
+ isTransparentColor: next,
+ brushSettings: nextBrush,
+ });
+ return next;
+ },
+
+ resetDefaultColors(colorModeOverride?: CanvasColorMode): void {
+ toolStoreActions.setPrimaryColor('#000000', true, colorModeOverride);
+ toolStoreActions.setSecondaryColor('#ffffff', false, colorModeOverride);
+ },
+
+ setQuickModifiers(patch: Partial<QuickModifiersState>): void {
+ useToolStore.setState((prev) => ({
+ quickModifiers: { ...prev.quickModifiers, ...patch },
+ }));
+ },
+
+ updateWandSettings(patch: Partial<WandSettings>): void {
+ useToolStore.setState((prev) => ({
+ wandSettings: { ...prev.wandSettings, ...patch },
+ }));
+ },
+
+ updateFillSettings(patch: Partial<FillSettings>): void {
+ useToolStore.setState((prev) => ({
+ fillSettings: { ...prev.fillSettings, ...patch },
+ }));
+ },
+
+ updateTextSettings(patch: Partial<TextSettings>): void {
+ useToolStore.setState((prev) => ({
+ textSettings: { ...prev.textSettings, ...patch },
+ }));
+ },
+
+ updateFrameSettings(patch: Partial<FrameSettings>): void {
+ useToolStore.setState((prev) => ({
+ frameSettings: { ...prev.frameSettings, ...patch },
+ }));
+ },
+
+ updateBalloonSettings(patch: Partial<BalloonSettings>): void {
+ useToolStore.setState((prev) => ({
+ balloonSettings: { ...prev.balloonSettings, ...patch },
+ }));
+ },
+
+ updateVectorEditSettings(patch: Partial<VectorEditSettings>): void {
+ useToolStore.setState((prev) => ({
+ vectorEditSettings: { ...prev.vectorEditSettings, ...patch },
+ }));
+ },
+
+ updateLiquifySettings(patch: Partial<LiquifySettings>): void {
+ useToolStore.setState((prev) => {
+ const next = { ...prev.liquifySettings, ...patch };
+ try {
+ if (typeof localStorage !== 'undefined') {
+ localStorage.setItem('sora_paint_liquify_settings', JSON.stringify(next));
+ }
+ } catch {
+ // Ignore storage errors
+ }
+ return { liquifySettings: next };
+ });
+ },
+};
diff --git a/src/stores/useUiStore.ts b/src/stores/useUiStore.ts
new file mode 100644
index 0000000..6b21a78
--- /dev/null
+++ b/src/stores/useUiStore.ts
@@ -0,0 +1,276 @@
+import { AppSettings, loadAppSettings, saveAppSettings } from '../types/settings';
+import { CrashedSessionInfo } from '../services/recoveryService';
+import { TonalCorrectionType, ProcessingBounds } from '../utils/tonalEngine';
+import { createStore } from './createStore';
+
+export interface TonalModalState {
+ isOpen: boolean;
+ type: TonalCorrectionType;
+ targetLayerId: string;
+ beforeImageData: ImageData | null;
+ selectionMask: Uint8Array | null;
+ bounds: ProcessingBounds;
+}
+
+export interface AdjustmentModalState {
+ isOpen: boolean;
+ layerId?: string;
+ initialType?: 'curves' | 'gradient-map' | 'levels' | 'color-balance';
+}
+
+export interface LayerStylesModalState {
+ isOpen: boolean;
+ layerId?: string;
+}
+
+export interface UiStoreState {
+ appView: 'home' | 'workspace';
+ leftPanelWidth: number;
+ isLeftPanelHidden: boolean;
+ rightSidebarWidth: number;
+ isRightSidebarHidden: boolean;
+ isWebtoonMode: boolean;
+ is3DLayerOpen: boolean;
+ initial3DFile: File | null;
+ appSettings: AppSettings;
+
+ // Modals
+ isNewCanvasModalOpen: boolean;
+ isResizeCanvasModalOpen: boolean;
+ isSettingsModalOpen: boolean;
+ isToneModalOpen: boolean;
+ isMangaEffectsModalOpen: boolean;
+ isWebtoonExportModalOpen: boolean;
+ isRecoveryModalOpen: boolean;
+ crashedSessions: CrashedSessionInfo[];
+ tonalModalState: TonalModalState;
+ adjustmentModalState: AdjustmentModalState;
+ layerStylesModalState: LayerStylesModalState;
+
+ // Transient feedback
+ isLoadingFile: boolean;
+ loadingStatus: string;
+ toastMessage: string | null;
+}
+
+const DEFAULT_TONAL_MODAL_STATE: TonalModalState = {
+ isOpen: false,
+ type: 'brightness-contrast',
+ targetLayerId: '',
+ beforeImageData: null,
+ selectionMask: null,
+ bounds: { x0: 0, y0: 0, x1: 0, y1: 0 },
+};
+
+function readStoredNumber(key: string, fallback: number): number {
+ try {
+ if (typeof localStorage !== 'undefined') {
+ const raw = localStorage.getItem(key);
+ if (raw !== null) {
+ const parsed = Number(raw);
+ if (Number.isFinite(parsed)) return parsed;
+ }
+ }
+ } catch {
+ // Ignore storage errors
+ }
+ return fallback;
+}
+
+const createInitialUiState = (): UiStoreState => ({
+ appView: 'workspace',
+ leftPanelWidth: readStoredNumber('ink_left_panel_width_v3', 118),
+ isLeftPanelHidden: false,
+ rightSidebarWidth: readStoredNumber('ink_right_sidebar_width_v3', 162),
+ isRightSidebarHidden: false,
+ isWebtoonMode: false,
+ is3DLayerOpen: false,
+ initial3DFile: null,
+ appSettings: loadAppSettings(),
+
+ isNewCanvasModalOpen: false,
+ isResizeCanvasModalOpen: false,
+ isSettingsModalOpen: false,
+ isToneModalOpen: false,
+ isMangaEffectsModalOpen: false,
+ isWebtoonExportModalOpen: false,
+ isRecoveryModalOpen: false,
+ crashedSessions: [],
+ tonalModalState: { ...DEFAULT_TONAL_MODAL_STATE },
+ adjustmentModalState: { isOpen: false },
+ layerStylesModalState: { isOpen: false },
+
+ isLoadingFile: false,
+ loadingStatus: '',
+ toastMessage: null,
+});
+
+export const useUiStore = createStore<UiStoreState>(createInitialUiState);
+
+let toastTimer: ReturnType<typeof setTimeout> | null = null;
+
+export const uiStoreActions = {
+ setAppView(appView: 'home' | 'workspace'): void {
+ useUiStore.setState({ appView });
+ },
+
+ setLeftPanelWidth(w: number): void {
+ useUiStore.setState({ leftPanelWidth: w });
+ try {
+ if (typeof localStorage !== 'undefined') {
+ localStorage.setItem('ink_left_panel_width_v3', String(w));
+ }
+ } catch {
+ // Ignore storage errors
+ }
+ },
+
+ setRightSidebarWidth(w: number): void {
+ useUiStore.setState({ rightSidebarWidth: w });
+ try {
+ if (typeof localStorage !== 'undefined') {
+ localStorage.setItem('ink_right_sidebar_width_v3', String(w));
+ }
+ } catch {
+ // Ignore storage errors
+ }
+ },
+
+ setLeftPanelHidden(hidden: boolean): void {
+ useUiStore.setState({ isLeftPanelHidden: hidden });
+ },
+
+ toggleLeftPanelHidden(): void {
+ useUiStore.setState((prev) => ({ isLeftPanelHidden: !prev.isLeftPanelHidden }));
+ },
+
+ setRightSidebarHidden(hidden: boolean): void {
+ useUiStore.setState({ isRightSidebarHidden: hidden });
+ },
+
+ toggleRightSidebarHidden(): void {
+ useUiStore.setState((prev) => ({ isRightSidebarHidden: !prev.isRightSidebarHidden }));
+ },
+
+ toggleAllPanels(): void {
+ useUiStore.setState((prev) => {
+ const nextHidden = !(prev.isLeftPanelHidden && prev.isRightSidebarHidden);
+ return {
+ isLeftPanelHidden: nextHidden,
+ isRightSidebarHidden: nextHidden,
+ };
+ });
+ },
+
+ setWebtoonMode(enabled: boolean): void {
+ useUiStore.setState({ isWebtoonMode: enabled });
+ },
+
+ toggleWebtoonMode(): void {
+ useUiStore.setState((prev) => ({ isWebtoonMode: !prev.isWebtoonMode }));
+ },
+
+ set3DLayerOpen(open: boolean, initialFile: File | null = null): void {
+ useUiStore.setState({
+ is3DLayerOpen: open,
+ initial3DFile: open ? initialFile : null,
+ });
+ },
+
+ updateAppSettings(newSettings: AppSettings): void {
+ useUiStore.setState({ appSettings: newSettings });
+ saveAppSettings(newSettings);
+ },
+
+ setNewCanvasModalOpen(open: boolean): void {
+ useUiStore.setState({ isNewCanvasModalOpen: open });
+ },
+
+ setResizeCanvasModalOpen(open: boolean): void {
+ useUiStore.setState({ isResizeCanvasModalOpen: open });
+ },
+
+ setSettingsModalOpen(open: boolean): void {
+ useUiStore.setState({ isSettingsModalOpen: open });
+ },
+
+ setToneModalOpen(open: boolean): void {
+ useUiStore.setState({ isToneModalOpen: open });
+ },
+
+ setMangaEffectsModalOpen(open: boolean): void {
+ useUiStore.setState({ isMangaEffectsModalOpen: open });
+ },
+
+ setWebtoonExportModalOpen(open: boolean): void {
+ useUiStore.setState({ isWebtoonExportModalOpen: open });
+ },
+
+ setRecoveryModal(open: boolean, sessions?: CrashedSessionInfo[]): void {
+ useUiStore.setState((prev) => ({
+ isRecoveryModalOpen: open,
+ crashedSessions: sessions ?? prev.crashedSessions,
+ }));
+ },
+
+ setCrashedSessions(
+ updater: CrashedSessionInfo[] | ((prev: CrashedSessionInfo[]) => CrashedSessionInfo[])
+ ): void {
+ useUiStore.setState((prev) => ({
+ crashedSessions: typeof updater === 'function' ? updater(prev.crashedSessions) : updater,
+ }));
+ },
+
+ setTonalModalState(
+ updater: TonalModalState | ((prev: TonalModalState) => TonalModalState)
+ ): void {
+ useUiStore.setState((prev) => ({
+ tonalModalState: typeof updater === 'function' ? updater(prev.tonalModalState) : updater,
+ }));
+ },
+
+ setAdjustmentModalState(adjustmentModalState: AdjustmentModalState): void {
+ useUiStore.setState({ adjustmentModalState });
+ },
+
+ setLayerStylesModalState(layerStylesModalState: LayerStylesModalState): void {
+ useUiStore.setState({ layerStylesModalState });
+ },
+
+ setLoading(isLoadingFile: boolean, loadingStatus = ''): void {
+ useUiStore.setState({ isLoadingFile, loadingStatus });
+ },
+
+ showToast(msg: string): void {
+ if (toastTimer) clearTimeout(toastTimer);
+ useUiStore.setState({ toastMessage: msg });
+ toastTimer = setTimeout(() => {
+ toastTimer = null;
+ useUiStore.setState({ toastMessage: null });
+ }, 3200);
+ },
+
+ clearToast(): void {
+ if (toastTimer) {
+ clearTimeout(toastTimer);
+ toastTimer = null;
+ }
+ useUiStore.setState({ toastMessage: null });
+ },
+};
+
+export function selectIsAnyModalOpen(state: UiStoreState, isHostModalOpen = false): boolean {
+ return (
+ state.isNewCanvasModalOpen ||
+ state.isResizeCanvasModalOpen ||
+ state.isSettingsModalOpen ||
+ state.isToneModalOpen ||
+ state.isMangaEffectsModalOpen ||
+ state.isWebtoonExportModalOpen ||
+ state.isRecoveryModalOpen ||
+ state.tonalModalState.isOpen ||
+ state.adjustmentModalState.isOpen ||
+ state.layerStylesModalState.isOpen ||
+ isHostModalOpen
+ );
+}
diff --git a/src/stores/useWorkspaceStore.ts b/src/stores/useWorkspaceStore.ts
new file mode 100644
index 0000000..0ce41b9
--- /dev/null
+++ b/src/stores/useWorkspaceStore.ts
@@ -0,0 +1,316 @@
+import {
+ CommandActionId,
+ DockPanelId,
+ PersistedWorkspaceState,
+ QuickAccessItem,
+ QuickAccessViewMode,
+ WorkspaceLayout,
+ WorkspacePresetId,
+} from '../types/workspace';
+import {
+ DEFAULT_COMMAND_BAR_IDS,
+ DEFAULT_QUICK_ACCESS_ITEMS,
+ MovePanelTarget,
+ cloneLayout,
+ getPresetLayout,
+ loadWorkspaceState,
+ movePanelInLayout,
+ resizeColumnInLayout,
+ resizeGroupSplitInLayout,
+ saveWorkspaceState,
+ setGroupActivePanelInLayout,
+ toggleColumnCollapsedInLayout,
+ togglePanelInLayout,
+} from '../utils/workspacePresets';
+import { createStore } from './createStore';
+import { useUiStore } from './useUiStore';
+
+export interface WorkspaceStoreState {
+ activePreset: WorkspacePresetId;
+ layout: WorkspaceLayout;
+ savedCustomLayout: WorkspaceLayout | null;
+ palettesHidden: boolean;
+ openPopover: { colId: string; panelId: DockPanelId } | null;
+ quickAccessItems: QuickAccessItem[];
+ quickAccessViewMode: QuickAccessViewMode;
+ commandBarIds: CommandActionId[];
+ showStatusBar: boolean;
+ showDocumentTabs: boolean;
+ showCommandBar: boolean;
+}
+
+const createInitialWorkspaceState = (): WorkspaceStoreState => {
+ const loaded = loadWorkspaceState();
+ return {
+ activePreset: loaded.activePreset,
+ layout: loaded.layout,
+ savedCustomLayout: loaded.savedCustomLayout,
+ palettesHidden: false,
+ openPopover: null,
+ quickAccessItems: loaded.quickAccessItems,
+ quickAccessViewMode: loaded.quickAccessViewMode,
+ commandBarIds: loaded.commandBarIds,
+ showStatusBar: loaded.showStatusBar,
+ showDocumentTabs: loaded.showDocumentTabs,
+ showCommandBar: loaded.showCommandBar,
+ };
+};
+
+export const useWorkspaceStore = createStore<WorkspaceStoreState>(createInitialWorkspaceState);
+
+function persistCurrentWorkspace(): void {
+ const s = useWorkspaceStore.getState();
+ const payload: PersistedWorkspaceState = {
+ version: 1,
+ activePreset: s.activePreset,
+ layout: s.layout,
+ savedCustomLayout: s.savedCustomLayout,
+ quickAccessItems: s.quickAccessItems,
+ quickAccessViewMode: s.quickAccessViewMode,
+ commandBarIds: s.commandBarIds,
+ showStatusBar: s.showStatusBar,
+ showDocumentTabs: s.showDocumentTabs,
+ showCommandBar: s.showCommandBar,
+ };
+ saveWorkspaceState(payload);
+}
+
+export const workspaceStoreActions = {
+ applyPreset(preset: WorkspacePresetId): void {
+ const prev = useWorkspaceStore.getState();
+ const nextLayout =
+ preset === 'custom'
+ ? cloneLayout(prev.savedCustomLayout ?? prev.layout)
+ : getPresetLayout(preset);
+ useWorkspaceStore.setState({
+ activePreset: preset,
+ layout: nextLayout,
+ openPopover: null,
+ palettesHidden: false,
+ });
+ useUiStore.setState({ isLeftPanelHidden: false, isRightSidebarHidden: false });
+ persistCurrentWorkspace();
+ },
+
+ resetWorkspace(): void {
+ const prev = useWorkspaceStore.getState();
+ const basePreset: Exclude<WorkspacePresetId, 'custom'> =
+ prev.activePreset === 'custom' ? 'default-illustration' : prev.activePreset;
+ const nextLayout = getPresetLayout(basePreset);
+ useWorkspaceStore.setState({
+ activePreset: basePreset,
+ layout: nextLayout,
+ openPopover: null,
+ palettesHidden: false,
+ showStatusBar: true,
+ showDocumentTabs: true,
+ showCommandBar: true,
+ });
+ useUiStore.setState({ isLeftPanelHidden: false, isRightSidebarHidden: false });
+ persistCurrentWorkspace();
+ },
+
+ saveAsCustomPreset(): void {
+ const prev = useWorkspaceStore.getState();
+ useWorkspaceStore.setState({
+ activePreset: 'custom',
+ savedCustomLayout: cloneLayout(prev.layout),
+ });
+ persistCurrentWorkspace();
+ },
+
+ movePanel(panelId: DockPanelId, target: MovePanelTarget): void {
+ useWorkspaceStore.setState((prev) => {
+ const nextLayout = movePanelInLayout(prev.layout, panelId, target);
+ return {
+ layout: nextLayout,
+ activePreset: 'custom',
+ savedCustomLayout: cloneLayout(nextLayout),
+ openPopover: null,
+ };
+ });
+ persistCurrentWorkspace();
+ },
+
+ setGroupActivePanel(colId: string, groupId: string, panelId: DockPanelId): void {
+ useWorkspaceStore.setState((prev) => ({
+ layout: setGroupActivePanelInLayout(prev.layout, colId, groupId, panelId),
+ }));
+ persistCurrentWorkspace();
+ },
+
+ toggleColumnCollapsed(colId: string, forceValue?: boolean): void {
+ useWorkspaceStore.setState((prev) => {
+ const nextLayout = toggleColumnCollapsedInLayout(prev.layout, colId, forceValue);
+ return {
+ layout: nextLayout,
+ activePreset: 'custom',
+ savedCustomLayout: cloneLayout(nextLayout),
+ openPopover: prev.openPopover?.colId === colId ? null : prev.openPopover,
+ };
+ });
+ persistCurrentWorkspace();
+ },
+
+ resizeColumn(colId: string, width: number): void {
+ useWorkspaceStore.setState((prev) => {
+ const nextLayout = resizeColumnInLayout(prev.layout, colId, width);
+ if (nextLayout === prev.layout) return prev;
+ return {
+ layout: nextLayout,
+ savedCustomLayout:
+ prev.activePreset === 'custom' ? cloneLayout(nextLayout) : prev.savedCustomLayout,
+ };
+ });
+ persistCurrentWorkspace();
+ },
+
+ resizeGroupSplit(
+ colId: string,
+ topGroupId: string,
+ bottomGroupId: string,
+ topRatio: number,
+ bottomRatio: number
+ ): void {
+ useWorkspaceStore.setState((prev) => {
+ const nextLayout = resizeGroupSplitInLayout(
+ prev.layout,
+ colId,
+ topGroupId,
+ bottomGroupId,
+ topRatio,
+ bottomRatio
+ );
+ return {
+ layout: nextLayout,
+ savedCustomLayout:
+ prev.activePreset === 'custom' ? cloneLayout(nextLayout) : prev.savedCustomLayout,
+ };
+ });
+ persistCurrentWorkspace();
+ },
+
+ togglePanelVisibility(panelId: DockPanelId): void {
+ useWorkspaceStore.setState((prev) => {
+ const nextLayout = togglePanelInLayout(prev.layout, panelId);
+ return {
+ layout: nextLayout,
+ activePreset: 'custom',
+ savedCustomLayout: cloneLayout(nextLayout),
+ openPopover: prev.openPopover?.panelId === panelId ? null : prev.openPopover,
+ };
+ });
+ persistCurrentWorkspace();
+ },
+
+ setPalettesHidden(hidden: boolean): void {
+ useWorkspaceStore.setState({ palettesHidden: hidden, openPopover: null });
+ useUiStore.setState({ isLeftPanelHidden: hidden, isRightSidebarHidden: hidden });
+ },
+
+ togglePalettesHidden(): boolean {
+ const next = !useWorkspaceStore.getState().palettesHidden;
+ workspaceStoreActions.setPalettesHidden(next);
+ return next;
+ },
+
+ togglePopover(colId: string, panelId: DockPanelId): void {
+ useWorkspaceStore.setState((prev) => {
+ if (prev.openPopover && prev.openPopover.colId === colId && prev.openPopover.panelId === panelId) {
+ return { openPopover: null };
+ }
+ return { openPopover: { colId, panelId } };
+ });
+ },
+
+ closePopover(): void {
+ if (useWorkspaceStore.getState().openPopover !== null) {
+ useWorkspaceStore.setState({ openPopover: null });
+ }
+ },
+
+ // Quick Access customization
+ addQuickAccessItem(item: QuickAccessItem): void {
+ useWorkspaceStore.setState((prev) => ({
+ quickAccessItems: [...prev.quickAccessItems, item],
+ }));
+ persistCurrentWorkspace();
+ },
+
+ removeQuickAccessItem(id: string): void {
+ useWorkspaceStore.setState((prev) => ({
+ quickAccessItems: prev.quickAccessItems.filter((item) => item.id !== id),
+ }));
+ persistCurrentWorkspace();
+ },
+
+ moveQuickAccessItem(id: string, direction: -1 | 1): void {
+ useWorkspaceStore.setState((prev) => {
+ const idx = prev.quickAccessItems.findIndex((item) => item.id === id);
+ const nextIdx = idx + direction;
+ if (idx < 0 || nextIdx < 0 || nextIdx >= prev.quickAccessItems.length) return prev;
+ const copy = [...prev.quickAccessItems];
+ const [moved] = copy.splice(idx, 1);
+ copy.splice(nextIdx, 0, moved);
+ return { quickAccessItems: copy };
+ });
+ persistCurrentWorkspace();
+ },
+
+ setQuickAccessViewMode(mode: QuickAccessViewMode): void {
+ useWorkspaceStore.setState({ quickAccessViewMode: mode });
+ persistCurrentWorkspace();
+ },
+
+ resetQuickAccessItems(): void {
+ useWorkspaceStore.setState({
+ quickAccessItems: DEFAULT_QUICK_ACCESS_ITEMS.map((x) => ({ ...x })),
+ });
+ persistCurrentWorkspace();
+ },
+
+ // Command Bar customization
+ toggleCommandBarItem(commandId: CommandActionId): void {
+ useWorkspaceStore.setState((prev) => {
+ const exists = prev.commandBarIds.includes(commandId);
+ const next = exists
+ ? prev.commandBarIds.filter((id) => id !== commandId)
+ : [...prev.commandBarIds, commandId];
+ return { commandBarIds: next };
+ });
+ persistCurrentWorkspace();
+ },
+
+ moveCommandBarItem(commandId: CommandActionId, direction: -1 | 1): void {
+ useWorkspaceStore.setState((prev) => {
+ const idx = prev.commandBarIds.indexOf(commandId);
+ const nextIdx = idx + direction;
+ if (idx < 0 || nextIdx < 0 || nextIdx >= prev.commandBarIds.length) return prev;
+ const copy = [...prev.commandBarIds];
+ const [moved] = copy.splice(idx, 1);
+ copy.splice(nextIdx, 0, moved);
+ return { commandBarIds: copy };
+ });
+ persistCurrentWorkspace();
+ },
+
+ resetCommandBar(): void {
+ useWorkspaceStore.setState({ commandBarIds: [...DEFAULT_COMMAND_BAR_IDS] });
+ persistCurrentWorkspace();
+ },
+
+ setShowStatusBar(show: boolean): void {
+ useWorkspaceStore.setState({ showStatusBar: show });
+ persistCurrentWorkspace();
+ },
+
+ setShowDocumentTabs(show: boolean): void {
+ useWorkspaceStore.setState({ showDocumentTabs: show });
+ persistCurrentWorkspace();
+ },
+
+ setShowCommandBar(show: boolean): void {
+ useWorkspaceStore.setState({ showCommandBar: show });
+ persistCurrentWorkspace();
+ },
+};
diff --git a/src/types/editor.ts b/src/types/editor.ts
index a766b22..b03c2ea 100644
--- a/src/types/editor.ts
+++ b/src/types/editor.ts
@@ -327,6 +327,7 @@ export type AnimationExportFormat = 'gif' | 'apng' | 'webm' | 'mp4' | 'png-zip';
export interface DocumentTab {
id: string;
name: string;
+ isDirty?: boolean;
dimensions: CanvasDimensions;
colorMode: CanvasColorMode;
savedFileInfo?: {
diff --git a/src/types/workspace.ts b/src/types/workspace.ts
new file mode 100644
index 0000000..bbf4936
--- /dev/null
+++ b/src/types/workspace.ts
@@ -0,0 +1,214 @@
+import { BrushPresetId, ToolType } from './editor';
+
+export type DockPanelId =
+ | 'tools'
+ | 'subtool'
+ | 'tool-property'
+ | 'brush-size'
+ | 'color'
+ | 'layers'
+ | 'history'
+ | 'quick-access';
+
+export type DockSide = 'left' | 'right';
+
+export type WorkspacePresetId =
+ | 'default-illustration'
+ | 'manga-studio'
+ | 'minimalist-tablet'
+ | 'custom';
+
+export interface DockGroup {
+ id: string;
+ panelIds: DockPanelId[];
+ activePanelId: DockPanelId;
+ heightRatio: number;
+}
+
+export interface DockColumn {
+ id: string;
+ width: number;
+ collapsed: boolean;
+ groups: DockGroup[];
+}
+
+export interface WorkspaceLayout {
+ leftDocks: DockColumn[];
+ rightDocks: DockColumn[];
+}
+
+export type CommandActionId =
+ | 'undo'
+ | 'redo'
+ | 'save'
+ | 'save-as'
+ | 'new-layer'
+ | 'duplicate-layer'
+ | 'clear-layer'
+ | 'merge-down'
+ | 'flip-h'
+ | 'flip-v'
+ | 'reset-zoom'
+ | 'reset-rotation'
+ | 'transform'
+ | 'deselect'
+ | 'toggle-palettes'
+ | 'swap-colors'
+ | 'transparent-ink';
+
+export type QuickAccessItemKind = 'command' | 'tool' | 'color' | 'brush';
+
+export interface QuickAccessItem {
+ id: string;
+ kind: QuickAccessItemKind;
+ label: string;
+ commandId?: CommandActionId;
+ toolId?: ToolType;
+ color?: string;
+ brushPresetId?: BrushPresetId;
+}
+
+export type QuickAccessViewMode = 'grid' | 'list';
+
+export interface PersistedWorkspaceState {
+ version: 1;
+ activePreset: WorkspacePresetId;
+ layout: WorkspaceLayout;
+ savedCustomLayout: WorkspaceLayout | null;
+ quickAccessItems: QuickAccessItem[];
+ quickAccessViewMode: QuickAccessViewMode;
+ commandBarIds: CommandActionId[];
+ showStatusBar: boolean;
+ showDocumentTabs: boolean;
+ showCommandBar: boolean;
+}
+
+export interface DockPanelMeta {
+ id: DockPanelId;
+ title: string;
+ shortTitle: string;
+ defaultSide: DockSide;
+ defaultWidth: number;
+ minWidth: number;
+ maxWidth: number;
+}
+
+export const ALL_DOCK_PANEL_IDS: DockPanelId[] = [
+ 'tools',
+ 'subtool',
+ 'tool-property',
+ 'brush-size',
+ 'color',
+ 'layers',
+ 'history',
+ 'quick-access',
+];
+
+export const DOCK_PANEL_META: Record<DockPanelId, DockPanelMeta> = {
+ tools: {
+ id: 'tools',
+ title: 'Tool',
+ shortTitle: 'Tool',
+ defaultSide: 'left',
+ defaultWidth: 46,
+ minWidth: 44,
+ maxWidth: 96,
+ },
+ subtool: {
+ id: 'subtool',
+ title: 'Sub Tool',
+ shortTitle: 'Sub',
+ defaultSide: 'left',
+ defaultWidth: 196,
+ minWidth: 140,
+ maxWidth: 340,
+ },
+ 'tool-property': {
+ id: 'tool-property',
+ title: 'Tool Property',
+ shortTitle: 'Prop',
+ defaultSide: 'left',
+ defaultWidth: 196,
+ minWidth: 148,
+ maxWidth: 340,
+ },
+ 'brush-size': {
+ id: 'brush-size',
+ title: 'Brush Size',
+ shortTitle: 'Size',
+ defaultSide: 'left',
+ defaultWidth: 196,
+ minWidth: 148,
+ maxWidth: 340,
+ },
+ color: {
+ id: 'color',
+ title: 'Color Wheel',
+ shortTitle: 'Color',
+ defaultSide: 'right',
+ defaultWidth: 224,
+ minWidth: 168,
+ maxWidth: 360,
+ },
+ layers: {
+ id: 'layers',
+ title: 'Layer',
+ shortTitle: 'Layer',
+ defaultSide: 'right',
+ defaultWidth: 224,
+ minWidth: 176,
+ maxWidth: 380,
+ },
+ history: {
+ id: 'history',
+ title: 'History',
+ shortTitle: 'Hist',
+ defaultSide: 'right',
+ defaultWidth: 224,
+ minWidth: 160,
+ maxWidth: 340,
+ },
+ 'quick-access': {
+ id: 'quick-access',
+ title: 'Quick Access',
+ shortTitle: 'Quick',
+ defaultSide: 'right',
+ defaultWidth: 184,
+ minWidth: 136,
+ maxWidth: 320,
+ },
+};
+
+export interface CommandCatalogEntry {
+ id: CommandActionId;
+ label: string;
+ shortLabel: string;
+ shortcut?: string;
+}
+
+export const COMMAND_CATALOG: CommandCatalogEntry[] = [
+ { id: 'save', label: 'Save', shortLabel: 'Save', shortcut: 'Ctrl+S' },
+ { id: 'save-as', label: 'Save As', shortLabel: 'Save As', shortcut: 'Ctrl+Shift+S' },
+ { id: 'undo', label: 'Undo', shortLabel: 'Undo', shortcut: 'Ctrl+Z' },
+ { id: 'redo', label: 'Redo', shortLabel: 'Redo', shortcut: 'Ctrl+Y' },
+ { id: 'flip-h', label: 'Flip Horizontal', shortLabel: 'Flip H', shortcut: 'Shift+H' },
+ { id: 'flip-v', label: 'Flip Vertical', shortLabel: 'Flip V', shortcut: 'Shift+V' },
+ { id: 'clear-layer', label: 'Clear Layer', shortLabel: 'Clear' },
+ { id: 'merge-down', label: 'Merge Down', shortLabel: 'Merge' },
+ { id: 'new-layer', label: 'New Layer', shortLabel: 'New Lyr', shortcut: 'Ctrl+Shift+N' },
+ { id: 'duplicate-layer', label: 'Duplicate Layer', shortLabel: 'Dup Lyr', shortcut: 'Ctrl+J' },
+ { id: 'transform', label: 'Free Transform', shortLabel: 'Transf', shortcut: 'Ctrl+T' },
+ { id: 'deselect', label: 'Deselect', shortLabel: 'Desel', shortcut: 'Ctrl+D' },
+ { id: 'reset-zoom', label: 'Reset Zoom', shortLabel: 'Fit', shortcut: 'Ctrl+0' },
+ { id: 'reset-rotation', label: 'Reset Rotation', shortLabel: '0°', shortcut: 'Ctrl+Alt+0' },
+ { id: 'swap-colors', label: 'Swap Colors', shortLabel: 'Swap', shortcut: 'X' },
+ { id: 'transparent-ink', label: 'Transparent Ink', shortLabel: 'Transp', shortcut: 'C' },
+ { id: 'toggle-palettes', label: 'Hide/Show Palettes', shortLabel: 'Palettes', shortcut: 'Tab' },
+];
+
+export const WORKSPACE_PRESET_LABELS: Record<WorkspacePresetId, string> = {
+ 'default-illustration': 'Default Illustration',
+ 'manga-studio': 'Manga Studio',
+ 'minimalist-tablet': 'Minimalist Tablet',
+ custom: 'Custom',
+};
diff --git a/src/utils/__tests__/workspaceDock.test.tsx b/src/utils/__tests__/workspaceDock.test.tsx
new file mode 100644
index 0000000..25817d8
--- /dev/null
+++ b/src/utils/__tests__/workspaceDock.test.tsx
@@ -0,0 +1,493 @@
+import { act } from 'react';
+import { createRoot, Root } from 'react-dom/client';
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import {
+ WORKSPACE_STORAGE_KEY,
+ findPanelLocation,
+ loadWorkspaceState,
+} from '../workspacePresets';
+import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';
+import { useUiStore } from '../../stores/useUiStore';
+import { BrushSizePalette } from '../../components/BrushSizePalette';
+import { StatusBar } from '../../components/StatusBar';
+import { DocumentTabBar } from '../../components/DocumentTabBar';
+import { BrushSettings, DocumentTab } 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) {}
+}
+
+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 = '';
+ attrs = new Map<string, string>();
+
+ 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)] : [];
+ }
+
+ 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>;
+ 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() {
+ 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,
+ 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 rafQueue: FrameRequestCallback[] = [];
+
+ const mockDoc = {
+ 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>,
+ 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),
+ } as MiniDoc;
+
+ mockDoc.documentElement = new MiniEl('html', mockDoc);
+ mockDoc.body = new MiniEl('body', mockDoc);
+ mockDoc.documentElement.appendChild(mockDoc.body);
+ mockDoc.activeElement = mockDoc.body;
+
+ class MockIFrame extends MiniEl {}
+
+ const rafMock = (cb: FrameRequestCallback) => {
+ rafQueue.push(cb);
+ return rafQueue.length;
+ };
+ const cancelRafMock = () => {};
+
+ const mockWin: Record<string, unknown> = {
+ innerWidth: 1440,
+ innerHeight: 900,
+ 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.requestAnimationFrame = rafMock;
+ g.cancelAnimationFrame = cancelRafMock;
+
+ const container = new MiniEl('div', mockDoc);
+ mockDoc.body.appendChild(container);
+
+ return {
+ container,
+ flushRaf: () => {
+ const batch = rafQueue.splice(0, rafQueue.length);
+ for (const cb of batch) cb(16);
+ },
+ cleanup: () => {
+ for (const [k, v] of Object.entries(saved)) {
+ if (v === undefined) delete g[k];
+ else g[k] = v;
+ }
+ },
+ };
+}
+
+describe('CSP Dock Workspace, Presets & Persistence', () => {
+ const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;
+
+ beforeEach(() => {
+ Object.defineProperty(globalThis, 'localStorage', {
+ value: createMemoryStorage(),
+ configurable: true,
+ writable: true,
+ });
+ useWorkspaceStore.reset();
+ useUiStore.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('moves any palette from right dock to left dock, collapses to compact strip, and persists across reload', () => {
+ const initialLoc = findPanelLocation(useWorkspaceStore.getState().layout, 'layers');
+ expect(initialLoc?.side).toBe('right');
+
+ // Move layers from right dock to left dock
+ workspaceStoreActions.movePanel('layers', { side: 'left' });
+ const movedLoc = findPanelLocation(useWorkspaceStore.getState().layout, 'layers');
+ expect(movedLoc?.side).toBe('left');
+ expect(useWorkspaceStore.getState().activePreset).toBe('custom');
+
+ // Collapse that column into compact icon strip and open popover
+ workspaceStoreActions.toggleColumnCollapsed(movedLoc!.colId, true);
+ const collapsedCol = useWorkspaceStore
+ .getState()
+ .layout.leftDocks.find((c) => c.id === movedLoc!.colId);
+ expect(collapsedCol?.collapsed).toBe(true);
+
+ workspaceStoreActions.togglePopover(movedLoc!.colId, 'layers');
+ expect(useWorkspaceStore.getState().openPopover).toEqual({
+ colId: movedLoc!.colId,
+ panelId: 'layers',
+ });
+
+ // Simulate full app reload from localStorage
+ useWorkspaceStore.reset();
+ const reloaded = useWorkspaceStore.getState();
+ expect(reloaded.activePreset).toBe('custom');
+ const reloadedLoc = findPanelLocation(reloaded.layout, 'layers');
+ expect(reloadedLoc?.side).toBe('left');
+ const reloadedCol = reloaded.layout.leftDocks.find((c) => c.id === reloadedLoc!.colId);
+ expect(reloadedCol?.collapsed).toBe(true);
+ });
+
+ it('toggles all palettes off and back on (Tab behavior) while staying synced with useUiStore', () => {
+ expect(useWorkspaceStore.getState().palettesHidden).toBe(false);
+
+ const hidden = workspaceStoreActions.togglePalettesHidden();
+ expect(hidden).toBe(true);
+ expect(useWorkspaceStore.getState().palettesHidden).toBe(true);
+ expect(useUiStore.getState().isLeftPanelHidden).toBe(true);
+ expect(useUiStore.getState().isRightSidebarHidden).toBe(true);
+
+ const restored = workspaceStoreActions.togglePalettesHidden();
+ expect(restored).toBe(false);
+ expect(useWorkspaceStore.getState().palettesHidden).toBe(false);
+ expect(useUiStore.getState().isLeftPanelHidden).toBe(false);
+ expect(useUiStore.getState().isRightSidebarHidden).toBe(false);
+ });
+
+ it('switches workspace presets and supports Reset Workspace cleanly', () => {
+ workspaceStoreActions.applyPreset('minimalist-tablet');
+ expect(useWorkspaceStore.getState().activePreset).toBe('minimalist-tablet');
+ expect(useWorkspaceStore.getState().layout.rightDocks[0].collapsed).toBe(true);
+
+ workspaceStoreActions.applyPreset('manga-studio');
+ expect(useWorkspaceStore.getState().activePreset).toBe('manga-studio');
+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'brush-size')?.side).toBe('left');
+
+ // Mutate into custom then reset back to default illustration
+ workspaceStoreActions.movePanel('color', { side: 'left' });
+ expect(useWorkspaceStore.getState().activePreset).toBe('custom');
+
+ workspaceStoreActions.resetWorkspace();
+ expect(useWorkspaceStore.getState().activePreset).toBe('default-illustration');
+ expect(findPanelLocation(useWorkspaceStore.getState().layout, 'color')?.side).toBe('right');
+ });
+
+ it('persists Quick Access and Command Bar customizations and survives corrupt localStorage', () => {
+ workspaceStoreActions.addQuickAccessItem({
+ id: 'qa-custom-red',
+ kind: 'color',
+ label: 'Hero Red',
+ color: '#e11d48',
+ });
+ workspaceStoreActions.setQuickAccessViewMode('list');
+ workspaceStoreActions.toggleCommandBarItem('deselect');
+
+ useWorkspaceStore.reset();
+ expect(
+ useWorkspaceStore.getState().quickAccessItems.some((i) => i.id === 'qa-custom-red')
+ ).toBe(true);
+ expect(useWorkspaceStore.getState().quickAccessViewMode).toBe('list');
+ expect(useWorkspaceStore.getState().commandBarIds).toContain('deselect');
+
+ // Corrupt storage falls back cleanly without throwing
+ localStorage.setItem(WORKSPACE_STORAGE_KEY, '{corrupt json');
+ const safe = loadWorkspaceState();
+ expect(safe.activePreset).toBe('default-illustration');
+ expect(safe.layout.leftDocks.length).toBeGreaterThan(0);
+ expect(safe.layout.rightDocks.length).toBeGreaterThan(0);
+ });
+});
+
+describe('Activated Components (BrushSizePalette, StatusBar, DocumentTabBar) in Both Themes', () => {
+ let dom: ReturnType<typeof installMiniDom>;
+ let root: Root | null = null;
+
+ beforeEach(() => {
+ dom = installMiniDom();
+ });
+
+ afterEach(() => {
+ if (root) {
+ act(() => {
+ root?.unmount();
+ });
+ root = null;
+ }
+ dom.cleanup();
+ });
+
+ it('renders BrushSizePalette, StatusBar (live pointer-stat + rotation reset), and DocumentTabBar (dirty *) in modern and vintage-manga themes', () => {
+ const onSelectSize = vi.fn();
+ const onResetRotation = vi.fn();
+ const onCloseDocument = vi.fn();
+ const brushSettings = {
+ preset: 'g-pen',
+ size: 10,
+ minSizeFactor: 0.2,
+ color: '#000000',
+ opacity: 1,
+ flow: 1,
+ spacing: 0.08,
+ grain: 0,
+ usePressure: true,
+ smoothing: true,
+ stabilization: 12,
+ } as BrushSettings;
+
+ const docs: DocumentTab[] = [
+ {
+ id: 'doc-1',
+ name: 'Chapter1.sora',
+ isDirty: true,
+ dimensions: { width: 1920, height: 1080, dpi: 300 },
+ colorMode: 'color',
+ layers: [],
+ activeLayerId: 'l1',
+ },
+ {
+ id: 'doc-2',
+ name: 'Cover.sora',
+ isDirty: false,
+ dimensions: { width: 2480, height: 3508, dpi: 600 },
+ colorMode: 'monochrome',
+ layers: [],
+ activeLayerId: 'l2',
+ },
+ ];
+
+ for (const theme of ['modern', 'vintage-manga'] as const) {
+ act(() => {
+ if (!root) root = createRoot(dom.container as unknown as Element);
+ root.render(
+ <div>
+ <DocumentTabBar
+ documents={docs}
+ activeDocumentId="doc-1"
+ onSelectDocument={() => {}}
+ onCloseDocument={onCloseDocument}
+ onNewDocument={() => {}}
+ themePreset={theme}
+ />
+ <BrushSizePalette
+ currentSize={10}
+ onSelectSize={onSelectSize}
+ activeBrushName="G-Pen"
+ tool="brush"
+ presetId="g-pen"
+ themePreset={theme}
+ />
+ <StatusBar
+ tool="brush"
+ brushSettings={brushSettings}
+ zoom={1.5}
+ rotation={45}
+ onResetRotation={onResetRotation}
+ colorMode="color"
+ showCursorCoordinates
+ showPressureInStatusBar
+ hasOpenDocument
+ themePreset={theme}
+ />
+ </div>
+ );
+ });
+
+ const tabBar = dom.container.findByAttr('data-testid', 'document-tab-bar');
+ const dirtyStar = dom.container.findByAttr('data-testid', 'dirty-indicator-doc-1');
+ const cleanStar = dom.container.findByAttr('data-testid', 'dirty-indicator-doc-2');
+ const brushPalette = dom.container.findByAttr('data-testid', 'brush-size-palette');
+ const statusBar = dom.container.findByAttr('data-testid', 'status-bar');
+
+ expect(tabBar?.getAttribute('data-theme-preset')).toBe(theme);
+ expect(dirtyStar?.textContent).toBe('*');
+ expect(cleanStar).toBeNull();
+ expect(brushPalette?.getAttribute('data-theme-preset')).toBe(theme);
+ expect(statusBar?.getAttribute('data-theme-preset')).toBe(theme);
+ expect(statusBar?.textContent).toContain('150%');
+ expect(statusBar?.textContent).toContain('45°');
+
+ // Fire canvas-pointer-stat event and verify StatusBar live DOM updates
+ act(() => {
+ window.dispatchEvent(
+ new CustomEvent('canvas-pointer-stat', { detail: { x: 420, y: 180, pressure: 0.75 } })
+ );
+ dom.flushRaf();
+ });
+ expect(statusBar?.textContent).toContain('420, 180px');
+ expect(statusBar?.textContent).toContain('75%');
+ }
+ });
+});
diff --git a/src/utils/workspacePresets.ts b/src/utils/workspacePresets.ts
new file mode 100644
index 0000000..c9c98fe
--- /dev/null
+++ b/src/utils/workspacePresets.ts
@@ -0,0 +1,773 @@
+import {
+ ALL_DOCK_PANEL_IDS,
+ COMMAND_CATALOG,
+ CommandActionId,
+ DOCK_PANEL_META,
+ DockColumn,
+ DockGroup,
+ DockPanelId,
+ DockSide,
+ PersistedWorkspaceState,
+ QuickAccessItem,
+ QuickAccessViewMode,
+ WorkspaceLayout,
+ WorkspacePresetId,
+} from '../types/workspace';
+
+export const WORKSPACE_STORAGE_KEY = 'ink_studio_workspace_v1';
+
+const VALID_PANEL_SET = new Set<string>(ALL_DOCK_PANEL_IDS);
+const VALID_COMMAND_SET = new Set<string>(COMMAND_CATALOG.map((c) => c.id));
+
+export const DEFAULT_ILLUSTRATION_LAYOUT: WorkspaceLayout = {
+ leftDocks: [
+ {
+ id: 'col-left-tools',
+ width: 46,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-tools',
+ panelIds: ['tools'],
+ activePanelId: 'tools',
+ heightRatio: 1,
+ },
+ ],
+ },
+ {
+ id: 'col-left-brushes',
+ width: 204,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-subtool',
+ panelIds: ['subtool'],
+ activePanelId: 'subtool',
+ heightRatio: 0.34,
+ },
+ {
+ id: 'grp-tool-prop',
+ panelIds: ['tool-property'],
+ activePanelId: 'tool-property',
+ heightRatio: 0.38,
+ },
+ {
+ id: 'grp-brush-size',
+ panelIds: ['brush-size'],
+ activePanelId: 'brush-size',
+ heightRatio: 0.28,
+ },
+ ],
+ },
+ ],
+ rightDocks: [
+ {
+ id: 'col-right-quick',
+ width: 180,
+ collapsed: true,
+ groups: [
+ {
+ id: 'grp-quick-access',
+ panelIds: ['quick-access'],
+ activePanelId: 'quick-access',
+ heightRatio: 1,
+ },
+ ],
+ },
+ {
+ id: 'col-right-main',
+ width: 224,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-color',
+ panelIds: ['color'],
+ activePanelId: 'color',
+ heightRatio: 0.3,
+ },
+ {
+ id: 'grp-layers-history',
+ panelIds: ['layers', 'history'],
+ activePanelId: 'layers',
+ heightRatio: 0.7,
+ },
+ ],
+ },
+ ],
+};
+
+export const MANGA_STUDIO_LAYOUT: WorkspaceLayout = {
+ leftDocks: [
+ {
+ id: 'col-manga-tools',
+ width: 46,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-manga-tools',
+ panelIds: ['tools'],
+ activePanelId: 'tools',
+ heightRatio: 1,
+ },
+ ],
+ },
+ {
+ id: 'col-manga-ink',
+ width: 196,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-manga-subtool',
+ panelIds: ['subtool'],
+ activePanelId: 'subtool',
+ heightRatio: 0.45,
+ },
+ {
+ id: 'grp-manga-size',
+ panelIds: ['brush-size'],
+ activePanelId: 'brush-size',
+ heightRatio: 0.55,
+ },
+ ],
+ },
+ {
+ id: 'col-manga-prop',
+ width: 184,
+ collapsed: true,
+ groups: [
+ {
+ id: 'grp-manga-prop',
+ panelIds: ['tool-property'],
+ activePanelId: 'tool-property',
+ heightRatio: 1,
+ },
+ ],
+ },
+ ],
+ rightDocks: [
+ {
+ id: 'col-manga-quick',
+ width: 168,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-manga-quick',
+ panelIds: ['quick-access'],
+ activePanelId: 'quick-access',
+ heightRatio: 0.65,
+ },
+ {
+ id: 'grp-manga-color',
+ panelIds: ['color'],
+ activePanelId: 'color',
+ heightRatio: 0.35,
+ },
+ ],
+ },
+ {
+ id: 'col-manga-layers',
+ width: 232,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-manga-layers',
+ panelIds: ['layers'],
+ activePanelId: 'layers',
+ heightRatio: 0.72,
+ },
+ {
+ id: 'grp-manga-history',
+ panelIds: ['history'],
+ activePanelId: 'history',
+ heightRatio: 0.28,
+ },
+ ],
+ },
+ ],
+};
+
+export const MINIMALIST_TABLET_LAYOUT: WorkspaceLayout = {
+ leftDocks: [
+ {
+ id: 'col-tablet-tools',
+ width: 46,
+ collapsed: false,
+ groups: [
+ {
+ id: 'grp-tablet-tools',
+ panelIds: ['tools'],
+ activePanelId: 'tools',
+ heightRatio: 1,
+ },
+ ],
+ },
+ {
+ id: 'col-tablet-left-strip',
+ width: 210,
+ collapsed: true,
+ groups: [
+ {
+ id: 'grp-tablet-brush',
+ panelIds: ['subtool', 'tool-property', 'brush-size', 'color'],
+ activePanelId: 'subtool',
+ heightRatio: 1,
+ },
+ ],
+ },
+ ],
+ rightDocks: [
+ {
+ id: 'col-tablet-right-strip',
+ width: 224,
+ collapsed: true,
+ groups: [
+ {
+ id: 'grp-tablet-layers',
+ panelIds: ['layers', 'history', 'quick-access'],
+ activePanelId: 'layers',
+ heightRatio: 1,
+ },
+ ],
+ },
+ ],
+};
+
+export const DEFAULT_QUICK_ACCESS_ITEMS: QuickAccessItem[] = [
+ { id: 'qa-flip-h', kind: 'command', label: 'Flip Horizontal', commandId: 'flip-h' },
+ { id: 'qa-clear-layer', kind: 'command', label: 'Clear Layer', commandId: 'clear-layer' },
+ { id: 'qa-merge-down', kind: 'command', label: 'Merge Down', commandId: 'merge-down' },
+ { id: 'qa-save', kind: 'command', label: 'Save', commandId: 'save' },
+ { id: 'qa-undo', kind: 'command', label: 'Undo', commandId: 'undo' },
+ { id: 'qa-redo', kind: 'command', label: 'Redo', commandId: 'redo' },
+ { id: 'qa-new-layer', kind: 'command', label: 'New Layer', commandId: 'new-layer' },
+ { id: 'qa-reset-zoom', kind: 'command', label: 'Reset Zoom', commandId: 'reset-zoom' },
+ { id: 'qa-tool-brush', kind: 'tool', label: 'Brush', toolId: 'brush' },
+ { id: 'qa-tool-eraser', kind: 'tool', label: 'Eraser', toolId: 'eraser' },
+ { id: 'qa-color-black', kind: 'color', label: 'Ink Black', color: '#000000' },
+ { id: 'qa-color-white', kind: 'color', label: 'Paper White', color: '#ffffff' },
+];
+
+export const DEFAULT_COMMAND_BAR_IDS: CommandActionId[] = [
+ 'save',
+ 'undo',
+ 'redo',
+ 'flip-h',
+ 'flip-v',
+ 'clear-layer',
+ 'merge-down',
+ 'toggle-palettes',
+];
+
+export function cloneLayout(layout: WorkspaceLayout): WorkspaceLayout {
+ return {
+ leftDocks: layout.leftDocks.map((col) => ({
+ ...col,
+ groups: col.groups.map((g) => ({
+ ...g,
+ panelIds: [...g.panelIds],
+ })),
+ })),
+ rightDocks: layout.rightDocks.map((col) => ({
+ ...col,
+ groups: col.groups.map((g) => ({
+ ...g,
+ panelIds: [...g.panelIds],
+ })),
+ })),
+ };
+}
+
+export function getPresetLayout(preset: Exclude<WorkspacePresetId, 'custom'>): WorkspaceLayout {
+ switch (preset) {
+ case 'manga-studio':
+ return cloneLayout(MANGA_STUDIO_LAYOUT);
+ case 'minimalist-tablet':
+ return cloneLayout(MINIMALIST_TABLET_LAYOUT);
+ case 'default-illustration':
+ default:
+ return cloneLayout(DEFAULT_ILLUSTRATION_LAYOUT);
+ }
+}
+
+export function listVisiblePanelIds(layout: WorkspaceLayout): Set<DockPanelId> {
+ const out = new Set<DockPanelId>();
+ for (const col of [...layout.leftDocks, ...layout.rightDocks]) {
+ for (const grp of col.groups) {
+ for (const pid of grp.panelIds) {
+ out.add(pid);
+ }
+ }
+ }
+ return out;
+}
+
+export function findPanelLocation(
+ layout: WorkspaceLayout,
+ panelId: DockPanelId
+): { side: DockSide; colId: string; groupId: string } | null {
+ for (const side of ['left', 'right'] as const) {
+ const cols = side === 'left' ? layout.leftDocks : layout.rightDocks;
+ for (const col of cols) {
+ for (const grp of col.groups) {
+ if (grp.panelIds.includes(panelId)) {
+ return { side, colId: col.id, groupId: grp.id };
+ }
+ }
+ }
+ }
+ return null;
+}
+
+function pruneEmptyContainers(columns: DockColumn[]): DockColumn[] {
+ return columns
+ .map((col) => {
+ const nonEmptyGroups = col.groups
+ .filter((g) => g.panelIds.length > 0)
+ .map((g) => ({
+ ...g,
+ activePanelId: g.panelIds.includes(g.activePanelId) ? g.activePanelId : g.panelIds[0],
+ }));
+ if (nonEmptyGroups.length === 0) return null;
+ const totalRatio = nonEmptyGroups.reduce((acc, g) => acc + (g.heightRatio || 1), 0) || 1;
+ return {
+ ...col,
+ groups: nonEmptyGroups.map((g) => ({
+ ...g,
+ heightRatio: Math.max(0.1, (g.heightRatio || 1) / totalRatio),
+ })),
+ };
+ })
+ .filter((c): c is DockColumn => c !== null);
+}
+
+export function removePanelFromLayout(
+ layout: WorkspaceLayout,
+ panelId: DockPanelId
+): WorkspaceLayout {
+ const stripCols = (cols: DockColumn[]) =>
+ pruneEmptyContainers(
+ cols.map((col) => ({
+ ...col,
+ groups: col.groups.map((g) => ({
+ ...g,
+ panelIds: g.panelIds.filter((id) => id !== panelId),
+ })),
+ }))
+ );
+
+ return {
+ leftDocks: stripCols(layout.leftDocks),
+ rightDocks: stripCols(layout.rightDocks),
+ };
+}
+
+let uidSeq = 1;
+function makeUid(prefix: string): string {
+ uidSeq += 1;
+ return `${prefix}-${Date.now().toString(36)}-${uidSeq}`;
+}
+
+export interface MovePanelTarget {
+ side: DockSide;
+ /** Target existing column id, or omit to create a new column on `side` */
+ targetColId?: string;
+ /** Target existing group id to merge as a tab */
+ targetGroupId?: string;
+ /** Insert as a new vertical group at index inside `targetColId` */
+ insertGroupIndex?: number;
+ /** Insert as a brand new dock column at index on `side` */
+ insertColumnIndex?: number;
+}
+
+export function movePanelInLayout(
+ layout: WorkspaceLayout,
+ panelId: DockPanelId,
+ target: MovePanelTarget
+): WorkspaceLayout {
+ // No-op if dropping onto the exact same single-panel group
+ const current = findPanelLocation(layout, panelId);
+ if (
+ current &&
+ current.side === target.side &&
+ current.colId === target.targetColId &&
+ current.groupId === target.targetGroupId
+ ) {
+ return setGroupActivePanelInLayout(layout, current.colId, current.groupId, panelId);
+ }
+
+ const cleaned = removePanelFromLayout(layout, panelId);
+ const next = cloneLayout(cleaned);
+ const targetCols = target.side === 'left' ? next.leftDocks : next.rightDocks;
+ const meta = DOCK_PANEL_META[panelId];
+
+ // 1. Merge into an existing group as a tab
+ if (target.targetColId && target.targetGroupId) {
+ const col = targetCols.find((c) => c.id === target.targetColId);
+ const grp = col?.groups.find((g) => g.id === target.targetGroupId);
+ if (col && grp) {
+ if (!grp.panelIds.includes(panelId)) {
+ grp.panelIds.push(panelId);
+ }
+ grp.activePanelId = panelId;
+ // If column was super narrow (e.g. tools 46px) and a regular palette joined it, expand width cleanly
+ if (col.width < meta.minWidth) {
+ col.width = meta.defaultWidth;
+ }
+ return next;
+ }
+ }
+
+ // 2. Insert as a new stacked group inside an existing column
+ if (target.targetColId) {
+ const col = targetCols.find((c) => c.id === target.targetColId);
+ if (col) {
+ const idx =
+ target.insertGroupIndex !== undefined
+ ? Math.max(0, Math.min(col.groups.length, target.insertGroupIndex))
+ : col.groups.length;
+ const newRatio = 1 / (col.groups.length + 1);
+ const scale = 1 - newRatio;
+ col.groups = col.groups.map((g) => ({ ...g, heightRatio: g.heightRatio * scale }));
+ col.groups.splice(idx, 0, {
+ id: makeUid('grp'),
+ panelIds: [panelId],
+ activePanelId: panelId,
+ heightRatio: newRatio,
+ });
+ if (col.width < meta.minWidth) {
+ col.width = meta.defaultWidth;
+ }
+ return next;
+ }
+ }
+
+ // 3. Create a new dock column on `target.side`
+ const newCol: DockColumn = {
+ id: makeUid(`col-${target.side}`),
+ width: meta.defaultWidth,
+ collapsed: false,
+ groups: [
+ {
+ id: makeUid('grp'),
+ panelIds: [panelId],
+ activePanelId: panelId,
+ heightRatio: 1,
+ },
+ ],
+ };
+
+ if (target.insertColumnIndex !== undefined) {
+ const idx = Math.max(0, Math.min(targetCols.length, target.insertColumnIndex));
+ targetCols.splice(idx, 0, newCol);
+ } else if (target.side === 'left') {
+ targetCols.push(newCol);
+ } else {
+ targetCols.unshift(newCol);
+ }
+
+ return next;
+}
+
+export function setGroupActivePanelInLayout(
+ layout: WorkspaceLayout,
+ colId: string,
+ groupId: string,
+ panelId: DockPanelId
+): WorkspaceLayout {
+ const mapCols = (cols: DockColumn[]) =>
+ cols.map((col) =>
+ col.id !== colId
+ ? col
+ : {
+ ...col,
+ groups: col.groups.map((g) =>
+ g.id !== groupId || !g.panelIds.includes(panelId)
+ ? g
+ : { ...g, activePanelId: panelId }
+ ),
+ }
+ );
+
+ return {
+ leftDocks: mapCols(layout.leftDocks),
+ rightDocks: mapCols(layout.rightDocks),
+ };
+}
+
+export function toggleColumnCollapsedInLayout(
+ layout: WorkspaceLayout,
+ colId: string,
+ forceValue?: boolean
+): WorkspaceLayout {
+ const mapCols = (cols: DockColumn[]) =>
+ cols.map((col) =>
+ col.id !== colId
+ ? col
+ : { ...col, collapsed: forceValue !== undefined ? forceValue : !col.collapsed }
+ );
+
+ return {
+ leftDocks: mapCols(layout.leftDocks),
+ rightDocks: mapCols(layout.rightDocks),
+ };
+}
+
+export function getColumnWidthBounds(col: DockColumn): { min: number; max: number } {
+ const panels = col.groups.flatMap((g) => g.panelIds);
+ if (panels.length === 1 && panels[0] === 'tools') {
+ return { min: 44, max: 92 };
+ }
+ let min = 136;
+ let max = 380;
+ for (const pid of panels) {
+ const meta = DOCK_PANEL_META[pid];
+ if (meta) {
+ if (meta.minWidth > min && pid !== 'tools') min = meta.minWidth;
+ if (meta.maxWidth > max) max = meta.maxWidth;
+ }
+ }
+ return { min, max };
+}
+
+export function resizeColumnInLayout(
+ layout: WorkspaceLayout,
+ colId: string,
+ requestedWidth: number
+): WorkspaceLayout {
+ const mapCols = (cols: DockColumn[]) =>
+ cols.map((col) => {
+ if (col.id !== colId) return col;
+ const { min, max } = getColumnWidthBounds(col);
+ const clamped = Math.max(min, Math.min(max, Math.round(requestedWidth)));
+ if (clamped === col.width) return col;
+ return { ...col, width: clamped };
+ });
+
+ return {
+ leftDocks: mapCols(layout.leftDocks),
+ rightDocks: mapCols(layout.rightDocks),
+ };
+}
+
+export function resizeGroupSplitInLayout(
+ layout: WorkspaceLayout,
+ colId: string,
+ topGroupId: string,
+ bottomGroupId: string,
+ nextTopRatio: number,
+ nextBottomRatio: number
+): WorkspaceLayout {
+ const mapCols = (cols: DockColumn[]) =>
+ cols.map((col) => {
+ if (col.id !== colId) return col;
+ return {
+ ...col,
+ groups: col.groups.map((g) => {
+ if (g.id === topGroupId) return { ...g, heightRatio: Math.max(0.1, nextTopRatio) };
+ if (g.id === bottomGroupId) return { ...g, heightRatio: Math.max(0.1, nextBottomRatio) };
+ return g;
+ }),
+ };
+ });
+
+ return {
+ leftDocks: mapCols(layout.leftDocks),
+ rightDocks: mapCols(layout.rightDocks),
+ };
+}
+
+export function togglePanelInLayout(
+ layout: WorkspaceLayout,
+ panelId: DockPanelId
+): WorkspaceLayout {
+ const existing = findPanelLocation(layout, panelId);
+ if (existing) {
+ return removePanelFromLayout(layout, panelId);
+ }
+ const meta = DOCK_PANEL_META[panelId];
+ const targetCols = meta.defaultSide === 'left' ? layout.leftDocks : layout.rightDocks;
+ const preferredCol = targetCols.find(
+ (c) => !(c.groups.length === 1 && c.groups[0].panelIds.length === 1 && c.groups[0].panelIds[0] === 'tools')
+ );
+ if (preferredCol && panelId !== 'tools') {
+ return movePanelInLayout(layout, panelId, {
+ side: meta.defaultSide,
+ targetColId: preferredCol.id,
+ insertGroupIndex: preferredCol.groups.length,
+ });
+ }
+ return movePanelInLayout(layout, panelId, {
+ side: meta.defaultSide,
+ insertColumnIndex: meta.defaultSide === 'left' ? 0 : targetCols.length,
+ });
+}
+
+function sanitizeColumns(raw: unknown, seenPanels: Set<DockPanelId>): DockColumn[] {
+ if (!Array.isArray(raw)) return [];
+ const result: DockColumn[] = [];
+ for (const item of raw) {
+ if (!item || typeof item !== 'object') continue;
+ const rec = item as Record<string, unknown>;
+ const colId = typeof rec.id === 'string' && rec.id.trim() ? rec.id : makeUid('col');
+ const collapsed = Boolean(rec.collapsed);
+ const rawGroups = Array.isArray(rec.groups) ? rec.groups : [];
+ const groups: DockGroup[] = [];
+ for (const gItem of rawGroups) {
+ if (!gItem || typeof gItem !== 'object') continue;
+ const gRec = gItem as Record<string, unknown>;
+ const rawPids = Array.isArray(gRec.panelIds) ? gRec.panelIds : [];
+ const panelIds: DockPanelId[] = [];
+ for (const pid of rawPids) {
+ if (typeof pid === 'string' && VALID_PANEL_SET.has(pid)) {
+ const typedPid = pid as DockPanelId;
+ if (!seenPanels.has(typedPid)) {
+ seenPanels.add(typedPid);
+ panelIds.push(typedPid);
+ }
+ }
+ }
+ if (panelIds.length === 0) continue;
+ const activePanelId =
+ typeof gRec.activePanelId === 'string' && panelIds.includes(gRec.activePanelId as DockPanelId)
+ ? (gRec.activePanelId as DockPanelId)
+ : panelIds[0];
+ const heightRatio =
+ typeof gRec.heightRatio === 'number' && Number.isFinite(gRec.heightRatio) && gRec.heightRatio > 0
+ ? gRec.heightRatio
+ : 1;
+ groups.push({
+ id: typeof gRec.id === 'string' && gRec.id.trim() ? gRec.id : makeUid('grp'),
+ panelIds,
+ activePanelId,
+ heightRatio,
+ });
+ }
+ if (groups.length === 0) continue;
+ const tentativeCol: DockColumn = { id: colId, width: 200, collapsed, groups };
+ const { min, max } = getColumnWidthBounds(tentativeCol);
+ const width =
+ typeof rec.width === 'number' && Number.isFinite(rec.width)
+ ? Math.max(min, Math.min(max, Math.round(rec.width)))
+ : Math.max(min, Math.min(max, 200));
+ result.push({ ...tentativeCol, width });
+ }
+ return pruneEmptyContainers(result);
+}
+
+export function sanitizeLayout(raw: unknown): WorkspaceLayout | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const rec = raw as Record<string, unknown>;
+ const seen = new Set<DockPanelId>();
+ const leftDocks = sanitizeColumns(rec.leftDocks, seen);
+ const rightDocks = sanitizeColumns(rec.rightDocks, seen);
+ if (leftDocks.length === 0 && rightDocks.length === 0) return null;
+ return { leftDocks, rightDocks };
+}
+
+function sanitizeQuickAccessItems(raw: unknown): QuickAccessItem[] {
+ if (!Array.isArray(raw)) return DEFAULT_QUICK_ACCESS_ITEMS.map((x) => ({ ...x }));
+ const items: QuickAccessItem[] = [];
+ for (const item of raw) {
+ if (!item || typeof item !== 'object') continue;
+ const r = item as Record<string, unknown>;
+ const id = typeof r.id === 'string' && r.id.trim() ? r.id : makeUid('qa');
+ const label = typeof r.label === 'string' && r.label.trim() ? r.label.slice(0, 48) : 'Action';
+ if (r.kind === 'command' && typeof r.commandId === 'string' && VALID_COMMAND_SET.has(r.commandId)) {
+ items.push({ id, kind: 'command', label, commandId: r.commandId as CommandActionId });
+ } else if (r.kind === 'tool' && typeof r.toolId === 'string') {
+ items.push({ id, kind: 'tool', label, toolId: r.toolId as QuickAccessItem['toolId'] });
+ } else if (
+ r.kind === 'color' &&
+ typeof r.color === 'string' &&
+ /^#[0-9a-fA-F]{3,6}$/.test(r.color)
+ ) {
+ items.push({ id, kind: 'color', label, color: r.color });
+ } else if (r.kind === 'brush' && typeof r.brushPresetId === 'string' && r.brushPresetId.trim()) {
+ items.push({ id, kind: 'brush', label, brushPresetId: r.brushPresetId });
+ }
+ }
+ return items;
+}
+
+function sanitizeCommandBarIds(raw: unknown): CommandActionId[] {
+ if (!Array.isArray(raw)) return [...DEFAULT_COMMAND_BAR_IDS];
+ const seen = new Set<CommandActionId>();
+ const out: CommandActionId[] = [];
+ for (const item of raw) {
+ if (typeof item === 'string' && VALID_COMMAND_SET.has(item)) {
+ const id = item as CommandActionId;
+ if (!seen.has(id)) {
+ seen.add(id);
+ out.push(id);
+ }
+ }
+ }
+ return out;
+}
+
+export function createDefaultPersistedWorkspace(): PersistedWorkspaceState {
+ return {
+ version: 1,
+ activePreset: 'default-illustration',
+ layout: cloneLayout(DEFAULT_ILLUSTRATION_LAYOUT),
+ savedCustomLayout: null,
+ quickAccessItems: DEFAULT_QUICK_ACCESS_ITEMS.map((x) => ({ ...x })),
+ quickAccessViewMode: 'grid',
+ commandBarIds: [...DEFAULT_COMMAND_BAR_IDS],
+ showStatusBar: true,
+ showDocumentTabs: true,
+ showCommandBar: true,
+ };
+}
+
+export function loadWorkspaceState(): PersistedWorkspaceState {
+ const fallback = createDefaultPersistedWorkspace();
+ try {
+ if (typeof localStorage === 'undefined') return fallback;
+ const raw = localStorage.getItem(WORKSPACE_STORAGE_KEY);
+ if (!raw) return fallback;
+ const parsed = JSON.parse(raw) as Record<string, unknown>;
+ if (!parsed || typeof parsed !== 'object') return fallback;
+
+ const validPresets: WorkspacePresetId[] = [
+ 'default-illustration',
+ 'manga-studio',
+ 'minimalist-tablet',
+ 'custom',
+ ];
+ const activePreset: WorkspacePresetId = validPresets.includes(parsed.activePreset as WorkspacePresetId)
+ ? (parsed.activePreset as WorkspacePresetId)
+ : 'default-illustration';
+
+ const layout = sanitizeLayout(parsed.layout) ?? fallback.layout;
+ const savedCustomLayout = sanitizeLayout(parsed.savedCustomLayout);
+ const quickAccessItems = sanitizeQuickAccessItems(parsed.quickAccessItems);
+ const quickAccessViewMode: QuickAccessViewMode =
+ parsed.quickAccessViewMode === 'list' ? 'list' : 'grid';
+ const commandBarIds = sanitizeCommandBarIds(parsed.commandBarIds);
+
+ return {
+ version: 1,
+ activePreset,
+ layout,
+ savedCustomLayout,
+ quickAccessItems,
+ quickAccessViewMode,
+ commandBarIds,
+ showStatusBar: typeof parsed.showStatusBar === 'boolean' ? parsed.showStatusBar : true,
+ showDocumentTabs: typeof parsed.showDocumentTabs === 'boolean' ? parsed.showDocumentTabs : true,
+ showCommandBar: typeof parsed.showCommandBar === 'boolean' ? parsed.showCommandBar : true,
+ };
+ } catch {
+ return fallback;
+ }
+}
+
+export function saveWorkspaceState(state: PersistedWorkspaceState): void {
+ try {
+ if (typeof localStorage === 'undefined') return;
+ localStorage.setItem(WORKSPACE_STORAGE_KEY, JSON.stringify(state));
+ } catch {
+ // Ignore storage quota/access errors
+ }
+}