Ir al contenido

ProfileAndAccount

La cuenta de la persona: quién es, cómo inicia sesión, dónde tiene la sesión abierta y cómo irse. Cada parte se guarda sola y lo dice; la contraseña y el segundo factor cambian en un diálogo.

import { AvatarUpload, InlineEdit, OtpInput } from '@sypnia/ui/react'

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

En un computador

Cámbiate el nombre, cambia la contraseña («wrong» como la actual se rechaza), activa el segundo factor (cualquier código menos 000000), cierra la sesión en otro dispositivo.

Tu cuenta

Lo que tu equipo ve de ti, y cómo inicias sesión.

Perfil

Foto

Mejor cuadrada. Hasta 2 MB.

AR

Nombre

Como lo ve tu equipo.

Ana Ruiz

Correo

Adonde llegan los enlaces de inicio y las alertas. Un cambio se confirma desde la dirección nueva.

ana@northwind.io

Inicio de sesión y seguridad

Contraseña

Cambiada hace 4 meses.

Segundo factor

Apagado. Un código de tu celular protege la cuenta aunque se filtre la contraseña.

Dónde tienes la sesión abierta

DispositivoLugarÚltima actividad
Firefox · macOS Este dispositivoBogotá, COAhora
Safari · iPhone Bogotá, COhace 3 horas
Chrome · Windows Madrid, EShace 6 días

Borrar tu cuenta

Tus proyectos pasan primero a los otros dueños. Los proyectos sin otro dueño se borran.

Código
import { useState, type ReactNode } from 'react';
import {
  Badge, Button, ConfirmDialog, CopyField, Dialog, Field, Form, FormActions, FormRow, InlineEdit, OtpInput, Page, PageHeader,
  Panel, PasswordInput, RowActions, SkeletonOf, SkeletonWords, Stack, Table, Text, Toaster, AvatarUpload, toast, useSypnia,
  type FormProblem,
} from '@sypnia/ui/react';

