Skip to content

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

17.3 KB
Raw Blame
import React, { useRef, useState, useCallback, useEffect } from 'react';
import {
  CanvasDimensions,
  CanvasColorMode,
  DirtyRect,
  DocumentStateDelta,
  HistoryActionType,
  HistoryItemMeta,
  LayerItem,
  LayerTreeDelta,
  TileDelta,
  VectorStroke,
} from '../../types/editor';
import { multiplayerService } from '../../services/multiplayerService';
import {
  clearNativeLayer,
  fromNativeLayerNodeMeta,
  getHistorySnapshotEntries,
  nativeGetHistory,
  nativeJumpHistory,
  nativePushHistoryMeta,
  nativeRedo,
  nativeResetHistory,
  nativeSelectiveRedo,
  nativeSelectiveUndo,
  nativeUndo,
  NativeHistoryMutationResult,
  NativeHistoryStateSnapshot,
  requestNativeThumbnails,
  subscribeNativeHistory,
  subscribeNativeStrokeCommitted,
} from '../../utils/nativeEngineBridge';
import { recoveryService } from '../../services/recoveryService';
import { documentStoreActions } from '../../stores';
import {
  ApplyDocumentStateDeltaFn,
  ApplyLayerTreeDeltaFn,
  LastStrokeEndState,
  PushHistoryStepFn,
} from './types';
import { t } from '../../i18n';

export interface UseDrawingHistoryParams {
  activeSessionId?: string | null;
  activeLayerId: string;
  activeLayerLocked: boolean;
  dimensions: CanvasDimensions;
  dimensionsRef: React.MutableRefObject<CanvasDimensions>;
  activeLayerIdRef: React.MutableRefObject<string>;
  colorModeRef: React.MutableRefObject<CanvasColorMode>;
  layersRef: React.MutableRefObject<LayerItem[] | undefined>;
  onUpdateLayerThumbnail: (layerId: string, immediate?: boolean) => void;
  onApplyLayerTreeDeltaRef?: React.MutableRefObject<ApplyLayerTreeDeltaFn | undefined>;
  onApplyDocumentStateDeltaRef?: React.MutableRefObject<ApplyDocumentStateDeltaFn | undefined>;
  onUpdateMaskThumbnailRef: React.MutableRefObject<((layerId: string) => void) | undefined>;
  isDrawingRef: React.MutableRefObject<boolean>;
  lastStrokeEndRef: React.MutableRefObject<LastStrokeEndState | null>;
  abortActiveStrokeRef: React.MutableRefObject<() => void>;
}

export interface SelectiveUndoResult {
  strokeId?: string;
  layerId: string;
  changedLayerIds?: string[];
  tileDeltas?: TileDelta[];
  syncedRemotely?: boolean;
  hadContestedTiles?: boolean;
  preservedPeerEdits?: boolean;
  conflictNotice?: string;
}

export interface UseDrawingHistoryResult {
  activeSessionIdRef: React.MutableRefObject<string | null>;
  historyList: HistoryItemMeta[];
  historyIndex: number;
  canUndo: boolean;
  canRedo: boolean;
  pushHistoryStep: PushHistoryStepFn;
  flushPendingHistoryTasks: () => void;
  enqueueHistoryTask: (task: () => void) => void;
  jumpToHistoryIndex: (targetIndex: number) => Promise<void>;
  undo: () => void;
  redo: () => void;
  selectiveUndo: (
    peerIdToUndo?: string | number,
    strokeIdToUndo?: string
  ) => Promise<SelectiveUndoResult | null>;
  selectiveRedo: (
    peerIdToRedo?: string | number
  ) => Promise<SelectiveUndoResult | null>;
  clearCanvas: () => void;
  resetHistory: (targetDocumentId?: string) => void;
}

