Skip to content

SettingsPage

A project's settings: sections as tabs down the side, one setting per row with what it does, and one SaveBar for the whole page that appears as soon as something changed and says how many changes wait.

import { VerticalTabs, FormRow, SaveBar } from '@sypnia/ui/react'

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

On a desktop

Change anything: the SaveBar appears and counts the changes; switching tabs keeps them. «Discard» puts everything back.

Settings

How the project northwind-shop works for everyone in it.

Shown in the console and in emails. The address does not change.

Time zone

Used for charts, daily backups and reports.

For invitations and alerts sent to the team.

Code
import { useState, type ReactNode } from 'react';
import {
  Alert, Button, FormRow, Input, LinkCard, NativeSelect, Page, PageHeader, SaveBar, SkeletonOf, Stack, Switch, TagInput,
  Toaster, TimezoneSelect, VerticalTabs, toast, useSypnia,
} from '@sypnia/ui/react';

// A project's settings: sections as tabs down the side, one setting per row with what it does, and one SaveBar for
// the whole page that appears when something changed. Switching tabs keeps the changes; leaving with changes asks.
const en = {
  allow: 'Allow', require: 'Require', title: 'Settings', lead: 'How the project northwind-shop works for everyone in it.', tabs: 'Settings sections',
  general: 'General', access: 'Access', api: 'API', danger: 'Danger zone',
  name: 'Project name', nameD: 'Shown in the console and in emails. The address does not change.', tz: 'Time zone', tzD: 'Used for charts, daily backups and reports.',
  lang: 'Language of emails', langD: 'For invitations and alerts sent to the team.',
  signups: 'Anyone with the link can sign up', signupsD: 'People who sign up through your app get an account in this project.',
  domains: 'Allowed email domains', domainsD: 'Only these can sign up. Leave it empty to allow any.', domainsAdd: 'Add a domain',
  mfa: 'Ask every member for a second factor', mfaD: 'Members without one are asked to set it up the next time they sign in.',
  origins: 'Allowed origins', originsD: 'Web addresses that may call the API from a browser.', originsAdd: 'Add an origin',
  limit: 'Requests per minute, per key', limitD: 'Above it the API answers 429 and says when to try again.',
  dangerText: 'Transfer, pause or delete the project.', dangerTitle: 'Open the danger zone',
  changes: (n: number) => (n === 1 ? '1 unsaved change' : `${n} unsaved changes`), saved: 'Settings saved',
  failed: 'The settings were not saved', failedBody: 'The connection dropped while saving. Your changes are still here: save again.',
};
const es: typeof en = {
  allow: 'Permitir', require: 'Exigir', title: 'Ajustes', lead: 'Cómo funciona el proyecto northwind-shop para todos en él.', tabs: 'Secciones de ajustes',
  general: 'General', access: 'Acceso', api: 'API', danger: 'Zona de peligro',
  name: 'Nombre del proyecto', nameD: 'Se ve en la consola y en los correos. La dirección no cambia.', tz: 'Zona horaria', tzD: 'Para gráficos, copias diarias e informes.',
  lang: 'Idioma de los correos', langD: 'Para las invitaciones y alertas que recibe el equipo.',
  signups: 'Cualquiera con el enlace puede registrarse', signupsD: 'Quien se registra por tu app recibe una cuenta en este proyecto.',
  domains: 'Dominios de correo permitidos', domainsD: 'Solo estos pueden registrarse. Déjalo vacío para permitir cualquiera.', domainsAdd: 'Agregar un dominio',
  mfa: 'Pedir un segundo factor a cada miembro', mfaD: 'A quien no lo tenga se le pide configurarlo la próxima vez que inicie sesión.',
  origins: 'Orígenes permitidos', originsD: 'Direcciones web que pueden llamar a la API desde un navegador.', originsAdd: 'Agregar un origen',
  limit: 'Solicitudes por minuto, por llave', limitD: 'Por encima, la API responde 429 y dice cuándo intentar de nuevo.',
  dangerText: 'Transferir, pausar o borrar el proyecto.', dangerTitle: 'Abrir la zona de peligro',
  changes: (n: number) => (n === 1 ? '1 cambio sin guardar' : `${n} cambios sin guardar`), saved: 'Ajustes guardados',
  failed: 'Los ajustes no se guardaron', failedBody: 'La conexión se cortó al guardar. Tus cambios siguen aquí: guarda de nuevo.',
};
const initial = { name: 'Northwind shop', tz: 'America/Bogota', lang: 'en', signups: true, domains: ['northwind.io'], mfa: false, origins: ['https://shop.northwind.io'], limit: '600' };
type Values = typeof initial;
const pause = (ms: number) => new Promise((r) => setTimeout(r, ms));

