diff --git a/packages/mask-editor/src/ui/components/PointerZone.test.ts b/packages/mask-editor/src/ui/components/PointerZone.test.ts index e7e7e9abdb4..aa7e8b5bc29 100644 --- a/packages/mask-editor/src/ui/components/PointerZone.test.ts +++ b/packages/mask-editor/src/ui/components/PointerZone.test.ts @@ -54,17 +54,20 @@ describe('PointerZone', () => { it.for([ ['pointerdown', 'handlePointerDown'], ['pointermove', 'handlePointerMove'], - ['pointerup', 'handlePointerUp'] + ['pointerup', 'handlePointerUp'], + ['pointercancel', 'handlePointerUp'] ] as const)( 'should forward %s to toolManager.%s', async ([eventName, handlerName]) => { renderZone() const zone = getZone() - zone.dispatchEvent(new Event(eventName, { bubbles: true })) + const event = new PointerEvent(eventName, { bubbles: true }) + zone.dispatchEvent(event) await nextTick() expect(mockToolManager[handlerName]).toHaveBeenCalledTimes(1) + expect(mockToolManager[handlerName]).toHaveBeenCalledWith(event) } ) diff --git a/packages/mask-editor/src/ui/components/PointerZone.vue b/packages/mask-editor/src/ui/components/PointerZone.vue index f4d9e876037..2141f7816b1 100644 --- a/packages/mask-editor/src/ui/components/PointerZone.vue +++ b/packages/mask-editor/src/ui/components/PointerZone.vue @@ -6,6 +6,7 @@ @pointerdown="handlePointerDown" @pointermove="handlePointerMove" @pointerup="handlePointerUp" + @pointercancel="handlePointerUp" @pointerleave="handlePointerLeave" @pointerenter="handlePointerEnter" @touchstart="handleTouchStart" diff --git a/packages/mask-editor/src/ui/components/ToolPanel.test.ts b/packages/mask-editor/src/ui/components/ToolPanel.test.ts index 9a02aab8622..15e3eeb240e 100644 --- a/packages/mask-editor/src/ui/components/ToolPanel.test.ts +++ b/packages/mask-editor/src/ui/components/ToolPanel.test.ts @@ -110,12 +110,19 @@ describe('ToolPanel', () => { expect(screen.getByTestId('zoom-percentage').textContent).toBe('124%') }) - it('should render image dimensions when an image is loaded', () => { - mockStore.image = new Image(800, 600) - renderPanel() + it.for([ + { dimensions: undefined, expected: '800x600' }, + { dimensions: { width: 600, height: 800 }, expected: '600x800' } + ])( + 'renders $expected for the current document dimensions $dimensions', + ({ dimensions, expected }) => { + mockStore.image = new Image(800, 600) + mockStore.canvasHistory = { ...mockStore.canvasHistory, dimensions } + renderPanel() - expect(screen.getByTestId('zoom-dimensions').textContent).toBe('800x600') - }) + expect(screen.getByTestId('zoom-dimensions').textContent).toBe(expected) + } + ) it('should render a single-space placeholder when no image', () => { mockStore.image = null diff --git a/packages/mask-editor/src/ui/components/ToolPanel.vue b/packages/mask-editor/src/ui/components/ToolPanel.vue index d495c3ab65f..3c192cbe8e7 100644 --- a/packages/mask-editor/src/ui/components/ToolPanel.vue +++ b/packages/mask-editor/src/ui/components/ToolPanel.vue @@ -61,7 +61,7 @@ const currentTool = computed(() => store.currentTool) const zoomText = computed(() => `${Math.round(store.displayZoomRatio * 100)}%`) const dimensionsText = computed(() => { - const img = store.image + const img = store.canvasHistory.dimensions ?? store.image return img ? `${img.width}x${img.height}` : ' ' }) diff --git a/packages/mask-editor/src/useBrushDrawing.test.ts b/packages/mask-editor/src/useBrushDrawing.test.ts index ea38da00196..166f9386c53 100644 --- a/packages/mask-editor/src/useBrushDrawing.test.ts +++ b/packages/mask-editor/src/useBrushDrawing.test.ts @@ -1,6 +1,7 @@ import { useMaskEditorStore } from './maskEditorStore' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { effectScope, ref } from 'vue' +import { afterEach, assert, beforeEach, describe, expect, it, vi } from 'vitest' +import { fromPartial } from '@total-typescript/shoehorn' +import { effectScope, nextTick, ref } from 'vue' import type { EffectScope } from 'vue' import { BrushShape, Tools } from './types' @@ -37,7 +38,6 @@ vi.mock(import('./useGPUResources'), () => { compositeStroke, copyGpuToCanvas, gpuRender: vi.fn(), - gpuDrawPoint: vi.fn(), clearGPU: vi.fn(), destroy: vi.fn(), initGPUResources: vi.fn().mockResolvedValue(undefined), @@ -65,15 +65,16 @@ import { useBrushDrawing } from './useBrushDrawing' function makePointerEvent( x: number, y: number, - opts: { buttons?: number; shiftKey?: boolean } = {} + opts: { buttons?: number; shiftKey?: boolean; pointerId?: number } = {} ): PointerEvent { - return { + return fromPartial({ offsetX: x, offsetY: y, + pointerId: opts.pointerId ?? 1, buttons: opts.buttons ?? 1, shiftKey: opts.shiftKey ?? false, preventDefault: vi.fn() - } as unknown as PointerEvent + }) } function makeMockCtx(): CanvasRenderingContext2D { @@ -187,31 +188,80 @@ describe('startDrawing error handling', () => { describe('startDrawing shift+click', () => { it('draws a line from the previous point when shift is held', async () => { - const { startDrawing } = setup() + const { startDrawing, drawEnd } = setup() + const ctx = mockStoreDef.maskCtx + assert.exists(ctx) await startDrawing(makePointerEvent(50, 50)) + await drawEnd(makePointerEvent(50, 50)) + vi.mocked(ctx.fill).mockClear() await startDrawing(makePointerEvent(100, 50, { shiftKey: true })) - expect( - (mockStoreDef.maskCtx as unknown as ReturnType) - .beginPath - ).toHaveBeenCalled() + expect(ctx.fill).toHaveBeenCalled() }) }) describe('handleDrawing', () => { - it('updates smoothingLastDrawTime after each move event', async () => { - const rafSpy = vi - .spyOn(window, 'requestAnimationFrame') - .mockImplementation((cb) => { - cb(0) - return 0 - }) + it('ignores another pointer without changing the active stroke', async () => { const { startDrawing, handleDrawing } = setup() - await startDrawing(makePointerEvent(50, 50)) - await handleDrawing(makePointerEvent(55, 55)) - expect(rafSpy).toHaveBeenCalled() - rafSpy.mockRestore() + await startDrawing(makePointerEvent(40, 60, { pointerId: 11 })) + await handleDrawing(makePointerEvent(50, 65, { pointerId: 11 })) + vi.advanceTimersToNextFrame() + const fill = vi.mocked(mockStoreDef.maskCtx!.fill) + fill.mockClear() + + await handleDrawing( + makePointerEvent(110, 85, { + pointerId: 22, + buttons: 2 + }) + ) + vi.advanceTimersToNextFrame() + + expect(fill).not.toHaveBeenCalled() + expect(mockStoreDef.maskCtx!.globalCompositeOperation).toBe('source-over') + + await handleDrawing( + makePointerEvent(110, 85, { + pointerId: 11, + buttons: 2 + }) + ) + vi.advanceTimersToNextFrame() + + expect(fill).toHaveBeenCalled() + expect(mockStoreDef.maskCtx!.globalCompositeOperation).toBe( + 'destination-out' + ) }) + it.for([11, 22])( + 'discards queued moves when a new stroke starts with pointer %s', + async (pointerId) => { + const { startDrawing, handleDrawing, drawEnd } = setup() + await startDrawing(makePointerEvent(40, 60, { pointerId: 11 })) + await handleDrawing( + makePointerEvent(110, 85, { + pointerId: 11, + buttons: 2 + }) + ) + await handleDrawing( + makePointerEvent(140, 90, { + pointerId: 11, + buttons: 2 + }) + ) + await drawEnd(new PointerEvent('pointerup', { pointerId: 11 })) + await startDrawing(makePointerEvent(30, 25, { pointerId })) + const fill = vi.mocked(mockStoreDef.maskCtx!.fill) + fill.mockClear() + + vi.advanceTimersToNextFrame() + + expect(fill).not.toHaveBeenCalled() + expect(mockStoreDef.maskCtx!.globalCompositeOperation).toBe('source-over') + } + ) + it('sets DestinationOut composition when tool is eraser during move', async () => { mockStoreDef.currentTool = Tools.Eraser vi.spyOn(window, 'requestAnimationFrame').mockImplementation((cb) => { @@ -272,6 +322,134 @@ describe('drawEnd canvas visibility', () => { }) describe('drawEnd', () => { + it('keeps a new stroke visible when the previous GPU readback completes', async () => { + const gpu = useGPUResources() + gpu.hasRenderer.value = true + gpu.previewCanvas.value = document.createElement('canvas') + type Readback = Awaited> + let finishReadback: ((value: Readback) => void) | undefined + const readback = new Promise((resolve) => { + finishReadback = resolve + }) + vi.mocked(gpu.copyGpuToCanvas).mockReturnValueOnce(readback) + const { startDrawing, drawEnd } = setup() + + await startDrawing(makePointerEvent(40, 60, { pointerId: 11 })) + const ending = drawEnd(makePointerEvent(50, 65, { pointerId: 11 })) + await startDrawing(makePointerEvent(80, 90, { pointerId: 22 })) + assert.exists(finishReadback) + finishReadback({ + maskData: new ImageData(200, 200), + rgbData: new ImageData(200, 200) + }) + await ending + + expect(gpu.clearPreview).not.toHaveBeenCalled() + expect(mockStoreDef.maskCanvas?.style.opacity).toBe('0') + expect(gpu.previewCanvas.value.style.opacity).toBe( + String(mockStoreDef.maskOpacity) + ) + await drawEnd(makePointerEvent(90, 95, { pointerId: 22 })) + expect(gpu.clearPreview).toHaveBeenCalledOnce() + expect(mockStoreDef.maskCanvas?.style.opacity).toBe( + String(mockStoreDef.maskOpacity) + ) + expect(saveStateSpy).toHaveBeenCalledTimes(2) + }) + + it.for(['pointerup', 'pointercancel'])( + 'finishes the owning stroke on %s outside the pointer zone', + async (type) => { + const zone = document.createElement('div') + vi.spyOn(zone, 'getBoundingClientRect').mockReturnValue( + new DOMRect(20, 10, 200, 200) + ) + mockStoreDef.pointerZone = zone + const ctx = mockStoreDef.maskCtx + assert.exists(ctx) + const { startDrawing, drawEnd } = setup() + await startDrawing(makePointerEvent(40, 60, { pointerId: 11 })) + window.dispatchEvent(new PointerEvent(type, { pointerId: 22 })) + await nextTick() + expect(saveStateSpy).not.toHaveBeenCalled() + + const end = new PointerEvent(type, { + pointerId: 11, + clientX: 120, + clientY: 90 + }) + window.dispatchEvent(end) + await nextTick() + expect(saveStateSpy).toHaveBeenCalledOnce() + await drawEnd(end) + expect(saveStateSpy).toHaveBeenCalledOnce() + + vi.mocked(ctx.arc).mockClear() + await startDrawing( + makePointerEvent(130, 80, { pointerId: 11, shiftKey: true }) + ) + expect(ctx.arc).toHaveBeenCalledWith( + 101, + 80, + expect.any(Number), + 0, + Math.PI * 2, + false + ) + await drawEnd( + new PointerEvent('pointerup', { + pointerId: 11, + clientX: 150, + clientY: 90 + }) + ) + expect(saveStateSpy).toHaveBeenCalledTimes(2) + } + ) + + it('stops listening for pointer completion when the editor scope closes', async () => { + const { startDrawing } = setup() + await startDrawing(makePointerEvent(40, 60, { pointerId: 11 })) + scope?.stop() + window.dispatchEvent(new PointerEvent('pointerup', { pointerId: 11 })) + await nextTick() + expect(saveStateSpy).not.toHaveBeenCalled() + }) + + it.for(['pointerup', 'pointercancel'])( + 'preserves the first stroke when a second pointer starts and sends %s', + async (type) => { + const { startDrawing, handleDrawing, drawEnd } = setup() + const ctx = mockStoreDef.maskCtx + assert.exists(ctx) + await startDrawing(makePointerEvent(40, 60, { pointerId: 11 })) + await handleDrawing(makePointerEvent(50, 65, { pointerId: 11 })) + vi.advanceTimersToNextFrame() + await startDrawing( + makePointerEvent(180, 180, { pointerId: 22, buttons: 2 }) + ) + await drawEnd( + new PointerEvent(type, { pointerType: 'pen', pointerId: 22 }) + ) + + expect(saveStateSpy).not.toHaveBeenCalled() + expect(useGPUResources().prepareStroke).toHaveBeenCalledOnce() + expect(ctx.globalCompositeOperation).toBe('source-over') + vi.mocked(ctx.fill).mockClear() + await handleDrawing(makePointerEvent(90, 95, { pointerId: 11 })) + vi.advanceTimersToNextFrame() + expect(ctx.fill).toHaveBeenCalled() + await drawEnd( + new PointerEvent(type, { pointerType: 'pen', pointerId: 11 }) + ) + expect(saveStateSpy).toHaveBeenCalledOnce() + + await startDrawing(makePointerEvent(180, 180, { pointerId: 22 })) + await drawEnd(new PointerEvent('pointerup', { pointerId: 22 })) + expect(saveStateSpy).toHaveBeenCalledTimes(2) + } + ) + it('calls compositeStroke indicating the active layer and erasing state', async () => { const { startDrawing, drawEnd } = setup() await startDrawing(makePointerEvent(50, 50)) diff --git a/packages/mask-editor/src/useBrushDrawing.ts b/packages/mask-editor/src/useBrushDrawing.ts index 5b5bea253f9..5e866ed6575 100644 --- a/packages/mask-editor/src/useBrushDrawing.ts +++ b/packages/mask-editor/src/useBrushDrawing.ts @@ -1,4 +1,5 @@ import { nextTick, ref } from 'vue' +import { useEventListener } from '@vueuse/core' import { CompositionOperation, Tools } from './types' import type { Point2D as Point } from '@comfyorg/shared-frontend-utils/geometry' @@ -27,16 +28,13 @@ export function useBrushDrawing(initialSettings?: { useBrushAdjustment(initialSettings) const gpu = useGPUResources() - const isDrawing = ref(false) const isDrawingLine = ref(false) const lineStartPoint = ref(null) const lineRemainder = ref(0) - const smoothingLastDrawTime = ref(new Date()) const initialDraw = ref(true) let strokeProcessor: StrokeProcessor | null = null - - // ── CPU drawing path ───────────────────────────────────────────────────────── + let drawingPointerId: number | undefined function drawShape(point: Point, overrideOpacity?: number) { const brush = store.brushSettings @@ -93,8 +91,6 @@ export function useBrushDrawing(initialSettings?: { ) } - // ── Drawing orchestration ──────────────────────────────────────────────────── - function initShape(compositionOperation: CompositionOperation) { const blendMode = store.maskBlendMode const mask_ctx = store.maskCtx @@ -161,7 +157,8 @@ export function useBrushDrawing(initialSettings?: { } async function startDrawing(event: PointerEvent): Promise { - isDrawing.value = true + if (drawingPointerId !== undefined) return + drawingPointerId = event.pointerId gpu.dirtyRect.value = resetDirtyRect() try { @@ -214,7 +211,6 @@ export function useBrushDrawing(initialSettings?: { strokeProcessor = new StrokeProcessor(targetSpacing) await drawWithBetterSmoothing(coords_canvas) - smoothingLastDrawTime.value = new Date() } catch (error) { /* c8 ignore start */ const isRgb = store.activeLayer === 'rgb' @@ -225,61 +221,53 @@ export function useBrushDrawing(initialSettings?: { gpu.clearPreview() /* c8 ignore stop */ console.error('[useBrushDrawing] Failed to start drawing:', error) - isDrawing.value = false + drawingPointerId = undefined isDrawingLine.value = false } } async function handleDrawing(event: PointerEvent): Promise { - const diff = performance.now() - smoothingLastDrawTime.value.getTime() + if (event.pointerId !== drawingPointerId) return + + const activeStroke = strokeProcessor const coords = { x: event.offsetX, y: event.offsetY } const coords_canvas = coordinateTransform.screenToCanvas(coords) const currentTool = store.currentTool - if (diff > 20 && !isDrawing.value) { - requestAnimationFrame(async () => { - if (!isDrawing.value) return - try { - initShape(CompositionOperation.SourceOver) - if (gpu.hasRenderer.value) { - await gpu.gpuDrawPoint(coords_canvas) - } else { - drawShape(coords_canvas) - } - } catch (error) { - console.error('[useBrushDrawing] Drawing error:', error) - } - }) - } else { - requestAnimationFrame(async () => { - if (!isDrawing.value) return - try { - if (currentTool === 'eraser' || event.buttons === 2) { - initShape(CompositionOperation.DestinationOut) - } else { - initShape(CompositionOperation.SourceOver) - } - await drawWithBetterSmoothing(coords_canvas) - } catch (error) { - console.error('[useBrushDrawing] Drawing error:', error) - } - }) - } - - smoothingLastDrawTime.value = new Date() + requestAnimationFrame(async () => { + if ( + event.pointerId !== drawingPointerId || + activeStroke !== strokeProcessor + ) + return + try { + const compositionOp = + currentTool === 'eraser' || event.buttons === 2 + ? CompositionOperation.DestinationOut + : CompositionOperation.SourceOver + initShape(compositionOp) + await drawWithBetterSmoothing(coords_canvas) + } catch (error) { + console.error('[useBrushDrawing] Drawing error:', error) + } + }) } async function drawEnd(event: PointerEvent): Promise { - const coords = { x: event.offsetX, y: event.offsetY } - const coords_canvas = coordinateTransform.screenToCanvas(coords) + if (drawingPointerId === undefined || event.pointerId !== drawingPointerId) + return - if (!isDrawing.value) return + const rect = store.pointerZone?.getBoundingClientRect() + const coords = rect + ? { x: event.clientX - rect.left, y: event.clientY - rect.top } + : { x: event.offsetX, y: event.offsetY } + const coords_canvas = coordinateTransform.screenToCanvas(coords) - isDrawing.value = false + drawingPointerId = undefined lineStartPoint.value = coords_canvas initialDraw.value = true - // Flush remaining stroke points + const completedStroke = strokeProcessor if (strokeProcessor) { const finalPoints = strokeProcessor.endStroke() if (finalPoints.length > 0) { @@ -290,17 +278,14 @@ export function useBrushDrawing(initialSettings?: { for (const p of finalPoints) drawShape(p) } } - strokeProcessor = null } - // Composite GPU stroke into the main texture const isRgb = store.activeLayer === 'rgb' const isErasing = store.currentTool === 'eraser' || store.maskCtx?.globalCompositeOperation === 'destination-out' gpu.compositeStroke(isRgb, isErasing) - // Read back GPU result let maskData: ImageData | undefined let rgbData: ImageData | undefined if (gpu.hasRenderer.value) { @@ -315,7 +300,6 @@ export function useBrushDrawing(initialSettings?: { /* c8 ignore stop */ } - // Save to history gpu.isSavingHistory.value = true try { store.canvasHistory.saveState(maskData, rgbData) @@ -324,9 +308,10 @@ export function useBrushDrawing(initialSettings?: { gpu.isSavingHistory.value = false } + if (strokeProcessor !== completedStroke) return + strokeProcessor = null gpu.clearPreview() - // Restore canvas visibility if (isRgb && store.rgbCanvas) { store.rgbCanvas.style.opacity = '1' } else if (!isRgb && store.maskCanvas) { @@ -337,6 +322,10 @@ export function useBrushDrawing(initialSettings?: { } } + useEventListener(window, ['pointerup', 'pointercancel'], drawEnd, { + capture: true + }) + return { startDrawing, handleDrawing, diff --git a/packages/mask-editor/src/useCanvasHistory.test.ts b/packages/mask-editor/src/useCanvasHistory.test.ts index 94b14fd8ced..606cfe498fb 100644 --- a/packages/mask-editor/src/useCanvasHistory.test.ts +++ b/packages/mask-editor/src/useCanvasHistory.test.ts @@ -462,4 +462,33 @@ describe('useCanvasHistory', () => { expect(window.requestAnimationFrame).toHaveBeenCalled() }) }) + it('invalidates old revisions after edits, undo, redo, and clear', () => { + const history = useCanvasHistory(layers) + history.saveInitialState() + const revisions = [history.revision.value] + history.saveState() + revisions.push(history.revision.value) + history.undo() + revisions.push(history.revision.value) + history.redo() + revisions.push(history.revision.value) + history.clearStates() + revisions.push(history.revision.value) + expect( + revisions.every( + (value, index) => index === 0 || value > revisions[index - 1] + ) + ).toBe(true) + }) + + it('invalidates old revisions when a full history keeps the same index', () => { + const history = useCanvasHistory(layers, 2) + history.saveInitialState() + history.saveState() + const before = history.revision.value + const index = history.currentStateIndex.value + history.saveState() + expect(history.currentStateIndex.value).toBe(index) + expect(history.revision.value).toBeGreaterThan(before) + }) }) diff --git a/packages/mask-editor/src/useCanvasHistory.ts b/packages/mask-editor/src/useCanvasHistory.ts index 31d60a040e7..cce9c942b23 100644 --- a/packages/mask-editor/src/useCanvasHistory.ts +++ b/packages/mask-editor/src/useCanvasHistory.ts @@ -1,6 +1,5 @@ import { ref, computed } from 'vue' -// Define the state interface for better readability interface CanvasState { mask: ImageData | ImageBitmap rgb: ImageData | ImageBitmap @@ -20,6 +19,13 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { const states = ref([]) const currentStateIndex = ref(-1) const initialized = ref(false) + const revision = ref(0) + const dimensions = computed(() => { + const current = states.value.at(currentStateIndex.value)?.mask + return current + ? { width: current.width, height: current.height } + : undefined + }) const canUndo = computed( () => states.value.length > 1 && currentStateIndex.value > 0 @@ -35,7 +41,6 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { const saveInitialState = () => { const { maskCtx, rgbCtx, imgCtx, maskCanvas, rgbCanvas, imgCanvas } = layers - // Ensure all 3 contexts and canvases are ready if ( !maskCtx || !rgbCtx || @@ -55,7 +60,6 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { states.value = [] - // Capture all three layers const maskState = maskCtx.getImageData( 0, 0, @@ -78,6 +82,7 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { states.value.push({ mask: maskState, rgb: rgbState, img: imgState }) currentStateIndex.value = 0 initialized.value = true + revision.value++ } const saveState = ( @@ -102,7 +107,6 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { return } - // Clear redo history states.value = states.value.slice(0, currentStateIndex.value + 1) let maskState: ImageData | ImageBitmap @@ -127,7 +131,6 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { states.value.push({ mask: maskState, rgb: rgbState, img: imgState }) currentStateIndex.value++ - // Maintain max history size and clean up memory if (states.value.length > maxStates) { const removed = states.value.shift() if (removed) { @@ -135,18 +138,21 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { } currentStateIndex.value-- } + revision.value++ } const undo = () => { if (!canUndo.value) return currentStateIndex.value-- restoreState(states.value[currentStateIndex.value]) + revision.value++ } const redo = () => { if (!canRedo.value) return currentStateIndex.value++ restoreState(states.value[currentStateIndex.value]) + revision.value++ } const restoreState = (state: CanvasState) => { @@ -161,7 +167,6 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { ) return - // Update canvas dimensions to match state (handles rotation undo/redo) const refData = state.mask const newWidth = refData.width const newHeight = refData.height @@ -202,11 +207,14 @@ export function useCanvasHistory(layers: CanvasHistoryLayers, maxStates = 20) { states.value = [] currentStateIndex.value = -1 initialized.value = false + revision.value++ } return { canUndo, canRedo, + revision, + dimensions, currentStateIndex, saveInitialState, saveState, diff --git a/packages/mask-editor/src/useCanvasTransform.test.ts b/packages/mask-editor/src/useCanvasTransform.test.ts index d7c9ac9ae5b..eedda125c13 100644 --- a/packages/mask-editor/src/useCanvasTransform.test.ts +++ b/packages/mask-editor/src/useCanvasTransform.test.ts @@ -225,6 +225,26 @@ describe('useCanvasTransform', () => { expect(mockStore.gpuTextureHeight).toBe(100) }) + it('saves GPU rotation without SharedArrayBuffer support', async () => { + vi.stubGlobal('SharedArrayBuffer', undefined) + mockStore.tgpuRoot = fromPartial>( + {} + ) + + await useCanvasTransform().rotateClockwise() + + expect(mockCanvasHistory.saveState).toHaveBeenCalledWith( + expect.objectContaining({ width: 50, height: 100 }), + expect.objectContaining({ width: 50, height: 100 }), + expect.objectContaining({ width: 50, height: 100 }) + ) + expect(mockStore.pendingGPUMaskData?.buffer).toBeInstanceOf(ArrayBuffer) + expect(mockStore.pendingGPURgbData?.buffer).toBeInstanceOf(ArrayBuffer) + expect(mockStore.pendingGPUMaskData?.slice(0, 4)).toEqual( + new Uint8ClampedArray([255, 0, 0, 255]) + ) + }) + it('should not recreate GPU textures when GPU is inactive', async () => { mockStore.tgpuRoot = null diff --git a/packages/mask-editor/src/useCanvasTransform.ts b/packages/mask-editor/src/useCanvasTransform.ts index 37b15c25929..d40250debba 100644 --- a/packages/mask-editor/src/useCanvasTransform.ts +++ b/packages/mask-editor/src/useCanvasTransform.ts @@ -102,25 +102,8 @@ export function useCanvasTransform() { const maskImageData = store.maskCtx.getImageData(0, 0, width, height) const rgbImageData = store.rgbCtx.getImageData(0, 0, width, height) - const maskData = new Uint8ClampedArray( - new ArrayBuffer(maskImageData.data.length) - ) - const rgbData = new Uint8ClampedArray( - new ArrayBuffer(rgbImageData.data.length) - ) - - maskData.set(maskImageData.data) - rgbData.set(rgbImageData.data) - - if ( - maskData.buffer instanceof SharedArrayBuffer || - rgbData.buffer instanceof SharedArrayBuffer - ) { - console.error( - '[useCanvasTransform] SharedArrayBuffer detected, WebGPU writeTexture will fail' - ) - return - } + const maskData = new Uint8ClampedArray(maskImageData.data) + const rgbData = new Uint8ClampedArray(rgbImageData.data) premultiplyData(maskData) premultiplyData(rgbData) diff --git a/packages/mask-editor/src/useGPUResources.test.ts b/packages/mask-editor/src/useGPUResources.test.ts index b6d9d1aeeca..74b283ee9be 100644 --- a/packages/mask-editor/src/useGPUResources.test.ts +++ b/packages/mask-editor/src/useGPUResources.test.ts @@ -1,7 +1,7 @@ import { useMaskEditorStore } from './maskEditorStore' import { fromPartial } from '@total-typescript/shoehorn' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { effectScope, nextTick } from 'vue' +import { effectScope, nextTick, reactive } from 'vue' import type { EffectScope } from 'vue' vi.mock(import('typegpu'), () => ({ @@ -33,6 +33,7 @@ let mockStore: ReturnType import { resetDirtyRect } from './brushDrawingUtils' import { useGPUResources } from './useGPUResources' +import { useCanvasHistory } from './useCanvasHistory' let scope: EffectScope | null = null @@ -41,6 +42,71 @@ function setup() { return scope.run(() => useGPUResources())! } +async function initializeGPU() { + vi.stubGlobal('GPUTextureUsage', { + COPY_DST: 2, + COPY_SRC: 1, + RENDER_ATTACHMENT: 16, + STORAGE_BINDING: 8, + TEXTURE_BINDING: 4 + }) + vi.stubGlobal('GPUBufferUsage', { + COPY_DST: 8, + COPY_SRC: 4, + STORAGE: 128, + MAP_READ: 1 + }) + vi.stubGlobal('ImageBitmap', class {}) + vi.stubGlobal('navigator', { + gpu: { getPreferredCanvasFormat: () => 'rgba8unorm' } + }) + const context = fromPartial({ + getImageData: vi.fn( + (_x: number, _y: number, width: number, height: number) => + fromPartial({ + width, + height, + data: new Uint8ClampedArray(width * height * 4).fill(255) + }) + ), + putImageData: vi.fn() + }) + const gpuDevice = { + createTexture: vi.fn(({ size }: GPUTextureDescriptor) => { + const [width, height] = + 'width' in size ? [size.width, size.height ?? 1] : [...size] + return fromPartial({ width, height, destroy: vi.fn() }) + }), + createBuffer: vi.fn(() => fromPartial({ destroy: vi.fn() })), + queue: { writeTexture: vi.fn() } + } + mockStore.tgpuRoot = fromPartial>({ + device: gpuDevice + }) + mockStore.maskCanvas = fromPartial({ + width: 4, + height: 3, + getContext: vi.fn(() => context) + }) + mockStore.rgbCanvas = fromPartial({ + width: 4, + height: 3, + getContext: vi.fn(() => context) + }) + mockStore.imgCanvas = fromPartial({ + width: 4, + height: 3, + getContext: vi.fn(() => context) + }) + mockStore.maskCtx = context + mockStore.rgbCtx = context + mockStore.imgCtx = context + mockStore.canvasHistory = reactive(useCanvasHistory(mockStore, 2)) + const resources = setup() + await resources.initGPUResources() + return { resources, gpuDevice } +} + beforeEach(() => { mockStore = useMaskEditorStore() mockStore.tgpuRoot = null @@ -49,7 +115,7 @@ beforeEach(() => { mockStore.maskCtx = null mockStore.rgbCtx = null mockStore.clearTrigger = 0 - mockStore.canvasHistory.currentStateIndex = 0 + mockStore.canvasHistory.revision = 0 mockStore.gpuTexturesNeedRecreation = false }) @@ -136,17 +202,85 @@ describe('watchers', () => { await nextTick() }) - it('currentStateIndex watcher short-circuits when isSavingHistory is true', async () => { - const { isSavingHistory } = setup() - isSavingHistory.value = true - mockStore.canvasHistory.currentStateIndex++ + it.for([ + { saving: false, uploads: 2 }, + { saving: true, uploads: 0 } + ])( + 'uploads $uploads layers for a full-history save when saving=$saving', + async ({ saving, uploads }) => { + const { resources, gpuDevice } = await initializeGPU() + mockStore.canvasHistory.saveInitialState() + mockStore.canvasHistory.saveState() + await nextTick() + expect(mockStore.canvasHistory.currentStateIndex).toBe(1) + gpuDevice.queue.writeTexture.mockClear() + gpuDevice.createTexture.mockClear() + resources.isSavingHistory.value = saving + + mockStore.canvasHistory.saveState() + await nextTick() + + expect(mockStore.canvasHistory.currentStateIndex).toBe(1) + expect(gpuDevice.queue.writeTexture).toHaveBeenCalledTimes(uploads) + expect(gpuDevice.createTexture).not.toHaveBeenCalled() + } + ) + + it('keeps uploaded texture dimensions aligned with rotation, undo, and redo', async () => { + const { gpuDevice } = await initializeGPU() + mockStore.canvasHistory.saveInitialState() + await nextTick() + mockStore.maskCanvas!.width = 3 + mockStore.maskCanvas!.height = 4 + mockStore.rgbCanvas!.width = 3 + mockStore.rgbCanvas!.height = 4 + mockStore.imgCanvas!.width = 3 + mockStore.imgCanvas!.height = 4 + gpuDevice.queue.writeTexture.mockClear() + + mockStore.canvasHistory.saveState() await nextTick() - }) - it('currentStateIndex watcher calls updateGPUFromCanvas when not saving history', async () => { - setup() - mockStore.canvasHistory.currentStateIndex++ + expect( + gpuDevice.queue.writeTexture.mock.calls.map(([target, , , extent]) => [ + target.texture.width, + target.texture.height, + extent + ]) + ).toEqual([ + [3, 4, { width: 3, height: 4 }], + [3, 4, { width: 3, height: 4 }] + ]) + gpuDevice.queue.writeTexture.mockClear() + + mockStore.canvasHistory.undo() await nextTick() + + expect( + gpuDevice.queue.writeTexture.mock.calls.map(([target, , , extent]) => [ + target.texture.width, + target.texture.height, + extent + ]) + ).toEqual([ + [4, 3, { width: 4, height: 3 }], + [4, 3, { width: 4, height: 3 }] + ]) + gpuDevice.queue.writeTexture.mockClear() + + mockStore.canvasHistory.redo() + await nextTick() + + expect( + gpuDevice.queue.writeTexture.mock.calls.map(([target, , , extent]) => [ + target.texture.width, + target.texture.height, + extent + ]) + ).toEqual([ + [3, 4, { width: 3, height: 4 }], + [3, 4, { width: 3, height: 4 }] + ]) }) it('gpuTexturesNeedRecreation watcher returns early when device is not initialised', async () => { @@ -176,71 +310,13 @@ describe('initPreviewCanvas', () => { }) describe('gpuRender', () => { - it('resolves immediately when renderer is not initialised', async () => { - const { gpuDrawPoint } = setup() - await expect(gpuDrawPoint({ x: 10, y: 20 })).resolves.toBeUndefined() - }) - it('uses full coverage for GPU stroke paths', async () => { - vi.stubGlobal('GPUTextureUsage', { - COPY_DST: 0x0002, - COPY_SRC: 0x0001, - RENDER_ATTACHMENT: 0x0010, - STORAGE_BINDING: 0x0008, - TEXTURE_BINDING: 0x0004 - }) - Object.defineProperty(navigator, 'gpu', { - configurable: true, - value: { getPreferredCanvasFormat: vi.fn(() => 'rgba8unorm') } - }) - - const imageData = fromPartial({ - data: new Uint8ClampedArray(4 * 4 * 4) - }) - const context = fromPartial({ - getImageData: vi.fn(() => imageData), - putImageData: vi.fn() - }) - const gpuDevice = { - createTexture: vi.fn(() => ({ - createView: vi.fn(), - destroy: vi.fn() - })), - queue: { - writeTexture: vi.fn() - } - } - mockStore.tgpuRoot = fromPartial>({ - device: gpuDevice - }) - mockStore.maskCanvas = fromPartial({ - getContext: vi.fn().mockReturnValue(context), - width: 4, - height: 4 - }) - mockStore.rgbCanvas = fromPartial({ - getContext: vi.fn().mockReturnValue(context), - width: 4, - height: 4 - }) - mockStore.maskCtx = context - mockStore.rgbCtx = context - - const resources = setup() - await resources.initGPUResources() + const { resources } = await initializeGPU() resources.gpuRender([{ x: 2, y: 2 }]) expect(mockRenderer.renderStrokeToAccumulator).toHaveBeenCalledWith( expect.any(Array), expect.objectContaining({ coverage: 1 }) ) - - mockRenderer.renderStrokeToAccumulator.mockClear() - await resources.gpuDrawPoint({ x: 2, y: 2 }) - - expect(mockRenderer.renderStrokeToAccumulator).toHaveBeenCalledWith( - expect.any(Array), - expect.objectContaining({ coverage: 1 }) - ) }) }) diff --git a/packages/mask-editor/src/useGPUResources.ts b/packages/mask-editor/src/useGPUResources.ts index 8099b18d59b..a03cf2dc4d2 100644 --- a/packages/mask-editor/src/useGPUResources.ts +++ b/packages/mask-editor/src/useGPUResources.ts @@ -53,7 +53,7 @@ export function useGPUResources() { ) watch( - () => store.canvasHistory.currentStateIndex, + () => store.canvasHistory.revision, async () => { if (isSavingHistory.value) return await updateGPUFromCanvas() @@ -79,23 +79,17 @@ export function useGPUResources() { const height = store.gpuTextureHeight try { - maskTexture?.destroy() - maskTexture = null - rgbTexture?.destroy() - rgbTexture = null - - maskTexture = createTexture(device, width, height) - rgbTexture = createTexture(device, width, height) + const textures = recreateTextures(device, width, height) if (store.pendingGPUMaskData && store.pendingGPURgbData) { device.queue.writeTexture( - { texture: maskTexture }, + { texture: textures.mask }, store.pendingGPUMaskData, { bytesPerRow: width * 4 }, { width, height } ) device.queue.writeTexture( - { texture: rgbTexture }, + { texture: textures.rgb }, store.pendingGPURgbData, { bytesPerRow: width * 4 }, { width, height } @@ -103,13 +97,6 @@ export function useGPUResources() { } else { await updateGPUFromCanvas() } - - if (previewCanvas.value && renderer) { - previewCanvas.value.width = width - previewCanvas.value.height = height - } - - resizeReadbackBuffers(device, width, height) } catch (error) { console.error( '[useGPUResources] Failed to recreate GPU textures:', @@ -171,6 +158,25 @@ export function useGPUResources() { }) } + function recreateTextures( + gpuDevice: GPUDevice, + width: number, + height: number + ) { + maskTexture?.destroy() + maskTexture = null + rgbTexture?.destroy() + rgbTexture = null + maskTexture = createTexture(gpuDevice, width, height) + rgbTexture = createTexture(gpuDevice, width, height) + if (previewCanvas.value && renderer) { + previewCanvas.value.width = width + previewCanvas.value.height = height + } + resizeReadbackBuffers(gpuDevice, width, height) + return { mask: maskTexture, rgb: rgbTexture } + } + function resizeReadbackBuffers( gpuDevice: GPUDevice, width: number, @@ -242,6 +248,10 @@ export function useGPUResources() { const w = store.maskCanvas.width const h = store.maskCanvas.height + if (maskTexture.width !== w || maskTexture.height !== h) { + recreateTextures(device, w, h) + } + const maskData = store.maskCtx.getImageData(0, 0, w, h) premultiplyData(maskData.data) device.queue.writeTexture( @@ -534,62 +544,6 @@ export function useGPUResources() { /* c8 ignore stop */ } - async function gpuDrawPoint(point: Point, opacity = 1): Promise { - if (!renderer) return - - /* c8 ignore start — requires live renderer */ - const width = store.maskCanvas!.width - const height = store.maskCanvas!.height - const { size, hardness } = store.brushSettings - const effectiveSize = getEffectiveBrushSize(size, hardness) - const effectiveHardness = getEffectiveHardness( - size, - hardness, - effectiveSize - ) - const brushShape = store.brushSettings.type === BrushShape.Rect ? 1 : 0 - - dirtyRect.value = updateDirtyRect( - dirtyRect.value, - point.x, - point.y, - effectiveSize - ) - - renderer.renderStrokeToAccumulator( - [{ x: point.x, y: point.y, pressure: opacity }], - { - size: effectiveSize, - coverage: 1, - hardness: effectiveHardness, - color: [1, 1, 1], - width, - height, - brushShape - } - ) - - if (maskTexture && previewContext) { - const isRgb = store.activeLayer === 'rgb' - const isErasing = - store.currentTool === 'eraser' || - store.maskCtx?.globalCompositeOperation === 'destination-out' - renderer.blitToCanvas( - previewContext, - { - opacity: store.brushSettings.opacity, - color: resolveColor(isRgb), - hardness: effectiveHardness, - screenSize: [width, height], - brushShape, - isErasing - }, - undefined - ) - } - /* c8 ignore stop */ - } - // ── Private helpers ───────────────────────────────────────────────────────── /* c8 ignore start — only reachable after successful GPU init */ @@ -611,7 +565,6 @@ export function useGPUResources() { destroy, // Rendering — called internally by useBrushDrawing gpuRender, - gpuDrawPoint, copyGpuToCanvas, // Renderer wrappers — called internally by useBrushDrawing prepareStroke, diff --git a/packages/mask-editor/src/usePanAndZoom.test.ts b/packages/mask-editor/src/usePanAndZoom.test.ts index f4e32a944ac..a7bfd70de7d 100644 --- a/packages/mask-editor/src/usePanAndZoom.test.ts +++ b/packages/mask-editor/src/usePanAndZoom.test.ts @@ -1,4 +1,6 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' +import { fromPartial } from '@total-typescript/shoehorn' +import { nextTick } from 'vue' import { usePanAndZoom } from './usePanAndZoom' import { useMaskEditorStore } from './maskEditorStore' @@ -22,11 +24,15 @@ function createMockElement(width = 1200, height = 800): HTMLElement { } as unknown as HTMLElement } -function createMockCanvas(width: number, height: number): HTMLCanvasElement { +function createMockCanvas( + width: number, + height: number, + context: CanvasRenderingContext2D | null = null +): HTMLCanvasElement { return { width, height, - getContext: vi.fn().mockImplementation(() => null), + getContext: vi.fn(() => context), clientWidth: width, clientHeight: height, style: {} as CSSStyleDeclaration, @@ -61,12 +67,12 @@ function createTouchEvent(touches: TouchList): TouchEvent { } as unknown as TouchEvent } -async function initComposable() { +async function initComposable(context: CanvasRenderingContext2D | null = null) { const pz = usePanAndZoom() const img = createMockImage(800, 600) const root = createMockElement() const container = createMockElement() - const canvas = createMockCanvas(800, 600) + const canvas = createMockCanvas(800, 600, context) mockStore.canvasContainer = container mockStore.maskCanvas = canvas await pz.initializeCanvasPanZoom(img, root) @@ -105,6 +111,82 @@ describe('usePanAndZoom', () => { expect(zoom).toBeGreaterThan(0) }) + it.for([ + { width: 200, height: 800 }, + { width: 284, height: 800 }, + { width: 1200, height: 0 } + ])( + 'keeps the last usable fit when the viewport is $width by $height', + async ({ width, height }) => { + const { pz } = await initComposable() + + await pz.initializeCanvasPanZoom( + createMockImage(800, 600), + createMockElement(width, height) + ) + await pz.zoom( + fromPartial({ clientX: 400, clientY: 300, deltaY: -100 }) + ) + + expect(mockStore.zoomRatio).toBeCloseTo(1.2595) + expect(Number.isFinite(mockStore.displayZoomRatio)).toBe(true) + } + ) + + it.for([0, 1200])( + 'recovers a deferred fit after opening at viewport width %s', + async (initialWidth) => { + const context = fromPartial({ + getImageData: vi.fn( + (_x: number, _y: number, width: number, height: number) => + fromPartial({ width, height }) + ) + }) + const pz = usePanAndZoom() + const root = createMockElement(initialWidth, 800) + const canvas = createMockCanvas(800, 600, context) + mockStore.maskCanvas = canvas + mockStore.rgbCanvas = createMockCanvas(800, 600, context) + mockStore.imgCanvas = createMockCanvas(800, 600, context) + mockStore.maskCtx = context + mockStore.rgbCtx = context + mockStore.imgCtx = context + mockStore.canvasHistory.clearStates() + mockStore.canvasContainer = createMockElement() + Object.defineProperty(canvas, 'clientWidth', { + get: () => canvas.width * mockStore.zoomRatio + }) + await pz.initializeCanvasPanZoom(createMockImage(800, 600), root) + mockStore.canvasHistory.saveInitialState() + await nextTick() + + Object.defineProperty(root, 'clientWidth', { value: 0 }) + canvas.width = 600 + canvas.height = 800 + mockStore.rgbCanvas.width = 600 + mockStore.rgbCanvas.height = 800 + mockStore.imgCanvas.width = 600 + mockStore.imgCanvas.height = 800 + mockStore.canvasHistory.saveState() + await nextTick() + const wheel = fromPartial({ + clientX: 400, + clientY: 300, + deltaY: -100 + }) + await pz.zoom(wheel) + expect(Number.isFinite(mockStore.displayZoomRatio)).toBe(true) + + Object.defineProperty(root, 'clientWidth', { value: 1200 }) + await pz.invalidatePanZoom() + + expect(mockStore.zoomRatio).toBe(1) + expect(mockStore.panOffset).toEqual({ x: 222, y: 0 }) + await pz.zoom(wheel) + expect(mockStore.displayZoomRatio).toBeCloseTo(1.1) + } + ) + it('accounts for panel widths via setPanOffset', async () => { const pz = usePanAndZoom() mockStore.canvasContainer = createMockElement() @@ -146,6 +228,82 @@ describe('usePanAndZoom', () => { }) describe('handlePanStart / handlePanMove', () => { + it('keeps a rotated document proportional without resizing its painted layer', async () => { + const { pz, canvas } = await initComposable() + const rgbCanvas = document.createElement('canvas') + rgbCanvas.width = 600 + rgbCanvas.height = 800 + mockStore.rgbCanvas = rgbCanvas + canvas.width = 600 + canvas.height = 800 + + await pz.invalidatePanZoom() + + const container = mockStore.canvasContainer! + expect( + parseFloat(container.style.width) / parseFloat(container.style.height) + ).toBe(0.75) + expect([rgbCanvas.width, rgbCanvas.height]).toEqual([600, 800]) + }) + + it('refits a rotated document and measures wheel zoom from the new fit', async () => { + const context = fromPartial({ + getImageData: vi.fn( + (_x: number, _y: number, width: number, height: number) => + fromPartial({ width, height }) + ) + }) + const { pz, canvas } = await initComposable(context) + const container = mockStore.canvasContainer! + Object.defineProperty(canvas, 'clientWidth', { + get: () => parseFloat(container.style.width) + }) + mockStore.rgbCanvas = createMockCanvas(800, 600, context) + mockStore.imgCanvas = createMockCanvas(800, 600, context) + mockStore.maskCtx = context + mockStore.rgbCtx = context + mockStore.imgCtx = context + mockStore.canvasHistory.clearStates() + mockStore.canvasHistory.saveInitialState() + await nextTick() + mockStore.maskCanvas!.width = 600 + mockStore.maskCanvas!.height = 800 + mockStore.rgbCanvas.width = 600 + mockStore.rgbCanvas.height = 800 + mockStore.imgCanvas.width = 600 + mockStore.imgCanvas.height = 800 + + mockStore.canvasHistory.saveState() + expect(mockStore.canvasHistory.dimensions).toEqual({ + width: 600, + height: 800 + }) + await nextTick() + + expect(container.style).toMatchObject({ + width: '600px', + height: '800px', + left: '222px', + top: '0px' + }) + expect(mockStore.displayZoomRatio).toBe(1) + + await pz.zoom( + fromPartial({ clientX: 400, clientY: 300, deltaY: -100 }) + ) + + expect(mockStore.displayZoomRatio).toBeCloseTo(1.1) + mockStore.resetZoomTrigger++ + await vi.advanceTimersByTimeAsync(600) + expect(container.style).toMatchObject({ + width: '600px', + height: '800px', + left: '222px', + top: '0px' + }) + expect(mockStore.displayZoomRatio).toBe(1) + }) + it('sets isPanning on the store', () => { const pz = usePanAndZoom() pz.handlePanStart({ clientX: 100, clientY: 200 } as PointerEvent) diff --git a/packages/mask-editor/src/usePanAndZoom.ts b/packages/mask-editor/src/usePanAndZoom.ts index 8bc008c46cb..69338bbcac8 100644 --- a/packages/mask-editor/src/usePanAndZoom.ts +++ b/packages/mask-editor/src/usePanAndZoom.ts @@ -49,7 +49,7 @@ export function usePanAndZoom() { const image = ref(null) const imageRootWidth = ref(0) - const imageRootHeight = ref(0) + let needsFit = false const cursorPoint = ref({ x: 0, y: 0 }) const penPointerIdList = ref([]) @@ -65,12 +65,14 @@ export function usePanAndZoom() { } const invalidatePanZoom = async (): Promise => { - const currentImage = image.value + const currentImage = store.maskCanvas ?? image.value if (!currentImage?.width || !currentImage.height || !zoom_ratio.value) { console.warn('Missing required properties for pan/zoom') return } + if (needsFit) fitCanvasToViewport(currentImage.width, currentImage.height) + const styles = calculatePanZoomStyles( currentImage.width, currentImage.height, @@ -192,7 +194,6 @@ export function usePanAndZoom() { const pinchFactor = newDistance / lastTouchZoomDistance.value const midpoint = getMidpoint(p0, p1) - // Apply midpoint drag const draggedPan: Offset = { x: pan_offset.value.x + midpoint.x - lastTouchMidPoint.value.x, y: pan_offset.value.y + midpoint.y - lastTouchMidPoint.value.y @@ -245,6 +246,9 @@ export function usePanAndZoom() { } if (!maskCanvas.value) return + if (needsFit) await invalidatePanZoom() + if (!imageRootWidth.value) return + const rect = maskCanvas.value.getBoundingClientRect() const focalX = cursorPosition.x - rect.left const focalY = cursorPosition.y - rect.top @@ -284,7 +288,8 @@ export function usePanAndZoom() { } const smoothResetView = async (duration: number = 500): Promise => { - if (!image.value || !rootElement.value) return + const currentImage = store.maskCanvas ?? image.value + if (!currentImage || !rootElement.value) return const startZoom = zoom_ratio.value const startPan = { ...pan_offset.value } @@ -294,8 +299,8 @@ export function usePanAndZoom() { const fitResult = calculateFitView({ rootWidth: rootElement.value.clientWidth, rootHeight: rootElement.value.clientHeight, - imageWidth: image.value.width, - imageHeight: image.value.height, + imageWidth: currentImage.width, + imageHeight: currentImage.height, toolPanelWidth, sidePanelWidth }) @@ -331,6 +336,35 @@ export function usePanAndZoom() { interpolatedZoomRatio.value = 1.0 } + function fitCanvasToViewport(width: number, height: number): void { + needsFit = true + const root = rootElement.value + if (!root) return + const { sidePanelWidth, toolPanelWidth } = getPanelDimensions() + const availableWidth = root.clientWidth - sidePanelWidth - toolPanelWidth + if ( + availableWidth <= 0 || + root.clientHeight <= 0 || + width <= 0 || + height <= 0 + ) + return + const fitResult = calculateFitView({ + rootWidth: root.clientWidth, + rootHeight: root.clientHeight, + imageWidth: width, + imageHeight: height, + toolPanelWidth, + sidePanelWidth + }) + imageRootWidth.value = fitResult.fittedWidth + zoom_ratio.value = fitResult.zoomRatio + pan_offset.value = fitResult.panOffset + interpolatedZoomRatio.value = 1 + store.displayZoomRatio = 1 + needsFit = false + } + const initializeCanvasPanZoom = async ( img: HTMLImageElement, root: HTMLElement, @@ -341,32 +375,30 @@ export function usePanAndZoom() { toolPanelElement.value = toolPanel || null sidePanelElement.value = sidePanel || null - const { sidePanelWidth, toolPanelWidth } = getPanelDimensions() - - const fitResult = calculateFitView({ - rootWidth: root.clientWidth, - rootHeight: root.clientHeight, - imageWidth: img.width, - imageHeight: img.height, - toolPanelWidth, - sidePanelWidth - }) - if (image.value === null) { image.value = img } - imageRootWidth.value = fitResult.fittedWidth - imageRootHeight.value = fitResult.fittedHeight - - zoom_ratio.value = fitResult.zoomRatio - pan_offset.value = fitResult.panOffset + fitCanvasToViewport(img.width, img.height) penPointerIdList.value = [] await invalidatePanZoom() } + watch( + [ + () => store.canvasHistory.dimensions?.width, + () => store.canvasHistory.dimensions?.height + ], + async () => { + const currentImage = store.maskCanvas ?? image.value + if (!currentImage?.width || !currentImage.height) return + fitCanvasToViewport(currentImage.width, currentImage.height) + await invalidatePanZoom() + } + ) + watch( () => store.resetZoomTrigger, async () => {