Skip to content

Build your personal knowledge base with Trilium Notes

refactor(onenote): use the color library for ink lightness reflection

Elian Doran2a36d84d255f
diff --git a/apps/server/package.json b/apps/server/package.json
index 39af194721..6d287e4aba 100644
--- a/apps/server/package.json
+++ b/apps/server/package.json
@@ -72,6 +72,7 @@
"cheerio": "1.2.0",
"chokidar": "5.0.0",
"cls-hooked": "4.2.2",
+ "color": "5.0.3",
"compression": "1.8.1",
"cookie-parser": "1.4.7",
"csrf-csrf": "4.0.3",
diff --git a/apps/server/src/services/import/onenote/color.spec.ts b/apps/server/src/services/import/onenote/color.spec.ts
index 1c8056a73c..b660faf163 100644
--- a/apps/server/src/services/import/onenote/color.spec.ts
+++ b/apps/server/src/services/import/onenote/color.spec.ts
@@ -1,56 +1,43 @@
import { describe, expect, it } from "vitest";
-import { hslToHex, parseHexColor, rgbToHsl } from "./color.js";
+import { parseColor, reflectLightness } from "./color.js";
-describe("parseHexColor", () => {
- it("parses #rrggbb and expands #rgb, tolerating case and whitespace", () => {
- expect(parseHexColor("#1353BA")).toEqual([0x13, 0x53, 0xba]);
- expect(parseHexColor("#333")).toEqual([0x33, 0x33, 0x33]);
- expect(parseHexColor(" #ffffff ")).toEqual([255, 255, 255]);
+/** reflectLightness on a raw CSS color string, for terser cases below. */
+function reflect(value: string): string | null {
+ const parsed = parseColor(value);
+ return parsed ? reflectLightness(parsed) : null;
+}
+
+describe("parseColor", () => {
+ it("parses the color forms OneNote emits: #rrggbb, #rgb, named and rgb()", () => {
+ expect(parseColor("#1353BA")?.hex()).toBe("#1353BA");
+ expect(parseColor("#333")?.hex()).toBe("#333333");
+ expect(parseColor("black")?.hex()).toBe("#000000");
+ expect(parseColor("rgb(54, 86, 35)")?.hex()).toBe("#365623");
});
- it("rejects anything that isn't a 3- or 6-digit hex color", () => {
- for (const value of ["", "black", "333333", "#33", "#33333", "#3333333", "#33g333", "rgb(0,0,0)"]) {
- expect(parseHexColor(value)).toBeNull();
+ it("returns null for anything that isn't a CSS color", () => {
+ for (const value of ["", "not-a-color", "#33", "#33g333", "url(x)"]) {
+ expect(parseColor(value)).toBeNull();
}
});
});
-describe("rgbToHsl / hslToHex", () => {
+describe("reflectLightness", () => {
it("lightness-reflects grays exactly (the near-black ink correction)", () => {
// #333333 -> #cccccc is the OneNote near-black case; pure black reflects to pure white.
- for (const [input, reflected] of [["#333333", "#cccccc"], ["#404040", "#bfbfbf"], ["#000000", "#ffffff"], ["#ffffff", "#000000"]]) {
- const rgb = parseHexColor(input);
- expect(rgb).not.toBeNull();
- const [hue, saturation, lightness] = rgbToHsl(rgb ?? [0, 0, 0]);
- expect(saturation).toBe(0);
- expect(hslToHex(hue, saturation, 1 - lightness)).toBe(reflected);
- }
+ expect(reflect("#333333")).toBe("#cccccc");
+ expect(reflect("#404040")).toBe("#bfbfbf");
+ expect(reflect("#000000")).toBe("#ffffff");
+ expect(reflect("#ffffff")).toBe("#000000");
});
it("preserves hue and saturation when reflecting chromatic colors", () => {
- // One color per hue sector of rgbToHsl, both lightness directions for hslToHex.
- const cases: [string, string][] = [
- ["#800000", "#ff7f7f"], // dark red (red-dominant sector)
- ["#008000", "#7fff7f"], // dark green (green-dominant sector)
- ["#000080", "#7f7fff"], // navy (blue-dominant sector)
- ["#800080", "#ff7fff"], // dark magenta (hue wraps past the top of the wheel)
- ["#ffe6e6", "#190000"] // near-white pink -> dark red (reflected lightness below 0.5)
- ];
- for (const [input, reflected] of cases) {
- const rgb = parseHexColor(input);
- expect(rgb).not.toBeNull();
- const [hue, saturation, lightness] = rgbToHsl(rgb ?? [0, 0, 0]);
- expect(hslToHex(hue, saturation, 1 - lightness)).toBe(reflected);
- }
- });
-
- it("round-trips a color through rgbToHsl and hslToHex unchanged", () => {
- for (const input of ["#1353ba", "#faf320", "#c62938", "#808080", "#000000"]) {
- const rgb = parseHexColor(input);
- expect(rgb).not.toBeNull();
- const [hue, saturation, lightness] = rgbToHsl(rgb ?? [0, 0, 0]);
- expect(hslToHex(hue, saturation, lightness)).toBe(input);
- }
+ // One color per hue region, both lightness directions.
+ expect(reflect("#800000")).toBe("#ff7f7f"); // dark red
+ expect(reflect("#008000")).toBe("#7fff7f"); // dark green
+ expect(reflect("#000080")).toBe("#7f7fff"); // navy
+ expect(reflect("#800080")).toBe("#ff7fff"); // dark magenta (hue wraps past the top of the wheel)
+ expect(reflect("#ffe6e6")).toBe("#190000"); // near-white pink -> dark red
});
});
diff --git a/apps/server/src/services/import/onenote/color.ts b/apps/server/src/services/import/onenote/color.ts
index cd3a0fe44a..7af4a910d2 100644
--- a/apps/server/src/services/import/onenote/color.ts
+++ b/apps/server/src/services/import/onenote/color.ts
@@ -1,73 +1,22 @@
/**
- * Small color helpers shared by the OneNote importer's HTML converter (table-shading correction in
+ * Color helpers shared by the OneNote importer's HTML converter (table-shading correction in
* converter.ts) and its InkML renderer (theme-adaptive ink in inkml.ts). Both correct the same
* OneNote quirk — colors exported for one canvas lightness rendered on the opposite one — by
- * reflecting a color's HSL lightness (L → 1 − L) while leaving hue and saturation untouched.
+ * reflecting a color's HSL lightness (L → 100 − L) while leaving hue and saturation untouched.
*/
-/** Parses a `#rgb` or `#rrggbb` colour to [r, g, b] (0-255), or null if it isn't a hex colour. */
-export function parseHexColor(value: string): [number, number, number] | null {
- const match = value.trim().match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i);
- if (!match) {
- return null;
- }
- const hex = match[1].length === 3 ? match[1].replace(/(.)/g, "$1$1") : match[1];
- return [parseInt(hex.slice(0, 2), 16), parseInt(hex.slice(2, 4), 16), parseInt(hex.slice(4, 6), 16)];
-}
+import Color, { type ColorInstance } from "color";
-/** Converts an [r, g, b] (0-255) colour to [h, s, l], each in [0, 1]. */
-export function rgbToHsl([r, g, b]: [number, number, number]): [number, number, number] {
- r /= 255;
- g /= 255;
- b /= 255;
- const max = Math.max(r, g, b);
- const min = Math.min(r, g, b);
- const lightness = (max + min) / 2;
- const delta = max - min;
- if (delta === 0) {
- return [0, 0, lightness];
- }
- const saturation = lightness > 0.5 ? delta / (2 - max - min) : delta / (max + min);
- let hue: number;
- switch (max) {
- case r:
- hue = (g - b) / delta + (g < b ? 6 : 0);
- break;
- case g:
- hue = (b - r) / delta + 2;
- break;
- default:
- hue = (r - g) / delta + 4;
- break;
+/** Parses any CSS color (`#rgb`/`#rrggbb`, named, `rgb()`, …), or null if the value isn't one. */
+export function parseColor(value: string): ColorInstance | null {
+ try {
+ return Color(value);
+ } catch {
+ return null;
}
- return [hue / 6, saturation, lightness];
}
-/** Converts [h, s, l] (each in [0, 1]) back to a `#rrggbb` hex colour. */
-export function hslToHex(h: number, s: number, l: number): string {
- const channel = (value: number) => Math.round(value * 255).toString(16).padStart(2, "0");
- if (s === 0) {
- return `#${channel(l).repeat(3)}`;
- }
- const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
- const p = 2 * l - q;
- const component = (t: number) => {
- if (t < 0) {
- t += 1;
- }
- if (t > 1) {
- t -= 1;
- }
- if (t < 1 / 6) {
- return p + (q - p) * 6 * t;
- }
- if (t < 1 / 2) {
- return q;
- }
- if (t < 2 / 3) {
- return p + (q - p) * (2 / 3 - t) * 6;
- }
- return p;
- };
- return `#${channel(component(h + 1 / 3))}${channel(component(h))}${channel(component(h - 1 / 3))}`;
+/** The `#rrggbb` hex of a color with its HSL lightness reflected (L → 100 − L), hue and saturation kept. */
+export function reflectLightness(color: ColorInstance): string {
+ return color.lightness(100 - color.lightness()).hex().toLowerCase();
}
diff --git a/apps/server/src/services/import/onenote/converter.ts b/apps/server/src/services/import/onenote/converter.ts
index 56fb7e9265..34a69e7eee 100644
--- a/apps/server/src/services/import/onenote/converter.ts
+++ b/apps/server/src/services/import/onenote/converter.ts
@@ -24,7 +24,7 @@
import { sanitize, utils } from "@triliumnext/core";
import { HTMLElement, parse } from "node-html-parser";
-import { hslToHex, parseHexColor, rgbToHsl } from "./color.js";
+import { parseColor, reflectLightness } from "./color.js";
/**
* The marker class the importer keys on to find OneNote file attachments (see importer.ts). The href
@@ -629,23 +629,18 @@ function columnPercentages(widths: number[]): number[] {
* OneNote's Graph API exports table cell shading as a dark *shade* of the colour OneNote actually
* displays: it keeps the hue and saturation but inverts the lightness (e.g. a cell shown as #b6d9a1
* comes back as #375623). Left as-is the cell imports far too dark — commonly dark-on-dark and
- * unreadable. So for a cell whose background is dark, reflect its lightness (L → 1 − L, hue/saturation
- * untouched) to recover the displayed light tint; light backgrounds (plausible shading as-is, and the
- * form correctly-exported colours arrive in) are left alone. Runs after normalizeNamedColors, so a
- * named background has already become the hex this keys on.
+ * unreadable. So for a cell whose background is dark, reflect its lightness (L → 100 − L,
+ * hue/saturation untouched) to recover the displayed light tint; light backgrounds (plausible shading
+ * as-is, and the form correctly-exported colours arrive in) are left alone.
*/
function correctTableShadingColors(scope: HTMLElement) {
for (const cell of scope.querySelectorAll("td, th")) {
const style = parseStyle(cell.getAttribute("style") ?? "");
- const rgb = parseHexColor(style.get("background-color") ?? "");
- if (!rgb) {
+ const background = parseColor(style.get("background-color") ?? "");
+ if (!background || background.lightness() >= 50) {
continue;
}
- const [hue, saturation, lightness] = rgbToHsl(rgb);
- if (lightness >= 0.5) {
- continue;
- }
- style.set("background-color", hslToHex(hue, saturation, 1 - lightness));
+ style.set("background-color", reflectLightness(background));
cell.setAttribute("style", serializeStyle(style));
}
}
diff --git a/apps/server/src/services/import/onenote/inkml.spec.ts b/apps/server/src/services/import/onenote/inkml.spec.ts
index dd080f50fe..3473e5822f 100644
--- a/apps/server/src/services/import/onenote/inkml.spec.ts
+++ b/apps/server/src/services/import/onenote/inkml.spec.ts
@@ -136,7 +136,7 @@ describe("inkmlToSvg", () => {
expect(svg).toContain(`style="stroke:light-dark(#190000, #ffe6e6)"`);
});
- it("adapts the named colors black and white through their hex equivalents", () => {
+ it("adapts named colors, keeping the original token on the as-sent side", () => {
const named = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML">
<inkml:definitions>
<inkml:brush xml:id="b0"><inkml:brushProperty name="color" value="Black"/></inkml:brush>
@@ -147,7 +147,8 @@ describe("inkmlToSvg", () => {
</inkml:ink>`;
const svg = inkmlToSvg(named) ?? "";
- expect((svg.match(/style="stroke:light-dark\(#000000, #ffffff\)"/g) ?? [])).toHaveLength(2);
+ expect(svg).toContain(`style="stroke:light-dark(Black, #ffffff)"`);
+ expect(svg).toContain(`style="stroke:light-dark(#000000, white)"`);
});
it("leaves ink readable under both themes literal and omits the adaptive style", () => {
diff --git a/apps/server/src/services/import/onenote/inkml.ts b/apps/server/src/services/import/onenote/inkml.ts
index ebe7fc0952..2e0d596fbc 100644
--- a/apps/server/src/services/import/onenote/inkml.ts
+++ b/apps/server/src/services/import/onenote/inkml.ts
@@ -18,7 +18,7 @@
import { HTMLElement, parse } from "node-html-parser";
-import { hslToHex, parseHexColor, rgbToHsl } from "./color.js";
+import { parseColor, reflectLightness } from "./color.js";
/** Padding around the rendered strokes, in coordinate units. */
const PADDING = 10;
@@ -41,11 +41,11 @@ interface Trace {
const DEFAULT_BRUSH: Brush = { color: "#000000", width: 70, height: 70, transparency: 0 };
/**
- * Ink darker than this HSL lightness is unreadable against a dark canvas, so it gets a
+ * Ink darker than this HSL lightness (0-100) is unreadable against a dark canvas, so it gets a
* lightness-reflected dark-mode variant. Matches the threshold correctTableShadingColors
* (converter.ts) uses for the same judgement on cell backgrounds.
*/
-const DARK_INK_MAX_LIGHTNESS = 0.5;
+const DARK_INK_MAX_LIGHTNESS = 50;
/**
* Ink at least this light is unreadable against a light canvas (it's near-white ink laid down on
@@ -53,13 +53,7 @@ const DARK_INK_MAX_LIGHTNESS = 0.5;
* light-mode variant. Deliberately high: mid-light colors like highlighter yellows and pastels are
* chosen for a light canvas and read fine there, so only the near-white band is adapted.
*/
-const LIGHT_INK_MIN_LIGHTNESS = 0.9;
-
-/** The named colors ink brushes can carry, mapped to the hex used inside `light-dark()`. */
-const NAMED_INK_COLORS = new Map([
- ["black", "#000000"],
- ["white", "#ffffff"]
-]);
+const LIGHT_INK_MIN_LIGHTNESS = 90;
/**
* Enables the `light-dark()` function used by adapted strokes. The used scheme is inherited from the
@@ -94,17 +88,17 @@ function strokeWidth(brush: Brush): number {
* dark color becomes a readable same-hue light one in dark mode instead of an invisible one.
*/
function adaptInkColor(color: string): string | null {
- const hex = NAMED_INK_COLORS.get(color.trim().toLowerCase()) ?? color;
- const rgb = parseHexColor(hex);
- if (!rgb) {
+ const literal = color.trim();
+ const parsed = parseColor(literal);
+ if (!parsed) {
return null;
}
- const [hue, saturation, lightness] = rgbToHsl(rgb);
+ const lightness = parsed.lightness();
if (lightness < DARK_INK_MAX_LIGHTNESS) {
- return `light-dark(${hex}, ${hslToHex(hue, saturation, 1 - lightness)})`;
+ return `light-dark(${literal}, ${reflectLightness(parsed)})`;
}
if (lightness >= LIGHT_INK_MIN_LIGHTNESS) {
- return `light-dark(${hslToHex(hue, saturation, 1 - lightness)}, ${hex})`;
+ return `light-dark(${reflectLightness(parsed)}, ${literal})`;
}
return null;
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 8ecf46322e..8adc49de45 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -719,6 +719,9 @@ importers:
cls-hooked:
specifier: 4.2.2
version: 4.2.2
+ color:
+ specifier: 5.0.3
+ version: 5.0.3
compression:
specifier: 1.8.1
version: 1.8.1([email protected])