Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

12.9 KB
Raw Blame
import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/contracts';
import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
import type { Viewport } from '@workbench/canvas-engine/viewport';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';

import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { describe, expect, it, vi } from 'vitest';

import { createBboxTool } from './bboxTool';

const bbox = { height: 96, width: 96, x: 16, y: 16 };

const makeDoc = (): CanvasDocumentContractV3 => ({
  background: 'transparent',
  bbox: { ...bbox },
  height: 512,
  stacks: stacksFrom([]),
  selectedLayerId: null,
  version: 3,
  width: 512,
});

const identityViewport = {
  documentToScreen: (p: Vec2): Vec2 => ({ x: p.x, y: p.y }),
} as unknown as Viewport;

const pointer = (
  x: number,
  y: number,
  opts: { shift?: boolean; alt?: boolean; ctrl?: boolean; meta?: boolean; buttons?: number } = {}
): PointerInput => ({
  buttons: opts.buttons ?? 1,
  documentPoint: { x, y },
  modifiers: {
    alt: opts.alt ?? false,
    ctrl: opts.ctrl ?? false,
    meta: opts.meta ?? false,
    shift: opts.shift ?? false,
  },
  pointerType: 'mouse',
  pressure: 0.5,
  screenPoint: { x, y },
  timeStamp: 0,
});

interface StructuralCommit {
  label: string;
  forward: CanvasProjectMutation;
  inverse: CanvasProjectMutation;
}

interface Harness {
  ctx: ToolContext;
  dispatched: CanvasProjectMutation[];
  commits: StructuralCommit[];
  previewOf: () => CanvasDocumentContractV3['bbox'] | null;
}

const createHarness = (doc: CanvasDocumentContractV3): Harness => {
  const dispatched: CanvasProjectMutation[] = [];
  const commits: StructuralCommit[] = [];
  const stores = createEngineStores();
  const ctx: ToolContext = {
    scheduleFrame: () => () => undefined,
    backend: null as never,
    commitStructural: (label, forward, inverse) => {
      commits.push({ forward, inverse, label });
      return { status: 'committed' as const };
    },
    captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
    createLayerId: () => 'x',
    createPath2D: (d) => ({ d }) as unknown as Path2D,
    dispatch: (action) => dispatched.push(action),
    beginStrokeEdit: () => null,
    getDocument: () => doc,
    invalidate: vi.fn(),
    layers: null as never,
    notifyLayerPainted: vi.fn(),
    setLayerTransformOverride: vi.fn(),
    setOverlayCursor: vi.fn(),
    stores,
    updateCursor: vi.fn(),
    viewport: identityViewport,
  };
  return { commits, ctx, dispatched, previewOf: () => stores.bboxPreview.get() };
};

const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDown?.(ctx, i);
const move = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerMove?.(ctx, i, [i]);
const up = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerUp?.(ctx, i);
const cancel = (t: Tool, ctx: ToolContext): void => t.onPointerCancel?.(ctx);

