Skip to content

ComponentsFeedback

SourceSource

Modal

A Discord-inspired centred dialog in three sizes, with a fixed header and footer around a body that scrolls, that closes on Escape, an overlay press or an explicit close control.

A centred dialog with a header, a body and a footer, built on Radix Dialog in React and Reka UI Dialog in Vue. The primitive owns the behaviour; newt/ui owns the look. It is the settings-panel shape from the client, so a form inside it looks like it belongs there.

The panel floats on --newt-bg-floating with a 1px --newt-border-subtle edge, a --newt-radius-lg corner and the high elevation shadow. The header, the body and the footer share a 24px inset. The header and the footer keep their size; when the panel reaches the viewport height, less a 24px margin, the body scrolls. The panel fades and scales up from 0.95 when it opens, in --newt-duration-slow with --newt-ease-overlay, and plays that backwards in --newt-duration-fast when it closes. The overlay fades with it.

Root class newt-modal
import { Button } from "@/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
} from "@/registry/bases/newt/ui/modal"

export default function ModalDemo() {
  return (
    <Modal>
      <ModalTrigger asChild>
        <Button variant="primary">Open modal</Button>
      </ModalTrigger>
      <ModalContent aria-describedby={undefined}>
        <ModalHeader>
          <ModalTitle>Modal title</ModalTitle>
        </ModalHeader>
        <ModalBody>Modal body content goes here.</ModalBody>
        <ModalFooter>
          <ModalClose asChild>
            <Button variant="secondary">Cancel</Button>
          </ModalClose>
          <ModalClose asChild>
            <Button variant="danger">Confirm</Button>
          </ModalClose>
        </ModalFooter>
      </ModalContent>
    </Modal>
  )
}
<script setup lang="ts">
import { Button } from "~~/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
} from "~~/registry/bases/newt/ui/modal"
</script>

<template>
  <Modal>
    <ModalTrigger as-child>
      <Button variant="primary">Open modal</Button>
    </ModalTrigger>
    <ModalContent :aria-describedby="undefined">
      <ModalHeader>
        <ModalTitle>Modal title</ModalTitle>
      </ModalHeader>
      <ModalBody>Modal body content goes here.</ModalBody>
      <ModalFooter>
        <ModalClose as-child>
          <Button variant="secondary">Cancel</Button>
        </ModalClose>
        <ModalClose as-child>
          <Button variant="danger">Confirm</Button>
        </ModalClose>
      </ModalFooter>
    </ModalContent>
  </Modal>
</template>

Installation

npx newtui@latest add modalnpx shadcn@latest add @newtui/modalnpx shadcn-vue@latest add @newtui/modalpnpm dlx newtui@latest add modalpnpm dlx shadcn@latest add @newtui/modalpnpm dlx shadcn-vue@latest add @newtui/modalyarn dlx newtui@latest add modalyarn dlx shadcn@latest add @newtui/modalyarn dlx shadcn-vue@latest add @newtui/modalbunx newtui@latest add modalbunx shadcn@latest add @newtui/modalbunx shadcn-vue@latest add @newtui/modaldeno run -A npm:newtui@latest add modaldeno run -A npm:shadcn@latest add @newtui/modaldeno run -A npm:shadcn-vue@latest add @newtui/modalvlx newtui@latest add modalvlx shadcn@latest add @newtui/modalvlx shadcn-vue@latest add @newtui/modalvp dlx newtui@latest add modalvp dlx shadcn@latest add @newtui/modalvp dlx shadcn-vue@latest add @newtui/modalnubx newtui@latest add modalnubx shadcn@latest add @newtui/modalnubx shadcn-vue@latest add @newtui/modalnlx newtui@latest add modalnlx shadcn@latest add @newtui/modalnlx shadcn-vue@latest add @newtui/modalupx newtui@latest add modalupx shadcn@latest add @newtui/modalupx shadcn-vue@latest add @newtui/modal

The shadcn CLI needs the @newtui registry in your components.json. Set it up.

Install the dependencies

npm install radix-ui class-variance-authoritypnpm add radix-ui class-variance-authorityyarn add radix-ui class-variance-authoritybun add radix-ui class-variance-authoritydeno add npm:radix-ui npm:class-variance-authorityvlt install radix-ui class-variance-authorityvp add radix-ui class-variance-authoritynub add radix-ui class-variance-authorityni radix-ui class-variance-authorityupm add radix-ui class-variance-authority
npm install reka-ui class-variance-authoritypnpm add reka-ui class-variance-authorityyarn add reka-ui class-variance-authoritybun add reka-ui class-variance-authoritydeno add npm:reka-ui npm:class-variance-authorityvlt install reka-ui class-variance-authorityvp add reka-ui class-variance-authoritynub add reka-ui class-variance-authorityni reka-ui class-variance-authorityupm add reka-ui class-variance-authority

Add the components it builds on

Copy the source into your project

"use client"

import { cva, type VariantProps } from "class-variance-authority"
import { Dialog as DialogPrimitive } from "radix-ui"
import * as React from "react"

import { cn } from "@/lib/utils"

