repose-material 0.28.13

Material components for Repose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#![allow(non_snake_case)]

use std::rc::Rc;
use std::sync::atomic::{AtomicU64, Ordering};

use repose_core::*;
use repose_ui::overlay::OverlayHandle;
use repose_ui::{Box, Column, ViewExt, ZStack};
use web_time::Duration;

use super::AlertDialogDefaults;
use super::{DatePicker, DatePickerConfig, DatePickerState};
use super::{TimePicker, TimePickerConfig, TimePickerState};

static DIALOG_COUNTER: AtomicU64 = AtomicU64::new(0);

/// State controlling dialog visibility.
pub struct DialogState {
    visible: Signal<bool>,
    id: u64,
}

impl Default for DialogState {
    fn default() -> Self {
        Self::new()
    }
}

impl DialogState {
    pub fn new() -> Self {
        Self {
            visible: signal(false),
            id: DIALOG_COUNTER.fetch_add(1, Ordering::Relaxed),
        }
    }

    pub fn key(&self, suffix: &str) -> String {
        format!("dlg_{}_{}", self.id, suffix)
    }

    pub fn is_visible(&self) -> bool {
        self.visible.get()
    }

    pub fn show(&self) {
        self.visible.set(true);
    }

    pub fn dismiss(&self) {
        self.visible.set(false);
    }
}

/// Configuration for dialog dismiss behavior.
/// Mirrors Compose's `DialogProperties`.
#[derive(Clone)]
pub struct DialogProperties {
    /// Called when the user attempts to dismiss the dialog
    /// (scrim click, Escape/Back press). When set, this overrides `state.dismiss()`.
    /// To make a dialog that never closes, pass `Some(Rc::new(|| {}))`.
    pub on_dismiss_request: Option<Rc<dyn Fn()>>,
    /// Whether clicking the scrim (outside the dialog surface) triggers dismissal.
    /// Default: `true`.
    pub dismiss_on_click_outside: bool,
    /// Whether pressing Escape (or Back gesture) triggers dismissal.
    /// Default: `true`.
    pub dismiss_on_back_press: bool,
    /// Compose `usePlatformDefaultWidth`. Default: true.
    pub use_platform_default_width: bool,
    /// Compose `usePlatformInsets` (+ IME). Default: true.
    pub use_platform_insets: bool,
}

impl Default for DialogProperties {
    fn default() -> Self {
        Self {
            on_dismiss_request: None,
            dismiss_on_click_outside: true,
            dismiss_on_back_press: true,
            use_platform_default_width: true,
            use_platform_insets: true,
        }
    }
}

fn preferred_dialog_width_dp(container_w: f32, container_h: f32) -> f32 {
    let smallest = container_w.min(container_h);
    if smallest >= 600.0 {
        super::DialogDefaults::PREFERRED_WIDTH_EXPANDED
    } else if smallest >= 480.0 {
        super::DialogDefaults::PREFERRED_WIDTH_MEDIUM
    } else {
        super::DialogDefaults::PREFERRED_WIDTH_COMPACT
    }
}

fn dialog_available_bounds(
    use_platform_default_width: bool,
    use_platform_insets: bool,
) -> (f32 /*max_w*/, f32 /*max_h*/, PaddingValues) {
    let win_w = get_window_container_width().max(0.0);
    let win_h = get_window_container_height().max(0.0);

    let mut pad = PaddingValues::default();
    if use_platform_insets {
        let insets = window_insets();
        // WindowInsets fields are physical px (see ime_padding / system_bars_padding).
        pad.left = px_to_dp(insets.left);
        pad.right = px_to_dp(insets.right);
        pad.top = px_to_dp(insets.top);
        pad.bottom = px_to_dp(insets.bottom) + px_to_dp(insets.ime_bottom);
    }

    let avail_w = (win_w - pad.left - pad.right).max(0.0);
    let avail_h = (win_h - pad.top - pad.bottom).max(0.0);

    let max_w = if use_platform_default_width {
        preferred_dialog_width_dp(win_w, win_h)
            .min(avail_w)
            .min(super::DialogDefaults::MAX_WIDTH)
    } else {
        avail_w.min(super::DialogDefaults::MAX_WIDTH)
    };
    // Always keep dialog fully on-screen vertically.
    let max_h = avail_h;

    (max_w.max(0.0), max_h.max(0.0), pad)
}

