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
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { LayerColorLabel, LayerItem } from '../../types/editor';
import { RightSidebar } from '../../components/RightSidebar';
import {
  DEFAULT_LAYER_FILTER_CRITERIA,
  computeBatchColorLabel,
  computeRestoreSolo,
  computeSoloToggle,
  filterLayerTree,
  fromPsdLayerColor,
  toPsdLayerColor,
} from '../layerOrganization';
import { sanitizeJsonLayer } from '../saveManager/types';
import { sanitizeWireLayerPatch } from '../collabSyncUtils';

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;
  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 options(): MiniEl[] {
    return this.childNodes.filter(
      (c): c is MiniEl => c instanceof MiniEl && c.tagName === 'OPTION'
    );
  }

  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,
      width: 200,
      height: 28,
      right: 200,
      bottom: 28,
      x: 0,
      y: 0,
      toJSON: () => ({}),
    };
  }

  focus() {}
  blur() {}
  select() {}

  override dispatchEvent(event: Event): boolean {
    if (!event.target) {
      Object.defineProperty(event, 'target', { value: this, configurable: true });
    }
    let cur: MiniEl | null = this;
    while (cur) {
      EventTarget.prototype.dispatchEvent.call(cur, event);
      if (!event.bubbles) break;
      cur = cur.parentNode;
    }
    return !event.defaultPrevented;
  }

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

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

  findAllByAttr(attr: string): MiniEl[] {
    const out: MiniEl[] = [];
    if (this.attrs.has(attr)) out.push(this);
    for (const c of this.childNodes) {
      if (c instanceof MiniEl) out.push(...c.findAllByAttr(attr));
    }
    return out;
  }
}

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,
    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: MiniDoc = {
    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),
  };

  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 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),
  };
  mockDoc.defaultView = mockWin;

  g.window = mockWin;
  g.document = mockDoc;
  g.HTMLElement = MiniEl;
  g.Node = MiniEl;
  g.Element = MiniEl;

  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 makeSampleLayers(): LayerItem[] {
  return [
    {
      id: 'folder-char',
      name: 'Character',
      type: 'folder',
      visible: true,
      opacity: 1,
      blendMode: 'pass-through',
      locked: false,
      collapsed: true, // Collapsed on purpose to test search revealing nested matches
      parentId: null,
      colorLabel: 'blue',
    },
    {
      id: 'layer-eyes',
      name: 'Eyes Highlight',
      type: 'raster',
      visible: true,
      opacity: 1,
      blendMode: 'add-glow',
      locked: false,
      parentId: 'folder-char',
      colorLabel: 'red',
    },
    {
      id: 'layer-inks',
      name: 'Lineart Inks',
      type: 'raster',
      visible: true,
      opacity: 1,
      blendMode: 'normal',
      locked: true,
      isReference: true,
      parentId: 'folder-char',
      colorLabel: 'green',
    },
    {
      id: 'layer-sketch',
      name: 'Rough Sketch',
      type: 'raster',
      visible: false, // Pre-hidden layer to verify solo restore preserves hidden state!
      opacity: 0.5,
      blendMode: 'normal',
      locked: false,
      parentId: null,
      colorLabel: 'orange',
    },
    {
      id: 'layer-title',
      name: 'Title Text',
      type: 'text',
      visible: true,
      opacity: 1,
      blendMode: 'normal',
      locked: false,
      parentId: null,
    },
    {
      id: 'layer-bg',
      name: 'Background',
      type: 'raster',
      visible: true,
      opacity: 1,
      blendMode: 'normal',
      locked: false,
      parentId: null,
    },
  ];
}

