lumen-dioxus 6.0.0

Lumen UI components for Dioxus: web, desktop, mobile, and Dioxus Native (Blitz).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
//! `Agenda`, `Schedule`, and the schedule model from `lumen-core`: slots, moves, conflicts,
//! recurrence, and resizing.
//!
//! The model works on ISO 8601 strings like `lumen-core` does. It accepts `YYYY-MM-DD` and
//! `YYYY-MM-DDTHH:MM[:SS[.fff]]` with an optional `Z` or `±HH:MM` offset. JavaScript reads a
//! date-time without an offset in the browser's local time zone; this port has no time zone data,
//! so it reads such values as UTC. Pass explicit offsets when the difference matters.

use dioxus::prelude::*;

use crate::class::{Glass, compose};

/// Props for [`Agenda`].
#[derive(Props, Clone, PartialEq)]
pub struct AgendaProps {
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute. Name it with `aria_label`.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// A `header` and an `ol` or `ul` of agenda items.
    pub children: Element,
}

/// A day or event agenda: a header and a list of timed items.
#[component]
pub fn Agenda(props: AgendaProps) -> Element {
    let glass = props.glass.class("ui-agenda");
    let class = compose([Some("ui-agenda"), glass.as_deref(), props.class.as_deref()]);

    rsx! {
        section { class, ..props.attributes, {props.children} }
    }
}

/// Props for [`Schedule`].
#[derive(Props, Clone, PartialEq)]
pub struct ScheduleProps {
    /// Glass intensity.
    #[props(default, into)]
    pub glass: Glass,
    /// Extra classes appended after the Lumen classes.
    #[props(into)]
    pub class: Option<String>,
    /// Any other `<section>` or global attribute. Name it with `aria_label`.
    #[props(extends = GlobalAttributes, extends = section)]
    pub attributes: Vec<Attribute>,
    /// The schedule grid: elements marked `data-ui-schedule-grid`, `data-ui-schedule-slot`, and
    /// `data-ui-schedule-event`. Build them from [`create_schedule_slots`].
    pub children: Element,
}

/// A resource or week schedule grid. Lay out its slots with [`create_schedule_slots`] and update
/// events with [`move_schedule_event`] and [`resize_schedule_events`].
#[component]
pub fn Schedule(props: ScheduleProps) -> Element {
    let glass = props.glass.class("ui-schedule");
    let class = compose([
        Some("ui-schedule"),
        glass.as_deref(),
        props.class.as_deref(),
    ]);

    rsx! {
        section { class, "data-ui-schedule": "true", ..props.attributes, {props.children} }
    }
}

/// One event on a [`Schedule`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ScheduleEvent {
    /// Unique id.
    pub id: String,
    /// Title shown on the event.
    pub title: String,
    /// ISO 8601 start, such as `2026-12-01T09:00:00Z`.
    pub start: String,
    /// ISO 8601 end, no earlier than `start`.
    pub end: String,
    /// The [`ScheduleResource`] that the event books, if any.
    pub resource_id: Option<String>,
}

/// A bookable resource, such as a room or a person.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ScheduleResource {
    /// Unique id that events reference.
    pub id: String,
    /// Display label.
    pub label: String,
}

/// One cell of a schedule grid: a date, optionally a resource, and the events that start in it.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ScheduleSlot {
    /// The date prefix, such as `2026-12-01`.
    pub date: String,
    /// Events whose start begins with `date` (and that book `resource`, when set).
    pub events: Vec<ScheduleEvent>,
    /// The resource column, when the grid has resources.
    pub resource: Option<ScheduleResource>,
}

/// Two events that overlap on the same resource.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ScheduleConflict {
    /// The earlier event in the input order.
    pub a: ScheduleEvent,
    /// The later event in the input order.
    pub b: ScheduleEvent,
}

/// Which edge [`resize_schedule_event`] moves.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum ScheduleResizeEdge {
    /// Moves the start.
    Start,
    /// Moves the end.
    #[default]
    End,
}