/// After merging caller modifiers, clamp size so the dialog can never escape the viewport.
fn clamp_dialog_modifier(mut m: Modifier, platform_max_w: f32, platform_max_h: f32) -> Modifier {
    let max_w = m
        .max_width
        .unwrap_or(platform_max_w)
        .min(platform_max_w)
        .max(0.0);
    let max_h = m
        .max_height
        .unwrap_or(platform_max_h)
        .min(platform_max_h)
        .max(0.0);
    m.max_width = Some(max_w);
    m.max_height = Some(max_h);

    // Compose Constraints: min cannot exceed max.
    if let Some(min_w) = m.min_width {
        m.min_width = Some(min_w.min(max_w).max(0.0));
    } else {
        m.min_width = Some(super::DialogDefaults::MIN_WIDTH.min(max_w).max(0.0));
    }
    if let Some(min_h) = m.min_height {
        m.min_height = Some(min_h.min(max_h).max(0.0));
    }
    m
}

/// A modal dialog rendered in the overlay layer with scrim and spring animation.
///
/// Unlike the inline `AlertDialog`, this version renders outside the layout tree
/// so it is never clipped by parent containers, scroll areas, or stacks.
///
/// Caller should create a `DialogState` and manage visibility via `show()`/`dismiss()`.
///
/// Focus behavior: dialog content is wrapped in a focus group, so Tab/Shift+Tab
/// cycles within the dialog instead of moving to background elements.
///
/// Escape handling: when the dialog content is focused and `dismiss_on_back_press`
/// is true, pressing Escape calls `on_dismiss_request` (or `state.dismiss()` if
/// no `on_dismiss_request` is set). Set `dismiss_on_back_press = false` or pass
/// `on_dismiss_request = Some(Rc::new(|| {}))` to prevent Escape from closing.
pub fn Dialog(
    state: Rc<DialogState>,
    overlay: OverlayHandle,
    modifier: Modifier,
    properties: DialogProperties,
    content: View,
) -> View {
    let overlay_id = remember_with_key(state.key("oid"), || signal(0u64));

    // RefCell holding the latest content so the overlay builder reads fresh state each frame
    let current_content = remember_state_with_key(state.key("c"), || Box(Modifier::new()));
    *current_content.borrow_mut() = content;

    // Store properties so the overlay closure reads fresh values each frame
    let props = remember_state_with_key(state.key("p"), || properties.clone());
    *props.borrow_mut() = properties;

    let scroll_state: Rc<repose_core::scroll::ScrollState> =
        remember_with_key(state.key("scroll"), repose_core::scroll::ScrollState::new);

    // Animated scale/alpha for enter/exit
    let spec = AnimationSpec::tween(Duration::from_millis(200), Easing::FastOutSlowIn);
    let anim = remember_state_with_key(state.key("anim"), || AnimatedValue::new(0.0, spec));
    let last_target = remember_state_with_key(state.key("atarget"), || f32::NAN);
    let anim_target = if state.is_visible() { 1.0 } else { 0.0 };

    {
        let mut a = anim.borrow_mut();
        let mut lt = last_target.borrow_mut();
        if lt.is_nan() || (*lt - anim_target).abs() > 1e-6 {
            a.set_spec(spec);
            a.set_target(anim_target);
            *lt = anim_target;
        }
        drop(lt);
        if a.update() {
            request_frame();
        }
    }

    let progress = *anim.borrow().get();
    let visible = state.is_visible() || progress > 0.01;

    if visible {
        if overlay_id.get() == 0 {
            let builder: Rc<dyn Fn() -> View> = Rc::new({
                let state = state.clone();
                let anim = anim.clone();
                let modifier = modifier.clone();
                let current_content = current_content.clone();
                let props = props.clone();
                let scroll_state = scroll_state.clone();
                move || {
                    let progress = *anim.borrow().get();
                    let alpha = progress.min(1.0);
                    let scale = 0.8 + 0.2 * progress;
                    let th = theme();
                    let content = current_content.borrow().clone();
                    let p = props.borrow().clone();

                    // Recomputed every frame → correct after resize / IME / insets.
                    let (platform_max_w, platform_max_h, inset_pad) = dialog_available_bounds(
                        p.use_platform_default_width,
                        p.use_platform_insets,
                    );

                    let dialog_mod = clamp_dialog_modifier(
                        Modifier::new()
                            .min_width(super::DialogDefaults::MIN_WIDTH)
                            .max_width(super::DialogDefaults::MAX_WIDTH)
                            .then(modifier.clone())
                            .justify_content(JustifyContent::CENTER)
                            .background(th.surface_container_high)
                            .clip_rounded(th.shapes.extra_large)
                            .alpha(alpha)
                            .scale(scale)
                            .focus_group()
                            .clickable()
                            .focusable(false)
                            .on_key_event({
                                let s = state.clone();
                                let props = props.clone();
                                move |ke| {
                                    use repose_core::input::{Key, KeyEventType};
                                    if ke.key == Key::Escape && ke.event_type == KeyEventType::Down
                                    {
                                        let (dismiss, cb) = {
                                            let p = props.borrow();
                                            (p.dismiss_on_back_press, p.on_dismiss_request.clone())
                                        };
                                        if dismiss {
                                            if let Some(cb) = cb {
                                                cb();
                                            } else {
                                                s.dismiss();
                                            }
                                            return true;
                                        }
                                    }
                                    false
                                }
                            }),
                        platform_max_w,
                        platform_max_h,
                    );

                    // Scroll when content exceeds the clamped height (dropdown pattern).
                    let axis_binding = match scroll_state.to_binding() {
                        repose_core::scroll::ScrollBinding::Vertical(a) => a,
                        _ => unreachable!(),
                    };
                    let scrollable_body = Box(Modifier::new()
                        .fill_max_width()
                        .max_height(platform_max_h)
                        .vertical_scroll(axis_binding))
                    .child(content);

                    let dialog = Box(dialog_mod).child(scrollable_body);

                    let scrim_color = AlertDialogDefaults::scrim_color();
                    let scrim_alpha = (scrim_color.3 as f32 / 255.0) * alpha;
                    let scrim = Box(Modifier::new()
                        .fill_max_size()
                        .background(scrim_color.with_alpha_f32(scrim_alpha.clamp(0.0, 1.0)))
                        .focusable(false)
                        .input_blocker()
                        .on_scroll(|_| Vec2::default())
                        .on_click({
                            let s = state.clone();
                            let props = props.clone();
                            move || {
                                let (dismiss, cb) = {
                                    let p = props.borrow();
                                    (p.dismiss_on_click_outside, p.on_dismiss_request.clone())
                                };
                                if dismiss {
                                    if let Some(cb) = cb {
                                        cb();
                                    } else {
                                        s.dismiss();
                                    }
                                }
                            }
                        }));

                    // Center inside the safe area (insets as padding), not the raw window.
                    ZStack(Modifier::new().fill_max_size().absolute()).child((
                        scrim,
                        Box(Modifier::new()
                            .fill_max_size()
                            .padding_values(inset_pad)
                            .justify_content(JustifyContent::CENTER)
                            .align_items(AlignItems::CENTER)
                            .hit_passthrough())
                        .child(dialog),
                    ))
                }
            });

            let id = overlay.show_entry(builder, 900.0, false);
            overlay_id.set(id);
        }
    } else {
        let prev = overlay_id.get();
        if prev != 0 {
            let _ = overlay.dismiss(prev);
            overlay_id.set(0);
        }
    }

    Box(Modifier::new())
}

