blinc_cn 0.6.0

Blinc Component Library - shadcn-style themed components built on blinc_layout primitives
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
//! Calendar component: a month of days to pick a date from
//!
//! A header with previous and next buttons around month and year selects, the
//! days of the week, and six weeks of days in a grid of seven. Days of the
//! months either side are muted, today is marked and the selected day is
//! filled. Choosing a day of a month either side turns to that month, and a
//! turning month slides in from its side while the old one slides out the
//! other.
//!
//! Days carry `data-outside`, `data-today`, `data-selected`, `data-events`,
//! `disabled` outside the allowed years, and `data-focus-visible` while the
//! keys are on them. A month's grid carries `data-enter` while it slides in
//! and `data-leaving` while it slides out, `"next"` or `"prev"`; the slide is
//! the `cn-calendar-*` keyframes. The navigation buttons carry `data-step`.
//! The look is the `.cn-calendar*` rules.
//!
//! A horizontal drag or two-finger swipe across the days moves the shown
//! month with it; let go far enough and the month turns, leftward to the
//! next, or it springs back. Vertical scrolling passes on to the page.
//! Once a day has been clicked, the arrows move by a day or a week, Page Up
//! and Page Down by a month, Home and End to the ends of the week, and Enter
//! or Space choose the day the keys are on.
//!
//! Events mark days: up to three per day show along its bottom edge, below
//! the number, which stays where it is, as a dot or the event's icon, coloured by `.cn-calendar-event` rules keyed on the
//! event's `data-kind`.
//!
//! # Example
//!
//! ```ignore
//! use blinc_cn::prelude::*;
//!
//! let picked = ctx.use_signal(None::<CalendarDay>);
//!
//! cn::calendar(picked)
//!     .week_start(1)
//!     .events(vec![
//!         CalendarEvent::new(CalendarDay::new(2026, 11, 3), "Standup").kind("meeting"),
//!         CalendarEvent::new(CalendarDay::new(2026, 11, 4), "Rain")
//!             .kind("weather")
//!             .icon(to_svg(icons::CLOUD_RAIN, 12.0)),
//!     ])
//!     .on_change(|day| println!("{day:?}"))
//! ```

use std::cell::OnceCell;
use std::sync::{Arc, Mutex};

use blinc_animation::{Easing, Keyframe, KeyframeAnimation, KeyframeId, SchedulerHandle};
use blinc_core::context_state::BlincContextState;
use blinc_core::reactive::{ReactiveGraph, Signal, computed, signal};
use blinc_layout::InstanceKey;
use blinc_layout::binding::{IntoReactive, Reactive};
use blinc_layout::div::ElementTypeId;
use blinc_layout::element::RenderProps;
use blinc_layout::prelude::*;
use blinc_layout::region::Row;
use blinc_layout::tree::{LayoutNodeId, LayoutTree};
use blinc_theme::ThemeState;

pub use super::calendar_date::CalendarDay;
use super::calendar_date::Month;
use super::number_gauge::GaugeFocus;
use super::select::{SelectBuilder, SelectOption, SelectSize};

const MONTHS: [&str; 12] = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December",
];
const WEEKDAYS: [&str; 7] = ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"];
const PREV_SVG: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m15 18-6-6 6-6"/></svg>"#;
const NEXT_SVG: &str = r#"<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m9 18 6-6-6-6"/></svg>"#;

/// How many years the year select lists, centred on the shown year.
const YEARS_LISTED: i32 = 201;
/// The height of a row of the year list, which builds only the rows in view.
const YEAR_ROW_HEIGHT: f32 = 32.0;
/// How far a press moves before its release stops being a click, in px.
const DRAG_SLOP: f32 = 8.0;
/// How far a two-finger swipe runs before it turns the month without
/// waiting for the fingers to lift, in px.
const SWIPE_FAR: f32 = 120.0;
/// The width of a month's grid, which a pull goes no further than.
const GRID_WIDTH: f32 = 252.0;
/// How long a swipe's scroll must pause before another can turn the month.
const SWIPE_QUIET_MS: u32 = 150;
/// How far a drag or swipe across the days goes for its release to turn the
/// month, in px.
const SWIPE_DISTANCE: f32 = 40.0;
/// The most events a day shows.
const MARKS_PER_DAY: usize = 3;

