Skip to content

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

14.4 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { Csp3DToolbar } from '../../components/Csp3DToolbar';
import { Tool3DPropertyInspector } from '../../components/Tool3DPropertyInspector';
import { useExternalFileDrop, UseExternalFileDropResult } from '../../hooks/useExternalFileDrop';
import {
  documentStoreActions,
  scene3DBridge,
  store3DActions,
  uiStoreActions,
} from '../../stores';
import { Primitive3DType } from '../primitives3D';

class TestTextNode {
  public nodeType = 3;
  public nodeName = '#text';
  public parentNode: TestElement | null = null;
  constructor(
    public nodeValue: string,
    public ownerDocument: TestDocument
  ) {}
}

class TestElement extends EventTarget {
  public nodeType = 1;
  public nodeName: string;
  public tagName: string;
  public namespaceURI = 'http://www.w3.org/1999/xhtml';
  public parentNode: TestElement | null = null;
  public childNodes: Array<TestElement | TestTextNode> = [];
  public style: Record<string, string> = {};
  public attributes = new Map<string, string>();
  public dataset: Record<string, string> = {};
  public value = '';
  public disabled = false;
  public type = '';
  public className = '';

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

  appendChild<T extends TestElement | TestTextNode>(child: T): T {
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }

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

  insertBefore<T extends TestElement | TestTextNode>(
    child: T,
    ref: TestElement | TestTextNode | null
  ): T {
    child.parentNode = this;
    const idx = ref ? this.childNodes.indexOf(ref) : -1;
    if (idx >= 0) this.childNodes.splice(idx, 0, child);
    else this.childNodes.push(child);
    return child;
  }

  setAttribute(name: string, val: string) {
    const str = String(val);
    this.attributes.set(name, str);
    if (name.startsWith('data-')) {
      const camel = name
        .slice(5)
        .replace(/-([a-z])/g, (_, ch: string) => ch.toUpperCase());
      this.dataset[camel] = str;
    }
    if (name === 'type') this.type = str;
    if (name === 'value') this.value = str;
  }

  removeAttribute(name: string) {
    this.attributes.delete(name);
    if (name.startsWith('data-')) {
      const camel = name
        .slice(5)
        .replace(/-([a-z])/g, (_, ch: string) => ch.toUpperCase());
      delete this.dataset[camel];
    }
  }

  getAttribute(name: string): string | null {
    return this.attributes.has(name) ? this.attributes.get(name)! : null;
  }

  closest(selector: string): TestElement | null {
    let cur: TestElement | null = this;
    while (cur) {
      if (selector === '[data-drop-zone]' && cur.dataset.dropZone !== undefined) return cur;
      if (selector === '[data-layer-id]' && cur.dataset.layerId !== undefined) return cur;
      if (
        selector === '[data-testid="sub-view-panel"]' &&
        cur.dataset.testid === 'sub-view-panel'
      ) {
        return cur;
      }
      cur = cur.parentNode;
    }
    return null;
  }

  getBoundingClientRect(): DOMRect {
    return {
      top: 0,
      left: 0,
      bottom: 200,
      right: 200,
      width: 200,
      height: 200,
      x: 0,
      y: 0,
      toJSON: () => ({}),
    } as DOMRect;
  }

  get textContent(): string {
    return this.childNodes
      .map((c) => (c instanceof TestTextNode ? c.nodeValue : c.textContent))
      .join('');
  }

  set textContent(v: string) {
    this.childNodes = [];
    if (v) this.appendChild(new TestTextNode(v, this.ownerDocument));
  }

  override dispatchEvent(event: Event): boolean {
    const path: EventTarget[] = [];
    let cur: TestElement | null = this;
    while (cur) {
      path.push(cur);
      cur = cur.parentNode;
    }
    path.push(this.ownerDocument);
    if (this.ownerDocument.defaultView && this.ownerDocument.defaultView instanceof EventTarget) {
      path.push(this.ownerDocument.defaultView);
    }

    Object.defineProperty(event, 'target', { value: this, configurable: true });
    for (const node of path) {
      Object.defineProperty(event, 'currentTarget', { value: node, configurable: true });
      EventTarget.prototype.dispatchEvent.call(node, event);
      if (event.cancelBubble) break;
    }
    return !event.defaultPrevented;
  }
}

class TestDocument extends EventTarget {
  public nodeType = 9;
  public activeElement: TestElement | null = null;
  public defaultView: unknown = null;
  public documentElement: TestElement;
  public body: TestElement;
  public hitElement: TestElement | null = null;

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

  createElement(tag: string) {
    return new TestElement(tag, this);
  }

  createElementNS(_ns: string, tag: string) {
    return new TestElement(tag, this);
  }

  createTextNode(text: string) {
    return new TestTextNode(text, this);
  }

  createComment() {
    return new TestTextNode('', this);
  }

  elementFromPoint(_x: number, _y: number) {
    return this.hitElement;
  }
}

