icedtea 0.17.2

Native desktop widgets and chrome for iced
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
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
//! Accessible name, role, value, hint, and state for every public widget.
//!
//! Pass [`A11y`] into the widget constructor. The constructor calls
//! [`attach`] and fills value, hint, and state from its arguments when
//! the record left them unset. Do not wrap an icedtea widget in a
//! second `attach`.
//!
//! iced 0.14 has no AccessKit slot. [`attach`] sets the iced widget id
//! from [`A11y::node_id`] (role, name, disabled). Value, hint, checked,
//! selected, toggled, expanded, live, required, and error stay on this
//! record. A screen reader does not receive them today. Keyboard order
//! is the working desktop path: an open modal first, then a focused
//! text field, then [`crate::key::handle`].
//!
//! An empty constructor caption falls back to [`A11y::name`]. A
//! non-empty caption is the visible face; the name is not rewritten to
//! match it. Decorative chrome may pass an empty name.
//!
//! ```
//! use icedtea::a11y::{A11y, Role};
//! let a = A11y::button("Save").with_disabled(true);
//! assert_eq!(a.role, Role::Button);
//! assert!(a.disabled);
//! assert!(a.apply_message(Some(1u8)).is_none());
//! ```

use iced::widget::{container, Id};
use iced::Element;

/// Platform role.
///
/// ```
/// use icedtea::a11y::{A11y, Role};
/// let a = A11y::button("Save");
/// assert_eq!(a.role, Role::Button);
/// assert!(!a.disabled);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    Button,
    Checkbox,
    Radio,
    Switch,
    Slider,
    Progress,
    SpinButton,
    TextBox,
    ComboBox,
    List,
    ListItem,
    Table,
    Tree,
    Tab,
    Menu,
    MenuItem,
    Dialog,
    Tooltip,
    Image,
    Link,
    Header,
    Status,
    Separator,
    Group,
}

impl Role {
    /// Stable token used in [`A11y::node_id`].
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Button => "button",
            Self::Checkbox => "checkbox",
            Self::Radio => "radio",
            Self::Switch => "switch",
            Self::Slider => "slider",
            Self::Progress => "progress",
            Self::SpinButton => "spinbutton",
            Self::TextBox => "textbox",
            Self::ComboBox => "combobox",
            Self::List => "list",
            Self::ListItem => "listitem",
            Self::Table => "table",
            Self::Tree => "tree",
            Self::Tab => "tab",
            Self::Menu => "menu",
            Self::MenuItem => "menuitem",
            Self::Dialog => "dialog",
            Self::Tooltip => "tooltip",
            Self::Image => "image",
            Self::Link => "link",
            Self::Header => "header",
            Self::Status => "status",
            Self::Separator => "separator",
            Self::Group => "group",
        }
    }
}

/// How a live region would be announced if the host published a tree.
///
/// iced 0.14 has no AccessKit slot; the field stays on [`A11y`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Live {
    #[default]
    Off,
    Polite,
    Assertive,
}

/// Accessible metadata attached to a widget.
///
/// This is the in-library semantics record (Flutter `Semantics` fields
/// icedtea can own without an OS assistive-technology hook). Pass it
/// into the constructor. [`attach`] does not publish role or value to
/// a screen reader on iced 0.14.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct A11y {
    pub name: String,
    pub role: Role,
    pub value: Option<String>,
    pub hint: Option<String>,
    pub disabled: bool,
    pub checked: Option<bool>,
    pub selected: Option<bool>,
    pub toggled: Option<bool>,
    pub expanded: Option<bool>,
    pub live: Live,
    pub required: bool,
    pub error: Option<String>,
}

impl A11y {
    pub fn new(name: impl Into<String>, role: Role) -> Self {
        Self {
            name: name.into(),
            role,
            value: None,
            hint: None,
            disabled: false,
            checked: None,
            selected: None,
            toggled: None,
            expanded: None,
            live: Live::Off,
            required: false,
            error: None,
        }
    }

    pub fn button(name: impl Into<String>) -> Self {
        Self::new(name, Role::Button)
    }

    pub fn with_value(mut self, value: impl Into<String>) -> Self {
        self.value = Some(value.into());
        self
    }

    pub fn with_hint(mut self, hint: impl Into<String>) -> Self {
        self.hint = Some(hint.into());
        self
    }

