Skip to content

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

1.3 KB
Raw Blame
import { useState } from "react";

const storageKey = (list: string) => `openmausbot.automations.paused-by-all.${list}`;

function read(list: string): readonly string[] {
  try {
    const ids: unknown = JSON.parse(sessionStorage.getItem(storageKey(list)) ?? "[]");
    return Array.isArray(ids) ? ids.filter((id): id is string => typeof id === "string") : [];
  } catch {
    return [];
  }
}

function write(list: string, ids: readonly string[]) {
  try {
    if (ids.length) sessionStorage.setItem(storageKey(list), JSON.stringify(ids));
    else sessionStorage.removeItem(storageKey(list));
  } catch { /* no storage: kept while the page is open */ }
}

/** The automations "Pause all" turned off in one list, so "Resume all" turns back on only those. Each list shown
 * (a department, a bot) keeps its own; it lasts while this window is open and is empty when none is kept. */
export function usePausedByAll(list: string): [ids: readonly string[], remember: (ids: readonly string[]) => void] {
  const [held, setHeld] = useState(() => ({ list, ids: read(list) }));
  let current = held;
  if (held.list !== list) {
    current = { list, ids: read(list) };
    setHeld(current);
  }
  const remember = (ids: readonly string[]) => {
    write(list, ids);
    setHeld({ list, ids });
  };
  return [current.ids, remember];
}