From 76366650adde8f25102fab4f41e1847f9460f1fb Mon Sep 17 00:00:00 2001 From: Shane Smith Date: Sun, 22 Nov 2026 22:41:37 +1030 Subject: [PATCH] feat: preview guild icons in light and dark mode, with visibility alerts --- DESIGN.md | 2 +- KNOWLEDGE_BASE.md | 6 +- resources/css/app.css | 8 +- resources/js/components/guild-dialog.tsx | 41 +- .../js/components/image-contrast-preview.tsx | 134 +++++++ resources/js/lib/image-contrast.ts | 198 ++++++++++ tests/Unit/GuildControls.test.tsx | 35 ++ tests/Unit/ImageContrast.test.ts | 350 ++++++++++++++++++ tests/Unit/ImageContrastPreview.test.tsx | 134 +++++++ 9 files changed, 903 insertions(+), 5 deletions(-) create mode 100644 resources/js/components/image-contrast-preview.tsx create mode 100644 resources/js/lib/image-contrast.ts create mode 100644 tests/Unit/ImageContrast.test.ts create mode 100644 tests/Unit/ImageContrastPreview.test.tsx diff --git a/DESIGN.md b/DESIGN.md index 1cb2aab6e..2a5abcf65 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -194,7 +194,7 @@ A cool, nearly colorless shell with one working blue and six author lanes reserv - **Author Lanes** (`lane-0` through `lane-5`, burnt orange, green, violet, teal, rose, ochre; each with a `-dark` lift): chosen by the user in Settings → Profile, otherwise assigned by hashing the user id (`User::automaticLane()`); every serialized user carries the effective `lane` (0–5) and the frontend paints it with `laneColor(user.lane)`. Used only for graph nodes, rail segments, the staged composer node, the 8px dot before a handle in profile contexts, and the 2px ring around a profile avatar. Never text, never fills behind text, never buttons. ### Tertiary -- **Rm Red** (`destructive`): delete affordances (trash icon on hover, inline confirm wash at 8% opacity, destructive button), "Unfollow" on hover, the composer counter at 0. +- **Rm Red** (`destructive`): delete affordances (trash icon on hover, inline confirm wash at 8% opacity, destructive button), "Unfollow" on hover, the composer counter at 0, and the border and warning status ("Hard to see", "Hard to see (WCAG)" or "Partly hard to see") on a guild icon preview. ### Neutral - **Cool Shell** (`shell`): page background around the feed column and side columns; also the hole punched in each node. diff --git a/KNOWLEDGE_BASE.md b/KNOWLEDGE_BASE.md index 6965f9e74..05fe3b2d1 100644 --- a/KNOWLEDGE_BASE.md +++ b/KNOWLEDGE_BASE.md @@ -659,7 +659,11 @@ Sources: [issue command UI](resources/js/components/issue-command.tsx), [issue v ### Guilds (preview) -Guilds are public groups around hashtags and are not generally available yet. In the preview, matching hashtags become small clickable guild labels; ordinary hashtags still open search. Create a guild from the Guilds overview or a hashtag's search page. From the overview, its display name determines the hashtag: “Laravel 4ever” becomes `#laravel4ever`. Display names and handles each allow up to 60 characters. When claiming a hashtag, the display name must match its letters, numbers and underscores, ignoring case; spaces, punctuation and decorative symbols are ignored, so `/dev/null` is valid for `#devnull`. Accents and underscores remain significant. Its creator joins automatically and maintains its display name, icon and description; a new display name must still match the hashtag, so `#adhd` can become “ADHD” but never another hashtag. Each person can create up to 100 guilds. A guild's name, description and icon pass the same automated moderation as commits before the guild is published or edited. When the moderation flags a new guild or an edit, it waits for an admin to review it instead: nothing of it is public until it is approved, the guild keeps its current details meanwhile, and a rejected submission is discarded. Submitting again for the same hashtag replaces the one still waiting, and new guilds waiting for review count toward the creation limit. +Guilds are public groups around hashtags and are not generally available yet. In the preview, matching hashtags become small clickable guild labels; ordinary hashtags still open search. Create a guild from the Guilds overview or a hashtag's search page. From the overview, its display name determines the hashtag: “Laravel 4ever” becomes `#laravel4ever`. Display names and handles each allow up to 60 characters. When claiming a hashtag, the display name must match its letters, numbers and underscores, ignoring case; spaces, punctuation and decorative symbols are ignored, so `/dev/null` is valid for `#devnull`. Accents and underscores remain significant. Its creator joins automatically and maintains its display name, icon and description; a new display name must still match the hashtag, so `#adhd` can become “ADHD” but never another hashtag. Each person can create up to 100 guilds. + +A guild's icon is an emoji or an uploaded image. When you upload an image, or edit a guild that already has one, the image is previewed in light and dark mode, with a warning if all or part of it is hard to see in one mode, such as a dark logo on a transparent background in dark mode, so you can pick another image before saving. “Hard to see (WCAG)” means the image can be made out but falls short of the contrast that the Web Content Accessibility Guidelines ask of graphics. An image that fills its own square or circle, such as a photo or a logo on a colored square, brings its own background, so it is only flagged if it nearly disappears. A drop shadow on one side of a logo can also count as a part that is hard to see, since it fades into one of the two backgrounds; the warning is advice, and you can still save the image. + +A guild's name, description and uploaded icon image (not an emoji) pass the same automated moderation as commits before the guild is published or edited. When the moderation flags a new guild or an edit, it waits for an admin to review it instead: nothing of it is public until it is approved, the guild keeps its current details meanwhile, and a rejected submission is discarded. Submitting again for the same hashtag replaces the one still waiting, and new guilds waiting for review count toward the creation limit. The Guilds page lists groups by member count, with 24 guilds per page. Search matches keywords in guild names, handles, and descriptions, ignoring case; a leading `#` is optional. This directory search is keyword-based, not semantic. Click a guild's member count to browse its members: the moderator appears first, labeled “(moderator)”, followed by newest joins, with 50 people per page and Load more for the next page. Joining adds matching commits to Following without following every author and clears any existing mute. When a commit appears only because of a joined guild, it says “because you joined” beside the guild label. Leave a guild to reveal its Mute control. Muting hides matching commits from logs and search, including commits by followed authors. You can still open the guild or a commit directly. diff --git a/resources/css/app.css b/resources/css/app.css index c1291a8d2..0dc703cdb 100644 --- a/resources/css/app.css +++ b/resources/css/app.css @@ -384,7 +384,9 @@ } } -:root { +/* data-theme-scope gives an element the regular light or dark tokens, as in the guild icon preview. */ +:root, +[data-theme-scope='light'] { --background: #f6f7f8; --foreground: #121417; --card: #ffffff; @@ -432,7 +434,9 @@ --sidebar-ring: var(--ring); } -.dark { +/* data-theme-scope gives an element the regular light or dark tokens, as in the guild icon preview. */ +.dark, +[data-theme-scope='dark'] { --background: #111112; --foreground: #ececec; --card: #18181a; diff --git a/resources/js/components/guild-dialog.tsx b/resources/js/components/guild-dialog.tsx index 35b0291c2..500fd794d 100644 --- a/resources/js/components/guild-dialog.tsx +++ b/resources/js/components/guild-dialog.tsx @@ -1,10 +1,11 @@ import type { FormComponentRef } from '@inertiajs/core'; import { Form, router } from '@inertiajs/react'; import { LoaderCircle, Plus, Save } from 'lucide-react'; -import { type ReactNode, useRef, useState } from 'react'; +import { type ReactNode, useEffect, useRef, useState } from 'react'; import { store, update } from '@/actions/App/Http/Controllers/GuildController'; import { EmojiPickerButton } from '@/components/emoji-picker'; import { GuildIcon } from '@/components/guild-icon'; +import { ImageContrastPreview } from '@/components/image-contrast-preview'; import InputError from '@/components/input-error'; import { Button } from '@/components/ui/button'; import { @@ -36,7 +37,30 @@ export function GuildDialog({ const [emoji, setEmoji] = useState(guild?.emoji ?? '💻'); const [removeIcon, setRemoveIcon] = useState(false); const [name, setName] = useState(guild?.name ?? handle ?? ''); + const [preview, setPreview] = useState(null); const form = useRef(null); + + const previewUrl = useRef(null); + + function showPreview(file: File | null) { + if (previewUrl.current) { + URL.revokeObjectURL(previewUrl.current); + } + previewUrl.current = file ? URL.createObjectURL(file) : null; + setPreview(previewUrl.current); + } + + useEffect( + () => () => { + if (previewUrl.current) { + URL.revokeObjectURL(previewUrl.current); + } + }, + [], + ); + // A new upload, or else the icon the guild has unless an emoji replaces it. + const previewSrc = + preview ?? (removeIcon ? null : (guild?.icon_url ?? null)); const nameHandle = name.replace(/[^\p{L}\p{M}\p{N}_]+/gu, '').toLowerCase(); const hashtag = guild?.handle ?? handle ?? nameHandle; @@ -48,6 +72,7 @@ export function GuildDialog({ onCloseAutoFocus={() => { setEmoji(guild?.emoji ?? '💻'); setRemoveIcon(false); + showPreview(null); setName(guild?.name ?? handle ?? ''); }} > @@ -215,9 +240,23 @@ export function GuildDialog({ name="images[]" type="file" accept="image/jpeg,image/png,image/webp" + onChange={(event) => + showPreview( + event.target.files?.[0] ?? null, + ) + } className={`${fieldClass} file:mr-3 file:text-sm`} aria-describedby="guild-icon-help guild-icon-error" /> + {previewSrc && ( + // Guild icons show at 13–48px. The check runs near the small end, where they fade + // most; the tiles show 40px, the most common size. + + )}

