core/
util.rs

1use input::StandardEvent;
2
3use crate::events::Event;
4
5#[macro_export]
6macro_rules! select {
7	(default $default: expr, $first: expr) => {
8		if let Some(value) = $first() {
9			value
10		}
11		else {
12			$default()
13		}
14	};
15	(default $default: expr, $first: expr, $($arg:expr),*) => {
16		if let Some(value) = $first() {
17			value
18		}
19		$(else if let Some(value) = $arg() {
20			value
21		})*
22		else {
23			$default()
24		}
25	};
26}
27
28#[macro_export]
29macro_rules! first {
30	($first: expr, $($arg:expr),*) => {
31		if $first().is_some() {
32		}
33		$(else if $arg().is_some() {
34		})*
35	};
36}
37
38/// Utility function to handle scroll events.
39#[inline]
40#[must_use]
41pub(crate) fn handle_view_data_scroll(event: Event, view_state: &view::State) -> Option<Event> {
42	match event {
43		Event::Standard(meta_event) if meta_event == StandardEvent::ScrollLeft => view_state.scroll_left(),
44		Event::Standard(meta_event) if meta_event == StandardEvent::ScrollRight => view_state.scroll_right(),
45		Event::Standard(meta_event) if meta_event == StandardEvent::ScrollDown => view_state.scroll_down(),
46		Event::Standard(meta_event) if meta_event == StandardEvent::ScrollUp => view_state.scroll_up(),
47		Event::Standard(meta_event) if meta_event == StandardEvent::ScrollTop => view_state.scroll_top(),
48		Event::Standard(meta_event) if meta_event == StandardEvent::ScrollBottom => view_state.scroll_bottom(),
49		Event::Standard(meta_event) if meta_event == StandardEvent::ScrollJumpDown => view_state.scroll_page_down(),
50		Event::Standard(meta_event) if meta_event == StandardEvent::ScrollJumpUp => view_state.scroll_page_up(),
51		_ => return None,
52	};
53	Some(event)
54}
55
56#[cfg(test)]
57mod tests {
58	use captur::capture;
59	use rstest::rstest;
60	use view::testutil::with_view_state;
61
62	use super::*;
63
64	#[rstest]
65	#[case::scroll_left(StandardEvent::ScrollLeft, "ScrollLeft")]
66	#[case::scroll_right(StandardEvent::ScrollRight, "ScrollRight")]
67	#[case::scroll_down(StandardEvent::ScrollDown, "ScrollDown")]
68	#[case::scroll_up(StandardEvent::ScrollUp, "ScrollUp")]
69	#[case::jump_down(StandardEvent::ScrollJumpDown, "PageDown")]
70	#[case::jump_up(StandardEvent::ScrollJumpUp, "PageUp")]
71	fn handle_view_data_scroll_event(#[case] meta_event: StandardEvent, #[case] action: &str) {
72		with_view_state(|context| {
73			capture!(action);
74			let event = Event::from(meta_event);
75			assert_eq!(handle_view_data_scroll(event, &context.state), Some(event));
76			context.assert_render_action(&[action]);
77		});
78	}
79
80	#[test]
81	fn handle_view_data_scroll_event_other() {
82		with_view_state(|context| {
83			let event = Event::from('a');
84			assert!(handle_view_data_scroll(event, &context.state).is_none());
85			context.assert_render_action(&[]);
86		});
87	}
88}