Skip to content

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

16.9 KB
Raw Blame
import { act } from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { createRoot, Root } from 'react-dom/client';
import { BrushStudioModal } from '../BrushStudioModal';
import { BrushStudioScratchpad } from '../brushStudio/BrushStudioScratchpad';
import { toolStoreActions, useToolStore } from '../../stores';
import { NEUTRAL_BRUSH_DEFAULTS } from '../../utils/brushPresetManager';
import type { BrushSettings } from '../../types/editor';
import * as nativeBridge from '../../utils/nativeEngineBridge';

(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

interface MockCanvasDrawLog {
  clears: number;
  ellipses: Array<{ rx: number; ry: number }>;
  arcs: Array<{ r: number }>;
  strokes: number;
}

class MiniText {
  nodeType = 3;
  nodeName = '#text';
  parentNode: MiniEl | null = null;
  constructor(
    public nodeValue: string,
    public ownerDocument: MiniDoc
  ) {}
}

class MiniComment {
  nodeType = 8;
  nodeName = '#comment';
  parentNode: MiniEl | null = null;
  constructor(
    public nodeValue: string,
    public ownerDocument: MiniDoc
  ) {}
}

class MiniStyle {
  private map = new Map<string, string>();
  [key: string]: unknown;
  setProperty(k: string, v: string) {
    this.map.set(k, String(v));
    this[k] = String(v);
  }
  getPropertyValue(k: string): string {
    return this.map.get(k) ?? (typeof this[k] === 'string' ? (this[k] as string) : '');
  }
  removeProperty(k: string) {
    this.map.delete(k);
    delete this[k];
  }
}

class MiniEl extends EventTarget {
  nodeType = 1;
  nodeName: string;
  tagName: string;
  namespaceURI = 'http://www.w3.org/1999/xhtml';
  parentNode: MiniEl | null = null;
  childNodes: Array<MiniEl | MiniText | MiniComment> = [];
  style = new MiniStyle();
  className = '';
  disabled = false;
  type = '';
  checked = false;
  oninput: ((ev: Event) => void) | null = null;
  clientWidth = 560;
  clientHeight = 440;
  width = 560;
  height = 440;
  attrs = new Map<string, string>();
  private _value = '';
  mockDrawLog: MockCanvasDrawLog = { clears: 0, ellipses: [], arcs: [], strokes: 0 };
  private mockCtx: Record<string, unknown> | null = null;

  constructor(
    tag: string,
    public ownerDocument: MiniDoc
  ) {
    super();
    this.nodeName = tag.toUpperCase();
    this.tagName = tag.toUpperCase();
  }

  get value(): string {
    return this._value;
  }
  set value(v: string) {
    this._value = String(v);
  }
  get firstChild() {
    return this.childNodes[0] ?? null;
  }
  get textContent(): string {
    return this.childNodes
      .map((c) =>
        c instanceof MiniText ? c.nodeValue : c instanceof MiniEl ? c.textContent : ''
      )
      .join('');
  }
  set textContent(val: string) {
    this.childNodes = val ? [new MiniText(val, this.ownerDocument)] : [];
  }

  getBoundingClientRect() {
    return {
      left: 0,
      top: 0,
      right: this.clientWidth,
      bottom: this.clientHeight,
      width: this.clientWidth,
      height: this.clientHeight,
      x: 0,
      y: 0,
      toJSON: () => ({}),
    };
  }

  getContext(kind: string) {
    if (this.tagName !== 'CANVAS' || kind !== '2d') return null;
    if (!this.mockCtx) {
      const log = this.mockDrawLog;
      this.mockCtx = {
        save: () => {},
        restore: () => {},
        translate: () => {},
        rotate: () => {},
        scale: () => {},
        beginPath: () => {},
        moveTo: () => {},
        lineTo: () => {},
        fill: () => {},
        stroke: () => {
          log.strokes += 1;
        },
        clearRect: () => {
          log.clears += 1;
        },
        fillRect: () => {},
        drawImage: () => {},
        putImageData: () => {},
        ellipse: (_x: number, _y: number, rx: number, ry: number) => {
          log.ellipses.push({ rx, ry });
        },
        arc: (_x: number, _y: number, r: number) => {
          log.arcs.push({ r });
        },
        globalAlpha: 1,
        fillStyle: '#000',
        strokeStyle: '#000',
        lineCap: 'round',
        lineJoin: 'round',
        lineWidth: 1,
        globalCompositeOperation: 'source-over',
      };
    }
    return this.mockCtx;
  }

  setPointerCapture() {}
  releasePointerCapture() {}
  hasPointerCapture() {
    return false;
  }
  focus() {
    this.ownerDocument.activeElement = this;
  }
  blur() {
    if (this.ownerDocument.activeElement === this) {
      this.ownerDocument.activeElement = this.ownerDocument.body;
    }
  }
  select() {}
  scrollIntoView() {}

  appendChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }

  insertBefore<T extends MiniEl | MiniText | MiniComment>(
    child: T,
    ref: MiniEl | MiniText | MiniComment | null
  ): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    if (!ref) {
      this.childNodes.push(child);
      return child;
    }
    const idx = this.childNodes.indexOf(ref);
    if (idx >= 0) this.childNodes.splice(idx, 0, child);
    else this.childNodes.push(child);
    return child;
  }

  removeChild<T extends MiniEl | MiniText | MiniComment>(child: T): T {
    const idx = this.childNodes.indexOf(child);
    if (idx >= 0) this.childNodes.splice(idx, 1);
    child.parentNode = null;
    return child;
  }

  setAttribute(name: string, value: string) {
    const v = String(value);
    this.attrs.set(name, v);
    if (name === 'class') this.className = v;
    if (name === 'type') this.type = v;
    if (name === 'value') this._value = v;
    if (name === 'width') this.width = Number(v) || this.width;
    if (name === 'height') this.height = Number(v) || this.height;
  }

  getAttribute(name: string): string | null {
    if (name === 'class') return this.className || this.attrs.get('class') || null;
    return this.attrs.get(name) ?? null;
  }

  removeAttribute(name: string) {
    this.attrs.delete(name);
    if (name === 'class') this.className = '';
  }

  hasAttribute(name: string): boolean {
    return this.attrs.has(name);
  }

  override dispatchEvent(event: Event): boolean {
    if (!event.target) {
      Object.defineProperty(event, 'target', { value: this, configurable: true });
    }
    let cur: MiniEl | null = this;
    while (cur) {
      Object.defineProperty(event, 'currentTarget', { value: cur, configurable: true });
      EventTarget.prototype.dispatchEvent.call(cur, event);
      if (!event.bubbles || event.cancelBubble) break;
      cur = cur.parentNode;
    }
    return !event.defaultPrevented;
  }

  click() {
    this.dispatchEvent(new Event('click', { bubbles: true, cancelable: true }));
  }
}

