Skip to content

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

22.1 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { COMMAND_CATALOG } from '../../types/workspace';
import { CspBrush } from '../../types/editor';
import {
  DEFAULT_QUICK_BRUSH_IDS,
  LEGACY_DEFAULT_QUICK_BRUSH_IDS,
  WORKSPACE_STORAGE_KEY,
  createDefaultPersistedWorkspace,
  loadWorkspaceState,
  sanitizeQuickBrushPanelState,
} from '../workspacePresets';
import { DEFAULT_COMMANDS, findShortcutConflicts } from '../shortcutManager';
import { ERASER_PRESET_ID } from '../brushPresetManager';
import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';
import { useToolStore } from '../../stores/useToolStore';
import { useUiStore } from '../../stores/useUiStore';
import {
  executeWorkspaceCommand,
  isCommandActive,
  isCommandDisabled,
  WorkspaceCommandHandlers,
} from '../../components/CommandBar';
import { QuickBrushPanel } from '../../components/QuickBrushPanel';
import { SubToolList } from '../../components/SubToolList';

function createMemoryStorage(): Storage {
  const store = new Map<string, string>();
  return {
    get length() {
      return store.size;
    },
    clear() {
      store.clear();
    },
    getItem(key: string) {
      return store.has(key) ? store.get(key)! : null;
    },
    key(index: number) {
      return Array.from(store.keys())[index] ?? null;
    },
    removeItem(key: string) {
      store.delete(key);
    },
    setItem(key: string, value: string) {
      store.set(key, String(value));
    },
  };
}

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 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: Record<string, string> = {};
  className = '';
  disabled = false;
  checked = false;
  value = '';
  attrs = new Map<string, string>();

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

  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)] : [];
  }

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

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

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

  setAttribute(k: string, v: string) {
    this.attrs.set(k, String(v));
  }

  getAttribute(k: string): string | null {
    return this.attrs.get(k) ?? null;
  }

  removeAttribute(k: string) {
    this.attrs.delete(k);
  }

  getContext() {
    return null;
  }

  getBoundingClientRect() {
    return {
      left: 820,
      right: 900,
      top: 120,
      bottom: 520,
      width: 80,
      height: 400,
      x: 820,
      y: 120,
      toJSON: () => ({}),
    };
  }

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

  findByAttr(attr: string, value: string): MiniEl | null {
    if (this.getAttribute(attr) === value) return this;
    for (const c of this.childNodes) {
      if (c instanceof MiniEl) {
        const found = c.findByAttr(attr, value);
        if (found) return found;
      }
    }
    return null;
  }
}

interface MiniDoc {
  nodeType: number;
  nodeName: string;
  documentElement: MiniEl;
  body: MiniEl;
  activeElement: MiniEl;
  defaultView: Record<string, unknown>;
  createElement: (tag: string) => MiniEl;
  createElementNS: (_ns: string, tag: string) => MiniEl;
  createTextNode: (text: string) => MiniText;
  createComment: (text: string) => MiniComment;
  addEventListener: EventTarget['addEventListener'];
  removeEventListener: EventTarget['removeEventListener'];
  dispatchEvent: EventTarget['dispatchEvent'];
}

