<!-- generated by scripts/gen-docs.mjs from docs/system/invite-field.md. Edit the source and rerun. -->
# InviteField

## Description
Collects the email addresses of people to invite and the role they will get, then sends the invitations in one request and says how it went.

`import { InviteField, inviteFieldLabels, type MemberRole } from "@/components/cobalt/ui/invite-field"`, source `registry/cobalt/ui/invite-field.tsx`, status `ready`.
Foundation: `hand-rolled`. Traps checked: `trap/field-label`, `trap/field-input-type`, `trap/field-error-link`, `trap/field-error-timing`, `trap/field-keeps-input`, `trap/field-affix-focus`, `trap/touch-input-zoom`, `trap/button-icon-name`, `trap/submit-repeat`, `trap/loading-label-swap`, `trap/loading-layout-shift`, `trap/disabled-drops-focus`, `trap/toast-errors`, `trap/live-region-double`, `trap/color-only-status`, `trap/touch-hover-flash`, `trap/reduced-motion-ignored`, `trap/select-empty-value` (n/a: a role is always picked, the last one by default).

It reads addresses through `import { addAddresses, isEmail, readAddresses, sameAddress } from "@/lib/cobalt/emails"` (source `registry/cobalt/lib/emails.ts`), which has no DOM: it splits text at commas, semicolons, spaces and new lines, keeps the address of the `Ada Park <ada.park@example.com>` form a mail app copies, drops a leading "mailto:", keeps a piece that is not an address marked as such, and adds an address once whatever its case.

`trap/field-label` is answered by a visible "Email addresses" over the box, the system's `FieldLabel` bound to the addresses' input through `Field`, with the line under the box as its `FieldDescription`; the role and Invite sit beside the box outside the `Field`, so the label and the line belong to the addresses alone, and the placeholder is never the name (ARIA). `trap/field-input-type` by `type="email"` with `multiple` and autofill turned off (ARIA). `trap/field-error-link` by `aria-invalid` on the field and `aria-describedby` on the line under it (ARIA). `trap/field-error-timing` by judging an address only once it becomes a chip, at a separator, Enter, a paste or leaving the field (States). `trap/field-keeps-input` by the addresses staying after a failed send (States). `trap/field-affix-focus` by a press anywhere on the box's free space focusing the field. `trap/touch-input-zoom` by the field box's 16px text below 768px (Tokens). `trap/button-icon-name` by each chip's remove button, named "Remove" and the address (ARIA). `trap/submit-repeat`, `trap/loading-label-swap` and `trap/loading-layout-shift` by `StateButton`, which keeps its 62px width and its name while pending and ignores a second press (States). `trap/disabled-drops-focus` by Invite, which is never turned off by its state, only by `disabled`, so a press with nothing to send keeps the focus (Keyboard). `trap/toast-errors` by the failure staying on the line until the addresses change or Invite is pressed again (States). `trap/live-region-double` by Invite's own status line saying Sending, Sent and Not sent, while the field's status line reads only what Invite cannot say, an address that cannot be invited or that there is nothing to send; the line under the field is its description and is not live (ARIA). `trap/color-only-status` by the words on the line, which name every refused address, and a visually hidden ", cannot be invited" on each refused chip (States). `trap/touch-hover-flash` by the system's `hover` variant, which applies only under `(hover: hover)`. `trap/reduced-motion-ignored` by `StateButton`, which keeps its fades and drops its movement under reduced motion (Motion).

As chips fill the box it grows a row at a time over the composer's settle (`--t-settle`, through `useFollowHeight`), and the line and whatever is under the field move with it: measured at 390 in dark, a long address that took a row of its own grew the field 64px in steps of at most 16px a frame over about 300ms, where it jumped in one frame. The box's shell keeps 4px of room inside its clip, so the box's focus ring is never cut.

### Foundation
Not applicable: hand-rolled.

