Skip to content

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

18.8 KB
Raw Blame
import { describe, it, expect, beforeEach } from 'vitest';
import {
  DEFAULT_APP_SETTINGS,
  loadAppSettings,
  saveAppSettings,
} from '../../types/settings';
import {
  QuickShapeRectangle,
  QuickShapeTriangle,
  buildQuickShapePreview,
  computeArcCircle,
  createQuickShapeSession,
  extractQuickShapeStrokeStyle,
  getRectangleCorners,
  playQuickShapeSnapClick,
  recognizeQuickShape,
  sampleQuickShapePoints,
  updateQuickShapeFromDrag,
} from '../quickShapeEngine';
import { Point } from '../../types/editor';

function makePoint(x: number, y: number, pressure = 0.65, width = 8, t = 0): Point {
  return { x, y, pressure, width, timestamp: t };
}

// Deterministic pseudo-noise for realistic human hand-wobble tests
function wobble(idx: number, amp: number): number {
  return Math.sin(idx * 1.73) * amp * 0.65 + Math.cos(idx * 2.91) * amp * 0.35;
}

function makeFreehandLine(
  x0: number,
  y0: number,
  x1: number,
  y1: number,
  steps = 40,
  noise = 2.0
): Point[] {
  const dx = x1 - x0;
  const dy = y1 - y0;
  const len = Math.hypot(dx, dy);
  const nx = -dy / Math.max(1, len);
  const ny = dx / Math.max(1, len);
  const pts: Point[] = [];
  for (let i = 0; i <= steps; i++) {
    const t = i / steps;
    const w = i === 0 || i === steps ? 0 : wobble(i, noise);
    pts.push(makePoint(x0 + dx * t + nx * w, y0 + dy * t + ny * w, 0.7, 10, i * 6));
  }
  return pts;
}

function makeFreehandArc(
  cx: number,
  cy: number,
  radius: number,
  startRad: number,
  sweepRad: number,
  steps = 48,
  noise = 2.5
): Point[] {
  const pts: Point[] = [];
  for (let i = 0; i <= steps; i++) {
    const t = i / steps;
    const a = startRad + sweepRad * t;
    const r = radius + (i === 0 || i === steps ? 0 : wobble(i, noise));
    pts.push(makePoint(cx + Math.cos(a) * r, cy + Math.sin(a) * r, 0.6, 8, i * 6));
  }
  return pts;
}

function makeFreehandEllipse(
  cx: number,
  cy: number,
  rx: number,
  ry: number,
  rotRad: number,
  steps = 64,
  noise = 2.5,
  overshootFrac = 0.05,
  ccw = true
): Point[] {
  const cos = Math.cos(rotRad);
  const sin = Math.sin(rotRad);
  const totalAngle = Math.PI * 2 * (1 + overshootFrac) * (ccw ? 1 : -1);
  const pts: Point[] = [];
  for (let i = 0; i <= steps; i++) {
    const a = (totalAngle * i) / steps;
    const w = wobble(i, noise);
    const lx = Math.cos(a) * (rx + w);
    const ly = Math.sin(a) * (ry + w * 0.7);
    pts.push(
      makePoint(cx + lx * cos - ly * sin, cy + lx * sin + ly * cos, 0.75, 10, i * 6)
    );
  }
  return pts;
}

function makeFreehandPolygon(
  vertices: Array<{ x: number; y: number }>,
  stepsPerEdge = 24,
  noise = 2.0
): Point[] {
  const pts: Point[] = [];
  let idx = 0;
  for (let e = 0; e < vertices.length; e++) {
    const a = vertices[e];
    const b = vertices[(e + 1) % vertices.length];
    const dx = b.x - a.x;
    const dy = b.y - a.y;
    const len = Math.max(1, Math.hypot(dx, dy));
    const nx = -dy / len;
    const ny = dx / len;
    for (let s = 0; s < stepsPerEdge; s++) {
      const t = s / stepsPerEdge;
      const w = wobble(idx++, noise);
      pts.push(makePoint(a.x + dx * t + nx * w, a.y + dy * t + ny * w, 0.7, 9, idx * 6));
    }
  }
  // Close slightly near first vertex
  pts.push(makePoint(vertices[0].x + 2, vertices[0].y - 1.5, 0.7, 9, idx * 6));
  return pts;
}

