use crate::widget::state; use crate::widget::Id; pub trait Operation { fn container( &mut self, id: Option<&Id>, operate_on_children: &mut dyn FnMut(&mut dyn Operation), ); fn focusable( &mut self, _state: &mut dyn state::Focusable, _id: Option<&Id>, ) { } fn finish(&self) -> Outcome { Outcome::None } } pub enum Outcome { None, Some(T), Chain(Box>), } pub fn focus(target: Id) -> impl Operation { struct Focus { target: Id, } impl Operation for Focus { fn focusable( &mut self, state: &mut dyn state::Focusable, id: Option<&Id>, ) { match id { Some(id) if id == &self.target => { state.focus(); } _ => { state.unfocus(); } } } fn container( &mut self, _id: Option<&Id>, operate_on_children: &mut dyn FnMut(&mut dyn Operation), ) { operate_on_children(self) } } Focus { target } } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] pub struct FocusCount { focused: Option, total: usize, } pub fn count_focusable(f: fn(FocusCount) -> O) -> impl Operation where O: Operation + 'static, { struct CountFocusable { count: FocusCount, next: fn(FocusCount) -> O, } impl Operation for CountFocusable where O: Operation + 'static, { fn focusable( &mut self, state: &mut dyn state::Focusable, _id: Option<&Id>, ) { if state.is_focused() { self.count.focused = Some(self.count.total); } self.count.total += 1; } fn container( &mut self, _id: Option<&Id>, operate_on_children: &mut dyn FnMut(&mut dyn Operation), ) { operate_on_children(self) } fn finish(&self) -> Outcome { Outcome::Chain(Box::new((self.next)(self.count))) } } CountFocusable { count: FocusCount::default(), next: f, } } pub fn focus_previous() -> impl Operation { struct FocusPrevious { count: FocusCount, current: usize, } impl Operation for FocusPrevious { fn focusable( &mut self, state: &mut dyn state::Focusable, _id: Option<&Id>, ) { if self.count.total == 0 { return; } match self.count.focused { None if self.current == self.count.total - 1 => state.focus(), Some(0) if self.current == 0 => state.unfocus(), Some(0) => {} Some(focused) if focused == self.current => state.unfocus(), Some(focused) if focused - 1 == self.current => state.focus(), _ => {} } self.current += 1; } fn container( &mut self, _id: Option<&Id>, operate_on_children: &mut dyn FnMut(&mut dyn Operation), ) { operate_on_children(self) } } count_focusable(|count| FocusPrevious { count, current: 0 }) } pub fn focus_next() -> impl Operation { struct FocusNext { count: FocusCount, current: usize, } impl Operation for FocusNext { fn focusable( &mut self, state: &mut dyn state::Focusable, _id: Option<&Id>, ) { match self.count.focused { None if self.current == 0 => state.focus(), Some(focused) if focused == self.current => state.unfocus(), Some(focused) if focused + 1 == self.current => state.focus(), _ => {} } self.current += 1; } fn container( &mut self, _id: Option<&Id>, operate_on_children: &mut dyn FnMut(&mut dyn Operation), ) { operate_on_children(self) } } count_focusable(|count| FocusNext { count, current: 0 }) }