An open source design system that's fully customizable and agent ready
TypeScript
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
* @file BottomSheetPanel.test.tsx
* @input Uses vitest, Testing Library, BottomSheetPanel
* @output Tests the shared sheet surface motion, keyboard scroll, and container
* padding contracts
* @position Internal presentation tests shared by standalone and switcher modes
*/
import * as stylex from '@stylexjs/stylex';
import {act, fireEvent, render, screen} from '@testing-library/react';
import {Suspense, use, useLayoutEffect} from 'react';
import {renderToString} from 'react-dom/server';
import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
import {
BottomSheetPanel,
type BottomSheetPanelMotion,
type BottomSheetPanelState,
} from './BottomSheetPanel';
const panelTransitionStyle = {
transitionProperty: 'transform, opacity',
transitionDuration: '410ms',
transitionDelay: '0ms',
};
beforeEach(() => {
vi.stubGlobal(
'matchMedia',
vi.fn().mockReturnValue({
matches: false,
media: '',
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
}),
);
});
afterEach(() => {
vi.unstubAllGlobals();
});
// A device with a touch pointer: only `(any-pointer: coarse)` matches.
function stubTouchPointer() {
vi.stubGlobal(
'matchMedia',
vi.fn((query: string) => ({
matches: query === '(any-pointer: coarse)',
media: query,
onchange: null,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
);
}
function renderPanel(
state: BottomSheetPanelState,
callbacks: {
onMotionStart?: (motion: BottomSheetPanelMotion) => void;
onMotionComplete?: (motion: BottomSheetPanelMotion) => void;
} = {},
) {
return render(
<BottomSheetPanel
label="Sheet details"
state={state}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}
onMotionStart={callbacks.onMotionStart}
onMotionComplete={callbacks.onMotionComplete}>
Panel content
</BottomSheetPanel>,
);
}
function renderNamedPanel(name: string) {
return render(
<BottomSheetPanel
label={name}
state={{kind: 'open', entering: false}}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
{name} content
</BottomSheetPanel>,
);
}
function getNamedPanel(name: string): HTMLElement {
const panel = screen
.getByText(`${name} content`)
.closest<HTMLElement>('.astryx-bottom-sheet');
if (panel == null) {
throw new Error(`${name} surface not found`);
}
return panel;
}
// Counts reads of `window.innerHeight` until `restore`. A read after a
// commit's DOM writes forces a style recalculation and a layout.
function countViewportHeightReads() {
const descriptor = Object.getOwnPropertyDescriptor(window, 'innerHeight');
let value = window.innerHeight;
const reads = {
count: 0,
restore: () => {
if (descriptor != null) {
Object.defineProperty(window, 'innerHeight', descriptor);
}
window.innerHeight = value;
},
};
Object.defineProperty(window, 'innerHeight', {
configurable: true,
get: () => {
reads.count += 1;
return value;
},
set: next => {
value = next;
},
});
return reads;
}
// Tracks the `resize` listeners on `window` until `restore`. `attached` is
// the number added and not yet removed.
function trackResizeListeners() {
const add = vi.spyOn(window, 'addEventListener');
const remove = vi.spyOn(window, 'removeEventListener');
return {
attached: () => {
const events = [
...add.mock.calls.map((call, index) => ({
type: call[0],
listener: call[1],
order: add.mock.invocationCallOrder[index] ?? 0,
isAdd: true,
})),
...remove.mock.calls.map((call, index) => ({
type: call[0],
listener: call[1],
order: remove.mock.invocationCallOrder[index] ?? 0,
isAdd: false,
})),
].sort((a, b) => a.order - b.order);
const live = new Set<unknown>();
for (const event of events) {
if (event.type !== 'resize') {
continue;
}
if (event.isAdd) {
live.add(event.listener);
} else {
live.delete(event.listener);
}
}
return live.size;
},
restore: () => {
add.mockRestore();
remove.mockRestore();
},
};
}
function getPanel(): HTMLElement {
const panel = screen
.getByText('Panel content')
.closest<HTMLElement>('.astryx-bottom-sheet');
if (panel == null) {
throw new Error('BottomSheetPanel surface not found');
}
return panel;
}
const callerSizeStyles = stylex.create({
height: {height: 500},
maxHeight: {maxHeight: 500},
color: {color: 'rebeccapurple'},
});
describe('BottomSheetPanel', () => {
it('keeps 40% of the viewport of its surface below the screen, for the whole stretch past the top', () => {
stubTouchPointer();
renderPanel({kind: 'open', entering: false});
// A finger's rubber band over a sheet as tall as the viewport shows at
// most 35.5% of the viewport.
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe(
`${Math.ceil(window.innerHeight * 0.4)}px`,
);
});
it('keeps the smallest reserve, 48 px, under a height the caller sets, on a device with a touch pointer', () => {
// Nothing extends a caller's height by the reserve, so a deeper one would
// hide that much more of the sheet below the screen.
stubTouchPointer();
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
style={{...panelTransitionStyle, height: 500}}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');
});
it('keeps the smallest reserve, 48 px, under a size the caller sets through xstyle, on a device with a touch pointer', () => {
stubTouchPointer();
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
style={panelTransitionStyle}
xstyle={callerSizeStyles.height}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');
});
it('keeps the smallest reserve, 48 px, under a maximum size in an xstyle array, on a device with a touch pointer', () => {
stubTouchPointer();
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
style={panelTransitionStyle}
xstyle={[callerSizeStyles.color, callerSizeStyles.maxHeight]}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');
});
it('keeps the smallest reserve, 48 px, under a class name the caller passes, on a device with a touch pointer', () => {
// A class name's rules can size the sheet, and nothing can read them.
stubTouchPointer();
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
className="caller-sheet"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');
});
it('keeps the smallest reserve, 48 px, under any xstyle, whose rules nothing can read, on a device with a touch pointer', () => {
stubTouchPointer();
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
style={panelTransitionStyle}
xstyle={callerSizeStyles.color}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');
});
it('keeps the viewport reserve under an empty xstyle and a style that does not size the sheet, on a device with a touch pointer', () => {
stubTouchPointer();
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
style={{...panelTransitionStyle, color: 'rebeccapurple'}}
xstyle={[false, undefined]}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).not.toBe(
'48px',
);
});
it('keeps the smallest reserve, 48 px, on a device with no touch pointer', () => {
renderPanel({kind: 'open', entering: false});
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe('48px');
});
it('follows the viewport with its reserve while it is presented', () => {
const viewportHeight = window.innerHeight;
stubTouchPointer();
renderPanel({kind: 'open', entering: false});
try {
act(() => {
window.innerHeight = 1000;
window.dispatchEvent(new Event('resize'));
});
expect(getPanel().style.getPropertyValue('--_sheet-reserve')).toBe(
'400px',
);
} finally {
window.innerHeight = viewportHeight;
}
});
it('reads the viewport height from its resize listener, not from layout, when it renders again', () => {
stubTouchPointer();
const {rerender} = renderPanel({kind: 'open', entering: false});
const reads = countViewportHeightReads();
try {
rerender(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content, changed
</BottomSheetPanel>,
);
expect(screen.getByText('Panel content, changed')).toBeTruthy();
expect(reads.count).toBe(0);
} finally {
reads.restore();
}
});
it('shares one viewport height among open sheets, and forgets it when the last one closes', () => {
const viewportHeight = window.innerHeight;
const listeners = trackResizeListeners();
stubTouchPointer();
try {
const first = renderNamedPanel('First sheet');
const second = renderNamedPanel('Second sheet');
act(() => {
window.innerHeight = 1000;
window.dispatchEvent(new Event('resize'));
});
expect(
getNamedPanel('First sheet').style.getPropertyValue('--_sheet-reserve'),
).toBe('400px');
expect(
getNamedPanel('Second sheet').style.getPropertyValue(
'--_sheet-reserve',
),
).toBe('400px');
first.unmount();
act(() => {
window.innerHeight = 900;
window.dispatchEvent(new Event('resize'));
});
expect(
getNamedPanel('Second sheet').style.getPropertyValue(
'--_sheet-reserve',
),
).toBe('360px');
second.unmount();
expect(listeners.attached()).toBe(0);
// With no sheet open, a resize reads nothing.
const reads = countViewportHeightReads();
try {
act(() => {
window.innerHeight = 700;
window.dispatchEvent(new Event('resize'));
});
expect(reads.count).toBe(0);
} finally {
reads.restore();
}
// Nothing kept the height meanwhile, so the next sheet reads the
// viewport in its first commit.
let firstReserve = '';
function FirstCommit() {
useLayoutEffect(() => {
firstReserve =
getNamedPanel('Third sheet').style.getPropertyValue(
'--_sheet-reserve',
);
}, []);
return null;
}
render(
<>
<BottomSheetPanel
label="Third sheet"
state={{kind: 'open', entering: false}}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Third sheet content
</BottomSheetPanel>
<FirstCommit />
</>,
);
expect(firstReserve).toBe('280px');
} finally {
listeners.restore();
window.innerHeight = viewportHeight;
}
});
it('reads the viewport again after a render that never commits', async () => {
const viewportHeight = window.innerHeight;
stubTouchPointer();
const never = new Promise<never>(() => {});
function Suspend(): null {
use(never);
return null;
}
try {
window.innerHeight = 900;
const suspended = await act(async () =>
render(
<Suspense fallback={null}>
<BottomSheetPanel
label="Hidden sheet"
state={{kind: 'open', entering: false}}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Hidden sheet content
</BottomSheetPanel>
<Suspend />
</Suspense>,
),
);
expect(screen.queryByText('Hidden sheet content')).toBeNull();
suspended.unmount();
// No listener watched the viewport since that render.
window.innerHeight = 650;
let firstReserve = '';
function FirstCommit() {
useLayoutEffect(() => {
firstReserve =
getNamedPanel('Next sheet').style.getPropertyValue(
'--_sheet-reserve',
);
}, []);
return null;
}
render(
<>
<BottomSheetPanel
label="Next sheet"
state={{kind: 'open', entering: false}}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Next sheet content
</BottomSheetPanel>
<FirstCommit />
</>,
);
expect(firstReserve).toBe('260px');
} finally {
window.innerHeight = viewportHeight;
}
});
it('renders on the server without reading the viewport', () => {
stubTouchPointer();
const reads = countViewportHeightReads();
try {
const html = renderToString(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
expect(html).toContain('Panel content');
expect(reads.count).toBe(0);
} finally {
reads.restore();
}
});
it('reports entrance completion only for the surface transform', () => {
const onMotionStart = vi.fn();
const onMotionComplete = vi.fn();
renderPanel(
{kind: 'open', entering: true},
{onMotionStart, onMotionComplete},
);
expect(onMotionStart).toHaveBeenCalledWith('entering');
fireEvent.transitionEnd(getPanel(), {propertyName: 'opacity'});
expect(onMotionComplete).not.toHaveBeenCalled();
fireEvent.transitionEnd(getPanel(), {propertyName: 'transform'});
expect(onMotionComplete).toHaveBeenCalledWith('entering');
});
it('completes a retained-sheet reactivation without waiting for a new entrance', () => {
const onMotionComplete = vi.fn();
const {rerender} = render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'retained', motion: 'covered', alignmentOffset: 0}}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}
onMotionComplete={onMotionComplete}>
Panel content
</BottomSheetPanel>,
);
rerender(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: true}}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}
onMotionComplete={onMotionComplete}>
Panel content
</BottomSheetPanel>,
);
expect(onMotionComplete).toHaveBeenCalledWith('entering');
});
it('applies the switcher alignment offset to a retained surface', () => {
renderPanel({
kind: 'retained',
motion: 'aligning',
alignmentOffset: 120,
});
expect(getPanel()).toHaveStyle({transform: 'translateY(120px)'});
});
it('maps exit and fade completion to their respective CSS properties', () => {
const onMotionComplete = vi.fn();
const {rerender} = renderPanel(
{kind: 'retained', motion: 'fading', alignmentOffset: 0},
{onMotionComplete},
);
fireEvent.transitionEnd(getPanel(), {propertyName: 'opacity'});
expect(onMotionComplete).toHaveBeenLastCalledWith('fading');
rerender(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'exiting'}}
height="hug"
style={panelTransitionStyle}
onDismiss={() => {}}
onScrimOpacity={() => {}}
onMotionComplete={onMotionComplete}>
Panel content
</BottomSheetPanel>,
);
fireEvent.transitionEnd(getPanel(), {propertyName: 'transform'});
expect(onMotionComplete).toHaveBeenLastCalledWith('exiting');
});
it('keeps exiting when the engine replaces the exit transition mid-flight', () => {
const onMotionComplete = vi.fn();
renderPanel({kind: 'exiting'}, {onMotionComplete});
const panel = getPanel();
// Chromium cancels a running transition whose end value changes, and
// starts one from where it was. The exit's percentage transform changes
// when the closing frame moves the sheet's height by a fraction of a pixel.
panel.getAnimations = () =>
[{transitionProperty: 'transform', playState: 'running'}] as never;
fireEvent.transitionCancel(panel, {propertyName: 'transform'});
expect(onMotionComplete).not.toHaveBeenCalled();
panel.getAnimations = () => [];
fireEvent.transitionEnd(panel, {propertyName: 'transform'});
expect(onMotionComplete).toHaveBeenCalledWith('exiting');
});
it('ends the exit when its transition is cancelled with nothing running on', () => {
const onMotionComplete = vi.fn();
renderPanel({kind: 'exiting'}, {onMotionComplete});
const panel = getPanel();
panel.getAnimations = () => [];
fireEvent.transitionCancel(panel, {propertyName: 'transform'});
expect(onMotionComplete).toHaveBeenCalledWith('exiting');
});
it('completes immediately when the rendered transition is disabled', () => {
// The stylesheet decides reduced motion (its transform transition
// collapses under the preference); the gesture hook no longer pins an
// inline `none` for it, so this models a rendered `transition: none`
// directly, as a mid-drag reconcile writes.
const nativeGetComputedStyle = window.getComputedStyle;
const spy = vi
.spyOn(window, 'getComputedStyle')
.mockImplementation((element, pseudo) => {
const declaration = nativeGetComputedStyle(element, pseudo);
if (
element instanceof HTMLElement &&
element.classList.contains('astryx-bottom-sheet')
) {
Object.defineProperty(declaration, 'transition', {
value: 'none',
configurable: true,
});
}
return declaration;
});
const onMotionComplete = vi.fn();
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: true}}
height="hug"
onDismiss={() => {}}
onScrimOpacity={() => {}}
onMotionComplete={onMotionComplete}>
Panel content
</BottomSheetPanel>,
);
expect(onMotionComplete).toHaveBeenCalledWith('entering');
spy.mockRestore();
});
it('derives its transition backstop from the rendered timing', () => {
vi.useFakeTimers();
try {
const onMotionComplete = vi.fn();
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: true}}
height="hug"
style={{
transitionProperty: 'transform, opacity',
transitionDuration: '0.5s, 200ms',
transitionDelay: '100ms, 0ms',
}}
onDismiss={() => {}}
onScrimOpacity={() => {}}
onMotionComplete={onMotionComplete}>
Panel content
</BottomSheetPanel>,
);
void act(() => vi.advanceTimersByTime(649));
expect(onMotionComplete).not.toHaveBeenCalled();
void act(() => vi.advanceTimersByTime(1));
expect(onMotionComplete).toHaveBeenCalledWith('entering');
} finally {
vi.useRealTimers();
}
});
it('does not detach a stable public ref during an ordinary rerender', () => {
const panelRef = vi.fn();
const {rerender, unmount} = render(
<BottomSheetPanel
label="Sheet details"
ref={panelRef}
state={{kind: 'open', entering: false}}
height="hug"
onDismiss={() => {}}
onScrimOpacity={() => {}}>
First render
</BottomSheetPanel>,
);
expect(panelRef).toHaveBeenCalledTimes(1);
rerender(
<BottomSheetPanel
label="Sheet details"
ref={panelRef}
state={{kind: 'open', entering: false}}
height="hug"
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Second render
</BottomSheetPanel>,
);
expect(panelRef).toHaveBeenCalledTimes(1);
unmount();
expect(panelRef).toHaveBeenLastCalledWith(null);
expect(panelRef).toHaveBeenCalledTimes(2);
});
it('floats the handle bar over content that starts at the sheet top edge', () => {
renderPanel({kind: 'open', entering: false});
const bar = getPanel().querySelector<HTMLElement>(
'div[aria-hidden="true"]',
);
if (bar == null) {
throw new Error('handle bar not found');
}
const body = bar.nextElementSibling as HTMLElement;
// Out of flow: the bar costs the content no layout space. That is the
// point of it -- the content sits closer to the sheet's top edge, and
// scrolled content passes beneath the pill rather than stopping at a
// hard edge.
expect(getComputedStyle(bar).position).toBe('absolute');
// So the body must not reserve room for it. A top padding here would
// push the content back down and undo the change.
expect(getComputedStyle(body).paddingTop).toBe('');
});
// The pill is only legible over the content riding up beneath it because
// the bar carries a backdrop; without it, text runs straight through the
// pill. jsdom's StyleX runtime does not inject the rule, so assert on the
// style definition itself (same approach as AspectRatio's reset.css tests).
it('backs the floating handle bar with a surface gradient', async () => {
const fs = await import('fs');
const path = await import('path');
const source = fs.readFileSync(
path.resolve(__dirname, './BottomSheetPanel.tsx'),
'utf-8',
);
const handleBar = source.match(/handleBar: \{([\s\S]*?)\n {2}\},/);
expect(handleBar).not.toBeNull();
expect(handleBar![1]).toContain("position: 'absolute'");
expect(handleBar![1]).toContain('linear-gradient(to bottom');
expect(handleBar![1]).toContain("colorVars['--color-background-surface']");
});
// While the sheet's transform animates between detents, WebKit can draw the
// bar under the scrolling body. The pill then vanishes until the sheet rests.
// This is asserted on the style definition, as the test above is.
it('gives the floating handle bar a compositing layer of its own', async () => {
const fs = await import('fs');
const path = await import('path');
const source = fs.readFileSync(
path.resolve(__dirname, './BottomSheetPanel.tsx'),
'utf-8',
);
const handleBar = source.match(/handleBar: \{([\s\S]*?)\n {2}\},/);
expect(handleBar).not.toBeNull();
expect(handleBar![1]).toContain("willChange: 'transform'");
});
// In dark mode the surface fill and the scrim sit a few RGB steps apart and
// the drop shadow is black on near-black, so the fill alone leaves the
// sheet's left and right edges invisible against the scrim. A hairline on
// the scrim-facing edges is what draws them. Asserted on the style
// definition for the same reason as the test above.
it('draws a hairline on the three edges that face the scrim', async () => {
const fs = await import('fs');
const path = await import('path');
const source = fs.readFileSync(
path.resolve(__dirname, './BottomSheetPanel.tsx'),
'utf-8',
);
const sheet = source.match(/\n {2}sheet: \{([\s\S]*?)\n {2}\},/);
expect(sheet).not.toBeNull();
for (const edge of [
'borderBlockStart',
'borderInlineStart',
'borderInlineEnd',
]) {
expect(sheet![1]).toContain(`${edge}Width: borderVars['--border-width']`);
expect(sheet![1]).toContain(`${edge}Style: 'solid'`);
expect(sheet![1]).toContain(`${edge}Color: colorVars['--color-border']`);
}
// The block-end edge sits below the viewport, under the overscroll
// padding, so it carries no hairline to draw.
expect(sheet![1]).not.toContain('borderBlockEndWidth');
});
// A theme that packs an inset ring into --shadow-high (the bundled themes all
// add one in dark mode) draws it just inside the sheet, where an opaque
// content wrapper such as Section paints over it -- so it showed only in the
// gap below the content and the side edges appeared to change width partway
// down. The scrolling body paints the surface across the whole inner box to
// hide the ring evenly.
it('paints the surface across the scrolling body so the edge stays uniform', async () => {
const fs = await import('fs');
const path = await import('path');
const source = fs.readFileSync(
path.resolve(__dirname, './BottomSheetPanel.tsx'),
'utf-8',
);
const body = source.match(/\n {2}body: \{([\s\S]*?)\n {2}\},/);
expect(body).not.toBeNull();
expect(body![1]).toContain(
"backgroundColor: colorVars['--color-background-surface']",
);
});
/**
* The exit is not the entrance played backwards.
*
* `--ease-standard` is a decelerate curve: on it the sheet was half gone in
* 59ms of a 410ms transition and 90% gone in 163ms, so the close was over
* before it could be seen. The closing state therefore reads the
* accelerating `--ease-exit` curve (its default is pinned in
* theme/tokens.test.ts), and only the closing state does. A touch
* presentation keeps its own curve, which the exit tokens do not change
* (spec:AST-090 FR12).
*/
it('closes on the exit curve, not the entrance timing', () => {
const declarationsFor = (element: HTMLElement) => {
const classes = new Set(element.className.split(/\s+/));
const out: string[] = [];
for (const styleSheet of Array.from(document.styleSheets)) {
let rules: CSSRuleList;
try {
rules = styleSheet.cssRules;
} catch {
continue;
}
for (const rule of Array.from(rules)) {
const selector = (rule as CSSStyleRule).selectorText;
const owner = selector?.match(/^\.([\w-]+)/)?.[1];
if (owner != null && classes.has(owner)) {
out.push(rule.cssText);
}
}
}
return out.join('\n');
};
// The rules inside an `@media` block with the given condition.
const mediaDeclarationsFor = (element: HTMLElement, condition: string) => {
const classes = new Set(element.className.split(/\s+/));
const out: string[] = [];
for (const styleSheet of Array.from(document.styleSheets)) {
let rules: CSSRuleList;
try {
rules = styleSheet.cssRules;
} catch {
continue;
}
for (const rule of Array.from(rules)) {
if (
!(rule instanceof CSSMediaRule) ||
rule.media.mediaText.replace(/\s/g, '') !== condition
) {
continue;
}
for (const inner of Array.from(rule.cssRules)) {
const selector = (inner as CSSStyleRule).selectorText;
const owner = selector?.match(/^\.([\w-]+)/)?.[1];
if (owner != null && classes.has(owner)) {
out.push(inner.cssText);
}
}
}
}
return out.join('\n');
};
const {container: closing} = render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'exiting'}}
height="hug"
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
const closingSheet = closing.querySelector(
'.astryx-bottom-sheet',
) as HTMLElement;
const closingRules = declarationsFor(closingSheet);
// The theme's exit curve, not a curve restated locally.
expect(closingRules).toContain(
'transition-timing-function: var(--ease-exit)',
);
expect(closingRules).not.toContain('cubic-bezier(.3,0,.6,.6)');
// Under a coarse pointer the close keeps its own curve, so a theme's
// `--ease-exit` does not reach a touch presentation.
const coarseClosingRules = mediaDeclarationsFor(
closingSheet,
'(pointer:coarse)',
);
expect(coarseClosingRules).toContain(
'transition-timing-function: cubic-bezier(.3,0,.6,.6)',
);
expect(coarseClosingRules).not.toContain('--ease-exit');
const {container: resting} = render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
onDismiss={() => {}}
onScrimOpacity={() => {}}>
Panel content
</BottomSheetPanel>,
);
const restingRules = declarationsFor(
resting.querySelector('.astryx-bottom-sheet') as HTMLElement,
);
expect(restingRules).toContain(
'transition-timing-function: var(--ease-standard)',
);
expect(restingRules).not.toContain('--ease-exit');
});
describe('container padding', () => {
// StyleX lowers the block edges to their physical properties.
const EDGES = [
['inline-start', 'padding-inline-start'],
['inline-end', 'padding-inline-end'],
['block-start', 'padding-top'],
['block-end', 'padding-bottom'],
] as const;
// The block-start inset never drops below the grab bar's height, so
// resting content starts below the bar. The block start publishes only the
// padding past that band; the other edges publish what they apply.
function renderWithPadding(padding?: 0 | 2) {
render(
<BottomSheetPanel
label="Sheet details"
state={{kind: 'open', entering: false}}
height="hug"
padding={padding}
onDismiss={() => {}}
onScrimOpacity={() => {}}>
<span data-testid="sheet-child">Panel content</span>
</BottomSheetPanel>,
);
// The content box is the child's parent: the observed box inside the
// scrolling body, not the body itself.
return getComputedStyle(screen.getByTestId('sheet-child').parentElement!);
}
// The band under the grab bar is applied on top of the published
// block-start, which is only the padding past the band: a lone Section
// escapes that and still starts below the bar (component:BottomSheet,
// Content area inset).
const BAND =
'calc(var(--container-padding-block-start,0px)+var(--spacing-6))';
it("pads by Dialog's default chain and publishes the inset it applies", () => {
const computed = renderWithPadding();
for (const [edge, property] of EDGES) {
const published = computed
.getPropertyValue(`--container-padding-${edge}`)
.replace(/\s+/g, '');
expect(published, edge).toContain(
`var(--astryx-bottom-sheet-padding-${edge}`,
);
expect(published, edge).toContain(
'var(--astryx-bottom-sheet-padding,var(--spacing-4))',
);
if (edge === 'block-start') {
expect(published, edge).toMatch(
/^max\(calc\(.*-var\(--spacing-6\)\),0px\)$/,
);
expect(
computed.getPropertyValue(property).replace(/\s+/g, ''),
edge,
).toBe(BAND);
continue;
}
// Applied padding reads the published value, so bleed children
// subtract exactly the inset they sit in.
expect(computed.getPropertyValue(property), edge).toBe(
`var(--container-padding-${edge})`,
);
}
for (const name of [
'--layout-padding-outer-x',
'--layout-padding-outer-y',
'--layout-padding-inner-x',
'--layout-padding-inner-y',
]) {
expect(
computed.getPropertyValue(name).replace(/\s+/g, ''),
name,
).toContain('var(--astryx-bottom-sheet-padding,var(--spacing-4))');
}
});
it.each([0, 2] as const)(
'applies and publishes an explicit padding step (%s)',
padding => {
const computed = renderWithPadding(padding);
const expected = `var(--spacing-${padding})`;
for (const [edge, property] of EDGES) {
const published =
edge === 'block-start'
? `max(calc(${expected} - var(--spacing-6)), 0px)`
: expected;
expect(
computed
.getPropertyValue(`--container-padding-${edge}`)
.replace(/\s+/g, ''),
edge,
).toBe(published.replace(/\s+/g, ''));
expect(
computed.getPropertyValue(property).replace(/\s+/g, ''),
edge,
).toBe(edge === 'block-start' ? BAND : expected.replace(/\s+/g, ''));
}
expect(computed.getPropertyValue('--layout-padding-inner-x')).toBe(
expected,
);
},
);
it('keeps the panel itself unpadded and free of a padding attribute', () => {
renderWithPadding(2);
const panel = getPanel();
expect(panel.hasAttribute('padding')).toBe(false);
expect(
getComputedStyle(panel).getPropertyValue(
'--container-padding-inline-start',
),
).toBe('0px');
});
});
});