/*
 * Radix owns the behaviour: open state, the focus trap, Escape and outside
 * press, scroll lock, hiding the page from screen readers, and giving focus
 * back to the trigger. Only the look is newt/ui's.
 */
const Modal = DialogPrimitive.Root

/*
 * It has no look of its own. Pass `asChild` to put the state on your own
 * button: `<ModalTrigger asChild><Button>Open</Button></ModalTrigger>`.
 * Focus returns to the trigger when the modal closes. A modal opened from
 * state alone has no trigger, so pass `onCloseAutoFocus` to `ModalContent`
 * to say where focus goes.
 */
const ModalTrigger = DialogPrimitive.Trigger

/**
 * Closes the modal when activated. Wrap a Button with `asChild` to keep its styling:
 * `<ModalClose asChild><Button variant="secondary">Cancel</Button></ModalClose>`
 */
const ModalClose = DialogPrimitive.Close

/*
 * The panel is centred with `inset-0` and `m-auto`, not with a transform, so
 * the open and close animations can scale it freely. It keeps a 24px margin to
 * the viewport and never grows past its height: `ModalBody` scrolls instead.
 * A `<form>` child is `display: contents`, so a form around the body and the
 * footer changes nothing. Another wrapper keeps the body from shrinking; then
 * the whole panel scrolls, and nothing is cut off.
 * Opening fades and scales up from 0.95 in `--newt-duration-slow`; closing
 * plays it backwards in `--newt-duration-fast`, and the primitive keeps the
 * panel mounted until the animation ends. Reduced motion turns both off.
 */
const modalContentVariants = cva(
  "fixed inset-0 z-[100] m-auto box-border flex h-fit w-[calc(100%-2*var(--newt-space-6))] flex-col overflow-y-auto overflow-x-hidden rounded-[var(--newt-radius-lg)] pb-[var(--newt-space-4)] border border-solid border-newt-border-subtle bg-newt-bg-floating text-newt-text-secondary shadow-elevation-high outline-none [&>form]:contents data-[state=open]:animate-[newt-modal-in_var(--newt-duration-slow)_var(--newt-ease-overlay)] data-[state=closed]:animate-[newt-modal-out_var(--newt-duration-fast)_var(--newt-ease-overlay)_forwards] motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none",
  {
    variants: {
      /* Each width is a maximum; a narrower viewport gets a narrower panel. */
      size: {
        sm: "max-h-[min(720px,calc(100%-2*var(--newt-space-6)))] max-w-[400px]",
        md: "max-h-[min(800px,calc(100%-2*var(--newt-space-6)))] max-w-[480px]",
        lg: "max-h-[calc(100%-2*var(--newt-space-6))] max-w-[680px]",
      },
    },
    defaultVariants: { size: "md" },
  }
)

type ModalSize = NonNullable<VariantProps<typeof modalContentVariants>["size"]>

const overlayClassName =
  "fixed inset-0 z-[100] bg-newt-overlay data-[state=open]:animate-[newt-modal-overlay-in_var(--newt-duration-slow)_var(--newt-ease-overlay)] data-[state=closed]:animate-[newt-modal-overlay-out_var(--newt-duration-fast)_var(--newt-ease-overlay)_forwards] motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none"

/* `scale` leaves `transform` free for a caller that positions the panel. */
const keyframes = `
@keyframes newt-modal-in { from { opacity: 0; scale: 0.95; } }
@keyframes newt-modal-out { to { opacity: 0; scale: 0.95; } }
@keyframes newt-modal-overlay-in { from { opacity: 0; } }
@keyframes newt-modal-overlay-out { to { opacity: 0; } }`

type ModalContentProps = React.ComponentPropsWithoutRef<
  typeof DialogPrimitive.Content
> & {
  /**
   * The panel's maximum width: `sm` 400px, `md` 480px, `lg` 680px.
   * @default "md"
   */
  size?: ModalSize
  /**
   * The element the overlay and panel are portalled into. Defaults to
   * `document.body`. A modal opened below a `DirectionProvider` or a themed
   * wrapper passes that element, so it keeps the direction and the palette.
   */
  container?: React.ComponentProps<typeof DialogPrimitive.Portal>["container"]
}

const ModalContent = React.forwardRef<
  React.ComponentRef<typeof DialogPrimitive.Content>,
  ModalContentProps
>(({ className, children, container, size = "md", ...props }, ref) => (
  <DialogPrimitive.Portal container={container}>
    <style>{keyframes}</style>
    <DialogPrimitive.Overlay className={overlayClassName} />
    <DialogPrimitive.Content
      ref={ref}
      data-size={size}
      className={cn(modalContentVariants({ size }), className)}
      {...props}
    >
      {children}
    </DialogPrimitive.Content>
  </DialogPrimitive.Portal>
))
ModalContent.displayName = "ModalContent"

const ModalHeader = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<"div">
>(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn(
      "flex shrink-0 flex-col gap-[var(--newt-space-2)] break-words px-[var(--newt-space-6)] pb-[var(--newt-space-2)] pt-[var(--newt-space-6)]",
      className
    )}
    {...props}
  />
))
ModalHeader.displayName = "ModalHeader"