| Given by the foundation | Added by the team |
|---|---|
| The system's `Field`, `FieldLabel`, `FieldControl` and `FieldDescription`, the field box classes from `input-group.tsx`, `Select` for the role, `StateButton` and `useAction` for the request, `quietAutofill`, `useFollowHeight` for the box and the line | A field that turns each address into a chip as it is typed, at a comma, a semicolon, a space or Enter, or a pasted list at once; Backspace in the empty field takes the last address back to edit. The label "Email addresses" over the box, from `labels.field`. A chip that cannot be invited, because it is not an address or is in `existing`, sits on the red wash, and the line under the field names every such address in one sentence, grouped by why, "ada@example and lee@ are not email addresses, and maria.lopez@example.com already has access", while the box keeps its fill; the line wraps when it needs a second line, and its box grows to it over the system's Grow (`--t-layout`). Role options carry a line on what each allows. Invite reports its request in place: Sending, then Sent with the sent addresses gone from the field and "2 invitations sent" on the line for 3 seconds, or Not sent with the addresses kept and the reason on the line. While the request is out the field is read only, the chips' remove buttons and the role ignore presses, and nothing greys out. A visually hidden status line reads a refused address or the empty message, which Invite cannot say. The field grows a line at a time as chips fill it, and the role and Invite stay where they are |

## Examples
Invites people to a shared watchlist: type or paste addresses and each becomes a chip; one that already has access stays red with the reason under the field.

Real uses, 0 call sites (`rg -n "<InviteField\b" app registry --glob '!registry/cobalt/ui/*'`): no showcase page draws one outside the examples, and the examples folder does not count.

Uses inside the registry: none. `MemberList` imports only the `MemberRole` type, `registry/cobalt/ui/member-list.tsx:19`. The share dialog on the MemberList page composes it with the list and the link, `docs/system/examples/member-list/in-dialog.tsx:30`.

### Example files
| File | Covers | Caption |
|---|---|---|
| `docs/system/examples/invite-field/default.tsx` | default | Invites people to a shared watchlist; an address that is not one, or already has access, stays red with the reason under the field, and Invite sends nothing until it goes |
| `docs/system/examples/invite-field/failed.tsx` | state:failed | The first send fails: Invite says Not sent in place, the two addresses stay, and the line says what to do; the second press goes through |
| `docs/system/examples/invite-field/default.tsx` | composition:Select | The role is the system Select, and each option says what the role allows |
| `docs/system/examples/invite-field/in-card.tsx` | composition:Card | A team page's invite card with three roles, Analyst picked first through `defaultRole` |

Example: Invites people to a shared watchlist; an address that is not one, or already has access, stays red with the reason under the field, and Invite sends nothing until it goes (`docs/system/examples/invite-field/default.tsx`)

```tsx
import { InviteField, type MemberRole } from "@/components/cobalt/ui/invite-field";

const roles: MemberRole[] = [
  { value: "owner", label: "Owner", description: "Can share, rename and delete the watchlist." },
  { value: "editor", label: "Editor", description: "Can add and remove funds and write notes." },
  { value: "viewer", label: "Viewer", description: "Can see the funds and notes." },
];

// Stands in for the request that sends the invitations.
const send = () => new Promise((resolve) => setTimeout(resolve, 900));

export default function Example() {
  return (
    <div className="w-full max-w-xl">
      <InviteField roles={roles} existing={["maria.lopez@example.com"]} onInvite={send} />
    </div>
  );
}
```

Example: The role is the system Select, and each option says what the role allows (`docs/system/examples/invite-field/default.tsx`)

```tsx
import { InviteField, type MemberRole } from "@/components/cobalt/ui/invite-field";

const roles: MemberRole[] = [
  { value: "owner", label: "Owner", description: "Can share, rename and delete the watchlist." },
  { value: "editor", label: "Editor", description: "Can add and remove funds and write notes." },
  { value: "viewer", label: "Viewer", description: "Can see the funds and notes." },
];

// Stands in for the request that sends the invitations.
const send = () => new Promise((resolve) => setTimeout(resolve, 900));

export default function Example() {
  return (
    <div className="w-full max-w-xl">
      <InviteField roles={roles} existing={["maria.lopez@example.com"]} onInvite={send} />
    </div>
  );
}
```

Example: A team page's invite card with three roles, Analyst picked first through `defaultRole` (`docs/system/examples/invite-field/in-card.tsx`)

