nsh_core/mobile.rs
1//! Capabilities specific to iOS and Android (TS
2//! `nsh/mobile`): the system's tab bar ([`TabBar`]), a native component the
3//! two backends register themselves ([`TAB_BAR_COMPONENT`]). Elsewhere, and
4//! on a platform built outside NSH without a tab bar
5//! ([`crate::platform::Environment::tab_bar`]), it takes no room and shows
6//! nothing. Common controls belong to `nsh/base`, with one cross-platform
7//! API; the tab bar is here because it is the app's top-level navigation,
8//! not a form control. System-styled form controls are not part of the
9//! runtime: an app that wants them adds them as an nshm.
10//!
11//! It also opens the app's own page in the system's settings
12//! ([`open_app_settings`], TS `AppSettings.open`), where the user turns
13//! back on a permission they denied: iOS's Settings app at the app,
14//! Android's App info. The core sends [`crate::Command::OpenAppSettings`]
15//! to a platform whose [`crate::platform::Environment::app_settings`] is
16//! set, which reports whether the system opened the page as
17//! [`crate::EventKind::OpenAppSettings`]. Elsewhere (the desktops, the web,
18//! a terminal, and an iPhone or iPad app running on a Mac, which has no
19//! page of the app's own) it fails at once with
20//! [`AppSettingsError::Unavailable`]. It acts on the application as a whole
21//! (the embedding app's page, for an embedded view), so an app that
22//! declares capabilities needs `application`.
23
24use crate::{
25 JsonValue,
26 element::{NativeEvent, native},
27 platform::TAB_BAR_COMPONENT,
28 prelude::*,
29};
30
31/// One tab of a [`TabBar`].
32#[derive(Debug, Clone, Default, PartialEq, JsObject)]
33#[non_exhaustive]
34pub struct TabBarItem {
35 /// Its title.
36 pub title: SharedString,
37 /// Its icon, by the platform's name for it: an SF Symbol on iOS
38 /// (`"house"`), a drawable of the app on Android (`res/drawable/home.xml`
39 /// is `"home"`, `"android:ic_menu_search"` the system's); TS's
40 /// `platform.select` picks one per platform.
41 #[prop(skip_none)]
42 pub icon: Option<SharedString>,
43 /// Its badge: a text (`"3"`, `"New"`), or `""` for a badge with no
44 /// text (Material 3's small dot on Android, UIKit's empty badge on iOS).
45 /// `None` (the default) shows none. The badge is the system's
46 /// (`badgeValue` on iOS, Material 3's on Android), and screen readers
47 /// say its text with the title.
48 #[prop(skip_none)]
49 pub badge: Option<SharedString>,
50}
51
52impl TabBarItem {
53 /// A tab titled `title`, with no icon.
54 pub fn new(title: impl Into<SharedString>) -> Self {
55 Self {
56 title: title.into(),
57 ..Self::default()
58 }
59 }
60
61 /// Its icon, by the platform's name for it ([`TabBarItem::icon`]).
62 pub fn icon(mut self, name: impl Into<SharedString>) -> Self {
63 self.icon = Some(name.into());
64 self
65 }
66
67 /// Its badge ([`TabBarItem::badge`]): a text, or `""` for a badge with
68 /// no text.
69 pub fn badge(mut self, text: impl Into<SharedString>) -> Self {
70 self.badge = Some(text.into());
71 self
72 }
73}
74
75/// The props of [`TabBar`].
76#[derive(Debug, Clone, PartialEq, Props)]
77pub struct TabBarProps {
78 /// The tabs, in order.
79 #[prop(default)]
80 pub items: Prop<Vec<TabBarItem>>,
81 /// The selected tab, by index (default 0; one past the tabs selects
82 /// none). The app owns it: the user's choice is reported with
83 /// `onChange`.
84 #[prop(default)]
85 pub selected_index: Prop<u32>,
86 /// Out of sight, without a transition (default false): the app sets it when
87 /// it switches tabs, whose pages are kept and shown again as they were.
88 #[prop(default)]
89 pub hidden: Prop<bool>,
90}
91
92/// The events of a [`TabBar`].
93#[derive(Debug, Clone, PartialEq, Event)]
94pub enum TabBarEvent {
95 /// The user chose a tab: its index. The bar shows the choice at once,
96 /// as the system's does; the app shows the tab's content and sets
97 /// `selectedIndex`.
98 #[args(index)]
99 Change(u32),
100}
101
102/// The system's tab bar: `UITabBar` on iOS (Liquid Glass on iOS 26), a
103/// Material 3 navigation bar on Android, each in the system's look. The app
104/// gives the tabs (`items`), says which is selected (`selectedIndex`), hears
105/// the user's choice (`onChange`), places the bar with its `class` and
106/// `style` and shows the selected tab's content; the bar's height is the
107/// system's where the style leaves it open. The selected tab takes the
108/// theme's `primary` (the other tabs keep the system's). The desktops and
109/// the web have no system tab bar: there it takes no room and shows
110/// nothing, and the app shows its tabs with `nsh/base`'s `Tabs`.
111#[component]
112pub fn TabBar(props: TabBarProps, cx: Scope<TabBarEvent>) -> impl IntoElement {
113 if !crate::element::has_tab_bar() {
114 return view().hidden().into_element();
115 }
116 let items = props.items;
117 native(TAB_BAR_COMPONENT)
118 // The bar's own view fills the element and takes every press it
119 // wants; the element must not take the strip it leaves once it is
120 // out of sight (`hidden`, or the navigation stack's
121 // `hidesBottomBarWhenPushed`), where an app draws controls of its
122 // own.
123 .pointer_events(PointerEvents::BoxNone)
124 .prop("items", move || items.with(|items| tabs_json(items)))
125 .prop("selectedIndex", move || {
126 JsonValue::from(props.selected_index.get())
127 })
128 .prop("hidden", move || JsonValue::Bool(props.hidden.get()))
129 // One color, for the appearance shown: sent again when either changes.
130 .prop("tint", || {
131 tokens()
132 .color("primary")
133 .map_or(JsonValue::Null, |primary| color(primary).to_hex().into())
134 })
135 .on_native_event(move |event: &NativeEvent| {
136 if &*event.name == "change"
137 && let Some(index) = event.data.as_u64()
138 {
139 cx.emit(TabBarEvent::Change(index as u32));
140 }
141 })
142 .into_element()
143}
144
145/// The tabs as the platforms read them: `[{ title, icon?, badge? }]`.
146fn tabs_json(items: &[TabBarItem]) -> JsonValue {
147 items
148 .iter()
149 .map(|item| {
150 let mut tab = serde_json::Map::new();
151 tab.insert("title".into(), item.title.as_ref().into());
152 if let Some(icon) = &item.icon {
153 tab.insert("icon".into(), icon.as_ref().into());
154 }
155 if let Some(badge) = &item.badge {
156 tab.insert("badge".into(), badge.as_ref().into());
157 }
158 JsonValue::Object(tab)
159 })
160 .collect()
161}
162
163// --- The app's page in the system's settings ---------------------------------
164
165/// Why [`open_app_settings`] failed.
166#[derive(Debug, Clone, Copy, PartialEq, Eq)]
167#[non_exhaustive]
168pub enum AppSettingsError {
169 /// The platform has no settings page of the app's own (TS:
170 /// `ERR_FEATURE_UNAVAILABLE_ON_PLATFORM`): only iOS and Android have
171 /// one ([`app_settings_available`]).
172 Unavailable,
173 /// The app declares capabilities without `application` (TS:
174 /// `ERR_ACCESS_DENIED`, `permission` `"application"`).
175 Denied,
176}
177
178impl std::fmt::Display for AppSettingsError {
179 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
180 match self {
181 Self::Unavailable => f.write_str(
182 "AppSettings.open: this platform has no settings page of the app's own (iOS and \
183 Android have one)",
184 ),
185 Self::Denied => f.write_str(
186 "AppSettings.open: the application is not granted: add `\"application\": true` to \
187 capabilities in nsh.json",
188 ),
189 }
190 }
191}
192
193impl std::error::Error for AppSettingsError {}
194
195impl AppSettingsError {
196 /// The error JS gets: an `Error` with the code to branch on.
197 pub(crate) fn js(self) -> crate::element::JsError {
198 match self {
199 Self::Unavailable => crate::element::JsError::Error(self.to_string())
200 .with_code(crate::element::codes::UNAVAILABLE),
201 Self::Denied => {
202 crate::element::JsError::access_denied(self.to_string(), "application", "")
203 }
204 }
205 }
206}
207
208/// Opens the app's own page in the system's settings (TS:
209/// `AppSettings.open` of `nsh/mobile`): where the user turns back on a
210/// permission they denied, as an "Open Settings" button beside the app's
211/// explanation does. To await in a task: whether the system opened the
212/// page; it fails with [`AppSettingsError::Unavailable`] where the platform
213/// has no such page (all but iOS and Android; [`app_settings_available`])
214/// and with [`AppSettingsError::Denied`] for an app that declares
215/// capabilities without `application`. Drop it when the answer does not
216/// matter.
217pub fn open_app_settings() -> crate::element::Answer<Result<bool, AppSettingsError>> {
218 let (answer, slot) = crate::element::Answer::new();
219 crate::element::act(crate::element::Action::OpenAppSettings(slot));
220 answer
221}
222
223/// Whether [`open_app_settings`] opens the app's page in the system's
224/// settings here (TS: `AppSettings.available()` of `nsh/mobile`): on iOS
225/// and Android, when the app's capabilities grant `application`. To await
226/// in a task, before showing an "Open Settings" button.
227pub fn app_settings_available() -> crate::element::Answer<bool> {
228 let (answer, slot) = crate::element::Answer::new();
229 crate::element::act(crate::element::Action::AppSettingsAvailable(slot));
230 answer
231}
232
233#[cfg(test)]
234mod tests {
235 use serde_json::json;
236
237 use super::{AppSettingsError, TabBarItem, tabs_json};
238
239 #[test]
240 fn app_settings_errors_carry_their_codes() {
241 let unavailable = AppSettingsError::Unavailable.js();
242 assert_eq!(
243 unavailable.code(),
244 Some("ERR_FEATURE_UNAVAILABLE_ON_PLATFORM")
245 );
246 assert!(
247 unavailable.message().contains("AppSettings.open"),
248 "{unavailable:?}"
249 );
250 let denied = AppSettingsError::Denied.js();
251 assert_eq!(denied.code(), Some("ERR_ACCESS_DENIED"));
252 assert!(
253 denied.message().contains("\"application\": true"),
254 "{denied:?}"
255 );
256 }
257
258 #[test]
259 fn tabs_reach_the_platform_as_titles_and_icons() {
260 let tabs = [
261 TabBarItem::new("Records").icon("list.bullet"),
262 TabBarItem::new("Stats"),
263 ];
264 assert_eq!(
265 tabs_json(&tabs),
266 json!([{ "title": "Records", "icon": "list.bullet" }, { "title": "Stats" }])
267 );
268 }
269
270 #[test]
271 fn badges_reach_the_platform_as_texts_and_empty_ones() {
272 let tabs = [
273 TabBarItem::new("Inbox").badge("3"),
274 TabBarItem::new("Brain").badge(""),
275 TabBarItem::new("Stats"),
276 ];
277 assert_eq!(
278 tabs_json(&tabs),
279 json!([
280 { "title": "Inbox", "badge": "3" },
281 { "title": "Brain", "badge": "" },
282 { "title": "Stats" },
283 ])
284 );
285 }
286}