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
145 changes: 145 additions & 0 deletions apps/frontend/src/components/Button/Button.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
import { fireEvent, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { renderWithProviders } from '../../test/render';
import { Button } from './Button';
import { BUTTON_VARIANTS, type ButtonVariant } from './variants';

const VARIANTS = Object.keys(BUTTON_VARIANTS) as ButtonVariant[];

describe('Button', () => {
it.each(VARIANTS)('renders the label for variant "%s"', (variant) => {
renderWithProviders(<Button variant={variant}>Label</Button>);
expect(screen.getByRole('button', { name: 'Label' })).toBeTruthy();
});

it('defaults to the primary variant and md size', () => {
renderWithProviders(<Button>Upload</Button>);
const button = screen.getByRole('button', { name: 'Upload' });
expect(button.getAttribute('data-variant')).toBe('primary');
expect(button.getAttribute('data-size')).toBe('md');
});

it('calls onClick when clicked', () => {
const onClick = vi.fn();
renderWithProviders(<Button onClick={onClick}>Go</Button>);
fireEvent.click(screen.getByRole('button', { name: 'Go' }));
expect(onClick).toHaveBeenCalledTimes(1);
});

it('does not call onClick when disabled', () => {
const onClick = vi.fn();
renderWithProviders(
<Button disabled onClick={onClick}>
Go
</Button>,
);
const button = screen.getByRole('button', { name: 'Go' });
expect(button).toHaveProperty('disabled', true);
fireEvent.click(button);
expect(onClick).not.toHaveBeenCalled();
});

it('is disabled, busy and ignores clicks while loading', () => {
const onClick = vi.fn();
renderWithProviders(
<Button loading onClick={onClick}>
Submit
</Button>,
);
const button = screen.getByRole('button');
expect(button).toHaveProperty('disabled', true);
expect(button.getAttribute('aria-busy')).toBe('true');
fireEvent.click(button);
expect(onClick).not.toHaveBeenCalled();
});

it('shows loadingText while loading', () => {
renderWithProviders(
<Button loading loadingText="Submitting">
Submit
</Button>,
);
expect(screen.getByText('Submitting')).toBeTruthy();
});

it('is not busy when not loading', () => {
renderWithProviders(<Button>Submit</Button>);
expect(screen.getByRole('button').getAttribute('aria-busy')).not.toBe(
'true',
);
});

it('renders leftIcon and rightIcon, hidden from assistive tech', () => {
renderWithProviders(
<Button
leftIcon={<svg data-testid="left" />}
rightIcon={<svg data-testid="right" />}
>
Source: All
</Button>,
);
const left = screen.getByTestId('left');
const right = screen.getByTestId('right');
expect(left.closest('[aria-hidden="true"]')).not.toBeNull();
expect(right.closest('[aria-hidden="true"]')).not.toBeNull();
// The icons don't change the accessible name.
expect(screen.getByRole('button', { name: 'Source: All' })).toBeTruthy();
});

it('is reachable by aria-label when icon-only', () => {
renderWithProviders(
<Button
variant="ghost"
aria-label="Open entry"
leftIcon={<svg data-testid="chevron" />}
/>,
);
expect(screen.getByRole('button', { name: 'Open entry' })).toBeTruthy();
});

it('defaults to type="button" and passes type="submit" through', () => {
const { unmount } = renderWithProviders(<Button>A</Button>);
expect(screen.getByRole('button', { name: 'A' }).getAttribute('type')).toBe(
'button',
);
unmount();
renderWithProviders(<Button type="submit">B</Button>);
expect(screen.getByRole('button', { name: 'B' }).getAttribute('type')).toBe(
'submit',
);
});

it('renders a real link when href is given', () => {
renderWithProviders(
<Button variant="link" href="/entry/today">
Today’s Entry
</Button>,
);
const link = screen.getByRole('link', { name: 'Today’s Entry' });
expect(link.tagName).toBe('A');
expect(link.getAttribute('href')).toBe('/entry/today');
expect(screen.queryByRole('button')).toBeNull();
});

it('adds rel for links that open in a new tab', () => {
renderWithProviders(
<Button variant="link" href="https://example.com" target="_blank">
Docs
</Button>,
);
expect(screen.getByRole('link', { name: 'Docs' }).getAttribute('rel')).toBe(
'noopener noreferrer',
);
});

it('works as the child of asChild with a custom link', () => {
renderWithProviders(
<Button asChild variant="link">
<a href="/x">Custom</a>
</Button>,
);
const link = screen.getByRole('link', { name: 'Custom' });
expect(link.getAttribute('href')).toBe('/x');
expect(link.hasAttribute('type')).toBe(false);
});
});
142 changes: 142 additions & 0 deletions apps/frontend/src/components/Button/Button.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import {
Button as ChakraButton,
type ButtonProps as ChakraButtonProps,
} from '@chakra-ui/react';
import type { ReactNode } from 'react';
import {
BUTTON_SIZES,
BUTTON_VARIANTS,
type ButtonSize,
type ButtonVariant,
} from './variants';

type BaseProps = Omit<
ChakraButtonProps,
'variant' | 'size' | 'loading' | 'loadingText' | 'children'
> & {
/** Look of the button. Label and icons are passed by the caller. */
variant?: ButtonVariant;
/** `md` is Figma's 40px. `sm` is a compact option (not in Figma). */
size?: ButtonSize;
leftIcon?: ReactNode;
rightIcon?: ReactNode;
/** Shows a spinner, disables the button and keeps its width. */
loading?: boolean;
loadingText?: ReactNode;
/** Renders a real `<a>` styled as the button (use for navigation). */
href?: string;
target?: string;
rel?: string;
};

// With no children the button is icon-only and needs an accessible name.
export type ButtonProps = BaseProps &
({ children: ReactNode } | { children?: undefined; 'aria-label': string });

const Icon = ({ children }: { children: ReactNode }) => (
<span
aria-hidden="true"
style={{ display: 'inline-flex', flexShrink: 0, alignItems: 'center' }}
>
{children}
</span>
);

/**
* Shared button. Built on Chakra's `Button` and styled with the tokens in
* `styles/tokens.css` to match the Figma "Buttons" frame (156:1559).
*
* - `variant` is the look (`primary`, `secondary`, `dark`, `link`, `ghost`).
* The caller passes the label and icons, so there is no variant per label.
* - `size` is `md` (Figma's 40px) or `sm` (compact, not in Figma).
* - `loading` shows a spinner, disables the button and sets `aria-busy`;
* `loadingText` replaces the label while loading.
* - `href` renders a real `<a>`. `asChild` wraps your own element (e.g. a
* router Link) and leaves its content and `type` alone.
* - `type` defaults to `"button"` so a button in a form never submits by
* accident. Pass `type="submit"` for Submit.
* - With no children it is icon-only and `aria-label` is required.
*
* Other Chakra props (`onClick`, `disabled`, `aria-*`, ...) pass through.
*
* @example
* <Button leftIcon={<Upload size={20} />} onClick={upload}>Upload</Button>
* <Button variant="secondary" onClick={close}>Cancel</Button>
* <Button variant="ghost" aria-label="Open entry" leftIcon={<ChevronRight size={26} />} />
*/
export function Button({
variant = 'primary',
size = 'md',
leftIcon,
rightIcon,
loading = false,
loadingText,
href,
target,
rel,
type,
asChild,
children,
...rest
}: ButtonProps) {
const styles = { ...BUTTON_VARIANTS[variant], ...BUTTON_SIZES[size] };
// `link` and `ghost` own their height, whatever the size.
if (variant === 'link') styles.h = 'auto';
if (variant === 'ghost') styles.h = BUTTON_VARIANTS.ghost.h;

const common = {
...styles,
'data-variant': variant,
'data-size': size,
...rest,
};

const content = (
<>
{leftIcon ? <Icon>{leftIcon}</Icon> : null}
{children}
{rightIcon ? <Icon>{rightIcon}</Icon> : null}
</>
);

if (href) {
return (
<ChakraButton
asChild
{...common}
type={undefined}
aria-busy={loading || undefined}
>
<a
href={href}
target={target}
rel={rel ?? (target === '_blank' ? 'noopener noreferrer' : undefined)}
>
{content}
</a>
</ChakraButton>
);
}

if (asChild) {
// The caller supplies the element (e.g. a router Link), so don't add
// `type` or wrap its content.
return (
<ChakraButton asChild {...common} type={undefined}>
{children}
</ChakraButton>
);
}

return (
<ChakraButton
{...common}
type={type ?? 'button'}
loading={loading}
loadingText={loadingText}
aria-busy={loading || undefined}
>
{content}
</ChakraButton>
);
}
3 changes: 3 additions & 0 deletions apps/frontend/src/components/Button/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './Button';
export { BUTTON_VARIANTS } from './variants';
export type { ButtonVariant, ButtonSize } from './variants';
Loading
Loading