Skip to content

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

20.2 KB
Raw Blame
// @ts-expect-error node built-in available in vitest runtime without @types/node
import fs from 'node:fs';
// @ts-expect-error node built-in available in vitest runtime without @types/node
import path from 'node:path';
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
  ALL_BUILTIN_BRUSHES,
  BUILTIN_BRUSHES,
  DECORATION_BRUSHES,
  DECORATION_BRUSH_SECTIONS,
  DEFAULT_DECORATION_PRESET_ID,
  getBuiltinBrushConfig,
  isDecorationPresetId,
} from '../presetBrushes';
import {
  DEFAULT_COMMANDS,
  buildSubToolShortcutCommands,
} from '../shortcutManager';
import {
  activateSubToolGroup,
  activateSubToolPreset,
  stepSubTool,
  stepSubToolGroup,
} from '../subToolNavigation';
import { activateQuickBrush, resolveQuickBrush } from '../quickBrushUtils';
import {
  subToolGroupStoreActions,
  toolStoreActions,
  useSubToolGroupStore,
  useToolStore,
} from '../../stores';
import { SubToolList } from '../../components/SubToolList';
import { ToolStrip } from '../../components/ToolStrip';
import type { CspBrush, DecorationCategory } from '../../types/editor';

function makeCustomDecoBrush(
  id: string,
  name: string,
  category: DecorationCategory
): CspBrush {
  return {
    id,
    name,
    category,
    badge: 'Decoration',
    size: 48,
    minSizeFactor: 0.2,
    flow: 1,
    opacity: 1,
    spacing: 0.3,
    hardness: 1,
    thickness: 1,
    angle: 0,
    smoothing: true,
    stabilization: 4,
    usePressure: false,
    useVelocity: false,
    importedAt: Date.now(),
  };
}

// Minimal DOM shim matching subToolGroupsAndShortcuts.test.tsx
class MiniNode {
  nodeType: number;
  parentNode: MiniEl | null = null;
  childNodes: MiniNode[] = [];
  constructor(nodeType: number) {
    this.nodeType = nodeType;
  }
  get firstChild() {
    return this.childNodes[0] ?? null;
  }
  get lastChild() {
    return this.childNodes[this.childNodes.length - 1] ?? null;
  }
  get nextSibling(): MiniNode | null {
    if (!this.parentNode) return null;
    const i = this.parentNode.childNodes.indexOf(this);
    return i >= 0 ? (this.parentNode.childNodes[i + 1] ?? null) : null;
  }
  get previousSibling(): MiniNode | null {
    if (!this.parentNode) return null;
    const i = this.parentNode.childNodes.indexOf(this);
    return i > 0 ? (this.parentNode.childNodes[i - 1] ?? null) : null;
  }
  get textContent(): string {
    return this.childNodes.map((c) => c.textContent).join('');
  }
  set textContent(v: string) {
    this.childNodes = v ? [new MiniText(String(v))] : [];
    for (const c of this.childNodes) c.parentNode = this as unknown as MiniEl;
  }
}

class MiniText extends MiniNode {
  data: string;
  constructor(data: string) {
    super(3);
    this.data = data;
  }
  get nodeValue() {
    return this.data;
  }
  set nodeValue(v: string) {
    this.data = String(v);
  }
  override get textContent() {
    return this.data;
  }
}

class MiniEl extends MiniNode {
  tagName: string;
  nodeName: string;
  attributes = new Map<string, string>();
  style: Record<string, string> = {};
  listeners = new Map<string, Set<EventListener>>();
  className = '';
  disabled = false;
  type = '';
  value = '';
  ownerDocument: unknown = null;

