diff --git a/src-tauri/src/config.rs b/src-tauri/src/config.rs index 2d67bd2..b462cfd 100644 --- a/src-tauri/src/config.rs +++ b/src-tauri/src/config.rs @@ -587,6 +587,12 @@ impl Default for ScriblConfig { rhs: "edit.duplicate".into(), desc: Some("Duplicate".into()), }, + KeymapEntry { + mode: "v".into(), + lhs: "".into(), + rhs: "selection.toggle_lock".into(), + desc: Some("Toggle Lock".into()), + }, ], toolbar: ToolbarConfig::default(), theme: ThemeConfig::default(), diff --git a/src-tauri/src/watcher.rs b/src-tauri/src/watcher.rs index 8b87b96..07dbf7c 100644 --- a/src-tauri/src/watcher.rs +++ b/src-tauri/src/watcher.rs @@ -123,6 +123,7 @@ scribl.keymap.set("v", "", "edit.copy", { desc = "Copy" }) scribl.keymap.set("v", "", "edit.paste", { desc = "Paste" }) scribl.keymap.set("v", "", "edit.cut", { desc = "Cut" }) scribl.keymap.set("v", "", "edit.duplicate", { desc = "Duplicate" }) +scribl.keymap.set("v", "", "selection.toggle_lock", { desc = "Toggle Lock" }) -------------------------------------------------------------------------------- -- 3. Floating Toolbar Layout diff --git a/src/components/canvas/SelectionOverlay.test.tsx b/src/components/canvas/SelectionOverlay.test.tsx index 238c8b7..bc7fb76 100644 --- a/src/components/canvas/SelectionOverlay.test.tsx +++ b/src/components/canvas/SelectionOverlay.test.tsx @@ -87,4 +87,55 @@ describe('SelectionOverlay', () => { const selectionBox = container.querySelector('[data-testid="unified-selection-box"]'); expect(selectionBox).toBeNull(); }); + + it('hides resize handles and renders lock badge when selected elements are locked', () => { + const lockedElements: Record = { + l1: { + ...elements.s1, + id: 'l1', + locked: true, + }, + }; + + const { container } = render( + , + ); + + const selectionBox = container.querySelector('[data-testid="unified-selection-box"]'); + expect(selectionBox).not.toBeNull(); + + // Corner handles must NOT be rendered + const handles = container.querySelectorAll('[data-testid^="handle-"]'); + expect(handles.length).toBe(0); + + // Lock badge must be rendered + const lockBadge = container.querySelector('[data-testid="selection-lock-badge"]'); + expect(lockBadge).not.toBeNull(); + }); + + it('does not render lock badge when selected elements are unlocked', () => { + const { container } = render( + , + ); + + const handles = container.querySelectorAll('[data-testid^="handle-"]'); + expect(handles.length).toBe(4); + + const lockBadge = container.querySelector('[data-testid="selection-lock-badge"]'); + expect(lockBadge).toBeNull(); + }); }); diff --git a/src/components/canvas/SelectionOverlay.tsx b/src/components/canvas/SelectionOverlay.tsx index 93e4d27..e5371f7 100644 --- a/src/components/canvas/SelectionOverlay.tsx +++ b/src/components/canvas/SelectionOverlay.tsx @@ -48,6 +48,8 @@ export const SelectionOverlay: React.FC = ({ const boxW = Math.max(1, screenBR.x - screenTL.x); const boxH = Math.max(1, screenBR.y - screenTL.y); const screenCenter = worldToScreen(bounds.centerX, bounds.centerY, camera, width, height); + const isAllLocked = activeSelectedIds.length > 0 + && activeSelectedIds.every((id) => elements[id]?.locked); return ( @@ -61,53 +63,85 @@ export const SelectionOverlay: React.FC = ({ fill='var(--color-selection-fill, rgba(2, 132, 199, 0.04))' stroke='var(--color-selection-stroke, #0284c7)' strokeWidth={1.5} + strokeDasharray={isAllLocked ? '4 3' : undefined} /> + {/* Lock Badge HUD */} + {isAllLocked && ( + + + + + )} + {/* 4 Corner Resize Handles */} - - - - + {!isAllLocked && ( + <> + + + + + + )} {/* Rotation Center Pivot and HUD Badge */} {rotationAngle !== undefined && rotationAngle !== null && ( diff --git a/src/components/settings/KeybindingsTab.tsx b/src/components/settings/KeybindingsTab.tsx index b35c632..b5ffc2a 100644 --- a/src/components/settings/KeybindingsTab.tsx +++ b/src/components/settings/KeybindingsTab.tsx @@ -224,6 +224,14 @@ const ALL_ACTIONS: ActionDefinition[] = [ defaultLhs: '', mode: 'v', }, + { + id: 'selection.toggle_lock_visual', + targetId: 'selection.toggle_lock', + label: 'Toggle Lock (Visual Mode)', + category: 'Visual Mode (Selection)', + defaultLhs: '', + mode: 'v', + }, ]; export const KeybindingsTab: React.FC = () => { diff --git a/src/core/commands/CommandRegistry.test.ts b/src/core/commands/CommandRegistry.test.ts index 39d96d5..a40d891 100644 --- a/src/core/commands/CommandRegistry.test.ts +++ b/src/core/commands/CommandRegistry.test.ts @@ -135,4 +135,36 @@ describe('CommandRegistry', () => { expect(commandRegistry.execute('file.copy_png')).toBe(true); expect(onCopyPng).toHaveBeenCalledTimes(2); }); + + it('executes selection.toggle_lock and toggles element lock state', () => { + const dummyStroke: StrokeElement = { + id: 'lock-item', + type: 'stroke', + x: 0, + y: 0, + width: 10, + height: 10, + zIndex: 1, + color: '#000', + size: 2, + thinning: 0.6, + smoothing: 0.5, + points: [{ x: 0, y: 0, pressure: 0.5 }], + locked: false, + }; + useDocumentStore.setState({ + elements: { 'lock-item': dummyStroke }, + elementIds: ['lock-item'], + selectedIds: ['lock-item'], + }); + + const cmd = commandRegistry.get('selection.toggle_lock'); + expect(cmd).toBeDefined(); + + commandRegistry.execute('selection.toggle_lock'); + expect(useDocumentStore.getState().elements['lock-item'].locked).toBe(true); + + commandRegistry.execute('selection.toggle_lock'); + expect(useDocumentStore.getState().elements['lock-item'].locked).toBe(false); + }); }); diff --git a/src/core/commands/CommandRegistry.ts b/src/core/commands/CommandRegistry.ts index 95c48db..031e28e 100644 --- a/src/core/commands/CommandRegistry.ts +++ b/src/core/commands/CommandRegistry.ts @@ -420,6 +420,16 @@ export function registerDefaultCommands(handlers?: { execute: () => {}, }); + commandRegistry.register({ + id: 'selection.toggle_lock', + label: 'Toggle Lock', + category: 'selection', + description: 'Lock or unlock selected elements', + execute: () => { + useDocumentStore.getState().toggleLockSelected(); + }, + }); + // Clipboard & Duplicate commandRegistry.register({ id: 'edit.copy', diff --git a/src/core/engine/HitTester.test.ts b/src/core/engine/HitTester.test.ts index 785ff0b..e580511 100644 --- a/src/core/engine/HitTester.test.ts +++ b/src/core/engine/HitTester.test.ts @@ -498,4 +498,92 @@ describe('HitTester', () => { expect(hitTestShape(unknown, { x: 5, y: 5 })).toBe(false); }); }); + + describe('Locked elements hit testing', () => { + const lockedShape: ShapeElement = { + id: 'locked_shape', + type: 'shape', + shapeType: 'rectangle', + x: 50, + y: 50, + width: 100, + height: 100, + zIndex: 2, + strokeColor: '#000', + fillColor: '#fff', + strokeWidth: 2, + strokeStyle: 'solid', + locked: true, + }; + + const unlockedStroke: StrokeElement = { + id: 'unlocked_stroke', + type: 'stroke', + x: 60, + y: 60, + width: 50, + height: 50, + zIndex: 1, + color: '#ff0000', + size: 4, + thinning: 0.6, + smoothing: 0.5, + points: [ + { x: 60, y: 60, pressure: 0.5 }, + { x: 100, y: 100, pressure: 0.5 }, + ], + locked: false, + }; + + const lockedElements = { + unlocked_stroke: unlockedStroke, + locked_shape: lockedShape, + }; + const lockedElementIds = ['unlocked_stroke', 'locked_shape']; + + it('hits locked element directly when ignoreLocked is omitted or false', () => { + const hit = hitTestPoint(lockedElements, lockedElementIds, { x: 80, y: 80 }); + expect(hit).toBe('locked_shape'); + }); + + it('passes through locked element to hit underlying unlocked element when ignoreLocked is true', () => { + // Point (80, 80) is on both the locked_shape (zIndex 2) and unlocked_stroke (zIndex 1) + const hit = hitTestPoint(lockedElements, lockedElementIds, { x: 80, y: 80 }, 8, { + ignoreLocked: true, + }); + expect(hit).toBe('unlocked_stroke'); + }); + + it('returns null when ignoreLocked is true and no unlocked elements intersect point', () => { + const hit = hitTestPoint(lockedElements, lockedElementIds, { x: 140, y: 140 }, 8, { + ignoreLocked: true, + }); + expect(hit).toBeNull(); + }); + + it('skips locked elements in marquee selection', () => { + const selected = hitTestMarquee(lockedElements, lockedElementIds, { + minX: 0, + minY: 0, + maxX: 200, + maxY: 200, + }); + expect(selected).toEqual(['unlocked_stroke']); + }); + + it('includes locked elements in marquee selection when includeLocked is true', () => { + const selected = hitTestMarquee( + lockedElements, + lockedElementIds, + { + minX: 0, + minY: 0, + maxX: 200, + maxY: 200, + }, + { includeLocked: true }, + ); + expect(selected).toEqual(['unlocked_stroke', 'locked_shape']); + }); + }); }); diff --git a/src/core/engine/HitTester.ts b/src/core/engine/HitTester.ts index e746a15..e932b7e 100644 --- a/src/core/engine/HitTester.ts +++ b/src/core/engine/HitTester.ts @@ -1,10 +1,15 @@ import { BoundingBox, CanvasElement, ShapeElement } from '../../types/canvas'; +export interface HitTestOptions { + ignoreLocked?: boolean; +} + export function hitTestPoint( elements: Record, elementIds: string[], point: { x: number; y: number; }, threshold: number = 8, + options?: HitTestOptions, ): string | null { // Check from top z-index down for (let i = elementIds.length - 1; i >= 0; i--) { @@ -12,6 +17,10 @@ export function hitTestPoint( const el = elements[id]; if (!el) continue; + if (options?.ignoreLocked && el.locked) { + continue; + } + let minX = Math.min(el.x, el.x + el.width); let maxX = Math.max(el.x, el.x + el.width); let minY = Math.min(el.y, el.y + el.height); @@ -254,10 +263,15 @@ function isShapeFilled(shape: ShapeElement): boolean { ); } +export interface HitTestMarqueeOptions { + includeLocked?: boolean; +} + export function hitTestMarquee( elements: Record, elementIds: string[], bounds: BoundingBox, + options?: HitTestMarqueeOptions, ): string[] { const result: string[] = []; const minX = Math.min(bounds.minX, bounds.maxX); @@ -268,6 +282,7 @@ export function hitTestMarquee( for (const id of elementIds) { const el = elements[id]; if (!el) continue; + if (el.locked && !options?.includeLocked) continue; let elMinX = Math.min(el.x, el.x + el.width); let elMaxX = Math.max(el.x, el.x + el.width); diff --git a/src/core/history/commands.ts b/src/core/history/commands.ts index 2792315..37ad456 100644 --- a/src/core/history/commands.ts +++ b/src/core/history/commands.ts @@ -286,11 +286,21 @@ export class ClearCanvasCommand implements Command { } execute(data: DocumentData): DocumentData { + const preservedElements: Record = {}; + const preservedIds: string[] = []; + for (const id of data.elementIds) { + const el = data.elements[id]; + if (el?.locked) { + preservedElements[id] = el; + preservedIds.push(id); + } + } + const preservedSelectedIds = data.selectedIds.filter((id) => preservedElements[id]); return { ...data, - elements: {}, - elementIds: [], - selectedIds: [], + elements: preservedElements, + elementIds: preservedIds, + selectedIds: preservedSelectedIds, }; } @@ -303,3 +313,46 @@ export class ClearCanvasCommand implements Command { }; } } + +export class SetElementsLockCommand implements Command { + id = `lock_${Date.now()}`; + name = 'Toggle Lock'; + + constructor( + private elementIds: string[], + private locked: boolean, + private previousStates: Record, + ) {} + + execute(data: DocumentData): DocumentData { + const nextElements = { ...data.elements }; + for (const id of this.elementIds) { + if (nextElements[id]) { + nextElements[id] = { + ...nextElements[id], + locked: this.locked, + }; + } + } + return { + ...data, + elements: nextElements, + }; + } + + undo(data: DocumentData): DocumentData { + const nextElements = { ...data.elements }; + for (const id of this.elementIds) { + if (nextElements[id]) { + nextElements[id] = { + ...nextElements[id], + locked: this.previousStates[id] ?? false, + }; + } + } + return { + ...data, + elements: nextElements, + }; + } +} diff --git a/src/core/history/history.test.ts b/src/core/history/history.test.ts index 5971e86..3800f6a 100644 --- a/src/core/history/history.test.ts +++ b/src/core/history/history.test.ts @@ -8,6 +8,7 @@ import { ClearCanvasCommand, DeleteElementsCommand, MoveElementsCommand, + SetElementsLockCommand, TransformElementsCommand, UpdateTextElementCommand, } from './commands'; @@ -295,4 +296,54 @@ describe('HistoryStack and Commands', () => { expect(undone.elements['s1']).toEqual(dummyStroke); expect(undone.selectedIds).toEqual(['s1']); }); + + it('preserves locked elements when executing ClearCanvasCommand', () => { + const history = new HistoryStack(); + const lockedEl: StrokeElement = { + ...dummyStroke, + id: 's_locked', + locked: true, + }; + const unlockedEl: StrokeElement = { + ...dummyStroke, + id: 's_unlocked', + locked: false, + }; + const data: DocumentData = { + elements: { s_locked: lockedEl, s_unlocked: unlockedEl }, + elementIds: ['s_locked', 's_unlocked'], + selectedIds: ['s_locked', 's_unlocked'], + }; + + const cleared = history.execute(new ClearCanvasCommand(data), data); + expect(cleared.elementIds).toEqual(['s_locked']); + expect(cleared.elements['s_locked']).toBeDefined(); + expect(cleared.elements['s_unlocked']).toBeUndefined(); + expect(cleared.selectedIds).toEqual(['s_locked']); + + const undone = history.undo(cleared); + expect(undone.elementIds).toEqual(['s_locked', 's_unlocked']); + expect(undone.elements['s_unlocked']).toBeDefined(); + }); + + it('executes SetElementsLockCommand and reverts to previous locked states on undo', () => { + const history = new HistoryStack(); + const el1: StrokeElement = { ...dummyStroke, id: 'el1', locked: false }; + const el2: StrokeElement = { ...dummyStroke, id: 'el2', locked: true }; + const data: DocumentData = { + elements: { el1, el2 }, + elementIds: ['el1', 'el2'], + selectedIds: ['el1', 'el2'], + }; + + // Lock all selected + const lockCmd = new SetElementsLockCommand(['el1', 'el2'], true, { el1: false, el2: true }); + const locked = history.execute(lockCmd, data); + expect(locked.elements['el1'].locked).toBe(true); + expect(locked.elements['el2'].locked).toBe(true); + + const undone = history.undo(locked); + expect(undone.elements['el1'].locked).toBe(false); + expect(undone.elements['el2'].locked).toBe(true); + }); }); diff --git a/src/core/input/KeybindingEngine.test.ts b/src/core/input/KeybindingEngine.test.ts index cac7756..901f79e 100644 --- a/src/core/input/KeybindingEngine.test.ts +++ b/src/core/input/KeybindingEngine.test.ts @@ -330,5 +330,32 @@ describe('KeybindingEngine', () => { ); expect(visualDelete?.lhs).toBe(''); }); + + it('dispatches selection.toggle_lock on Mod+Shift+L in visual mode', () => { + const visualEngine = new KeybindingEngine({ + executeCommand: (id) => { + executedCommands.push(id); + return true; + }, + getActiveMode: () => 'v', + }); + + visualEngine.registerKeymaps(DEFAULT_CONFIG.keymaps); + + const isMac = navigator.platform.toUpperCase().indexOf('MAC') >= 0; + executedCommands.length = 0; + // Trigger Cmd/Ctrl + Shift + L + visualEngine.handleKeyDown( + new KeyboardEvent('keydown', { + key: 'L', + metaKey: isMac, + ctrlKey: !isMac, + shiftKey: true, + cancelable: true, + }), + ); + + expect(executedCommands).toContain('selection.toggle_lock'); + }); }); }); diff --git a/src/core/input/PointerRouter.test.ts b/src/core/input/PointerRouter.test.ts index 73a6dcf..bd23bd2 100644 --- a/src/core/input/PointerRouter.test.ts +++ b/src/core/input/PointerRouter.test.ts @@ -965,4 +965,297 @@ describe('PointerRouter - Shape Drawing', () => { useToolStore.setState({ currentTool: 'pen' }); expect(useToolStore.getState().strokeSize).toBe(4); }); + + it('eraser tool ignores locked elements and deletes unlocked elements underneath', () => { + const lockedRect: ShapeElement = { + id: 'locked_box', + type: 'shape', + shapeType: 'rectangle', + x: 100, + y: 100, + width: 200, + height: 200, + zIndex: 2, + strokeColor: '#000', + fillColor: '#fff', + strokeWidth: 2, + strokeStyle: 'solid', + locked: true, + }; + + const unlockedStroke: StrokeElement = { + id: 'unlocked_line', + type: 'stroke', + x: 120, + y: 120, + width: 100, + height: 100, + zIndex: 1, + color: '#ff0000', + size: 4, + thinning: 0.6, + smoothing: 0.5, + points: [ + { x: 120, y: 120, pressure: 0.5 }, + { x: 220, y: 220, pressure: 0.5 }, + ], + locked: false, + }; + + useDocumentStore.setState({ + elements: { + locked_box: lockedRect, + unlocked_line: unlockedStroke, + }, + elementIds: ['unlocked_line', 'locked_box'], + selectedIds: [], + }); + + useToolStore.setState({ currentTool: 'eraser' }); + + // Erase point at world (150, 150) -> screen (650, 550) + router.handlePointerDown( + new PointerEvent('pointerdown', { + clientX: 650, + clientY: 550, + pointerId: 11, + pointerType: 'mouse', + buttons: 1, + }), + container, + ); + + const doc = useDocumentStore.getState(); + // locked_box must survive + expect(doc.elements['locked_box']).toBeDefined(); + // unlocked_line must be erased + expect(doc.elements['unlocked_line']).toBeUndefined(); + }); + + it('select tool selects locked element on click but prevents dragging', () => { + const lockedRect: ShapeElement = { + id: 'locked_box', + type: 'shape', + shapeType: 'rectangle', + x: 100, + y: 100, + width: 200, + height: 200, + zIndex: 1, + strokeColor: '#000', + fillColor: '#fff', + strokeWidth: 2, + strokeStyle: 'solid', + locked: true, + }; + + useDocumentStore.setState({ + elements: { locked_box: lockedRect }, + elementIds: ['locked_box'], + selectedIds: [], + }); + + useToolStore.setState({ currentTool: 'select' }); + + // Click at world (150, 150) -> screen (650, 550) + router.handlePointerDown( + new PointerEvent('pointerdown', { + clientX: 650, + clientY: 550, + pointerId: 12, + pointerType: 'mouse', + buttons: 1, + }), + container, + ); + + // Locked element should be selected + expect(useDocumentStore.getState().selectedIds).toEqual(['locked_box']); + + // Attempt to drag to screen (700, 600) -> world (200, 200) + router.handlePointerMove( + new PointerEvent('pointermove', { + clientX: 700, + clientY: 600, + pointerId: 12, + pointerType: 'mouse', + buttons: 1, + }), + ); + + router.handlePointerUp( + new PointerEvent('pointerup', { + clientX: 700, + clientY: 600, + pointerId: 12, + pointerType: 'mouse', + }), + container, + ); + + // Locked element should NOT have moved + expect(useDocumentStore.getState().elements['locked_box'].x).toBe(100); + expect(useDocumentStore.getState().elements['locked_box'].y).toBe(100); + }); + + it('skips locked elements during standard marquee selection and includes them when Shift is held', () => { + const lockedRect: ShapeElement = { + id: 'locked_box', + type: 'shape', + shapeType: 'rectangle', + x: 100, + y: 100, + width: 100, + height: 100, + zIndex: 1, + strokeColor: '#000000', + strokeWidth: 2, + strokeStyle: 'solid', + locked: true, + }; + + const unlockedRect: ShapeElement = { + id: 'unlocked_box', + type: 'shape', + shapeType: 'rectangle', + x: 300, + y: 100, + width: 100, + height: 100, + zIndex: 2, + strokeColor: '#000000', + strokeWidth: 2, + strokeStyle: 'solid', + locked: false, + }; + + useDocumentStore.setState({ + elements: { locked_box: lockedRect, unlocked_box: unlockedRect }, + elementIds: ['locked_box', 'unlocked_box'], + selectedIds: [], + }); + + useToolStore.setState({ currentTool: 'select' }); + + // 1. Marquee drag WITHOUT Shift across the whole canvas (0,0) to (500,300) + // Screen coords: world (0,0) -> (500, 400), world (500, 300) -> (1000, 700) + router.handlePointerDown( + new PointerEvent('pointerdown', { + clientX: 500, + clientY: 400, + pointerId: 13, + pointerType: 'mouse', + buttons: 1, + shiftKey: false, + }), + container, + ); + + router.handlePointerMove( + new PointerEvent('pointermove', { + clientX: 1000, + clientY: 700, + pointerId: 13, + pointerType: 'mouse', + buttons: 1, + shiftKey: false, + }), + ); + + // Only unlocked element should be selected + expect(useDocumentStore.getState().selectedIds).toEqual(['unlocked_box']); + + router.handlePointerUp( + new PointerEvent('pointerup', { + clientX: 1000, + clientY: 700, + pointerId: 13, + pointerType: 'mouse', + shiftKey: false, + }), + container, + ); + + // Clear selection + useDocumentStore.setState({ selectedIds: [] }); + + // 2. Marquee drag WITH Shift held across (0,0) to (500,300) + router.handlePointerDown( + new PointerEvent('pointerdown', { + clientX: 500, + clientY: 400, + pointerId: 14, + pointerType: 'mouse', + buttons: 1, + shiftKey: true, + }), + container, + ); + + router.handlePointerMove( + new PointerEvent('pointermove', { + clientX: 1000, + clientY: 700, + pointerId: 14, + pointerType: 'mouse', + buttons: 1, + shiftKey: true, + }), + ); + + // Both unlocked and locked elements should be selected + expect(useDocumentStore.getState().selectedIds).toEqual(['locked_box', 'unlocked_box']); + + router.handlePointerUp( + new PointerEvent('pointerup', { + clientX: 1000, + clientY: 700, + pointerId: 14, + pointerType: 'mouse', + shiftKey: true, + }), + container, + ); + + // 3. Additive Shift-marquee with pre-existing selection + useDocumentStore.setState({ selectedIds: ['unlocked_box'] }); + + // Drag marquee only over the locked box (world 50,50 to 250,250 -> screen 550,450 to 750,650) + router.handlePointerDown( + new PointerEvent('pointerdown', { + clientX: 550, + clientY: 450, + pointerId: 15, + pointerType: 'mouse', + buttons: 1, + shiftKey: true, + }), + container, + ); + + router.handlePointerMove( + new PointerEvent('pointermove', { + clientX: 750, + clientY: 650, + pointerId: 15, + pointerType: 'mouse', + buttons: 1, + shiftKey: true, + }), + ); + + // Should include previous selection plus newly enclosed locked box + expect(useDocumentStore.getState().selectedIds).toEqual(['unlocked_box', 'locked_box']); + + router.handlePointerUp( + new PointerEvent('pointerup', { + clientX: 750, + clientY: 650, + pointerId: 15, + pointerType: 'mouse', + shiftKey: true, + }), + container, + ); + }); }); diff --git a/src/core/input/PointerRouter.ts b/src/core/input/PointerRouter.ts index 352893a..4439d06 100644 --- a/src/core/input/PointerRouter.ts +++ b/src/core/input/PointerRouter.ts @@ -52,6 +52,7 @@ export class PointerRouter { private shapeStartWorld: { x: number; y: number; } = { x: 0, y: 0 }; private activeShapeTool: ShapeType | null = null; public marqueeBox: MarqueeBox | null = null; + private marqueeInitialSelectedIds: string[] = []; public onMarqueeUpdate?: (box: MarqueeBox | null) => void; public isRotateKeyHeld: boolean = false; public rotationAngle: number | null = null; @@ -168,8 +169,9 @@ export class PointerRouter { // 1. If elements are selected, check for Corner Handle Hit or Rotation Trigger if (doc.selectedIds.length > 0) { + const hasUnlocked = doc.selectedIds.some((id) => !doc.elements[id]?.locked); const bounds = computeSelectionBounds(doc.elements, doc.selectedIds); - if (bounds) { + if (bounds && hasUnlocked) { const screenHandles = { nw: worldToScreen(bounds.minX, bounds.minY, camera, width, height), ne: worldToScreen(bounds.maxX, bounds.minY, camera, width, height), @@ -260,13 +262,16 @@ export class PointerRouter { } } } - this.state = 'DRAGGING_SELECTION'; - this.lastDragWorld = worldPoint; - this.dragTotalDelta = { x: 0, y: 0 }; + if (!doc.elements[hitId]?.locked) { + this.state = 'DRAGGING_SELECTION'; + this.lastDragWorld = worldPoint; + this.dragTotalDelta = { x: 0, y: 0 }; + } } else { if (!e.shiftKey) { doc.setSelected([]); } + this.marqueeInitialSelectedIds = e.shiftKey ? [...doc.selectedIds] : []; this.state = 'SELECTING_MARQUEE'; this.marqueeBox = { startX: worldPoint.x, @@ -528,13 +533,23 @@ export class PointerRouter { this.onMarqueeUpdate?.({ ...this.marqueeBox }); const doc = useDocumentStore.getState(); - const hitIds = hitTestMarquee(doc.elements, doc.elementIds, { - minX: this.marqueeBox.startX, - minY: this.marqueeBox.startY, - maxX: this.marqueeBox.currentX, - maxY: this.marqueeBox.currentY, - }); - doc.setSelected(hitIds); + const hitIds = hitTestMarquee( + doc.elements, + doc.elementIds, + { + minX: this.marqueeBox.startX, + minY: this.marqueeBox.startY, + maxX: this.marqueeBox.currentX, + maxY: this.marqueeBox.currentY, + }, + { includeLocked: ev.shiftKey }, + ); + + if (ev.shiftKey && this.marqueeInitialSelectedIds.length > 0) { + doc.setSelected(Array.from(new Set([...this.marqueeInitialSelectedIds, ...hitIds]))); + } else { + doc.setSelected(hitIds); + } } } @@ -616,6 +631,7 @@ export class PointerRouter { this.scratchRenderer.stopEraserTrail(); } else if (this.state === 'SELECTING_MARQUEE') { this.marqueeBox = null; + this.marqueeInitialSelectedIds = []; this.onMarqueeUpdate?.(null); } else if (this.state === 'ZOOMING_SCRUB') { if (!this.zoomHasDragged) { @@ -703,7 +719,9 @@ export class PointerRouter { private performEraseAt(worldPoint: { x: number; y: number; }) { const doc = useDocumentStore.getState(); - const hitId = hitTestPoint(doc.elements, doc.elementIds, worldPoint, 12); + const hitId = hitTestPoint(doc.elements, doc.elementIds, worldPoint, 12, { + ignoreLocked: true, + }); if (hitId) { doc.deleteElements([hitId]); } diff --git a/src/stores/useConfigStore.ts b/src/stores/useConfigStore.ts index 0324a36..99b42a8 100644 --- a/src/stores/useConfigStore.ts +++ b/src/stores/useConfigStore.ts @@ -105,6 +105,7 @@ export const DEFAULT_CONFIG: ScriblConfig = { { mode: 'v', lhs: '', rhs: 'edit.paste', desc: 'Paste' }, { mode: 'v', lhs: '', rhs: 'edit.cut', desc: 'Cut' }, { mode: 'v', lhs: '', rhs: 'edit.duplicate', desc: 'Duplicate' }, + { mode: 'v', lhs: '', rhs: 'selection.toggle_lock', desc: 'Toggle Lock' }, ], toolbar: { position: 'bottom', diff --git a/src/stores/useDocumentStore.test.ts b/src/stores/useDocumentStore.test.ts index bd39be2..dc19db8 100644 --- a/src/stores/useDocumentStore.test.ts +++ b/src/stores/useDocumentStore.test.ts @@ -330,4 +330,123 @@ describe('useDocumentStore - movement and atomic undo/redo', () => { expect(reset.canRedo).toBe(false); }); }); + + describe('element locking support', () => { + const lockedStroke: StrokeElement = { + ...dummyStroke, + id: 's_locked', + locked: true, + }; + const unlockedStroke: StrokeElement = { + ...dummyStroke, + id: 's_unlocked', + locked: false, + }; + + beforeEach(() => { + const store = useDocumentStore.getState(); + store.resetDocument(); + store.addElement(lockedStroke); + store.addElement(unlockedStroke); + }); + + it('toggles lock on selected elements with undo/redo support', () => { + const store = useDocumentStore.getState(); + store.setSelected(['s_unlocked']); + + // Toggle lock -> should lock s_unlocked + store.toggleLockSelected(); + expect(useDocumentStore.getState().elements['s_unlocked'].locked).toBe(true); + + // Toggle lock again -> all selected are locked, so should unlock s_unlocked + store.toggleLockSelected(); + expect(useDocumentStore.getState().elements['s_unlocked'].locked).toBe(false); + + // Undo -> re-locks + useDocumentStore.getState().undo(); + expect(useDocumentStore.getState().elements['s_unlocked'].locked).toBe(true); + + // Undo again -> reverts to initially unlocked + useDocumentStore.getState().undo(); + expect(useDocumentStore.getState().elements['s_unlocked'].locked).toBe(false); + }); + + it('locks all selected elements if any selected element is unlocked', () => { + const store = useDocumentStore.getState(); + // Select both s_locked (true) and s_unlocked (false) + store.setSelected(['s_locked', 's_unlocked']); + + store.toggleLockSelected(); + const state = useDocumentStore.getState(); + expect(state.elements['s_locked'].locked).toBe(true); + expect(state.elements['s_unlocked'].locked).toBe(true); + }); + + it('deleteSelected ignores locked elements', () => { + const store = useDocumentStore.getState(); + store.setSelected(['s_locked', 's_unlocked']); + + store.deleteSelected(); + const state = useDocumentStore.getState(); + // s_locked must still exist! + expect(state.elementIds).toContain('s_locked'); + expect(state.elements['s_locked']).toBeDefined(); + // s_unlocked should be deleted + expect(state.elementIds).not.toContain('s_unlocked'); + expect(state.elements['s_unlocked']).toBeUndefined(); + }); + + it('deleteSelected is a no-op if all selected elements are locked', () => { + const store = useDocumentStore.getState(); + store.setSelected(['s_locked']); + const initialCanUndo = store.canUndo; + + store.deleteSelected(); + const state = useDocumentStore.getState(); + expect(state.elementIds).toContain('s_locked'); + expect(state.canUndo).toBe(initialCanUndo); + }); + + it('translateSelected and commitMoveSelected do not move locked elements', () => { + const store = useDocumentStore.getState(); + store.setSelected(['s_locked', 's_unlocked']); + + store.translateSelected(50, 50); + let state = useDocumentStore.getState(); + expect(state.elements['s_locked'].x).toBe(10); // Unmoved + expect(state.elements['s_unlocked'].x).toBe(60); // Moved + + store.commitMoveSelected(50, 50); + state = useDocumentStore.getState(); + expect(state.elements['s_locked'].x).toBe(10); + expect(state.elements['s_unlocked'].x).toBe(60); + }); + + it('clearDocument keeps locked elements and only removes unlocked elements', () => { + const store = useDocumentStore.getState(); + store.clearDocument(); + + const state = useDocumentStore.getState(); + expect(state.elementIds).toEqual(['s_locked']); + expect(state.elements['s_locked']).toBeDefined(); + expect(state.elements['s_unlocked']).toBeUndefined(); + expect(state.canUndo).toBe(true); + + // Undo restores the unlocked element + state.undo(); + const undone = useDocumentStore.getState(); + expect(undone.elementIds).toContain('s_unlocked'); + }); + + it('clearDocument is a no-op if all elements are locked', () => { + const store = useDocumentStore.getState(); + store.deleteElements(['s_unlocked']); + + const canUndoBefore = useDocumentStore.getState().history.canUndo(); + useDocumentStore.getState().clearDocument(); + + expect(useDocumentStore.getState().elements['s_locked']).toBeDefined(); + expect(useDocumentStore.getState().history.canUndo()).toBe(canUndoBefore); + }); + }); }); diff --git a/src/stores/useDocumentStore.ts b/src/stores/useDocumentStore.ts index 87bc092..132f881 100644 --- a/src/stores/useDocumentStore.ts +++ b/src/stores/useDocumentStore.ts @@ -8,6 +8,7 @@ import { ClearCanvasCommand, DeleteElementsCommand, MoveElementsCommand, + SetElementsLockCommand, TransformElementsCommand, } from '../core/history/commands'; import { HistoryStack } from '../core/history/HistoryStack'; @@ -44,6 +45,7 @@ interface DocumentState extends DocumentData { loadDocument: (data: { elements: Record; elementIds: string[]; }) => void; clearDocument: () => void; resetDocument: () => void; + toggleLockSelected: () => void; executeCommand: (command: Command) => void; } @@ -87,9 +89,12 @@ export const useDocumentStore = create((set, get) => ({ deleteElements: (ids: string[]) => { if (ids.length === 0) return; const { elements, elementIds, selectedIds, history } = get(); + const deletableIds = ids.filter((id) => !elements[id]?.locked); + if (deletableIds.length === 0) return; + const currentData: DocumentData = { elements, elementIds, selectedIds }; const nextData = history.execute( - new DeleteElementsCommand(ids, currentData), + new DeleteElementsCommand(deletableIds, currentData), currentData, ); set({ @@ -106,8 +111,11 @@ export const useDocumentStore = create((set, get) => ({ moveSelected: (dx: number, dy: number) => { const { elements, elementIds, selectedIds, history } = get(); if (selectedIds.length === 0 || (dx === 0 && dy === 0)) return; + const movableIds = selectedIds.filter((id) => !elements[id]?.locked); + if (movableIds.length === 0) return; + const currentData: DocumentData = { elements, elementIds, selectedIds }; - const nextData = history.execute(new MoveElementsCommand(selectedIds, dx, dy), currentData); + const nextData = history.execute(new MoveElementsCommand(movableIds, dx, dy), currentData); set({ ...nextData, canUndo: history.canUndo(), @@ -118,8 +126,11 @@ export const useDocumentStore = create((set, get) => ({ translateSelected: (dx: number, dy: number) => { const { elements, selectedIds } = get(); if (selectedIds.length === 0 || (dx === 0 && dy === 0)) return; + const movableIds = selectedIds.filter((id) => !elements[id]?.locked); + if (movableIds.length === 0) return; + const nextElements = { ...elements }; - for (const id of selectedIds) { + for (const id of movableIds) { const el = nextElements[id]; if (el) { nextElements[id] = applyElementDelta(el, dx, dy); @@ -129,9 +140,12 @@ export const useDocumentStore = create((set, get) => ({ }, commitMoveSelected: (totalDx: number, totalDy: number) => { - const { selectedIds, history } = get(); + const { elements, selectedIds, history } = get(); if (selectedIds.length === 0 || (totalDx === 0 && totalDy === 0)) return; - history.pushExecuted(new MoveElementsCommand([...selectedIds], totalDx, totalDy)); + const movableIds = selectedIds.filter((id) => !elements[id]?.locked); + if (movableIds.length === 0) return; + + history.pushExecuted(new MoveElementsCommand([...movableIds], totalDx, totalDy)); set({ canUndo: history.canUndo(), canRedo: history.canRedo(), @@ -139,8 +153,16 @@ export const useDocumentStore = create((set, get) => ({ }, transformSelectedLive: (updated: Record) => { + const { elements } = get(); + const filtered: Record = {}; + for (const [id, el] of Object.entries(updated)) { + if (!elements[id]?.locked) { + filtered[id] = el; + } + } + if (Object.keys(filtered).length === 0) return; set((state) => ({ - elements: { ...state.elements, ...updated }, + elements: { ...state.elements, ...filtered }, })); }, @@ -148,9 +170,10 @@ export const useDocumentStore = create((set, get) => ({ initial: Record, final: Record, ) => { - const { selectedIds, history } = get(); - if (selectedIds.length === 0) return; - history.pushExecuted(new TransformElementsCommand([...selectedIds], initial, final)); + const { elements, selectedIds, history } = get(); + const transformableIds = selectedIds.filter((id) => !elements[id]?.locked); + if (transformableIds.length === 0) return; + history.pushExecuted(new TransformElementsCommand([...transformableIds], initial, final)); set({ canUndo: history.canUndo(), canRedo: history.canRedo(), @@ -314,6 +337,8 @@ export const useDocumentStore = create((set, get) => ({ clearDocument: () => { const { elements, elementIds, selectedIds, history } = get(); if (elementIds.length === 0) return; + const hasUnlocked = elementIds.some((id) => !elements[id]?.locked); + if (!hasUnlocked) return; const currentData: DocumentData = { elements, elementIds, selectedIds }; const nextData = history.execute(new ClearCanvasCommand(currentData), currentData); @@ -335,6 +360,23 @@ export const useDocumentStore = create((set, get) => ({ }); }, + toggleLockSelected: () => { + const { elements, selectedIds, executeCommand } = get(); + if (selectedIds.length === 0) return; + + const anyUnlocked = selectedIds.some((id) => !elements[id]?.locked); + const targetLocked = anyUnlocked; + + const previousStates: Record = {}; + for (const id of selectedIds) { + if (elements[id]) { + previousStates[id] = elements[id].locked ?? false; + } + } + + executeCommand(new SetElementsLockCommand([...selectedIds], targetLocked, previousStates)); + }, + executeCommand: (command) => { const { elements, elementIds, selectedIds, history } = get(); const currentData: DocumentData = { elements, elementIds, selectedIds }; diff --git a/src/types/canvas.ts b/src/types/canvas.ts index a874d41..2a10356 100644 --- a/src/types/canvas.ts +++ b/src/types/canvas.ts @@ -18,6 +18,7 @@ export interface BaseElement { width: number; height: number; zIndex: number; + locked?: boolean; } export interface StrokeElement extends BaseElement {