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
//! A slider component with a glassmorphic visual style.
//!
//! ## Usage
//!
//! Use to select a value from a continuous range.
use std::sync::Arc;

use derive_builder::Builder;
use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
use tessera_ui::{
    Color, ComputedData, Constraint, CursorEventContent, DimensionValue, Dp, Px, PxPosition,
    accesskit::{Action, Role},
    focus_state::Focus,
    tessera,
    winit::window::CursorIcon,
};

use crate::{
    fluid_glass::{FluidGlassArgsBuilder, GlassBorder, fluid_glass},
    shape_def::Shape,
};

const ACCESSIBILITY_STEP: f32 = 0.05;

/// State for the `glass_slider` component.
pub(crate) struct GlassSliderStateInner {
    /// True if the user is currently dragging the slider.
    pub is_dragging: bool,
    /// The focus handler for the slider.
    pub focus: Focus,
}

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

impl GlassSliderStateInner {
    pub fn new() -> Self {
        Self {
            is_dragging: false,
            focus: Focus::new(),
        }
    }
}

#[derive(Clone)]
pub struct GlassSliderState {
    inner: Arc<RwLock<GlassSliderStateInner>>,
}

impl GlassSliderState {
    pub fn new() -> Self {
        Self {
            inner: Arc::new(RwLock::new(GlassSliderStateInner::new())),
        }
    }

    pub(crate) fn read(&self) -> RwLockReadGuard<'_, GlassSliderStateInner> {
        self.inner.read()
    }

    pub(crate) fn write(&self) -> RwLockWriteGuard<'_, GlassSliderStateInner> {
        self.inner.write()
    }

    /// Returns whether the slider thumb is currently being dragged.
    pub fn is_dragging(&self) -> bool {
        self.inner.read().is_dragging
    }

    /// Sets the dragging state manually. This allows custom gesture handling.
    pub fn set_dragging(&self, dragging: bool) {
        self.inner.write().is_dragging = dragging;
    }

    /// Requests focus for this slider instance.
    pub fn request_focus(&self) {
        self.inner.write().focus.request_focus();
    }

    /// Clears focus from this slider.
    pub fn clear_focus(&self) {
        self.inner.write().focus.unfocus();
    }

    /// Returns `true` if the slider currently has focus.
    pub fn is_focused(&self) -> bool {
        self.inner.read().focus.is_focused()
    }
}

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

/// Arguments for the `glass_slider` component.
#[derive(Builder, Clone)]
#[builder(pattern = "owned")]
pub struct GlassSliderArgs {
    /// The current value of the slider, ranging from 0.0 to 1.0.
    #[builder(default = "0.0")]
    pub value: f32,

    /// Callback function triggered when the slider's value changes.
    #[builder(default = "Arc::new(|_| {})")]
    pub on_change: Arc<dyn Fn(f32) + Send + Sync>,

    /// The width of the slider track.
    #[builder(default = "Dp(200.0)")]
    pub width: Dp,

    /// The height of the slider track.
    #[builder(default = "Dp(12.0)")]
    pub track_height: Dp,

    /// Glass tint color for the track background.
    #[builder(default = "Color::new(0.3, 0.3, 0.3, 0.15)")]
    pub track_tint_color: Color,

    /// Glass tint color for the progress fill.
    #[builder(default = "Color::new(0.5, 0.7, 1.0, 0.25)")]
    pub progress_tint_color: Color,

    /// Glass blur radius for all components.
    #[builder(default = "Dp(0.0)")]
    pub blur_radius: Dp,

    /// Border width for the track.
    #[builder(default = "Dp(1.0)")]
    pub track_border_width: Dp,

    /// Disable interaction.
    #[builder(default = "false")]
    pub disabled: bool,
    /// Optional accessibility label read by assistive technologies.
    #[builder(default, setter(strip_option, into))]
    pub accessibility_label: Option<String>,
    /// Optional accessibility description.
    #[builder(default, setter(strip_option, into))]
    pub accessibility_description: Option<String>,
}