    pub fn with_disabled(mut self, disabled: bool) -> Self {
        self.disabled = disabled;
        self
    }

    pub fn with_checked(mut self, checked: bool) -> Self {
        self.checked = Some(checked);
        self
    }

    pub fn with_selected(mut self, selected: bool) -> Self {
        self.selected = Some(selected);
        self
    }

    pub fn with_toggled(mut self, toggled: bool) -> Self {
        self.toggled = Some(toggled);
        self
    }

    pub fn with_expanded(mut self, expanded: bool) -> Self {
        self.expanded = Some(expanded);
        self
    }

    pub fn with_live(mut self, live: Live) -> Self {
        self.live = live;
        self
    }

    pub fn with_required(mut self, required: bool) -> Self {
        self.required = required;
        self
    }

    pub fn with_error(mut self, error: impl Into<String>) -> Self {
        self.error = Some(error.into());
        self
    }

    /// Keep an explicit value; otherwise store `fallback`.
    pub fn merge_value(mut self, fallback: impl Into<String>) -> Self {
        if self.value.is_none() {
            self.value = Some(fallback.into());
        }
        self
    }

    /// Keep an explicit hint; otherwise store `fallback` when non-empty.
    pub fn merge_hint(mut self, fallback: impl Into<String>) -> Self {
        if self.hint.is_none() {
            let h = fallback.into();
            if !h.is_empty() {
                self.hint = Some(h);
            }
        }
        self
    }

    /// Keep an explicit checked; otherwise store the constructor face.
    pub fn merge_checked(mut self, fallback: bool) -> Self {
        if self.checked.is_none() {
            self.checked = Some(fallback);
        }
        self
    }

    /// Keep an explicit selected; otherwise store the constructor face.
    pub fn merge_selected(mut self, fallback: bool) -> Self {
        if self.selected.is_none() {
            self.selected = Some(fallback);
        }
        self
    }

    /// Keep an explicit toggled; otherwise store the constructor face.
    pub fn merge_toggled(mut self, fallback: bool) -> Self {
        if self.toggled.is_none() {
            self.toggled = Some(fallback);
        }
        self
    }

    /// Keep an explicit expanded; otherwise store the constructor open flag.
    pub fn merge_expanded(mut self, fallback: bool) -> Self {
        if self.expanded.is_none() {
            self.expanded = Some(fallback);
        }
        self
    }

    /// Keep an explicit live; otherwise store `fallback` when this is Off.
    pub fn merge_live(mut self, fallback: Live) -> Self {
        if self.live == Live::Off {
            self.live = fallback;
        }
        self
    }

    /// Keep an explicit error; otherwise store `fallback` when non-empty.
    pub fn merge_error(mut self, fallback: Option<&str>) -> Self {
        if self.error.is_none() {
            if let Some(e) = fallback.filter(|t| !t.is_empty()) {
                self.error = Some(e.to_string());
            }
        }
        self
    }

    /// Same name and disabled, new role. Value, hint, and state stay unset.
    pub fn child(&self, role: Role) -> Self {
        Self::new(self.name.clone(), role).with_disabled(self.disabled)
    }

    /// Stable iced widget id: role, name, disabled. Value, hint, and
    /// state must not change the node identity.
    pub fn node_id(&self) -> String {
        format!(
            "{}|{}|{}",
            self.role.as_str(),
            self.name,
            u8::from(self.disabled),
        )
    }

    /// Visible caption. Constructor title wins when non-empty;
    /// [`Self::name`] is the fallback. An empty name plus an empty
    /// caption stays empty (decorative chrome).
    pub fn apply_name(&self, caption: impl Into<String>) -> String {
        let caption = caption.into();
        if caption.is_empty() {
            self.name.clone()
        } else {
            caption
        }
    }

    /// Value: explicit [`Self::value`] or the constructor fallback.
    pub fn apply_value(&self, fallback: impl Into<String>) -> String {
        self.value.clone().unwrap_or_else(|| fallback.into())
    }

    /// Hint: explicit [`Self::hint`] or the constructor fallback.
    pub fn apply_hint(&self, fallback: impl Into<String>) -> String {
        self.hint.clone().unwrap_or_else(|| fallback.into())
    }