function findByTestId(root: TestElement, testId: string): TestElement | null {
  if (root.getAttribute('data-testid') === testId) return root;
  for (const child of root.childNodes) {
    if (child instanceof TestElement) {
      const found = findByTestId(child, testId);
      if (found) return found;
    }
  }
  return null;
}

describe('3D Mode Primitives UI & Drag-and-Drop 3D Model Import', () => {
  const origWindow = (globalThis as Record<string, unknown>).window;
  const origDocument = (globalThis as Record<string, unknown>).document;
  const origHTMLElement = (globalThis as Record<string, unknown>).HTMLElement;
  const origHTMLIFrameElement = (globalThis as Record<string, unknown>).HTMLIFrameElement;
  const origElement = (globalThis as Record<string, unknown>).Element;
  const origNode = (globalThis as Record<string, unknown>).Node;
  const origActEnv = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;

  let doc: TestDocument;
  let win: EventTarget;
  let container: TestElement;
  let root: Root;

  beforeEach(() => {
    class HTMLIFrameElementShim extends TestElement {}
    (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
    doc = new TestDocument();
    win = Object.assign(new EventTarget(), {
      document: doc,
      innerWidth: 1280,
      innerHeight: 800,
      devicePixelRatio: 1,
      navigator: {},
      Node: TestElement,
      HTMLElement: TestElement,
      HTMLIFrameElement: HTMLIFrameElementShim,
      Element: TestElement,
    });
    doc.defaultView = win;
    (globalThis as Record<string, unknown>).document = doc;
    (globalThis as Record<string, unknown>).window = win;
    (globalThis as Record<string, unknown>).Element = TestElement;
    (globalThis as Record<string, unknown>).HTMLElement = TestElement;
    (globalThis as Record<string, unknown>).HTMLIFrameElement = HTMLIFrameElementShim;
    (globalThis as Record<string, unknown>).Node = TestElement;

    container = doc.createElement('div');
    doc.body.appendChild(container);
    root = createRoot(container as unknown as HTMLElement);
    store3DActions.resetSceneMeta();
  });

  afterEach(async () => {
    await act(async () => {
      root.unmount();
    });
    scene3DBridge.createPrimitive = undefined;
    uiStoreActions.set3DLayerOpen(false, null);
    documentStoreActions.setDocuments([]);
    documentStoreActions.setActiveDocumentId(null);
    (globalThis as Record<string, unknown>).window = origWindow;
    (globalThis as Record<string, unknown>).document = origDocument;
    (globalThis as Record<string, unknown>).HTMLElement = origHTMLElement;
    (globalThis as Record<string, unknown>).HTMLIFrameElement = origHTMLIFrameElement;
    (globalThis as Record<string, unknown>).Element = origElement;
    (globalThis as Record<string, unknown>).Node = origNode;
    (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = origActEnv;
  });

  it('opens Primitives popover in Csp3DToolbar and creates all 5 primitive shapes', () => {
    const onCreatePrimitive = vi.fn();

    act(() => {
      root.render(
        <Csp3DToolbar
          is3DToolActive={true}
          onActivate3DTool={() => {}}
          onDirectDrag={() => {}}
          onDirectDragEnd={() => {}}
          onTriggerImport={() => {}}
          onCreatePrimitive={onCreatePrimitive}
          onSnapToGround={() => {}}
          onUndo={() => {}}
          onRedo={() => {}}
          onOpenLTModal={() => {}}
          onBakeTo2D={() => {}}
          onClose={() => {}}
        />
      );
    });

    const shapes: Primitive3DType[] = ['cube', 'sphere', 'capsule', 'cylinder', 'pyramid'];
    for (const shape of shapes) {
      const trigger = findByTestId(container, 'toolbar-3d-primitives-btn');
      expect(trigger).not.toBeNull();
      act(() => {
        trigger!.dispatchEvent(new Event('click', { bubbles: true }));
      });
      const btn = findByTestId(container, `toolbar-3d-primitive-${shape}`);
      expect(btn).not.toBeNull();
      act(() => {
        btn!.dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(findByTestId(container, 'toolbar-3d-primitives-popover')).toBeNull();
    }

    expect(onCreatePrimitive.mock.calls.map((c) => c[0])).toEqual(shapes);
  });

  it('triggers scene3DBridge.createPrimitive for every primitive in Tool3DPropertyInspector', () => {
    const createSpy = vi.fn();
    scene3DBridge.createPrimitive = createSpy;
    documentStoreActions.setDocuments([
      {
        id: 'doc-1',
        name: 'Test',
        dimensions: { width: 800, height: 600, dpi: 300 },
        colorMode: 'color',
        layers: [],
        activeLayerId: '',
      },
    ]);
    documentStoreActions.setActiveDocumentId('doc-1');
    uiStoreActions.set3DLayerOpen(true);

    act(() => {
      root.render(<Tool3DPropertyInspector />);
    });

    const shapes: Primitive3DType[] = ['cube', 'sphere', 'capsule', 'cylinder', 'pyramid'];
    for (const shape of shapes) {
      const btn = findByTestId(container, `inspector-3d-primitive-${shape}`);
      expect(btn).not.toBeNull();
      act(() => {
        btn!.dispatchEvent(new Event('click', { bubbles: true }));
      });
    }

    expect(createSpy.mock.calls.map((c) => c[0])).toEqual(shapes);
  });

  it('imports dropped .glb/.obj models in 3D mode via HTML5 drag-and-drop without affecting image layer drops', async () => {
    const importImageFileAsLayer = vi.fn(async (file: File) => ({ id: 'l-1', name: file.name }));
    const import3DModelFile = vi.fn();
    const onMarkDirty = vi.fn();
    const showToast = vi.fn();

    const hookState: { current: UseExternalFileDropResult | null } = { current: null };
    function Harness() {
      hookState.current = useExternalFileDrop({
        enabled: true,
        is3DModeActive: true,
        importImageFileAsLayer,
        import3DModelFile,
        onMarkDirty,
        showToast,
      });
      return null;
    }

    const canvasZone = doc.createElement('main');
    canvasZone.setAttribute('data-drop-zone', 'canvas');
    doc.body.appendChild(canvasZone);

    const layersZone = doc.createElement('aside');
    layersZone.setAttribute('data-drop-zone', 'layers');
    doc.body.appendChild(layersZone);

    act(() => {
      root.render(<Harness />);
    });

    // 1. Dragging a .glb file over canvas highlights with payloadKind: '3d-model'
    const glbFile = new File([new Uint8Array([1, 2, 3, 4])], 'hero.glb', {
      type: 'model/gltf-binary',
    });
    doc.hitElement = canvasZone;
    const dragOverCanvas = new Event('dragover', { bubbles: true, cancelable: true });
    Object.defineProperty(dragOverCanvas, 'clientX', { value: 100 });
    Object.defineProperty(dragOverCanvas, 'clientY', { value: 100 });
    Object.defineProperty(dragOverCanvas, 'dataTransfer', {
      value: { types: ['Files'], files: [glbFile], dropEffect: 'none' },
    });

    act(() => {
      canvasZone.dispatchEvent(dragOverCanvas);
    });
    expect(hookState.current?.activeDropTarget).toEqual({ zone: 'canvas', payloadKind: '3d-model' });

    // 2. Dragging a .glb file over layers panel clears highlight (3D models don't insert into layer rows)
    doc.hitElement = layersZone;
    const dragOverLayers = new Event('dragover', { bubbles: true, cancelable: true });
    Object.defineProperty(dragOverLayers, 'clientX', { value: 100 });
    Object.defineProperty(dragOverLayers, 'clientY', { value: 100 });
    Object.defineProperty(dragOverLayers, 'dataTransfer', {
      value: { types: ['Files'], files: [glbFile], dropEffect: 'none' },
    });
    act(() => {
      layersZone.dispatchEvent(dragOverLayers);
    });
    expect(hookState.current?.activeDropTarget).toBeNull();

    // 3. Dropping a .glb file on canvas calls import3DModelFile and NOT importImageFileAsLayer
    doc.hitElement = canvasZone;
    const drop3DEvent = new Event('drop', { bubbles: true, cancelable: true });
    Object.defineProperty(drop3DEvent, 'clientX', { value: 100 });
    Object.defineProperty(drop3DEvent, 'clientY', { value: 100 });
    Object.defineProperty(drop3DEvent, 'dataTransfer', {
      value: { types: ['Files'], files: [glbFile] },
    });
    await act(async () => {
      canvasZone.dispatchEvent(drop3DEvent);
      await Promise.resolve();
    });
    expect(import3DModelFile).toHaveBeenCalledTimes(1);
    expect(import3DModelFile).toHaveBeenCalledWith(glbFile);
    expect(importImageFileAsLayer).not.toHaveBeenCalled();

    // 4. Dropping a .png image on canvas while in 3D mode still imports as a 2D layer
    const pngFile = new File([new Uint8Array([137, 80, 78, 71])], 'ref.png', {
      type: 'image/png',
    });
    const dropImgEvent = new Event('drop', { bubbles: true, cancelable: true });
    Object.defineProperty(dropImgEvent, 'clientX', { value: 100 });
    Object.defineProperty(dropImgEvent, 'clientY', { value: 100 });
    Object.defineProperty(dropImgEvent, 'dataTransfer', {
      value: { types: ['Files'], files: [pngFile] },
    });
    await act(async () => {
      canvasZone.dispatchEvent(dropImgEvent);
      await Promise.resolve();
    });
    expect(importImageFileAsLayer).toHaveBeenCalledTimes(1);
    expect(onMarkDirty).toHaveBeenCalledTimes(1);
  });
});