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,
264 pub doc: &'static str,
266 pub spread: bool,
270}
271
272pub trait Props: Clone + PartialEq + 'static {
274 #[doc(hidden)]
276 const ITEMS: Option<&'static str> = None;
277
278 #[doc(hidden)]
281 const LAZY_CHILDREN: bool = false;
282
283 #[doc(hidden)]
287 const GENERIC: bool = false;
288
289 fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
291
292 fn initial() -> Self;
294
295 fn set(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
298
299 fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
301
302 fn set_children(&mut self, children: Children) -> bool;
304
305 #[doc(hidden)]
308 fn held(&self) -> Self {
309 self.clone()
310 }
311
312 #[doc(hidden)]
316 fn update_from(&mut self, new: &Self) -> bool {
317 if self == new {
318 return false;
319 }
320 *self = new.clone();
321 true
322 }
323}
324
325impl Props for () {
327 fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
328 Vec::new()
329 }
330
331 fn initial() -> Self {}
332
333 fn set(&mut self, name: &str, _: Option<AnyValue>) -> Result<bool, PropError> {
334 Err(PropError(format!("unknown prop `{name}`")))
335 }
336
337 fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
338 false
339 }
340
341 fn set_children(&mut self, _: Children) -> bool {
342 false
343 }
344}
345
346pub trait Event: 'static {
353 fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
355
356 fn name(&self) -> &'static str;
358
359 fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
361
362 fn spread(&self) -> bool {
365 false
366 }
367}
368
369#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub enum NoEvent {}
372
373impl Event for NoEvent {
374 fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
375 Vec::new()
376 }
377
378 fn name(&self) -> &'static str {
379 match *self {}
380 }
381
382 fn data_js<'a>(&self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
383 match *self {}
384 }
385}
386
387#[derive(Debug, Clone)]
390pub struct ComponentSpec {
391 pub name: &'static str,
394 pub export: String,
396 pub doc: &'static str,
398 pub props: Vec<PropSpec>,
400 pub events: Vec<EventSpec>,
402 pub methods: Vec<MethodSpec>,
404 pub types: TsTypes,
406 pub lazy_children: bool,
410 pub generic: bool,
413}
414
415impl ComponentSpec {
416 pub(crate) fn of<C: Component>() -> Self {
417 let mut types = TsTypes::default();
418 let props = C::Props::spec(&mut types);
419 let events = C::Event::spec(&mut types);
420 let methods = (C::METHODS.specs)(&mut types);
421 let name = name_of::<C>();
422 Self {
423 name,
424 export: export_name(name).to_owned(),
425 doc: C::DOC,
426 props,
427 events,
428 methods,
429 types,
430 lazy_children: C::Props::LAZY_CHILDREN,
431 generic: C::Props::GENERIC,
432 }
433 }
434
435 pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
437 self.props
438 .iter()
439 .filter(|p| p.kind == PropKind::Slot)
440 .map(|p| p.name)
441 }
442
443 pub fn renderers(&self) -> impl Iterator<Item = &'static str> + '_ {
445 self.props
446 .iter()
447 .filter(|p| p.kind == PropKind::Renderer)
448 .map(|p| p.name)
449 }
450
451 pub fn takes_children(&self) -> bool {
453 self.props.iter().any(|p| p.kind == PropKind::Children)
454 }
455
456 pub fn items(&self) -> Option<&'static str> {
458 self.props
459 .iter()
460 .find(|p| p.kind == PropKind::Items)
461 .map(|p| p.name)
462 }
463
464 pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
466 self.props
467 .iter()
468 .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
469 .map(|p| p.name)
470 }
471}
472
473pub(crate) fn name_of<C: Component>() -> &'static str {
477 std::any::type_name::<C>()
478}
479
480fn export_name(type_name: &str) -> &str {
483 let path = type_name.split('<').next().unwrap_or(type_name);
484 path.rsplit("::").next().unwrap_or(path)
485}
486
487pub(crate) trait AnyInstance {
489 fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
490 fn set_props(&mut self, props: &dyn Any);
492 fn set_slot(&mut self, name: &'static str, filled: bool);
493 fn set_children(&mut self, present: bool);
494 fn cleanup(&mut self);
496 fn view(&mut self) -> ElNode;
498 fn name(&self) -> &'static str;
500 fn call(&mut self, call: MethodCall) -> Option<JsResult>;
503 fn owner(&self) -> Option<super::Owner>;
505 fn failure_owner(&self) -> super::Owner;
508 fn adopt(&mut self, parent: super::Owner);
512 fn place(&mut self, host: crate::NodeId, parent: super::Owner);
514}
515
516#[derive(Clone)]
520pub struct Root {
521 make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
522 tokens: Option<Arc<super::Tokens>>,
523 fonts: Vec<Arc<[u8]>>,
524 appearance: Option<crate::platform::Appearance>,
525 app_id: Option<String>,
526 status_bar: Option<crate::StatusBarSetting>,
527}
528
529impl Root {
530 pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
532 Self {
533 make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
534 tokens: None,
535 fonts: Vec::new(),
536 appearance: None,
537 app_id: None,
538 status_bar: None,
539 }
540 }
541
542 pub fn app_id(mut self, id: impl Into<String>) -> Self {
545 self.app_id = Some(id.into());
546 self
547 }
548
549 pub fn app_id_ref(&self) -> Option<&str> {
551 self.app_id.as_deref()
552 }
553
554 pub fn tokens(mut self, tokens: super::Tokens) -> Self {
557 self.tokens = Some(Arc::new(tokens));
558 self
559 }
560
561 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
564 self.fonts.push(data.into());
565 self
566 }
567
568 pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
572 self.appearance = Some(appearance);
573 self
574 }
575
576 pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
579 self.status_bar = Some(setting);
580 self
581 }
582
583 pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
585 self.status_bar
586 }
587
588 pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
591 self.appearance
592 }
593
594 pub fn tokens_ref(&self) -> Option<&super::Tokens> {
596 self.tokens.as_deref()
597 }
598
599 pub fn fonts(&self) -> &[Arc<[u8]>] {
601 &self.fonts
602 }
603
604 pub fn of<C: Component>() -> Self
606 where
607 C::Props: Default,
608 {
609 Self::new::<C>(C::Props::default)
610 }
611
612 pub(crate) fn element(&self) -> super::AnyElement {
614 (self.make)()
615 }
616}
617
618impl fmt::Debug for Root {
619 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620 f.write_str("Root")
621 }
622}
623
624pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
626 Box::new(super::once::OnceInstance::<C>::new())
627}
628
629#[derive(Clone)]
630struct ComponentType {
631 spec: Arc<ComponentSpec>,
632 make: fn() -> Box<dyn AnyInstance>,
633 id: TypeId,
635}
636
637#[derive(Clone)]
638struct ModuleType {
639 spec: Arc<ModuleSpec>,
640 type_name: &'static str,
642}
643
644#[derive(Clone)]
645struct ClassType {
646 spec: Arc<ClassSpec>,
647 type_name: &'static str,
649}
650
651#[derive(Clone, Default)]
654pub struct Registry {
655 types: Arc<FxHashMap<&'static str, ComponentType>>,
656 modules: Arc<FxHashMap<&'static str, ModuleType>>,
657 classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
660 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
662 native_values: Arc<Vec<&'static str>>,
665 namespace: Option<&'static str>,
668 ui_set: Option<&'static str>,
670 assets: Arc<Vec<&'static [super::AssetFile]>>,
672 tokens: Option<super::TokenSource>,
674 submodules: Arc<Vec<Registry>>,
677 setups: Arc<Vec<Setup>>,
679}
680
681type Setup = Arc<dyn Fn() + Send + Sync>;
683
684impl fmt::Debug for Registry {
685 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
686 f.debug_set().entries(self.types.keys()).finish()
687 }
688}
689
690impl Registry {
691 pub fn new() -> Self {
693 Self::default()
694 }
695
696 #[track_caller]
705 pub fn register<C: Component>(&mut self) -> &mut Self {
706 let spec = ComponentSpec::of::<C>();
707 let types = Arc::make_mut(&mut self.types);
708 if let Some(old) = types.get(spec.name) {
709 let set = self.ui_set.or(self.namespace);
710 panic!("{}", same_name(spec.name, old.id, TypeId::of::<C>(), set));
711 }
712 if self.classes.keys().any(|(_, name)| *name == spec.export) {
713 panic!(
714 "component `{}` is exported as `{}` like a class{}: rename one",
715 spec.name,
716 spec.export,
717 of_set(self.ui_set.or(self.namespace)),
718 );
719 }
720 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
721 panic!(
722 "components `{}` and `{}` are both exported as `{}`{}: rename one",
723 other.spec.name,
724 spec.name,
725 spec.export,
726 of_set(self.ui_set.or(self.namespace)),
727 );
728 }
729 types.insert(
730 spec.name,
731 ComponentType {
732 spec: Arc::new(spec),
733 make: make_instance::<C>,
734 id: TypeId::of::<C>(),
735 },
736 );
737 let mut refs = Vec::new();
738 (C::METHODS.refs)(&mut refs);
739 self.classes_named(refs)
740 }
741
742 #[track_caller]
750 pub fn module<M: Module>(&mut self) -> &mut Self {
751 let type_name = std::any::type_name::<M>();
752 if self.classes.keys().any(|(_, name)| *name == M::NAME) {
753 panic!(
754 "module `{type_name}` is named `{}` like a class{}: rename one",
755 M::NAME,
756 of_set(self.ui_set.or(self.namespace))
757 );
758 }
759 let modules = Arc::make_mut(&mut self.modules);
760 if let Some(old) = modules.get(M::NAME) {
761 panic!(
762 "{}",
763 same_module(
764 M::NAME,
765 old.type_name,
766 type_name,
767 self.ui_set.or(self.namespace)
768 )
769 );
770 }
771 modules.insert(
772 M::NAME,
773 ModuleType {
774 spec: Arc::new(ModuleSpec::of::<M>()),
775 type_name,
776 },
777 );
778 let mut refs = Vec::new();
779 for f in M::FUNCTIONS {
780 (f.refs)(&mut refs);
781 }
782 self.classes_named(refs)
783 }
784
785 #[track_caller]
798 pub fn class<C: Class>(&mut self) -> &mut Self {
799 self.class_def(C::DEF)
800 }
801
802 #[track_caller]
805 fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
806 for def in refs {
807 self.class_def(def);
808 }
809 self
810 }
811
812 #[track_caller]
813 fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
814 let type_name = (def.type_name)();
815 let set = self.ui_set.or(self.namespace);
816 if let Some(old) = self.classes.get(&(set, def.name)) {
817 if (old.spec.def.type_id)() == (def.type_id)() {
818 return self;
819 }
820 panic!("{}", same_class(def.name, old.type_name, type_name, set));
821 }
822 if self.modules.contains_key(def.name)
823 || self.types.values().any(|t| t.spec.export == def.name)
824 {
825 panic!(
826 "class `{type_name}` is named `{}` like a module or a component{}: rename one",
827 def.name,
828 of_set(set)
829 );
830 }
831 Arc::make_mut(&mut self.classes).insert(
832 (set, def.name),
833 ClassType {
834 spec: Arc::new(ClassSpec::of(def)),
835 type_name,
836 },
837 );
838 let mut refs = Vec::new();
840 for m in def.members {
841 (m.refs)(&mut refs);
842 }
843 self.classes_named(refs)
844 }
845
846 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
849 let r = Arc::make_mut(&mut self.reexports);
850 r.0.extend_from_slice(values);
851 r.1.extend_from_slice(types);
852 self
853 }
854
855 #[track_caller]
866 pub fn merged(sets: &[Registry]) -> Self {
867 let mut out = Self::default();
868 for set in sets.iter().flat_map(Registry::sets) {
869 out.tokens = out.tokens.or(set.tokens);
870 Arc::make_mut(&mut out.setups).extend(set.setups.iter().cloned());
871 let types = Arc::make_mut(&mut out.types);
872 for (name, ty) in set.types.iter() {
873 if let Some(old) = types.insert(name, ty.clone()) {
874 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
875 }
876 }
877 }
878 out
879 }
880
881 pub fn ui_set(specifier: &'static str) -> Self {
885 Self {
886 ui_set: Some(specifier),
887 ..Self::default()
888 }
889 }
890
891 pub fn specifier(&self) -> Option<&'static str> {
894 self.ui_set.or(self.namespace)
895 }
896
897 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
900 (&self.reexports.0, &self.reexports.1)
901 }
902
903 #[track_caller]
915 pub fn submodule(&mut self, set: Registry) -> &mut Self {
916 let under = match (self.ui_set, set.ui_set) {
917 (Some(parent), Some(child)) => child
918 .strip_prefix(parent)
919 .is_some_and(|rest| rest.len() > 1 && rest.starts_with('/')),
920 _ => false,
921 };
922 assert!(
923 under,
924 "a submodule is a UI set under a path of its set's specifier: {:?} under {:?}",
925 set.ui_set, self.ui_set
926 );
927 Arc::make_mut(&mut self.submodules).push(set);
928 self
929 }
930
931 pub fn sets(&self) -> Vec<&Registry> {
935 let mut out = vec![self];
936 for sub in self.submodules.iter() {
937 out.extend(sub.sets());
938 }
939 out
940 }
941
942 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
945 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
946 self
947 }
948
949 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
954 Arc::make_mut(&mut self.assets).push(files);
955 self
956 }
957
958 pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
961 self.tokens = Some(source);
962 self
963 }
964
965 pub fn setup(&mut self, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
973 Arc::make_mut(&mut self.setups).push(Arc::new(f));
974 self
975 }
976
977 pub(crate) fn run_setups(&self) {
980 for setup in self.setups.iter() {
981 setup();
982 }
983 }
984
985 pub fn tokens(&self, json: Option<&str>) -> Option<Result<super::Tokens, String>> {
989 self.tokens.map(|source| source(json))
990 }
991
992 pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
994 self.tokens
995 }
996
997 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
999 self.assets.iter().flat_map(|files| files.iter())
1000 }
1001
1002 pub fn native_value_names(&self) -> &[&'static str] {
1004 &self.native_values
1005 }
1006
1007 pub(crate) fn runtime(namespace: &'static str) -> Self {
1009 Self {
1010 namespace: Some(namespace),
1011 ..Self::default()
1012 }
1013 }
1014
1015 pub fn namespace(&self) -> Option<&'static str> {
1018 self.namespace
1019 }
1020
1021 pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
1023 let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
1024 specs.sort_by_key(|s| s.name);
1025 specs
1026 }
1027
1028 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
1030 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
1031 specs.sort_by_key(|s| s.name);
1032 specs
1033 }
1034
1035 pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
1040 let exported = self.modules.values().any(|m| {
1041 m.spec.flat
1042 && m.spec
1043 .functions
1044 .iter()
1045 .any(|f| !f.getter && f.name == function)
1046 });
1047 exported
1048 .then(|| {
1049 self.modules
1050 .values()
1051 .find(|m| !m.spec.flat && m.spec.name == function)
1052 .map(|m| m.spec.clone())
1053 })
1054 .flatten()
1055 }
1056
1057 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
1059 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
1060 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
1061 specs
1062 }
1063
1064 pub fn undocumented(&self) -> Vec<String> {
1073 let mut out = Vec::new();
1074 let specs = self.specs();
1075 for c in &specs {
1076 if c.doc.is_empty() {
1077 out.push(c.export.clone());
1078 }
1079 for p in c.props.iter().filter(|p| p.doc.is_empty()) {
1080 out.push(format!("{}.{}", c.export, p.name));
1081 }
1082 for e in c.events.iter().filter(|e| e.doc.is_empty()) {
1083 out.push(format!("{}.{}", c.export, handler_name(e.name)));
1084 }
1085 for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
1086 out.push(format!("{}.{}", c.export, m.name));
1087 }
1088 }
1089 for m in self.module_specs() {
1090 let merged = specs.iter().any(|c| c.export == m.name)
1091 || (!m.flat && self.function_members(m.name).is_some());
1092 if m.doc.is_empty() && !merged && !m.flat {
1093 out.push(m.name.to_owned());
1094 }
1095 for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
1096 out.push(if m.flat {
1097 f.name.to_owned()
1098 } else {
1099 format!("{}.{}", m.name, f.name)
1100 });
1101 }
1102 }
1103 for c in self.class_specs() {
1104 if c.doc.is_empty() {
1105 out.push(c.name.to_owned());
1106 }
1107 let documented_getter = |name: &str| {
1108 c.members
1109 .iter()
1110 .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
1111 };
1112 for m in c.members.iter().filter(|m| m.doc.is_empty()) {
1113 match m.kind {
1114 MemberKind::Constructor => out.push(format!("new {}", c.name)),
1115 MemberKind::Setter if documented_getter(m.name) => {}
1116 _ => out.push(format!("{}.{}", c.name, m.name)),
1117 }
1118 }
1119 }
1120 out
1121 }
1122
1123 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1125 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
1126 }
1127}
1128
1129fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
1131 if old == new {
1132 format!("component `{name}` is registered twice{}", of_set(set))
1133 } else {
1134 format!(
1135 "two different types named `{name}` are registered{} (two versions of one crate?)",
1136 of_set(set)
1137 )
1138 }
1139}
1140
1141fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1143 if old == new {
1144 format!("module `{old}` is registered twice{}", of_set(set))
1145 } else {
1146 format!(
1147 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
1148 of_set(set)
1149 )
1150 }
1151}
1152
1153fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1155 if old == new {
1156 format!("class `{old}` is registered twice{}", of_set(set))
1157 } else {
1158 format!(
1159 "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
1160 of_set(set)
1161 )
1162 }
1163}
1164
1165fn of_set(set: Option<&str>) -> String {
1167 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1168}
1169
1170pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
1179 let specs = registry.specs();
1180 let modules = registry.module_specs();
1181 let classes = registry.class_specs();
1182 use std::fmt::Write as _;
1183 let mut out = String::new();
1184 let doc = |out: &mut String, indent: &str, doc: &str| {
1185 if !doc.is_empty() {
1186 let _ = writeln!(out, "{indent}/** {doc} */");
1187 }
1188 };
1189 let mut types = TsTypes::default();
1191 for spec in &specs {
1192 types.merge(&spec.types);
1193 }
1194 for m in &modules {
1195 types.merge(&m.types);
1196 }
1197 for c in &classes {
1198 types.merge(&c.types);
1199 }
1200 for declaration in types.declarations() {
1201 let _ = write!(out, "{declaration}\n\n");
1202 }
1203 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
1204 let signatures = |f: &FunctionSpec| {
1206 let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
1207 let params = params
1208 .iter()
1209 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1210 .collect::<Vec<_>>()
1211 .join(", ");
1212 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1213 let returns = if f.promises() {
1214 format!("Promise<{value}>")
1215 } else {
1216 value
1217 };
1218 (params, returns)
1219 };
1220 if f.overloads.is_empty() {
1221 vec![one(&f.params, &f.returns)]
1222 } else {
1223 f.overloads
1224 .iter()
1225 .map(|(params, returns)| one(params, returns))
1226 .collect()
1227 }
1228 };
1229 let module_object = |out: &mut String, m: &ModuleSpec| {
1231 out.push_str("{\n");
1232 for f in &m.functions {
1233 for (params, returns) in signatures(f) {
1234 doc(out, " ", f.doc);
1235 if f.getter {
1236 let _ = writeln!(out, " readonly {}: {returns};", f.name);
1237 continue;
1238 }
1239 let _ = writeln!(out, " {}({params}): {returns};", f.name);
1240 }
1241 }
1242 for constant in &m.constants {
1243 doc(out, " ", constant.doc);
1244 let _ = writeln!(
1245 out,
1246 " readonly {}: {};",
1247 constant.name,
1248 constant.value.ts_type()
1249 );
1250 }
1251 out.push('}');
1252 };
1253 for spec in &specs {
1254 let (generic, params, extends) = match spec.items() {
1258 Some(_) => ("<T>", "<T>", ", ListItemsProps<T>"),
1259 None if spec.generic => ("<T>", "<T = any>", ""),
1260 None => ("", "", ""),
1261 };
1262 let host = if spec.methods.is_empty() {
1264 "ComponentHostProps"
1265 } else {
1266 let _ = write!(
1267 out,
1268 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: YNode;\n",
1269 spec.export
1270 );
1271 for m in &spec.methods {
1272 doc(&mut out, " ", m.doc);
1273 let params = m
1274 .params
1275 .iter()
1276 .map(|(n, ts, optional)| {
1277 format!("{n}{}: {ts}", if *optional { "?" } else { "" })
1278 })
1279 .collect::<Vec<_>>()
1280 .join(", ");
1281 let returns = match &m.returns {
1282 Some(ts) => format!("Promise<{ts}>"),
1283 None => "void".to_owned(),
1284 };
1285 let _ = writeln!(out, " {}({params}): {returns};", m.name);
1286 }
1287 out.push_str("}\n\n");
1288 "Omit<ComponentHostProps, \"ref\">"
1289 };
1290 let _ = writeln!(
1291 out,
1292 "export interface {}Props{params} extends {host}{extends} {{",
1293 spec.export
1294 );
1295 if !spec.methods.is_empty() {
1296 let _ = writeln!(
1297 out,
1298 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
1299 spec.export
1300 );
1301 }
1302 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
1303 doc(&mut out, " ", p.doc);
1304 let optional = if p.optional { "?" } else { "" };
1305 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
1306 }
1307 for e in &spec.events {
1308 doc(&mut out, " ", e.doc);
1309 let handler = handler_name(e.name);
1310 let arg = if e.data == "void" {
1311 String::new()
1312 } else if e.spread {
1313 e.data.clone()
1314 } else {
1315 format!("{}: {}", e.arg, e.data)
1316 };
1317 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
1318 }
1319 out.push_str("}\n\n");
1320 if omit.contains(&spec.export.as_str()) {
1321 continue;
1322 }
1323 doc(&mut out, "", spec.doc);
1324 let mut with = String::new();
1326 if let Some(m) = module_of(&spec.export) {
1327 with.push_str(" & ");
1328 module_object(&mut with, m);
1329 }
1330 let _ = write!(
1331 out,
1332 "export declare const {}: ({params}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1333 spec.export, spec.export,
1334 );
1335 }
1336 for m in &modules {
1337 if specs.iter().any(|s| s.export == m.name)
1338 || (!m.flat && registry.function_members(m.name).is_some())
1339 {
1340 continue;
1341 }
1342 if m.flat {
1343 for f in m
1344 .functions
1345 .iter()
1346 .filter(|f| !f.getter && !omit.contains(&f.name))
1347 {
1348 for (params, returns) in signatures(f) {
1349 doc(&mut out, "", f.doc);
1350 let _ = writeln!(
1351 out,
1352 "export declare function {}({params}): {returns};",
1353 f.name
1354 );
1355 }
1356 if let Some(members) = registry.function_members(f.name) {
1358 let _ = writeln!(out, "export declare namespace {} {{", f.name);
1359 for member in &members.functions {
1360 for (params, returns) in signatures(member) {
1361 doc(&mut out, " ", member.doc);
1362 let _ = if member.getter {
1363 writeln!(out, " const {}: {returns};", member.name)
1364 } else {
1365 writeln!(out, " function {}({params}): {returns};", member.name)
1366 };
1367 }
1368 }
1369 for constant in &members.constants {
1370 doc(&mut out, " ", constant.doc);
1371 let _ = writeln!(
1372 out,
1373 " const {}: {};",
1374 constant.name,
1375 constant.value.ts_type()
1376 );
1377 }
1378 out.push_str("}\n");
1379 }
1380 out.push('\n');
1381 }
1382 for constant in &m.constants {
1383 if !omit.contains(&constant.name) {
1384 doc(&mut out, "", constant.doc);
1385 let _ = writeln!(
1386 out,
1387 "export declare const {}: {};\n",
1388 constant.name,
1389 constant.value.ts_type()
1390 );
1391 }
1392 }
1393 if m.default && !omit.contains(&"default") {
1394 let _ = write!(out, "declare const defaultExport: ");
1395 module_object(&mut out, m);
1396 for native in registry.native_value_names() {
1398 let _ = write!(out, " & {{ {native}: typeof {native} }}");
1399 }
1400 out.push_str(";\nexport default defaultExport;\n\n");
1401 }
1402 continue;
1403 }
1404 doc(&mut out, "", m.doc);
1405 let _ = write!(out, "export interface {}Module ", m.name);
1406 module_object(&mut out, m);
1407 out.push_str("\n\n");
1408 if !omit.contains(&m.name) {
1409 doc(&mut out, "", m.doc);
1410 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1411 }
1412 if m.default && !omit.contains(&"default") {
1413 let _ = write!(
1414 out,
1415 "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
1416 m.name
1417 );
1418 }
1419 }
1420 for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
1421 class_declaration(&mut out, c);
1422 }
1423 out
1424}
1425
1426fn class_declaration(out: &mut String, c: &ClassSpec) {
1428 use std::fmt::Write as _;
1429 let doc = |out: &mut String, indent: &str, doc: &str| {
1430 if !doc.is_empty() {
1431 let _ = writeln!(out, "{indent}/** {doc} */");
1432 }
1433 };
1434 doc(out, "", c.doc);
1435 if c.def.interface {
1436 let _ = writeln!(out, "export interface {} {{", c.name);
1438 for m in &c.members {
1439 let params = m
1440 .params
1441 .iter()
1442 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1443 .collect::<Vec<_>>()
1444 .join(", ");
1445 let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
1446 let returns = if m.is_async {
1447 format!("Promise<{value}>")
1448 } else {
1449 value
1450 };
1451 doc(out, " ", m.doc);
1452 let has_setter = |name| {
1453 c.members
1454 .iter()
1455 .any(|s| s.kind == MemberKind::Setter && s.name == name)
1456 };
1457 let _ = match m.kind {
1458 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1459 MemberKind::Getter if has_setter(m.name) => {
1460 writeln!(out, " {}: {returns};", m.name)
1461 }
1462 MemberKind::Getter => writeln!(out, " readonly {}: {returns};", m.name),
1463 _ => Ok(()),
1466 };
1467 }
1468 out.push_str("}\n\n");
1469 return;
1470 }
1471 let _ = writeln!(out, "export declare class {} {{", c.name);
1472 if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
1473 out.push_str(" /** Made by the class's members only. */\n private constructor();\n");
1474 }
1475 let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
1476 let params = params
1477 .iter()
1478 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1479 .collect::<Vec<_>>()
1480 .join(", ");
1481 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1482 let returns = if m.is_async {
1483 format!("Promise<{value}>")
1484 } else {
1485 value
1486 };
1487 (params, returns)
1488 };
1489 for m in &c.members {
1490 if !m.overloads.is_empty() {
1491 for (params, returns) in &m.overloads {
1492 doc(out, " ", m.doc);
1493 let (params, returns) = one(m, params, returns);
1494 let _ = match m.kind {
1495 MemberKind::Static => {
1496 writeln!(out, " static {}({params}): {returns};", m.name)
1497 }
1498 _ => writeln!(out, " {}({params}): {returns};", m.name),
1499 };
1500 }
1501 continue;
1502 }
1503 doc(out, " ", m.doc);
1504 let (params, returns) = one(m, &m.params, &m.returns);
1505 let _ = match m.kind {
1506 MemberKind::Constructor => writeln!(out, " constructor({params});"),
1507 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1508 MemberKind::Getter => writeln!(out, " get {}(): {returns};", m.name),
1509 MemberKind::Setter => writeln!(out, " set {}({params});", m.name),
1510 MemberKind::Static => writeln!(out, " static {}({params}): {returns};", m.name),
1511 };
1512 }
1513 out.push_str(
1514 " /** 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",
1515 );
1516}
1517
1518fn handler_name(event: &str) -> String {
1520 let mut chars = event.chars();
1521 match chars.next() {
1522 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
1523 None => "on".to_owned(),
1524 }
1525}
1526
1527#[cfg(test)]
1528mod tests {
1529 use super::*;
1530 use crate::prelude::*;
1531
1532 #[derive(Default)]
1533 struct Stepper;
1534
1535 #[derive(Clone, PartialEq, Props)]
1537 struct StepperProps {
1538 value: f64,
1540 #[prop(default)]
1541 size: StepperSize,
1542 max_value: Option<f64>,
1543 label: Option<Slot>,
1545 children: Children,
1546 }
1547
1548 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
1549 enum StepperSize {
1550 #[default]
1551 Regular,
1552 ExtraLarge,
1553 }
1554
1555 #[derive(Event)]
1556 enum StepperEvent {
1557 Change {
1559 new_value: f64,
1560 },
1561 #[args(limit)]
1562 Limit(u32),
1563 Reset,
1564 }
1565
1566 struct StepperApi;
1567
1568 #[methods]
1569 impl StepperApi {
1570 pub(crate) fn jump_to(&self, value: f64) {
1572 let _ = value;
1573 }
1574
1575 pub(crate) fn value(&self) -> f64 {
1576 0.0
1577 }
1578
1579 #[allow(dead_code)]
1581 fn clamp(&self, value: f64) -> f64 {
1582 value
1583 }
1584 }
1585
1586 impl Component for Stepper {
1587 type Props = StepperProps;
1588 type Event = StepperEvent;
1589 const METHODS: Methods = Methods::of::<StepperApi>();
1590 const DOC: &'static str = "Picks a number.";
1591
1592 fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
1593 view()
1594 }
1595 }
1596
1597 #[test]
1598 fn the_declarations_come_from_the_types() {
1599 let mut registry = Registry::new();
1600 registry.register::<Stepper>();
1601 let ts = declarations(®istry, &[]);
1602 for line in [
1603 " /** The value. */\n value: number;",
1604 "export type StepperSize = \"regular\" | \"extraLarge\";",
1605 " size?: StepperSize;",
1606 " maxValue?: number | null;",
1607 " /** Above the control. */\n label?: JSX.Element;",
1608 " children?: JSX.Element;",
1609 " /** The value changed. */\n onChange?: (event: { newValue: number }) => void;",
1610 " onLimit?: (limit: number) => void;",
1611 " onReset?: () => void;",
1612 "/** Picks a number. */",
1613 "export interface StepperRef {",
1614 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
1615 " value(): Promise<number>;",
1616 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
1617 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
1618 ] {
1619 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
1620 }
1621 assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
1622 assert_eq!(StepperApi::METHODS.len(), 2);
1623 let mut props = StepperProps::initial();
1624 let size = |json| {
1625 let specs = StepperProps::spec(&mut TsTypes::default());
1626 let decode = specs
1627 .iter()
1628 .find(|p| p.name == "size")
1629 .unwrap()
1630 .decode
1631 .unwrap();
1632 super::super::json_host::decode(decode, json)
1633 };
1634 assert!(
1635 props
1636 .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
1637 .unwrap()
1638 );
1639 assert!(props.size == StepperSize::ExtraLarge);
1640 assert!(size(serde_json::json!("huge")).is_err());
1644 assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
1645 assert!(props.set("size", None).unwrap());
1646 assert!(props.size == StepperSize::Regular);
1647 let data = |e: &StepperEvent| super::super::json_host::event_data(e);
1648 assert_eq!(
1649 data(&StepperEvent::Change { new_value: 2.5 }),
1650 Some(serde_json::json!({ "newValue": 2.5 }))
1651 );
1652 assert_eq!(data(&StepperEvent::Limit(3)), Some(serde_json::json!(3)));
1653 assert_eq!(data(&StepperEvent::Reset), None);
1654 assert_eq!(StepperEvent::Reset.name(), "reset");
1655 }
1656
1657 #[test]
1658 fn exports_without_docs_are_listed() {
1659 let mut registry = Registry::new();
1660 registry.register::<Stepper>();
1661 assert_eq!(
1664 registry.undocumented(),
1665 [
1666 "Stepper.size",
1667 "Stepper.maxValue",
1668 "Stepper.children",
1669 "Stepper.onLimit",
1670 "Stepper.onReset",
1671 "Stepper.value",
1672 ]
1673 );
1674 let mut r = Registry::ui_set("test/maker");
1675 r.module::<Maker>();
1676 assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
1677 }
1678
1679 #[crate::element::class]
1681 struct Lonely;
1682
1683 #[crate::element::class]
1684 impl Lonely {
1685 pub(crate) fn new() -> Self {
1686 Lonely
1687 }
1688 }
1689
1690 #[crate::element::module]
1692 struct Maker;
1693
1694 #[crate::element::module]
1695 impl Maker {
1696 pub(crate) fn make() -> Instance<Lonely> {
1697 Instance::new(Lonely)
1698 }
1699 }
1700
1701 #[test]
1702 fn the_classes_a_signature_names_are_registered_with_it() {
1703 let mut r = Registry::ui_set("test/maker");
1704 r.module::<Maker>();
1705 let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
1708 assert_eq!(names, ["Lonely"]);
1709 let ts = declarations(&r, &[]);
1710 assert!(ts.contains("export declare class Lonely"), "{ts}");
1711 assert!(ts.contains("make(): Lonely;"), "{ts}");
1712 r.class::<Lonely>();
1714 assert_eq!(r.class_specs().len(), 1);
1715 let _ = Registry::merged(&[r]);
1716 }
1717
1718 #[crate::element::module]
1720 struct Checks;
1721
1722 #[crate::element::module(flat)]
1723 impl Checks {
1724 pub(crate) fn check(name: String) {
1726 let _ = name;
1727 }
1728 }
1729
1730 #[crate::element::module]
1732 struct CheckVariants;
1733
1734 #[crate::element::module(name = "check")]
1735 impl CheckVariants {
1736 pub(crate) const COUNT: u32 = 2;
1738
1739 pub(crate) fn skip(name: String) {
1741 let _ = name;
1742 }
1743
1744 pub(crate) fn todo(name: String) {
1745 let _ = name;
1746 }
1747 }
1748
1749 #[crate::element::module]
1751 struct Loose;
1752
1753 #[crate::element::module(name = "loose")]
1754 impl Loose {
1755 pub(crate) fn nothing() {}
1757 }
1758
1759 #[test]
1760 fn a_module_named_like_a_function_puts_its_functions_on_it() {
1761 let mut r = Registry::ui_set("test/checks");
1762 r.module::<Checks>()
1763 .module::<CheckVariants>()
1764 .module::<Loose>();
1765 assert_eq!(r.function_members("check").unwrap().name, "check");
1766 assert!(r.function_members("loose").is_none());
1767 let ts = declarations(&r, &[]);
1768 assert!(
1769 ts.contains(
1770 "/** Declares a check. */\n\
1771 export declare function check(name: string): void;\n\
1772 export declare namespace check {\n \
1773 /** Declares a check that does not run. */\n \
1774 function skip(name: string): void;\n \
1775 function todo(name: string): void;\n \
1776 /** How many variants there are. */\n \
1777 const COUNT: number;\n}\n"
1778 ),
1779 "{ts}"
1780 );
1781 assert!(
1782 !ts.contains("CheckVariants") && !ts.contains("checkModule"),
1783 "{ts}"
1784 );
1785 assert!(
1786 ts.contains("export declare const loose: looseModule;"),
1787 "{ts}"
1788 );
1789 assert_eq!(r.undocumented(), ["check.todo"]);
1791 let described = super::super::description::SetDescription::of(&r).unwrap();
1792 let exports: Vec<_> = described
1793 .exports
1794 .iter()
1795 .map(|e| (e.name.as_str(), e.kind))
1796 .collect();
1797 assert_eq!(
1798 exports,
1799 [
1800 ("check", super::super::description::ExportKind::Function),
1801 ("loose", super::super::description::ExportKind::Module)
1802 ]
1803 );
1804 }
1805
1806 mod clash {
1807 #[crate::element::class]
1809 pub(super) struct Lonely;
1810
1811 #[crate::element::class]
1812 impl Lonely {
1813 pub(super) fn new() -> Self {
1814 Lonely
1815 }
1816 }
1817 }
1818
1819 #[test]
1820 fn a_clash_through_a_signature_names_both_types() {
1821 let mut r = Registry::ui_set("test/maker");
1822 r.class::<clash::Lonely>();
1823 let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1825 r.module::<Maker>();
1826 }))
1827 .unwrap_err();
1828 let message = failed.downcast_ref::<String>().unwrap();
1829 assert!(
1830 message.contains("`nsh_core::element::component::tests::clash::Lonely`")
1831 && message.contains("`nsh_core::element::component::tests::Lonely`"),
1832 "{message}"
1833 );
1834 }
1835
1836 #[test]
1837 fn components_are_named_after_their_types() {
1838 let mut registry = Registry::ui_set("test/ui");
1839 registry.register::<Stepper>();
1840 let specs = registry.specs();
1841 assert_eq!(
1842 specs[0].name,
1843 "nsh_core::element::component::tests::Stepper"
1844 );
1845 assert_eq!(specs[0].export, "Stepper");
1846 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
1847 assert_eq!(export_name("Bare"), "Bare");
1848 }
1849
1850 mod other {
1851 use crate::prelude::*;
1852
1853 #[derive(Default)]
1855 pub(super) struct Stepper;
1856
1857 impl Component for Stepper {
1858 type Props = ();
1859 type Event = NoEvent;
1860
1861 fn view(_: (), _: crate::element::Scope<NoEvent>) -> impl IntoElement {
1862 view()
1863 }
1864 }
1865 }
1866
1867 #[test]
1868 #[should_panic(
1869 expected = "components `nsh_core::element::component::tests::Stepper` and `nsh_core::element::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
1870 )]
1871 fn two_components_of_one_set_cannot_share_an_export() {
1872 Registry::ui_set("test/ui")
1873 .register::<Stepper>()
1874 .register::<other::Stepper>();
1875 }
1876
1877 #[test]
1878 #[should_panic(
1879 expected = "component `nsh_core::element::component::tests::Stepper` is registered twice"
1880 )]
1881 fn a_component_is_registered_once() {
1882 Registry::new().register::<Stepper>().register::<Stepper>();
1883 }
1884
1885 #[test]
1888 fn a_sets_submodules_come_with_it() {
1889 let mut sub = Registry::ui_set("test/set/sub");
1890 sub.register::<Stepper>();
1891 let mut set = Registry::ui_set("test/set");
1892 set.submodule(sub);
1893 let specifiers: Vec<_> = set.sets().iter().map(|s| s.specifier()).collect();
1894 assert_eq!(specifiers, [Some("test/set"), Some("test/set/sub")]);
1895 assert_eq!(Registry::merged(&[set]).specs().len(), 1);
1896 let elsewhere = std::panic::catch_unwind(|| {
1898 Registry::ui_set("test/set").submodule(Registry::ui_set("test/settings"));
1899 });
1900 assert!(elsewhere.is_err());
1901 }
1902
1903 #[test]
1904 fn sets_may_share_exports_but_not_components() {
1905 let mut a = Registry::ui_set("test/a");
1906 a.register::<Stepper>();
1907 let mut b = Registry::ui_set("test/b");
1908 b.register::<other::Stepper>();
1909 let merged = Registry::merged(&[a.clone(), b]);
1910 assert_eq!(merged.specs().len(), 2);
1911 let twice = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1912 Registry::merged(&[a.clone(), a])
1913 }));
1914 let message = *twice.unwrap_err().downcast::<String>().unwrap();
1915 assert_eq!(
1916 message,
1917 "component `nsh_core::element::component::tests::Stepper` is registered twice, by two UI sets"
1918 );
1919 }
1920}