```tsx
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/cobalt/ui/card";
import { InviteField, type MemberRole } from "@/components/cobalt/ui/invite-field";

const roles: MemberRole[] = [
  { value: "admin", label: "Admin", description: "Can invite and remove people and change billing." },
  { value: "analyst", label: "Analyst", description: "Can build screens, watchlists and exports." },
  { value: "viewer", label: "Viewer", description: "Can read shared watchlists and notes." },
];

// Stands in for the request that sends the invitations.
const send = () => new Promise((resolve) => setTimeout(resolve, 900));

export default function Example() {
  return (
    <Card className="w-full max-w-xl">
      <CardHeader>
        <CardTitle>Invite your team</CardTitle>
        <CardDescription>Each person gets an email with a link that works for seven days.</CardDescription>
      </CardHeader>
      <CardContent>
        <InviteField roles={roles} defaultRole="analyst" onInvite={send} />
      </CardContent>
    </Card>
  );
}
```

## Variants
Not applicable: InviteField has no variant axis. The roles are data, and `disabled` is a state.

## States
| State | Trigger | What the user can do | Shown by, besides color | Checked by |
|---|---|---|---|---|
| empty | rendered with no addresses | type or paste addresses | the placeholder "Add email addresses" and the line "Separate addresses with commas or spaces" | test |
| typing | part of an address typed, before a separator | keep typing, then a comma, a semicolon, a space or Enter, or leave the field | the text in the field | by hand |
| chips | addresses turned into chips, or `defaultAddresses` | remove one, take the last back with Backspace, pick a role, press Invite | each address as a chip with its remove button | test |
| refused | a chip is not an address, or is in `existing` | remove it, or take it back and fix it | the chip on the red wash, ", cannot be invited" read after it, `aria-invalid` on the field, and the line naming every refused address in one sentence, grouped by why, such as "ada@example and lee@ are not email addresses, and maria.lopez@example.com already has access", which the field's status line reads once; at 390 that sentence takes two lines and the line's box grows 16px over 450ms, never in one frame (measured frame by frame at 1440 light and 390 dark) | test |
| nothing to send | Invite pressed with no address | type or paste an address | the line "Add an email address to invite", read once by the field's status line, until something is typed; Invite keeps the focus | by hand |
| pending | Invite pressed with addresses that can all be invited | wait | from 250ms a spinner and "Sending" inside Invite at its width, `aria-busy` and `aria-disabled`; the field read only and the remove buttons `aria-disabled`, all at their usual look; Enter, Backspace and paste in the field do nothing, and a role picked from the list is ignored, so the role shown is the one sent (measured) | by hand |
| sent | `onInvite` resolved | invite more people | a check and "Sent" in Invite for 1.5 seconds, the sent addresses gone from the field, and "2 invitations sent" on the line for 3 seconds (measured on the showcase) | by hand |
| failed | `onInvite` rejected | press Invite again, or change the addresses | a cross and "Not sent" in Invite for 1.5 seconds, then its label; the addresses stay; the line reads "Not sent. Check your connection and try again." until the addresses change, by typing, a paste or a removal, or Invite is pressed again (measured still there 4 seconds after the failure) | by hand |
| focus-visible | Tab into the field | type | the field box's accent edge and soft ring, after Tab only | by hand |
| hover | the pointer over a chip's remove button, under `(hover: hover)` | press it | pointer only, colour change: the grey fill behind the cross | by hand |
| disabled | `disabled` | nothing | the field, the remove buttons, the role and Invite disabled at half opacity | by hand |

Example: The first send fails: Invite says Not sent in place, the two addresses stay, and the line says what to do; the second press goes through (`docs/system/examples/invite-field/failed.tsx`)

```tsx
import { useRef } from "react";

import { InviteField, type MemberRole } from "@/components/cobalt/ui/invite-field";

const roles: MemberRole[] = [
  { value: "editor", label: "Editor", description: "Can add and remove funds and write notes." },
  { value: "viewer", label: "Viewer", description: "Can see the funds and notes." },
];

export default function Example() {
  const tries = useRef(0);
  // Stands in for a request that fails the first time.
  const send = () =>
    new Promise((resolve, reject) =>
      setTimeout(() => ((tries.current += 1) === 1 ? reject(new Error("offline")) : resolve(undefined)), 900),
    );
  return (
    <div className="w-full max-w-xl">
      <InviteField roles={roles} defaultAddresses={["lee.chen@example.com", "sofia.martin@example.com"]} onInvite={send} />
    </div>
  );
}
```