class MiniDoc extends EventTarget {
  nodeType = 9;
  defaultView: unknown = globalThis;
  oninput: ((ev: Event) => void) | null = null;
  documentElement: MiniEl;
  head: MiniEl;
  body: MiniEl;
  activeElement: MiniEl | null = null;

  constructor() {
    super();
    this.documentElement = new MiniEl('html', this);
    this.head = new MiniEl('head', this);
    this.body = new MiniEl('body', this);
    this.documentElement.appendChild(this.head);
    this.documentElement.appendChild(this.body);
    this.activeElement = this.body;
  }

  createElement(tag: string) {
    return new MiniEl(tag, this);
  }
  createElementNS(_ns: string, tag: string) {
    return new MiniEl(tag, this);
  }
  createTextNode(text: string) {
    return new MiniText(text, this);
  }
  createComment(text: string) {
    return new MiniComment(text, this);
  }
}

function byTestId(rootEl: MiniEl, id: string): MiniEl | null {
  if (rootEl.getAttribute('data-testid') === id) return rootEl;
  for (const c of rootEl.childNodes) {
    if (c instanceof MiniEl) {
      const hit = byTestId(c, id);
      if (hit) return hit;
    }
  }
  return null;
}

function makePointerEvent(
  type: string,
  props: {
    button?: number;
    pointerId?: number;
    pointerType?: string;
    clientX?: number;
    clientY?: number;
    pressure?: number;
  }
): Event {
  const ev = new Event(type, { bubbles: true, cancelable: true });
  Object.assign(ev, {
    button: props.button ?? 0,
    pointerId: props.pointerId ?? 1,
    pointerType: props.pointerType ?? 'pen',
    clientX: props.clientX ?? 0,
    clientY: props.clientY ?? 0,
    pressure: props.pressure ?? 0.8,
    tiltX: 0,
    tiltY: 0,
    twist: 0,
  });
  return ev;
}

function makeTestBrush(overrides: Partial<BrushSettings> = {}): BrushSettings {
  return {
    ...NEUTRAL_BRUSH_DEFAULTS,
    color: '#1d4ed8',
    size: 10,
    opacity: 1,
    flow: 1,
    hardness: 1,
    spacing: 0.1,
    smoothing: true,
    stabilization: 0,
    usePressure: true,
    minSizeFactor: 0.1,
    ...overrides,
  };
}