/// Something on a day: a meeting, the weather, a deadline.
///
/// `kind` becomes the mark's `data-kind`, which rules colour it by; `icon`
/// (SVG markup in `currentColor`) draws in place of the dot.
#[derive(Clone, Debug, PartialEq)]
pub struct CalendarEvent {
    pub day: CalendarDay,
    pub title: String,
    pub kind: Option<String>,
    pub icon: Option<String>,
}

impl CalendarEvent {
    pub fn new(day: CalendarDay, title: impl Into<String>) -> Self {
        Self {
            day,
            title: title.into(),
            kind: None,
            icon: None,
        }
    }

    /// The mark's `data-kind`.
    pub fn kind(mut self, kind: impl Into<String>) -> Self {
        self.kind = Some(kind.into());
        self
    }

    /// An icon drawn in place of the dot.
    pub fn icon(mut self, svg: impl Into<String>) -> Self {
        self.icon = Some(svg.into());
        self
    }
}

/// The events of `events` on `day`, in order.
pub fn events_on(events: &[CalendarEvent], day: CalendarDay) -> Vec<&CalendarEvent> {
    events.iter().filter(|e| e.day == day).collect()
}

/// Calendar component
pub struct Calendar {
    inner: Div,
}

impl ElementBuilder for Calendar {
    fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId {
        self.inner.build(tree)
    }

    fn render_props(&self) -> RenderProps {
        self.inner.render_props()
    }

    fn children_builders(&self) -> &[Box<dyn ElementBuilder>] {
        self.inner.children_builders()
    }

    fn element_type_id(&self) -> ElementTypeId {
        self.inner.element_type_id()
    }

    fn layout_style(&self) -> Option<&taffy::Style> {
        self.inner.layout_style()
    }

    fn element_classes(&self) -> &[std::sync::Arc<str>] {
        self.inner.element_classes()
    }

    fn element_id(&self) -> Option<&str> {
        self.inner.element_id()
    }

    fn event_handlers(&self) -> Option<&blinc_layout::event_handler::EventHandlers> {
        ElementBuilder::event_handlers(&self.inner)
    }
}

type ChangeCallback = Arc<dyn Fn(CalendarDay) + Send + Sync>;

/// Builder for a calendar bound to a selected day.
pub struct CalendarBuilder {
    key: InstanceKey,
    value: Signal<Option<CalendarDay>>,
    today: Option<CalendarDay>,
    week_start: u32,
    years: Years,
    events: Reactive<Vec<CalendarEvent>>,
    on_change: Option<ChangeCallback>,
    classes: Vec<std::sync::Arc<str>>,
    user_id: Option<String>,
    built: OnceCell<Calendar>,
}

impl CalendarBuilder {
    #[track_caller]
    pub fn new(value: Signal<Option<CalendarDay>>) -> Self {
        Self {
            key: InstanceKey::new("calendar"),
            value,
            today: None,
            week_start: 0,
            years: Years::default(),
            events: Reactive::Const(Vec::new()),
            on_change: None,
            classes: Vec::new(),
            user_id: None,
            built: OnceCell::new(),
        }
    }

    fn get_or_build(&self) -> &Calendar {
        ::blinc_layout::build_once::build_once(&self.built, || self.build_component())
    }

    /// The day marked as today; the local date by default.
    pub fn today(mut self, day: CalendarDay) -> Self {
        self.today = Some(day);
        self
    }

    /// The first day of the week: 0 for Sunday (the default), 1 for Monday.
    pub fn week_start(mut self, weekday: u32) -> Self {
        self.week_start = weekday % 7;
        self
    }

    /// The earliest year that can be shown or chosen.
    pub fn min_year(mut self, year: i32) -> Self {
        self.years.min = Some(year);
        self
    }

    /// The latest year that can be shown or chosen.
    pub fn max_year(mut self, year: i32) -> Self {
        self.years.max = Some(year);
        self
    }

    /// What is on which day: a list, or a Signal or Computed of one, whose
    /// changes the marks follow in place.
    pub fn events(mut self, events: impl IntoReactive<Vec<CalendarEvent>>) -> Self {
        self.events = events.into_reactive();
        self
    }

    /// Called with the day chosen.
    pub fn on_change<F>(mut self, callback: F) -> Self
    where
        F: Fn(CalendarDay) + Send + Sync + 'static,
    {
        self.on_change = Some(Arc::new(callback));
        self
    }

    /// Add a CSS class for selector matching
    pub fn class(mut self, name: impl AsRef<str>) -> Self {
        self.classes.push(blinc_core::intern::intern(name.as_ref()));
        self
    }