// The person's own account: who they are, how they sign in, where they are signed in, and how to leave. Each part
// saves on its own, at once, and says so; changing the password or the second factor happens in a dialog.
const en = {
  title: 'Your account', lead: 'What your team sees of you, and how you sign in.',
  profile: 'Profile', photo: 'Photo', photoD: 'Square works best. Up to 2 MB.', name: 'Name', nameD: 'As your team sees it.',
  email: 'Email', emailD: 'Where sign-in links and alerts go. A change is confirmed from the new address.',
  security: 'Sign-in and security', password: 'Password', passwordD: 'Changed 4 months ago.', change: 'Change password',
  mfa: 'Second factor', mfaOn: 'On: codes from your authenticator app.', mfaOff: 'Off. A code from your phone keeps the account safe even if the password leaks.',
  turnOn: 'Turn on', turnOff: 'Turn off', mfaTitle: 'Turn on the second factor', mfaStep1: 'Add this key to your authenticator app (1Password, Google Authenticator, Authy…).',
  mfaKey: 'Setup key', mfaStep2: 'Then type the 6-digit code it shows.', mfaCode: 'Code', mfaWrong: 'That code is not right. Codes change every 30 seconds: type the current one.', mfaDone: 'Second factor is on',
  current: 'Current password', next: 'New password', nextHint: 'At least 12 characters.', save: 'Change password', saving: 'Changing…', pwDone: 'Password changed. Other devices were signed out.',
  pwWrong: 'That is not your current password.', pwShort: 'Use 12 characters or more.', pwSame: 'Choose a password you have not used here.', pwNone: 'Write your current password.',
  sessions: 'Where you are signed in', device: 'Device', place: 'Place', active: 'Last active', thisOne: 'This device', now: 'Now',
  signOut: 'Sign out', signOutOthers: 'Sign out everywhere else', outDone: (d: string) => `Signed out of ${d}`, othersDone: 'Signed out everywhere else',
  leave: 'Delete your account', leaveD: 'Your projects pass to the other owners first. Projects with no other owner are deleted.', leaveBtn: 'Delete account',
  leaveQ: 'Delete your account?', leaveBody: 'You leave Northwind and Acme Retail. northwind-shop passes to Luis Ortega; sandbox, which has no other owner, is deleted with its data. This cannot be undone.',
  nameSaved: 'Name saved', actions: (d: string) => `Actions for ${d}`,
};
const es: typeof en = {
  title: 'Tu cuenta', lead: 'Lo que tu equipo ve de ti, y cómo inicias sesión.',
  profile: 'Perfil', photo: 'Foto', photoD: 'Mejor cuadrada. Hasta 2 MB.', name: 'Nombre', nameD: 'Como lo ve tu equipo.',
  email: 'Correo', emailD: 'Adonde llegan los enlaces de inicio y las alertas. Un cambio se confirma desde la dirección nueva.',
  security: 'Inicio de sesión y seguridad', password: 'Contraseña', passwordD: 'Cambiada hace 4 meses.', change: 'Cambiar contraseña',
  mfa: 'Segundo factor', mfaOn: 'Activo: códigos de tu app de autenticación.', mfaOff: 'Apagado. Un código de tu celular protege la cuenta aunque se filtre la contraseña.',
  turnOn: 'Activar', turnOff: 'Apagar', mfaTitle: 'Activar el segundo factor', mfaStep1: 'Agrega esta llave a tu app de autenticación (1Password, Google Authenticator, Authy…).',
  mfaKey: 'Llave de configuración', mfaStep2: 'Luego escribe el código de 6 dígitos que muestra.', mfaCode: 'Código', mfaWrong: 'Ese código no es correcto. Los códigos cambian cada 30 segundos: escribe el actual.', mfaDone: 'El segundo factor está activo',
  current: 'Contraseña actual', next: 'Contraseña nueva', nextHint: 'Al menos 12 caracteres.', save: 'Cambiar contraseña', saving: 'Cambiando…', pwDone: 'Contraseña cambiada. Se cerró la sesión en los otros dispositivos.',
  pwWrong: 'Esa no es tu contraseña actual.', pwShort: 'Usa 12 caracteres o más.', pwSame: 'Elige una contraseña que no hayas usado aquí.', pwNone: 'Escribe tu contraseña actual.',
  sessions: 'Dónde tienes la sesión abierta', device: 'Dispositivo', place: 'Lugar', active: 'Última actividad', thisOne: 'Este dispositivo', now: 'Ahora',
  signOut: 'Cerrar sesión', signOutOthers: 'Cerrar sesión en todos los demás', outDone: (d: string) => `Se cerró la sesión en ${d}`, othersDone: 'Se cerró la sesión en todos los demás',
  leave: 'Borrar tu cuenta', leaveD: 'Tus proyectos pasan primero a los otros dueños. Los proyectos sin otro dueño se borran.', leaveBtn: 'Borrar cuenta',
  leaveQ: '¿Borrar tu cuenta?', leaveBody: 'Sales de Northwind y de Acme Retail. northwind-shop pasa a Luis Ortega; sandbox, que no tiene otro dueño, se borra con sus datos. No se puede deshacer.',
  nameSaved: 'Nombre guardado', actions: (d: string) => `Acciones para ${d}`,
};
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));
type Session = { id: string; device: string; place: string; at: number; current?: boolean };
const sessions0: Session[] = [
  { id: 's1', device: 'Firefox · macOS', place: 'Bogotá, CO', at: 0, current: true },
  { id: 's2', device: 'Safari · iPhone', place: 'Bogotá, CO', at: 3 * 3600e3 },
  { id: 's3', device: 'Chrome · Windows', place: 'Madrid, ES', at: 6 * 86400e3 },
];

