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::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 /// A bar across days, not a line with a time.
91 fn is_bar(&self) -> bool {
92 self.all_day || self.first != self.last
93 }
94
95 fn covers(&self, day: i64) -> bool {
96 self.first <= day && day <= self.last
97 }
98}
99
100/// One piece of an instance in a week row. An instance hidden on some of
101/// its days by the "+N more" line becomes several pieces.
102#[derive(Clone, Debug, PartialEq)]
103pub struct Piece {
104 /// Index into the spans given to [`layout_week`].
105 pub item: usize,
106 pub col: usize,
107 pub len: usize,
108 pub line: usize,
109 /// The instance starts in this piece, rather than continuing into it.
110 pub starts: bool,
111 pub ends: bool,
112}
113
114#[derive(Clone, Debug, PartialEq)]
115pub struct WeekLayout {
116 pub pieces: Vec<Piece>,
117 /// Per day: how many instances the "+N more" line stands for.
118 pub more: [usize; 7],
119}
120
121/// Place a week's instances on `lines` lines. Bars come first, longer ones
122/// on top, then timed instances by start. A day with more instances than
123/// lines gives its last line to "+N more".
124pub fn layout_week(spans: &[Span], week: i64, lines: usize) -> WeekLayout {
125 let mut items: Vec<(usize, usize, usize)> = spans
126 .iter()
127 .enumerate()
128 .filter(|(_, s)| s.first <= week + 6 && s.last >= week)
129 .map(|(i, s)| {
130 let c0 = (s.first.max(week) - week) as usize;
131 let c1 = (s.last.min(week + 6) - week) as usize;
132 (i, c0, c1)
133 })
134 .collect();
135 items.sort_by_key(|&(i, c0, c1)| {
136 let s = &spans[i];
137 (!s.is_bar(), c0, usize::MAX - (c1 - c0), s.start_min, i)
138 });
139 let mut used: Vec<[bool; 7]> = Vec::new();
140 let mut placed = Vec::with_capacity(items.len());
141 let mut count = [0usize; 7];
142 for &(i, c0, c1) in &items {
143 let line = (0..)
144 .find(|&l| {
145 used.get(l)
146 .is_none_or(|row| !row[c0..=c1].iter().any(|&u| u))
147 })
148 .unwrap_or(0);
149 if used.len() <= line {
150 used.resize(line + 1, [false; 7]);
151 }
152 for c in c0..=c1 {
153 used[line][c] = true;
154 count[c] += 1;
155 }
156 placed.push((i, c0, c1, line));
157 }
158 let limit = |c: usize| {
159 if count[c] <= lines {
160 lines
161 } else {
162 lines.saturating_sub(1)
163 }
164 };
165 let mut pieces = Vec::new();
166 for &(i, c0, c1, line) in &placed {
167 let mut run: Option<usize> = None;
168 for c in c0..=c1 + 1 {
169 if c <= c1 && line < limit(c) {
170 run.get_or_insert(c);
171 } else if let Some(start) = run.take() {
172 let s = &spans[i];
173 pieces.push(Piece {
174 item: i,
175 col: start,
176 len: c - start,
177 line,
178 starts: start == c0 && s.first >= week,
179 ends: c - 1 == c1 && s.last <= week + 6,
180 });
181 }
182 }
183 }
184 let more = std::array::from_fn(|c| {
185 placed
186 .iter()
187 .filter(|&&(_, c0, c1, line)| c0 <= c && c <= c1 && line >= limit(c))
188 .count()
189 });
190 WeekLayout { pieces, more }
191}
192
193/// What an instance's time looks like on one of its days.
194#[derive(Clone, Copy, Debug, PartialEq)]
195pub enum When {
196 AllDay,
197 At(u32),
198 Range(u32, u32),
199 From(u32),
200 Until(u32),
201}
202
203pub fn when_on(s: &Span, day: i64) -> When {
204 if s.all_day {
205 When::AllDay
206 } else if s.first == s.last && s.start_min == s.end_min {
207 When::At(s.start_min)
208 } else if s.first == s.last {
209 When::Range(s.start_min, s.end_min)
210 } else if day == s.first {
211 When::From(s.start_min)
212 } else if day == s.last {
213 When::Until(s.end_min)
214 } else {
215 When::AllDay
216 }
217}
218
219/// Split plain text into runs, `true` for an `http(s)://` link. A trailing
220/// period or closing bracket belongs to the sentence, not the link.
221pub fn split_links(text: &str) -> Vec<(String, bool)> {
222 let mut out = Vec::new();
223 let mut rest = text;
224 while let Some(at) = ["https://", "http://"]
225 .iter()
226 .filter_map(|p| rest.find(p))
227 .min()
228 {
229 let end = rest[at..]
230 .find(|c: char| c.is_whitespace() || matches!(c, '<' | '>' | '"'))
231 .map_or(rest.len(), |e| at + e);
232 let link = rest[at..end].trim_end_matches(['.', ',', ';', ':', '!', '?', ')']);
233 let link_end = at + link.len();
234 if at > 0 {
235 out.push((rest[..at].to_string(), false));
236 }
237 out.push((link.to_string(), true));
238 rest = &rest[link_end..];
239 }
240 if !rest.is_empty() {
241 out.push((rest.to_string(), false));
242 }
243 out
244}
245
246// ---------------------------------------------------------------------------
247// Browser dates
248// ---------------------------------------------------------------------------
249
250fn js_day(d: &js_sys::Date) -> i64 {
251 days_from_civil(d.get_full_year() as i32, d.get_month() + 1, d.get_date())
252}
253
254fn day_date(day: i64) -> js_sys::Date {
255 let (y, m, d) = civil_from_days(day);
256 js_sys::Date::new_with_year_month_day(y as u32, m as i32 - 1, d as i32)
257}
258
259fn today() -> i64 {
260 js_day(&js_sys::Date::new_0())
261}
262
263/// Local midnight of `day` as RFC 3339 UTC, for the instances endpoint.
264fn day_rfc3339(day: i64) -> String {
265 day_date(day).to_iso_string().into()
266}
267
268fn span_of(i: &PimInstance) -> Span {
269 let s = js_sys::Date::new(&i.start.as_str().into());
270 let e = js_sys::Date::new(&i.end.as_str().into());
271 let first = js_day(&s);
272 let start_min = s.get_hours() * 60 + s.get_minutes();
273 let (last, end_min) = if e.get_time() > s.get_time() {
274 let last = js_day(&js_sys::Date::new(&JsValue::from_f64(e.get_time() - 1.0)));
275 let end_min = if js_day(&e) > last {
276 1440
277 } else {
278 e.get_hours() * 60 + e.get_minutes()
279 };
280 (last, end_min)
281 } else {
282 (first, start_min)
283 };
284 Span {
285 first,
286 last: last.max(first),
287 all_day: i.all_day,
288 start_min,
289 end_min,
290 }
291}
292
293fn fmt_min(day: i64, min: u32) -> String {
294 let (y, m, d) = civil_from_days(day);
295 let t = js_sys::Date::new_with_year_month_day_hr_min(
296 y as u32,
297 m as i32 - 1,
298 d as i32,
299 (min / 60) as i32,
300 (min % 60) as i32,
301 );
302 intl(&t, &[("hour", "2-digit"), ("minute", "2-digit")])
303}
304
305fn fmt_when(w: When, day: i64) -> String {
306 match w {
307 When::AllDay => i18n::t(k::PIM_ALL_DAY).to_string(),
308 When::At(m) => fmt_min(day, m),
309 When::Range(a, b) => format!("{} – {}", fmt_min(day, a), fmt_min(day, b)),
310 When::From(m) => i18n::t_fmt(k::PIM_FROM_TIME, &fmt_min(day, m)),
311 When::Until(m) => i18n::t_fmt(k::PIM_UNTIL_TIME, &fmt_min(day, m)),
312 }
313}
314
315fn fmt_day_long(day: i64) -> String {
316 intl(
317 &day_date(day),
318 &[
319 ("weekday", "long"),
320 ("day", "numeric"),
321 ("month", "long"),
322 ("year", "numeric"),
323 ],
324 )
325}
326
327fn fmt_day_short(day: i64) -> String {
328 intl(
329 &day_date(day),
330 &[
331 ("weekday", "short"),
332 ("day", "numeric"),
333 ("month", "short"),
334 ("year", "numeric"),
335 ],
336 )
337}
338
339/// The full time of an instance, for its details.
340fn fmt_span(s: &Span) -> String {
341 match (s.all_day, s.first == s.last) {
342 (true, true) => fmt_day_short(s.first),
343 (true, false) => format!("{} – {}", fmt_day_short(s.first), fmt_day_short(s.last)),
344 (false, true) => format!(
345 "{} · {}",
346 fmt_day_short(s.first),
347 fmt_when(when_on(s, s.first), s.first)
348 ),
349 (false, false) => format!(
350 "{} {} – {} {}",
351 fmt_day_short(s.first),
352 fmt_min(s.first, s.start_min),
353 fmt_day_short(s.last),
354 fmt_min(s.last, s.end_min)
355 ),
356 }
357}
358
359// ---------------------------------------------------------------------------
360// The view
361// ---------------------------------------------------------------------------
362
363/// Lines per day cell in the month grid, the last one shared with
364/// "+N more".
365const LINES: usize = 4;
366
367#[derive(Clone, Copy, Debug, PartialEq)]
368enum CalView {
369 Month(i32, u32),
370 Agenda,
371 Invitations,
372}
373
374impl CalView {
375 fn from_path(path: &[String]) -> Self {
376 match path.first().map(String::as_str) {
377 Some("agenda") => CalView::Agenda,
378 Some("invitations") => CalView::Invitations,
379 _ => path
380 .get(1)
381 .and_then(|ym| {
382 let (y, m) = ym.split_once('-')?;
383 let (y, m) = (y.parse().ok()?, m.parse().ok()?);
384 (1..=12).contains(&m).then_some(CalView::Month(y, m))
385 })
386 .unwrap_or_else(|| {
387 let (y, m, _) = civil_from_days(today());
388 CalView::Month(y, m)
389 }),
390 }
391 }
392
393 fn path(self) -> Vec<String> {
394 match self {
395 CalView::Month(y, m) => vec!["month".into(), format!("{y:04}-{m:02}")],
396 CalView::Agenda => vec!["agenda".into()],
397 CalView::Invitations => vec!["invitations".into()],
398 }
399 }
400}
401
402fn go(view: CalView) {
403 navigate(&Location {
404 section: Section::Calendar,
405 path: view.path(),
406 ..Location::root()
407 });
408}
409
410/// The event whose details are open, as the URL names it:
411/// `{collection}/{recurrence id or -}/{name}`.
412#[derive(Clone, Debug, PartialEq)]
413struct Opened {
414 collection_id: i64,
415 recurrence_id: Option<String>,
416 name: String,
417}
418
419impl Opened {
420 fn of(i: &PimInstance) -> Self {
421 Opened {
422 collection_id: i.collection_id,
423 recurrence_id: i.recurrence_id.clone(),
424 name: i.name.clone(),
425 }
426 }
427
428 fn param(&self) -> String {
429 format!(
430 "{}/{}/{}",
431 self.collection_id,
432 self.recurrence_id.as_deref().unwrap_or("-"),
433 self.name
434 )
435 }
436
437 fn parse(s: &str) -> Option<Self> {
438 let mut it = s.splitn(3, '/');
439 let collection_id = it.next()?.parse().ok()?;
440 let rid = it.next()?;
441 let name = it.next()?.to_string();
442 Some(Opened {
443 collection_id,
444 recurrence_id: (rid != "-").then(|| rid.to_string()),
445 name,
446 })
447 }
448
449 fn open(&self) {
450 router::set_open(&self.param());
451 }
452}
453
454/// An invitation as the instance it names, for the day and time helpers.
455fn inv_instance(v: &PimInvitation) -> PimInstance {
456 PimInstance {
457 collection_id: v.collection_id,
458 name: v.name.clone(),
459 uid: v.uid.clone(),
460 recurrence_id: v.recurrence_id.clone(),
461 start: v.start.clone(),
462 end: v.end.clone(),
463 all_day: v.all_day,
464 component: "VEVENT".into(),
465 summary: v.summary.clone(),
466 location: v.location.clone(),
467 status: None,
468 transparent: false,
469 has_attendees: true,
470 partstat: None,
471 organizer: None,
472 }
473}
474
475/// An instance with what the views derive from it.
476#[derive(Clone)]
477struct Shown {
478 inst: PimInstance,
479 span: Span,
480 color: String,
481}
482
483#[component]
484pub fn CalendarMain(
485 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
486 hidden: RwSignal<HashSet<i64>>,
487 loc: ReadSignal<Location>,
488 /// 0 is Sunday. From the profile.
489 week_start: Signal<u32>,
490) -> impl IntoView {
491 let view = Memo::new(move |_| loc.with(|l| CalView::from_path(&l.path)));
492 let opened = Memo::new(move |_| loc.with(|l| l.open.as_deref().and_then(Opened::parse)));
493 // Bumped after an answer or an import: every list refetches.
494 let tick = RwSignal::new(0u32);
495
496 let month = RwSignal::new(Option::<Result<api::PimInstances, String>>::None);
497 let month_seq = StoredValue::new(0u32);
498 let month_key = StoredValue::new(None::<(i32, u32)>);
499 Effect::new(move |_| {
500 tick.track();
501 collections.track();
502 let CalView::Month(y, m) = view.get() else {
503 return;
504 };
505 // Another month's instances would land on the wrong days.
506 if month_key.get_value() != Some((y, m)) {
507 month_key.set_value(Some((y, m)));
508 month.set(None);
509 }
510 let start = grid_start(y, m, week_start.get());
511 let seq = month_seq.get_value() + 1;
512 month_seq.set_value(seq);
513 spawn_local(async move {
514 let r = api::pim_instances(
515 &day_rfc3339(start),
516 &day_rfc3339(start + GRID_DAYS),
517 &browser_tz(),
518 )
519 .await;
520 if month_seq.get_value() == seq {
521 month.set(Some(r.map_err(|e| e.to_string())));
522 }
523 });
524 });
525
526 let agenda = RwSignal::new(Option::<Result<api::PimInstances, String>>::None);
527 let agenda_seq = StoredValue::new(0u32);
528 Effect::new(move |_| {
529 tick.track();
530 collections.track();
531 if view.get() != CalView::Agenda {
532 return;
533 }
534 let from = today();
535 let seq = agenda_seq.get_value() + 1;
536 agenda_seq.set_value(seq);
537 spawn_local(async move {
538 let r = api::pim_instances(
539 &day_rfc3339(from),
540 &day_rfc3339(from + AGENDA_DAYS),
541 &browser_tz(),
542 )
543 .await;
544 if agenda_seq.get_value() == seq {
545 agenda.set(Some(r.map_err(|e| e.to_string())));
546 }
547 });
548 });
549
550 let invitations = RwSignal::new(Option::<Result<Vec<PimInvitation>, String>>::None);
551 Effect::new(move |_| {
552 tick.track();
553 spawn_local(async move {
554 let r = api::pim_invitations(&browser_tz()).await;
555 let _ = invitations.try_set(Some(r.map_err(|e| e.to_string())));
556 });
557 });
558 let refresh = Callback::new(move |_| tick.update(|t| *t += 1));
559
560 let colors = Memo::new(move |_| {
561 collections.with(|c| {
562 c.iter()
563 .flatten()
564 .map(|c| (c.id, safe_color(c.color.as_deref())))
565 .collect::<HashMap<_, _>>()
566 })
567 });
568 let shown = move |list: &api::PimInstances| -> Vec<Shown> {
569 let colors = colors.get();
570 hidden.with(|h| {
571 list.instances
572 .iter()
573 .filter(|i| !h.contains(&i.collection_id))
574 .map(|i| Shown {
575 span: span_of(i),
576 color: colors
577 .get(&i.collection_id)
578 .cloned()
579 .unwrap_or_else(|| safe_color(None)),
580 inst: i.clone(),
581 })
582 .collect()
583 })
584 };
585
586 // PageUp / PageDown turn the month, unless typing or a dialog is open.
587 owned_window_listener(leptos::ev::keydown, move |ev| {
588 let step = match ev.key().as_str() {
589 "PageUp" => -1,
590 "PageDown" => 1,
591 _ => return,
592 };
593 let busy = web_sys::window()
594 .and_then(|w| w.document())
595 .and_then(|d| {
596 d.query_selector("dialog[open], input:focus, textarea:focus")
597 .ok()
598 })
599 .flatten()
600 .is_some();
601 if let (CalView::Month(y, m), false) = (view.get_untracked(), busy) {
602 ev.prevent_default();
603 let (y, m) = add_months(y, m, step);
604 go(CalView::Month(y, m));
605 }
606 });
607
608 let pending = move || {
609 invitations.with(|i| match i {
610 Some(Ok(list)) => list.len(),
611 _ => 0,
612 })
613 };
614 let toolbar = move || {
615 let v = view.get();
616 let title = match v {
617 CalView::Month(y, m) => intl(
618 &js_sys::Date::new_with_year_month_day(y as u32, m as i32 - 1, 1),
619 &[("month", "long"), ("year", "numeric")],
620 ),
621 CalView::Agenda => i18n::t(k::PIM_UPCOMING).to_string(),
622 CalView::Invitations => i18n::t(k::PIM_INVITATIONS).to_string(),
623 };
624 let nav = match v {
625 CalView::Month(y, m) => Some(view! {
626 <div class="cal-nav">
627 <button
628 class="icon-btn icon-btn-sm"
629 title=i18n::t(k::PIM_PREV_MONTH)
630 aria-label=i18n::t(k::PIM_PREV_MONTH)
631 on:click=move |_| {
632 let (y, m) = add_months(y, m, -1);
633 go(CalView::Month(y, m));
634 }
635 >
636 {icon_svg(IconName::ChevronRight, "ic-btn flip")}
637 </button>
638 <button
639 class="btn btn-sm"
640 on:click=move |_| {
641 let (y, m, _) = civil_from_days(today());
642 go(CalView::Month(y, m));
643 }
644 >
645 {i18n::t(k::PIM_TODAY)}
646 </button>
647 <button
648 class="icon-btn icon-btn-sm"
649 title=i18n::t(k::PIM_NEXT_MONTH)
650 aria-label=i18n::t(k::PIM_NEXT_MONTH)
651 on:click=move |_| {
652 let (y, m) = add_months(y, m, 1);
653 go(CalView::Month(y, m));
654 }
655 >
656 {icon_svg(IconName::ChevronRight, "ic-btn")}
657 </button>
658 </div>
659 }),
660 _ => None,
661 };
662 let this_month = match v {
663 CalView::Month(..) => v,
664 _ => {
665 let (y, m, _) = civil_from_days(today());
666 CalView::Month(y, m)
667 }
668 };
669 view! {
670 <div class="cal-toolbar">
671 {nav}
672 <h2 class="cal-title">{title}</h2>
673 <div class="cal-views" role="tablist">
674 <button
675 role="tab"
676 class="cal-view-btn"
677 class:active=matches!(v, CalView::Month(..))
678 aria-selected=matches!(v, CalView::Month(..)).to_string()
679 on:click=move |_| go(this_month)
680 >
681 {i18n::t(k::PIM_MONTH)}
682 </button>
683 <button
684 role="tab"
685 class="cal-view-btn"
686 class:active=v == CalView::Agenda
687 aria-selected=(v == CalView::Agenda).to_string()
688 on:click=move |_| go(CalView::Agenda)
689 >
690 {i18n::t(k::PIM_AGENDA)}
691 </button>
692 <button
693 role="tab"
694 class="cal-view-btn"
695 class:active=v == CalView::Invitations
696 aria-selected=(v == CalView::Invitations).to_string()
697 on:click=move |_| go(CalView::Invitations)
698 >
699 {i18n::t(k::PIM_INVITATIONS)}
700 {move || (pending() > 0).then(|| view! {
701 <span class="cal-badge">{pending()}</span>
702 })}
703 </button>
704 </div>
705 </div>
706 }
707 };
708
709 let body = move || match view.get() {
710 CalView::Month(y, m) => view! {
711 <MonthView y=y m=m week_start=week_start.get() data=month shown=shown/>
712 }
713 .into_any(),
714 CalView::Agenda => view! {
715 <AgendaView data=agenda shown=shown/>
716 }
717 .into_any(),
718 CalView::Invitations => view! {
719 <InvitationsView data=invitations collections=collections on_replied=refresh/>
720 }
721 .into_any(),
722 };
723
724 // The times of the open event come from whichever list holds it.
725 let times = move |o: &Opened| -> Option<Span> {
726 let find = |list: &Option<Result<api::PimInstances, String>>| {
727 list.as_ref().and_then(|r| r.as_ref().ok()).and_then(|l| {
728 l.instances
729 .iter()
730 .find(|i| Opened::of(i) == *o)
731 .map(span_of)
732 })
733 };
734 month
735 .with_untracked(find)
736 .or_else(|| agenda.with_untracked(find))
737 .or_else(|| {
738 invitations.with_untracked(|i| {
739 i.as_ref()
740 .and_then(|r| r.as_ref().ok())
741 .and_then(|l| {
742 l.iter().find(|v| {
743 v.collection_id == o.collection_id
744 && v.name == o.name
745 && v.recurrence_id == o.recurrence_id
746 })
747 })
748 .map(|v| span_of(&inv_instance(v)))
749 })
750 })
751 };
752 view! {
753 <div class="cal">
754 {toolbar}
755 {body}
756 </div>
757 {move || opened.get().map(|o| {
758 let span = times(&o);
759 view! {
760 <EventDialog
761 target=o
762 span=span
763 collections=collections
764 on_replied=refresh
765 on_close=Callback::new(move |_| router::close_open())
766 />
767 }
768 })}
769 }
770}
771
772fn truncated_note(list: &api::PimInstances) -> Option<impl IntoView + use<>> {
773 list.truncated.then(|| {
774 view! { <p class="cal-truncated">{i18n::t(k::PIM_TRUNCATED)}</p> }
775 })
776}
777
778fn loading_or_error(
779 data: &Option<Result<api::PimInstances, String>>,
780) -> Result<api::PimInstances, AnyView> {
781 match data {
782 None => Err(view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any()),
783 Some(Err(e)) => Err(view! { <div class="card error-card">{e.clone()}</div> }.into_any()),
784 Some(Ok(list)) => Ok(list.clone()),
785 }
786}
787
788/// One line of a day list: time, color and title.
789fn day_row(s: &Shown, day: i64) -> impl IntoView + use<> {
790 let o = Opened::of(&s.inst);
791 let when = fmt_when(when_on(&s.span, day), day);
792 let title = s
793 .inst
794 .summary
795 .clone()
796 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
797 let cancelled = struck(&s.inst);
798 let location = s.inst.location.clone();
799 view! {
800 <button class="cal-row" class:cal-cancelled=cancelled on:click=move |_| o.open()>
801 <span class="cal-row-time">{when}</span>
802 <span class="cal-dot" style=format!("--c: {}", s.color)></span>
803 <span class="cal-row-main">
804 <span class="cal-row-title">{title}</span>
805 {location.map(|l| view! { <span class="cal-row-meta">{l}</span> })}
806 </span>
807 </button>
808 }
809}
810
811#[component]
812fn MonthView(
813 y: i32,
814 m: u32,
815 week_start: u32,
816 data: RwSignal<Option<Result<api::PimInstances, String>>>,
817 shown: impl Fn(&api::PimInstances) -> Vec<Shown> + Copy + Send + Sync + 'static,
818) -> impl IntoView {
819 let start = grid_start(y, m, week_start);
820 let now = today();
821 let in_month = move |d: i64| {
822 let (yy, mm, _) = civil_from_days(d);
823 yy == y && mm == m
824 };
825 let selected = RwSignal::new(if in_month(now) {
826 now
827 } else {
828 days_from_civil(y, m, 1)
829 });
830 let list_ref: NodeRef<leptos::html::Div> = NodeRef::new();
831 let pick = move |day: i64| {
832 selected.set(day);
833 if let Some(el) = list_ref.get_untracked() {
834 let opts = web_sys::ScrollIntoViewOptions::new();
835 opts.set_block(web_sys::ScrollLogicalPosition::Nearest);
836 el.scroll_into_view_with_scroll_into_view_options(&opts);
837 }
838 };
839 let head = (0..7)
840 .map(|i| {
841 view! {
842 <div class="cal-head-day">{intl(&day_date(start + i), &[("weekday", "short")])}</div>
843 }
844 })
845 .collect::<Vec<_>>();
846 view! {
847 <div class="cal-month">
848 <div class="cal-head">{head}</div>
849 {move || data.with(|d| match loading_or_error(d) {
850 Err(v) => v,
851 Ok(list) => {
852 let items = shown(&list);
853 let spans: Vec<Span> = items.iter().map(|s| s.span).collect();
854 let weeks = (0..6)
855 .map(|w| {
856 let week = start + w * 7;
857 let layout = layout_week(&spans, week, LINES);
858 let cells = (0..7usize)
859 .map(|c| {
860 let day = week + c as i64;
861 let (_, _, dnum) = civil_from_days(day);
862 let dots: Vec<String> = items
863 .iter()
864 .filter(|s| s.span.covers(day))
865 .take(3)
866 .map(|s| s.color.clone())
867 .collect();
868 let label = fmt_day_long(day);
869 view! {
870 <button
871 class="cal-cell"
872 class:cal-out=!in_month(day)
873 class:cal-today=day == now
874 class:cal-sel=move || selected.get() == day
875 style=format!("grid-column: {}", c + 1)
876 aria-label=label
877 on:click=move |_| pick(day)
878 >
879 <span class="cal-num">{dnum}</span>
880 <span class="cal-dots">
881 {dots
882 .into_iter()
883 .map(|c| view! { <span class="cal-dot" style=format!("--c: {c}")></span> })
884 .collect::<Vec<_>>()}
885 </span>
886 </button>
887 }
888 })
889 .collect::<Vec<_>>();
890 let pieces = layout
891 .pieces
892 .iter()
893 .map(|p| {
894 let s = &items[p.item];
895 let o = Opened::of(&s.inst);
896 let bar = s.span.is_bar();
897 let title = s
898 .inst
899 .summary
900 .clone()
901 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
902 let time = (!bar).then(|| fmt_min(s.span.first, s.span.start_min));
903 let cancelled = struck(&s.inst);
904 let tip = match &time {
905 Some(t) => format!("{t} {title}"),
906 None => title.clone(),
907 };
908 view! {
909 <button
910 class="cal-item"
911 class:cal-bar=bar
912 class:cal-chip=!bar
913 class:cal-cont-l=!p.starts
914 class:cal-cont-r=!p.ends
915 class:cal-cancelled=cancelled
916 style=format!(
917 "grid-column: {} / span {}; grid-row: {}; --c: {}",
918 p.col + 1,
919 p.len,
920 p.line + 2,
921 s.color
922 )
923 title=tip
924 on:click=move |_| o.open()
925 >
926 {(!bar).then(|| view! { <span class="cal-dot"></span> })}
927 {time.map(|t| view! { <span class="cal-time">{t}</span> })}
928 <span class="cal-item-title">{title}</span>
929 </button>
930 }
931 })
932 .collect::<Vec<_>>();
933 let more = layout
934 .more
935 .iter()
936 .enumerate()
937 .filter(|&(_, &n)| n > 0)
938 .map(|(c, &n)| {
939 let day = week + c as i64;
940 view! {
941 <button
942 class="cal-more"
943 style=format!("grid-column: {}; grid-row: {}", c + 1, LINES + 1)
944 on:click=move |_| pick(day)
945 >
946 {i18n::t_fmt(k::PIM_MORE_N, &n.to_string())}
947 </button>
948 }
949 })
950 .collect::<Vec<_>>();
951 view! {
952 <div class="cal-week" style=format!("--lines: {LINES}")>
953 {cells}
954 {pieces}
955 {more}
956 </div>
957 }
958 })
959 .collect::<Vec<_>>();
960 let day_list = move || {
961 let day = selected.get();
962 let rows: Vec<_> = items
963 .iter()
964 .filter(|s| s.span.covers(day))
965 .map(|s| day_row(s, day))
966 .collect();
967 view! {
968 <h3 class="cal-day-title">{fmt_day_long(day)}</h3>
969 {if rows.is_empty() {
970 view! { <p class="muted cal-pad">{i18n::t(k::PIM_NO_EVENTS_DAY)}</p> }.into_any()
971 } else {
972 view! { <div class="cal-rows">{rows}</div> }.into_any()
973 }}
974 }
975 };
976 view! {
977 {truncated_note(&list)}
978 <div class="cal-weeks">{weeks}</div>
979 <div class="cal-day" node_ref=list_ref>{day_list}</div>
980 }
981 .into_any()
982 }
983 })}
984 </div>
985 }
986}
987
988/// The agenda shows today and the days after it. The month view is for
989/// browsing further.
990const AGENDA_DAYS: i64 = 7;
991
992#[component]
993fn AgendaView(
994 data: RwSignal<Option<Result<api::PimInstances, String>>>,
995 shown: impl Fn(&api::PimInstances) -> Vec<Shown> + Copy + Send + Sync + 'static,
996) -> impl IntoView {
997 view! {
998 <div class="cal-agenda">
999 {move || data.with(|d| match loading_or_error(d) {
1000 Err(v) => v,
1001 Ok(list) => {
1002 let items = shown(&list);
1003 let from = today();
1004 let groups: Vec<_> = (from..from + AGENDA_DAYS)
1005 .filter_map(|day| {
1006 let rows: Vec<_> = items
1007 .iter()
1008 .filter(|s| s.span.covers(day))
1009 .map(|s| day_row(s, day))
1010 .collect();
1011 (!rows.is_empty()).then(|| view! {
1012 <section class="cal-agenda-day">
1013 <h3 class="cal-day-title" class:cal-day-today=day == from>
1014 {fmt_day_long(day)}
1015 </h3>
1016 <div class="cal-rows">{rows}</div>
1017 </section>
1018 })
1019 })
1020 .collect();
1021 let empty = groups.is_empty().then(|| view! {
1022 <div class="empty-state">
1023 {icon_svg(IconName::Calendar, "empty-glyph")}
1024 <p class="muted">{i18n::t(k::PIM_NO_EVENTS_AGENDA)}</p>
1025 </div>
1026 });
1027 view! {
1028 {truncated_note(&list)}
1029 {empty}
1030 {groups}
1031 }
1032 .into_any()
1033 }
1034 })}
1035 </div>
1036 }
1037}
1038
1039/// Answer an invitation, then refresh the lists.
1040fn reply(
1041 toast: ToastMsg,
1042 collection_id: i64,
1043 name: String,
1044 recurrence_id: Option<String>,
1045 partstat: &'static str,
1046 done: Callback<()>,
1047) {
1048 spawn_local(async move {
1049 let body = PimReply {
1050 collection_id,
1051 name,
1052 recurrence_id,
1053 partstat: partstat.to_string(),
1054 tz: Some(browser_tz()),
1055 };
1056 match api::pim_reply(body).await {
1057 Ok(_) => {
1058 show(toast, i18n::t(k::PIM_REPLIED));
1059 done.run(());
1060 }
1061 Err(e) => show_error(toast, e.to_string()),
1062 }
1063 });
1064}
1065
1066/// Accept, maybe, decline. `current` marks the answer already given.
1067fn reply_buttons(
1068 current: Option<String>,
1069 on: impl Fn(&'static str) + Clone + 'static,
1070) -> impl IntoView {
1071 [
1072 ("ACCEPTED", k::PIM_ACCEPT),
1073 ("TENTATIVE", k::PIM_TENTATIVE),
1074 ("DECLINED", k::PIM_DECLINE),
1075 ]
1076 .map(|(ps, label)| {
1077 let on = on.clone();
1078 let active = current.as_deref() == Some(ps);
1079 view! {
1080 <button
1081 class="btn btn-sm"
1082 class:btn-primary=active
1083 aria-pressed=active.to_string()
1084 on:click=move |_| on(ps)
1085 >
1086 {i18n::t(label)}
1087 </button>
1088 }
1089 })
1090 .into_iter()
1091 .collect::<Vec<_>>()
1092}
1093
1094#[component]
1095fn InvitationsView(
1096 data: RwSignal<Option<Result<Vec<PimInvitation>, String>>>,
1097 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
1098 on_replied: Callback<()>,
1099) -> impl IntoView {
1100 let toast = use_context::<ToastMsg>().expect("toast context");
1101 view! {
1102 <div class="cal-invitations">
1103 {move || match data.get() {
1104 None => view! { <p class="muted cal-pad">{i18n::t(k::LOADING)}</p> }.into_any(),
1105 Some(Err(e)) => view! { <div class="card error-card">{e}</div> }.into_any(),
1106 Some(Ok(list)) if list.is_empty() => view! {
1107 <div class="empty-state">
1108 {icon_svg(IconName::Calendar, "empty-glyph")}
1109 <p class="muted">{i18n::t(k::PIM_NO_INVITATIONS)}</p>
1110 </div>
1111 }
1112 .into_any(),
1113 Some(Ok(list)) => {
1114 let names: HashMap<i64, String> = collections.with_untracked(|c| {
1115 c.iter().flatten().map(|c| (c.id, display_name(c))).collect()
1116 });
1117 list.into_iter()
1118 .map(|inv| {
1119 let o = Opened {
1120 collection_id: inv.collection_id,
1121 recurrence_id: inv.recurrence_id.clone(),
1122 name: inv.name.clone(),
1123 };
1124 let span = span_of(&inv_instance(&inv));
1125 let series = inv.recurring && inv.recurrence_id.is_none();
1126 let mut meta = vec![fmt_span(&span)];
1127 match (&inv.rrule, &inv.recurrence_id) {
1128 (Some(r), None) => meta.push(rrule_text(&with_start_day(r, span.first))),
1129 (None, Some(_)) => meta.push(i18n::t(k::PIM_THIS_EVENT).to_string()),
1130 _ => {}
1131 }
1132 if let Some(n) = names.get(&inv.collection_id) {
1133 meta.push(n.clone());
1134 }
1135 let organizer = inv.organizer.as_ref().map(|p| {
1136 p.name.clone().unwrap_or_else(|| {
1137 p.address.trim_start_matches("mailto:").to_string()
1138 })
1139 });
1140 let title = inv
1141 .summary
1142 .clone()
1143 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
1144 let (id, name, rid) =
1145 (inv.collection_id, inv.name.clone(), inv.recurrence_id.clone());
1146 let open = o.clone();
1147 view! {
1148 <div class="cal-inv">
1149 <button class="cal-inv-main" on:click=move |_| open.open()>
1150 <span class="cal-inv-title">{title}</span>
1151 <span class="cal-row-meta">{meta.join(" · ")}</span>
1152 {inv.location.clone().map(|l| view! { <span class="cal-row-meta">{l}</span> })}
1153 {organizer.map(|n| view! {
1154 <span class="cal-row-meta">{i18n::t_fmt(k::PIM_FROM_ORGANIZER, &n)}</span>
1155 })}
1156 {series.then(|| view! {
1157 <span class="cal-row-meta">{i18n::t(k::PIM_INV_SERIES_HINT)}</span>
1158 })}
1159 </button>
1160 <div class="cal-inv-actions">
1161 {reply_buttons(None, move |ps| {
1162 reply(toast, id, name.clone(), rid.clone(), ps, on_replied)
1163 })}
1164 </div>
1165 </div>
1166 }
1167 })
1168 .collect::<Vec<_>>()
1169 .into_any()
1170 }
1171 }}
1172 </div>
1173 }
1174}
1175
1176fn partstat_label(ps: Option<&str>) -> (&'static str, &'static str) {
1177 match ps {
1178 Some("ACCEPTED") => (k::PIM_PS_ACCEPTED, "ps-accepted"),
1179 Some("DECLINED") => (k::PIM_PS_DECLINED, "ps-declined"),
1180 Some("TENTATIVE") => (k::PIM_PS_TENTATIVE, "ps-tentative"),
1181 Some("DELEGATED") => (k::PIM_PS_DELEGATED, "ps-muted"),
1182 _ => (k::PIM_PS_NEEDS_ACTION, "ps-muted"),
1183 }
1184}
1185
1186/// `FREQ=WEEKLY;INTERVAL=2;BYDAY=TU` as words; an unknown FREQ stays raw.
1187fn rrule_text(rule: &str) -> String {
1188 let part = |key: &str| {
1189 rule.split(';')
1190 .find_map(|p| p.strip_prefix(key)?.strip_prefix('='))
1191 };
1192 let n = part("INTERVAL")
1193 .and_then(|n| n.parse::<u32>().ok())
1194 .unwrap_or(1);
1195 let keys = match part("FREQ") {
1196 Some("DAILY") => (k::PIM_RRULE_DAILY, k::PIM_RRULE_DAILY_N),
1197 Some("WEEKLY") => (k::PIM_RRULE_WEEKLY, k::PIM_RRULE_WEEKLY_N),
1198 Some("MONTHLY") => (k::PIM_RRULE_MONTHLY, k::PIM_RRULE_MONTHLY_N),
1199 Some("YEARLY") => (k::PIM_RRULE_YEARLY, k::PIM_RRULE_YEARLY_N),
1200 _ => return rule.to_string(),
1201 };
1202 let base = match n {
1203 1 => i18n::t(keys.0).to_string(),
1204 n => i18n::t_fmt(keys.1, &n.to_string()),
1205 };
1206 // Plain weekdays of a weekly rule, e.g. "Every week: Tue, Thu".
1207 let days: Vec<String> = match part("FREQ") {
1208 Some("WEEKLY") => part("BYDAY")
1209 .unwrap_or_default()
1210 .split(',')
1211 .filter_map(weekday_name)
1212 .collect(),
1213 _ => Vec::new(),
1214 };
1215 match days.is_empty() {
1216 true => base,
1217 false => format!("{base}: {}", days.join(", ")),
1218 }
1219}
1220
1221/// A weekly rule without BYDAY repeats on its start's weekday. Naming it
1222/// makes "Every week" read "Every week: Tue".
1223fn with_start_day(rule: &str, first: i64) -> String {
1224 let weekly = rule.split(';').any(|p| p == "FREQ=WEEKLY");
1225 if !weekly || rule.split(';').any(|p| p.starts_with("BYDAY=")) {
1226 return rule.to_string();
1227 }
1228 let code = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"][weekday(first) as usize];
1229 format!("{rule};BYDAY={code}")
1230}
1231
1232/// `TU` as the locale's short weekday name. Numbered days (`2TU`) are skipped.
1233fn weekday_name(code: &str) -> Option<String> {
1234 let offset = ["MO", "TU", "WE", "TH", "FR", "SA", "SU"]
1235 .iter()
1236 .position(|&d| d == code)?;
1237 // 2024-01-01 was a Monday.
1238 let date = js_sys::Date::new_with_year_month_day(2024, 0, 1 + offset as i32);
1239 Some(intl(&date, &[("weekday", "short")]))
1240}
1241
1242fn person_name(p: &api_types::PimPerson) -> String {
1243 p.name
1244 .clone()
1245 .unwrap_or_else(|| p.address.trim_start_matches("mailto:").to_string())
1246}
1247
1248/// Text with its web links clickable, for a `white-space: pre-wrap` block.
1249pub fn linkified(text: &str) -> impl IntoView + use<> {
1250 split_links(text)
1251 .into_iter()
1252 .map(|(t, link)| match link {
1253 true => {
1254 let href = t.clone();
1255 view! { <a href=href target="_blank" rel="noopener noreferrer">{t}</a> }.into_any()
1256 }
1257 false => t.into_any(),
1258 })
1259 .collect::<Vec<_>>()
1260}
1261
1262#[component]
1263fn EventDialog(
1264 target: Opened,
1265 span: Option<Span>,
1266 collections: ReadSignal<Option<Vec<PimCollectionInfo>>>,
1267 on_replied: Callback<()>,
1268 on_close: Callback<()>,
1269) -> impl IntoView {
1270 let toast = use_context::<ToastMsg>().expect("toast context");
1271 let detail = RwSignal::new(Option::<Result<PimEventDetail, String>>::None);
1272 let load = {
1273 let t = target.clone();
1274 move || {
1275 let t = t.clone();
1276 spawn_local(async move {
1277 let r = api::pim_object(
1278 t.collection_id,
1279 &t.name,
1280 t.recurrence_id.as_deref(),
1281 &browser_tz(),
1282 )
1283 .await;
1284 let r = match r {
1285 Ok(PimObjectDetail::Event(e)) => Ok(e),
1286 Ok(PimObjectDetail::Contact(_)) => Err(i18n::t(k::PIM_NOT_EVENT).to_string()),
1287 Err(e) => Err(e.to_string()),
1288 };
1289 let _ = detail.try_set(Some(r));
1290 });
1291 }
1292 };
1293 load();
1294 // For one instance of a series: answer it alone, or the whole series.
1295 let only_this = RwSignal::new(true);
1296 let collection = collections.with_untracked(|c| {
1297 c.iter()
1298 .flatten()
1299 .find(|c| c.id == target.collection_id)
1300 .map(|c| (display_name(c), safe_color(c.color.as_deref())))
1301 });
1302 let body = move || match detail.get() {
1303 None => view! { <p class="muted">{i18n::t(k::LOADING)}</p> }.into_any(),
1304 Some(Err(e)) => view! { <p class="form-error">{e}</p> }.into_any(),
1305 Some(Ok(d)) => {
1306 let title = d
1307 .summary
1308 .clone()
1309 .unwrap_or_else(|| i18n::t(k::PIM_NO_TITLE).to_string());
1310 let mine = d
1311 .attendees
1312 .iter()
1313 .find(|a| a.is_owner)
1314 .and_then(|a| a.partstat.clone());
1315 let series = target.recurrence_id.is_some() && d.rrule.is_some();
1316 let rid = target.recurrence_id.clone();
1317 let (id, name) = (target.collection_id, target.name.clone());
1318 let load = load.clone();
1319 let answer = move |ps: &'static str| {
1320 let rid = if only_this.get_untracked() {
1321 rid.clone()
1322 } else {
1323 None
1324 };
1325 let load = load.clone();
1326 reply(
1327 toast,
1328 id,
1329 name.clone(),
1330 rid,
1331 ps,
1332 Callback::new(move |_| {
1333 load();
1334 on_replied.run(());
1335 }),
1336 );
1337 };
1338 let url = d
1339 .url
1340 .clone()
1341 .filter(|u| u.starts_with("https://") || u.starts_with("http://"));
1342 view! {
1343 <h2 class="modal-title cal-detail-title" class:cal-cancelled=d.status.as_deref() == Some("CANCELLED")>
1344 {title}
1345 </h2>
1346 {(d.status.as_deref() == Some("CANCELLED")).then(|| view! {
1347 <p class="cal-flag">{i18n::t(k::PIM_CANCELLED)}</p>
1348 })}
1349 <dl class="cal-facts">
1350 {span.map(|s| view! {
1351 <dt>{i18n::t(k::PIM_WHEN)}</dt>
1352 <dd>{fmt_span(&s)}</dd>
1353 })}
1354 {d.rrule.clone().map(|r| view! {
1355 <dt>{i18n::t(k::PIM_REPEATS)}</dt>
1356 <dd title=r.clone()>{rrule_text(&r)}</dd>
1357 })}
1358 {d.location.clone().map(|l| view! {
1359 <dt>{i18n::t(k::PIM_LOCATION)}</dt>
1360 <dd class="cal-pre">{linkified(&l)}</dd>
1361 })}
1362 {collection.clone().map(|(n, c)| view! {
1363 <dt>{i18n::t(k::PIM_CALENDAR)}</dt>
1364 <dd><span class="cal-dot" style=format!("--c: {c}")></span>" "{n}</dd>
1365 })}
1366 {d.organizer.as_ref().map(|p| view! {
1367 <dt>{i18n::t(k::PIM_ORGANIZER)}</dt>
1368 <dd>{person_name(p)}</dd>
1369 })}
1370 {url.map(|u| {
1371 let href = u.clone();
1372 view! {
1373 <dt>{i18n::t(k::PIM_LINK)}</dt>
1374 <dd><a href=href target="_blank" rel="noopener noreferrer">{u}</a></dd>
1375 }
1376 })}
1377 {(!d.categories.is_empty()).then(|| view! {
1378 <dt>{i18n::t(k::PIM_CATEGORIES)}</dt>
1379 <dd>{d.categories.join(", ")}</dd>
1380 })}
1381 </dl>
1382 {(!d.attendees.is_empty()).then(|| view! {
1383 <h3 class="pim-section-title">{i18n::t(k::PIM_ATTENDEES)}</h3>
1384 <ul class="cal-attendees">
1385 {d.attendees
1386 .iter()
1387 .map(|a| {
1388 let (label, class) = partstat_label(a.partstat.as_deref());
1389 let optional = a.role.as_deref() == Some("OPT-PARTICIPANT");
1390 view! {
1391 <li>
1392 <span class="cal-att-name" title=a.person.address.clone()>
1393 {person_name(&a.person)}
1394 </span>
1395 {optional.then(|| view! { <span class="muted">{i18n::t(k::PIM_OPTIONAL)}</span> })}
1396 <span class=format!("ps-badge {class}")>{i18n::t(label)}</span>
1397 </li>
1398 }
1399 })
1400 .collect::<Vec<_>>()}
1401 </ul>
1402 })}
1403 {d.description.clone().filter(|t| !t.trim().is_empty()).map(|t| view! {
1404 <div class="cal-desc cal-pre">{linkified(&t)}</div>
1405 })}
1406 {d.can_reply.then(|| view! {
1407 <section class="cal-reply">
1408 <h3 class="pim-section-title">{i18n::t(k::PIM_YOUR_ANSWER)}</h3>
1409 {series.then(|| view! {
1410 <div class="cal-scope" role="radiogroup">
1411 <label class="check-row">
1412 <input
1413 type="radio"
1414 name="cal-scope"
1415 prop:checked=move || only_this.get()
1416 on:change=move |_| only_this.set(true)
1417 />
1418 {i18n::t(k::PIM_THIS_EVENT)}
1419 </label>
1420 <label class="check-row">
1421 <input
1422 type="radio"
1423 name="cal-scope"
1424 prop:checked=move || !only_this.get()
1425 on:change=move |_| only_this.set(false)
1426 />
1427 {i18n::t(k::PIM_ALL_EVENTS)}
1428 </label>
1429 </div>
1430 })}
1431 <div class="cal-inv-actions">{reply_buttons(mine, answer)}</div>
1432 </section>
1433 })}
1434 }
1435 .into_any()
1436 }
1437 };
1438 view! {
1439 <Modal class="pim-modal cal-detail" on_close=on_close>
1440 {body}
1441 <div class="modal-actions">
1442 <button class="btn" on:click=move |_| on_close.run(())>{i18n::t(k::CLOSE)}</button>
1443 </div>
1444 </Modal>
1445 }
1446}
1447
1448#[cfg(test)]
1449mod tests {
1450 use super::*;
1451
1452 fn day(y: i32, m: u32, d: u32) -> i64 {
1453 days_from_civil(y, m, d)
1454 }
1455
1456 fn timed(first: i64, start_min: u32) -> Span {
1457 Span {
1458 first,
1459 last: first,
1460 all_day: false,
1461 start_min,
1462 end_min: start_min + 60,
1463 }
1464 }
1465
1466 fn all_day(first: i64, last: i64) -> Span {
1467 Span {
1468 first,
1469 last,
1470 all_day: true,
1471 start_min: 0,
1472 end_min: 1440,
1473 }
1474 }
1475
1476 #[test]
1477 fn civil_days_round_trip() {
1478 assert_eq!(day(1970, 1, 1), 0);
1479 assert_eq!(day(2000, 3, 1), 11017);
1480 for z in [-800_000, -1, 0, 59, 60, 11016, 20_000, 2_000_000] {
1481 let (y, m, d) = civil_from_days(z);
1482 assert_eq!(day(y, m, d), z);
1483 }
1484 assert_eq!(civil_from_days(day(2024, 2, 29)), (2024, 2, 29));
1485 // 2026-10-01 is a Thursday.
1486 assert_eq!(weekday(day(2026, 10, 1)), 4);
1487 }
1488
1489 #[test]
1490 fn grid_starts_on_the_week_start() {
1491 // October 2026 starts on a Thursday.
1492 let sunday = grid_start(2026, 10, 0);
1493 let monday = grid_start(2026, 10, 1);
1494 assert_eq!(civil_from_days(sunday), (2026, 9, 27));
1495 assert_eq!(civil_from_days(monday), (2026, 9, 28));
1496 assert_eq!(weekday(monday), 1);
1497 assert_eq!(civil_from_days(grid_start(2026, 10, 6)), (2026, 9, 26));
1498 // A month starting on the week start begins the grid itself, and
1499 // six weeks always cover the whole month.
1500 assert_eq!(grid_start(2026, 6, 1), day(2026, 6, 1));
1501 for (y, m) in [(2026, 2), (2026, 8), (2027, 1)] {
1502 for ws in [0, 1, 6] {
1503 let s = grid_start(y, m, ws);
1504 let (ny, nm) = add_months(y, m, 1);
1505 assert!(s <= day(y, m, 1) && day(ny, nm, 1) <= s + GRID_DAYS);
1506 }
1507 }
1508 assert_eq!(add_months(2026, 12, 1), (2027, 1));
1509 assert_eq!(add_months(2026, 1, -1), (2025, 12));
1510 }
1511
1512 #[test]
1513 fn bars_split_across_weeks() {
1514 // Saturday to Tuesday, in weeks starting on Monday.
1515 let week1 = grid_start(2026, 10, 1);
1516 let span = all_day(day(2026, 10, 3), day(2026, 10, 6));
1517 let a = layout_week(&[span], week1, 4);
1518 assert_eq!(
1519 a.pieces,
1520 [Piece {
1521 item: 0,
1522 col: 5,
1523 len: 2,
1524 line: 0,
1525 starts: true,
1526 ends: false
1527 }]
1528 );
1529 let b = layout_week(&[span], week1 + 7, 4);
1530 assert_eq!(
1531 b.pieces,
1532 [Piece {
1533 item: 0,
1534 col: 0,
1535 len: 2,
1536 line: 0,
1537 starts: false,
1538 ends: true
1539 }]
1540 );
1541 assert_eq!(a.more, [0; 7]);
1542 }
1543
1544 #[test]
1545 fn busy_days_share_the_last_line_with_more() {
1546 let week = grid_start(2026, 10, 1);
1547 let mon = week;
1548 // Five timed events on Monday; a bar Monday to Wednesday.
1549 let mut spans: Vec<Span> = (0..5).map(|i| timed(mon, 600 + i * 30)).collect();
1550 spans.push(all_day(mon, mon + 2));
1551 let l = layout_week(&spans, week, 3);
1552 // Monday has six instances on three lines: two shown, four behind
1553 // "+4 more". The bar comes first, so it stays visible.
1554 assert_eq!(l.more, [4, 0, 0, 0, 0, 0, 0]);
1555 let bar = l.pieces.iter().find(|p| p.item == 5).unwrap();
1556 assert_eq!((bar.col, bar.len, bar.line), (0, 3, 0));
1557 assert_eq!(l.pieces.iter().filter(|p| p.col == 0).count(), 2);
1558 // Timed events keep their order.
1559 let first_chip = l.pieces.iter().find(|p| p.item != 5).unwrap();
1560 assert_eq!(first_chip.item, 0);
1561 }
1562
1563 #[test]
1564 fn a_weekly_rule_names_its_start_day() {
1565 let friday = days_from_civil(2026, 10, 2);
1566 assert_eq!(
1567 with_start_day("FREQ=WEEKLY", friday),
1568 "FREQ=WEEKLY;BYDAY=FR"
1569 );
1570 assert_eq!(
1571 with_start_day("FREQ=WEEKLY;BYDAY=MO", friday),
1572 "FREQ=WEEKLY;BYDAY=MO"
1573 );
1574 assert_eq!(with_start_day("FREQ=DAILY", friday), "FREQ=DAILY");
1575 }
1576
1577 #[test]
1578 fn a_bar_hidden_on_a_busy_day_splits() {
1579 let week = grid_start(2026, 10, 1);
1580 // Two bars over Mon–Wed; three timed events on Tuesday only.
1581 let mut spans = vec![all_day(week, week + 2), all_day(week, week + 2)];
1582 spans.extend((0..3).map(|i| timed(week + 1, 600 + i * 60)));
1583 let l = layout_week(&spans, week, 2);
1584 // Tuesday overflows, so its last line (the second bar) shows "+4".
1585 assert_eq!(l.more, [0, 4, 0, 0, 0, 0, 0]);
1586 let second: Vec<_> = l.pieces.iter().filter(|p| p.item == 1).collect();
1587 assert_eq!(second.len(), 2);
1588 assert_eq!(
1589 (second[0].col, second[0].len, second[0].ends),
1590 (0, 1, false)
1591 );
1592 assert_eq!(
1593 (second[1].col, second[1].len, second[1].starts),
1594 (2, 1, false)
1595 );
1596 }
1597
1598 #[test]
1599 fn times_on_each_day() {
1600 let s = Span {
1601 first: 10,
1602 last: 12,
1603 all_day: false,
1604 start_min: 22 * 60,
1605 end_min: 9 * 60,
1606 };
1607 assert_eq!(when_on(&s, 10), When::From(1320));
1608 assert_eq!(when_on(&s, 11), When::AllDay);
1609 assert_eq!(when_on(&s, 12), When::Until(540));
1610 assert_eq!(when_on(&timed(5, 600), 5), When::Range(600, 660));
1611 assert_eq!(when_on(&all_day(5, 5), 5), When::AllDay);
1612 }
1613
1614 #[test]
1615 fn links_are_found_in_text() {
1616 assert_eq!(
1617 split_links("See https://example.com/a?b=1. Or http://x.org)"),
1618 [
1619 ("See ".to_string(), false),
1620 ("https://example.com/a?b=1".to_string(), true),
1621 (". Or ".to_string(), false),
1622 ("http://x.org".to_string(), true),
1623 (")".to_string(), false),
1624 ]
1625 );
1626 assert_eq!(
1627 split_links("no links, javascript:alert(1)"),
1628 [("no links, javascript:alert(1)".to_string(), false)]
1629 );
1630 }
1631
1632 #[test]
1633 fn opened_round_trips() {
1634 let o = Opened {
1635 collection_id: 7,
1636 recurrence_id: Some("2026-10-05T08:00:00Z".into()),
1637 name: "a/b.ics".into(),
1638 };
1639 assert_eq!(Opened::parse(&o.param()), Some(o));
1640 let series = Opened {
1641 collection_id: -1,
1642 recurrence_id: None,
1643 name: "x.ics".into(),
1644 };
1645 assert_eq!(Opened::parse(&series.param()), Some(series));
1646 }
1647}
1648