/**
 * Pure Native Rust CoW History Hook (Phase 6).
 *
 * All raster, mask, selection, filter, transform, and liquify undo/redo deltas live in
 * `crates/ink-engine`'s zero-copy CoW tile history stack. WebView2 holds zero pixel buffers
 * and zero `UndoCacheManager` entries — only lightweight `HistoryItemMeta[]` for the History panel.
 */
export function useDrawingHistory({
  activeSessionId,
  activeLayerId,
  activeLayerLocked,
  dimensionsRef,
  activeLayerIdRef,
  layersRef,
  onApplyLayerTreeDeltaRef,
  onApplyDocumentStateDeltaRef,
  isDrawingRef,
  lastStrokeEndRef,
  abortActiveStrokeRef,
}: UseDrawingHistoryParams): UseDrawingHistoryResult {
  const activeSessionIdRef = useRef<string | null>(activeSessionId ?? null);
  const initializedHistoryDocRef = useRef<string | null>(null);
  const historyIndexRef = useRef<number>(-1);
  const lastHistorySigRef = useRef<string>('');
  const pendingHistoryTasksRef = useRef<Array<() => void>>([]);

  const [historyList, setHistoryList] = useState<HistoryItemMeta[]>([]);
  const [historyIndex, setHistoryIndex] = useState<number>(-1);
  const [canUndo, setCanUndo] = useState(false);
  const [canRedo, setCanRedo] = useState(false);

  const applyNativeHistorySnapshot = useCallback(
    (snap: NativeHistoryStateSnapshot | null | undefined) => {
      if (!snap || typeof snap !== 'object') return;
      const entries = getHistorySnapshotEntries(snap);
      const safeIndex =
        typeof snap.index === 'number' && Number.isFinite(snap.index)
          ? snap.index
          : entries.length - 1;
      const lastEntryId = entries.length > 0 ? entries[entries.length - 1]?.id ?? '' : '';
      const currentEntryId =
        safeIndex >= 0 && safeIndex < entries.length ? entries[safeIndex]?.id ?? '' : '';
      const nextCanUndo = Boolean(snap.canUndo);
      const nextCanRedo = Boolean(snap.canRedo);
      const sig = `${safeIndex}|${entries.length}|${lastEntryId}|${currentEntryId}|${nextCanUndo ? 1 : 0}|${nextCanRedo ? 1 : 0}`;
      if (sig === lastHistorySigRef.current) return;
      lastHistorySigRef.current = sig;

      historyIndexRef.current = safeIndex;
      setHistoryIndex(safeIndex);
      setCanUndo(nextCanUndo);
      setCanRedo(nextCanRedo);
      setHistoryList(entries);
    },
    []
  );

  const applyNativeMutationResult = useCallback(
    (res: NativeHistoryMutationResult | null, direction: 'undo' | 'redo' = 'redo') => {
      if (!res || !res.doc) return;
      if (activeSessionIdRef.current && res.doc.id && res.doc.id !== activeSessionIdRef.current) {
        return;
      }
      applyNativeHistorySnapshot(res.doc.history);
      if (res.documentStateDelta) {
        onApplyDocumentStateDeltaRef?.current?.(res.documentStateDelta, direction);
      }
      if (res.dimensionsChanged) {
        dimensionsRef.current = res.doc.dimensions;
        documentStoreActions.setDimensions(res.doc.dimensions, res.doc.id);
      }
      if (res.layersChanged) {
        const hydrated = res.doc.layers.map(fromNativeLayerNodeMeta);
        const prevLayers = layersRef.current ?? [];
        const prevActive = activeLayerIdRef.current;
        const nextActive = res.doc.activeLayerId ?? hydrated[0]?.id ?? '';
        layersRef.current = hydrated;
        if (nextActive) {
          activeLayerIdRef.current = nextActive;
        }
        onApplyLayerTreeDeltaRef?.current?.(
          {
            beforeLayers: prevLayers,
            afterLayers: hydrated,
            beforeActiveLayerId: prevActive,
            afterActiveLayerId: nextActive,
          },
          'redo'
        );
      }
      if (res.changedLayerIds.length > 0) {
        void requestNativeThumbnails(res.doc.id, res.changedLayerIds);
      }
      if (
        res.changedLayerIds.length > 0 ||
        res.dimensionsChanged ||
        res.layersChanged ||
        res.documentStateDelta
      ) {
        documentStoreActions.markDocumentDirty(res.doc.id, true);
      }
    },
    [
      activeLayerIdRef,
      applyNativeHistorySnapshot,
      dimensionsRef,
      layersRef,
      onApplyDocumentStateDeltaRef,
      onApplyLayerTreeDeltaRef,
    ]
  );

  // Subscribe to live Rust CoW history updates & committed native strokes so history,
  // undo/redo buttons, and the dirty-document (`*`) indicator always stay synchronized.
  useEffect(() => {
    const unsubHistory = subscribeNativeHistory((ev) => {
      if (activeSessionIdRef.current && ev.docId !== activeSessionIdRef.current) return;
      applyNativeHistorySnapshot(ev.history);
    });
    const unsubStroke = subscribeNativeStrokeCommitted((ev) => {
      const targetDocId = ev.docId || activeSessionIdRef.current;
      if (activeSessionIdRef.current && ev.docId && ev.docId !== activeSessionIdRef.current) return;
      if (ev.history) {
        applyNativeHistorySnapshot(ev.history);
      }
      if (targetDocId) {
        documentStoreActions.markDocumentDirty(targetDocId, true);
        recoveryService.notifyNativeStrokeCommitted(targetDocId);
      }
    });
    return () => {
      unsubHistory();
      unsubStroke();
    };
  }, [applyNativeHistorySnapshot]);

  const pushHistoryStep = useCallback<PushHistoryStepFn>(
    (
      actionType: HistoryActionType,
      label: string,
      _beforeData: ImageData | null,
      _afterData: ImageData | null,
      targetLayerId: string,
      _dirtyRect?: DirtyRect,
      explicitTileDeltas?: TileDelta[],
      _vectorDelta?: { before: VectorStroke[]; after: VectorStroke[] },
      _peerId?: string | number,
      _strokeId?: string,
      _isMaskEdit?: boolean,
      _layerTreeDelta?: LayerTreeDelta,
      documentStateDelta?: DocumentStateDelta
    ) => {
      const docId = activeSessionIdRef.current;
      if (!docId) return;
      // Rust owns all raster/layer CoW history; forward compact metadata deltas (rulers, timeline, selection)
      if (documentStateDelta && !explicitTileDeltas?.length) {
        void nativePushHistoryMeta({
          docId,
          actionType,
          label,
          layerId: targetLayerId || null,
          documentStateDelta,
          coalesceKey: documentStateDelta.coalesceKey,
        })
          .then((snap) => {
            if (snap && activeSessionIdRef.current === docId) {
              applyNativeHistorySnapshot(snap);
            }
          })
          .catch((err) => console.warn('[History] Native pushHistoryMeta failed:', err));
      }
    },
    [applyNativeHistorySnapshot]
  );

  const flushPendingHistoryTasks = useCallback(() => {
    const tasks = pendingHistoryTasksRef.current.splice(0);
    for (const task of tasks) {
      try {
        task();
      } catch (err) {
        console.warn('[History] Error flushing pending task:', err);
      }
    }
  }, []);

  const enqueueHistoryTask = useCallback((task: () => void) => {
    pendingHistoryTasksRef.current.push(task);
    queueMicrotask(() => {
      const next = pendingHistoryTasksRef.current.shift();
      if (next) {
        try {
          next();
        } catch (err) {
          console.warn('[History] Error running queued task:', err);
        }
      }
    });
  }, []);

  const jumpToHistoryIndex = useCallback(
    async (targetIndex: number) => {
      if (multiplayerService.isConnected() && multiplayerService.getLocalRole() === 'viewer') return;
      flushPendingHistoryTasks();
      if (isDrawingRef.current) {
        abortActiveStrokeRef.current();
      }
      const docId = activeSessionIdRef.current;
      if (!docId) return;
      const direction: 'undo' | 'redo' = targetIndex < historyIndexRef.current ? 'undo' : 'redo';
      try {
        const res = await nativeJumpHistory(docId, targetIndex);
        applyNativeMutationResult(res, direction);
      } catch (err) {
        console.warn('[History] Native jumpToHistoryIndex failed:', err);
      }
    },
    [abortActiveStrokeRef, applyNativeMutationResult, flushPendingHistoryTasks, isDrawingRef]
  );

  const undo = useCallback(() => {
    if (multiplayerService.isConnected() && multiplayerService.getLocalRole() === 'viewer') return;
    flushPendingHistoryTasks();
    if (isDrawingRef.current) {
      abortActiveStrokeRef.current();
    }
    const docId = activeSessionIdRef.current;
    if (!docId) return;
    void nativeUndo(docId)
      .then((res) => applyNativeMutationResult(res, 'undo'))
      .catch((err) => console.warn('[History] Native undo failed:', err));
  }, [abortActiveStrokeRef, applyNativeMutationResult, flushPendingHistoryTasks, isDrawingRef]);

  const redo = useCallback(() => {
    if (multiplayerService.isConnected() && multiplayerService.getLocalRole() === 'viewer') return;
    flushPendingHistoryTasks();
    if (isDrawingRef.current) {
      abortActiveStrokeRef.current();
    }
    const docId = activeSessionIdRef.current;
    if (!docId) return;
    void nativeRedo(docId)
      .then((res) => applyNativeMutationResult(res, 'redo'))
      .catch((err) => console.warn('[History] Native redo failed:', err));
  }, [abortActiveStrokeRef, applyNativeMutationResult, flushPendingHistoryTasks, isDrawingRef]);

  const selectiveUndo = useCallback(
    async (
      peerIdToUndo?: string | number,
      strokeIdToUndo?: string
    ): Promise<SelectiveUndoResult | null> => {
      flushPendingHistoryTasks();
      if (isDrawingRef.current) {
        abortActiveStrokeRef.current();
      }
      const docId = activeSessionIdRef.current;
      if (!docId) return null;
      try {
        const res = await nativeSelectiveUndo(
          docId,
          peerIdToUndo !== undefined ? String(peerIdToUndo) : undefined,
          strokeIdToUndo
        );
        if (!res) return null;
        applyNativeMutationResult(res, 'undo');
        if (multiplayerService.isConnected() && (!peerIdToUndo || peerIdToUndo === 'local')) {
          for (const lid of res.changedLayerIds) {
            multiplayerService.streamNativeLayerTiles(lid);
          }
        }
        return {
          strokeId: strokeIdToUndo,
          layerId: res.changedLayerIds[0] ?? activeLayerId,
          changedLayerIds: res.changedLayerIds,
          syncedRemotely: true,
        };
      } catch (err) {
        console.warn('[History] Native selectiveUndo failed:', err);
        return null;
      }
    },
    [abortActiveStrokeRef, activeLayerId, applyNativeMutationResult, flushPendingHistoryTasks, isDrawingRef]
  );

  const selectiveRedo = useCallback(
    async (peerIdToRedo?: string | number): Promise<SelectiveUndoResult | null> => {
      flushPendingHistoryTasks();
      if (isDrawingRef.current) {
        abortActiveStrokeRef.current();
      }
      const docId = activeSessionIdRef.current;
      if (!docId) return null;
      try {
        const res = await nativeSelectiveRedo(
          docId,
          peerIdToRedo !== undefined ? String(peerIdToRedo) : undefined
        );
        if (!res) return null;
        applyNativeMutationResult(res, 'redo');
        if (multiplayerService.isConnected() && (!peerIdToRedo || peerIdToRedo === 'local')) {
          for (const lid of res.changedLayerIds) {
            multiplayerService.streamNativeLayerTiles(lid);
          }
        }
        return {
          layerId: res.changedLayerIds[0] ?? activeLayerId,
          changedLayerIds: res.changedLayerIds,
          syncedRemotely: true,
        };
      } catch (err) {
        console.warn('[History] Native selectiveRedo failed:', err);
        return null;
      }
    },
    [abortActiveStrokeRef, activeLayerId, applyNativeMutationResult, flushPendingHistoryTasks, isDrawingRef]
  );

  const clearCanvas = useCallback(() => {
    if (!activeLayerId || activeLayerLocked) return;
    const dims = dimensionsRef.current;
    if (dims.width <= 0 || dims.height <= 0) return;
    const docId = activeSessionIdRef.current;
    if (!docId) return;
    void clearNativeLayer(docId, activeLayerId, true)
      .then((snap) => {
        if (snap && activeSessionIdRef.current === docId) {
          applyNativeHistorySnapshot(snap.history);
          documentStoreActions.markDocumentDirty(docId, true);
          void requestNativeThumbnails(docId, [activeLayerId]);
        }
      })
      .catch((err) => console.warn('[History] Native clearCanvas failed:', err));
  }, [activeLayerId, activeLayerLocked, applyNativeHistorySnapshot, dimensionsRef]);

  const resetHistory = useCallback(
    (targetDocumentId?: string) => {
      flushPendingHistoryTasks();
      const docId = targetDocumentId ?? activeSessionIdRef.current;
      if (!docId) {
        lastHistorySigRef.current = '';
        historyIndexRef.current = -1;
        setHistoryList([]);
        setHistoryIndex(-1);
        setCanUndo(false);
        setCanRedo(false);
        return;
      }
      lastHistorySigRef.current = '';
      void nativeResetHistory(docId, t('New Document'))
        .then((snap) => {
          if (snap && (!targetDocumentId || targetDocumentId === activeSessionIdRef.current)) {
            applyNativeHistorySnapshot(snap);
          }
        })
        .catch((err) => console.warn('[History] Native resetHistory failed:', err));
    },
    [applyNativeHistorySnapshot, flushPendingHistoryTasks]
  );

  // Sync history list from Rust whenever the active document tab changes (including initial mount)
  useEffect(() => {
    const nextDocId = activeSessionId ?? null;
    const prevDocId = activeSessionIdRef.current;
    const alreadyInitialized = initializedHistoryDocRef.current === nextDocId;
    if (prevDocId === nextDocId && alreadyInitialized) return;

    if (prevDocId !== nextDocId) {
      flushPendingHistoryTasks();
      if (isDrawingRef.current) {
        abortActiveStrokeRef.current();
      }
      lastStrokeEndRef.current = null;
    }

    activeSessionIdRef.current = nextDocId;
    initializedHistoryDocRef.current = nextDocId;
    lastHistorySigRef.current = '';

    if (!nextDocId) {
      historyIndexRef.current = -1;
      setHistoryList([]);
      setHistoryIndex(-1);
      setCanUndo(false);
      setCanRedo(false);
      return;
    }

    void nativeGetHistory(nextDocId)
      .then((snap) => {
        if (snap && activeSessionIdRef.current === nextDocId) {
          applyNativeHistorySnapshot(snap);
        }
      })
      .catch(() => {});
  }, [
    abortActiveStrokeRef,
    activeSessionId,
    applyNativeHistorySnapshot,
    flushPendingHistoryTasks,
    isDrawingRef,
    lastStrokeEndRef,
  ]);

  return {
    activeSessionIdRef,
    historyList,
    historyIndex,
    canUndo,
    canRedo,
    pushHistoryStep,
    flushPendingHistoryTasks,
    enqueueHistoryTask,
    jumpToHistoryIndex,
    undo,
    redo,
    selectiveUndo,
    selectiveRedo,
    clearCanvas,
    resetHistory,
  };
}