tessera-components 0.0.0

Basic components for tessera-ui, using md3e design principles.
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! A component that displays content sliding up from the bottom of the screen.
//!
//! ## Usage
//!
//! Used to show contextual information or actions in a modal sheet.
use std::{
    sync::Arc,
    time::{Duration, Instant},
};

use derive_setters::Setters;
use tessera_ui::{
    Color, ComputedData, Constraint, CursorEventContent, DimensionValue, Dp, MeasurementError,
    Modifier, PressKeyEventType, Px, PxPosition, State,
    layout::{LayoutInput, LayoutOutput, LayoutSpec},
    remember, tessera, use_context, winit,
};

use crate::{
    alignment::CrossAxisAlignment,
    animation,
    column::{ColumnArgs, column},
    fluid_glass::{FluidGlassArgs, fluid_glass},
    modifier::ModifierExt,
    shape_def::{RoundedCorner, Shape},
    spacer::spacer,
    surface::{SurfaceArgs, surface},
    theme::MaterialTheme,
};

const ANIM_TIME: Duration = Duration::from_millis(300);

/// Defines the visual style of the bottom sheet's scrim.
///
/// The scrim is the overlay that appears behind the bottom sheet, covering the
/// main content.
#[derive(Default, Clone, Copy)]
pub enum BottomSheetStyle {
    /// A translucent glass effect that blurs the content behind it.
    /// This style is more resource-intensive and may not be suitable for all
    /// targets.
    Glass,
    /// A simple, semi-transparent dark overlay. This is the default style.
    #[default]
    Material,
}

/// Configuration arguments for the [`bottom_sheet_provider`].
#[derive(Setters)]
pub struct BottomSheetProviderArgs {
    /// A callback that is invoked when the user requests to close the sheet.
    ///
    /// This can be triggered by clicking the scrim or pressing the `Escape`
    /// key. The callback is responsible for closing the sheet.
    #[setters(skip)]
    pub on_close_request: Arc<dyn Fn() + Send + Sync>,
    /// The visual style of the scrim. See [`BottomSheetStyle`].
    pub style: BottomSheetStyle,
    /// Whether the sheet is initially open (for declarative usage).
    pub is_open: bool,
}

impl BottomSheetProviderArgs {
    /// Create args with a required close-request callback.
    pub fn new(on_close_request: impl Fn() + Send + Sync + 'static) -> Self {
        Self {
            on_close_request: Arc::new(on_close_request),
            style: BottomSheetStyle::default(),
            is_open: false,
        }
    }

    /// Set the close-request callback.
    pub fn on_close_request<F>(mut self, on_close_request: F) -> Self
    where
        F: Fn() + Send + Sync + 'static,
    {
        self.on_close_request = Arc::new(on_close_request);
        self
    }

    /// Set the close-request callback using a shared callback.
    pub fn on_close_request_shared(
        mut self,
        on_close_request: Arc<dyn Fn() + Send + Sync>,
    ) -> Self {
        self.on_close_request = on_close_request;
        self
    }
}

/// Controller for [`bottom_sheet_provider`], managing open/closed state.
///
/// This controller can be created by the application and passed to the
/// [`bottom_sheet_provider_with_controller`]. It is used to control the
/// visibility of the sheet programmatically.
#[derive(Clone)]
pub struct BottomSheetController {
    is_open: bool,
    timer: Option<Instant>,
    is_dragging: bool,
    drag_offset: f32,
    drag_start_y: f32,
}

impl BottomSheetController {
    /// Creates a new controller.
    pub fn new(initial_open: bool) -> Self {
        Self {
            is_open: initial_open,
            timer: None,
            is_dragging: false,
            drag_offset: 0.0,
            drag_start_y: 0.0,
        }
    }

    /// Initiates the animation to open the bottom sheet.
    ///
    /// If the sheet is already open, this has no effect. If the sheet is
    /// currently closing, it will reverse direction and start opening from
    /// its current position.
    pub fn open(&mut self) {
        if !self.is_open {
            self.is_open = true;
            self.drag_offset = 0.0;
            let mut timer = Instant::now();
            if let Some(old_timer) = self.timer {
                let elapsed = old_timer.elapsed();
                if elapsed < ANIM_TIME {
                    timer += ANIM_TIME - elapsed;
                }
            }
            self.timer = Some(timer);
        }
    }

