Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
// @vitest-environment happy-dom
import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
MENU_MIN_WIDTH,
SidebarPopoverMenu,
anchoredMenuPosition,
nextMenuIndex,
submenuPosition,
type SidebarMenuItem,
} from "./SidebarPopoverMenu";
const viewport = { width: 1280, height: 800 };
const menu = { width: 280, height: 300 };
const wideRow = { left: 12, right: 288, top: 740, bottom: 784 };
const avatar = { left: 14, right: 58, top: 740, bottom: 784 };
describe("anchoredMenuPosition", () => {
it("opens above the trigger on its start edge, the same for a row and a lone avatar", () => {
expect(anchoredMenuPosition(wideRow, menu, viewport)).toEqual({ left: 12, top: 740 - 6 - 300 });
expect(anchoredMenuPosition(avatar, menu, viewport)).toEqual({ left: 14, top: 434 });
});
it("opens a choice at a row's end below it on its end edge, and above when it would run off the window", () => {
const end = { left: 700, right: 800, top: 200, bottom: 230 };
expect(anchoredMenuPosition(end, menu, viewport, false, "end")).toEqual({ left: 800 - 280, top: 236 });
expect(anchoredMenuPosition(end, menu, viewport, true, "end")).toEqual({ left: 700, top: 236 });
expect(anchoredMenuPosition({ ...end, top: 740, bottom: 770 }, menu, viewport, false, "end")).toEqual({ left: 520, top: 434 });
});
it("anchors to the trigger's right edge in RTL, and stays inside the window", () => {
const rtlRow = { left: 980, right: 1268, top: 740, bottom: 784 };
expect(anchoredMenuPosition(rtlRow, menu, viewport, true)).toEqual({ left: 1268 - 280, top: 434 });
expect(anchoredMenuPosition({ left: 0, right: 44, top: 740, bottom: 784 }, menu, viewport, true).left).toBe(8);
});
it("never runs off the inline end of a narrow window", () => {
expect(anchoredMenuPosition({ left: 200, right: 260, top: 500, bottom: 540 }, menu, { width: 320, height: 600 }).left).toBe(320 - 280 - 8);
});
it("drops below the trigger when there is no room above, and clamps to a short window", () => {
expect(anchoredMenuPosition({ left: 12, right: 60, top: 40, bottom: 80 }, menu, viewport).top).toBe(86);
expect(anchoredMenuPosition({ left: 12, right: 60, top: 100, bottom: 140 }, menu, { width: 800, height: 320 }).top).toBe(12);
});
});
describe("submenuPosition", () => {
const sheet = { left: 12, right: 292, top: 434, bottom: 734 };
const row = { left: 18, right: 286, top: 520, bottom: 560 };
const sub = { width: 240, height: 180 };
it("sits beside the menu on the inline end side, level with its row", () => {
expect(submenuPosition(sheet, row, sub, viewport)).toEqual({ left: 296, top: 514 });
expect(submenuPosition({ left: 988, right: 1268, top: 434, bottom: 734 }, row, sub, viewport, true)).toEqual({ left: 988 - 4 - 240, top: 514 });
});
it("flips to the other side when the window has no room", () => {
const right = { left: 900, right: 1180, top: 434, bottom: 734 };
expect(submenuPosition(right, row, sub, viewport).left).toBe(900 - 4 - 240);
});
});
it("moves through the items with arrows, Home and End, wrapping", () => {
expect(nextMenuIndex("ArrowDown", -1, 4)).toBe(0);
expect(nextMenuIndex("ArrowDown", 3, 4)).toBe(0);
expect(nextMenuIndex("ArrowUp", 0, 4)).toBe(3);
expect(nextMenuIndex("Home", 2, 4)).toBe(0);
expect(nextMenuIndex("End", 0, 4)).toBe(3);
expect(nextMenuIndex("a", 0, 4)).toBeNull();
});
describe("the anchored menu in a document", () => {
let host: HTMLDivElement;
let root: Root;
const picked: string[] = [];
const item = (key: string, extra: Partial<SidebarMenuItem> = {}): SidebarMenuItem => ({ key, label: key, onSelect: () => picked.push(key), ...extra });
const items: SidebarMenuItem[] = [
item("Usage"),
item("Help and support", { submenu: [item("Help Center"), item("About")] }),
item("Settings"),
item("Account", { separatorBefore: true, value: "Pro" }),
];
const sheet = () => document.querySelector<HTMLElement>("[data-sidebar-popover-menu]");
const submenu = () => document.querySelector<HTMLElement>("[data-sidebar-popover-submenu]");
const trigger = () => host.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!;
const key = async (target: Element, keyName: string) => {
await act(async () => {
target.dispatchEvent(new KeyboardEvent("keydown", { key: keyName, bubbles: true, cancelable: true }));
window.dispatchEvent(new KeyboardEvent("keydown", { key: keyName, cancelable: true }));
});
};
const flush = () => act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
beforeEach(async () => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
document.documentElement.dataset.reducedMotion = "true";
picked.length = 0;
host = document.createElement("div");
document.body.appendChild(host);
root = createRoot(host);
await act(async () => {
root.render(createElement(SidebarPopoverMenu, { items, ariaLabel: "You", renderTrigger: () => "You" }));
});
});
afterEach(async () => {
await act(async () => root.unmount());
host.remove();
});
it("portals one sheet, at least 237px wide, to the body, with the group divider and the trailing value and chevron", async () => {
await act(async () => trigger().click());
const menu = sheet()!;
expect(menu.parentElement).toBe(document.body);
expect(menu.style.position).toBe("fixed");
expect(menu.style.minWidth).toBe(`${MENU_MIN_WIDTH}px`);
expect(menu.getAttribute("role")).toBe("menu");
expect(menu.querySelectorAll('[role="separator"]')).toHaveLength(1);
expect(menu.textContent).toContain("Pro");
const support = [...menu.querySelectorAll('[role="menuitem"]')].find((node) => node.textContent?.includes("Help and support"))!;
expect(support.getAttribute("aria-haspopup")).toBe("menu");
expect(support.querySelector("svg")).not.toBeNull();
expect(menu.querySelector('[role="menuitem"]')!.className).toContain("text-[14px]");
});
it("opens from the keyboard on the first item and walks the items", async () => {
await key(trigger(), "ArrowUp");
await flush();
const rows = [...sheet()!.querySelectorAll<HTMLElement>('[role="menuitem"]')];
expect(document.activeElement).toBe(rows[0]);
await key(rows[0]!, "End");
expect(document.activeElement).toBe(rows[3]);
await key(rows[3]!, "ArrowDown");
expect(document.activeElement).toBe(rows[0]);
});
it("opens the submenu with the inline end arrow and closes only it with Escape", async () => {
await act(async () => trigger().click());
const support = [...sheet()!.querySelectorAll<HTMLElement>('[role="menuitem"]')][1]!;
support.focus();
await key(support, "ArrowRight");
await flush();
expect(submenu()).not.toBeNull();
expect(support.getAttribute("aria-expanded")).toBe("true");
const first = submenu()!.querySelector<HTMLElement>('[role="menuitem"]')!;
await act(async () => first.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true })));
expect(submenu()).toBeNull();
expect(sheet()).not.toBeNull();
expect(document.activeElement).toBe(support);
});
describe("hovering a row with a submenu", () => {
const wait = (ms: number) => act(async () => { await new Promise((resolve) => setTimeout(resolve, ms)); });
const rows = () => [...sheet()!.querySelectorAll<HTMLElement>('[role="menuitem"]')];
const hover = (to: Element, from: Element | null, y: number) => act(async () => {
from?.dispatchEvent(new MouseEvent("pointerout", { bubbles: true, relatedTarget: to, clientX: 100, clientY: y }));
to.dispatchEvent(new MouseEvent("pointerover", { bubbles: true, relatedTarget: from, clientX: 100, clientY: y }));
});
it("does not open it when the pointer only passes over the row", async () => {
await act(async () => trigger().dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 })));
const [usage, support, settings] = rows();
await hover(support!, usage!, 60);
await wait(100);
expect(submenu()).toBeNull();
await hover(settings!, support!, 90);
await wait(400);
expect(submenu()).toBeNull();
expect(support!.getAttribute("aria-expanded")).toBe("false");
});
it("opens it after the pointer rests on the row, and closes it the moment a sibling row takes the pointer", async () => {
await act(async () => trigger().dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 })));
const [usage, support, settings] = rows();
await hover(support!, usage!, 60);
await wait(320);
expect(submenu()).not.toBeNull();
expect(support!.classList.contains("bg-menu-hover")).toBe(false);
await hover(settings!, support!, 90);
expect(submenu()).toBeNull();
});
it("opens it at once on a click, without moving focus into it", async () => {
await act(async () => trigger().dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 })));
const support = rows()[1]!;
await act(async () => support.dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 })));
await flush();
expect(submenu()).not.toBeNull();
expect(submenu()!.contains(document.activeElement)).toBe(false);
});
});
it("runs a submenu item and closes everything", async () => {
await act(async () => trigger().click());
const support = [...sheet()!.querySelectorAll<HTMLElement>('[role="menuitem"]')][1]!;
await act(async () => support.click());
await act(async () => [...submenu()!.querySelectorAll<HTMLElement>('[role="menuitem"]')][1]!.click());
expect(picked).toEqual(["About"]);
expect(sheet()).toBeNull();
});
it("closes on Escape and gives focus back to the trigger", async () => {
await act(async () => trigger().click());
await key(sheet()!, "Escape");
expect(sheet()).toBeNull();
expect(document.activeElement).toBe(trigger());
});
describe("inside something that also closes on Escape, such as a panel", () => {
const outer = vi.fn();
const onWindow = vi.fn();
beforeEach(async () => {
outer.mockReset();
onWindow.mockReset();
window.addEventListener("keydown", onWindow);
await act(async () => {
root.render(createElement("div", { onKeyDown: (event: { key: string }) => outer(event.key) },
createElement(SidebarPopoverMenu, { items, ariaLabel: "You", renderTrigger: () => "You" })));
});
});
afterEach(() => window.removeEventListener("keydown", onWindow));
const escape = (target: Element) => act(async () => {
target.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
});
it("closes a mouse-opened menu on Escape at its trigger, and the panel never sees that Escape", async () => {
trigger().focus();
await act(async () => trigger().dispatchEvent(new MouseEvent("click", { bubbles: true, detail: 1 })));
expect(sheet()).not.toBeNull();
expect(document.activeElement).toBe(trigger());
await escape(trigger());
expect(sheet()).toBeNull();
expect(document.activeElement).toBe(trigger());
expect(outer).not.toHaveBeenCalled();
expect(onWindow).not.toHaveBeenCalled();
// With the menu closed, the next Escape is the panel's again.
await escape(trigger());
expect(outer).toHaveBeenCalledWith("Escape");
});
it("closes on Escape from inside the portalled sheet before the key bubbles to the panel", async () => {
await key(trigger(), "ArrowDown");
await flush();
const first = sheet()!.querySelector<HTMLElement>('[role="menuitem"]')!;
expect(document.activeElement).toBe(first);
outer.mockReset();
onWindow.mockReset();
await escape(first);
expect(sheet()).toBeNull();
expect(document.activeElement).toBe(trigger());
expect(outer).not.toHaveBeenCalled();
expect(onWindow).not.toHaveBeenCalled();
});
});
describe("opens on the mouse's press", () => {
const press = (target: Element, pointerType = "mouse", button = 0) =>
act(async () => { target.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, cancelable: true, pointerType, button })); });
// One Escape, as the browser sends it: the window sees it only if nothing handled it first.
const escape = (target: Element) => act(async () => {
const event = new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true });
target.dispatchEvent(event);
if (!event.defaultPrevented) window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", cancelable: true }));
});
const release = (target: Element, detail = 1) =>
act(async () => { target.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail })); });
it("opens on the press, and the click that ends the same press leaves it open", async () => {
await press(trigger());
expect(sheet()).not.toBeNull();
await release(trigger());
expect(sheet()).not.toBeNull();
expect(trigger().getAttribute("aria-expanded")).toBe("true");
});
it("closes on the next press of its trigger, and that press's click does not reopen it", async () => {
await press(trigger());
await release(trigger());
await press(trigger());
expect(sheet()).toBeNull();
await release(trigger());
expect(sheet()).toBeNull();
});
it("leaves touch, pen and a secondary button to the tap", async () => {
await press(trigger(), "touch");
expect(sheet()).toBeNull();
await release(trigger());
expect(sheet()).not.toBeNull();
await release(trigger());
await press(trigger(), "mouse", 2);
expect(sheet()).toBeNull();
});
it("still opens from Enter or Space on the first item, after a press that was released somewhere else", async () => {
await press(trigger());
await press(document.body);
expect(sheet()).toBeNull();
await release(trigger(), 0);
await flush();
expect(document.activeElement).toBe(sheet()!.querySelector('[role="menuitem"]'));
});
it("closes on a press outside after a press opened it", async () => {
await press(trigger());
await release(trigger());
await act(async () => document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true, pointerType: "mouse" })));
expect(sheet()).toBeNull();
});
it("hands focus back on Escape without the keyboard ring after the mouse opened it", async () => {
trigger().focus();
await press(trigger());
await release(trigger());
await escape(trigger());
expect(sheet()).toBeNull();
expect(document.activeElement).toBe(trigger());
expect(trigger().hasAttribute("data-quiet-focus")).toBe(true);
// The next key is the keyboard's: the ring is back.
await key(trigger(), "Tab");
expect(trigger().hasAttribute("data-quiet-focus")).toBe(false);
});
it("keeps the ring on Escape after the keyboard opened it", async () => {
await key(trigger(), "ArrowDown");
await flush();
await escape(sheet()!.querySelector('[role="menuitem"]')!);
expect(document.activeElement).toBe(trigger());
expect(trigger().hasAttribute("data-quiet-focus")).toBe(false);
});
it("keeps the ring when the mouse opened it but the arrows went into it", async () => {
await press(trigger());
await release(trigger());
await key(trigger(), "ArrowDown");
const first = sheet()!.querySelector<HTMLElement>('[role="menuitem"]')!;
first.focus();
await escape(first);
expect(document.activeElement).toBe(trigger());
expect(trigger().hasAttribute("data-quiet-focus")).toBe(false);
});
});
it("closes on a press outside, but not on a press inside the portalled sheet", async () => {
await act(async () => trigger().click());
await act(async () => sheet()!.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })));
expect(sheet()).not.toBeNull();
await act(async () => document.body.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })));
expect(sheet()).toBeNull();
});
});
describe("a menu opening below its trigger", () => {
it("shows a submenu the pointer can pick from", async () => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const picked: string[] = [];
const item = (key: string, extra: Partial<SidebarMenuItem> = {}): SidebarMenuItem => ({ key, label: key, onSelect: () => picked.push(key), ...extra });
const host = document.createElement("div");
document.body.appendChild(host);
const root = createRoot(host);
await act(async () => {
root.render(createElement(SidebarPopoverMenu, {
items: [item("Find"), item("All threads", { submenu: [item("Trip plan"), item("Our chat")] })],
ariaLabel: "More",
placement: "below",
renderTrigger: () => "More",
}));
});
await act(async () => host.querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!.click());
const row = [...host.querySelectorAll<HTMLElement>('[role="menuitem"]')].find((node) => node.textContent?.includes("All threads"))!;
await act(async () => row.click());
await act(async () => { await new Promise((resolve) => setTimeout(resolve, 20)); });
const sub = document.querySelector<HTMLElement>("[data-sidebar-popover-submenu]")!;
expect(sub).not.toBeNull();
expect(sub.style.visibility).not.toBe("hidden");
// The submenu sits outside the menu's own box, so pressing on it must not count as a press outside the menu.
const pick = sub.querySelector<HTMLElement>('[role="menuitem"]')!;
await act(async () => { pick.dispatchEvent(new PointerEvent("pointerdown", { bubbles: true })); });
await act(async () => pick.click());
expect(picked).toEqual(["Trip plan"]);
await act(async () => root.unmount());
host.remove();
});
});