1use std::{
6 any::{Any, TypeId},
7 fmt,
8 sync::Arc,
9};
10
11use rustc_hash::FxHashMap;
12
13use super::{
14 Children, IntoElement, PropError, Slot, TsType, TsTypes,
15 builder::{ComponentElement, ElNode},
16 call::{AnyValue, JsResult, MethodCall},
17 class::{Class, ClassDef, ClassSpec, MemberKind, Thrown},
18 js::{JsHost, JsIn, JsOwned},
19 module::{FunctionSpec, Module, ModuleSpec},
20};
21
22pub trait Component: 'static {
44 type Props: Props;
46
47 type Event: Event;
49
50 const METHODS: Methods = Methods::NONE;
53
54 const DOC: &'static str = "";
57
58 fn view(props: Self::Props, cx: super::Scope<Self::Event>) -> impl IntoElement;
62
63 fn element(props: Self::Props) -> ComponentElement<Self>
68 where
69 Self: Sized,
70 {
71 ComponentElement::new(props)
72 }
73}
74
75#[derive(Debug, Clone, PartialEq, Eq)]
78pub struct ComponentError {
79 pub component: &'static str,
81 pub message: String,
83}
84
85impl fmt::Display for ComponentError {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 write!(f, "{} failed: {}", self.component, self.message)
88 }
89}
90
91pub(crate) fn caught<R>(f: impl FnOnce() -> R) -> Result<R, String> {
93 std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).map_err(panic_message)
94}
95
96pub(crate) fn panic_message(payload: Box<dyn std::any::Any + Send>) -> String {
98 match payload.downcast::<String>() {
99 Ok(s) => *s,
100 Err(payload) => match payload.downcast::<&'static str>() {
101 Ok(s) => (*s).to_owned(),
102 Err(_) => "a panic".to_owned(),
103 },
104 }
105}
106
107pub struct Method {
110 pub name: &'static str,
112 pub doc: &'static str,
114 pub params: &'static [Param],
116 pub returns: Option<TsType>,
120 pub refs: super::ClassRefs,
122 pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
127}
128
129pub trait Api: Sized + 'static {
134 const METHODS: &'static [Method];
136}
137
138#[derive(Clone, Copy)]
141pub struct Methods {
142 specs: fn(&mut TsTypes) -> Vec<MethodSpec>,
143 refs: super::ClassRefs,
144}
145
146impl Methods {
147 pub const NONE: Self = Self {
149 specs: |_| Vec::new(),
150 refs: |_| {},
151 };
152
153 pub const fn of<A: Api>() -> Self {
155 Self {
156 specs: specs_of::<A>,
157 refs: |out| {
158 for m in A::METHODS {
159 (m.refs)(out);
160 }
161 },
162 }
163 }
164}
165
166fn specs_of<A: Api>(types: &mut TsTypes) -> Vec<MethodSpec> {
167 A::METHODS
168 .iter()
169 .map(|m| MethodSpec {
170 name: m.name,
171 doc: m.doc,
172 params: m
173 .params
174 .iter()
175 .map(|(n, ts, optional)| (*n, ts(types), *optional))
176 .collect(),
177 returns: m.returns.map(|ts| ts(types)),
178 call: m.call,
179 })
180 .collect()
181}
182
183pub type Param = (&'static str, TsType, bool);
186
187#[derive(Debug, Clone)]
189pub struct MethodSpec {
190 pub name: &'static str,
192 pub doc: &'static str,
194 pub params: Vec<(&'static str, String, bool)>,
197 pub returns: Option<String>,
199 pub call: fn(&dyn JsHost) -> Result<MethodCall, Thrown>,
201}
202
203impl MethodSpec {
204 pub fn promises(&self) -> bool {
209 self.returns.is_some()
210 }
211}
212
213#[derive(Debug, Clone, Copy, PartialEq, Eq)]
215pub enum PropKind {
216 Value,
219 Renderer,
223 Slot,
225 Children,
227 Items,
230}
231
232pub type PropDecode = fn(JsIn<'_>) -> Result<AnyValue, PropError>;
236
237#[derive(Debug, Clone)]
239pub struct PropSpec {
240 pub name: &'static str,
242 pub ts: String,
244 pub optional: bool,
246 pub doc: &'static str,
248 pub kind: PropKind,
250 pub decode: Option<PropDecode>,
252}
253
254#[derive(Debug, Clone)]
256pub struct EventSpec {
257 pub name: &'static str,
259 pub arg: &'static str,
262 pub data: String,
265 pub doc: &'static str,
267}
268
269pub trait Props: Clone + PartialEq + 'static {
271 #[doc(hidden)]
273 const ITEMS: Option<&'static str> = None;
274
275 #[doc(hidden)]
278 const LAZY_CHILDREN: bool = false;
279
280 #[doc(hidden)]
284 const GENERIC: bool = false;
285
286 fn spec(types: &mut TsTypes) -> Vec<PropSpec>;
288
289 fn initial() -> Self;
291
292 fn set(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
295
296 fn set_slot(&mut self, name: &str, slot: Option<Slot>) -> bool;
298
299 fn set_children(&mut self, children: Children) -> bool;
301
302 #[doc(hidden)]
305 fn held(&self) -> Self {
306 self.clone()
307 }
308
309 #[doc(hidden)]
313 fn update_from(&mut self, new: &Self) -> bool {
314 if self == new {
315 return false;
316 }
317 *self = new.clone();
318 true
319 }
320}
321
322impl Props for () {
324 fn spec(_: &mut TsTypes) -> Vec<PropSpec> {
325 Vec::new()
326 }
327
328 fn initial() -> Self {}
329
330 fn set(&mut self, name: &str, _: Option<AnyValue>) -> Result<bool, PropError> {
331 Err(PropError(format!("unknown prop `{name}`")))
332 }
333
334 fn set_slot(&mut self, _: &str, _: Option<Slot>) -> bool {
335 false
336 }
337
338 fn set_children(&mut self, _: Children) -> bool {
339 false
340 }
341}
342
343pub trait Event: 'static {
350 fn spec(types: &mut TsTypes) -> Vec<EventSpec>;
352
353 fn name(&self) -> &'static str;
355
356 fn data_js<'a>(&self, host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError>;
358}
359
360#[derive(Debug, Clone, Copy, PartialEq, Eq)]
362pub enum NoEvent {}
363
364impl Event for NoEvent {
365 fn spec(_types: &mut TsTypes) -> Vec<EventSpec> {
366 Vec::new()
367 }
368
369 fn name(&self) -> &'static str {
370 match *self {}
371 }
372
373 fn data_js<'a>(&self, _host: &'a dyn JsHost) -> Result<JsOwned<'a>, PropError> {
374 match *self {}
375 }
376}
377
378#[derive(Debug, Clone)]
381pub struct ComponentSpec {
382 pub name: &'static str,
385 pub export: String,
387 pub doc: &'static str,
389 pub props: Vec<PropSpec>,
391 pub events: Vec<EventSpec>,
393 pub methods: Vec<MethodSpec>,
395 pub types: TsTypes,
397 pub lazy_children: bool,
401 pub generic: bool,
404}
405
406pub const HOST_PROPS: &[&str] = &[
410 "class",
411 "classList",
412 "style",
413 "activeStyle",
414 "hoverStyle",
415 "focusStyle",
416 "focusWithinStyle",
417 "focusVisibleStyle",
418 "disabledStyle",
419 "testID",
420 "tooltip",
421 "onLayout",
422 "onFileDragEnter",
423 "onFileDragLeave",
424 "onFileDrop",
425 "onMouseEnter",
426 "onMouseMove",
427 "onMouseLeave",
428 "onMouseUp",
429 "onContextMenu",
430];
431
432type Specs = (
434 fn(&mut TsTypes) -> Vec<PropSpec>,
435 fn(&mut TsTypes) -> Vec<EventSpec>,
436 fn(&mut TsTypes) -> Vec<MethodSpec>,
437);
438
439impl ComponentSpec {
440 pub fn host_props(&self) -> impl Iterator<Item = &'static str> + '_ {
444 HOST_PROPS.iter().copied().filter(|&name| {
445 !self.props.iter().any(|p| p.name == name)
446 && !self.events.iter().any(|e| handler_name(e.name) == name)
447 })
448 }
449
450 pub(crate) fn of<C: Component>() -> Self {
451 Self::build(
452 name_of::<C>(),
453 C::DOC,
454 (C::Props::spec, C::Event::spec, C::METHODS.specs),
455 C::Props::LAZY_CHILDREN,
456 C::Props::GENERIC,
457 )
458 }
459
460 #[inline(never)]
462 fn build(
463 name: &'static str,
464 doc: &'static str,
465 (props, events, methods): Specs,
466 lazy_children: bool,
467 generic: bool,
468 ) -> Self {
469 let mut types = TsTypes::default();
470 let props = props(&mut types);
471 let events = events(&mut types);
472 let methods = methods(&mut types);
473 Self {
474 name,
475 export: export_name(name).to_owned(),
476 doc,
477 props,
478 events,
479 methods,
480 types,
481 lazy_children,
482 generic,
483 }
484 }
485
486 pub fn slots(&self) -> impl Iterator<Item = &'static str> + '_ {
488 self.props
489 .iter()
490 .filter(|p| p.kind == PropKind::Slot)
491 .map(|p| p.name)
492 }
493
494 pub fn renderers(&self) -> impl Iterator<Item = &'static str> + '_ {
496 self.props
497 .iter()
498 .filter(|p| p.kind == PropKind::Renderer)
499 .map(|p| p.name)
500 }
501
502 pub fn takes_children(&self) -> bool {
504 self.props.iter().any(|p| p.kind == PropKind::Children)
505 }
506
507 pub fn items(&self) -> Option<&'static str> {
509 self.props
510 .iter()
511 .find(|p| p.kind == PropKind::Items)
512 .map(|p| p.name)
513 }
514
515 pub(crate) fn holder(&self, name: &str) -> Option<&'static str> {
517 self.props
518 .iter()
519 .find(|p| matches!(p.kind, PropKind::Slot | PropKind::Items) && p.name == name)
520 .map(|p| p.name)
521 }
522}
523
524pub(crate) fn name_of<C: Component>() -> &'static str {
528 std::any::type_name::<C>()
529}
530
531fn export_name(type_name: &str) -> &str {
534 let path = type_name.split('<').next().unwrap_or(type_name);
535 path.rsplit("::").next().unwrap_or(path)
536}
537
538pub(crate) trait AnyInstance {
540 fn set_prop(&mut self, name: &str, value: Option<AnyValue>) -> Result<bool, PropError>;
541 fn set_props(&mut self, props: &dyn Any);
543 fn set_slot(&mut self, name: &'static str, filled: bool);
544 fn set_children(&mut self, present: bool);
545 fn cleanup(&mut self);
547 fn view(&mut self) -> ElNode;
549 fn name(&self) -> &'static str;
551 fn call(&mut self, call: MethodCall) -> Option<JsResult>;
554 fn owner(&self) -> Option<super::Owner>;
556 fn failure_owner(&self) -> super::Owner;
559 fn adopt(&mut self, parent: super::Owner);
563 fn place(&mut self, host: crate::NodeId, parent: super::Owner);
565}
566
567#[derive(Clone)]
571pub struct Root {
572 make: Arc<dyn Fn() -> super::AnyElement + Send + Sync>,
573 tokens: Option<Arc<super::Tokens>>,
574 fonts: Vec<Arc<[u8]>>,
575 appearance: Option<crate::platform::Appearance>,
576 app_id: Option<String>,
577 url_schemes: Vec<String>,
578 capabilities: Option<crate::access::Capabilities>,
579 status_bar: Option<crate::StatusBarSetting>,
580 main_window: Option<crate::desktop::MainWindowOptions>,
581 translations: Option<crate::i18n::Translations>,
582}
583
584impl Root {
585 pub fn new<C: Component>(props: impl Fn() -> C::Props + Send + Sync + 'static) -> Self {
587 Self {
588 make: Arc::new(move || super::IntoElement::into_element(C::element(props()))),
589 tokens: None,
590 fonts: Vec::new(),
591 appearance: None,
592 app_id: None,
593 url_schemes: Vec::new(),
594 capabilities: None,
595 status_bar: None,
596 main_window: None,
597 translations: None,
598 }
599 }
600
601 pub fn translations(mut self, translations: crate::i18n::Translations) -> Self {
604 self.translations = Some(translations);
605 self
606 }
607
608 #[doc(hidden)]
611 pub fn translations_json(self, json: &str) -> Self {
612 match crate::i18n::Translations::from_json(json) {
613 Ok(translations) => self.translations(translations),
614 Err(e) => {
615 log::warn!("locales: {e}");
616 self
617 }
618 }
619 }
620
621 pub fn translations_ref(&self) -> Option<&crate::i18n::Translations> {
623 self.translations.as_ref()
624 }
625
626 pub fn app_id(mut self, id: impl Into<String>) -> Self {
629 self.app_id = Some(id.into());
630 self
631 }
632
633 pub fn app_id_ref(&self) -> Option<&str> {
635 self.app_id.as_deref()
636 }
637
638 pub fn url_schemes(mut self, schemes: impl IntoIterator<Item = impl Into<String>>) -> Self {
642 self.url_schemes = schemes.into_iter().map(Into::into).collect();
643 self
644 }
645
646 pub fn url_schemes_ref(&self) -> &[String] {
648 &self.url_schemes
649 }
650
651 pub fn capabilities(mut self, capabilities: crate::access::Capabilities) -> Self {
657 self.capabilities = Some(capabilities);
658 self
659 }
660
661 #[doc(hidden)]
667 pub fn capabilities_json(self, json: &str) -> Self {
668 let read = serde_json::from_str::<serde_json::Value>(json)
669 .map_err(|e| e.to_string())
670 .and_then(|v| crate::access::Capabilities::from_json_lenient(&v));
671 let capabilities = match read {
672 Ok((capabilities, dropped)) => {
673 for what in dropped {
674 log::warn!("nsh.json: {what}, not granted");
675 }
676 capabilities
677 }
678 Err(e) => {
679 log::warn!("nsh.json: capabilities: {e}; nothing granted");
680 crate::access::Capabilities::default()
681 }
682 };
683 self.capabilities(capabilities)
684 }
685
686 pub fn capabilities_ref(&self) -> Option<&crate::access::Capabilities> {
689 self.capabilities.as_ref()
690 }
691
692 pub fn tokens(mut self, tokens: super::Tokens) -> Self {
695 self.tokens = Some(Arc::new(tokens));
696 self
697 }
698
699 pub fn font(mut self, data: impl Into<Arc<[u8]>>) -> Self {
702 self.fonts.push(data.into());
703 self
704 }
705
706 pub fn appearance(mut self, appearance: crate::platform::Appearance) -> Self {
710 self.appearance = Some(appearance);
711 self
712 }
713
714 pub fn status_bar(mut self, setting: crate::StatusBarSetting) -> Self {
717 self.status_bar = Some(setting);
718 self
719 }
720
721 pub fn main_window(mut self, options: crate::desktop::MainWindowOptions) -> Self {
726 self.main_window = Some(options);
727 self
728 }
729
730 #[doc(hidden)]
734 pub fn main_window_json(self, json: &str) -> Self {
735 let options = serde_json::from_str::<serde_json::Value>(json)
736 .map_err(|e| e.to_string())
737 .and_then(|v| {
738 crate::desktop::MainWindowOptions::from_json(&v).map_err(|e| e.to_string())
739 });
740 match options {
741 Ok(options) => self.main_window(options),
742 Err(e) => {
743 log::warn!("nsh.json: window: {e}");
744 self
745 }
746 }
747 }
748
749 pub fn main_window_ref(&self) -> Option<&crate::desktop::MainWindowOptions> {
751 self.main_window.as_ref()
752 }
753
754 pub fn status_bar_ref(&self) -> Option<crate::StatusBarSetting> {
756 self.status_bar
757 }
758
759 pub fn appearance_ref(&self) -> Option<crate::platform::Appearance> {
762 self.appearance
763 }
764
765 pub fn tokens_ref(&self) -> Option<&super::Tokens> {
767 self.tokens.as_deref()
768 }
769
770 pub fn fonts(&self) -> &[Arc<[u8]>] {
772 &self.fonts
773 }
774
775 pub fn of<C: Component>() -> Self
777 where
778 C::Props: Default,
779 {
780 Self::new::<C>(C::Props::default)
781 }
782
783 pub(crate) fn element(&self) -> super::AnyElement {
785 (self.make)()
786 }
787}
788
789impl fmt::Debug for Root {
790 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
791 f.write_str("Root")
792 }
793}
794
795pub(crate) fn make_instance<C: Component>() -> Box<dyn AnyInstance> {
797 Box::new(super::once::OnceInstance::<C>::new())
798}
799
800#[derive(Clone)]
801struct ComponentType {
802 spec: Arc<ComponentSpec>,
803 make: fn() -> Box<dyn AnyInstance>,
804 id: TypeId,
806}
807
808#[derive(Clone)]
809struct ModuleType {
810 spec: Arc<ModuleSpec>,
811 type_name: &'static str,
813}
814
815#[derive(Clone)]
816struct ClassType {
817 spec: Arc<ClassSpec>,
818 type_name: &'static str,
820}
821
822#[derive(Debug, Clone, Default)]
825#[non_exhaustive]
826pub struct BuiltInScrollbar {
827 pub target: crate::NodeId,
829 pub horizontal: bool,
831 pub theme: Option<Arc<crate::JsonValue>>,
834 pub app_theme: Option<super::AnyValue>,
837}
838
839pub type ScrollbarSource = fn(&BuiltInScrollbar) -> Option<super::AnyElement>;
844
845#[derive(Clone, Default)]
848pub struct Registry {
849 types: Arc<FxHashMap<&'static str, ComponentType>>,
850 modules: Arc<FxHashMap<&'static str, ModuleType>>,
851 classes: Arc<FxHashMap<(Option<&'static str>, &'static str), ClassType>>,
854 reexports: Arc<(Vec<&'static str>, Vec<&'static str>)>,
856 native_values: Arc<Vec<&'static str>>,
859 namespace: Option<&'static str>,
862 ui_set: Option<&'static str>,
864 assets: Arc<Vec<&'static [super::AssetFile]>>,
866 tokens: Option<super::TokenSource>,
868 scrollbars: Option<ScrollbarSource>,
870 submodules: Arc<Vec<Registry>>,
873 setups: Arc<Vec<Setup>>,
875}
876
877type Setup = Arc<dyn Fn() + Send + Sync>;
879
880impl fmt::Debug for Registry {
881 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
882 f.debug_set().entries(self.types.keys()).finish()
883 }
884}
885
886impl Registry {
887 pub fn new() -> Self {
889 Self::default()
890 }
891
892 #[track_caller]
901 pub fn register<C: Component>(&mut self) -> &mut Self {
902 let spec = ComponentSpec::of::<C>();
903 let mut refs = Vec::new();
904 (C::METHODS.refs)(&mut refs);
905 self.register_erased(spec, make_instance::<C>, TypeId::of::<C>(), refs)
906 }
907
908 #[track_caller]
911 #[inline(never)]
912 fn register_erased(
913 &mut self,
914 spec: ComponentSpec,
915 make: fn() -> Box<dyn AnyInstance>,
916 id: TypeId,
917 refs: Vec<&'static ClassDef>,
918 ) -> &mut Self {
919 let types = Arc::make_mut(&mut self.types);
920 if let Some(old) = types.get(spec.name) {
921 let set = self.ui_set.or(self.namespace);
922 panic!("{}", same_name(spec.name, old.id, id, set));
923 }
924 if self.classes.keys().any(|(_, name)| *name == spec.export) {
925 panic!(
926 "component `{}` is exported as `{}` like a class{}: rename one",
927 spec.name,
928 spec.export,
929 of_set(self.ui_set.or(self.namespace)),
930 );
931 }
932 if let Some(other) = types.values().find(|t| t.spec.export == spec.export) {
933 panic!(
934 "components `{}` and `{}` are both exported as `{}`{}: rename one",
935 other.spec.name,
936 spec.name,
937 spec.export,
938 of_set(self.ui_set.or(self.namespace)),
939 );
940 }
941 types.insert(
942 spec.name,
943 ComponentType {
944 spec: Arc::new(spec),
945 make,
946 id,
947 },
948 );
949 self.classes_named(refs)
950 }
951
952 #[track_caller]
960 pub fn module<M: Module>(&mut self) -> &mut Self {
961 let type_name = std::any::type_name::<M>();
962 if self.classes.keys().any(|(_, name)| *name == M::NAME) {
963 panic!(
964 "module `{type_name}` is named `{}` like a class{}: rename one",
965 M::NAME,
966 of_set(self.ui_set.or(self.namespace))
967 );
968 }
969 let modules = Arc::make_mut(&mut self.modules);
970 if let Some(old) = modules.get(M::NAME) {
971 panic!(
972 "{}",
973 same_module(
974 M::NAME,
975 old.type_name,
976 type_name,
977 self.ui_set.or(self.namespace)
978 )
979 );
980 }
981 modules.insert(
982 M::NAME,
983 ModuleType {
984 spec: Arc::new(ModuleSpec::of::<M>()),
985 type_name,
986 },
987 );
988 let mut refs = Vec::new();
989 for f in M::FUNCTIONS {
990 (f.refs)(&mut refs);
991 }
992 self.classes_named(refs)
993 }
994
995 #[track_caller]
1008 pub fn class<C: Class>(&mut self) -> &mut Self {
1009 self.class_def(C::DEF)
1010 }
1011
1012 #[track_caller]
1015 fn classes_named(&mut self, refs: Vec<&'static ClassDef>) -> &mut Self {
1016 for def in refs {
1017 self.class_def(def);
1018 }
1019 self
1020 }
1021
1022 #[track_caller]
1023 fn class_def(&mut self, def: &'static ClassDef) -> &mut Self {
1024 let type_name = (def.type_name)();
1025 let set = self.ui_set.or(self.namespace);
1026 if let Some(old) = self.classes.get(&(set, def.name)) {
1027 if (old.spec.def.type_id)() == (def.type_id)() {
1028 return self;
1029 }
1030 panic!("{}", same_class(def.name, old.type_name, type_name, set));
1031 }
1032 if self.modules.contains_key(def.name)
1033 || self.types.values().any(|t| t.spec.export == def.name)
1034 {
1035 panic!(
1036 "class `{type_name}` is named `{}` like a module or a component{}: rename one",
1037 def.name,
1038 of_set(set)
1039 );
1040 }
1041 Arc::make_mut(&mut self.classes).insert(
1042 (set, def.name),
1043 ClassType {
1044 spec: Arc::new(ClassSpec::of(def)),
1045 type_name,
1046 },
1047 );
1048 let mut refs = Vec::new();
1050 for m in def.members {
1051 (m.refs)(&mut refs);
1052 }
1053 self.classes_named(refs)
1054 }
1055
1056 pub fn reexport(&mut self, values: &[&'static str], types: &[&'static str]) -> &mut Self {
1059 let r = Arc::make_mut(&mut self.reexports);
1060 r.0.extend_from_slice(values);
1061 r.1.extend_from_slice(types);
1062 self
1063 }
1064
1065 #[track_caller]
1076 pub fn merged(sets: &[Registry]) -> Self {
1077 let mut out = Self::default();
1078 for set in sets.iter().flat_map(Registry::sets) {
1079 out.tokens = out.tokens.or(set.tokens);
1080 out.scrollbars = out.scrollbars.or(set.scrollbars);
1081 Arc::make_mut(&mut out.setups).extend(set.setups.iter().cloned());
1082 let types = Arc::make_mut(&mut out.types);
1083 for (name, ty) in set.types.iter() {
1084 if let Some(old) = types.insert(name, ty.clone()) {
1085 panic!("{}, by two UI sets", same_name(name, old.id, ty.id, None));
1086 }
1087 }
1088 }
1089 out
1090 }
1091
1092 pub fn ui_set(specifier: &'static str) -> Self {
1096 Self {
1097 ui_set: Some(specifier),
1098 ..Self::default()
1099 }
1100 }
1101
1102 pub fn specifier(&self) -> Option<&'static str> {
1105 self.ui_set.or(self.namespace)
1106 }
1107
1108 pub fn reexports(&self) -> (&[&'static str], &[&'static str]) {
1111 (&self.reexports.0, &self.reexports.1)
1112 }
1113
1114 #[track_caller]
1126 pub fn submodule(&mut self, set: Registry) -> &mut Self {
1127 let under = match (self.ui_set, set.ui_set) {
1128 (Some(parent), Some(child)) => child
1129 .strip_prefix(parent)
1130 .is_some_and(|rest| rest.len() > 1 && rest.starts_with('/')),
1131 _ => false,
1132 };
1133 assert!(
1134 under,
1135 "a submodule is a UI set under a path of its set's specifier: {:?} under {:?}",
1136 set.ui_set, self.ui_set
1137 );
1138 Arc::make_mut(&mut self.submodules).push(set);
1139 self
1140 }
1141
1142 pub fn sets(&self) -> Vec<&Registry> {
1146 let mut out = vec![self];
1147 for sub in self.submodules.iter() {
1148 out.extend(sub.sets());
1149 }
1150 out
1151 }
1152
1153 pub fn native_values(&mut self, values: &[&'static str]) -> &mut Self {
1156 Arc::make_mut(&mut self.native_values).extend_from_slice(values);
1157 self
1158 }
1159
1160 pub fn assets(&mut self, files: &'static [super::AssetFile]) -> &mut Self {
1165 Arc::make_mut(&mut self.assets).push(files);
1166 self
1167 }
1168
1169 pub fn tokens_from(&mut self, source: super::TokenSource) -> &mut Self {
1172 self.tokens = Some(source);
1173 self
1174 }
1175
1176 pub fn scrollbars_from(&mut self, source: ScrollbarSource) -> &mut Self {
1181 self.scrollbars = Some(source);
1182 self
1183 }
1184
1185 pub(crate) fn scrollbar_source(&self) -> Option<ScrollbarSource> {
1188 self.scrollbars
1189 }
1190
1191 pub fn setup(&mut self, f: impl Fn() + Send + Sync + 'static) -> &mut Self {
1199 Arc::make_mut(&mut self.setups).push(Arc::new(f));
1200 self
1201 }
1202
1203 pub(crate) fn run_setups(&self) {
1206 for setup in self.setups.iter() {
1207 setup();
1208 }
1209 }
1210
1211 pub(crate) fn run_setups_not_in(&self, old: &Registry) {
1214 for setup in self.setups.iter() {
1215 let known = old
1216 .setups
1217 .iter()
1218 .any(|o| std::ptr::addr_eq(Arc::as_ptr(o), Arc::as_ptr(setup)));
1219 if !known {
1220 setup();
1221 }
1222 }
1223 }
1224
1225 pub fn tokens(
1229 &self,
1230 json: Option<&str>,
1231 ) -> Option<Result<(super::Tokens, Vec<String>), String>> {
1232 self.tokens.map(|source| source(json))
1233 }
1234
1235 pub(crate) fn token_source(&self) -> Option<super::TokenSource> {
1237 self.tokens
1238 }
1239
1240 pub fn asset_files(&self) -> impl Iterator<Item = &'static super::AssetFile> + '_ {
1242 self.assets.iter().flat_map(|files| files.iter())
1243 }
1244
1245 pub fn native_value_names(&self) -> &[&'static str] {
1247 &self.native_values
1248 }
1249
1250 pub(crate) fn runtime(namespace: &'static str) -> Self {
1252 Self {
1253 namespace: Some(namespace),
1254 ..Self::default()
1255 }
1256 }
1257
1258 pub fn namespace(&self) -> Option<&'static str> {
1261 self.namespace
1262 }
1263
1264 pub fn class_specs(&self) -> Vec<Arc<ClassSpec>> {
1266 let mut specs: Vec<_> = self.classes.values().map(|c| c.spec.clone()).collect();
1267 specs.sort_by_key(|s| s.name);
1268 specs
1269 }
1270
1271 pub fn module_specs(&self) -> Vec<Arc<ModuleSpec>> {
1273 let mut specs: Vec<_> = self.modules.values().map(|m| m.spec.clone()).collect();
1274 specs.sort_by_key(|s| s.name);
1275 specs
1276 }
1277
1278 pub fn function_members(&self, function: &str) -> Option<Arc<ModuleSpec>> {
1283 let exported = self.modules.values().any(|m| {
1284 m.spec.flat
1285 && m.spec
1286 .functions
1287 .iter()
1288 .any(|f| !f.getter && f.name == function)
1289 });
1290 exported
1291 .then(|| {
1292 self.modules
1293 .values()
1294 .find(|m| !m.spec.flat && m.spec.name == function)
1295 .map(|m| m.spec.clone())
1296 })
1297 .flatten()
1298 }
1299
1300 pub fn specs(&self) -> Vec<Arc<ComponentSpec>> {
1302 let mut specs: Vec<_> = self.types.values().map(|t| t.spec.clone()).collect();
1303 specs.sort_by(|a, b| a.export.cmp(&b.export).then(a.name.cmp(b.name)));
1304 specs
1305 }
1306
1307 pub fn undocumented(&self) -> Vec<String> {
1316 let mut out = Vec::new();
1317 let specs = self.specs();
1318 for c in &specs {
1319 if c.doc.is_empty() {
1320 out.push(c.export.clone());
1321 }
1322 for p in c.props.iter().filter(|p| p.doc.is_empty()) {
1323 out.push(format!("{}.{}", c.export, p.name));
1324 }
1325 for e in c.events.iter().filter(|e| e.doc.is_empty()) {
1326 out.push(format!("{}.{}", c.export, handler_name(e.name)));
1327 }
1328 for m in c.methods.iter().filter(|m| m.doc.is_empty()) {
1329 out.push(format!("{}.{}", c.export, m.name));
1330 }
1331 }
1332 for m in self.module_specs() {
1333 let merged = specs.iter().any(|c| c.export == m.name)
1334 || (!m.flat && self.function_members(m.name).is_some());
1335 if m.doc.is_empty() && !merged && !m.flat {
1336 out.push(m.name.to_owned());
1337 }
1338 for f in m.functions.iter().filter(|f| f.doc.is_empty()) {
1339 out.push(if m.flat {
1340 f.name.to_owned()
1341 } else {
1342 format!("{}.{}", m.name, f.name)
1343 });
1344 }
1345 }
1346 for c in self.class_specs() {
1347 if c.doc.is_empty() {
1348 out.push(c.name.to_owned());
1349 }
1350 let documented_getter = |name: &str| {
1351 c.members
1352 .iter()
1353 .any(|m| m.kind == MemberKind::Getter && m.name == name && !m.doc.is_empty())
1354 };
1355 for m in c.members.iter().filter(|m| m.doc.is_empty()) {
1356 match m.kind {
1357 MemberKind::Constructor => out.push(format!("new {}", c.name)),
1358 MemberKind::Setter if documented_getter(m.name) => {}
1359 _ => out.push(format!("{}.{}", c.name, m.name)),
1360 }
1361 }
1362 }
1363 out
1364 }
1365
1366 pub(crate) fn make(&self, name: &str) -> Option<(Arc<ComponentSpec>, Box<dyn AnyInstance>)> {
1368 self.types.get(name).map(|t| (t.spec.clone(), (t.make)()))
1369 }
1370}
1371
1372fn same_name(name: &str, old: TypeId, new: TypeId, set: Option<&str>) -> String {
1374 if old == new {
1375 format!("component `{name}` is registered twice{}", of_set(set))
1376 } else {
1377 format!(
1378 "two different types named `{name}` are registered{} (two versions of one crate?)",
1379 of_set(set)
1380 )
1381 }
1382}
1383
1384fn same_module(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1386 if old == new {
1387 format!("module `{old}` is registered twice{}", of_set(set))
1388 } else {
1389 format!(
1390 "modules `{old}` and `{new}` are both named `{name}`{}: rename one",
1391 of_set(set)
1392 )
1393 }
1394}
1395
1396fn same_class(name: &str, old: &str, new: &str, set: Option<&str>) -> String {
1398 if old == new {
1399 format!("class `{old}` is registered twice{}", of_set(set))
1400 } else {
1401 format!(
1402 "classes `{old}` and `{new}` are both named `{name}`{}: rename one",
1403 of_set(set)
1404 )
1405 }
1406}
1407
1408fn of_set(set: Option<&str>) -> String {
1410 set.map(|s| format!(" in `{s}`")).unwrap_or_default()
1411}
1412
1413pub fn declarations(registry: &Registry, omit: &[&str]) -> String {
1422 let specs = registry.specs();
1423 let modules = registry.module_specs();
1424 let classes = registry.class_specs();
1425 use std::fmt::Write as _;
1426 let mut out = String::new();
1427 let doc = |out: &mut String, indent: &str, doc: &str| {
1428 if !doc.is_empty() {
1429 let _ = writeln!(out, "{indent}/** {doc} */");
1430 }
1431 };
1432 let mut types = TsTypes::default();
1434 for spec in &specs {
1435 types.merge(&spec.types);
1436 }
1437 for m in &modules {
1438 types.merge(&m.types);
1439 }
1440 for c in &classes {
1441 types.merge(&c.types);
1442 }
1443 for declaration in types.declarations() {
1444 let _ = write!(out, "{declaration}\n\n");
1445 }
1446 let module_of = |name: &str| modules.iter().find(|m| m.name == name);
1447 let signatures = |f: &FunctionSpec| {
1449 let one = |params: &[(&str, String, bool)], returns: &Option<String>| {
1450 let params = params
1451 .iter()
1452 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1453 .collect::<Vec<_>>()
1454 .join(", ");
1455 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1456 let returns = if f.promises() {
1457 format!("Promise<{value}>")
1458 } else {
1459 value
1460 };
1461 (params, returns)
1462 };
1463 if f.overloads.is_empty() {
1464 vec![one(&f.params, &f.returns)]
1465 } else {
1466 f.overloads
1467 .iter()
1468 .map(|(params, returns)| one(params, returns))
1469 .collect()
1470 }
1471 };
1472 let module_object = |out: &mut String, m: &ModuleSpec| {
1474 out.push_str("{\n");
1475 for f in &m.functions {
1476 for (params, returns) in signatures(f) {
1477 doc(out, " ", f.doc);
1478 if f.getter {
1479 let _ = writeln!(out, " readonly {}: {returns};", f.name);
1480 continue;
1481 }
1482 let _ = writeln!(out, " {}({params}): {returns};", f.name);
1483 }
1484 }
1485 for constant in &m.constants {
1486 doc(out, " ", constant.doc);
1487 let _ = writeln!(
1488 out,
1489 " readonly {}: {};",
1490 constant.name,
1491 constant.value.ts_type()
1492 );
1493 }
1494 out.push('}');
1495 };
1496 for spec in &specs {
1497 let (generic, params, extends) = match spec.items() {
1501 Some(_) => ("<T>", "<T>", ", ListItemsProps<T>"),
1502 None if spec.generic => ("<T>", "<T = any>", ""),
1503 None => ("", "", ""),
1504 };
1505 let mut omit: Vec<&str> = HOST_PROPS
1508 .iter()
1509 .copied()
1510 .filter(|&h| !spec.host_props().any(|p| p == h))
1511 .collect();
1512 if !spec.methods.is_empty() {
1513 omit.insert(0, "ref");
1514 }
1515 let host = if omit.is_empty() {
1516 "ComponentHostProps".to_owned()
1517 } else {
1518 let names = omit.iter().map(|n| format!("\"{n}\"")).collect::<Vec<_>>();
1519 format!("Omit<ComponentHostProps, {}>", names.join(" | "))
1520 };
1521 if !spec.methods.is_empty() {
1522 let _ = write!(
1523 out,
1524 "/** The ref of `{0}`: its methods. */\nexport interface {0}Ref {{\n /** The component's host node. */\n readonly node: ViewRef;\n",
1525 spec.export
1526 );
1527 for m in &spec.methods {
1528 doc(&mut out, " ", m.doc);
1529 let params = m
1530 .params
1531 .iter()
1532 .map(|(n, ts, optional)| {
1533 format!("{n}{}: {ts}", if *optional { "?" } else { "" })
1534 })
1535 .collect::<Vec<_>>()
1536 .join(", ");
1537 let returns = match &m.returns {
1538 Some(ts) => format!("Promise<{ts}>"),
1539 None => "void".to_owned(),
1540 };
1541 let _ = writeln!(out, " {}({params}): {returns};", m.name);
1542 }
1543 out.push_str("}\n\n");
1544 }
1545 let _ = writeln!(
1546 out,
1547 "export interface {}Props{params} extends {host}{extends} {{",
1548 spec.export
1549 );
1550 if !spec.methods.is_empty() {
1551 let _ = writeln!(
1552 out,
1553 " ref?: {0}Ref | ((ref: {0}Ref) => void);",
1554 spec.export
1555 );
1556 }
1557 for p in spec.props.iter().filter(|p| p.kind != PropKind::Items) {
1558 doc(&mut out, " ", p.doc);
1559 let optional = if p.optional { "?" } else { "" };
1560 let _ = writeln!(out, " {}{optional}: {};", p.name, p.ts);
1561 }
1562 for e in &spec.events {
1563 doc(&mut out, " ", e.doc);
1564 let handler = handler_name(e.name);
1565 let arg = if e.data == "void" {
1566 String::new()
1567 } else {
1568 format!("{}: {}", e.arg, e.data)
1569 };
1570 let _ = writeln!(out, " {handler}?: ({arg}) => void;");
1571 }
1572 out.push_str("}\n\n");
1573 if omit.contains(&spec.export.as_str()) {
1574 continue;
1575 }
1576 doc(&mut out, "", spec.doc);
1577 let mut with = String::new();
1579 if let Some(m) = module_of(&spec.export) {
1580 with.push_str(" & ");
1581 module_object(&mut with, m);
1582 }
1583 let _ = write!(
1584 out,
1585 "export declare const {}: ({params}(props: {}Props{generic}) => JSX.Element){with};\n\n",
1586 spec.export, spec.export,
1587 );
1588 }
1589 for m in &modules {
1590 if specs.iter().any(|s| s.export == m.name)
1591 || (!m.flat && registry.function_members(m.name).is_some())
1592 {
1593 continue;
1594 }
1595 if m.flat {
1596 for f in m
1597 .functions
1598 .iter()
1599 .filter(|f| !f.getter && !omit.contains(&f.name))
1600 {
1601 for (params, returns) in signatures(f) {
1602 doc(&mut out, "", f.doc);
1603 let _ = writeln!(
1604 out,
1605 "export declare function {}({params}): {returns};",
1606 f.name
1607 );
1608 }
1609 if let Some(members) = registry.function_members(f.name) {
1611 let _ = writeln!(out, "export declare namespace {} {{", f.name);
1612 for member in &members.functions {
1613 for (params, returns) in signatures(member) {
1614 doc(&mut out, " ", member.doc);
1615 let _ = if member.getter {
1616 writeln!(out, " const {}: {returns};", member.name)
1617 } else {
1618 writeln!(out, " function {}({params}): {returns};", member.name)
1619 };
1620 }
1621 }
1622 for constant in &members.constants {
1623 doc(&mut out, " ", constant.doc);
1624 let _ = writeln!(
1625 out,
1626 " const {}: {};",
1627 constant.name,
1628 constant.value.ts_type()
1629 );
1630 }
1631 out.push_str("}\n");
1632 }
1633 out.push('\n');
1634 }
1635 for constant in &m.constants {
1636 if !omit.contains(&constant.name) {
1637 doc(&mut out, "", constant.doc);
1638 let _ = writeln!(
1639 out,
1640 "export declare const {}: {};\n",
1641 constant.name,
1642 constant.value.ts_type()
1643 );
1644 }
1645 }
1646 if m.default && !omit.contains(&"default") {
1647 let _ = write!(out, "declare const defaultExport: ");
1648 module_object(&mut out, m);
1649 for native in registry.native_value_names() {
1651 let _ = write!(out, " & {{ {native}: typeof {native} }}");
1652 }
1653 out.push_str(";\nexport default defaultExport;\n\n");
1654 }
1655 continue;
1656 }
1657 doc(&mut out, "", m.doc);
1658 let _ = write!(out, "export interface {}Module ", m.name);
1659 module_object(&mut out, m);
1660 out.push_str("\n\n");
1661 if !omit.contains(&m.name) {
1662 doc(&mut out, "", m.doc);
1663 let _ = write!(out, "export declare const {0}: {0}Module;\n\n", m.name);
1664 }
1665 if m.default && !omit.contains(&"default") {
1666 let _ = write!(
1667 out,
1668 "declare const defaultExport: {}Module;\nexport default defaultExport;\n\n",
1669 m.name
1670 );
1671 }
1672 }
1673 for c in classes.iter().filter(|c| !omit.contains(&c.name)) {
1674 class_declaration(&mut out, c);
1675 }
1676 out
1677}
1678
1679fn class_declaration(out: &mut String, c: &ClassSpec) {
1681 use std::fmt::Write as _;
1682 let doc = |out: &mut String, indent: &str, doc: &str| {
1683 if !doc.is_empty() {
1684 let _ = writeln!(out, "{indent}/** {doc} */");
1685 }
1686 };
1687 doc(out, "", c.doc);
1688 if c.def.interface {
1689 let _ = writeln!(out, "export interface {} {{", c.name);
1691 for m in &c.members {
1692 let params = m
1693 .params
1694 .iter()
1695 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1696 .collect::<Vec<_>>()
1697 .join(", ");
1698 let value = m.returns.clone().unwrap_or_else(|| "void".to_owned());
1699 let returns = if m.is_async {
1700 format!("Promise<{value}>")
1701 } else {
1702 value
1703 };
1704 doc(out, " ", m.doc);
1705 let has_setter = |name| {
1706 c.members
1707 .iter()
1708 .any(|s| s.kind == MemberKind::Setter && s.name == name)
1709 };
1710 let _ = match m.kind {
1711 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1712 MemberKind::Getter if has_setter(m.name) => {
1713 writeln!(out, " {}: {returns};", m.name)
1714 }
1715 MemberKind::Getter => writeln!(out, " readonly {}: {returns};", m.name),
1716 _ => Ok(()),
1719 };
1720 }
1721 out.push_str("}\n\n");
1722 return;
1723 }
1724 let _ = writeln!(out, "export declare class {} {{", c.name);
1725 if !c.members.iter().any(|m| m.kind == MemberKind::Constructor) {
1726 out.push_str(" /** Made by the class's members only. */\n private constructor();\n");
1727 }
1728 let one = |m: &super::MemberSpec, params: &[(&str, String, bool)], returns: &Option<String>| {
1729 let params = params
1730 .iter()
1731 .map(|(n, ts, optional)| format!("{n}{}: {ts}", if *optional { "?" } else { "" }))
1732 .collect::<Vec<_>>()
1733 .join(", ");
1734 let value = returns.clone().unwrap_or_else(|| "void".to_owned());
1735 let returns = if m.is_async {
1736 format!("Promise<{value}>")
1737 } else {
1738 value
1739 };
1740 (params, returns)
1741 };
1742 for m in &c.members {
1743 if !m.overloads.is_empty() {
1744 for (params, returns) in &m.overloads {
1745 doc(out, " ", m.doc);
1746 let (params, returns) = one(m, params, returns);
1747 let _ = match m.kind {
1748 MemberKind::Static => {
1749 writeln!(out, " static {}({params}): {returns};", m.name)
1750 }
1751 _ => writeln!(out, " {}({params}): {returns};", m.name),
1752 };
1753 }
1754 continue;
1755 }
1756 doc(out, " ", m.doc);
1757 let (params, returns) = one(m, &m.params, &m.returns);
1758 let _ = match m.kind {
1759 MemberKind::Constructor => writeln!(out, " constructor({params});"),
1760 MemberKind::Method => writeln!(out, " {}({params}): {returns};", m.name),
1761 MemberKind::Getter => writeln!(out, " get {}(): {returns};", m.name),
1762 MemberKind::Setter => writeln!(out, " set {}({params});", m.name),
1763 MemberKind::Static => writeln!(out, " static {}({params}): {returns};", m.name),
1764 };
1765 }
1766 out.push_str(
1767 " /** 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",
1768 );
1769}
1770
1771fn handler_name(event: &str) -> String {
1773 let mut chars = event.chars();
1774 match chars.next() {
1775 Some(first) => format!("on{}{}", first.to_ascii_uppercase(), chars.as_str()),
1776 None => "on".to_owned(),
1777 }
1778}
1779
1780#[cfg(test)]
1781mod tests {
1782 use super::*;
1783 use crate::prelude::*;
1784
1785 #[derive(Default)]
1786 struct Stepper;
1787
1788 #[derive(Clone, PartialEq, Props)]
1790 struct StepperProps {
1791 value: f64,
1793 #[prop(default)]
1794 size: StepperSize,
1795 max_value: Option<f64>,
1796 label: Option<Slot>,
1798 children: Children,
1799 }
1800
1801 #[derive(Clone, Copy, PartialEq, Default, PropEnum)]
1802 enum StepperSize {
1803 #[default]
1804 Regular,
1805 ExtraLarge,
1806 }
1807
1808 #[derive(Event)]
1809 enum StepperEvent {
1810 Change {
1812 new_value: f64,
1813 },
1814 #[args(limit)]
1815 Limit(u32),
1816 Reset,
1817 }
1818
1819 struct StepperApi;
1820
1821 #[methods]
1822 impl StepperApi {
1823 pub(crate) fn jump_to(&self, value: f64) {
1825 let _ = value;
1826 }
1827
1828 pub(crate) fn value(&self) -> f64 {
1829 0.0
1830 }
1831
1832 #[allow(dead_code)]
1834 fn clamp(&self, value: f64) -> f64 {
1835 value
1836 }
1837 }
1838
1839 impl Component for Stepper {
1840 type Props = StepperProps;
1841 type Event = StepperEvent;
1842 const METHODS: Methods = Methods::of::<StepperApi>();
1843 const DOC: &'static str = "Picks a number.";
1844
1845 fn view(_: StepperProps, _: super::super::Scope<StepperEvent>) -> impl IntoElement {
1846 view()
1847 }
1848 }
1849
1850 #[test]
1851 fn the_declarations_come_from_the_types() {
1852 let mut registry = Registry::new();
1853 registry.register::<Stepper>();
1854 let ts = declarations(®istry, &[]);
1855 for line in [
1856 " /** The value. */\n value: number;",
1857 "export type StepperSize = \"regular\" | \"extraLarge\";",
1858 " size?: StepperSize;",
1859 " maxValue?: number | null;",
1860 " /** Above the control. */\n label?: JSX.Element;",
1861 " children?: JSX.Element;",
1862 " /** The value changed. */\n onChange?: (event: { newValue: number }) => void;",
1863 " onLimit?: (event: { limit: number }) => void;",
1864 " onReset?: () => void;",
1865 "/** Picks a number. */",
1866 "export interface StepperRef {",
1867 " /** Jumps to `value`. */\n jumpTo(value: number): void;",
1868 " value(): Promise<number>;",
1869 "export interface StepperProps extends Omit<ComponentHostProps, \"ref\"> {\n ref?: StepperRef | ((ref: StepperRef) => void);",
1870 "export declare const Stepper: ((props: StepperProps) => JSX.Element);",
1871 ] {
1872 assert!(ts.contains(line), "missing {line:?} in\n{ts}");
1873 }
1874 assert!(!ts.contains("clamp"), "a helper is not a method:\n{ts}");
1875 assert_eq!(StepperApi::METHODS.len(), 2);
1876 let mut props = StepperProps::initial();
1877 let size = |json| {
1878 let specs = StepperProps::spec(&mut TsTypes::default());
1879 let decode = specs
1880 .iter()
1881 .find(|p| p.name == "size")
1882 .unwrap()
1883 .decode
1884 .unwrap();
1885 super::super::json_host::decode(decode, json)
1886 };
1887 assert!(
1888 props
1889 .set("size", Some(size(serde_json::json!("extraLarge")).unwrap()))
1890 .unwrap()
1891 );
1892 assert!(props.size == StepperSize::ExtraLarge);
1893 assert!(size(serde_json::json!("huge")).is_err());
1897 assert!(props.set("size", Some(AnyValue::new(1.0f64))).is_err());
1898 assert!(props.set("size", None).unwrap());
1899 assert!(props.size == StepperSize::Regular);
1900 let data = |e: &StepperEvent| super::super::json_host::event_data(e);
1901 assert_eq!(
1902 data(&StepperEvent::Change { new_value: 2.5 }),
1903 Some(serde_json::json!({ "newValue": 2.5 }))
1904 );
1905 assert_eq!(
1906 data(&StepperEvent::Limit(3)),
1907 Some(serde_json::json!({ "limit": 3 }))
1908 );
1909 assert_eq!(data(&StepperEvent::Reset), None);
1910 assert_eq!(StepperEvent::Reset.name(), "reset");
1911 }
1912
1913 #[test]
1914 fn exports_without_docs_are_listed() {
1915 let mut registry = Registry::new();
1916 registry.register::<Stepper>();
1917 assert_eq!(
1920 registry.undocumented(),
1921 [
1922 "Stepper.size",
1923 "Stepper.maxValue",
1924 "Stepper.children",
1925 "Stepper.onLimit",
1926 "Stepper.onReset",
1927 "Stepper.value",
1928 ]
1929 );
1930 let mut r = Registry::ui_set("test/maker");
1931 r.module::<Maker>();
1932 assert_eq!(r.undocumented(), ["Maker.make", "new Lonely"]);
1933 }
1934
1935 #[crate::element::class]
1937 struct Lonely;
1938
1939 #[crate::element::class]
1940 impl Lonely {
1941 pub(crate) fn new() -> Self {
1942 Lonely
1943 }
1944 }
1945
1946 #[crate::element::module]
1948 struct Maker;
1949
1950 #[crate::element::module]
1951 impl Maker {
1952 pub(crate) fn make() -> Instance<Lonely> {
1953 Instance::new(Lonely)
1954 }
1955 }
1956
1957 #[test]
1958 fn the_classes_a_signature_names_are_registered_with_it() {
1959 let mut r = Registry::ui_set("test/maker");
1960 r.module::<Maker>();
1961 let names: Vec<_> = r.class_specs().iter().map(|c| c.name).collect();
1964 assert_eq!(names, ["Lonely"]);
1965 let ts = declarations(&r, &[]);
1966 assert!(ts.contains("export declare class Lonely"), "{ts}");
1967 assert!(ts.contains("make(): Lonely;"), "{ts}");
1968 r.class::<Lonely>();
1970 assert_eq!(r.class_specs().len(), 1);
1971 let _ = Registry::merged(&[r]);
1972 }
1973
1974 #[crate::element::module]
1976 struct Checks;
1977
1978 #[crate::element::module(flat)]
1979 impl Checks {
1980 pub(crate) fn check(name: String) {
1982 let _ = name;
1983 }
1984 }
1985
1986 #[crate::element::module]
1988 struct CheckVariants;
1989
1990 #[crate::element::module(name = "check")]
1991 impl CheckVariants {
1992 pub(crate) const COUNT: u32 = 2;
1994
1995 pub(crate) fn skip(name: String) {
1997 let _ = name;
1998 }
1999
2000 pub(crate) fn todo(name: String) {
2001 let _ = name;
2002 }
2003 }
2004
2005 #[crate::element::module]
2007 struct Loose;
2008
2009 #[crate::element::module(name = "loose")]
2010 impl Loose {
2011 pub(crate) fn nothing() {}
2013 }
2014
2015 #[test]
2016 fn a_module_named_like_a_function_puts_its_functions_on_it() {
2017 let mut r = Registry::ui_set("test/checks");
2018 r.module::<Checks>()
2019 .module::<CheckVariants>()
2020 .module::<Loose>();
2021 assert_eq!(r.function_members("check").unwrap().name, "check");
2022 assert!(r.function_members("loose").is_none());
2023 let ts = declarations(&r, &[]);
2024 assert!(
2025 ts.contains(
2026 "/** Declares a check. */\n\
2027 export declare function check(name: string): void;\n\
2028 export declare namespace check {\n \
2029 /** Declares a check that does not run. */\n \
2030 function skip(name: string): void;\n \
2031 function todo(name: string): void;\n \
2032 /** How many variants there are. */\n \
2033 const COUNT: number;\n}\n"
2034 ),
2035 "{ts}"
2036 );
2037 assert!(
2038 !ts.contains("CheckVariants") && !ts.contains("checkModule"),
2039 "{ts}"
2040 );
2041 assert!(
2042 ts.contains("export declare const loose: looseModule;"),
2043 "{ts}"
2044 );
2045 assert_eq!(r.undocumented(), ["check.todo"]);
2047 let described = super::super::description::SetDescription::of(&r).unwrap();
2048 let exports: Vec<_> = described
2049 .exports
2050 .iter()
2051 .map(|e| (e.name.as_str(), e.kind))
2052 .collect();
2053 assert_eq!(
2054 exports,
2055 [
2056 ("check", super::super::description::ExportKind::Function),
2057 ("loose", super::super::description::ExportKind::Module)
2058 ]
2059 );
2060 }
2061
2062 mod clash {
2063 #[crate::element::class]
2065 pub(super) struct Lonely;
2066
2067 #[crate::element::class]
2068 impl Lonely {
2069 pub(super) fn new() -> Self {
2070 Lonely
2071 }
2072 }
2073 }
2074
2075 #[test]
2076 fn a_clash_through_a_signature_names_both_types() {
2077 let mut r = Registry::ui_set("test/maker");
2078 r.class::<clash::Lonely>();
2079 let failed = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2081 r.module::<Maker>();
2082 }))
2083 .unwrap_err();
2084 let message = failed.downcast_ref::<String>().unwrap();
2085 assert!(
2086 message.contains("`nsh_core::element::component::tests::clash::Lonely`")
2087 && message.contains("`nsh_core::element::component::tests::Lonely`"),
2088 "{message}"
2089 );
2090 }
2091
2092 #[test]
2093 fn components_are_named_after_their_types() {
2094 let mut registry = Registry::ui_set("test/ui");
2095 registry.register::<Stepper>();
2096 let specs = registry.specs();
2097 assert_eq!(
2098 specs[0].name,
2099 "nsh_core::element::component::tests::Stepper"
2100 );
2101 assert_eq!(specs[0].export, "Stepper");
2102 assert_eq!(export_name("app::picker::Picker<app::Fruit>"), "Picker");
2103 assert_eq!(export_name("Bare"), "Bare");
2104 }
2105
2106 mod other {
2107 use crate::prelude::*;
2108
2109 #[derive(Default)]
2111 pub(super) struct Stepper;
2112
2113 impl Component for Stepper {
2114 type Props = ();
2115 type Event = NoEvent;
2116
2117 fn view(_: (), _: crate::element::Scope<NoEvent>) -> impl IntoElement {
2118 view()
2119 }
2120 }
2121 }
2122
2123 #[test]
2124 #[should_panic(
2125 expected = "components `nsh_core::element::component::tests::Stepper` and `nsh_core::element::component::tests::other::Stepper` are both exported as `Stepper` in `test/ui`"
2126 )]
2127 fn two_components_of_one_set_cannot_share_an_export() {
2128 Registry::ui_set("test/ui")
2129 .register::<Stepper>()
2130 .register::<other::Stepper>();
2131 }
2132
2133 #[test]
2134 #[should_panic(
2135 expected = "component `nsh_core::element::component::tests::Stepper` is registered twice"
2136 )]
2137 fn a_component_is_registered_once() {
2138 Registry::new().register::<Stepper>().register::<Stepper>();
2139 }
2140
2141 #[test]
2144 fn a_sets_submodules_come_with_it() {
2145 let mut sub = Registry::ui_set("test/set/sub");
2146 sub.register::<Stepper>();
2147 let mut set = Registry::ui_set("test/set");
2148 set.submodule(sub);
2149 let specifiers: Vec<_> = set.sets().iter().map(|s| s.specifier()).collect();
2150 assert_eq!(specifiers, [Some("test/set"), Some("test/set/sub")]);
2151 assert_eq!(Registry::merged(&[set]).specs().len(), 1);
2152 let elsewhere = std::panic::catch_unwind(|| {
2154 Registry::ui_set("test/set").submodule(Registry::ui_set("test/settings"));
2155 });
2156 assert!(elsewhere.is_err());
2157 }
2158
2159 #[test]
2160 fn sets_may_share_exports_but_not_components() {
2161 let mut a = Registry::ui_set("test/a");
2162 a.register::<Stepper>();
2163 let mut b = Registry::ui_set("test/b");
2164 b.register::<other::Stepper>();
2165 let merged = Registry::merged(&[a.clone(), b]);
2166 assert_eq!(merged.specs().len(), 2);
2167 let twice = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
2168 Registry::merged(&[a.clone(), a])
2169 }));
2170 let message = *twice.unwrap_err().downcast::<String>().unwrap();
2171 assert_eq!(
2172 message,
2173 "component `nsh_core::element::component::tests::Stepper` is registered twice, by two UI sets"
2174 );
2175 }
2176}
2177
2178#[cfg(test)]
2179mod root_tests {
2180 use super::Root;
2181 use crate::{access::Capabilities, prelude::*};
2182
2183 #[component]
2184 fn Empty() -> impl IntoElement {
2185 view()
2186 }
2187
2188 #[test]
2189 fn a_root_reads_its_declared_capabilities_as_packages_are_read() {
2190 assert_eq!(Root::of::<Empty>().capabilities_ref(), None);
2191 let root = Root::of::<Empty>().capabilities_json(r#"{"clipboard":true,"bluetooth":true}"#);
2193 let expected = Capabilities {
2194 clipboard: true,
2195 ..Capabilities::default()
2196 };
2197 assert_eq!(root.capabilities_ref(), Some(&expected));
2198 let root = Root::of::<Empty>().capabilities_json("not json");
2200 assert_eq!(root.capabilities_ref(), Some(&Capabilities::default()));
2201 }
2202}