/** The dialog's accessible name. Give it real text. */
const ModalTitle = React.forwardRef<
  React.ComponentRef<typeof DialogPrimitive.Title>,
  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
  <DialogPrimitive.Title
    ref={ref}
    className={cn(
      "m-0 text-[length:var(--newt-font-size-lg)] font-[number:var(--newt-font-weight-semibold)] leading-[var(--newt-line-height-tight)] text-newt-text-primary",
      className
    )}
    {...props}
  />
))
ModalTitle.displayName = "ModalTitle"

/**
 * Radix links it to the dialog with `aria-describedby`. A modal without one
 * passes `aria-describedby={undefined}` to `ModalContent` to say so.
 */
const ModalDescription = React.forwardRef<
  React.ComponentRef<typeof DialogPrimitive.Description>,
  React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
  <DialogPrimitive.Description
    ref={ref}
    className={cn(
      "m-0 text-[length:var(--newt-font-size-md)] font-[number:var(--newt-font-weight-normal)] leading-[var(--newt-line-height-tight)] text-newt-text-secondary",
      className
    )}
    {...props}
  />
))
ModalDescription.displayName = "ModalDescription"

/*
 * The part that scrolls when the panel reaches the viewport height. The header
 * and the footer keep their size. A form that wraps the body and the footer
 * needs nothing: a form child of the panel is `display: contents`.
 */
const ModalBody = React.forwardRef<HTMLDivElement, React.ComponentProps<"div">>(
  ({ className, ...props }, ref) => (
    <div
      ref={ref}
      className={cn(
        "min-h-0 flex-[0_1_auto] overflow-y-auto overscroll-contain break-words px-[var(--newt-space-6)] pb-[var(--newt-space-2)] pt-[var(--newt-space-4)] text-[length:var(--newt-font-size-md)] leading-[var(--newt-line-height-tight)] text-newt-text-secondary",
        className
      )}
      {...props}
    />
  )
)
ModalBody.displayName = "ModalBody"

const ModalFooter = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<"div">
>(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn(
      "flex shrink-0 flex-wrap justify-end gap-[var(--newt-space-2)] px-[var(--newt-space-6)] pb-0 pt-[var(--newt-space-4)]",
      className
    )}
    {...props}
  />
))
ModalFooter.displayName = "ModalFooter"

export {
  Modal,
  ModalTrigger,
  ModalContent,
  ModalHeader,
  ModalTitle,
  ModalDescription,
  ModalBody,
  ModalFooter,
  ModalClose,
  modalContentVariants,
}
export type { ModalContentProps, ModalSize }
<script setup lang="ts">
import {
  DialogRoot,
  useForwardPropsEmits,
  type DialogRootEmits,
  type DialogRootProps,
} from "reka-ui"

/*
 * Reka owns the behaviour: open state, the focus trap, Escape and outside
 * press, scroll lock, hiding the page from screen readers, and giving focus
 * back to the trigger. Use `v-model:open` to control it. Only the look is
 * newt/ui's.
 */
const props = defineProps<DialogRootProps>()
const emits = defineEmits<DialogRootEmits>()

const forwarded = useForwardPropsEmits(props, emits)
</script>

<template>
  <DialogRoot v-bind="forwarded">
    <slot />
  </DialogRoot>
</template>
<script setup lang="ts">
import { DialogTrigger, type DialogTriggerProps } from "reka-ui"

/*
 * It has no look of its own. Pass `as-child` to put the state on your own
 * button: `<ModalTrigger as-child><Button>Open</Button></ModalTrigger>`.
 * Focus returns to the trigger when the modal closes. A modal opened from
 * state alone has no trigger, so handle `@close-auto-focus` on `ModalContent`
 * to say where focus goes.
 */
const props = defineProps<DialogTriggerProps>()
</script>

<template>
  <DialogTrigger v-bind="props">
    <slot />
  </DialogTrigger>
</template>
<script setup lang="ts">
import {
  DialogContent,
  DialogOverlay,
  DialogPortal,
  useForwardPropsEmits,
  type DialogContentEmits,
  type DialogContentProps,
} from "reka-ui"
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

import { type ModalSize, modalContentVariants } from "."

defineOptions({ inheritAttrs: false })

const {
  class: className,
  container,
  size = "md",
  ...delegated
} = defineProps<
  DialogContentProps & {
    class?: HTMLAttributes["class"]
    /**
     * The element the overlay and panel are portalled into. Defaults to
     * `body`. A modal opened below a `DirectionProvider` or a themed wrapper
     * passes that element, so it keeps the direction and the palette.
     */
    container?: string | HTMLElement
    /** The panel's maximum width: `sm` 400px, `md` 480px, `lg` 680px. */
    size?: ModalSize
  }
>()
const emits = defineEmits<DialogContentEmits>()

const forwarded = useForwardPropsEmits(delegated, emits)

