BlueGit

ict rusty-teams

Files

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

week_grid.rs

d69b1473 History
week_grid.rs 9.7 KiB Download Raw
1use chatsvc::{CalendarEvent, ResponseType};
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
189pub fn hour_label(hour: u32) -> String {
190 match hour {
191 0 => "12 AM".to_owned(),
192 12 => "12 PM".to_owned(),
193 hour if hour < 12 => format!("{hour} AM"),
194 hour => format!("{} PM", hour - 12),
195 }
196}
197
198#[cfg(test)]
199mod tests {
200 use chrono::TimeZone;
201
202 use super::*;
203
204 fn event(start_hour: u32, start_minute: u32, minutes: i64) -> CalendarEvent {
205 let start = Utc
206 .with_ymd_and_hms(2026, 11, 9, start_hour, start_minute, 0)
207 .unwrap();
208 CalendarEvent {
209 object_id: format!("{start_hour}:{start_minute}"),
210 subject: "Sync".into(),
211 start,
212 end: start + Duration::minutes(minutes),
213 all_day: false,
214 cancelled: false,
215 online: true,
216 join_url: None,
217 thread_id: None,
218 organizer_name: None,
219 organizer_address: None,
220 ical_uid: None,
221 response: ResponseType::Accepted,
222 }
223 }
224
225 fn utc() -> FixedOffset {
226 FixedOffset::east_opt(0).unwrap()
227 }
228
229 #[test]
230 fn the_week_starts_on_monday() {
231 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
232 assert_eq!(
233 week_start(sunday),
234 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
235 );
236 assert_eq!(week_start(week_start(sunday)), week_start(sunday));
237 assert_eq!(
238 work_week_for(sunday),
239 NaiveDate::from_ymd_opt(2026, 11, 16).unwrap()
240 );
241 let friday = NaiveDate::from_ymd_opt(2026, 11, 13).unwrap();
242 assert_eq!(
243 work_week_for(friday),
244 NaiveDate::from_ymd_opt(2026, 11, 9).unwrap()
245 );
246 }
247
248 #[test]
249 fn overlapping_meetings_share_the_column_in_lanes() {
250 let events = vec![
251 event(9, 0, 60),
252 event(9, 30, 60),
253 event(10, 0, 30),
254 event(13, 0, 30),
255 ];
256 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
257 let days = week_days(&events, monday, WORK_WEEK_DAYS, utc());
258 assert_eq!(days.len(), 5);
259 let lanes: Vec<(usize, usize, usize)> = days[0]
260 .blocks
261 .iter()
262 .map(|block| (block.event_index, block.lane, block.lanes))
263 .collect();
264 assert_eq!(lanes, [(0, 0, 2), (1, 1, 2), (2, 0, 2), (3, 0, 1)]);
265 assert_eq!(days[0].blocks[0].start_minute, 9 * 60);
266 assert!(days[1].blocks.is_empty());
267 }
268
269 #[test]
270 fn declined_and_other_days_are_left_out_and_all_day_is_separate() {
271 let mut declined = event(9, 0, 30);
272 declined.response = ResponseType::Declined;
273 let mut all_day = event(0, 0, 24 * 60);
274 all_day.all_day = true;
275 let late = event(23, 30, 60);
276 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
277 let days = week_days(&[declined, all_day, late], monday, 2, utc());
278 assert!(days[0].blocks.iter().all(|block| block.event_index != 0));
279 assert_eq!(days[0].all_day, [1]);
280 assert_eq!(days[0].blocks[0].end_minute, MINUTES_PER_DAY);
281 assert_eq!(
282 (days[1].blocks[0].start_minute, days[1].blocks[0].end_minute),
283 (0, 30)
284 );
285 }
286
287 #[test]
288 fn spans_start_and_step_like_teams() {
289 let wednesday = NaiveDate::from_ymd_opt(2026, 11, 11).unwrap();
290 let monday = NaiveDate::from_ymd_opt(2026, 11, 9).unwrap();
291 assert_eq!(CalendarSpan::Day.start_for(wednesday), wednesday);
292 assert_eq!(CalendarSpan::WorkWeek.start_for(wednesday), monday);
293 assert_eq!(CalendarSpan::Week.start_for(wednesday), monday);
294 let sunday = NaiveDate::from_ymd_opt(2026, 11, 15).unwrap();
295 assert_eq!(CalendarSpan::Week.start_for(sunday), monday);
296 assert_eq!(CalendarSpan::Day.step(), Duration::days(1));
297 assert_eq!(CalendarSpan::Week.days(), 7);
298 }
299
300 #[test]
301 fn labels_read_like_teams() {
302 let monday = NaiveDate::from_ymd_opt(2026, 11, 30).unwrap();
303 assert_eq!(range_label(monday, 5), "November - December 2026");
304 assert_eq!(
305 range_label(NaiveDate::from_ymd_opt(2026, 11, 9).unwrap(), 5),
306 "November 2026"
307 );
308 assert_eq!(hour_label(0), "12 AM");
309 assert_eq!(hour_label(13), "1 PM");
310 }
311}