function installMiniDom() {
  const g = globalThis as unknown as Record<string, unknown>;
  const saved: Record<string, unknown> = {
    window: g.window,
    document: g.document,
    HTMLElement: g.HTMLElement,
    Node: g.Node,
    Element: g.Element,
    requestAnimationFrame: g.requestAnimationFrame,
    cancelAnimationFrame: g.cancelAnimationFrame,
    IS_REACT_ACT_ENVIRONMENT: g.IS_REACT_ACT_ENVIRONMENT,
  };
  g.IS_REACT_ACT_ENVIRONMENT = true;

  const winTarget = new EventTarget();
  const docTarget = new EventTarget();

  const mockDoc = {
    nodeType: 9,
    nodeName: '#document',
    documentElement: null as unknown as MiniEl,
    body: null as unknown as MiniEl,
    activeElement: null as unknown as MiniEl,
    defaultView: null as unknown as Record<string, unknown>,
    createElement: (tag: string) => new MiniEl(tag, mockDoc),
    createElementNS: (_ns: string, tag: string) => new MiniEl(tag, mockDoc),
    createTextNode: (text: string) => new MiniText(text, mockDoc),
    createComment: (text: string) => new MiniComment(text, mockDoc),
    addEventListener: docTarget.addEventListener.bind(docTarget),
    removeEventListener: docTarget.removeEventListener.bind(docTarget),
    dispatchEvent: docTarget.dispatchEvent.bind(docTarget),
  } as MiniDoc;

  mockDoc.documentElement = new MiniEl('html', mockDoc);
  mockDoc.body = new MiniEl('body', mockDoc);
  mockDoc.documentElement.appendChild(mockDoc.body);
  mockDoc.activeElement = mockDoc.body;

  class MockIFrame extends MiniEl {}
  const rafMock = () => 1;
  const cancelRafMock = () => {};

  const mockWin: Record<string, unknown> = {
    innerWidth: 1440,
    innerHeight: 900,
    document: mockDoc,
    Node: MiniEl,
    Element: MiniEl,
    HTMLElement: MiniEl,
    SVGElement: MiniEl,
    HTMLIFrameElement: MockIFrame,
    Event,
    CustomEvent,
    addEventListener: winTarget.addEventListener.bind(winTarget),
    removeEventListener: winTarget.removeEventListener.bind(winTarget),
    dispatchEvent: winTarget.dispatchEvent.bind(winTarget),
    requestAnimationFrame: rafMock,
    cancelAnimationFrame: cancelRafMock,
  };
  mockDoc.defaultView = mockWin;

  g.window = mockWin;
  g.document = mockDoc;
  g.HTMLElement = MiniEl;
  g.Node = MiniEl;
  g.Element = MiniEl;
  g.requestAnimationFrame = rafMock;
  g.cancelAnimationFrame = cancelRafMock;

  const container = new MiniEl('div', mockDoc);
  mockDoc.body.appendChild(container);

  return {
    container,
    cleanup: () => {
      for (const [k, v] of Object.entries(saved)) {
        if (v === undefined) delete g[k];
        else g[k] = v;
      }
    },
  };
}

function invokeReactProp(el: MiniEl | null, propName: string, eventArg?: unknown): void {
  expect(el).not.toBeNull();
  const key = Object.keys(el!).find((k) => k.startsWith('__reactProps'));
  expect(key).toBeDefined();
  const props = (el as unknown as Record<string, Record<string, (arg?: unknown) => void>>)[key!];
  expect(typeof props[propName]).toBe('function');
  props[propName](
    eventArg ?? {
      stopPropagation: () => {},
      preventDefault: () => {},
    }
  );
}