const overlayClass =
  "fixed inset-0 z-[100] bg-newt-overlay data-[state=open]:animate-[newt-modal-overlay-in_var(--newt-duration-slow)_var(--newt-ease-overlay)] data-[state=closed]:animate-[newt-modal-overlay-out_var(--newt-duration-fast)_var(--newt-ease-overlay)_forwards] motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none"
</script>

<template>
  <DialogPortal :to="container">
    <DialogOverlay :class="overlayClass" />
    <DialogContent
      v-bind="{ ...forwarded, ...$attrs }"
      :data-size="size"
      :class="cn(modalContentVariants({ size }), className)"
    >
      <slot />
    </DialogContent>
  </DialogPortal>
</template>

<style>
/* `scale` leaves `transform` free for a caller that positions the panel. */
@keyframes newt-modal-in {
  from {
    opacity: 0;
    scale: 0.95;
  }
}
@keyframes newt-modal-out {
  to {
    opacity: 0;
    scale: 0.95;
  }
}
@keyframes newt-modal-overlay-in {
  from {
    opacity: 0;
  }
}
@keyframes newt-modal-overlay-out {
  to {
    opacity: 0;
  }
}
</style>
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

const props = defineProps<{
  class?: HTMLAttributes["class"]
}>()
</script>

<template>
  <div
    :class="
      cn(
        'flex shrink-0 flex-col gap-[var(--newt-space-2)] break-words px-[var(--newt-space-6)] pb-[var(--newt-space-2)] pt-[var(--newt-space-6)]',
        props.class
      )
    "
  >
    <slot />
  </div>
