Skip to content

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

TypeScript

fix(AspectRatio): fit fills the box on the documented Tailwind setups (#7521)

Christopher Chedeaud3ec0b25cdb0
diff --git a/.changeset/aspect-ratio-fit-tailwind-layers.md b/.changeset/aspect-ratio-fit-tailwind-layers.md
new file mode 100644
index 0000000000..c33542df6f
--- /dev/null
+++ b/.changeset/aspect-ratio-fit-tailwind-layers.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/core': patch
+---
+
+[fix] `AspectRatio`'s `fit="cover"` and `fit="contain"` now fill the box on the documented Tailwind setups. The fit rules lived in `reset.css`, in the `reset` layer, and the setup guides put Tailwind's preflight in a layer above it, so preflight's `img, video { height: auto }` won and a fitted image kept its own aspect ratio. The fit sizing now ships with the component's own styles in `astryx-base`: above preflight, and below Tailwind's utilities, so a utility class on the child still wins. `reset.css` no longer carries AspectRatio rules.
+
+With `fit="cover"` or `fit="contain"`, a direct child's own Astryx styles (an Astryx component's own size or `object-fit`) no longer override the fill. To keep a child's own size, set it with an inline style, unlayered CSS or a rule in a later layer, or leave `fit` unset.
+
+@vjeux
diff --git a/.github/pages/assets/manifest.json b/.github/pages/assets/manifest.json
index bf0d9870db..7d7b51c961 100644
--- a/.github/pages/assets/manifest.json
+++ b/.github/pages/assets/manifest.json
@@ -6,7 +6,7 @@
},
"files": {
"reset.css": {
- "sha256": "67ea29d9956ef672bef552cfafb3a54dc936a1285296b03207bc0c46a735b41f"
+ "sha256": "463fa7b4a94245b25ea1bb03836e5cf6a36b9133193a747107fd307f4de7eb07"
},
"astryx.css": {
"sha256": "5865284828ab722b47d2ce2eeab79496d7f83bfe878286dba9861807f88d5e98"
diff --git a/.github/pages/assets/reset.css b/.github/pages/assets/reset.css
index 69e9e131e9..0b0231ba2e 100644
--- a/.github/pages/assets/reset.css
+++ b/.github/pages/assets/reset.css
@@ -203,35 +203,6 @@
height: auto;
}
- /* ===========================================================================
- AspectRatio Fit Baseline
- =========================================================================== */
-
- /*
- * Child sizing for AspectRatio's `fit` prop — the component marks the
- * child's direct parent with `data-astryx-aspect-ratio-override` (carrying
- * the fit value), and these direct-child rules size the child, so
- * consumers don't hand-write width/height/object-fit on every media child.
- * The marker sits on the parent itself, so the rules don't depend on
- * AspectRatio's internal element structure or its theming surface. As with
- * the [data-astryx-media] baseline below, the rules are zero-specificity
- * and any styling the child sets itself still wins. `fit="center"` needs
- * no rules here — the component centers the child from its own wrapper.
- */
- :where([data-astryx-aspect-ratio-override="cover"], [data-astryx-aspect-ratio-override="contain"])
- > :where(*) {
- width: 100%;
- height: 100%;
- }
-
- :where([data-astryx-aspect-ratio-override="cover"]) > :where(img, video) {
- object-fit: cover;
- }
-
- :where([data-astryx-aspect-ratio-override="contain"]) > :where(img, video) {
- object-fit: contain;
- }
-
/* ===========================================================================
Forms
=========================================================================== */
diff --git a/packages/core/src/AspectRatio/AspectRatio.test.tsx b/packages/core/src/AspectRatio/AspectRatio.test.tsx
index fe3fcdce3c..ee0e35ad7a 100644
--- a/packages/core/src/AspectRatio/AspectRatio.test.tsx
+++ b/packages/core/src/AspectRatio/AspectRatio.test.tsx
@@ -9,7 +9,7 @@
* SYNC: When AspectRatio.tsx changes, update tests to match new behavior
*/
-import {describe, it, expect, vi, beforeAll} from 'vitest';
+import {describe, it, expect, vi} from 'vitest';
import {render, screen} from '@testing-library/react';
import {AspectRatio} from './AspectRatio';
@@ -230,9 +230,8 @@ describe('AspectRatio', () => {
<img src="test.jpg" alt="Test" data-testid="image" />
</AspectRatio>,
);
- // The marker sits on the child's actual parent, so the reset.css
- // sizing rules are direct-child selectors with no dependence on
- // AspectRatio's internal structure.
+ // Earlier releases documented the marker, so it stays on the child's
+ // direct parent for product CSS that targets it.
const wrapper = screen.getByTestId('image').parentElement;
expect(wrapper).toHaveAttribute(
'data-astryx-aspect-ratio-override',
@@ -274,8 +273,11 @@ describe('AspectRatio', () => {
);
const wrapper = screen.getByTestId('image').parentElement;
expect(wrapper).not.toHaveAttribute('data-astryx-aspect-ratio-override');
- // Without the marker, none of the reset.css fit rules can match, so
- // existing self-styled children render exactly as before.
+ // Without fit the wrapper carries no child-sizing styles, so existing
+ // self-styled children render exactly as before.
+ expect(wrapper?.className).not.toContain('childFill');
+ expect(wrapper?.className).not.toContain('childCover');
+ expect(wrapper?.className).not.toContain('childContain');
expect(screen.getByTestId('image')).not.toHaveAttribute('class');
});
@@ -292,13 +294,37 @@ describe('AspectRatio', () => {
</AspectRatio>,
);
const image = screen.getByTestId('image');
- // Fit styling is pure CSS (zero-specificity reset rules); the child's
- // own className/style pass through untouched and always win, so
- // children that already size themselves keep their behavior.
+ // Fit styling is a direct-child rule on the wrapper; the child's own
+ // className/style pass through untouched, and an inline style still
+ // wins over it.
expect(image.className).toBe('consumer-class');
expect(image.style.objectFit).toBe('contain');
});
+ it('sizes the child from the wrapper with fit="cover"', () => {
+ render(
+ <AspectRatio ratio={16 / 9} fit="cover">
+ <img src="test.jpg" alt="Test" data-testid="image" />
+ </AspectRatio>,
+ );
+ const wrapper = screen.getByTestId('image').parentElement;
+ expect(wrapper?.className).toContain('childFill');
+ expect(wrapper?.className).toContain('childCover');
+ expect(wrapper?.className).not.toContain('childContain');
+ });
+
+ it('sizes the child from the wrapper with fit="contain"', () => {
+ render(
+ <AspectRatio ratio={16 / 9} fit="contain">
+ <img src="test.jpg" alt="Test" data-testid="image" />
+ </AspectRatio>,
+ );
+ const wrapper = screen.getByTestId('image').parentElement;
+ expect(wrapper?.className).toContain('childFill');
+ expect(wrapper?.className).toContain('childContain');
+ expect(wrapper?.className).not.toContain('childCover');
+ });
+
it('centers the child via the wrapper with fit="center"', () => {
render(
<AspectRatio ratio={16 / 9} fit="center">
@@ -309,6 +335,7 @@ describe('AspectRatio', () => {
expect(image).not.toHaveAttribute('class');
const wrapper = image.parentElement;
expect(wrapper?.className).toContain('childCenter');
+ expect(wrapper?.className).not.toContain('childFill');
});
it('does not center the wrapper for other fit values', () => {
@@ -353,45 +380,19 @@ describe('AspectRatio', () => {
});
});
- describe('reset.css fit baseline rules', () => {
- // The cover/contain child sizing ships as zero-specificity baseline
- // rules in reset.css keyed on the data-astryx-aspect-ratio-override
- // marker the component sets on the child's direct parent. These
- // assertions keep the stylesheet in sync with the component contract.
- let resetCSS: string;
-
- beforeAll(async () => {
+ describe('reset.css', () => {
+ it('carries no AspectRatio rules', async () => {
+ // fit ships with the component's StyleX styles in `astryx-base`. A
+ // rule in reset.css sits below the layer the documented Tailwind
+ // setups give preflight, whose `img, video { height: auto }` would
+ // undo the fill.
const fs = await import('fs');
const path = await import('path');
- resetCSS = fs.readFileSync(
+ const resetCSS = fs.readFileSync(
path.resolve(__dirname, '../reset.css'),
'utf-8',
);
- });
-
- it('sizes the child to fill the box for cover and contain', () => {
- const fillMatch = resetCSS.match(
- /:where\(\[data-astryx-aspect-ratio-override="cover"\], \[data-astryx-aspect-ratio-override="contain"\]\)\s*>\s*:where\(\*\)\s*\{([^}]+)\}/,
- );
- expect(fillMatch).not.toBeNull();
- expect(fillMatch![1]).toContain('width: 100%');
- expect(fillMatch![1]).toContain('height: 100%');
- });
-
- it('crops media with object-fit: cover for fit="cover"', () => {
- const coverMatch = resetCSS.match(
- /:where\(\[data-astryx-aspect-ratio-override="cover"\]\)\s*>\s*:where\(img, video\)\s*\{([^}]+)\}/,
- );
- expect(coverMatch).not.toBeNull();
- expect(coverMatch![1]).toContain('object-fit: cover');
- });
-
- it('letterboxes media with object-fit: contain for fit="contain"', () => {
- const containMatch = resetCSS.match(
- /:where\(\[data-astryx-aspect-ratio-override="contain"\]\)\s*>\s*:where\(img, video\)\s*\{([^}]+)\}/,
- );
- expect(containMatch).not.toBeNull();
- expect(containMatch![1]).toContain('object-fit: contain');
+ expect(resetCSS).not.toContain('aspect-ratio-override');
});
});
});
diff --git a/packages/core/src/AspectRatio/AspectRatio.tsx b/packages/core/src/AspectRatio/AspectRatio.tsx
index 59667c3dbb..3e14cb37a3 100644
--- a/packages/core/src/AspectRatio/AspectRatio.tsx
+++ b/packages/core/src/AspectRatio/AspectRatio.tsx
@@ -9,7 +9,6 @@
* SYNC: When modified, update these files to stay in sync:
* - /packages/core/src/AspectRatio/AspectRatio.doc.mjs
* - /packages/core/src/AspectRatio/AspectRatio.test.tsx
- * - /packages/core/src/reset.css (AspectRatio fit baseline rules)
* - /apps/storybook/stories/AspectRatio.stories.tsx
* - /packages/cli/assets/templates/blocks/components/AspectRatio/ (showcase blocks)
*/
@@ -91,13 +90,12 @@ export interface AspectRatioProps extends BaseProps<HTMLDivElement> {
* (`object-fit: contain`).
* - `center`: child keeps its natural size, centered in the box.
*
- * `cover`/`contain` child sizing ships as zero-specificity baseline rules
- * in `reset.css`, keyed on the `data-astryx-aspect-ratio-override`
- * attribute the component sets on the child's direct parent. Any styles
- * the child sets itself still win, so children that already size
- * themselves keep their behavior. When omitted, the child is left
- * unstyled (the pre-existing contract). `fit` is structural, not visual,
- * so it is not exposed on the theming surface.
+ * `cover`/`contain` size the child from the component's own styles, in
+ * the `astryx-base` cascade layer. Styles in a later layer (Tailwind
+ * utilities, `astryx-theme`), unlayered CSS, and inline styles on the
+ * child still win. When omitted, the child is left unstyled (the
+ * pre-existing contract). `fit` is structural, not visual, so it is not
+ * exposed on the theming surface.
*
* @example
* ```
@@ -140,15 +138,33 @@ const styles = stylex.create({
height: '100%',
},
// fit="center" centers the child at its natural size from the wrapper —
- // no styles on the child itself. The `cover`/`contain` child sizing can't
- // live here (StyleX has no descendant selectors); it ships as baseline
- // rules in reset.css keyed on the `data-astryx-aspect-ratio-override`
- // attribute the wrapper carries (see below).
+ // no styles on the child itself.
childCenter: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
+ // `cover`/`contain` must style the child itself (`object-fit` only applies
+ // on the replaced element), and StyleX has no child selector. The
+ // `:not([stylex-hack])` pseudo-class always matches, so StyleX accepts the
+ // key and emits `.x:not([stylex-hack]) > *`, a direct-child rule in the
+ // `astryx-base` layer like every other component style.
+ childFill: {
+ ':not([stylex-hack]) > *': {
+ width: '100%',
+ height: '100%',
+ },
+ },
+ childCover: {
+ ':not([stylex-hack]) > :is(img, video)': {
+ objectFit: 'cover',
+ },
+ },
+ childContain: {
+ ':not([stylex-hack]) > :is(img, video)': {
+ objectFit: 'contain',
+ },
+ },
});
// The ratio compiles to a CSS variable + a class-level declaration
@@ -234,14 +250,18 @@ export function AspectRatio({
style,
)}
{...props}>
- {/* The marker attribute carries the fit value so the reset.css child
- sizing can use direct-child selectors on this wrapper — the child's
- actual parent — without depending on AspectRatio's internal
- structure or on the theming surface (fit is structural, not
- themeable). The name is namespaced to avoid collisions. */}
+ {/* The marker attribute carries the fit value. No Astryx style keys on
+ it any more, but earlier releases documented it, so product CSS may
+ still target it. */}
<div
data-astryx-aspect-ratio-override={fit}
- {...stylex.props(styles.child, fit === 'center' && styles.childCenter)}>
+ {...stylex.props(
+ styles.child,
+ fit === 'center' && styles.childCenter,
+ (fit === 'cover' || fit === 'contain') && styles.childFill,
+ fit === 'cover' && styles.childCover,
+ fit === 'contain' && styles.childContain,
+ )}>
{children}
</div>
</div>
diff --git a/packages/core/src/AspectRatio/__tests__/AspectRatioFitLayers.a11y.browser.spec.ts b/packages/core/src/AspectRatio/__tests__/AspectRatioFitLayers.a11y.browser.spec.ts
new file mode 100644
index 0000000000..ad581c22f3
--- /dev/null
+++ b/packages/core/src/AspectRatio/__tests__/AspectRatioFitLayers.a11y.browser.spec.ts
@@ -0,0 +1,157 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file AspectRatioFitLayers.a11y.browser.spec.ts
+ * @input The built FitModes story (its rendered markup and compiled CSS) and
+ * Tailwind's preflight.css
+ * @output Browser evidence that `fit` fills the box on the documented setups
+ * @position AspectRatio integration proof. Which rule sizes the child is a
+ * cascade-layer question, and only a shipping engine resolves the cascade.
+ */
+
+import * as fs from 'node:fs';
+import {fileURLToPath} from 'node:url';
+import {expect, test, type Page} from '@playwright/test';
+import {
+ DEFAULT_STORYBOOK_DIR,
+ serveStorybook,
+ type StaticServer,
+} from '@astryxdesign/a11y-spec/storybook';
+
+const PREFLIGHT_CSS = fs.readFileSync(
+ fileURLToPath(import.meta.resolve('tailwindcss/preflight.css')),
+ 'utf8',
+);
+
+// The layer order each setup guide declares, and the layer preflight goes in.
+const TAILWIND_SETUPS = [
+ {
+ name: 'Tailwind v4',
+ order:
+ '@layer reset, theme, base, astryx-base, astryx-theme, components, utilities;',
+ preflightLayer: 'base',
+ },
+ {
+ name: 'Tailwind v3',
+ order: '@layer reset, tw-preflight, astryx-base, astryx-theme;',
+ preflightLayer: 'tw-preflight',
+ },
+];
+
+// A 100×100 image in a 320px-wide 16:9 box: filling the box makes it 320×180.
+const IMAGE =
+ "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='100' height='100'/%3E";
+
+type Fit = 'cover' | 'contain';
+
+let storybook: StaticServer;
+test.beforeAll(async () => {
+ storybook = await serveStorybook(
+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,
+ );
+});
+test.afterAll(async () => {
+ await storybook?.close();
+});
+
+/**
+ * The markup AspectRatio renders for `fit`, and every CSS rule the story
+ * page loaded, taken from the built story so the classes and rules are the
+ * component's real compiled output. The child image gets a fixed id, a
+ * local source and any extra class.
+ */
+async function captureStory(page: Page, fit: Fit, mediaClass: string) {
+ await page.goto(
+ `${storybook.origin}/iframe.html?id=core-aspectratio--fit-modes&viewMode=story`,
+ );
+ const wrapper = page.locator(`[data-astryx-aspect-ratio-override="${fit}"]`);
+ await expect(wrapper).toHaveCount(1);
+ return wrapper.evaluate(
+ (element, {image, extraClass}) => {
+ const root = element.parentElement?.cloneNode(true);
+ const media =
+ root instanceof HTMLElement ? root.querySelector('img') : null;
+ if (!(root instanceof HTMLElement) || media == null) {
+ throw new Error('FitModes no longer renders an img inside AspectRatio');
+ }
+ media.id = 'media';
+ media.src = image;
+ if (extraClass) {
+ media.classList.add(extraClass);
+ }
+ const css = [...document.styleSheets]
+ .flatMap(sheet => [...sheet.cssRules].map(rule => rule.cssText))
+ .join('\n');
+ return {html: root.outerHTML, css};
+ },
+ {image: IMAGE, extraClass: mediaClass},
+ );
+}
+
+/** Re-host the captured story with `before` CSS ahead of it and `after` CSS behind it. */
+async function measureMedia(
+ page: Page,
+ fit: Fit,
+ {
+ before = [],
+ after = [],
+ mediaClass = '',
+ }: {
+ before?: string[];
+ after?: string[];
+ mediaClass?: string;
+ },
+) {
+ const {html, css} = await captureStory(page, fit, mediaClass);
+ await page.setContent(
+ `<!doctype html><div style="width: 320px">${html}</div>`,
+ );
+ for (const content of [...before, css, ...after]) {
+ await page.addStyleTag({content});
+ }
+ await page.waitForFunction(
+ () => (document.getElementById('media') as HTMLImageElement).complete,
+ );
+ return page.evaluate(() => {
+ const media = document.getElementById('media');
+ if (!media) {
+ throw new Error('missing media');
+ }
+ const box = media.getBoundingClientRect();
+ return {
+ width: box.width,
+ height: box.height,
+ objectFit: getComputedStyle(media).objectFit,
+ };
+ });
+}
+
+for (const setup of TAILWIND_SETUPS) {
+ for (const fit of ['cover', 'contain'] as const) {
+ test(`fit="${fit}" fills the box on the ${setup.name} setup`, async ({
+ page,
+ }) => {
+ const media = await measureMedia(page, fit, {
+ before: [
+ setup.order,
+ `@layer ${setup.preflightLayer} { ${PREFLIGHT_CSS} }`,
+ ],
+ });
+ expect(media).toEqual({width: 320, height: 180, objectFit: fit});
+ });
+ }
+}
+
+test('fit fills the box with only Astryx CSS loaded', async ({page}) => {
+ const media = await measureMedia(page, 'cover', {});
+ expect(media).toEqual({width: 320, height: 180, objectFit: 'cover'});
+});
+
+test('a utility class on the child still wins over fit', async ({page}) => {
+ const media = await measureMedia(page, 'cover', {
+ before: [TAILWIND_SETUPS[0].order, `@layer base { ${PREFLIGHT_CSS} }`],
+ after: ['@layer utilities { .h-10 { height: 40px; } }'],
+ mediaClass: 'h-10',
+ });
+ expect(media).toEqual({width: 320, height: 40, objectFit: 'cover'});
+});
diff --git a/packages/core/src/reset.css b/packages/core/src/reset.css
index 69e9e131e9..0b0231ba2e 100644
--- a/packages/core/src/reset.css
+++ b/packages/core/src/reset.css
@@ -203,35 +203,6 @@
height: auto;
}
- /* ===========================================================================
- AspectRatio Fit Baseline
- =========================================================================== */
-
- /*
- * Child sizing for AspectRatio's `fit` prop — the component marks the
- * child's direct parent with `data-astryx-aspect-ratio-override` (carrying
- * the fit value), and these direct-child rules size the child, so
- * consumers don't hand-write width/height/object-fit on every media child.
- * The marker sits on the parent itself, so the rules don't depend on
- * AspectRatio's internal element structure or its theming surface. As with
- * the [data-astryx-media] baseline below, the rules are zero-specificity
- * and any styling the child sets itself still wins. `fit="center"` needs
- * no rules here — the component centers the child from its own wrapper.
- */
- :where([data-astryx-aspect-ratio-override="cover"], [data-astryx-aspect-ratio-override="contain"])
- > :where(*) {
- width: 100%;
- height: 100%;
- }
-
- :where([data-astryx-aspect-ratio-override="cover"]) > :where(img, video) {
- object-fit: cover;
- }
-
- :where([data-astryx-aspect-ratio-override="contain"]) > :where(img, video) {
- object-fit: contain;
- }
-
/* ===========================================================================
Forms
=========================================================================== */