describe('Quick-Access Brush Panel State, Persistence, Shortcuts & UI', () => {
  const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;

  beforeEach(() => {
    Object.defineProperty(globalThis, 'localStorage', {
      value: createMemoryStorage(),
      configurable: true,
      writable: true,
    });
    useWorkspaceStore.reset();
    useToolStore.reset();
    useUiStore.reset();
  });

  afterEach(() => {
    if (prevStorage === undefined) {
      delete (globalThis as unknown as Record<string, unknown>).localStorage;
    } else {
      Object.defineProperty(globalThis, 'localStorage', {
        value: prevStorage,
        configurable: true,
        writable: true,
      });
    }
  });

  it('persists quick brush panel settings, custom order, and sanitizes corrupt/legacy values', () => {
    const initial = useWorkspaceStore.getState().quickBrushPanel;
    expect(initial.visible).toBe(true);
    expect(initial.orientation).toBe('vertical');
    expect(initial.keepVisibleWhenPalettesHidden).toBe(true);
    expect(DEFAULT_QUICK_BRUSH_IDS).toEqual([]);
    expect(initial.brushIds).toEqual([]);

    // Add, deduplicate, move, reorder, and customize settings
    expect(workspaceStoreActions.addQuickBrush('g-pen')).toBe(true);
    expect(workspaceStoreActions.addQuickBrush('calligraphy')).toBe(true);
    expect(workspaceStoreActions.addQuickBrush('calligraphy')).toBe(false);
    workspaceStoreActions.reorderQuickBrush('calligraphy', 'g-pen');
    expect(useWorkspaceStore.getState().quickBrushPanel.brushIds[0]).toBe('calligraphy');

    workspaceStoreActions.moveQuickBrush('calligraphy', 1);
    expect(useWorkspaceStore.getState().quickBrushPanel.brushIds[1]).toBe('calligraphy');

    workspaceStoreActions.updateQuickBrushPanelSettings({
      orientation: 'horizontal',
      tileSize: 'large',
      columns: 2,
      previewStyle: 'stroke',
      showNames: false,
      showCategoryColors: false,
      opacity: 0.75,
      title: 'Inking Set',
      locked: true,
      showHideUiButton: true,
    });
    workspaceStoreActions.setQuickBrushPanelPosition({ x: 140, y: 88 }, true);

    // Simulate reload from localStorage
    useWorkspaceStore.reset();
    const reloaded = useWorkspaceStore.getState().quickBrushPanel;
    expect(reloaded.orientation).toBe('horizontal');
    expect(reloaded.tileSize).toBe('large');
    expect(reloaded.columns).toBe(2);
    expect(reloaded.previewStyle).toBe('stroke');
    expect(reloaded.showNames).toBe(false);
    expect(reloaded.showCategoryColors).toBe(false);
    expect(reloaded.opacity).toBe(0.75);
    expect(reloaded.title).toBe('Inking Set');
    expect(reloaded.locked).toBe(true);
    expect(reloaded.showHideUiButton).toBe(true);
    expect(reloaded.position).toEqual({ x: 140, y: 88 });
    expect(reloaded.brushIds[1]).toBe('calligraphy');

    // Sanitizer handles legacy preset IDs, duplicates, and out-of-range opacity
    const sanitized = sanitizeQuickBrushPanelState({
      orientation: 'invalid',
      tileSize: 'huge',
      columns: 99,
      opacity: 0.05,
      brushIds: ['oil-painting', 'oil-flat-alla-prima', '  ', 123],
      position: { x: NaN, y: 10 },
    });
    expect(sanitized.orientation).toBe('vertical');
    expect(sanitized.tileSize).toBe('medium');
    expect(sanitized.columns).toBe(1);
    expect(sanitized.opacity).toBe(0.4);
    expect(sanitized.position).toBeNull();
    expect(sanitized.brushIds).toEqual(['oil-flat-alla-prima']);

    // Corrupt localStorage still recovers safely to empty quick brushes
    localStorage.setItem(WORKSPACE_STORAGE_KEY, '{broken');
    const recovered = loadWorkspaceState();
    expect(recovered.quickBrushPanel?.brushIds).toEqual([]);
  });

  it('starts empty for new users and clears untouched legacy pre-added brushes on update without wiping custom lists', () => {
    // 1. Fresh install (no saved workspace) starts empty
    const fresh = loadWorkspaceState();
    expect(fresh.quickBrushPanel?.brushIds).toEqual([]);
    expect(fresh.migratedQuickBrushDefaults).toBe(true);

    // 2. Updating from a prior version with untouched legacy pre-added brushes clears them once
    const legacySaved = createDefaultPersistedWorkspace();
    delete legacySaved.migratedQuickBrushDefaults;
    legacySaved.quickBrushPanel = {
      ...legacySaved.quickBrushPanel!,
      brushIds: [...LEGACY_DEFAULT_QUICK_BRUSH_IDS],
    };
    localStorage.setItem(WORKSPACE_STORAGE_KEY, JSON.stringify(legacySaved));

    const migrated = loadWorkspaceState();
    expect(migrated.quickBrushPanel?.brushIds).toEqual([]);
    expect(migrated.migratedQuickBrushDefaults).toBe(true);

    // 3. Once migrated, manually pinning the exact legacy brushes again is preserved across reloads
    const rePinned = {
      ...migrated,
      quickBrushPanel: {
        ...migrated.quickBrushPanel!,
        brushIds: [...LEGACY_DEFAULT_QUICK_BRUSH_IDS],
      },
    };
    localStorage.setItem(WORKSPACE_STORAGE_KEY, JSON.stringify(rePinned));
    expect(loadWorkspaceState().quickBrushPanel?.brushIds).toEqual(LEGACY_DEFAULT_QUICK_BRUSH_IDS);

    // 4. Updating from a prior version where the user customized Quick Brushes preserves their list
    const customizedLegacy = createDefaultPersistedWorkspace();
    delete customizedLegacy.migratedQuickBrushDefaults;
    customizedLegacy.quickBrushPanel = {
      ...customizedLegacy.quickBrushPanel!,
      brushIds: ['g-pen', 'inkb-custom-liner'],
    };
    localStorage.setItem(WORKSPACE_STORAGE_KEY, JSON.stringify(customizedLegacy));

    const preserved = loadWorkspaceState();
    expect(preserved.quickBrushPanel?.brushIds).toEqual(['g-pen', 'inkb-custom-liner']);
    expect(preserved.migratedQuickBrushDefaults).toBe(true);
  });

  it('registers Shift+B shortcut without conflicts and exposes Command Bar toggle action', () => {
    const cmd = DEFAULT_COMMANDS.find((c) => c.id === 'view.toggleQuickBrushPanel');
    expect(cmd).toBeDefined();
    expect(cmd?.defaultShortcut).toBe('Shift+B');
    expect(findShortcutConflicts('view.toggleQuickBrushPanel', 'Shift+B', {})).toHaveLength(0);

    const catalogEntry = COMMAND_CATALOG.find((c) => c.id === 'toggle-quick-brushes');
    expect(catalogEntry).toBeDefined();

    const handlers: WorkspaceCommandHandlers = {
      onUndo: () => {},
      onRedo: () => {},
      canUndo: false,
      canRedo: false,
      hasOpenDocument: false,
    };
    expect(isCommandDisabled('toggle-quick-brushes', handlers)).toBe(false);
    expect(isCommandActive('toggle-quick-brushes', handlers, false)).toBe(true);

    executeWorkspaceCommand('toggle-quick-brushes', handlers);
    expect(useWorkspaceStore.getState().quickBrushPanel.visible).toBe(false);
    expect(isCommandActive('toggle-quick-brushes', handlers, false)).toBe(false);
  });

  describe('UI Rendering, Panel Settings, Hide-UI Behavior & SubToolList Pinning', () => {
    let dom: ReturnType<typeof installMiniDom>;
    let root: Root | null = null;

    const sampleCustomBrush: CspBrush = {
      id: 'inkb-custom-liner',
      name: 'Manga Hero Ink',
      size: 10,
      minSizeFactor: 0.1,
      flow: 1,
      opacity: 1,
      spacing: 0.05,
      hardness: 1,
      thickness: 1,
      antiAlias: 2,
      stabilization: 8,
      angle: 0,
      smoothing: true,
      usePressure: true,
      importedAt: 1700000000000,
    };

    beforeEach(() => {
      dom = installMiniDom();
    });

    afterEach(() => {
      if (root) {
        act(() => {
          root?.unmount();
        });
        root = null;
      }
      dom.cleanup();
    });

    it('renders QuickBrushPanel, switches brushes, stays visible when UI is hidden (Tab), and updates live via Settings popover', () => {
      const renderPanel = () => {
        act(() => {
          if (!root) root = createRoot(dom.container as unknown as Element);
          root.render(<QuickBrushPanel customBrushes={[sampleCustomBrush]} />);
        });
      };

      renderPanel();

      // Panel renders vertically by default and starts empty with an Add button
      let panel = dom.container.findByAttr('data-testid', 'quick-brush-panel');
      expect(panel).not.toBeNull();
      expect(panel?.getAttribute('data-orientation')).toBe('vertical');
      expect(panel?.getAttribute('data-locked')).toBe('false');
      expect(dom.container.findByAttr('data-testid', 'quick-brush-empty-add-btn')).not.toBeNull();

      // Add brushes and verify clicking a brush tile selects that brush in useToolStore
      act(() => {
        workspaceStoreActions.addQuickBrush('g-pen');
        workspaceStoreActions.addQuickBrush('real-g-pen');
      });
      const realGPenTile = dom.container.findByAttr(
        'data-testid',
        'quick-brush-tile-real-g-pen'
      );
      act(() => {
        invokeReactProp(realGPenTile, 'onClick');
      });
      expect(useToolStore.getState().tool).toBe('brush');
      expect(useToolStore.getState().activePresetId).toBe('real-g-pen');

      // Pinning and clicking Eraser activates eraser tool
      act(() => {
        workspaceStoreActions.addQuickBrush(ERASER_PRESET_ID);
      });
      const eraserTile = dom.container.findByAttr(
        'data-testid',
        `quick-brush-tile-${ERASER_PRESET_ID}`
      );
      act(() => {
        invokeReactProp(eraserTile, 'onClick');
      });
      expect(useToolStore.getState().tool).toBe('eraser');

      // Hiding all palettes (Tab) keeps QuickBrushPanel visible by default
      act(() => {
        workspaceStoreActions.setPalettesHidden(true);
      });
      expect(dom.container.findByAttr('data-testid', 'quick-brush-panel')).not.toBeNull();

      // Open Settings popover and switch to Horizontal + enable Hide UI button on bar
      const settingsBtn = dom.container.findByAttr('data-testid', 'quick-brush-settings-btn');
      act(() => {
        invokeReactProp(settingsBtn, 'onClick');
      });
      const body = document.body as unknown as MiniEl;
      const popover = body.findByAttr('data-testid', 'quick-brush-settings-popover');
      expect(popover).not.toBeNull();

      const horizBtn = body.findByAttr('data-testid', 'quick-brush-orient-horizontal');
      act(() => {
        invokeReactProp(horizBtn, 'onClick');
      });
      panel = dom.container.findByAttr('data-testid', 'quick-brush-panel');
      expect(panel?.getAttribute('data-orientation')).toBe('horizontal');
      expect(dom.container.findByAttr('data-testid', 'quick-brush-title-label')?.textContent).toBe(
        'Favorites'
      );

      // Toggle Hide/Show UI button onto the bar
      const hideUiCheckbox = body.findByAttr('data-testid', 'quick-brush-toggle-hide-ui-btn');
      act(() => {
        invokeReactProp(hideUiCheckbox, 'onChange', { target: { checked: true } });
      });
      expect(dom.container.findByAttr('data-testid', 'quick-brush-hide-ui-btn')).not.toBeNull();

      // Lock button locks panel and hides tile remove buttons
      const lockBtn = dom.container.findByAttr('data-testid', 'quick-brush-lock-btn');
      act(() => {
        invokeReactProp(lockBtn, 'onClick');
      });
      expect(useWorkspaceStore.getState().quickBrushPanel.locked).toBe(true);
      expect(dom.container.findByAttr('data-testid', 'quick-brush-remove-g-pen')).toBeNull();

      // Turning off keepVisibleWhenPalettesHidden hides panel while palettesHidden is true
      act(() => {
        workspaceStoreActions.updateQuickBrushPanelSettings({
          keepVisibleWhenPalettesHidden: false,
        });
      });
      expect(dom.container.findByAttr('data-testid', 'quick-brush-panel')).toBeNull();

      // Restoring palettes brings QuickBrushPanel back
      act(() => {
        workspaceStoreActions.setPalettesHidden(false);
      });
      expect(dom.container.findByAttr('data-testid', 'quick-brush-panel')).not.toBeNull();

      // Clicking close button hides QuickBrushPanel
      const closeBtn = dom.container.findByAttr('data-testid', 'quick-brush-close-btn');
      act(() => {
        invokeReactProp(closeBtn, 'onClick');
      });
      expect(useWorkspaceStore.getState().quickBrushPanel.visible).toBe(false);
      expect(dom.container.findByAttr('data-testid', 'quick-brush-panel')).toBeNull();
    });

    it('adds and removes builtin and custom brushes from SubToolList directly into QuickBrushPanel', () => {
      workspaceStoreActions.setQuickBrushPanelVisible(false);

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(
          <SubToolList customBrushes={[sampleCustomBrush]} setCustomBrushes={() => {}} />
        );
      });

      // Pin a builtin brush ('calligraphy') from SubToolList — adds it AND opens the hidden Quick Brush Panel
      const pinCalligraphyBtn = dom.container.findByAttr(
        'data-testid',
        'subtool-quick-pin-calligraphy'
      );
      act(() => {
        invokeReactProp(pinCalligraphyBtn, 'onClick');
      });
      expect(useWorkspaceStore.getState().quickBrushPanel.brushIds).toContain('calligraphy');
      expect(useWorkspaceStore.getState().quickBrushPanel.visible).toBe(true);

      // Pin an imported custom brush from SubToolList
      const pinCustomBtn = dom.container.findByAttr(
        'data-testid',
        `subtool-quick-pin-${sampleCustomBrush.id}`
      );
      act(() => {
        invokeReactProp(pinCustomBtn, 'onClick');
      });
      expect(useWorkspaceStore.getState().quickBrushPanel.brushIds).toContain(sampleCustomBrush.id);

      // Clicking again removes the custom brush from Quick Brush Panel
      act(() => {
        invokeReactProp(
          dom.container.findByAttr('data-testid', `subtool-quick-pin-${sampleCustomBrush.id}`),
          'onClick'
        );
      });
      expect(useWorkspaceStore.getState().quickBrushPanel.brushIds).not.toContain(
        sampleCustomBrush.id
      );

      // Header Star button toggles Quick Brush Panel visibility
      const headerToggleBtn = dom.container.findByAttr(
        'data-testid',
        'subtool-toggle-quick-brush-panel'
      );
      act(() => {
        invokeReactProp(headerToggleBtn, 'onClick');
      });
      expect(useWorkspaceStore.getState().quickBrushPanel.visible).toBe(false);
    });
  });
});