ev_lib 0.17.0

EV-invest shared Rust libraries, one per feature
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
use dioxus::prelude::*;

use crate::{
	cn,
	uikit::{
		ButtonVariant, CALENDAR_CAPTION, CALENDAR_DAY, CALENDAR_DAY_CELL, CALENDAR_DAY_EMPTY, CALENDAR_DAY_SELECTED, CALENDAR_DAY_TODAY, CALENDAR_GRID, CALENDAR_NAV, CALENDAR_NAV_BUTTON,
		CALENDAR_ROOT, CALENDAR_WEEK, CALENDAR_WEEKDAY, CALENDAR_WEEKDAY_ROW, Size, button::button_classes, primitives::use_controllable,
	},
};

const MONTHS: [&str; 12] = [
	"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December",
];
const WEEKDAYS: [&str; 7] = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"];
const CHEVRON_LEFT: &str = "m15 18-6-6 6-6";
const CHEVRON_RIGHT: &str = "m9 18 6-6-6-6";
/// A calendar date as plain `(year, month 1-12, day 1-31)`. The kernel does its
/// own date math (no `chrono`/`jiff`): `wasm32`-safe and dependency-free.
///
/// Fields are declared in `year, month, day` order, so the derived ordering is
/// chronological.
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct CalendarDate {
	pub year: i32,
	pub month: u32,
	pub day: u32,
}

impl CalendarDate {
	pub fn new(year: i32, month: u32, day: u32) -> Self {
		Self { year, month, day }
	}

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

	/// Days in `month` (1-12) of `year`, accounting for leap February.
	fn days_in_month(year: i32, month: u32) -> u32 {
		match month {
			1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
			4 | 6 | 9 | 11 => 30,
			2 if Self::is_leap(year) => 29,
			2 => 28,
			_ => 30,
		}
	}

	/// Weekday of the first day of the month, **Monday = 0 … Sunday = 6**, via
	/// Zeller's congruence (week starts Monday).
	fn first_weekday_monday0(year: i32, month: u32) -> u32 {
		// Zeller treats Jan/Feb as months 13/14 of the previous year.
		let (m, y) = if month < 3 { (month + 12, year - 1) } else { (month, year) };
		let k = y.rem_euclid(100);
		let j = y.div_euclid(100);
		let q = 1i32; // first of the month
		// h: 0 = Saturday, 1 = Sunday, 2 = Monday, …, 6 = Friday.
		let h = (q + (13 * (m as i32 + 1)) / 5 + k + k / 4 + j / 4 + 5 * j).rem_euclid(7);
		// Map Saturday-based h to Monday-based 0..=6.
		((h + 5).rem_euclid(7)) as u32
	}

	/// Same month + day shifted by `delta` months, clamped to the target
	/// month's length (used by the prev/next nav).
	fn add_months(&self, delta: i32) -> Self {
		let zero = (self.year as i64) * 12 + (self.month as i64 - 1) + delta as i64;
		let year = zero.div_euclid(12) as i32;
		let month = (zero.rem_euclid(12) + 1) as u32;
		let day = self.day.min(Self::days_in_month(year, month));
		Self { year, month, day }
	}
}

// Week starts Monday.

