Skip to content

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

40.3 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CspBrush } from '../../types/editor';
import { DEFAULT_APP_SETTINGS } from '../../types/settings';
import {
  DEFAULT_COMMANDS,
  SPRING_LOADED_HOLD_MS,
  ShortcutManager,
  SpringLoadedSubToolController,
  buildSubToolShortcutCommands,
  findShortcutConflicts,
  formatShortcutFromEvent,
  formatShortcutLabel,
  getSubToolCommandId,
  getSubToolGroupCommandId,
  matchesKeyboardEvent,
  normalizeShortcut,
  parseShortcut,
} from '../shortcutManager';
import {
  getOrderedSubToolIdsForTab,
  loadSubToolGroupsState,
  sanitizeSubToolGroupsState,
} from '../subToolGroups';
import {
  activateSubToolGroup,
  activateSubToolPreset,
  stepMainTool,
  stepSubTool,
  stepSubToolGroup,
} from '../subToolNavigation';
import {
  dispatchNativeOsHotkeyForTest,
  extractNativeOsHotkeyBindings,
} from '../nativeOsHotkeys';
import { resetBrushStorageCache, saveCustomBrush } from '../brushStorage';
import {
  subToolGroupStoreActions,
  toolStoreActions,
  uiStoreActions,
  useSubToolGroupStore,
  useToolStore,
  useUiStore,
} from '../../stores';
import { SubToolList } from '../../components/SubToolList';
import { GlobalShortcutListener } from '../../components/GlobalShortcutListener';
import { SettingsModal } from '../../components/SettingsModal';

// ---------------------------------------------------------------------------
// Minimal DOM shim (matches quickBrushPanel.test.tsx pattern for React 19)
// ---------------------------------------------------------------------------

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;
  }
  override set textContent(v: string) {
    this.data = String(v);
  }
}

class MiniEl extends MiniNode {
  tagName: string;
  namespaceURI = 'http://www.w3.org/1999/xhtml';
  attributes: Record<string, string> = {};
  style: Record<string, string> = {};
  listeners: Record<string, Array<(ev: unknown) => void>> = {};
  value = '';
  checked = false;
  disabled = false;
  type = '';
  ownerDocument: unknown = null;

  constructor(tag: string) {
    super(1);
    this.tagName = tag.toUpperCase();
  }
  get nodeName() {
    return this.tagName;
  }
  get className() {
    return this.attributes.class || '';
  }
  set className(v: string) {
    this.attributes.class = v;
  }
  appendChild<T extends MiniNode>(child: T): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    this.childNodes.push(child);
    return child;
  }
  insertBefore<T extends MiniNode>(child: T, ref: MiniNode | null): T {
    if (child.parentNode) child.parentNode.removeChild(child);
    child.parentNode = this;
    const idx = ref ? this.childNodes.indexOf(ref) : -1;
    if (idx < 0) this.childNodes.push(child);
    else this.childNodes.splice(idx, 0, child);
    return child;
  }
  removeChild<T extends MiniNode>(child: T): T {
    const idx = this.childNodes.indexOf(child);
    if (idx >= 0) this.childNodes.splice(idx, 1);
    child.parentNode = null;
    return child;
  }
  contains(node: MiniNode | null): boolean {
    if (!node) return false;
    if (node === this) return true;
    return this.childNodes.some((c) => c === node || (c instanceof MiniEl && c.contains(node)));
  }
  setAttribute(k: string, v: string) {
    this.attributes[k] = String(v);
  }
  getAttribute(k: string) {
    return this.attributes[k] ?? null;
  }
  removeAttribute(k: string) {
    delete this.attributes[k];
  }
  addEventListener(type: string, fn: (ev: unknown) => void) {
    if (!this.listeners[type]) this.listeners[type] = [];
    this.listeners[type].push(fn);
  }
  removeEventListener(type: string, fn: (ev: unknown) => void) {
    if (!this.listeners[type]) return;
    this.listeners[type] = this.listeners[type].filter((f) => f !== fn);
  }
  focus() {}
  blur() {}
  getBoundingClientRect() {
    return { left: 100, top: 100, right: 260, bottom: 320, width: 160, height: 220 };
  }
  findByAttr(attr: string, value: string): MiniEl | null {
    if (this.attributes[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;
  }
  collectByAttr(attr: string, value?: string, out: MiniEl[] = []): MiniEl[] {
    if (
      Object.prototype.hasOwnProperty.call(this.attributes, attr) &&
      (value === undefined || this.attributes[attr] === value)
    ) {
      out.push(this);
    }
    for (const c of this.childNodes) {
      if (c instanceof MiniEl) c.collectByAttr(attr, value, out);
    }
    return out;
  }
  querySelectorAll(selector: string): MiniEl[] {
    const eqMatch = /^\[([^=\]]+)="([^"]+)"\]$/.exec(selector.trim());
    if (eqMatch) {
      return this.collectByAttr(eqMatch[1], eqMatch[2]);
    }
    const bareMatch = /^\[([^=\]]+)\]$/.exec(selector.trim());
    if (bareMatch) {
      return this.collectByAttr(bareMatch[1]);
    }
    return [];
  }
  querySelector(selector: string): MiniEl | null {
    return this.querySelectorAll(selector)[0] ?? null;
  }
  closest(selector: string): MiniEl | null {
    const tags = selector
      .split(',')
      .map((s) => s.trim().toUpperCase())
      .filter(Boolean);
    let cur: MiniEl | null = this;
    while (cur) {
      if (tags.includes(cur.tagName)) return cur;
      cur = cur.parentNode;
    }
    return null;
  }
}

