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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech
//! `DateRangeEdit` — single unified control for picking a `DateRange`.
//!
//! Visually one widget: a single bordered frame containing two
//! `TextInputField` halves separated by a painted arrow glyph, with
//! a trailing built-in calendar button that opens a shared
//! `Calendar::range` popover. Backed by `Signal<Option<DateRange>>`.
//!
//! ```text
//! ┌──────────────────────────────────────┐
//! │ 05/12/2026 → 05/19/2026 │ 📅 │
//! └──────────────────────────────────────┘
//! ```
//!
//! # Why one frame?
//!
//! Two adjacent `DateEdit`s (one frame each) visually read as two
//! separate fields that happen to be next to each other. A single
//! frame says "this is one range". Same affordance the user is used
//! to from booking sites and analytics dashboards.
//!
//! # Behaviour
//!
//! - **Two text halves** — each masked from the resolved date pattern,
//! each with its own validator + segment-stepping (Up/Down on the
//! focused segment matches `DateEdit`).
//! - **Painted arrow separator** — a thin chevron-right glyph, no text.
//! Visual only; AT users see the wrapper's `Role::DateInput`.
//! - **One trailing calendar button** — Int UI `IconButton::embedded()` with
//! the calendar glyph. Opens a single popover hosting
//! `Calendar::range` bound to the outer signal. The two-anchor
//! click model (start-then-end) commits the range and closes the
//! popover. No per-half calendar buttons — there's only one
//! calendar, anchored to the wrapper.
//! - **One frame** — focus-aware border (`BorderRole::Focused` while
//! any half holds focus, otherwise `Default`), validation-aware
//! border (`Error` for `Invalid`, `Focused` for `Corrected`).
//! - **One validation strip** below the frame — composed feedback
//! from both halves (worse of the two wins).
//!
//! # Accessibility
//!
//! - Container — `Role::DateInput` with `set_value` formatted as
//! `YYYY-MM-DD/YYYY-MM-DD` (ISO range).
//! - Each `TextInputField` keeps its own `Role::TextInput` AT node;
//! the wrapper's `Role::DateInput` provides the range semantics.
//!
//! ```ignore
//! // Requires ctx.signal() — shown as ignore per convention.
//! use teksilo_widgets::date_range_edit::DateRangeEdit;
//! use jiff::civil::Weekday;
//!
//! let range = ctx.signal(None);
//! let _w = DateRangeEdit::new(range.clone())
//! .first_day_of_week(Weekday::Monday)
//! .on_value_changed(|r, _ctx| println!("{r:?}"));
//! ```
#[cfg(test)]
mod tests;
use std::rc::Rc;
use teksilo_i18n::localized;
use jiff::civil::Weekday;
use teksilo_canvas::{Path, Point, Rect, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::accesskit::{Action, Role};
use teksilo_core::build_context::BuildContext;
use teksilo_core::event::{EventResponse, Key, WidgetEvent};
use teksilo_core::overlay::{
DismissBehavior, OverlayDismissCallback, OverlayLayer, OverlayPlacement, OverlayRequest,
};
use teksilo_core::signal::{Prop, Signal};
use teksilo_core::widget::{EventContext, LayoutContext, Widget, WidgetPlacement};
use teksilo_core::widget_builder::{HandlerSet, WidgetBuilder};
use teksilo_core::widget_id::WidgetId;
use teksilo_i18n::resolve_message_widget;
use teksilo_tokens::{BorderRole, CornerRadius, SurfaceRole};
use crate::calendar::{Calendar, DateRange};
use crate::common::datetime::Date;
use crate::common::datetime::pattern::{
ParseTarget, ParsedPattern, ParsedValue, format_value, mask_for_pattern, parse_value,
segment_at_position, step_date_field,
};
use crate::common::datetime::types::today_local;
use crate::date_edit::{ValidationBehavior, build_date_validator, calendar_glyph_icon, clamp_date};
use crate::icon_button::{IconButton, IconButtonSize};
use crate::primitives::text_input_field::{TextInputField, ValidationFeedback};
use crate::primitives::{
Center, FixedSize, HStack, IconWidget, MinSize, Padding, RectWidget, VStack, ZStack,
};
use teksilo_i18n::LocalizedString;
type OnRangeChanged = Rc<dyn Fn(Option<DateRange>, &mut EventContext)>;
/// Two-handle date picker over `Signal<Option<DateRange>>`. See the
/// [module docs](self) for the visual layout and behaviour.
pub struct DateRangeEdit {
value: Signal<Option<DateRange>>,
/// Internal start half — drives the start `TextInputField` text
/// signal and is kept in sync with `value` via `ctx.effect`.
start_part: Signal<Option<Date>>,
end_part: Signal<Option<Date>>,
start_text: Signal<String>,
end_text: Signal<String>,
min_date: Option<Date>,
max_date: Option<Date>,
pattern: Option<String>,
placeholder_start: LocalizedString,
placeholder_end: LocalizedString,
first_day_of_week: Option<Weekday>,
/// Enabled state, static or reactive; forwarded to the arena at
/// build time.
enabled: Prop<bool>,
read_only: bool,
label: Option<LocalizedString>,
validation_behavior: ValidationBehavior,
/// How the trailing (end) half claims horizontal space. The
/// leading (start) half always sizes to its mask-derived
/// natural width — the start date stays put while the end half
/// either matches that natural width
/// (`WidthPolicy::Default`) or absorbs whatever extra space
/// the parent offers (`WidthPolicy::Fill`).
end_width_policy: crate::date_edit::WidthPolicy,
/// Composed validation feedback (severity-merged from both halves).
feedback: Signal<ValidationFeedback>,
/// `true` while either half holds keyboard focus — drives the
/// unified frame border.
focused: Signal<bool>,
/// `true` while the calendar popover is open — drives the
/// trigger's AT `set_expanded` and the open/close toggle.
range_popover_open: Signal<bool>,
on_value_changed: Option<OnRangeChanged>,
style_override: Option<teksilo_core::styles::SharedDateEditStyle>,
root_child_id: Option<WidgetId>,
/// Optional plain tooltip text shown after a hover delay. Mutually exclusive
/// with the rich / composite slots — every setter clears the other two so
/// the last call wins.
tooltip_text: Option<LocalizedString>,
/// Optional rich tooltip source (registry key or inline content).
rich_tooltip_source: Option<crate::tooltip::RichTooltipSource>,
/// Optional composite tooltip body (arbitrary widget tree).
composite_tooltip_content: Option<Box<dyn Widget>>,
}
impl std::fmt::Debug for DateRangeEdit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DateRangeEdit").finish_non_exhaustive()
}
}
impl DateRangeEdit {
/// Create a date-range picker bound to `value`.
pub fn new(value: Signal<Option<DateRange>>) -> Self {
let initial = value.get();
let start_part = Signal::new(initial.map(|r| r.start));
let end_part = Signal::new(initial.map(|r| r.end));
Self {
value,
start_part,
end_part,
start_text: Signal::new(String::new()),
end_text: Signal::new(String::new()),
min_date: None,
max_date: None,
pattern: None,
placeholder_start: LocalizedString::literal(String::new()),
placeholder_end: LocalizedString::literal(String::new()),
first_day_of_week: None,
enabled: Prop::Static(true),
read_only: false,
label: None,
validation_behavior: ValidationBehavior::AutoCorrect,
end_width_policy: crate::date_edit::WidthPolicy::Default,
feedback: Signal::new(ValidationFeedback::Pristine),
focused: Signal::new(false),
range_popover_open: Signal::new(false),
on_value_changed: None,
style_override: None,
root_child_id: None,
tooltip_text: None,
rich_tooltip_source: None,
composite_tooltip_content: None,
}
}
/// Per-call DateEditStyle override (shared with DateEdit family).
pub fn style(mut self, style: impl teksilo_core::styles::DateEditStyle) -> Self {
self.style_override = Some(std::rc::Rc::new(style));
self
}
/// Restrict the selectable start and end dates to those on or after `d`.
pub fn min_date(mut self, d: Date) -> Self {
self.min_date = Some(d);
self
}
/// Restrict the selectable start and end dates to those on or before `d`.
pub fn max_date(mut self, d: Date) -> Self {
self.max_date = Some(d);
self
}
/// Override the strftime-subset format pattern for both halves
/// (e.g. `"%d/%m/%Y"`). Defaults to the locale-derived pattern.
pub fn format_pattern(mut self, p: impl Into<String>) -> Self {
self.pattern = Some(p.into());
self
}
/// Placeholder shown in the start half when no date is set.
pub fn placeholder_start(mut self, text: impl Into<LocalizedString>) -> Self {
self.placeholder_start = text.into();
self
}
/// Placeholder shown in the end half when no date is set.
pub fn placeholder_end(mut self, text: impl Into<LocalizedString>) -> Self {
self.placeholder_end = text.into();
self
}
/// Override which weekday appears in the first column of the calendar popup.
pub fn first_day_of_week(mut self, w: Weekday) -> Self {
self.first_day_of_week = Some(w);
self
}
/// Set the enabled state, statically or reactively. Forwarded to the
/// arena at build time.
pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
self.enabled = enabled.into();
self
}
/// Make both halves read-only; the calendar button is also disabled.
pub fn read_only(mut self, read_only: bool) -> Self {
self.read_only = read_only;
self
}
/// Accessible label for the wrapper `Role::DateInput` node. When not set,
/// falls back to the localized `date-range-edit-name` message.
pub fn label(mut self, label: impl Into<LocalizedString>) -> Self {
let ls: LocalizedString = label.into();
self.label = Some(ls);
self
}
/// How both halves handle invalid or out-of-range text on blur / Enter.
/// Defaults to `ValidationBehavior::AutoCorrect`.
pub fn validation_behavior(mut self, behavior: ValidationBehavior) -> Self {
self.validation_behavior = behavior;
self
}
/// How the trailing (end) half claims horizontal space. The
/// leading (start) half always sizes to its natural mask width;
/// the end half follows this policy. Default
/// `WidthPolicy::Default` (natural width); pass
/// `WidthPolicy::Fill` to make the end half absorb extra
/// space the parent offers.
pub fn end_width_policy(mut self, policy: crate::date_edit::WidthPolicy) -> Self {
self.end_width_policy = policy;
self
}
/// Show a plain single-line tooltip on hover. Mutually exclusive with the
/// rich / composite tooltip slots — this setter clears the other two so the
/// last call wins.
pub fn tooltip(mut self, text: impl Into<LocalizedString>) -> Self {
self.tooltip_text = Some(text.into());
self.rich_tooltip_source = None;
self.composite_tooltip_content = None;
self
}
/// Show a rich tooltip sourced from the registry by `key`. Mutually
/// exclusive with the plain / composite tooltip slots — this setter clears
/// the other two so the last call wins.
pub fn rich_tooltip(mut self, key: impl Into<String>) -> Self {
self.rich_tooltip_source = Some(crate::tooltip::RichTooltipSource::Key(key.into()));
self.tooltip_text = None;
self.composite_tooltip_content = None;
self
}
/// Show a rich tooltip from an inline `TooltipContent` value. Mutually
/// exclusive with the plain / registry-key tooltip slots — this setter
/// clears the other two so the last call wins.
pub fn rich_tooltip_content(mut self, content: crate::tooltip::TooltipContent) -> Self {
self.rich_tooltip_source = Some(crate::tooltip::RichTooltipSource::Content(content));
self.tooltip_text = None;
self.composite_tooltip_content = None;
self
}
/// Show a composite tooltip whose body is an arbitrary widget tree. Mutually
/// exclusive with the plain / rich tooltip slots — this setter clears the
/// other two so the last call wins.
pub fn composite_tooltip(mut self, content: impl Widget + 'static) -> Self {
self.composite_tooltip_content = Some(Box::new(content));
self.tooltip_text = None;
self.rich_tooltip_source = None;
self
}
/// Reactive handle on the composed validation feedback (worse of the two
/// halves — `Invalid > Corrected > Valid > Pristine`).
pub fn validation_feedback_signal(&self) -> Signal<ValidationFeedback> {
self.feedback.clone()
}
/// Callback invoked whenever the range changes (including when one half
/// clears its value). Receives the new `Option<DateRange>` and an
/// `EventContext` for dispatching intents or side effects.
pub fn on_value_changed(
mut self,
f: impl Fn(Option<DateRange>, &mut EventContext) + 'static,
) -> Self {
self.on_value_changed = Some(Rc::new(f));
self
}
/// Clone the underlying `Signal<Option<DateRange>>` for external binding.
pub fn value(&self) -> Signal<Option<DateRange>> {
self.value.clone()
}
}
impl Widget for DateRangeEdit {
fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
let theme = ctx.theme_signal().get();
use crate::styles::recipe_date_edit_style as de;
use crate::styles::recipe_text_input_style as field_dims;
let focus_ring_width = theme.shape.focus_ring_width;
let self_id = ctx.self_id();
// Forward the enabled state into the arena; see IconButton.
ctx.enabled_when(self_id, self.enabled.clone());
let read_only = self.read_only;
// Resolve pattern — locale default unless overridden.
// A locale switch must re-derive the date pattern: it is read from
// `ctx.locale_signal()` at build time, and `WidgetTree::set_locale`
// only calls `mark_all_dirty` (layout + paint), which never re-runs
// `build()`. Without this binding the widget keeps rendering with
// the pattern of whatever locale was active when it was first
// built. Bound at `Rebuild` for the same reason `Calendar` binds
// the text scale there — the value is a build-time constant, so a
// relayout cannot pick it up.
ctx.locale_signal().bind_to(
ctx.self_id(),
ctx.binding_registry(),
teksilo_core::binding::BindingLevel::Rebuild,
);
let pattern_string = self.pattern.clone().unwrap_or_else(|| {
let tag = ctx.locale_signal().get().unwrap_or_default();
crate::common::datetime::format_pattern_for_locale(&tag).to_string()
});
let parsed_pattern = ParsedPattern::parse(&pattern_string)
.unwrap_or_else(|_| ParsedPattern::parse("%Y-%m-%d").unwrap());
let pattern_rc = Rc::new(parsed_pattern);
let mask_string = mask_for_pattern(&pattern_rc);
let min = self.min_date;
let max = self.max_date;
// Outer → halves: when the bound range changes externally,
// push start/end into the per-half date signals AND reformat
// their text. The text reformat is necessary so a programmatic
// `value.set(...)` shows up in the visible field, not just the
// hidden state.
{
let start_part = self.start_part.clone();
let end_part = self.end_part.clone();
let start_text = self.start_text.clone();
let end_text = self.end_text.clone();
let pattern = pattern_rc.clone();
ctx.effect(&self.value, move |new_range| {
let (s, e) = match new_range {
Some(r) => (Some(r.start), Some(r.end)),
None => (None, None),
};
if start_part.get() != s {
start_part.set(s);
}
if end_part.get() != e {
end_part.set(e);
}
let s_text = s
.map(|d| format_value(&pattern, Some(d), None))
.unwrap_or_default();
let e_text = e
.map(|d| format_value(&pattern, Some(d), None))
.unwrap_or_default();
if start_text.get() != s_text {
start_text.set(s_text);
}
if end_text.get() != e_text {
end_text.set(e_text);
}
});
}
// Seed text once at build time so the field shows the initial
// value without waiting for the first effect tick.
{
self.start_text.set(
self.start_part
.get()
.map(|d| format_value(&pattern_rc, Some(d), None))
.unwrap_or_default(),
);
self.end_text.set(
self.end_part
.get()
.map(|d| format_value(&pattern_rc, Some(d), None))
.unwrap_or_default(),
);
}
// ── Build each half as a bare TextInputField ───────────
// Each half returns (layout wrapper, inner editable field id).
let (start_field_id, start_inner_id) = self.build_half(
ctx,
HalfKind::Start,
pattern_rc.clone(),
&mask_string,
min,
max,
);
let (end_field_id, end_inner_id) = self.build_half(
ctx,
HalfKind::End,
pattern_rc.clone(),
&mask_string,
min,
max,
);
// ── Painted arrow separator ────────────────────────────
let separator_icon = arrow_right_icon(field_dims::TEXT_FIELD_HEIGHT * 0.45)
.color(teksilo_tokens::TextRole::Secondary);
let separator_id = ctx.add(
FixedSize::new()
.width(field_dims::TEXT_FIELD_HEIGHT * 0.65)
.height(field_dims::TEXT_FIELD_HEIGHT)
.child(Center::new().child(separator_icon)),
);
// ── Trailing calendar trigger ──────────────────────────
// Pre-build the dormant range calendar once.
let value_for_cal = self.value.clone();
let popover_open_for_cal = self.range_popover_open.clone();
let mut cal =
Calendar::range(value_for_cal.clone()).on_range_changed(move |new_range, ctx_evt| {
if new_range.is_some() {
popover_open_for_cal.set(false);
ctx_evt.dismiss_self_overlay_chain();
ctx_evt.request_frame();
}
});
if let Some(min) = self.min_date {
cal = cal.min_date(min);
}
if let Some(max) = self.max_date {
cal = cal.max_date(max);
}
if let Some(fdow) = self.first_day_of_week {
cal = cal.first_day_of_week(fdow);
}
// Detached rather than a child, and owned rather than orphaned — see
// `DateEdit`'s calendar for why both halves matter.
// Built the first time the popup is opened, not on every rebuild of the
// field. See `teksilo_core::deferred_subtree::DeferredSubtree`.
let cal_id = ctx.add_detached_deferred(self.range_popover_open.clone(), cal);
ctx.set_dormant(cal_id);
let popover_open = self.range_popover_open.clone();
let self_ref = ctx.self_id();
let dismiss_cb: OverlayDismissCallback = {
let popover_open = popover_open.clone();
Rc::new(move || {
popover_open.set(false);
})
};
let trigger_enabled = self.enabled.as_signal().map(move |on| *on && !read_only);
let trigger_btn = IconButton::new(calendar_glyph_icon(de::CALENDAR_ICON_SIZE))
.embedded()
.size(IconButtonSize::Default)
.enabled(trigger_enabled)
.tooltip(localized(move || {
resolve_message_widget("date-range-edit-trigger-tooltip", &[])
}))
.on_activate_fn(move |ctx_evt: &mut EventContext| {
if popover_open.get() {
popover_open.set(false);
ctx_evt.dismiss_all_except_hosts();
} else {
popover_open.set(true);
// Build the popup if this is its first open, before the overlay
// below is measured against it and focus moves into it.
ctx_evt.materialize_now(cal_id);
ctx_evt.activate(cal_id);
ctx_evt.show_overlay(OverlayRequest {
content_id: cal_id,
anchor: self_ref,
placement: OverlayPlacement::BelowPreferred,
dismiss: DismissBehavior::EscapeOrClickOutside,
layer: OverlayLayer::InTree,
parent_overlay: None,
on_dismiss: Some(dismiss_cb.clone()),
fade_duration: None,
});
ctx_evt.request_focus(cal_id);
}
});
let trigger_id = ctx.add(trigger_btn);
// ── Row layout ─────────────────────────────────────────
// No divider before the trailing trigger — Int UI's
// embedded IconButton sits flush inside the field's trailing slot
// (the same convention TextInput uses) and the button's own
// hover/pressed background gives it enough visual separation.
// Each half is wrapped in `Shrinkable` so the row can compress them
// when the unified frame is narrower than the combined natural mask
// width — the `TextInputField` inside then scrolls instead of
// overflowing. `Shrinkable` keeps each half's natural width when there
// is room, so the wide-case layout is unchanged.
let start_shrinkable =
ctx.add(crate::primitives::Shrinkable::new().child_id(start_field_id));
let end_shrinkable = ctx.add(crate::primitives::Shrinkable::new().child_id(end_field_id));
let row = HStack::new()
.spacing(0.0)
.add_child(start_shrinkable)
.add_child(separator_id)
.add_child(end_shrinkable)
.add_child(trigger_id);
let inline_row_id = ctx.add(row);
let row_id = ctx.add(
Padding::new(
0.0,
field_dims::TEXT_FIELD_PADDING_HORIZONTAL,
0.0,
field_dims::TEXT_FIELD_PADDING_HORIZONTAL,
)
.child_id(inline_row_id),
);
// ── Frame: bg + border driven by disabled + focus + validation ───
// This widget frames its two inner fields itself rather than
// delegating to `RecipeTextInputStyle`, so it has to opt into the
// neutral disabled roles the same way that recipe does — the
// accent-only substitution in `ColorProp::resolve` leaves
// `Content` / `Default` alone. Disabled outranks validation: an
// inert field must not shout an error the user cannot act on.
let feedback_for_border = self.feedback.clone();
let focused_for_border = self.focused.clone();
let is_disabled = ctx.effective_enabled_signal(self_id).map(|on| !*on);
let border_role = focused_for_border
.clone()
.zip3(&feedback_for_border, &is_disabled)
.map(|(focused, fb, disabled)| {
if *disabled {
return BorderRole::Disabled;
}
match fb {
ValidationFeedback::Invalid { .. } => BorderRole::Error,
ValidationFeedback::Corrected { .. } if !*focused => BorderRole::Focused,
_ => {
if *focused {
BorderRole::Focused
} else {
BorderRole::Field
}
}
}
});
let border_width_signal =
focused_for_border
.clone()
.zip(&feedback_for_border)
.map(move |(focused, fb)| {
if *focused || matches!(fb, ValidationFeedback::Invalid { .. }) {
focus_ring_width
} else {
field_dims::TEXT_FIELD_BORDER_WIDTH
}
});
let bg = RectWidget::new()
.background(SurfaceRole::Field)
.border_color(border_role)
.border_width(border_width_signal)
.corner_radius(CornerRadius::uniform(field_dims::TEXT_FIELD_CORNER_RADIUS));
let bg_id = ctx.add(bg);
let framed_id = ctx.add(ZStack::new().add_child(bg_id).add_child(row_id));
let sized_id =
ctx.add(MinSize::new(0.0, field_dims::TEXT_FIELD_HEIGHT).child_id(framed_id));
// ── Inline validation strip below the frame ───────────
let strip_id = ctx.add(crate::primitives::ValidationStrip::new(
self.feedback.clone(),
));
// WCAG 3.3.1 / 3.3.3: both editable halves are described by the shared
// validation message.
ctx.access_described_by(start_inner_id, strip_id);
ctx.access_described_by(end_inner_id, strip_id);
// Wrap the frame in `Expand::horizontal().respect_intrinsic()` so it
// claims the VStack's full width (a VStack doesn't stretch a child),
// while keeping its natural width as the basis when unconstrained. A
// bounded proposal narrows it and the `Shrinkable` halves compress.
let framed_in_vstack = ctx.add(
crate::primitives::Expand::horizontal()
.respect_intrinsic()
.child_id(sized_id),
);
let root_with_strip = ctx.add(
VStack::new()
.spacing(field_dims::TEXT_FIELD_VALIDATION_STRIP_GAP)
.add_child(framed_in_vstack)
.add_child(strip_id),
);
let style = crate::styles::recipe_date_edit_style::resolve_date_edit_style(
&self.style_override,
ctx,
);
let cfg = teksilo_core::styles::DateEditStyleConfig {
body: root_with_strip,
};
let root_id = style.make_body(&cfg, ctx);
self.root_child_id = Some(root_id);
// ── Tooltip attachment ─────────────────────────────────
if let Some(content) = self.composite_tooltip_content.take() {
let delay = ctx.theme().motion.tooltip_delay_heavy;
crate::tooltip::attach_composite_tooltip_boxed(ctx, root_id, content, delay);
} else if let Some(source) = self.rich_tooltip_source.clone() {
let delay = ctx.theme().motion.tooltip_delay;
crate::tooltip::attach_rich_tooltip_source(ctx, root_id, source, delay);
} else if let Some(text) = self.tooltip_text.clone() {
let delay = ctx.theme().motion.tooltip_delay;
crate::tooltip::attach_plain_tooltip(ctx, root_id, text, delay);
}
// ── Self handlers: focus_within drives the frame border ─
let handlers = HandlerSet::new().focus_within(self.focused.clone());
ctx.apply_self_handlers(handlers);
// Bind the value at AccessibilityOnly so the wrapper's AT
// node refreshes set_value when either half mutates.
let self_id = ctx.self_id();
self.value.bind_to(
self_id,
ctx.binding_registry(),
teksilo_core::binding::BindingLevel::AccessibilityOnly,
);
self.feedback.bind_to(
self_id,
ctx.binding_registry(),
teksilo_core::binding::BindingLevel::AccessibilityOnly,
);
self.range_popover_open.bind_to(
self_id,
ctx.binding_registry(),
teksilo_core::binding::BindingLevel::AccessibilityOnly,
);
// Suppress unused-field warning until we surface the trigger
// a11y separately.
let _ = trigger_id;
vec![root_with_strip]
}
fn layout_response(
&self,
proposal: SizeProposal,
ctx: &LayoutContext,
) -> teksilo_core::widget::LayoutResponse {
// Forward the inner LayoutResponse, then overlay flex=1 when
// the end half is Fill — the inner HStack consumes its
// children's flex internally and reports flex=0 to its
// parents, so the outer wrapper has to advertise flex
// explicitly for parent stacks to allocate slack.
let response = match self.root_child_id {
Some(id) => ctx
.child_layout_response(id, proposal)
.unwrap_or_else(|| proposal.resolve(0.0, 0.0).into()),
None => proposal.resolve(0.0, 0.0).into(),
};
if self.end_width_policy == crate::date_edit::WidthPolicy::Fill {
teksilo_core::widget::LayoutResponse::flexible(response.size, 1.0)
} else {
response
}
}
fn place_children(
&self,
bounds: Rect,
_proposal: SizeProposal,
children: &mut [WidgetPlacement],
_ctx: &LayoutContext,
) {
for child in children.iter_mut() {
child.origin = bounds.origin();
child.size = bounds.size();
}
}
fn children(&self) -> Vec<WidgetId> {
self.root_child_id.into_iter().collect()
}
fn accessibility(&self, builder: &mut AccessNodeBuilder) {
builder.set_role(Role::DateInput);
if let Some(ref label) = self.label {
builder.set_name(label.clone());
} else {
builder.set_name(resolve_message_widget("date-range-edit-name", &[]));
}
match self.value.get() {
Some(r) => {
builder.set_value(format!(
"{:04}-{:02}-{:02}/{:04}-{:02}-{:02}",
r.start.year(),
r.start.month(),
r.start.day(),
r.end.year(),
r.end.month(),
r.end.day(),
));
}
None => {
builder.set_placeholder(resolve_message_widget("date-range-edit-placeholder", &[]));
}
}
// Framework a11y walker sets `set_disabled` from arena state.
if self.read_only {
builder.set_read_only();
}
if matches!(self.feedback.get(), ValidationFeedback::Invalid { .. }) {
builder
.inner_mut()
.set_invalid(teksilo_core::accesskit::Invalid::True);
}
builder.add_action(Action::Focus);
}
}
#[derive(Clone, Copy)]
enum HalfKind {
Start,
End,
}
impl DateRangeEdit {
/// Build one half (start or end) as a bare `TextInputField` with
/// mask + validator + segment-stepping wired against the
/// appropriate per-half text/date signals. Returns the WidgetId
/// wrapped in a fixed-width container so both halves visually
/// align inside the unified frame.
#[allow(clippy::too_many_arguments)]
fn build_half(
&self,
ctx: &mut BuildContext,
kind: HalfKind,
pattern_rc: Rc<ParsedPattern>,
mask_string: &str,
min: Option<Date>,
max: Option<Date>,
) -> (WidgetId, WidgetId) {
use crate::styles::recipe_text_input_style as field_dims;
let (text_signal, date_signal, placeholder, other_date) = match kind {
HalfKind::Start => (
self.start_text.clone(),
self.start_part.clone(),
self.placeholder_start.clone(),
self.end_part.clone(),
),
HalfKind::End => (
self.end_text.clone(),
self.end_part.clone(),
self.placeholder_end.clone(),
self.start_part.clone(),
),
};
let validator =
build_date_validator(pattern_rc.clone(), min, max, self.validation_behavior);
let outer_value = self.value.clone();
let on_changed = self.on_value_changed.clone();
let merge_into_outer =
move |new_d: Option<Date>, other_d: Option<Date>, ctx_evt: &mut EventContext| {
let combined = match kind {
HalfKind::Start => match (new_d, other_d) {
(Some(s), Some(e)) => Some(DateRange::new(s, e)),
_ => None,
},
HalfKind::End => match (other_d, new_d) {
(Some(s), Some(e)) => Some(DateRange::new(s, e)),
_ => None,
},
};
if outer_value.get() != combined {
outer_value.set(combined);
if let Some(cb) = on_changed.as_ref() {
cb(combined, ctx_evt);
}
}
};
// Commit closure: parse the field text on Enter / blur, sync
// the per-half date signal, then merge into the outer range.
let commit: Rc<dyn Fn(&mut EventContext)> = {
let text_signal = text_signal.clone();
let date_signal = date_signal.clone();
let other_date = other_date.clone();
let pattern = pattern_rc.clone();
let merge = merge_into_outer.clone();
Rc::new(move |ctx_evt: &mut EventContext| {
let raw = text_signal.get();
let trimmed = raw.trim();
let parsed: Option<Date> = if trimmed.is_empty() {
None
} else {
match parse_value(&pattern, trimmed, ParseTarget::DateOnly) {
Some(ParsedValue::Date(d)) => Some(clamp_date(d, min, max)),
_ => date_signal.get(),
}
};
if date_signal.get() != parsed {
date_signal.set(parsed);
}
merge(parsed, other_date.get(), ctx_evt);
})
};
let inner_height =
(field_dims::TEXT_FIELD_HEIGHT - 2.0 * field_dims::TEXT_FIELD_BORDER_WIDTH).max(0.0);
let text_area_height =
(inner_height - 2.0 * field_dims::TEXT_FIELD_PADDING_VERTICAL).max(0.0);
let pattern_for_filter = pattern_rc.clone();
let mut field = TextInputField::new(text_signal.clone())
.enabled(self.enabled.clone())
.read_only(self.read_only)
.placeholder(placeholder)
.text_height(text_area_height)
.input_mask(mask_string)
.validator({
let v = validator.clone();
move |s| (v)(s)
})
.char_filter(move |c: char| {
if c.is_ascii_digit() || c == '-' || c == ' ' {
return true;
}
for tok in &pattern_for_filter.tokens {
if let crate::common::datetime::pattern::PatternToken::Literal(s) = tok
&& s.chars().any(|x| x == c)
{
return true;
}
}
false
});
// Mirror the inner field's feedback into the outer composed
// feedback signal (worse-of-two semantics).
{
let inner_feedback = field.validation_feedback_signal();
let composed = self.feedback.clone();
let other_feedback_owner = match kind {
HalfKind::Start => Some(self.feedback.clone()), // placeholder, replaced below
HalfKind::End => Some(self.feedback.clone()),
};
// The other half's feedback isn't accessible at this point
// (it's inside its own field). Compose via a per-half
// mirror: each half's effect computes max(self, current
// composed) → composed. As long as both halves install
// this, the worse always wins.
let _ = other_feedback_owner;
ctx.effect(&inner_feedback, move |new_fb| {
let merged = match (composed.get(), new_fb.clone()) {
(a, b) if rank(&a) >= rank(&b) => a,
(_, b) => b,
};
if composed.get() != merged {
composed.set(merged);
}
});
}
{
let commit = commit.clone();
field = field.on_submit_fn(move |ctx_evt| commit(ctx_evt));
}
{
let commit = commit.clone();
field = field.on_blur_fn(move |ctx_evt| commit(ctx_evt));
}
// Capture caret signal + caret_setter BEFORE moving the field
// into the tree, for segment-stepping.
let caret = field.caret_position();
let caret_setter = field.caret_setter();
// A11y: TimeInput-like role + the half's name for screen readers.
let half_label_key = match kind {
HalfKind::Start => "date-range-edit-start-name",
HalfKind::End => "date-range-edit-end-name",
};
let field_with_a11y = field
.access_role(Role::DateInput)
.access_label(resolve_message_widget(half_label_key, &[]));
let field_id = ctx.add(field_with_a11y);
// Padding around the field for visual alignment with the
// separator icon and trigger button.
let padded_field_id = ctx.add(
Padding::new(
field_dims::TEXT_FIELD_PADDING_VERTICAL,
4.0,
field_dims::TEXT_FIELD_PADDING_VERTICAL,
4.0,
)
.child_id(field_id),
);
// Width policy: start half is always at its natural mask
// width (so the start date doesn't reflow when only the end
// changes); end half follows `end_width_policy`. `Default`
// matches the start (fixed). `Fill` wraps in an
// `Expand::horizontal()` (zero-basis flex=1) so the end
// half absorbs the unified frame's leftover width.
let sized_field_id = match (kind, self.end_width_policy) {
(HalfKind::End, crate::date_edit::WidthPolicy::Fill) => {
ctx.add(crate::primitives::Expand::horizontal().child_id(padded_field_id))
}
_ => padded_field_id,
};
// ── Segment-stepping (Up/Down on focused segment) ──────
let segment_step: Rc<dyn Fn(i32, &mut EventContext)> = {
let pattern = pattern_rc.clone();
let date_signal = date_signal.clone();
let text_signal = text_signal.clone();
let other_date = other_date.clone();
let merge = merge_into_outer.clone();
Rc::new(move |delta: i32, ctx_evt: &mut EventContext| {
let pos = caret.get();
let Some((_, _, kind_seg)) = segment_at_position(&pattern, pos) else {
return;
};
let current = date_signal.get().unwrap_or_else(today_local);
let stepped = step_date_field(current, kind_seg, delta);
let clamped = clamp_date(stepped, min, max);
date_signal.set(Some(clamped));
text_signal.set(format_value(&pattern, Some(clamped), None));
caret_setter(pos);
merge(Some(clamped), other_date.get(), ctx_evt);
ctx_evt.request_frame();
})
};
// Attach key preview on a strict ancestor of the field — same
// pattern DateEdit uses for its ±segment stepping. No manual
// `enabled` gate here: dispatch is already centrally gated by
// `arena.is_enabled()` (walking up from the focused field
// through this ZStack to the composite root's `enabled_when`)
// before any handler — including `on_key_preview` — runs.
let read_only = self.read_only;
let step_for_key = segment_step.clone();
let stepping_id = ctx.add(ZStack::new().add_child(sized_field_id).on_key_preview(
move |event, ctx_evt| {
if read_only {
return EventResponse::Ignored;
}
let WidgetEvent::KeyDown { key, modifiers, .. } = event else {
return EventResponse::Ignored;
};
let mult = if modifiers.shift() { 10 } else { 1 };
let delta = match key {
Key::ArrowUp => mult,
Key::ArrowDown => -mult,
Key::PageUp => 10 * mult,
Key::PageDown => -10 * mult,
_ => return EventResponse::Ignored,
};
step_for_key(delta, ctx_evt);
EventResponse::Handled
},
));
// (layout wrapper, inner editable field) so the caller can wire
// `described_by` onto the node carrying Role::DateInput.
(stepping_id, field_id)
}
}
/// Severity rank for `ValidationFeedback`. Higher = more severe.
fn rank(fb: &ValidationFeedback) -> u8 {
match fb {
ValidationFeedback::Invalid { .. } => 3,
ValidationFeedback::Corrected { .. } => 2,
ValidationFeedback::Valid => 1,
ValidationFeedback::Pristine => 0,
}
}
/// Painted right-arrow chevron used as the visual separator
/// between the start and end halves. Same stroke convention as
/// the calendar header chevrons.
fn arrow_right_icon(size: f32) -> IconWidget {
let mut path = Path::new();
let s = size;
// Single chevron pointing right: `>`
path.move_to(Point::new(s * 0.35, s * 0.20));
path.line_to(Point::new(s * 0.70, s * 0.50));
path.line_to(Point::new(s * 0.35, s * 0.80));
IconWidget::from_path(path, size)
}