Skip to content
Open
Show file tree
Hide file tree
Changes from 4 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
7 changes: 7 additions & 0 deletions .changeset/code-inherit-in-media-surface.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@astryxdesign/core': patch
---

[fix] `<Code color="inherit">` on an inverted surface, such as in a Toast, now reads in every theme. Inline code keeps the page's chip there, so inherited code text takes the chip's own text color instead of the surface's, which drew dark text on a dark chip in Gothic.
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved

@cixzhang
51 changes: 51 additions & 0 deletions apps/storybook/stories/Code.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ import {Code} from '@astryxdesign/core/Code';
import {Text} from '@astryxdesign/core/Text';
import {Stack} from '@astryxdesign/core/Stack';
import {Link} from '@astryxdesign/core/Link';
import {MediaTheme} from '@astryxdesign/core/theme';
import {useToast} from '@astryxdesign/core/Toast';
import {useEffect} from 'react';

const meta: Meta<typeof Code> = {
title: 'Core/Code',
Expand Down Expand Up @@ -230,3 +233,51 @@ export const TextSizes: Story = {
expect(new Set(fontSizes).size).toBeGreaterThan(1);
},
};

/**
* Inline code on an inverted surface, as in a Toast: the chip keeps the
* page's look, and `color="inherit"` takes the chip's own primary text.
*/
export const InMediaSurface: Story = {
render: () => (
<div
style={{
backgroundColor: 'var(--color-background-inverted)',
padding: 16,
borderRadius: 8,
}}>
<MediaTheme mode="auto">
<Text>
Run <Code>pnpm build</Code>, then{' '}
<Code color="inherit">pnpm test</Code>
</Text>
</MediaTheme>
</div>
),
};

/**
* The same inline code in a Toast, whose card applies its own media side.
*/
export const InToast: Story = {
// A toast that stays up would cover the docs page, so it shows only here.
tags: ['!autodocs'],
render: function InToastStory() {
const toast = useToast();
useEffect(
() =>
toast({
body: (
<Text>
Run <Code>pnpm build</Code>, then{' '}
<Code color="inherit">pnpm test</Code>
</Text>
),
isAutoHide: false,
uniqueID: 'code-in-toast',
}),
[toast],
);
return <Text>A toast holds the code.</Text>;
},
};
36 changes: 18 additions & 18 deletions docs/specs/components/Code/Code.spec.md

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions docs/specs/components/theme/MediaTheme.spec.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ Consumer migration instructions belong in consumer docs and release notes.

- The wrapper, its surface marker, and resolving `auto` with `fallback`
(FR1–FR3).
- The internal StyleX marker the wrapper carries
(`theme/mediaSurface.stylex.ts`), so a component inside a media surface
styles itself for it with `stylex.when.ancestor`; inline code uses it
(`component:Code` FR2).

**Does not own / non-goals**

Expand Down
9 changes: 8 additions & 1 deletion packages/core/src/Code/Code.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
import {mergeProps} from '../utils';
import type {BaseProps} from '../BaseProps';
import {themeProps} from '../utils/themeProps';
import {mediaSurfaceMarker} from '../theme/mediaSurface.stylex';