/// Options for [`resize_schedule_event`].
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ScheduleResizeOptions {
    /// The edge to move. Defaults to the end.
    pub edge: ScheduleResizeEdge,
    /// Earliest allowed date-time for the moved edge.
    pub min: Option<String>,
    /// Latest allowed date-time for the moved edge.
    pub max: Option<String>,
    /// Snap step in minutes. Defaults to 15; values below 1 snap to whole minutes.
    pub snap_minutes: Option<f64>,
}

/// Why a schedule operation failed, mirroring the errors `lumen-core` throws.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ScheduleError {
    /// A date-time could not be parsed. Holds the field name.
    InvalidDateTime(&'static str),
    /// The event has an invalid date-time or starts after it ends.
    InvalidRange,
    /// The minimum bound is later than the maximum bound.
    InvalidBounds,
    /// The snap step is not finite.
    InvalidSnap,
    /// A result falls outside the supported date-time range.
    OutOfRange,
    /// The recurrence count is larger than [`SCHEDULE_MAX_RECURRENCES`].
    InvalidCount,
}

impl std::fmt::Display for ScheduleError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::InvalidDateTime(field) => {
                write!(formatter, "Schedule {field} must be a valid date-time.")
            }
            Self::InvalidRange => formatter.write_str(
                "Schedule event must have valid date-times with start no later than end.",
            ),
            Self::InvalidBounds => formatter.write_str("Schedule minimum cannot exceed maximum."),
            Self::InvalidSnap => formatter.write_str("Schedule snap minutes must be finite."),
            Self::OutOfRange => {
                formatter.write_str("Schedule date-time exceeds the supported range.")
            }
            Self::InvalidCount => write!(
                formatter,
                "Schedule recurrence count must be at most {SCHEDULE_MAX_RECURRENCES}."
            ),
        }
    }
}

impl std::error::Error for ScheduleError {}

/// The most occurrences [`expand_recurring_schedule_event`] creates, a safety bound that the
/// JavaScript version does not need because it fails on allocation instead.
pub const SCHEDULE_MAX_RECURRENCES: usize = 100_000;

const MS_PER_MINUTE: i64 = 60_000;
const MS_PER_DAY: i64 = 86_400_000;
/// The ECMAScript time value limit.
const MAX_TIME_MS: i64 = 8_640_000_000_000_000;
const MIN_EVENT_DURATION_MS: i64 = MS_PER_MINUTE;
const MAX_DATE_TIME_LENGTH: usize = 64;

fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
    let year = if month <= 2 { year - 1 } else { year };
    let era = year.div_euclid(400);
    let year_of_era = year - era * 400;
    let month_index = (month + 9) % 12;
    let day_of_year = (153 * month_index + 2) / 5 + day - 1;
    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;

    era * 146_097 + day_of_era - 719_468
}

fn civil_from_days(days: i64) -> (i64, i64, i64) {
    let days = days + 719_468;
    let era = days.div_euclid(146_097);
    let day_of_era = days - era * 146_097;
    let year_of_era =
        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
    let month_index = (5 * day_of_year + 2) / 153;
    let day = day_of_year - (153 * month_index + 2) / 5 + 1;
    let month = if month_index < 10 {
        month_index + 3
    } else {
        month_index - 9
    };
    let year = year_of_era + era * 400 + i64::from(month <= 2);

    (year, month, day)
}

fn is_leap_year(year: i64) -> bool {
    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
}

fn days_in_month(year: i64, month: i64) -> i64 {
    match month {
        2 if is_leap_year(year) => 29,
        2 => 28,
        4 | 6 | 9 | 11 => 30,
        _ => 31,
    }
}

/// Reads `count` ASCII digits starting at `index`.
fn read_digits(bytes: &[u8], index: usize, count: usize) -> Option<i64> {
    let digits = bytes.get(index..index + count)?;
    let mut value = 0_i64;

    for digit in digits {
        if !digit.is_ascii_digit() {
            return None;
        }

        value = value * 10 + i64::from(digit - b'0');
    }

    Some(value)
}

