# CopyField, CopyButton, CopyText

> Values to copy: a whole field, a button beside your own value, or an id inline with a small button.

- Import: `import { CopyButton, CopyField, CopyText } from '@nyxon/nasim';`
- Server Component: no, it needs a client component
- Since: 0.1.0; status: stable
- Source: libs/nasim/src/composites/CopyField.tsx
- Describes: @nyxon/nasim unreleased, after 0.12.0
- Page: https://nasim.nyxon.tech/docs/components/data/copy-field

<Example name="copy-field/link">
  ```tsx title="copy-field/link.tsx"
  import { CopyField } from '@nyxon/nasim';

  const copy = { label: 'لینک اشتراک' };
  // A sample address; a real one comes from the API.
  const link = 'https://panel.example.com/sub/demo-user-1042/connect';

  // A press anywhere on the field copies it. A long value is cut in the middle: its end stays.
  export default function Link() {
    return <CopyField label={copy.label} value={link} />;
  }
  ```
</Example>

<Callout title="In these previews">
  A preview is a page inside this one. Pressing a copy control here really
  copies to your clipboard. If your browser refuses the clipboard to an embedded
  page, you see what a person sees in an app that is refused it: «کپی نشد» and
  the value selected for copying by hand.
</Callout>

## Import [#import]

```tsx
import { CopyButton, CopyField, CopyText } from '@nyxon/nasim';
```

## Usage [#usage]

Three parts for three places. All three are client components; a Server Component renders them with
plain props.

* **`CopyField`**: the whole field, for a value to hand over (a subscription link, a wallet address).
  Pressed anywhere, it copies. Always left to right.
* **`CopyButton`**: a labelled button beside a value you draw yourself (a card number grouped in fours,
  a one-time secret).
* **`CopyText`**: an id, a link or a code inline, with a small icon button, for every id of a detail
  panel. A press on it never reaches the row around it.

```tsx
<CopyField label={t.services.subscriptionLink} value={subscriptionUrl} />
<CopyButton value={card} label={t.checkout.copyCard} />
<CopyText value={service.id} label={t.services.id} isLtr />
```

All three copy through `writeClipboard`: the clipboard API first, then the older copy command, which a
web view without the API's permission (Telegram's) still allows. Each says the result in place, never in
a toast. `onCopy(isCopied)` tells you whether the value reached the clipboard: a dialog that hands over a
secret closes only on `true`.

## Examples [#examples]

### A link [#a-link]

Shown above. A long value is cut in the middle, so its last eight characters stay visible and nothing
overflows.

### Several lines [#several-lines]

`multiline` shows a value of several lines whole, in a box of its own, and copies it whole.

<Example name="copy-field/multiline">
  ```tsx title="copy-field/multiline.tsx"
  import { CopyField } from '@nyxon/nasim';

  const copy = { label: 'پیکربندی وایرگارد' };
  // A sample profile without its private key; a real one comes from the API.
  const profile = [
    '[Interface]',
    'Address = 10.8.0.12/32',
    'DNS = 1.1.1.1',
    '',
    '[Peer]',
    'Endpoint = vpn.example.com:51820',
    'AllowedIPs = 0.0.0.0/0',
  ].join('\n');

  // A value of several lines is shown whole, left to right, and copied whole.
  export default function Multiline() {
    return <CopyField label={copy.label} value={profile} multiline />;
  }
  ```
</Example>

### A button beside your own value [#a-button-beside-your-own-value]

`value` is the canonical form (Latin digits, no separators), whatever the page shows.

<Example name="copy-field/copy-button">
  ```tsx title="copy-field/copy-button.tsx"
  import { CopyButton } from '@nyxon/nasim';

  const copy = { card: 'کپی شماره کارت', owner: 'به نام: فروشگاه نمونه' };
  // Not a card: a repeating pattern no bank issues. Shown grouped in fours, copied in its canonical form.
  const card = '1111222233334444';
  const grouped = card.replace(/(\d{4})(?=\d)/g, '$1 ');

  // CopyButton is the button beside a value you draw yourself.
  export default function CardNumber() {
    return (
      <div className="flex flex-col gap-2">
        <p dir="ltr" className="text-end font-mono text-lg tabular-nums">
          {grouped}
        </p>
        <p className="text-sm text-muted">{copy.owner}</p>
        <div className="flex flex-wrap gap-2">
          <CopyButton value={card} label={copy.card} />
        </div>
      </div>
    );
  }
  ```
</Example>

### Ids in a detail panel [#ids-in-a-detail-panel]

`isLtr` shows the value left to right in monospace and keeps a browser from translating it. `children`
is what is shown when that is not the value itself (a shortened link); `value` is what is copied.

