Skip to content

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

2.4 KB
Raw Blame
import { useSyncExternalStore } from 'react';
import {
  getNativeDiagnostics,
  isNativeCanvasActive,
  NativeEngineDiagnostics,
  subscribeNativeCanvasActive,
  subscribeNativeDiagnostics,
} from '../utils/nativeEngineBridge';

type Listener = () => void;

let currentDiagnostics: NativeEngineDiagnostics | null = null;
const listeners = new Set<Listener>();
let unsubDiag: (() => void) | null = null;
let unsubActive: (() => void) | null = null;
let generation = 0;

function emitChange(): void {
  for (const listener of listeners) {
    listener();
  }
}

function attachNativeSubscriptions(): void {
  if (unsubDiag !== null) return;
  const gen = ++generation;

  const fetchInitial = () => {
    if (!isNativeCanvasActive()) return;
    void getNativeDiagnostics().then((diag) => {
      if (gen !== generation || !diag || listeners.size === 0) return;
      currentDiagnostics = diag;
      emitChange();
    });
  };

  unsubDiag = subscribeNativeDiagnostics((diag) => {
    currentDiagnostics = diag;
    emitChange();
  });

  unsubActive = subscribeNativeCanvasActive((active) => {
    if (active) {
      fetchInitial();
    } else if (currentDiagnostics !== null) {
      currentDiagnostics = null;
      emitChange();
    }
  });

  fetchInitial();
}

function detachNativeSubscriptions(): void {
  generation++;
  unsubDiag?.();
  unsubDiag = null;
  unsubActive?.();
  unsubActive = null;
}

function subscribe(listener: Listener): () => void {
  listeners.add(listener);
  if (listeners.size === 1) {
    attachNativeSubscriptions();
  }
  return () => {
    listeners.delete(listener);
    if (listeners.size === 0) {
      detachNativeSubscriptions();
    }
  };
}

export function getNativeDiagnosticsSnapshot(): NativeEngineDiagnostics | null {
  return currentDiagnostics;
}

/**
 * Isolated external-store hook consumed ONLY by the `NativeGpuPerfHud` leaf component.
 * Keeps 4 Hz `native-engine://diagnostics` updates completely out of `CanvasArea` React state
 * and unsubscribes automatically whenever the perf HUD is unmounted.
 */
export function useNativeDiagnostics(): NativeEngineDiagnostics | null {
  return useSyncExternalStore(subscribe, getNativeDiagnosticsSnapshot, () => null);
}

/**
 * Resets cached diagnostics and tears down active listeners (for deterministic unit tests).
 */
export function resetNativeDiagnosticsStore(): void {
  detachNativeSubscriptions();
  listeners.clear();
  currentDiagnostics = null;
}