Skip to content

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

28.8 KB
Raw Blame
import React, { act } from 'react';
import { createRoot, Root } from 'react-dom/client';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { CanvasArea } from '../../components/CanvasArea';
import { SpeechBalloonOverlay } from '../../components/SpeechBalloonOverlay';
import { DockGroupView, renderPanelIcon } from '../../components/DockWorkspace';
import { FloatingPanelWindow } from '../../components/FloatingPanelWindow';
import { PressureCurveEditor } from '../../components/PressureCurveEditor';
import {
  useDocumentLifecycle,
  UseDocumentLifecycleParams,
} from '../../components/DocumentLifecycleManager';
import { ErrorBoundary } from '../../main';
import {
  documentStoreActions,
  toolStoreActions,
  uiStoreActions,
  useDocumentStore,
  useToolStore,
  useUiStore,
  useWorkspaceStore,
} from '../../stores';
import {
  COLOR_SETS_STORAGE_KEY,
  createInitialColorSetsState,
} from '../../stores/useColorSetsStore';
import {
  autoActionStoreActions,
  useAutoActionStore,
} from '../../stores/useAutoActionStore';
import {
  BrushSettings,
  LayerItem,
  NewCanvasOptions,
  SpeechBalloon,
} from '../../types/editor';
import { loadAppSettings } from '../../types/settings';
import {
  resetBrushSettingsCache,
  getEffectiveBrushSettings,
  loadAllSavedBrushSettings,
} from '../brushPresetManager';
import { evaluateFastSpline, getCompiledCurveLut } from '../brushMath';
import { enforceColorMode, hexToRgb, isValidHex, parseRgba } from '../colorUtils';
import {
  isLinearPressureCurve,
  normalizePressureCurve,
  sanitizePressureCurvePoints,
} from '../pressureCurve';
import {
  buildNativeBrushConfigPayload,
  createNativeDocument,
  parseCssColorToRgba,
  setNativePressureCurve,
  syncNativeFullBrushConfig,
} from '../nativeEngineBridge';
import {
  buildGradientMapLut,
  buildMonotonicCubicSplineLut,
  createDefaultGradientMesh,
  resolveGradientStops,
} from '../toolConfigs';
import {
  WORKSPACE_STORAGE_KEY,
  loadWorkspaceState,
} from '../workspacePresets';
import type {
  DockColumn,
  DockGroup,
  FloatingPanelState,
} from '../../types/workspace';
import {
  computeViewportQuadInDoc,
  isPointInConvexQuad,
} from '../../components/NavigatorPanel';

vi.mock('../recentDocumentsManager', () => ({
  saveRecentDocument: vi.fn().mockResolvedValue(undefined),
}));

// Minimal in-memory Storage implementation for legacy/corrupt localStorage tests
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));
    },
  };
}

function createStubCanvas2DContext(canvas: MiniEl) {
  return {
    canvas,
    save: vi.fn(),
    restore: vi.fn(),
    scale: vi.fn(),
    translate: vi.fn(),
    rotate: vi.fn(),
    transform: vi.fn(),
    setTransform: vi.fn(),
    clearRect: vi.fn(),
    fillRect: vi.fn(),
    strokeRect: vi.fn(),
    beginPath: vi.fn(),
    closePath: vi.fn(),
    moveTo: vi.fn(),
    lineTo: vi.fn(),
    bezierCurveTo: vi.fn(),
    quadraticCurveTo: vi.fn(),
    arc: vi.fn(),
    ellipse: vi.fn(),
    rect: vi.fn(),
    fill: vi.fn(),
    stroke: vi.fn(),
    clip: vi.fn(),
    drawImage: vi.fn(),
    fillText: vi.fn(),
    strokeText: vi.fn(),
    measureText: vi.fn(() => ({ width: 20 })),
    setLineDash: vi.fn(),
    createLinearGradient: vi.fn(() => ({ addColorStop: vi.fn() })),
    createRadialGradient: vi.fn(() => ({ addColorStop: vi.fn() })),
    getImageData: vi.fn(() => ({ data: new Uint8ClampedArray(16), width: 2, height: 2 })),
    putImageData: vi.fn(),
    fillStyle: '#000000',
    strokeStyle: '#000000',
    lineWidth: 1,
    lineCap: 'round',
    lineJoin: 'round',
    globalAlpha: 1,
    globalCompositeOperation: 'source-over',
    font: '12px sans-serif',
    textAlign: 'left',
    textBaseline: 'alphabetic',
    imageSmoothingEnabled: true,
    imageSmoothingQuality: 'high',
  };
}

