Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/adaptive colors: switch to pure-CSS color processing
Adorian Doranb84c4c084c2f
diff --git a/apps/client/src/services/adaptive_colors.spec.ts b/apps/client/src/services/adaptive_colors.spec.tsdeleted file mode 100644index 0efc6870fb..0000000000--- a/apps/client/src/services/adaptive_colors.spec.ts+++ /dev/null@@ -1,61 +0,0 @@-import { type AdaptiveColorRole, DEFAULT_ADAPTIVE_COLOR_BANDS } from "@triliumnext/commons";-import { readFileSync } from "fs";-import { join } from "path";-import { afterEach, describe, expect, it } from "vitest";--import { readAdaptiveColorBands } from "./adaptive_colors.js";--const styleCss = readFileSync(join(__dirname, "..", "stylesheets", "style.css"), "utf-8");--const ROLES: Record<string, AdaptiveColorRole> = {- "text": "text",- "background": "background",- "table-border": "tableBorder",- "table-background": "tableBackground"-};-const BOUNDS = {- "min-lightness": "minLightness",- "max-lightness": "maxLightness",- "max-chroma": "maxChroma"-} as const;--describe("readAdaptiveColorBands", () => {- const root = document.documentElement;-- afterEach(() => root.removeAttribute("style"));-- it("finds a limit for every variable in style.css, set to its default", () => {- const pattern = /--adaptive-([a-z-]+?)-(light|dark)-([a-z-]+):\s*([^;]+);/g;- // Themes load before style.css, so only a zero-specificity block lets their `:root` win.- const defaults = [ ...styleCss.matchAll(/:where\(:root\)\s*\{([^}]*)\}/g) ]- .map(([ , block ]) => block)- .join("\n");- const variables = [ ...defaults.matchAll(pattern) ];- expect(variables).toHaveLength(16);- expect([ ...styleCss.matchAll(pattern) ]).toHaveLength(16);-- for (const [ , role, theme, bound, value ] of variables) {- const field = BOUNDS[bound as keyof typeof BOUNDS];- expect(ROLES[role]).toBeDefined();- expect(field).toBeDefined();-- const band = DEFAULT_ADAPTIVE_COLOR_BANDS[ROLES[role]][theme as "light" | "dark"];- expect(value.trim() === "none" ? Infinity : Number(value)).toBe(band[field]);- }- });-- it("reads the values a theme defines, and keeps the default for the rest", () => {- root.style.setProperty("--adaptive-text-light-max-lightness", "35");- root.style.setProperty("--adaptive-text-dark-max-chroma", "none");- root.style.setProperty("--adaptive-table-border-dark-min-lightness", "50");- root.style.setProperty("--adaptive-background-dark-max-lightness", "dark");-- const bands = readAdaptiveColorBands(root);- expect(bands.text.light)- .toEqual({ minLightness: 0, maxLightness: 35, maxChroma: Infinity });- expect(bands.text.dark.maxChroma).toBe(Infinity);- expect(bands.tableBorder.dark.minLightness).toBe(50);- expect(bands.background).toEqual(DEFAULT_ADAPTIVE_COLOR_BANDS.background);- expect(bands.tableBackground).toEqual(DEFAULT_ADAPTIVE_COLOR_BANDS.tableBackground);- });-});diff --git a/apps/client/src/services/adaptive_colors.ts b/apps/client/src/services/adaptive_colors.tsdeleted file mode 100644index 7c1eae255d..0000000000--- a/apps/client/src/services/adaptive_colors.ts+++ /dev/null@@ -1,51 +0,0 @@-import {- type AdaptiveColorBand,- type AdaptiveColorBands,- type AdaptiveColorRole,- DEFAULT_ADAPTIVE_COLOR_BANDS-} from "@triliumnext/commons";--import { readCssVar } from "../utils/css-var.js";--/**- * The theme's limits for adaptive colors, read once from the `--adaptive-*` CSS variables declared- * in `style.css`.- */-export const ADAPTIVE_COLOR_BANDS = readAdaptiveColorBands(document.documentElement);--/**- * Reads the `--adaptive-<role>-<light|dark>-<min-lightness|max-lightness|max-chroma>` variables.- * A variable that is missing or not a number keeps its default; `none` means no chroma cap.- */-export function readAdaptiveColorBands(element: HTMLElement): AdaptiveColorBands {- return {- text: readRole(element, "text", "text"),- background: readRole(element, "background", "background"),- tableBorder: readRole(element, "tableBorder", "table-border"),- tableBackground: readRole(element, "tableBackground", "table-background")- };-}--function readRole(element: HTMLElement, role: AdaptiveColorRole, name: string) {- const defaults = DEFAULT_ADAPTIVE_COLOR_BANDS[role];- return {- light: readBand(element, `adaptive-${name}-light`, defaults.light),- dark: readBand(element, `adaptive-${name}-dark`, defaults.dark)- };-}--function readBand(element: HTMLElement, prefix: string, defaults: AdaptiveColorBand) {- return {- minLightness: readNumber(element, `${prefix}-min-lightness`, defaults.minLightness),- maxLightness: readNumber(element, `${prefix}-max-lightness`, defaults.maxLightness),- maxChroma: readNumber(element, `${prefix}-max-chroma`, defaults.maxChroma)- };-}--function readNumber(element: HTMLElement, name: string, defaultValue: number) {- const variable = readCssVar(element, name);- if (variable.asString()?.trim() === "none") {- return Infinity;- }- return variable.asNumber(defaultValue) ?? defaultValue;-}diff --git a/apps/client/src/stylesheets/adaptive-colors.css b/apps/client/src/stylesheets/adaptive-colors.cssnew file mode 100644index 0000000000..bad2e55413--- /dev/null+++ b/apps/client/src/stylesheets/adaptive-colors.css@@ -0,0 +1,99 @@+/*+ * Theme-adaptive text and table colors. The text editor saves each color again as `--tn-color`,+ * `--tn-background` or `--tn-border-color`; these rules keep its hue, move its CIELAB lightness+ * into the role's range and cap its chroma. Greys (chroma below 1.5) spread over the range.+ * Keep in step with `packages/share-theme/src/styles/adaptive-colors.css`.+ */++/* Zero specificity, so that a theme's :root wins although themes load before this file. */+:where(:root) {+ /* Adaptive font color limits */+ --adaptive-text-light-max-lightness: 40;+ --adaptive-text-light-max-chroma: 150;+ --adaptive-text-dark-min-lightness: 75;+ --adaptive-text-dark-max-chroma: 55;++ /* Adaptive font background color limits */+ --adaptive-background-light-min-lightness: 90;+ --adaptive-background-light-max-chroma: 20;+ --adaptive-background-dark-max-lightness: 30;+ --adaptive-background-dark-max-chroma: 30;++ /* Adaptive table border color limits */+ --adaptive-table-border-light-max-lightness: 60;+ --adaptive-table-border-light-max-chroma: 150;+ --adaptive-table-border-dark-min-lightness: 47;+ --adaptive-table-border-dark-max-chroma: 150;++ /* Adaptive table background color limits */+ --adaptive-table-background-light-min-lightness: 90;+ --adaptive-table-background-light-max-chroma: 20;+ --adaptive-table-background-dark-max-lightness: 30;+ --adaptive-table-background-dark-max-chroma: 30;+}++:root {+ --_adaptive-text-min: 0;+ --_adaptive-text-max: var(--adaptive-text-light-max-lightness);+ --_adaptive-text-chroma: var(--adaptive-text-light-max-chroma);+ --_adaptive-background-min: var(--adaptive-background-light-min-lightness);+ --_adaptive-background-max: 100;+ --_adaptive-background-chroma: var(--adaptive-background-light-max-chroma);+ --_adaptive-table-border-min: 0;+ --_adaptive-table-border-max: var(--adaptive-table-border-light-max-lightness);+ --_adaptive-table-border-chroma: var(--adaptive-table-border-light-max-chroma);+ --_adaptive-table-background-min: var(--adaptive-table-background-light-min-lightness);+ --_adaptive-table-background-max: 100;+ --_adaptive-table-background-chroma: var(--adaptive-table-background-light-max-chroma);+}++body.dark-theme {+ --_adaptive-text-min: var(--adaptive-text-dark-min-lightness);+ --_adaptive-text-max: 100;+ --_adaptive-text-chroma: var(--adaptive-text-dark-max-chroma);+ --_adaptive-background-min: 0;+ --_adaptive-background-max: var(--adaptive-background-dark-max-lightness);+ --_adaptive-background-chroma: var(--adaptive-background-dark-max-chroma);+ --_adaptive-table-border-min: var(--adaptive-table-border-dark-min-lightness);+ --_adaptive-table-border-max: 100;+ --_adaptive-table-border-chroma: var(--adaptive-table-border-dark-max-chroma);+ --_adaptive-table-background-min: 0;+ --_adaptive-table-background-max: var(--adaptive-table-background-dark-max-lightness);+ --_adaptive-table-background-chroma: var(--adaptive-table-background-dark-max-chroma);+}++/* `!important` beats the inline color, which browsers without relative colors keep showing. */+[style*="--tn-color"] {+ color: lch(from var(--tn-color)+ calc(min(1, c / 1.5) * clamp(var(--_adaptive-text-min), l, var(--_adaptive-text-max))+ + (1 - min(1, c / 1.5)) * (var(--_adaptive-text-min)+ + l / 100 * (var(--_adaptive-text-max) - var(--_adaptive-text-min))))+ min(c, var(--_adaptive-text-chroma)) h) !important;+}++[style*="--tn-background"] {+ background-color: lch(from var(--tn-background)+ calc(min(1, c / 1.5)+ * clamp(var(--_adaptive-background-min), l, var(--_adaptive-background-max))+ + (1 - min(1, c / 1.5)) * (var(--_adaptive-background-min)+ + l / 100 * (var(--_adaptive-background-max) - var(--_adaptive-background-min))))+ min(c, var(--_adaptive-background-chroma)) h) !important;+}++:is(table, td, th)[style*="--tn-border-color"] {+ border-color: lch(from var(--tn-border-color)+ calc(min(1, c / 1.5)+ * clamp(var(--_adaptive-table-border-min), l, var(--_adaptive-table-border-max))+ + (1 - min(1, c / 1.5)) * (var(--_adaptive-table-border-min) + l / 100+ * (var(--_adaptive-table-border-max) - var(--_adaptive-table-border-min))))+ min(c, var(--_adaptive-table-border-chroma)) h) !important;+}++:is(table, td, th)[style*="--tn-background"] {+ background-color: lch(from var(--tn-background)+ calc(min(1, c / 1.5) * clamp(var(--_adaptive-table-background-min), l,+ var(--_adaptive-table-background-max))+ + (1 - min(1, c / 1.5)) * (var(--_adaptive-table-background-min) + l / 100+ * (var(--_adaptive-table-background-max) - var(--_adaptive-table-background-min))))+ min(c, var(--_adaptive-table-background-chroma)) h) !important;+}diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.cssindex 9706bdadab..53b7f0fc98 100644--- a/apps/client/src/stylesheets/style.css+++ b/apps/client/src/stylesheets/style.css@@ -1,4 +1,5 @@@import "./boxicons-compat.css";+@import "./adaptive-colors.css";@font-face {font-family: Montserrat;@@ -32,47 +33,6 @@--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);-}--/* Zero specificity, so that a theme's :root wins although themes load before this file. */-:where(:root) {- /* Adaptive font color limits */- --adaptive-text-light-max-lightness: 40;- --adaptive-text-light-max-chroma: none;- --adaptive-text-dark-min-lightness: 75;- --adaptive-text-dark-max-chroma: 55;-- /* Adaptive font background color limits */- --adaptive-background-light-min-lightness: 90;- --adaptive-background-light-max-chroma: 20;- --adaptive-background-dark-max-lightness: 30;- --adaptive-background-dark-max-chroma: 30;-- /* Adaptive table border color limits */- --adaptive-table-border-light-max-lightness: 60;- --adaptive-table-border-light-max-chroma: none;- --adaptive-table-border-dark-min-lightness: 47;- --adaptive-table-border-dark-max-chroma: none;-- /* Adaptive table background color limits */- --adaptive-table-background-light-min-lightness: 90;- --adaptive-table-background-light-max-chroma: 20;- --adaptive-table-background-dark-max-lightness: 30;- --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 *,diff --git a/apps/client/src/widgets/sidebar/HighlightsList.tsx b/apps/client/src/widgets/sidebar/HighlightsList.tsxindex a7a79aa74b..40d60ecf56 100644--- a/apps/client/src/widgets/sidebar/HighlightsList.tsx+++ b/apps/client/src/widgets/sidebar/HighlightsList.tsx@@ -152,7 +152,10 @@ function HighlightItem<T extends RawHighlight>({ highlight, onClick }: {fontStyle: highlight.attrs.italic ? "italic" : undefined,textDecoration: highlight.attrs.underline ? "underline" : undefined,color: highlight.attrs.color,- backgroundColor: highlight.attrs.background+ backgroundColor: highlight.attrs.background,+ // Adapted to the theme by `adaptive-colors.css`, like the note's own colors.+ "--tn-color": highlight.attrs.color,+ "--tn-background": highlight.attrs.background}}html={highlight.text}/>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.tsindex 586c763ca0..188d21da67 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,10 +1,4 @@-import {- DEFAULT_ADAPTIVE_COLOR_BANDS as DEFAULTS,- HIGHLIGHT_BACKGROUND,- HIGHLIGHT_SOURCE,- splitAdaptiveColorValue,- toAdaptiveColorValue-} from "@triliumnext/commons";+import { HIGHLIGHT_BACKGROUND } from "@triliumnext/commons";import { describe, expect, it, vi } from "vitest";import { DEFAULT_COLOR_PALETTE } from "../../react/ColorPicker.js";@@ -21,49 +15,21 @@ const LABELS = [describe("buildFontColorConfig", () => {it("lists four greys, then every note color hue, four to a row", () => {- for (const palette of Object.values(buildFontColorConfig(DEFAULTS))) {+ for (const palette of Object.values(buildFontColorConfig())) {expect(palette.columns).toBe(4);expect(palette.colors.map(({ label }) => label)).toEqual(LABELS);+ expect(palette.colors.map(({ color }) => color)).toEqual(SOURCES);}});- 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) => toAdaptiveColorValue(color, "text")));- expect(fontBackgroundColor.colors.map(({ color }) => color))- .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}\)\/\*#[0-9a-f]{6}\*\/$/);- }- });-- it("turns the swatches into pairs with the theme's limits", () => {- const bands = {- ...DEFAULTS,- background: {- ...DEFAULTS.background,- dark: { minLightness: 0, maxLightness: 20, maxChroma: 10 }- }- };- const { colors } = buildFontColorConfig(bands).fontBackgroundColor;- expect(colors.map(({ color }) => color))- .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;- const yellow = colors.find(({ label }) => label === "Yellow")?.color ?? "";- expect(splitAdaptiveColorValue(yellow))- .toEqual({ color: HIGHLIGHT_BACKGROUND, source: HIGHLIGHT_SOURCE });+ it("uses the palette's yellow for Markdown highlights", () => {+ const { colors } = buildFontColorConfig().fontBackgroundColor;+ expect(colors.find(({ label }) => label === "Yellow")?.color).toBe(HIGHLIGHT_BACKGROUND);});});describe("buildTableColorConfig", () => {- it("gives table and cell borders and backgrounds the same swatches, as plain colors", () => {+ it("gives table and cell borders and backgrounds the same swatches", () => {const { tableProperties, tableCellProperties } = buildTableColorConfig();for (const colors of [tableProperties.borderColors, tableProperties.backgroundColors,diff --git a/apps/client/src/widgets/type_widgets/text/color_palette.ts b/apps/client/src/widgets/type_widgets/text/color_palette.tsindex f50f397e10..637926cf7a 100644--- a/apps/client/src/widgets/type_widgets/text/color_palette.ts+++ b/apps/client/src/widgets/type_widgets/text/color_palette.ts@@ -1,28 +1,19 @@-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`,- * with the color as picked kept (see `toAdaptiveColorValue`).+ * the note color palette.*/-export function buildFontColorConfig(bands: AdaptiveColorBands) {+export function buildFontColorConfig() {+ const colors = buildSwatches();return {- fontColor: { colors: buildAdaptedSwatches("text", bands), columns: 4 },- fontBackgroundColor: { colors: buildAdaptedSwatches("background", bands), columns: 4 }+ fontColor: { colors, columns: 4 },+ fontBackgroundColor: { colors, columns: 4 }};}-/**- * The same swatches for the table and cell properties, as plain colors: the table dialogs reject a- * `light-dark()` value, so `AdaptiveColors` turns the color into a pair when it is applied.- */+/** The same swatches for the table and cell properties. */export function buildTableColorConfig() {const colors = buildSwatches();return {@@ -44,13 +35,6 @@ const HUE_LABELS = ["Blue", "Purple"];-function buildAdaptedSwatches(role: AdaptiveColorRole, bands: AdaptiveColorBands) {- return buildSwatches().map((swatch) => ({- ...swatch,- color: toAdaptiveColorValue(swatch.color, role, bands)- }));-}-function buildSwatches() {// CKEditor has no name for pink, so it comes from the app's own catalogue.const hueLabels = [ ...HUE_LABELS, t("text-editor.colors.pink") ];diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 80064aff00..9ab5bf598a 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -3,7 +3,6 @@ import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/enimport { ALLOWED_PROTOCOLS, DISPLAYABLE_LOCALE_IDS, formatShortcut, IMAGE_UPLOAD_SUBTYPES, joinShortcut, KATEX_MACROS, MIME_TYPE_AUTO, normalizeMimeTypeForCKEditor } from "@triliumnext/commons";import i18next from "i18next";-import { ADAPTIVE_COLOR_BANDS } from "../../../services/adaptive_colors.js";import { copyHtmlWithToast, copyTextWithToast } from "../../../services/clipboard_ext.js";import { t } from "../../../services/i18n.js";import imageService from "../../../services/image.js";@@ -164,8 +163,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfialignment: {options: [ "left", "right", "center", "justify"]},- ...buildFontColorConfig(ADAPTIVE_COLOR_BANDS),- adaptiveColorBands: ADAPTIVE_COLOR_BANDS,+ ...buildFontColorConfig(),link: {defaultProtocol: "https://",allowedProtocols: ALLOWED_PROTOCOLS,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.htmlindex 5fefdfc5c1..291c9baf93 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> Markdownsyntax, as well as the canonical HTML representation in Trilium:</p><pre><code class="language-text-x-trilium-auto">==highlighted==-<span style="background-color:light-dark(#e8e4bd,#494917);--tn-background:#e5e64d;">Highlighted</span></code></pre>+<span style="background-color:#e5e64d;--tn-background:#e5e64d;">Highlighted</span></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.htmlindex bea9281f3a..01bb16730e 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,16 +72,17 @@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 appearin the list for easy reuse.</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>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>Colors adapt to the <a href="#root/_help_Wy267RK4M69c">theme</a>. Trilium+ shows each color in a lighter or darker shade that suits the current theme,+ so the text stays readable after switching between light and dark themes.+ 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, and to shared notes too. The note itself keeps the color+ as it was picked, so an exported note shows it unchanged.</p>+<p>Colors applied with older versions of Trilium are shown exactly as they+ were picked, until the note is next edited.</p>+<p>Older browsers that can't adapt colors show them exactly as they were+ picked.</p><p>To remove either the background or foreground color of a text, selectthe corresponding formatting button and press <em>Remove color</em> or usethe <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.htmlindex 91fd387c34..8992930247 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@@ -338,16 +338,13 @@ src="3_Tables_image.png" width="384" height="100"><p>The border and background colors of tables and cells adapt to the <a href="#root/_help_Wy267RK4M69c">theme</a>,the same way as <a href="#root/_help_Gr6xFaF6ioJ5">text colors</a> do. Acolor picked from the palette, chosen with the color picker or typed in- is saved in two shades, one for light themes and one for dark themes, so- borders stay visible and text stays readable on the background in both.- The hue stays the same.</p>-<p>Once a color is applied, its field shows the saved value as <code>light-dark(…)</code>.- 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>+ is shown in a lighter or darker shade that suits the current theme, so+ borders stay visible and text stays readable on the background. The hue+ stays the same, and the table keeps the color as it was picked.</p>+<p>Colors applied with older versions of Trilium are shown exactly as they+ were picked, until the note is next edited.</p>+<p>Older browsers that can't adapt colors show them exactly as they were+ picked.</p><h2>Caption</h2><p>Press the <span class="tn-icon cke cke-caption"></span> button toinsert a caption or a text description of the table, which is going todiff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Theme development/Reference.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Theme development/Reference.htmlindex 99f5044f4e..576765c112 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Theme development/Reference.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Theme development/Reference.html@@ -161,10 +161,11 @@ body.electron:not(.native-titlebar) {<p>Colors applied in a text note, from the font color and background colorbuttons (see <a class="reference-link" href="#root/_help_Gr6xFaF6ioJ5">General formatting</a>)or from the table and cell properties (see <a class="reference-link"- href="#root/_help_NdowYOC1GFKS">Tables</a>), are saved in two shades: one- for light themes and one for dark themes. A theme can change the limits- these shades are kept within, for example if its page background is much- darker or lighter than the one of the built-in themes:</p><pre><code class="language-text-css">:root {+ href="#root/_help_NdowYOC1GFKS">Tables</a>), are shown in a shade that+ suits the theme: the hue stays, while the lightness and the saturation+ are kept within limits. A theme can change these limits, for example if+ its page background is much darker or lighter than the one of the built-in+ themes:</p><pre><code class="language-text-css">:root {--adaptive-text-light-max-lightness: 35;--adaptive-text-dark-min-lightness: 80;}</code></pre>@@ -173,10 +174,12 @@ body.electron:not(.native-titlebar) {<li>The role is <code>text</code> (font color), <code>background</code> (fontbackground color), <code>table-border</code> or <code>table-background</code> (tablesand cells).</li>- <li><code>light</code> or <code>dark</code> is the shade the limit applies to.</li>+ <li><code>light</code> or <code>dark</code> is the kind of theme the limit applies+ to, as declared by <code>--theme-style</code>.</li><li>The limit is <code>min-lightness</code> or <code>max-lightness</code> (theCIELAB lightness, from 0 for black to 100 for white), or <code>max-chroma</code> (how- saturated the color can be, with <code>none</code> for no limit).</li>+ saturated the color can be; <code>150</code> sets no practical limit). Each+ value must be a plain number, otherwise the colors lose their adaptation.</li></ul><p>The defaults are:</p><figure class="table">@@ -184,15 +187,15 @@ body.electron:not(.native-titlebar) {<thead><tr><th>Role</th>- <th>Light shade</th>- <th>Dark shade</th>+ <th>Light themes</th>+ <th>Dark themes</th></tr></thead><tbody><tr><td><code>text</code></td>- <td><code>max-lightness: 40</code>, <code>max-chroma: none</code>+ <td><code>max-lightness: 40</code>, <code>max-chroma: 150</code></td><td><code>min-lightness: 75</code>, <code>max-chroma: 55</code></td>@@ -208,9 +211,9 @@ body.electron:not(.native-titlebar) {<tr><td><code>table-border</code></td>- <td><code>max-lightness: 60</code>, <code>max-chroma: none</code>+ <td><code>max-lightness: 60</code>, <code>max-chroma: 150</code></td>- <td><code>min-lightness: 47</code>, <code>max-chroma: none</code>+ <td><code>min-lightness: 47</code>, <code>max-chroma: 150</code></td></tr><tr>@@ -224,8 +227,11 @@ body.electron:not(.native-titlebar) {</tbody></table></figure>-<p>With these values, text stays at a contrast of at least 4.5:1 against- the page and on every background, and borders at 3:1.</p>-<p>The variables are read once, when Trilium starts. They apply to colors- applied from then on; colors already in notes keep the shades they were- saved with.</p>\ No newline at end of file+<p>With these values, colored text stays at a contrast of at least 4.5:1+ against the page, and so does the theme's own text on every background;+ borders stay at 3:1.</p>+<p>The limits apply while a note is displayed, so a change to them affects+ every note at once. The note itself keeps each color as it was picked,+ in its <code>color</code>, <code>background-color</code> or <code>border-color</code> style,+ and a second time in a <code>--tn-color</code>, <code>--tn-background</code> or <code>--tn-border-color</code> variable,+ which the adaptation reads.</p>\ No newline at end of filediff --git a/docs/User Guide/User Guide/Note Types/Markdown.md b/docs/User Guide/User Guide/Note Types/Markdown.mdindex 6b2f06bde3..f1d0f753b6 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);--tn-background:#e5e64d;">Highlighted</span>+ <span style="background-color:#e5e64d;--tn-background:#e5e64d;">Highlighted</span>```### Linksdiff --git a/docs/User Guide/User Guide/Note Types/Text/General formatting.md b/docs/User Guide/User Guide/Note Types/Text/General formatting.mdindex a47673d55d..62a61feef1 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,11 +65,11 @@ Selected text can be colored with one of the predefined colors from a palette orOnce there is at least one color defined in the document, it will appear in the list for easy reuse.-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 adapt to the [theme](../../Basic%20Concepts%20and%20Features/Themes.md). Trilium shows each color in a lighter or darker shade that suits the current theme, so the text stays readable after switching between light and dark themes. 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, and to shared notes too. The note itself keeps the color as it was picked, so an exported note shows it unchanged.-Colors applied with older versions of Trilium are kept exactly as they are, until a new color is applied to that text.+Colors applied with older versions of Trilium are shown exactly as they were picked, until the note is next edited.-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.+Older browsers that can't adapt colors show them exactly as they were picked.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/docs/User Guide/User Guide/Note Types/Text/Tables.md b/docs/User Guide/User Guide/Note Types/Text/Tables.mdindex 9c1d80362f..ea26fd88a4 100644--- a/docs/User Guide/User Guide/Note Types/Text/Tables.md+++ b/docs/User Guide/User Guide/Note Types/Text/Tables.md@@ -171,13 +171,11 @@ The cell will immediately update to reflect the changes, but the _Save_ button m## Border and background colors-The border and background colors of tables and cells adapt to the [theme](../../Basic%20Concepts%20and%20Features/Themes.md), the same way as [text colors](General%20formatting.md) do. A color picked from the palette, chosen with the color picker or typed in is saved in two shades, one for light themes and one for dark themes, so borders stay visible and text stays readable on the background in both. The hue stays the same.+The border and background colors of tables and cells adapt to the [theme](../../Basic%20Concepts%20and%20Features/Themes.md), the same way as [text colors](General%20formatting.md) do. A color picked from the palette, chosen with the color picker or typed in is shown in a lighter or darker shade that suits the current theme, so borders stay visible and text stays readable on the background. The hue stays the same, and the table keeps the color as it was picked.-Once a color is applied, its field shows the saved value as `light-dark(…)`. To change the color, pick or type a new one.+Colors applied with older versions of Trilium are shown exactly as they were picked, until the note is next edited.-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.+Older browsers that can't adapt colors show them exactly as they were picked.## Captiondiff --git a/docs/User Guide/User Guide/Theme development/Reference.md b/docs/User Guide/User Guide/Theme development/Reference.mdindex b8a6516a02..fd3cf758f7 100644--- a/docs/User Guide/User Guide/Theme development/Reference.md+++ b/docs/User Guide/User Guide/Theme development/Reference.md@@ -201,7 +201,7 @@ This will affect the behavior of the Electron application by informing the opera## Adaptive text and table colors-Colors applied in a text note, from the font color and background color buttons (see <a class="reference-link" href="../Note%20Types/Text/General%20formatting.md">General formatting</a>) or from the table and cell properties (see <a class="reference-link" href="../Note%20Types/Text/Tables.md">Tables</a>), are saved in two shades: one for light themes and one for dark themes. A theme can change the limits these shades are kept within, for example if its page background is much darker or lighter than the one of the built-in themes:+Colors applied in a text note, from the font color and background color buttons (see <a class="reference-link" href="../Note%20Types/Text/General%20formatting.md">General formatting</a>) or from the table and cell properties (see <a class="reference-link" href="../Note%20Types/Text/Tables.md">Tables</a>), are shown in a shade that suits the theme: the hue stays, while the lightness and the saturation are kept within limits. A theme can change these limits, for example if its page background is much darker or lighter than the one of the built-in themes:```css:root {@@ -213,18 +213,18 @@ Colors applied in a text note, from the font color and background color buttonsEach variable is named `--adaptive-<role>-<light|dark>-<limit>`:* The role is `text` (font color), `background` (font background color), `table-border` or `table-background` (tables and cells).-* `light` or `dark` is the shade the limit applies to.-* The limit is `min-lightness` or `max-lightness` (the CIELAB lightness, from 0 for black to 100 for white), or `max-chroma` (how saturated the color can be, with `none` for no limit).+* `light` or `dark` is the kind of theme the limit applies to, as declared by `--theme-style`.+* The limit is `min-lightness` or `max-lightness` (the CIELAB lightness, from 0 for black to 100 for white), or `max-chroma` (how saturated the color can be; `150` sets no practical limit). Each value must be a plain number, otherwise the colors lose their adaptation.The defaults are:-| Role | Light shade | Dark shade |+| Role | Light themes | Dark themes || --- | --- | --- |-| `text` | `max-lightness: 40`, `max-chroma: none` | `min-lightness: 75`, `max-chroma: 55` |+| `text` | `max-lightness: 40`, `max-chroma: 150` | `min-lightness: 75`, `max-chroma: 55` || `background` | `min-lightness: 90`, `max-chroma: 20` | `max-lightness: 30`, `max-chroma: 30` |-| `table-border` | `max-lightness: 60`, `max-chroma: none` | `min-lightness: 47`, `max-chroma: none` |+| `table-border` | `max-lightness: 60`, `max-chroma: 150` | `min-lightness: 47`, `max-chroma: 150` || `table-background` | `min-lightness: 90`, `max-chroma: 20` | `max-lightness: 30`, `max-chroma: 30` |-With these values, text stays at a contrast of at least 4.5:1 against the page and on every background, and borders at 3:1.+With these values, colored text stays at a contrast of at least 4.5:1 against the page, and so does the theme's own text on every background; borders stay at 3:1.-The variables are read once, when Trilium starts. They apply to colors applied from then on; colors already in notes keep the shades they were saved with.\ No newline at end of file+The limits apply while a note is displayed, so a change to them affects every note at once. The note itself keeps each color as it was picked, in its `color`, `background-color` or `border-color` style, and a second time in a `--tn-color`, `--tn-background` or `--tn-border-color` variable, which the adaptation reads.\ No newline at end of filediff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.tsindex 58f2fe59cb..836ccb0b2f 100644--- a/packages/ckeditor5/src/index.ts+++ b/packages/ckeditor5/src/index.ts@@ -5,7 +5,6 @@ import "ckeditor5/ckeditor5.css";import "./theme/blockquote.css";import "./theme/code_block_toolbar.css";import "./theme/link_embed_form.css";-import type { AdaptiveColorBands } from "@triliumnext/commons";import type { ClipboardImageEmbedConfig } from "./plugins/clipboard_image_embed.js";import type { PasteTarget } from "./plugins/cuttonote.js";import { COMMON_PLUGINS, CORE_PLUGINS, POPUP_EDITOR_PLUGINS } from "./plugins.js";@@ -109,8 +108,6 @@ declare module "ckeditor5" {copyHtml?(html: string, plainText: string): void;},clipboardImageEmbed?: ClipboardImageEmbedConfig,- /** The theme's limits for the colors `AdaptiveColors` stores (see `adaptColor`). */- adaptiveColorBands?: AdaptiveColorBands,autoSort?: {/** More date formats for table sorting to recognize, in Day.js syntax. */dateFormats?: string[];diff --git a/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts b/packages/ckeditor5/src/plugins/adaptive_colors.spec.tsindex 3fb358e095..df9136840e 100644--- a/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts+++ b/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts@@ -1,8 +1,3 @@-import {- adaptColor,- DEFAULT_ADAPTIVE_COLOR_BANDS,- toAdaptiveColorValue-} from "@triliumnext/commons";import {_getModelData as getModelData,_setModelData as setModelData,@@ -10,6 +5,7 @@ import {Essentials,FontBackgroundColor,FontColor,+ GeneralHtmlSupport,Paragraph,Table,TableCellProperties,@@ -31,91 +27,43 @@ describe("AdaptiveColors", () => {setModelData(editor.model, "<paragraph>[text]</paragraph>");});- 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: "#e5e64d" });+ it("stores the color as picked, and saves it again as a CSS variable", () => {+ editor.execute("fontColor", { value: "#e64d4d" });+ editor.execute("fontBackgroundColor", { value: "hsl(60, 75%, 60%)" });- 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}">`+ "<paragraph><$text fontBackgroundColor=\"hsl(60, 75%, 60%)\" fontColor=\"#e64d4d\">"+ "text</$text></paragraph>");- });-- 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("/*");+ expect(saved).toContain("color:#e64d4d;");+ expect(saved).toContain("--tn-color:#e64d4d;");+ expect(saved).toContain("background-color:hsl(60, 75%, 60%);");+ expect(saved).toContain("--tn-background:hsl(60, 75%, 60%);");+ });+ it("loads the color without its variable, and writes the variable again when saving", () => {+ const saved = "<p><span style=\"--tn-color:#e64d4d;color:#e64d4d;\">a</span></p>";editor.setData(saved);- expect(editor.getData()).toBe(saved);expect(getModelData(editor.model, { withoutSelection: true }))- .toContain(`fontColor="${toAdaptiveColorValue("#e64d4d", "text")}"`);- });+ .toBe("<paragraph><$text fontColor=\"#e64d4d\">a</$text></paragraph>");+ expect(editor.getData()).toBe(saved);- 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);+ // A color saved before the variables existed gets one too.+ editor.setData("<p><span style=\"color:#ff0000;\">b</span></p>");+ expect(editor.getData())+ .toBe("<p><span style=\"--tn-color:#ff0000;color:#ff0000;\">b</span></p>");});- 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="${value}">text</$text></paragraph>`);-+ it("removes the variable with the color", () => {+ editor.execute("fontColor", { value: "#e64d4d" });editor.execute("fontColor");- expect(editor.getData()).toBe("<p>text</p>");-editor.execute("fontBackgroundColor", { value: "#e64d4d" });editor.execute("fontBackgroundColor", { value: "" });expect(editor.getData()).toBe("<p>text</p>");});- it("uses the theme's limits from the editor config", async () => {- const bands = {- ...DEFAULT_ADAPTIVE_COLOR_BANDS,- text: {- ...DEFAULT_ADAPTIVE_COLOR_BANDS.text,- light: { minLightness: 0, maxLightness: 0, maxChroma: Infinity }- }- };- const themed = await createTestEditor(- [ Essentials, Paragraph, FontColor, AdaptiveColors ],- { adaptiveColorBands: bands }- );- setModelData(themed.model, "<paragraph>[text]</paragraph>");-- themed.execute("fontColor", { value: "#e64d4d" });- const value = toAdaptiveColorValue("#e64d4d", "text", bands);- expect(value).toMatch(/^light-dark\(#000000,/);- expect(getModelData(themed.model, { withoutSelection: true }))- .toBe(`<paragraph><$text fontColor="${value}">text</$text></paragraph>`);- });-- it("converts text colors in an editor without the table properties plugins", async () => {- const textOnly = await createTestEditor([- Essentials, Paragraph, FontColor, FontBackgroundColor, AdaptiveColors- ]);- setModelData(textOnly.model, "<paragraph>[text]</paragraph>");-- textOnly.execute("fontColor", { value: "#e64d4d" });- const value = toAdaptiveColorValue("#e64d4d", "text");- expect(getModelData(textOnly.model, { withoutSelection: true }))- .toBe(`<paragraph><$text fontColor="${value}">text</$text></paragraph>`);- });-- it("stores table and cell colors as pairs, through saving and loading", () => {+ it("writes the variables of table and cell backgrounds and borders", () => {setModelData(editor.model, "<table><tableRow><tableCell><paragraph>[]a</paragraph>"+ "</tableCell></tableRow></table>");editor.execute("tableBorderStyle", { value: "solid" });@@ -123,19 +71,16 @@ describe("AdaptiveColors", () => {editor.execute("tableBorderColor", { value: "#4d99e6" });editor.execute("tableBackgroundColor", { value: "#e5e64d" });editor.execute("tableCellBorderStyle", { value: "dashed" });- editor.execute("tableCellBorderWidth", { value: "1px" });editor.execute("tableCellBorderColor", { value: "#000000" });editor.execute("tableCellBackgroundColor", { value: "#e64d4d" });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("/*");+ expect(saved).toContain("border:2px solid #4d99e6;");+ expect(saved).toContain("--tn-border-color:#4d99e6;");+ expect(saved).toContain("--tn-background:#e5e64d;");+ expect(saved).toContain("border-color:#000000;");+ expect(saved).toContain("--tn-border-color:#000000;");+ expect(saved).toContain("--tn-background:#e64d4d;");editor.setData(saved);expect(editor.getData()).toBe(saved);@@ -147,6 +92,23 @@ describe("AdaptiveColors", () => {}editor.model.change((writer) => writer.setSelection(cellParagraph, 0));editor.execute("tableCellBackgroundColor", { value: "" });- expect(editor.getData()).not.toContain("--tn-background:#e64d4d");+ editor.execute("tableCellBorderColor", { value: "" });+ const cleared = editor.getData();+ expect(cleared).not.toContain("--tn-background:#e64d4d");+ expect(cleared).not.toContain("--tn-border-color:#000000");+ });++ it("keeps a variable out of the model, also with General HTML Support", async () => {+ const withGhs = await createTestEditor(+ [ Essentials, Paragraph, FontColor, GeneralHtmlSupport, AdaptiveColors ],+ { htmlSupport: { allow: [ { name: "span", styles: true } ] } }+ );+ withGhs.setData("<p><span style=\"--tn-color:#000000;color:#e64d4d;\">a</span></p>");++ // A stale variable would otherwise outlive its color and adapt the wrong one.+ expect(getModelData(withGhs.model, { withoutSelection: true }))+ .toBe("<paragraph><$text fontColor=\"#e64d4d\">a</$text></paragraph>");+ expect(withGhs.getData())+ .toBe("<p><span style=\"--tn-color:#e64d4d;color:#e64d4d;\">a</span></p>");});});diff --git a/packages/ckeditor5/src/plugins/adaptive_colors.ts b/packages/ckeditor5/src/plugins/adaptive_colors.tsindex 7751a6e2fb..f63854f7df 100644--- a/packages/ckeditor5/src/plugins/adaptive_colors.ts+++ b/packages/ckeditor5/src/plugins/adaptive_colors.ts@@ -1,27 +1,16 @@import {- adaptColor,- type AdaptiveColorBands,- type AdaptiveColorRole,- joinAdaptiveColorValue,- splitAdaptiveColorValue,- toAdaptiveColorValue-} from "@triliumnext/commons";-import {- type CommandExecuteEvent,type DowncastAttributeEvent,type ModelElement,Plugin,- priorities,+ type UpcastElementEvent,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.+ * Saves the colors of text and tables a second time as CSS variables: `--tn-color`,+ * `--tn-background` and `--tn-border-color`. The app's and the share theme's stylesheets derive a+ * shade that suits the theme from them; everything else shows the color itself, which stays in the+ * markup. The variables never reach the model.*/export default class AdaptiveColors extends Plugin {@@ -32,169 +21,84 @@ export default class AdaptiveColors extends Plugin {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, hasSource } ] of Object.entries(COMMANDS)) {- this.adaptCommandValue(commandName, role, hasSource, bands);- }+ this.addVariable("table", "tableBackgroundColor", "--tn-background");+ this.addVariable("table", "tableBorderColor", "--tn-border-color");+ this.addVariable("tableCell", "tableCellBackgroundColor", "--tn-background");+ this.addVariable("tableCell", "tableCellBorderColor", "--tn-border-color");+ this.dropVariablesOnLoad();}- private adaptCommandValue(- commandName: string,- role: AdaptiveColorRole,- hasSource: boolean,- bands: AdaptiveColorBands | undefined- ) {- // An editor without the table properties plugins has no table color commands.- const command = this.editor.commands.get(commandName);- if (!command) {- return;- }-- this.listenTo<CommandExecuteEvent>(command, "execute", (_eventInfo, args) => {- const options = args[0] as { value?: unknown } | undefined;- if (typeof options?.value === "string") {- 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({+ /** Writes a text color or highlight as CKEditor does, with the variable next to it. */+ private convertTextColor(modelKey: string, property: string, variable: string) {+ this.editor.conversion.for("downcast").attributeToElement({model: modelKey,view: (value: string, { writer }) => writer.createAttributeElement("span",- { style: toStyleText(value, property, sourceProperty) },+ { style: `${property}:${value};${variable}:${value}` },// 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.+ * Sets the variable on the `<table>` or the cell next to the style CKEditor writes for the+ * attribute, leaving CKEditor's conversion in place. A border whose sides differ gets none.*/- private convertTableBackground() {- const conversion = this.editor.conversion;- conversion.for("downcast").add((dispatcher) => {+ private addVariable(modelElement: string, attribute: string, variable: string) {+ this.editor.conversion.for("downcast").add((dispatcher) => {dispatcher.on<DowncastAttributeEvent<ModelElement>>(- "attribute:tableBackgroundColor:table",+ `attribute:${attribute}:${modelElement}`,(eventInfo, data, { consumable, mapper, writer }) => {- if (!consumable.consume(data.item, eventInfo.name)) {+ if (!consumable.test(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")) {+ const element = findStyledElement(mapper.toViewElement(data.item));+ if (!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);+ const value = data.attributeNewValue;+ if (typeof value === "string" && value) {+ writer.setStyle(variable, value, element);+ } else {+ writer.removeStyle(variable, element);}},{ 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, 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 };-}+ /** Takes the variables off loaded elements, so General HTML Support cannot keep a stale one. */+ private dropVariablesOnLoad() {+ this.editor.conversion.for("upcast").add((dispatcher) => {+ dispatcher.on<UpcastElementEvent>(+ "element",+ (_eventInfo, { viewItem }, { consumable }) => {+ for (const variable of VARIABLES) {+ if (viewItem.hasStyle(variable)) {+ consumable.consume(viewItem, { styles: variable });+ }+ }+ },+ { priority: "highest" }+ );+ });+ }-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(";");-}+const VARIABLES = [ "--tn-color", "--tn-background", "--tn-border-color" ];-/** 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());-}+/** The cell itself, or the `<table>` inside the table widget's `<figure>`. */+function findStyledElement(viewElement: ViewElement | undefined) {+ if (!viewElement?.is("element", "figure")) {+ return viewElement;+ }-function readBackground(element: ViewElement) {- return readValue(element, "background-color", "--tn-background");+ const table = [ ...viewElement.getChildren() ].find((child) => child.is("element", "table"));+ return table?.is("element") ? table : undefined;}diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex add128ff57..d522f4500e 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -1,5 +1,4 @@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.tsdeleted file mode 100644index 094427efdc..0000000000--- a/packages/commons/src/lib/adaptive_color.spec.ts+++ /dev/null@@ -1,158 +0,0 @@-import { describe, expect, it } from "vitest";--import {- adaptColor,- DEFAULT_ADAPTIVE_COLOR_BANDS,- joinAdaptiveColorValue,- splitAdaptiveColorValue,- toAdaptiveColorValue-} 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("keeps table borders visible and table backgrounds readable in both themes", () => {- const colors = [ ...HUES, ...GREYS ];- const text = colors.map((color) => pairOf(adaptColor(color, "text")));-- for (const theme of [ "light", "dark" ] as const) {- const { background: page, text: defaultText } = PAGE[theme];- for (const color of colors) {- // 3:1 is the WCAG minimum for graphical objects.- const border = pairOf(adaptColor(color, "tableBorder"))[theme];- expect(contrast(border, page)).toBeGreaterThanOrEqual(3);-- const cell = pairOf(adaptColor(color, "tableBackground"))[theme];- expect(contrast(defaultText, cell)).toBeGreaterThanOrEqual(4.5);- for (const textPair of text) {- expect(contrast(textPair[theme], cell)).toBeGreaterThanOrEqual(4.5);- }- }- }-- // A border that is already visible in both themes keeps its color.- expect(adaptColor("#e64d4d", "tableBorder")).toBe("light-dark(#e64d4d,#e64d4d)");- });-- it("uses the limits it is given instead of the defaults", () => {- const bands = {- ...DEFAULT_ADAPTIVE_COLOR_BANDS,- text: {- ...DEFAULT_ADAPTIVE_COLOR_BANDS.text,- light: { minLightness: 0, maxLightness: 0, maxChroma: Infinity }- }- };- const defaultDark = pairOf(adaptColor("#e64d4d", "text")).dark;- expect(adaptColor("#e64d4d", "text", bands)).toBe(`light-dark(#000000,${defaultDark})`);- });-- it("gives each grey a shade of its own in both themes", () => {- for (const role of [ "text", "background", "tableBorder", "tableBackground" ] 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"));- expect(adaptColor("rgb(100%, 0%, 0%)", "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("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%)",- "#11223344", "red", "var(--accent)", "#12345", "hsl(none 50% 50%)", ""- ]) {- 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.tsdeleted file mode 100644index 7cfe98afc3..0000000000--- a/packages/commons/src/lib/adaptive_color.ts+++ /dev/null@@ -1,224 +0,0 @@-/**- * What a color paints: text (Font Color), the background behind text (Font Background Color), or a- * table's or cell's border or background.- */-export type AdaptiveColorRole = "text" | "background" | "tableBorder" | "tableBackground";--/** The CIELAB lightness range and chroma cap of a role in one theme. */-export interface AdaptiveColorBand {- minLightness: number;- maxLightness: number;- maxChroma: number;-}--export type AdaptiveColorBands =- Record<AdaptiveColorRole, Record<"light" | "dark", AdaptiveColorBand>>;--/**- * Turns a color into a `light-dark(#light,#dark)` pair, so text, highlights and tables 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.- * @param bands the limits to use, for example the ones a theme defines.- */-export function adaptColor(- color: string,- role: AdaptiveColorRole,- bands: AdaptiveColorBands = DEFAULT_ADAPTIVE_COLOR_BANDS-): string {- const rgb = parseColor(color.trim());- if (!rgb) {- return color;- }-- const lab = rgbToLab(rgb);- const { light, dark } = bands[role];- 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.- * The client reads the theme's values from the `--adaptive-*` CSS variables in `style.css`.- */-export const DEFAULT_ADAPTIVE_COLOR_BANDS: AdaptiveColorBands = {- 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 }- },- tableBorder: {- light: { minLightness: 0, maxLightness: 60, maxChroma: Infinity },- dark: { minLightness: 47, maxLightness: 100, maxChroma: Infinity }- },- tableBackground: {- light: { minLightness: 90, maxLightness: 100, maxChroma: 20 },- dark: { minLightness: 0, maxLightness: 30, maxChroma: 30 }- }-};--type Rgb = [number, number, number];-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;--function fitToBand([ lightness, a, b ]: Lab, band: AdaptiveColorBand): 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 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(Math.min(1, Math.max(0, c)) * 255))- .map((c) => c.toString(16).padStart(2, "0"))- .join("")}`;-}diff --git a/packages/commons/src/lib/marked_extensions.ts b/packages/commons/src/lib/marked_extensions.tsindex bff709e1c8..2cc503ca2e 100644--- a/packages/commons/src/lib/marked_extensions.ts+++ b/packages/commons/src/lib/marked_extensions.ts@@ -1,7 +1,5 @@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.@@ -102,9 +100,6 @@ 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@@ -113,15 +108,15 @@ export const HIGHLIGHT_SOURCE = "#e5e64d";* 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 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.+ * 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.*/-export const HIGHLIGHT_BACKGROUND = adaptColor(HIGHLIGHT_SOURCE, "background");+export const HIGHLIGHT_BACKGROUND = "#e5e64d";-/** The style of a highlight, with the colour as picked as the text editor saves it. */+/** The style of a highlight as the text editor saves it, with the theme-adaptive variable. */export const HIGHLIGHT_STYLE =- `background-color:${HIGHLIGHT_BACKGROUND};--tn-background:${HIGHLIGHT_SOURCE};`;+ `background-color:${HIGHLIGHT_BACKGROUND};--tn-background:${HIGHLIGHT_BACKGROUND};`;/*** Creates an extension for highlights: `==text==` → a background-coloured `<span>`.@@ -155,7 +150,8 @@ export function createHighlightExtension(): TokenizerAndRendererExtension {},renderer(token) {- return `<span style="${HIGHLIGHT_STYLE}">${this.parser.parseInline(token.tokens as Token[])}</span>`;+ const content = this.parser.parseInline(token.tokens as Token[]);+ return `<span style="${HIGHLIGHT_STYLE}">${content}</span>`;}};}diff --git a/packages/share-theme/src/styles/adaptive-colors.css b/packages/share-theme/src/styles/adaptive-colors.cssnew file mode 100644index 0000000000..e21cb42566--- /dev/null+++ b/packages/share-theme/src/styles/adaptive-colors.css@@ -0,0 +1,100 @@+/*+ * Theme-adaptive text and table colors. The text editor saves each color again as `--tn-color`,+ * `--tn-background` or `--tn-border-color`; these rules keep its hue, move its CIELAB lightness+ * into the role's range and cap its chroma. Greys (chroma below 1.5) spread over the range.+ * Keep in step with `apps/client/src/stylesheets/adaptive-colors.css`.+ */++/* Zero specificity, so that a theme's :root wins although themes load before this file. */+:where(:root) {+ /* Adaptive font color limits */+ --adaptive-text-light-max-lightness: 40;+ --adaptive-text-light-max-chroma: 150;+ --adaptive-text-dark-min-lightness: 75;+ --adaptive-text-dark-max-chroma: 55;++ /* Adaptive font background color limits */+ --adaptive-background-light-min-lightness: 90;+ --adaptive-background-light-max-chroma: 20;+ --adaptive-background-dark-max-lightness: 30;+ --adaptive-background-dark-max-chroma: 30;++ /* Adaptive table border color limits */+ --adaptive-table-border-light-max-lightness: 60;+ --adaptive-table-border-light-max-chroma: 150;+ /* Higher than in the app, for 3:1 against the lighter dark page. */+ --adaptive-table-border-dark-min-lightness: 52;+ --adaptive-table-border-dark-max-chroma: 150;++ /* Adaptive table background color limits */+ --adaptive-table-background-light-min-lightness: 90;+ --adaptive-table-background-light-max-chroma: 20;+ --adaptive-table-background-dark-max-lightness: 30;+ --adaptive-table-background-dark-max-chroma: 30;+}++:root {+ --_adaptive-text-min: 0;+ --_adaptive-text-max: var(--adaptive-text-light-max-lightness);+ --_adaptive-text-chroma: var(--adaptive-text-light-max-chroma);+ --_adaptive-background-min: var(--adaptive-background-light-min-lightness);+ --_adaptive-background-max: 100;+ --_adaptive-background-chroma: var(--adaptive-background-light-max-chroma);+ --_adaptive-table-border-min: 0;+ --_adaptive-table-border-max: var(--adaptive-table-border-light-max-lightness);+ --_adaptive-table-border-chroma: var(--adaptive-table-border-light-max-chroma);+ --_adaptive-table-background-min: var(--adaptive-table-background-light-min-lightness);+ --_adaptive-table-background-max: 100;+ --_adaptive-table-background-chroma: var(--adaptive-table-background-light-max-chroma);+}++html.theme-dark {+ --_adaptive-text-min: var(--adaptive-text-dark-min-lightness);+ --_adaptive-text-max: 100;+ --_adaptive-text-chroma: var(--adaptive-text-dark-max-chroma);+ --_adaptive-background-min: 0;+ --_adaptive-background-max: var(--adaptive-background-dark-max-lightness);+ --_adaptive-background-chroma: var(--adaptive-background-dark-max-chroma);+ --_adaptive-table-border-min: var(--adaptive-table-border-dark-min-lightness);+ --_adaptive-table-border-max: 100;+ --_adaptive-table-border-chroma: var(--adaptive-table-border-dark-max-chroma);+ --_adaptive-table-background-min: 0;+ --_adaptive-table-background-max: var(--adaptive-table-background-dark-max-lightness);+ --_adaptive-table-background-chroma: var(--adaptive-table-background-dark-max-chroma);+}++/* `!important` beats the inline color, which browsers without relative colors keep showing. */+[style*="--tn-color"] {+ color: lch(from var(--tn-color)+ calc(min(1, c / 1.5) * clamp(var(--_adaptive-text-min), l, var(--_adaptive-text-max))+ + (1 - min(1, c / 1.5)) * (var(--_adaptive-text-min)+ + l / 100 * (var(--_adaptive-text-max) - var(--_adaptive-text-min))))+ min(c, var(--_adaptive-text-chroma)) h) !important;+}++[style*="--tn-background"] {+ background-color: lch(from var(--tn-background)+ calc(min(1, c / 1.5)+ * clamp(var(--_adaptive-background-min), l, var(--_adaptive-background-max))+ + (1 - min(1, c / 1.5)) * (var(--_adaptive-background-min)+ + l / 100 * (var(--_adaptive-background-max) - var(--_adaptive-background-min))))+ min(c, var(--_adaptive-background-chroma)) h) !important;+}++:is(table, td, th)[style*="--tn-border-color"] {+ border-color: lch(from var(--tn-border-color)+ calc(min(1, c / 1.5)+ * clamp(var(--_adaptive-table-border-min), l, var(--_adaptive-table-border-max))+ + (1 - min(1, c / 1.5)) * (var(--_adaptive-table-border-min) + l / 100+ * (var(--_adaptive-table-border-max) - var(--_adaptive-table-border-min))))+ min(c, var(--_adaptive-table-border-chroma)) h) !important;+}++:is(table, td, th)[style*="--tn-background"] {+ background-color: lch(from var(--tn-background)+ calc(min(1, c / 1.5) * clamp(var(--_adaptive-table-background-min), l,+ var(--_adaptive-table-background-max))+ + (1 - min(1, c / 1.5)) * (var(--_adaptive-table-background-min) + l / 100+ * (var(--_adaptive-table-background-max) - var(--_adaptive-table-background-min))))+ min(c, var(--_adaptive-table-background-chroma)) h) !important;+}diff --git a/packages/share-theme/src/styles/content.css b/packages/share-theme/src/styles/content.cssindex 28b6b58f78..20bbf614d3 100644--- a/packages/share-theme/src/styles/content.css+++ b/packages/share-theme/src/styles/content.css@@ -5,17 +5,6 @@--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/share-theme/src/styles/index.css b/packages/share-theme/src/styles/index.cssindex 61fc933925..9efc6d7516 100644--- a/packages/share-theme/src/styles/index.css+++ b/packages/share-theme/src/styles/index.css@@ -9,6 +9,7 @@@import "./layout.css";@import "./content.css";@import "./task-states.css";+@import "./adaptive-colors.css";@import "./content-footer.css";@import "./link-embed.css";diff --git a/packages/trilium-core/src/services/export/markdown.spec.ts b/packages/trilium-core/src/services/export/markdown.spec.tsindex e7a50199c3..2b14e922e0 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, HIGHLIGHT_SOURCE, HIGHLIGHT_STYLE, trimIndentation } from "@triliumnext/commons";+import { HIGHLIGHT_BACKGROUND, HIGHLIGHT_STYLE, trimIndentation } from "@triliumnext/commons";import { describe, expect,it } from "vitest";import markdownExportService, { DEFAULT_ADMONITION_TYPE } from "./markdown.js";@@ -852,30 +852,17 @@ 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.");+ it("renders the palette yellow as ==text==, ignoring its theme-adaptive variable", () => {+ const yellow = `<span style="background-color:${HIGHLIGHT_BACKGROUND};">a</span>`;+ expect(markdownExportService.toMarkdown(`<p>${yellow}</p>`)).toBe("==a==");+ const withVariable = `<span style="${HIGHLIGHT_STYLE}">b</span>`;+ expect(markdownExportService.toMarkdown(`<p>${withVariable}</p>`)).toBe("==b==");- // Another adaptive pair keeps its colour.- const red = `<span style="background-color:light-dark(#ffdad6,#713531)">red</span>`;+ // Another colour keeps its colour and its variable.+ const red = `<span style="background-color:#e64d4d;--tn-background:#e64d4d;">c</span>`;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.tsindex 5c9928238e..f7b2cec646 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, HIGHLIGHT_SOURCE } from "@triliumnext/commons/src/lib/marked_extensions.js";+import { HIGHLIGHT_BACKGROUND } 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";@@ -532,7 +532,9 @@ function isPlainDefaultHighlight(node: HTMLElement): boolean {return false;}- const declarations = parseStyleDeclarations(node.getAttribute("style"));+ // The text editor repeats every color in a `--tn-*` variable for the theme to adapt.+ const declarations = parseStyleDeclarations(node.getAttribute("style"))+ .filter(({ property }) => !property.startsWith("--tn-"));// A bare `<mark>` is a highlight with no colour of its own; a span always has a declaration,// since that is what the filter matched on.@@ -540,15 +542,6 @@ 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;}@@ -559,8 +552,9 @@ function isPlainDefaultHighlight(node: HTMLElement): boolean {&& 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);+/** The palette Yellow, and CKEditor's stock yellow that Markdown imports used before it. */+const DEFAULT_HIGHLIGHT_BACKGROUNDS = [ HIGHLIGHT_BACKGROUND, "hsl(60, 75%, 60%)" ]+ .map(normalizeColor);function parseStyleDeclarations(style: string | null) {return (style ?? "")diff --git a/packages/trilium-core/src/services/sanitizer.spec.ts b/packages/trilium-core/src/services/sanitizer.spec.tsindex 09cf3c9fb5..56e94bf39a 100644--- a/packages/trilium-core/src/services/sanitizer.spec.ts+++ b/packages/trilium-core/src/services/sanitizer.spec.ts@@ -74,49 +74,27 @@ 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>");- });-- 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)";+ it("keeps the theme-adaptive color variables next to the colors", () => {+ const style = "color:#e64d4d;--tn-color:#e64d4d;"+ + "background-color:#e5e64d;--tn-background:#e5e64d";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.+ // Only a color passes, only under these names, and a border color only on tables.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>`- + `<th style="border-color:${pair}">H</th>`- + `<td style="border:1px solid ${pair}">C</td>`- + `<td style="border-color:${pair}">D</td>`- + "</tr></tbody></table>";- expect(sanitizeHtml(dirty)).toBe(dirty);-- expect(sanitizeHtml(`<td style="border-color:light-dark(red,blue)">x</td>`))- .not.toContain("light-dark");+ expect(sanitizeHtml(`<span style="--tn-border-color:#e64d4d">x</span>`))+ .toBe("<span>x</span>");});it("keeps the border styles CKEditor writes for tables and cells", () => {// A border with a custom width is written as the shorthand, one with the default width as// separate properties.const dirty = `<figure class="table">`- + `<table style="border:2px solid light-dark(#4795e1,#4d99e6)"><tbody><tr>`+ + `<table style="border:2px solid #4d99e6;--tn-border-color:#4d99e6"><tbody><tr>`+ `<th style="border:1.5px double #000000">H</th>`- + `<td style="border-color:light-dark(#000000,#6f6f6f);border-style:dashed">C</td>`+ + `<td style="border-color:#555;--tn-border-color:#555;border-style:dashed">C</td>`+ `<td style="border-style:dotted;border-width:3px">D</td>`+ "</tr></tbody></table></figure>";expect(sanitizeHtml(dirty)).toBe(dirty);diff --git a/packages/trilium-core/src/services/sanitizer.ts b/packages/trilium-core/src/services/sanitizer.tsindex dbd8c236b4..ceef2d2e96 100644--- a/packages/trilium-core/src/services/sanitizer.ts+++ b/packages/trilium-core/src/services/sanitizer.ts@@ -36,16 +36,16 @@ 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 borderColorRegex = [ ...colorRegex, /^\s*transparent\s*$/ ];const sizeRegex = [/^\d+\.?\d*(?:px|em|%)$/];// The border styles CKEditor writes for tables and cells: the shorthand for a border with a// custom width, separate properties otherwise.const tableBorderStyles = {"border": [- /^\s*\d+\.?\d*(?:px|em|%)\s*(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)\s*(#(0x)?[0-9a-fA-F]+|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})%\)|light-dark\(\s*#[0-9a-fA-F]{6}\s*,\s*#[0-9a-fA-F]{6}\s*\))\s*$/+ /^\s*\d+\.?\d*(?:px|em|%)\s*(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)\s*(#(0x)?[0-9a-fA-F]+|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*$/],- "border-color": [ ...colorRegex, adaptiveColorRegex, /^\s*transparent\s*$/ ],+ "border-color": borderColorRegex,+ "--tn-border-color": borderColorRegex,"border-style": [/^\s*(none|hidden|dotted|dashed|solid|double|groove|ridge|inset|outset)\s*$/],@@ -71,11 +71,11 @@ export function sanitizeHtml(dirtyHtml: string) {},allowedStyles: {"*": {- 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 ],+ color: colorRegex,+ "background-color": colorRegex,+ // Copies of the colors that the app's and the share theme's stylesheets adapt.+ "--tn-color": colorRegex,+ "--tn-background": colorRegex,"margin-left": sizeRegex,"padding-left": sizeRegex,"text-align": [/^\s*(left|center|right|justify)\s*$/],