Ir al contenido

MasterDetail

Una lista a un lado y el elegido al otro: busca en la lista, elige uno, léelo y actúa sin perder tu lugar. En celulares son dos pantallas: elegir abre el detalle, «Volver» regresa a la lista.

import { Split, ListItem } from '@sypnia/ui/react'

En esta página
  1. En un computador
  2. En un celular
  3. Aún no se elige nada
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

En un computador

Elige un cliente, cambia de pestaña, busca en la lista, arrastra el divisor.

Clientes

412 personas que compraron en northwind-shop.

Ana Ruiz

ana@acme.com

Empresa
Acme Retail
Plan
Pro
Cliente desde
8 oct 2026
Gastó
120,00 US$2 pedidos
País
CO
ID
cus_1179
Código
import { useMemo, useState, type ReactNode } from 'react';
import {
  ActivityFeed, Avatar, BackButton, Badge, Button, DescriptionList, EmptyState, InlineCode, List, ListItem, Page, PageHeader,
  Panel, SearchInput, SkeletonOf, SkeletonWords, Split, Stack, Tabs, Table, useMediaQuery, useSypnia,
} from '@sypnia/ui/react';

// A list on one side and the chosen one on the other: search the list, pick a customer, read and act on it without
// losing your place. On phones the list and the detail are two screens: picking opens the detail, «Back» returns to
// the list where you were.
type Customer = { id: string; name: string; email: string; company: string; plan: 'pro' | 'team' | 'hobby'; since: number; spent: number; orders: number; country: string };
const en = {
  title: 'Customers', lead: '412 people who bought from northwind-shop.', search: 'Search customers', list: 'Customers', back: 'Customers',
  overview: 'Overview', orders: 'Orders', activity: 'Activity', email: 'Email', company: 'Company', plan: 'Plan', since: 'Customer since', spent: 'Spent', country: 'Country',
  write: 'Write to them', order: 'Order', date: 'Date', total: 'Total', none: (q: string) => `No customer matches «${q}»`, noneBody: 'Search by name, email or company.',
  pick: 'Choose a customer', pickBody: 'Their details, orders and activity show here.', plans: { pro: 'Pro', team: 'Team', hobby: 'Hobby' },
  acts: { order: 'placed an order', email: 'changed their email', signup: 'created an account' },
};
const es: typeof en = {
  title: 'Clientes', lead: '412 personas que compraron en northwind-shop.', search: 'Buscar clientes', list: 'Clientes', back: 'Clientes',
  overview: 'Resumen', orders: 'Pedidos', activity: 'Actividad', email: 'Correo', company: 'Empresa', plan: 'Plan', since: 'Cliente desde', spent: 'Gastó', country: 'País',
  write: 'Escribirle', order: 'Pedido', date: 'Fecha', total: 'Total', none: (q: string) => `Ningún cliente coincide con «${q}»`, noneBody: 'Busca por nombre, correo o empresa.',
  pick: 'Elige un cliente', pickBody: 'Aquí aparecen sus datos, pedidos y actividad.', plans: { pro: 'Pro', team: 'Team', hobby: 'Hobby' },
  acts: { order: 'hizo un pedido', email: 'cambió su correo', signup: 'creó una cuenta' },
};
const names = ['Ana Ruiz', 'Luis Ortega', 'Marta Gil', 'Kenji Mori', 'Sofía Paredes', 'Omar Haddad', 'Lena Vogel', 'Tomás Rivas', 'Aiko Tanaka', 'Pablo Serra'];
const companies = ['Acme Retail', 'Lumen Labs', 'Globex', 'Initech', 'Hooli'];
const day = 86400e3, now = Date.UTC(2026, 10, 17, 15);
// 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 customers: Customer[] = names.map((name, i) => ({
  id: `cus_${(48213 + i * 977).toString(36)}`, name, email: `${name.split(' ')[0].toLowerCase()}@${companies[i % 5].split(' ')[0].toLowerCase()}.com`,
  company: companies[i % 5], plan: (['pro', 'team', 'hobby'] as const)[i % 3], since: now - (40 + i * 37) * day, spent: 120 + i * 83.5, orders: 2 + ((i * 7) % 15), country: ['CO', 'ES', 'MX', 'JP', 'DE'][i % 5],
}));

