Skip to content

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

34.9 KB
Raw Blame
import {
  ToolType,
  BrushSettings,
  BrushPresetId,
  CanvasColorMode,
  WandSettings,
  FillSettings,
  TextSettings,
  FrameSettings,
  BalloonSettings,
  VectorEditSettings,
  LiquifySettings,
  ShapeSettings,
  GradientSettings,
  GradientMeshState,
  RetouchSettings,
  PenToolSettings,
  Point2D,
} from '../types/editor';
import { DEFAULT_SHAPE_SETTINGS } from '../utils/shapeEngine';
import {
  DEFAULT_GRADIENT_SETTINGS,
  DEFAULT_RETOUCH_SETTINGS,
  getSelectedMeshNodeIndices,
  invertGradientMeshSelection,
  rotateGradientMeshVertices,
  selectAllGradientMeshNodes,
  setGradientMeshRotation,
  setGradientMeshSelection,
  updateGradientMeshNodes,
} from '../utils/toolConfigs';
import {
  DEFAULT_TEXT_SETTINGS,
  extractPersistableTextStyle,
  loadInitialTextSettings,
  saveTextSettings,
} from '../utils/textSettings';
import {
  saveBrushSettingsDebounced,
  getEffectiveBrushSettings,
  getActivePresetId,
  saveActivePresetId,
  getActiveDecorationPresetId,
  saveActiveDecorationPresetId,
  ERASER_PRESET_ID,
  DEFAULT_BRUSH_PRESET_ID,
} from '../utils/brushPresetManager';
import {
  DEFAULT_DECORATION_PRESET_ID,
  prewarmDecorationBrushAssets,
} from '../utils/presetBrushes';
import { enforceColorMode, isValidHex } from '../utils/colorUtils';
import { safeLocalStorageGetItem, safeLocalStorageSetItem } from '../utils/safeStorage';
import { createStore } from './createStore';
import { useDocumentStore } from './useDocumentStore';
import { uiStoreActions } from './useUiStore';
import { store3DActions } from './use3DStore';

export interface QuickModifiersState {
  isAltActive: boolean;
  isSpaceDown: boolean;
  isShiftDown: boolean;
  isRotateModifier: boolean;
}

export interface ToolStoreState {
  tool: ToolType;
  activePresetId: BrushPresetId;
  activeBrushPresetId: BrushPresetId;
  activeDecorationPresetId: BrushPresetId;
  lastPaintTool: 'brush' | 'decoration';
  brushSettings: BrushSettings;
  lastBrushSettings: BrushSettings | null;
  lastDecorationSettings: BrushSettings | null;
  primaryColor: string;
  secondaryColor: string;
  isTransparentColor: boolean;
  recentColors: string[];
  quickModifiers: QuickModifiersState;
  wandSettings: WandSettings;
  fillSettings: FillSettings;
  textSettings: TextSettings;
  frameSettings: FrameSettings;
  balloonSettings: BalloonSettings;
  vectorEditSettings: VectorEditSettings;
  liquifySettings: LiquifySettings;
  shapeSettings: ShapeSettings;
  gradientSettings: GradientSettings;
  retouchSettings: RetouchSettings;
  penSettings: PenToolSettings;
  activeGradientMesh: GradientMeshState | null;
  isPickingCloneSource: boolean;
  cloneSourceAnchor: Point2D | null;
  activePenPointCount: number;
  activePenClosed: boolean;
  activePenSelectedAnchor: number | null;
}

export const COLOR_HISTORY_STORAGE_KEY = 'ink_studio_color_history_v1';
export const MAX_COLOR_HISTORY = 96;

const DEFAULT_RECENT_COLORS = [
  '#000000',
  '#3b82f6',
  '#ef4444',
  '#10b981',
  '#f59e0b',
  '#ffffff',
];

function normalizeHistoryHex(color: unknown): string | null {
  if (typeof color !== 'string') return null;
  const trimmed = color.trim();
  if (!isValidHex(trimmed)) return null;
  const bare = trimmed.startsWith('#') ? trimmed.slice(1) : trimmed;
  if (bare.length === 3) {
    return `#${bare[0]}${bare[0]}${bare[1]}${bare[1]}${bare[2]}${bare[2]}`.toLowerCase();
  }
  return `#${bare.slice(0, 6)}`.toLowerCase();
}

function loadInitialRecentColors(): string[] {
  try {
    const raw = safeLocalStorageGetItem(COLOR_HISTORY_STORAGE_KEY);
    if (raw === null) return [...DEFAULT_RECENT_COLORS];
    const parsed = JSON.parse(raw);
    if (!Array.isArray(parsed)) return [...DEFAULT_RECENT_COLORS];
    const seen = new Set<string>();
    const out: string[] = [];
    for (const item of parsed) {
      const hex = normalizeHistoryHex(item);
      if (hex && !seen.has(hex)) {
        seen.add(hex);
        out.push(hex);
        if (out.length >= MAX_COLOR_HISTORY) break;
      }
    }
    return out;
  } catch {
    return [...DEFAULT_RECENT_COLORS];
  }
}

