use std::{error::Error, fmt};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusCommand {
Next,
Previous,
First,
Last,
Activate,
Clear,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusError {
TargetLimitExceeded,
DuplicateTarget,
IneligibleTarget,
}
impl fmt::Display for FocusError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "invalid keyboard focus request: {self:?}")
}
}
impl Error for FocusError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FocusOutcome<T> {
pub focused: Option<T>,
pub activated: Option<T>,
}
#[derive(Debug)]
pub struct KeyboardFocus<T: Copy + Eq, S: Copy + Eq> {
focused: Option<T>,
scope: Option<S>,
max_targets: usize,
}
impl<T: Copy + Eq, S: Copy + Eq> KeyboardFocus<T, S> {
pub const fn new(max_targets: usize) -> Self {
Self {
focused: None,
scope: None,
max_targets,
}
}
pub const fn focused(&self) -> Option<T> {
self.focused
}
pub const fn scope(&self) -> Option<S> {
self.scope
}
pub fn clear(&mut self) {
self.focused = None;
}
pub fn synchronize(&mut self, scope: S, eligible: &[T]) -> Result<(), FocusError> {
self.validate(eligible)?;
if self.scope != Some(scope)
|| self
.focused
.is_some_and(|target| !eligible.contains(&target))
{
self.focused = None;
}
self.scope = Some(scope);
Ok(())
}
pub fn set_focused(
&mut self,
scope: S,
eligible: &[T],
target: Option<T>,
) -> Result<(), FocusError> {
self.validate(eligible)?;
if target.is_some_and(|target| !eligible.contains(&target)) {
return Err(FocusError::IneligibleTarget);
}
self.scope = Some(scope);
self.focused = target;
Ok(())
}
pub fn process(
&mut self,
scope: S,
eligible: &[T],
command: FocusCommand,
) -> Result<FocusOutcome<T>, FocusError> {
self.synchronize(scope, eligible)?;
let index = self
.focused
.and_then(|target| eligible.iter().position(|item| *item == target));
let mut activated = None;
match command {
FocusCommand::Clear => self.focused = None,
FocusCommand::Activate => activated = self.focused,
FocusCommand::First => self.focused = eligible.first().copied(),
FocusCommand::Last => self.focused = eligible.last().copied(),
FocusCommand::Next if !eligible.is_empty() => {
self.focused = eligible
.get(index.map_or(0, |index| (index + 1) % eligible.len()))
.copied();
}
FocusCommand::Previous if !eligible.is_empty() => {
self.focused = eligible
.get(
index
.filter(|index| *index > 0)
.map_or(eligible.len() - 1, |index| index - 1),
)
.copied();
}
FocusCommand::Next | FocusCommand::Previous => {}
}
Ok(FocusOutcome {
focused: self.focused,
activated,
})
}
fn validate(&self, eligible: &[T]) -> Result<(), FocusError> {
if eligible.len() > self.max_targets {
return Err(FocusError::TargetLimitExceeded);
}
for (index, target) in eligible.iter().enumerate() {
if eligible[..index].contains(target) {
return Err(FocusError::DuplicateTarget);
}
}
Ok(())
}
}