Skip to main content

lumen_dioxus/content/
schedule.rs

1//! `Agenda`, `Schedule`, and the schedule model from `lumen-core`: slots, moves, conflicts,
2//! recurrence, and resizing.
3//!
4//! The model works on ISO 8601 strings like `lumen-core` does. It accepts `YYYY-MM-DD` and
5//! `YYYY-MM-DDTHH:MM[:SS[.fff]]` with an optional `Z` or `±HH:MM` offset. JavaScript reads a
6//! date-time without an offset in the browser's local time zone; this port has no time zone data,
7//! so it reads such values as UTC. Pass explicit offsets when the difference matters.
8
9use dioxus::prelude::*;
10
11use crate::class::{Glass, compose};
12
13/// Props for [`Agenda`].
14#[derive(Props, Clone, PartialEq)]
15pub struct AgendaProps {
16    /// Glass intensity.
17    #[props(default, into)]
18    pub glass: Glass,
19    /// Extra classes appended after the Lumen classes.
20    #[props(into)]
21    pub class: Option<String>,
22    /// Any other `<section>` or global attribute. Name it with `aria_label`.
23    #[props(extends = GlobalAttributes, extends = section)]
24    pub attributes: Vec<Attribute>,
25    /// A `header` and an `ol` or `ul` of agenda items.
26    pub children: Element,
27}
28
29/// A day or event agenda: a header and a list of timed items.
30#[component]
31pub fn Agenda(props: AgendaProps) -> Element {
32    let glass = props.glass.class("ui-agenda");
33    let class = compose([Some("ui-agenda"), glass.as_deref(), props.class.as_deref()]);
34
35    rsx! {
36        section { class, ..props.attributes, {props.children} }
37    }
38}
39
40/// Props for [`Schedule`].
41#[derive(Props, Clone, PartialEq)]
42pub struct ScheduleProps {
43    /// Glass intensity.
44    #[props(default, into)]
45    pub glass: Glass,
46    /// Extra classes appended after the Lumen classes.
47    #[props(into)]
48    pub class: Option<String>,
49    /// Any other `<section>` or global attribute. Name it with `aria_label`.
50    #[props(extends = GlobalAttributes, extends = section)]
51    pub attributes: Vec<Attribute>,
52    /// The schedule grid: elements marked `data-ui-schedule-grid`, `data-ui-schedule-slot`, and
53    /// `data-ui-schedule-event`. Build them from [`create_schedule_slots`].
54    pub children: Element,
55}
56
57/// A resource or week schedule grid. Lay out its slots with [`create_schedule_slots`] and update
58/// events with [`move_schedule_event`] and [`resize_schedule_events`].
59#[component]
60pub fn Schedule(props: ScheduleProps) -> Element {
61    let glass = props.glass.class("ui-schedule");
62    let class = compose([
63        Some("ui-schedule"),
64        glass.as_deref(),
65        props.class.as_deref(),
66    ]);
67
68    rsx! {
69        section { class, "data-ui-schedule": "true", ..props.attributes, {props.children} }
70    }
71}
72
73/// One event on a [`Schedule`].
74#[derive(Clone, Debug, Default, PartialEq, Eq)]
75pub struct ScheduleEvent {
76    /// Unique id.
77    pub id: String,
78    /// Title shown on the event.
79    pub title: String,
80    /// ISO 8601 start, such as `2026-12-01T09:00:00Z`.
81    pub start: String,
82    /// ISO 8601 end, no earlier than `start`.
83    pub end: String,
84    /// The [`ScheduleResource`] that the event books, if any.
85    pub resource_id: Option<String>,
86}
87
88/// A bookable resource, such as a room or a person.
89#[derive(Clone, Debug, Default, PartialEq, Eq)]
90pub struct ScheduleResource {
91    /// Unique id that events reference.
92    pub id: String,
93    /// Display label.
94    pub label: String,
95}
96
97/// One cell of a schedule grid: a date, optionally a resource, and the events that start in it.
98#[derive(Clone, Debug, Default, PartialEq, Eq)]
99pub struct ScheduleSlot {
100    /// The date prefix, such as `2026-12-01`.
101    pub date: String,
102    /// Events whose start begins with `date` (and that book `resource`, when set).
103    pub events: Vec<ScheduleEvent>,
104    /// The resource column, when the grid has resources.
105    pub resource: Option<ScheduleResource>,
106}
107
108/// Two events that overlap on the same resource.
109#[derive(Clone, Debug, Default, PartialEq, Eq)]
110pub struct ScheduleConflict {
111    /// The earlier event in the input order.
112    pub a: ScheduleEvent,
113    /// The later event in the input order.
114    pub b: ScheduleEvent,
115}
116
117/// Which edge [`resize_schedule_event`] moves.
118#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
119pub enum ScheduleResizeEdge {
120    /// Moves the start.
121    Start,
122    /// Moves the end.
123    #[default]
124    End,
125}
126
127/// Options for [`resize_schedule_event`].
128#[derive(Clone, Debug, Default, PartialEq)]
129pub struct ScheduleResizeOptions {
130    /// The edge to move. Defaults to the end.
131    pub edge: ScheduleResizeEdge,
132    /// Earliest allowed date-time for the moved edge.
133    pub min: Option<String>,
134    /// Latest allowed date-time for the moved edge.
135    pub max: Option<String>,
136    /// Snap step in minutes. Defaults to 15; values below 1 snap to whole minutes.
137    pub snap_minutes: Option<f64>,
138}
139
140/// Why a schedule operation failed, mirroring the errors `lumen-core` throws.
141#[derive(Clone, Copy, Debug, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum ScheduleError {
144    /// A date-time could not be parsed. Holds the field name.
145    InvalidDateTime(&'static str),
146    /// The event has an invalid date-time or starts after it ends.
147    InvalidRange,
148    /// The minimum bound is later than the maximum bound.
149    InvalidBounds,
150    /// The snap step is not finite.
151    InvalidSnap,
152    /// A result falls outside the supported date-time range.
153    OutOfRange,
154    /// The recurrence count is larger than [`SCHEDULE_MAX_RECURRENCES`].
155    InvalidCount,
156}
157
158impl std::fmt::Display for ScheduleError {
159    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
160        match self {
161            Self::InvalidDateTime(field) => {
162                write!(formatter, "Schedule {field} must be a valid date-time.")
163            }
164            Self::InvalidRange => formatter.write_str(
165                "Schedule event must have valid date-times with start no later than end.",
166            ),
167            Self::InvalidBounds => formatter.write_str("Schedule minimum cannot exceed maximum."),
168            Self::InvalidSnap => formatter.write_str("Schedule snap minutes must be finite."),
169            Self::OutOfRange => {
170                formatter.write_str("Schedule date-time exceeds the supported range.")
171            }
172            Self::InvalidCount => write!(
173                formatter,
174                "Schedule recurrence count must be at most {SCHEDULE_MAX_RECURRENCES}."
175            ),
176        }
177    }
178}
179
180impl std::error::Error for ScheduleError {}
181
182/// The most occurrences [`expand_recurring_schedule_event`] creates, a safety bound that the
183/// JavaScript version does not need because it fails on allocation instead.
184pub const SCHEDULE_MAX_RECURRENCES: usize = 100_000;
185
186const MS_PER_MINUTE: i64 = 60_000;
187const MS_PER_DAY: i64 = 86_400_000;
188/// The ECMAScript time value limit.
189const MAX_TIME_MS: i64 = 8_640_000_000_000_000;
190const MIN_EVENT_DURATION_MS: i64 = MS_PER_MINUTE;
191const MAX_DATE_TIME_LENGTH: usize = 64;
192
193fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
194    let year = if month <= 2 { year - 1 } else { year };
195    let era = year.div_euclid(400);
196    let year_of_era = year - era * 400;
197    let month_index = (month + 9) % 12;
198    let day_of_year = (153 * month_index + 2) / 5 + day - 1;
199    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
200
201    era * 146_097 + day_of_era - 719_468
202}
203
204fn civil_from_days(days: i64) -> (i64, i64, i64) {
205    let days = days + 719_468;
206    let era = days.div_euclid(146_097);
207    let day_of_era = days - era * 146_097;
208    let year_of_era =
209        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
210    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
211    let month_index = (5 * day_of_year + 2) / 153;
212    let day = day_of_year - (153 * month_index + 2) / 5 + 1;
213    let month = if month_index < 10 {
214        month_index + 3
215    } else {
216        month_index - 9
217    };
218    let year = year_of_era + era * 400 + i64::from(month <= 2);
219
220    (year, month, day)
221}
222
223fn is_leap_year(year: i64) -> bool {
224    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
225}
226
227fn days_in_month(year: i64, month: i64) -> i64 {
228    match month {
229        2 if is_leap_year(year) => 29,
230        2 => 28,
231        4 | 6 | 9 | 11 => 30,
232        _ => 31,
233    }
234}
235
236/// Reads `count` ASCII digits starting at `index`.
237fn read_digits(bytes: &[u8], index: usize, count: usize) -> Option<i64> {
238    let digits = bytes.get(index..index + count)?;
239    let mut value = 0_i64;
240
241    for digit in digits {
242        if !digit.is_ascii_digit() {
243            return None;
244        }
245
246        value = value * 10 + i64::from(digit - b'0');
247    }
248
249    Some(value)
250}
251
252/// Parses an ISO 8601 date or date-time into milliseconds since the Unix epoch, with one linear
253/// scan. Returns `None` for anything else.
254pub(crate) fn parse_schedule_time(value: &str) -> Option<i64> {
255    let bytes = value.trim().as_bytes();
256
257    if bytes.len() > MAX_DATE_TIME_LENGTH {
258        return None;
259    }
260
261    let year = read_digits(bytes, 0, 4)?;
262    (bytes.get(4) == Some(&b'-')).then_some(())?;
263    let month = read_digits(bytes, 5, 2)?;
264    (bytes.get(7) == Some(&b'-')).then_some(())?;
265    let day = read_digits(bytes, 8, 2)?;
266
267    if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
268        return None;
269    }
270
271    let date_ms = days_from_civil(year, month, day) * MS_PER_DAY;
272
273    if bytes.len() == 10 {
274        return Some(date_ms);
275    }
276
277    (bytes.get(10) == Some(&b'T')).then_some(())?;
278    let hour = read_digits(bytes, 11, 2)?;
279    (bytes.get(13) == Some(&b':')).then_some(())?;
280    let minute = read_digits(bytes, 14, 2)?;
281    let mut index = 16;
282    let mut second = 0;
283    let mut millisecond = 0;
284
285    if bytes.get(index) == Some(&b':') {
286        second = read_digits(bytes, index + 1, 2)?;
287        index += 3;
288
289        if bytes.get(index) == Some(&b'.') {
290            index += 1;
291            let start = index;
292
293            while bytes.get(index).is_some_and(u8::is_ascii_digit) {
294                if index - start < 3 {
295                    millisecond = millisecond * 10 + i64::from(bytes[index] - b'0');
296                }
297
298                index += 1;
299            }
300
301            if index == start {
302                return None;
303            }
304
305            for _ in (index - start)..3 {
306                millisecond *= 10;
307            }
308        }
309    }
310
311    let valid_time = (hour < 24 && minute < 60 && second < 60)
312        || (hour == 24 && minute == 0 && second == 0 && millisecond == 0);
313
314    if !valid_time {
315        return None;
316    }
317
318    let offset_minutes = match bytes.get(index) {
319        None => 0,
320        Some(b'Z') if index + 1 == bytes.len() => 0,
321        Some(sign @ (b'+' | b'-')) if index + 6 == bytes.len() => {
322            let offset_hour = read_digits(bytes, index + 1, 2)?;
323            (bytes.get(index + 3) == Some(&b':')).then_some(())?;
324            let offset_minute = read_digits(bytes, index + 4, 2)?;
325
326            if offset_hour > 23 || offset_minute > 59 {
327                return None;
328            }
329
330            let total = offset_hour * 60 + offset_minute;
331
332            if *sign == b'+' { total } else { -total }
333        }
334        Some(_) => return None,
335    };
336
337    Some(
338        date_ms + hour * 3_600_000 + minute * MS_PER_MINUTE + second * 1000 + millisecond
339            - offset_minutes * MS_PER_MINUTE,
340    )
341}
342
343/// Formats milliseconds since the epoch like `Date.prototype.toISOString`.
344pub(crate) fn format_schedule_time(time: i64) -> Option<String> {
345    if time.abs() > MAX_TIME_MS {
346        return None;
347    }
348
349    let days = time.div_euclid(MS_PER_DAY);
350    let in_day = time.rem_euclid(MS_PER_DAY);
351    let (year, month, day) = civil_from_days(days);
352    let year_text = if (0..=9999).contains(&year) {
353        format!("{year:04}")
354    } else if year < 0 {
355        format!("-{:06}", -year)
356    } else {
357        format!("+{year:06}")
358    };
359
360    Some(format!(
361        "{year_text}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
362        in_day / 3_600_000,
363        in_day % 3_600_000 / MS_PER_MINUTE,
364        in_day % MS_PER_MINUTE / 1000,
365        in_day % 1000
366    ))
367}
368
369fn schedule_range(event: &ScheduleEvent) -> Option<(i64, i64)> {
370    let start = parse_schedule_time(&event.start)?;
371    let end = parse_schedule_time(&event.end)?;
372
373    (start <= end).then_some((start, end))
374}
375
376fn require_time(value: &str, field: &'static str) -> Result<i64, ScheduleError> {
377    parse_schedule_time(value).ok_or(ScheduleError::InvalidDateTime(field))
378}
379
380/// Groups events into one slot per date (and per resource, when `resources` is not empty).
381///
382/// An event belongs to a slot when its `start` begins with the slot date and, with resources,
383/// when it books that resource.
384pub fn create_schedule_slots(
385    dates: &[String],
386    events: &[ScheduleEvent],
387    resources: &[ScheduleResource],
388) -> Vec<ScheduleSlot> {
389    let slot = |date: &String, resource: Option<&ScheduleResource>| ScheduleSlot {
390        date: date.clone(),
391        events: events
392            .iter()
393            .filter(|event| {
394                event.start.starts_with(date.as_str())
395                    && resource.is_none_or(|resource| {
396                        event.resource_id.as_deref() == Some(resource.id.as_str())
397                    })
398            })
399            .cloned()
400            .collect(),
401        resource: resource.cloned(),
402    };
403
404    dates
405        .iter()
406        .flat_map(|date| {
407            if resources.is_empty() {
408                vec![slot(date, None)]
409            } else {
410                resources
411                    .iter()
412                    .map(|resource| slot(date, Some(resource)))
413                    .collect()
414            }
415        })
416        .collect()
417}
418
419/// Returns `events` with the event `event_id` moved to a new start and end, and to `resource_id`
420/// when it is set and not empty.
421pub fn move_schedule_event(
422    events: &[ScheduleEvent],
423    event_id: &str,
424    next_start: &str,
425    next_end: &str,
426    resource_id: Option<&str>,
427) -> Vec<ScheduleEvent> {
428    events
429        .iter()
430        .map(|event| {
431            if event.id != event_id {
432                return event.clone();
433            }
434
435            let mut moved = event.clone();
436            moved.start = next_start.to_string();
437            moved.end = next_end.to_string();
438
439            if let Some(resource) = resource_id.filter(|resource| !resource.is_empty()) {
440                moved.resource_id = Some(resource.to_string());
441            }
442
443            moved
444        })
445        .collect()
446}
447
448/// Repeats an event `count` times, `interval_days` apart. The first copy keeps the id; later ones
449/// get `{id}-2`, `{id}-3`, and so on. Dates are written in UTC ISO format.
450///
451/// # Errors
452///
453/// Fails when the event range is invalid, `count` exceeds [`SCHEDULE_MAX_RECURRENCES`], or an
454/// occurrence leaves the supported date-time range.
455pub fn expand_recurring_schedule_event(
456    event: &ScheduleEvent,
457    count: usize,
458    interval_days: i64,
459) -> Result<Vec<ScheduleEvent>, ScheduleError> {
460    if count > SCHEDULE_MAX_RECURRENCES {
461        return Err(ScheduleError::InvalidCount);
462    }
463
464    let (start, end) = schedule_range(event).ok_or(ScheduleError::InvalidRange)?;
465    let mut occurrences = Vec::with_capacity(count);
466
467    for index in 0..count {
468        let shift = i64::try_from(index)
469            .ok()
470            .and_then(|index| index.checked_mul(interval_days))
471            .and_then(|days| days.checked_mul(MS_PER_DAY))
472            .ok_or(ScheduleError::OutOfRange)?;
473        let next_start = start.checked_add(shift).ok_or(ScheduleError::OutOfRange)?;
474        let next_end = end.checked_add(shift).ok_or(ScheduleError::OutOfRange)?;
475        let mut occurrence = event.clone();
476
477        occurrence.start = format_schedule_time(next_start).ok_or(ScheduleError::OutOfRange)?;
478        occurrence.end = format_schedule_time(next_end).ok_or(ScheduleError::OutOfRange)?;
479
480        if index > 0 {
481            occurrence.id = format!("{}-{}", event.id, index + 1);
482        }
483
484        occurrences.push(occurrence);
485    }
486
487    Ok(occurrences)
488}
489
490/// Whether two different events overlap on the same resource. Events on different resources never
491/// overlap; an event with an invalid range overlaps everything on its resource.
492pub fn schedule_events_overlap(a: &ScheduleEvent, b: &ScheduleEvent) -> bool {
493    let booked = |event: &ScheduleEvent| event.resource_id.clone().filter(|id| !id.is_empty());
494
495    if a.id == b.id {
496        return false;
497    }
498
499    if let (Some(first), Some(second)) = (booked(a), booked(b))
500        && first != second
501    {
502        return false;
503    }
504
505    match (schedule_range(a), schedule_range(b)) {
506        (Some(first), Some(second)) => first.0 < second.1 && second.0 < first.1,
507        _ => true,
508    }
509}
510
511/// Every overlapping pair of events, in input order.
512pub fn schedule_conflicts(events: &[ScheduleEvent]) -> Vec<ScheduleConflict> {
513    let mut conflicts = Vec::new();
514
515    for (index, event) in events.iter().enumerate() {
516        for next in &events[index + 1..] {
517            if schedule_events_overlap(event, next) {
518                conflicts.push(ScheduleConflict {
519                    a: event.clone(),
520                    b: next.clone(),
521                });
522            }
523        }
524    }
525
526    conflicts
527}
528
529/// Whether `event` has a valid range and overlaps none of `events`.
530pub fn can_place_schedule_event(events: &[ScheduleEvent], event: &ScheduleEvent) -> bool {
531    schedule_range(event).is_some()
532        && !events
533            .iter()
534            .any(|other| schedule_events_overlap(event, other))
535}
536
537fn snap_time(value: i64, snap_minutes: Option<f64>) -> Result<i64, ScheduleError> {
538    let minutes = snap_minutes.unwrap_or(15.0);
539
540    if !minutes.is_finite() {
541        return Err(ScheduleError::InvalidSnap);
542    }
543
544    #[allow(
545        clippy::cast_precision_loss,
546        clippy::cast_possible_truncation,
547        reason = "time values stay within the ±8.64e15 ECMAScript range, which f64 holds exactly"
548    )]
549    let snapped = {
550        let step = minutes.max(1.0) * 60_000.0;
551        // `Math.round` rounds halves toward positive infinity.
552        ((value as f64 / step + 0.5).floor() * step) as i64
553    };
554
555    if snapped.abs() > MAX_TIME_MS {
556        return Err(ScheduleError::OutOfRange);
557    }
558
559    Ok(snapped)
560}
561
562/// Moves one edge of an event to `next_date_time`, snapped to `snap_minutes` and clamped to the
563/// `min` and `max` bounds. The event keeps at least one minute of duration unless a bound forces
564/// it shorter.
565///
566/// # Errors
567///
568/// Fails on an invalid event range, an unparsable target or bound, a minimum later than the
569/// maximum, or a non-finite snap step.
570pub fn resize_schedule_event(
571    event: &ScheduleEvent,
572    next_date_time: &str,
573    options: &ScheduleResizeOptions,
574) -> Result<ScheduleEvent, ScheduleError> {
575    let (start, end) = schedule_range(event).ok_or(ScheduleError::InvalidRange)?;
576    let min = options
577        .min
578        .as_deref()
579        .map(|value| require_time(value, "minimum"))
580        .transpose()?
581        .unwrap_or(i64::MIN);
582    let max = options
583        .max
584        .as_deref()
585        .map(|value| require_time(value, "maximum"))
586        .transpose()?
587        .unwrap_or(i64::MAX);
588
589    if min > max {
590        return Err(ScheduleError::InvalidBounds);
591    }
592
593    let snapped = snap_time(
594        require_time(next_date_time, "resize target")?,
595        options.snap_minutes,
596    )?;
597    let mut resized = event.clone();
598
599    match options.edge {
600        ScheduleResizeEdge::Start => {
601            let upper = min.max(max.min(end - MIN_EVENT_DURATION_MS));
602            resized.start =
603                format_schedule_time(snapped.clamp(min, upper)).ok_or(ScheduleError::OutOfRange)?;
604        }
605        ScheduleResizeEdge::End => {
606            let lower = max.min(min.max(start + MIN_EVENT_DURATION_MS));
607            resized.end =
608                format_schedule_time(snapped.clamp(lower, max)).ok_or(ScheduleError::OutOfRange)?;
609        }
610    }
611
612    Ok(resized)
613}
614
615/// Applies [`resize_schedule_event`] to the event `event_id` and returns every event.
616///
617/// # Errors
618///
619/// Fails when resizing the matching event fails.
620pub fn resize_schedule_events(
621    events: &[ScheduleEvent],
622    event_id: &str,
623    next_date_time: &str,
624    options: &ScheduleResizeOptions,
625) -> Result<Vec<ScheduleEvent>, ScheduleError> {
626    events
627        .iter()
628        .map(|event| {
629            if event.id == event_id {
630                resize_schedule_event(event, next_date_time, options)
631            } else {
632                Ok(event.clone())
633            }
634        })
635        .collect()
636}
637
638#[cfg(test)]
639mod tests {
640    use super::*;
641
642    fn event(id: &str, start: &str, end: &str, resource: Option<&str>) -> ScheduleEvent {
643        ScheduleEvent {
644            id: id.into(),
645            title: id.to_uppercase(),
646            start: start.into(),
647            end: end.into(),
648            resource_id: resource.map(Into::into),
649        }
650    }
651
652    #[test]
653    fn parses_and_formats_iso_date_times() {
654        assert_eq!(parse_schedule_time("1970-01-01"), Some(0));
655        assert_eq!(parse_schedule_time("1970-01-01T00:00:01.5Z"), Some(1500));
656        assert_eq!(
657            parse_schedule_time("2026-12-01T09:30:00+02:00"),
658            parse_schedule_time("2026-12-01T07:30:00Z")
659        );
660        assert_eq!(
661            parse_schedule_time("2024-02-29T24:00"),
662            parse_schedule_time("2024-03-01")
663        );
664        for invalid in [
665            "",
666            "2026-13-01",
667            "2023-02-29",
668            "2026-12-01T25:00",
669            "2026-12-01T09:00Zx",
670            "2026-12-01 09:00",
671            "2026-12-01T09:00:00.",
672            "2026-12-01T09:00+2:00",
673            "tomorrow",
674        ] {
675            assert_eq!(parse_schedule_time(invalid), None, "{invalid}");
676        }
677        assert_eq!(
678            format_schedule_time(parse_schedule_time("2026-12-01T09:05:07.008Z").unwrap_or(0))
679                .as_deref(),
680            Some("2026-12-01T09:05:07.008Z")
681        );
682        assert_eq!(
683            format_schedule_time(-1).as_deref(),
684            Some("1969-12-31T23:59:59.999Z")
685        );
686        assert_eq!(
687            format_schedule_time(253_402_300_800_000).as_deref(),
688            Some("+010000-01-01T00:00:00.000Z")
689        );
690        assert_eq!(format_schedule_time(MAX_TIME_MS + 1), None);
691    }
692
693    #[test]
694    fn parser_rejects_long_input_quickly() {
695        let long = format!("2026-12-01T09:00:00.{}Z", "1".repeat(100_000));
696        assert_eq!(parse_schedule_time(&long), None);
697        let digits = format!("2026-12-01T09:00:00.{}Z", "1".repeat(40));
698        assert!(parse_schedule_time(&digits).is_some());
699    }
700
701    #[test]
702    fn slots_group_events_by_date_and_resource() {
703        let events = vec![
704            event(
705                "a",
706                "2026-12-01T09:00Z",
707                "2026-12-01T10:00Z",
708                Some("room-1"),
709            ),
710            event(
711                "b",
712                "2026-12-02T09:00Z",
713                "2026-12-02T10:00Z",
714                Some("room-2"),
715            ),
716        ];
717        let dates = vec!["2026-12-01".to_string(), "2026-12-02".to_string()];
718        let plain = create_schedule_slots(&dates, &events, &[]);
719
720        assert_eq!(plain.len(), 2);
721        assert_eq!(plain[0].events[0].id, "a");
722        assert!(plain[0].resource.is_none());
723
724        let rooms = vec![
725            ScheduleResource {
726                id: "room-1".into(),
727                label: "Room 1".into(),
728            },
729            ScheduleResource {
730                id: "room-2".into(),
731                label: "Room 2".into(),
732            },
733        ];
734        let slots = create_schedule_slots(&dates, &events, &rooms);
735
736        assert_eq!(slots.len(), 4);
737        assert_eq!(slots[0].events.len(), 1);
738        assert_eq!(slots[1].events, Vec::new());
739        assert_eq!(slots[3].events[0].id, "b");
740    }
741
742    #[test]
743    fn moves_and_detects_conflicts() {
744        let events = vec![
745            event("a", "2026-12-01T09:00Z", "2026-12-01T10:00Z", Some("room")),
746            event("b", "2026-12-01T10:00Z", "2026-12-01T11:00Z", Some("room")),
747            event("c", "2026-12-01T09:30Z", "2026-12-01T10:30Z", Some("other")),
748        ];
749
750        assert_eq!(schedule_conflicts(&events), Vec::new());
751
752        let moved = move_schedule_event(
753            &events,
754            "b",
755            "2026-12-01T09:30Z",
756            "2026-12-01T10:30Z",
757            Some(""),
758        );
759        let conflicts = schedule_conflicts(&moved);
760
761        assert_eq!(conflicts.len(), 1);
762        assert_eq!(
763            (conflicts[0].a.id.as_str(), conflicts[0].b.id.as_str()),
764            ("a", "b")
765        );
766        assert_eq!(moved[1].resource_id.as_deref(), Some("room"));
767
768        let booked_elsewhere = move_schedule_event(&events, "c", "x", "y", Some("room"));
769        assert_eq!(booked_elsewhere[2].resource_id.as_deref(), Some("room"));
770
771        let candidate = event("d", "2026-12-01T10:00Z", "2026-12-01T10:15Z", Some("room"));
772        assert!(!can_place_schedule_event(&events, &candidate));
773        let free = event("d", "2026-12-01T11:00Z", "2026-12-01T12:00Z", Some("room"));
774        assert!(can_place_schedule_event(&events, &free));
775        let broken = event("e", "nope", "2026-12-01T12:00Z", None);
776        assert!(schedule_events_overlap(&broken, &events[0]));
777        assert!(!can_place_schedule_event(&[], &broken));
778    }
779
780    #[test]
781    fn expands_recurring_events() {
782        let weekly = event("standup", "2026-12-01T09:00Z", "2026-12-01T09:15Z", None);
783        let occurrences = expand_recurring_schedule_event(&weekly, 3, 7).unwrap_or_default();
784
785        assert_eq!(occurrences.len(), 3);
786        assert_eq!(occurrences[0].id, "standup");
787        assert_eq!(occurrences[2].id, "standup-3");
788        assert_eq!(occurrences[2].start, "2026-12-15T09:00:00.000Z");
789        assert_eq!(
790            expand_recurring_schedule_event(&weekly, 0, 7),
791            Ok(Vec::new())
792        );
793        assert_eq!(
794            expand_recurring_schedule_event(&weekly, SCHEDULE_MAX_RECURRENCES + 1, 1),
795            Err(ScheduleError::InvalidCount)
796        );
797        assert_eq!(
798            expand_recurring_schedule_event(&weekly, 3, i64::MAX),
799            Err(ScheduleError::OutOfRange)
800        );
801        let reversed = event("x", "2026-12-02", "2026-12-01", None);
802        assert_eq!(
803            expand_recurring_schedule_event(&reversed, 1, 1),
804            Err(ScheduleError::InvalidRange)
805        );
806    }
807
808    #[test]
809    fn resizes_with_snapping_and_bounds() {
810        let meeting = event("m", "2026-12-01T09:00Z", "2026-12-01T10:00Z", None);
811        let options = ScheduleResizeOptions::default();
812        let longer = resize_schedule_event(&meeting, "2026-12-01T10:37Z", &options);
813
814        assert_eq!(longer.map(|e| e.end), Ok("2026-12-01T10:30:00.000Z".into()));
815
816        let collapsed = resize_schedule_event(&meeting, "2026-12-01T08:00Z", &options);
817        assert_eq!(
818            collapsed.map(|e| e.end),
819            Ok("2026-12-01T09:01:00.000Z".into())
820        );
821
822        let start = ScheduleResizeOptions {
823            edge: ScheduleResizeEdge::Start,
824            min: Some("2026-12-01T08:30Z".into()),
825            snap_minutes: Some(5.0),
826            ..ScheduleResizeOptions::default()
827        };
828        let earlier = resize_schedule_event(&meeting, "2026-12-01T07:00Z", &start);
829        assert_eq!(
830            earlier.map(|e| e.start),
831            Ok("2026-12-01T08:30:00.000Z".into())
832        );
833
834        let bounded = ScheduleResizeOptions {
835            max: Some("2026-12-01T09:00:30Z".into()),
836            ..ScheduleResizeOptions::default()
837        };
838        let clipped = resize_schedule_event(&meeting, "2026-12-01T12:00Z", &bounded);
839        assert_eq!(
840            clipped.map(|e| e.end),
841            Ok("2026-12-01T09:00:30.000Z".into())
842        );
843
844        let inverted = ScheduleResizeOptions {
845            min: Some("2026-12-02".into()),
846            max: Some("2026-12-01".into()),
847            ..ScheduleResizeOptions::default()
848        };
849        assert_eq!(
850            resize_schedule_event(&meeting, "2026-12-01T12:00Z", &inverted),
851            Err(ScheduleError::InvalidBounds)
852        );
853        let infinite = ScheduleResizeOptions {
854            snap_minutes: Some(f64::NAN),
855            ..ScheduleResizeOptions::default()
856        };
857        assert_eq!(
858            resize_schedule_event(&meeting, "2026-12-01T12:00Z", &infinite),
859            Err(ScheduleError::InvalidSnap)
860        );
861        assert_eq!(
862            resize_schedule_event(&meeting, "later", &options),
863            Err(ScheduleError::InvalidDateTime("resize target"))
864        );
865
866        let events = vec![
867            meeting.clone(),
868            event("n", "2026-12-01", "2026-12-01", None),
869        ];
870        let resized = resize_schedule_events(&events, "n", "2026-12-01T01:00Z", &options);
871        assert_eq!(
872            resized.map(|list| list[1].end.clone()),
873            Ok("2026-12-01T01:00:00.000Z".into())
874        );
875    }
876}