use super::{state::commit, NumberOptions, NumberState, Numeric};
use crate::{
accessibility::Scope, AccessAction, AccessActionKind as Kind, AccessRole, Id, Rect, Ui,
};
pub(super) fn requests<T: Numeric>(
ui: &mut Ui<'_>,
node: Id,
state: &mut NumberState,
value: &mut T,
options: &NumberOptions<'_, T>,
) {
for action in ui.context.take_access_actions(node) {
if !options.enabled {
break;
}
match action {
AccessAction::Increment | AccessAction::Decrement => {
if state.editing && !commit(&state.buffer, value, options) {
state.invalid = true;
continue;
}
let units = if action == AccessAction::Increment {
1.0
} else {
-1.0
};
state.step_from(value, options, units);
if state.editing {
state.buffer = value.to_string();
}
}
AccessAction::SetNumericValue(next) if next.is_finite() => {
let (min, max) = (*options.range.start(), *options.range.end());
*value = T::from_f64(next).normalized(min, max);
state.committed(*value);
}
AccessAction::SetValue(text) => {
set_text(state, value, options, &text);
}
_ => {}
}
}
}
pub(super) fn set_text<T: Numeric>(
state: &mut NumberState,
value: &mut T,
options: &NumberOptions<'_, T>,
text: &str,
) -> bool {
let text = text.trim();
let text = text.strip_prefix(options.prefix.as_str()).unwrap_or(text);
let text = text.strip_suffix(options.suffix.as_str()).unwrap_or(text);
let parsed = commit(text.trim(), value, options);
if parsed {
state.committed(*value);
}
parsed
}
pub(super) fn describe<T: Numeric>(
ui: &mut Ui<'_>,
scope: Scope,
(hit, editor): (Id, bool),
rect: Rect,
value: T,
options: &NumberOptions<'_, T>,
state: &NumberState,
) {
let Some(index) = scope.0.map(|index| index as usize) else {
return;
};
let Some(node) = ui.context.a11y_node_mut(index) else {
return;
};
let id = node.id;
let shown = if editor {
state.buffer.clone()
} else {
options.display(value)
};
node.value(format!("{}{shown}{}", options.prefix, options.suffix))
.disabled(!options.enabled)
.invalid(state.invalid && options.enabled)
.action(Kind::Increment)
.action(Kind::Decrement)
.action(Kind::SetValue);
let (min, max) = (*options.range.start(), *options.range.end());
if min != T::MIN || max != T::MAX {
node.numeric(value.to_f64(), min.to_f64(), max.to_f64())
.step(options.step.to_f64());
}
if editor {
let field = ui.context.a11y_find(index + 1, |node| {
matches!(
node.role,
AccessRole::TextInput | AccessRole::MultilineTextInput
)
});
if let Some(field) = field.filter(|field| field.label.is_none()) {
field.labelled_by(id);
}
} else {
node.focus_on(hit);
}
ui.a11y_end(scope, Some(rect));
}