    /// Set the element ID for CSS selector matching
    pub fn id(mut self, id: &str) -> Self {
        self.user_id = Some(id.to_string());
        self
    }

    fn build_component(&self) -> Calendar {
        let years = self.years;
        if let (Some(min), Some(max)) = (years.min, years.max) {
            assert!(
                min <= max,
                "calendar min_year {min} is after max_year {max}"
            );
        }
        let key = self.key.get().to_string();
        let ctx = BlincContextState::get();
        let today = self.today.unwrap_or_else(CalendarDay::today);
        let at = self.value.try_get().flatten().unwrap_or(today);
        let first = CalendarDay::new(years.clamp(at.year), at.month, at.day);
        let keyed = |name: &str| format!("{key}_{name}");

        let nav = Nav {
            shown: ctx.use_signal_keyed(&keyed("shown"), || Month::of(first)),
            side: ctx.use_signal_keyed(&keyed("side"), || None),
            month_pick: ctx.use_signal_keyed(&keyed("month"), || first.month.to_string()),
            year_pick: ctx.use_signal_keyed(&keyed("year"), || first.year.to_string()),
            year_from: ctx.use_signal_keyed(&keyed("years"), || years.window(first.year)),
            years,
        };
        let root_id = self
            .user_id
            .clone()
            .unwrap_or_else(|| format!("cn-calendar-{key}"));
        let typography = ThemeState::get().typography();
        let parts = Parts {
            value: self.value,
            cursor: ctx.use_signal_keyed(&keyed("cursor"), || first),
            nav,
            focus: GaugeFocus::new(&key, &root_id),
            on_change: self.on_change.clone(),
            events: self.events.clone(),
            today,
            week_start: self.week_start,
            day_size: typography.text_sm,
            swiped: Arc::default(),
            glide: Glide {
                nav,
                pull: ctx.use_signal_keyed(&keyed("pull"), || 0.0f32),
                released: ctx.use_signal_keyed(&keyed("released"), || 0.0f32),
                outgoing: ctx.use_signal_keyed(&keyed("outgoing"), || None),
                turns: ctx.use_signal_keyed(&keyed("turns"), || 0u64),
            },
        };

        let mut weekdays = div().class("cn-calendar-weekdays").grid();
        for i in 0..7 {
            let name = WEEKDAYS[((i + self.week_start) % 7) as usize];
            weekdays = weekdays.child(
                div()
                    .class("cn-calendar-weekday")
                    .flex_row()
                    .items_center()
                    .justify_center()
                    .child(text(name).size(typography.text_xs).no_cursor()),
            );
        }

        let (shown, side) = (nav.shown, nav.side);
        let pages = computed(move |g: &ReactiveGraph| {
            vec![(
                g.get(shown).unwrap_or(Month::of(first)),
                g.get(side).flatten(),
            )]
        });
        let page_parts = parts.clone();
        let months = div()
            .class("cn-calendar-months")
            .relative()
            .overflow_clip()
            .for_each(
                &pages,
                |page: &(Month, Option<Side>)| page.0,
                move |(month, enter)| page(month, enter, &page_parts),
            );
        let months = swipeable(months, parts.glide, Arc::clone(&parts.swiped));

        let keys = parts.clone();
        let choose = parts.clone();
        let body = div()
            .class("cn-calendar-body")
            .attr("tabindex", "0")
            .attr("role", "grid")
            .flex_col()
            .child(weekdays)
            .child(months)
            .on_key_down(move |ctx| {
                let tabbed = blinc_layout::event_router::keyboard_focused_node();
                let focused = match tabbed {
                    Some(node) => node == ctx.node_id,
                    None => {
                        keys.focus.focused.get()
                            && !blinc_layout::widgets::text_input::has_focused_text_input()
                    }
                };
                if focused && keys.key(ctx.key_code) {
                    if tabbed.is_some() && !keys.focus.focused.get() {
                        keys.focus.press();
                    }
                    keys.focus.key();
                }
            })
            .on_click(move |ctx| {
                if blinc_layout::event_router::keyboard_focused_node() == Some(ctx.node_id) {
                    if let Some(day) = choose.cursor.try_get() {
                        choose.choose(day);
                    }
                }
            });

        let mut root = div()
            .class("cn-calendar")
            .id(&root_id)
            .flex_col()
            .child(header(&key, &parts))
            .child(body);
        for c in &self.classes {
            root = root.class(c);
        }
        Calendar { inner: root }
    }
}

