Skip to content

SecretReveal

A secret is shown once, when it is made, and never again. The dialog that shows it cannot be closed by accident, and «Done» waits until the person says they saved it.

import { CopyField, Dialog } from '@sypnia/ui/react'

On this page
  1. On a desktop
  2. On a phone
  3. When the key cannot be made
  4. When to use it
  5. For everyone
  6. Props

On a desktop

Press «Create a key»: the dialog opens at once with its words while the key waits in its own box, then the key. Try to close it before ticking the box.

API keys

Where it will be used, so you can tell keys apart: «checkout server».

Code
import { useState } from 'react';
import {
  Alert, Button, Callout, Checkbox, CopyField, Dialog, Field, Input, Notice, Panel, SkeletonOf, Snippet, Stack, Toaster, toast, useSypnia,
} from '@sypnia/ui/react';

// A secret is shown once, at the moment it is made, and never again: only its first characters stay visible. The
// dialog cannot be closed by accident while the secret is on screen, and «Done» waits until the person says they saved it.
const en = {
  panel: 'API keys', create: 'Create a key', name: 'Name of the key', nameHint: 'Where it will be used, so you can tell keys apart: «checkout server».',
  title: 'Save your new key', lead: 'Copy it now and keep it somewhere safe, like your password manager or your server’s environment.',
  once: 'This is the only time the whole key is shown. If you lose it, create a new one and delete this one.', keyLabel: 'Secret key',
  env: 'Use it as an environment variable', saved: 'I saved the key somewhere safe', done: 'Done', creating: 'Creating…',
  noName: 'Give the key a name first.', failed: 'The key could not be created', failedBody: 'Nothing was made, so nothing needs cleaning up. Try again.', retry: 'Try again',
  made: (n: string) => `The key «${n}» is ready`, after: (n: string, p: string) => `«${n}» now shows only as ${p}… in your list.`,
};
const es: typeof en = {
  panel: 'Llaves de API', create: 'Crear una llave', name: 'Nombre de la llave', nameHint: 'Dónde se usará, para distinguir las llaves: «servidor de pagos».',
  title: 'Guarda tu llave nueva', lead: 'Cópiala ahora y guárdala en un lugar seguro, como tu gestor de contraseñas o el entorno de tu servidor.',
  once: 'Esta es la única vez que se muestra la llave completa. Si la pierdes, crea una nueva y borra esta.', keyLabel: 'Llave secreta',
  env: 'Úsala como variable de entorno', saved: 'Guardé la llave en un lugar seguro', done: 'Listo', creating: 'Creando…',
  noName: 'Primero ponle un nombre a la llave.', failed: 'No se pudo crear la llave', failedBody: 'No se creó nada, así que no hay nada que limpiar. Intenta de nuevo.', retry: 'Intentar de nuevo',
  made: (n: string) => `La llave «${n}» está lista`, after: (n: string, p: string) => `«${n}» ahora se ve solo como ${p}… en tu lista.`,
};
const wait = (ms: number) => new Promise((r) => setTimeout(r, ms));
const sample = `sk_live_${'x'.repeat(32)}`; // as long as a real key
const newKey = () => `sk_live_${Array.from({ length: 32 }, () => 'abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'[Math.floor(Math.random() * 56)]).join('')}`;

