Ir al contenido

InviteMembers

El equipo de una organización: quién está y con qué rol, a quién se invitó y aún no llega, y cuántos puestos quedan. Invitar acepta varios correos a la vez y un rol.

import { TagInput, RadioCards, UsageBar } from '@sypnia/ui/react'

En esta página
  1. En un computador
  2. En un celular
  3. Solo tú
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

En un computador

Invita a varias personas a la vez (un correo mal escrito se nombra), cambia un rol, cancela una invitación pendiente, saca a alguien.

Miembros

Las personas de Northwind y lo que cada una puede hacer.

Puestos5 de 8

Miembros

PersonaRolEntró
ARAna Ruizana@northwind.ioTú · Dueño13 oct 2025
LOLuis Ortegaluis@northwind.io
2 nov 2025
MGMarta Gilmarta@northwind.io
19 ago 2026
KMKenji Morikenji@northwind.io
5 nov 2026

Invitaciones pendientes

PersonaRolEnviada
sofia@northwind.ioEditoranteayer
Código
import { useState } from 'react';
import {
  Badge, Button, ConfirmDialog, Dialog, EmptyState, Field, Form, FormActions, Identity, Page, PageHeader, Panel, RadioCards,
  RowActions, Select, SkeletonOf, SkeletonWords, Table, TagInput, Textarea, Toaster, UsageBar, toast, useSypnia, type FormProblem,
} from '@sypnia/ui/react';

// The team of an organization: who is in, with what role, who was invited and has not come yet, and how many seats
// are left. Inviting takes several emails at once and one role; wrong addresses are named one by one.
const en = {
  title: 'Members', lead: 'People in Northwind and what each can do.', invite: 'Invite people', seats: 'Seats', seatsAction: 'Add seats',
  members: 'Members', pending: 'Invitations waiting', person: 'Person', role: 'Role', since: 'Joined', sent: 'Sent', actions: (n: string) => `Actions for ${n}`,
  you: 'You', emails: 'Emails', emailsHint: 'Paste or type several, separated by commas or spaces.', emailsAdd: 'name@company.com',
  message: 'A note for them', send: 'Send invitations', sending: 'Sending…',
  noEmails: 'Write at least one email.', bad: (e: string) => `${e} is not an email address. Fix it or remove it.`, full: (n: number) => `Only ${n} seats are left. Remove some emails or add seats.`,
  sentN: (n: number) => (n === 1 ? 'Invitation sent' : `${n} invitations sent`), resend: 'Send again', resent: 'Invitation sent again', revoke: 'Cancel invitation', revoked: 'Invitation cancelled',
  remove: 'Remove from Northwind', removeQ: (n: string) => `Remove ${n} from Northwind?`, removeBody: 'They lose access at once. What they made stays, and their projects pass to you.', removed: (n: string) => `${n} was removed`,
  roleSaved: (n: string, r: string) => `${n} is now ${r}`,
  aloneTitle: 'It is only you so far', aloneBody: 'Invite the people you build with. Each one chooses a password and joins with the role you give them.',
  roles: [
    { value: 'owner', label: 'Owner', description: 'Everything, including billing and deleting projects.' },
    { value: 'editor', label: 'Editor', description: 'Builds: tables, keys, deploys. No billing.' },
    { value: 'reader', label: 'Reader', description: 'Sees everything, changes nothing.' },
  ],
};
const es: typeof en = {
  title: 'Miembros', lead: 'Las personas de Northwind y lo que cada una puede hacer.', invite: 'Invitar personas', seats: 'Puestos', seatsAction: 'Agregar puestos',
  members: 'Miembros', pending: 'Invitaciones pendientes', person: 'Persona', role: 'Rol', since: 'Entró', sent: 'Enviada', actions: (n: string) => `Acciones para ${n}`,
  you: 'Tú', emails: 'Correos', emailsHint: 'Pega o escribe varios, separados por comas o espacios.', emailsAdd: 'nombre@empresa.com',
  message: 'Una nota para ellos', send: 'Enviar invitaciones', sending: 'Enviando…',
  noEmails: 'Escribe al menos un correo.', bad: (e: string) => `${e} no es un correo. Corrígelo o quítalo.`, full: (n: number) => `Solo quedan ${n} puestos. Quita algunos correos o agrega puestos.`,
  sentN: (n: number) => (n === 1 ? 'Invitación enviada' : `${n} invitaciones enviadas`), resend: 'Enviar de nuevo', resent: 'Invitación enviada de nuevo', revoke: 'Cancelar invitación', revoked: 'Invitación cancelada',
  remove: 'Sacar de Northwind', removeQ: (n: string) => `¿Sacar a ${n} de Northwind?`, removeBody: 'Pierde el acceso de inmediato. Lo que hizo se queda, y sus proyectos pasan a ti.', removed: (n: string) => `${n} salió`,
  roleSaved: (n: string, r: string) => `${n} ahora es ${r}`,
  aloneTitle: 'Por ahora solo estás tú', aloneBody: 'Invita a las personas con las que construyes. Cada una elige su contraseña y entra con el rol que le des.',
  roles: [
    { value: 'owner', label: 'Dueño', description: 'Todo, incluida la facturación y borrar proyectos.' },
    { value: 'editor', label: 'Editor', description: 'Construye: tablas, llaves, despliegues. Sin facturación.' },
    { value: 'reader', label: 'Lector', description: 'Ve todo, no cambia nada.' },
  ],
};
type Member = { id: string; name: string; email: string; role: string; at: number; me?: boolean };
type Invite = { email: string; role: string; at: number };
const day = 86400e3, now = Date.UTC(2026, 10, 17, 15), SEATS = 8;
// Relative times («2 hours ago») are counted from the moment the page is drawn, so the server and the browser
// write the same words; dates that are shown as dates stay fixed.
const ago = (ms: number) => Date.now() - ms; // the words match; only the machine-readable dateTime differs by a moment