function getReactProps(el: MiniEl | null): Record<string, unknown> | null {
  if (!el) return null;
  const key = Object.keys(el).find((k) => k.startsWith('__reactProps$'));
  return key ? ((el as unknown as Record<string, unknown>)[key] as Record<string, unknown>) : null;
}

function invokeReactProp(el: MiniEl | null, propName: string, eventObj: Record<string, unknown> = {}) {
  const props = getReactProps(el);
  const fn = props?.[propName];
  if (typeof fn !== 'function') {
    throw new Error(`Expected prop "${propName}" on <${el?.tagName ?? 'null'}> to be a function`);
  }
  const ev = {
    preventDefault: () => {},
    stopPropagation: () => {},
    clientX: 140,
    clientY: 160,
    currentTarget: el,
    target: el,
    ...eventObj,
  };
  return (fn as (e: unknown) => unknown)(ev);
}

function installMiniDom() {
  const winListeners = new Map<string, Array<(ev: unknown) => void>>();
  const docEl = new MiniEl('html');
  const head = new MiniEl('head');
  const body = new MiniEl('body');
  const container = new MiniEl('div');
  body.appendChild(container);
  docEl.appendChild(head);
  docEl.appendChild(body);

  const fakeDoc = {
    nodeType: 9,
    nodeName: '#document',
    documentElement: docEl,
    head,
    body,
    activeElement: body,
    defaultView: null as unknown as Record<string, unknown>,
    createElement: (tag: string) => {
      const el = new MiniEl(tag);
      el.ownerDocument = fakeDoc;
      return el;
    },
    createElementNS: (_ns: string, tag: string) => {
      const el = new MiniEl(tag);
      el.ownerDocument = fakeDoc;
      return el;
    },
    createTextNode: (t: string) => {
      const tn = new MiniText(t);
      (tn as unknown as { ownerDocument: unknown }).ownerDocument = fakeDoc;
      return tn;
    },
    createComment: (t: string) => new MiniText(t),
    querySelector: (sel: string) => body.querySelector(sel),
    querySelectorAll: (sel: string) => body.querySelectorAll(sel),
    addEventListener: () => {},
    removeEventListener: () => {},
  };

  docEl.ownerDocument = fakeDoc;
  body.ownerDocument = fakeDoc;
  container.ownerDocument = fakeDoc;

  class MiniIFrame extends MiniEl {}
  const fakeWin = {
    document: fakeDoc,
    innerWidth: 1280,
    innerHeight: 800,
    addEventListener: (type: string, fn: (ev: unknown) => void) => {
      const list = winListeners.get(type) ?? [];
      list.push(fn);
      winListeners.set(type, list);
    },
    removeEventListener: (type: string, fn: (ev: unknown) => void) => {
      const list = winListeners.get(type) ?? [];
      winListeners.set(
        type,
        list.filter((f) => f !== fn)
      );
    },
    dispatchEvent: (ev: { type: string }) => {
      const list = [...(winListeners.get(ev.type) ?? [])];
      for (const fn of list) fn(ev);
      return true;
    },
    getSelection: () => null,
    requestAnimationFrame: (cb: FrameRequestCallback) => {
      cb(0);
      return 1;
    },
    cancelAnimationFrame: () => {},
    HTMLElement: MiniEl,
    HTMLIFrameElement: MiniIFrame,
    Element: MiniEl,
    Node: MiniNode,
  };
  fakeDoc.defaultView = fakeWin;

  const g = globalThis as Record<string, unknown>;
  const prevDoc = g.document;
  const prevWin = g.window;
  const prevHtml = g.HTMLElement;
  const prevEl = g.Element;
  const prevNode = g.Node;
  const prevIframe = g.HTMLIFrameElement;
  const prevAct = g.IS_REACT_ACT_ENVIRONMENT;

  g.document = fakeDoc;
  g.window = fakeWin;
  g.HTMLElement = MiniEl;
  g.Element = MiniEl;
  g.Node = MiniNode;
  g.HTMLIFrameElement = MiniIFrame;
  g.IS_REACT_ACT_ENVIRONMENT = true;

  return {
    container,
    body,
    window: fakeWin,
    dispatchKeyDown: (ev: Partial<KeyboardEvent>) => {
      const full = {
        type: 'keydown',
        key: '',
        code: '',
        ctrlKey: false,
        metaKey: false,
        shiftKey: false,
        altKey: false,
        repeat: false,
        target: body,
        preventDefault: vi.fn(),
        stopPropagation: vi.fn(),
        ...ev,
      };
      fakeWin.dispatchEvent(full);
      return full;
    },
    dispatchKeyUp: (ev: Partial<KeyboardEvent>) => {
      const full = {
        type: 'keyup',
        key: '',
        code: '',
        ctrlKey: false,
        metaKey: false,
        shiftKey: false,
        altKey: false,
        repeat: false,
        target: body,
        preventDefault: vi.fn(),
        stopPropagation: vi.fn(),
        ...ev,
      };
      fakeWin.dispatchEvent(full);
      return full;
    },
    cleanup: () => {
      g.document = prevDoc;
      g.window = prevWin;
      g.HTMLElement = prevHtml;
      g.Element = prevEl;
      g.Node = prevNode;
      g.HTMLIFrameElement = prevIframe;
      g.IS_REACT_ACT_ENVIRONMENT = prevAct;
    },
  };
}

function createSampleCustomBrush(id: string, name: string): CspBrush {
  return {
    id,
    name,
    size: 14,
    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,
  };
}

