Skip to content

ProfileAndAccount

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 and says so; the password and the second factor change in a dialog.

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

On this page
  1. On a desktop
  2. On a phone
  3. Skeleton
  4. When to use it
  5. For everyone
  6. Props

On a desktop

Rename yourself, change the password («wrong» as the current one is refused), turn on the second factor (any code but 000000), sign out of another device.

Your account

What your team sees of you, and how you sign in.

Profile

Photo

Square works best. Up to 2 MB.

AR

Name

As your team sees it.

Ana Ruiz

Email

Where sign-in links and alerts go. A change is confirmed from the new address.

ana@northwind.io

Sign-in and security

Password

Changed 4 months ago.

Second factor

Off. A code from your phone keeps the account safe even if the password leaks.

Where you are signed in

DevicePlaceLast active
Firefox · macOS This deviceBogotá, CONow
Safari · iPhone Bogotá, CO3 hours ago
Chrome · Windows Madrid, ES6 days ago

Delete your account

Your projects pass to the other owners first. Projects with no other owner are deleted.

Code
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>
  );
}

On a phone

On a phone the sessions become cards and every control goes under its text.

Skeleton

The real page while the account loads: every row keeps its words; the photo, name, email, two-step state and sessions wait in their own boxes, as long as the last ones.

Your account

What your team sees of you, and how you sign in.

Profile

Photo

Square works best. Up to 2 MB.

Name

As your team sees it.

Email

Where sign-in links and alerts go. A change is confirmed from the new address.

Sign-in and security

Password

Changed 4 months ago.

Second factor

Where you are signed in

DevicePlaceLast active

Delete your account

Your projects pass to the other owners first. Projects with no other owner are deleted.

When to use it

Use it when

  • The account page of every Sypnia console.
  • Saying what leaving does to the person's projects before they confirm.

Do not use it when

  • Settings of a project or an organization: those belong to their SettingsPage.
  • Asking for the current password to change the photo or the name.

For everyone

  • The name is edited in place: Enter saves, Escape cancels, and the focus comes back to the edit button.
  • The code boxes of the second factor read as one field; pasting fills them all.
  • Each session row has its own actions button, named with the device.

Props

AvatarUploadTypeDefault
namerequired string
onChangerequired (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
InlineEditTypeDefault
labelrequired

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

string
onSaverequired

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>
valuerequired 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)
OtpInputTypeDefault
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. On a desktop
  2. On a phone
  3. Skeleton
  4. When to use it
  5. For everyone
  6. Props

    Search pages, sections and terms