describe('Layer Organization Pure Logic (Search/Filter, Color Labels, Solo/Isolate)', () => {
  it('filters layers by search query, color label, and kind while preserving ancestor folders', () => {
    const layers = makeSampleLayers();

    // Name search for nested child inside collapsed folder
    const eyesRes = filterLayerTree(layers, {
      ...DEFAULT_LAYER_FILTER_CRITERIA,
      query: 'eyes',
    });
    expect(eyesRes.isActive).toBe(true);
    expect(eyesRes.matchCount).toBe(1);
    expect(eyesRes.directMatchIds.has('layer-eyes')).toBe(true);
    expect(eyesRes.ancestorOnlyIds.has('folder-char')).toBe(true);
    expect(eyesRes.visibleLayerIds.has('folder-char')).toBe(true);
    expect(eyesRes.visibleLayerIds.has('layer-eyes')).toBe(true);
    expect(eyesRes.visibleLayerIds.has('layer-bg')).toBe(false);

    // Filter by color label
    const redRes = filterLayerTree(layers, {
      ...DEFAULT_LAYER_FILTER_CRITERIA,
      colorLabel: 'red',
    });
    expect(redRes.matchCount).toBe(1);
    expect(redRes.directMatchIds.has('layer-eyes')).toBe(true);

    // Filter unlabeled layers ('none')
    const unlabeledRes = filterLayerTree(layers, {
      ...DEFAULT_LAYER_FILTER_CRITERIA,
      colorLabel: 'none',
    });
    expect(unlabeledRes.matchCount).toBe(2); // layer-title + layer-bg
    expect(unlabeledRes.directMatchIds.has('layer-title')).toBe(true);
    expect(unlabeledRes.directMatchIds.has('layer-bg')).toBe(true);

    // Filter by kind: hidden / locked / reference / text
    expect(
      filterLayerTree(layers, { ...DEFAULT_LAYER_FILTER_CRITERIA, kind: 'hidden' }).matchCount
    ).toBe(1);
    expect(
      filterLayerTree(layers, { ...DEFAULT_LAYER_FILTER_CRITERIA, kind: 'locked' }).matchCount
    ).toBe(1);
    expect(
      filterLayerTree(layers, { ...DEFAULT_LAYER_FILTER_CRITERIA, kind: 'reference' }).matchCount
    ).toBe(1);
    expect(
      filterLayerTree(layers, { ...DEFAULT_LAYER_FILTER_CRITERIA, kind: 'text' }).matchCount
    ).toBe(1);
  });

  it('batch-applies and clears layer color labels and round-trips through PSD, .ink, and collab sanitization', () => {
    const layers = makeSampleLayers();
    const updated = computeBatchColorLabel(
      layers,
      ['layer-title', 'layer-bg'],
      'layer-title',
      'purple'
    );
    expect(updated.find((l) => l.id === 'layer-title')?.colorLabel).toBe('purple');
    expect(updated.find((l) => l.id === 'layer-bg')?.colorLabel).toBe('purple');

    const cleared = computeBatchColorLabel(updated, ['layer-title'], 'layer-title', 'none');
    expect(cleared.find((l) => l.id === 'layer-title')?.colorLabel).toBeUndefined();

    // PSD color mapping parity
    expect(toPsdLayerColor('purple')).toBe('violet');
    expect(fromPsdLayerColor('violet')).toBe('purple');
    expect(toPsdLayerColor('red')).toBe('red');
    expect(fromPsdLayerColor('none')).toBeUndefined();

    // .ink JSON & collab wire sanitization
    expect(sanitizeJsonLayer({ id: 'x', colorLabel: 'cyan' }).colorLabel).toBe('cyan');
    expect(sanitizeJsonLayer({ id: 'x', colorLabel: 'invalid-color' }).colorLabel).toBeUndefined();
    expect(sanitizeWireLayerPatch({ colorLabel: 'orange' }).colorLabel).toBe('orange');
  });

  it('isolates a nested layer with ancestor preservation, switches solo targets cleanly, and restores exact pre-solo visibility', () => {
    const layers = makeSampleLayers();

    // 1. Alt+Click Eyes (nested inside Character folder) -> only Character + Eyes stay visible
    const step1 = computeSoloToggle(layers, 'layer-eyes', null);
    expect(step1.action).toBe('solo');
    expect(step1.nextSolo?.layerId).toBe('layer-eyes');
    expect(step1.nextLayers.find((l) => l.id === 'layer-eyes')?.visible).toBe(true);
    expect(step1.nextLayers.find((l) => l.id === 'folder-char')?.visible).toBe(true);
    expect(step1.nextLayers.find((l) => l.id === 'layer-inks')?.visible).toBe(false);
    expect(step1.nextLayers.find((l) => l.id === 'layer-sketch')?.visible).toBe(false);
    expect(step1.nextLayers.find((l) => l.id === 'layer-bg')?.visible).toBe(false);

    // 2. Switch solo directly to Rough Sketch (which was originally hidden!) -> becomes visible, original snapshot preserved
    const step2 = computeSoloToggle(step1.nextLayers, 'layer-sketch', step1.nextSolo);
    expect(step2.action).toBe('switch-solo');
    expect(step2.nextSolo?.layerId).toBe('layer-sketch');
    expect(step2.nextLayers.find((l) => l.id === 'layer-sketch')?.visible).toBe(true);
    expect(step2.nextLayers.find((l) => l.id === 'layer-eyes')?.visible).toBe(false);
    expect(step2.nextLayers.find((l) => l.id === 'folder-char')?.visible).toBe(false);

    // 3. Alt+Click Rough Sketch again -> restores ORIGINAL pre-solo visibility (Rough Sketch returns to false!)
    const step3 = computeSoloToggle(step2.nextLayers, 'layer-sketch', step2.nextSolo);
    expect(step3.action).toBe('restore');
    expect(step3.nextSolo).toBeNull();
    expect(step3.nextLayers.find((l) => l.id === 'layer-sketch')?.visible).toBe(false);
    expect(step3.nextLayers.find((l) => l.id === 'layer-eyes')?.visible).toBe(true);
    expect(step3.nextLayers.find((l) => l.id === 'layer-inks')?.visible).toBe(true);
    expect(step3.nextLayers.find((l) => l.id === 'layer-bg')?.visible).toBe(true);

    // 4. Soloing a folder isolates folder + preserves descendants' visibility while hiding outside layers
    const folderSolo = computeSoloToggle(layers, 'folder-char', null);
    expect(folderSolo.action).toBe('solo');
    expect(folderSolo.nextLayers.find((l) => l.id === 'folder-char')?.visible).toBe(true);
    expect(folderSolo.nextLayers.find((l) => l.id === 'layer-eyes')?.visible).toBe(true);
    expect(folderSolo.nextLayers.find((l) => l.id === 'layer-inks')?.visible).toBe(true);
    expect(folderSolo.nextLayers.find((l) => l.id === 'layer-bg')?.visible).toBe(false);

    // 5. Explicit restore helper restores cleanly
    const restored = computeRestoreSolo(folderSolo.nextLayers, folderSolo.nextSolo);
    expect(restored.nextSolo).toBeNull();
    expect(restored.nextLayers.find((l) => l.id === 'layer-bg')?.visible).toBe(true);
  });
});