export default function SettingsPage({ state = 'ready' }: { state?: 'ready' | 'loading' | 'error' }) {
  const { locale } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [saved, setSaved] = useState<Values>(initial);
  const [v, setV] = useState<Values>(initial);
  const [busy, setBusy] = useState(false);
  const [failed, setFailed] = useState(false);
  const set = <K extends keyof Values>(k: K, value: Values[K]) => setV((x) => ({ ...x, [k]: value }));
  const changed = (Object.keys(v) as (keyof Values)[]).filter((k) => JSON.stringify(v[k]) !== JSON.stringify(saved[k])).length;
  // Loading: the real page, tabs and rows with their words; each setting's control waits in its own box until the
  // saved values come.
  const loading = state === 'loading';
  const wait = (n: ReactNode) => (loading ? <SkeletonOf>{n}</SkeletonOf> : n);
  const save = async () => {
    setBusy(true); setFailed(false);
    await pause(1000);
    setBusy(false);
    if (state === 'error') { setFailed(true); return; }
    setSaved(v); toast(c.saved, { tone: 'ok' });
  };
  const general = (
    <Stack gap={0}>
      <FormRow label={c.name} description={c.nameD} htmlFor="set-name">{wait(<Input id="set-name" value={v.name} onChange={(e) => set('name', e.target.value)} />)}</FormRow>
      <FormRow label={c.tz} description={c.tzD}>{wait(<TimezoneSelect aria-label={c.tz} value={v.tz} onChange={(z) => z && set('tz', z)} />)}</FormRow>
      <FormRow label={c.lang} description={c.langD} htmlFor="set-lang">
        {wait(<NativeSelect id="set-lang" value={v.lang} onChange={(e) => set('lang', e.target.value)}><option value="en" lang="en">English</option><option value="es" lang="es">Español</option></NativeSelect>)}
      </FormRow>
    </Stack>
  );
  const access = (
    <Stack gap={0}>
      <FormRow label={c.signups} description={c.signupsD}>{wait(<Switch label={c.allow} checked={v.signups} onChange={(e) => set('signups', e.target.checked)} />)}</FormRow>
      <FormRow label={c.domains} description={c.domainsD}>{wait(<TagInput aria-label={c.domains} placeholder={c.domainsAdd} value={v.domains} onChange={(t) => set('domains', t)} disabled={!v.signups} />)}</FormRow>
      <FormRow label={c.mfa} description={c.mfaD}>{wait(<Switch label={c.require} checked={v.mfa} onChange={(e) => set('mfa', e.target.checked)} />)}</FormRow>
    </Stack>
  );
  const api = (
    <Stack gap={0}>
      <FormRow label={c.origins} description={c.originsD}>{wait(<TagInput aria-label={c.origins} placeholder={c.originsAdd} value={v.origins} onChange={(t) => set('origins', t)} />)}</FormRow>
      <FormRow label={c.limit} description={c.limitD} htmlFor="set-limit">{wait(<Input id="set-limit" inputMode="numeric" machine value={v.limit} onChange={(e) => set('limit', e.target.value.replace(/\D/g, ''))} />)}</FormRow>
    </Stack>
  );
  return (
    <Page>
      <PageHeader title={c.title} lead={c.lead} />
      {failed && <Alert tone="fail" title={c.failed} onDismiss={() => setFailed(false)}>{c.failedBody}</Alert>}
      <VerticalTabs label={c.tabs} items={[
        { id: 'general', label: c.general, icon: 'settings', content: general },
        { id: 'access', label: c.access, icon: 'lock', content: access },
        { id: 'api', label: c.api, icon: 'api', content: api },
        { id: 'danger', label: c.danger, icon: 'warning', content: <LinkCard href="#danger-zone" icon="warning" title={c.dangerTitle}>{c.dangerText}</LinkCard> },
      ]} />
      <SaveBar dirty={changed > 0} busy={busy} message={c.changes(changed)} onDiscard={() => { setV(saved); setFailed(false); }} onSave={save} />
      <Toaster />
    </Page>
  );
}

On a phone

On a phone the tabs sit on top, two by two, and each control goes under its sentence.

Skeleton

The real tabs and rows with their words; only each setting's control waits in its own box until the saved values come.

Settings

How the project northwind-shop works for everyone in it.

Shown in the console and in emails. The address does not change.

Time zone

Used for charts, daily backups and reports.

For invitations and alerts sent to the team.

When saving fails

Change something and save: the message says the changes are still there.

Settings

How the project northwind-shop works for everyone in it.

Shown in the console and in emails. The address does not change.

Time zone

Used for charts, daily backups and reports.

For invitations and alerts sent to the team.

When to use it

Use it when

  • Settings that belong together and are saved together: a project, an organization, an app.
  • Saying in each row what changes for people, not what the field is.

Do not use it when

  • Settings that apply at once on their own: a Switch that saves by itself needs no SaveBar.
  • Creating something new: that is a FormPage.
  • The danger zone mixed with the rest: it gets its own tab and its own confirmations.

For everyone

  • The tabs move with the arrow keys; on phones they sit on top, two by two.
  • The SaveBar is a named region; its count of changes is a status, read when it changes.
  • Every control is named by its row's title.

Props

VerticalTabsTypeDefault
itemsrequired VerticalTab[]
labelrequired string
onChange ((id: string) => void)
selected string
FormRowTypeDefault
labelrequired ReactNode
danger boolean
description ReactNode
htmlFor string
loading

The setting's value is on its way: the text stays and the control (`children`, when given) is drawn as a skeleton of its own box; without children, a skeleton of a control's height.

boolean
SaveBarTypeDefault
dirtyrequired boolean
onDiscardrequired () => void
onSaverequired () => void
busy boolean
message

What changed, if it helps: «3 changes in Columns». Defaults to «You have unsaved changes».

ReactNode
saveLabel string
  1. On a desktop
  2. On a phone
  3. Skeleton
  4. When saving fails
  5. When to use it
  6. For everyone
  7. Props

    Search pages, sections and terms