</template>
<script setup lang="ts">
import { DialogTitle, type DialogTitleProps } from "reka-ui"
import { computed, type HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

/* The dialog's accessible name. Give it real text. */
const props = defineProps<
  DialogTitleProps & { class?: HTMLAttributes["class"] }
>()

const delegated = computed(() => {
  const { class: _class, ...rest } = props
  return rest
})
</script>

<template>
  <DialogTitle
    v-bind="delegated"
    :class="
      cn(
        'm-0 text-[length:var(--newt-font-size-lg)] font-[number:var(--newt-font-weight-semibold)] leading-[var(--newt-line-height-tight)] text-newt-text-primary',
        props.class
      )
    "
  >
    <slot />
  </DialogTitle>
</template>
<script setup lang="ts">
import { DialogDescription, type DialogDescriptionProps } from "reka-ui"
import { computed, type HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

/*
 * Reka links it to the dialog with `aria-describedby`. A modal without one
 * passes `:aria-describedby="undefined"` to `ModalContent` to say so.
 */
const props = defineProps<
  DialogDescriptionProps & { class?: HTMLAttributes["class"] }
>()

const delegated = computed(() => {
  const { class: _class, ...rest } = props
  return rest
})
</script>

<template>
  <DialogDescription
    v-bind="delegated"
    :class="
      cn(
        'm-0 text-[length:var(--newt-font-size-md)] font-[number:var(--newt-font-weight-normal)] leading-[var(--newt-line-height-tight)] text-newt-text-secondary',
        props.class
      )
    "
  >
    <slot />
  </DialogDescription>
</template>
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

/*
 * The part that scrolls when the panel reaches the viewport height. The header
 * and the footer keep their size. A form that wraps the body and the footer
 * needs nothing: a form child of the panel is `display: contents`.
 */

const props = defineProps<{
  class?: HTMLAttributes["class"]
}>()
</script>

<template>
  <div
    :class="
      cn(
        'min-h-0 flex-[0_1_auto] overflow-y-auto overscroll-contain break-words px-[var(--newt-space-6)] pb-[var(--newt-space-2)] pt-[var(--newt-space-4)] text-[length:var(--newt-font-size-md)] leading-[var(--newt-line-height-tight)] text-newt-text-secondary',
        props.class
      )
    "
  >
    <slot />
  </div>
</template>
<script setup lang="ts">
import type { HTMLAttributes } from "vue"

import { cn } from "@/lib/utils"

const props = defineProps<{
  class?: HTMLAttributes["class"]
}>()
</script>

<template>
  <div
    :class="
      cn(
        'flex shrink-0 flex-wrap justify-end gap-[var(--newt-space-2)] px-[var(--newt-space-6)] pb-0 pt-[var(--newt-space-4)]',
        props.class
      )
    "
  >
    <slot />
  </div>
</template>
<script setup lang="ts">
import { DialogClose, type DialogCloseProps } from "reka-ui"

/*
 * Closes the modal when activated. Wrap a Button with `as-child` to keep its
 * styling: `<ModalClose as-child><Button variant="secondary">Cancel</Button></ModalClose>`
 */
const props = defineProps<DialogCloseProps>()
</script>

<template>
  <DialogClose v-bind="props">
    <slot />
  </DialogClose>
</template>
import { cva, type VariantProps } from "class-variance-authority"

export { default as Modal } from "./Modal.vue"
export { default as ModalTrigger } from "./ModalTrigger.vue"
export { default as ModalContent } from "./ModalContent.vue"
export { default as ModalHeader } from "./ModalHeader.vue"
export { default as ModalTitle } from "./ModalTitle.vue"
export { default as ModalDescription } from "./ModalDescription.vue"
export { default as ModalBody } from "./ModalBody.vue"
export { default as ModalFooter } from "./ModalFooter.vue"
export { default as ModalClose } from "./ModalClose.vue"

/*
 * The panel is centred with `inset-0` and `m-auto`, not with a transform, so
 * the open and close animations can scale it freely. It keeps a 24px margin to
 * the viewport and never grows past its height: `ModalBody` scrolls instead.
 * A `<form>` child is `display: contents`, so a form around the body and the
 * footer changes nothing. Another wrapper keeps the body from shrinking; then
 * the whole panel scrolls, and nothing is cut off.
 * Opening fades and scales up from 0.95 in `--newt-duration-slow`; closing
 * plays it backwards in `--newt-duration-fast`, and the primitive keeps the
 * panel mounted until the animation ends. Reduced motion turns both off.
 */
export const modalContentVariants = cva(
  "fixed inset-0 z-[100] m-auto box-border flex h-fit w-[calc(100%-2*var(--newt-space-6))] flex-col overflow-y-auto overflow-x-hidden rounded-[var(--newt-radius-lg)] pb-[var(--newt-space-4)] border border-solid border-newt-border-subtle bg-newt-bg-floating text-newt-text-secondary shadow-elevation-high outline-none [&>form]:contents data-[state=open]:animate-[newt-modal-in_var(--newt-duration-slow)_var(--newt-ease-overlay)] data-[state=closed]:animate-[newt-modal-out_var(--newt-duration-fast)_var(--newt-ease-overlay)_forwards] motion-reduce:data-[state=open]:animate-none motion-reduce:data-[state=closed]:animate-none",
  {
    variants: {
      /* Each width is a maximum; a narrower viewport gets a narrower panel. */
      size: {
        sm: "max-h-[min(720px,calc(100%-2*var(--newt-space-6)))] max-w-[400px]",
        md: "max-h-[min(800px,calc(100%-2*var(--newt-space-6)))] max-w-[480px]",
        lg: "max-h-[calc(100%-2*var(--newt-space-6))] max-w-[680px]",
      },
    },
    defaultVariants: { size: "md" },
  }
)

export type ModalSize = NonNullable<
  VariantProps<typeof modalContentVariants>["size"]
>

Update the import paths

The files import @/lib/utils and sibling components through the aliases in your components.json. Point them at wherever those live in your project.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Modal to your React project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

No CLI, no components.json: paste this into Claude, Cursor, Copilot or any coding assistant and it adds Modal to your Vue project by hand. The prompt carries the source of every file the CLI would write — this component's and those of the components it builds on — with the imports already pointed at the default aliases.

Usage

import { Modal } from "@/components/ui/modal"

export function Example() {
  return <Modal />
}
<script setup lang="ts">
import { Modal, ModalTrigger, ModalContent, ModalHeader, ModalTitle, ModalDescription, ModalBody, ModalFooter, ModalClose } from "@/components/ui/modal"
</script>

<template>
  <Modal />
</template>

Examples

Sizes

size on ModalContent sets the panel’s maximum width: sm is 400px, md 480px and lg 680px. md is the default. On a screen narrower than the size, the panel fills the viewport less a 24px margin.

Root class newt-modal
import { Button } from "@/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
  type ModalSize,
} from "@/registry/bases/newt/ui/modal"

const SIZES: readonly { size: ModalSize; width: string }[] = [
  { size: "sm", width: "400px" },
  { size: "md", width: "480px" },
  { size: "lg", width: "680px" },
]

/*
 * `size` sets the panel's maximum width. On a narrower screen every size fills
 * the viewport, less a 24px margin.
 */
export default function ModalSizesDemo() {
  return (
    <div className="flex flex-wrap gap-[var(--newt-space-2)]">
      {SIZES.map(({ size, width }) => (
        <Modal key={size}>
          <ModalTrigger asChild>
            <Button variant="secondary">Size {size}</Button>
          </ModalTrigger>
          <ModalContent size={size} aria-describedby={undefined}>
            <ModalHeader>
              <ModalTitle>Size {size}</ModalTitle>
            </ModalHeader>
            <ModalBody>This panel is at most {width} wide.</ModalBody>
            <ModalFooter>
              <ModalClose asChild>
                <Button variant="secondary">Close</Button>
              </ModalClose>
            </ModalFooter>
          </ModalContent>
        </Modal>
      ))}
    </div>
  )
}
<script setup lang="ts">
import { Button } from "~~/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
  type ModalSize,
} from "~~/registry/bases/newt/ui/modal"

/*
 * `size` sets the panel's maximum width. On a narrower screen every size fills
 * the viewport, less a 24px margin.
 */
const sizes: readonly { size: ModalSize; width: string }[] = [
  { size: "sm", width: "400px" },
  { size: "md", width: "480px" },
  { size: "lg", width: "680px" },
]
</script>

