Skip to content

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

33.8 KB
Raw Blame
import React, { Profiler, act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
  HairlineTabs,
  IconButton,
  PrecisionNumberInput,
  ScrubSlider,
  SectionDisclosure,
  SegmentedControl,
  ToggleSwitch,
  type ScrubSliderHandle,
} from '../index';
import { toolStoreActions, uiStoreActions, useUiStore } from '../../../stores';

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 MiniStyle {
  private map = new Map<string, string>();
  [key: string]: unknown;

  setProperty(k: string, v: string) {
    this.map.set(k, String(v));
    this[k] = String(v);
  }

  getPropertyValue(k: string): string {
    return this.map.get(k) ?? (typeof this[k] === 'string' ? (this[k] as string) : '');
  }

  removeProperty(k: string) {
    this.map.delete(k);
    delete this[k];
  }
}

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 = new MiniStyle();
  className = '';
  disabled = false;
  type = '';
  oninput: ((ev: Event) => void) | null = null;
  onchange: ((ev: Event) => void) | null = null;
  clientWidth = 200;
  clientHeight = 26;
  attrs = new Map<string, string>();
  private _value = '';
  private legacyListeners = new Map<string, Set<(ev: unknown) => void>>();
  capturedPointers = new Set<number>();
  setPointerCaptureCalls: number[] = [];
  releasePointerCaptureCalls: number[] = [];

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

  get value(): string {
    return this._value;
  }

  set value(v: string) {
    this._value = String(v);
  }

  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(pointerId: number) {
    this.setPointerCaptureCalls.push(pointerId);
    this.capturedPointers.add(pointerId);
  }

  hasPointerCapture(pointerId: number): boolean {
    return this.capturedPointers.has(pointerId);
  }

  releasePointerCapture(pointerId: number) {
    this.releasePointerCaptureCalls.push(pointerId);
    this.capturedPointers.delete(pointerId);
  }

  focus() {
    this.ownerDocument.activeElement = this;
    this.dispatchEvent(new Event('focus', { bubbles: false }));
    this.dispatchEvent(new Event('focusin', { bubbles: true }));
  }

  blur() {
    if (this.ownerDocument.activeElement === this) {
      this.ownerDocument.activeElement = this.ownerDocument.body;
    }
    this.dispatchEvent(new Event('blur', { bubbles: false }));
    this.dispatchEvent(new Event('focusout', { bubbles: true }));
  }

  select() {}

  attachEvent(eventName: string, listener: (ev: unknown) => void) {
    let set = this.legacyListeners.get(eventName);
    if (!set) {
      set = new Set();
      this.legacyListeners.set(eventName, set);
    }
    set.add(listener);
  }

  detachEvent(eventName: string, listener: (ev: unknown) => void) {
    this.legacyListeners.get(eventName)?.delete(listener);
  }

  fireLegacyPropertyChange(propertyName: string) {
    const set = this.legacyListeners.get('onpropertychange');
    if (!set) return;
    const ev = {
      type: 'propertychange',
      propertyName,
      target: this,
      srcElement: this,
    };
    set.forEach((fn) => fn(ev));
  }

  matchesSimpleSelector(sel: string): boolean {
    const trimmed = sel.trim();
    if (!trimmed) return false;
    if (trimmed.startsWith('[')) {
      const m = trimmed.match(/^\[([^=\]]+)(?:=["']?([^"'\]]*)["']?)?\]$/);
      if (!m) return false;
      const attrVal = this.getAttribute(m[1]);
      if (m[2] === undefined) return attrVal !== null;
      return attrVal === m[2];
    }
    return this.tagName === trimmed.toUpperCase();
  }

  closest(selectorList: string): MiniEl | null {
    const selectors = selectorList.split(',').map((s) => s.trim());
    let cur: MiniEl | null = this;
    while (cur) {
      if (selectors.some((sel) => cur!.matchesSimpleSelector(sel))) {
        return cur;
      }
      cur = cur.parentNode;
    }
    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));
    if (k === 'type') this.type = String(v);
    if (k === 'value') this._value = String(v);
    if (k === 'disabled') this.disabled = true;
  }

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

  removeAttribute(k: string) {
    this.attrs.delete(k);
    if (k === 'disabled') this.disabled = false;
  }

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

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

  findAll(pred: (el: MiniEl) => boolean): MiniEl[] {
    const out: MiniEl[] = [];
    const walk = (node: MiniEl | MiniText | MiniComment) => {
      if (node instanceof MiniEl) {
        if (pred(node)) out.push(node);
        for (const child of node.childNodes) walk(child);
      }
    };
    walk(this);
    return out;
  }

  findByAttr(attr: string, value: string): MiniEl | null {
    return this.findAll((el) => el.getAttribute(attr) === value)[0] ?? null;
  }
}

