BlueGit

ict rusty-teams

Files

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

list.rs

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