Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat: add XDSThumbnail component (#1255)

Cindy Zhang728e74641c13
diff --git a/apps/sandbox/src/app/(sandbox)/pages/media-mode/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/media-mode/page.tsx
new file mode 100644
index 0000000000..cfb014fd68
--- /dev/null
+++ b/apps/sandbox/src/app/(sandbox)/pages/media-mode/page.tsx
@@ -0,0 +1,242 @@
+'use client';
+
+import {useState} from 'react';
+import {XDSHeading, XDSText} from '@xds/core/Text';
+import {XDSVStack, XDSHStack} from '@xds/core/Layout';
+import {XDSButton} from '@xds/core/Button';
+import {XDSIcon} from '@xds/core/Icon';
+import {XDSMediaTheme} from '@xds/core/theme';
+import {XDSDivider} from '@xds/core';
+import {useImageModeTest, type Algorithm} from './useImageModeTest';
+
+// =============================================================================
+// Algorithm metadata
+// =============================================================================
+
+const ALGO_INFO: Record<Algorithm, {label: string; description: string}> = {
+ gamma: {label: 'BT.709 Gamma', description: 'Luma on gamma-encoded sRGB, threshold 0.5. Fast but overestimates brightness of saturated colors.'},
+ wcag: {label: 'WCAG 2', description: 'sRGB linearization + BT.709 coefficients, threshold 0.18. Standard web accessibility formula.'},
+ apca: {label: 'APCA', description: 'sRGB linearization + perceptual power curve (Y^0.56), threshold 0.5. Best mid-tone discrimination. Targeting WCAG 3.'},
+};
+
+const ALGO_FN: Record<Algorithm, {fn: (r: number, g: number, b: number) => number; threshold: number}> = {
+ gamma: {
+ fn: (r, g, b) => (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255,
+ threshold: 0.5,
+ },
+ wcag: {
+ fn: (r, g, b) => {
+ const lin = (c: number) => { const v = c / 255; return v <= 0.04045 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
+ },
+ threshold: 0.18,
+ },
+ apca: {
+ fn: (r, g, b) => {
+ const lin = (c: number) => Math.pow(c / 255, 2.4);
+ return Math.pow(0.2126729 * lin(r) + 0.7151522 * lin(g) + 0.0721750 * lin(b), 0.56);
+ },
+ threshold: 0.5,
+ },
+};
+
+// =============================================================================
+// Test data
+// =============================================================================
+
+const SOLID_COLORS: Array<{name: string; rgb: [number, number, number]}> = [
+ {name: 'black', rgb: [0, 0, 0]},
+ {name: 'white', rgb: [255, 255, 255]},
+ {name: 'red', rgb: [255, 0, 0]},
+ {name: 'green', rgb: [0, 255, 0]},
+ {name: 'blue', rgb: [0, 0, 255]},
+ {name: 'yellow', rgb: [255, 255, 0]},
+ {name: 'cyan', rgb: [0, 255, 255]},
+ {name: 'magenta', rgb: [255, 0, 255]},
+ {name: 'mid-gray', rgb: [128, 128, 128]},
+ {name: 'dark-gray', rgb: [64, 64, 64]},
+ {name: 'light-gray', rgb: [192, 192, 192]},
+ {name: 'orange', rgb: [255, 165, 0]},
+ {name: 'navy', rgb: [0, 0, 128]},
+ {name: 'forest', rgb: [0, 100, 0]},
+ {name: 'maroon', rgb: [128, 0, 0]},
+ {name: 'teal', rgb: [0, 128, 128]},
+];
+
+const IMAGE_SWATCHES = [
+ {label: 'forest', src: 'https://picsum.photos/id/10/200/200'},
+ {label: 'laptop', src: 'https://picsum.photos/id/15/200/200'},
+ {label: 'clouds', src: 'https://picsum.photos/id/28/200/200'},
+ {label: 'water', src: 'https://picsum.photos/id/36/200/200'},
+ {label: 'door', src: 'https://picsum.photos/id/96/200/200'},
+ {label: 'bones', src: 'https://picsum.photos/id/106/200/200'},
+ {label: 'road', src: 'https://picsum.photos/id/136/200/200'},
+ {label: 'puppy', src: 'https://picsum.photos/id/237/200/200'},
+];
+
+const BUTTON_REGION = {x: 0.5, y: 0.06, width: 0.44, height: 0.44};
+
+// =============================================================================
+// Shared styles (inline to avoid stylex issues in sandbox)
+// =============================================================================
+
+const swatchBoxStyle: React.CSSProperties = {
+ position: 'relative',
+ width: 64,
+ height: 64,
+ borderRadius: 8,
+ overflow: 'hidden',
+ boxShadow: '0 1px 2px rgba(0,0,0,0.1)',
+};
+
+const buttonPosStyle: React.CSSProperties = {
+ position: 'absolute',
+ top: 4,
+ right: 4,
+};
+
+const gridStyle: React.CSSProperties = {
+ display: 'flex',
+ flexWrap: 'wrap',
+ gap: 12,
+};
+
+const swatchStyle: React.CSSProperties = {
+ textAlign: 'center',
+ width: 72,
+};
+
+// =============================================================================
+// Swatch components
+// =============================================================================
+
+function RemoveButton() {
+ return (
+ <XDSButton
+ icon={<XDSIcon icon="close" size="xsm" />}
+ label="Remove"
+ variant="secondary"
+ size="sm"
+ isIconOnly
+ style={{height: 20, minWidth: 20}}
+ onClick={() => {}}
+ />
+ );
+}
+
+function Swatch({color, mode, value}: {color: typeof SOLID_COLORS[0]; mode: 'dark' | 'light'; value: number}) {
+ return (
+ <div style={swatchStyle}>
+ <XDSMediaTheme mode={mode}>
+ <div style={{...swatchBoxStyle, backgroundColor: `rgb(${color.rgb.join(',')})`}}>
+ <div style={buttonPosStyle}>
+ <RemoveButton />
+ </div>
+ </div>
+ </XDSMediaTheme>
+ <div style={{fontSize: 10, color: '#666', marginTop: 4, fontWeight: 600}}>{color.name}</div>
+ <div style={{fontSize: 9, color: mode === 'dark' ? '#c44' : '#48a'}}>
+ {value.toFixed(3)} → {mode}
+ </div>
+ </div>
+ );
+}
+
+function ImageSwatch({src, label, algorithm}: {src: string; label: string; algorithm: Algorithm}) {
+ const {mode, value} = useImageModeTest(src, {region: BUTTON_REGION, algorithm});
+ return (
+ <div style={swatchStyle}>
+ {mode != null ? (
+ <XDSMediaTheme mode={mode}>
+ <div style={swatchBoxStyle}>
+ <img
+ src={src}
+ alt={label}
+ style={{width: '100%', height: '100%', objectFit: 'cover', display: 'block'}}
+ />
+ <div style={buttonPosStyle}>
+ <RemoveButton />
+ </div>
+ </div>
+ </XDSMediaTheme>
+ ) : (
+ <div style={swatchBoxStyle}>
+ <img
+ src={src}
+ alt={label}
+ style={{width: '100%', height: '100%', objectFit: 'cover', display: 'block'}}
+ />
+ <div style={buttonPosStyle}>
+ <RemoveButton />
+ </div>
+ </div>
+ )}
+ <div style={{fontSize: 10, color: '#666', marginTop: 4}}>{label}</div>
+ <div style={{fontSize: 9, color: mode === 'dark' ? '#c44' : mode === 'light' ? '#48a' : '#999'}}>
+ {value != null ? `${value.toFixed(3)} → ${mode}` : 'detecting…'}
+ </div>
+ </div>
+ );
+}
+
+// =============================================================================
+// Page
+// =============================================================================
+
+export default function MediaModePage() {
+ const [algo, setAlgo] = useState<Algorithm>('apca');
+ const info = ALGO_INFO[algo];
+ const config = ALGO_FN[algo];
+
+ return (
+ <XDSVStack gap={6} style={{maxWidth: 800}}>
+ <div>
+ <XDSHeading level={2}>Media Mode Comparison</XDSHeading>
+ <XDSText type="body" color="secondary">
+ Compare luminance algorithms for detecting dark vs light surfaces.
+ Used by useImageMode + XDSMediaTheme to adapt overlaid controls.
+ </XDSText>
+ </div>
+
+ <XDSHStack gap={2}>
+ {(Object.keys(ALGO_INFO) as Algorithm[]).map(id => (
+ <XDSButton
+ key={id}
+ label={ALGO_INFO[id].label}
+ variant={algo === id ? 'primary' : 'secondary'}
+ size="sm"
+ onClick={() => setAlgo(id)}
+ />
+ ))}
+ </XDSHStack>
+
+ <div style={{fontSize: 12, color: '#888'}}>{info.description}</div>
+
+ <XDSDivider />
+
+ <XDSHeading level={4}>Solid Colors</XDSHeading>
+
+ <div style={gridStyle}>
+ {SOLID_COLORS.map(c => {
+ const value = config.fn(...c.rgb);
+ const mode: 'dark' | 'light' = value > config.threshold ? 'light' : 'dark';
+ return <Swatch key={c.name} color={c} mode={mode} value={value} />;
+ })}
+ </div>
+
+ <XDSDivider />
+
+ <XDSHeading level={4}>Real Images</XDSHeading>
+ <div style={{fontSize: 12, color: '#888'}}>
+ Samples the upper-right corner where a remove button would sit.
+ Switch algorithms above — images re-detect with the selected algorithm.
+ </div>
+
+ <div style={gridStyle}>
+ {IMAGE_SWATCHES.map(img => (
+ <ImageSwatch key={`${img.label}-${algo}`} src={img.src} label={img.label} algorithm={algo} />
+ ))}
+ </div>
+ </XDSVStack>
+ );
+}
diff --git a/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts b/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts
new file mode 100644
index 0000000000..8745a5cde7
--- /dev/null
+++ b/apps/sandbox/src/app/(sandbox)/pages/media-mode/useImageModeTest.ts
@@ -0,0 +1,118 @@
+'use client';
+
+/**
+ * Test variant of useImageMode that supports multiple luminance algorithms.
+ * Used in the media mode comparison sandbox to evaluate which algorithm
+ * produces the best results before updating the core hook.
+ */
+
+import {useState, useEffect} from 'react';
+import type {ImageSampleRegion} from '@xds/core/hooks';
+
+export type Algorithm = 'gamma' | 'wcag' | 'apca';
+
+/** BT.709 luma on gamma-encoded sRGB (current useImageMode) */
+function gammaLuma(r: number, g: number, b: number): number {
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
+}
+
+/** WCAG 2 relative luminance with sRGB linearization */
+function wcagLuminance(r: number, g: number, b: number): number {
+ const lin = (c: number) => {
+ const s = c / 255;
+ return s <= 0.04045 ? s / 12.92 : Math.pow((s + 0.055) / 1.055, 2.4);
+ };
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
+}
+
+/** APCA perceptual lightness: linearize, compute Y, apply power curve */
+function apcaLightness(r: number, g: number, b: number): number {
+ const lin = (c: number) => Math.pow(c / 255, 2.4);
+ const y = 0.2126729 * lin(r) + 0.7151522 * lin(g) + 0.0721750 * lin(b);
+ return Math.pow(y, 0.56);
+}
+
+const ALGO_CONFIG: Record<Algorithm, {fn: (r: number, g: number, b: number) => number; threshold: number}> = {
+ gamma: {fn: gammaLuma, threshold: 0.5},
+ wcag: {fn: wcagLuminance, threshold: 0.18},
+ apca: {fn: apcaLightness, threshold: 0.5},
+};
+
+export interface UseImageModeTestOptions {
+ region?: ImageSampleRegion;
+ algorithm?: Algorithm;
+ fallback?: 'dark' | 'light' | null;
+}
+
+/**
+ * Like useImageMode but with a selectable algorithm.
+ * Returns {mode, value} so the UI can show the raw number.
+ */
+export function useImageModeTest(
+ src: string | null | undefined,
+ options: UseImageModeTestOptions = {},
+): {mode: 'dark' | 'light' | null; value: number | null} {
+ const {region, algorithm = 'gamma', fallback = null} = options;
+ const [result, setResult] = useState<{mode: 'dark' | 'light' | null; value: number | null}>({
+ mode: fallback,
+ value: null,
+ });
+
+ useEffect(() => {
+ if (!src) {
+ setResult({mode: fallback, value: null});
+ return;
+ }
+
+ let cancelled = false;
+ const config = ALGO_CONFIG[algorithm];
+
+ async function detect() {
+ try {
+ const response = await fetch(src!, {mode: 'cors'});
+ const blob = await response.blob();
+ const bitmap = await createImageBitmap(blob);
+
+ if (cancelled) return;
+
+ const sx = region ? Math.round(region.x * bitmap.width) : 0;
+ const sy = region ? Math.round(region.y * bitmap.height) : 0;
+ const sw = region ? Math.round(region.width * bitmap.width) : bitmap.width;
+ const sh = region ? Math.round(region.height * bitmap.height) : bitmap.height;
+
+ const sampleSize = 10;
+ const canvas = new OffscreenCanvas(sampleSize, sampleSize);
+ const ctx = canvas.getContext('2d');
+ if (!ctx) return;
+
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, sampleSize, sampleSize);
+ const imageData = ctx.getImageData(0, 0, sampleSize, sampleSize).data;
+
+ let totalR = 0, totalG = 0, totalB = 0;
+ const pixelCount = sampleSize * sampleSize;
+ for (let i = 0; i < imageData.length; i += 4) {
+ totalR += imageData[i];
+ totalG += imageData[i + 1];
+ totalB += imageData[i + 2];
+ }
+
+ if (cancelled) return;
+
+ const r = totalR / pixelCount;
+ const g = totalG / pixelCount;
+ const b = totalB / pixelCount;
+ const value = config.fn(r, g, b);
+ const mode = value > config.threshold ? 'light' : 'dark';
+
+ setResult({mode, value});
+ } catch {
+ if (!cancelled) setResult({mode: fallback, value: null});
+ }
+ }
+
+ detect();
+ return () => { cancelled = true; };
+ }, [src, region?.x, region?.y, region?.width, region?.height, algorithm, fallback]);
+
+ return result;
+}
diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.ts
index 41552be0ee..fb3d2b4aa9 100644
--- a/apps/sandbox/src/app/sandboxPages.ts
+++ b/apps/sandbox/src/app/sandboxPages.ts
@@ -144,6 +144,12 @@ export const categories: SandboxCategory[] = [
description:
'Template gallery with SideNav layout, AI chat, and resizable preview panel',
},
+ {
+ name: 'Media Mode',
+ href: '/pages/media-mode/',
+ description:
+ 'Compare luminance algorithms (BT.709 / WCAG 2 / APCA) for dark/light surface detection',
+ },
],
},
];
diff --git a/apps/storybook/stories/Thumbnail.stories.tsx b/apps/storybook/stories/Thumbnail.stories.tsx
new file mode 100644
index 0000000000..9b3f175159
--- /dev/null
+++ b/apps/storybook/stories/Thumbnail.stories.tsx
@@ -0,0 +1,197 @@
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSThumbnail} from '@xds/core/Thumbnail';
+
+const meta: Meta<typeof XDSThumbnail> = {
+ title: 'Core/XDSThumbnail',
+ component: XDSThumbnail,
+ tags: ['autodocs'],
+ argTypes: {
+ src: {
+ control: 'text',
+ description: 'Image source URL',
+ },
+ alt: {
+ control: 'text',
+ description: 'Alt text for the image',
+ },
+ label: {
+ control: 'text',
+ description: 'Label below the thumbnail',
+ },
+ isDisabled: {
+ control: 'boolean',
+ description: 'Whether the thumbnail is disabled',
+ },
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSThumbnail>;
+
+// Deterministic picsum images by ID
+const DARK_IMAGE = 'https://picsum.photos/id/1042/200/200'; // dark interior
+const LIGHT_IMAGE = 'https://picsum.photos/id/1043/200/200'; // bright snow/sky
+const WARM_IMAGE = 'https://picsum.photos/id/1044/200/200'; // warm tones
+const MIXED_IMAGE = 'https://picsum.photos/id/1047/200/200'; // mixed tones
+
+export const Default: Story = {
+ args: {
+ src: LIGHT_IMAGE,
+ alt: 'Sample image',
+ },
+};
+
+export const WithLabel: Story = {
+ args: {
+ src: WARM_IMAGE,
+ alt: 'Vacation photo',
+ label: 'vacation.jpg',
+ },
+};
+
+export const WithRemove: Story = {
+ render: () => {
+ const [visible, setVisible] = useState(true);
+ if (!visible) return <p style={{color: '#888', fontSize: 12}}>Removed. <button onClick={() => setVisible(true)}>Undo</button></p>;
+ return (
+ <XDSThumbnail
+ src={LIGHT_IMAGE}
+ alt="Removable thumbnail"
+ label="photo.png"
+ onRemove={() => setVisible(false)}
+ />
+ );
+ },
+};
+
+export const WithCaption: Story = {
+ render: () => {
+ const [visible, setVisible] = useState(true);
+ if (!visible) return <p style={{color: '#888', fontSize: 12}}>Removed. <button onClick={() => setVisible(true)}>Undo</button></p>;
+ return (
+ <XDSThumbnail
+ src={WARM_IMAGE}
+ alt="Photo with metadata"
+ label="screenshot.png"
+ onRemove={() => setVisible(false)}
+ />
+ );
+ },
+};
+
+export const Clickable: Story = {
+ args: {
+ src: MIXED_IMAGE,
+ alt: 'Clickable thumbnail',
+ onClick: () => alert('Clicked!'),
+ label: 'preview.jpg',
+ },
+};
+
+export const Loading: Story = {
+ name: 'Loading (no preview)',
+ args: {
+ isLoading: true,
+ label: 'uploading.jpg',
+ },
+};
+
+export const Uploading: Story = {
+ name: 'Uploading (with preview)',
+ args: {
+ src: WARM_IMAGE,
+ alt: 'Uploading preview',
+ isLoading: true,
+ label: 'vacation.jpg',
+ },
+};
+
+export const Placeholder: Story = {
+ name: 'No Image (Placeholder)',
+ render: () => {
+ const [visible, setVisible] = useState(true);
+ if (!visible) return <p style={{color: '#888', fontSize: 12}}>Removed. <button onClick={() => setVisible(true)}>Undo</button></p>;
+ return (
+ <XDSThumbnail
+ label="report.pdf"
+ onRemove={() => setVisible(false)}
+ />
+ );
+ },
+};
+
+export const Disabled: Story = {
+ args: {
+ src: LIGHT_IMAGE,
+ alt: 'Disabled thumbnail',
+ label: 'locked.jpg',
+ onRemove: () => {},
+ isDisabled: true,
+ },
+};
+
+export const MediaModeTest: Story = {
+ name: 'Media Mode (dark vs light images)',
+ render: function MediaModeStory() {
+ const images = [
+ {src: DARK_IMAGE, label: 'dark.jpg', alt: 'Dark image'},
+ {src: LIGHT_IMAGE, label: 'light.jpg', alt: 'Light image'},
+ {src: MIXED_IMAGE, label: 'mixed.jpg', alt: 'Mixed tones'},
+ {src: WARM_IMAGE, label: 'warm.jpg', alt: 'Warm tones'},
+ ];
+ const [items, setItems] = useState(images);
+ return (
+ <div>
+ <p style={{fontSize: 12, color: '#888', marginBottom: 8}}>
+ Remove buttons should adapt: light icon on dark images, dark icon on light images.
+ </p>
+ <div style={{display: 'flex', gap: 8, alignItems: 'flex-start'}}>
+ {items.map(item => (
+ <XDSThumbnail
+ key={item.label}
+ src={item.src}
+ alt={item.alt}
+ label={item.label}
+ onRemove={() => setItems(prev => prev.filter(i => i.label !== item.label))}
+ />
+ ))}
+ {items.length === 0 && (
+ <p style={{color: '#888', fontSize: 12}}>
+ All removed. <button onClick={() => setItems(images)}>Reset</button>
+ </p>
+ )}
+ </div>
+ </div>
+ );
+ },
+};
+
+export const Gallery: Story = {
+ render: function GalleryStory() {
+ const initial = [
+ {id: 1, src: DARK_IMAGE, label: 'dark.jpg'},
+ {id: 2, src: LIGHT_IMAGE, label: 'light.jpg'},
+ {id: 4, src: WARM_IMAGE, label: 'warm.jpg'},
+ ];
+ const [items, setItems] = useState(initial);
+ return (
+ <div style={{display: 'flex', gap: 8, alignItems: 'flex-start'}}>
+ {items.map(item => (
+ <XDSThumbnail
+ key={item.id}
+ src={item.src}
+ alt={item.label}
+ label={item.label}
+ onRemove={() => setItems(prev => prev.filter(i => i.id !== item.id))}
+ />
+ ))}
+ {items.length === 0 && (
+ <p style={{color: '#888', fontSize: 12}}>
+ All removed. <button onClick={() => setItems(initial)}>Reset</button>
+ </p>
+ )}
+ </div>
+ );
+ },
+};
diff --git a/packages/core/package.json b/packages/core/package.json
index 7c217878f3..cfa3c2a5c3 100644
--- a/packages/core/package.json
+++ b/packages/core/package.json
@@ -394,6 +394,12 @@
"import": "./dist/TextInput/index.mjs",
"require": "./dist/TextInput/index.js"
},
+ "./Thumbnail": {
+ "source": "./src/Thumbnail/index.ts",
+ "types": "./dist/Thumbnail/index.d.ts",
+ "import": "./dist/Thumbnail/index.mjs",
+ "require": "./dist/Thumbnail/index.js"
+ },
"./TimeInput": {
"source": "./src/TimeInput/index.ts",
"types": "./dist/TimeInput/index.d.ts",
diff --git a/packages/core/src/Thumbnail/Thumbnail.doc.mjs b/packages/core/src/Thumbnail/Thumbnail.doc.mjs
new file mode 100644
index 0000000000..3c1f05fb94
--- /dev/null
+++ b/packages/core/src/Thumbnail/Thumbnail.doc.mjs
@@ -0,0 +1,69 @@
+/** @type {import('../docs-types').ComponentDoc} */
+
+export const docs = {
+ name: 'Thumbnail',
+ description:
+ 'A square preview card for image attachments. Shows a skeleton shimmer while uploading, the image on success, or a placeholder icon when no source is provided.',
+ keywords: ["thumbnail","attachment","preview","image","upload","dismiss","remove","loading"],
+ features: [
+ 'Square 1:1 aspect ratio via CSS aspect-ratio',
+ 'Skeleton shimmer during upload (isLoading)',
+ 'Upload overlay with spinner when isLoading + src',
+ 'Image preview with object-fit: cover',
+ 'APCA-based luminance detection for adaptive remove button contrast',
+ 'Concentric radius: button radius derived from container radius minus inset',
+ 'Hover shadow on interactive thumbnails (onClick)',
+ 'Label shown as tooltip on hover, used as aria-label',
+ 'Placeholder icon when no src',
+ 'Disabled state blocks all interactions and reduces opacity',
+ ],
+ props: [
+ {
+ name: 'src',
+ type: 'string',
+ description: 'Image source URL.',
+ },
+ {
+ name: 'alt',
+ type: 'string',
+ description: 'Alt text for the image.',
+ },
+ {
+ name: 'label',
+ type: 'string',
+ description: 'Accessible label (e.g. file name). Shown as tooltip on hover.',
+ },
+ {
+ name: 'onRemove',
+ type: '(e: React.MouseEvent) => void',
+ description: 'Callback for the overlaid remove button.',
+ },
+ {
+ name: 'onClick',
+ type: '(e: React.MouseEvent) => void',
+ description: 'Click handler. Adds button semantics and hover shadow.',
+ },
+ {
+ name: 'isLoading',
+ type: 'boolean',
+ description: 'Shows skeleton (no src) or upload overlay (with src).',
+ default: 'false',
+ },
+ {
+ name: 'isDisabled',
+ type: 'boolean',
+ description: 'Whether the thumbnail is disabled.',
+ default: 'false',
+ },
+ ],
+ examples: [
+ {
+ label: 'Image with remove',
+ code: '<XDSThumbnail src="/photo.jpg" alt="Vacation" label="vacation.jpg" onRemove={() => {}} />',
+ },
+ {
+ label: 'Clickable',
+ code: '<XDSThumbnail src="/preview.png" alt="Preview" onClick={openLightbox} />',
+ },
+ ],
+};
diff --git a/packages/core/src/Thumbnail/XDSThumbnail.test.tsx b/packages/core/src/Thumbnail/XDSThumbnail.test.tsx
new file mode 100644
index 0000000000..9112779f1e
--- /dev/null
+++ b/packages/core/src/Thumbnail/XDSThumbnail.test.tsx
@@ -0,0 +1,95 @@
+import {describe, it, expect, vi} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import {XDSThumbnail} from './XDSThumbnail';
+
+describe('XDSThumbnail', () => {
+ it('renders an image when src is provided', () => {
+ render(<XDSThumbnail src="/photo.jpg" alt="Test photo" />);
+ const img = screen.getByRole('img');
+ expect(img).toHaveAttribute('src', '/photo.jpg');
+ expect(img).toHaveAttribute('alt', 'Test photo');
+ });
+
+ it('renders placeholder when no src is provided', () => {
+ render(<XDSThumbnail data-testid="thumb" />);
+ const root = screen.getByTestId('thumb');
+ expect(root.querySelector('svg')).toBeInTheDocument();
+ expect(screen.queryByRole('img')).toBeNull();
+ });
+
+ it('shows skeleton when isLoading with no src', () => {
+ const {container} = render(
+ <XDSThumbnail isLoading data-testid="thumb" />,
+ );
+ expect(container.querySelector('.xds-skeleton')).toBeInTheDocument();
+ expect(screen.queryByRole('img')).toBeNull();
+ });
+
+ it('shows image with upload overlay when isLoading with src', () => {
+ render(
+ <XDSThumbnail src="/local.jpg" alt="Uploading" isLoading data-testid="thumb" />,
+ );
+ const img = screen.getByRole('img');
+ expect(img).toHaveAttribute('src', '/local.jpg');
+ expect(screen.getByRole('status')).toBeInTheDocument();
+ });
+
+ it('uses label as accessible name on root', () => {
+ render(<XDSThumbnail label="photo.png" data-testid="thumb" />);
+ expect(screen.getByTestId('thumb')).toHaveAttribute('aria-label', 'photo.png');
+ });
+
+ it('label is shown via tooltip, not as inline text', () => {
+ render(<XDSThumbnail label="photo.png" data-testid="thumb" />);
+ // Label should exist in DOM (tooltip) but not as a direct child text node
+ const thumb = screen.getByTestId('thumb');
+ expect(thumb.textContent).not.toContain('photo.png');
+ });
+
+ it('calls onRemove when remove button is clicked', async () => {
+ const user = userEvent.setup();
+ const onRemove = vi.fn();
+ render(<XDSThumbnail label="file.png" onRemove={onRemove} />);
+ const removeBtn = screen.getByRole('button', {name: 'Remove file.png'});
+ await user.click(removeBtn);
+ expect(onRemove).toHaveBeenCalledOnce();
+ });
+
+ it('calls onClick when thumbnail is clicked', async () => {
+ const user = userEvent.setup();
+ const onClick = vi.fn();
+ render(<XDSThumbnail src="/img.jpg" alt="Clickable" onClick={onClick} />);
+ const btn = screen.getByRole('button', {name: 'Open Clickable'});
+ await user.click(btn);
+ expect(onClick).toHaveBeenCalledOnce();
+ });
+
+ it('does not render remove button when disabled', () => {
+ const onRemove = vi.fn();
+ render(<XDSThumbnail label="file.png" onRemove={onRemove} isDisabled />);
+ expect(screen.queryByRole('button', {name: /Remove/})).toBeNull();
+ });
+
+ it('does not render onClick button when disabled', () => {
+ const onClick = vi.fn();
+ render(
+ <XDSThumbnail src="/img.jpg" alt="Test" onClick={onClick} isDisabled />,
+ );
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('is not interactive when isLoading', () => {
+ const onClick = vi.fn();
+ render(
+ <XDSThumbnail src="/img.jpg" alt="Test" onClick={onClick} isLoading />,
+ );
+ expect(screen.queryByRole('button')).toBeNull();
+ });
+
+ it('forwards ref to root element', () => {
+ const ref = vi.fn();
+ render(<XDSThumbnail ref={ref} data-testid="thumb" />);
+ expect(ref).toHaveBeenCalled();
+ });
+});
diff --git a/packages/core/src/Thumbnail/XDSThumbnail.tsx b/packages/core/src/Thumbnail/XDSThumbnail.tsx
new file mode 100644
index 0000000000..c7f8ec817c
--- /dev/null
+++ b/packages/core/src/Thumbnail/XDSThumbnail.tsx
@@ -0,0 +1,352 @@
+'use client';
+
+/**
+ * @file XDSThumbnail.tsx
+ * @input Uses React, stylex, XDSButton, XDSSkeleton, XDSSpinner, XDSMediaTheme, useImageMode
+ * @output Exports XDSThumbnail component, XDSThumbnailProps
+ * @position Core implementation; consumed by index.ts
+ *
+ * Square preview card for image attachments. Shows a skeleton shimmer while
+ * the image loads, the image on success, or a placeholder on failure.
+ * Uses useImageMode (APCA) to detect image luminance so the overlaid
+ * remove button always has sufficient contrast.
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Thumbnail/Thumbnail.doc.mjs
+ * - /packages/core/src/Thumbnail/XDSThumbnail.test.tsx
+ * - /packages/core/src/Thumbnail/index.ts
+ * - /apps/storybook/stories/Thumbnail.stories.tsx
+ */
+
+import {type ReactNode} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ radiusVars,
+ spacingVars,
+ shadowVars,
+ durationVars,
+ easeVars,
+} from '../theme/tokens.stylex';
+import {XDSButton} from '../Button';
+import {XDSIcon} from '../Icon';
+import {XDSSkeleton} from '../Skeleton';
+import {XDSSpinner} from '../Spinner';
+import {XDSTooltip} from '../Tooltip/XDSTooltip';
+import {XDSMediaTheme} from '../theme/XDSMediaTheme';
+import {useImageMode} from '../hooks/useImageMode';
+import type {XDSBaseProps} from '../XDSBaseProps';
+import {xdsClassName, mergeProps} from '../utils';
+
+/** Sample the region behind the remove button (20px button, 4px inset, in 64px container). */
+const BUTTON_REGION = {x: 0.5, y: 0.06, width: 0.44, height: 0.44};
+
+export interface XDSThumbnailProps extends XDSBaseProps<HTMLDivElement> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
+ /**
+ * Image source for the thumbnail preview.
+ * Shows a skeleton while loading, the image on success, or a placeholder on error.
+ */
+ src?: string;
+ /**
+ * Alt text for the image. Required for accessibility when `src` is provided.
+ */
+ alt?: string;
+ /**
+ * Accessible label for the thumbnail (e.g. file name).
+ * Not rendered visually — shown in a tooltip on hover and used
+ * as accessible name for the remove button.
+ */
+ label?: string;
+ /**
+ * Callback when the remove button is clicked.
+ * When provided, an overlaid close button appears in the top-right corner.
+ */
+ onRemove?: (e: React.MouseEvent) => void;
+ /**
+ * Click handler for opening a lightbox or detail view.
+ * When provided, the thumbnail renders as interactive.
+ */
+ onClick?: (e: React.MouseEvent) => void;
+ /**
+ * Content rendered below the thumbnail image area.
+ * Use for metadata like file size, duration, or status.
+ */
+ /**
+ * Whether the thumbnail is in a loading state.
+ * Shows a skeleton shimmer regardless of `src`. Use while uploading
+ * or processing before an image URL is available.
+ * @default false
+ */
+ isLoading?: boolean;
+ /**
+ * Whether the thumbnail is in a disabled state.
+ * @default false
+ */
+ isDisabled?: boolean;
+ /**
+ * Test ID for testing frameworks.
+ */
+ 'data-testid'?: string;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+const styles = stylex.create({
+ root: {
+ position: 'relative',
+ display: 'inline-flex',
+ flexDirection: 'column',
+ width: 64,
+ flexShrink: 0,
+ },
+ imageContainer: {
+ position: 'relative',
+ width: '100%',
+ aspectRatio: '1',
+ borderRadius: radiusVars['--radius-element'],
+ overflow: 'hidden',
+ backgroundColor: colorVars['--color-neutral'],
+ },
+ image: {
+ width: '100%',
+ height: '100%',
+ objectFit: 'cover',
+ display: 'block',
+ },
+ insetBorder: {
+ position: 'absolute',
+ inset: 0,
+ borderRadius: 'inherit',
+ boxShadow: `inset 0 0 0 1px ${colorVars['--color-border']}`,
+ pointerEvents: 'none',
+ },
+ placeholder: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ width: '100%',
+ height: '100%',
+ color: colorVars['--color-icon-secondary'],
+ },
+ interactive: {
+ cursor: 'pointer',
+ transitionProperty: 'opacity, box-shadow',
+ transitionDuration: durationVars['--duration-fast'],
+ transitionTimingFunction: easeVars['--ease-standard'],
+ boxShadow: {
+ default: 'none',
+ ':hover': {
+ '@media (hover: hover)': shadowVars['--shadow-med'],
+ },
+ },
+ opacity: {
+ default: 1,
+ ':hover': {
+ '@media (hover: hover)': 0.85,
+ },
+ ':active': 0.75,
+ },
+ },
+ interactiveButton: {
+ all: 'unset',
+ cursor: 'pointer',
+ display: 'block',
+ width: '100%',
+ height: '100%',
+ outline: {
+ default: null,
+ ':focus-visible': `2px solid ${colorVars['--color-accent']}`,
+ },
+ outlineOffset: {
+ default: '0',
+ ':focus-visible': '2px',
+ },
+ borderRadius: radiusVars['--radius-element'],
+ overflow: 'hidden',
+ },
+ removeButtonOverrides: {
+ position: 'absolute',
+ top: spacingVars['--spacing-1'],
+ right: spacingVars['--spacing-1'],
+ zIndex: 1,
+ '--button-radius': `calc(${radiusVars['--radius-element']} - ${spacingVars['--spacing-1']})`,
+ height: 20,
+ minWidth: 20,
+ } as Record<string, string | number>,
+ disabled: {
+ opacity: 0.5,
+ pointerEvents: 'none' as const,
+ },
+ uploadOverlay: {
+ position: 'absolute',
+ inset: 0,
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ backgroundColor: colorVars['--color-overlay'],
+ borderRadius: 'inherit',
+ zIndex: 1,
+ lineHeight: 0,
+ },
+});
+
+// =============================================================================
+// Placeholder icon — a simple image silhouette
+// =============================================================================
+
+function ImagePlaceholder() {
+ return (
+ <svg
+ width={24}
+ height={24}
+ viewBox="0 0 24 24"
+ fill="currentColor"
+ aria-hidden="true">
+ <path d="M21 19V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2M8.5 13.5l2.5 3 3.5-4.5 4.5 6H5l3.5-5.5z" />
+ </svg>
+ );
+}
+
+// =============================================================================
+// Component
+// =============================================================================
+
+/**
+ * A square thumbnail preview for image attachments.
+ *
+ * Shows a skeleton shimmer while the image loads, the image on success, or
+ * a placeholder icon on failure / when no src is provided. An overlaid
+ * remove button appears when `onRemove` is set.
+ *
+ * Uses `useImageMode` (APCA) to detect image luminance and `XDSMediaTheme`
+ * to ensure the remove button always has sufficient contrast against the image.
+ *
+ * @example
+ * ```
+ * <XDSThumbnail src="/photo.jpg" alt="Vacation photo" onRemove={() => {}} />
+ * <XDSThumbnail src="/preview.png" alt="Preview" onClick={() => {}} label="preview.png" />
+ * ```
+ */
+export function XDSThumbnail({
+ src,
+ alt,
+ label,
+ onRemove,
+ onClick,
+ isLoading = false,
+ isDisabled = false,
+ xstyle,
+ className,
+ style,
+ 'data-testid': testId,
+ ref,
+ ...props
+}: XDSThumbnailProps) {
+ const imageMode = useImageMode(src, {region: BUTTON_REGION, fallback: null});
+
+ const hasSrc = src != null;
+ const showSkeleton = isLoading && !hasSrc;
+ const showImage = hasSrc && !showSkeleton;
+ const showUploadOverlay = isLoading && hasSrc;
+ const showPlaceholder = !isLoading && !hasSrc;
+ const isInteractive = onClick != null && !isDisabled && !isLoading;
+ const accessibleName =
+ label && alt ? `${label} — ${alt}` : label ?? alt ?? 'thumbnail';
+
+ const imageContent = (
+ <>
+ {showImage && (
+ <img
+ src={src}
+ alt={alt ?? ''}
+ {...stylex.props(styles.image)}
+ />
+ )}
+ {showSkeleton && (
+ <XDSSkeleton radius={2} />
+ )}
+ {showPlaceholder && (
+ <div {...stylex.props(styles.placeholder)}>
+ <ImagePlaceholder />
+ </div>
+ )}
+ </>
+ );
+
+ const removeButtonEl =
+ onRemove != null && !isDisabled ? (
+ <XDSButton
+ icon={<XDSIcon icon="close" size="xsm" />}
+ label={`Remove ${accessibleName}`}
+ variant="secondary"
+ size="sm"
+ isIconOnly
+ onClick={e => {
+ e.stopPropagation();
+ onRemove(e);
+ }}
+ xstyle={styles.removeButtonOverrides}
+ />
+ ) : null;
+
+ const thumbnail = (
+ <div
+ ref={ref}
+ data-testid={testId}
+ aria-label={accessibleName}
+ {...mergeProps(
+ xdsClassName('thumbnail'),
+ stylex.props(
+ styles.root,
+ isDisabled && styles.disabled,
+ xstyle,
+ ),
+ className,
+ style,
+ )}
+ {...props}>
+ <div
+ {...stylex.props(
+ styles.imageContainer,
+ isInteractive && styles.interactive,
+ )}>
+ {isInteractive ? (
+ <button
+ type="button"
+ onClick={onClick}
+ aria-label={`Open ${accessibleName}`}
+ {...stylex.props(styles.interactiveButton)}>
+ {imageContent}
+ </button>
+ ) : (
+ imageContent
+ )}
+ {showImage && <div {...stylex.props(styles.insetBorder)} />}
+ {showUploadOverlay && (
+ <div {...stylex.props(styles.uploadOverlay)}>
+ <XDSSpinner size="sm" shade="onMedia" />
+ </div>
+ )}
+ {removeButtonEl != null && imageMode != null ? (
+ <XDSMediaTheme mode={imageMode}>
+ {removeButtonEl}
+ </XDSMediaTheme>
+ ) : (
+ removeButtonEl
+ )}
+ </div>
+ </div>
+ );
+
+ if (label != null) {
+ return <XDSTooltip content={label}>{thumbnail}</XDSTooltip>;
+ }
+
+ return thumbnail;
+}
+
+XDSThumbnail.displayName = 'XDSThumbnail';
diff --git a/packages/core/src/Thumbnail/index.ts b/packages/core/src/Thumbnail/index.ts
new file mode 100644
index 0000000000..fe96fe5741
--- /dev/null
+++ b/packages/core/src/Thumbnail/index.ts
@@ -0,0 +1,6 @@
+/**
+ * @file Thumbnail component barrel export
+ */
+
+export {XDSThumbnail} from './XDSThumbnail';
+export type {XDSThumbnailProps} from './XDSThumbnail';
diff --git a/packages/core/src/hooks/useImageMode.ts b/packages/core/src/hooks/useImageMode.ts
index 6492e5657e..a1eb1eec71 100644
--- a/packages/core/src/hooks/useImageMode.ts
+++ b/packages/core/src/hooks/useImageMode.ts
@@ -10,8 +10,9 @@
* its pixels via OffscreenCanvas. Runs entirely off the paint path —
* no visible canvas element, no layout thrash.
*
- * The 1×1 downsample trick lets the browser's internal resampling do
- * the averaging — no manual pixel-by-pixel luminance calculation.
+ * Uses APCA perceptual lightness (sRGB linearization + power curve)
+ * which handles saturated colors better than BT.709 gamma-luma or
+ * WCAG 2 relative luminance.
*
* For regional detection (e.g. "what's the luminance where the text
* overlay sits"), pass a `region` option to sample a specific area.
@@ -69,14 +70,23 @@ export interface UseImageModeOptions {
}
/**
- * Calculate perceptual brightness from sRGB values (0-255).
- * Uses BT.709 luma coefficients on gamma-encoded values (not linearized).
- * This gives a result that matches human perception better than
- * true relative luminance for the purpose of "is this image dark or light."
- * Returns 0-1 where 0 is black, 1 is white.
+ * APCA perceptual lightness from sRGB values (0-255).
+ *
+ * Linearizes sRGB with a 2.4 exponent, computes luminance Y using
+ * APCA coefficients (slightly refined from BT.709), then applies a
+ * perceptual power curve (Y^0.56) that maps linear light to a scale
+ * where 0.5 ≈ perceptual mid-gray.
+ *
+ * This outperforms both raw BT.709 gamma-luma and WCAG 2 relative
+ * luminance for dark/light surface detection — especially on saturated
+ * colors (reds, blues) where gamma-encoded luma overestimates brightness.
+ *
+ * Returns 0–1 where 0 is black, 1 is white.
*/
-function perceptualBrightness(r: number, g: number, b: number): number {
- return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
+function perceptualLightness(r: number, g: number, b: number): number {
+ const lin = (c: number) => Math.pow(c / 255, 2.4);
+ const y = 0.2126729 * lin(r) + 0.7151522 * lin(g) + 0.0721750 * lin(b);
+ return Math.pow(y, 0.56);
}
/**
@@ -144,8 +154,8 @@ export function useImageMode(
if (cancelled) return;
- const brightness = perceptualBrightness(r, g, b);
- setMode(brightness > threshold ? 'light' : 'dark');
+ const lightness = perceptualLightness(r, g, b);
+ setMode(lightness > threshold ? 'light' : 'dark');
} catch {
// CORS error, network error, etc. — keep fallback
if (!cancelled) setMode(fallback);
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 72aadc0947..c96b7209a7 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -60,6 +60,7 @@ export * from './ToggleButton';
export * from './Token';
export * from './Typeahead';
export * from './Tokenizer';
+export * from './Thumbnail';
export * from './PowerSearch';
export * from './TreeList';