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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech
//! Checkbox — a two-state or tristate checkbox with an optional label.
//!
//! `Checkbox` renders a square (or rounded-square / circle) toggle box
//! alongside an optional label and caption. Two modes are supported:
//!
//! - **Two-state** ([`Checkbox::new`]): toggles a `Signal<bool>` between
//! `true` (checked) and `false` (unchecked) on click or Space.
//! - **Tristate** ([`Checkbox::tristate`]): cycles a `Signal<CheckState>`
//! between `Checked` and `Unchecked` on user interaction; the
//! `Indeterminate` state is set only by external sources such as
//! `TreeCheckedModel` aggregation — clicking from `Indeterminate` goes
//! to `Checked`, not a further third state.
//!
//! Chrome (box shape, fill, focus ring) is driven by the active
//! `CheckboxStyle`; three visual variants are available via
//! [`CheckboxVariant`].
//!
//! ## Accessibility
//!
//! Announces as `Role::CheckBox`. A label is required in debug builds
//! unless `.labels_hidden(true)` is set (for embedding inside a composite
//! row that owns the AT name). Keyboard: Space toggles; lone-KeyUp guard
//! prevents spurious toggle when focus is restored after a shortcut.
//!
//! ```rust
//! # use teksilo_widgets::Checkbox;
//! # use teksilo_core::signal::Signal;
//! # use teksilo_i18n::lit;
//! let checked = Signal::new(false);
//! let _cb = Checkbox::new(checked)
//! .label(lit!("Accept terms and conditions"));
//! ```
use std::rc::Rc;
use teksilo_canvas::{Rect, Size, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::build_context::BuildContext;
use teksilo_core::event::{EventResponse, Key, WidgetEvent};
use teksilo_core::signal::{Prop, Signal};
use teksilo_core::styles::{
CheckboxState, CheckboxStyleConfig, CheckboxVariant, SharedCheckboxStyle,
};
use teksilo_core::widget::{CursorIcon, EventContext, LayoutContext, Widget, WidgetPlacement};
use teksilo_core::widget_builder::HandlerSet;
use teksilo_core::widget_id::WidgetId;
use teksilo_data::CheckState;
use teksilo_tokens::{TextRole, TextStyleRole, VAlignment};
use crate::button::InteractionState;
use crate::primitives::{HStack, MinSize, TextWidget, VStack};
use teksilo_i18n::LocalizedString;
// ---------------------------------------------------------------------------
// Internal state wrapper
// ---------------------------------------------------------------------------
/// Wraps either a bool state (two-state) or a CheckState state (tristate).
#[derive(Clone)]
enum CheckKind {
TwoState(Signal<bool>),
TriState(Signal<CheckState>),
}
impl CheckKind {
fn check_state(&self) -> CheckState {
match self {
CheckKind::TwoState(s) => CheckState::from(s.get()),
CheckKind::TriState(s) => s.get(),
}
}
/// A reactive `Signal<CheckState>` that tracks the underlying
/// mutable root of either variant. Used to compose multi-source
/// derived visuals (e.g. box colors that depend on both interaction
/// state and check state) so they dirty-track the check-state
/// source in addition to the interaction source.
fn check_state_signal(&self) -> Signal<CheckState> {
match self {
CheckKind::TwoState(s) => s.map(|b| CheckState::from(*b)),
CheckKind::TriState(s) => s.clone(),
}
}
fn toggle(&self) {
match self {
CheckKind::TwoState(s) => {
let current = s.get();
s.set(!current);
}
CheckKind::TriState(s) => {
// User clicks toggle Checked ↔ Unchecked. The
// `Indeterminate` state is reserved for external
// sources (e.g. `TreeCheckedModel` aggregation when
// descendants are mixed) — the user can't *set* a
// checkbox to "half"; clicking from Indeterminate
// checks the whole. This matches the Outlook /
// Files-app folder-checkbox semantic.
let current = s.get();
let next = if matches!(current, CheckState::Checked) {
CheckState::Unchecked
} else {
CheckState::Checked
};
s.set(next);
}
}
}
}
impl std::fmt::Debug for CheckKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CheckKind::TwoState(_) => write!(f, "TwoState"),
CheckKind::TriState(_) => write!(f, "TriState"),
}
}
}
// ---------------------------------------------------------------------------
// Checkbox
// ---------------------------------------------------------------------------
/// A checkbox that toggles a `Signal<bool>` or cycles a `Signal<CheckState>`.
pub struct Checkbox {
label: Option<LocalizedString>,
caption: Option<LocalizedString>,
kind: CheckKind,
/// Enabled state, static or reactive; forwarded into the arena at
/// build time. After build the arena is the single source of
/// truth — see `IconButton::enabled` for the architectural
/// rationale.
enabled: Prop<bool>,
/// When true, the checkbox renders only the box (no visual label /
/// caption next to it) AND its `accessibility(builder)` skips the
/// missing-label `debug_assert` — the parent composite is responsible
/// for providing the AT name (typically via its own `set_name(...)`
/// or an `access_label*` override). Used by `StandardListItem` /
/// `StandardTreeItem`.
labels_hidden: bool,
tooltip_text: Option<LocalizedString>,
rich_tooltip_source: Option<crate::tooltip::RichTooltipSource>,
composite_tooltip_content: Option<Box<dyn teksilo_core::widget::Widget>>,
variant: CheckboxVariant,
style_override: Option<SharedCheckboxStyle>,
root_child_id: Option<WidgetId>,
}
impl Checkbox {
/// Create a two-state checkbox bound to a `Signal<bool>`.
pub fn new(checked: Signal<bool>) -> Self {
Self {
label: None,
caption: None,
kind: CheckKind::TwoState(checked),
enabled: Prop::Static(true),
labels_hidden: false,
tooltip_text: None,
rich_tooltip_source: None,
composite_tooltip_content: None,
variant: CheckboxVariant::default(),
style_override: None,
root_child_id: None,
}
}
/// Create a tristate checkbox bound to a `Signal<CheckState>`.
///
/// User clicks toggle Checked ↔ Unchecked (clicking from Indeterminate
/// checks the whole). The `Indeterminate` state is reserved for external
/// sources — `TreeCheckedModel` aggregation when descendants are mixed,
/// "select all" indicators, etc. Matches the Outlook / Files-app
/// folder-checkbox semantic. Useful for parent checkboxes in tree views.
pub fn tristate(state: Signal<CheckState>) -> Self {
Self {
label: None,
caption: None,
kind: CheckKind::TriState(state),
enabled: Prop::Static(true),
labels_hidden: false,
tooltip_text: None,
rich_tooltip_source: None,
composite_tooltip_content: None,
variant: CheckboxVariant::default(),
style_override: None,
root_child_id: None,
}
}
/// Suppress the visual label/caption AND the debug-time
/// "missing accessible label" assertion. Use this **only** when
/// the checkbox is embedded inside a composite that owns the
/// row's accessible name (e.g. `StandardListItem` /
/// `StandardTreeItem`, where the row's `accessibility(builder)`
/// calls `set_name(...)` with the row label).
///
/// **A11y contract:** when `labels_hidden(true)` is set, the
/// caller MUST guarantee that an addressable AT ancestor
/// provides the name — either via that ancestor's own
/// `accessibility()` impl or a builder-level
/// `.access_label*` override. Without it the AT tree exposes a
/// `Role::CheckBox` node with no name; screen readers announce
/// "checkbox, checked" with no context. The Outlook /
/// Files-app row pattern (where the row label covers the
/// embedded checkbox) is the supported use case.
pub fn labels_hidden(mut self, hidden: bool) -> Self {
self.labels_hidden = hidden;
self
}
/// Set the visible label rendered to the right of the checkbox box,
/// also used as the AT name. Required unless `.labels_hidden(true)` is set.
pub fn label(mut self, label: impl Into<LocalizedString>) -> Self {
let ls: LocalizedString = label.into();
self.label = Some(ls);
self
}
/// Secondary explanatory text rendered below the label, left-aligned
/// with the label (not the box). Uses the `small` / `text_secondary`
/// style. Has no effect unless `label(...)` is also set.
pub fn caption(mut self, text: impl Into<LocalizedString>) -> Self {
let ls: LocalizedString = text.into();
self.caption = Some(ls);
self
}
/// Set the enabled state, statically or reactively. Forwarded to the
/// arena via `ctx.enabled_when(self_id, self.enabled.clone())` at
/// build time — a bound `Signal<bool>` updates live.
pub fn enabled(mut self, enabled: impl Into<Prop<bool>>) -> Self {
self.enabled = enabled.into();
self
}
/// Pick the design-language variant. Default `Square`. The active
/// `CheckboxStyle` impl decides what the variant means visually
/// (the IntUI `RecipeCheckboxStyle` honours all three variants
/// directly via corner-shape changes).
pub fn variant(mut self, variant: CheckboxVariant) -> Self {
self.variant = variant;
self
}
/// Per-call style override. Replaces the theme-wide default
/// `CheckboxStyle` for just this Checkbox instance — same role as
/// `Button::style(...)`.
pub fn style(mut self, style: impl teksilo_core::styles::CheckboxStyle) -> Self {
self.style_override = Some(Rc::new(style));
self
}
/// Attach a plain tooltip shown after a hover delay.
/// Clears any previously set rich or composite tooltip (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
}
/// Attach a rich tooltip resolved from the app-wide tooltip
/// registry. See [`Button::rich_tooltip`](crate::button::Button::rich_tooltip).
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
}
/// Attach a rich tooltip driven by inline `TooltipContent`.
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
}
/// Attach a composite tooltip — third tier, hosting an arbitrary
/// widget tree. See [`Button::composite_tooltip`](crate::button::Button::composite_tooltip).
pub fn composite_tooltip(
mut self,
content: impl teksilo_core::widget::Widget + 'static,
) -> Self {
self.composite_tooltip_content = Some(Box::new(content));
self.tooltip_text = None;
self.rich_tooltip_source = None;
self
}
fn check_state(&self) -> CheckState {
self.kind.check_state()
}
}
impl std::fmt::Debug for Checkbox {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Checkbox")
.field("label", &self.label)
.field("caption", &self.caption)
.field("kind", &self.kind)
.field("enabled", &self.enabled.get())
.finish()
}
}
// ---------------------------------------------------------------------------
// Widget
// ---------------------------------------------------------------------------
/// Internal interaction state — local to this widget's handlers; the
/// active `CheckboxStyle` only sees the four derived boolean signals
impl Widget for Checkbox {
fn build(&mut self, ctx: &mut BuildContext) -> Vec<WidgetId> {
use crate::styles::recipe_checkbox_style as cb_dims;
let kind = self.kind.clone();
let variant = self.variant;
let self_id = ctx.self_id();
// Forward the enabled state into the arena. After this point
// the arena is the single source of truth (same architecture
// as IconButton — leaves consume `effective_enabled` at paint
// time, events are gated on `is_enabled`, a11y walker reads it).
ctx.enabled_when(self_id, self.enabled.clone());
let effective_enabled = ctx.effective_enabled_signal(self_id);
// Interaction signal seeded to Idle — the arena's enabled-state
// is consulted separately via `effective_enabled`.
let interaction = ctx.signal(InteractionState::Idle);
// Bridge the widget-side `CheckState` (teksilo-data) to the style-
// protocol-side `CheckboxState` (teksilo-core). The mapping is 1-to-1;
// `.map()` registers the upstream root so the body repaints when
// the check state flips.
let style_state = kind.check_state_signal().map(|cs| match *cs {
CheckState::Unchecked => CheckboxState::Unchecked,
CheckState::Checked => CheckboxState::Checked,
CheckState::Indeterminate => CheckboxState::Indeterminate,
});
let is_hovered = interaction.map(|s| matches!(s, InteractionState::Hovered));
let is_pressed = interaction.map(|s| matches!(s, InteractionState::Pressed));
// `:focus-visible`: reveal the focus ring during keyboard navigation
// only, not on a mouse click. Gate raw focus on the input-modality
// signal (true after a key event, false after pointer-down).
let is_focused = interaction
.map(|s| matches!(s, InteractionState::Focused))
.and(&ctx.focus_visible());
// is_disabled derives from the arena (not from interaction).
let is_disabled = effective_enabled.map(|on| !*on);
let style: SharedCheckboxStyle = self
.style_override
.clone()
.or_else(|| ctx.theme().style_slots.checkbox.clone())
.unwrap_or_else(|| Rc::new(crate::styles::RecipeCheckboxStyle::default()));
let cfg = CheckboxStyleConfig {
state: style_state,
is_hovered,
is_pressed,
is_focused,
is_disabled,
variant,
};
let body_id = style.make_body(&cfg, ctx);
let mut row = HStack::new()
.spacing(cb_dims::CHECKBOX_LABEL_GAP)
.add_child(body_id);
if !self.labels_hidden
&& let Some(ref label) = self.label
{
let label_widget = TextWidget::new(label.clone())
.style(TextStyleRole::Body)
.color(TextRole::Primary)
.single_line()
.a11y_hidden();
let label_id = ctx.add(label_widget);
let label_column_id = if let Some(ref caption) = self.caption {
let caption_widget = TextWidget::new(caption.clone())
.style(TextStyleRole::Small)
.color(TextRole::Secondary)
.a11y_hidden();
let caption_id = ctx.add(caption_widget);
ctx.add(
VStack::new()
.spacing(2.0)
.add_child(label_id)
.add_child(caption_id),
)
} else {
label_id
};
row = row.add_child(label_column_id);
}
// When a caption is present, top-align the row so the box sits next
// to the label's first line rather than the center of both lines.
if self.caption.is_some() && self.label.is_some() {
row = row.alignment(VAlignment::Top);
}
let row_id = ctx.add(row);
let root_id = ctx.add(
MinSize::new(
cb_dims::CHECKBOX_BOX_HIT_AREA,
cb_dims::CHECKBOX_BOX_HIT_AREA,
)
.child_id(row_id),
);
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.take() {
let delay = ctx.theme().motion.tooltip_delay;
crate::tooltip::attach_rich_tooltip_source(ctx, root_id, source, delay);
} else if let Some(tooltip_text) = self.tooltip_text.clone() {
let delay = ctx.theme().motion.tooltip_delay;
crate::tooltip::attach_plain_tooltip(ctx, root_id, tooltip_text, delay);
}
self.root_child_id = Some(root_id);
// --- V2 attached handlers ---
let kind_tap = self.kind.clone();
let kind_key = self.kind.clone();
let kind_access = self.kind.clone();
let int_tap = interaction.clone();
let int_hover = interaction.clone();
let int_key = interaction.clone();
let int_focus = interaction.clone();
// Framework gates events on `arena.is_enabled(self_id)`, so
// these closures only run when the widget is effectively
// enabled. The old `if !enabled { return; }` snapshot guards
// are gone.
let handler_set = HandlerSet::new()
.on_tap({
move |_pos, _ctx: &mut EventContext| {
kind_tap.toggle();
int_tap.set(InteractionState::Hovered);
}
})
.on_hover({
move |entered: bool, _ctx: &mut EventContext| {
if entered {
int_hover.set(InteractionState::Hovered);
} else {
int_hover.set(InteractionState::Idle);
}
}
})
.on_key({
move |event: &WidgetEvent, _ctx: &mut EventContext| -> EventResponse {
match event {
WidgetEvent::KeyDown {
key: Key::Space, ..
} => {
int_key.set(InteractionState::Pressed);
EventResponse::Handled
}
WidgetEvent::KeyUp {
key: Key::Space, ..
} => {
// Lone-KeyUp guard: only toggle if we saw the
// matching KeyDown (state is Pressed). A stray KeyUp
// — e.g. a shortcut consumed the KeyDown and focus
// returned here — must NOT toggle.
if int_key.get() != InteractionState::Pressed {
return EventResponse::Ignored;
}
kind_key.toggle();
int_key.set(InteractionState::Focused);
EventResponse::Handled
}
_ => EventResponse::Ignored,
}
}
})
.on_focus({
move |gained: bool, _ctx: &mut EventContext| {
if gained {
if int_focus.get() == InteractionState::Idle {
int_focus.set(InteractionState::Focused);
}
} else {
int_focus.set(InteractionState::Idle);
}
}
})
.on_access_action({
move |action: teksilo_core::accesskit::Action,
_ctx: &mut EventContext|
-> EventResponse {
if action == teksilo_core::accesskit::Action::Click {
kind_access.toggle();
EventResponse::Handled
} else {
EventResponse::Ignored
}
}
})
// Focus walker skips disabled subtrees on its own.
.focusable(true)
.cursor(CursorIcon::Pointer);
ctx.apply_self_handlers(handler_set);
vec![root_id]
}
fn layout_response(
&self,
proposal: SizeProposal,
ctx: &LayoutContext,
) -> teksilo_core::widget::LayoutResponse {
if let Some(root) = self.root_child_id
&& let Some(size) = ctx.child_size(root, proposal)
{
return (size).into();
}
proposal.resolve(0.0, 0.0).into()
}
fn place_children(
&self,
bounds: Rect,
_proposal: SizeProposal,
children: &mut [WidgetPlacement],
_ctx: &LayoutContext,
) {
for child in children.iter_mut() {
child.origin = teksilo_canvas::Point::new(bounds.x, bounds.y);
child.size = Size::new(bounds.width, bounds.height);
}
}
fn accessibility(&self, builder: &mut AccessNodeBuilder) {
debug_assert!(
self.label.is_some() || self.labels_hidden,
"Checkbox is missing an accessible label — \
screen readers will announce \"checkbox\" with no context. \
Call .label(...) when constructing the widget, or \
.labels_hidden(true) when embedded in a composite that \
owns the AT name."
);
builder.set_role(teksilo_core::accesskit::Role::CheckBox);
if let Some(ref label) = self.label {
builder.set_name(label.resolve_now());
}
if let Some(ref caption) = self.caption {
builder.set_description(caption.resolve_now());
}
match self.check_state() {
CheckState::Checked => builder.set_toggled(true),
CheckState::Unchecked => builder.set_toggled(false),
CheckState::Indeterminate => {
// AccessKit's Toggled::Mixed maps to ARIA "mixed"
builder
.inner_mut()
.set_toggled(teksilo_core::accesskit::Toggled::Mixed);
}
}
// Framework's accessibility walker calls `set_disabled` based
// on `arena.is_enabled(self_id)` — no need to mirror here.
builder.add_action(teksilo_core::accesskit::Action::Click);
builder.add_action(teksilo_core::accesskit::Action::Focus);
}
fn children(&self) -> Vec<WidgetId> {
self.root_child_id.into_iter().collect()
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use teksilo_core::event::Modifiers;
use teksilo_core::widget_tree::WidgetTree;
use teksilo_i18n::lit;
#[test]
fn focus_ring_only_under_focus_visible() {
// `:focus-visible`: the focus border shows during keyboard navigation
// but not on a pointer click. Programmatic focus leaves `focus_visible`
// false → no border; a key press flips the modality and reveals it.
let theme = teksilo_core::presets::intui::light();
let ring = theme.colors.border_focused.to_array();
let mut tree = WidgetTree::new().with_theme(theme);
let cb = tree.add(Checkbox::new(Signal::new(false)).label(lit!("A")));
tree.layout(SizeProposal::exact(200.0, 80.0));
tree.focus(cb);
assert!(
!frame_has_color(&tree.render(), ring),
"no focus border while focus-visible is false (pointer modality)",
);
tree.press_key(Key::ArrowDown, Modifiers::NONE);
assert!(
frame_has_color(&tree.render(), ring),
"focus border shows under keyboard modality",
);
}
/// Whether `color` appears in any color-bearing layer of the frame.
fn frame_has_color(frame: &teksilo_canvas::RenderFrame, color: [f32; 4]) -> bool {
frame.shapes.iter().any(|s| s.color == color)
|| frame.decorations.iter().any(|d| d.color == color)
|| frame.cosmetic_lines.iter().any(|l| l.color == color)
}
// --- Two-state tests ---
#[test]
fn click_toggles_bool_state() {
let checked = Signal::new(false);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let cb = tree.add(Checkbox::new(checked.clone()).label(lit!("Accept")));
tree.layout(SizeProposal::exact(200.0, 80.0));
assert!(!checked.get());
tree.click(cb);
assert!(checked.get());
tree.click(cb);
assert!(!checked.get());
}
#[test]
fn space_toggles_bool_state() {
let checked = Signal::new(false);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let cb = tree.add(Checkbox::new(checked.clone()).label(lit!("Accept")));
tree.layout(SizeProposal::exact(200.0, 80.0));
tree.focus(cb);
tree.press_key(Key::Space, Modifiers::NONE);
assert!(checked.get());
tree.press_key(Key::Space, Modifiers::NONE);
assert!(!checked.get());
}
#[test]
fn lone_keyup_does_not_toggle() {
// Lone-KeyUp guard: a KeyUp with no matching KeyDown (e.g. a shortcut
// consumed the KeyDown, then focus returned here) must NOT toggle.
let checked = Signal::new(false);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let cb = tree.add(Checkbox::new(checked.clone()).label(lit!("Accept")));
tree.layout(SizeProposal::exact(200.0, 80.0));
tree.focus(cb);
tree.dispatch_event(WidgetEvent::KeyUp {
key: Key::Space,
modifiers: Modifiers::NONE,
});
assert!(!checked.get(), "a lone KeyUp must not toggle the checkbox");
// A matched pair still toggles.
tree.press_key(Key::Space, Modifiers::NONE);
assert!(checked.get());
}
#[test]
fn disabled_ignores_click() {
let checked = Signal::new(false);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let cb = tree.add(
Checkbox::new(checked.clone())
.label(lit!("Accept"))
.enabled(false),
);
tree.layout(SizeProposal::exact(200.0, 80.0));
tree.click(cb);
assert!(!checked.get());
}
#[test]
fn two_state_accessibility() {
let checked = Signal::new(true);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let cb = tree.add(Checkbox::new(checked).label(lit!("Accept")));
tree.layout(SizeProposal::exact(200.0, 80.0));
let info = tree.accessibility_node(cb);
assert_eq!(info.role(), teksilo_core::accesskit::Role::CheckBox);
assert_eq!(info.name(), Some("Accept"));
assert!(info.is_toggled());
}
// --- Tristate tests ---
#[test]
fn tristate_user_click_toggles_two_states() {
// User clicks only toggle Checked ↔ Unchecked. Indeterminate is
// reserved for external sources (TreeCheckedModel aggregation, etc.)
// — clicking from Indeterminate checks the whole. Outlook / Files-app
// folder-checkbox semantic.
let state = Signal::new(CheckState::Unchecked);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let cb = tree.add(Checkbox::tristate(state.clone()).label(lit!("Select All")));
tree.layout(SizeProposal::exact(200.0, 80.0));
assert_eq!(state.get(), CheckState::Unchecked);
tree.click(cb);
assert_eq!(state.get(), CheckState::Checked);
tree.click(cb);
assert_eq!(state.get(), CheckState::Unchecked);
// Clicking from Indeterminate checks the whole, NOT cycles.
state.set(CheckState::Indeterminate);
tree.click(cb);
assert_eq!(state.get(), CheckState::Checked);
}
#[test]
fn tristate_space_toggles_two_states() {
let state = Signal::new(CheckState::Unchecked);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let cb = tree.add(Checkbox::tristate(state.clone()).label(lit!("Select All")));
tree.layout(SizeProposal::exact(200.0, 80.0));
tree.focus(cb);
tree.press_key(Key::Space, Modifiers::NONE);
assert_eq!(state.get(), CheckState::Checked);
tree.press_key(Key::Space, Modifiers::NONE);
assert_eq!(state.get(), CheckState::Unchecked);
}
#[test]
fn tristate_indeterminate_shows_filled_background() {
// Indeterminate is_filled() == true, so it should have a primary background
let state = Signal::new(CheckState::Indeterminate);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
tree.add(Checkbox::tristate(state).label(lit!("Partial")));
tree.layout(SizeProposal::exact(200.0, 80.0));
let frame = tree.render();
let primary = teksilo_core::presets::intui::light()
.colors
.accent
.to_array();
assert!(
frame.shapes.iter().any(|s| s.color == primary),
"indeterminate checkbox should have primary-colored background"
);
}
#[test]
fn check_state_conversions() {
assert_eq!(CheckState::from(true), CheckState::Checked);
assert_eq!(CheckState::from(false), CheckState::Unchecked);
assert!(CheckState::Checked.is_filled());
assert!(CheckState::Indeterminate.is_filled());
assert!(!CheckState::Unchecked.is_filled());
}
#[test]
fn disabled_has_disabled_colors() {
let checked = Signal::new(true);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
tree.add(
Checkbox::new(checked)
.label(lit!("Disabled"))
.enabled(false),
);
tree.layout(SizeProposal::exact(200.0, 80.0));
let frame = tree.render();
let disabled_fill = teksilo_core::presets::intui::light()
.colors
.accent_disabled
.to_array();
assert!(
frame.shapes.iter().any(|s| s.color == disabled_fill),
"disabled checkbox should render with disabled_fill color"
);
}
#[test]
fn accessibility_has_actions() {
let checked = Signal::new(false);
let mut tree = WidgetTree::new().with_theme(teksilo_core::presets::intui::light());
let cb = tree.add(Checkbox::new(checked).label(lit!("Accept")));
tree.layout(SizeProposal::exact(200.0, 80.0));
let info = tree.accessibility_node(cb);
assert!(
info.actions()
.contains(&teksilo_core::accesskit::Action::Click)
);
}
}