/// The years that may be shown; either end may be open.
#[derive(Clone, Copy, Default)]
struct Years {
    min: Option<i32>,
    max: Option<i32>,
}

impl Years {
    fn allows(self, year: i32) -> bool {
        self.min.is_none_or(|m| year >= m) && self.max.is_none_or(|m| year <= m)
    }

    fn clamp(self, year: i32) -> i32 {
        let year = self.min.map_or(year, |m| year.max(m));
        self.max.map_or(year, |m| year.min(m))
    }

    /// The first year the year select lists with `year` shown.
    fn window(self, year: i32) -> i32 {
        let mut from = year - YEARS_LISTED / 2;
        if let Some(max) = self.max {
            from = from.min(max - (YEARS_LISTED - 1));
        }
        if let Some(min) = self.min {
            from = from.max(min);
        }
        from
    }

    fn listed(self, from: i32) -> i32 {
        self.max
            .map_or(YEARS_LISTED, |max| YEARS_LISTED.min(max - from + 1))
    }
}

/// The side a turning month comes in from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
enum Side {
    Next,
    Prev,
}

/// The month shown and the selects that name it.
#[derive(Clone, Copy)]
struct Nav {
    shown: Signal<Month>,
    side: Signal<Option<Side>>,
    month_pick: Signal<String>,
    year_pick: Signal<String>,
    /// The first year the year select lists.
    year_from: Signal<i32>,
    years: Years,
}

impl Nav {
    fn now(self) -> Option<Month> {
        self.shown.try_get()
    }

    /// Show `to`, sliding in from its side.
    fn turn(self, to: Month) {
        let Some(now) = self.now() else { return };
        if to == now || !self.years.allows(to.year) {
            return;
        }
        self.side
            .set(Some(if to > now { Side::Next } else { Side::Prev }));
        self.shown.set(to);
        self.month_pick.set(to.month.to_string());
        self.year_pick.set(to.year.to_string());
        let from = self.year_from.try_get().unwrap_or(to.year);
        if to.year < from || to.year >= from + self.years.listed(from) {
            self.year_from.set(self.years.window(to.year));
        }
    }
}

/// What the days of every month share.
#[derive(Clone)]
struct Parts {
    value: Signal<Option<CalendarDay>>,
    /// The day the keys are on.
    cursor: Signal<CalendarDay>,
    nav: Nav,
    focus: GaugeFocus,
    on_change: Option<ChangeCallback>,
    events: Reactive<Vec<CalendarEvent>>,
    today: CalendarDay,
    week_start: u32,
    day_size: f32,
    /// Set by a drag across the days, so the click its release makes chooses
    /// nothing.
    swiped: Arc<std::sync::atomic::AtomicBool>,
    glide: Glide,
}

impl Parts {
    fn choose(&self, day: CalendarDay) {
        if !self.nav.years.allows(day.year) {
            return;
        }
        self.value.set(Some(day));
        self.nav.turn(Month::of(day));
        self.cursor.set(day);
        if let Some(cb) = &self.on_change {
            cb(day);
        }
    }

    /// Keep the day the keys are on in the month picked, without choosing.
    fn jump(&self, to: Month) {
        if !self.nav.years.allows(to.year) {
            return;
        }
        let day = self.cursor.try_get().map_or(1, |d| d.day);
        self.cursor.set(CalendarDay::new(to.year, to.month, day));
        self.nav.turn(to);
    }

    /// A key while the calendar has focus; true when it did something.
    fn key(&self, code: u32) -> bool {
        const ENTER: u32 = 13;
        const SPACE: u32 = 32;
        const PAGE_UP: u32 = 33;
        const PAGE_DOWN: u32 = 34;
        const END: u32 = 35;
        const HOME: u32 = 36;
        const LEFT: u32 = 37;
        const UP: u32 = 38;
        const RIGHT: u32 = 39;
        const DOWN: u32 = 40;

        let Some(at) = self.cursor.try_get() else {
            return false;
        };
        let into_week = ((at.weekday() + 7 - self.week_start) % 7) as i64;
        let next = match code {
            LEFT => at.add_days(-1),
            RIGHT => at.add_days(1),
            UP => at.add_days(-7),
            DOWN => at.add_days(7),
            PAGE_UP => at.add_months(-1),
            PAGE_DOWN => at.add_months(1),
            HOME => at.add_days(-into_week),
            END => at.add_days(6 - into_week),
            ENTER | SPACE => {
                self.choose(at);
                return true;
            }
            _ => return false,
        };
        if self.nav.years.allows(next.year) {
            self.nav.turn(Month::of(next));
            self.cursor.set(next);
        }
        true
    }
}

