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