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 go(view: CalView) {
440 navigate(&Location {
441 section: Section::Calendar,
442 path: view.path(),
443 ..Location::root()
444 });
445}
446
447/// The event whose details are open, as the URL names it:
448/// `{collection}/{recurrence id or -}/{name}`.
449#[derive(Clone, Debug, PartialEq)]
450struct Opened {
451 collection_id: i64,
452 recurrence_id: Option<String>,
453 name: String,
454}
455
456impl Opened {
457 fn of(i: &PimInstance) -> Self {
458 Opened {
459 collection_id: i.collection_id,
460 recurrence_id: i.recurrence_id.clone(),
461 name: i.name.clone(),
462 }
463 }
464
465 fn param(&self) -> String {
466 format!(
467 "{}/{}/{}",
468 self.collection_id,
469 self.recurrence_id.as_deref().unwrap_or("-"),
470 self.name
471 )
472 }
473
474 fn parse(s: &str) -> Option<Self> {
475 let mut it = s.splitn(3, '/');
476 let collection_id = it.next()?.parse().ok()?;
477 let rid = it.next()?;
478 let name = it.next()?.to_string();
479 Some(Opened {
480 collection_id,
481 recurrence_id: (rid != "-").then(|| rid.to_string()),
482 name,
483 })
484 }
485
486 fn open(&self) {
487 router::set_open(&self.param());
488 }
489}
490
491/// An invitation as the instance it names, for the day and time helpers.
492fn inv_instance(v: &PimInvitation) -> PimInstance {
493 PimInstance {
494 collection_id: v.collection_id,
495 name: v.name.clone(),
496 uid: v.uid.clone(),
497 recurrence_id: v.recurrence_id.clone(),
498 start: v.start.clone(),
499 end: v.end.clone(),
500 all_day: v.all_day,
501 component: "VEVENT".into(),
502 summary: v.summary.clone(),
503 location: v.location.clone(),
504 status: None,
505 transparent: false,
506 has_attendees: true,
507 partstat: None,
508 organizer: None,
509 }
510}
511
512/// An instance with what the views derive from it.
513#[derive(Clone)]
514struct Shown {
515 inst: PimInstance,
516 span: Span,
517 color: String,
518}
519
520#[component]
521pub fn CalendarMain(
522 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
523 hidden: RwSignal<HashSet<i64>>,
524 loc: ReadSignal<Location>,
525 /// 0 is Sunday. From the profile.
526 week_start: Signal<u32>,
527) -> impl IntoView {
528 let view = Memo::new(move |_| loc.with(|l| CalView::from_path(&l.path)));
529 let opened = Memo::new(move |_| loc.with(|l| l.open.as_deref().and_then(Opened::parse)));
530 // Bumped after an answer or an import: every list refetches.
531 let tick = RwSignal::new(0u32);
532
533 let month = RwSignal::new(Option::<Result<api::PimInstances, String>>::None);
534 let month_seq = StoredValue::new(0u32);
535 let month_key = StoredValue::new(None::<(i32, u32)>);
536 // The new month's grid appears only after its fetch, without focus.
537 let refocus = StoredValue::new(false);
538 Effect::new(move |_| {
539 tick.track();
540 collections.track();
541 let CalView::Month(y, m) = view.get() else {
542 return;
543 };
544 // Another month's instances would land on the wrong days.
545 if month_key.get_value() != Some((y, m)) {
546 month_key.set_value(Some((y, m)));
547 month.set(None);
548 }
549 let start = grid_start(y, m, week_start.get());
550 let seq = month_seq.get_value() + 1;
551 month_seq.set_value(seq);
552 spawn_local(async move {
553 let r = api::pim_instances(
554 &day_rfc3339(start),
555 &day_rfc3339(start + GRID_DAYS),
556 &browser_tz(),
557 )
558 .await;
559 if month_seq.try_get_value() == Some(seq) {
560 let _ = month.try_set(Some(r.map_err(|e| e.to_string())));
561 if refocus.try_get_value() == Some(true) {
562 refocus.set_value(false);
563 request_animation_frame(|| {
564 let cell = web_sys::window()
565 .and_then(|w| w.document())
566 .and_then(|d| {
567 d.query_selector(".cal-weeks .cal-cell:not(.cal-out)")
568 .ok()
569 .flatten()
570 })
571 .and_then(|e| e.dyn_into::<web_sys::HtmlElement>().ok());
572 if let Some(cell) = cell {
573 let _ = cell.focus();
574 }
575 });
576 }
577 }
578 });
579 });
580
581 let agenda = RwSignal::new(Option::<Result<api::PimInstances, String>>::None);
582 let agenda_seq = StoredValue::new(0u32);
583 Effect::new(move |_| {
584 tick.track();
585 collections.track();
586 if view.get() != CalView::Agenda {
587 return;
588 }
589 let from = today();
590 let seq = agenda_seq.get_value() + 1;
591 agenda_seq.set_value(seq);
592 spawn_local(async move {
593 let r = api::pim_instances(
594 &day_rfc3339(from),
595 &day_rfc3339(from + AGENDA_DAYS),
596 &browser_tz(),
597 )
598 .await;
599 if agenda_seq.try_get_value() == Some(seq) {
600 let _ = agenda.try_set(Some(r.map_err(|e| e.to_string())));
601 }
602 });
603 });
604
605 let invitations = RwSignal::new(Option::<Result<Vec<PimInvitation>, String>>::None);
606 let invitations_seq = StoredValue::new(0u32);
607 Effect::new(move |_| {
608 tick.track();
609 collections.track();
610 let seq = invitations_seq.get_value() + 1;
611 invitations_seq.set_value(seq);
612 spawn_local(async move {
613 let r = api::pim_invitations(&browser_tz()).await;
614 if invitations_seq.try_get_value() == Some(seq) {
615 let _ = invitations.try_set(Some(r.map_err(|e| e.to_string())));
616 }
617 });
618 });
619 let refresh = Callback::new(move |_| tick.update(|t| *t += 1));
620
621 let colors = Memo::new(move |_| {
622 collections.with(|c| {
623 c.iter()
624 .flatten()
625 .map(|c| (c.id, safe_color(c.color.as_deref())))
626 .collect::<HashMap<_, _>>()
627 })
628 });
629 let shown = move |list: &api::PimInstances| -> Vec<Shown> {
630 let colors = colors.get();
631 hidden.with(|h| {
632 list.instances
633 .iter()
634 .filter(|i| !h.contains(&i.collection_id))
635 .map(|i| Shown {
636 span: span_of(i),
637 color: colors
638 .get(&i.collection_id)
639 .cloned()
640 .unwrap_or_else(|| safe_color(None)),
641 inst: i.clone(),
642 })
643 .collect()
644 })
645 };
646
647 // PageUp / PageDown turn the month while the grid has focus. Elsewhere
648 // they scroll the page to the day list.
649 owned_window_listener(leptos::ev::keydown, move |ev| {
650 let step = match ev.key().as_str() {
651 "PageUp" => -1,
652 "PageDown" => 1,
653 _ => return,
654 };
655 if ev.alt_key() || ev.ctrl_key() || ev.meta_key() || ev.shift_key() {
656 return;
657 }
658 let in_grid = web_sys::window()
659 .and_then(|w| w.document())
660 .and_then(|d| d.active_element())
661 .and_then(|e| e.closest(".cal-weeks").ok().flatten())
662 .is_some();
663 if let (CalView::Month(y, m), true) = (view.get_untracked(), in_grid) {
664 ev.prevent_default();
665 refocus.set_value(true);
666 let (y, m) = add_months(y, m, step);
667 go(CalView::Month(y, m));
668 }
669 });
670
671 let pending = move || {
672 invitations.with(|i| match i {
673 Some(Ok(list)) => list.len(),
674 _ => 0,
675 })
676 };
677 let is_month = Memo::new(move |_| matches!(view.get(), CalView::Month(..)));
678 // The month shown, or this month from another tab.
679 let this_month = move || match view.get_untracked() {
680 v @ CalView::Month(..) => v,
681 _ => {
682 let (y, m, _) = civil_from_days(today());
683 CalView::Month(y, m)
684 }
685 };
686 let step_month = move |step: i32| {
687 if let CalView::Month(y, m) = view.get_untracked() {
688 let (y, m) = add_months(y, m, step);
689 go(CalView::Month(y, m));
690 }
691 };
692 let title = move || match view.get() {
693 CalView::Month(y, m) => intl(
694 &js_sys::Date::new_with_year_month_day(y as u32, m as i32 - 1, 1),
695 &[("month", "long"), ("year", "numeric")],
696 ),
697 CalView::Agenda => i18n::t(k::PIM_UPCOMING).to_string(),
698 CalView::Invitations => i18n::t(k::PIM_INVITATIONS).to_string(),
699 };
700 let tab_of = |v: CalView| match v {
701 CalView::Month(..) => 0,
702 CalView::Agenda => 1,
703 CalView::Invitations => 2,
704 };
705 let selected = move |i: usize| tab_of(view.get()) == i;
706 let tab_at = move |i: usize| [this_month(), CalView::Agenda, CalView::Invitations][i];
707 // The buttons stay mounted across views, so a keyboard user keeps focus.
708 let toolbar = view! {
709 <div class="cal-toolbar">
710 {move || is_month.get().then(|| view! {
711 <div class="cal-nav">
712 <button
713 class="icon-btn icon-btn-sm"
714 title=i18n::t(k::PIM_PREV_MONTH)
715 aria-label=i18n::t(k::PIM_PREV_MONTH)
716 on:click=move |_| step_month(-1)
717 >
718 {icon_svg(IconName::ChevronRight, "ic-btn flip")}
719 </button>
720 <button
721 class="btn btn-sm"
722 on:click=move |_| {
723 let (y, m, _) = civil_from_days(today());
724 go(CalView::Month(y, m));
725 }
726 >
727 {i18n::t(k::PIM_TODAY)}
728 </button>
729 <button
730 class="icon-btn icon-btn-sm"
731 title=i18n::t(k::PIM_NEXT_MONTH)
732 aria-label=i18n::t(k::PIM_NEXT_MONTH)
733 on:click=move |_| step_month(1)
734 >
735 {icon_svg(IconName::ChevronRight, "ic-btn")}
736 </button>
737 </div>
738 })}
739 <h2 class="cal-title">{title}</h2>
740 <div class="cal-views" role="tablist" on:keydown=move |ev| {
741 let step = match ev.key().as_str() {
742 "ArrowRight" => 1,
743 "ArrowLeft" => -1,
744 _ => return,
745 };
746 ev.prevent_default();
747 let to = (tab_of(view.get_untracked()) as i32 + step).rem_euclid(3) as usize;
748 go(tab_at(to));
749 let tab = web_sys::window()
750 .and_then(|w| w.document())
751 .and_then(|d| d.get_element_by_id(TAB_IDS[to]))
752 .and_then(|e| e.dyn_into::<web_sys::HtmlElement>().ok());
753 if let Some(tab) = tab {
754 let _ = tab.focus();
755 }
756 }>
757 {(0..3).map(|i| view! {
758 <button
759 role="tab"
760 id=TAB_IDS[i]
761 aria-controls="cal-panel"
762 tabindex=move || if selected(i) { "0" } else { "-1" }
763 class="cal-view-btn"
764 class:active=move || selected(i)
765 aria-selected=move || selected(i).to_string()
766 on:click=move |_| go(tab_at(i))
767 >
768 {i18n::t([k::PIM_MONTH, k::PIM_AGENDA, k::PIM_INVITATIONS][i])}
769 {(i == 2).then_some(move || (pending() > 0).then(|| view! {
770 <span class="cal-badge">{pending()}</span>
771 }))}
772 </button>
773 }).collect_view()}
774 </div>
775 </div>
776 };
777
778 let body = move || match view.get() {
779 CalView::Month(y, m) => view! {
780 <MonthView y=y m=m week_start=week_start.get() data=month on_retry=refresh shown=shown/>
781 }
782 .into_any(),
783 CalView::Agenda => view! {
784 <AgendaView data=agenda on_retry=refresh shown=shown/>
785 }
786 .into_any(),
787 CalView::Invitations => view! {
788 <InvitationsView data=invitations collections=collections on_replied=refresh/>
789 }
790 .into_any(),
791 };
792
793 view! {
794 <div class="cal">
795 {toolbar}
796 <div
797 id="cal-panel"
798 role="tabpanel"
799 aria-labelledby=move || TAB_IDS[tab_of(view.get())]
800 >
801 {body}
802 </div>
803 </div>
804 {move || opened.get().map(|o| view! {
805 <EventDialog
806 target=o
807 collections=collections
808 on_replied=refresh
809 on_close=Callback::new(move |_| router::close_open())
810 />
811 })}
812 }
813}
814
815fn truncated_note(list: &api::PimInstances) -> Option<impl IntoView + use<>> {
816 list.truncated.then(|| {
817 view! { <p class="cal-truncated">{i18n::t(k::PIM_TRUNCATED)}</p> }
818 })
819}
820
821fn loading_or_error(
822 data: &Option<Result<api::PimInstances, String>>,
823 retry: Callback<()>,
824) -> Result<api::PimInstances, AnyView> {
825 match data {
826 None => Err(view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any()),
827 Some(Err(e)) => Err(view! {
828 <div class="card error-card">
829 <span>{e.clone()}</span>
830 <button class="btn" on:click=move |_| retry.run(())>{i18n::t(k::RETRY)}</button>
831 </div>
832 }
833 .into_any()),
834 Some(Ok(list)) => Ok(list.clone()),
835 }
836}
837
838/// One line of a day list: time, color and title.
839fn day_row(s: &Shown, day: i64) -> impl IntoView + use<> {
840 let o = Opened::of(&s.inst);
841 let when = fmt_when(when_on(&s.span, day), day);
842 let title = s
843 .inst
844 .summary
845 .clone()
846 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
847 let cancelled = struck(&s.inst);
848 let location = s.inst.location.clone();
849 view! {
850 <button class="cal-row" class:cal-cancelled=cancelled on:click=move |_| o.open()>
851 <span class="cal-row-time">{when}</span>
852 <span class="cal-dot" style=format!("--c: {}", s.color)></span>
853 <span class="cal-row-main">
854 <span class="cal-row-title">{title}</span>
855 {location.map(|l| view! { <span class="cal-row-meta">{l}</span> })}
856 </span>
857 </button>
858 }
859}
860
861#[component]
862fn MonthView(
863 y: i32,
864 m: u32,
865 week_start: u32,
866 data: RwSignal<Option<Result<api::PimInstances, String>>>,
867 on_retry: Callback<()>,
868 shown: impl Fn(&api::PimInstances) -> Vec<Shown> + Copy + Send + Sync + 'static,
869) -> impl IntoView {
870 let start = grid_start(y, m, week_start);
871 let now = today();
872 let in_month = move |d: i64| {
873 let (yy, mm, _) = civil_from_days(d);
874 yy == y && mm == m
875 };
876 let selected = RwSignal::new(if in_month(now) {
877 now
878 } else {
879 days_from_civil(y, m, 1)
880 });
881 let list_ref: NodeRef<leptos::html::Div> = NodeRef::new();
882 let pick = move |day: i64| {
883 selected.set(day);
884 if let Some(el) = list_ref.get_untracked() {
885 let opts = web_sys::ScrollIntoViewOptions::new();
886 opts.set_block(web_sys::ScrollLogicalPosition::Nearest);
887 el.scroll_into_view_with_scroll_into_view_options(&opts);
888 }
889 };
890 let head = (0..7)
891 .map(|i| {
892 view! {
893 <div class="cal-head-day">{intl(&day_date(start + i), &[("weekday", "short")])}</div>
894 }
895 })
896 .collect::<Vec<_>>();
897 view! {
898 <div class="cal-month">
899 <div class="cal-head">{head}</div>
900 {move || data.with(|d| match loading_or_error(d, on_retry) {
901 Err(v) => v,
902 Ok(list) => {
903 let items = shown(&list);
904 let spans: Vec<Span> = items.iter().map(|s| s.span).collect();
905 let weeks = (0..6)
906 .map(|w| {
907 let week = start + w * 7;
908 let layout = layout_week(&spans, week, LINES);
909 let cells = (0..7usize)
910 .map(|c| {
911 let day = week + c as i64;
912 let (_, _, dnum) = civil_from_days(day);
913 let on_day = items.iter().filter(|s| s.span.covers(day));
914 let n = on_day.clone().count();
915 let dots: Vec<String> =
916 on_day.take(3).map(|s| s.color.clone()).collect();
917 let label = match n {
918 0 => fmt_day_long(day),
919 1 => format!("{}, {}", fmt_day_long(day), i18n::t(k::PIM_EVENTS_ONE)),
920 n => format!(
921 "{}, {}",
922 fmt_day_long(day),
923 i18n::t_fmt(k::PIM_EVENTS_N, &n.to_string())
924 ),
925 };
926 view! {
927 <button
928 class="cal-cell"
929 class:cal-out=!in_month(day)
930 class:cal-today=day == now
931 class:cal-sel=move || selected.get() == day
932 style=format!("grid-column: {}", c + 1)
933 aria-label=label
934 on:click=move |_| pick(day)
935 >
936 <span class="cal-num">{dnum}</span>
937 <span class="cal-dots">
938 {dots
939 .into_iter()
940 .map(|c| view! { <span class="cal-dot" style=format!("--c: {c}")></span> })
941 .collect::<Vec<_>>()}
942 </span>
943 </button>
944 }
945 })
946 .collect::<Vec<_>>();
947 let pieces = layout
948 .pieces
949 .iter()
950 .map(|p| {
951 let s = &items[p.item];
952 let o = Opened::of(&s.inst);
953 let bar = s.span.is_bar();
954 let title = s
955 .inst
956 .summary
957 .clone()
958 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
959 let time = (!bar).then(|| fmt_min(s.span.first, s.span.start_min));
960 let cancelled = struck(&s.inst);
961 let tip = match &time {
962 Some(t) => format!("{t} {title}"),
963 None => title.clone(),
964 };
965 view! {
966 <button
967 class="cal-item"
968 class:cal-bar=bar
969 class:cal-chip=!bar
970 class:cal-cont-l=!p.starts
971 class:cal-cont-r=!p.ends
972 class:cal-cancelled=cancelled
973 style=format!(
974 "grid-column: {} / span {}; grid-row: {}; --c: {}",
975 p.col + 1,
976 p.len,
977 p.line + 2,
978 s.color
979 )
980 title=tip
981 on:click=move |_| o.open()
982 >
983 {(!bar).then(|| view! { <span class="cal-dot"></span> })}
984 {time.map(|t| view! { <span class="cal-time">{t}</span> })}
985 <span class="cal-item-title">{title}</span>
986 </button>
987 }
988 })
989 .collect::<Vec<_>>();
990 let more = layout
991 .more
992 .iter()
993 .enumerate()
994 .filter(|&(_, &n)| n > 0)
995 .map(|(c, &n)| {
996 let day = week + c as i64;
997 view! {
998 <button
999 class="cal-more"
1000 style=format!("grid-column: {}; grid-row: {}", c + 1, LINES + 1)
1001 on:click=move |_| pick(day)
1002 >
1003 {i18n::t_fmt(k::PIM_MORE_N, &n.to_string())}
1004 </button>
1005 }
1006 })
1007 .collect::<Vec<_>>();
1008 view! {
1009 <div class="cal-week" style=format!("--lines: {LINES}")>
1010 {cells}
1011 {pieces}
1012 {more}
1013 </div>
1014 }
1015 })
1016 .collect::<Vec<_>>();
1017 let day_list = move || {
1018 let day = selected.get();
1019 let rows: Vec<_> = items
1020 .iter()
1021 .filter(|s| s.span.covers(day))
1022 .map(|s| day_row(s, day))
1023 .collect();
1024 view! {
1025 <h3 class="cal-day-title">{fmt_day_long(day)}</h3>
1026 {if rows.is_empty() {
1027 view! { <p class="muted cal-pad">{i18n::t(k::PIM_NO_EVENTS_DAY)}</p> }.into_any()
1028 } else {
1029 view! { <div class="cal-rows">{rows}</div> }.into_any()
1030 }}
1031 }
1032 };
1033 view! {
1034 {truncated_note(&list)}
1035 <div class="cal-weeks">{weeks}</div>
1036 <div class="cal-day" node_ref=list_ref>{day_list}</div>
1037 }
1038 .into_any()
1039 }
1040 })}
1041 </div>
1042 }
1043}
1044
1045/// The agenda shows today and the days after it. The month view is for
1046/// browsing further.
1047const AGENDA_DAYS: i64 = 7;
1048
1049#[component]
1050fn AgendaView(
1051 data: RwSignal<Option<Result<api::PimInstances, String>>>,
1052 on_retry: Callback<()>,
1053 shown: impl Fn(&api::PimInstances) -> Vec<Shown> + Copy + Send + Sync + 'static,
1054) -> impl IntoView {
1055 view! {
1056 <div class="cal-agenda">
1057 {move || data.with(|d| match loading_or_error(d, on_retry) {
1058 Err(v) => v,
1059 Ok(list) => {
1060 let items = shown(&list);
1061 let from = today();
1062 let groups: Vec<_> = (from..from + AGENDA_DAYS)
1063 .filter_map(|day| {
1064 let rows: Vec<_> = items
1065 .iter()
1066 .filter(|s| s.span.covers(day))
1067 .map(|s| day_row(s, day))
1068 .collect();
1069 (!rows.is_empty()).then(|| view! {
1070 <section class="cal-agenda-day">
1071 <h3 class="cal-day-title" class:cal-day-today=day == from>
1072 {fmt_day_long(day)}
1073 </h3>
1074 <div class="cal-rows">{rows}</div>
1075 </section>
1076 })
1077 })
1078 .collect();
1079 let empty = groups.is_empty().then(|| view! {
1080 <div class="empty-state">
1081 {icon_svg(IconName::Calendar, "empty-glyph")}
1082 <p class="muted">{i18n::t(k::PIM_NO_EVENTS_AGENDA)}</p>
1083 </div>
1084 });
1085 view! {
1086 {truncated_note(&list)}
1087 {empty}
1088 {groups}
1089 }
1090 .into_any()
1091 }
1092 })}
1093 </div>
1094 }
1095}
1096
1097/// Answer an invitation, then refresh the lists, also after a failure: the
1098/// invitation may have changed elsewhere. `busy` stays set on success; `done`
1099/// ends it once the refresh has landed.
1100fn reply(
1101 toast: ToastMsg,
1102 busy: RwSignal<bool>,
1103 collection_id: i64,
1104 name: String,
1105 recurrence_id: Option<String>,
1106 partstat: &'static str,
1107 done: Callback<()>,
1108) {
1109 busy.set(true);
1110 spawn_local(async move {
1111 let body = PimReply {
1112 collection_id,
1113 name,
1114 recurrence_id,
1115 partstat: partstat.to_string(),
1116 tz: Some(browser_tz()),
1117 };
1118 match api::pim_reply(body).await {
1119 Ok(_) => {
1120 show(toast, i18n::t(k::PIM_REPLIED));
1121 // The dialog or view may be gone by now.
1122 let _ = done.try_run(());
1123 }
1124 Err(e) => {
1125 let _ = busy.try_set(false);
1126 show_error(toast, e.to_string());
1127 let _ = done.try_run(());
1128 }
1129 }
1130 });
1131}
1132
1133/// Accept, maybe, decline. `current` marks the answer already given.
1134fn reply_buttons(
1135 current: Option<String>,
1136 busy: RwSignal<bool>,
1137 on: impl Fn(&'static str) + Clone + 'static,
1138) -> impl IntoView {
1139 [
1140 ("ACCEPTED", k::PIM_ACCEPT),
1141 ("TENTATIVE", k::PIM_TENTATIVE),
1142 ("DECLINED", k::PIM_DECLINE),
1143 ]
1144 .map(|(ps, label)| {
1145 let on = on.clone();
1146 let active = current.as_deref() == Some(ps);
1147 view! {
1148 <button
1149 class="btn btn-sm"
1150 class:btn-primary=active
1151 aria-pressed=active.to_string()
1152 disabled=move || busy.get()
1153 on:click=move |_| on(ps)
1154 >
1155 {i18n::t(label)}
1156 </button>
1157 }
1158 })
1159 .into_iter()
1160 .collect::<Vec<_>>()
1161}
1162
1163#[component]
1164fn InvitationsView(
1165 data: RwSignal<Option<Result<Vec<PimInvitation>, String>>>,
1166 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
1167 on_replied: Callback<()>,
1168) -> impl IntoView {
1169 let toast = use_context::<ToastMsg>().expect("toast context");
1170 view! {
1171 <div class="cal-invitations">
1172 {move || match data.get() {
1173 None => view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any(),
1174 Some(Err(e)) => view! {
1175 <div class="card error-card">
1176 <span>{e}</span>
1177 <button class="btn" on:click=move |_| on_replied.run(())>{i18n::t(k::RETRY)}</button>
1178 </div>
1179 }
1180 .into_any(),
1181 Some(Ok(list)) if list.is_empty() => view! {
1182 <div class="empty-state">
1183 {icon_svg(IconName::Calendar, "empty-glyph")}
1184 <p class="muted">{i18n::t(k::PIM_NO_INVITATIONS)}</p>
1185 </div>
1186 }
1187 .into_any(),
1188 Some(Ok(list)) => {
1189 let names: HashMap<i64, String> = collections.with(|c| {
1190 c.iter().flatten().map(|c| (c.id, display_name(c))).collect()
1191 });
1192 list.into_iter()
1193 .map(|inv| {
1194 // A series opens at its next instance, the one listed.
1195 let o = Opened {
1196 collection_id: inv.collection_id,
1197 recurrence_id: inv
1198 .recurrence_id
1199 .clone()
1200 .or_else(|| inv.recurring.then(|| inv.start.clone())),
1201 name: inv.name.clone(),
1202 };
1203 let span = span_of(&inv_instance(&inv));
1204 let series = inv.recurring && inv.recurrence_id.is_none();
1205 let mut meta = vec![fmt_span(&span)];
1206 match (&inv.rrule, &inv.recurrence_id) {
1207 (Some(r), None) => meta.push(rrule_text(&with_start_day(r, span.first))),
1208 (None, Some(_)) => meta.push(i18n::t(k::PIM_THIS_EVENT).to_string()),
1209 _ => {}
1210 }
1211 if let Some(n) = names.get(&inv.collection_id) {
1212 meta.push(n.clone());
1213 }
1214 let organizer = inv.organizer.as_ref().map(|p| {
1215 p.name.clone().unwrap_or_else(|| {
1216 p.address.trim_start_matches("mailto:").to_string()
1217 })
1218 });
1219 let title = inv
1220 .summary
1221 .clone()
1222 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
1223 let (id, name, rid) =
1224 (inv.collection_id, inv.name.clone(), inv.recurrence_id.clone());
1225 let open = o.clone();
1226 let busy = RwSignal::new(false);
1227 view! {
1228 <div class="cal-inv">
1229 <button class="cal-inv-main" on:click=move |_| open.open()>
1230 <span class="cal-inv-title">{title}</span>
1231 <span class="cal-row-meta">{meta.join(" · ")}</span>
1232 {inv.location.clone().map(|l| view! { <span class="cal-row-meta">{l}</span> })}
1233 {organizer.map(|n| view! {
1234 <span class="cal-row-meta">{i18n::t_fmt(k::PIM_FROM_ORGANIZER, &n)}</span>
1235 })}
1236 {series.then(|| view! {
1237 <span class="cal-row-meta">{i18n::t(k::PIM_INV_SERIES_HINT)}</span>
1238 })}
1239 </button>
1240 <div class="cal-inv-actions">
1241 {reply_buttons(None, busy, move |ps| {
1242 reply(toast, busy, id, name.clone(), rid.clone(), ps, on_replied)
1243 })}
1244 </div>
1245 </div>
1246 }
1247 })
1248 .collect::<Vec<_>>()
1249 .into_any()
1250 }
1251 }}
1252 </div>
1253 }
1254}
1255
1256fn partstat_label(ps: Option<&str>) -> (&'static str, &'static str) {
1257 match ps {
1258 Some("ACCEPTED") => (k::PIM_PS_ACCEPTED, "ps-accepted"),
1259 Some("DECLINED") => (k::PIM_PS_DECLINED, "ps-declined"),
1260 Some("TENTATIVE") => (k::PIM_PS_TENTATIVE, "ps-tentative"),
1261 Some("DELEGATED") => (k::PIM_PS_DELEGATED, "ps-muted"),
1262 _ => (k::PIM_PS_NEEDS_ACTION, "ps-muted"),
1263 }
1264}
1265
1266/// `FREQ=WEEKLY;INTERVAL=2;BYDAY=TU` as words; a rule it cannot put into
1267/// words stays raw.
1268fn rrule_text(rule: &str) -> String {
1269 rrule_words(rule, weekday_name, month_name, until_date).unwrap_or_else(|| rule.to_string())
1270}
1271
1272fn rrule_words(
1273 rule: &str,
1274 day: fn(&str) -> Option<String>,
1275 month: fn(u32) -> Option<String>,
1276 date: fn(&str) -> Option<String>,
1277) -> Option<String> {
1278 let part = |key: &str| {
1279 rule.split(';')
1280 .find_map(|p| p.strip_prefix(key)?.strip_prefix('='))
1281 };
1282 let list = |key: &str| part(key).into_iter().flat_map(|v| v.split(','));
1283 let n = part("INTERVAL")
1284 .and_then(|n| n.parse::<u32>().ok())
1285 .unwrap_or(1);
1286 let freq = part("FREQ");
1287 let keys = match freq {
1288 Some("DAILY") => (k::PIM_RRULE_DAILY, k::PIM_RRULE_DAILY_N),
1289 Some("WEEKLY") => (k::PIM_RRULE_WEEKLY, k::PIM_RRULE_WEEKLY_N),
1290 Some("MONTHLY") => (k::PIM_RRULE_MONTHLY, k::PIM_RRULE_MONTHLY_N),
1291 Some("YEARLY") => (k::PIM_RRULE_YEARLY, k::PIM_RRULE_YEARLY_N),
1292 _ => return None,
1293 };
1294 let mut text = match n {
1295 1 => i18n::t(keys.0).to_string(),
1296 n => i18n::t_fmt(keys.1, &n.to_string()),
1297 };
1298 let numbered = matches!(freq, Some("MONTHLY" | "YEARLY"));
1299 let worded = |key: &str| match key {
1300 "FREQ" | "INTERVAL" | "UNTIL" | "COUNT" | "WKST" | "BYDAY" => true,
1301 "BYMONTH" => freq == Some("YEARLY"),
1302 "BYMONTHDAY" => numbered,
1303 _ => false,
1304 };
1305 let all_worded = rule
1306 .split(';')
1307 .all(|p| p.is_empty() || p.split_once('=').is_some_and(|(key, _)| worded(key)));
1308 // Without BYMONTH, a yearly BYDAY or BYMONTHDAY counts through the whole year.
1309 let yearwide = freq == Some("YEARLY")
1310 && part("BYMONTH").is_none()
1311 && (part("BYDAY").is_some() || part("BYMONTHDAY").is_some());
1312 // BYDAY with BYMONTHDAY is an intersection; listing both reads as a union.
1313 let both = part("BYDAY").is_some() && part("BYMONTHDAY").is_some();
1314 if !all_worded || yearwide || both {
1315 return None;
1316 }
1317 let mut on = Vec::new();
1318 for m in list("BYMONTH") {
1319 on.push(month(m.parse().ok()?)?);
1320 }
1321 for d in list("BYDAY") {
1322 let split = d.len().checked_sub(2)?;
1323 let (nth, code) = d.split_at_checked(split)?;
1324 let name = day(code)?;
1325 on.push(match nth {
1326 // A plain weekday outside WEEKLY means every such day of the
1327 // period, which "Every month: Mon" does not say.
1328 "" if freq == Some("WEEKLY") => name,
1329 "" => return None,
1330 _ if !numbered => return None,
1331 nth => i18n::t_fmt2(k::PIM_RRULE_NTH, ordinal(nth)?, &name),
1332 });
1333 }
1334 for d in list("BYMONTHDAY") {
1335 on.push(match d {
1336 "-1" => i18n::t(k::PIM_RRULE_LAST_DAY).to_string(),
1337 d => i18n::t_fmt(k::PIM_RRULE_MONTH_DAY, &d.parse::<u8>().ok()?.to_string()),
1338 });
1339 }
1340 if !on.is_empty() {
1341 text = format!("{text}: {}", on.join(", "));
1342 }
1343 if let Some(u) = part("UNTIL") {
1344 text = format!("{text}; {}", i18n::t_fmt(k::PIM_RRULE_UNTIL, &date(u)?));
1345 } else if let Some(c) = part("COUNT") {
1346 text = format!(
1347 "{text}; {}",
1348 i18n::t_fmt(k::PIM_RRULE_COUNT, &c.parse::<u32>().ok()?.to_string())
1349 );
1350 }
1351 Some(text)
1352}
1353
1354/// The ordinal of `2TU` or `-1FR`. Others are rare enough to stay raw.
1355fn ordinal(nth: &str) -> Option<&'static str> {
1356 Some(i18n::t(match nth {
1357 "1" | "+1" => k::PIM_RRULE_ORD_1,
1358 "2" | "+2" => k::PIM_RRULE_ORD_2,
1359 "3" | "+3" => k::PIM_RRULE_ORD_3,
1360 "4" | "+4" => k::PIM_RRULE_ORD_4,
1361 "5" | "+5" => k::PIM_RRULE_ORD_5,
1362 "-1" => k::PIM_RRULE_ORD_LAST,
1363 _ => return None,
1364 }))
1365}
1366
1367fn month_name(m: u32) -> Option<String> {
1368 let m = (1..=12).contains(&m).then_some(m)?;
1369 let date = js_sys::Date::new_with_year_month_day(2024, m as i32 - 1, 1);
1370 Some(intl(&date, &[("month", "long")]))
1371}
1372
1373/// UNTIL (`20261231` or `20261231T225959Z`) as a local date.
1374fn until_date(u: &str) -> Option<String> {
1375 let num = |r: std::ops::Range<usize>| u.get(r)?.parse::<u32>().ok();
1376 let (y, m, d) = (num(0..4)?, num(4..6)?, num(6..8)?);
1377 let date = match u.get(8..)? {
1378 t if t.len() == 8 && t.is_ascii() && t.ends_with('Z') => {
1379 let iso = format!(
1380 "{y:04}-{m:02}-{d:02}T{}:{}:{}Z",
1381 &t[1..3],
1382 &t[3..5],
1383 &t[5..7]
1384 );
1385 js_sys::Date::new(&iso.into())
1386 }
1387 // A DATE, or floating: the wall-clock date.
1388 _ => js_sys::Date::new_with_year_month_day(y, m as i32 - 1, d as i32),
1389 };
1390 (!date.get_time().is_nan()).then(|| intl(&date, &[("dateStyle", "medium")]))
1391}
1392
1393/// A weekly rule without BYDAY repeats on its start's weekday. Naming it
1394/// makes "Every week" read "Every week: Tue".
1395fn with_start_day(rule: &str, first: i64) -> String {
1396 let weekly = rule.split(';').any(|p| p == "FREQ=WEEKLY");
1397 if !weekly || rule.split(';').any(|p| p.starts_with("BYDAY=")) {
1398 return rule.to_string();
1399 }
1400 let code = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"][weekday(first) as usize];
1401 format!("{rule};BYDAY={code}")
1402}
1403
1404/// `TU` as the locale's short weekday name.
1405fn weekday_name(code: &str) -> Option<String> {
1406 let offset = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]
1407 .iter()
1408 .position(|&d| d == code)?;
1409 // 2024-01-01 was a Monday.
1410 let date = js_sys::Date::new_with_year_month_day(2024, 0, 1 + offset as i32);
1411 Some(intl(&date, &[("weekday", "short")]))
1412}
1413
1414fn person_name(p: &api_types::PimPerson) -> String {
1415 p.name
1416 .clone()
1417 .unwrap_or_else(|| p.address.trim_start_matches("mailto:").to_string())
1418}
1419
1420/// Text with its web links clickable, for a `white-space: pre-wrap` block.
1421pub fn linkified(text: &str) -> impl IntoView + use<> {
1422 split_links(text)
1423 .into_iter()
1424 .map(|(t, link)| match link {
1425 true => {
1426 let href = t.clone();
1427 view! { <a href=href target="_blank" rel="noopener noreferrer">{t}</a> }.into_any()
1428 }
1429 false => t.into_any(),
1430 })
1431 .collect::<Vec<_>>()
1432}
1433
1434#[component]
1435fn EventDialog(
1436 target: Opened,
1437 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
1438 on_replied: Callback<()>,
1439 on_close: Callback<()>,
1440) -> impl IntoView {
1441 let toast = use_context::<ToastMsg>().expect("toast context");
1442 let detail = RwSignal::new(Option::<Result<PimEventDetail, String>>::None);
1443 let busy = RwSignal::new(false);
1444 let load_seq = StoredValue::new(0u32);
1445 let load = {
1446 let t = target.clone();
1447 move || {
1448 let t = t.clone();
1449 // Also runs after an await, when the view may be gone.
1450 let Some(seq) = load_seq.try_get_value().map(|s| s + 1) else {
1451 return;
1452 };
1453 load_seq.set_value(seq);
1454 spawn_local(async move {
1455 let r = api::pim_object(
1456 t.collection_id,
1457 &t.name,
1458 t.recurrence_id.as_deref(),
1459 &browser_tz(),
1460 )
1461 .await;
1462 let r = match r {
1463 Ok(PimObjectDetail::Event(e)) => Ok(e),
1464 Ok(PimObjectDetail::Contact(_)) => Err(i18n::t(k::PIM_NOT_EVENT).to_string()),
1465 Err(e) => Err(e.to_string()),
1466 };
1467 if load_seq.try_get_value() == Some(seq) {
1468 let _ = detail.try_set(Some(r));
1469 let _ = busy.try_set(false);
1470 }
1471 });
1472 }
1473 };
1474 load();
1475 // For one instance of a series: answer it alone, or the whole series.
1476 let only_this = RwSignal::new(true);
1477 let collection_id = target.collection_id;
1478 let collection = Memo::new(move |_| {
1479 collections.with(|c| {
1480 c.iter()
1481 .flatten()
1482 .find(|c| c.id == collection_id)
1483 .map(|c| (display_name(c), safe_color(c.color.as_deref())))
1484 })
1485 });
1486 let body = move || match detail.get() {
1487 None => view! { <p class="muted">{i18n::t(k::LOADING)}</p> }.into_any(),
1488 Some(Err(e)) => view! { <p class="form-error">{e}</p> }.into_any(),
1489 Some(Ok(d)) => {
1490 let title = d
1491 .summary
1492 .clone()
1493 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
1494 let mine = d
1495 .attendees
1496 .iter()
1497 .find(|a| a.is_owner)
1498 .and_then(|a| a.partstat.clone());
1499 let series = target.recurrence_id.is_some() && d.rrule.is_some();
1500 let rid = target.recurrence_id.clone();
1501 let (id, name) = (target.collection_id, target.name.clone());
1502 let load = load.clone();
1503 let answer = move |ps: &'static str| {
1504 let rid = if only_this.get_untracked() {
1505 rid.clone()
1506 } else {
1507 None
1508 };
1509 let load = load.clone();
1510 reply(
1511 toast,
1512 busy,
1513 id,
1514 name.clone(),
1515 rid,
1516 ps,
1517 Callback::new(move |_| {
1518 load();
1519 let _ = on_replied.try_run(());
1520 }),
1521 );
1522 };
1523 let url = d
1524 .url
1525 .clone()
1526 .filter(|u| u.starts_with("https://") || u.starts_with("http://"));
1527 view! {
1528 <h2 id="cal-detail-title" class="modal-title cal-detail-title" class:cal-cancelled=d.status.as_deref() == Some("CANCELLED")>
1529 {title}
1530 </h2>
1531 {(d.status.as_deref() == Some("CANCELLED")).then(|| view! {
1532 <p class="cal-flag">{i18n::t(k::PIM_CANCELLED)}</p>
1533 })}
1534 <dl class="cal-facts">
1535 {d.start.as_deref().zip(d.end.as_deref()).map(|(s, e)| view! {
1536 <dt>{i18n::t(k::PIM_WHEN)}</dt>
1537 <dd>{fmt_span(&span_at(s, e, d.all_day))}</dd>
1538 })}
1539 {d.rrule.clone().map(|r| {
1540 let text = match d.start.as_deref().zip(d.end.as_deref()) {
1541 Some((s, e)) => rrule_text(&with_start_day(&r, span_at(s, e, d.all_day).first)),
1542 None => rrule_text(&r),
1543 };
1544 view! {
1545 <dt>{i18n::t(k::PIM_REPEATS)}</dt>
1546 <dd title=r.clone()>{text}</dd>
1547 }
1548 })}
1549 {d.location.clone().map(|l| view! {
1550 <dt>{i18n::t(k::PIM_LOCATION)}</dt>
1551 <dd class="cal-pre">{linkified(&l)}</dd>
1552 })}
1553 {collection.get().map(|(n, c)| view! {
1554 <dt>{i18n::t(k::PIM_CALENDAR)}</dt>
1555 <dd><span class="cal-dot" style=format!("--c: {c}")></span>" "{n}</dd>
1556 })}
1557 {d.organizer.as_ref().map(|p| view! {
1558 <dt>{i18n::t(k::PIM_ORGANIZER)}</dt>
1559 <dd>{person_name(p)}</dd>
1560 })}
1561 {url.map(|u| {
1562 let href = u.clone();
1563 view! {
1564 <dt>{i18n::t(k::PIM_LINK)}</dt>
1565 <dd><a href=href target="_blank" rel="noopener noreferrer">{u}</a></dd>
1566 }
1567 })}
1568 {(!d.categories.is_empty()).then(|| view! {
1569 <dt>{i18n::t(k::PIM_CATEGORIES)}</dt>
1570 <dd>{d.categories.join(", ")}</dd>
1571 })}
1572 </dl>
1573 {(!d.attendees.is_empty()).then(|| view! {
1574 <h3 class="pim-section-title">{i18n::t(k::PIM_ATTENDEES)}</h3>
1575 <ul class="cal-attendees">
1576 {d.attendees
1577 .iter()
1578 .map(|a| {
1579 let (label, class) = partstat_label(a.partstat.as_deref());
1580 let optional = a.role.as_deref() == Some("OPT-PARTICIPANT");
1581 view! {
1582 <li>
1583 <span class="cal-att-name" title=a.person.address.clone()>
1584 {person_name(&a.person)}
1585 </span>
1586 {optional.then(|| view! { <span class="muted">{i18n::t(k::PIM_OPTIONAL)}</span> })}
1587 <span class=format!("ps-badge {class}")>{i18n::t(label)}</span>
1588 </li>
1589 }
1590 })
1591 .collect::<Vec<_>>()}
1592 </ul>
1593 })}
1594 {d.description.clone().filter(|t| !t.trim().is_empty()).map(|t| view! {
1595 <div class="cal-desc cal-pre">{linkified(&t)}</div>
1596 })}
1597 {d.can_reply.then(|| view! {
1598 <section class="cal-reply">
1599 <h3 class="pim-section-title">{i18n::t(k::PIM_YOUR_ANSWER)}</h3>
1600 {series.then(|| view! {
1601 <div class="cal-scope" role="radiogroup">
1602 <label class="check-row">
1603 <input
1604 type="radio"
1605 name="cal-scope"
1606 prop:checked=move || only_this.get()
1607 on:change=move |_| only_this.set(true)
1608 />
1609 {i18n::t(k::PIM_THIS_EVENT)}
1610 </label>
1611 <label class="check-row">
1612 <input
1613 type="radio"
1614 name="cal-scope"
1615 prop:checked=move || !only_this.get()
1616 on:change=move |_| only_this.set(false)
1617 />
1618 {i18n::t(k::PIM_ALL_EVENTS)}
1619 </label>
1620 </div>
1621 })}
1622 <div class="cal-inv-actions">{reply_buttons(mine, busy, answer)}</div>
1623 </section>
1624 })}
1625 }
1626 .into_any()
1627 }
1628 };
1629 view! {
1630 <Modal class="pim-modal cal-detail" labelled_by="cal-detail-title" on_close=on_close>
1631 {body}
1632 <div class="modal-actions">
1633 <button class="btn" on:click=move |_| on_close.run(())>{i18n::t(k::CLOSE)}</button>
1634 </div>
1635 </Modal>
1636 }
1637}
1638
1639#[cfg(test)]
1640mod tests {
1641 use super::*;
1642
1643 #[test]
1644 fn url_years_are_clamped() {
1645 assert_eq!(parse_month("2026-10"), Some((2026, 10)));
1646 assert_eq!(parse_month("9999-12"), Some((9999, 12)));
1647 for bad in ["0050-01", "-3-01", "10000-01", "2026-13", "x-01"] {
1648 assert_eq!(parse_month(bad), None, "{bad}");
1649 }
1650 }
1651
1652 fn day(y: i32, m: u32, d: u32) -> i64 {
1653 days_from_civil(y, m, d)
1654 }
1655
1656 fn timed(first: i64, start_min: u32) -> Span {
1657 Span {
1658 first,
1659 last: first,
1660 all_day: false,
1661 start_min,
1662 end_min: start_min + 60,
1663 }
1664 }
1665
1666 fn all_day(first: i64, last: i64) -> Span {
1667 Span {
1668 first,
1669 last,
1670 all_day: true,
1671 start_min: 0,
1672 end_min: 1440,
1673 }
1674 }
1675
1676 #[test]
1677 fn civil_days_round_trip() {
1678 assert_eq!(day(1970, 1, 1), 0);
1679 assert_eq!(day(2000, 3, 1), 11017);
1680 for z in [-800_000, -1, 0, 59, 60, 11016, 20_000, 2_000_000] {
1681 let (y, m, d) = civil_from_days(z);
1682 assert_eq!(day(y, m, d), z);
1683 }
1684 assert_eq!(civil_from_days(day(2024, 2, 29)), (2024, 2, 29));
1685 // 2026-10-01 is a Thursday.
1686 assert_eq!(weekday(day(2026, 10, 1)), 4);
1687 }
1688
1689 #[test]
1690 fn grid_starts_on_the_week_start() {
1691 // October 2026 starts on a Thursday.
1692 let sunday = grid_start(2026, 10, 0);
1693 let monday = grid_start(2026, 10, 1);
1694 assert_eq!(civil_from_days(sunday), (2026, 9, 27));
1695 assert_eq!(civil_from_days(monday), (2026, 9, 28));
1696 assert_eq!(weekday(monday), 1);
1697 assert_eq!(civil_from_days(grid_start(2026, 10, 6)), (2026, 9, 26));
1698 // A month starting on the week start begins the grid itself, and
1699 // six weeks always cover the whole month.
1700 assert_eq!(grid_start(2026, 6, 1), day(2026, 6, 1));
1701 for (y, m) in [(2026, 2), (2026, 8), (2027, 1)] {
1702 for ws in [0, 1, 6] {
1703 let s = grid_start(y, m, ws);
1704 let (ny, nm) = add_months(y, m, 1);
1705 assert!(s <= day(y, m, 1) && day(ny, nm, 1) <= s + GRID_DAYS);
1706 }
1707 }
1708 assert_eq!(add_months(2026, 12, 1), (2027, 1));
1709 assert_eq!(add_months(2026, 1, -1), (2025, 12));
1710 }
1711
1712 #[test]
1713 fn bars_split_across_weeks() {
1714 // Saturday to Tuesday, in weeks starting on Monday.
1715 let week1 = grid_start(2026, 10, 1);
1716 let span = all_day(day(2026, 10, 3), day(2026, 10, 6));
1717 let a = layout_week(&[span], week1, 4);
1718 assert_eq!(
1719 a.pieces,
1720 [Piece {
1721 item: 0,
1722 col: 5,
1723 len: 2,
1724 line: 0,
1725 starts: true,
1726 ends: false
1727 }]
1728 );
1729 let b = layout_week(&[span], week1 + 7, 4);
1730 assert_eq!(
1731 b.pieces,
1732 [Piece {
1733 item: 0,
1734 col: 0,
1735 len: 2,
1736 line: 0,
1737 starts: false,
1738 ends: true
1739 }]
1740 );
1741 assert_eq!(a.more, [0; 7]);
1742 }
1743
1744 #[test]
1745 fn busy_days_share_the_last_line_with_more() {
1746 let week = grid_start(2026, 10, 1);
1747 let mon = week;
1748 // Five timed events on Monday; a bar Monday to Wednesday.
1749 let mut spans: Vec<Span> = (0..5).map(|i| timed(mon, 600 + i * 30)).collect();
1750 spans.push(all_day(mon, mon + 2));
1751 let l = layout_week(&spans, week, 3);
1752 // Monday has six instances on three lines: two shown, four behind
1753 // "+4 more". The bar comes first, so it stays visible.
1754 assert_eq!(l.more, [4, 0, 0, 0, 0, 0, 0]);
1755 let bar = l.pieces.iter().find(|p| p.item == 5).unwrap();
1756 assert_eq!((bar.col, bar.len, bar.line), (0, 3, 0));
1757 assert_eq!(l.pieces.iter().filter(|p| p.col == 0).count(), 2);
1758 // Timed events keep their order.
1759 let first_chip = l.pieces.iter().find(|p| p.item != 5).unwrap();
1760 assert_eq!(first_chip.item, 0);
1761 }
1762
1763 #[test]
1764 fn a_weekly_rule_names_its_start_day() {
1765 let friday = days_from_civil(2026, 10, 2);
1766 assert_eq!(
1767 with_start_day("FREQ=WEEKLY", friday),
1768 "FREQ=WEEKLY;BYDAY=FR"
1769 );
1770 assert_eq!(
1771 with_start_day("FREQ=WEEKLY;BYDAY=MO", friday),
1772 "FREQ=WEEKLY;BYDAY=MO"
1773 );
1774 assert_eq!(with_start_day("FREQ=DAILY", friday), "FREQ=DAILY");
1775 }
1776
1777 #[test]
1778 fn a_rule_reads_as_words() {
1779 let words = |r: &str| {
1780 rrule_words(
1781 r,
1782 |d| Some(d.to_string()),
1783 |m| Some(format!("M{m}")),
1784 |u| Some(u[..8].to_string()),
1785 )
1786 };
1787 assert_eq!(
1788 words("FREQ=WEEKLY;BYDAY=TU,TH").as_deref(),
1789 Some("Every week: TU, TH")
1790 );
1791 assert_eq!(
1792 words("FREQ=MONTHLY;BYDAY=2TU;COUNT=3").as_deref(),
1793 Some("Every month: 2nd TU; 3 times")
1794 );
1795 assert_eq!(
1796 words("FREQ=MONTHLY;INTERVAL=2;BYMONTHDAY=15,-1;UNTIL=20261231T225959Z").as_deref(),
1797 Some("Every 2 months: day 15, last day; until 20261231")
1798 );
1799 assert_eq!(
1800 words("FREQ=YEARLY;BYMONTH=5;BYDAY=-1SU").as_deref(),
1801 Some("Every year: M5, last SU")
1802 );
1803 assert_eq!(words("FREQ=MONTHLY;BYDAY=-2FR"), None);
1804 assert_eq!(words("FREQ=WEEKLY;BYDAY=2TU"), None);
1805 assert_eq!(words("FREQ=HOURLY"), None);
1806 for raw in [
1807 "FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1",
1808 "FREQ=MONTHLY;BYMONTH=6;BYMONTHDAY=1",
1809 "FREQ=WEEKLY;BYMONTHDAY=15",
1810 "FREQ=DAILY;BYMONTHDAY=1",
1811 "FREQ=YEARLY;BYMONTHDAY=15",
1812 "FREQ=YEARLY;BYDAY=MO",
1813 "FREQ=YEARLY;BYYEARDAY=100",
1814 "FREQ=YEARLY;BYWEEKNO=20;BYDAY=MO",
1815 "FREQ=DAILY;BYHOUR=9,17",
1816 "FREQ=WEEKLY;X-FOO=1",
1817 "FREQ=MONTHLY;BYDAY=MO",
1818 "FREQ=YEARLY;BYMONTH=3;BYDAY=SU",
1819 "FREQ=DAILY;BYDAY=MO,TU",
1820 "FREQ=MONTHLY;BYDAY=FR;BYMONTHDAY=13",
1821 "FREQ=MONTHLY;BYDAY=1FR;BYMONTHDAY=1,2,3",
1822 ] {
1823 assert_eq!(words(raw), None, "{raw}");
1824 }
1825 assert_eq!(
1826 words("FREQ=WEEKLY;WKST=SU;BYDAY=MO;").as_deref(),
1827 Some("Every week: MO")
1828 );
1829 }
1830
1831 #[test]
1832 fn a_bar_hidden_on_a_busy_day_splits() {
1833 let week = grid_start(2026, 10, 1);
1834 // Two bars over Mon–Wed; three timed events on Tuesday only.
1835 let mut spans = vec![all_day(week, week + 2), all_day(week, week + 2)];
1836 spans.extend((0..3).map(|i| timed(week + 1, 600 + i * 60)));
1837 let l = layout_week(&spans, week, 2);
1838 // Tuesday overflows, so its last line (the second bar) shows "+4".
1839 assert_eq!(l.more, [0, 4, 0, 0, 0, 0, 0]);
1840 let second: Vec<_> = l.pieces.iter().filter(|p| p.item == 1).collect();
1841 assert_eq!(second.len(), 2);
1842 assert_eq!(
1843 (second[0].col, second[0].len, second[0].ends),
1844 (0, 1, false)
1845 );
1846 assert_eq!(
1847 (second[1].col, second[1].len, second[1].starts),
1848 (2, 1, false)
1849 );
1850 }
1851
1852 #[test]
1853 fn times_on_each_day() {
1854 let s = Span {
1855 first: 10,
1856 last: 12,
1857 all_day: false,
1858 start_min: 22 * 60,
1859 end_min: 9 * 60,
1860 };
1861 assert_eq!(when_on(&s, 10), When::From(1320));
1862 assert_eq!(when_on(&s, 11), When::AllDay);
1863 assert_eq!(when_on(&s, 12), When::Until(540));
1864 // Ending at midnight, the last day runs to its end.
1865 let s = Span { end_min: 1440, ..s };
1866 assert_eq!(when_on(&s, 12), When::AllDay);
1867 assert_eq!(when_on(&timed(5, 600), 5), When::Range(600, 660));
1868 assert_eq!(when_on(&all_day(5, 5), 5), When::AllDay);
1869 }
1870
1871 #[test]
1872 fn links_are_found_in_text() {
1873 assert_eq!(
1874 split_links("See https://example.com/a?b=1. Or http://x.org)"),
1875 [
1876 ("See ".to_string(), false),
1877 ("https://example.com/a?b=1".to_string(), true),
1878 (". Or ".to_string(), false),
1879 ("http://x.org".to_string(), true),
1880 (")".to_string(), false),
1881 ]
1882 );
1883 assert_eq!(
1884 split_links("no links, javascript:alert(1)"),
1885 [("no links, javascript:alert(1)".to_string(), false)]
1886 );
1887 }
1888
1889 #[test]
1890 fn links_need_a_host_and_keep_balanced_brackets() {
1891 assert_eq!(
1892 split_links("a https:// b"),
1893 [("a https:// b".to_string(), false)]
1894 );
1895 assert_eq!(
1896 split_links("(https://en.wikipedia.org/wiki/Foo_(bar))"),
1897 [
1898 ("(".to_string(), false),
1899 ("https://en.wikipedia.org/wiki/Foo_(bar)".to_string(), true),
1900 (")".to_string(), false),
1901 ]
1902 );
1903 }
1904
1905 #[test]
1906 fn more_counts_the_hidden_items_of_a_column() {
1907 let week = grid_start(2026, 10, 1);
1908 let d = |c: i64| week + c;
1909 let five: Vec<Span> = (0..5).map(|n| timed(d(1), 60 * n)).collect();
1910 let l = layout_week(&five, week, 3);
1911 assert_eq!(l.more, [0, 3, 0, 0, 0, 0, 0]);
1912 }
1913
1914 #[test]
1915 fn a_lone_item_on_a_low_line_gets_no_more() {
1916 let week = grid_start(2026, 10, 1);
1917 let d = |c: i64| week + c;
1918 let spans = [all_day(d(0), d(4)), timed(d(6), 600)];
1919 let l = layout_week(&spans, week, 3);
1920 assert_eq!(l.more, [0; 7]);
1921 }
1922
1923 #[test]
1924 fn a_bar_pushed_below_the_lines_is_counted_where_it_hides() {
1925 let week = grid_start(2026, 10, 1);
1926 let d = |c: i64| week + c;
1927 // Three bars fill the lines of days 0 to 4, so the fourth lands on line 3.
1928 let mut spans = vec![all_day(d(0), d(4)); 3];
1929 spans.push(all_day(d(4), d(6)));
1930 let l = layout_week(&spans, week, 3);
1931 assert_eq!(l.more, [0, 0, 0, 0, 2, 1, 1]);
1932 }
1933
1934 #[test]
1935 fn midnight_end_is_the_next_day() {
1936 let mut s = timed(5, 600);
1937 s.last = 6;
1938 s.end_min = 1440;
1939 assert_eq!(s.end_at(), (7, 0));
1940 s.end_min = 540;
1941 assert_eq!(s.end_at(), (6, 540));
1942 }
1943
1944 #[test]
1945 fn opened_round_trips() {
1946 let o = Opened {
1947 collection_id: 7,
1948 recurrence_id: Some("2026-10-05T08:00:00Z".into()),
1949 name: "a/b.ics".into(),
1950 };
1951 assert_eq!(Opened::parse(&o.param()), Some(o));
1952 let series = Opened {
1953 collection_id: -1,
1954 recurrence_id: None,
1955 name: "x.ics".into(),
1956 };
1957 assert_eq!(Opened::parse(&series.param()), Some(series));
1958 }
1959}
1960