/*
* 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 = `
Meine Antwort
Am 24.11.2026 schrieb Anna:
Erster Satz. Zweiter Satz.
Dritter Absatz.
`;
/**
* Waits one macrotask so pending promises and timers (e.g. the config
* request of the compose script) can settle.
* @returns {Promise} 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