/// A dep-light single-month, single-date picker. Mirrors the landing
/// `Calendar`'s class names while replacing `react-day-picker` with hand-rolled
/// month-grid math.
///
/// Simplifications versus the source: one month only (no multi-month), a single
/// selected date (no range/multi), and none of the locale/dropdown/caption
/// features — see the package README.
#[component]
pub fn Calendar(
	/// The currently selected day, if any.
	selected: Option<CalendarDate>,
	/// Fired with the day a user activates.
	on_select: Option<EventHandler<CalendarDate>>,
	/// Controlled displayed month (any day in it is fine).
	month: Option<CalendarDate>,
	/// Uncontrolled initial displayed month.
	#[props(default = CalendarDate::new(2026, 6, 1))]
	default_month: CalendarDate,
	/// Fired when the displayed month changes via the nav buttons.
	on_month_change: Option<EventHandler<CalendarDate>>,
	/// "Today", highlighted in the grid.
	today: Option<CalendarDate>,
	/// Earliest selectable day (inclusive); earlier days render disabled.
	min: Option<CalendarDate>,
	/// Latest selectable day (inclusive); later days render disabled.
	max: Option<CalendarDate>,
	/// Disables the whole grid and the nav buttons; every day renders `data-disabled`.
	#[props(default)]
	disabled: bool,
	/// `aria-label` of the previous-month button; "Previous month" by default.
	previous_month_label: Option<String>,
	/// `aria-label` of the next-month button; "Next month" by default.
	next_month_label: Option<String>,
	#[props(default)] class: String,
) -> Element {
	let view = use_controllable(month, default_month, on_month_change);
	let current = view.get();

	let go = move |delta: i32| {
		view.set(current.add_months(delta));
	};

	let nav_class = button_classes(&ButtonVariant::Ghost, Size::Md, true, None, CALENDAR_NAV_BUTTON);
	let caption = format!("{} {}", MONTHS[(current.month - 1) as usize], current.year);
	let previous_label = previous_month_label.unwrap_or_else(|| String::from("Previous month"));
	let next_label = next_month_label.unwrap_or_else(|| String::from("Next month"));

	let lead = CalendarDate::first_weekday_monday0(current.year, current.month);
	let total = CalendarDate::days_in_month(current.year, current.month);
	// Pad leading blanks then the days, padded out to whole weeks of 7.
	let mut cells: Vec<Option<u32>> = (0..lead).map(|_| None).collect();
	cells.extend((1..=total).map(Some));
	while !cells.len().is_multiple_of(7) {
		cells.push(None);
	}
	let weeks: Vec<Vec<Option<u32>>> = cells.chunks(7).map(<[Option<u32>]>::to_vec).collect();

	let root = cn!(CALENDAR_ROOT, class);

	rsx! {
		div { class: root, "data-slot": "calendar", role: "application",
			div { class: CALENDAR_NAV,
				button {
					r#type: "button",
					class: nav_class.clone(),
					"aria-label": previous_label,
					disabled,
					onclick: move |_| go(-1),
					Chevron { d: CHEVRON_LEFT }
				}
				div { class: CALENDAR_CAPTION, "data-slot": "calendar-caption", {caption} }
				button {
					r#type: "button",
					class: nav_class.clone(),
					"aria-label": next_label,
					disabled,
					onclick: move |_| go(1),
					Chevron { d: CHEVRON_RIGHT }
				}
			}
			table { class: CALENDAR_GRID, role: "grid",
				thead {
					tr { class: CALENDAR_WEEKDAY_ROW,
						for wd in WEEKDAYS {
							th {
								class: CALENDAR_WEEKDAY,
								scope: "col",
								{wd}
							}
						}
					}
				}
				tbody {
					for week in weeks {
						tr { class: CALENDAR_WEEK,
							for cell in week {
								DayCell {
									cell,
									date: current,
									selected,
									today,
									min,
									max,
									disabled,
									on_select,
								}
							}
						}
					}
				}
			}
		}
	}
}

#[component]
fn DayCell(
	cell: Option<u32>,
	date: CalendarDate,
	selected: Option<CalendarDate>,
	today: Option<CalendarDate>,
	min: Option<CalendarDate>,
	max: Option<CalendarDate>,
	disabled: bool,
	on_select: Option<EventHandler<CalendarDate>>,
) -> Element {
	let Some(day) = cell else {
		return rsx! {
			td { class: CALENDAR_DAY_EMPTY }
		};
	};

	let this = CalendarDate::new(date.year, date.month, day);
	let is_selected = selected == Some(this);
	let is_today = today == Some(this);
	let is_disabled = disabled || min.is_some_and(|lo| this < lo) || max.is_some_and(|hi| this > hi);
	let aria_selected = if is_selected { "true" } else { "false" };

	let mut day_class = button_classes(&ButtonVariant::Ghost, Size::Md, true, None, CALENDAR_DAY);
	if is_selected {
		day_class = cn!(day_class, CALENDAR_DAY_SELECTED);
	} else if is_today {
		day_class = cn!(day_class, CALENDAR_DAY_TODAY);
	}

	rsx! {
		td {
			class: CALENDAR_DAY_CELL,
			role: "gridcell",
			"aria-selected": aria_selected,
			button {
				r#type: "button",
				class: day_class,
				"data-slot": "calendar-day",
				"data-selected": if is_selected { "true" } else { "false" },
				"data-today": if is_today { "true" } else { "false" },
				// Absent rather than "false", so the unbounded grid renders as before.
				"data-disabled": if is_disabled { Some("true") } else { None },
				disabled: is_disabled,
				onclick: move |_| {
					if is_disabled {
						return;
					}
					if let Some(h) = on_select {
						h.call(this);
					}
				},
				"{day}"
			}
		}
	}
}

