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