/// Configuration for alert dialog.
#[derive(Clone, Debug)]
pub struct AlertDialogConfig {
    pub modifier: Modifier,
    pub scrim_color: Color,
    pub min_width: f32,
    pub max_width: f32,
    pub horizontal_padding: f32,
    pub shape_radius: Option<f32>,
    pub container_color: Color,
    pub tonal_elevation: f32,
}

impl Default for AlertDialogConfig {
    fn default() -> Self {
        Self {
            modifier: Modifier::new(),
            scrim_color: AlertDialogDefaults::scrim_color(),
            min_width: AlertDialogDefaults::MIN_WIDTH,
            max_width: AlertDialogDefaults::MAX_WIDTH,
            horizontal_padding: AlertDialogDefaults::HORIZONTAL_PADDING,
            shape_radius: None,
            container_color: theme().surface_container_high,
            tonal_elevation: 0.0,
        }
    }
}

/// An improved AlertDialog using the overlay-based `Dialog`.
///
/// Shows a centered modal surface with title, text, confirm button, and optional
/// dismiss button. Managed via a shared `DialogState`.
pub fn AlertDialog(
    state: Rc<DialogState>,
    overlay: OverlayHandle,
    title: View,
    text: View,
    confirm_button: View,
    dismiss_button: Option<View>,
    config: AlertDialogConfig,
) -> View {
    let content = Box(Modifier::new()
        .background(config.container_color)
        .clip_rounded(
            config
                .shape_radius
                .unwrap_or_else(|| theme().shapes.extra_large),
        ))
    .child(super::alert_dialog_body(
        title,
        text,
        confirm_button,
        dismiss_button,
    ));

    Dialog(
        state,
        overlay,
        Modifier::new()
            .min_width(config.min_width)
            .max_width(config.max_width)
            .then(config.modifier),
        DialogProperties::default(),
        content,
    )
}

