Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Significance: patch
Type: changed

Metric cards: Draw the cards on their own tabs primitive, taking the design system’s hover, selected and focus states.
14 changes: 14 additions & 0 deletions projects/packages/premium-analytics/eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,14 @@ export default defineConfig(
message:
'Import these from @jetpack-premium-analytics/externals instead: it compiles them once into a shared script module rather than into every module that imports them. Missing an export? Add it to packages/externals/src/index.ts.',
},
{
// Base UI is what `@wordpress/ui` builds on, so `externals`
// already compiles it in: importing it anywhere else
// compiles a second copy.
regex: '^@base-ui/react(/.*)?$',
message:
'Build on @wordpress/ui from @jetpack-premium-analytics/externals, or on CardTabs from @jetpack-premium-analytics/ui. A primitive that needs Base UI itself takes it from externals, which already compiles it in behind @wordpress/ui.',
},
],
},
],
Expand Down Expand Up @@ -209,6 +217,12 @@ export default defineConfig(
message:
'Import these from @jetpack-premium-analytics/externals instead: it compiles them once into a shared script module rather than into every bundle that imports them. Missing an export? Add it to packages/externals/src/index.ts.',
},
{
// Same as the packages rule above.
regex: '^@base-ui/react(/.*)?$',
message:
'Build on @wordpress/ui from @jetpack-premium-analytics/externals, or on CardTabs from @jetpack-premium-analytics/ui. A primitive that needs Base UI itself takes it from externals, which already compiles it in behind @wordpress/ui.',
},
],
},
],
Expand Down
1 change: 1 addition & 0 deletions projects/packages/premium-analytics/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
"@automattic/jetpack-connection": "workspace:*",
"@automattic/jetpack-script-data": "workspace:*",
"@automattic/number-formatters": "workspace:*",
"@base-ui/react": "1.9.0",
"@date-fns/tz": "1.5.0",
"@jetpack-premium-analytics/data": "link:packages/data",
"@jetpack-premium-analytics/datetime": "link:packages/datetime",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,15 @@ export {
VisuallyHidden,
} from '@wordpress/ui';

/**
* Base UI
*
* The unstyled parts `@wordpress/ui` is built on, so they are already compiled
* in here. Prefixed because `Tabs` above is the design system's styled one.
*/
export { DirectionProvider as BaseDirectionProvider } from '@base-ui/react/direction-provider';
export { Tabs as BaseTabs } from '@base-ui/react/tabs';

/**
* DataViews
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { isRTL } from '@wordpress/i18n';
import { act } from 'react';
import { CardTabs } from '../index';

jest.mock( '@wordpress/i18n', () => ( {
...jest.requireActual( '@wordpress/i18n' ),
isRTL: jest.fn( () => false ),
} ) );

const METRICS = [
{ key: 'orders', label: 'Orders' },
{ key: 'visitors', label: 'Visitors' },
{ key: 'revenue', label: 'Revenue' },
];

function renderCardTabs( { disabledKey }: { disabledKey?: string } = {} ) {
const onValueChange = jest.fn();

render(
<CardTabs.Root value="visitors" onValueChange={ onValueChange }>
<CardTabs.List aria-label="Select metric">
{ METRICS.map( metric => (
<CardTabs.Tab
key={ metric.key }
value={ metric.key }
disabled={ metric.key === disabledKey }
>
{ metric.label }
</CardTabs.Tab>
) ) }
</CardTabs.List>
{ METRICS.map( metric => (
<CardTabs.Panel key={ metric.key } value={ metric.key }>
{ metric.label } chart
</CardTabs.Panel>
) ) }
</CardTabs.Root>
);

return { onValueChange };
}

describe( 'CardTabs', () => {
beforeEach( () => {
jest.mocked( isRTL ).mockReturnValue( false );
} );

it( 'shows the selected card’s panel, labelled by the card, and reports a click on another', async () => {
const user = userEvent.setup();
const { onValueChange } = renderCardTabs();

const selected = screen.getByRole( 'tab', { name: 'Visitors' } );
expect( selected ).toHaveAttribute( 'aria-selected', 'true' );
expect( screen.getByRole( 'tabpanel' ) ).toHaveAttribute( 'aria-labelledby', selected.id );
expect( screen.getByRole( 'tabpanel' ) ).toHaveTextContent( 'Visitors chart' );
expect( screen.queryByText( 'Orders chart' ) ).not.toBeInTheDocument();

await user.click( screen.getByRole( 'tab', { name: 'Orders' } ) );

expect( onValueChange ).toHaveBeenCalledWith( 'orders', expect.anything() );
} );

it( 'moves between cards with the arrow keys and selects only on Enter', async () => {
const user = userEvent.setup();
const { onValueChange } = renderCardTabs( { disabledKey: 'revenue' } );

act( () => screen.getByRole( 'tab', { name: 'Visitors' } ).focus() );
await user.keyboard( '{ArrowLeft}' );

expect( screen.getByRole( 'tab', { name: 'Orders' } ) ).toHaveFocus();
expect( onValueChange ).not.toHaveBeenCalled();

await user.keyboard( '{Enter}' );

expect( onValueChange ).toHaveBeenCalledWith( 'orders', expect.anything() );
} );

it( 'follows the text direction, so the left arrow moves forward in RTL', async () => {
jest.mocked( isRTL ).mockReturnValue( true );
const user = userEvent.setup();
renderCardTabs();

act( () => screen.getByRole( 'tab', { name: 'Orders' } ).focus() );
await user.keyboard( '{ArrowLeft}' );

expect( screen.getByRole( 'tab', { name: 'Visitors' } ) ).toHaveFocus();
} );
} );
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/* A card's narrowest inline size before the row wraps. No WPDS dimension
* token reaches this far; a consumer tunes it through
* `--jpa-card-tabs-min-inline-size`, as it tunes the padding. */
$card-tabs-min-inline-size: 10rem;

