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