# Button

## Introduction

Button is the primary interactive element for triggering actions. Built on Joy UI's Button with Framer Motion animation support, it provides multiple visual variants, sizes, colors, loading states, and decorator slots. Use buttons for form submissions, navigation triggers, modal actions, and data operations.

```tsx
<>
    {/* @ts-ignore */}
    <Button {...props} startDecorator={<Add />} />
    <IconButton {...props} aria-label="Add">
      <Add />
    </IconButton>
  </>
```

| Field   | Description | Default   |
| ------- | ----------- | --------- |
| color   | —           | "primary" |
| size    | —           | "md"      |
| variant | —           | "solid"   |

## Usage

```tsx
import { Button } from '@ceed/cds';

function MyComponent() {
  return <Button onClick={() => console.log('Clicked!')}>Click me</Button>;
}
```

## Examples

### Basic Usage

The most basic button usage.

```tsx
<>
    <Button {...props} />
    <Button {...props} disabled />
    <Button {...props} loading />
  </>
```

### Disabled State

A disabled button cannot be clicked and is visually dimmed.

```tsx
<>
    <Button {...props} startDecorator={<Add />} variant="solid">
      Solid
    </Button>
    <Button {...props} startDecorator={<Add />} variant="soft">
      Soft
    </Button>
    <Button {...props} startDecorator={<Add />} variant="outlined">
      Outlined
    </Button>
    <Button {...props} startDecorator={<Add />} variant="plain">
      Plain
    </Button>
  </>
```

### Loading State

Shows a loading indicator during async operations. The button is automatically disabled while loading.

```tsx
<Button
  children="Button"
  disabled={false}
  loading
  color="primary"
  size="md"
  variant="solid"
/>
```

## Customization

### Variants

Four visual styles are available to indicate action importance.

```tsx
<>
    <Button {...props} variant="solid">
      Solid
    </Button>
    <Button {...props} variant="soft">
      Soft
    </Button>
    <Button {...props} variant="outlined">
      Outlined
    </Button>
    <Button {...props} variant="plain">
      Plain
    </Button>
  </>
```

- **solid**: High-emphasis primary actions (default)
- **soft**: Medium-emphasis secondary actions with a subtle background
- **outlined**: Low-emphasis actions with a border
- **plain**: Minimal actions with text only

### Sizes

Three sizes are available: `sm`, `md` (default), and `lg`.

```tsx
<>
    <Button {...props} size="sm">
      Small
    </Button>
    <Button {...props} size="md">
      Medium
    </Button>
    <Button {...props} size="lg">
      Large
    </Button>
  </>
```

### Colors

Apply semantic colors to communicate intent.

```tsx
<>
    <Button {...props} color="primary">
      Primary
    </Button>
    <Button {...props} color="neutral">
      Neutral
    </Button>
    <Button {...props} color="danger">
      Danger
    </Button>
    <Button {...props} color="success">
      Success
    </Button>
    <Button {...props} color="warning">
      Warning
    </Button>
  </>
```

- **primary**: Main actions (default)
- **neutral**: Neutral actions
- **success**: Confirmation or positive actions
- **warning**: Caution-required actions
- **danger**: Destructive or irreversible actions

### Decorators

Add icons or other elements before or after the button text using `startDecorator` and `endDecorator`.

```tsx
<>
    <Button {...props} startDecorator={<Add />}>
      Add to cart
    </Button>
    <Button {...props} endDecorator={<Add />} color="success">
      Go to checkout
    </Button>
  </>
```

### Loading Indicator

Customize the loading spinner with the `loadingIndicator` prop.

```tsx
<>
    <Button {...props} loading>
      Default
    </Button>
    <Button {...props} loading loadingIndicator="Loading…">
      Custom
    </Button>
  </>
```

### Loading Position

Control where the loading indicator appears with `loadingPosition`.

```tsx
<>
    <Button {...props} loading loadingPosition="start">
      Start
    </Button>
    <Button {...props} loading loadingPosition="end" endDecorator={<Add />}>
      End
    </Button>
  </>
```

## Common Use Cases

### Form Submission

```tsx
<form onSubmit={handleSubmit}>
  <Stack spacing={2}>
    <Input placeholder="Enter your name" />
    <Input placeholder="Enter your email" />

    <Stack direction="row" spacing={2} justifyContent="flex-end">
      <Button variant="outlined" type="button" onClick={handleCancel}>
        Cancel
      </Button>
      <Button type="submit" loading={isSubmitting}>
        {isSubmitting ? 'Saving...' : 'Save'}
      </Button>
    </Stack>
  </Stack>
</form>
```

### Modal Actions

