Skip to content

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

30.5 KB
Raw Blame
import { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import {
  BOTTOM_DOCK_COL_ID,
  BOTTOM_DOCK_MAX_HEIGHT,
  BOTTOM_DOCK_MIN_HEIGHT,
  DockColumn,
  DockGroup,
  FloatingPanelState,
  WorkspaceLayout,
} from '../../types/workspace';
import {
  DEFAULT_ILLUSTRATION_LAYOUT,
  WORKSPACE_STORAGE_KEY,
  cloneLayout,
  findPanelLocation,
  getGroupCells,
  listVisiblePanelIds,
  loadWorkspaceState,
  mirrorWorkspaceLayout,
  parseWorkspaceBundle,
  sanitizeLayout,
  serializeWorkspaceBundle,
} from '../workspacePresets';
import { useWorkspaceStore, workspaceStoreActions } from '../../stores/useWorkspaceStore';
import {
  BottomDockView,
  DockGroupView,
  detectDockDropTarget,
  renderPanelIcon,
} from '../../components/DockWorkspace';
import { FloatingPanelWindow } from '../../components/FloatingPanelWindow';
import { releaseAllWorkspaceInteractionLocks } from '../workspacePointerGuard';

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

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>();
  rectOverride: {
    left: number;
    top: number;
    width: number;
    height: number;
  } | 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)] : [];
  }

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

  getBoundingClientRect() {
    const r = this.rectOverride ?? { left: 200, top: 60, width: 320, height: 240 };
    return {
      left: r.left,
      right: r.left + r.width,
      top: r.top,
      bottom: r.top + r.height,
      width: r.width,
      height: r.height,
      x: r.left,
      y: r.top,
      toJSON: () => ({}),
    };
  }

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

  querySelectorAll(selector: string): MiniEl[] {
    const match = selector.match(/^\[([a-zA-Z0-9-]+)\]$/);
    if (!match) return [];
    return this.findAllByAttr(match[1]);
  }

  querySelector(selector: string): MiniEl | null {
    return this.querySelectorAll(selector)[0] ?? null;
  }
}

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;
  querySelectorAll: (selector: string) => MiniEl[];
  querySelector: (selector: string) => MiniEl | null;
  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,
    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 = {
    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),
    querySelectorAll: (sel: string) => mockDoc.body.querySelectorAll(sel),
    querySelector: (sel: string) => mockDoc.body.querySelector(sel),
    addEventListener: docTarget.addEventListener.bind(docTarget),
    removeEventListener: docTarget.removeEventListener.bind(docTarget),
    dispatchEvent: docTarget.dispatchEvent.bind(docTarget),
  } as MiniDoc;

  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 = () => 1;
  const cancelRafMock = () => {};

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

