Skip to main content

nsh_core/element/
component.rs

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