function installLocalStorage() {
  const storage: Record<string, string> = {};
  (globalThis as unknown as { localStorage: Storage }).localStorage = {
    get length() {
      return Object.keys(storage).length;
    },
    key: (i: number) => Object.keys(storage)[i] ?? null,
    getItem: (k: string) => storage[k] ?? null,
    setItem: (k: string, v: string) => {
      storage[k] = String(v);
    },
    removeItem: (k: string) => {
      delete storage[k];
    },
    clear: () => {
      for (const k of Object.keys(storage)) delete storage[k];
    },
  };
  return storage;
}

describe('OS / Windows Key General Hotkey Support', () => {
  it('parses, normalizes, formats, and captures OS/Win/Meta key combinations independently from Ctrl', () => {
    expect(normalizeShortcut('Win + Q')).toBe('OS+Q');
    expect(normalizeShortcut('windows + shift + 1')).toBe('OS+Shift+1');
    expect(normalizeShortcut('Meta + Alt + Z')).toBe('OS+Alt+Z');
    expect(normalizeShortcut('super + [')).toBe('OS+[');
    expect(normalizeShortcut('Ctrl + Win + S')).toBe('Ctrl+OS+S');
    expect(normalizeShortcut('OS')).toBe('');
    expect(normalizeShortcut('Win')).toBe('');

    const parsed = parseShortcut('Ctrl+Win+Shift+2');
    expect(parsed).toMatchObject({
      ctrl: true,
      meta: true,
      shift: true,
      alt: false,
      key: '2',
      code: 'Digit2',
    });

    // Platform-specific display labels
    expect(formatShortcutLabel('OS+Q', 'windows')).toBe('Win + Q');
    expect(formatShortcutLabel('OS+Q', 'mac')).toBe('Cmd + Q');
    expect(formatShortcutLabel('OS+Q', 'linux')).toBe('OS + Q');
    expect(formatShortcutLabel('Ctrl+OS+Shift+E', 'windows')).toBe('Ctrl + Win + Shift + E');

    // Live KeyboardEvent recording distinguishes metaKey from ctrlKey and ignores bare Meta/OS
    expect(formatShortcutFromEvent({ key: 'Meta', code: 'MetaLeft', metaKey: true })).toBeNull();
    expect(formatShortcutFromEvent({ key: 'OS', code: 'OSLeft', metaKey: true })).toBeNull();
    expect(formatShortcutFromEvent({ key: 'q', code: 'KeyQ', metaKey: true })).toBe('OS+Q');
    expect(
      formatShortcutFromEvent({ key: 'q', code: 'KeyQ', ctrlKey: true, metaKey: true })
    ).toBe('Ctrl+OS+Q');
  });

  it('strictly separates Ctrl vs OS/Win matching on Windows/Linux while supporting macOS Cmd fallback', () => {
    expect(matchesKeyboardEvent({ key: 'z', code: 'KeyZ', metaKey: true }, 'OS+Z')).toBe(true);
    expect(matchesKeyboardEvent({ key: 'z', code: 'KeyZ', metaKey: true }, 'Ctrl+Z')).toBe(false);
    expect(matchesKeyboardEvent({ key: 'z', code: 'KeyZ', ctrlKey: true }, 'OS+Z')).toBe(false);
    expect(
      matchesKeyboardEvent({ key: 'z', code: 'KeyZ', ctrlKey: true, metaKey: true }, 'Ctrl+OS+Z')
    ).toBe(true);
    expect(
      matchesKeyboardEvent({ key: 'z', code: 'KeyZ', ctrlKey: true, metaKey: true }, 'OS+Z')
    ).toBe(false);

    const mgr = new ShortcutManager(DEFAULT_COMMANDS);
    mgr.setOverrides({ 'edit.redo': 'OS+Z' });

    // On Windows: Ctrl+Z -> Undo, Win+Z -> Redo
    expect(
      mgr.matchEvent({ key: 'z', code: 'KeyZ', ctrlKey: true, metaKey: false }, undefined, 'windows')?.id
    ).toBe('edit.undo');
    expect(
      mgr.matchEvent({ key: 'z', code: 'KeyZ', ctrlKey: false, metaKey: true }, undefined, 'windows')?.id
    ).toBe('edit.redo');

    // On macOS: explicit OS+Z wins over fallback, while unbound OS+S still falls back to Ctrl+S Save
    expect(
      mgr.matchEvent({ key: 'z', code: 'KeyZ', ctrlKey: false, metaKey: true }, undefined, 'mac')?.id
    ).toBe('edit.redo');
    expect(
      mgr.matchEvent({ key: 's', code: 'KeyS', ctrlKey: false, metaKey: true }, undefined, 'mac')?.id
    ).toBe('file.save');
  });

  it('extracts native OS-key bindings (including numpad alt codes) across all categories', () => {
    const bindings = extractNativeOsHotkeyBindings(DEFAULT_COMMANDS, {
      'edit.undo': 'Win+Z',
      'view.zoomActualSize': 'OS+1',
      'tool.brush': 'Ctrl+Win+B',
      'tool.eraser': 'E', // non-OS, must not be extracted
    });

    expect(bindings).toContainEqual({ code: 'KeyZ', ctrl: false, shift: false, alt: false });
    expect(bindings).toContainEqual({ code: 'Digit1', ctrl: false, shift: false, alt: false });
    expect(bindings).toContainEqual({ code: 'Numpad1', ctrl: false, shift: false, alt: false });
    expect(bindings).toContainEqual({ code: 'KeyB', ctrl: true, shift: false, alt: false });
    expect(bindings.some((b) => b.code === 'KeyE')).toBe(false);
  });
});

