Skip to content

Notifications

The inbox of what happened while the person was away, and where they choose what reaches them and how. Unread items carry the light; each kind of event is on or off for each channel.

import { NotificationList, CheckboxGroup } from '@sypnia/ui/react'

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

On a desktop

Open an item to mark it read, or mark all; switch between unread and all. Each change of a channel saves at once.

Notifications

What happened in your projects, and how it reaches you.

Inbox

What reaches you

Failures

A deploy, a backup or a job that did not finish.

Usage and billing

Limits close to being reached, invoices, failed payments.

Team

Invitations, new members, changes of role.

Weekly report

Every Monday: traffic, errors and speed of each project.

Code
import { useState } from 'react';
import {
  Button, CheckboxGroup, EmptyState, FormRow, NotificationList, Page, PageHeader, Panel,
  SegmentedControl, SkeletonOf, Stack, Toaster, toast, useSypnia, type NotificationEntry,
} from '@sypnia/ui/react';

// The inbox of what happened while the person was away, and where they choose what reaches them and how. Unread items
// carry the light; opening one marks it read; «Mark all as read» empties the count. Each kind of event says what it is
// and is on or off per channel.
const en = {
  title: 'Notifications', lead: 'What happened in your projects, and how it reaches you.', inbox: 'Inbox', show: 'Show',
  unread: 'Unread', all: 'All', prefs: 'What reaches you', channels: 'Channels', email: 'Email', console: 'In the console', phone: 'Push to your phone',
  caught: 'You are all caught up', caughtBody: 'New alerts, invitations and reports will show here. Choose below which ones also reach your email.',
  showAll: 'Show all', saved: 'Saved. It applies to the next notification.',
  items: [
    { id: 'n1', title: 'Deploy failed on northwind-shop', body: 'The migration 0042_add_refunds stopped at line 18. The previous version is still live.', tone: 'fail', icon: 'deploy', ago: 12 },
    { id: 'n2', title: 'Luis Ortega invited you to Acme Retail', body: 'You can read and edit its projects.', icon: 'user-plus', ago: 95 },
    { id: 'n3', title: 'Storage is at 82% of your plan', body: 'At this pace it fills in 9 days. Clean old files or move to a larger plan.', tone: 'warn', icon: 'usage', ago: 300 },
    { id: 'n4', title: 'Weekly report is ready', body: '1.2 million requests, 0.03% errors, p95 of 180 ms.', tone: 'ok', icon: 'chart-line', ago: 2900, read: true },
  ],
  events: [
    { id: 'failures', label: 'Failures', desc: 'A deploy, a backup or a job that did not finish.' },
    { id: 'usage', label: 'Usage and billing', desc: 'Limits close to being reached, invoices, failed payments.' },
    { id: 'team', label: 'Team', desc: 'Invitations, new members, changes of role.' },
    { id: 'reports', label: 'Weekly report', desc: 'Every Monday: traffic, errors and speed of each project.' },
  ],
};
const es: typeof en = {
  title: 'Notificaciones', lead: 'Lo que pasó en tus proyectos, y cómo te llega.', inbox: 'Bandeja', show: 'Mostrar',
  unread: 'Sin leer', all: 'Todas', prefs: 'Lo que te llega', channels: 'Canales', email: 'Correo', console: 'En la consola', phone: 'Aviso en tu celular',
  caught: 'Estás al día', caughtBody: 'Aquí aparecerán nuevas alertas, invitaciones e informes. Elige abajo cuáles también llegan a tu correo.',
  showAll: 'Ver todas', saved: 'Guardado. Aplica desde la próxima notificación.',
  items: [
    { id: 'n1', title: 'Falló el despliegue de northwind-shop', body: 'La migración 0042_add_refunds se detuvo en la línea 18. La versión anterior sigue en línea.', tone: 'fail', icon: 'deploy', ago: 12 },
    { id: 'n2', title: 'Luis Ortega te invitó a Acme Retail', body: 'Puedes ver y editar sus proyectos.', icon: 'user-plus', ago: 95 },
    { id: 'n3', title: 'El almacenamiento va en 82 % de tu plan', body: 'A este ritmo se llena en 9 días. Borra archivos viejos o pasa a un plan mayor.', tone: 'warn', icon: 'usage', ago: 300 },
    { id: 'n4', title: 'El informe semanal está listo', body: '1,2 millones de solicitudes, 0,03 % de errores, p95 de 180 ms.', tone: 'ok', icon: 'chart-line', ago: 2900, read: true },
  ],
  events: [
    { id: 'failures', label: 'Fallas', desc: 'Un despliegue, una copia o una tarea que no terminó.' },
    { id: 'usage', label: 'Uso y facturación', desc: 'Límites a punto de alcanzarse, facturas, pagos fallidos.' },
    { id: 'team', label: 'Equipo', desc: 'Invitaciones, miembros nuevos, cambios de rol.' },
    { id: 'reports', label: 'Informe semanal', desc: 'Cada lunes: tráfico, errores y velocidad de cada proyecto.' },
  ],
};
// 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 defaults: Record<string, string[]> = { failures: ['email', 'console', 'phone'], usage: ['email', 'console'], team: ['email', 'console'], reports: ['email'] };

