Skip to content

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

20.9 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { SubToolList } from '../SubToolList';
import { RightSidebar } from '../RightSidebar';
import { WelcomeScreen } from '../WelcomeScreen';
import { BrushStudioModal } from '../BrushStudioModal';
import { uiStoreActions, toolStoreActions } from '../../stores';
import { DEFAULT_APPEARANCE_CONFIG } from '../../types/appearance';
import type { LayerItem } from '../../types/editor';
import type { RecentDocument } from '../../utils/recentDocumentsManager';

const mockLoadRecentDocuments = vi.fn<() => Promise<RecentDocument[]>>();
const mockToggleStarDocument = vi.fn();
const mockRemoveRecentDocument = vi.fn();
const mockPermanentlyDeleteDocument = vi.fn();

vi.mock('../../utils/recentDocumentsManager', () => ({
  loadRecentDocuments: (...args: unknown[]) => mockLoadRecentDocuments(...(args as [])),
  toggleStarDocument: (...args: unknown[]) => mockToggleStarDocument(...args),
  removeRecentDocument: (...args: unknown[]) => mockRemoveRecentDocument(...args),
  permanentlyDeleteDocument: (...args: unknown[]) => mockPermanentlyDeleteDocument(...args),
  formatFileSize: (bytes: number) => `${Math.round(bytes / 1024)} KB`,
}));

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;
  clientWidth = 260;
  clientHeight = 120;
  width = 0;
  height = 0;
  attrs = new Map<string, string>();
  private _value = '';
  private legacyListeners = new Map<string, Set<(ev: unknown) => void>>();

  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 options(): MiniEl[] {
    const out: MiniEl[] = [];
    const visit = (node: MiniEl) => {
      for (const c of node.childNodes) {
        if (c instanceof MiniEl) {
          if (c.tagName === 'OPTION') out.push(c);
          else visit(c);
        }
      }
    };
    visit(this);
    return out;
  }

  selected = false;
  defaultSelected = false;

  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() {
    return null;
  }

  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;
  }

  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);
  }

  contains(target: unknown): boolean {
    if (target === this) return true;
    for (const c of this.childNodes) {
      if (c === target) return true;
      if (c instanceof MiniEl && c.contains(target)) return true;
    }
    return false;
  }

  addEventListener(
    type: string,
    listener: EventListenerOrEventListenerObject | null,
    options?: boolean | AddEventListenerOptions
  ) {
    if (typeof listener === 'function') {
      let set = this.legacyListeners.get(type);
      if (!set) {
        set = new Set();
        this.legacyListeners.set(type, set);
      }
      set.add(listener as (ev: unknown) => void);
    }
    super.addEventListener(type, listener, options);
  }

  removeEventListener(
    type: string,
    listener: EventListenerOrEventListenerObject | null,
    options?: boolean | EventListenerOptions
  ) {
    if (typeof listener === 'function') {
      this.legacyListeners.get(type)?.delete(listener as (ev: unknown) => void);
    }
    super.removeEventListener(type, listener, options);
  }

  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() {
    const ev = new Event('click', { bubbles: true, cancelable: true });
    this.dispatchEvent(ev);
  }
}

class MiniDoc extends EventTarget {
  nodeType = 9;
  defaultView: unknown = globalThis;
  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);
  }

  querySelectorAll() {
    return [];
  }
}

function walk(root: MiniEl, predicate: (el: MiniEl) => boolean): MiniEl[] {
  const out: MiniEl[] = [];
  const visit = (node: MiniEl) => {
    if (predicate(node)) out.push(node);
    for (const c of node.childNodes) {
      if (c instanceof MiniEl) visit(c);
    }
  };
  visit(root);
  return out;
}

function byTestId(root: MiniEl, id: string): MiniEl | null {
  return walk(root, (el) => el.getAttribute('data-testid') === id)[0] ?? null;
}

