BlueGit

ict rusty-teams

Files

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

list.rs

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