# Modal

Crate: `libero`
Import: `use libero::hooks::{ModalHandle, ModalScope, use_modal};`
Feature: `modal` (on by default, turns on `overlay-backdrop`, `focus-trap`, `use-back`; [features.md](features.md))
Source: <https://github.com/tdymel/libero/tree/main/libero/src/components/overlay/use_modal.rs>
Index: [index.md](index.md) lists every other page
Description: A hook that opens a render closure as a modal, with arguments and a result per opening.

A modal is a hook, not a component. `use_modal` takes a render closure and
returns a handle that opens it. The content is built only while it shows. Each
opening passes its arguments to the closure's `ModalScope`, and settles with
what `resolve` answered, or `None` when dismissed.

## Usage

`use_modal` takes the render closure, which every opening shares. The
`ModalScope` carries the arguments of the one showing.

```rust
use dioxus::prelude::*;
use libero::{
    components::{Button, Dialog, DialogActions, DialogBody, Flex, Text},
    hooks::{ModalScope, use_modal},
};

#[derive(Clone, Copy, PartialEq)]
enum SaveChoice {
    Save,
    Discard,
}

#[component]
fn Demo() -> Element {
    let prompt = use_modal(move |s: ModalScope<String, SaveChoice>| {
        let document = s.args();

        rsx! {
            Dialog {
                title: "Unsaved changes",
                size: "md",
                full_screen: "phone",
                DialogBody { Text { "{document} has changes you have not saved." } }
                DialogActions {
                    Button { variant: "text", onclick: move |_| s.close(), "Keep editing" }
                    Button {
                        variant: "filled",
                        color: "error",
                        onclick: move |_| s.resolve(SaveChoice::Discard),
                        "Discard"
                    }
                    Button {
                        variant: "filled",
                        color: "primary",
                        onclick: move |_| s.resolve(SaveChoice::Save),
                        "Save"
                    }
                }
            }
        }
    });
    let mut answer = use_signal(|| "none yet");

    rsx! {
        Flex {
            direction: "row",
            align: "center",
            gap: "md",
            Button {
                variant: "outlined",
                onclick: move |_| {
                    prompt.open_with("notes.md").onresult(move |result| {
                        answer.set(match result {
                            Some(SaveChoice::Save) => "saved",
                            Some(SaveChoice::Discard) => "discarded",
                            None => "dismissed",
                        });
                    });
                },
                "Close editor"
            }
            Text { role: "status", "Last answer: {answer}" }
        }
    }
}
```

## API

### `use_modal`

```rust,ignore
pub fn use_modal<S: Clone + 'static, R: Clone + 'static>(
    render: impl FnMut(ModalScope<S, R>) -> Element + 'static,
) -> ModalHandle<S, R>
```

| Argument | Type | Default | Description |
|---|---|---|---|
| `render` | `impl FnMut(ModalScope<S, R>) -> Element` | required | Builds the content, usually a `Dialog`, while the modal is open. Other content, a `Paper` or a plain box, takes clicks the same; only the backdrop around it closes. Style it there: the `Dialog`'s own `sx` and `parts` reach it in the portal. Returns a `ModalHandle<S, R>`, which is `Copy`: a trigger elsewhere in the tree can take it as a prop or from context. `R` defaults to `()`, for a modal that answers nothing; otherwise make it the dialog's own enum, not a `bool`. Escape, a backdrop click and Android's Back first ask the `Dialog`'s `ondismiss`: return `false` to keep a form with unsaved input open. Call it under `LiberoProvider`, in a component that outlives every trigger. The modal unmounts with that component, and its opening settles as dismissed. |

### `ModalHandle<S, R = ()>`

| Method | Returns | Description |
|---|---|---|
| `open_with(args: impl Into<S>)` | `Opening<R>` | Opens with these arguments, replacing whatever was showing. |
| `open()` | `Opening<R>` | Opens with `S::default()`. Needs `S: Default`. |
| `close()` | `()` | Dismisses whatever this modal is showing. |
| `is_open()` | `bool` | Whether this modal is showing. |

