Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

1.7 KB
Raw Blame
import { useCallback, useEffect, useMemo, useSyncExternalStore } from "react";

const focusedThreads = new Set<string>();
const listeners = new Map<string, Set<() => void>>();

function notify(threadId: string): void {
  const set = listeners.get(threadId);
  if (!set) return;
  for (const fn of Array.from(set)) fn();
}

/** Tracks whether the composer for `threadId` currently has keyboard focus (used for subtle mascot glance). */
export function setComposerFocused(threadId: string | null | undefined, focused: boolean): void {
  if (!threadId) return;
  const had = focusedThreads.has(threadId);
  if (had === focused) return;
  if (focused) focusedThreads.add(threadId);
  else focusedThreads.delete(threadId);
  notify(threadId);
}

/** Focus/blur handlers for a thread's composer input, clearing focus on thread switch or unmount. */
export function useComposerFocusHandlers(threadId: string | null | undefined): { onFocus: () => void; onBlur: () => void } {
  useEffect(() => () => setComposerFocused(threadId, false), [threadId]);
  return useMemo(
    () => ({
      onFocus: () => setComposerFocused(threadId, true),
      onBlur: () => setComposerFocused(threadId, false),
    }),
    [threadId],
  );
}

export function useComposerFocused(threadId: string | null | undefined): boolean {
  const subscribe = useCallback((listener: () => void) => {
    if (!threadId) return () => {};
    let set = listeners.get(threadId);
    if (!set) listeners.set(threadId, (set = new Set()));
    set.add(listener);
    return () => {
      set.delete(listener);
      if (set.size === 0) listeners.delete(threadId);
    };
  }, [threadId]);
  return useSyncExternalStore(subscribe, () => Boolean(threadId && focusedThreads.has(threadId)), () => false);
}