describe('RightSidebar Layer Organization UI (Search/Filter, Color Labels, Alt+Click Solo)', () => {
  let dom: ReturnType<typeof installMiniDom>;
  let root: Root | null = null;

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

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

  it('supports search/filter, color label picker, and Alt+Click solo with restore banner in RightSidebar', () => {
    const layers = makeSampleLayers();
    const onToggleVisibility = vi.fn();
    const onSoloLayer = vi.fn();
    const onExitSoloLayer = vi.fn();
    const onSetLayerColorLabel = vi.fn();

    const renderSidebar = (soloLayerId: string | null = null, currentLayers = layers) => {
      act(() => {
        if (!root) {
          root = createRoot(dom.container as unknown as Element);
        }
        root.render(
          <RightSidebar
            dockedMode="layers"
            hideColorPanel
            hasOpenDocument
            layers={currentLayers}
            activeLayerId="layer-eyes"
            soloLayerId={soloLayerId}
            historyList={[]}
            historyIndex={-1}
            onJumpToHistory={vi.fn()}
            canUndo={false}
            canRedo={false}
            onUndo={vi.fn()}
            onRedo={vi.fn()}
            onSelectLayer={vi.fn()}
            onAddLayer={vi.fn()}
            onDuplicateLayer={vi.fn()}
            onDeleteLayer={vi.fn()}
            onToggleVisibility={onToggleVisibility}
            onSoloLayer={onSoloLayer}
            onExitSoloLayer={onExitSoloLayer}
            onSetLayerColorLabel={onSetLayerColorLabel}
            onSetOpacity={vi.fn()}
            onSetBlendMode={vi.fn()}
            onToggleLock={vi.fn()}
            onToggleCollapse={vi.fn()}
            onRenameLayer={vi.fn()}
            onMoveLayerToFolder={vi.fn()}
          />
        );
      });
    };

    renderSidebar(null);

    // 1. Color label tags render on labeled rows
    expect(dom.container.findByAttr('data-testid', 'layer-color-tag-folder-char')).not.toBeNull();
    expect(dom.container.findByAttr('data-testid', 'layer-color-tag-layer-sketch')).not.toBeNull();

    // 2. Open Filter strip and filter by color label 'red' -> reveals nested 'layer-eyes' inside collapsed 'folder-char'
    act(() => {
      dom.container
        .findByAttr('data-testid', 'layer-filter-toggle')!
        .dispatchEvent(new Event('click', { bubbles: true }));
    });
    expect(dom.container.findByAttr('data-testid', 'layer-filter-strip')).not.toBeNull();

    act(() => {
      dom.container
        .findByAttr('data-testid', 'layer-filter-color-red')!
        .dispatchEvent(new Event('click', { bubbles: true }));
    });
    const redFilteredRows = dom.container
      .findByAttr('data-testid', 'layers-scroll-stack')!
      .findAllByAttr('data-layer-id')
      .map((el) => el.getAttribute('data-layer-id'));
    expect(redFilteredRows).toEqual(['folder-char', 'layer-eyes']);

    // Reset filter
    act(() => {
      dom.container
        .findByAttr('data-testid', 'layer-filter-reset')!
        .dispatchEvent(new Event('click', { bubbles: true }));
    });

    // 3. Assign color label from active-layer quick picker
    act(() => {
      dom.container
        .findByAttr('data-testid', 'active-layer-color-label-btn')!
        .dispatchEvent(new Event('click', { bubbles: true }));
    });
    act(() => {
      dom.container
        .findByAttr('data-testid', 'active-color-label-option-purple')!
        .dispatchEvent(new Event('click', { bubbles: true }));
    });
    expect(onSetLayerColorLabel).toHaveBeenCalledWith('layer-eyes', 'purple');

    // 4. Normal eye click calls onToggleVisibility; Alt+Click eye calls onSoloLayer
    const bgEyeBtn = dom.container.findByAttr('data-testid', 'layer-eye-layer-bg')!;
    act(() => {
      bgEyeBtn.dispatchEvent(Object.assign(new Event('click', { bubbles: true }), { altKey: false }));
    });
    expect(onToggleVisibility).toHaveBeenCalledWith('layer-bg');
    expect(onSoloLayer).not.toHaveBeenCalled();

    act(() => {
      bgEyeBtn.dispatchEvent(Object.assign(new Event('click', { bubbles: true }), { altKey: true }));
    });
    expect(onSoloLayer).toHaveBeenCalledWith('layer-bg');

    // 5. Render with soloLayerId active -> displays Solo banner and Restore button
    renderSidebar('layer-bg');
    const banner = dom.container.findByAttr('data-testid', 'layer-solo-banner');
    expect(banner).not.toBeNull();
    expect(banner?.textContent).toContain('Background');
    expect(
      dom.container.findByAttr('data-testid', 'layer-eye-layer-bg')?.getAttribute('data-solo-active')
    ).toBe('true');

    act(() => {
      dom.container
        .findByAttr('data-testid', 'layer-solo-restore-btn')!
        .dispatchEvent(new Event('click', { bubbles: true }));
    });
    expect(onExitSoloLayer).toHaveBeenCalledTimes(1);

    // 6. Right-click context menu exposes color labels and solo button
    const bgRow = dom.container.findByAttr('data-layer-id', 'layer-bg')!;
    act(() => {
      bgRow.dispatchEvent(
        Object.assign(new Event('contextmenu', { bubbles: true }), { clientX: 100, clientY: 120 })
      );
    });
    expect(dom.container.findByAttr('data-testid', 'context-menu-color-labels')).not.toBeNull();
    act(() => {
      dom.container
        .findByAttr('data-testid', 'context-color-label-cyan')!
        .dispatchEvent(new Event('click', { bubbles: true }));
    });
    expect(onSetLayerColorLabel).toHaveBeenCalledWith('layer-bg', 'cyan' satisfies LayerColorLabel);
  });
});