### `ModalScope<S, R = ()>`

| Method | Returns | Description |
|---|---|---|
| `args()` | `S` | The arguments this opening was given. Panics once the opening has ended. |
| `try_args()` | `Option<S>` | `args`, or `None` once the opening has closed or a later one superseded it. |
| `close()` | `()` | Ends it as a dismissal, the same as Escape. |
| `resolve(value: R)` | `()` | Ends it with an answer for the caller. |

### `Opening<R = ()>`

| Method | Returns | Description |
|---|---|---|
| `onresult(f: impl FnMut(Option<R>))` | `Self` | Runs when this opening settles, with `None` if it was dismissed. A replaced opening runs it with `None`. Awaiting the `Opening` gives the same answer instead, and `None` once replaced. |
| `close()` | `()` | Closes this opening, if it is still the one showing. |
| `.await` | `Option<R>` | The same outcome, as a future. `None` once replaced. Use it when async work waits on the answer, or for dialogs in sequence. |

### `ModalContext`

| Method | Returns | Description |
|---|---|---|
| `is_modal()` | `bool` | Whether the content is in a modal. Every modal provides this context to its content. |
| `close()` | `()` | Dismisses the modal around the content. `use_modal_close()` is the shorthand, for a component outside the render closure. |

A floating window provides an empty `ModalContext`, so its content is not
modal.

## Accessibility

### Keyboard

| Key | Action |
|---|---|
| `Escape` | Dismisses the modal unless the `Dialog`'s `ondismiss` refuses. A backdrop click does the same, except on a `role: "alertdialog"`, which ignores it. |
| `Tab` or `Shift+Tab` | Moves the focus within the modal. It does not leave while the modal shows. |

### Libero handles

- Focus moves into the modal, and back to the trigger once it closes.
- The focus trap, Escape and backdrop dismissal come from the modal. A `Dialog`
  on its own has none of them.
- A dismissal settles the `Opening` with `None`, so a result handler runs with
  `None`: match `Some(answer)` to act on an answer only.
- Android's Back button dismisses the top modal, as Escape does, rather than
  closing the app.
- When the focused control is removed, focus goes back into the modal, and Tab
  and Escape keep working.
- A `Dialog` with `role: "alertdialog"` ignores a backdrop click, so a stray
  click is no answer.
- With nothing focusable inside and no `Dialog`, focus lands on the modal's
  content box, so Escape still closes it.

### You must

- Name the `Dialog` with its `title`, or `aria_label`.
- Prefer a `Dialog`: other content has no dialog role or name, so a screen
  reader is not told a dialog opened.

### Example

A delete confirmation opened from a button: focus moves into the dialog, Tab
stays inside it, and Escape closes it and puts focus back on the button.

### Limits

- On Android, a modal opened without a tap (on mount or from a timer) may let
  Back close the app.
- On Android, once `ondismiss` refused a Back, the next Back closes the app
  unless a tap or key came between.
- In a desktop WebView or on Android, Tab and Shift+Tab move between the
  controls but can leave the modal at its ends.

## Theme defaults

| Struct | Field | Type | Description |
|---|---|---|---|
| `ZIndexDefaults` | `modal` | `i32` | The first modal's z-index (`1000`). |
| `ZIndexDefaults` | `modal_step` | `i32` | Added per stacked modal (`10`). |
| `ZIndexDefaults` | `overlay` | `i32` | The backdrop's layer (`300`), always below a modal. |

## CSS variables

| Variable | Description |
|---|---|
| `--lsx-modal-z-index` | This modal's stacking level. |
| `--lsx-z-index-modal` | The first modal's z-index, from the theme. |
| `--lsx-z-index-overlay` | The backdrop layer, from the theme. |

## Data attributes

The modal's root carries `data-lsx-scroll-lock`. The page behind it does not
scroll while the modal is open. A classic scrollbar's width is added to the
`html` element's own `padding-right`, so the page does not shift and the backdrop
covers the full width. Your own `position: fixed` element with `right: 0` still
shifts by that width.
