Skip to content

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

1.1 KB
Raw Blame
import { useEffect, useRef } from "react";
import { shownChatIsUnread } from "@/lib/shown-chat-unread";
import { shownChatHeldUnread } from "@/state/read-visible";
import { useStore } from "@/state/store";

/** Replies that reached the shown chat while the window was in the background stay unread; once the window has focus
 * again, that chat is read through `select`, which also puts the "New" divider above them and keeps a thread or fork
 * open beside it. A chat the person marked unread stays so when nothing newer reached it. */
export function useReadShownChatOnFocus(): void {
  const { state, dispatch } = useStore();
  const latest = useRef(state);
  latest.current = state;
  useEffect(() => {
    const readShownChat = () => {
      const { selectedId, newChat } = latest.current;
      if (selectedId && newChat?.botId !== selectedId && shownChatIsUnread(latest.current) && !shownChatHeldUnread(latest.current)) dispatch({ type: "select", id: selectedId, keepPanel: true });
    };
    window.addEventListener("focus", readShownChat);
    return () => window.removeEventListener("focus", readShownChat);
  }, [dispatch]);
}