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 url_schemes: Vec<String>,
542 status_bar: Option<crate::StatusBarSetting>,
543 main_window: Option<crate::desktop::MainWindowOptions>,
544 translations: Option<crate::i18n::Translations>,
545}
546
547impl Root {
548 pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
550 Self {
551 make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
552 tokens: None,
553 fonts: Vec::new(),
554 appearance: None,
555 app_id: None,
556 url_schemes: Vec::new(),
557 status_bar: None,
558 main_window: None,
559 translations: None,
560 }
561 }
562
563 pub fn translations(mut self, translations: crate::i18n::Translations) -> Self {
566 self.translations = Some(translations);
567 self
568 }
569
570 #[doc(hidden)]
573 pub fn translations_json(self, json: &str) -> Self {
574 match crate::i18n::Translations::from_json(json) {
575 Ok(translations) => self.translations(translations),
576 Err(e) => {
577 log::warn!("locales: {e}");
578 self
579 }
580 }
581 }
582
583 pub fn translations_ref(&self) -> Option<&crate::i18n::Translations> {
585 self.translations.as_ref()
586 }
587
588 pub fn app_id(mut self, id: impl Into<String>) -> Self {
591 self.app_id = Some(id.into());
592 self
593 }
594
595 pub fn app_id_ref(&self) -> Option<&str> {
597 self.app_id.as_deref()
598 }
599
600 pub fn url_schemes(mut self, schemes: impl IntoIterator<Item = impl Into<String>>) -> Self {
604 self.url_schemes = schemes.into_iter().map(Into::into).collect();
605 self
606 }
607
608 pub fn url_schemes_ref(&self) -> &[String] {
610 &self.url_schemes
611 }
612
613 pub fn tokens(mut self, tokens: super::Tokens) -> Self {
616 self.tokens = Some(Arc::new(tokens));
617 self
618 }
619
620 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
623 self.fonts.push(data.into());
624 self
625 }
626
627 pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
631 self.appearance = Some(appearance);
632 self
633 }
634
635 pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
638 self.status_bar = Some(setting);
639 self
640 }
641
642 pub fn main_window(mut self, options: crate::desktop::MainWindowOptions) -> Self {
647 self.main_window = Some(options);
648 self
649 }
650
651 #[doc(hidden)]
655 pub fn main_window_json(self, json: &str) -> Self {
656 let options = serde_json::from_str::<serde_json::Value>(json)
657 .map_err(|e| e.to_string())
658 .and_then(|v| {
659 crate::desktop::MainWindowOptions::from_json(&v).map_err(|e| e.to_string())
660 });
661 match options {
662 Ok(options) => self.main_window(options),
663 Err(e) => {
664 log::warn!("nsh.json: window: {e}");
665 self
666 }
667 }
668 }
669
670 pub fn main_window_ref(&self) -> Option<&crate::desktop::MainWindowOptions> {
672 self.main_window.as_ref()
673 }
674
675 pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
677 self.status_bar
678 }
679
680 pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
683 self.appearance
684 }
685
686 pub fn tokens_ref(&self) -> Option<&super::Tokens> {
688 self.tokens.as_deref()
689 }
690
691 pub fn fonts(&self) -> &[Arc<[u8]>] {
693 &self.fonts
694 }
695
696 pub fn of<C: Component>() -> Self
698 where
699 C::Props: Default,
700 {
701 Self::new::<C>(C::Props::default)
702 }
703
704 pub(crate) fn element(&self) -> super::AnyElement {
706 (self.make)()
707 }
708}
709
710impl fmt::Debug for Root {
711 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
712 f.write_str("Root")
713 }
714}
715
716pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
718 Box::new(super::once::OnceInstance::<C>::new())
719}
720
721#[derive(Clone)]
722struct ComponentType {
723 spec: Arc<ComponentSpec>,
724 make: fn() -> Box<dyn AnyInstance>,
725 id: TypeId,
727}
728
729#[derive(Clone)]
730struct ModuleType {
731 spec: Arc<ModuleSpec>,
732 type_name: &'static str,
734}
735
736#[derive(Clone)]
737struct ClassType {
738 spec: Arc<ClassSpec>,
739 type_name: &'static str,
741}
742
743#[derive(Debug, Clone, Default)]
746#[non_exhaustive]
747pub struct BuiltInScrollbar {
748 pub target: crate::NodeId,
750 pub horizontal: bool,
752 pub theme: Option<Arc<crate::JsonValue>>,
755 pub app_theme: Option<super::AnyValue>,
758}
759
760pub type ScrollbarSource = fn(&BuiltInScrollbar) -> Option<super::AnyElement>;
765
766#[derive(Clone, Default)]
769pub struct Registry {
770 types: Arc<FxHashMap<&'static str, ComponentType>>,
771 modules: Arc<FxHashMap<&'static str, ModuleType>>,
772 classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
775 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
777 native_values: Arc<Vec<&'static str>>,
780 namespace: Option<&'static str>,
783 ui_set: Option<&'static str>,
785 assets: Arc<Vec<&'static [super::AssetFile]>>,
787 tokens: Option<super::TokenSource>,
789 scrollbars: Option<ScrollbarSource>,
791 submodules: Arc<Vec<Registry>>,
794 setups: Arc<Vec<Setup>>,
796}
797
798type Setup = Arc<dyn Fn() + Send + Sync>;
800
801impl fmt::Debug for Registry {
802 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
803 f.debug_set().entries(self.types.keys()).finish()
804 }
805}
806
807impl Registry {
808 pub fn new() -> Self {
810 Self::default()
811 }
812
813 #[track_caller]
822 pub fn register<C: Component>(&mut self) -> &mut Self {
823 let spec = ComponentSpec::of::<C>();
824 let mut refs = Vec::new();
825 (C::METHODS.refs)(&mut refs);
826 self.register_erased(spec, make_instance::<C>, TypeId::of::<C>(), refs)
827 }
828
829 #[track_caller]
832 #[inline(never)]
833 fn register_erased(
834 &mut self,
835 spec: ComponentSpec,
836 make: fn() -> Box<dyn AnyInstance>,
837 id: TypeId,
838 refs: Vec<&'static ClassDef>,
839 ) -> &mut Self {
840 let types = Arc::make_mut(&mut self.types);
841 if let Some(old) = types.get(spec.name) {
842 let set = self.ui_set.or(self.namespace);
843 panic!("{}", same_name(spec.name, old.id, id, set));
844 }
845 if self.classes.keys().any(|(_, name)| *name == spec.export) {
846 panic!(
847 "component `{}` is exported as `{}` like a class{}: rename one",
848 spec.name,
849 spec.export,
850 of_set(self.ui_set.or(self.namespace)),
851 );
852 }
853 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
854 panic!(
855 "components `{}` and `{}` are both exported as `{}`{}: rename one",
856 other.spec.name,
857 spec.name,
858 spec.export,
859 of_set(self.ui_set.or(self.namespace)),
860 );
861 }
862 types.insert(
863 spec.name,
864 ComponentType {
865 spec: Arc::new(spec),
866 make,
867 id,
868 },
869 );
870 self.classes_named(refs)
871 }
872
873 #[track_caller]
881 pub fn module<M: Module>(&mut self) -> &mut Self {
882 let type_name = std::any::type_name::<M>();
883 if self.classes.keys().any(|(_, name)| *name == M::NAME) {
884 panic!(
885 "module `{type_name}` is named `{}` like a class{}: rename one",
886 M::NAME,
887 of_set(self.ui_set.or(self.namespace))
888 );
889 }
890 let modules = Arc::make_mut(&mut self.modules);
891 if let Some(old) = modules.get(M::NAME) {
892 panic!(
893 "{}",
894 same_module(
895 M::NAME,
896 old.type_name,
897 type_name,
898 self.ui_set.or(self.namespace)
899 )
900 );
901 }
902 modules.insert(
903 M::NAME,
904 ModuleType {
905 spec: Arc::new(ModuleSpec::of::<M>()),
906 type_name,
907 },
908 );
909 let mut refs = Vec::new();
910 for f in M::FUNCTIONS {
911 (f.refs)(&mut refs);
912 }
913 self.classes_named(refs)
914 }
915
916 #[track_caller]
929 pub fn class<C: Class>(&mut self) -> &mut Self {
930 self.class_def(C::DEF)
931 }
932
933 #[track_caller]
936 fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
937 for def in refs {
938 self.class_def(def);
939 }
940 self
941 }
942
943 #[track_caller]
944 fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
945 let type_name = (def.type_name)();
946 let set = self.ui_set.or(self.namespace);
947 if let Some(old) = self.classes.get(&(set, def.name)) {
948 if (old.spec.def.type_id)() == (def.type_id)() {
949 return self;
950 }
951 panic!("{}", same_class(def.name, old.type_name, type_name, set));
952 }
953 if self.modules.contains_key(def.name)
954 || self.types.values().any(|t| t.spec.export == def.name)
955 {
956 panic!(
957 "class `{type_name}` is named `{}` like a module or a component{}: rename one",
958 def.name,
959 of_set(set)
960 );
961 }
962 Arc::make_mut(&mut self.classes).insert(
963 (set, def.name),
964 ClassType {
965 spec: Arc::new(ClassSpec::of(def)),
966 type_name,
967 },
968 );
969 let mut refs = Vec::new();
971 for m in def.members {
972 (m.refs)(&mut refs);
973 }
974 self.classes_named(refs)
975 }
976
977 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
980 let r = Arc::make_mut(&mut self.reexports);
981 r.0.extend_from_slice(values);
982 r.1.extend_from_slice(types);
983 self
984 }
985
986 #[track_caller]
997 pub fn merged(sets: &[Registry]) -> Self {
998 let mut out = Self::default();
999 for set in sets.iter().flat_map(Registry::sets) {
1000 out.tokens = out.tokens.or(set.tokens);
1001 out.scrollbars = out.scrollbars.or(set.scrollbars);
1002 Arc::make_mut(&mut out.setups).extend(set.setups.iter().cloned());
1003 let types = Arc::make_mut(&mut out.types);
1004 for (name, ty) in set.types.iter() {
1005 if let Some(old) = types.insert(name, ty.clone()) {
1006 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
1007 }
1008 }
1009 }
1010 out
1011 }
1012
1013 pub fn ui_set(specifier: &'static str) -> Self {
1017 Self {
1018 ui_set: Some(specifier),
1019 ..Self::default()
1020 }
1021 }
1022
1023 pub fn specifier(&self) -> Option<&'static str> {
1026 self.ui_set.or(self.namespace)
1027 }
1028
1029 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
1032 (&self.reexports.0, &self.reexports.1)
1033 }
1034
1035 #[track_caller]
1047 pub fn submodule(&mut self, set: Registry) -> &mut Self {
1048 let under = match (self.ui_set, set.ui_set) {
1049 (Some(parent), Some(child)) => child
1050 .strip_prefix(parent)
1051 .is_some_and(|rest| rest.len() > 1 && rest.starts_with('/')),
1052 _ => false,
1053 };
1054 assert!(
1055 under,
1056 "a submodule is a UI set under a path of its set's specifier: {:?} under {:?}",
1057 set.ui_set, self.ui_set
1058 );
1059 Arc::make_mut(&mut self.submodules).push(set);
1060 self
1061 }
1062
1063 pub fn sets(&self) -> Vec<&Registry> {
1067 let mut out = vec![self];
1068 for sub in self.submodules.iter() {
1069 out.extend(sub.sets());
1070 }
1071 out
1072 }
1073
1074 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
1077 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
1078 self
1079 }
1080
1081 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
1086 Arc::make_mut(&mut self.assets).push(files);
1087 self
1088 }
1089
1090 pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
1093 self.tokens = Some(source);
1094 self
1095 }
1096
1097 pub fn scrollbars_from(&mut self, source: ScrollbarSource) -> &mut Self {
1102 self.scrollbars = Some(source);
1103 self
1104 }
1105
1106 pub(crate) fn scrollbar_source(&self) -> Option<ScrollbarSource> {
1109 self.scrollbars
1110 }
1111
1112 pub fn setup(&mut self, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
1120 Arc::make_mut(&mut self.setups).push(Arc::new(f));
1121 self
1122 }
1123
1124 pub(crate) fn run_setups(&self) {
1127 for setup in self.setups.iter() {
1128 setup();
1129 }
1130 }
1131
1132 pub(crate) fn run_setups_not_in(&self, old: &Registry) {
1135 for setup in self.setups.iter() {
1136 let known = old
1137 .setups
1138 .iter()
1139 .any(|o| std::ptr::addr_eq(Arc::as_ptr(o), Arc::as_ptr(setup)));
1140 if !known {
1141 setup();
1142 }
1143 }
1144 }
1145
1146 pub fn tokens(
1150 &self,
1151 json: Option<&str>,
1152 ) -> Option<Result<(super::Tokens, Vec<String>), String>> {
1153 self.tokens.map(|source| source(json))
1154 }
1155
1156 pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
1158 self.tokens
1159 }
1160
1161 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
1163 self.assets.iter().flat_map(|files| files.iter())
1164 }
1165
1166 pub fn native_value_names(&self) -> &[&'static str] {
1168 &self.native_values
1169 }
1170
1171 pub(crate) fn runtime(namespace: &'static str) -> Self {
1173 Self {
1174 namespace: Some(namespace),
1175 ..Self::default()
1176 }
1177 }
1178
1179 pub fn namespace(&self) -> Option<&'static str> {
1182 self.namespace
1183 }
1184
1185 pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
1187 let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
1188 specs.sort_by_key(|s| s.name);
1189 specs
1190 }
1191
1192 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
1194 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
1195 specs.sort_by_key(|s| s.name);
1196 specs
1197 }
1198
1199 pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
1204 let exported = self.modules.values().any(|m| {
1205 m.spec.flat
1206 && m.spec
1207 .functions
1208 .iter()
1209 .any(|f| !f.getter && f.name == function)
1210 });
1211 exported
1212 .then(|| {
1213 self.modules
1214 .values()
1215 .find(|m| !m.spec.flat && m.spec.name == function)
1216 .map(|m| m.spec.clone())
1217 })
1218 .flatten()
1219 }
1220
1221 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
1223 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
1224 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
1225 specs
1226 }
1227
1228 pub fn undocumented(&self) -> Vec<String> {
1237 let mut out = Vec::new();
1238 let specs = self.specs();
1239 for c in &specs {
1240 if c.doc.is_empty() {
1241 out.push(c.export.clone());
1242 }
1243 for p in c.props.iter().filter(|p| p.doc.is_empty()) {
1244 out.push(format!("{}.{}", c.export, p.name));
1245 }
1246 for e in c.events.iter().filter(|e| e.doc.is_empty()) {
1247 out.push(format!("{}.{}", c.export, handler_name(e.name)));
1248 }
1249 for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
1250 out.push(format!("{}.{}", c.export, m.name));
1251 }
1252 }
1253 for m in self.module_specs() {
1254 let merged = specs.iter().any(|c| c.export == m.name)
1255 || (!m.flat && self.function_members(m.name).is_some());
1256 if m.doc.is_empty() && !merged && !m.flat {
1257 out.push(m.name.to_owned());
1258 }
1259 for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
1260 out.push(if m.flat {
1261 f.name.to_owned()
1262 } else {
1263 format!("{}.{}", m.name, f.name)
1264 });
1265 }
1266 }
1267 for c in self.class_specs() {
1268 if c.doc.is_empty() {
1269 out.push(c.name.to_owned());
1270 }
1271 let documented_getter = |name: &str| {
1272 c.members
1273 .iter()
1274 .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
1275 };
1276 for m in c.members.iter().filter(|m| m.doc.is_empty()) {
1277 match m.kind {
1278 MemberKind::Constructor => out.push(format!("new {}", c.name)),
1279 MemberKind::Setter if documented_getter(m.name) => {}
1280 _ => out.push(format!("{}.{}", c.name, m.name)),
1281 }
1282 }
1283 }
1284 out
1285 }
1286
1287 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1289 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
1290 }
1291}
1292
1293fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
1295 if old == new {
1296 format!("component `{name}` is registered twice{}", of_set(set))
1297 } else {
1298 format!(
1299 "two different types named `{name}` are registered{} (two versions of one crate?)",
1300 of_set(set)
1301 )
1302 }
1303}
1304
1305fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1307 if old == new {
1308 format!("module `{old}` is registered twice{}", of_set(set))
1309 } else {
1310 format!(
1311 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
1312 of_set(set)
1313 )
1314 }
1315}
1316
1317fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1319 if old == new {
1320 format!("class `{old}` is registered twice{}", of_set(set))
1321 } else {
1322 format!(
1323 "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
1324 of_set(set)
1325 )
1326 }
1327}
1328
1329fn of_set(set: Option<&str>) -> String {
1331 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1332}
1333
1334pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
1343 let specs = registry.specs();
1344 let modules = registry.module_specs();
1345 let classes = registry.class_specs();
1346 use std::fmt::Write as _;
1347 let mut out = String::new();
1348 let doc = |out: &mut String, indent: &str, doc: &str| {
1349 if !doc.is_empty() {
1350 let _ = writeln!(out, "{indent}/** {doc} */");
1351 }
1352 };
1353 let mut types = TsTypes::default();
1355 for spec in &specs {
1356 types.merge(&spec.types);
1357 }
1358 for m in &modules {
1359 types.merge(&m.types);
1360 }
1361 for c in &classes {
1362 types.merge(&c.types);
1363 }
1364 for declaration in types.declarations() {
1365 let _ = write!(out, "{declaration}\n\n");
1366 }
1367 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
1368 let signatures = |f: &FunctionSpec| {
1370 let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
1371 let params = params
1372 .iter()
1373 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1374 .collect::<Vec<_>>()
1375 .join(", ");
1376 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1377 let returns = if f.promises() {
1378 format!("Promise<{value}>")
1379 } else {
1380 value
1381 };
1382 (params, returns)
1383 };
1384 if f.overloads.is_empty() {
1385 vec![one(&f.params, &f.returns)]
1386 } else {
1387 f.overloads
1388 .iter()
1389 .map(|(params, returns)| one(params, returns))
1390 .collect()
1391 }
1392 };
1393 let module_object = |out: &mut String, m: &ModuleSpec| {
1395 out.push_str("{\n");
1396 for f in &m.functions {
1397 for (params, returns) in signatures(f) {
1398 doc(out, " ", f.doc);
1399 if f.getter {
1400 let _ = writeln!(out, " readonly {}: {returns};", f.name);
1401 continue;
1402 }
1403 let _ = writeln!(out, " {}({params}): {returns};", f.name);
1404 }
1405 }
1406 for constant in &m.constants {
1407 doc(out, " ", constant.doc);
1408 let _ = writeln!(
1409 out,
1410 " readonly {}: {};",
1411 constant.name,
1412 constant.value.ts_type()
1413 );
1414 }
1415 out.push('}');
1416 };
1417 for spec in &specs {
1418 let (generic, params, extends) = match spec.items() {
1422 Some(_) => ("<T>", "<T>", ", ListItemsProps<T>"),
1423 None if spec.generic => ("<T>", "<T = any>", ""),
1424 None => ("", "", ""),
1425 };
1426 let host = if spec.methods.is_empty() {
1428 "ComponentHostProps"
1429 } else {
1430 let _ = write!(
1431 out,
1432 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: ViewRef;\n",
1433 spec.export
1434 );
1435 for m in &spec.methods {
1436 doc(&mut out, " ", m.doc);
1437 let params = m
1438 .params
1439 .iter()
1440 .map(|(n, ts, optional)| {
1441 format!("{n}{}: {ts}", if *optional { "?" } else { "" })
1442 })
1443 .collect::<Vec<_>>()
1444 .join(", ");
1445 let returns = match &m.returns {
1446 Some(ts) => format!("Promise<{ts}>"),
1447 None => "void".to_owned(),
1448 };
1449 let _ = writeln!(out, " {}({params}): {returns};", m.name);
1450 }
1451 out.push_str("}\n\n");
1452 "Omit<ComponentHostProps, \"ref\">"
1453 };
1454 let _ = writeln!(
1455 out,
1456 "export interface {}Props{params} extends {host}{extends} {{",
1457 spec.export
1458 );
1459 if !spec.methods.is_empty() {
1460 let _ = writeln!(
1461 out,
1462 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
1463 spec.export
1464 );
1465 }
1466 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
1467 doc(&mut out, " ", p.doc);
1468 let optional = if p.optional { "?" } else { "" };
1469 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
1470 }
1471 for e in &spec.events {
1472 doc(&mut out, " ", e.doc);
1473 let handler = handler_name(e.name);
1474 let arg = if e.data == "void" {
1475 String::new()
1476 } else {
1477 format!("{}: {}", e.arg, e.data)
1478 };
1479 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
1480 }
1481 out.push_str("}\n\n");
1482 if omit.contains(&spec.export.as_str()) {
1483 continue;
1484 }
1485 doc(&mut out, "", spec.doc);
1486 let mut with = String::new();
1488 if let Some(m) = module_of(&spec.export) {
1489 with.push_str(" & ");
1490 module_object(&mut with, m);
1491 }
1492 let _ = write!(
1493 out,
1494 "export declare const {}: ({params}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1495 spec.export, spec.export,
1496 );
1497 }
1498 for m in &modules {
1499 if specs.iter().any(|s| s.export == m.name)
1500 || (!m.flat && registry.function_members(m.name).is_some())
1501 {
1502 continue;
1503 }
1504 if m.flat {
1505 for f in m
1506 .functions
1507 .iter()
1508 .filter(|f| !f.getter && !omit.contains(&f.name))
1509 {
1510 for (params, returns) in signatures(f) {
1511 doc(&mut out, "", f.doc);
1512 let _ = writeln!(
1513 out,
1514 "export declare function {}({params}): {returns};",
1515 f.name
1516 );
1517 }
1518 if let Some(members) = registry.function_members(f.name) {
1520 let _ = writeln!(out, "export declare namespace {} {{", f.name);
1521 for member in &members.functions {
1522 for (params, returns) in signatures(member) {
1523 doc(&mut out, " ", member.doc);
1524 let _ = if member.getter {
1525 writeln!(out, " const {}: {returns};", member.name)
1526 } else {
1527 writeln!(out, " function {}({params}): {returns};", member.name)
1528 };
1529 }
1530 }
1531 for constant in &members.constants {
1532 doc(&mut out, " ", constant.doc);
1533 let _ = writeln!(
1534 out,
1535 " const {}: {};",
1536 constant.name,
1537 constant.value.ts_type()
1538 );
1539 }
1540 out.push_str("}\n");
1541 }
1542 out.push('\n');
1543 }
1544 for constant in &m.constants {
1545 if !omit.contains(&constant.name) {
1546 doc(&mut out, "", constant.doc);
1547 let _ = writeln!(
1548 out,
1549 "export declare const {}: {};\n",
1550 constant.name,
1551 constant.value.ts_type()
1552 );
1553 }
1554 }
1555 if m.default && !omit.contains(&"default") {
1556 let _ = write!(out, "declare const defaultExport: ");
1557 module_object(&mut out, m);
1558 for native in registry.native_value_names() {
1560 let _ = write!(out, " & {{ {native}: typeof {native} }}");
1561 }
1562 out.push_str(";\nexport default defaultExport;\n\n");
1563 }
1564 continue;
1565 }
1566 doc(&mut out, "", m.doc);
1567 let _ = write!(out, "export interface {}Module ", m.name);
1568 module_object(&mut out, m);
1569 out.push_str("\n\n");
1570 if !omit.contains(&m.name) {
1571 doc(&mut out, "", m.doc);
1572 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1573 }
1574 if m.default && !omit.contains(&"default") {
1575 let _ = write!(
1576 out,
1577 "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
1578 m.name
1579 );
1580 }
1581 }
1582 for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
1583 class_declaration(&mut out, c);
1584 }
1585 out
1586}
1587
1588fn class_declaration(out: &mut String, c: &ClassSpec) {
1590 use std::fmt::Write as _;
1591 let doc = |out: &mut String, indent: &str, doc: &str| {
1592 if !doc.is_empty() {
1593 let _ = writeln!(out, "{indent}/** {doc} */");
1594 }
1595 };
1596 doc(out, "", c.doc);
1597 if c.def.interface {
1598 let _ = writeln!(out, "export interface {} {{", c.name);
1600 for m in &c.members {
1601 let params = m
1602 .params
1603 .iter()
1604 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1605 .collect::<Vec<_>>()
1606 .join(", ");
1607 let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
1608 let returns = if m.is_async {
1609 format!("Promise<{value}>")
1610 } else {
1611 value
1612 };
1613 doc(out, " ", m.doc);
1614 let has_setter = |name| {
1615 c.members
1616 .iter()
1617 .any(|s| s.kind == MemberKind::Setter && s.name == name)
1618 };
1619 let _ = match m.kind {
1620 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1621 MemberKind::Getter if has_setter(m.name) => {
1622 writeln!(out, " {}: {returns};", m.name)
1623 }
1624 MemberKind::Getter => writeln!(out, " readonly {}: {returns};", m.name),
1625 _ => Ok(()),
1628 };
1629 }
1630 out.push_str("}\n\n");
1631 return;
1632 }
1633 let _ = writeln!(out, "export declare class {} {{", c.name);
1634 if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
1635 out.push_str(" /** Made by the class's members only. */\n private constructor();\n");
1636 }
1637 let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
1638 let params = params
1639 .iter()
1640 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1641 .collect::<Vec<_>>()
1642 .join(", ");
1643 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1644 let returns = if m.is_async {
1645 format!("Promise<{value}>")
1646 } else {
1647 value
1648 };
1649 (params, returns)
1650 };
1651 for m in &c.members {
1652 if !m.overloads.is_empty() {
1653 for (params, returns) in &m.overloads {
1654 doc(out, " ", m.doc);
1655 let (params, returns) = one(m, params, returns);
1656 let _ = match m.kind {
1657 MemberKind::Static => {
1658 writeln!(out, " static {}({params}): {returns};", m.name)
1659 }
1660 _ => writeln!(out, " {}({params}): {returns};", m.name),
1661 };
1662 }
1663 continue;
1664 }
1665 doc(out, " ", m.doc);
1666 let (params, returns) = one(m, &m.params, &m.returns);
1667 let _ = match m.kind {
1668 MemberKind::Constructor => writeln!(out, " constructor({params});"),
1669 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1670 MemberKind::Getter => writeln!(out, " get {}(): {returns};", m.name),
1671 MemberKind::Setter => writeln!(out, " set {}({params});", m.name),
1672 MemberKind::Static => writeln!(out, " static {}({params}): {returns};", m.name),
1673 };
1674 }
1675 out.push_str(
1676 " /** 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",
1677 );
1678}
1679
1680fn handler_name(event: &str) -> String {
1682 let mut chars = event.chars();
1683 match chars.next() {
1684 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
1685 None => "on".to_owned(),
1686 }
1687}
1688
1689#[cfg(test)]
1690mod tests {
1691 use super::*;
1692 use crate::prelude::*;
1693
1694 #[derive(Default)]
1695 struct Stepper;
1696
1697 #[derive(Clone, PartialEq, Props)]
1699 struct StepperProps {
1700 value: f64,
1702 #[prop(default)]
1703 size: StepperSize,
1704 max_value: Option<f64>,
1705 label: Option<Slot>,
1707 children: Children,
1708 }
1709
1710 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
1711 enum StepperSize {
1712 #[default]
1713 Regular,
1714 ExtraLarge,
1715 }
1716
1717 #[derive(Event)]
1718 enum StepperEvent {
1719 Change {
1721 new_value: f64,
1722 },
1723 #[args(limit)]
1724 Limit(u32),
1725 Reset,
1726 }
1727
1728 struct StepperApi;
1729
1730 #[methods]
1731 impl StepperApi {
1732 pub(crate) fn jump_to(&self, value: f64) {
1734 let _ = value;
1735 }
1736
1737 pub(crate) fn value(&self) -> f64 {
1738 0.0
1739 }
1740
1741 #[allow(dead_code)]
1743 fn clamp(&self, value: f64) -> f64 {
1744 value
1745 }
1746 }
1747
1748 impl Component for Stepper {
1749 type Props = StepperProps;
1750 type Event = StepperEvent;
1751 const METHODS: Methods = Methods::of::<StepperApi>();
1752 const DOC: &'static str = "Picks a number.";
1753
1754 fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
1755 view()
1756 }
1757 }
1758
1759 #[test]
1760 fn the_declarations_come_from_the_types() {
1761 let mut registry = Registry::new();
1762 registry.register::<Stepper>();
1763 let ts = declarations(®istry, &[]);
1764 for line in [
1765 " /** The value. */\n value: number;",
1766 "export type StepperSize = \"regular\" | \"extraLarge\";",
1767 " size?: StepperSize;",
1768 " maxValue?: number | null;",
1769 " /** Above the control. */\n label?: JSX.Element;",
1770 " children?: JSX.Element;",
1771 " /** The value changed. */\n onChange?: (event: { newValue: number }) => void;",
1772 " onLimit?: (event: { limit: number }) => void;",
1773 " onReset?: () => void;",
1774 "/** Picks a number. */",
1775 "export interface StepperRef {",
1776 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
1777 " value(): Promise<number>;",
1778 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
1779 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
1780 ] {
1781 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
1782 }
1783 assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
1784 assert_eq!(StepperApi::METHODS.len(), 2);
1785 let mut props = StepperProps::initial();
1786 let size = |json| {
1787 let specs = StepperProps::spec(&mut TsTypes::default());
1788 let decode = specs
1789 .iter()
1790 .find(|p| p.name == "size")
1791 .unwrap()
1792 .decode
1793 .unwrap();
1794 super::super::json_host::decode(decode, json)
1795 };
1796 assert!(
1797 props
1798 .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
1799 .unwrap()
1800 );
1801 assert!(props.size == StepperSize::ExtraLarge);
1802 assert!(size(serde_json::json!("huge")).is_err());
1806 assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
1807 assert!(props.set("size", None).unwrap());
1808 assert!(props.size == StepperSize::Regular);
1809 let data = |e: &StepperEvent| super::super::json_host::event_data(e);
1810 assert_eq!(
1811 data(&StepperEvent::Change { new_value: 2.5 }),
1812 Some(serde_json::json!({ "newValue": 2.5 }))
1813 );
1814 assert_eq!(
1815 data(&StepperEvent::Limit(3)),
1816 Some(serde_json::json!({ "limit": 3 }))
1817 );
1818 assert_eq!(data(&StepperEvent::Reset), None);
1819 assert_eq!(StepperEvent::Reset.name(), "reset");
1820 }
1821
1822 #[test]
1823 fn exports_without_docs_are_listed() {
1824 let mut registry = Registry::new();
1825 registry.register::<Stepper>();
1826 assert_eq!(
1829 registry.undocumented(),
1830 [
1831 "Stepper.size",
1832 "Stepper.maxValue",
1833 "Stepper.children",
1834 "Stepper.onLimit",
1835 "Stepper.onReset",
1836 "Stepper.value",
1837 ]
1838 );
1839 let mut r = Registry::ui_set("test/maker");
1840 r.module::<Maker>();
1841 assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
1842 }
1843
1844 #[crate::element::class]
1846 struct Lonely;
1847
1848 #[crate::element::class]
1849 impl Lonely {
1850 pub(crate) fn new() -> Self {
1851 Lonely
1852 }
1853 }
1854
1855 #[crate::element::module]
1857 struct Maker;
1858
1859 #[crate::element::module]
1860 impl Maker {
1861 pub(crate) fn make() -> Instance<Lonely> {
1862 Instance::new(Lonely)
1863 }
1864 }
1865
1866 #[test]
1867 fn the_classes_a_signature_names_are_registered_with_it() {
1868 let mut r = Registry::ui_set("test/maker");
1869 r.module::<Maker>();
1870 let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
1873 assert_eq!(names, ["Lonely"]);
1874 let ts = declarations(&r, &[]);
1875 assert!(ts.contains("export declare class Lonely"), "{ts}");
1876 assert!(ts.contains("make(): Lonely;"), "{ts}");
1877 r.class::<Lonely>();
1879 assert_eq!(r.class_specs().len(), 1);
1880 let _ = Registry::merged(&[r]);
1881 }
1882
1883 #[crate::element::module]
1885 struct Checks;
1886
1887 #[crate::element::module(flat)]
1888 impl Checks {
1889 pub(crate) fn check(name: String) {
1891 let _ = name;
1892 }
1893 }
1894
1895 #[crate::element::module]
1897 struct CheckVariants;
1898
1899 #[crate::element::module(name = "check")]
1900 impl CheckVariants {
1901 pub(crate) const COUNT: u32 = 2;
1903
1904 pub(crate) fn skip(name: String) {
1906 let _ = name;
1907 }
1908
1909 pub(crate) fn todo(name: String) {
1910 let _ = name;
1911 }
1912 }
1913
1914 #[crate::element::module]
1916 struct Loose;
1917
1918 #[crate::element::module(name = "loose")]
1919 impl Loose {
1920 pub(crate) fn nothing() {}
1922 }
1923
1924 #[test]
1925 fn a_module_named_like_a_function_puts_its_functions_on_it() {
1926 let mut r = Registry::ui_set("test/checks");
1927 r.module::<Checks>()
1928 .module::<CheckVariants>()
1929 .module::<Loose>();
1930 assert_eq!(r.function_members("check").unwrap().name, "check");
1931 assert!(r.function_members("loose").is_none());
1932 let ts = declarations(&r, &[]);
1933 assert!(
1934 ts.contains(
1935 "/** Declares a check. */\n\
1936 export declare function check(name: string): void;\n\
1937 export declare namespace check {\n \
1938 /** Declares a check that does not run. */\n \
1939 function skip(name: string): void;\n \
1940 function todo(name: string): void;\n \
1941 /** How many variants there are. */\n \
1942 const COUNT: number;\n}\n"
1943 ),
1944 "{ts}"
1945 );
1946 assert!(
1947 !ts.contains("CheckVariants") && !ts.contains("checkModule"),
1948 "{ts}"
1949 );
1950 assert!(
1951 ts.contains("export declare const loose: looseModule;"),
1952 "{ts}"
1953 );
1954 assert_eq!(r.undocumented(), ["check.todo"]);
1956 let described = super::super::description::SetDescription::of(&r).unwrap();
1957 let exports: Vec<_> = described
1958 .exports
1959 .iter()
1960 .map(|e| (e.name.as_str(), e.kind))
1961 .collect();
1962 assert_eq!(
1963 exports,
1964 [
1965 ("check", super::super::description::ExportKind::Function),
1966 ("loose", super::super::description::ExportKind::Module)
1967 ]
1968 );
1969 }
1970
1971 mod clash {
1972 #[crate::element::class]
1974 pub(super) struct Lonely;
1975
1976 #[crate::element::class]
1977 impl Lonely {
1978 pub(super) fn new() -> Self {
1979 Lonely
1980 }
1981 }
1982 }
1983
1984 #[test]
1985 fn a_clash_through_a_signature_names_both_types() {
1986 let mut r = Registry::ui_set("test/maker");
1987 r.class::<clash::Lonely>();
1988 let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1990 r.module::<Maker>();
1991 }))
1992 .unwrap_err();
1993 let message = failed.downcast_ref::<String>().unwrap();
1994 assert!(
1995 message.contains("`nsh_core::element::component::tests::clash::Lonely`")
1996 && message.contains("`nsh_core::element::component::tests::Lonely`"),
1997 "{message}"
1998 );
1999 }
2000
2001 #[test]
2002 fn components_are_named_after_their_types() {
2003 let mut registry = Registry::ui_set("test/ui");
2004 registry.register::<Stepper>();
2005 let specs = registry.specs();
2006 assert_eq!(
2007 specs[0].name,
2008 "nsh_core::element::component::tests::Stepper"
2009 );
2010 assert_eq!(specs[0].export, "Stepper");
2011 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
2012 assert_eq!(export_name("Bare"), "Bare");
2013 }
2014
2015 mod other {
2016 use crate::prelude::*;
2017
2018 #[derive(Default)]
2020 pub(super) struct Stepper;
2021
2022 impl Component for Stepper {
2023 type Props = ();
2024 type Event = NoEvent;
2025
2026 fn view(_: (), _: crate::element::Scope<NoEvent>) -> impl IntoElement {
2027 view()
2028 }
2029 }
2030 }
2031
2032 #[test]
2033 #[should_panic(
2034 expected = "components `nsh_core::element::component::tests::Stepper` and `nsh_core::element::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
2035 )]
2036 fn two_components_of_one_set_cannot_share_an_export() {
2037 Registry::ui_set("test/ui")
2038 .register::<Stepper>()
2039 .register::<other::Stepper>();
2040 }
2041
2042 #[test]
2043 #[should_panic(
2044 expected = "component `nsh_core::element::component::tests::Stepper` is registered twice"
2045 )]
2046 fn a_component_is_registered_once() {
2047 Registry::new().register::<Stepper>().register::<Stepper>();
2048 }
2049
2050 #[test]
2053 fn a_sets_submodules_come_with_it() {
2054 let mut sub = Registry::ui_set("test/set/sub");
2055 sub.register::<Stepper>();
2056 let mut set = Registry::ui_set("test/set");
2057 set.submodule(sub);
2058 let specifiers: Vec<_> = set.sets().iter().map(|s| s.specifier()).collect();
2059 assert_eq!(specifiers, [Some("test/set"), Some("test/set/sub")]);
2060 assert_eq!(Registry::merged(&[set]).specs().len(), 1);
2061 let elsewhere = std::panic::catch_unwind(|| {
2063 Registry::ui_set("test/set").submodule(Registry::ui_set("test/settings"));
2064 });
2065 assert!(elsewhere.is_err());
2066 }
2067
2068 #[test]
2069 fn sets_may_share_exports_but_not_components() {
2070 let mut a = Registry::ui_set("test/a");
2071 a.register::<Stepper>();
2072 let mut b = Registry::ui_set("test/b");
2073 b.register::<other::Stepper>();
2074 let merged = Registry::merged(&[a.clone(), b]);
2075 assert_eq!(merged.specs().len(), 2);
2076 let twice = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2077 Registry::merged(&[a.clone(), a])
2078 }));
2079 let message = *twice.unwrap_err().downcast::<String>().unwrap();
2080 assert_eq!(
2081 message,
2082 "component `nsh_core::element::component::tests::Stepper` is registered twice, by two UI sets"
2083 );
2084 }
2085}