# Team members

A team settings page: an invite form with a validated `Field` for email addresses and a role `Select`, a members `Table` with initials avatars, a role `Select` per row (the owner’s is locked), 2FA `Badge`s, a row `Menu` whose Remove asks first in a `Modal`, and pending invitations you can resend or revoke.

**Example: Fernhill team** (`examples/recipes/team-members.tsx`)

```tsx
'use client'

import {
  Badge,
  BodySmall,
  Button,
  Card,
  Field,
  Heading,
  Menu,
  Modal,
  Select,
  Stack,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableHeader,
  TableRow,
  Text,
  toastSuccess,
} from '@blocks/design-system'
import { Lock, MoreHorizontal, ShieldAlert, ShieldCheck } from 'lucide-react'
import { type FormEvent, useId, useRef, useState } from 'react'
import styles from './team-members.module.css'

const roles = [
  { value: 'admin', label: 'Admin' },
  { value: 'member', label: 'Member' },
  { value: 'viewer', label: 'Viewer' },
]
const roleLabel = (role: string) => roles.find((item) => item.value === role)?.label ?? 'Owner'

interface Member {
  email: string
  name: string
  role: string
  twoFactor: boolean
  lastActive: string
}

interface Invite {
  email: string
  role: string
  sent: string
}

const initialMembers: Member[] = [
  { email: 'dana@fernhill.example', name: 'Dana Whitfield', role: 'owner', twoFactor: true, lastActive: 'Active now' },
  { email: 'marcus@fernhill.example', name: 'Marcus Oyelaran', role: 'admin', twoFactor: true, lastActive: '2 hours ago' },
  { email: 'sofia@fernhill.example', name: 'Sofia Lindgren', role: 'member', twoFactor: false, lastActive: 'Yesterday' },
  { email: 'kenji@fernhill.example', name: 'Kenji Morimoto', role: 'member', twoFactor: true, lastActive: 'Nov 27' },
  { email: 'rosa@fernhill.example', name: 'Rosa Delgado', role: 'viewer', twoFactor: false, lastActive: 'Nov 12' },
]

const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

function initials(name: string) {
  return name
    .split(' ')
    .map((part) => part[0])
    .join('')
}

export default function TeamMembers() {
  const [members, setMembers] = useState(initialMembers)
  const [invites, setInvites] = useState<Invite[]>([{ email: 'lena@fernhill.example', role: 'member', sent: 'Sent Nov 29' }])
  const [inviteError, setInviteError] = useState<string | null>(null)
  // The modal keeps its member while it animates closed, so the title never flashes empty.
  const [confirming, setConfirming] = useState(false)
  const [removing, setRemoving] = useState<Member | null>(null)
  const membersHeading = useRef<HTMLHeadingElement>(null)
  const removed = useRef(false)
  const id = useId()

  function sendInvites(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const form = event.currentTarget
    const data = new FormData(form)
    const emails = String(data.get('emails'))
      .split(/[\s,]+/)
      .filter(Boolean)
    const taken = new Set([...members, ...invites].map((person) => person.email))
    const invalid = emails.find((email) => !emailPattern.test(email))
    const duplicate = emails.find((email) => taken.has(email))

    if (emails.length === 0) return setInviteError('Enter at least one email address.')
    if (invalid) return setInviteError(`“${invalid}” isn’t a valid email address.`)
    if (duplicate) return setInviteError(`${duplicate} is already on the team or invited.`)

    const role = String(data.get('role'))
    setInviteError(null)
    setInvites((current) => [...emails.map((email) => ({ email, role, sent: 'Sent just now' })), ...current])
    form.reset()
    toastSuccess(emails.length === 1 ? `Invited ${emails[0]}` : `Invited ${emails.length} people`)
  }

  function changeRole(member: Member, role: string) {
    setMembers((current) => current.map((item) => (item.email === member.email ? { ...item, role } : item)))
    toastSuccess(`${member.name} is now ${role === 'admin' ? 'an' : 'a'} ${roleLabel(role)}`)
  }

  function askToRemove(member: Member) {
    removed.current = false
    setRemoving(member)
    setConfirming(true)
  }

  function confirmRemove(event: FormEvent<HTMLFormElement>) {
    event.preventDefault()
    if (!confirming || !removing) return
    removed.current = true
    setMembers((current) => current.filter((item) => item.email !== removing.email))
    toastSuccess(`Removed ${removing.name} from Fernhill`)
    setConfirming(false)
  }

  function resend(invite: Invite) {
    setInvites((current) => current.map((item) => (item.email === invite.email ? { ...item, sent: 'Sent just now' } : item)))
    toastSuccess(`Sent a new invite to ${invite.email}`)
  }

  function revoke(invite: Invite) {
    setInvites((current) => current.filter((item) => item.email !== invite.email))
    toastSuccess(`Revoked the invite for ${invite.email}`)
  }

  return (
    <Stack gap="xl" dangerouslySetClassName={styles.team}>
      <Card as="section" padding="lg" aria-labelledby={`${id}-invite`}>
        <Stack as="form" gap="md" onSubmit={sendInvites} noValidate>
          <Heading as="h2" id={`${id}-invite`} fontSize="md">
            Invite people
          </Heading>
          <div className={styles.inviteRow}>
            <Field name="emails" invalid={inviteError !== null} dangerouslySetClassName={styles.emails}>
              <Field.Label>Email addresses</Field.Label>
              <Field.Control placeholder="ari@fernhill.example, sam@fernhill.example" onChange={() => setInviteError(null)} />
              <Field.Error match={inviteError !== null}>{inviteError}</Field.Error>
            </Field>
            <Stack gap="sm">
              <Select name="role" items={roles} defaultValue="member">
                <Select.Label>Role</Select.Label>
                <Select.Trigger dangerouslySetClassName={styles.roleTrigger} />
                <Select.Content>
                  {roles.map((role) => (
                    <Select.Item key={role.value} value={role.value}>
                      {role.label}
                    </Select.Item>
                  ))}
                </Select.Content>
              </Select>
            </Stack>
            <Button type="submit" variant="primary" dangerouslySetClassName={styles.inviteButton}>
              Send invites
            </Button>
          </div>
        </Stack>
      </Card>

      <Stack as="section" gap="md" aria-labelledby={`${id}-members`}>
        <Stack direction="row" justify="space-between" align="baseline" gap="sm" wrap="wrap">
          <Heading as="h2" id={`${id}-members`} ref={membersHeading} tabIndex={-1} fontSize="lg">
            Members
          </Heading>
          <BodySmall color="text-muted" margin="none">
            {members.length} of 10 seats
          </BodySmall>
        </Stack>
        <TableContainer tabIndex={0} role="region" dangerouslySetClassName={styles.scroller} aria-labelledby={`${id}-members`}>
          <Table dangerouslySetClassName={styles.members}>
            <TableHeader>
              <TableRow>
                <TableHead scope="col">Name</TableHead>
                <TableHead scope="col">Role</TableHead>
                <TableHead scope="col">2FA</TableHead>
                <TableHead scope="col">Last active</TableHead>
                <TableHead scope="col">
                  <span className="visually-hidden">Actions</span>
                </TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {members.map((member) => (
                <TableRow key={member.email} dangerouslySetClassName={styles.member}>
                  <TableHead scope="row" dangerouslySetClassName={styles.person}>
                    <span className={styles.avatar} aria-hidden>
                      {initials(member.name)}
                    </span>
                    <Stack gap="none">
                      <Text fontSize="sm" fontWeight="semibold">
                        {member.name}
                      </Text>
                      <Text fontSize="xs" fontWeight="body" color="text-muted">
                        {member.email}
                      </Text>
                    </Stack>
                  </TableHead>
                  <TableCell dangerouslySetClassName={styles.cellRole}>
                    {member.role === 'owner' ? (
                      <span className={styles.locked}>
                        <Lock aria-hidden size={12} />
                        Owner<span className="visually-hidden"> (transfer ownership to change)</span>
                      </span>
                    ) : (
                      <Select items={roles} value={member.role} onValueChange={(role) => role && changeRole(member, role)}>
                        <Select.Label dangerouslySetClassName="visually-hidden">Role for {member.name}</Select.Label>
                        <Select.Trigger size="sm" dangerouslySetClassName={styles.roleTrigger} />
                        <Select.Content>
                          {roles.map((role) => (
                            <Select.Item key={role.value} value={role.value}>
                              {role.label}
                            </Select.Item>
                          ))}
                        </Select.Content>
                      </Select>
                    )}
                  </TableCell>
                  <TableCell dangerouslySetClassName={styles.cellTwoFactor}>
                    {member.twoFactor ? (
                      <Badge tone="success" dangerouslySetClassName={styles.twoFactor}>
                        <ShieldCheck aria-hidden />
                        <span className={styles.wideOnly}>On</span>
                        <span className={styles.narrowOnly}>2FA on</span>
                      </Badge>
                    ) : (
                      <Badge tone="warning" dangerouslySetClassName={styles.twoFactor}>
                        <ShieldAlert aria-hidden />
                        <span className={styles.wideOnly}>Off</span>
                        <span className={styles.narrowOnly}>2FA off</span>
                      </Badge>
                    )}
                  </TableCell>
                  <TableCell dangerouslySetClassName={`${styles.nowrap} ${styles.cellActive}`}>
                    <Text fontSize="sm" color="text-muted">
                      {member.lastActive}
                    </Text>
                  </TableCell>
                  <TableCell dangerouslySetClassName={styles.cellActions}>
                    {member.role !== 'owner' && (
                      <Menu>
                        <Menu.Trigger render={<Button type="button" size="sm" variant="ghost" aria-label={`Actions for ${member.name}`} />}>
                          <MoreHorizontal aria-hidden size={16} />
                        </Menu.Trigger>
                        <Menu.Content align="end">
                          <Menu.LinkItem href={`#member-${member.email.split('@')[0]}`}>View activity</Menu.LinkItem>
                          <Menu.Separator />
                          <Menu.Item onClick={() => askToRemove(member)}>Remove from team…</Menu.Item>
                        </Menu.Content>
                      </Menu>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </TableContainer>
      </Stack>

      <Stack as="section" gap="md" aria-labelledby={`${id}-pending`}>
        <Heading as="h2" id={`${id}-pending`} fontSize="lg">
          Pending invitations
        </Heading>
        {invites.length === 0 ? (
          <BodySmall color="text-muted" margin="none">
            No pending invitations.
          </BodySmall>
        ) : (
          <Card as="ul" padding="none" margin="none" dangerouslySetClassName={styles.invites}>
            {invites.map((pending) => (
              <li key={pending.email} className={styles.invite}>
                <Stack gap="none">
                  <Text fontSize="sm" fontWeight="semibold">
                    {pending.email}
                  </Text>
                  <Text fontSize="xs" color="text-muted">
                    {roleLabel(pending.role)} · {pending.sent}
                  </Text>
                </Stack>
                <Stack direction="row" gap="sm">
                  <Button type="button" size="sm" variant="ghost" onClick={() => resend(pending)} aria-label={`Resend invite to ${pending.email}`}>
                    Resend
                  </Button>
                  <Button type="button" size="sm" variant="ghost" onClick={() => revoke(pending)} aria-label={`Revoke invite for ${pending.email}`}>
                    Revoke
                  </Button>
                </Stack>
              </li>
            ))}
          </Card>
        )}
      </Stack>

      <Modal open={confirming} onOpenChange={setConfirming}>
        {/* The removed row's menu button is gone, so focus lands on the list's heading instead. */}
        <Modal.Content finalFocus={() => (removed.current ? membersHeading.current : true)}>
          <Modal.Header>Remove {removing?.name}?</Modal.Header>
          <Stack as="form" gap="md" onSubmit={confirmRemove}>
            <Modal.Body>
              They lose access to every Fernhill project right away. Their comments and files stay. You can invite them again later.
            </Modal.Body>
            <Modal.Footer>
              <Modal.Close render={<Button type="button" variant="ghost" />}>Cancel</Modal.Close>
              <Button type="submit" variant="primary">
                Remove member
              </Button>
            </Modal.Footer>
          </Stack>
        </Modal.Content>
      </Modal>
    </Stack>
  )
}
```

## How it works

- **Invites validate on submit.** The form checks every address, rejects malformed ones and people already on the team, and shows the first problem with `Field.Error` on an `invalid` `Field`. Typing clears the error; a valid submit adds the invitations and confirms with a toast.
- **Every row control has a name.** Each role `Select` has a visually hidden `Select.Label` (“Role for Sofia Lindgren”), and each menu button is labelled with the member’s name. The owner’s role is text with a lock icon and a hidden note on how to change it.
- **Destructive actions confirm.** Remove opens a `Modal` that keeps the member’s name while it animates closed. After a removal the row’s menu button no longer exists, so `finalFocus` sends focus to the Members heading; after Cancel focus returns to the menu button as usual.
- **Status is spelled out.** 2FA badges pair a shield icon with “On” or “Off”, so the warning tone is never the only signal.
- **Phones get stacked members.** On a narrow container each row becomes name and email with the menu beside them, then the role select, 2FA and last active underneath, so no control is half off-screen.

## App-owned CSS

The invite row’s layout, avatars, the locked owner role, the invitation list and the narrow-screen member layout.

`examples/recipes/team-members.module.css`:

```css
/* Emails take the free space; role and the button sit beside them, or wrap below on a phone. */
.inviteRow {
  display: flex;
  flex-wrap: wrap;
  align-items: flex-start;
  gap: var(--ds-space-md);
}