export default function Notifications({ state = 'ready' }: { state?: 'ready' | 'loading' | 'empty' }) {
  const { locale } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [read, setRead] = useState<Set<string>>(() => new Set(state === 'empty' ? c.items.map((i) => i.id) : c.items.filter((i) => i.read).map((i) => i.id)));
  const [view, setView] = useState<'unread' | 'all'>('unread');
  const [prefs, setPrefs] = useState(defaults);
  // Loading: the real page. The inbox draws the last known notifications in their places as skeletons as long as
  // theirs; each kind of event keeps its words, and only its channels (the person's choices) wait in their box.
  const loading = state === 'loading';
  const entries: NotificationEntry[] = c.items
    .filter((i) => view === 'all' || !read.has(i.id))
    .map((i) => ({ id: i.id, title: i.title, body: i.body, icon: i.icon as NotificationEntry['icon'], tone: i.tone as NotificationEntry['tone'], at: ago(i.ago * 60e3), unread: !read.has(i.id), href: `#${i.id}` }));
  const channels = [{ value: 'email', label: c.email }, { value: 'console', label: c.console }, { value: 'phone', label: c.phone }];
  return (
    <Page>
      <PageHeader title={c.title} lead={c.lead} />
      <Panel title={c.inbox} actions={<SegmentedControl label={c.show} value={view} onChange={setView} options={[{ value: 'unread', label: c.unread }, { value: 'all', label: c.all }]} />}>
        {entries.length ? (
          <NotificationList loading={loading} items={entries} onOpen={(id) => setRead((r) => new Set(r).add(id))} onReadAll={() => setRead(new Set(c.items.map((i) => i.id)))} />
        ) : (
          <EmptyState icon="bell" compact title={c.caught} actions={view === 'unread' ? <Button onClick={() => setView('all')}>{c.showAll}</Button> : undefined}>{c.caughtBody}</EmptyState>
        )}
      </Panel>
      <Panel title={c.prefs}>
        <Stack gap={0}>
          {c.events.map((e) => (
            <FormRow key={e.id} label={e.label} description={e.desc}>
              {(() => {
                const group = <CheckboxGroup aria-label={`${e.label}: ${c.channels}`} orientation="horizontal" options={channels} value={prefs[e.id]}
                  onChange={(v) => { setPrefs((p) => ({ ...p, [e.id]: v })); toast(c.saved, { tone: 'ok' }); }} />;
                return loading ? <SkeletonOf>{group}</SkeletonOf> : group;
              })()}
            </FormRow>
          ))}
        </Stack>
      </Panel>
      <Toaster />
    </Page>
  );
}

On a phone

On a phone the channels sit two by two under each event.

All caught up

Nothing unread: say so, and offer to see everything.

Notifications

What happened in your projects, and how it reaches you.

Inbox

You are all caught up

New alerts, invitations and reports will show here. Choose below which ones also reach your email.

What reaches you

Failures

A deploy, a backup or a job that did not finish.

Usage and billing

Limits close to being reached, invoices, failed payments.

Team

Invitations, new members, changes of role.

Weekly report

Every Monday: traffic, errors and speed of each project.

Skeleton

The inbox draws the last notifications in their places, as skeletons as long as theirs; each kind of event keeps its words and only its channels wait.

Notifications

What happened in your projects, and how it reaches you.

Inbox

What reaches you

Failures

A deploy, a backup or a job that did not finish.

Usage and billing

Limits close to being reached, invoices, failed payments.

Team

Invitations, new members, changes of role.

Weekly report

Every Monday: traffic, errors and speed of each project.

When to use it

Use it when

  • The page behind the notification bell of a console.
  • Grouping preferences by kind of event, each with one sentence that says when it comes.

Do not use it when

  • Sending everything by email by default: failures yes, reports only when asked.
  • A preference without a sentence: «Usage» means nothing until it says «limits close to being reached».

For everyone

  • Unread items say so to screen readers, not only with the light.
  • «Mark all as read» is a button with its result announced.
  • Each group of channels is named by its event.

Props

NotificationListTypeDefault
itemsrequired NotificationEntry[]
empty

Shown when there is nothing. Defaults to «Nothing new».

ReactNode
loading

The notifications are on their way: pass the last known ones (or typical ones) as `items`; each is drawn in its place, its icon, title, text and time as skeletons as long as theirs.

boolean
onOpen ((id: string) => void)
onReadAll (() => void)
CheckboxGroupTypeDefault
optionsrequired 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 ((values: string[]) => void)
orientation

vertical: one under another (the default, easier to scan). horizontal: in a row that wraps, for short labels.

"horizontal" | "vertical"
value string[]
  1. On a desktop
  2. On a phone
  3. All caught up
  4. Skeleton
  5. When to use it
  6. For everyone
  7. Props

    Search pages, sections and terms