BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / call / list.rs

list.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
list.rs 9.3 KiB Download Raw
1use std::ops::Range;
2
3use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
4use store::ChatRecord;
5use teams_core::{CallDirection, CallLogEntry};
6
7use super::history::{CallRow, call_rows};
8
9pub const CALL_ROW_HEIGHT: f32 = 54.;
10pub const EMPTY_HEIGHT: f32 = 56.;
11const MAX_AGE_SECONDS: i64 = 60;
12const NO_CALLS_TEXT: &str = "No calls yet";
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
15pub enum HistoryFilter {
16 #[default]
17 All,
18 Missed,
19 Incoming,
20 Outgoing,
21}
22
23impl HistoryFilter {
24 pub const ALL: [HistoryFilter; 4] = [
25 HistoryFilter::All,
26 HistoryFilter::Missed,
27 HistoryFilter::Incoming,
28 HistoryFilter::Outgoing,
29 ];
30
31 pub fn label(self) -> &'static str {
32 match self {
33 HistoryFilter::All => "All",
34 HistoryFilter::Missed => "Missed",
35 HistoryFilter::Incoming => "Incoming",
36 HistoryFilter::Outgoing => "Outgoing",
37 }
38 }
39
40 fn empty_text(self) -> &'static str {
41 match self {
42 HistoryFilter::All => NO_CALLS_TEXT,
43 HistoryFilter::Missed => "No missed calls",
44 HistoryFilter::Incoming => "No incoming calls",
45 HistoryFilter::Outgoing => "No outgoing calls",
46 }
47 }
48
49 fn admits(self, entry: &CallLogEntry) -> bool {
50 match self {
51 HistoryFilter::All => true,
52 HistoryFilter::Missed => entry.missed(),
53 HistoryFilter::Incoming => {
54 entry.direction == CallDirection::Incoming && !entry.missed()
55 }
56 HistoryFilter::Outgoing => entry.direction == CallDirection::Outgoing,
57 }
58 }
59}
60
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum ListEntry {
63 Call(CallRow),
64 Empty(&'static str),
65}
66
67impl ListEntry {
68 pub fn height(&self) -> f32 {
69 match self {
70 ListEntry::Call(_) => CALL_ROW_HEIGHT,
71 ListEntry::Empty(_) => EMPTY_HEIGHT,
72 }
73 }
74}
75
76#[derive(Debug, Clone, PartialEq)]
77pub struct VisibleWindow {
78 pub range: Range<usize>,
79 pub before: f32,
80 pub after: f32,
81}
82
83#[derive(Debug, Clone)]
84struct BuiltAt {
85 day: NaiveDate,
86 time: DateTime<Utc>,
87}
88
89#[derive(Debug, Default)]
90pub struct CallsList {
91 entries: Vec<ListEntry>,
92 starts: Vec<f32>,
93 ends: Vec<f32>,
94 built_at: Option<BuiltAt>,
95 invalidated: bool,
96 filter: HistoryFilter,
97}
98
99impl CallsList {
100 pub fn invalidate(&mut self) {
101 self.invalidated = true;
102 }
103
104 pub fn filter(&self) -> HistoryFilter {
105 self.filter
106 }
107
108 pub fn set_filter(&mut self, filter: HistoryFilter) {
109 if self.filter != filter {
110 self.filter = filter;
111 self.invalidated = true;
112 }
113 }
114
115 pub fn needs_rebuild(&self, now: DateTime<Utc>, offset: FixedOffset) -> bool {
116 let Some(built_at) = &self.built_at else {
117 return true;
118 };
119 self.invalidated
120 || built_at.day != now.with_timezone(&offset).date_naive()
121 || now - built_at.time >= Duration::seconds(MAX_AGE_SECONDS)
122 }
123
124 pub fn entries(&self) -> &[ListEntry] {
125 &self.entries
126 }
127
128 pub fn rebuild(
129 &mut self,
130 history: &[CallLogEntry],
131 chats: &[ChatRecord],
132 now: DateTime<Utc>,
133 offset: FixedOffset,
134 ) {
135 let mut entries = Vec::new();
136 let filter = self.filter;
137 let admitted = history.iter().filter(|entry| filter.admits(entry));
138 let calls = call_rows(admitted, chats, now, offset);
139 if calls.is_empty() {
140 entries.push(ListEntry::Empty(self.filter.empty_text()));
141 }
142 entries.extend(calls.into_iter().map(ListEntry::Call));
143 self.set_entries(entries);
144 self.built_at = Some(BuiltAt {
145 day: now.with_timezone(&offset).date_naive(),
146 time: now,
147 });
148 self.invalidated = false;
149 }
150
151 fn set_entries(&mut self, entries: Vec<ListEntry>) {
152 let mut position = 0.;
153 self.starts = Vec::with_capacity(entries.len());
154 self.ends = Vec::with_capacity(entries.len());
155 for entry in &entries {
156 self.starts.push(position);
157 position += entry.height();
158 self.ends.push(position);
159 }
160 self.entries = entries;
161 }
162
163 pub fn total_height(&self) -> f32 {
164 self.ends.last().copied().unwrap_or(0.)
165 }
166
167 pub fn window(&self, from: f32, to: f32) -> VisibleWindow {
168 let first = self.ends.partition_point(|end| *end < from);
169 let last = self.starts.partition_point(|start| *start <= to).max(first);
170 VisibleWindow {
171 before: self
172 .starts
173 .get(first)
174 .copied()
175 .unwrap_or(self.total_height()),
176 after: match last.checked_sub(1).and_then(|index| self.ends.get(index)) {
177 Some(end) if last > first => self.total_height() - end,
178 _ => 0.,
179 },
180 range: first..last,
181 }
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use chrono::TimeZone;
188 use teams_core::{CallDirection, CallOutcome};
189
190 use super::*;
191
192 fn now() -> DateTime<Utc> {
193 Utc.with_ymd_and_hms(2026, 10, 12, 8, 0, 0).unwrap()
194 }
195
196 fn zero() -> FixedOffset {
197 FixedOffset::east_opt(0).unwrap()
198 }
199
200 fn call(id: &str) -> CallLogEntry {
201 CallLogEntry {
202 call_id: id.into(),
203 started_at: now() - Duration::hours(3),
204 duration_seconds: Some(60),
205 direction: CallDirection::Outgoing,
206 outcome: CallOutcome::Accepted,
207 is_meeting: false,
208 peer_id: Some("8:orgid:bea".into()),
209 peer_name: Some("Bea".into()),
210 thread_id: None,
211 }
212 }
213
214 fn built(calls: usize) -> CallsList {
215 let history: Vec<CallLogEntry> =
216 (0..calls).map(|index| call(&format!("c{index}"))).collect();
217 let mut list = CallsList::default();
218 list.rebuild(&history, &[], now(), zero());
219 list
220 }
221
222 #[test]
223 fn an_empty_history_shows_its_empty_text() {
224 assert_eq!(built(0).entries(), [ListEntry::Empty("No calls yet")]);
225 }
226
227 #[test]
228 fn the_history_filter_keeps_only_matching_calls() {
229 let missed = CallLogEntry {
230 direction: CallDirection::Incoming,
231 outcome: CallOutcome::Missed,
232 ..call("missed")
233 };
234 let incoming = CallLogEntry {
235 direction: CallDirection::Incoming,
236 ..call("incoming")
237 };
238 let history = [missed, incoming, call("outgoing")];
239 let keys = |filter: HistoryFilter| -> Vec<String> {
240 let mut list = CallsList::default();
241 list.set_filter(filter);
242 list.rebuild(&history, &[], now(), zero());
243 list.entries()
244 .iter()
245 .filter_map(|entry| match entry {
246 ListEntry::Call(row) => Some(row.key.clone()),
247 ListEntry::Empty(text) => Some((*text).to_owned()),
248 })
249 .collect()
250 };
251 assert_eq!(keys(HistoryFilter::All), ["missed", "incoming", "outgoing"]);
252 assert_eq!(keys(HistoryFilter::Missed), ["missed"]);
253 assert_eq!(keys(HistoryFilter::Incoming), ["incoming"]);
254 assert_eq!(keys(HistoryFilter::Outgoing), ["outgoing"]);
255 let mut list = CallsList::default();
256 list.set_filter(HistoryFilter::Missed);
257 list.rebuild(&[call("outgoing")], &[], now(), zero());
258 assert_eq!(
259 list.entries().last(),
260 Some(&ListEntry::Empty("No missed calls"))
261 );
262 }
263
264 #[test]
265 fn a_fresh_list_needs_a_rebuild_until_built() {
266 let mut list = CallsList::default();
267 assert!(list.needs_rebuild(now(), zero()));
268 list.rebuild(&[], &[], now(), zero());
269 assert!(!list.needs_rebuild(now() + Duration::seconds(30), zero()));
270 }
271
272 #[test]
273 fn invalidation_age_and_a_new_day_force_a_rebuild() {
274 let mut list = built(0);
275 list.invalidate();
276 assert!(list.needs_rebuild(now(), zero()));
277 list.rebuild(&[], &[], now(), zero());
278 assert!(list.needs_rebuild(now() + Duration::seconds(61), zero()));
279 assert!(list.needs_rebuild(now() + Duration::hours(17), zero()));
280 }
281
282 #[test]
283 fn the_window_keeps_only_rows_on_screen_and_spacers_for_the_rest() {
284 let list = built(100);
285 let total = list.total_height();
286 let window = list.window(1000., 1200.);
287 assert!(window.range.len() < 12);
288 assert!(window.range.start > 10);
289 assert_eq!(window.before, list.starts[window.range.start]);
290 let shown: f32 = list.entries()[window.range.clone()]
291 .iter()
292 .map(ListEntry::height)
293 .sum();
294 assert!((window.before + shown + window.after - total).abs() < 0.01);
295 }
296
297 #[test]
298 fn the_window_clamps_at_both_ends() {
299 let list = built(100);
300 let top = list.window(-300., 100.);
301 assert_eq!(top.range.start, 0);
302 assert_eq!(top.before, 0.);
303 let bottom = list.window(list.total_height() - 100., list.total_height() + 500.);
304 assert_eq!(bottom.range.end, list.entries().len());
305 assert_eq!(bottom.after, 0.);
306 let empty = CallsList::default().window(0., 100.);
307 assert_eq!(empty.range, 0..0);
308 assert_eq!(empty.before, 0.);
309 assert_eq!(empty.after, 0.);
310 }
311}