Ir al contenido

Notifications

La bandeja de lo que pasó mientras la persona no estaba, y donde elige qué le llega y cómo. Lo no leído lleva la luz; cada tipo de evento se prende o se apaga en cada canal.

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

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

En un computador

Abre una notificación para marcarla leída, o márcalas todas; cambia entre sin leer y todas. Cada cambio de canal se guarda al instante.

Notificaciones

Lo que pasó en tus proyectos, y cómo te llega.

Bandeja

Lo que te llega

Fallas

Un despliegue, una copia o una tarea que no terminó.

Uso y facturación

Límites a punto de alcanzarse, facturas, pagos fallidos.

Equipo

Invitaciones, miembros nuevos, cambios de rol.

Informe semanal

Cada lunes: tráfico, errores y velocidad de cada proyecto.

Código
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>
  );
}

En un celular

En un celular los canales van de a dos debajo de cada evento.

Al día

Nada sin leer: dilo, y ofrece ver todo.

Notificaciones

Lo que pasó en tus proyectos, y cómo te llega.

Bandeja

Estás al día

Aquí aparecerán nuevas alertas, invitaciones e informes. Elige abajo cuáles también llegan a tu correo.

Lo que te llega

Fallas

Un despliegue, una copia o una tarea que no terminó.

Uso y facturación

Límites a punto de alcanzarse, facturas, pagos fallidos.

Equipo

Invitaciones, miembros nuevos, cambios de rol.

Informe semanal

Cada lunes: tráfico, errores y velocidad de cada proyecto.

Skeleton

La bandeja dibuja las últimas notificaciones en su lugar, como skeletons tan largos como ellas; cada tipo de evento conserva sus palabras y solo sus canales esperan.

Notificaciones

Lo que pasó en tus proyectos, y cómo te llega.

Bandeja

Lo que te llega

Fallas

Un despliegue, una copia o una tarea que no terminó.

Uso y facturación

Límites a punto de alcanzarse, facturas, pagos fallidos.

Equipo

Invitaciones, miembros nuevos, cambios de rol.

Informe semanal

Cada lunes: tráfico, errores y velocidad de cada proyecto.

Cuándo usarlo

Úsalo cuando

  • La página detrás de la campana de notificaciones de una consola.
  • Agrupar las preferencias por tipo de evento, cada uno con una frase que dice cuándo llega.

No lo uses cuando

  • Enviar todo por correo por defecto: las fallas sí, los informes solo si se piden.
  • Una preferencia sin frase: «Uso» no dice nada hasta que dice «límites a punto de alcanzarse».

Para todos

  • Lo no leído se dice a los lectores de pantalla, no solo con la luz.
  • «Marcar todas como leídas» es un botón cuyo resultado se anuncia.
  • Cada grupo de canales se nombra con su evento.

Props

NotificationListTipoPor defecto
itemsobligatorio 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)
CheckboxGroupTipoPor 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 ((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. En un computador
  2. En un celular
  3. Al día
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos