Skip to main content

nsh_core/element/
header.rs

1//! iOS navigation-bar buttons (`ios={{ headerLeftItems }}`, `ios={{
2//! headerRightItems }}`).
3//!
4//! Rust apps build [`HeaderItem`]s with per-item [`HeaderItem::on_press`]
5//! and menus of [`super::desktop::MenuItem`]s (their
6//! [`super::desktop::MenuItem::on_select`]). [`register`] turns them into
7//! the platform's [`crate::HeaderItem`]s with numeric ids, keeps the
8//! handlers in [`super::menus::ViewMenus`], and a cleanup drops them when
9//! the binding is replaced or the page goes. The platform reports a
10//! chosen id as the root's [`crate::EventKind::Menu`].
11
12use std::{fmt, rc::Rc, sync::Arc};
13
14use super::{cleanup, desktop, menus::MenuHandler, reactive::Owner, view_menus};
15use crate::{HeaderItemContent, HeaderSystemItem};
16
17/// An iOS bar button for [`super::host::Screen::header_left_items`] and
18/// [`super::host::Screen::header_right_items`]:
19/// what it shows, an optional native menu of [`desktop::MenuItem`]s, and
20/// handlers that run when the platform reports their ids as the root's
21/// `Menu` event.
22///
23/// ```ignore
24/// HeaderItem::system(HeaderSystemItem::Edit).on_press(edit)
25/// HeaderItem::symbol_title("sparkles", "Upgrade").on_press(upgrade)
26/// HeaderItem::symbol("ellipsis.circle")
27///     .label("More")
28///     .menu([
29///         desktop::MenuItem::new("Share").on_select(share),
30///         desktop::MenuItem::submenu("Danger", [
31///             desktop::MenuItem::new("Delete").destructive(true).on_select(remove),
32///         ])
33///         .inline(true),
34///     ])
35/// ```
36#[derive(Clone)]
37pub struct HeaderItem {
38    key: Option<Arc<str>>,
39    content: HeaderItemContent,
40    label: Option<Arc<str>>,
41    disabled: bool,
42    on_press: Option<MenuHandler>,
43    menu: Option<Vec<desktop::MenuItem>>,
44    shares_background: bool,
45}
46
47impl HeaderItem {
48    fn of(content: HeaderItemContent) -> Self {
49        Self {
50            key: None,
51            content,
52            label: None,
53            disabled: false,
54            on_press: None,
55            menu: None,
56            shares_background: true,
57        }
58    }
59
60    /// A system-item button.
61    pub fn system(item: HeaderSystemItem) -> Self {
62        Self::of(HeaderItemContent::SystemItem(item))
63    }
64
65    /// An SF Symbol button.
66    pub fn symbol(name: impl Into<Arc<str>>) -> Self {
67        Self::of(HeaderItemContent::Symbol(name.into()))
68    }
69
70    /// A titled button (`label` is what it shows).
71    pub fn new(label: impl Into<Arc<str>>) -> Self {
72        Self::of(HeaderItemContent::Label(label.into()))
73    }
74
75    /// A button showing an SF Symbol and `title` after it; VoiceOver reads
76    /// the title unless [`Self::label`] is set.
77    pub fn symbol_title(name: impl Into<Arc<str>>, title: impl Into<Arc<str>>) -> Self {
78        Self::of(HeaderItemContent::SymbolTitle {
79            symbol: name.into(),
80            title: title.into(),
81        })
82    }
83
84    /// Optional key for keeping a `UIBarButtonItem` across updates; also
85    /// the button's accessibility identifier, which tests name it by
86    /// (`id:<key>`).
87    pub fn key(mut self, key: impl Into<Arc<str>>) -> Self {
88        self.key = Some(key.into());
89        self
90    }
91
92    /// VoiceOver's label when the content is a system item or symbol.
93    pub fn label(mut self, label: impl Into<Arc<str>>) -> Self {
94        self.label = Some(label.into());
95        self
96    }
97
98    /// Whether the button shares its background with the bar buttons next
99    /// to it (default true): on iOS 26 and later, false gives it a glass
100    /// capsule of its own instead of the one its neighbors share
101    /// (`UIBarButtonItem.sharesBackground`). Earlier iOS versions ignore
102    /// it.
103    pub fn shares_background(mut self, shares: bool) -> Self {
104        self.shares_background = shares;
105        self
106    }
107
108    /// Disables the button.
109    pub fn disabled(mut self, disabled: bool) -> Self {
110        self.disabled = disabled;
111        self
112    }
113
114    /// Runs `f` when the button is pressed and it has no menu.
115    pub fn on_press(mut self, f: impl Fn() + 'static) -> Self {
116        self.on_press = Some(Rc::new(f));
117        self
118    }
119
120    /// Opens this native menu on press (the button's [`Self::on_press`] is
121    /// unused while a menu is set).
122    pub fn menu(mut self, items: impl IntoIterator<Item = desktop::MenuItem>) -> Self {
123        self.menu = Some(items.into_iter().collect());
124        self
125    }
126}
127
128impl fmt::Debug for HeaderItem {
129    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130        f.debug_struct("HeaderItem")
131            .field("key", &self.key)
132            .field("content", &self.content)
133            .field("label", &self.label)
134            .field("disabled", &self.disabled)
135            .field("shares_background", &self.shares_background)
136            .field("menu", &self.menu.as_ref().map(|m| m.len()))
137            .finish_non_exhaustive()
138    }
139}
140
141/// Decodes `items` into the platform's form, keeps their handlers under a
142/// generation that a cleanup drops when this binding is replaced or the
143/// owner goes, and returns what [`crate::ScreenConfig::left_items`] /
144/// [`crate::ScreenConfig::right_items`] holds.
145pub(crate) fn register(items: Vec<HeaderItem>) -> Vec<crate::HeaderItem> {
146    let menus = view_menus();
147    let owner = Owner::current();
148    let mut handlers = Vec::new();
149    let mac = super::os() == crate::platform::Os::MacOs;
150    let decoded = items
151        .into_iter()
152        .map(|item| decode_item(item, mac, &owner, &mut handlers))
153        .collect();
154    let generation = menus.borrow_mut().push_header(handlers);
155    let weak = Rc::downgrade(&menus);
156    cleanup(move || {
157        if let Some(menus) = weak.upgrade() {
158            menus.borrow_mut().take_header(generation);
159        }
160    });
161    decoded
162}
163
164fn decode_item(
165    item: HeaderItem,
166    mac: bool,
167    owner: &Owner,
168    handlers: &mut Vec<(u32, MenuHandler)>,
169) -> crate::HeaderItem {
170    let menus = view_menus();
171    let press_id = match item.on_press {
172        Some(f) if item.menu.is_none() => {
173            let id = menus.borrow_mut().next_id();
174            let owner = *owner;
175            handlers.push((id, Rc::new(move || owner.run(&*f))));
176            id
177        }
178        _ => 0,
179    };
180    let menu = item.menu.map(|items| {
181        // Reuse the desktop menu decoder so item ids and handlers match.
182        desktop::decode_for_header(items, mac, owner, handlers)
183    });
184    crate::HeaderItem {
185        key: item.key,
186        content: item.content,
187        label: item.label,
188        disabled: item.disabled,
189        press_id,
190        menu,
191        shares_background: item.shares_background,
192    }
193}
194
195/// Whether two lists keep the same `UIBarButtonItem`s: count,
196/// keys (or unkeyed contents), content kind that can update in place, and
197/// whether each has a menu. A label's title or a symbol's image can change
198/// without rebuilding; a system-item change or a content-kind change needs
199/// a new button. Menus' contents, accessibility labels and `disabled` can
200/// change either way.
201#[doc(hidden)]
202pub fn same_buttons(a: &[crate::HeaderItem], b: &[crate::HeaderItem]) -> bool {
203    a.len() == b.len()
204        && a.iter()
205            .zip(b)
206            .all(|(x, y)| keepable(x, y) && x.menu.is_some() == y.menu.is_some())
207}
208
209/// What a kept button ([`same_buttons`]) shows once updated to an
210/// item: the platforms apply it to the button they kept, so a changed
211/// label, symbol, accessibility label or `disabled` reaches the screen.
212#[doc(hidden)]
213#[derive(Debug, Clone, PartialEq, Eq)]
214pub struct KeptButton<'a> {
215    pub content: KeptContent<'a>,
216    /// VoiceOver's label; `None` clears the one set before.
217    pub label: Option<&'a str>,
218    pub enabled: bool,
219    /// Whether it shares its background with its neighbors (iOS 26+).
220    pub shares_background: bool,
221}
222
223/// A kept button's content after an update.
224#[doc(hidden)]
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
226pub enum KeptContent<'a> {
227    /// This title, and no image.
228    Title(&'a str),
229    /// This SF Symbol, and no title; `fallback` is the title where the
230    /// platform has no such symbol.
231    Symbol { name: &'a str, fallback: &'a str },
232    /// This SF Symbol with this title after it (the title alone where the
233    /// platform has no such symbol).
234    SymbolTitle { name: &'a str, title: &'a str },
235    /// A system item: kept only while it is the same item, so its look
236    /// stays as it is.
237    Unchanged,
238}
239
240/// What the button kept for `item` shows ([`KeptButton`]).
241#[doc(hidden)]
242pub fn kept_button(item: &crate::HeaderItem) -> KeptButton<'_> {
243    let content = match &item.content {
244        HeaderItemContent::Label(title) => KeptContent::Title(title),
245        HeaderItemContent::Symbol(name) => KeptContent::Symbol {
246            name,
247            fallback: item.label.as_deref().unwrap_or(name),
248        },
249        HeaderItemContent::SymbolTitle { symbol, title } => KeptContent::SymbolTitle {
250            name: symbol,
251            title,
252        },
253        _ => KeptContent::Unchanged,
254    };
255    KeptButton {
256        content,
257        label: item.label.as_deref(),
258        enabled: !item.disabled,
259        shares_background: item.shares_background,
260    }
261}
262
263/// Whether UIKit can keep `a`'s `UIBarButtonItem` and apply `b` in place.
264fn keepable(a: &crate::HeaderItem, b: &crate::HeaderItem) -> bool {
265    match (a.key.as_deref(), b.key.as_deref()) {
266        (Some(ka), Some(kb)) if ka == kb => content_keeps_button(&a.content, &b.content),
267        (None, None) => a.content == b.content,
268        _ => false,
269    }
270}
271
272/// Label, symbol and symbol-with-title content update in place; a system
273/// item only when it is the same item (UIKit cannot change a system item on
274/// an existing button).
275fn content_keeps_button(a: &HeaderItemContent, b: &HeaderItemContent) -> bool {
276    match (a, b) {
277        (HeaderItemContent::Label(_), HeaderItemContent::Label(_)) => true,
278        (HeaderItemContent::Symbol(_), HeaderItemContent::Symbol(_)) => true,
279        (HeaderItemContent::SymbolTitle { .. }, HeaderItemContent::SymbolTitle { .. }) => true,
280        (HeaderItemContent::SystemItem(x), HeaderItemContent::SystemItem(y)) => x == y,
281        _ => false,
282    }
283}
284
285#[cfg(test)]
286mod tests {
287    use std::sync::Arc;
288
289    use super::*;
290    use crate::{HeaderItem as PlatformHeaderItem, HeaderSystemItem};
291
292    fn keyed(key: &str, content: HeaderItemContent) -> PlatformHeaderItem {
293        PlatformHeaderItem {
294            key: Some(Arc::from(key)),
295            content,
296            label: None,
297            disabled: false,
298            press_id: 0,
299            menu: None,
300            shares_background: true,
301        }
302    }
303
304    #[test]
305    fn keyed_label_change_keeps_button() {
306        let a = keyed("edit", HeaderItemContent::Label(Arc::from("Edit")));
307        let b = keyed("edit", HeaderItemContent::Label(Arc::from("Done")));
308        assert!(
309            same_buttons(&[a], &[b]),
310            "same key + Label→Label: update title in place"
311        );
312    }
313
314    #[test]
315    fn keyed_symbol_change_keeps_button() {
316        let a = keyed("star", HeaderItemContent::Symbol(Arc::from("star")));
317        let b = keyed("star", HeaderItemContent::Symbol(Arc::from("star.fill")));
318        assert!(
319            same_buttons(&[a], &[b]),
320            "same key + Symbol→Symbol: update image in place"
321        );
322    }
323
324    #[test]
325    fn a_kept_button_shows_the_new_title_symbol_label_and_state() {
326        // Edit → Done: the same key, a new title.
327        let done = keyed("edit", HeaderItemContent::Label(Arc::from("Done")));
328        assert_eq!(kept_button(&done).content, KeptContent::Title("Done"));
329        // star → star.fill: a new image; the label is the fallback title.
330        let mut filled = keyed("fav", HeaderItemContent::Symbol(Arc::from("star.fill")));
331        filled.label = Some(Arc::from("Favorite"));
332        assert_eq!(
333            kept_button(&filled).content,
334            KeptContent::Symbol {
335                name: "star.fill",
336                fallback: "Favorite"
337            }
338        );
339        // An accessibility label taken away is cleared, not kept.
340        filled.label = None;
341        filled.disabled = true;
342        let kept = kept_button(&filled);
343        assert_eq!(kept.label, None);
344        assert!(!kept.enabled);
345        assert_eq!(
346            kept.content,
347            KeptContent::Symbol {
348                name: "star.fill",
349                fallback: "star.fill"
350            }
351        );
352        // A system item keeps its look.
353        let system = keyed("x", HeaderItemContent::SystemItem(HeaderSystemItem::Edit));
354        assert_eq!(kept_button(&system).content, KeptContent::Unchanged);
355    }
356
357    #[test]
358    fn keyed_symbol_title_change_keeps_button() {
359        let a = keyed(
360            "plan",
361            HeaderItemContent::SymbolTitle {
362                symbol: Arc::from("sparkles"),
363                title: Arc::from("Upgrade"),
364            },
365        );
366        let b = keyed(
367            "plan",
368            HeaderItemContent::SymbolTitle {
369                symbol: Arc::from("star"),
370                title: Arc::from("Plans"),
371            },
372        );
373        assert!(same_buttons(&[a], std::slice::from_ref(&b)));
374        assert_eq!(
375            kept_button(&b).content,
376            KeptContent::SymbolTitle {
377                name: "star",
378                title: "Plans"
379            }
380        );
381        // A symbol alone is a different button (an image, no title).
382        let c = keyed("plan", HeaderItemContent::Symbol(Arc::from("star")));
383        assert!(!same_buttons(&[b], &[c]));
384    }
385
386    #[test]
387    fn keyed_system_item_change_rebuilds() {
388        let a = keyed("x", HeaderItemContent::SystemItem(HeaderSystemItem::Edit));
389        let b = keyed("x", HeaderItemContent::SystemItem(HeaderSystemItem::Done));
390        assert!(
391            !same_buttons(&[a], &[b]),
392            "UIKit cannot change a system item in place"
393        );
394    }
395
396    #[test]
397    fn keyed_content_kind_change_rebuilds() {
398        let a = keyed("x", HeaderItemContent::Label(Arc::from("Edit")));
399        let b = keyed("x", HeaderItemContent::Symbol(Arc::from("pencil")));
400        assert!(
401            !same_buttons(&[a], &[b]),
402            "Label→Symbol needs a new UIBarButtonItem"
403        );
404    }
405}