export default function SecretReveal({ state = 'ready' }: { state?: 'ready' | 'error' }) {
  const { locale } = useSypnia();
  const c = locale.startsWith('es') ? es : en;
  const [name, setName] = useState('checkout server');
  const [nameError, setNameError] = useState<string>();
  const [busy, setBusy] = useState(false);
  const [failed, setFailed] = useState(state === 'error');
  const [secret, setSecret] = useState<string | null>(null);
  const [open, setOpen] = useState(false);
  const [saved, setSaved] = useState(false);
  const [last, setLast] = useState<string>();
  const create = async () => {
    if (!name.trim()) { setNameError(c.noName); return; }
    setBusy(true); setFailed(false); setSaved(false);
    await wait(500);
    if (state === 'error') { setBusy(false); setFailed(true); return; }
    setOpen(true); // the dialog opens at once; its body is a skeleton until the key arrives
    await wait(1200);
    setBusy(false); setSecret(newKey());
  };
  const close = () => {
    toast(c.made(name), { tone: 'ok' });
    setLast(c.after(name, secret!.slice(0, 12))); setOpen(false); setSecret(null);
  };
  return (
    <>
      <Panel title={c.panel}>
        <Stack gap={4}>
          {failed && <Alert tone="fail" title={c.failed} actions={<Button size="sm" icon="refresh" onClick={create}>{c.retry}</Button>}>{c.failedBody}</Alert>}
          <Field label={c.name} hint={c.nameHint} error={nameError}><Input value={name} onChange={(e) => { setName(e.target.value); setNameError(undefined); }} /></Field>
          <div><Button variant="primary" icon="key" busy={busy} onClick={create}>{busy ? c.creating : c.create}</Button></div>
          {last && <Notice tone="ok">{last}</Notice>}
        </Stack>
      </Panel>
      {/* The dialog opens at once with its real words; until the key arrives, the key, the command and the box wait in
          their own boxes (a key of the same length), so nothing moves when it comes. */}
      <Dialog open={open} onClose={() => saved && close()} dismissable={false} dirty={!saved} title={c.title}
        footer={<Button variant="primary" disabled={!saved} onClick={close}>{c.done}</Button>}>
        <Stack gap={4}>
          <p>{c.lead}</p>
          <Field label={c.keyLabel}>{secret ? <CopyField value={secret} label={c.keyLabel} secret /> : <SkeletonOf><CopyField value={sample} label={c.keyLabel} secret /></SkeletonOf>}</Field>
          <Callout kind="warn">{c.once}</Callout>
          <Stack gap={2}><strong>{c.env}</strong>{secret ? <Snippet code={`export SYPNIA_KEY=${secret}`} label={c.env} /> : <SkeletonOf><Snippet code={`export SYPNIA_KEY=${sample}`} label={c.env} /></SkeletonOf>}</Stack>
          {secret ? <Checkbox label={c.saved} checked={saved} onChange={(e) => setSaved(e.target.checked)} /> : <Checkbox label={c.saved} disabled />}
        </Stack>
      </Dialog>
      <Toaster />
    </>
  );
}

On a phone

On a phone the dialog fills the screen and the buttons stay at the bottom.

When the key cannot be made

Nothing was made, so nothing needs cleaning up: say so, and offer to try again.

API keys

Where it will be used, so you can tell keys apart: «checkout server».

When to use it

Use it when

  • API keys, signing secrets, recovery codes, database passwords: anything the server keeps only as a hash.
  • Showing how to use the secret right there: the environment variable, ready to copy.

Do not use it when

  • Showing the secret again later: keep only its first characters and offer to create a new one.
  • Closing on a click outside: the person would lose a secret they cannot see again.

For everyone

  • The dialog takes the focus and keeps it; Escape and a press outside do not close it while the secret is unsaved.
  • Copy says «Copied» to screen readers; the masked value has a button to show it, with its state.
  • «Done» is disabled, not hidden, until the checkbox is ticked, so the person knows what is missing.

Props

CopyFieldTypeDefault
valuerequired string
label string
once boolean
secret boolean
DialogTypeDefault
onCloserequired () => void
titlerequired ReactNode
dirty

The form inside has changes that are not saved. A press outside or Escape then does not close it and does not lose them: the panel nudges and says to save or cancel. Only the buttons close it.

boolean
dismissable

Whether a press on the backdrop (outside the panel) closes it. On by default; Escape always closes it too. Set false for a form that must be finished or cancelled with its buttons.

boolean
footer

Buttons at the bottom, inside <Actions>.

ReactNode
lines

How many lines of skeleton the body shows while loading.

number
loading

What it shows is on its way: the title and the buttons stay, the body is lines of skeleton.

boolean
open

Whether it is open. It can also simply be mounted and unmounted: it is open while mounted.

boolean
size "sm" | "md" | "lg" | "xl" md
  1. On a desktop
  2. On a phone
  3. When the key cannot be made
  4. When to use it
  5. For everyone
  6. Props

    Search pages, sections and terms