Skip to main content

iced_cube/data/calendar/
mod.rs

1//! A calendar of entries with day, week, month, year, schedule and
2//! four-day views, and triggers that tell the app when an entry is
3//! created, is due or is about to be.
4//!
5//! The header has a Today button, arrows, the period in words and a menu
6//! of the [`View`]s. Day, week and four days put days side by side
7//! against the hours; the month is a grid of weeks with whole-day entries
8//! as bars and timed ones as a dot, a time and a title; the year is
9//! twelve small months; and the schedule lists the month's entries with
10//! each day's date beside them.
11//!
12//! [`State`] holds the [`Entries`], the [`View`], the period on show and
13//! the selection. Its [`update`](State::update) applies an [`Event`] and
14//! returns an [`Output`] for the things an app acts on: an entry was
15//! opened, a new one was asked for, an entry changed, another period came
16//! on show. The calendar never reads the clock; today's date and the
17//! current time are passed in.
18//!
19//! ```no_run
20//! use iced::Element;
21//! use iced_cube::data::calendar::{self, Entry, EntryId, Output, calendar};
22//! use jiff::Timestamp;
23//!
24//! #[derive(Debug, Clone)]
25//! enum Message {
26//!     Calendar(calendar::Event),
27//! }
28//!
29//! struct App {
30//!     calendar: calendar::State,
31//! }
32//!
33//! impl App {
34//!     fn new(now: Timestamp) -> Self {
35//!         Self {
36//!             calendar: calendar::State::at(now, calendar::Entries::system()),
37//!         }
38//!     }
39//!
40//!     fn update(&mut self, message: Message) {
41//!         let Message::Calendar(event) = message;
42//!         match self.calendar.update(event) {
43//!             // The user pressed a day twice or dragged out a time.
44//!             Some(Output::Requested(draft)) => {
45//!                 let id = self.calendar.entries().next_id();
46//!                 let entry = Entry::at(id, "New entry", draft.when);
47//!                 let _ = self.calendar.update(calendar::Event::Insert(entry));
48//!             }
49//!             Some(Output::Opened { entry, .. }) => println!("open {entry:?}"),
50//!             _ => {}
51//!         }
52//!     }
53//!
54//!     fn view(&self) -> Element<'_, Message> {
55//!         calendar(&self.calendar).on_event(Message::Calendar).into()
56//!     }
57//! }
58//! ```
59//!
60//! # Entries
61//!
62//! An [`Entry`] is timed, from one instant up to another, or covers whole
63//! days. It can [repeat](Repeat) daily, weekly, monthly or yearly. Timed
64//! entries are stored as instants and shown in the time zone of the
65//! [`Entries`] collection, so changing the time zone moves what is drawn
66//! and not what is stored.
67//!
68//! # Selecting and activating
69//!
70//! The first press on a day, a time slot or an entry selects it. A press
71//! on what is already selected activates it: an entry is
72//! [opened](Output::Opened), and a day or a slot [asks](Output::Requested)
73//! for a new entry there. Two quick presses therefore open or create, and
74//! so do two taps on a touch screen. In the week and day views a drag on
75//! empty space asks for an entry of that length, a drag on an entry moves
76//! it, and a drag on its top or lower edge changes when it starts or ends.
77//!
78//! The calendar only asks; the app decides what to show. [`editor`] is a
79//! ready-made form for that: title, all day, start and end date and time,
80//! how often it repeats and when that stops, colour, location and notes.
81//!
82//! # Triggers
83//!
84//! See [`schedule`] for telling the app when entries are created, due or
85//! almost due, including the ones missed while the app was not running.
86//!
87//! # Keyboard
88//!
89//! Shortcuts resolve through a [`Keymap`](crate::keys::Keymap) of
90//! [`Action`]s; see [`default_keymap`] and [`crate::keys`].
91
92mod agenda;
93pub mod editor;
94pub mod entry;
95mod gesture;
96pub mod layout;
97mod month;
98mod parts;
99pub mod repeat;
100pub mod rules;
101pub mod schedule;
102mod state;
103pub mod style;
104mod time_grid;
105mod year;
106
107use std::ops::Range;
108use std::rc::Rc;
109
110use iced::widget::{self, column, container, responsive, row, text};
111use iced::{Alignment, Element, Length, Theme};
112
113pub use entry::{
114    Change, Changed, Draft, Emphasis, Entries, Entry, EntryId, Occurrence, Paint, Tone, When,
115    instant,
116};
117/// The date and time library the calendar's types come from, so an app
118/// can use the same version without depending on it directly.
119pub use jiff;
120pub use parts::{
121    bar_label, day_id, entry_id, is_line, span_label, time_label, weekday_label, when_label,
122};
123pub use repeat::{Ends, Frequency, Repeat};
124pub use state::{
125    Action, Allow, DOUBLE_CLICK, Event, FOUR_DAYS, Output, SLOT_MINUTES, Selection, State, View,
126    default_keymap,
127};
128pub use time_grid::{
129    GUTTER, SNAP_MINUTES, hour_offset, hours_id, point_at, scroll_id, scroll_to_hour,
130};
131
132use crate::forms::select::select;
133use crate::lucide;
134use crate::primitives::button::{self, Size, button};
135use crate::primitives::icon_button::{self, icon_button};
136use crate::theme::{self, Tokens, space, text_size};
137use parts::{Handler, send};
138
139/// The height of an hour in the week and day views unless set.
140pub const DEFAULT_HOUR_HEIGHT: f32 = 48.0;
141
142/// The least an hour can be set to in the week and day views.
143pub const MIN_HOUR_HEIGHT: f32 = 36.0;
144
145/// The width below which the header puts the navigation buttons on a
146/// second line.
147pub const HEADER_BREAK: f32 = 520.0;
148
149/// The width of the menu of views in the header.
150pub const VIEW_MENU_WIDTH: f32 = 124.0;
151
152/// The id of the header's Today button.
153pub fn today_button_id() -> widget::Id {
154    widget::Id::new("iced-cube-calendar-today")
155}
156
157/// The id of the header's button to the previous period.
158pub fn previous_button_id() -> widget::Id {
159    widget::Id::new("iced-cube-calendar-previous")
160}
161
162/// The id of the header's button to the next period.
163pub fn next_button_id() -> widget::Id {
164    widget::Id::new("iced-cube-calendar-next")
165}
166
167/// The id of the header's menu of views.
168pub fn view_menu_id() -> widget::Id {
169    widget::Id::new("iced-cube-calendar-views")
170}
171
172/// A calendar builder. Convert it into an [`Element`] to render.
173pub struct Calendar<'a, Message> {
174    state: &'a State,
175    on_event: Option<Box<dyn Fn(Event) -> Message + 'a>>,
176    width: Length,
177    height: Length,
178    header: bool,
179    leading: Option<Element<'a, Message>>,
180    trailing: Option<Element<'a, Message>>,
181    hours: (u8, u8),
182    hour_height: f32,
183    start_hour: Option<u8>,
184}
185
186/// Renders `state`. Without [`on_event`](Calendar::on_event) it renders
187/// disabled: nothing can be pressed or dragged.
188pub fn calendar<Message>(state: &State) -> Calendar<'_, Message> {
189    Calendar {
190        state,
191        on_event: None,
192        width: Length::Fill,
193        height: Length::Fill,
194        header: true,
195        leading: None,
196        trailing: None,
197        hours: (0, 24),
198        hour_height: DEFAULT_HOUR_HEIGHT,
199        start_hour: None,
200    }
201}
202
203impl<Message> std::fmt::Debug for Calendar<'_, Message> {
204    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
205        f.debug_struct("Calendar")
206            .field("view", &self.state.view())
207            .field("cursor", &self.state.cursor())
208            .field("width", &self.width)
209            .field("height", &self.height)
210            .field("header", &self.header)
211            .field("leading", &self.leading.is_some())
212            .field("trailing", &self.trailing.is_some())
213            .field("hours", &self.hours)
214            .field("hour_height", &self.hour_height)
215            .field("start_hour", &self.start_hour)
216            .field("enabled", &self.on_event.is_some())
217            .finish()
218    }
219}
220
221impl<'a, Message> Calendar<'a, Message> {
222    pub fn on_event(mut self, on_event: impl Fn(Event) -> Message + 'a) -> Self {
223        self.on_event = Some(Box::new(on_event));
224        self
225    }
226
227    pub fn width(mut self, width: impl Into<Length>) -> Self {
228        self.width = width.into();
229        self
230    }
231
232    /// The height of the whole calendar. It fills the space it is given by
233    /// default, so give it a fixed height inside anything that scrolls.
234    pub fn height(mut self, height: impl Into<Length>) -> Self {
235        self.height = height.into();
236        self
237    }
238
239    /// Whether to show the Today button, the arrows, the title and the
240    /// menu of views. Turn it off to build your own from [`State::title`]
241    /// and the navigation [`Event`]s.
242    pub fn header(mut self, header: bool) -> Self {
243        self.header = header;
244        self
245    }
246
247    /// Something of the app's at the start of the header, before Today,
248    /// such as a button for a new entry.
249    pub fn header_leading(mut self, element: impl Into<Element<'a, Message>>) -> Self {
250        self.leading = Some(element.into());
251        self
252    }
253
254    /// Something of the app's at the end of the header, after the menu of
255    /// views.
256    pub fn header_trailing(mut self, element: impl Into<Element<'a, Message>>) -> Self {
257        self.trailing = Some(element.into());
258        self
259    }
260
261    /// Scrolls a whole-day week or day view to `hour` whenever a timed
262    /// view comes on show and when Today is pressed, so the working day is
263    /// in view instead of midnight. Off by default.
264    pub fn start_at_hour(mut self, hour: u8) -> Self {
265        self.start_hour = Some(hour.min(23));
266        self
267    }
268
269    /// The hours the week and day views show, such as `8..18` for a
270    /// working day. Defaults to the whole day, which scrolls.
271    pub fn hours(mut self, hours: Range<u8>) -> Self {
272        let first = hours.start.min(23);
273        self.hours = (first, hours.end.clamp(first + 1, 24));
274        self
275    }
276
277    /// The least height of an hour in the week and day views, which is at
278    /// least [`MIN_HOUR_HEIGHT`] so a half-hour entry still has room for
279    /// its title. Hours grow past it to fill the space when the ones on
280    /// show would leave room below, and scroll when they do not fit.
281    pub fn hour_height(mut self, height: f32) -> Self {
282        self.hour_height = height.max(MIN_HOUR_HEIGHT);
283        self
284    }
285}
286
287impl<'a, Message: Clone + 'a> From<Calendar<'a, Message>> for Element<'a, Message> {
288    fn from(calendar: Calendar<'a, Message>) -> Self {
289        let Calendar {
290            state,
291            on_event,
292            width,
293            height,
294            header,
295            leading,
296            trailing,
297            hours,
298            hour_height,
299            start_hour,
300        } = calendar;
301        let on_event: Handler<'a, Message> = on_event.map(Rc::from);
302        let options = time_grid::Options {
303            hours,
304            hour_height,
305            start_hour,
306        };
307
308        let body = match state.view() {
309            View::Month => month::view(state, &on_event),
310            View::Year => year::view(state, &on_event),
311            View::Agenda => agenda::view(state, &on_event),
312            View::Day | View::Week | View::FourDays => time_grid::view(state, options, &on_event),
313        };
314        let framed = container(body)
315            .width(Length::Fill)
316            .height(Length::Fill)
317            .padding(1)
318            .clip(true)
319            .style(|theme: &Theme| style::frame(&Tokens::of(theme)));
320
321        let mut content = column![].spacing(space::MD).width(width).height(height);
322        if header {
323            content = content.push(self::header(state, on_event.clone(), leading, trailing));
324        }
325        let content = content.push(framed);
326        #[cfg(feature = "icedwright")]
327        let content = icedwright_probe::semantic(content)
328            .role(icedwright_probe::role::Region)
329            .name("Calendar")
330            .description(state.title())
331            .component("iced_cube::calendar");
332        content.into()
333    }
334}
335
336/// The app's leading element, the Today button and arrows, the title, the
337/// menu of views and the app's trailing element.
338fn header<'a, Message: Clone + 'a>(
339    state: &'a State,
340    on_event: Handler<'a, Message>,
341    leading: Option<Element<'a, Message>>,
342    trailing: Option<Element<'a, Message>>,
343) -> Element<'a, Message> {
344    // The app's slots sit outside the part that rearranges itself on a
345    // narrow screen, since an element can only be placed once.
346    let adaptive = responsive(move |size| {
347        let step = |glyph, label: &'static str, event: Event, id: widget::Id| {
348            icon_button(glyph)
349                .label(label)
350                .id(id)
351                .variant(icon_button::Variant::Ghost)
352                .size(Size::Md)
353                .on_press_maybe(send(&on_event, event))
354        };
355        let navigation = row![
356            container(
357                button("Today")
358                    .variant(button::Variant::Outline)
359                    .size(Size::Md)
360                    .on_press_maybe(send(&on_event, Event::Today))
361            )
362            .id(today_button_id()),
363            step(
364                lucide!(ChevronLeft),
365                "Previous",
366                Event::Previous,
367                previous_button_id()
368            ),
369            step(lucide!(ChevronRight), "Next", Event::Next, next_button_id()),
370        ]
371        .spacing(space::XS)
372        .align_y(Alignment::Center);
373
374        let narrow = size.width < HEADER_BREAK;
375        let title = if narrow {
376            state.short_title()
377        } else {
378            state.title()
379        };
380        let title = text(title)
381            .size(if narrow { text_size::SM } else { text_size::MD })
382            .font(theme::semibold())
383            .wrapping(text::Wrapping::None)
384            .style(|theme: &Theme| text::Style {
385                color: Some(Tokens::of(theme).foreground),
386            });
387
388        let views = container(
389            select(&View::ALL[..], Some(state.view()))
390                .width(VIEW_MENU_WIDTH)
391                .on_select_maybe(
392                    on_event
393                        .clone()
394                        .map(|handler| move |view| handler(Event::Show(view))),
395                ),
396        )
397        .id(view_menu_id());
398        let title = container(title).width(Length::Fill).clip(true);
399
400        // A phone has the title beside the menu and the buttons below.
401        if narrow {
402            let lead = row![title, views]
403                .spacing(space::SM)
404                .align_y(Alignment::Center);
405            return column![lead, navigation].spacing(space::SM).into();
406        }
407        row![navigation, title, views]
408            .spacing(space::MD)
409            .align_y(Alignment::Center)
410            .into()
411    })
412    .width(Length::Fill)
413    .height(Length::Shrink);
414
415    if leading.is_none() && trailing.is_none() {
416        return adaptive.into();
417    }
418    let mut header = row![].spacing(space::XS).align_y(Alignment::Center);
419    if let Some(leading) = leading {
420        header = header.push(leading);
421    }
422    header = header.push(adaptive);
423    if let Some(trailing) = trailing {
424        header = header.push(trailing);
425    }
426    header.width(Length::Fill).into()
427}
428
429#[cfg(test)]
430mod tests {
431    use super::*;
432    use jiff::civil::date;
433
434    #[test]
435    fn builder_defaults_and_options() {
436        let state = State::new(date(2026, 11, 19));
437        let calendar: Calendar<'_, Event> = calendar(&state);
438        assert_eq!(calendar.width, Length::Fill);
439        assert_eq!(calendar.height, Length::Fill);
440        assert!(calendar.header);
441        assert_eq!(calendar.hours, (0, 24));
442        assert_eq!(calendar.hour_height, DEFAULT_HOUR_HEIGHT);
443        assert!(calendar.on_event.is_none());
444
445        let calendar = calendar
446            .width(400)
447            .height(300)
448            .header(false)
449            .hours(8..18)
450            .hour_height(60.0)
451            .on_event(|event| event);
452        assert_eq!(calendar.width, Length::Fixed(400.0));
453        assert_eq!(calendar.height, Length::Fixed(300.0));
454        assert!(!calendar.header);
455        assert_eq!(calendar.hours, (8, 18));
456        assert_eq!(calendar.hour_height, 60.0);
457        assert!(calendar.on_event.is_some());
458        assert!(format!("{calendar:?}").contains("enabled: true"));
459    }
460
461    #[test]
462    fn hours_and_hour_height_stay_in_range() {
463        let state = State::new(date(2026, 11, 19));
464        let hours = |range: Range<u8>| calendar::<Event>(&state).hours(range).hours;
465        assert_eq!(hours(0..24), (0, 24));
466        assert_eq!(hours(9..9), (9, 10));
467        assert_eq!(hours(20..99), (20, 24));
468        assert_eq!(hours(40..50), (23, 24));
469        #[allow(clippy::reversed_empty_ranges)]
470        let backwards = hours(18..8);
471        assert_eq!(backwards, (18, 19));
472        assert_eq!(
473            calendar::<Event>(&state).hour_height(2.0).hour_height,
474            MIN_HOUR_HEIGHT
475        );
476    }
477}