<template>
  <div class="flex flex-wrap gap-[var(--newt-space-2)]">
    <Modal v-for="{ size, width } in sizes" :key="size">
      <ModalTrigger as-child>
        <Button variant="secondary">Size {{ size }}</Button>
      </ModalTrigger>
      <ModalContent :size="size" :aria-describedby="undefined">
        <ModalHeader>
          <ModalTitle>Size {{ size }}</ModalTitle>
        </ModalHeader>
        <ModalBody>This panel is at most {{ width }} wide.</ModalBody>
        <ModalFooter>
          <ModalClose as-child>
            <Button variant="secondary">Close</Button>
          </ModalClose>
        </ModalFooter>
      </ModalContent>
    </Modal>
  </div>
</template>

With a form

Wrap the body and the footer in a form, so Enter in a field submits it. A form that is a direct child of ModalContent lays out as display: contents, so the body still scrolls and the footer stays in view; it needs no class. Another wrapper element keeps the body from shrinking: then the whole panel scrolls instead, and nothing is cut off. Give that wrapper contents to keep the header and the footer fixed. The field is the dialog’s first control, which is where focus lands when it opens; the submit button stays disabled until there is a name.

Root class newt-modal
"use client"

import * as React from "react"

import { Button } from "@/registry/bases/newt/ui/button"
import {
  Field,
  FieldHelp,
  Input,
  Label,
} from "@/registry/bases/newt/ui/form-fields"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
} from "@/registry/bases/newt/ui/modal"

/*
 * The form wraps the body and the footer, so Enter in the field submits it.
 * A form child of the panel lays out as `contents`, so the body still scrolls.
 * The field is the dialog's first control, which is where focus lands.
 */
export default function ModalFormDemo() {
  const [open, setOpen] = React.useState(false)
  const [name, setName] = React.useState("")

  return (
    <Modal open={open} onOpenChange={setOpen}>
      <ModalTrigger asChild>
        <Button variant="primary">Create channel</Button>
      </ModalTrigger>
      <ModalContent aria-describedby={undefined}>
        <ModalHeader>
          <ModalTitle>Create channel</ModalTitle>
        </ModalHeader>
        <form
          onSubmit={(e) => {
            e.preventDefault()
            setOpen(false)
            setName("")
          }}
        >
          <ModalBody>
            <Field>
              <Label htmlFor="modal-form-channel-name">Channel name</Label>
              <Input
                id="modal-form-channel-name"
                placeholder="new-channel"
                value={name}
                onChange={(e) => setName(e.target.value)}
              />
              <FieldHelp>Lowercase, with dashes instead of spaces.</FieldHelp>
            </Field>
          </ModalBody>
          <ModalFooter>
            <ModalClose asChild>
              <Button variant="secondary">Cancel</Button>
            </ModalClose>
            <Button type="submit" disabled={name.trim() === ""}>
              Create
            </Button>
          </ModalFooter>
        </form>
      </ModalContent>
    </Modal>
  )
}
<script setup lang="ts">
import { ref } from "vue"
import { Button } from "~~/registry/bases/newt/ui/button"
import {
  Field,
  FieldHelp,
  Input,
  Label,
} from "~~/registry/bases/newt/ui/form-fields"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
} from "~~/registry/bases/newt/ui/modal"

/*
 * The form wraps the body and the footer, so Enter in the field submits it.
 * A form child of the panel lays out as `contents`, so the body still scrolls.
 * The field is the dialog's first control, which is where focus lands.
 */
const open = ref(false)
const name = ref("")

function create() {
  open.value = false
  name.value = ""
}
</script>

<template>
  <Modal v-model:open="open">
    <ModalTrigger as-child>
      <Button variant="primary">Create channel</Button>
    </ModalTrigger>
    <ModalContent :aria-describedby="undefined">
      <ModalHeader>
        <ModalTitle>Create channel</ModalTitle>
      </ModalHeader>
      <form @submit.prevent="create">
        <ModalBody>
          <Field>
            <Label for="modal-form-channel-name">Channel name</Label>
            <Input
              id="modal-form-channel-name"
              v-model="name"
              placeholder="new-channel"
            />
            <FieldHelp>Lowercase, with dashes instead of spaces.</FieldHelp>
          </Field>
        </ModalBody>
        <ModalFooter>
          <ModalClose as-child>
            <Button variant="secondary">Cancel</Button>
          </ModalClose>
          <Button type="submit" :disabled="name.trim() === ''">Create</Button>
        </ModalFooter>
      </form>
    </ModalContent>
  </Modal>
</template>

Close button

A dialog that only informs needs no footer. Put one ModalClose around a secondary icon Button with an aria-label, and place it in the corner with absolute, outside ModalHeader, so its label does not become part of the dialog’s accessible name. Give the header end padding, so a long title does not run under it.

Root class newt-modal
import { Button } from "@/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalDescription,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
} from "@/registry/bases/newt/ui/modal"

/*
 * A dialog that only informs needs no footer: one `ModalClose` in the corner
 * is its way out, a secondary icon `Button`. It sits outside the header so
 * "Close" stays out of the dialog's accessible name. The body text is the
 * description, so a screen reader reads it after the title.
 */