describe('QuickShape Settings (disabled by default)', () => {
  beforeEach(() => {
    const storage: Record<string, string> = {};
    (globalThis as any).localStorage = {
      getItem: (k: string) => storage[k] || null,
      setItem: (k: string, v: string) => {
        storage[k] = String(v);
      },
      removeItem: (k: string) => {
        delete storage[k];
      },
      clear: () => {
        Object.keys(storage).forEach((k) => delete storage[k]);
      },
    };
  });

  it('is disabled by default and persists/sanitizes safely in AppSettings', () => {
    expect(DEFAULT_APP_SETTINGS.quickShapeEnabled).toBe(false);
    expect(loadAppSettings().quickShapeEnabled).toBe(false);

    // Legacy stored settings without quickShapeEnabled default safely to false
    localStorage.setItem('ink_studio_app_settings', JSON.stringify({ themePreset: 'modern' }));
    expect(loadAppSettings().quickShapeEnabled).toBe(false);

    // Corrupted non-boolean value falls back to false
    localStorage.setItem('ink_studio_app_settings', JSON.stringify({ quickShapeEnabled: 'yes' }));
    expect(loadAppSettings().quickShapeEnabled).toBe(false);

    // Enabling persists cleanly
    saveAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: true });
    expect(loadAppSettings().quickShapeEnabled).toBe(true);

    // Disabling persists cleanly
    saveAppSettings({ ...DEFAULT_APP_SETTINGS, quickShapeEnabled: false });
    expect(loadAppSettings().quickShapeEnabled).toBe(false);
  });
});