describe('Custom SubTool Groups (CSP-style) & Instrument Navigation', () => {
  beforeEach(() => {
    installLocalStorage();
    resetBrushStorageCache();
    subToolGroupStoreActions.resetAllGroups();
    toolStoreActions.selectTool('brush');
    activateSubToolPreset('g-pen', []);
  });

  it('creates, renames, reorders, moves brushes between, and deletes custom groups with persistence', () => {
    const inking = subToolGroupStoreActions.createGroup({
      name: 'Lineart',
      color: '#818cf8',
      initialBrushIds: ['g-pen', 'real-g-pen'],
    });
    const painting = subToolGroupStoreActions.createGroup({
      name: 'Painting',
      color: '#34d399',
      initialBrushIds: ['oil-flat-alla-prima'],
    });

    expect(useSubToolGroupStore.getState().groups.map((g) => g.name)).toEqual([
      'Lineart',
      'Painting',
    ]);

    // Moving a brush from Lineart -> Painting removes it from Lineart (CSP single-group ownership)
    subToolGroupStoreActions.moveBrushToGroup('real-g-pen', painting.id);
    const afterMove = useSubToolGroupStore.getState().groups;
    expect(afterMove.find((g) => g.id === inking.id)?.brushIds).toEqual(['g-pen']);
    expect(afterMove.find((g) => g.id === painting.id)?.brushIds).toEqual([
      'oil-flat-alla-prima',
      'real-g-pen',
    ]);

    // Reorder brushes within Painting
    subToolGroupStoreActions.reorderBrushInGroup(painting.id, 'real-g-pen', 'oil-flat-alla-prima');
    expect(
      useSubToolGroupStore.getState().groups.find((g) => g.id === painting.id)?.brushIds
    ).toEqual(['real-g-pen', 'oil-flat-alla-prima']);

    // Rename & reorder groups
    subToolGroupStoreActions.renameGroup(inking.id, 'Manga Inks');
    subToolGroupStoreActions.reorderGroup(painting.id, inking.id);
    expect(useSubToolGroupStore.getState().groups.map((g) => g.name)).toEqual([
      'Painting',
      'Manga Inks',
    ]);

    // Persisted reload preserves custom groups, order, and activeTab
    const reloaded = loadSubToolGroupsState();
    expect(reloaded.groups.map((g) => g.name)).toEqual(['Painting', 'Manga Inks']);
    expect(reloaded.groups[0].brushIds).toEqual(['real-g-pen', 'oil-flat-alla-prima']);

    // Sanitizer rejects invalid entries and deduplicates claimed brushes across groups
    const sanitized = sanitizeSubToolGroupsState({
      groups: [
        { id: 'all', name: 'Reserved', brushIds: ['g-pen'] },
        { id: 'g1', name: 'First', brushIds: ['g-pen', 'g-pen'] },
        { id: 'g2', name: 'Second', brushIds: ['g-pen', 'dot-pen'] },
      ],
      activeTab: 'nonexistent',
    });
    expect(sanitized.groups).toHaveLength(2);
    expect(sanitized.groups[0].brushIds).toEqual(['g-pen']);
    expect(sanitized.groups[1].brushIds).toEqual(['dot-pen']);
    expect(sanitized.activeTab).toBe('all');

    // Deleting custom group returns its brushes safely back to default built-in sections
    subToolGroupStoreActions.deleteGroup(painting.id);
    const penIds = getOrderedSubToolIdsForTab(
      'pen',
      useSubToolGroupStore.getState().groups,
      [],
      useSubToolGroupStore.getState().brushGroupOverrides,
      useSubToolGroupStore.getState().builtinGroupOrders
    );
    expect(penIds).toContain('real-g-pen');
    expect(penIds).not.toContain('g-pen'); // still owned by Manga Inks
  });

  it('moves brushes freely between built-in groups, reorders within them, and persists across reload', () => {
    const importedBrush = createSampleCustomBrush('inkb-imported-1', 'Imported Pen');

    // Move built-in 'real-g-pen' and 'g-pen' from Pen -> Sketch
    expect(subToolGroupStoreActions.moveBrushToGroup('real-g-pen', 'sketch')).toBe(true);
    expect(subToolGroupStoreActions.moveBrushToGroup('g-pen', 'sketch')).toBe(true);
    // Move imported brush from Imported -> Pen
    expect(subToolGroupStoreActions.moveBrushToGroup(importedBrush.id, 'pen')).toBe(true);

    const st = useSubToolGroupStore.getState();
    const penIds = getOrderedSubToolIdsForTab(
      'pen',
      st.groups,
      [importedBrush],
      st.brushGroupOverrides,
      st.builtinGroupOrders
    );
    const sketchIds = getOrderedSubToolIdsForTab(
      'sketch',
      st.groups,
      [importedBrush],
      st.brushGroupOverrides,
      st.builtinGroupOrders
    );
    expect(penIds).not.toContain('g-pen');
    expect(penIds).toContain(importedBrush.id);
    expect(sketchIds).toContain('g-pen');
    expect(sketchIds).toContain('real-g-pen');

    // Reorder 'g-pen' right before 'real-g-pen' inside Sketch
    subToolGroupStoreActions.reorderBrushInGroup(
      'sketch',
      'g-pen',
      'real-g-pen',
      'before',
      sketchIds
    );
    const reloaded = loadSubToolGroupsState();
    const sketchAfter = getOrderedSubToolIdsForTab(
      'sketch',
      reloaded.groups,
      [importedBrush],
      reloaded.brushGroupOverrides,
      reloaded.builtinGroupOrders
    );
    expect(sketchAfter[0]).toBe('g-pen');
    expect(sketchAfter[1]).toBe('real-g-pen');

    // Resetting 'g-pen' returns it to its factory Pen group
    subToolGroupStoreActions.removeBrushFromAllGroups('g-pen');
    const stReset = useSubToolGroupStore.getState();
    expect(
      getOrderedSubToolIdsForTab(
        'pen',
        stReset.groups,
        [importedBrush],
        stReset.brushGroupOverrides,
        stReset.builtinGroupOrders
      )
    ).toContain('g-pen');
  });

  it('cycles previous & next sub tools inside active custom group, main instruments, and sub tool groups', () => {
    const customInk = createSampleCustomBrush('inkb-hero-ink', 'Hero Ink');
    const customGroup = subToolGroupStoreActions.createGroup({
      name: 'My Ink Kit',
      initialBrushIds: ['g-pen', customInk.id, 'calligraphy'],
      selectTab: true,
    });

    activateSubToolPreset('g-pen', [customInk]);
    expect(useToolStore.getState().activePresetId).toBe('g-pen');

    // Next subtool -> customInk -> calligraphy -> wraps to g-pen
    expect(stepSubTool(1, [customInk])?.presetId).toBe(customInk.id);
    expect(useToolStore.getState().activePresetId).toBe(customInk.id);

    expect(stepSubTool(1, [customInk])?.presetId).toBe('calligraphy');
    expect(stepSubTool(1, [customInk])?.presetId).toBe('g-pen');

    // Previous subtool wraps backward to calligraphy
    expect(stepSubTool(-1, [customInk])?.presetId).toBe('calligraphy');

    // Main instrument cycling (Next & Previous Tool)
    toolStoreActions.selectTool('brush');
    expect(stepMainTool(1, false).tool).toBe('decoration');
    expect(stepMainTool(1, false).tool).toBe('eraser');
    expect(stepMainTool(1, false).tool).toBe('pipette');
    expect(stepMainTool(-1, false).tool).toBe('eraser');
    expect(stepMainTool(-1, false).tool).toBe('decoration');
    expect(stepMainTool(-1, false).tool).toBe('brush');
    // Wrap backward from brush without open doc skips '3d' and lands on 'vector-edit'
    expect(stepMainTool(-1, false).tool).toBe('vector-edit');
    // With open doc, '3d' is included
    expect(stepMainTool(1, true).tool).toBe('3d');

    // SubTool Group cycling & direct activation restores custom group's last active brush
    subToolGroupStoreActions.setActiveTab(customGroup.id);
    activateSubToolPreset(customInk.id, [customInk]);
    const nextGrp = stepSubToolGroup(1, [customInk]);
    expect(nextGrp?.groupId).toBe('pen');
    const backGrp = stepSubToolGroup(-1, [customInk]);
    expect(backGrp?.groupId).toBe(customGroup.id);
    expect(useToolStore.getState().activePresetId).toBe(customInk.id);

    const directOpen = activateSubToolGroup(customGroup.id, [customInk]);
    expect(directOpen?.groupName).toBe('My Ink Kit');
    expect(directOpen?.activatedBrushName).toBe('Hero Ink');
  });

  it('builds dynamic subtool & group commands, detects conflicts, and supports spring-loaded subtool holds', () => {
    const customBrush = createSampleCustomBrush('inkb-manga-pen', 'Manga Fineliner');
    const group = subToolGroupStoreActions.createGroup({
      name: 'Inking',
      initialBrushIds: [customBrush.id],
    });

    const dynamic = buildSubToolShortcutCommands([customBrush], [group]);
    const brushCmdId = getSubToolCommandId(customBrush.id);
    const groupCmdId = getSubToolGroupCommandId(group.id);

    expect(dynamic.find((c) => c.id === brushCmdId)?.label).toBe('Manga Fineliner');
    expect(dynamic.find((c) => c.id === groupCmdId)?.label).toBe('Group: Inking');

    const mgr = new ShortcutManager(DEFAULT_COMMANDS);
    mgr.setDynamicCommands(dynamic);
    mgr.setOverrides({
      [brushCmdId]: 'OS+1',
      [groupCmdId]: 'OS+Shift+1',
    });

    expect(
      mgr.matchEvent({ key: '1', code: 'Digit1', metaKey: true }, undefined, 'windows')?.id
    ).toBe(brushCmdId);
    expect(
      mgr.matchEvent(
        { key: '1', code: 'Digit1', metaKey: true, shiftKey: true },
        undefined,
        'windows'
      )?.id
    ).toBe(groupCmdId);

    // Conflict detection works across static + dynamic commands
    const conflictsWithBrush = findShortcutConflicts(
      'tool.eraser',
      'OS+1',
      { [brushCmdId]: 'OS+1' },
      mgr.getCommands()
    );
    expect(conflictsWithBrush.map((c) => c.id)).toEqual([brushCmdId]);

    // Spring-loaded subtool hold: tap keeps subtool, hold > 250ms reverts to previous tool+preset
    let clock = 1000;
    const subSpring = new SpringLoadedSubToolController(SPRING_LOADED_HOLD_MS, () => clock);
    expect(subSpring.handleSubToolKeyDown('Digit1', customBrush.id, 'brush', 'g-pen')).toBe(true);
    clock += 100;
    expect(subSpring.handleKeyUp('Digit1', 'brush', customBrush.id)).toBeNull(); // tap stays

    expect(subSpring.handleSubToolKeyDown('Digit1', customBrush.id, 'eraser', 'g-pen')).toBe(true);
    clock += 300;
    expect(subSpring.handleKeyUp('Digit1', 'brush', customBrush.id)).toEqual({
      tool: 'eraser',
      presetId: 'g-pen',
    });
  });
});