/* As many cards to a row as fit at their minimum size, every row sharing the
* width evenly. A consumer that balances its rows sets
* `--jpa-card-tabs-columns` instead. */
.list {
display: grid;
grid-template-columns: repeat(var(--jpa-card-tabs-columns, auto-fit), minmax(min(100%, var(--jpa-card-tabs-min-inline-size, #{$card-tabs-min-inline-size})), 1fr));
gap: var(--wpds-dimension-gap-sm);
min-inline-size: 0;
}

/* A card draws its own box, so there is no indicator to hide. The selected
* card's fill marks the selection; the other states take the interactive
* tokens Button and Tabs share. */
.tab {
display: flex;
align-items: flex-start;
inline-size: 100%;
min-inline-size: 0;
margin: 0;
padding: var(--jpa-card-tabs-padding, var(--wpds-dimension-padding-md));
overflow: hidden;
border: 0;
border-radius: var(--wpds-border-radius-lg);
background-color: var(--wpds-color-background-interactive-neutral-weak);
color: var(--wpds-color-foreground-interactive-neutral);
font: inherit;
text-align: start;
cursor: var(--wpds-cursor-control);
appearance: none;

/* Drawn inside the card, so the widget chrome's `overflow` cannot clip it.
* Transparent until focused; forced colors paint it regardless. */
outline: var(--wpds-border-width-focus) solid transparent;
outline-offset: calc(-1 * var(--wpds-border-width-focus));

@media not (prefers-reduced-motion) {
transition: background-color 0.1s linear;
}
}

.tab:focus-visible {
outline-color: var(--wpds-color-stroke-focus);
}

.tab:not([data-disabled]):not([aria-selected="true"]):is(:hover, :active) {
background-color: var(--wpds-color-background-interactive-neutral-weak-active);
color: var(--wpds-color-foreground-interactive-neutral-active);
}

.tab[aria-selected="true"] {
background-color: var(--wpds-color-background-interactive-brand-weak-active);
cursor: default;
}

.tab[data-disabled] {
color: var(--wpds-color-foreground-interactive-neutral-disabled);
cursor: default;
}

/* Fills do not survive forced colors, so the selected card doubles its edge. */
@media (forced-colors: active) {

.tab[aria-selected="true"] {
outline-width: var(--wpds-border-width-md);
outline-style: double;
}

.tab[data-disabled] {
color: GrayText;
}
}

.panel {
min-inline-size: 0;
min-block-size: 0;
}

/* The panel is a tab stop of its own, so it takes the outset ring `Tabs`
* gives its panel. */
.panel:focus-visible {
outline: var(--wpds-border-width-focus) solid var(--wpds-color-stroke-focus);
outline-offset: var(--wpds-border-width-focus);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
/**
* External dependencies
*/
import { BaseDirectionProvider, BaseTabs } from '@jetpack-premium-analytics/externals';
import { isRTL } from '@wordpress/i18n';
import clsx from 'clsx';
import { forwardRef } from 'react';
/**
* Internal dependencies
*/
import styles from './card-tabs.module.scss';
import type {
CardTabsListProps,
CardTabsPanelProps,
CardTabsRootProps,
CardTabsTabProps,
} from './types';

/**
* Groups the cards and their panels. Mirrors the `Tabs` API of `@wordpress/ui`,
* with each tab drawn as a card whose fill marks the selection.
*/
export const Root = forwardRef< HTMLDivElement, CardTabsRootProps >(
function CardTabsRoot( props, forwardedRef ) {
return (
<BaseDirectionProvider direction={ isRTL() ? 'rtl' : 'ltr' }>
<BaseTabs.Root ref={ forwardedRef } { ...props } />
</BaseDirectionProvider>
);
}
);

/** The row of cards, wrapping as the room runs out. */
export const List = forwardRef< HTMLDivElement, CardTabsListProps >( function CardTabsList(
{ className, ...otherProps },
forwardedRef
) {
return (
<BaseTabs.List
ref={ forwardedRef }
className={ clsx( styles.list, className ) }
{ ...otherProps }
/>
);
} );

/** A card: a button that shows its panel when activated. */
export const Tab = forwardRef< HTMLButtonElement, CardTabsTabProps >( function CardTabsTab(
{ className, ...otherProps },
forwardedRef
) {
return (
<BaseTabs.Tab
ref={ forwardedRef }
className={ clsx( styles.tab, className ) }
{ ...otherProps }
/>
);
} );

/** The panel shown while its card is selected. */
export const Panel = forwardRef< HTMLDivElement, CardTabsPanelProps >( function CardTabsPanel(
{ className, ...otherProps },
forwardedRef
) {
return (
<BaseTabs.Panel
ref={ forwardedRef }
className={ clsx( styles.panel, className ) }
{ ...otherProps }
/>
);
} );
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * as CardTabs from './card-tabs';
Loading
Loading