1use 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
22pub trait Component: 'static {
44 type Props: Props;
46
47 type Event: Event;
49
50 const METHODS: Methods = Methods::NONE;
53
54 const DOC: &'static str = "";
57
58 fn view(props: Self::Props, cx: super::Scope<Self::Event>) -> impl IntoElement;
62
63 fn element(props: Self::Props) -> ComponentElement<Self>
68 where
69 Self: Sized,
70 {
71 ComponentElement::new(props)
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ComponentError {
79 pub component: &'static str,
81 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
91pub(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
96pub(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
107pub struct Method {
110 pub name: &'static str,
112 pub doc: &'static str,
114 pub params: &'static [Param],
116 pub returns: Option<TsType>,
120 pub refs: super::ClassRefs,
122 pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
127}
128
129pub trait Api: Sized + 'static {
134 const METHODS: &'static [Method];
136}
137
138#[derive(Clone, Copy)]
141pub struct Methods {
142 specs: fn(&mut TsTypes) -> Vec<MethodSpec>,
143 refs: super::ClassRefs,
144}
145
146impl Methods {
147 pub const NONE: Self = Self {
149 specs: |_| Vec::new(),
150 refs: |_| {},
151 };
152
153 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
183pub type Param = (&'static str, TsType, bool);
186
187#[derive(Debug, Clone)]
189pub struct MethodSpec {
190 pub name: &'static str,
192 pub doc: &'static str,
194 pub params: Vec<(&'static str, String, bool)>,
197 pub returns: Option<String>,
199 pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
201}
202
203impl MethodSpec {
204 pub fn promises(&self) -> bool {
209 self.returns.is_some()
210 }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum PropKind {
216 Value,
219 Renderer,
223 Slot,
225 Children,
227 Items,
230}
231
232pub type PropDecode = fn(JsIn<'_>) -> Result<AnyValue, PropError>;
236
237#[derive(Debug, Clone)]
239pub struct PropSpec {
240 pub name: &'static str,
242 pub ts: String,
244 pub optional: bool,
246 pub doc: &'static str,
248 pub kind: PropKind,
250 pub decode: Option<PropDecode>,
252}
253
254#[derive(Debug, Clone)]
256pub struct EventSpec {
257 pub name: &'static str,
259 pub arg: &'static str,
262 pub data: String,
265 pub doc: &'static str,
267}
268
269pub trait Props: Clone + PartialEq + 'static {
271 #[doc(hidden)]
273 const ITEMS: Option<&'static str> = None;
274
275 #[doc(hidden)]
278 const LAZY_CHILDREN: bool = false;
279
280 #[doc(hidden)]
284 const GENERIC: bool = false;
285
286 fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
288
289 fn initial() -> Self;
291
292 fn set(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
295
296 fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
298
299 fn set_children(&mut self, children: Children) -> bool;
301
302 #[doc(hidden)]
305 fn held(&self) -> Self {
306 self.clone()
307 }
308
309 #[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
322impl 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
343pub trait Event: 'static {
350 fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
352
353 fn name(&self) -> &'static str;
355
356 fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
358}
359
360#[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#[derive(Debug, Clone)]
381pub struct ComponentSpec {
382 pub name: &'static str,
385 pub export: String,
387 pub doc: &'static str,
389 pub props: Vec<PropSpec>,
391 pub events: Vec<EventSpec>,
393 pub methods: Vec<MethodSpec>,
395 pub types: TsTypes,
397 pub lazy_children: bool,
401 pub generic: bool,
404}
405
406pub 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
432type Specs = (
434 fn(&mut TsTypes) -> Vec<PropSpec>,
435 fn(&mut TsTypes) -> Vec<EventSpec>,
436 fn(&mut TsTypes) -> Vec<MethodSpec>,
437);
438
439impl ComponentSpec {
440 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 #[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 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 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 pub fn takes_children(&self) -> bool {
504 self.props.iter().any(|p| p.kind == PropKind::Children)
505 }
506
507 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 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
524pub(crate) fn name_of<C: Component>() -> &'static str {
528 std::any::type_name::<C>()
529}
530
531pub(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
538pub(crate) trait AnyInstance {
540 fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
541 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 fn cleanup(&mut self);
547 fn view(&mut self) -> ElNode;
549 fn name(&self) -> &'static str;
551 fn call(&mut self, call: MethodCall) -> Option<JsResult>;
554 fn owner(&self) -> Option<super::Owner>;
556 fn failure_owner(&self) -> super::Owner;
559 fn adopt(&mut self, parent: super::Owner);
563 fn place(&mut self, host: crate::NodeId, parent: super::Owner);
565}
566
567#[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 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 pub fn translations(mut self, translations: crate::i18n::Translations) -> Self {
608 self.translations = Some(translations);
609 self
610 }
611
612 #[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 pub fn translations_ref(&self) -> Option<&crate::i18n::Translations> {
627 self.translations.as_ref()
628 }
629
630 pub fn app_id(mut self, id: impl Into<String>) -> Self {
633 self.app_id = Some(id.into());
634 self
635 }
636
637 pub fn app_id_ref(&self) -> Option<&str> {
639 self.app_id.as_deref()
640 }
641
642 pub fn app_info(mut self, info: crate::platform::AppInfo) -> Self {
646 self.app_info = Some(info);
647 self
648 }
649
650 #[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 #[doc(hidden)]
667 pub fn app_info_ref(&self) -> Option<&crate::platform::AppInfo> {
668 self.app_info.as_ref()
669 }
670
671 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 pub fn url_schemes_ref(&self) -> &[String] {
682 self.links.schemes()
683 }
684
685 pub fn links(mut self, links: crate::url_scheme::AppLinks) -> Self {
690 self.links = links;
691 self
692 }
693
694 #[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 pub fn links_ref(&self) -> &crate::url_scheme::AppLinks {
718 &self.links
719 }
720
721 pub fn capabilities(mut self, capabilities: crate::access::Capabilities) -> Self {
727 self.capabilities = Some(capabilities);
728 self
729 }
730
731 #[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 pub fn capabilities_ref(&self) -> Option<&crate::access::Capabilities> {
759 self.capabilities.as_ref()
760 }
761
762 pub fn tokens(mut self, tokens: super::Tokens) -> Self {
765 self.tokens = Some(Arc::new(tokens));
766 self
767 }
768
769 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
772 self.fonts.push(data.into());
773 self
774 }
775
776 pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
780 self.appearance = Some(appearance);
781 self
782 }
783
784 pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
787 self.status_bar = Some(setting);
788 self
789 }
790
791 pub fn main_window(mut self, options: crate::desktop::MainWindowOptions) -> Self {
796 self.main_window = Some(options);
797 self
798 }
799
800 #[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 pub fn main_window_ref(&self) -> Option<&crate::desktop::MainWindowOptions> {
821 self.main_window.as_ref()
822 }
823
824 pub fn application(mut self, options: crate::desktop::ApplicationOptions) -> Self {
828 self.application = Some(options);
829 self
830 }
831
832 #[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 pub fn application_ref(&self) -> Option<&crate::desktop::ApplicationOptions> {
853 self.application.as_ref()
854 }
855
856 pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
858 self.status_bar
859 }
860
861 pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
864 self.appearance
865 }
866
867 pub fn tokens_ref(&self) -> Option<&super::Tokens> {
869 self.tokens.as_deref()
870 }
871
872 pub fn fonts(&self) -> &[Arc<[u8]>] {
874 &self.fonts
875 }
876
877 pub fn of<C: Component>() -> Self
879 where
880 C::Props: Default,
881 {
882 Self::new::<C>(C::Props::default)
883 }
884
885 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
897pub const BY_NAME_MARKER: &str = "missing_instance";
902
903#[inline(never)]
907pub(crate) fn missing_instance() -> Box<dyn AnyInstance> {
908 unreachable!("a component made by name is made by its registry")
909}
910
911pub(crate) fn missing_spec() -> ComponentSpec {
913 unreachable!("a component made by name is made by its registry")
914}
915
916pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
918 Box::new(super::once::OnceInstance::<C>::new())
919}
920
921#[derive(Clone)]
922struct ComponentType {
923 spec: Arc<ComponentSpec>,
924 make: fn() -> Box<dyn AnyInstance>,
925 id: TypeId,
927}
928
929#[derive(Clone)]
930struct ModuleType {
931 spec: Arc<ModuleSpec>,
932 type_name: &'static str,
934}
935
936#[derive(Clone)]
937struct ClassType {
938 spec: Arc<ClassSpec>,
939 type_name: &'static str,
941}
942
943#[derive(Debug, Clone, Default)]
946#[non_exhaustive]
947pub struct BuiltInScrollbar {
948 pub target: crate::NodeId,
950 pub horizontal: bool,
952 pub theme: Option<Arc<crate::JsonValue>>,
955 pub theme_value: Option<super::AnyValue>,
959 pub app_theme: Option<super::AnyValue>,
962}
963
964pub type ScrollbarSource = fn(&BuiltInScrollbar) -> Option<super::AnyElement>;
969
970#[derive(Clone)]
977pub struct ScrollbarThemeValue {
978 source: ScrollbarSource,
979 theme: super::AnyValue,
980}
981
982impl ScrollbarThemeValue {
983 pub fn new(source: ScrollbarSource, theme: super::AnyValue) -> Self {
986 Self { source, theme }
987 }
988
989 pub fn source(&self) -> ScrollbarSource {
991 self.source
992 }
993
994 pub fn theme(&self) -> &super::AnyValue {
996 &self.theme
997 }
998}
999
1000impl PartialEq for ScrollbarThemeValue {
1001 fn eq(&self, other: &Self) -> bool {
1002 self.theme == other.theme
1003 }
1004}
1005
1006impl std::fmt::Debug for ScrollbarThemeValue {
1007 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1008 f.debug_tuple("ScrollbarThemeValue")
1009 .field(&self.theme)
1010 .finish()
1011 }
1012}
1013
1014#[derive(Clone, Default)]
1017pub struct Registry {
1018 types: Arc<FxHashMap<&'static str, ComponentType>>,
1019 modules: Arc<FxHashMap<&'static str, ModuleType>>,
1020 classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
1023 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
1025 native_values: Arc<Vec<&'static str>>,
1028 namespace: Option<&'static str>,
1031 ui_set: Option<&'static str>,
1033 assets: Arc<Vec<(&'static [crate::platform::Os], &'static [super::AssetFile])>>,
1036 tokens: Option<super::TokenSource>,
1038 scrollbars: Option<ScrollbarSource>,
1040 submodules: Arc<Vec<Registry>>,
1043 setups: Arc<Vec<Setup>>,
1045 fakes: Arc<Vec<(&'static str, Arc<dyn crate::fake::Fake>)>>,
1048}
1049
1050type Setup = Arc<dyn Fn() + Send + Sync>;
1052
1053impl fmt::Debug for Registry {
1054 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1055 f.debug_set().entries(self.types.keys()).finish()
1056 }
1057}
1058
1059impl Registry {
1060 pub fn new() -> Self {
1062 Self::default()
1063 }
1064
1065 #[track_caller]
1074 pub fn register<C: Component>(&mut self) -> &mut Self {
1075 let spec = ComponentSpec::of::<C>();
1076 let mut refs = Vec::new();
1077 (C::METHODS.refs)(&mut refs);
1078 self.register_erased(spec, make_instance::<C>, TypeId::of::<C>(), refs)
1079 }
1080
1081 #[track_caller]
1084 #[inline(never)]
1085 fn register_erased(
1086 &mut self,
1087 spec: ComponentSpec,
1088 make: fn() -> Box<dyn AnyInstance>,
1089 id: TypeId,
1090 refs: Vec<&'static ClassDef>,
1091 ) -> &mut Self {
1092 let types = Arc::make_mut(&mut self.types);
1093 if let Some(old) = types.get(spec.name) {
1094 let set = self.ui_set.or(self.namespace);
1095 panic!("{}", same_name(spec.name, old.id, id, set));
1096 }
1097 if self.classes.keys().any(|(_, name)| *name == spec.export) {
1098 panic!(
1099 "component `{}` is exported as `{}` like a class{}: rename one",
1100 spec.name,
1101 spec.export,
1102 of_set(self.ui_set.or(self.namespace)),
1103 );
1104 }
1105 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
1106 panic!(
1107 "components `{}` and `{}` are both exported as `{}`{}: rename one",
1108 other.spec.name,
1109 spec.name,
1110 spec.export,
1111 of_set(self.ui_set.or(self.namespace)),
1112 );
1113 }
1114 types.insert(
1115 spec.name,
1116 ComponentType {
1117 spec: Arc::new(spec),
1118 make,
1119 id,
1120 },
1121 );
1122 self.classes_named(refs)
1123 }
1124
1125 #[track_caller]
1133 pub fn module<M: Module>(&mut self) -> &mut Self {
1134 let type_name = std::any::type_name::<M>();
1135 if self.classes.keys().any(|(_, name)| *name == M::NAME) {
1136 panic!(
1137 "module `{type_name}` is named `{}` like a class{}: rename one",
1138 M::NAME,
1139 of_set(self.ui_set.or(self.namespace))
1140 );
1141 }
1142 let modules = Arc::make_mut(&mut self.modules);
1143 if let Some(old) = modules.get(M::NAME) {
1144 panic!(
1145 "{}",
1146 same_module(
1147 M::NAME,
1148 old.type_name,
1149 type_name,
1150 self.ui_set.or(self.namespace)
1151 )
1152 );
1153 }
1154 modules.insert(
1155 M::NAME,
1156 ModuleType {
1157 spec: Arc::new(ModuleSpec::of::<M>()),
1158 type_name,
1159 },
1160 );
1161 let mut refs = Vec::new();
1162 for f in M::FUNCTIONS {
1163 (f.refs)(&mut refs);
1164 }
1165 self.classes_named(refs)
1166 }
1167
1168 #[track_caller]
1181 pub fn class<C: Class>(&mut self) -> &mut Self {
1182 self.class_def(C::DEF)
1183 }
1184
1185 #[track_caller]
1188 fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
1189 for def in refs {
1190 self.class_def(def);
1191 }
1192 self
1193 }
1194
1195 #[track_caller]
1196 fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
1197 let type_name = (def.type_name)();
1198 let set = self.ui_set.or(self.namespace);
1199 if let Some(old) = self.classes.get(&(set, def.name)) {
1200 if (old.spec.def.type_id)() == (def.type_id)() {
1201 return self;
1202 }
1203 panic!("{}", same_class(def.name, old.type_name, type_name, set));
1204 }
1205 if self.modules.contains_key(def.name)
1206 || self.types.values().any(|t| t.spec.export == def.name)
1207 {
1208 panic!(
1209 "class `{type_name}` is named `{}` like a module or a component{}: rename one",
1210 def.name,
1211 of_set(set)
1212 );
1213 }
1214 Arc::make_mut(&mut self.classes).insert(
1215 (set, def.name),
1216 ClassType {
1217 spec: Arc::new(ClassSpec::of(def)),
1218 type_name,
1219 },
1220 );
1221 let mut refs = Vec::new();
1223 for m in def.members {
1224 (m.refs)(&mut refs);
1225 }
1226 self.classes_named(refs)
1227 }
1228
1229 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
1232 let r = Arc::make_mut(&mut self.reexports);
1233 r.0.extend_from_slice(values);
1234 r.1.extend_from_slice(types);
1235 self
1236 }
1237
1238 #[track_caller]
1249 pub fn merged(sets: &[Registry]) -> Self {
1250 let mut out = Self::default();
1251 for set in sets.iter().flat_map(Registry::sets) {
1252 out.tokens = out.tokens.or(set.tokens);
1253 out.scrollbars = out.scrollbars.or(set.scrollbars);
1254 Arc::make_mut(&mut out.setups).extend(set.setups.iter().cloned());
1255 let fakes = Arc::make_mut(&mut out.fakes);
1256 for (name, fake) in set.fakes.iter() {
1257 assert!(
1258 fakes.iter().all(|(n, _)| n != name),
1259 "two fakes are named `{name}`, by two UI sets"
1260 );
1261 fakes.push((name, fake.clone()));
1262 }
1263 let types = Arc::make_mut(&mut out.types);
1264 for (name, ty) in set.types.iter() {
1265 if let Some(old) = types.insert(name, ty.clone()) {
1266 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
1267 }
1268 }
1269 }
1270 out
1271 }
1272
1273 pub fn ui_set(specifier: &'static str) -> Self {
1277 Self {
1278 ui_set: Some(specifier),
1279 ..Self::default()
1280 }
1281 }
1282
1283 pub fn specifier(&self) -> Option<&'static str> {
1286 self.ui_set.or(self.namespace)
1287 }
1288
1289 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
1292 (&self.reexports.0, &self.reexports.1)
1293 }
1294
1295 #[track_caller]
1307 pub fn submodule(&mut self, set: Registry) -> &mut Self {
1308 let under = match (self.ui_set, set.ui_set) {
1309 (Some(parent), Some(child)) => child
1310 .strip_prefix(parent)
1311 .is_some_and(|rest| rest.len() > 1 && rest.starts_with('/')),
1312 _ => false,
1313 };
1314 assert!(
1315 under,
1316 "a submodule is a UI set under a path of its set's specifier: {:?} under {:?}",
1317 set.ui_set, self.ui_set
1318 );
1319 Arc::make_mut(&mut self.submodules).push(set);
1320 self
1321 }
1322
1323 pub fn sets(&self) -> Vec<&Registry> {
1327 let mut out = vec![self];
1328 for sub in self.submodules.iter() {
1329 out.extend(sub.sets());
1330 }
1331 out
1332 }
1333
1334 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
1337 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
1338 self
1339 }
1340
1341 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
1347 self.assets_for(&[], files)
1348 }
1349
1350 pub fn assets_for(
1356 &mut self,
1357 targets: &'static [crate::platform::Os],
1358 files: &'static [super::AssetFile],
1359 ) -> &mut Self {
1360 Arc::make_mut(&mut self.assets).push((targets, files));
1361 self
1362 }
1363
1364 pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
1367 self.tokens = Some(source);
1368 self
1369 }
1370
1371 pub fn scrollbars_from(&mut self, source: ScrollbarSource) -> &mut Self {
1376 self.scrollbars = Some(source);
1377 self
1378 }
1379
1380 pub(crate) fn scrollbar_source(&self) -> Option<ScrollbarSource> {
1383 self.scrollbars
1384 }
1385
1386 pub fn setup(&mut self, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
1394 Arc::make_mut(&mut self.setups).push(Arc::new(f));
1395 self
1396 }
1397
1398 #[track_caller]
1410 pub fn fake(&mut self, name: &'static str, fake: Arc<dyn crate::fake::Fake>) -> &mut Self {
1411 assert!(
1412 self.fakes.iter().all(|(n, _)| *n != name),
1413 "two fakes are named `{name}`{}",
1414 of_set(self.ui_set.or(self.namespace))
1415 );
1416 Arc::make_mut(&mut self.fakes).push((name, fake));
1417 self
1418 }
1419
1420 #[doc(hidden)]
1423 pub fn fakes(&self) -> Vec<(&'static str, Arc<dyn crate::fake::Fake>)> {
1424 self.sets()
1425 .into_iter()
1426 .flat_map(|set| set.fakes.iter().cloned())
1427 .collect()
1428 }
1429
1430 pub(crate) fn run_setups(&self) {
1433 for setup in self.setups.iter() {
1434 setup();
1435 }
1436 }
1437
1438 pub(crate) fn run_setups_not_in(&self, old: &Registry) {
1441 for setup in self.setups.iter() {
1442 let known = old
1443 .setups
1444 .iter()
1445 .any(|o| std::ptr::addr_eq(Arc::as_ptr(o), Arc::as_ptr(setup)));
1446 if !known {
1447 setup();
1448 }
1449 }
1450 }
1451
1452 pub fn tokens(
1456 &self,
1457 json: Option<&str>,
1458 ) -> Option<Result<(super::Tokens, Vec<String>), String>> {
1459 self.tokens.map(|source| source(json))
1460 }
1461
1462 pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
1464 self.tokens
1465 }
1466
1467 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
1470 self.assets.iter().flat_map(|(_, files)| files.iter())
1471 }
1472
1473 pub fn scoped_asset_files(
1476 &self,
1477 ) -> impl Iterator<Item = (&'static [crate::platform::Os], &'static super::AssetFile)> + '_
1478 {
1479 self.assets
1480 .iter()
1481 .flat_map(|&(targets, files)| files.iter().map(move |file| (targets, file)))
1482 }
1483
1484 pub fn native_value_names(&self) -> &[&'static str] {
1486 &self.native_values
1487 }
1488
1489 pub(crate) fn runtime(namespace: &'static str) -> Self {
1491 Self {
1492 namespace: Some(namespace),
1493 ..Self::default()
1494 }
1495 }
1496
1497 pub fn namespace(&self) -> Option<&'static str> {
1500 self.namespace
1501 }
1502
1503 pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
1505 let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
1506 specs.sort_by_key(|s| s.name);
1507 specs
1508 }
1509
1510 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
1512 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
1513 specs.sort_by_key(|s| s.name);
1514 specs
1515 }
1516
1517 pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
1522 let exported = self.modules.values().any(|m| {
1523 m.spec.flat
1524 && m.spec
1525 .functions
1526 .iter()
1527 .any(|f| !f.getter && f.name == function)
1528 });
1529 exported
1530 .then(|| {
1531 self.modules
1532 .values()
1533 .find(|m| !m.spec.flat && m.spec.name == function)
1534 .map(|m| m.spec.clone())
1535 })
1536 .flatten()
1537 }
1538
1539 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
1541 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
1542 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
1543 specs
1544 }
1545
1546 pub fn undocumented(&self) -> Vec<String> {
1555 let mut out = Vec::new();
1556 let specs = self.specs();
1557 for c in &specs {
1558 if c.doc.is_empty() {
1559 out.push(c.export.clone());
1560 }
1561 for p in c.props.iter().filter(|p| p.doc.is_empty()) {
1562 out.push(format!("{}.{}", c.export, p.name));
1563 }
1564 for e in c.events.iter().filter(|e| e.doc.is_empty()) {
1565 out.push(format!("{}.{}", c.export, handler_name(e.name)));
1566 }
1567 for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
1568 out.push(format!("{}.{}", c.export, m.name));
1569 }
1570 }
1571 for m in self.module_specs() {
1572 let merged = specs.iter().any(|c| c.export == m.name)
1573 || (!m.flat && self.function_members(m.name).is_some());
1574 if m.doc.is_empty() && !merged && !m.flat {
1575 out.push(m.name.to_owned());
1576 }
1577 for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
1578 out.push(if m.flat {
1579 f.name.to_owned()
1580 } else {
1581 format!("{}.{}", m.name, f.name)
1582 });
1583 }
1584 }
1585 for c in self.class_specs() {
1586 if c.doc.is_empty() {
1587 out.push(c.name.to_owned());
1588 }
1589 let documented_getter = |name: &str| {
1590 c.members
1591 .iter()
1592 .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
1593 };
1594 for m in c.members.iter().filter(|m| m.doc.is_empty()) {
1595 match m.kind {
1596 MemberKind::Constructor => out.push(format!("new {}", c.name)),
1597 MemberKind::Setter if documented_getter(m.name) => {}
1598 _ => out.push(format!("{}.{}", c.name, m.name)),
1599 }
1600 }
1601 }
1602 out
1603 }
1604
1605 pub(crate) fn make_type(
1608 &self,
1609 id: TypeId,
1610 ) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1611 self.types
1612 .values()
1613 .find(|t| t.id == id)
1614 .map(|t| (t.spec.clone(), (t.make)()))
1615 }
1616
1617 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1619 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
1620 }
1621}
1622
1623fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
1625 if old == new {
1626 format!("component `{name}` is registered twice{}", of_set(set))
1627 } else {
1628 format!(
1629 "two different types named `{name}` are registered{} (two versions of one crate?)",
1630 of_set(set)
1631 )
1632 }
1633}
1634
1635fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1637 if old == new {
1638 format!("module `{old}` is registered twice{}", of_set(set))
1639 } else {
1640 format!(
1641 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
1642 of_set(set)
1643 )
1644 }
1645}
1646
1647fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1649 if old == new {
1650 format!("class `{old}` is registered twice{}", of_set(set))
1651 } else {
1652 format!(
1653 "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
1654 of_set(set)
1655 )
1656 }
1657}
1658
1659fn of_set(set: Option<&str>) -> String {
1661 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1662}
1663
1664pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
1673 let specs = registry.specs();
1674 let modules = registry.module_specs();
1675 let classes = registry.class_specs();
1676 use std::fmt::Write as _;
1677 let mut out = String::new();
1678 let doc = |out: &mut String, indent: &str, doc: &str| {
1679 if !doc.is_empty() {
1680 let _ = writeln!(out, "{indent}/** {doc} */");
1681 }
1682 };
1683 let mut types = TsTypes::default();
1685 for spec in &specs {
1686 types.merge(&spec.types);
1687 }
1688 for m in &modules {
1689 types.merge(&m.types);
1690 }
1691 for c in &classes {
1692 types.merge(&c.types);
1693 }
1694 for declaration in types.declarations() {
1695 let _ = write!(out, "{declaration}\n\n");
1696 }
1697 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
1698 let signatures = |f: &FunctionSpec| {
1700 let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
1701 let params = params
1702 .iter()
1703 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1704 .collect::<Vec<_>>()
1705 .join(", ");
1706 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1707 let returns = if f.promises() {
1708 format!("Promise<{value}>")
1709 } else {
1710 value
1711 };
1712 (params, returns)
1713 };
1714 if f.overloads.is_empty() {
1715 vec![one(&f.params, &f.returns)]
1716 } else {
1717 f.overloads
1718 .iter()
1719 .map(|(params, returns)| one(params, returns))
1720 .collect()
1721 }
1722 };
1723 let module_object = |out: &mut String, m: &ModuleSpec| {
1725 out.push_str("{\n");
1726 for f in &m.functions {
1727 for (params, returns) in signatures(f) {
1728 doc(out, " ", f.doc);
1729 if f.getter {
1730 let _ = writeln!(out, " readonly {}: {returns};", f.name);
1731 continue;
1732 }
1733 let _ = writeln!(out, " {}({params}): {returns};", f.name);
1734 }
1735 }
1736 for constant in &m.constants {
1737 doc(out, " ", constant.doc);
1738 let _ = writeln!(
1739 out,
1740 " readonly {}: {};",
1741 constant.name,
1742 constant.value.ts_type()
1743 );
1744 }
1745 out.push('}');
1746 };
1747 for spec in &specs {
1748 let (generic, params, extends) = match spec.items() {
1752 Some(_) => ("<T>", "<T>", ", ListItemsProps<T>"),
1753 None if spec.generic => ("<T>", "<T = any>", ""),
1754 None => ("", "", ""),
1755 };
1756 let mut omit: Vec<&str> = HOST_PROPS
1759 .iter()
1760 .copied()
1761 .filter(|&h| !spec.host_props().any(|p| p == h))
1762 .collect();
1763 if !spec.methods.is_empty() {
1764 omit.insert(0, "ref");
1765 }
1766 let host = if omit.is_empty() {
1767 "ComponentHostProps".to_owned()
1768 } else {
1769 let names = omit.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>();
1770 format!("Omit<ComponentHostProps, {}>", names.join(" | "))
1771 };
1772 if !spec.methods.is_empty() {
1773 let _ = write!(
1774 out,
1775 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: ViewRef;\n",
1776 spec.export
1777 );
1778 for m in &spec.methods {
1779 doc(&mut out, " ", m.doc);
1780 let params = m
1781 .params
1782 .iter()
1783 .map(|(n, ts, optional)| {
1784 format!("{n}{}: {ts}", if *optional { "?" } else { "" })
1785 })
1786 .collect::<Vec<_>>()
1787 .join(", ");
1788 let returns = match &m.returns {
1789 Some(ts) => format!("Promise<{ts}>"),
1790 None => "void".to_owned(),
1791 };
1792 let _ = writeln!(out, " {}({params}): {returns};", m.name);
1793 }
1794 out.push_str("}\n\n");
1795 }
1796 let _ = writeln!(
1797 out,
1798 "export interface {}Props{params} extends {host}{extends} {{",
1799 spec.export
1800 );
1801 if !spec.methods.is_empty() {
1802 let _ = writeln!(
1803 out,
1804 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
1805 spec.export
1806 );
1807 }
1808 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
1809 doc(&mut out, " ", p.doc);
1810 let optional = if p.optional { "?" } else { "" };
1811 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
1812 }
1813 for e in &spec.events {
1814 doc(&mut out, " ", e.doc);
1815 let handler = handler_name(e.name);
1816 let arg = if e.data == "void" {
1817 String::new()
1818 } else {
1819 format!("{}: {}", e.arg, e.data)
1820 };
1821 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
1822 }
1823 out.push_str("}\n\n");
1824 if omit.contains(&spec.export.as_str()) {
1825 continue;
1826 }
1827 doc(&mut out, "", spec.doc);
1828 let mut with = String::new();
1830 if let Some(m) = module_of(&spec.export) {
1831 with.push_str(" & ");
1832 module_object(&mut with, m);
1833 }
1834 let _ = write!(
1835 out,
1836 "export declare const {}: ({params}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1837 spec.export, spec.export,
1838 );
1839 }
1840 for m in &modules {
1841 if specs.iter().any(|s| s.export == m.name)
1842 || (!m.flat && registry.function_members(m.name).is_some())
1843 {
1844 continue;
1845 }
1846 if m.flat {
1847 for f in m
1848 .functions
1849 .iter()
1850 .filter(|f| !f.getter && !omit.contains(&f.name))
1851 {
1852 for (params, returns) in signatures(f) {
1853 doc(&mut out, "", f.doc);
1854 let _ = writeln!(
1855 out,
1856 "export declare function {}({params}): {returns};",
1857 f.name
1858 );
1859 }
1860 if let Some(members) = registry.function_members(f.name) {
1862 let _ = writeln!(out, "export declare namespace {} {{", f.name);
1863 for member in &members.functions {
1864 for (params, returns) in signatures(member) {
1865 doc(&mut out, " ", member.doc);
1866 let _ = if member.getter {
1867 writeln!(out, " const {}: {returns};", member.name)
1868 } else {
1869 writeln!(out, " function {}({params}): {returns};", member.name)
1870 };
1871 }
1872 }
1873 for constant in &members.constants {
1874 doc(&mut out, " ", constant.doc);
1875 let _ = writeln!(
1876 out,
1877 " const {}: {};",
1878 constant.name,
1879 constant.value.ts_type()
1880 );
1881 }
1882 out.push_str("}\n");
1883 }
1884 out.push('\n');
1885 }
1886 for constant in &m.constants {
1887 if !omit.contains(&constant.name) {
1888 doc(&mut out, "", constant.doc);
1889 let _ = writeln!(
1890 out,
1891 "export declare const {}: {};\n",
1892 constant.name,
1893 constant.value.ts_type()
1894 );
1895 }
1896 }
1897 if m.default && !omit.contains(&"default") {
1898 let _ = write!(out, "declare const defaultExport: ");
1899 module_object(&mut out, m);
1900 for native in registry.native_value_names() {
1902 let _ = write!(out, " & {{ {native}: typeof {native} }}");
1903 }
1904 out.push_str(";\nexport default defaultExport;\n\n");
1905 }
1906 continue;
1907 }
1908 doc(&mut out, "", m.doc);
1909 let _ = write!(out, "export interface {}Module ", m.name);
1910 module_object(&mut out, m);
1911 out.push_str("\n\n");
1912 if !omit.contains(&m.name) {
1913 doc(&mut out, "", m.doc);
1914 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1915 }
1916 if m.default && !omit.contains(&"default") {
1917 let _ = write!(
1918 out,
1919 "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
1920 m.name
1921 );
1922 }
1923 }
1924 for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
1925 class_declaration(&mut out, c);
1926 }
1927 out
1928}
1929
1930fn class_declaration(out: &mut String, c: &ClassSpec) {
1932 use std::fmt::Write as _;
1933 let doc = |out: &mut String, indent: &str, doc: &str| {
1934 if !doc.is_empty() {
1935 let _ = writeln!(out, "{indent}/** {doc} */");
1936 }
1937 };
1938 doc(out, "", c.doc);
1939 if c.def.interface {
1940 let _ = writeln!(out, "export interface {} {{", c.name);
1942 for m in &c.members {
1943 let params = m
1944 .params
1945 .iter()
1946 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1947 .collect::<Vec<_>>()
1948 .join(", ");
1949 let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
1950 let returns = if m.is_async {
1951 format!("Promise<{value}>")
1952 } else {
1953 value
1954 };
1955 doc(out, " ", m.doc);
1956 let has_setter = |name| {
1957 c.members
1958 .iter()
1959 .any(|s| s.kind == MemberKind::Setter && s.name == name)
1960 };
1961 let _ = match m.kind {
1962 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1963 MemberKind::Getter if has_setter(m.name) => {
1964 writeln!(out, " {}: {returns};", m.name)
1965 }
1966 MemberKind::Getter => writeln!(out, " readonly {}: {returns};", m.name),
1967 _ => Ok(()),
1970 };
1971 }
1972 out.push_str("}\n\n");
1973 return;
1974 }
1975 let _ = writeln!(out, "export declare class {} {{", c.name);
1976 if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
1977 out.push_str(" /** Made by the class's members only. */\n private constructor();\n");
1978 }
1979 let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
1980 let params = params
1981 .iter()
1982 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1983 .collect::<Vec<_>>()
1984 .join(", ");
1985 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1986 let returns = if m.is_async {
1987 format!("Promise<{value}>")
1988 } else {
1989 value
1990 };
1991 (params, returns)
1992 };
1993 for m in &c.members {
1994 if !m.overloads.is_empty() {
1995 for (params, returns) in &m.overloads {
1996 doc(out, " ", m.doc);
1997 let (params, returns) = one(m, params, returns);
1998 let _ = match m.kind {
1999 MemberKind::Static => {
2000 writeln!(out, " static {}({params}): {returns};", m.name)
2001 }
2002 _ => writeln!(out, " {}({params}): {returns};", m.name),
2003 };
2004 }
2005 continue;
2006 }
2007 doc(out, " ", m.doc);
2008 let (params, returns) = one(m, &m.params, &m.returns);
2009 let _ = match m.kind {
2010 MemberKind::Constructor => writeln!(out, " constructor({params});"),
2011 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
2012 MemberKind::Getter => writeln!(out, " get {}(): {returns};", m.name),
2013 MemberKind::Setter => writeln!(out, " set {}({params});", m.name),
2014 MemberKind::Static => writeln!(out, " static {}({params}): {returns};", m.name),
2015 };
2016 }
2017 out.push_str(
2018 " /** Frees the Rust value now (else when the object is collected); the object throws after. */\n dispose(): void;\n [Symbol.dispose](): void;\n}\n\n",
2019 );
2020}
2021
2022fn handler_name(event: &str) -> String {
2024 let mut chars = event.chars();
2025 match chars.next() {
2026 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
2027 None => "on".to_owned(),
2028 }
2029}
2030
2031#[cfg(test)]
2032mod tests {
2033 use super::*;
2034 use crate::prelude::*;
2035
2036 #[test]
2037 fn by_name_marker_names_the_stand_in_make() {
2038 let name = std::any::type_name_of_val(&missing_instance);
2039 assert!(
2040 name.ends_with(&format!("::{BY_NAME_MARKER}")),
2041 "{name} is not {BY_NAME_MARKER}: update nsh-cli's by-name detection"
2042 );
2043 }
2044
2045 #[component]
2046 fn ByName() -> impl IntoElement {
2047 text("by name")
2048 }
2049
2050 #[test]
2051 fn a_component_made_by_name_has_the_marked_make() {
2052 let mut element = crate::element::ComponentElement::<ByName>::named(());
2053 let crate::element::ElKind::Component(c) = &element.node().kind else {
2054 panic!("not a component element");
2055 };
2056 assert!(std::ptr::fn_addr_eq(
2057 c.make,
2058 missing_instance as fn() -> Box<dyn AnyInstance>
2059 ));
2060 }
2061
2062 #[derive(Default)]
2063 struct Stepper;
2064
2065 #[derive(Clone, PartialEq, Props)]
2067 struct StepperProps {
2068 value: f64,
2070 #[prop(default)]
2071 size: StepperSize,
2072 max_value: Option<f64>,
2073 label: Option<Slot>,
2075 children: Children,
2076 }
2077
2078 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
2079 enum StepperSize {
2080 #[default]
2081 Regular,
2082 ExtraLarge,
2083 }
2084
2085 #[derive(Event)]
2086 enum StepperEvent {
2087 Change {
2089 new_value: f64,
2090 },
2091 #[args(limit)]
2092 Limit(u32),
2093 Reset,
2094 }
2095
2096 struct StepperApi;
2097
2098 #[methods]
2099 impl StepperApi {
2100 pub(crate) fn jump_to(&self, value: f64) {
2102 let _ = value;
2103 }
2104
2105 pub(crate) fn value(&self) -> f64 {
2106 0.0
2107 }
2108
2109 #[allow(dead_code)]
2111 fn clamp(&self, value: f64) -> f64 {
2112 value
2113 }
2114 }
2115
2116 impl Component for Stepper {
2117 type Props = StepperProps;
2118 type Event = StepperEvent;
2119 const METHODS: Methods = Methods::of::<StepperApi>();
2120 const DOC: &'static str = "Picks a number.";
2121
2122 fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
2123 view()
2124 }
2125 }
2126
2127 #[test]
2128 fn the_declarations_come_from_the_types() {
2129 let mut registry = Registry::new();
2130 registry.register::<Stepper>();
2131 let ts = declarations(®istry, &[]);
2132 for line in [
2133 " /** The value. */\n value: number;",
2134 "export type StepperSize = \"regular\" | \"extraLarge\";",
2135 " size?: StepperSize;",
2136 " maxValue?: number | null;",
2137 " /** Above the control. */\n label?: JSX.Element;",
2138 " children?: JSX.Element;",
2139 " /** The value changed. */\n onChange?: (event: { newValue: number }) => void;",
2140 " onLimit?: (event: { limit: number }) => void;",
2141 " onReset?: () => void;",
2142 "/** Picks a number. */",
2143 "export interface StepperRef {",
2144 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
2145 " value(): Promise<number>;",
2146 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
2147 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
2148 ] {
2149 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
2150 }
2151 assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
2152 assert_eq!(StepperApi::METHODS.len(), 2);
2153 let mut props = StepperProps::initial();
2154 let size = |json| {
2155 let specs = StepperProps::spec(&mut TsTypes::default());
2156 let decode = specs
2157 .iter()
2158 .find(|p| p.name == "size")
2159 .unwrap()
2160 .decode
2161 .unwrap();
2162 super::super::json_host::decode(decode, json)
2163 };
2164 assert!(
2165 props
2166 .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
2167 .unwrap()
2168 );
2169 assert!(props.size == StepperSize::ExtraLarge);
2170 assert!(size(serde_json::json!("huge")).is_err());
2174 assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
2175 assert!(props.set("size", None).unwrap());
2176 assert!(props.size == StepperSize::Regular);
2177 let data = |e: &StepperEvent| super::super::json_host::event_data(e);
2178 assert_eq!(
2179 data(&StepperEvent::Change { new_value: 2.5 }),
2180 Some(serde_json::json!({ "newValue": 2.5 }))
2181 );
2182 assert_eq!(
2183 data(&StepperEvent::Limit(3)),
2184 Some(serde_json::json!({ "limit": 3 }))
2185 );
2186 assert_eq!(data(&StepperEvent::Reset), None);
2187 assert_eq!(StepperEvent::Reset.name(), "reset");
2188 }
2189
2190 #[test]
2191 fn exports_without_docs_are_listed() {
2192 let mut registry = Registry::new();
2193 registry.register::<Stepper>();
2194 assert_eq!(
2197 registry.undocumented(),
2198 [
2199 "Stepper.size",
2200 "Stepper.maxValue",
2201 "Stepper.children",
2202 "Stepper.onLimit",
2203 "Stepper.onReset",
2204 "Stepper.value",
2205 ]
2206 );
2207 let mut r = Registry::ui_set("test/maker");
2208 r.module::<Maker>();
2209 assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
2210 }
2211
2212 #[crate::element::class]
2214 struct Lonely;
2215
2216 #[crate::element::class]
2217 impl Lonely {
2218 pub(crate) fn new() -> Self {
2219 Lonely
2220 }
2221 }
2222
2223 #[crate::element::module]
2225 struct Maker;
2226
2227 #[crate::element::module]
2228 impl Maker {
2229 pub(crate) fn make() -> Instance<Lonely> {
2230 Instance::new(Lonely)
2231 }
2232 }
2233
2234 #[test]
2235 fn the_classes_a_signature_names_are_registered_with_it() {
2236 let mut r = Registry::ui_set("test/maker");
2237 r.module::<Maker>();
2238 let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
2241 assert_eq!(names, ["Lonely"]);
2242 let ts = declarations(&r, &[]);
2243 assert!(ts.contains("export declare class Lonely"), "{ts}");
2244 assert!(ts.contains("make(): Lonely;"), "{ts}");
2245 r.class::<Lonely>();
2247 assert_eq!(r.class_specs().len(), 1);
2248 let _ = Registry::merged(&[r]);
2249 }
2250
2251 #[crate::element::module]
2253 struct Checks;
2254
2255 #[crate::element::module(flat)]
2256 impl Checks {
2257 pub(crate) fn check(name: String) {
2259 let _ = name;
2260 }
2261 }
2262
2263 #[crate::element::module]
2265 struct CheckVariants;
2266
2267 #[crate::element::module(name = "check")]
2268 impl CheckVariants {
2269 pub(crate) const COUNT: u32 = 2;
2271
2272 pub(crate) fn skip(name: String) {
2274 let _ = name;
2275 }
2276
2277 pub(crate) fn todo(name: String) {
2278 let _ = name;
2279 }
2280 }
2281
2282 #[crate::element::module]
2284 struct Loose;
2285
2286 #[crate::element::module(name = "loose")]
2287 impl Loose {
2288 pub(crate) fn nothing() {}
2290 }
2291
2292 #[test]
2293 fn a_module_named_like_a_function_puts_its_functions_on_it() {
2294 let mut r = Registry::ui_set("test/checks");
2295 r.module::<Checks>()
2296 .module::<CheckVariants>()
2297 .module::<Loose>();
2298 assert_eq!(r.function_members("check").unwrap().name, "check");
2299 assert!(r.function_members("loose").is_none());
2300 let ts = declarations(&r, &[]);
2301 assert!(
2302 ts.contains(
2303 "/** Declares a check. */\n\
2304 export declare function check(name: string): void;\n\
2305 export declare namespace check {\n \
2306 /** Declares a check that does not run. */\n \
2307 function skip(name: string): void;\n \
2308 function todo(name: string): void;\n \
2309 /** How many variants there are. */\n \
2310 const COUNT: number;\n}\n"
2311 ),
2312 "{ts}"
2313 );
2314 assert!(
2315 !ts.contains("CheckVariants") && !ts.contains("checkModule"),
2316 "{ts}"
2317 );
2318 assert!(
2319 ts.contains("export declare const loose: looseModule;"),
2320 "{ts}"
2321 );
2322 assert_eq!(r.undocumented(), ["check.todo"]);
2324 let described = super::super::description::SetDescription::of(&r).unwrap();
2325 let exports: Vec<_> = described
2326 .exports
2327 .iter()
2328 .map(|e| (e.name.as_str(), e.kind))
2329 .collect();
2330 assert_eq!(
2331 exports,
2332 [
2333 ("check", super::super::description::ExportKind::Function),
2334 ("loose", super::super::description::ExportKind::Module)
2335 ]
2336 );
2337 }
2338
2339 mod clash {
2340 #[crate::element::class]
2342 pub(super) struct Lonely;
2343
2344 #[crate::element::class]
2345 impl Lonely {
2346 pub(super) fn new() -> Self {
2347 Lonely
2348 }
2349 }
2350 }
2351
2352 #[test]
2353 fn a_clash_through_a_signature_names_both_types() {
2354 let mut r = Registry::ui_set("test/maker");
2355 r.class::<clash::Lonely>();
2356 let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2358 r.module::<Maker>();
2359 }))
2360 .unwrap_err();
2361 let message = failed.downcast_ref::<String>().unwrap();
2362 assert!(
2363 message.contains("`nsh_core::element::component::tests::clash::Lonely`")
2364 && message.contains("`nsh_core::element::component::tests::Lonely`"),
2365 "{message}"
2366 );
2367 }
2368
2369 #[test]
2370 fn components_are_named_after_their_types() {
2371 let mut registry = Registry::ui_set("test/ui");
2372 registry.register::<Stepper>();
2373 let specs = registry.specs();
2374 assert_eq!(
2375 specs[0].name,
2376 "nsh_core::element::component::tests::Stepper"
2377 );
2378 assert_eq!(specs[0].export, "Stepper");
2379 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
2380 assert_eq!(export_name("Bare"), "Bare");
2381 }
2382
2383 mod other {
2384 use crate::prelude::*;
2385
2386 #[derive(Default)]
2388 pub(super) struct Stepper;
2389
2390 impl Component for Stepper {
2391 type Props = ();
2392 type Event = NoEvent;
2393
2394 fn view(_: (), _: crate::element::Scope<NoEvent>) -> impl IntoElement {
2395 view()
2396 }
2397 }
2398 }
2399
2400 #[test]
2401 #[should_panic(
2402 expected = "components `nsh_core::element::component::tests::Stepper` and `nsh_core::element::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
2403 )]
2404 fn two_components_of_one_set_cannot_share_an_export() {
2405 Registry::ui_set("test/ui")
2406 .register::<Stepper>()
2407 .register::<other::Stepper>();
2408 }
2409
2410 #[test]
2411 #[should_panic(
2412 expected = "component `nsh_core::element::component::tests::Stepper` is registered twice"
2413 )]
2414 fn a_component_is_registered_once() {
2415 Registry::new().register::<Stepper>().register::<Stepper>();
2416 }
2417
2418 #[test]
2421 fn a_sets_submodules_come_with_it() {
2422 let mut sub = Registry::ui_set("test/set/sub");
2423 sub.register::<Stepper>();
2424 let mut set = Registry::ui_set("test/set");
2425 set.submodule(sub);
2426 let specifiers: Vec<_> = set.sets().iter().map(|s| s.specifier()).collect();
2427 assert_eq!(specifiers, [Some("test/set"), Some("test/set/sub")]);
2428 assert_eq!(Registry::merged(&[set]).specs().len(), 1);
2429 let elsewhere = std::panic::catch_unwind(|| {
2431 Registry::ui_set("test/set").submodule(Registry::ui_set("test/settings"));
2432 });
2433 assert!(elsewhere.is_err());
2434 }
2435
2436 #[test]
2437 fn sets_may_share_exports_but_not_components() {
2438 let mut a = Registry::ui_set("test/a");
2439 a.register::<Stepper>();
2440 let mut b = Registry::ui_set("test/b");
2441 b.register::<other::Stepper>();
2442 let merged = Registry::merged(&[a.clone(), b]);
2443 assert_eq!(merged.specs().len(), 2);
2444 let twice = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2445 Registry::merged(&[a.clone(), a])
2446 }));
2447 let message = *twice.unwrap_err().downcast::<String>().unwrap();
2448 assert_eq!(
2449 message,
2450 "component `nsh_core::element::component::tests::Stepper` is registered twice, by two UI sets"
2451 );
2452 }
2453
2454 struct NoFake;
2455
2456 impl crate::fake::Fake for NoFake {
2457 fn install(&self) {}
2458
2459 fn call(&self, _: &str, _: &[crate::JsonValue]) -> Result<crate::JsonValue, String> {
2460 Ok(crate::JsonValue::Null)
2461 }
2462 }
2463
2464 #[test]
2466 fn fake_names_are_unique_across_sets() {
2467 let mut a = Registry::ui_set("test/a");
2468 a.fake("test/mic", Arc::new(NoFake));
2469 let mut b = Registry::ui_set("test/b");
2470 b.fake("test/camera", Arc::new(NoFake));
2471 let names: Vec<_> = Registry::merged(&[a.clone(), b])
2472 .fakes()
2473 .into_iter()
2474 .map(|(name, _)| name)
2475 .collect();
2476 assert_eq!(names, ["test/mic", "test/camera"]);
2477 let mut c = Registry::ui_set("test/c");
2478 c.fake("test/mic", Arc::new(NoFake));
2479 let twice =
2480 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| Registry::merged(&[a, c])));
2481 let message = *twice.unwrap_err().downcast::<String>().unwrap();
2482 assert_eq!(message, "two fakes are named `test/mic`, by two UI sets");
2483 }
2484}
2485
2486#[cfg(test)]
2487mod root_tests {
2488 use super::Root;
2489 use crate::{access::Capabilities, prelude::*};
2490
2491 #[component]
2492 fn Empty() -> impl IntoElement {
2493 view()
2494 }
2495
2496 #[test]
2497 fn a_root_reads_its_declared_capabilities_as_packages_are_read() {
2498 assert_eq!(Root::of::<Empty>().capabilities_ref(), None);
2499 let root = Root::of::<Empty>().capabilities_json(r#"{"clipboard":true,"bluetooth":true}"#);
2501 let expected = Capabilities {
2502 clipboard: true,
2503 ..Capabilities::default()
2504 };
2505 assert_eq!(root.capabilities_ref(), Some(&expected));
2506 let root = Root::of::<Empty>().capabilities_json("not json");
2508 assert_eq!(root.capabilities_ref(), Some(&Capabilities::default()));
2509 }
2510}