### State precedence
- Failed and refused: Not applicable: a send needs every chip to be one that can be invited, and typing, a paste or a removal ends the failure before a new chip can be refused.
- Pending and a role picked from the list: pending wins. The pick is ignored, and the role sent stays shown.
- Refused and nothing to send: Not applicable: nothing to send means there is no chip.
- Pending and sent, or pending and failed: Not applicable: the request ends in one answer, which replaces pending.
- Sent and typing: both show. The line says how many were sent while the next address is typed.
- Refused and sent: Not applicable: a send needs every chip to be one that can be invited, and the next chip added ends the sent line.
- Pending and focus-visible: both show. Focus stays where it was, on Invite or in the read-only field.
- Disabled and every other state: disabled wins. Nothing takes a press.

### Motion
| Trigger | Kind | Preset | Properties | Reduced motion |
|---|---|---|---|---|
| Invite's words change to Sending, Sent or Not sent and back | announce | `StateButton`'s handover: the old copy leaves on 70 percent of `--t-pop`, the new arrives on the settle spring once the old is nearly gone | opacity, transform | the fades stay and the movement drops (`MotionConfig reducedMotion="user"`) |
| the role list opens or closes | announce | the Select's `popup-motion`, `--t-pop` on `--curve` | opacity | the same fade |
| a chip's remove button is hovered or pressed | input | `pressable`, `--t-press` on `--curve` | color, background-color | the same |

## Props

<!-- Props generated from registry/cobalt/ui/invite-field.tsx with TypeScript by scripts/props-table.mjs -->
| Prop | Type | Default | Purpose |
|---|---|---|---|
| `onInvite` | `(addresses: string[], role: string) => Promise<unknown>` |  | Sends the invitations. |
| `roles` | `MemberRole[]` |  | The roles that can be given, in order, each with a line on what it allows. |
| `className?` | `string` |  |  |
| `defaultAddresses?` | `string[]` | `[]` | Addresses the field opens with, such as people suggested from a team. |
| `defaultRole?` | `string` |  | The role picked when the field opens. |
| `disabled?` | `boolean` | `false` |  |
| `existing?` | `string[]` | `[]` | Addresses that already have access or an invitation, which cannot be invited again. |
| `labels?` | `Partial<{ field: string; placeholder: string; role: string; invite: string; inviting: string; invited: string; notInvited: string; remove: (address: string) => string; hint: string; notAnAddress: (addresses: string, count: number) => string; hasAccess: (addresses: string, count: number) => string; bothProblems: (notAddresses: string, withAccess: string) => string; list: (addresses: string[]) => string; problem: string; sent: (count: number) => string; failed: string; empty: string; }>` |  |  |

`roles` lists the roles in order, each a `value`, a `label` and an optional `description` of what it allows. `defaultRole` is the role picked when the field opens, the last role by default. `onInvite` gets the addresses and the role, and must resolve once the invitations are sent and reject when they are not. `existing` holds addresses that already have access or an invitation, matched whatever their case. `defaultAddresses` are chips the field opens with. `disabled` turns everything off. `labels` replaces any string in `inviteFieldLabels`: `field` is the visible label; `notAnAddress` and `hasAccess` take the addresses already joined by `list`, which writes "a, b, and c", and their count; `bothProblems` joins the two reasons; and `className` places the field.

## Usage

### When to use
- People are invited by email to something shared, such as a watchlist, a workspace or a team, with a role each.
- A list of addresses is pasted from a mail app or a spreadsheet and sent in one request.

### When not to use
- People are picked from a directory the app already holds, such as teammates by name. Use Combobox instead, with `multiple`.
- One address for an account, such as a contact field. Use Input instead, with `type="email"` inside a Field.
- Access is given by a link anyone with it can open. Use ShareLink instead, on the MemberList page.

