yororen_ui 0.2.0

Reusable UI components and widgets built on top of gpui.
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
use std::sync::Arc;

use gpui::{
    AppContext, Bounds, Div, Element, ElementId, Empty, GlobalElementId, Hsla, InspectorElementId,
    InteractiveElement, IntoElement, LayoutId, MouseButton, MouseDownEvent, ParentElement,
    RenderOnce, StatefulInteractiveElement, Styled, px, relative,
};

use gpui::prelude::FluentBuilder;

use crate::{component::create_internal_state, theme::ActiveTheme};

/// Creates a new slider element.
///
/// Sliders allow users to select a value from a range by dragging a thumb.
/// Use `.range(min, max)` to set the value range, and `.on_change()` to receive value updates.
///
/// # Example
/// ```rust,ignore
/// use yororen_ui::component::slider;
///
/// let s = slider("my-slider")
///     .range(0.0, 100.0)
///     .value(50.0)
///     .on_change(|value, _window, _cx| {
///         println!("Slider value: {}", value);
///     });
/// ```
pub fn slider(id: impl Into<ElementId>) -> Slider {
    Slider::new().id(id)
}

type ChangeFn = Arc<dyn Fn(f32, &mut gpui::Window, &mut gpui::App)>;

struct TrackBoundsElement {
    bounds_state: gpui::Entity<Bounds<gpui::Pixels>>,
    inner: gpui::AnyElement,
}

impl IntoElement for TrackBoundsElement {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl Element for TrackBoundsElement {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        window: &mut gpui::Window,
        cx: &mut gpui::App,
    ) -> (LayoutId, Self::RequestLayoutState) {
        (self.inner.request_layout(window, cx), ())
    }

    fn prepaint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        bounds: Bounds<gpui::Pixels>,
        _request_layout: &mut Self::RequestLayoutState,
        window: &mut gpui::Window,
        cx: &mut gpui::App,
    ) -> Self::PrepaintState {
        self.bounds_state.update(cx, |state, _| {
            *state = bounds;
        });
        self.inner.prepaint(window, cx);
    }

    fn paint(
        &mut self,
        _id: Option<&GlobalElementId>,
        _inspector_id: Option<&InspectorElementId>,
        _bounds: Bounds<gpui::Pixels>,
        _request_layout: &mut Self::RequestLayoutState,
        _prepaint: &mut Self::PrepaintState,
        window: &mut gpui::Window,
        cx: &mut gpui::App,
    ) {
        self.inner.paint(window, cx);
    }
}

#[derive(IntoElement)]
pub struct Slider {
    element_id: ElementId,
    base: Div,

    min: f32,
    max: f32,
    step: Option<f32>,
    value: Option<f32>,
    default_value: Option<f32>,

    disabled: bool,

    height: Option<gpui::AbsoluteLength>,
    bg: Option<Hsla>,
    fill_color: Option<Hsla>,
    border: Option<Hsla>,
    focus_border: Option<Hsla>,

    on_change: Option<ChangeFn>,
}

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

impl Slider {
    pub fn new() -> Self {
        Self {
            element_id: "ui:slider".into(),
            base: gpui::div(),

            min: 0.0,
            max: 1.0,
            step: None,
            value: None,
            default_value: None,

            disabled: false,

            height: None,
            bg: None,
            fill_color: None,
            border: None,
            focus_border: None,

            on_change: None,
        }
    }

    pub fn id(mut self, id: impl Into<ElementId>) -> Self {
        self.element_id = id.into();
        self
    }

    pub fn key(self, key: impl Into<ElementId>) -> Self {
        self.id(key)
    }

    pub fn range(mut self, min: f32, max: f32) -> Self {
        assert!(
            min < max,
            "Slider range: min ({min}) must be less than max ({max})"
        );
        self.min = min;
        self.max = max;
        self
    }

    pub fn step(mut self, step: f32) -> Self {
        assert!(step > 0.0, "Slider step must be greater than 0");
        self.step = Some(step);
        self
    }

    pub fn value(mut self, value: f32) -> Self {
        self.value = Some(value);
        self
    }

    pub fn default_value(mut self, default_value: f32) -> Self {
        self.default_value = Some(default_value);
        self
    }

    pub fn disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn height(mut self, height: gpui::AbsoluteLength) -> Self {
        self.height = Some(height);
        self
    }

