woocraft 0.4.5

GPUI components lib for Woocraft design system.
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
//! Numeric range slider control with single or dual thumb support.
//!
//! Slider allows users to select numeric values by dragging a thumb along a
//! horizontal track. Supports single value selection (one thumb) or range
//! selection (two thumbs). Configurable min/max bounds, step intervals, and
//! scale modes (linear or logarithmic). Useful for volume controls, price
//! filters, date range selection, and any numeric input where visual feedback
//! and drag interaction improves UX over text input.
//!
//! # Features
//! - **Single or Range**: One thumb for a single value, two thumbs for a range
//! - **Numeric Bounds**: Set min, max, and step increment
//! - **Scale Modes**: Linear (uniform spacing) or Logarithmic (for
//!   audio/exponential data)
//! - **Keyboard Support**: Arrow keys adjust value; Alt/Shift modifiers for
//!   large/small steps
//! - **Visual Feedback**: Filled track, thumb indicator, and optional labels
//!   (via delegate)
//! - **Smooth Dragging**: Immediate visual feedback while dragging
//!
//! # Example
//! ```rust,ignore
//! // Volume slider (0-100)
//! let slider_state = cx.new(|cx| {
//!   SliderState::new()
//!     .min(0.0)
//!     .max(100.0)
//!     .step(1.0)
//! });
//!
//! // Price range filter ($10-$100)
//! let range_slider = cx.new(|cx| {
//!   SliderState::new()
//!     .min(10.0)
//!     .max(100.0)
//!     .value(SliderValue::Range(25.0, 75.0))
//! });
//! ```

use gpui::{
  App, AppContext as _, Axis, Bounds, Context, DragMoveEvent, Empty, Entity, EntityId,
  EventEmitter, InteractiveElement as _, IntoElement, MouseButton, MouseDownEvent, MouseMoveEvent,
  ParentElement, Pixels, Render, RenderOnce, SharedString, StatefulInteractiveElement as _,
  StyleRefinement, Styled, Window, div, prelude::FluentBuilder as _, px, relative,
};

use crate::{ActiveTheme, ElementExt, Size, StyledExt, opacity};

#[derive(Clone)]
struct DragThumb((EntityId, bool));

impl Render for DragThumb {
  fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
    Empty
  }
}

/// Numeric value type for slider: single value or range.
///
/// `Single(f32)`: One numeric value (one thumb on the slider).
/// `Range(f32, f32)`: Two values representing a range (start, end) with two
/// thumbs. Range values are always kept in order (start ≤ end).
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SliderValue {
  /// Single value (one thumb).
  Single(f32),
  /// Range: start and end values (two thumbs). Automatically kept in order.
  Range(f32, f32),
}

impl Default for SliderValue {
  fn default() -> Self {
    Self::Single(0.0)
  }
}

impl From<f32> for SliderValue {
  fn from(value: f32) -> Self {
    Self::Single(value)
  }
}

impl From<(f32, f32)> for SliderValue {
  fn from(value: (f32, f32)) -> Self {
    Self::Range(value.0, value.1)
  }
}

impl SliderValue {
  pub fn is_range(&self) -> bool {
    matches!(self, Self::Range(_, _))
  }

  pub fn start(&self) -> f32 {
    match self {
      Self::Single(value) => *value,
      Self::Range(start, _) => *start,
    }
  }

  pub fn end(&self) -> f32 {
    match self {
      Self::Single(value) => *value,
      Self::Range(_, end) => *end,
    }
  }

  fn set_start(&mut self, value: f32) {
    match self {
      Self::Single(current) => *current = value,
      Self::Range(_, end) => *self = Self::Range(value.min(*end), *end),
    }
  }

  fn set_end(&mut self, value: f32) {
    match self {
      Self::Single(current) => *current = value,
      Self::Range(start, _) => *self = Self::Range(*start, value.max(*start)),
    }
  }
}

/// Numeric scale type for slider value calculation.
///
/// Linear: Values increase uniformly across the track. For volume, brightness,
/// etc. Logarithmic: Values increase exponentially. For audio frequencies,
/// price ranges, etc. Requires min > 0 for logarithmic scale.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SliderScale {
  /// Uniform spacing. Default.
  #[default]
  Linear,
  /// Exponential spacing (min must be > 0).
  Logarithmic,
}

#[derive(Clone)]
/// Events emitted by the slider when value changes.
pub enum SliderEvent {
  /// Emitted when user drags thumb or changes value via keyboard. Contains new
  /// value.
  Change(SliderValue),
}

