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