# Dialog

Janela modal, para decisão que não pode continuar em segundo plano.

Compõe com `DialogTrigger`, `DialogContent`, `DialogTitle`, `DialogDescription`,
`DialogFooter` e `DialogClose`.

Renderiza em portal dentro do container do `RivoProvider`, que carrega o tema.
Sem o Provider ele lanca erro, e não renderiza sem estilo.

## Quando não usar

Para confirmar o que não volta atrás (excluir, cancelar uma nota, sair sem
salvar), use `AlertDialog`. Este aqui fecha com Esc e com clique fora, e é isso
que o separa do outro: uma janela que se dispensa por engano não serve para uma
pergunta cuja resposta errada não tem desfazer.

Para o painel que abre no celular, prefira o `Sheet`: modal centralizado numa
tela estreita cobre quase tudo e briga com o teclado. E para o que só acrescenta
contexto ao lado de um botão (uma explicação, um formulário de duas linhas), o
`Popover` custa menos: o modal tranca o resto da página, e trancar a página para
mostrar um texto é cobrar caro por pouco.

## No React Native

Traduz: o `@rivocode/ui-native` exporta `Dialog` - `open`, `onOpenChange` e `title` como props; sem `DialogTrigger`. Abre em fade, e sem transição quando o sistema pede para reduzir movimento; o cartão sobe para o espaço acima do teclado. A API não é a mesma do web (no nativo tudo é controlado), e a [tabela de paridade](/react-native) diz o que muda peça a peça.

## Importação

```tsx
import { Dialog } from '@rivocode/ui'
```

## Exemplos

### Confirmação

```tsx
import { Button, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogTitle, DialogTrigger } from '@rivocode/ui'

export function Confirmation() {
  return (
    <div className="min-h-72">
      <Dialog defaultOpen>
        <DialogTrigger render={<Button variant="destructive" />}>Excluir projeto</DialogTrigger>
        <DialogContent>
          <DialogTitle>Excluir projeto</DialogTitle>
          <DialogDescription>
            Isto remove o projeto, o histórico e os arquivos ligados a ele. Não da para desfazer.
          </DialogDescription>
          <DialogFooter>
            <DialogClose render={<Button variant="ghost" />}>Cancelar</DialogClose>
            <Button variant="destructive">Excluir projeto</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  )
}
```

### Fechado

```tsx
import { Button, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogTitle, DialogTrigger } from '@rivocode/ui'

export function ClosedState() {
  return (
    <Dialog>
      <DialogTrigger render={<Button variant="secondary" />}>Abrir dialogo</DialogTrigger>
      <DialogContent>
        <DialogTitle>Título</DialogTitle>
        <DialogDescription>Corpo do dialogo.</DialogDescription>
      </DialogContent>
    </Dialog>
  )
}
```

## Props

| Prop | Tipo | Obrigatória | Desde | O que faz |
| --- | --- | --- | --- | --- |
| `actionsRef` | `RefObject<DialogRootActions \| null>` |  | 0.4.0 | A ref to imperative actions. |
| `defaultOpen` | `boolean` |  | 0.4.0 | Whether the dialog is initially open. |
| `defaultTriggerId` | `string \| null` |  | 0.4.0 | ID of the trigger that the dialog is associated with. |
| `disablePointerDismissal` | `boolean` |  | 0.4.0 | Whether to prevent the dialog from closing on outside presses. |
| `handle` | `DialogHandle<Payload>` |  | 0.4.0 | A handle to associate the dialog with a trigger. |
| `modal` | `"trap-focus" \| boolean` |  | 0.4.0 | Determines if the dialog enters a modal state when open. |
| `onOpenChange` | `((open: boolean, eventDetails: DialogRootChangeEventDetails) => void)` |  | 0.4.0 | Event handler called when the dialog is opened or closed. |
| `onOpenChangeComplete` | `((open: boolean) => void)` |  | 0.4.0 | Event handler called after any animations complete when the dialog is opened or closed. |
| `open` | `boolean` |  | 0.4.0 | Whether the dialog is currently open. |
| `triggerId` | `string \| null` |  | 0.4.0 | ID of the trigger that the dialog is associated with. |

## Partes

O componente se monta com as peças abaixo. Todas vêm de `@rivocode/ui`.

### DialogClose

Fecha o diálogo sem você guardar estado.

Envolve o botão de cancelar, o X do canto ou qualquer coisa que deva fechar.
Com `render`, vira o elemento que você passar.

| Prop | Tipo | Obrigatória | Desde | O que faz |
| --- | --- | --- | --- | --- |
| `nativeButton` | `boolean` |  | 0.4.0 | Whether the component renders a native `<button>` element when replacing it via the `render` prop. |
| `render` | `ComponentRenderFn<HTMLProps, DialogCloseState> \| ReactElement<unknown, string \| JSXElementConstructor<any>>` |  | 0.4.0 | Allows you to replace the component's HTML element with a different tag, or compose it with another component. |