    /// Initiates the animation to close the bottom sheet.
    ///
    /// If the sheet is already closed, this has no effect. If the sheet is
    /// currently opening, it will reverse direction and start closing from
    /// its current position.
    pub fn close(&mut self) {
        if self.is_open {
            self.is_open = false;
            let mut timer = Instant::now();
            if let Some(old_timer) = self.timer {
                let elapsed = old_timer.elapsed();
                if elapsed < ANIM_TIME {
                    timer += ANIM_TIME - elapsed;
                }
            }
            self.timer = Some(timer);
        }
    }

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

    /// Returns whether the sheet is currently animating in either direction.
    pub fn is_animating(&self) -> bool {
        self.timer.is_some_and(|t| t.elapsed() < ANIM_TIME)
    }

    fn snapshot(&self) -> (bool, Option<Instant>, f32) {
        (self.is_open, self.timer, self.drag_offset)
    }

    fn set_dragging(&mut self, dragging: bool) {
        self.is_dragging = dragging;
    }

    fn update_drag_offset(&mut self, offset: f32) {
        self.drag_offset = offset;
    }

    fn get_drag_offset(&self) -> f32 {
        self.drag_offset
    }

    fn is_dragging(&self) -> bool {
        self.is_dragging
    }

    fn set_drag_start_y(&mut self, y: f32) {
        self.drag_start_y = y;
    }

    fn get_drag_start_y(&self) -> f32 {
        self.drag_start_y
    }
}

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

/// Compute eased progress from an optional timer reference.
fn calc_progress_from_timer(timer: Option<&Instant>) -> f32 {
    let raw = match timer {
        None => 1.0,
        Some(t) => {
            let elapsed = t.elapsed();
            if elapsed >= ANIM_TIME {
                1.0
            } else {
                elapsed.as_secs_f32() / ANIM_TIME.as_secs_f32()
            }
        }
    };
    animation::easing(raw)
}

/// Compute blur radius for glass style.
fn blur_radius_for(progress: f32, is_open: bool, max_blur_radius: f32) -> f32 {
    if is_open {
        progress * max_blur_radius
    } else {
        max_blur_radius * (1.0 - progress)
    }
}

/// Compute scrim alpha for material style.
fn scrim_alpha_for(progress: f32, is_open: bool) -> f32 {
    if is_open {
        progress * 0.32
    } else {
        0.32 * (1.0 - progress)
    }
}

/// Compute Y position for bottom sheet placement.
fn compute_bottom_sheet_y(
    parent_height: Px,
    child_height: Px,
    progress: f32,
    is_open: bool,
    drag_offset: f32,
) -> i32 {
    let parent = parent_height.0 as f32;
    let child = child_height.0 as f32;
    let y = if is_open {
        parent - child * progress
    } else {
        parent - child * (1.0 - progress)
    };
    (y + drag_offset) as i32
}

fn render_glass_scrim(args: &BottomSheetProviderArgs, progress: f32, is_open: bool) {
    // Glass scrim: compute blur radius and render using fluid_glass.
    let max_blur_radius = 5.0;
    let blur_radius = blur_radius_for(progress, is_open, max_blur_radius);
    fluid_glass(
        FluidGlassArgs::default()
            .on_click_shared(args.on_close_request.clone())
            .tint_color(Color::TRANSPARENT)
            .modifier(Modifier::new().fill_max_size())
            .dispersion_height(Dp(0.0))
            .refraction_height(Dp(0.0))
            .block_input(true)
            .blur_radius(Dp(blur_radius as f64))
            .border(None)
            .shape(Shape::RoundedRectangle {
                top_left: RoundedCorner::manual(Dp(0.0), 3.0),
                top_right: RoundedCorner::manual(Dp(0.0), 3.0),
                bottom_right: RoundedCorner::manual(Dp(0.0), 3.0),
                bottom_left: RoundedCorner::manual(Dp(0.0), 3.0),
            })
            .noise_amount(0.0),
        || {},
    );
}

