nsh_core/element/module.rs
1//! Modules: functions a UI set exports to JS without a component
2//! (`AlertDialog.show(...)`, `Keyboard.dismiss()`), written in Rust with
3//! `#[module]` and generated into the set's JS module like its components.
4//! The signature decides how a call runs: a function without a context
5//! runs in the JS call and returns its value (as a class's method does);
6//! one taking `cx: &mut ModuleCx` is an op, ordered with the props set
7//! before it (a `Promise` when it returns a value, `Result<(), E>`
8//! included; `undefined` when it returns nothing: nothing answers it); an
9//! `async fn` runs as a task of the core (a `Promise`, of `void` too). In
10//! every kind the arguments are converted in the JS call, and the op
11//! carries a closure holding them (`super::call`).
12
13use std::{future::Future, pin::Pin};
14
15use super::{
16 DialogAnswer, TsType, TsTypes,
17 call::{JsResult, OpCall},
18 class::{AsyncCall, Thrown},
19 js::{JsHost, JsRaw},
20 task::{self, Action},
21};
22use crate::{AlertDialogRequest, Command, LayoutAnimation, ROOT_ID, StatusBarSetting};
23
24/// A JS object of functions (`#[module]` implements it).
25pub trait Module {
26 /// Its JS name: the type's own (`#[module] impl Keyboard`: `Keyboard`), which
27 /// `#[module]` writes; JS calls its functions by it (`Keyboard.dismiss`).
28 const NAME: &'static str;
29 /// Documentation (the `impl` block's doc comment).
30 const DOC: &'static str;
31 /// Its functions.
32 const FUNCTIONS: &'static [Function];
33 /// Its functions are exported one by one
34 /// rather than as an object (`#[module(flat)]`).
35 const FLAT: bool = false;
36 /// Export the same flat module object as `default`.
37 const DEFAULT: bool = false;
38 /// Associated primitive constants exported with the functions.
39 const CONSTANTS: &'static [Constant] = &[];
40}
41
42/// An owned primitive constant, shared by native exports and declarations.
43#[derive(Debug, Default, Clone, Copy, PartialEq)]
44pub enum ConstantValue {
45 /// No value; the default descriptor's value.
46 #[default]
47 Undefined,
48 /// A static UTF-8 string.
49 String(&'static str),
50 /// A JavaScript number.
51 Number(f64),
52 /// A JavaScript boolean.
53 Bool(bool),
54}
55
56impl ConstantValue {
57 /// The TypeScript primitive corresponding to this value.
58 pub const fn ts_type(self) -> &'static str {
59 match self {
60 Self::Undefined => "undefined",
61 Self::String(_) => "string",
62 Self::Number(_) => "number",
63 Self::Bool(_) => "boolean",
64 }
65 }
66}
67
68/// One typed associated constant exported by a module.
69#[derive(Debug, Default, Clone, Copy, PartialEq)]
70#[non_exhaustive]
71pub struct Constant {
72 /// Its JS name (preserved, including uppercase names).
73 pub name: &'static str,
74 /// Documentation.
75 pub doc: &'static str,
76 /// Its primitive value and declaration type.
77 pub value: ConstantValue,
78}
79
80impl Constant {
81 /// Builds a constant descriptor, including from generated downstream code.
82 pub const fn new(name: &'static str, doc: &'static str, value: ConstantValue) -> Self {
83 Self { name, doc, value }
84 }
85}
86
87/// A module function's parameter: its JS name, TypeScript type, and
88/// whether it may be left out.
89pub type ModuleParam = (&'static str, TsType, bool);
90
91/// The future of an `async` function or member: its result, or the
92/// message the `Promise` rejects with.
93pub type ModuleFuture = Pin<Box<dyn Future<Output = JsResult>>>;
94
95/// A function that runs in the JS call: it converts the call's values
96/// directly; its result is an owned JS value.
97pub type SyncCall = fn(&dyn JsHost) -> Result<JsRaw, Thrown>;
98
99/// How a module function runs.
100#[derive(Clone, Copy)]
101pub enum FunctionCall {
102 /// In the JS call (no context, not `async`): its value, or what it
103 /// throws.
104 Sync(SyncCall),
105 /// As an op, with a [`ModuleCx`], in order with what JS set before it
106 /// (its arguments converted in the JS call); an error rejects the
107 /// `Promise` (a wrong argument of one returning nothing throws).
108 Op(fn(&dyn JsHost) -> Result<OpCall, Thrown>),
109 /// As a task started in order with the UI's ops (its arguments
110 /// converted in the JS call): it reaches the platform with the same free
111 /// functions views use (`dialog`, `clipboard_string`, ...).
112 Async(AsyncCall),
113 /// In the JS call, returning a task's start ([`super::Later`]): JS gets
114 /// a promise of the task, rejected with what the call refuses (a
115 /// function returning a promise never throws).
116 Start(AsyncCall),
117}
118
119impl std::fmt::Debug for FunctionCall {
120 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
121 write!(f, "{:?}", self.kind())
122 }
123}
124
125impl FunctionCall {
126 /// What it is, for the glue and the declarations.
127 pub fn kind(&self) -> FunctionKind {
128 match self {
129 FunctionCall::Sync(_) => FunctionKind::Sync,
130 FunctionCall::Op(_) => FunctionKind::Op,
131 FunctionCall::Async(_) | FunctionCall::Start(_) => FunctionKind::Async,
132 }
133 }
134}
135
136/// How a module function runs ([`FunctionCall`]), for the glue and the
137/// declarations.
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum FunctionKind {
140 /// In the JS call: TS gets the value.
141 Sync,
142 /// An op: TS gets a promise of the value; without one (`()`), nothing
143 /// (`void`): the op runs in order with the UI, and no reply comes back.
144 Op,
145 /// A task: TS gets a promise of the value (`Promise<void>` without
146 /// one, settled when the task ends).
147 Async,
148}
149
150/// A function of a module (`#[module]` makes them).
151pub struct Function {
152 /// Its JS name (`alert`).
153 pub name: &'static str,
154 /// Documentation.
155 pub doc: &'static str,
156 /// Its parameters.
157 pub params: &'static [ModuleParam],
158 /// The TypeScript type of its result; `None`: nothing (`void`; a
159 /// promise of it for a task).
160 pub returns: Option<TsType>,
161 /// The classes its parameters and result name.
162 pub refs: super::ClassRefs,
163 /// How it runs.
164 pub call: FunctionCall,
165 /// A getter of the module's object (`#[getter]`: `process.env`), read
166 /// as a property and never a named export of a flat module.
167 pub getter: bool,
168 /// The signatures TypeScript sees instead of the one above, when the
169 /// result's type depends on the arguments (`#[overload(..)]`).
170 pub overloads: &'static [Overload],
171}
172
173/// One TypeScript signature of a function with several
174/// (`#[overload(fn(path: String) -> Vec<u8>)]`): its parameters and the
175/// type of its result (a promise of it when the function's is one).
176#[derive(Debug, Clone, Copy)]
177pub struct Overload {
178 /// Its parameters.
179 pub params: &'static [ModuleParam],
180 /// The TypeScript type of its result.
181 pub returns: Option<TsType>,
182}
183
184/// A signature of [`FunctionSpec::overloads`]: its parameters (JS name,
185/// TypeScript type, optional) and its result's type.
186pub type OverloadSpec = (Vec<(&'static str, String, bool)>, Option<String>);
187
188/// One function, for the glue and its declarations.
189#[derive(Debug, Clone)]
190pub struct FunctionSpec {
191 /// Its JS name.
192 pub name: &'static str,
193 /// Documentation.
194 pub doc: &'static str,
195 /// Its parameters: JS name, TypeScript type, optional.
196 pub params: Vec<(&'static str, String, bool)>,
197 /// The TypeScript type of its result.
198 pub returns: Option<String>,
199 /// How it runs.
200 pub kind: FunctionKind,
201 /// The call.
202 pub call: FunctionCall,
203 /// A getter of the module's object ([`Function::getter`]).
204 pub getter: bool,
205 /// The signatures TypeScript sees instead ([`Function::overloads`]).
206 pub overloads: Vec<OverloadSpec>,
207}
208
209impl FunctionSpec {
210 /// Whether JS gets a `Promise` of the result: a task always, an op
211 /// when it returns a value (`Result<(), E>` too, rejected with an
212 /// `Err`). An op returning `()` gives `undefined` (`void`): it runs in
213 /// order with the UI and nothing answers it, and a wrong argument
214 /// throws in the call.
215 pub fn promises(&self) -> bool {
216 match self.kind {
217 FunctionKind::Sync => false,
218 FunctionKind::Op => self.returns.is_some(),
219 FunctionKind::Async => true,
220 }
221 }
222}
223
224/// What a module is to JS.
225#[derive(Debug, Default, Clone)]
226#[non_exhaustive]
227pub struct ModuleSpec {
228 /// Its JS name.
229 pub name: &'static str,
230 /// Documentation.
231 pub doc: &'static str,
232 /// Its functions.
233 pub functions: Vec<FunctionSpec>,
234 /// Exported one by one ([`Module::FLAT`]).
235 pub flat: bool,
236 /// A default export of the same flat module object.
237 pub default: bool,
238 /// Primitive constants, including their declaration types.
239 pub constants: Vec<Constant>,
240 /// The named TypeScript types they use.
241 pub types: TsTypes,
242}
243
244impl ModuleSpec {
245 pub(crate) fn of<M: Module>() -> Self {
246 let mut types = TsTypes::default();
247 let functions = M::FUNCTIONS
248 .iter()
249 .map(|f| FunctionSpec {
250 name: f.name,
251 doc: f.doc,
252 params: f
253 .params
254 .iter()
255 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
256 .collect(),
257 returns: f.returns.map(|ts| ts(&mut types)),
258 kind: f.call.kind(),
259 call: f.call,
260 getter: f.getter,
261 overloads: f
262 .overloads
263 .iter()
264 .map(|o| {
265 let params = o
266 .params
267 .iter()
268 .map(|(n, ts, optional)| (*n, ts(&mut types), *optional))
269 .collect();
270 (params, o.returns.map(|ts| ts(&mut types)))
271 })
272 .collect(),
273 })
274 .collect();
275 Self {
276 name: M::NAME,
277 doc: M::DOC,
278 functions,
279 flat: M::FLAT,
280 default: M::DEFAULT,
281 constants: M::CONSTANTS.to_vec(),
282 types,
283 }
284 }
285}
286
287/// `future`, with a panic in it as its error (a promise JS waits for
288/// rejects with the message).
289pub(crate) async fn catching(future: ModuleFuture) -> JsResult {
290 struct Caught(ModuleFuture);
291 impl Future for Caught {
292 type Output = JsResult;
293
294 fn poll(
295 mut self: Pin<&mut Self>,
296 cx: &mut std::task::Context<'_>,
297 ) -> std::task::Poll<Self::Output> {
298 let future = &mut self.0;
299 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| future.as_mut().poll(cx)))
300 .unwrap_or_else(|payload| {
301 std::task::Poll::Ready(Err(super::component::panic_message(payload).into()))
302 })
303 }
304 }
305 Caught(future).await
306}
307
308/// The context of a module function that is not `async`: the platform's
309/// services, applied in order right after the call (an `async` one uses the
310/// free functions, `dialog(..)`, ...).
311#[derive(Default)]
312pub struct ModuleCx {
313 pub(crate) actions: Vec<Action>,
314}
315
316impl ModuleCx {
317 /// Shows `dialog`; await the answer in an `async` function.
318 pub fn dialog(&mut self, dialog: AlertDialogRequest) -> DialogAnswer {
319 let (answer, slot) = DialogAnswer::new();
320 self.actions.push(Action::Dialog(dialog, slot));
321 answer
322 }
323
324 /// Draws the views' bars with the built-in bar `source` makes of
325 /// `theme`, or with the platform's indicator
326 /// ([`set_builtin_scrollbars`](super::set_builtin_scrollbars)).
327 pub fn set_builtin_scrollbars(
328 &mut self,
329 source: super::ScrollbarSource,
330 theme: Option<super::AnyValue>,
331 ) {
332 self.actions.push(Action::BuiltInScrollbars(source, theme));
333 }
334
335 /// Runs `f` on the platform's main thread after the call, as
336 /// [`run_on_main_thread`](super::run_on_main_thread) does: `spawn` a task
337 /// that awaits the result, or drop it.
338 pub fn run_on_main_thread<R: Send + 'static>(
339 &mut self,
340 f: impl FnOnce() -> R + Send + 'static,
341 ) -> crate::main_thread::OnMainThread<R> {
342 let (task, result) = crate::main_thread::task(f);
343 self.actions.push(Action::MainThread(task));
344 result
345 }
346
347 /// Unfocuses the focused input, hiding the software keyboard.
348 pub fn dismiss_keyboard(&mut self) {
349 self.actions.push(Action::Command(ROOT_ID, Command::Blur));
350 }
351
352 /// Changes what functions set for the status bar (the fields `patch`
353 /// sets), under the settings components render.
354 pub fn set_status_bar(&mut self, patch: StatusBarSetting) {
355 self.actions.push(task::status_bar(patch));
356 }
357
358 /// Animates the layout changes of the next commit.
359 pub fn animate_layout(&mut self, animation: LayoutAnimation) {
360 self.actions.push(Action::Command(
361 ROOT_ID,
362 Command::LayoutAnimation(animation),
363 ));
364 }
365
366 /// The screen reader reads `message` (TS:
367 /// `announce`).
368 pub fn announce_for_accessibility(&mut self, message: impl Into<String>) {
369 self.actions.push(super::services::announce(message.into()));
370 }
371
372 /// The device plays `haptic` (TS: `Haptics` of `nsh/mobile`).
373 pub fn haptic(&mut self, haptic: crate::Haptic) {
374 self.actions.push(super::services::haptic(haptic));
375 }
376
377 /// Puts `text` on the system clipboard (TS: `Clipboard.writeText`).
378 /// The answer says whether the system clipboard took it.
379 pub fn set_clipboard(
380 &mut self,
381 text: impl Into<String>,
382 ) -> super::Answer<super::ClipboardWrite> {
383 let (answer, action) = super::services::set_clipboard(text.into());
384 self.actions.push(action);
385 answer
386 }
387
388 /// Puts `item`, its text and its HTML, on the system clipboard (TS:
389 /// `Clipboard.write`).
390 /// The answer says whether the system clipboard took it.
391 pub fn set_clipboard_item(
392 &mut self,
393 item: super::ClipboardItem,
394 ) -> super::Answer<super::ClipboardWrite> {
395 let (answer, action) = super::services::set_clipboard_item(item);
396 self.actions.push(action);
397 answer
398 }
399
400 /// Puts the image of a `data:` URI on the system clipboard (TS:
401 /// `Clipboard.writeImage`).
402 pub fn set_clipboard_image(&mut self, uri: impl Into<String>) {
403 self.actions
404 .push(super::services::set_clipboard_image(uri.into()));
405 }
406
407 /// Shows the surface in `appearance` whatever the system's (TS:
408 /// `setColorScheme`): [`crate::prelude::dark`] (the theme's mode),
409 /// `dark:` classes and the platform's controls follow it;
410 /// [`crate::platform::Appearance::System`] follows the system again.
411 pub fn set_color_scheme(&mut self, appearance: crate::platform::Appearance) {
412 self.actions.push(Action::Appearance(appearance));
413 }
414
415 /// Shows the app in `locale` whatever the user's language (`None`: the
416 /// user's again), as [`crate::i18n::set_locale`] does.
417 pub fn set_locale(&mut self, locale: Option<crate::platform::Locale>) {
418 self.actions.push(Action::Locale(locale));
419 }
420
421 /// Gives the core the app's translations (`nsh-js`: the bundle's).
422 #[doc(hidden)]
423 pub fn set_translations(&mut self, translations: crate::i18n::Translations) {
424 self.actions.push(Action::Translations(translations));
425 }
426
427 /// Merges translations into the core's dictionary (`nsh-js` and web:
428 /// `addTranslations`).
429 #[doc(hidden)]
430 pub fn add_translations(
431 &mut self,
432 map: std::collections::HashMap<String, std::collections::HashMap<String, String>>,
433 ) {
434 self.actions.push(Action::AddTranslations(map));
435 }
436
437 /// Asks the platform for `action` (the runtime's own modules).
438 pub(crate) fn act(&mut self, action: Action) {
439 self.actions.push(action);
440 }
441}
442
443#[cfg(test)]
444mod descriptor_tests {
445 use super::*;
446
447 #[nsh_macros::module]
448 struct Metadata;
449
450 #[nsh_macros::module(flat, default)]
451 impl Metadata {
452 /// An arbitrary string constant; no name-specific inference.
453 pub(crate) const LABEL: &'static str = "native";
454 pub(crate) const COUNT: i32 = -7;
455 pub(crate) const ENABLED: bool = true;
456 #[cfg(any())]
457 pub(crate) const OMITTED: bool = false;
458
459 pub(crate) fn version() -> u32 {
460 1
461 }
462 }
463
464 #[test]
465 fn descriptors_preserve_constants_default_and_value_derived_types() {
466 let module = ModuleSpec::of::<Metadata>();
467 assert!(module.flat && module.default);
468 assert_eq!(module.functions[0].name, "version");
469 assert_eq!(module.constants.len(), 3);
470 assert_eq!(module.constants[0].name, "LABEL");
471 assert_eq!(module.constants[0].value, ConstantValue::String("native"));
472 assert_eq!(module.constants[1].value, ConstantValue::Number(-7.0));
473 assert_eq!(module.constants[2].value, ConstantValue::Bool(true));
474 assert_eq!(
475 module
476 .constants
477 .iter()
478 .map(|c| c.value.ts_type())
479 .collect::<Vec<_>>(),
480 ["string", "number", "boolean"]
481 );
482 }
483
484 #[test]
485 fn descriptors_have_forward_compatible_defaults() {
486 let constant = Constant::default();
487 assert_eq!(constant.value, ConstantValue::Undefined);
488 assert_eq!(constant.value.ts_type(), "undefined");
489 let module = ModuleSpec::default();
490 assert!(!module.flat && !module.default);
491 assert!(module.functions.is_empty() && module.constants.is_empty());
492 }
493}