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