fn render_material_scrim(args: &BottomSheetProviderArgs, progress: f32, is_open: bool) {
    // Material scrim: compute alpha and render a simple dark surface.
    let scrim_alpha = scrim_alpha_for(progress, is_open);
    let scrim_color = use_context::<MaterialTheme>()
        .expect("MaterialTheme must be provided")
        .get()
        .color_scheme
        .scrim;
    surface(
        SurfaceArgs::default()
            .style(scrim_color.with_alpha(scrim_alpha).into())
            .on_click_shared(args.on_close_request.clone())
            .modifier(Modifier::new().fill_max_size())
            .block_input(true),
        || {},
    );
}

/// Render scrim according to configured style.
/// Delegates actual rendering to small, focused helpers to keep the
/// main API surface concise and improve readability.
fn render_scrim(args: &BottomSheetProviderArgs, progress: f32, is_open: bool) {
    match args.style {
        BottomSheetStyle::Glass => render_glass_scrim(args, progress, is_open),
        BottomSheetStyle::Material => render_material_scrim(args, progress, is_open),
    }
}

/// Create the keyboard handler closure used to close the sheet on Escape.
fn make_keyboard_closure(
    on_close: Arc<dyn Fn() + Send + Sync>,
) -> Box<dyn Fn(tessera_ui::InputHandlerInput<'_>) + Send + Sync> {
    Box::new(move |input: tessera_ui::InputHandlerInput<'_>| {
        for event in input.keyboard_events.drain(..) {
            if event.state == winit::event::ElementState::Pressed
                && let winit::keyboard::PhysicalKey::Code(winit::keyboard::KeyCode::Escape) =
                    event.physical_key
            {
                (on_close)();
            }
        }
    })
}

/// Handle drag gestures on the bottom sheet.
fn handle_drag_gestures(
    controller: State<BottomSheetController>,
    input: &mut tessera_ui::InputHandlerInput<'_>,
    on_close: &Arc<dyn Fn() + Send + Sync>,
) {
    let mut is_dragging = controller.with(|c| c.is_dragging());
    let drag_offset = controller.with(|c| c.get_drag_offset());

    for event in input.cursor_events.iter() {
        match &event.content {
            CursorEventContent::Pressed(PressKeyEventType::Left) => {
                if let Some(pos) = input.cursor_position_rel {
                    is_dragging = true;
                    controller.with_mut(|c| {
                        c.set_dragging(true);
                        c.set_drag_start_y(pos.y.0 as f32);
                    });
                }
            }
            CursorEventContent::Released(PressKeyEventType::Left) => {
                if is_dragging {
                    is_dragging = false;
                    controller.with_mut(|c| c.set_dragging(false));

                    if drag_offset > 100.0 {
                        (on_close)();
                    } else {
                        controller.with_mut(|c| c.update_drag_offset(0.0));
                    }
                }
            }
            _ => {}
        }
    }

    if is_dragging && let Some(pos) = input.cursor_position_rel {
        let current_y = pos.y.0 as f32;
        let start_y = controller.with(|c| c.get_drag_start_y());
        let delta = current_y - start_y;

        // Accumulate delta since component moves with drag.
        let new_offset = (drag_offset + delta).max(0.0);
        if (new_offset - drag_offset).abs() > 0.001 {
            controller.with_mut(|c| c.update_drag_offset(new_offset));
        }
    }
}

/// Place bottom sheet if present. Extracted to reduce complexity of the parent
/// function.
fn place_bottom_sheet_if_present(
    input: &LayoutInput<'_>,
    output: &mut LayoutOutput<'_>,
    is_open: bool,
    drag_offset: f32,
    progress: f32,
) {
    if input.children_ids().len() <= 2 {
        return;
    }

    let bottom_sheet_id = input.children_ids()[2];

    let parent_width = input.parent_constraint().width().get_max().unwrap_or(Px(0));
    let parent_height = input
        .parent_constraint()
        .height()
        .get_max()
        .unwrap_or(Px(0));

    // M3 Spec: Max width 640dp.
    let max_width_px = Dp(640.0).to_px();
    let is_large_screen = parent_width >= max_width_px;

    let sheet_width = if is_large_screen {
        max_width_px
    } else {
        parent_width
    };

    // M3 Spec: Top margin 56dp or 72dp.
    let top_margin = if is_large_screen {
        Dp(56.0).to_px()
    } else {
        Dp(72.0).to_px()
    };
    let max_height = (parent_height - top_margin).max(Px(0));

    let constraint = Constraint {
        width: DimensionValue::Fixed(sheet_width),
        height: DimensionValue::Wrap {
            min: None,
            max: Some(max_height),
        },
    };

    let child_size = match input.measure_child(bottom_sheet_id, &constraint) {
        Ok(s) => s,
        Err(_) => return,
    };

    let y = compute_bottom_sheet_y(
        parent_height,
        child_size.height,
        progress,
        is_open,
        drag_offset,
    );

    let x = if is_large_screen {
        (parent_width - child_size.width) / 2
    } else {
        Px(0)
    };

    output.place_child(bottom_sheet_id, PxPosition::new(x, Px(y)));
}