/// Parses an ISO 8601 date or date-time into milliseconds since the Unix epoch, with one linear
/// scan. Returns `None` for anything else.
pub(crate) fn parse_schedule_time(value: &str) -> Option<i64> {
    let bytes = value.trim().as_bytes();

    if bytes.len() > MAX_DATE_TIME_LENGTH {
        return None;
    }

    let year = read_digits(bytes, 0, 4)?;
    (bytes.get(4) == Some(&b'-')).then_some(())?;
    let month = read_digits(bytes, 5, 2)?;
    (bytes.get(7) == Some(&b'-')).then_some(())?;
    let day = read_digits(bytes, 8, 2)?;

    if !(1..=12).contains(&month) || day < 1 || day > days_in_month(year, month) {
        return None;
    }

    let date_ms = days_from_civil(year, month, day) * MS_PER_DAY;

    if bytes.len() == 10 {
        return Some(date_ms);
    }

    (bytes.get(10) == Some(&b'T')).then_some(())?;
    let hour = read_digits(bytes, 11, 2)?;
    (bytes.get(13) == Some(&b':')).then_some(())?;
    let minute = read_digits(bytes, 14, 2)?;
    let mut index = 16;
    let mut second = 0;
    let mut millisecond = 0;

    if bytes.get(index) == Some(&b':') {
        second = read_digits(bytes, index + 1, 2)?;
        index += 3;

        if bytes.get(index) == Some(&b'.') {
            index += 1;
            let start = index;

            while bytes.get(index).is_some_and(u8::is_ascii_digit) {
                if index - start < 3 {
                    millisecond = millisecond * 10 + i64::from(bytes[index] - b'0');
                }

                index += 1;
            }

            if index == start {
                return None;
            }

            for _ in (index - start)..3 {
                millisecond *= 10;
            }
        }
    }

    let valid_time = (hour < 24 && minute < 60 && second < 60)
        || (hour == 24 && minute == 0 && second == 0 && millisecond == 0);

    if !valid_time {
        return None;
    }

    let offset_minutes = match bytes.get(index) {
        None => 0,
        Some(b'Z') if index + 1 == bytes.len() => 0,
        Some(sign @ (b'+' | b'-')) if index + 6 == bytes.len() => {
            let offset_hour = read_digits(bytes, index + 1, 2)?;
            (bytes.get(index + 3) == Some(&b':')).then_some(())?;
            let offset_minute = read_digits(bytes, index + 4, 2)?;

            if offset_hour > 23 || offset_minute > 59 {
                return None;
            }

            let total = offset_hour * 60 + offset_minute;

            if *sign == b'+' { total } else { -total }
        }
        Some(_) => return None,
    };

    Some(
        date_ms + hour * 3_600_000 + minute * MS_PER_MINUTE + second * 1000 + millisecond
            - offset_minutes * MS_PER_MINUTE,
    )
}

/// Formats milliseconds since the epoch like `Date.prototype.toISOString`.
pub(crate) fn format_schedule_time(time: i64) -> Option<String> {
    if time.abs() > MAX_TIME_MS {
        return None;
    }

    let days = time.div_euclid(MS_PER_DAY);
    let in_day = time.rem_euclid(MS_PER_DAY);
    let (year, month, day) = civil_from_days(days);
    let year_text = if (0..=9999).contains(&year) {
        format!("{year:04}")
    } else if year < 0 {
        format!("-{:06}", -year)
    } else {
        format!("+{year:06}")
    };

    Some(format!(
        "{year_text}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
        in_day / 3_600_000,
        in_day % 3_600_000 / MS_PER_MINUTE,
        in_day % MS_PER_MINUTE / 1000,
        in_day % 1000
    ))
}

fn schedule_range(event: &ScheduleEvent) -> Option<(i64, i64)> {
    let start = parse_schedule_time(&event.start)?;
    let end = parse_schedule_time(&event.end)?;

    (start <= end).then_some((start, end))
}

fn require_time(value: &str, field: &'static str) -> Result<i64, ScheduleError> {
    parse_schedule_time(value).ok_or(ScheduleError::InvalidDateTime(field))
}

