# Value Field

A read-only monospace value with a copy button, which can be masked like an API key.

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

```tsx
import { ValueField } from "@/components/ui/value-field";

export default function ValueFieldBasic() {
  return (
    <ValueField
      label="Invite link"
      value="https://example.com/invite/7f3a9c"
      className="max-w-sm"
    />
  );
}
```

## 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/value-field
```

## Usage

```tsx
import { ValueField } from "@/components/ui/value-field";

export function InviteLink() {
  return <ValueField label="Invite link" value="https://example.com/invite/7f3a9c" />;
}
```

Long values scroll sideways. The copy button confirms the copy, including to screen readers.

`masked` hides the value, such as a secret key, until someone presses the eye button. Copying always
copies the whole value.

```tsx
import { ValueField } from "@/components/ui/value-field";

export function SecretKey() {
  return <ValueField masked label="Secret key" value="sk_live_7f3a9c2e81d4b05a" />;
}
```

The field's children are the buttons at the end of the row. Without children, it renders a
`ValueFieldCopy`, after a `ValueFieldReveal` when `masked` is set. Pass your own buttons to change
their order, leave one out or add a `ValueFieldRegenerate`.

`display` shows something in place of the value, such as the same text with its parts colored, as
[Package Command](https://ui.jarv.is/components/package-command.md)'s `PackageCommandText` does. The field still copies
`value`.

For password entry, use a [Password Input](https://ui.jarv.is/components/password-input.md). If the browser should never
see a secret at all, don't send it to the page.

## Composition

- `ValueField`
  - `ValueFieldReveal`
  - `ValueFieldCopy`
  - `ValueFieldRegenerate`

## Examples

### Without a label

Leave out `label` when the surrounding context makes clear what the value is.

```tsx
import { ValueField } from "@/components/ui/value-field";

export default function ValueFieldWithoutLabel() {
  return (
    <ValueField value="git clone https://github.com/jakejarvis/jarvis-ui" className="max-w-sm" />
  );
}
```

### Sizes

`size` sets the row's height: `sm`, `default` or `lg`. The buttons scale with it.

```tsx
import { ValueField } from "@/components/ui/value-field";

const sizes = ["sm", "default", "lg"] as const;

export default function ValueFieldSizes() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-4">
      {sizes.map((size) => (
        <ValueField key={size} size={size} value="pnpm dlx shadcn@latest" />
      ))}
    </div>
  );
}
```

### Copying on click

`copyOnClick` copies the value when someone clicks anywhere in the row, as long as no text in it is
selected. The copy button still copies from the keyboard.

```tsx
import { ValueField } from "@/components/ui/value-field";

export default function ValueFieldCopyOnClick() {
  return (
    <ValueField
      value="pnpm dlx shadcn@latest add @jarvis/button"
      copyOnClick
      className="max-w-sm"
    />
  );
}
```

### Confirming a copy

`ValueFieldCopy`'s `onCopy` runs after the value is copied, such as to show a
[Toast](https://ui.jarv.is/components/toast.md).

```tsx
"use client";

import { toast } from "@/components/ui/toast";
import { ValueField, ValueFieldCopy } from "@/components/ui/value-field";

export default function ValueFieldOnCopy() {
  return (
    <ValueField
      label="Install"
      value="pnpm dlx shadcn@latest add @jarvis/button"
      className="max-w-sm"
    >
      <ValueFieldCopy onCopy={() => toast.add({ title: "Copied to clipboard" })} />
    </ValueField>
  );
}
```

### Masked

```tsx
import { ValueField } from "@/components/ui/value-field";

export default function ValueFieldMasked() {
  return (
    <ValueField
      masked
      label="Secret key"
      value="sk_live_7f3a9c2e81d4b05a"
      visiblePrefix={8}
      className="max-w-sm"
    />
  );
}
```

### Visible characters

`visibleSuffix` and `visiblePrefix` set how many characters stay visible at each end while the
value is masked.

```tsx
import { ValueField } from "@/components/ui/value-field";