    /// Checked state: explicit [`Self::checked`] or the constructor fallback.
    pub fn apply_checked(&self, fallback: bool) -> bool {
        self.checked.unwrap_or(fallback)
    }

    /// Selected state: explicit [`Self::selected`] or the constructor fallback.
    pub fn apply_selected(&self, fallback: bool) -> bool {
        self.selected.unwrap_or(fallback)
    }

    /// Toggled state: explicit [`Self::toggled`] or the constructor fallback.
    pub fn apply_toggled(&self, fallback: bool) -> bool {
        self.toggled.unwrap_or(fallback)
    }

    /// Expanded state: explicit [`Self::expanded`] or the constructor fallback.
    pub fn apply_expanded(&self, fallback: bool) -> bool {
        self.expanded.unwrap_or(fallback)
    }

    /// Live: explicit non-Off [`Self::live`] or the constructor fallback.
    pub fn apply_live(&self, fallback: Live) -> Live {
        if self.live == Live::Off {
            fallback
        } else {
            self.live
        }
    }

    /// Error copy: explicit [`Self::error`] or the constructor fallback.
    pub fn apply_error(&self, fallback: Option<&str>) -> Option<String> {
        if let Some(e) = &self.error {
            return Some(e.clone());
        }
        fallback
            .filter(|t| !t.is_empty())
            .map(std::string::ToString::to_string)
    }

    /// Drop a press/toggle handler when disabled.
    pub fn apply_message<M>(&self, msg: Option<M>) -> Option<M> {
        if self.disabled {
            None
        } else {
            msg
        }
    }
}

