Skip to main content

iced_cube/data/calendar/
parts.rs

1//! Pieces the views share: entry chips, lanes of bars, day numbers and
2//! grid lines.
3
4use std::rc::Rc;
5
6use iced::advanced::layout::{self, Layout};
7use iced::advanced::widget::{Tree, Widget};
8use iced::advanced::{Renderer as _, renderer};
9use iced::widget::button::Status;
10use iced::widget::{self, Column, Row, Space, column, container, row, stack, svg, text};
11use iced::{
12    Alignment, Background, Border, Color, Element, Length, Padding, Rectangle, Renderer, Size,
13    Theme, mouse,
14};
15use jiff::Timestamp;
16use jiff::civil::Date;
17use jiff::tz::TimeZone;
18
19use super::entry::{Change, Emphasis, Entry, EntryId, Occurrence, Paint, When};
20use super::gesture::Pressable;
21use super::layout::{Bar, Fitted};
22use super::state::{Event, Selection, State};
23use super::style;
24use crate::data::ellipsis::ellipsis;
25use crate::icon::{opaque, themed};
26use crate::overlay::tooltip::tooltip;
27use crate::theme::{self, Tokens, radius, text_size};
28
29pub(super) type Handler<'a, Message> = Option<Rc<dyn Fn(Event) -> Message + 'a>>;
30
31/// The message for `event`, or `None` for a calendar without a handler,
32/// which renders disabled.
33pub(super) fn send<Message>(handler: &Handler<'_, Message>, event: Event) -> Option<Message> {
34    handler.as_ref().map(|handler| handler(event))
35}
36
37/// The height of an entry's bar.
38pub const CHIP_HEIGHT: f32 = 20.0;
39/// The space between lanes of bars.
40pub const LANE_GAP: f32 = 2.0;
41/// The side of the pill around a day's number.
42pub const NUMBER_SIZE: f32 = 22.0;
43/// The side of the circle around the day heading a column of hours.
44pub const HEADING_SIZE: f32 = 34.0;
45
46/// A time of day, such as "09:30".
47pub fn time_label(instant: Timestamp, time_zone: &TimeZone) -> String {
48    instant
49        .to_zoned_datetime(time_zone.clone())
50        .strftime("%H:%M")
51        .to_string()
52}
53
54/// When an occurrence happens within its day: "All day", or its start and
55/// end times.
56pub fn span_label(occurrence: &Occurrence, time_zone: &TimeZone) -> String {
57    if occurrence.all_day {
58        return String::from("All day");
59    }
60    if occurrence.end <= occurrence.start {
61        return time_label(occurrence.start, time_zone);
62    }
63    format!(
64        "{} - {}",
65        time_label(occurrence.start, time_zone),
66        time_label(occurrence.end, time_zone)
67    )
68}
69
70/// When a span is, in words, for a dialog or a list: "Thu 19 Nov, 10:00 -
71/// 11:30" for a time on one day, and the first and last day otherwise.
72pub fn when_label(when: &When, time_zone: &TimeZone) -> String {
73    const DAY: &str = "%a %-d %b";
74    match *when {
75        When::AllDay { first, last } if first == last => first.strftime(DAY).to_string(),
76        When::AllDay { first, last } => {
77            format!("{} - {}", first.strftime(DAY), last.strftime(DAY))
78        }
79        When::Timed { start, end } => {
80            let from = start.to_zoned_datetime(time_zone.clone());
81            let to = end.to_zoned_datetime(time_zone.clone());
82            let day = from.strftime(DAY);
83            let (first, last) = (from.strftime("%H:%M"), to.strftime("%H:%M"));
84            if end <= start {
85                return format!("{day}, {first}");
86            }
87            // An end at midnight closes the day the entry starts on.
88            let ends_that_night = to.time() == jiff::civil::Time::midnight()
89                && from.date().tomorrow().is_ok_and(|next| next == to.date());
90            if from.date() == to.date() || ends_that_night {
91                return format!("{day}, {first} - {last}");
92            }
93            format!("{day} {first} - {} {last}", to.strftime(DAY))
94        }
95    }
96}
97
98/// What a bar says: the title, after the start time for a timed entry
99/// that begins on the bar's first day.
100pub fn bar_label(title: &str, bar: &Bar, time_zone: &TimeZone) -> String {
101    if bar.occurrence.all_day || bar.starts_before {
102        return title.to_owned();
103    }
104    format!("{} {title}", time_label(bar.occurrence.start, time_zone))
105}
106
107pub(super) fn selection_of(occurrence: &Occurrence) -> Selection {
108    Selection::Entry {
109        entry: occurrence.entry,
110        start: occurrence.start,
111    }
112}
113
114/// A day's short name in capitals, such as "MON", or its first letter
115/// when `narrow`.
116pub fn weekday_label(date: Date, narrow: bool) -> String {
117    let name = date.strftime("%a").to_string().to_uppercase();
118    if narrow {
119        return name.chars().take(1).collect();
120    }
121    name
122}
123
124/// A day's number in a pill, filled for today.
125pub(super) fn day_number<'a, Message: 'a>(date: Date, day: style::Day) -> Element<'a, Message> {
126    number_pill(date, day, NUMBER_SIZE, text_size::XS)
127}
128
129/// A day's number as the heading of its column: larger, in a circle.
130pub(super) fn day_heading<'a, Message: 'a>(date: Date, day: style::Day) -> Element<'a, Message> {
131    number_pill(date, day, HEADING_SIZE, text_size::LG)
132}
133
134fn number_pill<'a, Message: 'a>(
135    date: Date,
136    day: style::Day,
137    side: f32,
138    size: f32,
139) -> Element<'a, Message> {
140    let font = if day.today {
141        theme::semibold()
142    } else {
143        theme::font()
144    };
145    let number = text(date.day().to_string())
146        .size(size)
147        .font(font)
148        .wrapping(text::Wrapping::None)
149        .style(move |theme: &Theme| text::Style {
150            color: Some(style::day_number(&Tokens::of(theme), day).foreground),
151        });
152    container(number)
153        .center(Length::Fixed(side))
154        .style(move |theme: &Theme| container::Style {
155            background: style::day_number(&Tokens::of(theme), day)
156                .background
157                .map(Background::Color),
158            border: Border {
159                radius: radius::FULL.into(),
160                ..Border::default()
161            },
162            ..container::Style::default()
163        })
164        .into()
165}
166
167/// The id of an occurrence's chip, bar or block in every view, for
168/// finding exactly one entry in tests and for operations on it.
169pub fn entry_id(entry: EntryId, start: Timestamp) -> widget::Id {
170    widget::Id::from(format!(
171        "iced-cube-calendar-entry-{}-{}",
172        entry.0,
173        start.as_millisecond()
174    ))
175}
176
177/// Reports an entry's chip, bar, block or row as a button named by its
178/// title, with a colour of its own as `colour` (`#rrggbb`) and `movable`
179/// or `removable` set to `false` when the calendar may not move or remove
180/// it. Its double presses are counted on the app's clock.
181#[cfg(feature = "icedwright")]
182pub(super) fn annotate_entry<'a, Message: 'a>(
183    element: impl Into<Element<'a, Message>>,
184    state: &State,
185    entry: &Entry,
186    selected: bool,
187    enabled: bool,
188) -> Element<'a, Message> {
189    let mut annotated = icedwright_probe::semantic(element)
190        .role(icedwright_probe::role::Button)
191        .name(entry.title().to_owned())
192        .click_clock(icedwright_probe::ClickClock::Probe)
193        .component("iced_cube::calendar");
194    if selected {
195        annotated = annotated.prop("selected", "true");
196    }
197    if let Some(colour) = entry.colour_of() {
198        annotated = annotated.prop("colour", hex(colour));
199    }
200    if !state.can_move(entry) {
201        annotated = annotated.prop("movable", "false");
202    }
203    if !state.can_remove(entry) {
204        annotated = annotated.prop("removable", "false");
205    }
206    if !enabled {
207        annotated = annotated.disabled(true);
208    }
209    annotated.into()
210}
211
212/// A colour as `#rrggbb`, leaving out its alpha as entries are drawn
213/// opaque.
214#[cfg(feature = "icedwright")]
215pub(super) fn hex(colour: Color) -> String {
216    let [red, green, blue, _] = colour.into_rgba8();
217    format!("#{red:02x}{green:02x}{blue:02x}")
218}
219
220/// The id of a day's cell in the month, or its heading over the hours,
221/// for finding it in tests and for drags that end on it.
222pub fn day_id(date: Date) -> widget::Id {
223    widget::Id::from(format!("iced-cube-calendar-day-{date}"))
224}
225
226/// Diagonal stripes exactly `size` big, so they keep the same spacing on
227/// any bar and never draw past it. The picture is cached by its bytes, so
228/// each size is drawn once.
229pub(super) fn hatch_handle(size: Size) -> svg::Handle {
230    let (width, height) = (size.width.round().max(1.0), size.height.round().max(1.0));
231    svg::Handle::from_memory(format!(
232        r##"<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}"><defs><pattern id="h" width="8" height="8" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><rect width="3" height="8" fill="#000"/></pattern></defs><rect width="{width}" height="{height}" fill="url(#h)"/></svg>"##
233    ).into_bytes())
234}
235
236/// Stripes in a colour from the theme, filling the space they are given.
237struct Hatch<C> {
238    colour: C,
239}
240
241impl<Message, C: Fn(&Theme) -> Option<Color>> Widget<Message, Theme, Renderer> for Hatch<C> {
242    fn size(&self) -> Size<Length> {
243        Size::new(Length::Fill, Length::Fill)
244    }
245
246    fn layout(
247        &mut self,
248        _tree: &mut Tree,
249        _renderer: &Renderer,
250        limits: &layout::Limits,
251    ) -> layout::Node {
252        layout::Node::new(limits.max())
253    }
254
255    fn draw(
256        &self,
257        _tree: &Tree,
258        renderer: &mut Renderer,
259        theme: &Theme,
260        _style: &renderer::Style,
261        layout: Layout<'_>,
262        _cursor: mouse::Cursor,
263        viewport: &Rectangle,
264    ) {
265        let Some(colour) = (self.colour)(theme) else {
266            return;
267        };
268        let bounds = layout.bounds();
269        let Some(clip) = bounds.intersection(viewport) else {
270            return;
271        };
272        let svg = iced::advanced::svg::Svg::new(hatch_handle(bounds.size()))
273            .color(opaque(colour))
274            .opacity(colour.a);
275        iced::advanced::svg::Renderer::draw_svg(renderer, svg, bounds, clip);
276    }
277}
278
279/// The marks of `look` laid over and under `label`: stripes behind a
280/// hatched entry and a line through a struck one. Their colours follow
281/// the theme as it draws.
282pub(super) fn marked<'a, Message: 'a>(
283    label: Element<'a, Message>,
284    paint: Paint,
285    look: style::Look,
286) -> Element<'a, Message> {
287    if !look.hatched() && !look.struck() {
288        return label;
289    }
290    let marks = move |theme: &Theme| style::marked(&Tokens::of(theme), paint, look, Status::Active);
291    let mut layers = stack![];
292    if look.hatched() {
293        layers = layers.push(Element::new(Hatch {
294            colour: move |theme: &Theme| marks(theme).hatch,
295        }));
296    }
297    layers = layers.push(label);
298    if look.struck() {
299        layers = layers.push(
300            container(
301                container(Space::new())
302                    .width(Length::Fill)
303                    .height(Length::Fixed(1.0))
304                    .style(move |theme: &Theme| container::Style {
305                        background: marks(theme).strike.map(Background::Color),
306                        ..container::Style::default()
307                    }),
308            )
309            .center_y(Length::Fill)
310            .width(Length::Fill),
311        );
312    }
313    layers.into()
314}
315
316/// How `entry` is drawn, given what is selected and pending.
317pub(super) fn look_of(state: &State, entry: &Entry, selected: bool) -> style::Look {
318    let removing = state.pending().is_some_and(|pending| {
319        pending.change == Change::Removed && pending.entry.id() == entry.id()
320    });
321    style::Look {
322        selected,
323        emphasis: if removing {
324            Emphasis::Struck
325        } else {
326            entry.emphasis_of()
327        },
328        preview: state.is_preview(entry.id()),
329    }
330}
331
332/// An entry's icon at `size`: muted, or in the entry's text colour when
333/// it is selected and filled with its paint, with its label as a tooltip.
334pub(super) fn entry_icon<'a, Message: 'a>(
335    entry: &Entry,
336    look: style::Look,
337    paint: Paint,
338    size: f32,
339) -> Option<Element<'a, Message>> {
340    let glyph = entry.icon_of()?;
341    let icon = themed(glyph, size, 1.0, move |theme: &Theme| {
342        let tokens = Tokens::of(theme);
343        if look.selected && !look.preview {
344            return style::marked(&tokens, paint, look, Status::Active)
345                .chip
346                .foreground;
347        }
348        tokens.muted_foreground
349    });
350    Some(match entry.icon_label_of() {
351        Some(label) => tooltip(icon, label.to_owned()).into(),
352        None => icon.into(),
353    })
354}
355
356/// An entry's icon, which is never cut off, then its label, which is.
357pub(super) fn labelled<'a, Message: 'a>(
358    icon: Option<Element<'a, Message>>,
359    label: String,
360    size: f32,
361    line: f32,
362    colour: impl Fn(&Theme) -> Color + 'a,
363) -> Element<'a, Message> {
364    let label = ellipsis(label).size(size, line).colour(colour);
365    let Some(icon) = icon else {
366        return label.into();
367    };
368    row![icon, label]
369        .spacing(3.0)
370        .align_y(Alignment::Center)
371        .into()
372}
373
374/// `content`, which sends `press`, sending a double press of `selection`
375/// instead when it completes a double click.
376pub(super) fn pressable<'a, Message: Clone + 'a>(
377    state: &State,
378    content: impl Into<Element<'a, Message>>,
379    selection: Selection,
380    on_event: &Handler<'a, Message>,
381) -> Element<'a, Message> {
382    Pressable::new(
383        content,
384        send(on_event, Event::DoublePress(selection)),
385        state.double_click(),
386    )
387    .into()
388}
389
390/// An entry as a bar: its icon and label on a wash of its tone, marked
391/// with its emphasis.
392pub(super) fn chip<'a, Message: Clone + 'a>(
393    state: &State,
394    bar: &Bar,
395    on_event: &Handler<'a, Message>,
396) -> Element<'a, Message> {
397    let Some(entry) = state.shown().get(bar.occurrence.entry) else {
398        return Space::new().into();
399    };
400    let paint = entry.paint_of();
401    let selection = selection_of(&bar.occurrence);
402    let look = look_of(state, entry, state.is_selected(selection));
403    let label = labelled(
404        entry_icon(entry, look, paint, text_size::XS),
405        bar_label(entry.title(), bar, state.time_zone()),
406        text_size::XS,
407        CHIP_HEIGHT,
408        move |theme| {
409            style::marked(&Tokens::of(theme), paint, look, Status::Active)
410                .chip
411                .foreground
412        },
413    );
414    let label = container(label)
415        .padding(Padding::from([0.0, 6.0]))
416        .center_y(Length::Fill)
417        .into();
418    let button = widget::button(marked(label, paint, look))
419        .width(Length::Fill)
420        .height(Length::Fixed(CHIP_HEIGHT))
421        .padding(0)
422        .on_press_maybe(send(on_event, Event::Press(selection)))
423        .style(move |theme, status| style::marked_button(&Tokens::of(theme), paint, look, status));
424    let chip: Element<'a, Message> = container(pressable(state, button, selection, on_event))
425        .id(entry_id(bar.occurrence.entry, bar.occurrence.start))
426        .width(Length::Fill)
427        .into();
428    #[cfg(feature = "icedwright")]
429    let chip = annotate_entry(chip, state, entry, look.selected, on_event.is_some());
430    chip
431}
432
433/// Whether a bar is a timed entry that starts and ends within one day,
434/// which the month shows as a dot, a time and a title with no fill.
435pub fn is_line(bar: &Bar) -> bool {
436    !bar.occurrence.all_day && bar.days() == 1 && !bar.starts_before && !bar.ends_after
437}
438
439/// A timed entry within one day: a dot in its tone, its start and its
440/// title, filled only while selected.
441pub(super) fn line<'a, Message: Clone + 'a>(
442    state: &State,
443    bar: &Bar,
444    on_event: &Handler<'a, Message>,
445) -> Element<'a, Message> {
446    let Some(entry) = state.shown().get(bar.occurrence.entry) else {
447        return Space::new().into();
448    };
449    let paint = entry.paint_of();
450    let selection = selection_of(&bar.occurrence);
451    let look = look_of(state, entry, state.is_selected(selection));
452    let label = labelled(
453        entry_icon(entry, look, paint, text_size::XS),
454        bar_label(entry.title(), bar, state.time_zone()),
455        text_size::XS,
456        CHIP_HEIGHT,
457        move |theme| style::marked_line(&Tokens::of(theme), paint, look, Status::Active).text_color,
458    );
459    let mut content = Row::new().spacing(4.0).align_y(Alignment::Center);
460    if !look.selected {
461        content = content.push(if look.emphasis == Emphasis::Outlined || look.preview {
462            ring(paint, 6.0)
463        } else {
464            dot(paint, 6.0)
465        });
466    }
467    let content = container(content.push(label))
468        .padding(Padding::from([0.0, 4.0]))
469        .center_y(Length::Fill)
470        .into();
471    let button = widget::button(marked(content, paint, look))
472        .width(Length::Fill)
473        .height(Length::Fixed(CHIP_HEIGHT))
474        .padding(0)
475        .on_press_maybe(send(on_event, Event::Press(selection)))
476        .style(move |theme, status| style::marked_line(&Tokens::of(theme), paint, look, status));
477    let line: Element<'a, Message> = container(pressable(state, button, selection, on_event))
478        .id(entry_id(bar.occurrence.entry, bar.occurrence.start))
479        .width(Length::Fill)
480        .into();
481    #[cfg(feature = "icedwright")]
482    let line = annotate_entry(line, state, entry, look.selected, on_event.is_some());
483    line
484}
485
486/// A circle outlined in a paint.
487pub(super) fn ring<'a, Message: 'a>(paint: Paint, size: f32) -> Element<'a, Message> {
488    container(Space::new())
489        .width(Length::Fixed(size))
490        .height(Length::Fixed(size))
491        .style(move |theme: &Theme| container::Style {
492            border: Border {
493                color: style::paint(&Tokens::of(theme), paint),
494                width: 1.5,
495                radius: radius::FULL.into(),
496            },
497            ..container::Style::default()
498        })
499        .into()
500}
501
502/// The count of entries a crowded day could not show. Pressing it opens
503/// the day.
504fn more<'a, Message: Clone + 'a>(
505    date: Date,
506    hidden: usize,
507    on_event: &Handler<'a, Message>,
508) -> Element<'a, Message> {
509    let label = text(format!("+{hidden} more"))
510        .size(text_size::XS)
511        .wrapping(text::Wrapping::None);
512    widget::button(label)
513        .width(Length::Fill)
514        .height(Length::Fixed(CHIP_HEIGHT))
515        .padding(Padding::from([0.0, 6.0]))
516        .clip(true)
517        .on_press_maybe(send(on_event, Event::OpenDay(date)))
518        .style(|theme, status| {
519            let tokens = Tokens::of(theme);
520            let hovered = matches!(status, Status::Hovered | Status::Pressed);
521            widget::button::Style {
522                background: hovered.then_some(Background::Color(tokens.accent)),
523                text_color: tokens.muted_foreground,
524                border: Border {
525                    radius: radius::SM.into(),
526                    ..Border::default()
527                },
528                ..widget::button::Style::default()
529            }
530        })
531        .into()
532}
533
534/// The bars of `fitted` as rows, one per lane, over `days`. The last of
535/// `lanes` also holds the counts of what crowded days left out.
536pub(super) fn lanes<'a, Message: Clone + 'a>(
537    state: &State,
538    days: &[Date],
539    fitted: &Fitted,
540    lanes: usize,
541    on_event: &Handler<'a, Message>,
542) -> Column<'a, Message> {
543    let mut rows = column![].spacing(LANE_GAP);
544    let used = fitted
545        .bars
546        .iter()
547        .map(|bar| bar.lane + 1)
548        .max()
549        .unwrap_or(0);
550    let counted = fitted.hidden.iter().any(|hidden| *hidden > 0);
551    let shown = if counted { lanes } else { used.min(lanes) };
552
553    for lane in 0..shown {
554        let mut row = Row::new().height(Length::Fixed(CHIP_HEIGHT));
555        let mut day = 0;
556        while day < days.len() {
557            let bar = fitted
558                .bars
559                .iter()
560                .find(|bar| bar.lane == lane && bar.first == day);
561            let hidden = fitted.hidden.get(day).copied().unwrap_or(0);
562            let (cell, span): (Element<'a, Message>, usize) = match bar {
563                Some(bar) if is_line(bar) => (line(state, bar, on_event), 1),
564                Some(bar) => (chip(state, bar, on_event), bar.days()),
565                None if lane + 1 == lanes && hidden > 0 => (more(days[day], hidden, on_event), 1),
566                None => (Space::new().into(), 1),
567            };
568            let portion = u16::try_from(span).unwrap_or(1);
569            row = row.push(
570                container(cell)
571                    .padding(Padding::from([0.0, 2.0]))
572                    .width(Length::FillPortion(portion)),
573            );
574            day += span;
575        }
576        rows = rows.push(row);
577    }
578    rows
579}
580
581/// Up to three dots in the paints of a day's entries, for a month too
582/// narrow for bars.
583pub(super) fn dots<'a, Message: 'a>(state: &State, occurrences: &[Occurrence]) -> Row<'a, Message> {
584    let mut row = Row::new().spacing(3.0).align_y(Alignment::Center);
585    for occurrence in occurrences.iter().take(3) {
586        let Some(entry) = state.shown().get(occurrence.entry) else {
587            continue;
588        };
589        row = row.push(dot(entry.paint_of(), 5.0));
590    }
591    row
592}
593
594/// A filled circle in a paint.
595pub(super) fn dot<'a, Message: 'a>(paint: Paint, size: f32) -> Element<'a, Message> {
596    container(Space::new())
597        .width(Length::Fixed(size))
598        .height(Length::Fixed(size))
599        .style(move |theme: &Theme| container::Style {
600            background: Some(Background::Color(style::paint(&Tokens::of(theme), paint))),
601            border: Border {
602                radius: radius::FULL.into(),
603                ..Border::default()
604            },
605            ..container::Style::default()
606        })
607        .into()
608}
609
610/// The lines of a grid: `columns` by `rows` equal cells, drawn between
611/// them and not around the outside.
612pub(super) fn rules<'a, Message: 'a>(columns: usize, rows: usize) -> Element<'a, Message> {
613    Element::new(Rules { columns, rows })
614}
615
616struct Rules {
617    columns: usize,
618    rows: usize,
619}
620
621impl<Message> Widget<Message, Theme, Renderer> for Rules {
622    fn size(&self) -> Size<Length> {
623        Size::new(Length::Fill, Length::Fill)
624    }
625
626    fn layout(
627        &mut self,
628        _tree: &mut Tree,
629        _renderer: &Renderer,
630        limits: &layout::Limits,
631    ) -> layout::Node {
632        layout::Node::new(limits.max())
633    }
634
635    fn draw(
636        &self,
637        _tree: &Tree,
638        renderer: &mut Renderer,
639        theme: &Theme,
640        _style: &renderer::Style,
641        layout: Layout<'_>,
642        _cursor: mouse::Cursor,
643        _viewport: &Rectangle,
644    ) {
645        let bounds = layout.bounds();
646        let colour = style::line(&Tokens::of(theme));
647        let mut line = |bounds: Rectangle| {
648            renderer.fill_quad(
649                renderer::Quad {
650                    bounds,
651                    ..renderer::Quad::default()
652                },
653                colour,
654            );
655        };
656        for column in 1..self.columns {
657            let x = bounds.x + bounds.width * column as f32 / self.columns as f32;
658            line(Rectangle::new(
659                iced::Point::new(x.round(), bounds.y),
660                Size::new(1.0, bounds.height),
661            ));
662        }
663        for row in 1..self.rows {
664            let y = bounds.y + bounds.height * row as f32 / self.rows as f32;
665            line(Rectangle::new(
666                iced::Point::new(bounds.x, y.round()),
667                Size::new(bounds.width, 1.0),
668            ));
669        }
670    }
671}
672
673#[cfg(test)]
674mod tests {
675    use super::*;
676    use crate::data::calendar::entry::{Entries, Entry, EntryId};
677    use crate::data::calendar::layout;
678    use jiff::civil::date;
679
680    fn at(day: i8, hour: i8, minute: i8) -> Timestamp {
681        date(2026, 11, day)
682            .at(hour, minute, 0, 0)
683            .to_zoned_datetime(TimeZone::UTC)
684            .map(|zoned| zoned.timestamp())
685            .unwrap_or_default()
686    }
687
688    #[test]
689    fn times_are_shown_on_the_24_hour_clock_in_the_calendar_time_zone() {
690        assert_eq!(time_label(at(3, 9, 5), &TimeZone::UTC), "09:05");
691        assert_eq!(time_label(at(3, 17, 30), &TimeZone::UTC), "17:30");
692        let Ok(tokyo) = TimeZone::get("Asia/Tokyo") else {
693            panic!("the time zone database is bundled for tests");
694        };
695        assert_eq!(time_label(at(3, 9, 5), &tokyo), "18:05");
696    }
697
698    #[test]
699    fn spans_say_all_day_a_range_or_a_single_time() {
700        let entries = Entries::utc().with([
701            Entry::new(EntryId(1), "Meeting", at(3, 9, 0), at(3, 10, 30)),
702            Entry::new(EntryId(2), "Deadline", at(3, 17, 0), at(3, 17, 0)),
703            Entry::all_day(EntryId(3), "Trip", date(2026, 11, 3), date(2026, 11, 3)),
704        ]);
705        let labels: Vec<_> = entries
706            .on(date(2026, 11, 3))
707            .iter()
708            .map(|occurrence| span_label(occurrence, entries.time_zone()))
709            .collect();
710        assert_eq!(labels, vec!["All day", "09:00 - 10:30", "17:00"]);
711    }
712
713    #[test]
714    fn weekdays_are_capitals_or_a_single_letter() {
715        let thursday = date(2026, 11, 19);
716        assert_eq!(weekday_label(thursday, false), "THU");
717        assert_eq!(weekday_label(thursday, true), "T");
718        assert_eq!(weekday_label(date(2026, 11, 22), false), "SUN");
719    }
720
721    #[test]
722    fn only_timed_entries_within_a_day_are_lines() {
723        let entries = Entries::utc().with([
724            Entry::new(EntryId(1), "Meeting", at(3, 9, 0), at(3, 10, 0)),
725            Entry::new(EntryId(2), "Overnight", at(4, 22, 0), at(5, 2, 0)),
726            Entry::all_day(EntryId(3), "Trip", date(2026, 11, 6), date(2026, 11, 6)),
727            Entry::new(EntryId(4), "Into next week", at(8, 22, 0), at(9, 2, 0)),
728        ]);
729        let week = layout::week_of(date(2026, 11, 3), jiff::civil::Weekday::Monday);
730        let bars = layout::bars(
731            &week,
732            &entries.between(week[0], week[6]),
733            entries.time_zone(),
734        );
735        let lines: Vec<_> = bars
736            .iter()
737            .filter(|bar| is_line(bar))
738            .map(|bar| bar.occurrence.entry.0)
739            .collect();
740        assert_eq!(lines, vec![1]);
741    }
742
743    #[test]
744    fn bars_lead_with_the_time_only_where_a_timed_entry_starts() {
745        let entries = Entries::utc().with([
746            Entry::new(EntryId(1), "Flight", at(8, 22, 0), at(9, 6, 0)),
747            Entry::all_day(EntryId(2), "Trip", date(2026, 11, 3), date(2026, 11, 3)),
748        ]);
749        let label = |week_of: Date, id: u64| {
750            let week = layout::week_of(week_of, jiff::civil::Weekday::Monday);
751            let bars = layout::bars(
752                &week,
753                &entries.between(week[0], week[6]),
754                entries.time_zone(),
755            );
756            let bar = bars.iter().find(|bar| bar.occurrence.entry == EntryId(id));
757            let title = entries.get(EntryId(id)).map(Entry::title);
758            match (bar, title) {
759                (Some(bar), Some(title)) => bar_label(title, bar, entries.time_zone()),
760                _ => String::new(),
761            }
762        };
763        assert_eq!(label(date(2026, 11, 8), 1), "22:00 Flight");
764        assert_eq!(label(date(2026, 11, 9), 1), "Flight", "carried over");
765        assert_eq!(label(date(2026, 11, 3), 2), "Trip");
766    }
767
768    #[test]
769    fn spans_are_described_by_their_days_and_times() {
770        let utc = &TimeZone::UTC;
771        let day = date(2026, 11, 19);
772        assert_eq!(when_label(&When::day(day), utc), "Thu 19 Nov");
773        assert_eq!(
774            when_label(&When::all_day(day, date(2026, 11, 21)), utc),
775            "Thu 19 Nov - Sat 21 Nov"
776        );
777        assert_eq!(
778            when_label(&When::timed(at(19, 10, 0), at(19, 11, 30)), utc),
779            "Thu 19 Nov, 10:00 - 11:30"
780        );
781        assert_eq!(
782            when_label(&When::timed(at(19, 17, 0), at(19, 17, 0)), utc),
783            "Thu 19 Nov, 17:00"
784        );
785        assert_eq!(
786            when_label(&When::timed(at(19, 22, 0), at(20, 2, 0)), utc),
787            "Thu 19 Nov 22:00 - Fri 20 Nov 02:00"
788        );
789        assert_eq!(
790            when_label(&When::timed(at(19, 23, 0), at(20, 0, 0)), utc),
791            "Thu 19 Nov, 23:00 - 00:00",
792            "an end at midnight is the same day"
793        );
794        assert_eq!(
795            when_label(&When::timed(at(19, 23, 0), at(21, 0, 0)), utc),
796            "Thu 19 Nov 23:00 - Sat 21 Nov 00:00"
797        );
798    }
799
800    #[test]
801    fn without_a_handler_nothing_is_sent() {
802        let none: Handler<'_, Event> = None;
803        assert_eq!(send(&none, Event::Next), None);
804        let some: Handler<'_, Event> = Some(Rc::new(|event| event));
805        assert_eq!(send(&some, Event::Next), Some(Event::Next));
806    }
807}