/// Internal state management for slider control.
///
/// Handles numeric range calculation, value clamping, and scale conversion
/// (linear/logarithmic). Emits `SliderEvent::Change` when user drags or adjusts
/// value via keyboard. Use `SliderValue::Single()` or `SliderValue::Range()` to
/// start with different modes.
pub struct SliderState {
  min: f32,
  max: f32,
  step: f32,
  value: SliderValue,
  percentage: std::ops::Range<f32>,
  bounds: Bounds<Pixels>,
  scale: SliderScale,
  active_thumb_start: bool,
}

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

impl SliderState {
  /// Create a new slider with default range (0-100), step 1, and linear scale.
  pub fn new() -> Self {
    let mut this = Self {
      min: 0.0,
      max: 100.0,
      step: 1.0,
      value: SliderValue::default(),
      percentage: 0.0..0.0,
      bounds: Bounds::default(),
      scale: SliderScale::Linear,
      active_thumb_start: false,
    };
    this.sync_percentage();
    this
  }

  /// Set the minimum value for the slider.
  ///
  /// Default: 0.0. For logarithmic scale, min must be > 0.
  pub fn min(mut self, min: f32) -> Self {
    self.min = min;
    self.sync_percentage();
    self
  }

  /// Set the maximum value for the slider.
  ///
  /// Default: 100.0. Must be greater than min.
  pub fn max(mut self, max: f32) -> Self {
    self.max = max;
    self.sync_percentage();
    self
  }

  /// Set the step interval for keyboard adjustments.
  ///
  /// When user presses arrow keys, value changes by step amount. Default: 1.0.
  /// For fine-grain control, use small steps (e.g., 0.1).
  pub fn step(mut self, step: f32) -> Self {
    self.step = step.max(0.000_001);
    self
  }

  /// Set the numeric scale mode (Linear or Logarithmic).
  ///
  /// Linear: uniform spacing (default). Logarithmic: exponential spacing.
  /// For logarithmic scale, min must be > 0.
  pub fn scale(mut self, scale: SliderScale) -> Self {
    if matches!(scale, SliderScale::Logarithmic) {
      assert!(self.min > 0.0, "min must be > 0 for logarithmic slider");
      assert!(
        self.max > self.min,
        "max must be > min for logarithmic slider"
      );
    }
    self.scale = scale;
    self.sync_percentage();
    self
  }

  pub fn default_value(mut self, value: impl Into<SliderValue>) -> Self {
    self.value = value.into();
    self.sync_percentage();
    self
  }

  pub fn set_value(&mut self, value: impl Into<SliderValue>, cx: &mut Context<Self>) {
    self.value = self.snap_and_clamp(value.into());
    self.sync_percentage();
    cx.emit(SliderEvent::Change(self.value));
    cx.notify();
  }

  pub fn value(&self) -> SliderValue {
    self.value
  }

  fn sync_percentage(&mut self) {
    match self.value {
      SliderValue::Single(value) => {
        let p = self.value_to_percentage(value.clamp(self.min, self.max));
        self.percentage = 0.0..p;
      }
      SliderValue::Range(start, end) => {
        let start = start.clamp(self.min, self.max);
        let end = end.clamp(self.min, self.max);
        self.percentage = self.value_to_percentage(start)..self.value_to_percentage(end);
      }
    }
  }

  fn set_bounds(&mut self, bounds: Bounds<Pixels>) {
    self.bounds = bounds;
  }

  fn snap_and_clamp(&self, value: SliderValue) -> SliderValue {
    let snap = |mut raw: f32| {
      raw = raw.clamp(self.min, self.max);
      if self.step > 0.0 {
        let steps = ((raw - self.min) / self.step).round();
        raw = self.min + steps * self.step;
      }
      raw.clamp(self.min, self.max)
    };

    match value {
      SliderValue::Single(value) => SliderValue::Single(snap(value)),
      SliderValue::Range(start, end) => {
        let start = snap(start);
        let end = snap(end).max(start);
        SliderValue::Range(start, end)
      }
    }
  }

  fn percentage_to_value(&self, percentage: f32) -> f32 {
    match self.scale {
      SliderScale::Linear => self.min + (self.max - self.min) * percentage,
      SliderScale::Logarithmic => {
        let base = self.max / self.min;
        (base.powf(percentage) * self.min).clamp(self.min, self.max)
      }
    }
  }