### DialogContent

O painel do diálogo, com a tarja de fundo e o portal já montados.

No desktop ele centraliza. **No celular ele encosta embaixo e ocupa a largura
toda**, que é onde o polegar alcança, centralizado, sobraria tarja dos dois
lados e o conteúdo ficaria espremido no meio da tela.

O portal usa o contêiner do `RivoProvider`, então o tema vale dentro dele.

| Prop | Tipo | Obrigatória | Desde | O que faz |
| --- | --- | --- | --- | --- |
| `classNames` | `Partial<Record<"backdrop", string>>` |  | 0.5.0 | Classe por parte: `backdrop`. |
| `finalFocus` | `boolean \| RefObject<HTMLElement \| null> \| ((closeType: InteractionType) => void \| boolean \| HTMLElement \| null)` |  | 0.4.0 | Determines the element to focus when the dialog is closed. |
| `initialFocus` | `boolean \| RefObject<HTMLElement \| null> \| ((openType: InteractionType) => void \| boolean \| HTMLElement \| null)` |  | 0.4.0 | Determines the element to focus when the dialog is opened. |
| `render` | `ComponentRenderFn<HTMLProps, DialogPopupState> \| ReactElement<unknown, string \| JSXElementConstructor<any>>` |  | 0.4.0 | Allows you to replace the component's HTML element with a different tag, or compose it with another component. |

### DialogDescription

A frase abaixo do título, com o que o diálogo pede.

Vira o `aria-describedby` do painel, então o leitor de tela lê o contexto junto
com o título, antes de chegar aos botões.

| Prop | Tipo | Obrigatória | Desde | O que faz |
| --- | --- | --- | --- | --- |
| `render` | `ComponentRenderFn<HTMLProps, DialogDescriptionState> \| ReactElement<unknown, string \| JSXElementConstructor<any>>` |  | 0.4.0 | Allows you to replace the component's HTML element with a different tag, or compose it with another component. |

### DialogFooter

A fila de ações do diálogo, alinhada à direita.

A ação que confirma vai por último na marcação, encostada na borda: é a que o
olho encontra por último no desktop.

**No celular os dois botões empilham e ocupam a largura toda**, porque o painel
já encosta embaixo e duas ações lado a lado numa tela estreita saem apertadas
demais. Na pilha a ordem se inverte: quem confirma sobe para o alto e quem
cancela fica rente ao polegar. É o mesmo comportamento do `AlertDialogFooter`.

### DialogTitle

O título do diálogo.

Não é enfeite: a Base UI liga ele no `aria-labelledby` do painel, e um diálogo
sem título é anunciado como "diálogo" e nada mais. Se o desenho não pede
título visível, mantenha a peça e esconda com `sr-only`.

| Prop | Tipo | Obrigatória | Desde | O que faz |
| --- | --- | --- | --- | --- |
| `render` | `ComponentRenderFn<HTMLProps, DialogTitleState> \| ReactElement<unknown, string \| JSXElementConstructor<any>>` |  | 0.4.0 | Allows you to replace the component's HTML element with a different tag, or compose it with another component. |

### DialogTrigger

O que abre o diálogo.

Por padrão sai como `<button>`. Para abrir a partir de outra peça, um item de
menu, um cartão inteiro, passe `render` com o elemento, e o estado de aberto
continua ligado no `aria-expanded` certo.

| Prop | Tipo | Obrigatória | Desde | O que faz |
| --- | --- | --- | --- | --- |
| `handle` | `DialogHandle<Payload>` |  | 0.4.0 | A handle to associate the trigger with a dialog. |
| `nativeButton` | `boolean` |  | 0.4.0 | Whether the component renders a native `<button>` element when replacing it via the `render` prop. |
| `payload` | `Payload` |  | 0.4.0 | A payload to pass to the dialog when it is opened. |
| `render` | `ComponentRenderFn<HTMLProps, DialogTriggerState> \| ReactElement<unknown, string \| JSXElementConstructor<any>>` |  | 0.4.0 | Allows you to replace the component's HTML element with a different tag, or compose it with another component. |

## Ver também

- [AlertDialog](/componentes/alert-dialog.md)
- [ContextMenu](/componentes/context-menu.md)
- [Popconfirm](/componentes/popconfirm.md)
- [Popover](/componentes/popover.md)
- [PreviewCard](/componentes/preview-card.md)
- [Sheet](/componentes/sheet.md)
- [Convenções da biblioteca](/convencoes.md): Provider, tokens e as regras que valem para toda peça
- [Índice completo](/llms.txt)