/// The previous and next buttons around the month and year selects.
fn header(key: &str, parts: &Parts) -> Div {
    let nav = parts.nav;
    let pick_month = parts.clone();
    let months = SelectBuilder::with_key(format!("{key}_month_picker"), nav.month_pick)
        .size(SelectSize::Small)
        .w(106.0)
        .options((1..=12u32).map(|m| SelectOption::new(m.to_string(), MONTHS[m as usize - 1])))
        .on_change(move |v| {
            if let (Ok(month), Some(now)) = (v.parse(), nav.now()) {
                pick_month.jump(Month {
                    year: now.year,
                    month,
                });
            }
        });

    let year_key = format!("{key}_year_picker");
    let from = nav.year_from;
    let windows = computed(move |g: &ReactiveGraph| vec![g.get(from).unwrap_or(0)]);
    let pick_year = parts.clone();
    let years = div().class("cn-calendar-year-picker").for_each(
        &windows,
        |from: &i32| *from,
        move |from: i32| {
            let listed = (from..from + nav.years.listed(from))
                .map(|y| SelectOption::new(y.to_string(), y.to_string()));
            let pick = pick_year.clone();
            SelectBuilder::with_key(year_key.clone(), nav.year_pick)
                .size(SelectSize::Small)
                .w(72.0)
                .virtual_rows(YEAR_ROW_HEIGHT)
                .options(listed)
                .on_change(move |v| {
                    if let (Ok(year), Some(now)) = (v.parse(), nav.now()) {
                        pick.jump(Month {
                            year,
                            month: now.month,
                        });
                    }
                })
        },
    );

    div()
        .class("cn-calendar-header")
        .flex_row()
        .items_center()
        .justify_between()
        .child(step(nav, Side::Prev))
        .child(
            div()
                .class("cn-calendar-caption")
                .flex_row()
                .items_center()
                .child(div().class("cn-calendar-month-picker").child(months))
                .child(years),
        )
        .child(step(nav, Side::Next))
}

/// The button that turns to the previous or next month.
fn step(nav: Nav, side: Side) -> Div {
    let (n, name, icon) = match side {
        Side::Prev => (-1, "prev", PREV_SVG),
        Side::Next => (1, "next", NEXT_SVG),
    };
    let shown = nav.shown;
    let years = nav.years;
    let disabled = computed(move |g: &ReactiveGraph| {
        g.get(shown).is_none_or(|m| !years.allows(m.shift(n).year))
    });
    div()
        .class("cn-calendar-nav")
        .attr("data-step", name)
        .attr_when("disabled", "", &disabled)
        .flex_row()
        .items_center()
        .justify_center()
        .child(
            div()
                .pointer_events_none()
                .child(svg(icon).size(16.0, 16.0)),
        )
        .on_click(move |_| {
            if let Some(now) = nav.now() {
                nav.turn(now.shift(n));
            }
        })
}

/// The shown month follows a horizontal drag or two-finger swipe across the
/// days. Let go past [`SWIPE_DISTANCE`] and the month turns, leftward to the
/// next; short of it, it springs back. The pointer leaving the days cancels
/// the gesture: the month springs back and the rest of it moves nothing.
/// Once a press has moved, its release chooses no day.
fn swipeable(months: Div, glide: Glide, swiped: Arc<std::sync::atomic::AtomicBool>) -> Div {
    use std::sync::atomic::Ordering::Relaxed;
    let drag = Arc::new(Mutex::new(Drag::default()));
    let (pressed, dragging, released) = (Arc::clone(&drag), Arc::clone(&drag), drag);
    let moved = Arc::clone(&swiped);
    let swipe = Arc::new(Mutex::new(Swipe::default()));
    let (lifted, left) = (Arc::clone(&swipe), Arc::clone(&swipe));
    months
        .on_mouse_down(move |_| {
            swiped.store(false, Relaxed);
            *pressed.lock().unwrap() = Drag::default();
        })
        .on_drag(move |ctx| {
            let mut drag = dragging.lock().unwrap();
            if drag.cancelled {
                return;
            }
            if !inside(ctx) {
                drag.cancelled = true;
                glide.pull(0.0);
                return;
            }
            drag.dx = ctx.drag_delta_x;
            if ctx.drag_delta_x.abs() >= DRAG_SLOP {
                moved.store(true, Relaxed);
                glide.pull(ctx.drag_delta_x);
            }
        })
        .on_drag_end(move |ctx| {
            let drag = std::mem::take(&mut *released.lock().unwrap());
            if drag.cancelled {
                return;
            }
            let dx = if ctx.drag_delta_x != 0.0 {
                ctx.drag_delta_x
            } else {
                drag.dx
            };
            glide.release(dx);
        })
        .on_scroll_x(move |ctx| {
            swipe.lock().unwrap().scroll(
                glide,
                ctx.scroll_delta_x,
                ctx.scroll_gesture,
                ctx.scroll_momentum,
            )
        })
        .on_scroll_end(move |_| lifted.lock().unwrap().lift(glide))
        .on_hover_leave(move |_| left.lock().unwrap().cancel(glide))
}

/// Whether the pointer is over the element an event reached, when the event
/// says where that is.
fn inside(ctx: &blinc_layout::event_handler::EventContext) -> bool {
    ctx.bounds_width <= 0.0
        || (ctx.mouse_x >= ctx.bounds_x
            && ctx.mouse_x <= ctx.bounds_x + ctx.bounds_width
            && ctx.mouse_y >= ctx.bounds_y
            && ctx.mouse_y <= ctx.bounds_y + ctx.bounds_height)
}

/// A drag across the days: how far it has gone, and whether leaving them
/// cancelled it.
#[derive(Default)]
struct Drag {
    dx: f32,
    cancelled: bool,
}

/// How far the shown month has been pulled, and where it was let go.
#[derive(Clone, Copy)]
struct Glide {
    nav: Nav,
    /// The shown month's offset while a gesture moves it.
    pull: Signal<f32>,
    /// The offset it was let go at, which a leaving month keeps.
    released: Signal<f32>,
    /// The page let go of to turn, by its month and the turn it was built
    /// after, which reads `released` from then on.
    outgoing: Signal<Option<(Month, u64)>>,
    /// How many turns by release there have been; a page is built after the
    /// count it reads, so a later page for the same month is not outgoing.
    turns: Signal<u64>,
}

impl Glide {
    fn pull(self, dx: f32) {
        self.pull.set(dx.clamp(-GRID_WIDTH, GRID_WIDTH));
    }

    /// Let go after moving `dx`: turn the month away from it if it went far
    /// enough, and put the shown month back where it belongs.
    fn release(self, dx: f32) {
        if dx.abs() >= SWIPE_DISTANCE {
            if let Some(now) = self.nav.now() {
                let to = now.shift(if dx < 0.0 { 1 } else { -1 });
                if self.nav.years.allows(to.year) {
                    // The month let go of holds its place before the pull
                    // returns to rest, so it never moves back first.
                    self.released.set(self.pull.try_get().unwrap_or(0.0));
                    let turns = self.turns.try_get().unwrap_or(0);
                    self.outgoing.set(Some((now, turns)));
                    self.turns.set(turns + 1);
                    self.pull.set(0.0);
                    self.nav.turn(to);
                    return;
                }
            }
        }
        self.pull.set(0.0);
    }
}

/// A two-finger swipe: the month follows its horizontal scroll and turns or
/// springs back when the fingers lift. Each touch is a new swipe, told by the
/// gesture number its scrolls carry; the momentum after a lift moves nothing.
/// One that runs on past [`SWIPE_FAR`] turns at once. A wheel reports no
/// gestures, so its swipes are told apart by a quiet moment between them,
/// timed on the wall clock as input events arrive.
#[derive(Default)]
struct Swipe {
    travel: f32,
    /// This swipe has turned, been let go or been cancelled; the rest of it
    /// moves nothing.
    spent: bool,
    gesture: u64,
    last: Option<web_time::Instant>,
}

impl Swipe {
    fn scroll(&mut self, glide: Glide, dx: f32, gesture: u64, momentum: bool) {
        if momentum {
            return;
        }
        let now = web_time::Instant::now();
        let quiet = self
            .last
            .is_none_or(|t| now.duration_since(t).as_millis() >= SWIPE_QUIET_MS as u128);
        self.last = Some(now);
        if gesture != self.gesture || (gesture == 0 && quiet) {
            self.gesture = gesture;
            self.travel = 0.0;
            self.spent = false;
        }
        if self.spent {
            return;
        }
        self.travel += dx;
        glide.pull(self.travel);
        if self.travel.abs() >= SWIPE_FAR {
            self.spent = true;
            glide.release(self.travel);
        }
    }