  fn value_to_percentage(&self, value: f32) -> f32 {
    match self.scale {
      SliderScale::Linear => {
        let range = self.max - self.min;
        if range <= 0.0 {
          0.0
        } else {
          ((value - self.min) / range).clamp(0.0, 1.0)
        }
      }
      SliderScale::Logarithmic => {
        let base = self.max / self.min;
        (value / self.min).log(base).clamp(0.0, 1.0)
      }
    }
  }

  fn choose_active_thumb(&mut self, axis: Axis, position: gpui::Point<Pixels>) {
    if !self.value.is_range() {
      self.active_thumb_start = false;
      return;
    }

    let total = if matches!(axis, Axis::Horizontal) {
      self.bounds.size.width
    } else {
      self.bounds.size.height
    };

    if total <= px(0.0) {
      self.active_thumb_start = false;
      return;
    }

    let inner_pos = if matches!(axis, Axis::Horizontal) {
      position.x - self.bounds.left()
    } else {
      self.bounds.bottom() - position.y
    };

    let center =
      ((self.percentage.end - self.percentage.start) * 0.5 + self.percentage.start) * total;
    self.active_thumb_start = inner_pos < center;
  }

  fn update_by_position(
    &mut self, axis: Axis, position: gpui::Point<Pixels>, is_start: bool, cx: &mut Context<Self>,
  ) {
    let total = if matches!(axis, Axis::Horizontal) {
      self.bounds.size.width
    } else {
      self.bounds.size.height
    };

    if total <= px(0.0) {
      return;
    }

    let inner_pos = if matches!(axis, Axis::Horizontal) {
      position.x - self.bounds.left()
    } else {
      self.bounds.bottom() - position.y
    };

    let raw_percentage = (inner_pos / total).clamp(0.0, 1.0);
    let percentage = if is_start {
      raw_percentage.clamp(0.0, self.percentage.end)
    } else {
      raw_percentage.clamp(self.percentage.start, 1.0)
    };

    let value = self.percentage_to_value(percentage);
    let value = match self.snap_and_clamp(SliderValue::Single(value)) {
      SliderValue::Single(v) => v,
      SliderValue::Range(..) => value,
    };

    if is_start {
      self.value.set_start(value);
    } else {
      self.value.set_end(value);
    }
    self.value = self.snap_and_clamp(self.value);
    self.sync_percentage();
    cx.emit(SliderEvent::Change(self.value));
    cx.notify();
  }
}

impl EventEmitter<SliderEvent> for SliderState {}

#[derive(IntoElement)]
pub struct Slider {
  id: SharedString,
  state: Entity<SliderState>,
  style: StyleRefinement,
  size: Size,
  disabled: bool,
  axis: Axis,
}

impl Slider {
  pub fn new(id: impl Into<SharedString>, state: &Entity<SliderState>) -> Self {
    Self {
      id: id.into(),
      state: state.clone(),
      style: StyleRefinement::default(),
      size: Size::default(),
      disabled: false,
      axis: Axis::Horizontal,
    }
  }

  pub fn horizontal(mut self) -> Self {
    self.axis = Axis::Horizontal;
    self
  }

  pub fn vertical(mut self) -> Self {
    self.axis = Axis::Vertical;
    self
  }
}

impl_disableable!(Slider);
impl_sizable!(Slider);
impl_styled!(Slider);

impl RenderOnce for Slider {
  fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
    let state = self.state.read(cx);
    let percentage = state.percentage.clone();
    let is_range = state.value.is_range();
    let _ = state;

    let axis = self.axis;
    let entity_id = self.state.entity_id();
    let state_for_down = self.state.clone();
    let state_for_move = self.state.clone();

    let bar_start = relative(percentage.start);
    let bar_end = relative(1. - percentage.end);

