Skip to content

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

10.1 KB
Raw Blame
import {
  CanvasDimensions,
  CanvasColorMode,
  DocumentStateDelta,
  DocumentTab,
  SoftProofSettings,
  DEFAULT_SOFT_PROOF_SETTINGS,
  CmykStandard,
  AnimationTimeline,
} from '../types/editor';
import { PerspectiveRuler, StraightRuler, ConstraintAxis } from '../types/perspective';
import { createDefaultStraightRuler } from '../utils/straightRulerMath';
import { SavedFileInfo } from '../utils/saveManager';
import { createStore } from './createStore';

export const INITIAL_CANVAS_DIMENSIONS: CanvasDimensions = {
  width: 1440,
  height: 900,
  dpi: 300,
};

export interface DocumentStoreState {
  documents: DocumentTab[];
  activeDocumentId: string | null;
  dimensions: CanvasDimensions;
  colorMode: CanvasColorMode;
  documentName: string;
  activeLayerId: string;
  activeEditTarget: 'layer' | 'mask';
  savedFileInfo: SavedFileInfo | null;
  softProofSettings: SoftProofSettings;
  valueCheckEnabled: boolean;
  animationTimeline: AnimationTimeline | null;
  perspectiveRuler: PerspectiveRuler | null;
  straightRuler: StraightRuler | null;
  activeLockedAxis: ConstraintAxis | null;
}

const createInitialDocumentState = (): DocumentStoreState => ({
  documents: [],
  activeDocumentId: null,
  dimensions: { ...INITIAL_CANVAS_DIMENSIONS },
  colorMode: 'color',
  documentName: '',
  activeLayerId: '',
  activeEditTarget: 'layer',
  savedFileInfo: null,
  softProofSettings: { ...DEFAULT_SOFT_PROOF_SETTINGS },
  valueCheckEnabled: false,
  animationTimeline: null,
  perspectiveRuler: null,
  straightRuler: null,
  activeLockedAxis: null,
});

export type DocumentHistoryRecorder = (
  label: string,
  delta: DocumentStateDelta
) => void;

export interface DocumentMutationHistoryOptions {
  recordHistory?: boolean;
  label?: string;
  coalesceKey?: string;
}

let activeRulerHistoryRecorder: DocumentHistoryRecorder | null = null;
let suppressRulerHistoryDepth = 0;

function cloneRulerValue<T>(val: T): T {
  if (val === null || val === undefined) return val;
  return JSON.parse(JSON.stringify(val));
}

export const useDocumentStore = createStore<DocumentStoreState>(createInitialDocumentState);