/// Helper: check if a cursor position is inside a measured component area.
/// Extracted to reduce duplication and keep the input handler concise.
fn cursor_within_component(cursor_pos: Option<PxPosition>, computed: &ComputedData) -> bool {
    if let Some(pos) = cursor_pos {
        let within_x = pos.x.0 >= 0 && pos.x.0 < computed.width.0;
        let within_y = pos.y.0 >= 0 && pos.y.0 < computed.height.0;
        within_x && within_y
    } else {
        false
    }
}

/// Helper: compute normalized progress (0.0..1.0) from cursor X and width.
/// Returns None when cursor is not available.
fn cursor_progress(cursor_pos: Option<PxPosition>, width_f: f32) -> Option<f32> {
    cursor_pos.map(|pos| (pos.x.0 as f32 / width_f).clamp(0.0, 1.0))
}

/// Helper: compute progress fill width in Px, clamped to >= 0.
fn compute_progress_width(total_width: Px, value: f32, border_padding_px: f32) -> Px {
    let total_f = total_width.0 as f32;
    let mut w = total_f * value - border_padding_px;
    if w < 0.0 {
        w = 0.0;
    }
    Px(w as i32)
}

/// Process cursor events and update the slider state accordingly.
/// Returns the new value (0.0..1.0) if a change should be emitted.
fn process_cursor_events(
    state: &GlassSliderState,
    input: &tessera_ui::InputHandlerInput,
    width_f: f32,
) -> Option<f32> {
    let mut new_value: Option<f32> = None;

    for event in input.cursor_events.iter() {
        match &event.content {
            CursorEventContent::Pressed(_) => {
                {
                    let mut inner = state.write();
                    inner.focus.request_focus();
                    inner.is_dragging = true;
                }
                if let Some(v) = cursor_progress(input.cursor_position_rel, width_f) {
                    new_value = Some(v);
                }
            }
            CursorEventContent::Released(_) => {
                state.write().is_dragging = false;
            }
            _ => {}
        }
    }

    if state.read().is_dragging
        && let Some(v) = cursor_progress(input.cursor_position_rel, width_f)
    {
        new_value = Some(v);
    }

    new_value
}