    div()
      .id(self.id)
      .when(matches!(axis, Axis::Horizontal), |this| {
        this.h(self.size.component_height()).w_full()
      })
      .when(matches!(axis, Axis::Vertical), |this| {
        this.w(self.size.component_height()).h(px(120.0))
      })
      .items_center()
      .justify_center()
      .child(
        div()
          .id(("slider-track", self.state.entity_id().as_u64()))
          .relative()
          .when(matches!(axis, Axis::Horizontal), |this| {
            this.h(self.size.track_thickness()).w_full()
          })
          .when(matches!(axis, Axis::Vertical), |this| {
            this.w(self.size.track_thickness()).h_full()
          })
          .rounded_full()
          .bg(cx.theme().muted)
          .on_prepaint({
            let state = self.state.clone();
            move |bounds, _, cx| {
              state.update(cx, |s, _| s.set_bounds(bounds));
            }
          })
          .when(!self.disabled, |this| {
            this
              .cursor_pointer()
              .on_mouse_down(MouseButton::Left, move |e: &MouseDownEvent, _, cx| {
                state_for_down.update(cx, |state, cx| {
                  state.choose_active_thumb(axis, e.position);
                  state.update_by_position(axis, e.position, state.active_thumb_start, cx);
                });
              })
              .on_mouse_move(move |e: &MouseMoveEvent, _, cx| {
                if e.pressed_button == Some(MouseButton::Left) {
                  state_for_move.update(cx, |state, cx| {
                    state.update_by_position(axis, e.position, state.active_thumb_start, cx);
                  });
                }
              })
          })
          .child(
            div()
              .absolute()
              .when(matches!(axis, Axis::Horizontal), |this| {
                this.left(bar_start).right(bar_end).top_0().bottom_0()
              })
              .when(matches!(axis, Axis::Vertical), |this| {
                this.bottom(bar_start).top(bar_end).left_0().right_0()
              })
              .rounded_full()
              .bg(cx.theme().primary),
          )
          .when(is_range, |this| {
            this.child(
              div()
                .id(("slider-thumb-start", self.state.entity_id().as_u64()))
                .absolute()
                .size(self.size.thumb_size())
                .rounded_full()
                .border_2()
                .border_color(cx.theme().primary)
                .bg(cx.theme().background)
                .when(matches!(axis, Axis::Horizontal), |this| {
                  this
                    .top(-(self.size.thumb_size() - self.size.track_thickness()) / 2.0)
                    .left(relative(percentage.start))
                    .ml(-self.size.thumb_size() / 2.0)
                })
                .when(matches!(axis, Axis::Vertical), |this| {
                  this
                    .left(-(self.size.thumb_size() - self.size.track_thickness()) / 2.0)
                    .bottom(relative(percentage.start))
                    .mb(-self.size.thumb_size() / 2.0)
                })
                .when(!self.disabled, |this| {
                  this
                    .cursor_pointer()
                    .on_mouse_down(MouseButton::Left, |_, _, cx| {
                      cx.stop_propagation();
                    })
                    .on_drag(DragThumb((entity_id, true)), |drag, _, _, cx| {
                      cx.stop_propagation();
                      cx.new(|_| drag.clone())
                    })
                    .on_drag_move({
                      let state = self.state.clone();
                      move |e: &DragMoveEvent<DragThumb>, _, cx| {
                        let DragThumb((id, is_start)) = e.drag(cx).clone();
                        if id != entity_id {
                          return;
                        }

                        let position = e.event.position;
                        state.update(cx, |state, cx| {
                          state.update_by_position(axis, position, is_start, cx);
                        });
                      }
                    })
                }),
            )
          })
          .child(
            div()
              .id(("slider-thumb-end", self.state.entity_id().as_u64()))
              .absolute()
              .size(self.size.thumb_size())
              .rounded_full()
              .border_2()
              .border_color(cx.theme().primary)
              .bg(cx.theme().background)
              .when(matches!(axis, Axis::Horizontal), |this| {
                this
                  .top(-(self.size.thumb_size() - self.size.track_thickness()) / 2.0)
                  .left(relative(percentage.end))
                  .ml(-self.size.thumb_size() / 2.0)
              })
              .when(matches!(axis, Axis::Vertical), |this| {
                this
                  .left(-(self.size.thumb_size() - self.size.track_thickness()) / 2.0)
                  .bottom(relative(percentage.end))
                  .mb(-self.size.thumb_size() / 2.0)
              })
              .when(!self.disabled, |this| {
                this
                  .cursor_pointer()
                  .on_mouse_down(MouseButton::Left, |_, _, cx| {
                    cx.stop_propagation();
                  })
                  .on_drag(DragThumb((entity_id, false)), |drag, _, _, cx| {
                    cx.stop_propagation();
                    cx.new(|_| drag.clone())
                  })
                  .on_drag_move({
                    let state = self.state.clone();
                    move |e: &DragMoveEvent<DragThumb>, _, cx| {
                      let DragThumb((id, is_start)) = e.drag(cx).clone();
                      if id != entity_id {
                        return;
                      }

                      let position = e.event.position;
                      state.update(cx, |state, cx| {
                        state.update_by_position(axis, position, is_start, cx);
                      });
                    }
                  })
              }),
          ),
      )
      .opacity(if self.disabled {
        opacity::DISABLED
      } else {
        1.0
      })
      .refine_style(&self.style)
  }
}