### Rules
- `rule/invite-field-pass-existing`: When people already have access or an invitation, pass their addresses in `existing` instead of leaving the server to refuse them, because the field then marks each one red with "already has access" before Invite is pressed, and sends nothing while one is in the field. Evidence: principle heuristic: error prevention, the refusal comes before the request; single use `docs/system/examples/member-list/in-dialog.tsx:32`, which passes the list's addresses. Check: review of every `InviteField` beside a `MemberList`.
  - Don't: `<InviteField roles={roles} onInvite={invite} />` above `<MemberList label="People with access">`
  - Do: `<InviteField roles={roles} existing={members.map((m) => m.email)} onInvite={invite} />`
- `rule/invite-field-reject-on-failure`: When `onInvite` does not send the invitations, reject its promise, such as `throw new Error("offline")`, instead of resolving with an error value, because only a rejection turns Invite to "Not sent" and keeps the addresses, while a resolved promise removes them and says "2 invitations sent". Evidence: person D39. Check: review of every `onInvite`.
  - Don't: `onInvite={async (addresses, role) => { const res = await api.invite(addresses, role); return res.ok; }}`
  - Do: `onInvite={async (addresses, role) => { const res = await api.invite(addresses, role); if (!res.ok) throw new Error(res.statusText); }}`
- `rule/invite-field-least-role-by-default`: When the roles run from most access to least, list them in that order and keep the last as the default, or pass `defaultRole` for the role most invitations get, instead of putting the most powerful role first and picked, because an invitation sent with the role nobody changed gives the access nobody chose. Evidence: principle heuristic: error prevention, the default is the safe choice; app 4/4 role lists given to an InviteField in docs/system/examples open on the last role, Viewer, or on `defaultRole="analyst"`. Check: review of every `roles` and `defaultRole`.
  - Don't: `<InviteField roles={[viewer, editor, owner]} onInvite={invite} />`
  - Do: `<InviteField roles={[owner, editor, viewer]} onInvite={invite} />`
- `rule/invite-field-under-a-title`: When placing an `InviteField`, put it under a title that says what the invitations are to, such as `DialogTitle` "Share Large cap core" or `CardTitle` "Invite your team", instead of on its own, because the field's label, "Email addresses", names only what goes in it, not what the invitations give access to. Evidence: person D34; principle wcag: 3.3.2 Labels or instructions, the purpose is visible. Check: review of every `InviteField`.
  - Don't: `<section><InviteField roles={roles} onInvite={invite} /></section>`
  - Do: `<Card><CardHeader><CardTitle>Invite your team</CardTitle></CardHeader><CardContent><InviteField roles={roles} onInvite={invite} /></CardContent></Card>`

### Content
- Follows `rule/writing-status-verb-ing`.
- `rule/invite-field-role-says-what-it-allows`: When writing a role's `description`, start with "Can" and say what the role may do in one sentence, such as "Can add and remove funds and write notes.", instead of repeating its name, because the option is where a person decides how much access to give. Evidence: app 5/5 role lists in the invite-field and member-list examples start each description with "Can"; principle heuristic: recognition rather than recall. Check: review of every `roles` array.
  - Don't: `{ value: "editor", label: "Editor", description: "Editor role." }`
  - Do: `{ value: "editor", label: "Editor", description: "Can add and remove funds and write notes." }`

### Anti-slop
- `rule/invite-field-not-a-textarea`: When collecting several addresses to invite, use `InviteField` instead of a `Textarea` or an `Input` split at commas on submit, because the field turns each address into a chip as it is typed, reads the `Name <address>` form a mail app copies, and marks the addresses it cannot send before anything is sent. Evidence: principle heuristic: error prevention; single use `docs/system/examples/member-list/in-dialog.tsx:30`. Check: review of every form that sends invitations.
  - Don't: `<Textarea placeholder="Emails, separated by commas" />`
  - Do: `<InviteField roles={roles} existing={members.map((m) => m.email)} onInvite={invite} />`
- `rule/invite-field-no-toast-after-sending`: When the invitations are sent, let Invite and the line under the field report it instead of calling `toast()`, because the field already says "Sent" and "2 invitations sent" where the person pressed. Evidence: person D39; principle wcag: 4.1.3 Status messages, one message per change of status. Check: review of every `onInvite` that calls `toast`.
  - Don't: `onInvite={async (addresses, role) => { await api.invite(addresses, role); toast("Invitations sent"); }}`
  - Do: `onInvite={(addresses, role) => api.invite(addresses, role)}`

