# Modal

Display content in a layer above the main page. Ideal for confirmations, alerts, and forms.

```tsx
import { Button, Heading, Input, Modal, Spacer, Text } from '@fluxui-dev/react';

<Modal.Trigger name="edit-profile">
    <Button>Edit profile</Button>
</Modal.Trigger>

<Modal name="edit-profile" className="md:w-96">
    <div className="space-y-6">
        <div>
            <Heading size="lg">Update profile</Heading>
            <Text className="mt-2">Make changes to your personal details.</Text>
        </div>

        <Input label="Name" placeholder="Your name" />
        <Input label="Date of birth" type="date" />

        <div className="flex">
            <Spacer />
            <Button type="submit" variant="primary">Save changes</Button>
        </div>
    </div>
</Modal>
```

## Modals in lists

To give each row of a list like `users.map` its own modal, pass the row's button as the `trigger` prop. The modal needs no `name`, so names can't collide.

```tsx
{users.map((user) => (
    <Modal key={user.id} trigger={<Button>Edit</Button>}>
        ...
    </Modal>
))}
```

## Passing data

Instead of giving each row its own modal, you can share a single named modal by passing a `payload` prop to each `Modal.Trigger` and a function receiving `{ payload }` as the `Modal` children. You can also pass a payload from code using `modal(name).open(payload)`.

```tsx
{users.map((user) => (
    <Modal.Trigger key={user.id} name="edit-user" payload={user}>
        <Button>Edit {user.name}</Button>
    </Modal.Trigger>
))}

<Modal<User> name="edit-user" className="md:w-96">
    {({ payload: user }) => (
        <div className="space-y-6">
            <Heading size="lg">Edit {user?.name}</Heading>

            <Input label="Name" defaultValue={user?.name} />
            <Input label="Email" type="email" defaultValue={user?.email} />

            <div className="flex">
                <Spacer />
                <Button type="submit" variant="primary">Save changes</Button>
            </div>
        </div>
    )}
</Modal>
```

When the modal opens without a payload, such as with `modal(name).open()`, `payload` is `undefined`. Its type defaults to `unknown`, so pass a type argument like `<Modal<User> name="edit-user">` to type it.

## Forms in modals

A modal renders at the end of the page's `body`, so it sits above everything else. Its fields are therefore not inside a form that wraps the modal, and do not submit with it. Put the form inside the modal instead.

```tsx
<Modal name="delete-account">
    <Form {...destroy.form()}>
        <Input name="password" type="password" label="Password" />
        <Button type="submit" variant="danger">Delete account</Button>
    </Form>
</Modal>
```

## JavaScript methods

You can import the `modal()` and `modals()` functions from `@fluxui-dev/react` to open and close modals by name from anywhere, such as an event handler.

Consider a "confirm" modal like so:

```tsx
<Modal name="confirm">
    {/* ... */}
</Modal>
```

You can now open and close this modal using the following functions:

```tsx
import { modal, modals } from '@fluxui-dev/react';

// Control the "confirm" modal anywhere on the page...
modal('confirm').open();
modal('confirm').close();

// Closes all modals on the page...
modals().close();
```

## Controlled state

Instead of using a `name`, you can control the modal's open state directly with the `open` and `onOpenChange` props.

```tsx
const [showConfirmModal, setShowConfirmModal] = useState(false);

<Button onClick={() => setShowConfirmModal(true)}>Delete post</Button>

<Modal open={showConfirmModal} onOpenChange={setShowConfirmModal}>
    {/* ... */}
</Modal>
```

## Close events

If you need to perform some logic after a modal closes, you can check the `open` value passed to `onOpenChange` like so:

```tsx
<Modal onOpenChange={(open) => !open && doSomething()}>
    {/* ... */}
</Modal>
```

## Cancel events

If you need to perform some logic after a modal is cancelled by clicking outside or pressing escape, you can check the `reason` in the `eventDetails` passed to `onOpenChange` like so:

```tsx
<Modal
    onOpenChange={(open, { reason }) => {
        if (!open && (reason === 'escape-key' || reason === 'outside-press')) doSomething();
    }}
>
    {/* ... */}
</Modal>
```

## Disable click outside

By default, clicking outside the modal will close it. If you want to disable this behavior, you can use the `dismissible={false}` prop.

```tsx
<Modal dismissible={false}>
    {/* ... */}
</Modal>
```

## Disable escape

By default, pressing escape will close the modal. If you want to disable this behavior, you can use the `escapable={false}` prop.

```tsx
<Modal escapable={false}>
    {/* ... */}
</Modal>
```

## Scrolling long content

By default, long modal content scrolls within the modal itself, making it easy to miss content below the fold. Set `scroll="body"` to let the modal extend beyond the viewport, making it obvious that content continues below.

```tsx
<Modal name="terms" scroll="body">
    {/* Long-form content like terms of service... */}
</Modal>
```

## Confirmation

Prompt a user for confirmation before performing a dangerous action.

