Ir para o conteúdo

Modal

Diálogo modal baseado no elemento dialog nativo.

Navegadores
Chrome 123+Firefox 121+Safari 17.5+
Nível
0
Tamanho compactado
944 B
Limite de layout forçado
0 ms
Limite do axe
0
Compatível com SSR
Sim
Construído sobre
elements/dialog
Contrato publicado
Ambiente de teste

Experimentar

Modal

Fechado

Controlado

O estado do componente pai controla este modal após a hidratação.

Alterações: 0, estado: fechado

Exemplos

Sizes

size writes data-size: sm 24rem, md (default) 28rem, lg 40rem, full fills the viewport. On a phone every size except full is a bottom sheet.

Small

24rem wide.

Large

40rem wide.

import { Modal } from "@gunkin/uiify";

export default function Example() {
  return (
    <>
      <Modal id="size-sm" size="sm" title="Small" trigger="Small">
        <p>24rem wide.</p>
      </Modal>
      <Modal id="size-lg" size="lg" title="Large" trigger="Large">
        <p>40rem wide.</p>
      </Modal>
    </>
  );
}

Long content

The title, content and footer share one scroll area. Compose the parts inside ModalBody for a document-style dialog.

Terms of service

The whole document scrolls together.

Clause 1: text that makes the document taller than the screen.

Clause 2: text that makes the document taller than the screen.

Clause 3: text that makes the document taller than the screen.

Clause 4: text that makes the document taller than the screen.

Clause 5: text that makes the document taller than the screen.

Clause 6: text that makes the document taller than the screen.

Clause 7: text that makes the document taller than the screen.

Clause 8: text that makes the document taller than the screen.

Clause 9: text that makes the document taller than the screen.

Clause 10: text that makes the document taller than the screen.

Clause 11: text that makes the document taller than the screen.

Clause 12: text that makes the document taller than the screen.

Clause 13: text that makes the document taller than the screen.

Clause 14: text that makes the document taller than the screen.

Clause 15: text that makes the document taller than the screen.

Clause 16: text that makes the document taller than the screen.

Clause 17: text that makes the document taller than the screen.

Clause 18: text that makes the document taller than the screen.

Clause 19: text that makes the document taller than the screen.

Clause 20: text that makes the document taller than the screen.

Clause 21: text that makes the document taller than the screen.

Clause 22: text that makes the document taller than the screen.

Clause 23: text that makes the document taller than the screen.

Clause 24: text that makes the document taller than the screen.

Clause 25: text that makes the document taller than the screen.

Clause 26: text that makes the document taller than the screen.

Clause 27: text that makes the document taller than the screen.

Clause 28: text that makes the document taller than the screen.

Clause 29: text that makes the document taller than the screen.

Clause 30: text that makes the document taller than the screen.

import { ModalTrigger, ModalContent, ModalBody, ModalHeader, ModalTitle, ModalClose, ModalFooter } from "@gunkin/uiify";
export default function Example() {
  return <>
    <ModalTrigger target="terms">Read terms</ModalTrigger>
    <ModalContent id="terms" aria-labelledby="terms-title">
      <ModalBody>
        <ModalHeader><ModalTitle id="terms-title">Terms of service</ModalTitle><ModalClose aria-label="Close" target="terms">×</ModalClose></ModalHeader>
        {Array.from({ length: 30 }, (_, index) => <p key={index}>Clause {index + 1}: text that makes the document taller than the screen.</p>)}
        <ModalFooter><ModalClose target="terms">Done</ModalClose></ModalFooter>
      </ModalBody>
    </ModalContent>
  </>;
}

Opening a modal from a modal

Render the child Modal inside the parent. It opens on top, Escape closes only the child, focus returns to the button that opened it, and the page is dimmed once.

Edit profile

Unsaved changes are lost when you close.

Discard changes?

This cannot be undone.

import { Modal, ModalClose } from "@gunkin/uiify";

export default function Example() {
  return (
    <Modal
      id="editor"
      trigger="Edit profile"
      title="Edit profile"
      description="Unsaved changes are lost when you close."
    >
      <Modal
        id="discard"
        trigger="Discard changes"
        title="Discard changes?"
        description="This cannot be undone."
        footer={<ModalClose target="discard">Keep editing</ModalClose>}
      />
    </Modal>
  );
}

API

Modal

ModalTrigger

PropTipoPadrãoDescrição
target*string—Id do ModalContent aberto por este botão; o navegador o resolve no clique, sem executar JavaScript nosso.
childrenReactNode—Conteúdo do botão acionador.
asTAs & NativeButtonAs<TAs>"button"Componente que encaminha props e ref a um botão nativo; outras tags são rejeitadas, pois comandos de invocador exigem um botão real.

