An open source design system that's fully customizable and agent ready
TypeScript
feat(AspectRatio): responsive ratio — emit ratio as an overridable class-level declaration (#3883)
Jiun Shin0b6762d2733b
diff --git a/.changeset/aspectratio-responsive-ratio.md b/.changeset/aspectratio-responsive-ratio.mdnew file mode 100644index 0000000000..2812e9bfd9--- /dev/null+++ b/.changeset/aspectratio-responsive-ratio.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+'@astryxdesign/cli': patch+---++[feat] AspectRatio: emit `ratio` as a class-level declaration instead of a hard inline style, so the ratio can be overridden responsively: StyleX consumers pass an `aspect-ratio` rule via `xstyle` (including under `@media`/`@container` conditions), and plain-CSS/Tailwind consumers override `aspect-ratio` from their own unlayered rules, which beat the `astryx-base` cascade layer regardless of specificity. The mixed-gallery template's hero now switches 3:1 to 3:2 when the grid stacks with a one-line override on a single element, replacing the duplicated hero markup the fixed inline ratio previously forced (#2798)+@jiunshinndiff --git a/packages/cli/assets/templates/pages/mixed-gallery/page.tsx b/packages/cli/assets/templates/pages/mixed-gallery/page.tsxindex 18e2e87c85..20f40abf5e 100644--- a/packages/cli/assets/templates/pages/mixed-gallery/page.tsx+++ b/packages/cli/assets/templates/pages/mixed-gallery/page.tsx@@ -36,7 +36,11 @@ const clipStyle: CSSProperties = {// 3 columns on desktop, dropping straight to 1 column below 720px (no 2-col// middle state). minmax(0, 1fr) (not 1fr) so tracks split evenly and ignore the// images' intrinsic min-width. The hero spans 2 columns on desktop, then fills-// the row once it's single-column.+// the row once it's single-column — and switches from 3:1 to 3:2 with a plain+// aspect-ratio override. AspectRatio's ratio is a class-level declaration in+// @layer astryx-base, and this <style> tag is unlayered, so the override wins+// regardless of specificity — every stacked tile is uniform without rendering+// the hero twice.const GALLERY_CSS = `.mixed-gallery-grid {display: grid;@@ -52,6 +56,7 @@ const GALLERY_CSS = `}.mixed-gallery-hero {grid-column: 1 / -1;+ aspect-ratio: 3 / 2;}}`;@@ -134,9 +139,13 @@ export default function MixedGalleryTemplate() {of three. Every tile is 3:2 except the hero, which is 3:1 so that(being 2 columns wide) it matches the row height exactly. Allrows are therefore the same height. Responsive via @container:- 3 columns → 1 column at ≤720px. */}+ 3 columns → 1 column at ≤720px, where the hero drops to 3:2 so+ the stacked tiles are uniform. */}<div className="mixed-gallery-grid">- {/* Hero — spans 2 columns; 3:1 keeps it level with the sidebar */}+ {/* Hero — spans 2 columns; 3:1 keeps it level with the sidebar.+ Stacked, the unlayered aspect-ratio override switches it to+ 3:2 (see GALLERY_CSS) — one element, no duplicate hero+ markup. */}<GalleryCardimage={IMAGES[0]}ratio={3 / 1}diff --git a/packages/core/src/AspectRatio/AspectRatio.doc.mjs b/packages/core/src/AspectRatio/AspectRatio.doc.mjsindex f22fc8739e..720db20e00 100644--- a/packages/core/src/AspectRatio/AspectRatio.doc.mjs+++ b/packages/core/src/AspectRatio/AspectRatio.doc.mjs@@ -16,6 +16,7 @@ export const docs = {{guidance: true, description: 'Use `fit="cover"` for images and video so the component sizes the child; the child should not repeat `width`/`height`/`objectFit` styles.'},{guidance: true, description: 'Pass one child. With `fit` set, every direct child is stretched to fill the box, so put an overlay or caption inside a single wrapper child rather than passing it as a second child.'},{guidance: true, description: 'Describe media children with `alt`, or `alt=""` when the image is decorative. AspectRatio adds no role and no accessible name of its own, so the child carries the whole accessible description.'},+ {guidance: true, description: 'For a breakpoint-dependent ratio, override the ratio responsively: pass an `aspectRatio` rule via `xstyle` (StyleX), or override `aspect-ratio` from your own unlayered CSS under a `@media`/`@container` rule — component styles live in the `astryx-base` cascade layer, so unlayered consumer CSS wins. Give an `xstyle` rule a `default` branch alongside the conditional one (`{default: 3, \'@container ...\': \'3 / 2\'}`) — with only the conditional branch the ratio is unset outside the query and the box collapses.'},{guidance: false, description: 'Use for general layout containers; use standard layout components instead.'},{guidance: false, description: 'Nest AspectRatio containers; one level is sufficient.'},{guidance: false, description: 'Constrain the height on its own. The width comes from the container, so a `height` or `maxHeight` by itself clamps the box off ratio; pair it with `width: "auto"` to size from the height instead.'},@@ -30,7 +31,7 @@ export const docs = {{name: 'ratio',type: 'number',- description: 'Aspect ratio as width/height (e.g. 16/9, 1).',+ description: 'Aspect ratio as width/height (e.g. 16/9, 1). Emitted as a class-level declaration (never inline), so `xstyle` rules or unlayered consumer CSS can override it responsively.',required: true,},{@@ -83,6 +84,7 @@ export const docsZh = {{guidance: true, description: 'Use `fit="cover"` for images and video so the component sizes the child; the child should not repeat `width`/`height`/`objectFit` styles.'},{guidance: true, description: 'Pass one child. With `fit` set, every direct child is stretched to fill the box, so put an overlay or caption inside a single wrapper child rather than passing it as a second child.'},{guidance: true, description: 'Describe media children with `alt`, or `alt=""` when the image is decorative. AspectRatio adds no role and no accessible name of its own, so the child carries the whole accessible description.'},+ {guidance: true, description: 'For a breakpoint-dependent ratio, override the ratio responsively: pass an `aspectRatio` rule via `xstyle` (StyleX), or override `aspect-ratio` from your own unlayered CSS under a `@media`/`@container` rule — component styles live in the `astryx-base` cascade layer, so unlayered consumer CSS wins. Give an `xstyle` rule a `default` branch alongside the conditional one (`{default: 3, \'@container ...\': \'3 / 2\'}`) — with only the conditional branch the ratio is unset outside the query and the box collapses.'},{guidance: false, description: 'Use for general layout containers; use standard layout components instead.'},{guidance: false, description: 'Nest AspectRatio containers; one level is sufficient.'},{guidance: false, description: 'Constrain the height on its own. The width comes from the container, so a `height` or `maxHeight` by itself clamps the box off ratio; pair it with `width: "auto"` to size from the height instead.'},@@ -94,7 +96,7 @@ export const docsZh = {],},props: [- {name: 'ratio', type: 'number', description: '宽高比,以宽/高表示(例如 16/9、1)。', required: true},+ {name: 'ratio', type: 'number', description: '宽高比,以宽/高表示(例如 16/9、1)。以类级声明输出(非内联样式),可通过 `xstyle` 规则或未分层的(unlayered)消费者 CSS 做响应式覆盖。', required: true},{name: 'shape',type: "'rectangle' | 'ellipse'",@@ -133,6 +135,7 @@ export const docsDense = {{guidance: true, description: 'Use `fit="cover"` for images and video so the component sizes the child; the child should not repeat `width`/`height`/`objectFit` styles.'},{guidance: true, description: 'Pass one child. With `fit` set, every direct child is stretched to fill the box, so put an overlay or caption inside a single wrapper child rather than passing it as a second child.'},{guidance: true, description: 'Describe media children with `alt`, or `alt=""` when the image is decorative. AspectRatio adds no role and no accessible name of its own, so the child carries the whole accessible description.'},+ {guidance: true, description: 'For a breakpoint-dependent ratio, override the ratio responsively: pass an `aspectRatio` rule via `xstyle` (StyleX), or override `aspect-ratio` from your own unlayered CSS under a `@media`/`@container` rule — component styles live in the `astryx-base` cascade layer, so unlayered consumer CSS wins. Give an `xstyle` rule a `default` branch alongside the conditional one (`{default: 3, \'@container ...\': \'3 / 2\'}`) — with only the conditional branch the ratio is unset outside the query and the box collapses.'},{guidance: false, description: 'Use for general layout containers; use standard layout components instead.'},{guidance: false, description: 'Nest AspectRatio containers; one level is sufficient.'},{guidance: false, description: 'Constrain the height on its own. The width comes from the container, so a `height` or `maxHeight` by itself clamps the box off ratio; pair it with `width: "auto"` to size from the height instead.'},@@ -144,7 +147,7 @@ export const docsDense = {],},propDescriptions: {- ratio: 'width/height ratio (e.g. 16/9, 1)',+ ratio: 'width/height ratio (e.g. 16/9, 1); class-level declaration (never inline) so xstyle/unlayered-CSS @container overrides win',shape: "container shape: 'rectangle' (default) | 'ellipse' (circle at ratio 1)",fit: "child layout: 'cover' fill+crop | 'contain' fill+letterbox | 'center' natural size; omitted = child styles itself",children: 'content positioned absolutely to fill container',diff --git a/packages/core/src/AspectRatio/AspectRatio.test.tsx b/packages/core/src/AspectRatio/AspectRatio.test.tsxindex a791644405..3a25d24e6b 100644--- a/packages/core/src/AspectRatio/AspectRatio.test.tsx+++ b/packages/core/src/AspectRatio/AspectRatio.test.tsx@@ -13,6 +13,20 @@ import {describe, it, expect, vi, beforeAll} from 'vitest';import {render, screen} from '@testing-library/react';import {AspectRatio} from './AspectRatio';+/**+ * The ratio compiles to a class-level `aspect-ratio: var(--x-aspectRatio)`+ * declaration with the value carried by a CSS variable (so xstyle/@media+ * and unlayered consumer CSS overrides can win). `--x-aspectRatio` is the+ * debug-mode variable name emitted for the `aspectRatio` property.+ */+function ratioVar(el: HTMLElement): string {+ return el.style.getPropertyValue('--x-aspectRatio');+}++function ratioValue(ratio: number): string {+ return String(ratio);+}+describe('AspectRatio', () => {it('renders with correct aspect ratio', () => {render(@@ -22,7 +36,7 @@ describe('AspectRatio', () => {);const element = screen.getByTestId('aspect-ratio');expect(element).toBeInTheDocument();- expect(element.style.aspectRatio).toBe(String(16 / 9));+ expect(ratioVar(element)).toBe(ratioValue(16 / 9));});it('children fill the container', () => {@@ -47,7 +61,7 @@ describe('AspectRatio', () => {</AspectRatio>,);const element = screen.getByTestId('aspect-ratio');- expect(element.style.aspectRatio).toBe(String(ratio));+ expect(ratioVar(element)).toBe(ratioValue(ratio));});it('renders with 4:3 ratio', () => {@@ -58,7 +72,7 @@ describe('AspectRatio', () => {</AspectRatio>,);const element = screen.getByTestId('aspect-ratio');- expect(element.style.aspectRatio).toBe(String(ratio));+ expect(ratioVar(element)).toBe(ratioValue(ratio));});it('renders with 1:1 square ratio', () => {@@ -68,7 +82,7 @@ describe('AspectRatio', () => {</AspectRatio>,);const element = screen.getByTestId('aspect-ratio');- expect(element.style.aspectRatio).toBe('1');+ expect(ratioVar(element)).toBe(ratioValue(1));});it('renders with 21:9 ultrawide ratio', () => {@@ -79,7 +93,7 @@ describe('AspectRatio', () => {</AspectRatio>,);const element = screen.getByTestId('aspect-ratio');- expect(element.style.aspectRatio).toBe(String(ratio));+ expect(ratioVar(element)).toBe(ratioValue(ratio));});it('renders an ellipse that respects the ratio (circle at 1:1)', () => {@@ -89,7 +103,7 @@ describe('AspectRatio', () => {</AspectRatio>,);const element = screen.getByTestId('aspect-ratio');- expect(element.style.aspectRatio).toBe('1');+ expect(ratioVar(element)).toBe(ratioValue(1));expect(element.className).toContain('ellipse');});@@ -101,7 +115,7 @@ describe('AspectRatio', () => {);const element = screen.getByTestId('aspect-ratio');// Ratio is preserved — the ellipse does not force 1:1.- expect(element.style.aspectRatio).toBe(String(16 / 9));+ expect(ratioVar(element)).toBe(ratioValue(16 / 9));expect(element.className).toContain('ellipse');});@@ -112,7 +126,7 @@ describe('AspectRatio', () => {</AspectRatio>,);const element = screen.getByTestId('aspect-ratio');- expect(element.style.aspectRatio).toBe('1');+ expect(ratioVar(element)).toBe(ratioValue(1));expect(element.className).toContain('rectangle');// No ellipse border-radius when shape is the default rectangleexpect(element.style.borderRadius).toBe('');@@ -177,6 +191,38 @@ describe('AspectRatio', () => {expect(video).toBeInTheDocument();});+ describe('responsive ratio', () => {+ it('emits the ratio as a class-level declaration, not an inline style', () => {+ render(+ <AspectRatio ratio={3 / 1} data-testid="aspect-ratio">+ <div>Hero</div>+ </AspectRatio>,+ );+ const element = screen.getByTestId('aspect-ratio');+ // No inline aspect-ratio — the declaration lives in a class reading a+ // CSS variable, so @media/@container rules (via xstyle, or via+ // unlayered consumer CSS beating the astryx-base layer) can override+ // it.+ expect(element.style.aspectRatio).toBe('');+ expect(ratioVar(element)).toBe(ratioValue(3 / 1));+ });++ it('lets a consumer inline style win over the class-level ratio', () => {+ render(+ <AspectRatio+ ratio={3 / 1}+ style={{aspectRatio: '3 / 2'}}+ data-testid="aspect-ratio">+ <div>Hero</div>+ </AspectRatio>,+ );+ const element = screen.getByTestId('aspect-ratio');+ // The consumer's style prop passes through untouched (it is no longer+ // merged with a component-owned inline aspect-ratio).+ expect(element.style.aspectRatio).toBe('3 / 2');+ });+ });+describe('fit', () => {it('marks the child\'s direct parent with data-astryx-aspect-ratio-override for fit="cover"', () => {render(@@ -277,7 +323,7 @@ describe('AspectRatio', () => {});describe('style merging', () => {- it('keeps the consumer style and applies the ratio over it', () => {+ it('keeps the consumer style and lets an inline ratio win', () => {render(<AspectRatioratio={16 / 9}@@ -288,7 +334,8 @@ describe('AspectRatio', () => {);const element = screen.getByTestId('aspect-ratio');expect(element.style.opacity).toBe('0.5');- expect(element.style.aspectRatio).toBe(String(16 / 9));+ expect(element.style.aspectRatio).toBe('3 / 1');+ expect(ratioVar(element)).toBe(ratioValue(16 / 9));});it('keeps a consumer className beside the theme target', () => {diff --git a/packages/core/src/AspectRatio/AspectRatio.tsx b/packages/core/src/AspectRatio/AspectRatio.tsxindex 0b70f541a4..4b1a52314a 100644--- a/packages/core/src/AspectRatio/AspectRatio.tsx+++ b/packages/core/src/AspectRatio/AspectRatio.tsx@@ -43,6 +43,25 @@ export interface AspectRatioProps extends BaseProps<HTMLDivElement> {ref?: React.Ref<HTMLDivElement>;/*** The aspect ratio as width/height (e.g., 16/9 = 1.777..., 4/3 = 1.333..., 1 for square).+ *+ * The ratio is emitted as a class-level declaration — never an inline+ * style — so it can be made responsive:+ * - StyleX consumers pass an `aspect-ratio` rule via `xstyle`, including+ * under `@media`/`@container` conditions.+ * - Plain-CSS/Tailwind consumers override `aspect-ratio` from their own+ * (unlayered) rules: the compiled component styles live in the+ * `astryx-base` cascade layer, and unlayered CSS wins over layered+ * rules regardless of specificity.+ *+ * @example+ * ```+ * // 3:1 hero that becomes 3:2 when its container stacks+ * <AspectRatio ratio={3 / 1} className="gallery-hero">…</AspectRatio>+ *+ * // CSS: @container gallery (max-width: 720px) {+ * // .gallery-hero { aspect-ratio: 3 / 2; }+ * // }+ * ```*/ratio: number;@@ -132,6 +151,20 @@ const styles = stylex.create({},});+// The ratio compiles to a CSS variable + a class-level declaration+// (aspect-ratio: var(--x)) instead of a raw inline style, so consumer+// overrides — `xstyle` rules, including ones inside @media/@container+// queries — can still win. A raw inline `aspect-ratio` would beat any class+// (same rationale as Grid's dynamic track values). Non-StyleX consumers+// don't need a dedicated hook: the compiled declaration sits in the+// `astryx-base` cascade layer, so any unlayered consumer rule wins+// regardless of specificity.+const dynamicStyles = stylex.create({+ ratio: (ratio: number) => ({+ aspectRatio: ratio,+ }),+});+/*** AspectRatio component for maintaining a specific aspect ratio for its children.*@@ -147,6 +180,11 @@ const styles = stylex.create({* `ratio={1}` or an oval at other ratios. Both shapes respect the provided* `ratio`.*+ * The ratio is a class-level declaration (not an inline style), so it can be+ * overridden responsively — via `xstyle` for StyleX consumers, or with a+ * plain unlayered `aspect-ratio` rule for plain-CSS consumers (component+ * styles live in the `astryx-base` cascade layer, which unlayered CSS beats).+ ** Sizing: the box takes its width from its container and derives its height* from the ratio, so it needs an ancestor with a definite width. Two* consequences are worth knowing. Constraining only the height (`height` or@@ -188,11 +226,12 @@ export function AspectRatio({themeProps('aspect-ratio', {shape}),stylex.props(styles.container,+ dynamicStyles.ratio(ratio),shape === 'ellipse' && styles.ellipse,xstyle,),className,- {...style, aspectRatio: ratio},+ style,)}{...props}>{/* The marker attribute carries the fit value so the reset.css child