const team: Member[] = [
  { id: 'm1', name: 'Ana Ruiz', email: 'ana@northwind.io', role: 'owner', at: now - 400 * day, me: true },
  { id: 'm2', name: 'Luis Ortega', email: 'luis@northwind.io', role: 'owner', at: now - 380 * day },
  { id: 'm3', name: 'Marta Gil', email: 'marta@northwind.io', role: 'editor', at: now - 90 * day },
  { id: 'm4', name: 'Kenji Mori', email: 'kenji@northwind.io', role: 'reader', at: now - 12 * day },
];
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const isEmail = (e: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(e);

export default function InviteMembers({ state = 'ready' }: { state?: 'ready' | 'loading' | 'alone' }) {
  const { locale, format } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [members, setMembers] = useState<Member[]>(state === 'alone' ? team.slice(0, 1) : team);
  const [invites, setInvites] = useState<Invite[]>(state === 'alone' ? [] : [{ email: 'sofia@northwind.io', role: 'editor', at: ago(2 * day) }]);
  const [open, setOpen] = useState(false);
  const [emails, setEmails] = useState<string[]>([]);
  const [role, setRole] = useState('editor');
  const [problems, setProblems] = useState<FormProblem[]>([]);
  const [removing, setRemoving] = useState<Member | null>(null);
  // Loading: the real page, with only what comes from the server as skeletons, as many and as long as on the last visit
  // (here `team` and one invitation): the seats' count, each person's name, email, role and date.
  const loading = state === 'loading';
  const roleName = (r: string) => c.roles.find((x) => x.value === r)!.label;
  const left = SEATS - members.length - invites.length;
  const check = (): FormProblem[] => {
    if (!emails.length) return [{ name: 'emails', label: c.emails, message: c.noEmails }];
    const bad = emails.find((e) => !isEmail(e));
    if (bad) return [{ name: 'emails', label: c.emails, message: c.bad(bad) }];
    if (emails.length > left) return [{ name: 'emails', label: c.emails, message: c.full(left) }];
    return [];
  };
  const inviteButton = <Button variant="primary" icon="user-plus" onClick={() => { setEmails([]); setProblems([]); setOpen(true); }}>{c.invite}</Button>;
  return (
    <Page>
      <PageHeader title={c.title} lead={c.lead} actions={inviteButton} />
      <UsageBar label={c.seats} loading={loading} used={members.length + invites.length} limit={SEATS} action={<Button size="sm" variant="quiet" href="#billing">{c.seatsAction}</Button>} />
      {members.length === 1 && !invites.length ? (
        <Panel><EmptyState icon="team" title={c.aloneTitle} actions={inviteButton}>{c.aloneBody}</EmptyState></Panel>
      ) : (
        <Panel title={c.members} flush>
          <Table label={c.members} rows={loading ? undefined : members} loading={loading} loadingRows={team.length} rowKey={(m) => m.id} columns={[
            { id: 'person', header: c.person, cell: (m) => <Identity name={m.name} meta={m.email} />,
              skeleton: (i) => <Identity loading name={team[i].name} meta={team[i].email} /> },
            { id: 'role', header: c.role, cell: (m) => (m.me ? <Badge tone="light">{c.you} · {roleName(m.role)}</Badge>
              : <Select aria-label={`${c.role}: ${m.name}`} size="sm" value={m.role} options={c.roles.map(({ value, label }) => ({ value, label }))}
                  onChange={(r) => { setMembers((l) => l.map((x) => (x.id === m.id ? { ...x, role: r } : x))); toast(c.roleSaved(m.name, roleName(r)), { tone: 'ok' }); }} />),
              skeleton: (i) => <SkeletonOf>{team[i].me ? <Badge tone="light">{c.you} · {roleName(team[i].role)}</Badge> : <Select aria-label="" size="sm" value={team[i].role} options={c.roles.map(({ value, label }) => ({ value, label }))} onChange={() => undefined} />}</SkeletonOf> },
            { id: 'since', header: c.since, cell: (m) => format.date(new Date(m.at)), skeleton: (i) => <SkeletonWords>{format.date(new Date(team[i].at))}</SkeletonWords> },
            { id: 'act', header: '', actions: true, skeleton: (i) => !team[i].me && <SkeletonOf><RowActions actions={[]} /></SkeletonOf>, cell: (m) => (m.me ? null : <RowActions label={c.actions(m.name)} actions={[{ id: 'remove', label: c.remove, icon: 'user-minus', danger: true, onAction: () => setRemoving(m) }]} />) },
          ]} />
        </Panel>
      )}
      {invites.length > 0 && (
        <Panel title={c.pending} flush>
          <Table label={c.pending} rows={loading ? undefined : invites} loading={loading} loadingRows={invites.length} rowKey={(i) => i.email} columns={[
            { id: 'email', header: c.person, cell: (i) => i.email, skeleton: (n) => <SkeletonWords>{invites[n].email}</SkeletonWords> },
            { id: 'role', header: c.role, cell: (i) => roleName(i.role), skeleton: (n) => <SkeletonWords>{roleName(invites[n].role)}</SkeletonWords> },
            { id: 'sent', header: c.sent, cell: (i) => format.relative(new Date(i.at)), skeleton: (n) => <SkeletonWords>{format.relative(new Date(invites[n].at))}</SkeletonWords> },
            { id: 'act', header: '', actions: true, skeleton: <SkeletonOf><RowActions actions={[]} /></SkeletonOf>, cell: (i) => <RowActions label={c.actions(i.email)} actions={[
              { id: 'resend', label: c.resend, icon: 'send', onAction: () => toast(c.resent, { tone: 'ok' }) },
              { id: 'revoke', label: c.revoke, icon: 'close', danger: true, onAction: () => { setInvites((l) => l.filter((x) => x.email !== i.email)); toast(c.revoked); } },
            ]} /> },
          ]} />
        </Panel>
      )}
      <Dialog open={open} onClose={() => setOpen(false)} dirty={emails.length > 0} title={c.invite}>
        <Form label={c.invite} validate={check} problems={problems} onSubmit={async () => {
          await wait(900);
          setInvites((l) => [...emails.map((email) => ({ email, role, at: Date.now() })), ...l]);
          toast(c.sentN(emails.length), { tone: 'ok' }); setOpen(false);
        }}>
          {({ errorFor }) => (
            <>
              <Field label={c.emails} hint={c.emailsHint} error={errorFor('emails')}>
                <TagInput name="emails" placeholder={c.emailsAdd} value={emails} normalize={(t) => t.trim().toLowerCase()} onChange={(t) => { setEmails(t); setProblems([]); }} />
              </Field>
              <Field label={c.role}><RadioCards name="role" options={c.roles} value={role} onChange={setRole} /></Field>
              <Field label={c.message} optional><Textarea name="note" rows={2} /></Field>
              <FormActions submitLabel={c.send} busyLabel={c.sending} />
            </>
          )}
        </Form>
      </Dialog>
      <ConfirmDialog open={removing !== null} tone="primary" title={removing ? c.removeQ(removing.name) : ''} action={c.remove} onClose={() => setRemoving(null)}
        onConfirm={() => { setMembers((l) => l.filter((x) => x.id !== removing!.id)); toast(c.removed(removing!.name), { tone: 'ok' }); setRemoving(null); }}>
        <p>{c.removeBody}</p>
      </ConfirmDialog>
      <Toaster />
    </Page>
  );
}

En un celular

En un celular cada miembro es una tarjeta, con el rol y las acciones adentro.

Solo tú

La primera visita: qué hace invitar, y el botón para hacerlo.

Miembros

Las personas de Northwind y lo que cada una puede hacer.

Puestos1 de 8

Por ahora solo estás tú

Invita a las personas con las que construyes. Cada una elige su contraseña y entra con el rol que le des.

Skeleton

La página real mientras carga el equipo: el conteo de puestos, cada persona y cada invitación como skeletons tan largos como los últimos, en sus columnas.

Miembros

Las personas de Northwind y lo que cada una puede hacer.

Puestos

Miembros

PersonaRolEntró

Invitaciones pendientes

PersonaRolEnviada

Cuándo usarlo

Úsalo cuando

  • La página de miembros de una organización o un proyecto.
  • Decir qué puede hacer cada rol donde se elige, no en una página de ayuda aparte.

No lo uses cuando

  • Un correo por diálogo: la gente invita a su equipo, no a una persona.
  • Ocultar las invitaciones pendientes: se pueden enviar de nuevo o cancelar.

Para todos

  • Cada correo es una etiqueta con su propio botón para quitarla; uno mal escrito se nombra en el error.
  • El rol de cada miembro es una lista nombrada con el nombre del miembro.
  • La barra de puestos dice cuántos se usan de cuántos, en palabras.

Props

TagInputTipoPor defecto
aria-describedby string
aria-label

The name for screen readers when there is no Field around it.

string
aria-labelledby string
className string
defaultValue string[]
disabled boolean
id

Inside a Field it comes from the Field.

string
invalid

Marks the value as wrong. Inside a `<Field error>` it is set for you.

boolean
max

The most tags it takes.

number
normalize

Tidies each tag before it is added (lowercase, no spaces…). Return an empty text to refuse it.

((tag: string) => string)
onChange ((tags: string[]) => void)
placeholder string
value string[]
RadioCardsTipoPor defecto
optionsobligatorio Option[]
aria-describedby string
aria-label

The name for screen readers when there is no Field around it.

string
aria-labelledby string
className string
defaultValue string
disabled boolean
id

Inside a Field it comes from the Field.

string
invalid

Marks the value as wrong. Inside a `<Field error>` it is set for you.

boolean
name

The name of the value when it travels in a form.

string
onChange ((value: string) => void)
value string | null
UsageBarTipoPor defecto
labelobligatorio ReactNode
limitobligatorio number
usedobligatorio number
action

The next step, shown from 80 %: usually a LinkButton to the plans.

ReactNode
format

How amounts are written: bytes, rows, requests. Defaults to a number.

((v: number) => string)
loading

The amount is on its way: the label stays, the amount and the bar are skeletons. Pass the last known `used` and `limit`, so the amount's bar is as long as its words will be.

boolean
resetsAt

When the count starts again, for monthly limits.

string | number | Date
  1. En un computador
  2. En un celular
  3. Solo tú
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos