BlueGit

ict rusty-teams

Files

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

list.rs

list.rs 12.2 KiB Download Raw
1use std::ops::Range;
2
3use chatsvc::CalendarEvent;
4use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
5use store::ChatRecord;
6use teams_core::{CallDirection, CallLogEntry};
7
8use super::agenda::{AgendaRow, group_by_day};
9use super::history::{CallRow, call_rows};
10
11pub const SECTION_HEIGHT: f32 = 34.;
12pub const DAY_HEIGHT: f32 = 26.;
13pub const AGENDA_ROW_HEIGHT: f32 = 58.;
14pub const CALL_ROW_HEIGHT: f32 = 54.;
15pub const EMPTY_HEIGHT: f32 = 56.;
16pub const FILTERS_HEIGHT: f32 = 36.;
17const MAX_AGE_SECONDS: i64 = 60;
18const UPCOMING_TITLE: &str = "Upcoming";
19const RECENT_TITLE: &str = "Recent";
20const NO_MEETINGS_TEXT: &str = "No meetings in the next 7 days";
21const NO_CALLS_TEXT: &str = "No calls yet";
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24pub enum HistoryFilter {
25 #[default]
26 All,
27 Missed,
28 Incoming,
29 Outgoing,
30}
31
32impl HistoryFilter {
33 pub const ALL: [HistoryFilter; 4] = [
34 HistoryFilter::All,
35 HistoryFilter::Missed,
36 HistoryFilter::Incoming,
37 HistoryFilter::Outgoing,
38 ];
39
40 pub fn label(self) -> &'static str {
41 match self {
42 HistoryFilter::All => "All",
43 HistoryFilter::Missed => "Missed",
44 HistoryFilter::Incoming => "Incoming",
45 HistoryFilter::Outgoing => "Outgoing",
46 }
47 }
48
49 fn empty_text(self) -> &'static str {
50 match self {
51 HistoryFilter::All => NO_CALLS_TEXT,
52 HistoryFilter::Missed => "No missed calls",
53 HistoryFilter::Incoming => "No incoming calls",
54 HistoryFilter::Outgoing => "No outgoing calls",
55 }
56 }
57
58 fn admits(self, entry: &CallLogEntry) -> bool {
59 match self {
60 HistoryFilter::All => true,
61 HistoryFilter::Missed => entry.missed(),
62 HistoryFilter::Incoming => entry.direction == CallDirection::Incoming && !entry.missed(),
63 HistoryFilter::Outgoing => entry.direction == CallDirection::Outgoing,
64 }
65 }
66}
67
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub enum ListEntry {
70 Section(&'static str),
71 Filters(HistoryFilter),
72 Day(String),
73 Agenda(AgendaRow),
74 Call(CallRow),
75 Empty(&'static str),
76}
77
78impl ListEntry {
79 pub fn height(&self) -> f32 {
80 match self {
81 ListEntry::Section(_) => SECTION_HEIGHT,
82 ListEntry::Filters(_) => FILTERS_HEIGHT,
83 ListEntry::Day(_) => DAY_HEIGHT,
84 ListEntry::Agenda(_) => AGENDA_ROW_HEIGHT,
85 ListEntry::Call(_) => CALL_ROW_HEIGHT,
86 ListEntry::Empty(_) => EMPTY_HEIGHT,
87 }
88 }
89}
90
91#[derive(Debug, Clone, PartialEq)]
92pub struct VisibleWindow {
93 pub range: Range<usize>,
94 pub before: f32,
95 pub after: f32,
96}
97
98#[derive(Debug, Clone)]
99struct BuiltAt {
100 day: NaiveDate,
101 time: DateTime<Utc>,
102}
103
104#[derive(Debug, Default)]
105pub struct CallsList {
106 entries: Vec<ListEntry>,
107 starts: Vec<f32>,
108 ends: Vec<f32>,
109 built_at: Option<BuiltAt>,
110 invalidated: bool,
111 filter: HistoryFilter,
112}
113
114impl CallsList {
115 pub fn invalidate(&mut self) {
116 self.invalidated = true;
117 }
118
119 pub fn filter(&self) -> HistoryFilter {
120 self.filter
121 }
122
123 pub fn set_filter(&mut self, filter: HistoryFilter) {
124 if self.filter != filter {
125 self.filter = filter;
126 self.invalidated = true;
127 }
128 }
129
130 pub fn needs_rebuild(&self, now: DateTime<Utc>, offset: FixedOffset) -> bool {
131 let Some(built_at) = &self.built_at else {
132 return true;
133 };
134 self.invalidated
135 || built_at.day != now.with_timezone(&offset).date_naive()
136 || now - built_at.time >= Duration::seconds(MAX_AGE_SECONDS)
137 }
138
139 pub fn entries(&self) -> &[ListEntry] {
140 &self.entries
141 }
142
143 pub fn rebuild(
144 &mut self,
145 history: &[CallLogEntry],
146 chats: &[ChatRecord],
147 events: &[CalendarEvent],
148 now: DateTime<Utc>,
149 offset: FixedOffset,
150 ) {
151 let mut entries = vec![ListEntry::Section(UPCOMING_TITLE)];
152 let days = group_by_day(events, now, offset);
153 if days.is_empty() {
154 entries.push(ListEntry::Empty(NO_MEETINGS_TEXT));
155 }
156 for day in days {
157 entries.push(ListEntry::Day(day.label));
158 entries.extend(day.rows.into_iter().map(ListEntry::Agenda));
159 }
160 entries.push(ListEntry::Section(RECENT_TITLE));
161 entries.push(ListEntry::Filters(self.filter));
162 let filter = self.filter;
163 let admitted = history.iter().filter(|entry| filter.admits(entry));
164 let calls = call_rows(admitted, chats, now, offset);
165 if calls.is_empty() {
166 entries.push(ListEntry::Empty(self.filter.empty_text()));
167 }
168 entries.extend(calls.into_iter().map(ListEntry::Call));
169 self.set_entries(entries);
170 self.built_at = Some(BuiltAt {
171 day: now.with_timezone(&offset).date_naive(),
172 time: now,
173 });
174 self.invalidated = false;
175 }
176
177 fn set_entries(&mut self, entries: Vec<ListEntry>) {
178 let mut position = 0.;
179 self.starts = Vec::with_capacity(entries.len());
180 self.ends = Vec::with_capacity(entries.len());
181 for entry in &entries {
182 self.starts.push(position);
183 position += entry.height();
184 self.ends.push(position);
185 }
186 self.entries = entries;
187 }
188
189 pub fn total_height(&self) -> f32 {
190 self.ends.last().copied().unwrap_or(0.)
191 }
192
193 pub fn window(&self, from: f32, to: f32) -> VisibleWindow {
194 let first = self.ends.partition_point(|end| *end < from);
195 let last = self.starts.partition_point(|start| *start <= to).max(first);
196 VisibleWindow {
197 before: self
198 .starts
199 .get(first)
200 .copied()
201 .unwrap_or(self.total_height()),
202 after: match last.checked_sub(1).and_then(|index| self.ends.get(index)) {
203 Some(end) if last > first => self.total_height() - end,
204 _ => 0.,
205 },
206 range: first..last,
207 }
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use chatsvc::ResponseType;
214 use chrono::TimeZone;
215 use teams_core::{CallDirection, CallOutcome};
216
217 use super::*;
218
219 fn now() -> DateTime<Utc> {
220 Utc.with_ymd_and_hms(2026, 10, 12, 8, 0, 0).unwrap()
221 }
222
223 fn zero() -> FixedOffset {
224 FixedOffset::east_opt(0).unwrap()
225 }
226
227 fn call(id: &str) -> CallLogEntry {
228 CallLogEntry {
229 call_id: id.into(),
230 started_at: now() - Duration::hours(3),
231 duration_seconds: Some(60),
232 direction: CallDirection::Outgoing,
233 outcome: CallOutcome::Accepted,
234 is_meeting: false,
235 peer_id: Some("8:orgid:bea".into()),
236 peer_name: Some("Bea".into()),
237 thread_id: None,
238 }
239 }
240
241 fn event(id: &str, minutes_from_now: i64) -> CalendarEvent {
242 CalendarEvent {
243 object_id: id.into(),
244 subject: id.into(),
245 start: now() + Duration::minutes(minutes_from_now),
246 end: now() + Duration::minutes(minutes_from_now + 30),
247 all_day: false,
248 cancelled: false,
249 online: true,
250 join_url: None,
251 thread_id: None,
252 organizer_name: None,
253 organizer_address: None,
254 ical_uid: None,
255 response: ResponseType::Accepted,
256 }
257 }
258
259 fn built(calls: usize, events: usize) -> CallsList {
260 let history: Vec<CallLogEntry> =
261 (0..calls).map(|index| call(&format!("c{index}"))).collect();
262 let agenda: Vec<CalendarEvent> = (0..events)
263 .map(|index| event(&format!("e{index}"), 30 + index as i64 * 60))
264 .collect();
265 let mut list = CallsList::default();
266 list.rebuild(&history, &[], &agenda, now(), zero());
267 list
268 }
269
270 #[test]
271 fn empty_sections_show_their_empty_text() {
272 let list = built(0, 0);
273 assert_eq!(
274 list.entries(),
275 [
276 ListEntry::Section("Upcoming"),
277 ListEntry::Empty("No meetings in the next 7 days"),
278 ListEntry::Section("Recent"),
279 ListEntry::Filters(HistoryFilter::All),
280 ListEntry::Empty("No calls yet"),
281 ]
282 );
283 }
284
285 #[test]
286 fn the_history_filter_keeps_only_matching_calls() {
287 let missed = CallLogEntry {
288 direction: CallDirection::Incoming,
289 outcome: CallOutcome::Missed,
290 ..call("missed")
291 };
292 let incoming = CallLogEntry {
293 direction: CallDirection::Incoming,
294 ..call("incoming")
295 };
296 let history = [missed, incoming, call("outgoing")];
297 let keys = |filter: HistoryFilter| -> Vec<String> {
298 let mut list = CallsList::default();
299 list.set_filter(filter);
300 list.rebuild(&history, &[], &[], now(), zero());
301 list.entries()
302 .iter()
303 .filter_map(|entry| match entry {
304 ListEntry::Call(row) => Some(row.key.clone()),
305 ListEntry::Empty(text) => Some((*text).to_owned()),
306 _ => None,
307 })
308 .skip(1)
309 .collect()
310 };
311 assert_eq!(keys(HistoryFilter::All), ["missed", "incoming", "outgoing"]);
312 assert_eq!(keys(HistoryFilter::Missed), ["missed"]);
313 assert_eq!(keys(HistoryFilter::Incoming), ["incoming"]);
314 assert_eq!(keys(HistoryFilter::Outgoing), ["outgoing"]);
315 let mut list = CallsList::default();
316 list.set_filter(HistoryFilter::Missed);
317 list.rebuild(&[call("outgoing")], &[], &[], now(), zero());
318 assert_eq!(list.entries().last(), Some(&ListEntry::Empty("No missed calls")));
319 }
320
321 #[test]
322 fn upcoming_comes_before_recent_with_day_headers() {
323 let list = built(2, 2);
324 let kinds: Vec<&str> = list
325 .entries()
326 .iter()
327 .map(|entry| match entry {
328 ListEntry::Section(_) => "section",
329 ListEntry::Filters(_) => "filters",
330 ListEntry::Day(_) => "day",
331 ListEntry::Agenda(_) => "agenda",
332 ListEntry::Call(_) => "call",
333 ListEntry::Empty(_) => "empty",
334 })
335 .collect();
336 assert_eq!(
337 kinds,
338 [
339 "section", "day", "agenda", "agenda", "section", "filters", "call", "call"
340 ]
341 );
342 }
343
344 #[test]
345 fn a_fresh_list_needs_a_rebuild_until_built() {
346 let mut list = CallsList::default();
347 assert!(list.needs_rebuild(now(), zero()));
348 list.rebuild(&[], &[], &[], now(), zero());
349 assert!(!list.needs_rebuild(now() + Duration::seconds(30), zero()));
350 }
351
352 #[test]
353 fn invalidation_age_and_a_new_day_force_a_rebuild() {
354 let mut list = built(0, 0);
355 list.invalidate();
356 assert!(list.needs_rebuild(now(), zero()));
357 list.rebuild(&[], &[], &[], now(), zero());
358 assert!(list.needs_rebuild(now() + Duration::seconds(61), zero()));
359 assert!(list.needs_rebuild(now() + Duration::hours(17), zero()));
360 }
361
362 #[test]
363 fn the_window_keeps_only_rows_on_screen_and_spacers_for_the_rest() {
364 let list = built(100, 0);
365 let total = list.total_height();
366 let window = list.window(1000., 1200.);
367 assert!(window.range.len() < 12);
368 assert!(window.range.start > 10);
369 assert_eq!(window.before, list.starts[window.range.start]);
370 let shown: f32 = list.entries()[window.range.clone()]
371 .iter()
372 .map(ListEntry::height)
373 .sum();
374 assert!((window.before + shown + window.after - total).abs() < 0.01);
375 }
376
377 #[test]
378 fn the_window_clamps_at_both_ends() {
379 let list = built(100, 0);
380 let top = list.window(-300., 100.);
381 assert_eq!(top.range.start, 0);
382 assert_eq!(top.before, 0.);
383 let bottom = list.window(list.total_height() - 100., list.total_height() + 500.);
384 assert_eq!(bottom.range.end, list.entries().len());
385 assert_eq!(bottom.after, 0.);
386 let empty = CallsList::default().window(0., 100.);
387 assert_eq!(empty.range, 0..0);
388 assert_eq!(empty.before, 0.);
389 assert_eq!(empty.after, 0.);
390 }
391}