1use crate::{
2 ControlAction, Node,
3 picker::{PickerSession, append_picker_dialog},
4};
5use std::fmt;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
9pub struct Date {
10 pub year: i64,
11 pub month: i64,
12 pub day: i64,
13}
14
15impl Default for Date {
16 fn default() -> Self {
17 Self {
18 year: 1970,
19 month: 1,
20 day: 1,
21 }
22 }
23}
24
25impl fmt::Display for Date {
26 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27 write!(f, "{:04}-{:02}-{:02}", self.year, self.month, self.day)
28 }
29}
30
31impl Date {
32 pub const MIN: Self = Self {
33 year: 1,
34 month: 1,
35 day: 1,
36 };
37 pub const MAX: Self = Self {
38 year: 9999,
39 month: 12,
40 day: 31,
41 };
42
43 pub fn new(year: i64, month: i64, day: i64) -> Option<Self> {
44 let date = Self { year, month, day };
45 date.valid().then_some(date)
46 }
47
48 pub fn valid(self) -> bool {
49 (1..=9999).contains(&self.year) && (1..=self.month_length()).contains(&self.day)
50 }
51
52 pub fn first_of_month(self) -> Self {
53 Self { day: 1, ..self }
54 }
55
56 pub fn last_of_month(self) -> Self {
57 Self {
58 day: self.month_length(),
59 ..self
60 }
61 }
62
63 fn month_length(self) -> i64 {
64 match self.month {
65 4 | 6 | 9 | 11 => 30,
66 2 => {
67 28 + i64::from(self.year % 4 == 0 && (self.year % 100 != 0 || self.year % 400 == 0))
68 }
69 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
70 _ => 0,
71 }
72 }
73
74 fn days_before_year(year: i64) -> i64 {
75 let prior = year - 1;
76 prior * 365 + prior / 4 - prior / 100 + prior / 400
77 }
78
79 fn ordinal(self) -> i64 {
80 Self::days_before_year(self.year) + self.day - 1
81 + (1..self.month)
82 .map(|month| Self { month, ..self }.month_length())
83 .sum::<i64>()
84 }
85
86 pub fn add_days(self, days: i64) -> Option<Self> {
87 if !self.valid() {
88 return None;
89 }
90 let ordinal = self.ordinal().checked_add(days)?;
91 if !(0..Self::days_before_year(10_000)).contains(&ordinal) {
92 return None;
93 }
94 let (mut year, mut end) = (1, 10_000);
95 while end - year > 1 {
96 let middle = (year + end) / 2;
97 if Self::days_before_year(middle) <= ordinal {
98 year = middle;
99 } else {
100 end = middle;
101 }
102 }
103 let mut day = ordinal - Self::days_before_year(year) + 1;
104 for month in 1..=12 {
105 let date = Self { year, month, day };
106 let count = date.month_length();
107 if day <= count {
108 return Some(date);
109 }
110 day -= count;
111 }
112 None
113 }
114
115 fn add_months(self, months: i64) -> Option<Self> {
116 if !self.valid() {
117 return None;
118 }
119 let index = ((self.year - 1) * 12 + self.month - 1).checked_add(months)?;
120 Self::new(index.div_euclid(12) + 1, index.rem_euclid(12) + 1, 1)
121 }
122}
123
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub enum CalendarAction {
126 Select(Date),
127 Browse(Date),
128}
129
130#[derive(Clone, Copy, Debug, PartialEq, Eq)]
131pub struct CalendarState {
132 pub minimum: Date,
133 pub maximum: Date,
134 pub selected: Date,
135 pub month: Date,
137}
138
139#[doc(hidden)]
140#[derive(Clone, Copy)]
141pub struct DateBounds {
142 minimum: Date,
143 maximum: Date,
144}
145
146impl DateBounds {
147 pub fn new(minimum: Date, maximum: Date) -> Self {
148 let minimum = if minimum.valid() { minimum } else { Date::MIN };
149 let maximum = if maximum.valid() { maximum } else { Date::MAX };
150 Self {
151 minimum,
152 maximum: maximum.max(minimum),
153 }
154 }
155
156 fn from_node(node: &Node) -> Self {
157 Self::new(
158 node.date("minimum-date").unwrap_or(Date::MIN),
159 node.date("maximum-date").unwrap_or(Date::MAX),
160 )
161 }
162
163 fn constrain(self, date: Date) -> Date {
164 let date = if date.valid() { date } else { Date::default() };
165 date.clamp(self.minimum, self.maximum)
166 }
167}
168
169impl CalendarState {
170 pub fn from_node(node: &Node) -> Self {
171 Self::with_bounds(
172 node.date("date").unwrap_or_default(),
173 node.date("display-month"),
174 DateBounds::from_node(node),
175 )
176 }
177
178 fn with_bounds(date: Date, month: Option<Date>, bounds: DateBounds) -> Self {
179 let selected = bounds.constrain(date);
180 let month = bounds
181 .constrain(month.filter(|date| date.valid()).unwrap_or(selected))
182 .first_of_month();
183 Self {
184 minimum: bounds.minimum,
185 maximum: bounds.maximum,
186 selected,
187 month,
188 }
189 }
190
191 pub fn allows(self, date: Date) -> bool {
192 date.valid() && (self.minimum..=self.maximum).contains(&date)
193 }
194
195 pub fn allows_month(self, month: Date) -> bool {
196 month.valid()
197 && month.day == 1
198 && month <= self.maximum
199 && month.last_of_month() >= self.minimum
200 }
201
202 pub fn adjacent_month(self, months: i64) -> Option<Date> {
203 self.month
204 .add_months(months)
205 .filter(|&date| self.allows_month(date))
206 }
207
208 pub fn cursor(self) -> Date {
209 if self.selected.first_of_month() == self.month {
210 self.selected
211 } else {
212 self.month.max(self.minimum)
213 }
214 }
215
216 pub fn cells(self, week_start: i64) -> [Option<Date>; 42] {
218 if !self.month.valid() {
219 return [None; 42];
220 }
221 let offset = (self.month.ordinal() - (week_start.clamp(1, 7) - 1)).rem_euclid(7);
222 std::array::from_fn(|index| self.month.add_days(index as i64 - offset))
223 }
224}
225
226#[doc(hidden)]
228#[derive(Default)]
229pub struct DatePopupState(PickerSession<(Date, Date)>);
230
231impl DatePopupState {
232 pub fn close(&self) {
233 self.0.close();
234 }
235
236 pub fn populate(&self, dialog: &mut Node, date: impl FnOnce() -> Date) {
237 let bounds = DateBounds::from_node(dialog);
238 let Some((date, month)) = self.0.begin(dialog, || {
239 let date = bounds.constrain(date());
240 (date, date.first_of_month())
241 }) else {
242 return;
243 };
244 let state = CalendarState::with_bounds(date, Some(month), bounds);
245 let mut calendar = Node::new("Calendar", None);
246 for key in [
247 "week-start",
248 "weekday-labels",
249 "font-size",
250 "font-family",
251 "font-weight",
252 "font-italic",
253 ] {
254 if let Some(value) = dialog.properties.get(key) {
255 calendar.properties.insert(key, value.clone());
256 }
257 }
258 calendar.properties.insert("date", state.selected.into());
259 calendar
260 .properties
261 .insert("display-month", state.month.into());
262 calendar
263 .properties
264 .insert("minimum-date", state.minimum.into());
265 calendar
266 .properties
267 .insert("maximum-date", state.maximum.into());
268 self.0.stamp(&mut calendar);
269 append_picker_dialog(dialog, calendar);
270 }
271
272 pub fn edit(&self, bounds: DateBounds, node: &Node, action: ControlAction) -> bool {
273 let (Some((date, month)), ControlAction::Calendar(action)) = (self.0.current(node), action)
274 else {
275 return false;
276 };
277 let state = CalendarState::with_bounds(date, Some(month), bounds);
278 if node.kind != "Calendar" || CalendarState::from_node(node) != state {
279 return false;
280 }
281 let next = match action {
282 CalendarAction::Select(date) if state.allows(date) => (date, date.first_of_month()),
283 CalendarAction::Browse(month) if state.allows_month(month) => (state.selected, month),
284 _ => return false,
285 };
286 if next == (state.selected, state.month) {
287 return false;
288 }
289 self.0.set(next);
290 true
291 }
292
293 pub fn finish(&self, bounds: DateBounds, dialog: &Node) -> Option<Date> {
294 self.0
295 .finish(dialog)
296 .map(|(date, _)| bounds.constrain(date))
297 }
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303
304 #[test]
305 fn gregorian_arithmetic_handles_leap_centuries_and_calendar_limits() {
306 let date = |year, month, day| Date::new(year, month, day).unwrap();
307 assert_eq!(date(1900, 2, 28).add_days(1), Some(date(1900, 3, 1)));
308 assert_eq!(date(2000, 2, 28).add_days(1), Some(date(2000, 2, 29)));
309 assert_eq!(date(2025, 1, 1).add_days(-1), Some(date(2024, 12, 31)));
310 assert_eq!(
311 date(1970, 1, 1).add_days(20_000).unwrap().add_days(-20_000),
312 Some(Date::default())
313 );
314 assert_eq!(Date::MIN.add_days(-1), None);
315 assert_eq!(Date::MAX.add_days(1), None);
316 assert_eq!(Date::MIN.add_days(i64::MAX), None);
317 }
318
319 #[test]
320 fn date_bounds_disable_cells_and_week_start_changes_the_first_column() {
321 let mut node = Node::new("Calendar", None);
322 let date = |month, day| Date::new(2024, month, day).unwrap();
323 node.properties.insert("date", date(2, 29).into());
324 node.properties.insert("minimum-date", date(2, 20).into());
325 node.properties.insert("maximum-date", date(3, 5).into());
326 let calendar = CalendarState::from_node(&node);
327 assert_eq!(calendar.cells(1)[0], Some(date(1, 29)));
328 assert_eq!(calendar.cells(7)[0], Some(date(1, 28)));
329 assert!(calendar.cells(1).contains(&Some(date(2, 29))));
330 assert!(!calendar.allows(date(2, 19)));
331 assert!(calendar.allows(date(3, 5)));
332 assert_eq!(calendar.adjacent_month(-1), None);
333 assert_eq!(calendar.adjacent_month(1), Some(date(3, 1)));
334 }
335}