export default function ProfileAndAccount({ state = 'ready' }: { state?: 'ready' | 'loading' }) {
  const { locale, format } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [name, setName] = useState('Ana Ruiz');
  const [photo, setPhoto] = useState<File | null>(null);
  const [mfa, setMfa] = useState(false);
  const [dialog, setDialog] = useState<'password' | 'mfa' | 'leave' | null>(null);
  const [problems, setProblems] = useState<FormProblem[]>([]);
  const [codeError, setCodeError] = useState<string>();
  const [sessions, setSessions] = useState(sessions0);
  const [busy, setBusy] = useState(false);
  // Loading: the real page. Every row keeps its label and description; what comes from the account (the photo, the
  // name, the email, whether two-step is on, the sessions) is a skeleton of its own box, as long as the last known value.
  const loading = state === 'loading';
  const wait = (n: ReactNode) => (loading ? <SkeletonOf>{n}</SkeletonOf> : n);
  const words = (n: ReactNode) => (loading ? <SkeletonWords>{n}</SkeletonWords> : n);
  const checkPw = (v: FormData): FormProblem[] => {
    const out: FormProblem[] = [];
    if (!String(v.get('current') ?? '')) out.push({ name: 'current', label: c.current, message: c.pwNone });
    if (String(v.get('next') ?? '').length < 12) out.push({ name: 'next', label: c.next, message: c.pwShort });
    return out;
  };
  return (
    <Page>
      <PageHeader title={c.title} lead={c.lead} />
      <Panel title={c.profile}>
        <Stack gap={0}>
          <FormRow label={c.photo} description={c.photoD}><AvatarUpload loading={loading} name={name} file={photo} onChange={setPhoto} maxSize={2 * 1024 * 1024} /></FormRow>
          <FormRow label={c.name} description={c.nameD}>
            {wait(<InlineEdit label={c.name} value={name} validate={(x) => (x.trim() ? undefined : c.nameD)} onSave={async (x) => { await pause(500); setName(x.trim()); toast(c.nameSaved, { tone: 'ok' }); }} />)}
          </FormRow>
          <FormRow label={c.email} description={c.emailD}><Text as="span" size="sm">{words('ana@northwind.io')}</Text></FormRow>
        </Stack>
      </Panel>
      <Panel title={c.security}>
        <Stack gap={0}>
          <FormRow label={c.password} description={c.passwordD}><Button icon="password" onClick={() => { setProblems([]); setDialog('password'); }}>{c.change}</Button></FormRow>
          <FormRow label={c.mfa} description={words(mfa ? c.mfaOn : c.mfaOff)}>
            {mfa ? <Stack gap={2}><Badge tone="ok" dot>{c.mfaDone}</Badge><Button variant="quiet" onClick={() => setMfa(false)}>{c.turnOff}</Button></Stack>
              : wait(<Button variant="primary" icon="two-factor" onClick={() => { setCodeError(undefined); setDialog('mfa'); }}>{c.turnOn}</Button>)}
          </FormRow>
        </Stack>
      </Panel>
      <Panel title={c.sessions} actions={sessions.length > 1 && wait(<Button size="sm" icon="sign-out" onClick={() => { setSessions((s) => s.filter((x) => x.current)); toast(c.othersDone, { tone: 'ok' }); }}>{c.signOutOthers}</Button>)} flush>
        <Table label={c.sessions} rows={loading ? undefined : sessions} loading={loading} loadingRows={sessions0.length} rowKey={(r) => r.id} columns={[
          { id: 'device', header: c.device, cell: (r) => <>{r.device} {r.current && <Badge tone="light">{c.thisOne}</Badge>}</>,
            skeleton: (i) => <><SkeletonWords>{sessions0[i].device}</SkeletonWords> {sessions0[i].current && <SkeletonOf><Badge tone="light">{c.thisOne}</Badge></SkeletonOf>}</> },
          { id: 'place', header: c.place, cell: (r) => r.place, skeleton: (i) => <SkeletonWords>{sessions0[i].place}</SkeletonWords> },
          { id: 'at', header: c.active, cell: (r) => (r.current ? c.now : format.relative(new Date(Date.now() - r.at))),
            skeleton: (i) => <SkeletonWords>{sessions0[i].current ? c.now : format.relative(new Date(Date.now() - sessions0[i].at))}</SkeletonWords> },
          { id: 'act', header: '', actions: true, skeleton: (i) => !sessions0[i].current && <SkeletonOf><RowActions actions={[]} /></SkeletonOf>, cell: (r) => (r.current ? null : <RowActions label={c.actions(r.device)} actions={[{ id: 'out', label: c.signOut, icon: 'sign-out', onAction: () => { setSessions((s) => s.filter((x) => x.id !== r.id)); toast(c.outDone(r.device), { tone: 'ok' }); } }]} />) },
        ]} />
      </Panel>
      <Panel>
        <FormRow label={c.leave} description={c.leaveD} danger><Button variant="danger" icon="trash" onClick={() => setDialog('leave')}>{c.leaveBtn}</Button></FormRow>
      </Panel>

      <Dialog open={dialog === 'password'} onClose={() => setDialog(null)} title={c.change} size="sm">
        <Form label={c.change} validate={checkPw} problems={problems} onSubmit={async (v) => {
          await pause(900);
          if (v.get('current') === 'wrong') { setProblems([{ name: 'current', label: c.current, message: c.pwWrong }]); return; }
          setDialog(null); toast(c.pwDone, { tone: 'ok' });
        }}>
          {({ errorFor }) => (
            <>
              <Field label={c.current} error={errorFor('current')}><PasswordInput name="current" autoComplete="current-password" onChange={() => setProblems([])} /></Field>
              <Field label={c.next} hint={c.nextHint} error={errorFor('next')}><PasswordInput name="next" autoComplete="new-password" /></Field>
              <FormActions submitLabel={c.save} busyLabel={c.saving} />
            </>
          )}
        </Form>
      </Dialog>
      <Dialog open={dialog === 'mfa'} onClose={() => setDialog(null)} title={c.mfaTitle} size="sm">
        <Stack gap={4}>
          <p>{c.mfaStep1}</p>
          <Field label={c.mfaKey}><CopyField value="JBSW Y3DP EHPK 3PXP" label={c.mfaKey} /></Field>
          <p>{c.mfaStep2}</p>
          <Field label={c.mfaCode} error={codeError}>
            <OtpInput onComplete={async (code) => { await pause(500); if (code === '000000') setCodeError(c.mfaWrong); else { setMfa(true); setDialog(null); toast(c.mfaDone, { tone: 'ok' }); } }} />
          </Field>
        </Stack>
      </Dialog>
      <ConfirmDialog open={dialog === 'leave'} title={c.leaveQ} action={c.leaveBtn} confirmWord="ana@northwind.io" busy={busy} onClose={() => setDialog(null)}
        onConfirm={async () => { setBusy(true); await pause(1000); setBusy(false); setDialog(null); }}>
        <p>{c.leaveBody}</p>
      </ConfirmDialog>
      <Toaster />
    </Page>
  );
}

