# Modal

> The everyday modal in one component: pass a title, description, body and footer. Built on Dialog.

Status: beta. Category: Overlays.

```ts
import { Modal, ModalClose } from '@glyphui/ui'
```

Exports: `Modal`, `ModalClose`, `modalStyles`.

## Notes

- Use Modal for most cases. Reach for the Dialog parts when you need a custom layout, AlertDialog or useConfirm() for yes/no decisions, and Sheet for side panels.
- The title is required: it becomes the modal’s accessible name.
- The footer sits outside the body, so a FormSubmit there needs form={form}; a plain submit button needs onSubmit on the Modal.
- Set closeOnOverlayClick={false} for forms where a stray click would lose input; Escape still closes.

## Modal props

| Prop | Type | Default | Description |
|---|---|---|---|
| `title` (required) | `ReactNode` |  | Heading of the modal. Also its accessible name. |
| `asChild` | `boolean` |  |  |
| `closeOnOverlayClick` | `boolean` |  | Close when the backdrop is clicked. Default true. |
| `defaultOpen` | `boolean` |  |  |
| `description` | `ReactNode` |  |  |
| `footer` | `ReactNode` |  | Actions at the bottom. Wrap a button in `ModalClose` to close on click. |
| `onOpenChange` | `((open: boolean) => void)` |  |  |
| `onSubmit` | `((event: FormEvent<HTMLFormElement>) => void)` |  | Turns the body and footer into one `<form>`, so a `type="submit"` button in the footer submits the fields in the body. The page does not reload. With `@glyphui/ui/form`, use `<Form>` in the body and `<FormSubmit form={form}>` in the footer instead. |
| `open` | `boolean` |  |  |
| `overlayClassName` | `string` |  |  |
| `showClose` | `boolean` |  | Show the close button in the corner. Default true. |
| `size` | `"sm" \| "md" \| "lg" \| "xl"` |  |  |
| `trigger` | `ReactNode` |  | Element that opens the modal, e.g. a Button. Optional when you control `open`. |

## Example: With a trigger

Pass the opening button as trigger; wrap footer buttons in ModalClose.

```tsx
import { Button, Field, Input, Modal, ModalClose } from '@glyphui/ui'
import { UserPlus } from 'lucide-react'

export default function Example() {
  return (
    <Modal
      title="Invite teammates"
      description="They get access to every project in Acme Inc."
      trigger={<Button leftIcon={<UserPlus />}>Invite</Button>}
      footer={
        <>
          <ModalClose asChild>
            <Button variant="outline">Cancel</Button>
          </ModalClose>
          <ModalClose asChild>
            <Button>Send invites</Button>
          </ModalClose>
        </>
      }
    >
      <Field label="Email addresses" description="Separate addresses with commas.">
        <Input placeholder="grace@acme.com, alan@acme.com" />
      </Field>
    </Modal>
  )
}
```

## Example: Controlled

Open it from code, e.g. after a row action or a keyboard shortcut.

```tsx
import { Button, Modal, Text } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [open, setOpen] = useState(false)
  return (
    <div className="flex flex-col items-center gap-3">
      <Button variant="outline" onClick={() => setOpen(true)}>
        View keyboard shortcuts
      </Button>
      <Text size="small" tone="muted">
        Modal is {open ? 'open' : 'closed'}
      </Text>
      <Modal
        open={open}
        onOpenChange={setOpen}
        size="sm"
        title="Keyboard shortcuts"
        footer={<Button onClick={() => setOpen(false)}>Got it</Button>}
      >
        <dl className="grid grid-cols-[1fr_auto] gap-y-2 text-small">
          <dt>Search</dt>
          <dd className="font-mono text-muted-foreground">⌘K</dd>
          <dt>New issue</dt>
          <dd className="font-mono text-muted-foreground">C</dd>
          <dt>Go to inbox</dt>
          <dd className="font-mono text-muted-foreground">G then I</dd>
        </dl>
      </Modal>
    </div>
  )
}
```

## Example: With a form

onSubmit turns the body and footer into one form, so a submit button in the footer works.