export default function ModalCloseButtonDemo() {
  return (
    <Modal>
      <ModalTrigger asChild>
        <Button variant="secondary">What&apos;s new</Button>
      </ModalTrigger>
      <ModalContent>
        <ModalHeader className="pe-[calc(2*var(--newt-space-2)+var(--newt-control-sm))]">
          <ModalTitle>What&apos;s new</ModalTitle>
        </ModalHeader>
        <ModalBody>
          <ModalDescription>
            Threads now keep their place when you switch channels, and the
            member list remembers which roles you collapsed.
          </ModalDescription>
        </ModalBody>
        <ModalClose asChild>
          <Button
            variant="secondary"
            size="icon"
            aria-label="Close"
            className="absolute end-[var(--newt-space-2)] top-[var(--newt-space-3)]"
          >
            <svg
              viewBox="0 0 16 16"
              aria-hidden="true"
              className="size-[var(--newt-space-4)]"
            >
              <path
                fill="none"
                stroke="currentColor"
                strokeWidth="2"
                strokeLinecap="round"
                d="m4 4 8 8m0-8-8 8"
              />
            </svg>
          </Button>
        </ModalClose>
      </ModalContent>
    </Modal>
  )
}
<script setup lang="ts">
import { Button } from "~~/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalDescription,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
} from "~~/registry/bases/newt/ui/modal"

/*
 * A dialog that only informs needs no footer: one `ModalClose` in the corner
 * is its way out, a secondary icon `Button`. It sits outside the header so
 * "Close" stays out of the dialog's accessible name. The body text is the
 * description, so a screen reader reads it after the title.
 */
</script>

<template>
  <Modal>
    <ModalTrigger as-child>
      <Button variant="secondary">What's new</Button>
    </ModalTrigger>
    <ModalContent>
      <ModalHeader
        class="pe-[calc(2*var(--newt-space-2)+var(--newt-control-sm))]"
      >
        <ModalTitle>What's new</ModalTitle>
      </ModalHeader>
      <ModalBody>
        <ModalDescription>
          Threads now keep their place when you switch channels, and the member
          list remembers which roles you collapsed.
        </ModalDescription>
      </ModalBody>
      <ModalClose as-child>
        <Button
          variant="secondary"
          size="icon"
          aria-label="Close"
          class="absolute end-[var(--newt-space-2)] top-[var(--newt-space-3)]"
        >
          <svg
            viewBox="0 0 16 16"
            aria-hidden="true"
            class="size-[var(--newt-space-4)]"
          >
            <path
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              d="m4 4 8 8m0-8-8 8"
            />
          </svg>
        </Button>
      </ModalClose>
    </ModalContent>
  </Modal>
</template>

Long content

ModalBody scrolls on its own when the panel reaches the viewport height. The title and the actions stay in view. Add a max-h-* utility to the body to make it scroll sooner, as this example does.

Root class newt-modal
import { Button } from "@/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
} from "@/registry/bases/newt/ui/modal"

const RULES = [
  "Be kind. Disagree with the idea, not with the person.",
  "Keep each channel on its topic; off-topic talk goes in the lounge.",
  "No spam, self-promotion or unsolicited direct messages.",
  "Mark spoilers, and keep anything not safe for work out entirely.",
  "Do not share anyone's personal details, including your own.",
  "Use a thread for a long discussion so the channel stays readable.",
  "Listen to the moderators. Appeal a decision in private, not in public.",
  "Report a problem with the report action instead of answering it.",
]

/*
 * The body scrolls on its own: the title and the actions stay where they are
 * however long the text gets. The panel stops 24px short of the viewport, and
 * `max-h-48` caps the body earlier, so it scrolls on a tall screen too.
 */
export default function ModalLongContentDemo() {
  return (
    <Modal>
      <ModalTrigger asChild>
        <Button variant="secondary">Read the rules</Button>
      </ModalTrigger>
      <ModalContent aria-describedby={undefined}>
        <ModalHeader>
          <ModalTitle>Server rules</ModalTitle>
        </ModalHeader>
        <ModalBody className="max-h-48">
          <ol className="flex list-decimal flex-col gap-3 ps-5">
            {RULES.map((rule) => (
              <li key={rule}>{rule}</li>
            ))}
          </ol>
        </ModalBody>
        <ModalFooter>
          <ModalClose asChild>
            <Button variant="secondary">Not now</Button>
          </ModalClose>
          <ModalClose asChild>
            <Button>I agree</Button>
          </ModalClose>
        </ModalFooter>
      </ModalContent>
    </Modal>
  )
}
<script setup lang="ts">
import { Button } from "~~/registry/bases/newt/ui/button"
import {
  Modal,
  ModalBody,
  ModalClose,
  ModalContent,
  ModalFooter,
  ModalHeader,
  ModalTitle,
  ModalTrigger,
} from "~~/registry/bases/newt/ui/modal"

/*
 * The body scrolls on its own: the title and the actions stay where they are
 * however long the text gets. The panel stops 24px short of the viewport, and
 * `max-h-48` caps the body earlier, so it scrolls on a tall screen too.
 */
