Skip to content

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

9.5 KB
Raw Blame
import type { SendKey } from "./send-key";
import { START_FRESH_KEYS } from "./start-fresh";
import { t } from "@/lib/i18n";
import { en, type LocaleKey } from "@/locales";

export interface ShortcutItem {
  id: string;
  description: string;
  macKeys: string[];
  winKeys: string[];
}

export interface ShortcutGroup {
  category: string;
  items: ShortcutItem[];
}

export const SHORTCUT_GROUPS: readonly ShortcutGroup[] = [
  {
    category: "Navigation",
    items: [
      {
        id: "command-palette",
        description: "Open command palette (switcher & transcript search)",
        macKeys: ["⌘", "K"],
        winKeys: ["Ctrl", "K"],
      },
      {
        id: "new-bot",
        description: "Create a new bot",
        macKeys: ["⌘", "N"],
        winKeys: ["Ctrl", "N"],
      },
      {
        id: "new-thread",
        description: "Start a new thread with the selected bot",
        macKeys: ["⌘", "⇧", "N"],
        winKeys: ["Ctrl", "Shift", "N"],
      },
      {
        id: "jump-bot",
        description: "Jump to bot 1–9 in the roster",
        macKeys: ["⌘", "1–9"],
        winKeys: ["Ctrl", "1–9"],
      },
      {
        id: "toggle-sidebar",
        description: "Collapse or expand the sidebar",
        macKeys: ["⌘", "\\"],
        winKeys: ["Ctrl", "\\"],
      },
      {
        id: "switch-bot",
        description: "Switch to previous / next bot",
        macKeys: ["⌘", "⇧", "[ / ]"],
        winKeys: ["Ctrl", "Shift", "[ / ]"],
      },
      {
        id: "switch-thread",
        description: "Switch to the bot's next / previous thread",
        macKeys: ["⌃", "Tab / ⇧Tab"],
        winKeys: ["Ctrl", "Tab / Shift+Tab"],
      },
      {
        id: "find-conversation",
        description: "Find in conversation",
        macKeys: ["⌘", "F"],
        winKeys: ["Ctrl", "F"],
      },
    ],
  },
  {
    category: "Chat & Composer",
    items: [
      {
        id: "send-message",
        description: "Send message",
        macKeys: ["Return"],
        winKeys: ["Enter"],
      },
      {
        id: "new-line",
        description: "Insert new line without sending",
        macKeys: ["⇧", "Return"],
        winKeys: ["Shift", "Enter"],
      },
      {
        id: "send-follow-up",
        description: "While a bot works: queue instead of steering, or the other way round",
        macKeys: ["⌘", "Return"],
        winKeys: ["Ctrl", "Enter"],
      },
      {
        id: "edit-last-message",
        description: "Edit last message (when composer is empty)",
        macKeys: ["↑"],
        winKeys: ["↑"],
      },
      {
        id: "start-fresh",
        description: "Start fresh in this conversation (keeps the messages)",
        macKeys: [...START_FRESH_KEYS.mac],
        winKeys: [...START_FRESH_KEYS.win],
      },
      {
        id: "dictation-toggle",
        description: "Start or stop dictation",
        macKeys: ["⌘", "D"],
        winKeys: ["Ctrl", "D"],
      },
      {
        id: "close-panel",
        description: "Close active drawer, modal, or find bar",
        macKeys: ["Esc"],
        winKeys: ["Esc"],
      },
      {
        id: "shortcuts-cheat-sheet",
        description: "Show keyboard shortcuts cheat sheet",
        macKeys: ["⌘", "/"],
        winKeys: ["Ctrl", "/"],
      },
    ],
  },
  {
    category: "Calls",
    items: [
      {
        id: "live-call-mute",
        description: "Mute or unmute a Live call",
        macKeys: ["⌘", "⇧", "M"],
        winKeys: ["Ctrl", "Shift", "M"],
      },
      {
        id: "live-call-hang-up",
        description: "Hang up a Live call",
        macKeys: ["⌘", "⇧", "H"],
        winKeys: ["Ctrl", "Shift", "H"],
      },
    ],
  },
  {
    category: "Management & Groups",
    items: [
      {
        id: "save-bulletin",
        description: "Save group instruction changes",
        macKeys: ["⌘", "Return"],
        winKeys: ["Ctrl", "Enter"],
      },
      {
        id: "reorder-section",
        description: "Reorder sidebar sections (focus a section heading)",
        macKeys: ["⌥", "↑ / ↓"],
        winKeys: ["Alt", "↑ / ↓"],
      },
    ],
  },
];

const CATEGORY_KEY: Record<string, LocaleKey> = {
  Navigation: "shortcuts.category.navigation",
  "Chat & Composer": "shortcuts.category.chat",
  Calls: "shortcuts.category.calls",
  "Management & Groups": "shortcuts.category.groups",
};

export const shortcutDescription = (item: ShortcutItem): string => {
  const key = `shortcuts.${item.id}`;
  return Object.hasOwn(en, key) ? t(key as LocaleKey) : item.description;
};
export const shortcutCategory = (group: ShortcutGroup): string => {
  const key = CATEGORY_KEY[group.category];
  return key ? t(key) : group.category;
};

