FormPage
Una página entera que crea algo: el camino de vuelta, un título que dice qué se crea, los campos en secciones que dicen para qué son, y un botón que dice qué pasa.
import { Form, FormSection, FormActions } from '@sypnia/ui/react'
En un computador
Pulsa «Crear base de datos»: el nombre orders ya existe, así que el servidor lo dice junto al campo. Cámbialo y envía de nuevo.
Nueva base de datos
Una base de datos Postgres con su API, copias de seguridad y un lugar en la región que elijas.
Código
import { useState } from 'react';
import {
Alert, BackButton, Button, EmptyState, Field, Form, FormActions, FormSection, Page, PageHeader,
RadioCards, RegionSelect, Select, SkeletonOf, SlugInput, Switch, Textarea, useSypnia, type FormProblem,
} from '@sypnia/ui/react';
// A whole page that creates something: the way back, a title that says what is made, the fields in sections that each
// say what they are for, and one button that says what happens. Checks before sending, lists what to fix, and shows
// what only the server knows (a name already taken) next to its field.
const en = {
back: 'Databases', title: 'New database', lead: 'A Postgres database with its API, backups and a place in the region you choose.',
s1: 'Name and place', s1d: 'The name is part of every address of the database. The region is where the data lives, and it cannot change later.',
name: 'Name', nameHint: 'Lowercase letters, numbers and dashes.', region: 'Region', regionHint: 'Choose the one closest to your users.',
about: 'What it is for', s2: 'Size', s2d: 'You can change the size at any time; the database restarts for a few seconds.',
s3: 'Backups', s3d: 'Copies of the whole database, to go back to a moment before a mistake.',
daily: 'Back up every day', dailyD: 'At 03:00 in the database’s region.', keep: 'Keep copies for',
cancel: 'Cancel', submit: 'Create database', busy: 'Creating…',
noName: 'Write a name for the database.', taken: (n: string) => `${n} is already a database in this project. Choose another name.`, noRegion: 'Choose a region.',
created: (n: string) => `${n} is ready`, createdBody: 'Its address and keys are on the database page. It is empty: create a table or import a CSV.',
open: 'Open the database', another: 'Create another',
failedTitle: 'This page could not load the regions', failedBody: 'Without them the database cannot be placed. Nothing was created. Try again.', retry: 'Try again',
days: (n: number) => `${n} days`,
};
const es: typeof en = {
back: 'Bases de datos', title: 'Nueva base de datos', lead: 'Una base de datos Postgres con su API, copias de seguridad y un lugar en la región que elijas.',
s1: 'Nombre y lugar', s1d: 'El nombre va en todas las direcciones de la base de datos. La región es donde viven los datos, y no se puede cambiar después.',
name: 'Nombre', nameHint: 'Letras minúsculas, números y guiones.', region: 'Región', regionHint: 'Elige la más cercana a tus usuarios.',
about: 'Para qué es', s2: 'Tamaño', s2d: 'Puedes cambiar el tamaño cuando quieras; la base de datos se reinicia por unos segundos.',
s3: 'Copias de seguridad', s3d: 'Copias de toda la base de datos, para volver a un momento antes de un error.',
daily: 'Copiar cada día', dailyD: 'A las 03:00 en la región de la base de datos.', keep: 'Guardar las copias por',
cancel: 'Cancelar', submit: 'Crear base de datos', busy: 'Creando…',
noName: 'Escribe un nombre para la base de datos.', taken: (n: string) => `${n} ya es una base de datos de este proyecto. Elige otro nombre.`, noRegion: 'Elige una región.',
created: (n: string) => `${n} está lista`, createdBody: 'Su dirección y sus llaves están en la página de la base de datos. Está vacía: crea una tabla o importa un CSV.',
open: 'Abrir la base de datos', another: 'Crear otra',
failedTitle: 'Esta página no pudo cargar las regiones', failedBody: 'Sin ellas no se puede ubicar la base de datos. No se creó nada. Intenta de nuevo.', retry: 'Intentar de nuevo',
days: (n: number) => `${n} días`,
};
const regions = [
{ id: 'eu-west', name: 'Europe (Ireland)', location: 'Dublin' }, { id: 'us-east', name: 'United States (Virginia)', location: 'Ashburn' },
{ id: 'sa-east', name: 'South America (São Paulo)', location: 'São Paulo' },
];
const sizes = (es_: boolean) => [
{ value: 'small', label: es_ ? 'Pequeña' : 'Small', description: es_ ? '2 GB de memoria · hasta 10 GB de datos' : '2 GB memory · up to 10 GB of data' },
{ value: 'medium', label: es_ ? 'Mediana' : 'Medium', description: es_ ? '8 GB de memoria · hasta 100 GB de datos' : '8 GB memory · up to 100 GB of data' },
{ value: 'large', label: es_ ? 'Grande' : 'Large', description: es_ ? '32 GB de memoria · hasta 1 TB de datos' : '32 GB memory · up to 1 TB of data' },
];
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
export default function FormPage({ state = 'ready' }: { state?: 'ready' | 'loading' | 'error' }) {
const { locale } = useSypnia();
const isEs = locale.startsWith('es');
const c = isEs ? es : en;
const [problems, setProblems] = useState<FormProblem[]>([]);
const [daily, setDaily] = useState(true);
const [done, setDone] = useState<string>();
const [failed, setFailed] = useState(state === 'error');
const header = <><div><BackButton href="#databases">{c.back}</BackButton></div><PageHeader title={c.title} lead={c.lead} /></>;
// Loading: the real form. Only what comes from the server waits, in its own box: the regions and the sizes; the
// rest is there, disabled until they come.
const loading = state === 'loading';
const off = failed || loading;
if (done) {
return (
<Page>
{header}
<EmptyState icon="success" title={c.created(done)} actions={<><Button variant="primary" href="#database">{c.open}</Button><Button onClick={() => setDone(undefined)}>{c.another}</Button></>}>{c.createdBody}</EmptyState>
</Page>
);
}
const check = (v: FormData): FormProblem[] => {
const out: FormProblem[] = [];
if (!String(v.get('name') ?? '').trim()) out.push({ name: 'name', label: c.name, message: c.noName });
if (!v.get('region')) out.push({ name: 'region', label: c.region, message: c.noRegion });
return out;
};
return (
<Page>
{header}
{failed && <Alert tone="fail" title={c.failedTitle} actions={<Button size="sm" icon="refresh" onClick={() => setFailed(false)}>{c.retry}</Button>}>{c.failedBody}</Alert>}
<Form label={c.title} validate={check} problems={problems} onSubmit={async (v) => {
await wait(1200);
const name = String(v.get('name'));
if (name === 'orders') setProblems([{ name: 'name', label: c.name, message: c.taken(name) }]);
else setDone(name);
}}>
{({ errorFor }) => (
<>
<FormSection title={c.s1} description={c.s1d}>
<Field label={c.name} hint={c.nameHint} error={errorFor('name')}><SlugInput name="name" defaultValue="orders" disabled={off} onChange={() => setProblems([])} /></Field>
<Field label={c.region} hint={c.regionHint} error={errorFor('region')}>{loading ? <SkeletonOf><RegionSelect name="region" regions={regions} /></SkeletonOf> : <RegionSelect name="region" regions={regions} disabled={failed} />}</Field>
<Field label={c.about} optional><Textarea name="about" rows={2} disabled={off} /></Field>
</FormSection>
<FormSection title={c.s2} description={c.s2d}>
{loading ? <SkeletonOf><RadioCards name="size" aria-label={c.s2} options={sizes(isEs)} defaultValue="small" /></SkeletonOf>
: <RadioCards name="size" aria-label={c.s2} options={sizes(isEs)} defaultValue="small" disabled={failed} />}
</FormSection>
<FormSection title={c.s3} description={c.s3d}>
<Switch name="daily" label={c.daily} description={c.dailyD} checked={daily} onChange={(e) => setDaily(e.target.checked)} disabled={off} />
{daily && <Field label={c.keep}><Select name="keep" defaultValue="30" disabled={off} options={[7, 30, 90].map((n) => ({ value: String(n), label: c.days(n) }))} /></Field>}
</FormSection>
<FormActions submitLabel={c.submit} busyLabel={c.busy} cancel={<Button variant="quiet" href="#databases">{c.cancel}</Button>} />
</>
)}
</Form>
</Page>
);
} En un celular
A 390 px el título de cada sección va encima de sus campos y los botones comparten el ancho.
Skeleton
El formulario real mientras cargan las regiones y los tamaños: solo esos dos esperan en sus propias cajas; los demás campos están ahí, deshabilitados.
Nueva base de datos
Una base de datos Postgres con su API, copias de seguridad y un lugar en la región que elijas.
Cuando la página no puede cargar lo que necesita
Las regiones no llegaron: el formulario se queda, deshabilitado, bajo un mensaje con «Intentar de nuevo».
Nueva base de datos
Una base de datos Postgres con su API, copias de seguridad y un lugar en la región que elijas.
Esta página no pudo cargar las regiones
Cuándo usarlo
Úsalo cuando
- Crear cualquier cosa con más de unos pocos campos: una base de datos, un proyecto, un webhook.
- Secciones cuando los campos responden preguntas distintas; cada sección dice en una frase por qué se pregunta.
- Decir en la ayuda lo que no se puede cambiar después, como la región.
No lo uses cuando
- Tres campos o menos: basta un Dialog.
- Editar ajustes que ya existen: eso es una SettingsPage, que guarda con una SaveBar.
- Un botón que dice «Enviar»: dice lo que pasa, «Crear base de datos».
Para todos
- Tras un intento fallido, el resumen de lo que hay que corregir toma el foco; cada línea lleva el foco a su campo.
- Los errores que encuentra el servidor, como un nombre que ya existe, se unen a su campo de la misma forma.
- Cada sección es una región nombrada por su título; el título de la página es el único h1.
Props
| Form | Tipo | Por defecto |
|---|---|---|
childrenobligatorioThe fields. Pass a function to get the form's state, for example `({ errorFor }) => <Field error={errorFor('name')}>…`. | ReactNode | ((state: FormState) => ReactNode) | |
onSubmitobligatorioRuns on submit with the form's values. It may be async: while it runs the submit button shows it is working. | (values: FormData) => void | Promise<void> | |
className | string | |
labelAccessible name of the form, when the page has more than one. | string | |
problemsProblems found by the server after sending (for example a name already taken). | FormProblem[] | |
validateChecks the values before sending. Return the problems, or an empty list when everything is right. When there are problems nothing is sent, an ErrorSummary appears at the top and the focus moves to it. | ((values: FormData) => FormProblem[]) |
| FormSection | Tipo | Por defecto |
|---|---|---|
titleobligatorio | ReactNode | |
className | string | |
description | ReactNode | |
fieldsHow many field skeletons to show while loading. | number | 2 |
loadingThe values are on their way: the title stays and the fields are skeletons. | boolean |
| FormActions | Tipo | Por defecto |
|---|---|---|
submitLabelobligatorio | string | |
align | "start" | "end" | |
busyLabelWhat the submit button says while it works: «Creating…». Defaults to «Saving…». | string | |
cancelUsually a quiet Button that goes back. | ReactNode | |
danger | boolean |