BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-call-model / src / week_grid.rs

week_grid.rs

week_grid.rs 10.9 KiB Download Raw
1use chatsvc::{CalendarEvent, ResponseType, ShowAs};
2use chrono::{DateTime, Datelike, Duration, FixedOffset, NaiveDate, Utc, Weekday};
3
4pub const WORK_WEEK_DAYS: i64 = 5;
5pub const MINUTES_PER_DAY: i64 = 24 * 60;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub struct WeekBlock {
9 pub event_index: usize,
10 pub start_minute: i64,
11 pub end_minute: i64,
12 pub lane: usize,
13 pub lanes: usize,
14}
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct WeekDay {
18 pub date: NaiveDate,
19 pub all_day: Vec<usize>,
20 pub blocks: Vec<WeekBlock>,
21}
22
23pub fn week_start(date: NaiveDate) -> NaiveDate {
24 date - Duration::days(i64::from(date.weekday().num_days_from_monday()))
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
28pub enum CalendarSpan {
29 Day,
30 #[default]
31 WorkWeek,
32 Week,
33}
34
35impl CalendarSpan {
36 pub const ALL: [CalendarSpan; 3] = [
37 CalendarSpan::Day,
38 CalendarSpan::WorkWeek,
39 CalendarSpan::Week,
40 ];
41
42 pub fn label(self) -> &'static str {
43 match self {
44 CalendarSpan::Day => "Day",
45 CalendarSpan::WorkWeek => "Work week",
46 CalendarSpan::Week => "Week",
47 }
48 }
49
50 pub fn days(self) -> i64 {
51 match self {
52 CalendarSpan::Day => 1,
53 CalendarSpan::WorkWeek => WORK_WEEK_DAYS,
54 CalendarSpan::Week => 7,
55 }
56 }
57
58 pub fn start_for(self, date: NaiveDate) -> NaiveDate {
59 match self {
60 CalendarSpan::Day => date,
61 CalendarSpan::WorkWeek => work_week_for(date),
62 CalendarSpan::Week => week_start(date),
63 }
64 }
65
66 pub fn step(self) -> Duration {
67 match self {
68 CalendarSpan::Day => Duration::days(1),
69 CalendarSpan::WorkWeek | CalendarSpan::Week => Duration::weeks(1),
70 }
71 }
72}
73
74/// On a weekend the work week view shows the coming week, as Outlook does.
75pub fn work_week_for(today: NaiveDate) -> NaiveDate {
76 match today.weekday() {
77 Weekday::Sat | Weekday::Sun => week_start(today) + Duration::weeks(1),
78 _ => week_start(today),
79 }
80}
81
82pub fn local_midnight(date: NaiveDate, offset: FixedOffset) -> DateTime<Utc> {
83 date.and_hms_opt(0, 0, 0)
84 .and_then(|local| local.and_local_timezone(offset).single())
85 .map(|local| local.with_timezone(&Utc))
86 .unwrap_or_else(|| date.and_hms_opt(0, 0, 0).unwrap_or_default().and_utc())
87}
88
89pub fn week_range(
90 start: NaiveDate,
91 days: i64,
92 offset: FixedOffset,
93) -> (DateTime<Utc>, DateTime<Utc>) {
94 (
95 local_midnight(start, offset),
96 local_midnight(start + Duration::days(days), offset),
97 )
98}
99
100pub fn shown_in_calendar(event: &CalendarEvent) -> bool {
101 event.response != ResponseType::Declined
102}
103
104pub fn week_days(
105 events: &[CalendarEvent],
106 start: NaiveDate,
107 days: i64,
108 offset: FixedOffset,
109) -> Vec<WeekDay> {
110 (0..days)
111 .map(|day| {
112 let date = start + Duration::days(day);
113 let (day_start, day_end) = week_range(date, 1, offset);
114 let mut all_day = Vec::new();
115 let mut spans = Vec::new();
116 for (index, event) in events.iter().enumerate() {
117 if !shown_in_calendar(event) || event.end <= day_start || event.start >= day_end {
118 continue;
119 }
120 if event.all_day {
121 all_day.push(index);
122 continue;
123 }
124 let start_minute = (event.start.max(day_start) - day_start).num_minutes();
125 let end_minute = (event.end.min(day_end) - day_start).num_minutes();
126 spans.push((index, start_minute, end_minute.max(start_minute + 1)));
127 }
128 WeekDay {
129 date,
130 all_day,
131 blocks: lay_out(spans),
132 }
133 })
134 .collect()
135}
136
137fn lay_out(mut spans: Vec<(usize, i64, i64)>) -> Vec<WeekBlock> {
138 spans.sort_by_key(|&(index, start, end)| (start, std::cmp::Reverse(end), index));
139 let mut blocks: Vec<WeekBlock> = Vec::with_capacity(spans.len());
140 let mut cluster_start = 0;
141 let mut cluster_end = i64::MIN;
142 let mut lane_ends: Vec<i64> = Vec::new();
143 for (index, start, end) in spans {
144 if start >= cluster_end {
145 close_cluster(&mut blocks[cluster_start..], lane_ends.len());
146 cluster_start = blocks.len();
147 lane_ends.clear();
148 }
149 let lane = match lane_ends.iter().position(|&lane_end| lane_end <= start) {
150 Some(free) => {
151 lane_ends[free] = end;
152 free
153 }
154 None => {
155 lane_ends.push(end);
156 lane_ends.len() - 1
157 }
158 };
159 cluster_end = cluster_end.max(end);
160 blocks.push(WeekBlock {
161 event_index: index,
162 start_minute: start,
163 end_minute: end,
164 lane,
165 lanes: 1,
166 });
167 }
168 close_cluster(&mut blocks[cluster_start..], lane_ends.len());
169 blocks
170}
171
172fn close_cluster(blocks: &mut [WeekBlock], lanes: usize) {
173 for block in blocks {
174 block.lanes = lanes.max(1);
175 }
176}
177
178pub fn range_label(start: NaiveDate, days: i64) -> String {
179 let end = start + Duration::days(days - 1);
180 if start.month() == end.month() {
181 start.format("%B %Y").to_string()
182 } else if start.year() == end.year() {
183 format!("{} - {}", start.format("%B"), end.format("%B %Y"))
184 } else {
185 format!("{} - {}", start.format("%B %Y"), end.format("%B %Y"))
186 }
187}
188
189#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190pub enum EventLook {
191 Busy,
192 Free,
193 Tentative,
194}
195
196pub fn event_look(event: &CalendarEvent) -> EventLook {
197 match event.show_as {
198 ShowAs::Free => EventLook::Free,
199 ShowAs::Tentative => EventLook::Tentative,
200 ShowAs::Busy | ShowAs::OutOfOffice | ShowAs::WorkingElsewhere => EventLook::Busy,
201 }
202}
203
204pub fn hour_label(hour: u32, twelve_hour: bool) -> String {
205 if !twelve_hour {
206 return hour.to_string();
207 }
208 match hour {
209 0 => "12 AM".to_owned(),
210 12 => "12 PM".to_owned(),
211 hour if hour < 12 => format!("{hour} AM"),
212 hour => format!("{} PM", hour - 12),
213 }
214}
215
216#[cfg(test)]
217mod tests {
218 use chrono::TimeZone;
219
220 use super::*;
221
222 fn event(start_hour: u32, start_minute: u32, minutes: i64) -> CalendarEvent {
223 let start = Utc
224 .with_ymd_and_hms(2026, 11, 9, start_hour, start_minute, 0)
225 .unwrap();
226 CalendarEvent {
227 object_id: format!("{start_hour}:{start_minute}"),
228 subject: "Sync".into(),
229 start,
230 end: start + Duration::minutes(minutes),
231 all_day: false,
232 cancelled: false,
233 online: true,
234 join_url: None,
235 thread_id: None,
236 organizer_name: None,
237 organizer_address: None,
238 ical_uid: None,
239 show_as: Default::default(),
240 response: ResponseType::Accepted,
241 }
242 }
243
244 fn utc() -> FixedOffset {
245 FixedOffset::east_opt(0).unwrap()
246 }
247
248 #[test]
249 fn the_week_starts_on_monday() {
250 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
251 assert_eq!(
252 week_start(sunday),
253 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
254 );
255 assert_eq!(week_start(week_start(sunday)), week_start(sunday));
256 assert_eq!(
257 work_week_for(sunday),
258 NaiveDate::from_ymd_opt(2026, 11, 16).unwrap()
259 );
260 let friday = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap();
261 assert_eq!(
262 work_week_for(friday),
263 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
264 );
265 }
266
267 #[test]
268 fn overlapping_meetings_share_the_column_in_lanes() {
269 let events = vec![
270 event(9, 0, 60),
271 event(9, 30, 60),
272 event(10, 0, 30),
273 event(13, 0, 30),
274 ];
275 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
276 let days = week_days(&events, monday, WORK_WEEK_DAYS, utc());
277 assert_eq!(days.len(), 5);
278 let lanes: Vec<(usize, usize, usize)> = days[0]
279 .blocks
280 .iter()
281 .map(|block| (block.event_index, block.lane, block.lanes))
282 .collect();
283 assert_eq!(lanes, [(0, 0, 2), (1, 1, 2), (2, 0, 2), (3, 0, 1)]);
284 assert_eq!(days[0].blocks[0].start_minute, 9 * 60);
285 assert!(days[1].blocks.is_empty());
286 }
287
288 #[test]
289 fn declined_and_other_days_are_left_out_and_all_day_is_separate() {
290 let mut declined = event(9, 0, 30);
291 declined.response = ResponseType::Declined;
292 let mut all_day = event(0, 0, 24 * 60);
293 all_day.all_day = true;
294 let late = event(23, 30, 60);
295 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
296 let days = week_days(&[declined, all_day, late], monday, 2, utc());
297 assert!(days[0].blocks.iter().all(|block| block.event_index != 0));
298 assert_eq!(days[0].all_day, [1]);
299 assert_eq!(days[0].blocks[0].end_minute, MINUTES_PER_DAY);
300 assert_eq!(
301 (days[1].blocks[0].start_minute, days[1].blocks[0].end_minute),
302 (0, 30)
303 );
304 }
305
306 #[test]
307 fn spans_start_and_step_like_teams() {
308 let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();
309 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
310 assert_eq!(CalendarSpan::Day.start_for(wednesday), wednesday);
311 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday), monday);
312 assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);
313 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
314 assert_eq!(CalendarSpan::Week.start_for(sunday), monday);
315 assert_eq!(CalendarSpan::Day.step(), Duration::days(1));
316 assert_eq!(CalendarSpan::Week.days(), 7);
317 }
318
319 #[test]
320 fn labels_read_like_teams() {
321 let monday = NaiveDate::from_ymd_opt(2026, 11, 30).unwrap();
322 assert_eq!(range_label(monday, 5), "November - December 2026");
323 assert_eq!(
324 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 5),
325 "November 2026"
326 );
327 assert_eq!(hour_label(0, true), "12 AM");
328 assert_eq!(hour_label(13, true), "1 PM");
329 assert_eq!(hour_label(13, false), "13");
330 }
331
332 #[test]
333 fn free_and_tentative_meetings_look_like_teams() {
334 let mut following = event(9, 0, 30);
335 following.show_as = ShowAs::Free;
336 following.response = ResponseType::Tentative;
337 let mut tentative = event(9, 0, 30);
338 tentative.show_as = ShowAs::Tentative;
339 let mut away = event(9, 0, 30);
340 away.show_as = ShowAs::OutOfOffice;
341 assert_eq!(event_look(&following), EventLook::Free);
342 assert_eq!(event_look(&tentative), EventLook::Tentative);
343 assert_eq!(event_look(&away), EventLook::Busy);
344 assert_eq!(event_look(&event(9, 0, 30)), EventLook::Busy);
345 }
346}