/// Groups events into one slot per date (and per resource, when `resources` is not empty).
///
/// An event belongs to a slot when its `start` begins with the slot date and, with resources,
/// when it books that resource.
pub fn create_schedule_slots(
    dates: &[String],
    events: &[ScheduleEvent],
    resources: &[ScheduleResource],
) -> Vec<ScheduleSlot> {
    let slot = |date: &String, resource: Option<&ScheduleResource>| ScheduleSlot {
        date: date.clone(),
        events: events
            .iter()
            .filter(|event| {
                event.start.starts_with(date.as_str())
                    && resource.is_none_or(|resource| {
                        event.resource_id.as_deref() == Some(resource.id.as_str())
                    })
            })
            .cloned()
            .collect(),
        resource: resource.cloned(),
    };

    dates
        .iter()
        .flat_map(|date| {
            if resources.is_empty() {
                vec![slot(date, None)]
            } else {
                resources
                    .iter()
                    .map(|resource| slot(date, Some(resource)))
                    .collect()
            }
        })
        .collect()
}

/// Returns `events` with the event `event_id` moved to a new start and end, and to `resource_id`
/// when it is set and not empty.
pub fn move_schedule_event(
    events: &[ScheduleEvent],
    event_id: &str,
    next_start: &str,
    next_end: &str,
    resource_id: Option<&str>,
) -> Vec<ScheduleEvent> {
    events
        .iter()
        .map(|event| {
            if event.id != event_id {
                return event.clone();
            }

            let mut moved = event.clone();
            moved.start = next_start.to_string();
            moved.end = next_end.to_string();

            if let Some(resource) = resource_id.filter(|resource| !resource.is_empty()) {
                moved.resource_id = Some(resource.to_string());
            }

            moved
        })
        .collect()
}

/// Repeats an event `count` times, `interval_days` apart. The first copy keeps the id; later ones
/// get `{id}-2`, `{id}-3`, and so on. Dates are written in UTC ISO format.
///
/// # Errors
///
/// Fails when the event range is invalid, `count` exceeds [`SCHEDULE_MAX_RECURRENCES`], or an
/// occurrence leaves the supported date-time range.
pub fn expand_recurring_schedule_event(
    event: &ScheduleEvent,
    count: usize,
    interval_days: i64,
) -> Result<Vec<ScheduleEvent>, ScheduleError> {
    if count > SCHEDULE_MAX_RECURRENCES {
        return Err(ScheduleError::InvalidCount);
    }

    let (start, end) = schedule_range(event).ok_or(ScheduleError::InvalidRange)?;
    let mut occurrences = Vec::with_capacity(count);

    for index in 0..count {
        let shift = i64::try_from(index)
            .ok()
            .and_then(|index| index.checked_mul(interval_days))
            .and_then(|days| days.checked_mul(MS_PER_DAY))
            .ok_or(ScheduleError::OutOfRange)?;
        let next_start = start.checked_add(shift).ok_or(ScheduleError::OutOfRange)?;
        let next_end = end.checked_add(shift).ok_or(ScheduleError::OutOfRange)?;
        let mut occurrence = event.clone();

        occurrence.start = format_schedule_time(next_start).ok_or(ScheduleError::OutOfRange)?;
        occurrence.end = format_schedule_time(next_end).ok_or(ScheduleError::OutOfRange)?;

        if index > 0 {
            occurrence.id = format!("{}-{}", event.id, index + 1);
        }

        occurrences.push(occurrence);
    }

    Ok(occurrences)
}

/// Whether two different events overlap on the same resource. Events on different resources never
/// overlap; an event with an invalid range overlaps everything on its resource.
pub fn schedule_events_overlap(a: &ScheduleEvent, b: &ScheduleEvent) -> bool {
    let booked = |event: &ScheduleEvent| event.resource_id.clone().filter(|id| !id.is_empty());

    if a.id == b.id {
        return false;
    }

    if let (Some(first), Some(second)) = (booked(a), booked(b))
        && first != second
    {
        return false;
    }

    match (schedule_range(a), schedule_range(b)) {
        (Some(first), Some(second)) => first.0 < second.1 && second.0 < first.1,
        _ => true,
    }
}

/// Every overlapping pair of events, in input order.
pub fn schedule_conflicts(events: &[ScheduleEvent]) -> Vec<ScheduleConflict> {
    let mut conflicts = Vec::new();

    for (index, event) in events.iter().enumerate() {
        for next in &events[index + 1..] {
            if schedule_events_overlap(event, next) {
                conflicts.push(ScheduleConflict {
                    a: event.clone(),
                    b: next.clone(),
                });
            }
        }
    }

    conflicts
}