export default function MasterDetail({ state = 'ready' }: { state?: 'ready' | 'loading' | 'none' }) {
  const { locale, format } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const phone = useMediaQuery('(max-width: 40rem)');
  const [query, setQuery] = useState('');
  const [current, setCurrent] = useState<string | null>(state === 'none' ? null : customers[0].id);
  const [opened, setOpened] = useState(false); // on phones: the detail is its own screen, opened by picking
  const shown = useMemo(() => customers.filter((x) => `${x.name} ${x.email} ${x.company}`.toLowerCase().includes(query.trim().toLowerCase())), [query]);
  // Loading: the real page. The list draws the last known customers in their places and the detail the one that was
  // open, every value a skeleton as long as its own; the search, the tabs and the names of the facts stay.
  const loading = state === 'loading';
  const words = (n: ReactNode) => (loading ? <SkeletonWords>{n}</SkeletonWords> : n);
  const sel = customers.find((x) => x.id === current);
  const list = (
    <Stack gap={3}>
      <SearchInput aria-label={c.search} value={query} onChange={(e) => setQuery(e.target.value)} />
      {shown.length ? (
        <List label={c.list} pageSize={20}>
          {shown.map((x) => <ListItem key={x.id} loading={loading} media={<Avatar name={x.name} size="sm" />} title={x.name} description={x.company} current={x.id === current} onClick={() => { setCurrent(x.id); setOpened(true); }} />)}
        </List>
      ) : <EmptyState icon="search" compact title={c.none(query)}>{c.noneBody}</EmptyState>}
    </Stack>
  );
  const detail = sel ? (
    <Stack gap={5}>
      {phone && <div><BackButton onPress={() => setOpened(false)}>{c.back}</BackButton></div>}
      <PageHeader title={words(sel.name)} lead={words(sel.email)} actions={loading ? <SkeletonOf><Button icon="mail">{c.write}</Button></SkeletonOf> : <Button icon="mail" href={`mailto:${sel.email}`}>{c.write}</Button>} />
      <Tabs label={sel.name} items={[
        { id: 'overview', label: c.overview, content: <DescriptionList loading={loading} items={[
          { term: c.company, description: sel.company }, { term: c.plan, description: <Badge tone="light">{c.plans[sel.plan]}</Badge> },
          { term: c.since, description: format.date(new Date(sel.since)) }, { term: c.spent, description: format.currency(sel.spent, 'USD'), hint: `${sel.orders} ${c.orders.toLowerCase()}` },
          { term: c.country, description: sel.country }, { term: 'ID', description: <InlineCode>{sel.id}</InlineCode> },
        ]} /> },
        { id: 'orders', label: c.orders, content: <Table label={c.orders} rowKey={(o) => o.id} rows={Array.from({ length: Math.min(sel.orders, 5) }, (_, i) => ({ id: `#${1042 - i}`, at: now - i * 9 * day, total: 18 + ((i * 31) % 90) }))}
          columns={[{ id: 'id', header: c.order, cell: (o) => o.id }, { id: 'at', header: c.date, cell: (o) => format.date(new Date(o.at)) }, { id: 'total', header: c.total, numeric: true, cell: (o) => format.currency(o.total, 'USD') }]} /> },
        { id: 'activity', label: c.activity, content: <ActivityFeed label={c.activity} items={[
          { id: 1, actor: { name: sel.name }, action: c.acts.order, target: '#1042', time: ago(2 * 3600e3), icon: 'cart' },
          { id: 2, actor: { name: sel.name }, action: c.acts.email, time: ago(12 * day), icon: 'mail' },
          { id: 3, actor: { name: sel.name }, action: c.acts.signup, time: sel.since, icon: 'user-plus' },
        ]} /> },
      ]} />
    </Stack>
  ) : <EmptyState icon="user" title={c.pick}>{c.pickBody}</EmptyState>;
  return (
    <Page wide>
      <PageHeader title={c.title} lead={c.lead} />
      {phone ? (opened && sel ? detail : list) : <Split label={c.list} defaultSize={34} min={24} max={50}>{[<Panel key="l">{list}</Panel>, <div key="d">{detail}</div>]}</Split>}
    </Page>
  );
}

