# Clamp

Long content clamped to a few lines, with a button to show the rest.

Source: [clamp.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/clamp.tsx)

```tsx
import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import { Clamp, ClampContent, ClampTrigger } from "@/components/ui/clamp";
import { people } from "@/examples/data";

const comments = [
  {
    author: people[0],
    time: "2h",
    body: [
      "I reproduced the double charge on staging. When a card needs 3-D Secure, the confirm step retries on the client after the redirect, and the webhook also finalizes the invoice. Both paths call finalizeInvoice, so we bill twice whenever the webhook wins the race.",
      "The fix makes finalizing idempotent on the invoice ID and drops the client retry. It's in #2291, with a test that fires both paths within 50ms of each other. Refunds for the 14 customers affected go out tomorrow.",
    ],
  },
  {
    author: people[1],
    time: "1h",
    body: ["Approved. Ship it behind the billing flag first."],
  },
];

export default function ClampComment() {
  return (
    <div className="flex w-full max-w-md flex-col gap-5">
      {comments.map((comment) => (
        <div key={comment.author.value} className="flex gap-3">
          <Avatar>
            <AvatarImage src={comment.author.image} alt="" />
            <AvatarFallback>{comment.author.initials}</AvatarFallback>
          </Avatar>
          <div className="flex min-w-0 flex-1 flex-col gap-1">
            <div className="flex items-baseline gap-2 text-sm">
              <span className="font-medium">{comment.author.name}</span>
              <span className="text-2xs text-faint">{comment.time}</span>
            </div>
            <Clamp>
              <ClampContent className="text-muted-foreground [&_p+p]:mt-2">
                {comment.body.map((paragraph) => (
                  <p key={paragraph}>{paragraph}</p>
                ))}
              </ClampContent>
              <ClampTrigger />
            </Clamp>
          </div>
        </div>
      ))}
    </div>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/clamp
```

## Usage

```tsx
import { Clamp, ClampContent, ClampTrigger } from "@/components/ui/clamp";

export function Comment({ body }: { body: string }) {
  return (
    <Clamp lines={3}>
      <ClampContent>
        <p>{body}</p>
      </ClampContent>
      <ClampTrigger />
    </Clamp>
  );
}
```

`ClampContent` shows the first `lines` lines, measured in its own line height, and fades out
the last one. `ClampTrigger` shows only when there's more to show. That's measured rather than
guessed, so short content gets neither the fade nor the button. Before the page loads in the
browser, CSS clamps the content to `lines` lines, fades the last one and reserves space for the
button, so long content already looks right in the server render. Content shorter than that gives
the space back once it's measured.

Tabbing to a link in the hidden lines opens the content, so focus never lands on something out of
sight. Screen readers read all of the content, whether it's open or not.

## Composition

- `Clamp`
  - `ClampContent`
  - `ClampTrigger`

## Examples

### Lines and labels

`lines` sets how many lines show while the content is closed. Set `more` and `less` on
`ClampTrigger` to change its labels.

```tsx
import { Clamp, ClampContent, ClampTrigger } from "@/components/ui/clamp";

const changes = [
  "Plan changes are self-serve, and take effect at the next invoice.",
  "Metered usage is out of beta, with alerts at 80% and 100% of a limit.",
  "SSO comes with every paid plan, through Okta, Google or Azure.",
  "Audit logs export to your own S3 bucket every night.",
  "Invoices come as PDFs in nine languages.",
  "Webhooks retry with backoff for up to three days.",
];

export default function ClampReleaseNotes() {
  return (
    <Clamp lines={4} className="w-full max-w-sm">
      <h3 className="text-sm font-medium">What’s new in 4.2</h3>
      <ClampContent className="text-muted-foreground">
        <ul className="list-disc pl-4">
          {changes.map((change) => (
            <li key={change}>{change}</li>
          ))}
        </ul>
      </ClampContent>
      <ClampTrigger more="All changes" less="Fewer changes" />
    </Clamp>
  );
}
```

## Props

| Part | Extends |
| --- | --- |
| `Clamp` | `<div>` |
| `ClampContent` | `<div>` |
| `ClampTrigger` | [`Button`](https://ui.jarv.is/components/button.md) |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### Clamp

| Prop            | Type                                                               | Default | Description                                                                                                                                                                               |
| --------------- | ------------------------------------------------------------------ | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `open?`         | `boolean`                                                          | —       | Whether the content is shown in full, when the state is controlled.                                                                                                                       |
| `defaultOpen?`  | `boolean`                                                          | `false` | Whether the content is shown in full initially, when the state is uncontrolled.                                                                                                           |
| `onOpenChange?` | `((open: boolean, eventDetails: ClampChangeEventDetails) => void)` | —       | Called when the trigger opens or closes the content, or when focus moving into the hidden lines opens it. Calling `eventDetails.cancel()` keeps the content as it is.                     |
| `lines?`        | `number`                                                           | `3`     | How many lines show while the content is collapsed, measured in its own line height.                                                                                                      |
| `className?`    | `string`                                                           | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`        | `React.CSSProperties`                                              | —       | Style applied to the element.                                                                                                                                                             |
| `render?`       | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement`           | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ClampContent

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### ClampTrigger

| Prop                     | Type                                                                                 | Default       | Description                                                                                                                                                                               |
| ------------------------ | ------------------------------------------------------------------------------------ | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `nativeButton?`          | `boolean`                                                                            | `true`        | Whether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `false` if the rendered element is not a button (for example, `<div>`).         |
| `focusableWhenDisabled?` | `boolean`                                                                            | `false`       | Whether the button should be focusable when disabled.                                                                                                                                     |
| `variant?`               | `"destructive" \| "ghost" \| "link" \| "outline" \| "primary" \| "secondary"`        | `"ghost"`     |                                                                                                                                                                                           |
| `size?`                  | `"default" \| "icon" \| "icon-lg" \| "icon-sm" \| "icon-xs" \| "lg" \| "sm" \| "xs"` | `"sm"`        |                                                                                                                                                                                           |
| `more?`                  | `React.ReactNode`                                                                    | `"Show more"` | The trigger's label while the content is clamped.                                                                                                                                         |
| `less?`                  | `React.ReactNode`                                                                    | `"Show less"` | The trigger's label while the content is shown in full.                                                                                                                                   |
| `className?`             | `string \| ((state: ButtonState) => string \| undefined)`                            | —             | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`                 | `React.CSSProperties \| ((state: ButtonState) => React.CSSProperties \| undefined)`  | —             | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`                | `ComponentRenderFn<HTMLProps, ButtonState> \| React.ReactElement`                    | —             | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

`ClampTrigger` takes the props of [Button](https://ui.jarv.is/components/button.md) too, and is a ghost button by
default.

### useClamp

`useClamp()` reads the `Clamp` that your component renders in, and returns its state:

| Value         | Type                      | Description                                                                                                                |
| ------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| `open`        | `boolean`                 | Whether the content is shown in full.                                                                                      |
| `setOpen`     | `(open: boolean) => void` | Opens or closes the content, as the trigger does. `onOpenChange` gets the reason `imperative-action`.                      |
| `overflowing` | `boolean \| null`         | Whether the content runs past `lines`, so there's more to show. `null` until the content is measured after the page loads. |
