BlueGit

ict rusty-teams

Files

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

week_grid.rs

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