function persistRecentColors(colors: string[]): void {
  safeLocalStorageSetItem(COLOR_HISTORY_STORAGE_KEY, JSON.stringify(colors), 'color history');
}

function pushColorHistory(prev: string[], rawColor: string): { list: string[]; changed: boolean } {
  const safePrev = Array.isArray(prev) ? prev.filter((c): c is string => typeof c === 'string') : [];
  const normalized = normalizeHistoryHex(rawColor);
  if (!normalized) return { list: safePrev, changed: false };
  if (safePrev.length > 0 && safePrev[0].toLowerCase() === normalized) {
    return { list: safePrev, changed: false };
  }
  const filtered = safePrev.filter((c) => c.toLowerCase() !== normalized);
  return {
    list: [normalized, ...filtered].slice(0, MAX_COLOR_HISTORY),
    changed: true,
  };
}

function createInitialBrushSettings(): { presetId: BrushPresetId; brushSettings: BrushSettings } {
  const activePreset = getActivePresetId();
  const effective = getEffectiveBrushSettings(activePreset);
  const resolvedPreset = (effective.preset || activePreset || DEFAULT_BRUSH_PRESET_ID) as BrushPresetId;
  return {
    presetId: resolvedPreset,
    brushSettings: {
      preset: resolvedPreset,
      size: effective.size ?? 8,
      minSizeFactor: effective.minSizeFactor ?? 0.04,
      color: '#000000',
      secondaryColor: '#ffffff',
      opacity: effective.opacity ?? 1.0,
      flow: effective.flow ?? 1.0,
      spacing: effective.spacing ?? 0.04,
      grain: effective.grain ?? 0,
      usePressure: effective.usePressure ?? true,
      smoothing: effective.smoothing ?? true,
      stabilization: effective.stabilization ?? 20,
      hardness: effective.hardness ?? 1.0,
      ...effective,
    } as BrushSettings,
  };
}

function loadInitialLiquifySettings(): LiquifySettings {
  const defaults: LiquifySettings = {
    mode: 'push',
    size: 80,
    strength: 50,
    hardness: 50,
    usePressure: true,
    multiLayer: false,
  };
  try {
    if (typeof localStorage !== 'undefined') {
      const saved = localStorage.getItem('ink_studio_liquify_settings');
      if (saved) {
        const parsed = JSON.parse(saved);
        if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
          return { ...defaults, ...(parsed as Partial<LiquifySettings>) };
        }
      }
    }
  } catch {
    // Ignore storage errors
  }
  return defaults;
}

function loadInitialShapeSettings(): ShapeSettings {
  try {
    if (typeof localStorage !== 'undefined') {
      const saved = localStorage.getItem('ink_studio_shape_settings');
      if (saved) {
        const parsed = JSON.parse(saved);
        if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
          return { ...DEFAULT_SHAPE_SETTINGS, ...(parsed as Partial<ShapeSettings>) };
        }
      }
    }
  } catch {
    // Ignore storage errors
  }
  return { ...DEFAULT_SHAPE_SETTINGS };
}

const DEFAULT_PEN_SETTINGS: PenToolSettings = {
  mode: 'draw',
  strokeWidth: 4,
  opacity: 1,
  strokeEnabled: true,
  fillEnabled: false,
  fillColorMode: 'secondary',
  customFillColor: '#ffffff',
  rubberBandPreview: true,
};

function loadInitialGradientSettings(): GradientSettings {
  try {
    if (typeof localStorage !== 'undefined') {
      const saved = localStorage.getItem('ink_studio_gradient_settings');
      if (saved) {
        const parsed = JSON.parse(saved);
        if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
          const rec = parsed as Partial<GradientSettings>;
          const validStops = Array.isArray(rec.stops)
            ? rec.stops.filter(
                (s): s is GradientSettings['stops'][number] =>
                  Boolean(s) &&
                  typeof s === 'object' &&
                  typeof s.color === 'string' &&
                  typeof s.offset === 'number' &&
                  Number.isFinite(s.offset)
              )
            : [];
          return {
            ...DEFAULT_GRADIENT_SETTINGS,
            ...rec,
            stops:
              validStops.length >= 2
                ? validStops
                : DEFAULT_GRADIENT_SETTINGS.stops.map((s) => ({ ...s })),
          };
        }
      }
    }
  } catch {
    // Ignore storage errors
  }
  return {
    ...DEFAULT_GRADIENT_SETTINGS,
    stops: DEFAULT_GRADIENT_SETTINGS.stops.map((s) => ({ ...s })),
  };
}

