> ## Documentation Index
> Fetch the complete documentation index at: https://docs.twenty.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Diálogo

> Presenta una tarea específica sobre la página actual.

## Resumen

Usa `Dialog` para formularios, detalles y otras tareas que se abren sobre la página. Gestiona el foco, el cierre con el teclado, los clics fuera y el desplazamiento. Usa [AlertDialog](https://docs.twenty.com/es/ui/primitives/surfaces/alert-dialog.md) cuando el usuario debe responder explícitamente a una decisión.

Esta API es para Twenty UI independiente y la aplicación host de Twenty. Los componentes front deben usar [`openCommandConfirmationModal`](https://docs.twenty.com/es/developers/extend/apps/layout/front-components#host-communication-api) del SDK en lugar de renderizar `Dialog` o `AlertDialog` directamente. Los diálogos nativos del navegador y los popovers también están prohibidos en el renderizador de componentes front.

**Light**

[Ejemplo de diálogo (light)](https://storybook.twenty.com/iframe.html?id=ui-surfaces-dialog--display\&viewMode=story\&globals=colorScheme:light)

**Dark**

[Ejemplo de diálogo (dark)](https://storybook.twenty.com/iframe.html?id=ui-surfaces-dialog--display\&viewMode=story\&globals=colorScheme:dark)

[Open in Storybook](https://storybook.twenty.com/?path=/story/ui-surfaces-dialog--display)

## "Uso"

### Estado no controlado

`Root` gestiona la visibilidad de forma predeterminada. Establece `defaultOpen` para su estado inicial. Los activadores, los controles de cierre, Escape y los clics fuera actualizan ese estado.

```tsx theme={null}
import { Button, Field, Input } from 'twenty-ui/primitives/input';
import { Dialog } from 'twenty-ui/primitives/surfaces';

export const AccountDialog = () => (
  <Dialog.Root defaultOpen={false}>
    <Dialog.Trigger render={<Button>Edit account</Button>} />
    <Dialog.Portal>
      <Dialog.Backdrop />
      <Dialog.Viewport>
        <Dialog.Popup>
          <Dialog.Header>
            <Dialog.Title>Edit account</Dialog.Title>
            <Dialog.Description>Update the account details.</Dialog.Description>
          </Dialog.Header>
          <Dialog.Body>
            <Field.Root name="company">
              <Field.Label>Company name</Field.Label>
              <Input defaultValue="Acme" />
            </Field.Root>
          </Dialog.Body>
          <Dialog.Footer>
            <Dialog.Close render={<Button variant="outline">Close</Button>} />
            <Dialog.Close render={<Button>Save</Button>} />
          </Dialog.Footer>
        </Dialog.Popup>
      </Dialog.Viewport>
    </Dialog.Portal>
  </Dialog.Root>
);
```

## Anatomía

```text theme={null}
Dialog.Root
├── Dialog.Trigger
└── Dialog.Portal
    ├── Dialog.Backdrop
    └── Dialog.Viewport
        └── Dialog.Popup
            ├── Dialog.Header
            │   ├── Dialog.Title
            │   └── Dialog.Description
            ├── Dialog.Body
            └── Dialog.Footer
                └── Dialog.Close
```

| Parte | Destino nativo y de ref |
| - | - |
| `Root` | Coordina la visibilidad y el comportamiento modal. No renderiza ningún nodo DOM y no acepta atributos nativos ni ref de DOM. |
| `Disparador` | Un botón de forma predeterminada. Abre el diálogo y proporciona un destino para restaurar el foco. |
| `Portal` | El div del portal. Gestiona el contenedor de destino y si el contenido cerrado permanece montado. |
| `Backdrop` | El div de fondo debajo de la ventana emergente. Opcional; omítelo cuando no se necesite un fondo visible. |
| `Viewport` | El div de posicionamiento alrededor de la ventana emergente. |
| `Popup` | El div del diálogo. Gestiona el contenido, el tamaño, los destinos de foco y la semántica del diálogo. |
| `Título` | Un `h2` de forma predeterminada. Proporciona el nombre accesible. Proporciona `aria-label` en `Popup` al omitirlo. |
| `Description` | Un párrafo de forma predeterminada. Asocia texto de apoyo con el diálogo. |
| `Header`, `Body`, `Footer` | Divs opcionales que organizan encabezados, contenido y acciones. |
| `Cerrar` | Un botón de forma predeterminada. Proporciona una acción de cierre visible, incluso para lectores de pantalla táctiles. |

Ensamble `Portal`, `Backdrop`, `Viewport` y `Popup` explícitamente. Cada parte del DOM acepta sus propios atributos nativos, controladores, `className`, `style`, ref y composición de `render`. Una ref apunta al elemento renderizado de esa parte. `Popup` no crea un portal, fondo ni viewport.

## Estado controlado

Pasa `open` y `onOpenChange` cuando la aplicación gestiona la visibilidad. El callback recibe el estado solicitado y los detalles del evento de Base UI, incluidos `reason`, `event`, `trigger` y `cancel()`. Actualiza el estado para aceptar un cambio o llama a `eventDetails.cancel()` para rechazarlo. `onOpenChangeComplete` se ejecuta cuando finaliza la animación de apertura o cierre.

```tsx theme={null}
import { useState } from 'react';
import { Button, Field, Input } from 'twenty-ui/primitives/input';
import { Dialog } from 'twenty-ui/primitives/surfaces';

export const AccountDialog = () => {
  const [open, setOpen] = useState(false);

  return (
    <Dialog.Root open={open} onOpenChange={setOpen}>
      <Dialog.Trigger render={<Button>Edit account</Button>} />
      <Dialog.Portal>
        <Dialog.Backdrop />
        <Dialog.Viewport>
          <Dialog.Popup>
            <Dialog.Header>
              <Dialog.Title>Edit account</Dialog.Title>
              <Dialog.Description>
                Update the account details.
              </Dialog.Description>
            </Dialog.Header>
            <Dialog.Body>
              <Field.Root name="company">
                <Field.Label>Company name</Field.Label>
                <Input defaultValue="Acme" />
              </Field.Root>
            </Dialog.Body>
            <Dialog.Footer>
              <Dialog.Close render={<Button variant="outline">Close</Button>} />
              <Dialog.Close render={<Button>Save</Button>} />
            </Dialog.Footer>
          </Dialog.Popup>
        </Dialog.Viewport>
      </Dialog.Portal>
    </Dialog.Root>
  );
};
```

Para un formulario asíncrono, mantén el diálogo abierto durante el envío. Ciérralo después de que se complete correctamente y muestra los errores dentro del diálogo.

## Composición

`Trigger` y `Close` aceptan `render` para componerse con `Button`, como se muestra arriba. Los envoltorios personalizados deben [reenviar las props y refs proporcionadas](https://docs.twenty.com/es/ui/primitives/overview#custom-components). Las partes del DOM conservan los nombres de clase, estilos y contratos de `render` con reconocimiento de estado de Base UI. `Header`, `Body` y `Footer` conservan su diseño con estilo y composición de div nativa.

Anida otro `Dialog.Root` dentro de un popup para abrir un segundo diálogo. Al cerrar el diálogo anidado, el foco vuelve a su activador en el diálogo principal.

Para abrir un diálogo desde triggers fuera de `Root`, cree un handle una vez con `Dialog.createHandle\<TPayload>()` y páselo a `handle` tanto en `Root` como en cada `Trigger`. Los valores de `payload` de `Trigger` están disponibles en la función de renderizado de `Root`. `Dialog.Handle` y el tipo público `DialogHandle` exponen el contrato del handle instalado:

| Miembro | Propósito |
| - | - |
| `open(triggerId)` | Abre con un trigger coincidente como trigger activo. |
| `open(null)` | Abre sin asociar un trigger. |
| `openWithPayload(payload)` | Abre con una carga útil tipada y sin trigger asociado. |
| `close()` | Solicita el cierre. |
| `isOpen` | Indica si el diálogo asociado está abierto. |

Las acciones imperativas solo tienen efecto mientras el Root asociado está montado. `actionsRef` de Root también expone `close()` y `unmount()` para un control explícito de la transición. Para controlar una animación de cierre externa, llame a `eventDetails.preventUnmountOnClose()` en `onOpenChange` y, luego, llame a la acción `unmount()` cuando finalice la animación.

`Title` usa `Heading` y de forma predeterminada es un `h2` con texto grande, color de texto principal, alineación centrada y espaciado 4 debajo. Usa `level` para cambiar el nivel del encabezado independientemente de `size`, o `color` para cambiar su color de texto. Los elementos nativos `className`, `style`, refs y `render` se reenvían al encabezado. Mantén un elemento de encabezado al usar `render`. `Description` está centrada como `Title`; AlertDialog mantiene ambos alineados a la izquierda.

`Popup` no tiene relleno. `Header`, `Body` y `Footer` proporcionan la sangría, por lo que el contenido colocado directamente en `Popup` queda junto a sus bordes.

## Foco, desplazamiento y cierre

`Root.modal` controla el límite de interacción:

| Valor | Foco | Desplazamiento de la página e interacción externa |
| - | - | - |
| `true` (predeterminado) | Atrapado dentro del diálogo | Se bloquean el desplazamiento de la página y la interacción externa. |
| `"trap-focus"` | Atrapado dentro del diálogo | El desplazamiento de la página y la interacción externa siguen disponibles. |
| `falso` | Puede salir del diálogo | El desplazamiento de la página y la interacción externa permanecen disponibles. |

Omita `Backdrop` cuando no se necesite un fondo visible. Para un diálogo no modal cuyo viewport debe permitir que los eventos de puntero pasen a la página, use `\<Dialog.Viewport data-backdrop-hidden="true">`; Popup permanece interactivo. Omitir solo el fondo visual no cambia `Root.modal`.

Establece `Popup.initialFocus` o `Popup.finalFocus` en una ref o devolución de llamada para elegir los destinos del foco; `false` desactiva ese movimiento automático del foco. Los callbacks de foco reciben el tipo de interacción y conservan el comportamiento de retorno booleano, elemento, null y undefined de Base UI. Normalmente, al cerrar se restaura el foco al trigger o al elemento previamente enfocado.

`Root.disablePointerDismissal` evita que los clics fuera soliciten el cierre. Para evitar el cierre con Escape, cancela el cambio `escape-key` en `onOpenChange`. Proporciona siempre una forma visible de cerrar un diálogo modal.

## Tamaños y portales

`Popup.size` acepta `sm`, `compact`, `md`, `lg`, `xl` y `fullscreen`, y su valor predeterminado es `md`. El contenido largo se desplaza dentro del popup. El ancho está limitado a la ventana gráfica.

Configure `Portal.container` para elegir un destino:

| Valor | Resolución |
| - | - |
| Omitido o `undefined` | Usa el contenedor de tema con ámbito más cercano. Sin uno, Base UI usa el portal principal o el cuerpo del documento. |
| Elemento o `ShadowRoot` | Usa ese destino explícito en lugar del ámbito del tema. |
| Referencia | Base UI resuelve su elemento actual. Una ref cuyo valor actual es null recurre al portal principal o al cuerpo del documento. |
| `null` | Espera sin montar. Proporcione un destino en un renderizado posterior para montar. |

`Portal.keepMounted` conserva el contenido y el estado del formulario mientras está cerrado. `Viewport` y `Popup` trasladan la dirección de texto proporcionada a un contenedor externo; sus props explícitas `dir` tienen prioridad. Sin un proveedor de dirección ni `dir` explícito, heredan del destino. Consulte [temas](https://docs.twenty.com/es/ui/theming.md) y [DirectionProvider](https://docs.twenty.com/es/ui/primitives/layout/direction-provider.md).

Personalice `Backdrop` y `Viewport` mediante sus propias props. Sus atributos nativos, controladores, refs y `render` se aplican a esos elementos independientemente de Popup. `forceRender` de Backdrop mantiene visible el fondo de un diálogo anidado cuando es necesario. El estado de apertura y transición de Base UI sigue estando disponible para estilos con reconocimiento de estado y callbacks de renderizado.

## Migración

Envuelva el contenido existente de `Dialog.Popup` en `Dialog.Portal` y `Dialog.Viewport`, y agregue un `Dialog.Backdrop` hermano dentro de Portal. Mueva `container` y `keepMounted` de Popup a Portal. Mueva las props anteriores de `backdrop` a Backdrop; sustituya `backdrop={false}` omitiendo Backdrop. Mueva `viewportProps` a Viewport, conservando `data-backdrop-hidden="true"` cuando el viewport deba permitir el paso de eventos de puntero externos. Mantenga `size`, `initialFocus`, `finalFocus`, los atributos nativos de popup y las refs de popup en Popup. Se eliminan las props de ensamblaje de Popup fusionadas.

Root, Trigger, Close, Title, Description, Header, Body, Footer y los handles existentes conservan sus funciones. Las props de partes públicas, los tipos de estado, acciones y detalles de eventos se exportan desde `twenty-ui/primitives/surfaces`.

## "Props"

### Dialog.Root

**Root.actionsRef** `RefObject\<DialogRootActions | null\>`

A ref to imperative actions.

* `unmount`: Ends the closing phase of the dialog after an externally controlled closing animation finishes.
  Call `preventUnmountOnClose()` in `onOpenChange` first, otherwise the dialog completes closing on its own.
  Whether it leaves the DOM is decided by `keepMounted` on the portal.
* `close`: Closes the dialog imperatively when called.

**Root.children** `ReactNode | PayloadChildRenderFunction\<Payload\>`

Parts or a render function receiving the active trigger payload. Root renders no DOM node.

**Root.defaultOpen** `boolean` (default: false)

Whether the dialog is initially open.

To render a controlled dialog, use the `open` prop instead.

**Root.defaultTriggerId** `string | null`

ID of the trigger that the dialog is associated with.
This is useful in conjunction with the `defaultOpen` prop to create an initially open dialog.

**Root.disablePointerDismissal** `boolean` (default: false)

Whether to prevent the dialog from closing on outside presses.
For non-modal dialogs, this also prevents the dialog from closing when focus moves outside of it.

**Root.handle** `DialogHandle\<Payload\>`

Connects detached triggers and imperative dialog actions.

**Root.modal** `boolean | "trap-focus"` (default: true)

Determines if the dialog enters a modal state when open.

* `true`: user interaction is limited to just the dialog: focus is trapped, document page scroll is locked, and pointer interactions on outside elements are disabled.
* `false`: user interaction with the rest of the document is allowed.
* `'trap-focus'`: focus is trapped inside the dialog, but document page scroll is not locked and pointer interactions outside of it remain enabled.

When `modal` is `true` or `'trap-focus'`, render `<Dialog.Close>` inside `<Dialog.Popup>` so
touch screen readers can escape the popup.

**Root.onOpenChange** `((open: boolean, eventDetails: DialogRootChangeEventDetails) =\> void)`

Receives the requested state and Base UI event details, including reason, event, trigger and cancel().

**Root.onOpenChangeComplete** `((open: boolean) =\> void)`

Event handler called after any animations complete when the dialog is opened or closed.

**Root.open** `boolean`

Whether the dialog is currently open.

**Root.triggerId** `string | null`

ID of the trigger that the dialog is associated with.
This is useful in conjunction with the `open` prop to create a controlled dialog.
There's no need to specify this prop when the dialog is uncontrolled (that is, when the `open` prop is not set).

### Dialog.Trigger

**Trigger.className** `string | ((state: DialogTriggerState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Trigger.handle** `DialogHandle\<Payload\>`

A handle to associate the trigger with a dialog.
Can be created with the Dialog.createHandle() method.

**Trigger.id** `string`

ID of the trigger. In addition to being forwarded to the rendered element,
it is also used to specify the active trigger for the dialog in controlled mode (with the DialogRoot `triggerId` prop).

**Trigger.nativeButton** `boolean` (default: true)

Whether the component renders a native `<button>` element when replacing it
via the `render` prop.
Set to `false` if the rendered element is not a button (for example, `<div>`).

**Trigger.payload** `Payload`

A payload to pass to the dialog when it is opened.

**Trigger.ref** `((((instance: HTMLButtonElement | null) =\> void | (() =\> VoidOrUndefinedOnly)) | RefObject\<HTMLButtonElement | null\>) & (((instance: HTMLElement | null) =\> void | (() =\> VoidOrUndefinedOnly)) | RefObject\<...\>)) | null`

Ref to the trigger button, or the element supplied through render.

**Trigger.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, DialogTriggerState\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.

**Trigger.style** `CSSProperties | ((state: DialogTriggerState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Dialog.Portal

**Portal.className** `string | ((state: DialogPortalState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Portal.container** `HTMLElement | ShadowRoot | RefObject\<HTMLElement | ShadowRoot | null\> | null`

Portal destination. Omit to use the nearest theme scope, then the parent portal or document body. Explicit null defers mounting; an element, ShadowRoot or ref keeps Base UI resolution.

**Portal.keepMounted** `boolean` (default: false)

Keeps the portal and its content mounted while closed.

**Portal.ref** `Ref\<HTMLDivElement\>`

Ref to the portal div, or the element supplied through render.

**Portal.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, DialogPortalState\>`

Composes the portal element. Native props and handlers target it.

**Portal.style** `CSSProperties | ((state: DialogPortalState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Dialog.Backdrop

**Backdrop.className** `string | ((state: DialogBackdropState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Backdrop.forceRender** `boolean` (default: false)

Renders the backdrop even when this dialog is nested.

**Backdrop.ref** `Ref\<HTMLDivElement\>`

Ref to the backdrop div, or the element supplied through render.

**Backdrop.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, DialogBackdropState\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.

**Backdrop.style** `CSSProperties | ((state: DialogBackdropState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Dialog.Viewport

**Viewport.children** `ReactNode`

Popup and any other content within the positioning viewport.

**Viewport.className** `string | ((state: DialogViewportState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Viewport.ref** `Ref\<HTMLDivElement\>`

Ref to the viewport div, or the element supplied through render.

**Viewport.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, DialogViewportState\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.

**Viewport.style** `CSSProperties | ((state: DialogViewportState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Dialog.Popup

**Popup.children** `ReactNode`

Dialog content. Compose inside Viewport and Portal; Popup does not create those parts or a Backdrop.

**Popup.className** `string | ((state: DialogPopupState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Popup.finalFocus** `boolean | RefObject\<HTMLElement | null\> | ((closeType: InteractionType) =\> boolean | void | HTMLElement | null)`

Controls focus restoration on closing. Accepts a boolean, element ref or callback receiving the interaction type.

**Popup.initialFocus** `boolean | RefObject\<HTMLElement | null\> | ((openType: InteractionType) =\> boolean | void | HTMLElement | null)`

Controls focus on opening. Accepts a boolean, element ref or callback receiving the interaction type.

**Popup.ref** `Ref\<HTMLDivElement\>`

Ref to the popup div, or the element supplied through render.

**Popup.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, DialogPopupState\>`

Composes the popup element while retaining native props, handlers, dialog semantics and focus behavior.

**Popup.size** `"compact" | "fullscreen" | "lg" | "md" | "sm" | "xl"` (default: md)

Width of the dialog, or `fullscreen` to fill the viewport.

**Popup.style** `CSSProperties | ((state: DialogPopupState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Dialog.Title

**Title.className** `string | ((state: DialogTitleState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Title.color** `"primary" | "secondary" | "tertiary"` (default: primary)

Theme font color. Defaults to `primary`.

**Title.level** `1 | 2 | 3 | 4 | 5 | 6` (default: 2)

Semantic heading level, from `h1` through `h6`. Does not change the visual size. Defaults to `2`.

**Title.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, DialogTitleState\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.

**Title.size** `"lg" | "md" | "sm" | "xl" | "xs" | "xxl"` (default: lg)

Visual font size, independent of the heading level. Defaults to `lg`.

**Title.style** `CSSProperties | ((state: DialogTitleState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Dialog.Description

**Description.className** `string | ((state: DialogDescriptionState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Description.ref** `Ref\<HTMLParagraphElement\>`

Ref to the description paragraph, or the element supplied through render.

**Description.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, DialogDescriptionState\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.

**Description.style** `CSSProperties | ((state: DialogDescriptionState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Dialog.Close

**Close.className** `string | ((state: DialogCloseState) =\> string | undefined)`

CSS class applied to the element, or a function that
returns a class based on the component's state.

**Close.nativeButton** `boolean` (default: true)

Whether the component renders a native `<button>` element when replacing it
via the `render` prop.
Set to `false` if the rendered element is not a button (for example, `<div>`).

**Close.ref** `Ref\<HTMLButtonElement\>`

Ref to the close button, or the element supplied through render.

**Close.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, DialogCloseState\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.

**Close.style** `CSSProperties | ((state: DialogCloseState) =\> CSSProperties | undefined)`

Style applied to the element, or a function that
returns a style object based on the component's state.

### Dialog.Header

**Header.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, \{\}\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.

### Dialog.Body

**Body.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, \{\}\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.

### Dialog.Footer

**Footer.render** `ReactElement\<unknown, string | JSXElementConstructor\<any\>\> | ComponentRenderFn\<HTMLProps, \{\}\>`

Allows you to replace the component's HTML element
with a different tag, or compose it with another component.

Accepts a `ReactElement` or a function that returns the element to render.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.