```tsx
<Modal open={open}>
  <ModalDialog>
    <ModalClose />
    <DialogTitle>Confirm Deletion</DialogTitle>
    <DialogContent>Are you sure you want to delete this item? This action cannot be undone.</DialogContent>

    <DialogActions>
      <Button variant="outlined" onClick={handleClose}>
        Cancel
      </Button>
      <Button color="danger" onClick={handleDelete}>
        Delete
      </Button>
    </DialogActions>
  </ModalDialog>
</Modal>
```

### Action Buttons with Icons

```tsx
<Stack direction="row" spacing={2}>
  <Button startDecorator={<AddIcon />}>Create New</Button>

  <Button variant="outlined" startDecorator={<DownloadIcon />} onClick={handleDownload}>
    Download
  </Button>

  <Button variant="soft" color="success" startDecorator={<ShareIcon />}>
    Share
  </Button>
</Stack>
```

### Async Operations

```tsx
function AsyncButton() {
  const [loading, setLoading] = useState(false);

  const handleAsyncAction = async () => {
    setLoading(true);
    try {
      await api.processData();
    } finally {
      setLoading(false);
    }
  };

  return (
    <Button loading={loading} onClick={handleAsyncAction} startDecorator={<ProcessIcon />}>
      Process Data
    </Button>
  );
}
```

## Props and Customization

### Key Props

| Prop               | Type                                                           | Default                | Description                                                       |
| ------------------ | -------------------------------------------------------------- | ---------------------- | ----------------------------------------------------------------- |
| `children`         | `ReactNode`                                                    | -                      | Button content (text, icons, etc.)                                |
| `variant`          | `'solid' \| 'soft' \| 'outlined' \| 'plain'`                   | `'solid'`              | Visual style                                                      |
| `size`             | `'sm' \| 'md' \| 'lg'`                                         | `'md'`                 | Button size                                                       |
| `color`            | `'primary' \| 'neutral' \| 'danger' \| 'success' \| 'warning'` | `'primary'`            | Color scheme                                                      |
| `disabled`         | `boolean`                                                      | `false`                | Disables the button                                               |
| `loading`          | `boolean`                                                      | `false`                | Shows a loading indicator and disables the button                 |
| `loadingIndicator` | `ReactNode`                                                    | `<CircularProgress />` | Custom loading indicator element                                  |
| `loadingPosition`  | `'start' \| 'end'`                                             | `'start'`              | Where the loading indicator appears                               |
| `startDecorator`   | `ReactNode`                                                    | -                      | Content rendered before the button text                           |
| `endDecorator`     | `ReactNode`                                                    | -                      | Content rendered after the button text                            |
| `fullWidth`        | `boolean`                                                      | `false`                | Stretches the button to fill its container width                  |
| `component`        | `ElementType`                                                  | `'button'`             | Root element type (polymorphic — can render as `a`, `Link`, etc.) |
| `type`             | `'button' \| 'submit' \| 'reset'`                              | `'button'`             | HTML button type attribute                                        |
| `onClick`          | `(event: MouseEvent) => void`                                  | -                      | Click event handler                                               |
| `sx`               | `SxProps`                                                      | -                      | Custom styles using the MUI system                                |

> **Note**: Button also accepts all Joy UI Button props and Framer Motion props.

### Polymorphic Usage

Button supports the `component` prop to render as a different element:

```tsx
// Render as an anchor tag
<Button component="a" href="/dashboard">Go to Dashboard</Button>

// Render as a React Router Link
<Button component={Link} to="/settings">Settings</Button>
```

## Best Practices

1. **Choose the right variant for the action hierarchy**:
   - Primary action: `solid`
   - Secondary action: `outlined` or `soft`
   - Tertiary/minimal action: `plain`

2. **Use consistent color semantics**:
   - Destructive actions: `danger`
   - Confirmations: `success`
   - Caution: `warning`

3. **Use clear, specific labels.** The button text should describe exactly what happens when clicked.

```tsx
// ✅ Good
<Button color="danger">Delete Account</Button>

// ❌ Bad
<Button color="danger">OK</Button>
```

4. **Show loading state during async operations** to provide user feedback.

```tsx
<Button loading={isSubmitting} type="submit">
  Save Changes
</Button>
```

5. **Limit the number of primary buttons** in a view. Typically one `solid` primary button per section.

## Accessibility

- **Keyboard accessible**: Tab to focus, Space or Enter to activate.
- **Screen reader support**: Button text is announced as the accessible name.
- **Disabled state**: When `disabled`, the button is removed from the tab order.
- **Loading state**: When `loading`, the button is announced as disabled. Consider adding `aria-label` to describe the loading context if the loading indicator replaces the text.
- **Color contrast**: All color/variant combinations meet WCAG AA contrast ratios.