<Example name="copy-field/copy-text">
  ```tsx title="copy-field/copy-text.tsx"
  import { CopyText, KeyValueList } from '@nyxon/nasim';

  const copy = {
    id: 'شناسهٔ سرویس',
    link: 'لینک اشتراک',
    plan: 'پلن',
    planValue: 'ماهانه، ۵۰ گیگابایت',
  };
  // Sample values; real ones come from the API.
  const service = {
    id: 'srv-1042',
    link: 'https://panel.example.com/sub/demo-user-1042/connect',
    shortLink: 'panel.example.com/…/1042',
  };

  // CopyText: an id or a link inline, with a small copy button, in a detail panel's list.
  export default function DetailIds() {
    return (
      <KeyValueList
        layout="stacked"
        items={[
          { label: copy.plan, value: copy.planValue },
          {
            label: copy.id,
            value: <CopyText value={service.id} label={copy.id} isLtr />,
          },
          {
            label: copy.link,
            value: (
              <CopyText value={service.link} label={copy.link} isLtr>
                {service.shortLink}
              </CopyText>
            ),
          },
        ]}
      />
    );
  }
  ```
</Example>

## Rules [#rules]

* Copy the canonical value, show the readable one: a card number is copied without its spaces.
* Never confirm a copy in a toast: the part says it where the press was.
* A failure is not hidden. When the clipboard refuses, the person needs the value on the page to copy by
  hand: `CopyField` selects it for them; beside a `CopyButton`, the value must be on screen.

## Accessibility [#accessibility]

* **`CopyField`**: one button named «کپی …» (from `label`) and described by the value, so the value is
  not read twice with «کپی». A live region says «کپی شد» only when the value reached the clipboard;
  otherwise «کپی نشد» shows in the field, the text is selected, and a line under the field says to copy
  it by hand.
* **`CopyButton`**: its label turns into `doneLabel` («کپی شد») for a moment and a polite live region
  announces it. A failure shows a danger icon and a line under the button, in words and in the live
  region, until the next press. On a coarse pointer it is 44px tall.
* **`CopyText`**: the icon button is named «کپی» and `label`. Its name does not change; the icon becomes
  a check and the live region says «کپی شد». On a touch screen it gets a 44px hit area.

## API [#api]

### CopyField [#copyfield]

| Prop        | Type                            | Default  | Description                                                                                            |
| ----------- | ------------------------------- | -------- | ------------------------------------------------------------------------------------------------------ |
| `label`     | `string`                        | required |                                                                                                        |
| `value`     | `string`                        | required | A value to hand over: subscription link, wallet address, card number.                                  |
| `multiline` | `boolean`                       | —        | A value of several lines (a WireGuard profile): shown whole in its own box, copied whole.              |
| `children`  | `ReactNode`                     | —        | Whatever belongs to the value, shown under its field (a QR code, a pager).                             |
| `onCopy`    | `((isCopied: boolean) => void)` | —        | Told whether the value reached the clipboard: a dialog that hands over a secret closes only on `true`. |

### CopyButton [#copybutton]

| Prop          | Type                                                                                          | Default  | Description                                                                        |
| ------------- | --------------------------------------------------------------------------------------------- | -------- | ---------------------------------------------------------------------------------- |
| `value`       | `string`                                                                                      | required | What is copied, in its canonical form (Latin digits, no separators).               |
| `label`       | `string`                                                                                      | required | Names the button («کپی شماره کارت»).                                               |
| `doneLabel`   | `string`                                                                                      | —        | Replaces the label for a moment after a copy. Defaults to «کپی شد».                |
| `variant`     | `"danger" \| "danger-soft" \| "ghost" \| "outline" \| "primary" \| "secondary" \| "tertiary"` | —        |                                                                                    |
| `size`        | `"lg" \| "md" \| "sm"`                                                                        | —        |                                                                                    |
| `className`   | `string`                                                                                      | —        |                                                                                    |
| `data-testid` | `string`                                                                                      | —        |                                                                                    |
| `onCopy`      | `((isCopied: boolean) => void)`                                                               | —        | Told whether the value reached the clipboard, to act only on a copy that happened. |

### CopyText [#copytext]

| Prop          | Type                            | Default  | Description                                                                            |
| ------------- | ------------------------------- | -------- | -------------------------------------------------------------------------------------- |
| `value`       | `string`                        | required | What is copied, in its canonical form.                                                 |
| `label`       | `string`                        | required | Names what is copied; the button says «کپی» and this («کپی شناسه سرویس»).              |
| `children`    | `ReactNode`                     | —        | What is shown when that is not the value itself (a shortened id). Defaults to `value`. |
| `isLtr`       | `boolean`                       | —        | An id, a link, a code: shown left to right in monospace, whatever the page direction.  |
| `doneLabel`   | `string`                        | —        | Replaces «کپی شد» in the live region.                                                  |
| `className`   | `string`                        | —        |                                                                                        |
| `data-testid` | `string`                        | —        |                                                                                        |
| `onCopy`      | `((isCopied: boolean) => void)` | —        | Told whether the value reached the clipboard, to act only on a copy that happened.     |

## Related [#related]

`KeyValueList` (the fields of one record, where `CopyText` sits beside every id).