describe('bbox tool: move gesture', () => {
  it('previews on move then commits one setCanvasBbox on up (grid-snapped)', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();

    down(tool, h.ctx, pointer(60, 60));
    move(tool, h.ctx, pointer(75, 75));
    expect(h.previewOf()).not.toBeNull();

    up(tool, h.ctx, pointer(75, 75));

    expect(h.dispatched).toHaveLength(0);
    expect(h.commits).toHaveLength(1);
    // origin snapped: 16+15 = 31 → grid 8 → 32.
    expect(h.commits[0]?.forward).toEqual({ bbox: { height: 96, width: 96, x: 32, y: 32 }, type: 'setCanvasBbox' });
    expect(h.commits[0]?.inverse).toEqual({ bbox: { ...bbox }, type: 'setCanvasBbox' });
    expect(h.previewOf()).toBeNull();
  });

  it('bypasses model-grid snapping while alt is held but stays on whole pixels', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    down(tool, h.ctx, pointer(60, 60, { alt: true }));
    move(tool, h.ctx, pointer(75.4, 75.6, { alt: true }));
    expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 31, y: 32 });

    up(tool, h.ctx, pointer(75.4, 75.6, { alt: true }));
    expect(h.commits[0]?.forward).toEqual({ bbox: { height: 96, width: 96, x: 31, y: 32 }, type: 'setCanvasBbox' });
  });

  it('keeps the live frame on whole pixels when grid snapping is disabled', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    h.ctx.stores.snapToGrid.set(false);

    down(tool, h.ctx, pointer(60, 60));
    move(tool, h.ctx, pointer(75.4, 75.6));

    expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 31, y: 32 });
  });

  it('constrains movement to the dominant axis while shift is held', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();

    down(tool, h.ctx, pointer(60, 60));
    move(tool, h.ctx, pointer(91, 69, { shift: true }));
    expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 48, y: 16 });
    up(tool, h.ctx, pointer(91, 69, { shift: true }));

    expect(h.commits[0]?.forward).toEqual({ bbox: { height: 96, width: 96, x: 48, y: 16 }, type: 'setCanvasBbox' });
  });

  it('resamples the shift-constrained axis during a drag', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();

    down(tool, h.ctx, pointer(60, 60));
    move(tool, h.ctx, pointer(69, 91, { shift: true }));
    expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 16, y: 48 });
    move(tool, h.ctx, pointer(91, 69, { shift: true }));
    expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 48, y: 16 });
  });

  it('normalizes a fractional origin on the shift-locked axis', () => {
    const doc = makeDoc();
    doc.bbox = { ...bbox, x: 16.25, y: 16.75 };
    const h = createHarness(doc);
    const tool = createBboxTool();
    h.ctx.stores.snapToGrid.set(false);

    down(tool, h.ctx, pointer(60, 60));
    move(tool, h.ctx, pointer(75.4, 60, { shift: true }));

    expect(h.previewOf()).toEqual({ height: 96, width: 96, x: 32, y: 17 });
  });
});

describe('bbox tool: resize gesture', () => {
  it.each([
    ['grid snapping is disabled', false, false],
    ['Alt bypasses the model grid', true, true],
  ])('keeps the live frame on whole pixels when %s', (_label, snapToGrid, alt) => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    h.ctx.stores.snapToGrid.set(snapToGrid);

    down(tool, h.ctx, pointer(112, 112, { alt }));
    move(tool, h.ctx, pointer(130.4, 130.6, { alt }));

    expect(h.previewOf()).toEqual({ height: 115, width: 114, x: 16, y: 16 });
    up(tool, h.ctx, pointer(130.4, 130.6, { alt }));
    expect(h.commits[0]?.forward).toEqual({
      bbox: { height: 115, width: 114, x: 16, y: 16 },
      type: 'setCanvasBbox',
    });
  });

  it('pixel-snaps a high-zoom NW resize without moving the fixed SE corner', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    h.ctx.stores.snapToGrid.set(false);
    const moved = pointer(15.5, 15.5);
    moved.screenPoint = { x: 12, y: 12 };

    down(tool, h.ctx, pointer(16, 16));
    move(tool, h.ctx, moved);

    const preview = h.previewOf();
    expect(preview).toEqual({ height: 96, width: 96, x: 16, y: 16 });
    expect(preview && { x: preview.x + preview.width, y: preview.y + preview.height }).toEqual({ x: 112, y: 112 });
  });

  it('resizes from the SE handle and commits the grid-snapped frame', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();

    down(tool, h.ctx, pointer(112, 112));
    move(tool, h.ctx, pointer(130, 130));
    up(tool, h.ctx, pointer(130, 130));

    expect(h.commits).toHaveLength(1);
    // right/bottom = 112+18 = 130 → grid 8 → 128; anchored at (16,16).
    expect(h.commits[0]?.forward).toEqual({ bbox: { height: 112, width: 112, x: 16, y: 16 }, type: 'setCanvasBbox' });
  });

  it('constrains the ratio while shift is held on an unlocked frame', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    down(tool, h.ctx, pointer(112, 112));
    move(tool, h.ctx, pointer(150, 112, { shift: true }));
    up(tool, h.ctx, pointer(150, 112, { shift: true }));
    const out = h.commits[0]?.forward as { bbox: { width: number; height: number } };
    expect(out.bbox.width).toBe(out.bbox.height);
  });

  it('mirrors the resize across the frame center while ctrl is held', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();

    down(tool, h.ctx, pointer(112, 112));
    move(tool, h.ctx, pointer(128, 128, { ctrl: true }));
    up(tool, h.ctx, pointer(128, 128, { ctrl: true }));

    // Both sides move 16: 96 + 32 = 128 per axis, center held at (64,64).
    expect(h.commits[0]?.forward).toEqual({
      bbox: { height: 128, width: 128, x: 0, y: 0 },
      type: 'setCanvasBbox',
    });
  });

  it('accepts meta as the mirror modifier (⌘ on macOS)', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();

    down(tool, h.ctx, pointer(112, 112));
    move(tool, h.ctx, pointer(128, 128, { meta: true }));
    up(tool, h.ctx, pointer(128, 128, { meta: true }));

    expect(h.commits[0]?.forward).toEqual({
      bbox: { height: 128, width: 128, x: 0, y: 0 },
      type: 'setCanvasBbox',
    });
  });

  it('leaves a move gesture unmirrored while ctrl is held', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();

    down(tool, h.ctx, pointer(60, 60, { ctrl: true }));
    move(tool, h.ctx, pointer(76, 76, { ctrl: true }));
    up(tool, h.ctx, pointer(76, 76, { ctrl: true }));

    expect(h.commits[0]?.forward).toEqual({ bbox: { height: 96, width: 96, x: 32, y: 32 }, type: 'setCanvasBbox' });
  });
});