```tsx
import { Button, Field, Input, Modal, Textarea, toast } from '@glyphui/ui'
import { useState } from 'react'

export default function Example() {
  const [open, setOpen] = useState(false)
  const [saving, setSaving] = useState(false)

  return (
    <Modal
      open={open}
      onOpenChange={setOpen}
      closeOnOverlayClick={false}
      title="New project"
      description="You can change these details later."
      trigger={<Button>New project</Button>}
      onSubmit={async () => {
        setSaving(true)
        await new Promise((resolve) => setTimeout(resolve, 800))
        setSaving(false)
        setOpen(false)
        toast.success('Project created')
      }}
      footer={
        <Button type="submit" loading={saving}>
          Create project
        </Button>
      }
    >
      <Field label="Name" required>
        <Input name="name" placeholder="Website redesign" required />
      </Field>
      <Field label="Description">
        <Textarea name="description" placeholder="What is this project about?" />
      </Field>
    </Modal>
  )
}
```

## Example: With a validated form

Schema validation with @glyphui/ui/form: <Form> in the body, <FormSubmit form={form}> in the footer.

```tsx
import {
  Button,
  DatePicker,
  Input,
  Modal,
  ModalClose,
  NumberInput,
  Select,
  SelectItem,
  toast,
} from '@glyphui/ui'
import { Form, FormError, FormField, FormSubmit, useForm } from '@glyphui/ui/form'
import { Plus } from 'lucide-react'
import { useState } from 'react'
import { z } from 'zod'

const customers = ['Northwind', 'Globex', 'Initech', 'Umbrella']

const schema = z.object({
  customer: z.string().min(1, 'Choose a customer'),
  amount: z.number('Enter an amount').positive('Must be more than zero'),
  due: z.date('Choose a due date'),
  memo: z.string().max(140, 'Keep it under 140 characters'),
})

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' })

export default function Example() {
  const [open, setOpen] = useState(false)
  const form = useForm({
    schema,
    defaultValues: { customer: '', amount: undefined, due: undefined, memo: '' },
  })

  return (
    <Modal
      open={open}
      onOpenChange={(next) => {
        if (!next) form.reset()
        setOpen(next)
      }}
      title="New invoice"
      description="The customer gets an email with a payment link."
      trigger={<Button leftIcon={<Plus />}>New invoice</Button>}
      footer={
        <>
          <ModalClose asChild>
            <Button variant="outline">Cancel</Button>
          </ModalClose>
          {/* Outside <Form>, so it gets the form explicitly. */}
          <FormSubmit form={form}>Create invoice</FormSubmit>
        </>
      }
    >
      <Form
        form={form}
        className="grid gap-4"
        onSubmit={async (values) => {
          await new Promise((resolve) => setTimeout(resolve, 600))
          if (values.amount > 50_000) {
            return { errors: { amount: 'Invoices over $50,000 need approval.' } }
          }
          toast.success('Invoice created', {
            description: `${values.customer} · ${usd.format(values.amount)}`,
          })
          setOpen(false)
          form.reset()
        }}
      >
        <FormError />
        <FormField control={form.control} name="customer" label="Customer" required>
          {(field) => (
            <Select
              placeholder="Choose a customer"
              value={field.value}
              onValueChange={field.onChange}
            >
              {customers.map((name) => (
                <SelectItem key={name} value={name}>
                  {name}
                </SelectItem>
              ))}
            </Select>
          )}
        </FormField>
        <div className="grid gap-4 sm:grid-cols-2">
          <FormField control={form.control} name="amount" label="Amount" required>
            {(field) => (
              <NumberInput
                value={field.value ?? null}
                onValueChange={(value) => field.onChange(value ?? undefined)}
                min={0}
                locale="en-US"
                formatOptions={{ style: 'currency', currency: 'USD' }}
              />
            )}
          </FormField>
          <FormField control={form.control} name="due" label="Due date" required>
            {(field) => (
              <DatePicker value={field.value} onValueChange={field.onChange} minDate={new Date()} />
            )}
          </FormField>
        </div>
        <FormField
          control={form.control}
          name="memo"
          label="Memo"
          description="Shown on the invoice."
        >
          {(field) => <Input placeholder="October usage" {...field} />}
        </FormField>
      </Form>
    </Modal>
  )
}
```

Live page: https://glyphui.xyz/components/modal