/// Configuration for [`DatePickerDialog`].
#[derive(Clone)]
pub struct DatePickerDialogConfig {
    pub modifier: Modifier,
    pub shape_radius: Option<f32>,
    pub colors: super::DatePickerColors,
}

impl Default for DatePickerDialogConfig {
    fn default() -> Self {
        Self {
            modifier: Modifier::new(),
            shape_radius: None,
            colors: super::DatePickerColors::default(),
        }
    }
}

/// M3 Date Picker Dialog - wraps [`DatePicker`] inside a modal [`Dialog`]
/// with confirm/cancel buttons. Equivalent to Compose's `DatePickerDialog`.
///
/// The `on_confirm` callback fires when a day is clicked or the OK button is pressed.
/// The `on_dismiss` fires on Cancel or scrim tap.
pub fn DatePickerDialog(
    state: Rc<DialogState>,
    overlay: OverlayHandle,
    picker_state: Rc<DatePickerState>,
    on_confirm: Rc<dyn Fn(i32, u32, u32)>,
    on_dismiss: Rc<dyn Fn()>,
    config: DatePickerDialogConfig,
) -> View {
    let content = Box(Modifier::new()
        .background(config.colors.container_color)
        .clip_rounded(
            config
                .shape_radius
                .unwrap_or_else(|| theme().shapes.extra_large),
        ))
    .child(Column(Modifier::new()).child((DatePicker(
        picker_state.clone(),
        on_confirm,
        on_dismiss,
        DatePickerConfig {
            colors: config.colors,
            ..DatePickerConfig::default()
        },
    ),)));

    Dialog(
        state,
        overlay,
        config.modifier,
        DialogProperties::default(),
        content,
    )
}

/// Configuration for [`TimePickerDialog`].
#[derive(Clone)]
pub struct TimePickerDialogConfig {
    pub modifier: Modifier,
    pub shape_radius: Option<f32>,
    pub container_color: Color,
    pub colors: super::TimePickerColors,
}

impl Default for TimePickerDialogConfig {
    fn default() -> Self {
        Self {
            modifier: Modifier::new(),
            shape_radius: None,
            container_color: theme().surface_container_high,
            colors: super::TimePickerColors::default(),
        }
    }
}

/// M3 Time Picker Dialog - wraps [`TimePicker`] inside a modal [`Dialog`]
/// with confirm/cancel buttons. Equivalent to Compose's `TimePickerDialog`.
///
/// The `on_confirm` callback fires when OK is pressed.
/// The `on_dismiss` fires on Cancel or scrim tap.
pub fn TimePickerDialog(
    state: Rc<DialogState>,
    overlay: OverlayHandle,
    picker_state: Rc<TimePickerState>,
    on_confirm: Rc<dyn Fn(u32, u32)>,
    on_dismiss: Rc<dyn Fn()>,
    config: TimePickerDialogConfig,
) -> View {
    let content = Box(Modifier::new()
        .background(config.container_color)
        .clip_rounded(
            config
                .shape_radius
                .unwrap_or_else(|| theme().shapes.extra_large),
        ))
    .child(Column(Modifier::new()).child((TimePicker(
        picker_state.clone(),
        on_confirm,
        on_dismiss,
        TimePickerConfig {
            colors: config.colors,
            ..TimePickerConfig::default()
        },
    ),)));

    Dialog(
        state,
        overlay,
        config.modifier,
        DialogProperties::default(),
        content,
    )
}