Skip to content

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

9.3 KB
Raw Blame
// @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 { setLocale } from "@/lib/i18n";
import { MESSAGE_ROW, MessageActions, menuViewFloor } from "./MessageActions";

let host: HTMLDivElement;
let root: Root;

const row = () => host.querySelector<HTMLElement>(`[${MESSAGE_ROW}]`)!;
const body = () => host.querySelector<HTMLElement>("p")!;
const tray = () => host.querySelector<HTMLElement>('[data-testid="message-actions"]')!;
const shown = () => tray().dataset.shown === "true";
const more = () => tray().querySelector<HTMLButtonElement>('button[aria-haspopup="menu"]')!;
const items = () => [...host.querySelectorAll<HTMLButtonElement>("[role=menuitem]")];

const box = (top: number, height: number): DOMRect =>
  ({ top, bottom: top + height, height, left: 8, right: 48, width: 40, x: 8, y: top, toJSON() { return {}; } }) as DOMRect;

const pointer = (type: string, target: Element, pointerType: string) =>
  act(async () => {
    target.dispatchEvent(new PointerEvent(type, { bubbles: type !== "pointerenter" && type !== "pointerleave", pointerType }));
  });

let picked: string[] = [];

async function render(forceOpen = false) {
  await act(async () => {
    root.render(
      createElement("div", { [MESSAGE_ROW]: "" },
        createElement("div", { "data-chat-bubble": "" }, createElement("p", null, "an answer"), createElement("video", { "data-media": "" })),
        createElement("span", { "data-outside": "" }, "gap"),
        createElement(MessageActions, {
          side: "bot",
          forceOpen,
          contextItems: [{ key: "reply", icon: null, label: "Reply", onSelect: () => picked.push("reply") }],
          menu: [
            { key: "pin", icon: null, label: "Pin message", onSelect: () => picked.push("pin") },
            { key: "raw", icon: null, label: "Show raw markdown", onSelect: () => picked.push("raw") },
          ],
          children: createElement("button", { type: "button" }, "copy"),
        }),
      ),
    );
  });
}

beforeEach(() => {
  setLocale("en");
  picked = [];
  host = document.createElement("div");
  document.body.append(host);
  root = createRoot(host);
});

afterEach(async () => {
  await act(async () => root.unmount());
  host.remove();
  vi.useRealTimers();
});