class MiniText {
  public nodeType = 3;
  public nodeName = '#text';
  public parentNode: MiniEl | null = null;
  constructor(
    public nodeValue: string,
    public ownerDocument: MiniDoc
  ) {}
}

class MiniComment {
  public nodeType = 8;
  public nodeName = '#comment';
  public parentNode: MiniEl | null = null;
  constructor(
    public nodeValue: string,
    public ownerDocument: MiniDoc
  ) {}
}

class MiniEl extends EventTarget {
  public nodeType = 1;
  public nodeName: string;
  public tagName: string;
  public namespaceURI: string;
  public parentNode: MiniEl | null = null;
  public childNodes: Array<MiniEl | MiniText | MiniComment> = [];
  public style: Record<string, string> = {};
  public className = '';
  public disabled = false;
  public value = '';
  public checked = false;
  public width = 300;
  public height = 150;
  public clientWidth = 1024;
  public clientHeight = 768;
  public offsetWidth = 1024;
  public offsetHeight = 768;
  public scrollLeft = 0;
  public scrollTop = 0;
  public dataset: Record<string, string> = {};
  public isContentEditable = false;
  private attrs = new Map<string, string>();
  private ctx2d: ReturnType<typeof createStubCanvas2DContext> | null = null;

  constructor(
    tag: string,
    public ownerDocument: MiniDoc,
    namespaceURI = 'http://www.w3.org/1999/xhtml'
  ) {
    super();
    this.nodeName = tag.toUpperCase();
    this.tagName = tag.toUpperCase();
    this.namespaceURI = namespaceURI;
  }

  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(String(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(): DOMRect {
    return {
      left: 0,
      top: 0,
      right: this.clientWidth,
      bottom: this.clientHeight,
      width: this.clientWidth,
      height: this.clientHeight,
      x: 0,
      y: 0,
      toJSON: () => ({}),
    };
  }

  getContext(type: string) {
    if (type === '2d') {
      if (!this.ctx2d) this.ctx2d = createStubCanvas2DContext(this);
      return this.ctx2d;
    }
    return null;
  }

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

  closest(_selector: string): MiniEl | null {
    return null;
  }

  querySelector(_selector: string): MiniEl | null {
    return null;
  }

  querySelectorAll(_selector: string): MiniEl[] {
    return [];
  }

  focus() {}
  blur() {}
  select() {}
  setPointerCapture() {}
  releasePointerCapture() {}
  hasPointerCapture() {
    return false;
  }

  findAllByTag(tag: string): MiniEl[] {
    const upper = tag.toUpperCase();
    const out: MiniEl[] = [];
    if (this.tagName === upper) out.push(this);
    for (const c of this.childNodes) {
      if (c instanceof MiniEl) out.push(...c.findAllByTag(tag));
    }
    return out;
  }
}

class MiniDoc extends EventTarget {
  public nodeType = 9;
  public nodeName = '#document';
  public defaultView: unknown = globalThis;
  public documentElement: MiniEl;
  public body: MiniEl;
  public activeElement: MiniEl;

  constructor() {
    super();
    this.documentElement = new MiniEl('html', this);
    this.body = new MiniEl('body', this);
    this.documentElement.appendChild(this.body);
    this.activeElement = this.body;
  }

  createElement(tag: string): MiniEl {
    return new MiniEl(tag, this);
  }

  createElementNS(ns: string, tag: string): MiniEl {
    return new MiniEl(tag, this, ns);
  }

  createTextNode(val: string): MiniText {
    return new MiniText(val, this);
  }

  createComment(val: string): MiniComment {
    return new MiniComment(val, this);
  }

  getElementById(_id: string): MiniEl | null {
    return null;
  }

  querySelector(_selector: string): MiniEl | null {
    return null;
  }

  querySelectorAll(_selector: string): MiniEl[] {
    return [];
  }

  execCommand(_cmd: string): boolean {
    return true;
  }
}

class StubResizeObserver {
  observe() {}
  unobserve() {}
  disconnect() {}
}

describe('Create New Canvas crash & Rules-of-Hooks regressions', () => {
  let root: Root | null = null;
  let container: MiniEl | null = null;
  let miniDoc: MiniDoc | null = null;
  let storage: Storage;
  const savedGlobals: Record<string, unknown> = {};
  const globalKeys = [
    'IS_REACT_ACT_ENVIRONMENT',
    'document',
    'window',
    'addEventListener',
    'removeEventListener',
    'dispatchEvent',
    'HTMLElement',
    'HTMLCanvasElement',
    'HTMLIFrameElement',
    'SVGElement',
    'Element',
    'Node',
    'ResizeObserver',
    'requestAnimationFrame',
    'cancelAnimationFrame',
    'devicePixelRatio',
    'innerWidth',
    'innerHeight',
    'getComputedStyle',
    'matchMedia',
    'localStorage',
  ];

  const baseLayer: LayerItem = {
    id: 'layer-1',
    name: 'Layer 1',
    type: 'raster',
    visible: true,
    opacity: 1,
    blendMode: 'normal',
    locked: false,
    parentId: null,
  };

  const baseBrushSettings: BrushSettings = {
    preset: 'g-pen',
    size: 12,
    minSizeFactor: 0.04,
    color: '#000000',
    secondaryColor: '#ffffff',
    opacity: 1,
    flow: 1,
    spacing: 0.05,
    grain: 0,
    usePressure: true,
    smoothing: true,
    stabilization: 10,
    hardness: 1,
  };

  beforeEach(() => {
    const g = globalThis as Record<string, unknown>;
    for (const k of globalKeys) {
      savedGlobals[k] = g[k];
    }

    storage = createMemoryStorage();
    miniDoc = new MiniDoc();
    const winEvents = new EventTarget();
    g.IS_REACT_ACT_ENVIRONMENT = true;
    g.document = miniDoc;
    g.window = globalThis;
    g.addEventListener = winEvents.addEventListener.bind(winEvents);
    g.removeEventListener = winEvents.removeEventListener.bind(winEvents);
    g.dispatchEvent = winEvents.dispatchEvent.bind(winEvents);
    g.HTMLElement = MiniEl;
    g.HTMLCanvasElement = MiniEl;
    g.HTMLIFrameElement = class HTMLIFrameElement {};
    g.SVGElement = MiniEl;
    g.Element = MiniEl;
    g.Node = MiniText;
    g.ResizeObserver = StubResizeObserver;
    g.requestAnimationFrame = (cb: FrameRequestCallback) =>
      setTimeout(() => cb(performance.now()), 0) as unknown as number;
    g.cancelAnimationFrame = (id: number) => clearTimeout(id);
    g.devicePixelRatio = 1;
    g.innerWidth = 1440;
    g.innerHeight = 900;
    g.getComputedStyle = () => ({ getPropertyValue: () => '' });
    g.matchMedia = () => ({
      matches: false,
      addEventListener: () => {},
      removeEventListener: () => {},
    });
    g.localStorage = storage;

    container = miniDoc.createElement('div');
    miniDoc.body.appendChild(container);
    root = createRoot(container as unknown as HTMLElement);

    resetBrushSettingsCache();
    documentStoreActions.setDocuments([]);
    documentStoreActions.setActiveDocumentId(null);
    documentStoreActions.setSavedFileInfo(null);
    uiStoreActions.setAppView('home');
    useWorkspaceStore.setState({ palettesHidden: false });
  });

  afterEach(() => {
    if (root) {
      act(() => {
        root?.unmount();
      });
    }
    root = null;
    container = null;
    miniDoc = null;
    resetBrushSettingsCache();

    const g = globalThis as Record<string, unknown>;
    for (const k of globalKeys) {
      if (savedGlobals[k] === undefined) {
        delete g[k];
      } else {
        g[k] = savedGlobals[k];
      }
    }
  });

  it('transitions CanvasArea from hasOpenDocument={false} to hasOpenDocument={true} and back with zero React hook errors', () => {
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    const viewportRef = React.createRef<HTMLDivElement>();
    const interactionRef = React.createRef<HTMLDivElement>();

    const makeCanvasProps = (hasOpenDocument: boolean) => ({
      viewportRef,
      interactionRef,
      dimensions: { width: 1200, height: 800, dpi: 300 },
      brushSettings: baseBrushSettings,
      onUpdateBrushSettings: vi.fn(),
      zoom: 1,
      pan: { x: 0, y: 0 },
      rotation: 0,
      isSpaceDown: false,
      isShiftDown: false,
      isRotateModifier: false,
      isPanning: false,
      isRotating: false,
      onStartPan: vi.fn(),
      onStartRotate: vi.fn(),
      isHovering: false,
      cursorPos: null,
      onPointerDown: vi.fn(),
      onPointerMove: vi.fn(),
      onPointerUp: vi.fn(),
      onPointerEnter: vi.fn(),
      onPointerLeave: vi.fn(),
      layers: [baseLayer],
      activeLayerId: baseLayer.id,
      getEffectiveOpacity: () => 1,
      isLayerEffectivelyVisible: () => true,
      hasOpenDocument,
    });

    try {
      expect(() => {
        act(() => {
          root!.render(React.createElement(CanvasArea, makeCanvasProps(false)));
        });
      }).not.toThrow();

      // Welcome -> Workspace transition (previously crashed with React #310 "Rendered more hooks than during the previous render")
      expect(() => {
        act(() => {
          root!.render(React.createElement(CanvasArea, makeCanvasProps(true)));
        });
      }).not.toThrow();

      // Workspace -> Welcome -> Workspace round-trip
      expect(() => {
        act(() => {
          root!.render(React.createElement(CanvasArea, makeCanvasProps(false)));
        });
        act(() => {
          root!.render(React.createElement(CanvasArea, makeCanvasProps(true)));
        });
      }).not.toThrow();

      const hookErrors = errorSpy.mock.calls.filter((call) =>
        String(call[0] ?? '').toLowerCase().includes('more hooks')
      );
      expect(hookErrors).toHaveLength(0);
    } finally {
      errorSpy.mockRestore();
    }
  });

  it('transitions SpeechBalloonOverlay across balloon={null} -> valid balloon -> null with zero React hook errors', () => {
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

    const sampleBalloon: SpeechBalloon = {
      id: 'balloon-1',
      shape: 'ellipse',
      bounds: { x: 100, y: 100, width: 220, height: 120 },
      tail: {
        start: { x: 180, y: 220, pressure: 0.5, width: 2 },
        control1: { x: 170, y: 260, pressure: 0.5, width: 2 },
        control2: { x: 140, y: 280, pressure: 0.5, width: 2 },
        tip: { x: 120, y: 310, pressure: 0.5, width: 2 },
      },
      fillColor: '#ffffff',
      strokeColor: '#000000',
      strokeWidth: 3,
      text: 'Hello!',
      fontFamily: 'sans-serif',
      fontSize: 20,
      vertical: false,
    };

    const baseProps = {
      zoom: 1,
      onUpdateBalloon: vi.fn(),
      onConfirmBalloon: vi.fn(),
      onDeleteBalloon: vi.fn(),
    };

    try {
      expect(() => {
        act(() => {
          root!.render(
            React.createElement(SpeechBalloonOverlay, { ...baseProps, balloon: null })
          );
        });
      }).not.toThrow();

      expect(() => {
        act(() => {
          root!.render(
            React.createElement(SpeechBalloonOverlay, { ...baseProps, balloon: sampleBalloon })
          );
        });
      }).not.toThrow();

      expect(() => {
        act(() => {
          root!.render(
            React.createElement(SpeechBalloonOverlay, { ...baseProps, balloon: null })
          );
        });
      }).not.toThrow();

      const hookErrors = errorSpy.mock.calls.filter((call) =>
        String(call[0] ?? '').toLowerCase().includes('more hooks')
      );
      expect(hookErrors).toHaveLength(0);
    } finally {
      errorSpy.mockRestore();
    }
  });

  it('handles handleCreateNewCanvas and workspace/store hydration with corrupted legacy localStorage payloads without throwing', () => {
    // Seed corrupted / legacy pre-migration localStorage entries across every affected subsystem
    storage.setItem(
      'ink_studio_app_settings',
      JSON.stringify({
        userName: 'Artist',
        // Missing pressureCurve on purpose in first check, plus malformed canvas defaults
        defaultWidth: null,
        defaultHeight: 'bad',
        defaultDpi: NaN,
        defaultBgColor: 12345,
      })
    );
    storage.setItem(
      WORKSPACE_STORAGE_KEY,
      JSON.stringify({
        version: 1,
        activePresetId: 'custom',
        layout: {
          leftDocks: [
            {
              id: 'col-empty',
              width: 240,
              groups: [{ id: 'grp-empty', panelIds: [], activePanelId: '', heightRatio: 1 }],
            },
          ],
          rightDocks: [{ id: 'col-bad', width: 260, groups: null }],
          floatingPanels: [
            {
              id: 'fp-empty',
              panelIds: [],
              activePanelId: '',
              x: 100,
              y: 100,
              width: 240,
              height: 240,
              collapsed: false,
              zIndex: 1,
            },
          ],
        },
      })
    );
    storage.setItem(
      'ink_studio_brush_settings_by_id',
      JSON.stringify({
        'g-pen': {
          size: Number.NaN,
          pressureCurve: [null, undefined, 'corrupt'],
          velocityCurve: 'not-an-array',
          sizeSensor: {
            usePressure: true,
            pressureCurve: [undefined],
          },
          dualBrushConfig: 'invalid',
        },
      })
    );
    storage.setItem(
      COLOR_SETS_STORAGE_KEY,
      JSON.stringify({
        sets: [{ id: 'bad', name: '', swatches: [{ hex: null }, { hex: '#zzzzzz' }] }],
        activeSetId: 'nonexistent',
      })
    );
    storage.setItem('ink_studio_color_history', JSON.stringify([null, 42, '#zzzzzz', 'bad']));
    storage.setItem('ink_studio_gradient_settings', JSON.stringify({ stops: [null, undefined] }));

    // 1. Hydrating app settings, workspace layout, brush settings, and color sets must never throw
    const loadedSettings = loadAppSettings();
    expect(loadedSettings.pressureCurve.points.length).toBeGreaterThanOrEqual(2);
    expect(loadedSettings.defaultWidth).toBeGreaterThan(0);
    expect(typeof loadedSettings.defaultBgColor).toBe('string');

    const loadedWorkspace = loadWorkspaceState();
    expect(loadedWorkspace.layout.leftDocks.length + loadedWorkspace.layout.rightDocks.length).toBeGreaterThan(0);

    resetBrushSettingsCache();
    const savedBrushes = loadAllSavedBrushSettings();
    expect(savedBrushes['g-pen']?.pressureCurve).toBeUndefined();
    const effectiveGPen = getEffectiveBrushSettings('g-pen');
    expect(Number.isFinite(effectiveGPen.size)).toBe(true);

    const colorSetsState = createInitialColorSetsState();
    expect(colorSetsState.sets.length).toBeGreaterThan(0);
    expect(colorSetsState.activeSetId).toBeTruthy();

    // Also verify PressureCurveEditor, DockGroupView, and FloatingPanelWindow survive malformed props directly
    expect(() => {
      act(() => {
        root!.render(
          React.createElement(PressureCurveEditor, {
            value: undefined as unknown as Parameters<typeof PressureCurveEditor>[0]['value'],
            onChange: vi.fn(),
          })
        );
      });
    }).not.toThrow();

    const emptyGroup: DockGroup = {
      id: 'corrupt-grp',
      panelIds: [],
      activePanelId: '' as unknown as DockGroup['activePanelId'],
      heightRatio: 1,
    };
    const emptyCol: DockColumn = {
      id: 'corrupt-col',
      width: 240,
      collapsed: false,
      groups: [emptyGroup],
    };
    expect(() => {
      act(() => {
        root!.render(
          React.createElement(DockGroupView, {
            side: 'left',
            col: emptyCol,
            group: emptyGroup,
            groupIndex: 0,
            themePreset: 'modern',
            draggingPanelId: null,
            onStartDragPanel: vi.fn(),
            onEndDragPanel: vi.fn(),
            renderPanelBody: () => null,
          })
        );
      });
    }).not.toThrow();

    const emptyFloating: FloatingPanelState = {
      id: 'corrupt-float',
      panelIds: [],
      activePanelId: '' as unknown as FloatingPanelState['activePanelId'],
      x: 80,
      y: 80,
      width: 220,
      height: 220,
      collapsed: false,
      zIndex: 1,
    };
    expect(() => {
      act(() => {
        root!.render(
          React.createElement(FloatingPanelWindow, {
            panel: emptyFloating,
            isDragging: false,
            isDockTargetActive: false,
            isMergeTabTarget: false,
            renderPanelBody: () => null,
            renderPanelIcon,
            onStartHeaderDrag: vi.fn(),
            onStartTabDrag: vi.fn(),
          })
        );
      });
    }).not.toThrow();

    // 2. Corrupt primaryColor in tool store & mount DocumentLifecycleManager, then trigger handleCreateNewCanvas
    useToolStore.setState({ primaryColor: 'not-a-hex' });
    let lifecycleApi: ReturnType<typeof useDocumentLifecycle> | null = null;
    const params: UseDocumentLifecycleParams = {
      layers: [baseLayer],
      activeLayer: baseLayer,
      activeLayerId: 'layer-1',
      getEffectiveOpacity: () => 1,
      isLayerEffectivelyVisible: () => true,
      setActiveLayerId: vi.fn(),
      resetToNewCanvas: vi.fn(() => ({ layers: [baseLayer], activeLayerId: 'layer-1' })),
      setDefaultToneFrequency: vi.fn(),
      clearDocument: vi.fn(),
      loadDocument: vi.fn(),
      switchDocumentSession: vi.fn(),
      resizeCanvas: vi.fn(),
      copyLayer: vi.fn(() => null),
      pasteLayer: vi.fn(async () => ({ success: false })),
      deleteLayer: vi.fn(),
      pasteLayerFromFile: vi.fn(async () => 'Pasted'),
      resetZoomAndCenter: vi.fn(),
      resetHistory: vi.fn(),
      pushHistoryStep: vi.fn(),
      showToast: vi.fn(),
    };

    function Harness() {
      lifecycleApi = useDocumentLifecycle(params);
      return null;
    }

    act(() => {
      root!.render(React.createElement(Harness));
    });

    expect(() => {
      act(() => {
        lifecycleApi!.handleCreateNewCanvas({
          name: 'Corrupt Test',
          width: 1920,
          height: 1080,
          dpi: 300,
          backgroundColor: '#zzzzzz',
          colorMode: 'monochrome',
          aspectRatioPreset: 'custom',
          aspectRatioX: 16,
          aspectRatioY: 9,
          lockAspectRatio: false,
        });
      });
    }).not.toThrow();

    // Also test with undefined/missing primaryColor & partial malformed NewCanvasOptions
    useToolStore.setState({ primaryColor: undefined as unknown as string });
    expect(() => {
      act(() => {
        lifecycleApi!.handleCreateNewCanvas({
          name: '',
          width: Number.NaN,
          height: -5,
          dpi: 0,
          backgroundColor: undefined as unknown as string,
          colorMode: 'grayscale',
        } as unknown as NewCanvasOptions);
      });
    }).not.toThrow();

    expect(useUiStore.getState().appView).toBe('workspace');
    expect(useDocumentStore.getState().documents).toHaveLength(2);
    expect(useDocumentStore.getState().activeDocumentId).toBe(
      useDocumentStore.getState().documents[1].id
    );

    // Restore clean primaryColor
    toolStoreActions.setPrimaryColor('#000000', false, 'color');
  });

  it('guards curve LUTs, pressure curves, color utilities, native bridge, toolConfigs, stores, and NavigatorPanel against undefined/malformed [0] inputs', async () => {
    // brushMath & pressureCurve
    expect(getCompiledCurveLut([undefined as unknown as [number, number]])).toBeNull();
    expect(getCompiledCurveLut('bad' as unknown as [number, number][])).toBeNull();
    expect(evaluateFastSpline(0.5, [null as unknown as [number, number]])).toBe(0.5);
    expect(
      isLinearPressureCurve([
        undefined as unknown as [number, number],
        undefined as unknown as [number, number],
      ])
    ).toBe(true);
    expect(sanitizePressureCurvePoints([undefined as unknown as [number, number]])).toEqual([
      [0, 0],
      [1, 1],
    ]);
    expect(normalizePressureCurve(undefined).points).toEqual([
      [0, 0],
      [1, 1],
    ]);

    // colorUtils & nativeEngineBridge
    expect(parseRgba(undefined as unknown as string)).toEqual([0, 0, 0, 1]);
    expect(enforceColorMode(undefined as unknown as string, 'monochrome')).toBe('#000000');
    expect(hexToRgb(undefined as unknown as string)).toEqual({ r: 0, g: 0, b: 0 });
    expect(isValidHex(undefined as unknown as string)).toBe(false);
    expect(parseCssColorToRgba(undefined)).toEqual([0.086, 0.086, 0.086, 1.0]);
    expect(parseCssColorToRgba(123 as unknown as string)).toEqual([0.086, 0.086, 0.086, 1.0]);

    const payload = await buildNativeBrushConfigPayload(
      'brush',
      {
        size: Number.NaN,
        pressureCurve: [undefined as unknown as [number, number]],
        subTips: [undefined as unknown as NonNullable<BrushSettings['subTips']>[number]],
      } as Partial<BrushSettings>,
      '#zzzzzz',
      undefined as unknown as string
    );
    expect(Array.isArray(payload.fgColor)).toBe(true);
    expect(Array.isArray(payload.bgColor)).toBe(true);
    expect(payload.pressureCurve).toBeNull();

    await expect(
      syncNativeFullBrushConfig('brush', undefined, '#000000', '#ffffff')
    ).resolves.toBeUndefined();
    await expect(
      setNativePressureCurve({
        enabled: true,
        preset: 'custom',
        points: [undefined as unknown as [number, number]],
      })
    ).resolves.toBeUndefined();
    await expect(
      createNativeDocument({
        docId: 'doc-test',
        name: 'Test',
        dimensions: { width: 800, height: 600, dpi: 300 },
      })
    ).resolves.toBeNull();

    // toolConfigs
    expect(buildMonotonicCubicSplineLut([undefined as unknown as [number, number]]).length).toBe(256);
    expect(buildGradientMapLut([null as unknown as { position: number; color: string }]).length).toBe(
      256 * 4
    );
    expect(
      resolveGradientStops(
        { stops: [] } as unknown as Parameters<typeof resolveGradientStops>[0],
        '#000000',
        '#ffffff'
      ).length
    ).toBeGreaterThanOrEqual(2);
    expect(
      createDefaultGradientMesh(
        { x: 0, y: 0, width: 100, height: 100 },
        2,
        2,
        '#000000',
        '#ffffff',
        [undefined as unknown as NonNullable<Parameters<typeof createDefaultGradientMesh>[5]>[number]]
      ).nodes.length
    ).toBe(4);

    // AutoAction store when sets are empty
    autoActionStoreActions.replaceSets([]);
    expect(useAutoActionStore.getState().sets).toEqual([]);
    const createdAction = autoActionStoreActions.createAction('Safe Action');
    expect(createdAction.name).toBe('Safe Action');
    expect(useAutoActionStore.getState().sets.length).toBe(1);

    // NavigatorPanel quad helpers
    const quad = computeViewportQuadInDoc(
      800,
      600,
      { pan: { x: 0, y: 0 }, zoom: 1, rotation: 0, flipX: false, flipY: false },
      { width: 1000, height: 1000, dpi: 300 }
    );
    expect(quad).toHaveLength(4);
    expect(
      isPointInConvexQuad(
        { x: 10, y: 10 },
        [] as unknown as Parameters<typeof isPointInConvexQuad>[1]
      )
    ).toBe(false);
  });

  it('renders ErrorBoundary with collapsible error stack, componentStack, and Copy Error Details button', () => {
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});

    function CrashingChild(): React.ReactElement {
      throw new TypeError("Cannot read properties of undefined (reading '0')");
    }

    try {
      act(() => {
        root!.render(
          React.createElement(ErrorBoundary, null, React.createElement(CrashingChild))
        );
      });

      const renderedText = container!.textContent;
      expect(renderedText).toContain('Graphics Editor Encountered an Error');
      expect(renderedText).toContain("Cannot read properties of undefined (reading '0')");
      expect(renderedText).toContain('Copy Error Details');
      expect(container!.findAllByTag('details').length).toBe(1);
      expect(renderedText).toContain('CrashingChild');
    } finally {
      errorSpy.mockRestore();
    }
  });
});