rust_widgets 2.0.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! ModalBottomSheet widget — Material-style modal bottom sheet with drag-to-dismiss.
//!
//! Displays a semi-transparent overlay behind a rounded top sheet containing a
//! drag handle, title, and optional content. Supports show/hide, drag-to-dismiss,
//! and overlay-click-to-dismiss. Emits a `dismissed` signal when closed.

use crate::core::{Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::GenericSignal;
use crate::widget::capability::coercion::expect_bool;
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// Material-style modal bottom sheet widget.
///
/// When visible, a semi-transparent overlay covers the widget geometry and a
/// rounded sheet appears at the bottom with a drag handle, title, and optional
/// child content. The user can tap the overlay or drag downward to dismiss.
pub struct ModalBottomSheet {
    base: BaseWidget,
    title: String,
    content: Option<Box<dyn Widget>>,
    is_visible: bool,
    drag_offset: f32,
    is_dragging: bool,
    /// Emitted when the sheet is dismissed by user interaction.
    pub dismissed: GenericSignal,
}

impl ModalBottomSheet {
    /// Creates a new ModalBottomSheet widget.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::ModalBottomSheet, geometry, "ModalBottomSheet"),
            title: String::new(),
            content: None,
            is_visible: false,
            drag_offset: 0.0,
            is_dragging: false,
            dismissed: GenericSignal::new(),
        }
    }

    /// Shows the bottom sheet.
    pub fn show(&mut self) {
        if !self.is_visible {
            self.is_visible = true;
            self.drag_offset = 0.0;
            self.is_dragging = false;
            self.base.request_redraw();
        }
    }

    /// Hides the bottom sheet without emitting the dismissed signal.
    pub fn hide(&mut self) {
        if self.is_visible {
            self.is_visible = false;
            self.drag_offset = 0.0;
            self.is_dragging = false;
            self.base.request_redraw();
        }
    }

    /// Returns whether the sheet is currently visible.
    pub fn is_visible(&self) -> bool {
        self.is_visible
    }

    /// Reports the sheet's own visibility flag.
    ///
    /// Deliberately distinct from [`Widget::is_visible`], which this widget
    /// overrides to return the same flag. Keeping the two entry points separate
    /// lets the property contract call the inherent one unambiguously.
    pub fn is_sheet_visible(&self) -> bool {
        self.is_visible
    }

    /// Sets the sheet title text.
    pub fn set_title(&mut self, title: impl Into<String>) {
        self.title = title.into();
        self.base.request_redraw();
    }

    /// Returns the sheet title.
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Sets the child content widget displayed in the sheet body.
    pub fn set_content(&mut self, widget: Box<dyn Widget>) {
        self.content = Some(widget);
        self.base.request_redraw();
    }

    /// Returns a reference to the child content, if any.
    pub fn content(&self) -> Option<&dyn Widget> {
        self.content.as_deref()
    }

    /// Returns a mutable reference to the child content, if any.
    pub fn content_mut(&mut self) -> Option<&mut dyn Widget> {
        self.content.as_deref_mut()
    }

    /// Returns the current drag offset.
    pub fn drag_offset(&self) -> f32 {
        self.drag_offset
    }

    /// Returns whether the user is currently dragging the sheet.
    pub fn is_dragging(&self) -> bool {
        self.is_dragging
    }

    /// Called when the user starts dragging the sheet.
    pub fn start_drag(&mut self) {
        if self.is_visible {
            self.is_dragging = true;
            self.base.request_redraw();
        }
    }

    /// Called to update the drag offset.
    /// Positive values indicate dragging downward.
    pub fn update_drag(&mut self, delta: f32) {
        if self.is_dragging {
            self.drag_offset = (self.drag_offset + delta).max(0.0);
            self.base.request_redraw();
        }
    }

    /// Called when the user ends the drag gesture.
    /// Dismisses the sheet if drag offset exceeds one third of the sheet height.
    pub fn end_drag(&mut self) {
        if self.is_dragging {
            self.is_dragging = false;
            let sheet_height = self.compute_sheet_height();
            if self.drag_offset > sheet_height as f32 / 3.0 {
                self.is_visible = false;
                self.dismissed.emit();
            }
            self.drag_offset = 0.0;
            self.base.request_redraw();
        }
    }

    /// Computes the approximate sheet panel height based on geometry and content.
    fn compute_sheet_height(&self) -> u32 {
        let rect = self.geometry();
        let title_height: u32 = 40;
        let handle_area: u32 = 24;
        let min_sheet = 120;
        let max_sheet = rect.height.saturating_sub(40);
        (title_height + handle_area + 80).min(max_sheet).max(min_sheet)
    }
}