  constructor(tag: string) {
    super(1);
    this.tagName = tag.toUpperCase();
    this.nodeName = this.tagName;
  }
  appendChild<T extends MiniNode>(child: T): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }
  removeChild<T extends MiniNode>(child: T): T {
    const i = this.childNodes.indexOf(child);
    if (i >= 0) {
      this.childNodes.splice(i, 1);
      child.parentNode = null;
    }
    return child;
  }
  insertBefore<T extends MiniNode>(child: T, ref: MiniNode | null): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    if (!ref) {
      this.childNodes.push(child);
      return child;
    }
    const i = this.childNodes.indexOf(ref);
    if (i >= 0) this.childNodes.splice(i, 0, child);
    else this.childNodes.push(child);
    return child;
  }
  setAttribute(k: string, v: string) {
    this.attributes.set(k, String(v));
    if (k === 'class') this.className = String(v);
  }
  getAttribute(k: string): string | null {
    return this.attributes.get(k) ?? null;
  }
  removeAttribute(k: string) {
    this.attributes.delete(k);
  }
  addEventListener(type: string, fn: EventListener) {
    if (!this.listeners.has(type)) this.listeners.set(type, new Set());
    this.listeners.get(type)!.add(fn);
  }
  removeEventListener(type: string, fn: EventListener) {
    this.listeners.get(type)?.delete(fn);
  }
  dispatchEvent(ev: { type: string; target?: unknown; currentTarget?: unknown; bubbles?: boolean; stopPropagation?: () => void; preventDefault?: () => void }) {
    let stopped = false;
    ev.target = ev.target ?? this;
    ev.preventDefault = ev.preventDefault ?? (() => {});
    ev.stopPropagation = () => {
      stopped = true;
    };
    let cur: MiniEl | null = this;
    while (cur && !stopped) {
      ev.currentTarget = cur;
      const set = cur.listeners.get(ev.type);
      if (set) {
        for (const fn of [...set]) fn(ev as unknown as Event);
      }
      if (!ev.bubbles) break;
      cur = cur.parentNode;
    }
    return true;
  }
  closest(sel: string): MiniEl | null {
    const tags = sel.split(',').map((s) => s.trim().toUpperCase());
    let cur: MiniEl | null = this;
    while (cur) {
      if (tags.includes(cur.tagName)) return cur;
      cur = cur.parentNode;
    }
    return null;
  }
  contains(node: MiniNode | null): boolean {
    let cur: MiniNode | null = node;
    while (cur) {
      if (cur === this) return true;
      cur = cur.parentNode;
    }
    return false;
  }
  getBoundingClientRect() {
    return { left: 0, top: 0, right: 100, bottom: 20, width: 100, height: 20, x: 0, y: 0 };
  }
  focus() {}
  getContext() {
    return null;
  }
  querySelectorAll(sel: string): MiniEl[] {
    const out: MiniEl[] = [];
    const attrMatch = sel.match(/^\[([^=\]]+)(?:="([^"]*)")?\]$/);
    const walk = (n: MiniNode) => {
      if (n instanceof MiniEl) {
        if (attrMatch) {
          const val = n.getAttribute(attrMatch[1]);
          if (attrMatch[2] !== undefined ? val === attrMatch[2] : val !== null) {
            out.push(n);
          }
        }
      }
      for (const c of n.childNodes) walk(c);
    };
    walk(this);
    return out;
  }
  querySelector(sel: string): MiniEl | null {
    return this.querySelectorAll(sel)[0] ?? null;
  }
}

function installMiniDom() {
  const docListeners = new Map<string, Set<EventListener>>();
  const winListeners = new Map<string, Set<EventListener>>();
  const body = new MiniEl('body');
  const html = new MiniEl('html');
  html.appendChild(body);
  const doc: Record<string, unknown> = {
    nodeType: 9,
    nodeName: '#document',
    documentElement: html,
    body,
    activeElement: body,
    defaultView: null,
    createElement: (tag: string) => {
      const el = new MiniEl(tag);
      el.ownerDocument = doc;
      return el;
    },
    createElementNS: (_ns: string, tag: string) => {
      const el = new MiniEl(tag);
      el.ownerDocument = doc;
      return el;
    },
    createTextNode: (t: string) => {
      const tn = new MiniText(t);
      (tn as unknown as { ownerDocument: unknown }).ownerDocument = doc;
      return tn;
    },
    createComment: (t: string) => new MiniText(t),
    addEventListener: (t: string, fn: EventListener) => {
      if (!docListeners.has(t)) docListeners.set(t, new Set());
      docListeners.get(t)!.add(fn);
    },
    removeEventListener: (t: string, fn: EventListener) => {
      docListeners.get(t)?.delete(fn);
    },
    querySelector: (sel: string) => body.querySelector(sel),
    querySelectorAll: (sel: string) => body.querySelectorAll(sel),
  };
  body.ownerDocument = doc;
  html.ownerDocument = doc;

  const store = new Map<string, string>();
  const ls = {
    getItem: (k: string) => store.get(k) ?? null,
    setItem: (k: string, v: string) => {
      store.set(k, String(v));
    },
    removeItem: (k: string) => {
      store.delete(k);
    },
    clear: () => store.clear(),
  };

  class MiniIFrame extends MiniEl {}
  const win: Record<string, unknown> = {
    document: doc,
    innerWidth: 1280,
    innerHeight: 800,
    localStorage: ls,
    HTMLElement: MiniEl,
    HTMLIFrameElement: MiniIFrame,
    Node: MiniNode,
    addEventListener: (t: string, fn: EventListener) => {
      if (!winListeners.has(t)) winListeners.set(t, new Set());
      winListeners.get(t)!.add(fn);
    },
    removeEventListener: (t: string, fn: EventListener) => {
      winListeners.get(t)?.delete(fn);
    },
    dispatchEvent: (ev: Event) => {
      for (const fn of [...(winListeners.get(ev.type) ?? [])]) fn(ev);
      return true;
    },
    IS_REACT_ACT_ENVIRONMENT: true,
  };
  doc.defaultView = win;

  (globalThis as unknown as Record<string, unknown>).document = doc;
  (globalThis as unknown as Record<string, unknown>).window = win;
  (globalThis as unknown as Record<string, unknown>).localStorage = ls;
  (globalThis as unknown as Record<string, unknown>).IS_REACT_ACT_ENVIRONMENT = true;
  (globalThis as unknown as Record<string, unknown>).HTMLElement = MiniEl;
  (globalThis as unknown as Record<string, unknown>).HTMLIFrameElement = MiniIFrame;
  (globalThis as unknown as Record<string, unknown>).Node = MiniNode;
  return { doc, body, win, ls };
}