function loadInitialRetouchSettings(): RetouchSettings {
  try {
    if (typeof localStorage !== 'undefined') {
      const saved = localStorage.getItem('ink_studio_retouch_settings');
      if (saved) {
        const parsed = JSON.parse(saved);
        if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
          return { ...DEFAULT_RETOUCH_SETTINGS, ...(parsed as Partial<RetouchSettings>) };
        }
      }
    }
  } catch {
    // Ignore storage errors
  }
  return { ...DEFAULT_RETOUCH_SETTINGS };
}

function loadInitialPenSettings(): PenToolSettings {
  try {
    if (typeof localStorage !== 'undefined') {
      const saved = localStorage.getItem('ink_studio_pen_settings');
      if (saved) {
        const parsed = JSON.parse(saved);
        if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
          return { ...DEFAULT_PEN_SETTINGS, ...(parsed as Partial<PenToolSettings>) };
        }
      }
    }
  } catch {
    // Ignore storage errors
  }
  return { ...DEFAULT_PEN_SETTINGS };
}

const createInitialToolState = (): ToolStoreState => {
  const { presetId, brushSettings } = createInitialBrushSettings();
  const decorationPresetId = getActiveDecorationPresetId();
  return {
    tool: 'brush',
    activePresetId: presetId,
    activeBrushPresetId: presetId,
    activeDecorationPresetId: decorationPresetId,
    lastPaintTool: 'brush',
    brushSettings,
    lastBrushSettings: brushSettings,
    lastDecorationSettings: null,
    primaryColor: '#000000',
    secondaryColor: '#ffffff',
    isTransparentColor: false,
    recentColors: loadInitialRecentColors(),
    quickModifiers: {
      isAltActive: false,
      isSpaceDown: false,
      isShiftDown: false,
      isRotateModifier: false,
    },
    wandSettings: {
      tolerance: 32,
      contiguous: true,
      antiAlias: true,
      referMode: 'active',
    },
    fillSettings: {
      method: 'refer-all',
      tolerance: 32,
      opacity: 1,
      smartReferMode: 'refer-reference',
      encloseTarget: 'all-enclosed',
      smartCloseGap: 10,
      smartAreaScale: 1,
      brushSize: 24,
    },
    textSettings: loadInitialTextSettings(),
    frameSettings: {
      mode: 'create',
      divideMode: 'same-folder',
      thickness: 4,
      fillBackground: true,
      fillColor: '#ffffff',
      strokeColor: '#000000',
      gutterVerticalMm: 3.0,
      gutterHorizontalMm: 5.0,
    },
    balloonSettings: {
      shape: 'ellipse',
      fillColor: '#ffffff',
      strokeColor: '#000000',
      strokeWidth: 3,
      text: '',
      fontFamily: "'Neucha', 'Anime Ace', 'Comic Sans MS', sans-serif",
      fontSize: 22,
      vertical: false,
    },
    vectorEditSettings: {
      mode: 'pinch',
      radius: 35,
      pinchStrength: 1.0,
      widthFactor: 1.5,
      simplifyTolerance: 2.0,
    },
    liquifySettings: loadInitialLiquifySettings(),
    shapeSettings: loadInitialShapeSettings(),
    gradientSettings: loadInitialGradientSettings(),
    retouchSettings: loadInitialRetouchSettings(),
    penSettings: loadInitialPenSettings(),
    activeGradientMesh: null,
    isPickingCloneSource: false,
    cloneSourceAnchor: null,
    activePenPointCount: 0,
    activePenClosed: false,
    activePenSelectedAnchor: null,
  };
};

export const useToolStore = createStore<ToolStoreState>(createInitialToolState);

function isValidBrushPresetId(presetId?: string | null): presetId is BrushPresetId {
  return Boolean(presetId && presetId !== ERASER_PRESET_ID && presetId !== 'eraser');
}

function resolveBrushPresetId(state: ToolStoreState): BrushPresetId {
  if (isValidBrushPresetId(state.activeBrushPresetId)) {
    return state.activeBrushPresetId;
  }
  if (state.tool !== 'decoration' && isValidBrushPresetId(state.activePresetId)) {
    return state.activePresetId;
  }
  if (isValidBrushPresetId(state.lastBrushSettings?.preset)) {
    return state.lastBrushSettings.preset;
  }
  return getActivePresetId();
}

function resolveDecorationPresetId(state: ToolStoreState): BrushPresetId {
  if (isValidBrushPresetId(state.activeDecorationPresetId)) {
    return state.activeDecorationPresetId;
  }
  if (state.tool === 'decoration' && isValidBrushPresetId(state.activePresetId)) {
    return state.activePresetId;
  }
  if (isValidBrushPresetId(state.lastDecorationSettings?.preset)) {
    return state.lastDecorationSettings.preset;
  }
  return getActiveDecorationPresetId() || DEFAULT_DECORATION_PRESET_ID;
}