interface MiniDoc {
  nodeType: number;
  nodeName: string;
  documentElement: MiniEl;
  body: MiniEl;
  activeElement: MiniEl;
  defaultView: Record<string, unknown>;
  oninput: ((ev: Event) => void) | null;
  onchange: ((ev: Event) => void) | null;
  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,
    HTMLInputElement: g.HTMLInputElement,
    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>,
    oninput: null,
    onchange: null,
    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,
    devicePixelRatio: 1,
    document: mockDoc,
    Node: MiniEl,
    Element: MiniEl,
    HTMLElement: MiniEl,
    HTMLInputElement: MiniEl,
    SVGElement: MiniEl,
    HTMLIFrameElement: MockIFrame,
    Event,
    CustomEvent,
    getSelection: () => ({
      anchorNode: null,
      anchorOffset: 0,
      focusNode: null,
      focusOffset: 0,
    }),
    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.HTMLInputElement = MiniEl;
  g.Node = MiniEl;
  g.Element = MiniEl;

  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 firePointer(
  el: MiniEl,
  type: 'pointerdown' | 'pointermove' | 'pointerup' | 'pointercancel',
  init: {
    clientX: number;
    clientY?: number;
    pointerId?: number;
    button?: number;
    shiftKey?: boolean;
    altKey?: boolean;
  }
) {
  const ev = Object.assign(new Event(type, { bubbles: true, cancelable: true }), {
    button: init.button ?? 0,
    pointerId: init.pointerId ?? 1,
    clientX: init.clientX,
    clientY: init.clientY ?? 12,
    shiftKey: Boolean(init.shiftKey),
    altKey: Boolean(init.altKey),
  });
  el.dispatchEvent(ev);
}

function fireKey(
  el: MiniEl,
  key: string,
  opts: { shiftKey?: boolean } = {}
) {
  const ev = Object.assign(new Event('keydown', { bubbles: true, cancelable: true }), {
    key,
    shiftKey: Boolean(opts.shiftKey),
  });
  el.dispatchEvent(ev);
}

function setInputText(inputEl: MiniEl, nextValue: string) {
  const nativeSetter = Object.getOwnPropertyDescriptor(MiniEl.prototype, 'value')?.set;
  nativeSetter?.call(inputEl, nextValue);
  inputEl.fireLegacyPropertyChange('value');
  inputEl.dispatchEvent(new Event('input', { bubbles: true }));
}

describe('Pro Controls Library (src/components/ui/)', () => {
  let dom: ReturnType<typeof installMiniDom>;
  let root: Root | null = null;

  beforeEach(() => {
    dom = installMiniDom();
    useUiStore.reset();
    uiStoreActions.updateAppearance({ sliderStyle: 'scrubber' });
  });

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

  describe('ScrubSlider', () => {
    it('supports pointer-capture drag, Shift 0.1x fine precision, and onCommit on pointerup', () => {
      const onChange = vi.fn();
      const onCommit = vi.fn();

      const Harness: React.FC = () => {
        const [val, setVal] = React.useState(50);
        return (
          <ScrubSlider
            data-testid="opacity-slider"
            label="Opacity"
            variant="opacity"
            min={0}
            max={100}
            step={1}
            defaultValue={100}
            unit="%"
            value={val}
            onChange={(next) => {
              onChange(next);
              setVal(next);
            }}
            onCommit={onCommit}
          />
        );
      };

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(<Harness />);
      });

      const slider = dom.container.findByAttr('data-testid', 'opacity-slider')!;
      expect(slider).not.toBeNull();
      expect(slider.getAttribute('role')).toBe('slider');
      expect(slider.getAttribute('data-slider-mode')).toBe('scrubber');
      expect(slider.getAttribute('data-variant')).toBe('opacity');
      expect(slider.getAttribute('aria-valuenow')).toBe('50');

      // Normal pointer drag across 200px width: 100px -> 150px (+25% => 75)
      act(() => {
        firePointer(slider, 'pointerdown', { clientX: 100, pointerId: 9 });
        firePointer(slider, 'pointermove', { clientX: 150, pointerId: 9 });
        firePointer(slider, 'pointerup', { clientX: 150, pointerId: 9 });
      });

      expect(slider.setPointerCaptureCalls).toEqual([9]);
      expect(slider.releasePointerCaptureCalls).toEqual([9]);
      expect(onChange).toHaveBeenLastCalledWith(75);
      expect(onCommit).toHaveBeenLastCalledWith(75);
      expect(slider.getAttribute('aria-valuenow')).toBe('75');

      // Shift fine drag: +40px across 200px width at 0.1x => +2% (75 -> 77 instead of 95)
      onChange.mockClear();
      onCommit.mockClear();
      act(() => {
        firePointer(slider, 'pointerdown', { clientX: 150, pointerId: 10, shiftKey: true });
        firePointer(slider, 'pointermove', { clientX: 190, pointerId: 10, shiftKey: true });
        firePointer(slider, 'pointerup', { clientX: 190, pointerId: 10, shiftKey: true });
      });

      expect(onChange).toHaveBeenLastCalledWith(77);
      expect(onCommit).toHaveBeenLastCalledWith(77);

      // Drag past bounds clamps cleanly to max (100)
      act(() => {
        firePointer(slider, 'pointerdown', { clientX: 180, pointerId: 11 });
        firePointer(slider, 'pointermove', { clientX: 340, pointerId: 11 });
        firePointer(slider, 'pointerup', { clientX: 340, pointerId: 11 });
      });
      expect(onChange).toHaveBeenLastCalledWith(100);
      expect(onCommit).toHaveBeenLastCalledWith(100);
    });

    it('resets to defaultValue on double-click and Alt+click', () => {
      const onChange = vi.fn();
      const onCommit = vi.fn();

      const Harness: React.FC = () => {
        const [val, setVal] = React.useState(35);
        return (
          <ScrubSlider
            data-testid="size-slider"
            label="Size"
            variant="size"
            min={1}
            max={200}
            step={1}
            defaultValue={12}
            unit="px"
            value={val}
            onChange={(next) => {
              onChange(next);
              setVal(next);
            }}
            onCommit={onCommit}
          />
        );
      };

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(<Harness />);
      });

      const slider = dom.container.findByAttr('data-testid', 'size-slider')!;

      // Double-click resets to 12
      act(() => {
        slider.dispatchEvent(new Event('dblclick', { bubbles: true, cancelable: true }));
      });
      expect(onChange).toHaveBeenLastCalledWith(12);
      expect(onCommit).toHaveBeenLastCalledWith(12);
      expect(slider.getAttribute('aria-valuenow')).toBe('12');

      // Drag away to 100, then Alt+click resets back to 12
      act(() => {
        firePointer(slider, 'pointerdown', { clientX: 100, pointerId: 2 });
        firePointer(slider, 'pointerup', { clientX: 100, pointerId: 2 });
      });
      expect(Number(slider.getAttribute('aria-valuenow'))).toBeGreaterThan(50);

      onChange.mockClear();
      onCommit.mockClear();
      act(() => {
        firePointer(slider, 'pointerdown', { clientX: 100, pointerId: 3, altKey: true });
      });
      expect(onChange).toHaveBeenCalledWith(12);
      expect(onCommit).toHaveBeenCalledWith(12);
    });