En un celular

En un celular primero va la lista; elegir abre el cliente y «Volver» regresa.

Aún no se elige nada

El lado del detalle dice qué aparecerá ahí.

Clientes

412 personas que compraron en northwind-shop.

Elige un cliente

Aquí aparecen sus datos, pedidos y actividad.

Skeleton

La lista dibuja los últimos clientes en su lugar y el detalle el que estaba abierto, cada valor tan largo como el suyo; la búsqueda, las pestañas y los nombres de los datos se quedan.

Clientes

412 personas que compraron en northwind-shop.

Empresa
Plan
Cliente desde
Gastó
País
ID

Cuándo usarlo

Úsalo cuando

  • Registros que se leen uno tras otro: clientes, tickets, mensajes, despliegues.
  • Un divisor que la persona puede arrastrar cuando ambos lados importan.

No lo uses cuando

  • Registros que necesitan todo el ancho para leerse: ábrelos en su propia página.
  • Dos paneles en un celular: muestra uno a la vez.

Para todos

  • El elegido lleva aria-current y la luz, nunca solo color.
  • El divisor se mueve con las flechas y dice su posición.
  • En celulares «Volver» devuelve el foco a la lista.

Props

SplitTipoPor defecto
childrenobligatorio

The two panes, in order.

[ReactNode, ReactNode]
className string
defaultSize

Size of the first pane at the start, in percent.

number 50
height

Height of the whole split, as CSS.

string
keepOnPhones

Keep the two panes side by side on phones too (they stack by default).

boolean
label

Name of the divider for screen readers: what it resizes.

string
max number 85
min

Limits of the first pane, in percent.

number 15
onSizeChange ((size: number) => void)
orientation

'horizontal': side by side. 'vertical': one above the other.

"horizontal" | "vertical" horizontal
size

Size of the first pane, when the parent keeps it.

number
ListItemTipoPor defecto
titleobligatorio ReactNode
actions

Buttons at the end (RowActions). On phones they go below.

ReactNode
current

The item shown next to the list right now: it carries the light and `aria-current`.

boolean
description

A second line: what it is, its state.

ReactNode
href

With it the whole item is a link.