ModalContent

PropTipoPadrãoDescrição
id*string—Id único fornecido pelo consumidor; referenciado pelo acionador e pelo destino de fechamento.
size"sm" | "md" | "lg" | "full""md"Faixa de largura (24, 28, 40rem). full preenche a área visível. Gravada em data-size; substitua --uiify-modal-inline-size para uma largura personalizada.
align"center" | "start""center"Posição vertical em tablets e computadores. Celulares recebem um painel inferior, salvo quando size é full.
dismiss"any" | "closerequest" | "none""any"closedby: any acrescenta toques no fundo, closerequest permite apenas Escape e none permite apenas seus controles. Safari não oferece closedby, então Escape sempre fecha; UIEnhance trata toques no fundo (any) e gestos no painel (exceto none).
backdrop"opaque" | "blur" | "none""opaque"Tratamento do fundo. Gravado em data-backdrop.
childrenReactNode—Conteúdo do diálogo.

ModalClose

PropTipoPadrãoDescrição
target*string—Id do ModalContent fechado por este botão.
childrenReactNode—Conteúdo do botão de fechar.
asTAs & NativeButtonAs<TAs>"button"Componente que encaminha props e ref a um botão nativo; outras tags são rejeitadas, pois comandos de invocador exigem um botão real.

ModalHeader

PropTipoPadrãoDescrição
childrenReactNode—Linha superior fixa com título, descrição e controle de fechamento.

ModalTitle

PropTipoPadrãoDescrição
childrenReactNode—O nome acessível do diálogo; referencie seu id em aria-labelledby.

ModalDescription

PropTipoPadrãoDescrição
childrenReactNode—Texto de apoio; referencie seu id em aria-describedby.

ModalBody

PropTipoPadrãoDescrição
childrenReactNode—A região de rolagem entre cabeçalho e rodapé.

ModalFooter

PropTipoPadrãoDescrição
childrenReactNode—Linha de ações fixada abaixo do corpo.

ModalGrabber

PropTipoPadrãoDescrição
childrenReactNode—Alça de arraste decorativa no painel móvel; o gesto começa aqui.

ModalClientContent (@gunkin/uiify/components/modal/client)

PropTipoPadrãoDescrição
id*string—Id único fornecido pelo consumidor; referenciado pelo acionador e pelo controle de fechamento.
openboolean—Estado de abertura controlado, que prevalece após a hidratação.
defaultOpenboolean—Estado inicial não controlado, aplicado com showModal() após a hidratação; a marcação do servidor permanece fechada.
onOpenChange(open: boolean) => void—Dispara uma vez por alteração nativa ou programática com o novo estado, inclusive uma vez na montagem se o navegador tiver aberto o diálogo antes da hidratação.
onOpenChangeComplete(open: boolean) => void—Dispara uma vez por transição de abertura ou fechamento após o fim das transições CSS, ou imediatamente quando não há transições, incluindo a transição de defaultOpen após a hidratação; nunca quando o diálogo não muda.
size"sm" | "md" | "lg" | "full""md"Faixa de largura (24, 28, 40rem). full preenche a área visível. Gravada em data-size; substitua --uiify-modal-inline-size para uma largura personalizada.
align"center" | "start""center"Posição vertical em tablets e computadores. Celulares recebem um painel inferior, salvo quando size é full.
dismiss"any" | "closerequest" | "none""any"closedby: any acrescenta toques no fundo, closerequest permite apenas Escape e none permite apenas seus controles. Safari não oferece closedby, então Escape sempre fecha; UIEnhance trata toques no fundo (any) e gestos no painel (exceto none).
backdrop"opaque" | "blur" | "none""opaque"Tratamento do fundo. Gravado em data-backdrop.
childrenReactNode—Conteúdo do diálogo.

Teclado

TeclaAção
EscapeFeche (apenas o modal superior quando houver aninhamento)
TabPercorra o foco dentro do modal
Shift+TabInverta a ordem de tabulação

Acessibilidade

<dialog> nativo aberto por um invocador command="show-modal" antes de qualquer JavaScript. O navegador controla modalidade, contenção de foco, Escape e retorno de foco; o fechamento usa request-close para permitir veto por onCancel. O ícone de fechar no cabeçalho está sempre presente. Em celulares, o modal é um painel inferior; deslizar para baixo e tocar no fundo são atalhos, nunca as únicas formas de sair.

Pontos de integração de estilos

data-uiify-modaldata-part="trigger|content|header|title|description|body|footer|grabber|close"data-size="sm|lg|full"data-align="start"data-backdrop="blur|none"--uiify-trigger-open (inside [data-uiify-modal][data-part="root"])--uiify-modal-inline-size (dialog width)