Inline Comment 0.2.0 - initial public release

Thunderbird/Betterbird add-on (Manifest V3): typing inside a quote splits
the quote and inserts your own text with a marker such as [OH]:.

- English and German user interface
- Licensed under the Mozilla Public License 2.0
- English documentation, JSDoc lint gate, 87 tests (node:test + jsdom)
This commit is contained in:
Oliver_Herb committed 2026-11-24 12:07:09 +01:00
commit 9053327486
57 files changed
+9849

No files matched your search

+457
View File
@@ -0,0 +1,457 @@
/*
* Copyright 2026 Oliver Herb
* SPDX-License-Identifier: MPL-2.0
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
"use strict";
/*
* End-to-end tests for the compose script in a simulated editor (jsdom).
* Each test loads the compose scripts (COMPOSE_SCRIPT_FILES) into a fresh
* jsdom window with a fake browser.runtime that answers "ic:getConfig",
* places the caret in a sample reply and dispatches keydown or beforeinput
* events. jsdom has no mail editor, so execCommand is emulated by a fake
* editor that records the commands it receives. Whether Betterbird really
* splits the quote like this on insertParagraph can only be checked by the
* manual test (.docs/guides/testplan.md).
*/
const { test } = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const {
createDocument,
setCaret,
setSelection,
firstText,
text,
} = require("./helpers/dom.js");
const {
COMPOSE_SCRIPT_FILES,
sanitizeSettings,
} = require("../src/lib/settings.js");
const SRC = path.join(__dirname, "..", "src");
// Source of the compose scripts, in the order the background script injects them.
const SOURCES = COMPOSE_SCRIPT_FILES.map((file) =>
fs.readFileSync(path.join(SRC, file), "utf8"),
);
// Sample HTML reply: own text on top, the attribution line and a quote with
// two paragraphs. The sample texts in this file are German on purpose (a
// reply as a German mail client writes it); only their structure matters.
const REPLY = `
<p id="own">Meine Antwort</p>
<div class="moz-cite-prefix">Am 24.11.2026 schrieb Anna:</div>
<blockquote type="cite" id="outer"><p id="q1">Erster Satz. Zweiter Satz.</p><p>Dritter Absatz.</p></blockquote>`;
/**
* Waits one macrotask so pending promises and timers (e.g. the config
* request of the compose script) can settle.
* @returns {Promise<void>} Resolves on the next turn of the event loop.
*/
function tick() {
return new Promise((resolve) => setTimeout(resolve, 0));
}
/**
* Replaces document.execCommand with a fake editor that supports the
* commands the compose script uses (insertParagraph, insertHTML, insertText,
* delete, undo) and records every call.
* @param {Window} window jsdom window whose document gets the fake editor.
* @param {{ nativeSplit: boolean }} options When nativeSplit is true,
* insertParagraph splits the quote like Betterbird does (a line break
* between the two halves, caret before it); when false, insertParagraph
* does nothing and returns false.
* @returns {{ calls: string[], insertedHtml: string[] }} The names of all
* executed commands and the HTML strings passed to insertHTML.
*/
function installFakeEditor(window, { nativeSplit }) {
const doc = window.document;
const calls = [];
// HTML strings passed to insertHTML, to check what the script hands over.
const insertedHtml = [];
/**
* Fake document.execCommand: records the command and emulates its effect
* on the current selection.
* @param {string} command Editor command, e.g. "insertParagraph".
* @param {boolean} _showUi Ignored, as in the real API.
* @param {string} [value] Argument of insertHTML and insertText.
* @returns {boolean} True if the command was handled, false for
* unsupported commands and for insertParagraph without a native split.
*/
doc.execCommand = (command, _showUi, value) => {
calls.push(command);
const IC = window.InlineComment;
const selection = doc.getSelection();
const range = selection.getRangeAt(0);
switch (command) {
case "insertParagraph": {
const ctx = IC.caretContext(doc);
if (!nativeSplit || !ctx || !ctx.cite) {
return false;
}
const br = doc.createElement("br");
IC.splitCiteAtRange(doc, ctx.range, ctx.cite, br);
const after = doc.createRange();
after.setStartBefore(br);
selection.removeAllRanges();
selection.addRange(after);
return true;
}
case "insertHTML": {
insertedHtml.push(value);
const template = doc.createElement("template");
template.innerHTML = value;
const last = template.content.lastChild;
range.insertNode(template.content);
range.setStartAfter(last);
range.collapse(true);
return true;
}
case "insertText": {
const node = doc.createTextNode(value);
range.insertNode(node);
range.setStartAfter(node);
range.collapse(true);
return true;
}
case "delete":
range.deleteContents();
return true;
case "undo":
return true;
default:
return false;
}
};
return { calls, insertedHtml };
}
/**
* Opens a simulated compose window: creates a jsdom document with the given
* body, installs a fake WebExtension runtime and the fake editor, then runs
* the compose scripts in the window.
* @param {string} bodyHtml Markup of the message body.
* @param {object} [options] Test options.
* @param {boolean} [options.active] Whether the add-on is switched on for
* this compose window. Defaults to true.
* @param {boolean} [options.isPlainText] Whether the message is composed as
* plain text. Defaults to false.
* @param {boolean} [options.nativeSplit] Whether the fake editor splits the
* quote on insertParagraph (see installFakeEditor). Defaults to false.
* @param {object} [options.settings] Settings merged over
* { splitMode: "manual" } and passed through sanitizeSettings.
* @returns {Promise<{ window: Window, doc: Document, calls: string[],
* insertedHtml: string[], listeners: Array<(message: object) => unknown>,
* config: object }>} The
* window and document, the recorded editor commands and insertHTML values,
* the registered runtime.onMessage listeners and the config sent to the
* compose script.
*/
async function openCompose(bodyHtml, options = {}) {
const { window, doc } = createDocument(bodyHtml, {
runScripts: "outside-only",
});
const listeners = [];
const config = {
active: options.active !== false,
isPlainText: Boolean(options.isPlainText),
settings: sanitizeSettings({ splitMode: "manual", ...options.settings }),
identity: { name: "Max Mustermann", email: "max@example.com" },
};
window.browser = {
runtime: {
/**
* Fake runtime.sendMessage: answers only the config request.
* @param {{ type: string }} message Message sent by the compose script.
* @returns {Promise<object | undefined>} The config for
* "ic:getConfig", undefined for any other message.
*/
sendMessage: async (message) =>
message.type === "ic:getConfig" ? config : undefined,
onMessage: {
/**
* Fake runtime.onMessage.addListener: records the listener so a
* test can call it with a pushed config.
* @param {(message: object) => unknown} listener Listener registered
* by the compose script.
* @returns {number} The new number of listeners (unused).
*/
addListener: (listener) => listeners.push(listener),
},
},
};
const { calls, insertedHtml } = installFakeEditor(window, {
nativeSplit: Boolean(options.nativeSplit),
});
for (const source of SOURCES) {
window.eval(source);
}
await tick();
return { window, doc, calls, insertedHtml, listeners, config };
}
/**
* Dispatches a cancelable, bubbling keydown event on the document body.
* @param {Window} window jsdom window to dispatch in.
* @param {string} key Value of KeyboardEvent.key, e.g. "a" or "Enter".
* @param {KeyboardEventInit} [init] Extra event properties such as
* { ctrlKey: true }.
* @returns {KeyboardEvent} The dispatched event, to check defaultPrevented.
*/
function press(window, key, init = {}) {
const event = new window.KeyboardEvent("keydown", {
key,
bubbles: true,
cancelable: true,
...init,
});
window.document.body.dispatchEvent(event);
return event;
}
/**
* Returns all inline comments inserted by the add-on.
* @param {Document} doc Document to search.
* @returns {NodeListOf<Element>} Elements carrying data-inline-comment.
*/
function comments(doc) {
return doc.querySelectorAll("[data-inline-comment]");
}
/**
* Tells whether the caret (the selection's anchor node) lies inside the
* element.
* @param {Document} doc Document whose selection is checked.
* @param {Element} element Element that should contain the caret.
* @returns {boolean} True if the anchor node is the element or inside it.
*/
function caretInside(doc, element) {
return element.contains(doc.getSelection().anchorNode);
}
test("typing inside a quote splits it and inserts the marker (manual split)", async () => {
const { window, doc } = await openCompose(REPLY);
setCaret(doc, firstText(doc.getElementById("q1")), "Erster Satz.".length);
const event = press(window, "a");
assert.equal(event.defaultPrevented, true);
const [comment] = comments(doc);
assert.ok(comment, "comment missing");
assert.equal(text(comment), "[MM]: a");
assert.equal(text(comment.previousElementSibling), "Erster Satz.");
const tail = comment.nextElementSibling;
assert.equal(tail.getAttribute("type"), "cite");
assert.deepEqual([...tail.querySelectorAll("p")].map(text), [
"Zweiter Satz.",
"Dritter Absatz.",
]);
assert.equal(doc.querySelectorAll('blockquote[type="cite"]').length, 2);
assert.ok(caretInside(doc, comment), "caret is not inside the comment");
// Typing on inside the comment does not insert a second marker.
const second = press(window, "b");
assert.equal(second.defaultPrevented, false);
assert.equal(comments(doc).length, 1);
});
test("native split: insertParagraph, then insertHTML", async () => {
const { window, doc, calls } = await openCompose(REPLY, {
nativeSplit: true,
settings: { splitMode: "native" },
});
setCaret(doc, firstText(doc.getElementById("q1")), "Erster Satz.".length);
press(window, "x");
assert.deepEqual(calls, ["insertParagraph", "insertHTML"]);
const [comment] = comments(doc);
assert.equal(text(comment), "[MM]: x");
assert.equal(comment.previousElementSibling.getAttribute("type"), "cite");
assert.ok(caretInside(doc, comment));
});
test("editor does not split: undo, then fall back to the manual split", async () => {
const { window, doc, calls } = await openCompose(REPLY, {
nativeSplit: false,
settings: { splitMode: "native" },
});
setCaret(doc, firstText(doc.getElementById("q1")), "Erster Satz.".length);
press(window, "y");
assert.deepEqual(calls, ["insertParagraph", "undo"]);
assert.equal(text(comments(doc)[0]), "[MM]: y");
assert.equal(doc.querySelectorAll('blockquote[type="cite"]').length, 2);
});
test("paused: nothing happens", async () => {
const { window, doc, calls } = await openCompose(REPLY, { active: false });
setCaret(doc, firstText(doc.getElementById("q1")), 3);
const event = press(window, "a");
assert.equal(event.defaultPrevented, false);
assert.equal(calls.length, 0);
assert.equal(comments(doc).length, 0);
});
test("a config message from the background script switches the add-on on", async () => {
const { window, doc, listeners, config } = await openCompose(REPLY, {
active: false,
});
listeners.forEach((listener) =>
listener({ type: "ic:config", config: { ...config, active: true } }),
);
setCaret(doc, firstText(doc.getElementById("q1")), 3);
assert.equal(press(window, "a").defaultPrevented, true);
assert.equal(comments(doc).length, 1);
});
test("outside quotes and for shortcuts: keys are not intercepted", async () => {
const { window, doc, calls } = await openCompose(REPLY);
setCaret(doc, firstText(doc.getElementById("own")), 2);
assert.equal(press(window, "a").defaultPrevented, false);
setCaret(doc, firstText(doc.getElementById("q1")), 3);
assert.equal(press(window, "c", { ctrlKey: true }).defaultPrevented, false);
assert.equal(press(window, "Enter").defaultPrevented, false);
assert.equal(calls.length, 0);
});
test("the gap left by Enter inside a quote gets the marker", async () => {
const { window, doc, calls } = await openCompose(
`<blockquote type="cite">Teil A</blockquote><br id="gap"><blockquote type="cite">Teil B</blockquote>`,
{ settings: { splitMode: "native" } },
);
const index = Array.prototype.indexOf.call(
doc.body.childNodes,
doc.getElementById("gap"),
);
setCaret(doc, doc.body, index);
assert.equal(press(window, "z").defaultPrevented, true);
assert.deepEqual(calls, ["insertHTML"]);
const [comment] = comments(doc);
assert.equal(text(comment), "[MM]: z");
assert.ok(caretInside(doc, comment));
});
test("selected quote text is replaced", async () => {
const { window, doc, calls } = await openCompose(REPLY);
const node = firstText(doc.getElementById("q1"));
setSelection(
doc,
node,
"Erster Satz. ".length,
node,
"Erster Satz. Zweiter Satz.".length,
);
press(window, "n");
assert.equal(calls[0], "delete");
assert.doesNotMatch(text(doc.body), /Zweiter Satz/);
assert.equal(text(comments(doc)[0]), "[MM]: n");
});
test("plain text: the marker is inserted as text, without an HTML block", async () => {
const { window, doc, calls } = await openCompose(
`<span _moz_quote="true" id="q">&gt; Erste Zeile<br>&gt; Zweite Zeile</span>`,
{ isPlainText: true, nativeSplit: true, settings: { splitMode: "native" } },
);
setCaret(doc, doc.getElementById("q").firstChild, "> Erste".length);
press(window, "k");
assert.deepEqual(calls, ["insertParagraph", "insertText"]);
assert.match(text(doc.body), /\[MM\]: k/);
assert.equal(doc.querySelector("div[data-inline-comment]"), null);
});
test("a custom template with {name} is used", async () => {
const { window, doc } = await openCompose(REPLY, {
settings: { template: "{name} meint:" },
});
setCaret(doc, firstText(doc.getElementById("q1")), 0);
press(window, "J");
assert.equal(text(comments(doc)[0]), "Max Mustermann meint: J");
});
test("fallback via beforeinput (e.g. on-screen keyboard)", async (t) => {
const { window, doc } = await openCompose(REPLY);
const probe = new window.InputEvent("beforeinput", {
inputType: "insertText",
data: "x",
});
if (probe.inputType !== "insertText") {
t.skip("jsdom does not support inputType");
return;
}
setCaret(doc, firstText(doc.getElementById("q1")), 3);
const event = new window.InputEvent("beforeinput", {
inputType: "insertText",
data: "ü",
bubbles: true,
cancelable: true,
});
doc.body.dispatchEvent(event);
assert.equal(event.defaultPrevented, true);
await tick();
assert.equal(text(comments(doc)[0]), "[MM]: ü");
});
test("native split: insertHTML gets the serialized comment node", async () => {
const { window, doc, insertedHtml } = await openCompose(REPLY, {
nativeSplit: true,
settings: { splitMode: "native" },
});
setCaret(doc, firstText(doc.getElementById("q1")), "Erster Satz.".length);
press(window, "x");
assert.equal(insertedHtml.length, 1);
const [html] = insertedHtml;
const [comment] = comments(doc);
const id = comment.getAttribute("data-inline-comment");
assert.match(id, /^ic-[0-9a-z]+-[0-9a-z]+$/);
const settings = sanitizeSettings({ splitMode: "native" });
const expected = window.InlineComment.createCommentNode(
doc,
"[MM]:",
"x",
settings,
id,
);
assert.equal(html, expected.outerHTML);
assert.ok(comment.isEqualNode(expected));
});
for (const splitMode of ["native", "manual"]) {
test(`HTML in the marker template stays text (${splitMode} split)`, async () => {
const template = '<img src="x" onerror="alert(1)"><b>{initials}</b>:';
const { window, doc } = await openCompose(REPLY, {
nativeSplit: true,
settings: { splitMode, template },
});
setCaret(doc, firstText(doc.getElementById("q1")), "Erster Satz.".length);
press(window, "<");
const [comment] = comments(doc);
assert.ok(comment, "comment missing");
assert.equal(doc.querySelector("img, b"), null);
assert.equal(
comment.querySelector("[data-inline-comment-marker]").textContent,
'<img src="x" onerror="alert(1)"><b>MM</b>:',
);
assert.equal(comment.lastChild.data, "\u00a0<");
});
}
test("manual split inserts the comment node without execCommand", async () => {
const { window, doc, calls } = await openCompose(REPLY, {
settings: { splitMode: "manual" },
});
setCaret(doc, firstText(doc.getElementById("q1")), "Erster Satz.".length);
press(window, " ");
assert.deepEqual(calls, []);
const [comment] = comments(doc);
assert.equal(comment.localName, "div");
assert.equal(
comment.querySelector("[data-inline-comment-marker]").textContent,
"[MM]:",
);
assert.equal(comment.lastChild.data, "\u00a0\u00a0");
assert.ok(caretInside(doc, comment));
});