Skip to content

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

1.8 KB
Raw Blame
import { useEffect, useLayoutEffect, useRef, useState } from "react";

/** The longest a chat switch keeps the chat it left on screen while the one it opens is read. */
export const SWITCH_HOLD_MS = 150;

interface Switchable {
  id: string;
  threadId: string;
  switchingTo?: string;
}

/**
 * The chat to draw. Opening another bot's conversation the app does not hold yet (its row marked for an unread reply,
 * or one of its threads) selects the bot at once but has its messages only when the server answers; drawing the bot
 * meanwhile paints its last conversation for a frame or more, then the one asked for. So the chat that was on screen
 * stays until the answer lands, up to `SWITCH_HOLD_MS`, then the selected bot as it is. `find` reads the held chat live,
 * so it keeps updating while held.
 */
export function useSwitchHold<T extends Switchable>(selected: T | undefined, find: (id: string) => T | undefined): T | undefined {
  const drawn = useRef<string | undefined>(undefined);
  const [expired, setExpired] = useState<string | null>(null);
  const waitingFor = selected?.switchingTo !== undefined && selected.switchingTo !== selected.threadId
    ? `${selected.id}:${selected.switchingTo}` : null;
  const from = waitingFor !== null && expired !== waitingFor && drawn.current !== undefined && drawn.current !== selected!.id
    ? find(drawn.current) : undefined;
  const shown = from ?? selected;
  const holding = from !== undefined;
  useLayoutEffect(() => {
    drawn.current = shown?.id;
  });
  useEffect(() => {
    // A switch that landed lets the next one to the same conversation hold again.
    if (waitingFor === null) return setExpired(null);
    if (!holding) return;
    const timer = setTimeout(() => setExpired(waitingFor), SWITCH_HOLD_MS);
    return () => clearTimeout(timer);
  }, [holding, waitingFor]);
  return shown;
}