    fn lift(&mut self, glide: Glide) {
        if !self.spent {
            glide.release(self.travel);
        }
        self.spent = true;
    }

    /// The pointer left: put the month back and let the rest go by.
    fn cancel(&mut self, glide: Glide) {
        if !self.spent {
            glide.pull(0.0);
        }
        self.spent = true;
    }
}

/// One month's grid, sliding in from `enter` when it has a side; it slides
/// out the other way once another month replaces it.
fn page(month: Month, enter: Option<Side>, parts: &Parts) -> Row {
    let leaving: Signal<Option<Side>> = signal(None);
    let out_to =
        |side: Side| computed(move |g: &ReactiveGraph| g.get(leaving).flatten() == Some(side));
    let gone = computed(move |g: &ReactiveGraph| g.get(leaving).flatten().is_some());
    // Shown, it follows the gesture's pull; leaving, it stays where it was let
    // go, so its slide out starts there.
    let glide = parts.glide;
    let born = glide.turns.try_get().unwrap_or(0);
    let kept = signal(0.0f32);
    let offset = computed(move |g: &ReactiveGraph| {
        if g.get(leaving).flatten().is_some() {
            g.get(kept).unwrap_or(0.0)
        } else if g.get(glide.outgoing).flatten() == Some((month, born)) {
            g.get(glide.released).unwrap_or(0.0)
        } else {
            g.get(glide.pull).unwrap_or(0.0)
        }
    });
    let mut grid = div()
        .class("cn-calendar-grid")
        .grid()
        .attr_when("data-enter", "next", enter == Some(Side::Next))
        .attr_when("data-enter", "prev", enter == Some(Side::Prev))
        .attr_when("data-leaving", "next", out_to(Side::Next))
        .attr_when("data-leaving", "prev", out_to(Side::Prev));
    for day in month.grid(parts.week_start) {
        grid = grid.child(day_cell(day, month, parts));
    }
    // The offset sits on a page around the grid, so the grid's slide
    // keyframes add to it rather than replace it.
    let page = div()
        .class("cn-calendar-page")
        .absolute_when(&gone)
        .bind_transform_from(&offset, |x: f32| Transform::translate(x, 0.0))
        .child(grid);

    // Kept until its slide has played: the theme's normal duration, on the
    // animation clock.
    let side = parts.nav.side;
    let timer = Arc::new(Mutex::new(Timer::default()));
    let start = Arc::clone(&timer);
    Row::new(page).on_leave(
        move || {
            // A month let go of slides out from where it was let go; one
            // turned by a button or key, from rest.
            let outgoing = glide.outgoing.try_get().flatten() == Some((month, born));
            kept.set(match outgoing {
                true => glide.released.try_get().unwrap_or(0.0),
                false => 0.0,
            });
            leaving.set(Some(side.try_get().flatten().unwrap_or(Side::Next)));
            let ms = ThemeState::get().animations().duration_normal as u32;
            start.lock().unwrap().start(ms);
        },
        move || timer.lock().unwrap().done(),
    )
}

/// A keyframe on the animation scheduler, so a wait is timed on the clock
/// the animations are.
#[derive(Default)]
struct Timer(Option<(SchedulerHandle, KeyframeId)>);

impl Timer {
    /// Start, or start again, a wait of `ms`.
    fn start(&mut self, ms: u32) {
        if let Some((scheduler, id)) = self.0.take() {
            scheduler.remove_keyframe(id);
        }
        let Some(scheduler) = blinc_layout::render_state::get_global_scheduler() else {
            return;
        };
        let frames = vec![
            Keyframe {
                time: 0.0,
                value: 0.0,
                easing: Easing::Linear,
            },
            Keyframe {
                time: 1.0,
                value: 1.0,
                easing: Easing::Linear,
            },
        ];
        if let Some(id) = scheduler.register_keyframe(KeyframeAnimation::new(ms.max(1), frames)) {
            scheduler.start_keyframe(id);
            self.0 = Some((scheduler, id));
        }
    }

    fn done(&self) -> bool {
        self.0
            .as_ref()
            .is_none_or(|(scheduler, id)| !scheduler.is_keyframe_playing(*id))
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        if let Some((scheduler, id)) = self.0.take() {
            scheduler.remove_keyframe(id);
        }
    }
}

