Skip to content

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

5.7 KB
Raw Blame
/**
 * Lightweight, zero-rerender workspace chrome interaction guard.
 *
 * Acquiring a lock while dragging tabs, floating panels, dock splitters, sliders, or panel
 * scrollbars guarantees that neither DOM pointer handlers nor the native WinTab / Windows Ink
 * bridge can accidentally initiate a canvas brush stroke — and sets `data-workspace-interacting`
 * on `document.documentElement` so CSS disables `pointer-events` on the canvas interaction surface
 * strictly for the duration of the drag without triggering React re-renders.
 */

type InteractionListener = (active: boolean) => void;

let nextLockId = 1;
const activeLocks = new Map<number, string>();
const listeners = new Set<InteractionListener>();
let safetyListenersInstalled = false;
let scrollbarGuardInstalled = false;

function syncRootAttribute(active: boolean): void {
  if (typeof document === 'undefined' || !document.documentElement) return;
  if (active) {
    document.documentElement.setAttribute('data-workspace-interacting', 'true');
  } else {
    document.documentElement.removeAttribute('data-workspace-interacting');
  }
}

function notifyListeners(active: boolean): void {
  syncRootAttribute(active);
  for (const listener of listeners) {
    try {
      listener(active);
    } catch {
      // Ignore listener errors so lock cleanup never fails
    }
  }
}

function installGlobalSafetyListeners(): void {
  if (safetyListenersInstalled || typeof window === 'undefined') return;
  safetyListenersInstalled = true;

  const handleWindowBlur = () => {
    if (activeLocks.size > 0) {
      releaseAllWorkspaceInteractionLocks();
    }
  };
  const handleVisibilityChange = () => {
    if (typeof document !== 'undefined' && document.hidden && activeLocks.size > 0) {
      releaseAllWorkspaceInteractionLocks();
    }
  };

  window.addEventListener('blur', handleWindowBlur);
  if (typeof document !== 'undefined') {
    document.addEventListener('visibilitychange', handleVisibilityChange);
  }
}

/**
 * Acquires a re-entrant workspace interaction lock for `reason`.
 * Returns an idempotent release function that MUST be called when the interaction ends.
 */
export function acquireWorkspaceInteractionLock(reason: string): () => void {
  installGlobalSafetyListeners();
  const id = nextLockId++;
  const wasActive = activeLocks.size > 0;
  activeLocks.set(id, reason);

  if (!wasActive) {
    notifyListeners(true);
  }

  let released = false;
  return () => {
    if (released) return;
    released = true;
    if (!activeLocks.delete(id)) return;
    if (activeLocks.size === 0) {
      notifyListeners(false);
    }
  };
}

export function isWorkspaceInteractionActive(): boolean {
  return activeLocks.size > 0;
}

export function getActiveWorkspaceInteractionReasons(): string[] {
  return Array.from(activeLocks.values());
}

export function releaseAllWorkspaceInteractionLocks(): void {
  if (activeLocks.size === 0) {
    syncRootAttribute(false);
    return;
  }
  activeLocks.clear();
  notifyListeners(false);
}

export function subscribeWorkspaceInteraction(listener: InteractionListener): () => void {
  listeners.add(listener);
  return () => {
    listeners.delete(listener);
  };
}

/**
 * Detects if a pointerdown event hits a native scrollbar gutter of a scrollable UI container
 * (outside the canvas viewport) or a native range input slider.
 */
function isScrollbarOrRangeInteraction(target: EventTarget | null, clientX: number, clientY: number): string | null {
  if (!target || typeof HTMLElement === 'undefined' || !(target instanceof HTMLElement)) {
    return null;
  }
  // Never block direct canvas interaction surface touches
  if (target.closest?.('[data-testid="canvas-interaction-surface"]')) {
    return null;
  }
  if (target.tagName === 'INPUT' && (target as HTMLInputElement).type === 'range') {
    return 'native-range-slider';
  }
  // Check if pointerdown landed on the native scrollbar gutter of this element
  const rect = typeof target.getBoundingClientRect === 'function' ? target.getBoundingClientRect() : null;
  if (!rect) return null;

  const vScrollbarWidth = target.offsetWidth - target.clientWidth;
  if (vScrollbarWidth > 0 && target.scrollHeight > target.clientHeight) {
    if (clientX >= rect.left + target.clientWidth && clientX <= rect.right + 2) {
      return 'scrollbar-drag';
    }
  }
  const hScrollbarHeight = target.offsetHeight - target.clientHeight;
  if (hScrollbarHeight > 0 && target.scrollWidth > target.clientWidth) {
    if (clientY >= rect.top + target.clientHeight && clientY <= rect.bottom + 2) {
      return 'scrollbar-drag';
    }
  }
  return null;
}

/**
 * Installs a single capture-phase listener on `window` that automatically guards native
 * panel scrollbar drags and `<input type="range">` drags across all UI panels.
 * Safe to call multiple times (idempotent).
 */
export function ensureGlobalChromeScrollbarGuard(): void {
  if (scrollbarGuardInstalled || typeof window === 'undefined') return;
  scrollbarGuardInstalled = true;

  let activeRelease: (() => void) | null = null;

  const releaseCurrent = () => {
    if (activeRelease) {
      const fn = activeRelease;
      activeRelease = null;
      fn();
    }
  };

  window.addEventListener(
    'pointerdown',
    (ev: PointerEvent) => {
      if (ev.button !== 0) return;
      const reason = isScrollbarOrRangeInteraction(ev.target, ev.clientX, ev.clientY);
      if (!reason) return;
      releaseCurrent();
      activeRelease = acquireWorkspaceInteractionLock(reason);
    },
    true
  );

  window.addEventListener('pointerup', releaseCurrent, true);
  window.addEventListener('pointercancel', releaseCurrent, true);
  window.addEventListener('dragend', releaseCurrent, true);
  window.addEventListener('drop', releaseCurrent, true);
}