impl Widget for ModalBottomSheet {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        crate::core::Size::new(300, 200)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `ModalBottomSheet`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_dialog.in.rs` / `access_write_dialog.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before. `visible` is served by the
/// inherent accessor rather than the base fallthrough, so a modal sheet's own
/// show/hide state is what the name reports.
impl WidgetProperties for ModalBottomSheet {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "visible" => Ok(CapabilityValue::Bool(self.is_sheet_visible())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "visible" => {
                if expect_bool(value)? {
                    self.show();
                } else {
                    self.hide();
                }
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["visible", BASE_PROPERTY_NAMES]
    }
}

impl Draw for ModalBottomSheet {
    fn draw(&mut self, context: &mut RenderContext) {
        if !self.is_visible {
            return;
        }

        let rect = self.geometry();
        let sheet_height = self.compute_sheet_height();
        let drag_offset_px = self.drag_offset as i32;

        // 1. Semi-transparent overlay
        let overlay_rect = Rect::new(rect.x, rect.y, rect.width, rect.height);
        context.fill_rect(overlay_rect, Color::rgba(0, 0, 0, 80));

        // 2. Sheet panel at the bottom, shifted by drag offset
        let sheet_y = rect.y + rect.height as i32 - sheet_height as i32 + drag_offset_px;
        let sheet_rect_panel = Rect::new(rect.x, sheet_y, rect.width, sheet_height);
        let corner_radius: u32 = 16;

        context.fill_rounded_rect(sheet_rect_panel, corner_radius, Color::rgba(248, 248, 248, 255));
        context.draw_rounded_rect_stroke(
            sheet_rect_panel,
            corner_radius,
            Color::rgba(220, 220, 220, 255),
            1,
        );

        // 3. Drag handle
        let handle_width: u32 = 36;
        let handle_height: u32 = 5;
        let handle_x = rect.x + (rect.width as i32 - handle_width as i32) / 2;
        let handle_y = sheet_y + 10;
        let handle_rect = Rect::new(handle_x, handle_y, handle_width, handle_height);
        context.fill_rounded_rect(handle_rect, handle_height / 2, Color::rgba(180, 180, 180, 200));

        // 4. Title
        let title_y = handle_y + handle_height as i32 + 12;
        let title_font = Font::simple("sans-serif", 16.0);
        let title_metrics = context.measure_text(&self.title, &title_font);
        if !self.title.is_empty() {
            let title_x = rect.x + (rect.width as i32 - title_metrics.width as i32) / 2;
            context.draw_text(
                Point::new(title_x.max(rect.x), title_y + title_metrics.ascent as i32),
                &self.title,
                &title_font,
                Color::rgba(30, 30, 30, 255),
                HorizontalAlignment::Left,
            );
        }

        // 5. Content area (child widget rendering is delegated)
        let content_top = title_y + title_metrics.height as i32 + 8;
        let content_bottom = rect.y + rect.height as i32 + drag_offset_px;
        let content_available = (content_bottom - content_top) as u32;

        if content_available > 20 {
            let content_rect = Rect::new(
                rect.x + 8,
                content_top,
                rect.width.saturating_sub(16),
                content_available,
            );
            context.fill_rect(content_rect, Color::WHITE);
        }
    }
}

impl EventHandler for ModalBottomSheet {
    fn handle_event(&mut self, event: &Event) {
        if !self.base.is_enabled() || !self.is_visible {
            return;
        }

        match event {
            Event::MousePress { pos, button } => {
                if *button == 1 {
                    let rect = self.geometry();
                    let sheet_height = self.compute_sheet_height();
                    let drag_offset_px = self.drag_offset as i32;
                    let sheet_y =
                        rect.y + rect.height as i32 - sheet_height as i32 + drag_offset_px;

                    // Check if click is in the sheet area (including drag handle area)
                    let in_sheet = pos.y >= sheet_y;

                    if in_sheet {
                        // Start potential drag
                        self.start_drag();
                    } else {
                        // Click on overlay — dismiss
                        self.is_visible = false;
                        self.dismissed.emit();
                        self.base.request_redraw();
                    }
                }
            }
            Event::MouseMove { pos: _ } => {
                // In a real integration, delta_y would be tracked from MousePress origin
            }
            Event::MouseRelease { pos: _, button } => {
                if *button == 1 && self.is_dragging {
                    self.end_drag();
                }
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Point;
    use crate::widget::svg::render_to_svg;
    use std::sync::atomic::{AtomicBool, Ordering};
    use std::sync::Arc;

    fn make_sheet() -> ModalBottomSheet {
        ModalBottomSheet::new(Rect::new(0, 0, 400, 600))
    }

    #[test]
    fn modal_bottom_sheet_default_state() {
        let sheet = make_sheet();
        assert!(!sheet.is_visible());
        assert_eq!(sheet.title(), "");
        assert_eq!(sheet.kind(), WidgetKind::ModalBottomSheet);
    }

    #[test]
    fn modal_bottom_sheet_show_and_hide() {
        let mut sheet = make_sheet();
        assert!(!sheet.is_visible());

        sheet.show();
        assert!(sheet.is_visible());

        sheet.hide();
        assert!(!sheet.is_visible());
    }

    #[test]
    fn modal_bottom_sheet_dismiss_signal_on_overlay_click() {
        let mut sheet = make_sheet();
        sheet.show();
        assert!(sheet.is_visible());

        let dismissed = Arc::new(AtomicBool::new(false));
        sheet.dismissed.connect({
            let d = Arc::clone(&dismissed);
            move || {
                d.store(true, Ordering::SeqCst);
            }
        });

        // Click above the sheet area (overlay region)
        // Sheet height is computed, but geometry is 600 tall so overlay is top portion
        sheet.handle_event(&Event::MousePress { pos: Point::new(200, 50), button: 1 });
        assert!(!sheet.is_visible());
        assert!(dismissed.load(Ordering::SeqCst));
    }

    #[test]
    fn modal_bottom_sheet_set_title() {
        let mut sheet = make_sheet();
        assert_eq!(sheet.title(), "");
        sheet.set_title("Options");
        assert_eq!(sheet.title(), "Options");
    }

    #[test]
    fn modal_bottom_sheet_drag_end_dismisses() {
        let mut sheet = make_sheet();
        sheet.show();
        assert!(sheet.is_visible());

        let dismissed = Arc::new(AtomicBool::new(false));
        sheet.dismissed.connect({
            let d = Arc::clone(&dismissed);
            move || {
                d.store(true, Ordering::SeqCst);
            }
        });

        // Start drag, push it past threshold, then release
        sheet.start_drag();
        assert!(sheet.is_dragging());

        // Push past 1/3 of sheet height (sheet is at least 120, so > 40)
        sheet.update_drag(80.0);
        assert_eq!(sheet.drag_offset(), 80.0);

        sheet.end_drag();
        assert!(!sheet.is_visible());
        assert!(dismissed.load(Ordering::SeqCst));
    }

    #[test]
    fn modal_bottom_sheet_drag_small_offset_no_dismiss() {
        let mut sheet = make_sheet();
        sheet.show();

        sheet.start_drag();
        sheet.update_drag(20.0);
        sheet.end_drag();

        // Small drag should not dismiss
        assert!(sheet.is_visible());
    }

    #[test]
    fn modal_bottom_sheet_svg_output_visible() {
        let mut sheet = make_sheet();
        sheet.set_title("Example");
        sheet.show();
        let svg = render_to_svg(&mut sheet);
        assert!(svg.starts_with("<svg"));
        assert!(svg.ends_with("</svg>"));
    }

    #[test]
    fn modal_bottom_sheet_svg_output_hidden() {
        let mut sheet = make_sheet();
        let svg = render_to_svg(&mut sheet);
        assert!(svg.starts_with("<svg"));
        assert!(svg.ends_with("</svg>"));
    }
}