Skip to content

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

27.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 {
  applyPerceptualGrayscaleToImageData,
  clampNavigatorSplitRatio,
  computePerceptualLuminanceByte,
  DEFAULT_NAVIGATOR_SPLIT_RATIO,
  nextNavigatorPreviewMode,
} from '../valueCheck';
import { useDocumentStore, documentStoreActions } from '../../stores/useDocumentStore';
import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';
import { useToolStore } from '../../stores/useToolStore';
import { COMMAND_CATALOG } from '../../types/workspace';
import { DEFAULT_COMMANDS } from '../shortcutManager';
import {
  executeWorkspaceCommand,
  isCommandActive,
  isCommandDisabled,
  WorkspaceCommandHandlers,
} from '../../components/CommandBar';
import {
  NavigatorPanel,
  computeNavigatorSplitRatioFromClientX,
  computePreviewBoxMetrics,
} from '../../components/NavigatorPanel';
import { Header } from '../../components/Header';
import { StatusBar } from '../../components/StatusBar';
import { CameraSubscriber, CameraTransformState, CanvasNavigationHandle } from '../../hooks/useCanvasNavigation';
import { CanvasDimensions, LayerItem } from '../../types/editor';

const mockNativeNav = vi.hoisted(() => ({
  renderNativeNavigatorPreview: vi.fn(),
  strokeListeners: new Set<() => void>(),
}));