string
icon "function" | "error" | "replay" | "performance" | "uptime" | "traces" | "rage-click" | "dead-click" | "alert" | "summary" | "watch" | "sleep" | "light" | "suggestion" | "prompt" | "mcp" | "pull-request" | "git-branch" | "fix" | "check" | "open-source" | "self-host" | "sdk" | "engine" | "signals-in" | "web" | "mobile" | "backend" | "cloud" | "data" | "user" | "clock" | "shield" | "lock" | "mail" | "star" | "copy" | "arrow-right" | "arrow-up-right" | "chevron-down" | "plus" | "close" | "play" | "pause" | "search" | "info" | "warning" | "trash" | "menu" | "download" | "upload" | "filter" | "home" | "table" | "key" | "users" | "sun" | "moon" | "globe" | "sign-out" | "link" | "edit" | "calendar" | "chevron-left" | "chevron-right" | "chevron-up" | "minus" | "more" | "sort" | "arrow-left" | "arrow-up" | "arrow-down" | "arrow-down-right" | "arrow-down-left" | "arrow-up-left" | "swap" | "swap-vertical" | "chevrons-up-down" | "chevrons-left" | "chevrons-right" | "chevrons-down" | "chevrons-up" | "enter" | "undo" | "redo" | "refresh" | "expand" | "collapse" | "fullscreen" | "fullscreen-exit" | "move" | "grip" | "more-vertical" | "trend-up" | "trend-down" | "log-in" | "external" | "slash" | "equal" | "check-small" | "close-small" | "success" | "failure" | "help" | "plus-circle" | "minus-circle" | "ban" | "pending" | "dot" | "dot-off" | "bolt" | "flag" | "pin" | "bookmark" | "heart" | "thumbs-up" | "thumbs-down" | "sparkle" | "target" | "idea" | "award" | "crown" | "bell" | "bell-off" | "bug" | "fire" | "leaf" | "file" | "file-text" | "file-code" | "file-plus" | "file-check" | "file-table" | "file-lock" | "files" | "folder" | "folder-open" | "folder-plus" | "archive" | "clipboard" | "clipboard-check" | "paperclip" | "image" | "save" | "cloud-upload" | "cloud-download" | "cloud-off" | "import" | "export" | "share" | "inbox" | "send" | "box" | "layers" | "tag" | "hash" | "at" | "qr-code" | "book" | "book-open" | "notebook" | "rows" | "columns" | "grid" | "list" | "list-ordered" | "list-checks" | "kanban" | "chart-line" | "chart-bar" | "chart-area" | "chart-parts" | "chart-scatter" | "gauge" | "funnel" | "heatmap" | "sparkline" | "percent" | "sum" | "variable" | "braces" | "brackets" | "null" | "primary-key" | "relation" | "index" | "query" | "backup" | "migrate" | "seed" | "csv" | "json" | "bold" | "italic" | "underline" | "strikethrough" | "heading" | "text" | "paragraph" | "quote" | "code" | "align-left" | "align-center" | "align-right" | "indent" | "outdent" | "unlink" | "scissors" | "eraser" | "highlight" | "duplicate" | "paste" | "wand" | "palette" | "brush" | "ruler" | "crop" | "user-plus" | "user-minus" | "user-check" | "user-x" | "user-circle" | "team" | "organization" | "id-card" | "contact" | "role" | "chat" | "chats" | "comment" | "phone" | "video" | "mic" | "mic-off" | "megaphone" | "rss" | "mail-open" | "handshake" | "wave" | "desktop" | "laptop" | "tablet" | "terminal" | "window" | "browser" | "server" | "cpu" | "memory" | "disk" | "network" | "wifi" | "wifi-off" | "plug" | "power" | "container" | "queue" | "cron" | "webhook" | "api" | "route" | "load-balancer" | "dns" | "domain" | "certificate" | "firewall" | "rocket" | "deploy" | "rollback" | "logs" | "test" | "pipeline" | "commit" | "merge" | "fork" | "release" | "environment" | "region" | "robot" | "agent" | "puzzle" | "credit-card" | "wallet" | "receipt" | "invoice" | "cart" | "bag" | "coins" | "dollar" | "gift" | "plan" | "upgrade" | "usage" | "bank" | "history" | "timer" | "hourglass" | "calendar-check" | "calendar-plus" | "map" | "compass" | "translate" | "accessibility" | "keyboard" | "pointer" | "hand" | "print" | "support" | "stop" | "record" | "skip-forward" | "skip-back" | "fast-forward" | "rewind" | "volume" | "mute" | "camera" | "zoom-in" | "zoom-out" | "eye-off" | "sliders" | "settings" | "toggle" | "sidebar-left" | "sidebar-right" | "panel-bottom" | "split" | "layout" | "dashboard" | "cards" | "density" | "dark-mode" | "theme" | "mouse" | "cursor" | "select" | "picture-in-picture" | "scan" | "unlock" | "shield-off" | "shield-alert" | "shield-user" | "password" | "fingerprint" | "two-factor" | "policy" | "incognito" | "verified" | "audit" | "secret" | "p-telemetry" | "p-cases" | "p-agent" | "p-git" | "p-data" | "p-files" | "p-run" | "p-ai" | "p-mail" | "p-domains" | "p-design" | "p-learn" | "p-skills" | "p-app" | "p-ui"
loading

The item is on its way: pass the last known (or typical) title and second line; they are bars as long as them, and the picture, icon and buttons are skeletons of their own boxes.

boolean
media

Something at the start instead of an icon: an Avatar.

ReactNode
meta

At the end: a date, a count, a badge.

ReactNode
onClick

With it (and no `href`) the whole item is a button: choosing one thing of the list, as in a master–detail view.

(() => void)
  1. En un computador
  2. En un celular
  3. Aún no se elige nada
  4. Skeleton
  5. Cuándo usarlo
  6. Para todos
  7. Props

    Busca páginas, secciones y términos