type Keys = Pick<ShortcutItem, "macKeys" | "winKeys">;
const ENTER: Keys = { macKeys: ["Return"], winKeys: ["Enter"] };
const SHIFT_ENTER: Keys = { macKeys: ["⇧", "Return"], winKeys: ["Shift", "Enter"] };
const MOD_ENTER: Keys = { macKeys: ["⌘", "Return"], winKeys: ["Ctrl", "Enter"] };
const SEND_ROWS: Record<Exclude<SendKey, "enter">, [Keys, Keys, Keys]> = {
  "shift-enter": [SHIFT_ENTER, ENTER, MOD_ENTER],
  "mod-enter": [MOD_ENTER, ENTER, { macKeys: ["⌘", "⇧", "Return"], winKeys: ["Ctrl", "Shift", "Enter"] }],
};

export function shortcutGroupsFor(sendKey: SendKey): readonly ShortcutGroup[] {
  if (sendKey === "enter") return SHORTCUT_GROUPS;
  const [send, newLine, followUp] = SEND_ROWS[sendKey];
  return SHORTCUT_GROUPS.map((group) => ({
    ...group,
    items: group.items.map((item) =>
      item.id === "send-message" ? { ...item, ...send }
        : item.id === "new-line" ? { ...item, ...newLine }
          : item.id === "send-follow-up" ? { ...item, ...followUp }
            : item),
  }));
}

export function isSidebarToggle(event: Pick<KeyboardEvent, "key" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey" | "defaultPrevented">): boolean {
  return !event.defaultPrevented && event.key === "\\" && (event.metaKey || event.ctrlKey) && !event.shiftKey && !event.altKey;
}

/**
 * The step of ⌘⇧] / ⌘⇧[ (Ctrl+Shift outside macOS) through the bots: 1, -1, or null for any other key. Outside
 * macOS, Shift turns the key into "}" / "{", so those count too. The physical key (`code`) is not used: on many
 * layouts BracketRight types another character.
 */
export function botCycleStep(event: Pick<KeyboardEvent, "key">): 1 | -1 | null {
  if (event.key === "]" || event.key === "}") return 1;
  if (event.key === "[" || event.key === "{") return -1;
  return null;
}

/** Ctrl on macOS too: ⌘Tab belongs to the system. keyCode 229 is a composing key in browsers that leave isComposing unset. */
export function threadCycleStep(event: Pick<KeyboardEvent, "key" | "ctrlKey" | "metaKey" | "altKey" | "shiftKey" | "defaultPrevented" | "isComposing" | "keyCode" | "target">): 1 | -1 | null {
  if (event.key !== "Tab" || !event.ctrlKey || event.metaKey || event.altKey || event.defaultPrevented || event.isComposing || event.keyCode === 229) return null;
  const target = event.target;
  if (typeof Element !== "undefined" && target instanceof Element && target.closest("dialog, [role=dialog], [role=alertdialog]")) return null;
  return event.shiftKey ? -1 : 1;
}

/**
 * ⌘D on macOS, Ctrl+D elsewhere. Ctrl+D on macOS stays the text field's delete-forward key. The physical key counts only
 * when the layout types no Latin letter there (Russian), not when it types another one (Dvorak).
 */
export function isDictationToggle(
  event: Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "shiftKey" | "altKey" | "defaultPrevented" | "isComposing">,
  isMac: boolean = isMacPlatform(),
): boolean {
  if (event.defaultPrevented || event.isComposing || event.shiftKey || event.altKey) return false;
  if (isMac ? !event.metaKey || event.ctrlKey : !event.ctrlKey || event.metaKey) return false;
  const key = event.key.toLowerCase();
  return key === "d" || (event.code === "KeyD" && !/^[a-z]$/.test(key));
}

export function shouldOpenKeyboardShortcuts(event: KeyboardEvent): boolean {
  if (event.defaultPrevented || event.isComposing || event.altKey) return false;
  const helpKey = event.key === "?" && !event.metaKey && !event.ctrlKey;
  const helpChord = event.key === "/" && (event.metaKey || event.ctrlKey) && !event.shiftKey;
  if (!helpKey && !helpChord) return false;
  const target = event.target;
  return !(target instanceof HTMLElement && (
    target.isContentEditable || target.closest("input, textarea, select, dialog, [role=dialog]")
  ));
}

export function isMacPlatform(): boolean {
  if (typeof window !== "undefined" && window.ogb?.platform) {
    return window.ogb.platform === "darwin";
  }
  if (typeof navigator !== "undefined" && navigator.userAgent) {
    return navigator.userAgent.includes("Mac");
  }
  return true;
}

export function shortcutKeysForPlatform(
  item: ShortcutItem,
  isMac: boolean = isMacPlatform(),
): string[] {
  return isMac ? item.macKeys : item.winKeys;
}

export function filterShortcutGroups(
  groups: readonly ShortcutGroup[],
  query: string,
  isMac: boolean = isMacPlatform(),
): ShortcutGroup[] {
  const normalized = query.trim().toLowerCase();
  if (!normalized) return [...groups];

  return groups
    .map((group) => {
      const filteredItems = group.items.filter((item) => {
        const keys = shortcutKeysForPlatform(item, isMac).join(" ").toLowerCase();
        return (
          shortcutDescription(item).toLowerCase().includes(normalized) ||
          shortcutCategory(group).toLowerCase().includes(normalized) ||
          keys.includes(normalized)
        );
      });
      return { ...group, items: filteredItems };
    })
    .filter((group) => group.items.length > 0);
}