En un celular

En un celular las sesiones se vuelven tarjetas y cada control va debajo de su texto.

Skeleton

La página real mientras carga la cuenta: cada fila conserva sus palabras; la foto, el nombre, el correo, la verificación en dos pasos y las sesiones esperan en sus propias cajas, tan largas como las últimas.

Tu cuenta

Lo que tu equipo ve de ti, y cómo inicias sesión.

Perfil

Foto

Mejor cuadrada. Hasta 2 MB.

Nombre

Como lo ve tu equipo.

Correo

Adonde llegan los enlaces de inicio y las alertas. Un cambio se confirma desde la dirección nueva.

Inicio de sesión y seguridad

Contraseña

Cambiada hace 4 meses.

Segundo factor

Dónde tienes la sesión abierta

DispositivoLugarÚltima actividad

Borrar tu cuenta

Tus proyectos pasan primero a los otros dueños. Los proyectos sin otro dueño se borran.

Cuándo usarlo

Úsalo cuando

  • La página de cuenta de toda consola de Sypnia.
  • Decir qué pasa con los proyectos de la persona al irse, antes de que confirme.

No lo uses cuando

  • Ajustes de un proyecto o de una organización: van en su SettingsPage.
  • Pedir la contraseña actual para cambiar la foto o el nombre.

Para todos

  • El nombre se edita en su lugar: Enter guarda, Escape cancela y el foco vuelve al botón de editar.
  • Las casillas del código del segundo factor se leen como un solo campo; pegar las llena todas.
  • Cada fila de sesión tiene su propio botón de acciones, nombrado con el dispositivo.

Props

AvatarUploadTipoPor defecto
nameobligatorio string
onChangeobligatorio (f: File | null) => void
file File | null
loading

The person's picture is on its way: the circle and the buttons are skeletons of their own boxes (pass the last known `value`, so the buttons are the ones that will come).

boolean
maxSize number 1024 * 1024
value string | null
InlineEditTipoPor defecto
labelobligatorio

What the value is called: it names the edit button and the field.

string
onSaveobligatorio

Saves the new value. Throw an Error with a readable message when it cannot be saved: it is shown under the field.

(value: string) => void | Promise<void>
valueobligatorio string
loading

The value is on its way: a bar the height of the text, with no edit button yet.

boolean
machine boolean
placeholder

Shown when the value is empty.

string
render

How the value reads when it is not being edited.

((value: string) => ReactNode)
validate

Returns what is wrong with a value, or nothing when it is right.

((value: string) => string)
OtpInputTipoPor defecto
aria-describedby string
aria-label

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

string
aria-labelledby string
autoFocus boolean
className 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
length

How many boxes.

number 6
onChange ((code: string) => void)
onComplete

Called when the last box is filled: the moment to check the code.

((code: string) => void)
type

digits: numbers only. text: letters and numbers.

"text" | "digits" digits
value string
  1. En un computador
  2. En un celular
  3. Skeleton
  4. Cuándo usarlo
  5. Para todos
  6. Props

    Busca páginas, secciones y términos