Skip to main content

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