tessera-ui-basic-components 2.7.0

Basic components for tessera-ui
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
//! A component that displays a side bar sliding in from the left.
//!
//! ## Usage
//!
//! Use to show app navigation or contextual controls.
use std::{
    sync::Arc,
    time::{Duration, Instant},
};

use derive_builder::Builder;
use parking_lot::RwLock;
use tessera_ui::{Color, DimensionValue, Dp, Px, PxPosition, tessera, winit};

use crate::{
    animation,
    fluid_glass::{FluidGlassArgsBuilder, fluid_glass},
    shape_def::Shape,
    surface::{SurfaceArgsBuilder, surface},
};

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

/// Defines the visual style of the side bar and its scrim.
///
/// The scrim is the overlay that appears behind the side bar, covering the main content.
#[derive(Default, Clone, Copy)]
pub enum SideBarStyle {
    /// A translucent glass effect that blurs the content behind it.
    /// This style may be more costly and is suitable when a blurred backdrop is desired.
    Glass,
    /// A simple, semi-transparent dark overlay. This is the default style.
    #[default]
    Material,
}

#[derive(Builder)]
pub struct SideBarProviderArgs {
    /// A callback that is invoked when the user requests to close the side bar.
    ///
    /// This can be triggered by clicking the scrim or pressing the `Escape` key.
    /// The callback is expected to call [`SideBarProviderState::close()`].
    pub on_close_request: Arc<dyn Fn() + Send + Sync>,
    /// The visual style used by the provider. See [`SideBarStyle`].
    #[builder(default)]
    pub style: SideBarStyle,
}

/// Manages the open/closed state of a [`side_bar_provider`].
///
/// This state object must be created by the application and passed to the
/// [`side_bar_provider`]. It is used to control the visibility of the side bar
/// programmatically. Clone the handle freely to share it across UI parts.
#[derive(Default)]
struct SideBarProviderStateInner {
    is_open: bool,
    timer: Option<Instant>,
}

#[derive(Clone, Default)]
pub struct SideBarProviderState {
    inner: Arc<RwLock<SideBarProviderStateInner>>,
}

impl SideBarProviderState {
    /// Creates a new handle. Equivalent to `Default::default()`.
    pub fn new() -> Self {
        Self::default()
    }

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

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

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

    /// Returns whether the side bar is currently animating.
    pub fn is_animating(&self) -> bool {
        self.inner
            .read()
            .timer
            .is_some_and(|t| t.elapsed() < ANIM_TIME)
    }

    fn snapshot(&self) -> (bool, Option<Instant>) {
        let inner = self.inner.read();
        (inner.is_open, inner.timer)
    }
}

/// 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.5
    } else {
        0.5 * (1.0 - progress)
    }
}

/// Compute X position for side bar placement.
fn compute_side_bar_x(child_width: Px, progress: f32, is_open: bool) -> i32 {
    let child = child_width.0 as f32;
    let x = if is_open {
        -child * (1.0 - progress)
    } else {
        -child * progress
    };
    x as i32
}

fn render_glass_scrim(args: &SideBarProviderArgs, 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(
        FluidGlassArgsBuilder::default()
            .on_click(args.on_close_request.clone())
            .tint_color(Color::TRANSPARENT)
            .width(DimensionValue::Fill {
                min: None,
                max: None,
            })
            .height(DimensionValue::Fill {
                min: None,
                max: None,
            })
            .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: Dp(0.0),
                top_right: Dp(0.0),
                bottom_right: Dp(0.0),
                bottom_left: Dp(0.0),
                g2_k_value: 3.0,
            })
            .noise_amount(0.0)
            .build()
            .unwrap(),
        None,
        || {},
    );
}

fn render_material_scrim(args: &SideBarProviderArgs, progress: f32, is_open: bool) {
    // Material scrim: compute alpha and render a simple dark surface.
    let scrim_alpha = scrim_alpha_for(progress, is_open);
    surface(
        SurfaceArgsBuilder::default()
            .style(Color::BLACK.with_alpha(scrim_alpha).into())
            .on_click(args.on_close_request.clone())
            .width(DimensionValue::Fill {
                min: None,
                max: None,
            })
            .height(DimensionValue::Fill {
                min: None,
                max: None,
            })
            .block_input(true)
            .build()
            .unwrap(),
        None,
        || {},
    );
}

/// 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: &SideBarProviderArgs, progress: f32, is_open: bool) {
    match args.style {
        SideBarStyle::Glass => render_glass_scrim(args, progress, is_open),
        SideBarStyle::Material => render_material_scrim(args, progress, is_open),
    }
}

/// Snapshot provider state to reduce lock duration and centralize access.
fn snapshot_state(state: &SideBarProviderState) -> (bool, Option<Instant>) {
    state.snapshot()
}

/// 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)();
            }
        }
    })
}

