Skip to main content

nsh_core/element/
component.rs

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