Skip to content

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

preasure and modifier key settings

sora669d0df1c966
diff --git a/src/App.tsx b/src/App.tsx
index 82ec482..c4237be 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -234,7 +234,7 @@ export function App() {
const drawing = useCanvasDrawing({
dimensions,
colorMode,
- disabled: !hasOpenDocument || nav.isSpaceDown || nav.isPanning || nav.isRotating,
+ disabled: !hasOpenDocument || nav.isSpaceDown || nav.isPanning || nav.isRotating || nav.isZoomDragging,
viewportRef: nav.viewportRef,
pan: nav.pan,
zoom: nav.zoom,
@@ -572,8 +572,14 @@ export function App() {
isRotateModifier: nav.isRotateModifier,
isPanning: nav.isPanning,
isRotating: nav.isRotating,
+ isZoomDragging: nav.isZoomDragging,
startPan: nav.startPan,
startRotate: nav.startRotate,
+ startZoomDrag: nav.startZoomDrag,
+ onSampleColor: shapeFillTools.handleSampleColor,
+ onUndo: handleUndo,
+ onRedo: drawing.redo,
+ onFlipHorizontal: nav.toggleFlipHorizontal,
isHovering: drawing.isHovering,
cursorPos: drawing.cursorPos,
onPointerDown: handlePointerDown,
@@ -656,6 +662,9 @@ export function App() {
shapeFillTools.setActiveBalloon,
shapeFillTools.handleConfirmBalloon,
shapeFillTools.handleDeleteBalloon,
+ shapeFillTools.handleSampleColor,
+ handleUndo,
+ drawing.redo,
activeAnimationTimeline,
handleUpdateAnimationTimeline,
handleAddAnimationCel,
@@ -791,6 +800,10 @@ export function App() {
handleOpenTonalModal={tonalActions.handleOpenTonalModal}
handleUpdateAnimationTimeline={handleUpdateAnimationTimeline}
handleAddAnimationCel={handleAddAnimationCel}
+ zoomIn={nav.zoomIn}
+ zoomOut={nav.zoomOut}
+ resetZoomAndCenter={nav.resetZoomAndCenter}
+ resetRotation={nav.resetRotation}
toggleFlipHorizontal={nav.toggleFlipHorizontal}
toggleFlipVertical={nav.toggleFlipVertical}
handleClearSelection={selectionTools.handleClearSelection}
diff --git a/src/components/AppShell.tsx b/src/components/AppShell.tsx
index 4affa70..6ccc414 100644
--- a/src/components/AppShell.tsx
+++ b/src/components/AppShell.tsx
@@ -52,8 +52,14 @@ interface CanvasAreaContainerProps {
isRotateModifier: boolean;
isPanning: boolean;
isRotating: boolean;
+ isZoomDragging?: boolean;
startPan: (e: React.PointerEvent) => void;
startRotate: (e: React.PointerEvent) => void;
+ startZoomDrag?: (e: React.PointerEvent) => void;
+ onSampleColor?: (pt: { x: number; y: number }) => void;
+ onUndo?: () => void;
+ onRedo?: () => void;
+ onFlipHorizontal?: () => void;
isHovering: boolean;
cursorPos: { x: number; y: number } | null;
onPointerDown: (e: React.PointerEvent<HTMLElement>, coalescedEvents?: PointerEvent[]) => void;
@@ -190,8 +196,14 @@ const CanvasAreaContainer: React.FC<CanvasAreaContainerProps> = React.memo((prop
isRotateModifier={props.isRotateModifier}
isPanning={props.isPanning}
isRotating={props.isRotating}
+ isZoomDragging={props.isZoomDragging}
onStartPan={props.startPan}
onStartRotate={props.startRotate}
+ onStartZoomDrag={props.startZoomDrag}
+ onSampleColor={props.onSampleColor}
+ onUndo={props.onUndo}
+ onRedo={props.onRedo}
+ onFlipHorizontal={props.onFlipHorizontal}
isHovering={props.isHovering}
cursorPos={props.cursorPos}
onPointerDown={props.onPointerDown}
diff --git a/src/components/CanvasArea.tsx b/src/components/CanvasArea.tsx
index b6bc757..7ebb2f6 100644
--- a/src/components/CanvasArea.tsx
+++ b/src/components/CanvasArea.tsx
@@ -30,6 +30,13 @@ import { AnimationTimeline } from './AnimationTimeline';
import { AnimationTimeline as AnimationTimelineType } from '../types/editor';
import { getOnionSkinFrames } from '../utils/animationEngine';
import { FloatingBrushPill } from './FloatingBrushPill';
+import { screenToCanvas } from '../utils/canvasUtils';
+import {
+ resolveHeldKeyModifierAction,
+ resolvePointerModifierAction,
+} from '../utils/shortcutManager';
+import { toolStoreActions, useToolStore, useUiStore } from '../stores';
+import { ModifierAction } from '../types/settings';
const PIPETTE_CURSOR_CSS = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg stroke='%23000000' stroke-width='3.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3Cg stroke='%23ffffff' stroke-width='1.5' stroke-linecap='round' stroke-linejoin='round' fill='none'%3E%3Cpath d='m14 7 3 3'/%3E%3Cpath d='M16.6 5.6a2.12 2.12 0 0 1 3 3L7 20.6 2 22l1.4-5L16.6 5.6z'/%3E%3C/g%3E%3C/svg%3E") 2 22, crosshair`;
@@ -49,8 +56,14 @@ interface CanvasAreaProps {
isRotateModifier: boolean;
isPanning: boolean;
isRotating: boolean;
+ isZoomDragging?: boolean;
onStartPan: (e: React.PointerEvent) => void;
onStartRotate: (e: React.PointerEvent) => void;
+ onStartZoomDrag?: (e: React.PointerEvent) => void;
+ onSampleColor?: (pt: { x: number; y: number }) => void;
+ onUndo?: () => void;
+ onRedo?: () => void;
+ onFlipHorizontal?: () => void;
isHovering: boolean;
cursorPos: { x: number; y: number } | null;
onPointerDown: (e: React.PointerEvent<HTMLElement>, coalesced?: PointerEvent[]) => void;
@@ -210,8 +223,14 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
isRotateModifier,
isPanning,
isRotating,
+ isZoomDragging = false,
onStartPan,
onStartRotate,
+ onStartZoomDrag,
+ onSampleColor,
+ onUndo,
+ onRedo,
+ onFlipHorizontal,
isWebtoonMode = false,
onToggleWebtoonMode,
onOpenWebtoonExport,
@@ -391,9 +410,11 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
};
const lastPointerPosRef = useRef<{ x: number; y: number } | null>(null);
- // Dynamic on-canvas brush resizing via Ctrl + Alt + Drag
- const [isCtrlAltDown, setIsCtrlAltDown] = useState(false);
+ // Dynamic on-canvas brush resizing via configured modifier (default Ctrl + Alt + Drag or Shift + Alt + Drag)
+ const [heldModifierAction, setHeldModifierAction] = useState<ModifierAction>('none');
const [isResizingBrush, setIsResizingBrush] = useState(false);
+ const [quickPalettePos, setQuickPalettePos] = useState<{ x: number; y: number } | null>(null);
+ const tempEraserPrevToolRef = useRef<ToolType | null>(null);
const resizeOriginRef = useRef<{ clientX: number; clientY: number }>({ clientX: 0, clientY: 0 });
const resizeStartSettingsRef = useRef<{ size: number; hardness: number }>({
size: brushSettings.size,
@@ -470,8 +491,13 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
isSpaceDown ||
isPanning ||
isRotating ||
+ isZoomDragging ||
isRotateModifier ||
isResizingBrush ||
+ heldModifierAction === 'brush-size' ||
+ heldModifierAction === 'pan' ||
+ heldModifierAction === 'rotate' ||
+ heldModifierAction === 'zoom-drag' ||
(tool !== 'brush' && tool !== 'eraser' && tool !== 'liquify' && tool !== 'select-pen' && tool !== 'select-eraser')
) {
ring.style.display = 'none';
@@ -533,7 +559,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
viewport.removeEventListener('pointerenter', handleViewportPointerEnterOrDown);
viewport.removeEventListener('pointerleave', handlePointerLeave);
};
- }, [isSpaceDown, isPanning, isRotating, isRotateModifier, isResizingBrush, viewportRef, tool, hasOpenDocument]);
+ }, [isSpaceDown, isPanning, isRotating, isZoomDragging, isRotateModifier, isResizingBrush, heldModifierAction, viewportRef, tool, hasOpenDocument]);
// Compute colored onion skin frames and active cel isolation for animation
const onionSkinFrames = useMemo(() => {
@@ -899,23 +925,36 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
};
}, []);
- // Track Ctrl + Alt key combinations globally
+ // Track held modifier key combinations globally according to Modifier Key Settings
useEffect(() => {
+ const syncHeldAction = (e: KeyboardEvent, spaceOverride?: boolean) => {
+ const action = resolveHeldKeyModifierAction(
+ {
+ ctrl: e.ctrlKey || e.metaKey,
+ shift: e.shiftKey,
+ alt: e.altKey,
+ space: spaceOverride !== undefined ? spaceOverride : isSpaceDown,
+ },
+ useUiStore.getState().appSettings.modifierKeys
+ );
+ setHeldModifierAction(action);
+ };
+
const handleKeyDown = (e: KeyboardEvent) => {
- if ((e.ctrlKey || e.metaKey) && e.altKey) {
- setIsCtrlAltDown(true);
+ if (e.key === 'Escape' && quickPalettePos) {
+ setQuickPalettePos(null);
}
+ syncHeldAction(e, e.code === 'Space' ? true : undefined);
};
const handleKeyUp = (e: KeyboardEvent) => {
- if (!((e.ctrlKey || e.metaKey) && e.altKey)) {
- setIsCtrlAltDown(false);
- }
+ syncHeldAction(e, e.code === 'Space' ? false : undefined);
};
const handleBlur = () => {
- setIsCtrlAltDown(false);
+ setHeldModifierAction('none');
setIsResizingBrush(false);
+ setQuickPalettePos(null);
};
window.addEventListener('keydown', handleKeyDown);
@@ -926,7 +965,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('blur', handleBlur);
};
- }, []);
+ }, [isSpaceDown, quickPalettePos]);
// Handle active brush resizing window drag listeners
useEffect(() => {
@@ -1005,26 +1044,6 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
}
};
- // Viewport background pointer down (clicking gray area to pan or rotate)
- const handleViewportPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
- releaseExternalFocus();
- if (e.button === 1) {
- onStartPan(e);
- return;
- }
- if (e.button === 0) {
- if ((e.ctrlKey || e.metaKey) && e.altKey) {
- startBrushResize(e);
- return;
- }
- if (isRotateModifier) {
- onStartRotate(e);
- } else if (isSpaceDown) {
- onStartPan(e);
- }
- }
- };
-
// Start brush resizing drag
const startBrushResize = (e: React.PointerEvent) => {
e.preventDefault();
@@ -1037,29 +1056,177 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
};
};
- // Canvas pointer down: check for resize, rotate, pan, or normal draw
- const handleCanvasPointerDown = (e: React.PointerEvent<HTMLElement>) => {
+ // Start continuous eyedropper sampling for modifier buttons (e.g. Right Click / Barrel Button)
+ const startModifierEyedropper = (e: React.PointerEvent) => {
+ if (!onSampleColor || !viewportRef.current) return;
+ e.preventDefault();
+ e.stopPropagation();
+
+ const sampleAtClient = (clientX: number, clientY: number) => {
+ const vp = viewportRef.current;
+ if (!vp) return;
+ const rect = vp.getBoundingClientRect();
+ const cam = navigation
+ ? navigation.getCameraState()
+ : { pan, zoom, rotation, flipX, flipY };
+ const pt = screenToCanvas(
+ clientX,
+ clientY,
+ rect,
+ cam.pan,
+ cam.zoom,
+ cam.rotation,
+ dimensions,
+ cam.flipX,
+ cam.flipY
+ );
+ onSampleColor(pt);
+ };
+
+ sampleAtClient(e.clientX, e.clientY);
+
+ const handleMove = (ev: PointerEvent) => {
+ sampleAtClient(ev.clientX, ev.clientY);
+ };
+ const handleUp = () => {
+ window.removeEventListener('pointermove', handleMove);
+ window.removeEventListener('pointerup', handleUp);
+ window.removeEventListener('pointercancel', handleUp);
+ };
+ window.addEventListener('pointermove', handleMove, { passive: true });
+ window.addEventListener('pointerup', handleUp);
+ window.addEventListener('pointercancel', handleUp);
+ };
+
+ // Open floating Quick Palette near cursor when mapped to 'quick-palette'
+ const openQuickPaletteAt = (e: React.PointerEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const vp = viewportRef.current;
+ if (!vp) return;
+ const rect = vp.getBoundingClientRect();
+ const x = Math.max(12, Math.min(rect.width - 210, e.clientX - rect.left));
+ const y = Math.max(12, Math.min(rect.height - 150, e.clientY - rect.top));
+ setQuickPalettePos({ x, y });
+ };
+
+ // Dispatch a resolved ModifierAction; returns true if the event was consumed
+ const dispatchModifierAction = (
+ action: ModifierAction,
+ e: React.PointerEvent<HTMLElement>,
+ allowDrawingPassThrough: boolean
+ ): boolean => {
+ switch (action) {
+ case 'pan':
+ onStartPan(e);
+ return true;
+ case 'rotate':
+ onStartRotate(e);
+ return true;
+ case 'zoom-drag':
+ if (onStartZoomDrag) {
+ onStartZoomDrag(e);
+ return true;
+ }
+ return false;
+ case 'brush-size':
+ startBrushResize(e);
+ return true;
+ case 'eyedropper':
+ if (e.button !== 0 || !allowDrawingPassThrough) {
+ startModifierEyedropper(e);
+ return true;
+ }
+ // When button 0 + Alt is held, GlobalShortcutListener already switched tool to pipette,
+ // or if not, sample directly via startModifierEyedropper
+ if (tool !== 'pipette') {
+ startModifierEyedropper(e);
+ return true;
+ }
+ return false;
+ case 'temp-eraser': {
+ if (!allowDrawingPassThrough) return false;
+ const cur = useToolStore.getState().tool;
+ if (cur !== 'eraser') {
+ tempEraserPrevToolRef.current = cur;
+ toolStoreActions.selectTool('eraser');
+ }
+ return false; // let stroke begin on eraser
+ }
+ case 'undo':
+ e.preventDefault();
+ e.stopPropagation();
+ onUndo?.();
+ return true;
+ case 'swap-colors':
+ e.preventDefault();
+ e.stopPropagation();
+ onSwapColors?.();
+ return true;
+ case 'quick-palette':
+ openQuickPaletteAt(e);
+ return true;
+ case 'straight-line':
+ case 'none':
+ default:
+ return false;
+ }
+ };
+
+ // Viewport background pointer down (clicking gray area to pan, rotate, zoom, resize, or quick palette)
+ const handleViewportPointerDown = (e: React.PointerEvent<HTMLDivElement>) => {
releaseExternalFocus();
- if (e.button === 1) {
- onStartPan(e);
+ if (quickPalettePos) setQuickPalettePos(null);
+
+ const modSettings = useUiStore.getState().appSettings.modifierKeys;
+ const resolved = resolvePointerModifierAction(
+ {
+ button: e.button,
+ pointerType: e.pointerType,
+ ctrlKey: e.ctrlKey,
+ metaKey: e.metaKey,
+ shiftKey: e.shiftKey,
+ altKey: e.altKey,
+ isSpaceDown,
+ },
+ modSettings
+ );
+ if (resolved && dispatchModifierAction(resolved.action, e, false)) {
return;
}
- if (e.button === 0) {
- // Dynamic Brush Resizing shortcut: Ctrl + Alt + Left Click Drag
- if ((e.ctrlKey || e.metaKey) && e.altKey) {
- startBrushResize(e);
- return;
- }
- if (isRotateModifier) {
- onStartRotate(e);
- return;
- }
- if (isSpaceDown) {
- onStartPan(e);
+ };
+
+ // Canvas pointer down: resolve Modifier Key Settings first, otherwise dispatch drawing/tool stroke
+ const handleCanvasPointerDown = (e: React.PointerEvent<HTMLElement>) => {
+ releaseExternalFocus();
+ if (quickPalettePos) setQuickPalettePos(null);
+
+ const modSettings = useUiStore.getState().appSettings.modifierKeys;
+ const resolved = resolvePointerModifierAction(
+ {
+ button: e.button,
+ pointerType: e.pointerType,
+ ctrlKey: e.ctrlKey,
+ metaKey: e.metaKey,
+ shiftKey: e.shiftKey,
+ altKey: e.altKey,
+ isSpaceDown,
+ },
+ modSettings
+ );
+
+ if (resolved) {
+ if (dispatchModifierAction(resolved.action, e, true)) {
return;
}
+ }
+
+ if (e.button === 0) {
e.preventDefault();
+ } else {
+ return;
}
+
const coalesced = extractCoalescedEvents(e);
(e as any).coalescedEvents = coalesced;
if (e.nativeEvent) {
@@ -1080,22 +1247,40 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
onPointerMove(e, coalesced, predicted);
};
+ const handleCanvasPointerUp = (e: React.PointerEvent<HTMLElement>) => {
+ onPointerUp(e);
+ if (tempEraserPrevToolRef.current !== null) {
+ const prev = tempEraserPrevToolRef.current;
+ tempEraserPrevToolRef.current = null;
+ toolStoreActions.selectTool(prev);
+ }
+ };
+
+ const handleContextMenu = (e: React.MouseEvent<HTMLElement>) => {
+ const modSettings = useUiStore.getState().appSettings.modifierKeys;
+ if (modSettings.rightClick !== 'none' || modSettings.stylusButton1 !== 'none') {
+ e.preventDefault();
+ }
+ };
// Determine cursor based on active mode
const getCursorStyle = (isOverCanvas: boolean): React.CSSProperties => {
- if (isResizingBrush || isCtrlAltDown) {
+ if (isResizingBrush || heldModifierAction === 'brush-size') {
return { cursor: 'ew-resize' };
}
- if (isRotating || isRotateModifier) {
+ if (isZoomDragging || heldModifierAction === 'zoom-drag') {
+ return { cursor: 'zoom-in' };
+ }
+ if (isRotating || isRotateModifier || heldModifierAction === 'rotate') {
return { cursor: ROTATE_CURSOR_CSS };
}
if (isPanning) {
return { cursor: 'grabbing' };
}
- if (isSpaceDown) {
+ if (isSpaceDown || heldModifierAction === 'pan') {
return { cursor: 'grab' };
}
- if (tool === 'pipette') {
+ if (tool === 'pipette' || heldModifierAction === 'eyedropper') {
return { cursor: PIPETTE_CURSOR_CSS };
}
if (tool === 'text') {
@@ -1146,6 +1331,7 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
<main
ref={viewportRef}
onPointerDown={handleViewportPointerDown}
+ onContextMenu={handleContextMenu}
className="flex-1 bg-[#161616] overflow-hidden relative select-none canvas-viewport"
style={{
touchAction: 'none',
@@ -1362,9 +1548,10 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
ref={interactionRef}
onPointerDown={handleCanvasPointerDown}
onPointerMove={handleCanvasPointerMove}
- onPointerUp={onPointerUp}
+ onPointerUp={handleCanvasPointerUp}
onPointerEnter={onPointerEnter}
onPointerLeave={onPointerLeave}
+ onContextMenu={handleContextMenu}
className="absolute inset-0 block touch-none z-20"
style={{
...getCursorStyle(true),
@@ -1594,6 +1781,88 @@ export const CanvasArea: React.FC<CanvasAreaProps> = React.memo(({
</div>
)}
+ {/* Floating Quick Palette Popover (triggered by modifier mapped to 'quick-palette') */}
+ {quickPalettePos && (
+ <div
+ onPointerDown={(e) => e.stopPropagation()}
+ onContextMenu={(e) => e.preventDefault()}
+ className="absolute z-50 bg-[#202020] border border-white/10 rounded-md shadow-[0_12px_32px_rgba(0,0,0,0.75)] p-2.5 w-48 space-y-2 text-[11px] text-[#e5e5e5] select-none"
+ style={{ left: `${quickPalettePos.x}px`, top: `${quickPalettePos.y}px` }}
+ >
+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a] uppercase tracking-wider">
+ <span>Quick Palette</span>
+ <button
+ type="button"
+ onClick={() => setQuickPalettePos(null)}
+ className="hover:text-[#e5e5e5] cursor-pointer px-1"
+ >
+ ×
+ </button>
+ </div>
+ <div className="grid grid-cols-6 gap-1">
+ {useToolStore.getState().recentColors.slice(0, 12).map((hex) => (
+ <button
+ key={hex}
+ type="button"
+ onClick={() => {
+ toolStoreActions.setPrimaryColor(hex);
+ setQuickPalettePos(null);
+ }}
+ className="w-6 h-6 rounded border border-white/15 cursor-pointer"
+ style={{ backgroundColor: hex }}
+ title={hex}
+ />
+ ))}
+ </div>
+ <div className="space-y-1">
+ <div className="flex items-center justify-between text-[10px] text-[#8a8a8a]">
+ <span>Size</span>
+ <span className="font-mono text-[#e5e5e5]">{brushSettings.size}px</span>
+ </div>
+ <input
+ type="range"
+ min="1"
+ max="300"
+ value={Math.round(brushSettings.size)}
+ onChange={(e) => onUpdateBrushSettings({ size: Number(e.target.value) })}
+ className="w-full"
+ />
+ </div>
+ <div className="grid grid-cols-3 gap-1 pt-0.5">
+ <button
+ type="button"
+ onClick={() => {
+ onUndo?.();
+ setQuickPalettePos(null);
+ }}
+ className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Undo
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ onRedo?.();
+ setQuickPalettePos(null);
+ }}
+ className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Redo
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ onFlipHorizontal?.();
+ setQuickPalettePos(null);
+ }}
+ className="px-1.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Flip H
+ </button>
+ </div>
+ </div>
+ )}
+
{/* Floating Webtoon Mode Controls (only shown when Webtoon Mode is active) */}
{isWebtoonMode && (
<div className="absolute top-3 right-3 z-40 flex items-center gap-1.5 select-none">
diff --git a/src/components/DocumentLifecycleManager.tsx b/src/components/DocumentLifecycleManager.tsx
index 1f64232..7103438 100644
--- a/src/components/DocumentLifecycleManager.tsx
+++ b/src/components/DocumentLifecycleManager.tsx
@@ -25,6 +25,7 @@ import {
saveCustomBrush,
} from '../utils/brushStorage';
import { documentStore } from '../utils/documentStore';
+import { shortcutManager } from '../utils/shortcutManager';
import { recoveryService, CrashedSessionInfo } from '../services/recoveryService';
import {
documentStoreActions,
@@ -287,13 +288,23 @@ export function useDocumentLifecycle({
);
const handleUpdateSettings = useCallback((newSettings: AppSettings) => {
+ const prev = useUiStore.getState().appSettings;
uiStoreActions.updateAppSettings(newSettings);
- documentStore.setTileBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
- toolStoreActions.updateBrushSettings({
- stabilization: newSettings.defaultStabilization,
- usePressure: newSettings.usePressureByDefault,
- smoothing: newSettings.smoothingEnabled,
- });
+ shortcutManager.setOverrides(newSettings.shortcuts);
+ if (prev.tileMemoryBudgetMb !== newSettings.tileMemoryBudgetMb) {
+ documentStore.setTileBudgetMb(newSettings.tileMemoryBudgetMb || 1024);
+ }
+ if (
+ prev.defaultStabilization !== newSettings.defaultStabilization ||
+ prev.usePressureByDefault !== newSettings.usePressureByDefault ||
+ prev.smoothingEnabled !== newSettings.smoothingEnabled
+ ) {
+ toolStoreActions.updateBrushSettings({
+ stabilization: newSettings.defaultStabilization,
+ usePressure: newSettings.usePressureByDefault,
+ smoothing: newSettings.smoothingEnabled,
+ });
+ }
}, []);
const handleProcessFile = useCallback(
diff --git a/src/components/GlobalShortcutListener.tsx b/src/components/GlobalShortcutListener.tsx
index 138eccc..d1e5699 100644
--- a/src/components/GlobalShortcutListener.tsx
+++ b/src/components/GlobalShortcutListener.tsx
@@ -7,6 +7,7 @@ import {
ToolType,
TransformSession,
} from '../types/editor';
+import { ModifierAction } from '../types/settings';
import { createDefaultAnimationTimeline } from '../utils/animationEngine';
import { createDefaultPerspectiveRuler } from '../utils/perspectiveMath';
import {
@@ -21,6 +22,11 @@ import {
saveCustomBrush,
} from '../utils/brushStorage';
import { TonalCorrectionType } from '../utils/tonalEngine';
+import {
+ SPRING_LOADED_HOLD_MS,
+ SpringLoadedToolController,
+ shortcutManager,
+} from '../utils/shortcutManager';
import {
documentStoreActions,
selectIsAnyModalOpen,
@@ -65,6 +71,10 @@ export interface GlobalShortcutListenerProps {
handleOpenTonalModal: (type: TonalCorrectionType) => void;
handleUpdateAnimationTimeline: (timeline: AnimationTimeline | null) => void;
handleAddAnimationCel: (frameIndex: number) => void;
+ zoomIn?: () => void;
+ zoomOut?: () => void;
+ resetZoomAndCenter?: () => void;
+ resetRotation?: () => void;
toggleFlipHorizontal: () => void;
toggleFlipVertical: () => void;
handleClearSelection: () => void;
@@ -76,20 +86,25 @@ export interface GlobalShortcutListenerProps {
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',
-};
+const NON_REPEATABLE_COMMANDS = new Set<string>([
+ 'color.swap',
+ 'color.reset',
+ 'color.transparent',
+ 'view.flipHorizontal',
+ 'view.flipVertical',
+ 'view.togglePalettes',
+ 'view.toggleLeftPanel',
+ 'view.softProof',
+ 'view.gamutWarning',
+ 'view.perspectiveRuler',
+ 'view.perspectiveSnap',
+ 'anim.toggleTimeline',
+ 'app.preferences',
+ 'file.new',
+ 'file.open',
+ 'file.save',
+ 'file.saveAs',
+]);
function isEditableTarget(target: EventTarget | null): boolean {
if (!(target instanceof HTMLElement)) return false;
@@ -97,24 +112,27 @@ function isEditableTarget(target: EventTarget | null): boolean {
return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
}
+function modifierActionToTempTool(action: ModifierAction): ToolType | null {
+ if (action === 'eyedropper') return 'pipette';
+ if (action === 'temp-eraser') return 'eraser';
+ return null;
+}
+
/**
- * Headless listener for global hotkeys, temporary tool holds, Alt eyedropper hold,
+ * Headless listener for global hotkeys (via centralized ShortcutManager),
+ * spring-loaded temporary tool holds (> 250ms), remappable modifier-key temporary tools,
* 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;
+ const springControllerRef = useRef(new SpringLoadedToolController(SPRING_LOADED_HOLD_MS));
+ const activeModHoldRef = useRef<{
+ modKey: 'Alt' | 'Control' | 'Shift';
prevTool: ToolType;
- targetTool: ToolType;
- downAt: number;
- usedWhileHeld: boolean;
+ tempTool: ToolType;
} | null>(null);
// Flush debounced brush settings on window close/unmount
@@ -127,327 +145,320 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea
};
}, []);
- // Global Keyboard Shortcuts (Layout-Independent e.code + CSP Hold-and-Release Temporary Tools)
+ // Register centralized command handlers once (reads propsRef imperatively)
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;
+ const restoreActiveModTool = () => {
+ const mod = activeModHoldRef.current;
+ if (!mod) return;
+ activeModHoldRef.current = null;
+ propsRef.current.isPipetteSamplingRef.current = false;
+ toolStoreActions.setQuickModifiers({ isAltActive: false });
+ toolStoreActions.setToolRaw(mod.prevTool);
+ };
- if (!e.shiftKey && (code === 'KeyZ' || key === 'z')) {
- if (!p.hasOpenDocument) return;
- e.preventDefault();
- p.handleUndo();
- return;
- }
+ const stepBrush = (dir: -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 });
+ }
+ };
+ shortcutManager.registerHandlers({
+ // Menu / File / App
+ 'file.new': () => uiStoreActions.setNewCanvasModalOpen(true),
+ 'file.open': () => propsRef.current.handleTriggerOpenFile(),
+ 'file.save': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleSave();
+ },
+ 'file.saveAs': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleSaveAs();
+ },
+ 'app.preferences': () => uiStoreActions.setSettingsModalOpen(true),
+ 'view.togglePalettes': () => {
+ if (!propsRef.current.textSession) workspaceStoreActions.togglePalettesHidden();
+ },
+ 'view.toggleLeftPanel': () => {
+ if (!propsRef.current.textSession) uiStoreActions.toggleLeftPanelHidden();
+ },
+ 'view.softProof': () => {
+ if (propsRef.current.hasOpenDocument) documentStoreActions.toggleSoftProof();
+ },
+ 'view.gamutWarning': () => {
+ if (propsRef.current.hasOpenDocument) documentStoreActions.toggleGamutWarning();
+ },
+ 'anim.toggleTimeline': () => {
+ const p = propsRef.current;
+ if (!p.hasOpenDocument) return;
+ if (p.activeAnimationTimeline) {
+ p.handleUpdateAnimationTimeline(null);
+ } else {
+ p.handleUpdateAnimationTimeline(createDefaultAnimationTimeline(p.layers));
+ }
+ },
+ 'anim.addCel': () => {
+ const p = propsRef.current;
+ if (!p.hasOpenDocument || !p.activeAnimationTimeline) return;
+ restoreActiveModTool();
+ p.handleAddAnimationCel(p.activeAnimationTimeline.currentFrame);
+ },
+
+ // Edit
+ 'edit.undo': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleUndo();
+ },
+ 'edit.redo': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.redo();
+ },
+ 'edit.copy': () => {
+ if (!propsRef.current.hasOpenDocument) return;
+ propsRef.current.handleCopySelectedLayer();
+ },
+ 'edit.paste': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handlePasteSelectedLayer();
+ },
+ 'edit.delete': () => {
+ const p = propsRef.current;
+ if (!p.hasOpenDocument) return;
+ if (p.selection) p.handleClearSelection();
+ else p.handleDeleteSelectedLayer();
+ },
+ 'edit.transform': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleStartTransform();
+ },
+ 'edit.selectAll': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleSelectAll();
+ },
+ 'edit.deselect': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleDeselect();
+ },
+ 'edit.invertSelection': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleInvertSelection();
+ },
+ 'edit.invertColors': () => {
+ const p = propsRef.current;
if (
- (e.shiftKey && (code === 'KeyZ' || key === 'z')) ||
- (!e.shiftKey && (code === 'KeyY' || key === 'y'))
+ !p.hasOpenDocument ||
+ !p.activeLayer ||
+ p.activeLayer.locked ||
+ p.activeLayer.type !== 'raster'
) {
- 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();
+ p.handleApplyReverseGradient();
+ },
+ 'edit.hueSaturation': () => {
+ const p = propsRef.current;
+ if (
+ !p.hasOpenDocument ||
+ !p.activeLayer ||
+ p.activeLayer.locked ||
+ p.activeLayer.type !== 'raster'
+ ) {
return;
}
-
- if (!e.shiftKey && (code === 'KeyU' || key === 'u')) {
- if (
- !p.hasOpenDocument ||
- !p.activeLayer ||
- p.activeLayer.locked ||
- p.activeLayer.type !== 'raster'
- ) {
- return;
+ p.handleOpenTonalModal('hue-saturation');
+ },
+
+ // Layer
+ 'layer.newRaster': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleAddLayer('raster');
+ },
+ 'layer.duplicate': () => {
+ const p = propsRef.current;
+ if (p.hasOpenDocument && p.activeLayer) p.duplicateLayer(p.activeLayerId);
+ },
+ 'layer.group': () => {
+ if (propsRef.current.hasOpenDocument) propsRef.current.handleGroupSelectedLayers();
+ },
+
+ // Canvas View
+ 'view.zoomIn': () => propsRef.current.zoomIn?.(),
+ 'view.zoomOut': () => propsRef.current.zoomOut?.(),
+ 'view.resetZoom': () => propsRef.current.resetZoomAndCenter?.(),
+ 'view.resetRotation': () => propsRef.current.resetRotation?.(),
+ 'view.flipHorizontal': () => {
+ const p = propsRef.current;
+ if (p.hasOpenDocument && !p.isSpaceDown) p.toggleFlipHorizontal();
+ },
+ 'view.flipVertical': () => {
+ const p = propsRef.current;
+ if (p.hasOpenDocument && !p.isSpaceDown) p.toggleFlipVertical();
+ },
+ 'view.perspectiveRuler': () => {
+ const p = propsRef.current;
+ documentStoreActions.setPerspectiveRuler((prev) => {
+ if (!prev) {
+ const next = createDefaultPerspectiveRuler('2-point', p.dimensions);
+ p.showToast('2-Point Perspective Ruler added to canvas');
+ return next;
}
- e.preventDefault();
- p.handleOpenTonalModal('hue-saturation');
- return;
- }
+ const next = { ...prev, enabled: !prev.enabled };
+ p.showToast(next.enabled ? 'Perspective Ruler: Shown' : 'Perspective Ruler: Hidden');
+ return next;
+ });
+ },
+ 'view.perspectiveSnap': () => {
+ const p = propsRef.current;
+ 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;
+ });
+ },
+
+ // Tools & Colors
+ 'tool.brushSizeDown': () => stepBrush(-1),
+ 'tool.brushSizeUp': () => stepBrush(1),
+ 'color.swap': () => toolStoreActions.swapColors(),
+ 'color.reset': () => toolStoreActions.resetDefaultColors(),
+ 'color.transparent': () => {
+ const next = toolStoreActions.toggleTransparentColor();
+ propsRef.current.showToast(
+ next ? 'Transparent ink mode active' : 'Color ink mode active'
+ );
+ },
+ });
- if (!e.shiftKey && (code === 'Comma' || key === ',' || key === '<')) {
- e.preventDefault();
- uiStoreActions.setSettingsModalOpen(true);
- return;
- }
+ return () => {
+ shortcutManager.clearHandlers();
+ };
+ }, []);
- 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;
- }
+ // Global Keyboard Shortcuts via ShortcutManager + Spring-Loaded Tools + Remappable Modifier Holds
+ useEffect(() => {
+ const clearModHold = () => {
+ const mod = activeModHoldRef.current;
+ if (!mod) return;
+ activeModHoldRef.current = null;
+ propsRef.current.isPipetteSamplingRef.current = false;
+ toolStoreActions.setQuickModifiers({ isAltActive: false });
+ if (useToolStore.getState().tool === mod.tempTool) {
+ toolStoreActions.setToolRaw(mod.prevTool);
+ }
+ };
- 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;
- }
+ 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;
}
- // 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 });
+ const modSettings = uiState.appSettings.modifierKeys;
+
+ // 1. Bare modifier key temporary tool holds (Alt / Ctrl / Shift remappable to Eyedropper or Temp Eraser)
+ if (
+ (e.key === 'Alt' || e.key === 'Control' || e.key === 'Shift') &&
+ !p.isDrawingRef.current &&
+ !p.isSelectionPenDrawingRef.current
+ ) {
+ const onlyAlt = e.key === 'Alt' && !e.ctrlKey && !e.metaKey && !e.shiftKey;
+ const onlyCtrl = e.key === 'Control' && !e.altKey && !e.shiftKey;
+ const onlyShift = e.key === 'Shift' && !e.ctrlKey && !e.metaKey && !e.altKey;
+
+ let action: ModifierAction = 'none';
+ let modKey: 'Alt' | 'Control' | 'Shift' | null = null;
+ if (onlyAlt) {
+ action = modSettings.alt;
+ modKey = 'Alt';
+ } else if (onlyCtrl) {
+ action = modSettings.ctrl;
+ modKey = 'Control';
+ } else if (onlyShift) {
+ action = modSettings.shift;
+ modKey = 'Shift';
+ }
+
+ const tempTool = modifierActionToTempTool(action);
+ if (tempTool && modKey) {
+ if (modKey === 'Alt') e.preventDefault();
+ if (!activeModHoldRef.current && !e.repeat) {
+ const currentTool = useToolStore.getState().tool;
+ if (currentTool !== tempTool) {
+ activeModHoldRef.current = { modKey, prevTool: currentTool, tempTool };
+ if (modKey === 'Alt') {
+ toolStoreActions.setQuickModifiers({ isAltActive: true });
+ }
+ toolStoreActions.setToolRaw(tempTool);
+ }
}
- p.handleAddAnimationCel(p.activeAnimationTimeline.currentFrame);
+ return;
}
- 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;
+ // Cancel temporary modifier tool if combined with another modifier/Space (e.g. Ctrl+Alt brush resize)
+ if (
+ activeModHoldRef.current &&
+ (e.code === 'Space' ||
+ (activeModHoldRef.current.modKey === 'Alt' && (e.ctrlKey || e.metaKey || e.shiftKey)) ||
+ (activeModHoldRef.current.modKey === 'Control' && (e.altKey || e.shiftKey)) ||
+ (activeModHoldRef.current.modKey === 'Shift' && (e.ctrlKey || e.metaKey || e.altKey)))
+ ) {
+ clearModHold();
}
- // 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;
- }
+ // 2. Match against centralized ShortcutManager (live overrides read imperatively!)
+ const overrides = uiState.appSettings.shortcuts;
+ shortcutManager.setOverrides(overrides);
+ const matched = shortcutManager.matchEvent(e, overrides);
- // 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();
+ if (matched) {
+ // Guard special contextual exceptions before preventDefault
+ if (matched.id === 'edit.copy') {
+ const textSel = window.getSelection()?.toString();
+ if (textSel && textSel.length > 0) return;
+ }
+ if (
+ (matched.id === 'view.togglePalettes' || matched.id === 'view.toggleLeftPanel') &&
+ p.textSession
+ ) {
return;
}
- if (code === 'KeyV' || key === 'v') {
- if (!p.hasOpenDocument || e.repeat) return;
- e.preventDefault();
- p.toggleFlipVertical();
+ if (
+ (matched.id === 'view.flipHorizontal' || matched.id === 'view.flipVertical') &&
+ p.isSpaceDown
+ ) {
return;
}
- }
- // Single-key tool & color shortcuts
- if (!e.shiftKey) {
- const mappedTool = CODE_TO_TOOL[code];
- if (mappedTool) {
+ if (matched.springLoaded && matched.toolId) {
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);
+ e.preventDefault();
+ const currentTool = useToolStore.getState().tool;
+ const nextTool = springControllerRef.current.handleToolKeyDown(
+ e.code || matched.id,
+ matched.toolId,
+ currentTool
+ );
+ if (nextTool) {
+ toolStoreActions.selectTool(nextTool);
}
return;
}
- if (code === 'KeyX' || key === 'x') {
- if (!e.repeat) toolStoreActions.swapColors();
+ if (e.repeat && NON_REPEATABLE_COMMANDS.has(matched.id)) {
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') {
+ shortcutManager.executeCommand(matched.id);
+ return;
+ }
+
+ // 3. Contextual Escape / Enter fallbacks for active sessions
+ const key = e.key.toLowerCase();
+ if (key === 'escape') {
if (p.transformSession?.active) {
e.preventDefault();
p.handleCancelTransform();
@@ -467,27 +478,39 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea
};
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);
+ // 1. Release spring-loaded tool hold (> 250ms or used while held)
+ const restored = springControllerRef.current.handleKeyUp(
+ e.code,
+ useToolStore.getState().tool
+ );
+ if (restored) {
+ toolStoreActions.selectTool(restored);
+ }
+
+ // 2. Release temporary modifier-key tool hold
+ const mod = activeModHoldRef.current;
+ if (mod) {
+ const released =
+ (mod.modKey === 'Alt' && (e.key === 'Alt' || !e.altKey)) ||
+ (mod.modKey === 'Control' && (e.key === 'Control' || (!e.ctrlKey && !e.metaKey))) ||
+ (mod.modKey === 'Shift' && (e.key === 'Shift' || !e.shiftKey));
+ if (released) {
+ if (mod.modKey === 'Alt') e.preventDefault();
+ clearModHold();
}
}
};
const handlePointerDownMarkUsed = () => {
- if (tempToolHoldRef.current) {
- tempToolHoldRef.current.usedWhileHeld = true;
- }
+ springControllerRef.current.markUsedWhileHeld();
};
const handleWindowBlur = () => {
- tempToolHoldRef.current = null;
+ const restored = springControllerRef.current.cancel(useToolStore.getState().tool);
+ if (restored) {
+ toolStoreActions.selectTool(restored);
+ }
+ clearModHold();
};
window.addEventListener('keydown', handleKeyDown);
@@ -502,85 +525,6 @@ export const GlobalShortcutListener: React.FC<GlobalShortcutListenerProps> = Rea
};
}, []);
- // 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) => {
diff --git a/src/components/PressureCurveEditor.tsx b/src/components/PressureCurveEditor.tsx
new file mode 100644
index 0000000..b3c6c4b
--- /dev/null
+++ b/src/components/PressureCurveEditor.tsx
@@ -0,0 +1,487 @@
+import React, { useRef, useState, useMemo, useCallback } from 'react';
+import { Trash2 } from 'lucide-react';
+import { PressureCurvePoint, PressureCurveSettings } from '../types/settings';
+import {
+ calculatePressureOpacity,
+ createPressureCurvePreset,
+ evaluateGlobalPressureCurve,
+ samplePressureCurve,
+ sanitizePressureCurvePoints,
+} from '../utils/pressureCurve';
+
+interface PressureCurveEditorProps {
+ value: PressureCurveSettings;
+ onChange: (next: PressureCurveSettings) => void;
+}
+
+const SVG_W = 220;
+const SVG_H = 180;
+const PAD = 14;
+const PLOT_W = SVG_W - PAD * 2;
+const PLOT_H = SVG_H - PAD * 2;
+const MAX_CONTROL_POINTS = 8;
+
+function toSvgX(nx: number): number {
+ return PAD + Math.max(0, Math.min(1, nx)) * PLOT_W;
+}
+
+function toSvgY(ny: number): number {
+ return PAD + (1 - Math.max(0, Math.min(1, ny))) * PLOT_H;
+}
+
+function fromClientToNorm(
+ svg: SVGSVGElement,
+ clientX: number,
+ clientY: number
+): PressureCurvePoint {
+ const rect = svg.getBoundingClientRect();
+ const sx = ((clientX - rect.left) / Math.max(1, rect.width)) * SVG_W;
+ const sy = ((clientY - rect.top) / Math.max(1, rect.height)) * SVG_H;
+ const nx = Math.max(0, Math.min(1, (sx - PAD) / PLOT_W));
+ const ny = Math.max(0, Math.min(1, 1 - (sy - PAD) / PLOT_H));
+ return [nx, ny];
+}
+
+export const PressureCurveEditor: React.FC<PressureCurveEditorProps> = ({ value, onChange }) => {
+ const svgRef = useRef<SVGSVGElement | null>(null);
+ const testCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const draggingIdxRef = useRef<number | null>(null);
+ const [selectedIdx, setSelectedIdx] = useState<number | null>(null);
+ const [liveSample, setLiveSample] = useState<{ input: number; output: number } | null>(null);
+
+ const testStrokeRef = useRef<{
+ active: boolean;
+ pointerId: number;
+ lastX: number;
+ lastY: number;
+ lastWidth: number;
+ lastAlpha: number;
+ }>({
+ active: false,
+ pointerId: -1,
+ lastX: 0,
+ lastY: 0,
+ lastWidth: 1,
+ lastAlpha: 1,
+ });
+
+ const points = useMemo(() => sanitizePressureCurvePoints(value.points), [value.points]);
+
+ const sampledCurve = useMemo(() => samplePressureCurve(value, 64), [value]);
+
+ const curvePathD = useMemo(() => {
+ if (sampledCurve.length === 0) return '';
+ return sampledCurve
+ .map(([x, y], i) => `${i === 0 ? 'M' : 'L'}${toSvgX(x).toFixed(2)},${toSvgY(y).toFixed(2)}`)
+ .join(' ');
+ }, [sampledCurve]);
+
+ const areaPathD = useMemo(() => {
+ if (!curvePathD) return '';
+ const xEnd = toSvgX(1).toFixed(2);
+ const xStart = toSvgX(0).toFixed(2);
+ const yBase = toSvgY(0).toFixed(2);
+ return `${curvePathD} L${xEnd},${yBase} L${xStart},${yBase} Z`;
+ }, [curvePathD]);
+
+ const updatePoints = useCallback(
+ (nextPts: PressureCurvePoint[]) => {
+ onChange({
+ enabled: value.enabled,
+ preset: 'custom',
+ points: sanitizePressureCurvePoints(nextPts),
+ });
+ },
+ [onChange, value.enabled]
+ );
+
+ const handleSvgPointerDown = (e: React.PointerEvent<SVGSVGElement>) => {
+ if (e.button !== 0 || !svgRef.current) return;
+ const [nx, ny] = fromClientToNorm(svgRef.current, e.clientX, e.clientY);
+
+ // Hit-test existing control points first
+ let hitIdx = -1;
+ let bestDist = 14;
+ const px = toSvgX(nx);
+ const py = toSvgY(ny);
+ for (let i = 0; i < points.length; i++) {
+ const d = Math.hypot(toSvgX(points[i][0]) - px, toSvgY(points[i][1]) - py);
+ if (d < bestDist) {
+ bestDist = d;
+ hitIdx = i;
+ }
+ }
+
+ if (hitIdx >= 0) {
+ draggingIdxRef.current = hitIdx;
+ setSelectedIdx(hitIdx);
+ svgRef.current.setPointerCapture(e.pointerId);
+ return;
+ }
+
+ // Insert new interior point if under limit
+ if (points.length < MAX_CONTROL_POINTS && nx > 0.03 && nx < 0.97) {
+ const next = [...points, [nx, ny] as PressureCurvePoint].sort((a, b) => a[0] - b[0]);
+ const insertedIdx = next.findIndex(
+ (p) => Math.abs(p[0] - nx) < 1e-4 && Math.abs(p[1] - ny) < 1e-4
+ );
+ updatePoints(next);
+ if (insertedIdx >= 0) {
+ draggingIdxRef.current = insertedIdx;
+ setSelectedIdx(insertedIdx);
+ svgRef.current.setPointerCapture(e.pointerId);
+ }
+ }
+ };
+
+ const handleSvgPointerMove = (e: React.PointerEvent<SVGSVGElement>) => {
+ const idx = draggingIdxRef.current;
+ if (idx === null || !svgRef.current) return;
+ const [nx, ny] = fromClientToNorm(svgRef.current, e.clientX, e.clientY);
+ const next = points.map(([x, y]) => [x, y] as PressureCurvePoint);
+
+ if (idx === 0) {
+ next[0] = [0, ny];
+ } else if (idx === next.length - 1) {
+ next[next.length - 1] = [1, ny];
+ } else {
+ const minX = next[idx - 1][0] + 0.03;
+ const maxX = next[idx + 1][0] - 0.03;
+ next[idx] = [Math.max(minX, Math.min(maxX, nx)), ny];
+ }
+ onChange({
+ enabled: value.enabled,
+ preset: 'custom',
+ points: next,
+ });
+ };
+
+ const handleSvgPointerUp = (e: React.PointerEvent<SVGSVGElement>) => {
+ if (draggingIdxRef.current !== null && svgRef.current) {
+ try {
+ if (svgRef.current.hasPointerCapture(e.pointerId)) {
+ svgRef.current.releasePointerCapture(e.pointerId);
+ }
+ } catch {
+ // Ignore release errors
+ }
+ }
+ draggingIdxRef.current = null;
+ };
+
+ const removePointAt = (idx: number) => {
+ if (idx <= 0 || idx >= points.length - 1) return;
+ const next = points.filter((_, i) => i !== idx);
+ setSelectedIdx(null);
+ updatePoints(next);
+ };
+
+ // --- Live Stylus Testing Strip ---
+ const clearTestCanvas = () => {
+ const canvas = testCanvasRef.current;
+ if (!canvas) return;
+ const ctx = canvas.getContext('2d');
+ ctx?.clearRect(0, 0, canvas.width, canvas.height);
+ setLiveSample(null);
+ };
+
+ const getTestRawPressure = (e: React.PointerEvent<HTMLCanvasElement>, normX: number): number => {
+ if (e.pointerType === 'pen' || e.pointerType === 'touch') {
+ return Math.max(0, Math.min(1, e.pressure || 0));
+ }
+ // Mouse fallback: smooth horizontal pressure ramp 0.05..1.0 so mouse users can preview curve response
+ return Math.max(0.05, Math.min(1, normX));
+ };
+
+ const drawTestDotOrSegment = (
+ x0: number,
+ y0: number,
+ w0: number,
+ a0: number,
+ x1: number,
+ y1: number,
+ w1: number,
+ a1: number
+ ) => {
+ const canvas = testCanvasRef.current;
+ if (!canvas) return;
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+
+ const dist = Math.hypot(x1 - x0, y1 - y0);
+ const steps = Math.max(1, Math.ceil(dist / 1.5));
+ ctx.save();
+ ctx.fillStyle = '#e5e5e5';
+ for (let i = 0; i <= steps; i++) {
+ const t = i / steps;
+ const x = x0 + (x1 - x0) * t;
+ const y = y0 + (y1 - y0) * t;
+ const r = Math.max(0.6, ((w0 + (w1 - w0) * t) * 0.5));
+ const alpha = Math.max(0.06, Math.min(1, a0 + (a1 - a0) * t));
+ ctx.globalAlpha = alpha;
+ ctx.beginPath();
+ ctx.arc(x, y, r, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ ctx.restore();
+ };
+
+ const handleTestPointerDown = (e: React.PointerEvent<HTMLCanvasElement>) => {
+ const canvas = testCanvasRef.current;
+ if (!canvas || e.button !== 0) return;
+ e.preventDefault();
+ canvas.setPointerCapture(e.pointerId);
+
+ const rect = canvas.getBoundingClientRect();
+ const scaleX = canvas.width / Math.max(1, rect.width);
+ const scaleY = canvas.height / Math.max(1, rect.height);
+ const x = (e.clientX - rect.left) * scaleX;
+ const y = (e.clientY - rect.top) * scaleY;
+ const rawP = getTestRawPressure(e, (e.clientX - rect.left) / Math.max(1, rect.width));
+ const mappedP = evaluateGlobalPressureCurve(rawP, value);
+ const width = 1.5 + mappedP * 18;
+ const alpha = calculatePressureOpacity(1.0, rawP, true, 0.12, value);
+
+ testStrokeRef.current = {
+ active: true,
+ pointerId: e.pointerId,
+ lastX: x,
+ lastY: y,
+ lastWidth: width,
+ lastAlpha: alpha,
+ };
+ setLiveSample({ input: rawP, output: mappedP });
+ drawTestDotOrSegment(x, y, width, alpha, x, y, width, alpha);
+ };
+
+ const handleTestPointerMove = (e: React.PointerEvent<HTMLCanvasElement>) => {
+ const st = testStrokeRef.current;
+ const canvas = testCanvasRef.current;
+ if (!st.active || st.pointerId !== e.pointerId || !canvas) return;
+
+ const rect = canvas.getBoundingClientRect();
+ const scaleX = canvas.width / Math.max(1, rect.width);
+ const scaleY = canvas.height / Math.max(1, rect.height);
+ const x = (e.clientX - rect.left) * scaleX;
+ const y = (e.clientY - rect.top) * scaleY;
+ const rawP = getTestRawPressure(e, (e.clientX - rect.left) / Math.max(1, rect.width));
+ const mappedP = evaluateGlobalPressureCurve(rawP, value);
+ const width = 1.5 + mappedP * 18;
+ const alpha = calculatePressureOpacity(1.0, rawP, true, 0.12, value);
+
+ drawTestDotOrSegment(st.lastX, st.lastY, st.lastWidth, st.lastAlpha, x, y, width, alpha);
+ st.lastX = x;
+ st.lastY = y;
+ st.lastWidth = width;
+ st.lastAlpha = alpha;
+ setLiveSample({ input: rawP, output: mappedP });
+ };
+
+ const handleTestPointerUp = (e: React.PointerEvent<HTMLCanvasElement>) => {
+ const st = testStrokeRef.current;
+ if (!st.active || st.pointerId !== e.pointerId) return;
+ st.active = false;
+ st.pointerId = -1;
+ try {
+ if (testCanvasRef.current?.hasPointerCapture(e.pointerId)) {
+ testCanvasRef.current.releasePointerCapture(e.pointerId);
+ }
+ } catch {
+ // Ignore release errors
+ }
+ };
+
+ return (
+ <section className="space-y-3">
+ <div className="flex items-center justify-between">
+ <div>
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Global Pen Pressure Curve</h3>
+ <p className="text-[11px] text-[#8a8a8a]">
+ Click curve to add point, drag to adjust, double-click interior point to remove
+ </p>
+ </div>
+ <label className="flex items-center gap-1.5 text-[11px] text-[#e5e5e5] cursor-pointer">
+ <input
+ type="checkbox"
+ checked={value.enabled}
+ onChange={(e) => onChange({ ...value, enabled: e.target.checked })}
+ />
+ <span>Enabled</span>
+ </label>
+ </div>
+
+ {/* Preset Row */}
+ <div className="flex items-center gap-1.5">
+ {(['linear', 'soft', 'hard'] as const).map((preset) => {
+ const active = value.preset === preset;
+ return (
+ <button
+ key={preset}
+ type="button"
+ onClick={() => onChange(createPressureCurvePreset(preset, value.enabled))}
+ className={`px-2.5 py-1 rounded text-[11px] capitalize transition-colors cursor-pointer ${
+ active
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] ring-1 ring-[var(--accent-border)] font-medium'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c]/60'
+ }`}
+ >
+ {preset}
+ </button>
+ );
+ })}
+ {liveSample && (
+ <span className="ml-auto font-mono text-[10px] text-[#8a8a8a]">
+ In {Math.round(liveSample.input * 100)}% {'->'} Out {Math.round(liveSample.output * 100)}%
+ </span>
+ )}
+ </div>
+
+ {/* Curve Graph + Live Stylus Test Strip side-by-side */}
+ <div className="grid grid-cols-1 sm:grid-cols-[220px_1fr] gap-3 items-stretch">
+ <div className="bg-[#161616] rounded p-1.5 flex flex-col items-center">
+ <svg
+ ref={svgRef}
+ viewBox={`0 0 ${SVG_W} ${SVG_H}`}
+ onPointerDown={handleSvgPointerDown}
+ onPointerMove={handleSvgPointerMove}
+ onPointerUp={handleSvgPointerUp}
+ onPointerCancel={handleSvgPointerUp}
+ className={`w-full h-[180px] touch-none select-none ${
+ value.enabled ? 'cursor-crosshair' : 'opacity-45'
+ }`}
+ >
+ {/* Plot background */}
+ <rect
+ x={PAD}
+ y={PAD}
+ width={PLOT_W}
+ height={PLOT_H}
+ fill="#121212"
+ stroke="#2c2c2c"
+ strokeWidth="1"
+ />
+
+ {/* 25% / 50% / 75% grid lines */}
+ {[0.25, 0.5, 0.75].map((t) => (
+ <g key={t} stroke="#242424" strokeWidth="1">
+ <line x1={toSvgX(t)} y1={PAD} x2={toSvgX(t)} y2={PAD + PLOT_H} />
+ <line x1={PAD} y1={toSvgY(t)} x2={PAD + PLOT_W} y2={toSvgY(t)} />
+ </g>
+ ))}
+
+ {/* Linear reference diagonal */}
+ <line
+ x1={toSvgX(0)}
+ y1={toSvgY(0)}
+ x2={toSvgX(1)}
+ y2={toSvgY(1)}
+ stroke="#3a3a3a"
+ strokeWidth="1"
+ strokeDasharray="3 3"
+ />
+
+ {/* Area fill under curve */}
+ {areaPathD && <path d={areaPathD} fill="var(--accent-subtle)" />}
+
+ {/* Monotone spline curve */}
+ {curvePathD && (
+ <path
+ d={curvePathD}
+ fill="none"
+ stroke="var(--accent)"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ )}
+
+ {/* Live test input/output crosshair */}
+ {liveSample && (
+ <g pointerEvents="none">
+ <line
+ x1={toSvgX(liveSample.input)}
+ y1={PAD}
+ x2={toSvgX(liveSample.input)}
+ y2={PAD + PLOT_H}
+ stroke="rgba(255,255,255,0.22)"
+ strokeWidth="1"
+ />
+ <circle
+ cx={toSvgX(liveSample.input)}
+ cy={toSvgY(liveSample.output)}
+ r="4"
+ fill="#ffffff"
+ stroke="#161616"
+ strokeWidth="1.5"
+ />
+ </g>
+ )}
+
+ {/* Draggable Control Points */}
+ {points.map(([px, py], idx) => {
+ const isEndpoint = idx === 0 || idx === points.length - 1;
+ const isSelected = selectedIdx === idx;
+ return (
+ <circle
+ key={`${idx}-${px.toFixed(3)}`}
+ cx={toSvgX(px)}
+ cy={toSvgY(py)}
+ r={isSelected ? 5.5 : 4.5}
+ fill={isEndpoint ? '#e5e5e5' : 'var(--accent)'}
+ stroke="#161616"
+ strokeWidth="1.5"
+ className="cursor-grab"
+ onDoubleClick={(e) => {
+ e.stopPropagation();
+ removePointAt(idx);
+ }}
+ onContextMenu={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ removePointAt(idx);
+ }}
+ />
+ );
+ })}
+ </svg>
+ <div className="w-full flex justify-between px-2 pt-0.5 text-[9px] font-mono text-[#8a8a8a]">
+ <span>Input 0%</span>
+ <span>Output Y / Input X</span>
+ <span>100%</span>
+ </div>
+ </div>
+
+ {/* Live Stylus Test Strip */}
+ <div className="bg-[#161616] rounded p-2.5 flex flex-col justify-between gap-2">
+ <div className="flex items-center justify-between">
+ <div>
+ <div className="text-[11px] font-medium text-[#e5e5e5]">Live Stylus Test Strip</div>
+ <div className="text-[10px] text-[#8a8a8a]">
+ Draw with pen (or drag left-to-right with mouse) to test size & opacity
+ </div>
+ </div>
+ <button
+ type="button"
+ onClick={clearTestCanvas}
+ className="flex items-center gap-1 px-2 py-1 rounded bg-[#202020] hover:bg-[#2c2c2c] text-[10px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
+ title="Clear test strip"
+ >
+ <Trash2 className="w-3 h-3" />
+ <span>Clear</span>
+ </button>
+ </div>
+ <canvas
+ ref={testCanvasRef}
+ width={360}
+ height={132}
+ onPointerDown={handleTestPointerDown}
+ onPointerMove={handleTestPointerMove}
+ onPointerUp={handleTestPointerUp}
+ onPointerCancel={handleTestPointerUp}
+ className="w-full h-[132px] rounded bg-[#121212] border border-[#2c2c2c] touch-none cursor-crosshair block"
+ />
+ </div>
+ </div>
+ </section>
+ );
+};
diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsx
index 03fe330..c7a39dc 100644
--- a/src/components/SettingsModal.tsx
+++ b/src/components/SettingsModal.tsx
@@ -1,24 +1,41 @@
-import React, { useState, useEffect } from 'react';
+import React, { useState, useEffect, useMemo } from 'react';
import {
X,
Palette,
Layers,
Paintbrush,
Keyboard,
+ SlidersHorizontal,
Info,
RotateCcw,
Check,
Search,
+ AlertTriangle,
} from 'lucide-react';
import {
AppSettings,
DEFAULT_APP_SETTINGS,
+ DEFAULT_MODIFIER_KEY_SETTINGS,
+ ModifierAction,
+ ModifierKeySlot,
+ MouseWheelAction,
ModernAccentColor,
MODERN_ACCENTS,
+ ShortcutCategory,
resolveModernAccentColor,
} from '../types/settings';
import { CanvasColorMode } from '../types/editor';
import { DPI_PRESETS } from './NewCanvasModal';
+import { PressureCurveEditor } from './PressureCurveEditor';
+import {
+ CommandDefinition,
+ DEFAULT_COMMANDS,
+ SHORTCUT_CATEGORIES,
+ findShortcutConflicts,
+ formatShortcutFromEvent,
+ formatShortcutLabel,
+ resolveCommandShortcut,
+} from '../utils/shortcutManager';
interface SettingsModalProps {
isOpen: boolean;
@@ -28,37 +45,61 @@ interface SettingsModalProps {
onShowToast: (message: string) => void;
}
-type SettingsTab = 'appearance' | 'canvas' | 'brush' | 'shortcuts' | 'about';
+type SettingsTab = 'appearance' | 'canvas' | 'brush' | 'shortcuts' | 'modifiers' | 'about';
-interface ShortcutRow {
- category: string;
- action: string;
- shortcut: string;
- desc: string;
-}
+const MODIFIER_ACTION_OPTIONS: Array<{ value: ModifierAction; label: string }> = [
+ { value: 'none', label: 'None' },
+ { value: 'pan', label: 'Pan / Hand Tool' },
+ { value: 'rotate', label: 'Rotate Canvas' },
+ { value: 'zoom-drag', label: 'Scrubby Zoom Drag' },
+ { value: 'eyedropper', label: 'Eyedropper (Sample Color)' },
+ { value: 'brush-size', label: 'Brush Size & Hardness Drag' },
+ { value: 'straight-line', label: 'Straight Line / Angle Snap' },
+ { value: 'temp-eraser', label: 'Temporary Eraser' },
+ { value: 'quick-palette', label: 'Quick Palette Popover' },
+ { value: 'swap-colors', label: 'Swap Primary / Secondary Color' },
+ { value: 'undo', label: 'Undo' },
+];
-const SHORTCUTS_DATA: ShortcutRow[] = [
- { category: 'File', action: 'New Canvas', shortcut: 'Ctrl + N', desc: 'Create a new canvas' },
- { category: 'File', action: 'Open File', shortcut: 'Ctrl + O', desc: 'Open images, PSD, or CSP files' },
- { category: 'File', action: 'Save', shortcut: 'Ctrl + S', desc: 'Save current document' },
- { category: 'File', action: 'Save As', shortcut: 'Ctrl + Shift + S', desc: 'Save as a new file' },
- { category: 'Edit', action: 'Undo', shortcut: 'Ctrl + Z', desc: 'Undo last action' },
- { category: 'Edit', action: 'Redo', shortcut: 'Ctrl + Y', desc: 'Redo undone action' },
- { category: 'Edit', action: 'Copy Layer', shortcut: 'Ctrl + C', desc: 'Copy selected layer' },
- { category: 'Edit', action: 'Paste Layer', shortcut: 'Ctrl + V', desc: 'Paste copied layer' },
- { category: 'Edit', action: 'Delete Layer', shortcut: 'Del', desc: 'Delete selected layer' },
- { category: 'Edit', action: 'Preferences', shortcut: 'Ctrl + ,', desc: 'Open preferences' },
- { category: 'Tools', action: 'Brush Tool', shortcut: 'B', desc: 'Switch to brush' },
- { category: 'Tools', action: 'Eraser Tool', shortcut: 'E', desc: 'Switch to eraser' },
- { category: 'Tools', action: 'Swap Colors', shortcut: 'X', desc: 'Swap primary and secondary colors' },
- { category: 'Tools', action: 'Brush Size & Hardness', shortcut: 'Ctrl + Alt + Drag', desc: 'Horizontal: size, Vertical: hardness' },
- { category: 'Navigation', action: 'Pan Canvas', shortcut: 'Space + Drag', desc: 'Pan viewport' },
- { category: 'Navigation', action: 'Rotate Canvas', shortcut: 'Shift + Space + Drag', desc: 'Rotate viewport' },
- { category: 'Navigation', action: 'Zoom In / Out', shortcut: 'Ctrl + +/-', desc: 'Adjust magnification' },
- { category: 'Navigation', action: 'Reset Zoom', shortcut: 'Ctrl + 0', desc: 'Fit & center canvas' },
- { category: 'Navigation', action: 'Reset Rotation', shortcut: 'Ctrl + Alt + 0', desc: 'Reset angle to 0°' },
- { category: 'Layers', action: 'New Raster Layer', shortcut: 'Ctrl + Shift + N', desc: 'Add transparent layer' },
- { category: 'Layers', action: 'Duplicate Layer', shortcut: 'Ctrl + J', desc: 'Clone current layer' },
+const MOUSE_WHEEL_OPTIONS: Array<{ value: MouseWheelAction; label: string }> = [
+ { value: 'zoom', label: 'Zoom In / Out' },
+ { value: 'scroll', label: 'Scroll / Pan Canvas' },
+ { value: 'brush-size', label: 'Adjust Brush Size' },
+];
+
+const MODIFIER_SLOTS: Array<{
+ slot: ModifierKeySlot;
+ label: string;
+ desc: string;
+}> = [
+ { slot: 'space', label: 'Space + Drag', desc: 'Hold Space while dragging on canvas' },
+ { slot: 'shift', label: 'Shift', desc: 'Hold Shift while clicking or dragging' },
+ { slot: 'ctrl', label: 'Ctrl', desc: 'Hold Ctrl / Cmd while clicking or dragging' },
+ { slot: 'alt', label: 'Alt', desc: 'Hold Alt while clicking or hovering' },
+ { slot: 'ctrlSpace', label: 'Ctrl + Space + Drag', desc: 'Hold Ctrl + Space and drag' },
+ { slot: 'shiftSpace', label: 'Shift + Space + Drag', desc: 'Hold Shift + Space and drag' },
+ {
+ slot: 'ctrlAlt',
+ label: 'Ctrl + Alt + Drag',
+ desc: 'Interactive brush size (horizontal) & hardness (vertical)',
+ },
+ {
+ slot: 'shiftAlt',
+ label: 'Shift + Alt + Drag',
+ desc: 'Alternate brush size / modifier drag combo',
+ },
+ { slot: 'rightClick', label: 'Right Click', desc: 'Secondary mouse button on canvas' },
+ { slot: 'middleClick', label: 'Middle Click', desc: 'Middle mouse button / wheel press' },
+ {
+ slot: 'stylusButton1',
+ label: 'Stylus Barrel Button 1',
+ desc: 'Lower stylus side button (or mouse side btn 1)',
+ },
+ {
+ slot: 'stylusButton2',
+ label: 'Stylus Barrel Button 2',
+ desc: 'Upper stylus side button (or mouse side btn 2)',
+ },
];
export const SettingsModal: React.FC<SettingsModalProps> = ({
@@ -71,11 +112,89 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
const [activeTab, setActiveTab] = useState<SettingsTab>('appearance');
const [localSettings, setLocalSettings] = useState<AppSettings>(settings);
const [searchQuery, setSearchQuery] = useState<string>('');
+ const [selectedCategory, setSelectedCategory] = useState<'All' | ShortcutCategory>('All');
+ const [recordingCommandId, setRecordingCommandId] = useState<string | null>(null);
+ const [pendingConflict, setPendingConflict] = useState<{
+ commandId: string;
+ shortcut: string;
+ conflicts: CommandDefinition[];
+ } | null>(null);
useEffect(() => {
setLocalSettings(settings);
}, [settings]);
+ useEffect(() => {
+ if (!isOpen) {
+ setRecordingCommandId(null);
+ setPendingConflict(null);
+ }
+ }, [isOpen]);
+
+ // Global capture listener while recording a shortcut keybinding
+ useEffect(() => {
+ if (!isOpen || !recordingCommandId) return;
+
+ const handleRecordKeyDown = (e: KeyboardEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ if (e.key === 'Escape' && !e.ctrlKey && !e.metaKey && !e.altKey && !e.shiftKey) {
+ setRecordingCommandId(null);
+ setPendingConflict(null);
+ return;
+ }
+
+ const captured = formatShortcutFromEvent(e);
+ if (!captured) return;
+
+ const conflicts = findShortcutConflicts(
+ recordingCommandId,
+ captured,
+ localSettings.shortcuts
+ );
+ if (conflicts.length > 0) {
+ setPendingConflict({
+ commandId: recordingCommandId,
+ shortcut: captured,
+ conflicts,
+ });
+ setRecordingCommandId(null);
+ return;
+ }
+
+ const nextShortcuts = {
+ ...localSettings.shortcuts,
+ [recordingCommandId]: captured,
+ };
+ const updated: AppSettings = { ...localSettings, shortcuts: nextShortcuts };
+ setLocalSettings(updated);
+ onUpdateSettings(updated);
+ setRecordingCommandId(null);
+ setPendingConflict(null);
+ };
+
+ window.addEventListener('keydown', handleRecordKeyDown, true);
+ return () => {
+ window.removeEventListener('keydown', handleRecordKeyDown, true);
+ };
+ }, [isOpen, recordingCommandId, localSettings, onUpdateSettings]);
+
+ const filteredCommands = useMemo(() => {
+ const q = searchQuery.trim().toLowerCase();
+ return DEFAULT_COMMANDS.filter((cmd) => {
+ if (selectedCategory !== 'All' && cmd.category !== selectedCategory) return false;
+ if (!q) return true;
+ const bound = formatShortcutLabel(resolveCommandShortcut(cmd, localSettings.shortcuts));
+ return (
+ cmd.label.toLowerCase().includes(q) ||
+ cmd.description.toLowerCase().includes(q) ||
+ cmd.category.toLowerCase().includes(q) ||
+ bound.toLowerCase().includes(q)
+ );
+ });
+ }, [searchQuery, selectedCategory, localSettings.shortcuts]);
+
if (!isOpen) return null;
const handleChange = <K extends keyof AppSettings>(key: K, value: AppSettings[K]) => {
@@ -85,18 +204,71 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
};
const handleResetDefaults = () => {
- setLocalSettings(DEFAULT_APP_SETTINGS);
- onUpdateSettings(DEFAULT_APP_SETTINGS);
+ setRecordingCommandId(null);
+ setPendingConflict(null);
+ const fresh: AppSettings = {
+ ...DEFAULT_APP_SETTINGS,
+ shortcuts: {},
+ modifierKeys: { ...DEFAULT_MODIFIER_KEY_SETTINGS },
+ pressureCurve: {
+ ...DEFAULT_APP_SETTINGS.pressureCurve,
+ points: DEFAULT_APP_SETTINGS.pressureCurve.points.map(([x, y]) => [x, y]),
+ },
+ };
+ setLocalSettings(fresh);
+ onUpdateSettings(fresh);
onShowToast('Preferences reset to defaults');
};
- const filteredShortcuts = SHORTCUTS_DATA.filter(
- (s) =>
- s.action.toLowerCase().includes(searchQuery.toLowerCase()) ||
- s.shortcut.toLowerCase().includes(searchQuery.toLowerCase()) ||
- s.desc.toLowerCase().includes(searchQuery.toLowerCase()) ||
- s.category.toLowerCase().includes(searchQuery.toLowerCase())
- );
+ const handleConfirmConflictReplace = () => {
+ if (!pendingConflict) return;
+ const nextShortcuts = { ...localSettings.shortcuts };
+ for (const c of pendingConflict.conflicts) {
+ nextShortcuts[c.id] = '';
+ }
+ nextShortcuts[pendingConflict.commandId] = pendingConflict.shortcut;
+ const updated: AppSettings = { ...localSettings, shortcuts: nextShortcuts };
+ setLocalSettings(updated);
+ onUpdateSettings(updated);
+ setPendingConflict(null);
+ onShowToast(`Assigned ${formatShortcutLabel(pendingConflict.shortcut)}`);
+ };
+
+ const handleResetSingleShortcut = (commandId: string) => {
+ const nextShortcuts = { ...localSettings.shortcuts };
+ delete nextShortcuts[commandId];
+ handleChange('shortcuts', nextShortcuts);
+ };
+
+ const handleClearSingleShortcut = (commandId: string) => {
+ handleChange('shortcuts', { ...localSettings.shortcuts, [commandId]: '' });
+ };
+
+ const handleResetAllShortcuts = () => {
+ setRecordingCommandId(null);
+ setPendingConflict(null);
+ handleChange('shortcuts', {});
+ onShowToast('Shortcuts reset to defaults');
+ };
+
+ const handleModifierSlotChange = (slot: ModifierKeySlot, action: ModifierAction) => {
+ handleChange('modifierKeys', {
+ ...localSettings.modifierKeys,
+ [slot]: action,
+ });
+ };
+
+ const handleMouseWheelChange = (action: MouseWheelAction) => {
+ handleChange('modifierKeys', {
+ ...localSettings.modifierKeys,
+ mouseWheel: action,
+ });
+ };
+
+ const handleResetModifiers = () => {
+ handleChange('modifierKeys', { ...DEFAULT_MODIFIER_KEY_SETTINGS });
+ onShowToast('Modifier keys reset to defaults');
+ };
const resolvedAccent = resolveModernAccentColor(
localSettings.modernAccent,
@@ -108,20 +280,27 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{ id: 'canvas', label: 'Canvas', icon: <Layers className="w-3.5 h-3.5" /> },
{ id: 'brush', label: 'Brush & Stylus', icon: <Paintbrush className="w-3.5 h-3.5" /> },
{ id: 'shortcuts', label: 'Shortcuts', icon: <Keyboard className="w-3.5 h-3.5" /> },
+ {
+ id: 'modifiers',
+ label: 'Modifier Keys',
+ icon: <SlidersHorizontal className="w-3.5 h-3.5" />,
+ },
{ id: 'about', label: 'About', icon: <Info className="w-3.5 h-3.5" /> },
];
return (
<div
+ role="dialog"
+ aria-modal="true"
className="fixed inset-0 z-50 flex items-center justify-center bg-black/75 p-4 select-none"
onClick={onClose}
onKeyDown={(e) => {
- if (e.key === 'Escape') onClose();
+ if (e.key === 'Escape' && !recordingCommandId) onClose();
}}
>
<div
onClick={(e) => e.stopPropagation()}
- className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] w-full max-w-2xl flex flex-col overflow-hidden text-xs text-[#e5e5e5] h-[520px]"
+ className="bg-[#202020] rounded-lg shadow-[0_24px_64px_rgba(0,0,0,0.8)] w-full max-w-3xl flex flex-col overflow-hidden text-xs text-[#e5e5e5] h-[600px]"
>
{/* Header */}
<div className="h-10 px-4 flex items-center justify-between bg-[#161616] shrink-0">
@@ -139,7 +318,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{/* Body */}
<div className="flex flex-1 overflow-hidden gap-px bg-[#161616]">
{/* Left Navigation */}
- <div className="w-40 bg-[#202020] p-2 flex flex-col justify-between shrink-0">
+ <div className="w-44 bg-[#202020] p-2 flex flex-col justify-between shrink-0">
<div className="space-y-0.5">
{tabs.map((t) => {
const active = activeTab === t.id;
@@ -147,7 +326,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
<button
key={t.id}
type="button"
- onClick={() => setActiveTab(t.id)}
+ onClick={() => {
+ setActiveTab(t.id);
+ setRecordingCommandId(null);
+ setPendingConflict(null);
+ }}
className={`w-full flex items-center gap-2 px-2.5 py-1.5 rounded text-left transition-colors cursor-pointer ${
active
? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium'
@@ -167,7 +350,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
className="w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#2c2c2c] transition-colors cursor-pointer"
>
<RotateCcw className="w-3 h-3" />
- <span>Reset Defaults</span>
+ <span>Reset All Defaults</span>
</button>
</div>
@@ -175,7 +358,6 @@ 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>
@@ -210,7 +392,6 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
</div>
</section>
- {/* Accent Color Customization */}
<section className="space-y-2.5">
<div className="flex items-center justify-between">
<div>
@@ -272,7 +453,6 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
</button>
</div>
- {/* Custom Hex & Native Picker */}
<div className="flex items-center gap-2.5 p-2.5 rounded bg-[#161616]">
<input
type="color"
@@ -321,7 +501,6 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
</div>
</section>
- {/* User Profile */}
<section className="space-y-2">
<h3 className="text-xs font-medium text-[#e5e5e5]">Artist Name</h3>
<input
@@ -341,7 +520,6 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
/>
</section>
- {/* Overlays */}
<section className="space-y-2">
<h3 className="text-xs font-medium text-[#e5e5e5]">Viewport Overlays</h3>
<div className="space-y-1 bg-[#161616] rounded p-2.5">
@@ -472,6 +650,11 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{activeTab === 'brush' && (
<>
+ <PressureCurveEditor
+ value={localSettings.pressureCurve}
+ onChange={(nextCurve) => handleChange('pressureCurve', nextCurve)}
+ />
+
<section className="space-y-2">
<div className="flex items-center justify-between">
<h3 className="text-xs font-medium text-[#e5e5e5]">Default Stabilization</h3>
@@ -535,29 +718,227 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({
{activeTab === 'shortcuts' && (
<div className="space-y-3">
- <div className="relative">
- <Search className="w-3.5 h-3.5 text-[#8a8a8a] absolute left-2.5 top-1/2 -translate-y-1/2" />
- <input
- type="text"
- placeholder="Filter shortcuts..."
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- className="w-full bg-[#161616] rounded pl-8 pr-3 py-1.5 text-xs text-[#e5e5e5] placeholder-[#8a8a8a]"
- />
+ <div className="flex items-center gap-2">
+ <div className="relative flex-1">
+ <Search className="w-3.5 h-3.5 text-[#8a8a8a] absolute left-2.5 top-1/2 -translate-y-1/2" />
+ <input
+ type="text"
+ placeholder="Search commands or keys..."
+ value={searchQuery}
+ onChange={(e) => setSearchQuery(e.target.value)}
+ className="w-full bg-[#161616] rounded pl-8 pr-3 py-1.5 text-xs text-[#e5e5e5] placeholder-[#8a8a8a]"
+ />
+ </div>
+ <button
+ type="button"
+ onClick={handleResetAllShortcuts}
+ className="flex items-center gap-1 px-2.5 py-1.5 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer shrink-0"
+ title="Reset all keybindings to defaults"
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span>Reset</span>
+ </button>
</div>
+
+ {/* Category Filter Pills */}
+ <div className="flex flex-wrap gap-1">
+ {(['All', ...SHORTCUT_CATEGORIES] as const).map((cat) => {
+ const active = selectedCategory === cat;
+ return (
+ <button
+ key={cat}
+ type="button"
+ onClick={() => setSelectedCategory(cat)}
+ className={`px-2.5 py-1 rounded text-[11px] transition-colors cursor-pointer ${
+ active
+ ? 'bg-[#2c2c2c] text-[#e5e5e5] font-medium ring-1 ring-[var(--accent-border)]'
+ : 'bg-[#161616] text-[#8a8a8a] hover:text-[#e5e5e5]'
+ }`}
+ >
+ {cat}
+ </button>
+ );
+ })}
+ </div>
+
+ {/* Conflict Resolution Banner */}
+ {pendingConflict && (
+ <div className="p-2.5 rounded bg-amber-500/10 border border-amber-500/40 flex items-center justify-between gap-2 text-[11px]">
+ <div className="flex items-center gap-2 text-amber-200">
+ <AlertTriangle className="w-4 h-4 shrink-0 text-amber-400" />
+ <span>
+ <strong className="font-mono">
+ {formatShortcutLabel(pendingConflict.shortcut)}
+ </strong>{' '}
+ conflicts with{' '}
+ <strong>
+ {pendingConflict.conflicts.map((c) => c.label).join(', ')}
+ </strong>
+ . Reassign anyway?
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5 shrink-0">
+ <button
+ type="button"
+ onClick={handleConfirmConflictReplace}
+ className="px-2 py-1 rounded bg-amber-500 text-black font-medium cursor-pointer"
+ >
+ Replace
+ </button>
+ <button
+ type="button"
+ onClick={() => setPendingConflict(null)}
+ className="px-2 py-1 rounded bg-[#161616] text-[#e5e5e5] hover:bg-[#2c2c2c] cursor-pointer"
+ >
+ Cancel
+ </button>
+ </div>
+ </div>
+ )}
+
<div className="space-y-0.5">
- {filteredShortcuts.map((row, idx) => (
+ {filteredCommands.map((cmd) => {
+ const activeKey = resolveCommandShortcut(cmd, localSettings.shortcuts);
+ const isRecording = recordingCommandId === cmd.id;
+ const isOverridden = Object.prototype.hasOwnProperty.call(
+ localSettings.shortcuts,
+ cmd.id
+ );
+ return (
+ <div
+ key={cmd.id}
+ className="flex items-center justify-between gap-2 px-2.5 py-1.5 rounded hover:bg-[#2c2c2c]/50"
+ >
+ <div className="min-w-0">
+ <div className="flex items-center gap-1.5">
+ <span className="text-xs text-[#e5e5e5] truncate">{cmd.label}</span>
+ <span className="text-[9px] px-1.5 py-0.5 rounded bg-[#161616] text-[#8a8a8a]">
+ {cmd.category}
+ </span>
+ {cmd.springLoaded && (
+ <span
+ className="text-[9px] px-1.5 py-0.5 rounded bg-[var(--accent-subtle)] text-[var(--accent)]"
+ title="Hold key > 250ms to temporarily activate and revert on release"
+ >
+ Hold
+ </span>
+ )}
+ </div>
+ <div className="text-[10px] text-[#8a8a8a] truncate">
+ {cmd.description}
+ </div>
+ </div>
+
+ <div className="flex items-center gap-1 shrink-0">
+ <button
+ type="button"
+ onClick={() => {
+ setPendingConflict(null);
+ setRecordingCommandId(isRecording ? null : cmd.id);
+ }}
+ className={`px-2 py-1 rounded font-mono text-[10px] min-w-[84px] text-center transition-colors cursor-pointer ${
+ isRecording
+ ? 'bg-[var(--accent)] text-[var(--accent-contrast)] font-semibold'
+ : activeKey
+ ? 'bg-[#161616] text-[#e5e5e5] hover:bg-[#2c2c2c]'
+ : 'bg-[#161616] text-[#8a8a8a] italic hover:bg-[#2c2c2c]'
+ }`}
+ title="Click and press a key combination to rebind"
+ >
+ {isRecording ? 'Press keys...' : formatShortcutLabel(activeKey)}
+ </button>
+ {activeKey && (
+ <button
+ type="button"
+ onClick={() => handleClearSingleShortcut(cmd.id)}
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#161616] cursor-pointer"
+ title="Unbind shortcut"
+ >
+ <X className="w-3 h-3" />
+ </button>
+ )}
+ {isOverridden && (
+ <button
+ type="button"
+ onClick={() => handleResetSingleShortcut(cmd.id)}
+ className="w-6 h-6 rounded flex items-center justify-center text-[#8a8a8a] hover:text-[#e5e5e5] hover:bg-[#161616] cursor-pointer"
+ title={`Reset to default (${formatShortcutLabel(cmd.defaultShortcut)})`}
+ >
+ <RotateCcw className="w-3 h-3" />
+ </button>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ )}
+
+ {activeTab === 'modifiers' && (
+ <div className="space-y-4">
+ <div className="flex items-center justify-between">
+ <div>
+ <h3 className="text-xs font-medium text-[#e5e5e5]">Modifier Key Settings</h3>
+ <p className="text-[11px] text-[#8a8a8a]">
+ Configure hold-to-act keys, mouse buttons, stylus barrel buttons, and scroll wheel
+ </p>
+ </div>
+ <button
+ type="button"
+ onClick={handleResetModifiers}
+ className="flex items-center gap-1 px-2.5 py-1 rounded bg-[#161616] hover:bg-[#2c2c2c] text-[11px] text-[#8a8a8a] hover:text-[#e5e5e5] cursor-pointer"
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span>Reset</span>
+ </button>
+ </div>
+
+ {/* Mouse Wheel */}
+ <div className="flex items-center justify-between gap-3 px-3 py-2 rounded bg-[#161616]">
+ <div>
+ <div className="text-xs text-[#e5e5e5] font-medium">Mouse Wheel</div>
+ <div className="text-[10px] text-[#8a8a8a]">
+ Action when scrolling wheel over the canvas viewport
+ </div>
+ </div>
+ <select
+ value={localSettings.modifierKeys.mouseWheel}
+ onChange={(e) => handleMouseWheelChange(e.target.value as MouseWheelAction)}
+ className="bg-[#202020] text-[#e5e5e5] text-xs px-2.5 py-1.5 rounded border border-white/10 cursor-pointer"
+ >
+ {MOUSE_WHEEL_OPTIONS.map((opt) => (
+ <option key={opt.value} value={opt.value}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
+ </div>
+
+ {/* Keyboard, Mouse & Stylus Modifier Slots */}
+ <div className="space-y-1">
+ {MODIFIER_SLOTS.map(({ slot, label, desc }) => (
<div
- key={idx}
- className="flex items-center justify-between px-2.5 py-1.5 rounded hover:bg-[#2c2c2c]/50"
+ key={slot}
+ className="flex items-center justify-between gap-3 px-3 py-2 rounded bg-[#161616]"
>
- <div>
- <div className="text-xs text-[#e5e5e5]">{row.action}</div>
- <div className="text-[10px] text-[#8a8a8a]">{row.desc}</div>
+ <div className="min-w-0">
+ <div className="text-xs text-[#e5e5e5] font-mono">{label}</div>
+ <div className="text-[10px] text-[#8a8a8a] truncate">{desc}</div>
</div>
- <kbd className="px-2 py-0.5 rounded bg-[#161616] font-mono text-[10px] text-[#e5e5e5]">
- {row.shortcut}
- </kbd>
+ <select
+ value={localSettings.modifierKeys[slot]}
+ onChange={(e) =>
+ handleModifierSlotChange(slot, e.target.value as ModifierAction)
+ }
+ className="bg-[#202020] text-[#e5e5e5] text-xs px-2.5 py-1.5 rounded border border-white/10 cursor-pointer shrink-0"
+ >
+ {MODIFIER_ACTION_OPTIONS.map((opt) => (
+ <option key={opt.value} value={opt.value}>
+ {opt.label}
+ </option>
+ ))}
+ </select>
</div>
))}
</div>
diff --git a/src/engine/StrokePipeline.ts b/src/engine/StrokePipeline.ts
index 8c41d29..34a47be 100644
--- a/src/engine/StrokePipeline.ts
+++ b/src/engine/StrokePipeline.ts
@@ -11,6 +11,8 @@ import { InputStabilizer, StabilizedSample } from './InputStabilizer';
import { SplineGenerator, SplinePoint, CubicBezierSegment } from './SplineGenerator';
import { TaperEngine } from './TaperEngine';
import type { DirtyRect } from '../types/editor';
+import type { PressureCurveSettings } from '../types/settings';
+import { evaluateGlobalPressureCurve, isLinearPressureCurve } from '../utils/pressureCurve';
export interface ViewportTransform {
panX: number;
@@ -43,6 +45,7 @@ export interface StrokeSamplePoint {
y: number;
pressure: number;
width: number;
+ opacity: number;
tiltX: number;
tiltY: number;
twist: number;
@@ -167,6 +170,7 @@ export class StrokePipeline {
y: 0,
pressure: 0,
width: 1,
+ opacity: 1,
tiltX: 0,
tiltY: 0,
twist: 0,
@@ -176,6 +180,7 @@ export class StrokePipeline {
vy: 0,
pointerType: 'pen',
};
+ private globalPressureCurve: PressureCurveSettings | null = null;
private scratchPredPt: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0 };
private scratchPrevPredPt: SplinePoint = { x: 0, y: 0, pressure: 0, width: 0, tiltX: 0, tiltY: 0, twist: 0 };
@@ -234,6 +239,14 @@ export class StrokePipeline {
this.strokeColor = color;
}
+ public setGlobalPressureCurve(curve: PressureCurveSettings | null): void {
+ this.globalPressureCurve = curve;
+ }
+
+ public getGlobalPressureCurve(): PressureCurveSettings | null {
+ return this.globalPressureCurve;
+ }
+
public getTaperEngine(): TaperEngine {
return this.taperEngine;
}
@@ -314,6 +327,7 @@ export class StrokePipeline {
brushSize?: number;
color?: string;
pointerId?: number;
+ globalPressureCurve?: PressureCurveSettings | null;
}): void {
this.stabilizer.reset();
this.splineGen.reset();
@@ -332,6 +346,9 @@ export class StrokePipeline {
if (config?.brushSize !== undefined || config?.color !== undefined) {
this.setBrushParameters(config.brushSize ?? this.baseBrushSize, config.color ?? this.strokeColor);
}
+ if (config?.globalPressureCurve !== undefined) {
+ this.globalPressureCurve = config.globalPressureCurve;
+ }
this.headIndex = 0;
this.tailIndex = 0;
@@ -498,13 +515,37 @@ export class StrokePipeline {
sample.vy = vy;
sample.pointerType = pointerType;
+ const calibratedStabPressure = evaluateGlobalPressureCurve(
+ stabPressure,
+ this.globalPressureCurve
+ );
+
if (options?.resolvePoint) {
- options.resolvePoint(rawX, rawY, rawP, stabPressure, pointerType, vx, vy, dtMs, sample);
+ sample.opacity = calibratedStabPressure;
+ options.resolvePoint(
+ rawX,
+ rawY,
+ rawP,
+ calibratedStabPressure,
+ pointerType,
+ vx,
+ vy,
+ dtMs,
+ sample
+ );
} else {
- const mappedPressure = this.taperEngine.mapPressure(stabPressure);
+ const hasNonLinearGlobalCurve = Boolean(
+ this.globalPressureCurve &&
+ this.globalPressureCurve.enabled &&
+ !isLinearPressureCurve(this.globalPressureCurve.points)
+ );
+ const mappedPressure = hasNonLinearGlobalCurve
+ ? calibratedStabPressure
+ : this.taperEngine.mapPressure(calibratedStabPressure);
const smoothPressure = this.taperEngine.smoothPressure(mappedPressure);
sample.pressure = smoothPressure;
sample.width = Math.max(0.5, this.baseBrushSize * smoothPressure);
+ sample.opacity = Math.max(0, Math.min(1, smoothPressure));
}
this.expandDirtyRect(sample.x, sample.y, sample.width + padExtra);
@@ -626,6 +667,7 @@ export class StrokePipeline {
sample.y = fp.y;
sample.pressure = fp.pressure;
sample.width = fp.width;
+ sample.opacity = fp.alpha;
sample.tiltX = this.knotP2.tiltX ?? 0;
sample.tiltY = this.knotP2.tiltY ?? 0;
sample.twist = this.knotP2.twist ?? 0;
diff --git a/src/hooks/drawing/useBrushStrokeSession.ts b/src/hooks/drawing/useBrushStrokeSession.ts
index 2983a8b..cecd306 100644
--- a/src/hooks/drawing/useBrushStrokeSession.ts
+++ b/src/hooks/drawing/useBrushStrokeSession.ts
@@ -48,7 +48,8 @@ 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 { useToolStore, useUiStore } from '../../stores';
+import { evaluateGlobalPressureCurve, isLinearPressureCurve } from '../../utils/pressureCurve';
import {
DraftCanvasElement,
ExtendedPointerEvent,
@@ -441,8 +442,11 @@ export function useBrushStrokeSession({
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 rawP = e.pressure !== undefined ? Math.max(0, Math.min(1.0, e.pressure)) : 0;
+ pressure = evaluateGlobalPressureCurve(
+ rawP,
+ useUiStore.getState().appSettings.pressureCurve
+ );
}
const width = calculateStrokeWidth(
@@ -470,6 +474,17 @@ export function useBrushStrokeSession({
[dimensionsRef, flipXRef, flipYRef, getBrushSettings, getViewportRect, panRef, rotationRef, zoomRef]
);
+ const resolveEffectiveOpacitySensor = useCallback(
+ (bs: BrushSettings, isMonochrome: boolean, isEraser: boolean) => {
+ if (bs.opacitySensor) return bs.opacitySensor;
+ if (bs.usePressure && !isMonochrome && !isEraser && (bs.flow ?? 1.0) < 0.99) {
+ return { usePressure: true, pressureMin: 0.2 };
+ }
+ return undefined;
+ },
+ []
+ );
+
const buildLiveTexturedOptions = useCallback(
(
bs: BrushSettings,
@@ -506,7 +521,7 @@ export function useBrushStrokeSession({
useVelocity: bs.useVelocity,
useTilt: Boolean(bs.useTilt),
sizeSensor: bs.sizeSensor,
- opacitySensor: bs.opacitySensor,
+ opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, isEraser),
densitySensor: bs.densitySensor,
subTips: bs.subTips,
subTipOrder: bs.subTipOrder,
@@ -543,7 +558,7 @@ export function useBrushStrokeSession({
dynamics: bs.dynamics,
secondaryColor: bs.secondaryColor,
}),
- []
+ [resolveEffectiveOpacitySensor]
);
const buildLiveRadialOptions = useCallback(
@@ -589,11 +604,11 @@ export function useBrushStrokeSession({
paperTextureScale: bs.paperTextureScale,
paperTextureRotate: bs.paperTextureRotate,
sizeSensor: bs.sizeSensor,
- opacitySensor: bs.opacitySensor,
+ opacitySensor: resolveEffectiveOpacitySensor(bs, isMonochrome, false),
densitySensor: bs.densitySensor,
taper: bs.taper,
}),
- []
+ [resolveEffectiveOpacitySensor]
);
const resolveStrokeColor = useCallback(
@@ -1044,7 +1059,12 @@ export function useBrushStrokeSession({
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 globalCurve = pipeline.getGlobalPressureCurve();
+ const hasCustomGlobalCurve = Boolean(
+ globalCurve && globalCurve.enabled && !isLinearPressureCurve(globalCurve.points)
+ );
+ const hasCustomCurve =
+ hasCustomGlobalCurve || 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);
@@ -1462,6 +1482,13 @@ export function useBrushStrokeSession({
const strokeFlow = isMonochrome ? 1.0 : bs.flow ?? 1.0;
const strokeSpacing = bs.spacing ?? 0.08;
+ const globalPressureCurve = useUiStore.getState().appSettings.pressureCurve;
+ const hasCustomGlobalCurve = Boolean(
+ globalPressureCurve &&
+ globalPressureCurve.enabled &&
+ !isLinearPressureCurve(globalPressureCurve.points)
+ );
+
const pipeline = strokePipelineRef.current;
pipeline.beginStroke({
stabilizerLevel: bs.stabilization ?? 0,
@@ -1470,11 +1497,13 @@ export function useBrushStrokeSession({
brushSize: bs.size,
color: strokeColor,
pointerId: e.pointerId,
+ globalPressureCurve,
});
const startNow = startPoint.timestamp ?? performance.now();
lastPointTimeRef.current = startNow;
- const hasCustomCurve = Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
+ const hasCustomCurve =
+ hasCustomGlobalCurve || Boolean(bs.pressureCurve && bs.pressureCurve.length > 0);
const taperEngine = pipeline.getTaperEngine();
if (bs.usePressure) {
const baseStartP = hasCustomCurve
@@ -1506,9 +1535,11 @@ export function useBrushStrokeSession({
)
);
+ const shiftAction = useUiStore.getState().appSettings.modifierKeys.shift;
const prevStrokeEnd = lastStrokeEndRef.current;
const isShiftLine =
Boolean(e.shiftKey) &&
+ shiftAction === 'straight-line' &&
!isMaskModeRef.current &&
prevStrokeEnd !== null &&
prevStrokeEnd.layerId === currentLayerId;
@@ -1997,6 +2028,7 @@ export function useBrushStrokeSession({
} else if (
!isShiftLineStrokeRef.current &&
isShiftKey &&
+ useUiStore.getState().appSettings.modifierKeys.shift === 'straight-line' &&
!ruler?.enabled &&
allStrokePointsRef.current.length > 0
) {
@@ -2520,13 +2552,23 @@ export function useBrushStrokeSession({
rCtx.clip();
applySelectionCanvasClip(rCtx, activeSelection);
- const needsIsolatedBake = (bs.opacity ?? 1.0) < 0.999 || hasWetEdge;
+ const effectiveOpacitySensor = resolveEffectiveOpacitySensor(
+ bs,
+ isMonochrome,
+ isEraser
+ );
+ const bakeBs: BrushSettings =
+ effectiveOpacitySensor && !bs.opacitySensor
+ ? { ...bs, opacitySensor: effectiveOpacitySensor }
+ : bs;
+
+ const needsIsolatedBake = (bakeBs.opacity ?? 1.0) < 0.999 || hasWetEdge;
if (!needsIsolatedBake) {
renderCompleteStroke(
rCtx,
allPoints,
- bs,
+ bakeBs,
currentTool,
effectiveMode,
isBgEraser,
@@ -2534,8 +2576,8 @@ export function useBrushStrokeSession({
Boolean(activeLayer?.alphaLocked)
);
} else {
- rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bs.opacity ?? 1.0));
- if ((isEraser && !isBgEraser) || bs.isTransparentInk) {
+ rCtx.globalAlpha = Math.max(0.01, Math.min(1.0, bakeBs.opacity ?? 1.0));
+ if ((isEraser && !isBgEraser) || bakeBs.isTransparentInk) {
rCtx.globalCompositeOperation = 'destination-out';
} else if (activeLayer?.alphaLocked) {
rCtx.globalCompositeOperation = 'source-atop';
@@ -2555,11 +2597,11 @@ export function useBrushStrokeSession({
bCtx,
allPoints,
{
- ...bs,
+ ...bakeBs,
opacity: 1.0,
isTransparentInk: false,
wetEdge: 0,
- color: isEraser && !isBgEraser ? '#000000' : bs.color,
+ color: isEraser && !isBgEraser ? '#000000' : bakeBs.color,
},
isEraser && !isBgEraser ? 'brush' : currentTool,
effectiveMode,
diff --git a/src/hooks/useCanvasNavigation.ts b/src/hooks/useCanvasNavigation.ts
index 4c238a4..8172ccc 100644
--- a/src/hooks/useCanvasNavigation.ts
+++ b/src/hooks/useCanvasNavigation.ts
@@ -1,5 +1,8 @@
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react';
import { CanvasDimensions } from '../types/editor';
+import { toolStoreActions, useToolStore, useUiStore } from '../stores';
+import { stepBrushSizePreset } from '../utils/brushPresetManager';
+import { resolveHeldKeyModifierAction } from '../utils/shortcutManager';
export const MIN_ZOOM = 0.01; // 1%
export const MAX_ZOOM = 32.0; // 3200%
@@ -143,8 +146,11 @@ export function useCanvasNavigation({
const [isSpaceDown, setIsSpaceDown] = useState<boolean>(false);
const [isShiftDown, setIsShiftDown] = useState<boolean>(false);
+ const [isCtrlDown, setIsCtrlDown] = useState<boolean>(false);
+ const [isAltDown, setIsAltDown] = useState<boolean>(false);
const [isPanning, setIsPanning] = useState<boolean>(false);
const [isRotating, setIsRotating] = useState<boolean>(false);
+ const [isZoomDragging, setIsZoomDragging] = useState<boolean>(false);
// Synchronous refs for sub-frame precision (authoritative source of truth during active interaction)
const zoomRef = useRef<number>(1.0);
@@ -155,8 +161,11 @@ export function useCanvasNavigation({
const isSpaceDownRef = useRef<boolean>(false);
const isShiftDownRef = useRef<boolean>(false);
+ const isCtrlDownRef = useRef<boolean>(false);
+ const isAltDownRef = useRef<boolean>(false);
const isPanningRef = useRef<boolean>(false);
const isRotatingRef = useRef<boolean>(false);
+ const isZoomDraggingRef = useRef<boolean>(false);
const cameraSubscribersRef = useRef<Set<CameraSubscriber>>(new Set());
const cameraBroadcastRafRef = useRef<number | null>(null);
@@ -225,7 +234,7 @@ export function useCanvasNavigation({
}
navCommitTimerRef.current = setTimeout(() => {
navCommitTimerRef.current = null;
- if (isPanningRef.current || isRotatingRef.current) return;
+ if (isPanningRef.current || isRotatingRef.current || isZoomDraggingRef.current) return;
commitNavStateImmediate();
}, NAV_STATE_COMMIT_DEBOUNCE_MS);
}, [commitNavStateImmediate]);
@@ -266,6 +275,22 @@ export function useCanvasNavigation({
center: { x: 0, y: 0 },
});
+ const zoomDragStartRef = useRef<{
+ clientX: number;
+ clientY: number;
+ anchorX: number;
+ anchorY: number;
+ startZoom: number;
+ startPan: { x: number; y: number };
+ }>({
+ clientX: 0,
+ clientY: 0,
+ anchorX: 0,
+ anchorY: 0,
+ startZoom: 1,
+ startPan: { x: 0, y: 0 },
+ });
+
const hasInitializedCenterRef = useRef<boolean>(false);
const setZoom = useCallback(
@@ -551,6 +576,23 @@ export function useCanvasNavigation({
setIsRotating(true);
}, []);
+ const startZoomDrag = useCallback((e: React.PointerEvent | PointerEvent) => {
+ e.preventDefault();
+ const viewport = viewportRef.current;
+ if (!viewport) return;
+ const rect = viewport.getBoundingClientRect();
+ zoomDragStartRef.current = {
+ clientX: e.clientX,
+ clientY: e.clientY,
+ anchorX: e.clientX - rect.left,
+ anchorY: e.clientY - rect.top,
+ startZoom: zoomRef.current,
+ startPan: { ...panRef.current },
+ };
+ isZoomDraggingRef.current = true;
+ setIsZoomDragging(true);
+ }, []);
+
useEffect(() => {
hasInitializedCenterRef.current = false;
}, [activeDocumentId]);
@@ -615,8 +657,34 @@ export function useCanvasNavigation({
delta *= 500;
}
- if (isWebtoonModeRef.current && !e.ctrlKey && !e.metaKey) {
- panRef.current = { x: panRef.current.x, y: panRef.current.y - delta };
+ const wheelAction = useUiStore.getState().appSettings.modifierKeys.mouseWheel;
+
+ if (wheelAction === 'brush-size' && !e.ctrlKey && !e.metaKey) {
+ const dir: -1 | 1 = delta < 0 ? 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;
+ }
+
+ if ((wheelAction === 'scroll' || isWebtoonModeRef.current) && !e.ctrlKey && !e.metaKey) {
+ let deltaX = e.deltaX;
+ if (e.deltaMode === 1) deltaX *= 28;
+ else if (e.deltaMode === 2) deltaX *= 500;
+ const scrollX = e.shiftKey ? delta : deltaX;
+ const scrollY = e.shiftKey ? 0 : delta;
+ panRef.current = {
+ x: isWebtoonModeRef.current ? panRef.current.x : panRef.current.x - scrollX,
+ y: panRef.current.y - scrollY,
+ };
scheduleCameraBroadcast();
scheduleNavStateCommit();
return;
@@ -644,7 +712,7 @@ export function useCanvasNavigation({
};
}, [activeDocumentId, scheduleCameraBroadcast, scheduleNavStateCommit]);
- // Global Keyboard Shortcuts (Space, Shift, Ctrl+0, Ctrl+Alt+0, Ctrl++, Ctrl+-)
+ // Modifier state tracking (Space, Shift, Ctrl, Alt) for navigation & modifier-key drag modes
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent) => {
const targetEl = e.target as HTMLElement | null;
@@ -654,51 +722,30 @@ export function useCanvasNavigation({
) {
return;
}
- if (document.querySelector('[role="dialog"]')) {
+ if (document.querySelector('[role="dialog"]') || useUiStore.getState().isSettingsModalOpen) {
return;
}
- if (e.key === 'Shift') {
- if (!isShiftDownRef.current) {
- isShiftDownRef.current = true;
- setIsShiftDown(true);
- }
+ if (e.key === 'Shift' && !isShiftDownRef.current) {
+ isShiftDownRef.current = true;
+ setIsShiftDown(true);
+ }
+ if ((e.key === 'Control' || e.key === 'Meta') && !isCtrlDownRef.current) {
+ isCtrlDownRef.current = true;
+ setIsCtrlDown(true);
+ }
+ if (e.key === 'Alt' && !isAltDownRef.current) {
+ isAltDownRef.current = true;
+ setIsAltDown(true);
}
- // Space key for Pan Hand Tool or Rotate with Shift+Space (skip Alt+Space so Animation playback can use it)
- if ((e.code === 'Space' || e.key === ' ') && !e.altKey && !e.ctrlKey && !e.metaKey) {
+ // Space key for Pan / Rotate / Scrubby Zoom (skip Alt+Space so Animation playback can use it)
+ if ((e.code === 'Space' || e.key === ' ') && !e.altKey) {
e.preventDefault();
if (!isSpaceDownRef.current) {
isSpaceDownRef.current = true;
setIsSpaceDown(true);
}
- return;
- }
-
- if (e.ctrlKey || e.metaKey) {
- if (e.altKey && (e.code === 'Digit0' || e.code === 'Numpad0' || e.key === '0')) {
- e.preventDefault();
- resetRotation();
- return;
- }
-
- if (!e.altKey && (e.code === 'Digit0' || e.code === 'Numpad0' || e.key === '0')) {
- e.preventDefault();
- resetZoomAndCenter();
- return;
- }
-
- if (e.code === 'Equal' || e.code === 'NumpadAdd' || e.key === '+' || e.key === '=') {
- e.preventDefault();
- zoomIn();
- return;
- }
-
- if (e.code === 'Minus' || e.code === 'NumpadSubtract' || e.key === '-' || e.key === '_') {
- e.preventDefault();
- zoomOut();
- return;
- }
}
};
@@ -707,6 +754,14 @@ export function useCanvasNavigation({
isShiftDownRef.current = false;
setIsShiftDown(false);
}
+ if (e.key === 'Control' || e.key === 'Meta') {
+ isCtrlDownRef.current = false;
+ setIsCtrlDown(false);
+ }
+ if (e.key === 'Alt') {
+ isAltDownRef.current = false;
+ setIsAltDown(false);
+ }
if (e.code === 'Space' || e.key === ' ') {
isSpaceDownRef.current = false;
setIsSpaceDown(false);
@@ -714,15 +769,22 @@ export function useCanvasNavigation({
};
const handleBlur = () => {
- const wasInteracting = isPanningRef.current || isRotatingRef.current;
+ const wasInteracting =
+ isPanningRef.current || isRotatingRef.current || isZoomDraggingRef.current;
isSpaceDownRef.current = false;
setIsSpaceDown(false);
isShiftDownRef.current = false;
setIsShiftDown(false);
+ isCtrlDownRef.current = false;
+ setIsCtrlDown(false);
+ isAltDownRef.current = false;
+ setIsAltDown(false);
isPanningRef.current = false;
setIsPanning(false);
isRotatingRef.current = false;
setIsRotating(false);
+ isZoomDraggingRef.current = false;
+ setIsZoomDragging(false);
if (wasInteracting) {
broadcastCameraImmediate();
commitNavStateImmediate();
@@ -738,7 +800,7 @@ export function useCanvasNavigation({
window.removeEventListener('keyup', handleKeyUp);
window.removeEventListener('blur', handleBlur);
};
- }, [resetRotation, resetZoomAndCenter, zoomIn, zoomOut, broadcastCameraImmediate, commitNavStateImmediate]);
+ }, [broadcastCameraImmediate, commitNavStateImmediate]);
// Panning pointermove: broadcasts directly to DOM/WebGL via rAF; commits React state only on pointerup
useEffect(() => {
@@ -856,6 +918,49 @@ export function useCanvasNavigation({
};
}, [isRotating, scheduleCameraBroadcast, broadcastCameraImmediate, commitNavStateImmediate]);
+ // Scrubby Zoom pointermove (default Ctrl+Space+Drag): zero-rerender via rAF camera broadcast
+ useEffect(() => {
+ if (!isZoomDragging) return;
+
+ const handleWindowPointerMove = (e: PointerEvent) => {
+ if (!isZoomDraggingRef.current) return;
+ const dx = e.clientX - zoomDragStartRef.current.clientX;
+ const { anchorX, anchorY, startZoom, startPan } = zoomDragStartRef.current;
+ const nextZoom = Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, startZoom * Math.exp(dx * 0.007)));
+ const ratio = nextZoom / startZoom;
+ zoomRef.current = nextZoom;
+ panRef.current = {
+ x: anchorX - (anchorX - startPan.x) * ratio,
+ y: anchorY - (anchorY - startPan.y) * ratio,
+ };
+ scheduleCameraBroadcast();
+ };
+
+ const handleWindowPointerUp = () => {
+ isZoomDraggingRef.current = false;
+ broadcastCameraImmediate();
+ setIsZoomDragging(false);
+ commitNavStateImmediate();
+ };
+
+ window.addEventListener('pointermove', handleWindowPointerMove, { passive: true });
+ window.addEventListener('pointerup', handleWindowPointerUp);
+ window.addEventListener('pointercancel', handleWindowPointerUp);
+
+ const prevCursor = document.body.style.cursor;
+ const prevUserSelect = document.body.style.userSelect;
+ document.body.style.cursor = 'zoom-in';
+ document.body.style.userSelect = 'none';
+
+ return () => {
+ window.removeEventListener('pointermove', handleWindowPointerMove);
+ window.removeEventListener('pointerup', handleWindowPointerUp);
+ window.removeEventListener('pointercancel', handleWindowPointerUp);
+ document.body.style.cursor = prevCursor;
+ document.body.style.userSelect = prevUserSelect;
+ };
+ }, [isZoomDragging, scheduleCameraBroadcast, broadcastCameraImmediate, commitNavStateImmediate]);
+
useEffect(() => {
const handleAuxClick = (e: MouseEvent) => {
if (e.button === 1) {
@@ -879,7 +984,11 @@ export function useCanvasNavigation({
[getCameraState, subscribeCamera]
);
- const isRotateModifier = isSpaceDown && isShiftDown;
+ const activeHeldModifierAction = resolveHeldKeyModifierAction(
+ { ctrl: isCtrlDown, shift: isShiftDown, alt: isAltDown, space: isSpaceDown },
+ useUiStore.getState().appSettings.modifierKeys
+ );
+ const isRotateModifier = activeHeldModifierAction === 'rotate';
return {
viewportRef,
@@ -898,11 +1007,15 @@ export function useCanvasNavigation({
subscribeCamera,
isSpaceDown,
isShiftDown,
+ isCtrlDown,
+ isAltDown,
isRotateModifier,
isPanning,
isRotating,
+ isZoomDragging,
startPan,
startRotate,
+ startZoomDrag,
zoomIn,
zoomOut,
resetZoomAndCenter,
diff --git a/src/types/settings.ts b/src/types/settings.ts
index b87a48e..25753de 100644
--- a/src/types/settings.ts
+++ b/src/types/settings.ts
@@ -72,6 +72,112 @@ export function getAccentContrastColor(hex: string): string {
return luminance > 0.55 ? '#161616' : '#e5e5e5';
}
+export type ShortcutCategory = 'Tools' | 'Menu' | 'Canvas View' | 'Layer' | 'Edit';
+
+export type ShortcutOverrides = Record<string, string>;
+
+export type ModifierKeySlot =
+ | 'space'
+ | 'shift'
+ | 'ctrl'
+ | 'alt'
+ | 'ctrlSpace'
+ | 'shiftSpace'
+ | 'ctrlAlt'
+ | 'shiftAlt'
+ | 'rightClick'
+ | 'middleClick'
+ | 'stylusButton1'
+ | 'stylusButton2';
+
+export type ModifierAction =
+ | 'none'
+ | 'pan'
+ | 'rotate'
+ | 'zoom-drag'
+ | 'eyedropper'
+ | 'brush-size'
+ | 'straight-line'
+ | 'temp-eraser'
+ | 'undo'
+ | 'swap-colors'
+ | 'quick-palette';
+
+export type MouseWheelAction = 'zoom' | 'scroll' | 'brush-size';
+
+export interface ModifierKeySettings {
+ space: ModifierAction;
+ shift: ModifierAction;
+ ctrl: ModifierAction;
+ alt: ModifierAction;
+ ctrlSpace: ModifierAction;
+ shiftSpace: ModifierAction;
+ ctrlAlt: ModifierAction;
+ shiftAlt: ModifierAction;
+ rightClick: ModifierAction;
+ middleClick: ModifierAction;
+ stylusButton1: ModifierAction;
+ stylusButton2: ModifierAction;
+ mouseWheel: MouseWheelAction;
+}
+
+export type PressureCurvePoint = [number, number];
+
+export type PressureCurvePreset = 'linear' | 'soft' | 'hard' | 'custom';
+
+export interface PressureCurveSettings {
+ enabled: boolean;
+ preset: PressureCurvePreset;
+ points: PressureCurvePoint[];
+}
+
+export const DEFAULT_MODIFIER_KEY_SETTINGS: ModifierKeySettings = {
+ space: 'pan',
+ shift: 'straight-line',
+ ctrl: 'none',
+ alt: 'eyedropper',
+ ctrlSpace: 'zoom-drag',
+ shiftSpace: 'rotate',
+ ctrlAlt: 'brush-size',
+ shiftAlt: 'brush-size',
+ rightClick: 'eyedropper',
+ middleClick: 'pan',
+ stylusButton1: 'eyedropper',
+ stylusButton2: 'pan',
+ mouseWheel: 'zoom',
+};
+
+export const PRESSURE_CURVE_PRESETS: Record<
+ Exclude<PressureCurvePreset, 'custom'>,
+ PressureCurvePoint[]
+> = {
+ linear: [
+ [0, 0],
+ [1, 1],
+ ],
+ soft: [
+ [0, 0],
+ [0.25, 0.48],
+ [0.6, 0.84],
+ [1, 1],
+ ],
+ hard: [
+ [0, 0],
+ [0.4, 0.16],
+ [0.75, 0.52],
+ [1, 1],
+ ],
+};
+
+export const DEFAULT_PRESSURE_CURVE_SETTINGS: PressureCurveSettings = {
+ enabled: true,
+ preset: 'linear',
+ points: [
+ [0, 0],
+ [1, 1],
+ ],
+};
+
export interface AppSettings {
// User Profile
userName: string;
@@ -101,6 +207,11 @@ export interface AppSettings {
smoothingEnabled: boolean;
maxHistorySteps: number;
+ // Shortcuts, Modifier Keys & Pen Pressure Calibration
+ shortcuts: ShortcutOverrides;
+ modifierKeys: ModifierKeySettings;
+ pressureCurve: PressureCurveSettings;
+
// Performance & Scratch Disk
tileMemoryBudgetMb: number;
}
@@ -129,13 +240,138 @@ export const DEFAULT_APP_SETTINGS: AppSettings = {
smoothingEnabled: true,
maxHistorySteps: 50,
+ shortcuts: {},
+ modifierKeys: { ...DEFAULT_MODIFIER_KEY_SETTINGS },
+ pressureCurve: {
+ ...DEFAULT_PRESSURE_CURVE_SETTINGS,
+ points: DEFAULT_PRESSURE_CURVE_SETTINGS.points.map(([x, y]) => [x, y] as PressureCurvePoint),
+ },
+
tileMemoryBudgetMb: 1024,
};
+const VALID_MODIFIER_ACTIONS = new Set<ModifierAction>([
+ 'none',
+ 'pan',
+ 'rotate',
+ 'zoom-drag',
+ 'eyedropper',
+ 'brush-size',
+ 'straight-line',
+ 'temp-eraser',
+ 'undo',
+ 'swap-colors',
+ 'quick-palette',
+]);
+
+const VALID_MOUSE_WHEEL_ACTIONS = new Set<MouseWheelAction>(['zoom', 'scroll', 'brush-size']);
+
+function sanitizeModifierKeys(raw: unknown): ModifierKeySettings {
+ const result: ModifierKeySettings = { ...DEFAULT_MODIFIER_KEY_SETTINGS };
+ if (!raw || typeof raw !== 'object') return result;
+ const obj = raw as Record<string, unknown>;
+ const slots: ModifierKeySlot[] = [
+ 'space',
+ 'shift',
+ 'ctrl',
+ 'alt',
+ 'ctrlSpace',
+ 'shiftSpace',
+ 'ctrlAlt',
+ 'shiftAlt',
+ 'rightClick',
+ 'middleClick',
+ 'stylusButton1',
+ 'stylusButton2',
+ ];
+ for (const slot of slots) {
+ if (typeof obj[slot] === 'string' && VALID_MODIFIER_ACTIONS.has(obj[slot] as ModifierAction)) {
+ result[slot] = obj[slot] as ModifierAction;
+ }
+ }
+ if (
+ typeof obj.mouseWheel === 'string' &&
+ VALID_MOUSE_WHEEL_ACTIONS.has(obj.mouseWheel as MouseWheelAction)
+ ) {
+ result.mouseWheel = obj.mouseWheel as MouseWheelAction;
+ }
+ return result;
+}
+
+function sanitizeShortcuts(raw: unknown): ShortcutOverrides {
+ const result: ShortcutOverrides = {};
+ if (!raw || typeof raw !== 'object') return result;
+ const obj = raw as Record<string, unknown>;
+ for (const [key, val] of Object.entries(obj)) {
+ if (typeof key === 'string' && typeof val === 'string') {
+ result[key] = val;
+ }
+ }
+ return result;
+}
+
+function sanitizePressureCurve(raw: unknown): PressureCurveSettings {
+ if (!raw || typeof raw !== 'object') {
+ return {
+ ...DEFAULT_PRESSURE_CURVE_SETTINGS,
+ points: DEFAULT_PRESSURE_CURVE_SETTINGS.points.map(([x, y]) => [x, y] as PressureCurvePoint),
+ };
+ }
+ const obj = raw as Record<string, unknown>;
+ const enabled = typeof obj.enabled === 'boolean' ? obj.enabled : true;
+ const preset: PressureCurvePreset =
+ obj.preset === 'linear' ||
+ obj.preset === 'soft' ||
+ obj.preset === 'hard' ||
+ obj.preset === 'custom'
+ ? obj.preset
+ : 'custom';
+ const rawPts = Array.isArray(obj.points) ? obj.points : DEFAULT_PRESSURE_CURVE_SETTINGS.points;
+ const validPts: PressureCurvePoint[] = [];
+ for (const p of rawPts) {
+ if (
+ Array.isArray(p) &&
+ p.length >= 2 &&
+ typeof p[0] === 'number' &&
+ typeof p[1] === 'number' &&
+ Number.isFinite(p[0]) &&
+ Number.isFinite(p[1])
+ ) {
+ validPts.push([
+ Math.max(0, Math.min(1, p[0])),
+ Math.max(0, Math.min(1, p[1])),
+ ]);
+ }
+ }
+ validPts.sort((a, b) => a[0] - b[0]);
+ if (validPts.length < 2) {
+ return {
+ enabled,
+ preset: 'linear',
+ points: [
+ [0, 0],
+ [1, 1],
+ ],
+ };
+ }
+ return { enabled, preset, points: validPts };
+}
+
const SETTINGS_KEY = 'ink_studio_app_settings';
export function loadAppSettings(): AppSettings {
try {
+ if (typeof localStorage === 'undefined' || typeof localStorage.getItem !== 'function') {
+ return {
+ ...DEFAULT_APP_SETTINGS,
+ shortcuts: {},
+ modifierKeys: { ...DEFAULT_MODIFIER_KEY_SETTINGS },
+ pressureCurve: {
+ ...DEFAULT_PRESSURE_CURVE_SETTINGS,
+ points: DEFAULT_PRESSURE_CURVE_SETTINGS.points.map(([x, y]) => [x, y] as PressureCurvePoint),
+ },
+ };
+ }
const raw = localStorage.getItem(SETTINGS_KEY);
const legacyName = localStorage.getItem('sora_paint_nickname') || '';
if (raw) {
@@ -173,22 +409,42 @@ export function loadAppSettings(): AppSettings {
modernCustomColor: validCustomColor,
uiTone: validTone,
tileMemoryBudgetMb: validBudget,
+ shortcuts: sanitizeShortcuts(parsed.shortcuts),
+ modifierKeys: sanitizeModifierKeys(parsed.modifierKeys),
+ pressureCurve: sanitizePressureCurve(parsed.pressureCurve),
};
} else if (legacyName) {
return {
...DEFAULT_APP_SETTINGS,
userName: legacyName,
hasPromptedName: true,
+ shortcuts: {},
+ modifierKeys: { ...DEFAULT_MODIFIER_KEY_SETTINGS },
+ pressureCurve: {
+ ...DEFAULT_PRESSURE_CURVE_SETTINGS,
+ points: DEFAULT_PRESSURE_CURVE_SETTINGS.points.map(([x, y]) => [x, y] as PressureCurvePoint),
+ },
};
}
} catch (err) {
console.warn('Failed to load settings from localStorage:', err);
}
- return { ...DEFAULT_APP_SETTINGS };
+ return {
+ ...DEFAULT_APP_SETTINGS,
+ shortcuts: {},
+ modifierKeys: { ...DEFAULT_MODIFIER_KEY_SETTINGS },
+ pressureCurve: {
+ ...DEFAULT_PRESSURE_CURVE_SETTINGS,
+ points: DEFAULT_PRESSURE_CURVE_SETTINGS.points.map(([x, y]) => [x, y] as PressureCurvePoint),
+ },
+ };
}
export function saveAppSettings(settings: AppSettings): void {
try {
+ if (typeof localStorage === 'undefined' || typeof localStorage.setItem !== 'function') {
+ return;
+ }
localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
} catch (err) {
console.warn('Failed to save settings to localStorage:', err);
diff --git a/src/utils/__tests__/pressureCurve.test.ts b/src/utils/__tests__/pressureCurve.test.ts
new file mode 100644
index 0000000..e6b8a8d
--- /dev/null
+++ b/src/utils/__tests__/pressureCurve.test.ts
@@ -0,0 +1,169 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ calculatePressureOpacity,
+ createPressureCurvePreset,
+ evaluateGlobalPressureCurve,
+ isLinearPressureCurve,
+ samplePressureCurve,
+ sanitizePressureCurvePoints,
+} from '../pressureCurve';
+import { calculateStrokeWidth } from '../canvasUtils';
+import { POINTER_TYPE_PEN, StrokePipeline } from '../../engine/StrokePipeline';
+import {
+ DEFAULT_APP_SETTINGS,
+ PressureCurveSettings,
+ loadAppSettings,
+ saveAppSettings,
+} from '../../types/settings';
+
+describe('Global Pen Pressure Curve Interpolation', () => {
+ beforeEach(() => {
+ const storage: Record<string, string> = {};
+ (globalThis as any).localStorage = {
+ getItem: (k: string) => storage[k] ?? null,
+ setItem: (k: string, v: string) => {
+ storage[k] = String(v);
+ },
+ removeItem: (k: string) => {
+ delete storage[k];
+ },
+ clear: () => {
+ Object.keys(storage).forEach((k) => delete storage[k]);
+ },
+ };
+ });
+
+ it('sanitizes control points by clamping, sorting, deduplicating, and pinning endpoints', () => {
+ const clean = sanitizePressureCurvePoints([
+ [0.8, 1.5],
+ [0.2, -0.2],
+ [0.205, 0.4],
+ [0.5, 0.6],
+ ]);
+ expect(clean[0][0]).toBe(0);
+ expect(clean[clean.length - 1][0]).toBe(1);
+ for (let i = 1; i < clean.length; i++) {
+ expect(clean[i][0]).toBeGreaterThan(clean[i - 1][0]);
+ }
+ for (const [x, y] of clean) {
+ expect(x).toBeGreaterThanOrEqual(0);
+ expect(x).toBeLessThanOrEqual(1);
+ expect(y).toBeGreaterThanOrEqual(0);
+ expect(y).toBeLessThanOrEqual(1);
+ }
+ });
+
+ it('evaluates Linear, Soft, and Hard presets monotonically within [0, 1]', () => {
+ const linear = createPressureCurvePreset('linear');
+ const soft = createPressureCurvePreset('soft');
+ const hard = createPressureCurvePreset('hard');
+
+ expect(isLinearPressureCurve(linear.points)).toBe(true);
+ expect(isLinearPressureCurve(soft.points)).toBe(false);
+ expect(isLinearPressureCurve(hard.points)).toBe(false);
+
+ // Mid-pressure comparison: Soft > Linear > Hard
+ const midSoft = evaluateGlobalPressureCurve(0.4, soft);
+ const midLinear = evaluateGlobalPressureCurve(0.4, linear);
+ const midHard = evaluateGlobalPressureCurve(0.4, hard);
+
+ expect(midLinear).toBeCloseTo(0.4, 4);
+ expect(midSoft).toBeGreaterThan(midLinear + 0.15);
+ expect(midHard).toBeLessThan(midLinear - 0.15);
+
+ // Monotonicity & bounds check across all presets
+ for (const curve of [linear, soft, hard]) {
+ const samples = samplePressureCurve(curve, 50);
+ expect(samples[0][1]).toBeCloseTo(0, 3);
+ expect(samples[samples.length - 1][1]).toBeCloseTo(1, 3);
+ for (let i = 1; i < samples.length; i++) {
+ expect(samples[i][1]).toBeGreaterThanOrEqual(samples[i - 1][1] - 1e-4);
+ expect(samples[i][1]).toBeLessThanOrEqual(1);
+ }
+ }
+ });
+
+ it('bypasses custom points when curve is disabled', () => {
+ const disabledSoft: PressureCurveSettings = {
+ ...createPressureCurvePreset('soft'),
+ enabled: false,
+ };
+ expect(evaluateGlobalPressureCurve(0.35, disabledSoft)).toBeCloseTo(0.35, 5);
+ });
+
+ it('alters both stroke thickness and opacity across Soft, Linear, and Hard curves', () => {
+ const soft = createPressureCurvePreset('soft');
+ const linear = createPressureCurvePreset('linear');
+ const hard = createPressureCurvePreset('hard');
+
+ const rawP = 0.4;
+ const pSoft = evaluateGlobalPressureCurve(rawP, soft);
+ const pLinear = evaluateGlobalPressureCurve(rawP, linear);
+ const pHard = evaluateGlobalPressureCurve(rawP, hard);
+
+ const wSoft = calculateStrokeWidth(40, pSoft, 0.1, true, 'pen');
+ const wLinear = calculateStrokeWidth(40, pLinear, 0.1, true, 'pen');
+ const wHard = calculateStrokeWidth(40, pHard, 0.1, true, 'pen');
+
+ expect(wSoft).toBeGreaterThan(wLinear);
+ expect(wLinear).toBeGreaterThan(wHard);
+
+ const opSoft = calculatePressureOpacity(1.0, rawP, true, 0.1, soft);
+ const opLinear = calculatePressureOpacity(1.0, rawP, true, 0.1, linear);
+ const opHard = calculatePressureOpacity(1.0, rawP, true, 0.1, hard);
+
+ expect(opSoft).toBeGreaterThan(opLinear);
+ expect(opLinear).toBeGreaterThan(opHard);
+ });
+
+ it('applies configured global pressure curve inside StrokePipeline to alter thickness and opacity', () => {
+ const runPipelineWithCurve = (curve: PressureCurveSettings) => {
+ const pipeline = new StrokePipeline();
+ pipeline.beginStroke({
+ stabilizerLevel: 0,
+ brushSize: 30,
+ globalPressureCurve: curve,
+ });
+ pipeline.enqueueSample(10, 10, 0.35, 0, 0, 0, 100, POINTER_TYPE_PEN);
+ pipeline.enqueueSample(25, 10, 0.35, 0, 0, 0, 116, POINTER_TYPE_PEN);
+ pipeline.enqueueSample(40, 10, 0.35, 0, 0, 0, 132, POINTER_TYPE_PEN);
+
+ let lastSample = { pressure: 0, width: 0, opacity: 0 };
+ pipeline.drain({
+ onPoint: (pt) => {
+ lastSample = { pressure: pt.pressure, width: pt.width, opacity: pt.opacity };
+ },
+ });
+ return lastSample;
+ };
+
+ const softOut = runPipelineWithCurve(createPressureCurvePreset('soft'));
+ const linearOut = runPipelineWithCurve(createPressureCurvePreset('linear'));
+ const hardOut = runPipelineWithCurve(createPressureCurvePreset('hard'));
+
+ expect(softOut.pressure).toBeGreaterThan(linearOut.pressure);
+ expect(linearOut.pressure).toBeGreaterThan(hardOut.pressure);
+
+ expect(softOut.width).toBeGreaterThan(linearOut.width);
+ expect(linearOut.width).toBeGreaterThan(hardOut.width);
+
+ expect(softOut.opacity).toBeGreaterThan(linearOut.opacity);
+ expect(linearOut.opacity).toBeGreaterThan(hardOut.opacity);
+ });
+
+ it('persists custom pressure curve points in AppSettings', () => {
+ const customCurve: PressureCurveSettings = {
+ enabled: true,
+ preset: 'custom',
+ points: [
+ [0, 0.05],
+ [0.3, 0.6],
+ [0.7, 0.9],
+ [1, 1],
+ ],
+ };
+ saveAppSettings({ ...DEFAULT_APP_SETTINGS, pressureCurve: customCurve });
+ const loaded = loadAppSettings();
+ expect(loaded.pressureCurve).toEqual(customCurve);
+ });
+});
diff --git a/src/utils/__tests__/shortcutManager.test.ts b/src/utils/__tests__/shortcutManager.test.ts
new file mode 100644
index 0000000..e9fea4a
--- /dev/null
+++ b/src/utils/__tests__/shortcutManager.test.ts
@@ -0,0 +1,318 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import {
+ DEFAULT_COMMANDS,
+ SPRING_LOADED_HOLD_MS,
+ ShortcutManager,
+ SpringLoadedToolController,
+ findShortcutConflicts,
+ formatShortcutFromEvent,
+ formatShortcutLabel,
+ matchesKeyboardEvent,
+ normalizeShortcut,
+ parseShortcut,
+ resolveHeldKeyModifierAction,
+ resolvePointerModifierAction,
+} from '../shortcutManager';
+import {
+ DEFAULT_APP_SETTINGS,
+ DEFAULT_MODIFIER_KEY_SETTINGS,
+ loadAppSettings,
+ saveAppSettings,
+} from '../../types/settings';
+
+describe('Shortcut Parsing, Normalization & Matching', () => {
+ it('parses and normalizes standard, modifier, and punctuation shortcuts', () => {
+ expect(normalizeShortcut('ctrl + z')).toBe('Ctrl+Z');
+ expect(normalizeShortcut('CMD+SHIFT+s')).toBe('Ctrl+Shift+S');
+ expect(normalizeShortcut('alt + c')).toBe('Alt+C');
+ expect(normalizeShortcut('ctrl + ,')).toBe('Ctrl+,');
+ expect(normalizeShortcut('[')).toBe('[');
+ expect(normalizeShortcut(']')).toBe(']');
+ expect(normalizeShortcut('ctrl + +')).toBe('Ctrl+=');
+ expect(normalizeShortcut('del')).toBe('Delete');
+ expect(normalizeShortcut('Control')).toBe('');
+
+ expect(formatShortcutLabel('Ctrl+Shift+S')).toBe('Ctrl + Shift + S');
+ expect(formatShortcutLabel('')).toBe('Unassigned');
+
+ const parsed = parseShortcut('Ctrl+Alt+0');
+ expect(parsed).toMatchObject({
+ ctrl: true,
+ shift: false,
+ alt: true,
+ key: '0',
+ code: 'Digit0',
+ });
+ });
+
+ it('matches KeyboardEvents layout-independently via e.code and numpad aliases', () => {
+ // Cyrillic layout pressing physical Z key with Ctrl
+ expect(
+ matchesKeyboardEvent({ key: 'я', code: 'KeyZ', ctrlKey: true }, 'Ctrl+Z')
+ ).toBe(true);
+
+ // Rejects extra modifiers
+ expect(
+ matchesKeyboardEvent({ key: 'z', code: 'KeyZ', ctrlKey: true, shiftKey: true }, 'Ctrl+Z')
+ ).toBe(false);
+
+ // Numpad aliases for zoom & reset
+ expect(
+ matchesKeyboardEvent({ key: '0', code: 'Numpad0', ctrlKey: true }, 'Ctrl+0')
+ ).toBe(true);
+ expect(
+ matchesKeyboardEvent({ key: '+', code: 'NumpadAdd', ctrlKey: true }, 'Ctrl+=')
+ ).toBe(true);
+ expect(
+ matchesKeyboardEvent({ key: '-', code: 'NumpadSubtract', ctrlKey: true }, 'Ctrl+-')
+ ).toBe(true);
+
+ // Brackets & comma
+ expect(matchesKeyboardEvent({ key: '[', code: 'BracketLeft' }, '[')).toBe(true);
+ expect(
+ matchesKeyboardEvent({ key: ',', code: 'Comma', ctrlKey: true }, 'Ctrl+,')
+ ).toBe(true);
+ });
+
+ it('captures live KeyboardEvents for recording UI and ignores bare modifiers', () => {
+ expect(formatShortcutFromEvent({ key: 'Control', code: 'ControlLeft', ctrlKey: true })).toBeNull();
+ expect(formatShortcutFromEvent({ key: 'Shift', code: 'ShiftLeft', shiftKey: true })).toBeNull();
+ expect(formatShortcutFromEvent({ key: 'Alt', code: 'AltLeft', altKey: true })).toBeNull();
+
+ expect(
+ formatShortcutFromEvent({ key: 'q', code: 'KeyQ', ctrlKey: true, shiftKey: true })
+ ).toBe('Ctrl+Shift+Q');
+ expect(formatShortcutFromEvent({ key: 'e', code: 'KeyE' })).toBe('E');
+ });
+});
+
+describe('Command Registry, Remapping, Conflict Detection & Persistence', () => {
+ beforeEach(() => {
+ const storage: Record<string, string> = {};
+ (globalThis as any).localStorage = {
+ getItem: (k: string) => storage[k] ?? null,
+ setItem: (k: string, v: string) => {
+ storage[k] = String(v);
+ },
+ removeItem: (k: string) => {
+ delete storage[k];
+ },
+ clear: () => {
+ Object.keys(storage).forEach((k) => delete storage[k]);
+ },
+ };
+ });
+
+ it('covers all 5 required categories and dispatches remapped commands immediately', () => {
+ const categories = new Set(DEFAULT_COMMANDS.map((c) => c.category));
+ expect(categories.has('Tools')).toBe(true);
+ expect(categories.has('Menu')).toBe(true);
+ expect(categories.has('Canvas View')).toBe(true);
+ expect(categories.has('Layer')).toBe(true);
+ expect(categories.has('Edit')).toBe(true);
+
+ const mgr = new ShortcutManager(DEFAULT_COMMANDS);
+ let undoCount = 0;
+ mgr.registerHandler('edit.undo', () => {
+ undoCount++;
+ });
+
+ // Default Ctrl+Z works
+ const defMatch = mgr.matchEvent({ key: 'z', code: 'KeyZ', ctrlKey: true });
+ expect(defMatch?.id).toBe('edit.undo');
+ expect(mgr.executeCommand(defMatch!.id)).toBe(true);
+ expect(undoCount).toBe(1);
+
+ // Remap immediately to Alt+Z without reload
+ mgr.setOverrides({ 'edit.undo': 'Alt+Z' });
+ expect(mgr.matchEvent({ key: 'z', code: 'KeyZ', ctrlKey: true })).toBeNull();
+ const remappedMatch = mgr.matchEvent({ key: 'z', code: 'KeyZ', altKey: true });
+ expect(remappedMatch?.id).toBe('edit.undo');
+ expect(mgr.executeCommand(remappedMatch!.id)).toBe(true);
+ expect(undoCount).toBe(2);
+ });
+
+ it('detects conflicts accurately against defaults and user overrides', () => {
+ const conflicts = findShortcutConflicts('tool.brush', 'E', {});
+ expect(conflicts.map((c) => c.id)).toEqual(['tool.eraser']);
+
+ // Rebinding eraser away clears conflict on E
+ const afterRebind = findShortcutConflicts('tool.brush', 'E', { 'tool.eraser': 'Q' });
+ expect(afterRebind).toHaveLength(0);
+
+ // Conflict against overridden key Q is detected
+ const conflictOnQ = findShortcutConflicts('tool.brush', 'Q', { 'tool.eraser': 'Q' });
+ expect(conflictOnQ.map((c) => c.id)).toEqual(['tool.eraser']);
+ });
+
+ it('persists remapped shortcuts and modifier keys in AppSettings', () => {
+ saveAppSettings({
+ ...DEFAULT_APP_SETTINGS,
+ shortcuts: { 'tool.eraser': 'Q', 'edit.undo': 'Alt+Z' },
+ modifierKeys: {
+ ...DEFAULT_MODIFIER_KEY_SETTINGS,
+ rightClick: 'quick-palette',
+ mouseWheel: 'brush-size',
+ stylusButton1: 'temp-eraser',
+ },
+ });
+
+ const loaded = loadAppSettings();
+ expect(loaded.shortcuts).toEqual({ 'tool.eraser': 'Q', 'edit.undo': 'Alt+Z' });
+ expect(loaded.modifierKeys.rightClick).toBe('quick-palette');
+ expect(loaded.modifierKeys.mouseWheel).toBe('brush-size');
+ expect(loaded.modifierKeys.stylusButton1).toBe('temp-eraser');
+ });
+});
+
+describe('Spring-Loaded Tool Switching (> 250ms hold-and-revert)', () => {
+ it('switches permanently on quick tap (< 250ms) when unused', () => {
+ let clock = 1000;
+ const ctrl = new SpringLoadedToolController(SPRING_LOADED_HOLD_MS, () => clock);
+
+ const activated = ctrl.handleToolKeyDown('KeyE', 'eraser', 'brush');
+ expect(activated).toBe('eraser');
+
+ clock += 120; // quick tap < 250ms
+ const restored = ctrl.handleKeyUp('KeyE', 'eraser');
+ expect(restored).toBeNull();
+ });
+
+ it('reverts to previous tool on keyup when held longer than 250ms', () => {
+ let clock = 1000;
+ const ctrl = new SpringLoadedToolController(SPRING_LOADED_HOLD_MS, () => clock);
+
+ expect(ctrl.handleToolKeyDown('KeyE', 'eraser', 'brush')).toBe('eraser');
+
+ clock += 260; // > 250ms hold
+ const restored = ctrl.handleKeyUp('KeyE', 'eraser');
+ expect(restored).toBe('brush');
+ });
+
+ it('reverts to previous tool on keyup when pointer was used while held even if < 250ms', () => {
+ let clock = 1000;
+ const ctrl = new SpringLoadedToolController(SPRING_LOADED_HOLD_MS, () => clock);
+
+ expect(ctrl.handleToolKeyDown('KeyI', 'pipette', 'brush')).toBe('pipette');
+ ctrl.markUsedWhileHeld();
+
+ clock += 100;
+ expect(ctrl.handleKeyUp('KeyI', 'pipette')).toBe('brush');
+ });
+
+ it('does not revert if current tool changed to something else before release', () => {
+ let clock = 1000;
+ const ctrl = new SpringLoadedToolController(SPRING_LOADED_HOLD_MS, () => clock);
+
+ expect(ctrl.handleToolKeyDown('KeyE', 'eraser', 'brush')).toBe('eraser');
+ clock += 400;
+ expect(ctrl.handleKeyUp('KeyE', 'fill')).toBeNull();
+ });
+
+ it('supports remapped tool keys seamlessly via physical key code', () => {
+ let clock = 5000;
+ const ctrl = new SpringLoadedToolController(SPRING_LOADED_HOLD_MS, () => clock);
+
+ expect(ctrl.handleToolKeyDown('KeyQ', 'eraser', 'brush')).toBe('eraser');
+ clock += 300;
+ expect(ctrl.handleKeyUp('KeyQ', 'eraser')).toBe('brush');
+ });
+});
+
+describe('Modifier Key Resolution', () => {
+ it('resolves default CSP modifier mappings including Ctrl+Alt and Shift+Alt brush resize', () => {
+ const base = {
+ button: 0,
+ pointerType: 'mouse',
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ altKey: false,
+ isSpaceDown: false,
+ };
+
+ expect(
+ resolvePointerModifierAction({ ...base, ctrlKey: true, altKey: true })
+ ).toEqual({ slot: 'ctrlAlt', action: 'brush-size' });
+
+ expect(
+ resolvePointerModifierAction({ ...base, shiftKey: true, altKey: true })
+ ).toEqual({ slot: 'shiftAlt', action: 'brush-size' });
+
+ expect(
+ resolvePointerModifierAction({ ...base, ctrlKey: true, isSpaceDown: true })
+ ).toEqual({ slot: 'ctrlSpace', action: 'zoom-drag' });
+
+ expect(
+ resolvePointerModifierAction({ ...base, shiftKey: true, isSpaceDown: true })
+ ).toEqual({ slot: 'shiftSpace', action: 'rotate' });
+
+ expect(resolvePointerModifierAction({ ...base, isSpaceDown: true })).toEqual({
+ slot: 'space',
+ action: 'pan',
+ });
+
+ expect(resolvePointerModifierAction({ ...base, button: 2 })).toEqual({
+ slot: 'rightClick',
+ action: 'eyedropper',
+ });
+
+ expect(resolvePointerModifierAction({ ...base, button: 1 })).toEqual({
+ slot: 'middleClick',
+ action: 'pan',
+ });
+
+ expect(resolvePointerModifierAction({ ...base, pointerType: 'pen', button: 2 })).toEqual({
+ slot: 'stylusButton1',
+ action: 'eyedropper',
+ });
+
+ expect(resolvePointerModifierAction({ ...base, pointerType: 'pen', button: 5 })).toEqual({
+ slot: 'stylusButton2',
+ action: 'pan',
+ });
+ });
+
+ it('respects remapped modifier actions for pointer and held-key states', () => {
+ const custom = {
+ ...DEFAULT_MODIFIER_KEY_SETTINGS,
+ rightClick: 'quick-palette' as const,
+ space: 'rotate' as const,
+ stylusButton1: 'brush-size' as const,
+ };
+
+ expect(
+ resolvePointerModifierAction(
+ {
+ button: 2,
+ pointerType: 'mouse',
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ altKey: false,
+ isSpaceDown: false,
+ },
+ custom
+ )
+ ).toEqual({ slot: 'rightClick', action: 'quick-palette' });
+
+ expect(
+ resolvePointerModifierAction(
+ {
+ button: 2,
+ pointerType: 'pen',
+ ctrlKey: false,
+ metaKey: false,
+ shiftKey: false,
+ altKey: false,
+ isSpaceDown: false,
+ },
+ custom
+ )
+ ).toEqual({ slot: 'stylusButton1', action: 'brush-size' });
+
+ expect(
+ resolveHeldKeyModifierAction({ ctrl: false, shift: false, alt: false, space: true }, custom)
+ ).toBe('rotate');
+ });
+});
diff --git a/src/utils/pressureCurve.ts b/src/utils/pressureCurve.ts
new file mode 100644
index 0000000..b41738c
--- /dev/null
+++ b/src/utils/pressureCurve.ts
@@ -0,0 +1,159 @@
+import {
+ PRESSURE_CURVE_PRESETS,
+ PressureCurvePoint,
+ PressureCurvePreset,
+ PressureCurveSettings,
+} from '../types/settings';
+import { evaluateFastSpline } from '../engine/CspBrushEngine';
+
+export { PRESSURE_CURVE_PRESETS };
+
+const MIN_POINT_SPACING_X = 0.02;
+
+/**
+ * Clamps, sorts, and deduplicates pressure curve control points while pinning endpoints at x=0 and x=1.
+ */
+export function sanitizePressureCurvePoints(
+ points: readonly PressureCurvePoint[]
+): PressureCurvePoint[] {
+ if (!points || points.length < 2) {
+ return [
+ [0, 0],
+ [1, 1],
+ ];
+ }
+
+ const clamped: PressureCurvePoint[] = points
+ .filter(
+ (p) =>
+ Array.isArray(p) &&
+ p.length >= 2 &&
+ Number.isFinite(p[0]) &&
+ Number.isFinite(p[1])
+ )
+ .map(([x, y]) => [
+ Math.max(0, Math.min(1, x)),
+ Math.max(0, Math.min(1, y)),
+ ]);
+
+ if (clamped.length < 2) {
+ return [
+ [0, 0],
+ [1, 1],
+ ];
+ }
+
+ clamped.sort((a, b) => a[0] - b[0]);
+
+ const dedup: PressureCurvePoint[] = [clamped[0]];
+ for (let i = 1; i < clamped.length; i++) {
+ const prev = dedup[dedup.length - 1];
+ if (clamped[i][0] - prev[0] >= MIN_POINT_SPACING_X) {
+ dedup.push(clamped[i]);
+ } else if (i === clamped.length - 1) {
+ dedup[dedup.length - 1] = clamped[i];
+ }
+ }
+
+ if (dedup.length < 2) {
+ return [
+ [0, dedup[0][1]],
+ [1, dedup[0][1]],
+ ];
+ }
+
+ // Ensure endpoints span [0, 1]
+ if (dedup[0][0] > 0.001) {
+ dedup.unshift([0, dedup[0][1]]);
+ } else {
+ dedup[0] = [0, dedup[0][1]];
+ }
+ const lastIdx = dedup.length - 1;
+ if (dedup[lastIdx][0] < 0.999) {
+ dedup.push([1, dedup[lastIdx][1]]);
+ } else {
+ dedup[lastIdx] = [1, dedup[lastIdx][1]];
+ }
+
+ return dedup;
+}
+
+/**
+ * Fast identity check to avoid unnecessary LUT lookups on default linear curve.
+ */
+export function isLinearPressureCurve(points?: readonly PressureCurvePoint[] | null): boolean {
+ if (!points || points.length < 2) return true;
+ if (points.length !== 2) return false;
+ return (
+ Math.abs(points[0][0]) < 1e-4 &&
+ Math.abs(points[0][1]) < 1e-4 &&
+ Math.abs(points[1][0] - 1) < 1e-4 &&
+ Math.abs(points[1][1] - 1) < 1e-4
+ );
+}
+
+/**
+ * Evaluates the global stylus pressure curve in O(1) via precompiled 256-entry PCHIP spline LUT.
+ * Input & output are clamped to [0, 1].
+ */
+export function evaluateGlobalPressureCurve(
+ rawPressure: number,
+ settings?: PressureCurveSettings | null
+): number {
+ if (!Number.isFinite(rawPressure) || rawPressure <= 0) return 0;
+ const clamped = rawPressure >= 1 ? 1 : rawPressure;
+ if (!settings || !settings.enabled || isLinearPressureCurve(settings.points)) {
+ return clamped;
+ }
+ return evaluateFastSpline(clamped, settings.points);
+}
+
+/**
+ * Samples the curve into N+1 points for SVG/Canvas plotting.
+ */
+export function samplePressureCurve(
+ settings?: PressureCurveSettings | null,
+ steps: number = 64
+): PressureCurvePoint[] {
+ const n = Math.max(2, Math.floor(steps));
+ const out: PressureCurvePoint[] = new Array(n + 1);
+ for (let i = 0; i <= n; i++) {
+ const x = i / n;
+ out[i] = [x, evaluateGlobalPressureCurve(x, settings)];
+ }
+ return out;
+}
+
+/**
+ * Creates a fresh preset PressureCurveSettings object.
+ */
+export function createPressureCurvePreset(
+ preset: Exclude<PressureCurvePreset, 'custom'>,
+ enabled: boolean = true
+): PressureCurveSettings {
+ const pts = PRESSURE_CURVE_PRESETS[preset];
+ return {
+ enabled,
+ preset,
+ points: pts.map(([x, y]) => [x, y] as PressureCurvePoint),
+ };
+}
+
+/**
+ * Computes effective stroke/dab opacity modulated by pressure and optional global pressure curve.
+ */
+export function calculatePressureOpacity(
+ baseOpacity: number,
+ pressure: number,
+ usePressure: boolean,
+ minOpacityFactor: number = 0.0,
+ globalCurve?: PressureCurveSettings | null
+): number {
+ const safeBase = Math.max(0, Math.min(1, Number.isFinite(baseOpacity) ? baseOpacity : 1));
+ if (!usePressure) return safeBase;
+ const p = globalCurve
+ ? evaluateGlobalPressureCurve(pressure, globalCurve)
+ : Math.max(0, Math.min(1, Number.isFinite(pressure) ? pressure : 0));
+ const minFloor = Math.max(0, Math.min(1, minOpacityFactor));
+ return Math.max(0, Math.min(1, safeBase * (minFloor + (1 - minFloor) * p)));
+}
diff --git a/src/utils/shortcutManager.ts b/src/utils/shortcutManager.ts
new file mode 100644
index 0000000..c7cc22b
--- /dev/null
+++ b/src/utils/shortcutManager.ts
@@ -0,0 +1,1065 @@
+import { ToolType } from '../types/editor';
+import {
+ DEFAULT_MODIFIER_KEY_SETTINGS,
+ ModifierAction,
+ ModifierKeySettings,
+ ModifierKeySlot,
+ ShortcutCategory,
+ ShortcutOverrides,
+} from '../types/settings';
+
+export const SPRING_LOADED_HOLD_MS = 250;
+
+export interface CommandDefinition {
+ id: string;
+ label: string;
+ description: string;
+ category: ShortcutCategory;
+ defaultShortcut: string;
+ /** Optional secondary default shortcut (only active when user has not overridden this command) */
+ altDefaultShortcut?: string;
+ /** Tool selected by this command (enables spring-loaded hold-to-revert) */
+ toolId?: ToolType;
+ /** Whether holding the key (> 250ms or used while held) reverts on keyup */
+ springLoaded?: boolean;
+ /** Runtime handler */
+ handler?: () => void;
+}
+
+export interface ParsedShortcut {
+ ctrl: boolean;
+ shift: boolean;
+ alt: boolean;
+ /** Canonical display key token (e.g. 'Z', '[', '0', 'Delete', 'Tab', ',') */
+ key: string;
+ /** Primary KeyboardEvent.code (e.g. 'KeyZ', 'BracketLeft', 'Digit0', 'Delete') */
+ code: string;
+ /** Optional alternate codes (e.g. 'Numpad0' for 'Digit0', 'NumpadAdd' for 'Equal') */
+ altCodes?: readonly string[];
+}
+
+export interface KeyboardEventLike {
+ key: string;
+ code?: string;
+ ctrlKey?: boolean;
+ metaKey?: boolean;
+ shiftKey?: boolean;
+ altKey?: boolean;
+ repeat?: boolean;
+}
+
+export const SHORTCUT_CATEGORIES: readonly ShortcutCategory[] = [
+ 'Tools',
+ 'Menu',
+ 'Canvas View',
+ 'Layer',
+ 'Edit',
+];
+
+export const DEFAULT_COMMANDS: readonly CommandDefinition[] = [
+ // --- Tools (spring-loaded where toolId is set) ---
+ {
+ id: 'tool.brush',
+ label: 'Brush Tool',
+ description: 'Switch to brush (hold > 250ms for temporary switch)',
+ category: 'Tools',
+ defaultShortcut: 'B',
+ toolId: 'brush',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.eraser',
+ label: 'Eraser Tool',
+ description: 'Switch to eraser (hold > 250ms for temporary switch)',
+ category: 'Tools',
+ defaultShortcut: 'E',
+ toolId: 'eraser',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.pipette',
+ label: 'Eyedropper Tool',
+ description: 'Sample color from canvas (hold > 250ms for temporary switch)',
+ category: 'Tools',
+ defaultShortcut: 'I',
+ toolId: 'pipette',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.liquify',
+ label: 'Liquify Tool',
+ description: 'Warp pixels with liquify brush',
+ category: 'Tools',
+ defaultShortcut: 'J',
+ toolId: 'liquify',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.selectRect',
+ label: 'Rectangle Selection',
+ description: 'Rectangular marquee selection',
+ category: 'Tools',
+ defaultShortcut: 'M',
+ toolId: 'select-rect',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.selectLasso',
+ label: 'Lasso Selection',
+ description: 'Freehand lasso selection',
+ category: 'Tools',
+ defaultShortcut: 'L',
+ toolId: 'select-lasso',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.selectWand',
+ label: 'Magic Wand',
+ description: 'Contiguous color area selection',
+ category: 'Tools',
+ defaultShortcut: 'W',
+ toolId: 'select-wand',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.fill',
+ label: 'Fill Bucket',
+ description: 'Flood fill enclosed regions',
+ category: 'Tools',
+ defaultShortcut: 'G',
+ toolId: 'fill',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.text',
+ label: 'Text Tool',
+ description: 'Place and edit manga typography',
+ category: 'Tools',
+ defaultShortcut: 'T',
+ toolId: 'text',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.frame',
+ label: 'Manga Frame Tool',
+ description: 'Create panel borders',
+ category: 'Tools',
+ defaultShortcut: 'F',
+ toolId: 'frame',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.balloon',
+ label: 'Speech Balloon',
+ description: 'Draw parametric speech balloons',
+ category: 'Tools',
+ defaultShortcut: 'O',
+ toolId: 'balloon',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.vectorEdit',
+ label: 'Vector Edit Tool',
+ description: 'Pinch, simplify, and adjust vector strokes',
+ category: 'Tools',
+ defaultShortcut: 'Y',
+ toolId: 'vector-edit',
+ springLoaded: true,
+ },
+ {
+ id: 'tool.brushSizeDown',
+ label: 'Decrease Brush Size',
+ description: 'Step brush diameter down',
+ category: 'Tools',
+ defaultShortcut: '[',
+ },
+ {
+ id: 'tool.brushSizeUp',
+ label: 'Increase Brush Size',
+ description: 'Step brush diameter up',
+ category: 'Tools',
+ defaultShortcut: ']',
+ },
+ {
+ id: 'color.swap',
+ label: 'Swap Colors',
+ description: 'Swap primary and secondary colors',
+ category: 'Tools',
+ defaultShortcut: 'X',
+ },
+ {
+ id: 'color.reset',
+ label: 'Default Colors',
+ description: 'Reset primary/secondary colors to black & white',
+ category: 'Tools',
+ defaultShortcut: 'D',
+ },
+ {
+ id: 'color.transparent',
+ label: 'Transparent Ink Mode',
+ description: 'Toggle drawing with transparent color',
+ category: 'Tools',
+ defaultShortcut: 'C',
+ },
+
+ // --- Menu ---
+ {
+ id: 'file.new',
+ label: 'New Canvas',
+ description: 'Create a new document',
+ category: 'Menu',
+ defaultShortcut: 'Ctrl+N',
+ },
+ {
+ id: 'file.open',
+ label: 'Open File',
+ description: 'Open image, PSD, or CSP file',
+ category: 'Menu',
+ defaultShortcut: 'Ctrl+O',
+ },
+ {
+ id: 'file.save',
+ label: 'Save',
+ description: 'Save active document',
+ category: 'Menu',
+ defaultShortcut: 'Ctrl+S',
+ },
+ {
+ id: 'file.saveAs',
+ label: 'Save As',
+ description: 'Save document to a new file',
+ category: 'Menu',
+ defaultShortcut: 'Ctrl+Shift+S',
+ },
+ {
+ id: 'app.preferences',
+ label: 'Preferences',
+ description: 'Open application preferences',
+ category: 'Menu',
+ defaultShortcut: 'Ctrl+,',
+ },
+ {
+ id: 'view.togglePalettes',
+ label: 'Toggle Palettes',
+ description: 'Show or hide docked UI palettes',
+ category: 'Menu',
+ defaultShortcut: 'Tab',
+ },
+ {
+ id: 'view.toggleLeftPanel',
+ label: 'Toggle Left Panel',
+ description: 'Show or hide the left tool panel',
+ category: 'Menu',
+ defaultShortcut: 'Shift+Tab',
+ },
+ {
+ id: 'view.softProof',
+ label: 'Toggle Soft Proof',
+ description: 'Preview CMYK/print soft proofing',
+ category: 'Menu',
+ defaultShortcut: 'Ctrl+Alt+Y',
+ },
+ {
+ id: 'view.gamutWarning',
+ label: 'Toggle Gamut Warning',
+ description: 'Highlight out-of-gamut colors',
+ category: 'Menu',
+ defaultShortcut: 'Ctrl+Shift+Y',
+ },
+ {
+ id: 'anim.toggleTimeline',
+ label: 'Toggle Animation Timeline',
+ description: 'Show or hide frame animation timeline',
+ category: 'Menu',
+ defaultShortcut: 'Ctrl+Alt+A',
+ },
+ {
+ id: 'anim.addCel',
+ label: 'Add Animation Cel',
+ description: 'Insert a new animation cel at current frame',
+ category: 'Menu',
+ defaultShortcut: 'Alt+C',
+ },
+
+ // --- Canvas View ---
+ {
+ id: 'view.zoomIn',
+ label: 'Zoom In',
+ description: 'Increase canvas magnification',
+ category: 'Canvas View',
+ defaultShortcut: 'Ctrl+=',
+ },
+ {
+ id: 'view.zoomOut',
+ label: 'Zoom Out',
+ description: 'Decrease canvas magnification',
+ category: 'Canvas View',
+ defaultShortcut: 'Ctrl+-',
+ },
+ {
+ id: 'view.resetZoom',
+ label: 'Reset Zoom & Fit',
+ description: 'Fit and center canvas in viewport',
+ category: 'Canvas View',
+ defaultShortcut: 'Ctrl+0',
+ },
+ {
+ id: 'view.resetRotation',
+ label: 'Reset Rotation',
+ description: 'Reset canvas angle to 0 deg',
+ category: 'Canvas View',
+ defaultShortcut: 'Ctrl+Alt+0',
+ },
+ {
+ id: 'view.flipHorizontal',
+ label: 'Flip View Horizontally',
+ description: 'Non-destructive horizontal canvas mirror',
+ category: 'Canvas View',
+ defaultShortcut: 'Shift+H',
+ },
+ {
+ id: 'view.flipVertical',
+ label: 'Flip View Vertically',
+ description: 'Non-destructive vertical canvas mirror',
+ category: 'Canvas View',
+ defaultShortcut: 'Shift+V',
+ },
+ {
+ id: 'view.perspectiveRuler',
+ label: 'Toggle Perspective Ruler',
+ description: 'Add or toggle 2-point perspective ruler',
+ category: 'Canvas View',
+ defaultShortcut: 'Ctrl+Shift+R',
+ },
+ {
+ id: 'view.perspectiveSnap',
+ label: 'Toggle Perspective Snapping',
+ description: 'Enable or disable brush snapping to perspective guides',
+ category: 'Canvas View',
+ defaultShortcut: 'Ctrl+Shift+P',
+ },
+
+ // --- Layer ---
+ {
+ id: 'layer.newRaster',
+ label: 'New Raster Layer',
+ description: 'Add transparent raster layer',
+ category: 'Layer',
+ defaultShortcut: 'Ctrl+Shift+N',
+ },
+ {
+ id: 'layer.duplicate',
+ label: 'Duplicate Layer',
+ description: 'Clone active layer',
+ category: 'Layer',
+ defaultShortcut: 'Ctrl+J',
+ },
+ {
+ id: 'layer.group',
+ label: 'Group Selected Layers',
+ description: 'Place selected layers in a folder',
+ category: 'Layer',
+ defaultShortcut: 'Ctrl+G',
+ },
+
+ // --- Edit ---
+ {
+ id: 'edit.undo',
+ label: 'Undo',
+ description: 'Undo last canvas action',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+Z',
+ },
+ {
+ id: 'edit.redo',
+ label: 'Redo',
+ description: 'Redo previously undone action',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+Y',
+ altDefaultShortcut: 'Ctrl+Shift+Z',
+ },
+ {
+ id: 'edit.copy',
+ label: 'Copy Layer',
+ description: 'Copy active layer to clipboard',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+C',
+ },
+ {
+ id: 'edit.paste',
+ label: 'Paste Layer',
+ description: 'Paste layer from clipboard',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+V',
+ },
+ {
+ id: 'edit.delete',
+ label: 'Clear / Delete Layer',
+ description: 'Clear active selection or delete selected layer',
+ category: 'Edit',
+ defaultShortcut: 'Delete',
+ altDefaultShortcut: 'Backspace',
+ },
+ {
+ id: 'edit.transform',
+ label: 'Free Transform',
+ description: 'Scale, rotate, or move layer/selection',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+T',
+ },
+ {
+ id: 'edit.selectAll',
+ label: 'Select All',
+ description: 'Select entire canvas',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+A',
+ },
+ {
+ id: 'edit.deselect',
+ label: 'Deselect',
+ description: 'Clear current selection marquee',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+D',
+ },
+ {
+ id: 'edit.invertSelection',
+ label: 'Invert Selection',
+ description: 'Invert active selection mask',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+Shift+I',
+ },
+ {
+ id: 'edit.invertColors',
+ label: 'Invert Colors',
+ description: 'Invert pixel colors on active raster layer',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+I',
+ },
+ {
+ id: 'edit.hueSaturation',
+ label: 'Hue / Saturation',
+ description: 'Open Hue & Saturation tonal correction',
+ category: 'Edit',
+ defaultShortcut: 'Ctrl+U',
+ },
+];
+
+// Bidirectional lookup tables for non-alphanumeric keys & layout-independent codes
+interface KeyCodeSpec {
+ key: string;
+ code: string;
+ altCodes?: readonly string[];
+ aliases?: readonly string[];
+}
+
+const SPECIAL_KEY_SPECS: readonly KeyCodeSpec[] = [
+ { key: '[', code: 'BracketLeft', aliases: ['bracketleft'] },
+ { key: ']', code: 'BracketRight', aliases: ['bracketright'] },
+ { key: ',', code: 'Comma', aliases: ['comma', '<'] },
+ { key: '.', code: 'Period', aliases: ['period', '>'] },
+ { key: '/', code: 'Slash', aliases: ['slash', '?'] },
+ { key: '\\', code: 'Backslash', aliases: ['backslash', '|'] },
+ { key: ';', code: 'Semicolon', aliases: ['semicolon', ':'] },
+ { key: "'", code: 'Quote', aliases: ['quote', '"'] },
+ { key: '`', code: 'Backquote', aliases: ['backquote', '~'] },
+ { key: '=', code: 'Equal', altCodes: ['NumpadAdd'], aliases: ['equal', 'plus', '+'] },
+ { key: '-', code: 'Minus', altCodes: ['NumpadSubtract'], aliases: ['minus', 'subtract', '_'] },
+ { key: 'Tab', code: 'Tab', aliases: ['tab'] },
+ { key: 'Space', code: 'Space', aliases: ['space', ' '] },
+ { key: 'Enter', code: 'Enter', altCodes: ['NumpadEnter'], aliases: ['enter', 'return'] },
+ { key: 'Escape', code: 'Escape', aliases: ['escape', 'esc'] },
+ { key: 'Delete', code: 'Delete', aliases: ['delete', 'del'] },
+ { key: 'Backspace', code: 'Backspace', aliases: ['backspace'] },
+ { key: 'ArrowUp', code: 'ArrowUp', aliases: ['arrowup', 'up'] },
+ { key: 'ArrowDown', code: 'ArrowDown', aliases: ['arrowdown', 'down'] },
+ { key: 'ArrowLeft', code: 'ArrowLeft', aliases: ['arrowleft', 'left'] },
+ { key: 'ArrowRight', code: 'ArrowRight', aliases: ['arrowright', 'right'] },
+ { key: 'Home', code: 'Home', aliases: ['home'] },
+ { key: 'End', code: 'End', aliases: ['end'] },
+ { key: 'PageUp', code: 'PageUp', aliases: ['pageup'] },
+ { key: 'PageDown', code: 'PageDown', aliases: ['pagedown'] },
+];
+
+const PURE_MODIFIER_KEYS = new Set([
+ 'control',
+ 'ctrl',
+ 'shift',
+ 'alt',
+ 'meta',
+ 'os',
+ 'command',
+ 'cmd',
+]);
+
+const PURE_MODIFIER_CODES = new Set([
+ 'ControlLeft',
+ 'ControlRight',
+ 'ShiftLeft',
+ 'ShiftRight',
+ 'AltLeft',
+ 'AltRight',
+ 'MetaLeft',
+ 'MetaRight',
+]);
+
+function resolveKeyToken(rawToken: string): KeyCodeSpec | null {
+ const token = rawToken.trim();
+ if (!token) return null;
+ const lower = token.toLowerCase();
+
+ // Single ASCII letter A-Z
+ if (/^[a-z]$/.test(lower)) {
+ const upper = lower.toUpperCase();
+ return { key: upper, code: `Key${upper}` };
+ }
+
+ // Single digit 0-9
+ if (/^[0-9]$/.test(token)) {
+ return { key: token, code: `Digit${token}`, altCodes: [`Numpad${token}`] };
+ }
+
+ // Function keys F1-F12
+ const fMatch = /^f([1-9]|1[0-2])$/i.exec(token);
+ if (fMatch) {
+ const fn = `F${fMatch[1]}`;
+ return { key: fn, code: fn };
+ }
+
+ // Direct KeyboardEvent.code like KeyB or Digit0
+ if (/^Key[A-Z]$/.test(token)) {
+ const ch = token.slice(3);
+ return { key: ch, code: token };
+ }
+ if (/^Digit[0-9]$/.test(token)) {
+ const d = token.slice(5);
+ return { key: d, code: token, altCodes: [`Numpad${d}`] };
+ }
+
+ for (const spec of SPECIAL_KEY_SPECS) {
+ if (
+ spec.key.toLowerCase() === lower ||
+ spec.code.toLowerCase() === lower ||
+ spec.aliases?.includes(lower)
+ ) {
+ return spec;
+ }
+ }
+
+ return null;
+}
+
+function resolveEventKeySpec(e: KeyboardEventLike): KeyCodeSpec | null {
+ const code = e.code || '';
+ if (PURE_MODIFIER_CODES.has(code) || PURE_MODIFIER_KEYS.has((e.key || '').toLowerCase())) {
+ return null;
+ }
+
+ // Prefer layout-independent physical e.code first
+ if (/^Key[A-Z]$/.test(code)) {
+ const ch = code.slice(3);
+ return { key: ch, code };
+ }
+ if (/^Digit[0-9]$/.test(code)) {
+ const d = code.slice(5);
+ return { key: d, code, altCodes: [`Numpad${d}`] };
+ }
+ if (/^Numpad[0-9]$/.test(code)) {
+ const d = code.slice(6);
+ return { key: d, code: `Digit${d}`, altCodes: [code] };
+ }
+ if (/^F([1-9]|1[0-2])$/.test(code)) {
+ return { key: code, code };
+ }
+
+ for (const spec of SPECIAL_KEY_SPECS) {
+ if (spec.code === code || spec.altCodes?.includes(code)) {
+ return spec;
+ }
+ }
+
+ // Fallback to e.key when e.code is absent (e.g. synthetic events)
+ if (e.key) {
+ return resolveKeyToken(e.key);
+ }
+ return null;
+}
+
+/**
+ * Parses a shortcut string such as 'Ctrl+Shift+S', 'Ctrl + ,', '[', or 'Alt+C'.
+ * Returns null if invalid or empty.
+ */
+export function parseShortcut(raw: string): ParsedShortcut | null {
+ if (!raw || typeof raw !== 'string') return null;
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+
+ // Handle literal '+' key carefully (e.g. 'Ctrl++' or '+')
+ let ctrl = false;
+ let shift = false;
+ let alt = false;
+ let mainToken = '';
+
+ if (trimmed === '+') {
+ mainToken = '+';
+ } else {
+ const parts: string[] = [];
+ let buf = '';
+ for (let i = 0; i < trimmed.length; i++) {
+ const ch = trimmed[i];
+ if (ch === '+') {
+ const cleaned = buf.trim();
+ if (cleaned) {
+ parts.push(cleaned);
+ buf = '';
+ } else {
+ // Trailing or doubled '+' represents the plus key itself
+ buf += '+';
+ }
+ } else {
+ buf += ch;
+ }
+ }
+ if (buf.trim()) parts.push(buf.trim());
+
+ for (let i = 0; i < parts.length; i++) {
+ const p = parts[i];
+ const lower = p.toLowerCase();
+ if (i < parts.length - 1) {
+ if (lower === 'ctrl' || lower === 'control' || lower === 'cmd' || lower === 'meta') {
+ ctrl = true;
+ continue;
+ }
+ if (lower === 'shift') {
+ shift = true;
+ continue;
+ }
+ if (lower === 'alt' || lower === 'option') {
+ alt = true;
+ continue;
+ }
+ }
+ mainToken = p;
+ }
+ }
+
+ if (!mainToken || PURE_MODIFIER_KEYS.has(mainToken.toLowerCase())) {
+ return null;
+ }
+
+ const spec = resolveKeyToken(mainToken);
+ if (!spec) return null;
+
+ return {
+ ctrl,
+ shift,
+ alt,
+ key: spec.key,
+ code: spec.code,
+ altCodes: spec.altCodes,
+ };
+}
+
+/**
+ * Serializes a ParsedShortcut into canonical storage format: 'Ctrl+Shift+Alt+Key'.
+ */
+export function serializeShortcut(parsed: ParsedShortcut): string {
+ const parts: string[] = [];
+ if (parsed.ctrl) parts.push('Ctrl');
+ if (parsed.shift) parts.push('Shift');
+ if (parsed.alt) parts.push('Alt');
+ parts.push(parsed.key);
+ return parts.join('+');
+}
+
+/**
+ * Normalizes any shortcut string into canonical form, or returns '' if invalid/empty.
+ */
+export function normalizeShortcut(raw: string): string {
+ const parsed = parseShortcut(raw);
+ return parsed ? serializeShortcut(parsed) : '';
+}
+
+/**
+ * Formats a canonical shortcut for clean UI display (e.g. 'Ctrl + Shift + S').
+ */
+export function formatShortcutLabel(raw: string): string {
+ const parsed = parseShortcut(raw);
+ if (!parsed) return 'Unassigned';
+ const parts: string[] = [];
+ if (parsed.ctrl) parts.push('Ctrl');
+ if (parsed.shift) parts.push('Shift');
+ if (parsed.alt) parts.push('Alt');
+ parts.push(parsed.key);
+ return parts.join(' + ');
+}
+
+/**
+ * Captures a canonical shortcut string from a live KeyboardEvent (for click-to-record UI).
+ * Returns null for pure modifier presses.
+ */
+export function formatShortcutFromEvent(e: KeyboardEventLike): string | null {
+ const spec = resolveEventKeySpec(e);
+ if (!spec) return null;
+ return serializeShortcut({
+ ctrl: Boolean(e.ctrlKey || e.metaKey),
+ shift: Boolean(e.shiftKey),
+ alt: Boolean(e.altKey),
+ key: spec.key,
+ code: spec.code,
+ altCodes: spec.altCodes,
+ });
+}
+
+/**
+ * Matches a live KeyboardEvent against a shortcut string (layout-independent via e.code).
+ */
+export function matchesKeyboardEvent(e: KeyboardEventLike, shortcutStr: string): boolean {
+ const parsed = parseShortcut(shortcutStr);
+ if (!parsed) return false;
+
+ const eventCtrl = Boolean(e.ctrlKey || e.metaKey);
+ const eventShift = Boolean(e.shiftKey);
+ const eventAlt = Boolean(e.altKey);
+
+ if (parsed.ctrl !== eventCtrl || parsed.shift !== eventShift || parsed.alt !== eventAlt) {
+ return false;
+ }
+
+ if (e.code) {
+ if (e.code === parsed.code) return true;
+ if (parsed.altCodes && parsed.altCodes.includes(e.code)) return true;
+ // Allow e.key match only when code does not contradict a different known letter/digit
+ return false;
+ }
+
+ const evSpec = resolveEventKeySpec(e);
+ return evSpec !== null && evSpec.code === parsed.code;
+}
+
+/**
+ * Returns the active canonical shortcut string for a command ('' if explicitly cleared).
+ */
+export function resolveCommandShortcut(
+ cmd: CommandDefinition,
+ overrides?: ShortcutOverrides
+): string {
+ if (overrides && Object.prototype.hasOwnProperty.call(overrides, cmd.id)) {
+ const raw = overrides[cmd.id];
+ return raw === '' ? '' : normalizeShortcut(raw);
+ }
+ return normalizeShortcut(cmd.defaultShortcut);
+}
+
+/**
+ * Detects other commands currently bound to the same candidate shortcut.
+ */
+export function findShortcutConflicts(
+ commandId: string,
+ candidateShortcut: string,
+ overrides?: ShortcutOverrides,
+ commands: readonly CommandDefinition[] = DEFAULT_COMMANDS
+): CommandDefinition[] {
+ const canonical = normalizeShortcut(candidateShortcut);
+ if (!canonical) return [];
+
+ const conflicts: CommandDefinition[] = [];
+ for (const cmd of commands) {
+ if (cmd.id === commandId) continue;
+ const active = resolveCommandShortcut(cmd, overrides);
+ if (active && active === canonical) {
+ conflicts.push(cmd);
+ }
+ }
+ return conflicts;
+}
+
+export interface ActiveToolHold {
+ code: string;
+ prevTool: ToolType;
+ targetTool: ToolType;
+ downAt: number;
+ usedWhileHeld: boolean;
+}
+
+/**
+ * Spring-loaded tool switch controller (CSP-style):
+ * - Quick tap (< thresholdMs, unused): permanently switches to targetTool.
+ * - Hold (>= thresholdMs) OR pointer used while held: reverts to prevTool on keyup.
+ */
+export class SpringLoadedToolController {
+ private activeHold: ActiveToolHold | null = null;
+ private thresholdMs: number;
+ private nowFn: () => number;
+
+ constructor(
+ thresholdMs: number = SPRING_LOADED_HOLD_MS,
+ nowFn: () => number = () => (typeof performance !== 'undefined' ? performance.now() : Date.now())
+ ) {
+ this.thresholdMs = thresholdMs;
+ this.nowFn = nowFn;
+ }
+
+ public getActiveHold(): Readonly<ActiveToolHold> | null {
+ return this.activeHold;
+ }
+
+ /**
+ * Call on spring-loaded tool keydown. Returns the tool to activate (or null if already active).
+ */
+ public handleToolKeyDown(
+ code: string,
+ targetTool: ToolType,
+ currentTool: ToolType
+ ): ToolType | null {
+ if (currentTool === targetTool) return null;
+ this.activeHold = {
+ code,
+ prevTool: currentTool,
+ targetTool,
+ downAt: this.nowFn(),
+ usedWhileHeld: false,
+ };
+ return targetTool;
+ }
+
+ /**
+ * Call when the user starts a pointer interaction while a tool key is held down.
+ */
+ public markUsedWhileHeld(): void {
+ if (this.activeHold) {
+ this.activeHold.usedWhileHeld = true;
+ }
+ }
+
+ /**
+ * Call on keyup. Returns the previous tool to restore if spring-loaded revert should trigger, else null.
+ */
+ public handleKeyUp(code: string, currentTool: ToolType): ToolType | null {
+ const hold = this.activeHold;
+ if (!hold || hold.code !== code) return null;
+ this.activeHold = null;
+
+ const heldMs = this.nowFn() - hold.downAt;
+ if ((heldMs >= this.thresholdMs || hold.usedWhileHeld) && currentTool === hold.targetTool) {
+ return hold.prevTool;
+ }
+ return null;
+ }
+
+ /**
+ * Clears active hold on window blur. Returns prevTool if currently in a spring-loaded hold > threshold.
+ */
+ public cancel(currentTool?: ToolType): ToolType | null {
+ const hold = this.activeHold;
+ this.activeHold = null;
+ if (!hold || !currentTool) return null;
+ const heldMs = this.nowFn() - hold.downAt;
+ if ((heldMs >= this.thresholdMs || hold.usedWhileHeld) && currentTool === hold.targetTool) {
+ return hold.prevTool;
+ }
+ return null;
+ }
+}
+
+/**
+ * Centralized Command & Shortcut Manager.
+ */
+export class ShortcutManager {
+ private commands: CommandDefinition[];
+ private commandMap: Map<string, CommandDefinition>;
+ private overrides: ShortcutOverrides = {};
+ private handlers: Map<string, () => void> = new Map();
+
+ constructor(initialCommands: readonly CommandDefinition[] = DEFAULT_COMMANDS) {
+ this.commands = initialCommands.map((c) => ({ ...c }));
+ this.commandMap = new Map(this.commands.map((c) => [c.id, c]));
+ }
+
+ public getCommands(): readonly CommandDefinition[] {
+ return this.commands;
+ }
+
+ public getCommand(id: string): CommandDefinition | undefined {
+ return this.commandMap.get(id);
+ }
+
+ public setOverrides(overrides: ShortcutOverrides | undefined): void {
+ this.overrides = overrides ? { ...overrides } : {};
+ }
+
+ public getOverrides(): ShortcutOverrides {
+ return { ...this.overrides };
+ }
+
+ public getShortcut(commandId: string): string {
+ const cmd = this.commandMap.get(commandId);
+ if (!cmd) return '';
+ return resolveCommandShortcut(cmd, this.overrides);
+ }
+
+ public registerHandler(commandId: string, handler: () => void): void {
+ this.handlers.set(commandId, handler);
+ const cmd = this.commandMap.get(commandId);
+ if (cmd) cmd.handler = handler;
+ }
+
+ public registerHandlers(handlerMap: Record<string, () => void>): void {
+ for (const [id, fn] of Object.entries(handlerMap)) {
+ this.registerHandler(id, fn);
+ }
+ }
+
+ public clearHandlers(): void {
+ this.handlers.clear();
+ for (const cmd of this.commands) {
+ cmd.handler = undefined;
+ }
+ }
+
+ public findConflicts(commandId: string, candidateShortcut: string): CommandDefinition[] {
+ return findShortcutConflicts(commandId, candidateShortcut, this.overrides, this.commands);
+ }
+
+ /**
+ * Finds the first matching command for a KeyboardEvent.
+ * Respects overrides immediately; falls back to altDefaultShortcut only if not overridden.
+ */
+ public matchEvent(
+ e: KeyboardEventLike,
+ overridesOverride?: ShortcutOverrides
+ ): CommandDefinition | null {
+ const activeOverrides = overridesOverride ?? this.overrides;
+
+ for (const cmd of this.commands) {
+ const bound = resolveCommandShortcut(cmd, activeOverrides);
+ if (bound && matchesKeyboardEvent(e, bound)) {
+ return cmd;
+ }
+ const isOverridden = Object.prototype.hasOwnProperty.call(activeOverrides, cmd.id);
+ if (!isOverridden && cmd.altDefaultShortcut && matchesKeyboardEvent(e, cmd.altDefaultShortcut)) {
+ return cmd;
+ }
+ }
+ return null;
+ }
+
+ public executeCommand(commandId: string): boolean {
+ const fn = this.handlers.get(commandId) ?? this.commandMap.get(commandId)?.handler;
+ if (!fn) return false;
+ fn();
+ return true;
+ }
+}
+
+export const shortcutManager = new ShortcutManager(DEFAULT_COMMANDS);
+
+// ---------------------------------------------------------------------------
+// Modifier Key Settings Helpers (shared by CanvasArea, GlobalShortcutListener, Navigation)
+// ---------------------------------------------------------------------------
+
+export interface PointerModifierContext {
+ button: number;
+ pointerType: string;
+ ctrlKey: boolean;
+ metaKey: boolean;
+ shiftKey: boolean;
+ altKey: boolean;
+ isSpaceDown: boolean;
+}
+
+export interface ResolvedPointerModifier {
+ slot: ModifierKeySlot;
+ action: ModifierAction;
+}
+
+/**
+ * Resolves the highest-specificity modifier action for a pointerdown event on the canvas.
+ */
+export function resolvePointerModifierAction(
+ ctx: PointerModifierContext,
+ settings: ModifierKeySettings = DEFAULT_MODIFIER_KEY_SETTINGS
+): ResolvedPointerModifier | null {
+ const isPen = ctx.pointerType === 'pen';
+ const ctrl = ctx.ctrlKey || ctx.metaKey;
+
+ // 1. Non-primary buttons (Stylus barrel buttons, Right click, Middle click)
+ if (isPen) {
+ if (ctx.button === 2 || ctx.button === 3) {
+ const action = settings.stylusButton1;
+ return action !== 'none' ? { slot: 'stylusButton1', action } : null;
+ }
+ if (ctx.button === 5 || ctx.button === 4) {
+ const action = settings.stylusButton2;
+ return action !== 'none' ? { slot: 'stylusButton2', action } : null;
+ }
+ } else {
+ if (ctx.button === 2) {
+ const action = settings.rightClick;
+ return action !== 'none' ? { slot: 'rightClick', action } : null;
+ }
+ if (ctx.button === 1) {
+ const action = settings.middleClick;
+ return action !== 'none' ? { slot: 'middleClick', action } : null;
+ }
+ if (ctx.button === 3) {
+ const action = settings.stylusButton1;
+ return action !== 'none' ? { slot: 'stylusButton1', action } : null;
+ }
+ if (ctx.button === 4) {
+ const action = settings.stylusButton2;
+ return action !== 'none' ? { slot: 'stylusButton2', action } : null;
+ }
+ }
+
+ // 2. Primary button (button 0) combined with held keyboard modifiers (2-key combos first)
+ if (ctx.button === 0) {
+ if (ctrl && ctx.altKey && !ctx.isSpaceDown) {
+ return settings.ctrlAlt !== 'none' ? { slot: 'ctrlAlt', action: settings.ctrlAlt } : null;
+ }
+ if (ctx.shiftKey && ctx.altKey && !ctrl && !ctx.isSpaceDown) {
+ return settings.shiftAlt !== 'none' ? { slot: 'shiftAlt', action: settings.shiftAlt } : null;
+ }
+ if (ctrl && ctx.isSpaceDown && !ctx.altKey) {
+ return settings.ctrlSpace !== 'none'
+ ? { slot: 'ctrlSpace', action: settings.ctrlSpace }
+ : null;
+ }
+ if (ctx.shiftKey && ctx.isSpaceDown && !ctrl && !ctx.altKey) {
+ return settings.shiftSpace !== 'none'
+ ? { slot: 'shiftSpace', action: settings.shiftSpace }
+ : null;
+ }
+ if (ctx.isSpaceDown && !ctrl && !ctx.altKey && !ctx.shiftKey) {
+ return settings.space !== 'none' ? { slot: 'space', action: settings.space } : null;
+ }
+ if (ctx.altKey && !ctrl && !ctx.shiftKey && !ctx.isSpaceDown) {
+ return settings.alt !== 'none' ? { slot: 'alt', action: settings.alt } : null;
+ }
+ if (ctrl && !ctx.altKey && !ctx.shiftKey && !ctx.isSpaceDown) {
+ return settings.ctrl !== 'none' ? { slot: 'ctrl', action: settings.ctrl } : null;
+ }
+ if (ctx.shiftKey && !ctrl && !ctx.altKey && !ctx.isSpaceDown) {
+ return settings.shift !== 'none' ? { slot: 'shift', action: settings.shift } : null;
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Resolves the active cursor/hover action for currently held keyboard modifiers (without clicking).
+ */
+export function resolveHeldKeyModifierAction(
+ state: { ctrl: boolean; shift: boolean; alt: boolean; space: boolean },
+ settings: ModifierKeySettings = DEFAULT_MODIFIER_KEY_SETTINGS
+): ModifierAction {
+ if (state.ctrl && state.alt && !state.space) return settings.ctrlAlt;
+ if (state.shift && state.alt && !state.ctrl && !state.space) return settings.shiftAlt;
+ if (state.ctrl && state.space && !state.alt) return settings.ctrlSpace;
+ if (state.shift && state.space && !state.ctrl && !state.alt) return settings.shiftSpace;
+ if (state.space && !state.ctrl && !state.alt && !state.shift) return settings.space;
+ if (state.alt && !state.ctrl && !state.shift && !state.space) return settings.alt;
+ if (state.ctrl && !state.alt && !state.shift && !state.space) return settings.ctrl;
+ if (state.shift && !state.ctrl && !state.alt && !state.space) return settings.shift;
+ return 'none';
+}