use super::state::Capture;
use par_term_config::KeyBinding;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RebuildReason {
Initial,
Bindings,
Capture,
}
#[derive(Debug, Default)]
pub struct MenuSync {
built: Option<(Vec<KeyBinding>, Capture)>,
}
impl MenuSync {
pub fn new() -> Self {
Self::default()
}
pub fn rebuild_reason(&self, live: &[KeyBinding], capture: &Capture) -> Option<RebuildReason> {
match &self.built {
None => Some(RebuildReason::Initial),
Some((built, _)) if built.as_slice() != live => Some(RebuildReason::Bindings),
Some((_, built_capture)) if built_capture != capture => Some(RebuildReason::Capture),
Some(_) => None,
}
}
pub fn record(&mut self, live: &[KeyBinding], capture: Capture) {
self.built = Some((live.to_vec(), capture));
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
fn kb(key: &str, action: &str) -> KeyBinding {
KeyBinding {
key: key.to_string(),
action: action.to_string(),
}
}
#[test]
fn nothing_recorded_means_build() {
let sync = MenuSync::new();
assert_eq!(
sync.rebuild_reason(&[], &None),
Some(RebuildReason::Initial)
);
}
#[test]
fn a_changed_binding_list_rebuilds_and_the_same_one_does_not() {
let mut sync = MenuSync::new();
let bindings = vec![kb("Cmd+T", "new_tab")];
sync.record(&bindings, None);
assert_eq!(sync.rebuild_reason(&bindings, &None), None);
let rebound = vec![kb("Cmd+Alt+T", "new_tab")];
assert_eq!(
sync.rebuild_reason(&rebound, &None),
Some(RebuildReason::Bindings)
);
let unbound: Vec<KeyBinding> = Vec::new();
assert_eq!(
sync.rebuild_reason(&unbound, &None),
Some(RebuildReason::Bindings)
);
}
#[test]
fn capturing_or_releasing_the_keyboard_rebuilds() {
let mut sync = MenuSync::new();
let bindings = vec![kb("Cmd+T", "new_tab")];
sync.record(&bindings, None);
let captured: Capture = Some(BTreeSet::new());
assert_eq!(
sync.rebuild_reason(&bindings, &captured),
Some(RebuildReason::Capture)
);
sync.record(&bindings, captured.clone());
assert_eq!(sync.rebuild_reason(&bindings, &captured), None);
let palette: Capture = Some(BTreeSet::from(["toggle_command_palette"]));
assert_eq!(
sync.rebuild_reason(&bindings, &palette),
Some(RebuildReason::Capture)
);
assert_eq!(
sync.rebuild_reason(&bindings, &None),
Some(RebuildReason::Capture)
);
}
}