function resolveCurrentPaintPresetId(state: ToolStoreState): BrushPresetId {
  if (state.tool === 'decoration') {
    return resolveDecorationPresetId(state);
  }
  return resolveBrushPresetId(state);
}

function buildRestoredBrushSettings(
  state: ToolStoreState,
  presetId: BrushPresetId,
  snapshotOverride?: BrushSettings | null
): BrushSettings {
  const effective = getEffectiveBrushSettings(presetId);
  const candidateSnapshot =
    snapshotOverride !== undefined ? snapshotOverride : state.lastBrushSettings;
  const snapshot =
    candidateSnapshot && candidateSnapshot.preset === presetId
      ? candidateSnapshot
      : null;

  // If getEffectiveBrushSettings couldn't resolve a custom brush from storage/cache
  // and fell back to the default preset, restore the in-memory snapshot instead.
  if (snapshot && effective.preset !== presetId) {
    return {
      ...snapshot,
      preset: presetId,
      color: state.primaryColor,
      secondaryColor: state.secondaryColor,
      isTransparentInk: state.isTransparentColor,
    };
  }

  return {
    ...state.brushSettings,
    ...effective,
    preset: (effective.preset || presetId) as BrushPresetId,
    customTipImage: effective.customTipImage ?? snapshot?.customTipImage,
    dualTipImage: effective.dualTipImage ?? snapshot?.dualTipImage,
    paperTextureImage: effective.paperTextureImage ?? snapshot?.paperTextureImage,
    subTipImages: effective.subTipImages ?? snapshot?.subTipImages,
    color: state.primaryColor,
    secondaryColor: state.secondaryColor,
    isTransparentInk: state.isTransparentColor,
  };
}