export const documentStoreActions = {
  setRulerHistoryRecorder(recorder: DocumentHistoryRecorder | null): void {
    activeRulerHistoryRecorder = recorder;
  },

  runWithoutRulerHistory<T>(fn: () => T): T {
    suppressRulerHistoryDepth += 1;
    try {
      return fn();
    } finally {
      suppressRulerHistoryDepth = Math.max(0, suppressRulerHistoryDepth - 1);
    }
  },

  setDocuments(updater: DocumentTab[] | ((prev: DocumentTab[]) => DocumentTab[])): void {
    useDocumentStore.setState((prev) => ({
      documents: typeof updater === 'function' ? updater(prev.documents) : updater,
    }));
  },

  setActiveDocumentId(id: string | null): void {
    useDocumentStore.setState({ activeDocumentId: id });
  },

  markDocumentDirty(id: string | null, isDirty: boolean): void {
    if (!id) return;
    useDocumentStore.setState((prev) => {
      const target = prev.documents.find((d) => d.id === id);
      if (!target || Boolean(target.isDirty) === isDirty) return prev;
      return {
        documents: prev.documents.map((d) => (d.id === id ? { ...d, isDirty } : d)),
      };
    });
  },

  /**
   * Updates active canvas dimensions. When `syncDocId` is provided (e.g. during canvas resize,
   * undo/redo, or remote resize), also updates that document tab's `dimensions` atomically so
   * `Ctrl+S`, tab switching, and recovery checkpoints never observe stale pre-resize dimensions.
   */
  setDimensions(dimensions: CanvasDimensions, syncDocId?: string | null): void {
    const normalized: CanvasDimensions = {
      width: dimensions.width,
      height: dimensions.height,
      ...(dimensions.dpi !== undefined ? { dpi: dimensions.dpi } : {}),
    };
    if (syncDocId) {
      useDocumentStore.setState((prev) => ({
        dimensions: normalized,
        documents: prev.documents.map((d) =>
          d.id === syncDocId ? { ...d, dimensions: normalized } : d
        ),
      }));
      return;
    }
    useDocumentStore.setState({ dimensions: normalized });
  },

  setColorMode(colorMode: CanvasColorMode, syncDocId?: string | null): void {
    if (syncDocId) {
      useDocumentStore.setState((prev) => ({
        colorMode,
        documents: prev.documents.map((d) =>
          d.id === syncDocId ? { ...d, colorMode } : d
        ),
      }));
      return;
    }
    useDocumentStore.setState({ colorMode });
  },

  setDocumentName(documentName: string): void {
    useDocumentStore.setState({ documentName });
  },

  setActiveLayerId(activeLayerId: string): void {
    useDocumentStore.setState({ activeLayerId });
  },

  setActiveEditTarget(activeEditTarget: 'layer' | 'mask'): void {
    useDocumentStore.setState({ activeEditTarget });
  },

  setSavedFileInfo(savedFileInfo: SavedFileInfo | null): void {
    useDocumentStore.setState({ savedFileInfo });
  },

  toggleSoftProof(): void {
    useDocumentStore.setState((prev) => ({
      softProofSettings: {
        ...prev.softProofSettings,
        enabled: !prev.softProofSettings.enabled,
      },
    }));
  },

  toggleGamutWarning(): void {
    useDocumentStore.setState((prev) => ({
      softProofSettings: {
        ...prev.softProofSettings,
        gamutWarning: !prev.softProofSettings.gamutWarning,
      },
    }));
  },

  setProofStandard(standard: CmykStandard): void {
    useDocumentStore.setState((prev) => ({
      softProofSettings: {
        ...prev.softProofSettings,
        standard,
      },
    }));
  },

  toggleValueCheck(): boolean {
    const next = !useDocumentStore.getState().valueCheckEnabled;
    useDocumentStore.setState({ valueCheckEnabled: next });
    return next;
  },

  setValueCheckEnabled(valueCheckEnabled: boolean): void {
    useDocumentStore.setState({ valueCheckEnabled });
  },

  setAnimationTimeline(animationTimeline: AnimationTimeline | null): void {
    useDocumentStore.setState({ animationTimeline });
  },

  setPerspectiveRuler(
    updater:
      | PerspectiveRuler
      | null
      | ((prev: PerspectiveRuler | null) => PerspectiveRuler | null),
    options?: DocumentMutationHistoryOptions
  ): void {
    const before = useDocumentStore.getState().perspectiveRuler;
    let nextValue: PerspectiveRuler | null = before;
    useDocumentStore.setState((prev) => {
      const next = typeof updater === 'function' ? updater(prev.perspectiveRuler) : updater;
      nextValue = next;
      if (prev.activeDocumentId) {
        return {
          perspectiveRuler: next,
          documents: prev.documents.map((d) =>
            d.id === prev.activeDocumentId ? { ...d, perspectiveRuler: next } : d
          ),
        };
      }
      return { perspectiveRuler: next };
    });

    if (
      options?.recordHistory !== false &&
      suppressRulerHistoryDepth === 0 &&
      activeRulerHistoryRecorder &&
      before !== nextValue
    ) {
      const label =
        options?.label ||
        (!before && nextValue
          ? 'Add Perspective Ruler'
          : before && !nextValue
            ? 'Remove Perspective Ruler'
            : 'Edit Perspective Ruler');
      activeRulerHistoryRecorder(label, {
        beforePerspectiveRuler: cloneRulerValue(before),
        afterPerspectiveRuler: cloneRulerValue(nextValue),
        coalesceKey:
          options?.coalesceKey ??
          (before && nextValue ? 'perspective-ruler' : undefined),
      });
    }
  },

  setStraightRuler(
    updater:
      | StraightRuler
      | null
      | ((prev: StraightRuler | null) => StraightRuler | null),
    options?: DocumentMutationHistoryOptions
  ): void {
    const before = useDocumentStore.getState().straightRuler;
    let nextValue: StraightRuler | null = before;
    useDocumentStore.setState((prev) => {
      const next = typeof updater === 'function' ? updater(prev.straightRuler) : updater;
      nextValue = next;
      if (prev.activeDocumentId) {
        return {
          straightRuler: next,
          documents: prev.documents.map((d) =>
            d.id === prev.activeDocumentId ? { ...d, straightRuler: next } : d
          ),
        };
      }
      return { straightRuler: next };
    });

    if (
      options?.recordHistory !== false &&
      suppressRulerHistoryDepth === 0 &&
      activeRulerHistoryRecorder &&
      before !== nextValue
    ) {
      const label =
        options?.label ||
        (!before && nextValue
          ? 'Enable Straight Ruler'
          : before && !nextValue
            ? 'Remove Straight Ruler'
            : before?.enabled !== nextValue?.enabled
              ? nextValue?.enabled
                ? 'Enable Straight Ruler'
                : 'Disable Straight Ruler'
              : 'Edit Straight Ruler');
      activeRulerHistoryRecorder(label, {
        beforeStraightRuler: cloneRulerValue(before),
        afterStraightRuler: cloneRulerValue(nextValue),
        coalesceKey:
          options?.coalesceKey ??
          (before && nextValue && before.enabled === nextValue.enabled
            ? 'straight-ruler'
            : undefined),
      });
    }
  },

  toggleStraightRuler(centerX?: number, centerY?: number): StraightRuler {
    const state = useDocumentStore.getState();
    const cx = centerX ?? state.dimensions.width * 0.5;
    const cy = centerY ?? state.dimensions.height * 0.5;
    const prev = state.straightRuler;
    const next: StraightRuler = prev
      ? { ...prev, enabled: !prev.enabled }
      : createDefaultStraightRuler(cx, cy);
    documentStoreActions.setStraightRuler(next, {
      label: next.enabled ? 'Enable Straight Ruler' : 'Disable Straight Ruler',
    });
    return next;
  },

  setActiveLockedAxis(newAxis: ConstraintAxis | null): void {
    const prev = useDocumentStore.getState().activeLockedAxis;
    if (prev === newAxis) return;
    if (
      prev &&
      newAxis &&
      prev.type === newAxis.type &&
      prev.origin.x === newAxis.origin.x &&
      prev.origin.y === newAxis.origin.y &&
      prev.dir.x === newAxis.dir.x &&
      prev.dir.y === newAxis.dir.y
    ) {
      return;
    }
    useDocumentStore.setState({ activeLockedAxis: newAxis });
  },
};

export function selectHasOpenDocument(state: DocumentStoreState): boolean {
  return Boolean(
    state.activeDocumentId && state.documents.some((d) => d.id === state.activeDocumentId)
  );
}