= { + easy: 'Easy to see', + partly: 'Partly hard to see', + wcag: 'Hard to see (WCAG)', + hard: 'Hard to see', +}; + +/** + * Shows an image on the light and dark mode backgrounds and flags a mode where all or part of it is + * hard to see. + * `label` names the image for screen readers; `size` is the size, in pixels, it is shown at elsewhere, + * so the check sees it as people will. The image is shown and checked as a centered square, and only + * a same-origin (or CORS-enabled) `src` can be checked: another shows without a status. + */ +export function ImageContrastPreview({ + src, + label = 'Image', + size, +}: { + src: string; + label?: string; + size: number; +}) { + return ( +

+ {modes.map((mode) => ( + // Keyed by the image, so a new one starts without a status. + + ))} +
+ ); +} + +// data-theme-scope gives the tile its mode's regular tokens. Only var(--…) reads follow it: +// bg-muted-style utilities resolve at the root. +function PreviewTile({ + src, + size, + theme, + label, +}: { + src: string; + size: number; + theme: 'light' | 'dark'; + label: string; +}) { + const tile = useRef(null); + const [status, setStatus] = useState(null); + const warns = status !== null && status !== 'easy'; + + return ( +
+ + { + let pixels; + try { + pixels = readPixels(event.currentTarget, size); + } catch { + // Pixels it can't read (another origin's, say) leave no status. + return; + } + setStatus( + visibility( + pixels, + getComputedStyle(tile.current!) + .getPropertyValue('--muted') + .trim(), + ), + ); + }} + /> + + + {label} + + {warns && ( + + )} + {/* Wraps beside the icon when the tile is narrow. */} + {status && ( + {statuses[status]} + )} + + +
+ ); +} diff --git a/resources/js/lib/image-contrast.ts b/resources/js/lib/image-contrast.ts new file mode 100644 index 000000000..55a3df3a9 --- /dev/null +++ b/resources/js/lib/image-contrast.ts @@ -0,0 +1,198 @@ +function luminance(r: number, g: number, b: number): number { + const [lr, lg, lb] = [r, g, b].map((channel) => { + const c = channel / 255; + return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * lr + 0.7152 * lg + 0.0722 * lb; +} + +export type Visibility = 'easy' | 'partly' | 'wcag' | 'hard'; + +// What a pixel is to visibility(); 0 is one too transparent to matter (under half opaque). +const shows = 1; +const vanishes = 2; +const seen = 3; + +// How a square image's RGBA pixels show over a #rrggbb background, each laid over it. A pixel +// shows at 3:1, WCAG's minimum for graphics, and is faint at 1.5:1: there, but short of it. The +// image is hard to see when fewer than 3% of its pixels show, so a thin logo still counts, and +// 'wcag' when 3% are at least faint. An image at least 3/4 opaque, such as a photo or a logo on +// its own square, rounded or round (a circle fills 79%), brings its own background: it is only hard +// to see when it nearly vanishes, fewer than 3% of it faint. Otherwise the image is partly hard to +// see when a connected part of it, 3% of it or more and at least half opaque, vanishes into the +// background. These parts don't count: one closed in by pixels that show, such as the hole in a +// letter, and ones that touch what shows and together surround all of it, such as a white square +// behind a dark logo (even one the logo cuts in two), its backing. +export function visibility( + pixels: Uint8ClampedArray, + background: string, +): Visibility { + const [br, bg, bb] = [1, 3, 5].map((i) => + Number.parseInt(background.slice(i, i + 2), 16), + ); + const backgroundLuminance = luminance(br, bg, bb); + const count = pixels.length / 4; + const side = Math.sqrt(count); + const minimum = count * 0.03; + const kinds = new Uint8Array(count); + // The box around the pixels that show: [left, top, right, bottom]. + const box = [side, side, -1, -1]; + let shown = 0; + // Pixels that are at least faint, shown ones included. + let faint = 0; + let solid = 0; + for (let p = 0; p < count; p++) { + const i = p * 4; + const alpha = pixels[i + 3] / 255; + const pixelLuminance = luminance( + pixels[i] * alpha + br * (1 - alpha), + pixels[i + 1] * alpha + bg * (1 - alpha), + pixels[i + 2] * alpha + bb * (1 - alpha), + ); + const contrast = + (Math.max(pixelLuminance, backgroundLuminance) + 0.05) / + (Math.min(pixelLuminance, backgroundLuminance) + 0.05); + if (contrast >= 3) { + kinds[p] = shows; + shown++; + grow(box, p % side, Math.floor(p / side)); + } else if (alpha >= 0.5) { + kinds[p] = vanishes; + } + if (contrast >= 1.5) { + faint++; + } + if (alpha >= 0.5) { + solid++; + } + } + if (solid >= count * 0.75) { + return faint >= minimum ? 'easy' : 'hard'; + } + if (shown < minimum) { + return faint >= minimum ? 'wcag' : 'hard'; + } + // The box around the vanishing parts that may be a backing, all together. + const parts = [side, side, -1, -1]; + for (let start = 0; start < count; start++) { + if (kinds[start] !== vanishes) { + continue; + } + // Gather this vanishing part, the box around it, whether it reaches the background, and + // whether it touches a pixel that shows. + const part = [start]; + const around = [side, side, -1, -1]; + kinds[start] = seen; + let size = 0; + let open = false; + let touches = false; + while (part.length > 0) { + const p = part.pop()!; + const x = p % side; + const y = (p - x) / side; + size++; + grow(around, x, y); + if (x === 0 || y === 0 || x === side - 1 || y === side - 1) { + open = true; + } + for ( + let ny = Math.max(y - 1, 0); + ny <= Math.min(y + 1, side - 1); + ny++ + ) { + for ( + let nx = Math.max(x - 1, 0); + nx <= Math.min(x + 1, side - 1); + nx++ + ) { + const q = ny * side + nx; + if (kinds[q] === 0) { + open = true; + } else if (kinds[q] === shows) { + touches = true; + } else if (kinds[q] === vanishes) { + kinds[q] = seen; + part.push(q); + } + } + } + } + if (!open || size < minimum) { + continue; + } + // A part apart from everything that shows can't be its backing. + if (!touches) { + return 'partly'; + } + grow(parts, around[0], around[1]); + grow(parts, around[2], around[3]); + } + if (parts[2] < 0) { + return 'easy'; + } + const backs = + parts[0] <= box[0] && + parts[1] <= box[1] && + parts[2] >= box[2] && + parts[3] >= box[3]; + return backs ? 'easy' : 'partly'; +} + +function grow(box: number[], x: number, y: number): void { + box[0] = Math.min(box[0], x); + box[1] = Math.min(box[1], y); + box[2] = Math.max(box[2], x); + box[3] = Math.max(box[3], y); +} + +// How many times finer than shown readPixels() samples an image, so a stroke thinner than a pixel +// keeps its color instead of being smoothed into the background. +const fineness = 4; + +// A loaded image's pixels as a centered square of `size` pixels, the size it will be shown at. +export function readPixels( + image: HTMLImageElement, + size: number, +): Uint8ClampedArray { + const fine = size * fineness; + const side = Math.min(image.naturalWidth, image.naturalHeight); + const canvas = document.createElement('canvas'); + canvas.width = fine; + canvas.height = fine; + const context = canvas.getContext('2d', { willReadFrequently: true })!; + context.drawImage( + image, + (image.naturalWidth - side) / 2, + (image.naturalHeight - side) / 2, + side, + side, + 0, + 0, + fine, + fine, + ); + return mostOpaque(context.getImageData(0, 0, fine, fine).data, fineness); +} + +// Square RGBA pixels shrunk by `scale`, which must divide their side, each block of them standing +// for itself by its most opaque pixel (the first, in a tie): a thin line keeps its color, and a +// translucent area its translucency. +export function mostOpaque( + pixels: Uint8ClampedArray, + scale: number, +): Uint8ClampedArray { + const fine = Math.sqrt(pixels.length / 4); + const size = fine / scale; + const shrunk = new Uint8ClampedArray(size * size * 4); + for (let y = 0; y < fine; y++) { + for (let x = 0; x < fine; x++) { + const from = (y * fine + x) * 4; + const to = + (Math.floor(y / scale) * size + Math.floor(x / scale)) * 4; + if (pixels[from + 3] > shrunk[to + 3]) { + shrunk.set(pixels.subarray(from, from + 4), to); + } + } + } + return shrunk; +} diff --git a/tests/Unit/GuildControls.test.tsx b/tests/Unit/GuildControls.test.tsx index c0fc2c72a..fb95869c6 100644 --- a/tests/Unit/GuildControls.test.tsx +++ b/tests/Unit/GuildControls.test.tsx @@ -65,6 +65,10 @@ const { ProfileGuilds } = const { Dialog, DialogClose } = await import('../../resources/js/components/ui/dialog'); const { HashtagGuild } = await import('../../resources/js/pages/search/index'); +const { EmojiPickerButton } = + await import('../../resources/js/components/emoji-picker'); +const { ImageContrastPreview } = + await import('../../resources/js/components/image-contrast-preview'); type Element = ReactElement>; function elements(node: ReactNode): Element[] { if (!React.isValidElement(node)) return []; @@ -607,3 +611,34 @@ test.each([true, false])( assert.equal(rows(view).length, 1); }, ); + +test('previews the icon a guild already has until an emoji replaces it', () => { + const guild = { + handle: 'rust', + name: 'Rust', + emoji: '🦀', + icon_url: '/guilds/rust/icon?v=1', + } as unknown as Guild; + const fields = () => { + cursor = 0; + const form = elements(GuildDialog({ guild, children: 'Edit' })).find( + (element) => element.type === Form, + )!; + return elements( + (form.props.children as (props: unknown) => ReactNode)({ + processing: false, + errors: {}, + }), + ); + }; + const preview = () => + fields().find((element) => element.type === ImageContrastPreview)?.props + .src; + + assert.equal(preview(), '/guilds/rust/icon?v=1'); + ( + fields().find((element) => element.type === EmojiPickerButton)!.props + .onPick as (emoji: string) => void + )('🔥'); + assert.equal(preview(), undefined); +}); diff --git a/tests/Unit/ImageContrast.test.ts b/tests/Unit/ImageContrast.test.ts new file mode 100644 index 000000000..f67bea4f2 --- /dev/null +++ b/tests/Unit/ImageContrast.test.ts @@ -0,0 +1,350 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { test } from 'node:test'; +import { + mostOpaque, + visibility, +} from '../../resources/js/lib/image-contrast.ts'; +import type { Visibility } from '../../resources/js/lib/image-contrast.ts'; + +const light = '#eef0f2'; +const dark = '#232326'; + +// A 10×10 icon: `share` of its pixels are `color`, the rest `rest`, as RGBA. +function icon( + color: [number, number, number, number], + share: number, + rest: [number, number, number, number] = [0, 0, 0, 0], +) { + const pixels = new Uint8ClampedArray(400); + for (let i = 0; i < 100; i++) { + pixels.set(i < share * 100 ? color : rest, i * 4); + } + return pixels; +} + +type Rgba = [number, number, number, number]; + +// A 10×10 icon drawn as rows of letters, each a color; "." is transparent. +function draw(rows: string[], colors: Record) { + const pixels = new Uint8ClampedArray(400); + rows.join('') + .split('') + .forEach((letter, i) => { + pixels.set(colors[letter] ?? [0, 0, 0, 0], i * 4); + }); + return pixels; +} + +const colors: Record = { + K: [0, 0, 0, 255], + W: [255, 255, 255, 255], + G: [235, 235, 235, 255], + O: [255, 138, 76, 255], + // Light gray, under half opaque. + g: [235, 235, 235, 100], +}; + +await test('judges icons against the light and dark backgrounds', () => { + // Name, pixels, and how each shows in light and in dark mode. + const cases: [string, Uint8ClampedArray, Visibility, Visibility][] = [ + ['dark logo', icon([0, 0, 0, 255], 0.3), 'easy', 'hard'], + ['white logo', icon([255, 255, 255, 255], 0.3), 'hard', 'easy'], + ['mid-gray logo', icon([119, 119, 119, 255], 0.3), 'easy', 'easy'], + // 1.8:1 on the light background: there, but short of WCAG's 3:1. + ['light-gray logo', icon([180, 180, 180, 255], 0.3), 'wcag', 'easy'], + ['thin dark-gray logo', icon([80, 80, 80, 255], 0.04), 'easy', 'wcag'], + // Deliberately translucent: judged as it is laid over the background. + [ + '30% opaque black watermark', + icon([0, 0, 0, 77], 0.3), + 'wcag', + 'hard', + ], + ['white square', icon([255, 255, 255, 255], 1), 'hard', 'easy'], + [ + 'nearly transparent dark logo', + icon([0, 0, 0, 40], 0.3), + 'hard', + 'hard', + ], + ['transparent image', icon([0, 0, 0, 0], 1), 'hard', 'hard'], + ['faint image', icon([0, 0, 0, 20], 1), 'hard', 'hard'], + [ + // The white square backs the logo, and the white in the O is its hole. + 'logo on its own rounded white square', + draw( + [ + '.WWWWWWWW.', + 'WWWWWWWWWW', + 'WWKKKKKKWW', + 'WWKWWWWKWW', + 'WWKWWWWKWW', + 'WWKWWWWKWW', + 'WWKWWWWKWW', + 'WWKKKKKKWW', + 'WWWWWWWWWW', + '.WWWWWWWW.', + ], + colors, + ), + 'easy', + 'easy', + ], + [ + 'opaque image of two halves', + draw(Array(10).fill('KKKKKGGGGG'), colors), + 'easy', + 'easy', + ], + [ + // Orange is 2:1 on the light background: there, but short of WCAG's 3:1. + 'orange and light-gray parts', + draw( + ['OOO.......', ...Array(8).fill('..........'), '.......GGG'], + colors, + ), + 'wcag', + 'easy', + ], + [ + 'black and light-gray parts, apart', + draw( + ['KKK.......', ...Array(8).fill('..........'), '.......GGG'], + colors, + ), + 'partly', + 'partly', + ], + [ + 'slanted black and light-gray halves, touching', + draw( + [ + '.....KKGG.', + '.....KKGG.', + '....KKGG..', + '....KKGG..', + '...KKGG...', + '...KKGG...', + '..KKGG....', + '..KKGG....', + '.KKGG.....', + '.KKGG.....', + ], + colors, + ), + 'partly', + 'partly', + ], + [ + // The logo cuts its backing in two; the halves still back it together. + 'logo across its own white backing', + draw( + [ + 'WW........', + 'WWW.......', + '.WWW......', + 'KKKKKKKKKK', + '....WWW...', + '.....WWW..', + '......WWW.', + '.......WWW', + '........WW', + '.........W', + ], + colors, + ), + 'easy', + 'partly', + ], + [ + // The white inside the ring is its hole, closed in by black. + 'dark ring filled white', + draw( + [ + '..........', + '..........', + '..KKKKKK..', + '..KWWWWK..', + '..KWWWWK..', + '..KWWWWK..', + '..KWWWWK..', + '..KKKKKK..', + '..........', + '..........', + ], + colors, + ), + 'easy', + 'easy', + ], + [ + // The brackets surround the letter but don't touch it, so they aren't its backing. + 'light-gray brackets around a black letter', + draw( + [ + '..........', + '.GG....GG.', + '.G......G.', + '.G..KK..G.', + 'G..K..K..G', + 'G..KKKK..G', + '.G.K..K.G.', + '.G......G.', + '.GG....GG.', + '..........', + ], + colors, + ), + 'partly', + 'partly', + ], + [ + 'logo on a white badge, beside a light-gray part', + draw( + [ + '.WWWW.....', + 'WWKKWW....', + 'WKKKKW....', + 'WWKKWW....', + '.WWWW.....', + '..........', + '..........', + '.......GGG', + '.......GGG', + '..........', + ], + colors, + ), + 'partly', + 'easy', + ], + [ + // The orange square is 2.5:1 on the light background, but it is the figure's own. + 'white figure on its own orange square', + draw( + [ + 'OOOOOOOOOO', + 'OOOOOOOOOO', + 'OOWWWWWWOO', + 'OWWWWWWWWO', + 'OWWWWWWWWO', + 'OWWWWWWWWO', + 'OOWOOOWOOO', + 'OOWOOOWOOO', + 'OOOOOOOOOO', + 'OOOOOOOOOO', + ], + { ...colors, O: [212, 133, 47, 255] }, + ), + 'easy', + 'easy', + ], + [ + // A white logo made for dark backgrounds, with a soft dark glow: the logo vanishes in light + // mode and only the faint glow is left. + 'white logo with a 30% black glow', + draw( + [ + '..........', + '.gggggggg.', + '.gWWWWWWg.', + '.gWWWWWWg.', + '.gWWWWWWg.', + '.gWWWWWWg.', + '.gWWWWWWg.', + '.gWWWWWWg.', + '.gggggggg.', + '..........', + ], + { ...colors, g: [0, 0, 0, 77] }, + ), + 'wcag', + 'easy', + ], + [ + 'photo of two halves with rounded corners', + draw( + [ + '.KKKKKKKK.', + ...Array(4).fill('KKKKKKKKKK'), + ...Array(4).fill('GGGGGGGGGG'), + '.GGGGGGGG.', + ], + colors, + ), + 'easy', + 'easy', + ], + [ + // 3% is 3 pixels here. + 'light-gray part under 3%', + draw( + ['KKK.......', ...Array(8).fill('..........'), '........GG'], + colors, + ), + 'easy', + 'hard', + ], + [ + // Corners touching still join pixels into one part. + 'light-gray part of 3%, joined at the corners', + draw( + [ + 'KKK.......', + ...Array(6).fill('..........'), + '.......G..', + '........G.', + '.........G', + ], + colors, + ), + 'partly', + 'partly', + ], + [ + 'light-gray part under half opaque', + draw( + ['KKK.......', ...Array(8).fill('..........'), '.......ggg'], + colors, + ), + 'easy', + 'partly', + ], + ]; + + for (const [name, pixels, inLight, inDark] of cases) { + assert.equal(visibility(pixels, light), inLight, `${name}, light`); + assert.equal(visibility(pixels, dark), inDark, `${name}, dark`); + } +}); + +await test('shrinks an image by its most opaque pixels, so thin lines keep their color', () => { + // 4×4 shrunk by 2: a one-pixel dark line in the top-left block, a translucent area in the + // top-right, nothing below. + const fine = new Uint8ClampedArray(64); + fine.set([80, 80, 80, 255], 0); + fine.set([0, 0, 0, 77], 3 * 4); + fine.set([0, 0, 0, 40], 2 * 4); + assert.deepEqual( + [...mostOpaque(fine, 2)], + [80, 80, 80, 255, 0, 0, 0, 77, 0, 0, 0, 0, 0, 0, 0, 0], + ); +}); + +await test('preview tiles get the regular light and dark backgrounds, never an event theme', () => { + const scoped = [ + ...readFileSync( + new URL('../../resources/css/app.css', import.meta.url), + 'utf8', + ).matchAll(/([^{}]*data-theme-scope[^{}]*)\{([^{}]*)\}/g), + ]; + assert.deepEqual( + scoped.map(([, , body]) => /--muted:\s*([^;]+);/.exec(body)?.[1]), + [light, dark], + ); + assert.doesNotMatch( + scoped.map(([, selector]) => selector).join(), + /data-event-theme/, + ); +}); diff --git a/tests/Unit/ImageContrastPreview.test.tsx b/tests/Unit/ImageContrastPreview.test.tsx new file mode 100644 index 000000000..5f3bae4cd --- /dev/null +++ b/tests/Unit/ImageContrastPreview.test.tsx @@ -0,0 +1,134 @@ +/// +import assert from 'node:assert/strict'; +import * as React from 'react'; +import type { ReactElement, ReactNode } from 'react'; +import { test, vi } from 'vite-plus/test'; + +// Each tile renders on its own, so one hook store stands in for React's. +const tileNode = {}; +let state: unknown[]; +let cursor = 0; +vi.doMock('react', () => ({ + ...React, + useRef: () => ({ current: tileNode }), + useState: (initial: unknown) => { + const index = cursor++; + if (!(index in state)) state[index] = initial; + return [ + state[index], + (value: unknown) => { + state[index] = value; + }, + ]; + }, +})); + +// Reading pixels needs a canvas, so the icon is given: a dark logo on a transparent background. +const pixels = new Uint8ClampedArray(400); +for (let i = 0; i < 30; i++) pixels.set([0, 0, 0, 255], i * 4); +const readPixels = vi.fn((_image: unknown, _size: number) => pixels); +vi.doMock('../../resources/js/lib/image-contrast', async () => ({ + ...(await vi.importActual('../../resources/js/lib/image-contrast')), + readPixels, +})); + +// Each tile's own --muted, as its data-theme-scope gives it. +const muted = { light: '#eef0f2', dark: '#232326' }; +let theme: 'light' | 'dark'; +const getComputedStyle = vi.fn((_element: unknown) => ({ + getPropertyValue: () => ` ${muted[theme]} `, +})); +vi.stubGlobal('getComputedStyle', getComputedStyle); + +const { ImageContrastPreview } = + await import('../../resources/js/components/image-contrast-preview'); + +type Element = ReactElement>; +function elements(node: ReactNode): Element[] { + if (!React.isValidElement(node)) return []; + const element = node as Element; + return [ + element, + ...React.Children.toArray(element.props.children as ReactNode).flatMap( + elements, + ), + ]; +} +function text(node: ReactNode): string { + if (typeof node === 'string') return node; + return elements(node) + .flatMap((element) => + React.Children.toArray(element.props.children as ReactNode), + ) + .filter((child) => typeof child === 'string') + .join(' '); +} + +// One mode's tile, before or after its image loads. +function tile(mode: 'light' | 'dark', load: boolean) { + theme = mode; + state = []; + const element = elements( + ImageContrastPreview({ src: 'blob:icon', size: 20 }), + ).find((candidate) => candidate.props.theme === mode)!; + const render = () => { + cursor = 0; + return (element.type as (props: unknown) => Element)(element.props); + }; + if (load) { + const image = elements(render()).find((e) => e.type === 'img')!; + (image.props.onLoad as (event: unknown) => void)({ currentTarget: {} }); + } + const root = render(); + return { + text: text(root), + warns: String(root.props.className).includes('--destructive'), + }; +} + +test('shows no status until the image loads', () => { + assert.deepEqual(tile('dark', false), { text: 'Dark mode', warns: false }); +}); + +test('marks only the mode where the icon is hard to see', () => { + assert.deepEqual(tile('dark', true), { + text: 'Dark mode Hard to see', + warns: true, + }); + assert.deepEqual(tile('light', true), { + text: 'Light mode Easy to see', + warns: false, + }); + // Judged at the size the caller shows it, against the tile's own --muted, not the page's. + assert.equal(readPixels.mock.calls.at(-1)?.[1], 20); + assert.equal(getComputedStyle.mock.calls.at(-1)?.[0], tileNode); +}); + +test('marks a mode where only part of the icon is hard to see', () => { + // The dark logo with a light-gray part apart from it, which vanishes in light mode. + const twoParts = pixels.slice(); + for (let i = 70; i < 100; i++) twoParts.set([235, 235, 235, 255], i * 4); + readPixels.mockImplementationOnce(() => twoParts); + assert.deepEqual(tile('light', true), { + text: 'Light mode Partly hard to see', + warns: true, + }); +}); + +test('says when an icon is only short of the WCAG minimum', () => { + // An orange logo: 2:1 on the light background, short of WCAG's 3:1. + const orange = new Uint8ClampedArray(400); + for (let i = 0; i < 30; i++) orange.set([255, 138, 76, 255], i * 4); + readPixels.mockImplementationOnce(() => orange); + assert.deepEqual(tile('light', true), { + text: 'Light mode Hard to see (WCAG)', + warns: true, + }); +}); + +test('shows no status for an image whose pixels the browser will not let it read', () => { + readPixels.mockImplementationOnce(() => { + throw new DOMException('The canvas has been tainted', 'SecurityError'); + }); + assert.deepEqual(tile('dark', true), { text: 'Dark mode', warns: false }); +});