vi.mock('../nativeEngineBridge', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../nativeEngineBridge')>();
  return {
    ...actual,
    isNativeCanvasActive: () => true,
    renderNativeNavigatorPreview: (...args: unknown[]) =>
      mockNativeNav.renderNativeNavigatorPreview(...args),
    subscribeNativeStrokeCommitted: (cb: () => void) => {
      mockNativeNav.strokeListeners.add(cb);
      return () => {
        mockNativeNav.strokeListeners.delete(cb);
      };
    },
    subscribeNativeHistory: () => () => {},
    subscribeNativeThumbnails: () => () => {},
  };
});

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(fillColor: [number, number, number, number] = [255, 0, 0, 255]) {
  let storedData: Uint8ClampedArray | null = null;
  let storedW = 0;
  let storedH = 0;
  const drawImageCalls: unknown[][] = [];

  return {
    drawImageCalls,
    getStoredData: () => storedData,
    save: vi.fn(),
    restore: vi.fn(),
    setTransform: vi.fn(),
    clearRect: vi.fn(),
    fillRect: vi.fn(),
    strokeRect: vi.fn(),
    beginPath: 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((...args: unknown[]) => {
      drawImageCalls.push(args);
    }),
    createImageData: (w: number, h: number) => ({
      data: new Uint8ClampedArray(w * h * 4),
      width: w,
      height: h,
    }),
    putImageData: vi.fn((img: { data: Uint8ClampedArray; width: number; height: number }) => {
      storedData = new Uint8ClampedArray(img.data);
      storedW = img.width;
      storedH = img.height;
    }),
    getImageData: vi.fn((_x: number, _y: number, w: number, h: number) => {
      if (storedData && storedW === w && storedH === h) {
        return { data: new Uint8ClampedArray(storedData), width: w, height: h };
      }
      const data = new Uint8ClampedArray(w * h * 4);
      for (let i = 0; i < data.length; i += 4) {
        data[i] = fillColor[0];
        data[i + 1] = fillColor[1];
        data[i + 2] = fillColor[2];
        data[i + 3] = fillColor[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 = 200;
  height = 120;
  clientWidth = 200;
  clientHeight = 120;
  attrs = new Map<string, string>();
  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 || event.cancelBubble) break;
      cur = cur.parentNode;
    }
    return !event.defaultPrevented;
  }

  getContext(type: string) {
    if (type === '2d') {
      if (!this.mockCtx) this.mockCtx = createMock2DContext(this.ownerDocument.mockPixelColor);
      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;
  }
}

interface MiniDoc {
  nodeType: number;
  nodeName: string;
  documentElement: MiniEl;
  body: MiniEl;
  activeElement: MiniEl;
  defaultView: Record<string, unknown>;
  mockPixelColor: [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(pixelColor: [number, number, number, number] = [255, 0, 0, 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,
    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>,
    mockPixelColor: pixelColor,
    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 rafMock = (cb: FrameRequestCallback) => {
    cb(16);
    return 1;
  };
  const cancelRafMock = () => {};

  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: 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,
    mockDoc,
    cleanup: () => {
      for (const [k, v] of Object.entries(saved)) {
        if (v === undefined) delete g[k];
        else g[k] = v;
      }
    },
  };
}

function createMockNavigation(initial?: Partial<CameraTransformState>) {
  const subs = new Set<CameraSubscriber>();
  const panRef = { current: initial?.pan ? { ...initial.pan } : { x: 400, y: 300 } };
  const zoomRef = { current: initial?.zoom ?? 1 };
  const rotationRef = { current: initial?.rotation ?? 0 };
  const flipXRef = { current: initial?.flipX ?? false };
  const flipYRef = { current: initial?.flipY ?? false };

  const emit = () => {
    const cam: CameraTransformState = {
      pan: { ...panRef.current },
      zoom: zoomRef.current,
      rotation: rotationRef.current,
      flipX: flipXRef.current,
      flipY: flipYRef.current,
    };
    subs.forEach((fn) => fn(cam));
  };

  const setPanLive = vi.fn((next: { x: number; y: number }) => {
    panRef.current = { ...next };
    emit();
  });
  const setZoomLive = vi.fn((z: number) => {
    zoomRef.current = z;
    emit();
  });
  const rotateBy = vi.fn((delta: number) => {
    rotationRef.current += delta;
    emit();
  });
  const commitCameraState = vi.fn();

  const handle: CanvasNavigationHandle = {
    panRef,
    zoomRef,
    rotationRef,
    flipXRef,
    flipYRef,
    getCameraState: () => ({
      pan: { ...panRef.current },
      zoom: zoomRef.current,
      rotation: rotationRef.current,
      flipX: flipXRef.current,
      flipY: flipYRef.current,
    }),
    subscribeCamera: (fn) => {
      subs.add(fn);
      return () => subs.delete(fn);
    },
    setPanLive,
    setZoomLive,
    rotateBy,
    commitCameraState,
  };

  return { handle, setPanLive, setZoomLive, commitCameraState };
}

describe('Perceptual Value Check Luminance Math', () => {
  it('preserves neutral grays identically and ranks saturated primaries by true perceptual luminance', () => {
    for (const gray of [0, 32, 64, 128, 192, 255]) {
      expect(computePerceptualLuminanceByte(gray, gray, gray)).toBe(gray);
    }

    const blueVal = computePerceptualLuminanceByte(0, 0, 255);
    const redVal = computePerceptualLuminanceByte(255, 0, 0);
    const greenVal = computePerceptualLuminanceByte(0, 255, 0);
    const yellowVal = computePerceptualLuminanceByte(255, 255, 0);

    // True linear-light Rec.709 / CIE Y perceptual values:
    // Blue (~76) < Red (~127) < Green (~220) < Yellow (~247)
    expect(blueVal).toBeGreaterThanOrEqual(72);
    expect(blueVal).toBeLessThanOrEqual(80);
    expect(redVal).toBeGreaterThanOrEqual(124);
    expect(redVal).toBeLessThanOrEqual(131);
    expect(greenVal).toBeGreaterThanOrEqual(216);
    expect(greenVal).toBeLessThanOrEqual(224);
    expect(yellowVal).toBeGreaterThanOrEqual(243);
    expect(yellowVal).toBeLessThanOrEqual(250);
    expect(blueVal).toBeLessThan(redVal);
    expect(redVal).toBeLessThan(greenVal);
    expect(greenVal).toBeLessThan(yellowVal);
  });

  it('converts full and split-slice ImageData regions in-place while preserving transparency', () => {
    // 4x1 row of pure red pixels, except pixel 3 is transparent
    const img = {
      width: 4,
      height: 1,
      data: new Uint8ClampedArray([
        255, 0, 0, 255, // x=0 (left / Color)
        255, 0, 0, 255, // x=1 (left / Color)
        255, 0, 0, 255, // x=2 (right / B/W)
        255, 0, 0, 0,   // x=3 (transparent)
      ]),
    };

    applyPerceptualGrayscaleToImageData(img, 2, 4);

    // Left half [0..2) remains pure red
    expect(Array.from(img.data.slice(0, 8))).toEqual([255, 0, 0, 255, 255, 0, 0, 255]);

    // Right pixel x=2 converted to perceptual gray (~127), alpha preserved
    const expectedRedGray = computePerceptualLuminanceByte(255, 0, 0);
    expect(Array.from(img.data.slice(8, 12))).toEqual([
      expectedRedGray,
      expectedRedGray,
      expectedRedGray,
      255,
    ]);

    // Transparent pixel x=3 untouched
    expect(Array.from(img.data.slice(12, 16))).toEqual([255, 0, 0, 0]);
  });

  it('clamps Navigator split ratios and cycles preview modes deterministically', () => {
    expect(clampNavigatorSplitRatio(0.01)).toBe(0.05);
    expect(clampNavigatorSplitRatio(0.99)).toBe(0.95);
    expect(clampNavigatorSplitRatio(0.42)).toBe(0.42);
    expect(clampNavigatorSplitRatio(Number.NaN)).toBe(DEFAULT_NAVIGATOR_SPLIT_RATIO);

    expect(nextNavigatorPreviewMode('color')).toBe('bw');
    expect(nextNavigatorPreviewMode('bw')).toBe('split');
    expect(nextNavigatorPreviewMode('split')).toBe('color');
  });
});

describe('Value Check & Navigator Split View Store, Command Bar & Shortcuts', () => {
  const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;

  beforeEach(() => {
    Object.defineProperty(globalThis, 'localStorage', {
      value: createMemoryStorage(),
      configurable: true,
      writable: true,
    });
    useDocumentStore.reset();
    useWorkspaceStore.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('toggles main-canvas Value Check independently of CMYK soft proof and persists Navigator mode & split ratio', () => {
    expect(useDocumentStore.getState().valueCheckEnabled).toBe(false);
    expect(documentStoreActions.toggleValueCheck()).toBe(true);
    expect(useDocumentStore.getState().valueCheckEnabled).toBe(true);
    expect(useDocumentStore.getState().softProofSettings.enabled).toBe(false);

    workspaceStoreActions.setNavigatorPreviewMode('bw');
    workspaceStoreActions.setNavigatorSplitRatio(0.35, true);
    expect(useWorkspaceStore.getState().navigatorPreviewMode).toBe('bw');
    expect(useWorkspaceStore.getState().navigatorSplitRatio).toBe(0.35);

    // Survives reload via persisted workspace state
    useWorkspaceStore.reset();
    expect(useWorkspaceStore.getState().navigatorPreviewMode).toBe('bw');
    expect(useWorkspaceStore.getState().navigatorSplitRatio).toBe(0.35);

    expect(workspaceStoreActions.cycleNavigatorPreviewMode()).toBe('split');
    expect(workspaceStoreActions.cycleNavigatorPreviewMode()).toBe('color');
  });

  it('exposes value-check in COMMAND_CATALOG and registers conflict-free default shortcuts', () => {
    const entry = COMMAND_CATALOG.find((c) => c.id === 'value-check');
    expect(entry).toBeDefined();
    expect(entry?.shortcut).toBe('Shift+Y');

    const onToggleValueCheck = vi.fn();
    const handlers: WorkspaceCommandHandlers = {
      canUndo: false,
      canRedo: false,
      onUndo: vi.fn(),
      onRedo: vi.fn(),
      onToggleValueCheck,
      valueCheckEnabled: true,
      hasOpenDocument: true,
    };

    expect(isCommandDisabled('value-check', handlers)).toBe(false);
    expect(isCommandDisabled('value-check', { ...handlers, hasOpenDocument: false })).toBe(true);
    expect(isCommandActive('value-check', handlers, false)).toBe(true);
    executeWorkspaceCommand('value-check', handlers);
    expect(onToggleValueCheck).toHaveBeenCalledTimes(1);

    const valueCmd = DEFAULT_COMMANDS.find((c) => c.id === 'view.valueCheck');
    const navModeCmd = DEFAULT_COMMANDS.find((c) => c.id === 'view.navigatorValueMode');
    expect(valueCmd?.defaultShortcut).toBe('Shift+Y');
    expect(navModeCmd?.defaultShortcut).toBe('Alt+Shift+Y');

    // Verify zero duplicate default shortcuts across all registered commands
    const seen = new Map<string, string>();
    for (const cmd of DEFAULT_COMMANDS) {
      if (!cmd.defaultShortcut) continue;
      const key = cmd.defaultShortcut.toLowerCase();
      expect(seen.has(key), `Duplicate shortcut ${cmd.defaultShortcut} (${seen.get(key)} vs ${cmd.id})`).toBe(false);
      seen.set(key, cmd.id);
    }
  });
});

describe('Navigator Live B/W Mode, Interactive Split View & Header/StatusBar 1-Click Value Check UI', () => {
  const prevStorage = (globalThis as unknown as Record<string, unknown>).localStorage;

  beforeEach(() => {
    Object.defineProperty(globalThis, 'localStorage', {
      value: createMemoryStorage(),
      configurable: true,
      writable: true,
    });
    useDocumentStore.reset();
    useWorkspaceStore.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('switches Navigator between Color, Live B/W, and draggable Split View without re-compositing tiles or panning canvas', () => {
    vi.useFakeTimers();
    const dom = installMiniDom([255, 0, 0, 255]);
    let root: Root | null = null;
    mockNativeNav.strokeListeners.clear();
    mockNativeNav.renderNativeNavigatorPreview.mockReset();
    mockNativeNav.renderNativeNavigatorPreview.mockResolvedValue({
      width: 64,
      height: 51,
      rgba: new Uint8ClampedArray(64 * 51 * 4),
    });

    try {
      const nav = createMockNavigation();
      const viewportRef = { current: { clientWidth: 800, clientHeight: 600 } as HTMLDivElement };
      const dims: CanvasDimensions = { width: 1000, height: 800, dpi: 300 };
      const layers: LayerItem[] = [
        {
          id: 'layer-1',
          name: 'Color',
          type: 'raster',
          visible: true,
          opacity: 1,
          blendMode: 'normal',
          locked: false,
          alphaLocked: false,
          clipped: false,
          parentId: null,
        },
      ];

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(
          <NavigatorPanel
            viewportRef={viewportRef}
            navigation={nav.handle}
            dimensions={dims}
            layers={layers}
            showCheckerboard={false}
            zoom={1}
            rotation={0}
            flipX={false}
            flipY={false}
            activeLayerId="layer-1"
            onZoomIn={vi.fn()}
            onZoomOut={vi.fn()}
            onFitToScreen={vi.fn()}
            onZoomActualSize={vi.fn()}
            onRotateLeft={vi.fn()}
            onRotateRight={vi.fn()}
            onResetRotation={vi.fn()}
            onToggleFlipHorizontal={vi.fn()}
            onToggleFlipVertical={vi.fn()}
            throttleMs={120}
          />
        );
      });

      expect(mockNativeNav.renderNativeNavigatorPreview).toHaveBeenCalledTimes(1);
      expect(dom.container.findByAttr('data-testid', 'nav-bw-badge')).toBeNull();
      expect(dom.container.findByAttr('data-testid', 'nav-split-handle')).toBeNull();

      // 1. Switch Navigator to Live B/W mode -> main canvas stays in Color, Navigator shows B/W badge, 0 extra tile composites
      act(() => {
        dom.container
          .findByAttr('data-testid', 'nav-mode-bw')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useWorkspaceStore.getState().navigatorPreviewMode).toBe('bw');
      expect(useDocumentStore.getState().valueCheckEnabled).toBe(false);
      expect(dom.container.findByAttr('data-testid', 'nav-bw-badge')).not.toBeNull();
      expect(mockNativeNav.renderNativeNavigatorPreview).toHaveBeenCalledTimes(1);

      // 2. Native Rust stroke commit triggers throttled real-time Navigator refresh!
      act(() => {
        mockNativeNav.strokeListeners.forEach((fn) => fn());
        vi.advanceTimersByTime(150);
      });
      expect(mockNativeNav.renderNativeNavigatorPreview).toHaveBeenCalledTimes(2);

      // 3. Switch Navigator to Split View -> shows draggable handle & CLR / B/W labels
      act(() => {
        dom.container
          .findByAttr('data-testid', 'nav-mode-split')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useWorkspaceStore.getState().navigatorPreviewMode).toBe('split');
      const handle = dom.container.findByAttr('data-testid', 'nav-split-handle');
      expect(handle).not.toBeNull();
      expect(dom.container.findByAttr('data-testid', 'nav-split-color-label')).not.toBeNull();
      expect(dom.container.findByAttr('data-testid', 'nav-split-bw-label')).not.toBeNull();

      // Drag split handle to ~25% across preview box -> updates splitRatio WITHOUT panning main canvas
      const m = computePreviewBoxMetrics(200, 120, dims);
      const dragClientX = m.offsetX + m.drawW * 0.25;
      expect(computeNavigatorSplitRatioFromClientX(dragClientX, 0, m)).toBeCloseTo(0.25, 2);

      act(() => {
        handle!.dispatchEvent(
          Object.assign(new Event('pointerdown', { bubbles: true }), {
            button: 0,
            pointerId: 7,
            clientX: dragClientX,
            clientY: 60,
          })
        );
        handle!.dispatchEvent(
          Object.assign(new Event('pointermove', { bubbles: true }), {
            button: 0,
            pointerId: 7,
            clientX: m.offsetX + m.drawW * 0.72,
            clientY: 60,
          })
        );
        handle!.dispatchEvent(
          Object.assign(new Event('pointerup', { bubbles: true }), {
            button: 0,
            pointerId: 7,
            clientX: m.offsetX + m.drawW * 0.72,
            clientY: 60,
          })
        );
      });
      expect(useWorkspaceStore.getState().navigatorSplitRatio).toBeCloseTo(0.72, 2);
      expect(nav.setPanLive).not.toHaveBeenCalled();

      // Double-click split handle resets cleanly to 0.5
      act(() => {
        handle!.dispatchEvent(new Event('dblclick', { bubbles: true }));
      });
      expect(useWorkspaceStore.getState().navigatorSplitRatio).toBe(0.5);

      // 4. 1-Click Value Check button inside Navigator toggles main canvas Value Check & displays Canvas B/W badge
      act(() => {
        dom.container
          .findByAttr('data-testid', 'nav-value-check')!
          .dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(useDocumentStore.getState().valueCheckEnabled).toBe(true);
      expect(dom.container.findByAttr('data-testid', 'nav-canvas-value-badge')).not.toBeNull();
    } finally {
      if (root) {
        act(() => {
          root?.unmount();
        });
      }
      dom.cleanup();
      vi.useRealTimers();
    }
  });

  it('renders 1-Click Value Check controls and active badges in Header and StatusBar', () => {
    const dom = installMiniDom();
    let root: Root | null = null;
    const onToggleValueCheck = vi.fn();

    try {
      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(
          <div>
            <Header
              canUndo={false}
              canRedo={false}
              onUndo={vi.fn()}
              onRedo={vi.fn()}
              zoom={1}
              onZoomIn={vi.fn()}
              onZoomOut={vi.fn()}
              onResetZoom={vi.fn()}
              rotation={0}
              onResetRotation={vi.fn()}
              hasOpenDocument={true}
              valueCheckEnabled={true}
              onToggleValueCheck={onToggleValueCheck}
            />
            <StatusBar
              tool="brush"
              brushSettings={useToolStore.getState().brushSettings}
              zoom={1}
              rotation={0}
              onResetRotation={vi.fn()}
              hasOpenDocument={true}
              valueCheckEnabled={true}
              onToggleValueCheck={onToggleValueCheck}
            />
          </div>
        );
      });

      const headerBtn = dom.container.findByAttr('data-testid', 'header-value-check-btn');
      const headerBadge = dom.container.findByAttr('data-testid', 'header-value-check-badge');
      const statusBadge = dom.container.findByAttr('data-testid', 'status-value-check-badge');

      expect(headerBtn).not.toBeNull();
      expect(headerBtn!.getAttribute('aria-pressed')).toBe('true');
      expect(headerBadge).not.toBeNull();
      expect(statusBadge).not.toBeNull();
      expect(statusBadge!.textContent).toContain('Value Check: B/W');

      act(() => {
        headerBtn!.dispatchEvent(new Event('click', { bubbles: true }));
        headerBadge!.dispatchEvent(new Event('click', { bubbles: true }));
        statusBadge!.dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(onToggleValueCheck).toHaveBeenCalledTimes(3);
    } finally {
      if (root) {
        act(() => {
          root?.unmount();
        });
      }
      dom.cleanup();
    }
  });
});