BlueGit

ict rusty-teams

Files

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

week_grid.rs

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