Skip to content

Build your personal knowledge base with Trilium Notes

client/adaptive colors: read color parameters from CSS

Adorian Doran602fc98c679b
diff --git a/apps/client/src/services/adaptive_colors.spec.ts b/apps/client/src/services/adaptive_colors.spec.ts
new file mode 100644
index 0000000000..fb7338583b
--- /dev/null
+++ b/apps/client/src/services/adaptive_colors.spec.ts
@@ -0,0 +1,56 @@
+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;
+ const variables = [ ...styleCss.matchAll(pattern) ];
+ expect(variables).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.ts
new file mode 100644
index 0000000000..7c1eae255d
--- /dev/null
+++ b/apps/client/src/services/adaptive_colors.ts
@@ -0,0 +1,51 @@
+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/style.css b/apps/client/src/stylesheets/style.css
index 5e136a2f97..b1c1f034e7 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -33,6 +33,30 @@
--tree-item-light-theme-max-color-lightness: 50;
--tree-item-dark-theme-min-color-lightness: 75;
+ /* 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;
+
/* Picks the half of the light-dark() text colors that matches the theme. */
color-scheme: var(--theme-style);
}
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 b116beb7b5..eb5a9ae6a9 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,4 +1,8 @@
-import { adaptColor, HIGHLIGHT_BACKGROUND } from "@triliumnext/commons";
+import {
+ adaptColor,
+ DEFAULT_ADAPTIVE_COLOR_BANDS as DEFAULTS,
+ HIGHLIGHT_BACKGROUND
+} from "@triliumnext/commons";
import { describe, expect, it, vi } from "vitest";
import { DEFAULT_COLOR_PALETTE } from "../../react/ColorPicker.js";
@@ -15,14 +19,14 @@ const LABELS = [
describe("buildFontColorConfig", () => {
it("lists four greys, then every note color hue, four to a row", () => {
- for (const palette of Object.values(buildFontColorConfig())) {
+ for (const palette of Object.values(buildFontColorConfig(DEFAULTS))) {
expect(palette.columns).toBe(4);
expect(palette.colors.map(({ label }) => label)).toEqual(LABELS);
}
});
it("stores each swatch as the pair for its role, without spaces", () => {
- const { fontColor, fontBackgroundColor } = buildFontColorConfig();
+ const { fontColor, fontBackgroundColor } = buildFontColorConfig(DEFAULTS);
expect(fontColor.colors.map(({ color }) => color))
.toEqual(SOURCES.map((color) => adaptColor(color, "text")));
expect(fontBackgroundColor.colors.map(({ color }) => color))
@@ -34,8 +38,22 @@ describe("buildFontColorConfig", () => {
}
});
- it("uses the palette's yellow for Markdown highlights", () => {
- const { colors } = buildFontColorConfig().fontBackgroundColor;
+ 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) => adaptColor(color, "background", bands)));
+ expect(colors[4].color).not.toBe(adaptColor(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);
});
});
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 c6d5919f78..2da53618f4 100644
--- a/apps/client/src/widgets/type_widgets/text/color_palette.ts
+++ b/apps/client/src/widgets/type_widgets/text/color_palette.ts
@@ -1,16 +1,16 @@
-import { adaptColor, type AdaptiveColorRole } from "@triliumnext/commons";
+import { adaptColor, type AdaptiveColorBands, type AdaptiveColorRole } from "@triliumnext/commons";
import { t } from "../../../services/i18n.js";
import { DEFAULT_COLOR_PALETTE } from "../../react/ColorPicker.js";
/**
* The swatches of the Font Color and Font Background Color dropdowns: four greys, then the hues of
- * the note color palette, each turned into a light and dark theme pair.
+ * the note color palette, each turned into a light and dark theme pair with the theme's `bands`.
*/
-export function buildFontColorConfig() {
+export function buildFontColorConfig(bands: AdaptiveColorBands) {
return {
- fontColor: { colors: buildAdaptedSwatches("text"), columns: 4 },
- fontBackgroundColor: { colors: buildAdaptedSwatches("background"), columns: 4 }
+ fontColor: { colors: buildAdaptedSwatches("text", bands), columns: 4 },
+ fontBackgroundColor: { colors: buildAdaptedSwatches("background", bands), columns: 4 }
};
}
@@ -39,8 +39,11 @@ const HUE_LABELS = [
"Blue", "Purple"
];
-function buildAdaptedSwatches(role: AdaptiveColorRole) {
- return buildSwatches().map((swatch) => ({ ...swatch, color: adaptColor(swatch.color, role) }));
+function buildAdaptedSwatches(role: AdaptiveColorRole, bands: AdaptiveColorBands) {
+ return buildSwatches().map((swatch) => ({
+ ...swatch,
+ color: adaptColor(swatch.color, role, bands)
+ }));
}
function buildSwatches() {
diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.ts
index 9ab5bf598a..80064aff00 100644
--- a/apps/client/src/widgets/type_widgets/text/config.ts
+++ b/apps/client/src/widgets/type_widgets/text/config.ts
@@ -3,6 +3,7 @@ import emojiDefinitionsUrl from "@triliumnext/ckeditor5/src/emoji_definitions/en
import { 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";
@@ -163,7 +164,8 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfi
alignment: {
options: [ "left", "right", "center", "justify"]
},
- ...buildFontColorConfig(),
+ ...buildFontColorConfig(ADAPTIVE_COLOR_BANDS),
+ adaptiveColorBands: ADAPTIVE_COLOR_BANDS,
link: {
defaultProtocol: "https://",
allowedProtocols: ALLOWED_PROTOCOLS,
diff --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.html
index 0a3efb2f32..99f5044f4e 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
@@ -156,4 +156,76 @@ body.electron:not(.native-titlebar) {
}</code></pre>
<p>This will affect the behavior of the Electron application by informing
the operating system of the color preference (e.g. background effects will
- appear correct on Windows).</p>
\ No newline at end of file
+ appear correct on Windows).</p>
+<h2>Adaptive text and table colors</h2>
+<p>Colors applied in a text note, from the font color and background color
+ buttons (see&nbsp;<a class="reference-link" href="#root/_help_Gr6xFaF6ioJ5">General formatting</a>)
+ or from the table and cell properties (see&nbsp;<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 {
+ --adaptive-text-light-max-lightness: 35;
+ --adaptive-text-dark-min-lightness: 80;
+}</code></pre>
+<p>Each variable is named <code>--adaptive-&lt;role&gt;-&lt;light|dark&gt;-&lt;limit&gt;</code>:</p>
+<ul>
+ <li>The role is <code>text</code> (font color), <code>background</code> (font
+ background color), <code>table-border</code> or <code>table-background</code> (tables
+ and cells).</li>
+ <li><code>light</code> or <code>dark</code> is the shade the limit applies to.</li>
+ <li>The limit is <code>min-lightness</code> or <code>max-lightness</code> (the
+ CIELAB 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>
+</ul>
+<p>The defaults are:</p>
+<figure class="table">
+ <table>
+ <thead>
+ <tr>
+ <th>Role</th>
+ <th>Light shade</th>
+ <th>Dark shade</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td><code>text</code>
+ </td>
+ <td><code>max-lightness: 40</code>, <code>max-chroma: none</code>
+ </td>
+ <td><code>min-lightness: 75</code>, <code>max-chroma: 55</code>
+ </td>
+ </tr>
+ <tr>
+ <td><code>background</code>
+ </td>
+ <td><code>min-lightness: 90</code>, <code>max-chroma: 20</code>
+ </td>
+ <td><code>max-lightness: 30</code>, <code>max-chroma: 30</code>
+ </td>
+ </tr>
+ <tr>
+ <td><code>table-border</code>
+ </td>
+ <td><code>max-lightness: 60</code>, <code>max-chroma: none</code>
+ </td>
+ <td><code>min-lightness: 47</code>, <code>max-chroma: none</code>
+ </td>
+ </tr>
+ <tr>
+ <td><code>table-background</code>
+ </td>
+ <td><code>min-lightness: 90</code>, <code>max-chroma: 20</code>
+ </td>
+ <td><code>max-lightness: 30</code>, <code>max-chroma: 30</code>
+ </td>
+ </tr>
+ </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
diff --git a/docs/User Guide/User Guide/Theme development/Reference.md b/docs/User Guide/User Guide/Theme development/Reference.md
index 33d9ec2519..b8a6516a02 100644
--- a/docs/User Guide/User Guide/Theme development/Reference.md
+++ b/docs/User Guide/User Guide/Theme development/Reference.md
@@ -197,4 +197,34 @@ If the theme is auto (e.g. supports both light or dark based on `prefers-color-s
}
```
-This will affect the behavior of the Electron application by informing the operating system of the color preference (e.g. background effects will appear correct on Windows).
\ No newline at end of file
+This will affect the behavior of the Electron application by informing the operating system of the color preference (e.g. background effects will appear correct on Windows).
+
+## 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:
+
+```css
+:root {
+ --adaptive-text-light-max-lightness: 35;
+ --adaptive-text-dark-min-lightness: 80;
+}
+```
+
+Each 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).
+
+The defaults are:
+
+| Role | Light shade | Dark shade |
+| --- | --- | --- |
+| `text` | `max-lightness: 40`, `max-chroma: none` | `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-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.
+
+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
diff --git a/packages/ckeditor5/src/index.ts b/packages/ckeditor5/src/index.ts
index 836ccb0b2f..58f2fe59cb 100644
--- a/packages/ckeditor5/src/index.ts
+++ b/packages/ckeditor5/src/index.ts
@@ -5,6 +5,7 @@ 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";
@@ -108,6 +109,8 @@ 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.ts
index bbe1d532d9..a8fd5a042a 100644
--- a/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts
+++ b/packages/ckeditor5/src/plugins/adaptive_colors.spec.ts
@@ -1,4 +1,4 @@
-import { adaptColor } from "@triliumnext/commons";
+import { adaptColor, DEFAULT_ADAPTIVE_COLOR_BANDS } from "@triliumnext/commons";
import {
_getModelData as getModelData,
_setModelData as setModelData,
@@ -65,6 +65,27 @@ describe("AdaptiveColors", () => {
.toBe("<paragraph>text</paragraph>");
});
+ 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 pair = adaptColor("#e64d4d", "text", bands);
+ expect(pair).toMatch(/^light-dark\(#000000,/);
+ expect(getModelData(themed.model, { withoutSelection: true }))
+ .toBe(`<paragraph><$text fontColor="${pair}">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
diff --git a/packages/ckeditor5/src/plugins/adaptive_colors.ts b/packages/ckeditor5/src/plugins/adaptive_colors.ts
index 7f5697c5ff..47dfeab89c 100644
--- a/packages/ckeditor5/src/plugins/adaptive_colors.ts
+++ b/packages/ckeditor5/src/plugins/adaptive_colors.ts
@@ -1,4 +1,4 @@
-import { adaptColor, type AdaptiveColorRole } from "@triliumnext/commons";
+import { adaptColor, type AdaptiveColorBands, type AdaptiveColorRole } from "@triliumnext/commons";
import { type CommandExecuteEvent, Plugin } from "ckeditor5";
/**
@@ -12,12 +12,17 @@ export default class AdaptiveColors extends Plugin {
}
afterInit() {
+ const bands = this.editor.config.get("adaptiveColorBands");
for (const [ commandName, role ] of Object.entries(COMMAND_ROLES)) {
- this.adaptCommandValue(commandName, role);
+ this.adaptCommandValue(commandName, role, bands);
}
}
- private adaptCommandValue(commandName: string, role: AdaptiveColorRole) {
+ private adaptCommandValue(
+ commandName: string,
+ role: AdaptiveColorRole,
+ bands: AdaptiveColorBands | undefined
+ ) {
// An editor without the table properties plugins has no table color commands.
const command = this.editor.commands.get(commandName);
if (!command) {
@@ -27,7 +32,7 @@ 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) };
+ args[0] = { ...options, value: adaptColor(options.value, role, bands) };
}
}, { priority: "high" });
}
diff --git a/packages/commons/src/lib/adaptive_color.spec.ts b/packages/commons/src/lib/adaptive_color.spec.ts
index 9392930300..7cd23e21da 100644
--- a/packages/commons/src/lib/adaptive_color.spec.ts
+++ b/packages/commons/src/lib/adaptive_color.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { adaptColor } from "./adaptive_color.js";
+import { adaptColor, DEFAULT_ADAPTIVE_COLOR_BANDS } from "./adaptive_color.js";
const HUES = [
"#e64d4d", "#e6994d", "#e5e64d", "#99e64d", "#4de64d", "#4de699",
@@ -63,6 +63,18 @@ describe("adaptColor", () => {
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)));
diff --git a/packages/commons/src/lib/adaptive_color.ts b/packages/commons/src/lib/adaptive_color.ts
index fc4d8b80ae..75bdd8f428 100644
--- a/packages/commons/src/lib/adaptive_color.ts
+++ b/packages/commons/src/lib/adaptive_color.ts
@@ -4,6 +4,16 @@
*/
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
@@ -11,32 +21,29 @@ export type AdaptiveColorRole = "text" | "background" | "tableBorder" | "tableBa
*
* @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): string {
+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 bands = BANDS[role];
- return `light-dark(${fitToBand(lab, bands.light)},${fitToBand(lab, bands.dark)})`;
-}
-
-type Rgb = [number, number, number];
-type Lab = [number, number, number];
-
-interface Band {
- minLightness: number;
- maxLightness: number;
- maxChroma: number;
+ const { light, dark } = bands[role];
+ return `light-dark(${fitToBand(lab, light)},${fitToBand(lab, dark)})`;
}
/**
- * The CIELAB lightness range and chroma cap per role and theme. Against the Next themes' page, the
- * limits keep text at 4.5:1 or more, also on every background, and borders at 3:1 or more.
+ * 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`.
*/
-const BANDS: Record<AdaptiveColorRole, Record<"light" | "dark", Band>> = {
+export const DEFAULT_ADAPTIVE_COLOR_BANDS: AdaptiveColorBands = {
text: {
light: { minLightness: 0, maxLightness: 40, maxChroma: Infinity },
dark: { minLightness: 75, maxLightness: 100, maxChroma: 55 }
@@ -55,6 +62,9 @@ const BANDS: Record<AdaptiveColorRole, Record<"light" | "dark", Band>> = {
}
};
+type Rgb = [number, number, number];
+type Lab = [number, number, number];
+
/** Below this CIELAB chroma a color counts as grey. */
const GREY_CHROMA = 1.5;
@@ -62,7 +72,7 @@ const D65_WHITE: Lab = [ 0.95047, 1, 1.08883 ];
const LAB_EPSILON = 216 / 24389;
const LAB_KAPPA = 24389 / 27;
-function fitToBand([ lightness, a, b ]: Lab, band: Band): string {
+function fitToBand([ lightness, a, b ]: Lab, band: AdaptiveColorBand): string {
const chroma = Math.hypot(a, b);
const hue = Math.atan2(b, a);