describe('Side-by-Side Split Palettes, Bottom Dock Zone & Granular Locks', () => {
  beforeEach(() => {
    (globalThis as Record<string, unknown>).localStorage = createMemoryStorage();
    releaseAllWorkspaceInteractionLocks();
    workspaceStoreActions.resetWorkspace();
  });

  afterEach(() => {
    releaseAllWorkspaceInteractionLocks();
  });

  it('migrates legacy DockColumn.groups layouts cleanly without breaking or losing panels', () => {
    const legacyState = {
      activePresetId: 'illustration',
      layout: {
        leftDocks: [
          {
            id: 'legacy-left',
            width: 240,
            collapsed: false,
            groups: [
              { id: 'lg-1', panelIds: ['tools', 'subtool'], activePanelId: 'subtool', heightRatio: 0.6 },
              { id: 'lg-2', panelIds: ['brush-size'], activePanelId: 'brush-size', heightRatio: 0.4 },
            ],
          },
        ],
        rightDocks: [
          {
            id: 'legacy-right',
            width: 260,
            collapsed: false,
            groups: [
              { id: 'rg-1', panelIds: ['color'], activePanelId: 'color', heightRatio: 0.5 },
              { id: 'rg-2', panelIds: ['layers'], activePanelId: 'layers', heightRatio: 0.5 },
            ],
          },
        ],
      },
    };

    localStorage.setItem(WORKSPACE_STORAGE_KEY, JSON.stringify(legacyState));
    const loaded = loadWorkspaceState();

    expect(loaded.workspaceLocks).toEqual({
      lockWidth: false,
      lockHeight: false,
      lockMove: false,
    });
    expect(loaded.layout.bottomDock).toBeUndefined();
    expect(loaded.layout.leftDocks[0].groups[0].splitCells).toBeUndefined();
    expect(getGroupCells(loaded.layout.leftDocks[0].groups[0])).toHaveLength(1);
    const visible = listVisiblePanelIds(loaded.layout);
    for (const expectedPid of ['tools', 'subtool', 'brush-size', 'color', 'layers'] as const) {
      expect(visible.has(expectedPid)).toBe(true);
    }
  });

  it('supports splitting 2 and 3 palettes side-by-side at equal height, resizing widthRatio, and rebalancing on removal', () => {
    const initial = useWorkspaceStore.getState().layout;
    const colorLoc = findPanelLocation(initial, 'color');
    expect(colorLoc).not.toBeNull();
    if (!colorLoc) return;

    // 1. Split color-sets side-by-side to the right of color (2 equal-height cells)
    workspaceStoreActions.movePanel('color-sets', {
      side: colorLoc.side,
      targetColId: colorLoc.colId,
      targetGroupId: colorLoc.groupId,
      splitHorizontal: 'right',
    });

    let layout = useWorkspaceStore.getState().layout;
    const rightCol = layout.rightDocks.find((c) => c.id === colorLoc.colId)!;
    const splitGroup = rightCol.groups.find((g) => g.id === colorLoc.groupId)!;
    expect(splitGroup.splitCells).toHaveLength(2);
    expect(splitGroup.splitCells![0].panelIds).toContain('color');
    expect(splitGroup.splitCells![1].panelIds).toEqual(['color-sets']);
    expect(splitGroup.splitCells![0].widthRatio).toBeCloseTo(0.5, 4);
    expect(splitGroup.splitCells![1].widthRatio).toBeCloseTo(0.5, 4);

    // 2. Split a 3rd palette (color-history) side-by-side to the right of the 2nd cell
    const secondCellId = splitGroup.splitCells![1].id;
    workspaceStoreActions.movePanel('color-history', {
      side: colorLoc.side,
      targetColId: colorLoc.colId,
      targetGroupId: colorLoc.groupId,
      targetCellId: secondCellId,
      splitHorizontal: 'right',
    });

    layout = useWorkspaceStore.getState().layout;
    const group3 = layout.rightDocks
      .find((c) => c.id === colorLoc.colId)!
      .groups.find((g) => g.id === colorLoc.groupId)!;
    expect(group3.splitCells).toHaveLength(3);
    expect(group3.splitCells!.map((c) => c.activePanelId)).toEqual([
      'color',
      'color-sets',
      'color-history',
    ]);
    const ratioSum3 = group3.splitCells!.reduce((acc, c) => acc + c.widthRatio, 0);
    expect(ratioSum3).toBeCloseTo(1, 4);

    // 3. Resize cell split between cell 0 and cell 1
    workspaceStoreActions.resizeCellSplit(
      colorLoc.colId,
      colorLoc.groupId,
      group3.splitCells![0].id,
      group3.splitCells![1].id,
      0.45,
      0.22,
      true
    );
    layout = useWorkspaceStore.getState().layout;
    const resizedGroup = layout.rightDocks
      .find((c) => c.id === colorLoc.colId)!
      .groups.find((g) => g.id === colorLoc.groupId)!;
    expect(resizedGroup.splitCells![0].widthRatio).toBeGreaterThan(
      resizedGroup.splitCells![1].widthRatio
    );

    // 4. Remove the 3rd cell -> remaining 2 cells cleanly rebalance to sum = 1
    workspaceStoreActions.togglePanelVisibility('color-history');
    layout = useWorkspaceStore.getState().layout;
    const afterRemoveOne = layout.rightDocks
      .find((c) => c.id === colorLoc.colId)!
      .groups.find((g) => g.id === colorLoc.groupId)!;
    expect(afterRemoveOne.splitCells).toHaveLength(2);
    const sumAfterOne = afterRemoveOne.splitCells!.reduce((acc, c) => acc + c.widthRatio, 0);
    expect(sumAfterOne).toBeCloseTo(1, 4);

    // 5. Remove the 2nd cell -> single remaining cell unwraps cleanly to legacy group (no splitCells)
    workspaceStoreActions.togglePanelVisibility('color-sets');
    layout = useWorkspaceStore.getState().layout;
    const unwrapped = layout.rightDocks
      .find((c) => c.id === colorLoc.colId)!
      .groups.find((g) => g.id === colorLoc.groupId)!;
    expect(unwrapped.splitCells).toBeUndefined();
    expect(unwrapped.panelIds).toContain('color');
  });

  it('supports Bottom Dock docking, side-by-side splits, height clamp, collapse/expand, undock cleanup, and mirroring', () => {
    // Dock color-sets to bottom
    workspaceStoreActions.movePanel('color-sets', { side: 'bottom' });
    let layout = useWorkspaceStore.getState().layout;
    expect(layout.bottomDock).toBeDefined();
    expect(layout.bottomDock!.cells).toHaveLength(1);
    expect(layout.bottomDock!.cells[0].panelIds).toEqual(['color-sets']);
    expect(findPanelLocation(layout, 'color-sets')?.side).toBe('bottom');

    // Split color-history side-by-side to the right inside bottom dock
    const firstBottomCellId = layout.bottomDock!.cells[0].id;
    workspaceStoreActions.movePanel('color-history', {
      side: 'bottom',
      targetColId: BOTTOM_DOCK_COL_ID,
      targetGroupId: BOTTOM_DOCK_COL_ID,
      targetCellId: firstBottomCellId,
      splitHorizontal: 'right',
    });

    layout = useWorkspaceStore.getState().layout;
    expect(layout.bottomDock!.cells).toHaveLength(2);
    expect(layout.bottomDock!.cells.map((c) => c.activePanelId)).toEqual([
      'color-sets',
      'color-history',
    ]);

    // Resize cell widths inside bottom dock
    workspaceStoreActions.resizeCellSplit(
      BOTTOM_DOCK_COL_ID,
      BOTTOM_DOCK_COL_ID,
      layout.bottomDock!.cells[0].id,
      layout.bottomDock!.cells[1].id,
      0.7,
      0.3,
      true
    );
    layout = useWorkspaceStore.getState().layout;
    expect(layout.bottomDock!.cells[0].widthRatio).toBeCloseTo(0.7, 3);
    expect(layout.bottomDock!.cells[1].widthRatio).toBeCloseTo(0.3, 3);

    // Resize bottom dock height clamped strictly within [96..420]
    workspaceStoreActions.resizeBottomDock(40, true);
    expect(useWorkspaceStore.getState().layout.bottomDock!.height).toBe(BOTTOM_DOCK_MIN_HEIGHT);
    workspaceStoreActions.resizeBottomDock(900, true);
    expect(useWorkspaceStore.getState().layout.bottomDock!.height).toBe(BOTTOM_DOCK_MAX_HEIGHT);
    workspaceStoreActions.resizeBottomDock(210, true);
    expect(useWorkspaceStore.getState().layout.bottomDock!.height).toBe(210);

    // Collapse & expand bottom dock
    workspaceStoreActions.toggleBottomDockCollapsed(true);
    expect(useWorkspaceStore.getState().layout.bottomDock!.collapsed).toBe(true);
    workspaceStoreActions.toggleBottomDockCollapsed(false);
    expect(useWorkspaceStore.getState().layout.bottomDock!.collapsed).toBe(false);

    // Also add a side-by-side split in right dock and check mirrorWorkspaceLayout round-trip
    const curLayout = useWorkspaceStore.getState().layout;
    const colorLoc = findPanelLocation(curLayout, 'color')!;
    workspaceStoreActions.movePanel('navigator', {
      side: colorLoc.side,
      targetColId: colorLoc.colId,
      targetGroupId: colorLoc.groupId,
      splitHorizontal: 'right',
    });
    const beforeMirror = sanitizeLayout(useWorkspaceStore.getState().layout);
    expect(beforeMirror).not.toBeNull();
    if (!beforeMirror) return;
    const mirrored = mirrorWorkspaceLayout(beforeMirror);
    expect(mirrored.bottomDock).toEqual(beforeMirror.bottomDock);
    const twiceMirrored = mirrorWorkspaceLayout(mirrored);
    expect(twiceMirrored).toEqual(beforeMirror);

    // Undocking all bottom panels removes bottomDock cleanly
    workspaceStoreActions.movePanel('color-sets', { side: 'right' });
    workspaceStoreActions.movePanel('color-history', { side: 'right' });
    expect(useWorkspaceStore.getState().layout.bottomDock).toBeUndefined();
  });

  it('persists granular workspaceLocks across storage, SavedWorkspaceProfile, and .inkworkspace bundles', () => {
    workspaceStoreActions.setWorkspaceLock('lockWidth', true);
    workspaceStoreActions.setWorkspaceLock('lockMove', true);
    expect(useWorkspaceStore.getState().workspaceLocks).toEqual({
      lockWidth: true,
      lockHeight: false,
      lockMove: true,
    });

    // Reload from localStorage
    const reloaded = loadWorkspaceState();
    expect(reloaded.workspaceLocks).toEqual({
      lockWidth: true,
      lockHeight: false,
      lockMove: true,
    });

    // Save custom workspace profile -> toggle lock all -> restore profile
    workspaceStoreActions.movePanel('color-sets', { side: 'bottom' });
    const profile = workspaceStoreActions.saveCustomWorkspace('Pen Display Locked');
    expect(profile.workspaceLocks).toEqual({
      lockWidth: true,
      lockHeight: false,
      lockMove: true,
    });
    expect(profile.layout.bottomDock?.cells[0].panelIds).toEqual(['color-sets']);

    // 1-click Lock All -> locks all 3, second click unlocks all 3
    workspaceStoreActions.toggleLockAllWorkspace();
    expect(useWorkspaceStore.getState().workspaceLocks).toEqual({
      lockWidth: true,
      lockHeight: true,
      lockMove: true,
    });
    workspaceStoreActions.toggleLockAllWorkspace();
    expect(useWorkspaceStore.getState().workspaceLocks).toEqual({
      lockWidth: false,
      lockHeight: false,
      lockMove: false,
    });

    // Apply saved profile restores locks & bottomDock
    workspaceStoreActions.loadCustomWorkspace(profile.id);
    expect(useWorkspaceStore.getState().workspaceLocks).toEqual({
      lockWidth: true,
      lockHeight: false,
      lockMove: true,
    });
    expect(useWorkspaceStore.getState().layout.bottomDock?.cells[0].panelIds).toEqual([
      'color-sets',
    ]);

    // .inkworkspace bundle serialization & parsing round-trip
    const bundleJson = serializeWorkspaceBundle({
      name: 'Studio Pen Bundle',
      layout: useWorkspaceStore.getState().layout,
      leftHandedMode: false,
      showToolOptionsBar: true,
      showStatusBar: true,
      showDocumentTabs: true,
      showCommandBar: true,
      workspaceLocks: useWorkspaceStore.getState().workspaceLocks,
    });
    const parsed = parseWorkspaceBundle(bundleJson);
    expect(parsed.ok).toBe(true);
    if (!parsed.ok) return;
    expect(parsed.bundle.workspaceLocks).toEqual({
      lockWidth: true,
      lockHeight: false,
      lockMove: true,
    });
    expect(parsed.bundle.layout.bottomDock?.cells[0].panelIds).toEqual(['color-sets']);
  });

  it('enforces locks in DockGroupView, BottomDockView, and FloatingPanelWindow while keeping tab switching usable', () => {
    const dom = installMiniDom();
    let root: Root | null = null;

    try {
      const group: DockGroup = {
        id: 'grp-split',
        panelIds: ['color', 'color-sliders', 'color-sets'],
        activePanelId: 'color',
        heightRatio: 0.5,
        splitCells: [
          {
            id: 'cell-a',
            widthRatio: 0.5,
            panelIds: ['color', 'color-sliders'],
            activePanelId: 'color',
          },
          {
            id: 'cell-b',
            widthRatio: 0.5,
            panelIds: ['color-sets'],
            activePanelId: 'color-sets',
          },
        ],
      };
      const col: DockColumn = {
        id: 'col-right-split',
        width: 440,
        collapsed: false,
        groups: [group],
      };
      const bottomDock = {
        height: 180,
        collapsed: false,
        cells: [
          { id: 'b-cell-1', widthRatio: 0.5, panelIds: ['color-history' as const], activePanelId: 'color-history' as const },
          { id: 'b-cell-2', widthRatio: 0.5, panelIds: ['info' as const], activePanelId: 'info' as const },
        ],
      };
      const floating: FloatingPanelState = {
        id: 'float-1',
        panelIds: ['navigator', 'sub-view'],
        activePanelId: 'navigator',
        x: 100,
        y: 100,
        width: 260,
        height: 240,
        zIndex: 42,
        collapsed: false,
      };

      const layoutWithAll: WorkspaceLayout = {
        ...cloneLayout(DEFAULT_ILLUSTRATION_LAYOUT),
        rightDocks: [col],
        bottomDock,
        floatingPanels: [floating],
      };
      useWorkspaceStore.setState({
        layout: layoutWithAll,
        workspaceLocks: { lockWidth: true, lockHeight: true, lockMove: true },
      });

      const onStartHeaderDrag = vi.fn();
      const onStartTabDrag = vi.fn();

      root = createRoot(dom.container as unknown as Element);
      act(() => {
        root!.render(
          <div>
            <DockGroupView
              side="right"
              col={col}
              group={group}
              themePreset="modern"
              draggingPanelId={null}
              onStartDragPanel={() => {}}
              onEndDragPanel={() => {}}
              onStartPointerTabDrag={onStartTabDrag}
              renderPanelBody={(pid) => <div data-testid={`body-${pid}`}>{pid}</div>}
            />
            <BottomDockView
              bottomDock={bottomDock}
              draggingPanelId={null}
              onStartDragPanel={() => {}}
              onEndDragPanel={() => {}}
              onStartPointerTabDrag={onStartTabDrag}
              renderPanelBody={(pid) => <div data-testid={`bbody-${pid}`}>{pid}</div>}
            />
            <FloatingPanelWindow
              panel={floating}
              isDragging={false}
              isDockTargetActive={false}
              isMergeTabTarget={false}
              renderPanelIcon={renderPanelIcon}
              renderPanelBody={(pid) => <div data-testid={`fbody-${pid}`}>{pid}</div>}
              onStartHeaderDrag={onStartHeaderDrag}
              onStartTabDrag={onStartTabDrag}
            />
          </div>
        );
      });

      // Split row renders both cells and locked vertical splitter
      expect(dom.container.findByAttr('data-testid', 'dock-cell-cell-a')).not.toBeNull();
      expect(dom.container.findByAttr('data-testid', 'dock-cell-cell-b')).not.toBeNull();
      const cellSplitter = dom.container.findByAttr('data-testid', 'dock-cell-splitter-grp-split-0');
      expect(cellSplitter?.getAttribute('data-locked')).toBe('true');

      // Bottom dock renders locked height resizer and locked vertical cell splitter
      const bottomResizer = dom.container.findByAttr('data-testid', 'bottom-dock-resizer');
      expect(bottomResizer?.getAttribute('data-locked')).toBe('true');
      const bottomCellSplitter = dom.container.findByAttr('data-testid', 'bottom-cell-splitter-0');
      expect(bottomCellSplitter?.getAttribute('data-locked')).toBe('true');

      const getReactProps = (el: MiniEl) => {
        const key = Object.keys(el).find((k) => k.startsWith('__reactProps'));
        expect(key).toBeDefined();
        return (el as unknown as Record<string, Record<string, (e: unknown) => void>>)[key!];
      };

      // Clicking bottom dock collapse button STILL works even when locked!
      const bottomCollapseBtn = dom.container.findByAttr('data-testid', 'bottom-dock-collapse-btn');
      expect(bottomCollapseBtn).not.toBeNull();
      act(() => {
        getReactProps(bottomCollapseBtn!).onClick?.({
          stopPropagation: () => {},
          preventDefault: () => {},
        });
      });
      expect(useWorkspaceStore.getState().layout.bottomDock?.collapsed).toBe(true);

      // Clicking a docked tab STILL switches active panel even when lockMove=true!
      const slidersTab = dom.container.findByAttr('data-testid', 'dock-tab-color-sliders');
      expect(slidersTab).not.toBeNull();
      act(() => {
        getReactProps(slidersTab!).onClick?.({
          stopPropagation: () => {},
          preventDefault: () => {},
        });
      });
      const updatedCellA = useWorkspaceStore
        .getState()
        .layout.rightDocks[0].groups[0].splitCells![0];
      expect(updatedCellA.activePanelId).toBe('color-sliders');

      // Dragging docked tab when lockMove=true does NOT start pointer drag
      act(() => {
        getReactProps(slidersTab!).onPointerDown?.({
          button: 0,
          stopPropagation: () => {},
          preventDefault: () => {},
        });
      });
      expect(onStartTabDrag).not.toHaveBeenCalled();

      // Floating panel header drag is blocked when lockMove=true, and edge resizers are hidden when lockWidth/lockHeight=true
      const floatingEl = dom.mockDoc.body.findByAttr('data-testid', 'floating-panel-navigator');
      expect(floatingEl).not.toBeNull();
      const floatHeader = floatingEl!.findByAttr('data-drop-floating-header', 'float-1');
      expect(floatHeader).not.toBeNull();
      act(() => {
        getReactProps(floatHeader!).onPointerDown?.({
          button: 0,
          target: floatHeader,
          stopPropagation: () => {},
          preventDefault: () => {},
        });
      });
      expect(onStartHeaderDrag).not.toHaveBeenCalled();
      expect(floatingEl!.findByAttr('data-resize-handle', 'e')).toBeNull();
      expect(floatingEl!.findByAttr('data-resize-handle', 's')).toBeNull();
      expect(floatingEl!.findByAttr('data-resize-handle', 'se')).toBeNull();
    } finally {
      if (root) {
        act(() => {
          root!.unmount();
        });
      }
      dom.cleanup();
    }
  });

  it('detectDockDropTarget resolves all 5 cell drop zones, bottom dock stage edge, and respects lockMove', () => {
    const dom = installMiniDom();
    try {
      const ws = dom.mockDoc.createElement('div');
      ws.rectOverride = { left: 0, top: 0, width: 1200, height: 800 };
      dom.mockDoc.body.appendChild(ws);

      const cellEl = dom.mockDoc.createElement('div');
      cellEl.setAttribute('data-drop-cell', 'right|col-r|grp-1|cell-1|0');
      cellEl.rectOverride = { left: 900, top: 100, width: 260, height: 300 };
      ws.appendChild(cellEl);

      const stageEl = dom.mockDoc.createElement('div');
      stageEl.rectOverride = { left: 240, top: 40, width: 660, height: 740 };
      ws.appendChild(stageEl);

      const layout = cloneLayout(DEFAULT_ILLUSTRATION_LAYOUT);
      const source = {
        kind: 'docked-tab' as const,
        panelId: 'brush-size' as const,
        sourceColId: 'col-left',
        sourceGroupId: 'grp-other',
        sourceCellId: 'cell-other',
        sourceGroupPanelCount: 1,
      };

      // 1. Header -> dock-tab
      const headerTarget = detectDockDropTarget(
        1030,
        112,
        ws as unknown as HTMLDivElement,
        null,
        null,
        layout,
        source,
        stageEl as unknown as HTMLDivElement,
        false
      );
      expect(headerTarget?.kind).toBe('dock-tab');

      // 2. Left edge -> dock-cell-split left
      const leftTarget = detectDockDropTarget(
        920,
        250,
        ws as unknown as HTMLDivElement,
        null,
        null,
        layout,
        source,
        stageEl as unknown as HTMLDivElement,
        false
      );
      expect(leftTarget).toMatchObject({ kind: 'dock-cell-split', splitHorizontal: 'left' });

      // 3. Right edge -> dock-cell-split right
      const rightTarget = detectDockDropTarget(
        1140,
        250,
        ws as unknown as HTMLDivElement,
        null,
        null,
        layout,
        source,
        stageEl as unknown as HTMLDivElement,
        false
      );
      expect(rightTarget).toMatchObject({ kind: 'dock-cell-split', splitHorizontal: 'right' });

      // 4. Top edge (below header) -> dock-split stack above
      const topTarget = detectDockDropTarget(
        1030,
        145,
        ws as unknown as HTMLDivElement,
        null,
        null,
        layout,
        source,
        stageEl as unknown as HTMLDivElement,
        false
      );
      expect(topTarget).toMatchObject({ kind: 'dock-split', insertGroupIndex: 0 });

      // 5. Bottom edge -> dock-split stack below
      const bottomTarget = detectDockDropTarget(
        1030,
        380,
        ws as unknown as HTMLDivElement,
        null,
        null,
        layout,
        source,
        stageEl as unknown as HTMLDivElement,
        false
      );
      expect(bottomTarget).toMatchObject({ kind: 'dock-split', insertGroupIndex: 1 });

      // 6. Center -> dock-tab
      const centerTarget = detectDockDropTarget(
        1030,
        250,
        ws as unknown as HTMLDivElement,
        null,
        null,
        layout,
        source,
        stageEl as unknown as HTMLDivElement,
        false
      );
      expect(centerTarget).toMatchObject({ kind: 'dock-tab', targetCellId: 'cell-1' });

      // 7. Bottom edge of canvas stage -> dock-bottom
      const stageBottomTarget = detectDockDropTarget(
        560,
        768,
        ws as unknown as HTMLDivElement,
        null,
        null,
        layout,
        source,
        stageEl as unknown as HTMLDivElement,
        false
      );
      expect(stageBottomTarget?.kind).toBe('dock-bottom');

      // 8. lockMove=true returns null everywhere
      const lockedTarget = detectDockDropTarget(
        560,
        768,
        ws as unknown as HTMLDivElement,
        null,
        null,
        layout,
        source,
        stageEl as unknown as HTMLDivElement,
        true
      );
      expect(lockedTarget).toBeNull();
    } finally {
      dom.cleanup();
    }
  });
});