Skip to content

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

23.4 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
  SUB_VIEW_STORAGE_KEY,
  subViewStoreActions,
  useSubViewStore,
} from '../../stores/useSubViewStore';
import { useToolStore } from '../../stores/useToolStore';
import { SubViewPanel } from '../../components/SubViewPanel';
import {
  BoardCardGeometry,
  SubViewTransform,
  applyStudyFilterToImageData,
  boardPointToCardLocal,
  boardPointToStagePoint,
  cardLocalToBoardPoint,
  computeBoardAutoLayout,
  computeBoardFitTransform,
  extractDominantColorsFromCanvas,
  getCardStageOverlay,
  hitTestBoardCards,
  hitTestCardHandle,
  stagePointToBoardPoint,
} from '../subViewEngine';

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

function createMock2DContext(pixelColor: [number, number, number, number] = [230, 90, 40, 255]) {
  return {
    save: vi.fn(),
    restore: vi.fn(),
    setTransform: vi.fn(),
    clearRect: vi.fn(),
    fillRect: vi.fn(),
    strokeRect: vi.fn(),
    beginPath: vi.fn(),
    rect: vi.fn(),
    clip: vi.fn(),
    arc: vi.fn(),
    moveTo: vi.fn(),
    lineTo: vi.fn(),
    closePath: vi.fn(),
    fill: vi.fn(),
    stroke: vi.fn(),
    translate: vi.fn(),
    rotate: vi.fn(),
    scale: vi.fn(),
    drawImage: vi.fn(),
    createImageData: (w: number, h: number) => ({
      data: new Uint8ClampedArray(w * h * 4),
      width: w,
      height: h,
    }),
    putImageData: vi.fn(),
    getImageData: vi.fn((_x: number, _y: number, w: number, h: number) => {
      const data = new Uint8ClampedArray(w * h * 4);
      for (let i = 0; i < data.length; i += 4) {
        data[i] = pixelColor[0];
        data[i + 1] = pixelColor[1];
        data[i + 2] = pixelColor[2];
        data[i + 3] = pixelColor[3];
      }
      return { data, width: w, height: h };
    }),
    imageSmoothingEnabled: true,
    fillStyle: '',
    strokeStyle: '',
    lineWidth: 1,
    globalAlpha: 1,
    globalCompositeOperation: 'source-over',
  };
}

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 = '';
  width = 240;
  height = 180;
  clientWidth = 240;
  clientHeight = 180;
  attrs = new Map<string, string>();
  private mockCtx: ReturnType<typeof createMock2DContext> | null = null;

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

  getBoundingClientRect() {
    return {
      left: 0,
      top: 0,
      width: this.clientWidth,
      height: this.clientHeight,
      right: this.clientWidth,
      bottom: this.clientHeight,
      x: 0,
      y: 0,
      toJSON: () => ({}),
    };
  }

  setPointerCapture() {}
  releasePointerCapture() {}

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

  getContext(type: string) {
    if (type === '2d') {
      if (!this.mockCtx) this.mockCtx = createMock2DContext(this.ownerDocument.mockSampleColor);
      return this.mockCtx;
    }
    return null;
  }

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

  findAllByAttrPrefix(attr: string, prefix: string): MiniEl[] {
    const out: MiniEl[] = [];
    const val = this.getAttribute(attr);
    if (val && val.startsWith(prefix)) out.push(this);
    for (const c of this.childNodes) {
      if (c instanceof MiniEl) {
        out.push(...c.findAllByAttrPrefix(attr, prefix));
      }
    }
    return out;
  }
}