#[component]
fn Chevron(d: &'static str) -> Element {
	rsx! {
		svg {
			class: "size-4",
			xmlns: "http://www.w3.org/2000/svg",
			width: "24",
			height: "24",
			view_box: "0 0 24 24",
			fill: "none",
			stroke: "currentColor",
			stroke_width: "2",
			stroke_linecap: "round",
			stroke_linejoin: "round",
			path { d }
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::uikit::test_util::render;

	#[test]
	fn days_in_month_handles_leap_february() {
		assert_eq!(CalendarDate::days_in_month(2024, 2), 29);
		assert_eq!(CalendarDate::days_in_month(2023, 2), 28);
		assert_eq!(CalendarDate::days_in_month(1900, 2), 28);
		assert_eq!(CalendarDate::days_in_month(2000, 2), 29);
		assert_eq!(CalendarDate::days_in_month(2026, 4), 30);
		assert_eq!(CalendarDate::days_in_month(2026, 1), 31);
	}

	#[test]
	fn first_weekday_is_monday_zero() {
		// 1 June 2026 is a Monday.
		assert_eq!(CalendarDate::first_weekday_monday0(2026, 6), 0);
		// 1 Jan 2026 is a Thursday.
		assert_eq!(CalendarDate::first_weekday_monday0(2026, 1), 3);
		// 1 Feb 2026 is a Sunday.
		assert_eq!(CalendarDate::first_weekday_monday0(2026, 2), 6);
	}

	#[test]
	fn add_months_wraps_year_and_clamps_day() {
		let dec = CalendarDate::new(2026, 12, 15);
		assert_eq!(dec.add_months(1), CalendarDate::new(2027, 1, 15));
		let jan = CalendarDate::new(2026, 1, 10);
		assert_eq!(jan.add_months(-1), CalendarDate::new(2025, 12, 10));
		// 31 Jan + 1 month clamps to 28 Feb (non-leap).
		let jan31 = CalendarDate::new(2026, 1, 31);
		assert_eq!(jan31.add_months(1), CalendarDate::new(2026, 2, 28));
	}

	#[test]
	fn renders_month_grid_with_slots_and_weekdays() {
		fn app() -> Element {
			rsx! {
				Calendar { default_month: CalendarDate::new(2026, 6, 1) }
			}
		}
		let html = render(app);
		assert!(html.contains("data-slot=\"calendar\""), "{html}");
		assert!(html.contains("June 2026"), "{html}");
		assert!(html.contains("Mo"));
		assert!(html.contains("role=\"gridcell\""), "{html}");
		// Every day of June is present.
		assert!(html.contains(">30<"), "{html}");
	}

	#[test]
	fn selected_and_today_get_their_classes() {
		fn app() -> Element {
			rsx! {
				Calendar {
					default_month: CalendarDate::new(2026, 6, 1),
					selected: CalendarDate::new(2026, 6, 10),
					today: CalendarDate::new(2026, 6, 15),
				}
			}
		}
		let html = render(app);
		assert!(html.contains("aria-selected=\"true\""), "{html}");
		assert!(html.contains("bg-primary"), "{html}");
		assert!(html.contains("bg-hover"), "{html}");
		assert!(html.contains("data-selected=\"true\""), "{html}");
	}

	#[test]
	fn unbounded_grid_has_no_disabled_days_and_english_nav_labels() {
		fn app() -> Element {
			rsx! {
				Calendar { default_month: CalendarDate::new(2026, 6, 1) }
			}
		}
		let html = render(app);
		assert!(!html.contains(" disabled=true"), "{html}");
		assert!(!html.contains("data-disabled"), "{html}");
		assert!(html.contains("aria-label=\"Previous month\""), "{html}");
		assert!(html.contains("aria-label=\"Next month\""), "{html}");
		assert!(html.contains("data-slot=\"calendar-caption\""), "{html}");
	}

	#[test]
	fn days_outside_min_max_render_disabled() {
		fn app() -> Element {
			rsx! {
				Calendar {
					default_month: CalendarDate::new(2026, 6, 1),
					min: CalendarDate::new(2026, 6, 10),
					max: CalendarDate::new(2026, 6, 20),
				}
			}
		}
		let html = render(app);
		// 9 days before `min` + 10 days after `max`.
		assert_eq!(html.matches("data-disabled=\"true\"").count(), 19, "{html}");
		assert_eq!(html.matches(" disabled=true").count(), 19, "{html}");
		let tenth = html.find(">10<").expect("day 10 rendered");
		let tag_start = html[..tenth].rfind("<button").expect("day 10 button");
		assert!(!html[tag_start..tenth].contains(" disabled=true"), "day at `min` stays enabled: {html}");
	}

	#[test]
	fn disabled_freezes_every_day_and_the_nav() {
		fn app() -> Element {
			rsx! {
				Calendar {
					default_month: CalendarDate::new(2026, 6, 1),
					disabled: true,
					min: CalendarDate::new(2026, 6, 10),
				}
			}
		}
		let html = render(app);
		// All 30 days of June, `min` notwithstanding.
		assert_eq!(html.matches("data-disabled=\"true\"").count(), 30, "{html}");
		// 30 days + the two nav buttons.
		assert_eq!(html.matches(" disabled=true").count(), 32, "{html}");
	}

	#[test]
	fn nav_labels_are_overridable() {
		fn app() -> Element {
			rsx! {
				Calendar {
					default_month: CalendarDate::new(2026, 6, 1),
					previous_month_label: "Предыдущий месяц",
					next_month_label: "Следующий месяц",
				}
			}
		}
		let html = render(app);
		assert!(html.contains("aria-label=\"Предыдущий месяц\""), "{html}");
		assert!(html.contains("aria-label=\"Следующий месяц\""), "{html}");
		assert!(!html.contains("Previous month"), "{html}");
	}

	#[test]
	fn calendar_date_orders_chronologically() {
		assert!(CalendarDate::new(2026, 6, 10) < CalendarDate::new(2026, 6, 11));
		assert!(CalendarDate::new(2026, 6, 30) < CalendarDate::new(2026, 7, 1));
		assert!(CalendarDate::new(2025, 12, 31) < CalendarDate::new(2026, 1, 1));
	}
}