calendar.rs
⎇
Raw
1//! The calendar section's main area: the month grid, the agenda, the open
2//! invitations and the details of one event.
3//!
4//! The server expands recurrences and resolves time zones. This view only
5//! places the instances it gets on local days.
6
7use std::collections::{HashMap, HashSet};
8
9use leptos::prelude::*;
10use wasm_bindgen::{JsCast, JsValue};
11use wasm_bindgen_futures::spawn_local;
12
13use crate::api::{
14 self, PimCollectionInfo, PimEventDetail, PimInstance, PimInvitation, PimObjectDetail, PimReply,
15};
16use crate::components::icon::icon_svg;
17use crate::components::modal::Modal;
18use crate::components::toast::{ToastMsg, show, show_error};
19use crate::i18n::{self, k};
20use crate::icons::IconName;
21use crate::router::{self, Location, Section, navigate};
22use crate::util::{intl, owned_window_listener};
23use crate::views::pim::{browser_tz, display_name, safe_color};
24
25// ---------------------------------------------------------------------------
26// Days and the month grid (pure, so it is testable off the browser)
27// ---------------------------------------------------------------------------
28
29/// Days since 1970-01-01 of a proleptic Gregorian date.
30pub fn days_from_civil(y: i32, m: u32, d: u32) -> i64 {
31 let y = i64::from(if m <= 2 { y - 1 } else { y });
32 let era = y.div_euclid(400);
33 let yoe = y - era * 400;
34 let m = i64::from(m);
35 let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + i64::from(d) - 1;
36 let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
37 era * 146_097 + doe - 719_468
38}
39
40pub fn civil_from_days(z: i64) -> (i32, u32, u32) {
41 let z = z + 719_468;
42 let era = z.div_euclid(146_097);
43 let doe = z - era * 146_097;
44 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
45 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
46 let mp = (5 * doy + 2) / 153;
47 let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
48 let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
49 let y = (yoe + era * 400 + i64::from(m <= 2)) as i32;
50 (y, m, d)
51}
52
53/// 0 is Sunday.
54pub fn weekday(day: i64) -> u32 {
55 (day + 4).rem_euclid(7) as u32
56}
57
58/// The first day the month grid shows: the week start on or before the 1st.
59pub fn grid_start(y: i32, m: u32, week_start: u32) -> i64 {
60 let first = days_from_civil(y, m, 1);
61 first - i64::from((weekday(first) + 7 - week_start) % 7)
62}
63
64/// The grid always shows six weeks, so its height never jumps.
65pub const GRID_DAYS: i64 = 42;
66
67/// Cancelled, or declined by the calendar's owner: shown struck through.
68fn struck(i: &api::PimInstance) -> bool {
69 i.status.as_deref() == Some("CANCELLED") || i.partstat.as_deref() == Some("DECLINED")
70}
71
72fn add_months(y: i32, m: u32, n: i32) -> (i32, u32) {
73 let i = y * 12 + m as i32 - 1 + n;
74 (i.div_euclid(12), i.rem_euclid(12) as u32 + 1)
75}
76
77/// Where an instance lies in local time: its first and last day, and the
78/// minute of the day it starts on the first and ends on the last. An end at
79/// midnight counts as minute 1440 of the day before.
80#[derive(Clone, Copy, Debug, PartialEq)]
81pub struct Span {
82 pub first: i64,
83 pub last: i64,
84 pub all_day: bool,
85 pub start_min: u32,
86 pub end_min: u32,
87}
88
89impl Span {
90 /// The day and minute the instance ends, midnight as 00:00 of the next day.
91 fn end_at(&self) -> (i64, u32) {
92 match self.end_min {
93 1440 => (self.last + 1, 0),
94 m => (self.last, m),
95 }
96 }
97
98 /// A bar across days, not a line with a time.
99 fn is_bar(&self) -> bool {
100 self.all_day || self.first != self.last
101 }
102
103 fn covers(&self, day: i64) -> bool {
104 self.first <= day && day <= self.last
105 }
106}
107
108/// One piece of an instance in a week row. An instance hidden on some of
109/// its days by the "+N more" line becomes several pieces.
110#[derive(Clone, Debug, PartialEq)]
111pub struct Piece {
112 /// Index into the spans given to [`layout_week`].
113 pub item: usize,
114 pub col: usize,
115 pub len: usize,
116 pub line: usize,
117 /// The instance starts in this piece, rather than continuing into it.
118 pub starts: bool,
119 pub ends: bool,
120}
121
122#[derive(Clone, Debug, PartialEq)]
123pub struct WeekLayout {
124 pub pieces: Vec<Piece>,
125 /// Per day: how many instances the "+N more" line stands for.
126 pub more: [usize; 7],
127}
128
129/// Place a week's instances on `lines` lines. Bars come first, longer ones
130/// on top, then timed instances by start. A day with more instances than
131/// lines gives its last line to "+N more".
132pub fn layout_week(spans: &[Span], week: i64, lines: usize) -> WeekLayout {
133 let mut items: Vec<(usize, usize, usize)> = spans
134 .iter()
135 .enumerate()
136 .filter(|(_, s)| s.first <= week + 6 && s.last >= week)
137 .map(|(i, s)| {
138 let c0 = (s.first.max(week) - week) as usize;
139 let c1 = (s.last.min(week + 6) - week) as usize;
140 (i, c0, c1)
141 })
142 .collect();
143 items.sort_by_key(|&(i, c0, c1)| {
144 let s = &spans[i];
145 (!s.is_bar(), c0, usize::MAX - (c1 - c0), s.start_min, i)
146 });
147 let mut used: Vec<[bool; 7]> = Vec::new();
148 let mut placed = Vec::with_capacity(items.len());
149 let mut count = [0usize; 7];
150 for &(i, c0, c1) in &items {
151 let line = (0..)
152 .find(|&l| {
153 used.get(l)
154 .is_none_or(|row| !row[c0..=c1].iter().any(|&u| u))
155 })
156 .unwrap_or(0);
157 if used.len() <= line {
158 used.resize(line + 1, [false; 7]);
159 }
160 for c in c0..=c1 {
161 used[line][c] = true;
162 count[c] = count[c].max(line + 1);
163 }
164 placed.push((i, c0, c1, line));
165 }
166 let limit = |c: usize| {
167 if count[c] <= lines {
168 lines
169 } else {
170 lines.saturating_sub(1)
171 }
172 };
173 let mut pieces = Vec::new();
174 for &(i, c0, c1, line) in &placed {
175 let mut run: Option<usize> = None;
176 for c in c0..=c1 + 1 {
177 if c <= c1 && line < limit(c) {
178 run.get_or_insert(c);
179 } else if let Some(start) = run.take() {
180 let s = &spans[i];
181 pieces.push(Piece {
182 item: i,
183 col: start,
184 len: c - start,
185 line,
186 starts: start == c0 && s.first >= week,
187 ends: c - 1 == c1 && s.last <= week + 6,
188 });
189 }
190 }
191 }
192 let more = std::array::from_fn(|c| {
193 placed
194 .iter()
195 .filter(|&&(_, c0, c1, line)| c0 <= c && c <= c1 && line >= limit(c))
196 .count()
197 });
198 WeekLayout { pieces, more }
199}
200
201/// What an instance's time looks like on one of its days.
202#[derive(Clone, Copy, Debug, PartialEq)]
203pub enum When {
204 AllDay,
205 At(u32),
206 Range(u32, u32),
207 From(u32),
208 Until(u32),
209}
210
211pub fn when_on(s: &Span, day: i64) -> When {
212 if s.all_day {
213 When::AllDay
214 } else if s.first == s.last && s.start_min == s.end_min {
215 When::At(s.start_min)
216 } else if s.first == s.last {
217 When::Range(s.start_min, s.end_min)
218 } else if day == s.first {
219 When::From(s.start_min)
220 } else if day == s.last && s.end_min < 1440 {
221 When::Until(s.end_min)
222 } else {
223 When::AllDay
224 }
225}
226
227/// Split plain text into runs, `true` for an `http(s)://` link. A trailing
228/// period or closing bracket belongs to the sentence, not the link.
229pub fn split_links(text: &str) -> Vec<(String, bool)> {
230 let mut out = Vec::new();
231 let mut rest = text;
232 let mut from = 0;
233 while let Some((at, scheme)) = ["https://", "http://"]
234 .iter()
235 .filter_map(|p| rest[from..].find(p).map(|i| (from + i, p.len())))
236 .min()
237 {
238 let end = rest[at..]
239 .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"'))
240 .map_or(rest.len(), |e| at + e);
241 let mut link = &rest[at..end];
242 loop {
243 let t = link.trim_end_matches(['.', ',', ';', ':', '!', '?']);
244 let t = match t.strip_suffix(')') {
245 Some(u) if t.matches(')').count() > t.matches('(').count() => u,
246 _ => t,
247 };
248 if t.len() == link.len() {
249 break;
250 }
251 link = t;
252 }
253 if link.len() <= scheme {
254 from = at + scheme;
255 continue;
256 }
257 if at > 0 {
258 out.push((rest[..at].to_string(), false));
259 }
260 out.push((link.to_string(), true));
261 rest = &rest[at + link.len()..];
262 from = 0;
263 }
264 if !rest.is_empty() {
265 out.push((rest.to_string(), false));
266 }
267 out
268}
269
270// ---------------------------------------------------------------------------
271// Browser dates
272// ---------------------------------------------------------------------------
273
274fn js_day(d: &js_sys::Date) -> i64 {
275 days_from_civil(d.get_full_year() as i32, d.get_month() + 1, d.get_date())
276}
277
278fn day_date(day: i64) -> js_sys::Date {
279 let (y, m, d) = civil_from_days(day);
280 js_sys::Date::new_with_year_month_day(y as u32, m as i32 - 1, d as i32)
281}
282
283fn today() -> i64 {
284 js_day(&js_sys::Date::new_0())
285}
286
287/// Local midnight of `day` as RFC 3339 UTC, for the instances endpoint.
288fn day_rfc3339(day: i64) -> String {
289 day_date(day).to_iso_string().into()
290}
291
292fn span_of(i: &PimInstance) -> Span {
293 span_at(&i.start, &i.end, i.all_day)
294}
295
296fn span_at(start: &str, end: &str, all_day: bool) -> Span {
297 let s = js_sys::Date::new(&start.into());
298 let e = js_sys::Date::new(&end.into());
299 let first = js_day(&s);
300 let start_min = s.get_hours() * 60 + s.get_minutes();
301 let (last, end_min) = if e.get_time() > s.get_time() {
302 let last = js_day(&js_sys::Date::new(&JsValue::from_f64(e.get_time() - 1.0)));
303 let end_min = if js_day(&e) > last {
304 1440
305 } else {
306 e.get_hours() * 60 + e.get_minutes()
307 };
308 (last, end_min)
309 } else {
310 (first, start_min)
311 };
312 Span {
313 first,
314 last: last.max(first),
315 all_day,
316 start_min,
317 end_min,
318 }
319}
320
321fn fmt_min(day: i64, min: u32) -> String {
322 let (y, m, d) = civil_from_days(day);
323 let t = js_sys::Date::new_with_year_month_day_hr_min(
324 y as u32,
325 m as i32 - 1,
326 d as i32,
327 (min / 60) as i32,
328 (min % 60) as i32,
329 );
330 intl(&t, &[("hour", "2-digit"), ("minute", "2-digit")])
331}
332
333fn fmt_when(w: When, day: i64) -> String {
334 match w {
335 When::AllDay => i18n::t(k::PIM_ALL_DAY).to_string(),
336 When::At(m) => fmt_min(day, m),
337 When::Range(a, b) => format!("{} – {}", fmt_min(day, a), fmt_min(day, b)),
338 When::From(m) => i18n::t_fmt(k::PIM_FROM_TIME, &fmt_min(day, m)),
339 When::Until(m) => i18n::t_fmt(k::PIM_UNTIL_TIME, &fmt_min(day, m)),
340 }
341}
342
343fn fmt_day_long(day: i64) -> String {
344 intl(
345 &day_date(day),
346 &[
347 ("weekday", "long"),
348 ("day", "numeric"),
349 ("month", "long"),
350 ("year", "numeric"),
351 ],
352 )
353}
354
355fn fmt_day_short(day: i64) -> String {
356 intl(
357 &day_date(day),
358 &[
359 ("weekday", "short"),
360 ("day", "numeric"),
361 ("month", "short"),
362 ("year", "numeric"),
363 ],
364 )
365}
366
367/// The full time of an instance, for its details.
368fn fmt_span(s: &Span) -> String {
369 match (s.all_day, s.first == s.last) {
370 (true, true) => fmt_day_short(s.first),
371 (true, false) => format!("{} – {}", fmt_day_short(s.first), fmt_day_short(s.last)),
372 (false, true) => format!(
373 "{} · {}",
374 fmt_day_short(s.first),
375 fmt_when(when_on(s, s.first), s.first)
376 ),
377 (false, false) => {
378 let (day, min) = s.end_at();
379 format!(
380 "{} {} – {} {}",
381 fmt_day_short(s.first),
382 fmt_min(s.first, s.start_min),
383 fmt_day_short(day),
384 fmt_min(day, min)
385 )
386 }
387 }
388}
389
390// ---------------------------------------------------------------------------
391// The view
392// ---------------------------------------------------------------------------
393
394const TAB_IDS: [&str; 3] = ["cal-tab-month", "cal-tab-agenda", "cal-tab-invitations"];
395
396/// Lines per day cell in the month grid, the last one shared with
397/// "+N more".
398const LINES: usize = 4;
399
400#[derive(Clone, Copy, Debug, PartialEq)]
401enum CalView {
402 Month(i32, u32),
403 Agenda,
404 Invitations,
405}
406
407/// `YYYY-MM` from the URL. Outside 1000–9999 JS dates and the grid disagree.
408fn parse_month(ym: &str) -> Option<(i32, u32)> {
409 let (y, m) = ym.split_once('-')?;
410 let (y, m) = (y.parse().ok()?, m.parse().ok()?);
411 ((1000..=9999).contains(&y) && (1..=12).contains(&m)).then_some((y, m))
412}
413
414impl CalView {
415 fn from_path(path: &[String]) -> Self {
416 match path.first().map(String::as_str) {
417 Some("agenda") => CalView::Agenda,
418 Some("invitations") => CalView::Invitations,
419 _ => path
420 .get(1)
421 .and_then(|ym| parse_month(ym))
422 .map(|(y, m)| CalView::Month(y, m))
423 .unwrap_or_else(|| {
424 let (y, m, _) = civil_from_days(today());
425 CalView::Month(y, m)
426 }),
427 }
428 }
429
430 fn path(self) -> Vec<String> {
431 match self {
432 CalView::Month(y, m) => vec!["month".into(), format!("{y:04}-{m:02}")],
433 CalView::Agenda => vec!["agenda".into()],
434 CalView::Invitations => vec!["invitations".into()],
435 }
436 }
437}
438
439fn location(view: CalView) -> Location {
440 Location {
441 section: Section::Calendar,
442 path: view.path(),
443 ..Location::root()
444 }
445}
446
447fn go(view: CalView) {
448 navigate(&location(view));
449}
450
451/// The event whose details are open, as the URL names it:
452/// `{collection}/{recurrence id or -}/{name}`.
453#[derive(Clone, Debug, PartialEq)]
454struct Opened {
455 collection_id: i64,
456 recurrence_id: Option<String>,
457 name: String,
458}
459
460impl Opened {
461 fn of(i: &PimInstance) -> Self {
462 Opened {
463 collection_id: i.collection_id,
464 recurrence_id: i.recurrence_id.clone(),
465 name: i.name.clone(),
466 }
467 }
468
469 fn param(&self) -> String {
470 format!(
471 "{}/{}/{}",
472 self.collection_id,
473 self.recurrence_id.as_deref().unwrap_or("-"),
474 self.name
475 )
476 }
477
478 fn parse(s: &str) -> Option<Self> {
479 let mut it = s.splitn(3, '/');
480 let collection_id = it.next()?.parse().ok()?;
481 let rid = it.next()?;
482 let name = it.next()?.to_string();
483 Some(Opened {
484 collection_id,
485 recurrence_id: (rid != "-").then(|| rid.to_string()),
486 name,
487 })
488 }
489
490 fn open(&self) {
491 router::set_open(&self.param());
492 }
493}
494
495/// An invitation as the instance it names, for the day and time helpers.
496fn inv_instance(v: &PimInvitation) -> PimInstance {
497 PimInstance {
498 collection_id: v.collection_id,
499 name: v.name.clone(),
500 uid: v.uid.clone(),
501 recurrence_id: v.recurrence_id.clone(),
502 start: v.start.clone(),
503 end: v.end.clone(),
504 all_day: v.all_day,
505 component: "VEVENT".into(),
506 summary: v.summary.clone(),
507 location: v.location.clone(),
508 status: None,
509 transparent: false,
510 has_attendees: true,
511 partstat: None,
512 organizer: None,
513 }
514}
515
516/// An instance with what the views derive from it.
517#[derive(Clone)]
518struct Shown {
519 inst: PimInstance,
520 span: Span,
521 color: String,
522}
523
524#[component]
525pub fn CalendarMain(
526 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
527 hidden: RwSignal<HashSet<i64>>,
528 loc: ReadSignal<Location>,
529 /// 0 is Sunday. From the profile.
530 week_start: Signal<u32>,
531) -> impl IntoView {
532 let view = Memo::new(move |_| loc.with(|l| CalView::from_path(&l.path)));
533 let opened = Memo::new(move |_| loc.with(|l| l.open.as_deref().and_then(Opened::parse)));
534 // Bumped after an answer or an import: every list refetches.
535 let tick = RwSignal::new(0u32);
536
537 let month = RwSignal::new(Option::<Result<api::PimInstances, String>>::None);
538 let month_seq = StoredValue::new(0u32);
539 let month_key = StoredValue::new(None::<(i32, u32)>);
540 // The new month's grid appears only after its fetch, without focus.
541 let refocus = StoredValue::new(false);
542 Effect::new(move |_| {
543 tick.track();
544 collections.track();
545 let CalView::Month(y, m) = view.get() else {
546 return;
547 };
548 // Another month's instances would land on the wrong days.
549 if month_key.get_value() != Some((y, m)) {
550 month_key.set_value(Some((y, m)));
551 month.set(None);
552 }
553 let start = grid_start(y, m, week_start.get());
554 let seq = month_seq.get_value() + 1;
555 month_seq.set_value(seq);
556 spawn_local(async move {
557 let r = api::pim_instances(
558 &day_rfc3339(start),
559 &day_rfc3339(start + GRID_DAYS),
560 &browser_tz(),
561 )
562 .await;
563 if month_seq.try_get_value() == Some(seq) {
564 let _ = month.try_set(Some(r.map_err(|e| e.to_string())));
565 if refocus.try_get_value() == Some(true) {
566 refocus.set_value(false);
567 request_animation_frame(|| {
568 let cell = web_sys::window()
569 .and_then(|w| w.document())
570 .and_then(|d| {
571 d.query_selector(".cal-weeks .cal-cell:not(.cal-out)")
572 .ok()
573 .flatten()
574 })
575 .and_then(|e| e.dyn_into::<web_sys::HtmlElement>().ok());
576 if let Some(cell) = cell {
577 let _ = cell.focus();
578 }
579 });
580 }
581 }
582 });
583 });
584
585 let agenda = RwSignal::new(Option::<Result<api::PimInstances, String>>::None);
586 let agenda_seq = StoredValue::new(0u32);
587 Effect::new(move |_| {
588 tick.track();
589 collections.track();
590 if view.get() != CalView::Agenda {
591 return;
592 }
593 let from = today();
594 let seq = agenda_seq.get_value() + 1;
595 agenda_seq.set_value(seq);
596 spawn_local(async move {
597 let r = api::pim_instances(
598 &day_rfc3339(from),
599 &day_rfc3339(from + AGENDA_DAYS),
600 &browser_tz(),
601 )
602 .await;
603 if agenda_seq.try_get_value() == Some(seq) {
604 let _ = agenda.try_set(Some(r.map_err(|e| e.to_string())));
605 }
606 });
607 });
608
609 let invitations = RwSignal::new(Option::<Result<Vec<PimInvitation>, String>>::None);
610 let invitations_seq = StoredValue::new(0u32);
611 Effect::new(move |_| {
612 tick.track();
613 collections.track();
614 let seq = invitations_seq.get_value() + 1;
615 invitations_seq.set_value(seq);
616 spawn_local(async move {
617 let r = api::pim_invitations(&browser_tz()).await;
618 if invitations_seq.try_get_value() == Some(seq) {
619 let _ = invitations.try_set(Some(r.map_err(|e| e.to_string())));
620 }
621 });
622 });
623 let refresh = Callback::new(move |_| tick.update(|t| *t += 1));
624
625 let colors = Memo::new(move |_| {
626 collections.with(|c| {
627 c.iter()
628 .flatten()
629 .map(|c| (c.id, safe_color(c.color.as_deref())))
630 .collect::<HashMap<_, _>>()
631 })
632 });
633 let shown = move |list: &api::PimInstances| -> Vec<Shown> {
634 let colors = colors.get();
635 hidden.with(|h| {
636 list.instances
637 .iter()
638 .filter(|i| !h.contains(&i.collection_id))
639 .map(|i| Shown {
640 span: span_of(i),
641 color: colors
642 .get(&i.collection_id)
643 .cloned()
644 .unwrap_or_else(|| safe_color(None)),
645 inst: i.clone(),
646 })
647 .collect()
648 })
649 };
650
651 // PageUp / PageDown turn the month while the grid has focus. Elsewhere
652 // they scroll the page to the day list.
653 owned_window_listener(leptos::ev::keydown, move |ev| {
654 let step = match ev.key().as_str() {
655 "PageUp" => -1,
656 "PageDown" => 1,
657 _ => return,
658 };
659 if ev.alt_key() || ev.ctrl_key() || ev.meta_key() || ev.shift_key() {
660 return;
661 }
662 let in_grid = web_sys::window()
663 .and_then(|w| w.document())
664 .and_then(|d| d.active_element())
665 .and_then(|e| e.closest(".cal-weeks").ok().flatten())
666 .is_some();
667 if let (CalView::Month(y, m), true) = (view.get_untracked(), in_grid) {
668 ev.prevent_default();
669 refocus.set_value(true);
670 let (y, m) = add_months(y, m, step);
671 go(CalView::Month(y, m));
672 }
673 });
674
675 let pending = move || {
676 invitations.with(|i| match i {
677 Some(Ok(list)) => list.len(),
678 _ => 0,
679 })
680 };
681 let is_month = Memo::new(move |_| matches!(view.get(), CalView::Month(..)));
682 // The month view selects today again even when the month stays.
683 let today_clicks = RwSignal::new(0u32);
684 // The month shown, or this month from another tab.
685 let this_month = move || match view.get_untracked() {
686 v @ CalView::Month(..) => v,
687 _ => {
688 let (y, m, _) = civil_from_days(today());
689 CalView::Month(y, m)
690 }
691 };
692 let step_month = move |step: i32| {
693 if let CalView::Month(y, m) = view.get_untracked() {
694 let (y, m) = add_months(y, m, step);
695 go(CalView::Month(y, m));
696 }
697 };
698 let title = move || match view.get() {
699 CalView::Month(y, m) => intl(
700 &js_sys::Date::new_with_year_month_day(y as u32, m as i32 - 1, 1),
701 &[("month", "long"), ("year", "numeric")],
702 ),
703 CalView::Agenda => i18n::t(k::PIM_UPCOMING).to_string(),
704 CalView::Invitations => i18n::t(k::PIM_INVITATIONS).to_string(),
705 };
706 let tab_of = |v: CalView| match v {
707 CalView::Month(..) => 0,
708 CalView::Agenda => 1,
709 CalView::Invitations => 2,
710 };
711 let selected = move |i: usize| tab_of(view.get()) == i;
712 let tab_at = move |i: usize| [this_month(), CalView::Agenda, CalView::Invitations][i];
713 // The buttons stay mounted across views, so a keyboard user keeps focus.
714 let toolbar = view! {
715 <div class="cal-toolbar">
716 {move || is_month.get().then(|| view! {
717 <div class="cal-nav">
718 <button
719 class="icon-btn icon-btn-sm"
720 title=i18n::t(k::PIM_PREV_MONTH)
721 aria-label=i18n::t(k::PIM_PREV_MONTH)
722 on:click=move |_| step_month(-1)
723 >
724 {icon_svg(IconName::ChevronRight, "ic-btn flip")}
725 </button>
726 <button
727 class="btn btn-sm"
728 on:click=move |_| {
729 let (y, m, _) = civil_from_days(today());
730 go(CalView::Month(y, m));
731 today_clicks.update(|n| *n += 1);
732 }
733 >
734 {i18n::t(k::PIM_TODAY)}
735 </button>
736 <button
737 class="icon-btn icon-btn-sm"
738 title=i18n::t(k::PIM_NEXT_MONTH)
739 aria-label=i18n::t(k::PIM_NEXT_MONTH)
740 on:click=move |_| step_month(1)
741 >
742 {icon_svg(IconName::ChevronRight, "ic-btn")}
743 </button>
744 </div>
745 })}
746 <h2 class="cal-title">{title}</h2>
747 <div class="cal-views" role="tablist" on:keydown=move |ev| {
748 if ev.alt_key() || ev.ctrl_key() || ev.meta_key() || ev.shift_key() {
749 return;
750 }
751 let at = tab_of(view.get_untracked());
752 let to = match ev.key().as_str() {
753 "ArrowRight" => (at + 1) % 3,
754 "ArrowLeft" => (at + 2) % 3,
755 "Home" => 0,
756 "End" => 2,
757 _ => return,
758 };
759 ev.prevent_default();
760 // Moving between tabs with keys adds no history entries.
761 router::replace(&location(tab_at(to)));
762 let tab = web_sys::window()
763 .and_then(|w| w.document())
764 .and_then(|d| d.get_element_by_id(TAB_IDS[to]))
765 .and_then(|e| e.dyn_into::<web_sys::HtmlElement>().ok());
766 if let Some(tab) = tab {
767 let _ = tab.focus();
768 }
769 }>
770 {(0..3).map(|i| view! {
771 <button
772 role="tab"
773 id=TAB_IDS[i]
774 aria-controls="cal-panel"
775 tabindex=move || if selected(i) { "0" } else { "-1" }
776 class="cal-view-btn"
777 class:active=move || selected(i)
778 aria-selected=move || selected(i).to_string()
779 on:click=move |_| go(tab_at(i))
780 >
781 {i18n::t([k::PIM_MONTH, k::PIM_AGENDA, k::PIM_INVITATIONS][i])}
782 {(i == 2).then_some(move || (pending() > 0).then(|| view! {
783 <span class="cal-badge">{pending()}</span>
784 }))}
785 </button>
786 }).collect_view()}
787 </div>
788 </div>
789 };
790
791 let body = move || match view.get() {
792 CalView::Month(y, m) => view! {
793 <MonthView
794 y=y
795 m=m
796 week_start=week_start.get()
797 data=month
798 on_retry=refresh
799 shown=shown
800 today_clicks=today_clicks
801 />
802 }
803 .into_any(),
804 CalView::Agenda => view! {
805 <AgendaView data=agenda on_retry=refresh shown=shown/>
806 }
807 .into_any(),
808 CalView::Invitations => view! {
809 <InvitationsView data=invitations collections=collections on_replied=refresh/>
810 }
811 .into_any(),
812 };
813
814 view! {
815 <div class="cal">
816 {toolbar}
817 <div
818 id="cal-panel"
819 role="tabpanel"
820 aria-labelledby=move || TAB_IDS[tab_of(view.get())]
821 >
822 {body}
823 </div>
824 </div>
825 {move || opened.get().map(|o| view! {
826 <EventDialog
827 target=o
828 collections=collections
829 on_replied=refresh
830 on_close=Callback::new(move |_| router::close_open())
831 />
832 })}
833 }
834}
835
836fn truncated_note(list: &api::PimInstances) -> Option<impl IntoView + use<>> {
837 list.truncated.then(|| {
838 view! { <p class="cal-truncated">{i18n::t(k::PIM_TRUNCATED)}</p> }
839 })
840}
841
842fn loading_or_error(
843 data: &Option<Result<api::PimInstances, String>>,
844 retry: Callback<()>,
845) -> Result<api::PimInstances, AnyView> {
846 match data {
847 None => Err(view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any()),
848 Some(Err(e)) => Err(view! {
849 <div class="card error-card">
850 <span>{e.clone()}</span>
851 <button class="btn" on:click=move |_| retry.run(())>{i18n::t(k::RETRY)}</button>
852 </div>
853 }
854 .into_any()),
855 Some(Ok(list)) => Ok(list.clone()),
856 }
857}
858
859/// One line of a day list: time, color and title.
860fn day_row(s: &Shown, day: i64) -> impl IntoView + use<> {
861 let o = Opened::of(&s.inst);
862 let when = fmt_when(when_on(&s.span, day), day);
863 let title = s
864 .inst
865 .summary
866 .clone()
867 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
868 let cancelled = struck(&s.inst);
869 let location = s.inst.location.clone();
870 view! {
871 <button class="cal-row" class:cal-cancelled=cancelled on:click=move |_| o.open()>
872 <span class="cal-row-time">{when}</span>
873 <span class="cal-dot" style=format!("--c: {}", s.color)></span>
874 <span class="cal-row-main">
875 <span class="cal-row-title">{title}</span>
876 {location.map(|l| view! { <span class="cal-row-meta">{l}</span> })}
877 </span>
878 </button>
879 }
880}
881
882#[component]
883fn MonthView(
884 y: i32,
885 m: u32,
886 week_start: u32,
887 data: RwSignal<Option<Result<api::PimInstances, String>>>,
888 on_retry: Callback<()>,
889 shown: impl Fn(&api::PimInstances) -> Vec<Shown> + Copy + Send + Sync + 'static,
890 today_clicks: RwSignal<u32>,
891) -> impl IntoView {
892 let start = grid_start(y, m, week_start);
893 let now = today();
894 let in_month = move |d: i64| {
895 let (yy, mm, _) = civil_from_days(d);
896 yy == y && mm == m
897 };
898 let selected = RwSignal::new(if in_month(now) {
899 now
900 } else {
901 days_from_civil(y, m, 1)
902 });
903 Effect::new(move |seen: Option<()>| {
904 today_clicks.track();
905 if seen.is_some() && in_month(today()) {
906 selected.set(today());
907 }
908 });
909 let list_ref: NodeRef<leptos::html::Div> = NodeRef::new();
910 let pick = move |day: i64| {
911 selected.set(day);
912 if let Some(el) = list_ref.get_untracked() {
913 let opts = web_sys::ScrollIntoViewOptions::new();
914 opts.set_block(web_sys::ScrollLogicalPosition::Nearest);
915 el.scroll_into_view_with_scroll_into_view_options(&opts);
916 }
917 };
918 let head = (0..7)
919 .map(|i| {
920 view! {
921 <div class="cal-head-day">{intl(&day_date(start + i), &[("weekday", "short")])}</div>
922 }
923 })
924 .collect::<Vec<_>>();
925 view! {
926 <div class="cal-month">
927 <div class="cal-head">{head}</div>
928 {move || data.with(|d| match loading_or_error(d, on_retry) {
929 Err(v) => v,
930 Ok(list) => {
931 let items = shown(&list);
932 let spans: Vec<Span> = items.iter().map(|s| s.span).collect();
933 let weeks = (0..6)
934 .map(|w| {
935 let week = start + w * 7;
936 let layout = layout_week(&spans, week, LINES);
937 let cells = (0..7usize)
938 .map(|c| {
939 let day = week + c as i64;
940 let (_, _, dnum) = civil_from_days(day);
941 let on_day = items.iter().filter(|s| s.span.covers(day));
942 let n = on_day.clone().count();
943 let dots: Vec<String> =
944 on_day.take(3).map(|s| s.color.clone()).collect();
945 let label = match n {
946 0 => fmt_day_long(day),
947 1 => format!("{}, {}", fmt_day_long(day), i18n::t(k::PIM_EVENTS_ONE)),
948 n => format!(
949 "{}, {}",
950 fmt_day_long(day),
951 i18n::t_fmt(k::PIM_EVENTS_N, &n.to_string())
952 ),
953 };
954 view! {
955 <button
956 class="cal-cell"
957 class:cal-out=!in_month(day)
958 class:cal-today=day == now
959 class:cal-sel=move || selected.get() == day
960 style=format!("grid-column: {}", c + 1)
961 aria-label=label
962 on:click=move |_| pick(day)
963 >
964 <span class="cal-num">{dnum}</span>
965 <span class="cal-dots">
966 {dots
967 .into_iter()
968 .map(|c| view! { <span class="cal-dot" style=format!("--c: {c}")></span> })
969 .collect::<Vec<_>>()}
970 </span>
971 </button>
972 }
973 })
974 .collect::<Vec<_>>();
975 let pieces = layout
976 .pieces
977 .iter()
978 .map(|p| {
979 let s = &items[p.item];
980 let o = Opened::of(&s.inst);
981 let bar = s.span.is_bar();
982 let title = s
983 .inst
984 .summary
985 .clone()
986 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
987 let time = (!bar).then(|| fmt_min(s.span.first, s.span.start_min));
988 let cancelled = struck(&s.inst);
989 let tip = match &time {
990 Some(t) => format!("{t} {title}"),
991 None => title.clone(),
992 };
993 view! {
994 <button
995 class="cal-item"
996 class:cal-bar=bar
997 class:cal-chip=!bar
998 class:cal-cont-l=!p.starts
999 class:cal-cont-r=!p.ends
1000 class:cal-cancelled=cancelled
1001 style=format!(
1002 "grid-column: {} / span {}; grid-row: {}; --c: {}",
1003 p.col + 1,
1004 p.len,
1005 p.line + 2,
1006 s.color
1007 )
1008 title=tip
1009 on:click=move |_| o.open()
1010 >
1011 {(!bar).then(|| view! { <span class="cal-dot"></span> })}
1012 {time.map(|t| view! { <span class="cal-time">{t}</span> })}
1013 <span class="cal-item-title">{title}</span>
1014 </button>
1015 }
1016 })
1017 .collect::<Vec<_>>();
1018 let more = layout
1019 .more
1020 .iter()
1021 .enumerate()
1022 .filter(|&(_, &n)| n > 0)
1023 .map(|(c, &n)| {
1024 let day = week + c as i64;
1025 view! {
1026 <button
1027 class="cal-more"
1028 style=format!("grid-column: {}; grid-row: {}", c + 1, LINES + 1)
1029 on:click=move |_| pick(day)
1030 >
1031 {i18n::t_fmt(k::PIM_MORE_N, &n.to_string())}
1032 </button>
1033 }
1034 })
1035 .collect::<Vec<_>>();
1036 view! {
1037 <div class="cal-week" style=format!("--lines: {LINES}")>
1038 {cells}
1039 {pieces}
1040 {more}
1041 </div>
1042 }
1043 })
1044 .collect::<Vec<_>>();
1045 let day_list = move || {
1046 let day = selected.get();
1047 let rows: Vec<_> = items
1048 .iter()
1049 .filter(|s| s.span.covers(day))
1050 .map(|s| day_row(s, day))
1051 .collect();
1052 view! {
1053 <h3 class="cal-day-title">{fmt_day_long(day)}</h3>
1054 {if rows.is_empty() {
1055 view! { <p class="muted cal-pad">{i18n::t(k::PIM_NO_EVENTS_DAY)}</p> }.into_any()
1056 } else {
1057 view! { <div class="cal-rows">{rows}</div> }.into_any()
1058 }}
1059 }
1060 };
1061 view! {
1062 {truncated_note(&list)}
1063 <div class="cal-weeks">{weeks}</div>
1064 <div class="cal-day" node_ref=list_ref>{day_list}</div>
1065 }
1066 .into_any()
1067 }
1068 })}
1069 </div>
1070 }
1071}
1072
1073/// The agenda shows today and the days after it. The month view is for
1074/// browsing further.
1075const AGENDA_DAYS: i64 = 7;
1076
1077#[component]
1078fn AgendaView(
1079 data: RwSignal<Option<Result<api::PimInstances, String>>>,
1080 on_retry: Callback<()>,
1081 shown: impl Fn(&api::PimInstances) -> Vec<Shown> + Copy + Send + Sync + 'static,
1082) -> impl IntoView {
1083 view! {
1084 <div class="cal-agenda">
1085 {move || data.with(|d| match loading_or_error(d, on_retry) {
1086 Err(v) => v,
1087 Ok(list) => {
1088 let items = shown(&list);
1089 let from = today();
1090 let groups: Vec<_> = (from..from + AGENDA_DAYS)
1091 .filter_map(|day| {
1092 let rows: Vec<_> = items
1093 .iter()
1094 .filter(|s| s.span.covers(day))
1095 .map(|s| day_row(s, day))
1096 .collect();
1097 (!rows.is_empty()).then(|| view! {
1098 <section class="cal-agenda-day">
1099 <h3 class="cal-day-title" class:cal-day-today=day == from>
1100 {fmt_day_long(day)}
1101 </h3>
1102 <div class="cal-rows">{rows}</div>
1103 </section>
1104 })
1105 })
1106 .collect();
1107 let empty = groups.is_empty().then(|| view! {
1108 <div class="empty-state">
1109 {icon_svg(IconName::Calendar, "empty-glyph")}
1110 <p class="muted">{i18n::t(k::PIM_NO_EVENTS_AGENDA)}</p>
1111 </div>
1112 });
1113 view! {
1114 {truncated_note(&list)}
1115 {empty}
1116 {groups}
1117 }
1118 .into_any()
1119 }
1120 })}
1121 </div>
1122 }
1123}
1124
1125/// Answer an invitation, then refresh the lists, also after a failure: the
1126/// invitation may have changed elsewhere. `busy` stays set on success; `done`
1127/// ends it once the refresh has landed.
1128fn reply(
1129 toast: ToastMsg,
1130 busy: RwSignal<bool>,
1131 collection_id: i64,
1132 name: String,
1133 recurrence_id: Option<String>,
1134 partstat: &'static str,
1135 done: Callback<()>,
1136) {
1137 busy.set(true);
1138 spawn_local(async move {
1139 let body = PimReply {
1140 collection_id,
1141 name,
1142 recurrence_id,
1143 partstat: partstat.to_string(),
1144 tz: Some(browser_tz()),
1145 };
1146 match api::pim_reply(body).await {
1147 Ok(_) => {
1148 show(toast, i18n::t(k::PIM_REPLIED));
1149 // The dialog or view may be gone by now.
1150 let _ = done.try_run(());
1151 }
1152 Err(e) => {
1153 let _ = busy.try_set(false);
1154 show_error(toast, e.to_string());
1155 let _ = done.try_run(());
1156 }
1157 }
1158 });
1159}
1160
1161/// Accept, maybe, decline. `current` marks the answer already given.
1162fn reply_buttons(
1163 current: Option<String>,
1164 busy: RwSignal<bool>,
1165 on: impl Fn(&'static str) + Clone + 'static,
1166) -> impl IntoView {
1167 [
1168 ("ACCEPTED", k::PIM_ACCEPT),
1169 ("TENTATIVE", k::PIM_TENTATIVE),
1170 ("DECLINED", k::PIM_DECLINE),
1171 ]
1172 .map(|(ps, label)| {
1173 let on = on.clone();
1174 let active = current.as_deref() == Some(ps);
1175 view! {
1176 <button
1177 class="btn btn-sm"
1178 class:btn-primary=active
1179 aria-pressed=active.to_string()
1180 disabled=move || busy.get()
1181 on:click=move |_| on(ps)
1182 >
1183 {i18n::t(label)}
1184 </button>
1185 }
1186 })
1187 .into_iter()
1188 .collect::<Vec<_>>()
1189}
1190
1191#[component]
1192fn InvitationsView(
1193 data: RwSignal<Option<Result<Vec<PimInvitation>, String>>>,
1194 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
1195 on_replied: Callback<()>,
1196) -> impl IntoView {
1197 let toast = use_context::<ToastMsg>().expect("toast context");
1198 view! {
1199 <div class="cal-invitations">
1200 {move || match data.get() {
1201 None => view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any(),
1202 Some(Err(e)) => view! {
1203 <div class="card error-card">
1204 <span>{e}</span>
1205 <button class="btn" on:click=move |_| on_replied.run(())>{i18n::t(k::RETRY)}</button>
1206 </div>
1207 }
1208 .into_any(),
1209 Some(Ok(list)) if list.is_empty() => view! {
1210 <div class="empty-state">
1211 {icon_svg(IconName::Calendar, "empty-glyph")}
1212 <p class="muted">{i18n::t(k::PIM_NO_INVITATIONS)}</p>
1213 </div>
1214 }
1215 .into_any(),
1216 Some(Ok(list)) => {
1217 let names: HashMap<i64, String> = collections.with(|c| {
1218 c.iter().flatten().map(|c| (c.id, display_name(c))).collect()
1219 });
1220 list.into_iter()
1221 .map(|inv| {
1222 // A series opens at its next instance, the one listed.
1223 let o = Opened {
1224 collection_id: inv.collection_id,
1225 recurrence_id: inv
1226 .recurrence_id
1227 .clone()
1228 .or_else(|| inv.recurring.then(|| inv.start.clone())),
1229 name: inv.name.clone(),
1230 };
1231 let span = span_of(&inv_instance(&inv));
1232 let series = inv.recurring && inv.recurrence_id.is_none();
1233 let mut meta = vec![fmt_span(&span)];
1234 match (&inv.rrule, &inv.recurrence_id) {
1235 (Some(r), None) => meta.push(rrule_text(r, Some(span.first))),
1236 (None, Some(_)) => meta.push(i18n::t(k::PIM_THIS_EVENT).to_string()),
1237 _ => {}
1238 }
1239 if let Some(n) = names.get(&inv.collection_id) {
1240 meta.push(n.clone());
1241 }
1242 let organizer = inv.organizer.as_ref().map(|p| {
1243 p.name.clone().unwrap_or_else(|| {
1244 p.address.trim_start_matches("mailto:").to_string()
1245 })
1246 });
1247 let title = inv
1248 .summary
1249 .clone()
1250 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
1251 let (id, name, rid) =
1252 (inv.collection_id, inv.name.clone(), inv.recurrence_id.clone());
1253 let open = o.clone();
1254 let busy = RwSignal::new(false);
1255 view! {
1256 <div class="cal-inv">
1257 <button class="cal-inv-main" on:click=move |_| open.open()>
1258 <span class="cal-inv-title">{title}</span>
1259 <span class="cal-row-meta">{meta.join(" · ")}</span>
1260 {inv.location.clone().map(|l| view! { <span class="cal-row-meta">{l}</span> })}
1261 {organizer.map(|n| view! {
1262 <span class="cal-row-meta">{i18n::t_fmt(k::PIM_FROM_ORGANIZER, &n)}</span>
1263 })}
1264 {series.then(|| view! {
1265 <span class="cal-row-meta">{i18n::t(k::PIM_INV_SERIES_HINT)}</span>
1266 })}
1267 </button>
1268 <div class="cal-inv-actions">
1269 {reply_buttons(None, busy, move |ps| {
1270 reply(toast, busy, id, name.clone(), rid.clone(), ps, on_replied)
1271 })}
1272 </div>
1273 </div>
1274 }
1275 })
1276 .collect::<Vec<_>>()
1277 .into_any()
1278 }
1279 }}
1280 </div>
1281 }
1282}
1283
1284fn partstat_label(ps: Option<&str>) -> (&'static str, &'static str) {
1285 match ps {
1286 Some("ACCEPTED") => (k::PIM_PS_ACCEPTED, "ps-accepted"),
1287 Some("DECLINED") => (k::PIM_PS_DECLINED, "ps-declined"),
1288 Some("TENTATIVE") => (k::PIM_PS_TENTATIVE, "ps-tentative"),
1289 Some("DELEGATED") => (k::PIM_PS_DELEGATED, "ps-muted"),
1290 _ => (k::PIM_PS_NEEDS_ACTION, "ps-muted"),
1291 }
1292}
1293
1294/// `FREQ=WEEKLY;INTERVAL=2;BYDAY=TU` as words; a rule it cannot put into
1295/// words stays raw.
1296/// `rule` in words, with the weekday of `first` when it names none, or
1297/// else `rule` itself.
1298fn rrule_text(rule: &str, first: Option<i64>) -> String {
1299 let full = first.map_or_else(|| rule.to_string(), |f| with_start_day(rule, f));
1300 rrule_words(&full, weekday_name, month_name, until_date).unwrap_or_else(|| rule.to_string())
1301}
1302
1303fn rrule_words(
1304 rule: &str,
1305 day: fn(&str) -> Option<String>,
1306 month: fn(u32) -> Option<String>,
1307 date: fn(&str) -> Option<String>,
1308) -> Option<String> {
1309 let part = |key: &str| {
1310 rule.split(';')
1311 .find_map(|p| p.strip_prefix(key)?.strip_prefix('='))
1312 };
1313 let list = |key: &str| part(key).into_iter().flat_map(|v| v.split(','));
1314 let n = match part("INTERVAL") {
1315 Some(n) => n.parse::<u32>().ok().filter(|&n| n > 0)?,
1316 None => 1,
1317 };
1318 let freq = part("FREQ");
1319 let keys = match freq {
1320 Some("DAILY") => (k::PIM_RRULE_DAILY, k::PIM_RRULE_DAILY_N),
1321 Some("WEEKLY") => (k::PIM_RRULE_WEEKLY, k::PIM_RRULE_WEEKLY_N),
1322 Some("MONTHLY") => (k::PIM_RRULE_MONTHLY, k::PIM_RRULE_MONTHLY_N),
1323 Some("YEARLY") => (k::PIM_RRULE_YEARLY, k::PIM_RRULE_YEARLY_N),
1324 _ => return None,
1325 };
1326 let mut text = match n {
1327 1 => i18n::t(keys.0).to_string(),
1328 n => i18n::t_fmt(keys.1, &n.to_string()),
1329 };
1330 let numbered = matches!(freq, Some("MONTHLY" | "YEARLY"));
1331 let worded = |key: &str| match key {
1332 "FREQ" | "INTERVAL" | "UNTIL" | "COUNT" | "WKST" | "BYDAY" => true,
1333 "BYMONTH" => freq == Some("YEARLY"),
1334 "BYMONTHDAY" => numbered,
1335 _ => false,
1336 };
1337 let all_worded = rule
1338 .split(';')
1339 .all(|p| p.is_empty() || p.split_once('=').is_some_and(|(key, _)| worded(key)));
1340 // Without BYMONTH, a yearly BYDAY or BYMONTHDAY counts through the whole year.
1341 let yearwide = freq == Some("YEARLY")
1342 && part("BYMONTH").is_none()
1343 && (part("BYDAY").is_some() || part("BYMONTHDAY").is_some());
1344 // BYDAY with BYMONTHDAY is an intersection; listing both reads as a union.
1345 let both = part("BYDAY").is_some() && part("BYMONTHDAY").is_some();
1346 if !all_worded || yearwide || both {
1347 return None;
1348 }
1349 let mut on = Vec::new();
1350 for m in list("BYMONTH") {
1351 on.push(month(m.parse().ok()?)?);
1352 }
1353 for d in list("BYDAY") {
1354 let split = d.len().checked_sub(2)?;
1355 let (nth, code) = d.split_at_checked(split)?;
1356 let name = day(code)?;
1357 on.push(match nth {
1358 // A plain weekday outside WEEKLY means every such day of the
1359 // period, which "Every month: Mon" does not say.
1360 "" if freq == Some("WEEKLY") => name,
1361 "" => return None,
1362 _ if !numbered => return None,
1363 nth => i18n::t_fmt2(k::PIM_RRULE_NTH, ordinal(nth)?, &name),
1364 });
1365 }
1366 for d in list("BYMONTHDAY") {
1367 on.push(match d {
1368 "-1" => i18n::t(k::PIM_RRULE_LAST_DAY).to_string(),
1369 d => i18n::t_fmt(k::PIM_RRULE_MONTH_DAY, &d.parse::<u8>().ok()?.to_string()),
1370 });
1371 }
1372 if !on.is_empty() {
1373 text = format!("{text}: {}", on.join(", "));
1374 }
1375 if let Some(u) = part("UNTIL") {
1376 text = format!("{text}; {}", i18n::t_fmt(k::PIM_RRULE_UNTIL, &date(u)?));
1377 } else if let Some(c) = part("COUNT") {
1378 text = format!(
1379 "{text}; {}",
1380 i18n::t_fmt(k::PIM_RRULE_COUNT, &c.parse::<u32>().ok()?.to_string())
1381 );
1382 }
1383 Some(text)
1384}
1385
1386/// The ordinal of `2TU` or `-1FR`. Others are rare enough to stay raw.
1387fn ordinal(nth: &str) -> Option<&'static str> {
1388 Some(i18n::t(match nth {
1389 "1" | "+1" => k::PIM_RRULE_ORD_1,
1390 "2" | "+2" => k::PIM_RRULE_ORD_2,
1391 "3" | "+3" => k::PIM_RRULE_ORD_3,
1392 "4" | "+4" => k::PIM_RRULE_ORD_4,
1393 "5" | "+5" => k::PIM_RRULE_ORD_5,
1394 "-1" => k::PIM_RRULE_ORD_LAST,
1395 _ => return None,
1396 }))
1397}
1398
1399fn month_name(m: u32) -> Option<String> {
1400 let m = (1..=12).contains(&m).then_some(m)?;
1401 let date = js_sys::Date::new_with_year_month_day(2024, m as i32 - 1, 1);
1402 Some(intl(&date, &[("month", "long")]))
1403}
1404
1405/// UNTIL (`20261231` or `20261231T225959Z`) as a local date.
1406fn until_date(u: &str) -> Option<String> {
1407 let num = |r: std::ops::Range<usize>| u.get(r)?.parse::<u32>().ok();
1408 let (y, m, d) = (num(0..4)?, num(4..6)?, num(6..8)?);
1409 let date = match u.get(8..)? {
1410 t if t.len() == 8 && t.is_ascii() && t.ends_with('Z') => {
1411 let iso = format!(
1412 "{y:04}-{m:02}-{d:02}T{}:{}:{}Z",
1413 &t[1..3],
1414 &t[3..5],
1415 &t[5..7]
1416 );
1417 js_sys::Date::new(&iso.into())
1418 }
1419 // A DATE, or floating: the wall-clock date.
1420 _ => js_sys::Date::new_with_year_month_day(y, m as i32 - 1, d as i32),
1421 };
1422 (!date.get_time().is_nan()).then(|| intl(&date, &[("dateStyle", "medium")]))
1423}
1424
1425/// A weekly rule without BYDAY repeats on its start's weekday. Naming it
1426/// makes "Every week" read "Every week: Tue".
1427fn with_start_day(rule: &str, first: i64) -> String {
1428 let weekly = rule.split(';').any(|p| p == "FREQ=WEEKLY");
1429 if !weekly || rule.split(';').any(|p| p.starts_with("BYDAY=")) {
1430 return rule.to_string();
1431 }
1432 let code = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"][weekday(first) as usize];
1433 format!("{rule};BYDAY={code}")
1434}
1435
1436/// `TU` as the locale's short weekday name.
1437fn weekday_name(code: &str) -> Option<String> {
1438 let offset = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]
1439 .iter()
1440 .position(|&d| d == code)?;
1441 // 2024-01-01 was a Monday.
1442 let date = js_sys::Date::new_with_year_month_day(2024, 0, 1 + offset as i32);
1443 Some(intl(&date, &[("weekday", "short")]))
1444}
1445
1446fn person_name(p: &api_types::PimPerson) -> String {
1447 p.name
1448 .clone()
1449 .unwrap_or_else(|| p.address.trim_start_matches("mailto:").to_string())
1450}
1451
1452/// Text with its web links clickable, for a `white-space: pre-wrap` block.
1453pub fn linkified(text: &str) -> impl IntoView + use<> {
1454 split_links(text)
1455 .into_iter()
1456 .map(|(t, link)| match link {
1457 true => {
1458 let href = t.clone();
1459 view! { <a href=href target="_blank" rel="noopener noreferrer">{t}</a> }.into_any()
1460 }
1461 false => t.into_any(),
1462 })
1463 .collect::<Vec<_>>()
1464}
1465
1466#[component]
1467fn EventDialog(
1468 target: Opened,
1469 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
1470 on_replied: Callback<()>,
1471 on_close: Callback<()>,
1472) -> impl IntoView {
1473 let toast = use_context::<ToastMsg>().expect("toast context");
1474 let detail = RwSignal::new(Option::<Result<PimEventDetail, String>>::None);
1475 let busy = RwSignal::new(false);
1476 let load_seq = StoredValue::new(0u32);
1477 // For one instance of a series: answer it alone (`true`), or the whole
1478 // series. Set on the first load, so a reply does not flip it.
1479 let chosen = RwSignal::new(None::<bool>);
1480 let load = {
1481 let t = target.clone();
1482 move || {
1483 let t = t.clone();
1484 // Also runs after an await, when the view may be gone.
1485 let Some(seq) = load_seq.try_get_value().map(|s| s + 1) else {
1486 return;
1487 };
1488 load_seq.set_value(seq);
1489 spawn_local(async move {
1490 let r = api::pim_object(
1491 t.collection_id,
1492 &t.name,
1493 t.recurrence_id.as_deref(),
1494 &browser_tz(),
1495 )
1496 .await;
1497 let r = match r {
1498 Ok(PimObjectDetail::Event(e)) => Ok(e),
1499 Ok(PimObjectDetail::Contact(_)) => Err(i18n::t(k::PIM_NOT_EVENT).to_string()),
1500 Err(e) => Err(e.to_string()),
1501 };
1502 if load_seq.try_get_value() == Some(seq) {
1503 // A reload after a reply keeps the event shown.
1504 match r {
1505 Err(e) if matches!(detail.try_get_untracked(), Some(Some(Ok(_)))) => {
1506 show_error(toast, e)
1507 }
1508 r => {
1509 // An unanswered series came as one invitation for all of it.
1510 if let (Ok(e), Some(None)) = (&r, chosen.try_get_untracked()) {
1511 let whole = e.series_partstat.as_deref() == Some("NEEDS-ACTION");
1512 let _ = chosen.try_set(Some(!whole));
1513 }
1514 let _ = detail.try_set(Some(r));
1515 }
1516 }
1517 let _ = busy.try_set(false);
1518 }
1519 });
1520 }
1521 };
1522 load();
1523 let collection_id = target.collection_id;
1524 let collection = Memo::new(move |_| {
1525 collections.with(|c| {
1526 c.iter()
1527 .flatten()
1528 .find(|c| c.id == collection_id)
1529 .map(|c| (display_name(c), safe_color(c.color.as_deref())))
1530 })
1531 });
1532 // Every state carries the element that names the dialog.
1533 let body = move || match detail.get() {
1534 None => {
1535 view! { <p id="cal-detail-title" class="muted">{i18n::t(k::LOADING)}</p> }.into_any()
1536 }
1537 Some(Err(e)) => view! { <p id="cal-detail-title" class="form-error">{e}</p> }.into_any(),
1538 Some(Ok(d)) => {
1539 let title = d
1540 .summary
1541 .clone()
1542 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
1543 let mine = d
1544 .attendees
1545 .iter()
1546 .find(|a| a.is_owner)
1547 .and_then(|a| a.partstat.clone());
1548 let series = target.recurrence_id.is_some() && d.rrule.is_some();
1549 let only_this = move || chosen.get().unwrap_or(true);
1550 let rid = target.recurrence_id.clone();
1551 let (id, name) = (target.collection_id, target.name.clone());
1552 let load = load.clone();
1553 let answer = move |ps: &'static str| {
1554 // Without the choice, the instance alone.
1555 let rid = if !series || chosen.get_untracked().unwrap_or(true) {
1556 rid.clone()
1557 } else {
1558 None
1559 };
1560 let load = load.clone();
1561 reply(
1562 toast,
1563 busy,
1564 id,
1565 name.clone(),
1566 rid,
1567 ps,
1568 Callback::new(move |_| {
1569 load();
1570 let _ = on_replied.try_run(());
1571 }),
1572 );
1573 };
1574 let url = d
1575 .url
1576 .clone()
1577 .filter(|u| u.starts_with("https://") || u.starts_with("http://"));
1578 view! {
1579 <h2 id="cal-detail-title" class="modal-title cal-detail-title" class:cal-cancelled=d.status.as_deref() == Some("CANCELLED")>
1580 {title}
1581 </h2>
1582 {(d.status.as_deref() == Some("CANCELLED")).then(|| view! {
1583 <p class="cal-flag">{i18n::t(k::PIM_CANCELLED)}</p>
1584 })}
1585 <dl class="cal-facts">
1586 {d.start.as_deref().zip(d.end.as_deref()).map(|(s, e)| view! {
1587 <dt>{i18n::t(k::PIM_WHEN)}</dt>
1588 <dd>{fmt_span(&span_at(s, e, d.all_day))}</dd>
1589 })}
1590 {d.rrule.clone().map(|r| {
1591 let text = match d.start.as_deref().zip(d.end.as_deref()) {
1592 Some((s, e)) => rrule_text(&r, Some(span_at(s, e, d.all_day).first)),
1593 None => rrule_text(&r, None),
1594 };
1595 view! {
1596 <dt>{i18n::t(k::PIM_REPEATS)}</dt>
1597 <dd title=r.clone()>{text}</dd>
1598 }
1599 })}
1600 {d.location.clone().map(|l| view! {
1601 <dt>{i18n::t(k::PIM_LOCATION)}</dt>
1602 <dd class="cal-pre">{linkified(&l)}</dd>
1603 })}
1604 {collection.get().map(|(n, c)| view! {
1605 <dt>{i18n::t(k::PIM_CALENDAR)}</dt>
1606 <dd><span class="cal-dot" style=format!("--c: {c}")></span>" "{n}</dd>
1607 })}
1608 {d.organizer.as_ref().map(|p| view! {
1609 <dt>{i18n::t(k::PIM_ORGANIZER)}</dt>
1610 <dd>{person_name(p)}</dd>
1611 })}
1612 {url.map(|u| {
1613 let href = u.clone();
1614 view! {
1615 <dt>{i18n::t(k::PIM_LINK)}</dt>
1616 <dd><a href=href target="_blank" rel="noopener noreferrer">{u}</a></dd>
1617 }
1618 })}
1619 {(!d.categories.is_empty()).then(|| view! {
1620 <dt>{i18n::t(k::PIM_CATEGORIES)}</dt>
1621 <dd>{d.categories.join(", ")}</dd>
1622 })}
1623 </dl>
1624 {(!d.attendees.is_empty()).then(|| view! {
1625 <h3 class="pim-section-title">{i18n::t(k::PIM_ATTENDEES)}</h3>
1626 <ul class="cal-attendees">
1627 {d.attendees
1628 .iter()
1629 .map(|a| {
1630 let (label, class) = partstat_label(a.partstat.as_deref());
1631 let optional = a.role.as_deref() == Some("OPT-PARTICIPANT");
1632 view! {
1633 <li>
1634 <span class="cal-att-name" title=a.person.address.clone()>
1635 {person_name(&a.person)}
1636 </span>
1637 {optional.then(|| view! { <span class="muted">{i18n::t(k::PIM_OPTIONAL)}</span> })}
1638 <span class=format!("ps-badge {class}")>{i18n::t(label)}</span>
1639 </li>
1640 }
1641 })
1642 .collect::<Vec<_>>()}
1643 </ul>
1644 })}
1645 {d.description.clone().filter(|t| !t.trim().is_empty()).map(|t| view! {
1646 <div class="cal-desc cal-pre">{linkified(&t)}</div>
1647 })}
1648 {d.can_reply.then(|| view! {
1649 <section class="cal-reply">
1650 <h3 class="pim-section-title">{i18n::t(k::PIM_YOUR_ANSWER)}</h3>
1651 {series.then(|| view! {
1652 <div class="cal-scope" role="radiogroup">
1653 <label class="check-row">
1654 <input
1655 type="radio"
1656 name="cal-scope"
1657 prop:checked=only_this
1658 on:change=move |_| chosen.set(Some(true))
1659 />
1660 {i18n::t(k::PIM_THIS_EVENT)}
1661 </label>
1662 <label class="check-row">
1663 <input
1664 type="radio"
1665 name="cal-scope"
1666 prop:checked=move || !only_this()
1667 on:change=move |_| chosen.set(Some(false))
1668 />
1669 {i18n::t(k::PIM_ALL_EVENTS)}
1670 </label>
1671 </div>
1672 })}
1673 <div class="cal-inv-actions">{reply_buttons(mine, busy, answer)}</div>
1674 </section>
1675 })}
1676 }
1677 .into_any()
1678 }
1679 };
1680 view! {
1681 <Modal class="pim-modal cal-detail" labelled_by="cal-detail-title" on_close=on_close>
1682 {body}
1683 <div class="modal-actions">
1684 <button class="btn" on:click=move |_| on_close.run(())>{i18n::t(k::CLOSE)}</button>
1685 </div>
1686 </Modal>
1687 }
1688}
1689
1690#[cfg(test)]
1691mod tests {
1692 use super::*;
1693
1694 #[test]
1695 fn url_years_are_clamped() {
1696 assert_eq!(parse_month("2026-10"), Some((2026, 10)));
1697 assert_eq!(parse_month("9999-12"), Some((9999, 12)));
1698 for bad in ["0050-01", "-3-01", "10000-01", "2026-13", "x-01"] {
1699 assert_eq!(parse_month(bad), None, "{bad}");
1700 }
1701 }
1702
1703 fn day(y: i32, m: u32, d: u32) -> i64 {
1704 days_from_civil(y, m, d)
1705 }
1706
1707 fn timed(first: i64, start_min: u32) -> Span {
1708 Span {
1709 first,
1710 last: first,
1711 all_day: false,
1712 start_min,
1713 end_min: start_min + 60,
1714 }
1715 }
1716
1717 fn all_day(first: i64, last: i64) -> Span {
1718 Span {
1719 first,
1720 last,
1721 all_day: true,
1722 start_min: 0,
1723 end_min: 1440,
1724 }
1725 }
1726
1727 #[test]
1728 fn civil_days_round_trip() {
1729 assert_eq!(day(1970, 1, 1), 0);
1730 assert_eq!(day(2000, 3, 1), 11017);
1731 for z in [-800_000, -1, 0, 59, 60, 11016, 20_000, 2_000_000] {
1732 let (y, m, d) = civil_from_days(z);
1733 assert_eq!(day(y, m, d), z);
1734 }
1735 assert_eq!(civil_from_days(day(2024, 2, 29)), (2024, 2, 29));
1736 // 2026-10-01 is a Thursday.
1737 assert_eq!(weekday(day(2026, 10, 1)), 4);
1738 }
1739
1740 #[test]
1741 fn grid_starts_on_the_week_start() {
1742 // October 2026 starts on a Thursday.
1743 let sunday = grid_start(2026, 10, 0);
1744 let monday = grid_start(2026, 10, 1);
1745 assert_eq!(civil_from_days(sunday), (2026, 9, 27));
1746 assert_eq!(civil_from_days(monday), (2026, 9, 28));
1747 assert_eq!(weekday(monday), 1);
1748 assert_eq!(civil_from_days(grid_start(2026, 10, 6)), (2026, 9, 26));
1749 // A month starting on the week start begins the grid itself, and
1750 // six weeks always cover the whole month.
1751 assert_eq!(grid_start(2026, 6, 1), day(2026, 6, 1));
1752 for (y, m) in [(2026, 2), (2026, 8), (2027, 1)] {
1753 for ws in [0, 1, 6] {
1754 let s = grid_start(y, m, ws);
1755 let (ny, nm) = add_months(y, m, 1);
1756 assert!(s <= day(y, m, 1) && day(ny, nm, 1) <= s + GRID_DAYS);
1757 }
1758 }
1759 assert_eq!(add_months(2026, 12, 1), (2027, 1));
1760 assert_eq!(add_months(2026, 1, -1), (2025, 12));
1761 }
1762
1763 #[test]
1764 fn bars_split_across_weeks() {
1765 // Saturday to Tuesday, in weeks starting on Monday.
1766 let week1 = grid_start(2026, 10, 1);
1767 let span = all_day(day(2026, 10, 3), day(2026, 10, 6));
1768 let a = layout_week(&[span], week1, 4);
1769 assert_eq!(
1770 a.pieces,
1771 [Piece {
1772 item: 0,
1773 col: 5,
1774 len: 2,
1775 line: 0,
1776 starts: true,
1777 ends: false
1778 }]
1779 );
1780 let b = layout_week(&[span], week1 + 7, 4);
1781 assert_eq!(
1782 b.pieces,
1783 [Piece {
1784 item: 0,
1785 col: 0,
1786 len: 2,
1787 line: 0,
1788 starts: false,
1789 ends: true
1790 }]
1791 );
1792 assert_eq!(a.more, [0; 7]);
1793 }
1794
1795 #[test]
1796 fn busy_days_share_the_last_line_with_more() {
1797 let week = grid_start(2026, 10, 1);
1798 let mon = week;
1799 // Five timed events on Monday; a bar Monday to Wednesday.
1800 let mut spans: Vec<Span> = (0..5).map(|i| timed(mon, 600 + i * 30)).collect();
1801 spans.push(all_day(mon, mon + 2));
1802 let l = layout_week(&spans, week, 3);
1803 // Monday has six instances on three lines: two shown, four behind
1804 // "+4 more". The bar comes first, so it stays visible.
1805 assert_eq!(l.more, [4, 0, 0, 0, 0, 0, 0]);
1806 let bar = l.pieces.iter().find(|p| p.item == 5).unwrap();
1807 assert_eq!((bar.col, bar.len, bar.line), (0, 3, 0));
1808 assert_eq!(l.pieces.iter().filter(|p| p.col == 0).count(), 2);
1809 // Timed events keep their order.
1810 let first_chip = l.pieces.iter().find(|p| p.item != 5).unwrap();
1811 assert_eq!(first_chip.item, 0);
1812 }
1813
1814 #[test]
1815 fn a_weekly_rule_names_its_start_day() {
1816 let friday = days_from_civil(2026, 10, 2);
1817 assert_eq!(
1818 with_start_day("FREQ=WEEKLY", friday),
1819 "FREQ=WEEKLY;BYDAY=FR"
1820 );
1821 assert_eq!(
1822 with_start_day("FREQ=WEEKLY;BYDAY=MO", friday),
1823 "FREQ=WEEKLY;BYDAY=MO"
1824 );
1825 assert_eq!(with_start_day("FREQ=DAILY", friday), "FREQ=DAILY");
1826 }
1827
1828 #[test]
1829 fn a_rule_reads_as_words() {
1830 let words = |r: &str| {
1831 rrule_words(
1832 r,
1833 |d| Some(d.to_string()),
1834 |m| Some(format!("M{m}")),
1835 |u| Some(u[..8].to_string()),
1836 )
1837 };
1838 assert_eq!(
1839 words("FREQ=WEEKLY;BYDAY=TU,TH").as_deref(),
1840 Some("Every week: TU, TH")
1841 );
1842 assert_eq!(
1843 words("FREQ=MONTHLY;BYDAY=2TU;COUNT=3").as_deref(),
1844 Some("Every month: 2nd TU; 3 times")
1845 );
1846 assert_eq!(
1847 words("FREQ=MONTHLY;INTERVAL=2;BYMONTHDAY=15,-1;UNTIL=20261231T225959Z").as_deref(),
1848 Some("Every 2 months: day 15, last day; until 20261231")
1849 );
1850 assert_eq!(
1851 words("FREQ=YEARLY;BYMONTH=5;BYDAY=-1SU").as_deref(),
1852 Some("Every year: M5, last SU")
1853 );
1854 assert_eq!(words("FREQ=MONTHLY;BYDAY=-2FR"), None);
1855 assert_eq!(words("FREQ=WEEKLY;BYDAY=2TU"), None);
1856 assert_eq!(words("FREQ=HOURLY"), None);
1857 for raw in [
1858 "FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1",
1859 "FREQ=MONTHLY;BYMONTH=6;BYMONTHDAY=1",
1860 "FREQ=WEEKLY;BYMONTHDAY=15",
1861 "FREQ=DAILY;BYMONTHDAY=1",
1862 "FREQ=YEARLY;BYMONTHDAY=15",
1863 "FREQ=YEARLY;BYDAY=MO",
1864 "FREQ=YEARLY;BYYEARDAY=100",
1865 "FREQ=YEARLY;BYWEEKNO=20;BYDAY=MO",
1866 "FREQ=DAILY;BYHOUR=9,17",
1867 "FREQ=WEEKLY;X-FOO=1",
1868 "FREQ=MONTHLY;BYDAY=MO",
1869 "FREQ=WEEKLY;INTERVAL=0",
1870 "FREQ=WEEKLY;INTERVAL=abc",
1871 "FREQ=YEARLY;BYMONTH=3;BYDAY=SU",
1872 "FREQ=DAILY;BYDAY=MO,TU",
1873 "FREQ=MONTHLY;BYDAY=FR;BYMONTHDAY=13",
1874 "FREQ=MONTHLY;BYDAY=1FR;BYMONTHDAY=1,2,3",
1875 ] {
1876 assert_eq!(words(raw), None, "{raw}");
1877 }
1878 assert_eq!(
1879 words("FREQ=WEEKLY;WKST=SU;BYDAY=MO;").as_deref(),
1880 Some("Every week: MO")
1881 );
1882 }
1883
1884 #[test]
1885 fn a_bar_hidden_on_a_busy_day_splits() {
1886 let week = grid_start(2026, 10, 1);
1887 // Two bars over Mon–Wed; three timed events on Tuesday only.
1888 let mut spans = vec![all_day(week, week + 2), all_day(week, week + 2)];
1889 spans.extend((0..3).map(|i| timed(week + 1, 600 + i * 60)));
1890 let l = layout_week(&spans, week, 2);
1891 // Tuesday overflows, so its last line (the second bar) shows "+4".
1892 assert_eq!(l.more, [0, 4, 0, 0, 0, 0, 0]);
1893 let second: Vec<_> = l.pieces.iter().filter(|p| p.item == 1).collect();
1894 assert_eq!(second.len(), 2);
1895 assert_eq!(
1896 (second[0].col, second[0].len, second[0].ends),
1897 (0, 1, false)
1898 );
1899 assert_eq!(
1900 (second[1].col, second[1].len, second[1].starts),
1901 (2, 1, false)
1902 );
1903 }
1904
1905 #[test]
1906 fn times_on_each_day() {
1907 let s = Span {
1908 first: 10,
1909 last: 12,
1910 all_day: false,
1911 start_min: 22 * 60,
1912 end_min: 9 * 60,
1913 };
1914 assert_eq!(when_on(&s, 10), When::From(1320));
1915 assert_eq!(when_on(&s, 11), When::AllDay);
1916 assert_eq!(when_on(&s, 12), When::Until(540));
1917 // Ending at midnight, the last day runs to its end.
1918 let s = Span { end_min: 1440, ..s };
1919 assert_eq!(when_on(&s, 12), When::AllDay);
1920 assert_eq!(when_on(&timed(5, 600), 5), When::Range(600, 660));
1921 assert_eq!(when_on(&all_day(5, 5), 5), When::AllDay);
1922 }
1923
1924 #[test]
1925 fn links_are_found_in_text() {
1926 assert_eq!(
1927 split_links("See https://example.com/a?b=1. Or http://x.org)"),
1928 [
1929 ("See ".to_string(), false),
1930 ("https://example.com/a?b=1".to_string(), true),
1931 (". Or ".to_string(), false),
1932 ("http://x.org".to_string(), true),
1933 (")".to_string(), false),
1934 ]
1935 );
1936 assert_eq!(
1937 split_links("no links, javascript:alert(1)"),
1938 [("no links, javascript:alert(1)".to_string(), false)]
1939 );
1940 }
1941
1942 #[test]
1943 fn links_need_a_host_and_keep_balanced_brackets() {
1944 assert_eq!(
1945 split_links("a https:// b"),
1946 [("a https:// b".to_string(), false)]
1947 );
1948 assert_eq!(
1949 split_links("(https://en.wikipedia.org/wiki/Foo_(bar))"),
1950 [
1951 ("(".to_string(), false),
1952 ("https://en.wikipedia.org/wiki/Foo_(bar)".to_string(), true),
1953 (")".to_string(), false),
1954 ]
1955 );
1956 }
1957
1958 #[test]
1959 fn more_counts_the_hidden_items_of_a_column() {
1960 let week = grid_start(2026, 10, 1);
1961 let d = |c: i64| week + c;
1962 let five: Vec<Span> = (0..5).map(|n| timed(d(1), 60 * n)).collect();
1963 let l = layout_week(&five, week, 3);
1964 assert_eq!(l.more, [0, 3, 0, 0, 0, 0, 0]);
1965 }
1966
1967 #[test]
1968 fn a_lone_item_on_a_low_line_gets_no_more() {
1969 let week = grid_start(2026, 10, 1);
1970 let d = |c: i64| week + c;
1971 let spans = [all_day(d(0), d(4)), timed(d(6), 600)];
1972 let l = layout_week(&spans, week, 3);
1973 assert_eq!(l.more, [0; 7]);
1974 }
1975
1976 #[test]
1977 fn a_bar_pushed_below_the_lines_is_counted_where_it_hides() {
1978 let week = grid_start(2026, 10, 1);
1979 let d = |c: i64| week + c;
1980 // Three bars fill the lines of days 0 to 4, so the fourth lands on line 3.
1981 let mut spans = vec![all_day(d(0), d(4)); 3];
1982 spans.push(all_day(d(4), d(6)));
1983 let l = layout_week(&spans, week, 3);
1984 assert_eq!(l.more, [0, 0, 0, 0, 2, 1, 1]);
1985 }
1986
1987 #[test]
1988 fn midnight_end_is_the_next_day() {
1989 let mut s = timed(5, 600);
1990 s.last = 6;
1991 s.end_min = 1440;
1992 assert_eq!(s.end_at(), (7, 0));
1993 s.end_min = 540;
1994 assert_eq!(s.end_at(), (6, 540));
1995 }
1996
1997 #[test]
1998 fn opened_round_trips() {
1999 let o = Opened {
2000 collection_id: 7,
2001 recurrence_id: Some("2026-10-05T08:00:00Z".into()),
2002 name: "a/b.ics".into(),
2003 };
2004 assert_eq!(Opened::parse(&o.param()), Some(o));
2005 let series = Opened {
2006 collection_id: -1,
2007 recurrence_id: None,
2008 name: "x.ics".into(),
2009 };
2010 assert_eq!(Opened::parse(&series.param()), Some(series));
2011 }
2012}
2013