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(link previews): correct favicons that vanish into the theme
Elian Dorana8ce94118815
diff --git a/apps/client/src/services/favicon_contrast.ts b/apps/client/src/services/favicon_contrast.tsnew file mode 100644index 0000000000..b44dae8bde--- /dev/null+++ b/apps/client/src/services/favicon_contrast.ts@@ -0,0 +1,108 @@+import {+ classifyFaviconContrast,+ type FaviconContrast,+ faviconContrastClass,+ measureFaviconVisibility,+ safeLinkPreviewImageSrc+} from "@triliumnext/commons";+import { useEffect, useState } from "preact/hooks";++/**+ * The measured verdict for each favicon we have looked at, so a note that links one site twenty+ * times measures it once. Keyed by the picture rather than by the site, since that is what was+ * measured — the same attachment URL always yields the same answer.+ *+ * Never invalidated: the answer is a property of the icon's own pixels and does not change when the+ * user switches theme. Acting on it does, which is why the verdict is handed to the stylesheets as a+ * class rather than being resolved into a filter here.+ */+const measured = new Map<string, FaviconContrast>();++/** Measurements still in flight, so several previews of one site share a single decode. */+const pending = new Map<string, Promise<FaviconContrast>>();++/**+ * The class a favicon should carry for the theme to be able to correct it, or undefined while the+ * measurement is still running and for an icon that needs no correction.+ *+ * Renders uncorrected first and corrects on the next frame. That is the right way round: an icon+ * briefly shown as its author drew it is what every other app shows permanently, whereas guessing+ * before measuring would mean occasionally inverting an icon that turns out to be fine.+ */+export function useFaviconContrastClass(src: string | undefined | null): string | undefined {+ const safeSrc = safeLinkPreviewImageSrc(src);+ const [contrast, setContrast] = useState<FaviconContrast>(() => (safeSrc && measured.get(safeSrc)) || "neutral");++ useEffect(() => {+ if (!safeSrc) {+ setContrast("neutral");+ return;+ }++ const known = measured.get(safeSrc);+ if (known) {+ setContrast(known);+ return;+ }++ let stillMounted = true;+ void faviconContrast(safeSrc).then((result) => {+ if (stillMounted) {+ setContrast(result);+ }+ });++ return () => {+ stillMounted = false;+ };+ }, [safeSrc]);++ return faviconContrastClass(contrast);+}++/** Measures an icon, or answers from the cache. Never rejects: an unreadable icon is simply left alone. */+function faviconContrast(src: string): Promise<FaviconContrast> {+ const cached = measured.get(src);+ if (cached) {+ return Promise.resolve(cached);+ }++ const inFlight = pending.get(src);+ if (inFlight) {+ return inFlight;+ }++ const measurement = loadAndMeasure(src).then((contrast) => {+ measured.set(src, contrast);+ pending.delete(src);+ return contrast;+ });++ pending.set(src, measurement);++ return measurement;+}++/**+ * Loads the icon a second time, into an image of our own, and measures that.+ *+ * Deliberately not the `<img>` the preview renders: this way the measurement owes nothing to when+ * that element mounts, whether it has already fired `load`, or whether it is on screen at all, and+ * the same answer serves every preview of the site at once. The second load is free — the browser+ * has the picture in its cache, this being the very URL it just drew.+ */+function loadAndMeasure(src: string): Promise<FaviconContrast> {+ return new Promise((resolve) => {+ const image = new Image();++ image.addEventListener("load", () => {+ const visibility = measureFaviconVisibility(image);+ resolve(visibility ? classifyFaviconContrast(visibility) : "neutral");+ }, { once: true });++ // An icon that will not load is one the preview is already showing its placeholder for.+ image.addEventListener("error", () => resolve("neutral"), { once: true });++ image.src = src;+ });+}diff --git a/apps/client/src/services/link_embed.tsx b/apps/client/src/services/link_embed.tsxindex 88f8eafed1..2ef3d1b7a6 100644--- a/apps/client/src/services/link_embed.tsx+++ b/apps/client/src/services/link_embed.tsx@@ -4,6 +4,7 @@ import { extractYouTubeVideoId, type LinkEmbedMetadata, safeHostname, safeLinkPrimport { render, type VNode } from "preact";import { useState } from "preact/hooks";+import { useFaviconContrastClass } from "./favicon_contrast.js";import { t } from "./i18n.js";import server from "./server.js";@@ -125,10 +126,15 @@ function ImagePlaceholder() {}function Favicon({ src }: { src?: string }) {+ // A site draws its icon for one background, and ours is not always that one — see+ // favicon_contrast.ts. The verdict travels as a class so that switching theme corrects the icon+ // without anything being measured again.+ const contrastClass = useFaviconContrastClass(src);+return (<PreviewPicturesrc={src}- className="link-embed-mention-favicon"+ className={contrastClass ? `link-embed-mention-favicon ${contrastClass}` : "link-embed-mention-favicon"}size={16}placeholder={<span className="link-embed-mention-dot" />}/>diff --git a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css b/apps/client/src/widgets/type_widgets/text/LinkEmbed.cssindex d3f644d2f8..aa1c5fee2d 100644--- a/apps/client/src/widgets/type_widgets/text/LinkEmbed.css+++ b/apps/client/src/widgets/type_widgets/text/LinkEmbed.css@@ -66,6 +66,20 @@flex-shrink: 0;}+/* A site draws its icon for one background, usually its own, and ours is not always that one:+ GitHub's octocat is black on nothing and vanishes on a dark theme, while a mark drawn white for a+ dark header vanishes on a light one. Which icons those are is measured from their own pixels (see+ favicon_contrast.ts) and arrives here as a class, leaving the theme to decide when to act on it —+ so switching theme corrects the icons immediately, with nothing measured again.+ The rotation before the inversion is what keeps this from being vandalism: invert(1) alone also+ sends every hue to its opposite, turning a navy mark pale yellow. Rotating the hue a half turn+ first puts it back, so what changes is lightness alone — a black glyph turns white, and a+ coloured one goes on being its own colour. */+body.dark-theme .link-embed-favicon-dark,+body.light-theme .link-embed-favicon-light {+ filter: hue-rotate(180deg) invert(1);+}+.ck-content .image img.link-embed-mention-favicon {min-width: unset;margin: 0 4px 0 0;@@ -225,7 +239,9 @@:root *:not(.link-embed-preview-wrapper) > a.link-embed-card:hover {background: var(--card-background-hover-color);- & img {+ /* The cover image alone, not every img in the card: the favicon is the card's other one, and+ brightening it says nothing while replacing the halo that keeps a dark icon legible. */+ & .link-embed-card-image {filter: var(--link-preview-card-image-hover-filter);}}diff --git a/packages/commons/src/index.ts b/packages/commons/src/index.tsindex 8b6f23755c..42e5976739 100644--- a/packages/commons/src/index.ts+++ b/packages/commons/src/index.ts@@ -28,6 +28,7 @@ export { default as BUILTIN_ATTRIBUTES } from "./lib/builtin_attributes.js";// barrel is imported by virtually every client module. Import them via their subpath instead,// e.g. "@triliumnext/commons/src/lib/spreadsheet/render_to_html".export * from "./lib/electron_api_interface.js";+export * from "./lib/favicon_contrast.js";export * from "./lib/link_embed.js";export * from "./lib/llm_api.js";export * from "./lib/marked_extensions.js";diff --git a/packages/commons/src/lib/favicon_contrast.spec.ts b/packages/commons/src/lib/favicon_contrast.spec.tsnew file mode 100644index 0000000000..f7def7bca5--- /dev/null+++ b/packages/commons/src/lib/favicon_contrast.spec.ts@@ -0,0 +1,106 @@+import { describe, expect, it } from "vitest";++import {+ classifyFaviconContrast,+ contrastRatio,+ faviconContrastClass,+ relativeLuminance,+ summarizeFaviconVisibility+} from "./favicon_contrast.js";++/** Builds an RGBA bitmap out of runs of identical pixels: `[r, g, b, alpha, howMany]`. */+function bitmap(...runs: [number, number, number, number, number][]): Uint8ClampedArray {+ const pixels: number[] = [];++ for (const [r, g, b, alpha, count] of runs) {+ for (let i = 0; i < count; i++) {+ pixels.push(r, g, b, alpha);+ }+ }++ return new Uint8ClampedArray(pixels);+}++const TRANSPARENT: [number, number, number, number, number] = [0, 0, 0, 0, 100];++describe("relative luminance and contrast", () => {+ it("anchors on black and white, and rates the pair at the maximum ratio", () => {+ expect(relativeLuminance({ r: 0, g: 0, b: 0 })).toBe(0);+ expect(relativeLuminance({ r: 255, g: 255, b: 255 })).toBeCloseTo(1, 5);++ expect(contrastRatio(0, 1)).toBeCloseTo(21, 5);+ // Order must not matter, and a colour against itself is the minimum.+ expect(contrastRatio(1, 0)).toBeCloseTo(21, 5);+ expect(contrastRatio(0.3, 0.3)).toBe(1);+ });++ it("ranks the channels by how much light each carries", () => {+ const red = relativeLuminance({ r: 255, g: 0, b: 0 });+ const green = relativeLuminance({ r: 0, g: 255, b: 0 });+ const blue = relativeLuminance({ r: 0, g: 0, b: 255 });++ expect(green).toBeGreaterThan(red);+ expect(red).toBeGreaterThan(blue);+ });+});++describe("classifying a favicon", () => {+ it("condemns a black glyph on nothing, which is the case that started all this", () => {+ // GitHub's octocat: a black mark on a transparent field.+ const visibility = summarizeFaviconVisibility(bitmap(TRANSPARENT, [0, 0, 0, 255, 40]));++ expect(visibility.hasContent).toBe(true);+ expect(visibility.onDark).toBe(0);+ expect(visibility.onLight).toBe(1);+ expect(classifyFaviconContrast(visibility)).toBe("dark");+ });++ it("condemns a white glyph on nothing just as readily, which a dark-mode-only fix would miss", () => {+ const visibility = summarizeFaviconVisibility(bitmap(TRANSPARENT, [255, 255, 255, 255, 40]));++ expect(visibility.onDark).toBe(1);+ expect(visibility.onLight).toBe(0);+ expect(classifyFaviconContrast(visibility)).toBe("light");+ });++ it("leaves an ordinary mid-tone colour alone on both surfaces", () => {+ const visibility = summarizeFaviconVisibility(bitmap([0x4a, 0x90, 0xd9, 255, 40]));++ expect(visibility.onDark).toBe(1);+ expect(visibility.onLight).toBe(1);+ expect(classifyFaviconContrast(visibility)).toBe("neutral");+ });++ it("leaves a filled tile alone: its own mark carries it, however dark the tile is", () => {+ // A black square with a white glyph over a fifth of it. The average colour is nearly black,+ // yet the glyph is what one actually sees, and it survives a dark theme untouched.+ const visibility = summarizeFaviconVisibility(bitmap([0, 0, 0, 255, 80], [255, 255, 255, 255, 20]));++ expect(visibility.onDark).toBeCloseTo(0.2, 5);+ expect(classifyFaviconContrast(visibility)).toBe("neutral");+ });++ it("weighs each pixel by how opaque it is, so a faint edge does not count as a whole mark", () => {+ // A black glyph whose only light pixels are half-transparent: not enough to save it.+ const visibility = summarizeFaviconVisibility(bitmap([0, 0, 0, 255, 90], [255, 255, 255, 26, 10]));++ expect(visibility.onDark).toBeLessThan(0.15);+ expect(classifyFaviconContrast(visibility)).toBe("dark");+ });++ it("says nothing about an icon that draws nothing", () => {+ const visibility = summarizeFaviconVisibility(bitmap(TRANSPARENT));++ expect(visibility).toEqual({ onDark: 0, onLight: 0, hasContent: false });+ expect(classifyFaviconContrast(visibility)).toBe("neutral");+ expect(summarizeFaviconVisibility(new Uint8ClampedArray()).hasContent).toBe(false);+ });+});++describe("faviconContrastClass", () => {+ it("names the two verdicts that need styling and stays silent on the third", () => {+ expect(faviconContrastClass("dark")).toBe("link-embed-favicon-dark");+ expect(faviconContrastClass("light")).toBe("link-embed-favicon-light");+ expect(faviconContrastClass("neutral")).toBeUndefined();+ });+});diff --git a/packages/commons/src/lib/favicon_contrast.ts b/packages/commons/src/lib/favicon_contrast.tsnew file mode 100644index 0000000000..b6014b2fd3--- /dev/null+++ b/packages/commons/src/lib/favicon_contrast.ts@@ -0,0 +1,190 @@+/**+ * Whether a link preview's favicon can actually be seen where we draw it.+ *+ * A site draws its icon for one background, usually its own. GitHub's is a black octocat on nothing,+ * which disappears the moment a dark theme puts it on a dark surface; a mark drawn white for a dark+ * header disappears just as completely on a light one. Both are the same fault seen from two sides,+ * and both are measured here the same way — by asking how much of what the icon draws would stand+ * out against each surface.+ *+ * The measurement is a property of the icon alone, deliberately: it is taken once per icon, cached+ * for as long as the page lives, and expressed as a class the stylesheets act on. Measuring against+ * the *live* background would be a little more accurate and would have to be redone every time the+ * user switches theme, which is exactly the sort of thing a stylesheet does for free.+ */++export interface Rgb {+ r: number;+ g: number;+ b: number;+}++/**+ * The contrast a graphic needs against its background to be made out (WCAG 2.1 SC 1.4.11).+ *+ * The more familiar 4.5:1 is the threshold for *text*, and it is the wrong tool here: against a+ * near-black and a near-white surface the two failing bands overlap, so almost every icon would be+ * judged invisible against one or the other and get inverted somewhere. At 3:1 there is a+ * comfortable middle band that ordinary colourful icons sit in, and only the genuinely too-dark and+ * too-light ones are touched.+ */+export const MIN_ICON_CONTRAST_RATIO = 3;++/**+ * The surfaces an icon is judged against. Real themes differ, but a preview is always drawn on+ * something close to one of these two, and the error at the edges costs far less than making the+ * answer theme-dependent would (see the note at the top of this file).+ */+const DARK_SURFACE: Rgb = { r: 0x1e, g: 0x1e, b: 0x1e };+const LIGHT_SURFACE: Rgb = { r: 0xff, g: 0xff, b: 0xff };++/** An sRGB channel (0–255) as its linear-light value, per WCAG's definition of relative luminance. */+function toLinearChannel(value: number): number {+ const channel = value / 255;++ return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4;+}++/** WCAG relative luminance: how much light a colour puts out, 0 for black and 1 for white. */+export function relativeLuminance({ r, g, b }: Rgb): number {+ return 0.2126 * toLinearChannel(r) + 0.7152 * toLinearChannel(g) + 0.0722 * toLinearChannel(b);+}++/** WCAG contrast ratio between two relative luminances, from 1 (identical) to 21 (black on white). */+export function contrastRatio(one: number, other: number): number {+ const lighter = Math.max(one, other);+ const darker = Math.min(one, other);++ return (lighter + 0.05) / (darker + 0.05);+}++/** How much of an icon would be made out against each of the two surfaces. */+export interface FaviconVisibility {+ /** Share of what the icon draws that clears {@link MIN_ICON_CONTRAST_RATIO} on a dark surface. */+ onDark: number;+ /** The same against a light surface. */+ onLight: number;+ /** False when the icon draws nothing at all — a fully transparent bitmap, or one we could not read. */+ hasContent: boolean;+}++/**+ * How much of an icon shows, measured over its own pixels.+ *+ * Each pixel is weighted by how opaque it is, so the transparent field around a glyph counts for+ * nothing and a soft edge counts for part of itself. Working in shares rather than in an average+ * colour is what lets an icon that carries its own background answer for itself: a black tile with a+ * white glyph averages out very dark, yet the glyph is a fifth of what it draws and is perfectly+ * legible on a dark theme, so it is left alone where an average would have condemned it.+ */+export function summarizeFaviconVisibility(pixels: Uint8ClampedArray): FaviconVisibility {+ const darkSurface = relativeLuminance(DARK_SURFACE);+ const lightSurface = relativeLuminance(LIGHT_SURFACE);++ let drawn = 0;+ let visibleOnDark = 0;+ let visibleOnLight = 0;++ for (let i = 0; i + 3 < pixels.length; i += 4) {+ const alpha = pixels[i + 3] / 255;+ if (alpha === 0) {+ continue;+ }++ const luminance = relativeLuminance({ r: pixels[i], g: pixels[i + 1], b: pixels[i + 2] });++ drawn += alpha;+ if (contrastRatio(luminance, darkSurface) >= MIN_ICON_CONTRAST_RATIO) {+ visibleOnDark += alpha;+ }+ if (contrastRatio(luminance, lightSurface) >= MIN_ICON_CONTRAST_RATIO) {+ visibleOnLight += alpha;+ }+ }++ if (drawn === 0) {+ return { onDark: 0, onLight: 0, hasContent: false };+ }++ return { onDark: visibleOnDark / drawn, onLight: visibleOnLight / drawn, hasContent: true };+}++/**+ * Which surface an icon needs help on: `dark` for one that fades into a dark theme, `light` for one+ * that fades into a light theme, `neutral` for one that holds its own on both.+ */+export type FaviconContrast = "dark" | "light" | "neutral";++/**+ * How much of an icon has to survive a surface for it to be left alone there.+ *+ * Not zero, because an icon is allowed a few stray pixels that happen to clear the threshold — a+ * black glyph with an anti-aliased edge or a single light speck is still a black glyph. A seventh of+ * the icon is enough to read as a shape, and is roughly the size of the white mark inside a filled+ * tile, which is the case this is really here to spare.+ */+const MIN_VISIBLE_SHARE = 0.15;++/** Reads {@link summarizeFaviconVisibility}'s measurement as the one decision the stylesheets need. */+export function classifyFaviconContrast(visibility: FaviconVisibility): FaviconContrast {+ if (!visibility.hasContent) {+ return "neutral";+ }++ if (visibility.onDark < MIN_VISIBLE_SHARE) {+ return "dark";+ }++ if (visibility.onLight < MIN_VISIBLE_SHARE) {+ return "light";+ }++ return "neutral";+}++/** The class an icon carries so the stylesheets can act on the measurement, or nothing for a neutral one. */+export function faviconContrastClass(contrast: FaviconContrast): string | undefined {+ return contrast === "neutral" ? undefined : `link-embed-favicon-${contrast}`;+}++/**+ * The square the icon is rasterised into to be measured. Well above the 16px it is drawn at, so a+ * thin glyph keeps enough pixels to weigh, and small enough that reading it back costs nothing.+ */+const SAMPLE_SIZE = 32;++/**+ * Measures a favicon that the browser has already loaded.+ *+ * Works off the rendered pixels rather than the file, which is what makes it indifferent to format:+ * by the time an `<img>` has loaded, an SVG, an ICO and a PNG are all just a bitmap the canvas can+ * read. It is also self-correcting for the icons that carry their own `prefers-color-scheme` rules,+ * since what we measure is the variant the browser chose to draw.+ *+ * Returns undefined when the icon cannot be measured, which the caller should read as "leave it+ * alone" rather than as any particular verdict.+ */+export function measureFaviconVisibility(image: CanvasImageSource): FaviconVisibility | undefined {+ const canvas = document.createElement("canvas");+ canvas.width = SAMPLE_SIZE;+ canvas.height = SAMPLE_SIZE;++ const context = canvas.getContext("2d", { willReadFrequently: true });+ if (!context) {+ return undefined;+ }++ try {+ // The destination size is given explicitly because an SVG that declares only a viewBox has no+ // intrinsic size at all, and reading naturalWidth for one answers 0 in some browsers. Drawing+ // into a fixed box sidesteps the question entirely.+ context.drawImage(image, 0, 0, SAMPLE_SIZE, SAMPLE_SIZE);++ return summarizeFaviconVisibility(context.getImageData(0, 0, SAMPLE_SIZE, SAMPLE_SIZE).data);+ } catch {+ // getImageData throws on a tainted canvas. A preview's pictures are always same-origin (see+ // isLocalPreviewImageSrc), so this should not happen — but an unreadable icon is a reason to+ // leave the icon as the site drew it, never a reason to fail the render around it.+ return undefined;+ }+}diff --git a/packages/share-theme/src/scripts/index.ts b/packages/share-theme/src/scripts/index.tsindex 6dd50add36..aee26fc793 100644--- a/packages/share-theme/src/scripts/index.ts+++ b/packages/share-theme/src/scripts/index.ts@@ -7,6 +7,7 @@ import setupMermaid from "./modules/mermaid.js";import setupMath from "./modules/math.js";import setupSidebars from "./modules/sidebar.js";import setupVideoFacades from "./modules/video_facade.js";+import setupFaviconContrast from "./modules/favicon_contrast.js";import api from "./modules/api.js";import "highlight.js/styles/default.css";import "@triliumnext/ckeditor5/src/theme/ck-content.css";@@ -32,6 +33,7 @@ function setupTextNote() {$try(setupMermaid);$try(setupMath);$try(setupVideoFacades);+ $try(setupFaviconContrast);}document.addEventListener(diff --git a/packages/share-theme/src/scripts/modules/favicon_contrast.ts b/packages/share-theme/src/scripts/modules/favicon_contrast.tsnew file mode 100644index 0000000000..afc5a3f449--- /dev/null+++ b/packages/share-theme/src/scripts/modules/favicon_contrast.ts@@ -0,0 +1,35 @@+import { classifyFaviconContrast, faviconContrastClass, measureFaviconVisibility } from "@triliumnext/commons";++/**+ * Corrects link-preview favicons that would be invisible against the page.+ *+ * A site draws its icon for one background, usually its own: GitHub's is a black octocat on nothing,+ * which disappears on the dark theme, and a mark drawn white for a dark header disappears on the+ * light one. Each icon's own pixels are measured (the shared logic lives in commons, so the app and+ * the shared page reach the same verdict about the same picture) and the answer is left on the+ * element as a class for `link-embed.css` to act on — which is what lets the visitor's theme switch+ * correct the icons with nothing measured again.+ */+export default function setupFaviconContrast() {+ for (const favicon of document.querySelectorAll<HTMLImageElement>("img.link-embed-mention-favicon")) {+ // A picture already in the browser's cache is complete before this runs and will never fire+ // `load`; one still arriving has to be waited for.+ if (favicon.complete) {+ classify(favicon);+ } else {+ favicon.addEventListener("load", () => classify(favicon), { once: true });+ }+ }+}++function classify(favicon: HTMLImageElement) {+ const visibility = measureFaviconVisibility(favicon);+ if (!visibility) {+ return;+ }++ const contrastClass = faviconContrastClass(classifyFaviconContrast(visibility));+ if (contrastClass) {+ favicon.classList.add(contrastClass);+ }+}diff --git a/packages/share-theme/src/styles/link-embed.css b/packages/share-theme/src/styles/link-embed.cssindex 8a0a3da4af..159910f2d8 100644--- a/packages/share-theme/src/styles/link-embed.css+++ b/packages/share-theme/src/styles/link-embed.css@@ -34,6 +34,18 @@flex-shrink: 0;}+/* A site draws its icon for one background, usually its own, and ours is not always that one:+ GitHub's octocat is black on nothing and vanishes on the dark theme, while a mark drawn white for+ a dark header vanishes on the light one. The classes are put on by the favicon_contrast script,+ which measures each icon's own pixels; the theme decides when to act on them.+ Rotating the hue a half turn before inverting is what keeps this from being vandalism: invert(1)+ alone also sends every hue to its opposite, so a navy mark would come back pale yellow. Mirrors+ the app-side rule in LinkEmbed.css, where the same markup faces the same problem. */+html.theme-dark .link-embed-favicon-dark,+html.theme-light .link-embed-favicon-light {+ filter: hue-rotate(180deg) invert(1);+}+.link-embed-mention-dot {display: inline-block;width: 8px;