export default function ValueFieldVisibleCharacters() {
  return (
    <div className="flex w-full max-w-sm flex-col gap-4">
      <ValueField masked label="Webhook signing secret" value="sk_whk_3c91e07b5fa24d68" />
      <ValueField
        masked
        label="Publishable key"
        value="ck_5d2a8e61c09f47b3"
        visiblePrefix={3}
        visibleSuffix={6}
      />
      <ValueField
        masked
        label="Database password"
        value="correct-horse-battery"
        visibleSuffix={0}
      />
    </div>
  );
}
```

### Regenerate

`ValueFieldRegenerate` is a button for generating a new value. If its `onClick` returns a promise,
the button stays pending until the promise settles: its icon spins and it ignores presses. If that
takes more than a second, screen readers announce "Regenerating value". Set `pendingAnnouncement`
to change the message, or to an empty string to silence it.

This example asks for confirmation first with an [Alert Dialog](https://ui.jarv.is/components/alert-dialog.md)'s
`createAlertDialogConfirm`. Once the new key is generated, it sets `revealed` to show the key, and
`onRevealedChange` keeps `revealed` in sync with the eye button.

```tsx
"use client";

import * as React from "react";

import { AlertDialogConfirm, createAlertDialogConfirm } from "@/components/ui/alert-dialog";
import {
  ValueField,
  ValueFieldCopy,
  ValueFieldRegenerate,
  ValueFieldReveal,
} from "@/components/ui/value-field";

const confirm = createAlertDialogConfirm();