function invokeReactClick(el: MiniEl | null) {
  if (!el) throw new Error('Expected element to click');
  const key = Object.keys(el).find((k) => k.startsWith('__reactProps$'));
  const props = key ? ((el as unknown as Record<string, unknown>)[key] as Record<string, unknown>) : null;
  const onClick = props?.onClick;
  if (typeof onClick !== 'function') {
    throw new Error(`Expected onClick handler on <${el.tagName}>`);
  }
  (onClick as (e: unknown) => void)({
    preventDefault: () => {},
    stopPropagation: () => {},
    currentTarget: el,
    target: el,
  });
}

describe('Decoration tool group (CSP-style)', () => {
  let root: Root | null = null;
  let container: MiniEl | null = null;

  beforeEach(() => {
    installMiniDom();
    subToolGroupStoreActions.resetAllGroups();
    toolStoreActions.selectTool('brush');
    activateSubToolPreset('g-pen');
  });

  afterEach(() => {
    if (root) {
      act(() => {
        root!.unmount();
      });
      root = null;
    }
    container = null;
  });

  it('keeps only the 6 core pen built-in brushes and zero built-in decoration brushes', () => {
    expect(BUILTIN_BRUSHES.map((b) => b.id)).toEqual([
      'g-pen',
      'real-g-pen',
      'textured-pen',
      'rough-pen',
      'dot-pen',
      'calligraphy',
    ]);
    expect(DECORATION_BRUSH_SECTIONS.map((s) => s.label)).toEqual([
      'Background',
      'Clothing',
      'Effect',
    ]);
    expect(DECORATION_BRUSHES).toHaveLength(0);
    expect(DEFAULT_DECORATION_PRESET_ID).toBe('');
    expect(BUILTIN_BRUSHES.some((b) => isDecorationPresetId(b.id))).toBe(false);
    expect(ALL_BUILTIN_BRUSHES.length).toBe(BUILTIN_BRUSHES.length + DECORATION_BRUSHES.length);
    for (const b of BUILTIN_BRUSHES) {
      expect(getBuiltinBrushConfig(b.id)).not.toBeNull();
    }
  });

  it('remembers Brush and Decoration active presets independently when switching tools', () => {
    const customRoses = makeCustomDecoBrush('inkb-deco-roses', 'Custom Roses', 'deco-effect');
    activateSubToolPreset('real-g-pen', [customRoses]);
    expect(useToolStore.getState().tool).toBe('brush');
    expect(useToolStore.getState().activePresetId).toBe('real-g-pen');

    // Pick Custom Roses inside Decoration
    activateSubToolPreset(customRoses.id, [customRoses]);
    expect(useToolStore.getState().tool).toBe('decoration');
    expect(useToolStore.getState().activePresetId).toBe(customRoses.id);

    // Switch back to Brush -> restores Real G-Pen
    toolStoreActions.selectTool('brush');
    expect(useToolStore.getState().tool).toBe('brush');
    expect(useToolStore.getState().activePresetId).toBe('real-g-pen');

    // Switch back to Decoration -> restores Custom Roses
    toolStoreActions.selectTool('decoration');
    expect(useToolStore.getState().tool).toBe('decoration');
    expect(useToolStore.getState().activePresetId).toBe(customRoses.id);

    // Switch to Eraser then pick a color -> returns to Decoration (last paint tool)
    toolStoreActions.selectTool('eraser');
    expect(useToolStore.getState().tool).toBe('eraser');
    toolStoreActions.setPrimaryColor('#ff3366');
    expect(useToolStore.getState().tool).toBe('decoration');
    expect(useToolStore.getState().activePresetId).toBe(customRoses.id);
  });

  it('cycles custom Decoration subtools and groups cleanly with stepSubTool / stepSubToolGroup', () => {
    const customBrushes = [
      makeCustomDecoBrush('inkb-deco-bg-1', 'Custom Skyline', 'deco-background'),
      makeCustomDecoBrush('inkb-deco-bg-2', 'Custom Clouds', 'deco-background'),
      makeCustomDecoBrush('inkb-deco-cloth-1', 'Custom Lace', 'deco-clothing'),
      makeCustomDecoBrush('inkb-deco-fx-1', 'Custom Petals', 'deco-effect'),
    ];
    for (const b of customBrushes) {
      subToolGroupStoreActions.moveBrushToGroup(b.id, b.category as DecorationCategory);
    }

    toolStoreActions.selectTool('decoration');
    activateSubToolPreset('inkb-deco-bg-1', customBrushes);

    const next = stepSubTool(1, customBrushes);
    expect(next?.presetId).toBe('inkb-deco-bg-2');
    expect(useToolStore.getState().tool).toBe('decoration');

    const grp1 = stepSubToolGroup(1, customBrushes);
    expect(grp1?.groupId).toBe('deco-background');
    const grp2 = stepSubToolGroup(1, customBrushes);
    expect(grp2?.groupId).toBe('deco-clothing');
    expect(useSubToolGroupStore.getState().activeDecorationTab).toBe('deco-clothing');
    expect(useToolStore.getState().activePresetId).toBe('inkb-deco-cloth-1');

    const grp3 = activateSubToolGroup('deco-effect', customBrushes);
    expect(grp3?.groupName).toBe('Effect');
    expect(useToolStore.getState().tool).toBe('decoration');
    expect(useToolStore.getState().activePresetId).toBe('inkb-deco-fx-1');
  });

  it('registers Decoration tool and custom decoration brushes in ShortcutManager and Quick Brushes', async () => {
    const customCherry = makeCustomDecoBrush('inkb-deco-cherry', 'Custom Cherry', 'deco-effect');
    expect(DEFAULT_COMMANDS.some((c) => c.id === 'tool.decoration' && c.toolId === 'decoration')).toBe(true);

    const dynamic = buildSubToolShortcutCommands([customCherry], []);
    expect(dynamic.some((c) => c.subToolPresetId === customCherry.id)).toBe(true);

    const resolved = resolveQuickBrush(customCherry.id, [customCherry]);
    expect(resolved).not.toBeNull();
    expect(resolved!.name).toBe('Custom Cherry');
    expect(resolved!.category).toBe('deco-effect');

    await activateQuickBrush(resolved!, [customCherry]);
    expect(useToolStore.getState().tool).toBe('decoration');
    expect(useToolStore.getState().activePresetId).toBe(customCherry.id);
  });

  it('renders Decoration button in ToolStrip and Decoration-scoped tabs/empty state/custom brushes in SubToolList', () => {
    const body = (document as unknown as { body: MiniEl }).body;
    container = document.createElement('div') as unknown as MiniEl;
    body.appendChild(container);
    root = createRoot(container as unknown as Element);

    const customLace = makeCustomDecoBrush('inkb-deco-lace', 'Custom Lace', 'deco-clothing');
    const customRoses = makeCustomDecoBrush('inkb-deco-roses', 'Custom Roses', 'deco-effect');

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

    const decoBtn = container.querySelector('[data-testid="toolstrip-decoration-btn"]');
    expect(decoBtn).not.toBeNull();
    // Initially in Brush mode -> Brush tab bar shown, Decoration tab bar hidden
    expect(container.querySelector('[data-testid="subtool-group-tab-bar"]')).not.toBeNull();
    expect(container.querySelector('[data-testid="subtool-decoration-tab-bar"]')).toBeNull();

    // Click Decoration tool in ToolStrip
    act(() => {
      invokeReactClick(decoBtn);
    });

    expect(useToolStore.getState().tool).toBe('decoration');
    expect(container.querySelector('[data-testid="subtool-decoration-tab-bar"]')).not.toBeNull();
    expect(container.querySelector('[data-testid="subtool-group-tab-deco-background"]')).not.toBeNull();
    expect(container.querySelector('[data-testid="subtool-group-tab-deco-clothing"]')).not.toBeNull();
    expect(container.querySelector('[data-testid="subtool-group-tab-deco-effect"]')).not.toBeNull();
    expect(container.querySelector('[data-testid="subtool-decoration-empty-state"]')).not.toBeNull();

    // Render with custom decoration brushes assigned to categories
    act(() => {
      subToolGroupStoreActions.moveBrushToGroup(customLace.id, 'deco-clothing');
      subToolGroupStoreActions.moveBrushToGroup(customRoses.id, 'deco-effect');
      root!.render(
        <div>
          <ToolStrip />
          <SubToolList customBrushes={[customLace, customRoses]} setCustomBrushes={() => {}} />
        </div>
      );
    });

    expect(container.querySelector('[data-testid="subtool-decoration-empty-state"]')).toBeNull();
    expect(container.querySelector(`[data-testid="subtool-row-${customLace.id}"]`)).not.toBeNull();
    expect(container.querySelector(`[data-testid="subtool-row-${customRoses.id}"]`)).not.toBeNull();

    // Filter to Clothing tab -> only the clothing custom brush is visible
    const clothingTab = container.querySelector('[data-testid="subtool-group-tab-deco-clothing"]');
    act(() => {
      invokeReactClick(clothingTab);
    });
    expect(container.querySelector(`[data-testid="subtool-row-${customLace.id}"]`)).not.toBeNull();
    expect(container.querySelector(`[data-testid="subtool-row-${customRoses.id}"]`)).toBeNull();

    // "+ Group" button is available in Decoration mode too
    const createGroupBtn = container.querySelector('[data-testid="subtool-create-group-btn"]');
    expect(createGroupBtn).not.toBeNull();
    act(() => {
      invokeReactClick(createGroupBtn);
    });
    expect(container.querySelector('[data-testid="subtool-create-group-form"]')).not.toBeNull();
    const confirmBtn = container.querySelector('[data-testid="subtool-create-group-confirm"]');
    act(() => {
      invokeReactClick(confirmBtn);
    });

    const createdGroups = useSubToolGroupStore.getState().groups;
    expect(createdGroups).toHaveLength(1);
    expect(createdGroups[0].toolScope).toBe('decoration');
    expect(useSubToolGroupStore.getState().activeDecorationTab).toBe(createdGroups[0].id);
    expect(container.querySelector(`[data-testid="subtool-group-tab-${createdGroups[0].id}"]`)).not.toBeNull();

    // Move a Decoration brush into the new Decoration custom group & verify persistence
    act(() => {
      subToolGroupStoreActions.moveBrushToGroup(customRoses.id, createdGroups[0].id);
    });
    expect(container.querySelector(`[data-testid="subtool-row-${customRoses.id}"]`)).not.toBeNull();

    // Switching back to Brush mode hides Decoration-scoped custom groups
    const brushBtn = container.querySelector('[data-testid="toolstrip-brush-btn"]');
    act(() => {
      invokeReactClick(brushBtn);
    });
    expect(container.querySelector(`[data-testid="subtool-group-tab-${createdGroups[0].id}"]`)).toBeNull();

    // Reloading from storage preserves toolScope & activeDecorationTab
    subToolGroupStoreActions.reloadFromStorage();
    expect(useSubToolGroupStore.getState().groups[0].toolScope).toBe('decoration');
    expect(useSubToolGroupStore.getState().activeDecorationTab).toBe(createdGroups[0].id);
  });

  it('routes canvas pointerDown/Move/Up to the brush stroke engine when Decoration tool is active', () => {
    const appSource = fs.readFileSync(
      // @ts-expect-error process is available in vitest runtime without @types/node
      path.resolve(process.cwd(), 'src/App.tsx'),
      'utf-8'
    );
    // Regression guard: App.tsx must dispatch pointerDown, pointerMove, and pointerUp
    // to drawing.handlePointer* for 'decoration' just like 'brush' and 'eraser'.
    const matches = appSource.match(/tool === 'brush' \|\| tool === 'decoration' \|\| tool === 'eraser'/g);
    expect(matches?.length).toBeGreaterThanOrEqual(3);
  });
});