Skip to main content

native_gui_core/
toolbar.rs

1//! Portable toolbar model.
2//!
3//! Shared, backend-agnostic model for `WidgetKind::Toolbar` per
4//! `docs/widget-expansion-roadmap.md` §14: stable [`ToolId`]s that survive
5//! rebuilds and reorders, separators, icon/text display modes, checkable and
6//! exclusive radio tools, dropdown tools, and the pure rules every lane must
7//! agree on.
8//!
9//! The rules are functions, not a second state store: [`Ui`](crate::Ui) owns
10//! the item list on the widget spec, applies these helpers, and forwards the
11//! resulting list to the backend. Keeping them here means the Mock oracle and
12//! the native toolbars cannot drift on the two behaviours that are easy to get
13//! wrong:
14//!
15//! - **radio exclusivity** — checking one member of a group unchecks the other
16//!   members, and a user toggle reports one `ToolToggled` per changed tool
17//!   (never a single "group" event);
18//! - **programmatic vs user edits** — [`set_tool_state`] is silent by design
19//!   (no activation echo), while [`click_tool`] is the user path that produces
20//!   the events.
21//!
22//! The native compositions (GTK `gtk::Box`, Win32 `TOOLBARCLASSNAME`, Cocoa
23//! `NSToolbar`) land later; until then every backend refuses
24//! the kind and the toolbar setters with the typed unsupported error instead
25//! of faking a toolbar.
26
27use std::fmt;
28
29use crate::artprov::IconRole;
30
31/// Stable, application-facing identifier of one toolbar tool.
32///
33/// The model never mints or reuses ids: applications own the values, and the
34/// same id keeps referring to the same tool across [`ToolbarItem`] rebuilds
35/// and reorders (`set_toolbar_items`), which is what lets an app map a
36/// `ToolActivated` back to its own command without title matching.
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
38pub struct ToolId(pub u64);
39
40impl ToolId {
41    /// The numeric value, for diagnostics and evidence dumps.
42    pub const fn get(self) -> u64 {
43        self.0
44    }
45}
46
47impl fmt::Display for ToolId {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        write!(f, "tool {}", self.0)
50    }
51}
52
53/// How a tool presents its label and icon where the lane supports both.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
55pub enum ToolDisplay {
56    /// Icon and text together (the default: neither is the only accessible
57    /// name).
58    #[default]
59    IconAndText,
60    /// Icon only; the label stays the accessible name and tooltip source.
61    IconOnly,
62    /// Text only, for lanes or tools without an icon.
63    TextOnly,
64}
65
66impl ToolDisplay {
67    /// Stable lowercase identifier used by tests and evidence dumps.
68    pub const fn as_str(self) -> &'static str {
69        match self {
70            Self::IconAndText => "icon-and-text",
71            Self::IconOnly => "icon-only",
72            Self::TextOnly => "text-only",
73        }
74    }
75}
76
77/// Toolbar stacking orientation.
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
79pub enum ToolbarOrientation {
80    /// Left-to-right (the default, and the only orientation Cocoa offers).
81    #[default]
82    Horizontal,
83    /// Top-to-bottom; gated per lane by the `toolbar_vertical` capability.
84    Vertical,
85}
86
87impl ToolbarOrientation {
88    /// Stable lowercase identifier used by tests and evidence dumps.
89    pub const fn as_str(self) -> &'static str {
90        match self {
91            Self::Horizontal => "horizontal",
92            Self::Vertical => "vertical",
93        }
94    }
95}
96
97/// One toolbar tool.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct ToolSpec {
100    /// Stable application-facing id.
101    pub id: ToolId,
102    /// Visible label (also the accessible name unless overridden by
103    /// [`ToolSpec::accessible_label`]).
104    pub label: String,
105    /// Optional accessible name for assistive technology, for tools whose visible
106    /// label is absent or not meaningful —
107    /// most importantly icon-only tools. [`ToolSpec::accessible_name`]
108    /// resolves the announcement as this value, else [`ToolSpec::label`],
109    /// else a documented `tool <id>` default, so a tool never announces
110    /// nothing.
111    pub accessible_label: Option<String>,
112    /// Optional tooltip/short help text.
113    pub tooltip: Option<String>,
114    /// Optional stock-art role; the artprov lane resolves it per DPI.
115    pub icon: Option<IconRole>,
116    /// Icon/text presentation preference.
117    pub display: ToolDisplay,
118    /// Whether the tool can be activated; disabled tools report as disabled
119    /// rather than disappearing.
120    pub enabled: bool,
121    /// Whether the tool is shown. Hidden tools keep their id and state.
122    pub visible: bool,
123    /// Whether the tool carries a checked state (radio member or toggle).
124    pub checkable: bool,
125    /// Current checked state for checkable tools.
126    pub checked: bool,
127    /// Radio-group owner id: the id of the first tool of the group. Members
128    /// share the same owner value, and checking one unchecks the rest.
129    pub radio_group: Option<ToolId>,
130    /// Whether activating the tool requests its dropdown menu (the app
131    /// composes the menu with the existing menu API after `ToolDropdown`).
132    pub dropdown: bool,
133}
134
135impl ToolSpec {
136    /// Creates an enabled, visible, plain tool with the default display mode.
137    pub fn new(id: ToolId, label: impl Into<String>) -> Self {
138        Self {
139            id,
140            label: label.into(),
141            accessible_label: None,
142            tooltip: None,
143            icon: None,
144            display: ToolDisplay::default(),
145            enabled: true,
146            visible: true,
147            checkable: false,
148            checked: false,
149            radio_group: None,
150            dropdown: false,
151        }
152    }
153
154    /// Sets the tooltip/short help text.
155    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
156        self.tooltip = Some(tooltip.into());
157        self
158    }
159
160    /// Sets the assistive-technology name, overriding [`ToolSpec::label`] for
161    /// icon-only or abbreviated tools.
162    pub fn with_accessible_label(mut self, label: impl Into<String>) -> Self {
163        self.accessible_label = Some(label.into());
164        self
165    }
166
167    /// Resolves the name assistive technology should announce for this tool.
168    ///
169    /// The fallback order is fixed so every lane announces the same string:
170    ///
171    /// 1. [`ToolSpec::accessible_label`] when it is set and not blank;
172    /// 2. otherwise [`ToolSpec::label`] when it is not blank — the visible
173    ///    text doubles as the accessible name;
174    /// 3. otherwise `tool <id>` (for example `tool 7`), so an icon-only tool
175    ///    with no label still announces something stable and identifiable
176    ///    instead of reaching a screen reader as an unlabelled control.
177    ///
178    /// The result is never empty.
179    pub fn accessible_name(&self) -> String {
180        if let Some(label) = self.accessible_label.as_deref().map(str::trim) {
181            if !label.is_empty() {
182                return label.to_owned();
183            }
184        }
185        let text = self.label.trim();
186        if !text.is_empty() {
187            return text.to_owned();
188        }
189        format!("tool {}", self.id.get())
190    }
191
192    /// Sets the stock-art role.
193    pub fn with_icon(mut self, icon: IconRole) -> Self {
194        self.icon = Some(icon);
195        self
196    }
197
198    /// Sets the icon/text presentation preference.
199    pub fn with_display(mut self, display: ToolDisplay) -> Self {
200        self.display = display;
201        self
202    }
203
204    /// Sets the enabled state.
205    pub fn with_enabled(mut self, enabled: bool) -> Self {
206        self.enabled = enabled;
207        self
208    }
209
210    /// Sets the visible state.
211    pub fn with_visible(mut self, visible: bool) -> Self {
212        self.visible = visible;
213        self
214    }
215
216    /// Makes the tool checkable.
217    pub fn with_checkable(mut self) -> Self {
218        self.checkable = true;
219        self
220    }
221
222    /// Sets the initial checked state (only meaningful for checkable tools).
223    pub fn with_checked(mut self, checked: bool) -> Self {
224        self.checked = checked;
225        self
226    }
227
228    /// Joins a radio group; `owner` is the id of the group's first member.
229    pub fn with_radio_group(mut self, owner: ToolId) -> Self {
230        self.radio_group = Some(owner);
231        self.checkable = true;
232        self
233    }
234
235    /// Marks the tool as a dropdown (menu) tool.
236    pub fn with_dropdown(mut self) -> Self {
237        self.dropdown = true;
238        self
239    }
240}
241
242/// One row of a toolbar.
243#[derive(Debug, Clone, PartialEq, Eq)]
244pub enum ToolbarItem {
245    /// A tool.
246    Tool(ToolSpec),
247    /// A separator gap between tools.
248    Separator,
249}
250
251impl ToolbarItem {
252    /// Convenience constructor for a plain tool.
253    pub fn tool(id: ToolId, label: impl Into<String>) -> Self {
254        Self::Tool(ToolSpec::new(id, label))
255    }
256
257    /// Convenience constructor for a separator.
258    pub const fn separator() -> Self {
259        Self::Separator
260    }
261
262    /// The tool when this row is one.
263    pub fn tool_spec(&self) -> Option<&ToolSpec> {
264        match self {
265            Self::Tool(tool) => Some(tool),
266            Self::Separator => None,
267        }
268    }
269
270    /// Mutable access to the tool when this row is one.
271    pub fn tool_spec_mut(&mut self) -> Option<&mut ToolSpec> {
272        match self {
273            Self::Tool(tool) => Some(tool),
274            Self::Separator => None,
275        }
276    }
277
278    /// Whether this row is a separator.
279    pub const fn is_separator(&self) -> bool {
280        matches!(self, Self::Separator)
281    }
282}
283
284/// Partial in-place update applied by [`crate::Ui::update_tool`].
285///
286/// `None` leaves a field untouched; clearing a tooltip, icon, or accessible
287/// label means sending a fresh [`ToolbarItem`] list instead (the model is a
288/// full-list replacement).
289#[derive(Debug, Clone, Default, PartialEq, Eq)]
290pub struct ToolUpdate {
291    /// New label.
292    pub label: Option<String>,
293    /// New assistive-technology name.
294    pub accessible_label: Option<String>,
295    /// New tooltip.
296    pub tooltip: Option<String>,
297    /// New stock-art role.
298    pub icon: Option<IconRole>,
299    /// New display mode.
300    pub display: Option<ToolDisplay>,
301    /// New enabled state.
302    pub enabled: Option<bool>,
303    /// New visible state.
304    pub visible: Option<bool>,
305    /// New dropdown flag.
306    pub dropdown: Option<bool>,
307}
308
309impl ToolUpdate {
310    /// An empty update (nothing changes).
311    pub fn new() -> Self {
312        Self::default()
313    }
314
315    /// Replaces the label.
316    pub fn with_label(mut self, label: impl Into<String>) -> Self {
317        self.label = Some(label.into());
318        self
319    }
320
321    /// Replaces the assistive-technology name.
322    pub fn with_accessible_label(mut self, label: impl Into<String>) -> Self {
323        self.accessible_label = Some(label.into());
324        self
325    }
326
327    /// Replaces the tooltip.
328    pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
329        self.tooltip = Some(tooltip.into());
330        self
331    }
332
333    /// Replaces the stock-art role.
334    pub fn with_icon(mut self, icon: IconRole) -> Self {
335        self.icon = Some(icon);
336        self
337    }
338
339    /// Replaces the display mode.
340    pub fn with_display(mut self, display: ToolDisplay) -> Self {
341        self.display = Some(display);
342        self
343    }
344
345    /// Replaces the enabled state.
346    pub fn with_enabled(mut self, enabled: bool) -> Self {
347        self.enabled = Some(enabled);
348        self
349    }
350
351    /// Replaces the visible state.
352    pub fn with_visible(mut self, visible: bool) -> Self {
353        self.visible = Some(visible);
354        self
355    }
356
357    /// Replaces the dropdown flag.
358    pub fn with_dropdown(mut self, dropdown: bool) -> Self {
359        self.dropdown = Some(dropdown);
360        self
361    }
362}
363
364/// A model rule violation, surfaced by the `Ui` setters as
365/// [`GuiError::Backend`](crate::GuiError::Backend) with this message.
366#[derive(Debug, Clone, Copy, PartialEq, Eq)]
367pub enum ToolbarError {
368    /// The same [`ToolId`] appears twice.
369    DuplicateToolId(ToolId),
370    /// A `radio_group` value does not match any tool in the list.
371    UnknownRadioGroup(ToolId),
372    /// The radio-group owner is not checkable, so the group cannot be
373    /// exclusive.
374    RadioGroupNotCheckable(ToolId),
375    /// The requested tool id is not in the list.
376    UnknownTool(ToolId),
377    /// A checked state was set on a tool that is not checkable.
378    NotCheckable(ToolId),
379}
380
381impl fmt::Display for ToolbarError {
382    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
383        match self {
384            Self::DuplicateToolId(id) => write!(f, "duplicate toolbar tool id {id}"),
385            Self::UnknownRadioGroup(id) => write!(
386                f,
387                "radio group {id} is not an existing checkable tool (removing a group owner \
388                 requires reassigning or clearing the group in the replacement list)"
389            ),
390            Self::RadioGroupNotCheckable(id) => {
391                write!(f, "radio group owner {id} is not checkable")
392            }
393            Self::UnknownTool(id) => write!(f, "unknown toolbar {id}"),
394            Self::NotCheckable(id) => write!(f, "{id} is not checkable"),
395        }
396    }
397}
398
399impl std::error::Error for ToolbarError {}
400
401/// The events a user click on a tool produces, decided by the shared rules so
402/// every lane reports the same interaction.
403#[derive(Debug, Clone, PartialEq, Eq)]
404pub enum ToolInteraction {
405    /// A plain tool was activated: emit `ToolActivated`.
406    Activated(ToolId),
407    /// A dropdown tool was clicked: emit `ToolDropdown` (the menu itself is
408    /// app-composed).
409    Dropdown(ToolId),
410    /// A checkable tool was toggled: emit one `ToolToggled` per entry, in
411    /// toolbar order (radio exclusivity therefore produces at most one extra
412    /// event for the member that was unchecked).
413    Toggled(Vec<(ToolId, bool)>),
414    /// A disabled or hidden tool consumed the click; nothing is emitted.
415    Ignored(ToolId),
416}
417
418/// Finds a tool by id.
419pub fn find_tool(items: &[ToolbarItem], id: ToolId) -> Option<&ToolSpec> {
420    items.iter().find_map(|item| match item {
421        ToolbarItem::Tool(tool) if tool.id == id => Some(tool),
422        _ => None,
423    })
424}
425
426/// Mutable lookup by id.
427pub fn find_tool_mut(items: &mut [ToolbarItem], id: ToolId) -> Option<&mut ToolSpec> {
428    items.iter_mut().find_map(|item| match item {
429        ToolbarItem::Tool(tool) if tool.id == id => Some(tool),
430        _ => None,
431    })
432}
433
434/// Validates a toolbar item list.
435///
436/// Rules: tool ids are unique, and every `radio_group` refers to an existing
437/// checkable tool (the group owner). Separators carry no state and are not
438/// validated.
439pub fn validate_toolbar_items(items: &[ToolbarItem]) -> Result<(), ToolbarError> {
440    let mut seen: Vec<ToolId> = Vec::with_capacity(items.len());
441    for item in items {
442        let Some(tool) = item.tool_spec() else {
443            continue;
444        };
445        if seen.contains(&tool.id) {
446            return Err(ToolbarError::DuplicateToolId(tool.id));
447        }
448        seen.push(tool.id);
449    }
450    for item in items {
451        let Some(tool) = item.tool_spec() else {
452            continue;
453        };
454        if let Some(group) = tool.radio_group {
455            match find_tool(items, group) {
456                None => return Err(ToolbarError::UnknownRadioGroup(group)),
457                Some(owner) if !owner.checkable => {
458                    return Err(ToolbarError::RadioGroupNotCheckable(group));
459                }
460                Some(_) => {}
461            }
462        }
463    }
464    Ok(())
465}
466
467/// Applies a programmatic checked-state change.
468///
469/// This is the non-user path: it never emits activation events (the caller
470/// decides whether anything should be reported), and checking a radio member
471/// unchecks its group peers so the group stays exclusive. The return value
472/// lists every tool whose state actually changed, in toolbar order (empty for
473/// a no-op), which is what an application needs to update its own model.
474pub fn set_tool_state(
475    items: &mut [ToolbarItem],
476    id: ToolId,
477    checked: bool,
478) -> Result<Vec<(ToolId, bool)>, ToolbarError> {
479    let target = find_tool(items, id).ok_or(ToolbarError::UnknownTool(id))?;
480    if !target.checkable {
481        return Err(ToolbarError::NotCheckable(id));
482    }
483    let group = target.radio_group;
484
485    let before: Vec<(ToolId, bool)> = items
486        .iter()
487        .filter_map(|item| item.tool_spec().map(|tool| (tool.id, tool.checked)))
488        .collect();
489
490    for item in items.iter_mut() {
491        let Some(tool) = item.tool_spec_mut() else {
492            continue;
493        };
494        if tool.id == id {
495            tool.checked = checked;
496        } else if checked && group.is_some() && tool.radio_group == group {
497            tool.checked = false;
498        }
499    }
500
501    Ok(state_changes(items, &before))
502}
503
504/// Applies a user click to the toolbar model.
505///
506/// Precedence per tool: a disabled or hidden tool consumes the click
507/// ([`ToolInteraction::Ignored`]); a dropdown tool reports
508/// [`ToolInteraction::Dropdown`]; a checkable tool toggles (with radio
509/// exclusivity) and reports [`ToolInteraction::Toggled`]; anything else
510/// reports [`ToolInteraction::Activated`].
511pub fn click_tool(items: &mut [ToolbarItem], id: ToolId) -> Result<ToolInteraction, ToolbarError> {
512    let tool = find_tool(items, id).ok_or(ToolbarError::UnknownTool(id))?;
513    if !tool.enabled || !tool.visible {
514        return Ok(ToolInteraction::Ignored(id));
515    }
516    if tool.dropdown {
517        return Ok(ToolInteraction::Dropdown(id));
518    }
519    if tool.checkable {
520        let next = !tool.checked;
521        let changes = set_tool_state(items, id, next)?;
522        return Ok(ToolInteraction::Toggled(changes));
523    }
524    Ok(ToolInteraction::Activated(id))
525}
526
527/// Applies a partial [`ToolUpdate`] to one tool.
528///
529/// `checked` is deliberately not part of the update: use
530/// [`set_tool_state`] so radio exclusivity and the silent-programmatic rule
531/// apply.
532pub fn apply_tool_update(
533    items: &mut [ToolbarItem],
534    id: ToolId,
535    update: &ToolUpdate,
536) -> Result<(), ToolbarError> {
537    let tool = find_tool_mut(items, id).ok_or(ToolbarError::UnknownTool(id))?;
538    if let Some(label) = &update.label {
539        tool.label = label.clone();
540    }
541    if let Some(accessible_label) = &update.accessible_label {
542        tool.accessible_label = Some(accessible_label.clone());
543    }
544    if let Some(tooltip) = &update.tooltip {
545        tool.tooltip = Some(tooltip.clone());
546    }
547    if let Some(icon) = update.icon {
548        tool.icon = Some(icon);
549    }
550    if let Some(display) = update.display {
551        tool.display = display;
552    }
553    if let Some(enabled) = update.enabled {
554        tool.enabled = enabled;
555    }
556    if let Some(visible) = update.visible {
557        tool.visible = visible;
558    }
559    if let Some(dropdown) = update.dropdown {
560        tool.dropdown = dropdown;
561    }
562    Ok(())
563}
564
565/// Diffs the item list against its pre-edit state, in toolbar order.
566fn state_changes(items: &[ToolbarItem], before: &[(ToolId, bool)]) -> Vec<(ToolId, bool)> {
567    let mut changes = Vec::new();
568    for item in items {
569        let Some(tool) = item.tool_spec() else {
570            continue;
571        };
572        let previous = before
573            .iter()
574            .find_map(|(id, checked)| (*id == tool.id).then_some(*checked));
575        if previous != Some(tool.checked) {
576            changes.push((tool.id, tool.checked));
577        }
578    }
579    changes
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585
586    fn sample() -> Vec<ToolbarItem> {
587        vec![
588            ToolbarItem::Tool(ToolSpec::new(ToolId(1), "New").with_icon(IconRole::New)),
589            ToolbarItem::tool(ToolId(2), "Open"),
590            ToolbarItem::Separator,
591            ToolbarItem::Tool(ToolSpec::new(ToolId(10), "Left").with_radio_group(ToolId(10))),
592            ToolbarItem::Tool(ToolSpec::new(ToolId(11), "Center").with_radio_group(ToolId(10))),
593            ToolbarItem::Tool(ToolSpec::new(ToolId(12), "Right").with_radio_group(ToolId(10))),
594            ToolbarItem::Tool(ToolSpec::new(ToolId(20), "Bold").with_checkable()),
595            ToolbarItem::Tool(ToolSpec::new(ToolId(30), "Layout").with_dropdown()),
596        ]
597    }
598
599    #[test]
600    fn defaults_are_enabled_visible_and_icon_and_text() {
601        let tool = ToolSpec::new(ToolId(7), "Save");
602        assert!(tool.enabled);
603        assert!(tool.visible);
604        assert!(!tool.checkable);
605        assert!(!tool.checked);
606        assert!(!tool.dropdown);
607        assert_eq!(tool.radio_group, None);
608        assert_eq!(tool.display, ToolDisplay::IconAndText);
609        assert_eq!(tool.accessible_label, None);
610        assert_eq!(tool.accessible_name(), "Save");
611        assert_eq!(
612            ToolbarOrientation::default(),
613            ToolbarOrientation::Horizontal
614        );
615    }
616
617    #[test]
618    fn validation_rejects_duplicate_ids_and_dangling_radio_groups() {
619        let duplicate = vec![
620            ToolbarItem::tool(ToolId(1), "A"),
621            ToolbarItem::tool(ToolId(1), "A again"),
622        ];
623        assert_eq!(
624            validate_toolbar_items(&duplicate),
625            Err(ToolbarError::DuplicateToolId(ToolId(1)))
626        );
627
628        let dangling = vec![ToolbarItem::Tool(
629            ToolSpec::new(ToolId(2), "B").with_radio_group(ToolId(1)),
630        )];
631        assert_eq!(
632            validate_toolbar_items(&dangling),
633            Err(ToolbarError::UnknownRadioGroup(ToolId(1)))
634        );
635
636        let not_checkable = vec![
637            ToolbarItem::tool(ToolId(1), "Owner"),
638            ToolbarItem::Tool(ToolSpec::new(ToolId(2), "Member").with_radio_group(ToolId(1))),
639        ];
640        // `with_radio_group` marks the member checkable, but the owner is a
641        // plain tool and cannot anchor an exclusive group.
642        assert_eq!(
643            validate_toolbar_items(&not_checkable),
644            Err(ToolbarError::RadioGroupNotCheckable(ToolId(1)))
645        );
646
647        assert_eq!(validate_toolbar_items(&sample()), Ok(()));
648    }
649
650    #[test]
651    fn programmatic_state_is_exclusive_and_silent() {
652        let mut items = sample();
653        let changes = set_tool_state(&mut items, ToolId(11), true).unwrap();
654        assert_eq!(changes, vec![(ToolId(11), true)]);
655
656        // Switching the group within the same call reports one uncheck.
657        let changes = set_tool_state(&mut items, ToolId(12), true).unwrap();
658        assert_eq!(changes, vec![(ToolId(11), false), (ToolId(12), true)]);
659        assert!(!find_tool(&items, ToolId(10)).unwrap().checked);
660
661        // A no-op reports nothing.
662        assert_eq!(set_tool_state(&mut items, ToolId(12), true), Ok(vec![]));
663
664        // Independent toggles are not part of any group.
665        let changes = set_tool_state(&mut items, ToolId(20), true).unwrap();
666        assert_eq!(changes, vec![(ToolId(20), true)]);
667        assert_eq!(
668            set_tool_state(&mut items, ToolId(1), true),
669            Err(ToolbarError::NotCheckable(ToolId(1)))
670        );
671        assert_eq!(
672            set_tool_state(&mut items, ToolId(99), true),
673            Err(ToolbarError::UnknownTool(ToolId(99)))
674        );
675    }
676
677    #[test]
678    fn user_clicks_follow_the_documented_precedence() {
679        let mut items = sample();
680        assert_eq!(
681            click_tool(&mut items, ToolId(1)),
682            Ok(ToolInteraction::Activated(ToolId(1)))
683        );
684        assert_eq!(
685            click_tool(&mut items, ToolId(30)),
686            Ok(ToolInteraction::Dropdown(ToolId(30)))
687        );
688
689        // Radio: first click checks, second click checks the other member and
690        // reports the uncheck as its own entry.
691        assert_eq!(
692            click_tool(&mut items, ToolId(10)),
693            Ok(ToolInteraction::Toggled(vec![(ToolId(10), true)]))
694        );
695        assert_eq!(
696            click_tool(&mut items, ToolId(11)),
697            Ok(ToolInteraction::Toggled(vec![
698                (ToolId(10), false),
699                (ToolId(11), true)
700            ]))
701        );
702        // Clicking the checked member clears the group.
703        assert_eq!(
704            click_tool(&mut items, ToolId(11)),
705            Ok(ToolInteraction::Toggled(vec![(ToolId(11), false)]))
706        );
707
708        // Disabled and hidden tools consume the click silently.
709        find_tool_mut(&mut items, ToolId(1)).unwrap().enabled = false;
710        find_tool_mut(&mut items, ToolId(2)).unwrap().visible = false;
711        assert_eq!(
712            click_tool(&mut items, ToolId(1)),
713            Ok(ToolInteraction::Ignored(ToolId(1)))
714        );
715        assert_eq!(
716            click_tool(&mut items, ToolId(2)),
717            Ok(ToolInteraction::Ignored(ToolId(2)))
718        );
719
720        // Dropdown wins over checkable.
721        let mut both = vec![ToolbarItem::Tool(
722            ToolSpec::new(ToolId(3), "Both")
723                .with_checkable()
724                .with_dropdown(),
725        )];
726        assert_eq!(
727            click_tool(&mut both, ToolId(3)),
728            Ok(ToolInteraction::Dropdown(ToolId(3)))
729        );
730    }
731
732    #[test]
733    fn updates_patch_only_the_named_fields() {
734        let mut items = sample();
735        let update = ToolUpdate::new()
736            .with_label("New file")
737            .with_enabled(false)
738            .with_display(ToolDisplay::TextOnly);
739        apply_tool_update(&mut items, ToolId(1), &update).unwrap();
740
741        let tool = find_tool(&items, ToolId(1)).unwrap();
742        assert_eq!(tool.label, "New file");
743        assert!(!tool.enabled);
744        assert_eq!(tool.display, ToolDisplay::TextOnly);
745        assert_eq!(tool.icon, Some(IconRole::New));
746        assert_eq!(tool.tooltip, None);
747        assert_eq!(
748            apply_tool_update(&mut items, ToolId(99), &update),
749            Err(ToolbarError::UnknownTool(ToolId(99)))
750        );
751    }
752
753    #[test]
754    fn separators_are_not_tools() {
755        let items = sample();
756        let separators = items.iter().filter(|item| item.is_separator()).count();
757        assert_eq!(separators, 1);
758        assert_eq!(ToolbarItem::separator().tool_spec(), None);
759    }
760
761    #[test]
762    fn accessible_names_fall_back_from_explicit_label_to_text_to_a_stable_default() {
763        // 1. An explicit accessible label wins: the icon-only case.
764        let icon_only = ToolSpec::new(ToolId(7), "").with_accessible_label("Bold");
765        assert_eq!(icon_only.accessible_name(), "Bold");
766
767        // 2. Without one, the visible text doubles as the accessible name.
768        let plain = ToolSpec::new(ToolId(8), "Open");
769        assert_eq!(plain.label, "Open");
770        assert_eq!(plain.accessible_label, None);
771        assert_eq!(plain.accessible_name(), "Open");
772
773        // 3. An icon-only tool with neither still announces an identifiable,
774        //    documented default instead of reaching AT unlabelled.
775        let unlabelled = ToolSpec::new(ToolId(9), "");
776        assert_eq!(unlabelled.accessible_name(), "tool 9");
777
778        // 4. Blank strings count as absent and are never announced verbatim.
779        let blank = ToolSpec::new(ToolId(10), "  ").with_accessible_label("   ");
780        assert_eq!(blank.accessible_name(), "tool 10");
781
782        // 5. Surrounding whitespace is trimmed from whatever is announced.
783        let padded = ToolSpec::new(ToolId(11), "  Save  ");
784        assert_eq!(padded.accessible_name(), "Save");
785    }
786
787    #[test]
788    fn accessible_label_round_trips_through_the_update_path() {
789        let mut items = sample();
790        assert_eq!(
791            find_tool(&items, ToolId(1)).unwrap().accessible_name(),
792            "New"
793        );
794
795        let update = ToolUpdate::new().with_accessible_label("New document");
796        apply_tool_update(&mut items, ToolId(1), &update).unwrap();
797
798        let tool = find_tool(&items, ToolId(1)).unwrap();
799        assert_eq!(tool.accessible_label.as_deref(), Some("New document"));
800        assert_eq!(tool.accessible_name(), "New document");
801        assert_eq!(tool.label, "New", "the override is announce-only");
802
803        // Re-labelling leaves the explicit accessible name authoritative.
804        apply_tool_update(
805            &mut items,
806            ToolId(1),
807            &ToolUpdate::new().with_label("New file"),
808        )
809        .unwrap();
810        let tool = find_tool(&items, ToolId(1)).unwrap();
811        assert_eq!(tool.label, "New file");
812        assert_eq!(tool.accessible_name(), "New document");
813
814        // An unrelated update never clobbers the accessible name.
815        apply_tool_update(
816            &mut items,
817            ToolId(1),
818            &ToolUpdate::new().with_enabled(false),
819        )
820        .unwrap();
821        let tool = find_tool(&items, ToolId(1)).unwrap();
822        assert_eq!(tool.accessible_label.as_deref(), Some("New document"));
823        assert_eq!(tool.accessible_name(), "New document");
824        assert!(!tool.enabled);
825    }
826}