describe('bbox tool: no-op cases', () => {
  it('commits nothing on a zero-delta gesture that returns to the origin', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    down(tool, h.ctx, pointer(60, 60));
    move(tool, h.ctx, pointer(70, 70));
    move(tool, h.ctx, pointer(60, 60));
    up(tool, h.ctx, pointer(60, 60));
    expect(h.commits).toHaveLength(0);
    expect(h.dispatched).toHaveLength(0);
    expect(h.previewOf()).toBeNull();
  });

  it('does nothing when pressing outside the frame (never deselects)', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    down(tool, h.ctx, pointer(400, 400));
    move(tool, h.ctx, pointer(420, 420));
    up(tool, h.ctx, pointer(420, 420));
    expect(h.commits).toHaveLength(0);
    expect(h.dispatched).toHaveLength(0);
    expect(h.previewOf()).toBeNull();
  });

  it('ignores a sub-threshold press (no drag)', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    down(tool, h.ctx, pointer(60, 60));
    up(tool, h.ctx, pointer(61, 61));
    expect(h.commits).toHaveLength(0);
  });
});

describe('bbox tool: cancel', () => {
  it('drops the preview and commits nothing on escape/cancel', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    down(tool, h.ctx, pointer(112, 112));
    move(tool, h.ctx, pointer(130, 130));
    expect(h.previewOf()).not.toBeNull();
    cancel(tool, h.ctx);
    expect(h.commits).toHaveLength(0);
    expect(h.dispatched).toHaveLength(0);
    expect(h.previewOf()).toBeNull();
  });
});

describe('bbox tool: hover cursors', () => {
  it('reflects the hovered handle/interior in the cursor and refreshes it on change', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    const cursorAt = (x: number, y: number): string | undefined => {
      move(tool, h.ctx, pointer(x, y));
      return tool.cursor?.(h.ctx);
    };

    expect(cursorAt(112, 112)).toBe('nwse-resize');
    expect(cursorAt(16, 112)).toBe('nesw-resize');
    expect(cursorAt(16, 16)).toBe('nwse-resize');
    expect(cursorAt(112, 16)).toBe('nesw-resize');
    expect(cursorAt(64, 16)).toBe('ns-resize');
    expect(cursorAt(112, 64)).toBe('ew-resize');
    expect(cursorAt(64, 64)).toBe('move');
    expect(cursorAt(400, 400)).toBe('default');
    expect(h.ctx.updateCursor).toHaveBeenCalled();
  });

  it('holds the grabbed handle cursor during a resize drag', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    down(tool, h.ctx, pointer(112, 112));
    move(tool, h.ctx, pointer(130, 130));
    expect(tool.cursor?.(h.ctx)).toBe('nwse-resize');
  });
});

describe('bbox tool: undo/redo contract', () => {
  it('carries an inverse that restores the prior bbox', () => {
    const h = createHarness(makeDoc());
    const tool = createBboxTool();
    down(tool, h.ctx, pointer(112, 112));
    move(tool, h.ctx, pointer(130, 130));
    up(tool, h.ctx, pointer(130, 130));
    expect(h.commits[0]?.inverse).toEqual({ bbox: { ...bbox }, type: 'setCanvasBbox' });
  });
});