#[derive(Clone)]
struct DragHandlerArgs {
    controller: State<BottomSheetController>,
    on_close: Arc<dyn Fn() + Send + Sync>,
}

#[tessera]
fn drag_handler(args: DragHandlerArgs, child: impl FnOnce() + Send + Sync + 'static) {
    let controller = args.controller;
    let on_close = args.on_close;

    input_handler(move |mut input| {
        handle_drag_gestures(controller, &mut input, &on_close);
    });

    child();
}

fn render_content(
    style: BottomSheetStyle,
    bottom_sheet_content: impl FnOnce() + Send + Sync + 'static,
    controller: State<BottomSheetController>,
    on_close: Arc<dyn Fn() + Send + Sync>,
) {
    let content_wrapper = move || {
        drag_handler(
            DragHandlerArgs {
                controller,
                on_close: on_close.clone(),
            },
            || {
                column(
                    ColumnArgs::default()
                        .modifier(Modifier::new().fill_max_width())
                        .cross_axis_alignment(CrossAxisAlignment::Center),
                    |scope| {
                        scope.child(|| {
                            spacer(Modifier::new().height(Dp(22.0)));
                        });
                        scope.child(|| {
                            surface(
                                SurfaceArgs::default()
                                    .style(
                                        use_context::<MaterialTheme>()
                                            .expect("MaterialTheme must be provided")
                                            .get()
                                            .color_scheme
                                            .on_surface_variant
                                            .with_alpha(0.4)
                                            .into(),
                                    )
                                    .shape(Shape::capsule())
                                    .modifier(Modifier::new().size(Dp(32.0), Dp(4.0))),
                                || {},
                            );
                        });
                        scope.child(|| {
                            spacer(Modifier::new().height(Dp(22.0)));
                        });

                        scope.child(bottom_sheet_content);
                    },
                );
            },
        );
    };
    match style {
        BottomSheetStyle::Glass => {
            fluid_glass(
                FluidGlassArgs::default()
                    .shape(Shape::RoundedRectangle {
                        top_left: RoundedCorner::manual(Dp(28.0), 3.0),
                        top_right: RoundedCorner::manual(Dp(28.0), 3.0),
                        bottom_right: RoundedCorner::manual(Dp(0.0), 3.0),
                        bottom_left: RoundedCorner::manual(Dp(0.0), 3.0),
                    })
                    .tint_color(Color::WHITE.with_alpha(0.4))
                    .modifier(Modifier::new().fill_max_width())
                    .refraction_amount(32.0)
                    .blur_radius(Dp(5.0))
                    .block_input(true),
                content_wrapper,
            );
        }
        BottomSheetStyle::Material => {
            surface(
                SurfaceArgs::default()
                    .style(
                        use_context::<MaterialTheme>()
                            .expect("MaterialTheme must be provided")
                            .get()
                            .color_scheme
                            .surface_container_low
                            .into(),
                    )
                    .shape(Shape::RoundedRectangle {
                        top_left: RoundedCorner::manual(Dp(28.0), 3.0),
                        top_right: RoundedCorner::manual(Dp(28.0), 3.0),
                        bottom_right: RoundedCorner::manual(Dp(0.0), 3.0),
                        bottom_left: RoundedCorner::manual(Dp(0.0), 3.0),
                    })
                    .modifier(Modifier::new().fill_max_width())
                    .block_input(true),
                content_wrapper,
            );
        }
    }
}

