Skip to main content

nsh_core/element/
component.rs

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