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
fix(onenote): adapt near-black ink for dark mode by contrast, not lookup
Elian Doran31ba13631bb5
diff --git a/apps/server/src/services/import/onenote/color.spec.ts b/apps/server/src/services/import/onenote/color.spec.tsnew file mode 100644index 0000000000..1c8056a73c--- /dev/null+++ b/apps/server/src/services/import/onenote/color.spec.ts@@ -0,0 +1,56 @@+import { describe, expect, it } from "vitest";++import { hslToHex, parseHexColor, rgbToHsl } 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]);+ });++ 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();+ }+ });+});++describe("rgbToHsl / hslToHex", () => {+ 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);+ }+ });++ 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);+ }+ });+});diff --git a/apps/server/src/services/import/onenote/color.ts b/apps/server/src/services/import/onenote/color.tsnew file mode 100644index 0000000000..cd3a0fe44a--- /dev/null+++ b/apps/server/src/services/import/onenote/color.ts@@ -0,0 +1,73 @@+/**+ * Small 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.+ */++/** 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)];+}++/** 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;+ }+ 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))}`;+}diff --git a/apps/server/src/services/import/onenote/converter.ts b/apps/server/src/services/import/onenote/converter.tsindex de6c9b0e68..56fb7e9265 100644--- a/apps/server/src/services/import/onenote/converter.ts+++ b/apps/server/src/services/import/onenote/converter.ts@@ -24,6 +24,8 @@import { sanitize, utils } from "@triliumnext/core";import { HTMLElement, parse } from "node-html-parser";+import { hslToHex, parseHexColor, rgbToHsl } from "./color.js";+/*** The marker class the importer keys on to find OneNote file attachments (see importer.ts). The href* carries the Graph resource URL (a placeholder the importer swaps for a local attachment link) and@@ -648,74 +650,6 @@ function correctTableShadingColors(scope: HTMLElement) {}}-/** Parses a `#rgb` or `#rrggbb` colour to [r, g, b] (0-255), or null if it isn't a hex colour. */-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)];-}--/** Converts an [r, g, b] (0-255) colour to [h, s, l], each in [0, 1]. */-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;- }- return [hue / 6, saturation, lightness];-}--/** Converts [h, s, l] (each in [0, 1]) back to a `#rrggbb` hex colour. */-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)}`;- }- /* v8 ignore next -- only called from correctTableShadingColors with l strictly above 0.5 */- 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))}`;-}-/** Drops list items that hold nothing but whitespace/<br> (OneNote's "exited the list" remnant). */function removeEmptyListItems(scope: HTMLElement) {for (const li of scope.querySelectorAll("li")) {diff --git a/apps/server/src/services/import/onenote/inkml.spec.ts b/apps/server/src/services/import/onenote/inkml.spec.tsindex e3a5a8f017..dd080f50fe 100644--- a/apps/server/src/services/import/onenote/inkml.spec.ts+++ b/apps/server/src/services/import/onenote/inkml.spec.ts@@ -49,12 +49,12 @@ describe("inkmlToSvg", () => {const svg = inkmlToSvg(dot) ?? "";expect(svg).toContain("<circle");expect(svg).not.toContain("<path");- // The default brush is OneNote's automatic ink, so the dot fills adaptively via the class.- expect(svg).toContain(`class="ink-auto"`);- expect(svg).toContain("circle.ink-auto{fill:light-dark(#000,#fff)}");+ // The default brush is black ink, so the dot fills theme-adaptively via an inline style.+ expect(svg).toContain(`style="fill:light-dark(#000000, #ffffff)"`);+ expect(svg).toContain("<style>svg{color-scheme:light dark}</style>");});- it("renders a deliberately-colored single-point trace with a literal fill", () => {+ it("renders a readable-colored single-point trace with a literal fill", () => {const dot = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML"><inkml:definitions><inkml:brush xml:id="br0"><inkml:brushProperty name="color" value="#FF0000"/></inkml:brush>@@ -63,25 +63,24 @@ describe("inkmlToSvg", () => {</inkml:ink>`;const svg = inkmlToSvg(dot) ?? "";- // A chosen color is baked into the dot's fill; no adaptive class or style block is emitted.+ // A color readable under both themes is baked into the dot's fill; no adaptive style is emitted.expect(svg).toContain("<circle");expect(svg).toContain(`fill="#FF0000"`);- expect(svg).not.toContain("ink-auto");+ expect(svg).not.toContain("light-dark");expect(svg).not.toContain("<style>");});- it("works without namespace prefixes and falls back to a default (automatic) brush", () => {+ it("works without namespace prefixes and falls back to a default (black) brush", () => {const plain = `<ink><trace>0 0, 10 10</trace></ink>`;const svg = inkmlToSvg(plain) ?? "";expect(svg).toContain("<path");- // The default brush is OneNote's automatic ink: rendered theme-adaptively, never hard black.- expect(svg).toContain(`class="ink-auto"`);+ // The default brush is black ink: rendered theme-adaptively, never hard black.+ expect(svg).toContain(`style="stroke:light-dark(#000000, #ffffff)"`);expect(svg).not.toContain(`stroke="#000000"`);- expect(svg).toContain("light-dark(#000,#fff)");});- it("renders OneNote's automatic ink (default black and its white inverse) theme-adaptively", () => {- const automatic = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML">+ it("renders black ink and its dark-canvas inverse (white) theme-adaptively", () => {+ const blackAndWhite = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML"><inkml:definitions><inkml:brush xml:id="black"><inkml:brushProperty name="color" value="#000000"/></inkml:brush><inkml:brush xml:id="white"><inkml:brushProperty name="color" value="#FFFFFF"/></inkml:brush>@@ -89,24 +88,88 @@ describe("inkmlToSvg", () => {<inkml:trace brushRef="#black">0 0, 10 10</inkml:trace><inkml:trace brushRef="#white">20 20, 30 30</inkml:trace></inkml:ink>`;- const svg = inkmlToSvg(automatic) ?? "";+ const svg = inkmlToSvg(blackAndWhite) ?? "";- // Both default black and its dark-mode inverse (white) become the adaptive class, not a color.- expect((svg.match(/class="ink-auto"/g) ?? [])).toHaveLength(2);+ // Lightness reflection maps black and white onto the same black-on-light/white-on-dark pair.+ expect((svg.match(/style="stroke:light-dark\(#000000, #ffffff\)"/gi) ?? [])).toHaveLength(2);expect(svg).not.toContain(`stroke="#000000"`);expect(svg).not.toContain(`stroke="#FFFFFF"`);// The adaptive <style> is emitted once, keyed to the embedding context's color-scheme.expect((svg.match(/<style>/g) ?? [])).toHaveLength(1);expect(svg).toContain("svg{color-scheme:light dark}");- expect(svg).toContain("path.ink-auto{stroke:light-dark(#000,#fff)}");});- it("leaves deliberately-colored ink literal and omits the adaptive style", () => {- // #FF0000 is a chosen color — untouched — and with no automatic strokes there's no <style> block.+ it("adapts palette near-blacks like #333333 for dark mode, keeping them literal in light mode", () => {+ // The reported regression: OneNote's black-looking pens are per-client near-blacks+ // (#333333, #404040, ...), not #000000. Reflected lightness lands within a rounding error+ // of OneNote's own dark-mode rendering (#333333 -> #cbc8c8 in OneNote, #cccccc here).+ const nearBlacks = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML">+ <inkml:definitions>+ <inkml:brush xml:id="b33"><inkml:brushProperty name="color" value="#333333"/></inkml:brush>+ <inkml:brush xml:id="b40"><inkml:brushProperty name="color" value="#404040"/></inkml:brush>+ </inkml:definitions>+ <inkml:trace brushRef="#b33">0 0, 10 10</inkml:trace>+ <inkml:trace brushRef="#b40">20 20, 30 30</inkml:trace>+ </inkml:ink>`;+ const svg = inkmlToSvg(nearBlacks) ?? "";++ expect(svg).toContain(`style="stroke:light-dark(#333333, #cccccc)"`);+ expect(svg).toContain(`style="stroke:light-dark(#404040, #bfbfbf)"`);+ expect(svg).not.toContain(`stroke="#333333"`);+ });++ it("keeps the hue when adapting saturated colors, in either direction", () => {+ // A dark blue must lighten to a readable *blue*, not to gray; a near-white pink must darken+ // to a red. The light-mode side always keeps the exact color OneNote sent.+ const saturated = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML">+ <inkml:definitions>+ <inkml:brush xml:id="navy"><inkml:brushProperty name="color" value="#000080"/></inkml:brush>+ <inkml:brush xml:id="pink"><inkml:brushProperty name="color" value="#ffe6e6"/></inkml:brush>+ </inkml:definitions>+ <inkml:trace brushRef="#navy">0 0, 10 10</inkml:trace>+ <inkml:trace brushRef="#pink">20 20, 30 30</inkml:trace>+ </inkml:ink>`;+ const svg = inkmlToSvg(saturated) ?? "";++ expect(svg).toContain(`style="stroke:light-dark(#000080, #7f7fff)"`);+ expect(svg).toContain(`style="stroke:light-dark(#190000, #ffe6e6)"`);+ });++ it("adapts the named colors black and white through their hex equivalents", () => {+ 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>+ <inkml:brush xml:id="b1"><inkml:brushProperty name="color" value="white"/></inkml:brush>+ </inkml:definitions>+ <inkml:trace brushRef="#b0">0 0, 10 10</inkml:trace>+ <inkml:trace brushRef="#b1">20 20, 30 30</inkml:trace>+ </inkml:ink>`;+ const svg = inkmlToSvg(named) ?? "";++ expect((svg.match(/style="stroke:light-dark\(#000000, #ffffff\)"/g) ?? [])).toHaveLength(2);+ });++ it("leaves ink readable under both themes literal and omits the adaptive style", () => {+ // #FF0000 (lightness exactly 0.5) and a mid-light gray are untouched — including #cccccc,+ // which is a dark-mode *target* but as source ink is readable on both canvases — and with no+ // adapted strokes there's no <style> block. An unparseable color also stays literal.+ const readable = `<inkml:ink xmlns:inkml="http://www.w3.org/2003/InkML">+ <inkml:definitions>+ <inkml:brush xml:id="gray"><inkml:brushProperty name="color" value="#cccccc"/></inkml:brush>+ <inkml:brush xml:id="odd"><inkml:brushProperty name="color" value="not-a-color"/></inkml:brush>+ </inkml:definitions>+ <inkml:trace brushRef="#gray">0 0, 10 10</inkml:trace>+ <inkml:trace brushRef="#odd">20 20, 30 30</inkml:trace>+ </inkml:ink>`;+ const graySvg = inkmlToSvg(readable) ?? "";+ expect(graySvg).toContain(`stroke="#cccccc"`);+ expect(graySvg).toContain(`stroke="not-a-color"`);+ expect(graySvg).not.toContain("light-dark");+ expect(graySvg).not.toContain("<style>");+const svg = inkmlToSvg(INKML) ?? "";expect(svg).toContain(`stroke="#FF0000"`);- expect(svg).not.toContain("ink-auto");expect(svg).not.toContain("<style>");});@@ -130,7 +193,7 @@ describe("inkmlToSvg", () => {const svg = inkmlToSvg(messy) ?? "";expect((svg.match(/<path/g) ?? [])).toHaveLength(1);- expect(svg).toContain(`stroke="#00AA00"`);+ expect(svg).toContain(`style="stroke:light-dark(#00AA00, #55ff55)"`); // dark green, adaptedexpect(svg).toContain(`stroke-width="70"`); // default width kept over the unparseable oneexpect(svg).not.toContain("#123456"); // the id-less brush is never referenced});@@ -152,13 +215,17 @@ describe("inkmlToSvg", () => {const svg = inkmlToSvg(readFileSync(join(FIXTURES_DIR, "sample.inkml"), "utf-8")) ?? "";// One <path> per <trace>, each resolving its brush color despite the `#{guid}{n}` brushRef ids.+ // The pens are all dark colors (including the palette's near-black #404040 rather than+ // #000000), so each adapts for dark mode while keeping its exact color in light mode.expect((svg.match(/<path/g) ?? []).length).toBe(42);- for (const color of ["#404040", "#1353BA", "#167D1D", "#C62938", "#904C15", "#FAF320"]) {- expect(svg).toContain(`stroke="${color}"`);+ for (const color of ["#404040", "#1353BA", "#167D1D", "#C62938", "#904C15"]) {+ expect(svg).toContain(`style="stroke:light-dark(${color}, #`);}+ expect(svg).toContain(`style="stroke:light-dark(#404040, #bfbfbf)"`);- // Highlighter strokes (transparency 0.496, rectangle tip) render translucent and use the- // larger height as their thickness rather than the thin pen-style width.+ // Highlighter strokes (transparency 0.496, rectangle tip) keep their literal mid-light+ // yellow, render translucent, and use the larger height as their thickness rather than the+ // thin pen-style width.expect(svg).toContain(`opacity="0.50"`);expect(svg).toContain(`stroke="#FAF320" stroke-width="1000"`);diff --git a/apps/server/src/services/import/onenote/inkml.ts b/apps/server/src/services/import/onenote/inkml.tsindex 6352786e85..ebe7fc0952 100644--- a/apps/server/src/services/import/onenote/inkml.ts+++ b/apps/server/src/services/import/onenote/inkml.ts@@ -18,6 +18,8 @@import { HTMLElement, parse } from "node-html-parser";+import { hslToHex, parseHexColor, rgbToHsl } from "./color.js";+/** Padding around the rendered strokes, in coordinate units. */const PADDING = 10;@@ -39,30 +41,33 @@ interface Trace {const DEFAULT_BRUSH: Brush = { color: "#000000", width: 70, height: 70, transparency: 0 };/**- * OneNote's automatic ink colors. Like its automatic *text* color (see removeDefaultTextColor in- * converter.ts), the default pen isn't a chosen color: it's black on OneNote's light canvas but- * inverts to white in dark mode. These two are rendered theme-adaptively (see AUTO_INK_STYLE) rather- * than baked as a hard color that would be unreadable under the opposite theme; every deliberately- * picked color is left exactly as OneNote sent it.+ * Ink darker than this HSL lightness 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;++/**+ * Ink at least this light is unreadable against a light canvas (it's near-white ink laid down on+ * OneNote's dark canvas — most commonly the automatic pen's white inverse), so it gets a reflected+ * 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 AUTOMATIC_INK_COLORS = new Set(["#000000", "#000", "black", "#ffffff", "#fff", "white"]);+const LIGHT_INK_MIN_LIGHTNESS = 0.9;-/** The class carried by an automatic-colored shape; the color itself comes from {@link AUTO_INK_STYLE}. */-const AUTO_INK_CLASS = "ink-auto";+/** 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"]+]);/**- * Theme-adaptive styling for automatic-colored strokes. `color-scheme: light dark` enables the- * `light-dark()` function; the used scheme is inherited from the embedding `<img>` — Trilium sets- * `color-scheme` from its active theme on `:root` (theme-next/base.css) and Chromium propagates it- * into the referenced SVG — so the ink follows Trilium's light/dark toggle instead of rendering as- * unreadable black-on-dark. Paths take the color on `stroke`, single-point dots on `fill`; qualifying- * each rule by element keeps the fill rule from overriding a path's `fill="none"` and flooding it solid.- * Emitted only when at least one automatic stroke is present.+ * Enables the `light-dark()` function used by adapted strokes. The used scheme is inherited from the+ * embedding `<img>` — Trilium sets `color-scheme` from its active theme on `:root`+ * (theme-next/base.css) and Chromium propagates it into the referenced SVG — so adapted ink follows+ * Trilium's light/dark toggle. Emitted only when at least one adapted stroke is present.*/-const AUTO_INK_STYLE =- `<style>svg{color-scheme:light dark}` +- `path.${AUTO_INK_CLASS}{stroke:light-dark(#000,#fff)}` +- `circle.${AUTO_INK_CLASS}{fill:light-dark(#000,#fff)}</style>`;+const COLOR_SCHEME_STYLE = `<style>svg{color-scheme:light dark}</style>`;/*** The on-screen stroke thickness. Pens carry equal width/height, but highlighters (rectangle tip)@@ -73,9 +78,35 @@ function strokeWidth(brush: Brush): number {return Math.max(brush.width, brush.height);}-/** Whether a brush color is OneNote's mode-adaptive automatic ink (default black / its white inverse). */-function isAutomaticColor(color: string): boolean {- return AUTOMATIC_INK_COLORS.has(color.trim().toLowerCase());+/**+ * The theme-adaptive `light-dark()` paint for an ink color that would be unreadable under one theme,+ * or null for a color readable under both (kept literal, exactly as OneNote sent it).+ *+ * Contrast — not provenance — is the rule, because InkML gives no way to tell the automatic pen from+ * a chosen color, and "black" ink is rarely literal `#000000`: each OneNote client's palette has its+ * own near-black (`#404040`, `#333333`, …). OneNote's own dark mode remaps a hard-coded lookup of+ * exact swatch values (`#000000`→`#edebe9`, `#333333`→`#cbc8c8`) and renders everything else+ * verbatim, unreadable included — a table not worth reproducing. Reflecting the HSL lightness+ * (L → 1 − L, hue/saturation untouched — the same correction correctTableShadingColors applies to+ * cell backgrounds) matches OneNote's sensible mappings to within a rounding error (`#333333` →+ * `#cccccc` vs its `#cbc8c8`) and also covers the colors OneNote itself gets wrong. A false positive+ * is cheap by construction: the light-mode rendering keeps the exact original, and a wrongly-adapted+ * 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) {+ return null;+ }+ const [hue, saturation, lightness] = rgbToHsl(rgb);+ if (lightness < DARK_INK_MAX_LIGHTNESS) {+ return `light-dark(${hex}, ${hslToHex(hue, saturation, 1 - lightness)})`;+ }+ if (lightness >= LIGHT_INK_MIN_LIGHTNESS) {+ return `light-dark(${hslToHex(hue, saturation, 1 - lightness)}, ${hex})`;+ }+ return null;}export function inkmlToSvg(inkml: string): string | null {@@ -99,11 +130,11 @@ export function inkmlToSvg(inkml: string): string | null {const height = maxY - minY + PADDING * 2;const scale = Math.min(1, MAX_DISPLAY_SIZE / Math.max(width, height, 1));- const hasAutomaticInk = traces.some((trace) => isAutomaticColor(trace.brush.color));+ const hasAdaptedInk = traces.some((trace) => adaptInkColor(trace.brush.color) !== null);const shapes = traces.flatMap((trace) => traceToSvg(trace, minX, minY)).join("");return (`<svg xmlns="http://www.w3.org/2000/svg" width="${Math.round(width * scale)}" height="${Math.round(height * scale)}" ` +- `viewBox="0 0 ${width} ${height}">${hasAutomaticInk ? AUTO_INK_STYLE : ""}${shapes}</svg>`+ `viewBox="0 0 ${width} ${height}">${hasAdaptedInk ? COLOR_SCHEME_STYLE : ""}${shapes}</svg>`);}@@ -202,16 +233,18 @@ function traceToSvg(trace: Trace, minX: number, minY: number): string[] {const opacity = 1 - transparency;const opacityAttr = opacity < 1 ? ` opacity="${opacity.toFixed(2)}"` : "";const point = (coord: number[]) => [coord[0] - minX + PADDING, coord[1] - minY + PADDING];- const automatic = isAutomaticColor(color);+ // Adapted paints go through `style` because `light-dark()` needs CSS value resolution, which+ // presentation attributes don't reliably get; literal colors stay plain attributes.+ const adapted = adaptInkColor(color);if (trace.coords.length === 1) {const [x, y] = point(trace.coords[0]);- const fillAttr = automatic ? ` class="${AUTO_INK_CLASS}"` : ` fill="${color}"`;+ const fillAttr = adapted ? ` style="fill:${adapted}"` : ` fill="${color}"`;return [`<circle cx="${x}" cy="${y}" r="${width / 2}"${fillAttr}${opacityAttr}/>`];}const path = trace.coords.map((coord, index) => `${index === 0 ? "M" : "L"} ${point(coord).join(" ")}`).join(" ");- const strokeAttr = automatic ? ` class="${AUTO_INK_CLASS}"` : ` stroke="${color}"`;+ const strokeAttr = adapted ? ` style="stroke:${adapted}"` : ` stroke="${color}"`;return [`<path d="${path}"${strokeAttr} stroke-width="${width}" fill="none" stroke-linecap="round" stroke-linejoin="round"${opacityAttr}/>`];}