1use crate::{LayoutNode, Point, Rect, Size, TextMeasurer, place_in_direction};
2use xrack_runtime::{
3 CalendarAction, CalendarHighlight, CalendarHighlightDay, CalendarState, Date, LayoutDirection,
4 Node,
5};
6
7const WEEKDAYS: [&str; 7] = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
8
9#[derive(Clone, Copy, PartialEq, Eq)]
10enum CalendarPart {
11 Calendar,
12 MonthGrid,
13 DayOfWeekRow,
14 WeekNumberColumn,
15}
16
17impl CalendarPart {
18 fn dimensions(self) -> (usize, usize) {
19 match self {
20 Self::Calendar => (7, 8),
21 Self::MonthGrid => (7, 6),
22 Self::DayOfWeekRow => (7, 1),
23 Self::WeekNumberColumn => (1, 6),
24 }
25 }
26
27 fn from_node(node: &Node) -> Self {
28 match node.kind {
29 "MonthGrid" => Self::MonthGrid,
30 "DayOfWeekRow" => Self::DayOfWeekRow,
31 "WeekNumberColumn" => Self::WeekNumberColumn,
32 _ => Self::Calendar,
33 }
34 }
35
36 fn cell(
37 self,
38 bounds: Rect,
39 column: usize,
40 row: usize,
41 span: usize,
42 direction: LayoutDirection,
43 ) -> Rect {
44 let (columns, rows) = self.dimensions();
45 let width = bounds.width / columns as f32;
46 let height = bounds.height / rows as f32;
47 let rect = Rect::new(
48 bounds.x + width * column as f32,
49 bounds.y + height * row as f32,
50 width * span as f32,
51 height,
52 );
53 place_in_direction(rect, bounds, direction)
54 }
55}
56
57pub(crate) fn preferred_size(node: &Node, text: &impl TextMeasurer) -> Size {
58 let part = CalendarPart::from_node(node);
59 let mut size = match part {
60 CalendarPart::Calendar => Size::new(294.0, 300.0),
61 CalendarPart::MonthGrid => Size::new(294.0, 216.0),
62 CalendarPart::DayOfWeekRow => Size::new(294.0, 32.0),
63 CalendarPart::WeekNumberColumn => Size::new(44.0, 216.0),
64 };
65 if text.text_scale() > 1.0 {
66 let row_height = (text.font_size(node) * 1.8 + 4.0).max(44.0);
67 size.height = size.height.max(row_height * part.dimensions().1 as f32);
68 }
69 size
70}
71
72pub(crate) fn month_cell(bounds: Rect, slot: usize, direction: LayoutDirection) -> Rect {
73 CalendarPart::MonthGrid.cell(bounds, slot % 7, slot / 7, 1, direction)
74}
75
76pub struct CalendarGeometry {
77 bounds: Rect,
78 part: CalendarPart,
79 pub state: CalendarState,
80 pub layout_direction: LayoutDirection,
81 cells: [Option<Date>; 42],
82 week_start: usize,
83 today: Option<Date>,
84 highlight: CalendarHighlight,
85}
86
87#[derive(Clone, Copy)]
88pub struct CalendarDay {
89 pub date: Date,
90 pub slot: usize,
91 pub bounds: Rect,
92 pub enabled: bool,
93 pub selected: bool,
94 pub in_month: bool,
95 pub today: bool,
96 pub highlight: CalendarHighlightDay,
97}
98
99#[derive(Clone, Copy)]
100pub struct CalendarWeek {
101 pub year: i64,
102 pub number: i64,
103 pub bounds: Rect,
104}
105
106impl CalendarGeometry {
107 pub fn new(node: &Node, bounds: Rect) -> Self {
108 Self::with_layout_direction(node, bounds, node.layout_direction().unwrap_or_default())
109 }
110
111 pub fn for_layout(node: &Node, layout: &LayoutNode) -> Self {
112 Self::with_layout_direction(node, layout.bounds, layout.layout_direction)
113 }
114
115 fn with_layout_direction(node: &Node, bounds: Rect, direction: LayoutDirection) -> Self {
116 let state = CalendarState::from_node(node);
117 let week_start = node.int("week-start").unwrap_or(1).clamp(1, 7);
118 let part = CalendarPart::from_node(node);
119 let cells = if part == CalendarPart::DayOfWeekRow {
120 [None; 42]
121 } else {
122 state.cells(week_start)
123 };
124 let highlight = CalendarHighlight::from_node(node, state.fixed_month);
125 Self {
126 bounds,
127 part,
128 state,
129 layout_direction: direction,
130 cells,
131 week_start: week_start as usize - 1,
132 today: node.date("today"),
133 highlight,
134 }
135 }
136
137 fn cell(&self, column: usize, row: usize, span: usize) -> Rect {
138 self.part
139 .cell(self.bounds, column, row, span, self.layout_direction)
140 }
141
142 pub fn has_header(&self) -> bool {
143 self.part == CalendarPart::Calendar
144 }
145
146 pub fn title(&self) -> Rect {
147 self.cell(1, 0, 5)
148 }
149
150 pub fn navigation(&self) -> [(Rect, Option<CalendarAction>); 2] {
151 if !self.has_header() {
152 return [(Rect::default(), None); 2];
153 }
154 [
155 (
156 self.cell(0, 0, 1),
157 self.state.adjacent_month(-1).map(CalendarAction::Browse),
158 ),
159 (
160 self.cell(6, 0, 1),
161 self.state.adjacent_month(1).map(CalendarAction::Browse),
162 ),
163 ]
164 }
165
166 pub fn weekdays<'a>(&'a self, node: &'a Node) -> impl Iterator<Item = (Rect, &'a str)> + 'a {
167 let labels = node.strings("weekday-labels");
168 let count = if matches!(
169 self.part,
170 CalendarPart::Calendar | CalendarPart::DayOfWeekRow
171 ) {
172 7
173 } else {
174 0
175 };
176 (0..count).map(move |column| {
177 let day = (self.week_start + column) % 7;
178 let label = labels.get(day).map_or(WEEKDAYS[day], String::as_str);
179 (self.cell(column, usize::from(self.has_header()), 1), label)
180 })
181 }
182
183 pub fn days(&self) -> impl Iterator<Item = CalendarDay> + '_ {
184 let count = if matches!(self.part, CalendarPart::Calendar | CalendarPart::MonthGrid) {
185 42
186 } else {
187 0
188 };
189 self.cells[..count]
190 .iter()
191 .enumerate()
192 .filter_map(|(index, &date)| {
193 let date = date?;
194 let in_month = self.state.month == date.first_of_month();
195 Some(CalendarDay {
196 date,
197 slot: index,
198 bounds: if self.part == CalendarPart::MonthGrid {
199 month_cell(self.bounds, index, self.layout_direction)
200 } else {
201 self.cell(index % 7, 2 + index / 7, 1)
202 },
203 enabled: self.state.allows(date),
204 selected: self.state.selected == date && self.state.allows(date),
205 in_month,
206 highlight: self.highlight.day(date, in_month),
207 today: self.today == Some(date),
208 })
209 })
210 }
211
212 pub fn weeks(&self) -> impl Iterator<Item = CalendarWeek> + '_ {
213 let count = if self.part == CalendarPart::WeekNumberColumn {
214 42
215 } else {
216 0
217 };
218 let thursday = (10 - self.week_start) % 7;
219 self.cells[..count]
220 .chunks_exact(7)
221 .enumerate()
222 .filter_map(move |(row, week)| {
223 let date = week[thursday].or_else(|| week.iter().flatten().next().copied())?;
226 let (year, number) = date.iso_week()?;
227 Some(CalendarWeek {
228 year,
229 number,
230 bounds: self.cell(0, row, 1),
231 })
232 })
233 }
234
235 pub fn cursor(&self) -> Option<Date> {
236 if self.has_header() {
237 let preferred = self.state.cursor();
238 let mut prior = None;
239 for day in self.days().filter(|day| day.in_month && day.enabled) {
240 if day.date >= preferred {
241 return Some(day.date);
242 }
243 prior = Some(day.date);
244 }
245 return prior;
246 }
247 if let Some(date) = self
248 .selection_in_view()
249 .filter(|&date| self.state.allows(date))
250 {
251 return Some(date);
252 }
253 self.days()
254 .find(|day| day.enabled && day.in_month)
255 .or_else(|| self.days().find(|day| day.enabled))
256 .map(|day| day.date)
257 }
258
259 pub(crate) fn navigation_origin(&self) -> Option<Date> {
260 self.selection_in_view().or_else(|| self.cursor())
263 }
264
265 fn selection_in_view(&self) -> Option<Date> {
266 let date = self.state.selected;
267 let current_month_only = self.has_header() || self.state.fixed_month;
268 (self.cells.contains(&Some(date))
269 && (!current_month_only || date.first_of_month() == self.state.month))
270 .then_some(date)
271 }
272
273 pub fn day_action(&self, date: Date) -> CalendarAction {
274 if self.part == CalendarPart::MonthGrid {
275 CalendarAction::Activate(date)
276 } else {
277 CalendarAction::Select(date)
278 }
279 }
280
281 pub fn action_at(&self, point: Point) -> Option<CalendarAction> {
282 for (bounds, action) in self.navigation() {
283 if bounds.contains(point) {
284 return action;
285 }
286 }
287 self.days()
288 .find(|day| day.enabled && day.bounds.contains(point))
289 .map(|day| self.day_action(day.date))
290 }
291
292 pub fn action_bounds(&self, action: CalendarAction) -> Option<Rect> {
293 match action {
294 CalendarAction::Select(date) | CalendarAction::Activate(date)
295 if action == self.day_action(date) =>
296 {
297 self.days()
298 .find(|day| day.date == date && day.enabled)
299 .map(|day| day.bounds)
300 }
301 CalendarAction::Browse(_) => self
302 .navigation()
303 .into_iter()
304 .find_map(|(rect, item)| (item == Some(action)).then_some(rect)),
305 _ => None,
306 }
307 }
308}