### Limits
- `rule/invite-field-line-length`: When replacing a line in `labels`, such as `failed`, `hint` or `empty`, keep it to 55 characters, because at 390 a longer line wraps to a second line, and the field grows by it, moving what is below once. Evidence: measured at 390 on /components/invite-field with Playwright, in the example's 310px field, the first cut at 56 characters, while the default `failed`, 46 characters, fits whole. Check: review of every `labels` passed.
  - Don't: `labels={{ failed: "We were not able to send your invitations right now. Please try again in a moment." }}`
  - Do: `labels={{ failed: "Not sent. Try again in a moment." }}`

## Accessibility
Rests on a native `input type="email"` with `multiple` inside the system field box, the system `Select` for the role, and `StateButton` for Invite. Screen reader pass with VoiceOver: NEEDS REVIEW.

### Keyboard
| Key | Where focus is | Effect | Focus after | Checked by |
|---|---|---|---|---|
| Comma, semicolon, Space | the field, with text typed | turns the text into a chip | stays in the field | by hand |
| Enter | the field, with text typed | turns the text into chips | stays in the field | by hand |
| Enter | the empty field | presses Invite: sends, or says what is missing | stays in the field | by hand |
| Backspace | the empty field, with chips | takes the last address back into the field to edit | stays in the field | by hand |
| Tab | the field | turns any text into chips as the field is left | the role (measured) | by hand |
| Shift+Tab | the field | moves back along the chips' remove buttons | the last chip's remove button (measured) | by hand |
| Enter, Space | a chip's remove button | removes the chip | the field | by hand |
| Enter, Space | the role | opens the list of roles; the arrows move, Enter picks | the role | by hand |
| Enter, Space | Invite | sends; with nothing to send, the line says so | stays on Invite, also while pending (measured) | by hand |
| Enter, Backspace, paste | the field while pending | nothing | stays in the field | by hand |

### ARIA
| Part | Role | Accessible name from | States and properties | Announced | Checked by |
|---|---|---|---|---|---|
| field | textbox | the visible `FieldLabel` "Email addresses" from `labels.field`, through its `for` | `aria-invalid` while a chip is refused, `aria-describedby` the line, the Field's description (measured in the browser), `readonly` while pending | the name, the placeholder while empty, and the line | test |
| chip | none, text | its address, then ", cannot be invited", visually hidden, when refused | none | read in order before the field | test |
| chip's remove button | button | "Remove" and the address, from `labels.remove` | `aria-disabled` while pending | "Remove ada.park@example.com, button" | test |
| role | combobox, the Select's trigger | "Role" from `labels.role` | `aria-expanded`, `aria-haspopup="listbox"` | the name and the role picked | by hand |
| role option | option | the role's label and its description | `aria-selected` | both lines | by hand |
| Invite | button | its label, "Invite", which never changes | `aria-busy` and `aria-disabled` while pending | the name; its own status line says "Sending", "Sent" or "Not sent" once (measured) | by hand |
| line under the field | none, the field's description through `aria-describedby` | none | not live | the hint, a reason, "2 invitations sent" or the failure, read with the field | by hand |
| field's status line | status, visually hidden | none | none | a refused address, such as "not-an-address is not an email address", or "Add an email address to invite", once as it comes; nothing for a send's result (measured) | by hand |

## Tokens
| Part | State | Token |
|---|---|---|
| field box | all | `--control`, `--r-control`, `--input` |
| field box | focus-visible | `--primary` |
| chip | all | `--card`, `--muted` in dark mode, `--r-control-sm` |
| chip | refused | `--destructive` |
| chip's remove button | hover | `--muted`, `--muted-hover` in dark mode, `--foreground`, `--t-press` |
| line under the field | all | `--muted-foreground`, `--destructive` |
| Invite | all | `StateButton`'s: `--primary`, and `--destructive` for the failure's wash |
| role | all | the Select's: `--control`, `--r-control`, `--input` |

## Related
- MemberList: the people who already have access, with their roles, and the link to share.
- Combobox: people picked by name from a directory the app holds.
- StateButton: the button that reports a request in place.
- Input: one email address in a Field.
