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:
commit
9053327486
57 files changed
+9849
No files matched your search
@@ -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">> Erste Zeile<br>> 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));
|
||||
});
|
||||
@@ -0,0 +1,92 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
/*
|
||||
* The add-on must not write markup into DOM sinks: addons.thunderbird.net
|
||||
* reviewers reject innerHTML/outerHTML assignments, insertAdjacentHTML and
|
||||
* document.write. DOM is built with createElement, textContent and
|
||||
* setAttribute instead. Reading outerHTML (to serialize a node for
|
||||
* execCommand "insertHTML") is allowed.
|
||||
*
|
||||
* These are static checks: every file below src/ is read as text and matched
|
||||
* against regular expressions for the forbidden sinks; no DOM is involved.
|
||||
*/
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const SRC = path.join(__dirname, "..", "src");
|
||||
|
||||
const FORBIDDEN = Object.freeze([
|
||||
{ name: "innerHTML", pattern: /innerHTML/ },
|
||||
{ name: "outerHTML =", pattern: /outerHTML\s*\+?=(?!=)/ },
|
||||
{ name: "insertAdjacentHTML", pattern: /insertAdjacentHTML/ },
|
||||
{ name: "document.write", pattern: /document\.write(?:ln)?\s*\(/ },
|
||||
]);
|
||||
|
||||
/**
|
||||
* Lists all files below dir, recursively (every type: scripts, pages,
|
||||
* styles, JSON, images).
|
||||
* @param {string} dir Absolute directory path.
|
||||
* @returns {string[]} Absolute paths of all files found.
|
||||
*/
|
||||
function allFiles(dir) {
|
||||
const files = [];
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
files.push(...allFiles(full));
|
||||
} else {
|
||||
files.push(full);
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the forbidden DOM sinks that occur in a source text.
|
||||
* @param {string} source File content to check.
|
||||
* @returns {string[]} Names (from FORBIDDEN) of the sinks found; empty if
|
||||
* the text is clean.
|
||||
*/
|
||||
function sinksIn(source) {
|
||||
return FORBIDDEN.filter(({ pattern }) => pattern.test(source)).map(
|
||||
({ name }) => name,
|
||||
);
|
||||
}
|
||||
|
||||
test("the sink patterns catch writes and allow reading outerHTML", () => {
|
||||
assert.deepEqual(sinksIn("el.innerHTML = html;"), ["innerHTML"]);
|
||||
assert.deepEqual(sinksIn("const x = el.innerHTML;"), ["innerHTML"]);
|
||||
assert.deepEqual(sinksIn("el.outerHTML = html;"), ["outerHTML ="]);
|
||||
assert.deepEqual(sinksIn("el.outerHTML=html;"), ["outerHTML ="]);
|
||||
assert.deepEqual(sinksIn("el.outerHTML += html;"), ["outerHTML ="]);
|
||||
assert.deepEqual(sinksIn("el.insertAdjacentHTML('beforeend', html);"), [
|
||||
"insertAdjacentHTML",
|
||||
]);
|
||||
assert.deepEqual(sinksIn("document.write('<p>');"), ["document.write"]);
|
||||
assert.deepEqual(sinksIn('exec("insertHTML", node.outerHTML);'), []);
|
||||
assert.deepEqual(sinksIn("if (a.outerHTML === b) {}"), []);
|
||||
});
|
||||
|
||||
test("no file in src/ writes markup into a DOM sink", () => {
|
||||
const files = allFiles(SRC);
|
||||
assert.ok(
|
||||
files.some((file) => file.endsWith(path.join("compose", "compose.js"))),
|
||||
"src/ was not scanned",
|
||||
);
|
||||
for (const file of files) {
|
||||
const found = sinksIn(fs.readFileSync(file, "utf8"));
|
||||
assert.deepEqual(found, [], path.relative(SRC, file));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,100 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
/*
|
||||
* Shared helpers for the DOM tests. They create jsdom documents, place the
|
||||
* caret or a selection the way a user would in the compose editor, and read
|
||||
* text back in a form that is easy to compare in assertions.
|
||||
*/
|
||||
|
||||
const { JSDOM } = require("jsdom");
|
||||
|
||||
/**
|
||||
* Creates a new jsdom document whose body contains the given markup.
|
||||
* @param {string} bodyHtml Markup placed inside <body>.
|
||||
* @param {import("jsdom").ConstructorOptions} [options] Options passed to the
|
||||
* JSDOM constructor, e.g. { runScripts: "outside-only" }.
|
||||
* @returns {{ dom: JSDOM, window: Window, doc: Document }} The JSDOM instance,
|
||||
* its window and its document.
|
||||
*/
|
||||
function createDocument(bodyHtml, options = {}) {
|
||||
const dom = new JSDOM(
|
||||
`<!doctype html><html><body>${bodyHtml}</body></html>`,
|
||||
options,
|
||||
);
|
||||
return { dom, window: dom.window, doc: dom.window.document };
|
||||
}
|
||||
|
||||
/**
|
||||
* Places the caret (a collapsed selection) at node/offset and makes it the
|
||||
* only range of the document selection.
|
||||
* @param {Document} doc Document whose selection is changed.
|
||||
* @param {Node} node Container node of the caret.
|
||||
* @param {number} offset Character offset in a text node, or child index in
|
||||
* an element.
|
||||
* @returns {Range} The collapsed range that was added to the selection.
|
||||
*/
|
||||
function setCaret(doc, node, offset) {
|
||||
const range = doc.createRange();
|
||||
range.setStart(node, offset);
|
||||
range.collapse(true);
|
||||
const selection = doc.getSelection();
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
return range;
|
||||
}
|
||||
|
||||
/**
|
||||
* Selects the content from (startNode, startOffset) to (endNode, endOffset)
|
||||
* and makes it the only range of the document selection.
|
||||
* @param {Document} doc Document whose selection is changed.
|
||||
* @param {Node} startNode Container node where the selection starts.
|
||||
* @param {number} startOffset Offset within startNode.
|
||||
* @param {Node} endNode Container node where the selection ends.
|
||||
* @param {number} endOffset Offset within endNode.
|
||||
* @returns {Range} The range that was added to the selection.
|
||||
*/
|
||||
function setSelection(doc, startNode, startOffset, endNode, endOffset) {
|
||||
const range = doc.createRange();
|
||||
range.setStart(startNode, startOffset);
|
||||
range.setEnd(endNode, endOffset);
|
||||
const selection = doc.getSelection();
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
return range;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the first text node below the element, in document order.
|
||||
* @param {Element} element Element to search.
|
||||
* @returns {Text | null} The first descendant text node, or null if there is
|
||||
* none.
|
||||
*/
|
||||
function firstText(element) {
|
||||
const walker = element.ownerDocument.createTreeWalker(element, 4);
|
||||
return walker.nextNode();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the text content of a node with normalized whitespace: no-break
|
||||
* spaces become plain spaces, runs of whitespace collapse to one space, and
|
||||
* leading and trailing whitespace is removed.
|
||||
* @param {Node} node Node to read.
|
||||
* @returns {string} The normalized text.
|
||||
*/
|
||||
function text(node) {
|
||||
return node.textContent
|
||||
.replace(/\u00a0/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
module.exports = { createDocument, setCaret, setSelection, firstText, text };
|
||||
@@ -0,0 +1,519 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
/*
|
||||
* Tests for the translations in src/_locales and the localization helper
|
||||
* src/lib/i18n.js, including the options page rendered in jsdom.
|
||||
*
|
||||
* The static checks compare the messages.json files with each other and
|
||||
* with the keys used in options.html, the scripts and manifest.json. The
|
||||
* options page tests load options.html into jsdom, provide a fake
|
||||
* WebExtension API (i18n, storage, identities) and run the page scripts, so
|
||||
* the rendered texts can be checked for each locale.
|
||||
*/
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const { createDocument, text } = require("./helpers/dom.js");
|
||||
const { localizeDocument } = require("../src/lib/i18n.js");
|
||||
const manifest = require("../src/manifest.json");
|
||||
|
||||
const SRC = path.join(__dirname, "..", "src");
|
||||
const LOCALES_DIR = path.join(SRC, "_locales");
|
||||
const LOCALES = fs.readdirSync(LOCALES_DIR).sort();
|
||||
const MESSAGES = Object.fromEntries(
|
||||
LOCALES.map((locale) => [
|
||||
locale,
|
||||
JSON.parse(
|
||||
fs.readFileSync(path.join(LOCALES_DIR, locale, "messages.json"), "utf8"),
|
||||
),
|
||||
]),
|
||||
);
|
||||
const DEFAULT_MESSAGES = MESSAGES[manifest.default_locale];
|
||||
const KEYS = Object.keys(DEFAULT_MESSAGES).sort();
|
||||
const OPTIONS_PAGE = manifest.options_ui.page;
|
||||
const OPTIONS_HTML = fs.readFileSync(path.join(SRC, OPTIONS_PAGE), "utf8");
|
||||
|
||||
/**
|
||||
* Lists all .js files below dir, recursively.
|
||||
* @param {string} [dir] Absolute directory path. Defaults to SRC.
|
||||
* @returns {string[]} Absolute paths of the .js files found.
|
||||
*/
|
||||
function sourceFiles(dir = SRC) {
|
||||
const files = [];
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
files.push(...sourceFiles(full));
|
||||
} else if (entry.name.endsWith(".js")) {
|
||||
files.push(full);
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the message keys an HTML page uses via data-i18n,
|
||||
* data-i18n-aria-label, data-i18n-title and similar attributes.
|
||||
* @param {string} html Page markup.
|
||||
* @returns {string[]} The keys, in document order (duplicates kept).
|
||||
*/
|
||||
function htmlKeys(html) {
|
||||
return [...html.matchAll(/\sdata-i18n(?:-[a-z-]+)?="([^"]*)"/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the literal keys passed to getMessage("...") or msg("...") in the
|
||||
* scripts below src/.
|
||||
* @returns {{ key: string, file: string }[]} Each key with the file it is
|
||||
* used in, relative to src/.
|
||||
*/
|
||||
function scriptKeys() {
|
||||
const keys = [];
|
||||
for (const file of sourceFiles()) {
|
||||
const source = fs.readFileSync(file, "utf8");
|
||||
for (const match of source.matchAll(
|
||||
/\b(?:getMessage|msg)\(\s*(["'`])([^"'`]+)\1/g,
|
||||
)) {
|
||||
keys.push({ key: match[2], file: path.relative(SRC, file) });
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects the keys referenced as __MSG_key__ in manifest.json.
|
||||
* @returns {string[]} The keys, in the order they appear.
|
||||
*/
|
||||
function manifestKeys() {
|
||||
return [
|
||||
...JSON.stringify(manifest).matchAll(/__MSG_([A-Za-z0-9_@]+)__/g),
|
||||
].map((match) => match[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Minimal stand-in for browser.i18n.getMessage: resolves named placeholders
|
||||
* ($NAME$, case-insensitive) and positional substitutions ($1 ... $9).
|
||||
* @param {object} messages Parsed messages.json of one locale.
|
||||
* @returns {(key: string, substitutions?: unknown) => string} A getMessage
|
||||
* function; it returns "" for unknown keys, like the real API.
|
||||
*/
|
||||
function makeGetMessage(messages) {
|
||||
return (key, substitutions) => {
|
||||
const entry = messages[key];
|
||||
if (!entry) {
|
||||
return "";
|
||||
}
|
||||
const values =
|
||||
substitutions === undefined ? [] : [].concat(substitutions).map(String);
|
||||
const placeholders = entry.placeholders || {};
|
||||
return entry.message
|
||||
.replace(/\$([A-Za-z0-9_@]+)\$/g, (match, name) => {
|
||||
const placeholder = placeholders[name.toLowerCase()];
|
||||
return placeholder ? placeholder.content : match;
|
||||
})
|
||||
.replace(/\$([1-9])/g, (match, index) => values[index - 1] ?? "");
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits one macrotask so pending promises (e.g. storage and identity
|
||||
* requests of the options page) can settle.
|
||||
* @returns {Promise<void>} Resolves on the next turn of the event loop.
|
||||
*/
|
||||
function tick() {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates manually driven timers: callbacks are only recorded and never run
|
||||
* by themselves, so a test can decide which timer fires and when.
|
||||
* @returns {{pending: Map<number, () => void>, setTimeout: (callback: () => void) => number, clearTimeout: (id: number) => void}}
|
||||
* The pending callbacks by timer ID and the two timer functions.
|
||||
*/
|
||||
function createFakeTimers() {
|
||||
let nextId = 1;
|
||||
const pending = new Map();
|
||||
return {
|
||||
pending,
|
||||
/**
|
||||
* Records a callback instead of scheduling it.
|
||||
* @param {() => void} callback Function the page wants to run later.
|
||||
* @returns {number} Timer ID for clearTimeout.
|
||||
*/
|
||||
setTimeout(callback) {
|
||||
const id = nextId++;
|
||||
pending.set(id, callback);
|
||||
return id;
|
||||
},
|
||||
/**
|
||||
* Forgets a recorded callback, like clearTimeout cancels a timer.
|
||||
* @param {number} id Timer ID returned by setTimeout.
|
||||
*/
|
||||
clearTimeout(id) {
|
||||
pending.delete(id);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads the options page in jsdom with a fake WebExtension API and runs its
|
||||
* scripts in the order of the <script> tags.
|
||||
* @param {string} locale Locale to render, e.g. "en" or "de".
|
||||
* @param {object} [options] Fake API data.
|
||||
* @param {object[]} [options.identities] Result of
|
||||
* browser.identities.list(). Defaults to an empty list.
|
||||
* @param {object} [options.stored] Value stored under the "settings" key.
|
||||
* @param {object} [options.timers] Fake timers from createFakeTimers();
|
||||
* when given, they replace the page's setTimeout and clearTimeout.
|
||||
* @returns {Promise<{ window: Window, doc: Document }>} The jsdom window
|
||||
* (close it after the test) and its document.
|
||||
*/
|
||||
async function openOptions(locale, { identities = [], stored, timers } = {}) {
|
||||
const dom = new JSDOM(OPTIONS_HTML, { runScripts: "outside-only" });
|
||||
const { window } = dom;
|
||||
if (timers) {
|
||||
window.setTimeout = timers.setTimeout;
|
||||
window.clearTimeout = timers.clearTimeout;
|
||||
}
|
||||
window.browser = {
|
||||
i18n: {
|
||||
getMessage: makeGetMessage(MESSAGES[locale]),
|
||||
/**
|
||||
* Fake i18n.getUILanguage.
|
||||
* @returns {string} The locale under test.
|
||||
*/
|
||||
getUILanguage: () => locale,
|
||||
},
|
||||
storage: {
|
||||
local: {
|
||||
/**
|
||||
* Fake storage.local.get: ignores the requested keys and always
|
||||
* returns the stored settings.
|
||||
* @returns {Promise<{ settings: object | undefined }>} The value
|
||||
* under the "settings" key.
|
||||
*/
|
||||
get: async () => ({ settings: stored }),
|
||||
/**
|
||||
* Fake storage.local.set: accepts and discards every write.
|
||||
* @returns {Promise<void>} Resolves immediately.
|
||||
*/
|
||||
set: async () => {},
|
||||
},
|
||||
},
|
||||
identities: {
|
||||
/**
|
||||
* Fake identities.list.
|
||||
* @returns {Promise<object[]>} The identities passed to openOptions.
|
||||
*/
|
||||
list: async () => identities,
|
||||
},
|
||||
};
|
||||
const dir = path.dirname(OPTIONS_PAGE);
|
||||
for (const [, src] of OPTIONS_HTML.matchAll(/<script src="([^"]+)"/g)) {
|
||||
window.eval(fs.readFileSync(path.join(SRC, dir, src), "utf8"));
|
||||
}
|
||||
await tick();
|
||||
await tick();
|
||||
return { window, doc: window.document };
|
||||
}
|
||||
|
||||
test("locales en and de exist and have the same keys", () => {
|
||||
assert.ok(LOCALES.includes("en"), "en missing");
|
||||
assert.ok(LOCALES.includes("de"), "de missing");
|
||||
assert.ok(KEYS.length > 0);
|
||||
for (const locale of LOCALES) {
|
||||
assert.deepEqual(Object.keys(MESSAGES[locale]).sort(), KEYS, locale);
|
||||
}
|
||||
});
|
||||
|
||||
test("every message has a text and an English description", () => {
|
||||
for (const locale of LOCALES) {
|
||||
for (const [key, entry] of Object.entries(MESSAGES[locale])) {
|
||||
const where = `${locale}/${key}`;
|
||||
assert.match(key, /^[A-Za-z0-9_@]+$/, where);
|
||||
assert.equal(typeof entry.message, "string", where);
|
||||
assert.notEqual(entry.message.trim(), "", where);
|
||||
assert.equal(typeof entry.description, "string", where);
|
||||
assert.notEqual(entry.description.trim(), "", where);
|
||||
// Descriptions are notes for translators and stay English everywhere.
|
||||
assert.equal(entry.description, DEFAULT_MESSAGES[key].description, where);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("placeholders are defined and the same in every locale", () => {
|
||||
for (const locale of LOCALES) {
|
||||
for (const [key, entry] of Object.entries(MESSAGES[locale])) {
|
||||
const where = `${locale}/${key}`;
|
||||
const defined = Object.keys(entry.placeholders || {}).sort();
|
||||
const expected = Object.keys(
|
||||
DEFAULT_MESSAGES[key].placeholders || {},
|
||||
).sort();
|
||||
assert.deepEqual(defined, expected, where);
|
||||
for (const [, name] of entry.message.matchAll(/\$([A-Za-z0-9_@]+)\$/g)) {
|
||||
assert.ok(defined.includes(name.toLowerCase()), `${where}: $${name}$`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("every data-i18n key in the options page exists", () => {
|
||||
const keys = htmlKeys(OPTIONS_HTML);
|
||||
assert.ok(keys.length > 20, "options page is not marked for translation");
|
||||
for (const key of keys) {
|
||||
assert.ok(KEYS.includes(key), `unknown key in options.html: ${key}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("elements with data-i18n contain only text", () => {
|
||||
const doc = new JSDOM(OPTIONS_HTML).window.document;
|
||||
for (const element of doc.querySelectorAll("[data-i18n]")) {
|
||||
assert.equal(
|
||||
element.children.length,
|
||||
0,
|
||||
`<${element.localName} data-i18n="${element.dataset.i18n}"> has child elements`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("options page loads i18n.js before options.js", () => {
|
||||
const scripts = [...OPTIONS_HTML.matchAll(/<script src="([^"]+)"/g)].map(
|
||||
(match) => match[1],
|
||||
);
|
||||
const i18n = scripts.indexOf("../lib/i18n.js");
|
||||
assert.ok(i18n >= 0, "i18n.js not loaded");
|
||||
assert.ok(i18n < scripts.indexOf("options.js"));
|
||||
});
|
||||
|
||||
test("every getMessage()/msg() key in the scripts exists", () => {
|
||||
const used = scriptKeys();
|
||||
assert.ok(used.length > 0, "no message keys found in src");
|
||||
for (const { key, file } of used) {
|
||||
assert.ok(KEYS.includes(key), `unknown key in ${file}: ${key}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("every __MSG_key__ in manifest.json exists", () => {
|
||||
const keys = manifestKeys();
|
||||
assert.ok(keys.includes("extensionName"));
|
||||
for (const key of keys) {
|
||||
assert.ok(KEYS.includes(key), `unknown key in manifest.json: ${key}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("every message is used somewhere", () => {
|
||||
const used = new Set([
|
||||
...htmlKeys(OPTIONS_HTML),
|
||||
...scriptKeys().map((entry) => entry.key),
|
||||
...manifestKeys(),
|
||||
]);
|
||||
for (const key of KEYS) {
|
||||
assert.ok(used.has(key), `unused message: ${key}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("localizeDocument replaces text and attributes, keeps fallbacks", () => {
|
||||
const { doc } = createDocument(`
|
||||
<h1 id="a" data-i18n="a">Fallback A</h1>
|
||||
<p id="missing" data-i18n="missing">Keep me</p>
|
||||
<div id="b" aria-label="old" data-i18n-aria-label="b"></div>
|
||||
<button id="c" title="old" data-i18n-title="c">Button</button>
|
||||
<span id="d" title="keep" data-i18n-title="missing">D</span>`);
|
||||
const messages = { a: "Text A", b: "Label B", c: "Title C" };
|
||||
const count = localizeDocument(doc, (key) => messages[key] || "");
|
||||
assert.equal(count, 3);
|
||||
assert.equal(doc.getElementById("a").textContent, "Text A");
|
||||
assert.equal(doc.getElementById("missing").textContent, "Keep me");
|
||||
assert.equal(doc.getElementById("b").getAttribute("aria-label"), "Label B");
|
||||
assert.equal(doc.getElementById("c").getAttribute("title"), "Title C");
|
||||
assert.equal(doc.getElementById("c").textContent, "Button");
|
||||
assert.equal(doc.getElementById("d").getAttribute("title"), "keep");
|
||||
});
|
||||
|
||||
test("localizeDocument tolerates missing or odd getMessage results", () => {
|
||||
const { doc } = createDocument(`<p id="p" data-i18n="x">Fallback</p>`);
|
||||
assert.equal(
|
||||
localizeDocument(doc, () => undefined),
|
||||
0,
|
||||
);
|
||||
assert.equal(
|
||||
localizeDocument(doc, () => null),
|
||||
0,
|
||||
);
|
||||
assert.equal(localizeDocument(doc, null), 0);
|
||||
assert.equal(doc.getElementById("p").textContent, "Fallback");
|
||||
});
|
||||
|
||||
for (const locale of ["de", "en"]) {
|
||||
test(`options page is fully translated (${locale})`, async () => {
|
||||
const getMessage = makeGetMessage(MESSAGES[locale]);
|
||||
const { window, doc } = await openOptions(locale);
|
||||
try {
|
||||
assert.equal(doc.documentElement.lang, locale);
|
||||
assert.equal(doc.title, getMessage("optionsTitle"));
|
||||
for (const element of doc.querySelectorAll("[data-i18n]")) {
|
||||
assert.equal(element.textContent, getMessage(element.dataset.i18n));
|
||||
}
|
||||
assert.equal(
|
||||
doc.getElementById("chips").getAttribute("aria-label"),
|
||||
getMessage("placeholderChipsLabel"),
|
||||
);
|
||||
assert.equal(
|
||||
doc.getElementById("profile").options[0].text,
|
||||
getMessage("profileAllIdentities"),
|
||||
);
|
||||
assert.equal(
|
||||
doc.getElementById("profileHint").textContent,
|
||||
getMessage("profileHintGlobal"),
|
||||
);
|
||||
} finally {
|
||||
window.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("options page: German profile list, hint and preview", async () => {
|
||||
const { window, doc } = await openOptions("de", {
|
||||
identities: [
|
||||
{ id: "id1", name: "Anna Beispiel", email: "anna@example.com" },
|
||||
{ id: "id2", name: "", email: "b@example.com" },
|
||||
],
|
||||
stored: { global: {}, identities: { id1: { template: "[A]:" } } },
|
||||
});
|
||||
try {
|
||||
const select = doc.getElementById("profile");
|
||||
assert.deepEqual(
|
||||
[...select.options].map((option) => option.text),
|
||||
[
|
||||
"Alle Identitäten (Standard)",
|
||||
"Anna Beispiel <anna@example.com> – eigene Einstellungen",
|
||||
"b@example.com",
|
||||
],
|
||||
);
|
||||
const preview = text(doc.getElementById("preview"));
|
||||
assert.match(preview, /Können Sie mir die Unterlagen bis Freitag/);
|
||||
assert.match(preview, /\[AB\]: Ja, kommen morgen\./);
|
||||
assert.match(preview, /Und bitte die Rechnung beilegen\./);
|
||||
|
||||
select.value = "id2";
|
||||
select.dispatchEvent(new window.Event("change", { bubbles: true }));
|
||||
assert.equal(
|
||||
doc.getElementById("profileHint").textContent,
|
||||
"Diese Identität nutzt die Einstellungen für alle Identitäten. Haken setzen, um sie anzupassen.",
|
||||
);
|
||||
|
||||
const reset = doc.getElementById("reset");
|
||||
assert.equal(reset.textContent, "Auf Standard zurücksetzen");
|
||||
select.value = "";
|
||||
select.dispatchEvent(new window.Event("change", { bubbles: true }));
|
||||
reset.click();
|
||||
assert.equal(reset.textContent, "Wirklich zurücksetzen?");
|
||||
} finally {
|
||||
window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("options page: English preview without identities", async () => {
|
||||
const { window, doc } = await openOptions("en");
|
||||
try {
|
||||
const preview = text(doc.getElementById("preview"));
|
||||
assert.match(preview, /Could you send me the documents by Friday\?/);
|
||||
assert.match(preview, /\[JD\]: Yes, they will arrive tomorrow\./);
|
||||
assert.match(preview, /And please attach the invoice\./);
|
||||
assert.equal(doc.getElementById("reset").textContent, "Reset to defaults");
|
||||
} finally {
|
||||
window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("options page: an old reset timer does not end a new confirm step", async () => {
|
||||
const timers = createFakeTimers();
|
||||
const { window, doc } = await openOptions("en", {
|
||||
stored: { global: {}, identities: {} },
|
||||
timers,
|
||||
});
|
||||
try {
|
||||
const reset = doc.getElementById("reset");
|
||||
const normalLabel = reset.textContent;
|
||||
const confirmLabel = MESSAGES.en.resetConfirm.message;
|
||||
|
||||
const before = new Set(timers.pending.keys());
|
||||
reset.click(); // arm
|
||||
const armTimers = [...timers.pending.keys()].filter(
|
||||
(id) => !before.has(id),
|
||||
);
|
||||
assert.equal(armTimers.length, 1);
|
||||
assert.equal(reset.textContent, confirmLabel);
|
||||
|
||||
reset.click(); // confirm: reset happens, the arm timer is cancelled
|
||||
assert.equal(reset.textContent, normalLabel);
|
||||
reset.click(); // arm again
|
||||
assert.equal(reset.textContent, confirmLabel);
|
||||
|
||||
// The first timer must not be able to end the new confirm step.
|
||||
for (const id of armTimers) {
|
||||
const callback = timers.pending.get(id);
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
assert.equal(reset.textContent, confirmLabel);
|
||||
} finally {
|
||||
window.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("options page: preview is built from DOM nodes, HTML stays text", async () => {
|
||||
const template = '<img src="x" onerror="alert(1)">{initials}:';
|
||||
const { window, doc } = await openOptions("en", {
|
||||
stored: { global: { template }, identities: {} },
|
||||
});
|
||||
try {
|
||||
const preview = doc.getElementById("preview");
|
||||
assert.deepEqual(
|
||||
[...preview.children].map((element) => element.localName),
|
||||
["blockquote", "div", "blockquote"],
|
||||
);
|
||||
for (const quote of preview.querySelectorAll("blockquote")) {
|
||||
assert.equal(quote.getAttribute("type"), "cite");
|
||||
}
|
||||
const comment = preview.children[1];
|
||||
assert.equal(comment.getAttribute("data-inline-comment"), "preview");
|
||||
assert.equal(preview.querySelector("img"), null);
|
||||
assert.equal(
|
||||
comment.querySelector("[data-inline-comment-marker]").textContent,
|
||||
'<img src="x" onerror="alert(1)">JD:',
|
||||
);
|
||||
assert.equal(
|
||||
text(comment),
|
||||
'<img src="x" onerror="alert(1)">JD: Yes, they will arrive tomorrow.',
|
||||
);
|
||||
|
||||
// Editing the template re-renders the preview instead of appending to it.
|
||||
const input = doc.getElementById("template");
|
||||
input.value = "{name} <b>says</b>:";
|
||||
input.dispatchEvent(new window.Event("input", { bubbles: true }));
|
||||
assert.equal(preview.children.length, 3);
|
||||
assert.equal(preview.querySelector("b"), null);
|
||||
assert.equal(
|
||||
text(preview.children[1]),
|
||||
"Jane Doe <b>says</b>: Yes, they will arrive tomorrow.",
|
||||
);
|
||||
} finally {
|
||||
window.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
/*
|
||||
* Licence checks: the MPL-2.0 text, the header in every source file and
|
||||
* the package metadata.
|
||||
*
|
||||
* The files are read from disk and compared as text: each licensed file
|
||||
* must start with the header in the comment style of its type (block
|
||||
* comment, HTML/SVG comment or shell comment).
|
||||
*/
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const pkg = require("../package.json");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const COPYRIGHT = "Copyright 2026 Oliver Herb";
|
||||
const SPDX = "SPDX-License-Identifier: MPL-2.0";
|
||||
const HEADER_LINES = Object.freeze([
|
||||
COPYRIGHT,
|
||||
SPDX,
|
||||
"",
|
||||
"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/.",
|
||||
]);
|
||||
|
||||
/** The header as it must appear, by comment style. */
|
||||
const HEADERS = Object.freeze({
|
||||
block: [
|
||||
"/*",
|
||||
...HEADER_LINES.map((line) => (line ? ` * ${line}` : " *")),
|
||||
" */",
|
||||
].join("\n"),
|
||||
markup: [
|
||||
"<!--",
|
||||
...HEADER_LINES.map((line) => (line ? ` ${line}` : "")),
|
||||
"-->",
|
||||
].join("\n"),
|
||||
shell: HEADER_LINES.map((line) => (line ? `# ${line}` : "#")).join("\n"),
|
||||
});
|
||||
|
||||
/**
|
||||
* Lists the files below dir whose names match the pattern.
|
||||
* @param {string} dir Directory relative to ROOT.
|
||||
* @param {RegExp} pattern Tested against the file name (not the path).
|
||||
* @param {boolean} [recursive] Whether to descend into subdirectories.
|
||||
* Defaults to true.
|
||||
* @returns {string[]} Matching file paths, relative to ROOT.
|
||||
*/
|
||||
function filesIn(dir, pattern, recursive = true) {
|
||||
const files = [];
|
||||
for (const entry of fs.readdirSync(path.join(ROOT, dir), {
|
||||
withFileTypes: true,
|
||||
})) {
|
||||
const relative = path.join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
if (recursive) {
|
||||
files.push(...filesIn(relative, pattern, recursive));
|
||||
}
|
||||
} else if (pattern.test(entry.name)) {
|
||||
files.push(relative);
|
||||
}
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
const LICENSED_FILES = [
|
||||
...filesIn("src", /\.(?:js|css|html|svg)$/),
|
||||
...filesIn("test", /\.js$/),
|
||||
...filesIn("scripts", /\.sh$/, false),
|
||||
"eslint.config.mjs",
|
||||
];
|
||||
|
||||
/**
|
||||
* Returns the text a licensed file must start with, depending on its type:
|
||||
* the header itself, preceded by the doctype (HTML) or the shebang (shell).
|
||||
* @param {string} file File path; only the extension is used.
|
||||
* @returns {string} The expected beginning of the file, without the
|
||||
* trailing newline.
|
||||
* @throws {Error} If there is no header rule for the file type.
|
||||
*/
|
||||
function expectedStart(file) {
|
||||
switch (path.extname(file)) {
|
||||
case ".js":
|
||||
case ".mjs":
|
||||
case ".css":
|
||||
return HEADERS.block;
|
||||
case ".html":
|
||||
return `<!doctype html>\n${HEADERS.markup}`;
|
||||
case ".svg":
|
||||
return HEADERS.markup;
|
||||
case ".sh":
|
||||
return `#!/usr/bin/env bash\n${HEADERS.shell}`;
|
||||
default:
|
||||
throw new Error(`no header rule for ${file}`);
|
||||
}
|
||||
}
|
||||
|
||||
test("LICENSE holds the Mozilla Public License 2.0", () => {
|
||||
const license = fs.readFileSync(path.join(ROOT, "LICENSE"), "utf8");
|
||||
assert.ok(license.startsWith("Mozilla Public License Version 2.0"));
|
||||
assert.match(license, /Exhibit B - "Incompatible With Secondary Licenses"/);
|
||||
});
|
||||
|
||||
test("every source, test and script file has the licence header", () => {
|
||||
assert.ok(LICENSED_FILES.includes(path.join("src", "lib", "marker.js")));
|
||||
assert.ok(
|
||||
LICENSED_FILES.includes(path.join("src", "options", "options.html")),
|
||||
);
|
||||
assert.ok(LICENSED_FILES.includes(path.join("src", "icons", "icon.svg")));
|
||||
assert.ok(LICENSED_FILES.includes(path.join("test", "helpers", "dom.js")));
|
||||
assert.ok(LICENSED_FILES.includes(path.join("scripts", "build.sh")));
|
||||
assert.ok(LICENSED_FILES.includes("eslint.config.mjs"));
|
||||
for (const file of LICENSED_FILES) {
|
||||
const source = fs
|
||||
.readFileSync(path.join(ROOT, file), "utf8")
|
||||
.replace(/\r\n/g, "\n");
|
||||
assert.ok(source.includes(SPDX), `${file}: ${SPDX} missing`);
|
||||
assert.ok(source.includes(COPYRIGHT), `${file}: ${COPYRIGHT} missing`);
|
||||
assert.ok(
|
||||
source.startsWith(`${expectedStart(file)}\n`),
|
||||
`${file}: header missing or not at the top`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("package.json declares MPL-2.0 and the public repository", () => {
|
||||
assert.equal(pkg.name, "inline-comment");
|
||||
assert.equal(pkg.license, "MPL-2.0");
|
||||
assert.equal(pkg.author, "Oliver Herb");
|
||||
assert.deepEqual(pkg.repository, {
|
||||
type: "git",
|
||||
url: "https://git.hassio-muc.de/Oliver_Herb/inline-comment.git",
|
||||
});
|
||||
assert.equal(
|
||||
pkg.homepage,
|
||||
"https://git.hassio-muc.de/Oliver_Herb/inline-comment",
|
||||
);
|
||||
assert.equal(
|
||||
pkg.bugs,
|
||||
"https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues",
|
||||
);
|
||||
});
|
||||
|
||||
test("the build puts LICENSE into the XPI root", () => {
|
||||
const script = fs.readFileSync(
|
||||
path.join(ROOT, "scripts", "build.sh"),
|
||||
"utf8",
|
||||
);
|
||||
assert.match(script, /^OUT="dist\/inline-comment-\$\{VERSION\}\.xpi"$/m);
|
||||
assert.match(script, /^zip -X -q -j "\$OUT" LICENSE$/m);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
/*
|
||||
* Static checks of src/manifest.json: manifest version, add-on ID and
|
||||
* minimum application version, localized fields, permissions, the version
|
||||
* number shared with package.json and CHANGELOG.md, and that every file the
|
||||
* manifest or the options page refers to exists. The JSON and HTML files are
|
||||
* read from disk; no browser or DOM is involved.
|
||||
*/
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const manifest = require("../src/manifest.json");
|
||||
const pkg = require("../package.json");
|
||||
const { COMPOSE_SCRIPT_FILES } = require("../src/lib/settings.js");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const SRC = path.join(ROOT, "src");
|
||||
|
||||
/**
|
||||
* Tells whether a file exists in the add-on source.
|
||||
* @param {string} relative Path relative to src/.
|
||||
* @returns {boolean} True if the file exists.
|
||||
*/
|
||||
function exists(relative) {
|
||||
return fs.existsSync(path.join(SRC, relative));
|
||||
}
|
||||
|
||||
test("Manifest V3 with a fixed add-on ID and minimum version 128", () => {
|
||||
assert.equal(manifest.manifest_version, 3);
|
||||
assert.equal(
|
||||
manifest.browser_specific_settings.gecko.id,
|
||||
"inline-comment@ih-engineering.de",
|
||||
);
|
||||
assert.equal(
|
||||
manifest.browser_specific_settings.gecko.strict_min_version,
|
||||
"128.0",
|
||||
);
|
||||
});
|
||||
|
||||
test("default locale is en and translations exist for en and de", () => {
|
||||
assert.equal(manifest.default_locale, "en");
|
||||
for (const locale of [manifest.default_locale, "de"]) {
|
||||
const file = `_locales/${locale}/messages.json`;
|
||||
assert.ok(exists(file), `missing: src/${file}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("name, description and button title come from _locales", () => {
|
||||
assert.equal(manifest.name, "__MSG_extensionName__");
|
||||
assert.equal(manifest.description, "__MSG_extensionDescription__");
|
||||
assert.equal(manifest.compose_action.default_title, "__MSG_actionTitle__");
|
||||
});
|
||||
|
||||
test("version is the same in manifest.json, package.json and CHANGELOG.md", () => {
|
||||
assert.equal(manifest.version, pkg.version);
|
||||
const changelog = fs.readFileSync(path.join(ROOT, "CHANGELOG.md"), "utf8");
|
||||
assert.match(
|
||||
changelog,
|
||||
new RegExp(`^## \\[${pkg.version.replace(/\./g, "\\.")}\\]`, "m"),
|
||||
);
|
||||
});
|
||||
|
||||
test("the required permissions are declared", () => {
|
||||
for (const permission of [
|
||||
"compose",
|
||||
"scripting",
|
||||
"storage",
|
||||
"accountsRead",
|
||||
]) {
|
||||
assert.ok(manifest.permissions.includes(permission), permission);
|
||||
}
|
||||
});
|
||||
|
||||
test("all referenced files exist", () => {
|
||||
const files = [
|
||||
...manifest.background.scripts,
|
||||
...COMPOSE_SCRIPT_FILES,
|
||||
manifest.options_ui.page,
|
||||
manifest.compose_action.default_icon,
|
||||
...Object.values(manifest.icons),
|
||||
];
|
||||
for (const file of files) {
|
||||
assert.ok(exists(file), `missing: src/${file}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the options page loads only existing scripts", () => {
|
||||
const html = fs.readFileSync(
|
||||
path.join(SRC, manifest.options_ui.page),
|
||||
"utf8",
|
||||
);
|
||||
const dir = path.dirname(manifest.options_ui.page);
|
||||
for (const [, src] of html.matchAll(/<script src="([^"]+)"/g)) {
|
||||
assert.ok(exists(path.join(dir, src)), `missing: ${src}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
/*
|
||||
* Unit tests for src/lib/marker.js: initials from names and addresses,
|
||||
* template placeholders, the marker variables, and the comment node that is
|
||||
* inserted into the mail (structure, inline styles, escaping). The pure
|
||||
* string functions are called directly; the DOM functions run against a
|
||||
* jsdom document.
|
||||
*/
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { JSDOM } = require("jsdom");
|
||||
const marker = require("../src/lib/marker.js");
|
||||
const { sanitizeSettings } = require("../src/lib/settings.js");
|
||||
const { createDocument } = require("./helpers/dom.js");
|
||||
|
||||
test("initials from the display name", () => {
|
||||
assert.equal(marker.initialsOf("Max Mustermann", ""), "MM");
|
||||
assert.equal(marker.initialsOf("Jürgen Beispiel", ""), "JB");
|
||||
assert.equal(marker.initialsOf("Hans-Peter Müller", ""), "HPM");
|
||||
assert.equal(marker.initialsOf("Dr. Max Mustermann", ""), "MM");
|
||||
assert.equal(marker.initialsOf("Dipl.-Ing. Anna Berg", ""), "AB");
|
||||
assert.equal(marker.initialsOf("Oliver Herb (ACME)", ""), "OH");
|
||||
assert.equal(marker.initialsOf("ölaf über", ""), "ÖÜ");
|
||||
});
|
||||
|
||||
test("initials for 'Last name, First name' and a company suffix", () => {
|
||||
assert.equal(marker.initialsOf("Herb, Oliver", ""), "OH");
|
||||
assert.equal(marker.initialsOf("Oliver Herb, Example Corp", ""), "OH");
|
||||
});
|
||||
|
||||
test("initials from the address when there is no name", () => {
|
||||
assert.equal(marker.initialsOf("", "jane.doe@example.com"), "JD");
|
||||
assert.equal(marker.initialsOf("", "info@example.com"), "I");
|
||||
assert.equal(marker.initialsOf("", ""), "?");
|
||||
assert.equal(marker.initialsOf(undefined, undefined), "?");
|
||||
});
|
||||
|
||||
test("at most four initials", () => {
|
||||
assert.equal(marker.initialsOf("A B C D E F", ""), "ABCD");
|
||||
});
|
||||
|
||||
test("placeholders are replaced, unknown ones are kept", () => {
|
||||
const vars = {
|
||||
name: "Max",
|
||||
initials: "MM",
|
||||
email: "m@example.com",
|
||||
date: "24.11.2026",
|
||||
time: "09:30",
|
||||
};
|
||||
assert.equal(marker.renderTemplate("[{initials}]:", vars), "[MM]:");
|
||||
assert.equal(
|
||||
marker.renderTemplate(
|
||||
"{name} <{email}> {date} {time} {initials}{initials}",
|
||||
vars,
|
||||
),
|
||||
"Max <m@example.com> 24.11.2026 09:30 MMMM",
|
||||
);
|
||||
assert.equal(marker.renderTemplate("{foo} {name}", vars), "{foo} Max");
|
||||
assert.equal(marker.renderTemplate("{name}", {}), "{name}");
|
||||
});
|
||||
|
||||
test("markerVariables: name falls back to the address, date in the requested locale format", () => {
|
||||
const now = new Date(2026, 10, 24, 9, 5);
|
||||
const vars = marker.markerVariables(
|
||||
{ name: "", email: "max@example.com" },
|
||||
now,
|
||||
"de-DE",
|
||||
);
|
||||
assert.equal(vars.name, "max@example.com");
|
||||
assert.equal(vars.initials, "M");
|
||||
assert.equal(vars.date, "24.11.2026");
|
||||
assert.equal(vars.time, "09:05");
|
||||
const none = marker.markerVariables(null, now, "de-DE");
|
||||
assert.equal(none.initials, "?");
|
||||
});
|
||||
|
||||
test("createCommentNode: structure, inline CSS only, id", () => {
|
||||
const { doc } = createDocument("");
|
||||
const settings = sanitizeSettings({});
|
||||
const node = marker.createCommentNode(doc, "[MM]:", "a", settings, "ic-1");
|
||||
assert.equal(node.ownerDocument, doc);
|
||||
assert.equal(node.isConnected, false);
|
||||
assert.equal(node.localName, "div");
|
||||
assert.deepEqual(
|
||||
[...node.attributes].map((attribute) => attribute.name),
|
||||
["data-inline-comment", "style"],
|
||||
);
|
||||
assert.equal(node.getAttribute("data-inline-comment"), "ic-1");
|
||||
assert.equal(node.getAttribute("style"), marker.commentStyle(settings));
|
||||
assert.match(node.getAttribute("style"), /^color:#0056b3;/);
|
||||
assert.equal(node.childNodes.length, 2);
|
||||
|
||||
const [span, textNode] = node.childNodes;
|
||||
assert.equal(span.localName, "span");
|
||||
assert.deepEqual(
|
||||
[...span.attributes].map((attribute) => attribute.name),
|
||||
["data-inline-comment-marker", "style"],
|
||||
);
|
||||
assert.equal(span.getAttribute("data-inline-comment-marker"), "");
|
||||
assert.equal(
|
||||
span.getAttribute("style"),
|
||||
"color:#003d80;font-weight:bold;font-style:normal;",
|
||||
);
|
||||
assert.equal(span.textContent, "[MM]:");
|
||||
assert.equal(textNode.nodeType, doc.TEXT_NODE);
|
||||
assert.equal(textNode.data, "\u00a0a");
|
||||
});
|
||||
|
||||
test("createCommentNode: outerHTML has the inline-CSS comment markup", () => {
|
||||
const { doc } = createDocument("");
|
||||
const settings = sanitizeSettings({});
|
||||
const html = marker.createCommentNode(
|
||||
doc,
|
||||
"[MM]:",
|
||||
"a b",
|
||||
settings,
|
||||
"ic-1",
|
||||
).outerHTML;
|
||||
assert.equal(
|
||||
html,
|
||||
`<div data-inline-comment="ic-1" style="${marker.commentStyle(settings)}">` +
|
||||
`<span data-inline-comment-marker="" style="${marker.markerStyle(settings)}">[MM]:</span>` +
|
||||
" a b</div>",
|
||||
);
|
||||
assert.doesNotMatch(html, /class=|<style/);
|
||||
});
|
||||
|
||||
test("createCommentNode: marker, text and id never become markup", () => {
|
||||
const { doc } = createDocument("");
|
||||
const settings = sanitizeSettings({});
|
||||
const markerText = '[<img src=x onerror="alert(1)">]:';
|
||||
const id = 'x" onmouseover="alert(1)';
|
||||
const node = marker.createCommentNode(
|
||||
doc,
|
||||
markerText,
|
||||
"<b>&</b>",
|
||||
settings,
|
||||
id,
|
||||
);
|
||||
assert.equal(node.querySelector("img, b"), null);
|
||||
assert.equal(node.hasAttribute("onmouseover"), false);
|
||||
assert.equal(node.getAttribute("data-inline-comment"), id);
|
||||
assert.equal(node.firstChild.textContent, markerText);
|
||||
assert.equal(node.lastChild.data, "\u00a0<b>&</b>");
|
||||
|
||||
// The serialized form (used for execCommand "insertHTML") parses back to
|
||||
// the very same node: no element or attribute can be smuggled in.
|
||||
const parsed = JSDOM.fragment(node.outerHTML).firstChild;
|
||||
assert.ok(parsed.isEqualNode(node));
|
||||
assert.equal(parsed.querySelector("img, b"), null);
|
||||
assert.equal(parsed.hasAttribute("onmouseover"), false);
|
||||
});
|
||||
|
||||
test("createCommentNode: highlight, italic and blank lines", () => {
|
||||
const { doc } = createDocument("");
|
||||
const settings = sanitizeSettings({
|
||||
highlight: true,
|
||||
highlightColor: "#ffeeaa",
|
||||
textItalic: true,
|
||||
blankLineBefore: true,
|
||||
blankLineAfter: true,
|
||||
markerBold: false,
|
||||
});
|
||||
const node = marker.createCommentNode(doc, "[MM]:", " ", settings, "x");
|
||||
const style = node.getAttribute("style");
|
||||
assert.match(style, /background-color:#ffeeaa;padding:2px 4px;/);
|
||||
assert.match(style, /font-style:italic;/);
|
||||
assert.match(style, /margin:1em 0 1em 0;/);
|
||||
assert.equal(
|
||||
node.firstChild.getAttribute("style"),
|
||||
"color:#003d80;font-weight:normal;font-style:normal;",
|
||||
);
|
||||
assert.equal(node.lastChild.data, "\u00a0\u00a0");
|
||||
assert.match(node.outerHTML, / <\/div>$/);
|
||||
});
|
||||
|
||||
test("createCommentNode accepts non-string values", () => {
|
||||
const { doc } = createDocument("");
|
||||
const node = marker.createCommentNode(doc, 42, 7, sanitizeSettings({}), 1);
|
||||
assert.equal(node.getAttribute("data-inline-comment"), "1");
|
||||
assert.equal(node.firstChild.textContent, "42");
|
||||
assert.equal(node.lastChild.data, "\u00a07");
|
||||
});
|
||||
|
||||
test("every documented variable is replaced by renderTemplate", () => {
|
||||
for (const variable of marker.VARIABLES) {
|
||||
assert.equal(
|
||||
marker.renderTemplate(`[{${variable}}]`, { [variable]: "X" }),
|
||||
"[X]",
|
||||
variable,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("buildCommentText for plain text", () => {
|
||||
const plain = sanitizeSettings({});
|
||||
assert.equal(marker.buildCommentText("[MM]:", "a", plain), "[MM]: a");
|
||||
const spaced = sanitizeSettings({ blankLineBefore: true });
|
||||
assert.equal(marker.buildCommentText("[MM]:", "a", spaced), "\n[MM]: a");
|
||||
});
|
||||
@@ -0,0 +1,366 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
/*
|
||||
* Unit tests for the DOM helpers in src/lib/quote.js: detecting mail quotes
|
||||
* (HTML blockquote and plain-text _moz_quote span), finding the quote or
|
||||
* comment around the caret, recognizing the gap left by Enter inside a
|
||||
* quote, filtering printable keys, and splitting a quote at the caret. Each
|
||||
* test builds a small reply in a jsdom document and places the caret or a
|
||||
* selection with the helpers from ./helpers/dom.js.
|
||||
*/
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const quote = require("../src/lib/quote.js");
|
||||
const marker = require("../src/lib/marker.js");
|
||||
const { sanitizeSettings } = require("../src/lib/settings.js");
|
||||
const {
|
||||
createDocument,
|
||||
setCaret,
|
||||
setSelection,
|
||||
firstText,
|
||||
text,
|
||||
} = require("./helpers/dom.js");
|
||||
|
||||
// Sample HTML reply: own text on top, the attribution line, a quote with a
|
||||
// nested quote inside, and an empty paragraph below. 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>
|
||||
<blockquote type="cite" id="inner"><p id="q2">Alt eins. Alt zwei.</p></blockquote>
|
||||
<p id="q3">Schluss.</p>
|
||||
</blockquote>
|
||||
<p id="after"><br></p>`;
|
||||
|
||||
test("isMailCite detects HTML and plain-text quotes", () => {
|
||||
const { doc } = createDocument(
|
||||
`<blockquote type="cite" id="a"></blockquote><blockquote id="b"></blockquote>` +
|
||||
`<blockquote type="CITE" id="c"></blockquote><span _moz_quote="true" id="d"></span>`,
|
||||
);
|
||||
assert.equal(quote.isMailCite(doc.getElementById("a")), true);
|
||||
assert.equal(quote.isMailCite(doc.getElementById("b")), false);
|
||||
assert.equal(quote.isMailCite(doc.getElementById("c")), true);
|
||||
assert.equal(quote.isMailCite(doc.getElementById("d")), true);
|
||||
assert.equal(quote.isMailCite(null), false);
|
||||
});
|
||||
|
||||
test("caretContext finds the outermost quote", () => {
|
||||
const { doc } = createDocument(REPLY);
|
||||
setCaret(doc, firstText(doc.getElementById("q2")), 3);
|
||||
const ctx = quote.caretContext(doc);
|
||||
assert.equal(ctx.cite.id, "outer");
|
||||
assert.equal(ctx.collapsed, true);
|
||||
assert.equal(ctx.comment, null);
|
||||
});
|
||||
|
||||
test("caretContext outside quotes and inside the user's own comment", () => {
|
||||
const { doc } = createDocument(
|
||||
`<p id="own">Text</p><div data-inline-comment="x" id="c"><span>[MM]:</span> Hallo</div>`,
|
||||
);
|
||||
setCaret(doc, firstText(doc.getElementById("own")), 2);
|
||||
assert.equal(quote.caretContext(doc).cite, null);
|
||||
setCaret(doc, doc.getElementById("c").lastChild, 2);
|
||||
const ctx = quote.caretContext(doc);
|
||||
assert.equal(ctx.cite, null);
|
||||
assert.equal(ctx.comment.id, "c");
|
||||
});
|
||||
|
||||
test("someone else's comment inside a quote counts as part of the quote", () => {
|
||||
const { doc } = createDocument(
|
||||
`<blockquote type="cite" id="q"><div data-inline-comment="alt" id="c">[AB]: alt</div></blockquote>`,
|
||||
);
|
||||
setCaret(doc, firstText(doc.getElementById("c")), 2);
|
||||
const ctx = quote.caretContext(doc);
|
||||
assert.equal(ctx.cite.id, "q");
|
||||
assert.equal(ctx.comment, null);
|
||||
});
|
||||
|
||||
test("caretContext without a selection", () => {
|
||||
const { doc } = createDocument("<p>x</p>");
|
||||
doc.getSelection().removeAllRanges();
|
||||
assert.equal(quote.caretContext(doc), null);
|
||||
});
|
||||
|
||||
test("isGapPosition: empty line between two parts of a quote", () => {
|
||||
const { doc } = createDocument(
|
||||
`<blockquote type="cite">A</blockquote><br id="gap"><blockquote type="cite">B</blockquote>`,
|
||||
);
|
||||
const body = doc.body;
|
||||
const index = Array.prototype.indexOf.call(
|
||||
body.childNodes,
|
||||
doc.getElementById("gap"),
|
||||
);
|
||||
const range = setCaret(doc, body, index);
|
||||
assert.equal(quote.isGapPosition(doc, range), true);
|
||||
});
|
||||
|
||||
test("isGapPosition: empty paragraph between quotes, caret inside the paragraph", () => {
|
||||
const { doc } = createDocument(
|
||||
`<blockquote type="cite">A</blockquote>\n<p id="gap"><br></p>\n<blockquote type="cite">B</blockquote>`,
|
||||
);
|
||||
const range = setCaret(doc, doc.getElementById("gap"), 0);
|
||||
assert.equal(quote.isGapPosition(doc, range), true);
|
||||
});
|
||||
|
||||
test("isGapPosition: not for a reply above or below the quote", () => {
|
||||
const { doc } = createDocument(
|
||||
`<p id="top"><br></p><div class="moz-cite-prefix">Am … schrieb:</div>` +
|
||||
`<blockquote type="cite">A</blockquote><p id="bottom"><br></p>`,
|
||||
);
|
||||
assert.equal(
|
||||
quote.isGapPosition(doc, setCaret(doc, doc.getElementById("top"), 0)),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
quote.isGapPosition(doc, setCaret(doc, doc.getElementById("bottom"), 0)),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("isGapPosition: not in a line that contains text", () => {
|
||||
const { doc } = createDocument(
|
||||
`<blockquote type="cite">A</blockquote><p id="t">Text</p><blockquote type="cite">B</blockquote>`,
|
||||
);
|
||||
const range = setCaret(doc, firstText(doc.getElementById("t")), 2);
|
||||
assert.equal(quote.isGapPosition(doc, range), false);
|
||||
});
|
||||
|
||||
test("isPrintableKey: characters yes, shortcuts no, AltGr yes", () => {
|
||||
/**
|
||||
* Builds a minimal keyboard event stand-in. The AltGr state is reported
|
||||
* through getModifierState("AltGraph"), as in a real KeyboardEvent.
|
||||
* @param {object} init Event properties such as key, ctrlKey or
|
||||
* isComposing, plus altGraph for the AltGr modifier state.
|
||||
* @returns {object} The fake event passed to isPrintableKey.
|
||||
*/
|
||||
const key = (init) => ({
|
||||
/**
|
||||
* Fake KeyboardEvent.getModifierState.
|
||||
* @param {string} name Modifier name, e.g. "AltGraph".
|
||||
* @returns {boolean | undefined} Truthy only for "AltGraph" when
|
||||
* init.altGraph is set.
|
||||
*/
|
||||
getModifierState: (name) => name === "AltGraph" && init.altGraph,
|
||||
...init,
|
||||
});
|
||||
assert.equal(quote.isPrintableKey(key({ key: "a" })), true);
|
||||
assert.equal(quote.isPrintableKey(key({ key: " " })), true);
|
||||
assert.equal(quote.isPrintableKey(key({ key: "ü", shiftKey: true })), true);
|
||||
assert.equal(quote.isPrintableKey(key({ key: "😀" })), true);
|
||||
assert.equal(quote.isPrintableKey(key({ key: "c", ctrlKey: true })), false);
|
||||
assert.equal(quote.isPrintableKey(key({ key: "v", metaKey: true })), false);
|
||||
assert.equal(quote.isPrintableKey(key({ key: "x", altKey: true })), false);
|
||||
assert.equal(
|
||||
quote.isPrintableKey(
|
||||
key({ key: "@", ctrlKey: true, altKey: true, altGraph: true }),
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(quote.isPrintableKey(key({ key: "Enter" })), false);
|
||||
assert.equal(quote.isPrintableKey(key({ key: "Dead" })), false);
|
||||
assert.equal(
|
||||
quote.isPrintableKey(key({ key: "a", isComposing: true })),
|
||||
false,
|
||||
);
|
||||
assert.equal(quote.isPrintableKey(null), false);
|
||||
});
|
||||
|
||||
test("splitCiteAtRange splits in the middle of the text", () => {
|
||||
const { doc } = createDocument(REPLY);
|
||||
const range = setCaret(
|
||||
doc,
|
||||
firstText(doc.getElementById("q1")),
|
||||
"Erster Satz.".length,
|
||||
);
|
||||
const outer = doc.getElementById("outer");
|
||||
const marker = doc.createElement("div");
|
||||
marker.id = "comment";
|
||||
const { before, after } = quote.splitCiteAtRange(doc, range, outer, marker);
|
||||
assert.equal(before, outer);
|
||||
assert.equal(text(before), "Erster Satz.");
|
||||
assert.equal(marker.previousElementSibling, before);
|
||||
assert.equal(marker.nextElementSibling, after);
|
||||
assert.equal(after.getAttribute("type"), "cite");
|
||||
assert.match(text(after), /^Zweiter Satz\. Alt eins\. Alt zwei\. Schluss\.$/);
|
||||
});
|
||||
|
||||
test("splitCiteAtRange also splits the nested quote", () => {
|
||||
const { doc } = createDocument(REPLY);
|
||||
const range = setCaret(
|
||||
doc,
|
||||
firstText(doc.getElementById("q2")),
|
||||
"Alt eins.".length,
|
||||
);
|
||||
const outer = doc.getElementById("outer");
|
||||
const marker = doc.createElement("div");
|
||||
const { before, after } = quote.splitCiteAtRange(doc, range, outer, marker);
|
||||
assert.equal(text(before), "Erster Satz. Zweiter Satz. Alt eins.");
|
||||
assert.equal(text(after), "Alt zwei. Schluss.");
|
||||
// The split-off half keeps the nesting: outer quote > inner quote.
|
||||
const nested = after.querySelector('blockquote[type="cite"]');
|
||||
assert.ok(nested);
|
||||
assert.equal(text(nested), "Alt zwei.");
|
||||
assert.equal(before.querySelectorAll('blockquote[type="cite"]').length, 1);
|
||||
});
|
||||
|
||||
test("splitCiteAtRange at the start and at the end leaves no empty quotes", () => {
|
||||
const start = createDocument(
|
||||
`<blockquote type="cite" id="q"><p id="p">Nur Text</p></blockquote>`,
|
||||
);
|
||||
const rangeStart = setCaret(
|
||||
start.doc,
|
||||
firstText(start.doc.getElementById("p")),
|
||||
0,
|
||||
);
|
||||
const nodeStart = start.doc.createElement("div");
|
||||
const resultStart = quote.splitCiteAtRange(
|
||||
start.doc,
|
||||
rangeStart,
|
||||
start.doc.getElementById("q"),
|
||||
nodeStart,
|
||||
);
|
||||
assert.equal(resultStart.before, null);
|
||||
assert.equal(text(resultStart.after), "Nur Text");
|
||||
assert.equal(start.doc.body.firstElementChild, nodeStart);
|
||||
|
||||
const end = createDocument(
|
||||
`<blockquote type="cite" id="q"><p id="p">Nur Text</p></blockquote>`,
|
||||
);
|
||||
const rangeEnd = setCaret(
|
||||
end.doc,
|
||||
firstText(end.doc.getElementById("p")),
|
||||
"Nur Text".length,
|
||||
);
|
||||
const nodeEnd = end.doc.createElement("div");
|
||||
const resultEnd = quote.splitCiteAtRange(
|
||||
end.doc,
|
||||
rangeEnd,
|
||||
end.doc.getElementById("q"),
|
||||
nodeEnd,
|
||||
);
|
||||
assert.equal(resultEnd.after, null);
|
||||
assert.equal(end.doc.body.lastElementChild, nodeEnd);
|
||||
});
|
||||
|
||||
test("splitCiteAtRange adds '> ' in a plain-text quote", () => {
|
||||
const { doc } = createDocument(
|
||||
`<span _moz_quote="true" id="q">> Erste Zeile und mehr<br>> Zweite</span>`,
|
||||
);
|
||||
const quoteSpan = doc.getElementById("q");
|
||||
const range = setCaret(doc, quoteSpan.firstChild, "> Erste Zeile".length);
|
||||
const node = quote.createPlainCommentElement(doc, "[MM]: a", "id1");
|
||||
const { after } = quote.splitCiteAtRange(doc, range, quoteSpan, node);
|
||||
assert.equal(after.firstChild.data, "> und mehr");
|
||||
assert.equal(after.getAttribute("_moz_quote"), "true");
|
||||
assert.equal(node.getAttribute("data-inline-comment"), "id1");
|
||||
assert.equal(text(node), "[MM]: a");
|
||||
});
|
||||
|
||||
test("hasContent: a plain-text quote with only '>' counts as empty", () => {
|
||||
const { doc } = createDocument(
|
||||
`<span _moz_quote="true" id="a">> <br>></span><blockquote type="cite" id="b"><img src="x.png"></blockquote>`,
|
||||
);
|
||||
assert.equal(quote.hasContent(doc.getElementById("a")), false);
|
||||
assert.equal(quote.hasContent(doc.getElementById("b")), true);
|
||||
});
|
||||
|
||||
test("placeCaretAtEnd puts the caret after the comment text", () => {
|
||||
const { doc } = createDocument("<p>x</p>");
|
||||
const element = marker.createCommentNode(
|
||||
doc,
|
||||
"[MM]:",
|
||||
"a",
|
||||
sanitizeSettings({}),
|
||||
"k",
|
||||
);
|
||||
doc.body.append(element);
|
||||
quote.placeCaretAtEnd(doc, element);
|
||||
const selection = doc.getSelection();
|
||||
assert.equal(selection.anchorNode, element.lastChild);
|
||||
assert.equal(selection.anchorOffset, element.lastChild.data.length);
|
||||
assert.equal(quote.caretContext(doc).comment, element);
|
||||
});
|
||||
|
||||
test("placeCaretAtEnd in an element without text", () => {
|
||||
const { doc } = createDocument("<p>x</p>");
|
||||
const element = doc.createElement("div");
|
||||
element.append(doc.createElement("br"));
|
||||
doc.body.append(element);
|
||||
quote.placeCaretAtEnd(doc, element);
|
||||
const selection = doc.getSelection();
|
||||
assert.equal(selection.anchorNode, element);
|
||||
assert.equal(selection.anchorOffset, 1);
|
||||
});
|
||||
|
||||
test("splitCiteAtRange with a comment node from createCommentNode", () => {
|
||||
const { doc } = createDocument(REPLY);
|
||||
const range = setCaret(
|
||||
doc,
|
||||
firstText(doc.getElementById("q1")),
|
||||
"Erster Satz.".length,
|
||||
);
|
||||
const node = marker.createCommentNode(
|
||||
doc,
|
||||
"[MM]:",
|
||||
"a",
|
||||
sanitizeSettings({}),
|
||||
"c1",
|
||||
);
|
||||
const { before, after } = quote.splitCiteAtRange(
|
||||
doc,
|
||||
range,
|
||||
doc.getElementById("outer"),
|
||||
node,
|
||||
);
|
||||
assert.equal(node.previousElementSibling, before);
|
||||
assert.equal(node.nextElementSibling, after);
|
||||
assert.equal(quote.isComment(node), true);
|
||||
assert.equal(text(node), "[MM]: a");
|
||||
});
|
||||
|
||||
test("the DOM helpers no longer export createCommentElement", () => {
|
||||
assert.equal("createCommentElement" in quote, false);
|
||||
assert.equal("buildCommentHtml" in marker, false);
|
||||
});
|
||||
|
||||
test("isBlankNode: images and rules are content, also at top level", () => {
|
||||
const { doc } = createDocument(
|
||||
`<hr id="hr"><img id="img" src="x.png"><p id="p"><img src="y.png"></p><p id="e"> </p>`,
|
||||
);
|
||||
assert.equal(quote.isBlankNode(doc.getElementById("hr")), false);
|
||||
assert.equal(quote.isBlankNode(doc.getElementById("img")), false);
|
||||
assert.equal(quote.isBlankNode(doc.getElementById("p")), false);
|
||||
assert.equal(quote.isBlankNode(doc.getElementById("e")), true);
|
||||
});
|
||||
|
||||
test("isGapPosition: no gap when a rule separates the quote parts", () => {
|
||||
const { doc } = createDocument(
|
||||
`<blockquote type="cite">A</blockquote><hr><br id="gap"><blockquote type="cite">B</blockquote>`,
|
||||
);
|
||||
const index = Array.prototype.indexOf.call(
|
||||
doc.body.childNodes,
|
||||
doc.getElementById("gap"),
|
||||
);
|
||||
const range = setCaret(doc, doc.body, index);
|
||||
assert.equal(quote.isGapPosition(doc, range), false);
|
||||
});
|
||||
|
||||
test("caretContext: a text selection is not collapsed", () => {
|
||||
const { doc } = createDocument(REPLY);
|
||||
const q1 = firstText(doc.getElementById("q1"));
|
||||
setSelection(doc, q1, 0, q1, 5);
|
||||
assert.equal(quote.caretContext(doc).collapsed, false);
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* 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";
|
||||
|
||||
/*
|
||||
* Unit tests for src/lib/settings.js: validating and normalizing user
|
||||
* settings, cleaning up the stored per-identity profiles, and resolving the
|
||||
* effective settings for an identity. Pure functions, called directly with
|
||||
* plain objects; no DOM or WebExtension API is needed. Some invalid inputs
|
||||
* are arbitrary German words (e.g. "blau", "unbekannt"); only their
|
||||
* invalidity matters.
|
||||
*/
|
||||
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const settings = require("../src/lib/settings.js");
|
||||
|
||||
const { DEFAULT_SETTINGS, sanitizeSettings, normalizeStore, resolveSettings } =
|
||||
settings;
|
||||
|
||||
test("empty input yields the defaults", () => {
|
||||
assert.deepEqual(sanitizeSettings(undefined), { ...DEFAULT_SETTINGS });
|
||||
assert.deepEqual(sanitizeSettings("quatsch"), { ...DEFAULT_SETTINGS });
|
||||
});
|
||||
|
||||
test("valid values are kept, colors are lower-cased", () => {
|
||||
const result = sanitizeSettings({
|
||||
template: "{name}:",
|
||||
markerColor: "#AABBCC",
|
||||
textBold: true,
|
||||
splitMode: "manual",
|
||||
});
|
||||
assert.equal(result.template, "{name}:");
|
||||
assert.equal(result.markerColor, "#aabbcc");
|
||||
assert.equal(result.textBold, true);
|
||||
assert.equal(result.splitMode, "manual");
|
||||
});
|
||||
|
||||
test("invalid values fall back to the defaults, unknown keys are dropped", () => {
|
||||
const result = sanitizeSettings({
|
||||
template: " ",
|
||||
markerColor: "blau",
|
||||
textColor: "#12345",
|
||||
textBold: "ja",
|
||||
splitMode: "irgendwie",
|
||||
unbekannt: 42,
|
||||
});
|
||||
assert.equal(result.template, DEFAULT_SETTINGS.template);
|
||||
assert.equal(result.markerColor, DEFAULT_SETTINGS.markerColor);
|
||||
assert.equal(result.textColor, DEFAULT_SETTINGS.textColor);
|
||||
assert.equal(result.textBold, DEFAULT_SETTINGS.textBold);
|
||||
assert.equal(result.splitMode, DEFAULT_SETTINGS.splitMode);
|
||||
assert.equal("unbekannt" in result, false);
|
||||
});
|
||||
|
||||
test("a template that is too long is truncated", () => {
|
||||
const result = sanitizeSettings({ template: "x".repeat(500) });
|
||||
assert.equal(result.template.length, settings.MAX_TEMPLATE_LENGTH);
|
||||
});
|
||||
|
||||
test("normalizeStore drops broken profiles", () => {
|
||||
const store = normalizeStore({
|
||||
global: { template: "[G]:" },
|
||||
identities: { id1: { template: "[A]:" }, id2: null, id3: "x" },
|
||||
});
|
||||
assert.equal(store.global.template, "[G]:");
|
||||
assert.deepEqual(Object.keys(store.identities), ["id1"]);
|
||||
});
|
||||
|
||||
test("resolveSettings: an identity's own profile wins over the global settings", () => {
|
||||
const stored = {
|
||||
global: { template: "[G]:" },
|
||||
identities: { id1: { template: "[A]:" } },
|
||||
};
|
||||
assert.equal(resolveSettings(stored, "id1").template, "[A]:");
|
||||
assert.equal(resolveSettings(stored, "id2").template, "[G]:");
|
||||
assert.equal(resolveSettings(stored, null).template, "[G]:");
|
||||
assert.equal(
|
||||
resolveSettings(undefined, "id1").template,
|
||||
DEFAULT_SETTINGS.template,
|
||||
);
|
||||
});
|
||||
|
||||
test("options page template field uses MAX_TEMPLATE_LENGTH", () => {
|
||||
const html = fs.readFileSync(
|
||||
path.join(__dirname, "..", "src", "options", "options.html"),
|
||||
"utf8",
|
||||
);
|
||||
const match = html.match(/id="template"[^>]*maxlength="(\d+)"/s);
|
||||
assert.ok(match, "maxlength of the template field not found");
|
||||
assert.equal(Number(match[1]), settings.MAX_TEMPLATE_LENGTH);
|
||||
});
|
||||
Reference in new issue
Block a user