An open source design system that's fully customizable and agent ready
TypeScript
[Component Audit] FieldStatus: long validation messages wrap inside narrow fields (#9126)
Cindy Zhang941ad9648882
diff --git a/.changeset/field-status-long-token-wrap.md b/.changeset/field-status-long-token-wrap.mdnew file mode 100644index 0000000000..279af5e550--- /dev/null+++ b/.changeset/field-status-long-token-wrap.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] FieldStatus wraps a long unbroken word in a validation message, such as an email address or URL echoed from the field, inside the message box instead of painting it past the field's edge where its end could not be read.++@cixzhangdiff --git a/apps/storybook/stories/FieldStatus.stories.tsx b/apps/storybook/stories/FieldStatus.stories.tsxindex d2625dee07..505dd72c1d 100644--- a/apps/storybook/stories/FieldStatus.stories.tsx+++ b/apps/storybook/stories/FieldStatus.stories.tsx@@ -3,7 +3,7 @@/*** @file FieldStatus.stories.tsx* @input FieldStatus from @astryxdesign/core- * @output Stable visual coverage for status tones and variants+ * @output Stable visual coverage for status tones and variants, plus the audit matrix (every tone in both presentations and wrapping content)* @position Core component stories and visual regression coverage*/@@ -38,3 +38,104 @@ export const Variants: Story = {</Stack>),};++const STATUS_TYPES = ['error', 'warning', 'success'] as const;+const PRESENTATIONS = ['attached', 'detached'] as const;++const STATUS_MESSAGES = {+ error: 'This field is required',+ warning: 'This value may be visible to others',+ success: 'Your changes were saved',+} as const;++// A validation message that echoes the value the person typed. The address is+// one unbroken token, so it can only fit a narrow field if the message wraps+// inside it.+const LONG_TOKEN_MESSAGE =+ 'Enter a valid address: [email protected] is not recognised';++const LONG_PROSE_MESSAGE =+ 'Passwords must be at least twelve characters long and include a mix of letters, numbers, and symbols so that they are hard to guess.';++const matrixStyle = {+ display: 'grid',+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(100%, 240px), 1fr))',+ gap: 16,+ width: '100%',+ padding: 16,+ boxSizing: 'border-box',+} as const;++const columnStyle = {+ display: 'flex',+ flexDirection: 'column',+ gap: 12,+ minWidth: 0,+} as const;++const narrowColumnStyle = {...columnStyle, maxWidth: 240} as const;++// A flex row sizes its items from their min-content width, the way a+// horizontal form row or an inline toolbar would.+const rowStyle = {display: 'flex', minWidth: 0} as const;++/**+ * Every status tone in both presentations, plus wrapping content in a narrow+ * container: a long sentence, a message carrying one long unbroken token, an+ * empty message, and the long-token message as an item of a flex row.+ */+export const AuditMatrix: Story = {+ render: () => (+ <div style={matrixStyle}>+ {PRESENTATIONS.map(variant => (+ <div key={variant} style={columnStyle}>+ {STATUS_TYPES.map(type => (+ <FieldStatus+ key={type}+ type={type}+ variant={variant}+ message={STATUS_MESSAGES[type]}+ data-audit-case={`${variant}-${type}`}+ />+ ))}+ </div>+ ))}+ <div style={narrowColumnStyle}>+ {PRESENTATIONS.map(variant => (+ <FieldStatus+ key={`${variant}-prose`}+ type="warning"+ variant={variant}+ message={LONG_PROSE_MESSAGE}+ data-audit-case={`${variant}-long-prose`}+ />+ ))}+ {PRESENTATIONS.map(variant => (+ <FieldStatus+ key={`${variant}-token`}+ type="error"+ variant={variant}+ message={LONG_TOKEN_MESSAGE}+ data-audit-case={`${variant}-long-token`}+ />+ ))}+ {PRESENTATIONS.map(variant => (+ <FieldStatus+ key={`${variant}-empty`}+ type="success"+ variant={variant}+ message=""+ data-audit-case={`${variant}-empty`}+ />+ ))}+ <div style={rowStyle}>+ <FieldStatus+ type="error"+ message={LONG_TOKEN_MESSAGE}+ data-audit-case="attached-long-token-in-row"+ />+ </div>+ </div>+ </div>+ ),+};diff --git a/packages/core/src/FieldStatus/FieldStatus.tsx b/packages/core/src/FieldStatus/FieldStatus.tsxindex 52f40138db..3307dc4734 100644--- a/packages/core/src/FieldStatus/FieldStatus.tsx+++ b/packages/core/src/FieldStatus/FieldStatus.tsx@@ -63,6 +63,10 @@ const styles = stylex.create({fontFamily: typographyVars['--font-family-body'],fontSize: typeScaleVars['--text-supporting-size'],lineHeight: typeScaleVars['--text-supporting-leading'],+ // A validation message often echoes the value that failed (an address, a+ // URL). Let such an unbroken token wrap inside the field instead of+ // painting past its edges (WCAG 2.2 SC 1.4.10 Reflow).+ overflowWrap: 'anywhere',},attached: {marginTop: `calc(-1 * ${ATTACHED_OVERLAP})`,@@ -118,6 +122,9 @@ const colorStyles = stylex.create({export type FieldStatusVariant = keyof FieldStatusVariantMap;export interface FieldStatusProps extends BaseProps<HTMLDivElement> {+ /**+ * Ref to the rendered message box.+ */ref?: React.Ref<HTMLDivElement>;/*** The type of status to display.diff --git a/packages/core/src/FieldStatus/__tests__/FieldStatusAudit.a11y.chromium.spec.ts b/packages/core/src/FieldStatus/__tests__/FieldStatusAudit.a11y.chromium.spec.tsnew file mode 100644index 0000000000..ccf8ffb9c1--- /dev/null+++ b/packages/core/src/FieldStatus/__tests__/FieldStatusAudit.a11y.chromium.spec.ts@@ -0,0 +1,477 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y audit FieldStatus++/**+ * @file FieldStatusAudit.a11y.chromium.spec.ts+ * @input Exact-head FieldStatus audit matrix across themes, modes, direction, viewport, and forced colors+ * @output Screenshots and fail-closed sensor receipts for the FieldStatus whole-component audit+ * @position Component-owned Night Watch browser evidence; CI runs it only for a FieldStatus audit pull request+ */++import {createHash} from 'node:crypto';+import {execFileSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {expect, test, type Page} from '@playwright/test';+import {holdMotionStill} from '@astryxdesign/a11y-spec/chromium';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++const OUTPUT = path.resolve('field-status-audit-evidence');+const STORY_ID = 'core-fieldstatus--audit-matrix';+const WIDE = {width: 1024, height: 900};+const NARROW = {width: 320, height: 1400};++type Mode = 'light' | 'dark';+type Direction = 'ltr' | 'rtl';+type Theme = 'neutral' | 'butter';++type AuditCase = {+ key: string;+ mode: Mode;+ direction: Direction;+ theme: Theme;+ viewport: {width: number; height: number};+ forcedColors: boolean;+};++type AuditReceipt = {+ passed: boolean;+ expected: Record<string, unknown>;+ failures: string[];+};++const EXPECTED_CASES = [+ 'attached-error',+ 'attached-warning',+ 'attached-success',+ 'detached-error',+ 'detached-warning',+ 'detached-success',+ 'attached-long-prose',+ 'detached-long-prose',+ 'attached-long-token',+ 'detached-long-token',+ 'attached-empty',+ 'detached-empty',+ 'attached-long-token-in-row',+];++const cases: AuditCase[] = [];+function addPair(+ key: string,+ options: Partial<Omit<AuditCase, 'key' | 'mode'>> = {},+) {+ for (const mode of ['light', 'dark'] as const) {+ cases.push({+ key: `${key}-${mode}`,+ mode,+ direction: options.direction ?? 'ltr',+ theme: options.theme ?? 'neutral',+ viewport: options.viewport ?? WIDE,+ forcedColors: options.forcedColors ?? false,+ });+ }+}++addPair('default');+addPair('custom-theme', {theme: 'butter'});+addPair('rtl', {direction: 'rtl'});+addPair('narrow', {viewport: NARROW});+addPair('forced-colors', {forcedColors: true});++test.describe.configure({mode: 'serial', retries: 0});+let server: StaticServer;+let checkoutSha: string;+let storybookSha: string;++function storyUrl(item: AuditCase) {+ return `${server.origin}/iframe.html?id=${STORY_ID}&viewMode=story&globals=colorMode:${item.mode};astryxTheme:${item.theme};direction:${item.direction}`;+}++async function settle(page: Page) {+ await holdMotionStill(page);+ await page.evaluate(async () => document.fonts.ready);+ await page.evaluate(+ async () =>+ new Promise<void>(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(() => resolve())),+ ),+ );+ await page.waitForTimeout(40);+}++async function observe(page: Page) {+ return page.evaluate((expectedCases: string[]) => {+ type Rgba = {r: number; g: number; b: number; a: number};+ function parseColor(color: string): Rgba | null {+ const match = color.match(/rgba?\(([^)]+)\)/);+ if (!match) {+ return null;+ }+ const [r, g, b, a = 1] = match[1]+ .split(/[\s,/]+/)+ .filter(Boolean)+ .map(Number);+ return {r, g, b, a};+ }+ function over(top: Rgba, bottom: Rgba): Rgba {+ return {+ r: top.r * top.a + bottom.r * (1 - top.a),+ g: top.g * top.a + bottom.g * (1 - top.a),+ b: top.b * top.a + bottom.b * (1 - top.a),+ a: 1,+ };+ }+ // The painted backdrop behind an element: its own fill composited over+ // every translucent ancestor fill down to the first opaque one (or the+ // white canvas when none is opaque).+ function backdrop(element: Element): Rgba {+ const layers: Rgba[] = [];+ for (+ let node: Element | null = element;+ node != null;+ node = node.parentElement+ ) {+ const color = parseColor(getComputedStyle(node).backgroundColor);+ if (color != null && color.a > 0) {+ layers.push(color);+ if (color.a >= 1) {+ break;+ }+ }+ }+ let result: Rgba = {r: 255, g: 255, b: 255, a: 1};+ for (const layer of layers.reverse()) {+ result = over(layer, result);+ }+ return result;+ }+ function luminance({r, g, b}: Rgba): number {+ const [lr, lg, lb] = [r, g, b].map(channel => {+ const c = channel / 255;+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;+ });+ return 0.2126 * lr + 0.7152 * lg + 0.0722 * lb;+ }+ function contrast(element: Element): number | null {+ const fg = parseColor(getComputedStyle(element).color);+ if (fg == null) {+ return null;+ }+ const bg = backdrop(element);+ const a = luminance(over(fg, bg));+ const b = luminance(bg);+ const [hi, lo] = a > b ? [a, b] : [b, a];+ return Math.round(((hi + 0.05) / (lo + 0.05)) * 100) / 100;+ }++ const boxes = Array.from(+ document.querySelectorAll<HTMLElement>('.astryx-field-status'),+ ).map(box => {+ const style = getComputedStyle(box);+ const rect = box.getBoundingClientRect();+ const column = box.parentElement?.getBoundingClientRect();+ const icons = Array.from(+ box.querySelectorAll<HTMLElement>('.astryx-field-status-icon'),+ );+ const icon = icons[0] ?? null;+ const iconRect = icon?.getBoundingClientRect() ?? null;+ const textNode =+ box.getAttribute('data-variant') === 'detached'+ ? (box.firstElementChild?.lastElementChild as HTMLElement | null)+ : box;+ const textRange = document.createRange();+ if (textNode) {+ textRange.selectNodeContents(textNode);+ }+ const lineRects = Array.from(textRange.getClientRects());+ const firstLine = lineRects[0] ?? null;+ const textRect = textRange.getBoundingClientRect();+ return {+ auditCase: box.getAttribute('data-audit-case'),+ type: box.getAttribute('data-type'),+ variant: box.getAttribute('data-variant'),+ role: box.getAttribute('role'),+ ariaLive: box.getAttribute('aria-live'),+ ariaHidden: box.getAttribute('aria-hidden'),+ text: box.textContent,+ iconCount: icons.length,+ iconHidden: icon ? icon.closest('[aria-hidden="true"]') != null : null,+ iconBeforeText:+ icon && textNode+ ? Boolean(+ icon.compareDocumentPosition(textNode) &+ Node.DOCUMENT_POSITION_FOLLOWING,+ )+ : null,+ iconOnFirstLine:+ iconRect && firstLine+ ? iconRect.top + iconRect.height / 2 >= firstLine.top - 1 &&+ iconRect.top + iconRect.height / 2 <= firstLine.bottom + 1+ : null,+ lines: lineRects.length,+ boxInlineOverflow: box.scrollWidth > box.clientWidth + 1,+ textInlineOverflow:+ lineRects.length > 0 &&+ (textRect.left < rect.left - 1 || textRect.right > rect.right + 1),+ escapesColumn: column+ ? rect.left < column.left - 1 || rect.right > column.right + 1+ : null,+ outlineStyle: style.outlineStyle,+ color: style.color,+ backgroundColor: style.backgroundColor,+ contrast: contrast(box),+ compositedBackground: (() => {+ const bg = backdrop(box);+ return `rgb(${Math.round(bg.r)}, ${Math.round(bg.g)}, ${Math.round(bg.b)})`;+ })(),+ fontSize: style.fontSize,+ geometry: {+ x: Math.round(rect.x * 10) / 10,+ y: Math.round(rect.y * 10) / 10,+ width: Math.round(rect.width * 10) / 10,+ height: Math.round(rect.height * 10) / 10,+ },+ };+ });+ const root = document.querySelector<HTMLElement>('.astryx-field-status');+ return {+ theme: document+ .querySelector('[data-astryx-theme]')+ ?.getAttribute('data-astryx-theme'),+ mode: document.documentElement.getAttribute('data-theme'),+ direction: root ? getComputedStyle(root).direction : null,+ viewport: {width: innerWidth, height: innerHeight},+ dpr: devicePixelRatio,+ reducedMotion: matchMedia('(prefers-reduced-motion: reduce)').matches,+ forcedColors: matchMedia('(forced-colors: active)').matches,+ documentOverflow: document.documentElement.scrollWidth > innerWidth + 1,+ fonts: document.fonts.status,+ runningAnimations: document+ .getAnimations()+ .filter(animation => animation.playState === 'running').length,+ storybookError:+ document.querySelector('.sb-show-errordisplay') != null ||+ document.body.classList.contains('sb-show-errordisplay'),+ cases: boxes.map(box => box.auditCase),+ expectedCases,+ boxes,+ };+ }, EXPECTED_CASES);+}++test.beforeAll(async () => {+ fs.rmSync(OUTPUT, {recursive: true, force: true});+ fs.mkdirSync(OUTPUT, {recursive: true});+ checkoutSha = execFileSync('git', ['rev-parse', 'HEAD'], {+ encoding: 'utf8',+ }).trim();+ const expected = process.env.ASTRYX_HEAD_SHA;+ if (expected && expected !== checkoutSha) {+ throw new Error(+ `checkout ${checkoutSha} does not match expected head ${expected}`,+ );+ }+ server = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+ const response = await fetch(`${server.origin}/astryx-build-sha.txt`);+ if (!response.ok) {+ throw new Error(`Storybook build has no SHA stamp (${response.status})`);+ }+ storybookSha = (await response.text()).trim();+ if (storybookSha !== checkoutSha) {+ throw new Error(+ `Storybook ${storybookSha} does not match checkout ${checkoutSha}`,+ );+ }+});++test.afterAll(async () => {+ await server?.close();+});++for (const item of cases) {+ test(item.key, async ({browser}) => {+ const context = await browser.newContext({+ viewport: item.viewport,+ deviceScaleFactor: 1,+ colorScheme: item.mode,+ reducedMotion: 'reduce',+ forcedColors: item.forcedColors ? 'active' : 'none',+ });+ const page = await context.newPage();+ const pageErrors: string[] = [];+ page.on('pageerror', error => pageErrors.push(String(error)));+ await page.goto(storyUrl(item), {waitUntil: 'load'});+ await page.locator('#storybook-root').waitFor();+ await expect(page.locator('.astryx-field-status')).toHaveCount(+ EXPECTED_CASES.length,+ );++ await settle(page);+ const first = await observe(page);+ await page.waitForTimeout(100);+ await settle(page);+ const observed = await observe(page);+ const geometryStable =+ JSON.stringify(first.boxes.map(box => box.geometry)) ===+ JSON.stringify(observed.boxes.map(box => box.geometry));++ const failures: string[] = [];+ const check = (condition: boolean, message: string) => {+ if (!condition) {+ failures.push(message);+ }+ };+ check(storybookSha === checkoutSha, 'storybook build mismatch');+ check(pageErrors.length === 0, `page errors: ${pageErrors.join(' | ')}`);+ check(!observed.storybookError, 'storybook error display');+ check(observed.theme === item.theme, `theme ${observed.theme}`);+ check(observed.mode === item.mode, `mode ${observed.mode}`);+ check(+ observed.direction === item.direction,+ `direction ${observed.direction}`,+ );+ check(+ observed.viewport.width === item.viewport.width &&+ observed.viewport.height === item.viewport.height,+ 'viewport mismatch',+ );+ check(observed.dpr === 1, `dpr ${observed.dpr}`);+ check(observed.reducedMotion, 'reduced motion not applied');+ check(+ observed.forcedColors === item.forcedColors,+ `forced colors ${observed.forcedColors}`,+ );+ check(observed.fonts === 'loaded', `fonts ${observed.fonts}`);+ check(observed.runningAnimations === 0, 'animations still running');+ check(geometryStable, 'geometry changed between samples');+ check(+ JSON.stringify(observed.cases) === JSON.stringify(EXPECTED_CASES),+ `cases ${observed.cases.join(',')}`,+ );+ for (const box of observed.boxes) {+ const id = box.auditCase ?? 'unknown';+ const [variant] = id.split('-');+ // Only the empty fixtures may measure no text line; everywhere else a+ // missing line means the text was not found, so the line-based checks+ // below cannot pass vacuously.+ const isEmpty = id.endsWith('-empty');+ check(+ isEmpty ? box.lines === 0 : box.lines > 0,+ `${id}: ${box.lines} text lines`,+ );+ check(box.variant === variant, `${id}: data-variant ${box.variant}`);+ check(+ box.role == null && box.ariaLive == null && box.ariaHidden == null,+ `${id}: box carries role, aria-live, or aria-hidden`,+ );+ if (variant === 'detached') {+ check(box.iconCount === 1, `${id}: ${box.iconCount} status glyphs`);+ check(box.iconHidden === true, `${id}: status glyph exposed to AT`);+ check(box.iconBeforeText === true, `${id}: glyph not before text`);+ // An empty message has no text line to align to.+ if (!isEmpty) {+ check(+ box.iconOnFirstLine === true,+ `${id}: glyph not aligned to first line`,+ );+ }+ } else {+ check(box.iconCount === 0, `${id}: attached box renders a glyph`);+ }+ check(!box.boxInlineOverflow, `${id}: message overflows its box`);+ check(!box.textInlineOverflow, `${id}: text paints outside its box`);+ check(box.escapesColumn === false, `${id}: box escapes its container`);+ // WCAG 2.2 SC 1.4.3: 12px supporting text needs 4.5:1 against the+ // composited fill it is painted on.+ check(+ box.contrast != null && box.contrast >= 4.5,+ `${id}: text contrast ${box.contrast}`,+ );+ if (item.forcedColors) {+ check(box.outlineStyle === 'solid', `${id}: no forced-colors boundary`);+ }+ }+ check(!observed.documentOverflow, 'document scrolls horizontally');++ const png = await page.screenshot({animations: 'disabled', fullPage: true});+ check(png.length > 1000, 'screenshot is empty');+ const image = `${item.key}.png`;+ const receipt = {+ schemaVersion: 1,+ expected: {+ build: checkoutSha,+ storyId: STORY_ID,+ mode: item.mode,+ direction: item.direction,+ theme: item.theme,+ viewport: item.viewport,+ forcedColors: item.forcedColors,+ cases: EXPECTED_CASES,+ reflow:+ 'no message overflows its box, no box escapes its container, no document horizontal scroll',+ },+ observed: {+ build: storybookSha,+ ...observed,+ geometryStable,+ pageErrors,+ },+ image: {+ file: image,+ sha256: createHash('sha256').update(png).digest('hex'),+ width: png.readUInt32BE(16),+ height: png.readUInt32BE(20),+ },+ failures,+ passed: failures.length === 0,+ };+ fs.writeFileSync(path.join(OUTPUT, image), png);+ fs.writeFileSync(+ path.join(OUTPUT, `${item.key}.sensors.json`),+ `${JSON.stringify(receipt, null, 2)}\n`,+ );+ await context.close();+ });+}++test('manifest is complete', async () => {+ const receiptFiles = fs+ .readdirSync(OUTPUT)+ .filter(file => file.endsWith('.sensors.json'));+ const receipts = receiptFiles.map(+ (file): AuditReceipt =>+ JSON.parse(+ fs.readFileSync(path.join(OUTPUT, file), 'utf8'),+ ) as AuditReceipt,+ );+ fs.writeFileSync(+ path.join(OUTPUT, 'manifest.json'),+ `${JSON.stringify(+ {+ schemaVersion: 1,+ component: 'core/FieldStatus',+ build: checkoutSha,+ frames: cases.map(item => ({+ key: item.key,+ image: `${item.key}.png`,+ receipt: `${item.key}.sensors.json`,+ })),+ },+ null,+ 2,+ )}\n`,+ );+ expect(receiptFiles).toHaveLength(cases.length);+ expect(+ receipts+ .filter(receipt => !receipt.passed)+ .map(receipt => ({frame: receipt.expected, failures: receipt.failures})),+ ).toEqual([]);+});