describe('QuickShape Geometry Recognition (All 6 Shapes)', () => {
  it('recognizes freehand horizontal, vertical, and diagonal lines', () => {
    const diagLine = makeFreehandLine(80, 120, 380, 290, 40, 2.2);
    const res = recognizeQuickShape(diagLine);
    expect(res).not.toBeNull();
    expect(res!.shape.kind).toBe('line');
    if (res!.shape.kind === 'line') {
      expect(res!.shape.start.x).toBeCloseTo(80, 0);
      expect(res!.shape.start.y).toBeCloseTo(120, 0);
      expect(res!.shape.end.x).toBeCloseTo(380, 0);
      expect(res!.shape.end.y).toBeCloseTo(290, 0);
    }

    // Nearly horizontal line auto-aligns cleanly
    const horizLine = makeFreehandLine(50, 200, 350, 204, 40, 1.5);
    const resH = recognizeQuickShape(horizLine);
    expect(resH?.shape.kind).toBe('line');
    if (resH?.shape.kind === 'line') {
      expect(Math.abs(resH.shape.end.y - resH.shape.start.y)).toBeLessThan(1);
    }
  });

  it('recognizes freehand minor and major circular arcs (CW & CCW)', () => {
    const minorArc = makeFreehandArc(300, 300, 140, 0.2, Math.PI * 0.75, 48, 2.5);
    const res1 = recognizeQuickShape(minorArc);
    expect(res1).not.toBeNull();
    expect(res1!.shape.kind).toBe('arc');
    if (res1!.shape.kind === 'arc') {
      const circ = computeArcCircle(res1!.shape.start, res1!.shape.mid, res1!.shape.end);
      expect(circ).not.toBeNull();
      expect(circ!.cx).toBeCloseTo(300, -1);
      expect(circ!.cy).toBeCloseTo(300, -1);
      expect(circ!.radius).toBeCloseTo(140, -1);
      expect(Math.abs(circ!.sweep)).toBeCloseTo(Math.PI * 0.75, 1);
    }

    // Major 230 deg CW arc
    const majorArc = makeFreehandArc(400, 350, 110, 0.4, -Math.PI * 1.28, 60, 2.2);
    const res2 = recognizeQuickShape(majorArc);
    expect(res2).not.toBeNull();
    expect(res2!.shape.kind).toBe('arc');
    if (res2!.shape.kind === 'arc') {
      const circ = computeArcCircle(res2!.shape.start, res2!.shape.mid, res2!.shape.end);
      expect(circ).not.toBeNull();
      expect(Math.abs(circ!.sweep)).toBeGreaterThan(Math.PI);
    }
  });

  it('recognizes freehand circles (with wobble and slight overshoot)', () => {
    const circlePts = makeFreehandEllipse(320, 280, 120, 115, 0.3, 64, 3.0, 0.08, true);
    const res = recognizeQuickShape(circlePts);
    expect(res).not.toBeNull();
    expect(res!.shape.kind).toBe('circle');
    if (res!.shape.kind === 'circle') {
      expect(res!.shape.center.x).toBeCloseTo(320, -1);
      expect(res!.shape.center.y).toBeCloseTo(280, -1);
      expect(res!.shape.radius).toBeGreaterThan(105);
      expect(res!.shape.radius).toBeLessThan(130);
    }
  });

  it('recognizes freehand rotated ellipses without confusing them for rectangles or circles', () => {
    const rot = (28 * Math.PI) / 180;
    const ellPts = makeFreehandEllipse(400, 300, 180, 82, rot, 72, 2.5, 0.04, false);
    const res = recognizeQuickShape(ellPts);
    expect(res).not.toBeNull();
    expect(res!.shape.kind).toBe('ellipse');
    if (res!.shape.kind === 'ellipse') {
      expect(res!.shape.center.x).toBeCloseTo(400, -1);
      expect(res!.shape.center.y).toBeCloseTo(300, -1);
      expect(res!.shape.rx).toBeGreaterThan(165);
      expect(res!.shape.rx).toBeLessThan(195);
      expect(res!.shape.ry).toBeGreaterThan(70);
      expect(res!.shape.ry).toBeLessThan(95);
      expect(Math.abs(res!.shape.rotation - rot)).toBeLessThan(0.18);
    }
  });

  it('recognizes freehand equilateral and scalene triangles', () => {
    const triPts = makeFreehandPolygon(
      [
        { x: 250, y: 120 },
        { x: 420, y: 380 },
        { x: 110, y: 350 },
      ],
      28,
      2.5
    );
    const res = recognizeQuickShape(triPts);
    expect(res).not.toBeNull();
    expect(res!.shape.kind).toBe('triangle');
    if (res!.shape.kind === 'triangle') {
      expect(res!.shape.vertices).toHaveLength(3);
      // Every ground-truth corner should match a detected vertex within ~15px
      const expected = [
        { x: 250, y: 120 },
        { x: 420, y: 380 },
        { x: 110, y: 350 },
      ];
      for (const exp of expected) {
        const minD = Math.min(
          ...res!.shape.vertices.map((v) => Math.hypot(v.x - exp.x, v.y - exp.y))
        );
        expect(minD).toBeLessThan(18);
      }
    }
  });

  it('recognizes freehand axis-aligned rectangles, rotated rectangles, and squares', () => {
    // Axis-aligned rectangle
    const rectPts = makeFreehandPolygon(
      [
        { x: 120, y: 140 },
        { x: 440, y: 140 },
        { x: 440, y: 320 },
        { x: 120, y: 320 },
      ],
      26,
      2.5
    );
    const res1 = recognizeQuickShape(rectPts);
    expect(res1).not.toBeNull();
    expect(res1!.shape.kind).toBe('rectangle');
    if (res1!.shape.kind === 'rectangle') {
      expect(res1!.shape.center.x).toBeCloseTo(280, -1);
      expect(res1!.shape.center.y).toBeCloseTo(230, -1);
      expect(Math.max(res1!.shape.width, res1!.shape.height)).toBeGreaterThan(300);
      expect(Math.min(res1!.shape.width, res1!.shape.height)).toBeGreaterThan(165);
    }

    // Rotated rectangle (25 deg)
    const rot = (25 * Math.PI) / 180;
    const baseRect: QuickShapeRectangle = {
      kind: 'rectangle',
      center: { x: 350, y: 320 },
      width: 260,
      height: 150,
      rotation: rot,
    };
    const rotRectPts = makeFreehandPolygon(getRectangleCorners(baseRect), 24, 2.2);
    const res2 = recognizeQuickShape(rotRectPts);
    expect(res2).not.toBeNull();
    expect(res2!.shape.kind).toBe('rectangle');
    if (res2!.shape.kind === 'rectangle') {
      expect(res2!.shape.center.x).toBeCloseTo(350, -1);
      expect(res2!.shape.center.y).toBeCloseTo(320, -1);
    }

    // Square (should NOT be confused with a circle!)
    const sqPts = makeFreehandPolygon(
      [
        { x: 150, y: 150 },
        { x: 350, y: 150 },
        { x: 350, y: 350 },
        { x: 150, y: 350 },
      ],
      26,
      2.5
    );
    const resSq = recognizeQuickShape(sqPts);
    expect(resSq).not.toBeNull();
    expect(resSq!.shape.kind).toBe('rectangle');
  });

  it('rejects tiny dots, S-curves, figure-8 loops, and chaotic scribbles', () => {
    // Tiny tap
    expect(recognizeQuickShape([makePoint(100, 100), makePoint(105, 104)])).toBeNull();

    // S-curve wave
    const sCurve: Point[] = [];
    for (let i = 0; i <= 50; i++) {
      const t = i / 50;
      sCurve.push(makePoint(100 + t * 300, 250 + Math.sin(t * Math.PI * 2) * 80, 0.6, 8, i * 6));
    }
    expect(recognizeQuickShape(sCurve)).toBeNull();

    // Figure-8 self-crossing loop
    const fig8: Point[] = [];
    for (let i = 0; i <= 80; i++) {
      const a = (i / 80) * Math.PI * 2;
      fig8.push(makePoint(300 + Math.sin(a) * 140, 300 + Math.sin(2 * a) * 100, 0.6, 8, i * 6));
    }
    expect(recognizeQuickShape(fig8)).toBeNull();
  });
});

