Skip to content

Build your personal knowledge base with Trilium Notes

client/text editor: use adaptive colors for font color and font background color

Adorian Doran4170efb8c8f3
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 6d2829effc..5e136a2f97 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -32,6 +32,9 @@
--tree-item-light-theme-max-color-lightness: 50;
--tree-item-dark-theme-min-color-lightness: 75;
+
+ /* Picks the half of the light-dark() text colors that matches the theme. */
+ color-scheme: var(--theme-style);
}
body#trilium-app.motion-disabled *,
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index dd41f51d6f..a7d721c4fb 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -4408,6 +4408,9 @@
"missing-icon": "missing icon",
"invalid-symbol": "the markdown symbol should be one character, excepting \"[\", \" \", \"X\", and \"]\"",
"duplicate-symbol": "duplicate markdown symbol"
+ },
+ "colors": {
+ "pink": "Pink"
}
},
"collection_filter": {
diff --git a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
index ffe42e8658..ef6d474f66 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
@@ -2,6 +2,7 @@
// DOMPurify relies on browser-faithful DOM traversal (NodeIterator); happy-dom
// mishandles it and strips valid markup (surfaced by dompurify 3.4.8). Run the
// sanitization-dependent specs under jsdom, which matches real-browser behavior.
+import { HIGHLIGHT_BACKGROUND } from "@triliumnext/commons";
import { describe, expect, it } from "vitest";
import { findActiveBlock, renderWithSourceLines } from "./Markdown.js";
@@ -247,7 +248,7 @@ describe("renderWithSourceLines", () => {
});
it("renders ==text== as a highlight, surviving sanitization", () => {
- expect(html("==hi==")).toBe('<p><span style="background-color:hsl(60, 75%, 60%);">hi</span></p>');
+ expect(html("==hi==")).toBe(`<p><span style="background-color:${HIGHLIGHT_BACKGROUND};">hi</span></p>`);
expect(html("a == b")).toBe("<p>a == b</p>");
});
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 59dacd0eef..87749ebb23 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -18,6 +18,7 @@ import { resolveContentLanguage } from "../../../utils/formatters.js";
import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams.js";
import buildAiAssistantStream, { type AiNoteLocationProvider, buildAiAssistantQuickActions } from "./ai_assistant_stream.js";
import diffAiResponse from "./ai_diff.js";
+import { buildFontColorConfig } from "./font_colors.js";
import { buildQuoteTransformation, resolveQuoteSetting } from "./quotes.js";
import { buildCustomTransformations, parseCustomReplacements } from "./replacements.js";
import { buildToolbarConfig } from "./toolbar.js";
@@ -161,6 +162,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
alignment: {
options: [ "left", "right", "center", "justify"]
},
+ ...buildFontColorConfig(),
link: {
defaultProtocol: "https://",
allowedProtocols: ALLOWED_PROTOCOLS,
diff --git a/apps/client/src/widgets/type_widgets/text/font_colors.spec.ts b/apps/client/src/widgets/type_widgets/text/font_colors.spec.ts
new file mode 100644
index 0000000000..dc1e64318e
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/font_colors.spec.ts
@@ -0,0 +1,40 @@
+import { adaptColor, HIGHLIGHT_BACKGROUND } from "@triliumnext/commons";
+import { describe, expect, it, vi } from "vitest";
+
+import { DEFAULT_COLOR_PALETTE } from "../../react/ColorPicker.js";
+import { buildFontColorConfig } from "./font_colors.js";
+
+vi.mock("../../../services/i18n.js", () => ({ t: (key: string) => key }));
+
+const SOURCES = [ "#000000", "#555555", "#aaaaaa", "#ffffff", ...DEFAULT_COLOR_PALETTE ];
+
+describe("buildFontColorConfig", () => {
+ it("lists four greys, then every note color hue, four to a row", () => {
+ for (const palette of Object.values(buildFontColorConfig())) {
+ expect(palette.columns).toBe(4);
+ expect(palette.colors.map(({ label }) => label)).toEqual([
+ "Black", "Dim grey", "Light grey", "White",
+ "Red", "Orange", "Yellow", "Light green", "Green", "Aquamarine", "Turquoise",
+ "Light blue", "Blue", "Purple", "text-editor.colors.pink"
+ ]);
+ }
+ });
+
+ it("stores each swatch as the pair for its role, without spaces", () => {
+ const { fontColor, fontBackgroundColor } = buildFontColorConfig();
+ expect(fontColor.colors.map(({ color }) => color))
+ .toEqual(SOURCES.map((color) => adaptColor(color, "text")));
+ expect(fontBackgroundColor.colors.map(({ color }) => color))
+ .toEqual(SOURCES.map((color) => adaptColor(color, "background")));
+
+ // CKEditor strips spaces from a color when a note loads, and matches swatches exactly.
+ for (const { color } of [ ...fontColor.colors, ...fontBackgroundColor.colors ]) {
+ expect(color).toMatch(/^light-dark\(#[0-9a-f]{6},#[0-9a-f]{6}\)$/);
+ }
+ });
+
+ it("uses the palette's yellow for Markdown highlights", () => {
+ const { colors } = buildFontColorConfig().fontBackgroundColor;
+ expect(colors.find(({ label }) => label === "Yellow")?.color).toBe(HIGHLIGHT_BACKGROUND);
+ });
+});
diff --git a/apps/client/src/widgets/type_widgets/text/font_colors.ts b/apps/client/src/widgets/type_widgets/text/font_colors.ts
new file mode 100644
index 0000000000..1e690be1b3
--- /dev/null
+++ b/apps/client/src/widgets/type_widgets/text/font_colors.ts
@@ -0,0 +1,42 @@
+import { adaptColor, type AdaptiveColorRole } from "@triliumnext/commons";
+
+import { t } from "../../../services/i18n.js";
+import { DEFAULT_COLOR_PALETTE } from "../../react/ColorPicker.js";
+
+/**
+ * The swatches of the Font Color and Font Background Color dropdowns: four greys, then the hues of
+ * the note color palette, each turned into a light and dark theme pair.
+ */
+export function buildFontColorConfig() {
+ return {
+ fontColor: buildPalette("text"),
+ fontBackgroundColor: buildPalette("background")
+ };
+}
+
+const GREYS = [
+ { color: "#000000", label: "Black" },
+ { color: "#555555", label: "Dim grey" },
+ { color: "#aaaaaa", label: "Light grey" },
+ { color: "#ffffff", label: "White" }
+];
+
+/** The names of the `DEFAULT_COLOR_PALETTE` hues, which CKEditor translates on its own. */
+const HUE_LABELS = [
+ "Red", "Orange", "Yellow", "Light green", "Green", "Aquamarine", "Turquoise", "Light blue",
+ "Blue", "Purple"
+];
+
+function buildPalette(role: AdaptiveColorRole) {
+ // CKEditor has no name for pink, so it comes from the app's own catalogue.
+ const hueLabels = [ ...HUE_LABELS, t("text-editor.colors.pink") ];
+ const swatches = [
+ ...GREYS,
+ ...DEFAULT_COLOR_PALETTE.map((color, index) => ({ color, label: hueLabels[index] }))
+ ];
+
+ return {
+ colors: swatches.map((swatch) => ({ ...swatch, color: adaptColor(swatch.color, role) })),
+ columns: 4
+ };
+}
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html
index a73baac44e..bfaaa6adc1 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Markdown.html
@@ -123,7 +123,7 @@
<li>
<p>Highlights (background color) are supported both via the <code>==</code> Markdown
syntax, as well as the canonical HTML representation in Trilium:</p><pre><code class="language-text-x-trilium-auto">==highlighted==
-&lt;span style="background-color:hsl(0,0%,100%);"&gt;Highlighted&lt;/span&gt;</code></pre>
+&lt;span style="background-color:light-dark(#e8e4bd,#494917);"&gt;Highlighted&lt;/span&gt;</code></pre>
</li>
</ul>
<h3>Links</h3>
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/General formatting.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/General formatting.html
index cb8023e476..d264868ff2 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/General formatting.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/General formatting.html
@@ -72,8 +72,14 @@
palette or any color can be selected using the color picker.</p>
<p>Once there is at least one color defined in the document, it will appear
in the list for easy reuse.</p>
-<p>When selecting a foreground or a background color, consider the contrast
- if switching between a dark theme or a light <a href="#root/_help_Wy267RK4M69c">theme</a>.</p>
+<p>Colors adapt to the <a href="#root/_help_Wy267RK4M69c">theme</a>. When
+ a color is applied, Trilium saves two shades of it, one for light themes
+ and one for dark themes, so the text stays readable after switching between
+ them. The hue stays the same: red text is red in both themes, only lighter
+ or darker. This applies to the palette, the color picker and the document
+ colors alike.</p>
+<p>Colors applied with older versions of Trilium are kept exactly as they
+ are, until a new color is applied to that text.</p>
<p>To remove either the background or foreground color of a text, select
the corresponding formatting button and press <em>Remove color</em> or use
the <em>Remove formatting</em> toolbar item.</p>
diff --git a/docs/User Guide/User Guide/Note Types/Markdown.md b/docs/User Guide/User Guide/Note Types/Markdown.md
index 8e7c9bb283..fe3c32c834 100644
--- a/docs/User Guide/User Guide/Note Types/Markdown.md
+++ b/docs/User Guide/User Guide/Note Types/Markdown.md
@@ -88,7 +88,7 @@ The following features are supported by Trilium's Markdown format and will show
```
==highlighted==
- <span style="background-color:hsl(0,0%,100%);">Highlighted</span>
+ <span style="background-color:light-dark(#e8e4bd,#494917);">Highlighted</span>
```
### Links
diff --git a/docs/User Guide/User Guide/Note Types/Text/General formatting.md b/docs/User Guide/User Guide/Note Types/Text/General formatting.md
index 79a050dceb..c326088441 100644
--- a/docs/User Guide/User Guide/Note Types/Text/General formatting.md
+++ b/docs/User Guide/User Guide/Note Types/Text/General formatting.md
@@ -65,7 +65,9 @@ Selected text can be colored with one of the predefined colors from a palette or
Once there is at least one color defined in the document, it will appear in the list for easy reuse.
-When selecting a foreground or a background color, consider the contrast if switching between a dark theme or a light [theme](../../Basic%20Concepts%20and%20Features/Themes.md).
+Colors adapt to the [theme](../../Basic%20Concepts%20and%20Features/Themes.md). When a color is applied, Trilium saves two shades of it, one for light themes and one for dark themes, so the text stays readable after switching between them. The hue stays the same: red text is red in both themes, only lighter or darker. This applies to the palette, the color picker and the document colors alike.
+
+Colors applied with older versions of Trilium are kept exactly as they are, until a new color is applied to that text.
To remove either the background or foreground color of a text, select the corresponding formatting button and press _Remove color_ or use the _Remove formatting_ toolbar item.
diff --git a/packages/ckeditor5/src/plugins.ts b/packages/ckeditor5/src/plugins.ts
index b30c5420b1..f6fa129f33 100644
--- a/packages/ckeditor5/src/plugins.ts
+++ b/packages/ckeditor5/src/plugins.ts
@@ -37,6 +37,7 @@ import CopyLinkUrlButton from "./plugins/copy_link_url.js";
import ImageActions from "./plugins/image_actions.js";
import ClipboardBareImage from "./plugins/clipboard_bare_image.js";
import ClipboardImageEmbed from "./plugins/clipboard_image_embed.js";
+import AdaptiveFontColor from "./plugins/adaptive_font_color.js";
import TriliumSnippets from "./plugins/snippets/snippets.js";
import TriliumAiAssistant from "./plugins/ai_assistant/ai_assistant.js";
@@ -111,6 +112,7 @@ const TRILIUM_PLUGINS: typeof Plugin[] = [
ImageActions,
ClipboardImageEmbed,
ClipboardBareImage,
+ AdaptiveFontColor,
TriliumSnippets,
TriliumAiAssistant,
FindInLinkWidgets,
diff --git a/packages/ckeditor5/src/plugins/adaptive_font_color.spec.ts b/packages/ckeditor5/src/plugins/adaptive_font_color.spec.ts
new file mode 100644
index 0000000000..e5b3d44685
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/adaptive_font_color.spec.ts
@@ -0,0 +1,58 @@
+import { adaptColor } from "@triliumnext/commons";
+import {
+ _getModelData as getModelData,
+ _setModelData as setModelData,
+ type ClassicEditor,
+ Essentials,
+ FontBackgroundColor,
+ FontColor,
+ Paragraph
+} from "ckeditor5";
+import { beforeEach, describe, expect, it } from "vitest";
+
+import { createTestEditor } from "../../test/editor-kit.js";
+import AdaptiveFontColor from "./adaptive_font_color.js";
+
+describe("AdaptiveFontColor", () => {
+ let editor: ClassicEditor;
+
+ beforeEach(async () => {
+ editor = await createTestEditor([
+ Essentials, Paragraph, FontColor, FontBackgroundColor, AdaptiveFontColor
+ ]);
+ setModelData(editor.model, "<paragraph>[text]</paragraph>");
+ });
+
+ it("stores a picked color as a light and dark theme pair", () => {
+ editor.execute("fontColor", { value: "hsl(0, 75%, 60%)" });
+ editor.execute("fontBackgroundColor", { value: "hsl(60,75%,60%)" });
+
+ const text = adaptColor("hsl(0, 75%, 60%)", "text");
+ const background = adaptColor("hsl(60,75%,60%)", "background");
+ expect(text).toMatch(/^light-dark\(/);
+ expect(getModelData(editor.model, { withoutSelection: true })).toBe(
+ `<paragraph><$text fontBackgroundColor="${background}" fontColor="${text}">`
+ + "text</$text></paragraph>"
+ );
+ });
+
+ it("keeps a pair through saving and loading the note", () => {
+ editor.execute("fontColor", { value: "#e64d4d" });
+ const saved = editor.getData();
+ expect(saved).toContain(`color:${adaptColor("#e64d4d", "text")}`);
+
+ editor.setData(saved);
+ expect(editor.getData()).toBe(saved);
+ });
+
+ it("keeps a pair as it is, and still removes a color", () => {
+ const pair = "light-dark(#b81e2c,#ff9f96)";
+ editor.execute("fontColor", { value: pair });
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe(`<paragraph><$text fontColor="${pair}">text</$text></paragraph>`);
+
+ editor.execute("fontColor");
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toBe("<paragraph>text</paragraph>");
+ });
+});
diff --git a/packages/ckeditor5/src/plugins/adaptive_font_color.ts b/packages/ckeditor5/src/plugins/adaptive_font_color.ts
new file mode 100644
index 0000000000..f01d951601
--- /dev/null
+++ b/packages/ckeditor5/src/plugins/adaptive_font_color.ts
@@ -0,0 +1,43 @@
+import { adaptColor, type AdaptiveColorRole } from "@triliumnext/commons";
+import {
+ type CommandExecuteEvent,
+ FontBackgroundColorEditing,
+ FontColorEditing,
+ Plugin
+} from "ckeditor5";
+
+/**
+ * Stores Font Color and Font Background Color as a light and dark theme pair (see `adaptColor`),
+ * whether the color comes from a palette swatch, the color picker or the document colors.
+ */
+export default class AdaptiveFontColor extends Plugin {
+
+ static get requires() {
+ return [ FontColorEditing, FontBackgroundColorEditing ] as const;
+ }
+
+ static get pluginName() {
+ return "AdaptiveFontColor" as const;
+ }
+
+ init() {
+ this.adaptCommandValue("fontColor", "text");
+ this.adaptCommandValue("fontBackgroundColor", "background");
+ }
+
+ private adaptCommandValue(commandName: string, role: AdaptiveColorRole) {
+ const command = this.editor.commands.get(commandName);
+ /* v8 ignore next 3 -- the required editing plugins register both commands. */
+ if (!command) {
+ return;
+ }
+
+ this.listenTo<CommandExecuteEvent>(command, "execute", (_eventInfo, args) => {
+ const options = args[0] as { value?: string } | undefined;
+ if (options?.value) {
+ args[0] = { ...options, value: adaptColor(options.value, role) };
+ }
+ }, { priority: "high" });
+ }
+
+}
diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.ts
index d522f4500e..add128ff57 100644
--- a/packages/commons/src/index.ts
+++ b/packages/commons/src/index.ts
@@ -1,4 +1,5 @@
export * from "./lib/i18n.js";
+export * from "./lib/adaptive_color.js";
export * from "./lib/katex_macros.js";
export * from "./lib/options_interface.js";
export * from "./lib/keyboard_actions_interface.js";
diff --git a/packages/commons/src/lib/adaptive_color.spec.ts b/packages/commons/src/lib/adaptive_color.spec.ts
new file mode 100644
index 0000000000..60c6a2caf8
--- /dev/null
+++ b/packages/commons/src/lib/adaptive_color.spec.ts
@@ -0,0 +1,93 @@
+import { describe, expect, it } from "vitest";
+
+import { adaptColor } from "./adaptive_color.js";
+
+const HUES = [
+ "#e64d4d", "#e6994d", "#e5e64d", "#99e64d", "#4de64d", "#4de699",
+ "#4de5e6", "#4d99e6", "#4d4de6", "#994de6", "#e64db3"
+];
+const GREYS = [ "#000000", "#555555", "#aaaaaa", "#ffffff" ];
+
+/** The Next themes' page background and default text color. */
+const PAGE = {
+ light: { background: "#ffffff", text: "#000000" },
+ dark: { background: "#242424", text: "#cccccc" }
+};
+
+describe("adaptColor", () => {
+ it("keeps the hue and moves the lightness into each theme's band", () => {
+ expect(adaptColor("#e64d4d", "text")).toBe("light-dark(#b81e2c,#ff9f96)");
+ expect(adaptColor("#e64d4d", "background")).toBe("light-dark(#ffdad6,#713531)");
+ expect(adaptColor("#e5e64d", "background")).toBe("light-dark(#e8e4bd,#494917)");
+ });
+
+ it("keeps every palette color readable in both themes", () => {
+ const colors = [ ...HUES, ...GREYS ];
+ const text = colors.map((color) => pairOf(adaptColor(color, "text")));
+ const backgrounds = colors.map((color) => pairOf(adaptColor(color, "background")));
+
+ for (const theme of [ "light", "dark" ] as const) {
+ const { background: page, text: defaultText } = PAGE[theme];
+ for (const pair of text) {
+ expect(contrast(pair[theme], page)).toBeGreaterThanOrEqual(4.5);
+ }
+ for (const pair of backgrounds) {
+ expect(contrast(defaultText, pair[theme])).toBeGreaterThanOrEqual(4.5);
+ for (const textPair of text) {
+ expect(contrast(textPair[theme], pair[theme])).toBeGreaterThanOrEqual(4.5);
+ }
+ }
+ }
+ });
+
+ it("gives each grey a shade of its own in both themes", () => {
+ for (const role of [ "text", "background" ] as const) {
+ const pairs = GREYS.map((grey) => pairOf(adaptColor(grey, role)));
+ expect(new Set(pairs.map(({ light }) => light)).size).toBe(GREYS.length);
+ expect(new Set(pairs.map(({ dark }) => dark)).size).toBe(GREYS.length);
+ }
+ expect(adaptColor("#000000", "text")).toBe("light-dark(#000000,#b9b9b9)");
+ expect(adaptColor("#ffffff", "text")).toBe("light-dark(#5e5e5e,#ffffff)");
+ });
+
+ it("reads hex, rgb() and hsl() in both syntaxes", () => {
+ const expected = adaptColor("#e64d4d", "text");
+ expect(adaptColor("#E64D4D", "text")).toBe(expected);
+ expect(adaptColor("rgb(230, 77, 77)", "text")).toBe(expected);
+ expect(adaptColor("rgb(230 77 77)", "text")).toBe(expected);
+ expect(adaptColor("#f00", "text")).toBe(adaptColor("#ff0000", "text"));
+
+ // The color picker's output, and the same value after CKEditor strips its spaces.
+ const fromPicker = adaptColor("hsl(210, 75%, 60%)", "background");
+ expect(fromPicker).toMatch(/^light-dark\(#[0-9a-f]{6},#[0-9a-f]{6}\)$/);
+ expect(adaptColor("hsl(210,75%,60%)", "background")).toBe(fromPicker);
+ expect(adaptColor("hsl(210deg 75% 60%)", "background")).toBe(fromPicker);
+ });
+
+ it("returns pairs, alpha colors and unknown values unchanged", () => {
+ for (const value of [
+ "light-dark(#b81e2c,#ff9f96)", "rgba(0, 0, 0, 0.5)", "rgb(0 0 0 / 50%)",
+ "#11223344", "red", "var(--accent)", "#12345", ""
+ ]) {
+ expect(adaptColor(value, "text")).toBe(value);
+ }
+ });
+});
+
+function pairOf(value: string) {
+ const match = /^light-dark\((#[0-9a-f]{6}),(#[0-9a-f]{6})\)$/.exec(value);
+ expect(match).not.toBeNull();
+ return { light: match?.[1] ?? "", dark: match?.[2] ?? "" };
+}
+
+function contrast(first: string, second: string) {
+ const [ a, b ] = [ luminance(first), luminance(second) ];
+ return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
+}
+
+function luminance(hex: string) {
+ const [ r, g, b ] = [ 1, 3, 5 ]
+ .map((start) => parseInt(hex.slice(start, start + 2), 16) / 255)
+ .map((c) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+}
diff --git a/packages/commons/src/lib/adaptive_color.ts b/packages/commons/src/lib/adaptive_color.ts
new file mode 100644
index 0000000000..6aac1923c4
--- /dev/null
+++ b/packages/commons/src/lib/adaptive_color.ts
@@ -0,0 +1,160 @@
+/** Whether a color is used for text (Font Color) or behind it (Font Background Color). */
+export type AdaptiveColorRole = "text" | "background";
+
+/**
+ * Turns a color into a `light-dark(#light,#dark)` pair, so text and highlights stay readable in
+ * both the light and the dark theme. The hue is kept; the CIELAB lightness is moved into the band
+ * of the role and theme, and the chroma is capped.
+ *
+ * @param color a hex, `rgb()` or `hsl()` color. Anything else, including a color that is already
+ * a pair, is returned unchanged.
+ */
+export function adaptColor(color: string, role: AdaptiveColorRole): string {
+ const rgb = parseColor(color.trim());
+ if (!rgb) {
+ return color;
+ }
+
+ const lab = rgbToLab(rgb);
+ const bands = BANDS[role];
+ return `light-dark(${fitToBand(lab, bands.light)},${fitToBand(lab, bands.dark)})`;
+}
+
+type Rgb = [number, number, number];
+type Lab = [number, number, number];
+
+interface Band {
+ minLightness: number;
+ maxLightness: number;
+ maxChroma: number;
+}
+
+/**
+ * The CIELAB lightness range and chroma cap per role and theme. The limits keep text at 4.5:1 or
+ * more against the Next themes' page and against every highlight.
+ */
+const BANDS: Record<AdaptiveColorRole, Record<"light" | "dark", Band>> = {
+ text: {
+ light: { minLightness: 0, maxLightness: 40, maxChroma: Infinity },
+ dark: { minLightness: 75, maxLightness: 100, maxChroma: 55 }
+ },
+ background: {
+ light: { minLightness: 90, maxLightness: 100, maxChroma: 20 },
+ dark: { minLightness: 0, maxLightness: 30, maxChroma: 30 }
+ }
+};
+
+/** Below this CIELAB chroma a color counts as grey. */
+const GREY_CHROMA = 1.5;
+
+const D65_WHITE: Lab = [ 0.95047, 1, 1.08883 ];
+const LAB_EPSILON = 216 / 24389;
+const LAB_KAPPA = 24389 / 27;
+
+function fitToBand([ lightness, a, b ]: Lab, band: Band): string {
+ const chroma = Math.hypot(a, b);
+ const hue = Math.atan2(b, a);
+
+ // Greys are spread over the band instead of clamped, so each grey keeps a shade of its own.
+ if (chroma < GREY_CHROMA) {
+ const range = band.maxLightness - band.minLightness;
+ return lchToHex(band.minLightness + (lightness / 100) * range, 0, hue);
+ }
+
+ const clamped = Math.min(Math.max(lightness, band.minLightness), band.maxLightness);
+ return lchToHex(clamped, Math.min(chroma, band.maxChroma), hue);
+}
+
+/** Parses `#rgb`, `#rrggbb`, `rgb()` and `hsl()` without alpha into sRGB channels from 0 to 1. */
+function parseColor(color: string): Rgb | undefined {
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color)?.[1];
+ if (hex) {
+ const full = hex.length === 3 ? [ ...hex ].map((digit) => digit + digit).join("") : hex;
+ return [ 0, 2, 4 ].map((start) => parseInt(full.slice(start, start + 2), 16) / 255) as Rgb;
+ }
+
+ const match = /^(rgb|hsl)\(([^()]*)\)$/i.exec(color);
+ const parts = match?.[2].split(/[\s,]+/).filter(Boolean);
+ if (!match || parts?.length !== 3) {
+ return undefined;
+ }
+
+ const numbers = parts.map((part) => parseFloat(part));
+ if (numbers.some((value) => !Number.isFinite(value))) {
+ return undefined;
+ }
+
+ if (match[1].toLowerCase() === "rgb") {
+ return numbers.map((value, index) => {
+ const channel = parts[index].endsWith("%") ? value / 100 : value / 255;
+ return Math.min(1, Math.max(0, channel));
+ }) as Rgb;
+ }
+
+ return hslToRgb(numbers[0], numbers[1] / 100, numbers[2] / 100);
+}
+
+function hslToRgb(hue: number, saturation: number, lightness: number): Rgb {
+ const s = Math.min(1, Math.max(0, saturation));
+ const l = Math.min(1, Math.max(0, lightness));
+ const amount = s * Math.min(l, 1 - l);
+ const channel = (offset: number) => {
+ const k = (offset + hue / 30) % 12;
+ return l - amount * Math.max(-1, Math.min(k - 3, 9 - k, 1));
+ };
+ return [ channel(0), channel(8), channel(4) ];
+}
+
+const toLinear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4);
+const fromLinear = (c: number) => (c <= 0.0031308 ? 12.92 * c : 1.055 * c ** (1 / 2.4) - 0.055);
+
+function rgbToLab(rgb: Rgb): Lab {
+ const [ r, g, b ] = rgb.map(toLinear);
+ const x = 0.4124564 * r + 0.3575761 * g + 0.1804375 * b;
+ const y = 0.2126729 * r + 0.7151522 * g + 0.072175 * b;
+ const z = 0.0193339 * r + 0.119192 * g + 0.9503041 * b;
+ const f = (t: number) => (t > LAB_EPSILON ? Math.cbrt(t) : (LAB_KAPPA * t + 16) / 116);
+ const [ fx, fy, fz ] = [ x / D65_WHITE[0], y / D65_WHITE[1], z / D65_WHITE[2] ].map(f);
+ return [ 116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz) ];
+}
+
+function lchToLinearRgb(lightness: number, chroma: number, hue: number): Rgb {
+ const fy = (lightness + 16) / 116;
+ const fx = fy + (chroma * Math.cos(hue)) / 500;
+ const fz = fy - (chroma * Math.sin(hue)) / 200;
+ const inverse = (t: number) => (t ** 3 > LAB_EPSILON ? t ** 3 : (116 * t - 16) / LAB_KAPPA);
+ const x = inverse(fx) * D65_WHITE[0];
+ const yRatio = lightness > LAB_KAPPA * LAB_EPSILON ? fy ** 3 : lightness / LAB_KAPPA;
+ const y = yRatio * D65_WHITE[1];
+ const z = inverse(fz) * D65_WHITE[2];
+ return [
+ 3.2404542 * x - 1.5371385 * y - 0.4985314 * z,
+ -0.969266 * x + 1.8760108 * y + 0.041556 * z,
+ 0.0556434 * x - 0.2040259 * y + 1.0572252 * z
+ ];
+}
+
+const isInGamut = (rgb: Rgb) => rgb.every((c) => c >= -1e-7 && c <= 1 + 1e-7);
+
+/** Converts to hex, lowering the chroma until the color fits sRGB so that the hue is kept. */
+function lchToHex(lightness: number, chroma: number, hue: number): string {
+ let rgb = lchToLinearRgb(lightness, chroma, hue);
+ if (!isInGamut(rgb)) {
+ let low = 0;
+ let high = chroma;
+ for (let step = 0; step < 30; step++) {
+ const middle = (low + high) / 2;
+ if (isInGamut(lchToLinearRgb(lightness, middle, hue))) {
+ low = middle;
+ } else {
+ high = middle;
+ }
+ }
+ rgb = lchToLinearRgb(lightness, low, hue);
+ }
+
+ return `#${rgb
+ .map((c) => Math.round(fromLinear(Math.min(1, Math.max(0, c))) * 255))
+ .map((c) => c.toString(16).padStart(2, "0"))
+ .join("")}`;
+}
diff --git a/packages/commons/src/lib/markdown_renderer.spec.ts b/packages/commons/src/lib/markdown_renderer.spec.ts
index 7eec091b03..e3f3b5bfb9 100644
--- a/packages/commons/src/lib/markdown_renderer.spec.ts
+++ b/packages/commons/src/lib/markdown_renderer.spec.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { CustomMarkdownRenderer, demoteHeadings, extractCodeBlocks, renderToHtml } from "./markdown_renderer.js";
+import { HIGHLIGHT_BACKGROUND } from "./marked_extensions.js";
import { DEFAULT_TASK_STATES, DONE_TASK_STATE, NONE_TASK_STATE, type TaskStateDef } from "./task_states.js";
/** Identity sanitizer so we can assert the raw rendered HTML. */
@@ -630,7 +631,7 @@ describe("renderToHtml", () => {
});
describe("highlights (==text==)", () => {
- const HL = '<span style="background-color:hsl(60, 75%, 60%);">';
+ const HL = `<span style="background-color:${HIGHLIGHT_BACKGROUND};">`;
it("renders ==text== as a background-coloured span without any flag", () => {
expect(render("==hi==")).toBe(`<p>${HL}hi</span></p>`);
diff --git a/packages/commons/src/lib/marked_extensions.ts b/packages/commons/src/lib/marked_extensions.ts
index 281b92d75a..b74d0476f9 100644
--- a/packages/commons/src/lib/marked_extensions.ts
+++ b/packages/commons/src/lib/marked_extensions.ts
@@ -1,5 +1,7 @@
import type { Token, TokenizerAndRendererExtension } from "marked";
+import { adaptColor } from "./adaptive_color.js";
+
/**
* Escapes HTML special characters to prevent XSS attacks.
* Used for both attribute values and text content.
@@ -101,7 +103,7 @@ export function createTransclusionExtension(options: TransclusionOptions = {}):
}
/**
- * Background colour for highlights: CKEditor's stock palette yellow (`==…==` carries no colour
+ * Background colour for highlights: the text editor's palette Yellow (`==…==` carries no colour
* of its own). Matches the `<span style="background-color:…">` markup CKEditor's Font
* Background Color feature emits, so a highlight rendered into a text note round-trips as an
* editable highlight. Deliberately not `<mark>`, which General HTML Support does keep but
@@ -112,7 +114,7 @@ export function createTransclusionExtension(options: TransclusionOptions = {}):
* `==…==` and which have to keep their colour as inline HTML, so the two directions must agree
* on the exact value.
*/
-export const HIGHLIGHT_BACKGROUND = "hsl(60, 75%, 60%)";
+export const HIGHLIGHT_BACKGROUND = adaptColor("#e5e64d", "background");
/**
* Creates an extension for highlights: `==text==` → a background-coloured `<span>`.
diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.ts
index 75c7523b84..d4afbb0816 100644
--- a/packages/trilium-core/src/services/export/markdown.spec.ts
+++ b/packages/trilium-core/src/services/export/markdown.spec.ts
@@ -1,4 +1,4 @@
-import { trimIndentation } from "@triliumnext/commons";
+import { HIGHLIGHT_BACKGROUND, trimIndentation } from "@triliumnext/commons";
import { describe, expect,it } from "vitest";
import markdownExportService, { DEFAULT_ADMONITION_TYPE } from "./markdown.js";
@@ -852,6 +852,16 @@ describe("Markdown export", () => {
.toBe("A ==highlight== here.");
});
+ it("renders the theme-adaptive yellow highlight as ==text==", () => {
+ const yellow = `<span style="background-color:${HIGHLIGHT_BACKGROUND};">highlight</span>`;
+ expect(markdownExportService.toMarkdown(`<p>A ${yellow} here.</p>`))
+ .toBe("A ==highlight== here.");
+
+ // Another adaptive pair keeps its colour.
+ const red = `<span style="background-color:light-dark(#ffdad6,#713531)">red</span>`;
+ expect(markdownExportService.toMarkdown(`<p>${red}</p>`)).toBe(red);
+ });
+
it("keeps any other colour as inline HTML rather than repainting it yellow", () => {
// A different background colour...
expect(markdownExportService.toMarkdown(
diff --git a/packages/trilium-core/src/services/export/markdown.ts b/packages/trilium-core/src/services/export/markdown.ts
index 336628f46c..be690e12aa 100644
--- a/packages/trilium-core/src/services/export/markdown.ts
+++ b/packages/trilium-core/src/services/export/markdown.ts
@@ -547,9 +547,12 @@ function isPlainDefaultHighlight(node: HTMLElement): boolean {
const [ declaration ] = declarations;
return declaration.property === "background-color"
- && normalizeColor(declaration.value) === normalizeColor(HIGHLIGHT_BACKGROUND);
+ && DEFAULT_HIGHLIGHT_BACKGROUNDS.includes(normalizeColor(declaration.value));
}
+/** The current yellow, and the one highlights got before colors adapted to the theme. */
+const DEFAULT_HIGHLIGHT_BACKGROUNDS = [ HIGHLIGHT_BACKGROUND, "hsl(60, 75%, 60%)" ].map(normalizeColor);
+
function parseStyleDeclarations(style: string | null) {
return (style ?? "")
.split(";")
diff --git a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts
index 7934804625..30571d30f5 100644
--- a/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts
+++ b/packages/trilium-core/src/services/import/obsidian/importer.integration.spec.ts
@@ -1,3 +1,4 @@
+import { HIGHLIGHT_BACKGROUND } from "@triliumnext/commons";
import { ZipArchive } from "archiver";
import LZString from "lz-string";
import { PassThrough } from "stream";
@@ -235,7 +236,7 @@ describe("Obsidian importer — integration", () => {
const note = importRoot.getChildNotes().find((n) => n.title === "Note");
// The highlight survives sanitization as a CKEditor background-colour span; the comment is
// rendered as an HTML comment, which the sanitizer then strips.
- expect(decodeUtf8(note?.getContent() ?? "")).toBe('<p>A <span style="background-color:hsl(60, 75%, 60%);">highlight</span> and a comment.</p>');
+ expect(decodeUtf8(note?.getContent() ?? "")).toBe(`<p>A <span style="background-color:${HIGHLIGHT_BACKGROUND};">highlight</span> and a comment.</p>`);
});
it("drops the .base/.canvas files and the .obsidian config folder, but keeps an orphan attachment", async () => {
diff --git a/packages/trilium-core/src/services/note_format_conversion.spec.ts b/packages/trilium-core/src/services/note_format_conversion.spec.ts
index aa14b9ae41..c75dd79fcf 100644
--- a/packages/trilium-core/src/services/note_format_conversion.spec.ts
+++ b/packages/trilium-core/src/services/note_format_conversion.spec.ts
@@ -1,4 +1,4 @@
-import { trimIndentation } from "@triliumnext/commons";
+import { HIGHLIGHT_BACKGROUND, trimIndentation } from "@triliumnext/commons";
import { describe, expect, it } from "vitest";
import { getContext } from "./context.js";
@@ -55,13 +55,13 @@ describe("note format conversion", () => {
const original = "Some ==highlighted== text.";
const { content: html } = convertNoteContent("markdown", original, "title");
- expect(html).toContain('<span style="background-color:hsl(60, 75%, 60%);">highlighted</span>');
+ expect(html).toContain(`<span style="background-color:${HIGHLIGHT_BACKGROUND};">highlighted</span>`);
expect(convertNoteContent("html", html, "title").content).toBe(original);
});
it("preserves a default-yellow highlight applied in the editor across an HTML -> Markdown -> HTML round-trip", () => {
- const original = '<p>Some <span style="background-color:hsl(60, 75%, 60%);">highlighted</span> text.</p>';
+ const original = `<p>Some <span style="background-color:${HIGHLIGHT_BACKGROUND};">highlighted</span> text.</p>`;
const { content: markdown } = convertNoteContent("html", original, "title");
expect(markdown).toBe("Some ==highlighted== text.");
diff --git a/packages/trilium-core/src/services/sanitizer.spec.ts b/packages/trilium-core/src/services/sanitizer.spec.ts
index b8b0c53c4d..676a716b35 100644
--- a/packages/trilium-core/src/services/sanitizer.spec.ts
+++ b/packages/trilium-core/src/services/sanitizer.spec.ts
@@ -74,6 +74,19 @@ describe("sanitize", () => {
expect(sanitizeHtml(dirty)).toBe(dirty);
});
+ it("keeps a light-dark() text and background color pair", () => {
+ const style = "color:light-dark(#b81e2c,#ff9f96);"
+ + "background-color:light-dark(#e8e4bd,#494917)";
+ const dirty = `<p><span style="${style}">x</span></p>`;
+ expect(sanitizeHtml(dirty)).toBe(dirty);
+
+ // Only a pair of hex colors passes; anything else inside light-dark() is dropped.
+ expect(sanitizeHtml(`<span style="color:light-dark(red,url(x))">x</span>`))
+ .toBe("<span>x</span>");
+ expect(sanitizeHtml(`<td style="border-color:light-dark(#000000,#ffffff)">x</td>`))
+ .not.toContain("light-dark");
+ });
+
it("keeps a fractional image aspect-ratio (OneNote reports fractional pixel dimensions)", () => {
// CKEditor's usual integer ratio still passes...
expect(sanitizeHtml(`<img style="aspect-ratio:991/403" src="x.png" />`)).toContain("aspect-ratio:991/403");
diff --git a/packages/trilium-core/src/services/sanitizer.ts b/packages/trilium-core/src/services/sanitizer.ts
index ee2645f629..a8242637b5 100644
--- a/packages/trilium-core/src/services/sanitizer.ts
+++ b/packages/trilium-core/src/services/sanitizer.ts
@@ -36,6 +36,8 @@ export function sanitizeHtml(dirtyHtml: string) {
}
const colorRegex = [/^#(0x)?[0-9a-f]+$/i, /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/, /^hsl\(\s*(\d{1,3})\s*,\s*(\d{1,3})%\s*,\s*(\d{1,3})%\s*\)$/];
+ // The light and dark theme pair the text editor writes (see `adaptColor`).
+ const adaptiveColorRegex = /^light-dark\(\s*#[0-9a-f]{6}\s*,\s*#[0-9a-f]{6}\s*\)$/i;
const sizeRegex = [/^\d+\.?\d*(?:px|em|%)$/];
// to minimize document changes, compress H
@@ -57,8 +59,8 @@ export function sanitizeHtml(dirtyHtml: string) {
},
allowedStyles: {
"*": {
- color: colorRegex,
- "background-color": colorRegex,
+ color: [ ...colorRegex, adaptiveColorRegex ],
+ "background-color": [ ...colorRegex, adaptiveColorRegex ],
"margin-left": sizeRegex,
"padding-left": sizeRegex,
"text-align": [/^\s*(left|center|right|justify)\s*$/],