/// Whether `event` has a valid range and overlaps none of `events`.
pub fn can_place_schedule_event(events: &[ScheduleEvent], event: &ScheduleEvent) -> bool {
    schedule_range(event).is_some()
        && !events
            .iter()
            .any(|other| schedule_events_overlap(event, other))
}

fn snap_time(value: i64, snap_minutes: Option<f64>) -> Result<i64, ScheduleError> {
    let minutes = snap_minutes.unwrap_or(15.0);

    if !minutes.is_finite() {
        return Err(ScheduleError::InvalidSnap);
    }

    #[allow(
        clippy::cast_precision_loss,
        clippy::cast_possible_truncation,
        reason = "time values stay within the ±8.64e15 ECMAScript range, which f64 holds exactly"
    )]
    let snapped = {
        let step = minutes.max(1.0) * 60_000.0;
        // `Math.round` rounds halves toward positive infinity.
        ((value as f64 / step + 0.5).floor() * step) as i64
    };

    if snapped.abs() > MAX_TIME_MS {
        return Err(ScheduleError::OutOfRange);
    }

    Ok(snapped)
}

/// Moves one edge of an event to `next_date_time`, snapped to `snap_minutes` and clamped to the
/// `min` and `max` bounds. The event keeps at least one minute of duration unless a bound forces
/// it shorter.
///
/// # Errors
///
/// Fails on an invalid event range, an unparsable target or bound, a minimum later than the
/// maximum, or a non-finite snap step.
pub fn resize_schedule_event(
    event: &ScheduleEvent,
    next_date_time: &str,
    options: &ScheduleResizeOptions,
) -> Result<ScheduleEvent, ScheduleError> {
    let (start, end) = schedule_range(event).ok_or(ScheduleError::InvalidRange)?;
    let min = options
        .min
        .as_deref()
        .map(|value| require_time(value, "minimum"))
        .transpose()?
        .unwrap_or(i64::MIN);
    let max = options
        .max
        .as_deref()
        .map(|value| require_time(value, "maximum"))
        .transpose()?
        .unwrap_or(i64::MAX);

    if min > max {
        return Err(ScheduleError::InvalidBounds);
    }

    let snapped = snap_time(
        require_time(next_date_time, "resize target")?,
        options.snap_minutes,
    )?;
    let mut resized = event.clone();

    match options.edge {
        ScheduleResizeEdge::Start => {
            let upper = min.max(max.min(end - MIN_EVENT_DURATION_MS));
            resized.start =
                format_schedule_time(snapped.clamp(min, upper)).ok_or(ScheduleError::OutOfRange)?;
        }
        ScheduleResizeEdge::End => {
            let lower = max.min(min.max(start + MIN_EVENT_DURATION_MS));
            resized.end =
                format_schedule_time(snapped.clamp(lower, max)).ok_or(ScheduleError::OutOfRange)?;
        }
    }

    Ok(resized)
}