/// Attach the record to a child. iced 0.14 has no AccessKit slot, so
/// this sets the iced widget id from [`A11y::node_id`] only.
///
/// The wrapper keeps the child's width and height so a fill child still
/// stretches. Value, hint, and state stay on `a11y`; they are not
/// written into the id.
pub fn attach<'a, M: 'a>(child: Element<'a, M>, a11y: &A11y) -> Element<'a, M> {
    let size = child.as_widget().size();
    container(child)
        .width(size.width)
        .height(size.height)
        .id(Id::from(a11y.node_id()))
        .into()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn builder_covers_roles() {
        let a = A11y::button("Go")
            .with_value("idle")
            .with_hint("Saves the buffer")
            .with_disabled(true)
            .with_checked(false)
            .with_selected(true)
            .with_toggled(false)
            .with_expanded(true)
            .with_live(Live::Polite)
            .with_required(true)
            .with_error("required");
        assert_eq!(a.name, "Go");
        assert_eq!(a.role, Role::Button);
        assert_eq!(a.value.as_deref(), Some("idle"));
        assert_eq!(a.hint.as_deref(), Some("Saves the buffer"));
        assert!(a.disabled);
        assert_eq!(a.checked, Some(false));
        assert_eq!(a.selected, Some(true));
        assert_eq!(a.toggled, Some(false));
        assert_eq!(a.expanded, Some(true));
        assert_eq!(a.live, Live::Polite);
        assert!(a.required);
        assert_eq!(a.error.as_deref(), Some("required"));
        for role in [
            Role::Checkbox,
            Role::Radio,
            Role::Switch,
            Role::Slider,
            Role::Progress,
            Role::SpinButton,
            Role::TextBox,
            Role::ComboBox,
            Role::List,
            Role::ListItem,
            Role::Table,
            Role::Tree,
            Role::Tab,
            Role::Menu,
            Role::MenuItem,
            Role::Dialog,
            Role::Tooltip,
            Role::Image,
            Role::Link,
            Role::Header,
            Role::Status,
            Role::Separator,
            Role::Group,
        ] {
            let a = A11y::new("x", role).with_value("v");
            assert!(a.node_id().starts_with(role.as_str()));
            assert!(a.node_id().contains("|x|"));
            let _: Element<'_, ()> = attach(iced::widget::text("x").into(), &a);
        }
        let disabled = A11y::button("Save").with_disabled(true).with_value("idle");
        assert_eq!(disabled.node_id(), "button|Save|1");
        assert!(disabled.apply_message(Some(1u8)).is_none());
        assert_eq!(disabled.apply_name("other"), "other");
        assert_eq!(A11y::button("").apply_name("Save"), "Save");
        assert_eq!(A11y::button("Name").apply_name(""), "Name");
        assert_eq!(A11y::button("Backspace").apply_name("⌫"), "⌫");
        assert_eq!(A11y::button("Backspace").name, "Backspace");
        assert!(A11y::new("c", Role::Checkbox)
            .with_checked(true)
            .apply_checked(false));
        assert!(!A11y::new("c", Role::Checkbox).apply_checked(false));
        assert_eq!(
            A11y::button("Go").with_checked(false).node_id(),
            A11y::button("Go").with_checked(true).node_id()
        );
        assert_eq!(
            A11y::button("Go").with_value("idle").node_id(),
            A11y::button("Go").with_value("busy").node_id()
        );
        assert_eq!(
            A11y::button("Go").with_checked(false).node_id(),
            "button|Go|0"
        );
        let parent = A11y::new("find", Role::Group)
            .with_disabled(true)
            .with_value("q");
        let child = parent.child(Role::TextBox);
        assert_eq!(child.name, "find");
        assert_eq!(child.role, Role::TextBox);
        assert!(child.disabled);
        assert!(child.value.is_none());
        assert_eq!(child.node_id(), "textbox|find|1");
        assert_eq!(parent.node_id(), "group|find|1");
        assert!(child.hint.is_none());
        assert!(child.expanded.is_none());
        assert_eq!(child.live, Live::Off);
        assert_eq!(
            A11y::button("Go").with_hint("a").node_id(),
            A11y::button("Go").with_hint("b").node_id()
        );
        assert_eq!(
            A11y::button("Go").with_live(Live::Polite).node_id(),
            A11y::button("Go").with_live(Live::Assertive).node_id()
        );
        assert!(A11y::button("").apply_name("").is_empty());
    }

    #[test]
    fn merge_keeps_explicit_and_fills_unset() {
        let filled = A11y::new("vol", Role::Slider)
            .with_value("0.2")
            .merge_value("0.9");
        assert_eq!(filled.value.as_deref(), Some("0.2"));
        let from_ctor = A11y::new("vol", Role::Slider).merge_value("0.4");
        assert_eq!(from_ctor.value.as_deref(), Some("0.4"));
        assert_eq!(from_ctor.apply_value("x"), "0.4");
        let hint = A11y::new("n", Role::TextBox).merge_hint("Help");
        assert_eq!(hint.hint.as_deref(), Some("Help"));
        assert_eq!(hint.apply_hint("other"), "Help");
        let err = A11y::new("n", Role::TextBox).merge_error(Some("bad"));
        assert_eq!(err.error.as_deref(), Some("bad"));
        assert_eq!(err.apply_error(Some("x")).as_deref(), Some("bad"));
        let open = A11y::new("notes", Role::Group).merge_expanded(true);
        assert_eq!(open.expanded, Some(true));
        assert!(open.apply_expanded(false));
        let live = A11y::new("toast", Role::Status).merge_live(Live::Polite);
        assert_eq!(live.live, Live::Polite);
        assert_eq!(live.apply_live(Live::Off), Live::Polite);
        assert_eq!(
            A11y::new("toast", Role::Status).apply_live(Live::Assertive),
            Live::Assertive
        );
        let bare = A11y::new("n", Role::TextBox);
        assert_eq!(
            bare.apply_error(Some("need a value")).as_deref(),
            Some("need a value")
        );
        assert!(bare.apply_error(Some("")).is_none());
        assert!(bare.apply_error(None).is_none());
        assert!(A11y::new("c", Role::Checkbox)
            .merge_checked(true)
            .apply_checked(false));
        assert!(A11y::new("s", Role::Switch)
            .merge_toggled(true)
            .apply_toggled(false));
        assert!(A11y::new("row", Role::ListItem)
            .merge_selected(true)
            .apply_selected(false));
    }

    #[test]
    fn live_and_value_update_on_a_new_record() {
        let first = A11y::new("p", Role::Progress)
            .merge_value("0.4")
            .merge_live(Live::Polite);
        assert_eq!(first.value.as_deref(), Some("0.4"));
        let later = A11y::new("p", Role::Progress)
            .merge_value("0.8")
            .merge_live(Live::Polite);
        assert_eq!(later.value.as_deref(), Some("0.8"));
        assert_eq!(first.node_id(), later.node_id());
        assert_ne!(first.value, later.value);
    }

    #[test]
    fn attach_keeps_fill_child() {
        use iced::widget::{container, Space};
        use iced::Length;
        let fill: Element<'_, ()> = container(Space::new())
            .width(Length::Fill)
            .height(Length::Fill)
            .into();
        let wrapped = attach(fill, &A11y::button("pane"));
        let size = wrapped.as_widget().size();
        assert_eq!(size.width, Length::Fill);
        assert_eq!(size.height, Length::Fill);
        let shrink: Element<'_, ()> = iced::widget::text("x").into();
        let wrapped = attach(shrink, &A11y::new("x", Role::Status));
        assert_eq!(wrapped.as_widget().size().width, Length::Shrink);
    }

    #[test]
    fn constructors_honor_disabled_name_and_record() {
        use crate::icon::Icons;
        use crate::theme;
        use crate::variant::Variant;
        use crate::widget;
        let tok = theme::named("dark").tokens;
        let disabled = A11y::button("Save").with_disabled(true);
        assert!(disabled.apply_message(Some(())).is_none());
        let _: Element<'_, ()> = widget::button(
            "",
            Some(()),
            tok,
            Variant::Primary,
            Icons::NONE,
            widget::ButtonOpts::SHRINK,
            disabled.clone(),
        );
        assert_eq!(disabled.apply_name(""), "Save");
        let named = A11y::button("Save");
        assert_eq!(named.apply_name(""), "Save");
        let _: Element<'_, ()> = widget::button(
            "",
            Some(()),
            tok,
            Variant::Primary,
            Icons::NONE,
            widget::ButtonOpts::SHRINK,
            named,
        );
        let rec = A11y::new("vol", Role::Slider)
            .with_hint("Volume")
            .merge_value(format!("{}", 0.4))
            .merge_checked(false);
        assert_eq!(rec.value.as_deref(), Some("0.4"));
        assert_eq!(rec.hint.as_deref(), Some("Volume"));
        assert_eq!(rec.checked, Some(false));
        let _: Element<'_, f32> = widget::slider(
            0.0..=1.0,
            0.4,
            |v| v,
            widget::SliderMarks {
                ticks: 2,
                min: "0",
                max: "1",
                vertical: false,
                thumb: "0.4",
            },
            tok,
            rec.clone(),
        );
        let box_rec = A11y::new("Accept", Role::Checkbox).with_checked(true);
        assert!(box_rec.apply_checked(false));
        let _: Element<'_, widget::CheckState> =
            widget::checkbox("Accept", widget::CheckState::Unchecked, |s| s, tok, box_rec);
        let field = A11y::new("Email", Role::Group)
            .merge_error(Some("Enter a valid address."))
            .merge_hint("We never share your email.");
        assert_eq!(field.error.as_deref(), Some("Enter a valid address."));
        assert_eq!(field.hint.as_deref(), Some("We never share your email."));
        let child = widget::text_input(
            "Email",
            "x",
            |s| s,
            None,
            widget::FieldOpts::NONE,
            tok,
            A11y::new("Email", Role::TextBox).merge_value("x"),
            None,
        );
        let _: Element<'_, String> = widget::field_support(
            child,
            Some("We never share your email."),
            Some("Enter a valid address."),
            tok,
            field,
        );
        let notes = A11y::new("Notes", Role::Group).merge_expanded(true);
        assert_eq!(notes.expanded, Some(true));
        let _: Element<'_, bool> = widget::expander(
            "Notes",
            None,
            iced::widget::text("body").into(),
            widget::Peek::Lines(2),
            true,
            1.0,
            |open| open,
            tok,
            notes,
        );
        let toast_rec = A11y::new("Saved", Role::Status)
            .merge_live(Live::Polite)
            .merge_value("Saved");
        assert_eq!(toast_rec.live, Live::Polite);
        assert_eq!(toast_rec.value.as_deref(), Some("Saved"));
        let t = crate::toast::Toast {
            id: 1,
            kind: crate::toast::ToastKind::Success,
            text: "Saved".into(),
            ttl_ms: 0,
            age_ms: 0,
        };
        let _: Element<'_, ()> = widget::toast_view(&t, (), tok, toast_rec);
    }
}