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    call::{AnyValue, JsResult, MethodCall},
16    class::{Class, ClassDef, ClassSpec, MemberKind, Thrown},
17    element::{ComponentElement, ElNode},
18    js::{JsHost, JsIn, JsOwned},
19    module::{FunctionSpec, Module, ModuleSpec},
20};
21
22/// A component written in Rust: a function that runs once ([`Self::view`])
23/// and makes its view, binding what changes to signals. Its props come from
24/// JS (or from the component whose view has it), its events go to JS.
25/// `#[component]` on a function makes the type and this impl.
26///
27/// It is registered under its type's full path ([`std::any::type_name`]:
28/// its crate, modules and name) and exported to JS as the type's own name
29/// (the last segment), so neither is written by hand
30/// ([`Registry::register`]).
31///
32/// ```ignore
33/// #[component]
34/// pub fn Button(props: ButtonProps, cx: Scope<ButtonEvent>) -> impl IntoElement {
35///     view()
36///         .px_4()
37///         .py_3()
38///         .bg(move || theme().primary) // nsh-base's theme
39///         .on_press(move || cx.emit(ButtonEvent::Press))
40///         .child(text(props.title))
41/// }
42/// ```
43pub trait Component: '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: those of the [`Api`] its view
51    /// registers (`Methods::of::<StepperApi>()`; none by default).
52    const METHODS: Methods = Methods::NONE;
53
54    /// Its documentation in TypeScript: the `#[component]` function's doc
55    /// comment (none by default).
56    const DOC: &'static str = "";
57
58    /// What it shows: its elements, with bindings where values change (TS:
59    /// a component's body). Runs once, under an owner of its own: what it
60    /// makes (signals, effects, timers) goes with the component.
61    fn view(props: Self::Props, cx: super::Scope<Self::Event>) -> impl IntoElement;
62
63    /// This component inside another one's view, given all its props.
64    /// A `#[component]` has a constructor of its own, which Rust views use
65    /// (`button().disabled(..)`); this stays for components implemented
66    /// by hand and for code generic over components.
67    fn element(props: Self::Props) -> ComponentElement<Self>
68    where
69        Self: Sized,
70    {
71        ComponentElement::new(props)
72    }
73}
74
75/// A component's code panicked: what an error boundary
76/// ([`super::catch_error`]) shows.
77#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ComponentError {
79    /// The component that failed (its registered name: its type's).
80    pub component: &'static str,
81    /// What its code panicked with.
82    pub message: String,
83}
84
85impl fmt::Display for ComponentError {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        write!(f, "{} failed: {}", self.component, self.message)
88    }
89}
90
91/// Runs component code, catching a panic as its message.
92pub(crate) fn caught<R>(f: impl FnOnce() -> R) -> Result<R, String> {
93    std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_message)
94}
95
96/// The message of a panic's payload.
97pub(crate) fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
98    match payload.downcast::<String>() {
99        Ok(s) => *s,
100        Err(payload) => match payload.downcast::<&'static str>() {
101            Ok(s) => (*s).to_owned(),
102            Err(_) => "a panic".to_owned(),
103        },
104    }
105}
106
107/// A method JS calls on a component's ref: one of its API's
108/// ([`Api`]; `#[methods]` makes them).
109pub struct Method {
110    /// Its JS name (`setValue`).
111    pub name: &'static str,
112    /// Documentation.
113    pub doc: &'static str,
114    /// Its parameters: JS names and TypeScript types.
115    pub params: &'static [Param],
116    /// The TypeScript type of its result (`None`: it returns nothing, and
117    /// JS gets `undefined`: the call runs in order with the props set
118    /// before it, with nothing to wait for).
119    pub returns: Option<TsType>,
120    /// The classes its parameters and result name.
121    pub refs: super::ClassRefs,
122    /// Its call, the arguments converted in the JS call: what the core
123    /// runs with the API, in order with the props set before it. A wrong
124    /// argument's error starts with the method's name; the host puts its
125    /// component's before it (`Stepper.setValue: ...`).
126    pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
127}
128
129/// What a component's ref does in JS: a handle its view makes, holding the
130/// signals its methods read and write, registered with
131/// [`super::Scope::methods`]. `#[methods]` on its `impl` block implements
132/// it.
133pub trait Api: Sized + 'static {
134    /// Its methods.
135    const METHODS: &'static [Method];
136}
137
138/// The methods a component's ref has, for its spec and declarations:
139/// [`Methods::of`] its [`Api`] (`#[component(methods = StepperApi)]`).
140#[derive(Clone, Copy)]
141pub struct Methods {
142    specs: fn(&mut TsTypes) -> Vec<MethodSpec>,
143    refs: super::ClassRefs,
144}
145
146impl Methods {
147    /// None.
148    pub const NONE: Self = Self {
149        specs: |_| Vec::new(),
150        refs: |_| {},
151    };
152
153    /// Those of `A`.
154    pub const fn of<A: Api>() -> Self {
155        Self {
156            specs: specs_of::<A>,
157            refs: |out| {
158                for m in A::METHODS {
159                    (m.refs)(out);
160                }
161            },
162        }
163    }
164}
165
166fn specs_of<A: Api>(types: &mut TsTypes) -> Vec<MethodSpec> {
167    A::METHODS
168        .iter()
169        .map(|m| MethodSpec {
170            name: m.name,
171            doc: m.doc,
172            params: m.params.iter().map(|(n, ts)| (*n, ts(types))).collect(),
173            returns: m.returns.map(|ts| ts(types)),
174            call: m.call,
175        })
176        .collect()
177}
178
179/// A method's parameter: its JS name, and its TypeScript type.
180pub type Param = (&'static str, TsType);
181
182/// One method, for the glue and its declarations.
183#[derive(Debug, Clone)]
184pub struct MethodSpec {
185    /// Its JS name.
186    pub name: &'static str,
187    /// Documentation.
188    pub doc: &'static str,
189    /// Its parameters: JS names and TypeScript types.
190    pub params: Vec<(&'static str, String)>,
191    /// The TypeScript type of its result; `None`: nothing (`void`).
192    pub returns: Option<String>,
193    /// Its call (the arguments converted in the JS call).
194    pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
195}
196
197impl MethodSpec {
198    /// Whether JS gets a `Promise` of the result: when the method returns
199    /// a value (`Result<(), E>` too, rejected with an `Err`). One
200    /// returning `()` gives `undefined` (`void`): the call runs in order
201    /// with the UI and nothing answers it, and a wrong argument throws.
202    pub fn promises(&self) -> bool {
203        self.returns.is_some()
204    }
205}
206
207/// What a prop is to the glue.
208#[derive(Debug, Clone, Copy, PartialEq, Eq)]
209pub enum PropKind {
210    /// A value: decoded in the JS call ([`PropSpec::decode`]), set by the
211    /// core.
212    Value,
213    /// A render function (`Option<Renderer<T>>`): decoded in the JS call
214    /// as a value is (a function, or none), its content rendered by JS
215    /// when the core asks for it ([`super::JsEvent::Render`]).
216    Renderer,
217    /// A named slot: JSX in a holder node.
218    Slot,
219    /// The JSX children.
220    Children,
221    /// Virtualized rows: in JS `each`, a row renderer and the data props of
222    /// `List` (the glue makes the list, the component places it).
223    Items,
224}
225
226/// What converts a JS value into a prop's Rust type (the prop's
227/// [`super::JsValue::from_js`], type-erased): `nsh-js` calls it when JS
228/// sets the prop.
229pub type PropDecode = fn(JsIn<'_>) -> Result<AnyValue, PropError>;
230
231/// One prop, for the glue and its declarations.
232#[derive(Debug, Clone)]
233pub struct PropSpec {
234    /// Its JS name (`accessibilityLabel`).
235    pub name: &'static str,
236    /// Its TypeScript type.
237    pub ts: String,
238    /// It may be left out.
239    pub optional: bool,
240    /// Documentation.
241    pub doc: &'static str,
242    /// What it is.
243    pub kind: PropKind,
244    /// A value prop's value from JS (`None` for slots, children and rows).
245    pub decode: Option<PropDecode>,
246}
247
248/// One event, for the glue and its declarations.
249#[derive(Debug, Clone)]
250pub struct EventSpec {
251    /// Its name (`press`: the handler is `onPress`).
252    pub name: &'static str,
253    /// The name of the handler's argument in TypeScript (`value`, or what
254    /// `#[args(..)]` on the variant says; unused without data).
255    pub arg: &'static str,
256    /// The TypeScript type of its data (`void` for none).
257    pub data: String,
258    /// Documentation.
259    pub doc: &'static str,
260    /// The handler takes several arguments (`#[args(open, reason)]` on a
261    /// variant of as many fields): `data` is their list (`open: boolean,
262    /// reason: …`), the data a JS array of them.
263    pub spread: bool,
264}
265
266/// A component's props. Derive it: `#[derive(Props)]`.
267pub trait Props: Clone + PartialEq + 'static {
268    /// The JS name of the [`super::Items`] prop, if it has one.
269    #[doc(hidden)]
270    const ITEMS: Option<&'static str> = None;
271
272    /// Its children are made only while the view places them
273    /// (`#[prop(lazy)]`).
274    #[doc(hidden)]
275    const LAZY_CHILDREN: bool = false;
276
277    /// The props (their named types declared in `types`).
278    fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
279
280    /// Every prop at its default.
281    fn initial() -> Self;
282
283    /// Prop `name` (its JS name) from JS, as [`PropSpec::decode`] made it;
284    /// `None` restores its default. Returns whether it changed.
285    fn set(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
286
287    /// Slot `name` filled (`Some`) or not; returns whether it changed.
288    fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
289
290    /// Whether the app passed children; returns whether it changed.
291    fn set_children(&mut self, children: Children) -> bool;
292
293    /// The props an instance keeps: each [`super::Prop`] field held in a
294    /// signal of the current owner, so new values reach only what read it.
295    #[doc(hidden)]
296    fn held(&self) -> Self {
297        self.clone()
298    }
299
300    /// An instance's props take `new`'s (a parent's region made the
301    /// element again): held props update their readers; returns whether
302    /// another field changed.
303    #[doc(hidden)]
304    fn update_from(&mut self, new: &Self) -> bool {
305        if self == new {
306            return false;
307        }
308        *self = new.clone();
309        true
310    }
311}
312
313/// The props of a component that has none (an app's root, say).
314impl Props for () {
315    fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
316        Vec::new()
317    }
318
319    fn initial() -> Self {}
320
321    fn set(&mut self, name: &str, _: Option<AnyValue>) -> Result<bool, PropError> {
322        Err(PropError(format!("unknown prop `{name}`")))
323    }
324
325    fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
326        false
327    }
328
329    fn set_children(&mut self, _: Children) -> bool {
330        false
331    }
332}
333
334/// A component's events. Derive it: `#[derive(Event)]`. The element of a
335/// `#[component]` emitting them gets a listener method per event, named
336/// as its TSX handler in snake case (`onPress` is `.on_press(..)`): a
337/// unit variant's takes `move || ..`, a one-field variant's the value
338/// (`move |index: &u32| ..`), a named-field variant's the event itself
339/// ([`ComponentBuilder`](super::ComponentBuilder)).
340pub trait Event: 'static {
341    /// The events (their named types declared in `types`).
342    fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
343
344    /// This event's name.
345    fn name(&self) -> &'static str;
346
347    /// Its data as a JS value of `host` (converted when JS hears it).
348    fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
349
350    /// The handler takes the items of the data (an array) as its
351    /// arguments ([`EventSpec::spread`]).
352    fn spread(&self) -> bool {
353        false
354    }
355}
356
357/// The events of a component that has none.
358#[derive(Debug, Clone, Copy, PartialEq, Eq)]
359pub enum NoEvent {}
360
361impl Event for NoEvent {
362    fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
363        Vec::new()
364    }
365
366    fn name(&self) -> &'static str {
367        match *self {}
368    }
369
370    fn data_js<'a>(&self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
371        match *self {}
372    }
373}
374
375/// What a component is to JS: its glue and declarations are generated
376/// from it ([`declarations`]).
377#[derive(Debug, Clone)]
378pub struct ComponentSpec {
379    /// Its registered name: its type's full path ([`std::any::type_name`]),
380    /// unique within one binary.
381    pub name: &'static str,
382    /// Its JS export: the type's own name, the last segment of its path.
383    pub export: String,
384    /// Documentation.
385    pub doc: &'static str,
386    /// Its props, slots and children.
387    pub props: Vec<PropSpec>,
388    /// Its events.
389    pub events: Vec<EventSpec>,
390    /// The methods of its ref.
391    pub methods: Vec<MethodSpec>,
392    /// The named TypeScript types they use.
393    pub types: TsTypes,
394    /// JS makes the children only while the view places them
395    /// (`#[prop(lazy)]` on its `Children`): the core tells it with a
396    /// `$children` event on the host.
397    pub lazy_children: bool,
398}
399
400impl ComponentSpec {
401    pub(crate) fn of<C: Component>() -> Self {
402        let mut types = TsTypes::default();
403        let props = C::Props::spec(&mut types);
404        let events = C::Event::spec(&mut types);
405        let methods = (C::METHODS.specs)(&mut types);
406        let name = name_of::<C>();
407        Self {
408            name,
409            export: export_name(name).to_owned(),
410            doc: C::DOC,
411            props,
412            events,
413            methods,
414            types,
415            lazy_children: C::Props::LAZY_CHILDREN,
416        }
417    }
418
419    /// Its named slots.
420    pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
421        self.props
422            .iter()
423            .filter(|p| p.kind == PropKind::Slot)
424            .map(|p| p.name)
425    }
426
427    /// Its render functions ([`PropKind::Renderer`]).
428    pub fn renderers(&self) -> impl Iterator<Item = &'static str> + '_ {
429        self.props
430            .iter()
431            .filter(|p| p.kind == PropKind::Renderer)
432            .map(|p| p.name)
433    }
434
435    /// Whether it takes JSX children.
436    pub fn takes_children(&self) -> bool {
437        self.props.iter().any(|p| p.kind == PropKind::Children)
438    }
439
440    /// Its [`PropKind::Items`] prop (one at most).
441    pub fn items(&self) -> Option<&'static str> {
442        self.props
443            .iter()
444            .find(|p| p.kind == PropKind::Items)
445            .map(|p| p.name)
446    }
447
448    /// The nodes the glue makes for it, by name: slots and the list.
449    pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
450        self.props
451            .iter()
452            .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
453            .map(|p| p.name)
454    }
455}
456
457/// The registered name of component `C`: its type's. It is only compared
458/// within one binary, so the format of [`std::any::type_name`] may change
459/// between compilers; the exports, which JS sees, are pinned by tests.
460pub(crate) fn name_of<C: Component>() -> &'static str {
461    std::any::type_name::<C>()
462}
463
464/// A type's own name, its JS export: the last segment of its path, without
465/// a generic type's arguments (the test `components_are_named_after_their_types`).
466fn export_name(type_name: &str) -> &str {
467    let path = type_name.split('<').next().unwrap_or(type_name);
468    path.rsplit("::").next().unwrap_or(path)
469}
470
471/// An instance: a component's props and view, their types erased.
472pub(crate) trait AnyInstance {
473    fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
474    /// Props from the component whose view has this one.
475    fn set_props(&mut self, props: &dyn Any);
476    fn set_slot(&mut self, name: &'static str, filled: bool);
477    fn set_children(&mut self, present: bool);
478    /// The component goes away: what its view made goes with it.
479    fn cleanup(&mut self);
480    /// Its view, made once.
481    fn view(&mut self) -> ElNode;
482    /// Its registered name.
483    fn name(&self) -> &'static str;
484    /// A method of its ref (its arguments decoded); `None` when it has no
485    /// ref of the method's type.
486    fn call(&mut self, call: MethodCall) -> Option<JsResult>;
487    /// Its view's owner, once its view is made.
488    fn owner(&self) -> Option<super::Owner>;
489    /// Where a failure of its code goes first: its owner, or where it is
490    /// made before it has one.
491    fn failure_owner(&self) -> super::Owner;
492    /// Made by JS (where no owner is): its view will be made under
493    /// `parent`, the owner of the nearest component above it in the tree,
494    /// so it sees that one's context.
495    fn adopt(&mut self, parent: super::Owner);
496    /// It is the component of `host`, made where `parent` owns.
497    fn place(&mut self, host: crate::NodeId, parent: super::Owner);
498}
499
500/// The root of a Rust app: makes the app's top component (on the engine
501/// thread, where elements live). The engine mounts it as the content of the
502/// surface (`nsh_engine::App::Rust`).
503#[derive(Clone)]
504pub struct Root {
505    make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
506    tokens: Option<Arc<super::Tokens>>,
507    fonts: Vec<Arc<[u8]>>,
508    appearance: Option<crate::platform::Appearance>,
509    app_id: Option<String>,
510    status_bar: Option<crate::StatusBarSetting>,
511}
512
513impl Root {
514    /// Component `C` with the props `props` makes.
515    pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
516        Self {
517            make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
518            tokens: None,
519            fonts: Vec::new(),
520            appearance: None,
521            app_id: None,
522            status_bar: None,
523        }
524    }
525
526    /// The app's id (`nsh.json` `"id"`, which nsh's generated code sets):
527    /// it names where the app keeps its data (`nsh/storage`).
528    pub fn app_id(mut self, id: impl Into<String>) -> Self {
529        self.app_id = Some(id.into());
530        self
531    }
532
533    /// The app's id ([`Root::app_id`]).
534    pub fn app_id_ref(&self) -> Option<&str> {
535        self.app_id.as_deref()
536    }
537
538    /// Renders with design tokens `tokens` (`nsh-base`'s theme's; by
539    /// default the UI sets' defaults).
540    pub fn tokens(mut self, tokens: super::Tokens) -> Self {
541        self.tokens = Some(Arc::new(tokens));
542        self
543    }
544
545    /// Registers a font file (TrueType / OpenType) before the first render;
546    /// styles name it by its family name.
547    pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
548        self.fonts.push(data.into());
549        self
550    }
551
552    /// Shows the app in `appearance` whatever the system's (`nsh.json`
553    /// `"appearance"`; later [`super::ambient::set_color_scheme`] calls
554    /// change it).
555    pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
556        self.appearance = Some(appearance);
557        self
558    }
559
560    /// The status bar's default (`nsh.json` `"statusBar"`), under what
561    /// pages and dialogs set (`Screen::status_bar`, `Modal::status_bar`).
562    pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
563        self.status_bar = Some(setting);
564        self
565    }
566
567    /// The status bar's default ([`Root::status_bar`]).
568    pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
569        self.status_bar
570    }
571
572    /// The appearance it starts in ([`Root::appearance`]; `None`: the
573    /// system's).
574    pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
575        self.appearance
576    }
577
578    /// The design tokens it renders with.
579    pub fn tokens_ref(&self) -> Option<&super::Tokens> {
580        self.tokens.as_deref()
581    }
582
583    /// The font files to register.
584    pub fn fonts(&self) -> &[Arc<[u8]>] {
585        &self.fonts
586    }
587
588    /// Component `C` with default props.
589    pub fn of<C: Component>() -> Self
590    where
591        C::Props: Default,
592    {
593        Self::new::<C>(C::Props::default)
594    }
595
596    /// The element of the root component.
597    pub(crate) fn element(&self) -> super::AnyElement {
598        (self.make)()
599    }
600}
601
602impl fmt::Debug for Root {
603    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
604        f.write_str("Root")
605    }
606}
607
608/// A new instance of `C`, its props not set yet.
609pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
610    Box::new(super::once::OnceInstance::<C>::new())
611}
612
613#[derive(Clone)]
614struct ComponentType {
615    spec: Arc<ComponentSpec>,
616    make: fn() -> Box<dyn AnyInstance>,
617    /// Tells two types of the same name apart (two versions of a crate).
618    id: TypeId,
619}
620
621#[derive(Clone)]
622struct ModuleType {
623    spec: Arc<ModuleSpec>,
624    /// The type that implements it.
625    type_name: &'static str,
626}
627
628#[derive(Clone)]
629struct ClassType {
630    spec: Arc<ClassSpec>,
631    /// The type that implements it.
632    type_name: &'static str,
633}
634
635/// What a UI set exports to JS: its components and modules, and what it
636/// passes on from the runtime. Cheap to clone.
637#[derive(Clone, Default)]
638pub struct Registry {
639    types: Arc<FxHashMap<&'static str, ComponentType>>,
640    modules: Arc<FxHashMap<&'static str, ModuleType>>,
641    /// By the specifier of their set and their name: the sets merged for
642    /// the core may have classes of the same name.
643    classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
644    /// Values and types of `nsh/_core` exported as they are.
645    reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
646    /// Values `nsh-js` makes for the set (declared by hand, not generated
647    /// from a spec).
648    native_values: Arc<Vec<&'static str>>,
649    /// The runtime module the functions belong to (`nsh/android`): JS
650    /// calls them as `nsh/android:Toast.show`, apart from any UI set's.
651    namespace: Option<&'static str>,
652    /// The JS module a UI set is imported as (`app/native`).
653    ui_set: Option<&'static str>,
654    /// The files its crates ship ([`Registry::assets`]).
655    assets: Arc<Vec<&'static [super::AssetFile]>>,
656    /// Makes the design tokens of a theme ([`Registry::tokens_from`]).
657    tokens: Option<super::TokenSource>,
658}
659
660impl fmt::Debug for Registry {
661    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
662        f.debug_set().entries(self.types.keys()).finish()
663    }
664}
665
666impl Registry {
667    /// An empty registry.
668    pub fn new() -> Self {
669        Self::default()
670    }
671
672    /// Registers component `C` under its type's name, exported to JS as
673    /// the type's own name ([`ComponentSpec::name`], [`ComponentSpec::export`]).
674    ///
675    /// # Panics
676    ///
677    /// When `C` is registered already, another type of the same name is
678    /// (two versions of one crate), or another component of the set has the
679    /// same export: a mistake in the code, caught by the app's first run.
680    #[track_caller]
681    pub fn register<C: Component>(&mut self) -> &mut Self {
682        let spec = ComponentSpec::of::<C>();
683        let types = Arc::make_mut(&mut self.types);
684        if let Some(old) = types.get(spec.name) {
685            let set = self.ui_set.or(self.namespace);
686            panic!("{}", same_name(spec.name, old.id, TypeId::of::<C>(), set));
687        }
688        if self.classes.keys().any(|(_, name)| *name == spec.export) {
689            panic!(
690                "component `{}` is exported as `{}` like a class{}: rename one",
691                spec.name,
692                spec.export,
693                of_set(self.ui_set.or(self.namespace)),
694            );
695        }
696        if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
697            panic!(
698                "components `{}` and `{}` are both exported as `{}`{}: rename one",
699                other.spec.name,
700                spec.name,
701                spec.export,
702                of_set(self.ui_set.or(self.namespace)),
703            );
704        }
705        types.insert(
706            spec.name,
707            ComponentType {
708                spec: Arc::new(spec),
709                make: make_instance::<C>,
710                id: TypeId::of::<C>(),
711            },
712        );
713        let mut refs = Vec::new();
714        (C::METHODS.refs)(&mut refs);
715        self.classes_named(refs)
716    }
717
718    /// Registers module `M`: its functions on a JS object named
719    /// [`Module::NAME`] (merged into the component exported by that name, if
720    /// the set has one).
721    ///
722    /// # Panics
723    ///
724    /// When the set has a module of that name already.
725    #[track_caller]
726    pub fn module<M: Module>(&mut self) -> &mut Self {
727        let type_name = std::any::type_name::<M>();
728        if self.classes.keys().any(|(_, name)| *name == M::NAME) {
729            panic!(
730                "module `{type_name}` is named `{}` like a class{}: rename one",
731                M::NAME,
732                of_set(self.ui_set.or(self.namespace))
733            );
734        }
735        let modules = Arc::make_mut(&mut self.modules);
736        if let Some(old) = modules.get(M::NAME) {
737            panic!(
738                "{}",
739                same_module(
740                    M::NAME,
741                    old.type_name,
742                    type_name,
743                    self.ui_set.or(self.namespace)
744                )
745            );
746        }
747        modules.insert(
748            M::NAME,
749            ModuleType {
750                spec: Arc::new(ModuleSpec::of::<M>()),
751                type_name,
752            },
753        );
754        let mut refs = Vec::new();
755        for f in M::FUNCTIONS {
756            (f.refs)(&mut refs);
757        }
758        self.classes_named(refs)
759    }
760
761    /// Registers class `C` (`#[class]`): a JS class named [`Class::DEF`]'s
762    /// name, which JS makes with `new` (when it has a constructor) and gets
763    /// from the members that return one. The classes its members'
764    /// signatures name are registered with it, as are those a module's
765    /// functions or a component's methods name ([`Registry::module`],
766    /// [`Registry::register`]): their objects reach JS, so they are
767    /// exported and declared. Registering a class again does nothing.
768    ///
769    /// # Panics
770    ///
771    /// When the set has another class, a module or a component of that
772    /// name already.
773    #[track_caller]
774    pub fn class<C: Class>(&mut self) -> &mut Self {
775        self.class_def(C::DEF)
776    }
777
778    /// Registers the classes in `refs` (a signature names them), unless
779    /// the set has them.
780    #[track_caller]
781    fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
782        for def in refs {
783            self.class_def(def);
784        }
785        self
786    }
787
788    #[track_caller]
789    fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
790        let type_name = (def.type_name)();
791        let set = self.ui_set.or(self.namespace);
792        if let Some(old) = self.classes.get(&(set, def.name)) {
793            if (old.spec.def.type_id)() == (def.type_id)() {
794                return self;
795            }
796            panic!("{}", same_class(def.name, old.type_name, type_name, set));
797        }
798        if self.modules.contains_key(def.name)
799            || self.types.values().any(|t| t.spec.export == def.name)
800        {
801            panic!(
802                "class `{type_name}` is named `{}` like a module or a component{}: rename one",
803                def.name,
804                of_set(set)
805            );
806        }
807        Arc::make_mut(&mut self.classes).insert(
808            (set, def.name),
809            ClassType {
810                spec: Arc::new(ClassSpec::of(def)),
811                type_name,
812            },
813        );
814        // What its members name, in turn (it is registered: a cycle ends).
815        let mut refs = Vec::new();
816        for m in def.members {
817            (m.refs)(&mut refs);
818        }
819        self.classes_named(refs)
820    }
821
822    /// Exports `values` and `types` of the runtime as they are (accessors
823    /// such as `safeArea`, hooks, types such as `Insets`).
824    pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
825        let r = Arc::make_mut(&mut self.reexports);
826        r.0.extend_from_slice(values);
827        r.1.extend_from_slice(types);
828        self
829    }
830
831    /// The components of all of `sets`, for making them by name (the
832    /// core's view of the sets a host serves). Not a module of its own.
833    /// Components of different sets may share an export (JS imports them
834    /// from different modules), not a name. Modules and classes are not
835    /// in it: their calls carry what they run.
836    ///
837    /// # Panics
838    ///
839    /// When two sets register the same component or two types of the same
840    /// name.
841    #[track_caller]
842    pub fn merged(sets: &[Registry]) -> Self {
843        let mut out = Self::default();
844        for set in sets {
845            out.tokens = out.tokens.or(set.tokens);
846            let types = Arc::make_mut(&mut out.types);
847            for (name, ty) in set.types.iter() {
848                if let Some(old) = types.insert(name, ty.clone()) {
849                    panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
850                }
851            }
852        }
853        out
854    }
855
856    /// The registry of a UI set apps import as `specifier`
857    /// (`app/native`). An app's crate makes its own with
858    /// `#[native_module("…")]`.
859    pub fn ui_set(specifier: &'static str) -> Self {
860        Self {
861            ui_set: Some(specifier),
862            ..Self::default()
863        }
864    }
865
866    /// The JS module the registry is imported as: a UI set's, or the
867    /// runtime module's (`None`: a Rust app's components).
868    pub fn specifier(&self) -> Option<&'static str> {
869        self.ui_set.or(self.namespace)
870    }
871
872    /// The runtime values and types exported as they are
873    /// ([`Registry::reexport`]).
874    pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
875        (&self.reexports.0, &self.reexports.1)
876    }
877
878    /// Exports `values` `nsh-js` makes for the set (`NavStack`, `NavPage`),
879    /// declared by hand rather than generated from a spec.
880    pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
881        Arc::make_mut(&mut self.native_values).extend_from_slice(values);
882        self
883    }
884
885    /// Ships `files` with the apps that use the set (`assets!()`: a crate's
886    /// `assets/` directory): `nsh run` serves them, `nsh package` copies
887    /// them into the app, and the engine registers the fonts among them
888    /// before the first render. `asset!` refers to one.
889    pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
890        Arc::make_mut(&mut self.assets).push(files);
891        self
892    }
893
894    /// Makes the design tokens of the app's theme file, and the defaults
895    /// (`nsh-base`'s theme): the core reads `nsh.json`'s `"theme"` with it.
896    pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
897        self.tokens = Some(source);
898        self
899    }
900
901    /// The tokens of theme file `json` (`None`: the defaults), by the
902    /// source a set brings ([`Registry::tokens_from`]; `None`: no set
903    /// does).
904    pub fn tokens(&self, json: Option<&str>) -> Option<Result<super::Tokens, String>> {
905        self.tokens.map(|source| source(json))
906    }
907
908    /// The files [`Registry::assets`] ships.
909    pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
910        self.assets.iter().flat_map(|files| files.iter())
911    }
912
913    /// The values of [`Registry::native_values`].
914    pub fn native_value_names(&self) -> &[&'static str] {
915        &self.native_values
916    }
917
918    /// A registry of the runtime's module `namespace` (`nsh/android`).
919    pub(crate) fn runtime(namespace: &'static str) -> Self {
920        Self {
921            namespace: Some(namespace),
922            ..Self::default()
923        }
924    }
925
926    /// The runtime module the registry's functions belong to (`None`: a UI
927    /// set's).
928    pub fn namespace(&self) -> Option<&'static str> {
929        self.namespace
930    }
931
932    /// The registered classes, by name.
933    pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
934        let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
935        specs.sort_by_key(|s| s.name);
936        specs
937    }
938
939    /// The registered modules, by name.
940    pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
941        let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
942        specs.sort_by_key(|s| s.name);
943        specs
944    }
945
946    /// The module whose functions JS finds on the function `function` of
947    /// a flat module of the set: a module named like it
948    /// (`#[module(name = "test")]`: `test.skip`), as a module named like a
949    /// component is on the component.
950    pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
951        let exported = self.modules.values().any(|m| {
952            m.spec.flat
953                && m.spec
954                    .functions
955                    .iter()
956                    .any(|f| !f.getter && f.name == function)
957        });
958        exported
959            .then(|| {
960                self.modules
961                    .values()
962                    .find(|m| !m.spec.flat && m.spec.name == function)
963                    .map(|m| m.spec.clone())
964            })
965            .flatten()
966    }
967
968    /// The registered components, by export.
969    pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
970        let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
971        specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
972        specs
973    }
974
975    /// The exports of the set that TS sees without documentation, by
976    /// their TS names (`Gauge`, `Gauge.max`, `Gauge.onChange`,
977    /// `Ledger.copy`, `new Account`, `Account.balance`): what to give a
978    /// doc comment. A component is documented by its `#[component]`
979    /// function, a module or class by its struct, the rest by their own
980    /// (a setter needs none beside its getter's; a module merged into a
981    /// component or a function of its name, or exported flat, by that
982    /// component or function, or its functions).
983    pub fn undocumented(&self) -> Vec<String> {
984        let mut out = Vec::new();
985        let specs = self.specs();
986        for c in &specs {
987            if c.doc.is_empty() {
988                out.push(c.export.clone());
989            }
990            for p in c.props.iter().filter(|p| p.doc.is_empty()) {
991                out.push(format!("{}.{}", c.export, p.name));
992            }
993            for e in c.events.iter().filter(|e| e.doc.is_empty()) {
994                out.push(format!("{}.{}", c.export, handler_name(e.name)));
995            }
996            for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
997                out.push(format!("{}.{}", c.export, m.name));
998            }
999        }
1000        for m in self.module_specs() {
1001            let merged = specs.iter().any(|c| c.export == m.name)
1002                || (!m.flat && self.function_members(m.name).is_some());
1003            if m.doc.is_empty() && !merged && !m.flat {
1004                out.push(m.name.to_owned());
1005            }
1006            for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
1007                out.push(if m.flat {
1008                    f.name.to_owned()
1009                } else {
1010                    format!("{}.{}", m.name, f.name)
1011                });
1012            }
1013        }
1014        for c in self.class_specs() {
1015            if c.doc.is_empty() {
1016                out.push(c.name.to_owned());
1017            }
1018            let documented_getter = |name: &str| {
1019                c.members
1020                    .iter()
1021                    .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
1022            };
1023            for m in c.members.iter().filter(|m| m.doc.is_empty()) {
1024                match m.kind {
1025                    MemberKind::Constructor => out.push(format!("new {}", c.name)),
1026                    MemberKind::Setter if documented_getter(m.name) => {}
1027                    _ => out.push(format!("{}.{}", c.name, m.name)),
1028                }
1029            }
1030        }
1031        out
1032    }
1033
1034    /// A new instance of component `name`.
1035    pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1036        self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
1037    }
1038}
1039
1040/// The message of two registrations under component name `name`.
1041fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
1042    if old == new {
1043        format!("component `{name}` is registered twice{}", of_set(set))
1044    } else {
1045        format!(
1046            "two different types named `{name}` are registered{} (two versions of one crate?)",
1047            of_set(set)
1048        )
1049    }
1050}
1051
1052/// The message of two modules named `name`.
1053fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1054    if old == new {
1055        format!("module `{old}` is registered twice{}", of_set(set))
1056    } else {
1057        format!(
1058            "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
1059            of_set(set)
1060        )
1061    }
1062}
1063
1064/// The message of two classes named `name`.
1065fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1066    if old == new {
1067        format!("class `{old}` is registered twice{}", of_set(set))
1068    } else {
1069        format!(
1070            "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
1071            of_set(set)
1072        )
1073    }
1074}
1075
1076/// ` in `app/native`` for a registry with a specifier.
1077fn of_set(set: Option<&str>) -> String {
1078    set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1079}
1080
1081/// The declarations of what `registry`'s specs export: one component per
1082/// spec (by its [`ComponentSpec::export`] name), one object per module
1083/// (its type `<Name>Module`; merged into a component of the same name; a
1084/// flat module's functions one by one), one class per class, and the
1085/// named types they use.
1086/// Exports named in `omit` are left out (their types stay): `nsh-js`
1087/// declares them, building on the module (`BackHandlerModule & ...`), as
1088/// it declares the re-exports and native values it makes.
1089pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
1090    let specs = registry.specs();
1091    let modules = registry.module_specs();
1092    let classes = registry.class_specs();
1093    use std::fmt::Write as _;
1094    let mut out = String::new();
1095    let doc = |out: &mut String, indent: &str, doc: &str| {
1096        if !doc.is_empty() {
1097            let _ = writeln!(out, "{indent}/** {doc} */");
1098        }
1099    };
1100    // The named types, once each.
1101    let mut types = TsTypes::default();
1102    for spec in &specs {
1103        types.merge(&spec.types);
1104    }
1105    for m in &modules {
1106        types.merge(&m.types);
1107    }
1108    for c in &classes {
1109        types.merge(&c.types);
1110    }
1111    for declaration in types.declarations() {
1112        let _ = write!(out, "{declaration}\n\n");
1113    }
1114    let module_of = |name: &str| modules.iter().find(|m| m.name == name);
1115    // A function's signatures: its own, or its overloads.
1116    let signatures = |f: &FunctionSpec| {
1117        let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
1118            let params = params
1119                .iter()
1120                .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1121                .collect::<Vec<_>>()
1122                .join(", ");
1123            let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1124            let returns = if f.promises() {
1125                format!("Promise<{value}>")
1126            } else {
1127                value
1128            };
1129            (params, returns)
1130        };
1131        if f.overloads.is_empty() {
1132            vec![one(&f.params, &f.returns)]
1133        } else {
1134            f.overloads
1135                .iter()
1136                .map(|(params, returns)| one(params, returns))
1137                .collect()
1138        }
1139    };
1140    // A module's object type.
1141    let module_object = |out: &mut String, m: &ModuleSpec| {
1142        out.push_str("{\n");
1143        for f in &m.functions {
1144            for (params, returns) in signatures(f) {
1145                doc(out, "  ", f.doc);
1146                if f.getter {
1147                    let _ = writeln!(out, "  readonly {}: {returns};", f.name);
1148                    continue;
1149                }
1150                let _ = writeln!(out, "  {}({params}): {returns};", f.name);
1151            }
1152        }
1153        for constant in &m.constants {
1154            doc(out, "  ", constant.doc);
1155            let _ = writeln!(
1156                out,
1157                "  readonly {}: {};",
1158                constant.name,
1159                constant.value.ts_type()
1160            );
1161        }
1162        out.push('}');
1163    };
1164    for spec in &specs {
1165        // A component with rows is generic over their type, like `List`.
1166        let (generic, extends) = match spec.items() {
1167            Some(_) => ("<T>", ", ListItemsProps<T>"),
1168            None => ("", ""),
1169        };
1170        // A component with methods: its ref is an object of them.
1171        let host = if spec.methods.is_empty() {
1172            "ComponentHostProps"
1173        } else {
1174            let _ = write!(
1175                out,
1176                "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n  /** The component's host node. */\n  readonly node: YNode;\n",
1177                spec.export
1178            );
1179            for m in &spec.methods {
1180                doc(&mut out, "  ", m.doc);
1181                let params = m
1182                    .params
1183                    .iter()
1184                    .map(|(n, ts)| format!("{n}: {ts}"))
1185                    .collect::<Vec<_>>()
1186                    .join(", ");
1187                let returns = match &m.returns {
1188                    Some(ts) => format!("Promise<{ts}>"),
1189                    None => "void".to_owned(),
1190                };
1191                let _ = writeln!(out, "  {}({params}): {returns};", m.name);
1192            }
1193            out.push_str("}\n\n");
1194            "Omit<ComponentHostProps, \"ref\">"
1195        };
1196        let _ = writeln!(
1197            out,
1198            "export interface {}Props{generic} extends {host}{extends} {{",
1199            spec.export
1200        );
1201        if !spec.methods.is_empty() {
1202            let _ = writeln!(
1203                out,
1204                "  ref?: {0}Ref | ((ref: {0}Ref) => void);",
1205                spec.export
1206            );
1207        }
1208        for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
1209            doc(&mut out, "  ", p.doc);
1210            let optional = if p.optional { "?" } else { "" };
1211            let _ = writeln!(out, "  {}{optional}: {};", p.name, p.ts);
1212        }
1213        for e in &spec.events {
1214            doc(&mut out, "  ", e.doc);
1215            let handler = handler_name(e.name);
1216            let arg = if e.data == "void" {
1217                String::new()
1218            } else if e.spread {
1219                e.data.clone()
1220            } else {
1221                format!("{}: {}", e.arg, e.data)
1222            };
1223            let _ = writeln!(out, "  {handler}?: ({arg}) => void;");
1224        }
1225        out.push_str("}\n\n");
1226        if omit.contains(&spec.export.as_str()) {
1227            continue;
1228        }
1229        doc(&mut out, "", spec.doc);
1230        // A module of the same name: its functions on the component.
1231        let mut with = String::new();
1232        if let Some(m) = module_of(&spec.export) {
1233            with.push_str(" & ");
1234            module_object(&mut with, m);
1235        }
1236        let _ = write!(
1237            out,
1238            "export declare const {}: ({generic}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1239            spec.export, spec.export,
1240        );
1241    }
1242    for m in &modules {
1243        if specs.iter().any(|s| s.export == m.name)
1244            || (!m.flat && registry.function_members(m.name).is_some())
1245        {
1246            continue;
1247        }
1248        if m.flat {
1249            for f in m
1250                .functions
1251                .iter()
1252                .filter(|f| !f.getter && !omit.contains(&f.name))
1253            {
1254                for (params, returns) in signatures(f) {
1255                    doc(&mut out, "", f.doc);
1256                    let _ = writeln!(
1257                        out,
1258                        "export declare function {}({params}): {returns};",
1259                        f.name
1260                    );
1261                }
1262                // A module of its name: its functions on the function.
1263                if let Some(members) = registry.function_members(f.name) {
1264                    let _ = writeln!(out, "export declare namespace {} {{", f.name);
1265                    for member in &members.functions {
1266                        for (params, returns) in signatures(member) {
1267                            doc(&mut out, "  ", member.doc);
1268                            let _ = if member.getter {
1269                                writeln!(out, "  const {}: {returns};", member.name)
1270                            } else {
1271                                writeln!(out, "  function {}({params}): {returns};", member.name)
1272                            };
1273                        }
1274                    }
1275                    for constant in &members.constants {
1276                        doc(&mut out, "  ", constant.doc);
1277                        let _ = writeln!(
1278                            out,
1279                            "  const {}: {};",
1280                            constant.name,
1281                            constant.value.ts_type()
1282                        );
1283                    }
1284                    out.push_str("}\n");
1285                }
1286                out.push('\n');
1287            }
1288            for constant in &m.constants {
1289                if !omit.contains(&constant.name) {
1290                    doc(&mut out, "", constant.doc);
1291                    let _ = writeln!(
1292                        out,
1293                        "export declare const {}: {};\n",
1294                        constant.name,
1295                        constant.value.ts_type()
1296                    );
1297                }
1298            }
1299            if m.default && !omit.contains(&"default") {
1300                let _ = write!(out, "declare const defaultExport: ");
1301                module_object(&mut out, m);
1302                // The registry's values `nsh-js` makes are on the object too.
1303                for native in registry.native_value_names() {
1304                    let _ = write!(out, " & {{ {native}: typeof {native} }}");
1305                }
1306                out.push_str(";\nexport default defaultExport;\n\n");
1307            }
1308            continue;
1309        }
1310        doc(&mut out, "", m.doc);
1311        let _ = write!(out, "export interface {}Module ", m.name);
1312        module_object(&mut out, m);
1313        out.push_str("\n\n");
1314        if !omit.contains(&m.name) {
1315            doc(&mut out, "", m.doc);
1316            let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1317        }
1318        if m.default && !omit.contains(&"default") {
1319            let _ = write!(
1320                out,
1321                "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
1322                m.name
1323            );
1324        }
1325    }
1326    for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
1327        class_declaration(&mut out, c);
1328    }
1329    out
1330}
1331
1332/// `export declare class Name { ... }`.
1333fn class_declaration(out: &mut String, c: &ClassSpec) {
1334    use std::fmt::Write as _;
1335    let doc = |out: &mut String, indent: &str, doc: &str| {
1336        if !doc.is_empty() {
1337            let _ = writeln!(out, "{indent}/** {doc} */");
1338        }
1339    };
1340    doc(out, "", c.doc);
1341    if c.def.interface {
1342        // No value: what its objects have.
1343        let _ = writeln!(out, "export interface {} {{", c.name);
1344        for m in &c.members {
1345            let params = m
1346                .params
1347                .iter()
1348                .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1349                .collect::<Vec<_>>()
1350                .join(", ");
1351            let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
1352            let returns = if m.is_async {
1353                format!("Promise<{value}>")
1354            } else {
1355                value
1356            };
1357            doc(out, "  ", m.doc);
1358            let has_setter = |name| {
1359                c.members
1360                    .iter()
1361                    .any(|s| s.kind == MemberKind::Setter && s.name == name)
1362            };
1363            let _ = match m.kind {
1364                MemberKind::Method => writeln!(out, "  {}({params}): {returns};", m.name),
1365                MemberKind::Getter if has_setter(m.name) => {
1366                    writeln!(out, "  {}: {returns};", m.name)
1367                }
1368                MemberKind::Getter => writeln!(out, "  readonly {}: {returns};", m.name),
1369                // A setter's property is its getter's; constructors and
1370                // statics belong to a class value it has none of.
1371                _ => Ok(()),
1372            };
1373        }
1374        out.push_str("}\n\n");
1375        return;
1376    }
1377    let _ = writeln!(out, "export declare class {} {{", c.name);
1378    if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
1379        out.push_str("  /** Made by the class's members only. */\n  private constructor();\n");
1380    }
1381    let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
1382        let params = params
1383            .iter()
1384            .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1385            .collect::<Vec<_>>()
1386            .join(", ");
1387        let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1388        let returns = if m.is_async {
1389            format!("Promise<{value}>")
1390        } else {
1391            value
1392        };
1393        (params, returns)
1394    };
1395    for m in &c.members {
1396        if !m.overloads.is_empty() {
1397            for (params, returns) in &m.overloads {
1398                doc(out, "  ", m.doc);
1399                let (params, returns) = one(m, params, returns);
1400                let _ = match m.kind {
1401                    MemberKind::Static => {
1402                        writeln!(out, "  static {}({params}): {returns};", m.name)
1403                    }
1404                    _ => writeln!(out, "  {}({params}): {returns};", m.name),
1405                };
1406            }
1407            continue;
1408        }
1409        doc(out, "  ", m.doc);
1410        let (params, returns) = one(m, &m.params, &m.returns);
1411        let _ = match m.kind {
1412            MemberKind::Constructor => writeln!(out, "  constructor({params});"),
1413            MemberKind::Method => writeln!(out, "  {}({params}): {returns};", m.name),
1414            MemberKind::Getter => writeln!(out, "  get {}(): {returns};", m.name),
1415            MemberKind::Setter => writeln!(out, "  set {}({params});", m.name),
1416            MemberKind::Static => writeln!(out, "  static {}({params}): {returns};", m.name),
1417        };
1418    }
1419    out.push_str(
1420        "  /** Frees the Rust value now (else when the object is collected); the object throws after. */\n  dispose(): void;\n  [Symbol.dispose](): void;\n}\n\n",
1421    );
1422}
1423
1424/// `press` -> `onPress`.
1425fn handler_name(event: &str) -> String {
1426    let mut chars = event.chars();
1427    match chars.next() {
1428        Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
1429        None => "on".to_owned(),
1430    }
1431}
1432
1433#[cfg(test)]
1434mod tests {
1435    use super::*;
1436    use crate::ui::prelude::*;
1437
1438    #[derive(Default)]
1439    struct Stepper;
1440
1441    /// Picks a number.
1442    #[derive(Clone, PartialEq, Props)]
1443    struct StepperProps {
1444        /// The value.
1445        value: f64,
1446        #[prop(default)]
1447        size: StepperSize,
1448        max_value: Option<f64>,
1449        /// Above the control.
1450        label: Option<Slot>,
1451        children: Children,
1452    }
1453
1454    #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
1455    enum StepperSize {
1456        #[default]
1457        Regular,
1458        ExtraLarge,
1459    }
1460
1461    #[derive(Event)]
1462    enum StepperEvent {
1463        /// The value changed.
1464        Change {
1465            new_value: f64,
1466        },
1467        #[args(limit)]
1468        Limit(u32),
1469        Reset,
1470    }
1471
1472    struct StepperApi;
1473
1474    #[methods]
1475    impl StepperApi {
1476        /// Jumps to `value`.
1477        pub(crate) fn jump_to(&self, value: f64) {
1478            let _ = value;
1479        }
1480
1481        pub(crate) fn value(&self) -> f64 {
1482            0.0
1483        }
1484
1485        /// A helper without `pub`: not a method of the ref.
1486        #[allow(dead_code)]
1487        fn clamp(&self, value: f64) -> f64 {
1488            value
1489        }
1490    }
1491
1492    impl Component for Stepper {
1493        type Props = StepperProps;
1494        type Event = StepperEvent;
1495        const METHODS: Methods = Methods::of::<StepperApi>();
1496        const DOC: &'static str = "Picks a number.";
1497
1498        fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
1499            view()
1500        }
1501    }
1502
1503    #[test]
1504    fn the_declarations_come_from_the_types() {
1505        let mut registry = Registry::new();
1506        registry.register::<Stepper>();
1507        let ts = declarations(&registry, &[]);
1508        for line in [
1509            "  /** The value. */\n  value: number;",
1510            "export type StepperSize = \"regular\" | \"extraLarge\";",
1511            "  size?: StepperSize;",
1512            "  maxValue?: number | null;",
1513            "  /** Above the control. */\n  label?: JSX.Element;",
1514            "  children?: JSX.Element;",
1515            "  /** The value changed. */\n  onChange?: (event: { newValue: number }) => void;",
1516            "  onLimit?: (limit: number) => void;",
1517            "  onReset?: () => void;",
1518            "/** Picks a number. */",
1519            "export interface StepperRef {",
1520            "  /** Jumps to `value`. */\n  jumpTo(value: number): void;",
1521            "  value(): Promise<number>;",
1522            "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n  ref?: StepperRef | ((ref: StepperRef) => void);",
1523            "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
1524        ] {
1525            assert!(ts.contains(line), "missing {line:?} in\n{ts}");
1526        }
1527        assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
1528        assert_eq!(StepperApi::METHODS.len(), 2);
1529        let mut props = StepperProps::initial();
1530        let size = |json| {
1531            let specs = StepperProps::spec(&mut TsTypes::default());
1532            let decode = specs
1533                .iter()
1534                .find(|p| p.name == "size")
1535                .unwrap()
1536                .decode
1537                .unwrap();
1538            super::super::json_host::decode(decode, json)
1539        };
1540        assert!(
1541            props
1542                .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
1543                .unwrap()
1544        );
1545        assert!(props.size == StepperSize::ExtraLarge);
1546        // A value of another type: the conversion fails (JS warns, the prop
1547        // keeps its value), and so does a decoded value of another prop's
1548        // type.
1549        assert!(size(serde_json::json!("huge")).is_err());
1550        assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
1551        assert!(props.set("size", None).unwrap());
1552        assert!(props.size == StepperSize::Regular);
1553        let data = |e: &StepperEvent| super::super::json_host::event_data(e);
1554        assert_eq!(
1555            data(&StepperEvent::Change { new_value: 2.5 }),
1556            Some(serde_json::json!({ "newValue": 2.5 }))
1557        );
1558        assert_eq!(data(&StepperEvent::Limit(3)), Some(serde_json::json!(3)));
1559        assert_eq!(data(&StepperEvent::Reset), None);
1560        assert_eq!(StepperEvent::Reset.name(), "reset");
1561    }
1562
1563    #[test]
1564    fn exports_without_docs_are_listed() {
1565        let mut registry = Registry::new();
1566        registry.register::<Stepper>();
1567        // `size`, `maxValue`, `children`, `onLimit`, `onReset` and the
1568        // ref's `value` have no doc comment.
1569        assert_eq!(
1570            registry.undocumented(),
1571            [
1572                "Stepper.size",
1573                "Stepper.maxValue",
1574                "Stepper.children",
1575                "Stepper.onLimit",
1576                "Stepper.onReset",
1577                "Stepper.value",
1578            ]
1579        );
1580        let mut r = Registry::ui_set("test/maker");
1581        r.module::<Maker>();
1582        assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
1583    }
1584
1585    /// A class no set registers.
1586    #[crate::ui::class]
1587    struct Lonely;
1588
1589    #[crate::ui::class]
1590    impl Lonely {
1591        pub(crate) fn new() -> Self {
1592            Lonely
1593        }
1594    }
1595
1596    /// Makes a `Lonely`.
1597    #[crate::ui::module]
1598    struct Maker;
1599
1600    #[crate::ui::module]
1601    impl Maker {
1602        pub(crate) fn make() -> Instance<Lonely> {
1603            Instance::new(Lonely)
1604        }
1605    }
1606
1607    #[test]
1608    fn the_classes_a_signature_names_are_registered_with_it() {
1609        let mut r = Registry::ui_set("test/maker");
1610        r.module::<Maker>();
1611        // The module's result names `Lonely`: it is the set's, declared and
1612        // exported.
1613        let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
1614        assert_eq!(names, ["Lonely"]);
1615        let ts = declarations(&r, &[]);
1616        assert!(ts.contains("export declare class Lonely"), "{ts}");
1617        assert!(ts.contains("make(): Lonely;"), "{ts}");
1618        // Registering it again does nothing.
1619        r.class::<Lonely>();
1620        assert_eq!(r.class_specs().len(), 1);
1621        let _ = Registry::merged(&[r]);
1622    }
1623
1624    /// Checks.
1625    #[crate::ui::module]
1626    struct Checks;
1627
1628    #[crate::ui::module(flat)]
1629    impl Checks {
1630        /// Declares a check.
1631        pub(crate) fn check(name: String) {
1632            let _ = name;
1633        }
1634    }
1635
1636    /// Unused: a module's doc when its functions are on `check`.
1637    #[crate::ui::module]
1638    struct CheckVariants;
1639
1640    #[crate::ui::module(name = "check")]
1641    impl CheckVariants {
1642        /// How many variants there are.
1643        pub(crate) const COUNT: u32 = 2;
1644
1645        /// Declares a check that does not run.
1646        pub(crate) fn skip(name: String) {
1647            let _ = name;
1648        }
1649
1650        pub(crate) fn todo(name: String) {
1651            let _ = name;
1652        }
1653    }
1654
1655    /// Named like no function of the set: an object of its own.
1656    #[crate::ui::module]
1657    struct Loose;
1658
1659    #[crate::ui::module(name = "loose")]
1660    impl Loose {
1661        /// Nothing.
1662        pub(crate) fn nothing() {}
1663    }
1664
1665    #[test]
1666    fn a_module_named_like_a_function_puts_its_functions_on_it() {
1667        let mut r = Registry::ui_set("test/checks");
1668        r.module::<Checks>()
1669            .module::<CheckVariants>()
1670            .module::<Loose>();
1671        assert_eq!(r.function_members("check").unwrap().name, "check");
1672        assert!(r.function_members("loose").is_none());
1673        let ts = declarations(&r, &[]);
1674        assert!(
1675            ts.contains(
1676                "/** Declares a check. */\n\
1677                 export declare function check(name: string): void;\n\
1678                 export declare namespace check {\n  \
1679                 /** Declares a check that does not run. */\n  \
1680                 function skip(name: string): void;\n  \
1681                 function todo(name: string): void;\n  \
1682                 /** How many variants there are. */\n  \
1683                 const COUNT: number;\n}\n"
1684            ),
1685            "{ts}"
1686        );
1687        assert!(
1688            !ts.contains("CheckVariants") && !ts.contains("checkModule"),
1689            "{ts}"
1690        );
1691        assert!(
1692            ts.contains("export declare const loose: looseModule;"),
1693            "{ts}"
1694        );
1695        // The members are documented as the function's.
1696        assert_eq!(r.undocumented(), ["check.todo"]);
1697        let described = super::super::description::SetDescription::of(&r).unwrap();
1698        let exports: Vec<_> = described
1699            .exports
1700            .iter()
1701            .map(|e| (e.name.as_str(), e.kind))
1702            .collect();
1703        assert_eq!(
1704            exports,
1705            [
1706                ("check", super::super::description::ExportKind::Function),
1707                ("loose", super::super::description::ExportKind::Module)
1708            ]
1709        );
1710    }
1711
1712    mod clash {
1713        /// Another class named `Lonely`.
1714        #[crate::ui::class]
1715        pub(super) struct Lonely;
1716
1717        #[crate::ui::class]
1718        impl Lonely {
1719            pub(super) fn new() -> Self {
1720                Lonely
1721            }
1722        }
1723    }
1724
1725    #[test]
1726    fn a_clash_through_a_signature_names_both_types() {
1727        let mut r = Registry::ui_set("test/maker");
1728        r.class::<clash::Lonely>();
1729        // `Maker.make` names the other `Lonely`.
1730        let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1731            r.module::<Maker>();
1732        }))
1733        .unwrap_err();
1734        let message = failed.downcast_ref::<String>().unwrap();
1735        assert!(
1736            message.contains("`nsh_core::ui::component::tests::clash::Lonely`")
1737                && message.contains("`nsh_core::ui::component::tests::Lonely`"),
1738            "{message}"
1739        );
1740    }
1741
1742    #[test]
1743    fn components_are_named_after_their_types() {
1744        let mut registry = Registry::ui_set("test/ui");
1745        registry.register::<Stepper>();
1746        let specs = registry.specs();
1747        assert_eq!(specs[0].name, "nsh_core::ui::component::tests::Stepper");
1748        assert_eq!(specs[0].export, "Stepper");
1749        assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
1750        assert_eq!(export_name("Bare"), "Bare");
1751    }
1752
1753    mod other {
1754        use crate::ui::prelude::*;
1755
1756        /// Another component exported as `Stepper`.
1757        #[derive(Default)]
1758        pub(super) struct Stepper;
1759
1760        impl Component for Stepper {
1761            type Props = ();
1762            type Event = NoEvent;
1763
1764            fn view(_: (), _: crate::ui::Scope<NoEvent>) -> impl IntoElement {
1765                view()
1766            }
1767        }
1768    }
1769
1770    #[test]
1771    #[should_panic(
1772        expected = "components `nsh_core::ui::component::tests::Stepper` and `nsh_core::ui::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
1773    )]
1774    fn two_components_of_one_set_cannot_share_an_export() {
1775        Registry::ui_set("test/ui")
1776            .register::<Stepper>()
1777            .register::<other::Stepper>();
1778    }
1779
1780    #[test]
1781    #[should_panic(
1782        expected = "component `nsh_core::ui::component::tests::Stepper` is registered twice"
1783    )]
1784    fn a_component_is_registered_once() {
1785        Registry::new().register::<Stepper>().register::<Stepper>();
1786    }
1787
1788    #[test]
1789    fn sets_may_share_exports_but_not_components() {
1790        let mut a = Registry::ui_set("test/a");
1791        a.register::<Stepper>();
1792        let mut b = Registry::ui_set("test/b");
1793        b.register::<other::Stepper>();
1794        let merged = Registry::merged(&[a.clone(), b]);
1795        assert_eq!(merged.specs().len(), 2);
1796        let twice = std::panic::catch_unwind(|| Registry::merged(&[a.clone(), a]));
1797        let message = *twice.unwrap_err().downcast::<String>().unwrap();
1798        assert_eq!(
1799            message,
1800            "component `nsh_core::ui::component::tests::Stepper` is registered twice, by two UI sets"
1801        );
1802    }
1803}