interface MiniDoc {
  nodeType: number;
  nodeName: string;
  documentElement: MiniEl;
  body: MiniEl;
  activeElement: MiniEl;
  defaultView: Record<string, unknown>;
  mockSampleColor: [number, number, number, number];
  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(sampleColor: [number, number, number, number] = [230, 90, 40, 255]) {
  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,
    Image: g.Image,
    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: 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>,
    mockSampleColor: sampleColor,
    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 MockImage {
    naturalWidth = 100;
    naturalHeight = 100;
    width = 100;
    height = 100;
    crossOrigin = '';
    onload: (() => void) | null = null;
    onerror: (() => void) | null = null;
    private _src = '';
    get src() {
      return this._src;
    }
    set src(val: string) {
      this._src = val;
      if (val && this.onload) this.onload();
    }
  }

  class MockIFrame extends MiniEl {}
  const rafMock = (cb: FrameRequestCallback) => {
    cb(16);
    return 1;
  };

  const mockWin: Record<string, unknown> = {
    innerWidth: 1440,
    innerHeight: 900,
    devicePixelRatio: 1,
    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: () => {},
  };
  mockDoc.defaultView = mockWin;

  g.window = mockWin;
  g.document = mockDoc;
  g.HTMLElement = MiniEl;
  g.Node = MiniEl;
  g.Element = MiniEl;
  g.Image = MockImage;
  g.requestAnimationFrame = rafMock;
  g.cancelAnimationFrame = () => {};

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

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

describe('Sub View 2.0 PureRef Board Engine & Study Filters', () => {
  it('round-trips board <-> stage and board <-> card local coordinates under rotation, zoom, pan, and flipX', () => {
    const transforms: SubViewTransform[] = [
      { zoom: 1, pan: { x: 0, y: 0 }, rotation: 0, flipX: false },
      { zoom: 1.75, pan: { x: 42, y: -28 }, rotation: 33, flipX: false },
      { zoom: 0.65, pan: { x: -18, y: 55 }, rotation: -72, flipX: true },
    ];

    for (const t of transforms) {
      const pt = { x: 37.5, y: -61.2 };
      const stagePt = boardPointToStagePoint(pt.x, pt.y, 320, 240, t);
      const back = stagePointToBoardPoint(stagePt.x, stagePt.y, 320, 240, t);
      expect(back.x).toBeCloseTo(pt.x, 4);
      expect(back.y).toBeCloseTo(pt.y, 4);
    }

    const card: BoardCardGeometry = {
      id: 'c1',
      width: 200,
      height: 100,
      boardX: 50,
      boardY: -30,
      boardScale: 1.5,
      boardRotation: 40,
      boardFlipX: true,
      boardFlipY: false,
      zIndex: 1,
    };
    const bPt = cardLocalToBoardPoint(25, -15, card);
    const backLocal = boardPointToCardLocal(bPt.x, bPt.y, card);
    expect(backLocal.x).toBeCloseTo(25, 4);
    expect(backLocal.y).toBeCloseTo(-15, 4);
  });

  it('hit-tests overlapping PureRef cards by highest zIndex and detects resize/rotate handles cleanly', () => {
    const boardTransform: SubViewTransform = {
      zoom: 1,
      pan: { x: 0, y: 0 },
      rotation: 0,
      flipX: false,
    };
    const cards: BoardCardGeometry[] = [
      {
        id: 'back',
        width: 100,
        height: 100,
        boardX: 0,
        boardY: 0,
        boardScale: 1,
        boardRotation: 0,
        boardFlipX: false,
        boardFlipY: false,
        zIndex: 1,
      },
      {
        id: 'front',
        width: 100,
        height: 100,
        boardX: 20,
        boardY: 0,
        boardScale: 1,
        boardRotation: 0,
        boardFlipX: false,
        boardFlipY: false,
        zIndex: 5,
      },
    ];

    // Overlap region at board (10, 0) -> stage (160, 100) for 300x200 stage
    const hitOverlap = hitTestBoardCards(160, 100, cards, 300, 200, boardTransform);
    expect(hitOverlap?.card.id).toBe('front');

    // Left-only region of back card at board (-40, 0) -> stage (110, 100)
    const hitBack = hitTestBoardCards(110, 100, cards, 300, 200, boardTransform);
    expect(hitBack?.card.id).toBe('back');

    // Handle hit-testing on front card
    const ov = getCardStageOverlay(cards[1], 300, 200, boardTransform);
    expect(hitTestCardHandle(ov.rotHandle.x, ov.rotHandle.y, cards[1], 300, 200, boardTransform)).toBe(
      'rotate'
    );
    expect(hitTestCardHandle(ov.br.x, ov.br.y, cards[1], 300, 200, boardTransform)).toBe('br');
    expect(
      hitTestCardHandle(ov.br.x, ov.br.y, { ...cards[1], locked: true }, 300, 200, boardTransform)
    ).toBeNull();
  });

  it('auto-arranges multiple cards in grid, row, and column layouts without overlapping and computes fit transform', () => {
    const items = [
      { id: 'a', width: 800, height: 600 },
      { id: 'b', width: 400, height: 800 },
      { id: 'c', width: 500, height: 500 },
      { id: 'd', width: 1000, height: 500 },
    ];

    for (const mode of ['grid', 'row', 'column'] as const) {
      const layout = computeBoardAutoLayout(items, mode, 12);
      expect(layout.size).toBe(4);
      const boxes = items.map((it) => {
        const p = layout.get(it.id)!;
        const hw = (it.width * p.boardScale) / 2;
        const hh = (it.height * p.boardScale) / 2;
        return { minX: p.boardX - hw, maxX: p.boardX + hw, minY: p.boardY - hh, maxY: p.boardY + hh };
      });
      // Verify zero pairwise overlap
      for (let i = 0; i < boxes.length; i++) {
        for (let j = i + 1; j < boxes.length; j++) {
          const a = boxes[i];
          const b = boxes[j];
          const overlapX = a.minX < b.maxX - 0.1 && a.maxX > b.minX + 0.1;
          const overlapY = a.minY < b.maxY - 0.1 && a.maxY > b.minY + 0.1;
          expect(overlapX && overlapY).toBe(false);
        }
      }
    }

    const fit = computeBoardFitTransform(
      [
        {
          id: 'a',
          width: 200,
          height: 100,
          boardX: 100,
          boardY: -50,
          boardScale: 1,
          boardRotation: 0,
          boardFlipX: false,
          boardFlipY: false,
          zIndex: 1,
        },
      ],
      300,
      200,
      20
    );
    const centerInStage = boardPointToStagePoint(100, -50, 300, 200, fit);
    expect(centerInStage.x).toBeCloseTo(150, 2);
    expect(centerInStage.y).toBeCloseTo(100, 2);
  });

  it('applies perceptual B/W grayscale and 2-value Notan / 3-value shape study posterization accurately', () => {
    // Pixels: dark blue (0,0,120), bright yellow (250,240,20), mid gray (128,128,128)
    const buf = new Uint8ClampedArray([
      0, 0, 120, 255,
      250, 240, 20, 255,
      128, 128, 128, 255,
    ]);
    const grayImg = { data: new Uint8ClampedArray(buf), width: 3, height: 1 };
    applyStudyFilterToImageData(grayImg, {
      grayscale: true,
      valueSteps: 0,
      notanThreshold: 128,
      brightness: 0,
      contrast: 0,
    });
    // Each pixel is neutral gray (R===G===B) and bright yellow is much brighter than dark blue
    expect(grayImg.data[0]).toBe(grayImg.data[1]);
    expect(grayImg.data[1]).toBe(grayImg.data[2]);
    expect(grayImg.data[4]).toBe(grayImg.data[5]);
    expect(grayImg.data[4]).toBeGreaterThan(grayImg.data[0] + 150);

    // 2-Value Notan study splits dark blue to black (16) and bright yellow to white (248)
    const notanImg = { data: new Uint8ClampedArray(buf), width: 3, height: 1 };
    applyStudyFilterToImageData(notanImg, {
      grayscale: true,
      valueSteps: 2,
      notanThreshold: 140,
      brightness: 0,
      contrast: 0,
    });
    expect(notanImg.data[0]).toBe(16);
    expect(notanImg.data[4]).toBe(248);
    expect(notanImg.data[8]).toBe(16);
  });

  it('extracts dominant distinct colors sorted by perceptual luminance', () => {
    const dom = installMiniDom([40, 120, 210, 255]);
    try {
      const fakeCanvas = dom.mockDoc.createElement('canvas') as unknown as HTMLCanvasElement;
      fakeCanvas.width = 20;
      fakeCanvas.height = 20;
      const swatches = extractDominantColorsFromCanvas(fakeCanvas, 5);
      expect(swatches.length).toBeGreaterThanOrEqual(1);
      expect(swatches[0].hex).toMatch(/^#[0-9a-f]{6}$/);
      expect(swatches[0].luminance).toBeGreaterThanOrEqual(0);
      expect(swatches[0].luminance).toBeLessThanOrEqual(100);
    } finally {
      dom.cleanup();
    }
  });
});

describe('SubViewPanel (References 2.0) PureRef UI, B/W Study Overlay & Persistence', () => {
  const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;

  beforeEach(() => {
    Object.defineProperty(globalThis, 'localStorage', {
      value: createMemoryStorage(),
      configurable: true,
      writable: true,
    });
    useSubViewStore.reset();
    useToolStore.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('defaults to PureRef Board mode, rotates & flips the board, and manipulates per-card B/W, flip, lock, duplicate, and arrange', () => {
    const dom = installMiniDom([230, 90, 40, 255]); // #e65a28
    let root: Root | null = null;

    try {
      subViewStoreActions.addImages([
        { id: 'ref-a', name: 'lighting_ref.png', src: 'data:image/png;base64,AAA', width: 200, height: 200 },
        { id: 'ref-b', name: 'pose_ref.png', src: 'data:image/png;base64,BBB', width: 200, height: 200 },
      ]);

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(<SubViewPanel colorMode="color" themePreset="modern" />);
      });

      const panel = dom.container.findByAttr('data-testid', 'sub-view-panel');
      expect(panel?.getAttribute('data-view-mode')).toBe('board');

      // Rotate & flip entire PureRef board viewport
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-rotate-right')!
          .dispatchEvent(new Event('click', { bubbles: true }));
        dom.container
          .findByAttr('data-testid', 'subview-flip-h')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useSubViewStore.getState().boardTransform.rotation).toBe(15);
      expect(useSubViewStore.getState().boardTransform.flipX).toBe(true);

      // Floating B/W study controls right on top of the reference
      expect(dom.container.findByAttr('data-testid', 'subview-study-overlay')).not.toBeNull();
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-bw-toggle')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useSubViewStore.getState().studyFilter.grayscale).toBe(true);

      // Cycle value study steps (2V Notan -> 3V -> 5V)
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-value-steps')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useSubViewStore.getState().studyFilter.valueSteps).toBe(2);

      // Toggle Squint Blur & Proportional Grid
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-squint-toggle')!
          .dispatchEvent(new Event('click', { bubbles: true }));
        dom.container
          .findByAttr('data-testid', 'subview-grid-toggle')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useSubViewStore.getState().studyFilter.squintBlur).toBe(true);
      expect(useSubViewStore.getState().studyFilter.gridMode).toBe('thirds');

      // Toggle Split Color | B/W compare curtain
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-split-bw-toggle')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useSubViewStore.getState().studyFilter.splitBw).toBe(true);
      expect(dom.container.findByAttr('data-testid', 'subview-split-handle')).not.toBeNull();

      // Turn split off to access per-card PureRef toolbar
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-split-bw-toggle')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });

      // Per-card B/W, Flip H, Lock, and Duplicate
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-card-bw-toggle')!
          .dispatchEvent(new Event('click', { bubbles: true }));
        dom.container
          .findByAttr('data-testid', 'subview-card-flip-h')!
          .dispatchEvent(new Event('click', { bubbles: true }));
        dom.container
          .findByAttr('data-testid', 'subview-card-lock')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      const cardB = useSubViewStore.getState().items.find((i) => i.id === 'ref-b')!;
      expect(cardB.grayscale).toBe(true);
      expect(cardB.boardFlipX).toBe(true);
      expect(cardB.locked).toBe(true);

      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-card-duplicate')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useSubViewStore.getState().items.length).toBe(3);

      // Auto-arrange menu -> Horizontal Strip
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-arrange-btn')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-arrange-row')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      const arrangedItems = useSubViewStore.getState().items;
      expect(arrangedItems.every((it) => it.boardY === 0)).toBe(true);

      // Dominant Color Palette strip picks primaryColor
      act(() => {
        dom.container
          .findByAttr('data-testid', 'subview-palette-toggle')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      const swatches = dom.container.findAllByAttrPrefix('data-testid', 'subview-palette-swatch-');
      expect(swatches.length).toBeGreaterThanOrEqual(1);
      act(() => {
        swatches[0].dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useToolStore.getState().primaryColor).toBe('#e65a28');

      // Reload persistence of v2 PureRef board state & study filter
      expect(localStorage.getItem(SUB_VIEW_STORAGE_KEY)).toBeTruthy();
      act(() => {
        useSubViewStore.reset();
      });
      expect(useSubViewStore.getState().items.length).toBe(3);
      expect(useSubViewStore.getState().viewMode).toBe('board');
      expect(useSubViewStore.getState().studyFilter.squintBlur).toBe(true);
      expect(useSubViewStore.getState().studyFilter.gridMode).toBe('thirds');
      expect(useSubViewStore.getState().items.find((i) => i.id === 'ref-b')?.grayscale).toBe(true);
    } finally {
      if (root) {
        act(() => {
          root?.unmount();
        });
      }
      dom.cleanup();
    }
  });
});