function newKey() {
  const bytes = crypto.getRandomValues(new Uint8Array(8));
  return `sk_live_${Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
}

export default function ValueFieldWithRegenerate() {
  const [key, setKey] = React.useState("sk_live_7f3a9c2e81d4b05a");
  const [revealed, setRevealed] = React.useState(false);

  async function regenerate() {
    const confirmed = await confirm({
      title: "Regenerate the secret key?",
      description: "Apps using the current key stop working until you give them the new one.",
      action: "Regenerate",
      variant: "destructive",
    });
    if (!confirmed) return;
    // Stands in for the request that makes a new key on your server.
    await new Promise((resolve) => setTimeout(resolve, 1200));
    setKey(newKey());
    setRevealed(true);
  }

  return (
    <>
      <ValueField
        masked
        label="Secret key"
        value={key}
        visiblePrefix={8}
        revealed={revealed}
        onRevealedChange={setRevealed}
        className="max-w-sm"
      >
        <ValueFieldReveal />
        <ValueFieldCopy />
        <ValueFieldRegenerate onClick={regenerate} />
      </ValueField>
      <AlertDialogConfirm confirm={confirm} />
    </>
  );
}
```

### With a switch

Use `revealed` to control whether a masked value is shown from outside the field, such as with a
[Switch](https://ui.jarv.is/components/switch.md). In this example, the field's only child is a `ValueFieldCopy`, so the
switch is the only way to show the value.

```tsx
"use client";

import * as React from "react";

import { FieldLabel } from "@/components/ui/field";
import { Switch } from "@/components/ui/switch";
import { ValueField, ValueFieldCopy } from "@/components/ui/value-field";

export default function ValueFieldWithSwitch() {
  const [revealed, setRevealed] = React.useState(false);

  return (
    <div className="flex w-full max-w-sm flex-col gap-3">
      <ValueField
        masked
        label="Secret key"
        value="sk_live_7f3a9c2e81d4b05a"
        visiblePrefix={8}
        revealed={revealed}
      >
        <ValueFieldCopy />
      </ValueField>
      <FieldLabel className="gap-2 font-normal">
        <Switch checked={revealed} onCheckedChange={setRevealed} />
        Show secret key
      </FieldLabel>
    </div>
  );
}
```

### Copy button

To copy a value shown some other way, use [Copy Button](https://ui.jarv.is/components/copy-button.md) on its own.

## Props

`ValueFieldReveal` and `ValueFieldRegenerate` take the props of a [Button](https://ui.jarv.is/components/button.md).
`ValueFieldCopy` takes the props of a `CopyButton` except `value` and `size`, which come from the
field. Each button's `aria-label` sets its accessible name, and its [Tooltip](https://ui.jarv.is/components/tooltip.md)
shows the same text. `ValueFieldReveal` keeps the same name whether the value is shown or hidden,
and is marked as pressed while the value is shown.

The file also exports `maskValue(value, visiblePrefix, visibleSuffix)`, which returns a masked
value as a string, such as for a [Table](https://ui.jarv.is/components/table.md) of keys.

| Part | Extends |
| --- | --- |
| `ValueField` | `<div>` |
| `ValueFieldReveal` | [`Button`](https://ui.jarv.is/components/button.md) |
| `ValueFieldCopy` | — |
| `ValueFieldRegenerate` | [`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`.

### ValueField

| Prop                | Type                                                                        | Default     | Description                                                                                                                                                                               |
| ------------------- | --------------------------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children?`         | `React.ReactNode`                                                           | —           | The buttons at the end of the row. Defaults to a `ValueFieldCopy`, after a `ValueFieldReveal` when `masked` is set.                                                                       |
| `value`             | `string`                                                                    | —           | The text shown and copied, such as a command or a key. Copying always copies all of it, even while it's masked.                                                                           |
| `display?`          | `React.ReactNode`                                                           | —           | Shown in place of `value`, such as the same text with its parts colored. `value` is still what's copied.                                                                                  |
| `label?`            | `React.ReactNode`                                                           | —           | A small label above the row.                                                                                                                                                              |
| `icon?`             | `React.ReactNode`                                                           | —           | An icon before the value, such as a terminal prompt for a command.                                                                                                                        |
| `copyOnClick?`      | `boolean`                                                                   | `false`     | Copies when someone clicks anywhere in the row, not only the copy button.                                                                                                                 |
| `masked?`           | `boolean`                                                                   | `false`     | Hides the value, such as an API key, until it's revealed.                                                                                                                                 |
| `visiblePrefix?`    | `number`                                                                    | `0`         | How many characters at the start stay visible while the value is masked, such as 8 for `sk_live_`.                                                                                        |
| `visibleSuffix?`    | `number`                                                                    | `4`         | How many characters at the end stay visible while the value is masked.                                                                                                                    |
| `revealed?`         | `boolean`                                                                   | —           | Whether a masked value is shown in full.                                                                                                                                                  |
| `defaultRevealed?`  | `boolean`                                                                   | `false`     | Whether a masked value is shown in full at first, when `revealed` isn't controlled.                                                                                                       |
| `onRevealedChange?` | `((revealed: boolean, eventDetails: ValueFieldChangeEventDetails) => void)` | —           | Called when a `ValueFieldReveal` shows or hides the value. Calling `eventDetails.cancel()` keeps the value as it is.                                                                      |
| `size?`             | `"default" \| "lg" \| "sm"`                                                 | `"default"` | The row's height: `sm` 24px, `default` 28px, `lg` 32px.                                                                                                                                   |
| `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. |

### ValueFieldReveal

| Prop                     | Type                                                                                 | Default     | Description                                                                                                                                                                               |
| ------------------------ | ------------------------------------------------------------------------------------ | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `focusableWhenDisabled?` | `boolean`                                                                            | `false`     | Whether the button should be focusable when disabled.                                                                                                                                     |
| `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>`).         |
| `variant?`               | `"default" \| "destructive" \| "ghost" \| "link" \| "outline" \| "primary"`          | `"ghost"`   |                                                                                                                                                                                           |
| `size?`                  | `"default" \| "icon" \| "icon-lg" \| "icon-sm" \| "icon-xs" \| "lg" \| "sm" \| "xs"` | `"default"` |                                                                                                                                                                                           |
| `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. |

### ValueFieldCopy

| Prop                     | Type                                                                                | Default     | Description                                                                                                                                                                               |
| ------------------------ | ----------------------------------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `aria-label?`            | `string`                                                                            | —           | Defines a string value that labels the current element. The button's accessible name, also shown in its tooltip until the button is pressed.                                              |
| `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?`               | `"default" \| "destructive" \| "ghost" \| "link" \| "outline" \| "primary"`         | —           |                                                                                                                                                                                           |
| `resetAfter?`            | `number`                                                                            | —           | How long the copied or failed state lasts before it resets, in milliseconds.                                                                                                              |
| `onCopy?`                | `((value: string) => void)`                                                         | —           | Called with the text once it's on the clipboard.                                                                                                                                          |
| `pendingAnnouncement?`   | `string`                                                                            | `"Loading"` | What screen readers announce when the promise from `value` hasn't settled after a second. Pass an empty string to announce nothing.                                                       |
| `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. |

### ValueFieldRegenerate

| 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?`               | `"default" \| "destructive" \| "ghost" \| "link" \| "outline" \| "primary"`          | `"ghost"`              |                                                                                                                                                                                           |
| `size?`                  | `"default" \| "icon" \| "icon-lg" \| "icon-sm" \| "icon-xs" \| "lg" \| "sm" \| "xs"` | `"default"`            |                                                                                                                                                                                           |
| `onClick?`               | `((event: UsePendingButtonEvent) => unknown)`                                        | —                      | Called when the button is pressed. Return a promise to keep the button pending, with its icon spinning, until it settles.                                                                 |
| `pendingAnnouncement?`   | `string`                                                                             | `"Regenerating value"` | What screen readers announce when the promise from `onClick` hasn't settled after a second. Pass an empty string to announce nothing.                                                     |
| `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. |