describe('QuickShape Interactive Handle & Corner Dragging', () => {
  const style = extractQuickShapeStrokeStyle([makePoint(0, 0, 0.72, 12)], 12);

  it('respects drag deadzone so lifting pen without intentional move never jumps', () => {
    const session = createQuickShapeSession(
      { kind: 'line', start: { x: 100, y: 100 }, end: { x: 300, y: 100 } },
      { x: 300, y: 100 },
      style
    );
    const updated = updateQuickShapeFromDrag(
      session,
      { x: 302, y: 101 },
      { shiftKey: false, altKey: false },
      1.0
    );
    expect(updated).toEqual(session.initialShape);
    expect(session.hasExitedDeadzone).toBe(false);
  });

  it('drags line endpoint with Shift 15-degree snap and Alt translation', () => {
    const session = createQuickShapeSession(
      { kind: 'line', start: { x: 100, y: 100 }, end: { x: 250, y: 100 } },
      { x: 250, y: 100 },
      style
    );

    // Drag endpoint diagonally with Shift -> snaps to 45 deg
    const snapped = updateQuickShapeFromDrag(
      session,
      { x: 245, y: 242 },
      { shiftKey: true, altKey: false },
      1.0
    );
    expect(snapped.kind).toBe('line');
    if (snapped.kind === 'line') {
      const angleDeg =
        (Math.atan2(snapped.end.y - snapped.start.y, snapped.end.x - snapped.start.x) * 180) /
        Math.PI;
      expect(angleDeg).toBeCloseTo(45, 3);
    }

    // Alt translates both endpoints together
    const moved = updateQuickShapeFromDrag(
      session,
      { x: 300, y: 140 },
      { shiftKey: false, altKey: true },
      1.0
    );
    if (moved.kind === 'line') {
      expect(moved.start.x).toBeCloseTo(150, 3);
      expect(moved.start.y).toBeCloseTo(140, 3);
      expect(moved.end.x).toBeCloseTo(300, 3);
      expect(moved.end.y).toBeCloseTo(140, 3);
    }
  });

  it('drags arc endpoint preserving bulge and bends arc curvature with Alt', () => {
    const session = createQuickShapeSession(
      {
        kind: 'arc',
        start: { x: 100, y: 200 },
        mid: { x: 200, y: 120 },
        end: { x: 300, y: 200 },
      },
      { x: 300, y: 200 },
      style
    );

    const dragged = updateQuickShapeFromDrag(
      session,
      { x: 400, y: 200 },
      { shiftKey: false, altKey: false },
      1.0
    );
    expect(dragged.kind).toBe('arc');
    if (dragged.kind === 'arc') {
      expect(dragged.end.x).toBeCloseTo(400, 3);
      expect(dragged.mid.x).toBeCloseTo(250, 3);
      // Bulge scaled proportionally with chord length (1.5x chord -> 1.5x sagitta = 120px above y=200 -> y=80)
      expect(dragged.mid.y).toBeCloseTo(80, 2);
    }

    const bent = updateQuickShapeFromDrag(
      session,
      { x: 300, y: 260 },
      { shiftKey: false, altKey: true },
      1.0
    );
    expect(session.activeHandleId).toBe('mid');
    if (bent.kind === 'arc') {
      expect(bent.mid.y).toBeCloseTo(180, 3);
    }
  });

  it('drags circle radius and snaps ellipse to circle with Shift', () => {
    const cSession = createQuickShapeSession(
      { kind: 'circle', center: { x: 200, y: 200 }, radius: 80, handleAngle: 0 },
      { x: 280, y: 200 },
      style
    );
    const resized = updateQuickShapeFromDrag(
      cSession,
      { x: 340, y: 200 },
      { shiftKey: false, altKey: false },
      1.0
    );
    if (resized.kind === 'circle') {
      expect(resized.radius).toBeCloseTo(140, 2);
    }

    const eSession = createQuickShapeSession(
      { kind: 'ellipse', center: { x: 200, y: 200 }, rx: 120, ry: 60, rotation: 0, handleAngle: 0 },
      { x: 320, y: 200 },
      style
    );
    const snappedEll = updateQuickShapeFromDrag(
      eSession,
      { x: 340, y: 200 },
      { shiftKey: true, altKey: false },
      1.0
    );
    if (snappedEll.kind === 'ellipse') {
      expect(snappedEll.rx).toBeCloseTo(snappedEll.ry, 3);
    }
  });

  it('drags triangle corner directly while keeping other 2 corners fixed', () => {
    const tri: QuickShapeTriangle = {
      kind: 'triangle',
      vertices: [
        { x: 200, y: 100 },
        { x: 320, y: 300 },
        { x: 80, y: 300 },
      ],
    };
    // Pen stopped near corner 1 (320, 300)
    const session = createQuickShapeSession(tri, { x: 318, y: 298 }, style);
    expect(session.activeCornerIndex).toBe(1);

    const dragged = updateQuickShapeFromDrag(
      session,
      { x: 380, y: 340 },
      { shiftKey: false, altKey: false },
      1.0
    );
    if (dragged.kind === 'triangle') {
      expect(dragged.vertices[0]).toEqual({ x: 200, y: 100 });
      expect(dragged.vertices[2]).toEqual({ x: 80, y: 300 });
      expect(dragged.vertices[1].x).toBeCloseTo(382, 2);
      expect(dragged.vertices[1].y).toBeCloseTo(342, 2);
    }
  });

  it('drags rectangle corner with opposite corner anchored and locks square with Shift', () => {
    const rect: QuickShapeRectangle = {
      kind: 'rectangle',
      center: { x: 200, y: 200 },
      width: 200,
      height: 100,
      rotation: 0,
    };
    const corners = getRectangleCorners(rect);
    // Corner 2 is bottom-right (300, 250); opposite corner 0 is top-left (100, 150)
    const session = createQuickShapeSession(rect, corners[2], style);
    expect(session.activeCornerIndex).toBe(2);

    const resized = updateQuickShapeFromDrag(
      session,
      { x: 360, y: 310 },
      { shiftKey: false, altKey: false },
      1.0
    );
    if (resized.kind === 'rectangle') {
      const nextCorners = getRectangleCorners(resized);
      // Opposite corner 0 stays anchored at (100, 150)
      expect(nextCorners[0].x).toBeCloseTo(100, 2);
      expect(nextCorners[0].y).toBeCloseTo(150, 2);
      // Active corner 2 moves to (360, 310)
      expect(nextCorners[2].x).toBeCloseTo(360, 2);
      expect(nextCorners[2].y).toBeCloseTo(310, 2);
      expect(resized.width).toBeCloseTo(260, 2);
      expect(resized.height).toBeCloseTo(160, 2);
    }

    const squared = updateQuickShapeFromDrag(
      session,
      { x: 360, y: 310 },
      { shiftKey: true, altKey: false },
      1.0
    );
    if (squared.kind === 'rectangle') {
      expect(squared.width).toBeCloseTo(squared.height, 2);
      expect(squared.width).toBeCloseTo(260, 2);
    }
  });

  it('samples smooth points and builds valid preview guides for all 6 shapes', () => {
    const shapes = [
      { kind: 'line' as const, start: { x: 50, y: 50 }, end: { x: 250, y: 150 } },
      { kind: 'arc' as const, start: { x: 50, y: 150 }, mid: { x: 150, y: 80 }, end: { x: 250, y: 150 } },
      { kind: 'circle' as const, center: { x: 200, y: 200 }, radius: 90, handleAngle: 0 },
      { kind: 'ellipse' as const, center: { x: 200, y: 200 }, rx: 120, ry: 60, rotation: 0.3, handleAngle: 0 },
      { kind: 'triangle' as const, vertices: [{ x: 200, y: 80 }, { x: 300, y: 260 }, { x: 100, y: 260 }] as [any, any, any] },
      { kind: 'rectangle' as const, center: { x: 200, y: 200 }, width: 180, height: 110, rotation: 0.2 },
    ];
    for (const s of shapes) {
      const pts = sampleQuickShapePoints(s, style);
      expect(pts.length).toBeGreaterThan(10);
      expect(pts[0].pressure).toBeCloseTo(style.pressure, 4);
      expect(pts[0].width).toBeCloseTo(style.width, 4);
      const sess = createQuickShapeSession(s, { x: 200, y: 200 }, style);
      const preview = buildQuickShapePreview(sess);
      expect(preview.svgPath.length).toBeGreaterThan(5);
      expect(preview.handles.length).toBeGreaterThanOrEqual(2);
      expect(preview.handles.some((h) => h.active)).toBe(true);
    }
    // Safe no-op in headless environment
    expect(() => playQuickShapeSnapClick()).not.toThrow();
  });
});