export const toolStoreActions = {
  selectTool(newTool: ToolType): void {
    const state = useToolStore.getState();
    const prevTool = state.tool;
    if (newTool === '3d') {
      if (prevTool !== '3d') {
        store3DActions.setPreviousToolBefore3D(prevTool);
      }
      store3DActions.setReferenceVisible(true);
      if (useDocumentStore.getState().documents.length > 0) {
        uiStoreActions.set3DLayerOpen(true);
      }
    }
    if (prevTool === newTool) return;

    const savedBrushSettings =
      prevTool === 'brush' && isValidBrushPresetId(state.brushSettings.preset)
        ? state.brushSettings
        : state.lastBrushSettings;
    const savedDecoSettings =
      prevTool === 'decoration' && isValidBrushPresetId(state.brushSettings.preset)
        ? state.brushSettings
        : state.lastDecorationSettings;
    const nextLastPaintTool: 'brush' | 'decoration' =
      prevTool === 'decoration'
        ? 'decoration'
        : prevTool === 'brush'
          ? 'brush'
          : state.lastPaintTool;

    if (newTool === 'eraser') {
      const preservedPresetId = resolveCurrentPaintPresetId(state);
      const eraserSettings = getEffectiveBrushSettings(ERASER_PRESET_ID);
      useToolStore.setState({
        tool: newTool,
        activePresetId: preservedPresetId,
        lastPaintTool: nextLastPaintTool,
        lastBrushSettings: savedBrushSettings,
        lastDecorationSettings: savedDecoSettings,
        brushSettings: {
          ...state.brushSettings,
          ...eraserSettings,
          preset: ERASER_PRESET_ID,
          color: state.primaryColor,
          secondaryColor: state.secondaryColor,
          isTransparentInk: state.isTransparentColor,
        },
      });
      return;
    }

    if (newTool === 'decoration') {
      prewarmDecorationBrushAssets();
      const decoPreset = resolveDecorationPresetId(state);
      const restoredDeco = buildRestoredBrushSettings(state, decoPreset, savedDecoSettings);
      const resolvedDecoId = (restoredDeco.preset || decoPreset) as BrushPresetId;
      useToolStore.setState({
        tool: 'decoration',
        activePresetId: resolvedDecoId,
        activeDecorationPresetId: resolvedDecoId,
        lastPaintTool: 'decoration',
        brushSettings: restoredDeco,
        lastBrushSettings: savedBrushSettings,
        lastDecorationSettings: restoredDeco,
      });
      return;
    }

    if (newTool === 'brush') {
      const brushPreset = resolveBrushPresetId(state);
      const restoredBrush = buildRestoredBrushSettings(state, brushPreset, savedBrushSettings);
      const resolvedBrushId = (restoredBrush.preset || brushPreset) as BrushPresetId;
      useToolStore.setState({
        tool: 'brush',
        activePresetId: resolvedBrushId,
        activeBrushPresetId: resolvedBrushId,
        lastPaintTool: 'brush',
        brushSettings: restoredBrush,
        lastBrushSettings: restoredBrush,
        lastDecorationSettings: savedDecoSettings,
      });
      return;
    }

    const needsBrushRestore =
      prevTool === 'eraser' ||
      state.brushSettings.preset === ERASER_PRESET_ID ||
      state.brushSettings.preset === 'eraser';

    if (needsBrushRestore) {
      const targetIsDeco = nextLastPaintTool === 'decoration';
      const activePreset = targetIsDeco
        ? resolveDecorationPresetId(state)
        : resolveBrushPresetId(state);
      const restored = buildRestoredBrushSettings(
        state,
        activePreset,
        targetIsDeco ? savedDecoSettings : savedBrushSettings
      );
      const resolvedId = (restored.preset || activePreset) as BrushPresetId;
      useToolStore.setState({
        tool: newTool,
        activePresetId: resolvedId,
        lastPaintTool: nextLastPaintTool,
        brushSettings: restored,
        lastBrushSettings: targetIsDeco ? savedBrushSettings : restored,
        lastDecorationSettings: targetIsDeco ? restored : savedDecoSettings,
      });
      return;
    }

    useToolStore.setState({
      tool: newTool,
      lastPaintTool: nextLastPaintTool,
      lastBrushSettings: savedBrushSettings,
      lastDecorationSettings: savedDecoSettings,
    });
  },

  setToolRaw(tool: ToolType): void {
    useToolStore.setState({ tool });
  },

  updateBrushSettings(newSettings: Partial<BrushSettings>): void {
    const state = useToolStore.getState();
    const isEraser = state.tool === 'eraser';
    const isDeco = state.tool === 'decoration';
    const next: BrushSettings = { ...state.brushSettings, ...newSettings };
    const nextValidPreset = isValidBrushPresetId(next.preset) ? next.preset : null;
    const targetPresetId = isEraser
      ? ERASER_PRESET_ID
      : nextValidPreset || resolveCurrentPaintPresetId(state);
    const isEphemeralShared =
      typeof targetPresetId === 'string' && targetPresetId.startsWith('collab-shared-');

    if (!isEphemeralShared) {
      saveBrushSettingsDebounced(targetPresetId, next);
      if (!isEraser && nextValidPreset) {
        if (isDeco) {
          saveActiveDecorationPresetId(nextValidPreset);
        } else if (state.tool === 'brush') {
          saveActivePresetId(nextValidPreset);
        }
      }
    }

    useToolStore.setState({
      brushSettings: next,
      activePresetId:
        !isEraser && nextValidPreset && (state.tool === 'brush' || isDeco)
          ? nextValidPreset
          : state.activePresetId,
      activeBrushPresetId:
        !isEraser && nextValidPreset && state.tool === 'brush'
          ? nextValidPreset
          : state.activeBrushPresetId,
      activeDecorationPresetId:
        !isEraser && nextValidPreset && isDeco
          ? nextValidPreset
          : state.activeDecorationPresetId,
      lastBrushSettings:
        !isEraser && !isDeco && nextValidPreset ? next : state.lastBrushSettings,
      lastDecorationSettings:
        !isEraser && isDeco && nextValidPreset ? next : state.lastDecorationSettings,
    });
  },

  /**
   * Equips a brush grabbed/shared from a remote collaborative artist without modifying
   * or overwriting any of the local user's persisted built-in or custom brush presets.
   */
  applySharedBrush(
    settings: BrushSettings,
    targetTool: 'brush' | 'decoration' = 'brush'
  ): void {
    const state = useToolStore.getState();
    const presetId = (settings.preset || 'collab-shared-brush') as BrushPresetId;
    const nextSettings: BrushSettings = {
      ...settings,
      preset: presetId,
      color: state.primaryColor,
      secondaryColor: state.secondaryColor,
      isTransparentInk: state.isTransparentColor,
    };

    useToolStore.setState({
      tool: targetTool,
      activePresetId: presetId,
      activeBrushPresetId:
        targetTool === 'brush' ? presetId : state.activeBrushPresetId,
      activeDecorationPresetId:
        targetTool === 'decoration' ? presetId : state.activeDecorationPresetId,
      lastPaintTool: targetTool,
      brushSettings: nextSettings,
      lastBrushSettings:
        targetTool === 'brush' ? nextSettings : state.lastBrushSettings,
      lastDecorationSettings:
        targetTool === 'decoration' ? nextSettings : state.lastDecorationSettings,
    });
  },

  addRecentColor(color: string): void {
    const state = useToolStore.getState();
    const { list, changed } = pushColorHistory(state.recentColors, color);
    if (!changed) return;
    useToolStore.setState({ recentColors: list });
    persistRecentColors(list);
  },

  removeRecentColor(color: string): void {
    const normalized = normalizeHistoryHex(color);
    if (!normalized) return;
    const state = useToolStore.getState();
    const next = state.recentColors.filter((c) => c.toLowerCase() !== normalized);
    if (next.length === state.recentColors.length) return;
    useToolStore.setState({ recentColors: next });
    persistRecentColors(next);
  },

  clearRecentColors(): void {
    const state = useToolStore.getState();
    if (state.recentColors.length === 0) {
      persistRecentColors([]);
      return;
    }
    useToolStore.setState({ recentColors: [] });
    persistRecentColors([]);
  },

  setPrimaryColor(color: string, commit = true, colorModeOverride?: CanvasColorMode): void {
    const mode = colorModeOverride ?? useDocumentStore.getState().colorMode;
    const effective = enforceColorMode(color, mode);
    const state = useToolStore.getState();
    const isEraser = state.tool === 'eraser';
    const isDeco = state.tool === 'decoration';

    const nextBrush: BrushSettings = {
      ...state.brushSettings,
      color: effective,
      isTransparentInk: false,
    };
    const targetPresetId = isEraser
      ? ERASER_PRESET_ID
      : isValidBrushPresetId(nextBrush.preset)
        ? nextBrush.preset
        : resolveCurrentPaintPresetId(state);
    if (typeof targetPresetId !== 'string' || !targetPresetId.startsWith('collab-shared-')) {
      saveBrushSettingsDebounced(targetPresetId, nextBrush);
    }

    const historyResult = commit
      ? pushColorHistory(state.recentColors, effective)
      : { list: state.recentColors, changed: false };
    const nextRecent = historyResult.list;

    let nextActiveGradientMesh = state.activeGradientMesh;
    if (
      state.tool === 'gradient' &&
      state.gradientSettings.type === 'mesh' &&
      state.activeGradientMesh
    ) {
      const selectedMeshIndices = getSelectedMeshNodeIndices(state.activeGradientMesh);
      if (selectedMeshIndices.length > 0) {
        nextActiveGradientMesh = updateGradientMeshNodes(
          state.activeGradientMesh,
          selectedMeshIndices,
          { color: effective }
        );
      }
    }

    useToolStore.setState({
      primaryColor: effective,
      isTransparentColor: false,
      brushSettings: nextBrush,
      lastBrushSettings:
        !isEraser && !isDeco && isValidBrushPresetId(nextBrush.preset)
          ? nextBrush
          : state.lastBrushSettings,
      lastDecorationSettings:
        !isEraser && isDeco && isValidBrushPresetId(nextBrush.preset)
          ? nextBrush
          : state.lastDecorationSettings,
      recentColors: nextRecent,
      activeGradientMesh: nextActiveGradientMesh,
    });

    if (historyResult.changed) {
      persistRecentColors(nextRecent);
    }

    if (isEraser) {
      toolStoreActions.selectTool(state.lastPaintTool || 'brush');
    }
  },

  setSecondaryColor(color: string, commit = true, colorModeOverride?: CanvasColorMode): void {
    const mode = colorModeOverride ?? useDocumentStore.getState().colorMode;
    const effective = enforceColorMode(color, mode);
    const state = useToolStore.getState();
    const isEraser = state.tool === 'eraser';
    const isDeco = state.tool === 'decoration';

    const nextBrush: BrushSettings = {
      ...state.brushSettings,
      secondaryColor: effective,
    };
    const targetPresetId = isEraser
      ? ERASER_PRESET_ID
      : isValidBrushPresetId(nextBrush.preset)
        ? nextBrush.preset
        : resolveCurrentPaintPresetId(state);
    if (typeof targetPresetId !== 'string' || !targetPresetId.startsWith('collab-shared-')) {
      saveBrushSettingsDebounced(targetPresetId, nextBrush);
    }

    const historyResult = commit
      ? pushColorHistory(state.recentColors, effective)
      : { list: state.recentColors, changed: false };
    const nextRecent = historyResult.list;

    useToolStore.setState({
      secondaryColor: effective,
      brushSettings: nextBrush,
      lastBrushSettings:
        !isEraser && !isDeco && isValidBrushPresetId(nextBrush.preset)
          ? nextBrush
          : state.lastBrushSettings,
      lastDecorationSettings:
        !isEraser && isDeco && isValidBrushPresetId(nextBrush.preset)
          ? nextBrush
          : state.lastDecorationSettings,
      recentColors: nextRecent,
    });

    if (historyResult.changed) {
      persistRecentColors(nextRecent);
    }
  },

  swapColors(colorModeOverride?: CanvasColorMode): void {
    const mode = colorModeOverride ?? useDocumentStore.getState().colorMode;
    const state = useToolStore.getState();
    const isEraser = state.tool === 'eraser';
    const isDeco = state.tool === 'decoration';
    const prevPrimary = state.primaryColor;
    const effectivePrimary = enforceColorMode(state.secondaryColor, mode);
    const nextBrush: BrushSettings = {
      ...state.brushSettings,
      color: effectivePrimary,
      secondaryColor: prevPrimary,
      isTransparentInk: false,
    };
    const targetPresetId = isEraser
      ? ERASER_PRESET_ID
      : isValidBrushPresetId(nextBrush.preset)
        ? nextBrush.preset
        : resolveCurrentPaintPresetId(state);
    if (typeof targetPresetId !== 'string' || !targetPresetId.startsWith('collab-shared-')) {
      saveBrushSettingsDebounced(targetPresetId, nextBrush);
    }

    const historyResult = pushColorHistory(state.recentColors, effectivePrimary);
    const nextRecent = historyResult.list;

    useToolStore.setState({
      primaryColor: effectivePrimary,
      secondaryColor: prevPrimary,
      isTransparentColor: false,
      brushSettings: nextBrush,
      lastBrushSettings:
        !isEraser && !isDeco && isValidBrushPresetId(nextBrush.preset)
          ? nextBrush
          : state.lastBrushSettings,
      lastDecorationSettings:
        !isEraser && isDeco && isValidBrushPresetId(nextBrush.preset)
          ? nextBrush
          : state.lastDecorationSettings,
      recentColors: nextRecent,
    });

    if (historyResult.changed) {
      persistRecentColors(nextRecent);
    }

    if (isEraser) {
      toolStoreActions.selectTool(state.lastPaintTool || 'brush');
    }
  },

  toggleTransparentColor(): boolean {
    const state = useToolStore.getState();
    const isEraser = state.tool === 'eraser';
    const isDeco = state.tool === 'decoration';
    const next = !state.isTransparentColor;
    const nextBrush: BrushSettings = {
      ...state.brushSettings,
      isTransparentInk: next,
    };
    const targetPresetId = isEraser
      ? ERASER_PRESET_ID
      : isValidBrushPresetId(nextBrush.preset)
        ? nextBrush.preset
        : resolveCurrentPaintPresetId(state);
    if (typeof targetPresetId !== 'string' || !targetPresetId.startsWith('collab-shared-')) {
      saveBrushSettingsDebounced(targetPresetId, nextBrush);
    }

    useToolStore.setState({
      isTransparentColor: next,
      brushSettings: nextBrush,
      lastBrushSettings:
        !isEraser && !isDeco && isValidBrushPresetId(nextBrush.preset)
          ? nextBrush
          : state.lastBrushSettings,
      lastDecorationSettings:
        !isEraser && isDeco && isValidBrushPresetId(nextBrush.preset)
          ? nextBrush
          : state.lastDecorationSettings,
    });
    return next;
  },

  resetDefaultColors(colorModeOverride?: CanvasColorMode): void {
    toolStoreActions.setPrimaryColor('#000000', true, colorModeOverride);
    toolStoreActions.setSecondaryColor('#ffffff', false, colorModeOverride);
  },

  setQuickModifiers(patch: Partial<QuickModifiersState>): void {
    useToolStore.setState((prev) => ({
      quickModifiers: { ...prev.quickModifiers, ...patch },
    }));
  },

  updateWandSettings(patch: Partial<WandSettings>): void {
    useToolStore.setState((prev) => ({
      wandSettings: { ...prev.wandSettings, ...patch },
    }));
  },

  updateFillSettings(patch: Partial<FillSettings>): void {
    useToolStore.setState((prev) => ({
      fillSettings: { ...prev.fillSettings, ...patch },
    }));
  },

  updateTextSettings(patch: Partial<TextSettings>): void {
    useToolStore.setState((prev) => {
      const sanitizedStyle = extractPersistableTextStyle(patch);
      const next: TextSettings = {
        ...prev.textSettings,
        ...sanitizedStyle,
        text: patch.text !== undefined ? patch.text : prev.textSettings.text,
      };
      saveTextSettings(next);
      return { textSettings: next };
    });
  },

  resetTextSettings(): void {
    const next: TextSettings = { ...DEFAULT_TEXT_SETTINGS };
    saveTextSettings(next);
    useToolStore.setState({ textSettings: next });
  },

  updateFrameSettings(patch: Partial<FrameSettings>): void {
    useToolStore.setState((prev) => ({
      frameSettings: { ...prev.frameSettings, ...patch },
    }));
  },

  updateBalloonSettings(patch: Partial<BalloonSettings>): void {
    useToolStore.setState((prev) => ({
      balloonSettings: { ...prev.balloonSettings, ...patch },
    }));
  },

  updateVectorEditSettings(patch: Partial<VectorEditSettings>): void {
    useToolStore.setState((prev) => ({
      vectorEditSettings: { ...prev.vectorEditSettings, ...patch },
    }));
  },

  updateLiquifySettings(patch: Partial<LiquifySettings>): void {
    useToolStore.setState((prev) => {
      const next = { ...prev.liquifySettings, ...patch };
      safeLocalStorageSetItem('ink_studio_liquify_settings', JSON.stringify(next), 'liquify settings');
      return { liquifySettings: next };
    });
  },

  updateShapeSettings(patch: Partial<ShapeSettings>): void {
    useToolStore.setState((prev) => {
      const next = { ...prev.shapeSettings, ...patch };
      safeLocalStorageSetItem('ink_studio_shape_settings', JSON.stringify(next), 'shape settings');
      return { shapeSettings: next };
    });
  },

  updateGradientSettings(patch: Partial<GradientSettings>): void {
    useToolStore.setState((prev) => {
      const next = { ...prev.gradientSettings, ...patch };
      safeLocalStorageSetItem('ink_studio_gradient_settings', JSON.stringify(next), 'gradient settings');
      return { gradientSettings: next };
    });
  },

  updateRetouchSettings(patch: Partial<RetouchSettings>): void {
    useToolStore.setState((prev) => {
      const next = { ...prev.retouchSettings, ...patch };
      safeLocalStorageSetItem('ink_studio_retouch_settings', JSON.stringify(next), 'retouch settings');
      return { retouchSettings: next };
    });
  },

  updatePenSettings(patch: Partial<PenToolSettings>): void {
    useToolStore.setState((prev) => {
      const next = { ...prev.penSettings, ...patch };
      safeLocalStorageSetItem('ink_studio_pen_settings', JSON.stringify(next), 'pen settings');
      return { penSettings: next };
    });
  },

  setActiveGradientMesh(
    updater:
      | GradientMeshState
      | null
      | ((prev: GradientMeshState | null) => GradientMeshState | null)
  ): void {
    useToolStore.setState((prev) => ({
      activeGradientMesh:
        typeof updater === 'function' ? updater(prev.activeGradientMesh) : updater,
    }));
  },

  updateActiveGradientMeshNode(index: number, patch: { color?: string; opacity?: number }): void {
    toolStoreActions.updateActiveGradientMeshNodes([index], patch);
  },

  updateActiveGradientMeshNodes(
    indices: readonly number[],
    patch: { color?: string; opacity?: number }
  ): void {
    useToolStore.setState((prev) => {
      const mesh = prev.activeGradientMesh;
      if (!mesh || indices.length === 0) return prev;
      const updated = updateGradientMeshNodes(mesh, indices, patch);
      return updated === mesh ? prev : { activeGradientMesh: updated };
    });
  },

  rotateActiveGradientMesh(deltaDeg: number): void {
    useToolStore.setState((prev) => {
      const mesh = prev.activeGradientMesh;
      if (!mesh) return prev;
      return { activeGradientMesh: rotateGradientMeshVertices(mesh, deltaDeg) };
    });
  },

  setActiveGradientMeshRotation(targetDeg: number): void {
    useToolStore.setState((prev) => {
      const mesh = prev.activeGradientMesh;
      if (!mesh) return prev;
      return { activeGradientMesh: setGradientMeshRotation(mesh, targetDeg) };
    });
  },

  selectAllActiveGradientMeshNodes(): void {
    useToolStore.setState((prev) => {
      const mesh = prev.activeGradientMesh;
      if (!mesh) return prev;
      return { activeGradientMesh: selectAllGradientMeshNodes(mesh) };
    });
  },

  clearActiveGradientMeshSelection(): void {
    useToolStore.setState((prev) => {
      const mesh = prev.activeGradientMesh;
      if (!mesh) return prev;
      return { activeGradientMesh: setGradientMeshSelection(mesh, []) };
    });
  },

  invertActiveGradientMeshSelection(): void {
    useToolStore.setState((prev) => {
      const mesh = prev.activeGradientMesh;
      if (!mesh) return prev;
      return { activeGradientMesh: invertGradientMeshSelection(mesh) };
    });
  },

  setIsPickingCloneSource(picking: boolean): void {
    useToolStore.setState({ isPickingCloneSource: picking });
  },

  setCloneSourceAnchor(anchor: Point2D | null): void {
    useToolStore.setState({ cloneSourceAnchor: anchor });
  },

  setActivePenSessionMeta(
    pointCount: number,
    closed: boolean,
    selectedAnchor: number | null
  ): void {
    useToolStore.setState({
      activePenPointCount: pointCount,
      activePenClosed: closed,
      activePenSelectedAnchor: selectedAnchor,
    });
  },
};

export interface InteractiveToolActionsBridge {
  initGradientMesh?: () => void;
  applyGradientMesh?: () => void;
  cancelGradientMesh?: () => void;
  commitPenPath?: () => void;
  cancelPenPath?: () => void;
  toggleClosePenPath?: () => void;
  deleteSelectedPenAnchor?: () => void;
  toggleSelectedPenAnchorSmooth?: () => void;
}

export const interactiveToolBridge: InteractiveToolActionsBridge = {};