describe('Pass 7 Signature Craft Surfaces', () => {
  let doc: MiniDoc;
  let container: MiniEl;
  let root: Root | null = null;
  const origDoc = globalThis.document;
  const origWin = globalThis.window;
  const origComputedStyle = globalThis.getComputedStyle;
  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;
  const origAct = (globalThis as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT;

  beforeEach(() => {
    doc = new MiniDoc();
    container = doc.createElement('div');
    doc.body.appendChild(container);
    const winTarget = new EventTarget();
    const mockGetComputedStyle = () => ({
      getPropertyValue: (name: string) => {
        if (name === '--ui-text-primary') return '#F2F4F8';
        if (name === '--ui-text-muted') return '#8E94A0';
        return '';
      },
    });
    class HTMLIFrameElementShim extends MiniEl {}
    const mockWindow = {
      document: doc,
      addEventListener: winTarget.addEventListener.bind(winTarget),
      removeEventListener: winTarget.removeEventListener.bind(winTarget),
      dispatchEvent: winTarget.dispatchEvent.bind(winTarget),
      getComputedStyle: mockGetComputedStyle,
      HTMLElement: MiniEl,
      HTMLIFrameElement: HTMLIFrameElementShim,
      Node: MiniEl,
      Element: MiniEl,
      devicePixelRatio: 1,
      innerWidth: 1280,
      innerHeight: 800,
    };
    doc.defaultView = mockWindow;
    const g = globalThis as Record<string, unknown>;
    g.IS_REACT_ACT_ENVIRONMENT = true;
    g.document = doc;
    g.window = mockWindow;
    g.HTMLElement = MiniEl;
    g.HTMLIFrameElement = HTMLIFrameElementShim;
    g.Node = MiniEl;
    g.Element = MiniEl;
    g.getComputedStyle = mockGetComputedStyle;
    mockLoadRecentDocuments.mockReset();
    mockLoadRecentDocuments.mockResolvedValue([]);
    mockToggleStarDocument.mockReset();
    mockRemoveRecentDocument.mockReset();
    mockPermanentlyDeleteDocument.mockReset();
    uiStoreActions.updateAppearance({ ...DEFAULT_APPEARANCE_CONFIG }, { persist: false });
    toolStoreActions.selectTool('brush');
  });

  afterEach(() => {
    if (root) {
      act(() => {
        root?.unmount();
      });
      root = null;
    }
    const g = globalThis as Record<string, unknown>;
    g.document = origDoc;
    g.window = origWin;
    g.getComputedStyle = origComputedStyle;
    g.HTMLElement = origHTMLElement;
    g.HTMLIFrameElement = origHTMLIFrameElement;
    g.Node = origNode;
    g.Element = origElement;
    g.IS_REACT_ACT_ENVIRONMENT = origAct;
  });

  it('SubToolList honors appearance.brushListStyle (stroke, compact, grid) and density', () => {
    root = createRoot(container as unknown as HTMLElement);
    const setCustomBrushes = vi.fn();

    act(() => {
      root!.render(<SubToolList customBrushes={[]} setCustomBrushes={setCustomBrushes} />);
    });

    const listRoot = byTestId(container, 'subtool-list-root');
    expect(listRoot).not.toBeNull();
    expect(listRoot?.getAttribute('data-brush-list-style')).toBe('stroke');
    expect(walk(container, (el) => el.tagName === 'CANVAS').length).toBeGreaterThan(0);

    // Switch to compact mode -> no stroke canvas previews rendered
    act(() => {
      uiStoreActions.updateAppearance({ brushListStyle: 'compact', density: 'compact' });
    });
    expect(listRoot?.getAttribute('data-brush-list-style')).toBe('compact');
    expect(listRoot?.getAttribute('data-density')).toBe('compact');
    expect(walk(container, (el) => el.tagName === 'CANVAS').length).toBe(0);

    // Switch to grid mode -> 2-column grid cards with stroke preview canvases
    act(() => {
      uiStoreActions.updateAppearance({ brushListStyle: 'grid', density: 'comfortable' });
    });
    expect(listRoot?.getAttribute('data-brush-list-style')).toBe('grid');
    expect(listRoot?.getAttribute('data-density')).toBe('comfortable');
    expect(walk(container, (el) => el.tagName === 'CANVAS').length).toBeGreaterThan(0);
    expect(
      walk(container, (el) => el.className.includes('grid-cols-2')).length
    ).toBeGreaterThan(0);
  });

  it('RightSidebar Layers Panel scales thumbnails via appearance.layerThumbSize and renders nested/clipped craft + bottom bar', () => {
    const layers: LayerItem[] = [
      {
        id: 'folder-1',
        name: 'Lineart Group',
        type: 'folder',
        visible: true,
        opacity: 1,
        blendMode: 'normal',
        locked: false,
        collapsed: false,
        parentId: null,
      },
      {
        id: 'layer-child',
        name: 'Inks',
        type: 'raster',
        visible: true,
        opacity: 0.85,
        blendMode: 'multiply',
        locked: false,
        parentId: 'folder-1',
      },
      {
        id: 'layer-clip',
        name: 'Clipped Shading',
        type: 'raster',
        visible: true,
        opacity: 0.7,
        blendMode: 'normal',
        locked: false,
        clipped: true,
        parentId: 'folder-1',
      },
    ];

    const onAddLayer = vi.fn();
    const onDeleteLayer = vi.fn();
    const onOpenLayerStylesModal = vi.fn();

    root = createRoot(container as unknown as HTMLElement);
    act(() => {
      root!.render(
        <RightSidebar
          dockedMode="layers"
          hideColorPanel
          hasOpenDocument
          layers={layers}
          activeLayerId="layer-child"
          historyList={[]}
          historyIndex={-1}
          onJumpToHistory={vi.fn()}
          canUndo={false}
          canRedo={false}
          onUndo={vi.fn()}
          onRedo={vi.fn()}
          onSelectLayer={vi.fn()}
          onAddLayer={onAddLayer}
          onDuplicateLayer={vi.fn()}
          onDeleteLayer={onDeleteLayer}
          onToggleVisibility={vi.fn()}
          onSetOpacity={vi.fn()}
          onSetBlendMode={vi.fn()}
          onToggleLock={vi.fn()}
          onToggleAlphaLock={vi.fn()}
          onToggleClipping={vi.fn()}
          onToggleCollapse={vi.fn()}
          onRenameLayer={vi.fn()}
          onMoveLayerToFolder={vi.fn()}
          onAddLayerMask={vi.fn()}
          onOpenAdjustmentModal={vi.fn()}
          onOpenLayerStylesModal={onOpenLayerStylesModal}
        />
      );
    });

    const section = byTestId(container, 'layers-panel-section');
    expect(section).not.toBeNull();
    expect(section?.getAttribute('data-layer-thumb-size')).toBe('standard');
    expect(byTestId(container, 'layers-sticky-header')).not.toBeNull();
    expect(byTestId(container, 'layers-bottom-action-bar')).not.toBeNull();

    // Standard thumbnails are 34px x 34px with theme-calibrated checkerboard
    const checkThumbSize = (expectedPx: string) => {
      const thumbs = walk(container, (el) => el.className.includes('ui-layer-thumb-checker'));
      expect(thumbs.length).toBeGreaterThanOrEqual(2);
      expect(thumbs[0].style.width).toBe(expectedPx);
      expect(thumbs[0].style.height).toBe(expectedPx);
    };
    checkThumbSize('34px');

    act(() => {
      uiStoreActions.updateAppearance({ layerThumbSize: 'compact' });
    });
    expect(section?.getAttribute('data-layer-thumb-size')).toBe('compact');
    checkThumbSize('24px');

    act(() => {
      uiStoreActions.updateAppearance({ layerThumbSize: 'large' });
    });
    expect(section?.getAttribute('data-layer-thumb-size')).toBe('large');
    checkThumbSize('46px');

    // Bottom action bar triggers Add Layer and Add Folder
    const bottomBar = byTestId(container, 'layers-bottom-action-bar')!;
    const addLayerBtn = walk(bottomBar, (el) => el.getAttribute('title') === 'New Layer (Ctrl+Shift+N)')[0];
    const addFolderBtn = walk(bottomBar, (el) => el.getAttribute('title') === 'New Folder / Group (Ctrl+G)')[0];
    const stylesBtn = walk(bottomBar, (el) => el.getAttribute('title') === 'Layer Styles (fx)')[0];
    expect(addLayerBtn).toBeDefined();
    expect(addFolderBtn).toBeDefined();
    expect(stylesBtn).toBeDefined();

    act(() => {
      addLayerBtn.click();
      addFolderBtn.click();
      stylesBtn.click();
    });
    expect(onAddLayer).toHaveBeenCalledWith('raster');
    expect(onAddLayer).toHaveBeenCalledWith('folder');
    expect(onOpenLayerStylesModal).toHaveBeenCalledWith('layer-child');
  });

  it('WelcomeScreen renders Atelier Hub with Quick-Start Sheets and recent dimensions', async () => {
    mockLoadRecentDocuments.mockResolvedValue([
      {
        id: 'doc-1',
        title: 'Chapter_01_Page_04.ink',
        path: '/projects/Chapter_01_Page_04.ink',
        lastOpened: Date.now(),
        size: 204800,
        isStarred: true,
        width: 2480,
        height: 3508,
        dpi: 300,
      },
    ]);

    const onNewDocument = vi.fn();
    const onCreateQuickCanvas = vi.fn();
    const onOpenFile = vi.fn();

    uiStoreActions.updateAppearance(
      {
        density: 'compact',
        cornerRadius: 'sharp',
        chromeStyle: 'islands',
      },
      { persist: false }
    );

    root = createRoot(container as unknown as HTMLElement);
    await act(async () => {
      root!.render(
        <WelcomeScreen
          userName="Sora"
          onNewDocument={onNewDocument}
          onCreateQuickCanvas={onCreateQuickCanvas}
          onOpenFile={onOpenFile}
          showToast={vi.fn()}
        />
      );
      await Promise.resolve();
    });

    const welcomeRoot = byTestId(container, 'welcome-atelier-hub');
    expect(welcomeRoot).not.toBeNull();
    expect(welcomeRoot?.className).toContain('ui-drafting-grid');
    expect(welcomeRoot?.getAttribute('data-density')).toBe('compact');
    expect(welcomeRoot?.getAttribute('data-chrome-style')).toBe('islands');

    // Quick-Start Manga B4 tile creates exact 600 DPI monochrome sheet
    const mangaBtn = byTestId(container, 'welcome-preset-manga-b4-600');
    expect(mangaBtn).not.toBeNull();
    act(() => {
      mangaBtn!.click();
    });
    expect(onCreateQuickCanvas).toHaveBeenCalledWith(
      expect.objectContaining({
        width: 6071,
        height: 8598,
        dpi: 600,
        colorMode: 'monochrome',
        defaultFrequency: 60,
      })
    );

    // Custom... tile opens full New Canvas modal
    const customBtn = byTestId(container, 'welcome-preset-custom');
    expect(customBtn).not.toBeNull();
    act(() => {
      customBtn!.click();
    });
    expect(onNewDocument).toHaveBeenCalledTimes(1);

    // Recent card shows aspect-aware dimensions metadata
    expect(container.textContent).toContain('2480×3508');
    expect(container.textContent).toContain('Chapter_01_Page_04.ink');
  });

  it('BrushStudioModal frames left category rail, live scratchpad surface switcher, and SectionDisclosure inspector', () => {
    const onClose = vi.fn();
    root = createRoot(container as unknown as HTMLElement);

    act(() => {
      root!.render(<BrushStudioModal isOpen onClose={onClose} showToast={vi.fn()} />);
    });

    const modal = byTestId(container, 'brush-studio-modal');
    expect(modal).not.toBeNull();
    expect(modal?.getAttribute('role')).toBe('dialog');

    const shapeTab = byTestId(container, 'brush-studio-tab-shape');
    const textureTab = byTestId(container, 'brush-studio-tab-texture');
    expect(shapeTab?.getAttribute('aria-current')).toBe('page');
    expect(textureTab?.getAttribute('aria-current')).toBeNull();

    // Scratchpad surface switcher defaults to Paper White and switches cleanly to Dark Studio / Mid-Grey
    const scratchpad = byTestId(container, 'brush-studio-scratchpad');
    expect(scratchpad).not.toBeNull();
    expect(scratchpad?.textContent).toContain('Paper White');
    const darkBtn = walk(
      scratchpad!,
      (el) => el.tagName === 'BUTTON' && el.textContent.trim() === 'Dark'
    )[0];
    const greyBtn = walk(
      scratchpad!,
      (el) => el.tagName === 'BUTTON' && el.textContent.trim() === 'Grey'
    )[0];
    expect(darkBtn).toBeDefined();
    expect(greyBtn).toBeDefined();
    act(() => {
      darkBtn.click();
    });
    expect(scratchpad?.textContent).toContain('Dark — Draw');
    act(() => {
      greyBtn.click();
    });
    expect(scratchpad?.textContent).toContain('Mid-Grey — Draw');

    // Switch left rail tab to Texture & Grain
    act(() => {
      textureTab!.click();
    });
    expect(textureTab?.getAttribute('aria-current')).toBe('page');
    expect(shapeTab?.getAttribute('aria-current')).toBeNull();
    expect(container.textContent).toContain('Surface Texture Library');
    expect(container.textContent).toContain('Grain & Paper Physics');
  });
});