Files
search-with-chatgpt-powered…/test/shortcut.test.js
golem ff61aff5b9 feat: rewrite the options page for first-time users (#23)
Rewrites the options page for first-time users without removing any setting. Customization in a lightweight package is what sets this extension apart. Design: `docs/superpowers/specs/2026-10-18-options-page-for-first-time-users-design.md`.

**User-visible changes**
- **Layout:** the description stays as the first line, followed by a **Usage instructions** section and the **Settings** section. Each section has a heading and a divider.
- **Usage instructions:** one labelled line per way to open ChatGPT, each with a small drawing:
  - **Address bar:** `<Ctrl>+L`, then `gpt`, a space and the question. The drawing shows a ChatGPT label because the address-bar code shipped in Firefox 157.0.1 enters search mode when an engine keyword is followed by a space. I checked that in its `omni.ja`, but it still needs confirming on screen; see the checks below.
  - **Right-click:** a drawing of the menu with Ask ChatGPT highlighted.
  - **Keyboard:** key caps for the user's actual shortcut, held down. The line is hidden when no shortcut is set.
  - **Toolbar:** the hovered button with the pointer, its tooltip, the puzzle-piece Extensions button, and a selected heading.
- **Drawings:** they are HTML/CSS and inline SVG, not screenshots, so they follow light and dark themes, stay sharp, and never go stale. They are centred. The package grows from 52.8 KB to 56.5 KB.
- **Settings:**
  - **Right-click menu** (was "Context menu") and **Open ChatGPT in** stay visible.
  - Choosing **Advanced** reveals a drawing of the Ask ChatGPT submenu (Ask normally, Explain, Summarize, Debug code). It lives in the block that only shows for Advanced, so it needs no script.
  - Prompt template, temporary chat and web search move under **More options**, whose heading names them. It opens by itself on load, or when a sync changes one of them, if one of them isn't at its default.
  - **Restore defaults** is right-aligned and red.
- **Bottom of the page:**
  - The keyword/default-engine and keyboard-shortcut notes become collapsed sections with numbered steps.
  - The project links are centred, and stack on narrow panels.
- **Hotkeys:** written as `<Ctrl>+L` and `<Alt>+<Shift>+G`, including the user's actual shortcut. Mac users see `<Cmd>`, `<Option>` and `<Return>`, detected with `runtime.getPlatformInfo`, which needs no permission.
- **Docs:**
  - Keyword wording is corrected in the options page and README: Firefox adds a custom keyword alongside `gpt` instead of replacing it.
  - README and AGENTS.md use the new setting names.
  - AGENTS.md records the keep-every-setting rule, the hotkey format and the "filled in, never sent" copy rule.

These still match the original options design spec: the temporary-chat and web-search wording, and the rule that copy never says the question is sent.

No permission, search URL, privacy or packaging changes.

**Checks**
- `npm test`: lint 0 errors / 0 warnings, 61/61 unit tests, build OK.
- New tests:
  - the key formatter, including the Mac names Firefox stores (Command, MacCtrl, Alt)
  - the page's written hotkeys match the formatter
  - the keyboard drawing's key caps follow the live shortcut
- Rendered in headless Firefox 157 with the extension APIs stubbed:
  - light and dark themes
  - 680 px and 360 px wide
  - Mac key names
  - More options opening for a customised prompt template
  - both bottom sections expanded

**Manual Firefox checks (`npm run dev` → about:addons → Preferences)**
- [x] Typing `gpt` and a space shows a ChatGPT label in the address bar, as drawn. If it doesn't, the drawing drops the label and shows plain `gpt how do magnets work?`
- [x] Light and dark themes, and a narrow about:addons width
- [x] Expanding More options and the two bottom sections grows the inline panel without clipping or scrolling
- [x] The Keyboard line and its key caps disappear when the shortcut is removed, and come back showing the new keys when one is set
- [x] More options opens by itself after changing the prompt template and reopening the page
- [x] Choosing Advanced shows the submenu drawing; Simple and Off hide it
- [x] Settings still save, and Restore defaults still works

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: https://git.zavage.net/Zavage-Software/search-with-chatgpt-powered-by-openai-extension/pulls/23
Co-authored-by: golem <golem@zavage.net>
2026-10-18 22:53:27 -06:00

141 lines
6.6 KiB
JavaScript

import test from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { formatShortcut, initializeShortcut, renderStaticShortcuts } from "../options/shortcut.js";
function setup(commands, os) {
const elements = Object.fromEntries([
"shortcut-intro", "shortcut-intro-key", "shortcut-keycaps", "shortcut-current", "change-shortcut",
].map((id) => [id, Object.assign(new EventTarget(), {
textContent: "",
hidden: true,
children: [],
replaceChildren(...children) { this.children = children; },
})]));
const document = Object.assign(new EventTarget(), {
visibilityState: "visible",
getElementById: (id) => elements[id],
createElement: (tagName) => ({ tagName, className: "", textContent: "" }),
});
const window = new EventTarget();
const ready = initializeShortcut({ commands, document, window, os });
return { elements, document, window, ready };
}
const flush = () => new Promise((resolve) => setImmediate(resolve));
const command = (shortcut) => ({ name: "ask-chatgpt", description: "Ask ChatGPT", shortcut });
// The drawing's key caps and the "+" text between them, in order.
const drawn = (element) => element.children.map((child) => child.textContent ?? child);
test("shows the configured command rather than another command or the default", async () => {
const { elements, ready } = setup({ getAll: async () => [
{ name: "other", description: "Other", shortcut: "Alt+O" }, command("Ctrl+Shift+Y"),
] });
await ready;
assert.equal(elements["shortcut-intro"].hidden, false);
assert.equal(elements["shortcut-intro-key"].textContent, "<Ctrl>+<Shift>+Y");
assert.equal(elements["shortcut-current"].textContent, "Current shortcut: <Ctrl>+<Shift>+Y");
assert.deepEqual(drawn(elements["shortcut-keycaps"]), ["Ctrl", "+", "Shift", "+", "Y"]);
assert.ok(elements["shortcut-keycaps"].children
.filter((child) => typeof child !== "string")
.every(({ tagName, className }) => tagName === "kbd" && className === "drawing-key"));
});
test("writes keys the way the page does, with Mac names on a Mac", () => {
assert.equal(formatShortcut("Alt+Shift+G", "linux"), "<Alt>+<Shift>+G");
assert.equal(formatShortcut("Ctrl+L", "win"), "<Ctrl>+L");
assert.equal(formatShortcut("Enter", undefined), "<Enter>");
assert.equal(formatShortcut("Ctrl+Shift+F5", "win"), "<Ctrl>+<Shift>+<F5>");
// Firefox names punctuation and media keys rather than using the character.
assert.equal(formatShortcut("Ctrl+Shift+Comma", "win"), "<Ctrl>+<Shift>+<Comma>");
assert.equal(formatShortcut("MediaPlayPause", "linux"), "<MediaPlayPause>");
assert.equal(formatShortcut("Alt+Shift+G", "mac"), "<Option>+<Shift>+G");
// Firefox reads a manifest's Ctrl as Command on a Mac, and stores shortcuts
// the user sets there with Command and MacCtrl.
assert.equal(formatShortcut("Ctrl+L", "mac"), "<Cmd>+L");
assert.equal(formatShortcut("Command+Shift+Y", "mac"), "<Cmd>+<Shift>+Y");
assert.equal(formatShortcut("MacCtrl+Alt+Y", "mac"), "<Ctrl>+<Option>+Y");
assert.equal(formatShortcut("Enter", "mac"), "<Return>");
});
test("a Mac shows its own key names for the configured shortcut", async () => {
const { elements, ready } = setup({ getAll: async () => [command("Alt+Shift+G")] }, "mac");
await ready;
assert.equal(elements["shortcut-intro-key"].textContent, "<Option>+<Shift>+G");
assert.deepEqual(drawn(elements["shortcut-keycaps"]), ["Option", "+", "Shift", "+", "G"]);
});
test("the page's written hotkeys match the formatter and are rewritten per platform", () => {
const html = readFileSync(new URL("../options/options.html", import.meta.url), "utf8");
const written = [...html.matchAll(/data-shortcut="([^"]+)">([^<]*)</g)];
assert.ok(written.length >= 2);
// Every hotkey must match the pattern above, or this test would skip it.
assert.equal(written.length, html.split("data-shortcut=").length - 1);
for (const [, shortcut, text] of written) {
assert.equal(text.replaceAll("&lt;", "<").replaceAll("&gt;", ">"), formatShortcut(shortcut, "linux"));
}
const elements = written.map(([, shortcut]) => ({ dataset: { shortcut }, textContent: "" }));
renderStaticShortcuts({ querySelectorAll: () => elements }, "mac");
assert.deepEqual(
elements.map(({ textContent }) => textContent),
written.map(([, shortcut]) => formatShortcut(shortcut, "mac")),
);
assert.ok(elements.some(({ textContent }) => textContent === "<Cmd>+L"));
});
test("updates an open page when the shortcut is removed", async () => {
let changed;
let shortcut = "Alt+Shift+G";
const { elements, ready } = setup({
getAll: async () => [command(shortcut)],
onChanged: { addListener: (listener) => { changed = listener; } },
});
await ready;
shortcut = "";
changed({ name: "ask-chatgpt", newShortcut: "", oldShortcut: "Alt+Shift+G" });
await flush();
assert.match(elements["shortcut-current"].textContent, /No keyboard shortcut assigned/);
assert.equal(elements["shortcut-intro"].hidden, true);
assert.equal(elements["shortcut-intro-key"].textContent, "");
assert.deepEqual(elements["shortcut-keycaps"].children, []);
});
test("refreshes on focus and visibility without the change event API", async () => {
let shortcut = "Alt+Shift+G";
const { elements, window, document, ready } = setup({ getAll: async () => [command(shortcut)] });
await ready;
shortcut = "Ctrl+Shift+Y";
window.dispatchEvent(new Event("focus"));
await flush();
assert.match(elements["shortcut-current"].textContent, /<Ctrl>\+<Shift>\+Y/);
shortcut = "Alt+J";
document.dispatchEvent(new Event("visibilitychange"));
await flush();
assert.match(elements["shortcut-current"].textContent, /<Alt>\+J/);
});
test("missing commands and failed reads never claim the default is assigned", async () => {
for (const commands of [undefined, { getAll: async () => [] }, {
getAll: async () => { throw new Error("Unavailable"); },
}]) {
const { elements, ready } = setup(commands);
await ready;
assert.doesNotMatch(elements["shortcut-current"].textContent, /<Alt>\+<Shift>\+G|Alt\+Shift\+G/);
assert.equal(elements["shortcut-intro"].hidden, true);
assert.equal(elements["change-shortcut"].hidden, true);
}
});
test("shortcut editor failure displays manual recovery instructions", async () => {
const { elements, ready } = setup({
getAll: async () => [command("Alt+J")],
openShortcutSettings: async () => { throw new Error("Unavailable"); },
});
await ready;
assert.equal(elements["change-shortcut"].hidden, false);
elements["change-shortcut"].dispatchEvent(new Event("click"));
await flush();
assert.match(elements["shortcut-current"].textContent, /Manage Extension Shortcuts/);
});