BlueGit

ict rusty-teams

Files

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

list.rs

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