Skip to main content

nsh_core/ui/
component.rs

1//! Components: the [`Component`] trait, its [`Props`] and [`Event`]s
2//! (derived), the [`Registry`] a surface renders from, and the JS glue and
3//! TypeScript declarations generated from them ([`declarations`]).
4
5use std::{
6    any::{Any, TypeId},
7    fmt,
8    sync::Arc,
9};
10
11use rustc_hash::FxHashMap;
12
13use super::{
14    Children, IntoElement, PropError, Slot, TsType, TsTypes,
15    element::{ComponentElement, ElNode},
16    module::{Function, FunctionSpec, Module, ModuleSpec},
17};
18use crate::JsonValue;
19
20/// A component written in Rust: a function that runs once ([`Self::view`])
21/// and makes its view, binding what changes to signals. Its props come from
22/// JS (or from the component whose view has it), its events go to JS.
23/// `#[component]` on a function makes the type and this impl.
24///
25/// It is registered under its type's name ([`std::any::type_name`]:
26/// `nsh_ui_mobile::button::Button`) and exported to JS as the type's own
27/// name (`Button`), so neither is written by hand
28/// ([`Registry::register`]).
29///
30/// ```ignore
31/// #[component]
32/// pub fn Button(props: ButtonProps, cx: Scope<ButtonEvent>) -> impl IntoElement {
33///     view()
34///         .px_4()
35///         .py_3()
36///         .bg(move || theme().primary)
37///         .on_press(move |_: &()| cx.emit(ButtonEvent::Press))
38///         .child(text(props.title))
39/// }
40/// ```
41pub trait Component: 'static {
42    /// Its props (`#[derive(Props)]`).
43    type Props: Props;
44
45    /// Its events (`#[derive(Event)]`; [`NoEvent`] for none).
46    type Event: Event;
47
48    /// The methods of its ref in JS: those of the [`Api`] its view
49    /// registers (`Methods::of::<StepperApi>()`; none by default).
50    const METHODS: Methods = Methods::NONE;
51
52    /// What it shows: its elements, with bindings where values change (TS:
53    /// a component's body). Runs once, under an owner of its own: what it
54    /// makes (signals, effects, timers) goes with the component.
55    fn view(props: Self::Props, cx: super::Scope<Self::Event>) -> impl IntoElement;
56
57    /// This component inside another one's view.
58    fn element(props: Self::Props) -> ComponentElement<Self>
59    where
60        Self: Sized,
61    {
62        ComponentElement::new(props)
63    }
64}
65
66/// A component's code panicked: what an error boundary
67/// ([`super::catch_error`]) shows.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct ComponentError {
70    /// The component that failed (its registered name: its type's).
71    pub component: &'static str,
72    /// What its code panicked with.
73    pub message: String,
74}
75
76impl fmt::Display for ComponentError {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        write!(f, "{} failed: {}", self.component, self.message)
79    }
80}
81
82/// Runs component code, catching a panic as its message.
83pub(crate) fn caught<R>(f: impl FnOnce() -> R) -> Result<R, String> {
84    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_message)
85}
86
87/// The message of a panic's payload.
88pub(crate) fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
89    match payload.downcast::<String>() {
90        Ok(s) => *s,
91        Err(payload) => match payload.downcast::<&'static str>() {
92            Ok(s) => (*s).to_owned(),
93            Err(_) => "a panic".to_owned(),
94        },
95    }
96}
97
98/// A method JS calls on a component's ref: one of its API's
99/// ([`Api`]; `#[methods]` makes them).
100pub struct Method<A: 'static> {
101    /// Its JS name (`setValue`).
102    pub name: &'static str,
103    /// Documentation.
104    pub doc: &'static str,
105    /// Its parameters: JS names and TypeScript types.
106    pub params: &'static [Param],
107    /// The TypeScript type of its result (`None`: it returns nothing, and
108    /// JS does not wait for it).
109    pub returns: Option<TsType>,
110    /// Calls it with JS's arguments.
111    pub call: fn(&A, Vec<JsonValue>) -> Result<JsonValue, PropError>,
112}
113
114/// What a component's ref does in JS: a handle its view makes, holding the
115/// signals its methods read and write, registered with
116/// [`super::Scope::methods`]. `#[methods]` on its `impl` block implements
117/// it.
118pub trait Api: Sized + 'static {
119    /// Its methods.
120    const METHODS: &'static [Method<Self>];
121}
122
123/// The methods a component's ref has, for its spec and declarations:
124/// [`Methods::of`] its [`Api`] (`#[component(methods = StepperApi)]`).
125#[derive(Clone, Copy)]
126pub struct Methods {
127    specs: fn(&mut TsTypes) -> Vec<MethodSpec>,
128}
129
130impl Methods {
131    /// None.
132    pub const NONE: Self = Self {
133        specs: |_| Vec::new(),
134    };
135
136    /// Those of `A`.
137    pub const fn of<A: Api>() -> Self {
138        Self {
139            specs: specs_of::<A>,
140        }
141    }
142}
143
144fn specs_of<A: Api>(types: &mut TsTypes) -> Vec<MethodSpec> {
145    A::METHODS
146        .iter()
147        .map(|m| MethodSpec {
148            name: m.name,
149            doc: m.doc,
150            params: m.params.iter().map(|(n, ts)| (*n, ts(types))).collect(),
151            returns: m.returns.map(|ts| ts(types)),
152        })
153        .collect()
154}
155
156/// A method's parameter: its JS name, and its TypeScript type.
157pub type Param = (&'static str, TsType);
158
159/// One method, for the glue and its declarations.
160#[derive(Debug, Clone)]
161pub struct MethodSpec {
162    /// Its JS name.
163    pub name: &'static str,
164    /// Documentation.
165    pub doc: &'static str,
166    /// Its parameters: JS names and TypeScript types.
167    pub params: Vec<(&'static str, String)>,
168    /// The TypeScript type of its result; `None`: nothing to wait for.
169    pub returns: Option<String>,
170}
171
172/// What a prop is to the glue.
173#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub enum PropKind {
175    /// A value, sent as `$name`.
176    Value,
177    /// A named slot: JSX in a holder node.
178    Slot,
179    /// The JSX children.
180    Children,
181    /// Virtualized rows: in JS `each`, a row renderer and the data props of
182    /// `List` (the glue makes the list, the component places it).
183    Items,
184}
185
186/// One prop, for the glue and its declarations.
187#[derive(Debug, Clone)]
188pub struct PropSpec {
189    /// Its JS name (`accessibilityLabel`).
190    pub name: &'static str,
191    /// Its TypeScript type.
192    pub ts: String,
193    /// It may be left out.
194    pub optional: bool,
195    /// Documentation.
196    pub doc: &'static str,
197    /// What it is.
198    pub kind: PropKind,
199}
200
201/// One event, for the glue and its declarations.
202#[derive(Debug, Clone)]
203pub struct EventSpec {
204    /// Its name (`press`: the handler is `onPress`).
205    pub name: &'static str,
206    /// The TypeScript type of its data (`void` for none).
207    pub data: String,
208    /// Documentation.
209    pub doc: &'static str,
210}
211
212/// A component's props. Derive it: `#[derive(Props)]`.
213pub trait Props: Clone + PartialEq + 'static {
214    /// The JS name of the [`super::Items`] prop, if it has one.
215    #[doc(hidden)]
216    const ITEMS: Option<&'static str> = None;
217
218    /// Its children are made only while the view places them
219    /// (`#[prop(lazy)]`).
220    #[doc(hidden)]
221    const LAZY_CHILDREN: bool = false;
222
223    /// The component's documentation (the struct's doc comment).
224    fn doc() -> &'static str;
225
226    /// The props (their named types declared in `types`).
227    fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
228
229    /// Every prop at its default.
230    fn initial() -> Self;
231
232    /// Prop `name` (its JS name) from JS; `None` restores its default.
233    /// Returns whether it changed.
234    fn set(&mut self, name: &str, value: Option<JsonValue>) -> Result<bool, PropError>;
235
236    /// Slot `name` filled (`Some`) or not; returns whether it changed.
237    fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
238
239    /// Whether the app passed children; returns whether it changed.
240    fn set_children(&mut self, children: Children) -> bool;
241
242    /// The props an instance keeps: each [`super::Prop`] field held in a
243    /// signal of the current owner, so new values reach only what read it.
244    #[doc(hidden)]
245    fn held(&self) -> Self {
246        self.clone()
247    }
248
249    /// An instance's props take `new`'s (a parent's region made the
250    /// element again): held props update their readers; returns whether
251    /// another field changed.
252    #[doc(hidden)]
253    fn update_from(&mut self, new: &Self) -> bool {
254        if self == new {
255            return false;
256        }
257        *self = new.clone();
258        true
259    }
260}
261
262/// The props of a component that has none (an app's root, say).
263impl Props for () {
264    fn doc() -> &'static str {
265        ""
266    }
267
268    fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
269        Vec::new()
270    }
271
272    fn initial() -> Self {}
273
274    fn set(&mut self, name: &str, _: Option<JsonValue>) -> Result<bool, PropError> {
275        Err(PropError(format!("unknown prop `{name}`")))
276    }
277
278    fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
279        false
280    }
281
282    fn set_children(&mut self, _: Children) -> bool {
283        false
284    }
285}
286
287/// A component's events. Derive it: `#[derive(Event)]`.
288pub trait Event: 'static {
289    /// The events (their named types declared in `types`).
290    fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
291
292    /// This event's name.
293    fn name(&self) -> &'static str;
294
295    /// Its data for JS.
296    fn data(&self) -> JsonValue;
297}
298
299/// The events of a component that has none.
300#[derive(Debug, Clone, Copy, PartialEq, Eq)]
301pub enum NoEvent {}
302
303impl Event for NoEvent {
304    fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
305        Vec::new()
306    }
307
308    fn name(&self) -> &'static str {
309        match *self {}
310    }
311
312    fn data(&self) -> JsonValue {
313        match *self {}
314    }
315}
316
317/// What a component is to JS: its glue and declarations are generated
318/// from it ([`declarations`]).
319#[derive(Debug, Clone)]
320pub struct ComponentSpec {
321    /// Its registered name: its type's ([`std::any::type_name`]:
322    /// `nsh_ui_mobile::button::Button`), unique within one binary.
323    pub name: &'static str,
324    /// Its JS export: the type's own name (`Button`).
325    pub export: String,
326    /// Documentation.
327    pub doc: &'static str,
328    /// Its props, slots and children.
329    pub props: Vec<PropSpec>,
330    /// Its events.
331    pub events: Vec<EventSpec>,
332    /// The methods of its ref.
333    pub methods: Vec<MethodSpec>,
334    /// The named TypeScript types they use.
335    pub types: TsTypes,
336    /// JS makes the children only while the view places them
337    /// (`#[prop(lazy)]` on its `Children`): the core tells it with a
338    /// `$children` event on the host.
339    pub lazy_children: bool,
340}
341
342impl ComponentSpec {
343    pub(crate) fn of<C: Component>() -> Self {
344        let mut types = TsTypes::default();
345        let props = C::Props::spec(&mut types);
346        let events = C::Event::spec(&mut types);
347        let methods = (C::METHODS.specs)(&mut types);
348        let name = name_of::<C>();
349        Self {
350            name,
351            export: export_name(name).to_owned(),
352            doc: C::Props::doc(),
353            props,
354            events,
355            methods,
356            types,
357            lazy_children: C::Props::LAZY_CHILDREN,
358        }
359    }
360
361    /// Its named slots.
362    pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
363        self.props
364            .iter()
365            .filter(|p| p.kind == PropKind::Slot)
366            .map(|p| p.name)
367    }
368
369    /// Whether it takes JSX children.
370    pub fn takes_children(&self) -> bool {
371        self.props.iter().any(|p| p.kind == PropKind::Children)
372    }
373
374    /// Its [`PropKind::Items`] prop (one at most).
375    pub fn items(&self) -> Option<&'static str> {
376        self.props
377            .iter()
378            .find(|p| p.kind == PropKind::Items)
379            .map(|p| p.name)
380    }
381
382    /// The nodes the glue makes for it, by name: slots and the list.
383    pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
384        self.props
385            .iter()
386            .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
387            .map(|p| p.name)
388    }
389}
390
391/// The registered name of component `C`: its type's. It is only compared
392/// within one binary, so the format of [`std::any::type_name`] may change
393/// between compilers; the exports, which JS sees, are pinned by tests.
394pub(crate) fn name_of<C: Component>() -> &'static str {
395    std::any::type_name::<C>()
396}
397
398/// A type's own name, its JS export: `nsh_ui_mobile::tab_bar::TabBar` ->
399/// `TabBar` (a generic one's without its arguments: `app::Picker<app::Fruit>`
400/// -> `Picker`).
401fn export_name(type_name: &str) -> &str {
402    let path = type_name.split('<').next().unwrap_or(type_name);
403    path.rsplit("::").next().unwrap_or(path)
404}
405
406/// An instance: a component's props and view, their types erased.
407pub(crate) trait AnyInstance {
408    fn set_prop(&mut self, name: &str, value: Option<JsonValue>) -> Result<bool, PropError>;
409    /// Props from the component whose view has this one.
410    fn set_props(&mut self, props: &dyn Any);
411    fn set_slot(&mut self, name: &'static str, filled: bool);
412    fn set_children(&mut self, present: bool);
413    /// The component goes away: what its view made goes with it.
414    fn cleanup(&mut self);
415    /// Its view, made once.
416    fn view(&mut self) -> ElNode;
417    /// Its registered name.
418    fn name(&self) -> &'static str;
419    /// Method `name` of its ref; `None` when it has none of that name.
420    fn call(&mut self, name: &str, args: Vec<JsonValue>) -> Option<Result<JsonValue, PropError>>;
421    /// Its view's owner, once its view is made.
422    fn owner(&self) -> Option<super::Owner>;
423    /// Where a failure of its code goes first: its owner, or where it is
424    /// made before it has one.
425    fn failure_owner(&self) -> super::Owner;
426    /// Made by JS (where no owner is): its view will be made under
427    /// `parent`, the owner of the nearest component above it in the tree,
428    /// so it sees that one's context.
429    fn adopt(&mut self, parent: super::Owner);
430    /// It is the component of `host`, made where `parent` owns.
431    fn place(&mut self, host: crate::NodeId, parent: super::Owner);
432}
433
434/// The root of a Rust app: makes the app's top component (on the engine
435/// thread, where elements live). The engine mounts it as the content of the
436/// surface (`nsh_engine::App::Rust`).
437#[derive(Clone)]
438pub struct Root {
439    make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
440    theme: Option<Arc<super::Theme>>,
441    fonts: Vec<Arc<[u8]>>,
442}
443
444impl Root {
445    /// Component `C` with the props `props` makes.
446    pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
447        Self {
448            make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
449            theme: None,
450            fonts: Vec::new(),
451        }
452    }
453
454    /// Renders with `theme` (by default the default one).
455    pub fn theme(mut self, theme: super::Theme) -> Self {
456        self.theme = Some(Arc::new(theme));
457        self
458    }
459
460    /// Registers a font file (TrueType / OpenType) before the first render;
461    /// styles name it by its family name.
462    pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
463        self.fonts.push(data.into());
464        self
465    }
466
467    /// The theme it renders with.
468    pub fn theme_ref(&self) -> Option<&super::Theme> {
469        self.theme.as_deref()
470    }
471
472    /// The font files to register.
473    pub fn fonts(&self) -> &[Arc<[u8]>] {
474        &self.fonts
475    }
476
477    /// Component `C` with default props.
478    pub fn of<C: Component>() -> Self
479    where
480        C::Props: Default,
481    {
482        Self::new::<C>(C::Props::default)
483    }
484
485    /// The element of the root component.
486    pub(crate) fn element(&self) -> super::AnyElement {
487        (self.make)()
488    }
489}
490
491impl fmt::Debug for Root {
492    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493        f.write_str("Root")
494    }
495}
496
497/// A new instance of `C`, its props not set yet.
498pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
499    Box::new(super::once::OnceInstance::<C>::new())
500}
501
502#[derive(Clone)]
503struct ComponentType {
504    spec: Arc<ComponentSpec>,
505    make: fn() -> Box<dyn AnyInstance>,
506    /// Tells two types of the same name apart (two versions of a crate).
507    id: TypeId,
508}
509
510#[derive(Clone)]
511struct ModuleType {
512    spec: Arc<ModuleSpec>,
513    functions: &'static [Function],
514    /// The type that implements it.
515    type_name: &'static str,
516}
517
518/// What a UI set exports to JS: its components and modules, and what it
519/// passes on from the runtime. Cheap to clone.
520#[derive(Clone, Default)]
521pub struct Registry {
522    types: Arc<FxHashMap<&'static str, ComponentType>>,
523    modules: Arc<FxHashMap<&'static str, ModuleType>>,
524    /// Values and types of `nsh/_core` exported as they are.
525    reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
526    /// Values `nsh-js` makes for the set (declared by hand, not generated
527    /// from a spec).
528    native_values: Arc<Vec<&'static str>>,
529    /// The runtime module the functions belong to (`nsh/android`): JS
530    /// calls them as `nsh/android:Toast.show`, apart from any UI set's.
531    namespace: Option<&'static str>,
532    /// The JS module a UI set is imported as (`nsh/ui/mobile`).
533    ui_set: Option<&'static str>,
534    /// The files its crates ship ([`Registry::assets`]).
535    assets: Arc<Vec<&'static [super::AssetFile]>>,
536}
537
538impl fmt::Debug for Registry {
539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540        f.debug_set().entries(self.types.keys()).finish()
541    }
542}
543
544impl Registry {
545    /// An empty registry.
546    pub fn new() -> Self {
547        Self::default()
548    }
549
550    /// Registers component `C` under its type's name, exported to JS as
551    /// the type's own name ([`ComponentSpec::name`], [`ComponentSpec::export`]).
552    ///
553    /// # Panics
554    ///
555    /// When `C` is registered already, another type of the same name is
556    /// (two versions of one crate), or another component of the set has the
557    /// same export: a mistake in the code, caught by the app's first run.
558    #[track_caller]
559    pub fn register<C: Component>(&mut self) -> &mut Self {
560        let spec = ComponentSpec::of::<C>();
561        let types = Arc::make_mut(&mut self.types);
562        if let Some(old) = types.get(spec.name) {
563            let set = self.ui_set.or(self.namespace);
564            panic!("{}", same_name(spec.name, old.id, TypeId::of::<C>(), set));
565        }
566        if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
567            panic!(
568                "components `{}` and `{}` are both exported as `{}`{}: rename one",
569                other.spec.name,
570                spec.name,
571                spec.export,
572                of_set(self.ui_set.or(self.namespace)),
573            );
574        }
575        types.insert(
576            spec.name,
577            ComponentType {
578                spec: Arc::new(spec),
579                make: make_instance::<C>,
580                id: TypeId::of::<C>(),
581            },
582        );
583        self
584    }
585
586    /// Registers module `M`: its functions on a JS object named
587    /// [`Module::NAME`] (merged into the component exported by that name, if
588    /// the set has one).
589    ///
590    /// # Panics
591    ///
592    /// When the set has a module of that name already.
593    #[track_caller]
594    pub fn module<M: Module>(&mut self) -> &mut Self {
595        let type_name = std::any::type_name::<M>();
596        let modules = Arc::make_mut(&mut self.modules);
597        if let Some(old) = modules.get(M::NAME) {
598            panic!(
599                "{}",
600                same_module(
601                    M::NAME,
602                    old.type_name,
603                    type_name,
604                    self.ui_set.or(self.namespace)
605                )
606            );
607        }
608        modules.insert(
609            M::NAME,
610            ModuleType {
611                spec: Arc::new(ModuleSpec::of::<M>()),
612                functions: M::FUNCTIONS,
613                type_name,
614            },
615        );
616        self
617    }
618
619    /// Exports `values` and `types` of the runtime as they are (accessors
620    /// such as `safeArea`, hooks, types such as `Insets`).
621    pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
622        let r = Arc::make_mut(&mut self.reexports);
623        r.0.extend_from_slice(values);
624        r.1.extend_from_slice(types);
625        self
626    }
627
628    /// The components and modules of all of `sets`, for finding them by
629    /// name (the core's view of the sets a host serves). Not a module of its
630    /// own. Components of different sets may share an export (JS imports
631    /// them from different modules), not a name.
632    ///
633    /// # Panics
634    ///
635    /// When two sets register the same component, two types of the same
636    /// name, or modules of the same name (JS calls their functions by it).
637    #[track_caller]
638    pub fn merged(sets: &[Registry]) -> Self {
639        let mut out = Self::default();
640        for set in sets {
641            let types = Arc::make_mut(&mut out.types);
642            for (name, ty) in set.types.iter() {
643                if let Some(old) = types.insert(name, ty.clone()) {
644                    panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
645                }
646            }
647            let modules = Arc::make_mut(&mut out.modules);
648            for (name, m) in set.modules.iter() {
649                if let Some(old) = modules.insert(name, m.clone()) {
650                    panic!(
651                        "{}, by two UI sets",
652                        same_module(name, old.type_name, m.type_name, None)
653                    );
654                }
655            }
656        }
657        out
658    }
659
660    /// The registry of a UI set apps import as `specifier`
661    /// (`nsh/ui/mobile`). An app's crate makes its own with
662    /// `#[native_module("…")]`.
663    pub fn ui_set(specifier: &'static str) -> Self {
664        Self {
665            ui_set: Some(specifier),
666            ..Self::default()
667        }
668    }
669
670    /// The JS module the registry is imported as: a UI set's, or the
671    /// runtime module's (`None`: a Rust app's components).
672    pub fn specifier(&self) -> Option<&'static str> {
673        self.ui_set.or(self.namespace)
674    }
675
676    /// The runtime values and types exported as they are
677    /// ([`Registry::reexport`]).
678    pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
679        (&self.reexports.0, &self.reexports.1)
680    }
681
682    /// Exports `values` `nsh-js` makes for the set (`Stack`, `Screen`),
683    /// declared by hand rather than generated from a spec.
684    pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
685        Arc::make_mut(&mut self.native_values).extend_from_slice(values);
686        self
687    }
688
689    /// Ships `files` with the apps that use the set (`assets!()`: a crate's
690    /// `assets/` directory): `nsh run` serves them, `nsh package` copies
691    /// them into the app, and the engine registers the fonts among them
692    /// before the first render. `asset!` refers to one.
693    pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
694        Arc::make_mut(&mut self.assets).push(files);
695        self
696    }
697
698    /// The files [`Registry::assets`] ships.
699    pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
700        self.assets.iter().flat_map(|files| files.iter())
701    }
702
703    /// The values of [`Registry::native_values`].
704    pub fn native_value_names(&self) -> &[&'static str] {
705        &self.native_values
706    }
707
708    /// A registry of the runtime's module `namespace` (`nsh/android`).
709    pub(crate) fn runtime(namespace: &'static str) -> Self {
710        Self {
711            namespace: Some(namespace),
712            ..Self::default()
713        }
714    }
715
716    /// The runtime module the registry's functions belong to (`None`: a UI
717    /// set's).
718    pub fn namespace(&self) -> Option<&'static str> {
719        self.namespace
720    }
721
722    /// Function `name` of a module (`Alert.alert`; with a namespace,
723    /// `nsh/android:Toast.show`).
724    pub(crate) fn function(&self, name: &str) -> Option<&'static Function> {
725        let name = match self.namespace {
726            Some(namespace) => name.strip_prefix(namespace)?.strip_prefix(':')?,
727            None => name,
728        };
729        let (module, function) = name.split_once('.')?;
730        self.modules
731            .get(module)?
732            .functions
733            .iter()
734            .find(|f| f.name == function)
735    }
736
737    /// The registered modules, by name.
738    pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
739        let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
740        specs.sort_by_key(|s| s.name);
741        specs
742    }
743
744    /// The registered components, by export.
745    pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
746        let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
747        specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
748        specs
749    }
750
751    /// A new instance of component `name`.
752    pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
753        self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
754    }
755}
756
757/// The message of two registrations under component name `name`.
758fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
759    if old == new {
760        format!("component `{name}` is registered twice{}", of_set(set))
761    } else {
762        format!(
763            "two different types named `{name}` are registered{} (two versions of one crate?)",
764            of_set(set)
765        )
766    }
767}
768
769/// The message of two modules named `name`.
770fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
771    if old == new {
772        format!("module `{old}` is registered twice{}", of_set(set))
773    } else {
774        format!(
775            "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
776            of_set(set)
777        )
778    }
779}
780
781/// ` in `nsh/ui/mobile`` for a registry with a specifier.
782fn of_set(set: Option<&str>) -> String {
783    set.map(|s| format!(" in `{s}`")).unwrap_or_default()
784}
785
786/// The declarations of what `registry`'s specs export: one component per
787/// spec (by its [`ComponentSpec::export`] name), one object per module
788/// (its type `<Name>Module`; merged into a component of the same name; a
789/// flat module's functions one by one), and the named types they use.
790/// Exports named in `omit` are left out (their types stay): `nsh-js`
791/// declares them, building on the module (`BackHandlerModule & ...`), as
792/// it declares the re-exports and native values it makes.
793pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
794    let specs = registry.specs();
795    let modules = registry.module_specs();
796    use std::fmt::Write as _;
797    let mut out = String::new();
798    let doc = |out: &mut String, indent: &str, doc: &str| {
799        if !doc.is_empty() {
800            let _ = writeln!(out, "{indent}/** {doc} */");
801        }
802    };
803    // The named types, once each.
804    let mut types = TsTypes::default();
805    for spec in &specs {
806        types.merge(&spec.types);
807    }
808    for m in &modules {
809        types.merge(&m.types);
810    }
811    for declaration in types.declarations() {
812        let _ = write!(out, "{declaration}\n\n");
813    }
814    let module_of = |name: &str| modules.iter().find(|m| m.name == name);
815    let signature = |f: &FunctionSpec| {
816        let params = f
817            .params
818            .iter()
819            .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
820            .collect::<Vec<_>>()
821            .join(", ");
822        let returns = match &f.returns {
823            Some(ts) => format!("Promise<{ts}>"),
824            None => "void".to_owned(),
825        };
826        (params, returns)
827    };
828    // A module's object type.
829    let module_object = |out: &mut String, m: &ModuleSpec| {
830        out.push_str("{\n");
831        for f in &m.functions {
832            doc(out, "  ", f.doc);
833            let (params, returns) = signature(f);
834            let _ = writeln!(out, "  {}({params}): {returns};", f.name);
835        }
836        out.push('}');
837    };
838    for spec in &specs {
839        // A component with rows is generic over their type, like `List`.
840        let (generic, extends) = match spec.items() {
841            Some(_) => ("<T>", ", ListItemsProps<T>"),
842            None => ("", ""),
843        };
844        // A component with methods: its ref is an object of them.
845        let host = if spec.methods.is_empty() {
846            "ComponentHostProps"
847        } else {
848            let _ = write!(
849                out,
850                "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n  /** The component's host node. */\n  readonly node: YNode;\n",
851                spec.export
852            );
853            for m in &spec.methods {
854                doc(&mut out, "  ", m.doc);
855                let params = m
856                    .params
857                    .iter()
858                    .map(|(n, ts)| format!("{n}: {ts}"))
859                    .collect::<Vec<_>>()
860                    .join(", ");
861                let returns = match &m.returns {
862                    Some(ts) => format!("Promise<{ts}>"),
863                    None => "void".to_owned(),
864                };
865                let _ = writeln!(out, "  {}({params}): {returns};", m.name);
866            }
867            out.push_str("}\n\n");
868            "Omit<ComponentHostProps, \"ref\">"
869        };
870        let _ = writeln!(
871            out,
872            "export interface {}Props{generic} extends {host}{extends} {{",
873            spec.export
874        );
875        if !spec.methods.is_empty() {
876            let _ = writeln!(
877                out,
878                "  ref?: {0}Ref | ((ref: {0}Ref) => void);",
879                spec.export
880            );
881        }
882        for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
883            doc(&mut out, "  ", p.doc);
884            let optional = if p.optional { "?" } else { "" };
885            let _ = writeln!(out, "  {}{optional}: {};", p.name, p.ts);
886        }
887        for e in &spec.events {
888            doc(&mut out, "  ", e.doc);
889            let handler = handler_name(e.name);
890            let arg = if e.data == "void" {
891                String::new()
892            } else {
893                format!("data: {}", e.data)
894            };
895            let _ = writeln!(out, "  {handler}?: ({arg}) => void;");
896        }
897        out.push_str("}\n\n");
898        if omit.contains(&spec.export.as_str()) {
899            continue;
900        }
901        doc(&mut out, "", spec.doc);
902        // A module of the same name: its functions on the component.
903        let mut with = String::new();
904        if let Some(m) = module_of(&spec.export) {
905            with.push_str(" & ");
906            module_object(&mut with, m);
907        }
908        let _ = write!(
909            out,
910            "export declare const {}: ({generic}(props: {}Props{generic}) => JSX.Element){with};\n\n",
911            spec.export, spec.export,
912        );
913    }
914    for m in &modules {
915        if specs.iter().any(|s| s.export == m.name) {
916            continue;
917        }
918        if m.flat {
919            for f in m.functions.iter().filter(|f| !omit.contains(&f.name)) {
920                doc(&mut out, "", f.doc);
921                let (params, returns) = signature(f);
922                let _ = write!(
923                    out,
924                    "export declare function {}({params}): {returns};\n\n",
925                    f.name
926                );
927            }
928            continue;
929        }
930        doc(&mut out, "", m.doc);
931        let _ = write!(out, "export interface {}Module ", m.name);
932        module_object(&mut out, m);
933        out.push_str("\n\n");
934        if !omit.contains(&m.name) {
935            doc(&mut out, "", m.doc);
936            let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
937        }
938    }
939    out
940}
941
942/// `press` -> `onPress`.
943fn handler_name(event: &str) -> String {
944    let mut chars = event.chars();
945    match chars.next() {
946        Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
947        None => "on".to_owned(),
948    }
949}
950
951#[cfg(test)]
952mod tests {
953    use super::*;
954    use crate::ui::prelude::*;
955
956    #[derive(Default)]
957    struct Stepper;
958
959    /// Picks a number.
960    #[derive(Clone, PartialEq, Props)]
961    struct StepperProps {
962        /// The value.
963        value: f64,
964        #[prop(default)]
965        size: StepperSize,
966        max_value: Option<f64>,
967        /// Above the control.
968        label: Option<Slot>,
969        children: Children,
970    }
971
972    #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
973    enum StepperSize {
974        #[default]
975        Regular,
976        ExtraLarge,
977    }
978
979    #[derive(Event)]
980    enum StepperEvent {
981        /// The value changed.
982        Change {
983            new_value: f64,
984        },
985        Limit(u32),
986        Reset,
987    }
988
989    struct StepperApi;
990
991    #[methods]
992    impl StepperApi {
993        /// Jumps to `value`.
994        fn jump_to(&self, value: f64) {
995            let _ = value;
996        }
997
998        fn value(&self) -> f64 {
999            0.0
1000        }
1001    }
1002
1003    impl Component for Stepper {
1004        type Props = StepperProps;
1005        type Event = StepperEvent;
1006        const METHODS: Methods = Methods::of::<StepperApi>();
1007
1008        fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
1009            view()
1010        }
1011    }
1012
1013    #[test]
1014    fn the_declarations_come_from_the_types() {
1015        let mut registry = Registry::new();
1016        registry.register::<Stepper>();
1017        let ts = declarations(&registry, &[]);
1018        for line in [
1019            "  /** The value. */\n  value: number;",
1020            "export type StepperSize = \"regular\" | \"extraLarge\";",
1021            "  size?: StepperSize;",
1022            "  maxValue?: number | null;",
1023            "  /** Above the control. */\n  label?: JSX.Element;",
1024            "  children?: JSX.Element;",
1025            "  /** The value changed. */\n  onChange?: (data: { newValue: number }) => void;",
1026            "  onLimit?: (data: number) => void;",
1027            "  onReset?: () => void;",
1028            "/** Picks a number. */",
1029            "export interface StepperRef {",
1030            "  /** Jumps to `value`. */\n  jumpTo(value: number): void;",
1031            "  value(): Promise<number>;",
1032            "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n  ref?: StepperRef | ((ref: StepperRef) => void);",
1033            "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
1034        ] {
1035            assert!(ts.contains(line), "missing {line:?} in\n{ts}");
1036        }
1037        let mut props = StepperProps::initial();
1038        assert!(
1039            props
1040                .set("size", Some(serde_json::json!("extraLarge")))
1041                .unwrap()
1042        );
1043        assert!(props.size == StepperSize::ExtraLarge);
1044        assert!(props.set("size", Some(serde_json::json!("huge"))).is_err());
1045        assert!(props.set("size", None).unwrap());
1046        assert!(props.size == StepperSize::Regular);
1047        assert_eq!(
1048            StepperEvent::Change { new_value: 2.5 }.data(),
1049            serde_json::json!({ "newValue": 2.5 })
1050        );
1051        assert_eq!(StepperEvent::Limit(3).data(), serde_json::json!(3));
1052        assert_eq!(StepperEvent::Reset.name(), "reset");
1053    }
1054
1055    #[test]
1056    fn components_are_named_after_their_types() {
1057        let mut registry = Registry::ui_set("test/ui");
1058        registry.register::<Stepper>();
1059        let specs = registry.specs();
1060        assert_eq!(specs[0].name, "nsh_core::ui::component::tests::Stepper");
1061        assert_eq!(specs[0].export, "Stepper");
1062        assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
1063        assert_eq!(export_name("Bare"), "Bare");
1064    }
1065
1066    mod other {
1067        use crate::ui::prelude::*;
1068
1069        /// Another component exported as `Stepper`.
1070        #[derive(Default)]
1071        pub(super) struct Stepper;
1072
1073        impl Component for Stepper {
1074            type Props = ();
1075            type Event = NoEvent;
1076
1077            fn view(_: (), _: crate::ui::Scope<NoEvent>) -> impl IntoElement {
1078                view()
1079            }
1080        }
1081    }
1082
1083    #[test]
1084    #[should_panic(
1085        expected = "components `nsh_core::ui::component::tests::Stepper` and `nsh_core::ui::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
1086    )]
1087    fn two_components_of_one_set_cannot_share_an_export() {
1088        Registry::ui_set("test/ui")
1089            .register::<Stepper>()
1090            .register::<other::Stepper>();
1091    }
1092
1093    #[test]
1094    #[should_panic(
1095        expected = "component `nsh_core::ui::component::tests::Stepper` is registered twice"
1096    )]
1097    fn a_component_is_registered_once() {
1098        Registry::new().register::<Stepper>().register::<Stepper>();
1099    }
1100
1101    #[test]
1102    fn sets_may_share_exports_but_not_components() {
1103        let mut a = Registry::ui_set("test/a");
1104        a.register::<Stepper>();
1105        let mut b = Registry::ui_set("test/b");
1106        b.register::<other::Stepper>();
1107        let merged = Registry::merged(&[a.clone(), b]);
1108        assert_eq!(merged.specs().len(), 2);
1109        let twice = std::panic::catch_unwind(|| Registry::merged(&[a.clone(), a]));
1110        let message = *twice.unwrap_err().downcast::<String>().unwrap();
1111        assert_eq!(
1112            message,
1113            "component `nsh_core::ui::component::tests::Stepper` is registered twice, by two UI sets"
1114        );
1115    }
1116}