    it('supports inline numeric editing with Enter commit (clamped) and Escape cancel', () => {
      const onChange = vi.fn();
      const onCommit = vi.fn();

      const Harness: React.FC = () => {
        const [val, setVal] = React.useState(40);
        return (
          <ScrubSlider
            data-testid="inline-slider"
            label="Hardness"
            min={5}
            max={100}
            step={1}
            unit="%"
            value={val}
            onChange={(next) => {
              onChange(next);
              setVal(next);
            }}
            onCommit={onCommit}
          />
        );
      };

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(<Harness />);
      });

      const slider = dom.container.findByAttr('data-testid', 'inline-slider')!;
      const readout = slider.findByAttr('data-scrub-readout', 'true')!;
      expect(readout.textContent).toBe('40%');

      // Click numeric readout -> enters edit mode
      act(() => {
        readout.dispatchEvent(new Event('click', { bubbles: true }));
      });

      let input = slider.findByAttr('data-scrub-input', 'true')!;
      expect(input).not.toBeNull();
      expect(input.value).toBe('40');

      // Type "82" and press Enter -> commits 82
      act(() => {
        setInputText(input, '82');
      });
      act(() => {
        fireKey(input, 'Enter');
      });
      expect(onChange).toHaveBeenLastCalledWith(82);
      expect(onCommit).toHaveBeenLastCalledWith(82);
      expect(slider.findByAttr('data-scrub-input', 'true')).toBeNull();
      expect(slider.findByAttr('data-scrub-readout', 'true')?.textContent).toBe('82%');