/// # glass_slider
///
/// Renders an interactive slider with a customizable glass effect.
///
/// ## Usage
///
/// Allow users to select a value from a continuous range (0.0 to 1.0) by dragging a thumb.
///
/// ## Parameters
///
/// - `args` — configures the slider's value, appearance, and `on_change` callback; see [`GlassSliderArgs`].
/// - `state` — a clonable [`GlassSliderState`] to manage interaction state like dragging and focus.
///
/// ## Examples
///
/// ```
/// use std::sync::{Arc, Mutex};
/// use tessera_ui_basic_components::glass_slider::{
///     glass_slider, GlassSliderArgsBuilder, GlassSliderState,
/// };
///
/// // In a real app, this would be part of your application's state.
/// let slider_value = Arc::new(Mutex::new(0.5));
/// let slider_state = GlassSliderState::new();
///
/// let on_change = {
///     let slider_value = slider_value.clone();
///     Arc::new(move |new_value| {
///         *slider_value.lock().unwrap() = new_value;
///     })
/// };
///
/// let args = GlassSliderArgsBuilder::default()
///     .value(*slider_value.lock().unwrap())
///     .on_change(on_change)
///     .build()
///     .unwrap();
///
/// // The component would be called in the UI like this:
/// // glass_slider(args, slider_state);
///
/// // For the doctest, we can simulate the callback.
/// (args.on_change)(0.75);
/// assert_eq!(*slider_value.lock().unwrap(), 0.75);
/// ```
#[tessera]
pub fn glass_slider(args: impl Into<GlassSliderArgs>, state: GlassSliderState) {
    let args: GlassSliderArgs = args.into();
    let border_padding_px = args.track_border_width.to_px().to_f32() * 2.0;

    // External track (background) with border - capsule shape
    fluid_glass(
        FluidGlassArgsBuilder::default()
            .width(DimensionValue::Fixed(args.width.to_px()))
            .height(DimensionValue::Fixed(args.track_height.to_px()))
            .tint_color(args.track_tint_color)
            .blur_radius(args.blur_radius)
            .shape({
                let track_radius_dp = Dp(args.track_height.0 / 2.0);
                Shape::RoundedRectangle {
                    top_left: track_radius_dp,
                    top_right: track_radius_dp,
                    bottom_right: track_radius_dp,
                    bottom_left: track_radius_dp,
                    g2_k_value: 2.0, // Capsule shape
                }
            })
            .border(GlassBorder::new(args.track_border_width.into()))
            .padding(args.track_border_width)
            .build()
            .unwrap(),
        None,
        move || {
            // Internal progress fill - capsule shape using surface
            let progress_width_px =
                compute_progress_width(args.width.to_px(), args.value, border_padding_px);
            let effective_height = args.track_height.to_px().to_f32() - border_padding_px;
            fluid_glass(
                FluidGlassArgsBuilder::default()
                    .width(DimensionValue::Fixed(progress_width_px))
                    .height(DimensionValue::Fill {
                        min: None,
                        max: None,
                    })
                    .tint_color(args.progress_tint_color)
                    .shape({
                        let effective_height_dp = Dp::from_pixels_f32(effective_height);
                        let radius_dp = Dp(effective_height_dp.0 / 2.0);
                        Shape::RoundedRectangle {
                            top_left: radius_dp,
                            top_right: radius_dp,
                            bottom_right: radius_dp,
                            bottom_left: radius_dp,
                            g2_k_value: 2.0, // Capsule shape
                        }
                    })
                    .refraction_amount(0.0)
                    .build()
                    .unwrap(),
                None,
                || {},
            );
        },
    );

    let on_change = args.on_change.clone();
    let args_for_handler = args.clone();
    let state_for_handler = state.clone();
    input_handler(Box::new(move |mut input| {
        if !args_for_handler.disabled {
            let is_in_component =
                cursor_within_component(input.cursor_position_rel, &input.computed_data);

            if is_in_component {
                input.requests.cursor_icon = CursorIcon::Pointer;
            }

            if is_in_component || state_for_handler.read().is_dragging {
                let width_f = input.computed_data.width.0 as f32;

                if let Some(v) = process_cursor_events(&state_for_handler, &input, width_f)
                    && (v - args_for_handler.value).abs() > f32::EPSILON
                {
                    on_change(v);
                }
            }
        }

        apply_glass_slider_accessibility(
            &mut input,
            &args_for_handler,
            args_for_handler.value,
            &args_for_handler.on_change,
        );
    }));

    measure(Box::new(move |input| {
        let self_width = args.width.to_px();
        let self_height = args.track_height.to_px();

        let track_id = input.children_ids[0];

        // Measure track
        let track_constraint = Constraint::new(
            DimensionValue::Fixed(self_width),
            DimensionValue::Fixed(self_height),
        );
        input.measure_child(track_id, &track_constraint)?;
        input.place_child(track_id, PxPosition::new(Px(0), Px(0)));

        Ok(ComputedData {
            width: self_width,
            height: self_height,
        })
    }));
}

fn apply_glass_slider_accessibility(
    input: &mut tessera_ui::InputHandlerInput<'_>,
    args: &GlassSliderArgs,
    current_value: f32,
    on_change: &Arc<dyn Fn(f32) + Send + Sync>,
) {
    let mut builder = input.accessibility().role(Role::Slider);

    if let Some(label) = args.accessibility_label.as_ref() {
        builder = builder.label(label.clone());
    }
    if let Some(description) = args.accessibility_description.as_ref() {
        builder = builder.description(description.clone());
    }

    builder = builder
        .numeric_value(current_value as f64)
        .numeric_range(0.0, 1.0);

    if args.disabled {
        builder = builder.disabled();
    } else {
        builder = builder
            .action(Action::Increment)
            .action(Action::Decrement)
            .focusable();
    }

    builder.commit();

    if args.disabled {
        return;
    }

    let value_for_handler = current_value;
    let on_change = on_change.clone();
    input.set_accessibility_action_handler(move |action| {
        let new_value = match action {
            Action::Increment => Some((value_for_handler + ACCESSIBILITY_STEP).clamp(0.0, 1.0)),
            Action::Decrement => Some((value_for_handler - ACCESSIBILITY_STEP).clamp(0.0, 1.0)),
            _ => None,
        };

        if let Some(new_value) = new_value
            && (new_value - value_for_handler).abs() > f32::EPSILON
        {
            on_change(new_value);
        }
    });
}