Skip to content

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

1.7 KB
Raw Blame
import { useCallback, useEffect } from 'react';
import { requestNativeThumbnails } from '../../utils/nativeEngineBridge';
import { LayerCanvasRegistryApi, LayerManagerContext } from './types';

export function useLayerCanvasRegistry(ctx: LayerManagerContext): LayerCanvasRegistryApi {
  const { dimensions, activeSessionIdRef, thumbDebounceTimersRef } = ctx;

  useEffect(() => {
    const timers = thumbDebounceTimersRef.current;
    return () => {
      for (const timer of timers.values()) {
        clearTimeout(timer);
      }
      timers.clear();
    };
  }, [thumbDebounceTimersRef]);

  // Request an async 64x64 PNG thumbnail generated directly on Rust Rayon workers (zero WebView canvas)
  const updateLayerThumbnail = useCallback(
    (id: string, immediate: boolean = false) => {
      const capturedDocId = activeSessionIdRef.current;
      if (!capturedDocId || !id) return;

      const run = () => {
        if (capturedDocId !== activeSessionIdRef.current) return;
        void requestNativeThumbnails(capturedDocId, [id]);
      };

      const existing = thumbDebounceTimersRef.current.get(id);
      if (existing) clearTimeout(existing);

      if (immediate) {
        thumbDebounceTimersRef.current.delete(id);
        run();
      } else {
        const isLargeDoc = dimensions.width * dimensions.height > 1024 * 1024;
        const delayMs = isLargeDoc ? 500 : 200;
        const timer = setTimeout(() => {
          thumbDebounceTimersRef.current.delete(id);
          run();
        }, delayMs);
        thumbDebounceTimersRef.current.set(id, timer);
      }
    },
    [activeSessionIdRef, dimensions.height, dimensions.width, thumbDebounceTimersRef]
  );

  return {
    updateLayerThumbnail,
  };
}