/// Place side bar if present. Extracted to reduce complexity of the parent function.
fn place_side_bar_if_present(
    input: &tessera_ui::MeasureInput<'_>,
    state_for_measure: &SideBarProviderState,
    progress: f32,
) {
    if input.children_ids.len() <= 2 {
        return;
    }

    let side_bar_id = input.children_ids[2];

    let child_size = match input.measure_child(side_bar_id, input.parent_constraint) {
        Ok(s) => s,
        Err(_) => return,
    };

    let current_is_open = state_for_measure.is_open();
    let x = compute_side_bar_x(child_size.width, progress, current_is_open);
    input.place_child(side_bar_id, PxPosition::new(Px(x), Px(0)));
}

/// # side_bar_provider
///
/// Provides a side bar that slides in from the left, with a scrim overlay.
///
/// ## Usage
///
/// Use as a top-level provider to display a navigation drawer or other contextual side content.
///
/// ## Parameters
///
/// - `args` — configures the side bar's style and `on_close_request` callback; see [`SideBarProviderArgs`].
/// - `state` — a clonable [`SideBarProviderState`] to manage the open/closed state.
/// - `main_content` — a closure that renders the main UI, which is visible behind the side bar.
/// - `side_bar_content` — a closure that renders the content of the side bar itself.
///
/// ## Examples
///
/// ```
/// use tessera_ui_basic_components::side_bar::SideBarProviderState;
///
/// let state = SideBarProviderState::new();
/// assert!(!state.is_open());
///
/// state.open();
/// assert!(state.is_open());
///
/// state.close();
/// assert!(!state.is_open());
/// ```
#[tessera]
pub fn side_bar_provider(
    args: SideBarProviderArgs,
    state: SideBarProviderState,
    main_content: impl FnOnce() + Send + Sync + 'static,
    side_bar_content: impl FnOnce() + Send + Sync + 'static,
) {
    // Render main content first.
    main_content();

    // Snapshot state once to minimize locking overhead.
    let (is_open, timer_opt) = snapshot_state(&state);

    // Fast exit when nothing to render.
    if !(is_open || timer_opt.is_some_and(|t| t.elapsed() < ANIM_TIME)) {
        return;
    }

    // Prepare values used by rendering and placement.
    let on_close_for_keyboard = args.on_close_request.clone();
    let progress = calc_progress_from_timer(timer_opt.as_ref());

    // Render the configured scrim.
    render_scrim(&args, progress, is_open);

    // Register keyboard handler (close on Escape).
    let keyboard_closure = make_keyboard_closure(on_close_for_keyboard);
    input_handler(keyboard_closure);

    // Render side bar content with computed alpha.
    side_bar_content_wrapper(args.style, side_bar_content);

    // Measurement: place main content, scrim and side bar.
    let state_for_measure = state.clone();
    let measure_closure = Box::new(move |input: &tessera_ui::MeasureInput<'_>| {
        // Place main content at origin.
        let main_content_id = input.children_ids[0];
        let main_content_size = input.measure_child(main_content_id, input.parent_constraint)?;
        input.place_child(main_content_id, PxPosition::new(Px(0), Px(0)));

        // Place scrim (if present) covering the whole parent.
        if input.children_ids.len() > 1 {
            let scrim_id = input.children_ids[1];
            input.measure_child(scrim_id, input.parent_constraint)?;
            input.place_child(scrim_id, PxPosition::new(Px(0), Px(0)));
        }

        // Place side bar (if present) using extracted helper.
        place_side_bar_if_present(input, &state_for_measure, progress);

        // Return the main content size (best-effort; unwrap used above to satisfy closure type).
        Ok(main_content_size)
    });
    measure(measure_closure);
}

#[tessera]
fn side_bar_content_wrapper(style: SideBarStyle, content: impl FnOnce() + Send + Sync + 'static) {
    match style {
        SideBarStyle::Glass => {
            fluid_glass(
                FluidGlassArgsBuilder::default()
                    .shape(Shape::RoundedRectangle {
                        top_left: Dp(0.0),
                        top_right: Dp(25.0),
                        bottom_right: Dp(25.0),
                        bottom_left: Dp(0.0),
                        g2_k_value: 3.0,
                    })
                    .tint_color(Color::new(0.6, 0.8, 1.0, 0.3))
                    .width(DimensionValue::from(Dp(250.0)))
                    .height(tessera_ui::DimensionValue::Fill {
                        min: None,
                        max: None,
                    })
                    .blur_radius(Dp(10.0))
                    .padding(Dp(16.0))
                    .block_input(true)
                    .build()
                    .unwrap(),
                None,
                content,
            );
        }
        SideBarStyle::Material => {
            surface(
                SurfaceArgsBuilder::default()
                    .style(Color::new(0.9, 0.9, 0.9, 1.0).into())
                    .width(DimensionValue::from(Dp(250.0)))
                    .height(tessera_ui::DimensionValue::Fill {
                        min: None,
                        max: None,
                    })
                    .padding(Dp(16.0))
                    .shape(Shape::RoundedRectangle {
                        top_left: Dp(0.0),
                        top_right: Dp(25.0),
                        bottom_right: Dp(25.0),
                        bottom_left: Dp(0.0),
                        g2_k_value: 3.0,
                    })
                    .block_input(true)
                    .build()
                    .unwrap(),
                None,
                content,
            );
        }
    }
}