      // Enter edit mode again, type "999" and press Escape -> cancels without firing onChange
      onChange.mockClear();
      onCommit.mockClear();
      act(() => {
        slider.findByAttr('data-scrub-readout', 'true')!.dispatchEvent(new Event('click', { bubbles: true }));
      });
      input = slider.findByAttr('data-scrub-input', 'true')!;
      act(() => {
        setInputText(input, '999');
      });
      act(() => {
        fireKey(input, 'Escape');
      });
      expect(onChange).not.toHaveBeenCalled();
      expect(onCommit).not.toHaveBeenCalled();
      expect(slider.findByAttr('data-scrub-readout', 'true')?.textContent).toBe('82%');

      // Enter edit mode and type out-of-range "250" -> clamps to max (100)
      act(() => {
        slider.findByAttr('data-scrub-readout', 'true')!.dispatchEvent(new Event('click', { bubbles: true }));
      });
      input = slider.findByAttr('data-scrub-input', 'true')!;
      act(() => {
        setInputText(input, '250');
      });
      act(() => {
        fireKey(input, 'Enter');
      });
      expect(onChange).toHaveBeenLastCalledWith(100);
    });

    it('supports full keyboard navigation (ArrowLeft/Right, PageUp/Down, Home/End)', () => {
      const onChange = vi.fn();

      const Harness: React.FC = () => {
        const [val, setVal] = React.useState(50);
        return (
          <ScrubSlider
            data-testid="kbd-slider"
            label="Flow"
            min={0}
            max={100}
            step={1}
            value={val}
            onChange={(next) => {
              onChange(next);
              setVal(next);
            }}
          />
        );
      };

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(<Harness />);
      });

      const slider = dom.container.findByAttr('data-testid', 'kbd-slider')!;

      act(() => fireKey(slider, 'ArrowRight'));
      expect(onChange).toHaveBeenLastCalledWith(51);

      act(() => fireKey(slider, 'ArrowLeft'));
      expect(onChange).toHaveBeenLastCalledWith(50);

      act(() => fireKey(slider, 'PageUp'));
      expect(onChange).toHaveBeenLastCalledWith(60);

      act(() => fireKey(slider, 'PageDown'));
      expect(onChange).toHaveBeenLastCalledWith(50);

      act(() => fireKey(slider, 'Home'));
      expect(onChange).toHaveBeenLastCalledWith(0);

      act(() => fireKey(slider, 'End'));
      expect(onChange).toHaveBeenLastCalledWith(100);
    });

    it('renders both scrubber and track modes (via global store and per-instance override) and supports logarithmic & zero-rerender liveRef sync', () => {
      const liveRef = React.createRef<ScrubSliderHandle>();
      const onChange = vi.fn();

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(
          <div>
            <ScrubSlider
              data-testid="global-mode-slider"
              label="Zoom"
              min={1}
              max={3200}
              step={1}
              unit="%"
              logarithmic
              value={100}
              liveRef={liveRef}
              onChange={onChange}
            />
            <ScrubSlider
              data-testid="override-track-slider"
              label="Override"
              sliderStyle="track"
              min={0}
              max={100}
              value={50}
              onChange={onChange}
            />
          </div>
        );
      });

      const globalSlider = dom.container.findByAttr('data-testid', 'global-mode-slider')!;
      const overrideSlider = dom.container.findByAttr('data-testid', 'override-track-slider')!;

      expect(globalSlider.getAttribute('data-slider-mode')).toBe('scrubber');
      expect(overrideSlider.getAttribute('data-slider-mode')).toBe('track');

      // Live zero-rerender DOM sync via imperative handle
      liveRef.current?.setLiveValue(400);
      expect(globalSlider.getAttribute('aria-valuenow')).toBe('400');
      expect(globalSlider.findByAttr('data-scrub-readout', 'true')?.textContent).toBe('400%');

      // Switching global appearance sliderStyle to 'track' updates globalSlider live
      act(() => {
        uiStoreActions.updateAppearance({ sliderStyle: 'track' });
      });

      const updatedGlobal = dom.container.findByAttr('data-testid', 'global-mode-slider')!;
      expect(updatedGlobal.getAttribute('data-slider-mode')).toBe('track');

      // Keyboard and drag still work identically in track mode
      act(() => fireKey(updatedGlobal, 'Home'));
      expect(onChange).toHaveBeenLastCalledWith(1);

      // Track mode supports pointer drag, Shift fine drag, double-click reset, and inline edit
      const trackChange = vi.fn();
      const trackCommit = vi.fn();
      const TrackHarness: React.FC = () => {
        const [v, setV] = React.useState(50);
        return (
          <ScrubSlider
            data-testid="track-mode-full"
            sliderStyle="track"
            label="Opacity"
            variant="opacity"
            min={0}
            max={100}
            step={1}
            defaultValue={80}
            unit="%"
            value={v}
            onChange={(n) => {
              trackChange(n);
              setV(n);
            }}
            onCommit={trackCommit}
          />
        );
      };

      act(() => {
        root?.render(<TrackHarness />);
      });

      const trackSlider = dom.container.findByAttr('data-testid', 'track-mode-full')!;
      expect(trackSlider.getAttribute('data-slider-mode')).toBe('track');
      act(() => {
        firePointer(trackSlider, 'pointerdown', { clientX: 100, pointerId: 21 });
        firePointer(trackSlider, 'pointermove', { clientX: 140, pointerId: 21 });
        firePointer(trackSlider, 'pointerup', { clientX: 140, pointerId: 21 });
      });
      expect(trackChange).toHaveBeenLastCalledWith(70);
      expect(trackCommit).toHaveBeenLastCalledWith(70);

      // Double-click reset in track mode
      act(() => {
        trackSlider.dispatchEvent(new Event('dblclick', { bubbles: true, cancelable: true }));
      });
      expect(trackChange).toHaveBeenLastCalledWith(80);

      // Inline numeric edit in track mode
      const trackReadout = trackSlider.findByAttr('data-scrub-readout', 'true')!;
      act(() => {
        trackReadout.dispatchEvent(new Event('click', { bubbles: true }));
      });
      const trackInput = trackSlider.findByAttr('data-scrub-input', 'true')!;
      act(() => {
        setInputText(trackInput, '33');
      });
      act(() => {
        fireKey(trackInput, 'Enter');
      });
      expect(trackChange).toHaveBeenLastCalledWith(33);
    });

    it('triggers zero unwanted re-renders when unrelated UI or tool store slices change', () => {
      let renderCount = 0;
      const noop = () => {};

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(
          <Profiler
            id="ScrubSliderIsolation"
            onRender={() => {
              renderCount += 1;
            }}
          >
            <ScrubSlider
              data-testid="isolated-slider"
              label="Opacity"
              min={0}
              max={100}
              value={100}
              onChange={noop}
            />
          </Profiler>
        );
      });

      expect(renderCount).toBe(1);

      act(() => {
        toolStoreActions.updateBrushSettings({ size: 64 });
        toolStoreActions.setPrimaryColor('#ff0044');
        uiStoreActions.setLeftPanelWidth(140);
        uiStoreActions.showToast('Saved');
      });

      expect(renderCount).toBe(1);
    });
  });

  describe('SegmentedControl', () => {
    it('selects options via click and keyboard arrows while respecting disabled options', () => {
      const onChange = vi.fn();

      const Harness: React.FC = () => {
        const [mode, setMode] = React.useState<'color' | 'split' | 'bw'>('color');
        return (
          <SegmentedControl<'color' | 'split' | 'bw'>
            data-testid="mode-seg"
            aria-label="Preview Mode"
            value={mode}
            onChange={(next) => {
              onChange(next);
              setMode(next);
            }}
            options={[
              { value: 'color', label: 'Color', 'data-testid': 'opt-color' },
              { value: 'split', label: 'Split', 'data-testid': 'opt-split' },
              { value: 'bw', label: 'B/W', 'data-testid': 'opt-bw' },
            ]}
          />
        );
      };

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(<Harness />);
      });

      const group = dom.container.findByAttr('data-testid', 'mode-seg')!;
      const colorBtn = dom.container.findByAttr('data-testid', 'opt-color')!;
      const splitBtn = dom.container.findByAttr('data-testid', 'opt-split')!;
      const bwBtn = dom.container.findByAttr('data-testid', 'opt-bw')!;

      expect(group.getAttribute('role')).toBe('radiogroup');
      expect(colorBtn.getAttribute('aria-checked')).toBe('true');
      expect(splitBtn.getAttribute('aria-checked')).toBe('false');

      // Click Split
      act(() => {
        splitBtn.dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(onChange).toHaveBeenLastCalledWith('split');
      expect(splitBtn.getAttribute('aria-checked')).toBe('true');

      // ArrowRight cycles to B/W
      act(() => fireKey(group, 'ArrowRight'));
      expect(onChange).toHaveBeenLastCalledWith('bw');
      expect(bwBtn.getAttribute('aria-checked')).toBe('true');

      // Home returns to Color
      act(() => fireKey(group, 'Home'));
      expect(onChange).toHaveBeenLastCalledWith('color');
    });
  });

  describe('ToggleSwitch', () => {
    it('toggles boolean state with switch semantics and blocks changes when disabled', () => {
      const onChange = vi.fn();

      const Harness: React.FC<{ disabled?: boolean }> = ({ disabled = false }) => {
        const [checked, setChecked] = React.useState(false);
        return (
          <ToggleSwitch
            data-testid="aa-toggle"
            label="Anti-Alias"
            description="Smooth brush edges"
            checked={checked}
            disabled={disabled}
            onChange={(next) => {
              onChange(next);
              setChecked(next);
            }}
          />
        );
      };

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(<Harness />);
      });

      const toggle = dom.container.findByAttr('data-testid', 'aa-toggle')!;
      expect(toggle.getAttribute('role')).toBe('switch');
      expect(toggle.getAttribute('aria-checked')).toBe('false');
      expect(toggle.textContent).toContain('Anti-Alias');
      expect(toggle.textContent).toContain('Smooth brush edges');

      act(() => {
        toggle.dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(onChange).toHaveBeenLastCalledWith(true);
      expect(toggle.getAttribute('aria-checked')).toBe('true');

      // Re-render disabled -> click does nothing
      onChange.mockClear();
      act(() => {
        root?.render(<Harness disabled />);
      });
      act(() => {
        toggle.dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(onChange).not.toHaveBeenCalled();
    });
  });

  describe('PrecisionNumberInput, HairlineTabs, SectionDisclosure & IconButton', () => {
    it('handles PrecisionNumberInput label scrubbing, Shift precision, and clamped inline edit', () => {
      const onChange = vi.fn();

      const Harness: React.FC = () => {
        const [val, setVal] = React.useState(20);
        return (
          <PrecisionNumberInput
            data-testid="num-field"
            label="X"
            unit="px"
            min={0}
            max={100}
            step={1}
            defaultValue={10}
            value={val}
            onChange={(next) => {
              onChange(next);
              setVal(next);
            }}
          />
        );
      };

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(<Harness />);
      });

      const wrapper = dom.container.findByAttr('data-testid', 'num-field')!;
      const handle = wrapper.findByAttr('data-precision-scrub-handle', 'true')!;

      // Scrub 20px right (4px/step => +5)
      act(() => {
        firePointer(handle, 'pointerdown', { clientX: 50, pointerId: 1 });
        firePointer(handle, 'pointermove', { clientX: 70, pointerId: 1 });
        firePointer(handle, 'pointerup', { clientX: 70, pointerId: 1 });
      });
      expect(onChange).toHaveBeenLastCalledWith(25);

      // Double-click handle resets to defaultValue (10)
      act(() => {
        handle.dispatchEvent(new Event('dblclick', { bubbles: true }));
      });
      expect(onChange).toHaveBeenLastCalledWith(10);

      // Inline typing with clamping & Escape cancel
      const numInput = wrapper.findAll((el) => el.tagName === 'INPUT')[0]!;
      act(() => {
        numInput.focus();
      });
      act(() => {
        setInputText(numInput, '150');
      });
      act(() => {
        fireKey(numInput, 'Enter');
      });
      expect(onChange).toHaveBeenLastCalledWith(100);

      onChange.mockClear();
      act(() => {
        numInput.focus();
      });
      act(() => {
        setInputText(numInput, '5');
      });
      act(() => {
        fireKey(numInput, 'Escape');
      });
      expect(onChange).not.toHaveBeenCalled();
    });

    it('renders HairlineTabs, SectionDisclosure, and IconButton with crisp accessible states', () => {
      const onTabChange = vi.fn();
      const onToggleSection = vi.fn();
      const onIconClick = vi.fn();

      act(() => {
        root = createRoot(dom.container as unknown as Element);
        root.render(
          <div>
            <HairlineTabs<'layers' | 'history'>
              data-testid="panel-tabs"
              value="layers"
              onChange={onTabChange}
              tabs={[
                { value: 'layers', label: 'Layers', 'data-testid': 'tab-layers' },
                { value: 'history', label: 'History', 'data-testid': 'tab-history' },
              ]}
            />
            <SectionDisclosure
              data-testid="ink-section"
              title="Ink"
              summary="96%"
              open={false}
              onToggle={onToggleSection}
            >
              <div>Hidden Body</div>
            </SectionDisclosure>
            <IconButton
              data-testid="lock-btn"
              active={true}
              title="Lock Layer"
              onClick={onIconClick}
              icon={<span>L</span>}
            />
          </div>
        );
      });

      const historyTab = dom.container.findByAttr('data-testid', 'tab-history')!;
      act(() => {
        historyTab.dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(onTabChange).toHaveBeenCalledWith('history');

      const section = dom.container.findByAttr('data-testid', 'ink-section')!;
      expect(section.textContent).toContain('Ink');
      expect(section.textContent).toContain('96%');
      expect(section.textContent).not.toContain('Hidden Body');
      const sectionBtn = section.findAll((el) => el.tagName === 'BUTTON')[0]!;
      act(() => {
        sectionBtn.dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(onToggleSection).toHaveBeenCalledTimes(1);

      const lockBtn = dom.container.findByAttr('data-testid', 'lock-btn')!;
      expect(lockBtn.getAttribute('aria-pressed')).toBe('true');
      expect(lockBtn.getAttribute('data-active')).toBe('true');
      act(() => {
        lockBtn.dispatchEvent(new Event('click', { bubbles: true }));
      });
      expect(onIconClick).toHaveBeenCalledTimes(1);
    });
  });
});