use super::{NumberOptions, NumberStyle, Numeric};
use crate::Vec2;
use winit::keyboard::{KeyCode, ModifiersState};
#[derive(Default)]
pub(crate) struct NumberState {
pub(super) buffer: String,
pub(super) snapshot: String,
pub(super) last_value: String,
pub(super) editing: bool,
origin: String,
units: f64,
last_step: String,
pub(super) pointer: Option<Vec2>,
pub(super) distance: f32,
pub(super) focused: bool,
pub(super) invalid: bool,
pub(crate) last_frame: u64,
}
impl NumberState {
pub(super) fn committed<T: Numeric>(&mut self, value: T) {
self.invalid = false;
self.snapshot = value.to_string();
self.origin = self.snapshot.clone();
self.units = 0.0;
self.buffer = self.snapshot.clone();
}
pub(super) fn observe<T: Numeric>(&mut self, value: T, enabled: bool) {
if self.last_value != value.to_string() || !enabled {
self.committed(value);
}
if !enabled {
self.editing = false;
self.pointer = None;
}
}
pub(super) fn begin<T: Numeric>(&mut self, value: T) {
self.committed(value);
self.editing = true;
}
pub(super) fn cancel<T: Numeric>(&mut self, value: &mut T) {
if let Ok(original) = self.snapshot.parse::<T>() {
*value = original;
}
self.committed(*value);
}
pub(super) fn rebase<T: Numeric>(&mut self, value: T) {
self.origin = value.to_string();
self.units = 0.0;
}
pub(super) fn step<T: Numeric>(
&mut self,
value: &mut T,
options: &NumberOptions<'_, T>,
units: f64,
) {
let (min, max) = (*options.range.start(), *options.range.end());
if self.origin.is_empty() || self.last_step != options.step.to_string() {
self.rebase(*value);
}
let origin = self.origin.parse::<T>().unwrap_or(*value);
self.last_step = options.step.to_string();
self.units += units;
*value = origin.offset(options.step, self.units, min, max);
if (*value == min && units < 0.0) || (*value == max && units > 0.0) {
self.rebase(*value);
}
self.invalid = false;
}
pub(super) fn step_from<T: Numeric>(
&mut self,
value: &mut T,
options: &NumberOptions<'_, T>,
units: f64,
) {
let (min, max) = (*options.range.start(), *options.range.end());
let origin = self.origin.parse::<T>().ok();
if origin.is_none_or(|o| !o.offset(options.step, self.units, min, max).same(*value)) {
self.rebase(*value);
}
self.step(value, options, units);
}
}
pub(super) fn commit<T: Numeric>(
text: &str,
value: &mut T,
options: &NumberOptions<'_, T>,
) -> bool {
let Some(next) = T::parse(text) else {
return false;
};
*value = next.normalized(*options.range.start(), *options.range.end());
true
}
pub(super) fn multiplier(mods: ModifiersState, style: &NumberStyle) -> f64 {
if mods.shift_key() {
style.shift_multiplier
} else if mods.control_key() {
style.ctrl_multiplier
} else {
1.0
}
}
pub(super) fn arrow(key: KeyCode) -> f64 {
match key {
KeyCode::ArrowUp | KeyCode::ArrowRight => 1.0,
KeyCode::ArrowDown | KeyCode::ArrowLeft => -1.0,
KeyCode::PageUp => 10.0,
KeyCode::PageDown => -10.0,
_ => 0.0,
}
}