use std::cell::Cell;
use std::rc::Rc;
use crabshell_reactive::{Memo, Signal, untrack};
use crate::cx::Cx;
use crate::input::{Drag, DragPhase, PIXELS_PER_STEP, Wheel};
use crate::keyboard::{Key, KeyEvent};
use crate::prop::{IntoProp, Prop};
use crate::scroll::Built;
use crate::style::Style;
use crate::widgets::{Align, Button, Column, Common, Element, Row, Stack, Widget};
type StyleFn = Rc<dyn Fn() -> Style>;
pub struct Slider {
props: SliderProps,
common: Common,
}
struct SliderProps {
value: Signal<f32>,
min: Option<Prop<f32>>,
max: Option<Prop<f32>>,
step: Option<Prop<f32>>,
vertical: Option<Prop<bool>>,
enabled: Option<Prop<bool>>,
style: Option<Prop<Style>>,
fill_style: Option<Prop<Style>>,
handle_style: Option<Prop<Style>>,
dragging: Option<Signal<bool>>,
}
const TRACK: (f32, f32) = (120.0, 4.0);
const HANDLE: f32 = 16.0;
const PARTS: f32 = 20.0;
impl Slider {
pub fn new(value: Signal<f32>) -> Slider {
Slider {
props: SliderProps {
value,
min: None,
max: None,
step: None,
vertical: None,
enabled: None,
style: None,
fill_style: None,
handle_style: None,
dragging: None,
},
common: Common::default(),
}
}
pub fn range(mut self, min: impl IntoProp<f32>, max: impl IntoProp<f32>) -> Slider {
self.props.min = Some(min.into_prop());
self.props.max = Some(max.into_prop());
self
}
pub fn step(mut self, step: impl IntoProp<f32>) -> Slider {
self.props.step = Some(step.into_prop());
self
}
pub fn vertical(mut self, vertical: impl IntoProp<bool>) -> Slider {
self.props.vertical = Some(vertical.into_prop());
self
}
pub fn enabled(mut self, enabled: impl IntoProp<bool>) -> Slider {
self.props.enabled = Some(enabled.into_prop());
self
}
pub fn style(mut self, style: impl IntoProp<Style>) -> Slider {
self.props.style = Some(style.into_prop());
self
}
pub fn fill_style(mut self, style: impl IntoProp<Style>) -> Slider {
self.props.fill_style = Some(style.into_prop());
self
}
pub fn handle_style(mut self, style: impl IntoProp<Style>) -> Slider {
self.props.handle_style = Some(style.into_prop());
self
}
pub fn dragging(mut self, dragging: Signal<bool>) -> Slider {
self.props.dragging = Some(dragging);
self
}
crate::widgets::visibility_methods!();
}
impl Widget for Slider {
fn into_element(self: Box<Self>) -> Element {
let Slider { props, common } = *self;
let mut once = Some(props);
let mut element = Box::new(Stack::new().children_keyed(
|| vec![()],
|_| (),
move |cx, _| {
Built(
once
.take()
.map(|props| Box::new(build(cx, props)).into_element()),
)
},
))
.into_element();
element.name = "Slider";
element.common = common;
element
}
}
#[derive(Clone, Copy)]
struct Range {
value: Signal<f32>,
min: Memo<f32>,
max: Memo<f32>,
step: Memo<f32>,
}
impl Range {
fn bounds(self) -> (f32, f32) {
let number = |n: f32| if n.is_nan() { 0.0 } else { n };
let min = number(self.min.get());
(min, number(self.max.get()).max(min))
}
fn fraction(self) -> f32 {
let (min, max) = self.bounds();
let value = self.value.get();
if max > min && !value.is_nan() {
((value - min) / (max - min)).clamp(0.0, 1.0)
} else {
0.0
}
}
fn unit(self) -> f32 {
let (min, max) = self.bounds();
self.snap().unwrap_or((max - min) / PARTS)
}
fn snap(self) -> Option<f32> {
untrack(|| self.step.try_get()).filter(|step| step.is_finite() && *step > 0.0)
}
fn now(self) -> f32 {
untrack(|| {
let (min, _) = self.bounds();
self.value.try_get().filter(|v| !v.is_nan()).unwrap_or(min)
})
}
fn write(self, value: f32) {
untrack(|| {
let (min, max) = self.bounds();
let mut value = if value.is_nan() { min } else { value };
if let Some(step) = self.snap() {
value = min + ((value - min) / step).round() * step;
}
let value = value.max(min).min(max);
if self.value.try_get() != Some(value) {
self.value.try_set(value);
}
});
}
fn write_fraction(self, t: f32) {
let (min, max) = untrack(|| self.bounds());
self.write(min + t.clamp(0.0, 1.0) * (max - min));
}
}
fn build(cx: &Cx, props: SliderProps) -> Button {
let SliderProps {
value,
min,
max,
step,
vertical,
enabled,
style,
fill_style,
handle_style,
dragging,
} = props;
let range = Range {
value,
min: cx.memo(shared_or(min, 0.0)),
max: cx.memo(shared_or(max, 1.0)),
step: cx.memo(shared_or(step, 0.0)),
};
if let Some(dragging) = dragging {
cx.signal(LetGo(dragging));
}
let vertical = cx.memo(shared_or(vertical, false));
let style = shared_style(style);
let fill_style = shared_style(fill_style);
let handle = {
let handle_style = shared_style(handle_style);
cx.memo(move || {
Style::new()
.width(HANDLE)
.height(HANDLE)
.merge(handle_style())
.shrink(0.0)
})
};
let fraction = cx.memo(move || range.fraction());
let on_drag = move |_: &Cx, drag: Drag| {
if let Some(dragging) = dragging {
let held = drag.phase != DragPhase::End;
if untrack(|| dragging.try_get()) != Some(held) {
dragging.try_set(held);
}
}
if drag.phase == DragPhase::End {
return;
}
let vertical = untrack(|| vertical.get());
let handle = untrack(|| handle.get());
let (at, length, size) = if vertical {
(drag.position.y, drag.size.height, handle.height)
} else {
(drag.position.x, drag.size.width, handle.width)
};
let size = size.unwrap_or(HANDLE).max(0.0);
let travel = length - size;
let t = if travel > 0.0 {
(at - size / 2.0) / travel
} else if length > 0.0 {
at / length
} else {
0.0
};
range.write_fraction(if vertical { 1.0 - t } else { t });
};
let partial = Cell::new(0.0_f32);
let on_wheel = move |_: &Cx, wheel: Wheel| {
let notches = wheel.x.notches - wheel.y.notches;
let steps = if notches != 0.0 {
notches
} else {
(wheel.x.pixels - wheel.y.pixels) / PIXELS_PER_STEP
};
if !steps.is_finite() {
return;
}
let unit = untrack(|| range.unit());
if range.snap().is_some() {
let total = partial.get() + steps;
let whole = total.trunc();
partial.set(total - whole);
if whole != 0.0 {
range.write(range.now() + whole * unit);
}
} else if steps != 0.0 {
range.write(range.now() + steps * unit);
}
if wheel.x.stop || wheel.y.stop {
partial.set(0.0);
}
};
let on_key = move |_: &Cx, event: &KeyEvent| {
let steps = match event.key {
Key::Left | Key::Down => -1.0,
Key::Right | Key::Up => 1.0,
_ => return false,
};
range.write(range.now() + steps * untrack(|| range.unit()));
true
};
let body = |column: bool| {
let parts = Parts {
style: Rc::clone(&style),
fill_style: Rc::clone(&fill_style),
handle,
fraction,
column,
};
parts.area().visible(move || vertical.get() == column)
};
let mut button = Button::new(Stack::new().child(body(false)).child(body(true)))
.on_drag(on_drag)
.on_wheel(on_wheel)
.on_key(on_key);
if let Some(enabled) = enabled {
button = button.enabled(enabled);
}
button
}
struct LetGo(Signal<bool>);
impl Drop for LetGo {
fn drop(&mut self) {
if untrack(|| self.0.try_get()) == Some(true) {
self.0.try_set(false);
}
}
}
struct Parts {
style: StyleFn,
fill_style: StyleFn,
handle: Memo<Style>,
fraction: Memo<f32>,
column: bool,
}
impl Parts {
fn area(self) -> Stack {
let Parts {
style,
fill_style,
handle,
fraction,
column,
} = self;
let (along, across) = TRACK;
let size = if column {
Style::new().width(across).height(along)
} else {
Style::new().width(along).height(across)
};
let half = move || {
let handle = handle.get();
let size = if column { handle.height } else { handle.width };
size.unwrap_or(HANDLE).max(0.0) / 2.0
};
let fill = Stack::new().style(move || fill_style().basis(half()).grow(fraction.get()));
let rest = Stack::new().style(move || Style::new().basis(half()).grow(1.0 - fraction.get()));
let track_style = move || {
size
.align_self(Align::Center)
.justify_self(Align::Center)
.merge(style())
};
let before = Stack::new().style(move || Style::new().basis(0.0).grow(fraction.get()));
let after = Stack::new().style(move || Style::new().basis(0.0).grow(1.0 - fraction.get()));
let knob = Stack::new().style(move || handle.get());
if column {
Stack::new()
.child(
Column::new()
.reverse(true)
.style(track_style)
.child(fill)
.child(rest),
)
.child(
Column::new()
.reverse(true)
.align(Align::Center)
.child(before)
.child(knob)
.child(after),
)
} else {
Stack::new()
.child(Row::new().style(track_style).child(fill).child(rest))
.child(
Row::new()
.align(Align::Center)
.child(before)
.child(knob)
.child(after),
)
}
}
}
fn shared_or<T: Clone + 'static>(prop: Option<Prop<T>>, default: T) -> impl FnMut() -> T + 'static {
let prop = prop.map(Prop::shared);
move || prop.as_ref().map_or_else(|| default.clone(), |prop| prop())
}
fn shared_style(prop: Option<Prop<Style>>) -> StyleFn {
match prop {
Some(prop) => prop.shared(),
None => Rc::new(Style::new),
}
}