forked from yewstack/yew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slider.rs
93 lines (82 loc) · 2.49 KB
/
slider.rs
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
use std::cell::Cell;
use web_sys::HtmlInputElement;
use yew::{events::InputEvent, html, Callback, Component, Context, Html, Properties, TargetCast};
thread_local! {
static SLIDER_ID: Cell<usize> = Cell::default();
}
fn next_slider_id() -> usize {
SLIDER_ID.with(|cell| cell.replace(cell.get() + 1))
}
#[derive(Clone, Debug, PartialEq, Properties)]
pub struct Props {
pub label: &'static str,
pub value: f64,
pub onchange: Callback<f64>,
#[prop_or_default]
pub precision: Option<usize>,
#[prop_or_default]
pub percentage: bool,
#[prop_or_default]
pub min: f64,
pub max: f64,
#[prop_or_default]
pub step: Option<f64>,
}
pub struct Slider {
id: usize,
}
impl Component for Slider {
type Message = ();
type Properties = Props;
fn create(_ctx: &Context<Self>) -> Self {
Self {
id: next_slider_id(),
}
}
fn update(&mut self, _ctx: &Context<Self>, _msg: Self::Message) -> bool {
unimplemented!()
}
fn view(&self, ctx: &Context<Self>) -> Html {
let Props {
label,
value,
ref onchange,
precision,
percentage,
min,
max,
step,
} = *ctx.props();
let precision = precision.unwrap_or_else(|| if percentage { 1 } else { 0 });
let display_value = if percentage {
format!("{:.p$}%", 100.0 * value, p = precision)
} else {
format!("{:.p$}", value, p = precision)
};
let id = format!("slider-{}", self.id);
let step = step.unwrap_or_else(|| {
let p = if percentage { precision + 2 } else { precision };
10f64.powi(-(p as i32))
});
let oninput = {
let onchange = onchange.clone();
Callback::from(move |e: InputEvent| {
let input: HtmlInputElement = e.target_unchecked_into();
let output = input.value_as_number();
onchange.emit(output);
})
};
html! {
<div class="slider">
<label for={id.clone()} class="slider__label">{ label }</label>
<input type="range"
{id}
class="slider__input"
min={min.to_string()} max={max.to_string()} step={step.to_string()}
{oninput}
/>
<span class="slider__value">{ display_value }</span>
</div>
}
}
}