const rules = [
  "Be kind. Disagree with the idea, not with the person.",
  "Keep each channel on its topic; off-topic talk goes in the lounge.",
  "No spam, self-promotion or unsolicited direct messages.",
  "Mark spoilers, and keep anything not safe for work out entirely.",
  "Do not share anyone's personal details, including your own.",
  "Use a thread for a long discussion so the channel stays readable.",
  "Listen to the moderators. Appeal a decision in private, not in public.",
  "Report a problem with the report action instead of answering it.",
]
</script>

<template>
  <Modal>
    <ModalTrigger as-child>
      <Button variant="secondary">Read the rules</Button>
    </ModalTrigger>
    <ModalContent :aria-describedby="undefined">
      <ModalHeader>
        <ModalTitle>Server rules</ModalTitle>
      </ModalHeader>
      <ModalBody class="max-h-48">
        <ol class="flex list-decimal flex-col gap-3 ps-5">
          <li v-for="rule in rules" :key="rule">{{ rule }}</li>
        </ol>
      </ModalBody>
      <ModalFooter>
        <ModalClose as-child>
          <Button variant="secondary">Not now</Button>
        </ModalClose>
        <ModalClose as-child>
          <Button>I agree</Button>
        </ModalClose>
      </ModalFooter>
    </ModalContent>
  </Modal>
</template>

API reference

Modal

PropType
open / v-model:open?boolean

Whether the dialog is shown. Leave it out and pass `defaultOpen` to let the modal own it.

Typeboolean
onOpenChange?(open: boolean) => void

React only. Called when the dialog asks to open or close; Vue emits `update:open`.

Type(open: boolean) => void

ModalContent

PropType
size?"sm" | "md" | "lg"

The panel's maximum width: 400px, 480px or 680px. It is also set as `data-size`.

Type"sm" | "md" | "lg"
Default"md"
onCloseAutoFocus?(event: Event) => void

Called when focus is about to return to the trigger. Call `event.preventDefault()` and focus an element yourself when the modal opened without a `ModalTrigger`. Vue emits `close-auto-focus`.

Type(event: Event) => void
aria-describedby?string | undefined

Pass `undefined` when the modal has no `ModalDescription`.

Typestring | undefined
container?HTMLElement

Element the overlay and panel are portalled into. A modal below a `DirectionProvider` or a themed wrapper passes that element to keep the direction and the palette.

TypeHTMLElement
Defaultdocument.body

ModalFooter

PropType
children?ReactNode

Actions, laid out end-aligned. They wrap onto a second line when they do not fit.

TypeReactNode

ModalTrigger and ModalClose render a button. Pass asChild (as-child in Vue) to put the behaviour on your own element, such as a Button. Every part also accepts the native attributes of the element it renders, and a className that is merged rather than replaced.

Accessibility

The dialog carries role="dialog" and aria-modal="true", and closes on Escape. ModalTitle is its accessible name, so give it real text; ModalDescription is its accessible description. When it opens, focus moves to its first control, or to the dialog itself when it has none; a child with autoFocus keeps the focus it took. While it is open, Tab and Shift+Tab cycle through its controls and never reach the page behind, which the primitive also hides from screen readers and the overlay covers for the pointer. When it closes, focus goes back to the ModalTrigger.

The page behind cannot scroll while the dialog is open; the body of the dialog can. Under prefers-reduced-motion: reduce the dialog and the overlay appear and leave at once, with no fade or scale. The close control and the footer actions are Buttons, so they keep its --newt-focus-ring outline.

In the plain HTML and CSS distribution, modal.js gives an overlay marked data-newt-modal the same keyboard behaviour. .newt-modal--sm, --md and --lg set the size; .newt-modal alone is md. The overlay and the dialog carry data-state; when the modal closes, the script releases the keyboard, makes the overlay inert and returns focus at once, then removes the overlay when its close animation ends. Give the .newt-modal__title element role="heading" and aria-level="2" when it is not a heading element, as the reference markup does. A .newt-modal__close class places a close control in the corner, and .newt-modal__header--dismissable leaves room for it.

Tokens

Modal reads its colours, radii and motion from the --newt-* tokens installed with the library. Override a token and every component that reads it follows, including this one — see the token layer. In the plain HTML and CSS distribution the same component is newt-modal.

  • --newt-space-6
  • --newt-overlay
  • --newt-duration-slow
  • --newt-ease-overlay
  • --newt-duration-fast
  • --newt-space-4
  • --newt-bg-floating
  • --newt-border-subtle
  • --newt-radius-lg
  • --newt-shadow-elevation-high
  • --newt-text-secondary
  • --newt-space-2
  • --newt-font-size-lg
  • --newt-font-weight-semibold
  • --newt-line-height-tight
  • --newt-text-primary
  • --newt-control-sm
  • --newt-font-size-md
  • --newt-font-weight-normal
  • --newt-space-3

Changelog

  1. feataccessible and themed Spoiler, Modal and CodeBlock#57