    pub fn bg(mut self, color: impl Into<Hsla>) -> Self {
        self.bg = Some(color.into());
        self
    }

    pub fn fill(mut self, color: impl Into<Hsla>) -> Self {
        self.fill_color = Some(color.into());
        self
    }

    pub fn border(mut self, color: impl Into<Hsla>) -> Self {
        self.border = Some(color.into());
        self
    }

    pub fn focus_border(mut self, color: impl Into<Hsla>) -> Self {
        self.focus_border = Some(color.into());
        self
    }

    pub fn on_change<F>(mut self, handler: F) -> Self
    where
        F: 'static + Fn(f32, &mut gpui::Window, &mut gpui::App),
    {
        self.on_change = Some(Arc::new(handler));
        self
    }
}

impl ParentElement for Slider {
    fn extend(&mut self, elements: impl IntoIterator<Item = gpui::AnyElement>) {
        self.base.extend(elements);
    }
}

impl Styled for Slider {
    fn style(&mut self) -> &mut gpui::StyleRefinement {
        self.base.style()
    }
}

impl InteractiveElement for Slider {
    fn interactivity(&mut self) -> &mut gpui::Interactivity {
        self.base.interactivity()
    }
}

impl StatefulInteractiveElement for Slider {}

impl RenderOnce for Slider {
    fn render(self, window: &mut gpui::Window, cx: &mut gpui::App) -> impl IntoElement {
        // Slider requires an element ID for keyed state management.
        // Use `.id()` to provide a stable ID, or a unique ID will be generated automatically.
        let id = self.element_id;

        let disabled = self.disabled;
        let theme = cx.theme().clone();
        let height = self.height.unwrap_or_else(|| px(36.).into());

        // Slider has no outer container background; `bg_color` controls the track color instead.
        let track_bg = if disabled {
            theme.surface.sunken
        } else {
            self.bg.unwrap_or(theme.surface.sunken)
        };

        let fill = if disabled {
            theme.content.disabled
        } else {
            self.fill_color.unwrap_or(theme.action.primary.bg)
        };

        let min = self.min;
        let max = self.max;
        let step = self.step;

        let on_change = self.on_change;
        let external_value = self.value;
        let default_value = self.default_value;

        // Determine if this is controlled mode (external value provided)
        let is_controlled = external_value.is_some();

        // Determine initial value for internal state
        // Use default_value if provided, otherwise use min
        let initial_value = default_value.unwrap_or(min);

        // Create internal state for drag/click interactions
        // In controlled mode, we still create it but don't update it
        let internal_value = create_internal_state(
            window,
            cx,
            &id,
            "ui:slider:value".to_string(),
            initial_value,
            true,
        )
        .expect("internal_value should always be created");

        // Use external value if provided (controlled), otherwise use internal value (uncontrolled)
        let mut value = external_value.unwrap_or(*internal_value.read(cx));

        value = clamp(value, min.min(max), max.max(min));
        let t = if (max - min).abs() <= f32::EPSILON {
            0.0
        } else {
            clamp((value - min) / (max - min), 0.0, 1.0)
        };

        let knob_diameter = 16.0;
        let track_height = 6.0;

        let track_bounds_state =
            window.use_keyed_state((id.clone(), "ui:slider:track-bounds"), cx, |_, _| {
                Bounds::default()
            });

        let set_from_mouse_x = {
            let internal_value = internal_value.clone();
            let on_change = on_change.clone();
            move |x: f32,
                  bounds: Bounds<gpui::Pixels>,
                  window: &mut gpui::Window,
                  cx: &mut gpui::App| {
                if bounds.size.width <= px(1.) {
                    return;
                }
                let left: f32 = bounds.left().into();
                let width: f32 = bounds.size.width.into();
                let mut ratio = (x - left) / width;
                ratio = clamp(ratio, 0.0, 1.0);

                let mut new_value = min + (max - min) * ratio;
                if let Some(step) = step.filter(|s| *s > 0.0) {
                    new_value = quantize(new_value, min, step);
                }
                new_value = clamp(new_value, min.min(max), max.max(min));

                // Only update internal state in uncontrolled mode
                // In controlled mode, external value controls the display
                if !is_controlled {
                    internal_value.update(cx, |state, cx| {
                        *state = new_value;
                        cx.notify();
                    });
                }
                if let Some(handler) = &on_change {
                    handler(new_value, window, cx);
                }
            }
        };

        let mut base = self
            .base
            .id(id.clone())
            .h(height)
            .w_full()
            .flex()
            .items_center()
            .px_3();

        base = if disabled {
            base.opacity(0.6).cursor_not_allowed()
        } else {
            base.cursor_pointer()
        };

        // Make the interaction hitbox more lenient: clicking or dragging anywhere in the slider's
        // container adjusts the value based on the track's bounds.
        base = base
            .on_drag((), move |_v: &(), _pos, _window, cx| cx.new(|_| Empty))
            .on_mouse_down(MouseButton::Left, {
                let track_bounds_state = track_bounds_state.clone();
                let set_from_mouse_x = set_from_mouse_x.clone();
                move |ev: &MouseDownEvent, window, cx| {
                    if disabled {
                        return;
                    }

                    let bounds = *track_bounds_state.read(cx);
                    if bounds.size.width > px(1.) {
                        let x: f32 = ev.position.x.into();
                        set_from_mouse_x(x, bounds, window, cx);
                    }

                    window.refresh();
                }
            })
            .on_drag_move::<()>({
                let track_bounds_state = track_bounds_state.clone();
                let set_from_mouse_x = set_from_mouse_x.clone();
                move |ev, window, cx| {
                    if disabled {
                        return;
                    }

                    let bounds = *track_bounds_state.read(cx);
                    if bounds.size.width > px(1.) {
                        let x: f32 = ev.event.position.x.into();
                        set_from_mouse_x(x, bounds, window, cx);
                    }
                }
            });

        base.child(TrackBoundsElement {
            bounds_state: track_bounds_state.clone(),
            inner: gpui::div()
                .id((id.clone(), "ui:slider:track"))
                .relative()
                .w_full()
                .h(px(track_height))
                .rounded_full()
                .bg(track_bg)
                .when(!disabled, |this| this.cursor_pointer())
                .on_drag((), move |_v: &(), _pos, _window, cx| cx.new(|_| Empty))
                .on_mouse_down(MouseButton::Left, {
                    let track_bounds_state = track_bounds_state.clone();
                    let set_from_mouse_x = set_from_mouse_x.clone();
                    move |ev: &MouseDownEvent, window, cx| {
                        if disabled {
                            return;
                        }

                        let bounds = *track_bounds_state.read(cx);
                        if bounds.size.width > px(1.) {
                            let x: f32 = ev.position.x.into();
                            set_from_mouse_x(x, bounds, window, cx);
                        }

                        window.refresh();
                    }
                })
                .on_drag_move::<()>({
                    let set_from_mouse_x = set_from_mouse_x.clone();
                    move |ev, window, cx| {
                        if disabled {
                            return;
                        }
                        let x: f32 = ev.event.position.x.into();
                        set_from_mouse_x(x, ev.bounds, window, cx);
                    }
                })
                .child(
                    gpui::div()
                        .absolute()
                        .top_0()
                        .left_0()
                        .h(px(track_height))
                        .rounded_full()
                        .bg(fill)
                        .w(gpui::relative(t)),
                )
                .child(
                    gpui::div()
                        .absolute()
                        .top(px(-(knob_diameter - track_height) / 2.0))
                        // Use left with percentage to position knob correctly
                        // This ensures knob is visible even when t=0
                        .when(t > 0.0, |this| this.left(relative(t)))
                        .when(t <= 0.0, |this| this.left_0())
                        .h(px(knob_diameter))
                        .w(px(knob_diameter))
                        .child(
                            gpui::div()
                                .w(px(knob_diameter))
                                .h(px(knob_diameter))
                                .rounded_full()
                                .bg(theme.action.primary.bg)
                                .hover(|this| this.bg(theme.action.primary.hover_bg))
                                .border_1()
                                .border_color(theme.surface.raised),
                        ),
                )
                .into_any_element(),
        })
    }
}

fn clamp(v: f32, min: f32, max: f32) -> f32 {
    v.max(min).min(max)
}

fn quantize(value: f32, origin: f32, step: f32) -> f32 {
    let n = ((value - origin) / step).round();
    origin + n * step
}