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
406type 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 #[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 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 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 pub fn takes_children(&self) -> bool {
468 self.props.iter().any(|p| p.kind == PropKind::Children)
469 }
470
471 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 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
488pub(crate) fn name_of<C: Component>() -> &'static str {
492 std::any::type_name::<C>()
493}
494
495fn 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
502pub(crate) trait AnyInstance {
504 fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
505 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 fn cleanup(&mut self);
511 fn view(&mut self) -> ElNode;
513 fn name(&self) -> &'static str;
515 fn call(&mut self, call: MethodCall) -> Option<JsResult>;
518 fn owner(&self) -> Option<super::Owner>;
520 fn failure_owner(&self) -> super::Owner;
523 fn adopt(&mut self, parent: super::Owner);
527 fn place(&mut self, host: crate::NodeId, parent: super::Owner);
529}
530
531#[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 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 pub fn app_id(mut self, id: impl Into<String>) -> Self {
560 self.app_id = Some(id.into());
561 self
562 }
563
564 pub fn app_id_ref(&self) -> Option<&str> {
566 self.app_id.as_deref()
567 }
568
569 pub fn tokens(mut self, tokens: super::Tokens) -> Self {
572 self.tokens = Some(Arc::new(tokens));
573 self
574 }
575
576 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
579 self.fonts.push(data.into());
580 self
581 }
582
583 pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
587 self.appearance = Some(appearance);
588 self
589 }
590
591 pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
594 self.status_bar = Some(setting);
595 self
596 }
597
598 pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
600 self.status_bar
601 }
602
603 pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
606 self.appearance
607 }
608
609 pub fn tokens_ref(&self) -> Option<&super::Tokens> {
611 self.tokens.as_deref()
612 }
613
614 pub fn fonts(&self) -> &[Arc<[u8]>] {
616 &self.fonts
617 }
618
619 pub fn of<C: Component>() -> Self
621 where
622 C::Props: Default,
623 {
624 Self::new::<C>(C::Props::default)
625 }
626
627 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
639pub(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 id: TypeId,
650}
651
652#[derive(Clone)]
653struct ModuleType {
654 spec: Arc<ModuleSpec>,
655 type_name: &'static str,
657}
658
659#[derive(Clone)]
660struct ClassType {
661 spec: Arc<ClassSpec>,
662 type_name: &'static str,
664}
665
666#[derive(Debug, Clone, Default)]
669#[non_exhaustive]
670pub struct BuiltInScrollbar {
671 pub target: crate::NodeId,
673 pub horizontal: bool,
675 pub theme: Option<Arc<crate::JsonValue>>,
678 pub app_theme: Option<super::AnyValue>,
681}
682
683pub type ScrollbarSource = fn(&BuiltInScrollbar) -> Option<super::AnyElement>;
688
689#[derive(Clone, Default)]
692pub struct Registry {
693 types: Arc<FxHashMap<&'static str, ComponentType>>,
694 modules: Arc<FxHashMap<&'static str, ModuleType>>,
695 classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
698 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
700 native_values: Arc<Vec<&'static str>>,
703 namespace: Option<&'static str>,
706 ui_set: Option<&'static str>,
708 assets: Arc<Vec<&'static [super::AssetFile]>>,
710 tokens: Option<super::TokenSource>,
712 scrollbars: Option<ScrollbarSource>,
714 submodules: Arc<Vec<Registry>>,
717 setups: Arc<Vec<Setup>>,
719}
720
721type 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 pub fn new() -> Self {
733 Self::default()
734 }
735
736 #[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 #[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 #[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 #[track_caller]
852 pub fn class<C: Class>(&mut self) -> &mut Self {
853 self.class_def(C::DEF)
854 }
855
856 #[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 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 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 #[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 pub fn ui_set(specifier: &'static str) -> Self {
940 Self {
941 ui_set: Some(specifier),
942 ..Self::default()
943 }
944 }
945
946 pub fn specifier(&self) -> Option<&'static str> {
949 self.ui_set.or(self.namespace)
950 }
951
952 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
955 (&self.reexports.0, &self.reexports.1)
956 }
957
958 #[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 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 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 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 pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
1016 self.tokens = Some(source);
1017 self
1018 }
1019
1020 pub fn scrollbars_from(&mut self, source: ScrollbarSource) -> &mut Self {
1025 self.scrollbars = Some(source);
1026 self
1027 }
1028
1029 pub(crate) fn scrollbar_source(&self) -> Option<ScrollbarSource> {
1032 self.scrollbars
1033 }
1034
1035 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 pub(crate) fn run_setups(&self) {
1050 for setup in self.setups.iter() {
1051 setup();
1052 }
1053 }
1054
1055 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 pub fn tokens(&self, json: Option<&str>) -> Option<Result<super::Tokens, String>> {
1073 self.tokens.map(|source| source(json))
1074 }
1075
1076 pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
1078 self.tokens
1079 }
1080
1081 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
1083 self.assets.iter().flat_map(|files| files.iter())
1084 }
1085
1086 pub fn native_value_names(&self) -> &[&'static str] {
1088 &self.native_values
1089 }
1090
1091 pub(crate) fn runtime(namespace: &'static str) -> Self {
1093 Self {
1094 namespace: Some(namespace),
1095 ..Self::default()
1096 }
1097 }
1098
1099 pub fn namespace(&self) -> Option<&'static str> {
1102 self.namespace
1103 }
1104
1105 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 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 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 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 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 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
1213fn 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
1225fn 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
1237fn 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
1249fn of_set(set: Option<&str>) -> String {
1251 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1252}
1253
1254pub 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 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 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 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 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 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 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 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 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
1508fn 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 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 _ => 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
1600fn 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 #[derive(Clone, PartialEq, Props)]
1619 struct StepperProps {
1620 value: f64,
1622 #[prop(default)]
1623 size: StepperSize,
1624 max_value: Option<f64>,
1625 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 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 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 #[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(®istry, &[]);
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 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 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 #[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 #[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 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 r.class::<Lonely>();
1799 assert_eq!(r.class_specs().len(), 1);
1800 let _ = Registry::merged(&[r]);
1801 }
1802
1803 #[crate::element::module]
1805 struct Checks;
1806
1807 #[crate::element::module(flat)]
1808 impl Checks {
1809 pub(crate) fn check(name: String) {
1811 let _ = name;
1812 }
1813 }
1814
1815 #[crate::element::module]
1817 struct CheckVariants;
1818
1819 #[crate::element::module(name = "check")]
1820 impl CheckVariants {
1821 pub(crate) const COUNT: u32 = 2;
1823
1824 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 #[crate::element::module]
1836 struct Loose;
1837
1838 #[crate::element::module(name = "loose")]
1839 impl Loose {
1840 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 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 #[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 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 #[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 #[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 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}