Skip to content

Build your personal knowledge base with Trilium Notes

client/adaptive colors: fallback to the original color when light-dark() is not supported

Adorian Doran69ebfb45e1c6
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 807fe0e5b1..9706bdadab 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -64,6 +64,17 @@
--adaptive-table-background-dark-max-chroma: 30;
}
+/* Without light-dark(), the inline adaptive color is dropped; show the color as picked instead. */
+@supports not (color: light-dark(#000, #fff)) {
+ [style*="--tn-color"] {
+ color: var(--tn-color) !important;
+ }
+
+ [style*="--tn-background"] {
+ background-color: var(--tn-background) !important;
+ }
+}
+
body#trilium-app.motion-disabled *,
body#trilium-app.motion-disabled *::before,
body#trilium-app.motion-disabled *::after {
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 ef6d474f66..74433e03ad 100644
--- a/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
+++ b/apps/client/src/widgets/type_widgets/markdown/Markdown.spec.ts
@@ -2,7 +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 { HIGHLIGHT_STYLE } from "@triliumnext/commons";
import { describe, expect, it } from "vitest";
import { findActiveBlock, renderWithSourceLines } from "./Markdown.js";
@@ -248,7 +248,7 @@ describe("renderWithSourceLines", () => {
});
it("renders ==text== as a highlight, surviving sanitization", () => {
- expect(html("==hi==")).toBe(`<p><span style="background-color:${HIGHLIGHT_BACKGROUND};">hi</span></p>`);
+ expect(html("==hi==")).toBe(`<p><span style="${HIGHLIGHT_STYLE}">hi</span></p>`);
expect(html("a == b")).toBe("<p>a == b</p>");
});
diff --git a/apps/client/src/widgets/type_widgets/text/color_palette.spec.ts b/apps/client/src/widgets/type_widgets/text/color_palette.spec.ts
index eb5a9ae6a9..586c763ca0 100644
--- a/apps/client/src/widgets/type_widgets/text/color_palette.spec.ts
+++ b/apps/client/src/widgets/type_widgets/text/color_palette.spec.ts
@@ -1,7 +1,9 @@
import {
- adaptColor,
DEFAULT_ADAPTIVE_COLOR_BANDS as DEFAULTS,
- HIGHLIGHT_BACKGROUND
+ HIGHLIGHT_BACKGROUND,
+ HIGHLIGHT_SOURCE,
+ splitAdaptiveColorValue,
+ toAdaptiveColorValue
} from "@triliumnext/commons";
import { describe, expect, it, vi } from "vitest";
@@ -25,16 +27,16 @@ describe("buildFontColorConfig", () => {
}
});
- it("stores each swatch as the pair for its role, without spaces", () => {
+ it("stores each swatch as its role's pair and the color as picked, without spaces", () => {
const { fontColor, fontBackgroundColor } = buildFontColorConfig(DEFAULTS);
expect(fontColor.colors.map(({ color }) => color))
- .toEqual(SOURCES.map((color) => adaptColor(color, "text")));
+ .toEqual(SOURCES.map((color) => toAdaptiveColorValue(color, "text")));
expect(fontBackgroundColor.colors.map(({ color }) => color))
- .toEqual(SOURCES.map((color) => adaptColor(color, "background")));
+ .toEqual(SOURCES.map((color) => toAdaptiveColorValue(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}\)$/);
+ expect(color).toMatch(/^light-dark\(#[0-9a-f]{6},#[0-9a-f]{6}\)\/\*#[0-9a-f]{6}\*\/$/);
}
});
@@ -48,13 +50,15 @@ describe("buildFontColorConfig", () => {
};
const { colors } = buildFontColorConfig(bands).fontBackgroundColor;
expect(colors.map(({ color }) => color))
- .toEqual(SOURCES.map((color) => adaptColor(color, "background", bands)));
- expect(colors[4].color).not.toBe(adaptColor(SOURCES[4], "background"));
+ .toEqual(SOURCES.map((color) => toAdaptiveColorValue(color, "background", bands)));
+ expect(colors[4].color).not.toBe(toAdaptiveColorValue(SOURCES[4], "background"));
});
it("matches the Markdown highlight's yellow with the default limits", () => {
const { colors } = buildFontColorConfig(DEFAULTS).fontBackgroundColor;
- expect(colors.find(({ label }) => label === "Yellow")?.color).toBe(HIGHLIGHT_BACKGROUND);
+ const yellow = colors.find(({ label }) => label === "Yellow")?.color ?? "";
+ expect(splitAdaptiveColorValue(yellow))
+ .toEqual({ color: HIGHLIGHT_BACKGROUND, source: HIGHLIGHT_SOURCE });
});
});
diff --git a/apps/client/src/widgets/type_widgets/text/color_palette.ts b/apps/client/src/widgets/type_widgets/text/color_palette.ts
index 2da53618f4..f50f397e10 100644
--- a/apps/client/src/widgets/type_widgets/text/color_palette.ts
+++ b/apps/client/src/widgets/type_widgets/text/color_palette.ts
@@ -1,11 +1,16 @@
-import { adaptColor, type AdaptiveColorBands, type AdaptiveColorRole } from "@triliumnext/commons";
+import {
+ type AdaptiveColorBands,
+ type AdaptiveColorRole,
+ toAdaptiveColorValue
+} 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 with the theme's `bands`.
+ * the note color palette, each turned into a light and dark theme pair with the theme's `bands`,
+ * with the color as picked kept (see `toAdaptiveColorValue`).
*/
export function buildFontColorConfig(bands: AdaptiveColorBands) {
return {
@@ -42,7 +47,7 @@ const HUE_LABELS = [
function buildAdaptedSwatches(role: AdaptiveColorRole, bands: AdaptiveColorBands) {
return buildSwatches().map((swatch) => ({
...swatch,
- color: adaptColor(swatch.color, role, bands)
+ color: toAdaptiveColorValue(swatch.color, role, bands)
}));
}
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 bfaaa6adc1..5fefdfc5c1 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:light-dark(#e8e4bd,#494917);"&gt;Highlighted&lt;/span&gt;</code></pre>
+&lt;span style="background-color:light-dark(#e8e4bd,#494917);--tn-background:#e5e64d;"&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 d264868ff2..bea9281f3a 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
@@ -80,6 +80,8 @@
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>Browsers too old to show the two shades, such as the mobile app on iOS
+ versions before 17.5, show the color exactly as it was picked instead.</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/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
index 88afde328a..91fd387c34 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Text/Tables.html
@@ -345,6 +345,9 @@ src="3_Tables_image.png" width="384" height="100">
To change the color, pick or type a new one.</p>
<p>Colors applied with older versions of Trilium are kept exactly as they
are, until a new color is applied.</p>
+<p>Browsers too old to show the two shades, such as the mobile app on iOS
+ versions before 17.5, show background colors exactly as they were picked,
+ and borders in their default color.</p>
<h2>Caption</h2>
<p>Press the&nbsp;<span class="tn-icon cke cke-caption"></span> button to
insert a caption or a text description of the table, which is going to
diff --git a/docs/User Guide/User Guide/Note Types/Markdown.md b/docs/User Guide/User Guide/Note Types/Markdown.md
index fe3c32c834..6b2f06bde3 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:light-dark(#e8e4bd,#494917);">Highlighted</span>
+ <span style="background-color:light-dark(#e8e4bd,#494917);--tn-background:#e5e64d;">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 c326088441..a47673d55d 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
@@ -69,6 +69,8 @@ Colors adapt to the [theme](../../Basic%20Concepts%20and%20Features/Themes.md).
Colors applied with older versions of Trilium are kept exactly as they are, until a new color is applied to that text.
+Browsers too old to show the two shades, such as the mobile app on iOS versions before 17.5, show the color exactly as it was picked instead.
+
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.
## Remove formatting
diff --git a/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.md
index cce325efed..9c1d80362f 100644
--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md
+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md
@@ -177,6 +177,8 @@ Once a color is applied, its field shows the saved value as `light-dark(…)`. T
Colors applied with older versions of Trilium are kept exactly as they are, until a new color is applied.
+Browsers too old to show the two shades, such as the mobile app on iOS versions before 17.5, show background colors exactly as they were picked, and borders in their default color.
+
## Caption
Press the <span class="tn-icon cke cke-caption"></span> button to insert a caption or a text description of the table, which is going to be displayed above the table.
diff --git a/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts b/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts
index a8fd5a042a..3fb358e095 100644
--- a/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts
+++ b/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts
@@ -1,4 +1,8 @@
-import { adaptColor, DEFAULT_ADAPTIVE_COLOR_BANDS } from "@triliumnext/commons";
+import {
+ adaptColor,
+ DEFAULT_ADAPTIVE_COLOR_BANDS,
+ toAdaptiveColorValue
+} from "@triliumnext/commons";
import {
_getModelData as getModelData,
_setModelData as setModelData,
@@ -27,42 +31,55 @@ describe("AdaptiveColors", () => {
setModelData(editor.model, "<paragraph>[text]</paragraph>");
});
- it("stores a picked text color as a light and dark theme pair", () => {
+ it("stores a picked text color as a pair, with the color as picked", () => {
editor.execute("fontColor", { value: "hsl(0, 75%, 60%)" });
- editor.execute("fontBackgroundColor", { value: "hsl(60,75%,60%)" });
+ editor.execute("fontBackgroundColor", { value: "#e5e64d" });
- const text = adaptColor("hsl(0, 75%, 60%)", "text");
- const background = adaptColor("hsl(60,75%,60%)", "background");
- expect(text).toMatch(/^light-dark\(/);
+ const text = toAdaptiveColorValue("hsl(0, 75%, 60%)", "text");
+ const background = toAdaptiveColorValue("#e5e64d", "background");
+ expect(text).toMatch(/^light-dark\(.+\)\/\*#[0-9a-f]{6}\*\/$/);
expect(getModelData(editor.model, { withoutSelection: true })).toBe(
`<paragraph><$text fontBackgroundColor="${background}" fontColor="${text}">`
+ "text</$text></paragraph>"
);
});
- it("keeps a text color pair through saving and loading the note", () => {
+ it("saves the pair and the color as picked as two declarations, and loads them back", () => {
editor.execute("fontColor", { value: "#e64d4d" });
+ editor.execute("fontBackgroundColor", { value: "#e5e64d" });
+
const saved = editor.getData();
expect(saved).toContain(`color:${adaptColor("#e64d4d", "text")}`);
+ expect(saved).toContain("--tn-color:#e64d4d");
+ expect(saved).toContain(`background-color:${adaptColor("#e5e64d", "background")}`);
+ expect(saved).toContain("--tn-background:#e5e64d");
+ expect(saved).not.toContain("/*");
editor.setData(saved);
expect(editor.getData()).toBe(saved);
+ expect(getModelData(editor.model, { withoutSelection: true }))
+ .toContain(`fontColor="${toAdaptiveColorValue("#e64d4d", "text")}"`);
+ });
+
+ it("loads a color saved without the color as picked as it is", () => {
+ const legacy = "<p><span style=\"color:#ff0000;\">a</span>"
+ + "<span style=\"color:light-dark(#b81e2c,#ff9f96);\">b</span></p>";
+ editor.setData(legacy);
+ expect(editor.getData()).toBe(legacy);
});
- it("keeps a pair as it is, and still removes a color", () => {
- const pair = "light-dark(#b81e2c,#ff9f96)";
- editor.execute("fontColor", { value: pair });
+ it("keeps an adapted value as it is, and removes both declarations with the color", () => {
+ const value = toAdaptiveColorValue("#e64d4d", "text");
+ editor.execute("fontColor", { value });
expect(getModelData(editor.model, { withoutSelection: true }))
- .toBe(`<paragraph><$text fontColor="${pair}">text</$text></paragraph>`);
+ .toBe(`<paragraph><$text fontColor="${value}">text</$text></paragraph>`);
editor.execute("fontColor");
- expect(getModelData(editor.model, { withoutSelection: true }))
- .toBe("<paragraph>text</paragraph>");
+ expect(editor.getData()).toBe("<p>text</p>");
editor.execute("fontBackgroundColor", { value: "#e64d4d" });
editor.execute("fontBackgroundColor", { value: "" });
- expect(getModelData(editor.model, { withoutSelection: true }))
- .toBe("<paragraph>text</paragraph>");
+ expect(editor.getData()).toBe("<p>text</p>");
});
it("uses the theme's limits from the editor config", async () => {
@@ -80,10 +97,10 @@ describe("AdaptiveColors", () => {
setModelData(themed.model, "<paragraph>[text]</paragraph>");
themed.execute("fontColor", { value: "#e64d4d" });
- const pair = adaptColor("#e64d4d", "text", bands);
- expect(pair).toMatch(/^light-dark\(#000000,/);
+ const value = toAdaptiveColorValue("#e64d4d", "text", bands);
+ expect(value).toMatch(/^light-dark\(#000000,/);
expect(getModelData(themed.model, { withoutSelection: true }))
- .toBe(`<paragraph><$text fontColor="${pair}">text</$text></paragraph>`);
+ .toBe(`<paragraph><$text fontColor="${value}">text</$text></paragraph>`);
});
it("converts text colors in an editor without the table properties plugins", async () => {
@@ -93,9 +110,9 @@ describe("AdaptiveColors", () => {
setModelData(textOnly.model, "<paragraph>[text]</paragraph>");
textOnly.execute("fontColor", { value: "#e64d4d" });
- const pair = adaptColor("#e64d4d", "text");
+ const value = toAdaptiveColorValue("#e64d4d", "text");
expect(getModelData(textOnly.model, { withoutSelection: true }))
- .toBe(`<paragraph><$text fontColor="${pair}">text</$text></paragraph>`);
+ .toBe(`<paragraph><$text fontColor="${value}">text</$text></paragraph>`);
});
it("stores table and cell colors as pairs, through saving and loading", () => {
@@ -113,11 +130,23 @@ describe("AdaptiveColors", () => {
const saved = editor.getData();
expect(saved).toContain(`border:2px solid ${adaptColor("#4d99e6", "tableBorder")}`);
expect(saved).toContain(`background-color:${adaptColor("#e5e64d", "tableBackground")}`);
+ expect(saved).toContain("--tn-background:#e5e64d");
// 1px is the default cell border width, so the cell gets no `border` shorthand.
expect(saved).toContain(`border-color:${adaptColor("#000000", "tableBorder")}`);
expect(saved).toContain(`background-color:${adaptColor("#e64d4d", "tableBackground")}`);
+ expect(saved).toContain("--tn-background:#e64d4d");
+ expect(saved).not.toContain("/*");
editor.setData(saved);
expect(editor.getData()).toBe(saved);
+
+ // Loading selects the whole table; removing a cell color needs the caret in the cell.
+ const cellParagraph = editor.model.document.getRoot()?.getNodeByPath([ 0, 0, 0, 0 ]);
+ if (!cellParagraph) {
+ throw new Error("The loaded table has no cell paragraph.");
+ }
+ editor.model.change((writer) => writer.setSelection(cellParagraph, 0));
+ editor.execute("tableCellBackgroundColor", { value: "" });
+ expect(editor.getData()).not.toContain("--tn-background:#e64d4d");
});
});
diff --git a/packages/ckeditor5/src/plugins/adaptive_colors.ts b/packages/ckeditor5/src/plugins/adaptive_colors.ts
index 47dfeab89c..7751a6e2fb 100644
--- a/packages/ckeditor5/src/plugins/adaptive_colors.ts
+++ b/packages/ckeditor5/src/plugins/adaptive_colors.ts
@@ -1,9 +1,27 @@
-import { adaptColor, type AdaptiveColorBands, type AdaptiveColorRole } from "@triliumnext/commons";
-import { type CommandExecuteEvent, Plugin } from "ckeditor5";
+import {
+ adaptColor,
+ type AdaptiveColorBands,
+ type AdaptiveColorRole,
+ joinAdaptiveColorValue,
+ splitAdaptiveColorValue,
+ toAdaptiveColorValue
+} from "@triliumnext/commons";
+import {
+ type CommandExecuteEvent,
+ type DowncastAttributeEvent,
+ type ModelElement,
+ Plugin,
+ priorities,
+ type ViewElement
+} from "ckeditor5";
/**
* Stores the colors of text and tables as a light and dark theme pair (see `adaptColor`), whether
* they come from a palette swatch, the color picker, the document colors or a typed value.
+ *
+ * Text, highlight and table backgrounds also keep the color as picked: in the model after the pair
+ * (see `toAdaptiveColorValue`), and in the saved note as a `--tn-color` or `--tn-background`
+ * property, which browsers without `light-dark()` fall back to.
*/
export default class AdaptiveColors extends Plugin {
@@ -11,16 +29,24 @@ export default class AdaptiveColors extends Plugin {
return "AdaptiveColors" as const;
}
+ init() {
+ this.convertTextColor("fontColor", "color", "--tn-color");
+ this.convertTextColor("fontBackgroundColor", "background-color", "--tn-background");
+ this.convertCellBackground();
+ this.convertTableBackground();
+ }
+
afterInit() {
const bands = this.editor.config.get("adaptiveColorBands");
- for (const [ commandName, role ] of Object.entries(COMMAND_ROLES)) {
- this.adaptCommandValue(commandName, role, bands);
+ for (const [ commandName, { role, hasSource } ] of Object.entries(COMMANDS)) {
+ this.adaptCommandValue(commandName, role, hasSource, bands);
}
}
private adaptCommandValue(
commandName: string,
role: AdaptiveColorRole,
+ hasSource: boolean,
bands: AdaptiveColorBands | undefined
) {
// An editor without the table properties plugins has no table color commands.
@@ -32,19 +58,143 @@ export default class AdaptiveColors extends Plugin {
this.listenTo<CommandExecuteEvent>(command, "execute", (_eventInfo, args) => {
const options = args[0] as { value?: unknown } | undefined;
if (typeof options?.value === "string") {
- args[0] = { ...options, value: adaptColor(options.value, role, bands) };
+ const value = hasSource
+ ? toAdaptiveColorValue(options.value, role, bands)
+ : adaptColor(options.value, role, bands);
+ args[0] = { ...options, value };
}
}, { priority: "high" });
}
+ /** Saves a text color or highlight as the pair and the color as picked, and reads it back. */
+ private convertTextColor(modelKey: string, property: string, sourceProperty: string) {
+ const conversion = this.editor.conversion;
+ conversion.for("downcast").attributeToElement({
+ model: modelKey,
+ view: (value: string, { writer }) => writer.createAttributeElement(
+ "span",
+ { style: toStyleText(value, property, sourceProperty) },
+ // CKEditor's own priority for font colors, so the two spans of a run merge.
+ { priority: 7 }
+ ),
+ converterPriority: "high"
+ });
+ conversion.for("upcast").elementToAttribute({
+ view: { name: "span", styles: { [property]: /[\s\S]+/, [sourceProperty]: /[\s\S]+/ } },
+ model: {
+ key: modelKey,
+ value: (element: ViewElement) => readValue(element, property, sourceProperty)
+ },
+ converterPriority: "high"
+ });
+ }
+
+ private convertCellBackground() {
+ const conversion = this.editor.conversion;
+ conversion.for("downcast").attributeToAttribute({
+ model: { name: "tableCell", key: "tableCellBackgroundColor" },
+ view: (value: string) => ({
+ key: "style",
+ value: toBackgroundStyles(value)
+ }),
+ converterPriority: "high"
+ });
+ conversion.for("upcast").attributeToAttribute({
+ view: { name: /^(td|th)$/, styles: BACKGROUND_STYLES },
+ model: {
+ key: "tableCellBackgroundColor",
+ value: readBackground
+ },
+ converterPriority: AHEAD_OF_TABLE_UPCAST
+ });
+ }
+
+ /**
+ * The table's background goes on the `<table>` inside the widget's `<figure>`, as CKEditor
+ * does.
+ */
+ private convertTableBackground() {
+ const conversion = this.editor.conversion;
+ conversion.for("downcast").add((dispatcher) => {
+ dispatcher.on<DowncastAttributeEvent<ModelElement>>(
+ "attribute:tableBackgroundColor:table",
+ (eventInfo, data, { consumable, mapper, writer }) => {
+ if (!consumable.consume(data.item, eventInfo.name)) {
+ return;
+ }
+
+ const figure = mapper.toViewElement(data.item);
+ const table = figure && [ ...figure.getChildren() ]
+ .find((child) => child.is("element", "table"));
+ if (!table?.is("element")) {
+ return;
+ }
+
+ const { attributeOldValue: oldValue, attributeNewValue: newValue } = data;
+ if (typeof oldValue === "string") {
+ writer.removeStyle(Object.keys(toBackgroundStyles(oldValue)), table);
+ }
+ if (typeof newValue === "string") {
+ writer.setStyle(toBackgroundStyles(newValue), table);
+ }
+ },
+ { priority: "high" }
+ );
+ });
+ conversion.for("upcast").attributeToAttribute({
+ view: { name: "table", styles: BACKGROUND_STYLES },
+ model: {
+ key: "tableBackgroundColor",
+ value: readBackground
+ },
+ converterPriority: AHEAD_OF_TABLE_UPCAST
+ });
+ }
+
}
-/** The color commands, and what their color paints. */
-const COMMAND_ROLES: Record<string, AdaptiveColorRole> = {
- fontColor: "text",
- fontBackgroundColor: "background",
- tableBorderColor: "tableBorder",
- tableCellBorderColor: "tableBorder",
- tableBackgroundColor: "tableBackground",
- tableCellBackgroundColor: "tableBackground"
+/**
+ * The color commands, what their color paints, and whether the color as picked is kept. Borders
+ * keep only the pair, which CKEditor can write into the `border` shorthand.
+ */
+const COMMANDS: Record<string, { role: AdaptiveColorRole; hasSource: boolean }> = {
+ fontColor: { role: "text", hasSource: true },
+ fontBackgroundColor: { role: "background", hasSource: true },
+ tableBorderColor: { role: "tableBorder", hasSource: false },
+ tableCellBorderColor: { role: "tableBorder", hasSource: false },
+ tableBackgroundColor: { role: "tableBackground", hasSource: true },
+ tableCellBackgroundColor: { role: "tableBackground", hasSource: true }
};
+
+const BACKGROUND_STYLES = { "background-color": /[\s\S]+/, "--tn-background": /[\s\S]+/ };
+
+/**
+ * An attribute upcast runs only once its element is converted, and CKEditor reads table and cell
+ * backgrounds at `low`; this one reads them just before.
+ */
+const AHEAD_OF_TABLE_UPCAST = priorities.low + 1;
+
+function toStyles(value: string, property: string, sourceProperty: string): Record<string, string> {
+ const { color, source } = splitAdaptiveColorValue(value);
+ return source ? { [property]: color, [sourceProperty]: source } : { [property]: value };
+}
+
+function toBackgroundStyles(value: string) {
+ return toStyles(value, "background-color", "--tn-background");
+}
+
+function toStyleText(value: string, property: string, sourceProperty: string) {
+ return Object.entries(toStyles(value, property, sourceProperty))
+ .map(([ name, styleValue ]) => `${name}:${styleValue}`)
+ .join(";");
+}
+
+/** Reads the pair and the color as picked; CKEditor removes spaces from a color it loads. */
+function readValue(element: ViewElement, property: string, sourceProperty: string) {
+ const color = (element.getStyle(property) ?? "").replace(/\s/g, "");
+ return joinAdaptiveColorValue(color, (element.getStyle(sourceProperty) ?? "").trim());
+}
+
+function readBackground(element: ViewElement) {
+ return readValue(element, "background-color", "--tn-background");
+}
diff --git a/packages/commons/src/lib/adaptive_color.spec.ts b/packages/commons/src/lib/adaptive_color.spec.ts
index 7cd23e21da..094427efdc 100644
--- a/packages/commons/src/lib/adaptive_color.spec.ts
+++ b/packages/commons/src/lib/adaptive_color.spec.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from "vitest";
-import { adaptColor, DEFAULT_ADAPTIVE_COLOR_BANDS } from "./adaptive_color.js";
+import {
+ adaptColor,
+ DEFAULT_ADAPTIVE_COLOR_BANDS,
+ joinAdaptiveColorValue,
+ splitAdaptiveColorValue,
+ toAdaptiveColorValue
+} from "./adaptive_color.js";
const HUES = [
"#e64d4d", "#e6994d", "#e5e64d", "#99e64d", "#4de64d", "#4de699",
@@ -100,6 +106,29 @@ describe("adaptColor", () => {
expect(adaptColor("hsl(210deg 75% 60%)", "background")).toBe(fromPicker);
});
+ it("builds the editor's value from the pair and the color as picked, in hex", () => {
+ const value = toAdaptiveColorValue("#E64D4D", "text");
+ expect(value).toBe("light-dark(#b81e2c,#ff9f96)/*#e64d4d*/");
+ expect(toAdaptiveColorValue("rgb(230, 77, 77)", "text")).toBe(value);
+ expect(toAdaptiveColorValue("hsl(0, 75%, 60%)", "text")).toMatch(/\/\*#[0-9a-f]{6}\*\/$/);
+ expect(splitAdaptiveColorValue(value))
+ .toEqual({ color: "light-dark(#b81e2c,#ff9f96)", source: "#e64d4d" });
+
+ // A value that is already built, a plain pair and a color that cannot be adapted stay.
+ for (const unchanged of [ value, "light-dark(#b81e2c,#ff9f96)", "red" ]) {
+ expect(toAdaptiveColorValue(unchanged, "text")).toBe(unchanged);
+ }
+ expect(splitAdaptiveColorValue("red")).toEqual({ color: "red" });
+ });
+
+ it("joins a loaded pair and color as picked, and ignores anything else", () => {
+ expect(joinAdaptiveColorValue("light-dark(#b81e2c,#ff9f96)", "#E64D4D"))
+ .toBe("light-dark(#b81e2c,#ff9f96)/*#e64d4d*/");
+ expect(joinAdaptiveColorValue("light-dark(#b81e2c,#ff9f96)", "red"))
+ .toBe("light-dark(#b81e2c,#ff9f96)");
+ expect(joinAdaptiveColorValue("#ff0000", "#e64d4d")).toBe("#ff0000");
+ });
+
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%)",
diff --git a/packages/commons/src/lib/adaptive_color.ts b/packages/commons/src/lib/adaptive_color.ts
index 75bdd8f428..7cfe98afc3 100644
--- a/packages/commons/src/lib/adaptive_color.ts
+++ b/packages/commons/src/lib/adaptive_color.ts
@@ -38,6 +38,41 @@ export function adaptColor(
return `light-dark(${fitToBand(lab, light)},${fitToBand(lab, dark)})`;
}
+/**
+ * The text editor's value for an adaptive color: the `adaptColor` pair, followed by the color as
+ * picked, in hex, inside a CSS comment. The comment keeps the value a valid CSS color, and the
+ * editor saves the picked color as a `--tn-color` or `--tn-background` property.
+ *
+ * @returns the value, or `color` unchanged if it cannot be adapted.
+ */
+export function toAdaptiveColorValue(
+ color: string,
+ role: AdaptiveColorRole,
+ bands: AdaptiveColorBands = DEFAULT_ADAPTIVE_COLOR_BANDS
+): string {
+ const rgb = parseColor(color.trim());
+ if (!rgb) {
+ return color;
+ }
+
+ return joinAdaptiveColorValue(adaptColor(color, role, bands), toHex(rgb));
+}
+
+/**
+ * Builds the text editor's value from a pair and the color as picked, as read from a saved note.
+ * Anything other than a `light-dark()` pair of hex colors and a hex color returns `pair` alone.
+ */
+export function joinAdaptiveColorValue(pair: string, source: string): string {
+ const isAdaptive = ADAPTIVE_PAIR.test(pair) && /^#[0-9a-f]{6}$/i.test(source);
+ return isAdaptive ? `${pair}/*${source.toLowerCase()}*/` : pair;
+}
+
+/** Splits the text editor's value into the color to show and the color as picked, if any. */
+export function splitAdaptiveColorValue(value: string): { color: string; source?: string } {
+ const match = /^(.+)\/\*(#[0-9a-f]{6})\*\/$/i.exec(value);
+ return match ? { color: match[1], source: match[2] } : { color: value };
+}
+
/**
* The limits used where no theme defines them, such as on the server. Against the Next themes'
* page, they keep text at 4.5:1 or more, also on every background, and borders at 3:1 or more.
@@ -68,6 +103,9 @@ type Lab = [number, number, number];
/** Below this CIELAB chroma a color counts as grey. */
const GREY_CHROMA = 1.5;
+/** A pair as `adaptColor` writes it. */
+const ADAPTIVE_PAIR = /^light-dark\(#[0-9a-f]{6},#[0-9a-f]{6}\)$/i;
+
const D65_WHITE: Lab = [ 0.95047, 1, 1.08883 ];
const LAB_EPSILON = 216 / 24389;
const LAB_KAPPA = 24389 / 27;
@@ -174,8 +212,13 @@ function lchToHex(lightness: number, chroma: number, hue: number): string {
rgb = lchToLinearRgb(lightness, low, hue);
}
+ return toHex(rgb.map((c) => fromLinear(Math.min(1, Math.max(0, c)))) as Rgb);
+}
+
+/** Formats sRGB channels from 0 to 1 as `#rrggbb`. */
+function toHex(rgb: Rgb): string {
return `#${rgb
- .map((c) => Math.round(fromLinear(Math.min(1, Math.max(0, c))) * 255))
+ .map((c) => Math.round(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 e3f3b5bfb9..8756d71d5d 100644
--- a/packages/commons/src/lib/markdown_renderer.spec.ts
+++ b/packages/commons/src/lib/markdown_renderer.spec.ts
@@ -1,7 +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 { HIGHLIGHT_STYLE } 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. */
@@ -631,7 +631,7 @@ describe("renderToHtml", () => {
});
describe("highlights (==text==)", () => {
- const HL = `<span style="background-color:${HIGHLIGHT_BACKGROUND};">`;
+ const HL = `<span style="${HIGHLIGHT_STYLE}">`;
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 b74d0476f9..bff709e1c8 100644
--- a/packages/commons/src/lib/marked_extensions.ts
+++ b/packages/commons/src/lib/marked_extensions.ts
@@ -102,6 +102,9 @@ export function createTransclusionExtension(options: TransclusionOptions = {}):
};
}
+/** The colour of a highlight as picked: the text editor's palette Yellow. */
+export const HIGHLIGHT_SOURCE = "#e5e64d";
+
/**
* 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
@@ -110,11 +113,15 @@ export function createTransclusionExtension(options: TransclusionOptions = {}):
* leaves inert: there is no Highlight plugin to apply or lift one, and the allow-list is bare
* element names, so a colour on it never reaches the editor's model.
*
- * The Markdown exporter compares against this to decide which highlights can collapse back to
- * `==…==` and which have to keep their colour as inline HTML, so the two directions must agree
- * on the exact value.
+ * The Markdown exporter compares against this and `HIGHLIGHT_SOURCE` to decide which highlights
+ * can collapse back to `==…==` and which have to keep their colour as inline HTML, so the two
+ * directions must agree on the exact value.
*/
-export const HIGHLIGHT_BACKGROUND = adaptColor("#e5e64d", "background");
+export const HIGHLIGHT_BACKGROUND = adaptColor(HIGHLIGHT_SOURCE, "background");
+
+/** The style of a highlight, with the colour as picked as the text editor saves it. */
+export const HIGHLIGHT_STYLE =
+ `background-color:${HIGHLIGHT_BACKGROUND};--tn-background:${HIGHLIGHT_SOURCE};`;
/**
* Creates an extension for highlights: `==text==` → a background-coloured `<span>`.
@@ -148,7 +155,7 @@ export function createHighlightExtension(): TokenizerAndRendererExtension {
},
renderer(token) {
- return `<span style="background-color:${HIGHLIGHT_BACKGROUND};">${this.parser.parseInline(token.tokens as Token[])}</span>`;
+ return `<span style="${HIGHLIGHT_STYLE}">${this.parser.parseInline(token.tokens as Token[])}</span>`;
}
};
}
diff --git a/packages/share-theme/src/styles/content.css b/packages/share-theme/src/styles/content.css
index 20bbf614d3..28b6b58f78 100644
--- a/packages/share-theme/src/styles/content.css
+++ b/packages/share-theme/src/styles/content.css
@@ -5,6 +5,17 @@
--ck-content-line-height: inherit !important;
}
+/* Without light-dark(), the inline adaptive color is dropped; show the color as picked instead. */
+@supports not (color: light-dark(#000, #fff)) {
+ [style*="--tn-color"] {
+ color: var(--tn-color) !important;
+ }
+
+ [style*="--tn-background"] {
+ background-color: var(--tn-background) !important;
+ }
+}
+
.ck-content code,
.ck-content pre {
color: var(--text-primary);
diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.ts
index d4afbb0816..e7a50199c3 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 { HIGHLIGHT_BACKGROUND, trimIndentation } from "@triliumnext/commons";
+import { HIGHLIGHT_BACKGROUND, HIGHLIGHT_SOURCE, HIGHLIGHT_STYLE, trimIndentation } from "@triliumnext/commons";
import { describe, expect,it } from "vitest";
import markdownExportService, { DEFAULT_ADMONITION_TYPE } from "./markdown.js";
@@ -862,6 +862,20 @@ describe("Markdown export", () => {
expect(markdownExportService.toMarkdown(`<p>${red}</p>`)).toBe(red);
});
+ it("recognises the yellow highlight by its colour as picked, whatever the theme made of it", () => {
+ expect(markdownExportService.toMarkdown(`<p><span style="${HIGHLIGHT_STYLE}">a</span></p>`))
+ .toBe("==a==");
+
+ // A theme with other limits stores another pair for the same yellow.
+ const themed = `<span style="--tn-background:${HIGHLIGHT_SOURCE};`
+ + "background-color:light-dark(#fffbd0,#333300);\">b</span>";
+ expect(markdownExportService.toMarkdown(`<p>${themed}</p>`)).toBe("==b==");
+
+ // Another colour as picked keeps its colour, even with the default yellow's pair.
+ const other = `<span style="--tn-background:#e64d4d;background-color:${HIGHLIGHT_BACKGROUND}">c</span>`;
+ expect(markdownExportService.toMarkdown(`<p>${other}</p>`)).toBe(other);
+ });
+
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 be690e12aa..5c9928238e 100644
--- a/packages/trilium-core/src/services/export/markdown.ts
+++ b/packages/trilium-core/src/services/export/markdown.ts
@@ -1,6 +1,6 @@
import { safeLinkPreviewHref, type TaskStateDef } from "@triliumnext/commons";
import { ADMONITION_TYPE_MAPPINGS } from "@triliumnext/commons/src/lib/markdown_renderer.js";
-import { HIGHLIGHT_BACKGROUND } from "@triliumnext/commons/src/lib/marked_extensions.js";
+import { HIGHLIGHT_BACKGROUND, HIGHLIGHT_SOURCE } from "@triliumnext/commons/src/lib/marked_extensions.js";
import { gfm, serializeStructuralHtml } from "@triliumnext/turndown-plugin-gfm";
import escapeHtml from "escape-html";
import { parse as parseHtml } from "node-html-parser";
@@ -540,6 +540,15 @@ function isPlainDefaultHighlight(node: HTMLElement): boolean {
return true;
}
+ // A highlight saved with its colour as picked is recognised by that colour, whatever pair the
+ // theme's limits gave it.
+ const source = declarations.find(({ property }) => property === "--tn-background");
+ if (source) {
+ return declarations.length === 2
+ && declarations.some(({ property }) => property === "background-color")
+ && normalizeColor(source.value) === normalizeColor(HIGHLIGHT_SOURCE);
+ }
+
if (declarations.length > 1) {
return false;
}
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 30571d30f5..cda9b3b15d 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,4 +1,4 @@
-import { HIGHLIGHT_BACKGROUND } from "@triliumnext/commons";
+import { HIGHLIGHT_STYLE } from "@triliumnext/commons";
import { ZipArchive } from "archiver";
import LZString from "lz-string";
import { PassThrough } from "stream";
@@ -236,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:${HIGHLIGHT_BACKGROUND};">highlight</span> and a comment.</p>`);
+ expect(decodeUtf8(note?.getContent() ?? "")).toBe(`<p>A <span style="${HIGHLIGHT_STYLE}">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 c75dd79fcf..64cc789b72 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 { HIGHLIGHT_BACKGROUND, trimIndentation } from "@triliumnext/commons";
+import { HIGHLIGHT_STYLE, 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:${HIGHLIGHT_BACKGROUND};">highlighted</span>`);
+ expect(html).toContain(`<span style="${HIGHLIGHT_STYLE}">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:${HIGHLIGHT_BACKGROUND};">highlighted</span> text.</p>`;
+ const original = `<p>Some <span style="${HIGHLIGHT_STYLE}">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 2aefeee0ad..09cf3c9fb5 100644
--- a/packages/trilium-core/src/services/sanitizer.spec.ts
+++ b/packages/trilium-core/src/services/sanitizer.spec.ts
@@ -85,6 +85,18 @@ describe("sanitize", () => {
.toBe("<span>x</span>");
});
+ it("keeps the color as picked that comes with an adaptive color", () => {
+ const style = "--tn-color:#e64d4d;color:light-dark(#b81e2c,#ff9f96);"
+ + "--tn-background:#e5e64d;background-color:light-dark(#e8e4bd,#494917)";
+ const dirty = `<p><span style="${style}">x</span></p>`
+ + `<table><tbody><tr><td style="--tn-background:#e64d4d">c</td></tr></tbody></table>`;
+ expect(sanitizeHtml(dirty)).toBe(dirty);
+
+ // Only a hex color passes, and only under these two names.
+ expect(sanitizeHtml(`<span style="--tn-color:url(x)">x</span>`)).toBe("<span>x</span>");
+ expect(sanitizeHtml(`<span style="--tn-other:#e64d4d">x</span>`)).toBe("<span>x</span>");
+ });
+
it("keeps light-dark() table and cell border colors", () => {
const pair = "light-dark(#000000,#6f6f6f)";
const dirty = `<table style="border-color:${pair}"><tbody><tr>`
diff --git a/packages/trilium-core/src/services/sanitizer.ts b/packages/trilium-core/src/services/sanitizer.ts
index 198229585b..dbd8c236b4 100644
--- a/packages/trilium-core/src/services/sanitizer.ts
+++ b/packages/trilium-core/src/services/sanitizer.ts
@@ -73,6 +73,9 @@ export function sanitizeHtml(dirtyHtml: string) {
"*": {
color: [ ...colorRegex, adaptiveColorRegex ],
"background-color": [ ...colorRegex, adaptiveColorRegex ],
+ // The color as picked behind an adaptive color, for browsers without light-dark().
+ "--tn-color": [ /^#[0-9a-f]{6}$/i ],
+ "--tn-background": [ /^#[0-9a-f]{6}$/i ],
"margin-left": sizeRegex,
"padding-left": sizeRegex,
"text-align": [/^\s*(left|center|right|justify)\s*$/],