.emails {
  flex: 1 1 16rem;
}

/* Line the button up with the controls, below their labels. */
.inviteButton {
  margin-top: calc(var(--ds-font-size-sm) * var(--ds-line-height-body) + var(--ds-space-sm));
}

.roleTrigger {
  min-width: 7.5rem;
}

.person {
  display: flex;
  align-items: center;
  gap: var(--ds-space-md);
  min-width: 12rem;
  font-weight: inherit;
}

.avatar {
  display: inline-flex;
  flex-shrink: 0;
  align-items: center;
  justify-content: center;
  width: calc(var(--ds-space-xl) + var(--ds-space-sm));
  height: calc(var(--ds-space-xl) + var(--ds-space-sm));
  border-radius: var(--ds-border-radius-circle);
  background-color: var(--ds-color-accent-subtle);
  color: var(--ds-color-accent-text);
  font-size: var(--ds-font-size-sm);
  font-weight: var(--ds-font-weight-semibold);
}

.locked {
  display: inline-flex;
  align-items: center;
  gap: var(--ds-space-sm);
  color: var(--ds-color-text-muted);
}

.nowrap {
  white-space: nowrap;
}

.invites {
  list-style: none;
}

.invite {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  gap: var(--ds-space-md);
  padding: var(--ds-space-md) var(--ds-space-lg);

  & + & {
    border-top: var(--ds-border-width-sm) solid var(--ds-color-border-subtle);
  }
}