describe('Brush Studio Live Preview', () => {
  let doc: MiniDoc;
  let container: MiniEl;
  let root: Root | null = null;
  const origDoc = globalThis.document;
  const origWin = globalThis.window;
  const origHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;
  const origHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;
  const origNode = (globalThis as Record<string, unknown>).Node;
  const origElement = (globalThis as Record<string, unknown>).Element;

  beforeEach(() => {
    doc = new MiniDoc();
    container = doc.createElement('div');
    doc.body.appendChild(container);
    const winTarget = new EventTarget();
    class HTMLIFrameElementShim extends MiniEl {}
    const mockWindow = {
      document: doc,
      addEventListener: winTarget.addEventListener.bind(winTarget),
      removeEventListener: winTarget.removeEventListener.bind(winTarget),
      dispatchEvent: winTarget.dispatchEvent.bind(winTarget),
      HTMLElement: MiniEl,
      HTMLIFrameElement: HTMLIFrameElementShim,
      Node: MiniEl,
      Element: MiniEl,
    };
    doc.defaultView = mockWindow;
    Object.defineProperty(globalThis, 'document', { value: doc, configurable: true });
    Object.defineProperty(globalThis, 'window', { value: mockWindow, configurable: true });
    (globalThis as Record<string, unknown>).HTMLElement = MiniEl;
    (globalThis as Record<string, unknown>).HTMLIFrameElement = HTMLIFrameElementShim;
    (globalThis as Record<string, unknown>).Node = MiniEl;
    (globalThis as Record<string, unknown>).Element = MiniEl;
    vi.spyOn(nativeBridge, 'isNativeCanvasActive').mockReturnValue(false);
    toolStoreActions.updateBrushSettings(makeTestBrush({ size: 12 }));
  });

  afterEach(() => {
    if (root) {
      act(() => {
        root!.unmount();
      });
      root = null;
    }
    Object.defineProperty(globalThis, 'document', { value: origDoc, configurable: true });
    Object.defineProperty(globalThis, 'window', { value: origWin, configurable: true });
    (globalThis as Record<string, unknown>).HTMLElement = origHTMLElement;
    (globalThis as Record<string, unknown>).HTMLIFrameElement = origHTMLIFrameElement;
    (globalThis as Record<string, unknown>).Node = origNode;
    (globalThis as Record<string, unknown>).Element = origElement;
    vi.restoreAllMocks();
  });

  it('re-renders a user-drawn stroke in real time when brush size changes', () => {
    root = createRoot(container as unknown as HTMLElement);
    const initialBs = makeTestBrush({ size: 8, spacing: 0.12 });

    act(() => {
      root!.render(<BrushStudioScratchpad brushSettings={initialBs} />);
    });

    const baseCanvas = byTestId(container, 'scratchpad-base-canvas')!;
    const draftCanvas = byTestId(container, 'scratchpad-draft-canvas')!;
    expect(baseCanvas).not.toBeNull();
    expect(draftCanvas).not.toBeNull();

    // Starter S-curve sample stroke rendered immediately on mount
    expect(baseCanvas.mockDrawLog.ellipses.length).toBeGreaterThan(0);

    // Draw a custom stroke on the scratchpad
    baseCanvas.mockDrawLog.ellipses.length = 0;
    act(() => {
      draftCanvas.dispatchEvent(
        makePointerEvent('pointerdown', { pointerId: 1, clientX: 80, clientY: 200, pressure: 0.8 })
      );
      draftCanvas.dispatchEvent(
        makePointerEvent('pointermove', { pointerId: 1, clientX: 260, clientY: 220, pressure: 0.8 })
      );
      draftCanvas.dispatchEvent(
        makePointerEvent('pointerup', { pointerId: 1, clientX: 260, clientY: 220, pressure: 0.8 })
      );
    });

    expect(baseCanvas.mockDrawLog.ellipses.length).toBeGreaterThan(0);
    const smallMaxRadius = Math.max(...baseCanvas.mockDrawLog.ellipses.map((e) => e.rx));

    // Increase brush size to 48px — recorded stroke must immediately re-render wider!
    baseCanvas.mockDrawLog.ellipses.length = 0;
    baseCanvas.mockDrawLog.clears = 0;
    act(() => {
      root!.render(
        <BrushStudioScratchpad brushSettings={makeTestBrush({ size: 48, spacing: 0.12 })} />
      );
    });

    expect(baseCanvas.mockDrawLog.clears).toBeGreaterThan(0);
    expect(baseCanvas.mockDrawLog.ellipses.length).toBeGreaterThan(0);
    const largeMaxRadius = Math.max(...baseCanvas.mockDrawLog.ellipses.map((e) => e.rx));
    expect(largeMaxRadius).toBeGreaterThan(smallMaxRadius * 4);
  });

  it('freezes drawn strokes when Live toggle is turned off and resumes when turned back on', () => {
    root = createRoot(container as unknown as HTMLElement);
    act(() => {
      root!.render(<BrushStudioScratchpad brushSettings={makeTestBrush({ size: 10 })} />);
    });

    const baseCanvas = byTestId(container, 'scratchpad-base-canvas')!;
    const draftCanvas = byTestId(container, 'scratchpad-draft-canvas')!;
    const liveBtn = byTestId(container, 'scratchpad-live-toggle')!;

    act(() => {
      draftCanvas.dispatchEvent(
        makePointerEvent('pointerdown', { pointerId: 2, clientX: 100, clientY: 150 })
      );
      draftCanvas.dispatchEvent(
        makePointerEvent('pointermove', { pointerId: 2, clientX: 240, clientY: 160 })
      );
      draftCanvas.dispatchEvent(
        makePointerEvent('pointerup', { pointerId: 2, clientX: 240, clientY: 160 })
      );
    });

    // Turn Live Preview OFF
    expect(liveBtn.getAttribute('aria-pressed')).toBe('true');
    act(() => {
      liveBtn.click();
    });
    expect(liveBtn.getAttribute('aria-pressed')).toBe('false');

    baseCanvas.mockDrawLog.ellipses.length = 0;
    baseCanvas.mockDrawLog.clears = 0;
    act(() => {
      root!.render(<BrushStudioScratchpad brushSettings={makeTestBrush({ size: 60 })} />);
    });
    // Frozen — no re-render on setting change
    expect(baseCanvas.mockDrawLog.clears).toBe(0);
    expect(baseCanvas.mockDrawLog.ellipses.length).toBe(0);

    // Turn Live Preview back ON — immediately replays stroke with size=60
    act(() => {
      liveBtn.click();
    });
    expect(baseCanvas.mockDrawLog.clears).toBeGreaterThan(0);
    expect(baseCanvas.mockDrawLog.ellipses.length).toBeGreaterThan(0);
  });

  it('exposes live quick-tune Size, Opacity, and Flow controls inside BrushStudioModal', () => {
    root = createRoot(container as unknown as HTMLElement);
    act(() => {
      root!.render(<BrushStudioModal isOpen onClose={vi.fn()} showToast={vi.fn()} />);
    });

    const sizeSlider = byTestId(container, 'scratchpad-size-slider')!;
    const opacitySlider = byTestId(container, 'scratchpad-opacity-slider')!;
    const flowSlider = byTestId(container, 'scratchpad-flow-slider')!;
    expect(sizeSlider).not.toBeNull();
    expect(opacitySlider).not.toBeNull();
    expect(flowSlider).not.toBeNull();

    // Trigger React's controlled range input onChange handler (handles both DOM input and Node-import fallback)
    const propsKey = Object.keys(sizeSlider).find((k) => k.startsWith('__reactProps$'));
    const reactProps = propsKey
      ? (sizeSlider as unknown as Record<string, { onChange?: (ev: unknown) => void }>)[propsKey]
      : undefined;
    expect(typeof reactProps?.onChange).toBe('function');
    act(() => {
      sizeSlider.value = '72';
      reactProps?.onChange?.({ target: sizeSlider, currentTarget: sizeSlider });
    });
    expect(useToolStore.getState().brushSettings.size).toBe(72);
  });

  it('dispatches recorded strokes to DX12 renderNativeScratchpadPreview when native canvas is active', async () => {
    vi.spyOn(nativeBridge, 'isNativeCanvasActive').mockReturnValue(true);
    const nativeSpy = vi
      .spyOn(nativeBridge, 'renderNativeScratchpadPreview')
      .mockResolvedValue(null);

    root = createRoot(container as unknown as HTMLElement);
    await act(async () => {
      root!.render(<BrushStudioScratchpad brushSettings={makeTestBrush({ size: 16 })} />);
    });
    expect(nativeSpy).toHaveBeenCalledTimes(1);
    expect(nativeSpy.mock.calls[0][1].size).toBe(16);
    expect(nativeSpy.mock.calls[0][4].length).toBe(1);

    // Editing brush size immediately triggers a fresh DX12 preview render on the same stroke
    await act(async () => {
      root!.render(<BrushStudioScratchpad brushSettings={makeTestBrush({ size: 42 })} />);
    });
    expect(nativeSpy.mock.calls.length).toBeGreaterThanOrEqual(2);
    const lastCall = nativeSpy.mock.calls[nativeSpy.mock.calls.length - 1];
    expect(lastCall[1].size).toBe(42);
    expect(lastCall[4].length).toBe(1);
  });
});