const styles = stylex.create({
base: {
Expand All @@ -49,8 +50,14 @@ const colorStyles = stylex.create({
secondary: {
color: colorVars['--color-text-secondary'],
},
// Inline code keeps the page's chip in a media surface, so inherited text
// there takes the chip's own primary text, not the surface's.
inherit: {
color: 'inherit',
color: {
default: 'inherit',
[stylex.when.ancestor('[data-astryx-media]', mediaSurfaceMarker)]:
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
colorVars['--color-text-primary'],
},
},
});

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,179 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
// @pr-a11y scope ^packages/core/src/theme/ ^packages/themes/
/**
* @file CodeInMediaSurface.a11y.chromium.spec.ts
* @input The built `Core/Code` InMediaSurface and InToast stories in every shipped theme and
* Core's base tokens, light and dark: default and `color="inherit"` inline
* code in Text on an inverted surface
* @output Chromium proof that each text part on the media surface, the code
* chips included, meets WCAG AA (4.5:1) against what it paints on
* @position Inline code keeps the page's chip in a media surface; inherited
* code text there takes the chip's own primary text.
*
* SYNC: Fixture lives in /apps/storybook/stories/Code.stories.tsx
* (InMediaSurface, InToast).
*/
import {expect, test, type Page} from '@astryxdesign/a11y-spec/playwright';
import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';
import {
DEFAULT_STORYBOOK_DIR,
serveStorybook,
type StaticServer,
} from '@astryxdesign/a11y-spec/storybook';

let storybook: StaticServer;

test.beforeAll(async () => {
storybook = await serveStorybook(
process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
);
});

test.afterAll(async () => {
await storybook?.close();
});

// A plain media surface, and a Toast, whose card applies its side itself.
const STORIES = ['core-code--in-media-surface', 'core-code--in-toast'];
// 'none' is Core's base tokens with no theme.
const SHIPPED_THEMES = [
'none',
'butter',
'chocolate',
'gothic',
'matcha',
'neutral',
'stone',
'y2k',
];
const MODES = ['light', 'dark'];

/** Each text part on a media surface that falls below 4.5:1. */
async function lowContrastParts(page: Page): Promise<string[]> {
return page.evaluate(() => {
const canvas = document.createElement('canvas').getContext('2d', {
willReadFrequently: true,
}) as CanvasRenderingContext2D;
type Rgba = [number, number, number, number];
const rgba = (color: string): Rgba => {
canvas.clearRect(0, 0, 1, 1);
canvas.fillStyle = color;
canvas.fillRect(0, 0, 1, 1);
const [r, g, b, a] = canvas.getImageData(0, 0, 1, 1).data;
return [r, g, b, a / 255];
};
const over = (top: Rgba, under: Rgba): Rgba => {
const a = top[3] + under[3] * (1 - top[3]);
const mix = (i: number) =>
a === 0
? 0
: (top[i] * top[3] + under[i] * under[3] * (1 - top[3])) / a;
return [mix(0), mix(1), mix(2), a];
};
const luminance = ([r, g, b]: Rgba) => {
const linear = (v: number) => {
const c = v / 255;
return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
};
const ratio = (a: Rgba, b: Rgba) => {
const [high, low] = [luminance(a), luminance(b)].sort((x, y) => y - x);
return (high + 0.05) / (low + 0.05);
};
const backdropOf = (element: Element): Rgba => {
const chain: Element[] = [];
for (
let node: Element | null = element;
node;
node = node.parentElement
) {
chain.unshift(node);
}
let background: Rgba = [255, 255, 255, 1];
for (const node of chain) {
background = over(
rgba(getComputedStyle(node).backgroundColor),
background,
);
}
return background;
};
const drawnColor = (element: Element, color: string, background: Rgba) => {
let opacity = 1;
for (
let node: Element | null = element;
node;
node = node.parentElement
) {
opacity *= Number(getComputedStyle(node).opacity);
}
const ink = rgba(color);
return over([ink[0], ink[1], ink[2], ink[3] * opacity], background);
};

const failures: string[] = [];
for (const tooltip of document.querySelectorAll('[data-astryx-media]')) {
const walker = document.createTreeWalker(tooltip, NodeFilter.SHOW_TEXT);
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
const text = node.textContent?.trim();
const element = node.parentElement;
if (!text || element == null) {
continue;
}
const background = backdropOf(element);
const drawn = drawnColor(
element,
getComputedStyle(element).color,
background,
);
const found = ratio(drawn, background);
if (found < 4.5) {
failures.push(`text "${text}": ${found.toFixed(2)}:1`);
}
}
for (const icon of tooltip.querySelectorAll('svg')) {
const background = backdropOf(icon);
const style = getComputedStyle(icon);
const paint =
style.fill !== 'none' && !style.fill.startsWith('url(')
? style.fill
: style.stroke !== 'none'
? style.stroke
: style.color;
const drawn = drawnColor(icon, paint, background);
const found = ratio(drawn, background);
if (found < 3) {
failures.push(`icon: ${found.toFixed(2)}:1`);
}
}
}
return failures;
});
}

for (const story of STORIES) {
for (const theme of SHIPPED_THEMES) {
test(`inline code reaches 4.5:1 in ${story} in ${theme}, light and dark`, async ({
page,
}) => {
const failures: string[] = [];
for (const mode of MODES) {
await page.goto(
`${storybook.origin}/iframe.html?id=${story}&viewMode=story&globals=astryxTheme:${theme};colorMode:${mode}`,
);
await holdMotionStill(page);
// A Toast's live region repeats its text, so wait on the code itself.
await expect(
page.locator('code', {hasText: 'pnpm test'}),
).toBeVisible();
failures.push(
...(await lowContrastParts(page)).map(
failure => `${mode}: ${failure}`,
),
);
}
expect(failures).toEqual([]);
});
}
}
7 changes: 6 additions & 1 deletion packages/core/src/theme/MediaTheme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {colorVars} from './tokens.stylex';
import {dataAttr} from '../naming';
import {useAutoMediaMode} from '../hooks/useAutoMediaMode';
import {MediaDarkPage, useMediaDarkPageAttribute} from './MediaDarkPage';
import {mediaSurfaceMarker} from './mediaSurface.stylex';

const styles = stylex.create({
root: {
Expand Down Expand Up @@ -111,7 +112,11 @@ export function MediaTheme({
ref={ref}
{...(resolved === 'off' ? null : {[dataAttr('media')]: resolved})}
{...(resolved === 'off' ? null : darkPage)}
{...stylex.props(styles.root, resolved !== 'off' && styles.active)}>
{...stylex.props(
mediaSurfaceMarker,
styles.root,
resolved !== 'off' && styles.active,
)}>
{/* Surfaces nested inside take their own sides. Always rendered, so
the children keep their place in the tree when the side clears. */}
<MediaDarkPage side={null}>{children}</MediaDarkPage>
Expand Down
19 changes: 19 additions & 0 deletions packages/core/src/theme/mediaSurface.stylex.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/**
* @file mediaSurface.stylex.ts
* @input StyleX markers
* @output Exports mediaSurfaceMarker
* @position Internal marker MediaTheme's element carries, so a component
* inside a media surface can style itself for it with
* `stylex.when.ancestor('[data-astryx-media]', mediaSurfaceMarker)`
*
* SYNC: When modified, update:
* - /packages/core/src/theme/MediaTheme.tsx
* - /packages/core/src/Code/Code.tsx
*/

import * as stylex from '@stylexjs/stylex';

export const mediaSurfaceMarker: ReturnType<typeof stylex.defineMarker> =
stylex.defineMarker();