/// Applies [`resize_schedule_event`] to the event `event_id` and returns every event.
///
/// # Errors
///
/// Fails when resizing the matching event fails.
pub fn resize_schedule_events(
    events: &[ScheduleEvent],
    event_id: &str,
    next_date_time: &str,
    options: &ScheduleResizeOptions,
) -> Result<Vec<ScheduleEvent>, ScheduleError> {
    events
        .iter()
        .map(|event| {
            if event.id == event_id {
                resize_schedule_event(event, next_date_time, options)
            } else {
                Ok(event.clone())
            }
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;

    fn event(id: &str, start: &str, end: &str, resource: Option<&str>) -> ScheduleEvent {
        ScheduleEvent {
            id: id.into(),
            title: id.to_uppercase(),
            start: start.into(),
            end: end.into(),
            resource_id: resource.map(Into::into),
        }
    }

    #[test]
    fn parses_and_formats_iso_date_times() {
        assert_eq!(parse_schedule_time("1970-01-01"), Some(0));
        assert_eq!(parse_schedule_time("1970-01-01T00:00:01.5Z"), Some(1500));
        assert_eq!(
            parse_schedule_time("2026-12-01T09:30:00+02:00"),
            parse_schedule_time("2026-12-01T07:30:00Z")
        );
        assert_eq!(
            parse_schedule_time("2024-02-29T24:00"),
            parse_schedule_time("2024-03-01")
        );
        for invalid in [
            "",
            "2026-13-01",
            "2023-02-29",
            "2026-12-01T25:00",
            "2026-12-01T09:00Zx",
            "2026-12-01 09:00",
            "2026-12-01T09:00:00.",
            "2026-12-01T09:00+2:00",
            "tomorrow",
        ] {
            assert_eq!(parse_schedule_time(invalid), None, "{invalid}");
        }
        assert_eq!(
            format_schedule_time(parse_schedule_time("2026-12-01T09:05:07.008Z").unwrap_or(0))
                .as_deref(),
            Some("2026-12-01T09:05:07.008Z")
        );
        assert_eq!(
            format_schedule_time(-1).as_deref(),
            Some("1969-12-31T23:59:59.999Z")
        );
        assert_eq!(
            format_schedule_time(253_402_300_800_000).as_deref(),
            Some("+010000-01-01T00:00:00.000Z")
        );
        assert_eq!(format_schedule_time(MAX_TIME_MS + 1), None);
    }

    #[test]
    fn parser_rejects_long_input_quickly() {
        let long = format!("2026-12-01T09:00:00.{}Z", "1".repeat(100_000));
        assert_eq!(parse_schedule_time(&long), None);
        let digits = format!("2026-12-01T09:00:00.{}Z", "1".repeat(40));
        assert!(parse_schedule_time(&digits).is_some());
    }

    #[test]
    fn slots_group_events_by_date_and_resource() {
        let events = vec![
            event(
                "a",
                "2026-12-01T09:00Z",
                "2026-12-01T10:00Z",
                Some("room-1"),
            ),
            event(
                "b",
                "2026-12-02T09:00Z",
                "2026-12-02T10:00Z",
                Some("room-2"),
            ),
        ];
        let dates = vec!["2026-12-01".to_string(), "2026-12-02".to_string()];
        let plain = create_schedule_slots(&dates, &events, &[]);

        assert_eq!(plain.len(), 2);
        assert_eq!(plain[0].events[0].id, "a");
        assert!(plain[0].resource.is_none());

        let rooms = vec![
            ScheduleResource {
                id: "room-1".into(),
                label: "Room 1".into(),
            },
            ScheduleResource {
                id: "room-2".into(),
                label: "Room 2".into(),
            },
        ];
        let slots = create_schedule_slots(&dates, &events, &rooms);

        assert_eq!(slots.len(), 4);
        assert_eq!(slots[0].events.len(), 1);
        assert_eq!(slots[1].events, Vec::new());
        assert_eq!(slots[3].events[0].id, "b");
    }

    #[test]
    fn moves_and_detects_conflicts() {
        let events = vec![
            event("a", "2026-12-01T09:00Z", "2026-12-01T10:00Z", Some("room")),
            event("b", "2026-12-01T10:00Z", "2026-12-01T11:00Z", Some("room")),
            event("c", "2026-12-01T09:30Z", "2026-12-01T10:30Z", Some("other")),
        ];

        assert_eq!(schedule_conflicts(&events), Vec::new());

        let moved = move_schedule_event(
            &events,
            "b",
            "2026-12-01T09:30Z",
            "2026-12-01T10:30Z",
            Some(""),
        );
        let conflicts = schedule_conflicts(&moved);

        assert_eq!(conflicts.len(), 1);
        assert_eq!(
            (conflicts[0].a.id.as_str(), conflicts[0].b.id.as_str()),
            ("a", "b")
        );
        assert_eq!(moved[1].resource_id.as_deref(), Some("room"));

        let booked_elsewhere = move_schedule_event(&events, "c", "x", "y", Some("room"));
        assert_eq!(booked_elsewhere[2].resource_id.as_deref(), Some("room"));

        let candidate = event("d", "2026-12-01T10:00Z", "2026-12-01T10:15Z", Some("room"));
        assert!(!can_place_schedule_event(&events, &candidate));
        let free = event("d", "2026-12-01T11:00Z", "2026-12-01T12:00Z", Some("room"));
        assert!(can_place_schedule_event(&events, &free));
        let broken = event("e", "nope", "2026-12-01T12:00Z", None);
        assert!(schedule_events_overlap(&broken, &events[0]));
        assert!(!can_place_schedule_event(&[], &broken));
    }

    #[test]
    fn expands_recurring_events() {
        let weekly = event("standup", "2026-12-01T09:00Z", "2026-12-01T09:15Z", None);
        let occurrences = expand_recurring_schedule_event(&weekly, 3, 7).unwrap_or_default();

        assert_eq!(occurrences.len(), 3);
        assert_eq!(occurrences[0].id, "standup");
        assert_eq!(occurrences[2].id, "standup-3");
        assert_eq!(occurrences[2].start, "2026-12-15T09:00:00.000Z");
        assert_eq!(
            expand_recurring_schedule_event(&weekly, 0, 7),
            Ok(Vec::new())
        );
        assert_eq!(
            expand_recurring_schedule_event(&weekly, SCHEDULE_MAX_RECURRENCES + 1, 1),
            Err(ScheduleError::InvalidCount)
        );
        assert_eq!(
            expand_recurring_schedule_event(&weekly, 3, i64::MAX),
            Err(ScheduleError::OutOfRange)
        );
        let reversed = event("x", "2026-12-02", "2026-12-01", None);
        assert_eq!(
            expand_recurring_schedule_event(&reversed, 1, 1),
            Err(ScheduleError::InvalidRange)
        );
    }

    #[test]
    fn resizes_with_snapping_and_bounds() {
        let meeting = event("m", "2026-12-01T09:00Z", "2026-12-01T10:00Z", None);
        let options = ScheduleResizeOptions::default();
        let longer = resize_schedule_event(&meeting, "2026-12-01T10:37Z", &options);

        assert_eq!(longer.map(|e| e.end), Ok("2026-12-01T10:30:00.000Z".into()));

        let collapsed = resize_schedule_event(&meeting, "2026-12-01T08:00Z", &options);
        assert_eq!(
            collapsed.map(|e| e.end),
            Ok("2026-12-01T09:01:00.000Z".into())
        );

        let start = ScheduleResizeOptions {
            edge: ScheduleResizeEdge::Start,
            min: Some("2026-12-01T08:30Z".into()),
            snap_minutes: Some(5.0),
            ..ScheduleResizeOptions::default()
        };
        let earlier = resize_schedule_event(&meeting, "2026-12-01T07:00Z", &start);
        assert_eq!(
            earlier.map(|e| e.start),
            Ok("2026-12-01T08:30:00.000Z".into())
        );

        let bounded = ScheduleResizeOptions {
            max: Some("2026-12-01T09:00:30Z".into()),
            ..ScheduleResizeOptions::default()
        };
        let clipped = resize_schedule_event(&meeting, "2026-12-01T12:00Z", &bounded);
        assert_eq!(
            clipped.map(|e| e.end),
            Ok("2026-12-01T09:00:30.000Z".into())
        );

        let inverted = ScheduleResizeOptions {
            min: Some("2026-12-02".into()),
            max: Some("2026-12-01".into()),
            ..ScheduleResizeOptions::default()
        };
        assert_eq!(
            resize_schedule_event(&meeting, "2026-12-01T12:00Z", &inverted),
            Err(ScheduleError::InvalidBounds)
        );
        let infinite = ScheduleResizeOptions {
            snap_minutes: Some(f64::NAN),
            ..ScheduleResizeOptions::default()
        };
        assert_eq!(
            resize_schedule_event(&meeting, "2026-12-01T12:00Z", &infinite),
            Err(ScheduleError::InvalidSnap)
        );
        assert_eq!(
            resize_schedule_event(&meeting, "later", &options),
            Err(ScheduleError::InvalidDateTime("resize target"))
        );

        let events = vec![
            meeting.clone(),
            event("n", "2026-12-01", "2026-12-01", None),
        ];
        let resized = resize_schedule_events(&events, "n", "2026-12-01T01:00Z", &options);
        assert_eq!(
            resized.map(|list| list[1].end.clone()),
            Ok("2026-12-01T01:00:00.000Z".into())
        );
    }
}