describe('UI & GlobalShortcutListener Integration for Custom Groups, SubTool Shortcuts & OS Key', () => {
  let dom: ReturnType<typeof installMiniDom>;
  let root: Root | null = null;
  const customBrush = createSampleCustomBrush('inkb-custom-ink', 'Custom Studio Ink');

  beforeEach(async () => {
    installLocalStorage();
    dom = installMiniDom();
    resetBrushStorageCache();
    subToolGroupStoreActions.resetAllGroups();
    uiStoreActions.updateAppSettings({ ...DEFAULT_APP_SETTINGS, shortcuts: {} });
    await saveCustomBrush(customBrush);
    toolStoreActions.selectTool('brush');
    activateSubToolPreset('g-pen', [customBrush]);
  });

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

  it('creates custom groups, assigns brushes, and binds OS-key subtool shortcuts inline in SubToolList', () => {
    act(() => {
      root = createRoot(dom.container as unknown as Element);
      root.render(<SubToolList customBrushes={[customBrush]} setCustomBrushes={() => {}} />);
    });

    // 1. Click "+ Create SubTool Group" button and create "My Inks"
    const createBtn = dom.container.findByAttr('data-testid', 'subtool-create-group-btn');
    act(() => {
      invokeReactProp(createBtn, 'onClick');
    });
    const nameInput = dom.container.findByAttr('data-testid', 'subtool-create-group-input');
    expect(nameInput).not.toBeNull();
    act(() => {
      invokeReactProp(nameInput, 'onChange', { target: { value: 'My Inks' } });
    });
    const confirmBtn = dom.container.findByAttr('data-testid', 'subtool-create-group-confirm');
    act(() => {
      invokeReactProp(confirmBtn, 'onClick');
    });

    const groups = useSubToolGroupStore.getState().groups;
    expect(groups).toHaveLength(1);
    expect(groups[0].name).toBe('My Inks');
    const groupId = groups[0].id;

    // 2. Open inline brush picker for "My Inks" and assign customBrush
    const addBrushesBtn = dom.container.findByAttr(
      'data-testid',
      `subtool-group-add-brushes-btn-${groupId}`
    );
    act(() => {
      invokeReactProp(addBrushesBtn, 'onClick');
    });
    const pickCustomBtn = dom.container.findByAttr(
      'data-testid',
      `subtool-group-pick-${groupId}-${customBrush.id}`
    );
    act(() => {
      invokeReactProp(pickCustomBtn, 'onClick');
    });
    expect(useSubToolGroupStore.getState().groups[0].brushIds).toEqual([customBrush.id]);

    // 3. Open context menu on customBrush row -> Set Shortcut... -> bind Win+1 (OS+1)
    const menuBtn = dom.container.findByAttr('data-testid', `subtool-menu-btn-${customBrush.id}`);
    act(() => {
      invokeReactProp(menuBtn, 'onClick');
    });
    const setShortcutBtn = dom.body.findByAttr('data-testid', 'subtool-ctx-set-shortcut');
    expect(setShortcutBtn).not.toBeNull();
    act(() => {
      invokeReactProp(setShortcutBtn, 'onClick');
    });

    // Toggle "+ Win Key" inside SubToolShortcutModal and press Digit1
    const osToggle = dom.body.findByAttr('data-testid', 'subtool-shortcut-os-toggle');
    expect(osToggle).not.toBeNull();
    act(() => {
      invokeReactProp(osToggle, 'onClick');
    });
    act(() => {
      dom.dispatchKeyDown({ key: '1', code: 'Digit1' });
    });

    expect(useUiStore.getState().appSettings.shortcuts[getSubToolCommandId(customBrush.id)]).toBe(
      'OS+1'
    );
    // Shortcut badge now renders on the subtool row
    const badge = dom.container.findByAttr(
      'data-testid',
      `subtool-shortcut-badge-${customBrush.id}`
    );
    expect(badge?.textContent).toBe('Win + 1');
  });

  it('supports Tauri-compatible pointer drag-and-drop across groups and drag-to-create custom groups', () => {
    act(() => {
      root = createRoot(dom.container as unknown as Element);
      root.render(<SubToolList customBrushes={[customBrush]} setCustomBrushes={() => {}} />);
    });

    // Both toolbar "+ Group" icon and wrapping tab bar "+ Group" button are rendered
    const createGroupBtn = dom.container.findByAttr('data-testid', 'subtool-create-group-btn')!;
    const toolbarNewGroupBtn = dom.container.findByAttr(
      'data-testid',
      'subtool-toolbar-new-group-btn'
    );
    const sketchTab = dom.container.findByAttr('data-testid', 'subtool-group-tab-sketch')!;
    const gPenRow = dom.container.findByAttr('data-testid', 'subtool-row-g-pen')!;
    const realGPenRow = dom.container.findByAttr('data-testid', 'subtool-row-real-g-pen')!;

    expect(createGroupBtn).not.toBeNull();
    expect(toolbarNewGroupBtn).not.toBeNull();

    // Give non-overlapping deterministic bounding boxes to drop targets
    const makeRect = (left: number, top: number, width: number, height: number) => ({
      left,
      top,
      right: left + width,
      bottom: top + height,
      width,
      height,
      x: left,
      y: top,
      toJSON: () => ({}),
    });
    // Reset default rects on all elements so only our positioned targets match test coordinates
    const allDropEls = [
      ...dom.container.querySelectorAll('[data-subtool-drop="create-group"]'),
      ...dom.container.querySelectorAll('[data-subtool-drop-tab]'),
      ...dom.container.querySelectorAll('[data-subtool-drop-row]'),
      ...dom.container.querySelectorAll('[data-subtool-drop-section]'),
    ];
    for (const el of allDropEls) {
      el.getBoundingClientRect = () => makeRect(0, 0, 0, 0);
    }
    const tabBar = dom.container.findByAttr('data-testid', 'subtool-group-tab-bar')!;
    tabBar.getBoundingClientRect = () => makeRect(0, 0, 200, 44);
    sketchTab.getBoundingClientRect = () => makeRect(60, 4, 48, 20);
    createGroupBtn.getBoundingClientRect = () => makeRect(120, 24, 60, 20);

    // 1. Pointer-drag 'g-pen' onto the 'Sketch' tab -> moves 'g-pen' into 'sketch'!
    act(() => {
      invokeReactProp(gPenRow, 'onPointerDown', { button: 0, clientX: 40, clientY: 120 });
    });
    act(() => {
      dom.window.dispatchEvent({ type: 'pointermove', clientX: 80, clientY: 14 } as unknown as {
        type: string;
      });
    });
    // Floating drag ghost appears with "Move to Sketch" hint
    const ghost = dom.body.findByAttr('data-testid', 'subtool-drag-ghost');
    expect(ghost?.textContent).toContain('G-Pen');
    expect(ghost?.textContent).toContain('Move to Sketch');

    act(() => {
      dom.window.dispatchEvent({ type: 'pointerup', clientX: 80, clientY: 14 } as unknown as {
        type: string;
      });
    });
    expect(useSubToolGroupStore.getState().brushGroupOverrides['g-pen']).toBe('sketch');

    // 2. Pointer-drag 'real-g-pen' onto "+ Group" button -> creates a new Custom SubTool Group!
    act(() => {
      invokeReactProp(realGPenRow, 'onPointerDown', { button: 0, clientX: 40, clientY: 150 });
    });
    act(() => {
      dom.window.dispatchEvent({ type: 'pointermove', clientX: 140, clientY: 32 } as unknown as {
        type: string;
      });
    });
    expect(dom.body.findByAttr('data-testid', 'subtool-drag-ghost')?.textContent).toContain(
      '+ Create New Group'
    );
    act(() => {
      dom.window.dispatchEvent({ type: 'pointerup', clientX: 140, clientY: 32 } as unknown as {
        type: string;
      });
    });

    const createdGroups = useSubToolGroupStore.getState().groups;
    expect(createdGroups).toHaveLength(1);
    expect(createdGroups[0].brushIds).toEqual(['real-g-pen']);
    expect(useSubToolGroupStore.getState().activeTab).toBe(createdGroups[0].id);
  });

  it('dispatches prev/next instrument, direct custom subtool, group, and native OS-key hotkeys in GlobalShortcutListener', () => {
    const group = subToolGroupStoreActions.createGroup({
      name: 'Fast Brushes',
      initialBrushIds: ['g-pen', customBrush.id],
      selectTab: true,
    });

    const brushCmdId = getSubToolCommandId(customBrush.id);
    const groupCmdId = getSubToolGroupCommandId(group.id);
    const toasts: string[] = [];
    const onUndo = vi.fn();

    uiStoreActions.updateAppSettings({
      ...DEFAULT_APP_SETTINGS,
      shortcuts: {
        [brushCmdId]: 'OS+1',
        [groupCmdId]: 'OS+2',
        'edit.undo': 'OS+Q',
      },
    });

    const isFalseRef = { current: false };
    act(() => {
      root = createRoot(dom.container as unknown as Element);
      root.render(
        <GlobalShortcutListener
          hasOpenDocument={true}
          dimensions={{ width: 800, height: 600, dpi: 300 }}
          layers={[]}
          activeLayer={undefined}
          activeLayerId=""
          selection={null}
          transformSession={null}
          textSession={null}
          activeAnimationTimeline={null}
          isSpaceDown={false}
          isHostModalOpen={false}
          isDrawingRef={isFalseRef}
          isSelectionPenDrawingRef={isFalseRef}
          isPipetteSamplingRef={isFalseRef}
          handleUndo={onUndo}
          redo={() => {}}
          handleAddLayer={() => {}}
          handleTriggerOpenFile={() => {}}
          handleSave={() => {}}
          handleSaveAs={() => {}}
          duplicateLayer={() => {}}
          handleCutSelection={() => {}}
          handleCopySelection={() => {}}
          handleCopySelectedLayer={() => {}}
          handlePasteSelectedLayer={() => {}}
          handleMoveSelectionToNewLayer={() => {}}
          handleCopySelectionToNewLayer={() => {}}
          handleGroupSelectedLayers={() => {}}
          handleStartTransform={() => {}}
          handleSelectAll={() => {}}
          handleDeselect={() => {}}
          handleInvertSelection={() => {}}
          handleApplyReverseGradient={() => {}}
          handleOpenTonalModal={() => {}}
          handleUpdateAnimationTimeline={() => {}}
          handleAddAnimationCel={() => {}}
          toggleFlipHorizontal={() => {}}
          toggleFlipVertical={() => {}}
          handleClearSelection={() => {}}
          handleDeleteSelectedLayer={() => {}}
          handleCancelTransform={() => {}}
          handleCancelText={() => {}}
          handleApplyTransform={() => {}}
          handleProcessFile={() => {}}
          showToast={(m) => toasts.push(m)}
        />
      );
    });

    // 1. Default '.' switches to Next Sub Tool inside active custom group
    expect(useToolStore.getState().activePresetId).toBe('g-pen');
    act(() => {
      dom.dispatchKeyDown({ key: '.', code: 'Period' });
    });
    expect(useToolStore.getState().activePresetId).toBe(customBrush.id);

    // 2. Default ',' switches back to Previous Sub Tool
    act(() => {
      dom.dispatchKeyDown({ key: ',', code: 'Comma' });
    });
    expect(useToolStore.getState().activePresetId).toBe('g-pen');

    // 3. Default 'Shift+.' switches to Next Main Tool (brush -> decoration)
    act(() => {
      dom.dispatchKeyDown({ key: '>', code: 'Period', shiftKey: true });
    });
    expect(useToolStore.getState().tool).toBe('decoration');

    // 4. Direct custom subtool hotkey via Win+1 (metaKey: true) jumps directly to brush + customBrush!
    act(() => {
      dom.dispatchKeyDown({ key: '1', code: 'Digit1', metaKey: true });
    });
    expect(useToolStore.getState().tool).toBe('brush');
    expect(useToolStore.getState().activePresetId).toBe(customBrush.id);

    // 5. General command (edit.undo) bound to OS+Q triggers via native Windows OS-hotkey event!
    act(() => {
      dispatchNativeOsHotkeyForTest({
        phase: 'keydown',
        code: 'KeyQ',
        key: 'q',
        ctrlKey: false,
        metaKey: true,
        shiftKey: false,
        altKey: false,
        repeat: false,
        isRecording: false,
      });
    });
    expect(onUndo).toHaveBeenCalledTimes(1);

    // 6. Native event with isRecording: true is ignored by GlobalShortcutListener
    act(() => {
      dispatchNativeOsHotkeyForTest({
        phase: 'keydown',
        code: 'KeyQ',
        key: 'q',
        ctrlKey: false,
        metaKey: true,
        shiftKey: false,
        altKey: false,
        repeat: false,
        isRecording: true,
      });
    });
    expect(onUndo).toHaveBeenCalledTimes(1);

    // 7. Direct custom group shortcut (OS+2) switches tab back to group even from 'pen' tab
    subToolGroupStoreActions.setActiveTab('pen');
    act(() => {
      dom.dispatchKeyDown({ key: '2', code: 'Digit2', metaKey: true });
    });
    expect(useSubToolGroupStore.getState().activeTab).toBe(group.id);
  });

  it('lists Sub Tools & Custom Groups in SettingsModal Shortcuts tab and records OS-key hotkeys', async () => {
    const group = subToolGroupStoreActions.createGroup({
      name: 'Manga Pens',
      initialBrushIds: [customBrush.id],
    });
    const onUpdateSettings = vi.fn();

    await act(async () => {
      root = createRoot(dom.container as unknown as Element);
      root.render(
        <SettingsModal
          isOpen={true}
          onClose={() => {}}
          settings={{ ...DEFAULT_APP_SETTINGS, shortcuts: {} }}
          onUpdateSettings={onUpdateSettings}
          onShowToast={() => {}}
        />
      );
      await Promise.resolve();
    });

    // Click Shortcuts tab in left nav
    const findButtonByText = (node: MiniEl, label: string): MiniEl | null => {
      if (node.tagName === 'BUTTON' && node.textContent.trim() === label) return node;
      for (const c of node.childNodes) {
        if (c instanceof MiniEl) {
          const hit = findButtonByText(c, label);
          if (hit) return hit;
        }
      }
      return null;
    };
    const shortcutsTabBtn = findButtonByText(dom.container, 'Shortcuts');
    expect(shortcutsTabBtn).not.toBeNull();
    act(() => {
      invokeReactProp(shortcutsTabBtn, 'onClick');
    });

    // Filter to 'Sub Tools' category
    const subToolsCatBtn = dom.container.findByAttr(
      'data-testid',
      'settings-shortcut-cat-Sub Tools'
    );
    expect(subToolsCatBtn).not.toBeNull();
    act(() => {
      invokeReactProp(subToolsCatBtn, 'onClick');
    });

    // Both the custom group and custom brush appear with click-to-record buttons
    const groupRecordBtn = dom.container.findByAttr(
      'data-testid',
      `settings-shortcut-record-${getSubToolGroupCommandId(group.id)}`
    );
    const brushRecordBtn = dom.container.findByAttr(
      'data-testid',
      `settings-shortcut-record-${getSubToolCommandId(customBrush.id)}`
    );
    expect(groupRecordBtn).not.toBeNull();
    expect(brushRecordBtn).not.toBeNull();

    // Record Win+Shift+3 (via metaKey: true) on customBrush
    act(() => {
      invokeReactProp(brushRecordBtn, 'onClick');
    });
    expect(
      dom.container.findByAttr('data-testid', 'settings-shortcut-recording-bar')
    ).not.toBeNull();

    act(() => {
      dom.dispatchKeyDown({ key: '3', code: 'Digit3', metaKey: true, shiftKey: true });
    });

    expect(onUpdateSettings).toHaveBeenCalled();
    const lastSettings = onUpdateSettings.mock.calls[onUpdateSettings.mock.calls.length - 1][0];
    expect(lastSettings.shortcuts[getSubToolCommandId(customBrush.id)]).toBe('OS+Shift+3');
  });
});