/// One day: its number, and the marks of what is on it.
fn day_cell(day: CalendarDay, month: Month, parts: &Parts) -> Div {
    let value = parts.value;
    let selected = computed(move |g: &ReactiveGraph| g.get(value).flatten() == Some(day));
    let (cursor, focused, keyed) = (parts.cursor, parts.focus.focused, parts.focus.keyed);
    let ringed = computed(move |g: &ReactiveGraph| {
        g.get(focused).unwrap_or(false)
            && g.get(keyed).unwrap_or(false)
            && g.get(cursor) == Some(day)
    });
    let events = parts.events.clone();
    let marks = computed(move |g: &ReactiveGraph| {
        events
            .read(g)
            .unwrap_or_default()
            .into_iter()
            .filter(|e| e.day == day)
            .take(MARKS_PER_DAY)
            .enumerate()
            .collect::<Vec<_>>()
    });
    let events = parts.events.clone();
    let has_marks = computed(move |g: &ReactiveGraph| {
        events
            .read(g)
            .is_some_and(|all| all.iter().any(|e| e.day == day))
    });

    let choose = parts.clone();
    div()
        .class("cn-calendar-day")
        .attr_when("data-outside", "", Month::of(day) != month)
        .attr_when("data-today", "", day == parts.today)
        .attr_when("data-selected", "", &selected)
        .attr_when("data-focus-visible", "", &ringed)
        .attr_when("data-events", "", &has_marks)
        .attr_when("disabled", "", !parts.nav.years.allows(day.year))
        .relative()
        .flex_row()
        .items_center()
        .justify_center()
        .child(
            text(day.day.to_string())
                .size(parts.day_size)
                .no_cursor()
                .pointer_events_none(),
        )
        .child(
            div()
                .class("cn-calendar-events")
                .absolute()
                .left(0.0)
                .right(0.0)
                .bottom(2.0)
                .h(8.0)
                .gap(0.5)
                .flex_row()
                .items_center()
                .justify_center()
                .pointer_events_none()
                .for_each(
                    &marks,
                    |(i, e): &(usize, CalendarEvent)| {
                        (*i, e.title.clone(), e.kind.clone(), e.icon.clone())
                    },
                    |(_, e): (usize, CalendarEvent)| mark(&e),
                ),
        )
        .on_click(move |_| {
            if choose
                .swiped
                .swap(false, std::sync::atomic::Ordering::Relaxed)
            {
                return;
            }
            choose.focus.press();
            choose.choose(day);
        })
}

/// An event's dot, or its icon.
fn mark(event: &CalendarEvent) -> Div {
    let mut m = div().class("cn-calendar-event").flex_shrink_0();
    if let Some(kind) = &event.kind {
        m = m.attr("data-kind", kind.as_str());
    }
    match &event.icon {
        Some(icon) => m
            .class("cn-calendar-event--icon")
            .child(svg(icon).size(8.0, 8.0)),
        None => m,
    }
}

impl ElementBuilder for CalendarBuilder {
    fn build(&self, tree: &mut LayoutTree) -> LayoutNodeId {
        self.get_or_build().build(tree)
    }

    fn render_props(&self) -> RenderProps {
        self.get_or_build().render_props()
    }

    fn children_builders(&self) -> &[Box<dyn ElementBuilder>] {
        self.get_or_build().children_builders()
    }

    fn element_type_id(&self) -> ElementTypeId {
        self.get_or_build().element_type_id()
    }

    fn layout_style(&self) -> Option<&taffy::Style> {
        self.get_or_build().layout_style()
    }

    fn element_classes(&self) -> &[std::sync::Arc<str>] {
        self.get_or_build().element_classes()
    }

    fn element_id(&self) -> Option<&str> {
        self.get_or_build().element_id()
    }

    fn event_handlers(&self) -> Option<&blinc_layout::event_handler::EventHandlers> {
        self.get_or_build().event_handlers()
    }
}

/// A calendar that reads and writes the selected day.
///
/// # Example
///
/// ```ignore
/// let picked = ctx.use_signal(None::<CalendarDay>);
/// cn::calendar(picked).on_change(|day| println!("{day:?}"))
/// ```
#[track_caller]
pub fn calendar(value: Signal<Option<CalendarDay>>) -> CalendarBuilder {
    CalendarBuilder::new(value)
}