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