```tsx
<Modal.Trigger name="delete-profile">
    <Button variant="danger">Delete</Button>
</Modal.Trigger>

<Modal name="delete-profile" className="min-w-[22rem]">
    <div className="space-y-6">
        <div>
            <Heading size="lg">Delete project?</Heading>

            <Text className="mt-2">
                You're about to delete this project.<br />
                This action cannot be reversed.
            </Text>
        </div>

        <div className="flex gap-2">
            <Spacer />

            <Modal.Close>
                <Button variant="ghost">Cancel</Button>
            </Modal.Close>

            <Button type="submit" variant="danger">Delete project</Button>
        </div>
    </div>
</Modal>
```

## Flyout

Use the `flyout` prop for a more anchored and long-form dialog.

```tsx
<Modal.Trigger name="edit-profile-flyout">
    <Button>Edit profile</Button>
</Modal.Trigger>

<Modal name="edit-profile-flyout" flyout>
    <div className="space-y-6">
        <div>
            <Heading size="lg">Update profile</Heading>
            <Text className="mt-2">Make changes to your personal details.</Text>
        </div>

        <Input label="Name" placeholder="Your name" />

        <Input label="Date of birth" type="date" />

        <div className="flex">
            <Spacer />

            <Button type="submit" variant="primary">Save changes</Button>
        </div>
    </div>
</Modal>
```

### Flyout positioning

By default, flyouts will open from the right. You can change this behavior by passing "left", or "bottom" into the `position` prop.

```tsx
<Modal flyout position="left">
    {/* ... */}
</Modal>
```

### Floating flyout

Use the "floating" variant to give your flyout modal a floating appearance.

```tsx
<Modal.Trigger name="edit-profile-floating">
    <Button>Edit profile</Button>
</Modal.Trigger>

<Modal name="edit-profile-floating" flyout variant="floating" className="md:w-lg">
    <div className="space-y-6">
        <Heading size="lg">Update profile</Heading>

        <Text>Make changes to your personal details.</Text>

        <Input label="Name" placeholder="Your name" />

        <Input label="Date of birth" type="date" />

        <div className="flex items-center justify-end gap-2">
            <Modal.Close>
                <Button variant="filled">Cancel</Button>
            </Modal.Close>

            <Button type="submit" variant="primary">Save changes</Button>
        </div>
    </div>
</Modal>
```

## Reference

### Modal

**Prop:**

- `name` - Unique identifier for the modal. Required when using `Modal.Trigger`, `modal()`, or `modals()`.
- `flyout` - If `true`, the modal will open as a flyout.
- `variant` - Visual style of the modal. Options: `default`, `floating`, `bare`.
- `position` - For flyout modals, the direction they open from. Options: `right` (default), `left`, `bottom`.
- `scroll` - Scrolling behavior for long content. Options: `body`. When set to `body`, the entire viewport scrolls instead of clipping overflow.
- `dismissible` - If `false`, prevents closing the modal by clicking outside. Default: `true`.
- `escapable` - If `false`, prevents closing the modal by pressing escape. Default: `true`.
- `closable` - If `false`, hides the close button. Default: `false` for the `bare` variant, `true` otherwise.
- `trigger` - An element that opens the modal when clicked, as an alternative to `Modal.Trigger`.
- `keepMounted` - If `true`, keeps the modal's content in the page while it is closed, so a form inside keeps what was typed. Default: `false`, so the content is removed on close and starts fresh each time the modal opens.
- `finalFocus` - A ref, or a function that returns an element, to focus when the modal closes. Default: the element that opened the modal.
- `open` - Controlled open state of the modal. Pair with `onOpenChange`.
- `defaultOpen` - Initial open state of the modal when uncontrolled.
- `onOpenChange` - Callback fired when the modal opens or closes, receiving the new open state and `eventDetails`, whose `reason` tells why.
- `children` - The modal's content, or a function that receives `{ payload }`, the value the modal was opened with.

**CSS:**

- `className` - Common use: `md:w-96` for width.

**Attribute:**

- `data-flux-modal` - Applied to the dialog element for styling and identification.

### Modal.Trigger

**Prop:**

- `name` - Name of the modal to trigger. Must match the modal's name.
- `shortcut` - Keyboard shortcut that opens the modal from anywhere on the page, such as `mod.k` (Cmd on Mac, Ctrl elsewhere), `cmd.k`, or `?`. Keys match the character typed, so write `?` rather than `shift.slash`. A shortcut without `cmd`, `ctrl`, `alt`, or `mod` doesn't fire while typing in a text field.
- `payload` - Value passed to the modal's children function when this trigger or its shortcut opens the modal.
- `children` - The trigger element (e.g., `Button`), which may be wrapped in a `Tooltip`. A `Tooltip` around `Modal.Trigger` works too.

### Modal.Close

**Prop:**

- `children` - The close trigger element (e.g., `Button`).

### modal()

JavaScript method for controlling modals.

**Parameter:**

- `name` - Name of the modal to control.

**Method:**

- `open(payload)` - Opens the modal, optionally passing `payload` to its children function.
- `close()` - Closes the modal.

### modals()

JavaScript method for controlling all modals on the page.

**Method:**

- `close()` - Closes every open modal that has a `name`.