describe("message actions row", () => {
  it("shows while the pointer is over the message and hides when it leaves", async () => {
    await render();
    expect(shown()).toBe(false);
    await pointer("pointerenter", row(), "mouse");
    expect(shown()).toBe(true);
    await pointer("pointerleave", row(), "mouse");
    expect(shown()).toBe(false);
  });

  it("does not treat a touch passing over as a hover", async () => {
    await render();
    await pointer("pointerenter", row(), "touch");
    expect(shown()).toBe(false);
  });

  it("shows on a tap of the message and hides on the next", async () => {
    await render();
    await pointer("pointerdown", body(), "touch");
    await pointer("pointerup", body(), "touch");
    expect(shown()).toBe(true);
    await pointer("pointerdown", body(), "touch");
    await pointer("pointerup", body(), "touch");
    expect(shown()).toBe(false);
  });

  it("shows on a long press of the message", async () => {
    vi.useFakeTimers();
    await render();
    await pointer("pointerdown", body(), "touch");
    await act(async () => { vi.advanceTimersByTime(500); });
    expect(shown()).toBe(true);
  });

  it("does not reveal actions after a canceled touch at the same position", async () => {
    vi.useFakeTimers();
    await render();
    await pointer("pointerdown", body(), "touch");
    await pointer("pointercancel", body(), "touch");
    await act(async () => { vi.advanceTimersByTime(500); });
    expect(shown()).toBe(false);
    await pointer("pointerup", body(), "touch");
    expect(shown()).toBe(false);
  });

  it("opens the more menu with the moved actions and closes it on a pick", async () => {
    await render();
    await pointer("pointerenter", row(), "mouse");
    expect(items()).toHaveLength(0);
    await act(async () => more().click());
    expect(more().getAttribute("aria-expanded")).toBe("true");
    expect(items().map((item) => item.textContent)).toEqual(["Pin message", "Show raw markdown"]);
    await pointer("pointerleave", row(), "mouse");
    expect(shown()).toBe(true);
    await act(async () => items()[0]!.click());
    expect(picked).toEqual(["pin"]);
    expect(items()).toHaveLength(0);
  });

  it("closes the menu on Escape", async () => {
    await render();
    await act(async () => more().click());
    expect(items()).toHaveLength(2);
    await act(async () => {
      document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
    });
    expect(items()).toHaveLength(0);
  });

  const rightClick = async (target: Element) => {
    const event = new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 40, clientY: 20 });
    await act(async () => { target.dispatchEvent(event); });
    return event.defaultPrevented;
  };

  it("opens the menu with the inline actions first on a right-click of the bubble", async () => {
    await render();
    expect(await rightClick(body())).toBe(true);
    expect(items().map((item) => item.textContent)).toEqual(["Reply", "Pin message", "Show raw markdown"]);
    await act(async () => items()[0]!.click());
    expect(picked).toEqual(["reply"]);
    await act(async () => more().click());
    expect(items().map((item) => item.textContent)).toEqual(["Pin message", "Show raw markdown"]);
  });

  it("leaves the native menu for a selection or a right-click beside the bubble", async () => {
    await render();
    expect(await rightClick(host.querySelector("[data-outside]")!)).toBe(false);
    window.getSelection()!.selectAllChildren(body());
    expect(await rightClick(body())).toBe(false);
    window.getSelection()!.removeAllRanges();
    expect(items()).toHaveLength(0);
  });

  it("leaves the native menu for a video in the bubble, which offers Save and Open", async () => {
    await render();
    expect(await rightClick(host.querySelector("[data-media]")!)).toBe(false);
    expect(items()).toHaveLength(0);
  });

  it("keeps a row that must stay reachable out", async () => {
    await render(true);
    expect(shown()).toBe(true);
    await pointer("pointerleave", row(), "mouse");
    expect(shown()).toBe(true);
  });

  it("opens the menu above a composer dock the downward sheet would cover", async () => {
    const frame = document.createElement("div");
    frame.setAttribute("data-glass-frame", "");
    const dock = document.createElement("div");
    dock.className = "chat-column-dock";
    host.replaceWith(frame);
    frame.append(host, dock);
    const restoreHeight = Object.getOwnPropertyDescriptor(window, "innerHeight");
    Object.defineProperty(window, "innerHeight", { configurable: true, value: 800 });
    const rects = vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(function (this: HTMLElement) {
      if (this === dock) return box(640, 160);
      if (this.getAttribute("role") === "menu") return box(632, 240);
      if (this.getAttribute("aria-haspopup") === "menu") return box(600, 28);
      return box(0, 0);
    });
    try {
      await render();
      await act(async () => more().click());
      const sheet = host.querySelector("[role=menu]")!;
      expect(sheet.className).toContain("bottom-full");
      expect(sheet.className).not.toContain("top-full");
    } finally {
      rects.mockRestore();
      if (restoreHeight) Object.defineProperty(window, "innerHeight", restoreHeight);
      else delete (window as { innerHeight?: number }).innerHeight;
      frame.replaceWith(host);
    }
  });
});

describe("menuViewFloor", () => {
  it("falls back to the window when there is no composer dock", () => {
    const node = document.createElement("div");
    expect(menuViewFloor(node, 800)).toBe(792);
    expect(menuViewFloor(null, 800)).toBe(792);
  });

  it("uses the closest chat column dock, not a dock in another frame", () => {
    const frame = document.createElement("div");
    frame.setAttribute("data-glass-frame", "");
    const from = frame.appendChild(document.createElement("div"));
    const dock = frame.appendChild(document.createElement("div"));
    dock.className = "chat-column-dock";
    const other = document.createElement("div");
    other.setAttribute("data-glass-frame", "");
    const otherDock = other.appendChild(document.createElement("div"));
    otherDock.className = "chat-column-dock";
    document.body.append(other, frame);
    vi.spyOn(dock, "getBoundingClientRect").mockReturnValue(box(640, 160));
    vi.spyOn(otherDock, "getBoundingClientRect").mockReturnValue(box(200, 80));
    expect(menuViewFloor(from, 800)).toBe(632);
    frame.remove();
    other.remove();
  });

  it("ignores a dock with no height", () => {
    const frame = document.createElement("div");
    frame.setAttribute("data-glass-frame", "");
    const from = frame.appendChild(document.createElement("div"));
    const dock = frame.appendChild(document.createElement("div"));
    dock.className = "chat-column-dock";
    document.body.append(frame);
    vi.spyOn(dock, "getBoundingClientRect").mockReturnValue(box(0, 0));
    expect(menuViewFloor(from, 800)).toBe(792);
    frame.remove();
  });
});