/// # bottom_sheet_provider
///
/// Provides a modal bottom sheet for contextual actions or information.
///
/// # Usage
///
/// Show contextual menus, supplemental information, or simple forms without
/// navigating away from the main screen.
///
/// ## Parameters
///
/// - `args` — configuration for the sheet's appearance and behavior; see
///   [`BottomSheetProviderArgs`].
/// - `main_content` — closure that renders the always-visible base UI.
/// - `bottom_sheet_content` — closure that renders the content of the sheet
///   itself.
///
/// # Examples
///
/// ```
/// # use tessera_ui::tessera;
/// # #[tessera]
/// # fn component() {
/// use tessera_components::bottom_sheet::{BottomSheetProviderArgs, bottom_sheet_provider};
/// # use tessera_components::theme::{MaterialTheme, material_theme};
///
/// # material_theme(|| MaterialTheme::default(), || {
/// bottom_sheet_provider(
///     BottomSheetProviderArgs::new(|| {}).is_open(true),
///     || { /* main content */ },
///     || { /* bottom sheet content */ },
/// );
/// # });
/// # }
/// # component();
/// ```
#[tessera]
pub fn bottom_sheet_provider(
    args: impl Into<BottomSheetProviderArgs>,
    main_content: impl FnOnce() + Send + Sync + 'static,
    bottom_sheet_content: impl FnOnce() + Send + Sync + 'static,
) {
    let args: BottomSheetProviderArgs = args.into();
    let controller = remember(|| BottomSheetController::new(args.is_open));

    let current_open = controller.with(|c| c.is_open());
    if args.is_open != current_open {
        if args.is_open {
            controller.with_mut(|c| c.open());
        } else {
            controller.with_mut(|c| c.close());
        }
    }

    bottom_sheet_provider_with_controller(args, controller, main_content, bottom_sheet_content);
}

/// # bottom_sheet_provider_with_controller
///
/// Controlled version of [`bottom_sheet_provider`] that accepts an external
/// controller.
///
/// # Usage
///
/// Show contextual menus, supplemental information, or simple forms without
/// navigating away from the main screen. And also need to control the sheet's
/// open/closed state programmatically via a controller.
///
/// # Parameters
///
/// - `args` — configuration for the sheet's appearance and behavior; see
///   [`BottomSheetProviderArgs`].
/// - `controller` — a [`BottomSheetController`] used to open and close the
///   sheet.
/// - `main_content` — closure that renders the always-visible base UI.
/// - `bottom_sheet_content` — closure that renders the content of the sheet
///   itself.
#[tessera]
pub fn bottom_sheet_provider_with_controller(
    args: impl Into<BottomSheetProviderArgs>,
    controller: State<BottomSheetController>,
    main_content: impl FnOnce() + Send + Sync + 'static,
    bottom_sheet_content: impl FnOnce() + Send + Sync + 'static,
) {
    let args: BottomSheetProviderArgs = args.into();

    main_content();

    // Snapshot state to minimize locking overhead.
    let (is_open, timer_opt, drag_offset) = controller.with(|c| c.snapshot());

    if !(is_open || timer_opt.is_some_and(|t| t.elapsed() < ANIM_TIME)) {
        return;
    }

    let on_close_for_keyboard = args.on_close_request.clone();
    let progress = calc_progress_from_timer(timer_opt.as_ref());

    render_scrim(&args, progress, is_open);

    let keyboard_closure = make_keyboard_closure(on_close_for_keyboard);
    input_handler(keyboard_closure);

    render_content(
        args.style,
        bottom_sheet_content,
        controller,
        args.on_close_request.clone(),
    );

    layout(BottomSheetLayout {
        progress,
        is_open,
        drag_offset,
    });
}

#[derive(Clone, PartialEq)]
struct BottomSheetLayout {
    progress: f32,
    is_open: bool,
    drag_offset: f32,
}

impl LayoutSpec for BottomSheetLayout {
    fn measure(
        &self,
        input: &LayoutInput<'_>,
        output: &mut LayoutOutput<'_>,
    ) -> Result<ComputedData, MeasurementError> {
        let main_content_id = input.children_ids()[0];
        let main_content_size = input.measure_child_in_parent_constraint(main_content_id)?;
        output.place_child(main_content_id, PxPosition::new(Px(0), Px(0)));

        if input.children_ids().len() > 1 {
            let scrim_id = input.children_ids()[1];
            input.measure_child_in_parent_constraint(scrim_id)?;
            output.place_child(scrim_id, PxPosition::new(Px(0), Px(0)));
        }

        place_bottom_sheet_if_present(input, output, self.is_open, self.drag_offset, self.progress);

        Ok(main_content_size)
    }
}