/* Positioned, so visually hidden text in the cells scrolls with the table instead of widening the page. */
.scroller {
  position: relative;
}

/* One step up from the badge's default, to match the row's text. */
span.twoFactor {
  font-size: var(--ds-font-size-sm);

  & svg {
    width: var(--ds-font-size-sm);
    height: var(--ds-font-size-sm);
  }
}

.team {
  container-type: inline-size;
}

/*
 * On a narrow container each member becomes a card-like row: name and email
 * with the menu beside them, then role, 2FA and last active underneath. The
 * header row stays in the table for screen readers but leaves the layout.
 */
/* The 2FA column header names the badge on a wide screen; stacked, the badge names itself. */
.narrowOnly {
  display: none;
}

@container (max-width: 34rem) {
  .narrowOnly {
    display: inline;
  }

  .wideOnly {
    display: none;
  }

  .members,
  .members > tbody {
    display: block;
  }

  .members > thead {
    position: absolute;
    width: 1px;
    height: 1px;
    overflow: hidden;
    clip-path: inset(50%);
  }

  .member {
    display: grid;
    grid-template-columns: auto auto minmax(0, 1fr) auto;
    align-items: center;
    gap: var(--ds-space-md);
    padding: var(--ds-space-md) var(--ds-space-sm);

    & > td,
    & > th {
      padding: 0;
    }
  }

  .person {
    grid-area: 1 / 1 / 2 / 4;
    min-width: 0;
  }

  .cellActions {
    grid-area: 1 / 4;
  }

  .cellRole {
    grid-area: 2 / 1;
  }

  .cellTwoFactor {
    grid-area: 2 / 2;
  }

  /* Clear of the 2FA badge; wraps rather than crowding it. */
  .member > .cellActive {
    grid-area: 2 / 3 / 3 / 5;
    justify-self: end;
    padding-left: var(--ds-space-md);
    white-space: normal;
    text-align: end;
  }
}
```
