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,102 @@
|
|||||||
|
# Architecture – Overview
|
||||||
|
|
||||||
|
## Building blocks
|
||||||
|
|
||||||
|
```text
|
||||||
|
Thunderbird / Betterbird
|
||||||
|
├── Background script (src/background.js) event page, Manifest V3
|
||||||
|
│ ├── registers the compose script (scripting.compose)
|
||||||
|
│ ├── keeps the on/off state per compose window (storage.session, else in memory)
|
||||||
|
│ ├── "Inline Comment" toolbar button (composeAction, badge "on"/"off")
|
||||||
|
│ └── delivers the configuration: settings + identity + on/off + plain text?
|
||||||
|
│
|
||||||
|
├── Compose script (src/compose/compose.js) in the editor document of every compose window
|
||||||
|
│ ├── intercepts typed characters inside a quote (keydown, fallback: beforeinput)
|
||||||
|
│ ├── splits the quote (editor command insertParagraph, fallback: manual split)
|
||||||
|
│ └── inserts the comment with its marker (insertHTML or insertText)
|
||||||
|
│
|
||||||
|
├── Options page (src/options/) settings in storage.local, localized texts
|
||||||
|
│
|
||||||
|
├── Translations (src/_locales/{en,de}/messages.json) default locale: en
|
||||||
|
│
|
||||||
|
└── Shared library (src/lib/) classic UMD scripts, testable under Node
|
||||||
|
├── settings.js defaults, validation, profiles per identity, compose script file list
|
||||||
|
├── marker.js placeholders, initials, comment as DOM node or plain text
|
||||||
|
├── quote.js quote and gap detection, manual split, caret placement
|
||||||
|
└── i18n.js localizeDocument() for data-i18n attributes (options page)
|
||||||
|
```
|
||||||
|
|
||||||
|
The library files attach their functions to `globalThis.InlineComment` and also export them through
|
||||||
|
`module.exports`, so the same file runs in the add-on and in the Node tests. They are classic scripts
|
||||||
|
rather than ES modules because compose scripts cannot load modules.
|
||||||
|
|
||||||
|
## What runs where
|
||||||
|
|
||||||
|
| Context | Scripts, in load order | Defined in |
|
||||||
|
| -------------- | ------------------------------------------------------------------------ | ------------------------------------------- |
|
||||||
|
| Background | `lib/settings.js`, `lib/marker.js`, `background.js` | `manifest.json` → `background` |
|
||||||
|
| Compose window | `lib/settings.js`, `lib/marker.js`, `lib/quote.js`, `compose/compose.js` | `COMPOSE_SCRIPT_FILES` in `lib/settings.js` |
|
||||||
|
| Options page | `lib/settings.js`, `lib/marker.js`, `lib/i18n.js`, `options/options.js` | `<script>` tags in `options.html` |
|
||||||
|
|
||||||
|
## Data flow
|
||||||
|
|
||||||
|
```text
|
||||||
|
Options page ──storage.local──▶ Background ──configuration──▶ Compose script
|
||||||
|
▲ │ │
|
||||||
|
Button (on/off) ───────────┘ └── tabs.sendMessage on ───────┘
|
||||||
|
change (settings,
|
||||||
|
identity, button)
|
||||||
|
```
|
||||||
|
|
||||||
|
The compose script asks for its configuration when it loads and whenever its window gets the focus
|
||||||
|
(`runtime.sendMessage({type: "ic:getConfig"})`) and keeps it locally, because the decision
|
||||||
|
"intercept or not" has to be made immediately on every key press.
|
||||||
|
|
||||||
|
## User interface texts
|
||||||
|
|
||||||
|
All texts the user sees come from `src/_locales/<locale>/messages.json` (English and German, default
|
||||||
|
`en`):
|
||||||
|
|
||||||
|
- `manifest.json`: name, description and button title as `__MSG_key__`.
|
||||||
|
- Background script: badge text and button tooltip via `i18n.getMessage()`.
|
||||||
|
- Options page: static texts via `data-i18n` attributes and `localizeDocument()`, dynamic texts
|
||||||
|
via `i18n.getMessage()`.
|
||||||
|
|
||||||
|
The compose script shows no texts of its own; the marker comes from the user's template. Details:
|
||||||
|
[../components/i18n.md](../components/i18n.md).
|
||||||
|
|
||||||
|
## DOM and markup
|
||||||
|
|
||||||
|
No file writes markup into a DOM sink (`innerHTML`, `outerHTML =`, `insertAdjacentHTML`,
|
||||||
|
`document.write`). Elements are built with `createElement`, `textContent` and `setAttribute`. The
|
||||||
|
editor still receives the HTML comment through `execCommand("insertHTML")`, with the HTML serialized
|
||||||
|
from such a DOM node. See [decision 0005](../decisions/0005-no-markup-sinks.md).
|
||||||
|
|
||||||
|
## Permissions
|
||||||
|
|
||||||
|
| Permission | Used for |
|
||||||
|
| -------------- | ----------------------------------------------------------------------- |
|
||||||
|
| `compose` | read compose windows (identity, plain text), run the compose script |
|
||||||
|
| `scripting` | register the compose script and inject it into open windows |
|
||||||
|
| `storage` | settings (`local`), on/off state per window (`session`) |
|
||||||
|
| `accountsRead` | name and address of the sender identity for the marker and for profiles |
|
||||||
|
|
||||||
|
## Packaging
|
||||||
|
|
||||||
|
`npm run build` checks formatting and runs the tests, then `scripts/build.sh` zips the contents of
|
||||||
|
`src/` into `dist/inline-comment-<version>.xpi` and adds `LICENSE` to the root of the XPI. The
|
||||||
|
version in `package.json`, `src/manifest.json` and `CHANGELOG.md` must match (checked by
|
||||||
|
`test/manifest.test.js`).
|
||||||
|
|
||||||
|
## Further reading
|
||||||
|
|
||||||
|
- Flows in detail: [system-design.md](./system-design.md)
|
||||||
|
- Components: [background](../components/background.md),
|
||||||
|
[compose script](../components/compose-script.md), [options page](../components/options.md),
|
||||||
|
[i18n](../components/i18n.md)
|
||||||
|
- Decisions:
|
||||||
|
- [0001 – Manifest V3 with scripting.compose](../decisions/0001-manifest-v3.md)
|
||||||
|
- [0002 – Let the editor split the quote](../decisions/0002-split-quote-via-editor.md)
|
||||||
|
- [0003 – keydown as trigger, beforeinput as fallback](../decisions/0003-keydown-as-trigger.md)
|
||||||
|
- [0004 – Licence: MPL-2.0](../decisions/0004-licence-mpl-2.0.md)
|
||||||
|
- [0005 – No markup sinks](../decisions/0005-no-markup-sinks.md)
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
# System Design – Flows
|
||||||
|
|
||||||
|
## 1. Start-up
|
||||||
|
|
||||||
|
1. Thunderbird loads the background script (`lib/settings.js`, `lib/marker.js`, `background.js`).
|
||||||
|
2. `ensureComposeScript()` registers the compose script with the ID `inline-comment-compose` unless it
|
||||||
|
is already registered. Files and order are listed in `COMPOSE_SCRIPT_FILES` (`lib/settings.js`).
|
||||||
|
It runs when the background script loads, on `runtime.onStartup` and on `runtime.onInstalled`.
|
||||||
|
3. On install or update (`runtime.onInstalled`), `injectIntoOpenComposeTabs()` also loads the script
|
||||||
|
into compose windows that are already open (registered scripts only apply to new windows). On
|
||||||
|
first install the options page opens.
|
||||||
|
|
||||||
|
## 2. A compose window opens
|
||||||
|
|
||||||
|
1. The compose script sends `ic:getConfig`.
|
||||||
|
2. The background script reads `compose.getComposeDetails(tabId)` (identity, plain text), the
|
||||||
|
identity (`identities.get`), the settings (`resolveSettings`) and the stored on/off state. Without
|
||||||
|
a stored state, `enabledByDefault` of the identity's settings applies.
|
||||||
|
3. Reply: `{ active, isPlainText, settings, identity: {name, email} }`. The button badge shows the
|
||||||
|
state (see [section 4](#4-onoff-and-changes)).
|
||||||
|
|
||||||
|
## 3. Key press inside a quote
|
||||||
|
|
||||||
|
```text
|
||||||
|
keydown while active (printable character, no Ctrl/Alt/Cmd shortcut, AltGr allowed)
|
||||||
|
└─ caret inside a mail quote (blockquote type=cite / _moz_quote)? or (HTML only) in the gap between two quote parts?
|
||||||
|
no → do nothing, the editor types as usual
|
||||||
|
yes → preventDefault + stopPropagation, startComment(character)
|
||||||
|
├─ selection not empty → execCommand("delete")
|
||||||
|
├─ inside a quote:
|
||||||
|
│ splitMode "native": execCommand("insertParagraph")
|
||||||
|
│ caret now outside every quote? → insertComment
|
||||||
|
│ otherwise → execCommand("undo") + manual split
|
||||||
|
│ splitMode "manual": manual split (splitCiteAtRange)
|
||||||
|
├─ in the gap: insertComment
|
||||||
|
└─ neither (e.g. the deletion removed the quote) → execCommand("insertText")
|
||||||
|
insertComment
|
||||||
|
├─ HTML: node = createCommentNode(document, marker, "a", settings, ID) (DOM APIs only)
|
||||||
|
│ <div data-inline-comment=ID style=…>
|
||||||
|
│ <span data-inline-comment-marker style=…>[OH]:</span> a
|
||||||
|
│ </div>
|
||||||
|
│ execCommand("insertHTML", node.outerHTML)
|
||||||
|
│ then move the caret to the end of the comment (found by its ID)
|
||||||
|
└─ plain text: execCommand("insertText", "[OH]: a")
|
||||||
|
```
|
||||||
|
|
||||||
|
- The marker text is the template rendered with `renderTemplate()` and `markerVariables()` (name,
|
||||||
|
initials and email of the sender identity, current date and time). It is set via `textContent`,
|
||||||
|
so a template such as `<b>{initials}</b>` stays literal text.
|
||||||
|
- In `createCommentNode()` the space after the marker and the spaces in the typed text become
|
||||||
|
non-breaking spaces, so the editor keeps leading and repeated spaces.
|
||||||
|
- The comment ID has the form `ic-<time>-<random>` and is only used to find the inserted element.
|
||||||
|
- The styles are inline CSS only (`commentStyle()`, `markerStyle()`), because other mail clients often
|
||||||
|
strip `<style>` blocks and classes.
|
||||||
|
|
||||||
|
Typing further inside the comment is not intercepted: the caret is neither inside a quote nor in the
|
||||||
|
gap. Enter inside the comment is left to the editor; the new line is not a gap either, because its
|
||||||
|
nearest non-blank neighbour above is the comment, not a quote, so it gets no new marker.
|
||||||
|
|
||||||
|
**Fallback `beforeinput`:** input without a matching key press (on-screen keyboard, emoji picker)
|
||||||
|
only arrives as `beforeinput` with `inputType = "insertText"`. It is intercepted and inserted in the
|
||||||
|
next task (`setTimeout 0`), because the editor should not receive further commands while an edit
|
||||||
|
action is running. Characters that arrive in the meantime are collected in `pendingText`.
|
||||||
|
|
||||||
|
## 4. On/off and changes
|
||||||
|
|
||||||
|
- Click on the button: invert the state, store it in `storage.session` (`active:<tabId>`; an
|
||||||
|
in-memory map if `storage.session` is not available), send the configuration to the window
|
||||||
|
(`tabs.sendMessage`) and update the button.
|
||||||
|
- Button state:
|
||||||
|
|
||||||
|
| State | Badge text (message key) | Badge colour | Tooltip (message key) |
|
||||||
|
| ------ | ------------------------ | ------------ | --------------------- |
|
||||||
|
| active | `badgeOn` ("on"/"an") | `#2e7d32` | `buttonTitleActive` |
|
||||||
|
| paused | `badgeOff` ("off"/"aus") | `#757575` | `buttonTitlePaused` |
|
||||||
|
|
||||||
|
- Sender identity changed (`compose.onIdentityChanged`): send the configuration again (marker,
|
||||||
|
profile).
|
||||||
|
- Settings saved (`storage.onChanged`, area `local`): send the configuration to all compose windows.
|
||||||
|
- Window closed (`tabs.onRemoved`): delete its state.
|
||||||
|
|
||||||
|
## 5. Manual split (fallback)
|
||||||
|
|
||||||
|
`splitCiteAtRange()` cuts the content from the caret to the end of the outermost quote
|
||||||
|
(`Range.extractContents()`). Partially selected ancestors, including inner quotes, come along as
|
||||||
|
shallow copies. The rest is put into a shallow copy of the outermost quote and inserted after the
|
||||||
|
comment. Empty halves are removed. For plain-text quotes, the second half gets a `> ` prefix when
|
||||||
|
its first line no longer starts with `>`.
|
||||||
|
|
||||||
|
The comment node comes from `createCommentNode()` (HTML) or `createPlainCommentElement()` (plain
|
||||||
|
text: `<span data-inline-comment>` with line breaks around the text) and is inserted with
|
||||||
|
`insertBefore()`. This change bypasses the editor and is not part of its undo history.
|
||||||
|
|
||||||
|
## 6. Logging
|
||||||
|
|
||||||
|
All console output starts with `[Inline Comment]`. Warnings and errors are always logged; the compose
|
||||||
|
script's diagnostic output (`console.debug`) only appears when the `debug` setting is on. The
|
||||||
|
background script logs a configuration push that could not be delivered (for example to a tab that
|
||||||
|
was just closed) with `console.debug`, independent of that setting.
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
- Pasting from the clipboard (`insertFromPaste`) is not handled.
|
||||||
|
- IME input (`compositionstart`) is not handled.
|
||||||
|
- Plain text: no gap detection, no blank line after the comment.
|
||||||
|
- Whether `insertParagraph` via `execCommand` splits the quote like the Enter key can only be
|
||||||
|
verified in the real editor (manual test). Otherwise the manual split takes over automatically.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Component: Background Script
|
||||||
|
|
||||||
|
**File:** `src/background.js` (loads `lib/settings.js` and `lib/marker.js` first, see `manifest.json`)
|
||||||
|
|
||||||
|
**What:** Event page according to Manifest V3. Thunderbird may stop it at any time and start it again
|
||||||
|
on the next event. Therefore all listeners are registered at the top level, and the on/off state lives
|
||||||
|
in `storage.session` instead of a variable. If `storage.session` is not available, an in-memory map
|
||||||
|
is used as a fallback (the state is then lost when the page stops).
|
||||||
|
|
||||||
|
**Tasks:**
|
||||||
|
|
||||||
|
- Register the compose script (`scripting.compose.registerScripts`) whenever the background script
|
||||||
|
loads, and inject it into open compose windows after install or update
|
||||||
|
(`scripting.executeScript`).
|
||||||
|
- Build and deliver the configuration (`ic:getConfig`), push changes (`ic:config`) after a button
|
||||||
|
click, an identity change (`compose.onIdentityChanged`) or saved settings (`storage.onChanged`).
|
||||||
|
- Toolbar button `composeAction`: a click toggles on/off; badge and tooltip show the state.
|
||||||
|
- Delete the saved on/off state of a closed tab (`tabs.onRemoved`).
|
||||||
|
- Open the options page after the first install.
|
||||||
|
|
||||||
|
**Messages:**
|
||||||
|
|
||||||
|
| Type | Direction | Content |
|
||||||
|
| -------------- | --------------------------- | -------------------------------------------------- |
|
||||||
|
| `ic:getConfig` | compose script → background | reply: `{active, isPlainText, settings, identity}` |
|
||||||
|
| `ic:config` | background → compose script | `{config}` as above |
|
||||||
|
|
||||||
|
**Button texts:** badge and tooltip are translated through `i18n.getMessage()` (helper `msg()`):
|
||||||
|
|
||||||
|
| State | Badge | Tooltip | Badge colour |
|
||||||
|
| ------ | ------------------------------- | ------------------- | ------------ |
|
||||||
|
| active | `badgeOn` (en "on", de "an") | `buttonTitleActive` | `#2e7d32` |
|
||||||
|
| paused | `badgeOff` (en "off", de "aus") | `buttonTitlePaused` | `#757575` |
|
||||||
|
|
||||||
|
The default tooltip and the add-on name come from `manifest.json` (`__MSG_actionTitle__`,
|
||||||
|
`__MSG_extensionName__`). Badge texts should stay at four characters or less. See
|
||||||
|
[i18n.md](./i18n.md).
|
||||||
|
|
||||||
|
**Troubleshooting:** `Tools → Developer Tools → Debug Add-ons → Inline Comment → Inspect` opens the
|
||||||
|
console of the background script. Messages start with `[Inline Comment]`.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# Component: Compose Script
|
||||||
|
|
||||||
|
**File:** `src/compose/compose.js` (loads `lib/settings.js`, `lib/marker.js` and `lib/quote.js`
|
||||||
|
first, see `COMPOSE_SCRIPT_FILES`)
|
||||||
|
|
||||||
|
**What:** Runs in the editor document of every compose window. Intercepts characters typed inside a
|
||||||
|
quote, splits the quote and inserts the comment with its marker. Flow:
|
||||||
|
[system-design.md](../architecture/system-design.md#3-key-press-inside-a-quote).
|
||||||
|
|
||||||
|
**Important:**
|
||||||
|
|
||||||
|
- `globalThis.__inlineCommentComposeLoaded` prevents the script from running twice (registration
|
||||||
|
plus injection after install or update).
|
||||||
|
- Changes to the text go through `document.execCommand`, so they end up in the editor's undo
|
||||||
|
history. Only the fallback (manual split) changes the DOM directly.
|
||||||
|
- The HTML comment is built as a DOM node by `createCommentNode()` (`lib/marker.js`) and handed to
|
||||||
|
the editor as `execCommand("insertHTML", node.outerHTML)`. No HTML is assembled from strings, see
|
||||||
|
[decision 0005](../decisions/0005-no-markup-sinks.md).
|
||||||
|
- Markers in the message body:
|
||||||
|
- quote: `blockquote[type=cite]` (HTML), `[_moz_quote=true]` (plain text)
|
||||||
|
- own comment: `[data-inline-comment="<id>"]`, marker: `[data-inline-comment-marker]`
|
||||||
|
- Comments inside a quote (for example inline comments written earlier in the thread) count as part
|
||||||
|
of the quote and are split like any other quoted text.
|
||||||
|
- The script shows no user interface texts, so it does not use `_locales`. Date and time in the
|
||||||
|
marker (`{date}`, `{time}`) are formatted in the application's locale.
|
||||||
|
|
||||||
|
**Troubleshooting:** In the settings, under "Advanced", turn on "Diagnostic output in the error
|
||||||
|
console". The messages appear in the error console of Thunderbird/Betterbird (`Ctrl+Shift+J`) and
|
||||||
|
start with `[Inline Comment]`.
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
# Component: Translations (i18n)
|
||||||
|
|
||||||
|
**Files:** `src/_locales/en/messages.json`, `src/_locales/de/messages.json`, `src/lib/i18n.js`;
|
||||||
|
checked by `test/i18n.test.js`
|
||||||
|
|
||||||
|
**What:** The user interface is available in English and German through the standard WebExtension
|
||||||
|
`i18n` API. `manifest.json` sets `"default_locale": "en"`. Thunderbird picks the messages that match
|
||||||
|
its user interface language and falls back to English for any other language.
|
||||||
|
|
||||||
|
## Message files
|
||||||
|
|
||||||
|
Each locale has one `messages.json`. Every entry has a key, the text and a description (the
|
||||||
|
`example` value is shortened here):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"profileOwnSettings": {
|
||||||
|
"message": "$IDENTITY$ – own settings",
|
||||||
|
"description": "Options page: entry of the identity drop-down list for an identity with its own settings.",
|
||||||
|
"placeholders": {
|
||||||
|
"identity": {
|
||||||
|
"content": "$1",
|
||||||
|
"example": "Jane Doe <…>"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Keys:** letters, digits, `_` and `@` only; the project uses camelCase.
|
||||||
|
- **Descriptions** are notes for translators. They are written in English and are identical in every
|
||||||
|
locale.
|
||||||
|
- **Placeholders** (`$NAME$`) are defined under `placeholders`; `$1` … `$9` take the substitutions
|
||||||
|
passed to `getMessage(key, [values])`. All locales define the same placeholders.
|
||||||
|
|
||||||
|
## Where messages are used
|
||||||
|
|
||||||
|
| Where | How | Example |
|
||||||
|
| --------------- | ----------------------------------------------------------- | ------------------------------------ |
|
||||||
|
| `manifest.json` | `__MSG_key__` | `"name": "__MSG_extensionName__"` |
|
||||||
|
| `background.js` | `msg(key)` → `i18n.getMessage(key)` | badge `badgeOn` / `badgeOff` |
|
||||||
|
| `options.html` | `data-i18n` and `data-i18n-aria-label` attributes | `<h2 data-i18n="markerHeading">` |
|
||||||
|
| `options.js` | `msg(key, substitutions)` for texts that change at run time | `msg("profileOwnSettings", [label])` |
|
||||||
|
|
||||||
|
The compose script has no texts of its own and does not use the i18n API.
|
||||||
|
|
||||||
|
## `localizeDocument()` (`src/lib/i18n.js`)
|
||||||
|
|
||||||
|
`localizeDocument(doc, getMessage)` walks the document once when the options page loads:
|
||||||
|
|
||||||
|
| Attribute | Effect |
|
||||||
|
| ---------------------- | ------------------------------------ |
|
||||||
|
| `data-i18n="key"` | replaces the element's `textContent` |
|
||||||
|
| `data-i18n-aria-label` | sets the `aria-label` attribute |
|
||||||
|
| `data-i18n-title` | sets the `title` attribute |
|
||||||
|
|
||||||
|
- The English text in the HTML stays as fallback when a message is missing (`getMessage()` returns an
|
||||||
|
empty string or no string at all).
|
||||||
|
- Elements with `data-i18n` must contain text only, because their whole content is replaced. Wrap
|
||||||
|
the text in a `<span data-i18n="…">` when the element also holds other elements (for example a
|
||||||
|
checkbox label).
|
||||||
|
- The function returns the number of replaced texts and attributes.
|
||||||
|
- Translations are always set as text (`textContent`, `setAttribute`, `new Option()`), never as
|
||||||
|
markup. A translation therefore cannot inject HTML (see
|
||||||
|
[decision 0005](../decisions/0005-no-markup-sinks.md)).
|
||||||
|
|
||||||
|
`options.js` calls it first thing, together with `document.documentElement.lang =
|
||||||
|
i18n.getUILanguage()`.
|
||||||
|
|
||||||
|
## Adding a string
|
||||||
|
|
||||||
|
1. Add the key to `src/_locales/en/messages.json` with the English `message` and an English
|
||||||
|
`description` that says where the text appears (and any limits, such as the length of a badge).
|
||||||
|
2. Add the same key to `src/_locales/de/messages.json` with the German `message`, the **same**
|
||||||
|
`description` and the same `placeholders`.
|
||||||
|
3. Use it:
|
||||||
|
- in `options.html`: `data-i18n="key"` (or `data-i18n-aria-label`, `data-i18n-title`) with the
|
||||||
|
English text as fallback content;
|
||||||
|
- in a script: `msg("key")` with the key as a **literal string**, so the tests can find it;
|
||||||
|
- in `manifest.json`: `__MSG_key__`.
|
||||||
|
4. Run `npm test`.
|
||||||
|
|
||||||
|
`test/i18n.test.js` checks that
|
||||||
|
|
||||||
|
- `en` and `de` exist and have exactly the same keys,
|
||||||
|
- every message has a text and the English description, and placeholders match across locales,
|
||||||
|
- every key used in `options.html`, in `msg()`/`getMessage()` calls and in `manifest.json` exists,
|
||||||
|
- every message is used somewhere (remove unused keys),
|
||||||
|
- elements with `data-i18n` contain no child elements,
|
||||||
|
- the options page is fully translated in both languages (rendered in jsdom).
|
||||||
|
|
||||||
|
## Adding a language
|
||||||
|
|
||||||
|
Create `src/_locales/<code>/messages.json` with all keys of the English file, translated messages and
|
||||||
|
unchanged descriptions and placeholders. The key, description and placeholder checks run for every
|
||||||
|
locale folder automatically; add the new code to the list in the test "options page is fully
|
||||||
|
translated" as well, so the rendered page is checked too.
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
# Component: Options Page and Settings
|
||||||
|
|
||||||
|
**Files:** `src/options/options.html`, `options.js`, `options.css`; logic in `src/lib/settings.js`,
|
||||||
|
preview via `src/lib/marker.js`, translations via `src/lib/i18n.js`
|
||||||
|
|
||||||
|
**Storage location:** `storage.local["settings"]`:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"global": {
|
||||||
|
"template": "[{initials}]:",
|
||||||
|
"textColor": "#0056b3",
|
||||||
|
"...": "..."
|
||||||
|
},
|
||||||
|
"identities": { "id3": { "template": "[{initials} / ACME]:", "...": "..." } }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Without its own profile, an identity uses `global`; the page then shows the global settings with
|
||||||
|
the fields disabled. An own profile is a complete copy that is created from `global` when the
|
||||||
|
checkbox "Own settings for this identity" is ticked; unticking it deletes the profile.
|
||||||
|
- Every value read passes through `sanitizeSettings()`: unknown keys are dropped, missing or invalid
|
||||||
|
values are replaced with the defaults.
|
||||||
|
|
||||||
|
**Settings:**
|
||||||
|
|
||||||
|
| Key | Default | Meaning |
|
||||||
|
| ------------------------------------------- | --------------- | -------------------------------------------- |
|
||||||
|
| `enabledByDefault` | `true` | new emails start with the add-on active |
|
||||||
|
| `template` | `[{initials}]:` | marker template, max. 200 characters |
|
||||||
|
| `markerColor`, `markerBold`, `markerItalic` | `#003d80`, bold | style of the marker |
|
||||||
|
| `textColor`, `textBold`, `textItalic` | `#0056b3` | style of the own text |
|
||||||
|
| `highlight`, `highlightColor` | off, `#fff8c5` | background of the comment |
|
||||||
|
| `blankLineBefore`, `blankLineAfter` | off | spacing (1em) before/after the comment¹ |
|
||||||
|
| `splitMode` | `native` | `native` = editor splits, `manual` = add-on |
|
||||||
|
| `debug` | off | `console.debug` output of the compose script |
|
||||||
|
|
||||||
|
¹ Plain-text messages only use `blankLineBefore`, as a line break before the marker. Colours, bold,
|
||||||
|
italic and highlight apply to HTML messages only.
|
||||||
|
|
||||||
|
Placeholders in the template: `{initials}`, `{name}`, `{email}`, `{date}`, `{time}`. The buttons
|
||||||
|
below the template field insert them at the cursor.
|
||||||
|
|
||||||
|
Changes are saved 300 ms after the last edit and reach open compose windows through
|
||||||
|
`storage.onChanged`.
|
||||||
|
"Reset to defaults" asks for confirmation: the first click changes the button text, a second click
|
||||||
|
within four seconds resets the settings shown.
|
||||||
|
|
||||||
|
**Identities:** read with `identities.list()`, or from `accounts.list()` if that is not available.
|
||||||
|
The profile list shows "All identities (default)" first, then each identity, marked when it has its
|
||||||
|
own settings.
|
||||||
|
|
||||||
|
**Preview:** built with DOM APIs only: two `<blockquote type="cite">` elements with sample text and
|
||||||
|
the comment node from `createCommentNode()` in between. Marker and texts are always plain text. It
|
||||||
|
uses the selected identity, otherwise the first identity, otherwise a sample identity from the
|
||||||
|
messages (`previewSampleName`, `previewSampleEmail`).
|
||||||
|
|
||||||
|
**Localization:** static texts carry `data-i18n` attributes and are replaced by `localizeDocument()`
|
||||||
|
when the page loads; `<html lang>` is set from `i18n.getUILanguage()`. Dynamic texts (profile list,
|
||||||
|
hints, status, reset confirmation, preview) come from `i18n.getMessage()`. Details:
|
||||||
|
[i18n.md](./i18n.md).
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
# 0001 – Manifest V3 with scripting.compose
|
||||||
|
|
||||||
|
**Date:** 2026-11-24 · **Status:** accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Thunderbird supports MailExtensions with Manifest V2 and V3. Thunderbird 128 is the first ESR release
|
||||||
|
with full Manifest V3 support; in Manifest V3, compose scripts are registered through
|
||||||
|
`scripting.compose`. The add-on is developed and tested with Betterbird 153, which is considerably
|
||||||
|
newer.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Manifest V3 with a minimum version of 128 (`strict_min_version`). Compose scripts are registered with
|
||||||
|
`scripting.compose.registerScripts` (replaces `composeScripts` from V2), and the background script is
|
||||||
|
an event page.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- The background script can be stopped at any time: state lives in `storage.session` (an in-memory
|
||||||
|
map only as a fallback when `storage.session` is missing), listeners are registered at the top
|
||||||
|
level.
|
||||||
|
- Registered scripts only apply to new compose windows; windows that are already open get the
|
||||||
|
script through `scripting.executeScript` after install or update.
|
||||||
|
- No execution of JavaScript strings, only files.
|
||||||
|
- Thunderbird versions before 128 are not supported.
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
# 0002 – Let the editor split the quote, manual split only as fallback
|
||||||
|
|
||||||
|
**Date:** 2026-11-24 · **Status:** accepted, to be confirmed by the manual test
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The original concept was to split the `<blockquote>` directly in the DOM. Direct DOM changes bypass
|
||||||
|
the editor: Ctrl+Z then does not work reliably, and nested quotes have to be handled by hand. The
|
||||||
|
Thunderbird mail editor, however, already splits quotes itself when Enter is pressed inside a quote,
|
||||||
|
right up to the outermost quote.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
Default (`splitMode = "native"`): trigger `execCommand("insertParagraph")`, which is the same action
|
||||||
|
as Enter. If the caret is outside every quote afterwards, the comment is inserted with `insertHTML`
|
||||||
|
(HTML messages) or `insertText` (plain-text messages). Both steps end up in the undo history.
|
||||||
|
|
||||||
|
If the editor does not split the quote, `insertParagraph` is reverted with `undo` and the manual
|
||||||
|
split (`splitCiteAtRange`) is used instead. The manual split can also be selected permanently in the
|
||||||
|
settings ("Advanced" → "Split the quote" → "by the add-on").
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- Ctrl+Z may need two steps (comment, then split).
|
||||||
|
- Whether `insertParagraph` via `execCommand` splits the quote exactly like the Enter key can only be
|
||||||
|
verified in the real editor. The automatic fallback keeps the add-on working if it does not.
|
||||||
|
- The manual split is not part of the editor's undo history.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# 0003 – keydown as trigger, beforeinput as fallback
|
||||||
|
|
||||||
|
**Date:** 2026-11-24 · **Status:** accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The quote should only be split on actual text input, not on clicking or selecting. Candidates are
|
||||||
|
`keydown` and `beforeinput`. During `beforeinput` an editor action is already running; further
|
||||||
|
`execCommand` calls inside it are not reliable in Gecko.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
- `keydown`: printable keys without Ctrl/Alt/Cmd (AltGr allowed, so that `@`, `€`, `{` work).
|
||||||
|
Intercept, then split and insert immediately.
|
||||||
|
- `beforeinput` with `inputType = "insertText"`: only for input without a matching key press
|
||||||
|
(on-screen keyboard, emoji picker). Intercept and insert in the next task; characters arriving in
|
||||||
|
between are collected in `pendingText`.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- Shortcuts such as Ctrl+C and Ctrl+A, named keys such as the arrow keys, Delete, Backspace and
|
||||||
|
Enter, and clicks never start a comment; the editor handles them as usual.
|
||||||
|
- Dead keys (`^`, `´`) deliver the finished character with the second key press; IME input
|
||||||
|
(`compositionstart`) is not handled.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# 0004 – Licence: Mozilla Public License 2.0
|
||||||
|
|
||||||
|
**Date:** 2026-11-24 · **Status:** accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The repository is published publicly, and the add-on is meant to be listed on addons.thunderbird.net
|
||||||
|
(ATN). The licence should:
|
||||||
|
|
||||||
|
- keep the author's attribution in copies, forks and reused files,
|
||||||
|
- make sure that improvements to the add-on's own files stay open, without restricting what the
|
||||||
|
add-on may be combined with,
|
||||||
|
- be easy to select on ATN and familiar to Thunderbird reviewers and contributors.
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
All source files are licensed under the Mozilla Public License 2.0 (MPL-2.0).
|
||||||
|
|
||||||
|
- **Attribution through per-file notices.** Every source file starts with a notice: copyright line,
|
||||||
|
`SPDX-License-Identifier: MPL-2.0` and the text of MPL Exhibit A. Under §3.4 of the MPL, recipients
|
||||||
|
may not remove or alter the substance of licence notices, including copyright notices, in the
|
||||||
|
Source Code Form. Because the notice sits in each file, the attribution travels with every file,
|
||||||
|
even when single files are copied into another project.
|
||||||
|
- **File-level copyleft.** Modified versions of covered files must stay under MPL-2.0, and their
|
||||||
|
source must be available when they are distributed, also as part of an executable form such as an
|
||||||
|
XPI (§3.1, §3.2). New files in a larger work may use any licence (§3.3), so the add-on can be
|
||||||
|
combined with code under other licences.
|
||||||
|
- **Built-in licence on ATN.** MPL-2.0 is one of the licences offered by the ATN listing form, so no
|
||||||
|
custom licence text has to be maintained there.
|
||||||
|
- **Common for Thunderbird add-ons.** Thunderbird itself is licensed under MPL-2.0, and many add-ons
|
||||||
|
use it; reviewers and contributors know its terms.
|
||||||
|
- In addition, MPL-2.0 contains an explicit patent licence from contributors (§2.1) and, without
|
||||||
|
Exhibit B in the headers, stays compatible with the GPL and LGPL as "Secondary Licenses" (§3.3).
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- **MIT:** short, very permissive and widely known. But there is no copyleft, so modified versions may
|
||||||
|
be distributed without source, and the attribution lives in a single licence text that is easily
|
||||||
|
lost when individual files are copied.
|
||||||
|
- **Apache-2.0:** permissive, with an explicit patent licence and a NOTICE file for attribution. But
|
||||||
|
there is no copyleft either, and the NOTICE and change-notice handling adds process without keeping
|
||||||
|
changes to the add-on's own files open.
|
||||||
|
- **CPAL-1.0:** strong attribution, since the attribution notice has to be shown in the user
|
||||||
|
interface. But it is rarely used and less familiar to reviewers, it is not a built-in choice on
|
||||||
|
ATN, it is incompatible with the GPL, and the user interface attribution clause is awkward for an
|
||||||
|
add-on that lives in the compose window.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- `LICENSE` with the full MPL-2.0 text lies in the repository root and in the root of every XPI
|
||||||
|
(`scripts/build.sh`).
|
||||||
|
- Every `.js` and `.css` file starts with the licence header as a block comment (after a shebang, if
|
||||||
|
any); HTML and SVG files carry it as `<!-- … -->` (HTML directly after `<!doctype html>`), shell
|
||||||
|
scripts as `# ` lines. JSON files have no header, because JSON has no comments.
|
||||||
|
- `package.json` declares `"license": "MPL-2.0"`.
|
||||||
|
- `test/license.test.js` checks the licence text, the header in every source, test and script file,
|
||||||
|
the package metadata and that `scripts/build.sh` adds `LICENSE` to the XPI.
|
||||||
|
- New files get the same header. Third-party code may only be added if its licence is compatible, and
|
||||||
|
it keeps its own notices.
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# 0005 – No markup sinks: build DOM with DOM APIs
|
||||||
|
|
||||||
|
**Date:** 2026-11-24 · **Status:** accepted
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Version 0.1.0 assembled the comment block as an HTML string with hand-written escaping and wrote it
|
||||||
|
into the DOM with `innerHTML` for the manual split and the options page preview. Reviewers on
|
||||||
|
addons.thunderbird.net (ATN) reject add-ons that create DOM nodes from HTML strings that may contain
|
||||||
|
unsanitized data, i.e. code that writes markup into DOM sinks: assignments to `innerHTML` or
|
||||||
|
`outerHTML`, `insertAdjacentHTML` and `document.write`. Such sinks are also the usual way for
|
||||||
|
untrusted text to turn into markup; here the marker template, the identity name and translated
|
||||||
|
messages all end up in the page.
|
||||||
|
|
||||||
|
At the same time, the comment must reach the mail editor through `execCommand("insertHTML")`: only
|
||||||
|
editor commands end up in the undo history, so Ctrl+Z keeps working (see
|
||||||
|
[decision 0002](./0002-split-quote-via-editor.md)).
|
||||||
|
|
||||||
|
## Decision
|
||||||
|
|
||||||
|
- **DOM APIs only.** Elements are built with `createElement`, `createTextNode`, `textContent`,
|
||||||
|
`setAttribute`, `append`, `replaceChildren` and `new Option()`. User data and messages are always
|
||||||
|
set as text, never parsed as markup.
|
||||||
|
- **Comment block:** `createCommentNode()` in `src/lib/marker.js` builds the `<div>` with the marker
|
||||||
|
`<span>` and the first text as a DOM node. The options page preview and the manual split insert
|
||||||
|
this node directly.
|
||||||
|
- **`insertHTML` stays for undo.** In the editor, the compose script serializes the same node with
|
||||||
|
`outerHTML` (reading only) and passes the string to `execCommand("insertHTML", …)`. The HTML is
|
||||||
|
therefore generated from DOM nodes, never assembled by hand, and text such as `<b>` in a marker
|
||||||
|
template arrives as escaped text.
|
||||||
|
- **Translations** are applied with `textContent` and `setAttribute` (`localizeDocument()`). Because
|
||||||
|
`textContent` replaces the whole content, elements with `data-i18n` must contain text only.
|
||||||
|
- **Guarded by a test:** `test/dom-sinks.test.js` scans every file in `src/` and fails on
|
||||||
|
`innerHTML`, `outerHTML` assignments, `insertAdjacentHTML` and `document.write`. Reading
|
||||||
|
`outerHTML` is allowed.
|
||||||
|
|
||||||
|
## Alternatives considered
|
||||||
|
|
||||||
|
- **Insert the node with DOM methods (such as `insertBefore()`) in the editor as well:** no markup
|
||||||
|
string at all, but the change bypasses the editor and Ctrl+Z no longer undoes it. Kept only for
|
||||||
|
the manual split.
|
||||||
|
- **`execCommand("insertText")` plus formatting commands:** no undo problem, but colours, bold and
|
||||||
|
data attributes would need several commands and are hard to control. Used only for plain-text
|
||||||
|
messages.
|
||||||
|
- **Keep escaping HTML strings by hand (as in 0.1.0) or sanitize them:** still writes into a markup
|
||||||
|
sink and would not pass the review rule; every new string is another chance to forget the escaping.
|
||||||
|
|
||||||
|
## Consequences
|
||||||
|
|
||||||
|
- New UI code must use DOM APIs; `npm test` fails otherwise.
|
||||||
|
- Elements with `data-i18n` must not contain child elements (checked by `test/i18n.test.js`).
|
||||||
|
- The preview in the options page and the comment in the editor are built by the same function and
|
||||||
|
look the same.
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
# Guide: Develop and test the add-on
|
||||||
|
|
||||||
|
This guide covers everything from a fresh clone to a release: build, load the add-on into
|
||||||
|
Thunderbird, debug it and check the package the way addons.thunderbird.net (ATN) does.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- **Node.js 22 or later** with npm (see `engines` in `package.json`).
|
||||||
|
- **zip** (Info-ZIP) and **bash**, used by `scripts/build.sh` to pack the `.xpi`. On Windows, use
|
||||||
|
Git Bash or WSL and make sure `zip` is on the `PATH`.
|
||||||
|
- **Thunderbird 128 or later** (or Betterbird) for loading and testing the add-on.
|
||||||
|
- Any editor. Formatting is done by Prettier (`npm run format`), so no editor settings are needed.
|
||||||
|
|
||||||
|
## Get the code
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://git.hassio-muc.de/Oliver_Herb/inline-comment.git
|
||||||
|
cd inline-comment
|
||||||
|
npm install
|
||||||
|
```
|
||||||
|
|
||||||
|
`npm install` only installs development tools (Prettier, ESLint, jsdom). The add-on itself has no
|
||||||
|
runtime dependencies.
|
||||||
|
|
||||||
|
## Everyday commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm test # unit and DOM tests (node:test + jsdom), no Thunderbird needed
|
||||||
|
npm run lint # ESLint: JavaScript checks and JSDoc rules
|
||||||
|
npm run format # format all files with Prettier
|
||||||
|
npm run check # format check + lint + tests, run before every push
|
||||||
|
npm run build # check + dist/inline-comment-<version>.xpi
|
||||||
|
```
|
||||||
|
|
||||||
|
Run a single test file with `node --test test/marker.test.js`.
|
||||||
|
|
||||||
|
The lint configuration is in `eslint.config.mjs`: the recommended rule sets of ESLint and
|
||||||
|
`eslint-plugin-jsdoc`, reported as errors, plus a JSDoc block with typed `@param` and `@returns`
|
||||||
|
tags for every named function. Inline callbacks are exempt. Each part of the code gets the globals
|
||||||
|
of the environment it runs in (Thunderbird extension scripts, the shared `src/lib/` scripts or
|
||||||
|
Node).
|
||||||
|
|
||||||
|
The `.xpi` is a plain ZIP of `src/` plus the `LICENSE` file. There is no bundler, no transpiler and
|
||||||
|
no minification: every file from `src/` goes into the package unchanged.
|
||||||
|
|
||||||
|
## Repository layout
|
||||||
|
|
||||||
|
| Path | Content |
|
||||||
|
| ------------------- | -------------------------------------------------------------------------- |
|
||||||
|
| `src/manifest.json` | Manifest V3, permissions, version |
|
||||||
|
| `src/background.js` | Registers the compose script, toolbar button, configuration per window |
|
||||||
|
| `src/compose/` | Compose script: catches typing inside a quote and inserts the comment |
|
||||||
|
| `src/lib/` | Testable logic (settings, marker, quote handling, i18n) as classic scripts |
|
||||||
|
| `src/options/` | Options page |
|
||||||
|
| `src/_locales/` | English and German UI texts |
|
||||||
|
| `test/` | Automated tests |
|
||||||
|
| `scripts/build.sh` | Packs the `.xpi` |
|
||||||
|
| `listing/` | Texts for the addons.thunderbird.net listing |
|
||||||
|
| `.docs/`, `.plan/` | Architecture, decisions, guides, roadmap |
|
||||||
|
|
||||||
|
Background: [architecture overview](../architecture/overview.md).
|
||||||
|
|
||||||
|
## Load the add-on in Thunderbird
|
||||||
|
|
||||||
|
**Temporarily** (until Thunderbird is restarted):
|
||||||
|
|
||||||
|
1. Open `about:debugging` (menu `Tools > Developer Tools > Debug Add-ons`, or the gear menu in the
|
||||||
|
Add-ons Manager) and select **This Thunderbird**.
|
||||||
|
2. Click **Load Temporary Add-on…** and select `dist/inline-comment-<version>.xpi`.
|
||||||
|
Alternatively select `src/manifest.json` to load the sources directly without building.
|
||||||
|
3. After a new build or a change in `src/`, click **Reload** next to the add-on.
|
||||||
|
4. Open a new compose window, for example a reply to a message that contains a quote.
|
||||||
|
|
||||||
|
**Permanently:** open the Add-ons Manager (`Tools > Add-ons and Themes`), click the gear icon,
|
||||||
|
choose **Install Add-on From File…** and select the `.xpi`. Thunderbird and Betterbird do not
|
||||||
|
enforce add-on signatures, so the unsigned build installs this way. A version installed from ATN
|
||||||
|
with the same add-on ID (`inline-comment@ih-engineering.de`) is replaced.
|
||||||
|
|
||||||
|
## Debugging
|
||||||
|
|
||||||
|
- **Background script:** in `about:debugging > This Thunderbird`, click **Inspect** next to
|
||||||
|
Inline Comment. The toolbox shows the console of the background script, the debugger and, under
|
||||||
|
Storage, the extension storage (key `settings` in `storage.local`).
|
||||||
|
- **Compose script:** it runs inside the editor of each compose window. Its messages appear in the
|
||||||
|
Error Console: `Tools > Developer Tools > Error Console` or **Ctrl+Shift+J**.
|
||||||
|
- **Debug output:** enable **Diagnostic output in the error console** in the options (section
|
||||||
|
Advanced) for detailed messages from the compose script. They are written with `console.debug`;
|
||||||
|
if they do not show up, check that the console filter includes debug messages.
|
||||||
|
- All messages of the add-on start with `[Inline Comment]`, so the console can be filtered by that
|
||||||
|
text.
|
||||||
|
|
||||||
|
## Manual test
|
||||||
|
|
||||||
|
The automated tests run in jsdom without a real mail editor. Before a release, work through the
|
||||||
|
manual test plan in Thunderbird: [testplan.md](./testplan.md).
|
||||||
|
|
||||||
|
## Release a new version
|
||||||
|
|
||||||
|
1. Make the change with tests and run `npm run check`.
|
||||||
|
2. Raise the version in `package.json` **and** `src/manifest.json` (Semantic Versioning) and add a
|
||||||
|
section for it to `CHANGELOG.md`. `test/manifest.test.js` checks that all three match.
|
||||||
|
3. Update the documentation (`README.md`, `README.de.md`, `.docs/` and, if the behaviour or the
|
||||||
|
permissions changed, `listing/`) in the same commit.
|
||||||
|
4. Run `npm run build` and work through the [manual test plan](./testplan.md) with the new `.xpi`.
|
||||||
|
5. Validate the package as described in the next section.
|
||||||
|
6. Commit, tag and push:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git commit -am "Release 0.3.0"
|
||||||
|
git tag -a v0.3.0 -m "Inline Comment 0.3.0"
|
||||||
|
git push origin main v0.3.0
|
||||||
|
```
|
||||||
|
|
||||||
|
7. Upload the `.xpi` to ATN as a new version. Use the `CHANGELOG.md` section as release notes. The
|
||||||
|
listing texts are in [listing/](../../listing/README.md).
|
||||||
|
|
||||||
|
## Validate the package for ATN
|
||||||
|
|
||||||
|
ATN checks every upload with Mozilla's `addons-linter`, as of November 2026 version 6.15.x (ATN's
|
||||||
|
server pins `~6.15.0`). Run the same version locally against the built package:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npx addons-linter@6.15.0 dist/inline-comment-<version>.xpi
|
||||||
|
```
|
||||||
|
|
||||||
|
- ATN accepts the upload when the linter reports **0 errors**. Warnings are shown to the reviewer
|
||||||
|
but do not block the upload.
|
||||||
|
- **Expected warnings:** `MANIFEST_PERMISSIONS` for `compose` and `accountsRead`. These are
|
||||||
|
Thunderbird permissions that the Firefox-oriented linter does not know, so the warnings are false
|
||||||
|
positives.
|
||||||
|
- Any other warning should be fixed or explained in the notes to reviewers
|
||||||
|
([listing/notes-to-reviewers.md](../../listing/notes-to-reviewers.md)).
|
||||||
|
|
||||||
|
**Optional:** Thunderbird's own [webext-linter](https://github.com/thunderbird/webext-linter) knows
|
||||||
|
the Thunderbird APIs and permissions and checks against the ATN review policies:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/thunderbird/webext-linter.git
|
||||||
|
cd webext-linter
|
||||||
|
npm install
|
||||||
|
node verify.js <path-to>/dist/inline-comment-<version>.xpi
|
||||||
|
```
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Manual test in Thunderbird
|
||||||
|
|
||||||
|
The automated tests run in jsdom without a real mail editor. The cases below check the behaviour in
|
||||||
|
Thunderbird (and Betterbird). Record the result together with the add-on version, the application
|
||||||
|
and its version and the date in the daily log (`.plan/daily/<date>.md`) or in the release issue.
|
||||||
|
|
||||||
|
**Preparation:** load the `.xpi` as a temporary add-on (see [development.md](./development.md)) and
|
||||||
|
reply to an email with a longer quote, ideally with history, i.e. nested quotes. Compose in HTML
|
||||||
|
unless a case says otherwise. In the table, `XY` stands for the initials of the sender identity.
|
||||||
|
|
||||||
|
## Behaviour
|
||||||
|
|
||||||
|
| No. | Step | Expected result |
|
||||||
|
| --- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------- |
|
||||||
|
| 1 | Click in the middle of a sentence inside the quote, type "a" | Quote split, `[XY]: a` in blue in between, caret after "a" |
|
||||||
|
| 2 | Keep typing, press Enter, keep typing | No new marker, the text stays blue |
|
||||||
|
| 3 | Ctrl+Z (twice if needed) | Comment gone, quote whole again |
|
||||||
|
| 4 | Type inside the inner (nested) quote | All quote levels split cleanly, no empty quote remnants |
|
||||||
|
| 5 | Inside the quote only click, select, Ctrl+C, arrow keys | Quote unchanged |
|
||||||
|
| 6 | Press Enter inside the quote, then type | The empty line gets the marker |
|
||||||
|
| 7 | Reply at the very top, above the quote | No marker |
|
||||||
|
| 8 | AltGr+Q (`@` on a German keyboard layout) inside the quote | Splits, `[XY]: @` |
|
||||||
|
| 9 | Select text inside the quote and type | Selection replaced, comment at this position |
|
||||||
|
| 10 | Click the "Inline Comment" toolbar button | Badge "off", typing inside the quote behaves normally; click again → "on" |
|
||||||
|
| 11 | Switch the sender (identity), type inside the quote | Marker of the new identity |
|
||||||
|
| 12 | Change the options (template `{name}:`, colour), use the open window | New values without restart |
|
||||||
|
| 13 | Send the email to a test mailbox at a webmail provider (Gmail, Outlook) | Colours and marker visible there |
|
||||||
|
| 14 | Reply in plain-text format, type inside the quote | Quote split, `[XY]: a` without `>` in front |
|
||||||
|
| 15 | Option "Split the quote: by the add-on (fallback)", cases 1 and 4 | Same result (without Ctrl+Z) |
|
||||||
|
| 16 | Keep the compose window open, reload the add-on, type inside the quote | Works without a new window |
|
||||||
|
|
||||||
|
## User interface languages
|
||||||
|
|
||||||
|
Switch the Thunderbird UI language under `Settings > General > Language` (install the language
|
||||||
|
pack or use a localized build if the language is not offered) and restart Thunderbird.
|
||||||
|
|
||||||
|
| No. | Step | Expected result |
|
||||||
|
| --- | --------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| 17 | English UI: open `Add-ons and Themes > Inline Comment > Options`, then a compose window | Add-on listed as "Inline Comment" with the English description; options page, headings, buttons and preview in English; tooltip and badge "on"/"off" in English; no message keys such as `__MSG_…__` visible |
|
||||||
|
| 18 | German UI: same steps as case 17 | Add-on listed as "Inline-Kommentar"; options page in German ("Inline-Kommentar – Einstellungen", "Profil", "Verhalten", …), German preview text, badge "an"/"aus"; no English leftovers, no clipped labels |
|
||||||
|
|
||||||
|
## Applications and versions
|
||||||
|
|
||||||
|
| No. | Step | Expected result |
|
||||||
|
| --- | --------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
|
||||||
|
| 19 | Thunderbird 160 (release channel): install the `.xpi`, run cases 1, 3, 4, 10, 12 and 14 | All pass; no errors or warnings for the add-on in `about:debugging` or the console |
|
||||||
|
| 20 | Thunderbird 153 ESR: install the `.xpi`, run cases 1, 3, 4, 10, 12 and 14 | All pass; no errors or warnings for the add-on in `about:debugging` or the console |
|
||||||
|
|
||||||
|
The full list (cases 1 to 18) runs at least once per release in one of these versions. Betterbird is
|
||||||
|
based on Thunderbird ESR; before a release, repeat the selection of case 20 there as well.
|
||||||
|
|
||||||
|
**If something fails:** enable "Diagnostic output in the error console" in the options, copy the
|
||||||
|
messages starting with `[Inline Comment]` from the Error Console (Ctrl+Shift+J) and record them with
|
||||||
|
the case number in the daily log, or open an issue at
|
||||||
|
<https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues>.
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
* text=auto eol=lf
|
||||||
|
*.svg text eol=lf
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
node_modules/
|
||||||
|
dist/
|
||||||
|
.idea/
|
||||||
|
*.log
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# 2026-11-24
|
||||||
|
|
||||||
|
## Session 1 – project set-up (0.1.0)
|
||||||
|
|
||||||
|
Project created from the concept "Smart Inline Comment" (working title).
|
||||||
|
|
||||||
|
### Done
|
||||||
|
|
||||||
|
- Research: no existing add-on splits quotes while typing and inserts a marker. Thunderbird only
|
||||||
|
splits quotes on Enter, without a marker (bug 1271835 is still open).
|
||||||
|
- Basics checked: Betterbird 153.8 as test application, Manifest V3 with `scripting.compose`
|
||||||
|
(Thunderbird 128 or later).
|
||||||
|
- Repository, documentation (`.docs/`, `.plan/`), code and tests created.
|
||||||
|
- Deviations from the concept: the editor splits the quote instead of our own DOM manipulation
|
||||||
|
(decision 0002), `keydown` instead of `beforeinput` as the trigger (decision 0003).
|
||||||
|
- Version 0.1.0 built, automated tests pass.
|
||||||
|
|
||||||
|
### Next steps
|
||||||
|
|
||||||
|
- Manual test following `.docs/guides/testplan.md`, especially tests 1, 3 and 4 (split by the
|
||||||
|
editor).
|
||||||
|
- Record the result here, fix bugs, then publish a release.
|
||||||
|
|
||||||
|
## Session 2 – public release preparation (0.2.0)
|
||||||
|
|
||||||
|
### Done
|
||||||
|
|
||||||
|
- **Licence: MPL-2.0.** Thunderbird itself is licensed under the Mozilla Public License 2.0, and it
|
||||||
|
is the common choice for Thunderbird add-ons. Its file-level copyleft keeps changes to these files
|
||||||
|
open, while the add-on can still be combined with code under other licences; it is accepted on
|
||||||
|
addons.thunderbird.net and compatible with the GPL. `LICENSE` is in the repository and in the XPI,
|
||||||
|
every source file carries the licence header (enforced by a test).
|
||||||
|
- **English/German UI:** options page, toolbar button, badge and add-on description come from
|
||||||
|
`_locales` (default locale `en`, plus `de`). Tests check that both locales have the same keys and
|
||||||
|
placeholders.
|
||||||
|
- **No markup in DOM sinks:** the comment block and the options preview are built with DOM APIs
|
||||||
|
instead of HTML strings (enforced by a test).
|
||||||
|
- **Fresh public repository:** the add-on will be published as the new repository
|
||||||
|
`inline-comment`, without the earlier private history. Package and XPI renamed to
|
||||||
|
`inline-comment`; code, comments and documentation translated to English.
|
||||||
|
- **ATN research:** `addons-linter` 6.15.0 reports 0 errors for the XPI. The remaining warnings are
|
||||||
|
false positives: the Firefox-oriented linter does not know Thunderbird-only permissions such as
|
||||||
|
`compose` and `accountsRead`.
|
||||||
|
- **JSDoc lint gate:** ESLint with `@eslint/js` and `eslint-plugin-jsdoc` (`eslint.config.mjs`,
|
||||||
|
`npm run lint`); `npm run check` now runs format check, lint and tests. Every named function has
|
||||||
|
a JSDoc block with typed parameters and return value.
|
||||||
|
- Version 0.2.0, automated tests pass.
|
||||||
|
|
||||||
|
### Next steps
|
||||||
|
|
||||||
|
- Manual test following `.docs/guides/testplan.md` in Thunderbird 160 and Thunderbird 153 ESR.
|
||||||
|
- Release in the public repository, then submit to addons.thunderbird.net with the listing texts in
|
||||||
|
`listing/`.
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
# Roadmap
|
||||||
|
|
||||||
|
## State on 2026-11-24
|
||||||
|
|
||||||
|
Version 0.2.0 is built and all automated tests pass. It adds an English/German UI, the MPL-2.0
|
||||||
|
licence and markup-free DOM building, and is prepared for the public repository. **The manual test
|
||||||
|
in Thunderbird is still open.**
|
||||||
|
|
||||||
|
## Phases
|
||||||
|
|
||||||
|
| Phase | Content | State |
|
||||||
|
| ----------------------- | ---------------------------------------------------------------------------------------------- | ------------ |
|
||||||
|
| 1 – Prototype | split the quote when typing, insert the marker | done (0.1.0) |
|
||||||
|
| 2 – Settings | options page, template with placeholders, colours, profiles per identity | done (0.1.0) |
|
||||||
|
| 3 – Polish | nested quotes, Ctrl+Z through the editor, on/off button, gap after Enter | done (0.1.0) |
|
||||||
|
| 4 – Release preparation | English/German UI, MPL-2.0, no markup written to DOM sinks, prepared for the public repository | done (0.2.0) |
|
||||||
|
| 5 – Manual test | [test plan](../.docs/guides/testplan.md) in Thunderbird 160 and Thunderbird 153 ESR | **next** |
|
||||||
|
| 6 – ATN submission | submit to addons.thunderbird.net, listing texts (English and German) in `listing/` | open |
|
||||||
|
|
||||||
|
## Next steps
|
||||||
|
|
||||||
|
1. Run the manual test plan in Thunderbird 160 and Thunderbird 153 ESR, record the results in
|
||||||
|
`.plan/daily/`, fix what fails.
|
||||||
|
2. Publish the `.xpi` as a release in the public repository.
|
||||||
|
3. Submit the add-on to addons.thunderbird.net (ATN) with the listing texts from `listing/`.
|
||||||
|
|
||||||
|
## Ideas for later
|
||||||
|
|
||||||
|
- Treat pasting from the clipboard inside a quote as a comment as well.
|
||||||
|
- Support IME input (`compositionstart`), e.g. Japanese input methods.
|
||||||
|
- Plain-text messages: detect the gap after Enter and add a blank line after the comment.
|
||||||
Whitespace-only changes.
@@ -0,0 +1,3 @@
|
|||||||
|
dist/
|
||||||
|
node_modules/
|
||||||
|
package-lock.json
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
{}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this add-on are documented in this file. The format is based on
|
||||||
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to
|
||||||
|
[Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [0.2.0] - 2026-11-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- English and German user interface: options page, toolbar button, badge and add-on
|
||||||
|
description are translated via `_locales` (default locale English).
|
||||||
|
- Licensed under the Mozilla Public License 2.0: `LICENSE` file in the repository and in the XPI,
|
||||||
|
licence header in every source file.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- The comment block is built with DOM APIs (`createElement`, `textContent`, `setAttribute`)
|
||||||
|
instead of HTML strings; no markup is written to `innerHTML` or similar sinks any more. The
|
||||||
|
editor still receives the comment through `insertHTML` (serialized from the DOM node), so
|
||||||
|
Ctrl+Z keeps working.
|
||||||
|
- The options page preview is built with DOM APIs as well.
|
||||||
|
- Package and XPI renamed to `inline-comment` (`dist/inline-comment-<version>.xpi`).
|
||||||
|
- Documentation translated to English.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- An image or horizontal rule between two quote parts is no longer treated as an empty line, so
|
||||||
|
typing next to it does not start a comment.
|
||||||
|
- Options page: the timer of an earlier reset confirmation no longer ends a new confirmation early.
|
||||||
|
|
||||||
|
## [0.1.0] - 2026-11-24
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- Typing inside a quote splits the quote at the caret and inserts your own text with a marker in
|
||||||
|
between, including nested quotes.
|
||||||
|
- The editor itself splits the quote (like pressing Enter inside a quote), so Ctrl+Z works. If the
|
||||||
|
editor does not split, the add-on splits the quote itself as a fallback.
|
||||||
|
- An empty line between two parts of a quote (after pressing Enter inside a quote) also gets the
|
||||||
|
marker when you type the first character.
|
||||||
|
- Marker template with the placeholders `{initials}`, `{name}`, `{email}`, `{date}`, `{time}`;
|
||||||
|
initials are taken from the display name of the sender identity, or from the address if there is
|
||||||
|
no name.
|
||||||
|
- Styling with inline CSS only: colour for marker and text, bold, italic, background, blank lines.
|
||||||
|
- Plain-text messages: the marker is inserted as plain text.
|
||||||
|
- "Inline Comment" button in the compose window turns the feature on or off for each email, with an
|
||||||
|
"on"/"off" badge.
|
||||||
|
- Options page with global settings, separate profiles per identity, placeholder buttons and a
|
||||||
|
preview.
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
# Contributing to Inline Comment
|
||||||
|
|
||||||
|
Rules and conventions for everyone who works on this repository.
|
||||||
|
|
||||||
|
## What this is
|
||||||
|
|
||||||
|
A MailExtension (Manifest V3) for **Thunderbird** and **Betterbird**, version 128 or later. When you
|
||||||
|
start typing inside a quoted block in the compose window, the add-on splits the quote at the caret
|
||||||
|
and inserts your own text in between, styled and prefixed with a marker such as `[OH]:`. Overview:
|
||||||
|
[README.md](./README.md), structure:
|
||||||
|
[.docs/architecture/overview.md](./.docs/architecture/overview.md).
|
||||||
|
|
||||||
|
## Read first
|
||||||
|
|
||||||
|
1. `.plan/roadmap.md` – current state and next steps
|
||||||
|
2. the latest entry in `.plan/daily/`
|
||||||
|
3. `.docs/architecture/system-design.md` – flows and design decisions
|
||||||
|
4. `.docs/decisions/` – architecture decision records
|
||||||
|
|
||||||
|
## Language
|
||||||
|
|
||||||
|
- **English** for code, identifiers, code comments, JSDoc, documentation, test names and commit
|
||||||
|
messages.
|
||||||
|
- Exceptions: the German UI strings in `src/_locales/de/messages.json`, the German readme
|
||||||
|
`README.de.md` and the German listing texts.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install # development tools only (prettier, eslint, jsdom)
|
||||||
|
npm test # unit and DOM tests (node:test + jsdom)
|
||||||
|
npm run lint # ESLint with the JSDoc rules (eslint.config.mjs)
|
||||||
|
npm run format # format all files with Prettier
|
||||||
|
npm run check # format check + lint + tests; run before every push
|
||||||
|
npm run build # check + dist/inline-comment-<version>.xpi
|
||||||
|
```
|
||||||
|
|
||||||
|
## Rules
|
||||||
|
|
||||||
|
- **Bilingual UI:** every user-visible string comes from `_locales` (default locale `en`, plus
|
||||||
|
`de`). Each UI string needs a key in **both** `src/_locales/en/messages.json` and
|
||||||
|
`src/_locales/de/messages.json`, with an English `description`. In extension pages, mark elements
|
||||||
|
with `data-i18n` (see `src/lib/i18n.js`); in scripts, use `i18n.getMessage()` of the WebExtension
|
||||||
|
API (`messenger` or `browser`). `test/i18n.test.js` enforces identical keys and placeholders in
|
||||||
|
both locales and that every key is used.
|
||||||
|
- **Licence header:** every new `.js`, `.css`, `.html`, `.svg` and `.sh` file in `src/`, `test/` and
|
||||||
|
`scripts/` needs the MPL-2.0 header: `.js` and `.css` as a block comment, HTML and SVG as
|
||||||
|
`<!-- -->` (HTML directly after `<!doctype html>`), shell scripts as `# ` lines after the shebang.
|
||||||
|
`eslint.config.mjs` carries it as well. JSON files get no header. `test/license.test.js` enforces
|
||||||
|
this.
|
||||||
|
- **JSDoc:** every named function (function declarations, and function or arrow expressions
|
||||||
|
assigned to a variable, property or object key) has a JSDoc block with a description, a typed
|
||||||
|
`@param` for each parameter and a typed `@returns` when it returns a value. Inline callbacks
|
||||||
|
passed directly as arguments are exempt. Prefer specific types (`unknown`, `object`,
|
||||||
|
`Record<string, T>`) over `*`, `Object` or `Function`, and write defaults in the description
|
||||||
|
("Defaults to …") instead of `[name=value]`. `npm run lint` enforces this.
|
||||||
|
- **No markup in DOM sinks:** never use `innerHTML`, `insertAdjacentHTML` or `document.write`, and
|
||||||
|
never assign to `outerHTML`. Build DOM nodes with `createElement`, `textContent` and
|
||||||
|
`setAttribute`. Reading `outerHTML` (to hand a node to the editor via `insertHTML`) is fine.
|
||||||
|
`test/dom-sinks.test.js` enforces this for every file in `src/`.
|
||||||
|
- **Mail HTML:** inline CSS only; no `<style>` blocks, no classes. Other mail clients strip them.
|
||||||
|
- **No runtime dependencies** in the add-on. npm packages are development tools only.
|
||||||
|
- **Script format:** files in `src/lib/` are classic scripts in the UMD pattern
|
||||||
|
(`globalThis.InlineComment` plus `module.exports`), because compose scripts cannot load ES modules.
|
||||||
|
- **No secrets, no private infrastructure, no personal data** in the repository: no tokens or
|
||||||
|
passwords, no internal host names, IP addresses or local paths, no real names or e-mail addresses
|
||||||
|
of third persons. Examples and test fixtures use invented names and `example.com` addresses.
|
||||||
|
- **Version and changelog:** every change that ships in the `.xpi` gets an entry in `CHANGELOG.md`
|
||||||
|
and a new version in `package.json` **and** `src/manifest.json`. `test/manifest.test.js` checks
|
||||||
|
that all three match.
|
||||||
|
- **Tests:** new behaviour only with tests. Testable logic belongs in `src/lib/`; `compose.js` and
|
||||||
|
`background.js` stay thin.
|
||||||
|
- **Manual test before releases:** the jsdom tests cannot cover the real mail editor. Before a
|
||||||
|
release, run the manual test plan in `.docs/guides/testplan.md` in Thunderbird and record the
|
||||||
|
result (version, application, date) in `.plan/daily/<date>.md`.
|
||||||
|
- **Docs in the same commit:** update `README.md` / `README.de.md`, `.docs/`, `CHANGELOG.md` and
|
||||||
|
`.plan/daily/<date>.md` in the same commit as the change.
|
||||||
|
|
||||||
|
## Workflow
|
||||||
|
|
||||||
|
- **Develop:** change code and tests, run `npm run check`.
|
||||||
|
- **Try it in Thunderbird:** `npm run build`, then load `dist/inline-comment-<version>.xpi` as a
|
||||||
|
temporary add-on (`about:debugging` → "This Thunderbird" → "Load Temporary Add-on…"). The guides
|
||||||
|
in `.docs/guides/` describe the details.
|
||||||
|
- **Release:** bump the version, update `CHANGELOG.md`, pass the manual test plan, then publish the
|
||||||
|
`.xpi` as a release in the public repository. Submission to addons.thunderbird.net is planned (see
|
||||||
|
`.plan/roadmap.md`).
|
||||||
@@ -0,0 +1,373 @@
|
|||||||
|
Mozilla Public License Version 2.0
|
||||||
|
==================================
|
||||||
|
|
||||||
|
1. Definitions
|
||||||
|
--------------
|
||||||
|
|
||||||
|
1.1. "Contributor"
|
||||||
|
means each individual or legal entity that creates, contributes to
|
||||||
|
the creation of, or owns Covered Software.
|
||||||
|
|
||||||
|
1.2. "Contributor Version"
|
||||||
|
means the combination of the Contributions of others (if any) used
|
||||||
|
by a Contributor and that particular Contributor's Contribution.
|
||||||
|
|
||||||
|
1.3. "Contribution"
|
||||||
|
means Covered Software of a particular Contributor.
|
||||||
|
|
||||||
|
1.4. "Covered Software"
|
||||||
|
means Source Code Form to which the initial Contributor has attached
|
||||||
|
the notice in Exhibit A, the Executable Form of such Source Code
|
||||||
|
Form, and Modifications of such Source Code Form, in each case
|
||||||
|
including portions thereof.
|
||||||
|
|
||||||
|
1.5. "Incompatible With Secondary Licenses"
|
||||||
|
means
|
||||||
|
|
||||||
|
(a) that the initial Contributor has attached the notice described
|
||||||
|
in Exhibit B to the Covered Software; or
|
||||||
|
|
||||||
|
(b) that the Covered Software was made available under the terms of
|
||||||
|
version 1.1 or earlier of the License, but not also under the
|
||||||
|
terms of a Secondary License.
|
||||||
|
|
||||||
|
1.6. "Executable Form"
|
||||||
|
means any form of the work other than Source Code Form.
|
||||||
|
|
||||||
|
1.7. "Larger Work"
|
||||||
|
means a work that combines Covered Software with other material, in
|
||||||
|
a separate file or files, that is not Covered Software.
|
||||||
|
|
||||||
|
1.8. "License"
|
||||||
|
means this document.
|
||||||
|
|
||||||
|
1.9. "Licensable"
|
||||||
|
means having the right to grant, to the maximum extent possible,
|
||||||
|
whether at the time of the initial grant or subsequently, any and
|
||||||
|
all of the rights conveyed by this License.
|
||||||
|
|
||||||
|
1.10. "Modifications"
|
||||||
|
means any of the following:
|
||||||
|
|
||||||
|
(a) any file in Source Code Form that results from an addition to,
|
||||||
|
deletion from, or modification of the contents of Covered
|
||||||
|
Software; or
|
||||||
|
|
||||||
|
(b) any new file in Source Code Form that contains any Covered
|
||||||
|
Software.
|
||||||
|
|
||||||
|
1.11. "Patent Claims" of a Contributor
|
||||||
|
means any patent claim(s), including without limitation, method,
|
||||||
|
process, and apparatus claims, in any patent Licensable by such
|
||||||
|
Contributor that would be infringed, but for the grant of the
|
||||||
|
License, by the making, using, selling, offering for sale, having
|
||||||
|
made, import, or transfer of either its Contributions or its
|
||||||
|
Contributor Version.
|
||||||
|
|
||||||
|
1.12. "Secondary License"
|
||||||
|
means either the GNU General Public License, Version 2.0, the GNU
|
||||||
|
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||||
|
Public License, Version 3.0, or any later versions of those
|
||||||
|
licenses.
|
||||||
|
|
||||||
|
1.13. "Source Code Form"
|
||||||
|
means the form of the work preferred for making modifications.
|
||||||
|
|
||||||
|
1.14. "You" (or "Your")
|
||||||
|
means an individual or a legal entity exercising rights under this
|
||||||
|
License. For legal entities, "You" includes any entity that
|
||||||
|
controls, is controlled by, or is under common control with You. For
|
||||||
|
purposes of this definition, "control" means (a) the power, direct
|
||||||
|
or indirect, to cause the direction or management of such entity,
|
||||||
|
whether by contract or otherwise, or (b) ownership of more than
|
||||||
|
fifty percent (50%) of the outstanding shares or beneficial
|
||||||
|
ownership of such entity.
|
||||||
|
|
||||||
|
2. License Grants and Conditions
|
||||||
|
--------------------------------
|
||||||
|
|
||||||
|
2.1. Grants
|
||||||
|
|
||||||
|
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||||
|
non-exclusive license:
|
||||||
|
|
||||||
|
(a) under intellectual property rights (other than patent or trademark)
|
||||||
|
Licensable by such Contributor to use, reproduce, make available,
|
||||||
|
modify, display, perform, distribute, and otherwise exploit its
|
||||||
|
Contributions, either on an unmodified basis, with Modifications, or
|
||||||
|
as part of a Larger Work; and
|
||||||
|
|
||||||
|
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||||
|
for sale, have made, import, and otherwise transfer either its
|
||||||
|
Contributions or its Contributor Version.
|
||||||
|
|
||||||
|
2.2. Effective Date
|
||||||
|
|
||||||
|
The licenses granted in Section 2.1 with respect to any Contribution
|
||||||
|
become effective for each Contribution on the date the Contributor first
|
||||||
|
distributes such Contribution.
|
||||||
|
|
||||||
|
2.3. Limitations on Grant Scope
|
||||||
|
|
||||||
|
The licenses granted in this Section 2 are the only rights granted under
|
||||||
|
this License. No additional rights or licenses will be implied from the
|
||||||
|
distribution or licensing of Covered Software under this License.
|
||||||
|
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||||
|
Contributor:
|
||||||
|
|
||||||
|
(a) for any code that a Contributor has removed from Covered Software;
|
||||||
|
or
|
||||||
|
|
||||||
|
(b) for infringements caused by: (i) Your and any other third party's
|
||||||
|
modifications of Covered Software, or (ii) the combination of its
|
||||||
|
Contributions with other software (except as part of its Contributor
|
||||||
|
Version); or
|
||||||
|
|
||||||
|
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||||
|
its Contributions.
|
||||||
|
|
||||||
|
This License does not grant any rights in the trademarks, service marks,
|
||||||
|
or logos of any Contributor (except as may be necessary to comply with
|
||||||
|
the notice requirements in Section 3.4).
|
||||||
|
|
||||||
|
2.4. Subsequent Licenses
|
||||||
|
|
||||||
|
No Contributor makes additional grants as a result of Your choice to
|
||||||
|
distribute the Covered Software under a subsequent version of this
|
||||||
|
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||||
|
permitted under the terms of Section 3.3).
|
||||||
|
|
||||||
|
2.5. Representation
|
||||||
|
|
||||||
|
Each Contributor represents that the Contributor believes its
|
||||||
|
Contributions are its original creation(s) or it has sufficient rights
|
||||||
|
to grant the rights to its Contributions conveyed by this License.
|
||||||
|
|
||||||
|
2.6. Fair Use
|
||||||
|
|
||||||
|
This License is not intended to limit any rights You have under
|
||||||
|
applicable copyright doctrines of fair use, fair dealing, or other
|
||||||
|
equivalents.
|
||||||
|
|
||||||
|
2.7. Conditions
|
||||||
|
|
||||||
|
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||||
|
in Section 2.1.
|
||||||
|
|
||||||
|
3. Responsibilities
|
||||||
|
-------------------
|
||||||
|
|
||||||
|
3.1. Distribution of Source Form
|
||||||
|
|
||||||
|
All distribution of Covered Software in Source Code Form, including any
|
||||||
|
Modifications that You create or to which You contribute, must be under
|
||||||
|
the terms of this License. You must inform recipients that the Source
|
||||||
|
Code Form of the Covered Software is governed by the terms of this
|
||||||
|
License, and how they can obtain a copy of this License. You may not
|
||||||
|
attempt to alter or restrict the recipients' rights in the Source Code
|
||||||
|
Form.
|
||||||
|
|
||||||
|
3.2. Distribution of Executable Form
|
||||||
|
|
||||||
|
If You distribute Covered Software in Executable Form then:
|
||||||
|
|
||||||
|
(a) such Covered Software must also be made available in Source Code
|
||||||
|
Form, as described in Section 3.1, and You must inform recipients of
|
||||||
|
the Executable Form how they can obtain a copy of such Source Code
|
||||||
|
Form by reasonable means in a timely manner, at a charge no more
|
||||||
|
than the cost of distribution to the recipient; and
|
||||||
|
|
||||||
|
(b) You may distribute such Executable Form under the terms of this
|
||||||
|
License, or sublicense it under different terms, provided that the
|
||||||
|
license for the Executable Form does not attempt to limit or alter
|
||||||
|
the recipients' rights in the Source Code Form under this License.
|
||||||
|
|
||||||
|
3.3. Distribution of a Larger Work
|
||||||
|
|
||||||
|
You may create and distribute a Larger Work under terms of Your choice,
|
||||||
|
provided that You also comply with the requirements of this License for
|
||||||
|
the Covered Software. If the Larger Work is a combination of Covered
|
||||||
|
Software with a work governed by one or more Secondary Licenses, and the
|
||||||
|
Covered Software is not Incompatible With Secondary Licenses, this
|
||||||
|
License permits You to additionally distribute such Covered Software
|
||||||
|
under the terms of such Secondary License(s), so that the recipient of
|
||||||
|
the Larger Work may, at their option, further distribute the Covered
|
||||||
|
Software under the terms of either this License or such Secondary
|
||||||
|
License(s).
|
||||||
|
|
||||||
|
3.4. Notices
|
||||||
|
|
||||||
|
You may not remove or alter the substance of any license notices
|
||||||
|
(including copyright notices, patent notices, disclaimers of warranty,
|
||||||
|
or limitations of liability) contained within the Source Code Form of
|
||||||
|
the Covered Software, except that You may alter any license notices to
|
||||||
|
the extent required to remedy known factual inaccuracies.
|
||||||
|
|
||||||
|
3.5. Application of Additional Terms
|
||||||
|
|
||||||
|
You may choose to offer, and to charge a fee for, warranty, support,
|
||||||
|
indemnity or liability obligations to one or more recipients of Covered
|
||||||
|
Software. However, You may do so only on Your own behalf, and not on
|
||||||
|
behalf of any Contributor. You must make it absolutely clear that any
|
||||||
|
such warranty, support, indemnity, or liability obligation is offered by
|
||||||
|
You alone, and You hereby agree to indemnify every Contributor for any
|
||||||
|
liability incurred by such Contributor as a result of warranty, support,
|
||||||
|
indemnity or liability terms You offer. You may include additional
|
||||||
|
disclaimers of warranty and limitations of liability specific to any
|
||||||
|
jurisdiction.
|
||||||
|
|
||||||
|
4. Inability to Comply Due to Statute or Regulation
|
||||||
|
---------------------------------------------------
|
||||||
|
|
||||||
|
If it is impossible for You to comply with any of the terms of this
|
||||||
|
License with respect to some or all of the Covered Software due to
|
||||||
|
statute, judicial order, or regulation then You must: (a) comply with
|
||||||
|
the terms of this License to the maximum extent possible; and (b)
|
||||||
|
describe the limitations and the code they affect. Such description must
|
||||||
|
be placed in a text file included with all distributions of the Covered
|
||||||
|
Software under this License. Except to the extent prohibited by statute
|
||||||
|
or regulation, such description must be sufficiently detailed for a
|
||||||
|
recipient of ordinary skill to be able to understand it.
|
||||||
|
|
||||||
|
5. Termination
|
||||||
|
--------------
|
||||||
|
|
||||||
|
5.1. The rights granted under this License will terminate automatically
|
||||||
|
if You fail to comply with any of its terms. However, if You become
|
||||||
|
compliant, then the rights granted under this License from a particular
|
||||||
|
Contributor are reinstated (a) provisionally, unless and until such
|
||||||
|
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||||
|
ongoing basis, if such Contributor fails to notify You of the
|
||||||
|
non-compliance by some reasonable means prior to 60 days after You have
|
||||||
|
come back into compliance. Moreover, Your grants from a particular
|
||||||
|
Contributor are reinstated on an ongoing basis if such Contributor
|
||||||
|
notifies You of the non-compliance by some reasonable means, this is the
|
||||||
|
first time You have received notice of non-compliance with this License
|
||||||
|
from such Contributor, and You become compliant prior to 30 days after
|
||||||
|
Your receipt of the notice.
|
||||||
|
|
||||||
|
5.2. If You initiate litigation against any entity by asserting a patent
|
||||||
|
infringement claim (excluding declaratory judgment actions,
|
||||||
|
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||||
|
directly or indirectly infringes any patent, then the rights granted to
|
||||||
|
You by any and all Contributors for the Covered Software under Section
|
||||||
|
2.1 of this License shall terminate.
|
||||||
|
|
||||||
|
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||||
|
end user license agreements (excluding distributors and resellers) which
|
||||||
|
have been validly granted by You or Your distributors under this License
|
||||||
|
prior to termination shall survive termination.
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 6. Disclaimer of Warranty *
|
||||||
|
* ------------------------- *
|
||||||
|
* *
|
||||||
|
* Covered Software is provided under this License on an "as is" *
|
||||||
|
* basis, without warranty of any kind, either expressed, implied, or *
|
||||||
|
* statutory, including, without limitation, warranties that the *
|
||||||
|
* Covered Software is free of defects, merchantable, fit for a *
|
||||||
|
* particular purpose or non-infringing. The entire risk as to the *
|
||||||
|
* quality and performance of the Covered Software is with You. *
|
||||||
|
* Should any Covered Software prove defective in any respect, You *
|
||||||
|
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||||
|
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||||
|
* essential part of this License. No use of any Covered Software is *
|
||||||
|
* authorized under this License except under this disclaimer. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
************************************************************************
|
||||||
|
* *
|
||||||
|
* 7. Limitation of Liability *
|
||||||
|
* -------------------------- *
|
||||||
|
* *
|
||||||
|
* Under no circumstances and under no legal theory, whether tort *
|
||||||
|
* (including negligence), contract, or otherwise, shall any *
|
||||||
|
* Contributor, or anyone who distributes Covered Software as *
|
||||||
|
* permitted above, be liable to You for any direct, indirect, *
|
||||||
|
* special, incidental, or consequential damages of any character *
|
||||||
|
* including, without limitation, damages for lost profits, loss of *
|
||||||
|
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||||
|
* and all other commercial damages or losses, even if such party *
|
||||||
|
* shall have been informed of the possibility of such damages. This *
|
||||||
|
* limitation of liability shall not apply to liability for death or *
|
||||||
|
* personal injury resulting from such party's negligence to the *
|
||||||
|
* extent applicable law prohibits such limitation. Some *
|
||||||
|
* jurisdictions do not allow the exclusion or limitation of *
|
||||||
|
* incidental or consequential damages, so this exclusion and *
|
||||||
|
* limitation may not apply to You. *
|
||||||
|
* *
|
||||||
|
************************************************************************
|
||||||
|
|
||||||
|
8. Litigation
|
||||||
|
-------------
|
||||||
|
|
||||||
|
Any litigation relating to this License may be brought only in the
|
||||||
|
courts of a jurisdiction where the defendant maintains its principal
|
||||||
|
place of business and such litigation shall be governed by laws of that
|
||||||
|
jurisdiction, without reference to its conflict-of-law provisions.
|
||||||
|
Nothing in this Section shall prevent a party's ability to bring
|
||||||
|
cross-claims or counter-claims.
|
||||||
|
|
||||||
|
9. Miscellaneous
|
||||||
|
----------------
|
||||||
|
|
||||||
|
This License represents the complete agreement concerning the subject
|
||||||
|
matter hereof. If any provision of this License is held to be
|
||||||
|
unenforceable, such provision shall be reformed only to the extent
|
||||||
|
necessary to make it enforceable. Any law or regulation which provides
|
||||||
|
that the language of a contract shall be construed against the drafter
|
||||||
|
shall not be used to construe this License against a Contributor.
|
||||||
|
|
||||||
|
10. Versions of the License
|
||||||
|
---------------------------
|
||||||
|
|
||||||
|
10.1. New Versions
|
||||||
|
|
||||||
|
Mozilla Foundation is the license steward. Except as provided in Section
|
||||||
|
10.3, no one other than the license steward has the right to modify or
|
||||||
|
publish new versions of this License. Each version will be given a
|
||||||
|
distinguishing version number.
|
||||||
|
|
||||||
|
10.2. Effect of New Versions
|
||||||
|
|
||||||
|
You may distribute the Covered Software under the terms of the version
|
||||||
|
of the License under which You originally received the Covered Software,
|
||||||
|
or under the terms of any subsequent version published by the license
|
||||||
|
steward.
|
||||||
|
|
||||||
|
10.3. Modified Versions
|
||||||
|
|
||||||
|
If you create software not governed by this License, and you want to
|
||||||
|
create a new license for such software, you may create and use a
|
||||||
|
modified version of this License if you rename the license and remove
|
||||||
|
any references to the name of the license steward (except to note that
|
||||||
|
such modified license differs from this License).
|
||||||
|
|
||||||
|
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||||
|
Licenses
|
||||||
|
|
||||||
|
If You choose to distribute Source Code Form that is Incompatible With
|
||||||
|
Secondary Licenses under the terms of this version of the License, the
|
||||||
|
notice described in Exhibit B of this License must be attached.
|
||||||
|
|
||||||
|
Exhibit A - Source Code Form License Notice
|
||||||
|
-------------------------------------------
|
||||||
|
|
||||||
|
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/.
|
||||||
|
|
||||||
|
If it is not possible or desirable to put the notice in a particular
|
||||||
|
file, then You may include the notice in a location (such as a LICENSE
|
||||||
|
file in a relevant directory) where a recipient would be likely to look
|
||||||
|
for such a notice.
|
||||||
|
|
||||||
|
You may add additional accurate notices of copyright ownership.
|
||||||
|
|
||||||
|
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||||
|
---------------------------------------------------------
|
||||||
|
|
||||||
|
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||||
|
defined by the Mozilla Public License, v. 2.0.
|
||||||
+245
@@ -0,0 +1,245 @@
|
|||||||
|
[English](./README.md) | **Deutsch**
|
||||||
|
|
||||||
|
# Inline-Kommentar
|
||||||
|
|
||||||
|
Ein Thunderbird-Add-on, um E-Mails direkt im Zitat zu beantworten. Wer auf eine Nachricht antwortet
|
||||||
|
und mitten im zitierten Text zu tippen beginnt, bekommt das Zitat an der Cursor-Position geteilt. Der
|
||||||
|
eigene Text steht dazwischen, farbig abgesetzt und mit einem Marker wie `[OH]:` davor.
|
||||||
|
|
||||||
|
```text
|
||||||
|
> Können Sie mir die Unterlagen bis Freitag schicken?
|
||||||
|
[OH]: Ja, kommen morgen.
|
||||||
|
> Und bitte die Rechnung beilegen.
|
||||||
|
```
|
||||||
|
|
||||||
|
In HTML-Nachrichten sind Marker und eigener Text farbig; in Reintext-Nachrichten hebt allein der
|
||||||
|
Marker den Kommentar ab.
|
||||||
|
|
||||||
|
> **Bildschirmfotos** des Verfassen-Fensters und der Einstellungsseite folgen hier vor der ersten
|
||||||
|
> Veröffentlichung auf addons.thunderbird.net.
|
||||||
|
|
||||||
|
## Kurzinfo
|
||||||
|
|
||||||
|
| Was | Wo |
|
||||||
|
| ----------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| Quellcode | [git.hassio-muc.de/Oliver_Herb/inline-comment](https://git.hassio-muc.de/Oliver_Herb/inline-comment) |
|
||||||
|
| Issues (Fehlerberichte) | [git.hassio-muc.de/Oliver_Herb/inline-comment/issues](https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues) |
|
||||||
|
| Add-on-ID | `inline-comment@ih-engineering.de` |
|
||||||
|
| Paket | `dist/inline-comment-<version>.xpi` (nach `npm run build`) |
|
||||||
|
| Sprachen | Englisch, Deutsch (richtet sich nach der Sprache von Thunderbird) |
|
||||||
|
| Änderungen | [CHANGELOG.md](./CHANGELOG.md) (Englisch) |
|
||||||
|
| Lizenz | [MPL-2.0](./LICENSE) |
|
||||||
|
|
||||||
|
## Kompatibilität
|
||||||
|
|
||||||
|
- **Thunderbird ab Version 128** (MailExtension mit Manifest V3, `strict_min_version` 128.0).
|
||||||
|
- Funktioniert auch in Betterbird, das auf Thunderbird aufbaut.
|
||||||
|
- HTML- und Reintext-Nachrichten, auch verschachtelte Zitate.
|
||||||
|
- Kein plattformabhängiger Code: Das Add-on besteht nur aus JavaScript, HTML und CSS.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
### Von addons.thunderbird.net
|
||||||
|
|
||||||
|
Sobald das Add-on auf addons.thunderbird.net (ATN) gelistet ist, lässt es sich von dort installieren:
|
||||||
|
in Thunderbird **Extras > Add-ons und Themes** öffnen, nach „Inline-Kommentar“ bzw. „Inline Comment“
|
||||||
|
suchen und **Zu Thunderbird hinzufügen** klicken. Updates kommen dann automatisch. Noch ist das
|
||||||
|
Add-on dort nicht gelistet.
|
||||||
|
|
||||||
|
### Aus einer Datei
|
||||||
|
|
||||||
|
1. Die Datei `inline-comment-<version>.xpi` besorgen, entweder von der
|
||||||
|
[Release-Seite](https://git.hassio-muc.de/Oliver_Herb/inline-comment/releases) oder selbst bauen
|
||||||
|
(siehe [Entwickeln](#entwickeln)).
|
||||||
|
2. In Thunderbird **Extras > Add-ons und Themes** öffnen (Add-ons-Verwaltung).
|
||||||
|
3. **Zahnrad > Add-on aus Datei installieren …** wählen und die `.xpi`-Datei auswählen.
|
||||||
|
|
||||||
|
Nach der ersten Installation öffnet sich die Einstellungsseite, damit man den Marker prüfen kann.
|
||||||
|
|
||||||
|
### Vorübergehend, zum Testen
|
||||||
|
|
||||||
|
Ein temporäres Add-on bleibt bis zum nächsten Neustart von Thunderbird geladen.
|
||||||
|
|
||||||
|
1. **Extras > Entwicklerwerkzeuge > Add-ons debuggen** (`about:debugging`) öffnen und
|
||||||
|
**Dieser Thunderbird** wählen.
|
||||||
|
2. **Temporäres Add-on laden …** klicken und die `.xpi`-Datei wählen, oder `src/manifest.json` aus
|
||||||
|
einem Klon dieses Repositorys.
|
||||||
|
3. Nach einer Änderung beim Add-on auf **Neu laden** klicken.
|
||||||
|
|
||||||
|
### Entfernen
|
||||||
|
|
||||||
|
Unter **Extras > Add-ons und Themes** das Add-on „Inline-Kommentar“ deaktivieren oder entfernen.
|
||||||
|
Bereits gesendete Nachrichten behalten ihre Formatierung.
|
||||||
|
|
||||||
|
## Bedienung
|
||||||
|
|
||||||
|
- **Im Zitat tippen:** auf eine Nachricht antworten, an der gewünschten Stelle in den zitierten Text
|
||||||
|
klicken und lostippen. Das Zitat wird an der Cursor-Position geteilt, Marker und eigener Text
|
||||||
|
erscheinen zwischen den beiden Teilen.
|
||||||
|
- **Weiterschreiben:** Der Kommentar lässt sich fortsetzen, auch über mehrere Zeilen mit Enter. Solange
|
||||||
|
der Cursor im eigenen Kommentar bleibt, kommt kein neuer Marker dazu.
|
||||||
|
- **Enter im Zitat, dann tippen:** Enter im Zitat teilt es mit einer leeren Zeile. Sobald man in dieser
|
||||||
|
Zeile tippt, bekommt sie den Marker (HTML-Nachrichten).
|
||||||
|
- **Zitat-Text ersetzen:** einen Teil des Zitats markieren und tippen. Die Markierung wird gelöscht,
|
||||||
|
der eigene Kommentar tritt an ihre Stelle.
|
||||||
|
- **Nichts passiert aus Versehen:** Klicken, Markieren, Kopieren und Bewegen des Cursors im Zitat
|
||||||
|
ändern nichts. Erst ein getipptes Zeichen beginnt einen Kommentar.
|
||||||
|
- **Knopf in der Symbolleiste:** Der Knopf **Inline-Kommentar** im Verfassen-Fenster schaltet das
|
||||||
|
Add-on für diese Nachricht an oder aus. Die Anzeige am Knopf zeigt **an** oder **aus**. Ob neue
|
||||||
|
Nachrichten mit eingeschaltetem Add-on beginnen, steht in den Einstellungen („In neuen E-Mails
|
||||||
|
automatisch aktiv“).
|
||||||
|
- **Rückgängig mit Strg+Z** (Cmd+Z unter macOS): nimmt Kommentar und Teilung zurück. Bei der
|
||||||
|
Standard-Teilung („durch den Editor“) ist die Teilung ein eigener Schritt: Wenn der Kommentar weg
|
||||||
|
ist, noch einmal drücken.
|
||||||
|
|
||||||
|
## Einstellungen
|
||||||
|
|
||||||
|
**Extras > Add-ons und Themes > Inline-Kommentar > Einstellungen** öffnen. Änderungen werden
|
||||||
|
automatisch gespeichert und gelten sofort auch in offenen Verfassen-Fenstern.
|
||||||
|
|
||||||
|
### Profile je Identität
|
||||||
|
|
||||||
|
Standardmäßig gilt ein Satz Einstellungen für alle Identitäten („Alle Identitäten (Standard)“). Eine
|
||||||
|
Identität wählen und **Eigene Einstellungen für diese Identität** anhaken, um ihr einen eigenen Marker
|
||||||
|
und eigene Farben zu geben, z. B. einen anderen Marker für die Arbeitsadresse. Eine Identität ohne
|
||||||
|
eigene Einstellungen nutzt die Einstellungen für alle Identitäten.
|
||||||
|
|
||||||
|
### Marker-Vorlage
|
||||||
|
|
||||||
|
Der Marker entsteht aus einer Vorlage. Standard ist `[{initials}]:`, das ergibt z. B. `[OH]:`. Die
|
||||||
|
Knöpfe unter dem Feld fügen einen Platzhalter ein:
|
||||||
|
|
||||||
|
| Platzhalter | Wird ersetzt durch |
|
||||||
|
| ------------ | ------------------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| `{initials}` | Initialen aus dem Anzeigenamen der Identität („Max Mustermann“ und „Mustermann, Max“ ergeben `MM`); ohne Namen aus der Adresse |
|
||||||
|
| `{name}` | Anzeigename der Absender-Identität (ohne Namen die Adresse) |
|
||||||
|
| `{email}` | E-Mail-Adresse der Absender-Identität |
|
||||||
|
| `{date}` | Aktuelles Datum im Format der Sprache von Thunderbird |
|
||||||
|
| `{time}` | Aktuelle Uhrzeit (Stunden und Minuten) |
|
||||||
|
|
||||||
|
Unbekannte Platzhalter bleiben stehen. Beispiele: `{initials}:`, `[{name}]`, `--- {initials} {date} {time}:`.
|
||||||
|
|
||||||
|
### Darstellung und Abstände
|
||||||
|
|
||||||
|
- **Farben:** Farbe für Marker und Text, jeweils **fett** und **kursiv**; wahlweise **hinterlegen** mit
|
||||||
|
eigener Hintergrundfarbe.
|
||||||
|
- **Abstände:** Leerzeile vor und/oder nach dem Kommentar.
|
||||||
|
- **Vorschau:** zeigt eine Beispiel-Antwort mit den aktuellen Einstellungen.
|
||||||
|
|
||||||
|
Der Kommentar wird nur mit Inline-CSS formatiert, damit die Farben auch in anderen Mailprogrammen
|
||||||
|
erhalten bleiben, die Stylesheets entfernen.
|
||||||
|
|
||||||
|
### Erweitert
|
||||||
|
|
||||||
|
- **Zitat teilen:**
|
||||||
|
- **durch den Editor (Strg+Z funktioniert)** (Standard): Der Mail-Editor teilt das Zitat wie bei
|
||||||
|
Enter im Zitat. Die Teilung lässt sich rückgängig machen. Teilt der Editor das Zitat nicht, teilt
|
||||||
|
es das Add-on selbst, wie bei der Notlösung.
|
||||||
|
- **durch das Add-on (Notlösung)**: Das Add-on teilt das Zitat immer selbst. Nur nutzen, wenn der
|
||||||
|
Standard in der eigenen Umgebung nicht funktioniert; diese Teilung lässt sich nicht mit Strg+Z
|
||||||
|
zurücknehmen.
|
||||||
|
- **Diagnose-Ausgaben in der Fehlerkonsole:** schreibt ausführliche Meldungen in die Fehlerkonsole
|
||||||
|
(**Extras > Entwicklerwerkzeuge > Fehlerkonsole**, Strg+Umschalt+J). Hilfreich für Fehlerberichte.
|
||||||
|
- **Auf Standard zurücksetzen** setzt das angezeigte Profil zurück (zum Bestätigen zweimal klicken).
|
||||||
|
|
||||||
|
## Datenschutz
|
||||||
|
|
||||||
|
- Das Add-on **erhebt keine Daten und überträgt nichts**. Es stellt keine Netzwerkanfragen und enthält
|
||||||
|
keine Statistik- oder Tracking-Funktionen.
|
||||||
|
- Die Einstellungen liegen lokal im Thunderbird-Profil (`storage.local`). Der An/Aus-Zustand je
|
||||||
|
Verfassen-Fenster liegt in `storage.session` und verfällt, wenn das Fenster geschlossen wird.
|
||||||
|
- **Name und E-Mail-Adresse der Identitäten** werden nur gelesen, um den Marker zu bilden und die
|
||||||
|
Identitäten auf der Einstellungsseite aufzulisten. Gespeichert werden sie nicht; ein Profil je
|
||||||
|
Identität wird unter der internen ID der Identität abgelegt.
|
||||||
|
- Im Verfassen-Fenster betrachtet das Add-on nur den Editor rund um den Cursor, um das Zitat zu finden.
|
||||||
|
Der Nachrichteninhalt wird weder gespeichert noch irgendwohin gesendet.
|
||||||
|
|
||||||
|
Berechtigungen laut `src/manifest.json`:
|
||||||
|
|
||||||
|
| Berechtigung | Wofür |
|
||||||
|
| -------------- | --------------------------------------------------------------------- |
|
||||||
|
| `compose` | Angaben zum Verfassen-Fenster (Identität, HTML oder Reintext) |
|
||||||
|
| `scripting` | Verfassen-Skript in die Verfassen-Fenster laden |
|
||||||
|
| `storage` | Einstellungen und An/Aus-Zustand je Verfassen-Fenster speichern |
|
||||||
|
| `accountsRead` | Name und Adresse der Identität für Marker und Einstellungsseite lesen |
|
||||||
|
|
||||||
|
## Grenzen
|
||||||
|
|
||||||
|
- **Einfügen:** Einfügen aus der Zwischenablage im Zitat teilt das Zitat nicht; der eingefügte Text
|
||||||
|
landet im Zitat.
|
||||||
|
- **IME-Eingabe:** Text, der über ein Eingabe-Hilfsprogramm (IME, z. B. für Chinesisch, Japanisch oder
|
||||||
|
Koreanisch) entsteht, teilt das Zitat nicht.
|
||||||
|
- **Reintext-Nachrichten:** Die leere Zeile nach Enter im Zitat wird nicht erkannt (sie bekommt keinen
|
||||||
|
Marker), und die Einstellung „Leerzeile nach dem Kommentar“ wirkt nicht.
|
||||||
|
- **Teilung durch das Add-on:** Eine Teilung, die das Add-on selbst vornimmt (Notlösung, oder wenn
|
||||||
|
der Editor das Zitat nicht teilt), lässt sich nicht mit Strg+Z rückgängig machen.
|
||||||
|
- **Empfänger**, die nur Reintext lesen, sehen nur den Marker, nicht die Farben.
|
||||||
|
|
||||||
|
## Entwickeln
|
||||||
|
|
||||||
|
Voraussetzungen: Node.js ab Version 22, `bash` und `zip` für den Build.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install # nur Entwicklungswerkzeuge (Prettier, ESLint, jsdom); keine Laufzeit-Abhängigkeiten
|
||||||
|
npm test # Unit- und DOM-Tests (node:test + jsdom)
|
||||||
|
npm run lint # ESLint mit JSDoc-Regeln
|
||||||
|
npm run check # Formatprüfung + Lint + Tests, vor jedem Push
|
||||||
|
npm run build # check + dist/inline-comment-<version>.xpi (enthält LICENSE)
|
||||||
|
```
|
||||||
|
|
||||||
|
- Ablauf, Fehlersuche in Thunderbird und neue Version (Englisch):
|
||||||
|
[.docs/guides/development.md](./.docs/guides/development.md)
|
||||||
|
- Handtest im echten Editor: [.docs/guides/testplan.md](./.docs/guides/testplan.md)
|
||||||
|
- Aufbau: [.docs/architecture/overview.md](./.docs/architecture/overview.md)
|
||||||
|
|
||||||
|
Jede Änderung, die ins `.xpi` geht, braucht einen Eintrag in [CHANGELOG.md](./CHANGELOG.md) und eine
|
||||||
|
neue Version in `package.json` **und** `src/manifest.json`; ein Test prüft, dass alle drei
|
||||||
|
übereinstimmen.
|
||||||
|
|
||||||
|
## Wo ändere ich was
|
||||||
|
|
||||||
|
| Thema | Datei |
|
||||||
|
| ------------------------------------------------- | ---------------------------------------------------------------- |
|
||||||
|
| Standardwerte, Prüfung der Einstellungen, Profile | `src/lib/settings.js` |
|
||||||
|
| Marker-Vorlage, Initialen, Kommentar-Block | `src/lib/marker.js` |
|
||||||
|
| Zitat-Erkennung, Teilung, Cursor | `src/lib/quote.js` |
|
||||||
|
| Übersetzungen in die Einstellungsseite einsetzen | `src/lib/i18n.js` |
|
||||||
|
| Texte der Oberfläche (Englisch, Deutsch) | `src/_locales/en/messages.json`, `src/_locales/de/messages.json` |
|
||||||
|
| Tastatur-Abfang im Verfassen-Fenster | `src/compose/compose.js` |
|
||||||
|
| Knopf, An/Aus-Zustand, Konfiguration | `src/background.js` |
|
||||||
|
| Einstellungsseite | `src/options/` |
|
||||||
|
| Berechtigungen, Version | `src/manifest.json` (+ `package.json`, `CHANGELOG.md`) |
|
||||||
|
| `.xpi` packen | `scripts/build.sh` |
|
||||||
|
| Tests | `test/` |
|
||||||
|
|
||||||
|
## Mitmachen
|
||||||
|
|
||||||
|
Fehlerberichte und Ideen bitte als
|
||||||
|
[Issue](https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues). Bei einem Fehler bitte angeben:
|
||||||
|
Version von Thunderbird (oder Betterbird), Betriebssystem, HTML- oder Reintext-Nachricht, die Schritte
|
||||||
|
zum Nachstellen und, wenn möglich, die Ausgabe der Fehlerkonsole mit eingeschalteten
|
||||||
|
„Diagnose-Ausgaben“. Issues dürfen auf Deutsch oder Englisch geschrieben werden.
|
||||||
|
|
||||||
|
Für Änderungen am Code: Code, Kommentare und Commit-Nachrichten auf Englisch, Tests für neue
|
||||||
|
Funktionen, jede Funktion mit JSDoc dokumentieren (`npm run lint` prüft das), jede neue Quelldatei
|
||||||
|
mit dem MPL-2.0-Lizenzkopf beginnen (`test/license.test.js` prüft das), `npm run check` ausführen
|
||||||
|
und einen Eintrag in `CHANGELOG.md` ergänzen. Eine neue Sprache braucht nur eine
|
||||||
|
`src/_locales/<sprache>/messages.json` mit denselben Schlüsseln wie die englische. Beiträge werden
|
||||||
|
unter der MPL-2.0 angenommen. Alle Projektregeln stehen (auf Englisch) in [CONTRIBUTING.md](./CONTRIBUTING.md).
|
||||||
|
|
||||||
|
## Hinweis zur Entstehung
|
||||||
|
|
||||||
|
Teile dieses Add-ons, insbesondere die Dokumentation und Fehlerbehebungen, sind mit Hilfe des
|
||||||
|
KI-Assistenten Claude (Anthropic) entstanden. Idee, Anforderungen und Tests: Oliver Herb.
|
||||||
|
|
||||||
|
## Lizenz
|
||||||
|
|
||||||
|
Copyright 2026 Oliver Herb. Lizenziert unter der Mozilla Public License 2.0 (MPL-2.0), siehe
|
||||||
|
[LICENSE](./LICENSE). Das Add-on darf genutzt, verändert und weitergegeben werden, auch als Fork,
|
||||||
|
solange die Copyright- und Lizenzhinweise in jeder Datei erhalten bleiben (MPL-2.0 §3.4) und
|
||||||
|
veränderte MPL-Dateien unter der MPL bleiben und ihr Quellcode verfügbar ist. Die MPL-2.0 gewährt
|
||||||
|
keine Markenrechte (§2.3): Forks bitte unter einem anderen Namen und mit eigener Add-on-ID
|
||||||
|
veröffentlichen.
|
||||||
|
|
||||||
|
Kein offizielles Projekt von Mozilla, MZLA Technologies oder dem Betterbird-Projekt und von diesen
|
||||||
|
weder unterstützt noch empfohlen. Thunderbird ist eine Marke der Mozilla Foundation.
|
||||||
@@ -0,0 +1,239 @@
|
|||||||
|
**English** | [Deutsch](./README.de.md)
|
||||||
|
|
||||||
|
# Inline Comment
|
||||||
|
|
||||||
|
A Thunderbird add-on for answering emails inline. When you reply to a message and start typing
|
||||||
|
inside the quoted text, the add-on splits the quote at the caret and inserts your own text in
|
||||||
|
between, set apart in colour and prefixed with a marker such as `[OH]:`.
|
||||||
|
|
||||||
|
```text
|
||||||
|
> Could you send me the documents by Friday?
|
||||||
|
[OH]: Yes, they will arrive tomorrow.
|
||||||
|
> And please attach the invoice.
|
||||||
|
```
|
||||||
|
|
||||||
|
In HTML messages the marker and your text are coloured; in plain-text messages the marker alone
|
||||||
|
sets your comment apart.
|
||||||
|
|
||||||
|
> **Screenshots** of the compose window and the options page will be added here before the first
|
||||||
|
> release on addons.thunderbird.net.
|
||||||
|
|
||||||
|
## At a glance
|
||||||
|
|
||||||
|
| What | Where |
|
||||||
|
| ----------- | ------------------------------------------------------------------------------------------------------------------ |
|
||||||
|
| Source code | [git.hassio-muc.de/Oliver_Herb/inline-comment](https://git.hassio-muc.de/Oliver_Herb/inline-comment) |
|
||||||
|
| Issues | [git.hassio-muc.de/Oliver_Herb/inline-comment/issues](https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues) |
|
||||||
|
| Add-on ID | `inline-comment@ih-engineering.de` |
|
||||||
|
| Package | `dist/inline-comment-<version>.xpi` (after `npm run build`) |
|
||||||
|
| Languages | English, German (follows the language of Thunderbird) |
|
||||||
|
| Changes | [CHANGELOG.md](./CHANGELOG.md) |
|
||||||
|
| Licence | [MPL-2.0](./LICENSE) |
|
||||||
|
|
||||||
|
## Compatibility
|
||||||
|
|
||||||
|
- **Thunderbird 128 or later** (Manifest V3 MailExtension, `strict_min_version` 128.0).
|
||||||
|
- Also works in Betterbird, which is based on Thunderbird.
|
||||||
|
- HTML and plain-text messages, including nested quotes.
|
||||||
|
- No platform-specific code: the add-on is plain JavaScript, HTML and CSS.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
### From addons.thunderbird.net
|
||||||
|
|
||||||
|
Once the add-on is listed on addons.thunderbird.net (ATN), install it from there: in Thunderbird open
|
||||||
|
**Tools > Add-ons and Themes**, search for "Inline Comment" and click **Add to Thunderbird**. Updates
|
||||||
|
are then installed automatically. The add-on is not listed yet.
|
||||||
|
|
||||||
|
### From a file
|
||||||
|
|
||||||
|
1. Get the file `inline-comment-<version>.xpi`, either from the
|
||||||
|
[releases page](https://git.hassio-muc.de/Oliver_Herb/inline-comment/releases) or by building it
|
||||||
|
yourself (see [Development](#development)).
|
||||||
|
2. In Thunderbird open **Tools > Add-ons and Themes** (Add-ons Manager).
|
||||||
|
3. Click the **gear icon > Install Add-on From File…** and select the `.xpi` file.
|
||||||
|
|
||||||
|
After the first installation the options page opens so you can check the marker.
|
||||||
|
|
||||||
|
### Temporarily, for testing
|
||||||
|
|
||||||
|
A temporary add-on stays loaded until Thunderbird is restarted.
|
||||||
|
|
||||||
|
1. Open **Tools > Developer Tools > Debug Add-ons** (`about:debugging`) and select
|
||||||
|
**This Thunderbird**.
|
||||||
|
2. Click **Load Temporary Add-on…** and select the `.xpi` file, or `src/manifest.json` from a
|
||||||
|
checkout of this repository.
|
||||||
|
3. After a change, click **Reload** next to the add-on.
|
||||||
|
|
||||||
|
### Removing
|
||||||
|
|
||||||
|
In **Tools > Add-ons and Themes**, disable or remove "Inline Comment". Messages you have already sent
|
||||||
|
keep their formatting.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
- **Type inside a quote:** reply to a message, click into the quoted text where you want to answer
|
||||||
|
and start typing. The quote is split at the caret, and the marker and your text appear between the
|
||||||
|
two parts.
|
||||||
|
- **Keep typing:** you can continue your comment, also over several lines with Enter. No new marker is
|
||||||
|
added as long as the caret stays inside your own comment.
|
||||||
|
- **Enter inside a quote, then type:** pressing Enter inside a quote splits it with an empty line. As
|
||||||
|
soon as you type on that empty line, it gets the marker (HTML messages).
|
||||||
|
- **Replace quoted text:** select part of the quote and type. The selection is deleted and your
|
||||||
|
comment takes its place.
|
||||||
|
- **Nothing happens by accident:** clicking, selecting, copying and moving the caret inside a quote
|
||||||
|
change nothing. Only a typed character starts a comment.
|
||||||
|
- **Toolbar button:** the **Inline Comment** button in the compose window turns the add-on on or off
|
||||||
|
for this message. Its badge shows **on** or **off**. Whether new messages start with the add-on on
|
||||||
|
is set in the options ("Active automatically in new emails").
|
||||||
|
- **Undo with Ctrl+Z** (Cmd+Z on macOS): undoes the comment and the split. With the default split mode
|
||||||
|
("by the editor") the split is a separate step, so press it once more after your comment is gone.
|
||||||
|
|
||||||
|
## Settings
|
||||||
|
|
||||||
|
Open **Tools > Add-ons and Themes > Inline Comment > Options**. Changes are saved automatically and
|
||||||
|
apply to open compose windows right away.
|
||||||
|
|
||||||
|
### Profiles per identity
|
||||||
|
|
||||||
|
By default, one set of settings applies to all identities ("All identities (default)"). Select an
|
||||||
|
identity and tick **Own settings for this identity** to give it its own marker and colours, for
|
||||||
|
example a different marker for a work address. An identity without its own settings uses the settings
|
||||||
|
for all identities.
|
||||||
|
|
||||||
|
### Marker template
|
||||||
|
|
||||||
|
The marker is built from a template. The default is `[{initials}]:`, which gives for example `[OH]:`.
|
||||||
|
Use the buttons below the field to insert a placeholder:
|
||||||
|
|
||||||
|
| Placeholder | Replaced with |
|
||||||
|
| ------------ | -------------------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| `{initials}` | Initials of the identity's display name ("Jane Doe" and "Doe, Jane" give `JD`); taken from the address if there is no name |
|
||||||
|
| `{name}` | Display name of the sending identity (the address if there is no name) |
|
||||||
|
| `{email}` | Email address of the sending identity |
|
||||||
|
| `{date}` | Current date in the format of Thunderbird's language |
|
||||||
|
| `{time}` | Current time (hours and minutes) |
|
||||||
|
|
||||||
|
Unknown placeholders stay as they are. Examples: `{initials}:`, `[{name}]`, `--- {initials} {date} {time}:`.
|
||||||
|
|
||||||
|
### Appearance and spacing
|
||||||
|
|
||||||
|
- **Colours:** marker colour and text colour, each with **bold** and **italic**; optionally a
|
||||||
|
**highlight** with its own background colour.
|
||||||
|
- **Spacing:** a blank line before and/or after the comment.
|
||||||
|
- **Preview:** shows a sample reply with the current settings.
|
||||||
|
|
||||||
|
The comment is formatted with inline CSS only, so the colours also survive in other mail programs
|
||||||
|
that strip style sheets.
|
||||||
|
|
||||||
|
### Advanced
|
||||||
|
|
||||||
|
- **Split the quote:**
|
||||||
|
- **by the editor (Ctrl+Z works)** (default): the mail editor splits the quote, as when you press
|
||||||
|
Enter inside a quote. The split can be undone. If the editor does not split the quote, the
|
||||||
|
add-on splits it itself, as in the fallback mode.
|
||||||
|
- **by the add-on (fallback)**: the add-on always splits the quote itself. Use this only if the
|
||||||
|
default does not work in your setup; this split cannot be undone with Ctrl+Z.
|
||||||
|
- **Diagnostic output in the error console:** writes detailed messages to the error console
|
||||||
|
(**Tools > Developer Tools > Error Console**, Ctrl+Shift+J). Useful for bug reports.
|
||||||
|
- **Reset to defaults** resets the profile that is shown (click twice to confirm).
|
||||||
|
|
||||||
|
## Privacy
|
||||||
|
|
||||||
|
- The add-on **collects no data and transmits nothing**. It makes no network requests and contains no
|
||||||
|
analytics or tracking.
|
||||||
|
- Settings are stored locally in your Thunderbird profile (`storage.local`). The on/off state of each
|
||||||
|
compose window is kept in `storage.session` and discarded when the window is closed.
|
||||||
|
- The **name and email address of your identities** are read only to render the marker and to list
|
||||||
|
the identities on the options page. They are not stored; a profile per identity is saved under the
|
||||||
|
identity's internal ID.
|
||||||
|
- In the compose window the add-on only looks at the editor around the caret to find the quote. The
|
||||||
|
message content is not stored or sent anywhere.
|
||||||
|
|
||||||
|
Permissions requested in `src/manifest.json`:
|
||||||
|
|
||||||
|
| Permission | Used for |
|
||||||
|
| -------------- | --------------------------------------------------------------------- |
|
||||||
|
| `compose` | Reading compose window details (identity, HTML or plain text) |
|
||||||
|
| `scripting` | Loading the compose script into compose windows |
|
||||||
|
| `storage` | Saving the settings and the on/off state per compose window |
|
||||||
|
| `accountsRead` | Reading identity name and address for the marker and the options page |
|
||||||
|
|
||||||
|
## Limitations
|
||||||
|
|
||||||
|
- **Paste:** pasting from the clipboard inside a quote does not split the quote; the pasted text ends
|
||||||
|
up inside the quote.
|
||||||
|
- **IME composition:** text entered through an input method editor (for example Chinese, Japanese or
|
||||||
|
Korean input) does not split the quote.
|
||||||
|
- **Plain-text messages:** the empty line after pressing Enter inside a quote is not detected (it gets
|
||||||
|
no marker), and the setting "Blank line after the comment" has no effect.
|
||||||
|
- **Split by the add-on:** a split made by the add-on itself (fallback mode, or when the editor does
|
||||||
|
not split the quote) cannot be undone with Ctrl+Z.
|
||||||
|
- **Recipients** who read plain text only see the marker, not the colours.
|
||||||
|
|
||||||
|
## Development
|
||||||
|
|
||||||
|
Requirements: Node.js 22 or later, `bash` and `zip` for the build.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install # development tools only (Prettier, ESLint, jsdom); no runtime dependencies
|
||||||
|
npm test # unit and DOM tests (node:test + jsdom)
|
||||||
|
npm run lint # ESLint with JSDoc rules
|
||||||
|
npm run check # format check + lint + tests, run before every push
|
||||||
|
npm run build # check + dist/inline-comment-<version>.xpi (includes LICENSE)
|
||||||
|
```
|
||||||
|
|
||||||
|
- Workflow, debugging in Thunderbird and releasing a new version:
|
||||||
|
[.docs/guides/development.md](./.docs/guides/development.md)
|
||||||
|
- Manual test in the real editor: [.docs/guides/testplan.md](./.docs/guides/testplan.md)
|
||||||
|
- Architecture: [.docs/architecture/overview.md](./.docs/architecture/overview.md)
|
||||||
|
|
||||||
|
Every change that goes into the `.xpi` needs an entry in [CHANGELOG.md](./CHANGELOG.md) and a new
|
||||||
|
version in `package.json` **and** `src/manifest.json`; a test checks that all three match.
|
||||||
|
|
||||||
|
## Where to change what
|
||||||
|
|
||||||
|
| Topic | File |
|
||||||
|
| ------------------------------------------- | ---------------------------------------------------------------- |
|
||||||
|
| Default settings, validation, profiles | `src/lib/settings.js` |
|
||||||
|
| Marker template, initials, comment block | `src/lib/marker.js` |
|
||||||
|
| Quote detection, splitting, caret | `src/lib/quote.js` |
|
||||||
|
| Applying translations to the options page | `src/lib/i18n.js` |
|
||||||
|
| User interface texts (English, German) | `src/_locales/en/messages.json`, `src/_locales/de/messages.json` |
|
||||||
|
| Keyboard handling in the compose window | `src/compose/compose.js` |
|
||||||
|
| Toolbar button, on/off state, configuration | `src/background.js` |
|
||||||
|
| Options page | `src/options/` |
|
||||||
|
| Permissions, version | `src/manifest.json` (+ `package.json`, `CHANGELOG.md`) |
|
||||||
|
| Packaging the `.xpi` | `scripts/build.sh` |
|
||||||
|
| Tests | `test/` |
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
Bug reports and ideas are welcome as
|
||||||
|
[issues](https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues). For a bug, please include the
|
||||||
|
Thunderbird (or Betterbird) version, your operating system, whether the message is HTML or plain text,
|
||||||
|
the steps to reproduce and, if possible, the output from the error console with "Diagnostic output"
|
||||||
|
turned on. Issues may be written in English or German.
|
||||||
|
|
||||||
|
For changes to the code: write code, comments and commit messages in English, add tests for new
|
||||||
|
functions, document every function with JSDoc (`npm run lint` checks it), start every new source
|
||||||
|
file with the MPL-2.0 licence header (`test/license.test.js` checks it), run `npm run check` and add
|
||||||
|
a `CHANGELOG.md` entry. A new language needs only a `src/_locales/<language>/messages.json` with the
|
||||||
|
same keys as the English one. Contributions are accepted under the MPL-2.0. All project rules are
|
||||||
|
listed in [CONTRIBUTING.md](./CONTRIBUTING.md).
|
||||||
|
|
||||||
|
## Development note
|
||||||
|
|
||||||
|
Parts of this add-on, in particular the documentation and bug fixes, were created with the help of
|
||||||
|
the AI assistant Claude (Anthropic). Idea, requirements and testing: Oliver Herb.
|
||||||
|
|
||||||
|
## Licence
|
||||||
|
|
||||||
|
Copyright 2026 Oliver Herb. Licensed under the Mozilla Public License 2.0 (MPL-2.0), see
|
||||||
|
[LICENSE](./LICENSE). You may use, modify and redistribute this add-on, also as a fork, as long as you
|
||||||
|
keep the copyright and licence notices in every file (MPL-2.0 §3.4) and keep modified MPL files under
|
||||||
|
the MPL with their source available. MPL-2.0 grants no trademark rights (§2.3): please give forks a
|
||||||
|
different name and their own add-on ID.
|
||||||
|
|
||||||
|
Not affiliated with or endorsed by Mozilla, MZLA Technologies or the Betterbird project. Thunderbird
|
||||||
|
is a trademark of the Mozilla Foundation.
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* ESLint flat config: the JSDoc lint gate of "npm run lint" (and therefore
|
||||||
|
* of "npm run check" and "npm run build").
|
||||||
|
*
|
||||||
|
* Rule sets: @eslint/js recommended plus eslint-plugin-jsdoc recommended,
|
||||||
|
* both reported as errors so that any finding fails the gate. On top of
|
||||||
|
* that every named function needs a JSDoc block with typed @param and
|
||||||
|
* @returns tags. Inline callbacks (functions passed directly as arguments)
|
||||||
|
* stay exempt.
|
||||||
|
*
|
||||||
|
* Environments:
|
||||||
|
* - src/background.js, src/compose/**, src/options/**: classic scripts in
|
||||||
|
* Thunderbird; browser globals plus the WebExtension namespaces
|
||||||
|
* "messenger" and "browser".
|
||||||
|
* - src/lib/**: classic UMD scripts that run in the browser and are also
|
||||||
|
* loaded with require() by the Node tests; browser and Node globals.
|
||||||
|
* - test/**, scripts/**: CommonJS for Node.
|
||||||
|
* - This file: an ES module for Node.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import js from "@eslint/js";
|
||||||
|
import jsdoc from "eslint-plugin-jsdoc";
|
||||||
|
import globals from "globals";
|
||||||
|
|
||||||
|
/** The WebExtension namespaces Thunderbird provides to add-on scripts. */
|
||||||
|
const WEB_EXTENSION_GLOBALS = Object.freeze({
|
||||||
|
messenger: "readonly",
|
||||||
|
browser: "readonly",
|
||||||
|
});
|
||||||
|
|
||||||
|
export default [
|
||||||
|
{
|
||||||
|
ignores: ["node_modules/**", "dist/**"],
|
||||||
|
},
|
||||||
|
js.configs.recommended,
|
||||||
|
jsdoc.configs["flat/recommended-error"],
|
||||||
|
{
|
||||||
|
name: "inline-comment/jsdoc-gate",
|
||||||
|
rules: {
|
||||||
|
"jsdoc/require-jsdoc": [
|
||||||
|
"error",
|
||||||
|
{
|
||||||
|
require: {
|
||||||
|
FunctionDeclaration: true,
|
||||||
|
FunctionExpression: true,
|
||||||
|
ArrowFunctionExpression: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
"jsdoc/require-param": "error",
|
||||||
|
"jsdoc/require-returns": ["error", { checkGetters: false }],
|
||||||
|
"jsdoc/require-param-type": "error",
|
||||||
|
"jsdoc/require-returns-type": "error",
|
||||||
|
"jsdoc/check-param-names": "error",
|
||||||
|
"jsdoc/no-undefined-types": "off",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "inline-comment/extension-scripts",
|
||||||
|
files: ["src/background.js", "src/compose/**/*.js", "src/options/**/*.js"],
|
||||||
|
languageOptions: {
|
||||||
|
sourceType: "script",
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
...WEB_EXTENSION_GLOBALS,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "inline-comment/lib",
|
||||||
|
files: ["src/lib/**/*.js"],
|
||||||
|
languageOptions: {
|
||||||
|
sourceType: "script",
|
||||||
|
globals: {
|
||||||
|
...globals.browser,
|
||||||
|
...globals.node,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "inline-comment/node",
|
||||||
|
files: ["test/**/*.js", "scripts/**/*.{js,cjs}"],
|
||||||
|
languageOptions: {
|
||||||
|
sourceType: "commonjs",
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "inline-comment/config",
|
||||||
|
files: ["eslint.config.mjs"],
|
||||||
|
languageOptions: {
|
||||||
|
sourceType: "module",
|
||||||
|
globals: {
|
||||||
|
...globals.node,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
# Listing on addons.thunderbird.net
|
||||||
|
|
||||||
|
Texts and settings for the public listing of Inline Comment on
|
||||||
|
[addons.thunderbird.net](https://addons.thunderbird.net) (ATN). The listing is English by default
|
||||||
|
with a German translation (locale switch in the ATN listing editor).
|
||||||
|
|
||||||
|
The text files in this folder are written to be pasted as they are. ATN does not render Markdown in
|
||||||
|
these fields (the description accepts plain text with a few HTML tags), so the files use only
|
||||||
|
paragraphs, simple lists and one indented example, which read well as plain text. Check the preview
|
||||||
|
after pasting.
|
||||||
|
|
||||||
|
## What to enter where
|
||||||
|
|
||||||
|
| ATN field | Value |
|
||||||
|
| ------------------ | ----------------------------------------------------------------------------------------------------------------- |
|
||||||
|
| Name | From `src/_locales/<lang>/messages.json`, key `extensionName`: "Inline Comment" (en), "Inline-Kommentar" (de) |
|
||||||
|
| Add-on URL (slug) | `inline-comment` |
|
||||||
|
| Summary | From `src/_locales/<lang>/messages.json`, key `extensionDescription` (max. 250 characters) |
|
||||||
|
| Description | [description.en.md](./description.en.md), German: [description.de.md](./description.de.md) |
|
||||||
|
| Category | Message Composition |
|
||||||
|
| Tags (max. 20) | inline reply, interleaved reply, quote, bottom posting, reply marker, comment, compose |
|
||||||
|
| License | Mozilla Public License 2.0 |
|
||||||
|
| Homepage | <https://git.hassio-muc.de/Oliver_Herb/inline-comment> |
|
||||||
|
| Support website | <https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues> |
|
||||||
|
| Support email | leave empty (support runs through the issue tracker) |
|
||||||
|
| Privacy policy | [privacy-policy.en.md](./privacy-policy.en.md), German: [privacy-policy.de.md](./privacy-policy.de.md) |
|
||||||
|
| Notes to reviewers | [notes-to-reviewers.md](./notes-to-reviewers.md) (English only) |
|
||||||
|
| Source code | Not needed: the package contains no minified, transpiled or generated code, the files are exactly those in `src/` |
|
||||||
|
| Release notes | The section of the version in [CHANGELOG.md](../CHANGELOG.md) |
|
||||||
|
| Icon | 512×512 PNG rendered from `src/icons/icon.svg` (see below) |
|
||||||
|
| Screenshots | Three screenshots, 16:10, 1280×800 pixels (see below) |
|
||||||
|
|
||||||
|
ATN reads the name and the summary from the uploaded package, localized through `_locales`. If they
|
||||||
|
are changed in the listing editor, keep `extensionName` and `extensionDescription` in both locales in
|
||||||
|
sync, so the add-ons manager and the listing say the same.
|
||||||
|
|
||||||
|
## Icon
|
||||||
|
|
||||||
|
Render the SVG icon to a 512×512 PNG with transparent background, for example with one of:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
rsvg-convert -w 512 -h 512 src/icons/icon.svg -o icon-512.png
|
||||||
|
inkscape src/icons/icon.svg --export-type=png --export-filename=icon-512.png -w 512 -h 512
|
||||||
|
```
|
||||||
|
|
||||||
|
The PNG is a generated file and does not need to be committed. Render it again whenever
|
||||||
|
`src/icons/icon.svg` changes.
|
||||||
|
|
||||||
|
## Screenshots
|
||||||
|
|
||||||
|
Format 16:10, 1280×800 pixels, PNG: ATN names this the maximum and recommended size (640×400 is the
|
||||||
|
smaller alternative). Use a test profile with a neutral sample identity such as "Jane Doe" with an
|
||||||
|
address at `example.com` (marker `[JD]:`) and sample emails, so that no real names, addresses or
|
||||||
|
message contents are visible. ATN shows the same screenshots in every language and translates only
|
||||||
|
the captions, so take them with the English UI and enter the German captions with the locale switch.
|
||||||
|
|
||||||
|
| No. | What to show | Caption (en) | Caption (de) |
|
||||||
|
| --- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------- |
|
||||||
|
| 1 | Compose window, HTML reply to an email with a nested quote: two comments with marker between parts of the quote, the "Inline Comment" toolbar button with the "on" badge visible | Type inside the quote: it is split and your comment set apart. | Im Zitat tippen: Es wird geteilt, dein Kommentar abgesetzt. |
|
||||||
|
| 2 | Options page: marker template, colours and the preview with the sample email | Choose marker, colors and spacing, with a live preview. | Marker, Farben und Abstände wählen, mit Vorschau. |
|
||||||
|
| 3 | Compose window, plain-text reply with a comment between two parts of the quote | Also works in plain-text emails. | Funktioniert auch in Reintext-E-Mails. |
|
||||||
|
|
||||||
|
## Before each submission
|
||||||
|
|
||||||
|
1. `npm run build` and `npx addons-linter@6.15.0 dist/inline-comment-<version>.xpi` (0 errors,
|
||||||
|
see [development.md](../.docs/guides/development.md)).
|
||||||
|
2. Work through the [manual test plan](../.docs/guides/testplan.md).
|
||||||
|
3. Check that the description, privacy policy and notes to reviewers still match the add-on (new
|
||||||
|
options, permissions or limitations).
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
Mit Inline-Kommentar beantwortest du eine E-Mail Punkt für Punkt, direkt im zitierten Text. Antworte auf eine Nachricht, klicke an eine beliebige Stelle im Zitat und tippe los: Das Zitat wird an dieser Stelle geteilt und dein eigener Text steht dazwischen, farbig abgesetzt und mit einem Marker wie [OH]: (deine Initialen) davor. Der Rest des Zitats geht unter deinem Kommentar weiter, so sieht der Empfänger auf einen Blick, auf welchen Satz du antwortest.
|
||||||
|
|
||||||
|
Eine Antwort sieht dann so aus:
|
||||||
|
|
||||||
|
> Können Sie mir die Unterlagen bis Freitag schicken?
|
||||||
|
[OH]: Ja, kommen morgen.
|
||||||
|
> Und bitte die Rechnung beilegen.
|
||||||
|
|
||||||
|
Bedienung
|
||||||
|
|
||||||
|
- Im Zitat klicken und tippen. Das Zitat wird geteilt, Marker und eigener Text erscheinen.
|
||||||
|
- Weiter schreiben, auch über mehrere Zeilen: Solange du im eigenen Kommentar bleibst, kommt kein neuer Marker dazu.
|
||||||
|
- Erst Enter im Zitat drücken und dann tippen: Die leere Zeile zwischen den beiden Zitat-Teilen bekommt den Marker.
|
||||||
|
- Text im Zitat markieren und tippen: Die Markierung wird durch deinen Kommentar ersetzt.
|
||||||
|
- Klicken, markieren und kopieren im Zitat ändert nichts. Erst ein getipptes Zeichen teilt das Zitat.
|
||||||
|
- Verschachtelte Zitate (Antworten auf Antworten) werden auf allen Ebenen geteilt.
|
||||||
|
- Strg+Z nimmt die Teilung zurück (mit den Standard-Einstellungen; ggf. zweimal drücken).
|
||||||
|
|
||||||
|
Knopf in der Symbolleiste
|
||||||
|
|
||||||
|
Der Knopf „Inline-Kommentar“ in der Symbolleiste des Verfassen-Fensters schaltet die Funktion für die aktuelle E-Mail an oder aus. Eine kleine Anzeige auf dem Knopf zeigt „an“ oder „aus“.
|
||||||
|
|
||||||
|
Einstellungen
|
||||||
|
|
||||||
|
Unter Add-ons und Themes, Inline-Kommentar, Einstellungen:
|
||||||
|
|
||||||
|
- Marker-Vorlage mit den Platzhaltern {initials} (Initialen), {name}, {email}, {date} und {time}. Standard: [{initials}]:
|
||||||
|
- Farben für Marker und Text, fett, kursiv und eine Hintergrundfarbe nach Wunsch.
|
||||||
|
- Eine Leerzeile vor oder nach dem Kommentar.
|
||||||
|
- Ob das Add-on in neuen E-Mails automatisch aktiv ist.
|
||||||
|
- Eigene Einstellungen je Absender-Identität, zum Beispiel ein anderer Marker für ein weiteres Konto.
|
||||||
|
- Eine Vorschau, die das Ergebnis schon beim Ändern der Einstellungen zeigt.
|
||||||
|
- Erweitert: wie das Zitat geteilt wird (durch den Editor, dann funktioniert Strg+Z, oder durch das Add-on als Notlösung) und Diagnose-Ausgaben für die Fehlersuche.
|
||||||
|
|
||||||
|
Der Kommentar wird nur mit Inline-Formatierung gestaltet. Marker und Farben bleiben deshalb auch in anderen Mailprogrammen und im Webmail sichtbar.
|
||||||
|
|
||||||
|
Reintext und Betterbird
|
||||||
|
|
||||||
|
Inline-Kommentar funktioniert auch in E-Mails im Reintext-Format: Marker und eigener Text werden als reiner Text ohne Farben eingefügt. Das Add-on läuft auch in Betterbird.
|
||||||
|
|
||||||
|
Bekannte Grenzen
|
||||||
|
|
||||||
|
- Einfügen aus der Zwischenablage im Zitat teilt das Zitat nicht.
|
||||||
|
- Eingaben über ein Eingabe-Hilfsfenster (zum Beispiel für Japanisch) teilen das Zitat nicht.
|
||||||
|
- In Reintext-E-Mails gibt es keine Leerzeile nach dem Kommentar, und eine mit Enter im Zitat erzeugte leere Zeile bekommt keinen Marker.
|
||||||
|
|
||||||
|
Datenschutz: Inline-Kommentar sammelt und überträgt keine Daten. Deine Einstellungen bleiben im lokalen Speicher des Add-ons auf deinem Rechner.
|
||||||
|
|
||||||
|
Benötigt Thunderbird 128 oder neuer. Die Oberfläche gibt es auf Deutsch und Englisch.
|
||||||
|
|
||||||
|
Hinweis zur Entstehung: Teile dieses Add-ons, insbesondere die Dokumentation und Fehlerbehebungen, sind mit Hilfe des KI-Assistenten Claude (Anthropic) entstanden.
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
Inline Comment helps you answer an email point by point, right inside the quoted text. Reply to a message, click anywhere in the quote and start typing: the quote is split at that point and your own text appears in between, set apart in color and introduced by a marker such as [OH]: (your initials). The rest of the quote continues below your comment, so the recipient sees at a glance which sentence you are answering.
|
||||||
|
|
||||||
|
A reply then looks like this:
|
||||||
|
|
||||||
|
> Could you send me the documents by Friday?
|
||||||
|
[OH]: Yes, they will arrive tomorrow.
|
||||||
|
> And please attach the invoice.
|
||||||
|
|
||||||
|
How to use
|
||||||
|
|
||||||
|
- Click inside a quote and type. The quote is split, the marker and your text appear.
|
||||||
|
- Keep typing, also across several lines: as long as you stay in your comment, no new marker is added.
|
||||||
|
- Press Enter inside a quote first and then type: the empty line between the two parts of the quote gets the marker.
|
||||||
|
- Select quoted text and type to replace it with your comment.
|
||||||
|
- Clicking, selecting and copying inside a quote change nothing. Only a typed character splits it.
|
||||||
|
- Nested quotes (replies to replies) are split on all levels.
|
||||||
|
- Ctrl+Z undoes the split (with the default settings; press it twice if needed).
|
||||||
|
|
||||||
|
Toolbar button
|
||||||
|
|
||||||
|
The "Inline Comment" button in the toolbar of the compose window turns the feature on or off for the current email. A badge on the button shows "on" or "off".
|
||||||
|
|
||||||
|
Options
|
||||||
|
|
||||||
|
Open Add-ons and Themes, Inline Comment, Options:
|
||||||
|
|
||||||
|
- Marker template with the placeholders {initials}, {name}, {email}, {date} and {time}. Default: [{initials}]:
|
||||||
|
- Colors for marker and text, bold, italic and an optional background color.
|
||||||
|
- A blank line before or after the comment.
|
||||||
|
- Whether the add-on is active automatically in new emails.
|
||||||
|
- Separate settings for each sender identity, for example a different marker for another account.
|
||||||
|
- A preview that shows the result while you change the settings.
|
||||||
|
- Advanced: how the quote is split (by the editor, so Ctrl+Z works, or by the add-on as a fallback) and diagnostic output for troubleshooting.
|
||||||
|
|
||||||
|
The comment is formatted with inline styles only, so the marker and the colors also show up in other mail programs and in webmail.
|
||||||
|
|
||||||
|
Plain text and Betterbird
|
||||||
|
|
||||||
|
Inline Comment also works in plain-text emails: the marker and your text are inserted as plain text, without colors. The add-on runs in Betterbird as well.
|
||||||
|
|
||||||
|
Known limitations
|
||||||
|
|
||||||
|
- Pasting from the clipboard inside a quote does not split the quote.
|
||||||
|
- Input through an input method editor (for example for Japanese) does not split the quote.
|
||||||
|
- In plain-text emails there is no blank line after the comment, and an empty line created with Enter inside a quote does not get the marker.
|
||||||
|
|
||||||
|
Privacy: Inline Comment collects and transmits no data. Your settings stay in the add-on's local storage on your computer.
|
||||||
|
|
||||||
|
Requires Thunderbird 128 or later. The user interface is available in English and German.
|
||||||
|
|
||||||
|
Development note: parts of this add-on, in particular the documentation and bug fixes, were created with the help of the AI assistant Claude (Anthropic).
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
Inline Comment splits a quote in the compose window when the user types inside it and inserts the typed text with a marker such as [XX]: (initials of the sender identity). Source code: https://git.hassio-muc.de/Oliver_Herb/inline-comment (MPL-2.0).
|
||||||
|
|
||||||
|
Test steps
|
||||||
|
|
||||||
|
1. Install the add-on. The options page opens once after installation; it can be closed.
|
||||||
|
2. Reply to an HTML email that contains some quoted text (compose in HTML format).
|
||||||
|
3. Click in the middle of a sentence inside the quote and type a few characters.
|
||||||
|
4. Expected: the quote is split at the cursor. Between the two parts of the quote there is a new line that starts with the marker [XX]: (XX = initials of the sender identity) in blue, followed by the typed text; the cursor stays after the text. Typing on, also after Enter, adds no further marker.
|
||||||
|
5. Press Ctrl+Z (twice if needed): the comment disappears and the quote is whole again.
|
||||||
|
6. Click the "Inline Comment" button in the toolbar of the compose window: the badge changes to "off" and typing inside the quote behaves normally (no split). Click again: the badge shows "on" and the feature works again.
|
||||||
|
7. Open Add-ons and Themes, Inline Comment, Options. Change the marker template to {name}: and pick another marker color; the preview updates. Go back to the open compose window and type inside the quote: the new marker and color are used without restarting.
|
||||||
|
8. Plain text: hold Shift while clicking Reply (opens the reply in the other format) or switch the account to plain-text composition. Type inside the quote: the quote is split and the line starts with [XX]: as plain text, without a ">" in front.
|
||||||
|
|
||||||
|
Permissions
|
||||||
|
|
||||||
|
- compose: compose.getComposeDetails (sender identity and whether the message is plain text) and compose.onIdentityChanged (update the marker when the sender is changed). Together with "scripting", it is also required for scripting.compose.
|
||||||
|
- scripting: scripting.compose.registerScripts loads the compose script into new compose windows; scripting.executeScript injects it into compose windows that were already open when the add-on was installed or updated.
|
||||||
|
- storage: storage.local holds the settings and the optional per-identity profiles; storage.session holds the on/off state of each open compose window, because the Manifest V3 background script can be terminated at any time.
|
||||||
|
- accountsRead: identities.get reads the name and email address of the sender identity to render the marker (initials, name or email placeholder). The options page uses identities.list (fallback accounts.list) to offer per-identity profiles.
|
||||||
|
|
||||||
|
The add-on requests no host permissions and makes no network requests. No data is collected or transmitted.
|
||||||
|
|
||||||
|
Why document.execCommand("insertHTML") is used
|
||||||
|
|
||||||
|
The comment is inserted with document.execCommand("insertHTML") so that the insertion becomes part of the editor's undo history and the user can undo it with Ctrl+Z. Direct DOM changes would bypass the undo stack. The HTML string passed to insertHTML is never assembled from strings: createCommentNode() in src/lib/marker.js builds the element with createElement, setAttribute, textContent and createTextNode, and the caller serializes it with outerHTML. The marker text and the typed text only ever become text nodes (textContent or createTextNode). The style attribute only contains values from sanitized settings: colors must match /^#[0-9a-f]{6}$/i (sanitizeSettings() in src/lib/settings.js, otherwise the default color is used), and boolean options map to fixed keywords such as "bold" or "italic". The add-on does not assign to innerHTML or outerHTML and does not use insertAdjacentHTML or document.write; test/dom-sinks.test.js in the repository enforces this. Other editor commands used: insertParagraph (lets the editor split the quote like Enter does), insertText, delete and undo.
|
||||||
|
|
||||||
|
Code
|
||||||
|
|
||||||
|
- No remote code: all scripts are part of the package, nothing is loaded at runtime.
|
||||||
|
- No minification, no transpiling, no bundler: the package is a plain ZIP of the src/ folder of the repository plus the LICENSE file (scripts/build.sh).
|
||||||
|
- No third-party libraries in the package. Prettier, ESLint and jsdom are used only as development tools for formatting, linting and tests and are not shipped.
|
||||||
|
|
||||||
|
Linter: addons-linter reports MANIFEST_PERMISSIONS warnings for "compose" and "accountsRead". These are Thunderbird permissions unknown to the linter; the warnings are expected.
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
Datenschutzerklärung für das Thunderbird-Add-on Inline-Kommentar (Add-on-ID inline-comment@ih-engineering.de). Stand: 24. November 2026.
|
||||||
|
|
||||||
|
Kurz gesagt: Inline-Kommentar sammelt keine Daten und überträgt keine Daten. Alles, was das Add-on braucht, bleibt auf deinem Rechner.
|
||||||
|
|
||||||
|
Was das Add-on speichert
|
||||||
|
|
||||||
|
- Deine Einstellungen (Marker-Vorlage, Farben, Abstände und die übrigen Optionen) und, falls du sie anlegst, eigene Profile für einzelne Absender-Identitäten. Sie liegen im lokalen Speicher des Add-ons in deinem Thunderbird-Profil. Profile sind mit der internen Identitäts-ID von Thunderbird verknüpft; Namen und E-Mail-Adressen werden nicht gespeichert.
|
||||||
|
- Ob das Add-on in einem offenen Verfassen-Fenster an- oder ausgeschaltet ist. Das wird nur im Sitzungsspeicher gehalten und verworfen, sobald das Fenster geschlossen oder Thunderbird beendet wird.
|
||||||
|
- Wenn du das Add-on entfernst, werden die gespeicherten Daten gelöscht.
|
||||||
|
|
||||||
|
Was das Add-on liest
|
||||||
|
|
||||||
|
- Name und E-Mail-Adresse der Absender-Identität der E-Mail, die du gerade schreibst, nur um den Marker zu bilden (zum Beispiel deine Initialen). Auf der Einstellungsseite wird die Liste deiner Identitäten gelesen, damit du ein Profil auswählen kannst. Diese Angaben werden nicht gespeichert und verlassen deinen Rechner nicht.
|
||||||
|
- Im Verfassen-Fenster prüft das Add-on, ob der Cursor in einem Zitat steht, und fügt dort deinen Kommentar ein. Von den Angaben zur E-Mail, die du gerade schreibst, verwendet es nur die Absender-Identität und ob die E-Mail im Reintext-Format geschrieben wird. Darüber hinaus liest, speichert oder versendet es den Inhalt deiner E-Mails nicht.
|
||||||
|
|
||||||
|
Netzwerkzugriff
|
||||||
|
|
||||||
|
Das Add-on stellt keine Verbindungen ins Netz her. Es enthält keine Analyse-, Telemetrie- oder Tracking-Funktionen, nutzt keine Dienste Dritter und lädt keinen Code nach.
|
||||||
|
|
||||||
|
Kontakt
|
||||||
|
|
||||||
|
Fragen zu dieser Erklärung: https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
Privacy policy of the Thunderbird add-on Inline Comment (add-on ID inline-comment@ih-engineering.de). Last updated: November 24, 2026.
|
||||||
|
|
||||||
|
In short: Inline Comment collects no data and transmits no data. Everything it needs stays on your computer.
|
||||||
|
|
||||||
|
What the add-on stores
|
||||||
|
|
||||||
|
- Your settings (marker template, colors, spacing and the other options) and, if you create them, separate profiles for individual sender identities. They are kept in the add-on's local extension storage in your Thunderbird profile. Profiles are linked to Thunderbird's internal identity ID; names and email addresses are not stored.
|
||||||
|
- Whether the add-on is switched on or off in an open compose window. This is kept in session storage only and is discarded when the window is closed or Thunderbird quits.
|
||||||
|
- Removing the add-on deletes the stored data.
|
||||||
|
|
||||||
|
What the add-on reads
|
||||||
|
|
||||||
|
- The name and email address of the sender identity of the email you are writing, only to render the marker (for example your initials). On the options page, the list of your identities is read so that you can choose a profile. This information is not stored and does not leave your computer.
|
||||||
|
- In the compose window, the add-on checks whether the cursor is inside a quote and inserts your comment there. Of the details of the email being written, it uses only the sender identity and whether the email is in plain-text format. It does not otherwise read, store or send the content of your emails.
|
||||||
|
|
||||||
|
Network access
|
||||||
|
|
||||||
|
The add-on makes no network requests. It contains no analytics, telemetry or tracking, uses no third-party services and loads no remote code.
|
||||||
|
|
||||||
|
Contact
|
||||||
|
|
||||||
|
Questions about this policy: https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues
|
||||||
Generated
+1910
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,33 @@
|
|||||||
|
{
|
||||||
|
"name": "inline-comment",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"private": true,
|
||||||
|
"description": "Thunderbird/Betterbird add-on: typing inside a quoted block splits the quote and inserts your own comment with a marker such as \"[OH]:\"",
|
||||||
|
"author": "Oliver Herb",
|
||||||
|
"license": "MPL-2.0",
|
||||||
|
"homepage": "https://git.hassio-muc.de/Oliver_Herb/inline-comment",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://git.hassio-muc.de/Oliver_Herb/inline-comment.git"
|
||||||
|
},
|
||||||
|
"bugs": "https://git.hassio-muc.de/Oliver_Herb/inline-comment/issues",
|
||||||
|
"scripts": {
|
||||||
|
"test": "node --test \"test/**/*.test.js\"",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"format": "prettier --write .",
|
||||||
|
"format:check": "prettier --check .",
|
||||||
|
"check": "npm run format:check && npm run lint && npm test",
|
||||||
|
"build": "npm run check && bash scripts/build.sh"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=22"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@eslint/js": "^10.0.1",
|
||||||
|
"eslint": "^10.15.0",
|
||||||
|
"eslint-plugin-jsdoc": "^65.5.3",
|
||||||
|
"globals": "^17.14.0",
|
||||||
|
"jsdom": "^31.0.1",
|
||||||
|
"prettier": "^3.10.1"
|
||||||
|
}
|
||||||
|
}
|
||||||
Executable
+32
@@ -0,0 +1,32 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# 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/.
|
||||||
|
|
||||||
|
# Builds the add-on package: an XPI file (a ZIP archive of src/ plus LICENSE).
|
||||||
|
#
|
||||||
|
# Output: dist/inline-comment-<version>.xpi, where <version> is read from
|
||||||
|
# src/manifest.json. An existing file of the same name is replaced, and the
|
||||||
|
# path of the new file is printed on success.
|
||||||
|
#
|
||||||
|
# Usage: npm run build (runs the format check and the tests first)
|
||||||
|
# bash scripts/build.sh (packages only, without checks)
|
||||||
|
#
|
||||||
|
# Requires: bash, node and zip.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")/.."
|
||||||
|
VERSION="$(node -p "require('./src/manifest.json').version")"
|
||||||
|
OUT="dist/inline-comment-${VERSION}.xpi"
|
||||||
|
|
||||||
|
mkdir -p dist
|
||||||
|
rm -f "$OUT"
|
||||||
|
# Pack the contents of src/ so that manifest.json sits in the XPI root.
|
||||||
|
(cd src && zip -r -X -q "../$OUT" . -x '*.DS_Store' -x '*~')
|
||||||
|
# Ship the licence text in the XPI root next to manifest.json.
|
||||||
|
zip -X -q -j "$OUT" LICENSE
|
||||||
|
|
||||||
|
echo "$OUT"
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
{
|
||||||
|
"extensionName": {
|
||||||
|
"message": "Inline-Kommentar",
|
||||||
|
"description": "Name of the add-on (manifest, options page heading)."
|
||||||
|
},
|
||||||
|
"extensionDescription": {
|
||||||
|
"message": "Tippt man in einem Zitat, wird das Zitat geteilt und der eigene Text farbig mit Marker wie [OH]: abgesetzt.",
|
||||||
|
"description": "Short description of the add-on shown in the add-ons manager."
|
||||||
|
},
|
||||||
|
"actionTitle": {
|
||||||
|
"message": "Inline-Kommentar",
|
||||||
|
"description": "Default tooltip of the toolbar button in the compose window."
|
||||||
|
},
|
||||||
|
"badgeOn": {
|
||||||
|
"message": "an",
|
||||||
|
"description": "Badge on the compose toolbar button while the add-on is active. Keep it very short (max. 4 characters)."
|
||||||
|
},
|
||||||
|
"badgeOff": {
|
||||||
|
"message": "aus",
|
||||||
|
"description": "Badge on the compose toolbar button while the add-on is paused. Keep it very short (max. 4 characters)."
|
||||||
|
},
|
||||||
|
"buttonTitleActive": {
|
||||||
|
"message": "Inline-Kommentar: aktiv – klicken zum Pausieren",
|
||||||
|
"description": "Tooltip of the compose toolbar button while the add-on is active."
|
||||||
|
},
|
||||||
|
"buttonTitlePaused": {
|
||||||
|
"message": "Inline-Kommentar: pausiert – klicken zum Aktivieren",
|
||||||
|
"description": "Tooltip of the compose toolbar button while the add-on is paused."
|
||||||
|
},
|
||||||
|
"optionsTitle": {
|
||||||
|
"message": "Inline-Kommentar – Einstellungen",
|
||||||
|
"description": "Document title of the options page."
|
||||||
|
},
|
||||||
|
"optionsIntro": {
|
||||||
|
"message": "Tippst du in einem Zitat, teilt das Add-on das Zitat an dieser Stelle und setzt deinen Marker vor den eigenen Text. Im Verfassen-Fenster schaltet der Knopf „Inline-Kommentar“ die Funktion für diese E-Mail an oder aus.",
|
||||||
|
"description": "Introduction at the top of the options page. The quoted button name should match actionTitle."
|
||||||
|
},
|
||||||
|
"profileHeading": {
|
||||||
|
"message": "Profil",
|
||||||
|
"description": "Options page: heading of the section that selects the identity whose settings are edited."
|
||||||
|
},
|
||||||
|
"profileLabel": {
|
||||||
|
"message": "Einstellungen für",
|
||||||
|
"description": "Options page: label of the drop-down list of identities."
|
||||||
|
},
|
||||||
|
"ownProfileLabel": {
|
||||||
|
"message": "Eigene Einstellungen für diese Identität",
|
||||||
|
"description": "Options page: checkbox that gives the selected identity its own settings."
|
||||||
|
},
|
||||||
|
"profileAllIdentities": {
|
||||||
|
"message": "Alle Identitäten (Standard)",
|
||||||
|
"description": "Options page: first entry of the identity drop-down list (global settings)."
|
||||||
|
},
|
||||||
|
"profileOwnSettings": {
|
||||||
|
"message": "$IDENTITY$ – eigene Einstellungen",
|
||||||
|
"description": "Options page: entry of the identity drop-down list for an identity with its own settings.",
|
||||||
|
"placeholders": {
|
||||||
|
"identity": {
|
||||||
|
"content": "$1",
|
||||||
|
"example": "Jane Doe <jane.doe@example.com>"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"profileHintGlobal": {
|
||||||
|
"message": "Gilt für alle Identitäten ohne eigene Einstellungen.",
|
||||||
|
"description": "Options page: hint below the profile selection when the global settings are selected."
|
||||||
|
},
|
||||||
|
"profileHintOwn": {
|
||||||
|
"message": "Diese Identität nutzt eigene Einstellungen.",
|
||||||
|
"description": "Options page: hint below the profile selection for an identity with its own settings."
|
||||||
|
},
|
||||||
|
"profileHintInherited": {
|
||||||
|
"message": "Diese Identität nutzt die Einstellungen für alle Identitäten. Haken setzen, um sie anzupassen.",
|
||||||
|
"description": "Options page: hint below the profile selection for an identity without its own settings."
|
||||||
|
},
|
||||||
|
"behaviorHeading": {
|
||||||
|
"message": "Verhalten",
|
||||||
|
"description": "Options page: section heading."
|
||||||
|
},
|
||||||
|
"enabledByDefaultLabel": {
|
||||||
|
"message": "In neuen E-Mails automatisch aktiv",
|
||||||
|
"description": "Options page: checkbox label."
|
||||||
|
},
|
||||||
|
"markerHeading": {
|
||||||
|
"message": "Marker",
|
||||||
|
"description": "Options page: section heading for the marker (the prefix such as [OH]: in front of the own text)."
|
||||||
|
},
|
||||||
|
"templateLabel": {
|
||||||
|
"message": "Vorlage",
|
||||||
|
"description": "Options page: label of the marker template text field."
|
||||||
|
},
|
||||||
|
"placeholderChipsLabel": {
|
||||||
|
"message": "Platzhalter einfügen",
|
||||||
|
"description": "Options page: accessible name of the group of buttons that insert placeholders into the marker template."
|
||||||
|
},
|
||||||
|
"chipInitials": {
|
||||||
|
"message": "Initialen",
|
||||||
|
"description": "Options page: button that inserts the {initials} placeholder."
|
||||||
|
},
|
||||||
|
"chipName": {
|
||||||
|
"message": "Name",
|
||||||
|
"description": "Options page: button that inserts the {name} placeholder."
|
||||||
|
},
|
||||||
|
"chipEmail": {
|
||||||
|
"message": "E-Mail",
|
||||||
|
"description": "Options page: button that inserts the {email} placeholder."
|
||||||
|
},
|
||||||
|
"chipDate": {
|
||||||
|
"message": "Datum",
|
||||||
|
"description": "Options page: button that inserts the {date} placeholder."
|
||||||
|
},
|
||||||
|
"chipTime": {
|
||||||
|
"message": "Uhrzeit",
|
||||||
|
"description": "Options page: button that inserts the {time} placeholder."
|
||||||
|
},
|
||||||
|
"appearanceHeading": {
|
||||||
|
"message": "Darstellung",
|
||||||
|
"description": "Options page: section heading for colors and font styles."
|
||||||
|
},
|
||||||
|
"markerColorLabel": {
|
||||||
|
"message": "Farbe Marker",
|
||||||
|
"description": "Options page: label of the marker color picker."
|
||||||
|
},
|
||||||
|
"textColorLabel": {
|
||||||
|
"message": "Farbe Text",
|
||||||
|
"description": "Options page: label of the comment text color picker."
|
||||||
|
},
|
||||||
|
"highlightColorLabel": {
|
||||||
|
"message": "Hintergrund",
|
||||||
|
"description": "Options page: label of the background color picker."
|
||||||
|
},
|
||||||
|
"boldLabel": {
|
||||||
|
"message": "fett",
|
||||||
|
"description": "Options page: checkbox label for bold font."
|
||||||
|
},
|
||||||
|
"italicLabel": {
|
||||||
|
"message": "kursiv",
|
||||||
|
"description": "Options page: checkbox label for italic font."
|
||||||
|
},
|
||||||
|
"highlightLabel": {
|
||||||
|
"message": "hinterlegen",
|
||||||
|
"description": "Options page: checkbox label that enables the background color."
|
||||||
|
},
|
||||||
|
"spacingHeading": {
|
||||||
|
"message": "Abstände",
|
||||||
|
"description": "Options page: section heading."
|
||||||
|
},
|
||||||
|
"blankLineBeforeLabel": {
|
||||||
|
"message": "Leerzeile vor dem Kommentar",
|
||||||
|
"description": "Options page: checkbox label."
|
||||||
|
},
|
||||||
|
"blankLineAfterLabel": {
|
||||||
|
"message": "Leerzeile nach dem Kommentar",
|
||||||
|
"description": "Options page: checkbox label."
|
||||||
|
},
|
||||||
|
"previewHeading": {
|
||||||
|
"message": "Vorschau",
|
||||||
|
"description": "Options page: section heading."
|
||||||
|
},
|
||||||
|
"previewQuoteQuestion": {
|
||||||
|
"message": "Können Sie mir die Unterlagen bis Freitag schicken?",
|
||||||
|
"description": "Options page preview: first quoted line of the sample email."
|
||||||
|
},
|
||||||
|
"previewCommentStart": {
|
||||||
|
"message": "Ja,",
|
||||||
|
"description": "Options page preview: first word(s) of the sample comment, shown right after the marker."
|
||||||
|
},
|
||||||
|
"previewCommentRest": {
|
||||||
|
"message": "kommen morgen.",
|
||||||
|
"description": "Options page preview: rest of the sample comment, appended after previewCommentStart and a space."
|
||||||
|
},
|
||||||
|
"previewQuoteRequest": {
|
||||||
|
"message": "Und bitte die Rechnung beilegen.",
|
||||||
|
"description": "Options page preview: second quoted line of the sample email."
|
||||||
|
},
|
||||||
|
"previewSampleName": {
|
||||||
|
"message": "Max Mustermann",
|
||||||
|
"description": "Options page preview: sample sender name, used only when no identity exists."
|
||||||
|
},
|
||||||
|
"previewSampleEmail": {
|
||||||
|
"message": "max.mustermann@example.com",
|
||||||
|
"description": "Options page preview: sample sender address, used only when no identity exists."
|
||||||
|
},
|
||||||
|
"advancedSummary": {
|
||||||
|
"message": "Erweitert",
|
||||||
|
"description": "Options page: title of the collapsible advanced section."
|
||||||
|
},
|
||||||
|
"splitModeLabel": {
|
||||||
|
"message": "Zitat teilen",
|
||||||
|
"description": "Options page: label of the drop-down list that selects how the quote is split."
|
||||||
|
},
|
||||||
|
"splitModeNative": {
|
||||||
|
"message": "durch den Editor (Strg+Z funktioniert)",
|
||||||
|
"description": "Options page: split mode option, the mail editor splits the quote."
|
||||||
|
},
|
||||||
|
"splitModeManual": {
|
||||||
|
"message": "durch das Add-on (Notlösung)",
|
||||||
|
"description": "Options page: split mode option, the add-on splits the quote itself."
|
||||||
|
},
|
||||||
|
"debugLabel": {
|
||||||
|
"message": "Diagnose-Ausgaben in der Fehlerkonsole",
|
||||||
|
"description": "Options page: checkbox label that enables debug logging."
|
||||||
|
},
|
||||||
|
"resetButton": {
|
||||||
|
"message": "Auf Standard zurücksetzen",
|
||||||
|
"description": "Options page: button that resets the shown settings."
|
||||||
|
},
|
||||||
|
"resetConfirm": {
|
||||||
|
"message": "Wirklich zurücksetzen?",
|
||||||
|
"description": "Options page: reset button text after the first click, asking for confirmation."
|
||||||
|
},
|
||||||
|
"statusSaved": {
|
||||||
|
"message": "Gespeichert",
|
||||||
|
"description": "Options page: status after the settings were saved."
|
||||||
|
},
|
||||||
|
"statusSaveFailed": {
|
||||||
|
"message": "Speichern fehlgeschlagen",
|
||||||
|
"description": "Options page: status when the settings could not be saved."
|
||||||
|
},
|
||||||
|
"statusLoadFailed": {
|
||||||
|
"message": "Einstellungen konnten nicht geladen werden",
|
||||||
|
"description": "Options page: status when the settings could not be loaded."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,224 @@
|
|||||||
|
{
|
||||||
|
"extensionName": {
|
||||||
|
"message": "Inline Comment",
|
||||||
|
"description": "Name of the add-on (manifest, options page heading)."
|
||||||
|
},
|
||||||
|
"extensionDescription": {
|
||||||
|
"message": "Type inside a quoted reply: the quote is split and your own text is set apart in color with a marker such as [OH]:.",
|
||||||
|
"description": "Short description of the add-on shown in the add-ons manager."
|
||||||
|
},
|
||||||
|
"actionTitle": {
|
||||||
|
"message": "Inline Comment",
|
||||||
|
"description": "Default tooltip of the toolbar button in the compose window."
|
||||||
|
},
|
||||||
|
"badgeOn": {
|
||||||
|
"message": "on",
|
||||||
|
"description": "Badge on the compose toolbar button while the add-on is active. Keep it very short (max. 4 characters)."
|
||||||
|
},
|
||||||
|
"badgeOff": {
|
||||||
|
"message": "off",
|
||||||
|
"description": "Badge on the compose toolbar button while the add-on is paused. Keep it very short (max. 4 characters)."
|
||||||
|
},
|
||||||
|
"buttonTitleActive": {
|
||||||
|
"message": "Inline Comment: active – click to pause",
|
||||||
|
"description": "Tooltip of the compose toolbar button while the add-on is active."
|
||||||
|
},
|
||||||
|
"buttonTitlePaused": {
|
||||||
|
"message": "Inline Comment: paused – click to activate",
|
||||||
|
"description": "Tooltip of the compose toolbar button while the add-on is paused."
|
||||||
|
},
|
||||||
|
"optionsTitle": {
|
||||||
|
"message": "Inline Comment – Settings",
|
||||||
|
"description": "Document title of the options page."
|
||||||
|
},
|
||||||
|
"optionsIntro": {
|
||||||
|
"message": "When you type inside a quote, the add-on splits the quote at that point and puts your marker in front of your own text. In the compose window, the “Inline Comment” button turns the feature on or off for that email.",
|
||||||
|
"description": "Introduction at the top of the options page. The quoted button name should match actionTitle."
|
||||||
|
},
|
||||||
|
"profileHeading": {
|
||||||
|
"message": "Profile",
|
||||||
|
"description": "Options page: heading of the section that selects the identity whose settings are edited."
|
||||||
|
},
|
||||||
|
"profileLabel": {
|
||||||
|
"message": "Settings for",
|
||||||
|
"description": "Options page: label of the drop-down list of identities."
|
||||||
|
},
|
||||||
|
"ownProfileLabel": {
|
||||||
|
"message": "Own settings for this identity",
|
||||||
|
"description": "Options page: checkbox that gives the selected identity its own settings."
|
||||||
|
},
|
||||||
|
"profileAllIdentities": {
|
||||||
|
"message": "All identities (default)",
|
||||||
|
"description": "Options page: first entry of the identity drop-down list (global settings)."
|
||||||
|
},
|
||||||
|
"profileOwnSettings": {
|
||||||
|
"message": "$IDENTITY$ – own settings",
|
||||||
|
"description": "Options page: entry of the identity drop-down list for an identity with its own settings.",
|
||||||
|
"placeholders": {
|
||||||
|
"identity": {
|
||||||
|
"content": "$1",
|
||||||
|
"example": "Jane Doe <jane.doe@example.com>"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"profileHintGlobal": {
|
||||||
|
"message": "Applies to all identities without their own settings.",
|
||||||
|
"description": "Options page: hint below the profile selection when the global settings are selected."
|
||||||
|
},
|
||||||
|
"profileHintOwn": {
|
||||||
|
"message": "This identity uses its own settings.",
|
||||||
|
"description": "Options page: hint below the profile selection for an identity with its own settings."
|
||||||
|
},
|
||||||
|
"profileHintInherited": {
|
||||||
|
"message": "This identity uses the settings for all identities. Check the box to customize them.",
|
||||||
|
"description": "Options page: hint below the profile selection for an identity without its own settings."
|
||||||
|
},
|
||||||
|
"behaviorHeading": {
|
||||||
|
"message": "Behavior",
|
||||||
|
"description": "Options page: section heading."
|
||||||
|
},
|
||||||
|
"enabledByDefaultLabel": {
|
||||||
|
"message": "Active automatically in new emails",
|
||||||
|
"description": "Options page: checkbox label."
|
||||||
|
},
|
||||||
|
"markerHeading": {
|
||||||
|
"message": "Marker",
|
||||||
|
"description": "Options page: section heading for the marker (the prefix such as [OH]: in front of the own text)."
|
||||||
|
},
|
||||||
|
"templateLabel": {
|
||||||
|
"message": "Template",
|
||||||
|
"description": "Options page: label of the marker template text field."
|
||||||
|
},
|
||||||
|
"placeholderChipsLabel": {
|
||||||
|
"message": "Insert placeholder",
|
||||||
|
"description": "Options page: accessible name of the group of buttons that insert placeholders into the marker template."
|
||||||
|
},
|
||||||
|
"chipInitials": {
|
||||||
|
"message": "Initials",
|
||||||
|
"description": "Options page: button that inserts the {initials} placeholder."
|
||||||
|
},
|
||||||
|
"chipName": {
|
||||||
|
"message": "Name",
|
||||||
|
"description": "Options page: button that inserts the {name} placeholder."
|
||||||
|
},
|
||||||
|
"chipEmail": {
|
||||||
|
"message": "Email",
|
||||||
|
"description": "Options page: button that inserts the {email} placeholder."
|
||||||
|
},
|
||||||
|
"chipDate": {
|
||||||
|
"message": "Date",
|
||||||
|
"description": "Options page: button that inserts the {date} placeholder."
|
||||||
|
},
|
||||||
|
"chipTime": {
|
||||||
|
"message": "Time",
|
||||||
|
"description": "Options page: button that inserts the {time} placeholder."
|
||||||
|
},
|
||||||
|
"appearanceHeading": {
|
||||||
|
"message": "Appearance",
|
||||||
|
"description": "Options page: section heading for colors and font styles."
|
||||||
|
},
|
||||||
|
"markerColorLabel": {
|
||||||
|
"message": "Marker color",
|
||||||
|
"description": "Options page: label of the marker color picker."
|
||||||
|
},
|
||||||
|
"textColorLabel": {
|
||||||
|
"message": "Text color",
|
||||||
|
"description": "Options page: label of the comment text color picker."
|
||||||
|
},
|
||||||
|
"highlightColorLabel": {
|
||||||
|
"message": "Background",
|
||||||
|
"description": "Options page: label of the background color picker."
|
||||||
|
},
|
||||||
|
"boldLabel": {
|
||||||
|
"message": "bold",
|
||||||
|
"description": "Options page: checkbox label for bold font."
|
||||||
|
},
|
||||||
|
"italicLabel": {
|
||||||
|
"message": "italic",
|
||||||
|
"description": "Options page: checkbox label for italic font."
|
||||||
|
},
|
||||||
|
"highlightLabel": {
|
||||||
|
"message": "highlight",
|
||||||
|
"description": "Options page: checkbox label that enables the background color."
|
||||||
|
},
|
||||||
|
"spacingHeading": {
|
||||||
|
"message": "Spacing",
|
||||||
|
"description": "Options page: section heading."
|
||||||
|
},
|
||||||
|
"blankLineBeforeLabel": {
|
||||||
|
"message": "Blank line before the comment",
|
||||||
|
"description": "Options page: checkbox label."
|
||||||
|
},
|
||||||
|
"blankLineAfterLabel": {
|
||||||
|
"message": "Blank line after the comment",
|
||||||
|
"description": "Options page: checkbox label."
|
||||||
|
},
|
||||||
|
"previewHeading": {
|
||||||
|
"message": "Preview",
|
||||||
|
"description": "Options page: section heading."
|
||||||
|
},
|
||||||
|
"previewQuoteQuestion": {
|
||||||
|
"message": "Could you send me the documents by Friday?",
|
||||||
|
"description": "Options page preview: first quoted line of the sample email."
|
||||||
|
},
|
||||||
|
"previewCommentStart": {
|
||||||
|
"message": "Yes,",
|
||||||
|
"description": "Options page preview: first word(s) of the sample comment, shown right after the marker."
|
||||||
|
},
|
||||||
|
"previewCommentRest": {
|
||||||
|
"message": "they will arrive tomorrow.",
|
||||||
|
"description": "Options page preview: rest of the sample comment, appended after previewCommentStart and a space."
|
||||||
|
},
|
||||||
|
"previewQuoteRequest": {
|
||||||
|
"message": "And please attach the invoice.",
|
||||||
|
"description": "Options page preview: second quoted line of the sample email."
|
||||||
|
},
|
||||||
|
"previewSampleName": {
|
||||||
|
"message": "Jane Doe",
|
||||||
|
"description": "Options page preview: sample sender name, used only when no identity exists."
|
||||||
|
},
|
||||||
|
"previewSampleEmail": {
|
||||||
|
"message": "jane.doe@example.com",
|
||||||
|
"description": "Options page preview: sample sender address, used only when no identity exists."
|
||||||
|
},
|
||||||
|
"advancedSummary": {
|
||||||
|
"message": "Advanced",
|
||||||
|
"description": "Options page: title of the collapsible advanced section."
|
||||||
|
},
|
||||||
|
"splitModeLabel": {
|
||||||
|
"message": "Split the quote",
|
||||||
|
"description": "Options page: label of the drop-down list that selects how the quote is split."
|
||||||
|
},
|
||||||
|
"splitModeNative": {
|
||||||
|
"message": "by the editor (Ctrl+Z works)",
|
||||||
|
"description": "Options page: split mode option, the mail editor splits the quote."
|
||||||
|
},
|
||||||
|
"splitModeManual": {
|
||||||
|
"message": "by the add-on (fallback)",
|
||||||
|
"description": "Options page: split mode option, the add-on splits the quote itself."
|
||||||
|
},
|
||||||
|
"debugLabel": {
|
||||||
|
"message": "Diagnostic output in the error console",
|
||||||
|
"description": "Options page: checkbox label that enables debug logging."
|
||||||
|
},
|
||||||
|
"resetButton": {
|
||||||
|
"message": "Reset to defaults",
|
||||||
|
"description": "Options page: button that resets the shown settings."
|
||||||
|
},
|
||||||
|
"resetConfirm": {
|
||||||
|
"message": "Really reset?",
|
||||||
|
"description": "Options page: reset button text after the first click, asking for confirmation."
|
||||||
|
},
|
||||||
|
"statusSaved": {
|
||||||
|
"message": "Saved",
|
||||||
|
"description": "Options page: status after the settings were saved."
|
||||||
|
},
|
||||||
|
"statusSaveFailed": {
|
||||||
|
"message": "Saving failed",
|
||||||
|
"description": "Options page: status when the settings could not be saved."
|
||||||
|
},
|
||||||
|
"statusLoadFailed": {
|
||||||
|
"message": "Settings could not be loaded",
|
||||||
|
"description": "Options page: status when the settings could not be loaded."
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,432 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Background script of the add-on.
|
||||||
|
*
|
||||||
|
* Runs in: the extension's background context, as a Manifest V3 event page.
|
||||||
|
* The application may unload it at any time and loads it again when one of
|
||||||
|
* the events registered below fires. It does not run in the compose editor,
|
||||||
|
* on the options page or in the Node tests.
|
||||||
|
*
|
||||||
|
* Responsibilities:
|
||||||
|
* - register the compose script and inject it into compose windows that
|
||||||
|
* were already open when the add-on was installed or updated
|
||||||
|
* - keep the on/off state per compose tab (toolbar button "Inline Comment")
|
||||||
|
* - give the compose script its configuration and send it a new one
|
||||||
|
* whenever the state, the sender identity or the saved settings change
|
||||||
|
*
|
||||||
|
* Loaded before this file (order in "background.scripts" of manifest.json):
|
||||||
|
* lib/settings.js and lib/marker.js, which fill globalThis.InlineComment.
|
||||||
|
* Only lib/settings.js is required here: this file uses STORAGE_KEY,
|
||||||
|
* COMPOSE_SCRIPT_FILES, normalizeStore and resolveSettings from it and
|
||||||
|
* nothing from lib/marker.js.
|
||||||
|
*
|
||||||
|
* Data flow:
|
||||||
|
* 1. The compose script (compose/compose.js) asks with
|
||||||
|
* { type: "ic:getConfig" } via runtime.sendMessage, on load and
|
||||||
|
* whenever its window gets focus.
|
||||||
|
* 2. buildConfig() combines the compose details (sender identity,
|
||||||
|
* plain-text mode), the identity's name and e-mail address, the
|
||||||
|
* settings that apply to this identity (from storage.local) and the
|
||||||
|
* saved on/off state of the tab (from storage.session, or an in-memory
|
||||||
|
* fallback) into
|
||||||
|
* { active, isPlainText, settings, identity: { name, email } }.
|
||||||
|
* 3. That object is the reply. Later changes are pushed to the tab with
|
||||||
|
* tabs.sendMessage as { type: "ic:config", config }.
|
||||||
|
* 4. The badge and tooltip of the toolbar button mirror config.active.
|
||||||
|
*/
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
/** WebExtension API namespace: Thunderbird's `messenger`, else `browser`. */
|
||||||
|
const api = globalThis.messenger || globalThis.browser;
|
||||||
|
/** Shared library namespace, filled by lib/settings.js and lib/marker.js. */
|
||||||
|
const IC = globalThis.InlineComment;
|
||||||
|
/** ID under which the compose script is registered with scripting.compose. */
|
||||||
|
const SCRIPT_ID = "inline-comment-compose";
|
||||||
|
/** Prefix for console output, so messages of this add-on are easy to find. */
|
||||||
|
const LOG_PREFIX = "[Inline Comment]";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Looks up a translated UI string from _locales in the current UI language.
|
||||||
|
* @param {string} key - Message name in messages.json, e.g. "badgeOn".
|
||||||
|
* @returns {string} The translated text, or an empty string if the key is
|
||||||
|
* unknown.
|
||||||
|
*/
|
||||||
|
function msg(key) {
|
||||||
|
return api.i18n.getMessage(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fallback store for the per-tab on/off state when storage.session is not
|
||||||
|
* available. It lives only in this instance of the background script, so
|
||||||
|
* the state is lost whenever the event page is unloaded.
|
||||||
|
* @type {Map<string, boolean>}
|
||||||
|
*/
|
||||||
|
const memoryState = new Map();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the storage key for the on/off state of one compose tab. The same
|
||||||
|
* key is used in storage.session and in the memoryState fallback.
|
||||||
|
* @param {number} tabId - ID of the compose tab.
|
||||||
|
* @returns {string} The key, e.g. "active:42".
|
||||||
|
*/
|
||||||
|
function stateKey(tabId) {
|
||||||
|
return `active:${tabId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the saved on/off state of a compose tab. Uses storage.session when
|
||||||
|
* the API provides it, because that survives an unload of the event page
|
||||||
|
* (it is only cleared when the application quits); otherwise the in-memory
|
||||||
|
* fallback.
|
||||||
|
* @param {number} tabId - ID of the compose tab.
|
||||||
|
* @returns {Promise<boolean|undefined>} The saved state, or undefined if none
|
||||||
|
* is saved for this tab (the toolbar button has not been clicked yet, or
|
||||||
|
* the in-memory fallback was lost with the event page).
|
||||||
|
*/
|
||||||
|
async function getTabState(tabId) {
|
||||||
|
const key = stateKey(tabId);
|
||||||
|
if (api.storage.session) {
|
||||||
|
const result = await api.storage.session.get(key);
|
||||||
|
return result[key];
|
||||||
|
}
|
||||||
|
return memoryState.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves the on/off state of a compose tab.
|
||||||
|
* Side effect: writes to storage.session, or to memoryState as fallback.
|
||||||
|
* @param {number} tabId - ID of the compose tab.
|
||||||
|
* @param {boolean} active - True if the add-on is switched on for this tab.
|
||||||
|
* @returns {Promise<void>} Resolves when the state is stored.
|
||||||
|
*/
|
||||||
|
async function setTabState(tabId, active) {
|
||||||
|
const key = stateKey(tabId);
|
||||||
|
if (api.storage.session) {
|
||||||
|
await api.storage.session.set({ [key]: active });
|
||||||
|
} else {
|
||||||
|
memoryState.set(key, active);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes the saved on/off state of a tab, so that no entries for closed
|
||||||
|
* tabs pile up. Removing a key that does not exist is harmless.
|
||||||
|
* Side effect: removes the key from storage.session or memoryState.
|
||||||
|
* @param {number} tabId - ID of the tab.
|
||||||
|
* @returns {Promise<void>} Resolves when the entry is removed.
|
||||||
|
*/
|
||||||
|
async function clearTabState(tabId) {
|
||||||
|
const key = stateKey(tabId);
|
||||||
|
if (api.storage.session) {
|
||||||
|
await api.storage.session.remove(key);
|
||||||
|
} else {
|
||||||
|
memoryState.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the saved settings of all profiles from storage.local and brings
|
||||||
|
* them into the expected shape: missing or invalid values become defaults
|
||||||
|
* and identity profiles that are not objects are dropped.
|
||||||
|
* @returns {Promise<{global: object, identities: Record<string, object>}>}
|
||||||
|
* The normalized store (see normalizeStore in lib/settings.js).
|
||||||
|
*/
|
||||||
|
async function loadStore() {
|
||||||
|
const result = await api.storage.local.get(IC.STORAGE_KEY);
|
||||||
|
return IC.normalizeStore(result[IC.STORAGE_KEY]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lists all open compose tabs in all windows.
|
||||||
|
* @returns {Promise<Array<object>>} The tabs.Tab objects whose type is
|
||||||
|
* "messageCompose".
|
||||||
|
*/
|
||||||
|
async function composeTabs() {
|
||||||
|
const tabs = await api.tabs.query({});
|
||||||
|
return tabs.filter((tab) => tab.type === "messageCompose");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registers the compose script (COMPOSE_SCRIPT_FILES, in this order) for
|
||||||
|
* compose windows opened from now on, unless a script with SCRIPT_ID is
|
||||||
|
* already registered. It runs on every load of the background script, on
|
||||||
|
* startup and after install or update; the check makes repeated calls
|
||||||
|
* harmless.
|
||||||
|
* Side effect: registers a compose script via scripting.compose.
|
||||||
|
* @returns {Promise<void>} Resolves when done; errors are logged as a
|
||||||
|
* warning, not thrown.
|
||||||
|
*/
|
||||||
|
async function ensureComposeScript() {
|
||||||
|
try {
|
||||||
|
const existing = await api.scripting.compose.getRegisteredScripts({
|
||||||
|
ids: [SCRIPT_ID],
|
||||||
|
});
|
||||||
|
if (existing.length > 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await api.scripting.compose.registerScripts([
|
||||||
|
{
|
||||||
|
id: SCRIPT_ID,
|
||||||
|
js: [...IC.COMPOSE_SCRIPT_FILES],
|
||||||
|
runAt: "document_idle",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
} catch (error) {
|
||||||
|
// Any failure is only logged. The expected one: when several triggers run
|
||||||
|
// at the same time (e.g. the top-level call and onStartup), another call
|
||||||
|
// may have registered SCRIPT_ID after the check above.
|
||||||
|
console.warn(LOG_PREFIX, "Registering the compose script:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Injects the compose script into every compose tab that is already open.
|
||||||
|
* Registered scripts only apply to compose windows opened later, so
|
||||||
|
* without this step windows that were open during install or update would
|
||||||
|
* not get the add-on until they are reopened. Injecting twice is safe,
|
||||||
|
* because compose/compose.js ignores a second load in the same window.
|
||||||
|
* Side effect: runs scripting.executeScript in each compose tab, one after
|
||||||
|
* another; a failure in one tab is logged and does not stop the others.
|
||||||
|
* @returns {Promise<void>} Resolves when all tabs have been tried.
|
||||||
|
*/
|
||||||
|
async function injectIntoOpenComposeTabs() {
|
||||||
|
for (const tab of await composeTabs()) {
|
||||||
|
try {
|
||||||
|
await api.scripting.executeScript({
|
||||||
|
target: { tabId: tab.id },
|
||||||
|
files: [...IC.COMPOSE_SCRIPT_FILES],
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(
|
||||||
|
LOG_PREFIX,
|
||||||
|
`Injecting into compose tab ${tab.id} failed:`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the configuration that the compose script of one tab works with.
|
||||||
|
* Reads the compose details (sender identity, plain-text mode), the
|
||||||
|
* identity's name and address, the settings that apply to this identity
|
||||||
|
* (its own profile or the global settings, see resolveSettings) and the
|
||||||
|
* saved on/off state. Without a saved state, enabledByDefault of those
|
||||||
|
* settings applies. Without a sender identity, the global settings apply and
|
||||||
|
* name and email are empty strings. If the identity cannot be read, a
|
||||||
|
* warning is logged, name and email are empty strings and the settings are
|
||||||
|
* still chosen by the identity's ID.
|
||||||
|
* @param {number} tabId - ID of the compose tab.
|
||||||
|
* @returns {Promise<{active: boolean, isPlainText: boolean, settings: object,
|
||||||
|
* identity: {name: string, email: string}}>} The configuration as
|
||||||
|
* compose/compose.js expects it. Rejects if reading the compose details or
|
||||||
|
* the storage fails.
|
||||||
|
*/
|
||||||
|
async function buildConfig(tabId) {
|
||||||
|
const details = await api.compose.getComposeDetails(tabId);
|
||||||
|
const identityId = details.identityId || null;
|
||||||
|
let identity = null;
|
||||||
|
if (identityId) {
|
||||||
|
try {
|
||||||
|
identity = await api.identities.get(identityId);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(LOG_PREFIX, "Identity not readable:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const settings = IC.resolveSettings(await loadStore(), identityId);
|
||||||
|
const saved = await getTabState(tabId);
|
||||||
|
return {
|
||||||
|
active: typeof saved === "boolean" ? saved : settings.enabledByDefault,
|
||||||
|
isPlainText: Boolean(details.isPlainText),
|
||||||
|
settings,
|
||||||
|
identity: {
|
||||||
|
name: (identity && identity.name) || "",
|
||||||
|
email: (identity && identity.email) || "",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shows the on/off state on the toolbar button of one compose tab: badge
|
||||||
|
* text ("on"/"off" in the UI language), badge color (green when on, grey
|
||||||
|
* when off) and tooltip. All three are set per tab, so every compose window
|
||||||
|
* shows its own state.
|
||||||
|
* Side effect: changes the composeAction of this tab.
|
||||||
|
* @param {number} tabId - ID of the compose tab.
|
||||||
|
* @param {boolean} active - True if the add-on is switched on for this tab.
|
||||||
|
* @returns {Promise<void>} Resolves when the button is updated; errors are
|
||||||
|
* logged as a warning, not thrown.
|
||||||
|
*/
|
||||||
|
async function updateButton(tabId, active) {
|
||||||
|
try {
|
||||||
|
await api.composeAction.setBadgeText({
|
||||||
|
tabId,
|
||||||
|
text: active ? msg("badgeOn") : msg("badgeOff"),
|
||||||
|
});
|
||||||
|
await api.composeAction.setBadgeBackgroundColor({
|
||||||
|
tabId,
|
||||||
|
color: active ? "#2e7d32" : "#757575",
|
||||||
|
});
|
||||||
|
await api.composeAction.setTitle({
|
||||||
|
tabId,
|
||||||
|
title: active ? msg("buttonTitleActive") : msg("buttonTitlePaused"),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(LOG_PREFIX, "Button not updated:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rebuilds the configuration of one compose tab, updates its toolbar button
|
||||||
|
* and sends the configuration to the tab's compose script as
|
||||||
|
* { type: "ic:config", config }. Used whenever something changes after the
|
||||||
|
* compose script has fetched its configuration (button click, identity
|
||||||
|
* change, saved settings).
|
||||||
|
* Side effects: composeAction of the tab, message to the tab.
|
||||||
|
* @param {number} tabId - ID of the compose tab.
|
||||||
|
* @returns {Promise<void>} Resolves when done; failures are logged at debug
|
||||||
|
* level only, not thrown.
|
||||||
|
*/
|
||||||
|
async function pushConfig(tabId) {
|
||||||
|
try {
|
||||||
|
const config = await buildConfig(tabId);
|
||||||
|
await updateButton(tabId, config.active);
|
||||||
|
await api.tabs.sendMessage(tabId, { type: "ic:config", config });
|
||||||
|
} catch (error) {
|
||||||
|
// Expected for tabs without a loaded compose script (e.g. one that was
|
||||||
|
// just closed), so this is only debug output.
|
||||||
|
console.debug(
|
||||||
|
LOG_PREFIX,
|
||||||
|
`Configuration not delivered to tab ${tabId}:`,
|
||||||
|
error,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sends a fresh configuration to every open compose tab, one after another,
|
||||||
|
* via pushConfig (which also updates each tab's toolbar button). Each tab
|
||||||
|
* gets its own configuration, because tabs can use different sender
|
||||||
|
* identities and therefore different settings profiles.
|
||||||
|
* @returns {Promise<void>} Resolves when all tabs have been handled; rejects
|
||||||
|
* only if the open tabs cannot be listed.
|
||||||
|
*/
|
||||||
|
async function pushToAllComposeTabs() {
|
||||||
|
for (const tab of await composeTabs()) {
|
||||||
|
await pushConfig(tab.id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// All listeners are registered synchronously at the top level, so that the
|
||||||
|
// application wakes the event page up for these events after an unload.
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Answers the compose script's request for its configuration. Handles only
|
||||||
|
* { type: "ic:getConfig" } sent from a tab; for every other message it
|
||||||
|
* returns undefined, so this listener sends no reply to it.
|
||||||
|
* Side effect: also updates the toolbar button of the sending tab on every
|
||||||
|
* request (on load and on window focus), so the badge is right as soon as
|
||||||
|
* the compose script has loaded.
|
||||||
|
* @param {object} message - The message sent with runtime.sendMessage.
|
||||||
|
* @param {object} sender - Information about the sender; sender.tab is the
|
||||||
|
* compose tab.
|
||||||
|
* @returns {Promise<object>|undefined} A promise for the configuration (see
|
||||||
|
* buildConfig), which becomes the reply; undefined if not handled. If
|
||||||
|
* buildConfig rejects, the sender's runtime.sendMessage rejects too.
|
||||||
|
*/
|
||||||
|
api.runtime.onMessage.addListener((message, sender) => {
|
||||||
|
if (!message || message.type !== "ic:getConfig" || !sender.tab) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const tabId = sender.tab.id;
|
||||||
|
return buildConfig(tabId).then(async (config) => {
|
||||||
|
await updateButton(tabId, config.active);
|
||||||
|
return config;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Toolbar button clicked: switches the add-on on or off for this compose
|
||||||
|
* tab. Takes the current state from buildConfig (saved state, else
|
||||||
|
* enabledByDefault), saves the opposite and pushes the new configuration to
|
||||||
|
* the tab, which also updates the button.
|
||||||
|
* Side effects: storage.session (or memoryState), button, message to the
|
||||||
|
* tab.
|
||||||
|
* @param {object} tab - The compose tab (tabs.Tab) whose button was clicked.
|
||||||
|
* @returns {Promise<void>} Resolves when the new state has been pushed.
|
||||||
|
*/
|
||||||
|
api.composeAction.onClicked.addListener(async (tab) => {
|
||||||
|
const config = await buildConfig(tab.id);
|
||||||
|
await setTabState(tab.id, !config.active);
|
||||||
|
await pushConfig(tab.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sender identity changed in a compose tab: sends a new configuration,
|
||||||
|
* because the marker values (name, email, initials) and the settings
|
||||||
|
* profile depend on the identity. A state saved by a button click stays;
|
||||||
|
* otherwise enabledByDefault of the new profile applies.
|
||||||
|
* @param {object} tab - The compose tab (tabs.Tab).
|
||||||
|
* @returns {Promise<void>} The pending pushConfig call.
|
||||||
|
*/
|
||||||
|
api.compose.onIdentityChanged.addListener((tab) => pushConfig(tab.id));
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Settings saved (by the options page): sends the new configuration to all
|
||||||
|
* open compose tabs, so the change applies without reopening them. Reacts
|
||||||
|
* only to STORAGE_KEY in storage.local; changes in other areas, such as the
|
||||||
|
* per-tab state in storage.session, are ignored. The push is started
|
||||||
|
* without waiting for it.
|
||||||
|
* @param {Record<string, {oldValue?: unknown, newValue?: unknown}>} changes -
|
||||||
|
* Changed keys with their old and new values.
|
||||||
|
* @param {string} area - Name of the storage area, e.g. "local".
|
||||||
|
*/
|
||||||
|
api.storage.onChanged.addListener((changes, area) => {
|
||||||
|
if (area === "local" && changes[IC.STORAGE_KEY]) {
|
||||||
|
pushToAllComposeTabs();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tab closed: deletes its saved on/off state. Fires for every kind of tab,
|
||||||
|
* which is harmless because removing a missing key does nothing. Errors are
|
||||||
|
* ignored, because there is nothing left to update for a closed tab.
|
||||||
|
* @param {number} tabId - ID of the closed tab.
|
||||||
|
*/
|
||||||
|
api.tabs.onRemoved.addListener((tabId) => {
|
||||||
|
clearTabState(tabId).catch(() => {});
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add-on installed or updated: registers the compose script and injects it
|
||||||
|
* into compose windows that are already open. When the add-on is newly
|
||||||
|
* installed (reason "install"), but not on an update, it also opens the
|
||||||
|
* options page, so a new user sees the settings once.
|
||||||
|
* @param {object} details - runtime.onInstalled details; details.reason is
|
||||||
|
* e.g. "install" or "update".
|
||||||
|
* @returns {Promise<void>} Resolves when the script is registered and
|
||||||
|
* injected.
|
||||||
|
*/
|
||||||
|
api.runtime.onInstalled.addListener(async (details) => {
|
||||||
|
await ensureComposeScript();
|
||||||
|
await injectIntoOpenComposeTabs();
|
||||||
|
if (details && details.reason === "install") {
|
||||||
|
api.runtime.openOptionsPage();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Application start with the add-on already installed: make sure the
|
||||||
|
// compose script is registered.
|
||||||
|
api.runtime.onStartup.addListener(ensureComposeScript);
|
||||||
|
|
||||||
|
// Also on every load of the background script, e.g. when the event page is
|
||||||
|
// woken up again; the check in ensureComposeScript makes this harmless.
|
||||||
|
ensureComposeScript();
|
||||||
@@ -0,0 +1,446 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Compose script: turns typing inside a quoted block into an inline comment.
|
||||||
|
*
|
||||||
|
* When the user types a character while the caret is inside a mail quote,
|
||||||
|
* the quote is split at the caret and the user's own text is inserted
|
||||||
|
* between the two halves, prefixed with a marker such as "[OH]:". Further
|
||||||
|
* typing inside that comment (also after Enter) adds no new marker.
|
||||||
|
*
|
||||||
|
* Runs in: the editor document of every compose window. background.js
|
||||||
|
* registers it as a compose script for new windows and injects it into
|
||||||
|
* compose windows that are already open when the add-on is installed or
|
||||||
|
* updated. In the Node tests (test/compose.test.js) it is evaluated in a
|
||||||
|
* jsdom window with a simulated execCommand.
|
||||||
|
*
|
||||||
|
* Must be loaded before it, in this order (see COMPOSE_SCRIPT_FILES in
|
||||||
|
* lib/settings.js): lib/settings.js, lib/marker.js, lib/quote.js. They put
|
||||||
|
* their helpers on globalThis.InlineComment.
|
||||||
|
*
|
||||||
|
* Data flow:
|
||||||
|
* 1. On load, and whenever the window gets focus, the script asks the
|
||||||
|
* background for its configuration ("ic:getConfig"). The background also
|
||||||
|
* pushes changes ("ic:config") when the toolbar button is toggled, the
|
||||||
|
* sender identity changes or the settings are saved.
|
||||||
|
* 2. keydown (main path) and beforeinput (fallback) are handled in the
|
||||||
|
* capture phase. While the add-on is active, a printable character typed
|
||||||
|
* inside a quote, or in the blank gap between two quote halves, is
|
||||||
|
* cancelled.
|
||||||
|
* 3. startComment() splits the quote (through the editor with
|
||||||
|
* "insertParagraph" for splitMode "native", or directly on the DOM for
|
||||||
|
* splitMode "manual" and as a fallback) and inserts the marker plus the
|
||||||
|
* typed text as a new comment between the halves. In a gap there is
|
||||||
|
* nothing to split, so only the comment is inserted.
|
||||||
|
* 4. Further typing is not intercepted: the caret is now in the comment,
|
||||||
|
* which is neither inside a quote nor a gap.
|
||||||
|
*
|
||||||
|
* The code is wrapped in an IIFE so that its variables stay private; the
|
||||||
|
* only global it sets is the load guard flag.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
// Guard against loading twice (registered compose script plus injection
|
||||||
|
// after installation or update), so the listeners are not added twice.
|
||||||
|
if (globalThis.__inlineCommentComposeLoaded) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
globalThis.__inlineCommentComposeLoaded = true;
|
||||||
|
|
||||||
|
/** WebExtension API namespace: `messenger` in Thunderbird/Betterbird, `browser` as fallback. */
|
||||||
|
const api = globalThis.messenger || globalThis.browser;
|
||||||
|
/** Shared helpers from lib/settings.js, lib/marker.js and lib/quote.js. */
|
||||||
|
const IC = globalThis.InlineComment;
|
||||||
|
/** Prefix for all console output of this script. */
|
||||||
|
const LOG_PREFIX = "[Inline Comment]";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration for this compose window, as built by the background script.
|
||||||
|
* @typedef {object} ComposeConfig
|
||||||
|
* @property {boolean} active - whether the add-on is switched on for this window
|
||||||
|
* @property {boolean} isPlainText - true for a plain-text message, false for HTML
|
||||||
|
* @property {object} settings - sanitized settings that apply to the sender identity: its own profile or the global settings (see resolveSettings in lib/settings.js)
|
||||||
|
* @property {{name: string, email: string}} identity - sender identity, used for the marker placeholders
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Caret position as returned by IC.caretContext (lib/quote.js).
|
||||||
|
* @typedef {object} CaretContext
|
||||||
|
* @property {Range} range - first range of the current selection
|
||||||
|
* @property {boolean} collapsed - true if nothing is selected
|
||||||
|
* @property {?Element} cite - outermost mail quote at the start of the selection, or null
|
||||||
|
* @property {?Element} comment - own comment that contains the start of the selection (only looked up outside quotes), or null
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Current configuration from the background script. null until the first
|
||||||
|
* valid configuration arrives; while it is null the script does nothing.
|
||||||
|
* @type {?ComposeConfig}
|
||||||
|
*/
|
||||||
|
let config = null;
|
||||||
|
/**
|
||||||
|
* Text of a deferred insertion from onBeforeInput: the intercepted input
|
||||||
|
* plus any characters that arrive (via keydown or beforeinput) before the
|
||||||
|
* timer runs. null when no insertion is pending.
|
||||||
|
* @type {?string}
|
||||||
|
*/
|
||||||
|
let pendingText = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes a diagnostic message to the console, but only when the "debug"
|
||||||
|
* setting is on, so normal use stays silent.
|
||||||
|
* @param {...unknown} args - values passed to console.debug after the log
|
||||||
|
* prefix
|
||||||
|
*/
|
||||||
|
function debug(...args) {
|
||||||
|
if (config && config.settings && config.settings.debug) {
|
||||||
|
console.debug(LOG_PREFIX, ...args);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stores a configuration received from the background script. Anything
|
||||||
|
* that is not an object with a `settings` property (e.g. an undefined
|
||||||
|
* answer) is ignored, so the last valid configuration stays in place.
|
||||||
|
* @param {?ComposeConfig} next - configuration to apply
|
||||||
|
*/
|
||||||
|
function applyConfig(next) {
|
||||||
|
if (next && typeof next === "object" && next.settings) {
|
||||||
|
config = next;
|
||||||
|
debug("Configuration applied", next);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Asks the background script for this window's configuration
|
||||||
|
* ("ic:getConfig") and applies the answer. A failed request is only logged
|
||||||
|
* as a warning so the editor keeps working; the previous configuration (or
|
||||||
|
* none, which means inactive) stays in place.
|
||||||
|
* @returns {Promise<void>} resolves once the answer is handled (applied, or ignored if invalid) or the request failed
|
||||||
|
*/
|
||||||
|
async function requestConfig() {
|
||||||
|
try {
|
||||||
|
applyConfig(await api.runtime.sendMessage({ type: "ic:getConfig" }));
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(LOG_PREFIX, "Configuration not loaded:", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tells whether typed input should be turned into comments in this window.
|
||||||
|
* @returns {boolean} true when a configuration is loaded and the add-on is switched on for this window
|
||||||
|
*/
|
||||||
|
function isActive() {
|
||||||
|
return Boolean(config && config.active);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs an editor command on the compose document. Changes made through
|
||||||
|
* execCommand land in the editor's undo history (Ctrl+Z), direct DOM
|
||||||
|
* changes do not; that is why the script prefers it.
|
||||||
|
* @param {string} command - command name, e.g. "insertText", "insertHTML", "insertParagraph", "delete" or "undo"
|
||||||
|
* @param {string} [value] - command argument; passed as null when omitted
|
||||||
|
* @returns {boolean} the result of document.execCommand
|
||||||
|
*/
|
||||||
|
function exec(command, value) {
|
||||||
|
return document.execCommand(
|
||||||
|
command,
|
||||||
|
false,
|
||||||
|
value === undefined ? null : value,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders the marker for a new comment from the template setting, e.g.
|
||||||
|
* "[{initials}]:" becomes "[OH]:". The placeholders are filled from the
|
||||||
|
* sender identity and the current date and time.
|
||||||
|
* @returns {string} the rendered marker text
|
||||||
|
*/
|
||||||
|
function markerText() {
|
||||||
|
return IC.renderTemplate(
|
||||||
|
config.settings.template,
|
||||||
|
IC.markerVariables(config.identity, new Date()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a value for the data-inline-comment attribute of a new comment.
|
||||||
|
* It lets insertComment find the comment again after "insertHTML", so it
|
||||||
|
* only has to be unique within this document: a timestamp plus a short
|
||||||
|
* random suffix is enough.
|
||||||
|
* @returns {string} an id like "ic-<base-36 time>-<random>"
|
||||||
|
*/
|
||||||
|
function newCommentId() {
|
||||||
|
return `ic-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inserts a new comment (marker plus the first typed text) at the caret
|
||||||
|
* through the editor, so the insertion can be undone with Ctrl+Z. Called
|
||||||
|
* when the caret is already outside the quote (after the editor split it,
|
||||||
|
* or in a gap). Plain-text messages get a text line via "insertText"; HTML
|
||||||
|
* messages get a styled block via "insertHTML", and the caret is then moved
|
||||||
|
* to the end of that block so further typing continues inside the comment.
|
||||||
|
* @param {string} text - the first typed character(s) of the comment
|
||||||
|
*/
|
||||||
|
function insertComment(text) {
|
||||||
|
if (config.isPlainText) {
|
||||||
|
exec(
|
||||||
|
"insertText",
|
||||||
|
IC.buildCommentText(markerText(), text, config.settings),
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const id = newCommentId();
|
||||||
|
// insertHTML keeps the insertion in the editor's undo history. The HTML
|
||||||
|
// is serialized from a node built with DOM APIs, never assembled by hand.
|
||||||
|
const comment = IC.createCommentNode(
|
||||||
|
document,
|
||||||
|
markerText(),
|
||||||
|
text,
|
||||||
|
config.settings,
|
||||||
|
id,
|
||||||
|
);
|
||||||
|
exec("insertHTML", comment.outerHTML);
|
||||||
|
// The editor inserts its own copy of the markup, not `comment` itself,
|
||||||
|
// so look the new element up by its id.
|
||||||
|
const element = document.querySelector(`[data-inline-comment="${id}"]`);
|
||||||
|
if (element) {
|
||||||
|
IC.placeCaretAtEnd(document, element);
|
||||||
|
} else {
|
||||||
|
debug("Inserted comment not found", id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lets the editor split the quote at the caret with "insertParagraph",
|
||||||
|
* like pressing Enter inside a quote, so the split is part of the undo
|
||||||
|
* history. That the command splits a mail quote the same way as the Enter
|
||||||
|
* key is not guaranteed (it can only be verified in Betterbird itself), so
|
||||||
|
* the result is checked: if there is no caret afterwards or it is still
|
||||||
|
* inside a quote, the command is reverted with "undo".
|
||||||
|
* @returns {boolean} true if the caret is now outside every quote; false if the command was undone and the caller should fall back to splitManually
|
||||||
|
*/
|
||||||
|
function splitWithEditor() {
|
||||||
|
exec("insertParagraph");
|
||||||
|
const after = IC.caretContext(document);
|
||||||
|
if (after && !after.cite) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
exec("undo");
|
||||||
|
debug("Editor did not split the quote, falling back to manual split");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manual split done directly on the DOM, used for splitMode "manual" and
|
||||||
|
* as the fallback when splitWithEditor fails. Cuts the outermost quote at
|
||||||
|
* the caret, puts a new comment between the two halves and removes a half
|
||||||
|
* that is left empty (IC.splitCiteAtRange), then moves the caret to the
|
||||||
|
* end of the comment. The comment is a <span> with line breaks
|
||||||
|
* (IC.createPlainCommentElement) for plain-text messages and the styled
|
||||||
|
* block from IC.createCommentNode for HTML. These changes bypass the
|
||||||
|
* editor, so they are not in its undo history. Does nothing if there is
|
||||||
|
* no selection or the caret is not inside a quote.
|
||||||
|
* @param {string} text - the first typed character(s) of the comment
|
||||||
|
*/
|
||||||
|
function splitManually(text) {
|
||||||
|
const ctx = IC.caretContext(document);
|
||||||
|
if (!ctx || !ctx.cite) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const id = newCommentId();
|
||||||
|
const node = config.isPlainText
|
||||||
|
? IC.createPlainCommentElement(
|
||||||
|
document,
|
||||||
|
IC.buildCommentText(markerText(), text, config.settings),
|
||||||
|
id,
|
||||||
|
)
|
||||||
|
: IC.createCommentNode(document, markerText(), text, config.settings, id);
|
||||||
|
IC.splitCiteAtRange(document, ctx.range, ctx.cite, node);
|
||||||
|
IC.placeCaretAtEnd(document, node);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tells whether the caret sits in a blank line between two mail quotes,
|
||||||
|
* e.g. the two halves left after pressing Enter inside a quote (see
|
||||||
|
* IC.isGapPosition). Typing there starts a comment as well. Only checked
|
||||||
|
* for HTML messages and a collapsed caret; plain-text messages have no
|
||||||
|
* gap detection.
|
||||||
|
* @param {CaretContext} ctx - current caret context
|
||||||
|
* @returns {boolean} true if the caret is in such a gap
|
||||||
|
*/
|
||||||
|
function isGap(ctx) {
|
||||||
|
return (
|
||||||
|
!config.isPlainText &&
|
||||||
|
ctx.collapsed &&
|
||||||
|
IC.isGapPosition(document, ctx.range)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decides whether typed input at this caret position must be intercepted:
|
||||||
|
* the start of the selection is inside a mail quote, or the caret is in a
|
||||||
|
* gap between two quote halves.
|
||||||
|
* @param {?CaretContext} ctx - current caret context, or null if there is no usable selection
|
||||||
|
* @returns {boolean} true if the input should start a comment
|
||||||
|
*/
|
||||||
|
function shouldHandle(ctx) {
|
||||||
|
return Boolean(ctx) && (Boolean(ctx.cite) || isGap(ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts a comment with the first typed text. The caret position is read
|
||||||
|
* again here, because in the beforeinput path this runs one task after
|
||||||
|
* the check and the caret may have moved. A selected range is deleted
|
||||||
|
* first, so the typed text replaces it. Inside a quote, the quote is split
|
||||||
|
* (by the editor for splitMode "native", by splitManually for "manual" or
|
||||||
|
* when the editor split fails) and the comment goes between the halves.
|
||||||
|
* In a gap the comment is inserted directly. If the caret is in neither
|
||||||
|
* place (e.g. the deleted selection took the whole quote with it), the
|
||||||
|
* text is typed as normal text. If there is no usable selection, nothing
|
||||||
|
* is inserted and the already cancelled input is dropped.
|
||||||
|
* @param {string} text - the intercepted character(s)
|
||||||
|
*/
|
||||||
|
function startComment(text) {
|
||||||
|
let ctx = IC.caretContext(document);
|
||||||
|
if (!ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!ctx.collapsed) {
|
||||||
|
// Replace selected quote text: delete it first, then go on as usual.
|
||||||
|
exec("delete");
|
||||||
|
ctx = IC.caretContext(document);
|
||||||
|
if (!ctx) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (ctx.cite) {
|
||||||
|
if (config.settings.splitMode === "native" && splitWithEditor()) {
|
||||||
|
insertComment(text);
|
||||||
|
} else {
|
||||||
|
splitManually(text);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (isGap(ctx)) {
|
||||||
|
insertComment(text);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
exec("insertText", text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Runs an action and logs any exception with the add-on's log prefix
|
||||||
|
* instead of letting it escape from the event listener or timer.
|
||||||
|
* @param {function(): void} action - the work to run
|
||||||
|
*/
|
||||||
|
function run(action) {
|
||||||
|
try {
|
||||||
|
action();
|
||||||
|
} catch (error) {
|
||||||
|
console.error(LOG_PREFIX, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Main path, registered in the capture phase: intercepts a printable key
|
||||||
|
* before the editor handles it. Inside a quote or gap the key's default
|
||||||
|
* action is cancelled, its propagation is stopped, and the character
|
||||||
|
* starts a comment instead. While a deferred insertion from onBeforeInput
|
||||||
|
* is pending, the key is cancelled and appended to pendingText wherever
|
||||||
|
* the caret is. Ignored when the add-on is inactive, the event was already
|
||||||
|
* cancelled, or the key is not printable or is a Ctrl/Alt/Cmd shortcut
|
||||||
|
* (AltGr characters count as printable; see IC.isPrintableKey).
|
||||||
|
* @param {KeyboardEvent} event - the keydown event
|
||||||
|
*/
|
||||||
|
function onKeyDown(event) {
|
||||||
|
if (!isActive() || event.defaultPrevented || !IC.isPrintableKey(event)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// A deferred insertion from onBeforeInput is waiting: queue the key
|
||||||
|
// behind it so the typed order is kept.
|
||||||
|
if (pendingText !== null) {
|
||||||
|
event.preventDefault();
|
||||||
|
pendingText += event.key;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!shouldHandle(IC.caretContext(document))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopPropagation();
|
||||||
|
run(() => startComment(event.key));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fallback path, registered in the capture phase, for text input that
|
||||||
|
* onKeyDown did not catch, e.g. from an on-screen keyboard or an emoji
|
||||||
|
* picker; it arrives as beforeinput with inputType "insertText". Inside a
|
||||||
|
* quote or gap
|
||||||
|
* the input is cancelled and the comment is started in the next task
|
||||||
|
* (setTimeout 0), not in the middle of the editor action that is still
|
||||||
|
* running. Characters that arrive until then are collected in pendingText.
|
||||||
|
* IME composition and all other input types are left to the editor.
|
||||||
|
* @param {InputEvent} event - the beforeinput event
|
||||||
|
*/
|
||||||
|
function onBeforeInput(event) {
|
||||||
|
if (!isActive() || event.defaultPrevented) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
event.inputType !== "insertText" ||
|
||||||
|
event.isComposing ||
|
||||||
|
typeof event.data !== "string" ||
|
||||||
|
event.data === ""
|
||||||
|
) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (pendingText !== null) {
|
||||||
|
event.preventDefault();
|
||||||
|
pendingText += event.data;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!shouldHandle(IC.caretContext(document))) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
event.preventDefault();
|
||||||
|
pendingText = event.data;
|
||||||
|
// Take everything collected so far, reset the buffer, then pass it to
|
||||||
|
// startComment in one piece.
|
||||||
|
setTimeout(() => {
|
||||||
|
const text = pendingText;
|
||||||
|
pendingText = null;
|
||||||
|
run(() => startComment(text));
|
||||||
|
}, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Listener for configuration pushes from the background script
|
||||||
|
* ("ic:config"), sent when the toolbar button is toggled, the sender
|
||||||
|
* identity changes or the settings are saved. Other messages are ignored
|
||||||
|
* and get no answer.
|
||||||
|
* @param {?{type: string, config?: ComposeConfig}} message - the runtime message
|
||||||
|
*/
|
||||||
|
api.runtime.onMessage.addListener((message) => {
|
||||||
|
if (message && message.type === "ic:config") {
|
||||||
|
applyConfig(message.config);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// Capture phase (third argument true), so these handlers run before any
|
||||||
|
// listener on the body or the elements inside it.
|
||||||
|
document.addEventListener("keydown", onKeyDown, true);
|
||||||
|
document.addEventListener("beforeinput", onBeforeInput, true);
|
||||||
|
// Fetch the configuration again on focus, in case the background script
|
||||||
|
// was restarted in the meantime.
|
||||||
|
window.addEventListener("focus", requestConfig);
|
||||||
|
requestConfig();
|
||||||
|
})();
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
<!--
|
||||||
|
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/.
|
||||||
|
-->
|
||||||
|
<!--
|
||||||
|
Add-on and compose toolbar icon: a quote bar (left) next to a speech
|
||||||
|
bubble, i.e. a comment placed inside a quote.
|
||||||
|
-->
|
||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
|
||||||
|
<rect x="3" y="4" width="3" height="24" rx="1.5" fill="#729fcf"/>
|
||||||
|
<path d="M11 6h16a2 2 0 0 1 2 2v11a2 2 0 0 1-2 2h-8l-5 4v-4h-3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z" fill="#0056b3"/>
|
||||||
|
<path d="M14 11h11M14 16h7" stroke="#ffffff" stroke-width="2" stroke-linecap="round"/>
|
||||||
|
</svg>
|
||||||
|
After Width: | Height: | Size: 741 B |
+147
@@ -0,0 +1,147 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Localization helper for the add-on's own HTML pages (currently only the
|
||||||
|
* options page).
|
||||||
|
*
|
||||||
|
* Why it exists: extension HTML pages have no built-in localization, because
|
||||||
|
* __MSG_*__ placeholders are only replaced in manifest.json and CSS files.
|
||||||
|
* The options page therefore marks translatable elements with data
|
||||||
|
* attributes, and localizeDocument() fills them with messages from
|
||||||
|
* _locales/<lang>/messages.json.
|
||||||
|
*
|
||||||
|
* Elements name their message key in data attributes:
|
||||||
|
* data-i18n="key" replaces the element's text content
|
||||||
|
* data-i18n-aria-label="key" sets the aria-label attribute
|
||||||
|
* data-i18n-title="key" sets the title attribute
|
||||||
|
* The English text in the HTML stays as fallback when a message is missing.
|
||||||
|
* Elements with data-i18n must contain text only, because their whole
|
||||||
|
* content is replaced (test/i18n.test.js checks this for the options page).
|
||||||
|
*
|
||||||
|
* Where it runs:
|
||||||
|
* - Options page: options/options.html loads it with a <script> tag after
|
||||||
|
* lib/settings.js and lib/marker.js and before options/options.js, which
|
||||||
|
* calls localizeDocument() once at start-up.
|
||||||
|
* - Node tests: test/i18n.test.js requires it directly and also runs the
|
||||||
|
* options page in jsdom.
|
||||||
|
* It is not loaded in the background script or the compose editor.
|
||||||
|
*
|
||||||
|
* Load order: it depends on no other file. It only has to be loaded before
|
||||||
|
* the script that calls localizeDocument().
|
||||||
|
*
|
||||||
|
* Data flow: options.js passes the document and a getMessage function that
|
||||||
|
* wraps the extension's i18n.getMessage() -> localizeDocument() reads each
|
||||||
|
* key from the data attributes -> lookup() fetches the message -> non-empty
|
||||||
|
* messages replace the element text or attribute value in the DOM.
|
||||||
|
*
|
||||||
|
* Classic script (not an ES module) in the same UMD pattern as settings.js.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UMD-style wrapper: builds the API once and publishes it. Under Node (tests)
|
||||||
|
* the API becomes module.exports. In every environment it is also merged into
|
||||||
|
* root.InlineComment; Object.assign keeps the members that other lib files
|
||||||
|
* have already added, so all lib files share one namespace object.
|
||||||
|
* Side effect: creates root.InlineComment if it does not exist yet.
|
||||||
|
* @param {typeof globalThis} root - Global object that receives the API.
|
||||||
|
* @param {() => object} factory - Creates the public API of this file
|
||||||
|
* ({ I18N_ATTRIBUTES, localizeDocument }).
|
||||||
|
*/
|
||||||
|
(function (root, factory) {
|
||||||
|
const api = factory();
|
||||||
|
if (typeof module === "object" && module.exports) {
|
||||||
|
module.exports = api;
|
||||||
|
}
|
||||||
|
root.InlineComment = Object.assign(root.InlineComment || {}, api);
|
||||||
|
})(globalThis, function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maps each data attribute that holds a message key to the attribute that
|
||||||
|
* receives the translated text. data-i18n itself is not listed because it
|
||||||
|
* sets the text content, not an attribute. Frozen so that other scripts
|
||||||
|
* reaching it through the shared InlineComment namespace cannot change it.
|
||||||
|
* @type {Readonly<Record<string, string>>}
|
||||||
|
*/
|
||||||
|
const I18N_ATTRIBUTES = Object.freeze({
|
||||||
|
"data-i18n-aria-label": "aria-label",
|
||||||
|
"data-i18n-title": "title",
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Looks up one message and normalizes the result to a string. Anything but
|
||||||
|
* a non-empty string counts as missing and yields "", so the caller can keep
|
||||||
|
* the HTML fallback with a simple truthiness check. This matches
|
||||||
|
* i18n.getMessage(), which returns "" for unknown keys, and also tolerates
|
||||||
|
* a missing message source or odd return values such as undefined or null.
|
||||||
|
* getMessage is called with the key only, so no substitutions are passed;
|
||||||
|
* messages used through data attributes cannot rely on $1 ... $9.
|
||||||
|
* Exceptions thrown by getMessage are not caught.
|
||||||
|
* @param {unknown} getMessage - Message source, e.g. (key) =>
|
||||||
|
* browser.i18n.getMessage(key). Anything that is not a function counts as
|
||||||
|
* "no messages available".
|
||||||
|
* @param {string | null} key - Message key read from a data attribute. An
|
||||||
|
* empty or missing key yields "" without calling getMessage.
|
||||||
|
* @returns {string} The message text, or "" when it is missing.
|
||||||
|
*/
|
||||||
|
function lookup(getMessage, key) {
|
||||||
|
if (!key || typeof getMessage !== "function") {
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
const text = getMessage(key);
|
||||||
|
return typeof text === "string" ? text : "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces the text and attributes of all marked elements in a document
|
||||||
|
* with translated messages. Keys without a message (empty string) keep the
|
||||||
|
* fallback from the HTML, so a missing translation never blanks the UI.
|
||||||
|
*
|
||||||
|
* Side effects: changes the DOM of doc. Text is set via textContent, so
|
||||||
|
* messages are inserted as plain text and never parsed as HTML; this also
|
||||||
|
* removes any child elements, which is why data-i18n elements must contain
|
||||||
|
* text only. Setting the text of <title> updates document.title, so a
|
||||||
|
* data-i18n on <title> also translates the page title. An element may carry
|
||||||
|
* data-i18n and attribute keys at the same time; each one is applied and
|
||||||
|
* counted separately.
|
||||||
|
* @param {Document} doc - Document to localize (the options page, or a
|
||||||
|
* jsdom document in the tests).
|
||||||
|
* @param {((key: string) => string) | null} getMessage - Message source,
|
||||||
|
* e.g. (key) => browser.i18n.getMessage(key). Should return "" for
|
||||||
|
* unknown keys; other non-string results are treated as missing as well.
|
||||||
|
* If it is not a function (e.g. null), nothing is replaced and 0 is
|
||||||
|
* returned.
|
||||||
|
* @returns {number} Number of texts and attributes replaced.
|
||||||
|
*/
|
||||||
|
function localizeDocument(doc, getMessage) {
|
||||||
|
let count = 0;
|
||||||
|
for (const element of doc.querySelectorAll("[data-i18n]")) {
|
||||||
|
const text = lookup(getMessage, element.getAttribute("data-i18n"));
|
||||||
|
// An empty result keeps the English fallback text from the HTML.
|
||||||
|
if (text) {
|
||||||
|
element.textContent = text;
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (const [source, target] of Object.entries(I18N_ATTRIBUTES)) {
|
||||||
|
for (const element of doc.querySelectorAll(`[${source}]`)) {
|
||||||
|
const text = lookup(getMessage, element.getAttribute(source));
|
||||||
|
if (text) {
|
||||||
|
element.setAttribute(target, text);
|
||||||
|
count += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public API: merged into globalThis.InlineComment and exported for Node.
|
||||||
|
return { I18N_ATTRIBUTES, localizeDocument };
|
||||||
|
});
|
||||||
@@ -0,0 +1,321 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Marker engine: resolves the placeholders of the marker template, derives
|
||||||
|
* initials from the sender identity and builds the comment that is inserted
|
||||||
|
* into a quote, either as a DOM element styled with inline CSS only (HTML
|
||||||
|
* messages) or as plain text (plain-text messages).
|
||||||
|
*
|
||||||
|
* Where it runs:
|
||||||
|
* - background script (listed in manifest.json "background.scripts"; loaded
|
||||||
|
* there, but background.js currently uses none of its functions),
|
||||||
|
* - compose editor (listed in COMPOSE_SCRIPT_FILES in settings.js, before
|
||||||
|
* lib/quote.js and compose/compose.js),
|
||||||
|
* - options page (marker preview, loaded by options.html),
|
||||||
|
* - Node tests (loaded with require()).
|
||||||
|
*
|
||||||
|
* Load order: this file has no load-time dependencies. In the extension it
|
||||||
|
* is loaded right after lib/settings.js; functions that take a `settings`
|
||||||
|
* object expect the sanitized shape produced by sanitizeSettings() there.
|
||||||
|
*
|
||||||
|
* Data flow in the compose editor:
|
||||||
|
* identity {name, email} + current time
|
||||||
|
* -> markerVariables() placeholder values (initials via initialsOf())
|
||||||
|
* -> renderTemplate() marker text, e.g. "[OH]:"
|
||||||
|
* -> createCommentNode() for HTML or buildCommentText() for plain text
|
||||||
|
* -> inserted by compose.js at the caret or between the quote halves.
|
||||||
|
*
|
||||||
|
* Classic script (no ES module) in the same UMD pattern as settings.js,
|
||||||
|
* because compose scripts cannot load modules.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UMD wrapper: runs the factory once and publishes its API (VARIABLES and
|
||||||
|
* the functions). The API is merged into globalThis.InlineComment (shared
|
||||||
|
* with the other lib files) and, under Node, also exported via
|
||||||
|
* module.exports for the tests.
|
||||||
|
* @param {object} root - global object (globalThis) that receives InlineComment
|
||||||
|
* @param {function(): object} factory - builds and returns the public API of
|
||||||
|
* this file (the object returned at its end); takes no arguments
|
||||||
|
*/
|
||||||
|
(function (root, factory) {
|
||||||
|
const api = factory();
|
||||||
|
if (typeof module === "object" && module.exports) {
|
||||||
|
module.exports = api;
|
||||||
|
}
|
||||||
|
root.InlineComment = Object.assign(root.InlineComment || {}, api);
|
||||||
|
})(globalThis, function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Placeholder names supported in the marker template, without braces
|
||||||
|
* ("{initials}" -> "initials"). Only exported as part of the API:
|
||||||
|
* renderTemplate() does not read this list but matches the same five names
|
||||||
|
* with its own regular expression, so both must be kept in sync.
|
||||||
|
*/
|
||||||
|
const VARIABLES = Object.freeze([
|
||||||
|
"name",
|
||||||
|
"initials",
|
||||||
|
"email",
|
||||||
|
"date",
|
||||||
|
"time",
|
||||||
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Abbreviations of academic titles and degrees ("Dr.", "Prof.", "med." in
|
||||||
|
* "Dr. med.", ...) that are skipped when building initials. A word only
|
||||||
|
* matches with its trailing dot ("Dr." but not "Dr"), case-insensitively.
|
||||||
|
* "Dipl.-Ing." is split at the hyphen first and matches as two words.
|
||||||
|
*/
|
||||||
|
const TITLE_PATTERN = /^(dr|prof|dipl|ing|mag|med|rer|nat|phil)\.$/i;
|
||||||
|
/** Any Unicode letter; words without one (e.g. "&" or "42") are ignored. */
|
||||||
|
const LETTER = /\p{L}/u;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derives initials from the display name, or from the e-mail address when
|
||||||
|
* the name contains no usable word.
|
||||||
|
* "Max Mustermann" -> "MM", "Herb, Oliver" -> "OH",
|
||||||
|
* "Dr. Hans-Peter Müller" -> "HPM"; with an empty name, an address with
|
||||||
|
* the local part "max.mustermann" -> "MM".
|
||||||
|
*
|
||||||
|
* Rules: bracketed additions such as "(ACME)" are dropped. A name with a
|
||||||
|
* comma is read as "Last, First" when it has exactly two parts and the
|
||||||
|
* part before the comma contains no whitespace; otherwise only the part
|
||||||
|
* before the first comma counts (e.g. "Name, Company"). Words are split at
|
||||||
|
* whitespace, "-" and "_"; academic titles and words without a letter are
|
||||||
|
* skipped. The first letter of at most the first four words is used.
|
||||||
|
* @param {string} name - display name of the sender identity; anything
|
||||||
|
* that is not a string counts as empty
|
||||||
|
* @param {string} email - e-mail address of the identity, used as fallback:
|
||||||
|
* its local part (before "@") is split at ".", "-", "_", "+" and digits
|
||||||
|
* @returns {string} the first letter of each of up to four words,
|
||||||
|
* upper-cased with German locale rules (usually one character each), or
|
||||||
|
* "?" when no word with a letter is found
|
||||||
|
*/
|
||||||
|
function initialsOf(name, email) {
|
||||||
|
let text = typeof name === "string" ? name : "";
|
||||||
|
// Drop additions in brackets such as "(ACME)" or "<Sales>". A space
|
||||||
|
// instead of nothing keeps the neighbouring words apart.
|
||||||
|
text = text.replace(/[([{<][^)\]}>]*[)\]}>]/g, " ");
|
||||||
|
if (text.includes(",")) {
|
||||||
|
const parts = text.split(",");
|
||||||
|
const first = parts[0].trim();
|
||||||
|
// Swap "Last, First"; otherwise keep only the part before the comma
|
||||||
|
// (e.g. "Max Mustermann, Example Corp").
|
||||||
|
text =
|
||||||
|
parts.length === 2 && first.split(/\s+/).length === 1
|
||||||
|
? `${parts[1]} ${first}`
|
||||||
|
: first;
|
||||||
|
}
|
||||||
|
let words = text
|
||||||
|
.split(/[\s\-_]+/u)
|
||||||
|
.filter((word) => word && !TITLE_PATTERN.test(word) && LETTER.test(word));
|
||||||
|
if (words.length === 0 && typeof email === "string") {
|
||||||
|
// Fall back to the local part of the address, e.g.
|
||||||
|
// "max.mustermann" -> "max", "mustermann".
|
||||||
|
const local = email.split("@")[0] || "";
|
||||||
|
words = local.split(/[.\-_+0-9]+/).filter((word) => LETTER.test(word));
|
||||||
|
}
|
||||||
|
if (words.length === 0) {
|
||||||
|
return "?";
|
||||||
|
}
|
||||||
|
// First letter of each word (leading non-letters are skipped). The fixed
|
||||||
|
// locale keeps the upper-casing independent of the system locale.
|
||||||
|
return words
|
||||||
|
.slice(0, 4)
|
||||||
|
.map((word) => word.match(LETTER)[0].toLocaleUpperCase("de"))
|
||||||
|
.join("");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Computes the values of all template placeholders from the sender
|
||||||
|
* identity and a point in time. compose.js calls it with the current time
|
||||||
|
* for every new comment, so {date} and {time} show when the comment was
|
||||||
|
* started; the options page does the same for its preview.
|
||||||
|
* @param {{name?: string, email?: string}|null} identity - sender identity;
|
||||||
|
* null or missing fields count as empty strings
|
||||||
|
* @param {Date} [now] - time used for {date} and {time}; anything that is
|
||||||
|
* not a Date falls back to the current time
|
||||||
|
* @param {string} [locale] - locale for date and time formatting, e.g.
|
||||||
|
* "de-DE"; when omitted (as both callers do), the runtime's default
|
||||||
|
* locale applies, which in Thunderbird and Betterbird normally follows
|
||||||
|
* the application language
|
||||||
|
* @returns {{name: string, initials: string, email: string, date: string, time: string}}
|
||||||
|
* placeholder values: name falls back to the address when the identity
|
||||||
|
* has no display name, initials come from initialsOf(), date uses the
|
||||||
|
* locale's default date format and time shows hours and minutes
|
||||||
|
*/
|
||||||
|
function markerVariables(identity, now, locale) {
|
||||||
|
const name = (identity && identity.name) || "";
|
||||||
|
const email = (identity && identity.email) || "";
|
||||||
|
const date = now instanceof Date ? now : new Date();
|
||||||
|
return {
|
||||||
|
name: name || email,
|
||||||
|
initials: initialsOf(name, email),
|
||||||
|
email,
|
||||||
|
date: date.toLocaleDateString(locale),
|
||||||
|
time: date.toLocaleTimeString(locale, {
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Replaces {name}, {initials}, {email}, {date} and {time} in the marker
|
||||||
|
* template with their values. Unknown placeholders such as {foo}, and
|
||||||
|
* known ones without a value (undefined or null), are left as they are,
|
||||||
|
* so a mistyped placeholder stays visible in the marker. The replacement
|
||||||
|
* is a single pass: placeholder text inside a value is not expanded again.
|
||||||
|
* @param {string} template - marker template, e.g. "[{initials}]:";
|
||||||
|
* converted with String()
|
||||||
|
* @param {Record<string, string>|null|undefined} variables - placeholder
|
||||||
|
* values, usually from markerVariables(); non-string values are
|
||||||
|
* converted with String()
|
||||||
|
* @returns {string} the rendered marker text, e.g. "[OH]:"
|
||||||
|
*/
|
||||||
|
function renderTemplate(template, variables) {
|
||||||
|
return String(template).replace(
|
||||||
|
/\{(name|initials|email|date|time)\}/g,
|
||||||
|
/**
|
||||||
|
* Replacement callback for one placeholder found in the template.
|
||||||
|
* @param {string} match - the whole placeholder, e.g. "{date}"
|
||||||
|
* @param {string} key - its name without braces, e.g. "date"
|
||||||
|
* @returns {string} the value as a string, or `match` unchanged when
|
||||||
|
* the value is undefined or null
|
||||||
|
*/
|
||||||
|
(match, key) => {
|
||||||
|
const value = variables ? variables[key] : undefined;
|
||||||
|
return value === undefined || value === null ? match : String(value);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the inline CSS for the comment block (the <div>): text colour,
|
||||||
|
* bold, italic, an optional highlight background with a little padding,
|
||||||
|
* and a vertical margin of 1em for "blank line before" and "blank line
|
||||||
|
* after". Inline CSS because many mail clients strip <style> blocks and
|
||||||
|
* classes (see createCommentNode()).
|
||||||
|
* @param {object} settings - sanitized settings (sanitizeSettings() in
|
||||||
|
* settings.js); uses textColor, textBold, textItalic, highlight,
|
||||||
|
* highlightColor, blankLineBefore and blankLineAfter. Colours are then
|
||||||
|
* "#rrggbb" strings, which is why they go into the CSS text unescaped.
|
||||||
|
* @returns {string} CSS declarations for a style attribute, each
|
||||||
|
* terminated by ";"
|
||||||
|
*/
|
||||||
|
function commentStyle(settings) {
|
||||||
|
const parts = [
|
||||||
|
`color:${settings.textColor}`,
|
||||||
|
`font-weight:${settings.textBold ? "bold" : "normal"}`,
|
||||||
|
`font-style:${settings.textItalic ? "italic" : "normal"}`,
|
||||||
|
];
|
||||||
|
if (settings.highlight) {
|
||||||
|
parts.push(
|
||||||
|
`background-color:${settings.highlightColor}`,
|
||||||
|
"padding:2px 4px",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const top = settings.blankLineBefore ? "1em" : "0";
|
||||||
|
const bottom = settings.blankLineAfter ? "1em" : "0";
|
||||||
|
parts.push(`margin:${top} 0 ${bottom} 0`);
|
||||||
|
return `${parts.join(";")};`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the inline CSS for the marker <span>: colour, bold and italic.
|
||||||
|
* @param {object} settings - sanitized settings; uses markerColor,
|
||||||
|
* markerBold and markerItalic
|
||||||
|
* @returns {string} CSS declarations for a style attribute, each
|
||||||
|
* terminated by ";"
|
||||||
|
*/
|
||||||
|
function markerStyle(settings) {
|
||||||
|
return (
|
||||||
|
`color:${settings.markerColor};` +
|
||||||
|
`font-weight:${settings.markerBold ? "bold" : "normal"};` +
|
||||||
|
`font-style:${settings.markerItalic ? "italic" : "normal"};`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the comment block for HTML messages as a detached DOM element:
|
||||||
|
* <div data-inline-comment="id" style="...">
|
||||||
|
* <span data-inline-comment-marker="" style="...">marker</span> text
|
||||||
|
* </div>
|
||||||
|
* Only inline CSS, because Outlook, Gmail and Apple Mail often strip
|
||||||
|
* <style> blocks and classes. The element is built with createElement,
|
||||||
|
* textContent and setAttribute only, so marker, text and id can never
|
||||||
|
* turn into markup. Callers that need an HTML string (execCommand
|
||||||
|
* "insertHTML" in compose.js) serialize the returned element; the manual
|
||||||
|
* split (splitCiteAtRange() in quote.js) and the options page preview
|
||||||
|
* insert the element itself.
|
||||||
|
*
|
||||||
|
* data-inline-comment lets quote.js recognise the add-on's own comments
|
||||||
|
* and lets compose.js find the inserted comment by its id;
|
||||||
|
* data-inline-comment-marker marks the marker span.
|
||||||
|
*
|
||||||
|
* No side effects on the document tree: the element belongs to `doc` but
|
||||||
|
* is not inserted anywhere.
|
||||||
|
* @param {Document} doc - document that owns the new element (the compose
|
||||||
|
* editor document or the options page document)
|
||||||
|
* @param {string} markerText - rendered marker, e.g. "[MM]:"; converted
|
||||||
|
* with String()
|
||||||
|
* @param {string} firstText - the first typed character(s), or on the
|
||||||
|
* options page the start of the sample comment; converted with String()
|
||||||
|
* @param {object} settings - sanitized settings, passed to commentStyle()
|
||||||
|
* and markerStyle()
|
||||||
|
* @param {string} id - unique id, used to find the comment and place the
|
||||||
|
* caret; converted with String()
|
||||||
|
* @returns {HTMLDivElement} the new comment element, not yet inserted
|
||||||
|
*/
|
||||||
|
function createCommentNode(doc, markerText, firstText, settings, id) {
|
||||||
|
const comment = doc.createElement("div");
|
||||||
|
comment.setAttribute("data-inline-comment", String(id));
|
||||||
|
comment.setAttribute("style", commentStyle(settings));
|
||||||
|
const marker = doc.createElement("span");
|
||||||
|
marker.setAttribute("data-inline-comment-marker", "");
|
||||||
|
marker.setAttribute("style", markerStyle(settings));
|
||||||
|
marker.textContent = String(markerText);
|
||||||
|
// Non-breaking spaces, so the editor keeps leading and repeated spaces.
|
||||||
|
// The first one separates the marker from the text.
|
||||||
|
const text = `\u00a0${String(firstText).replace(/ /g, "\u00a0")}`;
|
||||||
|
comment.append(marker, doc.createTextNode(text));
|
||||||
|
return comment;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the comment as plain text for plain-text messages: marker, one
|
||||||
|
* space, text, preceded by a line break when blankLineBefore is set
|
||||||
|
* (blankLineAfter is not applied to plain text). The line breaks that
|
||||||
|
* separate the comment from the quote halves are not added here; they come
|
||||||
|
* from splitting the quote (by the editor, or by the <br> elements of
|
||||||
|
* createPlainCommentElement() in quote.js for the manual split).
|
||||||
|
* @param {string} markerText - rendered marker, e.g. "[MM]:"
|
||||||
|
* @param {string} firstText - the first typed character(s)
|
||||||
|
* @param {object} settings - sanitized settings; only blankLineBefore is used
|
||||||
|
* @returns {string} the comment text, e.g. "[MM]: a" or "\n[MM]: a"
|
||||||
|
*/
|
||||||
|
function buildCommentText(markerText, firstText, settings) {
|
||||||
|
return `${settings.blankLineBefore ? "\n" : ""}${markerText} ${firstText}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public API, merged into globalThis.InlineComment by the wrapper above
|
||||||
|
// and exported for Node.
|
||||||
|
return {
|
||||||
|
VARIABLES,
|
||||||
|
initialsOf,
|
||||||
|
markerVariables,
|
||||||
|
renderTemplate,
|
||||||
|
commentStyle,
|
||||||
|
markerStyle,
|
||||||
|
createCommentNode,
|
||||||
|
buildCommentText,
|
||||||
|
};
|
||||||
|
});
|
||||||
@@ -0,0 +1,534 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Quote detection and DOM helpers for the compose editor.
|
||||||
|
*
|
||||||
|
* Where it runs: in the editor document of every compose window, and under
|
||||||
|
* Node for the tests. It is the third entry of COMPOSE_SCRIPT_FILES (see
|
||||||
|
* settings.js), which background.js registers for new compose windows and
|
||||||
|
* injects into compose windows that are already open. It is loaded after
|
||||||
|
* lib/settings.js and lib/marker.js and before compose/compose.js, which
|
||||||
|
* calls these helpers through globalThis.InlineComment. The file has no
|
||||||
|
* dependencies of its own: test/quote.test.js require()s it directly and
|
||||||
|
* passes in a jsdom document, test/compose.test.js evaluates it in a jsdom
|
||||||
|
* window together with the other compose script files. The background
|
||||||
|
* script and the options page do not load it.
|
||||||
|
*
|
||||||
|
* Quotes in the compose editor:
|
||||||
|
* - HTML: <blockquote type="cite"> (possibly nested)
|
||||||
|
* - plain text: <span _moz_quote="true"> containing "> " lines
|
||||||
|
* Comment elements inserted by the add-on carry the attribute
|
||||||
|
* data-inline-comment: the HTML comment block from marker.js and the
|
||||||
|
* plain-text comment of the manual split. A plain-text comment inserted
|
||||||
|
* through the editor ("insertText") is bare text without that attribute.
|
||||||
|
*
|
||||||
|
* Data flow: on keydown, compose.js uses isPrintableKey() to ignore named
|
||||||
|
* keys and Ctrl/Alt/Cmd shortcuts (its beforeinput fallback checks the
|
||||||
|
* input type instead). For an intercepted character it asks caretContext()
|
||||||
|
* whether the caret is inside a quote and, for HTML messages only,
|
||||||
|
* isGapPosition() whether it is in the blank line between two quote parts.
|
||||||
|
* After an editor split (split mode "native") it calls caretContext() again
|
||||||
|
* to check that the caret has left the quote. For the manual split (split
|
||||||
|
* mode "manual", or the fallback when the editor does not split the quote
|
||||||
|
* itself) splitCiteAtRange() cuts the outermost quote at the caret and
|
||||||
|
* inserts the comment node, built by createPlainCommentElement() for
|
||||||
|
* plain-text messages or by createCommentNode() in marker.js for HTML.
|
||||||
|
* placeCaretAtEnd() then moves the caret to the end of the new comment, so
|
||||||
|
* typing continues inside it; compose.js also calls it after inserting an
|
||||||
|
* HTML comment through the editor.
|
||||||
|
*
|
||||||
|
* Classic script (not an ES module), using the same UMD pattern as
|
||||||
|
* settings.js, because compose scripts are loaded as classic scripts.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UMD-style wrapper: builds the API once and, under Node, exports it as
|
||||||
|
* module.exports. In every environment it also merges the API into
|
||||||
|
* globalThis.InlineComment; Object.assign keeps the helpers that the other
|
||||||
|
* lib files have already put there.
|
||||||
|
* @param {typeof globalThis} root - Global object that receives the API.
|
||||||
|
* @param {function(): object} factory - Builds and returns the public API.
|
||||||
|
*/
|
||||||
|
(function (root, factory) {
|
||||||
|
const api = factory();
|
||||||
|
if (typeof module === "object" && module.exports) {
|
||||||
|
module.exports = api;
|
||||||
|
}
|
||||||
|
root.InlineComment = Object.assign(root.InlineComment || {}, api);
|
||||||
|
})(globalThis, function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
// Values of Node.ELEMENT_NODE, Node.TEXT_NODE and NodeFilter.SHOW_TEXT.
|
||||||
|
// Hard-coded because the globals Node and NodeFilter do not exist when
|
||||||
|
// the tests require() this file under Node.
|
||||||
|
const ELEMENT_NODE = 1;
|
||||||
|
const TEXT_NODE = 3;
|
||||||
|
const SHOW_TEXT = 4;
|
||||||
|
/**
|
||||||
|
* Attribute that marks comment elements inserted by the add-on; its value
|
||||||
|
* is the comment ID.
|
||||||
|
*/
|
||||||
|
const COMMENT_ATTRIBUTE = "data-inline-comment";
|
||||||
|
/**
|
||||||
|
* Selector for elements that count as visible content even without text.
|
||||||
|
* isBlankNode() and hasContent() only look for them among the descendants
|
||||||
|
* of the node they check, not at the node itself.
|
||||||
|
*/
|
||||||
|
const CONTENT_ELEMENTS = "img,video,iframe,table,hr,object,embed";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a node is a quote of the original message, in either
|
||||||
|
* format: an HTML `<blockquote type="cite">` (type compared
|
||||||
|
* case-insensitively) or any element with `_moz_quote="true"` (the
|
||||||
|
* plain-text quote). A `<blockquote>` with neither attribute is not a
|
||||||
|
* mail quote.
|
||||||
|
* @param {?Node} node - Node to test; may be null.
|
||||||
|
* @returns {boolean} True if the node is a mail quote element.
|
||||||
|
*/
|
||||||
|
function isMailCite(node) {
|
||||||
|
if (!node || node.nodeType !== ELEMENT_NODE) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
node.localName === "blockquote" &&
|
||||||
|
String(node.getAttribute("type") || "").toLowerCase() === "cite"
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return node.getAttribute("_moz_quote") === "true";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a node is an inline comment, i.e. an element that
|
||||||
|
* carries the data-inline-comment attribute (any value).
|
||||||
|
* @param {?Node} node - Node to test; may be null.
|
||||||
|
* @returns {boolean} True if the node is an inline comment element.
|
||||||
|
*/
|
||||||
|
function isComment(node) {
|
||||||
|
return (
|
||||||
|
Boolean(node) &&
|
||||||
|
node.nodeType === ELEMENT_NODE &&
|
||||||
|
node.hasAttribute(COMMENT_ATTRIBUTE)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the node itself if it is an element, otherwise its parent (for
|
||||||
|
* example the element around a text node). Range boundaries are often
|
||||||
|
* text nodes, while the upward walks below start from an element.
|
||||||
|
* @param {?Node} node - Any node; may be null.
|
||||||
|
* @returns {?Node} The element, the parent node, or null.
|
||||||
|
*/
|
||||||
|
function elementOf(node) {
|
||||||
|
if (!node) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return node.nodeType === ELEMENT_NODE ? node : node.parentNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the outermost mail quote that contains the node (the node itself
|
||||||
|
* counts). The walk goes upwards and stops at `root`, which is not
|
||||||
|
* tested. The outermost quote is wanted because a split has to cut the
|
||||||
|
* whole quote at the caret, including any nested quotes.
|
||||||
|
* @param {?Node} node - Start node, typically the caret container.
|
||||||
|
* @param {?Node} root - Upper bound of the search (the editor body).
|
||||||
|
* @returns {?Element} The outermost quote element, or null if none.
|
||||||
|
*/
|
||||||
|
function outermostCite(node, root) {
|
||||||
|
let found = null;
|
||||||
|
for (
|
||||||
|
let current = elementOf(node);
|
||||||
|
current && current !== root;
|
||||||
|
current = current.parentNode
|
||||||
|
) {
|
||||||
|
if (isMailCite(current)) {
|
||||||
|
found = current;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return found;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the nearest inline comment that contains the node (the node
|
||||||
|
* itself counts), walking upwards until `root`, which is not tested.
|
||||||
|
* @param {?Node} node - Start node, typically the caret container.
|
||||||
|
* @param {?Node} root - Upper bound of the search (the editor body).
|
||||||
|
* @returns {?Element} The nearest comment element, or null if none.
|
||||||
|
*/
|
||||||
|
function closestComment(node, root) {
|
||||||
|
for (
|
||||||
|
let current = elementOf(node);
|
||||||
|
current && current !== root;
|
||||||
|
current = current.parentNode
|
||||||
|
) {
|
||||||
|
if (isComment(current)) {
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Describes where the caret (or the start of the selection) is in the
|
||||||
|
* editor. Only the first range of the selection is used.
|
||||||
|
* `cite` is the outermost quote at the start of the selection, even if
|
||||||
|
* there are comments inside it at that point: comments within a quote
|
||||||
|
* are part of the quoted text, not the user's own. `comment` is the
|
||||||
|
* user's own comment around the caret and is only looked up outside
|
||||||
|
* quotes.
|
||||||
|
* @param {Document} doc - The compose editor document.
|
||||||
|
* @returns {{range: Range, collapsed: boolean, cite: Element|null, comment: Element|null}|null}
|
||||||
|
* The selection range, whether it is collapsed, and the enclosing quote
|
||||||
|
* and comment; null if there is no selection or no body, or the
|
||||||
|
* selection does not start inside the body.
|
||||||
|
*/
|
||||||
|
function caretContext(doc) {
|
||||||
|
const selection = doc.getSelection ? doc.getSelection() : null;
|
||||||
|
if (!selection || selection.rangeCount === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const range = selection.getRangeAt(0);
|
||||||
|
const root = doc.body;
|
||||||
|
if (!root || !root.contains(range.startContainer)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
const cite = outermostCite(range.startContainer, root);
|
||||||
|
return {
|
||||||
|
range,
|
||||||
|
collapsed: range.collapsed,
|
||||||
|
cite,
|
||||||
|
comment: cite ? null : closestComment(range.startContainer, root),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a node shows nothing, so the gap detection can treat it
|
||||||
|
* as an empty line or skip it: a text node with only whitespace
|
||||||
|
* (non-breaking spaces count as whitespace), a `<br>`, or an element
|
||||||
|
* whose text is only whitespace and which neither matches nor contains
|
||||||
|
* CONTENT_ELEMENTS. A content element itself (e.g. a top-level `<img>`
|
||||||
|
* or `<hr>`) is therefore never blank, so the gap detection does not skip
|
||||||
|
* an image or rule between two quote parts.
|
||||||
|
* Quotes and inline comments are never blank, even when empty, so the
|
||||||
|
* gap detection does not skip over them. Other node types (e.g. HTML
|
||||||
|
* comments) are not blank either.
|
||||||
|
* @param {?Node} node - Node to test; may be null.
|
||||||
|
* @returns {boolean} True if the node has no visible content.
|
||||||
|
*/
|
||||||
|
function isBlankNode(node) {
|
||||||
|
if (!node) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (node.nodeType === TEXT_NODE) {
|
||||||
|
return node.data.replace(/\u00a0/g, " ").trim() === "";
|
||||||
|
}
|
||||||
|
if (node.nodeType !== ELEMENT_NODE || isMailCite(node) || isComment(node)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (node.localName === "br") {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
node.matches(CONTENT_ELEMENTS) ||
|
||||||
|
node.querySelector(CONTENT_ELEMENTS)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return node.textContent.replace(/\u00a0/g, " ").trim() === "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the nearest sibling in the given direction that is not blank
|
||||||
|
* (see isBlankNode), skipping empty lines in between.
|
||||||
|
* @param {Node} node - Node whose siblings are searched.
|
||||||
|
* @param {number} direction - Negative for previous siblings, otherwise
|
||||||
|
* next siblings.
|
||||||
|
* @returns {?Node} The first non-blank sibling, or null if there is none.
|
||||||
|
*/
|
||||||
|
function siblingSkippingBlank(node, direction) {
|
||||||
|
let current = direction < 0 ? node.previousSibling : node.nextSibling;
|
||||||
|
while (current && isBlankNode(current)) {
|
||||||
|
current = direction < 0 ? current.previousSibling : current.nextSibling;
|
||||||
|
}
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the top-level node (direct child of `root`) that holds the caret
|
||||||
|
* line. If the caret sits directly in `root`, between two children, an
|
||||||
|
* adjacent blank node is taken as the line (the child after the caret
|
||||||
|
* first, then the one before); otherwise the child after the caret, or
|
||||||
|
* the one before it when the caret is at the end of `root`.
|
||||||
|
* @param {Range} range - Range whose start is the caret position.
|
||||||
|
* @param {Node} root - Node whose direct children are the lines (the
|
||||||
|
* editor body).
|
||||||
|
* @returns {?Node} The line node, or null if the caret is not inside
|
||||||
|
* `root` or `root` has no children.
|
||||||
|
*/
|
||||||
|
function lineNodeAt(range, root) {
|
||||||
|
const container = range.startContainer;
|
||||||
|
if (container === root) {
|
||||||
|
// No child contains the caret, so look at the neighbours of the offset.
|
||||||
|
const atOffset = root.childNodes[range.startOffset] || null;
|
||||||
|
const beforeOffset = root.childNodes[range.startOffset - 1] || null;
|
||||||
|
if (isBlankNode(atOffset)) {
|
||||||
|
return atOffset;
|
||||||
|
}
|
||||||
|
return isBlankNode(beforeOffset)
|
||||||
|
? beforeOffset
|
||||||
|
: atOffset || beforeOffset;
|
||||||
|
}
|
||||||
|
let node = container;
|
||||||
|
while (node && node.parentNode !== root) {
|
||||||
|
node = node.parentNode;
|
||||||
|
}
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether the caret is in a blank line between two parts of a
|
||||||
|
* quote. This is what the editor leaves behind after Enter is pressed
|
||||||
|
* inside a quote, so typing there starts a comment as well. compose.js
|
||||||
|
* only uses it for HTML messages.
|
||||||
|
* All conditions must hold: the range is collapsed, it is neither inside
|
||||||
|
* a quote nor inside an inline comment, its top-level line (direct child
|
||||||
|
* of the body) is blank, and the nearest non-blank siblings before and
|
||||||
|
* after that line are both mail quotes.
|
||||||
|
* @param {Document} doc - The compose editor document.
|
||||||
|
* @param {?Range} range - Caret range, usually from caretContext().
|
||||||
|
* @returns {boolean} True if the caret is in such a gap.
|
||||||
|
*/
|
||||||
|
function isGapPosition(doc, range) {
|
||||||
|
const root = doc.body;
|
||||||
|
if (!root || !range || !range.collapsed) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
outermostCite(range.startContainer, root) ||
|
||||||
|
closestComment(range.startContainer, root)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const line = lineNodeAt(range, root);
|
||||||
|
if (!line || !isBlankNode(line)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
isMailCite(siblingSkippingBlank(line, -1)) &&
|
||||||
|
isMailCite(siblingSkippingBlank(line, 1))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a key press types a character. Shortcuts with Ctrl, Alt
|
||||||
|
* or Cmd/Meta (e.g. Ctrl+C to copy) do not count, but characters typed
|
||||||
|
* with AltGr, such as @ or €, do. Named keys (Enter, Backspace, arrow
|
||||||
|
* keys) and key presses during an IME composition do not count either.
|
||||||
|
* @param {KeyboardEvent} event - The keydown event.
|
||||||
|
* @returns {boolean} True if the key types a single character.
|
||||||
|
*/
|
||||||
|
function isPrintableKey(event) {
|
||||||
|
if (!event || typeof event.key !== "string" || event.isComposing) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Named keys have longer key values. Spreading counts code points, so
|
||||||
|
// a character outside the BMP (e.g. an emoji) still counts as one.
|
||||||
|
if ([...event.key].length !== 1) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// AltGr may also set ctrlKey and altKey (e.g. on Windows); the
|
||||||
|
// AltGraph modifier state tells it apart from a real shortcut.
|
||||||
|
const altGraph =
|
||||||
|
typeof event.getModifierState === "function" &&
|
||||||
|
event.getModifierState("AltGraph");
|
||||||
|
if (event.metaKey) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if ((event.ctrlKey || event.altKey) && !altGraph) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether a node still shows something: it contains a descendant
|
||||||
|
* matching CONTENT_ELEMENTS (e.g. an image or table), or text other than
|
||||||
|
* whitespace (non-breaking spaces count as whitespace). For plain-text
|
||||||
|
* quotes (`_moz_quote="true"`) every ">" in the text is ignored, so a part
|
||||||
|
* that only consists of quote prefixes counts as empty. Used to drop
|
||||||
|
* empty halves after a split.
|
||||||
|
* @param {?Node} node - Node to test, usually one half of a split quote.
|
||||||
|
* @returns {boolean} True if visible content remains.
|
||||||
|
*/
|
||||||
|
function hasContent(node) {
|
||||||
|
if (!node) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
node.nodeType === ELEMENT_NODE &&
|
||||||
|
node.querySelector(CONTENT_ELEMENTS)
|
||||||
|
) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const plainQuote =
|
||||||
|
node.nodeType === ELEMENT_NODE &&
|
||||||
|
node.getAttribute("_moz_quote") === "true";
|
||||||
|
const text = node.textContent.replace(/\u00a0/g, " ");
|
||||||
|
return (plainQuote ? text.replace(/>/g, "") : text).trim() !== "";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Restores the "> " prefix of a plain-text quote part that was split off
|
||||||
|
* in the middle of a line. If its first text node does not start with
|
||||||
|
* ">", leading whitespace is removed and "> " is prepended, so the first
|
||||||
|
* line still reads as quoted. Parts that already start with ">" (split at
|
||||||
|
* a line start), parts without any text node, and quotes without
|
||||||
|
* `_moz_quote="true"` (HTML quotes) are left unchanged.
|
||||||
|
* Side effect: modifies that text node in place.
|
||||||
|
* @param {Document} doc - Document that owns the quote (creates the
|
||||||
|
* TreeWalker).
|
||||||
|
* @param {Element} quote - The quote part to fix.
|
||||||
|
*/
|
||||||
|
function fixPlainQuotePrefix(doc, quote) {
|
||||||
|
if (quote.getAttribute("_moz_quote") !== "true") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const walker = doc.createTreeWalker(quote, SHOW_TEXT);
|
||||||
|
const first = walker.nextNode();
|
||||||
|
if (first && !first.data.startsWith(">")) {
|
||||||
|
first.data = `> ${first.data.replace(/^\s+/, "")}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Splits the quote `cite` at the start of `range` and puts `insertNode`
|
||||||
|
* between the two halves. Used for the manual split (split mode
|
||||||
|
* "manual", or the fallback when the editor does not split the quote).
|
||||||
|
*
|
||||||
|
* Everything from the caret to the end of `cite` is cut out with
|
||||||
|
* Range.extractContents(). Elements between the caret and `cite` that
|
||||||
|
* are only partly inside that range, including nested quotes, stay in
|
||||||
|
* place with the part before the caret and come along as shallow copies
|
||||||
|
* holding the rest, so nested quotes are split as well. `insertNode` is
|
||||||
|
* placed directly after `cite`, and the cut-out part goes into a shallow
|
||||||
|
* copy of `cite` (same tag and attributes) placed after `insertNode`.
|
||||||
|
* For plain-text quotes the "> " prefix of that part is restored if
|
||||||
|
* missing. Halves left without content (see hasContent; caret at the
|
||||||
|
* very start or end) are removed.
|
||||||
|
*
|
||||||
|
* Side effects: changes the DOM directly, bypassing the editor, so the
|
||||||
|
* split is not part of the editor's undo history.
|
||||||
|
* @param {Document} doc - The compose editor document.
|
||||||
|
* @param {Range} range - Caret range; only its start is used.
|
||||||
|
* @param {Element} cite - Quote to split, normally the outermost quote
|
||||||
|
* around the caret (see caretContext).
|
||||||
|
* @param {Node} insertNode - Node to insert between the halves (the
|
||||||
|
* comment).
|
||||||
|
* @returns {{before: Element|null, after: Element|null}} The remaining
|
||||||
|
* halves; null for a half that was removed because it was empty.
|
||||||
|
*/
|
||||||
|
function splitCiteAtRange(doc, range, cite, insertNode) {
|
||||||
|
const tail = doc.createRange();
|
||||||
|
tail.setStart(range.startContainer, range.startOffset);
|
||||||
|
tail.setEnd(cite, cite.childNodes.length);
|
||||||
|
const tailContent = tail.extractContents();
|
||||||
|
|
||||||
|
// Shallow copy: keeps type="cite" or _moz_quote, but no children.
|
||||||
|
const after = cite.cloneNode(false);
|
||||||
|
after.appendChild(tailContent);
|
||||||
|
const parent = cite.parentNode;
|
||||||
|
parent.insertBefore(insertNode, cite.nextSibling);
|
||||||
|
parent.insertBefore(after, insertNode.nextSibling);
|
||||||
|
fixPlainQuotePrefix(doc, after);
|
||||||
|
|
||||||
|
let before = cite;
|
||||||
|
if (!hasContent(cite)) {
|
||||||
|
cite.remove();
|
||||||
|
before = null;
|
||||||
|
}
|
||||||
|
let afterKept = after;
|
||||||
|
if (!hasContent(after)) {
|
||||||
|
after.remove();
|
||||||
|
afterKept = null;
|
||||||
|
}
|
||||||
|
return { before, after: afterKept };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the comment element for plain-text messages. It is only needed
|
||||||
|
* for the manual split; on the editor path compose.js inserts plain text
|
||||||
|
* with the editor's insertText command instead. The `<br>` before and
|
||||||
|
* after the text put the comment on its own line between the halves.
|
||||||
|
* @param {Document} doc - Document that creates the nodes.
|
||||||
|
* @param {string} text - Complete comment text, as built by
|
||||||
|
* buildCommentText() in marker.js.
|
||||||
|
* @param {string} id - Comment ID, stored in the data-inline-comment
|
||||||
|
* attribute.
|
||||||
|
* @returns {HTMLSpanElement} `<span data-inline-comment="id">` with
|
||||||
|
* `<br>`, the text and another `<br>` inside.
|
||||||
|
*/
|
||||||
|
function createPlainCommentElement(doc, text, id) {
|
||||||
|
const span = doc.createElement("span");
|
||||||
|
span.setAttribute(COMMENT_ATTRIBUTE, id);
|
||||||
|
span.append(
|
||||||
|
doc.createElement("br"),
|
||||||
|
doc.createTextNode(text),
|
||||||
|
doc.createElement("br"),
|
||||||
|
);
|
||||||
|
return span;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Puts a collapsed caret at the end of the last text node inside
|
||||||
|
* `element`, or at the end of `element` (after its last child) if it
|
||||||
|
* contains no text node, so typing continues inside a newly inserted
|
||||||
|
* comment. For the plain-text comment element that is before its
|
||||||
|
* trailing `<br>`.
|
||||||
|
* Side effect: replaces the document's selection.
|
||||||
|
* @param {Document} doc - Document whose selection is changed.
|
||||||
|
* @param {Element} element - Element to put the caret into (the
|
||||||
|
* comment).
|
||||||
|
*/
|
||||||
|
function placeCaretAtEnd(doc, element) {
|
||||||
|
const walker = doc.createTreeWalker(element, SHOW_TEXT);
|
||||||
|
let last = null;
|
||||||
|
while (walker.nextNode()) {
|
||||||
|
last = walker.currentNode;
|
||||||
|
}
|
||||||
|
const range = doc.createRange();
|
||||||
|
if (last) {
|
||||||
|
range.setStart(last, last.data.length);
|
||||||
|
} else {
|
||||||
|
range.setStart(element, element.childNodes.length);
|
||||||
|
}
|
||||||
|
range.collapse(true);
|
||||||
|
const selection = doc.getSelection();
|
||||||
|
selection.removeAllRanges();
|
||||||
|
selection.addRange(range);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public API, exported by the wrapper at the top of the file.
|
||||||
|
return {
|
||||||
|
COMMENT_ATTRIBUTE,
|
||||||
|
isMailCite,
|
||||||
|
isComment,
|
||||||
|
outermostCite,
|
||||||
|
closestComment,
|
||||||
|
caretContext,
|
||||||
|
isBlankNode,
|
||||||
|
isGapPosition,
|
||||||
|
isPrintableKey,
|
||||||
|
hasContent,
|
||||||
|
splitCiteAtRange,
|
||||||
|
createPlainCommentElement,
|
||||||
|
placeCaretAtEnd,
|
||||||
|
};
|
||||||
|
});
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Settings of the add-on: default values, validation of stored or entered
|
||||||
|
* values, and selection of the settings that apply to a sender identity.
|
||||||
|
* Also holds the list of compose script files, which the background and the
|
||||||
|
* tests share.
|
||||||
|
*
|
||||||
|
* Storage layout: storage.local[STORAGE_KEY] holds one object
|
||||||
|
* { global: {...}, identities: { "<identityId>": {...} } }
|
||||||
|
* in which every profile is a complete settings object. If the sender
|
||||||
|
* identity of a message has its own profile, that profile applies as a whole
|
||||||
|
* (it is not merged with the global settings); otherwise the global settings
|
||||||
|
* apply.
|
||||||
|
*
|
||||||
|
* Where it runs:
|
||||||
|
* - Background: first entry of "background.scripts" in manifest.json.
|
||||||
|
* background.js reads the store with normalizeStore(), picks the settings
|
||||||
|
* of a compose tab with resolveSettings() and registers or injects the
|
||||||
|
* files listed in COMPOSE_SCRIPT_FILES.
|
||||||
|
* - Compose editor: first file of COMPOSE_SCRIPT_FILES. The compose script
|
||||||
|
* itself receives already resolved settings from the background through
|
||||||
|
* messages.
|
||||||
|
* - Options page: first script of options.html. options.js validates the
|
||||||
|
* form values with sanitizeSettings() and saves the whole store.
|
||||||
|
* - Node tests: loaded with require(); the compose and options page tests
|
||||||
|
* also evaluate it in jsdom windows.
|
||||||
|
*
|
||||||
|
* Load order: nothing has to be loaded before this file. It has no
|
||||||
|
* dependencies and creates globalThis.InlineComment if it does not exist yet;
|
||||||
|
* the other lib files add their functions to the same object.
|
||||||
|
*
|
||||||
|
* Data flow: storage.local -> normalizeStore() -> resolveSettings() ->
|
||||||
|
* settings sent to the compose window. On the options page: form values ->
|
||||||
|
* sanitizeSettings() -> store -> storage.local, and storage.onChanged makes
|
||||||
|
* the background push the new settings to all open compose windows.
|
||||||
|
*
|
||||||
|
* Classic script (not an ES module), because compose scripts cannot load
|
||||||
|
* modules. The UMD-style wrapper below makes the same file work as a browser
|
||||||
|
* script and as a CommonJS module for Node.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* UMD-style wrapper: builds the API of this file once and publishes it.
|
||||||
|
* Under Node (tests) the API becomes module.exports. In every environment it
|
||||||
|
* is also merged into root.InlineComment, where the extension scripts loaded
|
||||||
|
* after this file find it; Object.assign keeps members that other files have
|
||||||
|
* already added to that shared namespace.
|
||||||
|
* @param {typeof globalThis} root - global object that holds the shared
|
||||||
|
* InlineComment namespace
|
||||||
|
* @param {function(): object} factory - runs in strict mode and returns the
|
||||||
|
* public API (constants and functions) of this file; it has no side effects
|
||||||
|
*/
|
||||||
|
(function (root, factory) {
|
||||||
|
const api = factory();
|
||||||
|
if (typeof module === "object" && module.exports) {
|
||||||
|
module.exports = api;
|
||||||
|
}
|
||||||
|
root.InlineComment = Object.assign(root.InlineComment || {}, api);
|
||||||
|
})(globalThis, function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Key in storage.local under which the whole store (global settings plus
|
||||||
|
* per-identity profiles) is saved as one object. The background watches
|
||||||
|
* this key in storage.onChanged to forward changes to open compose windows.
|
||||||
|
*/
|
||||||
|
const STORAGE_KEY = "settings";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Files injected into every compose window, as paths relative to the
|
||||||
|
* extension root. background.js registers them for new compose windows and
|
||||||
|
* injects them into windows that are already open on install or update;
|
||||||
|
* the tests check that the files exist and load the same list.
|
||||||
|
* The order matters: the lib files must add their functions to
|
||||||
|
* globalThis.InlineComment before compose/compose.js runs and uses them.
|
||||||
|
*/
|
||||||
|
const COMPOSE_SCRIPT_FILES = Object.freeze([
|
||||||
|
"lib/settings.js",
|
||||||
|
"lib/marker.js",
|
||||||
|
"lib/quote.js",
|
||||||
|
"compose/compose.js",
|
||||||
|
]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allowed values of the splitMode setting, i.e. how the quote is split:
|
||||||
|
* - "native": the editor splits the quote (like Enter inside the quote),
|
||||||
|
* so Ctrl+Z can undo the split. If the editor does not split it, the
|
||||||
|
* compose script falls back to the manual split.
|
||||||
|
* - "manual": the add-on splits the quote itself with DOM operations
|
||||||
|
* (fallback; the split is not on the undo stack).
|
||||||
|
*/
|
||||||
|
const SPLIT_MODES = Object.freeze(["native", "manual"]);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default value of every setting. The keys define the complete set of
|
||||||
|
* settings: sanitizeSettings() keeps only these keys, and the options page
|
||||||
|
* iterates them to fill and read its form. The type of each default decides
|
||||||
|
* how a value is validated (booleans by type, strings by the key-specific
|
||||||
|
* rules in sanitizeSettings()) and whether the options page uses the
|
||||||
|
* "checked" or the "value" property of the form control.
|
||||||
|
* - enabledByDefault: whether the add-on is switched on in a compose
|
||||||
|
* window as long as its toolbar button has not been clicked there
|
||||||
|
* - template: marker template; {name}, {initials}, {email}, {date} and
|
||||||
|
* {time} are replaced (see marker.js)
|
||||||
|
* - marker*, text*: color, bold and italic of the marker and of the
|
||||||
|
* comment text (HTML messages only)
|
||||||
|
* - highlight, highlightColor: optional background color behind the whole
|
||||||
|
* comment (HTML messages only)
|
||||||
|
* - blankLineBefore, blankLineAfter: 1em margin above and below the
|
||||||
|
* comment; in plain-text messages only blankLineBefore applies, as a
|
||||||
|
* line break before the marker
|
||||||
|
* - splitMode: one of SPLIT_MODES
|
||||||
|
* - debug: diagnostic console output (console.debug) of the compose script
|
||||||
|
*/
|
||||||
|
const DEFAULT_SETTINGS = Object.freeze({
|
||||||
|
enabledByDefault: true,
|
||||||
|
template: "[{initials}]:",
|
||||||
|
markerColor: "#003d80",
|
||||||
|
markerBold: true,
|
||||||
|
markerItalic: false,
|
||||||
|
textColor: "#0056b3",
|
||||||
|
textBold: false,
|
||||||
|
textItalic: false,
|
||||||
|
highlight: false,
|
||||||
|
highlightColor: "#fff8c5",
|
||||||
|
blankLineBefore: false,
|
||||||
|
blankLineAfter: false,
|
||||||
|
splitMode: "native",
|
||||||
|
debug: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Maximum length of the marker template; sanitizeSettings() cuts longer
|
||||||
|
* input off. options.html sets the same limit as maxlength of the template
|
||||||
|
* input, so both must be changed together.
|
||||||
|
*/
|
||||||
|
const MAX_TEMPLATE_LENGTH = 200;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Accepted color format: "#rrggbb" only, the format that
|
||||||
|
* <input type="color"> uses. Colors are written into the inline CSS of the
|
||||||
|
* comment in the message, so nothing else may pass.
|
||||||
|
*/
|
||||||
|
const COLOR_PATTERN = /^#[0-9a-f]{6}$/i;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a complete, valid settings object built from untrusted input
|
||||||
|
* (stored data or form values). The result contains every key of
|
||||||
|
* DEFAULT_SETTINGS; unknown keys are dropped and missing or invalid values
|
||||||
|
* are replaced by their default, so callers never have to check values.
|
||||||
|
* Rules per key:
|
||||||
|
* - boolean defaults: only real booleans are accepted
|
||||||
|
* - template: a string that is not empty or whitespace only, kept as typed
|
||||||
|
* but cut to MAX_TEMPLATE_LENGTH UTF-16 code units (the check runs
|
||||||
|
* before the cut)
|
||||||
|
* - keys ending in "Color": must match "#rrggbb", returned in lower case
|
||||||
|
* - splitMode: one of SPLIT_MODES
|
||||||
|
* - any other key: always the default
|
||||||
|
* Does not modify the input.
|
||||||
|
* @param {unknown} input - candidate settings; anything that is not a
|
||||||
|
* non-null object yields the defaults
|
||||||
|
* @returns {typeof DEFAULT_SETTINGS} new settings object
|
||||||
|
*/
|
||||||
|
function sanitizeSettings(input) {
|
||||||
|
const source = input && typeof input === "object" ? input : {};
|
||||||
|
const result = {};
|
||||||
|
for (const [key, fallback] of Object.entries(DEFAULT_SETTINGS)) {
|
||||||
|
const value = source[key];
|
||||||
|
if (typeof fallback === "boolean") {
|
||||||
|
result[key] = typeof value === "boolean" ? value : fallback;
|
||||||
|
} else if (key === "template") {
|
||||||
|
result[key] =
|
||||||
|
typeof value === "string" && value.trim() !== ""
|
||||||
|
? value.slice(0, MAX_TEMPLATE_LENGTH)
|
||||||
|
: fallback;
|
||||||
|
} else if (key.endsWith("Color")) {
|
||||||
|
result[key] =
|
||||||
|
typeof value === "string" && COLOR_PATTERN.test(value)
|
||||||
|
? value.toLowerCase()
|
||||||
|
: fallback;
|
||||||
|
} else if (key === "splitMode") {
|
||||||
|
result[key] = SPLIT_MODES.includes(value) ? value : fallback;
|
||||||
|
} else {
|
||||||
|
// No validation rule for this key: never take an unchecked value.
|
||||||
|
result[key] = fallback;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Brings the stored value into the expected store shape. The global
|
||||||
|
* settings are always present (defaults if missing); identity profiles that
|
||||||
|
* are null or not objects are dropped, all others are sanitized. Every read
|
||||||
|
* of the store goes through this function, so stores with missing keys
|
||||||
|
* (e.g. from an older version) or damaged data never reach the rest of the
|
||||||
|
* add-on.
|
||||||
|
* normalizeStore(null) gives an empty store with default global settings.
|
||||||
|
* Returns new objects and does not modify the input.
|
||||||
|
* @param {unknown} stored - content of storage.local[STORAGE_KEY]; may be
|
||||||
|
* undefined, null or malformed
|
||||||
|
* @returns {{ global: typeof DEFAULT_SETTINGS,
|
||||||
|
* identities: Record<string, typeof DEFAULT_SETTINGS> }} sanitized store
|
||||||
|
*/
|
||||||
|
function normalizeStore(stored) {
|
||||||
|
const source = stored && typeof stored === "object" ? stored : {};
|
||||||
|
const identities = {};
|
||||||
|
if (source.identities && typeof source.identities === "object") {
|
||||||
|
for (const [id, profile] of Object.entries(source.identities)) {
|
||||||
|
if (profile && typeof profile === "object") {
|
||||||
|
identities[id] = sanitizeSettings(profile);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return { global: sanitizeSettings(source.global), identities };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the settings that apply to a sender identity: its own profile if
|
||||||
|
* the store has one, otherwise the global settings. A profile replaces the
|
||||||
|
* global settings as a whole; values are not merged key by key. The store
|
||||||
|
* is normalized first, so the result is always complete and valid.
|
||||||
|
* @param {unknown} stored - store as read from storage.local, raw or
|
||||||
|
* already normalized; it is passed through normalizeStore() either way
|
||||||
|
* @param {string|null|undefined} identityId - id of the sender identity;
|
||||||
|
* an empty or missing id selects the global settings
|
||||||
|
* @returns {typeof DEFAULT_SETTINGS} sanitized settings for that identity
|
||||||
|
*/
|
||||||
|
function resolveSettings(stored, identityId) {
|
||||||
|
const store = normalizeStore(stored);
|
||||||
|
// Own properties only, so inherited members such as "toString" never
|
||||||
|
// count as a profile.
|
||||||
|
if (
|
||||||
|
identityId &&
|
||||||
|
Object.prototype.hasOwnProperty.call(store.identities, identityId)
|
||||||
|
) {
|
||||||
|
return store.identities[identityId];
|
||||||
|
}
|
||||||
|
return store.global;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Public API: merged into globalThis.InlineComment and exported for Node.
|
||||||
|
return {
|
||||||
|
STORAGE_KEY,
|
||||||
|
COMPOSE_SCRIPT_FILES,
|
||||||
|
SPLIT_MODES,
|
||||||
|
DEFAULT_SETTINGS,
|
||||||
|
MAX_TEMPLATE_LENGTH,
|
||||||
|
sanitizeSettings,
|
||||||
|
normalizeStore,
|
||||||
|
resolveSettings,
|
||||||
|
};
|
||||||
|
});
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"manifest_version": 3,
|
||||||
|
"name": "__MSG_extensionName__",
|
||||||
|
"description": "__MSG_extensionDescription__",
|
||||||
|
"default_locale": "en",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"author": "Oliver Herb",
|
||||||
|
"browser_specific_settings": {
|
||||||
|
"gecko": {
|
||||||
|
"id": "inline-comment@ih-engineering.de",
|
||||||
|
"strict_min_version": "128.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"background": {
|
||||||
|
"scripts": ["lib/settings.js", "lib/marker.js", "background.js"]
|
||||||
|
},
|
||||||
|
"permissions": ["compose", "scripting", "storage", "accountsRead"],
|
||||||
|
"compose_action": {
|
||||||
|
"default_title": "__MSG_actionTitle__",
|
||||||
|
"default_icon": "icons/icon.svg",
|
||||||
|
"default_area": "maintoolbar"
|
||||||
|
},
|
||||||
|
"options_ui": {
|
||||||
|
"page": "options/options.html"
|
||||||
|
},
|
||||||
|
"icons": {
|
||||||
|
"16": "icons/icon.svg",
|
||||||
|
"32": "icons/icon.svg",
|
||||||
|
"64": "icons/icon.svg"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Styles of the options page (options.html). Follows the system light or
|
||||||
|
* dark theme through the color variables below.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/* Theme colors (light default, dark override) */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
--bg: #ffffff;
|
||||||
|
--fg: #1d1d1f;
|
||||||
|
--muted: #5f6368;
|
||||||
|
--border: #d0d4da;
|
||||||
|
--accent: #0056b3;
|
||||||
|
--quote: #729fcf;
|
||||||
|
color-scheme: light dark;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root {
|
||||||
|
--bg: #1f2023;
|
||||||
|
--fg: #e8e8ea;
|
||||||
|
--muted: #a0a4aa;
|
||||||
|
--border: #3a3d42;
|
||||||
|
--accent: #6ea8fe;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Page layout and headings */
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--fg);
|
||||||
|
font:
|
||||||
|
14px/1.5 system-ui,
|
||||||
|
sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
max-width: 720px;
|
||||||
|
margin: 0 auto;
|
||||||
|
padding: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 1.4em;
|
||||||
|
margin: 0 0 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h2 {
|
||||||
|
font-size: 1.05em;
|
||||||
|
margin: 0 0 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sections and form controls */
|
||||||
|
|
||||||
|
section,
|
||||||
|
details {
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
padding: 12px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
fieldset {
|
||||||
|
border: 0;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Disabled while an identity uses the inherited settings. */
|
||||||
|
fieldset:disabled {
|
||||||
|
opacity: 0.55;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: block;
|
||||||
|
margin: 4px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
label.check {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="text"],
|
||||||
|
select {
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 480px;
|
||||||
|
padding: 6px 8px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 4px;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Help texts */
|
||||||
|
|
||||||
|
.intro,
|
||||||
|
.hint {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Placeholder chips and footer button (pill buttons) */
|
||||||
|
|
||||||
|
.chips {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 6px;
|
||||||
|
margin-top: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chips button,
|
||||||
|
footer button {
|
||||||
|
padding: 4px 10px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 999px;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--accent);
|
||||||
|
font: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Appearance options: three columns, one color and its checkboxes per row */
|
||||||
|
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
|
gap: 4px 16px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Preview: fixed light colors in both themes, so it looks like a typical
|
||||||
|
* email body in the compose window.
|
||||||
|
*/
|
||||||
|
|
||||||
|
.preview {
|
||||||
|
padding: 12px;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 6px;
|
||||||
|
background: #ffffff;
|
||||||
|
color: #1d1d1f;
|
||||||
|
}
|
||||||
|
|
||||||
|
.preview blockquote {
|
||||||
|
margin: 0;
|
||||||
|
padding-left: 8px;
|
||||||
|
border-left: 2px solid var(--quote);
|
||||||
|
color: #555555;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Footer with reset button and save status */
|
||||||
|
|
||||||
|
footer {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 12px;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
padding-top: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
#status {
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Narrow windows: one column for the appearance options */
|
||||||
|
|
||||||
|
@media (max-width: 520px) {
|
||||||
|
.grid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,189 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<!--
|
||||||
|
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/.
|
||||||
|
-->
|
||||||
|
<!--
|
||||||
|
Options page of the add-on: global settings plus optional own settings
|
||||||
|
per sender identity (the "Profile" section).
|
||||||
|
Texts are localized at runtime by src/lib/i18n.js via the data-i18n and
|
||||||
|
data-i18n-aria-label keys; the English texts below are the fallback.
|
||||||
|
The form is filled and saved by options.js.
|
||||||
|
-->
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<title data-i18n="optionsTitle">Inline Comment – Settings</title>
|
||||||
|
<link rel="stylesheet" href="options.css" />
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main>
|
||||||
|
<h1 data-i18n="extensionName">Inline Comment</h1>
|
||||||
|
<p class="intro" data-i18n="optionsIntro">
|
||||||
|
When you type inside a quote, the add-on splits the quote at that point
|
||||||
|
and puts your marker in front of your own text. In the compose window,
|
||||||
|
the “Inline Comment” button turns the feature on or off for that email.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2 data-i18n="profileHeading">Profile</h2>
|
||||||
|
<label for="profile" data-i18n="profileLabel">Settings for</label>
|
||||||
|
<select id="profile"></select>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" id="ownProfile" />
|
||||||
|
<span data-i18n="ownProfileLabel"
|
||||||
|
>Own settings for this identity</span
|
||||||
|
>
|
||||||
|
</label>
|
||||||
|
<p class="hint" id="profileHint"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<form id="settings" autocomplete="off">
|
||||||
|
<fieldset id="fields">
|
||||||
|
<section>
|
||||||
|
<h2 data-i18n="behaviorHeading">Behavior</h2>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="enabledByDefault" />
|
||||||
|
<span data-i18n="enabledByDefaultLabel"
|
||||||
|
>Active automatically in new emails</span
|
||||||
|
>
|
||||||
|
</label>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2 data-i18n="markerHeading">Marker</h2>
|
||||||
|
<label for="template" data-i18n="templateLabel">Template</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="template"
|
||||||
|
name="template"
|
||||||
|
maxlength="200"
|
||||||
|
spellcheck="false"
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
class="chips"
|
||||||
|
id="chips"
|
||||||
|
aria-label="Insert placeholder"
|
||||||
|
data-i18n-aria-label="placeholderChipsLabel"
|
||||||
|
>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
data-var="{initials}"
|
||||||
|
data-i18n="chipInitials"
|
||||||
|
>
|
||||||
|
Initials
|
||||||
|
</button>
|
||||||
|
<button type="button" data-var="{name}" data-i18n="chipName">
|
||||||
|
Name
|
||||||
|
</button>
|
||||||
|
<button type="button" data-var="{email}" data-i18n="chipEmail">
|
||||||
|
Email
|
||||||
|
</button>
|
||||||
|
<button type="button" data-var="{date}" data-i18n="chipDate">
|
||||||
|
Date
|
||||||
|
</button>
|
||||||
|
<button type="button" data-var="{time}" data-i18n="chipTime">
|
||||||
|
Time
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2 data-i18n="appearanceHeading">Appearance</h2>
|
||||||
|
<div class="grid">
|
||||||
|
<label>
|
||||||
|
<span data-i18n="markerColorLabel">Marker color</span>
|
||||||
|
<input type="color" name="markerColor" />
|
||||||
|
</label>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="markerBold" />
|
||||||
|
<span data-i18n="boldLabel">bold</span>
|
||||||
|
</label>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="markerItalic" />
|
||||||
|
<span data-i18n="italicLabel">italic</span>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span data-i18n="textColorLabel">Text color</span>
|
||||||
|
<input type="color" name="textColor" />
|
||||||
|
</label>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="textBold" />
|
||||||
|
<span data-i18n="boldLabel">bold</span>
|
||||||
|
</label>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="textItalic" />
|
||||||
|
<span data-i18n="italicLabel">italic</span>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span data-i18n="highlightColorLabel">Background</span>
|
||||||
|
<input type="color" name="highlightColor" />
|
||||||
|
</label>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="highlight" />
|
||||||
|
<span data-i18n="highlightLabel">highlight</span>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2 data-i18n="spacingHeading">Spacing</h2>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="blankLineBefore" />
|
||||||
|
<span data-i18n="blankLineBeforeLabel"
|
||||||
|
>Blank line before the comment</span
|
||||||
|
>
|
||||||
|
</label>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="blankLineAfter" />
|
||||||
|
<span data-i18n="blankLineAfterLabel"
|
||||||
|
>Blank line after the comment</span
|
||||||
|
>
|
||||||
|
</label>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section>
|
||||||
|
<h2 data-i18n="previewHeading">Preview</h2>
|
||||||
|
<div id="preview" class="preview"></div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary data-i18n="advancedSummary">Advanced</summary>
|
||||||
|
<label for="splitMode" data-i18n="splitModeLabel"
|
||||||
|
>Split the quote</label
|
||||||
|
>
|
||||||
|
<select id="splitMode" name="splitMode">
|
||||||
|
<option value="native" data-i18n="splitModeNative">
|
||||||
|
by the editor (Ctrl+Z works)
|
||||||
|
</option>
|
||||||
|
<option value="manual" data-i18n="splitModeManual">
|
||||||
|
by the add-on (fallback)
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
<label class="check">
|
||||||
|
<input type="checkbox" name="debug" />
|
||||||
|
<span data-i18n="debugLabel"
|
||||||
|
>Diagnostic output in the error console</span
|
||||||
|
>
|
||||||
|
</label>
|
||||||
|
</details>
|
||||||
|
</fieldset>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
<button type="button" id="reset" data-i18n="resetButton">
|
||||||
|
Reset to defaults
|
||||||
|
</button>
|
||||||
|
<span id="status" role="status"></span>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
<script src="../lib/settings.js"></script>
|
||||||
|
<script src="../lib/marker.js"></script>
|
||||||
|
<script src="../lib/i18n.js"></script>
|
||||||
|
<script src="options.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,480 @@
|
|||||||
|
/*
|
||||||
|
* 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/.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Options page script: edits the settings for all sender identities (the
|
||||||
|
* global profile) and optional own profiles per sender identity, shows a live
|
||||||
|
* preview of the comment and resets a profile to the defaults. There is no
|
||||||
|
* save button: changes are saved automatically 300 ms after the last edit.
|
||||||
|
*
|
||||||
|
* Runs on the options page only (manifest "options_ui", options.html). The
|
||||||
|
* Node tests (test/i18n.test.js) also run it in jsdom with a fake WebExtension
|
||||||
|
* API. It is not loaded in the background or in the compose editor.
|
||||||
|
*
|
||||||
|
* Needs these scripts loaded first (options.html does this): lib/settings.js,
|
||||||
|
* lib/marker.js and lib/i18n.js, which attach their functions to
|
||||||
|
* globalThis.InlineComment. Its <script> tag is the last one in <body>, so all
|
||||||
|
* page elements exist when it runs. Reading the identities needs the
|
||||||
|
* "accountsRead" permission, saving needs "storage".
|
||||||
|
*
|
||||||
|
* Data flow:
|
||||||
|
* storage.local[STORAGE_KEY] -> normalizeStore() -> in-memory `store`
|
||||||
|
* -> writeForm() fills the form for the selected profile.
|
||||||
|
* Form edit -> readForm() (sanitized) -> store.global or
|
||||||
|
* store.identities[id] -> renderPreview() and a debounced save() that
|
||||||
|
* writes the whole store back.
|
||||||
|
* The background script listens to storage.onChanged and pushes the new
|
||||||
|
* settings to all open compose windows. This page itself reads storage only
|
||||||
|
* once, when it loads.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps the page logic so its constants and state stay out of the global
|
||||||
|
* scope that the classic lib scripts share. Runs once when the script loads.
|
||||||
|
*/
|
||||||
|
(function () {
|
||||||
|
"use strict";
|
||||||
|
|
||||||
|
/** WebExtension API: `messenger` in Thunderbird/Betterbird, or `browser`. */
|
||||||
|
const api = globalThis.messenger || globalThis.browser;
|
||||||
|
/** Library functions from lib/settings.js, lib/marker.js and lib/i18n.js. */
|
||||||
|
const IC = globalThis.InlineComment;
|
||||||
|
/** Prefix for console output, so the add-on's messages are easy to find. */
|
||||||
|
const LOG_PREFIX = "[Inline Comment]";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a translated message from _locales in the UI language.
|
||||||
|
* @param {string} key - Message name from messages.json.
|
||||||
|
* @param {string|string[]} [substitutions] - Values for the message's
|
||||||
|
* placeholders, e.g. the identity label for "profileOwnSettings".
|
||||||
|
* @returns {string} The translated text, or an empty string if the key is
|
||||||
|
* unknown.
|
||||||
|
*/
|
||||||
|
function msg(key, substitutions) {
|
||||||
|
return api.i18n.getMessage(key, substitutions);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set the page language (used e.g. by screen readers) and replace the
|
||||||
|
// English fallback texts and labels in options.html with the messages of
|
||||||
|
// the UI language.
|
||||||
|
document.documentElement.lang = api.i18n.getUILanguage();
|
||||||
|
IC.localizeDocument(document, msg);
|
||||||
|
|
||||||
|
/** Fictitious sender for the preview when no identity can be read. */
|
||||||
|
const SAMPLE_IDENTITY = {
|
||||||
|
name: msg("previewSampleName"),
|
||||||
|
email: msg("previewSampleEmail"),
|
||||||
|
};
|
||||||
|
/** Normal label of the reset button, restored after the confirm step. */
|
||||||
|
const RESET_LABEL = msg("resetButton");
|
||||||
|
|
||||||
|
// Page elements, see options.html.
|
||||||
|
const form = document.getElementById("settings");
|
||||||
|
const fields = document.getElementById("fields");
|
||||||
|
const profileSelect = document.getElementById("profile");
|
||||||
|
const ownProfile = document.getElementById("ownProfile");
|
||||||
|
const profileHint = document.getElementById("profileHint");
|
||||||
|
const preview = document.getElementById("preview");
|
||||||
|
const status = document.getElementById("status");
|
||||||
|
const resetButton = document.getElementById("reset");
|
||||||
|
const chips = document.getElementById("chips");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Complete settings store ({ global, identities }) as saved in
|
||||||
|
* storage.local. Starts as an empty store with default global settings, so
|
||||||
|
* it always has a valid shape. init() replaces it with the stored data;
|
||||||
|
* after that the event handlers replace its profiles (store.global,
|
||||||
|
* store.identities[id]) and save() writes the whole object.
|
||||||
|
*/
|
||||||
|
let store = IC.normalizeStore(null);
|
||||||
|
/** Sender identities (MailIdentity objects) listed in the drop-down. */
|
||||||
|
let identities = [];
|
||||||
|
/** Selected profile: "" is the global profile, otherwise an identity ID. */
|
||||||
|
let profileId = "";
|
||||||
|
/** Timer handle of the pending debounced save, see scheduleSave(). */
|
||||||
|
let saveTimer = null;
|
||||||
|
/** True while the reset button waits for its confirming second click. */
|
||||||
|
let resetArmed = false;
|
||||||
|
/** Timer handle that ends the reset confirm step, see disarmReset(). */
|
||||||
|
let resetTimer = null;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the sender identities of all accounts.
|
||||||
|
* Uses identities.list() when the API offers it, otherwise collects the
|
||||||
|
* identities from accounts.list(). Errors are logged and yield an empty
|
||||||
|
* list, so the page still works with the global profile alone.
|
||||||
|
* @returns {Promise<object[]>} MailIdentity objects (id, name, email, ...).
|
||||||
|
*/
|
||||||
|
async function loadIdentities() {
|
||||||
|
try {
|
||||||
|
if (api.identities && api.identities.list) {
|
||||||
|
return await api.identities.list();
|
||||||
|
}
|
||||||
|
const accounts = await api.accounts.list();
|
||||||
|
return accounts.flatMap((account) => account.identities || []);
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(LOG_PREFIX, "Identities not readable:", error);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Builds the display text of an identity for the profile drop-down.
|
||||||
|
* @param {{name?: string, email: string}} identity - Sender identity.
|
||||||
|
* @returns {string} "Name <email>", or only the address if there is no name.
|
||||||
|
*/
|
||||||
|
function identityLabel(identity) {
|
||||||
|
return identity.name
|
||||||
|
? `${identity.name} <${identity.email}>`
|
||||||
|
: identity.email;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tells whether an identity has its own settings profile.
|
||||||
|
* Uses hasOwnProperty, so names inherited from Object.prototype never count
|
||||||
|
* as a profile (the same check as resolveSettings() in lib/settings.js).
|
||||||
|
* @param {string} id - Identity ID; "" stands for the global profile.
|
||||||
|
* @returns {boolean} True if `id` is not empty and has an entry in
|
||||||
|
* store.identities.
|
||||||
|
*/
|
||||||
|
function hasOwnProfile(id) {
|
||||||
|
return (
|
||||||
|
Boolean(id) && Object.prototype.hasOwnProperty.call(store.identities, id)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the settings shown for the selected profile: the identity's own
|
||||||
|
* profile if it has one, otherwise the global settings, which are also the
|
||||||
|
* ones that apply to such an identity in the compose window.
|
||||||
|
* @returns {object} Settings object from `store` (not a copy).
|
||||||
|
*/
|
||||||
|
function currentSettings() {
|
||||||
|
return hasOwnProfile(profileId)
|
||||||
|
? store.identities[profileId]
|
||||||
|
: store.global;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Copies a settings object into the form controls.
|
||||||
|
* Walks the keys of DEFAULT_SETTINGS and fills the control named like each
|
||||||
|
* key; the type of the default decides whether `checked` or `value` is set.
|
||||||
|
* Keys without a control are skipped. Setting the properties fires no input
|
||||||
|
* events, so this does not trigger onFormChange().
|
||||||
|
* @param {object} settings - Sanitized settings object.
|
||||||
|
*/
|
||||||
|
function writeForm(settings) {
|
||||||
|
for (const [key, fallback] of Object.entries(IC.DEFAULT_SETTINGS)) {
|
||||||
|
const input = form.elements.namedItem(key);
|
||||||
|
if (!input) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (typeof fallback === "boolean") {
|
||||||
|
input.checked = settings[key];
|
||||||
|
} else {
|
||||||
|
input.value = settings[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reads the form controls into a settings object and sanitizes it.
|
||||||
|
* Invalid values (e.g. an empty template) and settings without a control
|
||||||
|
* fall back to their defaults through sanitizeSettings().
|
||||||
|
* @returns {object} Complete, valid settings object.
|
||||||
|
*/
|
||||||
|
function readForm() {
|
||||||
|
const values = {};
|
||||||
|
for (const [key, fallback] of Object.entries(IC.DEFAULT_SETTINGS)) {
|
||||||
|
const input = form.elements.namedItem(key);
|
||||||
|
if (input) {
|
||||||
|
values[key] =
|
||||||
|
typeof fallback === "boolean" ? input.checked : input.value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return IC.sanitizeSettings(values);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Picks the identity whose name and address fill the preview marker: the
|
||||||
|
* selected identity, for the global profile the first identity, and the
|
||||||
|
* sample identity if no identity could be read.
|
||||||
|
* @returns {{name?: string, email?: string}} Identity for markerVariables().
|
||||||
|
*/
|
||||||
|
function previewIdentity() {
|
||||||
|
const selected = identities.find((identity) => identity.id === profileId);
|
||||||
|
return selected || identities[0] || SAMPLE_IDENTITY;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders a sample reply into #preview: a quoted question, the comment
|
||||||
|
* with the current marker and styles, and a second quoted paragraph, like a
|
||||||
|
* quote split by the add-on.
|
||||||
|
* Takes the settings from the form (readForm()), which always holds the
|
||||||
|
* values of the shown profile, and uses the same createCommentNode() as the
|
||||||
|
* compose script, so it shows the comment as it is inserted into an HTML
|
||||||
|
* message.
|
||||||
|
* Side effect: replaces the children of #preview.
|
||||||
|
*/
|
||||||
|
function renderPreview() {
|
||||||
|
const settings = readForm();
|
||||||
|
const marker = IC.renderTemplate(
|
||||||
|
settings.template,
|
||||||
|
IC.markerVariables(previewIdentity(), new Date()),
|
||||||
|
);
|
||||||
|
// Built with DOM APIs only: marker and messages are always plain text.
|
||||||
|
/**
|
||||||
|
* Creates a quoted paragraph marked like a mail quote (type="cite").
|
||||||
|
* @param {string} text - Quoted text, set as plain text.
|
||||||
|
* @returns {HTMLQuoteElement} New <blockquote> element.
|
||||||
|
*/
|
||||||
|
const quote = (text) => {
|
||||||
|
const element = document.createElement("blockquote");
|
||||||
|
element.setAttribute("type", "cite");
|
||||||
|
element.textContent = text;
|
||||||
|
return element;
|
||||||
|
};
|
||||||
|
const comment = IC.createCommentNode(
|
||||||
|
document,
|
||||||
|
marker,
|
||||||
|
msg("previewCommentStart"),
|
||||||
|
settings,
|
||||||
|
"preview",
|
||||||
|
);
|
||||||
|
// Rest of the comment, as if the user had kept typing after the first
|
||||||
|
// word(s) in previewCommentStart.
|
||||||
|
comment.append(` ${msg("previewCommentRest")}`);
|
||||||
|
preview.replaceChildren(
|
||||||
|
quote(msg("previewQuoteQuestion")),
|
||||||
|
comment,
|
||||||
|
quote(msg("previewQuoteRequest")),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Switches the page to a profile and shows its settings.
|
||||||
|
* For an identity without own settings, the fields and the reset button are
|
||||||
|
* disabled and show the global settings it inherits. The "own settings"
|
||||||
|
* checkbox is disabled for the global profile, which has nothing to inherit.
|
||||||
|
* Side effects: sets `profileId`; updates checkbox, fieldset, reset button,
|
||||||
|
* hint text, form values and preview.
|
||||||
|
* @param {string} id - Identity ID, or "" for the global profile.
|
||||||
|
*/
|
||||||
|
function showProfile(id) {
|
||||||
|
profileId = id;
|
||||||
|
const own = hasOwnProfile(id);
|
||||||
|
ownProfile.checked = own;
|
||||||
|
ownProfile.disabled = !id;
|
||||||
|
fields.disabled = Boolean(id) && !own;
|
||||||
|
resetButton.disabled = fields.disabled;
|
||||||
|
if (!id) {
|
||||||
|
profileHint.textContent = msg("profileHintGlobal");
|
||||||
|
} else if (own) {
|
||||||
|
profileHint.textContent = msg("profileHintOwn");
|
||||||
|
} else {
|
||||||
|
profileHint.textContent = msg("profileHintInherited");
|
||||||
|
}
|
||||||
|
writeForm(currentSettings());
|
||||||
|
renderPreview();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves the store 300 ms after the last change (debounce).
|
||||||
|
* Text and color inputs fire an event per keystroke or drag step, and every
|
||||||
|
* write triggers storage.onChanged and a settings push to all open compose
|
||||||
|
* windows, so a burst of changes should lead to a single write.
|
||||||
|
* Side effect: shows "…" in the status line until save() has run.
|
||||||
|
*/
|
||||||
|
function scheduleSave() {
|
||||||
|
clearTimeout(saveTimer);
|
||||||
|
status.textContent = "…";
|
||||||
|
saveTimer = setTimeout(save, 300);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Writes the whole store to storage.local[STORAGE_KEY] and shows the result
|
||||||
|
* in the status line. Errors are logged instead of thrown, because the
|
||||||
|
* function runs from a timer where nobody could handle them.
|
||||||
|
* @returns {Promise<void>} Resolves when the write has finished or failed.
|
||||||
|
*/
|
||||||
|
async function save() {
|
||||||
|
try {
|
||||||
|
await api.storage.local.set({ [IC.STORAGE_KEY]: store });
|
||||||
|
status.textContent = msg("statusSaved");
|
||||||
|
} catch (error) {
|
||||||
|
status.textContent = msg("statusSaveFailed");
|
||||||
|
console.error(LOG_PREFIX, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handles every edit in the settings form (its input and change events and
|
||||||
|
* a placeholder inserted with a chip button): stores the sanitized form
|
||||||
|
* values in the selected profile, re-renders the preview and schedules a
|
||||||
|
* save.
|
||||||
|
* For an identity that inherits the global settings the store is left
|
||||||
|
* unchanged (its fields are disabled anyway).
|
||||||
|
*/
|
||||||
|
function onFormChange() {
|
||||||
|
const settings = readForm();
|
||||||
|
if (!profileId) {
|
||||||
|
store.global = settings;
|
||||||
|
} else if (hasOwnProfile(profileId)) {
|
||||||
|
store.identities[profileId] = settings;
|
||||||
|
}
|
||||||
|
renderPreview();
|
||||||
|
scheduleSave();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rebuilds the profile drop-down: first the global profile (value ""), then
|
||||||
|
* one entry per identity, labelled as "own settings" when it has its own
|
||||||
|
* profile, and selects `profileId` again.
|
||||||
|
* Side effect: replaces the options of #profile.
|
||||||
|
*/
|
||||||
|
function fillProfileSelect() {
|
||||||
|
profileSelect.replaceChildren(new Option(msg("profileAllIdentities"), ""));
|
||||||
|
for (const identity of identities) {
|
||||||
|
const label = identityLabel(identity);
|
||||||
|
const text = hasOwnProfile(identity.id)
|
||||||
|
? msg("profileOwnSettings", [label])
|
||||||
|
: label;
|
||||||
|
profileSelect.append(new Option(text, identity.id));
|
||||||
|
}
|
||||||
|
profileSelect.value = profileId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ends the reset confirm step and restores the normal button label.
|
||||||
|
* Called by the 4-second timer and right before a confirmed reset. It also
|
||||||
|
* cancels a pending timer, so the timer of an earlier confirm step cannot
|
||||||
|
* end a later one early.
|
||||||
|
*/
|
||||||
|
function disarmReset() {
|
||||||
|
clearTimeout(resetTimer);
|
||||||
|
resetTimer = null;
|
||||||
|
resetArmed = false;
|
||||||
|
resetButton.textContent = RESET_LABEL;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads the stored settings and the identities, shows the global profile
|
||||||
|
* and attaches the event listeners.
|
||||||
|
* The listeners are attached only after loading, so an edit made earlier
|
||||||
|
* cannot save the default placeholder store over the real settings.
|
||||||
|
* @returns {Promise<void>} Rejects e.g. if storage.local cannot be read.
|
||||||
|
*/
|
||||||
|
async function init() {
|
||||||
|
const stored = await api.storage.local.get(IC.STORAGE_KEY);
|
||||||
|
store = IC.normalizeStore(stored[IC.STORAGE_KEY]);
|
||||||
|
identities = await loadIdentities();
|
||||||
|
fillProfileSelect();
|
||||||
|
showProfile("");
|
||||||
|
|
||||||
|
// "input" fires while typing or dragging a color, "change" when a value
|
||||||
|
// is committed; checkboxes and drop-downs fire both. Handling both is
|
||||||
|
// safe: a duplicate call stores the same values again, re-renders the
|
||||||
|
// preview and restarts the save timer.
|
||||||
|
form.addEventListener("input", onFormChange);
|
||||||
|
form.addEventListener("change", onFormChange);
|
||||||
|
|
||||||
|
/** Shows the profile chosen in the drop-down. */
|
||||||
|
profileSelect.addEventListener("change", () =>
|
||||||
|
showProfile(profileSelect.value),
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turns the own profile of the selected identity on or off.
|
||||||
|
* On: the profile starts as a copy of the global settings (a separate
|
||||||
|
* object, so editing it leaves the global profile unchanged). Off: the
|
||||||
|
* profile is deleted and the identity uses the global settings again.
|
||||||
|
* Does nothing for the global profile (the checkbox is disabled there).
|
||||||
|
* Side effects: rebuilds the drop-down, shows the profile again with
|
||||||
|
* showProfile() (form, enabled state, hint, preview) and schedules a
|
||||||
|
* save.
|
||||||
|
*/
|
||||||
|
ownProfile.addEventListener("change", () => {
|
||||||
|
if (!profileId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (ownProfile.checked) {
|
||||||
|
store.identities[profileId] = { ...store.global };
|
||||||
|
} else {
|
||||||
|
delete store.identities[profileId];
|
||||||
|
}
|
||||||
|
fillProfileSelect();
|
||||||
|
showProfile(profileId);
|
||||||
|
scheduleSave();
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inserts the placeholder of a clicked chip button (its data-var, e.g.
|
||||||
|
* "{initials}") into the template at the caret, replacing any selected
|
||||||
|
* text, and puts the caret after it. One delegated listener on #chips
|
||||||
|
* serves all chip buttons. Clicks are ignored while the fields are
|
||||||
|
* disabled (identity that inherits the global settings); the chip buttons
|
||||||
|
* are inside the disabled fieldset then, so this is only a safeguard.
|
||||||
|
* @param {MouseEvent} event - Click somewhere inside #chips.
|
||||||
|
*/
|
||||||
|
chips.addEventListener("click", (event) => {
|
||||||
|
const button = event.target.closest("button[data-var]");
|
||||||
|
if (!button || fields.disabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const input = form.elements.namedItem("template");
|
||||||
|
// Without a known caret position, append at the end.
|
||||||
|
const start = input.selectionStart ?? input.value.length;
|
||||||
|
const end = input.selectionEnd ?? start;
|
||||||
|
input.setRangeText(button.dataset.var, start, end, "end");
|
||||||
|
input.focus();
|
||||||
|
// setRangeText() fires no input event, so apply the change explicitly.
|
||||||
|
onFormChange();
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resets the selected profile to the defaults in two steps: the first
|
||||||
|
* click turns the label into a confirm question for up to 4 seconds (see
|
||||||
|
* disarmReset()), a second click within that time resets. This guards
|
||||||
|
* against an accidental reset. A profile that inherits the global
|
||||||
|
* settings is left unchanged (the button is disabled there).
|
||||||
|
* Side effects: changes the button label; on the confirming click
|
||||||
|
* replaces the profile in `store`, updates form and preview and
|
||||||
|
* schedules a save.
|
||||||
|
*/
|
||||||
|
resetButton.addEventListener("click", () => {
|
||||||
|
if (!resetArmed) {
|
||||||
|
resetArmed = true;
|
||||||
|
resetButton.textContent = msg("resetConfirm");
|
||||||
|
resetTimer = setTimeout(disarmReset, 4000);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
disarmReset();
|
||||||
|
// A fresh, unfrozen copy of DEFAULT_SETTINGS.
|
||||||
|
const defaults = IC.sanitizeSettings({});
|
||||||
|
if (!profileId) {
|
||||||
|
store.global = defaults;
|
||||||
|
} else if (hasOwnProfile(profileId)) {
|
||||||
|
store.identities[profileId] = defaults;
|
||||||
|
}
|
||||||
|
writeForm(currentSettings());
|
||||||
|
renderPreview();
|
||||||
|
scheduleSave();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shows a load error in the status line and logs it when init() rejects,
|
||||||
|
* e.g. because storage.local cannot be read.
|
||||||
|
* @param {unknown} error - Reason for the rejection.
|
||||||
|
*/
|
||||||
|
init().catch((error) => {
|
||||||
|
status.textContent = msg("statusLoadFailed");
|
||||||
|
console.error(LOG_PREFIX, error);
|
||||||
|
});
|
||||||
|
})();
|
||||||
@@ -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