Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/shared/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,7 @@
"@noble/curves": "catalog:",
"@noble/hashes": "catalog:",
"@t3tools/contracts": "workspace:*",
"culori": "^4.0.2",
"effect": "catalog:",
"ffi-rs": "1.3.2",
"mdast-util-directive": "catalog:",
Expand All @@ -580,6 +581,7 @@
"devDependencies": {
"@effect/platform-node": "catalog:",
"@effect/vitest": "catalog:",
"@types/culori": "^4.0.1",
"@types/mdast": "^4.0.4",
"@types/node": "catalog:",
"micromark-util-types": "catalog:",
Expand Down
63 changes: 63 additions & 0 deletions packages/shared/src/htmlRender.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,77 @@
import { describe, expect, it } from "vite-plus/test";
import { wcagContrast } from "culori";

import {
htmlRenderTheme,
injectHtmlRenderBootstrap,
readHtmlRenderImageRequest,
readHtmlRenderLinkRequest,
} from "./htmlRender.ts";
import { T3_CODE_DARK_THEME_COLORS } from "./themePalettes.ts";
import { htmlRenderFromToolItem } from "./toolOutput.ts";

const reference = { attachmentId: "thread-abc-123.html", title: "Chart", height: 420 };

describe("htmlRenderTheme graphic contrast", () => {
it.each([
{ name: "the reported dark accent", canvas: "#161515", accent: "#21180e" },
{ name: "a midgray accent and canvas", canvas: "#757575", accent: "#747474" },
{ name: "a pale accent on a light canvas", canvas: "#fafafa", accent: "#eeeeee" },
{
name: "a dark accent that only a midgray card can carry",
canvas: "#161515",
accent: "#21180e",
surface: "#777777",
},
])(
"keeps graphic ink and paired text readable for $name",
({ canvas, accent, surface = T3_CODE_DARK_THEME_COLORS.surface }) => {
for (const appearance of ["dark", "light"] as const) {
const { variables } = htmlRenderTheme(
{ ...T3_CODE_DARK_THEME_COLORS, canvas, surface, accent, accentForeground: "#ffffff" },
appearance,
);

expect(variables["--background"]).toBe(canvas);
for (const key of [
"--accent",
...Array.from({ length: 6 }, (_, index) => `--chart-${index + 1}`),
]) {
for (const background of [canvas, surface]) {
expect(
wcagContrast(variables[key]!, background),
`${appearance} ${key} on ${background}`,
).toBeGreaterThanOrEqual(3);
}
}
expect(
wcagContrast(variables["--accent-foreground"]!, variables["--accent"]!),
appearance,
).toBeGreaterThanOrEqual(4.5);
}
},
);

it.each([
{ canvas: "#161515", accent: "#ffffff" },
{ canvas: "#ffffff", accent: "#000000" },
{ canvas: "#161515", accent: "rgb(255 255 255 / 80%)" },
{ canvas: "#161515", accent: "var(--brand)" },
{ canvas: "rgb(0 0 0 / 50%)", accent: "#111111" },
// No color reaches 3:1 on both; keep the one that already reads on the canvas.
{ canvas: "#505050", surface: "#aaaaaa", accent: "#ffffff" },
])("preserves passthrough accent $accent on $canvas", ({ canvas, surface = canvas, accent }) => {
const { variables } = htmlRenderTheme(
{ ...T3_CODE_DARK_THEME_COLORS, canvas, surface, accent },
"dark",
);

expect(variables["--accent"]).toBe(accent);
expect(variables["--chart-1"]).toBe(accent);
expect(variables["--accent-foreground"]).toBe(T3_CODE_DARK_THEME_COLORS.accentForeground);
});
});

describe("injectHtmlRenderBootstrap", () => {
it("puts the theme ahead of the page's own head content", () => {
const html =
Expand Down
19 changes: 15 additions & 4 deletions packages/shared/src/htmlRender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
type ThemeColors,
} from "./themePalettes.ts";
import { EVENT_CODE_SHORTCUT_KEYS } from "./keybindings.ts";
import { readableHtmlRenderColor } from "./htmlRenderColors.ts";

export const HTML_RENDER_TOOL_NAME = "html_render";
export const HTML_RENDER_MIN_HEIGHT = 80;
Expand Down Expand Up @@ -178,6 +179,17 @@ export function htmlRenderTheme(
fonts: HtmlRenderFonts = HTML_RENDER_DEFAULT_FONTS,
): HtmlRenderTheme {
const fixed = FIXED_COLORS[appearance];
// Graphics sit on the canvas or, per the render guide, inside a --card box.
const graphicSurfaces = [colors.canvas, colors.surface];
const accent = readableHtmlRenderColor(colors.accent, graphicSurfaces, 3);
const accentForeground =
accent === colors.accent
? colors.accentForeground
: readableHtmlRenderColor(colors.accentForeground, [accent], 4.5);
const chart = [
accent,
...fixed.chart.map((color) => readableHtmlRenderColor(color, graphicSurfaces, 3)),
];
return {
appearance,
variables: {
Expand All @@ -196,8 +208,8 @@ export function htmlRenderTheme(
"--ring": colors.focus,
"--primary": colors.messageAction,
"--primary-foreground": colors.messageActionForeground,
"--accent": colors.accent,
"--accent-foreground": colors.accentForeground,
"--accent": accent,
"--accent-foreground": accentForeground,
"--accent-surface": colors.accentSurface,
"--accent-surface-foreground": colors.accentSurfaceForeground,
"--destructive": colors.error,
Expand All @@ -212,8 +224,7 @@ export function htmlRenderTheme(
"--info-foreground": fixed.infoForeground,
"--code-background": colors.codeBackground,
"--code-foreground": colors.codeForeground,
"--chart-1": colors.accent,
...Object.fromEntries(fixed.chart.map((color, index) => [`--chart-${index + 2}`, color])),
...Object.fromEntries(chart.map((color, index) => [`--chart-${index + 1}`, color])),
"--radius": "0.625rem",
"--font-sans": fonts.sans,
"--font-mono": fonts.mono,
Expand Down
62 changes: 62 additions & 0 deletions packages/shared/src/htmlRenderColors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import "culori/css";
import { clampChroma, converter, formatHex, wcagContrast, type Rgb } from "culori/fn";

const toRgb = converter("rgb");
const toOklch = converter("oklch");
const LIGHTNESS_STEPS = 200;

/** Keeps `color` unless it falls below `minimum` contrast on any of `surfaces`. */
export function readableHtmlRenderColor(
color: string,
surfaces: readonly string[],
minimum: number,
): string {
const foreground = toRgb(color);
const backgrounds = surfaces.map((surface) => toRgb(surface));
const opaque = backgrounds.filter(
(background): background is Rgb => background !== undefined && (background.alpha ?? 1) >= 1,
);
// A translucent surface needs the host's underlying surface to determine contrast.
if (!foreground || opaque.length === 0 || opaque.length < backgrounds.length) return color;

const alpha = Math.max(0, Math.min(1, foreground.alpha ?? 1));
const paintedOn = (background: Rgb): Rgb => ({
mode: "rgb",
r: foreground.r * alpha + background.r * (1 - alpha),
g: foreground.g * alpha + background.g * (1 - alpha),
b: foreground.b * alpha + background.b * (1 - alpha),
});
const originalContrasts = opaque.map((background) =>
wcagContrast(paintedOn(background), background),
);
const originalWorst = Math.min(...originalContrasts);
if (originalWorst >= minimum) return color;

const base = toOklch(paintedOn(opaque[0]!));
let nearest: string | undefined;
let nearestDistance = Infinity;
let strongest = color;
let strongestWorst = originalWorst;
// Contrast against several surfaces is not monotonic in lightness, so scan it.
for (let step = 0; step <= LIGHTNESS_STEPS; step += 1) {
const lightness = step / LIGHTNESS_STEPS;
// Measure the encoded sRGB paint so rounding cannot put it below the threshold.
const candidate = formatHex(clampChroma({ ...base, l: lightness }, "oklch", "rgb"));
const contrasts = opaque.map((background) => wcagContrast(candidate, background));
const worst = Math.min(...contrasts);
const distance = Math.abs(lightness - base.l);
if (worst >= minimum && distance < nearestDistance) {
nearest = candidate;
nearestDistance = distance;
}
// A fallback must not give up a surface the original color already reads on.
const keepsSatisfied = contrasts.every(
(contrast, index) => contrast >= minimum || originalContrasts[index]! < minimum,
);
if (keepsSatisfied && worst > strongestWorst) {
strongest = candidate;
strongestWorst = worst;
}
}
return nearest ?? strongest;
}
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading